AI media harness for planning, generating, and editing locally
TypeScript
// @vitest-environment jsdom
import { installH3TestDependencies } from "../../lib/h3TestUtils";
import "@testing-library/jest-dom/vitest";
import { useState } from "react";
import { act, cleanup, createEvent, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { promptValue, typePrompt } from "./promptTestUtils";
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, saveImageDraft } from "../../lib/imageHistory";
import { createGeneratorTemplate, kreaImageTemplates, mossImageTemplate, fiboImageTemplate, fiboBaseTemplate, defaultGeneratorTemplate, saveGeneratorTemplateSettings } from "../../lib/settings";
import { createImageEditScene, createImageScene, imageScenePrompt } from "../../lib/imageScene";
import type { WorkItem } from "../../lib/workQueue";
import { compileImageEdits } from "../../lib/imageEditing";
import { invoke } from "@tauri-apps/api/core";
import * as persistence from "../../lib/persistence";
import fixture from "../../../fixtures/project-v1-image.json";
import snapshotFixture from "../../../fixtures/image-generation-snapshot.json";
vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
afterEach(() => { cleanup(); localStorage.clear(); installH3TestDependencies(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
function enableCompositionTools() {
const template = createGeneratorTemplate("MOSS", "moss");
saveGeneratorTemplateSettings({ templates: [template], defaultTemplateId: template.id, catalogVersion: 17 });
}
function setup(initial = parseProjectConfig(fixture), workItems: WorkItem[] = []) {
let latest: ProjectConfig = initial;
function Harness() {
const [config, setConfig] = useState(initial);
latest = config;
return <ImageEditor config={config} folderPath="D:/Images" onChange={setConfig} onGenerate={vi.fn()} onCancel={vi.fn()} workItems={workItems} />;
}
render(<Harness />);
return () => latest;
}
it("keeps the resolution preset when switching to H3 Image and back, including after reopening", () => {
vi.spyOn(persistence, "isTauri").mockReturnValue(true);
const normal = { ...defaultGeneratorTemplate(), id: "normal", name: "Normal image model" };
const h3 = { ...normal, id: "h3-image", name: "MiniMax H3 Image", modelType: "h3_image", defaultSteps: 6 };
saveGeneratorTemplateSettings({ templates: [normal, h3], defaultTemplateId: normal.id, catalogVersion: 23 });
installH3TestDependencies();
const initial = parseProjectConfig(fixture);
initial.imageScene = createImageScene("A forest");
initial.imageSettings = { resolution: "544p", aspectRatio: "1:1" };
const current = setup(initial);
expect(screen.getByRole("combobox", { name: "Resolution" })).toHaveTextContent("544 × 544");
choose("Generator", "MiniMax H3 Image");
expect(screen.getByRole("combobox", { name: "Resolution" })).toHaveTextContent("896 × 896");
choose("Resolution", "1280 × 1280");
expect(current().imageSettings?.resolution).toBe("768p");
choose("Generator", "Normal image model");
expect(screen.getByRole("combobox", { name: "Resolution" })).toHaveTextContent("768 × 768");
choose("Generator", "MiniMax H3 Image");
const saved = parseProjectConfig(current());
cleanup();
const reopened = setup(saved);
expect(screen.getByRole("combobox", { name: "Resolution" })).toHaveTextContent("1280 × 1280");
fireEvent.click(screen.getByRole("combobox", { name: "Resolution" }));
expect(screen.getByRole("option", { name: /3424 × 3424/ })).not.toHaveAttribute("aria-disabled", "true");
fireEvent.click(screen.getByRole("combobox", { name: "Resolution" }));
choose("Generator", "Normal image model");
choose("Resolution", "2048 × 2048");
choose("Generator", "MiniMax H3 Image");
expect(screen.getByRole("combobox", { name: "Resolution" })).toHaveTextContent("3424 × 3424");
expect(reopened().imageSettings?.resolution).toBe("2048p");
expect(screen.getByRole("button", { name: "Generate" })).toBeEnabled();
});
it("updates a low-resolution image preview in the canvas and image card, then removes it on completion", () => {
const config = parseProjectConfig(fixture);
config.imageScene = createImageScene("A forest");
const pending = saveImageDraft(config, "default", true, "pending");
const preview = { jobId: "job", width: 128, height: 128, fps: 24, step: 1, frames: ["/9j/AA=="] };
const work = { id: "job", imageDraftId: "pending", status: "generating", progress: 0.25, detail: "Generating", preview } as WorkItem;
const props = { config: pending, folderPath: "D:/Images", onChange: vi.fn(), onGenerate: vi.fn(), onCancel: vi.fn() };
const view = render(<ImageEditor {...props} workItems={[work]} />);
expect(screen.getByAltText("Image generation preview")).toHaveAttribute("src", "data:image/jpeg;base64,/9j/AA==");
expect(screen.getAllByAltText(/generation preview/)).toHaveLength(2);
view.rerender(<ImageEditor {...props} workItems={[{ ...work, preview: { ...preview, step: 2, frames: ["/9j/BB=="] } }]} />);
expect(screen.getByAltText("Image generation preview")).toHaveAttribute("src", "data:image/jpeg;base64,/9j/BB==");
view.rerender(<ImageEditor {...props} workItems={[{ ...work, status: "completed" }]} />);
expect(screen.queryAllByAltText(/generation preview/)).toHaveLength(0);
});
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];
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("allows Fibo text-to-image and editing while disabling unsupported templates", () => {
vi.spyOn(persistence, "isTauri").mockReturnValue(true);
const fibo = { ...fiboImageTemplate(), sources: {}, paths: { transformer: "fibo", textEncoder: "qwen", videoVae: "flux", tokenizer: "", audioVae: "" } };
saveGeneratorTemplateSettings({ templates: [fibo], defaultTemplateId: fibo.id, catalogVersion: 17 });
const initial = parseProjectConfig(fixture);
initial.imageScene = createImageScene("Make the sky blue");
setup(initial);
expect(screen.getByRole("combobox", { name: "Generator" })).toHaveTextContent("Fibo 2.0 Edit Turbo");
expect(screen.getByRole("button", { name: "Generate" })).toBeEnabled();
cleanup();
const source = { id: "source", kind: "image" as const, name: "Source", relativePath: "media/source.png", width: 512, height: 512, mimeType: "image/png", createdAt: initial.createdAt };
initial.assets = [source];
initial.imageScene = { ...createImageEditScene(source), outputAssetId: source.id };
initial.imageScene.nodes[0].description = "Make the sky blue";
setup(initial);
expect(screen.getByRole("button", { name: "Generate" })).toBeEnabled();
expect(screen.getByRole("radio", { name: "Edit Box" })).toBeEnabled();
expect(screen.getByRole("radio", { name: "Lasso" })).toBeEnabled();
expect(screen.queryByRole("spinbutton", { name: "CFG" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Template" }));
expect(screen.getByRole("menuitem", { name: "Zoom" })).toBeEnabled();
expect(screen.getByRole("menuitem", { name: "Character sheet" })).toBeDisabled();
});
it.each([mossImageTemplate(), ...kreaImageTemplates()])("offers $name for new images and disables editing and reference templates", (base) => {
vi.spyOn(persistence, "isTauri").mockReturnValue(true);
const moss = { ...base, sources: {}, paths: { transformer: "model", textEncoder: "qwen", videoVae: "vae", tokenizer: base.modelType === "moss" ? "tokenizer.json" : "", audioVae: "" } };
saveGeneratorTemplateSettings({ templates: [moss], defaultTemplateId: moss.id, catalogVersion: 17 });
const initial = parseProjectConfig(fixture);
initial.imageScene = createImageScene("A red apple");
setup(initial);
expect(screen.getByRole("combobox", { name: "Generator" })).toHaveTextContent(base.name);
expect(screen.getByRole("button", { name: "Generate" })).toBeEnabled();
cleanup();
const source = { id: "source", kind: "image" as const, name: "Apple", mimeType: "image/png", relativePath: "media/apple.png", width: 512, height: 512, createdAt: initial.createdAt };
initial.assets = [source];
initial.imageScene = { ...createImageEditScene(source, initial.imageScene), outputAssetId: source.id };
setup(initial);
expect(screen.getByRole("button", { name: "Generate" })).toBeDisabled();
expect(screen.getByRole("radio", { name: "Edit Box" })).toBeDisabled();
expect(screen.getByRole("status")).toHaveTextContent(`${base.name} does not support image editing`);
fireEvent.click(screen.getByRole("button", { name: "Template" }));
expect(screen.getByRole("menuitem", { name: "Zoom" })).toBeDisabled();
expect(screen.getByRole("menuitem", { name: "Character sheet" })).toBeDisabled();
});
it.each([
["extend", true, 1024], ["extend", false, 1024], ["character-sheet", true, 1024], ["character-sheet", false, 1024],
["character-sheet", true, 3424], ["character-sheet", false, 3424],
] as const)("shows the existing %s panel only while the selected entry is generating (pending: %s, height: %s)", (kind, pending, height) => {
const initial = parseProjectConfig(fixture);
const source = { id: "source", kind: "image" as const, name: "Original", relativePath: "media/source.png", width: 512, height: 512, mimeType: "image/png", createdAt: initial.createdAt };
initial.assets = [source];
const name = kind === "extend" ? "Zoom" : "Character sheet";
const generation = { ...imageGenerationSnapshot({ ...initial, imageScene: { ...createImageScene("Snowy forest"), steps: 28, seed: -1 } }, "Compiled prompt", "removed-generator"), usedSeed: 1234,
template: { sourceId: source.id, sourceName: source.name, generatorName: "Recorded generator", prompt: "Snowy forest", steps: 28, seed: -1,
...(kind === "extend" ? { kind, bounds: { x: -64, y: -32, width: 768, height: 640 } } : { kind, height }) } };
let saved = createTemplateImageDraft(initial, "template-result", `${name} result`, generation, { width: 512, height: 512 });
if (!pending) {
const result = { ...source, id: "template-result", name: `${name} result`, relativePath: "media/result.png" };
saved = completeImageDraft(saved, result.id, { ...result, imageGeneration: { ...generation, scene: createImageEditScene(result, generation.scene) } });
}
const reopened = parseProjectConfig(JSON.parse(JSON.stringify(saved)));
const current = setup(restoreGeneratedImage(reopened, "source"), pending ? [{ id: "job", imageAssetId: "source", imageDraftId: "template-result", status: "generating", progress: 0.25, detail: "Generating template" } as WorkItem] : []);
fireEvent.click(screen.getByRole("button", { name: `View ${name} result` }));
if (pending) {
const panel = within(screen.getByRole("complementary", { name: `${name} settings` }));
expect(panel.getByLabelText("Steps")).toHaveValue(28);
expect(panel.getByLabelText("Seed")).toHaveValue(-1);
expect(panel.getByLabelText("Steps")).toBeDisabled();
expect(panel.getByLabelText("Seed")).toBeDisabled();
expect(promptValue(panel.getByLabelText(`${name} prompt`))).toBe("Snowy forest");
expect(panel.getByRole("button", { name: "Executing…" })).toBeDisabled();
if (kind === "extend") {
expect(panel.getByLabelText("Zoom x")).toHaveValue(-64);
expect(panel.getByLabelText("Zoom y")).toHaveValue(-32);
expect(panel.getByLabelText("Zoom width")).toHaveValue(768);
expect(panel.getByLabelText("Zoom height")).toHaveValue(640);
} else {
expect(comboValue(panel.getByLabelText("Character sheet resolution"))).toBe(String(height));
expect(panel.getByText(/Sheet size:/)).toHaveTextContent(height === 3424 ? "9184 × 3424 px" : "2752 × 1024 px");
}
expect(screen.getByRole("button", { name: "Cancel" })).toBeEnabled();
expect(screen.getByRole("progressbar", { name: "Image generation progress" })).toBeInTheDocument();
fireEvent.contextMenu(screen.getByRole("button", { name: `View ${name} result` }));
expect(screen.getByRole("menuitem", { name: "Remove" })).toBeDisabled();
fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });
} else {
expect(screen.getByRole("complementary", { name: "Image node inspector" })).toBeInTheDocument();
expect(screen.getByLabelText("Edit prompt")).toBeInTheDocument();
expect(screen.queryByRole("complementary", { name: `${name} settings` })).not.toBeInTheDocument();
}
fireEvent.click(screen.getByRole("button", { name: "View Original" }));
expect(screen.queryByRole("complementary", { name: `${name} settings` })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: `View ${name} result` }));
expect(current().assets).toEqual(reopened.assets);
if (!pending) {
fireEvent.contextMenu(screen.getByRole("button", { name: `View ${name} result` }));
fireEvent.click(screen.getByRole("menuitem", { name: "Edit" }));
expect(screen.getByLabelText("Edit prompt")).toBeInTheDocument();
expect(current().assets.at(-1)?.imageDraft).toBe(true);
}
});
it.each(["extend", "character-sheet"] as const)("returns from %s settings to normal image editing as generation completes", (kind) => {
const config = parseProjectConfig(fixture);
const source = { id: "source", kind: "image" as const, name: "Original", relativePath: "media/source.png", width: 512, height: 512, mimeType: "image/png", createdAt: config.createdAt };
config.assets = [source];
const generation = { ...imageGenerationSnapshot({ ...config, imageScene: createImageScene() }, "Compiled prompt", "default"), usedSeed: 42,
template: { sourceId: source.id, sourceName: source.name, generatorName: "Default", prompt: "Forest", steps: 28, seed: 42,
...(kind === "extend" ? { kind, bounds: { x: -64, y: -32, width: 768, height: 640 } } : { kind, height: 1024 }) } };
const pending = createTemplateImageDraft(config, "result", "Result", generation, { width: 512, height: 512 });
const work = { id: "job", imageAssetId: "source", imageDraftId: "result", status: "generating", progress: 0.25, detail: "Generating template" } as WorkItem;
const props = { folderPath: "D:/Images", onChange: vi.fn(), onGenerate: vi.fn(), onCancel: vi.fn() };
const { rerender } = render(<ImageEditor {...props} config={pending} workItems={[work]} />);
expect(screen.getByRole("complementary", { name: kind === "extend" ? "Zoom settings" : "Character sheet settings" })).toBeInTheDocument();
const result = { ...source, id: "result", name: "Result", relativePath: "media/result.png" };
const completed = completeImageDraft(pending, result.id, { ...result, imageGeneration: { ...generation, scene: createImageEditScene(result, generation.scene) } });
rerender(<ImageEditor {...props} config={completed} workItems={[{ ...work, status: "completed", progress: 1 }]} />);
expect(screen.getByRole("complementary", { name: "Image node inspector" })).toBeInTheDocument();
expect(screen.getByLabelText("Edit prompt")).toBeInTheDocument();
expect(screen.getByLabelText("Used seed")).toHaveValue("42");
expect(screen.queryByRole("complementary", { name: /^(Zoom|Character sheet) settings$/ })).not.toBeInTheDocument();
});
/* 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 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);
const original = { id: "original", name: "Original", kind: "image" as const, relativePath: "media/original.png", mimeType: "image/png", width: 1001, height: 809, createdAt: initial.createdAt };
initial.imageScene = createImageEditScene({ name: original.name, relativePath: original.relativePath, width: original.width, height: original.height });
initial.imageScene.nodes[0].description = "Warm up the lighting";
initial.imageScene.outputSize = { width: 672, height: 544 };
const result = { ...original, id: "edited", name: "Edited", relativePath: "media/edited.png", width: 672, height: 544, parentAssetId: original.id,
imageGeneration: { ...imageGenerationSnapshot(initial, "Compiled edit", defaultGeneratorTemplate().id), usedSeed: 42 } };
initial.assets = [original, result];
const current = setup(restoreGeneratedImage(initial, result.id));
expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("");
expect(screen.getByLabelText("Seed")).toHaveValue(-1);
expect(screen.getByLabelText("Used seed")).toHaveValue("42");
const preview = () => document.querySelector<HTMLImageElement>(".image-frame img");
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("");
fireEvent.click(screen.getByRole("button", { name: "View Edited" }));
fireEvent.click(screen.getByRole("button", { name: "View Edited" }));
expect(current().assets).toEqual([original, result]);
expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("");
typePrompt(screen.getByLabelText("Edit prompt"), "Make it moonlit");
expect(current().assets[0]).toEqual(original);
expect(current().assets[1].imageGeneration).toEqual(result.imageGeneration);
expect(current().assets[2]).toMatchObject({ imageDraft: true, parentAssetId: "original", imageGeneration: {
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("");
expect(current().assets).toHaveLength(3);
});
it("edits imported-image generation settings and restores them with the draft", () => {
const initial = parseProjectConfig(fixture);
initial.assets = [{ id: "imported", name: "Imported", kind: "image", relativePath: "media/source.png", mimeType: "image/png", width: 1001, height: 809, createdAt: initial.createdAt }];
const current = setup(initial);
fireEvent.click(screen.getByRole("button", { name: "View Imported" }));
expect(comboValue(screen.getByLabelText("Resolution"))).toBe("1024x832");
typePrompt(screen.getByLabelText("Edit prompt"), "Warm up the lighting");
fireEvent.change(screen.getByLabelText("Steps"), { target: { value: "32" } });
fireEvent.change(screen.getByLabelText("Seed"), { target: { value: "123456" } });
choose("Resolution", "672 × 544");
expect(current().imageScene).toMatchObject({ steps: 32, seed: 123456, outputSize: { width: 672, height: 544 } });
expect(compileImageEdits(current()).edits[0]).toMatchObject({ width: 1001, height: 809 });
expect(current().assets[0]).toMatchObject({ width: 1001, height: 809 });
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("1024x832");
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);
expect(comboValue(screen.getByLabelText("Resolution"))).toBe("672x544");
choose("Resolution", "1024 × 832");
expect(compileImageEdits(current()).edits[0]).toMatchObject({ width: 1001, height: 809 });
});
it.each(["media/photo.png", "references/photo.webp", "references/frames/frame.png"])("opens %s for editing after measuring its preview and preserves the original", async (relativePath) => {
vi.spyOn(persistence, "readMediaFileUrl").mockResolvedValue("blob:imported");
vi.stubGlobal("URL", class extends URL { static revokeObjectURL = vi.fn(); });
const initial = parseProjectConfig(fixture);
initial.assets = [{ id: "imported", name: "Imported", kind: "image", relativePath, mimeType: "image/png", createdAt: initial.createdAt }];
const current = setup(initial);
fireEvent.click(screen.getByRole("button", { name: "View Imported" }));
const preview = await waitFor(() => {
const element = document.querySelector<HTMLImageElement>(".image-frame img");
expect(element).not.toBeNull();
return element!;
});
Object.defineProperties(preview, { naturalWidth: { value: 640 }, naturalHeight: { value: 480 } });
fireEvent.load(preview);
expect(current().imageScene).toMatchObject({ rootType: "image", outputAssetId: "imported", sourceImage: { relativePath, width: 640, height: 480 } });
expect(current().assets).toHaveLength(1);
expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("");
typePrompt(screen.getByLabelText("Edit prompt"), "Make the sky pink");
expect(compileImageEdits(current()).edits[0]).toMatchObject({ width: 640, height: 480 });
expect(current().assets[0]).toMatchObject({ id: "imported", relativePath, width: 640, height: 480 });
expect(current().assets[0].imageGeneration).toBeUndefined();
expect(current().assets[1]).toMatchObject({ imageDraft: true, parentAssetId: "imported" });
const draftId = current().assets[1].id;
fireEvent.click(screen.getByRole("button", { name: "View Imported" }));
expect(current().imageScene?.outputAssetId).toBe("imported");
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);
expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("Make the sky pink");
expect(parseProjectConfig(JSON.parse(JSON.stringify(current()))).imageScene).toEqual(current().imageScene);
});
it.each([
["Create Scene", "bar"], ["Create Reference", "bar"],
["Create Scene", "canvas"], ["Create Reference", "canvas"],
])("%s uses the target image from the %s menu without changing the viewed image", (action, source) => {
const initial = parseProjectConfig(fixture);
initial.assets = ["Viewed", "Chosen"].map((name) => ({ id: name, name, kind: "image", relativePath: `media/generated/${name}.png`, mimeType: "image/png", createdAt: initial.createdAt }));
initial.imageScene!.outputAssetId = source === "canvas" ? "Chosen" : "Viewed";
const current = setup(initial);
fireEvent.contextMenu(source === "canvas" ? screen.getByLabelText("Image placement canvas") : screen.getByRole("button", { name: "View Chosen" }));
if (source === "canvas") {
expect(screen.queryByRole("menuitem", { name: "New empty image" })).not.toBeInTheDocument();
expect(screen.queryByRole("menuitem", { name: "Add image file" })).not.toBeInTheDocument();
expect(screen.getByRole("menuitem", { name: "Edit" })).toBeEnabled();
}
fireEvent.click(screen.getByRole("menuitem", { name: action }));
const reopened = parseProjectConfig(JSON.parse(JSON.stringify(current())));
expect(reopened.references).toHaveLength(initial.references.length + 1);
const reference = reopened.references[0];
expect(reference.name).toBe("Chosen");
expect(referenceImages(reference)[0].relativePath).toBe("media/generated/Chosen.png");
expect(reopened.imageScene).toEqual(initial.imageScene);
expect(reopened.assets).toEqual(initial.assets);
expect(reopened.timeline).toEqual(initial.timeline);
if (action === "Create Scene") {
const job = reopened.generationJobs.at(-1)!;
expect(job).toMatchObject({ title: "Chosen", status: "draft", sceneType: "first-last-frame", startFrameReferenceId: reference.id });
expect(sceneFrameInputs(job, reopened).references.map((item) => item.id)).toContain(reference.id);
} else expect(reopened.generationJobs).toEqual(initial.generationJobs);
});
it("makes the viewed variant primary and removes it from the canvas menu", () => {
const initial = parseProjectConfig(fixture);
initial.assets = [
{ id: "original", name: "Original", kind: "image", relativePath: "media/original.png", mimeType: "image/png", createdAt: initial.createdAt },
{ id: "variant", name: "Variant", parentAssetId: "original", kind: "image", relativePath: "media/variant.png", mimeType: "image/png", createdAt: initial.createdAt },
];
initial.imageScene!.outputAssetId = "variant";
const current = setup(initial);
const viewport = screen.getByLabelText("Image placement canvas").closest(".image-viewport")!;
expect(viewport).not.toHaveAttribute("data-tooltip");
fireEvent.contextMenu(viewport, { clientX: 80, clientY: 90 });
fireEvent.keyDown(window, { key: "Escape" });
expect(viewport).toHaveFocus();
fireEvent.keyDown(viewport, { key: "F10", shiftKey: true });
fireEvent.click(screen.getByRole("menuitem", { name: "Make Primary" }));
expect(current().assets.find((asset) => asset.id === "variant")?.parentAssetId).toBeUndefined();
expect(current().assets.find((asset) => asset.id === "original")?.parentAssetId).toBe("variant");
fireEvent.contextMenu(viewport);
expect(screen.getByRole("menuitem", { name: "Make Primary" })).toBeDisabled();
fireEvent.click(screen.getByRole("menuitem", { name: "Remove" }));
expect(current().assets.map((asset) => asset.id)).toEqual(["original"]);
expect(current().imageScene!.outputAssetId).toBe("original");
});
it("opens no canvas menu without an image and disables reuse for empty drafts", () => {
setup();
const viewport = screen.getByLabelText("Image placement canvas").closest(".image-viewport")!;
fireEvent.contextMenu(viewport);
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
fireEvent.contextMenu(screen.getByLabelText("Generated images"));
fireEvent.click(screen.getByRole("menuitem", { name: "New empty image" }));
fireEvent.contextMenu(viewport);
expect(screen.getByRole("menuitem", { name: "Create Scene" })).toBeDisabled();
expect(screen.getByRole("menuitem", { name: "Create Reference" })).toBeDisabled();
expect(screen.getByRole("menuitem", { name: "Remove" })).toBeEnabled();
});
it("creates a reference from an external image variant using the keyboard menu", () => {
const initial = parseProjectConfig(fixture);
initial.assets = [
{ id: "original", name: "Original", kind: "image", relativePath: "media/original.png", mimeType: "image/png", createdAt: initial.createdAt },
{ id: "variant", name: "Variant", parentAssetId: "original", kind: "image", sourcePath: "D:/Pictures/variant.png", mimeType: "image/png", createdAt: initial.createdAt },
];
initial.imageScene!.outputAssetId = "original";
const current = setup(initial);
fireEvent.keyDown(screen.getByRole("button", { name: "View Variant" }), { key: "F10", shiftKey: true });
fireEvent.click(screen.getByRole("menuitem", { name: "Create Reference" }));
const reopened = parseProjectConfig(JSON.parse(JSON.stringify(current())));
expect(referenceImages(reopened.references[0])[0]).toMatchObject({ name: "Variant", sourcePath: "D:/Pictures/variant.png" });
});
it("disables image reuse for empty drafts and omits it on the empty bar", () => {
setup();
fireEvent.contextMenu(screen.getByLabelText("Generated images"));
expect(screen.queryByRole("menuitem", { name: "Create Scene" })).not.toBeInTheDocument();
expect(screen.queryByRole("menuitem", { name: "Create Reference" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("menuitem", { name: "New empty image" }));
fireEvent.contextMenu(screen.getByRole("button", { name: "View New image" }));
expect(screen.getByRole("menuitem", { name: "Create Scene" })).toBeDisabled();
expect(screen.getByRole("menuitem", { name: "Create Reference" })).toBeDisabled();
});
it.each([false, true])("shows and copies the selected result's exact seed as read-only (image edits: %s)", async (imageRoot) => {
const writeText = vi.fn().mockResolvedValue(undefined);
vi.stubGlobal("navigator", Object.assign(Object.create(navigator), { clipboard: { writeText } }));
const initial = parseProjectConfig(fixture);
if (imageRoot) initial.imageScene = createImageEditScene({ relativePath: "media/source.png", name: "Source", width: 768, height: 768 });
initial.assets = [Number.MAX_SAFE_INTEGER, 0].map((usedSeed, index) => ({
id: `seed-result-${index}`, name: `Seed result ${index}`, kind: "image", relativePath: `media/result-${index}.png`,
width: 768, height: 768, mimeType: "image/png", createdAt: initial.createdAt,
imageGeneration: { ...imageGenerationSnapshot(initial, "Submitted prompt", defaultGeneratorTemplate().id), usedSeed },
}));
initial.imageScene!.outputAssetId = "seed-result-0";
const current = setup(initial);
const seed = screen.getByLabelText("Used seed");
expect(seed).toHaveValue(String(Number.MAX_SAFE_INTEGER));
expect(seed).toHaveAttribute("readonly");
expect(seed).not.toBeDisabled();
fireEvent.click(screen.getByRole("button", { name: "Copy used seed" }));
await waitFor(() => expect(writeText).toHaveBeenLastCalledWith(String(Number.MAX_SAFE_INTEGER)));
fireEvent.click(screen.getByRole("button", { name: "View Seed result 1" }));
expect(screen.getByLabelText("Used seed")).toHaveValue("0");
fireEvent.click(screen.getByRole("button", { name: "Copy used seed" }));
await waitFor(() => expect(writeText).toHaveBeenLastCalledWith("0"));
expect(current().assets.map((asset) => asset.imageGeneration?.usedSeed)).toEqual([Number.MAX_SAFE_INTEGER, 0]);
writeText.mockRejectedValueOnce(new Error("Clipboard unavailable"));
fireEvent.click(screen.getByRole("button", { name: "Copy used seed" }));
await screen.findByText("Could not copy the seed. Select and copy it from the field.");
});
it("does not invent a used seed for an older random result or show one for drafts", () => {
const initial = parseProjectConfig(fixture);
initial.imageScene!.seed = -1;
const snapshot = imageGenerationSnapshot(initial, "Old prompt", defaultGeneratorTemplate().id);
initial.assets = [false, true].map((imageDraft, index) => ({ id: `old-${index}`, name: `Old ${index}`, kind: "image", imageDraft,
relativePath: `media/old-${index}.jpg`, mimeType: "image/jpeg", createdAt: initial.createdAt, imageGeneration: snapshot }));
initial.imageScene!.outputAssetId = "old-0";
setup(initial);
expect(screen.getByLabelText("Used seed")).toHaveValue("Not recorded");
expect(screen.getByRole("button", { name: "Copy used seed" })).toBeDisabled();
fireEvent.click(screen.getByRole("button", { name: "View Old 1" }));
expect(screen.queryByLabelText("Used seed")).not.toBeInTheDocument();
});
it("hides placement and palette controls by model type while preserving boxes and palettes", () => {
const h3 = createGeneratorTemplate("Renamed H3");
const future = createGeneratorTemplate("Future generator", "future-model");
saveGeneratorTemplateSettings({ templates: [h3, future], defaultTemplateId: h3.id, catalogVersion: 17 });
const current = setup();
const before = structuredClone(current().imageScene!.nodes);
expect(screen.queryByText("Color palette")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Title" }));
expect(screen.queryByText("Placement (0–1000)")).not.toBeInTheDocument();
expect(screen.queryByText("Color palette")).not.toBeInTheDocument();
expect(screen.queryByLabelText("Explicit placement")).not.toBeInTheDocument();
expect(screen.getByRole("radio", { name: "Draw object" })).toBeDisabled();
expect(screen.getByLabelText("Image placement canvas").querySelectorAll("rect[data-node]").length).toBeGreaterThan(0);
choose("Generator", "Future generator");
expect(screen.getByText("Placement (0–1000)")).toBeInTheDocument();
expect(screen.getByText("Color palette")).toBeInTheDocument();
choose("Generator", "Renamed H3");
expect(screen.queryByText("Placement (0–1000)")).not.toBeInTheDocument();
expect(screen.queryByText("Color palette")).not.toBeInTheDocument();
expect(current().imageScene!.nodes).toEqual(before);
});
it("adds image files in edit mode and saves whole-image and drawn edits with separate references", async () => {
vi.spyOn(persistence, "isTauri").mockReturnValue(true);
vi.spyOn(persistence, "readMediaFileUrl").mockResolvedValue(null);
const initial = parseProjectConfig(fixture);
initial.references = ["Mood", "Balloon"].map((name) => ({ id: name, name, kind: "text", description: name, intendedUse: [], createdAt: initial.createdAt }));
const current = setup(initial);
const addFile = () => {
fireEvent.contextMenu(screen.getByLabelText("Generated images"));
fireEvent.click(screen.getByRole("menuitem", { name: "Add image file" }));
};
vi.mocked(invoke).mockResolvedValueOnce(null);
addFile();
await waitFor(() => expect(invoke).toHaveBeenCalledWith("open_image_source", { folderPath: "D:/Images" }));
expect(current().imageScene).toEqual(initial.imageScene);
const source = { name: "Imported", relativePath: "media/imported/source.png", width: 1000, height: 800 };
vi.mocked(invoke).mockResolvedValueOnce(source);
addFile();
await waitFor(() => expect(current().imageScene?.sourceImage).toEqual(source));
const original = current().assets.find((asset) => !asset.imageDraft && asset.relativePath === source.relativePath)!;
expect(original).toMatchObject(source);
expect(current().assets.find((asset) => asset.imageDraft)?.parentAssetId).toBe(original.id);
expect(screen.queryByRole("combobox", { name: "Type" })).not.toBeInTheDocument();
// References come from what each prompt cites; there is no list to tick.
expect(screen.queryByRole("checkbox", { name: "Mood" })).not.toBeInTheDocument();
typePrompt(screen.getByLabelText("Edit prompt"), "Make the lighting warmer like @[ref:Mood]");
expect(compileImageEdits(current()).edits[0]).toMatchObject({ x: 0, y: 0, width: 1000, height: 800 });
const canvas = screen.getByLabelText("Image placement canvas");
Object.defineProperty(canvas, "setPointerCapture", { value: vi.fn() });
Object.defineProperty(canvas, "getBoundingClientRect", { value: () => ({ left: 0, top: 0, width: 1000, height: 800 }) });
const pointer = (type: "pointerDown" | "pointerMove" | "pointerUp", x: number, y: number) => {
const event = createEvent[type](canvas);
Object.defineProperties(event, { button: { value: 0 }, buttons: { value: type === "pointerUp" ? 0 : 1 }, pointerId: { value: 1 }, clientX: { value: x }, clientY: { value: y } });
fireEvent(canvas, event);
};
for (const key of ["o", "t", "g"]) fireEvent.keyDown(canvas, { key });
expect(screen.getByRole("radio", { name: "Select" })).toHaveAttribute("aria-checked", "true");
fireEvent.keyDown(canvas, { key: "e" });
expect(screen.getByRole("radio", { name: "Edit Box" })).toHaveAttribute("aria-checked", "true");
pointer("pointerDown", 100, 80); pointer("pointerMove", 400, 320); pointer("pointerUp", 400, 320);
expect(current().imageScene!.nodes[1]).toMatchObject({ name: "Edit", box: { x: 100, y: 100, width: 300, height: 300 } });
expect(screen.queryByText("Placement (0–1000)")).not.toBeInTheDocument();
expect(screen.queryByText("Color palette")).not.toBeInTheDocument();
expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("");
typePrompt(screen.getByLabelText("Edit prompt"), "Add a red @[ref:Balloon]");
const edits = compileImageEdits(current()).edits;
expect(edits.map((edit) => edit.references.map((reference) => reference.id))).toEqual([["Mood"], ["Balloon"]]);
const reopened = parseProjectConfig(JSON.parse(JSON.stringify(current())));
expect(reopened.imageScene).toEqual(current().imageScene);
expect(reopened.assets.at(-1)!.imageGeneration!.references.map((reference) => reference.id)).toEqual(["Mood", "Balloon"]);
fireEvent.contextMenu(screen.getByLabelText("Generated images"));
fireEvent.click(screen.getByRole("menuitem", { name: "New empty image" }));
fireEvent.click(screen.getByRole("button", { name: "View Editing Imported" }));
expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("Make the lighting warmer like @[ref:Mood]");
fireEvent.click(screen.getByRole("button", { name: "Edit" }));
expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("Add a red @[ref:Balloon]");
expect(screen.getByRole("button", { name: "Reference Balloon" })).toHaveClass("prompt-chip");
const beforeFailure = current();
vi.mocked(invoke).mockRejectedValueOnce(new Error("Image file is unreadable"));
addFile();
expect(await screen.findByText(/Image file is unreadable/)).toBeInTheDocument();
expect(current()).toEqual(beforeFailure);
});
it("starts an image root from the thumbnail Edit menu with edit tools and no type selector", () => {
const initial = parseProjectConfig(fixture);
initial.assets = [{ id: "saved", name: "Saved", kind: "image", relativePath: "media/generated/saved.jpg", mimeType: "image/jpeg", width: 101, height: 77, createdAt: initial.createdAt }];
const current = setup(initial);
fireEvent.contextMenu(screen.getByRole("button", { name: "View Saved" }));
fireEvent.click(screen.getByRole("menuitem", { name: "Edit" }));
expect(current().imageScene).toMatchObject({ rootType: "image", sourceImage: { relativePath: "media/generated/saved.jpg", width: 101, height: 77 }, outputAssetId: expect.stringMatching(/^image-draft-/) });
expect(current().imageScene!.nodes).toHaveLength(1);
expect(screen.queryByLabelText("Prompt (high-level description)")).not.toBeInTheDocument();
expect(screen.queryByRole("combobox", { name: "Type" })).not.toBeInTheDocument();
expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("");
expect(within(screen.getByRole("radiogroup", { name: "Canvas tool" })).getAllByRole("radio").map((tool) => tool.getAttribute("aria-label"))).toEqual(["Select", "Edit Box", "Lasso"]);
const draft = screen.getByRole("button", { name: "View Editing Saved" });
expect(draft).toHaveAttribute("aria-pressed", "true");
fireEvent.contextMenu(screen.getByRole("button", { name: "Image" }));
expect(screen.getAllByRole("menuitem").filter((item) => item.textContent?.startsWith("New ")).map((item) => item.textContent)).toEqual(["New Edit"]);
fireEvent.click(screen.getByRole("menuitem", { name: "New Edit" }));
typePrompt(screen.getByLabelText("Edit prompt"), "A red balloon");
fireEvent.click(screen.getByRole("button", { name: "View Saved" }));
expect(draft).toHaveAttribute("aria-pressed", "false");
fireEvent.click(draft);
expect(current().imageScene!.nodes[1].description).toBe("A red balloon");
expect(current().assets.filter((asset) => asset.imageDraft)).toHaveLength(1);
expect(parseProjectConfig(JSON.parse(JSON.stringify(current()))).assets).toEqual(current().assets);
expect(screen.getByLabelText("Image placement canvas").parentElement!.style.getPropertyValue("--image-ratio")).toBe(String(101 / 77));
fireEvent.contextMenu(screen.getByLabelText("Generated images"));
fireEvent.click(screen.getByRole("menuitem", { name: "New empty image" }));
expect(screen.getByLabelText("Prompt (high-level description)")).toBeInTheDocument();
expect(screen.getByRole("radio", { name: "Draw object" })).toBeInTheDocument();
// The empty image stays in Saved's family alongside the edit.
expect(screen.getByRole("button", { name: "Back to all images" })).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "View Editing Saved" }));
expect(current().imageScene!.sourceImage?.name).toBe("Saved");
});
it.each([false, true])("retains a renamed image root after switching images and reopening (draft: %s)", (imageDraft) => {
const initial = parseProjectConfig(fixture);
const snapshot = imageGenerationSnapshot(initial, imageDraft ? "" : "Original prompt", defaultGeneratorTemplate().id);
initial.assets = ["First", "Second"].map((name) => ({ id: name, name, kind: "image", imageDraft,
relativePath: `media/generated/${name}.jpg`, mimeType: "image/jpeg", createdAt: initial.createdAt,
imageGeneration: structuredClone(snapshot) }));
initial.imageScene!.outputAssetId = "First";
const current = setup(initial);
fireEvent.change(screen.getByRole("textbox", { name: "Name" }), { target: { value: "Cover image" } });
fireEvent.click(screen.getByRole("button", { name: "View Second" }));
expect(screen.getByRole("textbox", { name: "Name" })).toHaveValue(snapshot.scene.nodes[0].name);
fireEvent.click(screen.getByRole("button", { name: "View First" }));
expect(screen.getByRole("textbox", { name: "Name" })).toHaveValue("Cover image");
const reopened = parseProjectConfig(JSON.parse(JSON.stringify(current())));
expect(restoreGeneratedImage(reopened, "First").imageScene!.nodes[0].name).toBe("Cover image");
expect(reopened.assets).toHaveLength(2);
expect(reopened.assets[0].imageGeneration).toEqual({ ...snapshot,
scene: { ...snapshot.scene, nodes: snapshot.scene.nodes.map((node) => node.kind === "root" ? { ...node, name: "Cover image" } : node) } });
});
it("restores saved image settings while keeping the active generator until explicitly changed", () => {
const initial = parseProjectConfig(fixture);
const original = imageGenerationSnapshot(initial, "Original prompt", defaultGeneratorTemplate().id);
const saved = imageGenerationSnapshotSchema.parse(snapshotFixture);
saveGeneratorTemplateSettings({ defaultTemplateId: original.generatorTemplateId, templates: [defaultGeneratorTemplate(), { ...defaultGeneratorTemplate(), id: saved.generatorTemplateId, name: "Lantern generator" }] });
initial.assets = [original, saved].map((snapshot, index) => ({ id: `result-${index}`, name: `Result ${index}`, kind: "image", relativePath: `media/generated/result-${index}.jpg`, mimeType: "image/jpeg", createdAt: initial.createdAt, imageGeneration: snapshot }));
initial.imageScene!.outputAssetId = "result-0";
const current = setup(initial);
typePrompt(screen.getByLabelText("Prompt (high-level description)"), "Unsaved edit");
fireEvent.click(screen.getByRole("button", { name: "View Result 1" }));
expect(promptValue(screen.getByLabelText("Prompt (high-level description)"))).toBe(saved.scene.nodes[0].description);
expect(screen.getByLabelText("Steps")).toHaveValue(30);
expect(comboValue(screen.getByRole("combobox", { name: "Generator" }))).toBe(original.generatorTemplateId);
expect(screen.getByLabelText("Used generator")).toHaveValue("Lantern generator");
expect(screen.getByRole("button", { name: "Lantern" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Lettering" })).toBeInTheDocument();
expect(current().references).toEqual(saved.references);
expect(current().imageSettings).toMatchObject({ resolution: "1088p", aspectRatio: "4:5" });
// Viewing a result starts a fresh history: Ctrl+Z has nothing to undo.
undoImageEdit();
expect(promptValue(screen.getByLabelText("Prompt (high-level description)"))).toBe(saved.scene.nodes[0].description);
typePrompt(screen.getByLabelText("Prompt (high-level description)"), "Another edit");
fireEvent.click(screen.getByRole("button", { name: "View Result 0" }));
expect(current().imageScene).toEqual({ ...original.scene, outputAssetId: "result-0" });
expect(comboValue(screen.getByRole("combobox", { name: "Generator" }))).toBe(original.generatorTemplateId);
fireEvent.click(screen.getByRole("button", { name: "View Result 1" }));
expect(current().imageScene).toEqual({ ...saved.scene, outputAssetId: "result-1" });
expect(current().assets[1].imageGeneration).toEqual(saved);
fireEvent.click(screen.getByRole("button", { name: "Use this generator" }));
expect(comboValue(screen.getByRole("combobox", { name: "Generator" }))).toBe(saved.generatorTemplateId);
expect(current().imageScene).toEqual({ ...saved.scene, outputAssetId: "result-1" });
expect(current().settings).toEqual(initial.settings);
expect(current().brief.resolution).toBe(initial.brief.resolution);
expect(current().brief.aspectRatio).toBe(initial.brief.aspectRatio);
});
it("displays each generated image at its saved aspect ratio independently of future generation settings", () => {
const initial = parseProjectConfig(fixture);
initial.assets = [
{ id: "wide", name: "Wide", kind: "image", relativePath: "media/generated/wide.jpg", mimeType: "image/jpeg", width: 1376, height: 768, createdAt: initial.createdAt },
{ id: "tall", name: "Tall", kind: "image", relativePath: "media/generated/tall.jpg", mimeType: "image/jpeg", width: 1088, height: 1920, createdAt: initial.createdAt },
];
initial.imageScene!.outputAssetId = "wide";
const current = setup(initial);
const frame = screen.getByLabelText("Image placement canvas").parentElement!;
expect(frame.style.getPropertyValue("--image-ratio")).toBe(String(1376 / 768));
choose("Resolution", "2720 × 1536");
expect(current().imageSettings?.resolution).toBe("1536p");
expect(current().settings).toEqual(initial.settings);
expect(current().brief).toEqual(initial.brief);
choose("Resolution", "3648 × 2048");
choose("Aspect ratio", "1:1");
expect(current().imageSettings).toMatchObject({ resolution: "2048p", aspectRatio: "1:1" });
expect(frame.style.getPropertyValue("--image-ratio")).toBe(String(1376 / 768));
fireEvent.click(screen.getByRole("button", { name: "View Tall" }));
expect(frame.style.getPropertyValue("--image-ratio")).toBe(String(1088 / 1920));
fireEvent.click(screen.getByRole("button", { name: "View Wide" }));
expect(frame.style.getPropertyValue("--image-ratio")).toBe(String(1376 / 768));
const reopened = parseProjectConfig(JSON.parse(JSON.stringify(current())));
expect(reopened.assets).toEqual(initial.assets);
expect(reopened.settings).toEqual(initial.settings);
expect(reopened.brief).toEqual(initial.brief);
expect(reopened.imageSettings).toMatchObject({ resolution: "2048p", aspectRatio: "1:1" });
});
it("removes generated images through their context menu and keeps the preview and thumbnail valid", () => {
const initial = parseProjectConfig(fixture);
initial.assets = ["First", "Second", "Third"].map((name) => ({ id: name, name, kind: "image", relativePath: `media/generated/${name}.jpg`, mimeType: "image/jpeg", createdAt: initial.createdAt }));
initial.imageScene!.outputAssetId = "Second";
initial.thumbnail = "media/generated/Second.jpg";
const current = setup(initial);
const first = screen.getByRole("button", { name: "View First" });
fireEvent.contextMenu(first, { clientX: 80, clientY: 90 });
expect(screen.getByRole("menu", { name: "Generated image actions" })).toBeInTheDocument();
expect(current().imageScene!.outputAssetId).toBe("Second");
fireEvent.keyDown(window, { key: "Escape" });
expect(first).toHaveFocus();
expect(current().assets).toHaveLength(3);
fireEvent.keyDown(first, { key: "F10", shiftKey: true });
fireEvent.click(screen.getByRole("menuitem", { name: "Remove" }));
expect(screen.queryByRole("button", { name: "View First" })).not.toBeInTheDocument();
expect(current().imageScene!.outputAssetId).toBe("Second");
expect(current().thumbnail).toBe("media/generated/Second.jpg");
fireEvent.contextMenu(screen.getByRole("button", { name: "View Second" }));
fireEvent.click(screen.getByRole("menuitem", { name: "Remove" }));
expect(current().imageScene!.outputAssetId).toBe("Third");
expect(current().thumbnail).toBe("media/generated/Third.jpg");
expect(screen.getByRole("button", { name: "View Third" })).toHaveAttribute("aria-pressed", "true");
fireEvent.contextMenu(screen.getByRole("button", { name: "View Third" }));
fireEvent.click(screen.getByRole("menuitem", { name: "Remove" }));
expect(current().assets).toHaveLength(0);
expect(current().imageScene!.outputAssetId).toBeNull();
expect(current().imageScene!.sourceImage).toBeFalsy();
expect(current().thumbnail).toBeNull();
expect(within(screen.getByLabelText("Generated images")).queryByRole("button")).not.toBeInTheDocument();
expect(screen.getByText("Compose your image")).toBeInTheDocument();
expect(parseProjectConfig(JSON.parse(JSON.stringify(current()))).imageScene).toEqual(current().imageScene);
});
it("clears the source when removing the last image opened for editing", () => {
const initial = parseProjectConfig(fixture);
initial.assets = [{ id: "only", kind: "image", name: "Only", relativePath: "media/generated/only.png", mimeType: "image/png", width: 640, height: 480, createdAt: initial.createdAt }];
const current = setup(restoreGeneratedImage(initial, "only"));
expect(current().imageScene?.sourceImage?.relativePath).toBe("media/generated/only.png");
fireEvent.contextMenu(screen.getByRole("button", { name: "View Only" }));
fireEvent.click(screen.getByRole("menuitem", { name: "Remove" }));
expect(current().assets).toHaveLength(0);
expect(current().imageScene?.sourceImage).toBeNull();
expect(saveImageDraft(current()).assets).toHaveLength(0);
});
it("creates a blank draft from the image bar and preserves it while browsing", () => {
const initial = parseProjectConfig(fixture);
initial.assets = [{ id: "saved", name: "Saved", kind: "image", relativePath: "media/generated/saved.jpg", mimeType: "image/jpeg", width: 101, height: 77, createdAt: initial.createdAt }];
const current = setup(initial);
fireEvent.contextMenu(screen.getByRole("button", { name: "View Saved" }));
fireEvent.click(screen.getByRole("menuitem", { name: "New empty image" }));
expect(screen.queryByRole("combobox", { name: "Type" })).not.toBeInTheDocument();
expect(promptValue(screen.getByLabelText("Prompt (high-level description)"))).toBe("");
expect(current().imageScene!.nodes).toHaveLength(1);
expect(screen.getByRole("button", { name: "View New image" })).toHaveAttribute("aria-pressed", "true");
typePrompt(screen.getByLabelText("Prompt (high-level description)"), "A green forest");
fireEvent.click(screen.getByRole("button", { name: "View Saved" }));
fireEvent.click(screen.getByRole("button", { name: "View New image" }));
expect(promptValue(screen.getByLabelText("Prompt (high-level description)"))).toBe("A green forest");
expect(parseProjectConfig(JSON.parse(JSON.stringify(current()))).assets).toEqual(current().assets);
fireEvent.contextMenu(screen.getByLabelText("Generated images"));
expect(screen.queryByRole("menuitem", { name: "Remove" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("menuitem", { name: "New empty image" }));
expect(current().assets).toHaveLength(3);
expect(promptValue(screen.getByLabelText("Prompt (high-level description)"))).toBe("");
});
it("creates an image from the empty bar's keyboard context menu", () => {
const current = setup();
fireEvent.keyDown(screen.getByLabelText("Generated images"), { key: "F10", shiftKey: true });
fireEvent.click(screen.getByRole("menuitem", { name: "New empty image" }));
expect(current().assets).toHaveLength(1);
expect(current().assets[0]).toMatchObject({ name: "New image", imageDraft: true });
});
it("edits ordered style tokens with suggestions, custom tags, removal, undo, and mode-specific choices", () => {
const current = setup();
expect(screen.getByRole("button", { name: "Aesthetics tag: Minimal poster" })).toBeInTheDocument();
const aesthetics = screen.getByRole("combobox", { name: "Add Aesthetics tag" });
fireEvent.focus(aesthetics);
const list = () => within(screen.getByRole("listbox", { name: "Aesthetics suggestions" }));
expect(list().getByRole("option", { name: "whimsical" })).toBeInTheDocument();
fireEvent.change(aesthetics, { target: { value: "vibr" } });
fireEvent.click(list().getByRole("option", { name: "vibrant" }));
fireEvent.change(aesthetics, { target: { value: "vibr" } });
expect(screen.queryByRole("option", { name: "vibrant" })).not.toBeInTheDocument();
fireEvent.change(aesthetics, { target: { value: " intricate" } });
fireEvent.keyDown(aesthetics, { key: "Enter" });
fireEvent.change(aesthetics, { target: { value: "custom finish, " } });
expect(current().imageScene!.style.aesthetics).toBe("Minimal poster, vibrant, intricate, custom finish");
expect(aesthetics).toHaveValue("");
fireEvent.keyDown(aesthetics, { key: "Escape" });
expect(screen.queryByRole("listbox")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Remove vibrant from Aesthetics" }));
fireEvent.keyDown(screen.getByRole("button", { name: "Aesthetics tag: intricate" }), { key: "ArrowLeft", altKey: true });
expect(current().imageScene!.style.aesthetics).toBe("intricate, Minimal poster, custom finish");
undoImageEdit();
expect(current().imageScene!.style.aesthetics).toBe("Minimal poster, intricate, custom finish");
choose("Mode", "Photo");
const lighting = screen.getByRole("combobox", { name: "Add Lighting tag" });
fireEvent.change(lighting, { target: { value: "golden" } });
fireEvent.keyDown(lighting, { key: "ArrowDown" });
fireEvent.keyDown(lighting, { key: "Enter" });
const camera = screen.getByRole("combobox", { name: "Add Camera / lens tag" });
fireEvent.change(camera, { target: { value: "35mm" } });
fireEvent.click(screen.getByRole("option", { name: "35mm" }));
expect(imageScenePrompt(current().imageScene!)).toContain("A still photograph with Minimal poster, intricate, custom finish aesthetics, Sunrise, golden hour lighting, Screen print, 35mm camera and lens characteristics.");
fireEvent.blur(camera);
fireEvent.focus(aesthetics);
expect(screen.getByRole("option", { name: "photorealistic" })).toBeInTheDocument();
expect(screen.queryByRole("option", { name: "whimsical" })).not.toBeInTheDocument();
fireEvent.keyDown(aesthetics, { key: "Backspace" });
expect(current().imageScene!.style.aesthetics).toBe("Minimal poster, intricate");
choose("Mode", "None");
expect(comboValue(screen.getByRole("combobox", { name: "Mode" }))).toBe("none");
expect(screen.queryByRole("combobox", { name: "Add Aesthetics tag" })).not.toBeInTheDocument();
expect(imageScenePrompt(current().imageScene!)).not.toMatch(/still photograph|Minimal poster|golden hour|Screen print/);
expect(parseProjectConfig(JSON.parse(JSON.stringify(current()))).imageScene).toEqual(current().imageScene);
});
it("drags whole hierarchy branches to nest or reorder, preserves placement, and rejects cycles", () => {
const initial = parseProjectConfig(fixture);
const scene = initial.imageScene!;
scene.nodes.push({ ...scene.nodes[1], id: "cloud", name: "Cloud", parentId: "image-root" });
scene.nodes.push({ ...scene.nodes[2], id: "cloud-detail", name: "Cloud detail", parentId: "cloud" });
const current = setup(initial);
const row = (name: string) => screen.getByRole("button", { name }).closest<HTMLDivElement>(".image-tree__row")!;
const transfer = { setData: vi.fn(), effectAllowed: "", dropEffect: "" };
const drop = (source: string, target: string, y = 50) => {
fireEvent.dragStart(row(source), { dataTransfer: transfer });
const destination = row(target);
vi.spyOn(destination, "getBoundingClientRect").mockReturnValue({ top: 0, height: 100 } as DOMRect);
for (const type of ["dragOver", "drop"] as const) {
const event = createEvent[type](destination, { dataTransfer: transfer });
Object.defineProperty(event, "clientY", { value: y });
fireEvent(destination, event);
}
};
fireEvent.click(screen.getByRole("button", { name: "Collapse Cloud" }));
drop("Rocket", "Cloud");
expect(current().imageScene!.nodes.find((node) => node.id === "group-rocket")?.parentId).toBe("cloud");
expect(current().imageScene!.nodes.find((node) => node.id === "title")).toEqual(scene.nodes[2]);
expect(screen.getByRole("button", { name: "Collapse Cloud" })).toBeInTheDocument();
expect(screen.queryByLabelText("Parent")).not.toBeInTheDocument();
const nested = current().imageScene;
drop("Cloud", "Title");
expect(current().imageScene).toBe(nested);
drop("Rocket", "Rocket");
expect(current().imageScene).toBe(nested);
undoImageEdit();
expect(current().imageScene).toEqual(scene);
drop("Rocket", "Cloud", 99);
expect(current().imageScene!.nodes.filter((node) => node.parentId === "image-root").map((node) => node.id)).toEqual(["cloud", "group-rocket"]);
drop("Rocket", "Cloud", 1);
expect(current().imageScene!.nodes.filter((node) => node.parentId === "image-root").map((node) => node.id)).toEqual(["group-rocket", "cloud"]);
expect(row("Image")).toHaveAttribute("draggable", "false");
expect(current().imageScene!.nodes.find((node) => node.id === "group-rocket")?.box).toEqual(scene.nodes[1].box);
expect(parseProjectConfig(JSON.parse(JSON.stringify(current()))).imageScene).toEqual(current().imageScene);
});
it("uses the context menu for creation, inline rename, and independent subtree copy/paste", () => {
enableCompositionTools();
const current = setup();
const open = (name: string) => fireEvent.contextMenu(screen.getByRole("button", { name }));
const action = (name: string) => fireEvent.click(screen.getByRole("menuitem", { name: new RegExp(`^${name}(?:$| )`) }));
const panel = within(screen.getByRole("complementary", { name: "Image hierarchy" }));
expect(panel.queryByRole("button", { name: "Object" })).not.toBeInTheDocument();
expect(panel.queryByRole("button", { name: "Duplicate" })).not.toBeInTheDocument();
open("Image");
expect(screen.getByRole("menuitem", { name: /^Copy/ })).toBeDisabled();
expect(screen.getByRole("menuitem", { name: /^Delete/ })).toBeDisabled();
expect(screen.getByRole("menuitem", { name: /^Paste/ })).toBeDisabled();
fireEvent.keyDown(window, { key: "Escape" });
open("Rocket");
expect(screen.getByLabelText("Name")).toHaveValue("Rocket");
action("Copy");
actionAfterOpen("Rocket", "Rename");
const rename = screen.getByRole("textbox", { name: "Rename image node" });
expect(rename).toHaveFocus();
fireEvent.change(rename, { target: { value: "Launch vehicle" } });
fireEvent.keyDown(rename, { key: "Enter" });
expect(current().imageScene!.nodes.find((node) => node.id === "group-rocket")?.name).toBe("Launch vehicle");
actionAfterOpen("Image", "Paste");
const pasted = current().imageScene!.nodes.find((node) => node.name === "Rocket")!;
expect(pasted.id).not.toBe("group-rocket");
expect(pasted.parentId).toBe("image-root");
const child = current().imageScene!.nodes.find((node) => node.parentId === pasted.id)!;
expect(child.id).not.toBe("title");
expect(child.text).toBe("LIFT OFF");
expect(child.box).toEqual(fixture.imageScene.nodes[2].box);
actionAfterOpen("Rocket", "Delete");
expect(current().imageScene!.nodes.some((node) => node.id === child.id)).toBe(false);
undoImageEdit();
expect(current().imageScene!.nodes.some((node) => node.id === child.id)).toBe(true);
actionAfterOpen("Launch vehicle", "New Text");
const text = current().imageScene!.nodes.at(-1)!;
expect(text.parentId).toBe("group-rocket");
actionAfterOpen("Text", "New Object");
expect(current().imageScene!.nodes.at(-1)?.parentId).toBe("group-rocket");
expect(parseProjectConfig(JSON.parse(JSON.stringify(current()))).imageScene).toEqual(current().imageScene);
function actionAfterOpen(node: string, name: string) { open(node); action(name); }
});
it("supports menu keyboard navigation and tree shortcuts without intercepting name editing", () => {
enableCompositionTools();
const current = setup();
const rocket = screen.getByRole("button", { name: "Rocket" });
fireEvent.click(rocket);
fireEvent.keyDown(rocket, { key: "F10", shiftKey: true });
const first = screen.getByRole("menuitem", { name: "New Object" });
expect(first).toHaveFocus();
fireEvent.keyDown(first, { key: "End" });
expect(screen.getByRole("menuitem", { name: /^Delete/ })).toHaveFocus();
fireEvent.keyDown(window, { key: "Escape" });
expect(rocket).toHaveFocus();
fireEvent.keyDown(rocket, { key: "c", ctrlKey: true });
fireEvent.keyDown(rocket, { key: "F2" });
const rename = screen.getByRole("textbox", { name: "Rename image node" });
fireEvent.change(rename, { target: { value: "Discard this" } });
fireEvent.keyDown(rename, { key: "Delete" });
expect(current().imageScene!.nodes).toHaveLength(3);
fireEvent.keyDown(rename, { key: "Escape" });
expect(current().imageScene!.nodes[1].name).toBe("Rocket");
fireEvent.click(screen.getByRole("button", { name: "Title" }));
fireEvent.keyDown(screen.getByRole("button", { name: "Title" }), { key: "v", ctrlKey: true });
const pasted = current().imageScene!.nodes.at(-2)!;
expect(pasted.parentId).toBe("group-rocket");
expect(current().imageScene!.nodes).toHaveLength(5);
fireEvent.contextMenu(screen.getByRole("tree", { name: "Image nodes" }));
fireEvent.click(screen.getByRole("menuitem", { name: "New Group" }));
expect(current().imageScene!.nodes.at(-1)).toMatchObject({ kind: "group", parentId: "image-root" });
});
it("walks the tree with arrow keys as a single tab stop and duplicates with Ctrl+D", () => {
enableCompositionTools();
const current = setup();
const image = screen.getByRole("button", { name: "Image" });
expect(image).toHaveAttribute("tabindex", "0");
expect(screen.getByRole("button", { name: "Rocket" })).toHaveAttribute("tabindex", "-1");
fireEvent.keyDown(image, { key: "ArrowDown" });
expect(screen.getByRole("button", { name: "Rocket" })).toHaveAttribute("tabindex", "0");
fireEvent.keyDown(screen.getByRole("button", { name: "Rocket" }), { key: "ArrowLeft" });
expect(screen.queryByRole("button", { name: "Title" })).not.toBeInTheDocument();
fireEvent.keyDown(screen.getByRole("button", { name: "Rocket" }), { key: "ArrowRight" });
fireEvent.keyDown(screen.getByRole("button", { name: "Rocket" }), { key: "ArrowRight" });
expect(screen.getByRole("button", { name: "Title" })).toHaveAttribute("tabindex", "0");
fireEvent.keyDown(screen.getByRole("button", { name: "Title" }), { key: "d", ctrlKey: true });
expect(current().imageScene!.nodes.map((node) => node.name)).toContain("Title copy");
expect(screen.getByRole("button", { name: "Title copy" })).toHaveAttribute("tabindex", "0");
fireEvent.keyDown(screen.getByRole("button", { name: "Title copy" }), { key: "Home" });
expect(screen.getByRole("button", { name: "Image" })).toHaveAttribute("tabindex", "0");
});
it("deletes a box selected on the canvas, supports undo, and leaves text editing alone", () => {
const current = setup();
const original = current().imageScene!;
const canvas = screen.getByLabelText("Image placement canvas");
const viewport = canvas.closest(".image-viewport")!;
Object.defineProperty(canvas, "setPointerCapture", { value: vi.fn() });
const selectBox = (id: string) => {
const box = canvas.querySelector(`[data-node="${id}"]`)!;
const event = createEvent.pointerDown(box);
Object.defineProperties(event, { button: { value: 0 }, clientX: { value: 100 }, clientY: { value: 100 }, pointerId: { value: 1 } });
fireEvent(box, event);
const up = createEvent.pointerUp(canvas);
Object.defineProperty(up, "pointerId", { value: 1 });
fireEvent(canvas, up);
};
screen.getByLabelText("Prompt (high-level description)").focus();
selectBox("title");
expect(viewport).toHaveFocus();
const description = screen.getByLabelText("Description");
description.focus();
fireEvent.keyDown(description, { key: "Delete" });
expect(current().imageScene).toEqual(original);
selectBox("title");
fireEvent.keyDown(document.activeElement!, { key: "Delete" });
expect(canvas.querySelector('[data-node="title"]')).toBeNull();
expect(current().imageScene!.nodes.map((node) => node.id)).toEqual(["image-root", "group-rocket"]);
fireEvent.keyDown(viewport, { key: "z", ctrlKey: true });
expect(current().imageScene).toEqual(original);
// Deleting a group removes its children as it does in the hierarchy.
selectBox("group-rocket");
fireEvent.keyDown(document.activeElement!, { key: "Delete" });
expect(current().imageScene!.nodes.map((node) => node.id)).toEqual(["image-root"]);
fireEvent.keyDown(viewport, { key: "Delete" });
expect(current().imageScene!.nodes.map((node) => node.id)).toEqual(["image-root"]);
});
it("undoes and redoes image edits with the keyboard inside the editor only", () => {
enableCompositionTools();
const current = setup();
const before = current().imageScene!.nodes.length;
const rocket = screen.getByRole("button", { name: "Rocket" });
fireEvent.click(rocket);
fireEvent.keyDown(rocket, { key: "d", ctrlKey: true });
expect(current().imageScene!.nodes).toHaveLength(before + 2);
const tree = screen.getByRole("tree", { name: "Image nodes" });
fireEvent.keyDown(tree, { key: "z", ctrlKey: true });
expect(current().imageScene!.nodes).toHaveLength(before);
fireEvent.keyDown(tree, { key: "y", ctrlKey: true });
expect(current().imageScene!.nodes).toHaveLength(before + 2);
// Outside the editor Ctrl+Z is the project's, not this editor's.
fireEvent.keyDown(document.body, { key: "z", ctrlKey: true });
expect(current().imageScene!.nodes).toHaveLength(before + 2);
});
it("picks canvas tools from a radio group or their letter keys and zooms from the keyboard", () => {
enableCompositionTools();
setup();
const tools = screen.getByRole("radiogroup", { name: "Canvas tool" });
expect(within(tools).getByRole("radio", { name: "Select" })).toHaveAttribute("aria-checked", "true");
fireEvent.click(within(tools).getByRole("radio", { name: "Draw text" }));
expect(within(tools).getByRole("radio", { name: "Draw text" })).toHaveAttribute("aria-checked", "true");
const canvas = screen.getByLabelText("Image placement canvas");
fireEvent.keyDown(canvas, { key: "g" });
expect(within(tools).getByRole("radio", { name: "Draw group" })).toHaveAttribute("aria-checked", "true");
fireEvent.keyDown(canvas, { key: "v" });
expect(within(tools).getByRole("radio", { name: "Select" })).toHaveAttribute("aria-checked", "true");
expect(within(tools).getByRole("radio", { name: "Draw object" })).toHaveAttribute("data-tooltip-shortcut", "O");
const zoom = screen.getByRole("combobox", { name: "Image zoom" });
const frame = canvas.parentElement!;
expect(zoom).toHaveValue("Fit");
fireEvent.keyDown(canvas, { key: "=", ctrlKey: true });
expect(frame.style.getPropertyValue("--image-zoom")).toBe("1.5");
expect(zoom).toHaveValue("150%");
fireEvent.keyDown(canvas, { key: "-", ctrlKey: true });
fireEvent.keyDown(canvas, { key: "-", ctrlKey: true });
expect(frame.style.getPropertyValue("--image-zoom")).toBe("0.75");
// Presets from the drop-down button beside the field.
fireEvent.click(zoom.parentElement!.querySelector(".ui-combo__button")!);
fireEvent.click(screen.getByRole("option", { name: "200%" }));
expect(frame.style.getPropertyValue("--image-zoom")).toBe("2");
// Or any percentage, typed.
zoom.focus();
fireEvent.change(zoom, { target: { value: "137" } });
fireEvent.keyDown(zoom, { key: "Enter" });
expect(frame.style.getPropertyValue("--image-zoom")).toBe("1.37");
expect(zoom).toHaveValue("137%");
fireEvent.change(zoom, { target: { value: "9000%" } });
fireEvent.keyDown(zoom, { key: "Enter" });
expect(frame.style.getPropertyValue("--image-zoom")).toBe("1.37");
expect(zoom).toHaveValue("137%");
fireEvent.keyDown(canvas, { key: "0", ctrlKey: true });
expect(zoom).toHaveValue("Fit");
});
it("heads the inspector with the selected node rather than an Inspector title", () => {
setup();
const inspector = screen.getByRole("complementary", { name: "Image node inspector" });
expect(within(inspector).getByRole("heading", { name: "Image" })).toBeInTheDocument();
expect(within(inspector).getByText("Root")).toBeInTheDocument();
expect(screen.queryByRole("heading", { name: /^Inspector/ })).not.toBeInTheDocument();
expect(screen.getByRole("heading", { name: "Scene" })).toBeInTheDocument();
});
it("shows an image's family behind a back button, the original first", () => {
const initial = parseProjectConfig(fixture);
const image = (id: string, parentAssetId?: string) => ({ id, name: id, kind: "image" as const, relativePath: `media/generated/${id}.jpg`, mimeType: "image/jpeg", createdAt: initial.createdAt, ...(parentAssetId ? { parentAssetId } : {}) });
initial.assets = [image("Original"), image("Other"), image("Retry", "Original"), image("Edited", "Original")];
initial.imageScene!.outputAssetId = "Other";
setup(initial);
const bar = () => within(screen.getByLabelText("Generated images")).getAllByRole("button").map((button) => button.getAttribute("aria-label"));
expect(bar()).toEqual(["View Original, 3 versions", "View Other"]);
fireEvent.click(screen.getByRole("button", { name: "View Original, 3 versions" }));
expect(bar()).toEqual(["Back to all images", "View Original", "View Retry", "View Edited"]);
expect(screen.getByRole("button", { name: "View Original" })).toHaveAttribute("aria-pressed", "true");
fireEvent.click(screen.getByRole("button", { name: "View Edited" }));
expect(screen.getByRole("button", { name: "View Edited" })).toHaveAttribute("aria-pressed", "true");
fireEvent.click(screen.getByRole("button", { name: "Back to all images" }));
// Back to the originals, with the family still marked as the selection.
expect(bar()).toEqual(["View Original, 3 versions", "View Other"]);
expect(screen.getByRole("button", { name: "View Original, 3 versions" })).toHaveAttribute("aria-pressed", "true");
fireEvent.click(screen.getByRole("button", { name: "View Other" }));
expect(bar()).toEqual(["View Original, 3 versions", "View Other"]);
});
it.each(["Create Scene", "Create Reference"])("uses the chosen primary for %s from the main image bar", (action) => {
const initial = parseProjectConfig(fixture);
const image = (id: string, parentAssetId?: string) => ({ id, name: id, kind: "image" as const, relativePath: `media/${id}.png`, mimeType: "image/png", createdAt: initial.createdAt, ...(parentAssetId ? { parentAssetId } : {}) });
initial.assets = [image("Original"), image("Other"), image("Retry", "Original"), image("Chosen", "Original")];
initial.imageScene!.outputAssetId = "Original";
const current = setup(initial);
fireEvent.contextMenu(screen.getByRole("button", { name: "View Original" }));
expect(screen.getByRole("menuitem", { name: "Make Primary" })).toBeDisabled();
fireEvent.keyDown(document.activeElement!, { key: "Escape" });
fireEvent.keyDown(screen.getByRole("button", { name: "View Chosen" }), { key: "F10", shiftKey: true });
fireEvent.click(screen.getByRole("menuitem", { name: "Make Primary" }));
expect(current().imageScene).toEqual(initial.imageScene);
expect(screen.getByRole("button", { name: "View Original" })).toHaveAttribute("aria-pressed", "true");
fireEvent.click(screen.getByRole("button", { name: "Back to all images" }));
expect(within(screen.getByLabelText("Generated images")).getAllByRole("button").map((button) => button.getAttribute("aria-label")))
.toEqual(["View Chosen, 3 versions", "View Other"]);
fireEvent.contextMenu(screen.getByRole("button", { name: "View Chosen, 3 versions" }));
expect(screen.queryByRole("menuitem", { name: "Make Primary" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("menuitem", { name: action }));
const reopened = parseProjectConfig(JSON.parse(JSON.stringify(current())));
expect(referenceImages(reopened.references[0])[0].relativePath).toBe("media/Chosen.png");
if (action === "Create Scene") expect(reopened.generationJobs.at(-1)?.startFrameReferenceId).toBe(reopened.references[0].id);
expect(reopened.assets.find((asset) => asset.id === "Original")?.parentAssetId).toBe("Chosen");
expect(reopened.assets.find((asset) => asset.id === "Chosen")?.parentAssetId).toBeUndefined();
});
it.each(["thumbnail", "bar", "keyboard"])("creates an empty child in the browsed family from the %s menu", (target) => {
const initial = parseProjectConfig(fixture);
const image = (id: string, parentAssetId?: string) => ({ id, name: id, kind: "image" as const,
relativePath: `media/generated/${id}.jpg`, mimeType: "image/jpeg", createdAt: initial.createdAt, parentAssetId });
initial.assets = [image("Original"), image("Child", "Original"), image("Unrelated")];
initial.imageScene!.outputAssetId = "Child";
const current = setup(initial);
expect(screen.getByRole("button", { name: "Back to all images" })).toBeInTheDocument();
if (target === "thumbnail") fireEvent.contextMenu(screen.getByRole("button", { name: "View Child" }));
else if (target === "keyboard") fireEvent.keyDown(screen.getByLabelText("Generated images"), { key: "F10", shiftKey: true });
else fireEvent.contextMenu(screen.getByLabelText("Generated images"));
fireEvent.click(screen.getByRole("menuitem", { name: "New empty image" }));
const draft = current().assets.at(-1)!;
expect(draft).toMatchObject({ imageDraft: true, parentAssetId: "Original" });
expect(current().imageScene).toMatchObject({ outputAssetId: draft.id });
expect(current().imageScene!.rootType ?? "prompt").toBe("prompt");
expect(current().imageScene!.sourceImage).toBeUndefined();
expect(current().imageScene!.nodes).toHaveLength(1);
expect(promptValue(screen.getByLabelText("Prompt (high-level description)"))).toBe("");
expect(screen.getByRole("button", { name: "View New image" })).toHaveAttribute("aria-pressed", "true");
expect(screen.getByRole("button", { name: "Back to all images" })).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "View Unrelated" })).not.toBeInTheDocument();
typePrompt(screen.getByLabelText("Prompt (high-level description)"), "A new variation");
fireEvent.click(screen.getByRole("button", { name: "View Child" }));
fireEvent.click(screen.getByRole("button", { name: "View New image" }));
expect(promptValue(screen.getByLabelText("Prompt (high-level description)"))).toBe("A new variation");
expect(parseProjectConfig(JSON.parse(JSON.stringify(current()))).assets.find(({ id }) => id === draft.id)?.parentAssetId).toBe("Original");
// Returning to the main bar makes New empty image create a new primary again.
fireEvent.click(screen.getByRole("button", { name: "Back to all images" }));
fireEvent.contextMenu(screen.getByLabelText("Generated images"));
fireEvent.click(screen.getByRole("menuitem", { name: "New empty image" }));
expect(current().assets.at(-1)?.parentAssetId).toBeUndefined();
expect(screen.queryByRole("button", { name: "Back to all images" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "View Unrelated" })).toBeInTheDocument();
});
it("removes an original with a family only from inside the family, and the leftmost image takes its place", () => {
const initial = parseProjectConfig(fixture);
const image = (id: string, parentAssetId?: string) => ({ id, name: id, kind: "image" as const, relativePath: `media/generated/${id}.jpg`, mimeType: "image/jpeg", createdAt: initial.createdAt, ...(parentAssetId ? { parentAssetId } : {}) });
initial.assets = [image("Original"), image("Other"), image("Retry", "Original"), image("Edited", "Original")];
initial.imageScene!.outputAssetId = "Other";
const current = setup(initial);
const bar = () => within(screen.getByLabelText("Generated images")).getAllByRole("button").map((button) => button.getAttribute("aria-label"));
const remove = (name: string) => {
fireEvent.contextMenu(screen.getByRole("button", { name }));
return screen.getByRole("menuitem", { name: "Remove" });
};
// On the originals, an original with a family cannot be removed; one alone can.
expect(remove("View Original, 3 versions")).toBeDisabled();
fireEvent.keyDown(document.activeElement!, { key: "Escape" });
expect(remove("View Other")).toBeEnabled();
fireEvent.keyDown(document.activeElement!, { key: "Escape" });
// Inside the family it can, and the leftmost image becomes the original.
fireEvent.click(screen.getByRole("button", { name: "View Original, 3 versions" }));
fireEvent.click(remove("View Original"));
expect(bar()).toEqual(["Back to all images", "View Retry", "View Edited"]);
expect(screen.getByRole("button", { name: "View Retry" })).toHaveAttribute("aria-pressed", "true");
expect(current().assets.map((asset) => [asset.id, asset.parentAssetId])).toEqual([["Other", undefined], ["Retry", undefined], ["Edited", "Retry"]]);
// Emptying the family takes it off the originals too.
fireEvent.click(remove("View Retry"));
expect(bar()).toEqual(["View Other", "View Edited"]);
fireEvent.click(remove("View Edited"));
expect(bar()).toEqual(["View Other"]);
});
it("shows the image bar's scrollbar while it scrolls, then hides it again", () => {
vi.useFakeTimers();
try {
setup();
const bar = screen.getByLabelText("Generated images");
fireEvent.scroll(bar);
expect(bar).toHaveClass("image-results--scrolling");
act(() => { vi.advanceTimersByTime(1000); });
expect(bar).not.toHaveClass("image-results--scrolling");
} finally { vi.useRealTimers(); }
});
it("saves generation effects from the image root inspector and blocks them on MOSS", () => {
const initial = parseProjectConfig(fixture);
initial.imageScene = createImageScene("A red apple");
const latest = setup(initial);
fireEvent.click(screen.getByRole("button", { name: "Add effect" }));
fireEvent.click(screen.getByRole("button", { name: "Tone" }));
fireEvent.change(screen.getByRole("slider", { name: "Contrast" }), { target: { value: "1.5" } });
expect(latest().imageScene?.generationEffects?.tone?.contrast).toBe(1.5);
const saved = parseProjectConfig(JSON.parse(JSON.stringify(latest())));
cleanup();
saveGeneratorTemplateSettings({ templates: [mossImageTemplate()], defaultTemplateId: "moss-image", catalogVersion: 17 });
setup(saved);
expect(screen.getByRole("button", { name: "Add effect" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Generate" })).toBeDisabled();
expect(screen.getByRole("checkbox", { name: "Enable Tone" })).toBeEnabled();
});
it("shows CFG before Seed for MOSS and preserves its value when switching models", () => {
const paths = { transformer: "model", textEncoder: "encoder", videoVae: "vae", tokenizer: "tokenizer.json", audioVae: "audio" };
const moss = { ...mossImageTemplate(), sources: {}, paths };
const h3 = { ...createGeneratorTemplate("H3"), sources: {}, paths };
saveGeneratorTemplateSettings({ templates: [moss, h3], defaultTemplateId: moss.id, catalogVersion: 17 });
const initial = parseProjectConfig(fixture);
initial.imageScene = createImageScene("An apple");
const latest = setup(initial);
const cfg = screen.getByRole("spinbutton", { name: "CFG" });
expect(cfg).toHaveValue(3);
expect(cfg.compareDocumentPosition(screen.getByRole("spinbutton", { name: "Seed" })) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
fireEvent.change(cfg, { target: { value: "4.5" } });
expect(latest().imageScene?.cfgScales).toEqual({ moss: 4.5 });
fireEvent.change(cfg, { target: { value: "-1" } });
expect(latest().imageScene?.cfgScales?.moss).toBe(4.5);
choose("Generator", "H3");
expect(screen.queryByRole("spinbutton", { name: "CFG" })).toBeNull();
choose("Generator", "MOSS Image");
expect(screen.getByRole("spinbutton", { name: "CFG" })).toHaveValue(4.5);
const saved = parseProjectConfig(JSON.parse(JSON.stringify(latest())));
cleanup(); setup(saved);
expect(screen.getByRole("spinbutton", { name: "CFG" })).toHaveValue(4.5);
});
it("sets a temporary generation count, dismisses its panel and resets after one Generate click", () => {
vi.spyOn(persistence, "isTauri").mockReturnValue(true);
const template = { ...defaultGeneratorTemplate(), sources: {}, paths: { transformer: "model", textEncoder: "encoder", videoVae: "vae", tokenizer: "tokenizer.json", audioVae: "audio" } };
saveGeneratorTemplateSettings({ templates: [template], defaultTemplateId: template.id });
const config = parseProjectConfig(fixture);
const onGenerate = vi.fn();
const onChange = vi.fn();
const props = { config, folderPath: "D:/Images", onChange, onGenerate, onCancel: vi.fn() };
const { unmount } = render(<ImageEditor {...props} />);
const options = screen.getByRole("button", { name: "Generation options" });
expect(options.closest(".inspector-actions")).not.toBeNull();
fireEvent.click(options);
expect(screen.getByRole("dialog", { name: "Generation options" })).toBeInTheDocument();
const count = screen.getByRole("spinbutton", { name: "Count" });
expect(count).toHaveFocus();
expect(screen.getByText("Count")).toHaveAttribute("data-tooltip", "Different seeds for each image. Resets after generating.");
expect(screen.queryByText("Different seeds for each image. Resets after generating.")).not.toBeInTheDocument();
expect(count).toHaveValue(1);
for (const value of ["0", "101", "2.5", ""]) {
fireEvent.change(count, { target: { value } });
expect(count).toHaveAttribute("aria-invalid", "true");
expect(screen.getByRole("button", { name: "Generate" })).toBeDisabled();
}
fireEvent.change(count, { target: { value: "3" } });
fireEvent.keyDown(count, { key: "Escape" });
expect(screen.queryByRole("dialog", { name: "Generation options" })).not.toBeInTheDocument();
expect(options).toHaveFocus();
fireEvent.click(options);
expect(screen.getByRole("spinbutton", { name: "Count" })).toHaveValue(3);
fireEvent.click(screen.getByRole("button", { name: "Generate (3)" }));
expect(onGenerate).toHaveBeenLastCalledWith(expect.objectContaining({ id: template.id }), 3);
expect(screen.queryByRole("dialog", { name: "Generation options" })).not.toBeInTheDocument();
fireEvent.click(options);
expect(screen.getByRole("spinbutton", { name: "Count" })).toHaveValue(1);
fireEvent.keyDown(screen.getByRole("spinbutton", { name: "Count" }), { key: "Escape" });
fireEvent.click(screen.getByRole("button", { name: "Generate" }));
expect(onGenerate).toHaveBeenLastCalledWith(expect.objectContaining({ id: template.id }), 1);
expect(onChange).not.toHaveBeenCalled();
fireEvent.click(options);
fireEvent.change(screen.getByRole("spinbutton", { name: "Count" }), { target: { value: "4" } });
unmount();
render(<ImageEditor {...props} />);
fireEvent.click(screen.getByRole("button", { name: "Generation options" }));
expect(screen.getByRole("spinbutton", { name: "Count" })).toHaveValue(1);
});
it.each(["Edit Box", "Lasso"])("caps a drawn %s at the target resolution on a larger image", (tool) => {
const initial = parseProjectConfig(fixture);
initial.imageScene = createImageEditScene({ relativePath: "media/large.png", name: "Large", width: 4096, height: 4096 });
initial.imageScene.outputSize = { width: 512, height: 512 };
const current = setup(initial);
const canvas = screen.getByLabelText("Image placement canvas");
Object.defineProperty(canvas, "setPointerCapture", { value: vi.fn() });
Object.defineProperty(canvas, "getBoundingClientRect", { value: () => ({ left: 0, top: 0, width: 1000, height: 1000 }) });
const pointer = (type: "pointerDown" | "pointerMove" | "pointerUp", x: number, y: number, target: Element = canvas) => {
const event = createEvent[type](target);
Object.defineProperties(event, { button: { value: 0 }, pointerId: { value: 1 }, clientX: { value: x }, clientY: { value: y } });
fireEvent(target, event);
};
fireEvent.click(screen.getByRole("radio", { name: tool }));
pointer("pointerDown", 500, 500);
pointer("pointerMove", 900, 500);
pointer("pointerUp", tool === "Lasso" ? 500 : 900, 900);
expect(current().imageScene!.nodes[1].box).toEqual({ x: 500, y: 500, width: 125, height: 125 });
typePrompt(screen.getByLabelText("Edit prompt"), "A red flower");
expect(compileImageEdits(current()).edits[0]).toMatchObject({ x: 2048, y: 2048, width: 512, height: 512 });
if (tool === "Edit Box") {
const handle = canvas.querySelector("[data-resize]")!;
pointer("pointerDown", 625, 625, handle); pointer("pointerUp", 1000, 1000);
expect(current().imageScene!.nodes[1].box).toEqual({ x: 500, y: 500, width: 125, height: 125 });
}
expect(current().imageScene!.sourceImage).toMatchObject({ width: 4096, height: 4096 });
});
it("draws a lasso, edits its prompt, moves its outline, and saves it independently", () => {
const initial = parseProjectConfig(fixture);
initial.assets = [{ id: "source", name: "Source", kind: "image", relativePath: "media/source.png", mimeType: "image/png", width: 1000, height: 800, createdAt: initial.createdAt }];
const current = setup(initial);
fireEvent.contextMenu(screen.getByRole("button", { name: "View Source" }));
fireEvent.click(screen.getByRole("menuitem", { name: "Edit" }));
const canvas = screen.getByLabelText("Image placement canvas");
Object.defineProperty(canvas, "setPointerCapture", { value: vi.fn() });
Object.defineProperty(canvas, "getBoundingClientRect", { value: () => ({ left: 0, top: 0, width: 1000, height: 800 }) });
const pointer = (type: "pointerDown" | "pointerMove" | "pointerUp", x: number, y: number, target: Element = canvas) => {
const event = createEvent[type](target);
Object.defineProperties(event, { button: { value: 0 }, pointerId: { value: 1 }, clientX: { value: x }, clientY: { value: y } });
fireEvent(target, event);
};
fireEvent.click(screen.getByRole("radio", { name: "Lasso" }));
pointer("pointerDown", 100, 80); pointer("pointerMove", 400, 80); pointer("pointerUp", 100, 320);
expect(screen.getByRole("radio", { name: "Select" })).toHaveAttribute("aria-checked", "true");
expect(screen.getByRole("button", { name: "Lasso" })).toBeInTheDocument();
expect(canvas.querySelector("[data-resize]")).toBeNull();
const lasso = current().imageScene!.nodes[1];
expect(lasso).toMatchObject({ name: "Lasso", box: { x: 100, y: 100, width: 300, height: 300 }, lasso: [{ x: 0, y: 0 }, { x: 1000, y: 0 }, { x: 0, y: 1000 }] });
typePrompt(screen.getByLabelText("Edit prompt"), "Add a red flower");
fireEvent.click(screen.getByRole("button", { name: "Image" }));
const outline = canvas.querySelector("path[data-node]")!;
pointer("pointerDown", 150, 120, outline); pointer("pointerMove", 250, 200); pointer("pointerUp", 250, 200);
expect(current().imageScene!.nodes[1]).toMatchObject({ box: { x: 200, y: 200, width: 300, height: 300 }, lasso: lasso.lasso, description: "Add a red flower" });
expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("Add a red flower");
expect(compileImageEdits(current()).edits[0]).toMatchObject({ feather: 0, maskPolygon: [{ x: 200, y: 160 }, { x: 500, y: 160 }, { x: 200, y: 400 }] });
expect(parseProjectConfig(JSON.parse(JSON.stringify(current()))).imageScene).toEqual(current().imageScene);
expect(current().assets.find((asset) => asset.id === "source")?.imageEditing).toBeUndefined();
fireEvent.click(screen.getByRole("radio", { name: "Lasso" }));
pointer("pointerDown", 10, 10); pointer("pointerMove", 200, 100);
Object.defineProperty(canvas.closest(".image-viewport")!, "hasPointerCapture", { value: () => false });
fireEvent.pointerCancel(canvas);
expect(current().imageScene!.nodes).toHaveLength(2);
pointer("pointerDown", 10, 10); pointer("pointerUp", 200, 200);
expect(current().imageScene!.nodes).toHaveLength(2);
});
it.each(["queued", "generating", "encoding"] as const)("keeps the edit source visible while %s, then displays the completed image", 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);
const source = { id: "source", kind: "image" as const, name: "Original", relativePath: "media/source.png", width: 512, height: 512, mimeType: "image/png", createdAt: config.createdAt };
config.assets = [source];
config.imageScene = createImageEditScene(source);
config.imageScene.nodes[0].description = "Add snow";
const pending = saveImageDraft(config, "default", true, "pending");
const work = { id: "job", imageAssetId: source.id, imageDraftId: "pending", status, progress: 0.25, detail: "Working" } as WorkItem;
const props = { folderPath: "D:/Images", onChange: vi.fn(), onGenerate: vi.fn(), onCancel: vi.fn() };
const { rerender } = render(<ImageEditor {...props} config={pending} workItems={[work]} />);
await waitFor(() => expect(document.querySelector(".image-frame img")).toHaveAttribute("src", "blob:media/source.png"));
expect(document.querySelector(".image-frame .image-empty")).toBeNull();
expect(screen.getByRole("progressbar", { name: "Image generation progress" })).toBeInTheDocument();
const result = { ...source, id: "pending", name: "Edited image", relativePath: "media/result.png", imageGeneration: pending.assets[1].imageGeneration };
const completed = completeImageDraft(pending, result.id, result);
rerender(<ImageEditor {...props} config={completed} workItems={[{ ...work, status: "completed", progress: 1 }]} />);
await waitFor(() => expect(document.querySelector(".image-frame img")).toHaveAttribute("src", "blob:media/result.png"));
expect(screen.queryByRole("progressbar", { name: "Image generation progress" })).not.toBeInTheDocument();
expect(completed.assets[0]).toEqual(source);
});
it("combines and subtracts lassos using release-time modifiers and shows matching cursors", () => {
const initial = parseProjectConfig(fixture);
initial.imageScene = createImageEditScene({ name: "Source", relativePath: "media/source.png", width: 1000, height: 1000 });
const current = setup(initial);
const canvas = screen.getByLabelText("Image placement canvas");
Object.defineProperty(canvas, "setPointerCapture", { value: vi.fn() });
Object.defineProperty(canvas, "getBoundingClientRect", { value: () => ({ left: 0, top: 0, width: 1000, height: 1000 }) });
const pointer = (type: "pointerDown" | "pointerMove" | "pointerUp", x: number, y: number, ctrlKey = false, altKey = false) => {
const event = createEvent[type](canvas);
Object.defineProperties(event, { button: { value: 0 }, pointerId: { value: 1 }, clientX: { value: x }, clientY: { value: y }, ctrlKey: { value: ctrlKey }, altKey: { value: altKey } });
fireEvent(canvas, event);
};
const rectangle = (x: number, y: number, width: number, height: number, modifier?: "Control" | "Alt") => {
fireEvent.click(screen.getByRole("radio", { name: "Lasso" }));
pointer("pointerDown", x, y); pointer("pointerMove", x + width, y); pointer("pointerMove", x + width, y + height);
if (modifier) fireEvent.keyDown(window, { key: modifier, ctrlKey: modifier === "Control", altKey: modifier === "Alt" });
pointer("pointerUp", x, y + height, modifier === "Control", modifier === "Alt");
};
rectangle(100, 100, 300, 300);
const originalId = current().imageScene!.nodes[1].id;
typePrompt(screen.getByLabelText("Edit prompt"), "Red flower");
rectangle(300, 100, 300, 300, "Control");
expect(current().imageScene!.nodes).toHaveLength(2);
expect(current().imageScene!.nodes[1]).toMatchObject({ id: originalId, description: "Red flower", box: { x: 100, y: 100, width: 500, height: 300 } });
expect(canvas).toHaveClass("lasso-add");
fireEvent.keyUp(window, { key: "Control", ctrlKey: false });
expect(canvas).not.toHaveClass("lasso-add");
rectangle(200, 200, 100, 100, "Alt");
expect(canvas).toHaveClass("lasso-subtract");
expect(current().imageScene!.nodes[1].lassoContours).toHaveLength(1);
expect(canvas.querySelector("path[data-node]")!.getAttribute("d")!.match(/M/g)).toHaveLength(2);
const withHole = current().imageScene;
fireEvent.keyUp(window, { key: "Alt", altKey: false });
rectangle(800, 800, 100, 100, "Alt");
expect(current().imageScene).toEqual(withHole);
fireEvent.keyUp(window, { key: "Alt", altKey: false });
undoImageEdit();
expect(current().imageScene!.nodes[1].lassoContours).toBeUndefined();
fireEvent.keyDown(screen.getByRole("tree", { name: "Image nodes" }), { key: "y", code: "KeyY", ctrlKey: true });
expect(current().imageScene!.nodes[1].lassoContours).toHaveLength(1);
rectangle(800, 800, 100, 100, "Control");
expect(current().imageScene!.nodes).toHaveLength(3);
fireEvent.blur(window);
expect(canvas).not.toHaveClass("lasso-add");
expect(parseProjectConfig(JSON.parse(JSON.stringify(current()))).imageScene).toEqual(current().imageScene);
});
it("gates composition creation by model across menus, shortcuts and model switches", () => {
const h3 = createGeneratorTemplate("H3"), moss = createGeneratorTemplate("MOSS", "moss"), fibo = createGeneratorTemplate("Fibo", "fibo2");
saveGeneratorTemplateSettings({ templates: [h3, moss, fibo], defaultTemplateId: h3.id, catalogVersion: 17 });
const current = setup();
const before = structuredClone(current().imageScene!.nodes);
for (const name of ["Draw object", "Draw text", "Draw group"]) expect(screen.getByRole("radio", { name })).toBeDisabled();
const tree = screen.getByRole("tree", { name: "Image nodes" });
fireEvent.contextMenu(tree);
for (const name of ["New Object", "New Text", "New Group", "New Background"]) expect(screen.getByRole("menuitem", { name })).toBeDisabled();
fireEvent.keyDown(window, { key: "Escape" });
const canvas = screen.getByLabelText("Image placement canvas");
for (const key of ["o", "t", "g"]) fireEvent.keyDown(canvas, { key });
expect(screen.getByRole("radio", { name: "Select" })).toHaveAttribute("aria-checked", "true");
const rocket = screen.getByRole("button", { name: "Rocket" });
fireEvent.click(rocket);
fireEvent.keyDown(rocket, { key: "d", ctrlKey: true });
expect(current().imageScene!.nodes).toEqual(before);
for (const model of ["MOSS", "Fibo"]) {
choose("Generator", model);
for (const name of ["Draw object", "Draw text", "Draw group"]) expect(screen.getByRole("radio", { name })).toBeEnabled();
fireEvent.contextMenu(tree);
for (const name of ["New Object", "New Text", "New Group", "New Background"]) expect(screen.getByRole("menuitem", { name })).toBeEnabled();
fireEvent.keyDown(window, { key: "Escape" });
fireEvent.click(screen.getByRole("radio", { name: "Draw object" }));
expect(screen.getByRole("radio", { name: "Draw object" })).toHaveAttribute("aria-checked", "true");
choose("Generator", "H3");
expect(screen.getByRole("radio", { name: "Select" })).toHaveAttribute("aria-checked", "true");
}
expect(current().imageScene!.nodes).toEqual(before);
});
it("shows model-specific negative prompts, preserves them across model switches and explains Fibo", () => {
const h3 = createGeneratorTemplate("H3"), moss = createGeneratorTemplate("MOSS", "moss"), fibo = createGeneratorTemplate("Fibo", "fibo2");
saveGeneratorTemplateSettings({ templates: [h3, moss, fibo], defaultTemplateId: h3.id, catalogVersion: 17 });
const latest = setup();
expect(screen.queryByRole("textbox", { name: "Negative prompt" })).not.toBeInTheDocument();
choose("Generator", "MOSS");
const field = screen.getByRole("textbox", { name: "Negative prompt" });
expect(field).toBeEnabled();
fireEvent.change(field, { target: { value: "Watermarks, blurry details" } });
expect(parseProjectConfig(JSON.parse(JSON.stringify(latest()))).imageScene?.negativePrompts?.moss).toBe("Watermarks, blurry details");
expect(screen.getByRole("textbox", { name: "Negative prompt" }).compareDocumentPosition(screen.getByText("Image generation")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
choose("Generator", "Fibo");
expect(screen.getByRole("textbox", { name: "Negative prompt" })).toBeDisabled();
expect(screen.getByText("Negative prompt")).toHaveAttribute("data-tooltip", expect.stringContaining("does not support negative prompts"));
choose("Generator", "MOSS");
expect(screen.getByRole("textbox", { name: "Negative prompt" })).toHaveValue("Watermarks, blurry details");
expect(screen.queryByText("Background (environment)")).not.toBeInTheDocument();
});
it("uses Fibo's four-step default for fresh images and imports, preserving saved steps", () => {
const fibo = createGeneratorTemplate("Fibo", "fibo2");
saveGeneratorTemplateSettings({ templates: [fibo], defaultTemplateId: fibo.id, catalogVersion: 17 });
const initial = parseProjectConfig(fixture);
initial.imageScene!.steps = 12;
const imported = { id: "imported", kind: "image" as const, name: "Imported", relativePath: "media/source.png", width: 512, height: 512, mimeType: "image/png", createdAt: initial.createdAt };
initial.assets = [imported, { ...imported, id: "saved", name: "Saved", imageGeneration: imageGenerationSnapshot(initial, "Saved prompt", fibo.id) }];
const latest = setup(initial);
fireEvent.click(screen.getByRole("button", { name: "View Imported" }));
expect(screen.getByLabelText("Steps")).toHaveValue(4);
fireEvent.click(screen.getByRole("button", { name: "View Saved" }));
expect(screen.getByLabelText("Steps")).toHaveValue(12);
fireEvent.contextMenu(screen.getByLabelText("Generated images"));
fireEvent.click(screen.getByRole("menuitem", { name: "New empty image" }));
expect(screen.getByLabelText("Steps")).toHaveValue(4);
expect(latest().imageScene!.steps).toBe(4);
fireEvent.change(screen.getByLabelText("Steps"), { target: { value: "8" } });
expect(latest().imageScene!.steps).toBe(8);
});
it.each([fiboBaseTemplate(), { ...fiboImageTemplate(), editingModel: false }])("disables editing and Zoom for $name when editing is off", (template) => {
vi.spyOn(persistence, "isTauri").mockReturnValue(true);
const usable = { ...template, sources: {}, paths: { transformer: "fibo", textEncoder: "qwen", videoVae: "flux", tokenizer: "", audioVae: "" } };
saveGeneratorTemplateSettings({ templates: [usable], defaultTemplateId: usable.id, catalogVersion: 17 });
const initial = parseProjectConfig(fixture);
initial.imageScene = createImageScene("A forest");
setup(initial);
expect(screen.getByRole("button", { name: "Generate" })).toBeEnabled();
cleanup();
const source = { id: "source", kind: "image" as const, name: "Source", relativePath: "media/source.png", width: 512, height: 512, mimeType: "image/png", createdAt: initial.createdAt };
initial.assets = [source];
initial.imageScene = { ...createImageEditScene(source), outputAssetId: source.id };
initial.imageScene.nodes[0].description = "Make it blue";
setup(initial);
expect(screen.getByRole("button", { name: "Generate" })).toBeDisabled();
expect(screen.getByRole("radio", { name: "Edit Box" })).toBeDisabled();
expect(screen.getByRole("radio", { name: "Lasso" })).toBeDisabled();
fireEvent.click(screen.getByRole("button", { name: "Template" }));
expect(screen.getByRole("menuitem", { name: "Zoom" })).toBeDisabled();
});