AI media harness for planning, generating, and editing locally
TypeScript
Pass only prompt-mentioned references to still-image generation
Bitti08a7210c0634
diff --git a/src-tauri/assets/agent-image.md b/src-tauri/assets/agent-image.mdindex 7395651..c0aeac5 100644--- a/src-tauri/assets/agent-image.md+++ b/src-tauri/assets/agent-image.md@@ -29,4 +29,4 @@ All fields are required; copy unchanged authored fields from imageScene in the cUse exactly one root with parentId null. Other nodes have kind group, object, text or background, and parentId naming an existing node. IDs must be unique and the tree connected and acyclic. Objects, groups and text may carry box {"x":100,"y":100,"width":400,"height":600} in 0–1000 image coordinates; extents must be positive and stay within the image. Box null means automatic placement. A group's description provides context to its children. Text nodes use text for the exact lettering and description for appearance. Colors are hex #RRGGBB strings (up to 16). Names are short tree labels; put visual instructions in description. At most 500 nodes. Style mode is photo or art, steps 2–1000, seed -1 for random or a nonnegative safe integer. Placement is prose guidance to H3, not a guaranteed pixel mask.-Use project.set for project name, resolution and aspectRatio. Use ref.add/ref.set for reusable descriptions, then include their IDs in image.configure referenceIds. Unbind a reference before ref.remove. Bind only existing image/text references. Do not create scene.*, shot.* or clip.* commands for image projects. Preserve the current image composition unless asked to change it. Never invent files or claim to have generated an image: the user runs Generate in the Editor.+Use project.set for project name, resolution and aspectRatio. Use ref.add/ref.set for reusable descriptions, then mention each one in a description by its exact name in square brackets, e.g. "[Mara] holds the lantern". Only the references mentioned this way are passed to generation; referenceIds is no longer used to choose them. Mention only existing image/text references, and never put square brackets around anything else. Remove its mentions before ref.remove. Do not create scene.*, shot.* or clip.* commands for image projects. Preserve the current image composition unless asked to change it. Never invent files or claim to have generated an image: the user runs Generate in the Editor.diff --git a/src/components/ImageProject.integration.test.tsx b/src/components/ImageProject.integration.test.tsxindex a064e9e..354d761 100644--- a/src/components/ImageProject.integration.test.tsx+++ b/src/components/ImageProject.integration.test.tsx@@ -133,7 +133,8 @@ it("shows the full image prompt at the end of the inspector only when debug is e{ id: "mood", kind: "text", name: "Mood", description: "Peaceful and bright", intendedUse: [], createdAt: project.config.createdAt },{ id: "unused", kind: "text", name: "Unused", description: "Do not include this reference", intendedUse: [], createdAt: project.config.createdAt },];- project.config.imageScene!.referenceIds = ["subject", "mood"];+ // Only mentioned references reach the prompt; Unused is never mentioned.+ project.config.imageScene!.nodes[0].description = "A [Rocket] launch over the ocean at dawn, [Mood]";render(<ProjectWorkspace project={project} onBack={vi.fn()} onSave={vi.fn()} />);expect(screen.queryByRole("button", { name: "Debug prompt" })).not.toBeInTheDocument();act(() => saveDebugOptionsEnabled(true));@@ -147,11 +148,12 @@ it("shows the full image prompt at the end of the inspector only when debug is ebutton.focus();fireEvent.click(button);const prompt = within(screen.getByRole("dialog", { name: "Debug prompt" })).getByLabelText("The compiled MiniMax H3 prompt");- for (const line of imageScenePrompt(project.config.imageScene!, "Watercolor").split("\n")) expect(prompt.textContent).toContain(line);+ const compiled = imageScenePrompt(project.config.imageScene!, "Watercolor").replace("[Rocket]", "<Subject 1>").replace("[Mood]", "<Subject 2>");+ for (const line of compiled.split("\n")) expect(prompt.textContent).toContain(line);expect(prompt.textContent).toContain('Render the exact text "TO THE MOON".');expect(prompt.textContent).toContain("Watercolor visual style");expect(prompt.textContent).toContain("subject_definitions:\n<Subject 1> is Rocket, providing appearance from <Picture 1> and <Picture 2>. A silver rocket.\n<Subject 2> is Mood, providing appearance. Peaceful and bright.");- expect(prompt.textContent).toContain("[Shot 1] A rocket launch over the ocean at dawn.");+ expect(prompt.textContent).toContain("[Shot 1] A <Subject 1> launch over the ocean at dawn, <Subject 2>.");expect(prompt.textContent).toMatch(/overall_soundscape: N\/A\n\nnon_diegetic_music: N\/A$/);expect(prompt.textContent).not.toContain("Do not include this reference");fireEvent.keyDown(prompt, { key: "Escape" });diff --git a/src/components/workspace/ImageEditor.test.tsx b/src/components/workspace/ImageEditor.test.tsxindex dfa68c0..d5e03bf 100644--- a/src/components/workspace/ImageEditor.test.tsx+++ b/src/components/workspace/ImageEditor.test.tsx@@ -17,7 +17,9 @@ import snapshotFixture from "../../../fixtures/image-generation-snapshot.json";/* The prompt is a contenteditable: typing is its text and an input event. */const typePrompt = (field: HTMLElement, text: string) => { field.textContent = text; fireEvent.input(field); };-const promptValue = (field: HTMLElement) => field.textContent;+/* Reads a chip back as the [Name] it stands for, as the value stores it. */+const promptValue = (field: HTMLElement) => [...field.childNodes].map((node) => node instanceof HTMLElement && node.dataset.promptReference !== undefined+ ? `[${node.dataset.promptReference}]` : node.textContent ?? "").join("").replaceAll("", "");vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));afterEach(() => { cleanup(); localStorage.clear(); vi.restoreAllMocks(); });function setup(initial = parseProjectConfig(fixture)) {@@ -53,8 +55,9 @@ it("adds image files in edit mode and saves whole-image and drawn edits with sepaddFile();await waitFor(() => expect(current().imageScene?.sourceImage).toEqual(source));expect(screen.queryByRole("combobox", { name: "Type" })).not.toBeInTheDocument();- typePrompt(screen.getByLabelText("Edit prompt"), "Make the lighting warmer");- fireEvent.click(screen.getByRole("checkbox", { name: "Mood" }));+ // References come from what each prompt mentions; there is no list to tick.+ expect(screen.queryByRole("checkbox", { name: "Mood" })).not.toBeInTheDocument();+ typePrompt(screen.getByLabelText("Edit prompt"), "Make the lighting warmer like [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() });@@ -69,10 +72,9 @@ it("adds image files in edit mode and saves whole-image and drawn edits with sepfireEvent.keyDown(canvas, { key: "e" });expect(screen.getByRole("radio", { name: "Draw edit" })).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 }, referenceIds: [] });- expect(screen.getByRole("checkbox", { name: "Mood" })).not.toBeChecked();- typePrompt(screen.getByLabelText("Edit prompt"), "Add a red balloon");- fireEvent.click(screen.getByRole("checkbox", { name: "Balloon" }));+ expect(current().imageScene!.nodes[1]).toMatchObject({ name: "Edit", box: { x: 100, y: 100, width: 300, height: 300 } });+ expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("");+ typePrompt(screen.getByLabelText("Edit prompt"), "Add a red [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())));@@ -81,10 +83,10 @@ it("adds image files in edit mode and saves whole-image and drawn edits with sepfireEvent.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");+ expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("Make the lighting warmer like [Mood]");fireEvent.click(screen.getByRole("button", { name: "Edit" }));- expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("Add a red balloon");- expect(screen.getByRole("checkbox", { name: "Balloon" })).toBeChecked();+ expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("Add a red [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();diff --git a/src/components/workspace/ImageEditor.tsx b/src/components/workspace/ImageEditor.tsxindex 2431e7c..71b8667 100644--- a/src/components/workspace/ImageEditor.tsx+++ b/src/components/workspace/ImageEditor.tsx@@ -5,7 +5,6 @@ import { addImageNode, createImageEditScene, createImageScene, duplicateImageNodimport { compileImageEdits, editGeneratedImage, imageEditDebugPrompt } from "../../lib/imageEditing";import { outputDimensions } from "../../lib/export";import { compileImagePrompt } from "../../lib/imagePrompt";-import { promptReferenceNames } from "../../lib/promptReferences";import { createEmptyImage, restoreGeneratedImage, saveImageDraft } from "../../lib/imageHistory";import { isTauri } from "../../lib/persistence";import { IMAGE_RESOLUTIONS, type ProjectConfig } from "../../lib/project";@@ -148,7 +147,7 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGeneconst add = (kind: Exclude<ImageNode["kind"], "root">, box?: ImageBox) => {const parent = imageRoot ? root.id : insertParent;const next = addImageNode(scene, parent, imageRoot ? "object" : kind, box);- if (imageRoot) Object.assign(next.nodes.at(-1)!, { name: "Edit", referenceIds: [] });+ if (imageRoot) Object.assign(next.nodes.at(-1)!, { name: "Edit" });commit(next); setSelection(next.nodes.at(-1)!.id);setCollapsed((current) => { const next = new Set(current); next.delete(parent); return next; });};@@ -438,19 +437,7 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGeneconst promptLabel = imageRoot ? "Edit prompt" : selected.kind === "root" ? "Prompt (high-level description)" : "Description";const promptReferences = config.references.filter((reference) => reference.kind === "image" || reference.kind === "text").map((reference) => ({ id: reference.id, name: reference.name, detail: reference.kind === "image" ? "Image" : "Text", icon: <ReferenceIcon reference={reference} folderPath={folderPath} fallback={reference.kind === "image" ? <Image16 /> : <Text16 />} /> }));- /* A reference newly cited in a prompt is one the generation has to be- given, so citing it links it to the edit (or, composing, to the image). */- const changePrompt = (description: string) => {- const before = promptReferenceNames(selected.description);- const cited = promptReferenceNames(description).filter((name) => !before.includes(name))- .flatMap((name) => promptReferences.filter((reference) => reference.name === name).map((reference) => reference.id));- const nodes = scene.nodes.map((node) => node.id === selected.id ? { ...node, description } : node);- if (imageRoot) {- const referenceIds = selected.referenceIds ?? scene.referenceIds;- const linked = [...referenceIds, ...cited.filter((id) => !referenceIds.includes(id))];- commit({ ...scene, nodes: nodes.map((node) => node.id === selected.id && linked.length !== referenceIds.length ? { ...node, referenceIds: linked } : node) });- } else commit({ ...scene, nodes, referenceIds: selected.kind === "root" ? [...scene.referenceIds, ...cited.filter((id) => !scene.referenceIds.includes(id))] : scene.referenceIds });- };+return <div ref={editorRoot} className="image-editor" style={{ ...treePane.style, ...inspectorPane.style }}><aside ref={hierarchy} className="image-tree" aria-label="Image hierarchy" onContextMenu={(event) => { if ((event.target as HTMLElement).closest("input, textarea, [contenteditable=true]")) return; event.preventDefault(); setSelection(root.id); setContextMenu({ x: event.clientX, y: event.clientY }); }} onKeyDown={treeKeys}>{/* Undo and Redo live in the title bar; Ctrl+Z / Ctrl+Y still step the image edits here. */}@@ -594,17 +581,10 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene{scene.sourceImage && <p className="image-inspector__caption">{scene.sourceImage.name} · {scene.sourceImage.width} × {scene.sourceImage.height}</p>}<p className="image-inspector__caption">Applies to the whole image before the individual edits.</p></>}- <div className="image-inspector__area"><span id={rootField("prompt-label")}>{promptLabel}</span><PromptTextField key={selected.id} aria-labelledby={rootField("prompt-label")} value={selected.description} references={promptReferences} onChange={changePrompt} /></div>- {imageRoot && <PropSection title="References" persistKey="image.edit.references">- {config.references.filter((reference) => reference.kind === "image" || reference.kind === "text").map((reference) => {- const referenceIds = selected.referenceIds ?? scene.referenceIds;- return <label className="image-check" key={reference.id}><input type="checkbox" checked={referenceIds.includes(reference.id)} onChange={(event) => patchNode({ referenceIds: event.target.checked ? [...referenceIds, reference.id] : referenceIds.filter((id) => id !== reference.id) })} />{reference.name}</label>;- })}- {!config.references.some((reference) => reference.kind === "image" || reference.kind === "text") && <p className="image-inspector__caption">Add image or text references under References, then link them to this edit.</p>}- </PropSection>}+ <div className="image-inspector__area"><span id={rootField("prompt-label")}>{promptLabel}</span><PromptTextField key={selected.id} aria-labelledby={rootField("prompt-label")} value={selected.description} references={promptReferences} onChange={(description) => patchNode({ description })} /></div>{selected.kind === "text" && <PropRow label="Text to render" htmlFor={rootField("text")}><input id={rootField("text")} className="text-field" value={selected.text} onChange={(event) => patchNode({ text: event.target.value })} /></PropRow>}{selected.kind === "root" && !imageRoot && <>- <label className="image-inspector__area">Background (environment)<textarea className="text-field" rows={3} value={scene.background} onChange={(event) => commit({ ...scene, background: event.target.value })} /></label>+ <div className="image-inspector__area"><span id={rootField("background-label")}>Background (environment)</span><PromptTextField aria-labelledby={rootField("background-label")} rows={3} value={scene.background} references={promptReferences} onChange={(background) => commit({ ...scene, background })} /></div><PropSection title="Image generation" persistKey="image.generation"><PropRow label="Steps" htmlFor={rootField("steps")}><input id={rootField("steps")} className="text-field" type="number" min="2" max="1000" value={scene.steps} onChange={(event) => { const value = Number(event.target.value); if (Number.isInteger(value) && value >= 2 && value <= 1000) commit({ ...scene, steps: value }); }} /></PropRow><PropRow label="Seed" htmlFor={rootField("seed")}><input id={rootField("seed")} className="text-field" type="number" min="-1" max={Number.MAX_SAFE_INTEGER} value={scene.seed} data-tooltip="-1 picks a random seed" onChange={(event) => { const value = Number(event.target.value); if (Number.isSafeInteger(value) && value >= -1) commit({ ...scene, seed: value }); }} /></PropRow>@@ -618,10 +598,6 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene{scene.style.mode === "art" && <TagEditor label="Medium" value={scene.style.medium} suggestions={styleSuggestions.MediumSuggestions} onChange={(medium) => commit({ ...scene, style: { ...scene.style, medium } })} />}<TagEditor key={scene.style.mode} label={scene.style.mode === "photo" ? "Camera / lens" : "Art style"} value={scene.style.detail} suggestions={scene.style.mode === "photo" ? styleSuggestions.PhotoSuggestions : styleSuggestions.ArtSuggestions} onChange={(detail) => commit({ ...scene, style: { ...scene.style, detail } })} /></PropSection>- <PropSection title="References" persistKey="image.references">- {config.references.filter((reference) => reference.kind === "image" || reference.kind === "text").map((reference) => <label className="image-check" key={reference.id}><input type="checkbox" checked={scene.referenceIds.includes(reference.id)} onChange={(event) => commit({ ...scene, referenceIds: event.target.checked ? [...scene.referenceIds, reference.id] : scene.referenceIds.filter((id) => id !== reference.id) })} />{reference.name}</label>)}- {!config.references.length && <p className="image-inspector__caption">None yet — add them under References.</p>}- </PropSection></>}{selected.kind !== "root" && <PropSection title="Placement (0–1000)" persistKey="image.placement"><label className="image-check"><input type="checkbox" checked={Boolean(selected.box)} onChange={(event) => patchNode({ box: event.target.checked ? { x: 250, y: 250, width: 500, height: 500 } : null })} />Explicit placement</label>diff --git a/src/lib/imageEditing.test.ts b/src/lib/imageEditing.test.tsindex b582bec..0831e31 100644--- a/src/lib/imageEditing.test.ts+++ b/src/lib/imageEditing.test.ts@@ -39,13 +39,14 @@ it("reserves Picture 1 for the source and counts it toward H3's nine-picture limconfig.imageScene = addImageNode(createImageEditScene({ relativePath: "media/imported/source.png", name: "Source", width: 101, height: 77 }), "image-root", "object");config.imageScene.nodes[1].description = "A red balloon";config.references = Array.from({ length: 9 }, (_, index) => ({ id: `ref-${index}`, kind: "image" as const, name: `Reference ${index}`, description: "Red satin", relativePath: `references/${index}.png`, intendedUse: [], createdAt: config.createdAt }));- config.imageScene.referenceIds = config.references.slice(0, 8).map((reference) => reference.id);+ const mention = (count: number) => `A red balloon ${config.references.slice(0, count).map((reference) => `[${reference.name}]`).join(" ")}`;+ config.imageScene.nodes[1].description = mention(8);const prompt = compileImageEdits(config).edits[0].prompt;expect(prompt).toContain("<Subject 1> is Reference 0, providing appearance from <Picture 2>");expect(prompt).toContain("<Subject 8> is Reference 7, providing appearance from <Picture 9>");expect(prompt).toContain("[keyframe completion + reference generation]");expect(prompt).not.toMatch(/\b(box|mask\w*|rectangle|region|boundary|border|pixels?)\b/i);- config.imageScene.referenceIds.push("ref-8");+ config.imageScene.nodes[1].description = mention(9);expect(() => compileImageEdits(config)).toThrow("at most nine reference images");});@@ -63,28 +64,29 @@ it("starts with a clean image root and requires described edits before submissioexpect(parseProjectConfig(JSON.parse(JSON.stringify(edited))).imageScene).toEqual(edited.imageScene);});-it("applies whole-image actions first and compiles only each edit's linked references", () => {+it("applies whole-image actions first and compiles only the references each edit mentions", () => {const config = parseProjectConfig(fixture);config.imageScene = createImageEditScene({ relativePath: "media/source.png", name: "Source", width: 101, height: 77 });config.references = ["Lighting", "Balloon", "Unused"].map((name) => ({ id: name, name, kind: "image", description: name, relativePath: `references/${name}.png`, intendedUse: [], createdAt: config.createdAt }));const root = config.imageScene.nodes[0];- root.description = "Warm up the entire image";- root.referenceIds = ["Lighting"];+ root.description = "Warm up the entire image like [Lighting]";+ // Stored ids no longer choose anything: only mentions do.+ root.referenceIds = ["Unused"];expect(compileImageEdits(config).edits).toHaveLength(1);config.imageScene = addImageNode(config.imageScene, root.id, "object");- Object.assign(config.imageScene.nodes[1], { description: "Add a balloon", referenceIds: ["Balloon"] });+ Object.assign(config.imageScene.nodes[1], { description: "Add a [Balloon]" });let edits = compileImageEdits(config).edits;expect(edits[0]).toMatchObject({ x: 0, y: 0, width: 101, height: 77 });- expect(edits[0].prompt).toContain("Warm up the entire image");+ expect(edits[0].prompt).toContain("Warm up the entire image like <Subject 1>");expect(edits[0].prompt).toContain("<Subject 1> is Lighting, providing appearance from <Picture 2>");expect(edits[0].prompt).not.toContain("Balloon");expect(edits[1].prompt).toContain("<Subject 1> is Balloon, providing appearance from <Picture 2>");expect(edits[1].prompt).not.toContain("Lighting");expect(edits.map((edit) => edit.references.map((reference) => reference.id))).toEqual([["Lighting"], ["Balloon"]]);config.imageScene.referenceIds = ["Unused"];- config.imageScene.nodes[1].referenceIds = [];+ config.imageScene.nodes[1].description = "Add a balloon";edits = compileImageEdits(config).edits;expect(edits[1].references).toEqual([]);- config.imageScene.nodes[1].referenceIds = ["missing"];- expect(() => compileImageEdits(config)).toThrow("no longer exists");+ config.imageScene.nodes[1].description = "Add a [missing]";+ expect(() => compileImageEdits(config)).toThrow("The prompt mentions [missing]");});diff --git a/src/lib/imageEditing.ts b/src/lib/imageEditing.tsindex 5b7c912..7540d9b 100644--- a/src/lib/imageEditing.ts+++ b/src/lib/imageEditing.ts@@ -26,7 +26,7 @@ export function compileImageEdits(config: ProjectConfig): { source: ImageSource;const bottom = Math.min(source.height, Math.ceil((node.box.y + node.box.height) * source.height / 1000));const description = ["The edited keyframe corresponds to <Picture 1> with the following change. Preserve the composition and any previously completed edits.", node.description,node.text ? `Render the exact text "${node.text}".` : "", node.colors.length ? `Use these colors: ${node.colors.join(", ")}.` : ""].filter(Boolean).join(" ");- const editScene = { ...createImageScene(description), rootType: "image" as const, sourceImage: source, referenceIds: node.referenceIds ?? scene.referenceIds };+ const editScene = { ...createImageScene(description), rootType: "image" as const, sourceImage: source, referenceIds: [] };const compiled = compileImagePrompt({ ...config, settings: { ...config.settings, defaultLook: null }, imageScene: editScene });return { prompt: compiled.prompt, references: compiled.references, x, y, width: Math.max(1, right - x), height: Math.max(1, bottom - y) };});diff --git a/src/lib/imageHistory.ts b/src/lib/imageHistory.tsindex 786799c..14c1369 100644--- a/src/lib/imageHistory.ts+++ b/src/lib/imageHistory.ts@@ -1,8 +1,10 @@-import { createImageEditScene, createImageScene, imageSceneReferenceIds } from "./imageScene";+import { createImageEditScene, createImageScene, imageSceneReferenceIds, imageScenePromptText } from "./imageScene";+import { promptReferenceNames } from "./promptReferences";import type { ImageGenerationSnapshot, ProjectAsset, ProjectConfig } from "./project";export function imageGenerationSnapshot(config: ProjectConfig, prompt: string, generatorTemplateId: string): ImageGenerationSnapshot {const scene = config.imageScene ?? createImageScene(config.brief.prompt);+ const mentioned = promptReferenceNames(imageScenePromptText(scene));return structuredClone({scene: { ...scene, outputAssetId: null },resolution: config.settings.resolution,@@ -11,7 +13,10 @@ export function imageGenerationSnapshot(config: ProjectConfig, prompt: string, gbriefPrompt: config.brief.prompt,prompt,generatorTemplateId,- references: imageSceneReferenceIds(scene).map((id) => config.references.find((reference) => reference.id === id)!),+ // What the prompt mentions, plus any ids a scene saved before mentions+ // were how references are chosen (the snapshot schema still checks them).+ references: config.references.filter((reference) => imageSceneReferenceIds(scene).includes(reference.id)+ || ((reference.kind === "image" || reference.kind === "text") && mentioned.includes(reference.name))),});}diff --git a/src/lib/imagePrompt.test.ts b/src/lib/imagePrompt.test.tsindex e5d7feb..3e17762 100644--- a/src/lib/imagePrompt.test.ts+++ b/src/lib/imagePrompt.test.ts@@ -52,7 +52,8 @@ describe("MiniMax H3 still-image prompts", () => {{ id: "track", kind: "image", name: "Track", description: "A gravel track", relativePath: "references/track.png", intendedUse: [], createdAt: config.createdAt },{ id: "unused", kind: "text", name: "Unused", description: "Exclude these words", intendedUse: [], createdAt: config.createdAt },];- config.imageScene!.referenceIds = ["track", "palette", "runner"];+ // Only mentions choose references, in the order they are first mentioned.+ config.imageScene!.nodes[0].description = "On [Track] in [Palette] tones, [Runner] is suspended mid-stride";const result = compileImagePrompt(config);expect(result.references.map((reference) => reference.id)).toEqual(["track", "palette", "runner"]);expect(result.prompt.match(/^\w+:/gm)).toEqual(["subject_definitions:", "summary:", "retention_analysis:", "detailed_description:", "overall_soundscape:", "non_diegetic_music:"]);@@ -60,7 +61,7 @@ describe("MiniMax H3 still-image prompts", () => {expect(result.prompt).toContain("<Subject 2> is Palette, providing appearance. Warm ochre and red.");expect(result.prompt).toContain("<Subject 3> is Runner, providing appearance from <Picture 2> and <Picture 3>. Red jersey.");expect(result.prompt).toContain("summary:\n[reference generation] A single still image uses <Subject 1>, <Subject 2>, <Subject 3>");- expect(result.prompt).toContain("detailed_description:\nA still photograph.\n[Shot 1] A runner suspended mid-stride.");+ expect(result.prompt).toContain("detailed_description:\nA still photograph.\n[Shot 1] On <Subject 1> in <Subject 2> tones, <Subject 3> is suspended mid-stride.");for (let index = 1; index <= 3; index++) {expect(result.prompt).toContain(`<Subject ${index}> (appears in [Shot 1]): fully_preserved`);expect(result.prompt.split("detailed_description:")[1]).toContain(`Use <Subject ${index}>`);@@ -68,8 +69,8 @@ describe("MiniMax H3 still-image prompts", () => {expect(result.prompt).toMatch(/overall_soundscape: N\/A\n\nnon_diegetic_music: N\/A$/);expect(result.prompt).not.toContain("integrated_multimodal_description");expect(result.prompt).not.toMatch(/Exclude these words|<Video|<Audio|first frame|last frame/);- config.imageScene!.referenceIds = ["missing"];- expect(() => compileImagePrompt(config)).toThrow("no longer exists");+ config.imageScene!.nodes[0].description = "[Missing] runs";+ expect(() => compileImagePrompt(config)).toThrow("The prompt mentions [Missing], but no image or text reference has that name.");});it("uses the brief for legacy image documents and leaves genuinely empty prompts empty", () => {@@ -83,13 +84,15 @@ describe("MiniMax H3 still-image prompts", () => {const config = photo();config.references = [{ id: "identity", kind: "text", name: "Woman", description: "", intendedUse: ["character"], createdAt: config.createdAt,refmods: [{ id: "encoded", name: "Identity", sourcePath: "D:/identity.safetensors", strength: 1, copies: 1 }] }];- config.imageScene!.referenceIds = ["identity"];+ config.imageScene!.nodes[0].description = "[Woman] suspended mid-stride";const prompt = compileImagePrompt(config).prompt;expect(prompt).toContain("<Subject 1> is Woman, providing identity and appearance from the supplied reference conditioning.");expect(prompt).toContain("Use <Subject 1> for Woman's identity and appearance from the supplied reference conditioning.");expect(prompt).not.toMatch(/Additional visual guidance: Woman|<Picture|<Video|safetensors/);config.references[0].refmods![0].strength = 0;- expect(compileImagePrompt(config).prompt).not.toContain("Woman");+ // With nothing to condition on, the mention reads as the plain name.+ expect(compileImagePrompt(config).prompt).not.toMatch(/<Subject|\[Woman\]/);+ expect(compileImagePrompt(config).prompt).toContain("Woman suspended mid-stride.");expect(compileImagePrompt(config).prompt).toMatch(/^integrated_multimodal_description: \[Shot 1\]/);});it("keeps picture numbering independent of refmod and text subjects", () => {@@ -99,10 +102,26 @@ describe("MiniMax H3 still-image prompts", () => {{ id: "style", kind: "text", name: "Style", description: "", intendedUse: ["style"], createdAt: config.createdAt, refmods: [{ id: "style-mod", name: "Style", sourcePath: "D:/style.safetensors", strength: 1, copies: 1 }] },{ id: "runner", kind: "image", name: "Runner", description: "Red jersey", relativePath: "references/runner.png", intendedUse: ["character"], createdAt: config.createdAt },];- config.imageScene!.referenceIds = config.references.map((reference) => reference.id);+ config.imageScene!.nodes[0].description = "[Disabled] and a [Style] frame around [Runner]";const prompt = compileImagePrompt(config).prompt;expect(prompt).toContain("<Subject 1> is Style, providing visual style from the supplied reference conditioning.");expect(prompt).toContain("<Subject 2> is Runner, providing identity and appearance from <Picture 1>.");- expect(prompt).not.toMatch(/Disabled|<Subject 3>|<Picture 2>|<Video/);+ expect(prompt).not.toMatch(/Disabled,|is Disabled|<Subject 3>|<Picture 2>|<Video/);+ });+ it("passes only the references the prompt mentions, from any node or the background", () => {+ const config = photo();+ config.references = [+ { id: "hero", kind: "image", name: "Hero", description: "", relativePath: "references/hero.png", intendedUse: ["character"], createdAt: config.createdAt },+ { id: "sky", kind: "text", name: "Sky", description: "", content: "Violet dusk", intendedUse: [], createdAt: config.createdAt },+ { id: "clip", kind: "video", name: "Clip", description: "", relativePath: "references/clip.mp4", intendedUse: [], createdAt: config.createdAt },+ ];+ config.imageScene!.referenceIds = ["sky"];+ expect(compileImagePrompt(config).references).toEqual([]);+ const scene = addImageNode(config.imageScene!, "image-root", "object");+ scene.nodes.at(-1)!.description = "[Hero] waving";+ config.imageScene = { ...scene, background: "A [Sky] over the hills" };+ expect(compileImagePrompt(config).references.map((reference) => reference.id)).toEqual(["hero", "sky"]);+ config.imageScene.background = "[Clip]";+ expect(() => compileImagePrompt(config)).toThrow("[Clip]");});});diff --git a/src/lib/imagePrompt.ts b/src/lib/imagePrompt.tsindex 675c251..7531574 100644--- a/src/lib/imagePrompt.ts+++ b/src/lib/imagePrompt.ts@@ -1,4 +1,5 @@-import { createImageScene, imageScenePromptParts } from "./imageScene";+import { createImageScene, imageScenePromptParts, imageScenePromptText } from "./imageScene";+import { replacePromptReferences, resolvePromptReferences } from "./promptReferences";import { activeReferenceRefmods, referenceDefinition, referenceImages, type ProjectConfig } from "./project";import { SHOT_TAG_GROUPS } from "./shot-tags";@@ -6,12 +7,8 @@ import { SHOT_TAG_GROUPS } from "./shot-tags";* six-section contracts still apply to a single silent image. */export function compileImagePrompt(config: ProjectConfig) {const scene = config.imageScene ?? createImageScene(config.brief.prompt);- const references = scene.referenceIds.map((id) => {- const reference = config.references.find((candidate) => candidate.id === id);- if (!reference) throw new Error(`Selected image reference '${id}' no longer exists.`);- if (reference.kind === "video" || reference.kind === "audio") throw new Error("Still images accept image and text references.");- return reference;- });+ // Only the references the prompt mentions as [Name] go to the generation.+ const references = resolvePromptReferences(imageScenePromptText(scene), config.references.filter((reference) => reference.kind === "image" || reference.kind === "text"));// An inpainting source is also an explicit composition anchor. The caller// submits it before the selected reference pictures, even with no subjects.const editing = scene.rootType === "image" && Boolean(scene.sourceImage);@@ -29,13 +26,16 @@ export function compileImagePrompt(config: ProjectConfig) {});if (picture > 9) throw new Error("MiniMax H3 supports at most nine reference images per generation.");const look = SHOT_TAG_GROUPS.find((group) => group.id === "visualStyle")?.options.find((option) => option.id === config.settings.defaultLook)?.label;- const visual = imageScenePromptParts(scene, look);- if (!visual) return { prompt: "", references };+ const parts = imageScenePromptParts(scene, look);+ if (!parts) return { prompt: "", references };+ const label = (index: number) => `<Subject ${index + 1}>`;+ // A mention reads as the subject it defines, or by name when it defines none.+ const mention = (name: string) => { const index = subjects.findIndex((subject) => subject.name === name); return index < 0 ? name : label(index); };+ const visual = { style: replacePromptReferences(parts.style, mention), composition: replacePromptReferences(parts.composition, mention) };const audio = ["overall_soundscape: N/A", "non_diegetic_music: N/A"];if (!subjects.length && !editing) return {prompt: [`integrated_multimodal_description: [Shot 1] ${visual.style}\n${visual.composition}`, ...audio].join("\n\n"), references,};- const label = (index: number) => `<Subject ${index + 1}>`;const definitions = subjects.map((subject, index) => `${label(index)} is ${subject.name}, providing ${subject.role}${subject.source}. ${subject.description}`);const retention = subjects.map((subject, index) => `${label(index)} (appears in [Shot 1]): fully_preserved - retain the referenced ${subject.role} of ${subject.name} while following the requested composition and styling.`);if (editing) {diff --git a/src/lib/imageScene.ts b/src/lib/imageScene.tsindex 3bc7b0f..78aa2c8 100644--- a/src/lib/imageScene.ts+++ b/src/lib/imageScene.ts@@ -45,6 +45,10 @@ export type ImageBox = NonNullable<ImageNode["box"]>;export const imageSceneReferenceIds = (scene: ImageScene): string[] =>[...new Set([...scene.referenceIds, ...scene.nodes.flatMap((node) => node.referenceIds ?? [])])];+/** Every authored line of the scene a reference can be mentioned in as [Name]. */+export const imageScenePromptText = (scene: ImageScene): string =>+ [...scene.nodes.map((node) => node.description), scene.background].join("\n");+export function createImageScene(prompt = ""): ImageScene {return { nodes: [{ id: "image-root", parentId: null, kind: "root", name: "Image", description: prompt, text: "", box: null, colors: [] }],background: "", style: { mode: "photo", aesthetics: "", lighting: "", medium: "", detail: "" }, steps: 20, seed: -1, referenceIds: [], outputAssetId: null };diff --git a/src/lib/promptReferences.ts b/src/lib/promptReferences.tsindex 789870d..c6e5e59 100644--- a/src/lib/promptReferences.ts+++ b/src/lib/promptReferences.ts@@ -37,3 +37,18 @@ export function promptReferenceNames(text: string): string[] {}return seen;}++/** The references a prompt mentions, first mention first. A name no reference+ * has is an error: the chip shows it as missing, and generating anyway would+ * quietly drop what the prompt asks for. */+export function resolvePromptReferences<T extends { name: string }>(text: string, references: readonly T[]): T[] {+ return promptReferenceNames(text).map((name) => {+ const reference = references.find((candidate) => candidate.name === name);+ if (!reference) throw new Error(`The prompt mentions [${name}], but no image or text reference has that name.`);+ return reference;+ });+}++/** The text with every `[Name]` written by `label` instead. */+export const replacePromptReferences = (text: string, label: (name: string) => string): string =>+ splitPromptText(text).map((part) => part.kind === "text" ? part.value : label(part.value)).join("");diff --git a/src/lib/workQueue.test.ts b/src/lib/workQueue.test.tsindex e2035c5..cbb145a 100644--- a/src/lib/workQueue.test.ts+++ b/src/lib/workQueue.test.ts@@ -89,10 +89,9 @@ describe("image generation work", () => {const { queue } = setup();const record = imageProject();let scene = createImageEditScene({ name: "Source", relativePath: "media/generated/source.jpg", width: 101, height: 77 });- scene.nodes[0].description = "Make the light warmer";- scene.nodes[0].referenceIds = ["Lighting"];+ scene.nodes[0].description = "Make the light warmer like [Lighting]";scene = addImageNode(scene, "image-root", "object");- Object.assign(scene.nodes[1], { name: "Edit", description: "Add a red balloon", referenceIds: ["Balloon"] });+ Object.assign(scene.nodes[1], { name: "Edit", description: "Add a red [Balloon]" });record.config.imageScene = scene;record.config.references = ["Lighting", "Balloon"].map((name) => ({ id: name, name, kind: "image", description: name,relativePath: `references/${name}.png`, intendedUse: [], createdAt: record.config.createdAt,@@ -123,13 +122,12 @@ describe("image generation work", () => {const { queue } = setup();const record = imageProject();let scene = createImageEditScene({ name: "Source", relativePath: "media/generated/source.jpg", width: 101, height: 77 });- for (const description of ["A red balloon", "A blue boat"]) {+ for (const description of ["A red balloon like [Balloon]", "A blue boat beside [Balloon]"]) {scene = addImageNode(scene, "image-root", "object");scene.nodes.at(-1)!.description = description;}record.config.imageScene = scene;record.config.references = [{ id: "balloon", kind: "image", name: "Balloon", description: "Red satin", relativePath: "references/balloon.png", intendedUse: [], createdAt: record.config.createdAt }];- scene.referenceIds = ["balloon"];const session = queue.project(record);vi.mocked(invoke).mockResolvedValue({ relativePath: "media/generated/edited.png", width: 101, height: 77 });queue.enqueueImage(session, template);@@ -224,7 +222,7 @@ describe("image generation work", () => {{ id: "outfit", name: "Outfit", sourcePath: "D:/Refmods/outfit.safetensors", strength: 1, copies: 1 },{ id: "disabled", name: "Disabled", sourcePath: "D:/Refmods/off.safetensors", strength: 0, copies: 3 },] }];- project.config.imageScene!.referenceIds = ["person"];+ project.config.imageScene!.nodes[0].description += " with [Person]";queue.enqueueImage(queue.project(project), template);await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce());const request = vi.mocked(enqueueSlopfabGeneration).mock.calls[0][0];@@ -240,7 +238,7 @@ describe("image generation work", () => {const project = imageProject();project.config.settings.defaultLook = "watercolor";project.config.references = [{ id: "ocean", kind: "image", name: "Ocean", description: "Turquoise water", relativePath: "references/ocean.png", intendedUse: [], createdAt: project.config.createdAt }];- project.config.imageScene!.referenceIds = ["ocean"];+ project.config.imageScene!.nodes[0].description += " over [Ocean]";const preview = compileImagePrompt(project.config).prompt;queue.enqueueImage(queue.project(project), template);await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce());