AI media harness for planning, generating, and editing locally
TypeScript
Stop sending filenames and app boilerplate to the model
Bitti0067f8492443
diff --git a/src/components/ProjectWorkspace.test.ts b/src/components/ProjectWorkspace.test.tsindex 775cbd1..ee103b1 100644--- a/src/components/ProjectWorkspace.test.ts+++ b/src/components/ProjectWorkspace.test.ts@@ -1,17 +1,34 @@// @vitest-environment jsdom-import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { createElement } from "react";import { afterEach, describe, expect, it, vi } from "vitest";import completeFixture from "../../fixtures/project-v1-complete.json";-import { createProjectConfig, parseProjectConfig } from "../lib/project";+import { compileMiniMaxH3Prompt, createProjectConfig, parseProjectConfig } from "../lib/project";import { formatDurationTimecode } from "./ProjectWorkspace";import { ProjectWorkspace } from "./ProjectWorkspace";import { GeneratorView } from "./workspace/GeneratorView";+import { ReferencesView } from "./workspace/ReferencesView";import { TimelineView } from "./workspace/TimelineView";+vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));+afterEach(cleanup);+/** Runs `body` with the app believing it is inside the desktop shell, so the+ * REAL Tauri import path executes instead of the browser fallback. */+async function asDesktopApp(importedImage: { name: string; relativePath: string }, body: () => void | Promise<void>) {+ const { invoke } = await import("@tauri-apps/api/core");+ (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__ = {};+ vi.mocked(invoke).mockResolvedValue(importedImage);+ try {+ await body();+ } finally {+ delete (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__;+ vi.mocked(invoke).mockReset();+ }+}+describe("project workspace timecode", () => {it("formats project duration as valid hours, minutes, and seconds", () => {expect(formatDurationTimecode(0)).toBe("00:00:00");@@ -174,11 +191,15 @@ describe("project workspace timecode", () => {references: [{ id: "ref-text", kind: "text", name: "Mara", description: "Calm architect.", content: "Calm architect.", intendedUse: ["character"], createdAt: fresh.createdAt }],generationJobs: [{ ...fresh.generationJobs[0], referenceIds: ["ref-text"] }],});- render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange: () => undefined, onOpenTimeline: () => undefined, selectedJobId: fresh.generationJobs[0].id }));- const refs = document.querySelector(".job-refs")!.textContent ?? "";- expect(refs).toContain("The text definition is written into this shot’s prompt.");- // No image is bound, so nothing is sent to the engine as an asset.- expect(refs).not.toContain("Images are sent to the video engine");+ const { container } = render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange: () => undefined, onOpenTimeline: () => undefined, selectedJobId: fresh.generationJobs[0].id }));+ expect(document.querySelector(".job-refs")!.textContent).toContain("The text definition is written into this shot’s prompt.");+ // The composer hint says the same thing about the same references. Scoping+ // this to .job-refs hid a second copy of the claim that was still wrong.+ expect(container.querySelector(".generation-composer__hint")!.textContent).toContain("The text definition is written into the prompt.");+ // No image exists anywhere in this project, so NOTHING on the screen may+ // claim something is sent to the engine as an asset.+ expect(container.textContent).not.toContain("images are sent to the video engine");+ expect(container.textContent).not.toContain("Images are sent to the video engine");});it("says why Duplicate and Delete are unavailable, not just that they are", () => {@@ -191,6 +212,36 @@ describe("project workspace timecode", () => {}});+ it("sends no filename and no app boilerplate to the model for a really imported image", async () => {+ // Built the way the PRODUCT builds it — the actual "Add image" button and+ // the actual Tauri import path — not a hand-written reference with a tidy+ // name and description. Every earlier compiler test supplied both by hand,+ // which is exactly why this shipped.+ const config = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });+ const onChange = vi.fn();+ await asDesktopApp({ name: "IMG_4821", relativePath: "references/IMG_4821.jpg" }, async () => {+ render(createElement(ReferencesView, { config, folderPath: "C:\\Ceramic Lamp", onChange }));+ fireEvent.click(screen.getByRole("button", { name: "Add image" }));+ await waitFor(() => expect(onChange).toHaveBeenCalled());+ });++ const imported = onChange.mock.calls[0][0].references[0];+ expect(imported.relativePath).toBe("references/IMG_4821.jpg");+ // The import writes no prose: description is what the compiler hands the+ // model as the user's own account of the picture.+ expect(imported.description).toBe("");++ const compiled = compileMiniMaxH3Prompt("a cat walking across a sunny kitchen floor", [imported]);+ expect(compiled).toContain("<Subject 1> is the content shown in <Picture 1>.");+ for (const line of compiled.split("\n").filter((row) => row.startsWith("<Subject "))) {+ expect(line).not.toContain("IMG_4821");+ expect(line).not.toContain("Visual reference");+ }+ expect(compiled).not.toContain("IMG_4821");+ expect(compiled).not.toContain("Visual reference");+ expect(compiled).toContain("fully_preserved - the referenced characteristics are retained.");+ });+it("labels a cancelled preview as cancelled instead of queued", () => {const fresh = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });const config = parseProjectConfig({ ...fresh, generationJobs: [{ ...fresh.generationJobs[0], status: "cancelled", stage: "failed" }] });diff --git a/src/components/ProjectWorkspace.tsx b/src/components/ProjectWorkspace.tsxindex b5c0f2a..a215c80 100644--- a/src/components/ProjectWorkspace.tsx+++ b/src/components/ProjectWorkspace.tsx@@ -45,11 +45,11 @@ export function ProjectWorkspace({ project, initialView = "timeline", onBack, onsetDirty(true);};- const save = async () => {+ const save = async (record?: ProjectRecord) => {setSaving(true);setSaveError(null);try {- await onSave({ ...project, config });+ await onSave(record ?? { ...project, config });setDirty(false);} catch (reason) {setSaveError(reason instanceof Error ? reason.message : String(reason));@@ -105,7 +105,11 @@ export function ProjectWorkspace({ project, initialView = "timeline", onBack, on{ id: "codex", label: "Codex", state: "unavailable", executable: null, version: null, detail: "Checking provider…" },]}onProviderChange={selectProvider}- onRecord={(record) => { setConfig(record.config); setDirty(false); void onSave(record); }}+ /* Routed through the same save() as the Save button. Clearing `dirty`+ up front showed "All changes saved" even when the write then failed,+ and swallowed the reason; save() clears only on success and surfaces+ the failure in the toast. */+ onRecord={(record) => { setConfig(record.config); void save(record); }}/></footer>{saveError && <div className="toast" role="alert"><strong>Couldn’t save project</strong><span>{saveError}</span><button onClick={() => setSaveError(null)}>Dismiss</button></div>}</div>;diff --git a/src/components/PromptComposer.tsx b/src/components/PromptComposer.tsxindex 329ddac..ae2609c 100644--- a/src/components/PromptComposer.tsx+++ b/src/components/PromptComposer.tsx@@ -53,6 +53,9 @@ export function PromptComposer({ busy, onCreate }: PromptComposerProps) {const promptInput = useRef<HTMLTextAreaElement>(null);const referencesAvailable = isTauri();+ /* The box holds words the user typed, not an untouched example, so a chip+ click would throw them away. */+ const replacesUserText = prompt.trim().length > 0 && !ideas.some((idea) => idea.prompt === prompt);/* The description box is the first thing you use, so start in it — saving aclick on the headline flow. Runs once, and only while focus is still on the@@ -169,9 +172,15 @@ export function PromptComposer({ busy, onCreate }: PromptComposerProps) {</div></div>+ {/* Clicking a chip overwrites the box. That is the right idiom while the+ box is empty or still holds an example, but silently discarding words+ the user typed is not — a controlled textarea gives no usable undo+ after a programmatic set. Rather than disable the chips (which would+ block the common "try another example" flow), say plainly what the+ click will do. */}<div className="idea-row">- <span className="idea-row__label">Not sure where to start?</span>- {ideas.map((idea) => <button key={idea.label} onClick={() => setPrompt(idea.prompt)}>{idea.label}</button>)}+ <span className="idea-row__label">{replacesUserText ? "Replace what you’ve written with an example" : "Not sure where to start?"}</span>+ {ideas.map((idea) => <button key={idea.label} onClick={() => setPrompt(idea.prompt)} title={replacesUserText ? `Replace your description with the “${idea.label}” example` : `Use the “${idea.label}” example`}>{idea.label}</button>)}</div></section>);diff --git a/src/components/workspace/GeneratorView.tsx b/src/components/workspace/GeneratorView.tsxindex 9bc85bf..dd47d58 100644--- a/src/components/workspace/GeneratorView.tsx+++ b/src/components/workspace/GeneratorView.tsx@@ -2,7 +2,7 @@ import { listen } from "@tauri-apps/api/event";import { AlertCircle, Ban, Check, ChevronRight, Clock3, Film, Info, LoaderCircle, Play, RefreshCw, Sparkles, Square, WandSparkles, X } from "lucide-react";import { useEffect, useMemo, useRef, useState } from "react";import { isTauri } from "../../lib/persistence";-import { compileMiniMaxH3Prompt, createDraftGenerationJob, isReferenceUsable, isVisualReference, projectFilePath, usableImageReferences, type GenerationJob, type ProjectAsset, type ProjectConfig, type ProjectReference, type TimelineClip, type TimelineTrack } from "../../lib/project";+import { compileMiniMaxH3Prompt, createDraftGenerationJob, isReferenceDescribed, isReferenceUsable, isVisualReference, projectFilePath, usableImageReferences, type GenerationJob, type ProjectAsset, type ProjectConfig, type ProjectReference, type TimelineClip, type TimelineTrack } from "../../lib/project";import { cancelVidfabGeneration, enqueueVidfabGeneration, resolveVidfabPlan, type VidfabGenerationRequest, type VidfabStatus } from "../../lib/runtime";interface GeneratorViewProps {@@ -275,7 +275,12 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on<b>{ref.name}</b>{skipped? <p className="job-refs__reason">{skipped}</p>- : ref.intendedUse.length > 0 && <small>Your tags: {ref.intendedUse.join(", ")}</small>}+ : !isReferenceDescribed(ref)+ // Used, but incomplete: the picture goes to the engine while+ // nothing tells it what to keep. Silence here let a+ // boilerplate-filled card look finished.+ ? <p className="job-refs__reason">Not described yet — the picture is sent, but nothing tells the engine what to keep.</p>+ : ref.intendedUse.length > 0 && <small>Your tags: {ref.intendedUse.join(", ")}</small>}</div>;})}{promptRefs.length === 0@@ -364,9 +369,11 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on: "Nothing renders on this computer yet, so your shot is saved as a draft you can run later."}{/* Images are sent as real assets (referencePaths) AND cited as<Picture N>; text definitions reach the engine only as prose- inside <Subject N>. Say exactly that — no more. */}+ inside <Subject N>. Say exactly that — no more, and only about the+ references actually in hand: the same referenceRouting the shot+ panel uses, so the two places cannot drift apart. */}{usableReferences.length > 0- ? ` It will use ${usableReferences.length === 1 ? "your reference" : `the first ${Math.min(2, usableReferences.length)} of your ${usableReferences.length} references`}: images are sent to the video engine, and text definitions are written into the prompt.`+ ? ` It will use ${usableReferences.length === 1 ? "your reference" : `the first ${Math.min(2, usableReferences.length)} of your ${usableReferences.length} references`}. ${referenceRouting(usableReferences.slice(0, 2), "the prompt")}`: ""}</p></section>@@ -408,16 +415,16 @@ function QueueGroup({ title, jobs, selectedId, onSelect }: { title: string; jobs/* Only claim the route the bound references actually take. Saying "images aresent … text definitions are written into the prompt" for a shot that has onlyone of the two describes something that isn't happening. */-const referenceRouting = (references: ProjectReference[]): string => {+const referenceRouting = (references: ProjectReference[], prompt = "this shot’s prompt"): string => {const hasImage = references.some((reference) => reference.kind === "image");const hasText = references.some((reference) => reference.kind !== "image");- if (hasImage && hasText) return "Images are sent to the video engine as reference assets; text definitions are written into this shot’s prompt.";+ if (hasImage && hasText) return `Images are sent to the video engine as reference assets; text definitions are written into ${prompt}.`;if (hasImage) return references.length === 1? "The image is sent to the video engine as a reference asset.": "The images are sent to the video engine as reference assets.";return references.length === 1- ? "The text definition is written into this shot’s prompt."- : "The text definitions are written into this shot’s prompt.";+ ? `The text definition is written into ${prompt}.`+ : `The text definitions are written into ${prompt}.`;};/* Why a reference that is bound to this shot never reaches its prompt, or nulldiff --git a/src/components/workspace/ReferencesView.tsx b/src/components/workspace/ReferencesView.tsxindex 2de0868..9cedd53 100644--- a/src/components/workspace/ReferencesView.tsx+++ b/src/components/workspace/ReferencesView.tsx@@ -1,7 +1,7 @@import { BookOpen, Check, FileText, Image, Link2, Plus, Sparkles, Trash2, Upload, Users } from "lucide-react";import { invoke } from "@tauri-apps/api/core";import { useMemo, useState } from "react";-import { isReferenceUsable, type ProjectConfig, type ProjectReference } from "../../lib/project";+import { isReferenceDescribed, type ProjectConfig, type ProjectReference } from "../../lib/project";import { isTauri } from "../../lib/persistence";type ReferenceUse = ProjectReference["intendedUse"][number];@@ -45,7 +45,12 @@ export function ReferencesView({ config, folderPath, onChange }: { config: Projeconst imported = await invoke<{ name: string; relativePath: string } | null>("choose_reference_image", { folderPath });if (!imported) return;const id = `ref-${Date.now()}`;- const reference: ProjectReference = { id, kind: "image", name: imported.name, description: "Visual reference copied into this portable project.", relativePath: imported.relativePath, intendedUse: ["style"], createdAt: new Date().toISOString() };+ // Empty on purpose, exactly like addTextReference. This field is compiled+ // into the prompt as the user's own account of the picture, so a filing+ // note here ("Visual reference copied into this portable project.") was+ // shipped to the model as if they had written it. The card says the+ // definition is missing instead of faking one.+ const reference: ProjectReference = { id, kind: "image", name: imported.name, description: "", relativePath: imported.relativePath, intendedUse: ["style"], createdAt: new Date().toISOString() };onChange({ ...config, references: [reference, ...config.references] });setSelectedId(id);} catch (reason) {@@ -78,7 +83,11 @@ export function ReferencesView({ config, folderPath, onChange }: { config: Proje<div className="reference-grid">{config.references.map((ref) => <button key={ref.id} className={selectedId === ref.id ? "selected" : ""} onClick={() => setSelectedId(ref.id)}>{ref.kind === "image" ? <span className="reference-art"><Image size={26} /><em>Image file</em></span> : <span className="reference-copy-art"><FileText size={26} /><em>Text definition</em></span>}- <span className="reference-card__body"><span><b>{ref.name}</b><small>{ref.kind === "text" ? "Text definition" : ref.relativePath}</small></span>{isReferenceUsable(ref) ? <p>{ref.description}</p> : <p className="reference-card__incomplete">Not described yet — it won’t be used until you add a definition.</p>}<span className="use-tags">{ref.intendedUse.map((use) => <i key={use}>{use}</i>)}</span></span>+ <span className="reference-card__body"><span><b>{ref.name}</b><small>{ref.kind === "text" ? "Text definition" : ref.relativePath}</small></span>{isReferenceDescribed(ref)+ ? <p>{ref.description}</p>+ : <p className="reference-card__incomplete">{ref.kind === "image"+ ? "Not described yet — the picture is sent, but nothing tells the engine what to keep."+ : "Not described yet — it won’t be used until you add a definition."}</p>}<span className="use-tags">{ref.intendedUse.map((use) => <i key={use}>{use}</i>)}</span></span></button>)}<button className="reference-add-card" onClick={() => void addImage()}><span><Plus size={22} /></span><b>Add a reference</b><small>Import an image or write a definition</small></button></div>diff --git a/src/lib/project.test.ts b/src/lib/project.test.tsindex 0d24415..7532335 100644--- a/src/lib/project.test.ts+++ b/src/lib/project.test.ts@@ -109,10 +109,13 @@ describe("project schema", () => {// §2.2: an image defining a character/scene/style is cited INSIDE its// <Subject N> line and never becomes a standalone <Picture N> entry.- expect(compiled).toContain("<Subject 1> is Harbor facade, shown in <Picture 1>.");+ expect(compiled).toContain("<Subject 1> is the content shown in <Picture 1>. Pale stone fins.");expect(compiled).not.toMatch(/^<Picture \d+> is /m);// A text reference has no asset, so it cites no picture.- expect(compiled).toContain("<Subject 2> is Mara.");+ expect(compiled).toContain("<Subject 2>: Calm architect in charcoal wool.");+ // The library label is never asserted as the subject's identity.+ expect(compiled).not.toContain("Harbor facade");+ expect(compiled).not.toContain("Mara");// §3: task-type prefix; no <Audio N> because no audio asset exists (§2.4).expect(compiled).toContain("summary:\n[reference generation] ");@@ -135,8 +138,10 @@ describe("project schema", () => {const first = img("a", "Alpha", "references/a.jpg");const second = img("b", "Beta", "references/b.jpg");const compiled = compileMiniMaxH3Prompt("A shot", [first, second]);- expect(compiled).toContain("<Subject 1> is Alpha, shown in <Picture 1>.");- expect(compiled).toContain("<Subject 2> is Beta, shown in <Picture 2>.");+ expect(compiled).toContain("<Subject 1> is the content shown in <Picture 1>.");+ expect(compiled).toContain("<Subject 2> is the content shown in <Picture 2>.");+ expect(compiled).not.toContain("Alpha");+ expect(compiled).not.toContain("Beta");expect(usableImageReferences([first, second]).map((r) => r.relativePath)).toEqual(["references/a.jpg", "references/b.jpg",]);@@ -214,7 +219,7 @@ describe("project schema", () => {it("still compiles a reference that carries a visual tag alongside audio", () => {const narrator = textReference({ id: "ref-narrator", name: "Narrator", description: "On-camera, warm low voice.", intendedUse: ["character", "audio"] });const compiled = compileMiniMaxH3Prompt("A quiet lighthouse at dawn", [narrator]);- expect(compiled).toContain("<Subject 1> is Narrator.");+ expect(compiled).toContain("<Subject 1>: On-camera, warm low voice.");expect(compiled).toContain("<Subject 1> (appears in [Shot 1]): fully_preserved - ");});@@ -228,7 +233,7 @@ describe("project schema", () => {expect(usableImageReferences(references).map((reference) => reference.id)).toEqual(["img-visual"]);const compiled = compileMiniMaxH3Prompt("A shot", references);- expect(compiled).toContain("<Subject 1> is Harbor facade, shown in <Picture 1>.");+ expect(compiled).toContain("<Subject 1> is the content shown in <Picture 1>.");expect(compiled).not.toContain("<Picture 2>");expect(compiled).not.toContain("<Subject 2>");expect(compiled).not.toContain("Waveform note");diff --git a/src/lib/project.ts b/src/lib/project.tsindex 5dbf9e0..47bcdd9 100644--- a/src/lib/project.ts+++ b/src/lib/project.ts@@ -197,12 +197,32 @@ export function projectFilePath(folderPath: string, relativePath: string): strinreturn `${root}${separator}${relativePath.split(/[\\/]/).join(separator)}`;}+/** The words the USER wrote about a reference, or "" — never a library label+ * and never anything this app authored. Both import paths used to seed+ * `description` with filing boilerplate ("Visual reference copied into this+ * portable project."), which the compiler then handed to the model as the+ * user's own account of the picture. Both now write an empty string, and this+ * is the single place that decides what counts as the user's description. */+export function referenceDefinition(reference: ProjectReference): string {+ return (reference.description.trim() || reference.content?.trim() || "").trim();+}++/** Whether the user has said anything about this reference yet. An IMAGE is+ * still usable without it — the picture itself is real payload — but it is not+ * complete, and the UI has to say so rather than letting an empty definition+ * look finished. */+export function isReferenceDescribed(reference: ProjectReference): boolean {+ return referenceDefinition(reference) !== "";+}+/** A reference the user has actually filled in. Blank ones are a legitimate- * in-progress state, but they must not take a binding slot from a real one. */+ * in-progress state, but they must not take a binding slot from a real one.+ * An image qualifies on its file alone: it can be sent to the engine and cited+ * as <Picture N> with nothing written about it. */export function isReferenceUsable(reference: ProjectReference): boolean {return reference.kind === "image"? Boolean(reference.relativePath)- : Boolean(reference.description.trim() || reference.content?.trim());+ : isReferenceDescribed(reference);}/** Reference guide §2.1: `<Subject N>` is VISIBLE content. A reference tagged@@ -334,11 +354,20 @@ export function compileMiniMaxH3Prompt(creativeBrief: string, references: Projec// No <Audio N> is emitted either: §2.4 defines it as an actual audio asset,// and every reference in this app is text or image. An "audio" intendedUse// is a note about desired sound, not a signal to copy.+ // The identity slot carries ONLY what the user wrote. `name` is a library+ // label, not a description: for an imported image it is the source file's+ // stem, so using it here shipped "<Subject 1> is IMG_4821, shown in+ // <Picture 1>." and a retention line promising to retain "the defined+ // characteristics of IMG_4821". Neither names anything visible, and both+ // present an app-generated string to the model as the user's own words.+ // An image with no definition still belongs in the prompt — the picture is+ // real payload — so it is cited without any claim about what it contains.const definitions = usable.map((reference, index) => {- const detail = (reference.description.trim() || reference.content?.trim() || "").replace(/\s+/g, " ");+ const detail = endSentence(referenceDefinition(reference).replace(/\s+/g, " "));const picture = pictureNumber.get(reference.id);- const source = picture ? `, shown in <Picture ${picture}>` : "";- return `${referenceLabel(reference, index)} is ${reference.name.trim()}${source}.${detail ? ` ${detail}` : ""}`;+ const label = referenceLabel(reference, index);+ if (!picture) return `${label}: ${detail}`;+ return `${label} is the content shown in <Picture ${picture}>.${detail ? ` ${detail}` : ""}`;});const labels = usable.map((reference, index) => referenceLabel(reference, index));@@ -354,8 +383,11 @@ export function compileMiniMaxH3Prompt(creativeBrief: string, references: Projec// §4.1: one line per label using the fixed marker vocabulary. Their defined// role is carried through unchanged, so fully_preserved is the honest marker.// §5.4: never write (Sx) in retention_analysis.+ // No `name` here either: "the defined characteristics of IMG_4821 are+ // retained" names nothing to retain. The label already points at the+ // definition above, which is where the characteristics actually live.const retention = usable.map((reference, index) =>- `${referenceLabel(reference, index)} (appears in [Shot 1]): fully_preserved - the defined characteristics of ${reference.name.trim()} are retained.`);+ `${referenceLabel(reference, index)} (appears in [Shot 1]): fully_preserved - the referenced characteristics are retained.`);// §5.2: in full-reference mode the style opening comes BEFORE [Shot 1], not// after it. §5.3: cite each <Subject N> where it appears in the shot.