commit d8aaeb65719332ff5e25328e51ce006086de66fd
parent 41b949da44a4f35001bed5fcca50f86940626ee3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 23 Oct 2026 20:46:30 -0400
umtool: Play the cut -- the whole cut or a take played in the browser, no render, with notes at the playhead
/projects/<p>/play (?take=<id>): every entry in timeline order on one cut
clock (lib/report/playCut.mjs), each clip from its cached window through the
bench's raw route (take-aware), the live preview's chrome composed from the
estimate (a take's under takes/<id>/out/, served under @take/<id>), the next
clip preloaded in a second <video>. A take's manifest is the project's now +
its style and own patches (lib/report/takeManifest.mjs), from take.json or a
recipe. Notes at the playhead: a new `cut` anchor (cut second, clip, source
second, take), printed by `umtool notes`; Send to the assistant reuses the
video-assist note path (noteRequestOf takes a cut note with where it was
taken). Linked from the Cut tab and the takes page.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
35 files changed, 2202 insertions(+), 123 deletions(-)
diff --git a/common/lib/report/draft/tasks/videoAssist.test.ts b/common/lib/report/draft/tasks/videoAssist.test.ts
@@ -10,7 +10,7 @@ import { startFakeAnthropic, toolTurn, type FakeAnthropic } from "../../../../te
import { jsonReply, startFakeOllama, PROMPT_CAP_TOKENS, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs";
import { ASSIST_NOTE, ASSIST_REQUESTS, answerOf, writeAssistProject } from "../../../../testing/clips/assistProject.mjs";
import { readAssistProposals } from "../../videoAssistProposals.mjs";
-import { ASSIST_CODE_MODEL, VideoAssistRefusal, noteReplyOf, noteRequestOf, planVideoAssist, runVideoAssist } from "./videoAssist";
+import { ASSIST_CODE_MODEL, VideoAssistRefusal, cutContextOf, noteReplyOf, noteRequestOf, planVideoAssist, runVideoAssist } from "./videoAssist";
import type { LlmConfig } from "../../../llm";
let tmp: string;
@@ -113,6 +113,25 @@ test("refusals at the ask: no manifest, no request, an API ask over its cap; a n
await assert.rejects(noteRequestOf(dir, "n_absent00"), /no note n_absent00/);
});
+test("a note taken in the Play view: its text with where it was taken is the request, in the prompt the model reads", async () => {
+ const dir = path.join(tmp, "cut-note");
+ writeAssistProject(dir, { note: "this drags — start later", anchor: { kind: "cut", t: 72.44, entry: "r002", sourceT: 94.8, take: "short-19" } });
+ const request = await noteRequestOf(dir, ASSIST_NOTE);
+ assert.equal(request, "this drags — start later (noted while playing take short-19 at 1:12.4, in clip r002 at source 94.8 s)");
+ assert.equal(cutContextOf({ t: 3 }), "(noted while playing the cut at 0:03.0)");
+ let prompt = "";
+ ol.push((body: { messages: { role: string; content: string }[] }) => {
+ prompt = userOfOllama(body);
+ return jsonReply({ ops: [], reply: "Nothing to change." });
+ });
+ const out = await runVideoAssist({ project: dir, model: "qwen3:8b", request, note: ASSIST_NOTE }, { llm });
+ assert.equal(out.status, "done");
+ assert.ok(prompt.includes(`THE REQUEST:\n${request}`), prompt.slice(0, 400));
+ // A part of the project other than the cut is still the clip editor's.
+ writeAssistProject(path.join(tmp, "entry-note"), { note: "x", anchor: { kind: "entry", entry: "r002" } });
+ await assert.rejects(noteRequestOf(path.join(tmp, "entry-note"), ASSIST_NOTE), /on a part of the project/);
+});
+
test("a note's reply: the proposals in words, the refusals, where to apply", () => {
const text = noteReplyOf({
version: 1, promptVersion: "video-assist-1", at: "t", model: "m", request: "r", scope: "all", reply: "Quicker joins.",
diff --git a/common/lib/report/draft/tasks/videoAssist.ts b/common/lib/report/draft/tasks/videoAssist.ts
@@ -77,7 +77,33 @@ export async function loadAssistProject(dir: string): Promise<{ dir: string; man
}
}
-/** A project-level note's text, as the request (an Ask on a note). */
+/** `m:ss.s`, a cut second as the Play view shows it. */
+const cutClock = (t: number) => {
+ const s = Math.max(0, Number.isFinite(t) ? t : 0);
+ const m = Math.floor(s / 60);
+ return `${m}:${(s - m * 60).toFixed(1).padStart(4, "0")}`;
+};
+
+/**
+ * Where a note taken in umtool's Play view was taken (a `cut` anchor), as the
+ * words appended to its request: "(noted while playing take short-19 at
+ * 1:12.4, in clip c04 at source 194.2 s)". The clip names what "this" is; a
+ * take's patch is not what the ops edit (they edit the project's cut).
+ */
+export function cutContextOf(a: { t?: unknown; entry?: unknown; sourceT?: unknown; take?: unknown }): string {
+ const where = [`at ${cutClock(Number(a.t))}`];
+ if (typeof a.entry === "string" && a.entry) {
+ where.push(`in clip ${a.entry}${typeof a.sourceT === "number" && Number.isFinite(a.sourceT) ? ` at source ${a.sourceT.toFixed(1)} s` : ""}`);
+ }
+ const take = typeof a.take === "string" && a.take ? `take ${a.take}` : "the cut";
+ return `(noted while playing ${take} ${where.join(", ")})`;
+}
+
+/**
+ * A note's text, as the request (an Ask on a note): a note on the whole
+ * project, or one taken in the Play view (`cut`: its text with where it was
+ * taken -- the cut second, the clip, the take).
+ */
export async function noteRequestOf(dir: string, noteId: string): Promise<string> {
let doc: unknown = null;
try {
@@ -86,12 +112,21 @@ export async function noteRequestOf(dir: string, noteId: string): Promise<string
throw new VideoAssistRefusal(`${dir} has no notes.json: no note ${noteId}`);
}
const notes = (doc as { notes?: unknown[] })?.notes;
- const n = Array.isArray(notes) ? (notes.find((x) => (x as { id?: unknown })?.id === noteId) as { text?: unknown; status?: unknown; anchor?: { kind?: unknown } } | undefined) : undefined;
+ const n = Array.isArray(notes)
+ ? (notes.find((x) => (x as { id?: unknown })?.id === noteId) as { text?: unknown; status?: unknown; anchor?: { kind?: unknown; t?: unknown; entry?: unknown; sourceT?: unknown; take?: unknown } } | undefined)
+ : undefined;
if (!n) throw new VideoAssistRefusal(`no note ${noteId} in ${dir}/notes.json`);
- if (n.anchor?.kind !== "whole") throw new VideoAssistRefusal(`${noteId} is on a part of the project: the assistant answers a note on the whole project (a clip's note is the clip editor's Ask)`);
+ const kind = n.anchor?.kind;
+ if (kind !== "whole" && kind !== "cut") {
+ throw new VideoAssistRefusal(`${noteId} is on a part of the project: the assistant answers a note on the whole project or one taken in the Play view (a clip's note is the clip editor's Ask)`);
+ }
if (n.status !== "open") throw new VideoAssistRefusal(`${noteId} is resolved`);
const text = typeof n.text === "string" ? n.text.trim() : "";
if (!text) throw new VideoAssistRefusal(`${noteId} has no text`);
+ if (kind === "cut") {
+ const where = ` ${cutContextOf(n.anchor ?? {})}`;
+ return `${text.slice(0, ASSIST_REQUEST_MAX - where.length)}${where}`;
+ }
return text.slice(0, ASSIST_REQUEST_MAX);
}
diff --git a/common/testing/clips/assistProject.mjs b/common/testing/clips/assistProject.mjs
@@ -89,14 +89,14 @@ export const answerOf = (row) => ({ ops: row.answer, reply: "" });
* @param {string} dir
* @param {{ deck?: boolean, note?: string | null }} [o]
*/
-export function writeAssistProject(dir, { deck = false, note = null } = {}) {
+export function writeAssistProject(dir, { deck = false, note = null, anchor = { kind: "whole" } } = {}) {
const manifest = deck ? assistDeckManifest() : assistManifest();
mkdirSync(dir, { recursive: true });
writeFileSync(path.join(dir, "video.manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
if (note) {
writeFileSync(
path.join(dir, "notes.json"),
- `${JSON.stringify({ version: 1, subject: { kind: "video-project", project: path.basename(dir) }, notes: [{ id: ASSIST_NOTE, status: "open", author: "operator", text: note, at: ASSIST_AT, updatedAt: ASSIST_AT, anchor: { kind: "whole" }, replies: [] }] }, null, 1)}\n`,
+ `${JSON.stringify({ version: 1, subject: { kind: "video-project", project: path.basename(dir) }, notes: [{ id: ASSIST_NOTE, status: "open", author: "operator", text: note, at: ASSIST_AT, updatedAt: ASSIST_AT, anchor, replies: [] }] }, null, 1)}\n`,
);
}
return { dir, manifest };
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **umtool plays a whole report video, or one take of it, in the browser without rendering it, and takes notes as it plays.** The Cut tab's **Play the cut** (and **Play** beside each take on the takes page) opens `/projects/<project>/play`: every clip plays in order from its fetched window, with the on-screen panel, the tally, the stamps, the markers and the finale drawn over it as the live preview draws them, on one clock across the whole cut, the next clip loaded behind the one playing. A take plays the project's video as it is now with the take's changes, including a take with its own clip list and one a recipe names that was never rendered; **Blurred clips: uncensored** on a take plays its clips as recorded. Space plays and pauses, N and P move between clips, ← and → move 5 seconds, a clip list jumps, and the speed keeps the voice's pitch. A line under the picture lists what it does not do: each crossfade is a hard cut at its middle, cards and teasers are placeholders with their heading, edges are not snapped to silence, and the sound is the recording's. A clip with nothing fetched is a named placeholder and the video plays on. M (or **Note at playhead**) pauses and saves a note at that second of the cut, naming the clip on screen, its second in the recording and the take; the notes list in order, a click plays from there, `umtool notes <project>` prints each with where it was taken, and **Send to the assistant** on a note (or **Send all open notes**) asks the video assistant, whose reply lands on the note and whose edits wait for **Apply all**. With no assistant configured the button says why. Needs a restart of umtool.
- **umtool's clip walk goes through the recordings in date order.** `p`/`n` and the Cut tab's walk used to follow the cut, which can open on a finale and end years earlier. The walk now goes by each clip's date (its on-screen date, else the recording's upload date), with a recording's clips together in the order they come in it, so what is left out between two clips, or split off into a clip of its own, comes up next. The cut's own order is unchanged.
- **A clip from a stream captured live can be trimmed again in umtool's clip editor.** Such a stream's record has no length, which umtool passed on as zero, so every drag of a clip's edge snapped back to the left with "that is the edge of what is cached". An unknown length is now treated as unknown.
- **umtool's clip editor opens a clip from a whole saved recording as a short excerpt.** When the only file holding a clip was the whole recording (hours long), the editor used all of it as its view: a waveform of the whole stream with the clip a sliver in it, and a video seeking hours into a large file. It now cuts the clip and 45 seconds either side from the recording once, on the umtool machine, and works on that; the cut starts when the clip is opened and is kept for the next time. The rendered video still cuts from the whole recording.
diff --git a/umtool/app/api/report/chrome/files/[...path]/route.ts b/umtool/app/api/report/chrome/files/[...path]/route.ts
@@ -6,7 +6,11 @@ import {
previewDirFor,
rangeResponse,
resolveReport,
+ TAKE_SEGMENT,
} from "@/lib/report/serve.mjs";
+import { readFile } from "node:fs/promises";
+import { isTakeId } from "@/lib/report/takes.mjs";
+import { playManifestPath, takePlayDir } from "@/lib/report/takeManifest.mjs";
export const dynamic = "force-dynamic";
@@ -28,6 +32,10 @@ export const dynamic = "force-dynamic";
// deeper: <project>/<variant>/posts-preview-<segment>/<file…>, where <segment>
// must be an entry of this cut (previewDirFor), and the file is then confined
// to THAT window's directory by the same deckPreviewFile.
+//
+// A TAKE's pages (the Play view) are served under `<project>/<variant>/@take/<id>/…`:
+// the take id checked, the cut's entry ids its play manifest's, and the file
+// confined to takes/<id>/out/<variant>/chrome/<the preview>/ the same way.
const TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
@@ -56,8 +64,20 @@ export async function GET(request: Request, ctx: { params: Promise<{ path: strin
const r = await resolveReport(projectId, variant);
if ("error" in r) return new Response(r.error, { status: r.status });
- const ids = (selectVariant(r.manifest, r.variant).timeline ?? []).map((e: { id: string }) => e.id);
- const where = previewDirFor(r.project.dir, r.variant, rest, ids);
+ let dir = r.project.dir;
+ let manifest = r.manifest;
+ let tail = rest;
+ if (rest[0] === TAKE_SEGMENT) {
+ const take = rest[1];
+ if (!isTakeId(take)) return new Response("not found", { status: 404 });
+ const played = await readFile(playManifestPath(r.project.dir, take), "utf8").then(JSON.parse, () => null);
+ if (!played) return new Response("not found", { status: 404 });
+ dir = takePlayDir(r.project.dir, take);
+ manifest = played;
+ tail = rest.slice(2);
+ }
+ const ids = (selectVariant(manifest, r.variant).timeline ?? []).map((e: { id: string }) => e.id);
+ const where = previewDirFor(dir, r.variant, tail, ids);
if (!where) return new Response("not found", { status: 404 });
const file = await deckPreviewFile(where.dir, where.rest);
if (!file) return new Response("not found", { status: 404 });
diff --git a/umtool/app/api/report/chrome/preview/route.ts b/umtool/app/api/report/chrome/preview/route.ts
@@ -17,6 +17,8 @@ import {
deckGeometry, deckLayout, deckOn, feedGeometry, postsGeometry, stampGeometry, validateChrome,
} from "umtool-report-to-video/deck";
import { resolveFactcheck, stampsDrawn, tallyOf } from "umtool-report-to-video/factcheck";
+import { cachedTakeManifest, takePlayDir, writePlayManifest } from "@/lib/report/takeManifest.mjs";
+import { isTakeId } from "@/lib/report/takes.mjs";
export const dynamic = "force-dynamic";
@@ -65,7 +67,13 @@ export const dynamic = "force-dynamic";
// `estimate: true` -- the clip editor's live preview -- draws the manifest's
// estimate even when a build's schedule exists (scheduleForPreview).
//
-// The client sends a project id, a variant and the drafts. Never a path.
+// `take: <id>` -- the Play view playing a take: the take's manifest (the
+// project's now + its style's and its own patches, takeManifest.mjs) is
+// written beside the project's as `.take-<id>.play.json` and its pages are
+// composed under takes/<id>/out/<variant>/chrome/, served under
+// `<project>/<variant>/@take/<id>/` -- never over the project's own preview.
+//
+// The client sends a project id, a variant, a take id and the drafts. Never a path.
export async function POST(request: Request) {
let body: Record<string, unknown>;
try {
@@ -97,7 +105,20 @@ export async function POST(request: Request) {
// estimate even when a build's schedule exists, so a moved window is
// placed where it is now.
const estimate = body.estimate === true;
- const { variantManifest, schedule } = await scheduleForPreview(r.project, r.manifest, r.variant, draft, postsDraft, { claimsDraft, estimate });
+ // A take: its manifest, and its own place to compose into.
+ const take = body.take === undefined || body.take === null || body.take === "" ? null : String(body.take);
+ if (take !== null && !isTakeId(take)) return Response.json({ error: "take is a take id" }, { status: 400 });
+ let manifest = r.manifest;
+ let target: { dir: string; manifestFile?: string } = r.project;
+ if (take) {
+ try {
+ manifest = (await cachedTakeManifest(r.project.dir, take)).manifest;
+ target = { dir: takePlayDir(r.project.dir, take), manifestFile: await writePlayManifest(r.project.dir, take, manifest) };
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 404 });
+ }
+ }
+ const { variantManifest, schedule } = await scheduleForPreview(r.project, manifest, r.variant, draft, postsDraft, { claimsDraft, estimate });
const render = (variantManifest.render ?? {}) as Record<string, unknown>;
if (!deckOn(render)) {
return Response.json(
@@ -112,12 +133,12 @@ export async function POST(request: Request) {
}
try {
- await composeDeckPreview(r.project, r.variant, schedule);
+ await composeDeckPreview(target, r.variant, schedule);
} catch (e) {
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500 });
}
// `posts: false` -- the clip bench's strip, which has no footage to lay them on.
- const windows = body.posts === false ? [] : await composePostsPreviews(r.project, r.variant, schedule);
+ const windows = body.posts === false ? [] : await composePostsPreviews(target, r.variant, schedule);
const stamp = Date.now();
const isFeed = body.posts !== false && (schedule as { layout?: string }).layout === "feed";
let feed: Record<string, unknown> | null = null;
@@ -125,7 +146,7 @@ export async function POST(request: Request) {
const g = feedGeometry(render);
let error: string | null = null;
try {
- await composeFeedPreview(r.project, r.variant, schedule);
+ await composeFeedPreview(target, r.variant, schedule);
} catch (e) {
error = e instanceof Error ? e.message : String(e);
}
@@ -133,7 +154,7 @@ export async function POST(request: Request) {
geometry: g.column,
footage: g.footage,
boxes: await segmentBoxes(r.project, r.variant, (variantManifest.timeline ?? []) as { id: string }[], render),
- ...(error ? { error } : { src: `${feedPreviewSrc(r.project.id, r.variant)}?v=${stamp}` }),
+ ...(error ? { error } : { src: `${feedPreviewSrc(r.project.id, r.variant, take)}?v=${stamp}` }),
};
}
@@ -144,13 +165,13 @@ export async function POST(request: Request) {
if (body.posts !== false && stampsDrawn(schedule, render)) {
let error: string | null = null;
try {
- await composeStampPreview(r.project, r.variant, schedule);
+ await composeStampPreview(target, r.variant, schedule);
} catch (e) {
error = e instanceof Error ? e.message : String(e);
}
stampDoc = {
geometry: stampGeometry(render, { feed: (schedule as { layout?: string }).layout === "feed" }),
- ...(error ? { error } : { src: `${stampPreviewSrc(r.project.id, r.variant)}?v=${stamp}` }),
+ ...(error ? { error } : { src: `${stampPreviewSrc(r.project.id, r.variant, take)}?v=${stamp}` }),
};
}
@@ -162,7 +183,7 @@ export async function POST(request: Request) {
if (body.posts !== false && fin) {
let error: string | null = null;
try {
- await composeFinalePreview(r.project, r.variant, schedule);
+ await composeFinalePreview(target, r.variant, schedule);
} catch (e) {
error = e instanceof Error ? e.message : String(e);
}
@@ -171,7 +192,7 @@ export async function POST(request: Request) {
geometry: { x: 0, y: 0, width: g.W, height: g.H },
from: fin.from,
to: fin.to,
- ...(error ? { error } : { src: `${finalePreviewSrc(r.project.id, r.variant)}?v=${stamp}` }),
+ ...(error ? { error } : { src: `${finalePreviewSrc(r.project.id, r.variant, take)}?v=${stamp}` }),
};
}
@@ -179,7 +200,7 @@ export async function POST(request: Request) {
{
// `v` so the iframe reloads a recomposed preview; the files themselves
// are served no-store, so its relative asset urls need none.
- src: `${deckPreviewSrc(r.project.id, r.variant)}?v=${stamp}`,
+ src: `${deckPreviewSrc(r.project.id, r.variant, take)}?v=${stamp}`,
variant: r.variant,
geometry: deckGeometry(render),
// The ground a footage moved aside for the posts (schedule.moves) leaves showing.
@@ -193,7 +214,7 @@ export async function POST(request: Request) {
segment: w.segment,
from: w.from,
to: w.to,
- ...(w.ok ? { src: `${postsPreviewSrc(r.project.id, r.variant, w.segment)}?v=${stamp}` } : { error: w.error }),
+ ...(w.ok ? { src: `${postsPreviewSrc(r.project.id, r.variant, w.segment, take)}?v=${stamp}` } : { error: w.error }),
})),
},
...(feed ? { feed } : {}),
diff --git a/umtool/app/api/report/raw/route.ts b/umtool/app/api/report/raw/route.ts
@@ -36,7 +36,8 @@ export async function GET(request: Request) {
const all = await windowsFor(c.project, { video: c.claim.video });
windows = all.filter((w: { name: string }) => windows.some((x) => x.name === w.name));
} else {
- const r = await resolveClip(projectId, url.searchParams.get("clip") ?? "");
+ // `take` (the Play view playing a take): the take's clip, its window as the take has it.
+ const r = await resolveClip(projectId, url.searchParams.get("clip") ?? "", { take: url.searchParams.get("take") || null });
if ("error" in r) return new Response(r.error, { status: r.status });
windows = await windowsFor(r.project, r.clip);
}
diff --git a/umtool/components/projects/PlayCutPage.tsx b/umtool/components/projects/PlayCutPage.tsx
@@ -0,0 +1,60 @@
+import Link from "next/link";
+import { playHref, projectsHref } from "@/lib/hrefs";
+import { pieceHrefOfProject } from "@/lib/pieces/article";
+import type { ProjectRef } from "@/lib/project-types";
+import { playView } from "@/lib/report/playView.mjs";
+import { NotesProvider } from "@/components/notes/NotesProvider";
+import { BenchFrame, BenchTop } from "./bench/BenchShell";
+import PlayCut, { type PlayViewData } from "./review/PlayCut";
+
+// `/projects/<project>/play` (and `?take=<id>`) -- THE PLAY VIEW
+// (umtool/docs/knobs.md, "Play the cut"): the whole cut, or a take, played in the browser in
+// its final look with no render -- every clip from its cached source window,
+// in timeline order, on one cut clock, the live preview's chrome over it --
+// and the notes taken while it plays (anchored to the cut second, the clip
+// and the take), each one the operator's, an agent's to act on (`umtool
+// notes`), or the video assistant's to answer. lib/report/playView.mjs reads
+// what it plays; nothing here fetches, cuts or renders.
+
+const KEYS = [
+ { keys: ["Space"], label: "play" },
+ { keys: ["N", "P"], label: "next / prev clip" },
+ { keys: ["←", "→"], label: "∓5 s" },
+ { keys: ["M"], label: "note" },
+];
+
+export default async function PlayCutPage({ project, take, note }: { project: ProjectRef; take?: string; note?: string }) {
+ const [view, back] = await Promise.all([playView(project, { take: take || null }), pieceHrefOfProject(project.id, { tab: "cut" })]);
+ const top = (
+ <BenchTop
+ trail={[{ href: projectsHref(), label: "Projects" }]}
+ back={{ href: back, label: project.id }}
+ kind="Play the cut"
+ here={"error" in view || !view.take ? "the cut" : `take ${view.take.id}`}
+ keys={KEYS}
+ />
+ );
+ if ("error" in view) {
+ return (
+ <BenchFrame kind="play" top={top}>
+ <main className="deck-main flex-1 p-4">
+ <p data-play-error="" className="text-[12px] text-reject-text">
+ {view.error}{" "}
+ {take && (
+ <Link href={playHref(project.id)} className="ink-link">
+ play the cut instead
+ </Link>
+ )}
+ </p>
+ </main>
+ </BenchFrame>
+ );
+ }
+ return (
+ <BenchFrame kind="play" top={top}>
+ <NotesProvider target={{ project: project.id }}>
+ <PlayCut view={view as PlayViewData} initialNote={note ?? null} />
+ </NotesProvider>
+ </BenchFrame>
+ );
+}
diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx
@@ -10,6 +10,7 @@ import TakesPage from "./TakesPage";
import NarrationPage from "./NarrationPage";
import ReviewPage from "./ReviewPage";
import ClipDeckPage from "./ClipDeckPage";
+import PlayCutPage from "./PlayCutPage";
// ---------------------------------------------------------------------------
// The one place a kind id is matched against a component.
@@ -67,6 +68,9 @@ export default async function ProjectView({
// keep / cut / not him / read aloud (release 34), applied at render;
// on a cut that is not a montage, the clip editor (release 35 C2).
if (rest.length === 1 && rest[0] === "clips") return <ClipDeckPage project={project} show={search.show} mode={search.mode} clip={search.clip} />;
+ // `/projects/<project>/play` -- the whole cut (or `?take=<id>`) played in
+ // the browser in its final look, no render, with notes taken as it plays.
+ if (rest.length === 1 && rest[0] === "play") return <PlayCutPage project={project} take={search.take} note={search.note} />;
return notFound();
}
case "sweep-report": {
diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx
@@ -1,6 +1,7 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
+import Link from "next/link";
import { useRouter } from "next/navigation";
import DeletePlan from "@/components/DeletePlan";
import AnchoredNotes from "@/components/notes/AnchoredNotes";
@@ -9,6 +10,7 @@ import TimedNotes from "@/components/notes/TimedNotes";
import { badgeVariants, type BadgeVariants } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import { fmtAgo } from "@/lib/format";
+import { playHref } from "@/lib/hrefs";
import { BenchBody, VerdictBar } from "./bench/BenchShell";
import { startTakeJob } from "./NewTakePanel";
@@ -437,12 +439,20 @@ function TakeCard({
picked
</span>
)}
+ <Link
+ href={playHref(project, { take: t.id })}
+ data-play-take={t.id}
+ className="ml-auto text-[11px] ink-link"
+ title="play this take's whole cut in the browser, in its final look, without rendering it"
+ >
+ Play
+ </Link>
<button
type="button"
data-action="listen"
aria-pressed={listening}
disabled={!ready || t.previewSize == null}
- className={`ml-auto rounded border px-2 py-0.5 text-[11px] ${tone("sel", listening)}`}
+ className={`rounded border px-2 py-0.5 text-[11px] ${tone("sel", listening)}`}
onClick={onListen}
>
{listening ? "Listening" : "Listen"}
diff --git a/umtool/components/projects/report/AssistBox.tsx b/umtool/components/projects/report/AssistBox.tsx
@@ -6,6 +6,7 @@ import { buttonVariants } from "@/components/ui/button";
import { useSharedNotes } from "@/components/notes/NotesProvider";
import { NoteThread } from "@/components/notes/NoteThread";
import { cn } from "@/lib/utils";
+import type { NoteReply } from "@/lib/annotations/types";
// ---------------------------------------------------------------------------
// THE ASK BOX (release 38 lane E): the video assistant, optional in every
@@ -23,9 +24,9 @@ import { cn } from "@/lib/utils";
type Scope = "look" | "clips" | "fx" | "all";
type ProposedOp = { id: string; op: Record<string, unknown>; diff: string; warning?: string; status: "proposed" | "applied" | "dismissed" | "failed"; error?: string; now?: string | null; diffNow?: string | null };
-type Proposals = { at: string; model: string; request: string; scope: string; note?: string; reply?: string; ops: ProposedOp[]; refused: { op: Record<string, unknown>; why: string }[] };
-type Job = { id: string; status: string; ended: boolean; queue: { key?: string; position?: number } | null; last: string | null; summary: string | null; note?: string; request?: string };
-type View = {
+export type Proposals = { at: string; model: string; request: string; scope: string; note?: string; reply?: string; ops: ProposedOp[]; refused: { op: Record<string, unknown>; why: string }[] };
+export type Job = { id: string; status: string; ended: boolean; queue: { key?: string; position?: number } | null; last: string | null; summary: string | null; note?: string; request?: string };
+export type View = {
proposals: Proposals | null;
error: string | null;
route: { route: "code" | "api" | "local" | null; model: string | null; why: string | null } | null;
@@ -36,14 +37,14 @@ type View = {
type Preview = { size: number; mtimeMs: number; stale: boolean; record: { clips?: string[] } | null } | null;
type PreviewJob = { id: string; state: string; error: string | null };
-const routeLine = (v: View): string => {
+export const routeLine = (v: View): string => {
if (!v.route) return `The assistant needs the editor${v.editorError ? ` (${v.editorError})` : ""}. Every setting here is a field you can change by hand.`;
if (v.route.why) return `${v.route.why}. Every setting here is a field you can change by hand.`;
if (v.route.route === "local") return `On the local model${v.route.model ? ` (${v.route.model})` : ""}, through the GPU: it waits while a transcription runs. Nothing changes until you Apply.`;
return `On the Claude API${v.route.model ? ` (${v.route.model})` : ""}. Nothing changes until you Apply.`;
};
-const jobLine = (j: Job): string => {
+export const jobLine = (j: Job): string => {
if (j.ended) return j.status === "done" ? (j.summary ?? "Done") : `The ask ${j.status}${j.last ? ` — ${j.last}` : ""}`;
if (j.status === "queued") {
const gpu = j.queue?.key === "draft:local";
@@ -144,7 +145,7 @@ export function useAssist(project: string) {
}
/** The proposals as a diff list: Apply one, Apply all, Dismiss. */
-function ProposalList({ p, busy, onApply, onDismiss }: { p: Proposals; busy: boolean; onApply: (ids: string[] | null) => void; onDismiss: () => void }) {
+export function ProposalList({ p, busy, onApply, onDismiss }: { p: Proposals; busy: boolean; onApply: (ids: string[] | null) => void; onDismiss: () => void }) {
const waiting = p.ops.filter((o) => o.status === "proposed" || o.status === "failed");
const applicable = waiting.filter((o) => !o.now);
return (
@@ -270,6 +271,57 @@ function JoinPreview({ project, version }: { project: string; version: string })
);
}
+/**
+ * Under an agent's reply that carries the assistant's proposals (`assist`):
+ * how many, and Apply all -- only while they are the proposals on file and
+ * something still waits. Nothing is written until the click.
+ */
+export function AssistReplyApply({
+ reply: r,
+ proposals: p,
+ busy,
+ apply,
+ onApplied,
+}: {
+ reply: NoteReply;
+ proposals: Proposals | null;
+ busy: boolean;
+ apply: (ids: string[] | null, at?: string) => Promise<boolean>;
+ onApplied: () => void;
+}) {
+ const pr = r.proposal;
+ if (!pr || pr.kind !== "assist" || r.author !== "agent") return null;
+ const current = !!p && p.at === pr.at;
+ const waiting = current ? p!.ops.filter((o) => o.status === "proposed" && !o.now).length : 0;
+ return (
+ <div data-reply-proposal="assist" className="ml-4 flex flex-wrap items-center gap-1.5 text-[11px] text-text-2">
+ <span className={badgeVariants({ variant: "meter", size: "sm" })}>proposes</span>
+ <span>
+ {pr.ops} edit{pr.ops === 1 ? "" : "s"}
+ </span>
+ {!current ? (
+ <span className="text-muted">a newer ask replaced these</span>
+ ) : waiting ? (
+ <button
+ type="button"
+ data-apply-proposal="assist"
+ disabled={busy}
+ onClick={() =>
+ void apply(null, pr.at).then((ok) => {
+ if (ok) onApplied();
+ })
+ }
+ className={buttonVariants({ variant: "go", size: "sm" })}
+ >
+ Apply all
+ </button>
+ ) : (
+ <span className="text-muted">nothing waiting</span>
+ )}
+ </div>
+ );
+}
+
/** The project-level notes, each with Ask the assistant; an agent reply's proposals with Apply all. */
function ProjectNotes({ project, a, scope, apply }: { project: string; a: ReturnType<typeof useAssist>; scope: Scope; apply: (ids: string[] | null, at?: string) => Promise<boolean> }) {
const notes = useSharedNotes({ project });
@@ -310,39 +362,7 @@ function ProjectNotes({ project, a, scope, apply }: { project: string; a: Return
</button>
) : null
}
- afterReply={(r) => {
- const pr = r.proposal;
- if (!pr || pr.kind !== "assist" || r.author !== "agent") return null;
- const current = !!p && p.at === pr.at;
- const waiting = current ? p!.ops.filter((o) => o.status === "proposed" && !o.now).length : 0;
- return (
- <div data-reply-proposal="assist" className="ml-4 flex flex-wrap items-center gap-1.5 text-[11px] text-text-2">
- <span className={badgeVariants({ variant: "meter", size: "sm" })}>proposes</span>
- <span>
- {pr.ops} edit{pr.ops === 1 ? "" : "s"}
- </span>
- {!current ? (
- <span className="text-muted">a newer ask replaced these</span>
- ) : waiting ? (
- <button
- type="button"
- data-apply-proposal="assist"
- disabled={a.busy}
- onClick={() =>
- void apply(null, pr.at).then((ok) => {
- if (ok) void notes.write({ op: "reply", id: n.id, text: "Applied the assistant's edits" });
- })
- }
- className={buttonVariants({ variant: "go", size: "sm" })}
- >
- Apply all
- </button>
- ) : (
- <span className="text-muted">nothing waiting</span>
- )}
- </div>
- );
- }}
+ afterReply={(r) => <AssistReplyApply reply={r} proposals={p} busy={a.busy} apply={apply} onApplied={() => void notes.write({ op: "reply", id: n.id, text: "Applied the assistant's edits" })} />}
/>
))}
<div className="flex flex-wrap items-start gap-2">
diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx
@@ -8,7 +8,7 @@ import {
} from "@/lib/projects/report.mjs";
import { listTakes } from "@/lib/report/takes.mjs";
import { buttonVariants } from "@/components/ui/button";
-import { clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, projectHref, takesHref } from "@/lib/hrefs";
+import { clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, playHref, projectHref, takesHref } from "@/lib/hrefs";
import { montageClipsOf, momentKeysOf, readRulingsState } from "@/lib/report/montageRulings.mjs";
import FetchUnfetchedButton from "../FetchUnfetchedButton";
import { clipRecord, storedUrlOf } from "@/lib/clips/stored";
@@ -157,6 +157,12 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
</span>
</div>
)}
+ {/* The whole cut played in the browser in its final look, no render (the Play view). */}
+ {clips.length > 0 && (
+ <Link href={playHref(project.id)} data-play-cut-link="" className={buttonVariants({ size: "lg" })} title="play the whole cut here, chrome and all, without rendering it; notes at the playhead">
+ Play the cut
+ </Link>
+ )}
{/* A montage's instances, ruled by ear before a render (release 34). */}
{montage.length > 0 && (
<Link
diff --git a/umtool/components/projects/review/LiveDeckPreview.tsx b/umtool/components/projects/review/LiveDeckPreview.tsx
@@ -8,7 +8,8 @@ import type { EditorClip } from "@/lib/report/clipEditorTypes";
import { footageAt } from "@/lib/report/footage-move.mjs";
import { clipStamps, clockText, cutTimeAt, finaleUp, liveClock, stampAt, tallyAt } from "@/lib/report/liveClock.mjs";
import { tallyVerdicts } from "umtool-report-to-video/factcheck";
-import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH, blurCaptionLayout } from "umtool-report-to-video/clip-blur";
+import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH } from "umtool-report-to-video/clip-blur";
+import { drawFootage } from "./footageCanvas";
import { DeckFrame, FeedOverlay, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type DeckTexts, type Rect } from "../OnscreenSection";
// ---------------------------------------------------------------------------
@@ -200,43 +201,7 @@ export default function LiveDeckPreview({
lastDraw.current = { el, media: video, t: video?.currentTime ?? -1, bg: bgRef.current, size: `${el.width}x${el.height}`, blur: blurKey };
// What the canvas draws, for a test to read: "on" while the blur covers the playhead.
el.dataset.liveBlur = blurNow ? "on" : "off";
- const ctx = el.getContext("2d");
- if (!ctx) return;
- ctx.fillStyle = bgRef.current;
- ctx.fillRect(0, 0, el.width, el.height);
- if (!video) return;
- // Fitted into the box, keeping its aspect, padded in the ground (deckFraming's `fit`).
- const k = Math.min(el.width / video.videoWidth, el.height / video.videoHeight);
- const w = video.videoWidth * k;
- const hh = video.videoHeight * k;
- const x = (el.width - w) / 2;
- const y = (el.height - hh) / 2;
- if (!blurNow) {
- ctx.drawImage(video, x, y, w, hh);
- return;
- }
- // The build's blur: gblur on the picture as it plays, sigma = strength % of its height.
- ctx.save();
- ctx.beginPath();
- ctx.rect(x, y, w, hh);
- ctx.clip();
- ctx.filter = `blur(${((blurNow.strength / 100) * hh).toFixed(1)}px)`;
- ctx.drawImage(video, x, y, w, hh);
- ctx.restore();
- // Its caption, laid out as the build lays it (top centre, one box a line).
- const lay = blurCaptionLayout(blurNow.caption, w, hh);
- ctx.font = `bold ${lay.fontSize}px "IBM Plex Mono", ui-monospace, monospace`;
- ctx.textBaseline = "top";
- lay.lines.forEach((line, i) => {
- const tw = ctx.measureText(line).width;
- const ty = y + lay.top + i * lay.lineHeight;
- ctx.globalAlpha = 0.78;
- ctx.fillStyle = bgRef.current;
- ctx.fillRect(x + (w - tw) / 2 - lay.pad, ty - lay.pad, tw + 2 * lay.pad, lay.fontSize + 2 * lay.pad);
- ctx.globalAlpha = 1;
- ctx.fillStyle = "#fff";
- ctx.fillText(line, x + (w - tw) / 2, ty);
- });
+ drawFootage(el, video, bgRef.current, blurNow);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -0,0 +1,818 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { badgeVariants } from "@/components/ui/badge";
+import { buttonVariants } from "@/components/ui/button";
+import { useSharedNotes } from "@/components/notes/NotesProvider";
+import { NoteComposer, NoteThread } from "@/components/notes/NoteThread";
+import type { Anchor, Note } from "@/lib/annotations/types";
+import { playHref } from "@/lib/hrefs";
+import { cn } from "@/lib/utils";
+import { footageAt } from "@/lib/report/footage-move.mjs";
+import { finaleUp, stampAt, tallyAt } from "@/lib/report/liveClock.mjs";
+import { clockText, cutAtSource, cutNotesRequest, itemIndexAt, playPlan, shownSeconds, sourceAt, startOf } from "@/lib/report/playCut.mjs";
+import { tallyVerdicts } from "umtool-report-to-video/factcheck";
+import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH } from "umtool-report-to-video/clip-blur";
+import { AssistReplyApply, ProposalList, jobLine, routeLine, useAssist } from "../report/AssistBox";
+import { DeckFrame, FeedOverlay, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type Rect } from "../OnscreenSection";
+import { drawFootage, type FootageBlur } from "./footageCanvas";
+
+// ---------------------------------------------------------------------------
+// THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): the whole cut -- or a take -- played
+// continuously in this browser in its final look, with no render; and the
+// notes taken as it plays.
+//
+// THE CLOCK is one cut clock across every entry (lib/report/playCut.mjs):
+// the estimate's segments (the live preview's schedule when the cut has a
+// deck: posts' holds included), each clip played from its cached source
+// window -- the bench's own media route, /api/report/raw, `take` for a take's
+// clip -- and the crossfades played as HARD CUTS at the middle of each one.
+// While a clip plays the clock IS its <video>'s position mapped through the
+// play window (liveClock.mjs's rule), so the deck's rail pip, the tally, the
+// stamps and the finale advance exactly as the live preview places them; a
+// card, a hold or a clip with no media on disk advance it by the wall clock.
+//
+// TWO <video> elements: the one playing and the next clip's, loaded and
+// seeked to its first shown second while this one plays, swapped at the cut.
+//
+// THE CHROME is the live preview's (LiveDeckPreview.tsx): the build's own
+// pages composed from the estimate (POST /api/report/chrome/preview,
+// `estimate: true`, `take` for a take -- composed under the take's own
+// directory) and seeked in cut seconds; the footage drawn into a canvas at
+// the footage box by footageCanvas.ts, blurred as the build blurs it unless
+// the cut (or the take) renders uncensored.
+//
+// THE NOTES: `m` (or Note at playhead) pauses and takes a note anchored to
+// the cut second, the clip on screen and its source second, and the take
+// (anchor `cut`, the project's notes.json through the notes route). Listed
+// in cut order; a click seeks there. `umtool notes <project>` prints them for
+// an agent; Send to the assistant asks the video assistant (the editor's
+// `video-assist`, routed by settings.generation), which replies on the note
+// with an Apply -- nothing is written until the operator's click.
+// ---------------------------------------------------------------------------
+
+export type PlayEntry = {
+ id: string;
+ type: string;
+ heading: string;
+ date?: string | null;
+ quote?: string | null;
+ video?: string;
+ start?: number;
+ end?: number;
+ cutStart?: number | null;
+ cutEnd?: number | null;
+ blur?: { on?: boolean; caption?: string; strength?: number; from?: number; to?: number } | null;
+ media?: { name: string; from: number; to: number } | null;
+};
+
+export type PlayViewData = {
+ project: string;
+ take: { id: string; label: string; summary: string; made: boolean; from: string } | null;
+ note: string | null;
+ takes: { id: string; label: string; made: boolean }[];
+ leadIn: number;
+ transition: number;
+ blurRendered: boolean;
+ deckOn: boolean;
+ segments: { id: string; start: number; duration: number; hold?: number }[];
+ entries: PlayEntry[];
+};
+
+type LiveDoc = DeckPreviewDoc & {
+ leadIn?: number;
+ verdictLabels?: Record<string, string>;
+ schedule: DeckPreviewDoc["schedule"] & { finale?: { from: number; to: number } };
+};
+type Ui = { t: number; cur: number; playing: boolean; ended: boolean; waiting: boolean };
+
+/** The clip bench's speeds; the <video> keeps the voice's pitch by itself (`preservesPitch`). */
+const RATES = [0.75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3] as const;
+const SKIP_S = 5;
+
+const APPROXIMATE =
+ "approximate: each crossfade is a hard cut at its middle; cards, teasers and images are placeholders; the edges are not snapped to silence; the sound is the source's (no room, no Audio knobs); the clock is the estimate's";
+
+const fmtLen = (s: number) => (s >= 60 ? clockText(s).replace(/\.\d$/, "") : `${s.toFixed(1)} s`);
+
+export default function PlayCut({ view, initialNote }: { view: PlayViewData; initialNote: string | null }) {
+ const router = useRouter();
+ const project = view.project;
+ const take = view.take?.id ?? null;
+
+ // ---- the composition (the live preview's) ---------------------------------
+ const [doc, setDoc] = useState<LiveDoc | null>(null);
+ const [composeState, setComposeState] = useState<"composing" | "ready" | "no-deck" | "error">(view.deckOn ? "composing" : "no-deck");
+ const [composeError, setComposeError] = useState<string | null>(null);
+ const seq = useRef(0);
+ const compose = useCallback(async () => {
+ const mine = ++seq.current;
+ setComposeState("composing");
+ try {
+ const r = await fetch("/api/report/chrome/preview", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, estimate: true, ...(take ? { take } : {}) }),
+ });
+ const j = (await r.json().catch(() => ({}))) as LiveDoc & { error?: string; deckOn?: boolean };
+ if (mine !== seq.current) return;
+ if (!r.ok) {
+ setDoc(null);
+ setComposeState(j.deckOn === false ? "no-deck" : "error");
+ setComposeError(j.deckOn === false ? null : String(j.error ?? `HTTP ${r.status}`));
+ } else {
+ setDoc(j);
+ setComposeState("ready");
+ setComposeError(null);
+ }
+ } catch (e) {
+ if (mine === seq.current) {
+ setComposeState("error");
+ setComposeError(e instanceof Error ? e.message : String(e));
+ }
+ }
+ }, [project, take]);
+ useEffect(() => {
+ if (view.deckOn) void compose();
+ }, [compose, view.deckOn]);
+
+ // ---- the plan ----------------------------------------------------------------
+ const schedule = doc?.schedule ?? null;
+ const segments = schedule?.segments ?? view.segments;
+ const leadIn = doc?.leadIn ?? view.leadIn;
+ const plan = useMemo(() => playPlan(segments, view.entries, { leadIn }), [segments, view.entries, leadIn]);
+ const entryOf = useMemo(() => new Map(view.entries.map((e) => [e.id, e])), [view.entries]);
+ const planRef = useRef(plan);
+ planRef.current = plan;
+ const entryRef = useRef(entryOf);
+ entryRef.current = entryOf;
+
+ // ---- the engine ----------------------------------------------------------------
+ const vA = useRef<HTMLVideoElement | null>(null);
+ const vB = useRef<HTMLVideoElement | null>(null);
+ const canvas = useRef<HTMLCanvasElement | null>(null);
+ const slotEl = useCallback((k: number) => (k === 0 ? vA.current : vB.current), []);
+ const eng = useRef({ t: 0, cur: 0, playing: false, ended: false, rate: 1, last: 0, active: 0, held: [-1, -1] as number[], failed: new Set<string>(), waiting: false });
+ const [ui, setUi] = useState<Ui>({ t: 0, cur: 0, playing: false, ended: false, waiting: false });
+ const [rate, setRate] = useState(1);
+ const [failed, setFailed] = useState<Record<string, string>>({});
+ const bg = doc?.background ?? "#000";
+ const bgRef = useRef(bg);
+ bgRef.current = bg;
+
+ const srcOf = useCallback(
+ (id: string, file: string) => `/api/report/raw?${new URLSearchParams({ project, clip: id, ...(take ? { take } : {}), file }).toString()}`,
+ [project, take],
+ );
+ const hasVideo = useCallback((i: number) => {
+ const item = planRef.current.items[i];
+ const e = item ? entryRef.current.get(item.id) : null;
+ return !!item?.clip && !!e?.media && !eng.current.failed.has(item.id);
+ }, []);
+
+ /** Put item i's media in a slot, at the source second cut second t shows. */
+ const load = useCallback(
+ (slot: number, i: number, t: number) => {
+ const item = planRef.current.items[i];
+ const e = item ? entryRef.current.get(item.id) : null;
+ const v = slotEl(slot);
+ if (!v || !item?.clip || !e?.media) return;
+ const want = Math.max(0, (sourceAt(item, t) ?? item.clip.sourceFrom) - e.media.from);
+ const url = srcOf(item.id, e.media.name);
+ if (eng.current.held[slot] !== i || v.getAttribute("src") !== url) {
+ v.setAttribute("src", url);
+ v.dataset.playSlotItem = item.id;
+ eng.current.held[slot] = i;
+ }
+ v.playbackRate = eng.current.rate;
+ v.preservesPitch = true;
+ const seek = () => {
+ try {
+ v.currentTime = want;
+ } catch {
+ // Not seekable yet: the metadata listener seeks.
+ }
+ };
+ if (v.readyState >= 1) seek();
+ else v.addEventListener("loadedmetadata", seek, { once: true });
+ },
+ [slotEl, srcOf],
+ );
+
+ /** Make item i the one on screen at cut second t, and load the next clip behind it. */
+ const enter = useCallback(
+ (i: number, t: number) => {
+ const e = eng.current;
+ const items = planRef.current.items;
+ if (!items.length) return;
+ e.cur = Math.max(0, Math.min(i, items.length - 1));
+ e.t = t;
+ if (hasVideo(e.cur)) {
+ const other = 1 - e.active;
+ const slot = e.held[e.active] === e.cur ? e.active : e.held[other] === e.cur ? other : e.active;
+ if (slot !== e.active) {
+ slotEl(e.active)?.pause();
+ e.active = slot;
+ }
+ load(slot, e.cur, t);
+ if (e.playing) void slotEl(slot)?.play().catch(() => {});
+ } else {
+ vA.current?.pause();
+ vB.current?.pause();
+ }
+ // The next clip with media, ready behind this one before the cut.
+ for (let j = e.cur + 1; j < items.length; j += 1) {
+ if (!hasVideo(j)) continue;
+ if (e.held[e.active] !== j) {
+ load(1 - e.active, j, items[j].from);
+ slotEl(1 - e.active)?.pause();
+ }
+ break;
+ }
+ },
+ [hasVideo, load, slotEl],
+ );
+
+ const publish = useCallback(() => {
+ const e = eng.current;
+ setUi((u) =>
+ Math.abs(u.t - e.t) > 1 / 30 || u.cur !== e.cur || u.playing !== e.playing || u.ended !== e.ended || u.waiting !== e.waiting
+ ? { t: Math.round(e.t * 1000) / 1000, cur: e.cur, playing: e.playing, ended: e.ended, waiting: e.waiting }
+ : u,
+ );
+ }, []);
+
+ const seekTo = useCallback(
+ (t: number) => {
+ const p = planRef.current;
+ const e = eng.current;
+ const at = Math.max(0, Math.min(t, Math.max(0, p.total - 0.001)));
+ e.ended = false;
+ e.last = 0;
+ enter(itemIndexAt(p, at), at);
+ publish();
+ },
+ [enter, publish],
+ );
+
+ const setPlaying = useCallback(
+ (on: boolean) => {
+ const e = eng.current;
+ if (on && e.ended) {
+ e.ended = false;
+ enter(0, 0);
+ }
+ e.playing = on;
+ e.last = 0;
+ const v = slotEl(e.active);
+ if (on && hasVideo(e.cur) && e.held[e.active] === e.cur) void v?.play().catch(() => {});
+ if (!on) {
+ vA.current?.pause();
+ vB.current?.pause();
+ }
+ publish();
+ },
+ [enter, hasVideo, publish, slotEl],
+ );
+
+ // The first entry loaded on arrival; the plan changing (the composed
+ // schedule replacing the estimate's segments) re-places the current second.
+ useEffect(() => {
+ const e = eng.current;
+ enter(itemIndexAt(plan, e.t), e.t);
+ publish();
+ }, [plan, enter, publish]);
+
+ useEffect(() => {
+ eng.current.rate = rate;
+ for (const v of [vA.current, vB.current]) if (v) v.playbackRate = rate;
+ }, [rate]);
+
+ // A slot's media that will not play (gone, refused): that clip plays as a placeholder.
+ const onMediaError = useCallback(
+ (slot: number) => {
+ const e = eng.current;
+ const i = e.held[slot];
+ const item = planRef.current.items[i];
+ if (!item) return;
+ e.failed.add(item.id);
+ e.held[slot] = -1;
+ setFailed((f) => ({ ...f, [item.id]: "the media did not load" }));
+ },
+ [],
+ );
+
+ // Every animation frame: the clock, the cut to the next entry, the picture.
+ const lastDraw = useRef({ key: "" });
+ useEffect(() => {
+ let raf = 0;
+ const tick = (now: number) => {
+ raf = requestAnimationFrame(tick);
+ const e = eng.current;
+ const p = planRef.current;
+ const items = p.items;
+ if (!items.length) return;
+ const dt = e.last ? Math.min(0.25, (now - e.last) / 1000) : 0;
+ e.last = now;
+ let item = items[e.cur];
+ const ent = entryRef.current.get(item.id);
+ const v = slotEl(e.active);
+ const playingVideo = hasVideo(e.cur) && !!v && !!ent?.media && e.held[e.active] === e.cur;
+ e.waiting = false;
+ if (e.playing) {
+ if (playingVideo && v && ent?.media && item.clip) {
+ const src = ent.media.from + v.currentTime;
+ if (src >= item.clip.sourceTo - 0.01 || v.ended) {
+ // Past the footage (a carrying clip's hold): its last frame, the wall clock.
+ if (!v.paused) v.pause();
+ e.t += dt * e.rate;
+ } else if (v.readyState >= 2 && !v.seeking) {
+ if (v.paused) void v.play().catch(() => {});
+ e.t = cutAtSource(item, src);
+ } else e.waiting = true; // buffering: the clock waits for the picture
+ } else e.t += dt * e.rate;
+ if (e.t >= item.to - 0.001) {
+ if (e.cur + 1 < items.length) {
+ enter(e.cur + 1, item.to);
+ item = items[e.cur];
+ } else {
+ e.t = p.total;
+ e.playing = false;
+ e.ended = true;
+ vA.current?.pause();
+ vB.current?.pause();
+ }
+ }
+ }
+ publish();
+
+ // The picture: the playing clip's frame in the footage box, blurred as the build blurs it.
+ const el = canvas.current;
+ if (!el) return;
+ const cur = items[e.cur];
+ const ce = entryRef.current.get(cur.id);
+ const pv = hasVideo(e.cur) && e.held[e.active] === e.cur ? slotEl(e.active) : null;
+ const video = pv && pv.readyState >= 2 && pv.videoWidth > 0 ? pv : null;
+ const src = video && ce?.media ? ce.media.from + video.currentTime : null;
+ const b = ce?.blur && view.blurRendered ? ce.blur : null;
+ const blurNow: FootageBlur =
+ b && src !== null && (b.from ?? -Infinity) <= src && src <= (b.to ?? Infinity)
+ ? { strength: b.strength ?? BLUR_STRENGTH.default, caption: b.caption ?? BLUR_CAPTION_DEFAULT }
+ : null;
+ const key = `${cur.id}|${video ? video.currentTime : -1}|${bgRef.current}|${el.width}x${el.height}|${blurNow ? `${blurNow.strength}${blurNow.caption}` : ""}`;
+ if (key === lastDraw.current.key) return;
+ lastDraw.current.key = key;
+ el.dataset.playBlur = blurNow ? "on" : "off";
+ drawFootage(el, video, bgRef.current, blurNow);
+ };
+ raf = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(raf);
+ }, [enter, hasVideo, publish, slotEl, view.blurRendered]);
+
+ // ---- the controls ----------------------------------------------------------------
+ const next = useCallback(() => seekTo(startOf(planRef.current, eng.current.cur + 1)), [seekTo]);
+ const prev = useCallback(() => seekTo(startOf(planRef.current, eng.current.cur - 1)), [seekTo]);
+ const skip = useCallback((d: number) => seekTo(eng.current.t + d), [seekTo]);
+
+ // ---- the notes -------------------------------------------------------------------
+ const notes = useSharedNotes({ project });
+ const mine = useMemo(
+ () =>
+ notes.notes
+ .filter((n) => n.anchor.kind === "cut" && (n.anchor.take ?? null) === take)
+ .sort((a, b) => (a.anchor as { t: number }).t - (b.anchor as { t: number }).t),
+ [notes.notes, take],
+ );
+ const [drafting, setDrafting] = useState<Extract<Anchor, { kind: "cut" }> | null>(null);
+ const noteHere = useCallback(() => {
+ const e = eng.current;
+ const item = planRef.current.items[e.cur];
+ if (!item) return;
+ setPlaying(false);
+ const src = item.clip ? sourceAt(item, e.t) : null;
+ setDrafting({ kind: "cut", t: Math.round(e.t * 100) / 100, entry: item.id, ...(src !== null ? { sourceT: src } : {}), ...(take ? { take } : {}) });
+ }, [setPlaying, take]);
+
+ // `?note=<id>` (the Inbox's link): seek to it once the notes are read.
+ const sought = useRef(false);
+ useEffect(() => {
+ if (sought.current || !initialNote) return;
+ const n = mine.find((x) => x.id === initialNote);
+ if (!n) return;
+ sought.current = true;
+ seekTo((n.anchor as { t: number }).t);
+ }, [initialNote, mine, seekTo]);
+
+ // ---- the keys ----------------------------------------------------------------------
+ useEffect(() => {
+ const onKey = (ev: KeyboardEvent) => {
+ const tgt = ev.target as HTMLElement | null;
+ if (tgt && (tgt.closest("input, textarea, select, [contenteditable=true]") || ev.metaKey || ev.ctrlKey || ev.altKey)) return;
+ if (ev.key === " ") setPlaying(!eng.current.playing);
+ else if (ev.key === "n") next();
+ else if (ev.key === "p") prev();
+ else if (ev.key === "ArrowRight") skip(SKIP_S);
+ else if (ev.key === "ArrowLeft") skip(-SKIP_S);
+ else if (ev.key === "m") noteHere();
+ else return;
+ ev.preventDefault();
+ };
+ // Space on a focused button would click it too on keyup: the key is the transport's here.
+ const onUp = (ev: KeyboardEvent) => {
+ const tgt = ev.target as HTMLElement | null;
+ if (ev.key === " " && !tgt?.closest("input, textarea, select, [contenteditable=true]")) ev.preventDefault();
+ };
+ window.addEventListener("keydown", onKey);
+ window.addEventListener("keyup", onUp);
+ return () => {
+ window.removeEventListener("keydown", onKey);
+ window.removeEventListener("keyup", onUp);
+ };
+ }, [next, prev, skip, noteHere, setPlaying]);
+
+ // ---- what is on screen -------------------------------------------------------------
+ const t = ui.t;
+ const item = plan.items[ui.cur] ?? null;
+ const entry = item ? entryOf.get(item.id) : null;
+ const g = doc?.geometry ?? null;
+ const box: Rect | null = g ? (doc?.feed?.footage ?? g.footage) : null;
+ const move = schedule ? footageAt(schedule, t) : null;
+ const rect: Rect | null = move?.rect ?? box;
+ const order = useMemo(() => (schedule?.factcheck ? tallyVerdicts(schedule.factcheck.stamps) : []), [schedule]);
+ const tally = schedule?.factcheck ? tallyAt(schedule, t, order) : [];
+ const stamp = schedule ? stampAt(schedule, t) : null;
+ const finaleNow = !!schedule && finaleUp(schedule, t);
+ const postsWin = doc?.posts ? postsWindowAt(doc.posts.windows, t) : null;
+ const missing = !!item?.clip && !entry?.media;
+ const broken = !!item && !!failed[item.id];
+ const placeholder = item && (!item.clip || missing || broken) ? { kind: !item.clip ? "card" : "missing", item, entry } : null;
+ const pct = (n: number, of: number) => `${(n / of) * 100}%`;
+ const segTitle = (id: string) => schedule?.segments.find((s) => s.id === id)?.title || null;
+
+ const placeholderCard = placeholder ? (
+ <div
+ data-play-placeholder={placeholder.kind}
+ data-play-missing={placeholder.kind === "missing" ? placeholder.item.id : undefined}
+ className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-1 p-6 text-center"
+ style={{ background: placeholder.kind === "card" ? bg : "transparent" }}
+ >
+ {placeholder.kind === "card" ? (
+ <>
+ <span className="rounded bg-black/50 px-1.5 py-0.5 font-mono text-[11px] uppercase tracking-wide text-white/70">{placeholder.item.type}</span>
+ <span className="max-w-[80%] text-[clamp(14px,2.4vw,30px)] font-semibold text-white">{placeholder.entry?.heading ?? placeholder.item.id}</span>
+ <span className="text-[11px] text-white/60">not drawn here: the build renders it</span>
+ </>
+ ) : (
+ <span className="rounded bg-black/75 px-2 py-1 text-[12px] text-white">
+ {placeholder.item.id}: {broken ? failed[placeholder.item.id] : "not fetched"} — {placeholder.entry?.video}@{placeholder.entry?.start}–{placeholder.entry?.end}
+ {", playing on as a placeholder"}
+ </span>
+ )}
+ </div>
+ ) : null;
+
+ const footageCanvas = (style: React.CSSProperties | undefined, w: number, h: number) => (
+ <canvas ref={canvas} data-play-footage="" data-play-move={move ? move.segment : ""} width={w} height={h} className="absolute" style={style} />
+ );
+
+ return (
+ <div
+ data-play-cut={take ?? ""}
+ data-play-state={ui.ended ? "ended" : ui.playing ? (ui.waiting ? "waiting" : "playing") : "paused"}
+ data-play-t={String(Math.round(t * 100) / 100)}
+ data-play-item={item?.id ?? ""}
+ data-play-compose={composeState}
+ className="grid min-h-0 flex-1 grid-cols-1 lg:grid-cols-[minmax(0,1fr)_380px]"
+ >
+ <main className="deck-main min-h-0 space-y-2 overflow-auto p-4">
+ {/* The two players: never shown, drawn into the canvas. */}
+ <div className="pointer-events-none fixed left-0 top-0 h-px w-px overflow-hidden opacity-0" aria-hidden>
+ <video ref={vA} data-play-slot="0" preload="auto" playsInline onError={() => onMediaError(0)} />
+ <video ref={vB} data-play-slot="1" preload="auto" playsInline onError={() => onMediaError(1)} />
+ </div>
+
+ <div className="w-full max-w-[960px]">
+ {doc && g && box ? (
+ <DeckFrame preview={doc} t={t} texts={{}} testid="play-deck">
+ <div className="absolute inset-0" style={{ background: bg }} />
+ {footageCanvas(rect ? { left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H) } : undefined, box.width, box.height)}
+ {placeholderCard}
+ {doc.feed && <FeedOverlay key={doc.feed.src ?? "none"} feed={doc.feed} frame={g} t={t} testid="play-feed" />}
+ {postsWin && doc.posts && <PostsOverlay key={`${postsWin.segment}:${postsWin.src ?? "none"}`} win={postsWin} geometry={doc.posts.geometry} frame={g} t={t} />}
+ {doc.stamp && <FeedOverlay key={`stamp:${doc.stamp.src ?? "none"}`} feed={doc.stamp} frame={g} t={t} ready="stamp:ready" testid="play-stamp" name="fact-check stamps" />}
+ {doc.finale && finaleNow && (
+ <div className="pointer-events-none absolute inset-0" style={{ zIndex: 2 }} data-play-finale="">
+ <FeedOverlay key={`finale:${doc.finale.src ?? "none"}`} feed={doc.finale} frame={g} t={t} ready="finale:ready" testid="play-finale" name="finale" />
+ </div>
+ )}
+ </DeckFrame>
+ ) : (
+ <div className="relative w-full overflow-hidden rounded border border-[var(--color-line)] bg-black" style={{ aspectRatio: "16 / 9" }} data-testid="play-plain">
+ {footageCanvas({ inset: 0, width: "100%", height: "100%" }, 1280, 720)}
+ {placeholderCard}
+ </div>
+ )}
+ </div>
+
+ {/* ---- the transport ---- */}
+ <div className="flex flex-wrap items-center gap-2 text-[12px]" data-play-transport="">
+ <button type="button" data-play-prev="" onClick={prev} className={buttonVariants({ variant: "quiet", size: "sm" })} title="previous entry (p)">
+ ‹ prev
+ </button>
+ <button type="button" data-play-back="" onClick={() => skip(-SKIP_S)} className={buttonVariants({ variant: "quiet", size: "sm" })} title="back 5 s (←)">
+ −5 s
+ </button>
+ <button type="button" data-play-toggle="" onClick={() => setPlaying(!ui.playing)} className={buttonVariants({ variant: "go", size: "sm" })} title="play / pause (space)">
+ {ui.playing ? "Pause" : ui.ended ? "Play again" : "Play"}
+ </button>
+ <button type="button" data-play-fwd="" onClick={() => skip(SKIP_S)} className={buttonVariants({ variant: "quiet", size: "sm" })} title="on 5 s (→)">
+ +5 s
+ </button>
+ <button type="button" data-play-next="" onClick={next} className={buttonVariants({ variant: "quiet", size: "sm" })} title="next entry (n)">
+ next ›
+ </button>
+ <label className="inline-flex items-center gap-1 text-text-2">
+ speed
+ <select data-play-rate="" value={rate} onChange={(e) => setRate(Number(e.target.value))} className="rounded border border-seam-2 bg-ground px-1 py-0.5 text-[12px] text-text">
+ {RATES.map((r) => (
+ <option key={r} value={r}>
+ {r}×
+ </option>
+ ))}
+ </select>
+ </label>
+ <span className="num font-mono text-[12px] text-text" data-play-clock="">
+ {clockText(t)} / {clockText(plan.total)}
+ </span>
+ {item && (
+ <span className="num font-mono text-[11.5px] text-muted" data-play-readout="">
+ {ui.cur + 1} of {plan.items.length} · {item.id}
+ {segTitle(item.id) ? ` · ${segTitle(item.id)}` : ""}
+ </span>
+ )}
+ {ui.waiting && <span className="micro" data-play-waiting="">loading…</span>}
+ <button type="button" data-play-note-add="" onClick={noteHere} className={cn(buttonVariants({ size: "sm" }), "ml-auto")} title="pause and take a note here (m)">
+ Note at playhead
+ </button>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11.5px] text-text-2" data-play-hud="">
+ {tally.length > 0 && <span data-play-tally={tally.map((r) => `${r.verdict}:${r.count}`).join(",")}>tally {tally.map((r) => `${doc?.verdictLabels?.[r.verdict] ?? r.verdict} ${r.count}`).join(" · ")}</span>}
+ {schedule?.factcheck && <span data-play-stamp={stamp ? `${stamp.claim}:${stamp.phase}` : ""}>{stamp ? `stamp ${stamp.claim} (${stamp.phase})` : "no stamp on screen"}</span>}
+ {finaleNow && <span data-play-finale-up="">finale</span>}
+ {composeState === "composing" && <span className="micro">composing the chrome…</span>}
+ {composeState === "no-deck" && <span className="text-muted">no on-screen deck in this cut: the footage alone</span>}
+ {composeState === "error" && (
+ <span role="alert" className="text-reject-text" data-play-compose-error="">
+ the chrome did not compose: {composeError}
+ </span>
+ )}
+ {composeState !== "composing" && view.deckOn && (
+ <button type="button" className="ink-link" onClick={() => void compose()} title="compose the pages again from the manifest">
+ Recompose
+ </button>
+ )}
+ <button
+ type="button"
+ className="ink-link"
+ data-play-reload=""
+ title="read the cut again (after an edit elsewhere) and compose its pages again"
+ onClick={() => {
+ router.refresh();
+ if (view.deckOn) void compose();
+ }}
+ >
+ Reload the cut
+ </button>
+ </div>
+ <p className="m-0 text-[11px] text-muted" data-play-approximate="">
+ {APPROXIMATE}
+ {!view.blurRendered ? " · blurred clips play unblurred (render.blur off)" : ""}
+ {view.note ? ` · ${view.note}` : ""}
+ </p>
+ {doc?.finale?.error && <p className="m-0 text-[11px] text-reject-text">the finale did not compose: {doc.finale.error}</p>}
+ </main>
+
+ {/* ---- the side: what plays, the takes, the notes ---- */}
+ <aside className="flex min-h-0 flex-col gap-3 overflow-auto border-t border-seam bg-panel p-3 lg:border-l lg:border-t-0" data-play-side="">
+ <section data-play-takes="">
+ <h2 className="micro m-0 mb-1">Playing</h2>
+ <div className="flex flex-wrap gap-1.5 text-[12px]">
+ <Link href={playHref(project)} aria-current={take ? undefined : "page"} data-play-take-link="" className={take ? "ink-link" : "font-medium text-text"}>
+ the cut
+ </Link>
+ {view.takes.map((tk) => (
+ <Link
+ key={tk.id}
+ href={playHref(project, { take: tk.id })}
+ aria-current={tk.id === take ? "page" : undefined}
+ data-play-take-link={tk.id}
+ className={tk.id === take ? "font-medium text-text" : "ink-link"}
+ title={tk.made ? tk.label : `${tk.label} (not rendered yet)`}
+ >
+ {tk.id}
+ {tk.made ? "" : "*"}
+ </Link>
+ ))}
+ </div>
+ {view.take && (
+ <p className="m-0 mt-1 text-[11.5px] text-text-2" data-play-take={view.take.id}>
+ take “{view.take.label}”: the project’s manifest with its patch ({view.take.from}){view.take.made ? "" : " — not rendered yet"}
+ </p>
+ )}
+ </section>
+
+ <section>
+ <h2 className="micro m-0 mb-1">
+ {plan.items.length} entries · {clockText(plan.total)}
+ </h2>
+ <ol className="m-0 list-none space-y-0.5 p-0" data-play-list="">
+ {plan.items.map((it, i) => {
+ const e = entryOf.get(it.id);
+ const date = it.clip ? segTitle(it.id) || e?.date : null;
+ return (
+ <li key={it.id}>
+ <button
+ type="button"
+ data-play-row={it.id}
+ aria-current={i === ui.cur ? "true" : undefined}
+ onClick={() => seekTo(it.from)}
+ className={cn("flex w-full items-baseline gap-2 rounded-[3px] px-1.5 py-1 text-left text-[12px]", i === ui.cur ? "bg-panel-2 text-text" : "text-text-2 hover:bg-panel-2")}
+ >
+ <span className="font-mono">{it.id}</span>
+ <span className="min-w-0 flex-1 truncate text-muted">{it.clip ? (date ?? "") : `${it.type} · ${e?.heading ?? ""}`}</span>
+ {it.clip && !e?.media && <span className={badgeVariants({ variant: "blocking", size: "sm" })} data-play-row-missing="">not fetched</span>}
+ {failed[it.id] && <span className={badgeVariants({ variant: "blocking", size: "sm" })}>no media</span>}
+ {e?.blur && <span className="text-[10.5px] text-muted">{view.blurRendered ? "blurred" : "unblurred"}</span>}
+ <span className="num font-mono text-[11px] text-muted">{fmtLen(shownSeconds(it))}</span>
+ </button>
+ </li>
+ );
+ })}
+ </ol>
+ </section>
+
+ <PlayNotes
+ project={project}
+ take={take}
+ notes={notes}
+ mine={mine}
+ drafting={drafting}
+ onCancel={() => setDrafting(null)}
+ onAdded={() => setDrafting(null)}
+ onSeek={(n) => seekTo((n.anchor as { t: number }).t)}
+ onApplied={() => {
+ router.refresh();
+ if (view.deckOn) void compose();
+ }}
+ />
+ </aside>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// The notes taken while playing: the composer at the playhead, the list in
+// cut order (a click seeks), each one sent to the assistant on a click.
+// ---------------------------------------------------------------------------
+
+function PlayNotes({
+ project,
+ take,
+ notes,
+ mine,
+ drafting,
+ onCancel,
+ onAdded,
+ onSeek,
+ onApplied,
+}: {
+ project: string;
+ take: string | null;
+ notes: ReturnType<typeof useSharedNotes>;
+ mine: Note[];
+ drafting: Extract<Anchor, { kind: "cut" }> | null;
+ onCancel: () => void;
+ onAdded: () => void;
+ onSeek: (n: Note) => void;
+ onApplied: () => void;
+}) {
+ const a = useAssist(project);
+ const reloadNotes = notes.reload;
+ useEffect(() => {
+ if (a.ended) void reloadNotes();
+ }, [a.ended, reloadNotes]);
+ const blocked = !a.view ? "reading the assistant's route…" : (a.view.route?.why ?? (!a.view.route ? "the assistant needs the editor" : null));
+ const running = !!a.job && !a.job.ended;
+ const asking = running ? (a.job?.note ?? "all") : null;
+ const p = a.view?.proposals ?? null;
+ const open = mine.filter((n) => n.status === "open");
+ const all = cutNotesRequest(mine, { take });
+ const apply = async (ids: string[] | null, at?: string) => {
+ const ok = await a.apply(ids, at ?? p?.at);
+ if (ok) onApplied();
+ return ok;
+ };
+ const where = (n: Note) => {
+ const an = n.anchor as Extract<Anchor, { kind: "cut" }>;
+ return (
+ <button type="button" data-play-note-seek={an.t} onClick={() => onSeek(n)} className="num shrink-0 font-mono text-[11px] ink-link" title="play from here">
+ {clockText(an.t)}
+ {an.entry ? ` · ${an.entry}` : ""}
+ </button>
+ );
+ };
+ return (
+ <section data-play-notes={mine.length} className="space-y-1.5">
+ <h3 className="micro m-0">
+ Notes{take ? ` on take ${take}` : " on the cut"}
+ {mine.length ? ` — ${open.length} open` : ""}
+ </h3>
+ {drafting && (
+ <NoteComposer
+ testId="play-note-input"
+ busy={notes.busy}
+ placeholder="what to change here — Enter to save"
+ head={
+ <span className="num font-mono text-[11px] text-text-2" data-play-note-at={drafting.t}>
+ at {clockText(drafting.t)}
+ {drafting.entry ? ` · ${drafting.entry}` : ""}
+ </span>
+ }
+ onCancel={onCancel}
+ onAdd={(text) =>
+ void notes.write({ op: "add", text, anchor: drafting }).then((n) => {
+ if (n) onAdded();
+ })
+ }
+ />
+ )}
+ {!drafting && !mine.length && <p className="m-0 text-[11.5px] text-muted">Press m (or Note at playhead) while it plays.</p>}
+ {mine.map((n) => (
+ <div key={n.id} data-play-note={n.id}>
+ <NoteThread
+ note={n}
+ write={notes.write}
+ busy={notes.busy}
+ head={where(n)}
+ actions={
+ n.status === "open" ? (
+ <button
+ type="button"
+ data-play-send={n.id}
+ disabled={notes.busy || a.busy || !!blocked || running}
+ title={blocked ?? "the assistant reads this note (with where it was taken) and replies here; what it proposes waits for your Apply"}
+ onClick={() => void a.ask({ note: n.id, scope: "all" })}
+ className="ink-link disabled:opacity-40"
+ >
+ {asking === n.id ? "Asking…" : "Send to the assistant"}
+ </button>
+ ) : null
+ }
+ afterReply={(r) => <AssistReplyApply reply={r} proposals={p} busy={a.busy} apply={apply} onApplied={() => void notes.write({ op: "reply", id: n.id, text: "Applied the assistant's edits" })} />}
+ />
+ </div>
+ ))}
+ <div className="space-y-1 border-t border-seam pt-1.5" data-play-assist={a.view?.route?.route ?? "none"}>
+ <div className="flex flex-wrap items-center gap-2">
+ <button
+ type="button"
+ data-play-send-all=""
+ disabled={!all || !!blocked || running || a.busy}
+ title={blocked ?? "every open note here, in cut order, as one request; its proposals come back below"}
+ onClick={() => all && void a.ask({ request: all, scope: "all" })}
+ className={buttonVariants({ size: "sm" })}
+ >
+ {asking === "all" ? "Asking…" : `Send all open notes${open.length ? ` (${open.length})` : ""}`}
+ </button>
+ {running && (
+ <button type="button" onClick={() => void a.cancel()} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Stop
+ </button>
+ )}
+ </div>
+ {a.view && (
+ <p className="m-0 text-[11px] text-muted" data-play-assist-status="">
+ {routeLine(a.view)}
+ </p>
+ )}
+ <p className="m-0 text-[11px] text-muted">
+ For Claude Code: <code className="font-mono">umtool notes {project}</code> prints these with where each was taken.
+ </p>
+ {a.job && (
+ <p className="m-0 text-[11.5px] text-text-2" data-play-assist-job={a.job.status}>
+ {jobLine(a.job)}
+ </p>
+ )}
+ {(a.error || a.view?.error) && (
+ <p role="alert" className="m-0 text-[11.5px] text-reject-text">
+ {a.error ?? a.view?.error}
+ </p>
+ )}
+ {p && <ProposalList p={p} busy={a.busy} onApply={(ids) => void apply(ids)} onDismiss={() => void a.dismiss(null)} />}
+ </div>
+ </section>
+ );
+}
diff --git a/umtool/components/projects/review/footageCanvas.ts b/umtool/components/projects/review/footageCanvas.ts
@@ -0,0 +1,51 @@
+import { blurCaptionLayout } from "umtool-report-to-video/clip-blur";
+
+// THE FOOTAGE AS THE BUILD FRAMES IT, drawn into a canvas: the live preview's
+// (LiveDeckPreview.tsx) and the Play view's (PlayCut.tsx) one picture. The
+// playing <video> fitted into the footage box keeping its aspect, padded in
+// the palette's ground (deckFraming's `fit`); a clip's `blur` (clip-blur.mjs)
+// through the canvas's own Gaussian -- the build's sigma, its strength as a %
+// of the picture's height -- with its caption laid out by the build's own
+// blurCaptionLayout (top centre, one box a line). No second decode: the
+// element that plays is the element drawn.
+
+/** The blur on screen now: its strength (% of the picture's height) and its caption; null when none. */
+export type FootageBlur = { strength: number; caption: string } | null;
+
+export function drawFootage(el: HTMLCanvasElement, video: HTMLVideoElement | null, bg: string, blur: FootageBlur) {
+ const ctx = el.getContext("2d");
+ if (!ctx) return;
+ ctx.fillStyle = bg;
+ ctx.fillRect(0, 0, el.width, el.height);
+ if (!video) return;
+ const k = Math.min(el.width / video.videoWidth, el.height / video.videoHeight);
+ const w = video.videoWidth * k;
+ const hh = video.videoHeight * k;
+ const x = (el.width - w) / 2;
+ const y = (el.height - hh) / 2;
+ if (!blur) {
+ ctx.drawImage(video, x, y, w, hh);
+ return;
+ }
+ // The build's blur: gblur on the picture as it plays, sigma = strength % of its height.
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(x, y, w, hh);
+ ctx.clip();
+ ctx.filter = `blur(${((blur.strength / 100) * hh).toFixed(1)}px)`;
+ ctx.drawImage(video, x, y, w, hh);
+ ctx.restore();
+ const lay = blurCaptionLayout(blur.caption, w, hh);
+ ctx.font = `bold ${lay.fontSize}px "IBM Plex Mono", ui-monospace, monospace`;
+ ctx.textBaseline = "top";
+ lay.lines.forEach((line, i) => {
+ const tw = ctx.measureText(line).width;
+ const ty = y + lay.top + i * lay.lineHeight;
+ ctx.globalAlpha = 0.78;
+ ctx.fillStyle = bg;
+ ctx.fillRect(x + (w - tw) / 2 - lay.pad, ty - lay.pad, tw + 2 * lay.pad, lay.fontSize + 2 * lay.pad);
+ ctx.globalAlpha = 1;
+ ctx.fillStyle = "#fff";
+ ctx.fillText(line, x + (w - tw) / 2, ty);
+ });
+}
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -176,6 +176,37 @@ build does that the preview does not: it snaps each edge to a silence (the deck'
(here the clip plays alone), it applies room's muted edges and the clip's Audio knobs, and it draws in the render's
browser. **Render this clip** is the pixel-true check of all of that but the joins.
+## Play the cut (the whole cut, or a take, with no render)
+
+`/projects/<p>/play` — the Cut tab's **Play the cut**, or a take's **Play** on the takes page
+(`/projects/<p>/play?take=<id>`) — plays the WHOLE cut in this browser in its final look, for iterating without a
+render: every entry in timeline order, each clip from its cached source window (the bench's media route, an
+excerpt of a long recording), the live preview's chrome over it on ONE cut clock — the rail's pip, the tally, the
+stamps, the markers and the finale advance as in the render — and the next clip loaded behind the playing one so
+the cut is near-seamless. A take plays the project's manifest **as it is now** with the take's style patch and its
+own patch (a take's own `timeline` included), from `takes/<id>/take.json` or — not rendered yet — a recipe that
+names it; its pages are composed under `takes/<id>/out/`, never over the project's. `render.blur: "off"` on the
+take plays its blurred clips as recorded.
+
+| | In umtool | Keys |
+|---|---|---|
+| play / pause, ±5 s, previous / next entry, speed (the voice keeps its pitch) | the transport under the picture | Space, ← →, P N |
+| jump to an entry; which clips are not fetched | the list beside the picture (id, date, length) | — |
+| a note at the playhead: the cut second, the clip on screen and its source second, the take (anchor `cut`) | **Note at playhead**, Enter to save; a note's time seeks there | M |
+| the assistant on a note (its reply lands on the note, its edits wait for **Apply all**), or on every open note at once | a note's **Send to the assistant**; **Send all open notes** | — |
+
+What it does not do (the line under the picture says so): each crossfade is a **hard cut at its middle** (where
+the deck hands its title over); cards, teasers and images are **placeholders** with their heading for their
+seconds; the edges are not snapped to silence; the sound is the source's (no room, no Audio knobs); the clock is the
+estimate's (a carrying clip's posts hold included when the cut has a deck). A clip whose source window is not on
+disk is a named placeholder that plays on — fetch it from the Cut tab. **Reload the cut** reads an edit made
+elsewhere.
+
+The notes are the project's `notes.json` ([notes.md](notes.md)): `umtool notes <p>` prints each with its cut second,
+its clip and source, and — for a take — that its patch is the file to edit. **Send to the assistant** is the video
+assistant's ask on a note ([report-video.md](report-video.md)): routed by `settings.generation` (`video-assist`),
+it replies on the note as the agent; with no route the button says why, and the note is still Claude Code's.
+
Then the cut: the Build tab's **final** preset (a full build, about an hour for a 36-clip cut), and Deliver's
**Make variants**.
diff --git a/umtool/docs/notes.md b/umtool/docs/notes.md
@@ -5,7 +5,7 @@
| On | Where in umtool |
|---|---|
| an article (the store's `/articles/<id>`, or a site's `/sites/<site>/<report>`) | the piece's **Article** tab: a passage, a section, a citation, the whole article ([piece.md](piece.md#reading-and-noting-the-article-tab)); a timed note on its video |
-| a report-video project | the **Cut** tab's rows, the clip bench and the clip editor's **Comments** on a clip (`entry`, [report-video.md](report-video.md#reviewing-assistant-clips-the-clip-editor)), the takes bench (`take`), the **Build** tab's final video and a take's preview (`moment`), an edit to a generated manifest (`edit`) |
+| a report-video project | the **Cut** tab's rows, the clip bench and the clip editor's **Comments** on a clip (`entry`, [report-video.md](report-video.md#reviewing-assistant-clips-the-clip-editor)), the takes bench (`take`), the **Build** tab's final video and a take's preview (`moment`), the Play view at the playhead (`cut`), an edit to a generated manifest (`edit`) |
| a song | the song piece's **Notes** tab and the notes beside each cut and file (a song's own `notes.json`, not this store) |
A note is saved where the agent that made the thing can read it back, act on the right SOURCE file, and reply or
@@ -128,6 +128,7 @@ overwritten — fix it by hand first.
| `entry` | `entry` (a timeline entry id) | the entry's title, quote and source span |
| `take` | `take` (a take id) | the take's label and summary, and its verdict |
| `edit` | `entry?`, `field`, `from`, `to` | an edit made in umtool to a GENERATED manifest — port it into the generator's inputs |
+| `cut` | `t` (the cut second), `entry?`, `sourceT?`, `take?` | a note taken in the Play view ([knobs.md](knobs.md#play-the-cut-the-whole-cut-or-a-take-with-no-render)): the cut second, the entry on screen with its source span and the source second there, and for a take its patch as the file to edit |
A text anchor is a quote with 32 characters of context either side (the W3C
TextQuoteSelector), never an offset, so it survives a regenerated `report.json`:
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -41,6 +41,7 @@ import { makeVideoAssistFixture } from "./video-assist-fixture.mjs";
import { makeKnobsFixture } from "./knobs-fixture.mjs";
import { makeMarksFixture } from "./marks-fixture.mjs";
import { makeLivePreviewFixture } from "./live-preview-fixture.mjs";
+import { makePlayCutFixture } from "./play-cut-fixture.mjs";
const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song");
const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song"));
@@ -1833,6 +1834,8 @@ makeKnobsFixture({ reports, manifest, deckManifest, cachedWindow: path.join(REPO
makeMarksFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 });
// The clip editor's live preview and Render this clip (plans/live-preview.md, live-preview.spec.ts).
makeLivePreviewFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
+// The Play view: the whole cut (and a take) played with no render, notes at the playhead (play-cut.spec.ts).
+makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// TWO MORE cached windows for vid1, and they are the regression rather than
// decoration.
diff --git a/umtool/e2e/fixtures/play-cut-fixture.mjs b/umtool/e2e/fixtures/play-cut-fixture.mjs
@@ -0,0 +1,55 @@
+// What play-cut.spec.ts plays (umtool/docs/knobs.md, "Play the cut"): a short deck cut on
+// vid1 (the fixture corpus's synthetic source, its 0-9 s window cached in
+// out/clips-raw), never built -- the Play view plays it from the cached
+// window on the estimate's clock -- with a card between clips, a clip whose
+// source was never fetched (a placeholder, not a stall), and two takes: one
+// made (takes/short/take.json, its own timeline: c04 then c01) and one only
+// a recipe names (quick-joins, a hard-cut look).
+//
+// c01 vid1 1.0-3.0 c02 vid1 3.5-5.5 k01 card 1.5 s
+// c03 nofetch 2-4 (no window on disk) c04 vid1 6.0-8.0
+//
+// Synthetic, like every fixture.
+import { copyFileSync, mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+/**
+ * @param {{ reports: string, deckManifest: Function, cachedWindow: string }} o
+ */
+export function makePlayCutFixture({ reports, deckManifest, cachedWindow }) {
+ const dir = path.join(reports, "play-cut-fixture");
+ mkdirSync(dir, { recursive: true });
+ const timeline = [
+ { type: "clip", id: "c01", video: "vid1", start: 1.0, end: 3.0, cite: 1, lock: true, quote: "This is a complete sentence.", onscreen: { title: "24 Oct 2020" } },
+ { type: "clip", id: "c02", video: "vid1", start: 3.5, end: 5.5, cite: 4, lock: true, quote: "And this one runs on", onscreen: { title: "2 Dec 2024" } },
+ { type: "card", id: "k01", style: "chapter", seconds: 1.5, heading: "Between the clips" },
+ { type: "clip", id: "c03", video: "nofetch", start: 2.0, end: 4.0, cite: 2, lock: true, quote: "never fetched" },
+ { type: "clip", id: "c04", video: "vid1", start: 6.0, end: 8.0, cite: 6, lock: true, quote: "of that it finishes here.", onscreen: { title: "27 Feb 2025" } },
+ ];
+ const m = deckManifest("play-cut-fixture", "The Play Cut Fixture", timeline);
+ m.render.fetchPad = 0;
+ writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n");
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", "vid1_0.00-9.00.mp4"));
+ // A made take with its own timeline (a JSON merge patch replaces the list).
+ mkdirSync(path.join(dir, "takes", "short"), { recursive: true });
+ writeFileSync(
+ path.join(dir, "takes", "short", "take.json"),
+ JSON.stringify(
+ {
+ id: "short", group: "takes", order: 1, label: "Short", kind: "different", summary: "c04 first, then c01",
+ preview: "preview.mp4", window: "full", style: null,
+ patch: { timeline: [timeline[4], timeline[0]] },
+ },
+ null,
+ 2,
+ ) + "\n",
+ );
+ copyFileSync(cachedWindow, path.join(dir, "takes", "short", "preview.mp4"));
+ // A take only a recipe names: never rendered, still playable.
+ writeFileSync(
+ path.join(dir, "takes", "recipe.json"),
+ JSON.stringify({ takes: [{ id: "quick-joins", label: "Quick joins", patch: { render: { transition: 0 } } }] }, null, 2) + "\n",
+ );
+ return { dir };
+}
diff --git a/umtool/e2e/play-cut.spec.ts b/umtool/e2e/play-cut.spec.ts
@@ -0,0 +1,142 @@
+import { test, expect, type Page } from "@playwright/test";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// The Play view (umtool/docs/knobs.md, "Play the cut"): the whole cut played in the browser
+// on one cut clock, no render -- clip 1 plays, the clock carries into clip 2,
+// prev / next / the keys move between entries (a card and an unfetched clip
+// play as placeholders), a note taken at the playhead lists and seeks, and a
+// take plays its own timeline. Fixture: e2e/fixtures/play-cut-fixture.mjs.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const PROJECT = "reports/play-cut-fixture";
+const DIR = path.join(FIXTURE, "reports", "play-cut-fixture");
+
+const root = (page: Page) => page.locator("[data-play-cut]");
+const tNow = async (page: Page) => Number(await root(page).getAttribute("data-play-t"));
+const rows = (page: Page) => page.locator("[data-play-row]");
+
+test.beforeEach(() => {
+ test.setTimeout(120_000);
+});
+
+test("the cut plays clip after clip on one clock; prev / next / keys; placeholders never stall", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ await page.goto(urls.playHref(PROJECT));
+ await expect(root(page)).toHaveAttribute("data-play-state", "paused");
+ await expect(rows(page)).toHaveCount(5);
+ expect(await rows(page).evaluateAll((els) => els.map((e) => e.getAttribute("data-play-row")))).toEqual(["c01", "c02", "k01", "c03", "c04"]);
+ await expect(page.locator('[data-play-row="c03"] [data-play-row-missing]')).toBeVisible();
+ await expect(page.locator('[data-play-row="c01"]')).toHaveAttribute("aria-current", "true");
+ await expect(page.locator("[data-play-approximate]")).toContainText("hard cut");
+
+ // Play: clip 1's media (the bench's raw route) plays, the clock moves.
+ await page.locator("[data-play-toggle]").click();
+ await expect(root(page)).toHaveAttribute("data-play-item", "c01");
+ await expect.poll(() => tNow(page), { timeout: 20_000 }).toBeGreaterThan(0.5);
+ // ...and carries on into clip 2 (c01 is shown to 1.9 s on the estimate's clock).
+ await expect(root(page)).toHaveAttribute("data-play-item", "c02", { timeout: 20_000 });
+ await expect(page.locator('[data-play-row="c02"]')).toHaveAttribute("aria-current", "true");
+ await expect
+ .poll(() => page.locator('video[data-play-slot-item="c02"]').evaluate((v: HTMLVideoElement) => !v.paused && v.readyState >= 2), { timeout: 15_000 })
+ .toBe(true);
+ await expect.poll(() => tNow(page)).toBeGreaterThan(1.9);
+ await page.keyboard.press("Space");
+ await expect(root(page)).toHaveAttribute("data-play-state", "paused");
+
+ // Next: the card, shown as a placeholder from its first second.
+ await page.locator("[data-play-next]").click();
+ await expect(root(page)).toHaveAttribute("data-play-item", "k01");
+ await expect(page.locator('[data-play-placeholder="card"]')).toContainText("Between the clips");
+ expect(await tNow(page)).toBeCloseTo(3.7, 1);
+ // n: the clip whose source was never fetched -- named, not waited on.
+ await page.keyboard.press("n");
+ await expect(root(page)).toHaveAttribute("data-play-item", "c03");
+ await expect(page.locator('[data-play-missing="c03"]')).toContainText("not fetched");
+ // Playing through it: the wall clock carries on to c04.
+ await page.locator("[data-play-toggle]").click();
+ await expect(root(page)).toHaveAttribute("data-play-item", "c04", { timeout: 15_000 });
+ await page.keyboard.press("Space");
+ // p, prev: back an entry at a time.
+ await page.keyboard.press("p");
+ await expect(root(page)).toHaveAttribute("data-play-item", "c03");
+ await page.locator("[data-play-prev]").click();
+ await expect(root(page)).toHaveAttribute("data-play-item", "k01");
+ // ← is 5 s back: from 3.7, the cut's first second.
+ await page.keyboard.press("ArrowLeft");
+ await expect(root(page)).toHaveAttribute("data-play-item", "c01");
+ expect(await tNow(page)).toBe(0);
+ await page.keyboard.press("ArrowRight");
+ await expect(root(page)).toHaveAttribute("data-play-item", "c03");
+ expect(await tNow(page)).toBeCloseTo(5, 1);
+ // A row is a jump.
+ await page.locator('[data-play-row="c02"]').click();
+ await expect(root(page)).toHaveAttribute("data-play-item", "c02");
+ expect(await tNow(page)).toBeCloseTo(1.9, 1);
+});
+
+test("a note at the playhead: anchored to the cut second, the clip and its source second; listed; a click seeks", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ await page.goto(urls.playHref(PROJECT));
+ await expect(root(page)).toHaveAttribute("data-play-state", "paused");
+ await page.locator('[data-play-row="c02"]').click();
+ await page.keyboard.press("ArrowRight"); // 1.9 + 5 = 6.9: c04
+ await expect(root(page)).toHaveAttribute("data-play-item", "c04");
+ await page.keyboard.press("m");
+ const input = page.getByTestId("play-note-input");
+ await expect(input).toBeFocused();
+ await expect(page.locator("[data-play-note-at]")).toHaveAttribute("data-play-note-at", "6.9");
+ await input.fill("start this one later");
+ await input.press("Enter");
+ const note = page.locator("[data-play-note]");
+ await expect(note).toHaveCount(1);
+ await expect(note).toContainText("start this one later");
+ await expect(note.locator("[data-play-note-seek]")).toContainText("0:06.9 · c04");
+ await expect(page.locator("[data-play-send-all]")).toContainText("(1)");
+
+ // Written through the notes store: the cut anchor, the clip, its source second (c04 starts at 6.7 on the clock: 6.0 + 0.2).
+ const doc = JSON.parse(readFileSync(path.join(DIR, "notes.json"), "utf8"));
+ const n = doc.notes.find((x: { text: string }) => x.text === "start this one later");
+ expect(n.anchor).toEqual({ kind: "cut", t: 6.9, entry: "c04", sourceT: 6.2 });
+ expect(n.author).toBe("operator");
+
+ // Elsewhere, then the note's time: back where it was taken.
+ await page.locator('[data-play-row="c01"]').click();
+ await expect(root(page)).toHaveAttribute("data-play-item", "c01");
+ await note.locator("[data-play-note-seek]").click();
+ await expect(root(page)).toHaveAttribute("data-play-item", "c04");
+ expect(await tNow(page)).toBeCloseTo(6.9, 1);
+});
+
+test("a take plays its own timeline (its patch over the project's manifest); a recipe's take plays unrendered", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ // The takes page links each take's Play view.
+ await page.goto(urls.takesHref(PROJECT));
+ await expect(page.locator('a[data-play-take="short"]')).toHaveAttribute("href", urls.playHref(PROJECT, { take: "short" }));
+
+ await page.goto(urls.playHref(PROJECT, { take: "short" }));
+ await expect(root(page)).toHaveAttribute("data-play-cut", "short");
+ await expect(page.locator('[data-play-take="short"]')).toContainText("take “Short”");
+ await expect(rows(page)).toHaveCount(2);
+ expect(await rows(page).evaluateAll((els) => els.map((e) => e.getAttribute("data-play-row")))).toEqual(["c04", "c01"]);
+ await page.locator("[data-play-toggle]").click();
+ await expect(root(page)).toHaveAttribute("data-play-item", "c01", { timeout: 20_000 });
+ // The take's clip came through the raw route with the take named.
+ const src = await page.locator('video[data-play-slot-item="c01"]').getAttribute("src");
+ expect(new URL(String(src), "http://x").searchParams.get("take")).toBe("short");
+ await page.keyboard.press("Space");
+
+ // The recipe's take: listed, not made, playing the project's timeline with its look.
+ await page.locator('[data-play-take-link="quick-joins"]').click();
+ await expect(root(page)).toHaveAttribute("data-play-cut", "quick-joins");
+ await expect(page.locator('[data-play-take="quick-joins"]')).toContainText("not rendered yet");
+ await expect(rows(page)).toHaveCount(5);
+ // A hard-cut look: each entry is its segment, so c02 starts at 2 s, not 1.9.
+ await page.locator('[data-play-row="c02"]').click();
+ expect(await tNow(page)).toBeCloseTo(2, 2);
+});
diff --git a/umtool/lib/annotations/cli.test.mjs b/umtool/lib/annotations/cli.test.mjs
@@ -102,3 +102,31 @@ test("a video project's digest names the generator and lists the takes' verdicts
assert.match(d.text, /- `deck` “Deck first” \(open, similar\): like — keep the beat/);
await rm(root, { recursive: true });
});
+
+test("a note taken in the Play view: the CLI prints its cut second, its clip and source, and the take's patch as the source", async () => {
+ const { root, reports, opts } = await fixture();
+ const proj = path.join(reports, "ws", "polemic-x");
+ // A take with its own timeline: e1 moved later in its recording, and an entry of its own.
+ await mkdir(path.join(proj, "takes", "short-19"), { recursive: true });
+ await writeFile(
+ path.join(proj, "takes", "short-19", "take.json"),
+ JSON.stringify({
+ id: "short-19", group: "takes", order: 1, label: "Short 19", kind: "different", preview: "preview.mp4",
+ patch: { timeline: [{ type: "clip", id: "e1", channel: "ch", video: "v1", start: 12, end: 20, cutStart: 13, cutEnd: 19, quote: "I never said X" }, { type: "card", id: "k9", heading: "The end" }] },
+ }),
+ );
+ const t = await projectTarget("ws/polemic-x", opts);
+ await writeNote(t, { op: "add", text: "Trim the start.", anchor: { kind: "cut", t: 2.5, entry: "e1", sourceT: 12.4 } }, { by: "operator" });
+ await writeNote(t, { op: "add", text: "Card too long.", anchor: { kind: "cut", t: 70.25, entry: "k9", take: "short-19" } }, { by: "operator" });
+ await writeNote(t, { op: "add", text: "Gone take.", anchor: { kind: "cut", t: 1, take: "gone" } }, { by: "operator" });
+ const d = await run(["ws/polemic-x"], opts);
+ assert.equal(d.code, 0, d.text);
+ assert.match(d.text, /\*\*On:\*\* 0:02\.5 of the cut, as the Play view plays it/);
+ assert.match(d.text, /entry `e1` \(clip\) “Denial”\n> I never said X\nsource ch\/v1@10-20, at source 12\.4 s/);
+ assert.match(d.text, /\*\*On:\*\* 1:10\.3 of take `short-19` “Short 19”/);
+ assert.match(d.text, /entry `k9` \(card\) “The end”/);
+ assert.match(d.text, /an edit for this take alone goes in its patch/);
+ assert.match(d.text, /take `gone`: no take gone/);
+ assert.match(d.text, /video\.manifest\.json` is regenerated by/);
+ await rm(root, { recursive: true });
+});
diff --git a/umtool/lib/annotations/digest.mjs b/umtool/lib/annotations/digest.mjs
@@ -13,6 +13,9 @@
// entry the timeline entry's title and quote
// take the take's label and summary, and the operator's verdict on it
// edit what changed, from → to, to port into the generator's inputs
+// cut a moment of the cut as the Play view plays it: the cut second, the
+// take (resolved: the project's manifest + its patches), the entry
+// on screen with its source span and the source second there
//
// A video project's digest also lists every take with its verdict and note
// (takes/verdicts.json): the agent that rendered the takes reads them here.
@@ -20,6 +23,7 @@ import { readFile } from "node:fs/promises";
import path from "node:path";
import { REPORTS_ROOT } from "../paths.mjs";
import { listTakes, readVerdicts } from "../report/takes.mjs";
+import { resolveTakeManifest } from "../report/takeManifest.mjs";
import { locateQuote, sentenceAround } from "./anchor.mjs";
const readJson = (file) => readFile(/* turbopackIgnore: true */ file, "utf8").then(JSON.parse, () => null);
@@ -56,6 +60,12 @@ const clip = (s, n = 300) => {
return t.length > n ? `${t.slice(0, n - 1)}…` : t;
};
const quoteLine = (s) => `> ${clip(s, 400)}`;
+/** `m:ss.s` -- a cut second as the Play view's readout shows it. */
+const cutClock = (t) => {
+ const s = Math.max(0, Number(t) || 0);
+ const m = Math.floor(s / 60);
+ return `${m}:${(s - m * 60).toFixed(1).padStart(4, "0")}`;
+};
const hms = (t) => {
const s = Math.max(0, Math.round(Number(t) || 0));
const h = Math.floor(s / 3600);
@@ -125,6 +135,35 @@ function anchorLines(a, ctx) {
if (t?.summary) lines.push(`summary: ${clip(t.summary, 300)}`);
return lines;
}
+ case "cut": {
+ // The take's manifest (the project's now + its patches) when a take played; else the project's.
+ const m = a.take ? ctx.takeManifests?.get(a.take) ?? null : manifest;
+ const t = a.take ? takes?.find((x) => x.id === a.take) : null;
+ const lines = [
+ `**On:** ${cutClock(a.t)} of ${a.take ? `take \`${a.take}\`${t ? ` “${t.label}”` : ""}` : "the cut"}, as the Play view plays it (the estimated clock, cut seconds; nothing rendered)`,
+ ];
+ if (a.entry) {
+ const e = (m?.timeline ?? []).find((x) => x.id === a.entry);
+ if (!e) lines.push(`entry \`${a.entry}\` (no longer in the ${a.take ? "take's " : ""}manifest)`);
+ else {
+ const title = e.title ?? e.onscreen?.title ?? e.heading;
+ lines.push(`entry \`${a.entry}\` (${e.type ?? "entry"})${title ? ` “${clip(title, 160)}”` : ""}`);
+ if (e.quote) lines.push(quoteLine(e.quote));
+ const channel = e.channel ?? m?.provenance?.channelSlug;
+ if (e.type === "clip" && e.video) {
+ lines.push(`source ${channel ? `${channel}/` : ""}${e.video}@${e.start}-${e.end}${e.cutStart !== undefined ? ` (cut ${e.cutStart}-${e.cutEnd})` : ""}${a.sourceT !== undefined ? `, at source ${a.sourceT} s` : ""}`);
+ }
+ }
+ }
+ if (a.take) {
+ lines.push(
+ ctx.takeErrors?.get(a.take)
+ ? `take \`${a.take}\`: ${ctx.takeErrors.get(a.take)}`
+ : `the take is the project's manifest with its patch (\`takes/${a.take}/take.json\`, or its recipe): an edit for this take alone goes in its patch`,
+ );
+ }
+ return lines;
+ }
case "edit":
return [
`**On:** an edit made in umtool to a GENERATED manifest — port it into the generator's inputs`,
@@ -160,6 +199,7 @@ const STATUS = { open: (n) => n.status === "open", resolved: (n) => n.status !==
export async function digest(entry, { status = "open", reportsRoot = REPORTS_ROOT, projectDir } = {}) {
const lines = [];
const doc = entry.doc;
+ /** @type {{ kind: string, report: any, manifest: any, takes: any, verdicts: any, takeManifests?: Map<string, any>, takeErrors?: Map<string, string> }} */
const ctx = { kind: entry.kind, report: null, manifest: null, takes: null, verdicts: null };
let heading;
if (entry.kind === "article") {
@@ -172,6 +212,16 @@ export async function digest(entry, { status = "open", reportsRoot = REPORTS_ROO
const t = await listTakes(dir);
ctx.takes = t.takes;
ctx.verdicts = await readVerdicts(dir);
+ // A note taken while a take played names its entry in the TAKE's manifest.
+ ctx.takeManifests = new Map();
+ ctx.takeErrors = new Map();
+ for (const take of new Set((doc?.notes ?? []).filter((n) => n.anchor?.kind === "cut" && n.anchor.take).map((n) => n.anchor.take))) {
+ try {
+ ctx.takeManifests.set(take, (await resolveTakeManifest(dir, take)).manifest);
+ } catch (e) {
+ ctx.takeErrors.set(take, e instanceof Error ? e.message : String(e));
+ }
+ }
heading = `# Notes on ${entry.id}${ctx.manifest?.title ? ` — ${ctx.manifest.title}` : ""}`;
}
lines.push(heading, "");
diff --git a/umtool/lib/annotations/shape.mjs b/umtool/lib/annotations/shape.mjs
@@ -15,7 +15,7 @@ export const NOTES_VERSION = 1;
export const NOTE_TEXT_LIMIT = 8000;
export const NOTE_STATUSES = ["open", "resolved", "wontfix"];
export const NOTE_AUTHORS = ["operator", "agent"];
-export const ANCHOR_KINDS = ["text", "cite", "section", "whole", "moment", "entry", "take", "edit"];
+export const ANCHOR_KINDS = ["text", "cite", "section", "whole", "moment", "entry", "take", "edit", "cut"];
export const REPORT_BLOCKS = ["title", "subtitle", "summary", "method"];
const ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
@@ -104,6 +104,28 @@ export function validateAnchor(raw) {
}
return { anchor: out };
}
+ case "cut": {
+ // A moment of the CUT as the Play view plays it (no file: nothing is
+ // rendered) -- the cut second on its clock, the clip on screen and its
+ // source second there, and the take when it was a take that played.
+ const t = Number(a.t);
+ if (!Number.isFinite(t) || t < 0) return { error: "cut anchor needs t ≥ 0" };
+ const out = { kind: "cut", t: Number(t.toFixed(2)) };
+ if (a.entry !== undefined) {
+ if (!short(a.entry, 128) || !ID.test(a.entry)) return { error: "cut entry is not an entry id" };
+ out.entry = a.entry;
+ }
+ if (a.sourceT !== undefined) {
+ const s = Number(a.sourceT);
+ if (!Number.isFinite(s) || s < 0) return { error: "cut sourceT is not a second ≥ 0" };
+ out.sourceT = Number(s.toFixed(2));
+ }
+ if (a.take !== undefined) {
+ if (!isStr(a.take) || !TAKE_ID.test(a.take)) return { error: "cut take is not a take id" };
+ out.take = a.take;
+ }
+ return { anchor: out };
+ }
case "edit": {
if (!short(a.field, 128) || !a.field) return { error: "edit anchor needs a field" };
if (a.entry !== undefined && (!short(a.entry, 128) || !ID.test(a.entry))) return { error: "edit entry is not an entry id" };
diff --git a/umtool/lib/annotations/store.test.mjs b/umtool/lib/annotations/store.test.mjs
@@ -143,6 +143,16 @@ test("anchors: every kind validates; bad ones refuse", () => {
for (const a of bad) assert.ok("error" in validateAnchor(a), JSON.stringify(a));
});
+test("the cut anchor (the Play view): the cut second, the clip and its source second, the take", () => {
+ assert.deepEqual(validateAnchor({ kind: "cut", t: 61.234, entry: "c04", sourceT: 194.256, take: "short-19", bogus: 1 }).anchor, {
+ kind: "cut", t: 61.23, entry: "c04", sourceT: 194.26, take: "short-19",
+ });
+ assert.deepEqual(validateAnchor({ kind: "cut", t: 0 }).anchor, { kind: "cut", t: 0 });
+ for (const a of [{ kind: "cut" }, { kind: "cut", t: -1 }, { kind: "cut", t: 1, take: "Bad Id" }, { kind: "cut", t: 1, entry: "has space" }, { kind: "cut", t: 1, sourceT: -2 }]) {
+ assert.ok("error" in validateAnchor(a), JSON.stringify(a));
+ }
+});
+
async function sitesFixture() {
const root = await tmp();
const sites = path.join(root, "sites");
diff --git a/umtool/lib/annotations/types.ts b/umtool/lib/annotations/types.ts
@@ -40,7 +40,9 @@ export type Anchor =
| { kind: "moment"; file: string; t: number; take?: string; entry?: string; resolved?: MomentResolved }
| { kind: "entry"; entry: string }
| { kind: "take"; take: string }
- | { kind: "edit"; entry?: string; field: string; from: unknown; to: unknown };
+ | { kind: "edit"; entry?: string; field: string; from: unknown; to: unknown }
+ /** A moment of the cut as the Play view plays it: the cut second, the clip and its source second, the take. */
+ | { kind: "cut"; t: number; entry?: string; sourceT?: number; take?: string };
export type AnchorKind = Anchor["kind"];
diff --git a/umtool/lib/decisions.ts b/umtool/lib/decisions.ts
@@ -1,5 +1,5 @@
import { readSong, resolveRendition, songProjectId, thumbAliasesFor } from "./browse";
-import { cutHref as cutPageHref, projectHref } from "./hrefs";
+import { cutHref as cutPageHref, playHref, projectHref } from "./hrefs";
import { cachedLoudness } from "./loudness";
import { DEFAULT_TARGET, loudnessVerdict } from "./loudness-types";
import { buildStatus, readManifest } from "./manifest";
@@ -359,6 +359,8 @@ function anchorLabel(a: { kind: string; [k: string]: unknown }): string {
return `take ${a.take}`;
case "edit":
return `edit ${a.field}${a.entry ? ` on ${a.entry}` : ""}`;
+ case "cut":
+ return `${a.take ? `take ${a.take} ` : "cut "}@ ${Number(a.t).toFixed(1)}s${a.entry ? ` (${a.entry})` : ""}`;
default:
return "whole";
}
@@ -394,7 +396,11 @@ export async function noteDecisions(): Promise<Decision[]> {
projectKind: article ? "article" : ((f as { projectKind?: string }).projectKind ?? "project"),
target: anchorLabel(n.anchor as { kind: string }),
why: `${firstLine(n.text)}${replies}`,
- href: `${page}?note=${encodeURIComponent(n.id)}`,
+ // A note taken in the Play view opens there, on its take.
+ href:
+ !article && n.anchor.kind === "cut"
+ ? playHref(f.id, { take: (n.anchor as { take?: string }).take ?? null, note: n.id })
+ : `${page}?note=${encodeURIComponent(n.id)}`,
severity: "open",
at: Number.isFinite(at) ? at : 0,
});
diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts
@@ -297,6 +297,15 @@ export function clipEditorHref(project: string, q: NoteOpt & { clip?: string; mo
return withQuery(`/projects/${encodePath(project)}/clips`, { ...(q.mode ? { mode: q.mode } : {}), ...(q.clip ? { clip: q.clip } : {}) }, q.note);
}
+/**
+ * The Play view (umtool/docs/knobs.md, "Play the cut"): the whole cut played in the browser
+ * in its final look, no render; `take` plays that take (the project's
+ * manifest with its patches).
+ */
+export function playHref(project: string, q: NoteOpt & { take?: string | null } = {}): string {
+ return withQuery(`/projects/${encodePath(project)}/play`, q.take ? { take: q.take } : {}, q.note);
+}
+
/** The narration script, card by card. */
export function narrationHref(project: string, q: NoteOpt = {}): string {
return withQuery(`/projects/${encodePath(project)}/narration`, {}, q.note);
diff --git a/umtool/lib/pieces/tabs.mjs b/umtool/lib/pieces/tabs.mjs
@@ -171,7 +171,8 @@ export function tabOfSection(name) {
/** Where a note's anchor is drawn: a row's on the Cut, a timed note on the final video on Build. */
export function tabOfNoteAnchor(kind) {
- if (kind === "entry" || kind === "edit") return "cut";
+ // A Play-view note (`cut`) is reached from the Cut tab's Play the cut; its own link opens the Play view.
+ if (kind === "entry" || kind === "edit" || kind === "cut") return "cut";
if (kind === "moment") return "build";
return "overview";
}
diff --git a/umtool/lib/report/onscreen.mjs b/umtool/lib/report/onscreen.mjs
@@ -490,6 +490,17 @@ function serialised(key, fn) {
}
/**
+ * The manifest a preview is composed from: the project's own, or -- the Play
+ * view playing a take -- `project.manifestFile`, the take's merged manifest
+ * written beside the project's (takeManifest.mjs writePlayManifest), with
+ * `project.dir` the take's directory, so its pages are composed under
+ * takes/<id>/out/<variant>/chrome/ and never over the project's.
+ *
+ * @param {{ dir: string, manifestFile?: string }} project
+ */
+const manifestOf = (project) => project.manifestFile ?? manifestPath(project.dir);
+
+/**
* Compose the preview project for a cut from `schedule`. No render.
*
* compose-chrome decides where the project goes; the files route serves
@@ -505,7 +516,7 @@ export async function composeDeckPreview(project, variant, schedule) {
const want = deckPreviewDir(project.dir, variant);
return serialised(want, async () => {
/** @type {Record<string, unknown>} */
- const args = { manifestPath: manifestPath(project.dir), outDir, variant, region: "deck", schedule, preview: true };
+ const args = { manifestPath: manifestOf(project), outDir, variant, region: "deck", schedule, preview: true };
const r = await composeChrome(/** @type {any} */ (args));
if (r?.projDir && path.resolve(r.projDir) !== path.resolve(want)) {
throw new Error(`compose-chrome wrote the preview to ${r.projDir}, not ${want}`);
@@ -530,7 +541,7 @@ export async function composeFeedPreview(project, variant, schedule, { compose =
const want = feedPreviewDir(project.dir, variant);
return serialised(want, async () => {
/** @type {Record<string, unknown>} */
- const args = { manifestPath: manifestPath(project.dir), outDir, variant, region: "feed", schedule, preview: true };
+ const args = { manifestPath: manifestOf(project), outDir, variant, region: "feed", schedule, preview: true };
const r = await compose(/** @type {any} */ (args));
if (r?.projDir && path.resolve(r.projDir) !== path.resolve(want)) {
throw new Error(`compose-chrome wrote the feed preview to ${r.projDir}, not ${want}`);
@@ -555,7 +566,7 @@ export async function composeStampPreview(project, variant, schedule, { compose
const want = stampPreviewDir(project.dir, variant);
return serialised(want, async () => {
/** @type {Record<string, unknown>} */
- const args = { manifestPath: manifestPath(project.dir), outDir, variant, region: "stamp", schedule, preview: true };
+ const args = { manifestPath: manifestOf(project), outDir, variant, region: "stamp", schedule, preview: true };
const r = await compose(/** @type {any} */ (args));
if (r?.projDir && path.resolve(r.projDir) !== path.resolve(want)) {
throw new Error(`compose-chrome wrote the stamps preview to ${r.projDir}, not ${want}`);
@@ -581,7 +592,7 @@ export async function composeFinalePreview(project, variant, schedule, { compose
const want = finalePreviewDir(project.dir, variant);
return serialised(want, async () => {
/** @type {Record<string, unknown>} */
- const args = { manifestPath: manifestPath(project.dir), outDir, variant, region: "finale", schedule, preview: true };
+ const args = { manifestPath: manifestOf(project), outDir, variant, region: "finale", schedule, preview: true };
const r = await compose(/** @type {any} */ (args));
if (r?.projDir && path.resolve(r.projDir) !== path.resolve(want)) {
throw new Error(`compose-chrome wrote the finale preview to ${r.projDir}, not ${want}`);
@@ -640,7 +651,7 @@ export async function composePostsPreview(project, variant, schedule, window, {
return serialised(want, async () => {
/** @type {Record<string, unknown>} */
const args = {
- manifestPath: manifestPath(project.dir),
+ manifestPath: manifestOf(project),
outDir,
variant,
region: "posts",
diff --git a/umtool/lib/report/playCut.mjs b/umtool/lib/report/playCut.mjs
@@ -0,0 +1,143 @@
+// THE PLAY VIEW'S CLOCK (umtool/docs/knobs.md, "Play the cut"): a whole cut -- or a take --
+// played in the browser on ONE continuous cut clock, clip after clip, with the
+// live preview's chrome over it. Pure: no DOM, no React, so the arithmetic is
+// unit-tested (playCut.test.mjs) and the page only applies it.
+//
+// The clock is the estimate's (the same schedule the live preview composes
+// its pages from, deck.mjs estimateSchedule): segment i starts at
+// `segments[i].start` and lasts `duration` (its hold included); consecutive
+// segments overlap by the crossfade. The page plays them as HARD CUTS at the
+// middle of each overlap -- where the deck hands its title over -- so a clip
+// plays from its play window's first source second (its segment's start) to
+// the second at that midpoint, and the next clip enters that far into its
+// own. A clip's source second at cut second t is liveClock.mjs's rule
+// (`seg.start + (src − playWindow.from)`); past its footage (a carrying
+// clip's hold) its last frame holds.
+
+import { clockText, livePlayWindow } from "./liveClock.mjs";
+
+/** @typedef {{ id: string, start: number, duration: number, hold?: number }} Segment */
+/**
+ * @typedef {{
+ * id: string, index: number, type: string,
+ * start: number, end: number, the segment, in the cut's seconds
+ * from: number, to: number, what the page shows of it: midpoint to midpoint
+ * clip: null | { sourceFrom: number, sourceTo: number, playEnd: number, hold: number },
+ * }} PlayItem
+ */
+
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const round = (v) => Math.round(v * 1000) / 1000;
+
+/**
+ * The cut as the page plays it: one item per segment, in the cut's order.
+ * `entries` are the cut's timeline entries (the variant's), matched to the
+ * segments by id; a segment with no entry plays as a placeholder.
+ *
+ * @param {Segment[]} segments
+ * @param {Array<Record<string, any>>} entries
+ * @param {{ leadIn?: number }} [opts]
+ * @returns {{ items: PlayItem[], total: number }}
+ */
+export function playPlan(segments, entries, { leadIn = 0.4 } = {}) {
+ const byId = new Map((entries ?? []).map((e) => [e?.id, e]));
+ const segs = (segments ?? []).filter((s) => s && fin(s.start) && fin(s.duration));
+ const items = segs.map((s, i) => {
+ const e = byId.get(s.id) ?? null;
+ const end = s.start + s.duration;
+ const prev = segs[i - 1];
+ const next = segs[i + 1];
+ // The midpoint of the overlap with each neighbour (a hard cut has none: its start).
+ const from = prev ? Math.min(s.start + Math.max(0, prev.start + prev.duration - s.start) / 2, end) : 0;
+ const to = next ? Math.max(next.start + Math.max(0, end - next.start) / 2, from) : end;
+ let clip = null;
+ if (e?.type === "clip" && fin(e.start) && fin(e.end)) {
+ const pw = livePlayWindow(/** @type {any} */ (e), leadIn);
+ const hold = fin(s.hold) && /** @type {number} */ (s.hold) > 0 ? /** @type {number} */ (s.hold) : 0;
+ clip = { sourceFrom: pw.from, sourceTo: pw.to, playEnd: round(s.start + Math.max(0, pw.to - pw.from)), hold };
+ }
+ return { id: s.id, index: i, type: String(e?.type ?? "entry"), start: round(s.start), end: round(end), from: round(from), to: round(to), clip };
+ });
+ const total = items.length ? items[items.length - 1].end : 0;
+ return { items, total: round(total) };
+}
+
+/** The item on screen at cut second t (the last whose `from` ≤ t); -1 for an empty plan. */
+export function itemIndexAt(plan, t) {
+ const items = plan?.items ?? [];
+ if (!items.length) return -1;
+ if (!fin(t) || t <= items[0].from) return 0;
+ for (let i = items.length - 1; i >= 0; i -= 1) if (t >= items[i].from) return i;
+ return 0;
+}
+
+/**
+ * The SOURCE second a clip item shows at cut second t: its play window's,
+ * clamped into it -- before its footage its first frame, past it (the hold)
+ * its last. null for an item that is not a clip.
+ *
+ * @param {PlayItem} item
+ * @param {number} t
+ */
+export function sourceAt(item, t) {
+ if (!item?.clip || !fin(t)) return null;
+ const c = item.clip;
+ return round(Math.min(c.sourceTo, Math.max(c.sourceFrom, c.sourceFrom + (t - item.start))));
+}
+
+/** The cut second a clip item's source second plays at (the inverse inside its footage). */
+export function cutAtSource(item, src) {
+ if (!item?.clip || !fin(src)) return item?.start ?? 0;
+ return round(item.start + (src - item.clip.sourceFrom));
+}
+
+/** Is cut second t past the clip's footage, in its hold (its last frame shown)? */
+export const inHold = (item, t) => !!item?.clip && fin(t) && t > item.clip.playEnd;
+
+/** The cut second a jump to item i lands on: where the page starts showing it. */
+export const startOf = (plan, i) => plan?.items?.[Math.max(0, Math.min(i, (plan?.items?.length ?? 1) - 1))]?.from ?? 0;
+
+/** How long the page shows an item (its share of the cut, midpoint to midpoint). */
+export const shownSeconds = (item) => round(Math.max(0, (item?.to ?? 0) - (item?.from ?? 0)));
+
+export { clockText };
+
+/** How many characters "Send all open notes" may send (the video assistant's request cap). */
+export const SEND_ALL_MAX = 2000;
+
+/**
+ * "Send all open notes": the open notes taken while playing, in cut order, as
+ * ONE request in words for the video assistant -- each with where it was
+ * taken (the cut second, the clip, the source second), cut to the request's
+ * cap. null when there is nothing open.
+ *
+ * @param {Array<{ status: string, text: string, anchor: { kind: string, t?: number, entry?: string, take?: string, sourceT?: number } }>} notes
+ * @param {{ take?: string | null, max?: number }} [opts]
+ */
+export function cutNotesRequest(notes, { take = null, max = SEND_ALL_MAX } = {}) {
+ const open = (notes ?? [])
+ .filter((n) => n.status === "open" && n.anchor?.kind === "cut" && (n.anchor.take ?? null) === (take ?? null))
+ .sort((a, b) => (a.anchor.t ?? 0) - (b.anchor.t ?? 0));
+ if (!open.length) return null;
+ const head = `Notes taken while playing ${take ? `take ${take}` : "the cut"}, in order:`;
+ const lines = [head];
+ let len = head.length;
+ for (const [i, n] of open.entries()) {
+ const line = `${i + 1}. ${cutPlace(n.anchor)}: ${String(n.text).replace(/\s+/g, " ").trim()}`;
+ if (len + 1 + line.length > max) {
+ const rest = `(${open.length - i} more not sent)`;
+ if (len + 1 + rest.length <= max) lines.push(rest);
+ break;
+ }
+ lines.push(line);
+ len += 1 + line.length;
+ }
+ return lines.join("\n");
+}
+
+/** Where a cut note was taken, in words: "at 1:12.4, in clip c04 (source 194.2 s)". */
+export function cutPlace(a) {
+ const parts = [`at ${clockText(a?.t ?? 0)}`];
+ if (a?.entry) parts.push(`in clip ${a.entry}${fin(a.sourceT) ? ` (source ${Number(a.sourceT).toFixed(1)} s)` : ""}`);
+ return parts.join(", ");
+}
diff --git a/umtool/lib/report/playCut.test.mjs b/umtool/lib/report/playCut.test.mjs
@@ -0,0 +1,126 @@
+// The Play view's clock (playCut.mjs): one cut clock across clips, the hard
+// cut at the middle of each crossfade, a clip's source second at a cut
+// second and back, a carrying clip's hold, cards between clips, and the
+// "Send all open notes" request.
+//
+// Run with: node --test lib/report/playCut.test.mjs
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { estimateSchedule } from "umtool-report-to-video/deck";
+import { liveClock, cutTimeAt } from "./liveClock.mjs";
+import { cutAtSource, cutNotesRequest, cutPlace, inHold, itemIndexAt, playPlan, shownSeconds, sourceAt, startOf } from "./playCut.mjs";
+
+const manifest = (transition = 0.5) => ({
+ slug: "t",
+ provenance: { channelSlug: "c", siteOrigin: "https://archive.example" },
+ render: { width: 1920, height: 1080, fps: 30, transition, chrome: { engine: "hyperframes", layout: "deck", deck: {} } },
+ timeline: [
+ { type: "clip", id: "a", video: "v1", start: 10, end: 14 },
+ // Cut 104–108 inside its extent: the play window starts 0.4 s before the cut.
+ { type: "clip", id: "b", video: "v2", start: 100, end: 130, cutStart: 104, cutEnd: 108 },
+ { type: "card", id: "k", seconds: 3, heading: "A card" },
+ { type: "clip", id: "c", video: "v3", start: 50, end: 53 },
+ ],
+});
+
+test("the plan: one item per segment, midpoint to midpoint, the cut's total", () => {
+ const m = manifest(0.5);
+ const s = estimateSchedule(m);
+ const plan = playPlan(s.segments, m.timeline, { leadIn: 0.4 });
+ assert.deepEqual(plan.items.map((i) => i.id), ["a", "b", "k", "c"]);
+ // a: 4 s from 0; b: 4.4 s from 3.5 (overlap 0.5); k: 3 s from 7.4; c: 3 s from 9.9.
+ assert.deepEqual(plan.items.map((i) => i.start), [0, 3.5, 7.4, 9.9]);
+ assert.equal(plan.total, 12.9);
+ assert.deepEqual(plan.items.map((i) => [i.from, i.to]), [[0, 3.75], [3.75, 7.65], [7.65, 10.15], [10.15, 12.9]]);
+ // The items tile the cut: each shown from where the last stopped.
+ assert.equal(plan.items.reduce((n, i) => n + shownSeconds(i), 0), plan.total);
+ assert.equal(plan.items[2].clip, null);
+ assert.equal(plan.items[2].type, "card");
+ assert.deepEqual(plan.items[1].clip, { sourceFrom: 103.6, sourceTo: 108, playEnd: 7.9, hold: 0 });
+});
+
+test("the clock across clips: the item at t, its source second, and back", () => {
+ const m = manifest(0.5);
+ const plan = playPlan(estimateSchedule(m).segments, m.timeline);
+ assert.equal(itemIndexAt(plan, 0), 0);
+ assert.equal(itemIndexAt(plan, 3.74), 0);
+ assert.equal(itemIndexAt(plan, 3.75), 1);
+ assert.equal(itemIndexAt(plan, 8), 2);
+ assert.equal(itemIndexAt(plan, 99), 3);
+ assert.equal(itemIndexAt({ items: [] }, 1), -1);
+ const [a, b, k, c] = plan.items;
+ // a plays its window second for second; the hard cut lands 0.25 s into b's window.
+ assert.equal(sourceAt(a, 0), 10);
+ assert.equal(sourceAt(a, 3.7), 13.7);
+ assert.equal(sourceAt(b, 3.75), 103.85);
+ assert.equal(cutAtSource(b, 103.85), 3.75);
+ assert.equal(sourceAt(c, 10.15), 50.25);
+ assert.equal(sourceAt(k, 8), null);
+ // The jump targets are where the page starts showing each item.
+ assert.equal(startOf(plan, 1), 3.75);
+ assert.equal(startOf(plan, 9), 10.15);
+ assert.equal(startOf(plan, -1), 0);
+});
+
+test("the clock agrees with the live preview's (liveClock) inside every clip", () => {
+ const m = manifest(0.5);
+ const s = estimateSchedule(m);
+ const plan = playPlan(s.segments, m.timeline);
+ for (const item of plan.items.filter((i) => i.clip)) {
+ const e = m.timeline.find((x) => x.id === item.id);
+ const lc = liveClock(s, /** @type {any} */ (e));
+ assert.ok(lc);
+ for (const t of [item.from, (item.from + item.to) / 2, item.to - 0.01]) {
+ const src = /** @type {number} */ (sourceAt(item, t));
+ assert.ok(Math.abs(cutTimeAt(lc, src).t - t) < 0.002, `${item.id} at ${t}`);
+ }
+ }
+});
+
+test("a hard-cut cut (transition 0): items are the segments themselves", () => {
+ const m = manifest(0);
+ const plan = playPlan(estimateSchedule(m).segments, m.timeline);
+ assert.deepEqual(plan.items.map((i) => [i.from, i.to]), [[0, 4], [4, 8.4], [8.4, 11.4], [11.4, 14.4]]);
+ assert.equal(sourceAt(plan.items[1], 4), 103.6);
+});
+
+test("a carrying clip's hold: its last frame past its footage", () => {
+ const segs = [
+ { id: "a", start: 0, duration: 6, hold: 2 },
+ { id: "b", start: 6, duration: 3 },
+ ];
+ const entries = [
+ { type: "clip", id: "a", video: "v", start: 10, end: 14 },
+ { type: "clip", id: "b", video: "v", start: 20, end: 23 },
+ ];
+ const plan = playPlan(segs, entries);
+ const a = plan.items[0];
+ assert.equal(a.clip?.playEnd, 4);
+ assert.equal(a.clip?.hold, 2);
+ assert.equal(inHold(a, 3.9), false);
+ assert.equal(inHold(a, 5), true);
+ assert.equal(sourceAt(a, 5), 14);
+});
+
+test("Send all open notes: the open notes on this cut (or take), in cut order, with where each was taken", () => {
+ const notes = [
+ { status: "open", text: "too long here", anchor: { kind: "cut", t: 61.2, entry: "c04", sourceT: 194.2 } },
+ { status: "open", text: "start sooner", anchor: { kind: "cut", t: 3.1, entry: "c01" } },
+ { status: "resolved", text: "done", anchor: { kind: "cut", t: 5 } },
+ { status: "open", text: "on the take", anchor: { kind: "cut", t: 9, take: "short-19" } },
+ { status: "open", text: "whole", anchor: { kind: "whole" } },
+ ];
+ assert.equal(
+ cutNotesRequest(notes),
+ "Notes taken while playing the cut, in order:\n1. at 0:03.1, in clip c01: start sooner\n2. at 1:01.2, in clip c04 (source 194.2 s): too long here",
+ );
+ assert.equal(cutNotesRequest(notes, { take: "short-19" }), "Notes taken while playing take short-19, in order:\n1. at 0:09.0: on the take");
+ assert.equal(cutNotesRequest(notes.slice(2, 3)), null);
+ // Over the cap: what does not fit is counted, not cut mid-sentence.
+ const many = Array.from({ length: 50 }, (_, i) => ({ status: "open", text: "x".repeat(60), anchor: { kind: "cut", t: i } }));
+ const req = /** @type {string} */ (cutNotesRequest(many, { max: 400 }));
+ assert.ok(req.length <= 400);
+ assert.match(req, /more not sent\)$/);
+ assert.equal(cutPlace({ t: 0 }), "at 0:00.0");
+});
diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs
@@ -0,0 +1,88 @@
+// THE PLAY VIEW's data (umtool/docs/knobs.md, "Play the cut"): what `/projects/<p>/play`
+// (and `?take=<id>`) plays, read on the server -- the cut's entries in
+// timeline order, each clip's play window and the cached source window its
+// media comes from (the bench's own rule, serve.mjs windowsFor: the widest
+// file holding it, an excerpt of a long recording), the estimate's segments
+// (the clock when the cut has no deck; with a deck the live preview's
+// schedule replaces them, holds included), and the takes it can switch to.
+//
+// Nothing is fetched or cut here: a clip whose source window is not on disk
+// is listed with `media: null` and plays as a placeholder.
+import { DEFAULT_VARIANT, selectVariant } from "umtool-report-to-video/build-video";
+import { deckOn, estimatedDuration, scheduleFrom, transitionOf } from "umtool-report-to-video/deck";
+import { readManifest } from "../projects/report.mjs";
+import { pickWindow, projectCache, windowsFor } from "./serve.mjs";
+import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs";
+
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const text = (v) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim() : "");
+
+/** The words a placeholder shows for an entry that is not a clip (a card, a teaser, an image). */
+export function headingOf(e) {
+ const line = Array.isArray(e?.lines) ? e.lines.map((l) => (typeof l === "string" ? l : text(l?.text))).find(Boolean) : "";
+ return text(e?.heading) || text(e?.title) || text(e?.onscreen?.title) || line || text(e?.text) || String(e?.type ?? "entry");
+}
+
+/**
+ * @param {{ id: string, dir: string }} project
+ * @param {{ take?: string | null }} [opts]
+ */
+export async function playView(project, { take = null } = {}) {
+ const base = await readManifest(project.dir);
+ if (!base) return { error: "this project has no video.manifest.json" };
+ let manifest = base;
+ /** @type {null | { id: string, label: string, summary: string, made: boolean, from: string }} */
+ let takeInfo = null;
+ let note = null;
+ if (take) {
+ try {
+ const r = await resolveTakeManifest(project.dir, take);
+ manifest = r.manifest;
+ takeInfo = { id: r.take.id, label: r.take.label, summary: r.take.summary, made: r.take.made, from: r.take.from };
+ note = r.note;
+ } catch (e) {
+ return { error: e instanceof Error ? e.message : String(e) };
+ }
+ }
+ const selected = selectVariant(manifest, DEFAULT_VARIANT);
+ const render = selected.render ?? {};
+ const timeline = (selected.timeline ?? []).filter((e) => e && typeof e.id === "string");
+ const D = transitionOf(render);
+ const durs = timeline.map((e) => estimatedDuration(e, render, D));
+ const { starts } = scheduleFrom(durs, D);
+ const segments = timeline.map((e, i) => ({ id: e.id, start: Math.round(starts[i] * 1000) / 1000, duration: Math.round(durs[i] * 1000) / 1000 }));
+ const cache = await projectCache(project, manifest);
+ const entries = await Promise.all(
+ timeline.map(async (e) => {
+ if (e.type !== "clip" || !fin(e.start) || !fin(e.end)) return { id: e.id, type: String(e.type ?? "entry"), heading: headingOf(e) };
+ const win = pickWindow(await windowsFor(project, e, cache), null);
+ return {
+ id: e.id,
+ type: "clip",
+ heading: text(e.onscreen?.title) || text(e.title) || text(e.quote) || e.id,
+ date: text(e.date) || text(e.onscreen?.title) || null,
+ quote: text(e.quote) || null,
+ video: String(e.video ?? ""),
+ start: e.start,
+ end: e.end,
+ cutStart: fin(e.cutStart) ? e.cutStart : null,
+ cutEnd: fin(e.cutEnd) ? e.cutEnd : null,
+ blur: e.blur && typeof e.blur === "object" ? e.blur : null,
+ // The window the bench would play: its name for the raw route, and the source second its file starts at.
+ media: win ? { name: win.name, from: win.from, to: win.to } : null,
+ };
+ }),
+ );
+ return {
+ project: project.id,
+ take: takeInfo,
+ note,
+ takes: await playableTakes(project.dir),
+ leadIn: fin(render.leadIn) ? render.leadIn : 0.4,
+ transition: D,
+ blurRendered: render.blur !== "off",
+ deckOn: deckOn(render),
+ segments,
+ entries,
+ };
+}
diff --git a/umtool/lib/report/serve.mjs b/umtool/lib/report/serve.mjs
@@ -23,12 +23,31 @@ import {
readManifest,
} from "../projects/report.mjs";
-export async function resolveClip(projectId, clipId) {
+/**
+ * A request's project and clip, both members of the scan. With `take` (the
+ * Play view playing a take), the clip is the TAKE's -- the project's manifest
+ * with the take's patches (takeManifest.mjs) -- since a take may move a
+ * clip's window or carry a clip of its own.
+ *
+ * @param {string} projectId
+ * @param {string} clipId
+ * @param {{ take?: string | null }} [opts]
+ */
+export async function resolveClip(projectId, clipId, { take = null } = {}) {
const projects = await walkProjects(REPORTS_ROOT);
const project = projects.find((p) => p.id === projectId);
if (!project) return { error: "no such project", status: 404 };
- const manifest = await readManifest(project.dir);
+ let manifest = await readManifest(project.dir);
if (!manifest) return { error: "no manifest", status: 404 };
+ if (take) {
+ try {
+ // Loaded on a take's request only: the take maker's graph stays out of every other route.
+ const { cachedTakeManifest } = await import("./takeManifest.mjs");
+ manifest = (await cachedTakeManifest(project.dir, take)).manifest;
+ } catch (e) {
+ return { error: e instanceof Error ? e.message : String(e), status: 404 };
+ }
+ }
const clip = clipsOf(manifest).find((e) => e.id === clipId);
if (!clip) return { error: "no such clip", status: 404 };
return { project, manifest, clip };
@@ -416,8 +435,20 @@ export const decodeProjectSegment = (seg) => {
};
/** The iframe src for a cut's preview composition. */
-export const deckPreviewSrc = (projectId, variant) =>
- `/api/report/chrome/files/${encodeProjectSegment(projectId)}/${variant}/index.html`;
+/** @type {(projectId: string, variant: string, take?: string | null) => string} */
+export const deckPreviewSrc = (projectId, variant, take = null) =>
+ `${previewBase(projectId, variant, take)}/index.html`;
+
+/**
+ * The files route's prefix for a cut's preview pages: `<project>/<variant>`,
+ * and for a TAKE's (the Play view; composed under takes/<id>/out/<variant>/)
+ * `<project>/<variant>/@take/<id>` -- a segment no preview directory is named.
+ */
+export const TAKE_SEGMENT = "@take";
+/** @param {string} projectId @param {string} variant @param {string | null | undefined} take */
+function previewBase(projectId, variant, take) {
+ return `/api/report/chrome/files/${encodeProjectSegment(projectId)}/${variant}${take ? `/${TAKE_SEGMENT}/${take}` : ""}`;
+}
/**
* Resolve the url segments after `<project>/<variant>/` to a file INSIDE the
@@ -472,8 +503,9 @@ export const feedPreviewDir = (projectDir, variant) =>
path.join(projectDir, "out", variant, "chrome", FEED_PREVIEW);
/** The iframe src for a cut's posts-feed preview composition. */
-export const feedPreviewSrc = (projectId, variant) =>
- `/api/report/chrome/files/${encodeProjectSegment(projectId)}/${variant}/${FEED_PREVIEW}/index.html`;
+/** @type {(projectId: string, variant: string, take?: string | null) => string} */
+export const feedPreviewSrc = (projectId, variant, take = null) =>
+ `${previewBase(projectId, variant, take)}/${FEED_PREVIEW}/index.html`;
// The fact-check STAMPS' preview composition (a schedule that stamps a
// claim): one project for the whole cut, out/<variant>/chrome/stamp-preview/,
@@ -485,8 +517,9 @@ export const stampPreviewDir = (projectDir, variant) =>
path.join(projectDir, "out", variant, "chrome", STAMP_PREVIEW);
/** The iframe src for a cut's fact-check stamps preview composition. */
-export const stampPreviewSrc = (projectId, variant) =>
- `/api/report/chrome/files/${encodeProjectSegment(projectId)}/${variant}/${STAMP_PREVIEW}/index.html`;
+/** @type {(projectId: string, variant: string, take?: string | null) => string} */
+export const stampPreviewSrc = (projectId, variant, take = null) =>
+ `${previewBase(projectId, variant, take)}/${STAMP_PREVIEW}/index.html`;
// The FINALE's preview composition (a schedule with `finale`): one project
// for its window, out/<variant>/chrome/finale-preview/ (compose-chrome names
@@ -499,16 +532,18 @@ export const finalePreviewDir = (projectDir, variant) =>
path.join(projectDir, "out", variant, "chrome", FINALE_PREVIEW);
/** The iframe src for a cut's finale preview composition. */
-export const finalePreviewSrc = (projectId, variant) =>
- `/api/report/chrome/files/${encodeProjectSegment(projectId)}/${variant}/${FINALE_PREVIEW}/index.html`;
+/** @type {(projectId: string, variant: string, take?: string | null) => string} */
+export const finalePreviewSrc = (projectId, variant, take = null) =>
+ `${previewBase(projectId, variant, take)}/${FINALE_PREVIEW}/index.html`;
/** The preview project of the posts window on one segment. */
export const postsPreviewDir = (projectDir, variant, segment) =>
path.join(projectDir, "out", variant, "chrome", `${POSTS_PREVIEW_PREFIX}${segment}`);
/** The iframe src for one posts window's preview composition. */
-export const postsPreviewSrc = (projectId, variant, segment) =>
- `/api/report/chrome/files/${encodeProjectSegment(projectId)}/${variant}/${POSTS_PREVIEW_PREFIX}${encodeURIComponent(segment)}/index.html`;
+/** @type {(projectId: string, variant: string, segment: string, take?: string | null) => string} */
+export const postsPreviewSrc = (projectId, variant, segment, take = null) =>
+ `${previewBase(projectId, variant, take)}/${POSTS_PREVIEW_PREFIX}${encodeURIComponent(segment)}/index.html`;
/**
* Which preview directory a files request is for, and the segments left to
diff --git a/umtool/lib/report/takeManifest.mjs b/umtool/lib/report/takeManifest.mjs
@@ -0,0 +1,160 @@
+// A TAKE'S MANIFEST WITHOUT RENDERING IT (the Play view, umtool/docs/knobs.md, "Play the cut"):
+// the project's manifest as it is NOW with the take's style patch, then its
+// own patch, applied (RFC 7386 merge patches, takeMaker.mjs's order) -- so a
+// take is played in the browser with every edit made to the cut since it was
+// last rendered, and a take a recipe names but nobody has rendered yet plays
+// too.
+//
+// takes/<id>/take.json a made take: its `style` and `patch`
+// takes/recipe.json, a take not made yet: its spec in a recipe
+// takes/all-styles.recipe.json (parseRecipe's shape)
+//
+// A style that is no longer installed falls back to the take's own
+// takes/<id>/video.manifest.json (the manifest it was rendered from), and
+// says so; a take with neither is an error. Nothing here writes but
+// writePlayManifest: `.take-<id>.play.json` beside the project's manifest
+// (so a relative asset in it resolves as the project's do), what the chrome
+// preview composes a take's pages from -- a scratch file, rewritten on every
+// compose, never read by a build.
+import { readFile, stat, writeFile, rename } from "node:fs/promises";
+import path from "node:path";
+import { ALL_STYLES_RECIPE, MANIFEST, RECIPE_FILE, loadMontageStyles, mergePatch, parseRecipe } from "./takeMaker.mjs";
+import { isTakeId, listTakes, parseTake, takesDirOf, TAKE_FILE } from "./takes.mjs";
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+
+async function readJson(file) {
+ try {
+ return JSON.parse(await readFile(/* turbopackIgnore: true */ file, "utf8"));
+ } catch {
+ return null;
+ }
+}
+
+/** Where a take's play manifest is written (beside the project's manifest). */
+export const playManifestPath = (projectDir, id) => path.join(/* turbopackIgnore: true */ projectDir, `.take-${id}.play.json`);
+
+/** The directory a take's preview pages are composed under (`<dir>/out/<variant>/chrome/*-preview`). */
+export const takePlayDir = (projectDir, id) => path.join(takesDirOf(projectDir), id);
+
+/**
+ * A take's spec as the Play view needs it: from takes/<id>/take.json, else
+ * from a recipe. null when no file names it.
+ *
+ * @param {string} projectDir
+ * @param {string} id
+ * @returns {Promise<null | { id: string, label: string, summary: string, style: string | null, patch: Record<string, unknown> | null, made: boolean, from: string }>}
+ */
+export async function takeSpecOf(projectDir, id) {
+ if (!isTakeId(id)) return null;
+ const raw = await readJson(path.join(takesDirOf(projectDir), id, TAKE_FILE));
+ if (raw) {
+ const r = parseTake(id, raw);
+ if (!("error" in r)) {
+ return { id, label: r.take.label, summary: r.take.summary, style: r.take.style, patch: r.take.patch, made: true, from: `takes/${id}/${TAKE_FILE}` };
+ }
+ }
+ for (const name of [RECIPE_FILE, ALL_STYLES_RECIPE]) {
+ const doc = await readJson(path.join(takesDirOf(projectDir), name));
+ if (!doc) continue;
+ let recipe;
+ try {
+ recipe = parseRecipe(doc);
+ } catch {
+ continue;
+ }
+ const spec = recipe.takes.find((t) => t.id === id);
+ if (spec) return { id, label: spec.label, summary: spec.summary, style: spec.style, patch: spec.patch, made: false, from: `takes/${name}` };
+ }
+ return null;
+}
+
+/**
+ * Every take the Play view can play: the made ones (listTakes's order), then
+ * the ones a recipe names that are not made yet.
+ *
+ * @param {string} projectDir
+ * @returns {Promise<Array<{ id: string, label: string, made: boolean }>>}
+ */
+export async function playableTakes(projectDir) {
+ const { takes } = await listTakes(projectDir);
+ const out = takes.map((t) => ({ id: t.id, label: t.label, made: true }));
+ const seen = new Set(out.map((t) => t.id));
+ for (const name of [RECIPE_FILE, ALL_STYLES_RECIPE]) {
+ const doc = await readJson(path.join(takesDirOf(projectDir), name));
+ if (!doc) continue;
+ try {
+ for (const t of parseRecipe(doc).takes) {
+ if (seen.has(t.id)) continue;
+ seen.add(t.id);
+ out.push({ id: t.id, label: t.label, made: false });
+ }
+ } catch {
+ // A recipe that does not parse names no take here; the Takes page says why.
+ }
+ }
+ return out;
+}
+
+/**
+ * The take's manifest: the project's manifest now + the style's patch + the
+ * take's patch. Throws (an Error whose message is the reason) when the take
+ * is not named anywhere or the project has no manifest.
+ *
+ * @param {string} projectDir
+ * @param {string} id
+ * @param {{ styles?: Record<string, { patch: Record<string, unknown> }> | null, base?: Record<string, unknown> | null }} [opts]
+ * @returns {Promise<{ manifest: Record<string, any>, take: NonNullable<Awaited<ReturnType<typeof takeSpecOf>>>, note: string | null }>}
+ */
+export async function resolveTakeManifest(projectDir, id, { styles = null, base = null } = {}) {
+ if (!isTakeId(id)) throw new Error(`"${id}" is not a take id`);
+ const take = await takeSpecOf(projectDir, id);
+ if (!take) throw new Error(`no take ${id} (no takes/${id}/${TAKE_FILE}, and no recipe names it)`);
+ const project = base ?? (await readJson(path.join(projectDir, MANIFEST)));
+ if (!isObj(project)) throw new Error(`the project has no ${MANIFEST}`);
+ let stylePatch = null;
+ let note = null;
+ if (take.style) {
+ const all = styles ?? (await loadMontageStyles()).styles;
+ stylePatch = all[take.style]?.patch ?? null;
+ if (!stylePatch) {
+ // The style is gone: the manifest the take was rendered from, as it was.
+ const frozen = take.made ? await readJson(path.join(takesDirOf(projectDir), id, MANIFEST)) : null;
+ if (!isObj(frozen)) throw new Error(`take ${id}: its style "${take.style}" is not installed, and it has no rendered manifest`);
+ return { manifest: frozen, take, note: `the style "${take.style}" is not installed: playing the manifest the take was rendered from` };
+ }
+ }
+ const manifest = [stylePatch, take.patch].filter(Boolean).reduce((m, p) => mergePatch(m, p), project);
+ if (!isObj(manifest) || !Array.isArray(manifest.timeline)) throw new Error(`take ${id}: the patched manifest has no timeline`);
+ return { manifest: /** @type {Record<string, any>} */ (manifest), take, note };
+}
+
+// One merged manifest per (take, the files it is made from), for the media
+// routes: a <video> asks for its bytes many times over.
+/** @type {Map<string, { key: string, value: Promise<Awaited<ReturnType<typeof resolveTakeManifest>>> }>} */
+const memo = new Map();
+const mtimeOf = (f) => stat(/* turbopackIgnore: true */ f).then((s) => s.mtimeMs, () => 0);
+
+/** resolveTakeManifest, remembered until the project's manifest, the take or a recipe changes. */
+export async function cachedTakeManifest(projectDir, id) {
+ const dir = takesDirOf(projectDir);
+ const key = (
+ await Promise.all([path.join(projectDir, MANIFEST), path.join(dir, id, TAKE_FILE), path.join(dir, RECIPE_FILE), path.join(dir, ALL_STYLES_RECIPE)].map(mtimeOf))
+ ).join("|");
+ const slot = `${projectDir}\0${id}`;
+ const hit = memo.get(slot);
+ if (hit && hit.key === key) return hit.value;
+ const value = resolveTakeManifest(projectDir, id);
+ value.catch(() => memo.delete(slot));
+ memo.set(slot, { key, value });
+ return value;
+}
+
+/** Write a take's play manifest (tmp + rename); returns its path. */
+export async function writePlayManifest(projectDir, id, manifest) {
+ const file = playManifestPath(projectDir, id);
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(tmp, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
+ await rename(tmp, file);
+ return file;
+}
diff --git a/umtool/lib/report/takeManifest.test.mjs b/umtool/lib/report/takeManifest.test.mjs
@@ -0,0 +1,125 @@
+// A take's manifest without rendering it (takeManifest.mjs): the project's
+// manifest now + the style's patch + the take's own, from take.json or a
+// recipe; the frozen manifest when the style is gone; the play manifest.
+//
+// Run with: node --test lib/report/takeManifest.test.mjs
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { cachedTakeManifest, playableTakes, playManifestPath, resolveTakeManifest, takeSpecOf, writePlayManifest } from "./takeManifest.mjs";
+
+const base = () => ({
+ slug: "p",
+ render: { transition: 0.5, blur: "on" },
+ timeline: [
+ { type: "clip", id: "c01", video: "v", start: 1, end: 3 },
+ { type: "clip", id: "c02", video: "v", start: 4, end: 6 },
+ { type: "clip", id: "c03", video: "v", start: 7, end: 9 },
+ ],
+});
+
+async function project() {
+ const dir = await mkdtemp(path.join(tmpdir(), "take-manifest-"));
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(base()));
+ await mkdir(path.join(dir, "takes", "short"), { recursive: true });
+ await writeFile(
+ path.join(dir, "takes", "short", "take.json"),
+ JSON.stringify({
+ id: "short", group: "takes", order: 1, label: "Short", kind: "different", preview: "preview.mp4",
+ style: null,
+ // A take with its own timeline: c03 then c01, uncensored.
+ patch: { render: { blur: "off" }, timeline: [base().timeline[2], base().timeline[0]] },
+ }),
+ );
+ await writeFile(
+ path.join(dir, "takes", "recipe.json"),
+ JSON.stringify({ takes: [{ id: "short", label: "dup" }, { id: "quick-joins", label: "Quick joins", patch: { render: { transition: 0.15 } } }, { id: "styled", label: "Styled", style: "grey" }] }),
+ );
+ return dir;
+}
+
+test("a made take: the project's manifest NOW with its patch (its own timeline)", async () => {
+ const dir = await project();
+ try {
+ const r = await resolveTakeManifest(dir, "short", { styles: {} });
+ assert.deepEqual(r.manifest.timeline.map((e) => e.id), ["c03", "c01"]);
+ assert.equal(r.manifest.render.blur, "off");
+ assert.equal(r.manifest.render.transition, 0.5);
+ assert.equal(r.take.made, true);
+ assert.equal(r.take.from, "takes/short/take.json");
+ assert.equal(r.note, null);
+ // An edit to the project after the take was made is in what plays.
+ const m = base();
+ m.render.transition = 0.3;
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m));
+ assert.equal((await resolveTakeManifest(dir, "short", { styles: {} })).manifest.render.transition, 0.3);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("a take a recipe names, not made yet; a style's patch before the take's", async () => {
+ const dir = await project();
+ try {
+ const r = await resolveTakeManifest(dir, "quick-joins", { styles: {} });
+ assert.equal(r.manifest.render.transition, 0.15);
+ assert.deepEqual(r.manifest.timeline.map((e) => e.id), ["c01", "c02", "c03"]);
+ assert.equal(r.take.made, false);
+ assert.equal(r.take.from, "takes/recipe.json");
+ const s = await resolveTakeManifest(dir, "styled", { styles: { grey: { patch: { render: { grade: "grey" } } } } });
+ assert.equal(s.manifest.render.grade, "grey");
+ // The made take wins over the recipe's line of the same id.
+ assert.equal((await takeSpecOf(dir, "short"))?.label, "Short");
+ assert.deepEqual(await playableTakes(dir), [
+ { id: "short", label: "Short", made: true },
+ { id: "quick-joins", label: "Quick joins", made: false },
+ { id: "styled", label: "Styled", made: false },
+ ]);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("refusals: no such take, a bad id, a gone style with nothing rendered", async () => {
+ const dir = await project();
+ try {
+ await assert.rejects(resolveTakeManifest(dir, "nope", { styles: {} }), /no take nope/);
+ await assert.rejects(resolveTakeManifest(dir, "../x", { styles: {} }), /not a take id/);
+ await assert.rejects(resolveTakeManifest(dir, "styled", { styles: {} }), /style "grey" is not installed/);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("a gone style on a made take: the manifest it was rendered from", async () => {
+ const dir = await project();
+ try {
+ const frozen = { ...base(), slug: "frozen" };
+ await writeFile(path.join(dir, "takes", "short", "video.manifest.json"), JSON.stringify(frozen));
+ const doc = JSON.parse(await readFile(path.join(dir, "takes", "short", "take.json"), "utf8"));
+ await writeFile(path.join(dir, "takes", "short", "take.json"), JSON.stringify({ ...doc, style: "gone" }));
+ const r = await resolveTakeManifest(dir, "short", { styles: {} });
+ assert.equal(r.manifest.slug, "frozen");
+ assert.match(String(r.note), /not installed/);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("the play manifest is written beside the project's; the cache follows the files", async () => {
+ const dir = await project();
+ try {
+ const file = await writePlayManifest(dir, "short", { timeline: [] });
+ assert.equal(file, playManifestPath(dir, "short"));
+ assert.equal(path.dirname(file), dir);
+ assert.deepEqual(JSON.parse(await readFile(file, "utf8")), { timeline: [] });
+ const a = await cachedTakeManifest(dir, "quick-joins");
+ assert.equal(a.manifest.render.transition, 0.15);
+ assert.equal(await cachedTakeManifest(dir, "quick-joins"), a);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});