Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Separate image edits and pending generations

Bitti2357967b46f5
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index 686644f..fe756f7 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -19,7 +19,8 @@ This alpha update adds Prompt video scenes, agent image drafts, Sol attention an
- Generation effects reuse VAE fingerprints between jobs, removing repeated full-file calibration checks for unchanged VAEs. Changed or replaced VAEs are verified again; saved calibrations remain reusable after restarting.
- Renamed image roots on the still image creation page now retain their names when switching images and reopening projects.
-- Image edits keep the original as the parent with its saved prompt and settings. Child results open as normal images ready for further edits; selecting images does not create editing copies.
+- Image edits keep their prompts and settings separate from the original. Child results open as normal images ready for further edits; selecting images does not create editing copies.
+- Image generation immediately selects a separate empty entry showing Queued or Generating. Progress stays on that entry, and the result replaces it when ready.
- Whole-image edits disable feathering at the native generation boundary, including requests with missing or previously saved feather settings.
- Imported still images now have steps, seed and resolution controls. Resolution defaults to the source dimensions rounded down to multiples of 32, with additional sizes matching the source aspect ratio.
- Fixed CUDA transformer-loading memory failures with bounded upload buffers, more accurate memory budgeting and automatic retries with more CPU offloading, while preserving precision and output settings.
diff --git a/src/components/ImageProject.integration.test.tsx b/src/components/ImageProject.integration.test.tsx
index f14e801..7b9b8d8 100644
--- a/src/components/ImageProject.integration.test.tsx
+++ b/src/components/ImageProject.integration.test.tsx
@@ -119,28 +119,49 @@ it.each([false, true])("scopes generation controls to each image and queues othe
render(<ProjectWorkspace project={project} workQueue={queue} onBack={vi.fn()} onSave={vi.fn()} />);
const panel = within(screen.getByRole("region", { name: "Image panel" }));
const toolbar = within(screen.getByRole("toolbar", { name: "Image tools" }));
- fireEvent.click(toolbar.getByRole("button", { name: "Generate" }));
+ const inspector = within(screen.getByRole("complementary", { name: "Image node inspector" }));
+ const selectOriginal = (name: string) => {
+ const back = screen.queryByRole("button", { name: "Back to all images" });
+ if (back) fireEvent.click(back);
+ fireEvent.click(screen.getByRole("button", { name: new RegExp(`^View ${name}(,|$)`) }));
+ };
+ const selectPending = (id: string) => fireEvent.click(document.querySelector<HTMLButtonElement>(`[data-image-asset="${id}"]`)!);
+ fireEvent.click(inspector.getByRole("button", { name: "Generate" }));
await waitFor(() => expect(enqueue).toHaveBeenCalledOnce());
- expect(toolbar.getByRole("button", { name: "Cancel" })).toBeEnabled();
- fireEvent.click(screen.getByRole("button", { name: "View Second" }));
- expect(toolbar.queryByRole("button", { name: "Cancel" })).not.toBeInTheDocument();
+ const first = queue.getSnapshot()[0];
+ expect(first.imageDraftId).toBe(imageDraft ? "First" : first.id);
+ expect(document.querySelector(`[data-image-asset="${first.imageDraftId}"]`)).toHaveTextContent("Generating");
+ expect(document.querySelector(".image-frame img")).toBeNull();
+ expect(inspector.getByRole("button", { name: "Cancel" })).toBeEnabled();
+ selectOriginal("Second");
+ expect(inspector.queryByRole("button", { name: "Cancel" })).not.toBeInTheDocument();
expect(toolbar.getByRole("combobox", { name: "Generator" })).toBeEnabled();
- fireEvent.click(toolbar.getByRole("button", { name: "Generate" }));
- expect(queue.getSnapshot().map((item) => [item.imageAssetId, item.status])).toEqual([["First", "generating"], ["Second", "queued"]]);
+ fireEvent.click(inspector.getByRole("button", { name: "Generate" }));
+ const second = queue.getSnapshot()[1];
+ expect(second.imageDraftId).toBe(imageDraft ? "Second" : second.id);
+ expect(queue.getSnapshot().map((item) => item.status)).toEqual(["generating", "queued"]);
+ expect(document.querySelector(`[data-image-asset="${second.imageDraftId}"]`)).toHaveTextContent("Queued");
expect(enqueue).toHaveBeenCalledOnce();
- fireEvent.click(screen.getByRole("button", { name: "View Third" }));
- expect(toolbar.getByRole("button", { name: "Generate" })).toBeEnabled();
+ selectOriginal("Third");
+ expect(inspector.getByRole("button", { name: "Generate" })).toBeEnabled();
expect(panel.queryByRole("progressbar")).not.toBeInTheDocument();
- fireEvent.contextMenu(screen.getByRole("button", { name: "View First" }));
+ selectOriginal("First");
+ if (!imageDraft) {
+ expect(inspector.getByRole("button", { name: "Generate" })).toBeEnabled();
+ expect(panel.queryByRole("progressbar")).not.toBeInTheDocument();
+ expect(queue.project(project).getSnapshot().config.assets.find((asset) => asset.id === "First")).toEqual(project.config.assets[0]);
+ }
+ selectPending(first.imageDraftId!);
+ fireEvent.contextMenu(document.querySelector(`[data-image-asset="${first.imageDraftId}"]`)!);
expect(screen.getByRole("menuitem", { name: "Remove" })).toBeDisabled();
fireEvent.keyDown(screen.getByRole("menu", { name: "Generated image actions" }), { key: "Escape" });
- fireEvent.click(screen.getByRole("button", { name: "View First" }));
- fireEvent.click(toolbar.getByRole("button", { name: "Cancel" }));
- await waitFor(() => expect(cancel).toHaveBeenCalledWith(queue.getSnapshot()[0].id));
- fireEvent.click(screen.getByRole("button", { name: "View Second" }));
- fireEvent.click(toolbar.getByRole("button", { name: "Cancel" }));
+ fireEvent.click(inspector.getByRole("button", { name: "Cancel" }));
+ await waitFor(() => expect(cancel).toHaveBeenCalledWith(first.id));
+ selectOriginal("Second");
+ selectPending(second.imageDraftId!);
+ fireEvent.click(inspector.getByRole("button", { name: "Cancel" }));
expect(queue.getSnapshot()[1].status).toBe("cancelled");
- expect(toolbar.getByRole("button", { name: "Generate" })).toBeEnabled();
+ expect(inspector.getByRole("button", { name: "Generate" })).toBeEnabled();
});
it("exports the selected image from the Export tab and handles cancellation and errors", async () => {
diff --git a/src/components/workspace/ImageBar.tsx b/src/components/workspace/ImageBar.tsx
index 15c21dc..89f01df 100644
--- a/src/components/workspace/ImageBar.tsx
+++ b/src/components/workspace/ImageBar.tsx
@@ -1,6 +1,7 @@
import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";
import { imageFamily, imageFamilyRoot } from "../../lib/imageHistory";
import type { ProjectAsset } from "../../lib/project";
+import { isWorkActive, type WorkItem } from "../../lib/workQueue";
import { ChevronLeft16, Edit11, Image24 } from "../ui/icons";
import { ReferenceImage } from "./ReferenceImage";
import "../../styles/image-editor.css";
@@ -20,9 +21,10 @@ export const ImageBar = forwardRef<HTMLDivElement | null, {
images: ProjectAsset[];
selectedId: string | null | undefined;
folderPath: string;
+ workItems?: readonly WorkItem[];
onSelect: (id: string) => void;
onMenu?: (id: string | null, x: number, y: number, inFamily: boolean) => void;
-}>(function ImageBar({ images, selectedId, folderPath, onSelect, onMenu }, ref) {
+}>(function ImageBar({ images, selectedId, folderPath, workItems = [], onSelect, onMenu }, ref) {
const bar = useRef<HTMLDivElement>(null);
useImperativeHandle(ref, () => bar.current as HTMLDivElement);
@@ -37,6 +39,7 @@ export const ImageBar = forwardRef<HTMLDivElement | null, {
const shown = inFamily ? family : primaries;
const pressed = inFamily ? selectedId : root;
const childCount = (id: string) => images.filter((asset) => asset.id !== id && imageFamilyRoot(images, asset.id) === id).length;
+ const pending = new Map(workItems.filter(isWorkActive).map((work) => [work.imageDraftId ?? work.imageAssetId ?? work.id, work.status === "queued" ? "Queued" : "Generating"]));
const previousCount = useRef(shown.length);
useLayoutEffect(() => {
@@ -113,7 +116,7 @@ export const ImageBar = forwardRef<HTMLDivElement | null, {
{inFamily && <button type="button" className="image-results__back" aria-label="Back to all images" data-tooltip="All images"
onClick={() => { setShowAll(true); bar.current?.focus(); }}><ChevronLeft16 aria-hidden="true" /></button>}
{shown.map((asset) => <button key={asset.id} type="button" data-image-asset={asset.id} data-tooltip={asset.name}
- aria-label={`View ${asset.name}${!inFamily && childCount(asset.id) ? `, ${childCount(asset.id) + 1} versions` : ""}`} aria-pressed={asset.id === pressed}
+ aria-label={`View ${asset.name}${!inFamily && childCount(asset.id) ? `, ${childCount(asset.id) + 1} versions` : ""}`} aria-pressed={asset.id === pressed} aria-busy={pending.has(asset.id)}
onContextMenu={onMenu && ((event) => { event.preventDefault(); event.stopPropagation(); onMenu(asset.id, event.clientX, event.clientY, inFamily); })}
onKeyDown={onMenu && ((event) => {
if (!menuKey(event)) return;
@@ -122,9 +125,9 @@ export const ImageBar = forwardRef<HTMLDivElement | null, {
onMenu(asset.id, bounds.left, bounds.bottom, inFamily);
})}
onClick={() => { setShowAll(false); onSelect(asset.id); }}>
- {asset.relativePath || asset.sourcePath ? <ReferenceImage folderPath={folderPath} relativePath={asset.relativePath} sourcePath={asset.sourcePath} alt={asset.name} /> : <Image24 aria-hidden="true" />}
+ {!pending.has(asset.id) && (asset.relativePath || asset.sourcePath) ? <ReferenceImage folderPath={folderPath} relativePath={asset.relativePath} sourcePath={asset.sourcePath} alt={asset.name} /> : <Image24 aria-hidden="true" />}
{!inFamily && childCount(asset.id) > 0 && <span className="image-family-badge" aria-hidden="true">{childCount(asset.id) + 1}</span>}
- {asset.imageDraft && <span className="image-draft-badge"><Edit11 aria-hidden="true" />{asset.imageGeneration?.scene.rootType === "image" ? "Editing" : "Draft"}</span>}
+ {pending.has(asset.id) ? <span className="image-draft-badge">{pending.get(asset.id)}</span> : asset.imageDraft && <span className="image-draft-badge"><Edit11 aria-hidden="true" />{asset.imageGeneration?.scene.rootType === "image" ? "Editing" : "Draft"}</span>}
</button>)}
</div>;
});
diff --git a/src/components/workspace/ImageEditor.test.tsx b/src/components/workspace/ImageEditor.test.tsx
index 5a3c4ac..f3d8a50 100644
--- a/src/components/workspace/ImageEditor.test.tsx
+++ b/src/components/workspace/ImageEditor.test.tsx
@@ -7,7 +7,7 @@ import { afterEach, expect, it, vi } from "vitest";
import { ImageEditor } from "./ImageEditor";
import { choose, comboValue } from "./comboTestUtils";
import { imageGenerationSnapshotSchema, parseProjectConfig, referenceImages, sceneFrameInputs, type ProjectConfig } from "../../lib/project";
-import { completeImageDraft, createTemplateImageDraft, imageGenerationSnapshot, restoreGeneratedImage } from "../../lib/imageHistory";
+import { completeImageDraft, createTemplateImageDraft, imageGenerationSnapshot, restoreGeneratedImage, saveImageDraft } from "../../lib/imageHistory";
import { createGeneratorTemplate, mossImageTemplate, defaultGeneratorTemplate, saveGeneratorTemplateSettings } from "../../lib/settings";
import { createImageEditScene, createImageScene, imageScenePrompt } from "../../lib/imageScene";
import type { WorkItem } from "../../lib/workQueue";
@@ -30,6 +30,42 @@ function setup(initial = parseProjectConfig(fixture), workItems: WorkItem[] = []
return () => latest;
}
+it.each(["queued", "generating"] as const)("shows a separate empty %s entry without progress on the original", async (status) => {
+ vi.spyOn(persistence, "readMediaFileUrl").mockImplementation(async (_folder, location) => `blob:${location.relativePath}`);
+ vi.stubGlobal("URL", class extends URL { static revokeObjectURL = vi.fn(); });
+ const config = parseProjectConfig(fixture);
+ config.imageScene = createImageScene("A forest");
+ const original = { id: "original", kind: "image" as const, name: "Original", relativePath: "media/original.png", width: 512, height: 512,
+ mimeType: "image/png", createdAt: config.createdAt, imageGeneration: imageGenerationSnapshot(config, "Compiled forest", "default") };
+ config.assets = [original];
+ // Also cover hiding the source thumbnail while an image edit generates.
+ if (status === "generating") {
+ config.imageScene = createImageEditScene(original);
+ config.imageScene.nodes[0].description = "Add snow";
+ }
+ config.imageScene.outputAssetId = original.id;
+ const pending = saveImageDraft(config, "default", true, "pending");
+ const current = setup(pending, [{ id: "job", imageAssetId: original.id, imageDraftId: "pending", status, progress: 0.25, detail: "Working" } as WorkItem]);
+ const draftName = pending.assets[1].name;
+ const draft = screen.getByRole("button", { name: `View ${draftName}` });
+ expect(draft).toHaveAttribute("aria-pressed", "true");
+ expect(draft).toHaveAttribute("aria-busy", "true");
+ expect(draft).toHaveTextContent(status === "queued" ? "Queued" : "Generating");
+ expect(within(draft).queryByRole("img")).not.toBeInTheDocument();
+ expect(document.querySelector(".image-frame img")).toBeNull();
+ expect(document.querySelector(".image-frame")).toHaveTextContent(status === "queued" ? "Queued" : "Generating");
+ const source = screen.getByRole("button", { name: "View Original" });
+ expect(source).toHaveAttribute("aria-busy", "false");
+ fireEvent.click(source);
+ expect(screen.queryByRole("progressbar", { name: "Image generation progress" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Cancel" })).not.toBeInTheDocument();
+ expect(current().imageScene!.nodes[0].description).toBe("A forest");
+ await waitFor(() => expect(document.querySelector(".image-frame img")).toHaveAttribute("src", "blob:media/original.png"));
+ fireEvent.click(screen.getByRole("button", { name: `View ${draftName}` }));
+ expect(document.querySelector(".image-frame img")).toBeNull();
+ expect(current().assets[0]).toEqual(original);
+});
+
it("offers MOSS for new images and disables editing and reference templates", () => {
vi.spyOn(persistence, "isTauri").mockReturnValue(true);
const moss = { ...mossImageTemplate(), sources: {}, paths: { transformer: "moss", textEncoder: "qwen", videoVae: "flux", tokenizer: "tokenizer.json", audioVae: "" } };
@@ -130,7 +166,7 @@ it.each(["extend", "character-sheet"] as const)("returns from %s settings to nor
/* Undo lives in the title bar; inside the editor it is Ctrl+Z. */
const undoImageEdit = () => fireEvent.keyDown(screen.getByRole("tree", { name: "Image nodes" }), { key: "z", code: "KeyZ", ctrlKey: true });
-it("keeps the prompt on the parent, opens children without drafts, and edits a child's own pixels", async () => {
+it("keeps prompts independent, opens children without drafts, and edits a child's own pixels", async () => {
vi.spyOn(persistence, "readMediaFileUrl").mockImplementation(async (_folder, location) => `blob:${location.relativePath}`);
vi.stubGlobal("URL", class extends URL { static revokeObjectURL = vi.fn(); });
const initial = parseProjectConfig(fixture);
@@ -149,7 +185,7 @@ it("keeps the prompt on the parent, opens children without drafts, and edits a c
await waitFor(() => expect(preview()).toHaveAttribute("src", "blob:media/edited.png"));
expect(preview()!.parentElement!.style.getPropertyValue("--image-ratio")).toBe(String(672 / 544));
fireEvent.click(screen.getByRole("button", { name: "View Original" }));
- expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("Warm up the lighting");
+ expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("");
fireEvent.click(screen.getByRole("button", { name: "View Edited" }));
fireEvent.click(screen.getByRole("button", { name: "View Edited" }));
expect(current().assets).toEqual([original, result]);
@@ -161,9 +197,11 @@ it("keeps the prompt on the parent, opens children without drafts, and edits a c
scene: { sourceImage: { relativePath: "media/edited.png" }, nodes: [{ description: "Make it moonlit" }] } } });
await waitFor(() => expect(preview()).toHaveAttribute("src", "blob:media/edited.png"));
fireEvent.click(screen.getByRole("button", { name: "View Edited" }));
+ expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("");
+ fireEvent.click(screen.getByRole("button", { name: "View Editing Edited" }));
expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("Make it moonlit");
fireEvent.click(screen.getByRole("button", { name: "View Original" }));
- expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("Warm up the lighting");
+ expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("");
expect(current().assets).toHaveLength(3);
});
@@ -183,7 +221,9 @@ it("edits imported-image generation settings and restores them with the draft",
const reopened = parseProjectConfig(JSON.parse(JSON.stringify(current())));
expect(reopened.imageScene).toEqual(current().imageScene);
fireEvent.click(screen.getByRole("button", { name: "View Imported" }));
- expect(comboValue(screen.getByLabelText("Resolution"))).toBe("672x544");
+ expect(comboValue(screen.getByLabelText("Resolution"))).toBe("992x800");
+ expect(screen.getByLabelText("Steps")).toHaveValue(20);
+ expect(screen.getByLabelText("Seed")).toHaveValue(-1);
fireEvent.click(screen.getByRole("button", { name: "View Editing Imported" }));
expect(screen.getByLabelText("Steps")).toHaveValue(32);
expect(screen.getByLabelText("Seed")).toHaveValue(123456);
@@ -217,7 +257,9 @@ it.each(["media/photo.png", "references/photo.webp", "references/frames/frame.pn
const draftId = current().assets[1].id;
fireEvent.click(screen.getByRole("button", { name: "View Imported" }));
expect(current().imageScene?.outputAssetId).toBe("imported");
- expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("Make the sky pink");
+ undoImageEdit();
+ expect(current().imageScene?.outputAssetId).toBe("imported");
+ expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("");
expect(current().assets).toHaveLength(2);
fireEvent.click(screen.getByRole("button", { name: "View Editing Imported" }));
expect(current().imageScene?.outputAssetId).toBe(draftId);
diff --git a/src/components/workspace/ImageEditor.tsx b/src/components/workspace/ImageEditor.tsx
index b6dc605..449a8b3 100644
--- a/src/components/workspace/ImageEditor.tsx
+++ b/src/components/workspace/ImageEditor.tsx
@@ -8,7 +8,7 @@ import { compileImageEdits, editGeneratedImage, imageEditDebugPrompt, imageEditO
import { imageSettings } from "../../lib/imageSettings";
import { outputDimensions } from "../../lib/export";
import { compileImagePrompt } from "../../lib/imagePrompt";
-import { createEmptyImage, imageEditingSnapshot, imageFamily, imageFamilyRoot, makeImagePrimary, removeImageAsset, restoreGeneratedImage, saveImageDraft } from "../../lib/imageHistory";
+import { createEmptyImage, imageFamily, imageFamilyRoot, makeImagePrimary, removeImageAsset, restoreGeneratedImage, saveImageDraft } from "../../lib/imageHistory";
import { isTauri } from "../../lib/persistence";
import { createDraftGenerationJob, isVideoReference, PROJECT_RESOLUTIONS, referenceTypeLabel, type ProjectConfig, type ProjectReference } from "../../lib/project";
import { defaultGeneratorTemplate, generationStepsForTemplate, loadDebugOptionsEnabled, loadGeneratorTemplateSettings, MINIMAX_H3_MODEL_TYPE, generatorModel, templateSupportsImages, subscribeDebugOptions, subscribeGeneratorTemplates, templateUsable, type GeneratorTemplate } from "../../lib/settings";
@@ -165,7 +165,7 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene
pan.current = null; setPanning(false);
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
};
- const work = workItems.filter((item) => item.imageAssetId === scene.outputAssetId || item.imageDraftId === scene.outputAssetId || item.id === scene.outputAssetId).at(-1);
+ const work = workItems.filter((item) => (item.imageDraftId ?? item.imageAssetId ?? item.id) === scene.outputAssetId).at(-1);
const active = work && isWorkActive(work);
const output = config.assets.find((asset) => asset.id === scene.outputAssetId);
const templateSnapshot = output?.imageDraft ? output.imageGeneration?.template : undefined;
@@ -227,12 +227,11 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene
};
const resetImageEditing = (id: string) => {
const asset = config.assets.find((asset) => asset.id === id);
- const snapshot = asset && (imageEditingSnapshot(config, asset) ?? asset.imageGeneration);
- if (!snapshot) return;
+ const snapshot = asset?.imageGeneration;
undo.current = []; redo.current = []; historyChanged((value) => value + 1);
pointer.current = null; setDraftBox(null); setDrawKind(null); setRenaming(null);
- setCollapsed(new Set()); setSelection(snapshot.scene.nodes.find((node) => node.kind === "root")!.id);
- if (imageTemplates.some((candidate) => candidate.id === snapshot.generatorTemplateId)) {
+ setCollapsed(new Set()); setSelection(snapshot?.scene.nodes.find((node) => node.kind === "root")?.id ?? "image-root");
+ if (snapshot && imageTemplates.some((candidate) => candidate.id === snapshot.generatorTemplateId)) {
setTemplateId(snapshot.generatorTemplateId);
localStorage.setItem("slopus.image-generator-template.v1", snapshot.generatorTemplateId);
}
@@ -687,7 +686,7 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene
onPointerUpCapture={endPan} onPointerCancelCapture={endPan} onLostPointerCapture={endPan}
onAuxClick={(event) => { if (event.button === 1) event.preventDefault(); }}>
<div className="image-frame" style={{ "--image-ratio": width / height, "--image-zoom": view.zoom, "--image-pan-x": `${view.x}px`, "--image-pan-y": `${view.y}px` } as CSSProperties}>
- {showResult ? <ReferenceImage key={output!.id} folderPath={folderPath} relativePath={output!.relativePath} sourcePath={output!.sourcePath} alt={output!.name} /> : imageRoot && scene.sourceImage ? <ReferenceImage folderPath={folderPath} relativePath={scene.sourceImage.relativePath} alt={scene.sourceImage.name} /> : output && !imageRoot && (output.relativePath || output.sourcePath) ? <ReferenceImage key={output.id} folderPath={folderPath} relativePath={output.relativePath} sourcePath={output.sourcePath} alt={output.name} onMeasured={!output.imageGeneration ? (size) => measureImportedImage(output.id, size) : undefined} /> : <div className="image-empty"><Image32 aria-hidden="true" /><strong>{templateSnapshot ? output!.name : imageRoot ? "Add an image to edit" : "Compose your image"}</strong><span>{templateSnapshot ? active ? "The generated image will appear here." : "No generated image yet." : imageRoot ? "Choose Add image file in the image bar menu, then enter an edit prompt." : "Add objects, text and groups, then describe them in the inspector."}</span></div>}
+ {active && output?.imageDraft ? <div className="image-empty" role="status"><Image32 aria-hidden="true" /><strong>{work.status === "queued" ? "Queued" : "Generating"}</strong><span>The generated image will appear here.</span></div> : showResult ? <ReferenceImage key={output!.id} folderPath={folderPath} relativePath={output!.relativePath} sourcePath={output!.sourcePath} alt={output!.name} /> : imageRoot && scene.sourceImage ? <ReferenceImage folderPath={folderPath} relativePath={scene.sourceImage.relativePath} alt={scene.sourceImage.name} /> : output && !imageRoot && (output.relativePath || output.sourcePath) ? <ReferenceImage key={output.id} folderPath={folderPath} relativePath={output.relativePath} sourcePath={output.sourcePath} alt={output.name} onMeasured={!output.imageGeneration ? (size) => measureImportedImage(output.id, size) : undefined} /> : <div className="image-empty"><Image32 aria-hidden="true" /><strong>{templateSnapshot ? output!.name : imageRoot ? "Add an image to edit" : "Compose your image"}</strong><span>{templateSnapshot ? active ? "The generated image will appear here." : "No generated image yet." : imageRoot ? "Choose Add image file in the image bar menu, then enter an edit prompt." : "Add objects, text and groups, then describe them in the inspector."}</span></div>}
<svg className={`image-overlay ${drawKind ? "drawing" : ""}`} viewBox="0 0 1000 1000" preserveAspectRatio="none" aria-label="Image placement canvas" onPointerDown={pointerDown} onPointerMove={pointerMove} onPointerUp={pointerUp} onPointerCancel={() => { pointer.current = null; setDraftBox(null); }}>
{boxes && scene.nodes.filter((node) => node.box).map((node) => {
const box = pointer.current?.id === node.id && draftBox ? draftBox : node.box!;
@@ -699,7 +698,7 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene
</div></div>}
{(error || work?.error) && <InfoBar className="image-error" severity="error" title="Couldn’t update the image" message={error ?? work?.error ?? ""} onClose={error ? () => setError(null) : undefined} />}
<div className="image-status" role="status">{active && <ProgressBar value={work.progress * 100} aria-label="Image generation progress" />}<span>{active ? work.detail : extendMode && extendOptions ? `Zoom: ${extendSize?.width ?? "-"} \u00d7 ${extendSize?.height ?? "-"} px` : templateSnapshot ? `${templateSnapshot.kind === "extend" ? "Zoom" : "Character sheet"} · ${width} × ${height} px` : imageRoot ? editingBlocked ?? editPlan?.error ?? `${width} × ${height} · ${editPlan?.edits.length} edits in hierarchy order` : !isTauri() ? "Image generation is available in the desktop app." : `${width} × ${height}${isMiniMaxH3 ? "" : " · Placement boxes guide the prompt"}`}</span></div>
- <ImageBar ref={imageResults} images={images} selectedId={scene.outputAssetId} folderPath={folderPath} onSelect={selectImage}
+ <ImageBar ref={imageResults} workItems={workItems} images={images} selectedId={scene.outputAssetId} folderPath={folderPath} onSelect={selectImage}
onMenu={(id, x, y, inFamily) => { setContextMenu(null); setImageMenu({ id, x, y, inFamily, source: "bar" }); }} />
</section>
<Splitter {...inspectorPane.splitterProps} reverse aria-label="Resize inspector" />
diff --git a/src/lib/imageHistory.test.ts b/src/lib/imageHistory.test.ts
index 5c46d68..b35d5f0 100644
--- a/src/lib/imageHistory.test.ts
+++ b/src/lib/imageHistory.test.ts
@@ -6,7 +6,35 @@ import snapshotFixture from "../../fixtures/image-generation-snapshot.json";
import { createImageEditScene, createImageScene } from "./imageScene";
describe("generated image history", () => {
- it("retains the parent's edit instructions after reopening and deleting its children", () => {
+ it("restores a generated original's own prompt despite legacy shared edit instructions", () => {
+ const config = parseProjectConfig(fixture);
+ config.imageScene = createImageScene("A forest at sunrise");
+ const generation = imageGenerationSnapshot(config, "Compiled forest", "generator");
+ const source = { name: "Original", relativePath: "media/original.png", width: 640, height: 480 };
+ config.imageScene = createImageEditScene(source);
+ config.imageScene.nodes[0].description = "Make it snow";
+ const legacyEditing = imageGenerationSnapshot(config, "Compiled snow", "generator");
+ config.assets = [{ ...source, id: "original", kind: "image", mimeType: "image/png", createdAt: config.createdAt,
+ imageGeneration: generation, imageEditing: legacyEditing }];
+ config.imageScene.outputAssetId = "original";
+ const drafted = saveImageDraft(config, "generator");
+ const draftId = drafted.imageScene!.outputAssetId!;
+ const changed = structuredClone(drafted);
+ changed.imageScene!.nodes[0].description = "Make it moonlit";
+ changed.imageScene!.steps = 32;
+ const saved = saveImageDraft(changed, "generator");
+ expect(saved.assets[0]).toEqual(config.assets[0]);
+ expect(drafted.assets[1].imageGeneration!.scene.nodes[0].description).toBe("Make it snow");
+ const reopened = parseProjectConfig(JSON.parse(JSON.stringify(saved)));
+ const original = restoreGeneratedImage(reopened, "original");
+ expect(original.imageScene!.nodes[0].description).toBe("A forest at sunrise");
+ expect(original.imageScene!.steps).toBe(20);
+ const edit = restoreGeneratedImage(original, draftId);
+ expect(edit.imageScene!.nodes[0].description).toBe("Make it moonlit");
+ expect(edit.imageScene!.steps).toBe(32);
+ });
+
+ it("keeps edits on their own image after reopening and deleting children", () => {
const initial = parseProjectConfig(fixture);
const source = { name: "Original", relativePath: "media/original.png", width: 640, height: 480 };
initial.assets = [{ ...source, id: "original", kind: "image", mimeType: "image/png", createdAt: initial.createdAt }];
@@ -19,14 +47,14 @@ describe("generated image history", () => {
expect(completed.imageScene!.sourceImage?.relativePath).toBe("media/edited.png");
const reopened = parseProjectConfig(JSON.parse(JSON.stringify(completed)));
const parent = restoreGeneratedImage({ ...reopened, assets: removeImageAsset(reopened.assets, draft.id) }, "original");
- expect(parent.imageScene!.nodes[0].description).toBe("Make the sky pink");
+ expect(parent.imageScene!.nodes[0].description).toBe("");
+ expect(completed.assets[0]).toEqual(initial.assets[0]);
+ expect(draft.imageGeneration!.scene.nodes[0].description).toBe("Make the sky pink");
expect(parent.imageScene!.sourceImage).toEqual(source);
expect(saveImageDraft(parent)).toBe(parent);
expect(parent.assets).toHaveLength(1);
expect(parent.assets[0].imageGeneration).toBeUndefined();
- const invalid = structuredClone(parent);
- invalid.assets[0].imageEditing!.scene.sourceImage!.relativePath = "media/another.png";
- expect(() => parseProjectConfig(invalid)).toThrow("Image editing instructions must use this image as their source.");
+ expect(parent.assets[0].imageEditing).toBeUndefined();
});
it("keeps a submitted template intact when editing its pending entry and completing in the background", () => {
@@ -108,7 +136,7 @@ describe("generated image history", () => {
expect(snapshot.scene.outputAssetId).toBeNull();
config.assets = [{ id: "legacy", kind: "image", name: "Legacy", relativePath: "media/generated/legacy.jpg", mimeType: "image/jpeg", createdAt: config.createdAt }];
const restored = restoreGeneratedImage(config, "legacy");
- expect(restored.imageScene).toEqual({ ...config.imageScene, outputAssetId: "legacy" });
+ expect(restored.imageScene).toEqual({ ...createImageScene(), outputAssetId: "legacy" });
expect(restored.settings).toEqual(config.settings);
});
diff --git a/src/lib/imageHistory.ts b/src/lib/imageHistory.ts
index 2100527..8e39a49 100644
--- a/src/lib/imageHistory.ts
+++ b/src/lib/imageHistory.ts
@@ -18,13 +18,6 @@ export function imageGenerationSnapshot(config: ProjectConfig, prompt: string, g
});
}
-/** Recover older parents' instructions from their saved edits until authored again. */
-export function imageEditingSnapshot(config: ProjectConfig, asset: ProjectAsset): ImageGenerationSnapshot | undefined {
- return asset.imageEditing ?? (!asset.imageDraft && asset.relativePath ? [...config.assets].reverse().find((candidate) => candidate.id !== asset.id
- && !candidate.imageGeneration?.template && candidate.imageGeneration?.scene.rootType === "image"
- && candidate.imageGeneration.scene.sourceImage?.relativePath === asset.relativePath)?.imageGeneration : undefined) ?? undefined;
-}
-
/** The primary image of `id`'s family: its parent, or itself when it is the
* primary (or its parent has since been removed). */
export function imageFamilyRoot(assets: readonly ProjectAsset[], id: string | null | undefined): string | undefined {
@@ -64,7 +57,7 @@ export function removeImageAsset(assets: readonly ProjectAsset[], id: string): P
}
/** Keep the editable version in history without creating another image file. */
-export function saveImageDraft(config: ProjectConfig, generatorTemplateId?: string, regenerate = false): ProjectConfig {
+export function saveImageDraft(config: ProjectConfig, generatorTemplateId?: string, regenerate = false, draftId?: string): ProjectConfig {
const scene = config.imageScene;
if (!scene) return config;
const selected = config.assets.find((asset) => asset.id === scene.outputAssetId);
@@ -72,8 +65,10 @@ export function saveImageDraft(config: ProjectConfig, generatorTemplateId?: stri
// recipe with the editor's generic image settings. Edits become another draft.
const templateDraft = selected?.imageDraft && selected.imageGeneration?.template;
if (templateDraft && JSON.stringify({ ...scene, outputAssetId: null }) === JSON.stringify(selected.imageGeneration!.scene)) return config;
- const source = scene.rootType === "image" ? scene.sourceImage : null;
- if (!source && !selected?.imageDraft) {
+ const sourceImage = scene.rootType === "image" ? scene.sourceImage : null;
+ // Copy only source pixels and dimensions, never an asset's identity or history.
+ const source = sourceImage && { relativePath: sourceImage.relativePath, name: sourceImage.name, width: sourceImage.width, height: sourceImage.height };
+ if (!regenerate && !source && !selected?.imageDraft) {
const generation = selected?.imageGeneration;
const root = scene.nodes.find((node) => node.kind === "root");
const savedRoot = generation?.scene.nodes.find((node) => node.kind === "root");
@@ -85,8 +80,8 @@ export function saveImageDraft(config: ProjectConfig, generatorTemplateId?: stri
nodes: generation.scene.nodes.map((node) => node.kind === "root" ? { ...node, name: root.name } : node) } },
} : asset) };
}
- const saved = selected && !selected.imageDraft ? imageEditingSnapshot(config, selected) : selected?.imageGeneration;
- const snapshot = imageGenerationSnapshot(config, "", generatorTemplateId || saved?.generatorTemplateId || selected?.imageGeneration?.generatorTemplateId || "image-draft");
+ const saved = selected?.imageGeneration;
+ const snapshot = imageGenerationSnapshot(config, "", generatorTemplateId || saved?.generatorTemplateId || "image-draft");
// Merely viewing a finished edit (including session autosave) must not create
// a draft. Generate explicitly forks it, even when its inputs are unchanged.
if (!regenerate && selected && !selected.imageDraft && saved && !saved.template
@@ -97,14 +92,11 @@ export function saveImageDraft(config: ProjectConfig, generatorTemplateId?: stri
config = { ...config, assets: [...config.assets, { id: `image-source-${crypto.randomUUID()}`, kind: "image", ...source,
mimeType: /\.png$/i.test(source.relativePath) ? "image/png" : "image/jpeg", createdAt: new Date().toISOString() }] };
}
- if (!selected?.imageDraft && scene.outputAssetId && scene.nodes.length === 1 && !scene.nodes[0].description.trim()) return config;
+ if (!regenerate && !selected?.imageDraft && scene.outputAssetId && scene.nodes.length === 1 && !scene.nodes[0].description.trim()) return config;
const existing = selected?.imageDraft && !templateDraft ? selected : undefined;
- const id = existing?.id ?? `image-draft-${crypto.randomUUID()}`;
+ const id = existing?.id ?? draftId ?? `image-draft-${crypto.randomUUID()}`;
const edited = source && config.assets.find((asset) => asset.kind === "image" && !asset.imageDraft && asset.relativePath === source.relativePath);
- if (edited && JSON.stringify(edited.imageEditing) !== JSON.stringify(snapshot)) {
- config = { ...config, assets: config.assets.map((asset) => asset.id === edited.id ? { ...asset, imageEditing: structuredClone(snapshot) } : asset) };
- }
- const parentAssetId = existing?.parentAssetId ?? imageFamilyRoot(config.assets, templateDraft ? selected.id : edited?.id);
+ const parentAssetId = existing?.parentAssetId ?? imageFamilyRoot(config.assets, templateDraft ? selected.id : edited?.id ?? (!selected?.imageDraft ? selected?.id : undefined));
if (existing && existing.parentAssetId === parentAssetId && JSON.stringify(existing.imageGeneration) === JSON.stringify(snapshot)) return config;
const asset = { id, kind: "image" as const, ...source, name: existing?.name ?? (source ? `Editing ${source.name}` : "New image"),
imageDraft: true, mimeType: /\.png$/i.test(source?.relativePath ?? "") ? "image/png" : "image/jpeg",
@@ -150,17 +142,18 @@ export function completeImageDraft(config: ProjectConfig, id: string, result: Pr
export function restoreGeneratedImage(config: ProjectConfig, id: string): ProjectConfig {
const asset = config.assets.find((candidate) => candidate.id === id && candidate.kind === "image");
if (!asset) return config;
- const editing = !asset.imageDraft ? imageEditingSnapshot(config, asset) : undefined;
- const snapshot = editing ?? asset.imageGeneration;
+ // Each image owns its inputs. Legacy imageEditing fields held a child's
+ // instructions on its source and must not override the source's own recipe.
+ const snapshot = asset.imageGeneration;
const source = !snapshot && imageSourceSchema.safeParse(asset);
if (source && source.success) {
return { ...config, thumbnail: asset.relativePath ?? null,
- imageScene: { ...createImageEditScene(source.data, config.imageScene ?? undefined), outputAssetId: id } };
+ imageScene: { ...createImageEditScene(source.data), outputAssetId: id } };
}
if (!snapshot) return { ...config, thumbnail: asset.relativePath ?? null,
- imageScene: { ...(config.imageScene?.rootType === "image" ? createImageScene() : config.imageScene ?? createImageScene(config.brief.prompt)), outputAssetId: id } };
+ imageScene: { ...createImageScene(), outputAssetId: id } };
const restored = structuredClone(snapshot);
- const scene = !editing && !asset.imageDraft && restored.scene.rootType === "image" && asset.relativePath && asset.width && asset.height
+ const scene = !asset.imageDraft && restored.scene.rootType === "image" && asset.relativePath && asset.width && asset.height
? createImageEditScene({ relativePath: asset.relativePath, name: asset.name, width: asset.width, height: asset.height }, restored.scene)
: restored.scene;
const references = new Map(restored.references.map((reference) => [reference.id, reference]));
diff --git a/src/lib/workQueue.test.ts b/src/lib/workQueue.test.ts
index caf0607..4d40afb 100644
--- a/src/lib/workQueue.test.ts
+++ b/src/lib/workQueue.test.ts
@@ -18,7 +18,7 @@ import { prepareReferenceVideos, releaseReferenceVideos } from "./referenceVideo
import { downloadTemplateWeights, getWeightDownloadState } from "./weightDownloads";
import { compileImagePrompt } from "./imagePrompt";
import { addImageNode, createImageEditScene } from "./imageScene";
-import { createEmptyImage, makeImagePrimary, restoreGeneratedImage } from "./imageHistory";
+import { createEmptyImage, imageGenerationSnapshot, makeImagePrimary, restoreGeneratedImage } from "./imageHistory";
import { sceneGenerationRequest } from "./sceneGeneration";
import { bridgeGapFrames, currentLongShotArchives } from "./longShot";
@@ -450,7 +450,8 @@ describe("image generation work", () => {
const { queue } = setup();
const record = imageProject();
record.config.assets = ["first", "second", "third"].map((id) => ({ id, kind: "image", name: id, imageDraft,
- relativePath: `media/${id}.jpg`, mimeType: "image/jpeg", createdAt: record.config.createdAt }));
+ relativePath: `media/${id}.jpg`, mimeType: "image/jpeg", createdAt: record.config.createdAt,
+ imageGeneration: imageGenerationSnapshot(record.config, "Compiled prompt", template.id) }));
record.config.imageScene!.outputAssetId = "first";
const session = queue.project(record);
vi.mocked(invoke).mockImplementation(async (_command, args) => ({ relativePath: `media/${(args as { jobId: string }).jobId}.jpg`, width: 768, height: 768 }));
@@ -461,7 +462,13 @@ describe("image generation work", () => {
queue.enqueueImage(session, template);
const [first, second] = queue.getSnapshot();
expect(queue.getSnapshot()).toHaveLength(2);
- expect(second).toMatchObject({ imageAssetId: "second", status: "queued" });
+ expect(second).toMatchObject({ imageAssetId: imageDraft ? "second" : second.id, imageDraftId: imageDraft ? "second" : second.id, status: "queued" });
+ expect(session.getSnapshot().config.imageScene!.outputAssetId).toBe(second.imageDraftId);
+ if (!imageDraft) {
+ expect(session.getSnapshot().config.assets.slice(0, 3)).toEqual(record.config.assets);
+ expect(session.getSnapshot().config.assets.find((asset) => asset.id === second.imageDraftId)).toMatchObject({ imageDraft: true, parentAssetId: "second" });
+ expect(session.getSnapshot().config.assets.find((asset) => asset.id === second.imageDraftId)?.relativePath).toBeUndefined();
+ }
expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce();
session.update((current) => restoreGeneratedImage(current, "third"));
await finish(queue, first.id);
@@ -531,7 +538,9 @@ describe("image generation work", () => {
expect(result.assets[1].imageGeneration!.references.map((reference) => reference.id)).toEqual(["Lighting", "Balloon"]);
expect(result.imageScene!.nodes).toHaveLength(1);
expect(result.imageScene!.nodes[0].description).toBe("");
- expect(restoreGeneratedImage(result, result.assets[0].id).imageScene!.nodes).toEqual(scene.nodes);
+ expect(result.assets[1].imageGeneration!.scene.nodes).toEqual(scene.nodes);
+ expect(restoreGeneratedImage(result, result.assets[0].id).imageScene!.nodes).toMatchObject([{ description: "" }]);
+ expect(result.assets[0].imageEditing).toBeUndefined();
});
it("submits ordered inpainting as one job, saves a child PNG, and retains its edit recipe", async () => {
const { queue } = setup();
@@ -570,7 +579,9 @@ describe("image generation work", () => {
expect(result.imageScene!.outputAssetId).toBe(draftId);
expect(result.imageScene).toMatchObject({ rootType: "image", sourceImage: { relativePath: "media/generated/edited.png" } });
expect(result.assets[1]).toMatchObject({ mimeType: "image/png", imageGeneration: { scene, prompt: expect.stringContaining("Edit 2 (24, 16, 48, 32)") } });
- expect(restoreGeneratedImage(result, result.assets[0].id).imageScene!.nodes).toEqual(scene.nodes);
+ expect(result.assets[1].imageGeneration!.scene.nodes).toEqual(scene.nodes);
+ expect(restoreGeneratedImage(result, result.assets[0].id).imageScene!.nodes).toMatchObject([{ description: "" }]);
+ expect(result.assets[0].imageEditing).toBeUndefined();
expect(releaseRendered).toHaveBeenCalledWith(request.jobId);
});
it("submits the selected image edit resolution, steps and seed to planning and generation", async () => {
@@ -599,8 +610,8 @@ describe("image generation work", () => {
vi.spyOn(crypto, "getRandomValues").mockImplementation((array) => { (array as Uint32Array).set([0, ++seed]); return array; });
const session = queue.project(record);
for (let index = 0; index < 3; index++) {
- if (index === 2) session.update((config) => ({ ...config, imageScene: { ...config.imageScene!,
- nodes: config.imageScene!.nodes.map((node) => ({ ...node, description: "Make it moonlit" })) } }));
+ if (index > 0) session.update((config) => ({ ...config, imageScene: { ...structuredClone(record.config.imageScene!), outputAssetId: config.assets[0].id,
+ nodes: record.config.imageScene!.nodes.map((node) => ({ ...node, description: index === 2 ? "Make it moonlit" : "Warm up the lighting" })) } }));
const previous = structuredClone(session.getSnapshot().config.assets.filter((asset) => !asset.imageDraft));
queue.enqueueImage(session, template);
await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(index + 1));
@@ -611,14 +622,14 @@ describe("image generation work", () => {
await finish(queue, request.jobId);
const config = parseProjectConfig(JSON.parse(JSON.stringify(session.getSnapshot().config)));
expect(config.assets).toHaveLength(index + 2);
- expect(config.assets.slice(0, previous.length).map(({ imageEditing: _editing, ...asset }) => asset)).toEqual(previous.map(({ imageEditing: _editing, ...asset }) => asset));
+ expect(config.assets.slice(0, previous.length)).toEqual(previous);
expect(config.assets[0]).toMatchObject({ name: "Original", relativePath: "media/source.png", width: 1001, height: 809 });
expect(config.assets.slice(1).every((asset) => asset.parentAssetId === config.assets[0].id && !asset.imageDraft)).toBe(true);
expect(config.imageScene!.nodes[0].description).toBe("");
expect(config.imageScene!.sourceImage?.relativePath).toBe(`media/edited-${index}.png`);
session.update(() => restoreGeneratedImage(config, config.assets[0].id));
- expect(session.getSnapshot().config.imageScene).toMatchObject({ seed: -1, sourceImage: { relativePath: "media/source.png" }, outputSize: { width: 672, height: 544 } });
- expect(session.getSnapshot().config.imageScene!.nodes[0].description).toBe(index === 2 ? "Make it moonlit" : "Warm up the lighting");
+ expect(session.getSnapshot().config.imageScene).toMatchObject({ seed: -1, sourceImage: { relativePath: "media/source.png" } });
+ expect(session.getSnapshot().config.imageScene!.nodes[0].description).toBe("");
expect(session.getSnapshot().config.assets).toHaveLength(index + 2);
}
});
@@ -729,7 +740,8 @@ describe("image generation work", () => {
expect(invoke).toHaveBeenCalledWith("save_generated_image", { folderPath: "C:/Image", jobId: request.jobId });
const saved = session.getSnapshot().config;
expect(saved.imageScene?.background).toBe("Edited during generation");
- expect(saved.imageScene?.outputAssetId).toBe(request.jobId);
+ expect(saved.imageScene?.outputAssetId).not.toBe(request.jobId);
+ expect(saved.assets.find((asset) => asset.id === saved.imageScene?.outputAssetId)).toMatchObject({ imageDraft: true, imageGeneration: { scene: { background: "Edited during generation" } } });
expect(saved.assets[0]).toMatchObject({ kind: "image", mimeType: "image/jpeg", relativePath: "media/generated/still.jpg", width: 768, height: 768 });
expect(saved.assets[0].imageGeneration).toMatchObject({ resolution: "768p", aspectRatio: "1:1", prompt: request.prompt, generatorTemplateId: template.id });
expect(saved.assets[0].imageGeneration!.scene.background).not.toBe("Edited during generation");
@@ -758,7 +770,9 @@ describe("image generation work", () => {
expect(queue.getSnapshot().find((item) => item.id === image.id)?.status).toBe("cancelled");
await finish(queue, queue.getSnapshot()[0].id);
expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce();
- expect(session.getSnapshot().config.assets).toHaveLength(0);
+ expect(session.getSnapshot().config.assets).toHaveLength(1);
+ expect(session.getSnapshot().config.assets[0]).toMatchObject({ id: image.imageDraftId, imageDraft: true });
+ expect(session.getSnapshot().config.assets[0].relativePath).toBeUndefined();
});
it("retains the saved image for retry when writing the project fails", async () => {
const { queue, saved } = setup(); const session = queue.project(imageProject());
diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.ts
index ae9dcce..f594b0c 100644
--- a/src/lib/workQueue.ts
+++ b/src/lib/workQueue.ts
@@ -271,29 +271,32 @@ export class WorkQueue {
enqueueImage(session: ProjectSession, template: GeneratorTemplate) {
if (!isTauri()) throw new Error("Image generation requires the desktop app and downloaded model weights.");
if (!templateSupportsImages(template)) throw new Error("Choose a prompt generator for images.");
- session.update((config) => saveImageDraft(config, template.id, true));
- const current = session.getSnapshot().config;
+ let current = session.getSnapshot().config;
const scene = current.imageScene ?? createImageScene(current.brief.prompt);
if (!generatorModel(template.modelType).imageEditing && scene.rootType === "image") throw new Error(`${generatorModel(template.modelType).label} does not support image editing. Choose an editing generator.`);
if (activeGenerationEffects(scene.generationEffects) && !generatorModel(template.modelType).generationEffects) throw new Error("This model does not support generation effects. Bypass or remove the effects, or choose another generator.");
const edit = scene.rootType === "image" ? compileImageEdits(current) : null;
if (!imageScenePrompt(scene)) throw new Error("Describe the image or add an object before generating.");
const projectKey = projectQueueKey(session.record);
- if (this.items.some((item) => item.projectKey === projectKey && item.kind === "image" && item.imageAssetId === scene.outputAssetId && isWorkActive(item))) return;
+ if (this.items.some((item) => item.projectKey === projectKey && item.kind === "image" && (item.imageDraftId ?? item.imageAssetId) === scene.outputAssetId && isWorkActive(item))) return;
+ const { prompt, references } = edit ? edit.edits[0] : compileImagePrompt(current, { modelType: template.modelType });
+ const { width, height } = edit ? imageEditOutputSize(scene) : outputDimensions(imageSettings(current).resolution, imageSettings(current).aspectRatio);
+ const id = `image-${crypto.randomUUID()}`;
+ const guidanceScale = imageCfgScale(template.modelType, scene.cfgScales);
+ // Publish and select the job's own entry before generation starts. The
+ // finished source stays untouched, and an existing empty draft is reused.
+ session.update((config) => saveImageDraft({ ...config, imageScene: {
+ ...(config.imageScene ?? scene),
+ ...(guidanceScale !== undefined ? { cfgScales: { ...(config.imageScene ?? scene).cfgScales, [template.modelType]: guidanceScale } } : {}),
+ } }, template.id, true, id));
+ current = session.getSnapshot().config;
const config = structuredClone({ ...current, providerSettings: { ...current.providerSettings,
slopfab: engineProviderSetting(template.paths, current.providerSettings.slopfab, template.attention, template.loras, "prompt", template.additionalSafetensors, false, template.sources, template) } });
- const guidanceScale = imageCfgScale(template.modelType, scene.cfgScales);
- if (guidanceScale !== undefined) config.imageScene = { ...structuredClone(scene), cfgScales: { ...scene.cfgScales, [template.modelType]: guidanceScale } };
- const { prompt, references } = edit ? edit.edits[0] : compileImagePrompt(current, { modelType: template.modelType });
const referencePaths = (selected: typeof references) => [
...(edit ? [projectItemPath(session.record.folderPath, edit.source)!] : []),
...selected.flatMap((reference) => referenceImages(reference).map((image) => projectItemPath(session.record.folderPath, image)!)),
];
- const { width, height } = edit ? imageEditOutputSize(scene) : outputDimensions(imageSettings(current).resolution, imageSettings(current).aspectRatio);
- const id = `image-${crypto.randomUUID()}`;
- const imageDraftId = current.assets.find((asset) => asset.id === scene.outputAssetId && asset.imageDraft)?.id;
- // Generating again from a finished image makes a new image in its family.
- const imageParentId = imageDraftId ? undefined : imageFamilyRoot(current.assets, scene.outputAssetId);
+ const imageDraftId = current.imageScene!.outputAssetId!;
let finish!: () => void;
const done = new Promise<void>((resolve) => { finish = resolve; });
const request: SlopfabGenerationRequest = { ...(guidanceScale !== undefined ? { guidanceScale } : {}), generationEffects: activeGenerationEffects(scene.generationEffects), jobId: id, stillImage: true, frames: 1, prompt: edit ? edit.edits[0].prompt : prompt,
@@ -304,8 +307,8 @@ export class WorkQueue {
referencePaths: referencePaths(references),
refmods: referenceRefmodInputs(session.record.folderPath, references),
};
- this.work.set(id, { id, image: true, imageDraftId, imageParentId, imageGeneration: { ...imageGenerationSnapshot(config, edit ? imageEditDebugPrompt(edit.edits) : prompt, template.id), usedSeed: request.seed }, session, sceneId: scene.nodes.find((node) => node.kind === "root")!.id, config, snapshot: JSON.stringify(scene), request, submitted: false, cancelled: false, done, finish });
- this.items = [...this.items, { id, kind: "image", imageAssetId: scene.outputAssetId, imageDraftId, projectKey, folderPath: session.record.folderPath, projectName: config.name, sceneId: scene.nodes.find((node) => node.kind === "root")!.id,
+ this.work.set(id, { id, image: true, imageDraftId, imageGeneration: { ...imageGenerationSnapshot(config, edit ? imageEditDebugPrompt(edit.edits) : prompt, template.id), usedSeed: request.seed }, session, sceneId: scene.nodes.find((node) => node.kind === "root")!.id, config, snapshot: JSON.stringify(config.imageScene), request, submitted: false, cancelled: false, done, finish });
+ this.items = [...this.items, { id, kind: "image", imageAssetId: imageDraftId, imageDraftId, projectKey, folderPath: session.record.folderPath, projectName: config.name, sceneId: scene.nodes.find((node) => node.kind === "root")!.id,
title: "Image · " + config.name, submittedAt: new Date().toISOString(), status: "queued", progress: 0, detail: "Waiting to generate image", error: null, completionAt: null, cancelling: false, needsSave: false,
settings: { frames: 1, steps: request.steps, seed: request.seed, canvasWidth: width, canvasHeight: height } }];
this.publish(); this.icons.yieldToVideo(); void this.pump();