AI media harness for planning, generating, and editing locally
TypeScript
Move timeline cases out of the workspace tests
Bittiba525e216e0e
diff --git a/src/components/ProjectWorkspace.test.ts b/src/components/ProjectWorkspace.test.tsindex ef68b27..45e2f43 100644--- a/src/components/ProjectWorkspace.test.ts+++ b/src/components/ProjectWorkspace.test.ts@@ -4,17 +4,16 @@ import "@testing-library/jest-dom/vitest";import { act, cleanup, createEvent, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { listen } from "@tauri-apps/api/event";-import { createElement, useEffect, useState } from "react";+import { createElement } from "react";import { afterEach, describe, expect, it, vi } from "vitest";import completeFixture from "../../fixtures/project-v1-complete.json";-import { compileMiniMaxH3Prompt, createProjectConfig, parseProjectConfig, sceneShots, STORY_TRACK_ID, UNTITLED_SCENE, type GenerationJob, type ProjectAsset, type ProjectConfig, type ProjectRecord, type TimelineClip } from "../lib/project";+import { compileMiniMaxH3Prompt, createProjectConfig, parseProjectConfig, sceneShots, UNTITLED_SCENE, type GenerationJob, type ProjectConfig, type ProjectRecord } from "../lib/project";import { saveGeneratedScene } from "../lib/generatedVideo";import { formatDurationTimecode, isGenerationOngoing } 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";import { saveDebugOptionsEnabled } from "../lib/settings";vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));@@ -92,73 +91,6 @@ async function withFakeDecoder(file: { seconds: number; width: number; height: n}}-/** The same fake media stack as above, except that NOTHING settles on its own:- * each <video>/<audio> the panel opens waits here until the test lands it.- * That is what makes a staggered decode reproducible — two files finishing at- * their own speeds, with a render and a flush in between, which is the window- * the measurement race lives in and the reason a queue alone never closed it. */-async function withStagedDecoder(file: { seconds: number; width: number; height: number }, body: (stage: {- /** Resolves once the panel has opened at least this many media elements. */- opened: (count: number) => Promise<void>;- /** Land one decode: metadata arrives, the poster seek answers, effects run. */- settle: (index: number) => Promise<void>;-}) => Promise<void>) {- const { invoke } = await import("@tauri-apps/api/core");- (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__ = {};- vi.mocked(invoke).mockResolvedValue(new ArrayBuffer(8));- URL.createObjectURL = () => "blob:slopus-test";- URL.revokeObjectURL = () => undefined;- const media = HTMLMediaElement.prototype.load;- const canvas = HTMLCanvasElement.prototype.getContext;- HTMLMediaElement.prototype.load = () => undefined;- HTMLCanvasElement.prototype.getContext = () => null;- const create = document.createElement.bind(document);- const waiting: HTMLElement[] = [];- const spy = vi.spyOn(document, "createElement").mockImplementation((tag: string, options?: ElementCreationOptions) => {- const element = create(tag, options);- if (tag === "video" || tag === "audio") {- for (const [name, value] of [["duration", file.seconds], ["videoWidth", file.width], ["videoHeight", file.height]] as const) {- Object.defineProperty(element, name, { value, configurable: true });- }- let currentTime = 0;- Object.defineProperty(element, "currentTime", {- configurable: true,- get: () => currentTime,- set: (value: number) => { currentTime = value; setTimeout(() => element.dispatchEvent(new Event("seeked")), 0); },- });- waiting.push(element);- }- return element;- });- // One macrotask turn, with React's queues drained around it.- const turn = () => act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });- try {- await body({- opened: async (count) => {- for (let attempt = 0; attempt < 50 && waiting.length < count; attempt += 1) await turn();- if (waiting.length < count) throw new Error(`Only ${waiting.length} of ${count} files were opened.`);- },- settle: async (index) => {- const element = waiting[index];- await act(async () => {- element.dispatchEvent(new Event("loadeddata"));- element.dispatchEvent(new Event("loadedmetadata"));- });- // The poster seek answers on a timer of its own, and the flush that- // follows it is the write under test.- await turn();- await turn();- },- });- } finally {- spy.mockRestore();- HTMLMediaElement.prototype.load = media;- HTMLCanvasElement.prototype.getContext = canvas;- delete (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__;- vi.mocked(invoke).mockReset();- }-}-describe("the one definition of an ongoing generation", () => {it("is every status with something still to lose, and nothing else", () => {const statuses: GenerationJob["status"][] = ["draft", "queued", "generating", "ready", "completed", "failed", "cancelled"];@@ -364,7 +296,7 @@ describe("project workspace timecode", () => {project: { folderPath: "C:\\Ceramic Lamp", config }, initialView: "timeline",onBack: () => undefined, onSave: async () => undefined,}));- fireEvent.click(screen.getByRole("button", { name: "Add or generate a scene" }));+ fireEvent.click(screen.getByRole("button", { name: "Add scene" }));await screen.findByRole("heading", { name: "Generator" });// A new project already carries one draft made from the user's own words.// "Add or generate a scene" must open that, not stack a second near-identical@@ -387,25 +319,6 @@ describe("project workspace timecode", () => {expect(screen.queryByText("NORTHERN LIGHT")).toBeNull();});- /* jsdom has no DataTransfer, and the drop handler reads a custom type off it,- so the drag has to carry its own. Same contract as the browser's: setData- during dragstart, types visible during dragover, getData on drop. */- function fakeDataTransfer() {- const data: Record<string, string> = {};- return {- dropEffect: "none", effectAllowed: "all",- types: [] as string[],- setData(type: string, value: string) { data[type] = value; this.types.push(type); },- getData(type: string) { return data[type] ?? ""; },- };- }-- /** What a view actually wrote. The timeline hands up UPDATERS rather than- * finished configs (see ConfigUpdate), so reading a call means applying it- * to the config the view was holding at the time. */- const wrote = (call: unknown, current: ProjectConfig): ProjectConfig =>- typeof call === "function" ? (call as (value: ProjectConfig) => ProjectConfig)(current) : call as ProjectConfig;-/** A project carrying one importable clip of each kind, so the media panel* has a card that belongs on a video track and one that belongs on audio. */function projectWithMedia(): ProjectConfig {@@ -419,604 +332,6 @@ describe("project workspace timecode", () => {}] });}- /** The lane for the first track of this kind, and the card for that asset. */- const laneAt = (container: HTMLElement, index: number) => container.querySelectorAll(".track-lane")[index];- const cardFor = (asset: ProjectAsset) => screen.getByTitle(new RegExp(`^${asset.name} —`));-- function mediaPanel(config: ProjectConfig, onChange = vi.fn()) {- const view = render(createElement(TimelineView, { config, folderPath: "C:\Ceramic Lamp", onChange, onOpenGenerator: () => undefined }));- fireEvent.click(screen.getByRole("button", { name: "Media" }));- return { ...view, onChange };- }-- it("switches the media panel between grid and list, and remembers which", () => {- localStorage.removeItem("slopus.media-layout.v1");- const { container } = mediaPanel(projectWithMedia());- expect(container.querySelector(".media-grid--grid")).not.toBeNull();- fireEvent.click(screen.getByRole("button", { name: "List" }));- expect(container.querySelector(".media-grid--list")).not.toBeNull();- expect(container.querySelector(".media-grid--grid")).toBeNull();- // The choice is a habit, not a per-project setting: it outlives the mount.- cleanup();- const second = mediaPanel(projectWithMedia());- expect(second.container.querySelector(".media-grid--list")).not.toBeNull();- });-- it("keeps imported media in Media and lists Generator scenes even before generation", () => {- const base = projectWithMedia();- const config = parseProjectConfig({ ...base, timeline: { tracks: base.timeline.tracks.map((track) => track.id === STORY_TRACK_ID ? { ...track, clips: [{- id: "clip-macro", assetId: "asset-macro", trackId: track.id, startMs: 0, durationMs: 5000, sourceStartMs: 0, label: "Macro footage", color: null, status: "approved",- }] } : track) } });- const { container } = render(createElement(TimelineView, { config, folderPath: "C:\\Ceramic Lamp", onChange: () => undefined, onOpenGenerator: () => undefined }));-- expect(container.querySelector(".scene-list")!.textContent).toContain("First scene");- expect(container.querySelector(".scene-list")!.textContent).not.toContain("Macro footage");- expect(container.querySelector(".scene-list")!.textContent).not.toContain("Not rendered yet");- expect(container.querySelector(".scene-card__thumb")).not.toBeNull();- expect(container.querySelector(".scene-card__thumb .shot-thumb")).toBeNull();- expect(screen.queryByRole("heading", { name: "Generator scenes" })).toBeNull();- fireEvent.click(screen.getByRole("button", { name: "Media" }));- const media = container.querySelector(".media-grid")! as HTMLElement;- expect(screen.queryByRole("heading", { name: "Project media" })).toBeNull();- expect(screen.getByRole("button", { name: "Import" })).not.toBeNull();- expect(media.querySelector(".media-import")).toBeNull();- expect(within(media).getByText("Macro footage")).not.toBeNull();- expect(within(media).getByText("Room tone")).not.toBeNull();- });-- it("keeps the Import label while an import is in progress", async () => {- const { invoke } = await import("@tauri-apps/api/core");- (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__ = {};- let finish!: () => void;- const pending = new Promise<unknown[]>((resolve) => { finish = () => resolve([]); });- vi.mocked(invoke).mockReturnValue(pending as never);- try {- mediaPanel(projectWithMedia());- const button = screen.getByRole("button", { name: "Import" });- fireEvent.click(button);- expect(button.textContent).toContain("Import");- expect(button.textContent).not.toContain("Importing");- expect(button).toHaveProperty("disabled", true);- await act(async () => { finish(); await pending; });- } finally {- delete (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__;- vi.mocked(invoke).mockReset();- }- });-- it("shows audio-only waveforms without restoring clip name panels", () => {- const base = projectWithMedia();- const config = parseProjectConfig({- ...base,- assets: base.assets.map((asset) => asset.kind === "video" ? { ...asset, hasAudio: true } : asset),- timeline: { tracks: base.timeline.tracks.map((track, index) => ({- ...track,- clips: index === 0 ? [{- id: "clip-video", assetId: "asset-macro", trackId: track.id, startMs: 0, durationMs: 5_000,- sourceStartMs: 0, label: "Macro footage", color: null, status: "approved" as const,- }] : index === 1 ? [{- id: "clip-audio", assetId: "asset-room", trackId: track.id, startMs: 0, durationMs: 5_000,- sourceStartMs: 0, label: "Room tone", color: null, status: "approved" as const,- }] : [],- })) },- });- const onChange = vi.fn();- const { container } = render(createElement(TimelineView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenGenerator: () => undefined }));-- expect(container.querySelectorAll(".clip-audio-visualization")).toHaveLength(2);- expect(container.querySelector(".clip-audio-visualization__center")).toBeNull();- expect(container.querySelector(".clip-audio-visualization__envelope")).toBeNull();- expect(container.querySelector("polyline")).toBeNull();- expect(container.querySelector(".clip-audio-visualization i")).toBeNull();- expect(container.querySelectorAll(".timeline-clip--audio-only")).toHaveLength(1);- expect(container.querySelector(".clip-text")).toBeNull();- fireEvent.click(screen.getByRole("button", { name: "Mute audio on Track 1" }));- expect(wrote(onChange.mock.calls[0][0], config).timeline.tracks[0].muted).toBe(true);- });-- it("shows the waveform below thumbnails for generated files from older projects", () => {- const base = createProjectConfig({ name: "Older render", prompt: "A harbour", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 10 });- const job = {- ...base.generationJobs[0], status: "ready" as const, stage: "completed" as const, progress: 1,- outputRelativePath: "media/generated/job-initial-brief.mp4",- };- const assetId = "asset-job-initial-brief";- const config = parseProjectConfig({- ...base,- generationJobs: [job],- assets: [{- id: assetId, kind: "generated", name: job.title, relativePath: job.outputRelativePath,- mimeType: "video/mp4", durationMs: 10_000, width: 1920, height: 1080, createdAt: base.createdAt,- }],- timeline: { tracks: base.timeline.tracks.map((track, index) => ({- ...track,- clips: index === 0 ? [{- id: "clip-old", assetId, trackId: track.id, startMs: 0, durationMs: 10_000,- sourceStartMs: 0, label: job.title, color: null, status: "generated" as const,- }] : [],- })) },- });- const { container } = render(createElement(TimelineView, { config, folderPath: "C:\\Older render", onChange: () => undefined, onOpenGenerator: () => undefined }));- const clip = container.querySelector(".timeline-clip--has-audio");- expect(clip?.querySelector(".clip-audio-visualization")).not.toBeNull();- });-- it("removes project media and every timeline use of it", () => {- const base = projectWithMedia();- const config = parseProjectConfig({- ...base,- timeline: { tracks: base.timeline.tracks.map((track) => track.id === STORY_TRACK_ID ? { ...track, clips: [{- id: "clip-macro-a", assetId: "asset-macro", trackId: track.id, startMs: 0, durationMs: 2_000, sourceStartMs: 0, label: "Macro A", color: null, status: "approved",- }, {- id: "clip-macro-b", assetId: "asset-macro", trackId: track.id, startMs: 3_000, durationMs: 2_000, sourceStartMs: 2_000, label: "Macro B", color: null, status: "approved",- }] } : track) },- });- const { onChange } = mediaPanel(config);-- fireEvent.click(screen.getByRole("button", { name: "Remove Macro footage from project" }));- const next = wrote(onChange.mock.calls[0][0], config);- expect(next.assets.map((asset) => asset.id)).toEqual(["asset-room"]);- expect(next.timeline.tracks.flatMap((track) => track.clips).some((clip) => clip.assetId === "asset-macro")).toBe(false);- expect(parseProjectConfig(next)).toBeTruthy();- });-- it("drops an ungenerated Generator scene onto an audiovisual track as a valid draft clip", () => {- const config = projectWithMedia();- const onChange = vi.fn();- const { container } = render(createElement(TimelineView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenGenerator: () => undefined }));- const scene = screen.getByTitle(/^First scene — drag onto a track/);- const dataTransfer = fakeDataTransfer();-- fireEvent.dragStart(scene, { dataTransfer });- fireEvent.drop(laneAt(container, 1), { dataTransfer });- const next = wrote(onChange.mock.calls[0][0], config);- const generatedAsset = next.assets.find((asset) => asset.id === "asset-job-initial-brief")!;- const clip = next.timeline.tracks.flatMap((track) => track.clips).find((item) => item.assetId === generatedAsset.id)!;- expect(generatedAsset.kind).toBe("generated");- expect(generatedAsset.relativePath ?? null).toBeNull();- expect(clip.status).toBe("draft");- expect(clip.label).toBe("First scene");- expect(parseProjectConfig(next)).toBeTruthy();- });-- it("drops a video onto any audiovisual track", () => {- const config = projectWithMedia();- const video = config.assets[0];- const { container, onChange } = mediaPanel(config);- const card = screen.getByTitle(new RegExp(`^${video.name} —`));- const lane = laneAt(container, 1);-- const dataTransfer = fakeDataTransfer();- fireEvent.dragStart(card, { dataTransfer });- fireEvent.dragOver(lane, { dataTransfer });- fireEvent.drop(lane, { dataTransfer });- const next = wrote(onChange.mock.calls[0][0], config);- const track = next.timeline.tracks[1];- const dropped = track.clips.find((clip) => clip.assetId === video.id)!;- expect(dropped.label).toBe(video.name);- // A zero-width lane in jsdom must still yield a real start time, not NaN.- expect(Number.isFinite(dropped.startMs)).toBe(true);- expect(parseProjectConfig(next)).toBeTruthy();- });-- it("drops an audio-only file onto an audiovisual track", () => {- const config = projectWithMedia();- const sound = config.assets[1];- const { container, onChange } = mediaPanel(config);-- const dataTransfer = fakeDataTransfer();- fireEvent.dragStart(cardFor(sound), { dataTransfer });- // Video and audio are separated in BOTH directions. The video test beside- // this one only proved the video half; a sound landing on a video track- // makes a clip with a picture track and no picture.- fireEvent.drop(laneAt(container, 2), { dataTransfer });- const next = wrote(onChange.mock.calls[0][0], config);- expect(next.timeline.tracks[2].clips.map((clip) => clip.assetId)).toEqual([sound.id]);- expect(container.querySelectorAll(".track-lane")).toHaveLength(3);- expect(parseProjectConfig(next)).toBeTruthy();- });-- it("lands the dropped clip under the pointer and selects it", () => {- const config = projectWithMedia();- const video = config.assets[0];- const { container, onChange, rerender } = mediaPanel(config);- const lane = laneAt(container, 0) as HTMLElement;- // jsdom lays nothing out, so the lane has to be told how wide it is — the- // drop reads exactly this to turn a pointer position into a start time.- lane.getBoundingClientRect = () => ({ left: 100, width: 1000, top: 0, right: 1100, bottom: 72, height: 72, x: 100, y: 0, toJSON: () => ({}) });-- const dataTransfer = fakeDataTransfer();- fireEvent.dragStart(cardFor(video), { dataTransfer });- // jsdom has no DragEvent, so fireEvent builds a plain Event and drops any- // pointer coordinates on the floor. The drop reads clientX, so put it back.- const drop = createEvent.drop(lane, { dataTransfer });- Object.defineProperty(drop, "clientX", { value: 350 });- fireEvent(lane, drop);-- const next = wrote(onChange.mock.calls[0][0], config);- const dropped = next.timeline.tracks.flatMap((track) => track.clips)[0];- // A quarter of the way along a 30-second canvas, not pinned to zero.- expect(dropped.startMs).toBe(Math.round(0.25 * 30_000));- expect(parseProjectConfig(next)).toBeTruthy();-- // Dropping something and then having to find it again is a fair definition- // of a broken drop, so the new clip arrives selected.- rerender(createElement(TimelineView, { config: next, folderPath: "C:\Ceramic Lamp", onChange, onOpenGenerator: () => undefined }));- const clip = container.querySelector(".timeline-clip.selected");- expect(clip).not.toBeNull();- expect(clip!.getAttribute("title")).toContain(video.name);- });-- it("marks a locked lane as unavailable while media is being dragged", () => {- const base = projectWithMedia();- const config = {- ...base,- timeline: { tracks: base.timeline.tracks.map((track, index) => index === 1 ? { ...track, locked: true } : track) },- };- const { container } = mediaPanel(config);- const rejected = () => Array.from(container.querySelectorAll(".track-lane--reject"));-- expect(rejected()).toHaveLength(0);- const dataTransfer = fakeDataTransfer();- fireEvent.dragStart(cardFor(config.assets[1]), { dataTransfer });- // Every video track, for the whole drag — not only the one under the- // pointer. A dark lane on its own says nothing the user can act on.- expect(rejected()).toHaveLength(1);- fireEvent.dragEnd(cardFor(config.assets[1]));- expect(rejected()).toHaveLength(0);- });-- /** The same project with its video asset already measured, as the media panel- * measures it the first time it decodes the file for a thumbnail. */- const measuredVideo = (config: ProjectConfig, durationMs: number) => parseProjectConfig({- ...config,- assets: config.assets.map((asset) => asset.kind === "video" ? { ...asset, durationMs, width: 1920, height: 1080 } : asset),- });-- /** That project with one clip of the video already cut into the story track. */- const withClip = (config: ProjectConfig, clip: Partial<TimelineClip>) => parseProjectConfig({- ...config,- timeline: { tracks: config.timeline.tracks.map((track) => track.id === STORY_TRACK_ID ? { ...track, clips: [{- id: "clip-macro", assetId: config.assets[0].id, trackId: STORY_TRACK_ID,- startMs: 0, durationMs: 40_000, sourceStartMs: 0, label: "Macro footage", color: null, status: "approved", ...clip,- }] } : track) },- });-- const droppedClip = (calls: { mock: { calls: unknown[][] } }, current: ProjectConfig) =>- wrote(calls.mock.calls[0][0], current).timeline.tracks.flatMap((track) => track.clips)[0];-- it("drops a clip as long as the footage, and falls back to the stated default only when nothing measured it", () => {- /* B3: every dropped clip used to be five seconds, forever — a 40-second- rush included, with no way anywhere in the app to change it. */- const known = measuredVideo(projectWithMedia(), 40_000);- const first = mediaPanel(known);- const transfer = fakeDataTransfer();- fireEvent.dragStart(cardFor(known.assets[0]), { dataTransfer: transfer });- fireEvent.drop(laneAt(first.container, 0), { dataTransfer: transfer });- expect(droppedClip(first.onChange, known).durationMs).toBe(40_000);- expect(wrote(first.onChange.mock.calls[0][0], known).brief.targetDurationSeconds).toBe(40);- expect(parseProjectConfig(wrote(first.onChange.mock.calls[0][0], known))).toBeTruthy();- cleanup();-- // Nothing has decoded this one, so there is no length to honour and the- // documented stand-in is what lands.- const unknown = projectWithMedia();- const second = mediaPanel(unknown);- const transferTwo = fakeDataTransfer();- fireEvent.dragStart(cardFor(unknown.assets[0]), { dataTransfer: transferTwo });- fireEvent.drop(laneAt(second.container, 0), { dataTransfer: transferTwo });- expect(droppedClip(second.onChange, unknown).durationMs).toBe(5_000);- });-- it("keeps a long drop at the requested position and grows the saved project beyond ten minutes", () => {- const config = measuredVideo(projectWithMedia(), 700_000);- const view = mediaPanel(config);- const lane = laneAt(view.container, 0) as HTMLElement;- lane.getBoundingClientRect = () => ({ left: 100, width: 1000 } as DOMRect);- const dataTransfer = fakeDataTransfer();- fireEvent.dragStart(cardFor(config.assets[0]), { dataTransfer });- const drop = createEvent.drop(lane, { dataTransfer });- Object.defineProperty(drop, "clientX", { value: 1100 });- fireEvent(lane, drop);- const next = wrote(view.onChange.mock.calls[0][0], config);- expect(next.timeline.tracks.flatMap((track) => track.clips)[0]).toMatchObject({ startMs: 30_000, durationMs: 700_000 });- expect(next.brief.targetDurationSeconds).toBe(730);- expect(parseProjectConfig(next)).toBeTruthy();- });-- it("uses an editable clip name as the inspector heading", () => {- const config = withClip(measuredVideo(projectWithMedia(), 40_000), {});- const onChange = vi.fn();- const { container } = render(createElement(TimelineView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenGenerator: () => undefined }));-- expect(container.querySelector(".clip-inspector")).not.toBeNull();- expect(screen.queryByText("Clip details")).toBeNull();- expect(container.querySelector(".inspector-summary")).toBeNull();- const heading = screen.getByRole("heading", { name: "Macro footage" });- const name = within(heading).getByRole("textbox", { name: "Clip name" });- expect((name as HTMLInputElement).value).toBe("Macro footage");- expect(screen.queryByRole("heading", { name: "Clip" })).toBeNull();-- fireEvent.change(screen.getByTitle(/^How long this clip lasts/), { target: { value: "8" } });- const next = wrote(onChange.mock.calls[0][0], config);- expect(next.timeline.tracks.flatMap((track) => track.clips)[0].durationMs).toBe(8_000);- fireEvent.change(name, { target: { value: "Opening detail" } });- expect(wrote(onChange.mock.calls.at(-1)![0], config).timeline.tracks.flatMap((track) => track.clips)[0].label).toBe("Opening detail");- fireEvent.change(name, { target: { value: "" } });- expect(wrote(onChange.mock.calls.at(-1)![0], config).timeline.tracks.flatMap((track) => track.clips)[0].label).toBe("Untitled clip");- });-- /* --- Dragging clips on the timeline ---------------------------------------- jsdom lays nothing out and has no PointerEvent, so both are supplied here:- the lane is told how wide it is (a drag turns pixels into milliseconds- against exactly this), and each gesture is a bubbling event carrying the- coordinates the handlers read. 1000px over a 30-second canvas makes the- arithmetic legible: 1px is 30ms, and the 8px magnet is 240ms.- ======================================================================= */-- const LANE_WIDTH = 1000;- const LANE_RECT = { left: 0, width: LANE_WIDTH, top: 0, right: LANE_WIDTH, bottom: 72, height: 72, x: 0, y: 0, toJSON: () => ({}) } as DOMRect;-- function pointerEvent(type: string, clientX: number, clientY = 40) {- const event = new Event(type, { bubbles: true, cancelable: true });- for (const [key, value] of Object.entries({ clientX, clientY, button: 0, pointerId: 1 })) {- Object.defineProperty(event, key, { value });- }- return event;- }-- /** A project with clips cut into one of its tracks. */- const withClips = (config: ProjectConfig, clips: Partial<TimelineClip>[], trackId = STORY_TRACK_ID) => parseProjectConfig({- ...config,- timeline: { tracks: config.timeline.tracks.map((track) => track.id === trackId ? { ...track, clips: clips.map((clip, index) => ({- id: `clip-${index}`, assetId: config.assets[0].id, trackId,- startMs: 0, durationMs: 4_000, sourceStartMs: 0, label: `Shot ${index + 1}`, color: null, status: "approved", ...clip,- })) } : track) },- });-- /** Renders the timeline with every lane measured, and hands back what a drag- * needs: the lanes, the clips, and whatever was written. */- function timeline(config: ProjectConfig) {- const onChange = vi.fn();- const view = render(createElement(TimelineView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenGenerator: () => undefined }));- for (const lane of view.container.querySelectorAll(".track-lane")) lane.getBoundingClientRect = () => LANE_RECT;- const laneOf = (trackId: string) => view.container.querySelector(`[data-track-id="${trackId}"]`) as HTMLElement;- const written = () => onChange.mock.calls.length ? wrote(onChange.mock.calls.at(-1)![0], config) : undefined;- const clipsOn = (trackId: string) => written()?.timeline.tracks.find((track) => track.id === trackId)?.clips ?? [];- return { ...view, onChange, laneOf, written, clipsOn };- }-- /** One whole gesture: press on `grip`, move to `toX`, release. */- function drag(grip: Element, fromX: number, toX: number, clientY = 40) {- fireEvent(grip, pointerEvent("pointerdown", fromX, clientY));- fireEvent(window, pointerEvent("pointermove", toX, clientY));- fireEvent(window, pointerEvent("pointerup", toX, clientY));- }-- /** Which lane the pointer is over. jsdom cannot hit-test, so this is the one- * thing about a cross-lane drag a test has to supply. */- const overLane = (lane: HTMLElement) => {- (document as unknown as { elementsFromPoint: () => Element[] }).elementsFromPoint = () => [lane];- };- const stopHitTesting = () => { delete (document as unknown as { elementsFromPoint?: unknown }).elementsFromPoint; };-- it("drags a clip along its own lane and writes where it landed", () => {- const config = withClips(measuredVideo(projectWithMedia(), 40_000), [{ startMs: 2_000, durationMs: 4_000 }]);- const view = timeline(config);- // Taken hold of 1s into the clip and dropped 6s further along: the clip- // moves by what the POINTER moved, rather than jumping its head under it.- drag(view.container.querySelector(".timeline-clip")!, 100, 300);- expect(view.clipsOn(STORY_TRACK_ID)[0]).toMatchObject({ startMs: 8_000, durationMs: 4_000 });- expect(parseProjectConfig(view.written()!)).toBeTruthy();- });-- it("drags a clip onto another audiovisual track", () => {- const config = withClips(measuredVideo(projectWithMedia(), 40_000), [{ startMs: 0, durationMs: 4_000 }]);- const view = timeline(config);- overLane(view.laneOf("track-v2"));- drag(view.container.querySelector(".timeline-clip")!, 20, 220);- expect(view.clipsOn(STORY_TRACK_ID)).toHaveLength(0);- expect(view.clipsOn("track-v2")[0]).toMatchObject({ startMs: 6_000, trackId: "track-v2" });- expect(parseProjectConfig(view.written()!)).toBeTruthy();-- stopHitTesting();- });-- it("extends the project when an existing clip is dragged past its end", () => {- const config = withClips(measuredVideo(projectWithMedia(), 40_000), [{ startMs: 0, durationMs: 4_000 }]);- const view = timeline(config);- drag(view.container.querySelector(".timeline-clip")!, 20, 1220);- const moved = view.clipsOn(STORY_TRACK_ID)[0];- expect(moved.startMs).toBe(36_000);- expect(view.written()!.brief.targetDurationSeconds).toBe(40);- expect(parseProjectConfig(view.written()!)).toBeTruthy();- });-- it("moves audio-only media from one audiovisual track to another", () => {- const measured = parseProjectConfig({- ...projectWithMedia(),- assets: projectWithMedia().assets.map((asset) => asset.kind === "audio" ? { ...asset, durationMs: 20_000 } : asset),- });- const config = withClips(measured, [{ startMs: 0, durationMs: 6_000, assetId: "asset-room", label: "Room tone" }], "track-v2");- const view = timeline(config);- overLane(view.laneOf("track-v3"));- drag(view.container.querySelector(".timeline-clip")!, 10, 110);- expect(view.clipsOn("track-v2")).toHaveLength(0);- expect(view.clipsOn("track-v3")[0]).toMatchObject({ startMs: 3_000, trackId: "track-v3" });- stopHitTesting();- });-- it("will not lay one clip over another", () => {- const config = withClips(measuredVideo(projectWithMedia(), 40_000), [- { startMs: 0, durationMs: 4_000 },- { startMs: 12_000, durationMs: 4_000 },- ]);- const view = timeline(config);- // Dragged from 12s back to 1s, right on top of the first clip: it lands- // flush against the side it was nearer to, and nothing overlaps.- drag(view.container.querySelectorAll(".timeline-clip")[1], 400, 33);- expect(view.clipsOn(STORY_TRACK_ID).map((clip) => [clip.startMs, clip.durationMs])).toEqual([[0, 4_000], [4_000, 4_000]]);- expect(parseProjectConfig(view.written()!)).toBeTruthy();- });-- it("snaps a dragged clip to the cut beside it", () => {- const config = withClips(measuredVideo(projectWithMedia(), 40_000), [- { startMs: 0, durationMs: 4_000 },- { startMs: 20_000, durationMs: 4_000 },- ]);- const view = timeline(config);- /* Dropped with its head 150ms past the first clip's tail — inside the 240ms- magnet, so the gap closes completely rather than leaving a hole too small- to see and too real for the encoder to ignore. */- drag(view.container.querySelectorAll(".timeline-clip")[1], 667, 138);- expect(view.clipsOn(STORY_TRACK_ID)[1].startMs).toBe(4_000);- });-- it("trims the tail by dragging the right edge, and never past the footage", () => {- const config = withClips(measuredVideo(projectWithMedia(), 40_000), [{ startMs: 0, durationMs: 6_000, sourceStartMs: 1_000 }]);- const view = timeline(config);- drag(view.container.querySelector(".clip-handle--end")!, 200, 100);- // Only the length changes: the head of the clip and the point it starts- // inside the file are not what the right-hand edge is holding.- expect(view.clipsOn(STORY_TRACK_ID)[0]).toMatchObject({ startMs: 0, durationMs: 3_000, sourceStartMs: 1_000 });-- // The file is 40s long and this clip starts 1s into it, so 39s is all the- // tail there is, however far the pointer goes.- cleanup();- const second = timeline(config);- drag(second.container.querySelector(".clip-handle--end")!, 200, 1_600);- expect(second.clipsOn(STORY_TRACK_ID)[0].durationMs).toBe(39_000);- });-- it("trims the head by dragging the left edge, moving the cut and the source together", () => {- const config = withClips(measuredVideo(projectWithMedia(), 40_000), [{ startMs: 4_000, durationMs: 6_000, sourceStartMs: 2_000 }]);- const view = timeline(config);- drag(view.container.querySelector(".clip-handle--start")!, 133, 250);- // Three and a half seconds later on the ruler is three and a half seconds- // later in the footage.- expect(view.clipsOn(STORY_TRACK_ID)[0]).toMatchObject({ startMs: 7_500, durationMs: 2_500, sourceStartMs: 5_500 });-- // Pulled the other way it stops where the file's own head is: only 2s of- // footage exists before this clip's first frame.- cleanup();- const second = timeline(config);- drag(second.container.querySelector(".clip-handle--start")!, 133, 0);- expect(second.clipsOn(STORY_TRACK_ID)[0]).toMatchObject({ startMs: 2_000, durationMs: 8_000, sourceStartMs: 0 });- });-- it("abandons a drag on Escape and writes nothing", () => {- const config = withClips(measuredVideo(projectWithMedia(), 40_000), [{ startMs: 2_000, durationMs: 4_000 }]);- const view = timeline(config);- fireEvent(view.container.querySelector(".timeline-clip")!, pointerEvent("pointerdown", 100));- fireEvent(window, pointerEvent("pointermove", 400));- fireEvent.keyDown(window, { key: "Escape" });- fireEvent(window, pointerEvent("pointerup", 400));- expect(view.onChange).not.toHaveBeenCalled();- });-- it("refuses to drag or trim anything on a locked track", () => {- const config = withClips(measuredVideo(projectWithMedia(), 40_000), [{ startMs: 2_000, durationMs: 4_000 }]);- const locked = parseProjectConfig({ ...config, timeline: { tracks: config.timeline.tracks.map((track) => track.id === STORY_TRACK_ID ? { ...track, locked: true } : track) } });- const view = timeline(locked);- drag(view.container.querySelector(".timeline-clip")!, 100, 400);- expect(view.onChange).not.toHaveBeenCalled();- // The handles are not merely inert, they are absent: a control that cannot- // do anything is worse than no control at all.- expect(view.container.querySelector(".clip-handle")).toBeNull();- expect(view.container.querySelector(".clip-delete")).toBeNull();- });-- it("removes a clip from its track with the control on the clip itself", () => {- const config = withClips(measuredVideo(projectWithMedia(), 40_000), [- { startMs: 0, durationMs: 4_000, label: "Opening" },- { startMs: 8_000, durationMs: 4_000, label: "Closing" },- ]);- const view = timeline(config);- fireEvent.click(screen.getByRole("button", { name: "Delete Opening" }));- expect(view.clipsOn(STORY_TRACK_ID).map((clip) => clip.label)).toEqual(["Closing"]);- expect(parseProjectConfig(view.written()!)).toBeTruthy();- });-- it("keeps a clip's place in the source when it is duplicated", () => {- // Otherwise every copy replays the head of the file, which is the same five- // seconds the original already showed.- const config = withClip(measuredVideo(projectWithMedia(), 40_000), { startMs: 0, durationMs: 6_000, sourceStartMs: 12_000 });- const onChange = vi.fn();- render(createElement(TimelineView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenGenerator: () => undefined }));- fireEvent.click(screen.getByRole("button", { name: "Duplicate" }));- const next = wrote(onChange.mock.calls[0][0], config);- const clips = next.timeline.tracks.flatMap((track) => track.clips);- expect(clips).toHaveLength(2);- const copy = clips.find((clip) => clip.id !== "clip-macro")!;- expect(copy.sourceStartMs).toBe(12_000);- expect(copy.durationMs).toBe(6_000);- expect(parseProjectConfig(next)).toBeTruthy();- });-- it("records the length the media panel actually measured onto the asset", async () => {- /* Held in state and fed back in, exactly as ProjectWorkspace holds it: two- files are measured here, and each measurement has to survive the other. */- const seen: ProjectConfig[] = [];- function Harness({ initial }: { initial: ProjectConfig }) {- const [config, setConfig] = useState(initial);- useEffect(() => { seen.push(config); }, [config]);- return createElement(TimelineView, { config, folderPath: "C:\\Measured Project", onChange: setConfig, onOpenGenerator: () => undefined });- }- await withFakeDecoder({ seconds: 40, width: 1920, height: 1080 }, async () => {- render(createElement(Harness, { initial: projectWithMedia() }));- fireEvent.click(screen.getByRole("button", { name: "Media" }));- await waitFor(() => expect(seen.at(-1)!.assets.every((asset) => asset.durationMs !== null)).toBe(true), { timeout: 8_000 });- });- const final = seen.at(-1)!;- const video = final.assets.find((asset) => asset.kind === "video")!;- expect(video.durationMs).toBe(40_000);- expect(video.width).toBe(1920);- expect(video.height).toBe(1080);- // Sound has no picture but it does have a length, and the timeline needs it.- expect(final.assets.find((asset) => asset.kind === "audio")!.durationMs).toBe(40_000);- expect(parseProjectConfig(final)).toBeTruthy();- // Measuring is not editing: once every file is known, it stops writing.- const settled = seen.length;- await new Promise((resolve) => setTimeout(resolve, 50));- expect(seen.length).toBe(settled);- // Longer than the wait above: a decode that never finishes has to fail this- // test on its assertion, not by timing the test out before its cleanup runs.- }, 20_000);-- it("keeps a measurement that lands before the one before it has come back down", async () => {- /* The race the queue never covered. Two files finish decoding one after the- other; each finish flushes. The flush used to rebuild the whole config- from the `config` prop of the render it ran in, so the second flush —- running before the first write had returned as a new prop — rebuilt from- the config that still knew nothing and dropped the first measurement.- Here the holder deliberately never feeds anything back, which is that- window at its widest, and both measurements still have to survive. */- const config = projectWithMedia();- const onChange = vi.fn();- await withStagedDecoder({ seconds: 40, width: 1920, height: 1080 }, async (stage) => {- render(createElement(TimelineView, { config, folderPath: "C:\\Staged Project", onChange, onOpenGenerator: () => undefined }));- fireEvent.click(screen.getByRole("button", { name: "Media" }));- await stage.opened(2);- await stage.settle(0);- await stage.settle(1);- });- // Two files, two separate writes: one write for both would mean the second- // decode never landed and the test is proving nothing.- expect(onChange.mock.calls.length).toBeGreaterThanOrEqual(2);- /* Fold every write onto the config the view was given, in the order it- asked for them — which is all a holder does with them. A write that- carries a whole config replaces what came before it; an updater is- applied to it. */- const folded = onChange.mock.calls.reduce(- (current: ProjectConfig, call) => typeof call[0] === "function" ? (call[0] as (value: ProjectConfig) => ProjectConfig)(current) : call[0] as ProjectConfig,- config,- );- expect(folded.assets.map((asset) => [asset.name, asset.durationMs])).toEqual([["Macro footage", 40_000], ["Room tone", 40_000]]);- expect(folded.assets.find((asset) => asset.kind === "video")!.width).toBe(1920);- expect(parseProjectConfig(folded)).toBeTruthy();- }, 20_000);-it("does not mark a saved project edited for having its media looked at", async () => {/* N3: opening the Media panel measured the files, the measurement went backthrough the same door as a user's edit, and Save lit up on a project@@ -1031,7 +346,7 @@ describe("project workspace timecode", () => {expect(save().disabled).toBe(true);expect(save().getAttribute("data-tooltip")).toBe("Everything is saved");- fireEvent.click(screen.getByRole("button", { name: "Media" }));+ fireEvent.click(screen.getByRole("tab", { name: "Media" }));// The panel prints the length it read, so this waits on the measurement// itself rather than on a guess at how long a decode takes.await waitFor(() => expect(screen.getAllByText(/40\.0s/).length).toBe(2), { timeout: 8_000 });@@ -1049,69 +364,6 @@ describe("project workspace timecode", () => {expect(parseProjectConfig(saved.config)).toBeTruthy();}, 20_000);- it("keeps the transport on the timeline, with one timecode and one reason", () => {- const empty = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });- const { container, rerender } = render(createElement(TimelineView, { config: empty, folderPath: "C:\Ceramic Lamp", onChange: () => undefined, onOpenGenerator: () => undefined }));-- // It sits in the timeline toolbar now, not under the program monitor.- expect(container.querySelector(".monitor-transport")).toBeNull();- expect(container.querySelector(".timeline-toolbar .timeline-transport")).not.toBeNull();- /* The transport is the three controls and NOTHING else. The clock and the- format used to ride inside it, which pushed the buttons off to one side- of whatever the cluster happened to measure — and the cluster has to be- centred on the picture above it, which only works if its own contents are- symmetrical. They live beside the heading now instead; jsdom lays nothing- out, so what is pinned here is the arrangement the CSS centres, and the- measured geometry is recorded against --video-centre-shift. */- expect(Array.from(container.querySelectorAll(".timeline-transport > *")).map((el) => el.getAttribute("aria-label")))- .toEqual(["Go to beginning", "Play", "Step forward one second"]);- const lead = container.querySelector(".timeline-toolbar__lead")!;- expect(lead.querySelector("h2")!.textContent).toBe("Timeline");- expect(lead.querySelector(".transport-time")).not.toBeNull();- expect(lead.querySelector(".transport-format")).not.toBeNull();- // Reading order left to right: what this panel is, where it stands, what it- // is. The heading has to come first or the clock is a label on nothing.- expect(Array.from(lead.children).map((el) => el.tagName)).toEqual(["H2", "STRONG", "SPAN"]);- // the playhead time is printed once. The toolbar used to print it beside- // the heading while the monitor printed it again, which reads as two clocks.- expect(container.textContent!.match(/\d\d:\d\d:\d\d:\d\d/g)).toHaveLength(1);- // Pixels, not the id: "1080p" names one edge and leaves the other a guess.- expect(container.querySelector(".transport-format")!.textContent).toBe("1920 × 1080 · 24 fps");-- // An empty timeline has nothing to play, and every control says so rather- // than only going grey.- for (const label of ["Go to beginning", "Play", "Step forward one second"]) {- const button = screen.getByRole("button", { name: label }) as HTMLButtonElement;- expect(button.disabled, label).toBe(true);- expect(button.title, label).toBe("Nothing to play yet — add or generate a scene first.");- }-- // With a clip on the timeline they come alive, and Space still plays.- const config = parseProjectConfig(completeFixture);- rerender(createElement(TimelineView, { config, folderPath: "C:\Ceramic Lamp", onChange: () => undefined, onOpenGenerator: () => undefined }));- expect((screen.getByRole("button", { name: "Play" }) as HTMLButtonElement).disabled).toBe(false);- fireEvent.keyDown(container.querySelector(".timeline-view")!, { code: "Space" });- expect(screen.getByRole("button", { name: "Pause" })).not.toBeNull();- fireEvent.click(screen.getByRole("button", { name: "Pause" }));- expect(screen.getByRole("button", { name: "Play" })).not.toBeNull();- });-- it("does not delete a selected clip from a locked track", () => {- const config = parseProjectConfig(completeFixture);- const firstTrackWithClip = config.timeline.tracks.find((track) => track.clips.length > 0)!;- const locked = { ...config, timeline: { tracks: config.timeline.tracks.map((track) => track.id === firstTrackWithClip.id ? { ...track, locked: true } : track) } };- const onChange = vi.fn();- const { container } = render(createElement(TimelineView, { config: locked, folderPath: "C:\Locked Project", onChange, onOpenGenerator: () => undefined }));- const timeline = container.querySelector(".timeline-view")!;- fireEvent.keyDown(timeline, { key: "Delete" });- expect(onChange).not.toHaveBeenCalled();- // Still disabled — and now it says why, rather than keeping the enabled- // wording while being unclickable.- const deleteButton = screen.getByRole("button", { name: "Delete" }) as HTMLButtonElement;- expect(deleteButton.disabled).toBe(true);- expect(deleteButton.title).toBe("This clip’s track is locked");- });-it("keeps timeline actions out of scene settings", () => {const config = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });render(createElement(GeneratorView, { config, folderPath: "C:\Ceramic Lamp", onChange: () => undefined, onOpenTimeline: () => undefined, selectedJobId: config.generationJobs[0].id }));@@ -1208,21 +460,6 @@ describe("project workspace timecode", () => {expect(screen.queryByText("The video engine only follows the words in the shots.")).toBeNull();});- it("disables Split while the playhead sits outside the selected clip", () => {- const config = parseProjectConfig(completeFixture);- const { container } = render(createElement(TimelineView, { config, folderPath: "C:\Timeline Project", onChange: () => undefined, onOpenGenerator: () => undefined }));- const split = () => screen.getByRole("button", { name: "Split" }) as HTMLButtonElement;- // The playhead starts at the head of the first clip, where splitSelected- // returns early — so the button must not look live.- expect(split().disabled).toBe(true);- expect(split().title).toBe("Move the playhead inside the selected clip to split it");- // Scrubbing inside the selected timeline clip makes it a real split. Scene- // cards now open Generator scenes and are no longer aliases for clips.- fireEvent.wheel(container.querySelector(".timeline-grid")!, { deltaY: 100, deltaMode: 0 });- expect(split().disabled).toBe(false);- expect(split().title).toBe("Split at playhead");- });-it("keeps a half-written shot line when you visit another tab and come back", async () => {const config = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });render(createElement(ProjectWorkspace, {@@ -1261,16 +498,6 @@ describe("project workspace timecode", () => {expect(onChange.mock.calls[0][0].generationJobs[0].referenceIds).toEqual([]);});- it("says why Duplicate and Delete are unavailable, not just that they are", () => {- const config = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });- render(createElement(TimelineView, { config, folderPath: "C:\Timeline Project", onChange: () => undefined, onOpenGenerator: () => undefined }));- for (const label of ["Duplicate", "Delete"]) {- const button = screen.getByRole("button", { name: label }) as HTMLButtonElement;- expect(button.disabled).toBe(true);- expect(button.title).toBe(`Select a clip to ${label.toLowerCase()} it`);- }- });-it("sends no filename and no app boilerplate to the model for a really imported image", async () => {// Built the way the PRODUCT builds it — the actual "Add image" button and// the actual Tauri import path — not a hand-written reference with a tidy@@ -1326,18 +553,6 @@ describe("project workspace timecode", () => {expect(screenText).toContain("Not described yet — the picture is sent, but nothing tells the engine what to keep.");});- it("makes timelines longer than one minute horizontally scrollable at a readable scale", () => {- const short = createProjectConfig({ name: "Short", prompt: "", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 60 });- const view = render(createElement(TimelineView, { config: short, folderPath: "C:\\Short", onChange: () => undefined, onOpenGenerator: () => undefined }));- expect((view.container.querySelector(".timeline-grid") as HTMLElement).style.width).toBe("100%");- expect(view.container.querySelector(".timeline-grid-scroll--wide")).toBeNull();-- const long = createProjectConfig({ name: "Long", prompt: "", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 120 });- view.rerender(createElement(TimelineView, { config: long, folderPath: "C:\\Long", onChange: () => undefined, onOpenGenerator: () => undefined }));- expect((view.container.querySelector(".timeline-grid") as HTMLElement).style.width).toBe("200%");- expect(view.container.querySelector(".timeline-grid-scroll--wide")).toBeTruthy();- });-it("lays references out as a scrolling main area beside a full-height inspector", () => {const config = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });const { container } = render(createElement(ReferencesView, { config, folderPath: "C:\\Ceramic Lamp", onChange: () => undefined }));