Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Group regenerated and edited images under their original in the image bar

Bittif6965c22f44d
diff --git a/src-tauri/src/project/commands/clips.rs b/src-tauri/src/project/commands/clips.rs
index a861981..d3e5794 100644
--- a/src-tauri/src/project/commands/clips.rs
+++ b/src-tauri/src/project/commands/clips.rs
@@ -63,6 +63,7 @@ pub(super) fn apply(
has_audio: None,
image_generation: None,
image_draft: None,
+ parent_asset_id: None,
created_at: job.created_at.clone(),
});
planned_id
diff --git a/src-tauri/src/project/model.rs b/src-tauri/src/project/model.rs
index 87deec9..2c31919 100644
--- a/src-tauri/src/project/model.rs
+++ b/src-tauri/src/project/model.rs
@@ -97,6 +97,10 @@ pub(crate) struct ProjectAsset {
pub(crate) image_generation: Option<super::image::ImageGenerationSnapshot>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) image_draft: Option<bool>,
+ /// The original image this one was regenerated or edited from; the image
+ /// bar shows a family as the original followed by these.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(crate) parent_asset_id: Option<String>,
pub(crate) created_at: String,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
diff --git a/src-tauri/src/project/validation/assets.rs b/src-tauri/src/project/validation/assets.rs
index 91619f5..768f189 100644
--- a/src-tauri/src/project/validation/assets.rs
+++ b/src-tauri/src/project/validation/assets.rs
@@ -23,6 +23,9 @@ pub(super) fn validate(config: &mut ProjectConfig) -> Result<(), String> {
return Err("Image generation snapshot has a missing reference.".into());
}
}
+ if asset.parent_asset_id.as_ref().is_some_and(|parent| asset.kind != "image" || parent.trim().is_empty() || *parent == asset.id) {
+ return Err(format!("Asset '{}' can only name another image as its parent.", asset.id));
+ }
if asset.id.trim().is_empty() || asset.name.trim().is_empty() {
return Err("Asset id and name cannot be empty.".into());
}
diff --git a/src-tauri/src/tests/media_access.rs b/src-tauri/src/tests/media_access.rs
index 5fecdaf..1e5949c 100644
--- a/src-tauri/src/tests/media_access.rs
+++ b/src-tauri/src/tests/media_access.rs
@@ -113,6 +113,7 @@ fn external_media_is_readable_only_because_the_project_names_it() {
has_audio: None,
image_generation: None,
image_draft: None,
+ parent_asset_id: None,
created_at: config.created_at.clone(),
});
let created = create_project_in(root.path(), &config).unwrap();
@@ -286,6 +287,7 @@ fn a_project_the_user_only_opened_reads_any_media_file_it_names() {
has_audio: None,
image_generation: None,
image_draft: None,
+ parent_asset_id: None,
created_at: config.created_at.clone(),
});
}
diff --git a/src-tauri/src/tests/persistence.rs b/src-tauri/src/tests/persistence.rs
index 3819ba7..cd8d366 100644
--- a/src-tauri/src/tests/persistence.rs
+++ b/src-tauri/src/tests/persistence.rs
@@ -390,6 +390,7 @@ fn a_project_file_only_yields_media_a_hand_edit_cannot_widen() {
has_audio: None,
image_generation: None,
image_draft: None,
+ parent_asset_id: None,
created_at: config.created_at.clone(),
});
let created = create_project_in(root.path(), &config).unwrap();
diff --git a/src/components/workspace/ImageBar.tsx b/src/components/workspace/ImageBar.tsx
index ebfcd9f..82c4b1d 100644
--- a/src/components/workspace/ImageBar.tsx
+++ b/src/components/workspace/ImageBar.tsx
@@ -1,6 +1,7 @@
-import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef, type KeyboardEvent } from "react";
+import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";
+import { imageFamilyRoot } from "../../lib/imageHistory";
import type { ProjectAsset } from "../../lib/project";
-import { Edit11, Image24 } from "../ui/icons";
+import { ChevronLeft16, Edit11, Image24 } from "../ui/icons";
import { ReferenceImage } from "./ReferenceImage";
import "../../styles/image-editor.css";
@@ -9,7 +10,12 @@ import "../../styles/image-editor.css";
draft badged. The mouse wheel scrolls it sideways, and a new image scrolls
into view at the end; the arrow keys step through it. `onMenu` opens a
context menu for an image (id) or for the bar (null) at a point; without it
- the bar has no menu. */
+ the bar has no menu.
+
+ An image regenerated or edited from another joins that image's family. The
+ bar lists the originals; while an image with a family is selected it shows
+ just that family — the original first, then the images made from it — with
+ a back button at its leading edge that returns to the originals. */
export const ImageBar = forwardRef<HTMLDivElement | null, {
images: ProjectAsset[];
selectedId: string | null | undefined;
@@ -20,12 +26,24 @@ export const ImageBar = forwardRef<HTMLDivElement | null, {
const bar = useRef<HTMLDivElement>(null);
useImperativeHandle(ref, () => bar.current as HTMLDivElement);
- const previousCount = useRef(images.length);
+ const root = imageFamilyRoot(images, selectedId);
+ const family = root ? images.filter((asset) => asset.id === root || imageFamilyRoot(images, asset.id) === root) : [];
+ // Selecting an image opens its family; Back shows the originals until the
+ // next selection.
+ const [showAll, setShowAll] = useState(false);
+ useEffect(() => setShowAll(false), [selectedId]);
+ const inFamily = !showAll && family.length > 1;
+ const originals = images.filter((asset) => imageFamilyRoot(images, asset.id) === asset.id);
+ const shown = inFamily ? [images.find((asset) => asset.id === root)!, ...family.filter((asset) => asset.id !== root)] : originals;
+ const pressed = inFamily ? selectedId : root;
+ const childCount = (id: string) => images.filter((asset) => asset.id !== id && imageFamilyRoot(images, asset.id) === id).length;
+
+ const previousCount = useRef(shown.length);
useLayoutEffect(() => {
const element = bar.current;
- if (element && images.length > previousCount.current) element.scrollLeft = element.scrollWidth;
- previousCount.current = images.length;
- }, [images.length]);
+ if (element && shown.length > previousCount.current) element.scrollLeft = element.scrollWidth;
+ previousCount.current = shown.length;
+ }, [shown.length]);
useEffect(() => {
const element = bar.current;
if (!element) return;
@@ -38,7 +56,7 @@ export const ImageBar = forwardRef<HTMLDivElement | null, {
};
element.addEventListener("wheel", wheel, { passive: false });
return () => element.removeEventListener("wheel", wheel);
- }, [images.length]);
+ }, [shown.length]);
/* Left and Right step the focus along the thumbnails, Home and End jump to
either end, and the bar scrolls to keep the focused one in view. Moving
@@ -72,7 +90,10 @@ export const ImageBar = forwardRef<HTMLDivElement | null, {
const bounds = event.currentTarget.getBoundingClientRect();
onMenu(null, bounds.left, bounds.top);
}}>
- {images.map((asset) => <button key={asset.id} type="button" data-image-asset={asset.id} data-tooltip={asset.name} aria-label={`View ${asset.name}`} aria-pressed={asset.id === selectedId}
+ {inFamily && <button type="button" className="image-results__back" aria-label="Back to all images" data-tooltip="All images"
+ onClick={() => { setShowAll(true); bar.current?.focus(); }}><ChevronLeft16 aria-hidden="true" /></button>}
+ {shown.map((asset) => <button key={asset.id} type="button" data-image-asset={asset.id} data-tooltip={asset.name}
+ aria-label={`View ${asset.name}${!inFamily && childCount(asset.id) ? `, ${childCount(asset.id) + 1} versions` : ""}`} aria-pressed={asset.id === pressed}
onContextMenu={onMenu && ((event) => { event.preventDefault(); event.stopPropagation(); onMenu(asset.id, event.clientX, event.clientY); })}
onKeyDown={onMenu && ((event) => {
if (!menuKey(event)) return;
@@ -80,8 +101,9 @@ export const ImageBar = forwardRef<HTMLDivElement | null, {
const bounds = event.currentTarget.getBoundingClientRect();
onMenu(asset.id, bounds.left, bounds.bottom);
})}
- onClick={() => onSelect(asset.id)}>
+ onClick={() => { setShowAll(false); onSelect(asset.id); }}>
{asset.relativePath || asset.sourcePath ? <ReferenceImage folderPath={folderPath} relativePath={asset.relativePath} sourcePath={asset.sourcePath} alt={asset.name} /> : <Image24 aria-hidden="true" />}
+ {!inFamily && childCount(asset.id) > 0 && <span className="image-family-badge" aria-hidden="true">{childCount(asset.id) + 1}</span>}
{asset.imageDraft && <span className="image-draft-badge"><Edit11 aria-hidden="true" />{asset.imageGeneration?.scene.rootType === "image" ? "Editing" : "Draft"}</span>}
</button>)}
</div>;
diff --git a/src/components/workspace/ImageEditor.test.tsx b/src/components/workspace/ImageEditor.test.tsx
index 3bc7b67..37ccfc6 100644
--- a/src/components/workspace/ImageEditor.test.tsx
+++ b/src/components/workspace/ImageEditor.test.tsx
@@ -119,7 +119,10 @@ it("starts an image root from the thumbnail Edit menu with edit tools and no typ
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();
- fireEvent.click(draft);
+ // The edit is in Saved's family, which the bar opens from Saved.
+ expect(screen.queryByRole("button", { name: "Back to all images" })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "View Saved, 2 versions" }));
+ fireEvent.click(screen.getByRole("button", { name: "View Editing Saved" }));
expect(current().imageScene!.sourceImage?.name).toBe("Saved");
});
@@ -512,3 +515,24 @@ it("heads the inspector with the selected node rather than an Inspector title",
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"]);
+});
diff --git a/src/components/workspace/ImageEditor.tsx b/src/components/workspace/ImageEditor.tsx
index c2c06bb..bbae5c5 100644
--- a/src/components/workspace/ImageEditor.tsx
+++ b/src/components/workspace/ImageEditor.tsx
@@ -5,7 +5,7 @@ import { addImageNode, createImageEditScene, createImageScene, duplicateImageNod
import { compileImageEdits, editGeneratedImage, imageEditDebugPrompt } from "../../lib/imageEditing";
import { outputDimensions } from "../../lib/export";
import { compileImagePrompt } from "../../lib/imagePrompt";
-import { createEmptyImage, restoreGeneratedImage, saveImageDraft } from "../../lib/imageHistory";
+import { createEmptyImage, removeImageAsset, restoreGeneratedImage, saveImageDraft } from "../../lib/imageHistory";
import { isTauri } from "../../lib/persistence";
import { PROJECT_RESOLUTIONS, referenceTypeLabel, type ProjectConfig } from "../../lib/project";
import { defaultGeneratorTemplate, loadDebugOptionsEnabled, loadGeneratorTemplateSettings, subscribeDebugOptions, subscribeGeneratorTemplates, templateNeedsDownload, type GeneratorTemplate } from "../../lib/settings";
@@ -195,7 +195,7 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene
? remaining[Math.min(currentImages.findIndex((asset) => asset.id === id), remaining.length - 1)]
: remaining.find((asset) => asset.id === currentScene.outputAssetId);
const updated = { ...current,
- assets: current.assets.filter((asset) => asset.id !== id),
+ assets: removeImageAsset(current.assets, id),
imageScene: removingSelected && removed.imageDraft && !next ? currentScene.rootType === "image" ? createImageEditScene(null, currentScene) : createImageScene() : { ...currentScene, outputAssetId: removingSelected ? next?.id ?? null : currentScene.outputAssetId },
thumbnail: removingSelected || current.thumbnail === removed.relativePath ? next?.relativePath ?? null : current.thumbnail,
timeline: { ...current.timeline, tracks: current.timeline.tracks.map((track) => ({ ...track, clips: track.clips.filter((clip) => clip.assetId !== id) })) },
diff --git a/src/lib/imageHistory.test.ts b/src/lib/imageHistory.test.ts
index 6d95520..d4c6571 100644
--- a/src/lib/imageHistory.test.ts
+++ b/src/lib/imageHistory.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { imageGenerationSnapshot, restoreGeneratedImage, saveImageDraft } from "./imageHistory";
+import { completeImageDraft, imageFamilyRoot, imageGenerationSnapshot, 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";
@@ -79,4 +79,30 @@ describe("generated image history", () => {
expect(restored.imageScene!.outputAssetId).toBe("legacy");
expect(restored.imageScene!.sourceImage).toBeUndefined();
});
+ it("puts an edit of any image in its original's family, one level deep", () => {
+ const config = parseProjectConfig(fixture);
+ const image = (id: string, parentAssetId?: string) => ({ id, name: id, kind: "image" as const, relativePath: `media/generated/${id}.png`, mimeType: "image/png", width: 101, height: 77, createdAt: config.createdAt, ...(parentAssetId ? { parentAssetId } : {}) });
+ config.assets = [image("original"), image("child", "original")];
+ expect(imageFamilyRoot(config.assets, "child")).toBe("original");
+ expect(imageFamilyRoot(config.assets, "original")).toBe("original");
+ // Editing the child starts a draft in the original's family, not the child's.
+ config.imageScene = createImageEditScene({ relativePath: "media/generated/child.png", name: "child", width: 101, height: 77 });
+ const drafted = saveImageDraft(config, "test");
+ const draft = drafted.assets.find((asset) => asset.imageDraft)!;
+ expect(draft.parentAssetId).toBe("original");
+ // Generating it keeps the family.
+ const done = completeImageDraft(drafted, draft.id, { ...image(draft.id), imageGeneration: draft.imageGeneration });
+ expect(done.assets.find((asset) => asset.id === draft.id)).toMatchObject({ imageDraft: false, parentAssetId: "original" });
+ expect(parseProjectConfig(JSON.parse(JSON.stringify(done))).assets).toEqual(done.assets);
+ // An imported file starts a family of its own.
+ config.imageScene = createImageEditScene({ relativePath: "media/imported/photo.png", name: "photo", width: 101, height: 77 });
+ expect(saveImageDraft(config, "test").assets.find((asset) => asset.imageDraft)!.parentAssetId).toBeUndefined();
+ });
+
+ it("keeps a family together when its original is removed", () => {
+ const config = parseProjectConfig(fixture);
+ const image = (id: string, parentAssetId?: string) => ({ id, name: id, kind: "image" as const, relativePath: `media/generated/${id}.jpg`, mimeType: "image/jpeg", createdAt: config.createdAt, ...(parentAssetId ? { parentAssetId } : {}) });
+ const assets = removeImageAsset([image("a"), image("b", "a"), image("c", "a"), image("d")], "a");
+ expect(assets.map((asset) => [asset.id, asset.parentAssetId])).toEqual([["b", undefined], ["c", "b"], ["d", undefined]]);
+ });
});
diff --git a/src/lib/imageHistory.ts b/src/lib/imageHistory.ts
index 35a9c84..f31fe50 100644
--- a/src/lib/imageHistory.ts
+++ b/src/lib/imageHistory.ts
@@ -18,6 +18,23 @@ export function imageGenerationSnapshot(config: ProjectConfig, prompt: string, g
});
}
+/** The first image of `id`'s family: its parent, or itself when it is an
+ * original (or its parent has since been removed). */
+export function imageFamilyRoot(assets: readonly ProjectAsset[], id: string | null | undefined): string | undefined {
+ const asset = assets.find((candidate) => candidate.id === id && candidate.kind === "image");
+ if (!asset) return undefined;
+ return asset.parentAssetId && assets.some((candidate) => candidate.id === asset.parentAssetId && candidate.kind === "image") ? asset.parentAssetId : asset.id;
+}
+
+/** Removes an image. Its children stay a family: the oldest becomes the
+ * original the others belong to. */
+export function removeImageAsset(assets: readonly ProjectAsset[], id: string): ProjectAsset[] {
+ const children = assets.filter((asset) => asset.parentAssetId === id);
+ const heir = children[0]?.id;
+ return assets.filter((asset) => asset.id !== id).map((asset) => asset.parentAssetId !== id ? asset
+ : asset.id === heir ? { ...asset, parentAssetId: undefined } : { ...asset, parentAssetId: heir });
+}
+
/** Keep the editable version in history without creating another image file. */
export function saveImageDraft(config: ProjectConfig, generatorTemplateId?: string): ProjectConfig {
const scene = config.imageScene;
@@ -28,11 +45,13 @@ export function saveImageDraft(config: ProjectConfig, generatorTemplateId?: stri
if (!selected?.imageDraft && scene.outputAssetId && scene.nodes.length === 1 && !scene.nodes[0].description.trim()) return config;
const existing = selected?.imageDraft ? 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 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"),
imageDraft: true, mimeType: /\.png$/i.test(source?.relativePath ?? "") ? "image/png" : "image/jpeg",
- imageGeneration: snapshot, createdAt: existing?.createdAt ?? new Date().toISOString() };
+ imageGeneration: snapshot, ...(parentAssetId ? { parentAssetId } : {}), createdAt: existing?.createdAt ?? new Date().toISOString() };
return { ...config, imageScene: { ...scene, outputAssetId: id }, assets: existing ? config.assets.map((item) => item.id === id ? asset : item) : [...config.assets, asset] };
}
@@ -52,7 +71,7 @@ export function completeImageDraft(config: ProjectConfig, id: string, result: Pr
const changed = draft && JSON.stringify({ ...draft.imageGeneration, prompt: "" }) !== JSON.stringify({ ...result.imageGeneration, prompt: "" });
// 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 };
+ const asset = { ...result, id, imageDraft: false, ...(draft?.parentAssetId ? { parentAssetId: draft.parentAssetId } : {}) };
const assets = config.assets.some((item) => item.id === id) ? config.assets.map((item) => item.id === id ? asset : item) : [...config.assets, asset];
const next = { ...config, assets: pending ? [...assets, pending] : assets };
if (!selected) return next;
diff --git a/src/lib/project.ts b/src/lib/project.ts
index 4e44bb4..d896af6 100644
--- a/src/lib/project.ts
+++ b/src/lib/project.ts
@@ -180,12 +180,18 @@ export const projectAssetSchema = z.object({
hasAudio: z.boolean().nullish(),
imageGeneration: imageGenerationSnapshotSchema.nullish(),
imageDraft: z.boolean().nullish(),
+ /** The original image this one was regenerated or edited from. Always the
+ * family's first image, never another child, so a family is one level. */
+ parentAssetId: idSchema.nullish(),
createdAt: isoDateSchema,
}).superRefine((asset, context) => {
checkOneLocation(asset, context, `Asset '${asset.id}'`);
if (asset.imageDraft && (asset.kind !== "image" || !asset.imageGeneration || (asset.imageGeneration.scene.rootType === "image" && !asset.imageGeneration.scene.sourceImage))) {
context.addIssue({ code: z.ZodIssueCode.custom, message: "Image drafts require a scene snapshot and image roots require a source." });
}
+ if (asset.parentAssetId && (asset.kind !== "image" || asset.parentAssetId === asset.id)) {
+ context.addIssue({ code: z.ZodIssueCode.custom, path: ["parentAssetId"], message: "Only an image can have a parent image, and not itself." });
+ }
if (asset.imageGeneration && asset.kind !== "image") {
context.addIssue({ code: z.ZodIssueCode.custom, path: ["imageGeneration"], message: "Only image assets can store image generation history." });
}
diff --git a/src/lib/workQueue.test.ts b/src/lib/workQueue.test.ts
index 4dc6d91..ded926d 100644
--- a/src/lib/workQueue.test.ts
+++ b/src/lib/workQueue.test.ts
@@ -84,6 +84,10 @@ describe("image generation work", () => {
expect(result.imageScene!.outputAssetId).toBe("third");
expect(result.thumbnail).toBe("media/third.jpg");
expect(result.assets.filter((asset) => [first, second].some((item) => asset.relativePath === `media/${item.id}.jpg`))).toHaveLength(2);
+ // Generating again from a finished image adds to its family; a draft
+ // becomes the image itself.
+ expect([first, second].map((item) => result.assets.find((asset) => asset.relativePath === `media/${item.id}.jpg`)!.parentAssetId))
+ .toEqual(imageDraft ? [undefined, undefined] : ["first", "second"]);
});
it("submits whole-image and local edits with separate reference pictures and refmods", async () => {
const { queue } = setup();
diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.ts
index b585020..5639fb7 100644
--- a/src/lib/workQueue.ts
+++ b/src/lib/workQueue.ts
@@ -3,7 +3,7 @@ import { invoke } from "@tauri-apps/api/core";
import { createImageEditScene, createImageScene, imageScenePrompt } from "./imageScene";
import { compileImageEdits, imageEditDebugPrompt } from "./imageEditing";
import { compileImagePrompt } from "./imagePrompt";
-import { completeImageDraft, imageGenerationSnapshot, saveImageDraft } from "./imageHistory";
+import { completeImageDraft, imageFamilyRoot, imageGenerationSnapshot, saveImageDraft } from "./imageHistory";
import type { ImageGenerationSnapshot } from "./project";
import { outputDimensions } from "./export";
import { projectItemPath, referenceImages, referenceRefmodInputs } from "./project";
@@ -44,6 +44,8 @@ export interface WorkItem {
}
interface PendingWork {
imageDraftId?: string;
+ /** The family a regenerated image joins. */
+ imageParentId?: string;
image?: boolean;
imageGeneration?: ImageGenerationSnapshot;
id: string;
@@ -222,6 +224,8 @@ export class WorkQueue {
const { width, height } = edit?.source ?? outputDimensions(current.settings.resolution, current.settings.aspectRatio);
const id = `image-${crypto.randomUUID()}`;
const imageDraftId = current.assets.find((asset) => asset.id === scene.outputAssetId && asset.imageDraft)?.id;
+ // Generating again from a finished image makes a new image in its family.
+ const imageParentId = imageDraftId ? undefined : imageFamilyRoot(current.assets, scene.outputAssetId);
let finish!: () => void;
const done = new Promise<void>((resolve) => { finish = resolve; });
const request: SlopfabGenerationRequest = { jobId: id, stillImage: true, frames: 1, prompt: edit ? edit.edits[0].prompt : prompt,
@@ -232,7 +236,7 @@ export class WorkQueue {
referencePaths: referencePaths(references),
refmods: referenceRefmodInputs(session.record.folderPath, references),
};
- this.work.set(id, { id, image: true, imageDraftId, imageGeneration: imageGenerationSnapshot(config, edit ? imageEditDebugPrompt(edit.edits) : prompt, template.id), session, sceneId: scene.nodes.find((node) => node.kind === "root")!.id, config, snapshot: JSON.stringify(scene), request, submitted: false, cancelled: false, done, finish });
+ this.work.set(id, { id, image: true, imageDraftId, imageParentId, imageGeneration: imageGenerationSnapshot(config, edit ? imageEditDebugPrompt(edit.edits) : prompt, template.id), session, sceneId: scene.nodes.find((node) => node.kind === "root")!.id, config, snapshot: JSON.stringify(scene), request, submitted: false, cancelled: false, done, finish });
this.items = [...this.items, { id, kind: "image", imageAssetId: scene.outputAssetId, imageDraftId, projectKey, folderPath: session.record.folderPath, projectName: config.name, sceneId: scene.nodes.find((node) => node.kind === "root")!.id,
title: "Image · " + config.name, submittedAt: new Date().toISOString(), status: "queued", progress: 0, detail: "Waiting to generate image", error: null, completionAt: null, cancelling: false, needsSave: false,
settings: { frames: 1, steps: request.steps, seed: request.seed, canvasWidth: width, canvasHeight: height } }];
@@ -421,7 +425,7 @@ export class WorkQueue {
thumbnail: saved.relativePath,
imageScene: { ...(work.request.imageEdit && JSON.stringify(current.imageScene) === work.snapshot ? createImageEditScene({ ...saved, name: "Edited image" }, current.imageScene ?? undefined) : current.imageScene ?? createImageScene()), outputAssetId: work.id },
} : {}),
- assets: [...current.assets, { id: work.id, kind: "image", name: `Image ${current.assets.filter((asset) => asset.kind === "image").length + 1}`, ...saved, imageGeneration: work.imageGeneration, mimeType: work.request.imageEdit ? "image/png" : "image/jpeg", createdAt: new Date().toISOString() }],
+ assets: [...current.assets, { id: work.id, kind: "image", name: `Image ${current.assets.filter((asset) => asset.kind === "image").length + 1}`, ...saved, imageGeneration: work.imageGeneration, mimeType: work.request.imageEdit ? "image/png" : "image/jpeg", ...(work.imageParentId && current.assets.some((asset) => asset.id === work.imageParentId) ? { parentAssetId: work.imageParentId } : {}), createdAt: new Date().toISOString() }],
}));
try { await work.session.save(); this.patch(work.id, { status: "completed", progress: 1, detail: "Image saved" }); }
catch (reason) { this.patch(work.id, { status: "failed", progress: 1, needsSave: true, detail: "Image created; project save failed", error: describeDiagnosticError(reason) }); }
diff --git a/src/styles/image-editor.css b/src/styles/image-editor.css
index 606c9e4..1e49b9b 100644
--- a/src/styles/image-editor.css
+++ b/src/styles/image-editor.css
@@ -76,6 +76,11 @@
.image-draft-badge { position: absolute; bottom: 0; left: 0; right: 0; display: flex; align-items: center; justify-content: center; gap: 3px; padding: 2px; background: var(--glass); color: var(--text-primary); font-size: var(--text-xs); }
.image-results button[aria-pressed="true"] { border-color: var(--accent); }
.image-results img { width: 100%; height: 100%; object-fit: cover; }
+/* Back to the originals, at the leading edge of a family. */
+.image-results button.image-results__back { flex: 0 0 32px; display: grid; place-items: center; border: 0; color: var(--text-secondary); background: transparent; }
+.image-results button.image-results__back:hover { color: var(--text-primary); background: var(--fill-subtle-hover); }
+/* How many images an original's family holds, itself included. */
+.image-family-badge { position: absolute; top: 2px; right: 2px; min-width: 18px; padding: 0 4px; border-radius: var(--radius-pill); color: var(--on-accent); background: var(--accent); font-size: var(--text-xs); line-height: 18px; text-align: center; }
/* --- Inspector -------------------------------------------------------------------
Label + control pairs are PropRows; the free-text fields stay full width