AI media harness for planning, generating, and editing locally
TypeScript
Rebuild the generator around a scene editor
Bittibcbdbb27beeb
diff --git a/src/components/ProjectWorkspace.test.ts b/src/components/ProjectWorkspace.test.tsindex 69a783b..87dd51c 100644--- a/src/components/ProjectWorkspace.test.ts+++ b/src/components/ProjectWorkspace.test.ts@@ -8,6 +8,7 @@ import { compileMiniMaxH3Prompt, createProjectConfig, parseProjectConfig, STORY_import { formatDurationTimecode } from "./ProjectWorkspace";import { ProjectWorkspace } from "./ProjectWorkspace";import { GeneratorView } from "./workspace/GeneratorView";+import { REFERENCE_DRAG_TYPE } from "./workspace/SceneEditor";import { ReferencesView } from "./workspace/ReferencesView";import { TimelineView } from "./workspace/TimelineView";@@ -621,15 +622,15 @@ 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 shot")).not.toBeNull();- expect(screen.queryByText("3 references guide this shot")).toBeNull();+ 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 shot")).not.toBeNull();+ expect(screen.getByText("Not described yet — not used by this scene")).not.toBeNull();expect(screen.getByText(/sound note/)).not.toBeNull();});- it("renames a shot, and never saves it nameless", () => {+ it("renames a scene, and never saves it nameless", () => {const config = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });const onChange = vi.fn();render(createElement(GeneratorView, { config, folderPath: "C:\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));@@ -638,7 +639,7 @@ describe("project workspace timecode", () => {expect(onChange.mock.calls[0][0].generationJobs[0].title).toBe("Clay on the wheel");// The schema has no room for an empty title, so an emptied field falls back.fireEvent.change(field, { target: { value: "" } });- expect(onChange.mock.calls[1][0].generationJobs[0].title).toBe("Untitled shot");+ expect(onChange.mock.calls[1][0].generationJobs[0].title).toBe("Untitled scene");expect(parseProjectConfig(onChange.mock.calls[1][0])).toBeTruthy();});@@ -679,12 +680,12 @@ describe("project workspace timecode", () => {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 shot")).toBeNull();- expect(screen.getByText("No references used by this shot")).not.toBeNull();+ 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 above.")).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 shot/)).toBeNull();+ expect(screen.queryByText(/text definitions are written into this scene/)).toBeNull();});it("disables Split while the playhead sits outside the selected clip", () => {@@ -740,7 +741,7 @@ describe("project workspace timecode", () => {generationJobs: [{ ...fresh.generationJobs[0], referenceIds: ["ref-text"] }],});const { container } = render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange: () => undefined, onOpenTimeline: () => undefined, selectedJobId: fresh.generationJobs[0].id }));- expect(document.querySelector(".job-refs")!.textContent).toContain("The text definition is written into this shot’s prompt.");+ expect(document.querySelector(".job-refs")!.textContent).toContain("The text definition is written into this scene’s prompt.");// The composer hint says the same thing about the same references. Scoping// this to .job-refs hid a second copy of the claim that was still wrong.expect(container.querySelector(".generation-composer__hint")!.textContent).toContain("The text definition is written into the prompt.");@@ -806,94 +807,220 @@ describe("project workspace timecode", () => {expect(screenText).toContain("Not described yet — the picture is sent, but nothing tells the engine what to keep.");});- /** Opens one tag group inside ONE picker and ticks one of its options. The- * generator shows two pickers at once — the shot being written and the shot- * selected — so every query here has to say which. */- function pickTag(scope: HTMLElement, group: string, option: string) {- fireEvent.click(within(scope).getByRole("button", { name: new RegExp(`^${group}`) }));- fireEvent.click(within(scope).getByRole("button", { name: option, pressed: false }));+ /** 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+ * every term the vocabulary holds. */+ function addSetting(shotNumber: number, group: string, value: string) {+ fireEvent.change(screen.getByRole("combobox", { name: `Add a setting to shot ${shotNumber}` }), { target: { value: group } });+ fireEvent.change(screen.getByRole("combobox", { name: new RegExp(`^Value for .* on shot ${shotNumber}$`) }), { target: { value } });}- it("calls the authoring section “Describe the shot”, on a new shot and an old one", () => {- const fresh = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });- // With a shot selected this heading used to rename itself to "Write another- // shot", which read as a footnote to the shot above rather than as the- // place shots are made.+ const lampProject = () => createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });++ it("calls the rail Scenes, drops the eyebrow, and offers no way back to the timeline from the header", () => {+ const fresh = lampProject();for (const config of [parseProjectConfig({ ...fresh, generationJobs: [] }), fresh]) {- const { unmount } = render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange: () => undefined, onOpenTimeline: () => undefined }));- expect(screen.getByRole("heading", { name: "Describe the shot" })).not.toBeNull();- expect(screen.queryByText("Write another shot")).toBeNull();- // And it says which surface authors a shot and which one edits one, so- // the dock at the bottom of the window is not mistaken for this.- expect(document.querySelector(".generation-composer__lede")!.textContent).toContain("changing a shot that already exists");+ const { container, unmount } = render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange: () => undefined, onOpenTimeline: () => undefined }));+ expect(screen.getByRole("complementary", { name: "Scenes" })).not.toBeNull();+ expect(container.querySelector(".generator-heading .eyebrow")).toBeNull();+ expect(screen.queryByRole("button", { name: "View timeline" })).toBeNull();+ // A new scene is still started from this page, and it says so.+ expect(screen.getByRole("heading", { name: "Start another scene" })).not.toBeNull();+ expect(document.querySelector(".generation-composer__lede")!.textContent).toContain("changing a scene that already exists");unmount();}});- it("builds a new shot from tags as well as prose, and shows the prompt first", () => {- localStorage.clear();- const config = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });+ it("splits a scene into three shots on the bar, each with its own line and cut", () => {+ const config = lampProject();const onChange = vi.fn();- const { container } = render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined }));- fireEvent.change(container.querySelector(".generation-composer textarea")!, { target: { value: "hands shaping wet clay on a spinning wheel" } });-- const composer = container.querySelector(".generation-composer") as HTMLElement;- pickTag(composer, "Camera movement", "Push in");- // Speed and amplitude only mean something once a movement exists, so they- // are offered only after one is chosen — the compiler drops them otherwise.- pickTag(composer, "Movement speed", "Slow");-- // The compiled prompt is on screen BEFORE anything is committed, and the- // words the user typed are still marked as theirs.- expect(composer.querySelector(".compiled-prompt__text")!.textContent).toContain("Camera movement: push in, slow speed.");- expect(composer.querySelector(".prompt-part--brief")!.textContent).toBe("hands shaping wet clay on a spinning wheel");- expect([...composer.querySelectorAll(".prompt-part--tag")].map((part) => part.textContent)).toContain("push in, slow speed");- // The tag terms are NOT dressed up as the user's own writing.- expect(composer.querySelector(".prompt-part--brief")!.textContent).not.toContain("push in");+ const { rerender } = render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));++ // Two more shots, and the scene stretched to hold them.+ fireEvent.click(screen.getByRole("button", { name: "Add a shot" }));+ let next = onChange.mock.calls.at(-1)![0];+ expect(next.generationJobs[0].shots).toHaveLength(2);+ rerender(createElement(GeneratorView, { config: parseProjectConfig(next), folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));+ fireEvent.click(screen.getByRole("button", { name: "Add a shot" }));+ next = onChange.mock.calls.at(-1)![0];+ rerender(createElement(GeneratorView, { config: parseProjectConfig(next), folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));++ fireEvent.change(screen.getByRole("slider", { name: "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.+ for (const [shotNumber, startSeconds, line] of [[2, 3, "she stops at the doorway"], [3, 6.5, "the door opens"]] as const) {+ fireEvent.change(screen.getByRole("spinbutton", { name: `Shot ${shotNumber} starts at, in seconds` }), { target: { value: String(startSeconds) } });+ next = onChange.mock.calls.at(-1)![0];+ rerender(createElement(GeneratorView, { config: parseProjectConfig(next), folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));+ fireEvent.change(screen.getByRole("textbox", { name: `What happens in shot ${shotNumber}` }), { target: { value: line } });+ next = onChange.mock.calls.at(-1)![0];+ rerender(createElement(GeneratorView, { config: parseProjectConfig(next), folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));+ }- fireEvent.click(screen.getByRole("button", { name: /Save as a draft|Generate/ }));- const created = onChange.mock.calls[0][0].generationJobs[0];- expect(created.shotTags).toEqual({ cameraMovement: ["push-in"], cameraSpeed: ["slow"] });- expect(created.compiledPrompt).toContain("Camera movement: push in, slow speed.");- // The whole config still validates, so this is a shot that can be saved.- expect(parseProjectConfig(onChange.mock.calls[0][0])).toBeTruthy();+ const compiled = document.querySelector(".compiled-prompt__text")!.textContent!;+ expect(compiled).toContain("[Shot 1] Live-action, cinematic, A quiet product film.");+ expect(compiled).toContain("[Shot 2] (cut at 3s) she stops at the doorway.");+ expect(compiled).toContain("[Shot 3] (cut at 6.5s) the door opens");+ expect(compiled.indexOf("[Shot 2]")).toBeLessThan(compiled.indexOf("[Shot 3]"));+ // And the whole thing is still a project that can be saved.+ expect(parseProjectConfig(next)).toBeTruthy();+ });++ it("keeps the scene inside nought to fifteen seconds", () => {+ const config = lampProject();+ const onChange = vi.fn();+ 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;+ expect(length.min).toBe("0");+ expect(length.max).toBe("15");+ // The bound is enforced, not merely advertised: a hand-set value past the+ // end is clamped rather than persisted as a scene the schema refuses.+ fireEvent.change(length, { target: { value: "40" } });+ expect(onChange.mock.calls.at(-1)![0].generationJobs[0].durationSeconds).toBe(15);+ fireEvent.change(length, { target: { value: "-3" } });+ 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+ // rather than leaving a grey button.+ expect(screen.queryByText(/no frames to render/)).toBeNull();+ });++ it("adds a setting to one shot and takes it off again, without touching the other shot", () => {+ 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 }));+ addSetting(1, "cameraMovement", "push-in");+ let next = onChange.mock.calls.at(-1)![0];+ expect(next.generationJobs[0].shots[0].settings).toEqual({ cameraMovement: ["push-in"] });+ rerender(createElement(GeneratorView, { config: parseProjectConfig(next), folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));++ // Speed only means something once a movement exists, so it is refused until+ // then and offered afterwards — the compiler drops it otherwise.+ addSetting(1, "cameraSpeed", "slow");+ next = onChange.mock.calls.at(-1)![0];+ expect(next.generationJobs[0].shots[0].settings).toEqual({ cameraMovement: ["push-in"], cameraSpeed: ["slow"] });+ rerender(createElement(GeneratorView, { config: parseProjectConfig(next), folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));++ // The compiled prompt shows it immediately, with the term marked as the+ // user's choice rather than as their own prose.+ const prompt = document.querySelector(".compiled-prompt__text")!;+ expect(prompt.textContent).toContain("Camera movement: push in, slow speed.");+ expect([...document.querySelectorAll(".prompt-part--tag")].map((part) => part.textContent)).toContain("push in, slow speed");+ expect(document.querySelector(".prompt-part--brief")!.textContent).not.toContain("push in");++ fireEvent.click(screen.getByRole("button", { name: "Remove Camera movement: Push in from shot 1" }));+ expect(onChange.mock.calls.at(-1)![0].generationJobs[0].shots[0].settings).toEqual({ cameraSpeed: ["slow"] });});it("refuses movement speed until there is a movement for it to qualify", () => {- localStorage.clear();- const config = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });- const { container } = render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange: () => undefined, onOpenTimeline: () => undefined }));+ const config = lampProject();+ render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange: () => undefined, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));// Not merely disabled — it says why, the way every other blocked control on// this screen does.- const composer = container.querySelector(".generation-composer") as HTMLElement;- const speed = within(composer).getByRole("button", { name: /^Movement speed/ }) as HTMLButtonElement;+ const menu = screen.getByRole("combobox", { name: "Add a setting to shot 1" });+ const speed = within(menu).getByRole("option", { name: /^Movement speed/ }) as HTMLOptionElement;expect(speed.disabled).toBe(true);- expect(speed.textContent).toContain("Needs a camera movement first");+ expect(speed.textContent).toContain("needs a camera movement first");+ // The look belongs to the whole scene, so it is not offered per shot.+ expect(within(menu).queryByRole("option", { name: "Look" })).toBeNull();+ expect(screen.getByRole("combobox", { name: "The look of this scene" })).not.toBeNull();});- it("reopens an existing shot's tags so they can be adjusted", () => {- 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], shotTags: { lens: ["macro-lens"] } }] });+ it("reopens a scene written before scenes existed, with its tags on its one shot", () => {+ const fresh = lampProject();+ // The legacy shape: no shots, no length, tags on the job itself.+ const legacy = { ...fresh.generationJobs[0], shots: null, durationSeconds: null, shotTags: { lens: ["macro-lens"] } };+ const config = parseProjectConfig({ ...fresh, generationJobs: [legacy] });const onChange = vi.fn();- const { container } = render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));- // The saved tag is reported in the terms it puts in the prompt, not a- // paraphrase of them.- const shotTags = container.querySelector(".job-tags") as HTMLElement;- expect(screen.getByText("1 tag shapes this shot")).not.toBeNull();- expect(within(shotTags).getByRole("button", { name: /^Lens/ }).textContent).toContain("macro lens");- expect(container.querySelector(".compiled-prompt__text")!.textContent).toContain("macro lens, A quiet product film");+ render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));++ // One shot, holding the words and the tags the file already had.+ expect((screen.getByRole("textbox", { name: "What happens in shot 1" }) as HTMLTextAreaElement).value).toBe("A quiet product film");+ expect(screen.getByText("macro lens")).not.toBeNull();+ expect(screen.queryByRole("textbox", { name: "What happens in shot 2" })).toBeNull();+ 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();++ // The first edit moves the tags onto the shot, and clears the legacy copy+ // so the two can never disagree.+ addSetting(1, "lighting", "soft-light");+ const next = onChange.mock.calls.at(-1)![0].generationJobs[0];+ expect(next.shots[0].settings).toEqual({ lens: ["macro-lens"], lighting: ["soft-light"] });+ expect(next.shotTags).toBeNull();+ expect(parseProjectConfig(onChange.mock.calls.at(-1)![0])).toBeTruthy();+ });- pickTag(shotTags, "Lens", "Telephoto");- expect(onChange.mock.calls[0][0].generationJobs[0].shotTags).toEqual({ lens: ["telephoto-lens"] });+ it("locks a running scene, because the engine already has the prompt", () => {+ 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("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);+ expect((screen.getByRole("slider", { name: "Scene length in seconds" }) as HTMLInputElement).disabled).toBe(true);+ expect(screen.getByText(/It can be changed once it finishes/)).not.toBeNull();});- it("locks a running shot's tags, because the engine already has the prompt", () => {- 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: "generating", stage: "generating", progress: 0.4, shotTags: { lens: ["macro-lens"] } }] });- const { container } = render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange: () => undefined, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));- const shotTags = container.querySelector(".job-tags") as HTMLElement;- expect((within(shotTags).getByRole("button", { name: /^Lens/ }) as HTMLButtonElement).disabled).toBe(true);- expect(screen.getByText(/Its tags can be changed once it finishes/)).not.toBeNull();+ it("drops a reference into a line, cites it as a subject, and swaps it for another", () => {+ const fresh = lampProject();+ const createdAt = fresh.createdAt;+ const references = [+ { id: "ref-woman", kind: "text", name: "Red-haired woman", description: "Dark red hair, green canvas jacket.", content: "Dark red hair, green canvas jacket.", intendedUse: ["character"], createdAt },+ { id: "ref-street", kind: "text", name: "City street", description: "Brick warehouses, wet cobbles.", content: "Brick warehouses, wet cobbles.", intendedUse: ["location"], createdAt },+ ];+ const config = parseProjectConfig({ ...fresh, references, generationJobs: [{ ...fresh.generationJobs[0], shots: [{ id: "shot-a", startSeconds: 0, action: "" }], referenceIds: [] }] });+ const onChange = vi.fn();+ const render1 = render(createElement(GeneratorView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));+ const show = (next: ProjectConfig) => render1.rerender(createElement(GeneratorView, { config: parseProjectConfig(next), folderPath: "C:\\Ceramic Lamp", onChange, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));++ // Dragged out of the palette and dropped onto the line.+ const drop = (referenceId: string) => {+ const field = screen.getByRole("textbox", { name: "What happens in shot 1" });+ const event = createEvent.drop(field);+ Object.defineProperty(event, "dataTransfer", { value: { getData: (type: string) => type === REFERENCE_DRAG_TYPE ? referenceId : "", types: [REFERENCE_DRAG_TYPE] } });+ fireEvent(field, event);+ };+ drop("ref-woman");+ let next = onChange.mock.calls.at(-1)![0];+ // Writing it into the line is what binds it to the scene, which is what+ // gives it a subject number and a place in reference_paths.+ expect(next.generationJobs[0].referenceIds).toEqual(["ref-woman"]);+ show(next);++ fireEvent.change(screen.getByRole("textbox", { name: "What happens in shot 1" }), { target: { value: "[Reference 1] walks towards the camera on " } });+ next = onChange.mock.calls.at(-1)![0];+ show(next);+ drop("ref-street");+ next = onChange.mock.calls.at(-1)![0];+ expect(next.generationJobs[0].referenceIds).toEqual(["ref-woman", "ref-street"]);+ show(next);++ // What the user reads in the field is "Reference N"; what is stored is the+ // reference's id, so a rename or a reorder cannot re-point the sentence.+ expect((screen.getByRole("textbox", { name: "What happens in shot 1" }) as HTMLTextAreaElement).value)+ .toBe("[Reference 1] walks towards the camera on [Reference 2]");+ expect(next.generationJobs[0].shots[0].action).toBe("@[ref:ref-woman] walks towards the camera on @[ref:ref-street]");+ const compiled = () => document.querySelector(".compiled-prompt__text")!.textContent!;+ expect(compiled()).toContain("<Subject 1> walks towards the camera on <Subject 2>");+ expect(compiled()).not.toContain("@[ref:");+ // The citation is PolStudio's format, not something the user typed.+ expect([...document.querySelectorAll(".prompt-part--frame")].map((part) => part.textContent)).toContain("<Subject 1>");+ expect(document.querySelector(".prompt-part--brief")!.textContent).not.toContain("<Subject");++ // Clicking the first reference in the line offers every other one.+ const token = screen.getByRole("combobox", { name: "Reference 1 · Red-haired woman — choose another reference" });+ expect([...token.querySelectorAll("option")].map((option) => option.textContent)).toEqual([+ "Reference 1 · Red-haired woman", "Reference 2 · City street", "Take it out of the line",+ ]);+ fireEvent.change(token, { target: { value: "ref-street" } });+ next = onChange.mock.calls.at(-1)![0];+ show(next);+ expect(next.generationJobs[0].shots[0].action).toBe("@[ref:ref-street] walks towards the camera on @[ref:ref-street]");+ expect(compiled()).toContain("<Subject 2> walks towards the camera on <Subject 2>");});it("labels a cancelled preview as cancelled instead of queued", () => {diff --git a/src/components/workspace/GeneratorView.tsx b/src/components/workspace/GeneratorView.tsxindex 886286e..b0ee5e4 100644--- a/src/components/workspace/GeneratorView.tsx+++ b/src/components/workspace/GeneratorView.tsx@@ -1,10 +1,10 @@import { listen } from "@tauri-apps/api/event";-import { AlertCircle, Ban, Check, ChevronRight, Clock3, Film, Info, LoaderCircle, Play, Plus, RefreshCw, Sparkles, Square, WandSparkles, X } from "lucide-react";+import { AlertCircle, Ban, Check, ChevronRight, Clock3, Info, LoaderCircle, Play, Plus, RefreshCw, Sparkles, Square, WandSparkles, X } from "lucide-react";import { useEffect, useMemo, useRef, useState } from "react";import { isTauri } from "../../lib/persistence";-import { compileMiniMaxH3Prompt, compileMiniMaxH3PromptSegments, createDraftGenerationJob, STORY_TRACK_ID, isReferenceDescribed, isReferenceUsable, isVisualReference, projectItemPath, shotTagSelectionSchema, usableImageReferences, type GenerationJob, type ProjectAsset, type ProjectConfig, type ProjectReference, type TimelineClip, type TimelineTrack } from "../../lib/project";-import { countShotTags, hasCameraMovement, normalizeShotTagSelection, selectedShotTagOptions, SHOT_TAG_GROUPS, toggleShotTag, type ShotTagSelection } from "../../lib/shot-tags";+import { actionReferenceIds, compileGenerationJobPrompt, compileGenerationJobSegments, compileMiniMaxH3PromptSegments, createDraftGenerationJob, danglingReferenceTokens, sceneDurationSeconds, sceneShots, STORY_TRACK_ID, isReferenceDescribed, isReferenceUsable, isVisualReference, projectItemPath, usableImageReferences, type GenerationJob, type ProjectAsset, type ProjectConfig, type ProjectReference, type PromptSegment, type TimelineClip, type TimelineTrack } from "../../lib/project";import { cancelVidfabGeneration, enqueueVidfabGeneration, resolveVidfabPlan, type VidfabGenerationRequest, type VidfabStatus } from "../../lib/runtime";+import { SceneEditor } from "./SceneEditor";interface GeneratorViewProps {config: ProjectConfig;@@ -14,7 +14,7 @@ interface GeneratorViewProps {onOpenTimeline: () => void;selectedJobId?: string;/** Composer text, held by the parent. Switching tabs unmounts this view, and- * keeping the half-written shot in local state threw the user's own words+ * keeping the half-written scene in local state threw the user's own words* away — the one thing this app is not allowed to do. Optional so the view* still works standalone; it falls back to its own state. */draftPrompt?: string;@@ -28,17 +28,6 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, onconst [ownPrompt, setOwnPrompt] = useState("");const prompt = draftPrompt ?? ownPrompt;const setPrompt: (value: string) => void = onDraftPromptChange ?? setOwnPrompt;- /* The tags on the shot being written. They belong to the half-written shot,- not to the project, so they live outside the config until it is created —- but switching tabs unmounts this view, and dropping a dozen deliberate- choices on the way back is the same loss the composer text was rescued- from. Parked per project, exactly like the media panel's layout habit. */- const draftTagsKey = `polstudio.draft-shot-tags.v1:${config.id}`;- const [draftTags, setDraftTagsState] = useState<ShotTagSelection>(() => readDraftTags(draftTagsKey));- const setDraftTags = (next: ShotTagSelection) => {- setDraftTagsState(next);- writeDraftTags(draftTagsKey, next);- };const [planNotes, setPlanNotes] = useState<Record<string, string>>({});const composerRef = useRef<HTMLTextAreaElement | null>(null);const configRef = useRef(config);@@ -49,25 +38,27 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, onconst queued = jobs.filter((job) => job.status === "queued");const drafts = jobs.filter((job) => job.status === "draft");const completed = jobs.filter((job) => ["ready", "completed", "failed", "cancelled"].includes(job.status));- // Queued and generating shots have already been handed to the engine with+ // Queued and generating scenes have already been handed to the engine with// their references attached; re-binding now would change nothing about that// 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. compileMiniMaxH3Prompt 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- // shot when the compiled prompt never mentioned it.+ // 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]);- // The references a NEW shot would bind and the compiler would then keep. Both- // filters, or the hint promises a reference the prompt drops and a legacy- // audio-only one eats a binding slot a real reference should have had.+ // The references a NEW scene could cite. Both filters, or the hint promises a+ // reference the prompt drops and a legacy audio-only one looks available.const usableReferences = useMemo(() => config.references.filter((ref) => isReferenceUsable(ref) && isVisualReference(ref)),[config.references],);const runtimeReady = runtime?.state === "ready";- const submitLabel = runtimeReady ? "Generate this shot" : "Save as a draft";+ const submitLabel = runtimeReady ? "Generate this scene" : "Save as a draft";+ /* 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;useEffect(() => { if (selectedJobId) setSelectedId(selectedJobId); }, [selectedJobId]);@@ -75,20 +66,42 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, onconst current = configRef.current;onChange({ ...current, generationJobs: current.generationJobs.map((job) => job.id === id ? { ...job, ...updates } : job) });};++ /* An edit from the scene editor. Writing a reference into a line BINDS it to+ the scene, because binding is what gives it a <Subject N> and puts its+ picture 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 below is where that decision is made. */+ const updateScene = (job: GenerationJob, updates: Partial<GenerationJob>) => {+ const next: Partial<GenerationJob> = { ...updates, updatedAt: new Date().toISOString() };+ if (updates.shots) {+ const referenceIds = [...job.referenceIds];+ for (const shot of updates.shots) {+ for (const id of actionReferenceIds(shot.action)) {+ if (!referenceIds.includes(id) && config.references.some((reference) => reference.id === id)) referenceIds.push(id);+ }+ }+ next.referenceIds = referenceIds;+ }+ updateJob(job.id, next);+ };+const requestFor = (job: GenerationJob): VidfabGenerationRequest => {- // Only the references actually bound to this job, in list order. The same- // ordered list drives the <Picture N> numbering inside the compiled prompt,- // because vidfab.rs adds reference_paths sequentially — so array index 0- // must be the asset the prompt calls <Picture 1>.+ // Only the references actually bound to this scene, in list order. The same+ // ordered list drives the <Subject N> / <Picture N> numbering inside the+ // compiled prompt, because vidfab.rs adds reference_paths sequentially — so+ // array index 0 must be the asset the prompt calls <Picture 1>.const bound = configRef.current.references.filter((reference) => job.referenceIds.includes(reference.id));return {jobId: job.id,// Recompiled from current state so edits to a bound reference or a- // retagged shot reach the engine, rather than sending a prompt frozen at+ // retimed shot reach the engine, rather than sending a prompt frozen at// draft-creation time. This is the ONE string vidfab is given, and it is// the same string the compiled-prompt panel shows.- prompt: compileMiniMaxH3Prompt(job.creativeBrief, bound, job.shotTags ?? null),- frames: Math.round(6 * config.settings.frameRate),+ prompt: compileGenerationJobPrompt(job, bound),+ // The scene's own length, not a fixed six seconds.+ frames: Math.round(sceneDurationSeconds(job) * config.settings.frameRate),steps: 50,seed: 482091,aspectRatio: config.settings.aspectRatio,@@ -129,22 +142,20 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on};const createJob = async () => {- // Never synthesise a prompt: a shot must only ever describe what the user+ // Never synthesise a prompt: a scene must only ever describe what the user// actually typed, or it gets read back to them as their own request.const cleanPrompt = prompt.trim();if (!cleanPrompt) return;- // Same pair the compiler applies, so a bound reference is always one that- // actually reaches the prompt.- const bound = config.references.filter((ref) => isReferenceUsable(ref) && isVisualReference(ref)).slice(0, 2);- const draft = createDraftGenerationJob(cleanPrompt, { referenceIds: bound.map((ref) => ref.id), references: bound, shotTags: draftTags });+ // Nothing is auto-bound: which references steer a scene is now decided by+ // writing them into a line, or by the checkbox list. Binding the first two+ // in the library decided that for the user, and often for a scene that+ // never mentioned either of them.+ const draft = createDraftGenerationJob(cleanPrompt);const job: GenerationJob = runtimeReady ? { ...draft, status: "queued" } : draft;const next = { ...config, generationJobs: [job, ...jobs] };onChange(next);setSelectedId(job.id);setPrompt("");- // The tags moved into the shot, so the composer starts clean for the next- // one rather than silently applying the last shot's camera to it.- setDraftTags({});try {const request = requestFor(job);const plan = await resolveVidfabPlan(request, next);@@ -165,8 +176,9 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, onconst 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: 6_000, createdAt: now };+ 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 madea renamed first video track invisible here — the next insert built asecond one beside it. The name check is the fallback for projects saved@@ -176,14 +188,14 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, onconst story: TimelineTrack = existingStory ?? { id: STORY_TRACK_ID, kind: "video", name: "Track 1, Video", 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 ?? 6_000, sourceStartMs: 0, label: job.title, color: "#4f6ba8", status: "generated" };+ 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();};- // "Keep drafting other shots" has to be a real control, not advice, so the- // ready state always has somewhere to go.+ // "Start another scene" has to be a real control, not advice, so the ready+ // state always has somewhere to go.const focusComposer = () => {const node = composerRef.current;if (!node) return;@@ -192,8 +204,9 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on};/* Binding order does not matter: requestFor and the compiler both read- config.references in list order and keep whatever this job names, so the- <Picture N> numbering stays in lockstep however the boxes are ticked. */+ 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)@@ -207,28 +220,25 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on};return <div className="generator-view">- <aside className="queue-panel" aria-label="Shots">+ <aside className="queue-panel" aria-label="Scenes"><div className="queue-panel__title"><div>- <span>Shots</span>+ <span>Scenes</span><b>{queueSummary(active.length, queued.length, jobs.length)}</b></div>- {/* A shot is its words, and PolStudio never writes those for anyone —- so this opens the composer rather than adding an empty job to the- list. Same destination as "Describe another shot" below. */}- <button className="queue-panel__new" onClick={focusComposer} aria-label="Describe a new shot" title="Describe a new shot"><Plus size={18} /></button>+ {/* A scene is its words, and PolStudio never writes those for anyone —+ so this opens the composer rather than adding an empty scene to the+ list. Same destination as "Start another scene" below. */}+ <button className="queue-panel__new" onClick={focusComposer} aria-label="Describe a new scene" title="Describe a new scene"><Plus size={18} /></button></div><div className="queue-panel__scroll"><QueueGroup title="Rendering now" jobs={active} selectedId={selectedId} onSelect={setSelectedId} /><QueueGroup title="Waiting to render" jobs={queued} selectedId={selectedId} onSelect={setSelectedId} /><QueueGroup title="Drafts" jobs={drafts} selectedId={selectedId} onSelect={setSelectedId} /><QueueGroup title="Already run" jobs={completed} selectedId={selectedId} onSelect={setSelectedId} />- {jobs.length === 0 && <p className="queue-empty">No shots yet. Describe one in the box on the right and it will appear here.</p>}+ {jobs.length === 0 && <p className="queue-empty">No scenes yet. Describe one in the box on the right and it will appear here.</p>}</div>- {/* One line: the headline already IS the status. The paragraph under it- restated the same fact in a second sentence, and the "frames, not a- video file" limit is still disclosed in the composer, at the point- where someone actually commits to a render. */}+ {/* One line: the headline already IS the status. */}<div className={`queue-runtime queue-runtime--${runtime?.state ?? "checking"}`}><span className="queue-runtime__state"><i /> {runtimeHeadline(runtime)}</span></div>@@ -237,26 +247,34 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on<main className="generator-main"><header className="generator-heading"><div>- <span className="eyebrow">Create shots</span><h1>Generator</h1>- <p>Describe a shot in your own words and PolStudio turns it into a scene you can keep editing. You always see what the video engine can actually do before anything starts.</p>+ <p>A scene is up to fifteen seconds long and holds as many shots as you split it into. Write what happens in each one; PolStudio turns the whole scene into a single MiniMax H3 prompt you can read before anything is sent.</p></div>- <button className="secondary-button" onClick={onOpenTimeline}><Film size={16} /> View timeline</button></header>- {/* The draft made from the user's own words leads the screen: they- just described their video, so the next step is running that shot,- not describing it again in a different unit. */}{selected && <section className="job-detail"><div className="job-detail__visual">- {/* A labelled placeholder, never invented art — the same rule the scene- thumb, media thumb and reference cards follow. PolStudio cannot- display real frames yet, so it shows none. */}- <div className={`generation-preview generation-preview--${selected.status}`}>- {selected.status === "generating" && <span className="generation-scanner" aria-hidden="true" />}- <span className="preview-status">{previewStatus(selected)}</span>- <p className="generation-preview__caption">{previewCaption(selected)}</p>- </div>+ {/* THE control on this screen: the lines the user writes, the shots+ they are split into, and the settings hung off each one. */}+ <SceneEditor+ key={selected.id}+ job={selected}+ references={config.references}+ disabled={refsLocked}+ onChange={(updates) => updateScene(selected, updates)}+ />+ {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>}++ {/* 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."}+ />+<div className="job-progress-block"><div className="job-progress-block__head"><b>{progressTitle(selected)}</b>@@ -277,17 +295,6 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on</li></ol></div>- {/* Every setting on this shot collapsed into the one string vidfab is- given. Recompiled from what the shot holds right now, so it cannot- disagree with what the next run sends. */}- <CompiledPrompt- creativeBrief={selected.creativeBrief}- references={boundRefs}- shotTags={selected.shotTags ?? null}- caption={refsLocked- ? "This is the prompt the engine was given for the run in progress."- : "Rebuilt from this shot’s words, tags and references every time it is sent."}- /></div><aside className="job-detail__info">@@ -295,36 +302,27 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on<span className={`status-icon status-icon--${selected.status}`}>{statusIcon(selected.status)}</span><div><span className="job-title__badge">{STATUS_BADGE[selected.status]}</span>- {/* The title is the one part of a shot PolStudio writes for the+ {/* The title is the one part of a scene PolStudio writes for theuser — taken from their first words — so it has to be theirsto change. Blanking it falls back rather than saving a- nameless shot the schema would reject. */}+ nameless scene the schema would reject. */}<h2><inputclassName="job-title__name"value={selected.title}aria-label={`Rename ${selected.title}`}- title="Rename this shot"- onChange={(event) => updateJob(selected.id, { title: event.target.value || "Untitled shot", updatedAt: new Date().toISOString() })}+ title="Rename this scene"+ onChange={(event) => updateJob(selected.id, { title: event.target.value || "Untitled scene", updatedAt: new Date().toISOString() })}/></h2></div></div>- <div className="job-prompt">- <span>What you asked for</span>- <p>{selected.creativeBrief}</p>- </div>-- {/* Tags are stored with the shot, so an existing one can be reopened- and retagged rather than rewritten from scratch. */}- <div className="job-tags">- <span>{shotTagSummary(selected.shotTags ?? null)}</span>- <ShotTagPicker- idPrefix={selected.id}- value={selected.shotTags ?? {}}- disabled={refsLocked}- onChange={(next) => updateJob(selected.id, { shotTags: normalizeShotTagSelection(next), updatedAt: new Date().toISOString() })}- />- {refsLocked && <p className="job-refs__empty">This shot is already with the engine. Its tags can be changed once it finishes, and the next run will use them.</p>}+ {/* A labelled placeholder, never invented art — the same rule the+ scene thumb, media thumb and reference cards follow. PolStudio+ cannot display real frames yet, so it shows none. */}+ <div className={`generation-preview generation-preview--${selected.status}`}>+ {selected.status === "generating" && <span className="generation-scanner" aria-hidden="true" />}+ <span className="preview-status">{previewStatus(selected)}</span>+ <p className="generation-preview__caption">{previewCaption(selected)}</p></div>{(planNotes[selected.id] || selected.error) && <div className="job-runtime-note">@@ -335,18 +333,19 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on<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, {sceneShots(selected).length === 1 ? "one shot" : `${sceneShots(selected).length} shots`}</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>- <div><dt>Video file</dt><dd>{selected.outputRelativePath ? "Ready to use in your edit" : "Not created yet"}</dd></div></dl><div className="job-refs">- <span>{promptRefs.length === 0 ? "No references used by this shot" : promptRefs.length === 1 ? "1 reference guides this shot" : `${promptRefs.length} references guide this shot`}</span>+ <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 shot is the user's decision, and until now the two that were- bound when the draft was written were the two it kept forever.- A bound reference the prompt skips stays listed with its reason —- hiding it would leave the user wondering where it went. */}+ 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, index) => {const bound = selected.referenceIds.includes(ref.id);const skipped = skipReason(ref);@@ -369,32 +368,34 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on: 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 shot.</p>}+ {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>}{/* The request was already handed to the engine, so a change herewould say it steered a render it never touched. */}- {refsLocked && <p className="job-refs__empty">This shot is already with the engine. Its references can be changed once it finishes, and the next run will use them.</p>}+ {refsLocked && <p className="job-refs__empty">This scene is already with the engine. Its references can be changed once it finishes, and the next run will use them.</p>}{promptRefs.length === 0? <p className="job-refs__empty">The video engine only follows the words above.</p>: <p className="job-refs__empty">{referenceRouting(promptRefs)} The tags are your own notes and don’t change what is sent.</p>}</div><div className="job-actions">- {selected.status === "generating" && <button className="danger-button" onClick={() => cancelJob(selected)}><Square size={14} /> Stop this shot</button>}+ {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} onClick={() => void startDraft(selected)}>- <WandSparkles size={15} /> {runtimeReady ? (jobs.length === 1 ? "Generate your first shot" : "Generate this shot") : "Can’t generate yet"}+ <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} onClick={() => void prepareOrRetry(selected)}>- <RefreshCw size={15} /> {runtimeReady ? "Try this shot again" : "Can’t try again yet"}+ <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 shot again.</p>}+ {!runtimeReady && <p className="job-actions__note">PolStudio needs a working video engine before it can run this scene again.</p>}</>}{selected.status === "ready" && <>@@ -403,11 +404,11 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on<p>The frames and sound were rendered and are held in memory, but PolStudio can’t package them into a video file yet — that step isn’t built. Nothing was written to your project folder.</p></div><div className="job-actions__choices">- <button className="primary-button" disabled={!runtimeReady} onClick={() => void prepareOrRetry(selected)}>- <RefreshCw size={15} /> {runtimeReady ? "Run this shot again" : "Can’t run it again yet"}+ <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><button className="secondary-button" onClick={focusComposer}>- <Sparkles size={15} /> Describe another shot+ <Sparkles size={15} /> Start another scene</button></div></>}@@ -417,8 +418,8 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on{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} onClick={() => void prepareOrRetry(selected)}>- <RefreshCw size={15} /> {runtimeReady ? "Run this shot again" : "Can’t run it again yet"}+ <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 saving a video file, so there is nothing to add to your edit.</p></>}@@ -426,17 +427,15 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on</aside></section>}- {/* Always here, and always called the same thing. It used to rename- itself to "Write another shot" the moment a shot existed, which read- as a footnote to the shot above rather than as the place shots are- made. This is where a shot is authored; the dock along the bottom of- the window changes one that already exists. */}- <section className="generation-composer" aria-labelledby="describe-the-shot">+ {/* Where a NEW scene is started. The scene above is where one is written;+ this is only the door onto the next one, which is why it is one line+ and sits at the foot of the page. */}+ <section className="generation-composer" aria-labelledby="start-another-scene"><div className="generation-composer__head">- <h2 className="generation-composer__label" id="describe-the-shot"><Sparkles size={17} /> Describe the shot</h2>+ <h2 className="generation-composer__label" id="start-another-scene"><Sparkles size={17} /> Start another scene</h2><p className="generation-composer__lede">- Write what happens in your own words, then pick the camera, light and mood from MiniMax H3’s own vocabulary.- New shots are made here. The prompt bar along the bottom of the window is for changing a shot that already exists — it doesn’t start one.+ One line is enough to open a scene — it becomes its first shot, and you can split the scene and add more above.+ The prompt bar along the bottom of the window is for changing a scene that already exists — it doesn’t start one.</p></div><label className="generation-composer__field">@@ -448,27 +447,21 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, onplaceholder="Example: hands shaping wet clay on a spinning wheel, the wheel slowing as the rim thins."/></label>- <ShotTagPicker idPrefix="new-shot" value={draftTags} onChange={setDraftTags} />{/* Visible before the button is ever pressed: the exact words that go- to the engine, with the user's own prose marked apart from the terms- their tags contributed. */}+ to the engine, with the user's own prose marked apart from the+ format PolStudio adds around it. */}{prompt.trim().length > 0 && <CompiledPrompt- creativeBrief={prompt}- references={usableReferences.slice(0, 2)}- shotTags={draftTags}- caption={`Nothing is sent until you choose “${submitLabel}”.`}+ segments={compileMiniMaxH3PromptSegments(prompt, [])}+ caption={`Nothing is sent until you choose “${submitLabel}”. A new scene starts with no references; drag one into a line once it exists.`}/>}<div className="generation-composer__foot"><div className="generation-settings">- <span className="generation-settings__lead">Every shot is made as</span>+ <span className="generation-settings__lead">A new scene is made as</span><span className="setting-chip"><em>Length</em><b>6 seconds</b></span><span className="setting-chip"><em>Shape</em><b>{config.settings.aspectRatio}</b></span><span className="setting-chip"><em>Size</em><b>{config.settings.resolution.toUpperCase()}</b></span><span className="setting-chip"><em>Model</em><b>MiniMax H3</b></span></div>- {/* Primary whether or not a shot is already selected: this is the- authoring surface, and demoting it the moment one shot existed- made it look like an afterthought to the shot above. */}<button className="primary-button generation-composer__submit" onClick={() => void createJob()} disabled={!prompt.trim()}><WandSparkles size={17} /> {submitLabel}</button>@@ -476,121 +469,66 @@ export function GeneratorView({ config, folderPath, runtime = null, onChange, on{/* Disclosed at the point of commitment, not after an expensive run. */}{runtimeReady && <p className="generation-composer__limit"><Info size={16} />- <span>A finished shot renders frames into memory. PolStudio can’t save them as a video file yet, so nothing lands in your project folder and there is nothing to add to the timeline.</span>+ <span>A finished scene renders frames into memory. PolStudio can’t save them as a video file yet, so nothing lands in your project folder and there is nothing to add to the timeline.</span></p>}<p className="generation-composer__hint">{runtimeReady- ? "Shots render one at a time, so a new shot joins the queue behind anything already running."- : "Nothing renders on this computer yet, so your shot is saved as a draft you can run later."}+ ? "Scenes render one at a time, so a new scene joins the queue behind anything already running."+ : "Nothing renders on this computer yet, so your scene is saved as a draft you can run later."}{/* Images are sent as real assets (referencePaths) AND cited as<Picture N>; text definitions reach the engine only as proseinside <Subject N>. Say exactly that — no more, and only about the- references actually in hand: the same referenceRouting the shot+ references actually in hand: the same referenceRouting the scenepanel uses, so the two places cannot drift apart. */}{usableReferences.length > 0- ? ` It will use ${usableReferences.length === 1 ? "your reference" : `the first ${Math.min(2, usableReferences.length)} of your ${usableReferences.length} references`}. ${referenceRouting(usableReferences.slice(0, 2), "the prompt")}`+ ? ` ${usableReferences.length === 1 ? "Your reference is" : `Your ${usableReferences.length} references are`} used by a scene once you write ${usableReferences.length === 1 ? "it" : "one"} into one of its lines. ${referenceRouting(usableReferences, "the prompt")}`: ""}</p></section>{!selected && <div className="job-empty"><span className="job-empty__icon"><Sparkles size={26} /></span>- <h2>Start with one shot</h2>- <p>Write what should happen on screen in the box above — who or what is in frame, what they do, the sound. Then choose “{submitLabel}”.</p>+ <h2>Start with one scene</h2>+ <p>Write what should happen on screen in the box above — who or what is in frame, what they do. Then choose “{submitLabel}”.</p><ul className="job-empty__tips">- <li>One moment per shot works better than a whole scene.</li>- <li>The camera, the light and the mood have tags above, in the video model’s own words.</li>+ <li>A scene can be up to 15 seconds and split into as many shots as you like.</li>+ <li>Each shot gets its own line, its own start time and its own settings.</li>+ <li>Drag a reference into a line and the prompt cites it as a subject.</li><li>You can read the finished prompt before anything is sent.</li>- <li>Every shot stays editable, so you can rewrite and run it again.</li></ul></div>}</main></div>;}-/* One accordion row per group in the taxonomy. All eleven groups open at once- would be ninety-odd chips before the user has typed a word, so a row shows- what it holds and opens on demand — and a row with choices in it says which,- using the exact terms those choices put in the prompt.-- The vocabulary is never spelled here: every label and every term comes from- src/lib/shot-tags.ts, so this component cannot invent a synonym. */-function ShotTagPicker({ idPrefix, value, onChange, disabled = false }: {- idPrefix: string;- value: ShotTagSelection;- onChange: (next: ShotTagSelection) => void;- disabled?: boolean;-}) {- const [openGroup, setOpenGroup] = useState<string | null>(null);- const movementChosen = hasCameraMovement(value);- return <div className="shot-tags">- <p className="shot-tags__lead">- {countShotTags(value) === 0- ? "Optional. Anything you tag is added to the prompt in MiniMax H3’s own words, next to yours."- : `${countShotTags(value)} ${countShotTags(value) === 1 ? "tag" : "tags"} — each one adds its term to the prompt below.`}- </p>- {SHOT_TAG_GROUPS.map((group) => {- const chosen = value[group.id] ?? [];- // Speed and amplitude qualify a movement. With none chosen the compiler- // leaves them out, so offering them would promise something the prompt- // does not do.- const blocked = Boolean(group.requiresMovement) && !movementChosen;- const open = openGroup === group.id;- const panelId = `${idPrefix}-${group.id}-panel`;- const terms = group.options.filter((option) => chosen.includes(option.id)).map((option) => option.term);- return <div key={group.id} className={`shot-tag-group ${open ? "shot-tag-group--open" : ""} ${blocked ? "shot-tag-group--blocked" : ""}`}>- <button- type="button"- className="shot-tag-group__head"- aria-expanded={open}- aria-controls={panelId}- disabled={disabled || blocked}- onClick={() => setOpenGroup(open ? null : group.id)}- >- <b>{group.label}</b>- <span>{blocked ? "Needs a camera movement first" : terms.length > 0 ? terms.join(", ") : "None"}</span>- <ChevronRight size={16} />- </button>- {open && <div className="shot-tag-group__body" id={panelId}>- <p className="shot-tag-group__help">{group.help} {group.multiple ? "Choose as many as you like." : "One at a time."}</p>- <div className="shot-tag-group__options">- {group.options.map((option) => {- const on = chosen.includes(option.id);- return <button- key={option.id}- type="button"- className={`shot-tag ${on ? "shot-tag--on" : ""}`}- aria-pressed={on}- disabled={disabled}- title={`Puts “${option.term}” in the prompt`}- onClick={() => onChange(toggleShotTag(value, group.id, option.id))}- >{option.label}</button>;- })}- </div>- </div>}- </div>;- })}- </div>;+/** Why this scene cannot be handed to the engine, in the user's words, or null.+ * Each one is a real state of the scene, not a policy: a scene with no words+ * has nothing to render, a scene of no length is no frames at all, and a name+ * the prompt cannot cite would be silently dropped from the middle of a line. */+function sendBlocker(job: GenerationJob, references: ProjectReference[]): string | null {+ const shots = sceneShots(job);+ if (shots.every((shot) => shot.action.trim().length === 0)) {+ return "Write what happens in at least one shot before this scene can be generated.";+ }+ if (sceneDurationSeconds(job) <= 0) {+ return "This scene is nought seconds long, so there are no frames to render. Give it a length first.";+ }+ const dangling = danglingReferenceTokens(shots, references);+ if (dangling.length > 0) {+ return "A reference named in one of the lines can no longer be used, and would be left out of the prompt. Swap it for another one or take it out of the line first.";+ }+ return null;}/* The compiled prompt, shown before anything is sent and coloured by who wrotewhich part. The segments come from the compiler itself, so this panel is thestring vidfab receives — not a re-rendering of it that could drift. */-function CompiledPrompt({ creativeBrief, references, shotTags, caption }: {- creativeBrief: string;- references: ProjectReference[];- shotTags: ShotTagSelection | null;- caption: string;-}) {- const segments = useMemo(- () => compileMiniMaxH3PromptSegments(creativeBrief, references, shotTags),- [creativeBrief, references, shotTags],- );+function CompiledPrompt({ segments, caption }: { segments: PromptSegment[]; caption: string }) {return <section className="compiled-prompt" aria-label="The compiled MiniMax H3 prompt">- <span className="compiled-prompt__title">The prompt this shot becomes</span>+ <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 tags</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) =>@@ -599,38 +537,6 @@ function CompiledPrompt({ creativeBrief, references, shotTags, caption }: {</section>;}-/* Counts only what this build can turn into a term — a tag id saved by a newer- build is kept in the file but has no words here, so claiming it is in the- prompt would be a claim about something that isn't. */-const shotTagSummary = (tags: ShotTagSelection | null): string => {- const chosen = selectedShotTagOptions(tags);- if (chosen.length === 0) return "No tags on this shot";- return chosen.length === 1 ? "1 tag shapes this shot" : `${chosen.length} tags shape this shot`;-};--/* The half-written shot's tags, parked per project. Anything unreadable is- treated as no tags rather than thrown at the user: this is a convenience- store, and nothing in it is the only copy of anything. */-const readDraftTags = (key: string): ShotTagSelection => {- try {- const stored = localStorage.getItem(key);- if (!stored) return {};- const parsed = shotTagSelectionSchema.safeParse(JSON.parse(stored));- return parsed.success ? parsed.data : {};- } catch {- return {};- }-};--const writeDraftTags = (key: string, tags: ShotTagSelection) => {- try {- if (Object.keys(tags).length === 0) localStorage.removeItem(key);- else localStorage.setItem(key, JSON.stringify(tags));- } catch {- /* A full or blocked store costs the parked copy, nothing on screen. */- }-};-/* The rail sits before the <h1> in the DOM, so its group titles are labelledgroups rather than headings — otherwise the document outline would startmid-tree with an <h3>. */@@ -652,9 +558,9 @@ function QueueGroup({ title, jobs, selectedId, onSelect }: { title: string; jobs}/* Only claim the route the bound references actually take. Saying "images are- sent … text definitions are written into the prompt" for a shot that has only+ sent … text definitions are written into the prompt" for a scene that has onlyone of the two describes something that isn't happening. */-const referenceRouting = (references: ProjectReference[], prompt = "this shot’s prompt"): string => {+const referenceRouting = (references: ProjectReference[], prompt = "this scene’s prompt"): string => {const hasImage = references.some((reference) => reference.kind === "image");const hasText = references.some((reference) => reference.kind !== "image");if (hasImage && hasText) return `Images are sent to the video engine as reference assets; text definitions are written into ${prompt}.`;@@ -666,11 +572,11 @@ const referenceRouting = (references: ProjectReference[], prompt = "this shot’: `The text definitions are written into ${prompt}.`;};-/* Why a reference that is bound to this shot never reaches its prompt, or null+/* Why a reference that is bound to this scene never reaches its prompt, or nullwhen it does. The wording mirrors the References card so the two screensdescribe the same state in the same words. */const skipReason = (reference: ProjectReference): string | null => {- if (!isReferenceUsable(reference)) return "Not described yet — not used by this shot";+ 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;};@@ -705,16 +611,18 @@ const queueSummary = (active: number, waiting: number, total: number) => {if (total === 0) return "Nothing here yet";if (active > 0) return `${active} rendering · ${waiting} waiting`;if (waiting > 0) return `${waiting} waiting to render`;- return total === 1 ? "1 shot" : `${total} shots`;+ return total === 1 ? "1 scene" : `${total} scenes`;};const queueLine = (job: GenerationJob) => {+ const shots = sceneShots(job).length;+ const shape = `${sceneDurationSeconds(job).toFixed(1)}s · ${shots === 1 ? "1 shot" : `${shots} shots`}`;switch (job.status) {case "generating": return `Rendering · ${Math.round(job.progress * 100)}%`;case "queued": return "Waiting its turn";- case "draft": return "Draft — not started";+ case "draft": return `Draft — ${shape}`;case "ready": return "Frames rendered · no video file";- case "completed": return job.outputRelativePath ? "Ready to use · 6 seconds" : "Finished with no file";+ case "completed": return job.outputRelativePath ? `Ready to use · ${shape}` : "Finished with no file";case "failed": return "Didn’t finish";case "cancelled": return "Cancelled";}@@ -737,7 +645,7 @@ const progressTitle = (job: GenerationJob) => {const stageCopy = (job: GenerationJob) => {switch (job.status) {case "generating": return "The video engine is building the motion and the sound.";- case "queued": return "Waiting for the shot ahead of it to finish.";+ case "queued": return "Waiting for the scene ahead of it to finish.";case "draft": return "Saved with your project. Nothing has been rendered yet.";case "ready": return "The frames and sound exist in memory. PolStudio can’t package them into a video file yet.";case "completed": return job.outputRelativePath ? "Saved in your project and ready to drop into the timeline." : "This run ended without saving a video file.";@@ -763,7 +671,7 @@ const previewStatus = (job: GenerationJob) => {const previewCaption = (job: GenerationJob): string => {switch (job.status) {case "generating": return "Frames are being built now. PolStudio can’t show them while they are still in memory.";- case "queued": return "This shot hasn’t started, so there is no picture to show.";+ case "queued": return "This scene hasn’t started, so there is no picture to show.";case "draft": return "Nothing has been rendered, so there is no picture to show.";case "ready": return "The frames exist in memory only. PolStudio can’t display or save them yet.";case "completed": return job.outputRelativePath ? "A video file was saved. Open it in the timeline to watch it." : "This run ended without a video file, so there is no picture to show.";@@ -782,4 +690,3 @@ const runtimeHeadline = (runtime: VidfabStatus | null) => {case "incompatible": return "Video engine doesn’t match";}};-diff --git a/src/components/workspace/ReferencesView.tsx b/src/components/workspace/ReferencesView.tsxindex 435d7d8..ac1cfb1 100644--- a/src/components/workspace/ReferencesView.tsx+++ b/src/components/workspace/ReferencesView.tsx@@ -67,9 +67,8 @@ export function ReferencesView({ config, folderPath, onChange }: { config: Projereturn <div className="references-view"><header className="references-heading"><div>- <span className="eyebrow">Consistency library</span><h1>References</h1>- <p>Keep the people, places, products, and visual rules for this project in one place. Each new shot uses the first two it can use from this list.</p>+ <p>Keep the people, places, products, and visual rules for this project in one place. A scene uses one once you drag it into a shot’s line in the generator.</p></div><div><button className="secondary-button" onClick={() => addTextReference()}><FileText size={16} /> New definition</button>diff --git a/src/components/workspace/SceneEditor.tsx b/src/components/workspace/SceneEditor.tsxnew file mode 100644index 0000000..e8db1fc--- /dev/null+++ b/src/components/workspace/SceneEditor.tsx@@ -0,0 +1,641 @@+import { Plus, Trash2, X } from "lucide-react";+import { useCallback, useMemo, useRef, useState } from "react";+import {+ actionReferenceIds,+ danglingReferenceTokens,+ isReferenceUsable,+ isVisualReference,+ normalizeSceneShots,+ referenceToken,+ sceneBriefText,+ sceneDurationSeconds,+ sceneShots,+ splitActionText,+ SCENE_MAX_SECONDS,+ SCENE_MIN_SECONDS,+ type GenerationJob,+ type ProjectReference,+ type SceneShot,+} from "../../lib/project";+import {+ hasCameraMovement,+ normalizeShotTagSelection,+ selectedShotTagOptions,+ shotTagGroup,+ toggleShotTag,+ SHOT_TAG_GROUPS,+ type ShotTagSelection,+} from "../../lib/shot-tags";++/** What a reference chip carries when it is dragged into a shot's line. A+ * private type, so a file dragged in from the desktop is never mistaken for+ * one — the drop handler checks for it before it touches the text. */+export const REFERENCE_DRAG_TYPE = "application/x-polstudio-reference";++/** The step the length slider and the cut handles move in. Half a second is the+ * finest cut the timestamp format prints exactly (`formatSceneSeconds`), so+ * nothing here can set a time the prompt then rounds behind the user's back. */+const STEP_SECONDS = 0.5;++const seconds = (value: number): string => `${value.toFixed(1)}s`;++interface SceneEditorProps {+ job: GenerationJob;+ /** Every reference in the project. Any of them can be dropped into a line;+ * doing so binds it to the scene, which is what gives it a number. */+ references: ProjectReference[];+ /** True once the scene is with the engine: it already has the prompt, so an+ * edit now would change nothing about that run while claiming otherwise. */+ disabled: boolean;+ onChange: (updates: Partial<GenerationJob>) => void;+}++export function SceneEditor({ job, references, disabled, onChange }: SceneEditorProps) {+ const shots = useMemo(() => sceneShots(job), [job]);+ const duration = sceneDurationSeconds(job);+ /* Everything that COULD be cited: the same filter pair the compiler applies,+ over the whole project. See the lockstep note on `usableImageReferences`. */+ const citable = useMemo(+ () => references.filter((reference) => isReferenceUsable(reference) && isVisualReference(reference)),+ [references],+ );+ /* And everything this scene actually cites, in the order the compiler numbers+ it: `boundRefs` in GeneratorView is `config.references` filtered by this+ scene's ids, so PROJECT order — not the order boxes were ticked — decides+ which reference is <Subject 1>. "Reference N" on screen is that number and+ nothing else, which is the whole point of numbering it here. */+ const numbered = useMemo(+ () => citable.filter((reference) => job.referenceIds.includes(reference.id)),+ [citable, job.referenceIds],+ );+ /* Numbering for the text. The cited references come first; anything a line+ still names but the prompt can no longer use is appended, so a broken token+ keeps a number and survives being typed around instead of vanishing on the+ next keystroke. */+ const tokenOrder = useMemo(() => {+ const order = numbered.map((reference) => reference.id);+ for (const shot of shots) {+ for (const id of actionReferenceIds(shot.action)) if (!order.includes(id)) order.push(id);+ }+ return order;+ }, [numbered, shots]);+ const referenceById = useMemo(() => new Map(references.map((reference) => [reference.id, reference])), [references]);+ const dangling = useMemo(() => danglingReferenceTokens(shots, references), [shots, references]);+ const [activeShotId, setActiveShotId] = useState<string | null>(null);+ const active = shots.some((shot) => shot.id === activeShotId) ? activeShotId : shots[0]?.id ?? null;++ /* Every edit lands here. The shots are the truth; `prompt` and `creativeBrief`+ are rewritten from them as the mirror they now are, and the legacy per-job+ `shotTags` is cleared because its terms have just moved onto a shot — two+ copies of the same choice is how one of them goes stale. */+ const write = useCallback((next: SceneShot[], extra: Partial<GenerationJob> = {}) => {+ const nextShots = normalizeSceneShots(next);+ const text = sceneBriefText(nextShots);+ onChange({+ shots: nextShots,+ shotTags: null,+ prompt: text,+ creativeBrief: text,+ durationSeconds: duration,+ ...extra,+ });+ }, [duration, onChange]);++ const patchShot = (id: string, updates: Partial<SceneShot>) =>+ write(shots.map((shot) => shot.id === id ? { ...shot, ...updates } : shot));++ const setDuration = (value: number) => {+ const next = Math.min(SCENE_MAX_SECONDS, Math.max(SCENE_MIN_SECONDS, Math.round(value / STEP_SECONDS) * STEP_SECONDS));+ // A shot cannot start after the scene ends, so shortening the scene pulls+ // the later cuts back with it rather than leaving them past the end.+ write(shots.map((shot) => ({ ...shot, startSeconds: Math.min(shot.startSeconds, next) })), { durationSeconds: next });+ };++ const addShot = () => {+ const last = shots[shots.length - 1];+ const halfway = Math.round(((last.startSeconds + duration) / 2) / STEP_SECONDS) * STEP_SECONDS;+ const start = Math.min(duration, Math.max(last.startSeconds + STEP_SECONDS, halfway));+ const shot: SceneShot = { id: `shot-${crypto.randomUUID()}`, startSeconds: start, action: "" };+ write([...shots, shot]);+ setActiveShotId(shot.id);+ };++ const removeShot = (id: string) => {+ // A scene is at least one shot: with none there is nowhere to write, and+ // the compiler would have nothing to make a [Shot 1] out of.+ if (shots.length <= 1) return;+ write(shots.filter((shot) => shot.id !== id));+ };++ return <section className="scene-editor" aria-label="This scene">+ <SceneLengthBar+ shots={shots}+ duration={duration}+ disabled={disabled}+ onDuration={setDuration}+ onStart={(id, startSeconds) => patchShot(id, { startSeconds })}+ onSelect={setActiveShotId}+ activeShotId={active}+ />++ <ol className="shot-list">+ {shots.map((shot, index) => <li key={shot.id}>+ <ShotCard+ shot={shot}+ index={index}+ endsAt={index + 1 < shots.length ? shots[index + 1].startSeconds : duration}+ duration={duration}+ disabled={disabled}+ removable={shots.length > 1}+ focused={shot.id === active}+ tokenOrder={tokenOrder}+ referenceById={referenceById}+ citable={citable}+ numbered={numbered}+ onFocus={() => setActiveShotId(shot.id)}+ onChange={(updates) => patchShot(shot.id, updates)}+ onRemove={() => removeShot(shot.id)}+ />+ </li>)}+ </ol>++ <button type="button" className="secondary-button scene-editor__add" disabled={disabled} onClick={addShot}>+ <Plus size={16} /> Add a shot+ </button>++ <ReferencePalette+ citable={citable}+ numbered={numbered}+ dangling={dangling}+ referenceById={referenceById}+ disabled={disabled || !active}+ onInsert={(referenceId) => {+ const shot = shots.find((item) => item.id === active);+ if (!shot) return;+ const spacer = shot.action && !/\s$/.test(shot.action) ? " " : "";+ patchShot(shot.id, { action: `${shot.action}${spacer}${referenceToken(referenceId)}` });+ }}+ />++ <SceneSettings job={job} shots={shots} disabled={disabled} onChange={onChange} onShots={write} />+ </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 below, because a bar cannot be+ * read by a screen reader and cannot be typed into. */+function SceneLengthBar({ shots, duration, disabled, onDuration, onStart, onSelect, activeShotId }: {+ shots: SceneShot[];+ duration: number;+ disabled: boolean;+ onDuration: (value: number) => void;+ onStart: (id: string, value: number) => void;+ onSelect: (id: string) => void;+ activeShotId: string | null;+}) {+ 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 ${shot.id === activeShotId ? "scene-bar__shot--active" : ""}`}+ 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));+ }}+ />}+ <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>;+}++/* --- One shot ------------------------------------------------------------- */++function ShotCard({ shot, index, endsAt, duration, disabled, removable, focused, tokenOrder, referenceById, citable, numbered, onFocus, onChange, onRemove }: {+ shot: SceneShot;+ index: number;+ endsAt: number;+ duration: number;+ disabled: boolean;+ removable: boolean;+ focused: boolean;+ tokenOrder: string[];+ referenceById: Map<string, ProjectReference>;+ citable: ProjectReference[];+ numbered: ProjectReference[];+ onFocus: () => void;+ onChange: (updates: Partial<SceneShot>) => void;+ onRemove: () => void;+}) {+ const fieldRef = useRef<HTMLTextAreaElement | null>(null);+ const settings = shot.settings ?? {};++ /* The line, written the way the user reads and types it. What is STORED is+ `@[ref:<id>]`, which survives a rename and a reorder; what is SHOWN is+ "[Reference N]", which is what they were promised and what they may type by+ hand. The two are one mapping, applied in both directions here and nowhere+ else, so the field can never show a citation the storage does not hold. */+ const display = useMemo(() => splitActionText(shot.action).map((part) => {+ if (part.kind === "text") return part.value;+ const number = tokenOrder.indexOf(part.value) + 1;+ return number > 0 ? `[Reference ${number}]` : part.value;+ }).join(""), [shot.action, tokenOrder]);++ const store = (typed: string): string => typed.replace(/\[Reference (\d+)\]/g, (whole, digits: string) => {+ const id = tokenOrder[Number(digits) - 1];+ // A number nobody has a reference for stays exactly as typed. It is the+ // user's own text, and turning it into a citation would invent a subject.+ return id ? referenceToken(id) : whole;+ });++ const insertAtCaret = (referenceId: string) => {+ const number = tokenOrder.indexOf(referenceId) + 1;+ const field = fieldRef.current;+ const at = field ? field.selectionStart : display.length;+ const before = display.slice(0, at);+ const after = display.slice(at);+ const lead = before && !/\s$/.test(before) ? " " : "";+ // A reference this scene does not cite yet has no number, so the token is+ // written by id and the number appears once the scene binds it.+ const token = number > 0 ? `[Reference ${number}]` : referenceToken(referenceId);+ onChange({ action: store(`${before}${lead}${token}${after}`) });+ };++ return <article className={`shot-card ${focused ? "shot-card--focused" : ""}`}>+ <header className="shot-card__head">+ <b>Shot {index + 1}</b>+ <label className="shot-card__start">+ <span>Starts at</span>+ <input+ type="number"+ min={SCENE_MIN_SECONDS}+ max={duration}+ step={STEP_SECONDS}+ value={shot.startSeconds}+ disabled={disabled || index === 0}+ aria-label={`Shot ${index + 1} starts at, in seconds`}+ title={index === 0 ? "The first shot always opens the scene." : undefined}+ onChange={(event) => onChange({ startSeconds: Math.min(duration, Math.max(0, Number(event.target.value) || 0)) })}+ />+ <em>to {seconds(endsAt)}</em>+ </label>+ {removable && <button+ type="button"+ className="shot-card__remove"+ disabled={disabled}+ aria-label={`Remove shot ${index + 1}`}+ onClick={onRemove}+ ><Trash2 size={15} /></button>}+ </header>++ {/* The line is the point of this screen, so it is the biggest thing on it. */}+ <label className="shot-card__action">+ <span className="shot-card__sublabel">What happens, in your own words</span>+ <textarea+ ref={fieldRef}+ value={display}+ disabled={disabled}+ aria-label={`What happens in shot ${index + 1}`}+ placeholder="Example: she walks towards the camera and stops under the awning."+ onFocus={onFocus}+ onChange={(event) => onChange({ action: store(event.target.value) })}+ onDragOver={(event) => { if (event.dataTransfer.types.includes(REFERENCE_DRAG_TYPE)) event.preventDefault(); }}+ onDrop={(event) => {+ const referenceId = event.dataTransfer.getData(REFERENCE_DRAG_TYPE);+ if (!referenceId) return;+ event.preventDefault();+ insertAtCaret(referenceId);+ }}+ />+ </label>++ <ActionReadback+ action={shot.action}+ tokenOrder={tokenOrder}+ referenceById={referenceById}+ citable={citable}+ numbered={numbered}+ disabled={disabled}+ onRepoint={(from, to) => onChange({ action: shot.action.split(referenceToken(from)).join(referenceToken(to)) })}+ onDrop={(from) => onChange({ action: shot.action.split(referenceToken(from)).join("") })}+ />++ <ShotSettings+ settings={settings}+ disabled={disabled}+ shotNumber={index + 1}+ onChange={(next) => onChange({ settings: normalizeShotTagSelection(next) })}+ />+ </article>;+}++/** 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+ * touching a single character the user typed around it. */+function ActionReadback({ action, tokenOrder, referenceById, citable, numbered, disabled, onRepoint, onDrop }: {+ action: string;+ tokenOrder: string[];+ referenceById: Map<string, ProjectReference>;+ citable: ProjectReference[];+ numbered: ProjectReference[];+ disabled: boolean;+ onRepoint: (from: string, to: string) => void;+ onDrop: (from: string) => void;+}) {+ const parts = splitActionText(action);+ if (!parts.some((part) => part.kind === "reference")) return null;+ const label = (id: string): string => {+ const number = tokenOrder.indexOf(id) + 1;+ const name = referenceById.get(id)?.name;+ return `Reference ${number > 0 ? number : "?"}${name ? ` · ${name}` : ""}`;+ };+ return <p className="shot-readback">+ <span className="shot-readback__lead">Every reference in the line can be swapped for another:</span>+ {parts.map((part, index) => part.kind === "text"+ ? <span key={index} className="shot-readback__text">{part.value}</span>+ : <select+ key={index}+ className={`shot-readback__token ${citable.some((reference) => reference.id === part.value) ? "" : "shot-readback__token--broken"}`}+ value={part.value}+ disabled={disabled}+ aria-label={`${label(part.value)} — choose another reference`}+ onChange={(event) => {+ if (event.target.value === "") onDrop(part.value);+ else if (event.target.value !== part.value) onRepoint(part.value, event.target.value);+ }}+ >+ {/* A reference that can no longer be cited still has to be selectable,+ or the control could not show what the line currently says. */}+ {!citable.some((reference) => reference.id === part.value) && <option value={part.value}>{label(part.value)} — can’t be used</option>}+ {citable.map((reference) => {+ const number = numbered.findIndex((item) => item.id === reference.id) + 1;+ return <option key={reference.id} value={reference.id}>+ {number > 0 ? `Reference ${number} · ${reference.name}` : `${reference.name} — not in this scene yet`}+ </option>;+ })}+ <option value="">Take it out of the line</option>+ </select>)}+ </p>;+}++/* --- Settings ------------------------------------------------------------- */++/** Settings are ADDED one at a time and given a value, rather than laid out as+ * a wall of every term the vocabulary holds. A shot with none is finished as+ * it is; nothing here is required. */+function ShotSettings({ settings, disabled, shotNumber, onChange }: {+ settings: ShotTagSelection;+ disabled: boolean;+ shotNumber: number;+ onChange: (next: ShotTagSelection) => void;+}) {+ const [pending, setPending] = useState<string | null>(null);+ const chosen = selectedShotTagOptions(settings);+ const movement = hasCameraMovement(settings);+ // The look is set once for the whole scene, so it is not offered here — the+ // description opens with ONE style, and a second one on shot 3 has nowhere in+ // the prompt to go.+ const groups = SHOT_TAG_GROUPS.filter((group) => !group.sceneWide);+ const group = pending ? shotTagGroup(pending) : undefined;++ return <div className="shot-settings">+ <ul className="shot-settings__chips">+ {chosen.map(({ group: owner, option }) => <li key={`${owner.id}-${option.id}`}>+ <span className="setting-tag">+ <em>{owner.label}</em>+ <b>{option.label}</b>+ <button+ type="button"+ disabled={disabled}+ aria-label={`Remove ${owner.label}: ${option.label} from shot ${shotNumber}`}+ title={`Puts “${option.term}” in the prompt`}+ onClick={() => onChange(toggleShotTag(settings, owner.id, option.id))}+ ><X size={13} /></button>+ </span>+ </li>)}+ {chosen.length === 0 && <li className="shot-settings__none">No settings on this shot, which is a finished shot.</li>}+ </ul>+ <div className="shot-settings__add">+ <select+ value={pending ?? ""}+ disabled={disabled}+ aria-label={`Add a setting to shot ${shotNumber}`}+ onChange={(event) => setPending(event.target.value || null)}+ >+ <option value="">Add a setting…</option>+ {groups.map((option) => {+ // Speed and amplitude qualify a movement. With none chosen the+ // compiler leaves them out, so offering them would promise something+ // the prompt does not do.+ const blocked = Boolean(option.requiresMovement) && !movement;+ return <option key={option.id} value={option.id} disabled={blocked}>+ {option.label}{blocked ? " — needs a camera movement first" : ""}+ </option>;+ })}+ </select>+ {group && <select+ value=""+ disabled={disabled}+ aria-label={`Value for ${group.label} on shot ${shotNumber}`}+ onChange={(event) => {+ if (!event.target.value) return;+ onChange(toggleShotTag(settings, group.id, event.target.value));+ setPending(null);+ }}+ >+ <option value="">Choose a value…</option>+ {group.options.map((option) => <option key={option.id} value={option.id}>{option.label}</option>)}+ </select>}+ {group && <span className="shot-settings__help">{group.help}</span>}+ </div>+ </div>;+}++/** What belongs to the whole scene rather than to one shot: the look the+ * description opens with (base guide §4.1), and the two sound fields the guide+ * defines per prompt (§4.6, §4.7). */+function SceneSettings({ job, shots, disabled, onChange, onShots }: {+ job: GenerationJob;+ shots: SceneShot[];+ disabled: boolean;+ onChange: (updates: Partial<GenerationJob>) => void;+ onShots: (next: SceneShot[]) => 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+ // is written. One place, never a second field that could disagree with it.+ const chosen = shots.map((shot) => shot.settings?.[look.id]?.[0]).find(Boolean) ?? "";++ return <div className="scene-settings">+ <h3>The whole scene</h3>+ <label className="scene-settings__field">+ <span>Look</span>+ <select+ value={chosen}+ disabled={disabled}+ aria-label="The look of this scene"+ onChange={(event) => {+ const value = event.target.value;+ onShots(shots.map((shot, index) => {+ const settings = { ...(shot.settings ?? {}) };+ if (index === 0 && value) settings[look.id] = [value];+ else delete settings[look.id];+ return { ...shot, settings: normalizeShotTagSelection(settings) };+ }));+ }}+ >+ <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>+ <textarea+ value={job.soundscape ?? ""}+ disabled={disabled}+ aria-label="The sound of this scene"+ 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>+ <textarea+ value={job.music ?? ""}+ disabled={disabled}+ aria-label="The music of this scene"+ 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>;+}++/* --- The references this scene can use ------------------------------------ */++function ReferencePalette({ citable, numbered, dangling, referenceById, disabled, onInsert }: {+ citable: ProjectReference[];+ numbered: ProjectReference[];+ dangling: string[];+ referenceById: Map<string, ProjectReference>;+ disabled: boolean;+ onInsert: (referenceId: string) => void;+}) {+ return <div className="reference-palette">+ <span className="reference-palette__lead">+ {citable.length === 0+ ? "This project has no references the prompt can use yet. Add one under References and it can be dropped into a line."+ : "Drag one into a line, or add it to the end of the shot you were last writing in."}+ </span>+ <ul>+ {citable.map((reference) => {+ const number = numbered.findIndex((item) => item.id === reference.id) + 1;+ return <li key={reference.id}>+ <button+ type="button"+ className="reference-chip"+ draggable={!disabled}+ disabled={disabled}+ title={number > 0+ ? `Writes “Reference ${number}” into the line, and <Subject ${number}> into the prompt`+ : "Dropping it into a line adds it to this scene, and it takes the next Reference number"}+ onDragStart={(event) => {+ event.dataTransfer.setData(REFERENCE_DRAG_TYPE, reference.id);+ event.dataTransfer.effectAllowed = "copy";+ }}+ onClick={() => onInsert(reference.id)}+ >+ <em>{number > 0 ? `Reference ${number}` : "Not in this scene yet"}</em>+ <b>{reference.name}</b>+ </button>+ </li>;+ })}+ </ul>+ {dangling.length > 0 && <p className="reference-palette__broken">+ {dangling.length === 1 ? "One reference named in this scene" : `${dangling.length} references named in this scene`} can no+ longer be used — {dangling.map((id) => referenceById.get(id)?.name ?? "one that was deleted").join(", ")}. Those names are+ left out of the compiled prompt below, and the scene cannot be sent until each one is swapped for another reference or taken+ out of the line.+ </p>}+ </div>;+}