Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Put scene controls on the board

Bitti462b5f2198a9
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index c611bc4..15a76e7 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -172,6 +172,10 @@ struct ReusableReference {
#[serde(rename_all = "camelCase")]
struct SceneShot {
id: String,
+ /// Added after scenes shipped. An absent name keeps the numbered Shot N
+ /// label, and is skipped so older project files do not grow a new key.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ name: Option<String>,
#[serde(default)]
start_seconds: f64,
/// The user's own line, tokens and all. May be empty: a shot they have just
@@ -792,6 +796,12 @@ fn validate_and_normalize_config(mut config: ProjectConfig) -> Result<ProjectCon
job.id, shot.id
));
}
+ if shot.name.as_deref().is_some_and(str::is_empty) {
+ return Err(format!(
+ "Shot '{}' in scene '{}' has an empty name.",
+ shot.id, job.id
+ ));
+ }
if !shot.start_seconds.is_finite() || !(0.0..=15.0).contains(&shot.start_seconds) {
return Err(format!(
"Shot '{}' in scene '{}' starts at {} seconds, outside the 0-15 second scene.",
@@ -3692,6 +3702,7 @@ mod tests {
job.reference_ids = Vec::new();
job.shots = Some(vec![SceneShot {
id: "scene-walk-shot-1".into(),
+ name: None,
start_seconds: 0.0,
action: String::new(),
settings: None,
@@ -3707,6 +3718,18 @@ mod tests {
assert_eq!(shots[0].action, "");
}
+ #[test]
+ fn a_shot_name_survives_the_project_round_trip() {
+ let mut config = scene_fixture();
+ config.generation_jobs[0].shots.as_mut().unwrap()[0].name = Some("Doorway reveal".into());
+
+ let normalized = validate_and_normalize_config(config).expect("a named shot is valid");
+ assert_eq!(
+ normalized.generation_jobs[0].shots.as_ref().unwrap()[0].name.as_deref(),
+ Some("Doorway reveal")
+ );
+ }
+
#[test]
fn a_scene_is_bounded_to_fifteen_seconds_on_both_the_length_and_the_cuts() {
// The frontend spells this `z.number().min(0).max(15)` on both fields.
diff --git a/src/components/ProjectWorkspace.test.ts b/src/components/ProjectWorkspace.test.ts
index ae0f375..c897966 100644
--- a/src/components/ProjectWorkspace.test.ts
+++ b/src/components/ProjectWorkspace.test.ts
@@ -186,7 +186,7 @@ describe("project workspace timecode", () => {
// shot the user has no way to tell apart.
expect(screen.getByRole("heading", { name: "First scene" })).not.toBeNull();
expect(screen.queryByRole("heading", { name: "New scene draft" })).toBeNull();
- expect(screen.getAllByText("DRAFT").length).toBe(1);
+ expect(screen.queryByText("DRAFT")).toBeNull();
});
it("leaves the monitor empty rather than explaining the emptiness", () => {
@@ -804,17 +804,10 @@ describe("project workspace timecode", () => {
expect(deleteButton.title).toBe("This clip’s track is locked");
});
- it("inserts only a completed job with a real output into the first video track", () => {
- 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: "completed", stage: "completed", progress: 1, outputRelativePath: "media/generated/first-scene.mp4" }] });
- const onChange = vi.fn();
- const onOpenTimeline = vi.fn();
- render(createElement(GeneratorView, { config, folderPath: "C:\Ceramic Lamp", onChange, onOpenTimeline, selectedJobId: config.generationJobs[0].id }));
- fireEvent.click(screen.getByRole("button", { name: "Insert into Track 1" }));
- const next = onChange.mock.calls[0][0];
- expect(next.assets[0].relativePath).toBe("media/generated/first-scene.mp4");
- expect(next.timeline.tracks.find((track: { id: string }) => track.id === STORY_TRACK_ID).clips).toHaveLength(1);
- expect(onOpenTimeline).toHaveBeenCalledOnce();
+ it("keeps timeline actions out of scene settings", () => {
+ const config = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });
+ render(createElement(GeneratorView, { config, folderPath: "C:\Ceramic Lamp", onChange: () => undefined, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));
+ expect(screen.queryByRole("button", { name: "Insert into Track 1" })).toBeNull();
});
it("counts only the references that actually reach the compiled prompt", () => {
@@ -829,12 +822,11 @@ describe("project workspace timecode", () => {
];
const config = parseProjectConfig({ ...fresh, references, generationJobs: [{ ...fresh.generationJobs[0], referenceIds: ["ref-lamp", "ref-blank", "ref-score"] }] });
render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange: () => undefined, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));
- expect(screen.getByText("1 reference guides this scene")).not.toBeNull();
- expect(screen.queryByText("3 references guide this scene")).toBeNull();
- // Skipped references stay visible, each with its reason.
- expect(screen.getByText("Lead character")).not.toBeNull();
- expect(screen.getByText("Not described yet — not used by this scene")).not.toBeNull();
- expect(screen.getByText(/sound note/)).not.toBeNull();
+ const prompt = document.querySelector(".debug-prompt .compiled-prompt__text")!.textContent!;
+ expect(prompt).toContain("<Subject 1>");
+ expect(prompt).not.toContain("Lead character");
+ expect(prompt).not.toContain("Score idea");
+ expect(screen.queryByRole("checkbox")).toBeNull();
});
it("renames a scene, and never saves it nameless", () => {
@@ -850,7 +842,7 @@ describe("project workspace timecode", () => {
expect(parseProjectConfig(onChange.mock.calls[1][0])).toBeTruthy();
});
- it("links and unlinks a reference to the selected shot", () => {
+ it("keeps reference selection controls out of scene settings", () => {
const fresh = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });
const createdAt = fresh.createdAt;
const references = [
@@ -858,23 +850,12 @@ describe("project workspace timecode", () => {
{ id: "ref-light", kind: "text", name: "Window light", description: "Soft north light, long shadows.", content: "Soft north light, long shadows.", intendedUse: ["style"], createdAt },
];
const config = parseProjectConfig({ ...fresh, references, generationJobs: [{ ...fresh.generationJobs[0], referenceIds: ["ref-lamp"] }] });
- const onChange = vi.fn();
- render(createElement(GeneratorView, { config, folderPath: "C:\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));
-
- // Every reference in the project is offered, bound or not.
- const lamp = screen.getByRole("checkbox", { name: /Lamp silhouette/ }) as HTMLInputElement;
- const light = screen.getByRole("checkbox", { name: /Window light/ }) as HTMLInputElement;
- expect(lamp.checked).toBe(true);
- expect(light.checked).toBe(false);
-
- fireEvent.click(light);
- expect(onChange.mock.calls[0][0].generationJobs[0].referenceIds).toEqual(["ref-lamp", "ref-light"]);
-
- fireEvent.click(lamp);
- expect(onChange.mock.calls[1][0].generationJobs[0].referenceIds).toEqual([]);
+ const { container } = render(createElement(GeneratorView, { config, folderPath: "C:\Ceramic Lamp", onChange: () => undefined, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));
+ expect(screen.queryByRole("checkbox")).toBeNull();
+ expect(container.querySelector(".job-refs")).toBeNull();
});
- it("shows each reference's own picture in the generator, and invents none", async () => {
+ it("keeps reference previews out of scene settings", () => {
/* This list used to render <i class="ref-mini ref-mini--{index}"> against a
hardcoded gradient, and only --1 had a rule of its own — so every
reference except the second wore the SAME fabricated picture, over files
@@ -890,44 +871,27 @@ describe("project workspace timecode", () => {
const config = parseProjectConfig({ ...fresh, references, generationJobs: [{ ...fresh.generationJobs[0], referenceIds: ["ref-photo"] }] });
const { container } = render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange: () => undefined, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));
- const tiles = () => [...container.querySelectorAll(".job-refs .ref-mini")];
- await waitFor(() => expect(tiles()).toHaveLength(2));
- /* The index-keyed class is what made the stand-in look deliberate. */
- expect(container.querySelector("[class*='ref-mini--']")).toBeNull();
-
- /* The image reference goes through the same component References uses, so
- outside the desktop shell it says which state it is in — loading, or the
- file is not where the project says — instead of drawing something. */
- const drawn = tiles().filter((tile) => tile.querySelector("img, .reference-image-fallback"));
- expect(drawn).toHaveLength(1);
- expect(drawn[0].parentElement!.textContent).toContain("Lamp photograph");
-
- /* Both tiles are hidden from the checkbox's own name: the name is the next
- node inside the same <label>, and announcing it twice is what an alt
- text here would cost. */
- expect(tiles().every((tile) => tile.getAttribute("aria-hidden") === "true")).toBe(true);
- expect(screen.getByRole("checkbox", { name: /Lamp photograph/ })).not.toBeNull();
+ expect(container.querySelector(".job-refs")).toBeNull();
+ expect(screen.queryByText("Lamp photograph")).toBeNull();
});
- it("locks a running shot’s references, because the engine already has them", () => {
+ it("locks the retained settings while a scene is running", () => {
const fresh = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });
const references = [{ id: "ref-lamp", kind: "text", name: "Lamp silhouette", description: "Matte cream ceramic.", content: "Matte cream ceramic.", intendedUse: ["product"], createdAt: fresh.createdAt }];
const config = parseProjectConfig({ ...fresh, references, generationJobs: [{ ...fresh.generationJobs[0], status: "generating", stage: "generating", progress: 0.4, referenceIds: ["ref-lamp"] }] });
render(createElement(GeneratorView, { config, folderPath: "C:\Ceramic Lamp", onChange: () => undefined, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));
- expect((screen.getByRole("checkbox", { name: /Lamp silhouette/ }) as HTMLInputElement).disabled).toBe(true);
+ expect((screen.getByRole("combobox", { name: "The look of this scene" }) as HTMLSelectElement).disabled).toBe(true);
+ expect((screen.getByRole("textbox", { name: "The sound of this scene" }) as HTMLTextAreaElement).disabled).toBe(true);
+ expect((screen.getByRole("textbox", { name: "The music of this scene" }) as HTMLTextAreaElement).disabled).toBe(true);
});
- it("tells the user the engine only follows the words when every bound reference is skipped", () => {
+ it("does not show reference guidance in scene settings", () => {
const fresh = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });
const references = [{ id: "ref-blank", kind: "text", name: "Lead character", description: "", content: null, intendedUse: ["character"], createdAt: fresh.createdAt }];
const config = parseProjectConfig({ ...fresh, references, generationJobs: [{ ...fresh.generationJobs[0], referenceIds: ["ref-blank"] }] });
render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange: () => undefined, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));
- expect(screen.queryByText("1 reference guides this scene")).toBeNull();
- expect(screen.getByText("No references used by this scene")).not.toBeNull();
- expect(screen.getByText("The video engine only follows the words in the shots.")).not.toBeNull();
- // The claim that a text definition is written into the prompt must not
- // appear when nothing is written into it.
- expect(screen.queryByText(/text definitions are written into this scene/)).toBeNull();
+ expect(screen.queryByText("No references used by this scene")).toBeNull();
+ expect(screen.queryByText("The video engine only follows the words in the shots.")).toBeNull();
});
it("disables Split while the playhead sits outside the selected clip", () => {
@@ -976,7 +940,7 @@ describe("project workspace timecode", () => {
] });
const onChange = vi.fn();
render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined }));
- fireEvent.click(screen.getByRole("button", { name: "Add a scene" }));
+ fireEvent.click(screen.getByRole("button", { name: "Add Scene" }));
// It would take a binding slot and then be dropped by the compiler, so the
// shot would claim a reference its prompt never mentions.
expect(onChange.mock.calls[0][0].generationJobs[0].referenceIds).toEqual([]);
@@ -1038,6 +1002,18 @@ describe("project workspace timecode", () => {
expect(screenText).toContain("Not described yet — the picture is sent, but nothing tells the engine what to keep.");
});
+ it("lays references out as a scrolling main area beside a full-height inspector", () => {
+ const config = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });
+ const { container } = render(createElement(ReferencesView, { config, folderPath: "C:\\Ceramic Lamp", onChange: () => undefined }));
+ const view = container.querySelector(".references-view")!;
+ expect(Array.from(view.children).slice(0, 2).map((element) => element.className)).toEqual(["references-main", "reference-inspector"]);
+ expect(container.querySelector(".references-heading__actions")!.textContent).toContain("New definition");
+ expect(container.querySelector(".references-heading__actions")!.textContent).toContain("Add image");
+ expect(container.querySelector(".reference-inspector__scroll")).not.toBeNull();
+ expect(container.querySelector(".reference-layout")).toBeNull();
+ expect(container.querySelector(".reference-library__toolbar")).toBeNull();
+ });
+
/* The Generator is a board of shot cards and a panel that edits whichever
one is open. It opens on the SCENE — the thing with a state, a prompt and a
Generate button — so a test that wants a shot's own controls has to choose
@@ -1051,7 +1027,7 @@ describe("project workspace timecode", () => {
/** Opens the scene's own settings, which live on the line that separates its
* row of cards from the next scene's. */
const openScene = (sceneTitle = "First scene") =>
- fireEvent.click(screen.getByRole("button", { name: `Scene settings for ${sceneTitle}` }));
+ fireEvent.click(screen.getByRole("button", { name: `Settings for ${sceneTitle}` }));
/** Adds one setting to one shot: choose the setting, then choose its value.
* Settings are added one at a time now, rather than laid out as a wall of
@@ -1082,7 +1058,7 @@ describe("project workspace timecode", () => {
that it does. */
expect(screen.queryByRole("heading", { name: "Start another scene" })).toBeNull();
expect(container.querySelector(".generation-composer")).toBeNull();
- expect(screen.getByRole("button", { name: "Add a scene" })).not.toBeNull();
+ expect(screen.getByRole("button", { name: "Add Scene" })).not.toBeNull();
unmount();
}
});
@@ -1128,13 +1104,14 @@ describe("project workspace timecode", () => {
openShot(1);
expect(screen.getByRole("textbox", { name: "What happens in shot 1" })).not.toBeNull();
- // One thing at a time: the scene's own controls are not also on screen.
- expect(screen.queryByRole("slider", { name: "Scene length in seconds" })).toBeNull();
+ // The shared scene header stays visible, while the right panel edits only
+ // the shot.
+ expect(screen.getByRole("slider", { name: "First scene length in seconds" })).not.toBeNull();
expect(screen.queryByRole("textbox", { name: "Rename First scene" })).toBeNull();
// And the way back up is named, so a shot is never a dead end.
- fireEvent.click(screen.getByRole("button", { name: "First scene · Scene settings" }));
- expect(screen.getByRole("slider", { name: "Scene length in seconds" })).not.toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "First scene" }));
+ expect(screen.getByRole("slider", { name: "First scene length in seconds" })).not.toBeNull();
openShot(1);
openScene();
@@ -1145,7 +1122,7 @@ describe("project workspace timecode", () => {
const config = lampProject();
const onChange = vi.fn();
const { rerender } = render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));
- fireEvent.click(screen.getByRole("button", { name: "Add a scene" }));
+ fireEvent.click(screen.getByRole("button", { name: "Add Scene" }));
const next = onChange.mock.calls.at(-1)![0];
// It goes to the head of the list and does not disturb the scene already there.
@@ -1165,10 +1142,12 @@ describe("project workspace timecode", () => {
// And it cannot be generated until the user writes a line in it.
rerender(createElement(GeneratorView, { config: parseProjectConfig(next), folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: added.id }));
- expect(screen.getByText("Write what happens in at least one shot before this scene can be generated.")).not.toBeNull();
+ const addedScene = screen.getByRole("region", { name: UNTITLED_SCENE });
+ const generate = within(addedScene).getByRole("button", { name: "Generate" }) as HTMLButtonElement;
+ expect(generate.disabled).toBe(true);
});
- it("splits a scene into three shots on the bar, each with its own line and cut", () => {
+ it("splits a scene into three shots, each with its own line and cut", () => {
const config = lampProject();
const onChange = vi.fn();
const { rerender } = render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));
@@ -1183,12 +1162,12 @@ describe("project workspace timecode", () => {
rerender(createElement(GeneratorView, { config: parseProjectConfig(next), folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));
openScene();
- fireEvent.change(screen.getByRole("slider", { name: "Scene length in seconds" }), { target: { value: "9" } });
+ fireEvent.change(screen.getByRole("slider", { name: "First scene length in seconds" }), { target: { value: "9" } });
next = onChange.mock.calls.at(-1)![0];
expect(next.generationJobs[0].durationSeconds).toBe(9);
rerender(createElement(GeneratorView, { config: parseProjectConfig(next), folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));
- // Each cut is set on the bar, and the second and third lines are written.
+ // Each cut is set on its shot, and the second and third lines are written.
for (const [shotNumber, startSeconds, line] of [[2, 3, "she stops at the doorway"], [3, 6.5, "the door opens"]] as const) {
openShot(shotNumber);
fireEvent.change(screen.getByRole("spinbutton", { name: `Shot ${shotNumber} starts at, in seconds` }), { target: { value: String(startSeconds) } });
@@ -1213,8 +1192,8 @@ describe("project workspace timecode", () => {
const config = lampProject();
const onChange = vi.fn();
const app = render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));
- const length = () => screen.getByRole("slider", { name: "Scene length in seconds" }) as HTMLInputElement;
- // The length belongs to the scene, so it is on the scene's own panel.
+ const length = () => screen.getByRole("slider", { name: "First scene length in seconds" }) as HTMLInputElement;
+ // The length belongs to the scene, so it is on the scene's header.
expect(length().min).toBe("0");
expect(length().max).toBe("15");
// The bound is enforced, not merely advertised: a hand-set value past the
@@ -1225,10 +1204,10 @@ describe("project workspace timecode", () => {
const emptied = onChange.mock.calls.at(-1)![0];
expect(emptied.generationJobs[0].durationSeconds).toBe(0);
expect(parseProjectConfig(emptied)).toBeTruthy();
- // A scene of no length has no frames to render, and the screen says so in
- // words rather than leaving a grey button with no explanation.
+ // A scene of no length has no frames to render; the header keeps the value
+ // editable without adding another description to the settings panel.
app.rerender(createElement(GeneratorView, { config: parseProjectConfig(emptied), folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));
- expect(screen.getByText(/nought seconds long, so there are no frames to render/)).not.toBeNull();
+ expect(length().value).toBe("0");
});
it("adds a setting to one shot and takes it off again, without touching the other shot", () => {
@@ -1296,8 +1275,10 @@ describe("project workspace timecode", () => {
expect(screen.queryByRole("button", { name: "Shot 2 of First scene" })).toBeNull();
openScene();
expect(document.querySelector(".compiled-prompt__text")!.textContent).toContain("macro lens, A quiet product film");
- // Its length is the one it was always generated at, said out loud.
- expect(screen.getByText("6.0 seconds, one shot")).not.toBeNull();
+ // Its length remains on the header slider; the old length/shot-count line
+ // under the scene name is gone.
+ expect((screen.getByRole("slider", { name: "First scene length in seconds" }) as HTMLInputElement).value).toBe("6");
+ expect(screen.queryByText("6.0 seconds, one shot")).toBeNull();
// The first edit moves the tags onto the shot, and clears the legacy copy
// so the two can never disagree.
@@ -1313,7 +1294,7 @@ describe("project workspace timecode", () => {
const fresh = lampProject();
const config = parseProjectConfig({ ...fresh, generationJobs: [{ ...fresh.generationJobs[0], status: "generating", stage: "generating", progress: 0.4 }] });
render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange: () => undefined, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));
- expect((screen.getByRole("slider", { name: "Scene length in seconds" }) as HTMLInputElement).disabled).toBe(true);
+ expect((screen.getByRole("slider", { name: "First scene length in seconds" }) as HTMLInputElement).disabled).toBe(true);
openShot(1);
expect((screen.getByRole("textbox", { name: "What happens in shot 1" }) as HTMLTextAreaElement).disabled).toBe(true);
expect((screen.getByRole("combobox", { name: "Add a setting to shot 1" }) as HTMLSelectElement).disabled).toBe(true);
@@ -1461,7 +1442,7 @@ describe("project workspace timecode", () => {
show();
};
- set("slider", "Scene length in seconds", "12");
+ set("slider", "First scene length in seconds", "12");
press("Add a shot to First scene");
press("Add a shot to First scene");
@@ -1567,7 +1548,8 @@ describe("project workspace timecode", () => {
// The card's picture is the placeholder that says why there is no picture.
expect(screen.getByRole("img", { name: "Shot 1 — Cancelled" })).not.toBeNull();
expect(screen.getByText("CANCELLED")).not.toBeNull();
- expect(screen.getByText("Generation stopped")).not.toBeNull();
+ expect(screen.getAllByText("Cancelled").length).toBeGreaterThan(0);
+ expect(document.querySelector(".job-progress-block")).toBeNull();
expect(screen.queryByText("Waiting in queue")).toBeNull();
});
});
diff --git a/src/components/workspace/GeneratorView.test.tsx b/src/components/workspace/GeneratorView.test.tsx
new file mode 100644
index 0000000..8782260
--- /dev/null
+++ b/src/components/workspace/GeneratorView.test.tsx
@@ -0,0 +1,147 @@
+// @vitest-environment jsdom
+
+import "@testing-library/jest-dom/vitest";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { useState } from "react";
+import { afterEach, describe, expect, it } from "vitest";
+import { createDraftGenerationJob, createProjectConfig, parseProjectConfig, sceneShots, type ProjectConfig } from "../../lib/project";
+import type { VidfabStatus } from "../../lib/runtime";
+import { GeneratorView } from "./GeneratorView";
+
+afterEach(cleanup);
+
+const readyRuntime: VidfabStatus = {
+ state: "ready",
+ dllPath: "test",
+ version: "test",
+ detail: "Ready",
+ models: [],
+};
+
+const project = (): ProjectConfig => {
+ const base = createProjectConfig({
+ name: "Drag test",
+ prompt: "Opening action",
+ aspectRatio: "16:9",
+ resolution: "1080p",
+ targetDurationSeconds: 20,
+ });
+ const now = "2026-08-22T00:00:00.000Z";
+ const first = createDraftGenerationJob("Opening action", {
+ id: "scene-first",
+ title: "First scene",
+ now,
+ durationSeconds: 6,
+ shots: [
+ { id: "shot-first-a", startSeconds: 0, action: "Opening action" },
+ { id: "shot-first-b", startSeconds: 3, action: "Second action" },
+ ],
+ });
+ const second = createDraftGenerationJob("Another scene", {
+ id: "scene-second",
+ title: "Second scene",
+ now,
+ durationSeconds: 8,
+ shots: [{ id: "shot-second-a", startSeconds: 0, action: "Another scene" }],
+ });
+ return { ...base, generationJobs: [first, second] };
+};
+
+const transfer = (): DataTransfer => {
+ const data = new Map<string, string>();
+ const value = {
+ effectAllowed: "none",
+ get types() { return [...data.keys()]; },
+ setData(type: string, content: string) { data.set(type, content); },
+ getData(type: string) { return data.get(type) ?? ""; },
+ };
+ return value as unknown as DataTransfer;
+};
+
+function setup() {
+ let latest = project();
+ function Harness() {
+ const [config, setConfig] = useState(latest);
+ latest = config;
+ return <GeneratorView
+ config={config}
+ folderPath="C:\\project"
+ runtime={readyRuntime}
+ onChange={setConfig}
+ onOpenTimeline={() => undefined}
+ />;
+ }
+ render(<Harness />);
+ return { latest: () => latest };
+}
+
+describe("Generator scene controls", () => {
+ it("reorders shots inside a scene while keeping its cut slots", () => {
+ const state = setup();
+ const shotTransfer = transfer();
+ fireEvent.dragStart(screen.getByRole("button", { name: "Shot 1 of First scene" }), { dataTransfer: shotTransfer });
+ fireEvent.drop(screen.getByRole("button", { name: "Add a shot to First scene" }).parentElement!, { dataTransfer: shotTransfer });
+
+ const first = state.latest().generationJobs.find((job) => job.id === "scene-first")!;
+ expect(sceneShots(first).map((shot) => shot.id)).toEqual(["shot-first-b", "shot-first-a"]);
+ expect(sceneShots(first).map((shot) => shot.startSeconds)).toEqual([0, 3]);
+ });
+
+ it("reorders scenes and moves shots between scenes by drag and drop", () => {
+ const state = setup();
+
+ const sceneTransfer = transfer();
+ fireEvent.dragStart(screen.getByRole("button", { name: "Drag Second scene to reorder scenes" }), { dataTransfer: sceneTransfer });
+ fireEvent.drop(screen.getByRole("region", { name: "First scene" }), { dataTransfer: sceneTransfer });
+ expect(state.latest().generationJobs.map((job) => job.id)).toEqual(["scene-second", "scene-first"]);
+
+ const shotTransfer = transfer();
+ fireEvent.dragStart(screen.getByRole("button", { name: "Shot 2 of First scene" }), { dataTransfer: shotTransfer });
+ fireEvent.drop(screen.getByRole("button", { name: "Shot 1 of Second scene" }).parentElement!, { dataTransfer: shotTransfer });
+
+ const source = state.latest().generationJobs.find((job) => job.id === "scene-first")!;
+ const target = state.latest().generationJobs.find((job) => job.id === "scene-second")!;
+ expect(sceneShots(source).map((shot) => shot.id)).toEqual(["shot-first-a"]);
+ expect(sceneShots(target).map((shot) => shot.id)).toEqual(["shot-first-b", "shot-second-a"]);
+ expect(sceneShots(target).map((shot) => shot.startSeconds)).toEqual([0, 4]);
+ });
+
+ it("puts scene length and confirmed removal in the header without a Draft indicator", () => {
+ const state = setup();
+ expect(screen.queryByText("DRAFT")).not.toBeInTheDocument();
+ expect(screen.queryByText(/^Draft/)).not.toBeInTheDocument();
+
+ fireEvent.change(screen.getByRole("slider", { name: "First scene length in seconds" }), { target: { value: "10" } });
+ expect(state.latest().generationJobs[0].durationSeconds).toBe(10);
+
+ fireEvent.click(screen.getByRole("button", { name: "Remove scene First scene" }));
+ expect(screen.getByRole("alertdialog", { name: "Remove scene?" })).toBeInTheDocument();
+ expect(state.latest().generationJobs.map((job) => job.id)).toEqual(["scene-first", "scene-second"]);
+ fireEvent.click(screen.getByRole("button", { name: "Remove scene" }));
+ expect(state.latest().generationJobs.map((job) => job.id)).toEqual(["scene-second"]);
+ });
+
+ it("renames a shot and confirms before removing it", () => {
+ const state = setup();
+ fireEvent.click(screen.getByRole("button", { name: "Shot 2 of First scene" }));
+ fireEvent.change(screen.getByRole("textbox", { name: "Rename shot 2" }), { target: { value: "Doorway reveal" } });
+ expect(sceneShots(state.latest().generationJobs[0])[1].name).toBe("Doorway reveal");
+ expect(parseProjectConfig(state.latest()).generationJobs[0].shots?.[1].name).toBe("Doorway reveal");
+ expect(screen.getByRole("button", { name: "Doorway reveal of First scene" })).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "Remove shot 2" }));
+ expect(screen.getByRole("alertdialog", { name: "Remove shot?" })).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
+ expect(sceneShots(state.latest().generationJobs[0])).toHaveLength(2);
+
+ fireEvent.click(screen.getByRole("button", { name: "Remove shot 2" }));
+ fireEvent.click(screen.getByRole("button", { name: "Remove shot" }));
+ expect(sceneShots(state.latest().generationJobs[0])).toHaveLength(1);
+ });
+
+ it("queues every valid draft from Generate All", async () => {
+ const state = setup();
+ fireEvent.click(screen.getByRole("button", { name: "Generate All" }));
+ await waitFor(() => expect(state.latest().generationJobs.map((job) => job.status)).toEqual(["queued", "queued"]));
+ });
+});
diff --git a/src/components/workspace/GeneratorView.tsx b/src/components/workspace/GeneratorView.tsx
index 5385275..ccd57f7 100644
--- a/src/components/workspace/GeneratorView.tsx
+++ b/src/components/workspace/GeneratorView.tsx
@@ -1,12 +1,10 @@
-import { Ban, Check, FileText, Image as ImageIcon, LoaderCircle, Music2, Play, Plus, RefreshCw, Sparkles, Square, Video, WandSparkles, X } from "lucide-react";
+import { Plus, Sparkles, WandSparkles } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
-import { resolutionLabel } from "../../lib/export";
-import { actionReferenceIds, compileGenerationJobPrompt, compileGenerationJobSegments, createDraftGenerationJob, danglingReferenceTokens, sceneDurationSeconds, sceneShots, SCENE_MAX_SECONDS, SCENE_MIN_SECONDS, STORY_TRACK_ID, isReferenceDescribed, isReferenceUsable, isVisualReference, projectItemPath, usableImageReferences, type GenerationJob, type ProjectAsset, type ProjectConfig, type ProjectReference, type PromptSegment, type SceneShot, type TimelineClip, type TimelineTrack } from "../../lib/project";
+import { actionReferenceIds, compileGenerationJobPrompt, compileGenerationJobSegments, createDraftGenerationJob, danglingReferenceTokens, sceneDurationSeconds, sceneShots, SCENE_MAX_SECONDS, SCENE_MIN_SECONDS, projectItemPath, usableImageReferences, type GenerationJob, type ProjectConfig, type ProjectReference, type PromptSegment, type SceneShot } from "../../lib/project";
import { cancelVidfabGeneration, enqueueVidfabGeneration, resolveVidfabPlan, type VidfabGenerationRequest, type VidfabStatus } from "../../lib/runtime";
-import { ReferenceImage } from "./ReferenceImage";
import { SceneBoard, type GeneratorSelection } from "./SceneBoard";
import { SceneInspector, ShotInspector, STEP_SECONDS, writeShots } from "./SceneEditor";
-import { progressTitle, stageCopy, statusIcon, STATUS_WORD } from "./sceneStatus";
+import { statusIcon } from "./sceneStatus";
interface GeneratorViewProps {
config: ProjectConfig;
@@ -17,6 +15,10 @@ interface GeneratorViewProps {
selectedJobId?: string;
}
+type RemovalTarget =
+ | { kind: "scene"; job: GenerationJob }
+ | { kind: "shot"; job: GenerationJob; shotId: string; shotName: string };
+
/* The Generator is a BOARD and a PANEL.
*
* The board is every scene in the project, each one a row of shot cards reading
@@ -28,7 +30,7 @@ interface GeneratorViewProps {
* The panel is whatever is open — one shot, or the scene itself. Nothing is
* edited on the board, and nothing is duplicated in the panel: there is exactly
* one place to change any given thing. */
-export function GeneratorView({ config, folderPath, runtime = null, onChange, onOpenTimeline, selectedJobId }: GeneratorViewProps) {
+export function GeneratorView({ config, folderPath, runtime = null, onChange, selectedJobId }: GeneratorViewProps) {
const jobs = config.generationJobs;
const configRef = useRef(config);
configRef.current = config;
@@ -37,7 +39,8 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on
Opening the Generator, or arriving from a clip in the timeline, opens the
SCENE — the thing that has a state, a prompt and a Generate button. */
const [selection, setSelection] = useState<GeneratorSelection>(() => ({ jobId: selectedJobId ?? jobs.find((job) => job.status === "generating")?.id ?? jobs[0]?.id ?? "", shotId: null }));
- const [planNotes, setPlanNotes] = useState<Record<string, string>>({});
+ const [, setPlanNotes] = useState<Record<string, string>>({});
+ const [removalTarget, setRemovalTarget] = useState<RemovalTarget | null>(null);
useEffect(() => { if (selectedJobId) setSelection({ jobId: selectedJobId, shotId: null }); }, [selectedJobId]);
@@ -55,15 +58,7 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on
// run while claiming otherwise.
const refsLocked = selected?.status === "generating" || selected?.status === "queued";
const boundRefs = useMemo(() => config.references.filter((ref) => selected?.referenceIds.includes(ref.id)), [config.references, selected]);
- // Bound is not the same as used. The compiler drops a reference that isn't
- // described yet, and isVisualReference drops an audio-only one, so a count
- // taken from the IDs alone told the user a definition was steering the scene
- // when the compiled prompt never mentioned it.
- const promptRefs = useMemo(() => boundRefs.filter((ref) => isReferenceUsable(ref) && isVisualReference(ref)), [boundRefs]);
const runtimeReady = runtime?.state === "ready";
- /* Why this scene cannot be sent, or null. Every one of these is a state the
- user can see and fix; the button says the reason rather than sitting grey. */
- const blocked = selected ? sendBlocker(selected, config.references) : null;
const updateJob = (id: string, updates: Partial<GenerationJob>) => {
const current = configRef.current;
@@ -75,8 +70,8 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on
in `reference_paths` — a citation the engine was never sent the reference
for would point at nothing. Nothing is ever auto-unbound: taking a name out
of one line is not a decision to stop steering the scene with it, and the
- checkbox list in the scene panel is where that decision is made. */
- const updateScene = (job: GenerationJob, updates: Partial<GenerationJob>) => {
+ reference library is where those references themselves are managed. */
+ const mergeSceneUpdates = (job: GenerationJob, updates: Partial<GenerationJob>): GenerationJob => {
const next: Partial<GenerationJob> = { ...updates, updatedAt: new Date().toISOString() };
if (updates.shots) {
const referenceIds = [...job.referenceIds];
@@ -87,9 +82,12 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on
}
next.referenceIds = referenceIds;
}
- updateJob(job.id, next);
+ return { ...job, ...next };
};
+ const updateScene = (job: GenerationJob, updates: Partial<GenerationJob>) =>
+ updateJob(job.id, mergeSceneUpdates(job, updates));
+
/* --- The shots of a scene ------------------------------------------------
Every one of these goes through writeShots, so the mirrored `prompt` and
`creativeBrief` can never fall behind the lines they mirror. */
@@ -128,6 +126,68 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on
setShots(job, sceneShots(job).map((shot) => ({ ...shot, startSeconds: Math.min(shot.startSeconds, next) })), { durationSeconds: next });
};
+ const moveScene = (jobId: string, beforeJobId: string | null) => {
+ const current = configRef.current;
+ const moving = current.generationJobs.find((job) => job.id === jobId);
+ if (!moving || beforeJobId === jobId) return;
+ const without = current.generationJobs.filter((job) => job.id !== jobId);
+ const index = beforeJobId === null ? without.length : without.findIndex((job) => job.id === beforeJobId);
+ if (index < 0) return;
+ const generationJobs = [...without.slice(0, index), moving, ...without.slice(index)];
+ onChange({ ...current, generationJobs });
+ };
+
+ /** Reordering keeps the existing cut slots. A cross-scene move inserts a new
+ * cut between its neighbours (or at the end), so array order and playback
+ * order remain the same even though scene shots are normalized by time. */
+ const moveShot = (sourceJobId: string, shotId: string, targetJobId: string, beforeShotId: string | null) => {
+ const current = configRef.current;
+ const source = current.generationJobs.find((job) => job.id === sourceJobId);
+ const target = current.generationJobs.find((job) => job.id === targetJobId);
+ if (!source || !target) return;
+ if ([source.status, target.status].some((status) => status === "queued" || status === "generating")) return;
+
+ const sourceShots = sceneShots(source);
+ const moving = sourceShots.find((shot) => shot.id === shotId);
+ if (!moving) return;
+
+ if (source.id === target.id) {
+ const without = sourceShots.filter((shot) => shot.id !== shotId);
+ const index = beforeShotId === null ? without.length : without.findIndex((shot) => shot.id === beforeShotId);
+ if (index < 0) return;
+ const ordered = [...without.slice(0, index), moving, ...without.slice(index)];
+ const starts = sourceShots.map((shot) => shot.startSeconds);
+ const retimed = ordered.map((shot, at) => ({ ...shot, startSeconds: starts[at] }));
+ const updated = mergeSceneUpdates(source, writeShots(source, retimed));
+ onChange({ ...current, generationJobs: current.generationJobs.map((job) => job.id === source.id ? updated : job) });
+ setSelection({ jobId: source.id, shotId });
+ return;
+ }
+
+ // A scene with no shots cannot be represented or edited.
+ if (sourceShots.length <= 1) return;
+ const targetShots = sceneShots(target);
+ const insertAt = beforeShotId === null ? targetShots.length : targetShots.findIndex((shot) => shot.id === beforeShotId);
+ if (insertAt < 0) return;
+ const inserted = { ...moving, startSeconds: 0 };
+ const orderedTargetShots = [...targetShots.slice(0, insertAt), inserted, ...targetShots.slice(insertAt)];
+ const targetDuration = sceneDurationSeconds(target);
+ // A destination gains a cut, so divide its available time again. This
+ // avoids a zero-length shot when one is dropped at either edge.
+ const nextTargetShots = orderedTargetShots.map((shot, at) => ({
+ ...shot,
+ startSeconds: at === 0 ? 0 : Math.min(targetDuration, Math.round((targetDuration * at / orderedTargetShots.length) / STEP_SECONDS) * STEP_SECONDS),
+ }));
+ const nextSourceShots = sourceShots.filter((shot) => shot.id !== shotId);
+ const updatedSource = mergeSceneUpdates(source, writeShots(source, nextSourceShots));
+ const updatedTarget = mergeSceneUpdates(target, writeShots(target, nextTargetShots));
+ onChange({
+ ...current,
+ generationJobs: current.generationJobs.map((job) => job.id === source.id ? updatedSource : job.id === target.id ? updatedTarget : job),
+ });
+ setSelection({ jobId: target.id, shotId });
+ };
+
const requestFor = (job: GenerationJob): VidfabGenerationRequest => {
// Only the references actually bound to this scene, in list order. The same
// ordered list drives the <Subject N> / <Picture N> numbering inside the
@@ -174,13 +234,26 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on
window hands the request to Claude Code or Codex, which returns the whole
project with the new scene in it. Nothing is auto-bound either way — which
references steer a scene is decided by writing them into a line or by the
- checkbox list beside it. */
+ references already named by its shots. */
const newScene = () => {
const job = createDraftGenerationJob("");
onChange({ ...config, generationJobs: [job, ...jobs] });
setSelection({ jobId: job.id, shotId: null });
};
+ const removeScene = (job: GenerationJob) => {
+ const current = configRef.current;
+ const at = current.generationJobs.findIndex((item) => item.id === job.id);
+ if (at < 0) return;
+ if (job.status === "generating" || job.status === "queued") void cancelVidfabGeneration(job.id);
+ const generationJobs = current.generationJobs.filter((item) => item.id !== job.id);
+ onChange({ ...current, generationJobs });
+ if (selection.jobId === job.id) {
+ const fallback = generationJobs[Math.min(at, generationJobs.length - 1)];
+ setSelection({ jobId: fallback?.id ?? "", shotId: null });
+ }
+ };
+
const startDraft = async (job: GenerationJob) => {
if (!runtimeReady) return;
updateJob(job.id, { status: "queued", stage: "queued", error: null, updatedAt: new Date().toISOString() });
@@ -195,45 +268,47 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on
setPlanNotes((current) => ({ ...current, [job.id]: `Planned as ${plan.alignedFrames} frames at ${plan.canvasWidth}×${plan.canvasHeight}. ${plan.boundary}` }));
await enqueueVidfabGeneration(request, configRef.current);
} catch (reason) {
- updateJob(job.id, { error: reason instanceof Error ? reason.message : String(reason) });
+ updateJob(job.id, { status: "failed", stage: "failed", error: reason instanceof Error ? reason.message : String(reason) });
}
};
- const insertIntoStory = (job: GenerationJob) => {
- if (!job.outputRelativePath) return;
- const now = new Date().toISOString();
- const lengthMs = Math.round(sceneDurationSeconds(job) * 1000);
- const existingAsset = config.assets.find((asset) => asset.relativePath === job.outputRelativePath);
- const asset: ProjectAsset = existingAsset ?? { id: `asset-${crypto.randomUUID()}`, kind: "generated", name: job.title, relativePath: job.outputRelativePath, mimeType: "video/mp4", durationMs: lengthMs, createdAt: now };
- /* By id first: tracks can be renamed, and matching on the name alone made
- a renamed first video track invisible here — the next insert built a
- second one beside it. The name check is the fallback for projects saved
- before the id was fixed, when the track was still called "Story". */
- const existingStory = config.timeline.tracks.find((track) => track.id === STORY_TRACK_ID)
- ?? config.timeline.tracks.find((track) => track.kind === "video" && track.name === "Story");
- const story: TimelineTrack = existingStory ?? { id: STORY_TRACK_ID, kind: "video", name: "Track 1", locked: false, muted: false, clips: [] };
- if (story.locked) return;
- const startMs = story.clips.reduce((end, clip) => Math.max(end, clip.startMs + clip.durationMs), 0);
- const clip: TimelineClip = { id: `clip-${crypto.randomUUID()}`, assetId: asset.id, trackId: story.id, startMs, durationMs: asset.durationMs || lengthMs || 1, sourceStartMs: 0, label: job.title, color: "#4f6ba8", status: "generated" };
- const tracks = existingStory ? config.timeline.tracks.map((track) => track.id === story.id ? { ...track, clips: [...track.clips, clip] } : track) : [{ ...story, clips: [clip] }, ...config.timeline.tracks];
- onChange({ ...config, assets: existingAsset ? config.assets : [...config.assets, asset], timeline: { tracks }, generationJobs: jobs.map((item) => item.id === job.id ? { ...item, clipId: clip.id, updatedAt: now } : item) });
- onOpenTimeline();
+ const generateScene = (job: GenerationJob) => {
+ if (job.status === "draft") void startDraft(job);
+ else void prepareOrRetry(job);
};
- /* Binding order does not matter: requestFor and the compiler both read
- config.references in list order and keep whatever this scene names, so the
- <Subject N> / <Picture N> numbering stays in lockstep however the boxes are
- ticked. */
- const toggleReference = (job: GenerationJob, referenceId: string) => {
- const referenceIds = job.referenceIds.includes(referenceId)
- ? job.referenceIds.filter((id) => id !== referenceId)
- : [...job.referenceIds, referenceId];
- updateJob(job.id, { referenceIds, updatedAt: new Date().toISOString() });
+ const draftScenesReady = jobs.filter((job) => job.status === "draft" && !sendBlocker(job, config.references));
+
+ const generateAll = async () => {
+ if (!runtimeReady || draftScenesReady.length === 0) return;
+ const current = configRef.current;
+ const ids = new Set(draftScenesReady.map((job) => job.id));
+ const now = new Date().toISOString();
+ onChange({
+ ...current,
+ generationJobs: current.generationJobs.map((job) => ids.has(job.id)
+ ? { ...job, status: "queued", stage: "queued", progress: 0, error: null, updatedAt: now }
+ : job),
+ });
+
+ for (const job of draftScenesReady) {
+ try {
+ const request = requestFor(job);
+ const plan = await resolveVidfabPlan(request, current);
+ setPlanNotes((notes) => ({ ...notes, [job.id]: `Planned as ${plan.alignedFrames} frames at ${plan.canvasWidth}×${plan.canvasHeight}. ${plan.boundary}` }));
+ await enqueueVidfabGeneration(request, current);
+ } catch (reason) {
+ updateJob(job.id, { status: "failed", stage: "failed", error: reason instanceof Error ? reason.message : String(reason) });
+ }
+ }
};
- const cancelJob = (job: GenerationJob) => {
- if (job.status === "generating" || job.status === "queued") void cancelVidfabGeneration(job.id);
- updateJob(job.id, { status: "cancelled", stage: "failed", updatedAt: new Date().toISOString() });
+ const generationBlocker = (job: GenerationJob): string | null => {
+ if (!runtimeReady) return runtime?.detail ?? "The video generator is not ready.";
+ if (job.status === "queued") return "This scene is already waiting in the queue.";
+ if (job.status === "generating") return "This scene is generating now.";
+ if (job.status === "ready") return "This scene is being saved now.";
+ return sendBlocker(job, config.references);
};
return <div className={`generator-view ${selected ? "" : "generator-view--empty"}`}>
@@ -252,7 +327,19 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on
for anyone — it gives the user somewhere to write them, and the
scene keeps the name UNTITLED_SCENE until they rename it. */}
<button className="secondary-button" onClick={newScene} title="Add an empty scene — you write the shots">
- <Plus size={16} aria-hidden="true" /> Add a scene
+ <Plus size={16} aria-hidden="true" /> Add Scene
+ </button>
+ <button
+ className="primary-button"
+ disabled={!runtimeReady || draftScenesReady.length === 0}
+ title={!runtimeReady
+ ? runtime?.detail ?? "The video generator is not ready."
+ : draftScenesReady.length === 0
+ ? "There are no ready draft scenes to generate."
+ : `Generate ${draftScenesReady.length} draft ${draftScenesReady.length === 1 ? "scene" : "scenes"}`}
+ onClick={() => void generateAll()}
+ >
+ <WandSparkles size={16} aria-hidden="true" /> Generate All
</button>
</div>
</header>
@@ -264,6 +351,12 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on
selection={{ jobId: selected?.id ?? "", shotId: openShot?.id ?? null }}
onSelect={setSelection}
onAddShot={addShot}
+ onDuration={setDuration}
+ onRemoveScene={(job) => setRemovalTarget({ kind: "scene", job })}
+ onGenerate={generateScene}
+ generationBlocker={generationBlocker}
+ onMoveScene={moveScene}
+ onMoveShot={moveShot}
/>}
{/* No scenes at all — which, on a new project, is where everyone starts.
@@ -284,16 +377,24 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on
</div>}
</main>
- {selected && <aside className="generator-panel" aria-label={openShot ? `Shot ${shotIndex + 1} of ${selected.title}` : `Scene: ${selected.title}`}>
+ {selected && <aside className="generator-panel" aria-label={openShot ? `${openShot.name ?? `Shot ${shotIndex + 1}`} of ${selected.title}` : `Scene: ${selected.title}`}>
{openShot
? <>
<header className="panel-head">
{/* The way back up: the scene this shot belongs to, which is the
same thing its line on the board opens. */}
<button type="button" className="panel-head__up" onClick={() => setSelection({ jobId: selected.id, shotId: null })}>
- {selected.title} · Scene settings
+ {selected.title}
</button>
- <h2>Shot {shotIndex + 1}<small>of {selectedShots.length === 1 ? "one shot" : `${selectedShots.length} shots`}</small></h2>
+ <h2><input
+ className="shot-title__name"
+ value={openShot.name ?? ""}
+ placeholder={`Shot ${shotIndex + 1}`}
+ aria-label={`Rename shot ${shotIndex + 1}`}
+ title="Rename this shot"
+ disabled={refsLocked}
+ onChange={(event) => patchShot(selected, openShot.id, { name: event.target.value || null })}
+ /></h2>
</header>
<div className="panel-scroll">
<ShotInspector
@@ -308,7 +409,7 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on
disabled={refsLocked}
removable={selectedShots.length > 1}
onChange={(updates) => patchShot(selected, openShot.id, updates)}
- onRemove={() => removeShot(selected, openShot.id)}
+ onRemove={() => setRemovalTarget({ kind: "shot", job: selected, shotId: openShot.id, shotName: openShot.name ?? `Shot ${shotIndex + 1}` })}
/>
{refsLocked && <p className="job-refs__empty">This scene is already with the engine. It can be changed once it finishes, and the next run will use the changes.</p>}
</div>
@@ -316,7 +417,7 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on
: <>
<header className="panel-head">
<div className="job-title">
- <span className={`status-icon status-icon--${selected.status}`}>{statusIcon(selected.status)}</span>
+ {selected.status !== "draft" && <span className={`status-icon status-icon--${selected.status}`}>{statusIcon(selected.status)}</span>}
<div>
{/* The badge is on the scene's own line on the board, where the
eye compares one scene against the next. A second copy of it
@@ -337,35 +438,6 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on
</header>
<div className="panel-scroll">
- <div className="job-progress-block">
- <div className="job-progress-block__head">
- <b>{progressTitle(selected)}</b>
- <span>{stageCopy(selected)}</span>
- </div>
- <div className="progress-track"><i style={{ width: `${selected.progress * 100}%` }} /></div>
- <ol className="stage-rail">
- {STAGES.map((stage, index) => {
- const done = selected.progress > 0 && selected.progress >= stage.at;
- return <li key={stage.label} className={done ? "done" : ""}>
- <i>{done ? <Check size={14} /> : index + 1}</i>
- <span>{stage.label}</span>
- </li>;
- })}
- <li className="stage-rail__blocked">
- <i><Ban size={14} /></i>
- <span>Save as a video file<small>Not built yet</small></span>
- </li>
- </ol>
- </div>
-
- {(planNotes[selected.id] || selected.error) && <div className="job-runtime-note">
- <span>What actually happened</span>
- <p>{planNotes[selected.id] ?? selected.error}</p>
- <small>Reported by the video engine (vidfab).</small>
- </div>}
-
- {/* How long the scene runs, where its cuts fall, and the three
- things the H3 guide defines once per prompt. */}
<SceneInspector
key={selected.id}
job={selected}
@@ -373,134 +445,32 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on
disabled={refsLocked}
onChange={(updates) => updateScene(selected, updates)}
onShots={(next) => setShots(selected, next)}
- onDuration={(value) => setDuration(selected, value)}
- onSelectShot={(shotId) => setSelection({ jobId: selected.id, shotId })}
/>
- {refsLocked && <p className="job-refs__empty">This scene is already with the engine. It can be changed once it finishes, and the next run will use the changes.</p>}
-
- <div className="job-refs">
- <span>{promptRefs.length === 0 ? "No references used by this scene" : promptRefs.length === 1 ? "1 reference guides this scene" : `${promptRefs.length} references guide this scene`}</span>
- {/* Every reference in the project, each a checkbox: which ones steer
- a scene is the user's decision. Writing one into a line ticks it
- here; unticking it takes it out of the prompt and out of what is
- sent to the engine. A bound reference the prompt skips stays
- listed with its reason — hiding it would leave the user
- wondering where it went. */}
- {config.references.map((ref) => {
- const bound = selected.referenceIds.includes(ref.id);
- const picture = ref.kind === "image" && (ref.relativePath || ref.sourcePath);
- const skipped = skipReason(ref);
- return <label key={ref.id} className={`job-ref ${bound ? "job-ref--bound" : ""}`}>
- <input
- type="checkbox"
- checked={bound}
- disabled={refsLocked}
- onChange={() => toggleReference(selected, ref.id)}
- />
- {/* The reference's real picture, not a stand-in. aria-hidden
- because the name it illustrates is the next node in this
- same <label>, and repeating it would say every reference
- twice when the checkbox announces itself. */}
- <span className="ref-mini" aria-hidden="true">
- {picture
- ? <ReferenceImage folderPath={folderPath} relativePath={ref.relativePath} sourcePath={ref.sourcePath} alt="" />
- : referenceKindIcon(ref.kind)}
- </span>
- <b>{ref.name}</b>
- {skipped
- ? <p className="job-refs__reason">{skipped}</p>
- : bound && !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>}
- </label>;
- })}
- {config.references.length === 0 && <p className="job-refs__empty">This project has no references yet. Add one under References and it can steer this scene.</p>}
- {/* Only the empty case says anything now. With references actually
- bound, the list above already shows what each one is and what is
- wrong with any that will not be used; a paragraph restating the
- route every one of them takes was a sentence about the system
- rather than about this scene. */}
- {promptRefs.length === 0 && <p className="job-refs__empty">The video engine only follows the words in the shots.</p>}
- </div>
-
- {/* Every setting on this scene collapsed into the one string vidfab is
- given. Recompiled from what the scene holds right now, so it cannot
- disagree with what the next run sends. */}
- <CompiledPrompt
- segments={compileGenerationJobSegments(selected, boundRefs)}
- caption={refsLocked
- ? "This is the prompt the engine was given for the run in progress."
- : "Rebuilt from this scene’s shots, settings and references every time it is sent."}
- />
-
- <dl className="job-meta">
- <div><dt>Video model</dt><dd>MiniMax H3</dd></div>
- <div><dt>Scene length</dt><dd>{sceneDurationSeconds(selected).toFixed(1)} seconds, {selectedShots.length === 1 ? "one shot" : `${selectedShots.length} shots`}</dd></div>
- {/* The project's own settings, not this scene's. The frame size is
- what the edit is exported at; the engine picks its own canvas
- from the shape alone (set_aspect is the only geometry vidfab
- takes), and the plan note above reports the one it picked. */}
- <div><dt>Shape</dt><dd>{config.settings.aspectRatio}</dd></div>
- <div><dt>Frame size</dt><dd>{resolutionLabel(config.settings.resolution, config.settings.aspectRatio)}</dd></div>
- <div><dt>Where it is</dt><dd>{STATUS_WORD[selected.status]}</dd></div>
- <div><dt>Saved to</dt><dd>{selected.outputRelativePath ?? "Nothing saved to disk"}</dd></div>
- </dl>
- </div>
-
- <div className="job-actions">
- {blocked && !refsLocked && <p className="job-actions__note">{blocked}</p>}
-
- {selected.status === "generating" && <button className="danger-button" onClick={() => cancelJob(selected)}><Square size={14} /> Stop this scene</button>}
-
- {selected.status === "queued" && <button className="danger-button" onClick={() => cancelJob(selected)}><X size={14} /> Take out of the queue</button>}
-
- {selected.status === "draft" && <>
- <button className="primary-button" disabled={!runtimeReady || Boolean(blocked)} onClick={() => void startDraft(selected)}>
- <WandSparkles size={15} /> {runtimeReady ? (jobs.length === 1 ? "Generate your first scene" : "Generate this scene") : "Can’t generate yet"}
- </button>
- {!runtimeReady && <p className="job-actions__note">This draft is saved with your project. PolStudio needs a working video engine before it can render it.</p>}
- </>}
-
- {(selected.status === "failed" || selected.status === "cancelled") && <>
- <button className="primary-button" disabled={!runtimeReady || Boolean(blocked)} onClick={() => void prepareOrRetry(selected)}>
- <RefreshCw size={15} /> {runtimeReady ? "Try this scene again" : "Can’t try again yet"}
- </button>
- {!runtimeReady && <p className="job-actions__note">PolStudio needs a working video engine before it can run this scene again.</p>}
- </>}
-
- {/* Between the last frame and the file: the pictures are rendered
- and are being encoded into an .mp4 in the project folder. It is
- a real step with a real duration — a few hundred megabytes
- through the machine's encoder — so it is a state, not a
- flicker. */}
- {selected.status === "ready" && <p className="job-actions__note">
- <LoaderCircle size={15} className="spin" /> Saving this scene into your project folder…
- </p>}
-
- {selected.status === "completed" && selected.outputRelativePath && !selected.clipId && <>
- <button className="primary-button" onClick={() => insertIntoStory(selected)}><Play size={15} /> Insert into Track 1</button>
- <p className="job-actions__note">Saved to <code>{selected.outputRelativePath}</code>.</p>
- </>}
-
- {/* Something was left out of the file — the scene is finished and
- the file exists, so this is a note rather than a failure. */}
- {selected.status === "completed" && selected.outputRelativePath && selected.error && <p className="job-actions__note">{selected.error}</p>}
-
- {selected.status === "completed" && selected.clipId && <button className="primary-button" onClick={onOpenTimeline}><Play size={15} /> Open in timeline</button>}
-
- {selected.status === "completed" && !selected.outputRelativePath && <>
- <button className="primary-button" disabled={!runtimeReady || Boolean(blocked)} onClick={() => void prepareOrRetry(selected)}>
- <RefreshCw size={15} /> {runtimeReady ? "Run this scene again" : "Can’t run it again yet"}
- </button>
- <p className="job-actions__note">This run finished without a video file in your project folder, so there is nothing to add to your edit.</p>
- </>}
+ {import.meta.env.DEV && <details className="debug-prompt">
+ <summary>Debug: final prompt</summary>
+ <CompiledPrompt segments={compileGenerationJobSegments(selected, boundRefs)} />
+ </details>}
</div>
</>}
</aside>}
+
+ {removalTarget && <div className="remove-dialog-backdrop">
+ <div className="remove-dialog" role="alertdialog" aria-modal="true" aria-labelledby="remove-dialog-title">
+ <h2 id="remove-dialog-title">Remove {removalTarget.kind}?</h2>
+ <p>{removalTarget.kind === "scene"
+ ? `Remove “${removalTarget.job.title}” and all of its shots?`
+ : `Remove “${removalTarget.shotName}” from “${removalTarget.job.title}”?`}</p>
+ <div>
+ <button type="button" className="secondary-button" onClick={() => setRemovalTarget(null)}>Cancel</button>
+ <button type="button" className="danger-button" onClick={() => {
+ if (removalTarget.kind === "scene") removeScene(removalTarget.job);
+ else removeShot(removalTarget.job, removalTarget.shotId);
+ setRemovalTarget(null);
+ }}>Remove {removalTarget.kind}</button>
+ </div>
+ </div>
+ </div>}
</div>;
}
@@ -526,54 +496,13 @@ function sendBlocker(job: GenerationJob, references: ProjectReference[]): string
/* The compiled prompt, shown before anything is sent and coloured by who wrote
which part. The segments come from the compiler itself, so this panel is the
string vidfab receives — not a re-rendering of it that could drift. */
-function CompiledPrompt({ segments, caption }: { segments: PromptSegment[]; caption: string }) {
+function CompiledPrompt({ segments }: { segments: PromptSegment[] }) {
return <section className="compiled-prompt" aria-label="The compiled MiniMax H3 prompt">
- <span className="compiled-prompt__title">The prompt this scene becomes</span>
- <p className="compiled-prompt__key">
- <em className="compiled-prompt__swatch compiled-prompt__swatch--brief">your words</em>
- <em className="compiled-prompt__swatch compiled-prompt__swatch--tag">your settings</em>
- <em className="compiled-prompt__swatch compiled-prompt__swatch--frame">the H3 format, added by PolStudio</em>
- </p>
<pre className="compiled-prompt__text">{segments.map((segment, index) =>
<span key={index} className={`prompt-part prompt-part--${segment.kind}`}>{segment.value}</span>)}</pre>
- <small>{caption}</small>
</section>;
}
-/* Why a reference that is bound to this scene never reaches its prompt, or null
- when it does. The wording mirrors the References card so the two screens
- describe the same state in the same words. */
-const skipReason = (reference: ProjectReference): string | null => {
- if (!isReferenceUsable(reference)) return "Not described yet — not used by this scene";
- if (!isVisualReference(reference)) return "Tagged as a sound note, so it isn’t sent to the video engine.";
- return null;
-};
-
-/* The stand-in for a reference whose own picture is not being shown. The four
- kinds get four icons, which they did not before: an `image` arm sat here that
- nothing could reach — referenceSchema refuses an image with no file, so a
- parsed image reference always has one and always renders the real picture —
- while `video` and `audio`, which DO reach here (they are pointed at rather
- than copied, and ReferenceImage cannot show a frame of either), fell through
- to the same page icon a written definition gets. Same icons as
- MediaThumbnail, so a clip and the reference it came from read alike. */
-const referenceKindIcon = (kind: ProjectReference["kind"]) =>
- kind === "video" ? <Video size={16} />
- : kind === "audio" ? <Music2 size={16} />
- /* Unreachable for anything zod parsed; kept so a future kind that can
- legitimately arrive without a file is not silently called a document. */
- : kind === "image" ? <ImageIcon size={16} />
- : <FileText size={16} />;
-
-/* The three things that happen to a scene, in the order they happen. "Save" is
- the encode: the engine's pictures being written into an .mp4 in the project
- folder, which is the last tenth of the bar. */
-const STAGES: Array<{ label: string; at: number }> = [
- { label: "Prepare", at: 0.01 },
- { label: "Render", at: 0.5 },
- { label: "Save", at: 0.9 },
-];
-
const boardSummary = (active: number, waiting: number, total: number) => {
if (total === 0) return "Nothing here yet";
if (active > 0) return `${active} rendering · ${waiting} waiting`;
diff --git a/src/components/workspace/SceneBoard.tsx b/src/components/workspace/SceneBoard.tsx
index e4ec6a3..f800a65 100644
--- a/src/components/workspace/SceneBoard.tsx
+++ b/src/components/workspace/SceneBoard.tsx
@@ -1,65 +1,193 @@
-import { Plus, SlidersHorizontal } from "lucide-react";
-import { sceneDurationSeconds, sceneShots, splitActionText, type GenerationJob, type ProjectReference, type SceneShot } from "../../lib/project";
+import { GripVertical, Plus, SlidersHorizontal, Trash2, WandSparkles } from "lucide-react";
+import {
+ SCENE_MAX_SECONDS,
+ SCENE_MIN_SECONDS,
+ sceneDurationSeconds,
+ sceneShots,
+ splitActionText,
+ type GenerationJob,
+ type ProjectReference,
+ type SceneShot,
+} from "../../lib/project";
import { selectedShotTagOptions } from "../../lib/shot-tags";
-import { referenceOrder } from "./SceneEditor";
-import { sceneLine, statusIcon, STATUS_BADGE } from "./sceneStatus";
+import { referenceOrder, STEP_SECONDS } from "./SceneEditor";
+import { statusIcon, STATUS_BADGE } from "./sceneStatus";
import { ShotThumbnail } from "./ShotThumbnail";
-/** What the right-hand panel is looking at. A scene is always named; `shotId`
- * is the shot inside it, or null when the SCENE itself is what is open —
- * which is what the line above each row of cards selects. */
export interface GeneratorSelection {
jobId: string;
shotId: string | null;
}
+export const SCENE_DRAG_TYPE = "application/x-polstudio-scene";
+export const SHOT_DRAG_TYPE = "application/x-polstudio-shot";
+
const seconds = (value: number): string => `${value.toFixed(1)}s`;
+const hasDragType = (types: readonly string[], type: string): boolean => Array.from(types).includes(type);
+
+interface ShotDragData {
+ jobId: string;
+ shotId: string;
+}
-/* The board: every scene in the project, one row of shot cards each, separated
- * by the line that carries the scene's own name and settings.
- *
- * Shots read left to right in the order they play, and the cards are the
- * SUMMARY of a shot — its picture, its words and the settings hung off it.
- * Nothing is edited here; clicking one opens it in the panel to the right. */
-export function SceneBoard({ jobs, folderPath, references, selection, onSelect, onAddShot }: {
+const readShotDrag = (value: string): ShotDragData | null => {
+ try {
+ const parsed = JSON.parse(value) as Partial<ShotDragData>;
+ return typeof parsed.jobId === "string" && typeof parsed.shotId === "string"
+ ? { jobId: parsed.jobId, shotId: parsed.shotId }
+ : null;
+ } catch {
+ return null;
+ }
+};
+
+/** The Generator board. Scene headers own scene-wide actions and timing; shot
+ * cards remain the entry point to a shot's editor and double as drop targets. */
+export function SceneBoard({
+ jobs,
+ folderPath,
+ references,
+ selection,
+ onSelect,
+ onAddShot,
+ onDuration,
+ onRemoveScene,
+ onGenerate,
+ generationBlocker,
+ onMoveScene,
+ onMoveShot,
+}: {
jobs: GenerationJob[];
folderPath: string;
references: ProjectReference[];
selection: GeneratorSelection;
onSelect: (selection: GeneratorSelection) => void;
onAddShot: (job: GenerationJob) => void;
+ onDuration: (job: GenerationJob, value: number) => void;
+ onRemoveScene: (job: GenerationJob) => void;
+ onGenerate: (job: GenerationJob) => void;
+ generationBlocker: (job: GenerationJob) => string | null;
+ onMoveScene: (jobId: string, beforeJobId: string | null) => void;
+ onMoveShot: (sourceJobId: string, shotId: string, targetJobId: string, beforeShotId: string | null) => void;
}) {
return <div className="scene-board">
- {jobs.map((job) => {
+ {jobs.map((job, jobIndex) => {
const shots = sceneShots(job);
const duration = sceneDurationSeconds(job);
const order = referenceOrder(job, shots, references);
const named = new Map(references.map((reference) => [reference.id, reference.name]));
const sceneOpen = selection.jobId === job.id && selection.shotId === null;
- return <section key={job.id} className={`scene-section ${selection.jobId === job.id ? "scene-section--current" : ""}`} aria-label={job.title}>
- {/* The scene line: the rule that separates one scene's shots from the
- next one's, and the control that opens the scene's own settings. */}
+ const locked = job.status === "queued" || job.status === "generating";
+ const blocker = generationBlocker(job);
+
+ const dropScene = (event: React.DragEvent<HTMLElement>) => {
+ if (!hasDragType(event.dataTransfer.types, SCENE_DRAG_TYPE)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ const draggedId = event.dataTransfer.getData(SCENE_DRAG_TYPE);
+ if (!draggedId) return;
+ const box = event.currentTarget.getBoundingClientRect();
+ const after = box.height > 0 && event.clientY > box.top + box.height / 2;
+ onMoveScene(draggedId, after ? jobs[jobIndex + 1]?.id ?? null : job.id);
+ };
+
+ return <section
+ key={job.id}
+ className={`scene-section ${selection.jobId === job.id ? "scene-section--current" : ""}`}
+ aria-label={job.title}
+ onDragOver={(event) => {
+ if (hasDragType(event.dataTransfer.types, SCENE_DRAG_TYPE)) event.preventDefault();
+ }}
+ onDrop={dropScene}
+ >
<header className="scene-rule">
+ <span
+ className="scene-rule__drag"
+ role="button"
+ tabIndex={0}
+ draggable
+ aria-label={`Drag ${job.title} to reorder scenes`}
+ title="Drag to reorder this scene"
+ onDragStart={(event) => {
+ event.dataTransfer.setData(SCENE_DRAG_TYPE, job.id);
+ event.dataTransfer.effectAllowed = "move";
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "ArrowUp" && jobIndex > 0) {
+ event.preventDefault();
+ onMoveScene(job.id, jobs[jobIndex - 1].id);
+ } else if (event.key === "ArrowDown" && jobIndex < jobs.length - 1) {
+ event.preventDefault();
+ onMoveScene(job.id, jobs[jobIndex + 2]?.id ?? null);
+ }
+ }}
+ ><GripVertical size={17} aria-hidden="true" /></span>
+
+ <div className="scene-rule__summary">
+ {job.status !== "draft" && <span className={`scene-rule__status scene-rule__status--${job.status}`}>{statusIcon(job.status, 15)}</span>}
+ <span className="scene-rule__text">
+ <b>{job.title}</b>
+ </span>
+ {job.status !== "draft" && <span className="scene-rule__badge">{STATUS_BADGE[job.status]}</span>}
+ </div>
+
+ <label className="scene-rule__length">
+ <span>Length</span>
+ <input
+ type="range"
+ min={SCENE_MIN_SECONDS}
+ max={SCENE_MAX_SECONDS}
+ step={STEP_SECONDS}
+ value={duration}
+ disabled={locked}
+ aria-label={`${job.title} length in seconds`}
+ onChange={(event) => onDuration(job, Number(event.target.value))}
+ />
+ <b>{seconds(duration)}</b>
+ </label>
+
<button
type="button"
- className={`scene-rule__open ${sceneOpen ? "scene-rule__open--open" : ""}`}
+ className="secondary-button scene-rule__settings-button"
aria-pressed={sceneOpen}
- aria-label={`Scene settings for ${job.title}`}
+ aria-label={`Settings for ${job.title}`}
onClick={() => onSelect({ jobId: job.id, shotId: null })}
- >
- <span className={`scene-rule__status scene-rule__status--${job.status}`}>{statusIcon(job.status, 15)}</span>
- <span className="scene-rule__text">
- <b>{job.title}</b>
- <small>{sceneLine(job)}</small>
- </span>
- <span className="scene-rule__badge">{STATUS_BADGE[job.status]}</span>
- <span className="scene-rule__settings"><SlidersHorizontal size={15} aria-hidden="true" /> Scene settings</span>
- </button>
- <span className="scene-rule__line" aria-hidden="true" />
+ ><SlidersHorizontal size={15} aria-hidden="true" /> Settings</button>
+
+ <button
+ type="button"
+ className="scene-rule__remove"
+ aria-label={`Remove scene ${job.title}`}
+ title={`Remove ${job.title}`}
+ onClick={() => onRemoveScene(job)}
+ ><Trash2 size={16} aria-hidden="true" /></button>
+
+ <button
+ type="button"
+ className="primary-button scene-rule__generate"
+ disabled={Boolean(blocker)}
+ title={blocker ?? `Generate ${job.title}`}
+ onClick={() => onGenerate(job)}
+ ><WandSparkles size={15} aria-hidden="true" /> Generate</button>
</header>
<ol className="shot-grid">
- {shots.map((shot, index) => <li key={shot.id}>
+ {shots.map((shot, index) => <li
+ key={shot.id}
+ onDragOver={(event) => {
+ if (hasDragType(event.dataTransfer.types, SHOT_DRAG_TYPE)) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }}
+ onDrop={(event) => {
+ if (!hasDragType(event.dataTransfer.types, SHOT_DRAG_TYPE)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ const dragged = readShotDrag(event.dataTransfer.getData(SHOT_DRAG_TYPE));
+ if (dragged) onMoveShot(dragged.jobId, dragged.shotId, job.id, shot.id);
+ }}
+ >
<ShotCard
job={job}
shot={shot}
@@ -69,14 +197,34 @@ export function SceneBoard({ jobs, folderPath, references, selection, onSelect,
order={order}
named={named}
open={selection.jobId === job.id && selection.shotId === shot.id}
+ draggable={!locked}
onOpen={() => onSelect({ jobId: job.id, shotId: shot.id })}
+ onDragStart={(event) => {
+ event.dataTransfer.setData(SHOT_DRAG_TYPE, JSON.stringify({ jobId: job.id, shotId: shot.id }));
+ event.dataTransfer.effectAllowed = "move";
+ }}
/>
</li>)}
- <li>
+ <li
+ onDragOver={(event) => {
+ if (hasDragType(event.dataTransfer.types, SHOT_DRAG_TYPE)) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }}
+ onDrop={(event) => {
+ if (!hasDragType(event.dataTransfer.types, SHOT_DRAG_TYPE)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ const dragged = readShotDrag(event.dataTransfer.getData(SHOT_DRAG_TYPE));
+ if (dragged) onMoveShot(dragged.jobId, dragged.shotId, job.id, null);
+ }}
+ >
<button
type="button"
className="shot-card shot-card--add"
aria-label={`Add a shot to ${job.title}`}
+ disabled={locked}
onClick={() => onAddShot(job)}
>
<Plus size={18} aria-hidden="true" />
@@ -89,20 +237,18 @@ export function SceneBoard({ jobs, folderPath, references, selection, onSelect,
</div>;
}
-/** One shot, as it reads on the board. Everything on it is a summary of what
- * the panel to the right edits — no control of its own, because a card that
- * both opens a shot and changes it is a card you cannot click. */
-function ShotCard({ job, shot, index, endsAt, folderPath, order, named, open, onOpen }: {
+function ShotCard({ job, shot, index, endsAt, folderPath, order, named, open, draggable, onOpen, onDragStart }: {
job: GenerationJob;
shot: SceneShot;
index: number;
endsAt: number;
folderPath: string;
- /** Reference ids in the order this scene numbers them. */
order: string[];
named: Map<string, string>;
open: boolean;
+ draggable: boolean;
onOpen: () => void;
+ onDragStart: (event: React.DragEvent<HTMLButtonElement>) => void;
}) {
const parts = splitActionText(shot.action);
const written = shot.action.trim().length > 0;
@@ -112,18 +258,17 @@ function ShotCard({ job, shot, index, endsAt, folderPath, order, named, open, on
type="button"
className={`shot-card ${open ? "shot-card--open" : ""}`}
aria-pressed={open}
- aria-label={`Shot ${index + 1} of ${job.title}`}
+ aria-label={`${shot.name ?? `Shot ${index + 1}`} of ${job.title}`}
+ title={draggable ? "Drag to reorder this shot or move it to another scene" : "This shot cannot be moved while its scene is rendering"}
+ draggable={draggable}
+ onDragStart={onDragStart}
onClick={onOpen}
>
<ShotThumbnail folderPath={folderPath} job={job} seconds={shot.startSeconds} shotNumber={index + 1} />
-
<span className="shot-card__head">
- <b>Shot {index + 1}</b>
+ <b>{shot.name ?? `Shot ${index + 1}`}</b>
<em>{seconds(shot.startSeconds)} – {seconds(endsAt)}</em>
</span>
-
- {/* The line as it was written, with each citation shown as the reference it
- points at rather than as the token that stores it. */}
<span className={`shot-card__line ${written ? "" : "shot-card__line--empty"}`}>
{written
? parts.map((part, at) => part.kind === "text"
@@ -131,11 +276,8 @@ function ShotCard({ job, shot, index, endsAt, folderPath, order, named, open, on
: <em key={at} className="shot-card__ref">{named.get(part.value) ?? `Reference ${order.indexOf(part.value) + 1}`}</em>)
: "No words yet — choose this shot and write what happens."}
</span>
-
<span className="shot-card__tags">
- {chosen.map(({ group, option }) => <em key={`${group.id}-${option.id}`} className="shot-card__tag">
- {option.label}
- </em>)}
+ {chosen.map(({ group, option }) => <em key={`${group.id}-${option.id}`} className="shot-card__tag">{option.label}</em>)}
{chosen.length === 0 && <em className="shot-card__tag shot-card__tag--none">No settings</em>}
</span>
</button>;
diff --git a/src/components/workspace/SceneEditor.tsx b/src/components/workspace/SceneEditor.tsx
index a828f54..279da24 100644
--- a/src/components/workspace/SceneEditor.tsx
+++ b/src/components/workspace/SceneEditor.tsx
@@ -10,7 +10,6 @@ import {
sceneBriefText,
sceneDurationSeconds,
splitActionText,
- SCENE_MAX_SECONDS,
SCENE_MIN_SECONDS,
type GenerationJob,
type ProjectReference,
@@ -228,17 +227,15 @@ export function ShotInspector({ job, shots, shot, index, endsAt, duration, refer
/* --- The scene, opened from its own line ---------------------------------- */
-/** What belongs to the whole scene rather than to one shot: how long it runs
- * and where its cuts fall, the look the description opens with (base guide
- * §4.1), and the two sound fields the guide defines per prompt (§4.6, §4.7). */
-export function SceneInspector({ job, shots, disabled, onChange, onShots, onDuration, onSelectShot }: {
+/** What remains in scene settings: the look the description opens with (base
+ * guide §4.1), and the two sound fields the guide defines per prompt (§4.6,
+ * §4.7). Length lives in the scene header where it stays visible. */
+export function SceneInspector({ job, shots, disabled, onChange, onShots }: {
job: GenerationJob;
shots: SceneShot[];
disabled: boolean;
onChange: (updates: Partial<GenerationJob>) => void;
onShots: (next: SceneShot[]) => void;
- onDuration: (value: number) => void;
- onSelectShot: (shotId: string) => void;
}) {
const look = SHOT_TAG_GROUPS.find((group) => group.id === "visualStyle")!;
// The style is read off the first shot that carries one, so that is where it
@@ -246,17 +243,8 @@ export function SceneInspector({ job, shots, disabled, onChange, onShots, onDura
const chosen = shots.map((shot) => shot.settings?.[look.id]?.[0]).find(Boolean) ?? "";
return <section className="scene-inspector" aria-label="This scene">
- <SceneLengthBar
- shots={shots}
- duration={sceneDurationSeconds(job)}
- disabled={disabled}
- onDuration={onDuration}
- onStart={(id, startSeconds) => onShots(shots.map((shot) => shot.id === id ? { ...shot, startSeconds } : shot))}
- onSelect={onSelectShot}
- />
-
<div className="scene-settings">
- <h3>The whole scene</h3>
+ <h3>Scene</h3>
<label className="scene-settings__field">
<span>Look</span>
<select
@@ -276,7 +264,6 @@ export function SceneInspector({ job, shots, disabled, onChange, onShots, onDura
<option value="">Guessed from your words</option>
{look.options.map((option) => <option key={option.id} value={option.id}>{option.label}</option>)}
</select>
- <small>{look.help}</small>
</label>
<label className="scene-settings__field">
<span>Sound</span>
@@ -287,7 +274,6 @@ export function SceneInspector({ job, shots, disabled, onChange, onShots, onDura
placeholder="Ambience, and the sounds the action itself makes."
onChange={(event) => onChange({ soundscape: event.target.value })}
/>
- <small>Goes into <code>overall_soundscape</code>. Left blank, PolStudio writes a line that adds nothing your description has not already established.</small>
</label>
<label className="scene-settings__field">
<span>Music</span>
@@ -298,117 +284,11 @@ export function SceneInspector({ job, shots, disabled, onChange, onShots, onDura
placeholder="Instrumentation, tempo and dynamics — not a mood."
onChange={(event) => onChange({ music: event.target.value })}
/>
- <small>Goes into <code>non_diegetic_music</code>. Left blank, it is sent as N/A, because a score nobody asked for is one PolStudio would have invented.</small>
</label>
</div>
</section>;
}
-/* --- The length, and where each shot starts ------------------------------- */
-
-/** The bar the scene is split on. Each shot is a segment; the line between two
- * of them is the cut, and it can be dragged or nudged with the arrow keys.
- * Every shot also carries a plain number field in its own panel, because a bar
- * cannot be read by a screen reader and cannot be typed into. */
-function SceneLengthBar({ shots, duration, disabled, onDuration, onStart, onSelect }: {
- shots: SceneShot[];
- duration: number;
- disabled: boolean;
- onDuration: (value: number) => void;
- onStart: (id: string, value: number) => void;
- onSelect: (id: string) => void;
-}) {
- const trackRef = useRef<HTMLDivElement | null>(null);
- const [dragging, setDragging] = useState<string | null>(null);
-
- /** Where a cut may sit: after the shot in front of it, before the one behind,
- * and never past the end of the scene. */
- const limits = (index: number): [number, number] => [
- shots[index - 1].startSeconds + STEP_SECONDS,
- Math.min(duration, index + 1 < shots.length ? shots[index + 1].startSeconds - STEP_SECONDS : duration),
- ];
-
- const clamp = (index: number, value: number): number => {
- const [low, high] = limits(index);
- const stepped = Math.round(value / STEP_SECONDS) * STEP_SECONDS;
- return Math.min(Math.max(stepped, low), Math.max(low, high));
- };
-
- const dragTo = (index: number, clientX: number) => {
- const track = trackRef.current?.getBoundingClientRect();
- // jsdom, and any layout that has not happened yet, report a zero-width box.
- // Guessing a position from that would throw every cut to the head of the
- // scene the moment a handle was touched.
- if (!track || track.width <= 0 || index <= 0) return;
- onStart(shots[index].id, clamp(index, ((clientX - track.left) / track.width) * duration));
- };
-
- const width = (index: number): number => {
- if (duration <= 0) return 100 / shots.length;
- const end = index + 1 < shots.length ? shots[index + 1].startSeconds : duration;
- return Math.max(0, (end - shots[index].startSeconds) / duration) * 100;
- };
-
- return <div className="scene-bar">
- <div className="scene-bar__head">
- <label className="scene-bar__length">
- <span>Scene length</span>
- <input
- type="range"
- min={SCENE_MIN_SECONDS}
- max={SCENE_MAX_SECONDS}
- step={STEP_SECONDS}
- value={duration}
- disabled={disabled}
- aria-label="Scene length in seconds"
- onChange={(event) => onDuration(Number(event.target.value))}
- />
- <b>{seconds(duration)}</b>
- </label>
- <span className="scene-bar__range">A scene runs from 0 to {SCENE_MAX_SECONDS} seconds, and holds as many shots as you split it into.</span>
- </div>
-
- <div
- className="scene-bar__track"
- ref={trackRef}
- onPointerMove={(event) => { if (dragging !== null) dragTo(shots.findIndex((shot) => shot.id === dragging), event.clientX); }}
- onPointerUp={() => setDragging(null)}
- onPointerLeave={() => setDragging(null)}
- >
- {shots.map((shot, index) => <div
- key={shot.id}
- className="scene-bar__shot"
- style={{ width: `${width(index)}%` }}
- >
- {index > 0 && <button
- type="button"
- className="scene-bar__handle"
- role="slider"
- aria-label={`Cut to shot ${index + 1}`}
- aria-valuemin={limits(index)[0]}
- aria-valuemax={limits(index)[1]}
- aria-valuenow={shot.startSeconds}
- aria-valuetext={seconds(shot.startSeconds)}
- disabled={disabled}
- onPointerDown={() => setDragging(shot.id)}
- onKeyDown={(event) => {
- const delta = event.key === "ArrowLeft" ? -STEP_SECONDS : event.key === "ArrowRight" ? STEP_SECONDS : 0;
- if (delta === 0) return;
- event.preventDefault();
- onStart(shot.id, clamp(index, shot.startSeconds + delta));
- }}
- />}
- {/* Opens the shot in the panel, which is the same thing clicking its
- card on the board does — the bar is the other way to reach it. */}
- <button type="button" className="scene-bar__label" onClick={() => onSelect(shot.id)}>
- <b>Shot {index + 1}</b>
- <em>{seconds(shot.startSeconds)}</em>
- </button>
- </div>)}
- </div>
- </div>;
-}
-
/** The same line, read back with each reference as a control. This is where
* "click Reference 1 and choose another one" lives: the select IS the token,
* so re-pointing it changes which reference the sentence names without
diff --git a/src/lib/project.ts b/src/lib/project.ts
index aa1b1bb..f587bc3 100644
--- a/src/lib/project.ts
+++ b/src/lib/project.ts
@@ -235,6 +235,9 @@ export const DEFAULT_SCENE_SECONDS = 6;
export const sceneShotSchema = z.object({
id: idSchema,
+ /** Optional so every project written before shots could be named keeps
+ * round-tripping unchanged. The UI falls back to its numbered Shot N label. */
+ name: z.string().min(1).nullish(),
/** Seconds from the head of the scene. The first shot always starts at 0;
* `normalizeSceneShots` enforces that rather than trusting the file. */
startSeconds: z.number().min(SCENE_MIN_SECONDS).max(SCENE_MAX_SECONDS),
diff --git a/src/styles/generator.css b/src/styles/generator.css
index 015137f..59288a7 100644
--- a/src/styles/generator.css
+++ b/src/styles/generator.css
@@ -136,32 +136,44 @@
.scene-rule {
display: flex;
+ flex-wrap: wrap;
align-items: center;
gap: var(--space-3);
+ width: 100%;
+ padding: var(--space-3);
+ border: 1px solid var(--line);
+ border-radius: var(--radius-lg);
+ background: var(--panel);
+}
+
+.scene-rule__drag {
+ width: var(--control-sm);
+ height: var(--control-sm);
+ flex: 0 0 auto;
+ display: grid;
+ place-items: center;
+ border-radius: var(--radius-sm);
+ color: var(--text-muted);
+ cursor: grab;
+}
+
+.scene-rule__drag:hover {
+ color: var(--text-primary);
+ background: var(--panel-2);
+}
+
+.scene-rule__drag:active {
+ cursor: grabbing;
}
-.scene-rule__open {
+.scene-rule__summary {
+ flex: 1 1 280px;
min-width: 0;
min-height: var(--control-sm);
display: flex;
align-items: center;
gap: var(--space-3);
- padding: var(--space-2) var(--space-3);
- border: 1px solid transparent;
- border-radius: var(--radius-md);
- color: inherit;
- background: none;
- text-align: left;
-}
-
-.scene-rule__open:hover {
- border-color: var(--line-strong);
- background: var(--panel);
-}
-
-.scene-rule__open--open {
- border-color: var(--accent);
- background: var(--accent-soft);
+ padding: var(--space-2) 0;
}
.scene-rule__status {
@@ -214,12 +226,6 @@
white-space: nowrap;
}
-.scene-rule__text small {
- color: var(--text-muted);
- font-size: var(--text-xs);
- line-height: var(--leading-snug);
-}
-
.scene-rule__badge {
flex: 0 0 auto;
color: var(--text-muted);
@@ -227,19 +233,58 @@
letter-spacing: var(--tracking-label);
}
-.scene-rule__settings {
+.scene-rule__settings-button {
flex: 0 0 auto;
- display: inline-flex;
+ min-height: var(--control-sm);
+ white-space: nowrap;
+}
+
+.scene-rule__length {
+ flex: 0 0 auto;
+ display: flex;
align-items: center;
gap: var(--space-2);
+ min-height: var(--control-sm);
color: var(--text-muted);
font-size: var(--text-xs);
font-weight: var(--weight-semibold);
}
-.scene-rule__open:hover .scene-rule__settings,
-.scene-rule__open--open .scene-rule__settings {
- color: var(--accent-bright);
+.scene-rule__length input[type="range"] {
+ width: 150px;
+ max-width: 18vw;
+ accent-color: var(--accent);
+}
+
+.scene-rule__length b {
+ min-width: 4.5ch;
+ color: var(--text-primary);
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+}
+
+.scene-rule__remove {
+ width: var(--control-sm);
+ height: var(--control-sm);
+ flex: 0 0 auto;
+ display: grid;
+ place-items: center;
+ padding: 0;
+ border: 1px solid var(--line);
+ border-radius: var(--radius-sm);
+ color: var(--text-muted);
+ background: var(--panel-2);
+}
+
+.scene-rule__remove:hover {
+ border-color: var(--danger);
+ color: var(--danger);
+}
+
+.scene-rule__generate {
+ flex: 0 0 auto;
+ min-height: var(--control-sm);
+ white-space: nowrap;
}
/* The line itself: what actually separates one scene from the next. */
@@ -424,6 +469,11 @@
color: inherit;
background: var(--panel);
text-align: left;
+ cursor: grab;
+}
+
+.shot-card:active:not(:disabled) {
+ cursor: grabbing;
}
.shot-card:hover {
@@ -518,6 +568,7 @@
border-style: dashed;
color: var(--text-muted);
background: none;
+ cursor: pointer;
}
.shot-card--add:hover {
@@ -630,15 +681,23 @@
}
.shot-card__remove {
- display: grid;
- place-items: center;
- width: var(--control-sm);
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: var(--space-2);
+ width: auto;
+ min-width: var(--control-sm);
height: var(--control-sm);
- padding: 0;
+ padding: 0 var(--space-3);
border: 1px solid var(--line);
border-radius: var(--radius-sm);
color: var(--text-muted);
background: var(--panel-2);
+ white-space: nowrap;
+}
+
+.shot-card__remove svg {
+ flex: 0 0 auto;
}
.shot-card__remove:hover:not(:disabled) {
@@ -1094,6 +1153,31 @@
letter-spacing: 0;
}
+.shot-title__name {
+ width: 100%;
+ min-width: 0;
+ padding: 2px var(--space-1);
+ margin-left: calc(var(--space-1) * -1);
+ border: 1px solid transparent;
+ border-radius: var(--radius-sm);
+ color: inherit;
+ background: none;
+ font: inherit;
+ letter-spacing: inherit;
+}
+
+.shot-title__name:hover:not(:disabled),
+.shot-title__name:focus {
+ border-color: var(--accent-bright);
+ background: var(--panel-2);
+ outline: none;
+}
+
+.shot-title__name::placeholder {
+ color: var(--text-primary);
+ opacity: 1;
+}
+
/* The way back up to the scene, which is the same place its line on the board
opens — so a shot is never a dead end. */
.panel-head__up {
@@ -1160,106 +1244,54 @@
flex-direction: column;
gap: var(--space-4);
}
-/* --- Progress block -------------------------------------------------------- */
-
-.job-progress-block {
- padding: 0;
-}
-.job-progress-block__head {
- display: flex;
- flex-direction: column;
- gap: var(--space-1);
-}
-
-.job-progress-block__head b {
- color: var(--text-primary);
- font-size: var(--text-lg);
- font-weight: var(--weight-semibold);
- line-height: var(--leading-snug);
- letter-spacing: var(--tracking-tight);
-}
-
-.job-progress-block__head span {
- max-width: 70ch;
+.debug-prompt summary {
color: var(--text-muted);
- font-size: var(--text-base);
- line-height: var(--leading-normal);
-}
-
-.job-progress-block .progress-track {
- height: 8px;
- margin: var(--space-4) 0 var(--space-4);
- background: var(--panel-3);
-}
-
-/* The rail shows the three steps that can actually happen today, plus the one
- step PolStudio cannot do at all — drawn as blocked, never as "pending". */
-
-.stage-rail {
- display: flex;
- flex-wrap: wrap;
- align-items: center;
- gap: var(--space-2) var(--space-5);
- margin: 0;
- padding: 0;
- list-style: none;
+ cursor: pointer;
+ font-size: var(--text-xs);
}
-.stage-rail li {
- display: flex;
- align-items: center;
- gap: var(--space-2);
- color: var(--text-muted);
- font-size: var(--text-sm);
- line-height: var(--leading-snug);
+.debug-prompt .compiled-prompt {
+ margin-top: var(--space-3);
}
-.stage-rail li i {
- width: 26px;
- height: 26px;
- flex: 0 0 auto;
+.remove-dialog-backdrop {
+ position: fixed;
+ z-index: 120;
+ inset: 0;
display: grid;
place-items: center;
- border: 1px solid var(--line-strong);
- border-radius: 50%;
- font-style: normal;
- font-size: var(--text-2xs);
- font-family: var(--font-mono);
-}
-
-.stage-rail li.done {
- color: var(--text-secondary);
-}
-
-.stage-rail li.done i {
- color: var(--on-accent);
- border-color: var(--accent-bright);
- background: var(--accent);
+ padding: var(--space-4);
+ background: var(--scrim);
+ backdrop-filter: blur(5px);
}
-.stage-rail__blocked {
- margin-left: auto;
+.remove-dialog {
+ width: min(440px, 100%);
+ padding: var(--space-6);
+ border: 1px solid var(--line-strong);
+ border-radius: var(--radius-lg);
+ background: var(--panel);
+ box-shadow: var(--shadow);
}
-.stage-rail__blocked i {
- color: var(--danger);
- border-color: color-mix(in srgb, var(--danger) 45%, transparent) !important;
- background: color-mix(in srgb, var(--danger) 14%, transparent);
+.remove-dialog h2 {
+ margin: 0;
+ color: var(--text-primary);
+ font-size: var(--text-xl);
}
-.stage-rail__blocked span {
- display: flex;
- flex-direction: column;
+.remove-dialog p {
+ margin: var(--space-3) 0 var(--space-5);
color: var(--text-secondary);
+ line-height: var(--leading-normal);
}
-.stage-rail__blocked small {
- color: var(--danger);
- font-size: var(--text-2xs);
- line-height: var(--leading-snug);
+.remove-dialog > div {
+ display: flex;
+ justify-content: flex-end;
+ gap: var(--space-2);
}
-
/* --- The panel's scrolling middle ----------------------------------------- */
.panel-scroll {
@@ -1700,13 +1732,6 @@
padding: var(--space-4);
}
- .stage-rail {
- gap: var(--space-2) var(--space-4);
- }
-
- .stage-rail__blocked {
- margin-left: 0;
- }
}
/* Under 960 the panel has nowhere left to go sideways, so it goes under the
@@ -1731,4 +1756,4 @@
grid-template-columns: minmax(0, 1fr);
gap: var(--space-3);
}
-}
\ No newline at end of file
+}