Skip to content

AI media harness for planning, generating, and editing locally

TypeScript
52.7 KB
Raw Blame
import { describe, expect, it } from "vitest";
import completeFixture from "../../fixtures/project-v1-complete.json";
import createdFixture from "../../fixtures/project-v1-created.json";
import externalFixture from "../../fixtures/project-v1-external-media.json";
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 { outputDimensions } from "./export";
import {
  compileMiniMaxH3Prompt,
  createProjectConfig,
  deriveH3Style,
  isExternalItem,
  isReferenceUsable,
  normalizeProjectPath,
  normalizeTimelineTracks,
  parseProjectConfig,
  projectFilePath,
  projectItemPath,
  projectNameFromPrompt,
  projectReferenceSchema,
  resolutionSchema,
  roundClipTransform,
  seedProjectWorkspace,
  LEGACY_RESOLUTIONS,
  PROJECT_RESOLUTIONS,
  STORY_TRACK_ID,
  usableImageReferences,
  usableReferenceImages,
  actionReferenceIds,
  compileGenerationJobPrompt,
  compileGenerationJobSegments,
  createDraftGenerationJob,
  danglingReferenceTokens,
  formatSceneSeconds,
  generationJobSchema,
  referenceToken,
  sceneBriefText,
  sceneDurationSeconds,
  sceneGenerationReferences,
  sceneFrameInputs,
  sceneShots,
  splitActionText,
  type ProjectConfig,
  DEFAULT_SCENE_SECONDS,
  DEFAULT_GENERATION_STEPS,
  RANDOM_GENERATION_SEED,
  SCENE_MAX_SECONDS,
  LEGACY_PROJECT_FILE_NAMES,
  PROJECT_FILE_NAME,
  type ProjectReference,
} from "./project";

it("inherits the project Look only when the scene has no explicit Look", () => {
  const config = createProjectConfig({ name: "Looks", prompt: "A forest", aspectRatio: "16:9", resolution: "768p", targetDurationSeconds: 0, defaultLook: "watercolor" });
  const restored = parseProjectConfig(JSON.parse(JSON.stringify(config)));
  const job = restored.generationJobs[0];
  expect(compileGenerationJobPrompt(job, [], restored.settings.defaultLook)).toContain("Watercolor");
  expect(sceneShots(job)[0].settings?.visualStyle).toBeUndefined();
  const explicit = { ...job, shots: sceneShots(job).map((shot) => ({ ...shot, settings: { visualStyle: ["claymation"] } })) };
  expect(compileGenerationJobPrompt(explicit, [], "watercolor")).toContain("Claymation");
  expect(compileGenerationJobPrompt(explicit, [], "watercolor")).not.toContain("Watercolor");
  expect(compileGenerationJobPrompt(job, [], null)).toBe(compileGenerationJobPrompt(job));
});
/** Regenerated by `cargo test` from the Rust validator's real output. */
const wireFixtures = {
  created: wireCreated,
  complete: wireComplete,
  initialReference: initialReferenceWire,
  externalMedia: wireExternal,
  scene: wireScene,
};

/** Body of one compiled section, for both prompt shapes: T2VA writes
 *  `name: value` on one line, full-reference mode writes `name:\nvalue`, and in
 *  both cases sections are separated by a blank line. */
const section = (compiled: string, name: string): string =>
  // No "m" flag on purpose: detailed_description spans two lines, and a
  // multiline `$` would end the capture at the first line break.
  compiled.match(new RegExp(`(?:^|\\n\\n)${name}:[ \\n]([\\s\\S]*?)(?=\\n\\n|$)`))?.[1] ?? "";

const now = "2026-01-01T00:00:00.000Z";
const textReference = (over: Partial<ProjectReference> = {}): ProjectReference => projectReferenceSchema.parse({
  id: "ref-1", kind: "text", name: "Mara", description: "Calm architect in charcoal wool.",
  intendedUse: ["character"], createdAt: now, ...over,
});
const imageReference = (over: Partial<ProjectReference> = {}): ProjectReference => projectReferenceSchema.parse({
  id: "ref-img", kind: "image", name: "Harbor facade", description: "Pale stone fins.",
  relativePath: "references/harbor.jpg", intendedUse: ["location"], createdAt: now, ...over,
});

describe("project schema", () => {
  it("rounds editable clip transforms to two decimal places", () => {
    expect(roundClipTransform({ scale: 123.4567, rotation: -8.7654, positionX: 0.005, positionY: -0.004 }))
      .toEqual({ scale: 123.46, rotation: -8.77, positionX: 0.01, positionY: 0 });
  });

  it("creates a versioned, validated project", () => {
    const project = createProjectConfig({
      name: "Launch film",
      prompt: "A tactile product launch",
      aspectRatio: "16:9",
      resolution: "4k",
      targetDurationSeconds: 45,
    });
    expect(parseProjectConfig(project)).toEqual(project);
    expect(project.schemaVersion).toBe(1);
    expect(project.generationType).toBe("video");
    // Three audiovisual layers, numbered rather than named after a job:
    // the seed says where a track sits, not what the user must put on it.
    expect(project.timeline.tracks.map((track) => track.name)).toEqual(["Track 1", "Track 2", "Track 3"]);
    expect(project.timeline.tracks.map((track) => track.kind)).toEqual(["video", "video", "video"]);
    // GeneratorView inserts generated shots by id. Renaming the tracks must
    // not move that target off the first video track.
    expect(project.timeline.tracks[0].id).toBe(STORY_TRACK_ID);
    expect(project.timeline.tracks.every((track) => track.clips.length === 0)).toBe(true);
    expect(project.references).toEqual([]);
    expect(project.generationJobs).toHaveLength(1);
    expect(project.generationJobs[0].creativeBrief).toBe("A tactile product launch");
    expect(project.generationJobs[0].status).toBe("draft");
    expect(project).not.toHaveProperty("agentConversation");
    expect(project.providerSettings).toEqual({});
  });

  it("defaults legacy projects to video and writes their type on the next save", () => {
    expect(createdFixture).not.toHaveProperty("generationType");
    const migrated = parseProjectConfig(createdFixture);
    expect(migrated.generationType).toBe("video");
    expect(JSON.parse(JSON.stringify(migrated)).generationType).toBe("video");
  });

  it.each(["video", "image", "3d", "music", "speech"])("preserves the %s project type through JSON", (generationType) => {
    const project = parseProjectConfig({ ...createdFixture, generationType });
    expect(project.generationType).toBe(generationType);
    expect(parseProjectConfig(JSON.parse(JSON.stringify(project)))).toEqual(project);
  });

  it.each([null, "", "unknown", "Video", 3])("rejects an invalid explicit project type: %s", (generationType) => {
    expect(() => parseProjectConfig({ ...createdFixture, generationType })).toThrow();
  });

  it("migrates legacy audio lanes onto canonical numbered tracks", () => {
    const base = createProjectConfig({
      name: "Legacy edit", prompt: "", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30,
    });
    const legacy = {
      ...base,
      timeline: { tracks: [
        base.timeline.tracks[0],
        { id: "track-music", kind: "audio" as const, name: "Music", locked: false, muted: false, clips: [] },
        { id: "track-voice", kind: "audio" as const, name: "Voice-over", locked: false, muted: true, clips: [] },
      ] },
    };
    const migrated = parseProjectConfig(legacy);
    expect(migrated.timeline.tracks.map((track) => track.name)).toEqual(["Track 1", "Track 2", "Track 3"]);
    expect(migrated.timeline.tracks.map((track) => track.kind)).toEqual(["video", "video", "video"]);
    expect(migrated.timeline.tracks[2].muted).toBe(true);
  });

  it("persists clip transforms, looks, and transitions while old clips keep defaults", () => {
    const project = createProjectConfig({
      name: "Treated cut",
      prompt: "A graded product cut",
      aspectRatio: "16:9",
      resolution: "1080p",
      targetDurationSeconds: 30,
    });
    project.timeline.tracks[0].clips.push({
      id: "clip-treated",
      assetId: "asset-a",
      trackId: STORY_TRACK_ID,
      startMs: 0,
      durationMs: 2_000,
      sourceStartMs: 0,
      label: "Treated",
      color: null,
      status: "approved",
      transform: { scale: 115, rotation: -4, positionX: 8, positionY: -3 },
      look: { opacity: 72 },
      transition: { type: "wipe-left", durationMs: 600 },
    });

    expect(parseProjectConfig(project).timeline.tracks[0].clips[0]).toMatchObject({
      transform: { scale: 115, rotation: -4, positionX: 8, positionY: -3 },
      look: { opacity: 72 },
      transition: { type: "wipe-left", durationMs: 600 },
    });
  });

  it("compiles the initial brief into exactly the three MiniMax H3 core fields", () => {
    const project = createProjectConfig({
      name: "Launch film",
      prompt: "A tactile product launch with rain and close macro camera moves",
      aspectRatio: "16:9",
      resolution: "1080p",
      targetDurationSeconds: 30,
    });
    const job = project.generationJobs[0];
    const compiled = compileGenerationJobPrompt(job);
    expect(job.creativeBrief).toBe(project.brief.prompt);
    expect(job).not.toHaveProperty("compiledPrompt");
    expect(compiled.match(/^[a-z_]+:/gm)).toEqual([
      "integrated_multimodal_description:",
      "overall_soundscape:",
      "non_diegetic_music:",
    ]);
    expect(compiled).toContain(project.brief.prompt);
    // Base guide §4.1: [Shot 1] opens with the style, and carries no timestamp (§4.2).
    expect(compiled).toMatch(/integrated_multimodal_description: \[Shot 1\] Live-action, cinematic, /);
    expect(compiled).not.toMatch(/\[Shot 1\] At \d/);
    // §4.7: no abstract mood words or statements of emotional function.
    expect(compiled).toContain("non_diegetic_music: N/A");
  });

  it("selects the H3 style from the user's own words rather than inventing one", () => {
    // Base guide §4.1: "for T2VA, select it from the user's text".
    expect(deriveH3Style("A watercolour short about a heron")).toBe("Watercolor");
    expect(deriveH3Style("A 2D animated title sequence")).toBe("2D-animated");
    expect(deriveH3Style("A claymation breakfast scene")).toBe("Claymation");
    expect(deriveH3Style("A documentary about harbour pilots")).toBe("Live-action, documentary");
    expect(deriveH3Style("A quiet lighthouse at dawn")).toBe("Live-action, cinematic");
  });

  it("switches to the six-section full-reference shape when references are bound", () => {
    const reference = (over: Partial<ProjectReference>): ProjectReference => projectReferenceSchema.parse({
      id: "ref-1", kind: "text", name: "Mara", description: "Calm architect in charcoal wool.",
      intendedUse: ["character"], createdAt: new Date().toISOString(), ...over,
    });
    const image = reference({ id: "ref-2", kind: "image", name: "Harbor facade", relativePath: "references/harbor.jpg", description: "Pale stone fins." });
    const compiled = compileMiniMaxH3Prompt("A quiet lighthouse at dawn", [image, reference({})]);

    // Ref guide §1: six sections, this exact order. detailed_description
    // REPLACES integrated_multimodal_description (§5.2).
    expect(compiled.match(/^[a-z_]+:/gm)).toEqual([
      "subject_definitions:",
      "summary:",
      "retention_analysis:",
      "detailed_description:",
      "overall_soundscape:",
      "non_diegetic_music:",
    ]);
    expect(compiled).not.toContain("integrated_multimodal_description");

    // §2.2: an image defining a character/scene/style is cited INSIDE its
    // <Subject N> line and never becomes a standalone <Picture N> entry.
    expect(compiled).toContain("<Subject 1> is the content shown in <Picture 1>. Pale stone fins.");
    expect(compiled).not.toMatch(/^<Picture \d+> is /m);
    // A text reference has no asset, so it cites no picture.
    expect(compiled).toContain("<Subject 2>: Calm architect in charcoal wool.");
    // The library label is never asserted as the subject's identity.
    expect(compiled).not.toContain("Harbor facade");
    expect(compiled).not.toContain("Mara");

    // §3: task-type prefix; no <Audio N> because no audio asset exists (§2.4).
    expect(compiled).toContain("summary:\n[reference generation] ");
    expect(compiled).not.toContain("<Audio");

    // §4.1: fixed relationship markers, one line per label. §5.4: no (Sx) here.
    expect(compiled).toContain("<Subject 1> (appears in [Shot 1]): fully_preserved - ");
    expect(compiled).toContain("<Subject 2> (appears in [Shot 1]): fully_preserved - ");

    // §5.2: the style opening precedes [Shot 1] in full-reference mode.
    expect(compiled).toMatch(/detailed_description:\nThe target video is in a live-action, cinematic style\.\n\[Shot 1\] /);
  });

  it("numbers <Picture N> in the order the engine consumes reference_paths", () => {
    // slopfab.rs iterates reference_paths sequentially, so index 0 is <Picture 1>.
    const img = (id: string, name: string, path: string): ProjectReference => projectReferenceSchema.parse({
      id, kind: "image", name, description: "A reference.", relativePath: path,
      intendedUse: ["style"], createdAt: new Date().toISOString(),
    });
    const first = img("a", "Alpha", "references/a.jpg");
    const second = img("b", "Beta", "references/b.jpg");
    const compiled = compileMiniMaxH3Prompt("A shot", [first, second]);
    expect(compiled).toContain("<Subject 1> is the content shown in <Picture 1>.");
    expect(compiled).toContain("<Subject 2> is the content shown in <Picture 2>.");
    expect(compiled).not.toContain("Alpha");
    expect(compiled).not.toContain("Beta");
    expect(usableImageReferences([first, second]).map((r) => r.relativePath)).toEqual([
      "references/a.jpg", "references/b.jpg",
    ]);
  });

  it("ignores blank references so they cannot take a binding slot", () => {
    const blank = projectReferenceSchema.parse({
      id: "blank", kind: "text", name: "New definition", description: "",
      intendedUse: ["style"], createdAt: new Date().toISOString(),
    });
    expect(isReferenceUsable(blank)).toBe(false);
    // With only a blank reference, the prompt stays in T2VA shape.
    expect(compileMiniMaxH3Prompt("A shot", [blank])).toContain("integrated_multimodal_description:");
  });

  it("terminates the brief so it cannot fuse into the sentence that follows", () => {
    const compiled = compileMiniMaxH3Prompt(
      "a cat walking across a sunny kitchen floor",
      [imageReference(), textReference()],
    );
    // summary: "... floor <Subject 1> and <Subject 2> provide ..." was one
    // fused sentence before the terminal stop was added.
    const summary = section(compiled, "summary");
    expect(summary).not.toContain("floor <Subject 1>");
    expect(summary).toContain("floor. <Subject 1>");
    // detailed_description: "... floor The shot features ..." likewise.
    const detailed = section(compiled, "detailed_description");
    expect(detailed).not.toContain("floor The shot features");
    expect(detailed).toContain("floor. The shot features");
  });

  it("never gives an already-punctuated brief a second terminal mark", () => {
    for (const [brief, tail] of [
      ["A cat naps on the sill.", "sill."],
      ["Watch the cat leap!", "leap!"],
      ["Where did the cat go?", "go?"],
      ["The cat pauses…", "pauses…"],
    ]) {
      const compiled = compileMiniMaxH3Prompt(brief, [textReference()]);
      expect(section(compiled, "summary")).toContain(`${tail} <Subject 1>`);
      expect(section(compiled, "detailed_description")).toContain(`${tail} The shot features`);
      expect(compiled).not.toContain(`${tail}.`);
    }
  });

  it("keeps the default soundscape free of any ambience the user never described", () => {
    // Base guide §4.6: N/A only on an explicit request for silence, so a line
    // must still be emitted — but it may not invent a place or a weather.
    const soundscape = section(compileMiniMaxH3Prompt("a rocket launch over the ocean"), "overall_soundscape");
    expect(soundscape.trim().length).toBeGreaterThan(0);
    expect(soundscape.trim()).not.toBe("N/A");
    for (const invented of ["room tone", "wind", "rain", "traffic", "birds", "indoor", "street"]) {
      expect(soundscape.toLowerCase()).not.toContain(invented);
    }
  });

  it("never compiles an audio-tagged reference as a visible subject", () => {
    // Ref guide §2.1: <Subject N> is VISIBLE content, so a note about sound is
    // dropped rather than announced on screen — and no <Audio N> is invented
    // for it either (§2.5).
    const audioOnly = textReference({ id: "ref-score", name: "Score idea", description: "Sparse piano.", intendedUse: ["audio"] });
    const compiled = compileMiniMaxH3Prompt("A quiet lighthouse at dawn", [audioOnly]);
    expect(compiled).not.toContain("<Subject");
    expect(compiled).not.toContain("<Audio");
    expect(compiled).not.toContain("Score idea");
    expect(compiled).not.toContain("Sparse piano");
    // With no usable visual reference left, the prompt falls back to T2VA.
    expect(compiled.match(/^[a-z_]+:/gm)).toEqual([
      "integrated_multimodal_description:",
      "overall_soundscape:",
      "non_diegetic_music:",
    ]);
  });

  it("still compiles a reference that carries a visual tag alongside audio", () => {
    const narrator = textReference({ id: "ref-narrator", name: "Narrator", description: "On-camera, warm low voice.", intendedUse: ["character", "audio"] });
    const compiled = compileMiniMaxH3Prompt("A quiet lighthouse at dawn", [narrator]);
    expect(compiled).toContain("<Subject 1>: On-camera, warm low voice.");
    expect(compiled).toContain("<Subject 1> (appears in [Shot 1]): fully_preserved - ");
  });

  it("drops an audio-tagged image from both the prompt and reference_paths together", () => {
    // The two filters must agree: GeneratorView builds referencePaths from
    // usableImageReferences while the prompt numbers <Picture N> from the
    // compiler's list, and slopfab.rs consumes the array positionally.
    const audioImage = imageReference({ id: "img-audio", name: "Waveform note", relativePath: "references/waveform.png", intendedUse: ["audio"] });
    const visualImage = imageReference({ id: "img-visual", name: "Harbor facade", relativePath: "references/harbor.jpg", intendedUse: ["location"] });
    const references = [audioImage, visualImage];

    expect(usableImageReferences(references).map((reference) => reference.id)).toEqual(["img-visual"]);
    const compiled = compileMiniMaxH3Prompt("A shot", references);
    expect(compiled).toContain("<Subject 1> is the content shown in <Picture 1>.");
    expect(compiled).not.toContain("<Picture 2>");
    expect(compiled).not.toContain("<Subject 2>");
    expect(compiled).not.toContain("Waveform note");
  });

  it("keeps canonical style casing in the detailed-description opening", () => {
    // Base guide §4.1 names them "3D CG" and "2D-animated"; toLowerCase()
    // turned those into "3d cg" and "2d-animated".
    expect(deriveH3Style("A 3D CGI creature short")).toBe("3D CG");
    expect(compileMiniMaxH3Prompt("A 3D CGI creature short", [textReference()]))
      .toContain("The target video is in a 3D CG style.");
    expect(deriveH3Style("A 2D anime chase across rooftops")).toBe("2D-animated");
    expect(compileMiniMaxH3Prompt("A 2D anime chase across rooftops", [textReference()]))
      .toContain("The target video is in a 2D-animated style.");
  });

  it("accepts the real bytes the Rust validator writes, for every generated wire fixture", () => {
    // The other half of a contract that used to be checked by remembering: a
    // Rust test regenerates these three files from validate_and_normalize_config
    // on every `cargo test`, and this parses them with the real zod schema. A
    // field added on one side with the wrong optionality now fails here instead
    // of waiting to be noticed — which is how the last blocking bug survived
    // nine rounds. A diff in `git status` after cargo test means the wire
    // format moved and this test is the frontend's verdict on it.
    for (const [name, wire] of Object.entries(wireFixtures)) {
      // Deep equality, not a hand-maintained key list. This closes THREE
      // directions at once and needs no upkeep:
      //   - a null reaching a field zod spells bare `.optional()` throws here;
      //   - a field Rust writes that zod does not know is silently STRIPPED by
      //     the non-strict schema, so `parsed` loses it and this comparison
      //     fails — previously nothing caught that, and the frontend would then
      //     re-save and quietly drop the field from the user's file;
      //   - a default zod applies that Rust does not send shows up as an added
      //     key and fails too.
      // The previous version listed five key names by hand, which is exactly
      // the kind of remembering this fixture pair was introduced to replace.
      expect(parseProjectConfig(wire), name).toEqual(wire);
    }
  });

  it("compiles a clean prompt from a reference the Rust import path really produced", () => {
    // Built by create_project_in_with_references against a real file on disk —
    // not a hand-written reference with a tidy name and description. Every
    // compiler test used to supply both by hand, which is exactly why an
    // imported image shipped its filename and a filing note to the model.
    const config = parseProjectConfig(initialReferenceWire);
    const imported = config.references.find((reference) => reference.kind === "image");
    expect(imported, "the Rust fixture must contain an imported image").toBeTruthy();
    expect(imported!.description).toBe("");

    const compiled = compileMiniMaxH3Prompt("a cat walking across a sunny kitchen floor", [imported!]);
    expect(compiled).toContain("<Subject 1> is the content shown in <Picture 1>.");
    expect(compiled).toContain("fully_preserved - the referenced characteristics are retained.");
    // The library label is the source file's stem. It is not a description and
    // must appear nowhere in the text sent to the model.
    expect(imported!.name.length).toBeGreaterThan(0);
    expect(compiled).not.toContain(imported!.name);
    expect(compiled).not.toContain("Visual reference");
  });

  it("accepts a freshly created project exactly as createProjectConfig writes it", () => {
    // 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
    // change that lands only in the TypeScript leaves the two layers testing
    // different projects. Compare the part that was seeded.
    const created = createProjectConfig({
      name: "Freshly created project",
      prompt: "a rocket launch over the ocean at dawn",
      aspectRatio: "16:9",
      resolution: "1080p",
      targetDurationSeconds: 60,
    });
    expect(createdFixture.timeline).toEqual(created.timeline);
  });

  it("accepts an explicit null for every optional the backend can serialise as null", () => {
    // Rust serialises Option::None as JSON null unless the field carries
    // skip_serializing_if, and zod's bare .optional() REJECTS null. That
    // mismatch made create_project, open_project and every recent-projects row
    // fail in the desktop app while the browser preview stayed green.
    const config = structuredClone(completeFixture) as Record<string, any>;
    config.assets[0].durationMs = null;
    config.assets[0].width = null;
    config.assets[0].height = null;
    config.timeline.tracks[0].clips[0].color = null;
    config.generationJobs[0].clipId = null;
    const parsed = parseProjectConfig(config);
    expect(parsed.assets[0].durationMs ?? null).toBeNull();
    expect(parsed.generationJobs[0].clipId ?? null).toBeNull();
    expect(parsed.timeline.tracks[0].clips[0].color ?? null).toBeNull();
  });

  it("still rejects a wrongly typed value in those same optional fields", () => {
    // Tolerating null must not turn into tolerating anything.
    for (const mutate of [
      (config: any) => { config.assets[0].width = 0; },
      (config: any) => { config.assets[0].durationMs = -1; },
      (config: any) => { config.generationJobs[0].clipId = ""; },
      (config: any) => { config.timeline.tracks[0].clips[0].color = 7; },
    ]) {
      const config = structuredClone(completeFixture) as any;
      mutate(config);
      expect(() => parseProjectConfig(config)).toThrow();
    }
  });

  it("keeps multiple pictures attached to one text reference and sends each one", () => {
    const reference = projectReferenceSchema.parse({
      id: "product", kind: "text", name: "Product", description: "Matte ceramic lamp.",
      images: [
        { id: "front", name: "Front", relativePath: "references/front.png" },
        { id: "side", name: "Side", relativePath: "references/side.png" },
      ],
      intendedUse: ["product"], createdAt: new Date().toISOString(),
    });
    expect(isReferenceUsable(reference)).toBe(true);
    expect(usableReferenceImages([reference]).map((image) => image.relativePath)).toEqual([
      "references/front.png", "references/side.png",
    ]);
    expect(compileMiniMaxH3Prompt("A shot", [reference]))
      .toContain("<Subject 1> is the content shown in <Picture 1> and <Picture 2>.");
  });

  it("ignores stale saved bindings and uses only current citations and explicit frame inputs", () => {
    const references = ["image", "video", "audio", "text"].map((kind) => projectReferenceSchema.parse({
      id: kind, kind, name: kind, description: "Guidance", intendedUse: [], createdAt: createdFixture.createdAt,
      ...(kind === "text" ? { refmods: [{ id: "mod", name: "Style", sourcePath: "C:/style.safetensors", strength: 1, copies: 1 }] }
        : { sourcePath: `C:/reference.${kind === "image" ? "png" : kind === "video" ? "mp4" : "wav"}` }),
    }));
    const job = createDraftGenerationJob(references.map(({ id }) => referenceToken(id)).join(" "), {
      referenceIds: references.map(({ id }) => id),
    });
    expect(sceneGenerationReferences(job, references)).toEqual(references);
    job.shots![0].action = "A quiet landscape.";
    expect(sceneGenerationReferences(job, references)).toEqual([]);
    job.startFrameReferenceId = "image";
    expect(sceneGenerationReferences(job, references).map(({ id }) => id)).toEqual(["image"]);
    job.startFrameReferenceId = undefined;
    job.referenceIds = [];
    job.shots![0].action = referenceToken("video");
    expect(sceneGenerationReferences(job, references).map(({ id }) => id)).toEqual(["video"]);
  });

  it("uses a dedicated image as Picture 1 and the scene's first frame", () => {
    const image = (id: string, name: string, path: string): ProjectReference => projectReferenceSchema.parse({
      id, kind: "image", name, description: "", relativePath: path,
      intendedUse: [], createdAt: new Date().toISOString(),
    });
    const opening = image("opening", "Opening still", "references/opening.jpg");
    const subject = image("subject", "Product", "references/product.jpg");
    const job = createDraftGenerationJob("@[ref:subject] turns towards camera.", {
      id: "scene-with-frame",
      references: [opening, subject],
      referenceIds: ["subject"],
      startFrameReferenceId: "opening",
    });
    const ordered = sceneGenerationReferences(job, [subject, opening]);
    const compiled = compileGenerationJobPrompt(job, ordered);

    expect(ordered.map((reference) => reference.id)).toEqual(["opening", "subject"]);
    expect(compiled).toContain("<Picture 1> is the first frame of the video.");
    expect(compiled).toContain("The video begins with <Picture 1>.");
    expect(compiled).toContain("The opening frame matches <Picture 1>.");
    expect(compiled).toContain("<Subject 1> is the content shown in <Picture 2>.");
    expect(compiled).not.toContain("<Subject 2>");
  });

  it("numbers opening, closing and subject pictures together, sending one image per frame anchor", () => {
    const image = (id: string): ProjectReference => projectReferenceSchema.parse({
      id, kind: "text", name: id, description: "", intendedUse: [], createdAt: createdFixture.createdAt,
      images: [1, 2].map((n) => ({ id: `${id}-${n}`, name: id, relativePath: `references/${id}-${n}.png` })),
    });
    const references = [image("subject"), image("end"), image("start")];
    const job = createDraftGenerationJob("@[ref:subject] turns.", { startFrameReferenceId: "start", endFrameReferenceId: "end", referenceIds: ["subject", "start", "end"] });
    const ordered = sceneGenerationReferences(job, references);
    expect(usableReferenceImages(ordered).map((image) => image.relativePath)).toEqual([
      "references/start-1.png", "references/end-1.png", "references/subject-1.png", "references/subject-2.png",
    ]);
    const prompt = compileGenerationJobPrompt(job, ordered);
    expect(prompt).toContain("<Picture 1> is the first frame of the video.");
    expect(prompt).toContain("<Picture 2> is the last frame of the video.");
    expect(prompt).toContain("<Subject 1> is the content shown in <Picture 3> and <Picture 4>.");
    expect(prompt).toContain("<Picture 2>: last_frame - used as the closing frame.");
    expect(prompt).toContain("The closing frame matches <Picture 2>.");
    const endOnly = { ...job, startFrameReferenceId: undefined, referenceIds: [] };
    expect(compileGenerationJobPrompt(endOnly, sceneGenerationReferences(endOnly, references))).toContain("<Picture 1> is the last frame of the video.");
    const same = { ...job, shots: [{ id: "shot", startSeconds: 0, action: "The subject turns." }], endFrameReferenceId: "start", referenceIds: [] };
    expect(usableReferenceImages(sceneGenerationReferences(same, references))).toHaveLength(1);
    expect(compileGenerationJobPrompt(same, sceneGenerationReferences(same, references))).toContain("Picture 1 (from Shot 1) aligns with the 0.00-second mark of the target video; Picture 1 (from Shot 1) aligns with the");
  });

  it("resolves scene continuity from board order and the current latent archive", () => {
    const config = parseProjectConfig(createdFixture);
    const first = { ...config.generationJobs[0], latentRelativePath: "latents/work-first.safetensors" };
    const second = createDraftGenerationJob("Continue", { usePreviousSceneLastFrame: true });
    config.generationJobs = [first, second];
    const inputs = sceneFrameInputs(second, config);
    expect(inputs.previousSceneId).toBe(first.id);
    expect(inputs.continuationRelativePath).toBe("latents/work-first.safetensors");
    expect(usableReferenceImages(inputs.references)).toHaveLength(0);
    expect(compileGenerationJobPrompt(inputs.job, inputs.references)).not.toContain("is the first frame of the video.");
    first.latentRelativePath = "latents/work-rerendered.safetensors";
    expect(sceneFrameInputs(second, config).continuationRelativePath).toBe("latents/work-rerendered.safetensors");
    config.generationJobs.reverse();
    expect(sceneFrameInputs(second, config).previousSceneId).toBeUndefined();
  });

  it("allows a generated scene asset to wait for its render without relaxing imported media", () => {
    const waiting = structuredClone(createdFixture) as any;
    waiting.assets = [{
      id: "asset-job-initial-brief",
      kind: "generated",
      name: "First scene",
      relativePath: null,
      sourcePath: null,
      mimeType: "video/mp4",
      durationMs: 6000,
      width: null,
      height: null,
      createdAt: waiting.createdAt,
    }];
    expect(parseProjectConfig(waiting).assets[0].relativePath ?? null).toBeNull();

    waiting.assets[0].kind = "video";
    expect(() => parseProjectConfig(waiting)).toThrow(/must have either/);
  });

  it("resolves project-relative reference paths to absolute for the engine", () => {
    // Image references reach slopfab.rs verbatim, so the frontend resolves
    // these paths even though latents are resolved separately in the backend.
    expect(projectFilePath("C:\\Projects\\Lighthouse", "references/a.jpg")).toBe("C:\\Projects\\Lighthouse\\references\\a.jpg");
    expect(projectFilePath("/home/nn/lighthouse", "references/a.jpg")).toBe("/home/nn/lighthouse/references/a.jpg");
    expect(projectFilePath("/home/nn/lighthouse/", "references/a.jpg")).toBe("/home/nn/lighthouse/references/a.jpg");
  });

  it("keeps video and audio where they are, and resolves both kinds of location", () => {
    // The whole point of the external location: a 40 GB rush is referenced, not
    // duplicated into the project folder.
    const config = parseProjectConfig(externalFixture);
    const video = config.assets.find((asset) => asset.id === "asset-external-video")!;
    const image = config.assets.find((asset) => asset.id === "asset-copied-image")!;
    expect(video.relativePath ?? null).toBeNull();
    expect(video.sourcePath).toBe("D:\\tmp\\news\\News broadcast\\rush-01.mp4");
    expect(isExternalItem(video)).toBe(true);
    expect(isExternalItem(image)).toBe(false);

    // An external path is already absolute and must come back untouched; a
    // copied one resolves against the project folder. Resolving an external
    // clip against the folder would name a file that was never there.
    expect(projectItemPath("D:\\Projects\\News", video)).toBe("D:\\tmp\\news\\News broadcast\\rush-01.mp4");
    expect(projectItemPath("D:\\Projects\\News", image)).toBe("D:\\Projects\\News\\media\\title-card.png");
    expect(projectItemPath("D:\\Projects\\News", { relativePath: null, sourcePath: null })).toBeNull();

    // A reference behaves the same way: the image is copied in, the video is not.
    const externalReference = config.references.find((reference) => reference.kind === "video")!;
    expect(externalReference.sourcePath).toBe("\\\\studio-nas\\shared\\reference cut.mov");
    expect(config.references.find((reference) => reference.kind === "image")!.relativePath)
      .toBe("references/harbor facade.png");
    // Only images are sent to the engine, so a video reference is not one of
    // the <Picture N> assets however it is stored.
    expect(usableImageReferences(config.references).map((reference) => reference.id)).toEqual(["ref-copied-image"]);
  });

  it("accepts a project written before external media existed", () => {
    // Every asset in this fixture carries a relativePath and no sourcePath —
    // exactly what every project written by an earlier build looks like.
    const config = parseProjectConfig(completeFixture);
    expect(config.assets.every((asset) => asset.relativePath && !asset.sourcePath)).toBe(true);
  });

  it("refuses a location that is ambiguous, missing, or not absolute", () => {
    const withAsset = (over: Record<string, unknown>) => {
      const config = structuredClone(completeFixture) as any;
      config.assets[0] = { ...config.assets[0], ...over };
      return () => parseProjectConfig(config);
    };
    // Both at once: nothing downstream could say which file is meant.
    expect(withAsset({ sourcePath: "D:\\Footage\\clip.mp4" })).toThrow();
    // Neither: an asset with no file is not an asset.
    expect(withAsset({ relativePath: null, sourcePath: null })).toThrow();
    // A relative "external" path resolves against nothing at all.
    for (const path of ["Footage\\clip.mp4", "media/clip.mp4", "..\\..\\clip.mp4", "D:\\..\\clip.mp4", ""]) {
      expect(withAsset({ relativePath: null, sourcePath: path }), path).toThrow();
    }
    // The three absolute forms are accepted on every platform: a project file
    // written on Windows is still read on Linux and back.
    for (const path of ["D:\\Footage\\clip.mp4", "D:/Footage/clip.mp4", "/home/nn/clip.mp4", "\\\\nas\\share\\clip.mp4"]) {
      expect(withAsset({ relativePath: null, sourcePath: path })(), path).toBeTruthy();
    }
    // And a reference cannot claim both either.
    const bothOnReference = structuredClone(completeFixture) as any;
    bothOnReference.references[1] = { ...bothOnReference.references[1], sourcePath: "D:\\Footage\\ref.png" };
    expect(() => parseProjectConfig(bothOnReference)).toThrow();
  });

  it("names the settings file slopus.json and remembers what it used to be", () => {
    expect(PROJECT_FILE_NAME).toBe("slopus.json");
    // Both older names still open a project (project_file_in, Rust side); only
    // the current one is ever written.
    expect(LEGACY_PROJECT_FILE_NAMES).toEqual(["polstudio.json", "pols.json", "polstudio.project.json"]);
    expect(LEGACY_PROJECT_FILE_NAMES).not.toContain(PROJECT_FILE_NAME);
  });

  it("parses the complete cross-layer fixture while dropping derived project state", () => {
    const expected = structuredClone(completeFixture) as Record<string, unknown>;
    expected.generationType = "video";
    delete expected.agentConversation;
    for (const job of expected.generationJobs as Array<Record<string, unknown>>) delete job.compiledPrompt;
    const expectedTimeline = expected.timeline as { tracks: ProjectConfig["timeline"]["tracks"] };
    expected.timeline = { tracks: normalizeTimelineTracks(expectedTimeline.tracks) };
    expect(parseProjectConfig(completeFixture)).toEqual(expected);
  });

  it("normalizes portable paths to project-root relative forward slashes", () => {
    expect(normalizeProjectPath("./media\\imported//clip.mp4")).toBe("media/imported/clip.mp4");
    const config = structuredClone(completeFixture);
    config.assets[0].relativePath = "media\\imported\\macro.mp4";
    expect(parseProjectConfig(config).assets[0].relativePath).toBe("media/imported/macro.mp4");
  });

  it.each([
    "/etc/passwd",
    "\\Windows\\system.ini",
    "C:\\Users\\creator\\clip.mp4",
    "https://example.com/clip.mp4",
    "media/../../outside.mp4",
    "references/../outside.png",
  ])("rejects escaping stored path %s", (relativePath) => {
    const config = structuredClone(completeFixture);
    config.assets[0].relativePath = relativePath;
    expect(() => parseProjectConfig(config)).toThrow();
  });

  it("applies path containment to every stored path field", () => {
    const thumbnail = structuredClone(completeFixture);
    thumbnail.thumbnail = "../thumbnail.webp";
    const reference = structuredClone(completeFixture);
    reference.references[1].relativePath = "../product.png";
    const job = structuredClone(completeFixture);
    job.generationJobs[0].outputRelativePath = "C:\\output.mp4";
    for (const config of [thumbnail, reference, job]) {
      expect(() => parseProjectConfig(config)).toThrow();
    }
  });

  it("rejects unknown schema versions", () => {
    expect(() => parseProjectConfig({ schemaVersion: 99 })).toThrow();
  });

  it("derives a compact working title", () => {
    expect(projectNameFromPrompt("Create a cinematic film about a midnight train through Europe")).toBe(
      "Cinematic film about a midnight train through",
    );
  });

  it("seeds a portable, screenshot-ready editing workspace", () => {
    const project = seedProjectWorkspace(createProjectConfig({
      name: "Northern Light",
      prompt: "A brand film about humane architecture",
      aspectRatio: "16:9",
      resolution: "4k",
      targetDurationSeconds: 34,
    }));
    expect(project.timeline.tracks).toHaveLength(3);
    expect(project.timeline.tracks.map((track) => track.name)).toEqual(["Track 1", "Track 2", "Track 3"]);
    // Every demo clip has to land on a track that is actually in the seed.
    const trackIds = new Set(project.timeline.tracks.map((track) => track.id));
    expect(project.timeline.tracks.flatMap((track) => track.clips).every((clip) => trackIds.has(clip.trackId))).toBe(true);
    expect(project.generationJobs.some((job) => job.status === "generating")).toBe(true);
    expect(project.references.some((reference) => reference.kind === "image")).toBe(true);
    // The seeded workspace is entirely project-owned: every asset is a file
    // inside the folder, none of them points outside it.
    expect(project.assets.every((asset) => !asset.sourcePath)).toBe(true);
    expect(project.assets.every((asset) => !asset.relativePath?.match(/^([a-z]:|[/\\])/i))).toBe(true);
    expect(project.generationJobs.filter((job) => job.outputRelativePath).every((job) => !job.outputRelativePath!.match(/^([a-z]:|[/\\])/i))).toBe(true);
  });
});

describe("the frame sizes a project can be", () => {
  it("accepts exactly the ladder plus the names already on disk, and nothing else", () => {
    /* `is_supported_resolution` in src-tauri/src/project/validation/values.rs spells the same
       names. They have to agree in BOTH directions: Rust writes the settings
       file before the frontend ever parses it, so a name Rust accepts and zod
       refuses is saved and then fails to open (see CLAUDE.md). */
    expect(resolutionSchema.options).toEqual([...PROJECT_RESOLUTIONS, ...LEGACY_RESOLUTIONS]);
    expect(resolutionSchema.options).toEqual([
      "416p", "544p", "640p", "768p", "1088p", "1344p", "1536p", "2048p", "720p", "1080p", "4k",
    ]);
    for (const rejected of ["8k", "480p", "1080P", "768", ""]) {
      expect(resolutionSchema.safeParse(rejected).success).toBe(false);
    }
  });

  it("gives every name the schema accepts a frame size in every shape", () => {
    /* The two lists live in different files — the names in project.ts, the
       pixels in export.ts — and TypeScript only pins the table's KEYS to the
       type. A name added to the schema alone would reach `outputDimensions` as
       an undefined row and throw on the export screen, not here. */
    for (const resolution of resolutionSchema.options) {
      for (const ratio of ["16:9", "9:16", "1:1", "4:5"] as const) {
        const { width, height } = outputDimensions(resolution, ratio);
        expect(Number.isInteger(width) && width > 0).toBe(true);
        expect(Number.isInteger(height) && height > 0).toBe(true);
      }
    }
  });

  it("creates a project at the size it was asked for, with the brief agreeing", () => {
    const config = createProjectConfig({
      name: "Ladder", prompt: "A quiet product film", aspectRatio: "9:16", resolution: "416p", targetDurationSeconds: 15,
    });
    expect(config.settings.resolution).toBe("416p");
    // The brief carries its own copy and the two must not drift apart.
    expect(config.brief.resolution).toBe("416p");
    expect(outputDimensions(config.settings.resolution, config.settings.aspectRatio)).toEqual({ width: 416, height: 736 });
  });
});

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.5, "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] At 00:03.500, she stops at the doorway.");
    expect(compiled).toContain("[Shot 3] At 00:06.500, 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] At ");
    // 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("keeps shot speech inside MiniMax dialogue tags with its selected language", () => {
    const firstLine = "行こう! Keep the punctuation, exactly.";
    const secondLine = "I will meet you there.";
    const job = createDraftGenerationJob("", {
      id: "scene-dialogue", title: "Dialogue", now, durationSeconds: 6,
      shots: [
        { id: "dialogue-a", startSeconds: 0, action: "She turns toward the doorway", speech: firstLine, speechLanguage: "Japanese" },
        { id: "dialogue-b", startSeconds: 3, action: "The camera follows", speech: secondLine },
      ],
    });

    for (const compiled of [compileGenerationJobPrompt(job), compileGenerationJobPrompt(job, [imageReference()])]) {
      expect(compiled).toContain(`The scene's speaker (S1) says, <d>[Japanese] ${firstLine}</d>`);
      expect(compiled).toContain(`The scene's speaker (S1) says, <d>[English] ${secondLine}</d>`);
      // The full-reference summary must not repeat spoken words without tags.
      expect(compiled.split(firstLine)).toHaveLength(2);
      expect(compiled.split(secondLine)).toHaveLength(2);
    }

    expect(sceneShots(job)[0]).toEqual(expect.objectContaining({ speech: firstLine, speechLanguage: "Japanese" }));
    expect(generationJobSchema.parse(job)).toEqual(job);
  });

  it("omits an empty speech field from the compiled prompt", () => {
    const job = createDraftGenerationJob("A silent look", {
      id: "scene-silent", title: "Silent", now,
      shots: [{ id: "silent-a", startSeconds: 0, action: "A silent look", speech: "   ", speechLanguage: "French" }],
    });
    expect(compileGenerationJobPrompt(job)).not.toContain("<d>");
    expect(compileGenerationJobPrompt(job)).not.toContain("(S1)");
  });

  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
    // names nobody, so nothing claims it features anyone, and shot 3 names only
    // the street.
    expect(compiled).toContain("<Subject 1> (appears in [Shot 1]): fully_preserved");
    expect(compiled).toContain("<Subject 2> (appears in [Shot 1], [Shot 3]): fully_preserved");
    expect(compiled).toContain("[Shot 2] At 00:04.500, Medium close-up, she stops at a doorway and looks up.\n");
    // 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("defaults new scenes to 20 steps and a random seed marker", () => {
    const job = createDraftGenerationJob("A slow push towards the doorway.");
    expect(job.steps).toBe(DEFAULT_GENERATION_STEPS);
    expect(job.seed).toBe(RANDOM_GENERATION_SEED);
    expect(generationJobSchema.safeParse({ ...job, steps: 1 }).success).toBe(false);
    expect(generationJobSchema.safeParse({ ...job, seed: -2 }).success).toBe(false);
  });

  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,
    );
  });
});