AI media harness for planning, generating, and editing locally
TypeScript
Show template generations in the image bar
Bitti163d5e96597e
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.mdindex 35a7739..403ad8e 100644--- a/RELEASE_NOTES.md+++ b/RELEASE_NOTES.md@@ -4,6 +4,7 @@ This alpha update adds LAN generation workers, Linux support, expanded color gra## What's new+- Extend and Character Sheet create a selectable image-bar entry as soon as generation is queued. Selecting it while generation runs shows the template's existing settings panel with the submitted settings. Finished results open in the normal image editor.- LAN workers: run the Slopus worker package on another Windows or Linux computer and pick it in the new **Settings → Workers** tab to generate there. Slopus finds workers on the local network automatically, or by address. Workers download generator weights from their download links themselves and use CUDA when available, with a Vulkan fallback; local-only files are sent from this computer, and finished videos, images and latents are saved in your project as usual.- Slopus for Linux (x86_64): install the .deb or .rpm package, or run the AppImage, which updates itself. Local generation on Linux needs an NVIDIA GPU with CUDA 13.- Every project now includes Video and Image tabs. Older video and image projects keep their saved content, and Export supports both output types.diff --git a/src-tauri/src/project/image.rs b/src-tauri/src/project/image.rsindex 2d171f3..4d19e2f 100644--- a/src-tauri/src/project/image.rs+++ b/src-tauri/src/project/image.rs@@ -13,9 +13,43 @@ pub(crate) struct ImageGenerationSnapshot {pub generator_template_id: String,#[serde(default, skip_serializing_if = "Option::is_none")]pub used_seed: Option<u64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub template: Option<ImageTemplateSnapshot>,pub references: Vec<super::references::ReusableReference>,}+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub(crate) struct ImageTemplateSnapshot {+ pub kind: String,+ pub source_id: String,+ pub source_name: String,+ pub generator_name: String,+ pub prompt: String,+ pub steps: u32,+ pub seed: i64,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub bounds: Option<ImageBox>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub height: Option<u32>,+}++impl ImageTemplateSnapshot {+ pub(crate) fn validate(&self) -> Result<(), String> {+ let valid_options = match self.kind.as_str() {+ "extend" => self.height.is_none() && self.bounds.as_ref().is_some_and(|b|+ [b.x, b.y, b.width, b.height].iter().all(|v| v.is_finite()) && b.width > 0.0 && b.height > 0.0),+ "character-sheet" => self.bounds.is_none() && matches!(self.height, Some(512 | 1024 | 1536 | 2048)),+ _ => false,+ };+ if !valid_options || self.source_id.is_empty() || self.source_name.is_empty() || self.generator_name.is_empty()+ || !(2..=1000).contains(&self.steps) || !(-1..=9_007_199_254_740_991).contains(&self.seed) {+ return Err("Invalid image template snapshot settings.".into());+ }+ Ok(())+ }+}+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase", deny_unknown_fields)]pub struct ImageScene {diff --git a/src-tauri/src/project/validation/assets.rs b/src-tauri/src/project/validation/assets.rsindex 8ff405e..248efc8 100644--- a/src-tauri/src/project/validation/assets.rs+++ b/src-tauri/src/project/validation/assets.rs@@ -24,6 +24,7 @@ pub(super) fn validate(config: &mut ProjectConfig) -> Result<(), String> {}if let Some(snapshot) = &mut asset.image_generation {snapshot.scene.validate()?;+ if let Some(template) = &snapshot.template { template.validate()?; }if asset.kind != "image"|| !is_supported_resolution(&snapshot.resolution)|| !is_supported_aspect_ratio(&snapshot.aspect_ratio)diff --git a/src-tauri/src/tests/images.rs b/src-tauri/src/tests/images.rsindex 0759ed1..541dd0c 100644--- a/src-tauri/src/tests/images.rs+++ b/src-tauri/src/tests/images.rs@@ -165,6 +165,33 @@ fn image_tree_survives_folder_creation_save_and_reopen() {assert_eq!(roundtrip.image_scene, config.image_scene);}+#[test]+fn image_template_settings_survive_save_and_reopen() {+ for template in [+ serde_json::json!({"kind":"extend", "sourceId":"source", "sourceName":"Original", "generatorName":"Default generator", "prompt":"Continue the forest", "steps":28, "seed":-1, "bounds":{"x":-64,"y":-32,"width":768,"height":640}}),+ serde_json::json!({"kind":"character-sheet", "sourceId":"source", "sourceName":"Original", "generatorName":"Default generator", "prompt":"Red coat", "steps":28, "seed":0, "height":1024}),+ ] {+ for pending in [true, false] {+ let mut config = image_fixture();+ let mut snapshot: serde_json::Value = serde_json::from_str(include_str!("../../../fixtures/image-generation-snapshot.json")).unwrap();+ snapshot["template"] = template.clone();+ snapshot["usedSeed"] = serde_json::json!(1234);+ config.assets.push(serde_json::from_value(serde_json::json!({+ "id":"template-result", "kind":"image", "name":"Template result", "mimeType":"image/png",+ "width":512, "height":512, "createdAt":config.created_at, "imageDraft":pending,+ "relativePath":if pending { None } else { Some("media/result.png") }, "imageGeneration":snapshot+ })).unwrap());+ let root = tempfile::tempdir().unwrap();+ let created = create_project_in(root.path(), &config).unwrap();+ let reopened = read_project(Path::new(&created.folder_path)).unwrap();+ assert_eq!(reopened.config.assets, config.assets);+ let mut invalid = config;+ invalid.assets.last_mut().unwrap().image_generation.as_mut().unwrap().template.as_mut().unwrap().kind = "unknown".into();+ assert!(validate_and_normalize_config(invalid).is_err());+ }+ }+}+#[test]fn image_and_video_content_coexist_after_save_and_reopen_for_both_legacy_types() {for generation_type in [GenerationType::Video, GenerationType::Image] {diff --git a/src/components/workspace/CharacterSheetSettings.tsx b/src/components/workspace/CharacterSheetSettings.tsxindex 9a689fb..b04b0aa 100644--- a/src/components/workspace/CharacterSheetSettings.tsx+++ b/src/components/workspace/CharacterSheetSettings.tsx@@ -6,13 +6,14 @@ import { Dismiss16, Sparkle16 } from "../ui/icons";import { PromptTextField, type PromptReference } from "./PromptTextField";import { TemplateDebugPrompt } from "./TemplateDebugPrompt";-export function CharacterSheetSettings({ config, source, references, missingLabel, defaultSteps, disabledReason, busy, onExecute, onClose }: {+export function CharacterSheetSettings({ config, source, references, missingLabel, defaultSteps, disabledReason, busy, initialOptions, onExecute, onClose }: {config: ProjectConfig; source: ProjectAsset; references: PromptReference[]; missingLabel: (id: string) => string;defaultSteps: number; disabledReason: string | null; busy: boolean;+ initialOptions?: CharacterSheetOptions;onExecute: (options: CharacterSheetOptions) => void; onClose: () => void;}) {const [options, setOptions] = useState<CharacterSheetOptions>(() => ({ ...emptyCharacterSheetOptions(), height: characterSheetDimensions(config.settings.resolution)[0].height,- steps: config.imageScene?.steps ?? defaultSteps, seed: config.imageScene?.seed ?? -1 }));+ steps: config.imageScene?.steps ?? defaultSteps, seed: config.imageScene?.seed ?? -1, ...initialOptions }));const dimensions = characterSheetDimensions(config.settings.resolution, options.height);const [error, setError] = useState<string | null>(null);const compiled = useMemo(() => {diff --git a/src/components/workspace/ImageEditor.test.tsx b/src/components/workspace/ImageEditor.test.tsxindex db46372..324aabd 100644--- a/src/components/workspace/ImageEditor.test.tsx+++ b/src/components/workspace/ImageEditor.test.tsx@@ -7,9 +7,10 @@ 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 { imageGenerationSnapshot } from "../../lib/imageHistory";+import { completeImageDraft, createTemplateImageDraft, imageGenerationSnapshot, restoreGeneratedImage } from "../../lib/imageHistory";import { createGeneratorTemplate, defaultGeneratorTemplate, saveGeneratorTemplateSettings } from "../../lib/settings";-import { createImageEditScene, imageScenePrompt } from "../../lib/imageScene";+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";@@ -18,17 +19,92 @@ import snapshotFixture from "../../../fixtures/image-generation-snapshot.json";vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));afterEach(() => { cleanup(); localStorage.clear(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });-function setup(initial = parseProjectConfig(fixture)) {+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()} />;+ return <ImageEditor config={config} folderPath="D:/Images" onChange={setConfig} onGenerate={vi.fn()} onCancel={vi.fn()} workItems={workItems} />;}render(<Harness />);return () => latest;}+it.each([+ ["extend", true], ["extend", false], ["character-sheet", true], ["character-sheet", false],+] as const)("shows the existing %s panel only while the selected entry is generating (pending: %s)", (kind, pending) => {+ 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" ? "Extend" : "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: 1024 }) } };+ 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("Extend x")).toHaveValue(-64);+ expect(panel.getByLabelText("Extend y")).toHaveValue(-32);+ expect(panel.getByLabelText("Extend width")).toHaveValue(768);+ expect(panel.getByLabelText("Extend height")).toHaveValue(640);+ } else expect(comboValue(panel.getByLabelText("Character sheet resolution"))).toBe("1024");+ 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" ? "Extend 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: /^(Extend|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 });diff --git a/src/components/workspace/ImageEditor.tsx b/src/components/workspace/ImageEditor.tsxindex d30c3c7..06fe18f 100644--- a/src/components/workspace/ImageEditor.tsx+++ b/src/components/workspace/ImageEditor.tsx@@ -150,9 +150,12 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGenepan.current = null; setPanning(false);if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);};- const work = workItems.filter((item) => item.imageAssetId === scene.outputAssetId).at(-1);+ const work = workItems.filter((item) => item.imageAssetId === scene.outputAssetId || item.imageDraftId === scene.outputAssetId || item.id === scene.outputAssetId).at(-1);const active = work && isWorkActive(work);const output = config.assets.find((asset) => asset.id === scene.outputAssetId);+ const templateSnapshot = output?.imageDraft ? output.imageGeneration?.template : undefined;+ const runningTemplate = active ? templateSnapshot : undefined;+ const templateSource = runningTemplate && config.assets.find((asset) => asset.id === runningTemplate.sourceId);let extendSize: { width: number; height: number } | null = null;if (extendMode && extendOptions && output?.width && output.height) {try { extendSize = extendOutputDimensions(config, { width: output.width, height: output.height }, extendOptions.bounds); }@@ -524,7 +527,7 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene{/* Generate and the generator lead; canvas tools and view controlsshare the centered group. */}<div className="image-tools__start">- {(!extendMode || active) && <button className="primary-button image-generate-button" data-tooltip={editPlan?.error ?? undefined} disabled={active ? work.cancelling || work.status === "encoding" : !isTauri() || !template || !templateUsable(template) || (imageRoot ? Boolean(editPlan?.error) : !imageScenePrompt(scene))} onClick={() => attempt(() => active ? onCancel(work.id) : onGenerate(template!))}>{active ? <Stop14 aria-hidden="true" /> : <Sparkle16 aria-hidden="true" />}{active ? work.cancelling ? "Cancelling…" : "Cancel" : "Generate"}</button>}+ {(!extendMode || active) && <button className="primary-button image-generate-button" data-tooltip={editPlan?.error ?? undefined} disabled={active ? work.cancelling || work.status === "encoding" : Boolean(templateSnapshot && output?.imageDraft) || !isTauri() || !template || !templateUsable(template) || (imageRoot ? Boolean(editPlan?.error) : !imageScenePrompt(scene))} onClick={() => attempt(() => active ? onCancel(work.id) : onGenerate(template!))}>{active ? <Stop14 aria-hidden="true" /> : <Sparkle16 aria-hidden="true" />}{active ? work.cancelling ? "Cancelling…" : "Cancel" : "Generate"}</button>}<ComboBoxclassName="image-generator"aria-label="Generator"@@ -628,7 +631,7 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene{ label: "Create Reference", icon: <References16 />, disabled: !canUseMenuImage, action: () => attempt(() => createFromImage(imageMenu.id!, false)) },{ label: "Remove", icon: <Delete16 />, danger: true,separator: true,- disabled: workItems.some((item) => isWorkActive(item) && item.imageAssetId === imageMenu.id) || (!imageMenu.inFamily && imageFamily(images, imageMenu.id).length > 1),+ disabled: workItems.some((item) => isWorkActive(item) && (item.imageAssetId === imageMenu.id || item.imageDraftId === imageMenu.id || item.id === imageMenu.id)) || (!imageMenu.inFamily && imageFamily(images, imageMenu.id).length > 1),action: () => removeImage(imageMenu.id!) },] : []),]} />}@@ -661,7 +664,7 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGeneonPointerUpCapture={endPan} onPointerCancelCapture={endPan} onLostPointerCapture={endPan}onAuxClick={(event) => { if (event.button === 1) event.preventDefault(); }}><div className="image-frame" style={{ "--image-ratio": width / height, "--image-zoom": view.zoom, "--image-pan-x": `${view.x}px`, "--image-pan-y": `${view.y}px` } as CSSProperties}>- {imageRoot && scene.sourceImage ? <ReferenceImage folderPath={folderPath} relativePath={scene.sourceImage.relativePath} alt={scene.sourceImage.name} /> : output && !imageRoot && (output.relativePath || output.sourcePath) ? <ReferenceImage key={output.id} folderPath={folderPath} relativePath={output.relativePath} sourcePath={output.sourcePath} alt={output.name} onMeasured={!output.imageGeneration ? (size) => measureImportedImage(output.id, size) : undefined} /> : <div className="image-empty"><Image32 aria-hidden="true" /><strong>{imageRoot ? "Add an image to edit" : "Compose your image"}</strong><span>{imageRoot ? "Choose Add image file in the image bar menu, then enter an edit prompt." : "Add objects, text and groups, then describe them in the inspector."}</span></div>}+ {imageRoot && scene.sourceImage ? <ReferenceImage folderPath={folderPath} relativePath={scene.sourceImage.relativePath} alt={scene.sourceImage.name} /> : output && !imageRoot && (output.relativePath || output.sourcePath) ? <ReferenceImage key={output.id} folderPath={folderPath} relativePath={output.relativePath} sourcePath={output.sourcePath} alt={output.name} onMeasured={!output.imageGeneration ? (size) => measureImportedImage(output.id, size) : undefined} /> : <div className="image-empty"><Image32 aria-hidden="true" /><strong>{templateSnapshot ? output!.name : imageRoot ? "Add an image to edit" : "Compose your image"}</strong><span>{templateSnapshot ? active ? "The generated image will appear here." : "No generated image yet." : imageRoot ? "Choose Add image file in the image bar menu, then enter an edit prompt." : "Add objects, text and groups, then describe them in the inspector."}</span></div>}<svg className={`image-overlay ${drawKind ? "drawing" : ""}`} viewBox="0 0 1000 1000" preserveAspectRatio="none" aria-label="Image placement canvas" onPointerDown={pointerDown} onPointerMove={pointerMove} onPointerUp={pointerUp} onPointerCancel={() => { pointer.current = null; setDraftBox(null); }}>{boxes && scene.nodes.filter((node) => node.box).map((node) => {const box = pointer.current?.id === node.id && draftBox ? draftBox : node.box!;@@ -672,7 +675,7 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene{boxes && scene.nodes.filter((node) => node.box).map((node) => { const box = pointer.current?.id === node.id && draftBox ? draftBox : node.box!; return <span key={node.id} className="image-box-label" style={{ left: `${box.x / 10}%`, top: `${box.y / 10}%` }}>{node.name}</span>; })}</div></div>}{(error || work?.error) && <InfoBar className="image-error" severity="error" title="Couldn’t update the image" message={error ?? work?.error ?? ""} onClose={error ? () => setError(null) : undefined} />}- <div className="image-status" role="status">{active && <ProgressBar value={work.progress * 100} aria-label="Image generation progress" />}<span>{active ? work.detail : extendMode && extendOptions ? `Extend: ${extendSize?.width ?? "-"} \u00d7 ${extendSize?.height ?? "-"} px` : imageRoot ? editPlan?.error ?? `${width} × ${height} · ${editPlan?.edits.length} edits in hierarchy order` : !isTauri() ? "Image generation is available in the desktop app." : `${width} × ${height}${isMiniMaxH3 ? "" : " · Placement boxes guide the prompt"}`}</span></div>+ <div className="image-status" role="status">{active && <ProgressBar value={work.progress * 100} aria-label="Image generation progress" />}<span>{active ? work.detail : extendMode && extendOptions ? `Extend: ${extendSize?.width ?? "-"} \u00d7 ${extendSize?.height ?? "-"} px` : templateSnapshot ? `${templateSnapshot.kind === "extend" ? "Extend" : "Character sheet"} · ${width} × ${height} px` : imageRoot ? editPlan?.error ?? `${width} × ${height} · ${editPlan?.edits.length} edits in hierarchy order` : !isTauri() ? "Image generation is available in the desktop app." : `${width} × ${height}${isMiniMaxH3 ? "" : " · Placement boxes guide the prompt"}`}</span></div><ImageBar ref={imageResults} images={images} selectedId={scene.outputAssetId} folderPath={folderPath} onSelect={selectImage}onMenu={(id, x, y, inFamily) => { setContextMenu(null); setImageMenu({ id, x, y, inFamily, source: "bar" }); }} /></section>@@ -685,6 +688,14 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGeneconfig={config} source={output} references={promptReferences} missingLabel={missingReference} defaultSteps={template?.defaultSteps ?? 20} busy={Boolean(active)}disabledReason={!isTauri() ? "Template execution is available in the desktop app." : !onGenerateCharacterSheet || !template || !templateUsable(template) ? "Choose a downloaded generator to execute this template." : null}onExecute={(options) => onGenerateCharacterSheet?.(template!, output.id, options)} onClose={() => setTemplateSourceId(null)}+ /> : runningTemplate && templateSource ? runningTemplate.kind === "extend" ? <ExtendSettings+ config={config} source={templateSource} options={runningTemplate} onChange={() => {}}+ references={promptReferences} missingLabel={missingReference} busy disabledReason={null}+ onExecute={() => {}} onClose={() => selectImage(templateSource.id)}+ /> : <CharacterSheetSettings key={output!.id}+ config={config} source={templateSource} initialOptions={runningTemplate} defaultSteps={runningTemplate.steps}+ references={promptReferences} missingLabel={missingReference} busy disabledReason={null}+ onExecute={() => {}} onClose={() => selectImage(templateSource.id)}/> : <aside className="image-inspector" aria-label="Image node inspector">{/* The selected node heads the inspector, not an "Inspector" title. */}{/* The name is edited in place in the header, as a shot's or a clip'sdiff --git a/src/lib/characterSheet.test.ts b/src/lib/characterSheet.test.tsindex 36c08a6..b54bf64 100644--- a/src/lib/characterSheet.test.ts+++ b/src/lib/characterSheet.test.ts@@ -1,5 +1,6 @@// @vitest-environment jsdomimport { waitFor } from "@testing-library/react";+import { restoreGeneratedImage, saveImageDraft } from "./imageHistory";import { invoke } from "@tauri-apps/api/core";import { listen } from "@tauri-apps/api/event";import { afterEach, beforeEach, expect, it, vi } from "vitest";@@ -52,6 +53,14 @@ it.each([false, true])("uses a shared front-view outfit with square portrait andqueue.enqueueCharacterSheet(session, template, "source");expect(queue.getSnapshot()).toHaveLength(1);const id = queue.getSnapshot()[0].id;+ const pending = parseProjectConfig(JSON.parse(JSON.stringify(session.getSnapshot().config)));+ expect(pending.assets).toHaveLength(2);+ expect(pending.assets[1]).toMatchObject({ id, imageDraft: true, parentAssetId: "source", width: 2752, height: 1024,+ imageGeneration: { template: { kind: "character-sheet", sourceId: "source", sourceName: "Hero", generatorName: template.name, prompt: "", height: 1024 } } });+ expect(pending.assets[1].relativePath).toBeUndefined();+ expect(pending.imageScene!.outputAssetId).toBe(id);+ expect(queue.getSnapshot()[0].imageDraftId).toBe(id);+ expect(saveImageDraft(restoreGeneratedImage(pending, id)).assets).toEqual(pending.assets);let seed: number | undefined;const order = [1, 0, 2, 3];for (let index = 0; index < 4; index++) {@@ -75,8 +84,9 @@ it.each([false, true])("uses a shared front-view outfit with square portrait andexpect(request.prompt).toContain("head and body facing away, face hidden");}expect(request.prompt).not.toContain("A still photograph");- expect(session.getSnapshot().config.assets).toEqual(original.assets);- if (changed && index === 0) session.update((current) => ({ ...current, imageScene: { ...current.imageScene!, nodes: current.imageScene!.nodes.map((node) => ({ ...node, description: "Changed during generation" })) } }));+ expect(session.getSnapshot().config.assets[0]).toEqual(original.assets[0]);+ expect(session.getSnapshot().config.assets[1]).toMatchObject({ id, imageDraft: true });+ if (changed && index === 0) session.update((current) => restoreGeneratedImage(current, "source"));emit("framesReady", request.jobId);if (index < 3) {await waitFor(() => expect(releaseRendered).toHaveBeenCalledWith(request.jobId));@@ -89,6 +99,8 @@ it.each([false, true])("uses a shared front-view outfit with square portrait andexpect(reopened.assets[0]).toEqual(original.assets[0]);expect(reopened.assets[1]).toMatchObject({ id, name: "Character sheet - Hero", mimeType: "image/png", ...result, imageGeneration: { usedSeed: seed } });expect(reopened.assets[1].parentAssetId).toBe("source");+ expect(reopened.assets[1].imageDraft).toBe(false);+ expect(reopened.assets[1].imageGeneration!.template).toEqual(pending.assets[1].imageGeneration!.template);expect(reopened.imageScene!.outputAssetId).toBe(changed ? "source" : id);expect(reopened.generationJobs).toEqual(original.generationJobs);expect(reopened.timeline).toEqual(original.timeline);@@ -149,7 +161,6 @@ it("keeps the required view after template instructions without repeating orientit.each([0, 12345, -1])("uses template steps and seed %s for every view and saved settings", async (seed) => {const { queue, session } = setup();- const original = structuredClone(session.getSnapshot().config.imageScene);const options = { prompt: "", steps: 37, seed };queue.enqueueCharacterSheet(session, template, "source", options);options.steps = 10; options.seed = 999;@@ -161,12 +172,12 @@ it.each([0, 12345, -1])("uses template steps and seed %s for every view and savefor (let index = 0; index < 4; index++) {const request = await requestAt(index);expect(request).toMatchObject({ steps: 37, seed: usedSeed });- expect(session.getSnapshot().config.imageScene).toEqual(original);+ expect(session.getSnapshot().config.imageScene).toMatchObject({ outputAssetId: queue.getSnapshot()[0].id, steps: 37, seed });emit("framesReady", request.jobId);}await waitFor(() => expect(queue.getSnapshot()[0].status).toBe("completed"));const reopened = parseProjectConfig(JSON.parse(JSON.stringify(session.getSnapshot().config)));- expect(reopened.assets.at(-1)?.imageGeneration).toMatchObject({ usedSeed, scene: { steps: 37, seed } });+ expect(reopened.assets.at(-1)?.imageGeneration).toMatchObject({ usedSeed, scene: { steps: 37, seed }, template: { steps: 37, seed } });});it.each([{ steps: 1 }, { steps: 1001 }, { steps: 2.5 }, { steps: NaN }, { seed: -2 }, { seed: 0.5 }, { seed: Number.MAX_SAFE_INTEGER + 1 }])("rejects invalid template sampling settings %j", (settings) => {@@ -188,7 +199,8 @@ it.each(["cancelled", "failed"])("discards partial views after the second render}emit(state, second.jobId, "Stopped second view");await waitFor(() => expect(queue.getSnapshot()[0].status).toBe(state));- expect(session.getSnapshot().config.assets).toHaveLength(1);+ expect(session.getSnapshot().config.assets).toHaveLength(2);+ expect(session.getSnapshot().config.assets[1]).toMatchObject({ id, imageDraft: true });expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(2);expect(invoke).not.toHaveBeenCalledWith("combine_character_sheet", expect.anything());expect(invoke).toHaveBeenCalledWith("discard_character_sheet_views", { folderPath: "C:/Character", sheetId: id });@@ -264,7 +276,8 @@ it("does not publish a partial result when combining fails and lets the next jobqueue.enqueueCharacterSheet(session, template, "another");for (let index = 0; index < 4; index++) emit("framesReady", (await requestAt(index)).jobId);await waitFor(() => expect(queue.getSnapshot()[0]).toMatchObject({ status: "failed", error: "Could not combine views" }));- expect(session.getSnapshot().config.assets.map((asset) => asset.id)).toEqual(["source", "another"]);+ expect(session.getSnapshot().config.assets.map((asset) => asset.id)).toEqual(["source", id, "another", queue.getSnapshot()[1].id]);+ expect(session.getSnapshot().config.assets.filter((asset) => asset.imageDraft)).toHaveLength(2);expect(invoke).toHaveBeenCalledWith("discard_character_sheet_views", { folderPath: "C:/Character", sheetId: id });const next = await requestAt(4);await queue.cancel(queue.getSnapshot()[1].id);diff --git a/src/lib/extendWork.test.ts b/src/lib/extendWork.test.tsindex c1833a4..51aba49 100644--- a/src/lib/extendWork.test.ts+++ b/src/lib/extendWork.test.ts@@ -9,6 +9,7 @@ import { cancelSlopfabGeneration, enqueueSlopfabGeneration, resolveSlopfabPlan }import { EMPTY_ENGINE_SETTINGS, type GeneratorTemplate } from "./settings";import { WorkQueue } from "./workQueue";import type { ExtendOptions } from "./extendImage";+import { restoreGeneratedImage, saveImageDraft } from "./imageHistory";vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn() }));@@ -52,6 +53,14 @@ it.each([false, true])("extends a frozen source and saves a child with a durablequeue.enqueueExtendImage(session, template, "source", input);input.bounds.width = 999; input.prompt = "Changed";expect(queue.getSnapshot()).toHaveLength(1);+ const pending = parseProjectConfig(JSON.parse(JSON.stringify(session.getSnapshot().config)));+ const entry = pending.assets.at(-1)!;+ expect(entry).toMatchObject({ id: queue.getSnapshot()[0].id, imageDraft: true, parentAssetId: "root", width: 128, height: 64,+ imageGeneration: { template: { kind: "extend", sourceId: "source", sourceName: "source", generatorName: "H3", ...options() } } });+ expect(entry.relativePath).toBeUndefined();+ expect(pending.imageScene!.outputAssetId).toBe(entry.id);+ expect(queue.getSnapshot()[0].imageDraftId).toBe(entry.id);+ expect(saveImageDraft(restoreGeneratedImage(pending, entry.id)).assets).toEqual(pending.assets);const request = await submitted();const { jobId } = request;expect(request).toMatchObject({ stillImage: true, frames: 1, seed: 0, steps: 25, canvasWidth: 128, canvasHeight: 64,@@ -63,7 +72,7 @@ it.each([false, true])("extends a frozen source and saves a child with a durableexpect(request.prompt).toContain("Continue the forest");expect(request.prompt).not.toContain("Changed");expect(invoke).toHaveBeenCalledWith("prepare_extend_image", { folderPath: "C:/Extend", jobId, sourceId: "source", bounds: options().bounds, output: { width: 128, height: 64 } });- if (changed) session.update((config) => ({ ...config, imageScene: { ...config.imageScene!, nodes: config.imageScene!.nodes.map((node) => ({ ...node, description: "New prompt" })) } }));+ if (changed) session.update((config) => restoreGeneratedImage(config, "source"));emit("framesReady", jobId);await waitFor(() => expect(queue.getSnapshot()[0].status).toBe("completed"));const reopened = parseProjectConfig(JSON.parse(JSON.stringify(session.getSnapshot().config)));@@ -71,6 +80,9 @@ it.each([false, true])("extends a frozen source and saves a child with a durableexpect(asset).toMatchObject({ id: jobId, name: "Extended - source", parentAssetId: "root", mimeType: "image/png", ...result,imageGeneration: { usedSeed: 0, scene: { steps: 25, seed: 0, sourceImage: { ...result } } } });expect(reopened.assets.slice(0, 2)).toEqual(initial.assets);+ expect(reopened.assets).toHaveLength(3);+ expect(asset.imageDraft).toBe(false);+ expect(asset.imageGeneration!.template).toEqual(entry.imageGeneration!.template);expect(reopened.imageScene!.outputAssetId).toBe(changed ? "source" : jobId);expect(JSON.stringify(asset)).not.toContain("cache/extend-images");expect(invoke).toHaveBeenCalledWith("save_extended_image", { folderPath: "C:/Extend", jobId });@@ -102,7 +114,8 @@ it.each(["failed", "cancelled"])("does not publish a result after generation isemit(state, request.jobId);await waitFor(() => expect(queue.getSnapshot()[0].status).toBe(state));await waitFor(() => expect(invoke).toHaveBeenCalledWith("discard_extend_image", { folderPath: "C:/Extend", jobId: request.jobId }));- expect(session.getSnapshot().config.assets).toHaveLength(2);+ expect(session.getSnapshot().config.assets).toHaveLength(3);+ expect(session.getSnapshot().config.assets.at(-1)).toMatchObject({ id: request.jobId, imageDraft: true });expect(vi.mocked(invoke).mock.calls.some(([command]) => command === "save_extended_image")).toBe(false);});diff --git a/src/lib/imageHistory.test.ts b/src/lib/imageHistory.test.tsindex 4156ff4..6fc8e75 100644--- a/src/lib/imageHistory.test.ts+++ b/src/lib/imageHistory.test.ts@@ -1,11 +1,35 @@import { describe, expect, it } from "vitest";-import { completeImageDraft, imageFamily, imageFamilyRoot, imageGenerationSnapshot, makeImagePrimary, removeImageAsset, restoreGeneratedImage, saveImageDraft } from "./imageHistory";+import { completeImageDraft, createTemplateImageDraft, imageFamily, imageFamilyRoot, imageGenerationSnapshot, makeImagePrimary, removeImageAsset, restoreGeneratedImage, saveImageDraft } from "./imageHistory";import { imageGenerationSnapshotSchema, parseProjectConfig } from "./project";import fixture from "../../fixtures/project-v1-image.json";import snapshotFixture from "../../fixtures/image-generation-snapshot.json";-import { createImageEditScene } from "./imageScene";+import { createImageEditScene, createImageScene } from "./imageScene";describe("generated image history", () => {+ it("keeps a submitted template intact when editing its pending entry and completing in the background", () => {+ const config = parseProjectConfig(fixture);+ config.imageScene = createImageScene("Forest");+ const source = { id: "source", kind: "image" as const, name: "Original", relativePath: "media/original.png", width: 512, height: 512, mimeType: "image/png", createdAt: config.createdAt };+ config.assets = [source];+ const generation = { ...imageGenerationSnapshot(config, "Frozen prompt", "generator"), usedSeed: 12,+ template: { kind: "extend" as const, sourceId: source.id, sourceName: source.name, generatorName: "Default", prompt: "Forest", steps: 20, seed: -1,+ bounds: { x: -32, y: 0, width: 768, height: 512 } } };+ const pending = createTemplateImageDraft(config, "job", "Extended image", generation, { width: 512, height: 320 });+ const scene = structuredClone(pending.imageScene!);+ scene.nodes[0].description = "A new idea";+ const edited = saveImageDraft({ ...pending, imageScene: scene });+ const draft = edited.assets.at(-1)!;+ expect(draft).toMatchObject({ imageDraft: true, parentAssetId: "source", imageGeneration: { scene: { nodes: [{ description: "A new idea" }] } } });+ expect(draft.id).not.toBe("job");+ expect(draft.imageGeneration!.template).toBeUndefined();+ expect(edited.assets[1]).toEqual(pending.assets[1]);+ const result = { ...source, id: "job", name: "Extended image", relativePath: "media/extended.png" };+ const done = completeImageDraft(edited, "job", { ...result, imageGeneration: { ...generation, scene: createImageEditScene(result) } });+ expect(done.imageScene!.outputAssetId).toBe(draft.id);+ expect(done.assets).toHaveLength(3);+ expect(done.assets[1]).toMatchObject({ imageDraft: false, imageGeneration: { template: generation.template, usedSeed: 12 } });+ expect(done.assets[2]).toEqual(draft);+ });it("preserves a whole-image prompt and linked references as a new draft of a saved image", () => {const config = parseProjectConfig(fixture);const source = { relativePath: "media/generated/source.png", name: "Source", width: 101, height: 77 };diff --git a/src/lib/imageHistory.ts b/src/lib/imageHistory.tsindex 498b652..cd64540 100644--- a/src/lib/imageHistory.ts+++ b/src/lib/imageHistory.ts@@ -61,13 +61,17 @@ export function saveImageDraft(config: ProjectConfig, generatorTemplateId?: striconst scene = config.imageScene;if (!scene) return config;const selected = config.assets.find((asset) => asset.id === scene.outputAssetId);+ // Template entries record a submitted job. Selecting one must not replace its+ // recipe with the editor's generic image settings. Edits become another draft.+ const templateDraft = selected?.imageDraft && selected.imageGeneration?.template;+ if (templateDraft && JSON.stringify({ ...scene, outputAssetId: null }) === JSON.stringify(selected.imageGeneration!.scene)) return config;const source = scene.rootType === "image" ? scene.sourceImage : null;if (!source && !selected?.imageDraft) return config;if (!selected?.imageDraft && scene.outputAssetId && scene.nodes.length === 1 && !scene.nodes[0].description.trim()) return config;- const existing = selected?.imageDraft ? selected : undefined;+ const existing = selected?.imageDraft && !templateDraft ? selected : undefined;const id = existing?.id ?? `image-draft-${crypto.randomUUID()}`;const edited = source && config.assets.find((asset) => asset.kind === "image" && !asset.imageDraft && asset.relativePath === source.relativePath);- const parentAssetId = existing ? existing.parentAssetId : imageFamilyRoot(config.assets, edited?.id);+ const parentAssetId = existing ? existing.parentAssetId : imageFamilyRoot(config.assets, templateDraft ? selected.id : edited?.id);const snapshot = imageGenerationSnapshot(config, "", generatorTemplateId || existing?.imageGeneration?.generatorTemplateId || selected?.imageGeneration?.generatorTemplateId || "image-draft");if (existing && JSON.stringify(existing.imageGeneration) === JSON.stringify(snapshot)) return config;const asset = { id, kind: "image" as const, ...source, name: existing?.name ?? (source ? `Editing ${source.name}` : "New image"),@@ -88,10 +92,18 @@ export function createEmptyImage(config: ProjectConfig, generatorTemplateId?: streturn { ...next, assets: [...config.assets, asset] };}+/** Publish the selectable entry before a template job starts using the engine. */+export function createTemplateImageDraft(config: ProjectConfig, id: string, name: string, generation: ImageGenerationSnapshot, size: { width: number; height: number }): ProjectConfig {+ const parentAssetId = imageFamilyRoot(config.assets, generation.template!.sourceId);+ const asset: ProjectAsset = { id, kind: "image", name, mimeType: "image/png", ...size, imageDraft: true,+ parentAssetId, imageGeneration: structuredClone(generation), createdAt: new Date().toISOString() };+ return restoreGeneratedImage({ ...config, assets: [...config.assets, asset] }, id);+}+export function completeImageDraft(config: ProjectConfig, id: string, result: ProjectAsset): ProjectConfig {const draft = config.assets.find((asset) => asset.id === id && asset.imageDraft);const selected = config.imageScene?.outputAssetId === id;- const changed = draft && JSON.stringify({ ...draft.imageGeneration, prompt: "", usedSeed: undefined }) !== JSON.stringify({ ...result.imageGeneration, prompt: "", usedSeed: undefined });+ const changed = draft && !draft.imageGeneration?.template && JSON.stringify({ ...draft.imageGeneration, prompt: "", usedSeed: undefined }) !== JSON.stringify({ ...result.imageGeneration, prompt: "", usedSeed: undefined });// Edits made during generation remain a separate draft on the original source.const pending = changed ? { ...draft, id: `image-draft-${crypto.randomUUID()}` } : null;const asset = { ...result, id, imageDraft: false, ...(draft?.parentAssetId ? { parentAssetId: draft.parentAssetId } : {}) };diff --git a/src/lib/project.ts b/src/lib/project.tsindex 906cc35..6a2c22a 100644--- a/src/lib/project.ts+++ b/src/lib/project.ts@@ -138,6 +138,17 @@ export const LEGACY_RESOLUTIONS = ["720p", "1080p", "4k"] as const;export const resolutionSchema = z.enum([...PROJECT_RESOLUTIONS, ...LEGACY_RESOLUTIONS]);+const imageTemplateFields = {+ sourceId: z.string().min(1), sourceName: z.string().min(1), generatorName: z.string().min(1),+ prompt: z.string(), steps: z.number().int().min(2).max(1000), seed: z.number().int().min(-1).max(Number.MAX_SAFE_INTEGER),+};+const imageTemplateSnapshotSchema = z.discriminatedUnion("kind", [+ z.object({ ...imageTemplateFields, kind: z.literal("extend"), bounds: z.object({+ x: z.number().finite(), y: z.number().finite(), width: z.number().positive().finite(), height: z.number().positive().finite(),+ }) }),+ z.object({ ...imageTemplateFields, kind: z.literal("character-sheet"), height: z.number().int().refine((height) => [512, 1024, 1536, 2048].includes(height), "Unsupported character sheet height.") }),+]);+export const imageGenerationSnapshotSchema = z.object({scene: imageSceneSchema,resolution: resolutionSchema,@@ -147,6 +158,7 @@ export const imageGenerationSnapshotSchema = z.object({prompt: z.string(),generatorTemplateId: z.string().min(1),usedSeed: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional(),+ template: imageTemplateSnapshotSchema.optional(),references: z.array(z.lazy(() => projectReferenceSchema)).max(100),}).superRefine((snapshot, context) => {const ids = new Set(snapshot.references.map((reference) => reference.id));diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.tsindex c9dd0b7..818c02d 100644--- a/src/lib/workQueue.ts+++ b/src/lib/workQueue.ts@@ -5,7 +5,7 @@ import { compileImageEdits, imageEditDebugPrompt } from "./imageEditing";import { compileImagePrompt } from "./imagePrompt";import { compileExtendImage, type ExtendOptions } from "./extendImage";import { CHARACTER_SHEET_ORDER, CHARACTER_SHEET_VIEWS, characterSheetDimensions, compileCharacterSheet, type CharacterSheetOptions } from "./characterSheet";-import { completeImageDraft, imageFamilyRoot, imageGenerationSnapshot, saveImageDraft } from "./imageHistory";+import { completeImageDraft, createTemplateImageDraft, imageFamilyRoot, imageGenerationSnapshot, saveImageDraft } from "./imageHistory";import type { ImageGenerationSnapshot } from "./project";import { outputDimensions } from "./export";import { projectItemPath, referenceDefinition, referenceImages, referenceRefmodInputs } from "./project";@@ -318,13 +318,19 @@ export class WorkQueue {imageEdit: { sourceRelativePath, edits: compiled.edits } };let finish!: () => void;const done = new Promise<void>((resolve) => { finish = resolve; });- this.work.set(id, { id, image: true, extend: { sourceId, name: `Extended - ${source.name}`, options: structuredClone(options) }, imageParentId: sourceId,- imageGeneration: { ...imageGenerationSnapshot({ ...config, imageScene: compiled.scene }, compiled.prompt, template.id), usedSeed: request.seed },+ const imageGeneration: ImageGenerationSnapshot = {+ ...imageGenerationSnapshot({ ...config, imageScene: { ...createImageScene(options.prompt), steps: request.steps, seed: options.seed } }, compiled.prompt, template.id),+ usedSeed: request.seed,+ template: { kind: "extend", sourceId, sourceName: source.name, generatorName: template.name, ...structuredClone(options), steps: request.steps },+ };+ this.work.set(id, { id, image: true, imageDraftId: id, extend: { sourceId, name: `Extended - ${source.name}`, options: structuredClone(options) }, imageParentId: sourceId,+ imageGeneration,session, sceneId: current.imageScene?.nodes[0].id ?? "image-root", config, snapshot: JSON.stringify(current.imageScene), request, submitted: false, cancelled: false, done, finish });- this.items = [...this.items, { id, kind: "image", imageAssetId: sourceId, projectKey, folderPath: session.record.folderPath, projectName: config.name,+ this.items = [...this.items, { id, kind: "image", imageAssetId: sourceId, imageDraftId: id, projectKey, folderPath: session.record.folderPath, projectName: config.name,sceneId: this.work.get(id)!.sceneId, title: `Extend · ${source.name}`, submittedAt: new Date().toISOString(), status: "queued", progress: 0,detail: "Waiting to extend image", error: null, completionAt: null, cancelling: false, needsSave: false,settings: { frames: 1, steps: request.steps, seed: request.seed, canvasWidth: request.canvasWidth, canvasHeight: request.canvasHeight } }];+ session.update((current) => createTemplateImageDraft(current, id, `Extended - ${source.name}`, imageGeneration, compiled.layout.output));this.publish(); this.icons.yieldToVideo(); void this.pump();}enqueueCharacterSheet(session: ProjectSession, template: GeneratorTemplate, sourceId: string, options?: CharacterSheetOptions) {@@ -353,15 +359,23 @@ export class WorkQueue {seed: imageGenerationSeed(config.imageScene.seed),referencePaths: views[firstView].references.flatMap((reference) => referenceImages(reference).map((image) => projectItemPath(session.record.folderPath, image)!)),refmods: referenceRefmodInputs(session.record.folderPath, views[firstView].references) };- this.work.set(id, { id, image: true, characterSheet: { views, dimensions, sourceId, name: `Character sheet - ${source.name}`, index: 0 },- imageGeneration: { ...imageGenerationSnapshot(config, views.map((view) => view.prompt).join("\n\n"), template.id), usedSeed: request.seed,- references: [...new Map(views.flatMap((view) => view.references.slice(1)).map((reference) => [reference.id, reference])).values()] },+ const imageGeneration: ImageGenerationSnapshot = {+ ...imageGenerationSnapshot({ ...config, imageScene: { ...createImageScene(options?.prompt ?? ""), steps: request.steps, seed: config.imageScene.seed } }, views.map((view) => view.prompt).join("\n\n"), template.id),+ usedSeed: request.seed,+ references: [...new Map(views.flatMap((view) => view.references.slice(1)).map((reference) => [reference.id, reference])).values()],+ template: { kind: "character-sheet", sourceId, sourceName: source.name, generatorName: template.name, prompt: options?.prompt ?? "",+ height, steps: request.steps, seed: config.imageScene.seed },+ };+ this.work.set(id, { id, image: true, imageDraftId: id, characterSheet: { views, dimensions, sourceId, name: `Character sheet - ${source.name}`, index: 0 },+ imageGeneration,session, sceneId: current.imageScene?.nodes[0].id ?? "image-root", config, snapshot: JSON.stringify(current.imageScene),request, submitted: false, cancelled: false, done, finish });- this.items = [...this.items, { id, kind: "image", imageAssetId: sourceId, projectKey, folderPath: session.record.folderPath, projectName: config.name,+ this.items = [...this.items, { id, kind: "image", imageAssetId: sourceId, imageDraftId: id, projectKey, folderPath: session.record.folderPath, projectName: config.name,sceneId: this.work.get(id)!.sceneId, title: `Character sheet · ${source.name}`, submittedAt: new Date().toISOString(),status: "queued", progress: 0, detail: "Waiting to generate character sheet", error: null, completionAt: null, cancelling: false, needsSave: false,settings: { frames: 4, steps: request.steps, seed: request.seed, canvasWidth: width, canvasHeight: height } }];+ session.update((current) => createTemplateImageDraft(current, id, `Character sheet - ${source.name}`, imageGeneration,+ { width: dimensions.reduce((total, view) => total + view.width, 0), height }));this.publish(); this.icons.yieldToVideo(); void this.pump();}/** Queues encoding one reference's images, video or sound into a refmod file. */@@ -611,11 +625,9 @@ export class WorkQueue {const scene = createImageEditScene({ ...saved, name: sheet.name }, work.config.imageScene ?? undefined);scene.referenceIds = [];const generation = { ...work.imageGeneration!, scene };- work.session.update((current) => ({ ...current,- ...(current.imageScene?.outputAssetId === sheet.sourceId && JSON.stringify(current.imageScene) === work.snapshot- ? { thumbnail: saved.relativePath, imageScene: { ...scene, outputAssetId: work.id } } : {}),- assets: [...current.assets, { id: work.id, kind: "image", name: sheet.name, ...saved, mimeType: "image/png",- parentAssetId: imageFamilyRoot(current.assets, sheet.sourceId), imageGeneration: generation, createdAt: new Date().toISOString() }],+ work.session.update((current) => completeImageDraft(current, work.id, {+ id: work.id, kind: "image", name: sheet.name, ...saved, mimeType: "image/png",+ parentAssetId: imageFamilyRoot(current.assets, sheet.sourceId), imageGeneration: generation, createdAt: new Date().toISOString(),}));try { await work.session.save(); this.patch(work.id, { status: "completed", progress: 1, detail: "Character sheet saved" }); }catch (reason) { this.patch(work.id, { status: "failed", progress: 1, needsSave: true, detail: "Character sheet created; project save failed", error: describeDiagnosticError(reason) }); }@@ -683,11 +695,9 @@ export class WorkQueue {if (work.extend) {const scene = createImageEditScene({ ...saved, name: work.extend.name }, { ...work.config.imageScene!, steps: work.request.steps, seed: work.request.seed });work.imageGeneration = { ...work.imageGeneration!, scene };- work.session.update((current) => ({ ...current,- ...(current.imageScene?.outputAssetId === work.extend!.sourceId && JSON.stringify(current.imageScene) === work.snapshot- ? { thumbnail: saved.relativePath, imageScene: { ...scene, outputAssetId: work.id } } : {}),- assets: [...current.assets, { id: work.id, kind: "image", name: work.extend!.name, ...saved, mimeType: "image/png",- parentAssetId: imageFamilyRoot(current.assets, work.extend!.sourceId), imageGeneration: work.imageGeneration, createdAt: new Date().toISOString() }],+ work.session.update((current) => completeImageDraft(current, work.id, {+ id: work.id, kind: "image", name: work.extend!.name, ...saved, mimeType: "image/png",+ parentAssetId: imageFamilyRoot(current.assets, work.extend!.sourceId), imageGeneration: work.imageGeneration, createdAt: new Date().toISOString(),}));} else {work.session.update((current) => work.imageDraftId ? completeImageDraft(current, work.imageDraftId, {