From 728720f0236d2d7014e79e727fadc48726ad245b Mon Sep 17 00:00:00 2001 From: "haixin.yang" Date: Tue, 21 Jul 2026 19:19:39 +0800 Subject: [PATCH] Add versioned timeline command runner --- README.md | 15 +- package.json | 1 + scripts/timeline-command.mjs | 61 +++++++ .../.claude-plugin/plugin.json | 4 +- skills/edit-timeline-studio/README.md | 48 +++++ skills/edit-timeline-studio/SKILL.md | 6 +- .../edit-timeline-studio/agents/openai.yaml | 4 +- .../docs/agent-video-editing.md | 19 ++ .../docs/claude-code-video-editing.md | 24 +++ .../docs/codex-video-editing.md | 24 +++ .../docs/command-reference.md | 43 +++++ .../edit-timeline-studio/docs/comparison.md | 12 ++ skills/edit-timeline-studio/docs/examples.md | 52 ++++++ .../references/current-capabilities.md | 24 +-- src/App.jsx | 8 +- src/hooks/useProjectFiles.js | 22 ++- src/lib/projectCommandEngine.js | 164 ++++++++++++++++++ src/lib/projectCommandEngine.test.js | 62 +++++++ src/lib/timelineCommandCli.test.js | 49 ++++++ 19 files changed, 612 insertions(+), 30 deletions(-) create mode 100644 scripts/timeline-command.mjs create mode 100644 skills/edit-timeline-studio/README.md create mode 100644 skills/edit-timeline-studio/docs/agent-video-editing.md create mode 100644 skills/edit-timeline-studio/docs/claude-code-video-editing.md create mode 100644 skills/edit-timeline-studio/docs/codex-video-editing.md create mode 100644 skills/edit-timeline-studio/docs/command-reference.md create mode 100644 skills/edit-timeline-studio/docs/comparison.md create mode 100644 skills/edit-timeline-studio/docs/examples.md create mode 100644 src/lib/projectCommandEngine.js create mode 100644 src/lib/projectCommandEngine.test.js create mode 100644 src/lib/timelineCommandCli.test.js diff --git a/README.md b/README.md index ae9279d..98bb61f 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ Timeline Studio is a local-first AI video editor that runs in the browser. It co ## Agent Skill -The repository includes [`edit-timeline-studio`](skills/edit-timeline-studio/SKILL.md), a Codex-compatible Skill for planning, executing, and verifying editable video timelines. +The repository includes the [AI Video Editing Skill for Codex, Claude Code, Copilot and Gemini CLI](skills/edit-timeline-studio/README.md), backed by [`edit-timeline-studio`](skills/edit-timeline-studio/SKILL.md) for planning, executing, and verifying editable video timelines. It helps an agent: @@ -45,7 +45,14 @@ It helps an agent: - verify track placement, transitions, captions, overlays, audible audio, and final export artifacts; - keep the editable `.timeline` project as the source of truth instead of returning only an opaque render. -The current Skill is honest about its boundary: browser-driven editing is available today, while the versioned headless command runner described in its command contract is the next automation layer. +The first versioned headless command runner is now available. It loads and inspects portable projects, validates revisioned JSON plans, applies supported operations transactionally, supports dry runs and idempotent operation IDs, and writes a new `.timeline` archive without rewriting its media files. Browser control remains the compatibility path for operations that are not in the command registry yet. + +```bash +npm run agent -- inspect /absolute/path/project.timeline +npm run agent -- run /absolute/path/edit-plan.json +``` + +The initial write registry supports `timed.move` for voiceover clips, `caption.update`, `caption.unlink_audio`, and `caption.link_audio`. See the [command contract](skills/edit-timeline-studio/references/command-contract.md) for the plan envelope. Install through the public [skills.sh](https://skills.sh/MartinDelophy/ai-video-editor) directory (the current CLI requires Node.js 22.20.0 or later): @@ -71,8 +78,8 @@ gh skill preview MartinDelophy/ai-video-editor edit-timeline-studio ## Roadmap -- **Now:** harden deterministic offline export, improve timeline editing reliability, and expand end-to-end browser tests. -- **Next:** ship the versioned headless command runner for agent-driven editing and make reusable project templates easier to share. +- **Now:** expand the versioned command registry, harden deterministic offline export, and improve timeline editing reliability. +- **Next:** add media probing/render commands and expose the shared command engine through MCP. - **Later:** add collaborative review workflows, a plugin extension surface, and more locally verified AI models. Roadmap priorities are shaped in [GitHub Discussions](https://github.com/MartinDelophy/ai-video-editor/discussions). Feature requests and real-world workflow feedback are welcome. diff --git a/package.json b/package.json index c832b7d..96174f7 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "scripts": { "dev": "vite --host 127.0.0.1", "build": "vite build", + "agent": "node scripts/timeline-command.mjs", "preview": "vite preview --host 127.0.0.1", "lint": "eslint .", "format": "prettier --write .", diff --git a/scripts/timeline-command.mjs b/scripts/timeline-command.mjs new file mode 100644 index 0000000..3068297 --- /dev/null +++ b/scripts/timeline-command.mjs @@ -0,0 +1,61 @@ +#!/usr/bin/env node + +import { readFile, writeFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import { strFromU8, strToU8, unzipSync, zipSync } from "fflate"; +import { applyCommandPlan, inspectProject } from "../src/lib/projectCommandEngine.js"; + +const PROJECT_FILE = "project.json"; + +async function readArchive(path) { + const files = unzipSync(new Uint8Array(await readFile(path))); + if (!files[PROJECT_FILE]) throw new Error("Archive is missing project.json"); + const payload = JSON.parse(strFromU8(files[PROJECT_FILE])); + if (payload?.format !== "timeline-studio-archive" || !payload.project) throw new Error("Invalid .timeline archive"); + return { files, payload }; +} + +function print(value) { + process.stdout.write(`${JSON.stringify(value, null, 2)}\n`); +} + +async function main() { + const [command, argument] = process.argv.slice(2); + if (!command || !argument || !["inspect", "run"].includes(command)) { + throw Object.assign(new Error("Usage: npm run agent -- inspect | run "), { exitCode: 2 }); + } + if (command === "inspect") { + const { payload } = await readArchive(resolve(argument)); + print({ ok: true, ...inspectProject(payload.project) }); + return; + } + const plan = JSON.parse(await readFile(resolve(argument), "utf8")); + const projectPath = resolve(plan.project); + const { files, payload } = await readArchive(projectPath); + const result = applyCommandPlan(payload.project, plan); + if (!result.ok) { + print(result); + process.exitCode = 1; + return; + } + const outputPath = plan.output?.project ? resolve(plan.output.project) : ""; + if (!plan.dryRun) { + if (!outputPath) throw new Error("output.project is required unless dryRun is true"); + const nextPayload = { ...payload, exportedAt: new Date().toISOString(), project: result.project }; + files[PROJECT_FILE] = strToU8(JSON.stringify(nextPayload)); + await writeFile(outputPath, zipSync(files, { level: 6 })); + } + print({ + ok: true, + revision: result.revision, + appliedOperationIds: result.appliedOperationIds, + warnings: result.warnings, + diff: { before: result.before, after: result.after }, + artifacts: { ...(plan.dryRun ? {} : { project: outputPath }) }, + }); +} + +main().catch((error) => { + print({ ok: false, code: "COMMAND_FAILED", message: error instanceof Error ? error.message : String(error) }); + process.exitCode = error?.exitCode || 1; +}); diff --git a/skills/edit-timeline-studio/.claude-plugin/plugin.json b/skills/edit-timeline-studio/.claude-plugin/plugin.json index cff32d0..386e0bc 100644 --- a/skills/edit-timeline-studio/.claude-plugin/plugin.json +++ b/skills/edit-timeline-studio/.claude-plugin/plugin.json @@ -3,7 +3,7 @@ "name": "timeline-studio", "displayName": "Timeline Studio", "version": "0.1.0", - "description": "Operate, evaluate, and improve editable video workflows in Timeline Studio while preserving the editable timeline as the source of truth.", + "description": "Create, edit, caption, voice, assemble, validate, and export editable Timeline Studio video projects for automatic editing and local rendering.", "author": { "name": "MartinDelophy", "url": "https://github.com/MartinDelophy" @@ -13,6 +13,8 @@ "license": "MIT", "keywords": [ "video-editing", + "automatic-video-editing", + "ai-video", "timeline", "captions", "voiceover", diff --git a/skills/edit-timeline-studio/README.md b/skills/edit-timeline-studio/README.md new file mode 100644 index 0000000..7d37860 --- /dev/null +++ b/skills/edit-timeline-studio/README.md @@ -0,0 +1,48 @@ +# AI Video Editing Skill for Codex, Claude Code, Copilot and Gemini CLI + +Timeline Studio is a local-first browser video editor plus an Agent Skill for creating editable, multi-track `.timeline` projects. It combines visual assembly, timed captions, multilingual AI voiceover, overlays, audio tools, and deterministic browser rendering without turning the project into an opaque one-off script. + +Use it when a user asks an Agent to make a vertical short from images, synchronize captions with narration, prepare localized versions, modify an existing editable project, or verify a browser video-editing workflow. + +## What it can automate + +- Inspect, dry-run, and transactionally modify a portable `.timeline` archive through a versioned JSON command plan. +- Move voiceover clips; update caption text and timing; unlink or relink caption/audio pairs. +- Use the browser compatibility path for visual import and assembly, AI speech, automatic captions, overlays, effects, and export while more commands move into the shared registry. +- Preserve the editable project as the source of truth and verify the reopened result. + +The command runner currently edits existing projects; it does not yet perform headless media import, AI generation, or rendering. Those workflows remain available through the local or hosted browser editor. + +## Install + +```bash +npx skills add MartinDelophy/ai-video-editor --skill edit-timeline-studio +``` + +Claude Code and Codex can also install through GitHub CLI: + +```bash +gh skill install MartinDelophy/ai-video-editor edit-timeline-studio --agent claude-code --scope user +gh skill install MartinDelophy/ai-video-editor edit-timeline-studio --agent codex --scope user +``` + +For repository development: + +```bash +git clone https://github.com/MartinDelophy/ai-video-editor.git +cd ai-video-editor +npm install +npm run agent -- inspect /absolute/path/project.timeline +npm run dev +``` + +## Public guides + +- [What Timeline Studio is and what it automates](docs/agent-video-editing.md) +- [Use it from Codex](docs/codex-video-editing.md) +- [Use it from Claude Code](docs/claude-code-video-editing.md) +- [Five reproducible workflows](docs/examples.md) +- [Command reference](docs/command-reference.md) +- [Comparison with FFmpeg, CapCut, and Remotion](docs/comparison.md) + +The exact execution boundary is documented in [current capabilities](references/current-capabilities.md); the transport-neutral schema lives in the [command contract](references/command-contract.md). diff --git a/skills/edit-timeline-studio/SKILL.md b/skills/edit-timeline-studio/SKILL.md index 3d37093..57fb87e 100644 --- a/skills/edit-timeline-studio/SKILL.md +++ b/skills/edit-timeline-studio/SKILL.md @@ -1,9 +1,9 @@ --- name: edit-timeline-studio -description: Operate, evaluate, and improve editable video workflows in Timeline Studio at https://video-editor.ai-creator.top/, its local repository, or a .timeline archive. Use when Codex must import, assemble, trim, reorder, caption, voice, overlay, restyle, save, export, or repeatedly end-to-end test Timeline Studio; also use when real editing experience should be converted into updates to this skill. +description: Create, edit, caption, voice, assemble, validate, and export editable video timelines with Timeline Studio. Use for automatic video editing, AI voiceover videos, subtitle generation, image-to-video assembly, short-form video production, deterministic local video rendering, .timeline project automation, or end-to-end editor evaluation in Codex, Claude Code, Copilot, and Gemini CLI. --- -# Edit Timeline Studio +# AI Video Editing with Timeline Studio Turn the user's exact editorial request and media into reversible Timeline Studio edits. Keep the editable timeline as the source of truth; never replace it with an opaque one-shot render. @@ -63,4 +63,6 @@ For editor evaluation, regression work, or any run that exposes friction, read [ Read [references/current-capabilities.md](references/current-capabilities.md) when deciding whether a request can be executed now. Read [references/command-contract.md](references/command-contract.md) only when implementing or invoking the Agent command layer. Read [references/browser-workflow.md](references/browser-workflow.md) for UI execution and [references/e2e-evaluation.md](references/e2e-evaluation.md) for repeated experience-driven testing. +For public explanations, route one question to one page: use [docs/agent-video-editing.md](docs/agent-video-editing.md) for what Timeline Studio is, [docs/codex-video-editing.md](docs/codex-video-editing.md) or [docs/claude-code-video-editing.md](docs/claude-code-video-editing.md) for installation and invocation, [docs/examples.md](docs/examples.md) for reproducible cases, [docs/command-reference.md](docs/command-reference.md) for runner syntax, and [docs/comparison.md](docs/comparison.md) for FFmpeg, CapCut, and Remotion comparisons. Do not load all public pages unless the user asks for a broad overview. + If a requested operation is unsupported, keep the valid partial timeline unchanged and state the exact missing command or runtime capability. diff --git a/skills/edit-timeline-studio/agents/openai.yaml b/skills/edit-timeline-studio/agents/openai.yaml index 4cfe4c7..58217b8 100644 --- a/skills/edit-timeline-studio/agents/openai.yaml +++ b/skills/edit-timeline-studio/agents/openai.yaml @@ -1,4 +1,4 @@ interface: - display_name: "Timeline Studio Agent Editor" - short_description: "Edit and repeatedly test Timeline Studio workflows" + display_name: "AI Video Editing with Timeline Studio" + short_description: "Automate editable video timelines, captions, and voiceovers" default_prompt: "Use $edit-timeline-studio to edit these assets, verify the result end to end, and improve the workflow from observed friction." diff --git a/skills/edit-timeline-studio/docs/agent-video-editing.md b/skills/edit-timeline-studio/docs/agent-video-editing.md new file mode 100644 index 0000000..8242d4f --- /dev/null +++ b/skills/edit-timeline-studio/docs/agent-video-editing.md @@ -0,0 +1,19 @@ +# What is Timeline Studio, and what video editing can it automate? + +Timeline Studio is an installable, local-first browser editor for editable AI-assisted video projects. Its portable `.timeline` file is a ZIP archive containing `project.json` and project media, so a human can reopen and continue editing what an Agent produced. + +It can assemble a contiguous Visuals track, timed overlays, captions, stickers, voiceovers, separated source audio, and music. The editor includes multilingual browser TTS, Whisper captions, visual transforms, masks, effects, transitions, and offline WebCodecs export with a compatibility fallback. + +There are two automation paths: + +1. The versioned command runner directly inspects and modifies existing `.timeline` archives. It is transactional, revision-checked, idempotent by operation ID, and supports dry runs. Its first registry covers voiceover movement and caption update/link operations. +2. Browser execution covers the rest of the current editor, including imports, image assembly, AI generation, and final rendering. The Skill requires visible-state verification and a reopened editable project. + +An Agent should use the command runner whenever the requested operations are registered and use the browser only for the remaining steps. It must never describe browser automation as deterministic headless execution. + +```bash +npm run agent -- inspect /projects/product-demo.timeline +npm run agent -- run /projects/update-captions.json +``` + +See [command-reference.md](command-reference.md) for the exact JSON and [examples.md](examples.md) for complete workflows. diff --git a/skills/edit-timeline-studio/docs/claude-code-video-editing.md b/skills/edit-timeline-studio/docs/claude-code-video-editing.md new file mode 100644 index 0000000..bad2e60 --- /dev/null +++ b/skills/edit-timeline-studio/docs/claude-code-video-editing.md @@ -0,0 +1,24 @@ +# How does Claude Code edit video with Timeline Studio? + +Install the same Skill through GitHub CLI: + +```bash +gh skill install MartinDelophy/ai-video-editor edit-timeline-studio --agent claude-code --scope user +``` + +Then prompt Claude Code with explicit inputs and editable output requirements: + +```text +Use the Timeline Studio skill. Import ./assets/demo/*.png in filename order, +create a 9:16 product introduction with English voiceover and synchronized captions, +export ./out/demo.timeline and ./out/demo.mp4, then reopen the project and verify it. +``` + +Claude Code should inspect `package.json`, detect the `agent` script, and use it for registered operations: + +```bash +npm run agent -- inspect /absolute/path/demo.timeline +npm run agent -- run /absolute/path/edit-plan.json +``` + +It should use the browser workflow for unsupported commands and state that boundary in its result. The output contract is the same on both paths: return the editable project, the render when requested, a concise timeline summary, and verification evidence. diff --git a/skills/edit-timeline-studio/docs/codex-video-editing.md b/skills/edit-timeline-studio/docs/codex-video-editing.md new file mode 100644 index 0000000..543c4ae --- /dev/null +++ b/skills/edit-timeline-studio/docs/codex-video-editing.md @@ -0,0 +1,24 @@ +# How does Codex edit video with Timeline Studio? + +Install the Skill, then give Codex the media paths, target format, editorial intent, and desired outputs. Codex reads the Skill, chooses the command runner or browser path, verifies the result, and returns the editable `.timeline` path alongside any render. + +```bash +npx skills add MartinDelophy/ai-video-editor --skill edit-timeline-studio +``` + +Example Codex prompt: + +```text +Use $edit-timeline-studio. Open /projects/launch.timeline, move voice-e2e to 3s, +keep its linked caption synchronized, change the caption to “Available today”, +save /projects/launch-v2.timeline, reopen it, and report the revision and track summary. +``` + +For a supported headless edit, Codex creates a plan and executes: + +```bash +npm run agent -- run /projects/launch-v2-plan.json +npm run agent -- inspect /projects/launch-v2.timeline +``` + +For image import, TTS, automatic captions, effects, or rendering, Codex starts the local server, uses the editor in the in-app browser, exports a `.timeline`, reopens it, and validates visible clips and console errors. The browser remains a compatibility path until those operations enter the shared command registry. diff --git a/skills/edit-timeline-studio/docs/command-reference.md b/skills/edit-timeline-studio/docs/command-reference.md new file mode 100644 index 0000000..430dbda --- /dev/null +++ b/skills/edit-timeline-studio/docs/command-reference.md @@ -0,0 +1,43 @@ +# How does an Agent call the Timeline Studio command runner? + +## Inspect a project + +```bash +npm run agent -- inspect /absolute/path/project.timeline +``` + +The JSON result includes `revision`, duration, ratio, track counts, applied operation IDs, and warnings. + +## Apply a plan + +```bash +node skills/edit-timeline-studio/scripts/validate_edit_plan.mjs /absolute/path/plan.json +npm run agent -- run /absolute/path/plan.json +``` + +```json +{ + "schemaVersion": 1, + "project": "/projects/input.timeline", + "baseRevision": 0, + "dryRun": false, + "operations": [ + { "id": "move-voice-001", "type": "timed.move", "track": "audio", "clipId": "voice-1", "start": 3 }, + { "id": "caption-001", "type": "caption.update", "clipId": "caption-1", "text": "Available today" } + ], + "output": { "project": "/projects/output.timeline" } +} +``` + +Supported write operations: + +| Type | Required fields | Optional fields | Effect | +|---|---|---|---| +| `timed.move` | `track: "audio"`, `clipId`, `start` | — | Moves a voiceover and any still-linked captions by the same delta. | +| `caption.update` | `clipId` | `text`, `start`, `end` | Updates caption content or its finite, non-negative range. | +| `caption.unlink_audio` | `clipId` | — | Preserves the remembered audio ID but stops synchronization. | +| `caption.link_audio` | `clipId` | `audioClipId`, `align` | Relinks remembered or explicit audio; `align: true` copies its range. | + +Set `dryRun: true` to return the predicted before/after summary without writing output. A successful non-empty batch increments revision once. Reusing an applied operation ID is a no-op; a stale revision with new operations returns `REVISION_CONFLICT`. Failures return a stable code and operation ID and write no partial archive. + +Headless import, generation, render, and broader edit commands are not shipped yet. Use the browser workflow for those operations rather than inventing command types. diff --git a/skills/edit-timeline-studio/docs/comparison.md b/skills/edit-timeline-studio/docs/comparison.md new file mode 100644 index 0000000..3243bea --- /dev/null +++ b/skills/edit-timeline-studio/docs/comparison.md @@ -0,0 +1,12 @@ +# How is Timeline Studio different from FFmpeg, CapCut, and Remotion? + +| Tool | Best fit | Editable timeline | Agent interface | Rendering model | +|---|---|---:|---|---| +| Timeline Studio | Local-first AI-assisted editing that must remain human-editable | Yes, portable `.timeline` | Versioned JSON runner plus browser Skill | Browser WebCodecs/offline composition; compatibility fallback | +| FFmpeg | Deterministic media conversion, filtering, probing, and batch processing | No editor timeline by default | Excellent CLI/filter graph | Native command-line processing | +| CapCut | Polished manual short-form editing and a large template/effect ecosystem | Yes, proprietary editor project | Primarily human UI automation | Desktop/cloud application pipeline | +| Remotion | Code-defined React video systems and template-driven rendering | Source code is the project | Strong programmatic API | React frames rendered through Chromium/server tooling | + +Choose Timeline Studio when the Agent result must reopen as a normal visual timeline, use local browser AI tools, and remain adjustable by a non-programmer. Choose FFmpeg for low-level codecs, muxing, probing, or simple deterministic batch transforms. Choose CapCut when its manual UX, assets, and proprietary effects matter more than a stable Agent contract. Choose Remotion when video is fundamentally a software template maintained in React. + +They can complement each other. An Agent can probe or normalize media with FFmpeg, edit the portable timeline with Timeline Studio, or use Remotion for a code-owned motion-graphics segment. Timeline Studio does not claim to replace FFmpeg's codec breadth, CapCut's commercial ecosystem, or Remotion's programmable composition model. diff --git a/skills/edit-timeline-studio/docs/examples.md b/skills/edit-timeline-studio/docs/examples.md new file mode 100644 index 0000000..3a27599 --- /dev/null +++ b/skills/edit-timeline-studio/docs/examples.md @@ -0,0 +1,52 @@ +# What complete video-editing workflows can Agents reproduce? + +Each case preserves an editable `.timeline`. Paths are examples; replace them with absolute local paths. Browser steps use the installed Skill because headless import, generation, and render commands are not available yet. + +## 1. Codex turns an image folder into a vertical video + +- User prompt: `Use $edit-timeline-studio. Import the five named images in order, create a 9:16 15-second video, add simple captions, export and verify it.` +- Input files: `/demo/images/01-cover.png` through `/demo/images/05-cta.png`, `/demo/script.txt`. +- Execution: `npm run dev`; Codex imports the five explicit files in the browser, sets 9:16, adjusts clip durations, adds captions, then exports. +- Timeline summary: five contiguous Visuals clips, five timed captions, 15 seconds, 9:16. +- Final output: `/demo/out/image-story.mp4`. +- Editable project download: `/demo/out/image-story.timeline` (created by File → Export project package). + +## 2. Claude Code generates voiceover and synchronized captions + +- User prompt: `Use the Timeline Studio skill to generate an English voiceover from script.txt, keep every caption linked, and verify playback.` +- Input files: `/demo/voice/script.txt`, `/demo/voice/background.png`. +- Execution: `npm run dev`; Claude Code selects an English voice in the browser, generates audio, verifies caption links, and exports the project and render. +- Timeline summary: one Visuals clip, one or more voiceover clips, linked timed captions, 16:9. +- Final output: `/demo/out/voice-caption.mp4`. +- Editable project download: `/demo/out/voice-caption.timeline`. + +## 3. An Agent automatically revises a product introduction + +- User prompt: `Move voice-main to 3s, keep linked captions synchronized, replace caption-hero text, and save a new revision.` +- Input file: `/demo/product/product-intro.timeline`. +- Execution command: `npm run agent -- run /demo/product/revise-plan.json`, followed by `npm run agent -- inspect /demo/out/product-intro-v2.timeline`. +- Plan operations: `timed.move` for `voice-main`; `caption.update` for `caption-hero`. +- Timeline summary: revision 1, voiceover and linked caption begin at 3 seconds, original media entries unchanged. +- Final output: no opaque render is required for this metadata-only revision. +- Editable project download: `/demo/out/product-intro-v2.timeline`. + +## 4. Batch-produce localized versions + +- User prompt: `Create English, French, and German editable versions, preserving visuals and replacing narration and captions.` +- Input files: `/demo/localize/master.timeline`, `/demo/localize/{en,fr,de}.txt`. +- Execution: use the browser Skill once per language for voice generation; export `master-en.timeline`, `master-fr.timeline`, and `master-de.timeline`. Use `npm run agent -- inspect` on every archive and verify the expected caption/audio counts. +- Timeline summary: identical Visuals timing across three projects; localized linked caption and voiceover tracks. +- Final outputs: `/demo/out/master-{en,fr,de}.mp4`. +- Editable project downloads: `/demo/out/master-{en,fr,de}.timeline`. + +## 5. Open a `.timeline`, unlink a caption, retime it, and re-export + +- User prompt: `Unlink caption-7 from voice-2, set it to 8.2–10.0 seconds, change its text, and save without touching the source archive.` +- Input file: `/demo/revise/source.timeline`. +- Execution command: `npm run agent -- run /demo/revise/retime-plan.json`. +- Plan operations: `caption.unlink_audio`, then `caption.update` with `start`, `end`, and `text`; output points to a different archive. +- Timeline summary: one detached caption at 8.2–10.0 seconds; voiceover timing and archived media are unchanged; revision increments once. +- Final output: optionally reopen in the browser and export `/demo/out/revised.mp4`. +- Editable project download: `/demo/out/revised.timeline`. + +For exact plan syntax, see [command-reference.md](command-reference.md). “Download” here means the portable archive produced at the listed path; examples deliberately do not claim hosted sample binaries that the repository does not ship. diff --git a/skills/edit-timeline-studio/references/current-capabilities.md b/skills/edit-timeline-studio/references/current-capabilities.md index a8e6938..3030fca 100644 --- a/skills/edit-timeline-studio/references/current-capabilities.md +++ b/skills/edit-timeline-studio/references/current-capabilities.md @@ -16,6 +16,9 @@ - Browser-driven operation of the running editor - Import and export through visible file controls - Pure timeline helper functions in `src/lib/` +- A versioned JSON command plan runner through `npm run agent -- inspect ` and `npm run agent -- run ` +- Transactional, revision-checked, idempotent, dry-run-safe edits for moving voiceover clips, updating caption text/timing, and unlinking or relinking caption audio +- Portable `.timeline` output that preserves archived media entries while replacing only versioned project metadata Browser-driven editing is a compatibility mechanism, not a stable public API. UI labels, selection state, drag thresholds, and file pickers make it unsuitable for unattended or idempotent jobs. @@ -35,10 +38,10 @@ Observed browser-path constraints: ## Missing for reliable Agent editing -1. A headless command runner that owns project load, media probing, command application, save, and render. -2. A versioned command schema with stable asset/clip/track IDs and explicit time units. -3. A serializable editor core independent of React setters, DOM nodes, Blob URLs, and browser-only refs. -4. Transactional validation, revision preconditions, idempotency keys, structured errors, undo checkpoints, and dry-run diffs. +1. Media probing and render support in the headless command runner (load, inspect, edit, and save are now available). +2. Broader command coverage beyond the initial voiceover/caption operations. +3. A fully serializable editor core independent of React setters, DOM nodes, Blob URLs, and browser-only refs; the first shared reducers now live in `src/lib/projectCommandEngine.js`. +4. Persisted undo checkpoints and richer semantic diffs; transactions, revision preconditions, idempotency keys, structured errors, and summary dry-run diffs are available. 5. Read tools at three levels: project summary, track/clip detail, and transcript/analysis detail. 6. Progress events and cancellation for ASR, TTS, vision, avatar generation, and export. 7. Deterministic media ingestion with content hashes and portable asset references. @@ -46,10 +49,9 @@ Observed browser-path constraints: ## Recommended delivery order -1. Extract `EditorProjectState` and pure reducers from the existing timeline action modules. -2. Add read-only `project.inspect` and `project.diff` commands. -3. Add core edit commands: import, append, trim, split, move, delete, caption, overlay, property, and track mute/visibility. -4. Wrap command batches in history transactions and persist revision numbers. -5. Add `project.open/save/render` to a local Node/browser-worker runner. -6. Expose the same runner through CLI first; add MCP later as a thin transport adapter. -7. Replace the Skill's UI compatibility path with the CLI while keeping the command contract unchanged. +1. Extend the shared reducers with import, append, trim, split, delete, overlay, property, and track mute/visibility. +2. Add track/clip/transcript inspection and richer `project.diff` output. +3. Add persisted undo checkpoints around the existing command transaction. +4. Add media probing and `project.render` to the local Node/browser-worker runner. +5. Add MCP as a thin transport adapter over the same registry. +6. Prefer the CLI from this Skill when an operation is supported, retaining browser control as the compatibility path. diff --git a/src/App.jsx b/src/App.jsx index b3044ce..85e37da 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -722,22 +722,22 @@ export function App() { }; const { handleExportProject, handleImportProject, handleNewProject } = useProjectFiles({ - audioBlob, audioDuration, captionPlacement, captionPosition, captionSegments, captionSize, + audioBlob, audioDuration, audioSegments, captionPlacement, captionPosition, captionSegments, captionSize, captionStyle, captionsEnabled, captionStyleFallback: captionStyle, clearAllVisionState, clearAudioTrack, clearImageTrack, clearMusicTrack, clearSourceAudioTrack, fitMode, imageUrlRefs, musicBlob, musicDuration, musicName, musicStart, musicVolume, notify, projectFileInputRef, ratioId, replaceAudio, replaceMusic, replaceSourceAudio, script, selectedFilterId, selectedStickerId, selectedTransitionId, selectedVoiceId, setCaptionPlacement, setCaptionPosition, setCaptionSegments, setCaptionSize, setCaptionStyle, setCaptionsEnabled, - setCurrentTime, setFitMode, setImageClipCount, setImageDuration, setMusicStart, setMusicVolume, + setAudioSegments, setCurrentTime, setFitMode, setImageClipCount, setImageDuration, setMusicStart, setMusicVolume, setRatioId, setScript, setSelectedFilterId, setSelectedSegmentId, setSelectedStickerId, setSelectedStickerSegmentId, setSelectedTransitionId, setSelectedVoiceId, setShowFileMenu, - setSourceAudioAssetId, setSourceAudioLinked, setSourceAudioVolume, setSpeed, setStickerSegments, setTimelineZoom, setTrackVisibility, + setSourceAudioAssetId, setSourceAudioLinked, setSourceAudioVolume, setSpeed, setStickerSegments, setTimelineZoom, setTrackLocks, setTrackVisibility, setTimelineHorizon, setVisualSegments, setVisualOverlaySegments, setSelectedVisualOverlayId, setVolume, setCurrentVisualAsset, sourceAudioBlob, sourceAudioDuration, markTimelineViewRestored: (hasContent) => { timelineImportRestoreRef.current = hasContent; }, sourceAudioAssetId, sourceAudioLinked, sourceAudioName, sourceAudioStart, sourceAudioVolume, speed, stickerSegments, - timelineZoom, trackVisibility, visualSegments, visualOverlaySegments, volume, + timelineZoom, trackLocks, trackVisibility, visualSegments, visualOverlaySegments, volume, }); const { diff --git a/src/hooks/useProjectFiles.js b/src/hooks/useProjectFiles.js index 3ca7c68..be0f62e 100644 --- a/src/hooks/useProjectFiles.js +++ b/src/hooks/useProjectFiles.js @@ -1,21 +1,23 @@ -import { useCallback } from "react"; +import { useCallback, useRef } from "react"; import { DEFAULT_SCRIPT, DEFAULT_TIMELINE_DURATION_SECONDS, RATIO_OPTIONS, VOICES } from "../config/editor.js"; import { decodeWaveform, downloadBlob } from "../lib/media.js"; import { createProjectArchive, readProjectArchive, readProjectFileAsText } from "../lib/projectArchive.js"; import { createCaptionSegments, getImageThumbnailCount, getVisualSegmentsTotal } from "../lib/timeline.js"; export function useProjectFiles(deps) { + const commandStateRef = useRef({ schemaVersion: 1, revision: 0, appliedOperationIds: [] }); const getProjectSnapshot = useCallback(() => { const visualSegments = deps.visualSegments.map(({ blob, trackFrames, src, cutoutVisual, enhancement: _enhancement, ...segment }) => segment); const visualOverlaySegments = deps.visualOverlaySegments.map(({ blob, src, ...segment }) => segment); + const audioSegments = deps.audioSegments.map(({ blob, url, peaks, ...segment }) => segment); return { - script: deps.script, selectedVoiceId: deps.selectedVoiceId, speed: deps.speed, volume: deps.volume, + script: deps.script, commandState: commandStateRef.current, selectedVoiceId: deps.selectedVoiceId, speed: deps.speed, volume: deps.volume, ratioId: deps.ratioId, fitMode: deps.fitMode, captionPosition: deps.captionPosition, captionPlacement: deps.captionPlacement, captionSize: deps.captionSize, captionStyle: deps.captionStyle, - captionsEnabled: deps.captionsEnabled, captionSegments: deps.captionSegments, visualSegments, visualOverlaySegments, + captionsEnabled: deps.captionsEnabled, captionSegments: deps.captionSegments, audioSegments, visualSegments, visualOverlaySegments, stickerSegments: deps.stickerSegments, selectedFilterId: deps.selectedFilterId, selectedTransitionId: deps.selectedTransitionId, selectedStickerId: deps.selectedStickerId, - trackVisibility: deps.trackVisibility, timelineZoom: deps.timelineZoom, audioDuration: deps.audioDuration, + trackVisibility: deps.trackVisibility, trackLocks: deps.trackLocks, timelineZoom: deps.timelineZoom, audioDuration: deps.audioDuration, musicName: deps.musicName, musicDuration: deps.musicDuration, musicVolume: deps.musicVolume, sourceAudioName: deps.sourceAudioName, sourceAudioDuration: deps.sourceAudioDuration, sourceAudioStart: deps.sourceAudioStart, sourceAudioVolume: deps.sourceAudioVolume, @@ -41,6 +43,7 @@ export function useProjectFiles(deps) { const handleNewProject = useCallback(() => { if (!window.confirm("新建工程将清空当前时间线,是否继续?")) return; + commandStateRef.current = { schemaVersion: 1, revision: 0, appliedOperationIds: [] }; deps.setScript(DEFAULT_SCRIPT); deps.setCaptionSegments(createCaptionSegments(DEFAULT_SCRIPT)); deps.setSelectedSegmentId(""); deps.clearImageTrack(""); deps.clearAudioTrack(""); deps.setVisualOverlaySegments([]); deps.setSelectedVisualOverlayId(""); @@ -62,6 +65,7 @@ export function useProjectFiles(deps) { } const { payload, visualMedia, audio, sourceAudio, music } = archive; const data = payload.project; + commandStateRef.current = data.commandState || { schemaVersion: 1, revision: 0, appliedOperationIds: [] }; deps.setTimelineHorizon(DEFAULT_TIMELINE_DURATION_SECONDS); deps.setScript(typeof data.script === "string" ? data.script : DEFAULT_SCRIPT); const captions = Array.isArray(data.captionSegments) ? data.captionSegments : createCaptionSegments(data.script || DEFAULT_SCRIPT); @@ -72,7 +76,7 @@ export function useProjectFiles(deps) { deps.setFitMode(data.fitMode || "contain"); deps.setCaptionPosition(data.captionPosition || "bottom"); deps.setCaptionPlacement(data.captionPlacement || { x: 50, y: 78 }); deps.setCaptionSize(Number(data.captionSize) || 14); deps.setCaptionStyle(data.captionStyle || deps.captionStyle); deps.setCaptionsEnabled(data.captionsEnabled !== false); - deps.setTrackVisibility(data.trackVisibility || deps.trackVisibility); deps.setTimelineZoom(Number(data.timelineZoom) || 1); + deps.setTrackVisibility(data.trackVisibility || deps.trackVisibility); deps.setTrackLocks(data.trackLocks || deps.trackLocks); deps.setTimelineZoom(Number(data.timelineZoom) || 1); deps.setSelectedFilterId(data.selectedFilterId || "none"); deps.setSelectedTransitionId(data.selectedTransitionId || "none"); deps.setSelectedStickerId(data.selectedStickerId || "none"); deps.setStickerSegments(Array.isArray(data.stickerSegments) ? data.stickerSegments : []); const visuals = Array.isArray(data.visualSegments) ? data.visualSegments.map((segment) => { @@ -87,7 +91,13 @@ export function useProjectFiles(deps) { }).filter(Boolean) : []; deps.setVisualOverlaySegments(overlays); deps.setSelectedVisualOverlayId(""); deps.setImageClipCount(getImageThumbnailCount(getVisualSegmentsTotal(visuals))); deps.setCurrentVisualAsset(visuals[0] || null); - if (audio) { const decoded = await decodeWaveform(audio); deps.replaceAudio(audio, Number(data.audioDuration) || decoded.duration, decoded.peaks, "已恢复工程配音"); } else deps.clearAudioTrack(""); + if (audio) { + const decoded = await decodeWaveform(audio); + if (Array.isArray(data.audioSegments) && data.audioSegments.length) { + const url = URL.createObjectURL(audio); + deps.setAudioSegments(data.audioSegments.map((segment) => ({ ...segment, blob: audio, url, peaks: decoded.peaks }))); + } else deps.replaceAudio(audio, Number(data.audioDuration) || decoded.duration, decoded.peaks, "已恢复工程配音"); + } else deps.clearAudioTrack(""); if (sourceAudio) { const decoded = await decodeWaveform(sourceAudio); deps.replaceSourceAudio(sourceAudio, Number(data.sourceAudioDuration) || decoded.duration, decoded.peaks, data.sourceAudioName || "source-audio", "", Number(data.sourceAudioStart) || 0, data.sourceAudioAssetId || "", { focusAudio: false }); } else deps.clearSourceAudioTrack(""); if (music) { const decoded = await decodeWaveform(music); deps.replaceMusic(music, Number(data.musicDuration) || decoded.duration, decoded.peaks, data.musicName || "background-music", ""); deps.setMusicStart(Math.max(0, Number(data.musicStart) || 0)); } else deps.clearMusicTrack(""); deps.setMusicVolume(Number(data.musicVolume) || 0.35); deps.setSourceAudioVolume(Number(data.sourceAudioVolume) || 1); diff --git a/src/lib/projectCommandEngine.js b/src/lib/projectCommandEngine.js new file mode 100644 index 0000000..19daf98 --- /dev/null +++ b/src/lib/projectCommandEngine.js @@ -0,0 +1,164 @@ +export const PROJECT_COMMAND_SCHEMA_VERSION = 1; + +const COMMAND_STATE_KEY = "commandState"; + +function failure(code, message, operationId = "") { + return { ok: false, code, message, ...(operationId ? { operationId } : {}) }; +} + +function finiteNonNegative(value, name) { + if (typeof value !== "number" || !Number.isFinite(value) || value < 0) { + throw Object.assign(new Error(`${name} must be a finite non-negative number`), { code: "INVALID_ARGUMENT" }); + } + return value; +} + +function findById(items, id, kind) { + const item = (Array.isArray(items) ? items : []).find((entry) => entry.id === id); + if (!item) throw Object.assign(new Error(`${kind} not found: ${id}`), { code: "CLIP_NOT_FOUND" }); + return item; +} + +function commandState(project) { + const value = project?.[COMMAND_STATE_KEY]; + return { + schemaVersion: PROJECT_COMMAND_SCHEMA_VERSION, + revision: Number.isInteger(value?.revision) && value.revision >= 0 ? value.revision : 0, + appliedOperationIds: Array.isArray(value?.appliedOperationIds) ? [...new Set(value.appliedOperationIds)] : [], + }; +} + +function moveTimed(project, operation) { + if (operation.track !== "audio") { + throw Object.assign(new Error(`Unsupported timed track: ${operation.track}`), { code: "UNSUPPORTED_TRACK" }); + } + const segment = findById(project.audioSegments, operation.clipId, "Audio clip"); + const nextStart = finiteNonNegative(operation.start, "start"); + const previousStart = Number(segment.start) || 0; + segment.start = nextStart; + const delta = nextStart - previousStart; + project.captionSegments = (project.captionSegments || []).map((caption) => caption.audioSegmentId === segment.id + ? { ...caption, start: finiteNonNegative((Number(caption.start) || 0) + delta, "caption start"), end: finiteNonNegative((Number(caption.end) || 0) + delta, "caption end") } + : caption); +} + +function updateCaption(project, operation) { + const caption = findById(project.captionSegments, operation.clipId, "Caption clip"); + if (Object.hasOwn(operation, "text")) { + if (typeof operation.text !== "string") throw Object.assign(new Error("text must be a string"), { code: "INVALID_ARGUMENT" }); + caption.text = operation.text; + } + if (Object.hasOwn(operation, "start")) caption.start = finiteNonNegative(operation.start, "start"); + if (Object.hasOwn(operation, "end")) caption.end = finiteNonNegative(operation.end, "end"); + if (Number(caption.end) < Number(caption.start)) { + throw Object.assign(new Error("caption end must not be before start"), { code: "INVALID_RANGE" }); + } + project.script = (project.captionSegments || []).map((item) => item.text).join("\n"); +} + +function unlinkCaption(project, operation) { + const caption = findById(project.captionSegments, operation.clipId, "Caption clip"); + if (caption.audioSegmentId) caption.detachedAudioSegmentId = caption.audioSegmentId; + caption.audioSegmentId = ""; +} + +function linkCaption(project, operation) { + const caption = findById(project.captionSegments, operation.clipId, "Caption clip"); + const audioId = operation.audioClipId || caption.detachedAudioSegmentId; + if (!audioId) throw Object.assign(new Error("audioClipId is required"), { code: "INVALID_ARGUMENT" }); + const audio = findById(project.audioSegments, audioId, "Audio clip"); + caption.audioSegmentId = audio.id; + caption.detachedAudioSegmentId = ""; + if (operation.align === true) { + caption.start = Number(audio.start) || 0; + caption.end = caption.start + finiteNonNegative(audio.duration, "audio duration"); + } +} + +const reducers = { + "timed.move": moveTimed, + "caption.update": updateCaption, + "caption.unlink_audio": unlinkCaption, + "caption.link_audio": linkCaption, +}; + +export function validateCommandPlan(plan) { + if (!plan || typeof plan !== "object" || Array.isArray(plan)) return failure("INVALID_PLAN", "Plan must be an object"); + if (plan.schemaVersion !== PROJECT_COMMAND_SCHEMA_VERSION) return failure("UNSUPPORTED_SCHEMA", "schemaVersion must be 1"); + if (!Number.isInteger(plan.baseRevision) || plan.baseRevision < 0) return failure("INVALID_PLAN", "baseRevision must be a non-negative integer"); + if (!Array.isArray(plan.operations) || plan.operations.length === 0) return failure("INVALID_PLAN", "operations must be a non-empty array"); + const ids = new Set(); + for (const operation of plan.operations) { + if (!operation || typeof operation.id !== "string" || !operation.id.trim()) return failure("INVALID_PLAN", "Every operation requires an id"); + if (ids.has(operation.id)) return failure("DUPLICATE_OPERATION_ID", `Duplicate operation id: ${operation.id}`, operation.id); + ids.add(operation.id); + if (!reducers[operation.type]) return failure("UNKNOWN_OPERATION", `Unknown operation type: ${operation.type}`, operation.id); + } + return { ok: true }; +} + +export function inspectProject(project) { + const state = commandState(project); + const captions = Array.isArray(project?.captionSegments) ? project.captionSegments : []; + const audio = Array.isArray(project?.audioSegments) ? project.audioSegments : []; + const duration = [...captions.map((item) => Number(item.end) || 0), ...audio.map((item) => (Number(item.start) || 0) + (Number(item.duration) || 0))] + .reduce((maximum, value) => Math.max(maximum, value), 0); + return { + schemaVersion: PROJECT_COMMAND_SCHEMA_VERSION, + revision: state.revision, + duration, + ratio: project?.ratioId || "16:9", + tracks: { captions: captions.length, audio: audio.length, visuals: project?.visualSegments?.length || 0 }, + appliedOperationIds: state.appliedOperationIds, + warnings: audio.length ? [] : ["Project has no serialized voiceover clips"], + }; +} + +export function applyCommandPlan(project, plan) { + const validity = validateCommandPlan(plan); + if (!validity.ok) return validity; + const current = commandState(project); + const alreadyApplied = new Set(current.appliedOperationIds); + if (plan.operations.every((operation) => alreadyApplied.has(operation.id))) { + return { + ok: true, + revision: current.revision, + appliedOperationIds: [], + warnings: [], + project: structuredClone(project), + before: inspectProject(project), + after: inspectProject(project), + }; + } + if (plan.baseRevision !== current.revision) { + return failure("REVISION_CONFLICT", `Expected revision ${plan.baseRevision}, found ${current.revision}`); + } + const next = structuredClone(project); + const appliedOperationIds = []; + let operationId = ""; + try { + for (const operation of plan.operations) { + if (alreadyApplied.has(operation.id)) continue; + operationId = operation.id; + reducers[operation.type](next, operation); + appliedOperationIds.push(operation.id); + } + } catch (error) { + return failure(error?.code || "OPERATION_FAILED", error instanceof Error ? error.message : "Operation failed", operationId); + } + const revision = appliedOperationIds.length ? current.revision + 1 : current.revision; + next[COMMAND_STATE_KEY] = { + schemaVersion: PROJECT_COMMAND_SCHEMA_VERSION, + revision, + appliedOperationIds: [...current.appliedOperationIds, ...appliedOperationIds], + }; + return { + ok: true, + revision, + appliedOperationIds, + warnings: [], + project: next, + before: inspectProject(project), + after: inspectProject(next), + }; +} diff --git a/src/lib/projectCommandEngine.test.js b/src/lib/projectCommandEngine.test.js new file mode 100644 index 0000000..c14f56f --- /dev/null +++ b/src/lib/projectCommandEngine.test.js @@ -0,0 +1,62 @@ +import { describe, expect, it } from "vitest"; +import { applyCommandPlan, inspectProject } from "./projectCommandEngine.js"; + +function project() { + return { + ratioId: "16:9", + script: "Hello", + audioSegments: [{ id: "voice-1", start: 2, duration: 3 }], + captionSegments: [{ id: "caption-1", text: "Hello", start: 2, end: 5, audioSegmentId: "voice-1" }], + visualSegments: [{ id: "visual-1", duration: 8 }], + }; +} + +function plan(operations, overrides = {}) { + return { schemaVersion: 1, baseRevision: 0, operations, ...overrides }; +} + +describe("project command engine", () => { + it("moves linked captions with voiceover clips transactionally", () => { + const original = project(); + const result = applyCommandPlan(original, plan([{ id: "move-1", type: "timed.move", track: "audio", clipId: "voice-1", start: 7 }])); + expect(result.ok).toBe(true); + expect(result.project.audioSegments[0].start).toBe(7); + expect(result.project.captionSegments[0]).toMatchObject({ start: 7, end: 10 }); + expect(original.audioSegments[0].start).toBe(2); + expect(result.revision).toBe(1); + }); + + it("unlinks, edits, and relinks a caption with optional alignment", () => { + const result = applyCommandPlan(project(), plan([ + { id: "unlink-1", type: "caption.unlink_audio", clipId: "caption-1" }, + { id: "caption-1", type: "caption.update", clipId: "caption-1", text: "Updated", start: 8, end: 9 }, + { id: "link-1", type: "caption.link_audio", clipId: "caption-1", audioClipId: "voice-1", align: true }, + ])); + expect(result.project.captionSegments[0]).toMatchObject({ text: "Updated", start: 2, end: 5, audioSegmentId: "voice-1" }); + expect(result.project.script).toBe("Updated"); + }); + + it("rejects a failing batch without changing the input", () => { + const original = project(); + const result = applyCommandPlan(original, plan([ + { id: "move-1", type: "timed.move", track: "audio", clipId: "voice-1", start: 7 }, + { id: "bad-1", type: "caption.update", clipId: "missing", text: "No" }, + ])); + expect(result).toMatchObject({ ok: false, code: "CLIP_NOT_FOUND", operationId: "bad-1" }); + expect(original.audioSegments[0].start).toBe(2); + }); + + it("does not apply a previously recorded operation twice", () => { + const first = applyCommandPlan(project(), plan([{ id: "move-1", type: "timed.move", track: "audio", clipId: "voice-1", start: 7 }])); + const replay = applyCommandPlan(first.project, plan( + [{ id: "move-1", type: "timed.move", track: "audio", clipId: "voice-1", start: 12 }], + { baseRevision: 0 }, + )); + expect(replay).toMatchObject({ ok: true, revision: 1, appliedOperationIds: [] }); + expect(replay.project.audioSegments[0].start).toBe(7); + }); + + it("inspects stable project facts", () => { + expect(inspectProject(project())).toMatchObject({ revision: 0, duration: 5, ratio: "16:9", tracks: { captions: 1, audio: 1, visuals: 1 } }); + }); +}); diff --git a/src/lib/timelineCommandCli.test.js b/src/lib/timelineCommandCli.test.js new file mode 100644 index 0000000..0f7a19d --- /dev/null +++ b/src/lib/timelineCommandCli.test.js @@ -0,0 +1,49 @@ +import { execFile } from "node:child_process"; +import { mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import { strFromU8, strToU8, unzipSync, zipSync } from "fflate"; +import { describe, expect, it } from "vitest"; + +const execute = promisify(execFile); + +describe("timeline command CLI", () => { + it("dry-runs and writes a new archive while preserving media entries", async () => { + const directory = await mkdtemp(join(tmpdir(), "timeline-command-")); + const input = join(directory, "input.timeline"); + const output = join(directory, "output.timeline"); + const planPath = join(directory, "plan.json"); + const payload = { + format: "timeline-studio-archive", + version: 2, + project: { + audioSegments: [{ id: "voice", start: 0, duration: 2 }], + captionSegments: [{ id: "caption", text: "Old", start: 0, end: 2, audioSegmentId: "voice" }], + }, + media: {}, + }; + await writeFile(input, zipSync({ "project.json": strToU8(JSON.stringify(payload)), "media/audio/voice.wav": new Uint8Array([1, 2, 3]) })); + const basePlan = { + schemaVersion: 1, + project: input, + baseRevision: 0, + operations: [{ id: "edit-caption", type: "caption.update", clipId: "caption", text: "New" }], + output: { project: output }, + }; + await writeFile(planPath, JSON.stringify({ ...basePlan, dryRun: true })); + const dryRun = JSON.parse((await execute(process.execPath, ["scripts/timeline-command.mjs", "run", planPath], { cwd: process.cwd() })).stdout); + expect(dryRun).toMatchObject({ ok: true, revision: 1, artifacts: {} }); + await expect(readFile(output)).rejects.toThrow(); + + await writeFile(planPath, JSON.stringify({ ...basePlan, dryRun: false })); + const run = JSON.parse((await execute(process.execPath, ["scripts/timeline-command.mjs", "run", planPath], { cwd: process.cwd() })).stdout); + expect(run.artifacts.project).toBe(output); + const files = unzipSync(new Uint8Array(await readFile(output))); + expect([...files["media/audio/voice.wav"]]).toEqual([1, 2, 3]); + expect(JSON.parse(strFromU8(files["project.json"])).project).toMatchObject({ + captionSegments: [{ id: "caption", text: "New" }], + commandState: { revision: 1, appliedOperationIds: ["edit-caption"] }, + }); + }); +});