Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Cite image references by id and label refmod references

Bitti7a8b05db0255
diff --git a/src-tauri/assets/agent-image.md b/src-tauri/assets/agent-image.md
index c0aeac5..2ca3369 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 c
Use 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 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.
+Use project.set for project name, resolution and aspectRatio. Use ref.add/ref.set for reusable descriptions, then cite each one in a description or the background as @[ref:<id>] with its reference ID, e.g. "@[ref:ref-mara] holds the lantern". Only the references cited this way are passed to generation; referenceIds is no longer used to choose them. Cite only existing image/text references. Remove its citations 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-tauri/src/project/commands/images.rs b/src-tauri/src/project/commands/images.rs
index 7e7c254..f29053b 100644
--- a/src-tauri/src/project/commands/images.rs
+++ b/src-tauri/src/project/commands/images.rs
@@ -349,6 +349,15 @@ pub(super) fn apply(
_ => unreachable!("command dispatched to the wrong domain"),
}
scene.validate()?;
+ for id in scene.cited_reference_ids()? {
+ if !project.references.iter().any(|reference| {
+ reference.id == id && matches!(reference.kind.as_str(), "image" | "text")
+ }) {
+ return Err(format!(
+ "The image cites '@[ref:{id}]', which must name an existing image or text reference."
+ ));
+ }
+ }
for id in &scene.reference_ids {
if !project.references.iter().any(|reference| {
&reference.id == id && matches!(reference.kind.as_str(), "image" | "text")
diff --git a/src-tauri/src/project/commands/references.rs b/src-tauri/src/project/commands/references.rs
index 21f0444..78f6e3a 100644
--- a/src-tauri/src/project/commands/references.rs
+++ b/src-tauri/src/project/commands/references.rs
@@ -74,9 +74,12 @@ pub(super) fn apply(
if project
.image_scene
.as_ref()
- .is_some_and(|scene| scene.reference_ids.contains(id))
+ .is_some_and(|scene| {
+ scene.reference_ids.contains(id)
+ || scene.cited_reference_ids().is_ok_and(|cited| cited.contains(&id.as_str()))
+ })
{
- return Err(format!("reference '{id}' is still used by the image; update image.set before removing it"));
+ return Err(format!("reference '{id}' is still used by the image; remove its citations before removing it"));
}
let at = project
.references
diff --git a/src-tauri/src/project/image.rs b/src-tauri/src/project/image.rs
index b536256..eec60dc 100644
--- a/src-tauri/src/project/image.rs
+++ b/src-tauri/src/project/image.rs
@@ -70,6 +70,20 @@ pub struct ImageStyle {
}
impl ImageScene {
+ /// Every reference the scene's prompts cite as `@[ref:<id>]` — node
+ /// descriptions and the background — which is what generation is given.
+ pub(crate) fn cited_reference_ids(&self) -> Result<Vec<&str>, String> {
+ let mut ids = Vec::new();
+ for text in self.nodes.iter().map(|node| node.description.as_str()).chain([self.background.as_str()]) {
+ for id in super::reference_tokens::action_reference_ids(text)? {
+ if !ids.contains(&id) {
+ ids.push(id);
+ }
+ }
+ }
+ Ok(ids)
+ }
+
pub fn validate(&self) -> Result<(), String> {
if self.root_type.as_deref().is_some_and(|kind| !matches!(kind, "prompt" | "image")) {
return Err("Invalid image root type.".into());
diff --git a/src-tauri/src/tests/images.rs b/src-tauri/src/tests/images.rs
index e842cc9..e2bb4b1 100644
--- a/src-tauri/src/tests/images.rs
+++ b/src-tauri/src/tests/images.rs
@@ -305,6 +305,24 @@ fn granular_image_commands_edit_subtrees_without_touching_generated_outputs() {
}
}
+#[test]
+fn image_prompts_cite_existing_references_and_keep_them_from_removal() {
+ use crate::project::commands::{execute_commands_at, ProjectCommand};
+ let command = |value: serde_json::Value| -> ProjectCommand { serde_json::from_value(value).unwrap() };
+ let current = image_fixture();
+ let add = command(serde_json::json!({"op":"ref.add","id":"ref-mara","name":"Mara","text":"A lighthouse keeper","use":["character"]}));
+ let cite = command(serde_json::json!({"op":"image.configure","prompt":"@[ref:ref-mara] holds the lantern","background":"Fog"}));
+ let next = execute_commands_at(&current, &[add.clone(), cite], &current.updated_at).unwrap();
+ assert_eq!(next.image_scene.as_ref().unwrap().cited_reference_ids().unwrap(), ["ref-mara"]);
+ let remove = command(serde_json::json!({"op":"ref.remove","id":"ref-mara"}));
+ let error = execute_commands_at(&next, &[remove], &next.updated_at).unwrap_err();
+ assert!(error.contains("still used by the image"), "{error}");
+ for text in ["@[ref:missing] waves", "A @[ref:ref-mara"] {
+ let cite = command(serde_json::json!({"op":"image.configure","background":text}));
+ assert!(execute_commands_at(&current, &[add.clone(), cite], &current.updated_at).is_err(), "{text}");
+ }
+}
+
#[test]
fn invalid_image_commands_roll_back_the_entire_batch() {
use crate::project::commands::{execute_commands_at, ProjectCommand};
diff --git a/src/components/ImageProject.integration.test.tsx b/src/components/ImageProject.integration.test.tsx
index 05742f5..f190a84 100644
--- a/src/components/ImageProject.integration.test.tsx
+++ b/src/components/ImageProject.integration.test.tsx
@@ -132,8 +132,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 },
];
- // 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]";
+ // Only cited references reach the prompt; Unused is never cited.
+ project.config.imageScene!.nodes[0].description = "A @[ref:subject] launch over the ocean at dawn, @[ref:mood]";
render(<ProjectWorkspace project={project} onBack={vi.fn()} onSave={vi.fn()} />);
expect(screen.queryByRole("button", { name: "Debug prompt" })).not.toBeInTheDocument();
act(() => saveDebugOptionsEnabled(true));
@@ -147,7 +147,7 @@ it("shows the full image prompt at the end of the inspector only when debug is e
button.focus();
fireEvent.click(button);
const prompt = within(screen.getByRole("dialog", { name: "Debug prompt" })).getByLabelText("The compiled MiniMax H3 prompt");
- const compiled = imageScenePrompt(project.config.imageScene!, "Watercolor").replace("[Rocket]", "<Subject 1>").replace("[Mood]", "<Subject 2>");
+ const compiled = imageScenePrompt(project.config.imageScene!, "Watercolor").replace("@[ref:subject]", "<Subject 1>").replace("@[ref: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");
diff --git a/src/components/ProjectWorkspace.test.ts b/src/components/ProjectWorkspace.test.ts
index 0f3c07f..68263e4 100644
--- a/src/components/ProjectWorkspace.test.ts
+++ b/src/components/ProjectWorkspace.test.ts
@@ -19,7 +19,7 @@ import { SHOT_TAG_GROUPS } from "../lib/shot-tags";
import { chooseOption, optionNames } from "./workspace/comboTestUtils";
vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
-const storedLine = (field: HTMLElement) => promptValue(field, (id) => `@[ref:${id}]`);
+const storedLine = promptValue;
vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => undefined) }));
vi.mock("../lib/generatedVideo", () => ({ saveGeneratedScene: vi.fn(), releaseRendered: vi.fn(async () => true) }));
@@ -941,7 +941,7 @@ describe("project workspace timecode", () => {
// The picker says which references the scene already numbers.
fireEvent.click(screen.getByRole("button", { name: "Reference" }));
expect(within(screen.getByRole("dialog", { name: "Insert a reference" })).getAllByRole("button").map((button) => button.textContent))
- .toEqual(["Red-haired womanNot in this scene yet", "City streetNot in this scene yet"]);
+ .toEqual(["Red-haired womanNot in this scene yet · Text", "City streetNot in this scene yet · Text"]);
fireEvent.click(screen.getByRole("button", { name: "Reference" }));
insertPromptReference("Red-haired woman");
let next = onChange.mock.calls.at(-1)![0];
@@ -977,7 +977,7 @@ describe("project workspace timecode", () => {
fireEvent.click(line().querySelectorAll(".prompt-chip")[0]);
const picker = screen.getByRole("dialog", { name: "Change reference Red-haired woman" });
expect(within(picker).getAllByRole("button").map((button) => button.textContent))
- .toEqual(["Red-haired womanReference 1", "City streetReference 2", "Remove from the prompt"]);
+ .toEqual(["Red-haired womanReference 1 · Text", "City streetReference 2 · Text", "Remove from the prompt"]);
fireEvent.click(within(picker).getByRole("button", { name: /^City street/ }));
next = onChange.mock.calls.at(-1)![0];
show(next);
diff --git a/src/components/workspace/ImageEditor.test.tsx b/src/components/workspace/ImageEditor.test.tsx
index e41285b..3bc7b67 100644
--- a/src/components/workspace/ImageEditor.test.tsx
+++ b/src/components/workspace/ImageEditor.test.tsx
@@ -51,9 +51,9 @@ it("adds image files in edit mode and saves whole-image and drawn edits with sep
addFile();
await waitFor(() => expect(current().imageScene?.sourceImage).toEqual(source));
expect(screen.queryByRole("combobox", { name: "Type" })).not.toBeInTheDocument();
- // References come from what each prompt mentions; there is no list to tick.
+ // References come from what each prompt cites; there is no list to tick.
expect(screen.queryByRole("checkbox", { name: "Mood" })).not.toBeInTheDocument();
- typePrompt(screen.getByLabelText("Edit prompt"), "Make the lighting warmer like [Mood]");
+ typePrompt(screen.getByLabelText("Edit prompt"), "Make the lighting warmer like @[ref:Mood]");
expect(compileImageEdits(current()).edits[0]).toMatchObject({ x: 0, y: 0, width: 1000, height: 800 });
const canvas = screen.getByLabelText("Image placement canvas");
Object.defineProperty(canvas, "setPointerCapture", { value: vi.fn() });
@@ -70,7 +70,7 @@ it("adds image files in edit mode and saves whole-image and drawn edits with sep
pointer("pointerDown", 100, 80); pointer("pointerMove", 400, 320); pointer("pointerUp", 400, 320);
expect(current().imageScene!.nodes[1]).toMatchObject({ name: "Edit", box: { x: 100, y: 100, width: 300, height: 300 } });
expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("");
- typePrompt(screen.getByLabelText("Edit prompt"), "Add a red [Balloon]");
+ typePrompt(screen.getByLabelText("Edit prompt"), "Add a red @[ref:Balloon]");
const edits = compileImageEdits(current()).edits;
expect(edits.map((edit) => edit.references.map((reference) => reference.id))).toEqual([["Mood"], ["Balloon"]]);
const reopened = parseProjectConfig(JSON.parse(JSON.stringify(current())));
@@ -79,9 +79,9 @@ it("adds image files in edit mode and saves whole-image and drawn edits with sep
fireEvent.contextMenu(screen.getByLabelText("Generated images"));
fireEvent.click(screen.getByRole("menuitem", { name: "New empty image" }));
fireEvent.click(screen.getByRole("button", { name: "View Editing Imported" }));
- expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("Make the lighting warmer like [Mood]");
+ expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("Make the lighting warmer like @[ref:Mood]");
fireEvent.click(screen.getByRole("button", { name: "Edit" }));
- expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("Add a red [Balloon]");
+ expect(promptValue(screen.getByLabelText("Edit prompt"))).toBe("Add a red @[ref:Balloon]");
expect(screen.getByRole("button", { name: "Reference Balloon" })).toHaveClass("prompt-chip");
const beforeFailure = current();
vi.mocked(invoke).mockRejectedValueOnce(new Error("Image file is unreadable"));
diff --git a/src/components/workspace/ImageEditor.tsx b/src/components/workspace/ImageEditor.tsx
index 71b8667..03b9746 100644
--- a/src/components/workspace/ImageEditor.tsx
+++ b/src/components/workspace/ImageEditor.tsx
@@ -7,7 +7,7 @@ import { outputDimensions } from "../../lib/export";
import { compileImagePrompt } from "../../lib/imagePrompt";
import { createEmptyImage, restoreGeneratedImage, saveImageDraft } from "../../lib/imageHistory";
import { isTauri } from "../../lib/persistence";
-import { IMAGE_RESOLUTIONS, type ProjectConfig } from "../../lib/project";
+import { IMAGE_RESOLUTIONS, referenceTypeLabel, type ProjectConfig } from "../../lib/project";
import { defaultGeneratorTemplate, loadDebugOptionsEnabled, loadGeneratorTemplateSettings, subscribeDebugOptions, subscribeGeneratorTemplates, templateNeedsDownload, type GeneratorTemplate } from "../../lib/settings";
import { isWorkActive, type WorkItem } from "../../lib/workQueue";
import type { ConfigUpdate } from "./TimelineView";
@@ -436,7 +436,9 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene
const rootField = (field: string) => `${editorId}-${field}`;
const 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 />} /> }));
+ .map((reference) => ({ id: reference.id, name: reference.name, detail: referenceTypeLabel(reference), icon: <ReferenceIcon reference={reference} folderPath={folderPath} fallback={reference.kind === "image" ? <Image16 /> : <Text16 />} /> }));
+ // A chip for a video or audio reference names it; one deleted says so.
+ const missingReference = (id: string) => config.references.find((reference) => reference.id === id)?.name ?? "Deleted reference";
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}>
@@ -581,10 +583,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={(description) => patchNode({ description })} /></div>
+ <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} missingLabel={missingReference} 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 && <>
- <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>
+ <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} missingLabel={missingReference} 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>
diff --git a/src/components/workspace/PromptTextField.test.tsx b/src/components/workspace/PromptTextField.test.tsx
index bcef944..76b7759 100644
--- a/src/components/workspace/PromptTextField.test.tsx
+++ b/src/components/workspace/PromptTextField.test.tsx
@@ -4,11 +4,15 @@ import { useState } from "react";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
import { PromptTextField, type PromptReference } from "./PromptTextField";
-import { canCitePromptReference, promptReferenceNames, splitPromptText } from "../../lib/promptReferences";
+import { referenceTypeLabel, type ProjectReference } from "../../lib/project";
afterEach(cleanup);
-const references: PromptReference[] = [{ id: "hero", name: "Hero", icon: <img alt="" src="data:image/png;base64," data-testid="hero-icon" /> }, { id: "castle", name: "Castle" }, { id: "odd", name: "Odd [v2]" }];
+const references: PromptReference[] = [
+ { id: "hero", name: "Hero", icon: <img alt="" src="data:image/png;base64," data-testid="hero-icon" /> },
+ { id: "castle", name: "Castle" },
+ { id: "odd]", name: "Odd" },
+];
function setup(initial: string, onInsertReference = vi.fn()) {
let latest = initial;
@@ -30,35 +34,25 @@ const caretAt = (node: Node, offset: number) => {
fireEvent(document, new Event("selectionchange"));
};
-it("reads references out of the text as [Name]", () => {
- expect(splitPromptText("A [Hero] at the [Castle].")).toEqual([
- { kind: "text", value: "A " }, { kind: "reference", value: "Hero" }, { kind: "text", value: " at the " },
- { kind: "reference", value: "Castle" }, { kind: "text", value: "." },
- ]);
- expect(splitPromptText("[] and [a\nb] stay text")).toEqual([{ kind: "text", value: "[] and [a\nb] stay text" }]);
- expect(promptReferenceNames("[Hero] meets [Castle] and [Hero]")).toEqual(["Hero", "Castle"]);
- expect(canCitePromptReference("Odd [v2]")).toBe(false);
-});
-
-it("shows references as chips, and ones no reference is named as missing", () => {
- const { field } = setup("[Hero] walks to [Tower]");
+it("shows cited references as chips by name, and a deleted one as missing", () => {
+ const { field } = setup("@[ref:hero] walks to @[ref:tower]");
const chips = field.querySelectorAll(".prompt-chip");
- expect([...chips].map((chip) => chip.textContent)).toEqual(["Hero", "Tower"]);
+ expect([...chips].map((chip) => chip.textContent)).toEqual(["Hero", "Deleted reference"]);
expect(chips[1]).toHaveClass("prompt-chip--missing");
expect(chips[0]).toHaveAttribute("contenteditable", "false");
- expect(field).toHaveTextContent("Hero walks to Tower");
+ expect(field).toHaveTextContent("Hero walks to Deleted reference");
});
-it("inserts the chosen reference at the caret from the toolbar", () => {
+it("inserts the chosen reference at the caret from the toolbar, never fused to a word", () => {
const onInsert = vi.fn();
const { field, value } = setup("A knight rides", onInsert);
caretAt(field.firstChild!, 2);
fireEvent.click(screen.getByRole("button", { name: "Reference" }));
expect(screen.getByRole("dialog", { name: "Insert a reference" })).toBeInTheDocument();
- expect(screen.getByRole("button", { name: "Odd [v2]" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Odd" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Hero" })).toContainElement(screen.getByTestId("hero-icon"));
fireEvent.click(screen.getByRole("button", { name: "Hero" }));
- expect(value()).toBe("A [Hero] knight rides");
+ expect(value()).toBe("A @[ref:hero] knight rides");
expect(onInsert).toHaveBeenCalledWith(references[0]);
expect(field.querySelector(".prompt-chip")).toHaveTextContent("Hero");
expect(screen.queryByRole("dialog")).toBeNull();
@@ -68,39 +62,48 @@ it("adds a reference at the end of a field that was never focused", () => {
const { value } = setup("Ride to ");
fireEvent.click(screen.getByRole("button", { name: "Reference" }));
fireEvent.click(screen.getByRole("button", { name: "Castle" }));
- expect(value()).toBe("Ride to [Castle]");
+ expect(value()).toBe("Ride to @[ref:castle]");
});
it("opens the picker from a chip to change it or take it out", () => {
- const { field, value } = setup("[Hero] at the [Hero] gate");
+ const { field, value } = setup("@[ref:hero] at the @[ref:hero] gate");
fireEvent.click(field.querySelectorAll(".prompt-chip")[1]);
expect(screen.getByRole("dialog", { name: "Change reference Hero" })).toHaveTextContent("Cites Hero");
expect(screen.getByRole("button", { name: "Hero" })).toHaveAttribute("aria-pressed", "true");
fireEvent.click(screen.getByRole("button", { name: "Castle" }));
- expect(value()).toBe("[Hero] at the [Castle] gate");
+ expect(value()).toBe("@[ref:hero] at the @[ref:castle] gate");
fireEvent.click(field.querySelectorAll(".prompt-chip")[0]);
fireEvent.click(screen.getByRole("button", { name: "Remove from the prompt" }));
- expect(value()).toBe(" at the [Castle] gate");
+ expect(value()).toBe(" at the @[ref:castle] gate");
expect(field.querySelectorAll(".prompt-chip")).toHaveLength(1);
});
-it("turns a [Name] typed by hand into a chip and keeps line breaks as text", () => {
+it("turns a token pasted or typed by hand into a chip and keeps line breaks as text", () => {
const { field, value } = setup("");
- field.textContent = "Meet [Hero]";
+ field.textContent = "Meet @[ref:hero]";
fireEvent.input(field);
- expect(value()).toBe("Meet [Hero]");
+ expect(value()).toBe("Meet @[ref:hero]");
expect(field.querySelector(".prompt-chip")).toHaveTextContent("Hero");
field.focus();
caretAt(field.firstChild!, 4);
fireEvent.keyDown(field, { key: "Enter" });
- expect(value()).toBe("Meet\n [Hero]");
+ expect(value()).toBe("Meet\n @[ref:hero]");
});
it("pastes only the characters", () => {
const { field, value } = setup("Hello");
caretAt(field.firstChild!, 5);
- fireEvent.paste(field, { clipboardData: { getData: (type: string) => type === "text/plain" ? " <b>[Castle]</b>\r\nnext" : "" } });
- expect(value()).toBe("Hello <b>[Castle]</b>\nnext");
+ fireEvent.paste(field, { clipboardData: { getData: (type: string) => type === "text/plain" ? " <b>@[ref:castle]</b>\r\nnext" : "" } });
+ expect(value()).toBe("Hello <b>@[ref:castle]</b>\nnext");
+});
+
+it("names a refmod reference as a refmod, whatever else it holds", () => {
+ const base = { description: "", intendedUse: [], createdAt: "2026-01-01T00:00:00.000Z" };
+ const refmods = [{ id: "encoded", name: "Identity", sourcePath: "D:/identity.safetensors", strength: 1, copies: 1 }];
+ expect(referenceTypeLabel({ ...base, id: "a", kind: "text", name: "A", refmods } as ProjectReference)).toBe("Refmod");
+ expect(referenceTypeLabel({ ...base, id: "b", kind: "image", name: "B", relativePath: "b.png", refmods } as ProjectReference)).toBe("Refmod");
+ expect(referenceTypeLabel({ ...base, id: "c", kind: "image", name: "C", relativePath: "c.png" } as ProjectReference)).toBe("Image");
+ expect(referenceTypeLabel({ ...base, id: "d", kind: "text", name: "D" } as ProjectReference)).toBe("Text");
});
diff --git a/src/components/workspace/PromptTextField.tsx b/src/components/workspace/PromptTextField.tsx
index 179f893..414db15 100644
--- a/src/components/workspace/PromptTextField.tsx
+++ b/src/components/workspace/PromptTextField.tsx
@@ -1,5 +1,5 @@
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from "react";
-import { canCitePromptReference, promptReferenceToken, splitPromptText, type PromptPart } from "../../lib/promptReferences";
+import { canTokenizeReference, referenceToken, splitActionText, type ActionPart } from "../../lib/project";
import { Add14, Delete14 } from "../ui/icons";
import { Flyout, TextField } from "../ui";
import "../../styles/prompt-field.css";
@@ -17,26 +17,27 @@ export interface PromptReference {
* and carries its key: what `split` reads out of the token and `token` writes
* back. */
export interface PromptTokenFormat {
- split: (text: string) => PromptPart[];
+ split: (text: string) => ActionPart[];
token: (key: string) => string;
key: (reference: PromptReference) => string;
/** Why a reference cannot be written as a token, or null when it can. */
uncitable?: (reference: PromptReference) => string | null;
}
-/** `[Name]` — readable in the saved text, and what a person may type by hand. */
-export const NAME_TOKENS: PromptTokenFormat = {
- split: splitPromptText,
- token: promptReferenceToken,
- key: (reference) => reference.name,
- uncitable: (reference) => canCitePromptReference(reference.name) ? null : "Rename it without brackets to cite it in a prompt",
+/** `@[ref:<id>]` — an id survives a rename and a reorder; the chip shows the
+ * name. The same token the video compiler and the agent read. */
+export const REFERENCE_TOKENS: PromptTokenFormat = {
+ split: splitActionText,
+ token: referenceToken,
+ key: (reference) => reference.id,
+ uncitable: (reference) => canTokenizeReference(reference.id) ? null : "This reference can’t be written into a prompt",
};
/* A multi-line prompt whose references are smart chips inside the text.
The value is plain text with each reference written into it as a token —
- `[Name]` by default (see lib/promptReferences), or any other `format` — and
- the field shows every token as a chip. The Reference button on the toolbar
+ `@[ref:<id>]` by default, or any other `format` — and the field shows every
+ token as a chip. The Reference button on the toolbar
above opens a picker and drops the chosen reference at the caret; clicking a
chip opens the same picker to change it to another reference or take it out.
@@ -68,7 +69,7 @@ interface Chips {
missingLabel: (key: string) => string;
}
-export function PromptTextField({ value, onChange, references, format = NAME_TOKENS, missingLabel = (key) => key, missingTooltip = "No reference has this name — click to choose one", onInsertReference, disabled = false, placeholder, rows = 4, id, className, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy }: {
+export function PromptTextField({ value, onChange, references, format = REFERENCE_TOKENS, missingLabel = () => "Deleted reference", missingTooltip = "Left out of the prompt — click to swap it for another reference or remove it", onInsertReference, disabled = false, placeholder, rows = 4, id, className, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy }: {
value: string;
onChange: (value: string) => void;
/** The references the picker offers; a chip for any other key is missing. */
diff --git a/src/components/workspace/SceneEditor.tsx b/src/components/workspace/SceneEditor.tsx
index 296e609..3c41d01 100644
--- a/src/components/workspace/SceneEditor.tsx
+++ b/src/components/workspace/SceneEditor.tsx
@@ -3,12 +3,12 @@ import { useId, useMemo, useState, type ReactNode } from "react";
import { ComboBox, InfoBar, PropRow, PropSection } from "../ui";
import {
actionReferenceIds,
- canTokenizeReference,
danglingReferenceTokens,
isReferenceUsable,
isVisualReference,
isVideoTransition,
referenceImages,
+ referenceTypeLabel,
usableVideoReferences,
normalizeSceneShots,
referenceToken,
@@ -37,18 +37,9 @@ import {
type ShotTagSelection,
} from "../../lib/shot-tags";
import { CommittedNumberInput } from "./CommittedNumberInput";
-import { PromptTextField, type PromptTokenFormat } from "./PromptTextField";
+import { PromptTextField } from "./PromptTextField";
import { ReferenceIcon } from "./ReferenceIcon";
-/** A line cites a reference by id — `@[ref:<id>]` — which survives a rename
- * and a reorder; the chip shows its name. */
-const ACTION_TOKENS: PromptTokenFormat = {
- split: splitActionText,
- token: referenceToken,
- key: (reference) => reference.id,
- uncitable: (reference) => canTokenizeReference(reference.id) ? null : "This reference can’t be written into a line",
-};
-
/** The step the length slider and the cut handles move in. Half a second is the
* finest cut the timestamp format prints exactly (`formatSceneSeconds`), so
* nothing here can set a time the prompt then rounds behind the user's back. */
@@ -137,7 +128,7 @@ export function ShotInspector({ job, shots, shot, index, endsAt, duration, refer
const pickable = useMemo(() => citable.map((reference) => {
const number = numbered.findIndex((item) => item.id === reference.id) + 1;
return {
- id: reference.id, name: reference.name, detail: number > 0 ? `Reference ${number}` : "Not in this scene yet",
+ id: reference.id, name: reference.name, detail: `${number > 0 ? `Reference ${number}` : "Not in this scene yet"} · ${referenceTypeLabel(reference)}`,
icon: <ReferenceIcon reference={reference} folderPath={folderPath} fallback={reference.kind === "video" ? <Video16 /> : referenceImages(reference).length ? <Image16 /> : <Text16 />} />,
};
}), [citable, numbered, folderPath]);
@@ -184,10 +175,8 @@ export function ShotInspector({ job, shots, shot, index, endsAt, duration, refer
aria-label={`Describe shot ${shotNumber}`}
rows={6}
value={shot.action}
- format={ACTION_TOKENS}
references={pickable}
missingLabel={(referenceId) => referenceById.get(referenceId)?.name ?? "Deleted reference"}
- missingTooltip="Left out of the prompt — click to swap it for another reference or remove it"
disabled={disabled}
placeholder={job.sceneType === "pose" ? "Example: a dancer in a red coat performs this movement on a rainy city street." : "Example: she walks towards the camera and stops under the awning."}
onChange={(action) => onChange({ action })}
diff --git a/src/components/workspace/promptTestUtils.ts b/src/components/workspace/promptTestUtils.ts
index de811fc..3a7297c 100644
--- a/src/components/workspace/promptTestUtils.ts
+++ b/src/components/workspace/promptTestUtils.ts
@@ -8,8 +8,8 @@ export const typePrompt = (field: HTMLElement, text: string) => {
fireEvent.input(field);
};
-/** The value on screen; `token` writes a chip's key back (default `[Name]`). */
-export const promptValue = (field: HTMLElement, token = (key: string) => `[${key}]`): string =>
+/** The value on screen, each chip written back as the token it stands for. */
+export const promptValue = (field: HTMLElement, token = (key: string) => `@[ref:${key}]`): string =>
[...field.childNodes].map((node) => node instanceof HTMLElement && node.dataset.promptReference !== undefined
? token(node.dataset.promptReference) : node.textContent ?? "").join("").replaceAll("​", "");
diff --git a/src/lib/imageEditing.test.ts b/src/lib/imageEditing.test.ts
index 0831e31..b4353f2 100644
--- a/src/lib/imageEditing.test.ts
+++ b/src/lib/imageEditing.test.ts
@@ -39,7 +39,7 @@ it("reserves Picture 1 for the source and counts it toward H3's nine-picture lim
config.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 }));
- const mention = (count: number) => `A red balloon ${config.references.slice(0, count).map((reference) => `[${reference.name}]`).join(" ")}`;
+ const mention = (count: number) => `A red balloon ${config.references.slice(0, count).map((reference) => `@[ref:${reference.id}]`).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>");
@@ -64,17 +64,17 @@ it("starts with a clean image root and requires described edits before submissio
expect(parseProjectConfig(JSON.parse(JSON.stringify(edited))).imageScene).toEqual(edited.imageScene);
});
-it("applies whole-image actions first and compiles only the references each edit mentions", () => {
+it("applies whole-image actions first and compiles only the references each edit cites", () => {
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 like [Lighting]";
- // Stored ids no longer choose anything: only mentions do.
+ root.description = "Warm up the entire image like @[ref:Lighting]";
+ // Stored ids no longer choose anything: only citations 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]" });
+ Object.assign(config.imageScene.nodes[1], { description: "Add a @[ref: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 like <Subject 1>");
@@ -87,6 +87,6 @@ it("applies whole-image actions first and compiles only the references each edit
config.imageScene.nodes[1].description = "Add a balloon";
edits = compileImageEdits(config).edits;
expect(edits[1].references).toEqual([]);
- config.imageScene.nodes[1].description = "Add a [missing]";
- expect(() => compileImageEdits(config)).toThrow("The prompt mentions [missing]");
+ config.imageScene.nodes[1].description = "Add a @[ref:missing]";
+ expect(() => compileImageEdits(config)).toThrow("The prompt cites a reference that no longer exists.");
});
diff --git a/src/lib/imageHistory.ts b/src/lib/imageHistory.ts
index 14c1369..35a9c84 100644
--- a/src/lib/imageHistory.ts
+++ b/src/lib/imageHistory.ts
@@ -1,10 +1,9 @@
import { createImageEditScene, createImageScene, imageSceneReferenceIds, imageScenePromptText } from "./imageScene";
-import { promptReferenceNames } from "./promptReferences";
-import type { ImageGenerationSnapshot, ProjectAsset, ProjectConfig } from "./project";
+import { actionReferenceIds, type ImageGenerationSnapshot, type ProjectAsset, type 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));
+ const cited = actionReferenceIds(imageScenePromptText(scene));
return structuredClone({
scene: { ...scene, outputAssetId: null },
resolution: config.settings.resolution,
@@ -13,10 +12,9 @@ export function imageGenerationSnapshot(config: ProjectConfig, prompt: string, g
briefPrompt: config.brief.prompt,
prompt,
generatorTemplateId,
- // 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))),
+ // What the prompt cites, plus any ids a scene saved before citations were
+ // how references are chosen (the snapshot schema still checks them).
+ references: config.references.filter((reference) => imageSceneReferenceIds(scene).includes(reference.id) || cited.includes(reference.id)),
});
}
diff --git a/src/lib/imagePrompt.test.ts b/src/lib/imagePrompt.test.ts
index 3e17762..d4493cb 100644
--- a/src/lib/imagePrompt.test.ts
+++ b/src/lib/imagePrompt.test.ts
@@ -52,8 +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 },
];
- // 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";
+ // Only citations choose references, in the order they are first cited.
+ config.imageScene!.nodes[0].description = "On @[ref:track] in @[ref:palette] tones, @[ref: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:"]);
@@ -69,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!.nodes[0].description = "[Missing] runs";
- expect(() => compileImagePrompt(config)).toThrow("The prompt mentions [Missing], but no image or text reference has that name.");
+ config.imageScene!.nodes[0].description = "@[ref:missing] runs";
+ expect(() => compileImagePrompt(config)).toThrow("The prompt cites a reference that no longer exists.");
});
it("uses the brief for legacy image documents and leaves genuinely empty prompts empty", () => {
@@ -84,14 +84,14 @@ 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!.nodes[0].description = "[Woman] suspended mid-stride";
+ config.imageScene!.nodes[0].description = "@[ref:identity] 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;
// With nothing to condition on, the mention reads as the plain name.
- expect(compileImagePrompt(config).prompt).not.toMatch(/<Subject|\[Woman\]/);
+ expect(compileImagePrompt(config).prompt).not.toMatch(/<Subject|@\[ref:/);
expect(compileImagePrompt(config).prompt).toContain("Woman suspended mid-stride.");
expect(compileImagePrompt(config).prompt).toMatch(/^integrated_multimodal_description: \[Shot 1\]/);
});
@@ -102,13 +102,13 @@ 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!.nodes[0].description = "[Disabled] and a [Style] frame around [Runner]";
+ config.imageScene!.nodes[0].description = "@[ref:disabled] and a @[ref:style] frame around @[ref: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,|is Disabled|<Subject 3>|<Picture 2>|<Video/);
});
- it("passes only the references the prompt mentions, from any node or the background", () => {
+ it("passes only the references the prompt cites, 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 },
@@ -118,10 +118,10 @@ describe("MiniMax H3 still-image prompts", () => {
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" };
+ scene.nodes.at(-1)!.description = "@[ref:hero] waving";
+ config.imageScene = { ...scene, background: "A @[ref:sky] over the hills" };
expect(compileImagePrompt(config).references.map((reference) => reference.id)).toEqual(["hero", "sky"]);
- config.imageScene.background = "[Clip]";
- expect(() => compileImagePrompt(config)).toThrow("[Clip]");
+ config.imageScene.background = "@[ref:clip]";
+ expect(() => compileImagePrompt(config)).toThrow("the prompt cites the video reference 'Clip'");
});
});
diff --git a/src/lib/imagePrompt.ts b/src/lib/imagePrompt.ts
index 7531574..b8c957c 100644
--- a/src/lib/imagePrompt.ts
+++ b/src/lib/imagePrompt.ts
@@ -1,14 +1,18 @@
import { createImageScene, imageScenePromptParts, imageScenePromptText } from "./imageScene";
-import { replacePromptReferences, resolvePromptReferences } from "./promptReferences";
-import { activeReferenceRefmods, referenceDefinition, referenceImages, type ProjectConfig } from "./project";
+import { actionReferenceIds, activeReferenceRefmods, referenceDefinition, referenceImages, splitActionText, type ProjectConfig } from "./project";
import { SHOT_TAG_GROUPS } from "./shot-tags";
/** Shared by generation and Debug Prompt. H3's base three-field / reference
* six-section contracts still apply to a single silent image. */
export function compileImagePrompt(config: ProjectConfig) {
const scene = config.imageScene ?? createImageScene(config.brief.prompt);
- // 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"));
+ // Only the references the prompt cites as @[ref:<id>] go to the generation.
+ const references = actionReferenceIds(imageScenePromptText(scene)).map((id) => {
+ const reference = config.references.find((candidate) => candidate.id === id);
+ if (!reference) throw new Error("The prompt cites a reference that no longer exists. Swap or remove it before generating.");
+ if (reference.kind === "video" || reference.kind === "audio") throw new Error(`Still images accept image and text references; the prompt cites the ${reference.kind} reference '${reference.name}'.`);
+ return reference;
+ });
// 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);
@@ -22,16 +26,20 @@ export function compileImagePrompt(config: ProjectConfig) {
const description = /[.!?。!?]$/.test(content) ? content : `${content}.`;
const role = reference.intendedUse.includes("character") || reference.intendedUse.includes("animal") ? "identity and appearance" : reference.intendedUse.includes("style") ? "visual style" : "appearance";
const sources = [...labels, ...(refmods.length ? ["the supplied reference conditioning"] : [])];
- return [{ name: reference.name, role, description, source: sources.length ? ` from ${sources.join(" and ")}` : "" }];
+ return [{ id: reference.id, name: reference.name, role, description, source: sources.length ? ` from ${sources.join(" and ")}` : "" }];
});
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 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) };
+ // A citation reads as the subject it defines, or by name when it defines none.
+ const cite = (text: string) => splitActionText(text).map((part) => {
+ if (part.kind === "text") return part.value;
+ const index = subjects.findIndex((subject) => subject.id === part.value);
+ return index < 0 ? references.find((reference) => reference.id === part.value)!.name : label(index);
+ }).join("");
+ const visual = { style: cite(parts.style), composition: cite(parts.composition) };
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,
diff --git a/src/lib/imageScene.ts b/src/lib/imageScene.ts
index 78aa2c8..c869a43 100644
--- a/src/lib/imageScene.ts
+++ b/src/lib/imageScene.ts
@@ -45,7 +45,7 @@ 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]. */
+/** Every authored line of the scene a reference can be cited in as @[ref:<id>]. */
export const imageScenePromptText = (scene: ImageScene): string =>
[...scene.nodes.map((node) => node.description), scene.background].join("\n");
diff --git a/src/lib/project.ts b/src/lib/project.ts
index 8798298..f6be2ca 100644
--- a/src/lib/project.ts
+++ b/src/lib/project.ts
@@ -740,6 +740,14 @@ export const referenceRefmodInputs = (folderPath: string, references: ProjectRef
* route would be a guess. The tag is no longer offered in the UI; this only
* meets references saved before that. A reference carrying any other tag, or
* no tag at all, is visible content as before. */
+/** The kind a picker names a reference by. A refmod reference steers the
+ * model with its encoded conditioning, whatever else it holds. */
+export function referenceTypeLabel(reference: ProjectReference): "Refmod" | "Video" | "Image" | "Text" {
+ if (reference.refmods?.length) return "Refmod";
+ if (reference.kind === "video") return "Video";
+ return reference.kind === "image" || referenceImages(reference).length ? "Image" : "Text";
+}
+
export function isVisualReference(reference: ProjectReference): boolean {
return reference.kind === "video" || reference.intendedUse.length === 0 || reference.intendedUse.some((use) => use !== "audio");
}
diff --git a/src/lib/promptReferences.ts b/src/lib/promptReferences.ts
deleted file mode 100644
index c6e5e59..0000000
--- a/src/lib/promptReferences.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-/** References cited inside a free-text prompt, stored in the text itself as
- * `[Reference name]`. The prompt field reads the same syntax back and shows
- * each one as a smart chip, so what is saved and what is shown are one parse.
- * A name holding a bracket or a line break could not be read back, so such a
- * reference cannot be cited this way. */
-
-export interface PromptPart {
- kind: "text" | "reference";
- /** The literal characters for `text`; the reference name for `reference`. */
- value: string;
-}
-
-const PROMPT_REFERENCE = /\[([^[\]\n]+)\]/g;
-
-export const promptReferenceToken = (name: string): string => `[${name}]`;
-
-export const canCitePromptReference = (name: string): boolean => name.trim().length > 0 && !/[[\]\n]/.test(name);
-
-export function splitPromptText(text: string): PromptPart[] {
- const parts: PromptPart[] = [];
- let cursor = 0;
- for (const match of text.matchAll(PROMPT_REFERENCE)) {
- const at = match.index ?? 0;
- if (at > cursor) parts.push({ kind: "text", value: text.slice(cursor, at) });
- parts.push({ kind: "reference", value: match[1] });
- cursor = at + match[0].length;
- }
- if (cursor < text.length) parts.push({ kind: "text", value: text.slice(cursor) });
- return parts;
-}
-
-/** Every reference name cited by a prompt, in the order it is first cited. */
-export function promptReferenceNames(text: string): string[] {
- const seen: string[] = [];
- for (const part of splitPromptText(text)) {
- if (part.kind === "reference" && !seen.includes(part.value)) seen.push(part.value);
- }
- 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/runtime.ts b/src/lib/runtime.ts
index 2f7a0a7..e2b3a79 100644
--- a/src/lib/runtime.ts
+++ b/src/lib/runtime.ts
@@ -1,5 +1,5 @@
import { invoke } from "@tauri-apps/api/core";
-import { createImageScene } from "./imageScene";
+import { createImageScene, imageScenePromptText } from "./imageScene";
import { applyImageCommand, type ImageCommand } from "./imageCommands";
import { isTauri } from "./persistence";
import type { TemplateLora } from "./loras";
@@ -316,6 +316,7 @@ function executeDemoCommands(config: ProjectConfig, commands: ProjectCommand[]):
if (next.generationType !== "image") throw new Error(`${command.op} requires an image project.`);
const scene = applyImageCommand(next.imageScene ?? createImageScene(next.brief.prompt), command);
for (const id of scene.referenceIds) if (!next.references.some((reference) => reference.id === id && ["image", "text"].includes(reference.kind))) throw new Error(`Image reference '${id}' must name an existing image or text reference.`);
+ for (const id of actionReferenceIds(imageScenePromptText(scene))) if (!next.references.some((reference) => reference.id === id && ["image", "text"].includes(reference.kind))) throw new Error(`The image cites '@[ref:${id}]', which must name an existing image or text reference.`);
next.imageScene = scene;
break;
}
@@ -347,8 +348,8 @@ function executeDemoCommands(config: ProjectConfig, commands: ProjectCommand[]):
break;
}
case "ref.remove": {
- if (next.imageScene?.referenceIds.includes(command.id)) throw new Error(`Reference '${command.id}' is still used by the image; update image.set before removing it.`);
const token = `@[ref:${command.id}]`;
+ if (next.imageScene && (next.imageScene.referenceIds.includes(command.id) || imageScenePromptText(next.imageScene).includes(token))) throw new Error(`Reference '${command.id}' is still used by the image; remove its citations before removing it.`);
if (next.generationJobs.some((job) => job.startFrameReferenceId === command.id || job.endFrameReferenceId === command.id || job.shots?.some((shot) => shot.action.includes(token)))) {
throw new Error(`Reference '${command.id}' is still used by a scene.`);
}
diff --git a/src/lib/workQueue.test.ts b/src/lib/workQueue.test.ts
index cbb145a..4dc6d91 100644
--- a/src/lib/workQueue.test.ts
+++ b/src/lib/workQueue.test.ts
@@ -89,9 +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 like [Lighting]";
+ scene.nodes[0].description = "Make the light warmer like @[ref:Lighting]";
scene = addImageNode(scene, "image-root", "object");
- Object.assign(scene.nodes[1], { name: "Edit", description: "Add a red [Balloon]" });
+ Object.assign(scene.nodes[1], { name: "Edit", description: "Add a red @[ref: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,
@@ -122,7 +122,7 @@ 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 like [Balloon]", "A blue boat beside [Balloon]"]) {
+ for (const description of ["A red balloon like @[ref:balloon]", "A blue boat beside @[ref:balloon]"]) {
scene = addImageNode(scene, "image-root", "object");
scene.nodes.at(-1)!.description = description;
}
@@ -222,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!.nodes[0].description += " with [Person]";
+ project.config.imageScene!.nodes[0].description += " with @[ref:person]";
queue.enqueueImage(queue.project(project), template);
await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce());
const request = vi.mocked(enqueueSlopfabGeneration).mock.calls[0][0];
@@ -238,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!.nodes[0].description += " over [Ocean]";
+ project.config.imageScene!.nodes[0].description += " over @[ref:ocean]";
const preview = compileImagePrompt(project.config).prompt;
queue.enqueueImage(queue.project(project), template);
await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce());