Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Teach the rust validator about scenes, with a fixture both sides read

Bitti644f14003db5
diff --git a/fixtures/project-v1-scene.json b/fixtures/project-v1-scene.json
new file mode 100644
index 0000000..d253f2c
--- /dev/null
+++ b/fixtures/project-v1-scene.json
@@ -0,0 +1,113 @@
+{
+ "schemaVersion": 1,
+ "id": "project-scene-1",
+ "name": "A scene of three shots",
+ "createdAt": "2026-02-01T00:00:00.000Z",
+ "updatedAt": "2026-02-01T00:30:00.000Z",
+ "thumbnail": null,
+ "settings": {
+ "aspectRatio": "16:9",
+ "resolution": "1080p",
+ "frameRate": 30,
+ "backgroundColor": "#10131a"
+ },
+ "brief": {
+ "prompt": "a woman crossing a wet city street",
+ "status": "draft",
+ "targetDurationSeconds": 30,
+ "aspectRatio": "16:9",
+ "resolution": "1080p"
+ },
+ "assets": [],
+ "timeline": {
+ "tracks": [
+ {
+ "id": "track-story",
+ "kind": "video",
+ "name": "Track 1, Video",
+ "locked": false,
+ "muted": false,
+ "clips": []
+ },
+ {
+ "id": "track-a1",
+ "kind": "audio",
+ "name": "Track 1, Audio",
+ "locked": false,
+ "muted": false,
+ "clips": []
+ }
+ ]
+ },
+ "references": [
+ {
+ "id": "reference-woman",
+ "kind": "image",
+ "name": "Red-haired woman",
+ "description": "A woman in her thirties with dark red hair and a green canvas jacket.",
+ "content": null,
+ "relativePath": "references/red-haired-woman.png",
+ "intendedUse": ["character"],
+ "createdAt": "2026-02-01T00:05:00.000Z"
+ },
+ {
+ "id": "reference-street",
+ "kind": "image",
+ "name": "City street",
+ "description": "A narrow street of brick warehouses with wet cobbles and hanging cables.",
+ "content": null,
+ "relativePath": "references/city-street.png",
+ "intendedUse": ["location"],
+ "createdAt": "2026-02-01T00:06:00.000Z"
+ }
+ ],
+ "generationJobs": [
+ {
+ "id": "scene-walk",
+ "title": "She crosses the street",
+ "prompt": "@[ref:reference-woman] walks towards the camera on @[ref:reference-street]\n\nshe stops at a doorway and looks up\n\nthe door opens and light spills across @[ref:reference-street]",
+ "status": "draft",
+ "stage": "queued",
+ "progress": 0,
+ "providerId": "minimax-h3",
+ "creativeBrief": "@[ref:reference-woman] walks towards the camera on @[ref:reference-street]\n\nshe stops at a doorway and looks up\n\nthe door opens and light spills across @[ref:reference-street]",
+ "compiledPrompt": "a stale draft-time snapshot; the sender recompiles from the scene",
+ "referenceIds": ["reference-woman", "reference-street"],
+ "shots": [
+ {
+ "id": "scene-walk-shot-1",
+ "startSeconds": 0,
+ "action": "@[ref:reference-woman] walks towards the camera on @[ref:reference-street]",
+ "settings": {
+ "cameraMovement": ["push-in"],
+ "cameraSpeed": ["slow"],
+ "shotSize": ["wide"],
+ "visualStyle": ["live-action-cinematic"]
+ }
+ },
+ {
+ "id": "scene-walk-shot-2",
+ "startSeconds": 4.5,
+ "action": "she stops at a doorway and looks up",
+ "settings": {
+ "shotSize": ["medium-close-up"]
+ }
+ },
+ {
+ "id": "scene-walk-shot-3",
+ "startSeconds": 9,
+ "action": "the door opens and light spills across @[ref:reference-street]"
+ }
+ ],
+ "durationSeconds": 12,
+ "soundscape": "Rain on cobbles, distant traffic, her boots on stone.",
+ "music": "Low sustained cello, slow tempo, swelling in the last two seconds.",
+ "createdAt": "2026-02-01T00:10:00.000Z",
+ "updatedAt": "2026-02-01T00:30:00.000Z"
+ }
+ ],
+ "agentConversation": {
+ "messages": []
+ },
+ "providerSettings": {}
+}
diff --git a/fixtures/rust-serialized-scene.json b/fixtures/rust-serialized-scene.json
new file mode 100644
index 0000000..0236dd1
--- /dev/null
+++ b/fixtures/rust-serialized-scene.json
@@ -0,0 +1,132 @@
+{
+ "schemaVersion": 1,
+ "id": "project-scene-1",
+ "name": "A scene of three shots",
+ "createdAt": "2026-02-01T00:00:00.000Z",
+ "updatedAt": "2026-02-01T00:30:00.000Z",
+ "thumbnail": null,
+ "settings": {
+ "aspectRatio": "16:9",
+ "resolution": "1080p",
+ "frameRate": 30,
+ "backgroundColor": "#10131a"
+ },
+ "brief": {
+ "prompt": "a woman crossing a wet city street",
+ "status": "draft",
+ "targetDurationSeconds": 30,
+ "aspectRatio": "16:9",
+ "resolution": "1080p"
+ },
+ "assets": [],
+ "timeline": {
+ "tracks": [
+ {
+ "id": "track-story",
+ "kind": "video",
+ "name": "Track 1, Video",
+ "locked": false,
+ "muted": false,
+ "clips": []
+ },
+ {
+ "id": "track-a1",
+ "kind": "audio",
+ "name": "Track 1, Audio",
+ "locked": false,
+ "muted": false,
+ "clips": []
+ }
+ ]
+ },
+ "references": [
+ {
+ "id": "reference-woman",
+ "kind": "image",
+ "name": "Red-haired woman",
+ "description": "A woman in her thirties with dark red hair and a green canvas jacket.",
+ "content": null,
+ "relativePath": "references/red-haired-woman.png",
+ "intendedUse": [
+ "character"
+ ],
+ "createdAt": "2026-02-01T00:05:00.000Z"
+ },
+ {
+ "id": "reference-street",
+ "kind": "image",
+ "name": "City street",
+ "description": "A narrow street of brick warehouses with wet cobbles and hanging cables.",
+ "content": null,
+ "relativePath": "references/city-street.png",
+ "intendedUse": [
+ "location"
+ ],
+ "createdAt": "2026-02-01T00:06:00.000Z"
+ }
+ ],
+ "generationJobs": [
+ {
+ "id": "scene-walk",
+ "title": "She crosses the street",
+ "prompt": "@[ref:reference-woman] walks towards the camera on @[ref:reference-street]\n\nshe stops at a doorway and looks up\n\nthe door opens and light spills across @[ref:reference-street]",
+ "status": "draft",
+ "stage": "queued",
+ "progress": 0.0,
+ "providerId": "minimax-h3",
+ "creativeBrief": "@[ref:reference-woman] walks towards the camera on @[ref:reference-street]\n\nshe stops at a doorway and looks up\n\nthe door opens and light spills across @[ref:reference-street]",
+ "compiledPrompt": "a stale draft-time snapshot; the sender recompiles from the scene",
+ "referenceIds": [
+ "reference-woman",
+ "reference-street"
+ ],
+ "shots": [
+ {
+ "id": "scene-walk-shot-1",
+ "startSeconds": 0.0,
+ "action": "@[ref:reference-woman] walks towards the camera on @[ref:reference-street]",
+ "settings": {
+ "cameraMovement": [
+ "push-in"
+ ],
+ "cameraSpeed": [
+ "slow"
+ ],
+ "shotSize": [
+ "wide"
+ ],
+ "visualStyle": [
+ "live-action-cinematic"
+ ]
+ }
+ },
+ {
+ "id": "scene-walk-shot-2",
+ "startSeconds": 4.5,
+ "action": "she stops at a doorway and looks up",
+ "settings": {
+ "shotSize": [
+ "medium-close-up"
+ ]
+ }
+ },
+ {
+ "id": "scene-walk-shot-3",
+ "startSeconds": 9.0,
+ "action": "the door opens and light spills across @[ref:reference-street]"
+ }
+ ],
+ "durationSeconds": 12.0,
+ "soundscape": "Rain on cobbles, distant traffic, her boots on stone.",
+ "music": "Low sustained cello, slow tempo, swelling in the last two seconds.",
+ "outputRelativePath": null,
+ "error": null,
+ "createdAt": "2026-02-01T00:10:00.000Z",
+ "updatedAt": "2026-02-01T00:30:00.000Z"
+ }
+ ],
+ "agentConversation": {
+ "messages": []
+ },
+ "providerSettings": {}
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index e30d595..b57378c 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -160,12 +160,38 @@ struct ReusableReference {
created_at: String,
}
+/// One shot inside a scene. Mirrors `sceneShotSchema` in src/lib/project.ts.
+///
+/// `startSeconds` and `action` are REQUIRED on the zod side and are plain
+/// (non-`Option`) fields here, so they are always written — a `#[serde(default)]`
+/// covers a file that predates them without ever producing a key zod refuses.
+/// `settings` is the only optional one and carries `skip_serializing_if`,
+/// because zod spells it `.nullish()` for the same reason `shotTags` is.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct SceneShot {
+ id: String,
+ #[serde(default)]
+ start_seconds: f64,
+ /// The user's own line, tokens and all. May be empty: a shot they have just
+ /// added has nothing written in it, and this layer never fills it in.
+ #[serde(default)]
+ action: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ settings: Option<BTreeMap<String, Vec<String>>>,
+}
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct GenerationJob {
id: String,
#[serde(default)]
title: String,
+ /// A MIRROR of the scene's shot lines for a scene-shaped job, and the user's
+ /// only copy of their words for every job written before scenes existed.
+ /// That is why it may be empty here but not there — see the emptiness rule
+ /// in `validate_and_normalize_config`, which is zod's `superRefine` on
+ /// `generationJobSchema` written out.
#[serde(default)]
prompt: String,
status: String,
@@ -190,6 +216,24 @@ struct GenerationJob {
/// dropped on the next save.
#[serde(default, skip_serializing_if = "Option::is_none")]
shot_tags: Option<BTreeMap<String, Vec<String>>>,
+ /// The shots this scene holds, in playing order. Every one of the four
+ /// fields below is an `Option` with `skip_serializing_if`, because every
+ /// project written before scenes existed has none of these keys and must
+ /// round-trip byte-for-byte: zod spells all four `.nullish()`, so `null`
+ /// would also be readable, but an absent key is what the old files have.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ shots: Option<Vec<SceneShot>>,
+ /// How long the whole scene runs, 0-15 seconds. Absent means the length
+ /// every shot was generated at before this was settable.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ duration_seconds: Option<f64>,
+ /// Base guide §4.6 and §4.7 — per-prompt fields, so they sit on the scene
+ /// rather than on a shot. Absent means the compiler writes its own
+ /// content-neutral line and marks it as PolStudio's own words.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ soundscape: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ music: Option<String>,
// `clipId` is `.optional()` and NOT `.nullable()` on the frontend, and no
// freshly created job ever has one, so emitting `"clipId": null` made every
// create_project / open_project response fail zod. Keep the key absent.
@@ -716,11 +760,65 @@ fn validate_and_normalize_config(mut config: ProjectConfig) -> Result<ProjectCon
}
}
for job in &mut config.generation_jobs {
+ /* Normalise the scene BEFORE anything is judged, so both layers judge
+ the same thing. An empty `shots` array collapses to no key at all —
+ the same three-step tidy `normalize_shot_tags` performs, for the same
+ reason: two builds must write the same bytes for the same scene. The
+ ORDER of the shots is left exactly as given; the frontend orders them
+ by start time when it reads them (`normalizeSceneShots`), and a layer
+ that reordered on write would produce a spurious diff on every save.
+ Both layers ACCEPT the same files either way, which is the contract. */
+ if let Some(shots) = job.shots.as_mut() {
+ let mut seen: BTreeSet<String> = BTreeSet::new();
+ for shot in shots.iter_mut() {
+ if shot.id.trim().is_empty() {
+ return Err(format!("Scene '{}' has a shot with an empty id.", job.id));
+ }
+ if !seen.insert(shot.id.clone()) {
+ return Err(format!(
+ "Scene '{}' has two shots with the id '{}'.",
+ job.id, shot.id
+ ));
+ }
+ if !shot.start_seconds.is_finite() || !(0.0..=15.0).contains(&shot.start_seconds) {
+ return Err(format!(
+ "Shot '{}' in scene '{}' starts at {} seconds, outside the 0-15 second scene.",
+ shot.id, job.id, shot.start_seconds
+ ));
+ }
+ shot.settings = normalize_shot_tags(shot.settings.take())
+ .map_err(|reason| format!("Shot '{}' {reason}", shot.id))?;
+ }
+ }
+ if job.shots.as_ref().is_some_and(|shots| shots.is_empty()) {
+ job.shots = None;
+ }
+ if let Some(seconds) = job.duration_seconds {
+ if !seconds.is_finite() || !(0.0..=15.0).contains(&seconds) {
+ return Err(format!(
+ "Scene '{}' is {seconds} seconds long, outside the 0-15 second range.",
+ job.id
+ ));
+ }
+ }
+ // Blank is the same as unset for both of these; the compiler falls back
+ // to its own line, and writing `""` would be a key zod has to tolerate
+ // for no gain.
+ for field in [&mut job.soundscape, &mut job.music] {
+ if field.as_deref().is_some_and(|text| text.trim().is_empty()) {
+ *field = None;
+ }
+ }
+ /* The words live in ONE of two places. A scene keeps them on its shots,
+ so `prompt` and `creativeBrief` are only its mirror and may be blank;
+ a job with no shots — every project written before scenes existed —
+ keeps them here, where blank would mean the user's words were lost.
+ `generationJobSchema.superRefine` in src/lib/project.ts is this rule. */
+ let has_shots = job.shots.as_ref().is_some_and(|shots| !shots.is_empty());
if job.id.trim().is_empty()
|| job.title.trim().is_empty()
- || job.prompt.trim().is_empty()
- || job.creative_brief.trim().is_empty()
|| job.compiled_prompt.trim().is_empty()
+ || (!has_shots && (job.prompt.trim().is_empty() || job.creative_brief.trim().is_empty()))
{
return Err(
"Generation job id, title, prompt, creative brief, and compiled prompt cannot be empty.".into(),
@@ -1903,10 +2001,14 @@ mod tests {
serde_json::from_str(include_str!("../../fixtures/project-v1-complete.json")).unwrap()
}
- /// Byte-exact output of the frontend's `createProjectConfig` — what a real
- /// newly created project looks like before anything has been edited. The
- /// complete fixture cannot stand in for it: it has no draft job without a
- /// clip, which is the shape that broke every create and open.
+ /// A project created BEFORE scenes existed, and the shape every project on
+ /// disk today still has: one generation job with no `shots`, no
+ /// `durationSeconds` and no sound fields, holding its words in `prompt` and
+ /// `creativeBrief` alone. It was the byte-exact output of
+ /// `createProjectConfig`, which now opens a scene instead — the file is kept
+ /// exactly as it was because that is the point of it. The complete fixture
+ /// cannot stand in for it: it has no draft job without a clip, which is the
+ /// shape that broke every create and open.
fn created_fixture() -> ProjectConfig {
serde_json::from_str(include_str!("../../fixtures/project-v1-created.json")).unwrap()
}
@@ -1921,6 +2023,14 @@ mod tests {
.unwrap()
}
+ /// A SCENE: three shots with their own start times, settings and reference
+ /// tokens, plus the two per-prompt sound fields. Every key scenes added is
+ /// present here, so a struct that forgets `skip_serializing_if` shows up in
+ /// `rust-serialized-scene.json` and fails on the frontend's real zod.
+ fn scene_fixture() -> ProjectConfig {
+ serde_json::from_str(include_str!("../../fixtures/project-v1-scene.json")).unwrap()
+ }
+
/// The keys the frontend schema spells `.optional()` with NO `.nullable()`
/// (src/lib/project.ts lines 42-44, 56, 109). zod's `.optional()` rejects
/// `null`, so an explicit null under any of these names makes the whole
@@ -1978,7 +2088,11 @@ mod tests {
// The cross-layer direction that went unchecked for nine rounds: Rust
// WRITING something zod cannot read. Browser mode never touches Rust,
// so nothing else catches it.
- for (name, config) in [("created", created_fixture()), ("complete", fixture())] {
+ for (name, config) in [
+ ("created", created_fixture()),
+ ("complete", fixture()),
+ ("scene", scene_fixture()),
+ ] {
let config = validate_and_normalize_config(config).unwrap();
let found = forbidden_nulls(&config);
assert!(
@@ -2051,6 +2165,12 @@ mod tests {
"rust-serialized-external-media.json",
&serialize(&validate_and_normalize_config(external_fixture()).unwrap()),
);
+ // Everything a scene added: shots with start times and per-shot
+ // settings, a scene length, and the two sound fields.
+ write_fixture(
+ "rust-serialized-scene.json",
+ &serialize(&validate_and_normalize_config(scene_fixture()).unwrap()),
+ );
// An ACTUALLY IMPORTED reference: produced by the same function the
// create-project command calls, not a hand-written fixture record.
@@ -2133,7 +2253,11 @@ mod tests {
#[test]
fn both_fixtures_round_trip_losslessly_through_json() {
- for (name, config) in [("created", created_fixture()), ("complete", fixture())] {
+ for (name, config) in [
+ ("created", created_fixture()),
+ ("complete", fixture()),
+ ("scene", scene_fixture()),
+ ] {
let normalized = validate_and_normalize_config(config).unwrap();
let json = serde_json::to_string_pretty(&normalized).unwrap();
let reparsed: ProjectConfig = serde_json::from_str(&json).unwrap();
@@ -3280,6 +3404,121 @@ mod tests {
);
}
+ #[test]
+ fn a_project_written_before_scenes_existed_still_opens_and_grows_no_scene_keys() {
+ // Both pre-scene shapes: the byte-exact output of createProjectConfig,
+ // and a fuller project. Neither has `shots`, `durationSeconds`,
+ // `soundscape` or `music`, and neither may sprout one — the frontend
+ // reads such a job as a single-shot scene without the file changing.
+ for (name, config) in [("created", created_fixture()), ("complete", fixture())] {
+ let opened = validate_and_normalize_config(config).unwrap();
+ let job = &opened.generation_jobs[0];
+ assert_eq!(job.shots, None, "{name}");
+ assert_eq!(job.duration_seconds, None, "{name}");
+ assert_eq!(job.soundscape, None, "{name}");
+ assert_eq!(job.music, None, "{name}");
+ let json = serde_json::to_string_pretty(&opened).unwrap();
+ for key in ["shots", "durationSeconds", "soundscape", "music"] {
+ assert!(
+ !json.contains(&format!("\"{key}\"")),
+ "the {name} fixture grew a {key} key it never had: {json}"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn a_scene_keeps_its_shots_and_normalizes_them_the_way_the_frontend_does() {
+ let scene = validate_and_normalize_config(scene_fixture()).unwrap();
+ let job = &scene.generation_jobs[0];
+ let shots = job.shots.as_ref().expect("the scene fixture has shots");
+ assert_eq!(shots.len(), 3);
+ assert_eq!(
+ shots.iter().map(|shot| shot.start_seconds).collect::<Vec<_>>(),
+ vec![0.0, 4.5, 9.0]
+ );
+ assert_eq!(job.duration_seconds, Some(12.0));
+ // Per-shot settings go through the same tidy as the legacy per-job tags.
+ assert_eq!(shots[0].settings.as_ref().unwrap()["shotSize"], vec!["wide"]);
+ assert_eq!(shots[2].settings, None);
+ // Its words are on the shots, and `prompt`/`creativeBrief` mirror them.
+ assert!(shots[0].action.contains("@[ref:reference-woman]"));
+
+ // An emptied group is dropped from a SHOT's settings exactly as it is
+ // from a job's tags, and an emptied shot list collapses to no key.
+ let mut emptied = scene_fixture();
+ emptied.generation_jobs[0].shots.as_mut().unwrap()[1].settings =
+ Some(BTreeMap::from([("mood".into(), Vec::new())]));
+ let emptied = validate_and_normalize_config(emptied).unwrap();
+ assert_eq!(emptied.generation_jobs[0].shots.as_ref().unwrap()[1].settings, None);
+
+ let mut no_shots = scene_fixture();
+ no_shots.generation_jobs[0].shots = Some(Vec::new());
+ let no_shots = validate_and_normalize_config(no_shots).unwrap();
+ assert_eq!(no_shots.generation_jobs[0].shots, None);
+ let json = serde_json::to_string_pretty(&no_shots).unwrap();
+ assert!(!json.contains("\"shots\""), "an empty shot list must not be written: {json}");
+ }
+
+ #[test]
+ fn a_scene_may_have_no_words_left_in_its_mirror_but_a_pre_scene_job_may_not() {
+ // The words live on the shots, so blanking the mirror is not a loss.
+ let mut scene = scene_fixture();
+ scene.generation_jobs[0].prompt = String::new();
+ scene.generation_jobs[0].creative_brief = String::new();
+ assert!(
+ validate_and_normalize_config(scene).is_ok(),
+ "a scene keeps its words on its shots, so the mirror may be blank"
+ );
+
+ // Without shots the mirror IS the only copy, and blanking it would lose
+ // them. zod's superRefine on generationJobSchema refuses the same file.
+ for blank in [0, 1] {
+ let mut legacy = fixture();
+ if blank == 0 {
+ legacy.generation_jobs[0].prompt = String::new();
+ } else {
+ legacy.generation_jobs[0].creative_brief = String::new();
+ }
+ assert!(
+ validate_and_normalize_config(legacy).is_err(),
+ "a job with no shots must keep its words"
+ );
+ }
+ }
+
+ #[test]
+ fn a_scene_is_bounded_to_fifteen_seconds_on_both_the_length_and_the_cuts() {
+ // The frontend spells this `z.number().min(0).max(15)` on both fields.
+ for seconds in [0.0, 7.5, 15.0] {
+ let mut config = scene_fixture();
+ config.generation_jobs[0].duration_seconds = Some(seconds);
+ assert!(
+ validate_and_normalize_config(config).is_ok(),
+ "rejected a valid scene length of {seconds}s"
+ );
+ }
+ for seconds in [-0.5, 15.1, f64::NAN, f64::INFINITY] {
+ let mut config = scene_fixture();
+ config.generation_jobs[0].duration_seconds = Some(seconds);
+ assert!(
+ validate_and_normalize_config(config).is_err(),
+ "accepted a scene length of {seconds}s"
+ );
+ let mut cut = scene_fixture();
+ cut.generation_jobs[0].shots.as_mut().unwrap()[1].start_seconds = seconds;
+ assert!(
+ validate_and_normalize_config(cut).is_err(),
+ "accepted a cut at {seconds}s"
+ );
+ }
+ // Two shots that share an id would make "the shot with id X" ambiguous
+ // in every edit the UI performs. zod refuses the same file.
+ let mut twins = scene_fixture();
+ twins.generation_jobs[0].shots.as_mut().unwrap()[1].id = "scene-walk-shot-1".into();
+ assert!(validate_and_normalize_config(twins).is_err());
+ }
+
#[test]
fn validator_accepts_every_boundary_the_frontend_schema_allows() {
for aspect_ratio in ["16:9", "9:16", "1:1", "4:5"] {
diff --git a/src/lib/project.test.ts b/src/lib/project.test.ts
index 9dd299c..498e4ed 100644
--- a/src/lib/project.test.ts
+++ b/src/lib/project.test.ts
@@ -6,6 +6,8 @@ import wireCreated from "../../fixtures/rust-serialized-created.json";
import wireExternal from "../../fixtures/rust-serialized-external-media.json";
import wireComplete from "../../fixtures/rust-serialized-complete.json";
import initialReferenceWire from "../../fixtures/rust-serialized-initial-reference.json";
+import sceneFixture from "../../fixtures/project-v1-scene.json";
+import wireScene from "../../fixtures/rust-serialized-scene.json";
import {
compileMiniMaxH3Prompt,
@@ -22,6 +24,20 @@ import {
seedProjectWorkspace,
STORY_TRACK_ID,
usableImageReferences,
+ actionReferenceIds,
+ compileGenerationJobPrompt,
+ compileGenerationJobSegments,
+ createDraftGenerationJob,
+ danglingReferenceTokens,
+ formatSceneSeconds,
+ generationJobSchema,
+ referenceToken,
+ sceneBriefText,
+ sceneDurationSeconds,
+ sceneShots,
+ splitActionText,
+ DEFAULT_SCENE_SECONDS,
+ SCENE_MAX_SECONDS,
LEGACY_PROJECT_FILE_NAMES,
PROJECT_FILE_NAME,
type ProjectReference,
@@ -32,6 +48,7 @@ const wireFixtures = {
complete: wireComplete,
initialReference: initialReferenceWire,
externalMedia: wireExternal,
+ scene: wireScene,
};
/** Body of one compiled section, for both prompt shapes: T2VA writes
@@ -319,8 +336,9 @@ describe("project schema", () => {
});
it("accepts a freshly created project exactly as createProjectConfig writes it", () => {
- // This fixture is the byte-exact output of createProjectConfig. Its first
- // job has NO clipId key at all, which is what every real project looks like.
+ // This fixture is a project created before scenes existed — the shape every
+ // project on disk still has. Its first job has NO clipId key at all, which
+ // is what every real project looks like.
expect(parseProjectConfig(createdFixture)).toBeTruthy();
expect("clipId" in createdFixture.generationJobs[0]).toBe(false);
// Rust reads THIS file and writes the wire fixtures from it, so a seed
@@ -511,3 +529,158 @@ describe("project schema", () => {
expect(project.generationJobs.filter((job) => job.outputRelativePath).every((job) => !job.outputRelativePath!.match(/^([a-z]:|[/\\])/i))).toBe(true);
});
});
+
+describe("scenes and the shots inside them", () => {
+ const now = "2026-02-01T00:00:00.000Z";
+ const scene = () => parseProjectConfig(sceneFixture);
+ const shot = (id: string, startSeconds: number, action: string, settings?: Record<string, string[]>) =>
+ ({ id, startSeconds, action, ...(settings ? { settings } : {}) });
+
+ it("reads a job written before scenes existed as a single-shot scene", () => {
+ // Word for word, tag for tag — the migration adds nothing and drops nothing.
+ const legacy = parseProjectConfig(completeFixture).generationJobs[0];
+ expect(legacy.shots ?? null).toBeNull();
+ const shots = sceneShots(legacy);
+ expect(shots).toHaveLength(1);
+ expect(shots[0].action).toBe(legacy.creativeBrief);
+ expect(shots[0].startSeconds).toBe(0);
+ expect(shots[0].settings).toEqual(legacy.shotTags);
+ // And it is generated at the length it always was, without the file saying so.
+ expect(sceneDurationSeconds(legacy)).toBe(DEFAULT_SCENE_SECONDS);
+
+ // The prompt it compiles to is the one it has always compiled to.
+ expect(compileGenerationJobPrompt(legacy, []))
+ .toBe(compileMiniMaxH3Prompt(legacy.creativeBrief, [], legacy.shotTags ?? null));
+ });
+
+ it("compiles three shots in order, each cut carrying its own timestamp", () => {
+ const job = createDraftGenerationJob("", {
+ id: "scene-three", title: "Three shots", now, durationSeconds: 9,
+ shots: [
+ // Deliberately out of order in the array: the START TIMES decide.
+ shot("b", 3, "she stops at the doorway"),
+ shot("a", 0, "she walks towards the camera"),
+ shot("c", 6.5, "the door opens"),
+ ],
+ });
+ const compiled = compileGenerationJobPrompt(job, []);
+ expect(compiled).toContain("[Shot 1] Live-action, cinematic, she walks towards the camera.");
+ 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");
+ // In order, and only shot 1 is timestamp-free (base guide §4.2).
+ expect(compiled.indexOf("[Shot 1]")).toBeLessThan(compiled.indexOf("[Shot 2]"));
+ expect(compiled.indexOf("[Shot 2]")).toBeLessThan(compiled.indexOf("[Shot 3]"));
+ expect(compiled).not.toContain("[Shot 1] (cut");
+ // The mirror is the user's own lines and nothing else.
+ expect(job.creativeBrief).toBe("she walks towards the camera\n\nshe stops at the doorway\n\nthe door opens");
+ expect(sceneBriefText(sceneShots(job))).toBe(job.creativeBrief);
+ });
+
+ it("turns a reference token into <Subject N>, in lockstep with reference_paths", () => {
+ const config = scene();
+ const job = config.generationJobs[0];
+ const compiled = compileGenerationJobPrompt(job, config.references);
+ // Subject numbering follows the project's reference order, which is the
+ // same order usableImageReferences hands to reference_paths — so <Picture 1>
+ // is the first path sent and <Subject 1> is the thing it shows.
+ const images = usableImageReferences(config.references);
+ expect(images.map((reference) => reference.id)).toEqual(["reference-woman", "reference-street"]);
+ expect(compiled).toContain("<Subject 1> is the content shown in <Picture 1>.");
+ expect(compiled).toContain("<Subject 2> is the content shown in <Picture 2>.");
+ // The token in the user's line became the citation, in place.
+ expect(compiled).toContain("[Shot 1] Wide shot, <Subject 1> walks towards the camera on <Subject 2>.");
+ // The raw token never reaches the model.
+ expect(compiled).not.toContain("@[ref:");
+ // Retention names the shots each subject is really written into — shot 2
+ // cites nobody, so it features both, and shot 3 cites only the street.
+ expect(compiled).toContain("<Subject 1> (appears in [Shot 1], [Shot 2]): fully_preserved");
+ expect(compiled).toContain("<Subject 2> (appears in [Shot 1], [Shot 2], [Shot 3]): fully_preserved");
+ // The scene's own sound and music replace the two default lines.
+ expect(compiled).toContain("overall_soundscape:\nRain on cobbles, distant traffic, her boots on stone.");
+ expect(compiled).toContain("non_diegetic_music:\nLow sustained cello");
+
+ // Both are the user's own words, and the citations are not.
+ const segments = compileGenerationJobSegments(job, config.references);
+ expect(segments.some((part) => part.kind === "brief" && part.value === " walks towards the camera on ")).toBe(true);
+ expect(segments.some((part) => part.kind === "frame" && part.value === "<Subject 1>")).toBe(true);
+ expect(segments.some((part) => part.kind === "brief" && part.value.startsWith("Rain on cobbles"))).toBe(true);
+ // And the preview IS the string that is sent.
+ expect(segments.map((part) => part.value).join("")).toBe(compiled);
+ });
+
+ it("re-points a token at another reference and the compiled prompt follows", () => {
+ const config = scene();
+ const job = config.generationJobs[0];
+ const before = compileGenerationJobPrompt(job, config.references);
+ expect(before).toContain("<Subject 1> walks towards the camera on <Subject 2>");
+
+ // The swap the editor performs: the token's reference id is replaced, not
+ // the words around it.
+ const swapped = {
+ ...job,
+ shots: job.shots!.map((current) => current.id === "scene-walk-shot-1"
+ ? { ...current, action: current.action.replace(referenceToken("reference-woman"), referenceToken("reference-street")) }
+ : current),
+ };
+ const after = compileGenerationJobPrompt(swapped, config.references);
+ expect(after).toContain("<Subject 2> walks towards the camera on <Subject 2>");
+ expect(after).not.toContain("<Subject 1> walks towards the camera");
+ expect(actionReferenceIds(swapped.shots![0].action)).toEqual(["reference-street"]);
+ });
+
+ it("leaves a token whose reference can no longer be cited out, and names it", () => {
+ const config = scene();
+ const job = config.generationJobs[0];
+ // The reference is deleted from the project; the sentence keeps its shape.
+ const remaining = config.references.filter((reference) => reference.id !== "reference-woman");
+ expect(danglingReferenceTokens(sceneShots(job), remaining)).toEqual(["reference-woman"]);
+ const compiled = compileGenerationJobPrompt(job, remaining);
+ expect(compiled).toContain("[Shot 1] Wide shot, walks towards the camera on <Subject 1>.");
+ expect(compiled).not.toContain("@[ref:");
+ // Nothing dangles while every reference is still there.
+ expect(danglingReferenceTokens(sceneShots(job), config.references)).toEqual([]);
+ });
+
+ it("splits a line into the user's characters and the references they dropped in", () => {
+ expect(splitActionText("a @[ref:one] and @[ref:two]")).toEqual([
+ { kind: "text", value: "a " },
+ { kind: "reference", value: "one" },
+ { kind: "text", value: " and " },
+ { kind: "reference", value: "two" },
+ ]);
+ expect(splitActionText("no references here")).toEqual([{ kind: "text", value: "no references here" }]);
+ expect(splitActionText("")).toEqual([]);
+ });
+
+ it("holds a scene to nought through fifteen seconds, on its length and on every cut", () => {
+ const valid = (patch: Record<string, unknown>) =>
+ generationJobSchema.safeParse({ ...scene().generationJobs[0], ...patch }).success;
+ for (const durationSeconds of [0, 0.5, DEFAULT_SCENE_SECONDS, SCENE_MAX_SECONDS]) {
+ expect(valid({ durationSeconds }), `${durationSeconds}s`).toBe(true);
+ }
+ for (const durationSeconds of [-0.1, 15.1, 60]) {
+ expect(valid({ durationSeconds }), `${durationSeconds}s`).toBe(false);
+ }
+ expect(valid({ shots: [shot("a", 0, "x"), shot("b", 15, "y")] })).toBe(true);
+ expect(valid({ shots: [shot("a", 0, "x"), shot("b", 15.5, "y")] })).toBe(false);
+ expect(valid({ shots: [shot("a", 0, "x"), shot("b", -1, "y")] })).toBe(false);
+ // Two shots cannot share an id; every edit the editor makes addresses one.
+ expect(valid({ shots: [shot("a", 0, "x"), shot("a", 2, "y")] })).toBe(false);
+ // A scene keeps its words on its shots, so the mirror may be blank — a job
+ // with no shots may not, because there the mirror is the only copy.
+ expect(valid({ prompt: "", creativeBrief: "" })).toBe(true);
+ expect(valid({ prompt: "", creativeBrief: "", shots: null })).toBe(false);
+ expect(formatSceneSeconds(3)).toBe("3");
+ expect(formatSceneSeconds(4.5)).toBe("4.5");
+ });
+
+ it("keeps the scene fixture readable by both validators, in both directions", () => {
+ // The frontend's own file and the bytes Rust really wrote for it.
+ expect(parseProjectConfig(sceneFixture)).toBeTruthy();
+ expect(parseProjectConfig(wireScene)).toEqual(wireScene);
+ // Rust writes floats; the shapes still line up field for field.
+ expect(parseProjectConfig(wireScene).generationJobs[0].shots).toEqual(
+ parseProjectConfig(sceneFixture).generationJobs[0].shots,
+ );
+ });
+});