AI media harness for planning, generating, and editing locally
TypeScript
Edit and render Motions on the timeline
Bittica9007cad3c4
diff --git a/README.md b/README.mdindex d58d2ad..7f3aec8 100644--- a/README.md+++ b/README.md@@ -36,6 +36,7 @@ Slopus brings an AI assistant, a scene generator, reusable references, a timelin- **LAN workers.** Generate on another Windows or Linux computer. Workers download available weights, receive local files as needed, and return results to your project.- **Generator templates.** Download weights or use local files. Save model and attention settings per template, with optional **MotionCache** for supported modes. Import and export URL-based templates as portable [`.slop` bundles](docs/generator-weights.md#sharing-generator-templates).- **Timeline.** Video and audio tracks with thumbnails, waveforms, snapping, trimming, splitting, zoom and keyboard shortcuts. Transform, opacity, chroma key, fades and wipes, plus GPU effects (sharpen, blur, color correction, vignette, `.cube` LUTs) that can be bypassed.+- **Motions.** Add an empty Motion on the timeline, then ask the agent to create its animation. Select and move or resize named elements in the video preview; edit parameters and JavaScript in the right panel. Render as reference video adds an MP4 to References for MiniMax generation.- **Image editor.** Generate images from prompts, objects and text, or open an image and describe whole-image or local edits. Keep originals, drafts and versions in the image bar.- **Export.** Video: MP4 in H.264, VP9 or AV1 (as your encoders allow) at a chosen resolution, frame rate and quality; exports keep running in the background. Images: pick one from the image bar and save it as JPG or PNG at a chosen size and quality.- **Undo everywhere.** Save, Undo and Redo sit in the title bar; Ctrl+Z and Ctrl+Y cover edits from any view, the agent and project settings.diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.mdindex 6c63287..6f2956e 100644--- a/RELEASE_NOTES.md+++ b/RELEASE_NOTES.md@@ -4,6 +4,8 @@ This alpha update adds Prompt video scenes, agent image drafts, Sol attention an## What's new+- **Motions.** Create an empty Motion on the timeline and ask the agent to animate it with JavaScript. Edit named elements in the preview, adjust exposed parameters and view or change the full source in the inspector. Motions support transparent layering, scrubbing and video export. Render a Motion as a reference video to add it to References for MiniMax generation.+- **Fibo 2.0 Base and editing capabilities.** Added the Base generator with the Dev transformer and shared Fibo encoder/VAE. A per-template Editing model switch controls image editing and Zoom, defaults off for Base and MOSS, and is preserved when sharing templates. Fibo Edit Turbo now supports Zoom with masked border generation that preserves the source image.- **Image negative prompts.** MOSS exposes a Negative prompt field below the image root prompt, saved per model with drafts and generated images and applied during local or LAN generation. Fibo Turbo shows the field disabled because its single positive prediction does not support negative prompts. Visibility and support are controlled by model settings. Update LAN workers to protocol 17.diff --git a/src/components/workspace/MediaThumbnail.tsx b/src/components/workspace/MediaThumbnail.tsxindex b4e0231..1dd1c5e 100644--- a/src/components/workspace/MediaThumbnail.tsx+++ b/src/components/workspace/MediaThumbnail.tsx@@ -1,3 +1,4 @@+import { MotionCanvas } from "./MotionCanvas";import { Audio22, Image22, Video22, Warning22 } from "../ui/icons";import { useEffect, useRef, useState } from "react";import { readMediaFileUrl } from "../../lib/persistence";@@ -198,7 +199,7 @@ const wantsMeasuring = (asset: ProjectAsset) =>? !asset.width || !asset.height: !asset.durationMs || (asset.kind === "video" && asset.hasAudio == null);-export function MediaThumbnail({ folderPath, asset, onMeasured, posterTimeSeconds = POSTER_TIME_SECONDS, jpegQuality = DEFAULT_JPEG_QUALITY }: {+function FileMediaThumbnail({ folderPath, asset, onMeasured, posterTimeSeconds = POSTER_TIME_SECONDS, jpegQuality = DEFAULT_JPEG_QUALITY }: {folderPath: string;asset: ProjectAsset;/** Called once with whatever the decode could measure, so the project can@@ -287,3 +288,7 @@ export function MediaThumbnail({ folderPath, asset, onMeasured, posterTimeSeconddata-tooltip={failed ? "Couldn’t read this file" : undefined}>{icon}</span>;}++export function MediaThumbnail(props: React.ComponentProps<typeof FileMediaThumbnail>) {+ return props.asset.motion ? <MotionCanvas motion={props.asset.motion} time={0} /> : <FileMediaThumbnail {...props} />;+}diff --git a/src/components/workspace/MotionCanvas.tsx b/src/components/workspace/MotionCanvas.tsxnew file mode 100644index 0000000..4348d15--- /dev/null+++ b/src/components/workspace/MotionCanvas.tsx@@ -0,0 +1,46 @@+import { useEffect, useRef, useState, type CSSProperties } from "react";+import { CanvasMotionRenderer, MotionRuntime } from "../../lib/motionRuntime";+import type { Motion, MotionNode } from "../../lib/motion";+import type { PreviewMedia } from "../../lib/previewPresentation";++/** One in-flight evaluation per player. Rapid seeks coalesce to the latest+ * request, and obsolete frames never replace the current timeline position. */+export function MotionCanvas({ motion, time, style, media, playerKey, onFrame }: {+ motion: Motion; time: number; style?: CSSProperties; media?: PreviewMedia; playerKey?: string;+ onFrame?: (nodes: MotionNode[]) => void;+}) {+ const canvas = useRef<HTMLCanvasElement>(null);+ const latest = useRef({ motion, time, onFrame }); latest.current = { motion, time, onFrame };+ const lastFrame = useRef<MotionNode[] | null>(null);+ const request = useRef<(() => void) | null>(null);+ const [error, setError] = useState<string | null>(null);+ useEffect(() => {+ const runtime = new MotionRuntime();+ let live = true, busy = false, revision = 0;+ const draw = async () => {+ if (busy || !live || !canvas.current) return;+ busy = true;+ const version = revision, state = latest.current;+ try {+ const nodes = await runtime.evaluate(state.motion, state.time);+ if (!live || !canvas.current || (version !== revision && (state.motion !== latest.current.motion || Math.abs(state.time - latest.current.time) > 0.1))) return;+ const scale = Math.min(1, 1280 / Math.max(state.motion.width, state.motion.height));+ const width = Math.max(1, Math.round(state.motion.width * scale)), height = Math.max(1, Math.round(state.motion.height * scale));+ if (canvas.current.width !== width) canvas.current.width = width;+ if (canvas.current.height !== height) canvas.current.height = height;+ new CanvasMotionRenderer(canvas.current).render(nodes, state.motion.width, state.motion.height);+ if (playerKey) { media?.set(playerKey, canvas.current); media?.setMotionTime(playerKey, state.time); }+ media?.invalidate();+ lastFrame.current = nodes; latest.current.onFrame?.(nodes); setError(null);+ } catch (reason) { if (live && version === revision) setError(reason instanceof Error ? reason.message : String(reason)); }+ finally { busy = false; if (live && version !== revision) void draw(); }+ };+ request.current = () => { revision++; void draw(); };+ request.current();+ return () => { live = false; request.current = null; runtime.dispose(); if (playerKey) media?.set(playerKey, null); };+ }, [media, playerKey]);+ useEffect(() => request.current?.(), [motion, time]);+ useEffect(() => { if (lastFrame.current) onFrame?.(lastFrame.current); }, [onFrame]);+ return <><canvas ref={canvas} style={style} className="motion-canvas" aria-label="Motion preview" />+ {error && <div className="program-note program-note--error" role="alert">{error}</div>}</>;+}diff --git a/src/components/workspace/MotionHandles.tsx b/src/components/workspace/MotionHandles.tsxnew file mode 100644index 0000000..2c0aef1--- /dev/null+++ b/src/components/workspace/MotionHandles.tsx@@ -0,0 +1,45 @@+import { useRef } from "react";+import { motionOverride, type Motion, type MotionNode } from "../../lib/motion";++/** Editor chrome uses the evaluated positions, while gestures change only+ * persistent offsets/scales. Scripts and original scene elements stay intact. */+export function MotionHandles({ motion, nodes, selectedId, onSelect, onChange }: {+ motion: Motion; nodes: MotionNode[]; selectedId: string | null; onSelect: (id: string) => void; onChange: (motion: Motion) => void;+}) {+ const root = useRef<HTMLDivElement>(null);+ const origin = useRef<HTMLSpanElement>(null), horizontal = useRef<HTMLSpanElement>(null), vertical = useRef<HTMLSpanElement>(null);+ const drag = useRef<{ inverse: DOMMatrix; angle: number; id: string; x: number; y: number; width: number; height: number; resize: boolean; initial: Motion } | null>(null);+ return <div ref={root} className="motion-handles" onClick={(e) => e.stopPropagation()}+ onPointerMove={(e) => {+ const g = drag.current; if (!g) return;+ const delta = g.inverse.transformPoint(new DOMPoint(e.clientX - g.x, e.clientY - g.y));+ const dx = delta.x, dy = delta.y;+ const localX = dx * Math.cos(g.angle) + dy * Math.sin(g.angle);+ const localY = -dx * Math.sin(g.angle) + dy * Math.cos(g.angle);+ const edit = motionOverride(g.initial, g.id);+ const next = g.resize ? { ...edit, scale: [Math.max(0.01, edit.scale[0] * (g.width + localX) / (g.width || 1)), Math.max(0.01, edit.scale[1] * (g.height + localY) / (g.height || 1)), edit.scale[2]] as [number, number, number] }+ : { ...edit, offset: [edit.offset[0] + dx, edit.offset[1] + dy, edit.offset[2]] as [number, number, number] };+ next.offset = next.offset.map((v) => Math.round(v * 100) / 100) as [number, number, number];+ next.scale = next.scale.map((v) => Math.round(v * 1000) / 1000) as [number, number, number];+ onChange({ ...g.initial, overrides: { ...g.initial.overrides, [g.id]: next } });+ }} onPointerUp={() => { drag.current = null; }} onPointerCancel={() => { drag.current = null; }}>+ <span ref={origin} style={{ position: "absolute", left: 0, top: 0 }} />+ <span ref={horizontal} style={{ position: "absolute", left: "100%", top: 0 }} />+ <span ref={vertical} style={{ position: "absolute", left: 0, top: "100%" }} />+ {nodes.filter((node) => node.visible && motion.nodes.some((n) => n.id === node.id)).map((node) => <button key={node.id} type="button"+ className={`motion-element${selectedId === node.id ? " is-selected" : ""}`} aria-label={`Select Motion element ${node.name}`}+ style={{ left: `${node.position[0] / motion.width * 100}%`, top: `${node.position[1] / motion.height * 100}%`,+ width: `${Math.abs(node.width * node.scale[0]) / motion.width * 100}%`, height: `${Math.abs(node.height * node.scale[1]) / motion.height * 100}%`, transform: `rotate(${node.rotation[2]}deg) scale(${Math.sign(node.width * node.scale[0]) || 1}, ${Math.sign(node.height * node.scale[1]) || 1})` }}+ onPointerDown={(e) => {+ if (e.button !== 0) return; e.stopPropagation(); e.preventDefault(); onSelect(node.id);+ const o = origin.current!.getBoundingClientRect(), x = horizontal.current!.getBoundingClientRect(), y = vertical.current!.getBoundingClientRect();+ const matrix = new DOMMatrix([(x.x - o.x) / motion.width, (x.y - o.y) / motion.width, (y.x - o.x) / motion.height, (y.y - o.y) / motion.height, 0, 0]);+ if (Math.abs(matrix.a * matrix.d - matrix.b * matrix.c) < 1e-10) return;+ root.current!.setPointerCapture(e.pointerId);+ drag.current = { inverse: matrix.inverse(), angle: node.rotation[2] * Math.PI / 180, id: node.id, x: e.clientX, y: e.clientY, width: node.width * node.scale[0], height: node.height * node.scale[1],+ resize: (e.target as HTMLElement).dataset.resize === "true", initial: motion };+ }}>+ {selectedId === node.id && <span className="motion-resize" data-resize="true" aria-label="Resize Motion element" />}+ </button>)}+ </div>;+}diff --git a/src/components/workspace/MotionInspector.test.tsx b/src/components/workspace/MotionInspector.test.tsxnew file mode 100644index 0000000..5808b6e--- /dev/null+++ b/src/components/workspace/MotionInspector.test.tsx@@ -0,0 +1,33 @@+// @vitest-environment jsdom+import "@testing-library/jest-dom/vitest";+import { afterEach, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { useState } from "react";+import { MotionInspector } from "./MotionInspector";+import { emptyMotion, motionNodeSchema, type Motion } from "../../lib/motion";++afterEach(cleanup);+it("edits named elements and parameters without changing source until Apply", () => {+ let latest: Motion;+ const bake = vi.fn();+ function Harness() {+ const [motion, change] = useState(() => ({ ...emptyMotion(), nodes: [motionNodeSchema.parse({ id: "title", name: "Title", kind: "text", text: "Hello" })],+ parameters: [{ id: "speed", label: "Speed", type: "number" as const, value: 2, min: 0, max: 10 }] } as Motion));+ latest = motion;+ return <MotionInspector motion={motion} selectedId="title" onSelect={() => {}} onChange={change} onRenderReference={bake} />;+ }+ render(<Harness />);+ fireEvent.change(screen.getByLabelText("Element text"), { target: { value: "Edited" } });+ fireEvent.change(screen.getByLabelText("Element Offset X"), { target: { value: "25" } });+ fireEvent.change(screen.getByLabelText("Speed"), { target: { value: "4" } });+ expect(latest!.overrides.title).toMatchObject({ text: "Edited", offset: [25, 0, 0] });+ expect(latest!.nodes[0].text).toBe("Hello");+ expect(latest!.parameters[0].value).toBe(4);+ const source = "export function update({nodes,time}) { nodes[0].position[0] += time; }";+ fireEvent.change(screen.getByLabelText("Motion JavaScript source"), { target: { value: source } });+ expect(latest!.source).not.toBe(source);+ fireEvent.click(screen.getByRole("button", { name: "Apply source" }));+ expect(latest!.source).toBe(source);+ fireEvent.click(screen.getByRole("button", { name: "Render as reference video" }));+ expect(bake).toHaveBeenCalledOnce();+});diff --git a/src/components/workspace/MotionInspector.tsx b/src/components/workspace/MotionInspector.tsxnew file mode 100644index 0000000..9327bc6--- /dev/null+++ b/src/components/workspace/MotionInspector.tsx@@ -0,0 +1,60 @@+import { useEffect, useState } from "react";+import { motionOverride, motionOverrideSchema, motionSchema, type Motion } from "../../lib/motion";+import { PropSection, PropRow } from "../ui";++export function MotionInspector({ motion, selectedId, onSelect, onChange, disabled = false, onRenderReference, rendering = false }: {+ motion: Motion; selectedId: string | null; onSelect: (id: string | null) => void; onChange: (motion: Motion) => void;+ disabled?: boolean; onRenderReference?: () => void; rendering?: boolean;+}) {+ const [source, setSource] = useState(motion.source);+ const [error, setError] = useState<string | null>(null);+ useEffect(() => setSource(motion.source), [motion.source]);+ const change = (next: Motion) => {+ const result = motionSchema.safeParse(next);+ if (result.success) { onChange(result.data); setError(null); }+ else setError(result.error.issues[0].message);+ };+ const node = motion.nodes.find(({ id }) => id === selectedId);+ const edit = node ? motionOverride(motion, node.id) : null;+ return <>+ <PropSection title="Motion" persistKey="motion.document">+ <PropRow label="Duration"><input className="text-field" type="number" aria-label="Motion duration" min={0.1} max={600} step={0.1} disabled={disabled}+ value={motion.duration} onChange={(e) => change({ ...motion, duration: Number(e.target.value) })} /><span>s</span></PropRow>+ <button className="secondary-button" disabled={disabled || rendering || !onRenderReference} onClick={onRenderReference}>{rendering ? "Rendering reference…" : "Render as reference video"}</button>+ </PropSection>+ <PropSection title="Elements" persistKey="motion.elements">+ {!motion.nodes.length && <p className="settings-description">This Motion is empty. Ask the agent to add elements and animation.</p>}+ {motion.nodes.map((item) => <button key={item.id} className="secondary-button" aria-pressed={selectedId === item.id} onClick={() => onSelect(item.id)}>{item.name}</button>)}+ {node && edit && <>+ {(["offset", "scale", "rotation"] as const).flatMap((property) => (property === "rotation" ? [2] : [0, 1]).map((axis) => {+ const label = `${property === "offset" ? "Offset" : property === "scale" ? "Scale" : "Rotation"}${property === "rotation" ? "" : axis === 0 ? " X" : " Y"}`;+ return <PropRow key={`${property}-${axis}`} label={label}><input className="text-field" type="number" aria-label={`Element ${label}`} disabled={disabled}+ step={property === "scale" ? 0.05 : 1} value={edit[property][axis]} onChange={(e) => {+ const value = Number(e.target.value); if (!Number.isFinite(value)) return;+ const vector = [...edit[property]] as [number, number, number]; vector[axis] = value;+ change({ ...motion, overrides: { ...motion.overrides, [node.id]: { ...edit, [property]: vector } } });+ }} /></PropRow>;+ }))}+ <PropRow label="Fill"><input className="text-field" aria-label="Element fill" disabled={disabled} value={edit.fill ?? node.fill}+ onChange={(e) => change({ ...motion, overrides: { ...motion.overrides, [node.id]: { ...edit, fill: e.target.value } } })} /></PropRow>+ {node.kind === "text" && <PropRow label="Text"><input className="text-field" aria-label="Element text" disabled={disabled} value={edit.text ?? node.text}+ onChange={(e) => change({ ...motion, overrides: { ...motion.overrides, [node.id]: { ...edit, text: e.target.value } } })} /></PropRow>}+ <button className="secondary-button" disabled={disabled} onClick={() => change({ ...motion, overrides: { ...motion.overrides, [node.id]: motionOverrideSchema.parse({}) } })}>Reset element adjustments</button>+ </>}+ </PropSection>+ <PropSection title="Parameters" persistKey="motion.parameters">+ {motion.parameters.length === 0 && <p className="settings-description">The agent can expose movement, timing, color and text controls here.</p>}+ {motion.parameters.map((p) => <PropRow key={p.id} label={p.label}><input className="text-field" aria-label={p.label} disabled={disabled}+ type={p.type === "boolean" ? "checkbox" : p.type === "number" ? "number" : "text"}+ min={p.min} max={p.max} step={p.step ?? "any"} checked={p.type === "boolean" ? Boolean(p.value) : undefined}+ value={p.type === "boolean" ? undefined : String(p.value)} onChange={(e) => change({ ...motion, parameters: motion.parameters.map((item) => item.id !== p.id ? item : {+ ...item, value: p.type === "boolean" ? e.target.checked : p.type === "number" ? Number(e.target.value) : e.target.value,+ }) })} /></PropRow>)}+ </PropSection>+ <PropSection title="JavaScript" persistKey="motion.source">+ <textarea className="text-field motion-source" aria-label="Motion JavaScript source" spellCheck={false} disabled={disabled} value={source} onChange={(e) => setSource(e.target.value)} />+ <button className="secondary-button" disabled={disabled || source === motion.source} onClick={() => change({ ...motion, source })}>Apply source</button>+ {error && <p role="alert">{error}</p>}+ </PropSection>+ </>;+}diff --git a/src/components/workspace/ProgramLayer.tsx b/src/components/workspace/ProgramLayer.tsxindex 0c7ef6a..d6cba63 100644--- a/src/components/workspace/ProgramLayer.tsx+++ b/src/components/workspace/ProgramLayer.tsx@@ -1,3 +1,6 @@+import { MotionCanvas } from "./MotionCanvas";+import type { MotionNode } from "../../lib/motion";+import type { ComponentProps } from "react";import { clipPlaybackRate, clipSourceTimeMs } from "../../lib/clipTiming";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties } from "react";import { clipFrameStyle, clipVisualSettings, type ClipFrameStyle } from "../../lib/export";@@ -21,7 +24,7 @@ export function previewMediaStyle(frame: ClipFrameStyle): CSSProperties {}/** Prepared clips keep their decoder and effect renderer when made visible. */-export function ProgramLayer({ clip, playerKey, asset, sources, playheadMs, playing, rate = 1, active, foreground, muted, externalSeek, depth, media, composited }: {+function MediaProgramLayer({ clip, playerKey, asset, sources, playheadMs, playing, rate = 1, active, foreground, muted, externalSeek, depth, media, composited }: {clip: TimelineClip;playerKey: string;asset: ProjectAsset | undefined;@@ -119,3 +122,17 @@ export function ProgramLayer({ clip, playerKey, asset, sources, playheadMs, play: (!url || (!ready && !isImage)) && <div className="program-note"><span>Loading {clip.label}…</span></div>)}</div>;}++export function ProgramLayer(props: ComponentProps<typeof MediaProgramLayer> & { onMotionFrame?: (clipId: string, nodes: MotionNode[]) => void }) {+ const motionFrame = useCallback((nodes: MotionNode[]) => props.onMotionFrame?.(props.clip.id, nodes), [props.onMotionFrame, props.clip.id]);+ if (!props.asset?.motion) return <MediaProgramLayer {...props} />;+ const { clip, asset, active, depth, composited } = props;+ const needsGpu = hasVideoEffects(activeVideoEffects(clip)) || Boolean(clipChromaKey(clip));+ return <div className="program-layer" data-clip-id={clip.id} data-active={active} aria-hidden={!active}+ style={{ visibility: active ? "visible" : "hidden", zIndex: depth }}>+ <MotionCanvas motion={asset.motion!} time={clipSourceTimeMs(clip, props.playheadMs) / 1000}+ media={props.media} playerKey={props.playerKey} onFrame={motionFrame}+ style={{ ...previewMediaStyle(clipFrameStyle(clipVisualSettings(clip), props.playheadMs - clip.startMs)), ...(composited ? { visibility: "hidden" } : {}) }} />+ {active && !composited && needsGpu && <div className="program-note program-note--error" role="alert">Motion effects preview requires WebGPU.</div>}+ </div>;+}diff --git a/src/components/workspace/ProgramMonitor.tsx b/src/components/workspace/ProgramMonitor.tsxindex 55163a7..28ed139 100644--- a/src/components/workspace/ProgramMonitor.tsx+++ b/src/components/workspace/ProgramMonitor.tsx@@ -1,9 +1,11 @@+import { MotionHandles } from "./MotionHandles";+import type { Motion, MotionNode } from "../../lib/motion";import { clipPlaybackRate, clipSourceTimeMs } from "../../lib/clipTiming";import { ProgramLayer } from "./ProgramLayer";import { ProgramPicture } from "./ProgramPicture";import { Film16 } from "../ui/icons";import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { clipFrameStyle, clipVisualSettings, outputDimensions } from "../../lib/export";+import { clipFrameStyle, clipVisualSettings, outputDimensions, fitRect } from "../../lib/export";import { isTauri } from "../../lib/persistence";import type { ClipTransform, ProjectAsset, ProjectConfig, TimelineClip } from "../../lib/project";import { clipEndMs } from "../../lib/timeline";@@ -49,7 +51,10 @@ const clamp = (value: number, minimum: number, maximum: number) => Math.max(miniconst angleAt = (x: number, y: number, centerX: number, centerY: number) => Math.atan2(y - centerY, x - centerX) * 180 / Math.PI;const normalizedAngle = (value: number) => ((value + 180) % 360 + 360) % 360 - 180;-export function ProgramMonitor({ config, folderPath, playheadMs, playing, rate = 1, onSeek, onPlayingChange, selectedClipId = null, transformEditingDisabled = false, onSelectClip, onTransformChange }: {+export function ProgramMonitor({ config, folderPath, playheadMs, playing, rate = 1, onSeek, onPlayingChange, selectedClipId = null, transformEditingDisabled = false, onSelectClip, onTransformChange, selectedMotionNodeId, onSelectMotionNode, onMotionChange }: {+ selectedMotionNodeId?: string | null;+ onSelectMotionNode?: (id: string) => void;+ onMotionChange?: (motion: Motion) => void;config: ProjectConfig;folderPath: string;playheadMs: number;@@ -70,6 +75,10 @@ export function ProgramMonitor({ config, folderPath, playheadMs, playing, rate =onSelectClip?: (clipId: string) => void;onTransformChange?: (clipId: string, transform: ClipTransform) => void;}) {+ const [motionFrame, setMotionFrame] = useState<{ id: string; nodes: MotionNode[] } | null>(null);+ const receiveMotionFrame = useCallback((id: string, nodes: MotionNode[]) => {+ if (id === selectedClipId && !playing) setMotionFrame({ id, nodes });+ }, [selectedClipId, playing]);const tracks = useMemo(() => continuationPlaybackTracks(config), [config.timeline.tracks, config.assets, config.generationJobs]);const assetsById = useMemo(() => new Map(config.assets.map((candidate) => [candidate.id, candidate])), [config.assets]);const segments = useMemo(() => previewSegments(tracks, assetsById), [tracks, assetsById]);@@ -138,7 +147,19 @@ export function ProgramMonitor({ config, folderPath, playheadMs, playing, rate =const sources = useMemo(() => new PreviewSources(folderPath), [folderPath]);const media = useMemo(() => new PreviewMedia(), [folderPath]);const [composited, setComposited] = useState(false);+ const [pictureSize, setPictureSize] = useState({ width: 0, height: 0 });+ useEffect(() => {+ const element = pictureRef.current;+ if (!element || !asset?.motion) return;+ const measure = () => setPictureSize({ width: element.clientWidth, height: element.clientHeight });+ measure();+ if (typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(measure); observer.observe(element);+ return () => observer.disconnect();+ }, [Boolean(asset?.motion)]);const dimensions = outputDimensions(config.settings.resolution, config.settings.aspectRatio);+ const projectFit = fitRect(dimensions.width, dimensions.height, pictureSize.width || dimensions.width, pictureSize.height || dimensions.height);+ const motionFit = asset?.motion ? fitRect(asset.motion.width, asset.motion.height, projectFit.width, projectFit.height) : projectFit;const previewScale = Math.min(1, 1280 / Math.max(dimensions.width, dimensions.height));useEffect(() => () => sources.dispose(), [sources]);@@ -319,7 +340,7 @@ export function ProgramMonitor({ config, folderPath, playheadMs, playing, rate =else if (asset?.kind === "generated" && !asset.relativePath && !asset.sourcePath) {overlay = <div className="program-note"><Film16 /><span>{clip.label} isn’t generated yet</span></div>;}- else if (!isTauri()) {+ else if (!isTauri() && !asset?.motion) {overlay = <div className="program-note"><Film16 /><span>Playback needs the desktop app</span></div>;}@@ -351,6 +372,7 @@ export function ProgramMonitor({ config, folderPath, playheadMs, playing, rate =sources={sources}media={media}composited={composited}+ onMotionFrame={receiveMotionFrame}playheadMs={depth >= 0 ? playheadMs : prepareAtMs}playing={mediaPlaying}rate={rate}@@ -361,7 +383,13 @@ export function ProgramMonitor({ config, folderPath, playheadMs, playing, rate =depth={depth >= 0 ? layers.length - depth : 0}/>;})}</div>- {clip && frameStyle && editingClipId === clip.id && onTransformChange && !transformEditingDisabled && <div+ {clip && asset?.motion && selectedClipId === clip.id && onMotionChange && onSelectMotionNode && !playing && !transformEditingDisabled && frameStyle && <div className="motion-edit-surface"+ style={{ width: motionFit.width, height: motionFit.height,+ transform: `translate(${frameStyle.transform.positionX / 100 * projectFit.width}px, ${frameStyle.transform.positionY / 100 * projectFit.height}px) scale(${frameStyle.transform.scale / 100}) rotate(${frameStyle.transform.rotation}deg)` }}>+ <MotionHandles motion={asset.motion} nodes={motionFrame?.id === clip.id ? motionFrame.nodes : []} selectedId={selectedMotionNodeId ?? null}+ onSelect={onSelectMotionNode} onChange={onMotionChange} />+ </div>}+ {clip && !asset?.motion && frameStyle && editingClipId === clip.id && onTransformChange && !transformEditingDisabled && <divclassName="program-transform"style={{ transform: `translate(${frameStyle.transform.positionX}%, ${frameStyle.transform.positionY}%) scale(${frameStyle.transform.scale / 100}) rotate(${frameStyle.transform.rotation}deg)` }}role="group"diff --git a/src/components/workspace/TimelineView.test.tsx b/src/components/workspace/TimelineView.test.tsxindex 808819a..3dbdc4b 100644--- a/src/components/workspace/TimelineView.test.tsx+++ b/src/components/workspace/TimelineView.test.tsx@@ -985,3 +985,17 @@ describe("measuring media", () => {expect(folded.assets.map((asset) => [asset.name, asset.durationMs])).toEqual([["Macro footage", 40_000], ["Room tone", 40_000]]);}, 20_000);});+++it("creates an empty inline Motion and places it on an unlocked video track", () => {+ const config = projectWithMedia();+ const { onChange } = render_(config);+ fireEvent.click(screen.getByRole("button", { name: "Add Motion" }));+ const update = onChange.mock.calls.at(-1)![0];+ const next = typeof update === "function" ? update(config) : update;+ const motion = next.assets.find((asset: ProjectAsset) => asset.kind === "motion")!;+ expect(motion.motion.nodes).toEqual([]);+ expect(motion.motion.source).toContain("export function update");+ expect(motion.relativePath).toBeUndefined();+ expect(next.timeline.tracks.flatMap((track: ProjectConfig["timeline"]["tracks"][number]) => track.clips).some((clip: TimelineClip) => clip.assetId === motion.id)).toBe(true);+});diff --git a/src/components/workspace/TimelineView.tsx b/src/components/workspace/TimelineView.tsxindex a933312..fb35573 100644--- a/src/components/workspace/TimelineView.tsx+++ b/src/components/workspace/TimelineView.tsx@@ -1,3 +1,7 @@+import { startMotionReferenceJob } from "../../lib/exportJob";+import { motionReferenceExport, motionVideoReference } from "../../lib/motionReference";+import { emptyMotion, MOTION_MIME, type Motion } from "../../lib/motion";+import { MotionInspector } from "./MotionInspector";import { clipEffectCount, ClipEffects } from "./ClipEffects";import { clipPlaybackRate, clipSourceTimeMs, MIN_CLIP_SPEED, MAX_CLIP_SPEED } from "../../lib/clipTiming";import { continuationPlaybackTracks, sceneMediaDurationMs, sceneMediaStartSeconds } from "../../lib/continuationMedia";@@ -83,8 +87,9 @@ const SHUTTLE_SPEEDS = [1, 2, 4];Five kinds, each with one colour and one glyph wherever it appears: theclip's title strip, the track chip, the inspector's kind chip. The kind isthe MEDIA's; a clip whose file is missing takes its track's. */-type ClipKind = "video" | "generated" | "image" | "audio" | "caption";+type ClipKind = "motion" | "video" | "generated" | "image" | "audio" | "caption";const CLIP_KINDS: Record<ClipKind, { label: string; color: string; icon: React.ReactNode; glyph: React.ReactNode }> = {+ motion: { label: "Motion", color: "var(--clip-image)", icon: <Sparkle16 />, glyph: <Sparkle12 /> },video: { label: "Video", color: "var(--clip-video)", icon: <Film16 />, glyph: <Film12 aria-hidden="true" /> },generated: { label: "Generated video", color: "var(--clip-generated)", icon: <Sparkle16 />, glyph: <Sparkle12 aria-hidden="true" /> },image: { label: "Still image", color: "var(--clip-image)", icon: <Image16 />, glyph: <Image12 aria-hidden="true" /> },@@ -221,6 +226,9 @@ export function TimelineView({ config, folderPath, generationCompletionTimes = {}) {const firstClip = config.timeline.tracks.flatMap((track) => track.clips)[0];const fps = config.settings.frameRate;+ const [motionRendering, setMotionRendering] = useState(false);+ const [motionNotice, setMotionNotice] = useState<string | null>(null);+ const [motionNodeId, setMotionNodeId] = useState<string | null>(null);const [selectedId, setSelectedId] = useState(firstClip?.id ?? "");const [playhead, setPlayhead] = useState(firstClip?.startMs ?? 0);const [playing, setPlaying] = useState(false);@@ -801,7 +809,7 @@ export function TimelineView({ config, folderPath, generationCompletionTimes = {? Math.max(1, ((sceneMediaDurationMs(selectedAsset) ?? selectedAsset.durationMs) - selected.sourceStartMs) / clipPlaybackRate(selected)): null;const minClipMs = Math.max(1, Math.round(1000 / fps));- const speedDisabled = !selected || tracks.find((track) => track.id === selected.trackId)?.locked || !selectedAsset || !["video", "generated", "audio"].includes(selectedAsset.kind);+ const speedDisabled = !selected || tracks.find((track) => track.id === selected.trackId)?.locked || !selectedAsset || !["video", "generated", "audio", "motion"].includes(selectedAsset.kind);const changeSpeed = (percent: number) => {if (!selected || speedDisabled) return;const next = retimeClip(tracks, selected.id, percent / 100);@@ -1056,6 +1064,41 @@ export function TimelineView({ config, folderPath, generationCompletionTimes = {setSelectedId((current) => removedClipIds.has(current) ? "" : current);};+ const updateMotion = (motion: Motion) => {+ if (!selectedAsset?.motion) return;+ const id = selectedAsset.id;+ onChange((current) => ({ ...current, assets: current.assets.map((asset) => asset.id !== id ? asset : {+ ...asset, motion, width: motion.width, height: motion.height, durationMs: Math.round(motion.duration * 1000),+ }) }), `motion:${id}`);+ };+ const renderMotionReference = async () => {+ if (!selectedAsset?.motion || motionRendering || !isTauri()) return;+ const asset = structuredClone(selectedAsset);+ setMotionRendering(true); setMotionNotice(null);+ try {+ const saved = await startMotionReferenceJob({ folderPath, ...motionReferenceExport(config, asset) });+ if (saved) {+ const reference = motionVideoReference(asset, saved.relativePath);+ onChange((current) => ({ ...current, references: [...current.references, reference] }));+ setMotionNotice(`Added ${reference.name} to References. Select it in a MiniMax video prompt.`);+ } else setMotionNotice("Motion reference was not saved. See Work Queue for cancellation or error details.");+ } catch (reason) { setMotionNotice(String(reason)); }+ finally { setMotionRendering(false); }+ };+ const addMotion = () => {+ const size = outputDimensions(config.settings.resolution, config.settings.aspectRatio);+ const motion = emptyMotion(Math.min(4096, size.width), Math.min(4096, size.height));+ const id = `motion-${crypto.randomUUID()}`, clipId = `clip-${crypto.randomUUID()}`;+ const track = tracks.find((t) => !t.locked && t.kind === "video");+ if (!track) { setImportError("Unlock a video track to add a Motion."); return; }+ const start = Math.max(playhead, ...track.clips.map(clipEndMs));+ const asset: ProjectAsset = { id, name: "Empty Motion", kind: "motion", mimeType: MOTION_MIME, motion, width: motion.width, height: motion.height,+ durationMs: 5000, hasAudio: false, createdAt: new Date().toISOString() };+ const item: TimelineClip = { id: clipId, assetId: id, trackId: track.id, label: asset.name, startMs: start, durationMs: 5000, sourceStartMs: 0, status: "approved" };+ onChange((current) => ({ ...current, assets: [...current.assets, asset], timeline: { ...current.timeline,+ tracks: current.timeline.tracks.map((t) => t.id === track.id ? { ...t, clips: [...t.clips, item] } : t) } }));+ setSelectedId(clipId); setMotionNodeId(null); setMediaSelectedId(id); setPanelTab("media"); setPlayhead(start);+ };const addScene = () => {// A new project already carries an unstarted draft made from the user's own// words, so open that rather than stacking a near-identical second shot.@@ -1243,6 +1286,7 @@ export function TimelineView({ config, folderPath, generationCompletionTimes = {items={[{ value: "scenes", label: "Scenes" }, { value: "media", label: "Media" }]}/>}actions={<>+ <button type="button" className="scene-panel__import" aria-label="Add Motion" onClick={addMotion} {...tooltipProps("Add empty Motion")}><Sparkle16 /><span className="sr-only">Add Motion</span></button><buttontype="button"className="scene-panel__import"@@ -1386,6 +1430,7 @@ export function TimelineView({ config, folderPath, generationCompletionTimes = {selectedClipId={selectedId}transformEditingDisabled={selectedTrack?.locked ?? false}onSelectClip={setSelectedId}+ selectedMotionNodeId={motionNodeId} onSelectMotionNode={setMotionNodeId} onMotionChange={selectedAsset?.motion ? updateMotion : undefined}onTransformChange={(clipId, transform) => updateClip(clipId, { transform: roundClipTransform(transform) }, `transform:${clipId}:gesture`)}/>: <EmptyState@@ -1470,6 +1515,8 @@ export function TimelineView({ config, folderPath, generationCompletionTimes = {onClick={(event) => menu.open(event.currentTarget, clipMenuItems(selected), { "aria-label": `${selected.label} actions`, placement: "bottom-end", focusFirst: true })}><More16 aria-hidden="true" /></button>}/>+ {selectedAsset?.motion && <MotionInspector key={selectedAsset.id} motion={selectedAsset.motion} selectedId={motionNodeId} onSelect={setMotionNodeId} onChange={updateMotion} disabled={visualControlsDisabled} onRenderReference={isTauri() ? () => void renderMotionReference() : undefined} rendering={motionRendering} />}+ {motionNotice && <p className="panel-hint" role="status">{motionNotice}</p>}<PropSection title="Timing" persistKey="timeline.clip.timing" summary={`${shortTimecode(selected.startMs, fps)} → ${shortTimecode(clipEndMs(selected), fps)}`}><PropRow label="Speed" htmlFor="clip-speed" value={clipPlaybackRate(selected)} defaultValue={1}onReset={speedDisabled ? undefined : () => changeSpeed(100)}diff --git a/src/lib/export.ts b/src/lib/export.tsindex e20271e..93b803c 100644--- a/src/lib/export.ts+++ b/src/lib/export.ts@@ -481,7 +481,7 @@ export function visibleClipsAt(if (best) {visible.push(best);const transition = clipTransition(best);- const revealing = Boolean(clipChromaKey(best)) || clipLook(best).opacity < 100 ||+ const revealing = Boolean(assetsById?.get(best.assetId)?.motion) || Boolean(clipChromaKey(best)) || clipLook(best).opacity < 100 ||(transition.type !== "cut" && timeMs - best.startMs < transition.durationMs);if (!revealing) break;}@@ -571,10 +571,10 @@ export function buildExportPlan(config: ProjectConfig, settings: ExportSettings)outside it — imported video and audio are never copied in, so they onlyever have the second. Neither means there is no file to read, and the runwould die on the first frame; say so here, where the button still is. */- if (!asset.relativePath && !asset.sourcePath) {+ if (!asset.motion && !asset.relativePath && !asset.sourcePath) {locationless.push(`${segment.label} (${asset.name})`);}- const drawable = DEMUXABLE_VIDEO.has(asset.mimeType) || DRAWABLE_IMAGE.has(asset.mimeType);+ const drawable = Boolean(asset.motion) || DEMUXABLE_VIDEO.has(asset.mimeType) || DRAWABLE_IMAGE.has(asset.mimeType);if (!drawable) undecodable.push(`${segment.label} (${asset.name}, ${asset.mimeType})`);}if (missing.length > 0) {diff --git a/src/lib/exportJob.test.ts b/src/lib/exportJob.test.tsindex 8223fec..8c771d5 100644--- a/src/lib/exportJob.test.ts+++ b/src/lib/exportJob.test.ts@@ -5,7 +5,7 @@ import { listen } from "@tauri-apps/api/event";import { createProjectConfig } from "./project";import { defaultExportSettings, buildExportPlan } from "./export";import { runExport, writeExportFile, type ExportProgress, type ExportResult } from "./exportPipeline";-import { cancelExportJob, clearFinishedExports, getExportJobs, resetExportJobForTests, startExportJob, startImageExportJob } from "./exportJob";+import { cancelExportJob, clearFinishedExports, getExportJobs, resetExportJobForTests, startExportJob, startImageExportJob, startMotionReferenceJob } from "./exportJob";vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => undefined) }));@@ -71,3 +71,25 @@ it("follows image progress outside its view and cancels the native export", asynexpect(invoke).toHaveBeenCalledWith("cancel_image_export", { jobId: id });expect(getExportJobs()[0]).toMatchObject({ status: "cancelled", cancelling: false });});+++it("saves rendered Motion bytes into the project and returns its reference path", async () => {+ vi.mocked(runExport).mockResolvedValue(result);+ vi.mocked(invoke).mockResolvedValue({ relativePath: "media/generated/motion.mp4", bytes: 42 });+ const saved = await startMotionReferenceJob(video());+ expect(saved).toEqual({ relativePath: "media/generated/motion.mp4", bytes: 42 });+ expect(invoke).toHaveBeenCalledWith("write_generated_video", result.bytes, { headers: {+ "x-generated-folder": "D%3A%2FMovie", "x-generated-job": expect.stringMatching(/^motion-/),+ } });+ expect(getExportJobs()[0]).toMatchObject({ status: "completed", outcome: { kind: "saved", path: "D:/Movie/media/generated/motion.mp4" } });+});++it("does not save a Motion reference if encoding is cancelled", async () => {+ let finish!: (result: ExportResult) => void;+ vi.mocked(runExport).mockImplementation(() => new Promise((resolve) => { finish = resolve; }));+ const done = startMotionReferenceJob(video());+ cancelExportJob(); finish(result);+ expect(await done).toBeNull();+ expect(invoke).not.toHaveBeenCalled();+ expect(getExportJobs()[0].status).toBe("cancelled");+});diff --git a/src/lib/exportJob.ts b/src/lib/exportJob.tsindex fc4ec31..95c1f78 100644--- a/src/lib/exportJob.ts+++ b/src/lib/exportJob.ts@@ -268,3 +268,23 @@ export function resetExportJobForTests() {jobs = []; pending = []; running = false;listeners.forEach((listener) => listener());}++/** Uses the normal export queue so Motion baking participates in cancellation,+ * work status and the app's exit guard, including after its view unmounts. */+export async function startMotionReferenceJob(options: Omit<StartExportOptions, "destination">): Promise<{ relativePath: string; bytes: number } | null> {+ const snapshot = structuredClone(options);+ let saved: { relativePath: string; bytes: number } | null = null;+ await enqueueExport({ folderPath: options.folderPath, projectName: `${options.config.name} - Motion reference`, destination: null, kind: "video" }, async () => {+ try {+ const result = await runExport({ ...snapshot, cancelled: () => cancelRequested, onProgress: (progress) => set({ progress }) });+ if (cancelRequested) throw new ExportCancelled();+ saved = await invoke<{ relativePath: string; bytes: number }>("write_generated_video", result.bytes, { headers: {+ "x-generated-folder": encodeURIComponent(snapshot.folderPath), "x-generated-job": `motion-${crypto.randomUUID()}`,+ } });+ set({ outcome: { kind: "saved", path: `${snapshot.folderPath}/${saved.relativePath}`, bytes: saved.bytes, audioProblems: [], audioShortfalls: [] } });+ } catch (reason) {+ set({ outcome: reason instanceof ExportCancelled ? { kind: "cancelled" } : { kind: "failed", message: String(reason) } });+ }+ });+ return saved;+}diff --git a/src/lib/exportPipeline.ts b/src/lib/exportPipeline.tsindex ef92bdc..3570e8d 100644--- a/src/lib/exportPipeline.ts+++ b/src/lib/exportPipeline.ts@@ -1,3 +1,4 @@+import { motionFrameReader } from "./motionRuntime";/// <reference types="@webgpu/types" />/* ============================================================================@@ -894,6 +895,7 @@ interface LayerFrameReader {export async function openLayerFrameReader(folderPath: string, asset: ProjectAsset, startUs: number, stopIfCancelled: () => void,): Promise<LayerFrameReader> {+ if (asset.motion) return motionFrameReader(asset.motion, stopIfCancelled);const bytes = await readAssetBytes(folderPath, asset);stopIfCancelled();if (asset.mimeType.startsWith("image/")) {@@ -1381,7 +1383,7 @@ export async function runExport(options: ExportRunOptions): Promise<ExportResultstopIfCancelled();if (segment.kind === "gap") {for (let index = segment.startFrame; index < segment.endFrame; index += 1) await emit(null, index);- } else if (segment.underlays?.length) {+ } else if (segment.underlays?.length || assetFor(segment.assetId)?.motion) {await renderLayeredSegment(segment);} else {await renderClipSegment(segment);@@ -1521,6 +1523,15 @@ export async function drawPreviewFrame(options: {const asset = config.assets.find((candidate) => candidate.id === clip.assetId);if (!asset) throw new Error("This clip points at media that is not in this project.");+ if (asset.motion) {+ const reader = motionFrameReader(asset.motion, () => {});+ try {+ const frame = await reader.frameAt(clip.sourceTimeMs * 1000);+ const box = fitRect(frame.displayWidth, frame.displayHeight, canvas.width, canvas.height);+ context.drawImage(frame, box.x, box.y, box.width, box.height);+ } finally { reader.dispose(); }+ return;+ }const url = await sources.url(asset);if (asset.mimeType.startsWith("image/")) {diff --git a/src/lib/motion.test.ts b/src/lib/motion.test.tsnew file mode 100644index 0000000..6234224--- /dev/null+++ b/src/lib/motion.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from "vitest";+import { emptyMotion, MOTION_MIME, motionNodeSchema, motionOverrideSchema, motionSchema } from "./motion";+import { evaluateMotion, type MotionUpdate } from "./motionEvaluation";+import { motionReferenceExport, motionVideoReference } from "./motionReference";+import { createProjectConfig, isReferenceUsable, parseProjectConfig, type ProjectAsset } from "./project";+import { visibleClipsAt } from "./export";++function fixture() {+ const motion = emptyMotion(320, 180);+ motion.nodes = [motionNodeSchema.parse({ id: "title", name: "Title", kind: "text", text: "Original" })];+ motion.parameters = [{ id: "speed", label: "Speed", type: "number", value: 40 }];+ const asset: ProjectAsset = { id: "motion-test", name: "Test", kind: "motion", mimeType: MOTION_MIME, motion, createdAt: new Date(0).toISOString() };+ const config = createProjectConfig({ name: "Test", prompt: "Test", resolution: "720p", aspectRatio: "16:9", targetDurationSeconds: 5 });+ config.assets = [asset];+ return { motion, asset, config };+}++describe("Motions", () => {+ it("evaluates arbitrary seeks independently and applies editable overrides after animation", () => {+ const { motion } = fixture();+ motion.overrides.title = motionOverrideSchema.parse({ offset: [10, 20, 0], text: "Edited", scale: [2, 1, 1] });+ const update: MotionUpdate = ({ nodes, time, parameters, random }, draw) => {+ nodes[0].position[0] += time * Number(parameters.speed);+ draw.ellipse({ id: "particle", position: [random() * 100, 0, 0] });+ };+ const frame = evaluateMotion(motion, 2, update);+ evaluateMotion(motion, 4, update);+ expect(evaluateMotion(motion, 2, update)).toEqual(frame);+ expect(frame[0]).toMatchObject({ position: [90, 20, 0], text: "Edited", scale: [2, 1, 1] });+ expect(motion.nodes[0]).toMatchObject({ position: [0, 0, 0], text: "Original" });+ expect(evaluateMotion(motion, 100, update)[0].position[0]).toBe(210);+ });+ it("supports scene IDs that also name Object prototype properties", () => {+ const { motion } = fixture();+ motion.nodes[0].id = "constructor";+ expect(evaluateMotion(motion, 0, () => {})[0].position).toEqual([0, 0, 0]);+ });+ it("rejects invalid script output, duplicate IDs and asynchronous updates", () => {+ const { motion } = fixture();+ expect(() => evaluateMotion(motion, 0, ({ nodes }) => { nodes[0].position[0] = Infinity; })).toThrow();+ expect(() => evaluateMotion(motion, 0, (_, draw) => draw.rect({ id: "title" }))).toThrow(/unique/);+ expect(() => evaluateMotion(motion, 0, async () => {})).toThrow(/synchronous/);+ expect(() => evaluateMotion(motion, 0, (_, draw) => { for (let i = 0; i < 1024; i++) draw.rect({}); })).toThrow(/1024/);+ });+ it("round trips inline scenes, source, parameters and adjustments without a media path", () => {+ const { config, motion } = fixture();+ motion.overrides.title = motionOverrideSchema.parse({ offset: [7, 9, 0] });+ expect(parseProjectConfig(JSON.parse(JSON.stringify(config))).assets[0].motion).toEqual(motion);+ expect(() => parseProjectConfig({ ...config, assets: [{ ...config.assets[0], relativePath: "media/fake.mp4" }] })).toThrow();+ expect(motionSchema.safeParse({ ...motion, overrides: { missing: {} } }).success).toBe(false);+ expect(motionSchema.safeParse({ ...motion, parameters: [{ id: "speed", label: "Speed", type: "number", value: "wrong" }] }).success).toBe(false);+ });+ it("bakes only the selected Motion and creates a usable video reference", () => {+ const { config, asset, motion } = fixture();+ motion.duration = 0.5;+ const result = motionReferenceExport(config, asset);+ expect(result.plan.blockers).toEqual([]);+ expect(result.plan.frameCount).toBe(48);+ expect(result.settings.frameRate).toBe(24);+ expect(result.config.timeline.tracks[0].clips).toHaveLength(1);+ expect(result.config.timeline.tracks[0].clips[0].durationMs).toBe(2000);+ expect(config.timeline.tracks[0].clips).toHaveLength(0);+ expect(result.config.assets[0].motion).not.toBe(motion);+ const reference = motionVideoReference(asset, "media/motion-test.mp4");+ expect(isReferenceUsable(reference)).toBe(true);+ expect(reference.video).toMatchObject({ mode: "video", durationSeconds: 2, includeAudio: false });+ motion.duration = 20;+ expect(motionVideoReference(asset, "media/motion-long.mp4").video?.durationSeconds).toBe(15);+ });+ it("keeps opaque footage underneath transparent Motion layers", () => {+ const { config, asset } = fixture();+ const { config: snapshot } = motionReferenceExport(config, asset);+ const top = snapshot.timeline.tracks[0]; top.muted = false;+ const background: ProjectAsset = { id: "video", kind: "video", name: "Video", mimeType: "video/mp4", relativePath: "media/video.mp4", createdAt: asset.createdAt };+ const bottom = { ...top, id: "bottom", clips: [{ ...top.clips[0], id: "video-clip", assetId: "video", trackId: "bottom" }] };+ expect(visibleClipsAt([top, bottom], 100, new Map([[asset.id, asset], [background.id, background]])).map(c => c.assetId)).toEqual([asset.id, "video"]);+ });+});diff --git a/src/lib/motion.ts b/src/lib/motion.tsindex cffcccd..83735cf 100644--- a/src/lib/motion.ts+++ b/src/lib/motion.ts@@ -52,10 +52,10 @@ export function emptyMotion(width = 1280, height = 720): Motion {return motionSchema.parse({ version: 1, space: "2d", width, height, duration: 5, nodes: [], parameters: [],source: "// Ask the agent to create this Motion.\n// Time is in seconds. Modify named nodes or add primitives with draw.\nexport function update({ time, duration, parameters, nodes }, draw) {\n}\n" });}-export const motionOverride = (motion: Motion, id: string): MotionOverride => motion.overrides[id] ?? motionOverrideSchema.parse({});+export const motionOverride = (motion: Motion, id: string): MotionOverride => Object.prototype.hasOwnProperty.call(motion.overrides, id) ? motion.overrides[id] : motionOverrideSchema.parse({});export function applyMotionOverrides(nodes: MotionNode[], motion: Motion): MotionNode[] {return nodes.map((node) => {- const edit = motion.overrides[node.id];+ const edit = Object.prototype.hasOwnProperty.call(motion.overrides, node.id) ? motion.overrides[node.id] : undefined;if (!edit) return node;return { ...node, position: node.position.map((v, i) => v + edit.offset[i]) as MotionNode["position"],rotation: node.rotation.map((v, i) => v + edit.rotation[i]) as MotionNode["rotation"],diff --git a/src/lib/motionReference.ts b/src/lib/motionReference.tsnew file mode 100644index 0000000..800d453--- /dev/null+++ b/src/lib/motionReference.ts@@ -0,0 +1,22 @@+import { bitrateFor, buildExportPlan, defaultExportSettings } from "./export";+import { type ProjectAsset, type ProjectConfig, type ProjectReference } from "./project";++/** Bake the complete Motion, independent of its current timeline placement.+ * Short motions hold their final pose to satisfy the two-second video input. */+export function motionReferenceExport(config: ProjectConfig, asset: ProjectAsset) {+ if (!asset.motion) throw new Error("Select a Motion to render as a reference.");+ const durationMs = Math.max(2000, Math.round(asset.motion.duration * 1000));+ const snapshot: ProjectConfig = { ...structuredClone(config), generationJobs: [], assets: [structuredClone(asset)],+ timeline: { ...config.timeline, tracks: [{ id: "motion-reference", kind: "video", name: "Motion", locked: false, muted: true,+ clips: [{ id: "motion-reference-clip", assetId: asset.id, trackId: "motion-reference", startMs: 0, durationMs, sourceStartMs: 0, label: asset.name, status: "approved" }] }] } };+ const settings = { ...defaultExportSettings(snapshot), width: Math.ceil(asset.motion.width / 2) * 2, height: Math.ceil(asset.motion.height / 2) * 2, frameRate: 24 as const };+ const plan = buildExportPlan(snapshot, settings);+ if (plan.blockers.length) throw new Error(plan.blockers.join(" "));+ return { config: snapshot, settings, plan, bitrate: bitrateFor(settings.width, settings.height, settings.frameRate, "high") };+}++export function motionVideoReference(asset: ProjectAsset, relativePath: string): ProjectReference {+ return { id: `ref-${crypto.randomUUID()}`, kind: "video", name: `${asset.name} Motion`, description: "", relativePath,+ intendedUse: ["style"], createdAt: new Date().toISOString(),+ video: { mode: "video", startSeconds: 0, durationSeconds: Math.min(15, Math.max(2, asset.motion!.duration)), includeAudio: false } };+}diff --git a/src/lib/previewPresentation.ts b/src/lib/previewPresentation.tsindex b955b3e..7d7ceb1 100644--- a/src/lib/previewPresentation.ts+++ b/src/lib/previewPresentation.ts@@ -1,13 +1,15 @@+import { clipSourceTimeMs } from "./clipTiming";import { clipFrameStyle, clipVisualSettings } from "./export";import type { Compositor } from "./exportPipeline";import type { TimelineClip } from "./project";-type PreviewMediaElement = HTMLVideoElement | HTMLImageElement;+type PreviewMediaElement = HTMLVideoElement | HTMLImageElement | HTMLCanvasElement;/** Prepared decoders belong to players; the displayed canvas belongs to the* monitor. Media arriving asynchronously requests a redraw of the current cut. */export class PreviewMedia {private elements = new Map<string, PreviewMediaElement>();+ private motionTimes = new Map<string, number>();private listeners = new Set<() => void>();private events = ["loadeddata", "seeked", "load"];private changed = () => { this.listeners.forEach((listener) => listener()); };@@ -19,9 +21,14 @@ export class PreviewMedia {if (element) {this.elements.set(id, element);this.events.forEach((event) => element.addEventListener(event, this.changed));- } else this.elements.delete(id);+ } else { this.elements.delete(id); this.motionTimes.delete(id); }}+ setMotionTime(id: string, time: number) { this.motionTimes.set(id, time); }+ motionTime(id: string) { return this.motionTimes.get(id); }++ invalidate() { this.changed(); }+get(id: string) { return this.elements.get(id); }subscribe(listener: () => void) {@@ -37,10 +44,13 @@ export function presentPreviewFrame(compositor: Compositor, media: PreviewMedia,const pictures: { frame: VideoFrame; clip: TimelineClip }[] = [];try {for (const clip of layers) {- const element = media.get(playerKeys?.get(clip.id) ?? clip.id);+ const key = playerKeys?.get(clip.id) ?? clip.id;+ const element = media.get(key);if (!element) return false;+ const canvas = element instanceof HTMLCanvasElement;const video = element instanceof HTMLVideoElement;- if (video ? element.readyState < 2 || element.seeking || !element.videoWidth || !element.videoHeight+ if (canvas && media.motionTime(key) !== undefined && Math.abs(media.motionTime(key)! - clipSourceTimeMs(clip, playheadMs) / 1000) > 0.1) return false;+ if (canvas ? !element.width || !element.height : video ? element.readyState < 2 || element.seeking || !element.videoWidth || !element.videoHeight: !element.complete || !element.naturalWidth || !element.naturalHeight) return false;pictures.push({ frame: new VideoFrame(element, { timestamp: Math.round(playheadMs * 1000) }), clip });}diff --git a/src/lib/timelineCapture.ts b/src/lib/timelineCapture.tsindex e1c5c02..6a46fa4 100644--- a/src/lib/timelineCapture.ts+++ b/src/lib/timelineCapture.ts@@ -18,7 +18,7 @@ export function timelineCapturePlan(config: ProjectConfig, at: number) {const layers = visibleClipsAt(tracks, timeMs, assets).reverse().map((clip) => {const asset = assets.get(clip.assetId);if (!asset) throw new Error(`Clip "${clip.label}" points at missing media.`);- if (!asset.relativePath && !asset.sourcePath) throw new Error(`Clip "${clip.label}" has no generated or imported media to capture.`);+ if (!asset.motion && !asset.relativePath && !asset.sourcePath) throw new Error(`Clip "${clip.label}" has no generated or imported media to capture.`);return { asset, sourceTimeUs: Math.round((clipSourceTimeMs(clip, timeMs)) * 1000),style: clipFrameStyle(clipVisualSettings(clip), timeMs - clip.startMs) };});diff --git a/src/styles/timeline.css b/src/styles/timeline.cssindex f781c68..076ed85 100644--- a/src/styles/timeline.css+++ b/src/styles/timeline.css@@ -1754,3 +1754,14 @@ button.transport-time:hover { background: var(--fill-subtle-hover); }.grading-wheel__handle { position: absolute; width: 10px; height: 10px; border: 2px solid var(--focus-outer); border-radius: 50%; box-shadow: 0 0 0 1px var(--focus-inner); transform: translate(-50%, -50%); pointer-events: none; }.generation-effects > .clip-effect__note { padding-left: 0; }++/* Motions share the media layout and preserve transparent backgrounds. */+.program-layer > .motion-canvas { width: 100%; height: 100%; object-fit: contain; }+.media-card .motion-canvas { width: 100%; height: 100%; max-height: 140px; object-fit: contain; }+.motion-source { width: 100%; min-height: 280px; resize: vertical; font-family: ui-monospace, monospace; font-size: 12px; line-height: 1.5; white-space: pre; tab-size: 2; }+.motion-edit-surface { position: absolute; left: 50%; top: 50%; translate: -50% -50%; z-index: 5; pointer-events: none; }+.motion-handles { position: absolute; inset: 0; pointer-events: none; }+.motion-element { position: absolute; min-width: 8px; min-height: 8px; padding: 0; background: transparent; border: 1px solid transparent; transform-origin: 0 0; pointer-events: auto; cursor: move; touch-action: none; }+.motion-element:hover { border-color: var(--text-secondary); }+.motion-element.is-selected { border: 1px solid var(--accent); }+.motion-resize { position: absolute; width: 10px; height: 10px; right: -5px; bottom: -5px; background: var(--on-accent); border: 1px solid var(--accent); cursor: nwse-resize; }