commit a24a44c7eceddd98ca16795be0f553b3f3a84fc3
parent 41b949da44a4f35001bed5fcca50f86940626ee3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 23 Oct 2026 22:19:08 -0400
Merge lane/play-the-cut: Play the cut — the full-video iteration view (one clock across a cut or a take, the reel strip with the counter's staircase, dailies notes on a cut anchor, send to the assistant)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
36 files changed, 3150 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,26 @@ 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)");
+ assert.equal(cutContextOf({ t: 3, entry: "c01", ask: "trim" }), "(noted while playing the cut at 0:03.0, in clip c01; asks for a trim)");
+ 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,34 @@ 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; ask?: 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";
+ const ask = typeof a.ask === "string" && /^[a-z]{2,8}$/.test(a.ask) && a.ask !== "other" ? `; asks for a ${a.ask}` : "";
+ return `(noted while playing ${take} ${where.join(", ")}${ask})`;
+}
+
+/**
+ * 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 +113,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; ask?: 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 timecoded 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. Under the picture, the **reel strip** shows the whole cut at once: a cell per clip or card as wide as it plays, shaded by the recording's date, hatched when its media is not fetched, the sections' boundaries with their first date, the counter (the tally) drawn as a staircase with its total at the end and at the playhead, and each note as a pin; click or drag on it to move through the cut. Under the strip, **Now** shows what the clip on screen says with the spoken line lit, and which clip comes next. Space plays and pauses, J K L go back, pause and play (L again is faster, at the voice's own pitch), ← and → move 5 seconds, N and P move between clips, [ and ] between notes, and ? lists the keys. 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 says "No media for this clip — fetch it" and the video plays on. M (or **Note at 09:44**) saves a note at that second of the cut, naming the clip on screen, its second in the recording, the take, and what it asks for (Trim, Cut, Move, Fact, Look or Other); playback pauses while you write and goes on when it is saved (**Pause while I write**). The notes list in cut order (open, all or resolved), a timecode plays from there, `umtool notes <project>` prints each with where it was taken and what it asks for, and **Send to the assistant** on a note (or **Send N open notes to the assistant**) 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,52 @@
+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.
+
+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}`}
+ />
+ );
+ 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,60 @@ 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,
+ variant = "go",
+}: {
+ reply: NoteReply;
+ proposals: Proposals | null;
+ busy: boolean;
+ apply: (ids: string[] | null, at?: string) => Promise<boolean>;
+ onApplied: () => void;
+ /** "outline" where the page's one primary action is another (the Play view's Save note). */
+ variant?: "go" | "outline";
+}) {
+ 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, 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 +365,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,1202 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { useSharedNotes } from "@/components/notes/NotesProvider";
+import { NoteThread } from "@/components/notes/NoteThread";
+import type { Anchor, CutAsk, 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 {
+ counterSteps, cutAtSource, cutNotesRequest, itemIndexAt, playPlan, runningTime, seamsOf, 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, routeLine, jobLine, useAssist } from "../report/AssistBox";
+import { DeckFrame, FeedOverlay, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type Rect } from "../OnscreenSection";
+import { drawFootage, type FootageBlur } from "./footageCanvas";
+import ReelStrip, { type StripCounter } from "./ReelStrip";
+
+// ---------------------------------------------------------------------------
+// THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): a screening room. The
+// whole cut -- or a take -- played continuously in this browser in its final
+// look, with no render, and timecoded notes left as it plays that become the
+// next cut.
+//
+// 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 PAGE (the design brief): the player; under it the REEL STRIP
+// (ReelStrip.tsx, the signature: the cut as film, the counter's staircase,
+// the notes' pins, the playhead, the ruler); under that NOW, on the reader
+// surface: what the clip on screen says, the spoken line lit as it plays;
+// beside them the NOTES in reel order. Desk tokens for the tool, the reader
+// for what a source said, SIGNAL for the one interaction colour (the
+// playhead, the pins, Save note), METER for the count.
+//
+// THE NOTES: M (or "Note at 09:44") takes a note anchored to the cut second,
+// the clip on screen and its source second, the take, and what it asks for
+// (Trim, Cut, Move, Fact, Look, Other: the anchor's `ask`) -- the project's
+// notes.json through the notes route. `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;
+ dateKey?: number | null;
+ dateLabel?: string | null;
+ section?: unknown;
+ channel?: 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;
+ title: string;
+ take: { id: string; label: string; summary: string; made: boolean; from: string } | null;
+ note: string | null;
+ takes: { id: string; label: string; made: boolean }[];
+ counter: { verdicts: { id: string; label: string }[]; stamps: { landed: number; verdict: string; count: number }[] };
+ markers: { after: string; label: string }[];
+ 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 };
+type CutAnchor = Extract<Anchor, { kind: "cut" }>;
+
+/** 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;
+/** L, tapped while playing: the next of these. */
+const L_RATES = [1, 1.5, 2, 2.5, 3];
+const SKIP_S = 5;
+/** The player is as wide as leaves the strip and Now on screen under it (never under 480 px). */
+const PLAYER_MAX_W = "max(480px, min(1100px, calc((100dvh - 430px) * 16 / 9)))";
+const PAUSE_KEY = "umtool.play.pauseWhileWriting";
+
+/** The dailies' kinds of note: what it asks for, and its key (with Alt, in the composer). */
+const ASKS: { id: CutAsk; label: string; key: string }[] = [
+ { id: "trim", label: "Trim", key: "t" },
+ { id: "cut", label: "Cut", key: "c" },
+ { id: "move", label: "Move", key: "m" },
+ { id: "fact", label: "Fact", key: "f" },
+ { id: "look", label: "Look", key: "l" },
+ { id: "other", label: "Other", key: "o" },
+];
+
+const KEYS: { keys: string; what: string }[] = [
+ { keys: "Space", what: "play / pause" },
+ { keys: "J", what: "back 5 s (tap again: further)" },
+ { keys: "K", what: "pause" },
+ { keys: "L", what: "play (tap again: 1.5×, 2×, …)" },
+ { keys: "← →", what: "5 s back / on" },
+ { keys: "P N", what: "previous / next clip" },
+ { keys: "[ ]", what: "previous / next note" },
+ { keys: "M", what: "note at the playhead" },
+ { keys: "Alt+T C M F L O", what: "the note's kind, while writing" },
+ { keys: "Enter", what: "save the note (Shift+Enter: a new line)" },
+ { keys: "Esc", what: "close the note, or this" },
+ { keys: "?", what: "these keys" },
+];
+
+const APPROXIMATE =
+ "Approximate: crossfades are hard cuts at their middle, cards and teasers are placeholders, edges are not snapped to silence, the sound is the recording's own, the clock is the estimate's."
+
+/** `mm:ss.s` -- a note's or the playhead's timecode. */
+const timecode = (t: number) => `${runningTime(t)}.${Math.floor(((Math.max(0, t) % 1) + 1e-9) * 10)}`;
+
+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: string; el: HTMLCanvasElement | null }>({ key: "", el: null });
+ 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}` : ""}`;
+ // A new canvas (the composed frame replacing the plain one) is drawn even while nothing moves.
+ if (key === lastDraw.current.key && el === lastDraw.current.el) return;
+ lastDraw.current = { key, el };
+ 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]);
+ const changeRate = useCallback((r: number) => setRate(r), []);
+ // J tapped again within a moment steps further back each time (there is no true reverse).
+ const jTap = useRef({ at: 0, step: SKIP_S });
+ const back = useCallback(() => {
+ const now = performance.now();
+ jTap.current.step = now - jTap.current.at < 800 ? Math.min(60, jTap.current.step * 2) : SKIP_S;
+ jTap.current.at = now;
+ skip(-jTap.current.step);
+ }, [skip]);
+ const lPlay = useCallback(() => {
+ if (!eng.current.playing) {
+ setPlaying(true);
+ return;
+ }
+ const up = L_RATES.find((r) => r > eng.current.rate + 1e-6);
+ if (up) changeRate(up);
+ }, [setPlaying, changeRate]);
+
+ // ---- 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 CutAnchor).t - (b.anchor as CutAnchor).t),
+ [notes.notes, take],
+ );
+ const [drafting, setDrafting] = useState<CutAnchor | null>(null);
+ const [pauseWhileWriting, setPauseWhileWriting] = useState(true);
+ useEffect(() => {
+ try {
+ if (window.localStorage.getItem(PAUSE_KEY) === "off") setPauseWhileWriting(false);
+ } catch {
+ // No storage: on, the default.
+ }
+ }, []);
+ const resumeAfter = useRef(false);
+ const noteHere = useCallback(() => {
+ const e = eng.current;
+ const item = planRef.current.items[e.cur];
+ if (!item) return;
+ resumeAfter.current = false;
+ if (pauseWhileWriting && e.playing) {
+ resumeAfter.current = true;
+ 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 } : {}) });
+ }, [pauseWhileWriting, setPlaying, take]);
+ const closeDraft = useCallback(() => {
+ setDrafting(null);
+ if (resumeAfter.current) {
+ resumeAfter.current = false;
+ setPlaying(true);
+ }
+ }, [setPlaying]);
+ const stepNote = useCallback(
+ (d: 1 | -1) => {
+ const t = eng.current.t;
+ const ts = mine.map((n) => (n.anchor as CutAnchor).t);
+ const to = d > 0 ? ts.find((x) => x > t + 0.05) : [...ts].reverse().find((x) => x < t - 0.05);
+ if (to !== undefined) seekTo(to);
+ },
+ [mine, seekTo],
+ );
+
+ // `?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 CutAnchor).t);
+ }, [initialNote, mine, seekTo]);
+
+ // ---- the keys ----------------------------------------------------------------------
+ const [help, setHelp] = useState(false);
+ useEffect(() => {
+ const onKey = (ev: KeyboardEvent) => {
+ const tgt = ev.target as HTMLElement | null;
+ if (ev.key === "Escape") {
+ if (help) setHelp(false);
+ return;
+ }
+ if (tgt && (tgt.closest("input, textarea, select, [contenteditable=true]") || ev.metaKey || ev.ctrlKey || ev.altKey)) return;
+ const k = ev.key;
+ if (k === " ") setPlaying(!eng.current.playing);
+ else if (k === "j" || k === "J") back();
+ else if (k === "k" || k === "K") setPlaying(false);
+ else if (k === "l" || k === "L") lPlay();
+ else if (k === "n" || k === "N") next();
+ else if (k === "p" || k === "P") prev();
+ else if (k === "ArrowRight") skip(SKIP_S);
+ else if (k === "ArrowLeft") skip(-SKIP_S);
+ else if (k === "[") stepNote(-1);
+ else if (k === "]") stepNote(1);
+ else if (k === "m" || k === "M") noteHere();
+ else if (k === "?") setHelp((h) => !h);
+ 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);
+ };
+ }, [back, help, lPlay, next, prev, skip, stepNote, 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}%`;
+
+ // The reel strip's counter: the composed schedule's stamps when there is one, else the estimate's.
+ const counters = useMemo<StripCounter[]>(() => {
+ const stamps = (schedule?.factcheck?.stamps as { landed: number; verdict: string; count?: number }[] | undefined) ?? view.counter.stamps;
+ const labels = new Map(view.counter.verdicts.map((v) => [v.id, v.label]));
+ const ids = [...new Set(stamps.map((s) => s.verdict))];
+ return ids.map((id) => ({ id, label: doc?.verdictLabels?.[id] ?? labels.get(id) ?? id, steps: counterSteps(stamps, id) }));
+ }, [schedule, view.counter, doc?.verdictLabels]);
+ const seams = useMemo(() => seamsOf(view.entries, view.markers), [view.entries, view.markers]);
+ const pins = useMemo(() => mine.map((n) => ({ id: n.id, t: (n.anchor as CutAnchor).t, text: n.text, open: n.status === "open" })), [mine]);
+ const stripEntries = useMemo(() => new Map(view.entries.map((e) => [e.id, e])), [view.entries]);
+
+ 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.5 p-6 text-center"
+ style={{ background: placeholder.kind === "card" ? bg : "transparent" }}
+ >
+ {placeholder.kind === "card" ? (
+ <>
+ <span className="micro text-white/60">{placeholder.item.type}</span>
+ <span className="max-w-[80%] font-display text-[clamp(15px,2.6vw,32px)] font-semibold text-white">{placeholder.entry?.heading ?? placeholder.item.id}</span>
+ <span className="text-[11px] text-white/55">a placeholder: the build draws it</span>
+ </>
+ ) : (
+ <span className="rounded-[3px] bg-black/75 px-2.5 py-1 text-[12.5px] text-white">
+ {broken ? `${failed[placeholder.item.id]} — ${placeholder.item.id} plays on as a placeholder` : `No media for ${placeholder.item.id} — fetch it`}
+ <span className="mt-0.5 block font-mono text-[11px] text-white/60">
+ {placeholder.entry?.video}@{placeholder.entry?.start}–{placeholder.entry?.end}
+ </span>
+ </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} />
+ );
+ const iconBtn = cn(buttonVariants({ variant: "outline", size: "sm" }), "min-w-9 font-mono");
+
+ 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="flex flex-col min-[900px]:min-h-0 min-[900px]:flex-1 min-[900px]:overflow-hidden"
+ >
+ {/* ---- the head: the cut's title, what plays, the running time ---- */}
+ <header className="flex flex-wrap items-center gap-x-4 gap-y-1.5 border-b border-seam px-4 py-2">
+ <h1 className="m-0 min-w-0 truncate font-display text-[17px] font-semibold tracking-[-0.01em] text-text">{view.title}</h1>
+ <nav aria-label="What plays" className="flex flex-wrap items-center rounded-[3px] border border-seam-2 p-0.5 text-[12px]" data-play-takes="">
+ {[{ id: null as string | null, label: "The cut", made: true }, ...view.takes].map((tk) => {
+ const on = (tk.id ?? null) === take;
+ return (
+ <Link
+ key={tk.id ?? "cut"}
+ href={playHref(project, { take: tk.id })}
+ aria-current={on ? "page" : undefined}
+ data-play-take-link={tk.id ?? ""}
+ title={tk.id ? `${tk.label}${tk.made ? "" : " (not rendered yet)"}` : "the project's cut"}
+ className={cn("rounded-[2px] px-2 py-0.5", on ? "bg-panel-2 font-medium text-text" : "text-muted-2 hover:text-text", !tk.made && "italic")}
+ >
+ {tk.id ?? "The cut"}
+ </Link>
+ );
+ })}
+ </nav>
+ <span className="ml-auto font-mono text-[15px] tabular-nums text-text" data-play-clock="">
+ {runningTime(t)} <span className="text-muted">/ {runningTime(plan.total)}</span>
+ </span>
+ <button type="button" onClick={() => setHelp(true)} className={iconBtn} aria-label="keys" title="keys (?)" data-play-help="">
+ ?
+ </button>
+ </header>
+ {view.take && (
+ <p className="m-0 border-b border-seam px-4 py-1 text-[11.5px] text-text-2" data-play-take={view.take.id}>
+ take “{view.take.label}”: the project’s cut with its patch ({view.take.from}){view.take.made ? "" : " — not rendered yet"}
+ {view.take.summary ? ` · ${view.take.summary}` : ""}
+ </p>
+ )}
+
+ <div className="grid grid-cols-1 min-[900px]:min-h-0 min-[900px]:flex-1 min-[900px]:grid-cols-[minmax(0,1fr)_minmax(300px,380px)]">
+ <main className="deck-main min-w-0 space-y-3 p-4 min-[900px]:min-h-0 min-[900px]:overflow-auto">
+ {/* ---- the player ----
+ The two <video>s sit full size UNDER the frame (which is opaque
+ and drawn from them): an element the browser can see on the
+ page loads and decodes a paused frame, where a hidden 1 px one
+ was left at its metadata. They stay put while the frame above
+ switches from plain to composed. */}
+ <div className="relative w-full" style={{ maxWidth: PLAYER_MAX_W }}>
+ <div className="pointer-events-none absolute inset-0 overflow-hidden" aria-hidden>
+ <video ref={vA} data-play-slot="0" preload="auto" playsInline onError={() => onMediaError(0)} className="absolute inset-0 h-full w-full" />
+ <video ref={vB} data-play-slot="1" preload="auto" playsInline onError={() => onMediaError(1)} className="absolute inset-0 h-full w-full" />
+ </div>
+ <div className="relative">
+ {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-seam bg-black" style={{ aspectRatio: "16 / 9" }} data-testid="play-plain">
+ {footageCanvas({ inset: 0, width: "100%", height: "100%" }, 1280, 720)}
+ {placeholderCard}
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* ---- the transport ---- */}
+ <div className="flex flex-wrap items-center gap-1.5 text-[12px]" data-play-transport="">
+ <button type="button" data-play-prev="" onClick={prev} className={iconBtn} title="previous clip (P)" aria-label="previous clip">
+ ‹ Prev
+ </button>
+ <button type="button" data-play-back="" onClick={() => skip(-SKIP_S)} className={iconBtn} title="back 5 s (←, J)">
+ −5
+ </button>
+ <button type="button" data-play-toggle="" onClick={() => setPlaying(!ui.playing)} className={cn(iconBtn, "min-w-20")} title="play / pause (Space)">
+ {ui.playing ? "Pause" : ui.ended ? "Play again" : "Play"}
+ </button>
+ <button type="button" data-play-fwd="" onClick={() => skip(SKIP_S)} className={iconBtn} title="on 5 s (→)">
+ +5
+ </button>
+ <button type="button" data-play-next="" onClick={next} className={iconBtn} title="next clip (N)" aria-label="next clip">
+ Next ›
+ </button>
+ <label className="ml-1 inline-flex items-center gap-1 text-muted-2">
+ <span className="sr-only">speed</span>
+ <select data-play-rate="" value={rate} onChange={(e) => changeRate(Number(e.target.value))} className="rounded-[3px] border border-seam-2 bg-ground px-1 py-[3px] font-mono text-[12px] text-text" title="speed (L while playing); the voice keeps its pitch">
+ {RATES.map((r) => (
+ <option key={r} value={r}>
+ {r}×
+ </option>
+ ))}
+ </select>
+ </label>
+ {item && (
+ <span className="min-w-0 truncate font-mono text-[11.5px] text-muted" data-play-readout="">
+ {ui.cur + 1}/{plan.items.length} · {item.id}
+ </span>
+ )}
+ {ui.waiting && <span className="text-[11.5px] text-muted" data-play-waiting="">loading…</span>}
+ <span className="ml-auto flex flex-wrap items-center gap-x-2 text-[11.5px] text-muted" data-play-hud="">
+ {tally.length > 0 && <span className="sr-only" data-play-tally={tally.map((r) => `${r.verdict}:${r.count}`).join(",")} />}
+ {schedule?.factcheck && (
+ <span data-play-stamp={stamp ? `${stamp.claim}:${stamp.phase}` : ""}>{stamp ? `stamp ${stamp.claim}` : ""}</span>
+ )}
+ {finaleNow && <span data-play-finale-up="">finale</span>}
+ {composeState === "composing" && <span>composing the chrome…</span>}
+ {composeState === "no-deck" && <span>no on-screen deck: the footage alone</span>}
+ </span>
+ </div>
+ {composeState === "error" && (
+ <p role="alert" className="m-0 text-[11.5px] text-reject-text" data-play-compose-error="">
+ The chrome did not compose: {composeError}. The footage plays without it; Recompose after fixing the cut.
+ </p>
+ )}
+ {doc?.finale?.error && <p className="m-0 text-[11.5px] text-reject-text">The finale did not compose: {doc.finale.error}</p>}
+
+ {/* ---- the reel strip ---- */}
+ <ReelStrip
+ items={plan.items}
+ total={plan.total}
+ entries={stripEntries}
+ t={t}
+ cur={ui.cur}
+ seams={seams}
+ counters={counters}
+ pins={pins}
+ failed={failed}
+ timecode={timecode}
+ onSeek={seekTo}
+ onSeekItem={(i) => seekTo(startOf(planRef.current, i))}
+ />
+
+ {/* ---- now ---- */}
+ <NowReader project={project} item={item} entry={entry ?? null} t={t} next={plan.items[ui.cur + 1] ?? null} nextEntry={plan.items[ui.cur + 1] ? (entryOf.get(plan.items[ui.cur + 1].id) ?? null) : null} broken={broken} />
+
+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1 text-[11px] text-muted" data-play-approximate="">
+ <span>
+ {APPROXIMATE}
+ {!view.blurRendered ? " Blurred clips play unblurred (render.blur off)." : ""}
+ {view.note ? ` ${view.note}.` : ""}
+ </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"
+ onClick={() => {
+ router.refresh();
+ if (view.deckOn) void compose();
+ }}
+ >
+ Reload the cut
+ </button>
+ </div>
+ </main>
+
+ {/* ---- the notes ---- */}
+ <aside className="flex min-h-0 flex-col border-t border-seam bg-panel min-[900px]:border-l min-[900px]:border-t-0" data-play-side="">
+ <PlayNotes
+ project={project}
+ take={take}
+ notes={notes}
+ mine={mine}
+ drafting={drafting}
+ nowLabel={timecode(t)}
+ pauseWhileWriting={pauseWhileWriting}
+ onPauseWhileWriting={(on) => {
+ setPauseWhileWriting(on);
+ try {
+ window.localStorage.setItem(PAUSE_KEY, on ? "on" : "off");
+ } catch {
+ // A preference, not state.
+ }
+ }}
+ onNote={noteHere}
+ onClose={closeDraft}
+ onSeek={(n) => seekTo((n.anchor as CutAnchor).t)}
+ onApplied={() => {
+ router.refresh();
+ if (view.deckOn) void compose();
+ }}
+ />
+ </aside>
+ </div>
+
+ {help && (
+ <div role="dialog" aria-modal="true" aria-label="Keys" className="fixed inset-0 z-50 flex items-center justify-center bg-black/55 p-4" onClick={() => setHelp(false)} data-play-keys="">
+ <div className="w-full max-w-[420px] rounded-[3px] border border-seam-2 bg-panel p-4 text-[12.5px] text-text-2" onClick={(e) => e.stopPropagation()}>
+ <div className="mb-2 flex items-center">
+ <h2 className="micro m-0">Keys</h2>
+ <button type="button" autoFocus onClick={() => setHelp(false)} className={cn(buttonVariants({ variant: "quiet", size: "sm" }), "ml-auto")}>
+ Close
+ </button>
+ </div>
+ <dl className="m-0 grid grid-cols-[auto_1fr] gap-x-4 gap-y-1">
+ {KEYS.map((k) => (
+ <div key={k.keys} className="contents">
+ <dt className="font-mono text-text">{k.keys}</dt>
+ <dd className="m-0">{k.what}</dd>
+ </div>
+ ))}
+ </dl>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// NOW: what the clip on screen says, on the reader (paper is the record), its
+// spoken line lit as it plays; what comes next. A card is our words: the desk.
+// ---------------------------------------------------------------------------
+
+type Cue = { start: number; end: number; text: string };
+const cueCache = new Map<string, Promise<Cue[] | null>>();
+
+function NowReader({
+ project,
+ item,
+ entry,
+ t,
+ next,
+ nextEntry,
+ broken,
+}: {
+ project: string;
+ item: ReturnType<typeof playPlan>["items"][number] | null;
+ entry: PlayEntry | null;
+ t: number;
+ next: ReturnType<typeof playPlan>["items"][number] | null;
+ nextEntry: PlayEntry | null;
+ broken: boolean;
+}) {
+ const [cues, setCues] = useState<{ key: string; cues: Cue[] | null } | null>(null);
+ const clip = item?.clip ?? null;
+ const key = clip && entry?.video ? `${entry.channel ?? ""}|${entry.video}|${clip.sourceFrom}|${clip.sourceTo}` : null;
+ useEffect(() => {
+ if (!key || !clip || !entry?.video) return;
+ let live = true;
+ if (!cueCache.has(key)) {
+ const q = new URLSearchParams({ project, video: entry.video, from: String(clip.sourceFrom), to: String(clip.sourceTo), ...(entry.channel ? { channel: entry.channel } : {}) });
+ cueCache.set(
+ key,
+ fetch(`/api/report/cues?${q}`, { cache: "no-store" })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((j: { cues?: Cue[] } | null) => j?.cues ?? null)
+ .catch(() => null),
+ );
+ }
+ void cueCache.get(key)!.then((c) => {
+ if (live) setCues({ key, cues: c });
+ });
+ return () => {
+ live = false;
+ };
+ }, [key, project, clip, entry?.video, entry?.channel]);
+ const src = item && clip ? sourceAt(item, t) : null;
+ const list = cues?.key === key ? (cues.cues ?? []) : [];
+ const lit = src === null ? -1 : list.findIndex((c) => src >= c.start && src < c.end);
+ const box = useRef<HTMLDivElement | null>(null);
+ useEffect(() => {
+ const el = box.current?.querySelector<HTMLElement>("[data-lit]");
+ const b = box.current;
+ if (el && b) b.scrollTop = Math.max(0, el.offsetTop - b.clientHeight / 3);
+ }, [lit, key]);
+ if (!item) return null;
+ const nextLine = next ? (
+ <p className="m-0 text-[11.5px]" data-play-next-up={next.id}>
+ next: <span className="font-mono">{next.id}</span>
+ {nextEntry?.dateLabel ? ` · ${nextEntry.dateLabel}` : next.clip ? "" : ` · ${next.type}`}
+ </p>
+ ) : (
+ <p className="m-0 text-[11.5px]">the end of the cut</p>
+ );
+
+ if (!clip) {
+ return (
+ <section data-play-now={item.id} className="rounded-[3px] border border-seam bg-panel px-3.5 py-2.5 text-text-2">
+ <p className="m-0 font-mono text-[11.5px] text-muted">
+ {item.id} · {item.type}
+ </p>
+ <p className="m-0 mt-1 text-[14px] text-text">{entry?.heading}</p>
+ <div className="mt-2 text-muted">{nextLine}</div>
+ </section>
+ );
+ }
+ return (
+ <section data-play-now={item.id} className="reader rounded-[2px]">
+ <header className="flex flex-wrap items-baseline gap-x-2 border-b border-reader-seam px-3.5 py-1.5">
+ <span className="font-mono text-[12px] font-medium">{item.id}</span>
+ {entry?.dateLabel && <span className="text-[12px] text-reader-2">{entry.dateLabel}</span>}
+ {entry?.video && <span className="font-mono text-[11px] text-reader-dim">{entry.video}</span>}
+ {(!entry?.media || broken) && <span className="text-[11.5px] text-reader-dim">· No media for this clip — fetch it</span>}
+ </header>
+ <div ref={box} className="relative max-h-[124px] overflow-auto py-1.5 font-serif text-[14.5px] leading-[1.45]" data-play-words="">
+ {list.length > 0 ? (
+ list.map((c, i) => (
+ <div key={`${c.start}-${i}`} className="lit-line reader-cue" data-lit={i === lit ? "" : undefined} data-play-cue={c.start}>
+ <span className="reader-t">{runningTime(c.start)}</span>
+ <span>{c.text}</span>
+ </div>
+ ))
+ ) : (
+ <p className="m-0 px-3.5 py-1 text-reader-2">{entry?.quote ? `“${entry.quote}”` : "No transcript for this recording."}</p>
+ )}
+ </div>
+ <div className="border-t border-reader-seam px-3.5 py-1.5 text-reader-dim">{nextLine}</div>
+ </section>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// THE NOTES, in reel order: the composer at the playhead (kind chips, Save
+// note), Open / All / Resolved, each note's timecode a seek, the assistant
+// on a note or on every open one, its proposals Applied only on a click.
+// ---------------------------------------------------------------------------
+
+type Filter = "open" | "all" | "resolved";
+
+function PlayNotes({
+ project,
+ take,
+ notes,
+ mine,
+ drafting,
+ nowLabel,
+ pauseWhileWriting,
+ onPauseWhileWriting,
+ onNote,
+ onClose,
+ onSeek,
+ onApplied,
+}: {
+ project: string;
+ take: string | null;
+ notes: ReturnType<typeof useSharedNotes>;
+ mine: Note[];
+ drafting: CutAnchor | null;
+ nowLabel: string;
+ pauseWhileWriting: boolean;
+ onPauseWhileWriting: (on: boolean) => void;
+ onNote: () => void;
+ onClose: () => 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 [filter, setFilter] = useState<Filter>("open");
+ const [opened, setOpened] = useState<Record<string, boolean>>({});
+ const blocked = !a.view ? "Reading how the assistant is routed…" : a.view.route?.why ? `${a.view.route.why}.` : !a.view.route ? "The assistant needs the editor, and it did not answer." : 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 resolved = mine.filter((n) => n.status !== "open");
+ const shown = filter === "open" ? open : filter === "resolved" ? resolved : mine;
+ 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 askOf = (n: Note) => (n.anchor as CutAnchor).ask;
+ const head = (n: Note) => {
+ const an = n.anchor as CutAnchor;
+ const ask = ASKS.find((x) => x.id === an.ask);
+ return (
+ <>
+ <button type="button" data-play-note-seek={an.t} onClick={() => onSeek(n)} className="shrink-0 font-mono text-[11.5px] text-signal-text hover:underline" title="play from here">
+ {timecode(an.t)}
+ </button>
+ {an.entry && <span className="shrink-0 font-mono text-[11px] text-muted">{an.entry}</span>}
+ {ask && (
+ <span className="shrink-0 rounded-[2px] border border-seam-2 px-1 text-[10.5px] leading-[15px] text-text-2" data-play-note-ask={ask.id}>
+ {ask.label.toLowerCase()}
+ </span>
+ )}
+ </>
+ );
+ };
+ const count = (f: Filter) => (f === "open" ? open.length : f === "resolved" ? resolved.length : mine.length);
+
+ return (
+ <section data-play-notes={mine.length} className="flex min-h-0 flex-1 flex-col">
+ <div className="space-y-2 border-b border-seam p-3">
+ {drafting ? (
+ <Composer anchor={drafting} busy={notes.busy} onCancel={onClose} onSave={async (text, ask) => {
+ const n = await notes.write({ op: "add", text, anchor: { ...drafting, ...(ask ? { ask } : {}) } });
+ if (n) onClose();
+ }} />
+ ) : (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
+ <button type="button" data-play-note-add="" onClick={onNote} className={cn(buttonVariants({ variant: "outline", size: "sm" }), "font-mono")} title="note this moment (M)">
+ Note at {nowLabel}
+ </button>
+ <label className="inline-flex items-center gap-1.5 text-[11.5px] text-text-2">
+ <input type="checkbox" data-play-pause-writing="" checked={pauseWhileWriting} onChange={(e) => onPauseWhileWriting(e.target.checked)} />
+ Pause while I write
+ </label>
+ </div>
+ )}
+ </div>
+
+ <div className="flex items-center gap-2 px-3 pt-2.5">
+ <h2 className="micro m-0">Notes{take ? ` · ${take}` : ""}</h2>
+ <div role="tablist" aria-label="Which notes" className="ml-auto flex rounded-[3px] border border-seam-2 p-0.5 text-[11.5px]">
+ {(["open", "all", "resolved"] as Filter[]).map((f) => (
+ <button
+ key={f}
+ type="button"
+ role="tab"
+ aria-selected={filter === f}
+ data-play-note-filter={f}
+ onClick={() => setFilter(f)}
+ className={cn("rounded-[2px] px-1.5 py-px capitalize", filter === f ? "bg-panel-2 text-text" : "text-muted-2 hover:text-text")}
+ >
+ {f} <span className="font-mono">{count(f)}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <ol className="m-0 min-h-0 flex-1 list-none space-y-2.5 overflow-auto p-3" data-play-note-list="">
+ {!mine.length && <li className="text-[12px] text-muted">Press M while it plays to note this moment.</li>}
+ {mine.length > 0 && !shown.length && <li className="text-[12px] text-muted">{filter === "open" ? "No open notes." : "Nothing resolved yet."}</li>}
+ {shown.map((n) => {
+ const collapsed = n.status !== "open" && filter === "all" && !opened[n.id];
+ if (collapsed) {
+ return (
+ <li key={n.id} data-play-note={n.id} data-play-note-collapsed="">
+ <button type="button" onClick={() => setOpened((o) => ({ ...o, [n.id]: true }))} className="flex w-full items-baseline gap-1.5 text-left text-[11.5px] text-muted hover:text-text">
+ <span className="font-mono">{timecode((n.anchor as CutAnchor).t)}</span>
+ <span>✓</span>
+ <span className="min-w-0 truncate">{n.text.split("\n")[0]}</span>
+ </button>
+ </li>
+ );
+ }
+ return (
+ <li key={n.id} data-play-note={n.id}>
+ <NoteThread
+ note={n}
+ write={notes.write}
+ busy={notes.busy}
+ head={head(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 (where it was taken, what it asks for) and replies here; what it proposes waits for your Apply"}
+ onClick={() => void a.ask({ note: n.id, scope: askOf(n) === "look" ? "look" : "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} variant="outline" onApplied={() => void notes.write({ op: "reply", id: n.id, text: "Applied the assistant's edits" })} />
+ )}
+ />
+ </li>
+ );
+ })}
+ </ol>
+
+ <div className="space-y-1.5 border-t border-seam p-3" 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 reel order, as one request; its proposals come back below"}
+ onClick={() => all && void a.ask({ request: all, scope: "all" })}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ >
+ {asking === "all" ? "Asking…" : `Send ${open.length} open note${open.length === 1 ? "" : "s"} to the assistant`}
+ </button>
+ {running && (
+ <button type="button" onClick={() => void a.cancel()} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Stop
+ </button>
+ )}
+ </div>
+ {blocked ? (
+ <p className="m-0 text-[11px] text-muted" data-play-assist-blocked="">
+ {blocked}
+ </p>
+ ) : (
+ 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">
+ Claude Code reads these with <code className="font-mono text-text-2">umtool notes {project}</code>.
+ </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>
+ );
+}
+
+/** The note being written: where, its words, what it asks for, Save note. */
+function Composer({ anchor, busy, onCancel, onSave }: { anchor: CutAnchor; busy: boolean; onCancel: () => void; onSave: (text: string, ask: CutAsk | null) => void | Promise<void> }) {
+ const [text, setText] = useState("");
+ const [ask, setAsk] = useState<CutAsk | null>(null);
+ const save = () => {
+ if (text.trim()) void onSave(text, ask);
+ };
+ return (
+ <div className="space-y-1.5" data-play-composer="">
+ <p className="m-0 font-mono text-[12px] text-text" data-play-note-at={anchor.t}>
+ Note at {timecode(anchor.t)}
+ {anchor.entry ? <span className="text-muted"> · {anchor.entry}</span> : null}
+ </p>
+ <textarea
+ autoFocus
+ rows={2}
+ value={text}
+ data-testid="play-note-input"
+ onChange={(e) => setText(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ onCancel();
+ } else if (e.key === "Enter" && !e.shiftKey && !e.altKey) {
+ e.preventDefault();
+ save();
+ } else if (e.altKey) {
+ const k = ASKS.find((x) => x.key === e.key.toLowerCase() || e.code === `Key${x.key.toUpperCase()}`);
+ if (k) {
+ e.preventDefault();
+ setAsk((cur) => (cur === k.id ? null : k.id));
+ }
+ }
+ }}
+ placeholder="What to change here"
+ className="block w-full resize-y rounded-[3px] border border-seam-2 bg-ground px-2 py-1.5 text-[13px] text-text outline-none focus:border-signal"
+ />
+ <div className="flex flex-wrap gap-1" role="group" aria-label="What it asks for">
+ {ASKS.map((k) => (
+ <button
+ key={k.id}
+ type="button"
+ aria-pressed={ask === k.id}
+ data-play-ask={k.id}
+ title={`Alt+${k.key.toUpperCase()}`}
+ onClick={() => setAsk((cur) => (cur === k.id ? null : k.id))}
+ className={cn("rounded-[2px] border px-1.5 py-px text-[11.5px]", ask === k.id ? "border-text-2 bg-panel-2 text-text" : "border-seam-2 text-muted-2 hover:text-text")}
+ >
+ {k.label}
+ </button>
+ ))}
+ </div>
+ <div className="flex items-center gap-2">
+ <button type="button" data-play-note-save="" disabled={busy || !text.trim()} onClick={save} className={buttonVariants({ variant: "go", size: "sm" })}>
+ Save note
+ </button>
+ <button type="button" onClick={onCancel} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Cancel
+ </button>
+ <span className="ml-auto text-[11px] text-muted">Enter saves · Esc closes</span>
+ </div>
+ </div>
+ );
+}
diff --git a/umtool/components/projects/review/ReelStrip.tsx b/umtool/components/projects/review/ReelStrip.tsx
@@ -0,0 +1,255 @@
+"use client";
+
+import { useMemo, useRef, useState } from "react";
+import { cn } from "@/lib/utils";
+import { counterAt, dateRamp, playPlan, rulerTicks, runningTime, shownSeconds } from "@/lib/report/playCut.mjs";
+
+type PlayItem = ReturnType<typeof playPlan>["items"][number];
+
+// ---------------------------------------------------------------------------
+// THE REEL STRIP (the Play view's signature): the whole cut as a strip of
+// film. One cell per entry, as wide as the page shows it; a clip's cell
+// tinted by its recording's date (older recedes toward the ground); a clip
+// with no media hatched; the sections' seams as hairlines with the section's
+// first date above; the deck's counter plotted across it as a staircase in
+// METER, its total at the right end and at the playhead; the notes as SIGNAL
+// pins at their cut second; the playhead a 1px SIGNAL line. Click or drag
+// anywhere to scrub; a cell's Enter jumps to its start; the ruler under it
+// counts the minutes.
+// ---------------------------------------------------------------------------
+
+export type StripEntry = { id: string; type: string; heading: string; dateKey?: number | null; dateLabel?: string | null; media?: unknown };
+export type StripCounter = { id: string; label: string; steps: Array<{ t: number; n: number }> };
+export type StripPin = { id: string; t: number; text: string; open: boolean };
+export type StripSeam = { before: string; index: number; date: string | null; label: string | null };
+
+const CELLS_H = 56;
+const pctOf = (t: number, total: number) => `${total > 0 ? Math.max(0, Math.min(100, (t / total) * 100)) : 0}%`;
+
+export default function ReelStrip({
+ items,
+ total,
+ entries,
+ t,
+ cur,
+ seams,
+ counters,
+ pins,
+ failed,
+ timecode,
+ onSeek,
+ onSeekItem,
+}: {
+ items: PlayItem[];
+ total: number;
+ entries: Map<string, StripEntry>;
+ t: number;
+ cur: number;
+ seams: StripSeam[];
+ counters: StripCounter[];
+ pins: StripPin[];
+ failed: Record<string, string>;
+ timecode: (t: number) => string;
+ onSeek: (t: number) => void;
+ onSeekItem: (i: number) => void;
+}) {
+ const cells = useRef<HTMLDivElement | null>(null);
+ const [hover, setHover] = useState<number | null>(null);
+ const scrubbing = useRef(false);
+ const ramp = useMemo(() => dateRamp([...entries.values()]), [entries]);
+ const max = Math.max(1, ...counters.map((c) => c.steps[c.steps.length - 1]?.n ?? 0));
+ const { ticks } = useMemo(() => rulerTicks(total), [total]);
+ const tAt = (clientX: number) => {
+ const r = cells.current?.getBoundingClientRect();
+ if (!r || r.width <= 0) return 0;
+ return Math.max(0, Math.min(1, (clientX - r.left) / r.width)) * total;
+ };
+ const counterNow = counters.map((c) => ({ ...c, now: counterAt(c.steps, t), end: c.steps[c.steps.length - 1]?.n ?? 0 }));
+ const hovered = hover !== null ? items[hover] : null;
+ const he = hovered ? entries.get(hovered.id) : null;
+ const noMedia = (it: PlayItem) => !!it.clip && (!entries.get(it.id)?.media || !!failed[it.id]);
+
+ return (
+ <section data-play-strip="" aria-label="The cut as a reel" className="select-none">
+ {/* the seams' dates, the counter's total at the right end */}
+ <div className="relative h-4 font-mono text-[10px] leading-4 text-muted">
+ {seams.map((s) => {
+ const it = items[s.index];
+ if (!it) return null;
+ return (
+ <span key={s.before} data-play-seam-date={s.before} className="absolute top-0 -translate-x-px whitespace-nowrap pl-1" style={{ left: pctOf(it.from, total) }} title={s.label ?? undefined}>
+ {s.date ?? s.label ?? ""}
+ </span>
+ );
+ })}
+ {counterNow.length > 0 && (
+ <span className="absolute right-0 top-0 whitespace-nowrap bg-ground pl-1.5 text-meter" data-play-counter-end={counterNow.map((c) => `${c.id}:${c.end}`).join(",")}>
+ {counterNow.map((c) => `${c.label} ${c.end}`).join(" · ")}
+ </span>
+ )}
+ </div>
+
+ {/* a hovered cell, named above it */}
+ <div className="relative h-0">
+ {hovered && (
+ <span
+ data-play-strip-hover={hovered.id}
+ className="pointer-events-none absolute -top-4 z-10 whitespace-nowrap rounded-[2px] border border-seam-2 bg-panel px-1.5 font-mono text-[10.5px] leading-4 text-text-2"
+ style={{
+ left: pctOf((hovered.from + hovered.to) / 2, total),
+ transform: `translateX(${(hovered.from + hovered.to) / 2 / Math.max(total, 1e-9) > 0.75 ? "-100%" : (hovered.from + hovered.to) / 2 / Math.max(total, 1e-9) < 0.25 ? "0" : "-50%"})`,
+ }}
+ >
+ {hovered.id}
+ {he?.dateLabel ? ` · ${he.dateLabel}` : hovered.clip ? "" : ` · ${hovered.type}`} · {shownSeconds(hovered).toFixed(1)} s
+ {noMedia(hovered) ? " · no media — fetch it" : ""}
+ </span>
+ )}
+ </div>
+
+ {/* the notes' pins */}
+ <div className="relative h-3">
+ {pins.map((p) => (
+ <button
+ key={p.id}
+ type="button"
+ data-play-pin={p.id}
+ title={`${timecode(p.t)} — ${p.text.split("\n")[0]}`}
+ aria-label={`note at ${timecode(p.t)}: ${p.text.split("\n")[0]}`}
+ onClick={() => onSeek(p.t)}
+ className={cn("absolute top-0 h-3 w-2 -translate-x-1/2 p-0", p.open ? "opacity-100" : "opacity-45")}
+ style={{ left: pctOf(p.t, total) }}
+ >
+ <span className="absolute left-1/2 top-0 h-2 w-2 -translate-x-1/2 rotate-45 bg-signal" />
+ <span className="absolute left-1/2 top-1.5 h-1.5 w-px -translate-x-1/2 bg-signal" />
+ </button>
+ ))}
+ </div>
+
+ {/* the cells: click or drag to scrub */}
+ <div
+ ref={cells}
+ data-play-cells=""
+ className="relative cursor-col-resize overflow-hidden rounded-[2px] border border-seam bg-ground touch-none"
+ style={{ height: CELLS_H }}
+ onPointerDown={(e) => {
+ if (e.button !== 0) return;
+ scrubbing.current = true;
+ e.currentTarget.setPointerCapture(e.pointerId);
+ onSeek(tAt(e.clientX));
+ }}
+ onPointerMove={(e) => {
+ const r = cells.current?.getBoundingClientRect();
+ if (r) {
+ const x = tAt(e.clientX);
+ const i = items.findIndex((it) => x >= it.from && x < it.to);
+ setHover(i >= 0 ? i : null);
+ }
+ if (scrubbing.current) onSeek(tAt(e.clientX));
+ }}
+ onPointerUp={() => {
+ scrubbing.current = false;
+ }}
+ onPointerLeave={() => setHover(null)}
+ >
+ {items.map((it, i) => {
+ const e = entries.get(it.id);
+ const f = ramp.get(it.id);
+ const missing = noMedia(it);
+ const base = it.clip
+ ? `color-mix(in srgb, var(--seam-2) ${Math.round(30 + 60 * (f ?? 0.5))}%, var(--ground))`
+ : "var(--panel)";
+ return (
+ <button
+ key={it.id}
+ type="button"
+ tabIndex={0}
+ data-play-row={it.id}
+ aria-current={i === cur ? "true" : undefined}
+ aria-label={`${it.id}${e?.dateLabel ? `, ${e.dateLabel}` : ""}, ${shownSeconds(it).toFixed(1)} seconds${missing ? ", no media" : ""}`}
+ title={missing ? `${it.id}: no media — fetch it` : undefined}
+ data-play-row-missing={missing ? "" : undefined}
+ onClick={(ev) => {
+ // A pointer's click scrubbed on pointerdown; a key's (Enter) jumps to the entry's start.
+ if (ev.detail === 0) onSeekItem(i);
+ }}
+ className={cn(
+ "absolute top-0 h-full overflow-hidden border-r border-ground px-1 pt-0.5 text-left font-mono text-[10px] leading-3",
+ it.clip ? "text-text-2" : "text-muted",
+ i === cur && "shadow-[inset_0_-2px_0_var(--signal)]",
+ )}
+ style={{
+ left: pctOf(it.from, total),
+ width: pctOf(it.to - it.from, total),
+ background: missing
+ ? `repeating-linear-gradient(135deg, var(--seam-2) 0 1px, transparent 1px 6px), ${base}`
+ : base,
+ }}
+ >
+ <span className="block whitespace-nowrap">{it.id}</span>
+ {!it.clip && <span className="block whitespace-nowrap text-[9px] uppercase tracking-wide opacity-80">{it.type}</span>}
+ </button>
+ );
+ })}
+
+ {/* the sections' seams */}
+ {seams.map((s) => {
+ const it = items[s.index];
+ return it ? <span key={s.before} aria-hidden className="pointer-events-none absolute top-0 h-full w-px bg-text-2 opacity-60" style={{ left: pctOf(it.from, total) }} /> : null;
+ })}
+
+ {/* the counter's staircase */}
+ {counters.length > 0 && total > 0 && (
+ <svg aria-hidden className="pointer-events-none absolute inset-0 h-full w-full" viewBox="0 0 1000 100" preserveAspectRatio="none" data-play-staircase="">
+ {counters.map((c, k) => {
+ const y = (n: number) => 94 - (n / max) * 78;
+ let d = `M0,${y(0)}`;
+ for (const s of c.steps) d += ` H${(s.t / total) * 1000} V${y(s.n)}`;
+ d += " H1000";
+ return (
+ <path
+ key={c.id}
+ d={d}
+ fill="none"
+ stroke={k === 0 ? "var(--meter)" : k === 1 ? "var(--m3)" : "var(--m5)"}
+ strokeWidth={1.5}
+ vectorEffect="non-scaling-stroke"
+ strokeLinejoin="miter"
+ />
+ );
+ })}
+ </svg>
+ )}
+
+ {/* the playhead */}
+ <span aria-hidden data-play-playhead="" className="pointer-events-none absolute top-0 h-full w-px bg-signal" style={{ left: pctOf(t, total) }} />
+ </div>
+
+ {/* the playhead's timecode and the counter at it; a hovered cell's line */}
+ <div className="relative h-4 font-mono text-[10.5px] leading-4">
+ <span
+ className="absolute top-0 whitespace-nowrap text-signal-text"
+ style={{ left: pctOf(t, total), transform: `translateX(${t / Math.max(total, 1e-9) > 0.8 ? "-100%" : t / Math.max(total, 1e-9) > 0.2 ? "-50%" : "0"})` }}
+ data-play-strip-at=""
+ >
+ {timecode(t)}
+ {counterNow.map((c) => (
+ <span key={c.id} className="text-meter">
+ {" "}
+ · {c.label} {c.now}
+ </span>
+ ))}
+ </span>
+ </div>
+ {/* the ruler */}
+ <div className="relative h-4 border-t border-seam font-mono text-[10px] leading-4 text-muted" aria-hidden data-play-ruler="">
+ {ticks.map((s) => (
+ <span key={s} className="absolute top-0" style={{ left: pctOf(s, total) }}>
+ <span className="absolute -top-px left-0 h-1.5 w-px bg-seam-2" />
+ {s > 0 && s < total - total * 0.04 && <span className="absolute left-0 top-0.5 -translate-x-1/2 whitespace-nowrap">{runningTime(s)}</span>}
+ </span>
+ ))}
+ </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,39 @@ 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, back (tap again: further), pause, play (tap again: 1.5×, 2×, …; the voice keeps its pitch), ±5 s, previous / next clip | the transport under the picture, the speed menu | Space, J K L, ← →, P N |
+| the whole cut at a glance: a cell per entry as wide as it plays, tinted by its recording's date (older is darker), hatched when its media is not fetched; the sections' seams with their first date; the counter (the deck's tally) as a staircase with its total at the end and at the playhead; the notes as pins | the **reel strip** under the picture: click or drag to scrub, a cell's Enter jumps to its start, hover names it | — |
+| what the clip on screen says, its spoken line lit as it plays, and what comes next | **Now**, under the strip | — |
+| a note at the playhead: the cut second, the clip on screen and its source second, the take, and what it asks for (Trim, Cut, Move, Fact, Look, Other: the anchor's `ask`); playback pauses while you write (**Pause while I write**, on by default) and goes on when it is saved | **Note at 09:44**, the kind chips, **Save note**; the list in reel order (Open / All / Resolved); a note's timecode seeks there | M, Alt+T C M F L O, Enter, Esc, [ ] |
+| 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 N open notes to the assistant** | — |
+| every key | **?** | ? |
+
+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,64 @@
+// 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 (k1 at 4.5) k01 card 1.5 s
+// c03 nofetch 2-4 (no window on disk) c04 vid1 6.0-8.0 (k2, counts 2)
+// sections 0 (c01, c02) and 1 (c03, c04); one counter, "Seizures"
+//
+// 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, section: 0, 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, section: 0, lock: true, quote: "And this one runs on", onscreen: { title: "2 Dec 2024" },
+ claim: { id: "k1", verdict: "CORROBORATED", at: 4.5 },
+ },
+ { 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, section: 1, lock: true, quote: "never fetched" },
+ {
+ type: "clip", id: "c04", video: "vid1", start: 6.0, end: 8.0, cite: 6, section: 1, lock: true, quote: "of that it finishes here.", onscreen: { title: "27 Feb 2025" },
+ claim: { id: "k2", verdict: "CORROBORATED", count: 2 },
+ },
+ ];
+ const m = deckManifest("play-cut-fixture", "The Play Cut Fixture", timeline);
+ m.render.fetchPad = 0;
+ // One counter, as the Huck cut has: the reel strip's staircase steps 1 at c02, 2 more at c04.
+ m.render.chrome = { ...m.render.chrome, factcheck: { verdicts: { CORROBORATED: { label: "Seizures", color: "#6fa8dc" } }, stamp: { seconds: 1 } } };
+ 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,210 @@
+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), the reel strip scrubs and
+// carries the counter's staircase, a note taken at the playhead (with its
+// kind) lists, pins and seeks, and a take plays its own timeline.
+// Screenshots at 1280 and 390 px land in test-results. 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; the strip scrubs; 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]')).toHaveCount(1);
+ await expect(page.locator('[data-play-row="c01"]')).toHaveAttribute("aria-current", "true");
+ await expect(page.locator("[data-play-approximate]")).toContainText("hard cut");
+ // The strip: the section seam before c03 dated by its first dated clip, the counter's staircase and its total.
+ await expect(page.locator('[data-play-seam-date="c03"]')).toHaveText("27 Feb 2025");
+ await expect(page.locator("[data-play-staircase] path")).toHaveCount(1);
+ await expect(page.locator("[data-play-counter-end]")).toHaveText("Seizures 3");
+ await expect(page.locator("[data-play-strip-at]")).toContainText("Seizures 0");
+ await expect(page.locator("[data-play-clock]")).toContainText("00:00 / 00:08");
+ // Hovering a cell names it: the clip, its recording's date, how long it plays.
+ await page.locator('[data-play-row="c02"]').hover();
+ await expect(page.locator('[data-play-strip-hover="c02"]')).toHaveText("c02 · 2 Dec 2024 · 1.8 s");
+ await page.locator('[data-play-row="c03"]').hover();
+ await expect(page.locator('[data-play-strip-hover="c03"]')).toContainText("no media — fetch it");
+
+ // 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);
+ // NOW: c02 on the reader, the next entry named.
+ await expect(page.locator('[data-play-now="c02"]')).toBeVisible();
+ await expect(page.locator("[data-play-next-up]")).toHaveAttribute("data-play-next-up", "k01");
+ await page.keyboard.press("k");
+ 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);
+ // The stamp on c02 (k1 at source 4.5) has landed by now: the counter at the playhead says so.
+ await expect(page.locator("[data-play-strip-at]")).toContainText("Seizures 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("No media for c03 — fetch it");
+ // Playing through it (L): the wall clock carries on to c04.
+ await page.keyboard.press("l");
+ await expect(root(page)).toHaveAttribute("data-play-item", "c04", { timeout: 15_000 });
+ await page.keyboard.press("Space");
+ await expect(root(page)).toHaveAttribute("data-play-state", "paused");
+ // 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 cell's Enter jumps to its start; a click on the strip scrubs to that second.
+ await page.locator('[data-play-row="c02"]').press("Enter");
+ await expect(root(page)).toHaveAttribute("data-play-item", "c02");
+ expect(await tNow(page)).toBeCloseTo(1.9, 1);
+ const cells = page.locator("[data-play-cells]");
+ const box = (await cells.boundingBox())!;
+ await page.mouse.click(box.x + box.width * 0.9, box.y + box.height / 2);
+ await expect(root(page)).toHaveAttribute("data-play-item", "c04");
+ expect(Math.abs((await tNow(page)) - 0.9 * 8.7)).toBeLessThan(0.15);
+
+ // ? lists the keys; Esc closes it.
+ await page.keyboard.press("?");
+ await expect(page.locator("[data-play-keys]")).toContainText("previous / next note");
+ await page.keyboard.press("Escape");
+ await expect(page.locator("[data-play-keys]")).toHaveCount(0);
+});
+
+test("a note at the playhead: its kind, the cut second, the clip and its source second; listed, pinned, [ ] and a click seek", 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(page.locator("[data-play-note-list]")).toContainText("Press M while it plays to note this moment.");
+ await page.locator('[data-play-row="c02"]').press("Enter");
+ await page.keyboard.press("ArrowRight"); // 1.9 + 5 = 6.9: c04
+ await expect(root(page)).toHaveAttribute("data-play-item", "c04");
+ await expect(page.locator("[data-play-note-add]")).toHaveText("Note at 00:06.9");
+ // Paused, the clip's frame is in the picture (the fixture's window is dark green), not a black box.
+ await expect
+ .poll(
+ () =>
+ page.locator("[data-play-footage]").evaluate((c: HTMLCanvasElement) => {
+ const [r, g, b] = c.getContext("2d")!.getImageData(Math.floor(c.width / 2), Math.floor(c.height / 2), 1, 1).data;
+ return g > 60 && r < 40 && b < 40;
+ }),
+ { timeout: 15_000 },
+ )
+ .toBe(true);
+ 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("Alt+t");
+ await expect(page.locator('[data-play-ask="trim"]')).toHaveAttribute("aria-pressed", "true");
+ 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]")).toHaveText("00:06.9");
+ await expect(note.locator("[data-play-note-ask]")).toHaveText("trim");
+ await expect(page.locator("[data-play-pin]")).toHaveCount(1);
+ await expect(page.locator("[data-play-send-all]")).toHaveText("Send 1 open note to the assistant");
+
+ // Written through the notes store: the cut anchor, the clip, its source second (c04 starts at 6.7: 6.0 + 0.2), the kind.
+ 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, ask: "trim" });
+ expect(n.author).toBe("operator");
+
+ // Elsewhere, then ] (the next note) and the note's timecode: back where it was taken.
+ await page.locator('[data-play-row="c01"]').press("Enter");
+ await expect(root(page)).toHaveAttribute("data-play-item", "c01");
+ await page.keyboard.press("]");
+ await expect(root(page)).toHaveAttribute("data-play-item", "c04");
+ expect(await tNow(page)).toBeCloseTo(6.9, 1);
+ await page.locator('[data-play-row="c01"]').press("Enter");
+ 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);
+
+ // How it looks: the desk at 1280, the stack at a phone's 390 (no sideways scroll).
+ await page.setViewportSize({ width: 1280, height: 860 });
+ await page.screenshot({ path: test.info().outputPath("play-1280.png") });
+ await page.setViewportSize({ width: 390, height: 844 });
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true);
+ await page.screenshot({ path: test.info().outputPath("play-390.png") });
+ await page.locator("[data-play-now]").scrollIntoViewIfNeeded();
+ await page.screenshot({ path: test.info().outputPath("play-390-now.png") });
+ await page.locator("[data-play-send-all]").scrollIntoViewIfNeeded();
+ await page.screenshot({ path: test.info().outputPath("play-390-notes.png") });
+ // And the dark base, at the desk's width.
+ await page.emulateMedia({ colorScheme: "dark" });
+ await page.setViewportSize({ width: 1280, height: 860 });
+ await page.screenshot({ path: test.info().outputPath("play-1280-dark.png") });
+});
+
+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(page.locator('[data-play-take-link="short"]')).toHaveAttribute("aria-current", "page");
+ 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"]').press("Enter");
+ 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, ask: "trim" } }, { 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, /\*\*Asks for:\*\* a trim \(a clip's edges\)\nentry `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,22 @@ const clip = (s, n = 300) => {
return t.length > n ? `${t.slice(0, n - 1)}…` : t;
};
const quoteLine = (s) => `> ${clip(s, 400)}`;
+/** What a Play-view note's `ask` means, for the agent. */
+const ASK_WORDS = {
+ trim: "a trim (a clip's edges)",
+ cut: "a cut (an entry out)",
+ move: "a move (an entry elsewhere in the order)",
+ fact: "a fact check (a claim, a stamp, a count)",
+ look: "a change of look (the chrome, the joins, the picture)",
+ other: "something else (read the note)",
+};
+
+/** `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 +145,36 @@ 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.ask) lines.push(`**Asks for:** ${ASK_WORDS[a.ask] ?? a.ask}`);
+ 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 +210,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 +223,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,8 +15,10 @@ 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"];
+/** What a note taken in the Play view asks for (a `cut` anchor's `ask`): the dailies' kinds. */
+export const CUT_ASKS = ["trim", "cut", "move", "fact", "look", "other"];
const ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const TAKE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
@@ -104,6 +106,33 @@ 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, the take when it was a take that played, and
+ // what the note asks for (`ask`, CUT_ASKS: a trim, a cut, a move, …).
+ 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;
+ }
+ if (a.ask !== undefined) {
+ if (!CUT_ASKS.includes(/** @type {string} */ (a.ask))) return { error: `cut ask is one of ${CUT_ASKS.join(", ")}` };
+ out.ask = a.ask;
+ }
+ 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,17 @@ 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 });
+ assert.equal(validateAnchor({ kind: "cut", t: 1, ask: "trim" }).anchor.ask, "trim");
+ 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 }, { kind: "cut", t: 1, ask: "please" }]) {
+ 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
@@ -7,6 +7,7 @@
// this file adds the types.
export {
ANCHOR_KINDS,
+ CUT_ASKS,
NOTE_AUTHORS,
NOTE_STATUSES,
NOTE_TEXT_LIMIT,
@@ -40,7 +41,12 @@ 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; ask?: CutAsk };
+
+/** What a Play-view note asks for (shape.mjs CUT_ASKS). */
+export type CutAsk = "trim" | "cut" | "move" | "fact" | "look" | "other";
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,272 @@
+// 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, ask?: string } }>} 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 ask = n.anchor.ask && n.anchor.ask !== "other" ? ` [${n.anchor.ask}]` : "";
+ const line = `${i + 1}. ${cutPlace(n.anchor)}${ask}: ${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(", ");
+}
+
+// ---------------------------------------------------------------------------
+// THE REEL STRIP (PlayCut.tsx): the whole cut as a strip of film -- a cell
+// per entry as wide as it is shown, tinted by its recording's date, the
+// sections' seams, the counter's staircase, the time ruler.
+// ---------------------------------------------------------------------------
+
+/**
+ * Each entry's place on the date ramp, 0 (the oldest recording) to 1 (the
+ * newest), by `dateKey` (YYYYMMDD); null for an entry with no date. One date
+ * throughout is 1 for every dated entry.
+ *
+ * @param {Array<{ id: string, dateKey?: number | null }>} entries
+ * @returns {Map<string, number | null>}
+ */
+export function dateRamp(entries) {
+ const days = (k) => {
+ const y = Math.floor(k / 10000);
+ const m = Math.floor((k % 10000) / 100);
+ const d = k % 100;
+ return Date.UTC(y, m - 1, d) / 86400000;
+ };
+ const dated = (entries ?? []).filter((e) => fin(e.dateKey)).map((e) => days(/** @type {number} */ (e.dateKey)));
+ const lo = Math.min(...dated);
+ const hi = Math.max(...dated);
+ return new Map(
+ (entries ?? []).map((e) => [e.id, fin(e.dateKey) ? (hi > lo ? round((days(/** @type {number} */ (e.dateKey)) - lo) / (hi - lo)) : 1) : null]),
+ );
+}
+
+/**
+ * Where the cut changes section: before entry i when it is the first clip of
+ * a new `section` (sections.mjs's rule), or right after a deck marker's
+ * `after` clip. Each seam names the first date after it (the first dated
+ * clip from there on) and the marker's label when a marker made it.
+ *
+ * @param {Array<{ id: string, type: string, section?: unknown, dateLabel?: string | null }>} entries the cut's, in order
+ * @param {Array<{ after: string, label?: string }>} [markers] render.chrome.deck.markers
+ * @returns {Array<{ before: string, index: number, date: string | null, label: string | null }>}
+ */
+export function seamsOf(entries, markers = []) {
+ const list = entries ?? [];
+ /** @type {Map<number, string | null>} */
+ const at = new Map();
+ let prev;
+ list.forEach((e, i) => {
+ if (e.type !== "clip") return;
+ const s = e.section;
+ if (s !== undefined && s !== null && prev !== undefined && s !== prev && i > 0) at.set(i, null);
+ if (s !== undefined && s !== null) prev = s;
+ });
+ for (const m of markers ?? []) {
+ const i = list.findIndex((e) => e.id === m?.after);
+ if (i >= 0 && i + 1 < list.length) at.set(i + 1, typeof m.label === "string" && m.label ? m.label : (at.get(i + 1) ?? null));
+ }
+ return [...at.entries()]
+ .sort((a, b) => a[0] - b[0])
+ .map(([i, label]) => ({
+ before: list[i].id,
+ index: i,
+ date: list.slice(i).find((e) => e.type === "clip" && e.dateLabel)?.dateLabel ?? null,
+ label,
+ }));
+}
+
+/**
+ * The counter as a staircase: for one verdict (or every one, `verdict`
+ * null), the running total after each stamp lands, in cut order --
+ * `[{ t, n }]`, one point per step (stamps landing together are one step).
+ *
+ * @param {Array<{ landed: number, verdict: string, count?: number }>} stamps the schedule's factcheck stamps
+ * @param {string | null} [verdict]
+ */
+export function counterSteps(stamps, verdict = null) {
+ const mine = (stamps ?? []).filter((s) => fin(s.landed) && (verdict === null || s.verdict === verdict)).sort((a, b) => a.landed - b.landed);
+ /** @type {Array<{ t: number, n: number }>} */
+ const out = [];
+ let n = 0;
+ for (const s of mine) {
+ n += fin(s.count) ? /** @type {number} */ (s.count) : 1;
+ const last = out[out.length - 1];
+ if (last && last.t === round(s.landed)) last.n = n;
+ else out.push({ t: round(s.landed), n });
+ }
+ return out;
+}
+
+/** The counter's total at cut second t (the steps that landed by then). */
+export function counterAt(steps, t) {
+ let n = 0;
+ for (const s of steps ?? []) if (s.t <= t) n = s.n;
+ return n;
+}
+
+/**
+ * The time ruler's ticks: a round step (seconds) that gives at most
+ * `maxTicks` ticks over the cut, and each tick's second.
+ *
+ * @param {number} total
+ * @param {number} [maxTicks]
+ */
+export function rulerTicks(total, maxTicks = 12) {
+ const steps = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600];
+ const T = fin(total) && total > 0 ? total : 0;
+ const step = steps.find((s) => T / s <= maxTicks) ?? steps[steps.length - 1];
+ const ticks = [];
+ for (let t = 0; t <= T + 1e-9; t += step) ticks.push(t);
+ return { step, ticks };
+}
+
+/** `m:ss` (or `h:mm:ss`): a ruler's or the running time's label. */
+export function runningTime(t) {
+ const s = Math.max(0, Math.floor(fin(t) ? t : 0));
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const ss = String(s % 60).padStart(2, "0");
+ return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${String(m).padStart(2, "0")}:${ss}`;
+}
+
+/** YYYYMMDD → "24 Oct 2020". */
+export function dateKeyLabel(k) {
+ if (!fin(k)) return null;
+ const MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+ const y = Math.floor(k / 10000);
+ const m = Math.floor((k % 10000) / 100);
+ const d = k % 100;
+ return m >= 1 && m <= 12 ? `${d} ${MON[m - 1]} ${y}` : null;
+}
diff --git a/umtool/lib/report/playCut.test.mjs b/umtool/lib/report/playCut.test.mjs
@@ -0,0 +1,176 @@
+// 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 {
+ counterAt, counterSteps, cutAtSource, cutNotesRequest, cutPlace, dateKeyLabel, dateRamp, inHold, itemIndexAt, playPlan, rulerTicks,
+ runningTime, seamsOf, 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", ask: "trim" } },
+ { 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 [trim]: 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");
+});
+
+test("the reel strip: the date ramp, the seams, the counter's staircase, the ruler", () => {
+ const ramp = dateRamp([
+ { id: "a", dateKey: 20201024 },
+ { id: "b", dateKey: 20241202 },
+ { id: "k" },
+ { id: "c", dateKey: 20221113 },
+ ]);
+ assert.equal(ramp.get("a"), 0);
+ assert.equal(ramp.get("b"), 1);
+ assert.equal(ramp.get("k"), null);
+ assert.ok(Number(ramp.get("c")) > 0.4 && Number(ramp.get("c")) < 0.6);
+ assert.equal(dateRamp([{ id: "x", dateKey: 20200101 }]).get("x"), 1);
+
+ const entries = [
+ { id: "a", type: "clip", section: 0, dateLabel: "24 Oct 2020" },
+ { id: "b", type: "clip", section: 0, dateLabel: "1 Dec 2020" },
+ { id: "k", type: "card" },
+ { id: "c", type: "clip", section: 1, dateLabel: "13 Nov 2022" },
+ { id: "d", type: "clip", section: 1, dateLabel: "2 Dec 2024" },
+ ];
+ assert.deepEqual(seamsOf(entries), [{ before: "c", index: 3, date: "13 Nov 2022", label: null }]);
+ assert.deepEqual(seamsOf(entries, [{ after: "a", label: "Rescue" }, { after: "d", label: "past the end" }]), [
+ { before: "b", index: 1, date: "1 Dec 2020", label: "Rescue" },
+ { before: "c", index: 3, date: "13 Nov 2022", label: null },
+ ]);
+
+ const stamps = [
+ { landed: 5, verdict: "E", count: 2 },
+ { landed: 1, verdict: "E" },
+ { landed: 5, verdict: "G" },
+ { landed: 9, verdict: "E" },
+ ];
+ assert.deepEqual(counterSteps(stamps, "E"), [{ t: 1, n: 1 }, { t: 5, n: 3 }, { t: 9, n: 4 }]);
+ assert.deepEqual(counterSteps(stamps), [{ t: 1, n: 1 }, { t: 5, n: 4 }, { t: 9, n: 5 }]);
+ assert.equal(counterAt(counterSteps(stamps, "E"), 4.9), 1);
+ assert.equal(counterAt(counterSteps(stamps, "E"), 5), 3);
+ assert.equal(counterAt([], 3), 0);
+
+ assert.deepEqual(rulerTicks(8.7), { step: 1, ticks: [0, 1, 2, 3, 4, 5, 6, 7, 8] });
+ assert.equal(rulerTicks(1142).step, 120);
+ assert.equal(rulerTicks(0).ticks.length, 1);
+ assert.equal(runningTime(581.4), "09:41");
+ assert.equal(runningTime(3725), "1:02:05");
+ assert.equal(dateKeyLabel(20250227), "27 Feb 2025");
+ assert.equal(dateKeyLabel(null), null);
+});
diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs
@@ -0,0 +1,119 @@
+// 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, estimateSchedule, scheduleFrom, transitionOf } from "umtool-report-to-video/deck";
+import { resolveFactcheck } from "umtool-report-to-video/factcheck";
+import { clipDateKey, readManifest } from "../projects/report.mjs";
+import { dateKeyLabel } from "./playCut.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), section: e.section ?? null };
+ const win = pickWindow(await windowsFor(project, e, cache), null);
+ const dateKey = clipDateKey(e);
+ const onscreenDate = text(e.onscreen?.title);
+ return {
+ id: e.id,
+ type: "clip",
+ // The recording's date (the on-screen date, else the upload date): the reel strip's tint.
+ dateKey,
+ dateLabel: dateKey === null ? null : /^\d{1,2}\s+[A-Za-z]{3}/.test(onscreenDate) ? onscreenDate : dateKeyLabel(dateKey),
+ section: e.section ?? null,
+ channel: typeof e.channel === "string" ? e.channel : null,
+ 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,
+ };
+ }),
+ );
+ // The counter (the deck's tally): each stamp's landing second and count on
+ // the estimate's clock, and each verdict's word -- the reel strip's
+ // staircase before (or without) the chrome's own schedule.
+ let counter = { verdicts: /** @type {Array<{ id: string, label: string }>} */ ([]), stamps: /** @type {Array<{ landed: number, verdict: string, count: number }>} */ ([]) };
+ try {
+ const est = estimateSchedule(selected);
+ const stamps = (est?.factcheck?.stamps ?? []).filter((x) => fin(x.landed));
+ const words = /** @type {Record<string, { label: string }>} */ (resolveFactcheck(render).verdicts ?? {});
+ const ids = [...new Set(stamps.map((x) => String(x.verdict)))];
+ counter = {
+ verdicts: ids.map((id) => ({ id, label: words[id]?.label ?? id })),
+ stamps: stamps.map((x) => ({ landed: x.landed, verdict: String(x.verdict), count: fin(x.count) ? x.count : 1 })),
+ };
+ } catch {
+ // A cut the deck cannot schedule counts nothing on the strip.
+ }
+ const markers = Array.isArray(render.chrome?.deck?.markers)
+ ? render.chrome.deck.markers.filter((m) => m && typeof m.after === "string").map((m) => ({ after: m.after, label: typeof m.label === "string" ? m.label : "" }))
+ : [];
+ return {
+ project: project.id,
+ title: text(manifest.title) || project.id,
+ counter,
+ markers,
+ 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 });
+ }
+});