Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 29742cfb3baedd8e82e4f461d2061a02f69e9009
parent 51ebbd4a4865eb6db85c69c87ab5e24d988c5bd1
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun,  1 Nov 2026 22:12:58 -0500

Merge lane/play-audio-once (with lane/play-walk-app, lane/ui-cut-editing, lane/ui-cut-integrity, lane/playcut-gaps): Play and the clip bench as one app, the reel strip's zoom and drag reorder, the latest take as the working cut, the stamp fix; sections edited as sections, flash-forward, the trailer's beats, take housekeeping; the cite follows the edge, take patches follow a removal, QR links checked; each clip's sound decoded once, a gapped clip per kept piece, asked for in the order it is due

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Aumtool/app/api/report/bench/route.ts | 21+++++++++++++++++++++
Mumtool/app/api/report/clip/route.ts | 4++++
Aumtool/app/api/report/links/route.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/patch-markers/route.ts | 41+++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/play-view/route.ts | 16++++++++++++++++
Aumtool/app/api/report/takes/housekeeping/route.ts | 42++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/report/takes/pick/route.ts | 9++++++---
Mumtool/app/api/report/timeline/route.ts | 35++++++++++++++++++++++++++++++++++-
Aumtool/app/api/report/trailer-beats/route.ts | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/report/window/route.ts | 18++++++++++++++++--
Mumtool/bin/umtool.mjs | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/ClipBench.tsx | 196+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/components/projects/ClipBenchPage.tsx | 255+++----------------------------------------------------------------------------
Mumtool/components/projects/PlayCutPage.tsx | 13+++++++++----
Mumtool/components/projects/ProjectView.tsx | 5++++-
Mumtool/components/projects/TakesBench.tsx | 128+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/components/projects/TakesPage.tsx | 19+++++++++++++++++--
Mumtool/components/projects/TimelineEditor.tsx | 257+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Aumtool/components/projects/TrailerBeatsEditor.tsx | 313+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/TrailerPage.tsx | 24++++++++++++++++++++++++
Mumtool/components/projects/bench/GapsZoom.tsx | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Aumtool/components/projects/cutApp/CutApp.tsx | 232+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/report/CutTab.tsx | 347+++++++++++++++++++++++++++++++++++++++++++++++++------------------------------
Aumtool/components/projects/report/DecisionSettle.tsx | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/report/OverviewTab.tsx | 15++++++++++++---
Mumtool/components/projects/review/ClipDeck.tsx | 2+-
Mumtool/components/projects/review/ClipEditor.tsx | 42++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/review/CutEditing.tsx | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/PlayCut.tsx | 343++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mumtool/components/projects/review/ReelStrip.tsx | 585+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Aumtool/components/projects/review/WhatPlays.tsx | 159+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/playEngine/audioBank.ts | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mumtool/components/projects/review/playEngine/codecPicture.ts | 31+++++++++++++++++++++++--------
Mumtool/components/projects/review/playEngine/engine.ts | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------
Mumtool/components/projects/review/playEngine/usePlayEngine.ts | 14++++++++------
Mumtool/docs/cli.md | 24++++++++++++++++++++++--
Mumtool/docs/clip-bench.md | 38++++++++++++++++++++++++++++++++++++++
Mumtool/docs/inbox.md | 7++++++-
Mumtool/docs/knobs.md | 179+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/docs/report-video.md | 30++++++++++++++++++++++++++++++
Aumtool/e2e/cut-flash.spec.ts | 135+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/cut-integrity.spec.ts | 220+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/cut-sections.spec.ts | 134+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/cut-editing-fixture.mjs | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/cut-integrity-fixture.mjs | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 31+++++++++++++++++++++++++++++++
Mumtool/e2e/gaps-zoom.spec.ts | 49+++++++++++++++++++++++++++++++++++++++----------
Mumtool/e2e/phone-walk.spec.ts | 7++++---
Aumtool/e2e/play-walk.spec.ts | 271+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/take-housekeeping.spec.ts | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/trailer-beats.spec.ts | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/decisions.ts | 14++++++++++++++
Mumtool/lib/hrefs.ts | 9++++++++-
Mumtool/lib/inbox/groups.mjs | 5+++++
Mumtool/lib/inbox/what.mjs | 5+++++
Mumtool/lib/projects/report.mjs | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/bankTrim.mjs | 31+++++++++++++++++++++++++++++--
Mumtool/lib/report/bankTrim.test.mjs | 12+++++++++++-
Aumtool/lib/report/benchData.ts | 300+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/citeFollow.mjs | 182+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/clipDeck.ts | 21++++++++++++++++-----
Mumtool/lib/report/clipEditor.mjs | 40++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/clipEditorTypes.ts | 2+-
Aumtool/lib/report/cut-integrity.test.mjs | 494+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/delete.mjs | 4++++
Mumtool/lib/report/knobs.test.mjs | 34++++++++++++++++++++++++++++++++++
Aumtool/lib/report/linkCheck.mjs | 296+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/linksCli.mjs | 161+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 390+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Aumtool/lib/report/patchMarkers.mjs | 265+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/pieceWants.test.mjs | 28++++++++++++++++++++++++++++
Aumtool/lib/report/placeIn.test.mjs | 154+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/playCut.mjs | 31+++++++++++++++++++++++++++++++
Aumtool/lib/report/playDecodes.test.mjs | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/playSchedule.mjs | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Aumtool/lib/report/playTakeGaps.test.mjs | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/playView.mjs | 48+++++++++++++++++++++++++++++++++++++++++++-----
Aumtool/lib/report/sectionEdit.mjs | 399+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/sectionEdit.test.mjs | 273+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/stripDrag.mjs | 165+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/stripDrag.test.mjs | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/takeCli.mjs | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/lib/report/takeEdit.mjs | 33+++++++++++++++++++++++++++++++++
Aumtool/lib/report/takeHousekeeping.mjs | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takeHousekeeping.test.mjs | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/takeMaker.mjs | 14++++++++++----
Mumtool/lib/report/takes.mjs | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mumtool/lib/report/timelineCli.mjs | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Aumtool/lib/report/trailerBeats.mjs | 439+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/trailerBeats.test.mjs | 142+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/trailerBeatsCli.mjs | 219+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/trailerCandidates.mjs | 39+++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/trailerCli.mjs | 27++++++++++++++++++++++++++-
Aumtool/lib/report/workingCut.mjs | 172+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/workingCut.test.mjs | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/playwright.config.ts | 4++++
96 files changed, 10363 insertions(+), 750 deletions(-)

diff --git a/umtool/app/api/report/bench/route.ts b/umtool/app/api/report/bench/route.ts @@ -0,0 +1,21 @@ +import { projectRef } from "@/lib/projects"; +import { clipBenchData } from "@/lib/report/benchData"; + +export const dynamic = "force-dynamic"; + +// THE CLIP BENCH'S DATA as JSON, for Play's in-place bench (components/projects/cutApp/CutApp.tsx): +// GET ?project=<id>&clip=<id>[&take=<id>][&from=play&at=<s>][&order=cut] +// +// The same function the bench's own page renders from (lib/report/benchData.ts), +// so the bench inside Play and the one on its own page cannot disagree. A clip +// that is not a clip of the cut is a 404, as the page's. +export async function GET(request: Request) { + const q = new URL(request.url).searchParams; + const project = await projectRef(q.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const clip = q.get("clip") ?? ""; + const search = Object.fromEntries([...q.entries()].filter(([k]) => k !== "project" && k !== "clip")); + const r = await clipBenchData(project, clip, { search, take: q.get("walkTake") || null, order: q.get("order") === "cut" ? "cut" : "walk" }); + if (!r) return Response.json({ error: `${clip} is not a clip of the cut` }, { status: 404 }); + return Response.json(r, { headers: { "cache-control": "no-store" } }); +} diff --git a/umtool/app/api/report/clip/route.ts b/umtool/app/api/report/clip/route.ts @@ -69,6 +69,10 @@ export async function GET(request: Request) { muteFrom: clip.muteFrom ?? null, // Seconds cut out of its middle (gaps.mjs). gaps: Array.isArray(clip.gaps) ? clip.gaps : [], + // What the walk said that is not a verdict, and a deliberate repeat. + walkNote: typeof clip.walkNote === "string" ? clip.walkNote : null, + star: clip.star === true, + repeatOf: typeof clip.repeatOf === "string" ? clip.repeatOf : null, }, view, // `v`: the version of each window's bytes, for the media URLs -- a refetch diff --git a/umtool/app/api/report/links/route.ts b/umtool/app/api/report/links/route.ts @@ -0,0 +1,63 @@ +import { projectRef } from "@/lib/projects"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { linkVerdicts, readLinkCheck, runLinkCheck } from "@/lib/report/linkCheck.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { withEditNotes } from "@/lib/report/guard"; +import { updateClip } from "@/lib/report/manifest.mjs"; + +export const dynamic = "force-dynamic"; + +// DO THE QR LINKS OPEN (lib/report/linkCheck.mjs; UI notes #8): every clip QR +// the cut draws, resolved against the site it links -- corpus.json, the +// channel's manifest, slugToPage, the shard's record. One request at a time; +// a site that does not answer leaves its links unverified. The project page's +// Check links (the link-dead / links-unverified / links-unchecked rows), and +// `umtool links <project>`. +// +// GET ?project=<id> the recorded check (out/links.json) read against the manifest as it is now +// POST { project, fix? } check now, record it, and answer the same; `fix`: first +// rewrite every dead link the last check knows the fix for +// (a Twitch id the site serves as v<id>) through the window writer +const headers = { "cache-control": "no-store" }; + +async function answer(dir: string, doc: Awaited<ReturnType<typeof readLinkCheck>>) { + const m = await readManifest(dir); + const v = linkVerdicts(m ?? {}, doc); + return { doc, verdicts: { ...v, unchecked: v.unchecked.length } }; +} + +export async function GET(request: Request) { + const url = new URL(request.url); + const project = await projectRef(url.searchParams.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404, headers }); + return Response.json(await answer(project.dir, await readLinkCheck(project.dir)), { headers }); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/links"); + if (refused) return refused; + const b = (await request.json().catch(() => null)) as { project?: unknown; fix?: unknown } | null; + if (!b || typeof b !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); + const project = await projectRef(String(b.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404, headers }); + let m = await readManifest(project.dir); + if (!m) return Response.json({ error: "the project has no video.manifest.json" }, { status: 400, headers }); + try { + const fixed: { clip: string; from: string; to: string }[] = []; + if (b.fix === true) { + const last = await readLinkCheck(project.dir); + const now = new Map(((m.timeline ?? []) as { id: string; citeUrl?: string }[]).map((e) => [e.id, e.citeUrl])); + for (const l of last?.links ?? []) { + // Only a link still exactly what the check saw: an edit since is somebody's decision. + if (l.state !== "dead" || !l.fix || now.get(l.clip) !== l.url) continue; + await withEditNotes(project, () => updateClip(project.dir, l.clip, { citeUrl: l.fix })); + fixed.push({ clip: l.clip, from: l.url, to: l.fix }); + } + if (fixed.length) m = await readManifest(project.dir); + } + const doc = await runLinkCheck(project.dir, m); + return Response.json({ ok: true, fixed, ...(await answer(project.dir, doc)) }, { headers }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500, headers }); + } +} diff --git a/umtool/app/api/report/patch-markers/route.ts b/umtool/app/api/report/patch-markers/route.ts @@ -0,0 +1,41 @@ +import { projectRef } from "@/lib/projects"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { fixStalePatchMarkers, stalePatchMarkers } from "@/lib/report/patchMarkers.mjs"; +import { refuseCaller } from "@/lib/report/caller"; + +export const dynamic = "force-dynamic"; + +// A TAKE PATCH'S MARKERS, BACK ON THE CUT (lib/report/patchMarkers.mjs; UI +// notes #6). The patch-markers-stale row's "Take the cut's markers", and +// `umtool patch-markers <project> <file> --fix`: each marker after a clip +// that is not in the cut takes the `after` of the cut's marker with the same +// label; one no marker of the cut shares a label with is left, and named. +// +// GET ?project=<id> every stale patch marker +// POST { project, file } settle that patch +const headers = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const project = await projectRef(url.searchParams.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404, headers }); + const m = await readManifest(project.dir); + return Response.json({ stale: m ? await stalePatchMarkers(project.dir, m) : [] }, { headers }); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/patch-markers"); + if (refused) return refused; + const b = (await request.json().catch(() => null)) as { project?: unknown; file?: unknown } | null; + if (!b || typeof b !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); + const project = await projectRef(String(b.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404, headers }); + const m = await readManifest(project.dir); + if (!m) return Response.json({ error: "the project has no video.manifest.json" }, { status: 400, headers }); + try { + const r = await fixStalePatchMarkers(project.dir, m, String(b.file ?? "")); + return Response.json({ ok: true, ...r }, { headers }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400, headers }); + } +} diff --git a/umtool/app/api/report/play-view/route.ts b/umtool/app/api/report/play-view/route.ts @@ -0,0 +1,16 @@ +import { projectRef } from "@/lib/projects"; +import { playView } from "@/lib/report/playView.mjs"; + +export const dynamic = "force-dynamic"; + +// PLAY'S VIEW as JSON (lib/report/playView.mjs): what `/projects/<p>/play` renders, read again +// in place after an edit (components/projects/review/PlayCut.tsx reloadView) rather than by a +// router refresh. GET ?project=<id>[&take=<id> | &cut=1]; no take: the latest take. +export async function GET(request: Request) { + const q = new URL(request.url).searchParams; + const project = await projectRef(q.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const view = await playView(project, { take: q.get("take") || null, bare: q.get("cut") === "1" }); + if ("error" in view) return Response.json(view, { status: 400 }); + return Response.json(view, { headers: { "cache-control": "no-store" } }); +} diff --git a/umtool/app/api/report/takes/housekeeping/route.ts b/umtool/app/api/report/takes/housekeeping/route.ts @@ -0,0 +1,42 @@ +import { projectRef } from "@/lib/projects"; +import { isTakeId, listTakes, setTakeSuperseded } from "@/lib/report/takes.mjs"; +import { relabelTake } from "@/lib/report/takeEdit.mjs"; +import { renderHolds } from "@/lib/report/takeHousekeeping.mjs"; + +export const dynamic = "force-dynamic"; + +// TAKE HOUSEKEEPING (UI notes 2026-10-30, item 19) -- the takes list's +// Relabel and Superseded; Delete is /api/report/takes/delete. +// +// POST { project, take, op: "relabel", label } take.json's label (an undo +// point of the take's own), +// refused while it renders +// POST { project, take, op: "supersede", by?: <take> } verdicts.json: folded away +// POST { project, take, op: "unsupersede" } the mark cleared +// +// The CLI's twins: `umtool takes relabel | supersede [--clear]`. +export async function POST(request: Request) { + const body = (await request.json().catch(() => null)) as { project?: string; take?: string; op?: string; label?: string; by?: string | null } | null; + if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 }); + if (!isTakeId(body.take)) return Response.json({ error: "take must be a take id" }, { status: 400 }); + const take = body.take; + const project = await projectRef(String(body.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const known = (await listTakes(project.dir)).takes.map((t) => t.id); + if (!known.includes(take)) return Response.json({ error: "no such take" }, { status: 404 }); + try { + if (body.op === "relabel") { + const r = await relabelTake(project.dir, take, String(body.label ?? ""), { holds: await renderHolds(project.dir, take) }); + return Response.json({ ok: true, take, label: r.label, was: r.was, revision: r.revision?.rel ?? null }, { headers: { "cache-control": "no-store" } }); + } + if (body.op === "supersede" || body.op === "unsupersede") { + const by = typeof body.by === "string" && body.by ? body.by : null; + const r = await setTakeSuperseded(project.dir, take, { by, clear: body.op === "unsupersede", known }); + return Response.json({ ok: true, take, ...r }, { headers: { "cache-control": "no-store" } }); + } + return Response.json({ error: "op must be relabel, supersede or unsupersede" }, { status: 400 }); + } catch (e) { + const message = e instanceof Error ? e.message : String(e); + return Response.json({ error: message, ...(/changed since/.test(message) ? { stale: true } : {}) }, { status: /rendering now|being rendered/.test(message) ? 409 : 400 }); + } +} diff --git a/umtool/app/api/report/takes/pick/route.ts b/umtool/app/api/report/takes/pick/route.ts @@ -5,7 +5,10 @@ import { isTakeId } from "@/lib/report/takes.mjs"; export const dynamic = "force-dynamic"; -// "USE THIS TAKE" (release 33). POST { project, take, anyway? } +// "USE THIS TAKE" (release 33). POST { project, take, anyway?, pin? } +// +// `pin` (1 Nov 2026): true pins the pick (a newer whole-cut take is not +// auto-picked over it), false unpins; absent keeps a re-picked take's pin. // // The take's video.manifest.json over the project's, through the manifest // writer (lib/report/manifest.mjs replaceManifest: the auto snapshot @@ -17,13 +20,13 @@ export const dynamic = "force-dynamic"; // was made from -- the pick would throw away what changed since -- until the // operator says `anyway` (a second, explicit click). export async function POST(request: Request) { - const body = (await request.json().catch(() => null)) as { project?: unknown; take?: unknown; anyway?: unknown } | null; + const body = (await request.json().catch(() => null)) as { project?: unknown; take?: unknown; anyway?: unknown; pin?: unknown } | null; if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 }); if (!isTakeId(body.take)) return Response.json({ error: "take must be a take id" }, { status: 400 }); const project = await projectRef(String(body.project ?? "")); if (!project) return Response.json({ error: "no such project" }, { status: 404 }); try { - const r = await pickTake(project, body.take, { anyway: body.anyway === true }); + const r = await pickTake(project, body.take, { anyway: body.anyway === true, pinned: body.pin === true ? true : body.pin === false ? false : undefined }); invalidateProjects(); const historyHref = await pieceHrefOfProject(project.id, { tab: "history" }); return Response.json({ ok: true, ...r, historyHref }, { headers: { "cache-control": "no-store" } }); diff --git a/umtool/app/api/report/timeline/route.ts b/umtool/app/api/report/timeline/route.ts @@ -3,16 +3,23 @@ import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, StructureRefused, + addSection, duplicateEntry, insertEntry, manifestToken, moveEntry, + moveSectionBoundary, + moveToSection, + placeEntries, removeEntry, + removeSection, + sectionsOf, rejectClip, removeWrongSpeaker, removePost, undoStructural, updateFactcheck, + updateSection, updateTeaser, upsertPost, } from "@/lib/report/manifest.mjs"; @@ -43,6 +50,14 @@ export const dynamic = "force-dynamic"; // post-remove { id } // factcheck { factcheck: { verdicts?, stamp?, tally? } | null } // undo {} restore the newest auto snapshot +// place { ids: [id…], before: id | null, section? } a drop on Play's reel strip: before that entry +// (null: the end), the clips joining that section; its own undo point +// section-move { ids: [id…], section, position?: "start" | "end" } clips into a section +// section-add { afterId, label?, color? } new section here (a marker after the clip) +// section-boundary { marker, afterId } drag a boundary (between its neighbours) +// section-remove { marker } the section joins the one before it +// section-set { marker, label?, color? } relabel / recolour a section +// (each section op brings the take patches' markers along: lib/report/patchMarkers.mjs syncSectionMarkers) // // Every op snapshots the manifest first (`revisions/<stamp>-auto-before-<op>`), // is checked by the build's own validators, and on a GENERATED manifest leaves @@ -70,6 +85,8 @@ export async function GET(request: Request) { teasers, posts: Array.isArray(r.manifest.posts) ? r.manifest.posts : [], deckOn: deckOn(render), + // The deck's sections (its markers), for "move to section…" and the section bars. + sections: deckOn(render) ? sectionsOf(r.manifest) : [], factcheck: (render.chrome as { factcheck?: unknown } | undefined)?.factcheck ?? null, factcheckResolved: resolveFactcheck(render), // The stamp's knobs (video knobs): their defaults, bounds and motions, the form's placeholders. @@ -128,8 +145,24 @@ export async function POST(request: Request) { return updateFactcheck(dir, (body.factcheck ?? null) as Record<string, unknown> | null, { token }); case "undo": return undoStructural(dir, { token }); + case "place": + return placeEntries(dir, Array.isArray(body.ids) ? body.ids.map(String) : [id], { + token, + before: typeof body.before === "string" && body.before ? body.before : null, + section: body.section === undefined || body.section === null || body.section === "" ? null : Number(body.section), + }); + case "section-move": + return moveToSection(dir, Array.isArray(body.ids) ? body.ids.map(String) : [id], Number(body.section), { token, position: body.position === "start" ? "start" : "end" }); + case "section-add": + return addSection(dir, String(body.afterId ?? id), { label: typeof body.label === "string" ? body.label : null, color: typeof body.color === "string" ? body.color : null }, { token }); + case "section-boundary": + return moveSectionBoundary(dir, Number(body.marker), String(body.afterId ?? ""), { token }); + case "section-remove": + return removeSection(dir, Number(body.marker), { token }); + case "section-set": + return updateSection(dir, Number(body.marker), Object.fromEntries(["label", "color"].filter((k) => k in body).map((k) => [k, body[k]])), { token }); default: - throw new Error("op must be move, remove, reject, wrong-speaker, duplicate, insert, teaser, post, post-remove, factcheck or undo"); + throw new Error("op must be move, place, remove, reject, wrong-speaker, duplicate, insert, teaser, post, post-remove, factcheck, undo, section-move, section-add, section-boundary, section-remove or section-set"); } }; diff --git a/umtool/app/api/report/trailer-beats/route.ts b/umtool/app/api/report/trailer-beats/route.ts @@ -0,0 +1,96 @@ +import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { + BeatsStale, + TRAILER_LIMITS, + addTrailerBeat, + beatsToken, + introSecondsOf, + moveTrailerBeat, + orderTrailerBeats, + readTrailerBeats, + removeTrailerBeat, + setTrailerSettings, + trailerCandidatesOf, + trailerView, + updateTrailerBeat, +} from "@/lib/report/trailerBeats.mjs"; + +export const dynamic = "force-dynamic"; + +// THE TRAILER'S BEATS (UI notes 2026-10-30, item 11): promo/trailer-beats.json +// through its one writer (lib/report/trailerBeats.mjs), the Trailer page's and +// Add to trailer's -- `umtool trailer-beats` is the CLI's twin. +// +// GET ?project=<id> the view (each beat's length, the running length against +// the limit, beats outside their clip, the cut's order), the +// ★ candidates, the cut's clips, the platform limits, the token +// POST { project, token, op, … } +// add { beat: { id, start, end, label? } | { at, dur }, at? } (default: the cut's order) +// set { index, patch: { start?, end?, at?, dur?, label? } } +// remove { index } +// move { index, to } +// order {} the cut's order +// settings { limit?, xfade?, intro? } null: the default again +// A stale token is a 409. + +const noStore = { "cache-control": "no-store" }; + +async function view(dir: string, manifest: Record<string, unknown>) { + const doc = await readTrailerBeats(dir); + const v = trailerView(manifest, doc, { introSeconds: doc.settings?.intro ? await introSecondsOf(dir) : null }); + const clips = ((manifest.timeline ?? []) as Record<string, unknown>[]) + .filter((e) => e?.type === "clip") + .map((e) => ({ id: String(e.id), start: Number(e.cutStart ?? e.start), end: Number(e.cutEnd ?? e.end) })); + return { ...v, candidates: trailerCandidatesOf(manifest, doc.beats), clips, limits: TRAILER_LIMITS, token: await beatsToken(dir), exists: doc.exists }; +} + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + try { + return Response.json(await view(r.project.dir, r.manifest), { headers: noStore }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/trailer-beats"); + if (refused) return refused; + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return Response.json({ error: "expected JSON" }, { status: 400 }); + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const dir = r.project.dir; + const token = typeof body.token === "string" ? body.token : null; + try { + switch (body.op) { + case "add": + await addTrailerBeat(dir, (body.beat ?? {}) as Record<string, unknown>, { token, at: typeof body.at === "number" ? body.at : null, manifest: r.manifest }); + break; + case "set": + await updateTrailerBeat(dir, Number(body.index), (body.patch ?? {}) as Record<string, unknown>, { token }); + break; + case "remove": + await removeTrailerBeat(dir, Number(body.index), { token }); + break; + case "move": + await moveTrailerBeat(dir, Number(body.index), Number(body.to), { token }); + break; + case "order": + await orderTrailerBeats(dir, r.manifest, { token }); + break; + case "settings": + await setTrailerSettings(dir, Object.fromEntries(["limit", "xfade", "intro"].filter((k) => k in body).map((k) => [k, body[k]])), { token }); + break; + default: + return Response.json({ error: "op must be add, set, remove, move, order or settings" }, { status: 400 }); + } + return Response.json({ ok: true, ...(await view(dir, r.manifest)) }, { headers: noStore }); + } catch (e) { + if (e instanceof BeatsStale) return Response.json({ error: e.message, stale: true }, { status: 409 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} diff --git a/umtool/app/api/report/window/route.ts b/umtool/app/api/report/window/route.ts @@ -1,5 +1,5 @@ import { withEditNotes } from "@/lib/report/guard"; -import { StaleToken, updateClip } from "@/lib/report/manifest.mjs"; +import { MarksOutside, StaleToken, updateClip } from "@/lib/report/manifest.mjs"; import { updateTakeClip } from "@/lib/report/takeEdit.mjs"; import { resolveClip } from "@/lib/report/serve.mjs"; import { refuseCaller } from "@/lib/report/caller"; @@ -59,9 +59,19 @@ export async function PUT(request: Request) { // plays on, in source seconds; empty or null clears it. Checked by the // writer against the clip's window, like the cut. "muteFrom", + // The fix for a window save refused because a stamp's second (claim.at, a mark's at) or the + // mute mark would fall outside the new window, retried in the same write: "first" | "nearest" + // | a source second | "clear" (markFix), "nearest" | "clear" (muteFix). The refusal (400) + // carries `outside` -- each mark's second and where the fixes would put it. + "markFix", + "muteFix", // The clip this one re-plays on purpose (a callback, a flash-forward), so // their overlap is not flagged or trimmed; empty or null clears it. "repeatOf", + // What the walk said that is not a verdict: an editorial note (not a + // correction) and the ★ favourite, a trailer candidate. + "walkNote", + "star", // Seconds taken out of the clip's middle (gaps.mjs): the whole list // (`gaps`, empty clears), one span added (`gapAdd`: {from, to} or // "12.3-15.1"), or the gap holding a source second removed (`gapRemove`). @@ -109,7 +119,8 @@ export async function PUT(request: Request) { }), ); return Response.json( - { ok: true, entry: res.entry, before: res.before, token: res.token, editNotes }, + // `citeFollowed`: the cite / the QR's t= this edit moved with an edge (lib/report/citeFollow.mjs). + { ok: true, entry: res.entry, before: res.before, token: res.token, editNotes, ...(res.citeFollowed ? { citeFollowed: res.citeFollowed } : {}) }, { headers: { "cache-control": "no-store" } }, ); } catch (e) { @@ -119,6 +130,9 @@ export async function PUT(request: Request) { { status: 409 }, ); } + if (e instanceof MarksOutside) { + return Response.json({ error: e.message, outside: { kind: e.kind, window: e.window, marks: e.marks } }, { status: 400 }); + } return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); } } diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -14,6 +14,7 @@ // [--q TEXT] [--sort name|recent] [--json] // umtool show <project> [--json] // umtool check [<project> | --all] [--json] exit 1 on anything blocking +// umtool links <project> [--json] [--fix] do the clip QRs open on their sites (out/links.json) // umtool decisions [--json] // umtool inbox [--all] [--json] the decisions grouped as the inbox ranks them // umtool schedule list | show <id> [--json] the recurring reports (R5), read-only @@ -69,10 +70,15 @@ // [--draft] record it without rendering (walk it first) · --id <id> --promote [--anyway] make it the cut // [--priority] render mode for the take's lifetime: the machine is the render's (AGENTS.md "Render mode") // umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway] +// | ls <project> | relabel <project> <take> <label> | supersede <project> <take> [--by T] [--clear] +// | delete <project> <take> [--dry-run] [--force] take housekeeping // umtool render-mode on [--for 90m] [--note T] | off [--force] | status [--json] render mode: a render gets the machine // umtool render-mode on [--for 90m] [--print-token] -- <cmd …> held while <cmd> runs (its env carries the token) // umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] // [--out NAME] [--dry-run] [--json] a trailer cut from the take's finished master +// umtool trailer-beats <project> [ls | add <clip> [<from>-<to>] | set <n> <from>-<to> | remove <n> | move <n> --to <m> +// | order | limit <s|m:ss|x> | xfade <s> | intro on|off | candidates [--add]] the trailer's beats +// (promo/trailer-beats.json): running length against the limit, beats outside their clip // umtool rulings <project> [import [--dry-run] | set <clip> <verdict> [--reason R] [--match M] | clear <clip>] // the clip deck's montage rulings (release 34) // umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] the clip windows, asked of @@ -378,6 +384,8 @@ async function cmdCheck() { if (d.severity === "info" && !has("--all-severities")) continue; console.log(`${d.severity.toUpperCase().padEnd(8)} ${d.project} ${d.kind} ${d.target}`); console.log(` ${d.why}`); + // The command that settles it, when the row knows one (the UI's action's twin). + if (d.fix) console.log(` fix: ${d.fix}`); } const partial = refs.filter((p) => !decisionsAreComplete(p.kind)).length; console.log( @@ -762,6 +770,10 @@ function usage() { " [--q TEXT] [--sort name|recent] [--json]", " umtool show <project> [--json]", " umtool check [<project>] [--json] exit 1 on anything blocking", + " umtool links <project> [--json] [--fix] do the clip QRs open on their sites? (corpus.json -> slugToPage", + " -> the shard's record; polite, cached; out/links.json, which check reads); exit 1 when one is dead", + " umtool patch-markers <project> [<file>.patch.json] [--fix] [--json] take patches whose deck markers name a", + " clip not in the cut; --fix gives each the after of the cut's marker of the same label", " umtool decisions [--json]", " umtool inbox [--all] [--json] the decisions, grouped and ranked as the inbox shows them", " (--all: the hidden ones on parked/done pieces, and the quiet group)", @@ -775,11 +787,18 @@ function usage() { " attribution too: --title, --date YYYY-MM-DD, --cite, --cite-url, --quote", " --repeat-of <clip> it re-plays that clip on purpose (a callback): their overlap is not flagged or trimmed", " --correction TEXT what the REPORT got wrong here (never rendered)", + " --walk-note TEXT an editorial note from the walk (not a correction; never rendered)", + " --star / --no-star the walk's favourite: a trailer candidate (umtool trailer <p> --candidates)", + " a window edit that leaves --cite (or the citeUrl's t=) more than 5 s before the clip, or", + " after it, moves it to the clip's first second; an explicit --cite moves the QR's t= with it", " --verdict confirmed|incorrect what the walk said; incorrect needs --correction", " --reject <why> [--note TEXT] rejected on the walk, kept in place (`umtool timeline <p> reject`", " takes it out, on record): not-matching|wrong-speaker (fact errors: incorrect, the note its", " correction) or irrelevant|repeats|weak|privacy|other (rejected; other needs --note)", " --cut-start S --cut-end E --lock-cut the cut the video renders", + " --move-stamp first|nearest|<s> | --clear-stamp with --start/--end: a stamp's second (claim.at,", + " a mark's at) the new window would leave outside moves to the first second that plays, the nearest,", + " or <s>, or loses its at -- in the same write; --move-mute nearest | --clear-mute the mute mark's", " --gap FROM-TO (repeatable) cut those source seconds out of the clip's middle: it plays", " as ONE segment of jump cuts (gaps.mjs; inside the cut, ≥ 0.2 s, 0.5 s kept between);", " --gap-remove S the gap holding source second S · --gaps 'A-B,C-D' the whole list ('' clears)", @@ -853,6 +872,9 @@ function usage() { " umtool take <project> --id <id> --promote [--anyway] make this the cut: the take's patch applied to the", " manifest, one undo point (revisions/…-auto-before-promote-take)", " umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]", + " | ls <project> | relabel <project> <take> <label…> | supersede <project> <take> [--by <take>] [--clear]", + " | delete <project> <take> [--dry-run] [--force] take housekeeping: a label fixed, a take folded away", + " as superseded, a take deleted -- refused while a render names it", " umtool render-mode on [--for 90m] [--note T] | off [--force] | status [--json] render mode: a render the", " operator waits for gets the machine (other heavy jobs wait; the editor's transcription and", " download lanes held); `on` is a window for a chain of renders (default 2h)", @@ -862,6 +884,10 @@ function usage() { " umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] [--out NAME]", " a trailer cut from the take's finished master: the master's own frames, so the deck shows the", " whole timeline; beats are clip source seconds or master seconds ([--dry-run] the mapping only)", + " umtool trailer-beats <project> [ls] | add <clip> [<from>-<to>] [--at N] [--label L] | add-raw <at> <dur> | set <n> <from>-<to>", + " | remove <n> | move <n> --to <m> | order | limit <s|m:ss|x|instagram|shorts|tiktok> | xfade <s> | intro on|off", + " | candidates [--add] the trailer's beats (promo/trailer-beats.json, the Trailer page's file): each", + " beat's length, the running length against the platform limit (X 2:20), beats outside their clip", " umtool rulings <project> [--json] | import [--dry-run] | set <clip> keep|cut|not-him|read-aloud [--reason R] [--match M] | clear <clip>", " the clip deck's montage rulings (montage-rulings.json); a render leaves the ruled-out clips out", " umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] [--json]", @@ -965,6 +991,12 @@ const COMMANDS = { // Render mode (2026-10-30): lib/report/renderMode.mjs. "render-mode": async () => process.exit(await (await import("../lib/report/renderMode.mjs")).renderModeCommand(argv.slice(argv.indexOf("render-mode") + 1))), trailer: async () => process.exit(await (await import("../lib/report/trailerCli.mjs")).trailerCommand(argv.slice(argv.indexOf("trailer") + 1))), + // Do the QR links open on their sites (UI notes #8): lib/report/linksCli.mjs. + links: async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linksCommand(argv.slice(argv.indexOf("links") + 1))), + // A take patch's markers back on the cut (UI notes #6): lib/report/linksCli.mjs. + "patch-markers": async () => process.exit(await (await import("../lib/report/linksCli.mjs")).patchMarkersCommand(argv.slice(argv.indexOf("patch-markers") + 1))), + // The trailer's beats, edited (UI notes item 11): lib/report/trailerBeatsCli.mjs. + "trailer-beats": async () => process.exit(await (await import("../lib/report/trailerBeatsCli.mjs")).trailerBeatsCommand(argv.slice(argv.indexOf("trailer-beats") + 1))), // The clip deck's rulings (release 34): lib/report/rulingsCli.mjs. rulings: async () => process.exit(await (await import("../lib/report/rulingsCli.mjs")).rulingsCommand(argv.slice(argv.indexOf("rulings") + 1))), // Fetch windows and stand-ins (release 35 O1): lib/report/fetchCli.mjs, standInsCli.mjs. @@ -1054,11 +1086,31 @@ async function cmdWindow() { ["--lock-end", "lockEnd"], // The cut, pinned against the resolver. `lock` is about the EXTENT. ["--lock-cut", "lockCut"], + // The walk's favourite: a trailer candidate (lib/report/trailerCandidates.mjs). + ["--star", "star"], ]) { if (has(flag)) patch[key] = true; if (has(`--no-${flag.slice(2)}`)) patch[key] = false; } if (val("--note") !== undefined) patch.note = val("--note"); + // A window edit refused because a stamp's second (or the mute mark) would fall outside it: + // the fix in the same write (manifest.mjs MarksOutside) -- the stamp to the first second + // that plays, the nearest one or a named second, or its `at` cleared; the mute mark to the + // nearest second, or cleared. + if (val("--move-stamp") !== undefined) { + const v = String(val("--move-stamp")); + if (!["first", "nearest"].includes(v) && !Number.isFinite(Number(v))) die(`--move-stamp ${v}: first, nearest or a source second`); + patch.markFix = v === "first" || v === "nearest" ? v : Number(v); + } + if (has("--clear-stamp")) { + if (patch.markFix !== undefined) die("--move-stamp or --clear-stamp, not both"); + patch.markFix = "clear"; + } + if (val("--move-mute") !== undefined) { + if (String(val("--move-mute")) !== "nearest") die("--move-mute nearest (the mute mark to the nearest second the clip plays)"); + patch.muteFix = "nearest"; + } + if (has("--clear-mute")) patch.muteFix = "clear"; // Gaps inside the clip (gaps.mjs): seconds taken out of its middle, so it // renders as one segment of jump cuts. `--gap` adds one (repeatable), // `--gap-remove S` takes out the gap holding S, `--gaps` sets the list @@ -1086,6 +1138,9 @@ async function cmdWindow() { ["--cite-url", "citeUrl"], ["--quote", "quote"], ["--correction", "correction"], + // Not attribution: an editorial note from the walk ("THIS IS GOLD") -- not + // a correction, which says the report got a fact wrong. + ["--walk-note", "walkNote"], // Not attribution: the clip this one re-plays on purpose (a callback, a // flash-forward), so its overlap with that clip is neither flagged nor trimmed. ["--repeat-of", "repeatOf"], @@ -1178,6 +1233,12 @@ async function cmdWindow() { if (patch.verdict !== undefined || patch.correction !== undefined) { console.log(` review: ${reviewWords(res.entry)}`); } + if (patch.walkNote !== undefined) console.log(res.entry.walkNote ? ` walk note: ${res.entry.walkNote}` : " walk note cleared"); + if (patch.star !== undefined) console.log(res.entry.star ? " ★ starred — a trailer candidate (umtool trailer <p> --candidates)" : " ★ cleared"); + // The cite follows the edge (lib/report/citeFollow.mjs): said, so a window + // edit that moved the clock or the QR is never silent. + if (res.citeFollowed?.cite) console.log(` cite followed the edge: ${hms(res.citeFollowed.cite.from)} -> ${hms(res.citeFollowed.cite.to)}`); + if (res.citeFollowed?.citeUrl) console.log(` QR followed: ${res.citeFollowed.citeUrl.to}`); if (reject !== undefined) { console.log(` still in the cut: umtool timeline ${p.id} reject ${clipId} ${String(reject).trim()} takes it out, on the record (removed.json)`); } @@ -1191,9 +1252,17 @@ async function cmdWindow() { : ` (generated by ${editNotes.generatedBy}; nothing changed)`, ); } + if (patch.markFix !== undefined) console.log(` stamp: ${patch.markFix === "clear" ? "its second cleared" : `moved (${patch.markFix})`} — ${JSON.stringify(res.entry.claims ?? res.entry.claim ?? null)}`); + if (patch.muteFix !== undefined) console.log(` mute mark: ${res.entry.muteFrom ?? "cleared"}`); console.log(`\nRun resolve-windows to see whether the widener agrees:`); console.log(` node umtool/report-to-video/resolve-windows.mjs ${p.dir}/video.manifest.json`); } catch (e) { + // A stamp (or the mute mark) left outside the new window: say the fixes, in this command's words. + if (e?.name === "MarksOutside" && Array.isArray(e.marks)) { + const m = e.marks[0]; + const flag = e.kind === "mute" ? ["--move-mute nearest", "--clear-mute"] : [`--move-stamp first (${m.first})`, `--move-stamp nearest (${m.nearest})`, "--clear-stamp"]; + die(`${e.message}\n or in the same write: add ${flag.join(", or ")}`); + } die(e?.message ?? String(e)); } } diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -5,7 +5,8 @@ import { rejectionOf } from "@/lib/report/rejectReasons.mjs"; import AnchoredNotes, { notesOn } from "@/components/notes/AnchoredNotes"; import GeneratedBanner from "@/components/notes/GeneratedBanner"; import { useSharedNotes, wroteNotes } from "@/components/notes/NotesProvider"; -import { useCallback, useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { LatestLine, type WorkingCut } from "./review/WhatPlays"; import { createPortal } from "react-dom"; import Link from "next/link"; import { useRouter } from "next/navigation"; @@ -147,6 +148,12 @@ type Clip = { gaps: Span[]; /** "confirmed" / "incorrect" / "rejected", or null for "nobody has looked at this yet". */ verdict: "confirmed" | "incorrect" | "rejected" | null; + /** An editorial note from the walk -- not a correction (a fact error). Never rendered. */ + walkNote: string | null; + /** The walk's favourite (★): a trailer candidate (lib/report/trailerCandidates.mjs). */ + star: boolean; + /** The clip this one re-plays on purpose (a callback, a flash-forward), or null. */ + repeatOf: string | null; /** Why it was rejected (lib/report/rejectReasons.mjs): wrong-speaker under incorrect, a cut reason under rejected. */ reason: string | null; /** The rejection's note (a cut reason's; a fact reason's note is the correction). */ @@ -197,6 +204,7 @@ const ATTRIB = [ ["citeUrl", "citeUrl", "Where the QR points. Empty derives it from the archive. Set it when the clip is cut from a mirror that reads better."], ["quote", "quote", "The words this clip exists for. Not drawn on screen — it is what the cut is checked against."], ["correction", "correction", "On an incorrect clip (rejected as doesn't match or wrong speaker): what the report got wrong — wrong speaker, wrong addressee, wrong date, read by the next report pass. On a confirmed or rejected-as-irrelevant one it is just a note: why the window moved, or something a reader should know. Never rendered."], + ["walkNote", "walk note", "An editorial note from the walk: this is gold, it wants a beat of silence, move it to another section. Not a correction — that says the report got a fact wrong. ★ (s) makes the clip a trailer candidate. Never rendered."], ] as const; type AttribKey = (typeof ATTRIB)[number][0]; @@ -235,6 +243,9 @@ const fromEntry = (prev: Clip, e: Record<string, unknown>): Clip => ({ muteFrom: e.muteFrom == null ? null : Number(e.muteFrom), gaps: Array.isArray(e.gaps) ? (e.gaps as Span[]) : [], verdict: e.verdict === "confirmed" || e.verdict === "incorrect" || e.verdict === "rejected" ? e.verdict : null, + walkNote: (e.walkNote as string) ?? null, + star: e.star === true, + repeatOf: (e.repeatOf as string) ?? null, reason: (e.reason as string) ?? null, rejectNote: (e.rejectNote as string) ?? null, onscreen: (e.onscreen as Onscreen | undefined) ?? null, @@ -309,6 +320,10 @@ export type ClipBenchData = { * if one was (its render does not change when this manifest does). */ fromPlay?: { href: string; take: string | null } | null; + /** Walk → Play: the cut from this clip (the bench opened on its own, not from Play, not a take's). */ + playHere?: string | null; + /** The working cut's name (lib/report/workingCut.mjs): the latest whole-cut take and the edits since it. */ + working?: WorkingCut; /** * WALKING A TAKE (/projects/<p>/takes/<take>/clip/<id>): the clip is the * take's -- the project's manifest with the take's patch applied -- and @@ -513,7 +528,18 @@ type Session = { more?: AudioBufferSourceNode[]; }; -export default function ClipBench({ data }: { data: ClipBenchData }) { +export default function ClipBench({ + data, + navigate, +}: { + data: ClipBenchData; + /** + * Inside Play (components/projects/cutApp/CutApp.tsx): every move this bench makes -- p / n, + * Confirm's advance, Back to the cut -- goes through here, so Play stays mounted and the + * history is the app's. Absent, Next's router. + */ + navigate?: (href: string) => void; +}) { // The project's notes: this clip's row notes, and the edit notes a save on a // generated manifest leaves (the save says so, and they are re-read). const notes = useSharedNotes({ project: data.project }); @@ -554,6 +580,11 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { playheadRef.current = playhead; }, [playhead]); const [note, setNote] = useState<string | null>(null); + // A window save refused because a stamp's second (or the mute mark) would fall outside the new + // window (manifest.mjs MarksOutside): the refused patch, kept to retry with the fix the + // operator picks -- the unsaved trim is never lost. + type Outside = { kind: "mark" | "mute"; window: { start: number; end: number }; marks: { index: number | null; id: string | null; at: number; first: number; nearest: number }[] }; + const [fix, setFix] = useState<{ patch: Record<string, unknown>; outside: Outside } | null>(null); const [busy, setBusy] = useState<string | null>(null); const [dirty, setDirty] = useState(false); const [draft, setDraft] = useState<Record<AttribKey, string>>(() => emptyDraft(data.clip)); @@ -585,7 +616,8 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { const [segPaused, setSegPaused] = useState(true); const [segDur, setSegDur] = useState(0); - const router = useRouter(); + const nextRouter = useRouter(); + const router = useMemo(() => (navigate ? { ...nextRouter, push: (h: string) => navigate(h) } : nextRouter), [navigate, nextRouter]); const video = useRef<HTMLVideoElement | null>(null); // A REF, not state. Two saves can be in flight -- tab out of `title` straight // into `date` and both blur handlers fire -- and the second must carry the @@ -685,8 +717,8 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { // The desk's "Back to the cut" lives in the bench head (BenchTop's slot). const [topSlot, setTopSlot] = useState<Element | null>(null); useEffect(() => { - if (data.fromPlay) setTopSlot(document.querySelector("[data-bench-top-slot]")); - }, [data.fromPlay]); + if (data.fromPlay || data.playHere) setTopSlot(document.querySelector("[data-bench-top-slot]")); + }, [data.fromPlay, data.playHere]); const hrefOf = useCallback( (which: "prev" | "next") => { const id = which === "prev" ? data.prev : data.next; @@ -1497,6 +1529,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { lastSaved.current = j; setBusy(null); if (wroteNotes(j)) void notes.reload(); + setFix(!r.ok && j.outside ? { patch, outside: j.outside as Outside } : null); if (!r.ok) { setNote( j.stale @@ -1525,9 +1558,14 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { } // Re-sync only the fields this save carried, and from what the writer // actually stored -- which is trimmed, rounded, or gone. + // The cite and the QR follow a moved edge (lib/report/citeFollow.mjs): + // their boxes show what the writer stored, and the save says so. + const followed = j.citeFollowed as { cite?: { from: number; to: number }; citeUrl?: { to: string } } | undefined; setDraft((d) => { const out = { ...d }; for (const [k] of ATTRIB) if (patch[k] !== undefined) out[k] = attribValue(next, k); + if (followed?.cite) out.cite = attribValue(next, "cite"); + if (followed?.citeUrl) out.citeUrl = attribValue(next, "citeUrl"); return out; }); // The on-screen pair saves as one value. Each field goes back to what was @@ -1542,7 +1580,13 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { })); } token.current = String(j.token ?? ""); - setNote("saved"); + setNote( + followed?.cite + ? `saved — the cite followed the edge: ${hms(followed.cite.from)} → ${hms(followed.cite.to)}${followed.citeUrl ? ", and the QR with it" : ""}` + : followed?.citeUrl + ? "saved — the QR's t= followed the edge" + : "saved", + ); // The widener's opinion changes when the window does. void refresh(); return true; @@ -1751,6 +1795,17 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { router.push(to); }, [data.fromPlay, dirty, muteMoved, save, windowPatch, router]); + /** + * ★: the walk's favourite, a trailer candidate (lib/report/trailerCandidates.mjs). + * Not a verdict and not a note -- one key (`s`), written at once. + */ + const toggleStar = useCallback(() => { + const on = !clip.star; + void save({ star: on }).then((ok) => { + if (ok) setNote(on ? `★ ${clip.id} — a trailer candidate` : `★ cleared on ${clip.id}`); + }); + }, [clip.star, clip.id, save]); + /** Reject ▾: the reasons (RejectClip) -- on a phone in a sheet, keyboard up; on the desk where the answer sits. */ const rejectClip = useCallback(() => { if (isPhoneNow()) { @@ -2037,6 +2092,11 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { case "X": rejectClip(); break; + // ★ the clip: a favourite, a trailer candidate (not a verdict). + case "s": + case "S": + toggleStar(); + break; // How fast you listen, and whether a clip plays itself on arrival. case "-": case "_": @@ -2124,6 +2184,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { hrefOf, confirmClip, rejectClip, + toggleStar, choosePlayback, mute, mutePick, @@ -2641,6 +2702,17 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { > Reject ▾ <kbd>x</kbd> </button> + <button + type="button" + data-verdict-star={clip.star ? "on" : "off"} + aria-pressed={clip.star} + className={buttonVariants({ variant: clip.star ? "go" : "quiet", size: "md" })} + disabled={!!busy} + onClick={toggleStar} + title="a favourite: the clip becomes a trailer candidate (the Cut tab's ★ list, umtool trailer <p> --candidates). Not a verdict" + > + {clip.star ? "★ Starred" : "☆ Star"} <kbd>s</kbd> + </button> <span data-verdict-state="" className={ @@ -2809,6 +2881,52 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { </ReaderPane> ); + // A refused save's one-click fixes: move the stamp (to the first second that plays, or the + // nearest), or clear its second -- each the same save again, with the fix, in one write. + const wordsAt = (sec: number) => { + const c = cues.find((x) => sec >= x.start && sec < x.end) ?? cues.find((x) => x.start >= sec); + return c ? c.text.replace(/\s+/g, " ").trim().slice(0, 60) : null; + }; + // Drawn twice (the desk's note row, the phone's): each copy its own attributes, so no selector matches both. + const fixBox = (w: "bench" | "walk") => fix ? ( + <div role="group" aria-label="fix the refused save" {...{ [`data-${w}-fix`]: fix.outside.kind }} className="flex flex-wrap items-center gap-1.5 text-[12px]"> + <span className="text-text-2"> + {fix.outside.kind === "mute" ? "The mute mark" : fix.outside.marks.length > 1 ? `${fix.outside.marks.length} stamps` : "The stamp"} at {fix.outside.marks.map((m) => m.at.toFixed(2)).join(", ")} would be outside {fix.outside.window.start.toFixed(2)}–{fix.outside.window.end.toFixed(2)}: + </span> + {(fix.outside.kind === "mark" ? (["first", "nearest"] as const) : (["nearest"] as const)).map((how) => { + const m = fix.outside.marks[0]; + const at = m[how]; + if (how === "nearest" && fix.outside.kind === "mark" && Math.abs(m.nearest - m.first) < 0.005) return null; + const words = wordsAt(at); + return ( + <button + key={how} + type="button" + {...{ [`data-${w}-fix-move`]: how }} + disabled={!!busy} + className={buttonVariants({ variant: "outline", size: "sm" })} + title={words ? `it lands on “${words}”` : undefined} + onClick={() => void save({ ...fix.patch, ...(fix.outside.kind === "mute" ? { muteFix: how } : { markFix: how }) })} + > + Move {fix.outside.kind === "mute" ? "the mark" : "the stamp"} to {at.toFixed(2)} ({how === "first" ? "first second" : "nearest"}){words ? ` — “${words}”` : ""} + </button> + ); + })} + <button + type="button" + {...{ [`data-${w}-fix-clear`]: "" }} + disabled={!!busy} + className={buttonVariants({ variant: "outline", size: "sm" })} + onClick={() => void save({ ...fix.patch, ...(fix.outside.kind === "mute" ? { muteFix: "clear" } : { markFix: "clear" }) })} + > + {fix.outside.kind === "mute" ? "Clear the mute mark" : "Clear the stamp's second (claim.at)"} + </button> + <button type="button" className="ink-link" onClick={() => setFix(null)}> + keep editing + </button> + </div> + ) : null; + // ---- the phone's own pieces (see "THE WALK ON A PHONE", above) ------------- // Each is md:hidden; the desk never draws them. Their data attributes are // their own (`data-walk-*`), so no desk selector ever matches two elements. @@ -2929,12 +3047,23 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { Undo the extension </button> )} + <button + type="button" + data-walk-star={clip.star ? "on" : "off"} + aria-pressed={clip.star} + disabled={!!busy} + onClick={toggleStar} + className={cn(buttonVariants({ variant: clip.star ? "go" : "outline", size: "md" }), "h-11")} + > + {clip.star ? "★ Starred" : "☆ Star"} + </button> {busy && <span className="text-meter">{busy}</span>} {note && ( <span data-walk-said="" className="text-doubt-text"> {note} </span> )} + <span className="md:hidden">{fixBox("walk")}</span> <span data-walk-verdict={verdict} className={cn("ml-auto", verdict === "confirmed" ? "text-kept-text" : verdict === "incorrect" || verdict === "rejected" ? "text-doubt-text" : "text-muted")}> {verdictLabel(clip)} </span> @@ -3112,7 +3241,14 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { ); // The desk's Back to the cut, in the bench head. const deskBack = - data.fromPlay && topSlot + !data.fromPlay && data.playHere && topSlot + ? createPortal( + <a href={data.playHere} data-play-from-here="" className={buttonVariants({ variant: "outline", size: "sm" })} title="Play the cut from this clip (the reel strip, the deck, the notes)"> + ▶ Play the cut from here + </a>, + topSlot, + ) + : data.fromPlay && topSlot ? createPortal( <> <button @@ -3184,11 +3320,28 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { <span className="micro max-md:hidden" data-ready-count=""> ready {data.ready} of {data.needing} needing judgement </span> + {/* The working cut's name: what this bench edits, and the latest take it was made into. */} + {data.working && !data.take && <LatestLine project={data.project} working={data.working} className="max-md:hidden" />} {!data.fetched && ( <span className={cn(badgeVariants({ variant: "state", size: "sm" }), "max-md:order-[21] max-md:self-start")} data-clip-unfetched=""> not fetched yet </span> )} + {/* A deliberate repeat (`repeatOf`): its overlap with that clip is the point. */} + {clip.repeatOf && ( + <span + data-bench-repeat-of={clip.repeatOf} + title={`re-plays ${clip.repeatOf} on purpose (a callback, a flash-forward): their overlap is neither flagged nor trimmed`} + className={cn(badgeVariants({ variant: "info", size: "sm" }), "max-md:order-[21] max-md:self-start")} + > + repeats {clip.repeatOf} + </span> + )} + {clip.star && ( + <span data-bench-star="" title="starred on the walk: a trailer candidate" className={cn(badgeVariants({ variant: "state", size: "sm" }), "max-md:order-[21] max-md:self-start")}> + ★ trailer + </span> + )} {/* The renderer's own line, live. It used to sit four hundred pixels down the page; it is the one string this bench exists to get right, so it heads the screen. */} @@ -3491,6 +3644,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { {note} </span> )} + {fixBox("bench")} </div> {/* ---- the instrument ---- @@ -4213,12 +4367,34 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { return ( <label key={k} className="block" title={why}> <span className="font-mono text-[11px] text-[var(--color-text)]">{label}</span> + {/* A "correction" on a clip whose facts are right is an editorial note + written in the only box there was (the Ember walk: "THIS IS GOLD"): + one press moves it to the walk note, where it belongs. */} + {k === "correction" && + (clip.correction ?? "").trim() && + (clip.verdict === "confirmed" || clip.verdict === "rejected") && + !(clip.walkNote ?? "").trim() && + !changed && ( + <button + type="button" + data-move-to-walk-note="" + disabled={!!busy} + onClick={(e) => { + e.preventDefault(); + void save({ walkNote: clip.correction ?? "", correction: "" }); + }} + className="ml-2 text-[11px] text-signal-text underline" + title="it is an editorial note, not a fact error: moves it to the walk note and clears the correction" + > + move to walk note + </button> + )} {changed && ( <span className="ml-2 text-[11px] text-[var(--color-dirty)]"> unsaved — was {attribValue(clip, k) || "(empty)"} </span> )} - {k === "quote" || k === "correction" ? ( + {k === "quote" || k === "correction" || k === "walkNote" ? ( <textarea data-attrib-field={k} name={k} @@ -4227,7 +4403,9 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { placeholder={ k === "correction" ? "what the report got wrong: speaker, addressee, date, wording…" - : "" + : k === "walkNote" + ? "an editorial note: gold, too long, wants a beat of silence, move it…" + : "" } onChange={(e) => setDraft((d) => ({ ...d, [k]: e.target.value }))} onBlur={() => commit(k)} diff --git a/umtool/components/projects/ClipBenchPage.tsx b/umtool/components/projects/ClipBenchPage.tsx @@ -1,24 +1,11 @@ -import { notFound } from "next/navigation"; -import { projectsHref, clipBenchHref, playHref, takeClipHref, takeWalkHref, takesHref } from "@/lib/hrefs"; import { BenchFrame, BenchTop } from "./bench/BenchShell"; -import ClipBench, { type ClipBenchData } from "./ClipBench"; -import { - clipVerdict, - cuesInWindow, - siblingsOf, - walkOrder, - walkReadiness, -} from "@/lib/projects/report.mjs"; -import { walkNeighbours, walkOf } from "@/lib/report/walkData.mjs"; -import { projectCache, segmentFor, windowVersion, windowsFor } from "@/lib/report/serve.mjs"; -import { FETCH_MAX_PAD } from "@/lib/report/driver.mjs"; -import { deckOn } from "umtool-report-to-video/deck"; -import { pieceHrefOfProject } from "@/lib/pieces/article"; +import ClipBench from "./ClipBench"; +import { clipBenchDataOr404 } from "@/lib/report/benchData"; import type { ProjectRef } from "@/lib/project-types"; -// The server half of the bench: resolve the clip, read what it needs, and hand -// it over. The clip id is validated as a MEMBER of the timeline, never as a -// path -- the same rule every other name that crosses the wire here follows. +// The server half of the bench: lib/report/benchData.ts reads what it needs +// (the same function Play's in-place bench fetches through /api/report/bench), +// and this page draws it in the bench shell. export default async function ClipBenchPage({ project, @@ -36,239 +23,11 @@ export default async function ClipBenchPage({ */ take?: string | null; }) { - // `?all=1`: the walk visits every fetched clip, judged or not. - const all = search.all === "1"; - let walk: Awaited<ReturnType<typeof walkOf>>; - try { - walk = await walkOf(project, { take, all }); - } catch { - notFound(); - } - const manifest = walk.manifest; - const detail = walk.detail; - const entry = detail.entries.find( - (e: { id: string; kind: string }) => e.id === clipId && e.kind === "clip", - ); - if (!entry) notFound(); - - // In WALK order (by source date, each recording's clips together): `p`/`n` - // step through the recordings, not the cut (lib/projects/report.mjs, walkOrder). - const clips = walkOrder(detail.entries) as typeof detail.entries; - const i = clips.findIndex((e: { id: string }) => e.id === clipId); - - // ---- where `p` and `n` go ------------------------------------------------ - // - // The walk visits the clips that still NEED JUDGEMENT and are FETCHED, in - // walk order (by source). A clip nobody can play is a dead end -- there is nothing to - // judge and the only move is to press `n` again -- and one already answered is - // the round trip a walk exists to remove. A URL still opens ANY clip: this - // page renders it, says what it has (or has not) got, and points its links at - // the fetched, unjudged neighbours on either side. (walkData.mjs, the - // reading `umtool walk` prints; `all` keeps the judged ones on it too.) - const readiness = walkReadiness(clips); - const { prev, next } = walkNeighbours(walk.order, walk.onWalk, clipId); - - // One listing of clips-raw for the page: readClipDetail already built one to - // answer `fetched` for every clip, and this is the same question for this one. - const windows = await windowsFor(project, entry, await projectCache(project, manifest)); - // The mtime rides along so a re-render busts the browser's cache: the segment - // is written back to the SAME path, and without it the player would keep - // showing the cut from before the edit. A take's clip has none: the - // project's segments are the project's cut. - const seg = take ? null : await segmentFor(project, clipId); - const widest = windows[0] ?? null; - const view = widest - ? { from: widest.from, to: widest.to } - : { from: Math.max(0, entry.start - 20), to: entry.end + 20 }; - const cues = await cuesInWindow(project.dir, clipId, view.from, view.to, { manifest }); - - const data: ClipBenchData = { - project: project.id, - clip: { - id: entry.id, - video: entry.video, - channel: entry.channel ?? null, - start: entry.start, - end: entry.end, - cite: entry.cite ?? null, - quote: entry.quote ?? null, - note: entry.note ?? null, - correction: entry.correction ?? null, - title: entry.title ?? null, - date: entry.date ?? null, - citeUrl: entry.citeUrl ?? null, - lock: !!entry.lock, - lockStart: !!entry.lockStart, - lockEnd: !!entry.lockEnd, - cutStart: entry.cutStart ?? null, - cutEnd: entry.cutEnd ?? null, - lockCut: !!entry.lockCut, - // The mute mark, from the manifest's own entry: readClipDetail's rows - // carry the fields it reads, and this is not one of them. - muteFrom: - ((manifest.timeline ?? []) as { id: string; muteFrom?: number }[]).find((e) => e.id === clipId) - ?.muteFrom ?? null, - // Seconds cut out of its middle (gaps.mjs), likewise from the manifest's own entry. - gaps: - ((manifest.timeline ?? []) as { id: string; gaps?: { from: number; to: number }[] }[]).find((e) => e.id === clipId) - ?.gaps ?? [], - verdict: - entry.verdict === "confirmed" || entry.verdict === "incorrect" || entry.verdict === "rejected" ? entry.verdict : null, - // Why it was rejected (lib/report/rejectReasons.mjs), from the manifest's own entry. - ...(() => { - const own = ((manifest.timeline ?? []) as { id: string; reason?: unknown; rejectNote?: unknown }[]).find((e) => e.id === clipId); - return { - reason: typeof own?.reason === "string" ? own.reason : null, - rejectNote: typeof own?.rejectNote === "string" ? own.rejectNote : null, - }; - })(), - // From the manifest's own entry: what the on-screen panel says over this - // clip, when somebody has written it. - onscreen: - ((manifest.timeline ?? []) as { id: string; onscreen?: { title?: string; subtitle?: string } }[]).find( - (e) => e.id === clipId, - )?.onscreen ?? null, - }, - // Whether the cut is built with the on-screen panel. Decides whether the - // bench composes a preview of it; the fields are there either way. - deckOn: deckOn(manifest.render ?? {}), - generatedBy: typeof manifest.generatedBy === "string" ? manifest.generatedBy : null, - view, - // `v`: the version of each window's bytes, for the media URLs (serve.mjs, "A REPLACED FILE IS A NEW FILE"). - windows: await Promise.all( - windows.map(async (w: { name: string; from: number; to: number; path: string }) => ({ - name: w.name, - from: w.from, - to: w.to, - v: await windowVersion(w), - })), - ), - proposed: entry.proposed ?? null, - endsSentence: entry.endsSentence ?? null, - noPunctuation: !!entry.noPunctuation, - sourceDuration: entry.duration ?? null, - segment: take ? null : (seg?.rel ?? entry.segment ?? null), - segmentMtime: seg?.mtimeMs ?? null, - // What the header would say with no overrides. Shown beside the fields that - // replace it, because "the archive says 2019" is the whole reason `date` - // exists. - sourceTitle: entry.sourceTitleClean ?? null, - uploadDate: entry.uploadDate ?? null, - sourceChannel: entry.sourceChannel ?? null, - prev: prev, - next: next, - index: i + 1, - total: clips.length, - // The OTHERS, so the bench can add this clip's own answer to the count - // without a reload and without knowing anything about the rest of the cut. - /** The walk's own reading: fetched clips that still need an answer. */ - ready: readiness.ready, - needing: readiness.needing, - /** Is there a cached file holding THIS clip's window, end to end? */ - fetched: !!entry.fetched, - reviewedOthers: clips.filter( - (e: { id: string }) => e.id !== clipId && clipVerdict(e) !== "unreviewed", - ).length, - cues: cues?.cues ?? [], - siblings: siblingsOf(manifest, clipId), - // The project's manifest token, or -- walking a take -- the take's. - token: walk.token, - fetchPad: manifest.render?.fetchPad ?? 3, - // The widest the fetch route will go. The BUTTON has to know it: it names - // the pad it will ask for, and "that is as wide as it goes" is a different - // sentence from a number the server quietly clamps. - maxPad: FETCH_MAX_PAD, - // The widest cached RAW window: it has no chrome burned in, which is what a - // mix is looking at, and it exists as soon as the clip has been fetched - // once. start/end are the window minus the file's own start, because a mix - // spec is relative to the file it names. - mixHref: widest - ? `/tools/mix?${new URLSearchParams({ - // The window's own path; see ReportProject — a window may live in - // the corpus rather than under out/clips-raw. - body: widest.path, - start: (entry.start - widest.from).toFixed(2), - end: (entry.end - widest.from).toFixed(2), - from: project.id, - clip: clipId, - })}` - : null, - }; - - // The piece this view belongs to: the article's when an article claims the project (P4a-2). - // Walking a take, Back is the take's walk (its overview), on the Takes page's side. - const back = take ? takeWalkHref(project.id, take, { all }) : await pieceHrefOfProject(project.id, { tab: "cut" }); - // ---- opened from Play the cut ("Edit this clip") -------------------------- - // - // `?from=play` rides every walk link from here (p / n / Confirm's advance), - // so "Back to the cut" survives walking on; `at` is only ever the clip Play - // was on. Back lands on the PROJECT's cut, positioned by clip id plus the - // offset into it -- never by raw cut seconds, which the edit just moved for - // everything after this clip. A take's render does not change when the - // project's manifest does, so a take's Back is the project's cut too, and - // the bench says so (`take`). - const fromPlay = !take && search.from === "play"; - const playTake = fromPlay && search.take ? search.take : null; - const atRaw = Number(search.at); - const at = fromPlay && Number.isFinite(atRaw) && atRaw > 0 ? atRaw : 0; - const href = (id: string) => - take ? takeClipHref(project.id, take, id, { all }) : clipBenchHref(project.id, id, fromPlay ? { play: { take: playTake } } : {}); - data.walkHrefs = { - prev: prev ? href(prev) : null, - next: next ? href(next) : null, - back, - backLabel: take ? `take ${take}` : project.name, - }; - if (take && walk.take) { - const timeline = (manifest.timeline ?? []) as { id: string }[]; - data.take = { - id: take, - label: walk.take.label, - draft: walk.take.draft, - editable: walk.take.editable, - all, - takesHref: takesHref(project.id), - walkHref: takeWalkHref(project.id, take, { all }), - toggleAllHref: takeClipHref(project.id, take, clipId, { all: !all }), - clipHref: Object.fromEntries(data.siblings.map((sb: { id: string }) => [sb.id, takeClipHref(project.id, take, sb.id, { all })])), - at: timeline.findIndex((e) => e.id === clipId), - entries: timeline.length, - }; - } - data.fromPlay = fromPlay ? { href: playHref(project.id, { clip: clipId, at }), take: playTake } : null; + const { data, top } = await clipBenchDataOr404(project, clipId, { search, take, order: search.order === "cut" ? "cut" : "walk" }); return ( // The bench shell (P4b): its top bar here, the body -- the work, the // verdict bar, the reader -- in ClipBench, which owns their state. - <BenchFrame - kind="clip" - top={ - <BenchTop - trail={ - take - ? [{ href: projectsHref(), label: "Projects" }, { href: takesHref(project.id), label: `${project.name} · takes` }] - : [{ href: projectsHref(), label: "Projects" }] - } - back={{ href: back, label: take ? `take ${take}` : project.name }} - kind={take ? "Take walk" : "Clip bench"} - here={clipId} - // The walk on a phone draws its own place bar (ClipBench). - phone="hidden" - slot={fromPlay} - pos={{ index: i + 1, total: clips.length }} - prev={prev ? { href: href(prev), label: prev, attrs: { "data-clip-nav": "prev" } } : null} - next={next ? { href: href(next), label: next, attrs: { "data-clip-nav": "next" } } : null} - keys={[ - { keys: ["y"], label: "confirm" }, - { keys: ["x"], label: "note" }, - { keys: ["[", "]", ",", "."], label: "nudge" }, - { keys: ["space"], label: "play" }, - { keys: ["p", "n"], label: "walk" }, - ]} - // Which source is playing. - note={`${entry.video}${entry.channel ? ` · ${entry.channel}` : ""}`} - /> - } - > + <BenchFrame kind="clip" top={<BenchTop {...top} />}> <ClipBench data={data} /> </BenchFrame> ); diff --git a/umtool/components/projects/PlayCutPage.tsx b/umtool/components/projects/PlayCutPage.tsx @@ -6,6 +6,7 @@ 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"; +import CutApp from "./cutApp/CutApp"; // `/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 @@ -19,24 +20,27 @@ import PlayCut, { type PlayViewData } from "./review/PlayCut"; export default async function PlayCutPage({ project, take, + bare = false, note, clip, at, }: { project: ProjectRef; take?: string; + /** `?cut=1`: the project's manifest alone, no take's patch (the default is the latest take). */ + bare?: boolean; note?: string; /** `?clip=<id>&at=<s>`: start on that clip, that far into it (the clip bench's "Back to the cut"). */ clip?: string; at?: string; }) { - const [view, back] = await Promise.all([playView(project, { take: take || null }), pieceHrefOfProject(project.id, { tab: "cut" })]); + const [view, back] = await Promise.all([playView(project, { take: take || null, bare }), 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}`} + here={"error" in view || !view.take ? "the manifest" : view.take.defaulted ? `latest · ${view.take.id}` : `take ${view.take.id}`} /> ); if ("error" in view) { @@ -55,8 +59,9 @@ export default async function PlayCutPage({ </BenchFrame> ); } + // Play and the clip bench as ONE app (cutApp/CutApp.tsx): Play stays mounted, the bench opens in place. return ( - <BenchFrame kind="play" top={top}> + <CutApp project={project.id} playTop={top}> <NotesProvider target={{ project: project.id }}> <PlayCut view={view as PlayViewData} @@ -64,6 +69,6 @@ export default async function PlayCutPage({ initialAt={clip ? { clip, at: Number.isFinite(Number(at)) ? Math.max(0, Number(at)) : 0 } : null} /> </NotesProvider> - </BenchFrame> + </CutApp> ); } diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx @@ -12,6 +12,7 @@ import ReviewPage from "./ReviewPage"; import ClipDeckPage from "./ClipDeckPage"; import PlayCutPage from "./PlayCutPage"; import TakeWalkPage from "./TakeWalkPage"; +import TrailerPage from "./TrailerPage"; import { isTakeId } from "@/lib/report/takes.mjs"; // --------------------------------------------------------------------------- @@ -80,7 +81,9 @@ export default async function ProjectView({ 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} clip={search.clip} at={search.at} />; + // `/projects/<project>/trailer` -- the trailer's beats (promo/trailer-beats.json). + if (rest.length === 1 && rest[0] === "trailer") return <TrailerPage project={project} />; + if (rest.length === 1 && rest[0] === "play") return <PlayCutPage project={project} take={search.take} bare={search.cut === "1"} note={search.note} clip={search.clip} at={search.at} />; return notFound(); } case "sweep-report": { diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx @@ -52,6 +52,10 @@ export type Take = { draft?: boolean; /** The walk's last edit to its patch (later than builtAt: the render is older than the take). */ editedAt?: string | null; + /** What a running render names (takeHousekeeping.mjs renderHolds): it is rendering, or a render is made from it. */ + holds?: string[]; + /** The newest whole-cut take of the manifest: the working cut's name (lib/report/workingCut.mjs). */ + latest?: boolean; }; /** A take's work files, as `GET /api/report/takes/prune` measures them (lib/report/takePrune.mjs). */ @@ -76,7 +80,7 @@ type WorkPlan = { }; export type Verdict = "like" | "maybe" | "no"; -export type TakeVerdict = { verdict: Verdict | null; note: string; at: string; picked?: true }; +export type TakeVerdict = { verdict: Verdict | null; note: string; at: string; picked?: true; pinned?: true; superseded?: { by: string | null; at: string } }; const KIND_TONE: Record<Take["kind"], BadgeVariants["variant"]> = { reference: "on", @@ -136,6 +140,9 @@ export default function TakesBench({ children?: React.ReactNode; }) { const [verdicts, setVerdicts] = useState(initial); + // Superseded takes (UI notes item 19) are folded away unless asked for. + const [showSuperseded, setShowSuperseded] = useState(false); + const allIds = groups.flatMap((g) => g.takes.map((t) => ({ id: t.id, label: t.label }))); const [listen, setListen] = useState<string | null>(null); const [ready, setReady] = useState(false); const videos = useRef(new Map<string, HTMLVideoElement>()); @@ -311,10 +318,23 @@ export default function TakesBench({ </button> </span> </div> + {(() => { + const hidden = g.takes.filter((t) => verdicts[t.id]?.superseded).length; + return hidden > 0 ? ( + <p className="mb-2 text-[11px] text-[var(--color-dim)]" data-superseded-count={hidden}> + {hidden} superseded take{hidden === 1 ? "" : "s"} {showSuperseded ? "shown, dimmed" : "folded away"} ·{" "} + <button type="button" data-action="show-superseded" aria-pressed={showSuperseded} onClick={() => setShowSuperseded((v) => !v)} className="ink-link"> + {showSuperseded ? "fold them away" : "show them"} + </button> + </p> + ) : null; + })()} <div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3"> - {g.takes.map((t) => ( + {g.takes.filter((t) => showSuperseded || !verdicts[t.id]?.superseded).map((t) => ( <TakeCard key={t.id} + others={allIds.filter((o) => o.id !== t.id)} + onVerdicts={(v) => setVerdicts(v)} project={project} take={t} src={previewSrc(project, t)} @@ -462,6 +482,8 @@ function TakeWorkLine({ project, work: w, ready, onFreed }: { project: string; w } function TakeCard({ + others, + onVerdicts, project, take: t, src, @@ -477,6 +499,9 @@ function TakeCard({ work, onFreed, }: { + /** The project's other takes: what "superseded by" may name. */ + others: { id: string; label: string }[]; + onVerdicts: (verdicts: Record<string, TakeVerdict>) => void; project: string; take: Take; src: string; @@ -560,6 +585,32 @@ function TakeCard({ setBusy(false); if (r.error) setError(r.error); }; + // Housekeeping (UI notes item 19): relabel, superseded (POST /api/report/takes/housekeeping). + const [relabel, setRelabel] = useState<string | null>(null); + const [supBy, setSupBy] = useState<string>(verdict?.superseded?.by ?? ""); + const housekeeping = async (body: Record<string, unknown>) => { + setBusy(true); + setError(null); + try { + const r = await fetch("/api/report/takes/housekeeping", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, take: t.id, ...body }), + cache: "no-store", + }); + const j = (await r.json().catch(() => ({}))) as { error?: string; verdicts?: Record<string, TakeVerdict> }; + if (!r.ok) { + setError(j.error ?? `HTTP ${r.status}`); + return false; + } + if (j.verdicts) onVerdicts(j.verdicts); + router.refresh(); + return true; + } finally { + setBusy(false); + } + }; + const superseded = verdict?.superseded ?? null; const windowWords = t.window === "full" ? "full cut" : t.window ? `${t.window.at}–${t.window.at + t.window.dur} s` : null; // Walk a take: a draft is walked before it is rendered; a rendered take // walked since says its render is older than it (editedAt after builtAt). @@ -571,7 +622,8 @@ function TakeCard({ data-take={t.id} data-kind={t.kind} data-verdict={current ?? ""} - className="flex flex-col overflow-hidden rounded border bg-[var(--color-panel)]" + data-superseded={superseded ? (superseded.by ?? "") : undefined} + className={`flex flex-col overflow-hidden rounded border bg-[var(--color-panel)] ${superseded ? "opacity-60" : ""}`} style={{ borderColor: `var(--color-${hue ?? "line"})` }} > {t.previewSize != null ? ( @@ -604,7 +656,35 @@ function TakeCard({ )} <div className="flex flex-1 flex-col gap-1.5 px-3 py-2"> <div className="flex flex-wrap items-center gap-2"> - <h3 className="text-[13px] text-[var(--color-text)]">{t.label}</h3> + {relabel === null ? ( + <h3 className="text-[13px] text-[var(--color-text)]" data-take-label=""> + {t.label} + <button type="button" data-action="relabel" disabled={!ready || busy} onClick={() => setRelabel(t.label)} className="ml-1 text-[11px] text-[var(--color-dim)] hover:text-[var(--color-text)]" title="relabel this take (take.json's label)" aria-label={`relabel ${t.id}`}> + ✎ + </button> + </h3> + ) : ( + <span className="inline-flex flex-1 items-center gap-1"> + <input + autoFocus + data-take-relabel={t.id} + value={relabel} + maxLength={200} + onChange={(e) => setRelabel(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Escape") setRelabel(null); + if (e.key === "Enter") void housekeeping({ op: "relabel", label: relabel }).then((ok) => ok && setRelabel(null)); + }} + className="min-w-0 flex-1 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]" + /> + <button type="button" data-action="relabel-save" disabled={busy || !relabel.trim()} onClick={() => void housekeeping({ op: "relabel", label: relabel }).then((ok) => ok && setRelabel(null))} className={buttonVariants({ variant: "go", size: "sm" })}> + Save + </button> + <button type="button" onClick={() => setRelabel(null)} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Cancel + </button> + </span> + )} <span className={badgeVariants({ variant: KIND_TONE[t.kind], size: "sm" })}>{t.kind}</span> <span className="num text-[11px] text-[var(--color-dim)]" suppressHydrationWarning> {t.seconds != null && `${t.seconds.toFixed(1)} s`} @@ -612,9 +692,24 @@ function TakeCard({ {windowWords && ` · ${windowWords}`} {t.quick && " · quick"} </span> + {t.latest && ( + <span data-take-latest="" title="the newest whole-cut take of the manifest: what Play plays, and Re-render remakes" className={badgeVariants({ variant: "on", size: "sm" })}> + latest + </span> + )} {verdict?.picked && ( - <span data-take-picked="" className={badgeVariants({ variant: "on", size: "sm" })}> - picked + <span data-take-picked="" title={`“Use this take” (or a new whole-cut take) made it its group's pick${verdict.pinned ? "; pinned" : ""}`} className={badgeVariants({ variant: "info", size: "sm" })}> + picked{verdict.pinned ? " · pinned" : ""} + </span> + )} + {(t.holds ?? []).length > 0 && ( + <span data-take-held="" title={(t.holds ?? []).join("; ")} className={badgeVariants({ variant: "meter", size: "sm" })}> + {(t.holds ?? []).some((h) => h.startsWith("it is rendering")) ? "rendering now" : "a render is made from it"} + </span> + )} + {superseded && ( + <span data-take-superseded={superseded.by ?? ""} className={badgeVariants({ variant: "state", size: "sm" })}> + superseded{superseded.by ? ` by ${superseded.by}` : ""} </span> )} {t.draft && ( @@ -749,6 +844,27 @@ function TakeCard({ </p> )} <TakeWorkLine project={project} work={work} ready={ready} onFreed={onFreed} /> + <div className="flex flex-wrap items-center gap-1.5 text-[11px]" data-take-housekeeping={t.id}> + {superseded ? ( + <button type="button" data-action="unsupersede" disabled={!ready || busy} onClick={() => void housekeeping({ op: "unsupersede" })} className={buttonVariants({ size: "sm" })}> + Not superseded + </button> + ) : ( + <> + <select data-take-superseded-by={t.id} value={supBy} disabled={!ready || busy || !!verdict?.picked} onChange={(e) => setSupBy(e.target.value)} className="rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 text-[11px]" title={verdict?.picked ? "the picked take is not superseded" : "which take replaces this one"}> + <option value="">by (any later take)</option> + {others.map((o) => ( + <option key={o.id} value={o.id}> + {o.id} + </option> + ))} + </select> + <button type="button" data-action="supersede" disabled={!ready || busy || !!verdict?.picked} onClick={() => void housekeeping({ op: "supersede", by: supBy || null })} className={buttonVariants({ size: "sm" })}> + Mark superseded + </button> + </> + )} + </div> <div className="flex flex-wrap"> <DeletePlan label={`Delete take ${t.id}`} diff --git a/umtool/components/projects/TakesPage.tsx b/umtool/components/projects/TakesPage.tsx @@ -7,9 +7,13 @@ import { listTakes, readVerdicts } from "@/lib/report/takes.mjs"; import { pieceHrefOfProject } from "@/lib/pieces/article"; import type { ProjectRef } from "@/lib/project-types"; import { hashText, lastGroup, loadMontageStyles } from "@/lib/report/takeMaker.mjs"; +import { renderHolds } from "@/lib/report/takeHousekeeping.mjs"; import { fxPresetsFor } from "umtool-report-to-video/fx"; import NewTakePanel from "./NewTakePanel"; import TakesBench, { type Take, type TakeVerdict } from "./TakesBench"; +import { LatestLine } from "./review/WhatPlays"; +import { readWorkingCut } from "@/lib/report/workingCut.mjs"; +import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs"; // `/browse/<project>/takes` -- alternative renders of one part of the cut, // watched side by side and judged like / maybe / no. @@ -35,7 +39,11 @@ export default async function TakesPage({ project }: { project: ProjectRef }) { } catch { effects = []; } - const takes = (listing.takes as Take[]).map((t) => ({ ...t, stale: t.baseHash ? t.baseHash !== current : null })); + // What a running render names (take housekeeping): the card says so, and relabel/delete refuse. + const holds = new Map(await Promise.all((listing.takes as Take[]).map(async (t) => [t.id, await renderHolds(project.dir, t.id)] as const))); + // The working cut's name: the latest whole-cut take and the edits since it (lib/report/workingCut.mjs). + const working = await readWorkingCut(project.dir, { manifestText, resolveNow: async (id) => (await resolveTakeManifest(project.dir, id)).manifest }).catch(() => null); + const takes = (listing.takes as Take[]).map((t) => ({ ...t, stale: t.baseHash ? t.baseHash !== current : null, holds: holds.get(t.id) ?? [], latest: t.id === working?.latest?.id })); const byId = new Map(takes.map((t) => [t.id, t])); const panel = project.kind === "report-video" ? ( @@ -95,7 +103,14 @@ export default async function TakesPage({ project }: { project: ProjectRef }) { project={project.id} groups={listing.groups.map((g) => ({ group: g.group, takes: g.takes.map((t: { id: string }) => byId.get(t.id) as Take) }))} initial={verdicts as Record<string, TakeVerdict>} - head={panel} + head={ + <> + <p className="m-0 text-[12.5px]" data-takes-working=""> + <LatestLine project={project.id} working={working} /> + </p> + {panel} + </> + } > {skipped} </TakesBench> diff --git a/umtool/components/projects/TimelineEditor.tsx b/umtool/components/projects/TimelineEditor.tsx @@ -19,15 +19,27 @@ import { MANIFEST_CHANGED, announceManifestChanged, refusalOf, timelineOp } from // is a structural write (POST /api/report/timeline): snapshotted first, so // "Undo" restores the cut as it was before the last burst of edits. +/** One section of a deck cut (lib/report/sectionEdit.mjs), as the timeline route sends it. */ +export type SectionInfo = { index: number; label: string | null; color: string | null; marker: number | null; clips: string[]; words: string }; + type Ctx = { project: string; busy: boolean; run: (op: string, args: Record<string, unknown>) => Promise<boolean>; dragging: React.MutableRefObject<{ id: string; at: number } | null>; + /** A section boundary being dragged (its marker), else null. */ + draggingBar: React.MutableRefObject<number | null>; + /** The deck's sections ([] without a deck): the row menu's "move to section…". */ + sections: SectionInfo[]; + /** Clips ticked for a multi-clip "move to section…". */ + selected: Set<string>; + toggle: (id: string) => void; }; const TimelineCtx = createContext<Ctx | null>(null); +export const useTimeline = () => useContext(TimelineCtx); const rowOf = (el: EventTarget | null) => (el instanceof Element ? (el.closest("li[data-entry][data-at]") as HTMLLIElement | null) : null); +const barOf = (el: EventTarget | null) => (el instanceof Element ? (el.closest("li[data-section-bar]") as HTMLLIElement | null) : null); const rowKey = (li: HTMLLIElement) => ({ id: li.dataset.entry ?? "", at: Number(li.dataset.at) }); export function TimelineList({ project, count, children }: { project: string; count: number; children: React.ReactNode }) { @@ -39,9 +51,21 @@ export function TimelineList({ project, count, children }: { project: string; co const [error, setError] = useState<string | null>(null); const [over, setOver] = useState<number | null>(null); const dragging = useRef<{ id: string; at: number } | null>(null); + const draggingBar = useRef<number | null>(null); // The entries in order (Add clip's "after"), as the route last said. const [entries, setEntries] = useState<{ id: string; type: string }[]>([]); + const [sections, setSections] = useState<SectionInfo[]>([]); + const [selected, setSelected] = useState<Set<string>>(() => new Set()); + const [bulkTo, setBulkTo] = useState<string>(""); const [adding, setAdding] = useState(false); + const toggle = useCallback((id: string) => { + setSelected((cur) => { + const next = new Set(cur); + if (next.has(id)) next.delete(id); + else next.add(id); + return next; + }); + }, []); const loadToken = useCallback(async () => { const r = await fetch(`/api/report/timeline?project=${encodeURIComponent(project)}`, { cache: "no-store" }); @@ -49,6 +73,7 @@ export function TimelineList({ project, count, children }: { project: string; co if (r.ok) { tokenRef.current = typeof j.token === "string" ? j.token : null; if (Array.isArray(j.timeline)) setEntries(j.timeline); + setSections(Array.isArray(j.sections) ? j.sections : []); } return tokenRef.current; }, [project]); @@ -96,8 +121,15 @@ export function TimelineList({ project, count, children }: { project: string; co }); }; + const moveSelected = () => { + if (!selected.size || bulkTo === "") return; + void run("section-move", { ids: [...selected], section: Number(bulkTo) }).then((ok) => { + if (ok) setSelected(new Set()); + }); + }; + return ( - <TimelineCtx.Provider value={{ project, busy, run, dragging }}> + <TimelineCtx.Provider value={{ project, busy, run, dragging, draggingBar, sections, selected, toggle }}> <div className="mb-1.5 flex flex-wrap items-center gap-2 text-[11px]"> <button type="button" data-testid="timeline-undo" disabled={busy} onClick={() => void run("undo", {})} className={buttonVariants({ size: "sm" })}> Undo last edit @@ -106,8 +138,27 @@ export function TimelineList({ project, count, children }: { project: string; co Add clip </button> <span className="text-[var(--color-dim)]"> - drag ⠿ or <kbd>alt</kbd>+<kbd>↑</kbd>/<kbd>↓</kbd> to move + drag ⠿ or <kbd>alt</kbd>+<kbd>↑</kbd>/<kbd>↓</kbd> to move{sections.length > 1 ? "; drag a section bar onto a clip to move its boundary, a clip onto a bar to move it into that section" : ""} </span> + {sections.length > 0 && selected.size > 0 && ( + <span data-testid="timeline-bulk" className="inline-flex flex-wrap items-center gap-1.5 rounded border border-[var(--color-sel)] px-1.5 py-0.5"> + <span>{selected.size} selected</span> + <select data-testid="timeline-bulk-section" value={bulkTo} onChange={(e) => setBulkTo(e.target.value)} className="rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 text-[11px]"> + <option value="">move to section…</option> + {sections.map((sec) => ( + <option key={sec.index} value={sec.index}> + {sec.words} + </option> + ))} + </select> + <button type="button" data-testid="timeline-bulk-move" disabled={busy || bulkTo === ""} onClick={moveSelected} className={buttonVariants({ variant: "go", size: "sm" })}> + Move + </button> + <button type="button" data-testid="timeline-bulk-clear" disabled={busy} onClick={() => setSelected(new Set())} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Clear + </button> + </span> + )} {busy && <span className="text-[var(--color-dim)]">saving…</span>} {error && ( <span data-testid="timeline-error" className="text-[var(--color-bad)]"> @@ -130,7 +181,20 @@ export function TimelineList({ project, count, children }: { project: string; co data-drop-at={over ?? ""} onKeyDown={onKeyDown} onDragOver={(e) => { + if (draggingBar.current !== null) { + // A boundary goes after a CLIP. + const li = rowOf(e.target); + if (!li || li.dataset.kind !== "clip") return; + e.preventDefault(); + setOver(rowKey(li).at); + return; + } if (!dragging.current) return; + const bar = barOf(e.target); + if (bar) { + e.preventDefault(); + return; + } const li = rowOf(e.target); if (!li) return; e.preventDefault(); @@ -139,9 +203,26 @@ export function TimelineList({ project, count, children }: { project: string; co onDragLeave={() => setOver(null)} onDrop={(e) => { const from = dragging.current; + const marker = draggingBar.current; const li = rowOf(e.target); + const bar = barOf(e.target); dragging.current = null; + draggingBar.current = null; setOver(null); + if (marker !== null) { + if (!li || li.dataset.kind !== "clip") return; + e.preventDefault(); + void run("section-boundary", { marker, afterId: rowKey(li).id }); + return; + } + if (from && bar) { + // A clip dropped on a section's bar opens that section (its start); + // ticked clips go with it. + e.preventDefault(); + const ids = selected.has(from.id) ? [...selected] : [from.id]; + void run("section-move", { ids, section: Number(bar.dataset.sectionBar), position: "start" }).then((ok) => ok && setSelected(new Set())); + return; + } if (!from || !li) return; e.preventDefault(); const to = rowKey(li).at; @@ -277,14 +358,28 @@ export function AddClipForm({ } /** Inside one row: the drag handle and the row's menu. */ -export function RowControls({ id, at }: { id: string; at: number }) { +export function RowControls({ id, at, kind = "entry" }: { id: string; at: number; kind?: string }) { const ctx = useContext(TimelineCtx); const [menu, setMenu] = useState(false); const [insert, setInsert] = useState<string | null>(null); + const [toSection, setToSection] = useState(false); + const [newSection, setNewSection] = useState(false); if (!ctx) return null; - const { busy, run, dragging } = ctx; + const { busy, run, dragging, sections, selected, toggle } = ctx; + const isClip = kind === "clip"; + const mine = isClip ? sections.find((s) => s.clips.includes(id)) : undefined; return ( <> + {isClip && sections.length > 0 && ( + <input + type="checkbox" + data-select-clip={id} + aria-label={`select ${id}`} + checked={selected.has(id)} + onChange={() => toggle(id)} + className="accent-[var(--color-sel)]" + /> + )} <span draggable={!busy} data-drag-handle={id} @@ -311,12 +406,50 @@ export function RowControls({ id, at }: { id: string; at: number }) { <button type="button" data-row-action="insert" disabled={busy} onClick={() => (setMenu(false), setInsert(""))} className="px-1 py-0.5 text-left hover:bg-[var(--color-panel-2)]"> insert clip after </button> + {isClip && sections.length > 0 && ( + <button type="button" data-row-action="to-section" disabled={busy} onClick={() => (setMenu(false), setToSection(true))} className="px-1 py-0.5 text-left hover:bg-[var(--color-panel-2)]"> + move to section… + </button> + )} + {isClip && sections.length > 0 && ( + <button type="button" data-row-action="new-section" disabled={busy} onClick={() => (setMenu(false), setNewSection(true))} className="px-1 py-0.5 text-left hover:bg-[var(--color-panel-2)]"> + new section here + </button> + )} <button type="button" data-row-action="remove" disabled={busy} onClick={() => (setMenu(false), void run("remove", { id, at }))} className="px-1 py-0.5 text-left text-[var(--color-bad)] hover:bg-[var(--color-panel-2)]"> remove </button> </span> )} </span> + {toSection && ( + <span data-testid={`to-section-${id}`} className="inline-flex items-center gap-1 text-[11px]"> + <select + autoFocus + data-testid={`to-section-select-${id}`} + defaultValue="" + onChange={(e) => { + const v = e.target.value; + if (v === "") return; + const ids = selected.has(id) ? [...selected] : [id]; + void run("section-move", { ids, section: Number(v) }).then((ok) => ok && setToSection(false)); + }} + onKeyDown={(e) => e.key === "Escape" && setToSection(false)} + className="rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 text-[11px]" + > + <option value="">move {selected.has(id) && selected.size > 1 ? `${selected.size} clips` : id} to…</option> + {sections.map((sec) => ( + <option key={sec.index} value={sec.index} disabled={sec.index === mine?.index && !(selected.size > 1)}> + {sec.words} + </option> + ))} + </select> + <button type="button" onClick={() => setToSection(false)} className={buttonVariants({ variant: "quiet", size: "sm" })}> + cancel + </button> + </span> + )} + {newSection && <NewSectionForm id={id} busy={busy} onCancel={() => setNewSection(false)} onAdd={(label, color) => run("section-add", { afterId: id, label, color }).then((ok) => ok && setNewSection(false))} />} {insert !== null && ( <input autoFocus @@ -346,3 +479,119 @@ export function RowNotes({ id, project }: { id: string; project: string }) { </div> ); } + +/** "New section here": a label (at most 24 characters, blank for a tick) and a colour. */ +export function NewSectionForm({ + id, + busy, + onCancel, + onAdd, + initial = { label: "", color: "#6fc3ff" }, + verb = "Add section", +}: { + id: string; + busy: boolean; + onCancel: () => void; + onAdd: (label: string, color: string) => void; + initial?: { label: string; color: string }; + verb?: string; +}) { + const [label, setLabel] = useState(initial.label); + const [color, setColor] = useState(initial.color); + const long = [...label.trim()].length > 24; + return ( + <span data-testid={`new-section-${id}`} className="inline-flex flex-wrap items-center gap-1 text-[11px]"> + <input + autoFocus + data-testid={`new-section-label-${id}`} + value={label} + maxLength={40} + placeholder="section label (blank: a tick)" + onChange={(e) => setLabel(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Escape") onCancel(); + if (e.key === "Enter" && !long) onAdd(label.trim(), color); + }} + className="w-48 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[11px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]" + /> + <span className={`num font-mono ${long ? "text-[var(--color-bad)]" : "text-[var(--color-dim)]"}`}>{[...label.trim()].length}/24</span> + <input type="color" data-testid={`new-section-color-${id}`} value={color} onChange={(e) => setColor(e.target.value)} className="h-5 w-7 cursor-pointer rounded border border-[var(--color-line)] bg-transparent" title="the section's colour on the rail" /> + <button type="button" data-testid={`new-section-add-${id}`} disabled={busy || long} onClick={() => onAdd(label.trim(), color)} className={buttonVariants({ variant: "go", size: "sm" })}> + {verb} + </button> + <button type="button" disabled={busy} onClick={onCancel} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Cancel + </button> + </span> + ); +} + +/** + * A section's bar between the rows: its colour, number and label, how many + * clips. Dragged onto a clip, the boundary follows that clip (between its + * neighbours); a clip dropped on it opens the section. Edit relabels and + * recolours it; Remove joins it to the section before. §0 has no marker: no + * handle, no edit. + */ +export function SectionBar({ section }: { section: SectionInfo }) { + const ctx = useContext(TimelineCtx); + const [editing, setEditing] = useState(false); + if (!ctx) return null; + const { busy, run, draggingBar } = ctx; + const k = section.marker; + return ( + <li + data-section-bar={section.index} + data-marker={k ?? ""} + className="flex flex-wrap items-center gap-2 rounded-sm border-l-4 bg-[var(--color-panel-2)] px-2 py-1 text-[11.5px]" + style={{ borderLeftColor: section.color ?? "var(--color-line)" }} + > + {k !== null ? ( + <span + draggable={!busy} + data-bar-handle={k} + title="drag onto a clip: the section starts after it" + onDragStart={(e) => { + draggingBar.current = k; + e.dataTransfer.effectAllowed = "move"; + e.dataTransfer.setData("text/plain", `marker:${k}`); + }} + onDragEnd={() => (draggingBar.current = null)} + className="cursor-grab select-none text-[13px] leading-none text-[var(--color-dim)]" + > + ⇕ + </span> + ) : ( + <span className="w-3" /> + )} + <span className="inline-block h-2.5 w-2.5 rounded-full" style={{ background: section.color ?? "transparent", border: "1px solid var(--color-line)" }} /> + <span className="font-mono text-[var(--color-dim)]">§{section.index}</span> + <span className="text-[var(--color-text)]" data-section-label=""> + {section.label ?? (section.index === 0 ? "the opening" : "(no label)")} + </span> + <span className="micro"> + {section.clips.length} clip{section.clips.length === 1 ? "" : "s"} + </span> + {k !== null && !editing && ( + <span className="ml-auto flex items-center gap-1"> + <button type="button" data-section-edit={k} disabled={busy} onClick={() => setEditing(true)} className={buttonVariants({ variant: "quiet", size: "sm" })}> + edit + </button> + <button type="button" data-section-remove={k} disabled={busy} onClick={() => void run("section-remove", { marker: k })} className={buttonVariants({ variant: "quiet", size: "sm" })} title="remove this boundary: the section joins the one before it"> + remove boundary + </button> + </span> + )} + {k !== null && editing && ( + <NewSectionForm + id={`m${k}`} + busy={busy} + verb="Save" + initial={{ label: section.label ?? "", color: /^#[0-9a-f]{6}$/i.test(section.color ?? "") ? (section.color as string) : "#6fc3ff" }} + onCancel={() => setEditing(false)} + onAdd={(label, color) => void run("section-set", { marker: k, label, color }).then((ok) => ok && setEditing(false))} + /> + )} + </li> + ); +} diff --git a/umtool/components/projects/TrailerBeatsEditor.tsx b/umtool/components/projects/TrailerBeatsEditor.tsx @@ -0,0 +1,313 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; + +// The Trailer page's editor (TrailerPage.tsx): every write is POST +// /api/report/trailer-beats, the one writer `umtool trailer-beats` uses too. + +type Row = { + n: number; + kind: "clip" | "raw"; + id?: string; + start?: number; + end?: number; + at?: number; + dur?: number; + label: string | null; + seconds: number; + running: number; + over: boolean; + clip: { start: number; end: number; at: number; section: string | null; quote: string | null } | null; + problems: string[]; +}; +type View = { + file: string; + limit: number; + xfade: number; + intro: boolean; + introSeconds: number | null; + total: number; + remaining: number; + over: boolean; + inOrder: boolean; + outside: number; + rows: Row[]; + candidates: { id: string; start: number; end: number; quote: string | null; walkNote: string | null }[]; + clips: { id: string; start: number; end: number }[]; + limits: { id: string; label: string; seconds: number }[]; + token: string | null; + exists: boolean; +}; + +const clock = (s: number) => { + if (!Number.isFinite(s)) return "—"; + const m = Math.floor(Math.abs(s) / 60); + const r = Math.abs(s) - m * 60; + return `${s < 0 ? "−" : ""}${m}:${r < 10 ? "0" : ""}${r.toFixed(1)}`; +}; +const input = + "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 font-mono text-[11px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]"; + +export default function TrailerBeatsEditor({ project }: { project: string }) { + const [view, setView] = useState<View | null>(null); + const [error, setError] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + const [addClip, setAddClip] = useState(""); + const [addFrom, setAddFrom] = useState(""); + const [addTo, setAddTo] = useState(""); + + const load = useCallback(async () => { + const r = await fetch(`/api/report/trailer-beats?project=${encodeURIComponent(project)}`, { cache: "no-store" }); + const j = await r.json().catch(() => ({})); + if (!r.ok) setError(j.error ?? `HTTP ${r.status}`); + else setView(j as View); + }, [project]); + useEffect(() => { + void load(); + }, [load]); + + const op = async (name: string, args: Record<string, unknown> = {}) => { + setBusy(true); + setError(null); + try { + const r = await fetch("/api/report/trailer-beats", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, token: view?.token ?? null, op: name, ...args }), + }); + const j = await r.json().catch(() => ({})); + if (!r.ok) { + setError(j.stale ? "the beats changed since this page read them — reloaded; try again" : (j.error ?? `HTTP ${r.status}`)); + if (j.stale) await load(); + return false; + } + setView(j as View); + return true; + } finally { + setBusy(false); + } + }; + + if (!view) return <p className="text-[12px] text-[var(--color-dim)]">{error ?? "reading the beats…"}</p>; + const pct = Math.min(100, (view.total / view.limit) * 100); + const preset = view.limits.find((l) => l.seconds === view.limit)?.id ?? "custom"; + const pickClip = (id: string) => { + setAddClip(id); + const c = view.clips.find((x) => x.id === id); + if (c) { + setAddFrom(String(c.start)); + setAddTo(String(c.end)); + } + }; + + return ( + <div data-testid="trailer-editor" className="space-y-3"> + {/* ---- the running length against the limit ---- */} + <section className="space-y-1.5 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"> + <div className="flex flex-wrap items-baseline gap-3"> + <span data-testid="trailer-total" data-over={view.over ? "1" : "0"} className={`num font-mono text-[20px] ${view.over ? "text-[var(--color-bad)]" : "text-[var(--color-text)]"}`}> + {clock(view.total)} + </span> + <span className="text-[12px] text-[var(--color-dim)]"> + of {clock(view.limit)} ·{" "} + {view.over ? <span className="text-[var(--color-bad)]">over by {(view.total - view.limit).toFixed(1)} s</span> : `${view.remaining.toFixed(1)} s to spare`} · {view.rows.length} beat + {view.rows.length === 1 ? "" : "s"} · crossfade {view.xfade} s{view.intro ? ` · intro ${view.introSeconds ?? "?"} s` : ""} + </span> + {view.outside > 0 && ( + <span data-testid="trailer-outside" className="text-[12px] text-[var(--color-bad)]"> + {view.outside} beat{view.outside === 1 ? "" : "s"} to fix + </span> + )} + </div> + <div className="h-2 w-full overflow-hidden rounded bg-[var(--color-ink)]" aria-hidden> + <div className="h-full" style={{ width: `${pct}%`, background: view.over ? "var(--color-bad)" : "var(--color-sel)" }} /> + </div> + <div className="flex flex-wrap items-center gap-2 text-[11px]"> + <label className="inline-flex items-center gap-1"> + limit + <select + data-testid="trailer-limit" + value={preset} + disabled={busy} + onChange={(e) => { + const l = view.limits.find((x) => x.id === e.target.value); + if (l) void op("settings", { limit: l.seconds }); + }} + className={input} + > + {view.limits.map((l) => ( + <option key={l.id} value={l.id}> + {l.label} + </option> + ))} + {preset === "custom" && <option value="custom">{clock(view.limit)} (custom)</option>} + </select> + </label> + <label className="inline-flex items-center gap-1"> + or seconds + <input + data-testid="trailer-limit-seconds" + defaultValue={view.limit} + key={`limit-${view.limit}`} + onKeyDown={(e) => e.key === "Enter" && void op("settings", { limit: Number((e.target as HTMLInputElement).value) })} + className={`${input} w-16`} + /> + </label> + <label className="inline-flex items-center gap-1"> + crossfade + <input + data-testid="trailer-xfade" + defaultValue={view.xfade} + key={`xfade-${view.xfade}`} + onKeyDown={(e) => e.key === "Enter" && void op("settings", { xfade: Number((e.target as HTMLInputElement).value) })} + className={`${input} w-12`} + /> + s + </label> + <label className="inline-flex items-center gap-1"> + <input type="checkbox" data-testid="trailer-intro" checked={view.intro} disabled={busy} onChange={(e) => void op("settings", { intro: e.target.checked })} /> + open on the brand intro + </label> + <button type="button" data-testid="trailer-order" disabled={busy || view.inOrder} onClick={() => void op("order")} className={buttonVariants({ size: "sm" })} title="put the beats in the order the cut plays their clips"> + {view.inOrder ? "in the cut's order" : "Order by the cut"} + </button> + {error && ( + <span data-testid="trailer-error" className="text-[var(--color-bad)]"> + {error} + </span> + )} + </div> + </section> + + {/* ---- the beats ---- */} + <section> + <h2 className="micro mb-1">beats — {view.file}</h2> + {view.rows.length === 0 ? ( + <p className="text-[12px] text-[var(--color-dim)]">No beats yet: add one below, from the ★ clips, or with Add to trailer in the clip editor.</p> + ) : ( + <ol className="m-0 list-none space-y-1 p-0"> + {view.rows.map((r, i) => ( + <BeatRow key={`${i}:${r.id ?? r.at}:${r.start ?? r.dur}`} row={r} index={i} last={i === view.rows.length - 1} busy={busy} op={op} /> + ))} + </ol> + )} + </section> + + {/* ---- add ---- */} + <section className="flex flex-wrap items-center gap-2 rounded border border-dashed border-[var(--color-line)] px-3 py-2 text-[11px]"> + <span className="micro">add a beat</span> + <select data-testid="trailer-add-clip" value={addClip} onChange={(e) => pickClip(e.target.value)} className={input}> + <option value="">clip…</option> + {view.clips.map((c, k) => ( + <option key={`${c.id}:${k}`} value={c.id}> + {c.id} ({c.start}–{c.end}) + </option> + ))} + </select> + <input data-testid="trailer-add-from" value={addFrom} placeholder="from" onChange={(e) => setAddFrom(e.target.value)} className={`${input} w-20`} /> + – + <input data-testid="trailer-add-to" value={addTo} placeholder="to" onChange={(e) => setAddTo(e.target.value)} className={`${input} w-20`} /> + <button + type="button" + data-testid="trailer-add" + disabled={busy || !addClip || !(Number(addTo) > Number(addFrom))} + onClick={() => void op("add", { beat: { id: addClip, start: Number(addFrom), end: Number(addTo) } }).then((ok) => ok && (setAddClip(""), setAddFrom(""), setAddTo("")))} + className={buttonVariants({ variant: "go", size: "sm" })} + > + Add + </button> + <span className="text-[var(--color-dim)]">it goes where the cut plays it</span> + </section> + + {/* ---- the walk's favourites ---- */} + <section data-testid="trailer-candidates"> + <h2 className="micro mb-1">★ from the walk — {view.candidates.length} not yet beats</h2> + {view.candidates.length === 0 ? ( + <p className="text-[11px] text-[var(--color-dim)]">Star a clip on the walk and it is offered here.</p> + ) : ( + <ul className="m-0 list-none space-y-1 p-0 text-[11.5px]"> + {view.candidates.map((c) => ( + <li key={c.id} data-candidate={c.id} className="flex flex-wrap items-baseline gap-2"> + <span className="font-mono">★ {c.id}</span> + <span className="num font-mono text-[var(--color-dim)]"> + {c.start}–{c.end} + </span> + {c.walkNote && <span className="text-[var(--color-text)]">{c.walkNote}</span>} + {c.quote && <span className="text-[var(--color-dim)]">&ldquo;{c.quote.slice(0, 100)}{c.quote.length > 100 ? "…" : ""}&rdquo;</span>} + <button type="button" disabled={busy} onClick={() => void op("add", { beat: { id: c.id, start: c.start, end: c.end } })} className={buttonVariants({ size: "sm" })}> + Add + </button> + </li> + ))} + </ul> + )} + </section> + <p className="text-[11px] text-[var(--color-dim)]"> + Cut it: <code className="font-mono">umtool trailer {project} --take &lt;take&gt;{view.intro ? " --intro" : ""} --beats &lt;project&gt;/{view.file} --xfade {view.xfade}</code> · the same edits:{" "} + <code className="font-mono">umtool trailer-beats {project}</code> + </p> + </div> + ); +} + +function BeatRow({ row: r, index: i, last, busy, op }: { row: Row; index: number; last: boolean; busy: boolean; op: (name: string, args?: Record<string, unknown>) => Promise<boolean> }) { + const [from, setFrom] = useState(String(r.kind === "clip" ? r.start : r.at)); + const [to, setTo] = useState(String(r.kind === "clip" ? r.end : r.dur)); + const save = () => { + const a = Number(from); + const b = Number(to); + if (!Number.isFinite(a) || !Number.isFinite(b)) return; + if (r.kind === "clip" && (a !== r.start || b !== r.end)) void op("set", { index: i, patch: { start: a, end: b } }); + if (r.kind === "raw" && (a !== r.at || b !== r.dur)) void op("set", { index: i, patch: { at: a, dur: b } }); + }; + const fit = () => { + if (!r.clip) return; + const a = Math.max(r.start ?? r.clip.start, r.clip.start); + const b = Math.min(r.end ?? r.clip.end, r.clip.end); + void op("set", { index: i, patch: b - a >= 0.5 ? { start: a, end: b } : { start: r.clip.start, end: r.clip.end } }); + }; + const bad = r.problems.length > 0; + return ( + <li + data-beat={r.n} + data-beat-id={r.id ?? ""} + data-beat-problem={bad ? "1" : "0"} + data-beat-over={r.over ? "1" : "0"} + className={`flex flex-wrap items-center gap-2 rounded border px-2 py-1 text-[11.5px] ${bad ? "border-[var(--color-bad)]" : "border-[var(--color-line)]"} bg-[var(--color-panel)]`} + > + <span className="num w-5 text-right font-mono text-[var(--color-dim)]">{r.n}</span> + <span className="w-14 font-mono text-[var(--color-text)]">{r.kind === "clip" ? r.id : "master"}</span> + <input data-beat-from={r.n} value={from} onChange={(e) => setFrom(e.target.value)} onBlur={save} onKeyDown={(e) => e.key === "Enter" && save()} className={`${input} w-20`} title={r.kind === "clip" ? "source second it starts at" : "master second"} /> + {r.kind === "clip" ? "–" : "for"} + <input data-beat-to={r.n} value={to} onChange={(e) => setTo(e.target.value)} onBlur={save} onKeyDown={(e) => e.key === "Enter" && save()} className={`${input} w-20`} title={r.kind === "clip" ? "source second it ends at" : "seconds"} /> + <span className="num w-14 text-right font-mono">{r.seconds.toFixed(2)} s</span> + <span className={`num w-14 text-right font-mono ${r.over ? "text-[var(--color-bad)]" : "text-[var(--color-dim)]"}`} title="the trailer's length at the end of this beat"> + {clock(r.running)} + </span> + {r.clip?.section && <span className="micro">{r.clip.section}</span>} + {bad && ( + <span data-beat-problems={r.n} className="text-[var(--color-bad)]"> + {r.problems.join("; ")} + </span> + )} + <span className="ml-auto flex items-center gap-1"> + {bad && r.clip && ( + <button type="button" data-beat-fit={r.n} disabled={busy} onClick={fit} className={buttonVariants({ size: "sm" })} title="pull the beat's edges inside the clip's window"> + fit to clip + </button> + )} + <button type="button" data-beat-up={r.n} disabled={busy || i === 0} onClick={() => void op("move", { index: i, to: i - 1 })} className={buttonVariants({ variant: "quiet", size: "sm" })}> + ↑ + </button> + <button type="button" data-beat-down={r.n} disabled={busy || last} onClick={() => void op("move", { index: i, to: i + 1 })} className={buttonVariants({ variant: "quiet", size: "sm" })}> + ↓ + </button> + <button type="button" data-beat-remove={r.n} disabled={busy} onClick={() => void op("remove", { index: i })} className={buttonVariants({ variant: "quiet", size: "sm" })}> + remove + </button> + </span> + {r.clip?.quote && <span className="basis-full truncate pl-7 text-[11px] text-[var(--color-dim)]">&ldquo;{r.clip.quote}&rdquo;</span>} + </li> + ); +} diff --git a/umtool/components/projects/TrailerPage.tsx b/umtool/components/projects/TrailerPage.tsx @@ -0,0 +1,24 @@ +import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell"; +import { projectsHref } from "@/lib/hrefs"; +import { pieceHrefOfProject } from "@/lib/pieces/article"; +import type { ProjectRef } from "@/lib/project-types"; +import TrailerBeatsEditor from "./TrailerBeatsEditor"; + +// `/projects/<project>/trailer` -- the trailer's beats (UI notes 2026-10-30, +// item 11): promo/trailer-beats.json, its running length against the +// platform's limit, the beats outside their clips, the cut's order, the walk's +// ★ clips -- edited here, or by `umtool trailer-beats`. The trailer itself is +// cut by `umtool trailer <p> --take <t> --beats <that file>`. +export default async function TrailerPage({ project }: { project: ProjectRef }) { + const back = await pieceHrefOfProject(project.id, { tab: "cut" }); + return ( + <BenchFrame + kind="trailer" + top={<BenchTop trail={[{ href: projectsHref(), label: "Projects" }]} back={{ href: back, label: project.id }} kind="Trailer" here="beats" />} + > + <BenchBody workClassName="space-y-3"> + <TrailerBeatsEditor project={project.id} /> + </BenchBody> + </BenchFrame> + ); +} diff --git a/umtool/components/projects/bench/GapsZoom.tsx b/umtool/components/projects/bench/GapsZoom.tsx @@ -100,8 +100,30 @@ export type WaveZoom = ReturnType<typeof useWaveZoom>; const btn = buttonVariants({ variant: "outline", size: "sm" }); -/** − / + / Fit / Zoom to selection, and how much is shown. */ -export function ZoomControls({ zoom, whole, selection, playhead }: { zoom: WaveZoom; whole: Span; selection: Span | null; playhead: number | null }) { +/** + * − / + / Fit / Zoom to selection, and how much is shown. The same controls zoom Play's reel strip + * (ReelStrip.tsx), over cut seconds: `selectionLabel` / `selectionTitle` name what the last button + * zooms to there ("Zoom to clip"), `wholeLabel` what fit shows ("whole cut"), `children` any more. + */ +export function ZoomControls({ + zoom, + whole, + selection, + playhead, + selectionLabel = "Zoom to selection", + selectionTitle = "zoom to the gap you are selecting, else the selection (F)", + wholeLabel = "whole window", + children, +}: { + zoom: WaveZoom; + whole: Span; + selection: Span | null; + playhead: number | null; + selectionLabel?: string; + selectionTitle?: string; + wholeLabel?: string; + children?: React.ReactNode; +}) { const at = playhead != null && playhead >= zoom.vis.from && playhead <= zoom.vis.to ? playhead : null; const shown = zoom.vis.to - zoom.vis.from; return ( @@ -113,7 +135,7 @@ export function ZoomControls({ zoom, whole, selection, playhead }: { zoom: WaveZ <button type="button" data-zoom-in="" className={btn} title="zoom in at the playhead, else the middle (z; Ctrl/⌘ + wheel at the pointer)" onClick={() => zoom.zoomIn(at)}> + </button> - <button type="button" data-zoom-fit="" className={btn} disabled={!zoom.zoomed} title="the whole cached window (f)" onClick={zoom.fit}> + <button type="button" data-zoom-fit="" className={btn} disabled={!zoom.zoomed} title={`the ${wholeLabel} (f)`} onClick={zoom.fit}> Fit </button> <button @@ -121,13 +143,14 @@ export function ZoomControls({ zoom, whole, selection, playhead }: { zoom: WaveZ data-zoom-selection="" className={btn} disabled={!selection} - title="zoom to the gap you are selecting, else the selection (F)" + title={selectionTitle} onClick={() => selection && zoom.to(selection)} > - Zoom to selection + {selectionLabel} </button> + {children} <span className="num text-[11px] text-[var(--color-dim)]" data-zoom-shown={shown.toFixed(2)}> - {zoom.zoomed ? `${shown < 10 ? shown.toFixed(2) : shown.toFixed(1)} s of ${(whole.to - whole.from).toFixed(0)} s` : "whole window"} + {zoom.zoomed ? `${shown < 10 ? shown.toFixed(2) : shown.toFixed(1)} s of ${(whole.to - whole.from).toFixed(0)} s` : wholeLabel} </span> </span> ); @@ -263,7 +286,22 @@ const OVERVIEW_H = 22; * selection, the gaps, and the stretch shown -- dragged to pan, clicked * elsewhere to centre there, pinched (two fingers) to zoom. */ -export function ZoomOverview({ zoom, whole, peaks, sel, gaps }: { zoom: WaveZoom; whole: Span; peaks: Peaks | null; sel: Span; gaps: Span[] }) { +export function ZoomOverview({ + zoom, + whole, + peaks = null, + sel = null, + gaps = [], + paint, +}: { + zoom: WaveZoom; + whole: Span; + peaks?: Peaks | null; + sel?: Span | null; + gaps?: Span[]; + /** Draw the whole yourself (Play's reel strip: its cells and seams) in place of the peaks; `toX` maps a second. */ + paint?: (g: CanvasRenderingContext2D, toX: (t: number) => number, width: number, height: number) => void; +}) { const pal = usePalette(); const box = useRef<HTMLDivElement | null>(null); const canvas = useRef<HTMLCanvasElement | null>(null); @@ -290,8 +328,14 @@ export function ZoomOverview({ zoom, whole, peaks, sel, gaps }: { zoom: WaveZoom g.clearRect(0, 0, width, OVERVIEW_H); const mid = OVERVIEW_H / 2; const toX = (t: number) => ((t - whole.from) / W) * width; - g.fillStyle = alpha(pal.signal, 0.12); - g.fillRect(toX(sel.from), 0, Math.max(1, toX(sel.to) - toX(sel.from)), OVERVIEW_H); + if (paint) { + paint(g, toX, width, OVERVIEW_H); + return; + } + if (sel) { + g.fillStyle = alpha(pal.signal, 0.12); + g.fillRect(toX(sel.from), 0, Math.max(1, toX(sel.to) - toX(sel.from)), OVERVIEW_H); + } if (peaks && peaks.max.length) { const n = peaks.max.length; const pSpan = Math.max(1e-6, peaks.to - peaks.from); @@ -307,7 +351,7 @@ export function ZoomOverview({ zoom, whole, peaks, sel, gaps }: { zoom: WaveZoom } g.fillStyle = alpha(pal.reject, 0.45); for (const gp of gaps) g.fillRect(toX(gp.from), 0, Math.max(1, toX(gp.to) - toX(gp.from)), OVERVIEW_H); - }, [peaks, width, whole.from, W, sel.from, sel.to, gaps, pal]); + }, [peaks, width, whole.from, W, sel?.from, sel?.to, gaps, pal, paint]); const drag = useRef<{ id: number; grab: number } | null>(null); const tAt = (clientX: number) => { diff --git a/umtool/components/projects/cutApp/CutApp.tsx b/umtool/components/projects/cutApp/CutApp.tsx @@ -0,0 +1,232 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"; +import { BenchFrame, BenchTop } from "../bench/BenchShell"; +import ClipBench, { type ClipBenchData } from "../ClipBench"; +import type { BenchTopSpec } from "@/lib/report/benchData"; + +// --------------------------------------------------------------------------- +// PLAY AND WALK AS ONE APP (operator, 1 Nov 2026: "'play the cut' and 'walk +// the cut' have trouble transitioning back and forth ... a core user flow"). +// +// The audit (each side a page load) found Play starting over on every return +// -- the deck composed again, the edges measured again, the sound decoded +// again: 38-61 s on a 127-clip cut -- the take dropped, a second Play pushed +// onto the history, and no way from the bench back to Play at all. +// +// So on `/projects/<p>/play` Play is never unmounted. Edit this clip (E) +// opens the clip bench IN PLACE -- its data from GET /api/report/bench, the +// same function the bench's own page renders from (lib/report/benchData.ts) +// -- with Play hidden and paused under it, everything it had kept: the +// composed deck, the decoded sound, the edges, the strip's zoom, the take. +// The URL moves by history.pushState (`/clip/<id>?from=play&at&order=cut`), +// so Back and Forward step between the two, a reload or a link is the +// server's page as it always was, and history never stacks a second Play: +// "Back to the cut" goes back the entries the app pushed. The bench walks +// the CUT's order here (p / n are the reel strip's neighbours). Back on Play +// the view is read again (router.refresh: the bench may have saved), and +// Play recomposes only when the manifest's token moved. +// --------------------------------------------------------------------------- + +type View = { kind: "play" } | { kind: "clip"; id: string; href: string }; +type Bench = { data: ClipBenchData; top: BenchTopSpec }; + +export type CutAppApi = { + view: View["kind"]; + /** Open the bench on a clip, in place (`href`: the bench's address, from clipBenchHref). */ + openClip: (id: string, href: string) => void; + /** Called each time Play is shown again (Play reads its view again: the bench may have saved). */ + onReturn: (fn: () => void) => () => void; +}; +const Ctx = createContext<CutAppApi | null>(null); +/** Play's handle on the app: null when Play is drawn on its own (a test page, an old build). */ +export const useCutApp = () => useContext(Ctx); + +/** The clip id in a bench address of this project, or null. */ +function clipOf(pathname: string, project: string): string | null { + const base = `/projects/${project.split("/").map(encodeURIComponent).join("/")}/clip/`; + if (!pathname.startsWith(base)) return null; + const rest = pathname.slice(base.length); + return rest && !rest.includes("/") ? decodeURIComponent(rest) : null; +} +const isPlay = (pathname: string, project: string) => pathname === `/projects/${project.split("/").map(encodeURIComponent).join("/")}/play`; + +export default function CutApp({ project, playTop, children }: { project: string; playTop: React.ReactNode; children: React.ReactNode }) { + const router = useRouter(); + const [view, setView] = useState<View>({ kind: "play" }); + const [bench, setBench] = useState<{ key: string; state: "loading" | "ready" | "error"; bench?: Bench; error?: string } | null>(null); + // How many entries the app pushed past Play: "Back to the cut" goes back that many. + const depth = useRef(0); + const seq = useRef(0); + const returns = useRef(new Set<() => void>()); + const onReturn = useCallback((fn: () => void) => { + returns.current.add(fn); + return () => { + returns.current.delete(fn); + }; + }, []); + const returned = useCallback(() => { + for (const fn of returns.current) fn(); + }, []); + + // The neighbours (p / n) are read ahead while you work on a clip, so stepping is instant; a + // clip already visited is always read again (you may have saved on it). + const ahead = useRef(new Map<string, Promise<{ ok: boolean; status: number; body: Bench & { error?: string } }>>()); + const fetchBench = useCallback( + (id: string, href: string) => { + const u = new URL(href, window.location.origin); + const q = new URLSearchParams(u.search); + q.set("project", project); + q.set("clip", id); + q.set("order", "cut"); + return fetch(`/api/report/bench?${q.toString()}`, { cache: "no-store" }).then(async (r) => ({ ok: r.ok, status: r.status, body: (await r.json().catch(() => ({}))) as Bench & { error?: string } })); + }, + [project], + ); + const load = useCallback( + async (id: string, href: string) => { + const mine = ++seq.current; + const pending = ahead.current.get(href) ?? fetchBench(id, href); + ahead.current.clear(); + setBench({ key: href, state: "loading" }); + try { + const r = await pending; + if (mine !== seq.current) return; + if (!r.ok) setBench({ key: href, state: "error", error: r.body.error ?? `HTTP ${r.status}` }); + else { + setBench({ key: href, state: "ready", bench: r.body }); + for (const nb of [r.body.top.next, r.body.top.prev]) { + if (!nb) continue; + const nu = new URL(nb.href, window.location.origin); + const nid = clipOf(nu.pathname, project); + const nh = `${nu.pathname}${nu.search}`; + if (nid && !ahead.current.has(nh)) ahead.current.set(nh, fetchBench(nid, nh).catch((e) => ({ ok: false, status: 0, body: { error: String(e) } as Bench & { error?: string } }))); + } + } + } catch (e) { + if (mine === seq.current) setBench({ key: href, state: "error", error: e instanceof Error ? e.message : String(e) }); + } + }, + [project, fetchBench], + ); + + const withCutOrder = (href: string) => { + const u = new URL(href, window.location.origin); + u.searchParams.set("order", "cut"); + return `${u.pathname}${u.search}`; + }; + const openClip = useCallback( + (id: string, href: string) => { + const h = withCutOrder(href); + depth.current += 1; + window.history.pushState({ ...(window.history.state ?? {}), cutApp: depth.current }, "", h); + setView({ kind: "clip", id, href: h }); + void load(id, h); + }, + [load], + ); + + const backToPlay = useCallback(() => { + if (depth.current > 0) { + const n = depth.current; + depth.current = 0; + window.history.go(-n); + return; + } + // Opened straight on a bench entry (a Forward into it): Play's own address. + window.history.pushState({ ...(window.history.state ?? {}), cutApp: 0 }, "", `/projects/${project}/play`); + setView({ kind: "play" }); + returned(); + }, [project, returned]); + + /** Every move the bench makes: within the app when it is this project's bench or Play, else a page. */ + const navigate = useCallback( + (href: string) => { + const u = new URL(href, window.location.origin); + if (isPlay(u.pathname, project)) { + backToPlay(); + return; + } + const id = clipOf(u.pathname, project); + if (id && !u.pathname.includes("/takes/")) { + openClip(id, `${u.pathname}${u.search}`); + return; + } + router.push(href); + }, + [project, backToPlay, openClip, router], + ); + + // Back / Forward: the address says which view. + useEffect(() => { + const onPop = () => { + const p = window.location.pathname; + const st = (window.history.state ?? {}) as { cutApp?: number }; + if (isPlay(p, project)) { + depth.current = 0; + setView({ kind: "play" }); + setBench(null); + returned(); + return; + } + const id = clipOf(p, project); + if (id) { + depth.current = typeof st.cutApp === "number" ? st.cutApp : depth.current; + const h = `${p}${window.location.search}`; + setView({ kind: "clip", id, href: h }); + void load(id, h); + } + }; + window.addEventListener("popstate", onPop); + return () => window.removeEventListener("popstate", onPop); + }, [project, load, returned]); + + // A click on an in-app link inside the bench (its head's ‹ prev / next ›, a sibling, Back to the cut): the app's. + const onClickCapture = (e: React.MouseEvent) => { + if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; + const a = (e.target as HTMLElement | null)?.closest?.("a[href]") as HTMLAnchorElement | null; + if (!a || a.target === "_blank") return; + const u = new URL(a.href, window.location.origin); + if (u.origin !== window.location.origin) return; + if (isPlay(u.pathname, project) || (clipOf(u.pathname, project) && !u.pathname.includes("/takes/"))) { + e.preventDefault(); + e.stopPropagation(); + navigate(`${u.pathname}${u.search}`); + } + }; + + const api = useMemo<CutAppApi>(() => ({ view: view.kind, openClip, onReturn }), [view.kind, openClip, onReturn]); + const b = bench?.state === "ready" ? bench.bench : null; + return ( + <Ctx.Provider value={api}> + {/* Play: mounted always, hidden (and paused) while the bench is up. */} + <div className={view.kind === "play" ? "contents" : "hidden"} data-cut-app-play={view.kind === "play" ? "shown" : "hidden"}> + <BenchFrame kind="play" top={playTop}> + {children} + </BenchFrame> + </div> + {view.kind === "clip" && ( + <div className="contents" data-cut-app-bench={view.id} onClickCapture={onClickCapture}> + {b ? ( + <BenchFrame kind="clip" top={<BenchTop {...b.top} />}> + <ClipBench key={view.href} data={b.data} navigate={navigate} /> + </BenchFrame> + ) : ( + <div className="flex h-full flex-col"> + <div className="flex items-center gap-3 border-b border-seam px-4 py-2 text-[12px]"> + <button type="button" className="ink-link" data-cut-app-back="" onClick={backToPlay}> + ‹ Back to the cut + </button> + <span className="font-mono text-text">{view.id}</span> + <span className="text-muted" data-cut-app-loading={bench?.state ?? ""}> + {bench?.state === "error" ? `the bench did not open: ${bench.error}` : "opening the bench…"} + </span> + </div> + </div> + )} + </div> + )} + </Ctx.Provider> + ); +} diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -8,11 +8,15 @@ 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, playHref, projectHref, takeWalkHref, takesHref } from "@/lib/hrefs"; +import { clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, playHref, projectHref, takeWalkHref, takesHref, trailerHref } from "@/lib/hrefs"; +import { readTrailerBeats } from "@/lib/report/trailerBeats.mjs"; import { montageClipsOf, momentKeysOf, readRulingsState } from "@/lib/report/montageRulings.mjs"; import FetchUnfetchedButton from "../FetchUnfetchedButton"; import { clipRecord, storedUrlOf } from "@/lib/clips/stored"; -import { RowControls, RowNotes, TimelineList } from "../TimelineEditor"; +import { Fragment } from "react"; +import { deckOn } from "umtool-report-to-video/deck"; +import { sectionModel, sectionWords } from "@/lib/report/sectionEdit.mjs"; +import { RowControls, RowNotes, SectionBar, TimelineList, type SectionInfo } from "../TimelineEditor"; import { Pill, TONE, hms, type ReportTabProps } from "./shared"; import VoiceMatchPanel from "./VoiceMatchPanel"; import FetchWindowsPanel from "./FetchWindowsPanel"; @@ -20,6 +24,7 @@ import BenchPrepPanel from "./BenchPrepPanel"; import { lastStartedRun, projectFetchBody, readFetchRuns } from "@/lib/report/fetchWindows.mjs"; import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; import { clipMomentKey } from "umtool-report-to-video/montage-rulings"; +import { trailerCandidates } from "@/lib/report/trailerCandidates.mjs"; // The Cut tab: the timeline, read back -- the walk into it, its takes, every // entry with what is wrong with it, and the corrections the walk collected. @@ -37,6 +42,8 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor verdict: "confirmed" | "incorrect" | "rejected" | "unreviewed"; }[]; const clips = entries.filter((e) => e.kind === "clip"); + // The walk's ★ clips, as trailer beats (lib/report/trailerCandidates.mjs). + const candidates = trailerCandidates(m); // How much of the cut has been walked. One definition, shared with the bench // header and `umtool corrections`. const review = reviewOf(m); @@ -60,6 +67,8 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor const walkStart = (readiness.readyIds[0] as string | undefined) ?? clips[0]?.id; const showAll = search.all === "1"; const takes = await listTakes(project.dir); + // The trailer's beats (promo/trailer-beats.json): how many, for the Trailer link. + const trailerBeats = await readTrailerBeats(project.dir).then((d) => d.beats.length, () => null); // A montage (clips carrying `montage`) is ruled on the clip deck (release 34): // how many of its instances have no ruling yet. const montage = montageClipsOf(m) as { id: string }[]; @@ -125,132 +134,19 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor return `${toolsMixHref()}?${q}`; }; - return ( - <> - <div className="flex flex-wrap items-start gap-3"> - {/* ---- the way in ---- - Every clip row carries a bench link, which is the right control for - "go to that one" and the wrong one for "start". Reviewing a cut is - watching every clip in order, and the first clip is where that - begins -- so it is a button in the title bar rather than the - eleventh link on a page whose first screenful is decisions, - sources and the build chain. */} - {clips.length > 0 && ( - <div data-walk-cut="" className="flex flex-col items-start gap-1"> - {/* Where the walk STARTS is where the walk goes: the first clip - that still needs an answer and can be played. A cut whose - first clip is already judged (or not fetched) would otherwise - open on a clip `n` immediately leaves. */} - <Link - href={clipBenchHref(project.id, walkStart)} - data-walk-start={walkStart} - className={buttonVariants({ variant: "go", size: "lg" })} - > - Walk the cut → start at {walkStart} - </Link> - <span className="text-[11px] text-[var(--color-dim)]" data-walk-progress=""> - <kbd>p</kbd> / <kbd>n</kbd> move between clips · {review.reviewed} of {review.total}{" "} - reviewed{review.incorrect > 0 ? ` · ${review.incorrect} incorrect` : ""} - {review.rejected > 0 ? ` · ${review.rejected} rejected` : ""} - {" · "} - <span data-ready-count=""> - ready {readiness.ready} of {readiness.needing} needing judgement - </span> - </span> - {/* The bench's first-open work (a long recording's excerpt, the - waveform), made ahead in the background (lib/report/benchPrep.mjs). */} - <BenchPrepPanel project={project.id} /> - </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 - href={clipDeckHref(project.id)} - data-clip-deck-link={unruled} - className={buttonVariants({ size: "lg" })} - > - Clips — {unruled ? `${unruled} of ${montage.length} to rule` : `${montage.length} ruled`} - </Link> - )} - {/* Any other cut's clips -- an assistant's above all -- adjusted by a person (release 35 C2). */} - {montage.length === 0 && clips.length > 0 && ( - <Link - href={clipEditorHref(project.id)} - data-clip-editor-link={assisted.length} - className={buttonVariants({ size: "lg" })} - > - Clip editor — {clips.length} clip{clips.length === 1 ? "" : "s"} - {assisted.length ? ` · ${assisted.length} by the assistant${assistedByYou ? `, ${assistedByYou} edited by you` : ""}` : ""} - </Link> - )} - {/* Alternative renders of part of the cut, judged on their own page -- - where the first one is made, too (release 33's take maker). */} - {takes.exists ? ( - <Link - href={takesHref(project.id)} - data-takes-link={takes.takes.length} - className={buttonVariants({ size: "lg" })} - > - Takes — {takes.takes.length} - </Link> - ) : ( - <Link href={takesHref(project.id)} data-takes-make-link="" className={buttonVariants({ variant: "quiet", size: "sm" })}> - Make takes - </Link> - )} - {/* Walk a take: the drafts first -- a draft exists to be walked before it is rendered. */} - {takes.takes.some((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash) && ( - <span data-walk-takes="" className="flex flex-wrap items-center gap-1.5 text-[11.5px]"> - <span className="micro">walk a take</span> - {[...takes.takes] - .filter((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash) - .sort((a: { draft?: boolean }, b: { draft?: boolean }) => Number(!!b.draft) - Number(!!a.draft)) - .slice(0, 6) - .map((t: { id: string; label: string; draft?: boolean }) => ( - <Link key={t.id} href={takeWalkHref(project.id, t.id)} data-walk-take={t.id} className="ink-link" title={t.label}> - {t.id} - {t.draft ? " (draft)" : ""} - </Link> - ))} - </span> - )} - {clips.length > 0 && ( - <VoiceMatchPanel - project={project.id} - summary={voiceMatchSummary(voices)} - /> - )} - {fetchBody && <FetchWindowsPanel project={project.id} items={fetchBody.items} skipped={fetchBody.skipped} lastRun={fetchBody.lastRun} />} - </div> + // The deck's sections (its markers, lib/report/sectionEdit.mjs): a bar + // opens each one, after the clip its marker follows. + const sectionBars = (() => { + const after = new Map<number, SectionInfo>(); + if (!deckOn(m?.render)) return { opening: null as SectionInfo | null, after, sectionOf: null as Map<string, number> | null }; + const model = sectionModel(m); + const words = (s: (typeof model.sections)[number]) => ({ ...s, words: sectionWords(s) }) as SectionInfo; + model.placed.forEach((p: { pos: number }, i: number) => after.set(p.pos, words(model.sections[i + 1]))); + // Under the deck a row's § is its deck section (the markers), not the legacy `section` field. + return { opening: model.sections.length > 1 ? words(model.sections[0]) : null, after, sectionOf: model.sections.length > 1 ? (model.sectionOf as Map<string, number>) : null }; + })(); - {/* --- the timeline --------------------------------------------- */} - <section> - <h2 className="micro mb-1.5"> - the cut — {entries.length} entries, in array order - </h2> - {/* The gap between "ready" and "needing", closed in one press. Every - row below it that reads "not fetched yet" is one of these, and - closing them one bench page at a time was the loop this replaces. - The default pad is the fetch route's own (±20 s), so a clip - fetched here and a clip fetched from the bench land in the same - file. */} - {pendingFetch.length > 0 && ( - <div className="mb-1.5"> - <FetchUnfetchedButton - project={project.id} - pending={pendingFetch.map((id) => ({ id, padBefore: 20, padAfter: 20 }))} - storedUrlClips={storedPending} - /> - </div> - )} - <TimelineList project={project.id} count={entries.length}> - {entries.map((e, at) => { + const renderRow = (e: (typeof entries)[number], at: number) => { // Anything that is not a CLIP renders generically. The timeline's // vocabulary is open -- one real manifest carries `scroll` and // `chart` beside its cards -- and a page that only knows two words @@ -258,7 +154,6 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor if (e.kind !== "clip") { return ( <li - key={`${e.id}@${at}`} data-entry={e.id} data-kind={e.kind} data-at={at} @@ -283,7 +178,6 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor const midSentence = e.endsSentence === false && !e.lockEnd && !e.lock; return ( <li - key={`${e.id}@${at}`} data-entry={e.id} data-kind="clip" data-at={at} @@ -294,7 +188,7 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-1.5 outline-none focus:border-[var(--color-sel)]" > <div className="flex flex-wrap items-baseline gap-2 text-[12px]"> - <RowControls id={e.id} at={at} /> + <RowControls id={e.id} at={at} kind="clip" /> <span className="font-mono text-[var(--color-text)]">{e.id}</span> <span className="num font-mono text-[11px] text-[var(--color-dim)]"> {e.video} {hms(e.start)}–{hms(e.end)} ({(e.end - e.start).toFixed(1)}s) @@ -302,6 +196,17 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor {e.lock && <Pill>locked</Pill>} {!e.lock && e.lockStart && <Pill>start pinned</Pill>} {!e.lock && e.lockEnd && <Pill>end pinned</Pill>} + {/* The walk's favourite (a trailer candidate) and a deliberate repeat. */} + {e.star === true && ( + <span data-star={e.id} title="starred on the walk: a trailer candidate"> + <Pill tone={TONE.open}>★ trailer</Pill> + </span> + )} + {typeof e.repeatOf === "string" && e.repeatOf && ( + <span data-repeat-of={e.repeatOf} title={`re-plays ${e.repeatOf} on purpose: their overlap is neither flagged nor trimmed`}> + <Pill>repeats {e.repeatOf}</Pill> + </span> + )} {/* The PLAYER's question, and the walk's: is this clip watchable end to end right now. `data-cached` keeps the BUILD's -- the padded window it would fetch -- because @@ -358,7 +263,7 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor > bench → </Link> - <span className="micro">§{e.section ?? 0}</span> + <span className="micro" data-row-section={sectionBars.sectionOf?.get(e.id) ?? e.section ?? 0}>§{sectionBars.sectionOf?.get(e.id) ?? e.section ?? 0}</span> </span> </div> {(showAll || midSentence || e.proposed) && e.quote && ( @@ -367,6 +272,11 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor {String(e.quote).length > 240 ? "…" : ""}&rdquo; </p> )} + {typeof e.walkNote === "string" && e.walkNote && ( + <p data-walk-note-of={e.id} className="mt-1 text-[11px] leading-snug text-text-2"> + <span className="micro">walk note</span> {e.walkNote} + </p> + )} {midSentence && e.endCueText && ( <p className="num mt-1 text-[11px] text-text-2"> cut lands inside: &ldquo;…{String(e.endCueText).trim().slice(-64)}&rdquo; @@ -381,7 +291,146 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor <RowNotes id={e.id} project={project.id} /> </li> ); - })} + }; + + return ( + <> + <div className="flex flex-wrap items-start gap-3"> + {/* ---- the way in ---- + Every clip row carries a bench link, which is the right control for + "go to that one" and the wrong one for "start". Reviewing a cut is + watching every clip in order, and the first clip is where that + begins -- so it is a button in the title bar rather than the + eleventh link on a page whose first screenful is decisions, + sources and the build chain. */} + {clips.length > 0 && ( + <div data-walk-cut="" className="flex flex-col items-start gap-1"> + {/* Where the walk STARTS is where the walk goes: the first clip + that still needs an answer and can be played. A cut whose + first clip is already judged (or not fetched) would otherwise + open on a clip `n` immediately leaves. */} + <Link + href={clipBenchHref(project.id, walkStart)} + data-walk-start={walkStart} + className={buttonVariants({ variant: "go", size: "lg" })} + > + Walk the cut → start at {walkStart} + </Link> + <span className="text-[11px] text-[var(--color-dim)]" data-walk-progress=""> + <kbd>p</kbd> / <kbd>n</kbd> move between clips · {review.reviewed} of {review.total}{" "} + reviewed{review.incorrect > 0 ? ` · ${review.incorrect} incorrect` : ""} + {review.rejected > 0 ? ` · ${review.rejected} rejected` : ""} + {" · "} + <span data-ready-count=""> + ready {readiness.ready} of {readiness.needing} needing judgement + </span> + </span> + {/* The bench's first-open work (a long recording's excerpt, the + waveform), made ahead in the background (lib/report/benchPrep.mjs). */} + <BenchPrepPanel project={project.id} /> + </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 + href={clipDeckHref(project.id)} + data-clip-deck-link={unruled} + className={buttonVariants({ size: "lg" })} + > + Clips — {unruled ? `${unruled} of ${montage.length} to rule` : `${montage.length} ruled`} + </Link> + )} + {/* Any other cut's clips -- an assistant's above all -- adjusted by a person (release 35 C2). */} + {montage.length === 0 && clips.length > 0 && ( + <Link + href={clipEditorHref(project.id)} + data-clip-editor-link={assisted.length} + className={buttonVariants({ size: "lg" })} + > + Clip editor — {clips.length} clip{clips.length === 1 ? "" : "s"} + {assisted.length ? ` · ${assisted.length} by the assistant${assistedByYou ? `, ${assistedByYou} edited by you` : ""}` : ""} + </Link> + )} + {/* Alternative renders of part of the cut, judged on their own page -- + where the first one is made, too (release 33's take maker). */} + {takes.exists ? ( + <Link + href={takesHref(project.id)} + data-takes-link={takes.takes.length} + className={buttonVariants({ size: "lg" })} + > + Takes — {takes.takes.length} + </Link> + ) : ( + <Link href={takesHref(project.id)} data-takes-make-link="" className={buttonVariants({ variant: "quiet", size: "sm" })}> + Make takes + </Link> + )} + {/* The trailer's beats: the running length against the platform's limit (UI notes item 11). */} + {clips.length > 0 && ( + <Link href={trailerHref(project.id)} data-trailer-link={trailerBeats ?? ""} className={buttonVariants({ variant: trailerBeats ? "outline" : "quiet", size: trailerBeats ? "lg" : "sm" })}> + {trailerBeats ? `Trailer — ${trailerBeats} beat${trailerBeats === 1 ? "" : "s"}` : trailerBeats === null ? "Trailer (beats file unreadable)" : "Trailer beats"} + </Link> + )} + {/* Walk a take: the drafts first -- a draft exists to be walked before it is rendered. */} + {takes.takes.some((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash) && ( + <span data-walk-takes="" className="flex flex-wrap items-center gap-1.5 text-[11.5px]"> + <span className="micro">walk a take</span> + {[...takes.takes] + .filter((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash) + .sort((a: { draft?: boolean }, b: { draft?: boolean }) => Number(!!b.draft) - Number(!!a.draft)) + .slice(0, 6) + .map((t: { id: string; label: string; draft?: boolean }) => ( + <Link key={t.id} href={takeWalkHref(project.id, t.id)} data-walk-take={t.id} className="ink-link" title={t.label}> + {t.id} + {t.draft ? " (draft)" : ""} + </Link> + ))} + </span> + )} + {clips.length > 0 && ( + <VoiceMatchPanel + project={project.id} + summary={voiceMatchSummary(voices)} + /> + )} + {fetchBody && <FetchWindowsPanel project={project.id} items={fetchBody.items} skipped={fetchBody.skipped} lastRun={fetchBody.lastRun} />} + </div> + + {/* --- the timeline --------------------------------------------- */} + <section> + <h2 className="micro mb-1.5"> + the cut — {entries.length} entries, in array order + </h2> + {/* The gap between "ready" and "needing", closed in one press. Every + row below it that reads "not fetched yet" is one of these, and + closing them one bench page at a time was the loop this replaces. + The default pad is the fetch route's own (±20 s), so a clip + fetched here and a clip fetched from the bench land in the same + file. */} + {pendingFetch.length > 0 && ( + <div className="mb-1.5"> + <FetchUnfetchedButton + project={project.id} + pending={pendingFetch.map((id) => ({ id, padBefore: 20, padAfter: 20 }))} + storedUrlClips={storedPending} + /> + </div> + )} + <TimelineList project={project.id} count={entries.length}> + {sectionBars.opening && <SectionBar section={sectionBars.opening} />} + {entries.map((e, at) => ( + <Fragment key={`${e.id}@${at}`}> + {renderRow(e, at)} + {sectionBars.after.get(at) && <SectionBar section={sectionBars.after.get(at)!} />} + </Fragment> + ))} </TimelineList> <div className="mt-2"> <Link @@ -393,6 +442,40 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor </div> </section> + {/* --- the walk's ★ clips: the trailer's candidates ------------------- */} + {candidates.length > 0 && ( + <section + data-trailer-candidates={candidates.length} + className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2" + > + <h2 className="micro mb-1.5"> + ★ trailer candidates — {candidates.length} · {candidates.reduce((n, b) => n + b.end - b.start, 0).toFixed(1)} s + </h2> + <ul className="space-y-1"> + {candidates.map((b) => ( + <li key={b.id} data-trailer-candidate={b.id} className="flex flex-wrap items-baseline gap-2 text-[12px] leading-snug"> + <Link href={clipBenchHref(project.id, b.id)} className="ink-link font-mono text-[11px]"> + {b.id} + </Link> + <span className="num font-mono text-[11px] text-[var(--color-dim)]"> + {hms(b.start)}–{hms(b.end)} ({(b.end - b.start).toFixed(1)} s) + </span> + {b.quote && <span className="text-[var(--color-dim)]">&ldquo;{b.quote.slice(0, 120)}{b.quote.length > 120 ? "…" : ""}&rdquo;</span>} + {b.walkNote && <span className="text-text-2">— {b.walkNote}</span>} + </li> + ))} + </ul> + <p className="mt-2 text-[11px] text-[var(--color-dim)]"> + <code className="font-mono">umtool trailer {project.id} --candidates --json</code> prints them as a trailer&rsquo;s{" "} + <code className="font-mono">--beats-json</code>.{" "} + <Link href={trailerHref(project.id)} className="ink-link"> + Add them on the Trailer page + </Link> + . + </p> + </section> + )} + {/* --- corrections ------------------------------------------------ */} {/* Not a decision and not a defect in the CUT: a correction says the diff --git a/umtool/components/projects/report/DecisionSettle.tsx b/umtool/components/projects/report/DecisionSettle.tsx @@ -0,0 +1,110 @@ +"use client"; + +import { useState } from "react"; +import { useRouter } from "next/navigation"; +import { buttonVariants } from "@/components/ui/button"; +import type { Decision } from "@/lib/decisions"; + +// The one-press settle beside a check row (lib/projects/report.mjs `settle`): +// a clip patch through the window writer -- "It's deliberate: b repeats a" +// (repeatOf), "Move to 12:34" (the clock and the QR back on the clip) -- or a +// link check against the sites the QRs open. The row's `fix` is the same +// thing from a terminal; nothing here needs a model. + +export default function DecisionSettle({ + project, + settle, + token = null, +}: { + project: string; + settle: NonNullable<Decision["settle"]>; + token?: string | null; +}) { + const router = useRouter(); + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<string | null>(null); + const [err, setErr] = useState<string | null>(null); + + const run = async () => { + setBusy(true); + setErr(null); + try { + const r = + settle.kind === "patch" + ? await fetch("/api/report/window", { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, clip: settle.clip, ...settle.patch, ...(token ? { token } : {}) }), + }) + : settle.kind === "patch-markers" + ? await fetch("/api/report/patch-markers", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, file: settle.file }), + }) + : await fetch("/api/report/links", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, ...(settle.fix ? { fix: true } : {}) }), + }); + const j = (await r.json().catch(() => ({}))) as { + error?: string; + verdicts?: { ok: number; dead: unknown[]; unverified: unknown[]; archive: number }; + fixed?: { clip: string }[]; + notes?: string[]; + left?: { label: string | null; after: string }[]; + }; + if (!r.ok) { + setErr(j.error ?? `HTTP ${r.status}`); + return; + } + if (settle.kind === "check-links" && j.verdicts) { + const v = j.verdicts; + setSaid(`${j.fixed?.length ? `fixed ${j.fixed.map((f) => f.clip).join(", ")} · ` : ""}${v.ok} of ${v.archive} open · ${v.dead.length} dead · ${v.unverified.length} not verified`); + } else if (settle.kind === "patch-markers") { + const moved = j.notes?.length ?? 0; + const left = j.left ?? []; + setSaid( + `${moved} marker${moved === 1 ? "" : "s"} moved` + + (left.length ? ` · left by hand: ${left.map((l) => `${l.label ? `"${l.label}"` : "a marker"} after ${l.after}`).join(", ")}` : ""), + ); + } else setSaid("saved"); + router.refresh(); + } catch (e) { + setErr(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + + return ( + <span className="inline-flex items-center gap-2" data-settle={settle.kind}> + <button + type="button" + data-settle-button={settle.kind === "patch" ? settle.clip : settle.kind === "patch-markers" ? settle.file : "links"} + disabled={busy} + onClick={() => void run()} + className={buttonVariants({ variant: settle.kind === "patch" ? "go" : "outline", size: "sm" })} + title={ + settle.kind === "patch" + ? `writes ${Object.keys(settle.patch).join(", ")} on ${settle.clip} through the window writer` + : settle.kind === "patch-markers" + ? `each marker of ${settle.file} after a clip that is gone takes the cut's marker of the same label` + : "resolves every clip QR against the site it links (corpus.json → the shard's record), one request at a time per host" + } + > + {busy ? (settle.kind === "check-links" ? "Checking…" : "Saving…") : settle.label} + </button> + {said && !err && ( + <span data-settle-said="" className="text-[11.5px] text-text-2"> + {said} + </span> + )} + {err && ( + <span data-settle-error="" className="text-[11.5px] text-doubt-text"> + {err} + </span> + )} + </span> + ); +} diff --git a/umtool/components/projects/report/OverviewTab.tsx b/umtool/components/projects/report/OverviewTab.tsx @@ -14,6 +14,8 @@ import { decisionsForProject } from "@/lib/projects"; import type { Decision } from "@/lib/decisions"; import type { PieceFrame } from "@/lib/pieces/frame"; import { TONE, hms, type ReportTabProps } from "./shared"; +import DecisionSettle from "./DecisionSettle"; +import { manifestToken } from "@/lib/report/manifest.mjs"; // The Overview tab (canvas "Piece · Overview"): the Next card, then the // piece's decisions and -- when it is an article's video -- the article and @@ -29,6 +31,9 @@ const VIA: Record<string, string> = { export default async function OverviewTab({ project, detail, frame }: ReportTabProps & { frame: PieceFrame }) { const { manifest: m, build, entries } = detail; const decisions = await decisionsForProject(project); + // The settles beside the rows write through the window writer with the + // manifest's token, as every other manifest write does. + const token = await manifestToken(project.dir).catch(() => null); const readme = await readFile(path.join(project.dir, "README.md"), "utf8").catch(() => null); const p = (m.provenance ?? {}) as Record<string, unknown>; const clips = entries.filter((e) => e.kind === "clip"); @@ -53,7 +58,7 @@ export default async function OverviewTab({ project, detail, frame }: ReportTabP <div className="grid grid-cols-1 gap-[22px] lg:grid-cols-[minmax(0,1.25fr)_minmax(0,1fr)]"> <div className="min-w-0 space-y-4"> {/* --- what is wrong, first ------------------------------------- */} - <ProjectDecisions project={project.id} decisions={decisions} /> + <ProjectDecisions project={project.id} decisions={decisions} token={token} /> {iterations && iterations.iterations.length > 0 && article && ( <section data-piece-iterations={iterations.iterations.length}> @@ -152,7 +157,7 @@ export default async function OverviewTab({ project, detail, frame }: ReportTabP } /** A project's decisions, what is waiting first (ReportProject's section, unchanged). */ -export function ProjectDecisions({ project, decisions }: { project: string; decisions: Decision[] }) { +export function ProjectDecisions({ project, decisions, token = null }: { project: string; decisions: Decision[]; token?: string | null }) { return ( <> {decisions.length > 0 && ( @@ -174,7 +179,11 @@ export function ProjectDecisions({ project, decisions }: { project: string; deci </span> <span className="font-mono text-[12px] text-[var(--color-text)]">{d.target}</span> <span className="text-[12px] text-[var(--color-dim)]">{d.why}</span> - <span className="micro ml-auto">{d.kind}</span> + {/* The one-press settle, when the row knows one; `fix` is its terminal twin. */} + {d.settle && <DecisionSettle project={project} settle={d.settle} token={token} />} + <span className="micro ml-auto" data-fix={d.fix ?? undefined} title={d.fix ? `from a terminal: ${d.fix}` : undefined}> + {d.kind} + </span> </li> ))} </ul> diff --git a/umtool/components/projects/review/ClipDeck.tsx b/umtool/components/projects/review/ClipDeck.tsx @@ -930,7 +930,7 @@ function EndCard({ </div> {rerender && ( <p className="m-0 text-[11.5px] text-muted" data-rerender-why={rerender.why}> - {rerender.why === "picked" ? "The picked take" : "The whole-cut take"} + {rerender.why === "latest" ? `The latest take, ${rerender.take}` : rerender.why === "picked" ? "The picked take" : "The newest whole-cut take"} {since !== null ? ` · ${since} ruling${since === 1 ? "" : "s"} since it was made` : ""} </p> )} diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx @@ -8,6 +8,7 @@ import { useSharedNotes } from "@/components/notes/NotesProvider"; import { notesOn } from "@/components/notes/AnchoredNotes"; import { NoteThread } from "@/components/notes/NoteThread"; import type { CitedPlay } from "@/lib/clips/types"; +import { FlashForwardForm, addToTrailer } from "./CutEditing"; import { edgeClock, newClipEntry, nextFreeId, provenanceWords, quoteBetween, roleOf, snapCut, snapPoints, spanQuote } from "@/lib/report/clipEditorModel.mjs"; import type { EditorClip, EditorView, Neighbourhood, Proposal, RenderTarget, Speaker, Turn } from "@/lib/report/clipEditorTypes"; import { cn } from "@/lib/utils"; @@ -271,6 +272,40 @@ export default function ClipEditor({ if (id) choose(id); }); }; + // Flash-forward the selected span (a repeat elsewhere in the cut, or moved + // out of the clip), and Add to trailer (the selection, else the cut): UI + // notes 2026-10-30, items 2 and 11 (CutEditing.tsx). + const [flash, setFlash] = useState<{ from: number; to: number } | null>(null); + const selInClip = !!selection && selection.cutEnd - selection.cutStart >= 0.5 && selection.cutStart >= clip.start - 0.02 && selection.cutEnd <= clip.end + 0.02; + const openFlash = () => { + if (!selection || !selInClip) { + setError(`select the span to flash forward on the strip, inside ${clip.id}'s window (${edgeClock(clip.start)}–${edgeClock(clip.end)})`); + return; + } + setFlash({ from: r2(selection.cutStart), to: r2(selection.cutEnd) }); + }; + const goFlash = (body: Record<string, unknown>) => { + void flush() + .then(() => write(body, body.move ? `Moved ${edgeClock(Number(body.from))}–${edgeClock(Number(body.to))} out of ${clip.id}` : `Flash-forward: a copy of ${edgeClock(Number(body.from))}–${edgeClock(Number(body.to))} put earlier`)) + .then((j) => { + if (!j) return; + setFlash(null); + setSelection(null); + const id = (j.result as { id?: string } | null)?.id; + if (id) setStatus(`${body.move ? "Moved" : "Copied"} to ${id} (a repeat of ${clip.id}${body.move ? ", moved" : ""})`); + }); + }; + const trailer = () => { + const span = selInClip && selection ? { from: r2(selection.cutStart), to: r2(selection.cutEnd) } : { from: cut.cutStart, to: cut.cutEnd }; + void flush().then(async () => { + const r = await addToTrailer(project, clip.id, span); + if (r.ok) { + setError(null); + setStatus(r.message); + } else setError(r.message); + }); + }; + // New clip (from the selection, or the span after this clip): the form, then // the timeline route's `insert` after this clip -- snapshotted, checked by // the build's own validators, an edit note on a generated cut -- and the @@ -697,7 +732,14 @@ export default function ClipEditor({ <button type="button" data-action="new-clip" disabled={busy} onClick={openNewClip} className={buttonVariants({ size: "md" })} title="a new clip from this recording, inserted after this one (drag on the strip to select its span first, or type it)"> {selection ? "New clip from selection…" : "New clip…"} </button> + <button type="button" data-action="flash-forward" disabled={busy || !selInClip} onClick={openFlash} className={buttonVariants({ size: "md" })} title={selInClip ? "a tight copy of the selection earlier in the cut (its attribution and locks copied), or moved out of this clip" : `select a span inside ${clip.id} on the strip first`}> + Flash-forward selection… + </button> + <button type="button" data-action="add-to-trailer" disabled={busy} onClick={trailer} className={buttonVariants({ size: "md" })} title="the selection (else the cut) as a trailer beat — the Trailer page has the running length"> + Add to trailer + </button> </div> + {flash && <FlashForwardForm project={project} clipId={clip.id} span={flash} busy={busy} onCancel={() => setFlash(null)} onGo={goFlash} />} {newClip && ( <NewClipForm key={`${clip.id}:${newClip.cutStart}-${newClip.cutEnd}`} diff --git a/umtool/components/projects/review/CutEditing.tsx b/umtool/components/projects/review/CutEditing.tsx @@ -0,0 +1,149 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { edgeClock } from "@/lib/report/clipEditorModel.mjs"; + +// Two of the clip editor's edits on the CUT rather than the clip (UI notes +// 2026-10-30, items 2 and 11): +// +// Flash-forward this span… a tight copy of the selected seconds put +// earlier (after an entry, or into a section), its +// attribution and locks copied, as a repeat of +// this clip -- or moved out of it (POST +// /api/report/clip-editor { op: "flash-forward" }, +// manifest.mjs flashForward; `umtool timeline <p> +// flash-forward`) +// Add to trailer the selection (else the cut) as a trailer beat, +// in the cut's order (POST /api/report/trailer-beats, +// trailerBeats.mjs; `umtool trailer-beats <p> add`) + +type Section = { index: number; words: string; clips: string[] }; +type Entry = { id: string; type: string }; + +export function FlashForwardForm({ + project, + clipId, + span, + busy, + onCancel, + onGo, +}: { + project: string; + clipId: string; + span: { from: number; to: number }; + busy: boolean; + onCancel: () => void; + onGo: (body: Record<string, unknown>) => void; +}) { + const [entries, setEntries] = useState<Entry[]>([]); + const [sections, setSections] = useState<Section[]>([]); + const [where, setWhere] = useState<"after" | "section">("after"); + const [after, setAfter] = useState<string>(""); + const [section, setSection] = useState<string>(""); + const [move, setMove] = useState(false); + // A choice made before the sections came back is the person's: the default never overrides it. + const touched = useRef(false); + useEffect(() => { + let live = true; + void fetch(`/api/report/timeline?project=${encodeURIComponent(project)}`, { cache: "no-store" }) + .then((r) => r.json()) + .then((j: { timeline?: Entry[]; sections?: Section[] }) => { + if (!live) return; + const tl = Array.isArray(j.timeline) ? j.timeline : []; + setEntries(tl); + const secs = Array.isArray(j.sections) ? j.sections : []; + setSections(secs); + // A flash-forward goes EARLIER: by default, the start of the section this clip is in. + const mine = secs.find((s) => s.clips.includes(clipId)); + if (mine && secs.length > 1 && !touched.current) { + setWhere("section"); + setSection(String(mine.index)); + } + }) + .catch(() => {}); + return () => { + live = false; + }; + }, [project, clipId]); + const input = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[11px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]"; + const mineAt = entries.findIndex((e) => e.id === clipId); + const go = () => + onGo({ + op: "flash-forward", + clip: clipId, + from: span.from, + to: span.to, + move, + ...(where === "section" && section !== "" ? { section: Number(section), position: "start" } : { after: after || null }), + }); + return ( + <div data-testid="flash-forward-form" className="space-y-1.5 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-2 text-[11.5px]"> + <div className="flex flex-wrap items-center gap-2"> + <span className="micro">flash-forward</span> + <span className="num font-mono"> + {clipId} {edgeClock(span.from)}–{edgeClock(span.to)} ({(span.to - span.from).toFixed(1)} s) + </span> + </div> + <div className="flex flex-wrap items-center gap-2"> + {sections.length > 1 && ( + <label className="inline-flex items-center gap-1"> + <input type="radio" name="ff-where" checked={where === "section"} onChange={() => ((touched.current = true), setWhere("section"))} data-testid="ff-where-section" /> + at the start of + <select data-testid="ff-section" value={section} onChange={(e) => ((touched.current = true), setSection(e.target.value), setWhere("section"))} className={input}> + {sections.map((s) => ( + <option key={s.index} value={s.index}> + {s.words} + </option> + ))} + </select> + </label> + )} + <label className="inline-flex items-center gap-1"> + <input type="radio" name="ff-where" checked={where === "after"} onChange={() => ((touched.current = true), setWhere("after"))} data-testid="ff-where-after" /> + after + <select data-testid="ff-after" value={after} onChange={(e) => ((touched.current = true), setAfter(e.target.value), setWhere("after"))} className={input}> + <option value="">(the start)</option> + {entries.map((e, i) => ( + <option key={`${e.id}:${i}`} value={e.id}> + {e.id} · {e.type} + {i >= mineAt && mineAt >= 0 ? " (later: a callback)" : ""} + </option> + ))} + </select> + </label> + </div> + <label className="inline-flex items-center gap-1" title="take the span out of this clip (it must sit at one of its edges); the clip keeps the rest — otherwise a copy, marked as a deliberate repeat"> + <input type="checkbox" data-testid="ff-move" checked={move} onChange={(e) => setMove(e.target.checked)} /> + move it out of {clipId} (not a repeat) + </label> + <div className="flex flex-wrap items-center gap-2"> + <button type="button" data-testid="ff-go" disabled={busy} onClick={go} className={buttonVariants({ variant: "go", size: "sm" })}> + {move ? "Move the span" : "Copy the span"} + </button> + <button type="button" disabled={busy} onClick={onCancel} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Cancel + </button> + <span className="text-[var(--color-dim)]">the title, date, cite, QR link, quote, speakers and locks go with it</span> + </div> + </div> + ); +} + +/** Add the span to the trailer's beats; says where it landed and the running length. */ +export async function addToTrailer(project: string, clipId: string, span: { from: number; to: number }): Promise<{ ok: boolean; message: string }> { + const read = await fetch(`/api/report/trailer-beats?project=${encodeURIComponent(project)}`, { cache: "no-store" }).then((r) => r.json()).catch(() => ({})); + const r = await fetch("/api/report/trailer-beats", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, token: read.token ?? null, op: "add", beat: { id: clipId, start: span.from, end: span.to } }), + }); + const j = (await r.json().catch(() => ({}))) as { error?: string; rows?: { id?: string; start?: number; n: number }[]; total?: number; limit?: number; over?: boolean }; + if (!r.ok) return { ok: false, message: j.error ?? `HTTP ${r.status}` }; + const row = j.rows?.find((x) => x.id === clipId && Math.abs((x.start ?? 0) - span.from) < 0.01); + const clock = (s: number) => `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, "0")}`; + return { + ok: true, + message: `Added to the trailer${row ? ` as beat ${row.n}` : ""}: ${clock(j.total ?? 0)} of ${clock(j.limit ?? 140)}${j.over ? " — OVER the limit" : ""}`, + }; +} diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -1,13 +1,12 @@ "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 { clipBenchHref, playHref } from "@/lib/hrefs"; +import { clipBenchHref } 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"; @@ -20,8 +19,12 @@ import { DeckFrame, FeedOverlay, ModuleLayers, PostsOverlay, postsWindowAt, type import { usePlayEngine } from "./playEngine/usePlayEngine"; import { useRenderCuts, type RenderCuts } from "./playEngine/useRenderCuts"; import type { EngineInfo, MediaRef } from "./playEngine/engine"; -import ReelStrip, { type StripCounter } from "./ReelStrip"; +import ReelStrip, { type StripCounter, type StripEdit } from "./ReelStrip"; +import { useWaveZoom, ZoomControls } from "../bench/GapsZoom"; +import { followVis, itemSections } from "@/lib/report/stripDrag.mjs"; import RejectClip from "./RejectClip"; +import WhatPlays, { type WorkingCut } from "./WhatPlays"; +import { useCutApp } from "../cutApp/CutApp"; import { ClipExportButtons, ClipExportStatus, useClipExport } from "../ClipExport"; // --------------------------------------------------------------------------- @@ -113,9 +116,18 @@ export type PlayEntry = { export type PlayViewData = { project: string; title: string; - take: { id: string; label: string; summary: string; made: boolean; from: string } | null; + take: { id: string; label: string; summary: string; made: boolean; from: string; ownTimeline?: boolean; defaulted?: boolean } | null; note: string | null; takes: { id: string; label: string; made: boolean }[]; + /** The working cut's name: the latest whole-cut take, the edits since, the pick (lib/report/workingCut.mjs). */ + working?: WorkingCut; + /** The project's sections (the deck's markers) and each clip's: where a drop on the strip lands. */ + sections?: { index: number; label: string | null; color: string | null; marker: number | null; count: number }[]; + sectionOf?: Record<string, number>; + /** The manifest's token when the view was read: a reorder from a stale view is refused, not lost. */ + token?: string; + /** The take's patch sets its own sections (markers out of step with the cut's): a drop changes the cut, not them. */ + sectionsDiffer?: boolean; counter: { verdicts: { id: string; label: string }[]; stamps: { landed: number; verdict: string; count: number }[] }; markers: { after: string; label: string }[]; leadIn: number; @@ -166,6 +178,8 @@ const KEYS: { keys: string; what: string }[] = [ { keys: "[ ]", what: "previous / next note" }, { keys: "M", what: "note at the playhead" }, { keys: "E", what: "edit this clip on the bench (Back returns here)" }, + { keys: "z Z f F", what: "the strip: zoom in / out at the playhead, fit, zoom to this clip (Ctrl/⌘ + wheel at the pointer)" }, + { keys: "Alt+← →", what: "on a focused cell: move it one place (at a seam, into the next section first)" }, { keys: "X then 1–7", what: "reject this clip, and why (doesn't match, wrong speaker, irrelevant, repeats, weak, privacy, other)" }, { 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)" }, @@ -210,7 +224,7 @@ const STRIP_H = 120; const timecode = (t: number) => `${runningTime(t)}.${Math.floor(((Math.max(0, t) % 1) + 1e-9) * 10)}`; export default function PlayCut({ - view, + view: served, initialNote, initialAt = null, }: { @@ -220,8 +234,41 @@ export default function PlayCut({ initialAt?: { clip: string; at: number } | null; }) { const router = useRouter(); + // THE VIEW, read again in place (GET /api/report/play-view) after an edit -- never by + // router.refresh(): a refresh commits Next's own idea of the URL when it lands, which undid + // the bench's address when it was opened meanwhile. A new view from the server (a take + // link) replaces it. + const [view, setView] = useState(served); + useEffect(() => setView(served), [served]); + const reloadSeq = useRef(0); + const reloadView = useCallback(async () => { + const mine = ++reloadSeq.current; + const q = new URLSearchParams({ project: served.project }); + if (view.take && !view.take.defaulted) q.set("take", view.take.id); + else if (!view.take) q.set("cut", "1"); + try { + const r = await fetch(`/api/report/play-view?${q.toString()}`, { cache: "no-store" }); + const j = (await r.json()) as PlayViewData & { error?: string }; + if (mine === reloadSeq.current && r.ok && !j.error) setView(j); + } catch { + // The view stays as it was; Reload the cut asks again. + } + }, [served.project, view.take]); + // Inside the one app (cutApp/CutApp.tsx): Edit opens the bench in place, and the keys are Play's only while it shows. + const app = useCutApp(); + const shown = !app || app.view === "play"; + useEffect(() => app?.onReturn(() => void reloadView()), [app, reloadView]); + const shownRef = useRef(shown); + shownRef.current = shown; const project = view.project; const take = view.take?.id ?? null; + // Edits made here (Reject, a reorder, the bench) write the PROJECT'S manifest, which a take + // without a timeline of its own plays as it is now -- the latest take follows them. A take + // with its own timeline does not: nothing structural is offered on it (its walk edits it). + const editable = !view.take?.ownTimeline; + // A note taken on the latest take (the default) is a note on the cut: the manifest is the + // file to edit. On a take chosen by name it is that take's, as it always was. + const noteTake = view.take && !view.take.defaulted ? take : null; // Export clip (ClipExport.tsx): the clip at the playhead -- or the one a note points at -- clean, into exports/. const clipExport = useClipExport(project, take); @@ -262,7 +309,13 @@ export default function PlayCut({ }, [compose, view.deckOn]); // ---- the plan ---------------------------------------------------------------- - const schedule = doc?.schedule ?? null; + // The composed schedule, while it is the cut's ORDER: a reorder (the strip's drop) re-reads the + // view at once, and until the deck is composed again its segments would play the old order -- + // so the estimate's (the view's own, in the new order) stand in meanwhile. + const composedOrder = doc?.schedule?.segments?.map((x) => x.id).join("\n") ?? null; + const viewOrder = useMemo(() => view.segments.map((x) => x.id).join("\n"), [view.segments]); + const scheduleNow = composedOrder !== null && composedOrder === viewOrder; + const schedule = scheduleNow ? (doc?.schedule ?? null) : null; const segments = schedule?.segments ?? view.segments; const leadIn = doc?.leadIn ?? view.leadIn; // The render's edges (useRenderCuts: the build's snap), asked again when an entry's edges change. @@ -308,7 +361,9 @@ export default function PlayCut({ }).toString()}`, [project, take], ); - const engine = usePlayEngine({ plan, entries: entryOf, srcOf, audioOf, blurRendered: view.blurRendered, bg, style: edges.style }); + const engine = usePlayEngine({ + plan, entries: entryOf, srcOf, audioOf, blurRendered: view.blurRendered, bg, style: edges.style, edgesPending: edges.state === "measuring", + }); const { ui, rate, failed, seekTo, setPlaying, now } = engine; const setRate = engine.setRate; @@ -319,6 +374,20 @@ export default function PlayCut({ // composed schedule replacing the estimate's, the render's edges arriving. // Let go once both have settled. A card keeps its offset. const anchor = useRef<{ clip: string; at: number; src?: number; t?: number } | null>(initialAt); + // A place set to be found again (back from the bench, after a reorder): the effect below runs + // for it even when the plan did not change. + const [anchorTick, setAnchorTick] = useState(0); + // ...and held until the view read again after it arrives (a refresh is on its way), at most 20 s. + const awaitView = useRef(0); + const holdForView = useCallback(() => { + awaitView.current = performance.now(); + setAnchorTick((n) => n + 1); + }, []); + useEffect(() => { + if (!awaitView.current) return; + awaitView.current = 0; + setAnchorTick((n) => n + 1); + }, [view]); // THE PLACE IN THE URL: Play keeps where it is -- the clip, the offset into // it, the cut second and the rejected-clips toggle -- in its own URL // (replaceState, at most once a second, never a history entry of its own), @@ -353,19 +422,40 @@ export default function PlayCut({ if (it.clip && a.src === undefined && edges.state !== "measuring") a.src = sourceAt(it, inside(it.from + a.at)) ?? undefined; const landed = it.clip && a.src !== undefined ? inside(cutAtSource(it, a.src)) : inside(it.from + a.at); seekTo(landed); - if (composeState !== "composing" && edges.state !== "measuring") { + const waiting = awaitView.current > 0 && performance.now() - awaitView.current < 20_000; + if (composeState !== "composing" && edges.state !== "measuring" && !waiting) { anchor.current = null; // The cut second it was left at is not where that clip's offset is now: an edit moved it. if (a.t !== undefined && Math.abs(landed - a.t) > 0.1) setBackToast(`Back at ${a.clip} · ${timecode(landed)} (the cut changed)`); } - }, [plan, composeState, edges.state, seekTo]); + }, [plan, composeState, edges.state, seekTo, anchorTick]); // A structural write landed (Reject, its undo): the view and the chrome are read again. const afterStructure = useCallback(() => { setPlaying(false); - router.refresh(); + void reloadView(); + }, [reloadView, setPlaying]); + // The deck is composed again whenever the manifest moved (its token): a Reject, a reorder, an + // Apply, the bench's save seen on the way back -- once, however the view came to be re-read. + const composedFor = useRef(view.token); + useEffect(() => { + if (view.token === composedFor.current) return; + composedFor.current = view.token; if (view.deckOn) void compose(); - }, [router, view.deckOn, compose, setPlaying]); + }, [view.token, view.deckOn, compose]); + // Hidden under the bench (the one app), Play does not play on; shown again, it finds the clip it + // left by its id and the source second (an edit on the bench may have moved it in the cut). + const leftAt = useRef<{ clip: string; at: number; t: number } | null>(null); + const wasShown = useRef(shown); + useEffect(() => { + if (!shown) setPlaying(false); + else if (!wasShown.current && leftAt.current) { + anchor.current = { ...leftAt.current }; + leftAt.current = null; + holdForView(); + } + wasShown.current = shown; + }, [shown, setPlaying, holdForView]); // ---- the controls ---------------------------------------------------------------- const next = useCallback(() => seekTo(startOf(planRef.current, now().cur + 1)), [seekTo, now]); @@ -392,8 +482,11 @@ export default function PlayCut({ // ---- 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], + () => + notes.notes + .filter((n) => n.anchor.kind === "cut" && ((n.anchor.take ?? null) === noteTake || (view.take?.defaulted && (n.anchor.take ?? null) === take))) + .sort((a, b) => (a.anchor as CutAnchor).t - (b.anchor as CutAnchor).t), + [notes.notes, take, noteTake, view.take?.defaulted], ); // A note's second on this clock: by its clip and source second when it has them (the // render's edges re-time the cut; a note stays on the word it was taken on), else its t. @@ -421,8 +514,8 @@ export default function PlayCut({ 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, now]); + setDrafting({ kind: "cut", t: Math.round(e.t * 100) / 100, entry: item.id, ...(src !== null ? { sourceT: src } : {}), ...(noteTake ? { take: noteTake } : {}) }); + }, [pauseWhileWriting, setPlaying, noteTake, now]); const closeDraft = useCallback(() => { setDrafting(null); if (resumeAfter.current) { @@ -455,8 +548,8 @@ export default function PlayCut({ const e = now(); const it = planRef.current.items[e.cur]; if (!it?.clip) return null; - return clipBenchHref(project, it.id, { play: { at: Math.round(Math.max(0, e.t - it.from) * 100) / 100, take } }); - }, [project, take, now]); + return clipBenchHref(project, it.id, { play: { at: Math.round(Math.max(0, e.t - it.from) * 100) / 100, take: view.take?.defaulted ? null : take } }); + }, [project, take, now, view.take?.defaulted]); /** Play's place as its own URL: the clip on screen, the offset into it, the cut second, the toggle. */ const placeHref = useCallback(() => { const e = now(); @@ -477,14 +570,34 @@ export default function PlayCut({ if (!h) return; setPlaying(false); // Where Back lands: this place, written now (the one push is the bench's). - window.history.replaceState(null, "", placeHref()); + window.history.replaceState(window.history.state, "", placeHref()); + if (app) { + // In place: Play stays as it is; on the way back the clip (and the source second) is found again. + const e = now(); + const it = planRef.current.items[e.cur]; + leftAt.current = it ? { clip: it.id, at: Math.max(0, e.t - it.from), t: e.t } : null; + app.openClip(it?.id ?? "", h); + return; + } router.push(h); - }, [editHref, router, setPlaying, placeHref]); + }, [editHref, router, setPlaying, placeHref, app, now]); const lastPlace = useRef(0); + // A navigation in flight (a take link, Play the latest): Play's own URL write would land on + // top of it and cancel it (the audit's "a take link clicked while playing is cancelled"), so + // nothing is written until the new view arrives. + const navigating = useRef(false); + const onNavigate = useCallback(() => { + navigating.current = true; + setPlaying(false); + }, [setPlaying]); + useEffect(() => { + navigating.current = false; + }, [view]); useEffect(() => { // Not while a place is still being restored: the URL holds it until it lands. if (anchor.current) return; const due = () => { + if (navigating.current || !shownRef.current) return; lastPlace.current = performance.now(); const h = placeHref(); if (h !== `${window.location.pathname}${window.location.search}${window.location.hash}`) window.history.replaceState(null, "", h); @@ -494,10 +607,102 @@ export default function PlayCut({ return () => clearTimeout(id); }, [ui.t, ui.cur, ui.playing, showRejected, placeHref]); + // ---- the reel strip's zoom (the bench waveform's, over cut seconds) ------------------ + const zoom = useWaveZoom({ from: 0, to: Math.max(1, plan.total) }); + const stripSecs = useMemo(() => itemSections(plan.items, view.sectionOf ?? {}), [plan.items, view.sectionOf]); + /** The span of the clip on screen, and of its section: what Zoom to clip / to section show. */ + const curSpan = useCallback(() => { + const it = planRef.current.items[now().cur]; + return it ? { from: it.from, to: it.to } : null; + }, [now]); + const sectionSpan = useCallback(() => { + const items = planRef.current.items; + const i = now().cur; + if (!items[i]) return null; + let a = i; + let b = i; + while (a > 0 && stripSecs[a - 1] === stripSecs[i]) a -= 1; + while (b < items.length - 1 && stripSecs[b + 1] === stripSecs[i]) b += 1; + return { from: items[a].from, to: items[b].to }; + }, [now, stripSecs]); + // Zoomed and playing, the strip pages on with the playhead. + useEffect(() => { + if (!zoom.zoomed || !ui.playing) return; + const v = followVis(zoom.vis, { from: 0, to: plan.total }, ui.t); + if (v) zoom.set(v); + }, [ui.t, ui.playing, zoom, plan.total]); + + // ---- reorder (the strip's drop, Alt+arrows, Move to…): one write, an Undo after ------ + const [edit, setEdit] = useState<{ busy: boolean; error: string | null; done: { words: string; token: string | null; undone?: boolean } | null }>({ busy: false, error: null, done: null }); + const lastToken = useRef<string | null>(view.token ?? null); + useEffect(() => { + lastToken.current = view.token ?? null; + setEdit((x) => (x.busy ? { ...x, busy: false } : x)); + }, [view.token]); + /** Keep the playhead on the clip it is on, the same distance in, across the re-read. */ + const holdPlace = useCallback(() => { + const e = now(); + const it = planRef.current.items[e.cur]; + if (it) anchor.current = { clip: it.id, at: Math.max(0, e.t - it.from) }; + holdForView(); + }, [now, holdForView]); + const timelineWrite = useCallback( + async (body: Record<string, unknown>) => { + const r = await fetch("/api/report/timeline", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, token: lastToken.current, ...body }), + }); + const j = (await r.json().catch(() => ({}))) as { error?: string; errors?: string[]; stale?: boolean; token?: string }; + return { r, j }; + }, + [project], + ); + const runEdit = useCallback( + async (e: StripEdit) => { + setEdit({ busy: true, error: null, done: null }); + const body = e.op === "place" ? { op: "place", ids: e.ids, before: e.before, section: e.section } : { op: "section-move", ids: e.ids, section: e.section, position: e.position }; + const { r, j } = await timelineWrite(body); + if (r.status === 409 && j.stale) { + setEdit({ busy: false, error: "The cut changed since this page read it — read again; drop it again", done: null }); + void reloadView(); + return; + } + if (!r.ok) { + setEdit({ busy: false, error: [j.error ?? `HTTP ${r.status}`, ...(j.errors ?? [])].join(" — "), done: null }); + return; + } + lastToken.current = j.token ?? null; + holdPlace(); + setEdit({ busy: true, error: null, done: { words: e.words, token: j.token ?? null } }); + void reloadView(); + }, + [timelineWrite, holdPlace, reloadView], + ); + const undoEdit = useCallback(async () => { + const d = edit.done; + if (!d) return; + setEdit({ busy: true, error: null, done: d }); + // The structural undo, guarded by the token the drop left: an edit made since is not undone by mistake. + const { r, j } = await timelineWrite({ op: "undo", token: d.token }); + if (!r.ok) { + setEdit({ busy: false, error: r.status === 409 ? "Not undone: the cut changed since that move (Undo last edit on the Cut tab takes back the newest edit)" : (j.error ?? `HTTP ${r.status}`), done: null }); + return; + } + lastToken.current = j.token ?? null; + holdPlace(); + setEdit({ busy: true, error: null, done: { ...d, undone: true } }); + void reloadView(); + }, [edit.done, timelineWrite, holdPlace, reloadView]); + const editableWhy = !editable + ? `take ${take} has its own timeline: reorder it on its walk (umtool timeline <p> --take ${take} move)` + : null; + // ---- the keys ---------------------------------------------------------------------- const [help, setHelp] = useState(false); useEffect(() => { const onKey = (ev: KeyboardEvent) => { + if (!shownRef.current) return; const tgt = ev.target as HTMLElement | null; if (ev.key === "Escape") { if (help) setHelp(false); @@ -517,12 +722,19 @@ export default function PlayCut({ else if (k === "]") stepNote(1); else if (k === "m" || k === "M") noteHere(); else if (k === "e" || k === "E") editHere(); - else if (k === "?") setHelp((h) => !h); + else if (k === "z") zoom.zoomIn(now().t); + else if (k === "Z") zoom.zoomOut(now().t); + else if (k === "f") zoom.fit(); + else if (k === "F") { + const c = curSpan(); + if (c) zoom.to(c); + } 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) => { + if (!shownRef.current) return; const tgt = ev.target as HTMLElement | null; if (ev.key === " " && !tgt?.closest("input, textarea, select, [contenteditable=true]")) ev.preventDefault(); }; @@ -532,7 +744,7 @@ export default function PlayCut({ window.removeEventListener("keydown", onKey); window.removeEventListener("keyup", onUp); }; - }, [back, help, lPlay, next, prev, skip, stepNote, noteHere, editHere, setPlaying, now]); + }, [back, help, lPlay, next, prev, skip, stepNote, noteHere, editHere, setPlaying, now, zoom, curSpan]); // ---- what is on screen ------------------------------------------------------------- const t = ui.t; @@ -664,23 +876,7 @@ export default function PlayCut({ {/* ---- 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 max-md:-mx-4"> <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> + <WhatPlays project={project} take={view.take} takes={view.takes} working={view.working ?? null} onNavigate={onNavigate} /> <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> @@ -688,10 +884,17 @@ export default function PlayCut({ ? </button> </header> - {view.take && ( - <p className="m-0 border-b border-seam px-4 py-1 text-[11.5px] text-text-2 max-md:-mx-4 max-md:-mt-3" data-play-take={view.take.id}> - take “{view.take.label}”: the project&rsquo;s cut with its patch ({view.take.from}){view.take.made ? "" : " — not rendered yet"} + {view.take ? ( + <p className="m-0 border-b border-seam px-4 py-1 text-[11.5px] text-text-2 max-md:-mx-4 max-md:-mt-3" data-play-take={view.take.id} data-play-take-defaulted={view.take.defaulted ? "" : undefined}> + {view.take.defaulted ? "the latest take, " : ""}take “{view.take.label}”: the project&rsquo;s cut as it is now with its patch ({view.take.from}){view.take.made ? "" : " — not rendered yet"} {view.take.summary ? ` · ${view.take.summary}` : ""} + {view.take.ownTimeline + ? " — it has its own timeline: edits to the cut do not show in it, and nothing here edits it (walk the take)" + : " · edits here go to the cut, and show at once"} + </p> + ) : ( + <p className="m-0 border-b border-seam px-4 py-1 text-[11.5px] text-text-2 max-md:-mx-4 max-md:-mt-3" data-play-take=""> + the project&rsquo;s manifest alone — no take&rsquo;s look (title, deck and effects patches are not applied) </p> )} @@ -832,7 +1035,7 @@ export default function PlayCut({ <ClipExportStatus exp={clipExport} /> </div> {/* Reject ▾ (x): the clip on screen out of the cut for a reason, on record, with an undo (the project's cut: not on a take). */} - {!take && ( + {editable && ( <RejectClip project={project} hotkey @@ -854,6 +1057,31 @@ export default function PlayCut({ {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 ---- */} + <div className="flex flex-wrap items-center gap-2 text-[11px]" data-strip-zoom-controls=""> + <ZoomControls + zoom={zoom} + whole={{ from: 0, to: Math.max(1, plan.total) }} + selection={item ? { from: item.from, to: item.to } : null} + playhead={t} + selectionLabel="Zoom to clip" + selectionTitle="the clip on screen fills the strip (F)" + wholeLabel="whole cut" + > + <button + type="button" + data-zoom-section="" + className={buttonVariants({ variant: "outline", size: "sm" })} + disabled={!item} + title="the section the clip on screen is in fills the strip" + onClick={() => { + const sp = sectionSpan(); + if (sp) zoom.to(sp); + }} + > + Zoom to section + </button> + </ZoomControls> + </div> <ReelStrip items={plan.items} total={plan.total} @@ -868,7 +1096,31 @@ export default function PlayCut({ onSeek={seekTo} onSeekItem={(i) => seekTo(startOf(planRef.current, i))} skipped={plan.skipped.map((x) => ({ ...x, why: entryOf.get(x.id)?.rejected?.why ?? "" }))} + zoom={zoom} + sections={view.sections ?? []} + sectionOf={view.sectionOf ?? {}} + editable={editableWhy} + onEdit={(e) => void runEdit(e)} + busy={edit.busy} + notice={ + view.sectionsDiffer && view.take + ? `take ${view.take.id}'s patch sets its own sections (render.chrome.deck.markers), out of step with the cut's: a move here changes the cut's clips and sections; the strip's seams are this take's until its patch's markers are brought in step` + : null + } /> + {(edit.done || edit.error) && ( + <p role="status" data-strip-toast={edit.error ? "error" : edit.done?.undone ? "undone" : "done"} className={cn("m-0 flex flex-wrap items-center gap-2 text-[11.5px]", edit.error ? "text-reject-text" : "text-text-2")}> + {edit.error ? edit.error : edit.done?.undone ? `Undone: ${edit.done.words}` : `Moved: ${edit.done?.words}`} + {edit.done && !edit.done.undone && !edit.error && ( + <button type="button" className="ink-link" data-strip-undo="" disabled={edit.busy && !edit.done.token} onClick={() => void undoEdit()}> + Undo + </button> + )} + <button type="button" className="ink-link" onClick={() => setEdit((x) => ({ ...x, error: null, done: null }))}> + dismiss + </button> + </p> + )} {rejected.length > 0 && ( <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11.5px] text-muted" data-play-rejected={rejected.map((e) => e.id).join(" ")}> <span> @@ -924,7 +1176,7 @@ export default function PlayCut({ data-play-reload="" title="read the cut again after an edit elsewhere" onClick={() => { - router.refresh(); + void reloadView(); if (view.deckOn) void compose(); }} > @@ -954,10 +1206,7 @@ export default function PlayCut({ onNote={noteHere} onClose={closeDraft} onSeek={(n) => seekTo(noteT(n.anchor as CutAnchor))} - onApplied={() => { - router.refresh(); - if (view.deckOn) void compose(); - }} + onApplied={() => void reloadView()} exportable={(id) => { const e = entryOf.get(id); return e?.type === "clip" && !!e.media; diff --git a/umtool/components/projects/review/ReelStrip.tsx b/umtool/components/projects/review/ReelStrip.tsx @@ -1,8 +1,11 @@ "use client"; -import { useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { cn } from "@/lib/utils"; -import { counterAt, dateRamp, gapJoins, playPlan, rulerTicks, runningTime, shownSeconds } from "@/lib/report/playCut.mjs"; +import { counterAt, dateRamp, gapJoins, playPlan, runningTime, shownSeconds } from "@/lib/report/playCut.mjs"; +import { rulerFor, tickLabel } from "@/lib/report/benchZoom.mjs"; +import { dropSlot, edgeSpeed, itemSections, labelsThatFit, sectionName } from "@/lib/report/stripDrag.mjs"; +import { ZoomOverview, type WaveZoom } from "../bench/GapsZoom"; type PlayItem = ReturnType<typeof playPlan>["items"][number]; @@ -11,20 +14,44 @@ type PlayItem = ReturnType<typeof playPlan>["items"][number]; // 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. +// name and 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 on a cell's body to scrub; a cell's Enter jumps to its start. +// +// ZOOM (1 Nov 2026) is the bench waveform's (bench/GapsZoom.tsx useWaveZoom, +// benchZoom.mjs), over cut seconds: Ctrl/⌘ + wheel at the pointer, − / + / +// Fit / Zoom to clip / Zoom to section (z Z f F, in PlayCut), the wheel pans +// while zoomed, an overview under the strip shows the whole cut and what is +// shown (drag it), a ruler of round ticks. Zoomed, a cell shows its id and +// date, the seams their section, and the view follows the playhead. +// +// REORDER (1 Nov 2026): grab a cell by its top band (the grip, ⠿) -- or +// anywhere with Alt held -- and drag. An insertion bar in the section's +// colour and the drop's words ("→ §3 Leaves it open, before o02") follow the +// pointer; its left half lands before a cell, its right half after it, so at a +// seam the two sides are the end of one section and the start of the next. At +// a zoomed strip's edge it pans; Ctrl/⌘ + wheel zooms mid-drag; Esc cancels. +// A drop is one write through `onEdit` (the place op: lib/report/sectionEdit.mjs +// placeIn). The keyboard's: Alt+← / Alt+→ on a focused cell (crossing a seam +// first changes its section, then moves it), and Move to… for a section. // --------------------------------------------------------------------------- export type StripEntry = { id: string; type: string; heading: string; dateKey?: number | null; dateLabel?: string | null; media?: unknown; rejected?: { why: string } | null }; 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 }; +export type StripSection = { index: number; label: string | null; color: string | null; count?: number }; +/** A structural edit the strip asks for: a drop, an Alt+arrow, or Move to…. */ +export type StripEdit = + | { op: "place"; ids: string[]; before: string | null; section: number | null; words: string } + | { op: "section-move"; ids: string[]; section: number; position: "start" | "end"; words: string }; const CELLS_H = 56; -const pctOf = (t: number, total: number) => `${total > 0 ? Math.max(0, Math.min(100, (t / total) * 100)) : 0}%`; +/** The grip band at a cell's top: a press there drags the cell; below it scrubs. */ +const GRIP_H = 18; +/** How far a press moves before it is a drag (px). */ +const DRAG_PX = 4; export default function ReelStrip({ items, @@ -40,6 +67,13 @@ export default function ReelStrip({ onSeek, onSeekItem, skipped = [], + zoom, + sections = [], + sectionOf = {}, + editable = null, + onEdit, + busy = false, + notice = null, }: { items: PlayItem[]; total: number; @@ -55,36 +89,171 @@ export default function ReelStrip({ onSeekItem: (i: number) => void; /** Entries left out of the plan (clips the walk rejected): a struck-through marker at the seam, why on hover. */ skipped?: { id: string; at: number; why: string }[]; + /** What is shown (the bench's zoom over cut seconds, owned by PlayCut for its keys). */ + zoom: WaveZoom; + /** The project's sections (the deck's markers) and each clip's: where a drop lands. */ + sections?: StripSection[]; + sectionOf?: Record<string, number>; + /** null: reordering is on; a string: why it is not (said under the strip). */ + editable?: string | null; + onEdit?: (e: StripEdit) => void; + busy?: boolean; + /** A word about what a move here does and does not change (a take with sections of its own). */ + notice?: string | null; }) { 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 vis = zoom.vis; + const span = Math.max(1e-6, vis.to - vis.from); + const frac = (x: number) => (x - vis.from) / span; + const pct = (x: number) => `${frac(x) * 100}%`; + const wpct = (a: number, b: number) => `${((b - a) / span) * 100}%`; + const inView = (a: number, b: number) => b >= vis.from && a <= vis.to; + const { step, ticks } = useMemo(() => rulerFor(vis, 12), [vis]); + // The strip's width in px: which labels fit, how wide a cell is. + const [width, setWidth] = useState(1000); + useEffect(() => { + const el = cells.current; + if (!el) return; + const ro = new ResizeObserver(() => setWidth(el.clientWidth || 1000)); + ro.observe(el); + setWidth(el.clientWidth || 1000); + return () => ro.disconnect(); + }, []); + const pxPerS = width / span; 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; + if (!r || r.width <= 0) return vis.from; + return vis.from + Math.max(0, Math.min(1, (clientX - r.left) / r.width)) * span; }; 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]); + const secs = useMemo(() => itemSections(items, sectionOf), [items, sectionOf]); + const colorOf = (k: number) => sections.find((s) => s.index === k)?.color ?? "var(--muted)"; + const named = sections.length > 1; + + // ---- the seams' labels: "27 Feb 2025 §3 Leaves it open" where they fit ---- + const seamLabels = useMemo(() => { + const list = seams + .map((s) => { + const it = items[s.index]; + if (!it) return null; + const sec = secs[s.index]; + const text = named ? [s.date, sectionName(sections, sec)].filter(Boolean).join(" ") : (s.date ?? s.label ?? ""); + return { s, sec, x: ((it.from - vis.from) / span) * width, w: text.length * 6.2 + 8 }; + }) + .filter((x): x is NonNullable<typeof x> => !!x && x.x >= -x.w && x.x <= width); + const shown = new Set(labelsThatFit(list.map((l) => ({ x: l.x, w: l.w })))); + return list.map((l, i) => ({ ...l, shown: shown.has(i) })); + }, [seams, items, secs, sections, named, width, vis.from, span]); + + // ---- the drag ---- + type Drag = { id: string; pointerId: number; x0: number; on: boolean; x: number; y: number }; + const [drag, setDrag] = useState<Drag | null>(null); + const dragRef = useRef<Drag | null>(null); + dragRef.current = drag; + const [refusal, setRefusal] = useState<string | null>(null); + const slot = drag?.on ? dropSlot(items, secs, sections, [drag.id], tAt(drag.x)) : null; + const canDrag = editable === null && !!onEdit && !busy; + // The edge: a zoomed strip pans while the pointer is near either end. + const zoomRef = useRef(zoom); + zoomRef.current = zoom; + useEffect(() => { + if (!drag?.on) return; + let raf = 0; + let last = performance.now(); + const tick = (now: number) => { + const d = dragRef.current; + const z = zoomRef.current; + const r = cells.current?.getBoundingClientRect(); + if (d?.on && r && z.zoomed) { + const v = edgeSpeed(d.x - r.left, r.width); + if (v) z.pan(v * (z.vis.to - z.vis.from) * ((now - last) / 1000)); + } + last = now; + raf = requestAnimationFrame(tick); + }; + raf = requestAnimationFrame(tick); + return () => cancelAnimationFrame(raf); + }, [drag?.on]); + const cancelDrag = useCallback(() => setDrag(null), []); + useEffect(() => { + if (!drag) return; + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") { + e.stopPropagation(); + e.preventDefault(); + cancelDrag(); + } + }; + window.addEventListener("keydown", onKey, true); + return () => window.removeEventListener("keydown", onKey, true); + }, [drag, cancelDrag]); + const finishDrag = () => { + const d = dragRef.current; + setDrag(null); + if (!d) return; + if (!d.on) { + // A press on the grip that never moved: a click -- scrub there, as anywhere. + onSeek(tAt(d.x)); + return; + } + const s = dropSlot(items, secs, sections, [d.id], tAt(d.x)); + if (!s || s.noop) return; + if (s.refused) { + setRefusal(`${d.id}: ${s.refused}`); + return; + } + setRefusal(null); + onEdit?.({ op: "place", ids: [d.id], before: s.before, section: named ? s.section : null, words: `${d.id} ${s.words}` }); + }; + + // ---- the keyboard: Alt+← / Alt+→ one place, crossing a seam first into the next section ---- + const nudge = (i: number, dir: -1 | 1) => { + const it = items[i]; + if (!it || !onEdit || editable !== null || busy) return; + const s = secs[i]; + const j = i + dir; + if (j < 0 || j >= items.length) return; + if (it.clip && named && secs[j] !== s) { + // At a seam: the same slot, the next section. + const alone = !items.some((x, k) => k !== i && x.clip && secs[k] === s); + if (alone) { + setRefusal(`${it.id}: ${sectionName(sections, s)} would have no clip left — remove its boundary first, or move another clip into it`); + return; + } + onEdit({ op: "place", ids: [it.id], before: items[i + 1]?.id ?? null, section: secs[j], words: `${it.id} → ${sectionName(sections, secs[j])}` }); + return; + } + const before = dir < 0 ? items[j].id : (items[j + 1]?.id ?? null); + onEdit({ op: "place", ids: [it.id], before, section: it.clip && named ? s : null, words: `${it.id} ${dir < 0 ? `before ${items[j].id}` : `after ${items[j].id}`}` }); + }; + const [picker, setPicker] = useState<{ id: string } | null>(null); + + const ghostItem = drag?.on ? items.find((x) => x.id === drag.id) : null; + const curItem = items[cur] ?? null; 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> - ); - })} + <section data-play-strip="" aria-label="The cut as a reel" className="select-none" data-strip-zoom={zoom.zoomed ? `${vis.from.toFixed(2)}-${vis.to.toFixed(2)}` : "fit"}> + {/* the seams' dates and sections, the counter's total at the right end */} + <div className="relative h-4 overflow-hidden font-mono text-[10px] leading-4 text-muted"> + {seamLabels.map((l) => ( + <span + key={l.s.before} + data-play-seam-section={l.sec} + className={cn("absolute top-0 -translate-x-px whitespace-nowrap pl-1", !l.shown && "invisible")} + style={{ left: l.x, borderLeft: named ? `2px solid ${colorOf(l.sec)}` : undefined }} + title={[l.s.date, named ? sectionName(sections, l.sec) : l.s.label].filter(Boolean).join(" · ")} + > + <span data-play-seam-date={l.s.before}>{named ? (l.s.date ?? "") : (l.s.date ?? l.s.label ?? "")}</span> + {named && <span className={cn("text-text-2", l.s.date && "ml-1")}>{sectionName(sections, l.sec)}</span>} + </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(" · ")} @@ -92,15 +261,15 @@ export default function ReelStrip({ )} </div> - {/* a hovered cell, named above it */} + {/* a hovered cell, named above it; the drop's words while dragging */} <div className="relative h-0"> - {hovered && ( + {hovered && !drag?.on && inView(hovered.from, hovered.to) && ( <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%"})`, + left: pct((hovered.from + hovered.to) / 2), + transform: `translateX(${frac((hovered.from + hovered.to) / 2) > 0.75 ? "-100%" : frac((hovered.from + hovered.to) / 2) < 0.25 ? "0" : "-50%"})`, }} > {hovered.id} @@ -108,69 +277,111 @@ export default function ReelStrip({ {noMedia(hovered) ? " · no media — fetch it" : ""} </span> )} + {slot && ( + <span + data-strip-drop={slot.noop ? "here" : (slot.before ?? "-")} + data-strip-drop-section={slot.section} + data-strip-drop-refused={slot.refused ? "" : undefined} + className={cn( + "pointer-events-none absolute -top-4 z-20 whitespace-nowrap rounded-[2px] border px-1.5 font-mono text-[10.5px] leading-4", + slot.refused ? "border-reject-text bg-panel text-reject-text" : "border-seam-2 bg-panel text-text", + )} + style={{ left: pct(slot.at), transform: `translateX(${frac(slot.at) > 0.6 ? "-100%" : "0"})` }} + > + {slot.refused ? `refused: ${slot.refused}` : `${drag?.id} ${slot.words}`} + </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 className="relative h-3 overflow-hidden"> + {pins + .filter((p) => inView(p.t, p.t)) + .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: pct(p.t) }} + > + <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 */} + {/* the cells: click or drag the body to scrub; the grip band drags the cell */} <div - ref={cells} + ref={(node) => { + cells.current = node; + zoom.ref(node); + }} data-play-cells="" - className="relative cursor-col-resize overflow-hidden rounded-[2px] border border-seam bg-ground touch-none" + data-strip-dragging={drag?.on ? drag.id : undefined} + className={cn("relative overflow-hidden rounded-[2px] border border-seam bg-ground touch-none", drag?.on ? "cursor-grabbing" : "cursor-col-resize")} style={{ height: CELLS_H }} onPointerDown={(e) => { if (e.button !== 0) return; + const r = cells.current?.getBoundingClientRect(); + const x = tAt(e.clientX); + const i = items.findIndex((it) => x >= it.from && x < it.to); + const onGrip = !!r && e.clientY - r.top < GRIP_H; + if (i >= 0 && canDrag && (onGrip || e.altKey)) { + e.currentTarget.setPointerCapture(e.pointerId); + setDrag({ id: items[i].id, pointerId: e.pointerId, x0: e.clientX, on: false, x: e.clientX, y: e.clientY }); + return; + } scrubbing.current = true; e.currentTarget.setPointerCapture(e.pointerId); - onSeek(tAt(e.clientX)); + onSeek(x); }} 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); + const d = dragRef.current; + if (d && d.pointerId === e.pointerId) { + const on = d.on || Math.abs(e.clientX - d.x0) >= DRAG_PX; + setDrag({ ...d, on, x: e.clientX, y: e.clientY }); + return; } - if (scrubbing.current) onSeek(tAt(e.clientX)); + 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(x); }} - onPointerUp={() => { + onPointerUp={(e) => { + if (dragRef.current && dragRef.current.pointerId === e.pointerId) { + finishDrag(); + return; + } scrubbing.current = false; }} + onPointerCancel={() => { + scrubbing.current = false; + cancelDrag(); + }} onPointerLeave={() => setHover(null)} > {items.map((it, i) => { + if (!inView(it.from, it.to)) return null; const e = entries.get(it.id); const f = ramp.get(it.id); const missing = noMedia(it); const wrong = e?.rejected?.why ?? null; - const base = it.clip - ? `color-mix(in srgb, var(--seam-2) ${Math.round(30 + 60 * (f ?? 0.5))}%, var(--ground))` - : "var(--panel)"; + const base = it.clip ? `color-mix(in srgb, var(--seam-2) ${Math.round(30 + 60 * (f ?? 0.5))}%, var(--ground))` : "var(--panel)"; + const px = (it.to - it.from) * pxPerS; + const dragged = drag?.on && drag.id === it.id; return ( <button key={it.id} type="button" tabIndex={0} data-play-row={it.id} + data-play-row-section={secs[i]} aria-current={i === cur ? "true" : undefined} - aria-label={`${it.id}${e?.dateLabel ? `, ${e.dateLabel}` : ""}, ${shownSeconds(it).toFixed(1)} seconds${missing ? ", no media" : ""}`} + aria-label={`${it.id}${e?.dateLabel ? `, ${e.dateLabel}` : ""}, ${shownSeconds(it).toFixed(1)} seconds${missing ? ", no media" : ""}${named ? `, ${sectionName(sections, secs[i])}` : ""}`} title={wrong ? `${it.id}: rejected — ${wrong}` : missing ? `${it.id}: no media — fetch it` : undefined} data-play-row-missing={missing ? "" : undefined} data-play-row-rejected={wrong ? "" : undefined} @@ -178,57 +389,89 @@ export default function ReelStrip({ // A pointer's click scrubbed on pointerdown; a key's (Enter) jumps to the entry's start. if (ev.detail === 0) onSeekItem(i); }} + onKeyDown={(ev) => { + if (ev.altKey && (ev.key === "ArrowLeft" || ev.key === "ArrowRight")) { + ev.preventDefault(); + ev.stopPropagation(); + nudge(i, ev.key === "ArrowLeft" ? -1 : 1); + } + }} 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", + "group absolute top-0 h-full overflow-hidden border-r border-ground px-1 text-left font-mono text-[10px] leading-3", it.clip ? "text-text-2" : "text-muted", wrong && "text-muted line-through opacity-60", i === cur && "shadow-[inset_0_-2px_0_var(--signal)]", + dragged && "opacity-35", )} 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, + left: pct(it.from), + width: wpct(it.from, it.to), + 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>} + {/* the grip band: the section's colour along its top, ⠿ where there is room */} + <span + aria-hidden + data-strip-grip={it.id} + className={cn("absolute inset-x-0 top-0 block", canDrag && "cursor-grab group-hover:bg-[color-mix(in_srgb,var(--signal)_14%,transparent)]")} + style={{ height: GRIP_H, borderTop: named ? `2px solid ${colorOf(secs[i])}` : undefined }} + title={canDrag ? `drag to move ${it.id} (Alt+← → on the keyboard)` : (editable ?? undefined)} + /> + {px >= 14 && ( + <span className={cn("pointer-events-none relative z-[5] mt-1 block w-fit max-w-full overflow-hidden whitespace-nowrap rounded-[2px]", px >= 40 && "bg-ground/70 px-0.5")}> + {px >= 40 && canDrag && <span className="mr-0.5 text-muted-2">⠿</span>} + {it.id} + </span> + )} + {px >= 70 && it.clip && e?.dateLabel && <span className="pointer-events-none relative z-[5] block w-fit whitespace-nowrap rounded-[2px] bg-ground/70 px-0.5 text-[9px] text-muted">{e.dateLabel}</span>} + {!it.clip && px >= 30 && <span className="pointer-events-none relative block whitespace-nowrap text-[9px] uppercase tracking-wide opacity-80">{it.type}</span>} </button> ); })} {/* a clip's gaps (gaps.mjs): a jump cut inside its cell, where the seconds it leaves out were */} {items.flatMap((it) => - gapJoins(it).map((g) => ( - <span - key={`gap:${it.id}:${g.from}`} - data-play-gap={`${it.id}@${g.at}`} - title={`${it.id}: ${(g.to - g.from).toFixed(2)} s cut out (${g.from.toFixed(2)}–${g.to.toFixed(2)}) — a jump cut`} - aria-hidden - className="pointer-events-none absolute top-0 z-[1] h-full w-0 border-l border-dashed border-[var(--color-dirty)]" - style={{ left: pctOf(g.at, total) }} - /> - )), + gapJoins(it) + .filter((g) => inView(g.at, g.at)) + .map((g) => ( + <span + key={`gap:${it.id}:${g.from}`} + data-play-gap={`${it.id}@${g.at}`} + title={`${it.id}: ${(g.to - g.from).toFixed(2)} s cut out (${g.from.toFixed(2)}–${g.to.toFixed(2)}) — a jump cut`} + aria-hidden + className="pointer-events-none absolute top-0 z-[1] h-full w-0 border-l border-dashed border-[var(--color-dirty)]" + style={{ left: pct(g.at) }} + /> + )), )} {/* the entries skipped (rejected on the walk): a greyed, struck-through tag where they would play */} - {skipped.map((x) => ( - <span - key={`skip:${x.id}`} - data-play-skipped={x.id} - title={`${x.id} skipped — rejected${x.why ? ` — ${x.why}` : ""}`} - className="absolute bottom-0 z-[1] -translate-x-1/2 rounded-[2px] bg-ground/90 px-0.5 font-mono text-[9px] leading-3 text-muted line-through opacity-80" - style={{ left: pctOf(x.at, total) }} - > - {x.id} - </span> - ))} + {skipped + .filter((x) => inView(x.at, x.at)) + .map((x) => ( + <span + key={`skip:${x.id}`} + data-play-skipped={x.id} + title={`${x.id} skipped — rejected${x.why ? ` — ${x.why}` : ""}`} + className="absolute bottom-0 z-[1] -translate-x-1/2 rounded-[2px] bg-ground/90 px-0.5 font-mono text-[9px] leading-3 text-muted line-through opacity-80" + style={{ left: pct(x.at) }} + > + {x.id} + </span> + ))} - {/* the sections' seams */} + {/* the sections' seams, in the new section's colour */} {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; + return it && inView(it.from, it.from) ? ( + <span + key={s.before} + aria-hidden + data-strip-seam={s.before} + className="pointer-events-none absolute top-0 z-[2] h-full w-px opacity-80" + style={{ left: pct(it.from), background: named ? colorOf(secs[s.index]) : "var(--text-2)" }} + /> + ) : null; })} {/* the counter's staircase */} @@ -236,53 +479,155 @@ export default function ReelStrip({ <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" - /> - ); + const X = (s: number) => frac(s) * 1000; + let d = `M${X(0)},${y(0)}`; + for (const s of c.steps) d += ` H${X(s.t)} V${y(s.n)}`; + d += ` H${X(total)}`; + 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 insertion bar while dragging, in the drop's section's colour */} + {slot && !slot.noop && ( + <span + aria-hidden + data-strip-insert={slot.before ?? "-"} + className="pointer-events-none absolute top-0 z-[7] h-full w-[3px] -translate-x-1/2 rounded-sm" + style={{ left: pct(slot.at), background: slot.refused ? "var(--reject-text)" : named ? colorOf(slot.section) : "var(--signal)", boxShadow: "0 0 0 1px var(--ground)" }} + /> + )} + {/* 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) }} /> + {inView(t, t) && <span aria-hidden data-play-playhead="" className="pointer-events-none absolute top-0 z-[6] h-full w-px bg-signal" style={{ left: pct(t) }} />} </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"> + {/* the dragged cell, following the pointer */} + {ghostItem && drag && ( <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="" + aria-hidden + data-strip-ghost={ghostItem.id} + className="pointer-events-none fixed z-50 -translate-x-1/2 rounded-[2px] border border-signal bg-panel px-1.5 py-0.5 font-mono text-[11px] text-text shadow-lg" + style={{ left: drag.x, top: drag.y + 18 }} > - {timecode(t)} - {counterNow.map((c) => ( - <span key={c.id} className="text-meter"> - {" "} - · {c.label} {c.now} - </span> - ))} + ⠿ {ghostItem.id} + {entries.get(ghostItem.id)?.dateLabel ? ` · ${entries.get(ghostItem.id)?.dateLabel}` : ""} · {shownSeconds(ghostItem).toFixed(1)} s </span> + )} + + {/* the playhead's timecode and the counter at it */} + <div className="relative h-4 overflow-hidden font-mono text-[10.5px] leading-4"> + {inView(t, t) && ( + <span + className="absolute top-0 whitespace-nowrap text-signal-text" + style={{ left: pct(t), transform: `translateX(${frac(t) > 0.8 ? "-100%" : frac(t) > 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=""> + {/* the ruler: round ticks over what is shown */} + <div className="relative h-4 overflow-hidden border-t border-seam font-mono text-[10px] leading-4 text-muted" aria-hidden data-play-ruler={step}> {ticks.map((s) => ( - <span key={s} className="absolute top-0" style={{ left: pctOf(s, total) }}> + <span key={s} className="absolute top-0" style={{ left: pct(s) }}> <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>} + {s > vis.from + span * 0.02 && s < vis.to - span * 0.04 && <span className="absolute left-0 top-0.5 -translate-x-1/2 whitespace-nowrap">{step >= 1 ? runningTime(s) : tickLabel(s, step)}</span>} </span> ))} </div> + {/* the whole cut under a zoomed strip: drag to pan, click to centre */} + {zoom.zoomed && ( + <div className="mt-1" data-strip-overview=""> + <ZoomOverview + zoom={zoom} + whole={{ from: 0, to: total }} + paint={(g, toX, w, h) => { + items.forEach((it, i) => { + g.fillStyle = named ? (sections.find((s) => s.index === secs[i])?.color ?? "#888") : "#888"; + g.globalAlpha = it.clip ? 0.55 : 0.25; + g.fillRect(toX(it.from), 3, Math.max(1, toX(it.to) - toX(it.from) - 0.5), h - 6); + }); + g.globalAlpha = 1; + g.fillStyle = "#e5484d"; + g.fillRect(Math.min(w - 1.5, toX(t)), 0, 1.5, h); + }} + /> + </div> + )} + + {/* the strip's own row: how to move, Move to…, why reordering is off, a refused drop */} + <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-muted" data-strip-tools=""> + {onEdit && editable === null ? ( + <span> + drag a cell by its top band (or with Alt) to move it · Alt+← → on a focused cell ·{" "} + <button + type="button" + className="ink-link" + data-strip-move-to="" + disabled={!curItem?.clip || busy || sections.length < 2} + onClick={() => curItem?.clip && setPicker({ id: curItem.id })} + title={sections.length < 2 ? "the cut has one section" : "move the clip on screen to the start or end of a section"} + > + Move {curItem?.clip ? curItem.id : "this clip"} to… + </button> + </span> + ) : editable ? ( + <span data-strip-locked="">{editable}</span> + ) : null} + {notice && ( + <span data-strip-notice="" className="text-doubt-text"> + {notice} + </span> + )} + {busy && <span data-strip-busy="">moving…</span>} + {refusal && ( + <span role="alert" className="text-reject-text" data-strip-refusal=""> + {refusal}{" "} + <button type="button" className="ink-link" onClick={() => setRefusal(null)}> + dismiss + </button> + </span> + )} + </div> + {picker && ( + <div role="dialog" aria-label={`Move ${picker.id} to`} data-strip-picker={picker.id} className="mt-1 max-h-[40vh] overflow-auto rounded-[3px] border border-seam-2 bg-panel p-2 text-[12px]"> + <div className="mb-1 flex items-center gap-2"> + <span className="micro">Move {picker.id} to</span> + <button type="button" autoFocus className="ml-auto ink-link" onClick={() => setPicker(null)}> + close + </button> + </div> + <ul className="m-0 grid list-none gap-0.5 p-0 [grid-template-columns:repeat(auto-fill,minmax(260px,1fr))]"> + {sections.map((s) => ( + <li key={s.index} className="flex items-center gap-2" data-strip-picker-section={s.index}> + <span className="inline-block h-2.5 w-2.5 shrink-0 rounded-sm" style={{ background: s.color ?? "var(--muted)" }} /> + <span className="min-w-0 flex-1 truncate">{sectionName(sections, s.index)}</span> + {(["start", "end"] as const).map((pos) => ( + <button + key={pos} + type="button" + data-strip-picker-go={`${s.index}:${pos}`} + className="ink-link" + onClick={() => { + setPicker(null); + onEdit?.({ op: "section-move", ids: [picker.id], section: s.index, position: pos, words: `${picker.id} → the ${pos} of ${sectionName(sections, s.index)}` }); + }} + > + {pos} + </button> + ))} + </li> + ))} + </ul> + </div> + )} </section> ); } diff --git a/umtool/components/projects/review/WhatPlays.tsx b/umtool/components/projects/review/WhatPlays.tsx @@ -0,0 +1,159 @@ +"use client"; + +import Link from "next/link"; +import { playHref, takesHref } from "@/lib/hrefs"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// WHAT PLAYS (operator, 1 Nov 2026): the working cut's NAME, as prominent as a +// take's -- "Latest: draft-22 · 28:03 · +3 edits since" -- and the switch to an +// older take or to the manifest alone. The latest take is the newest +// whole-cut take made from the project (lib/report/workingCut.mjs); the edits +// since it are the project's manifest against what that take rendered. The +// pick (verdicts.json) is secondary: named small, only when it is not the +// latest. Every switch is a link (`?take=`, `?cut=1`, nothing for the latest); +// `onNavigate` lets Play stop writing its own URL while one is in flight. +// --------------------------------------------------------------------------- + +export type WorkingCut = { + latest: { id: string; label: string; builtAt: string | null; seconds: number | null } | null; + edits: { count: number; words: string[]; same: boolean } | null; + picked: { id: string; at: string | null; pinned: boolean; label: string } | null; +} | null; + +export type WhatPlaysTake = { id: string; label: string; summary: string; made: boolean; from: string; ownTimeline?: boolean; defaulted?: boolean } | null; + +const mmss = (s: number | null) => (typeof s === "number" ? `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}` : null); +const day = (iso: string | null) => { + if (!iso) return null; + const d = new Date(iso); + return Number.isNaN(d.getTime()) ? null : d.toLocaleDateString(undefined, { day: "numeric", month: "short" }); +}; + +/** "+3 edits since" / "no edits since" / "edits since: unknown". */ +export function editsLine(w: WorkingCut) { + if (!w?.latest) return ""; + if (!w.edits) return "edits since: unknown"; + return w.edits.count === 0 ? "no edits since" : `+${w.edits.count} edit${w.edits.count === 1 ? "" : "s"} since`; +} + +/** The working cut's line, alone (the bench's head, the Takes page). */ +export function LatestLine({ project, working, className }: { project: string; working: WorkingCut; className?: string }) { + if (!working) return null; + const l = working.latest; + return ( + <span data-working-cut={l?.id ?? ""} data-working-edits={working.edits?.count ?? ""} className={cn("inline-flex flex-wrap items-baseline gap-x-1.5", className)}> + {l ? ( + <> + <span className="micro">Latest</span> + <Link href={playHref(project)} className="font-mono font-medium text-text hover:underline" title={l.label}> + {l.id} + </Link> + {mmss(l.seconds) && <span className="font-mono text-muted">{mmss(l.seconds)}</span>} + <span className="text-muted" title={working.edits?.words.join("\n") || undefined} data-working-edit-words={working.edits?.words.join("; ") ?? ""}> + · {editsLine(working)} + </span> + </> + ) : ( + <span className="text-muted">no whole-cut take yet — the manifest is the cut</span> + )} + </span> + ); +} + +export default function WhatPlays({ + project, + take, + takes, + working, + onNavigate, +}: { + project: string; + take: WhatPlaysTake; + takes: { id: string; label: string; made: boolean }[]; + working: WorkingCut; + onNavigate?: () => void; +}) { + const latest = working?.latest ?? null; + const current = take?.id ?? null; + const isLatest = !!latest && current === latest.id; + // A few takes are pills; many are a list (the latest and the one playing stay pills). + const many = takes.length > 4; + const pills = many ? takes.filter((t) => t.id === current || t.id === latest?.id) : takes; + const rest = many ? takes.filter((t) => !pills.includes(t)) : []; + const link = (t: { id: string | null; label: string; made: boolean }, label: string) => { + const on = t.id === null ? take === null : t.id === current; + const href = t.id === null ? playHref(project, { bare: true }) : t.id === latest?.id ? playHref(project) : playHref(project, { take: t.id }); + return ( + <Link + key={t.id ?? "cut"} + href={href} + onClick={onNavigate} + aria-current={on ? "page" : undefined} + data-play-take-link={t.id ?? ""} + title={t.id ? `${t.label}${t.made ? "" : " (not rendered yet)"}` : "the project's manifest alone: no take's look"} + className={cn("rounded-[2px] px-2 py-0.5", on ? "bg-panel-2 font-medium text-text" : "text-muted-2 hover:text-text", !t.made && "italic")} + > + {label} + </Link> + ); + }; + return ( + <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1"> + {/* The working cut's name, first and largest. */} + <span + data-play-working={latest?.id ?? ""} + data-play-working-edits={working?.edits?.count ?? ""} + className="inline-flex flex-wrap items-baseline gap-x-1.5 text-[13px]" + > + {latest ? ( + <> + <span className="micro">{isLatest ? "Latest" : "Latest is"}</span> + {isLatest ? ( + <span className="font-mono font-semibold text-text" title={latest.label}> + {latest.id} + </span> + ) : ( + <Link href={playHref(project)} onClick={onNavigate} className="font-mono font-semibold text-text underline decoration-dotted" title={`${latest.label} — play it`} data-play-latest-link=""> + {latest.id} + </Link> + )} + {mmss(latest.seconds) && <span className="font-mono text-[12px] text-muted">{mmss(latest.seconds)}</span>} + <span className="text-[12px] text-muted" title={working?.edits?.words.join("\n") || undefined} data-play-edit-words={working?.edits?.words.join("; ") ?? ""}> + · {editsLine(working)} + </span> + </> + ) : ( + <span className="text-[12px] text-muted">no whole-cut take yet — the manifest is the cut</span> + )} + </span> + <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=""> + {pills.map((t) => link(t, t.id))} + {link({ id: null, label: "the manifest alone", made: true }, "manifest only")} + {rest.length > 0 && ( + <details className="relative" data-play-more-takes=""> + <summary className="cursor-pointer list-none rounded-[2px] px-2 py-0.5 text-muted-2 hover:text-text">{rest.length} more ▾</summary> + <div className="absolute left-0 top-full z-40 mt-1 flex max-h-[50vh] min-w-[260px] flex-col overflow-auto rounded-[3px] border border-seam-2 bg-panel p-1 shadow-lg"> + {rest + .slice() + .reverse() + .map((t) => ( + <span key={t.id} className="flex items-baseline gap-2 whitespace-nowrap"> + {link(t, t.id)} + <span className="truncate text-[11px] text-muted">{t.label}</span> + </span> + ))} + </div> + </details> + )} + </nav> + {working?.picked && working.picked.id !== latest?.id && ( + <Link href={takesHref(project)} className="text-[11px] text-muted-2 hover:text-text" data-play-picked={working.picked.id} title={`“Use this take” last copied ${working.picked.id} over the manifest${working.picked.pinned ? " (pinned)" : ""}`}> + picked: {working.picked.id} + {day(working.picked.at) ? ` (${day(working.picked.at)})` : ""} + {working.picked.pinned ? ", pinned" : ""} + </Link> + )} + </div> + ); +} diff --git a/umtool/components/projects/review/playEngine/audioBank.ts b/umtool/components/projects/review/playEngine/audioBank.ts @@ -1,4 +1,4 @@ -import { keysToTrim } from "@/lib/report/bankTrim.mjs"; +import { coveringSlot, keysToTrim } from "@/lib/report/bankTrim.mjs"; import { timeStretch, wantsStretch } from "@/lib/report/timeStretch.mjs"; import type { MediaRef } from "./engine"; @@ -6,13 +6,20 @@ import type { MediaRef } from "./engine"; // fetched as PCM from the bench's /api/report/audio -- ffmpeg's decode of the // same cached window the picture comes from, so the samples are the ones the // build cuts, with no browser AAC priming to argue about -- and decoded once -// into an AudioBuffer. One buffer per CLIP (its sound and a quarter second -// either side, playSchedule.mjs decodeSpanOf), never a window: a window can be -// a two-minute excerpt and a cut has fifty clips, so the bank holds the clips -// around the playhead and lets the rest go, oldest use first, past a budget -// of decoded bytes (a 20-minute cut never holds 20 minutes of PCM). The clips -// the engine last asked for (touch) are never let go, even over the budget: -// one let go is asked for again at once, and the clock holds on it (bankTrim.mjs). +// into an AudioBuffer. One buffer per clip's SOUND, never a window: a window +// can be a two-minute excerpt and a cut has fifty clips. A clip with gaps is +// one buffer per kept piece (pieces under a second apart share one), never +// its gaps (playSchedule.mjs decodesOf). The bank holds the clips around the +// playhead and lets the rest go, oldest use first, past a budget of decoded +// bytes (a 20-minute cut never holds 20 minutes of PCM). The decodes the +// engine last asked for (touch) are never let go, even over the budget: one +// let go is asked for again at once, and the clock holds on it (bankTrim.mjs). +// +// A DECODE IS FOUND BY WHAT IT COVERS (`resolve`, bankTrim.mjs coveringSlot): +// a node plays from any decode of its clip's window whose span holds the +// seconds it reads, so the decode made on the manifest's edges (wider at the +// ends while the render's are measured) is the one the render's edges play +// from -- each clip's sound is asked for once, not once per set of edges. // // At a speed but 1x a clip is time-stretched at its own pitch (the bench's // timeStretch.mjs, WSOLA) and the stretched copy played at 1x -- the bench's @@ -21,8 +28,12 @@ import type { MediaRef } from "./engine"; /** A clip's decoded sound: its buffer and the source second of its first sample. */ export type ClipSound = { key: string; from: number; buf: AudioBuffer }; +type Span = { from: number; to: number }; + type Slot = { key: string; + /** The source seconds asked for (inside the window: the route clamps to it). */ + span: Span; state: "loading" | "ready" | "failed"; p: Promise<ClipSound | null>; sound: ClipSound | null; @@ -48,19 +59,44 @@ export class AudioBank { private budget = DEFAULT_BUDGET, ) {} - static keyOf(id: string, media: MediaRef, span: { from: number; to: number }) { - return `${id}|${media.name}|${media.v ?? ""}|${span.from}|${span.to}`; + static keyOf(id: string, media: MediaRef, span: Span) { + return `${AudioBank.prefixOf(id, media)}${span.from}|${span.to}`; + } + + /** Every decode of one clip's window (these bytes) starts with this. */ + static prefixOf(id: string, media: MediaRef) { + return `${id}|${media.name}|${media.v ?? ""}|`; } - /** The decode of a clip's span: started once, shared by every caller. */ - request(id: string, media: MediaRef, span: { from: number; to: number }): Promise<ClipSound | null> { + /** A decode held (or under way) that covers `need`, without asking for anything: its key, or null. */ + lookup(id: string, media: MediaRef, need: Span): string | null { + return coveringSlot([...this.slots.values()], AudioBank.prefixOf(id, media), need); + } + + /** + * The decode a span plays from: one held that covers `need` if there is + * one, else `ask` decoded (started once, shared by every caller). Its key, + * for peek and touch, and its promise. + */ + resolve(id: string, media: MediaRef, need: Span, ask: Span): { key: string; p: Promise<ClipSound | null> } { + const have = this.lookup(id, media, need); + if (have) { + const s = this.slots.get(have)!; + s.used = ++this.clock; + return { key: have, p: s.p }; + } + return { key: AudioBank.keyOf(id, media, ask), p: this.request(id, media, ask) }; + } + + /** The decode of exactly this span: started once, shared by every caller. */ + request(id: string, media: MediaRef, span: Span): Promise<ClipSound | null> { const key = AudioBank.keyOf(id, media, span); const have = this.slots.get(key); if (have) { have.used = ++this.clock; return have.p; } - const slot: Slot = { key, state: "loading", p: Promise.resolve(null), sound: null, why: null, bytes: 0, used: ++this.clock }; + const slot: Slot = { key, span: { from: span.from, to: span.to }, state: "loading", p: Promise.resolve(null), sound: null, why: null, bytes: 0, used: ++this.clock }; slot.p = (async () => { try { const r = await fetch(this.urlOf(id, media, span.from, span.to)); @@ -90,17 +126,17 @@ export class AudioBank { return slot.p; } - /** What the bank has for a clip now, without waiting: the sound, "loading", or "failed". */ - peek(id: string, media: MediaRef, span: { from: number; to: number }): ClipSound | "loading" | "failed" | null { - const s = this.slots.get(AudioBank.keyOf(id, media, span)); + /** What the bank has under a key now, without waiting: the sound, "loading", or "failed". */ + peek(key: string | null): ClipSound | "loading" | "failed" | null { + const s = key ? this.slots.get(key) : undefined; if (!s) return null; s.used = ++this.clock; return s.state === "ready" ? s.sound : s.state; } - /** Why a clip's sound did not decode (said in the Approximate line). */ - why(id: string, media: MediaRef, span: { from: number; to: number }) { - return this.slots.get(AudioBank.keyOf(id, media, span))?.why ?? null; + /** Why a decode failed (said in the Approximate line). */ + why(key: string) { + return this.slots.get(key)?.why ?? null; } /** These are the clips wanted now: marked in use, and kept by every trim until the next touch. */ @@ -144,6 +180,18 @@ export class AudioBank { return this.slots.size; } + /** Seconds of sound decoded and held now. */ + get seconds() { + let n = 0; + for (const s of this.slots.values()) n += s.sound?.buf.duration ?? 0; + return Math.round(n * 1000) / 1000; + } + + /** Each decode held: its clip, the span asked for and its state (the engine's stats, for the e2e and a probe). */ + get held() { + return [...this.slots.values()].map((s) => ({ id: s.key.split("|")[0], from: s.span.from, to: s.span.to, state: s.state })); + } + /** Over the budget: the least recently used decodes not wanted now go (a failure is kept, it is small and says why). */ private trim() { for (const k of keysToTrim([...this.slots.values()], this.wanted, this.budget)) this.slots.delete(k); diff --git a/umtool/components/projects/review/playEngine/codecPicture.ts b/umtool/components/projects/review/playEngine/codecPicture.ts @@ -23,12 +23,16 @@ type Track = NonNullable<ReturnType<typeof videoTrackOf>>; /** Frames decoded ahead of the one on screen, at most. */ const MAX_FRAMES = 10; +/** Frames a primed decoder (the piece after a gap's join, not on screen yet) holds ready. */ +const PRIME_FRAMES = 3; /** How far ahead of the clock (s, in decode order) chunks are fed. */ const AHEAD_S = 0.6; /** * A byte-range read: up to this many samples (four seconds at 30 fps) or * bytes, whichever comes first -- few round trips, since a busy server answers - * each in a few hundred ms -- and the blocks a clip keeps. + * each in a few hundred ms -- and the blocks a clip keeps. A count of SAMPLES + * (frames), not seconds: two seconds at 60 fps, which is only more round + * trips (a block is found by sample index, never by time), not a wrong frame. */ const BLOCK = 120; const BLOCK_BYTES = 2 * 1024 * 1024; @@ -245,8 +249,12 @@ class ClipDecoder { this.flushed = false; } - /** Decode toward media time t (s): seek when t is outside what is queued or coming, then feed ahead. */ - want(t: number) { + /** + * Decode toward media time t (s): seek when t is outside what is queued or coming, then feed + * ahead -- at most `limit` frames decoded or queued (a primed piece holds a few, not a full queue: + * every open VideoFrame is decoder memory, and three decoders' full queues stall a decoder). + */ + want(t: number, limit = MAX_FRAMES) { if (this.state !== "ready" || !this.dec || !this.track) return; const s = this.track.samples; const tUs = t * 1e6; @@ -258,7 +266,9 @@ class ClipDecoder { const farAhead = this.q.head < tUs - 1e6 && this.feed >= 0 && seekPoint(s, t).key > this.feed; if (this.feed < 0 || behind || farAhead) this.seek(t); try { - while (this.dec.decodeQueueSize + this.q.size < MAX_FRAMES && this.feed < s.length) { + // The decoder kept busy (MAX_FRAMES in flight, the way through a long GOP to the frame wanted), + // the frames HELD bounded by `limit`. + while (this.q.size < limit && this.dec.decodeQueueSize + this.q.size < MAX_FRAMES && this.feed < s.length) { const x = s[this.feed]; if (x.dts > t + AHEAD_S) break; const data = this.bytesOf(this.feed); @@ -313,22 +323,27 @@ class ClipDecoder { } } -/** The decoders of the clips on screen and the next: one per cached window URL, let go when not wanted. */ +/** + * The decoders of the clips on screen and the next: one per cached window URL -- and per kept + * piece of a gapped clip (`<url>#p<k>`, the piece after a join primed before it) -- let go when + * not wanted. + */ export class CodecPicture { private clips = new Map<string, ClipDecoder>(); private tick = 0; /** Decode toward each wanted (url, media time); close the decoders nobody wants now. */ - sync(wants: { url: string; mediaTime: number }[]) { + sync(wants: { url: string; mediaTime: number; prime?: boolean }[]) { this.tick += 1; for (const w of wants) { let d = this.clips.get(w.url); if (!d) { - d = new ClipDecoder(w.url); + // `<url>#p<k>`: a gapped clip's later piece, decoded by a decoder of its own (engine.ts pieceKeys). + d = new ClipDecoder(w.url.replace(/#p\d+$/, "")); this.clips.set(w.url, d); } d.used = this.tick; - d.want(w.mediaTime); + d.want(w.mediaTime, w.prime ? PRIME_FRAMES : MAX_FRAMES); } for (const [url, d] of this.clips) { // A refusal is remembered (cheap, and asking again would fetch the moov again); anything else unwanted is closed. diff --git a/umtool/components/projects/review/playEngine/engine.ts b/umtool/components/projects/review/playEngine/engine.ts @@ -1,7 +1,7 @@ import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH } from "umtool-report-to-video/clip-blur"; import { inGap } from "umtool-report-to-video/gaps"; -import { cutAtSource, itemIndexAt, playPlan, sourceAt } from "@/lib/report/playCut.mjs"; -import { audioSpans, decodeSpanOf, scheduleFrom } from "@/lib/report/playSchedule.mjs"; +import { cutAtSource, itemIndexAt, pieceWants, playPlan, sourceAt } from "@/lib/report/playCut.mjs"; +import { EDGE_SLACK, audioSpans, decodesOf, scheduleFrom } from "@/lib/report/playSchedule.mjs"; import { drawFootageLayers, type FootageLayer } from "../footageCanvas"; import { AudioBank, type ClipSound } from "./audioBank"; import { CodecPicture, codecsAvailable } from "./codecPicture"; @@ -83,6 +83,8 @@ const DUE = 0.06; const START_LEAD = 0.08; /** A WebCodecs clip this far behind the sound (s) for this long (ms) plays on an element instead. */ const LAG_S = 0.25; +/** A gapped clip's later piece is a slot of its own on the elements: item index + piece × this. */ +const PIECE_SLOT = 100_000; const LAG_FOR = 700; /** Clips decoded ahead of and behind the playhead. */ const DECODE_AHEAD = 3; @@ -94,6 +96,10 @@ export class PlayEngine { plan: Plan = { items: [], total: 0, edges: "estimate" }; private entries = new Map<string, EngineEntry>(); private spans: ReturnType<typeof audioSpans> = []; + /** Each clip's decodes, one per span (its piece), from the plan and the entry's window (decodesOf). */ + private decodes = new Map<string, ReturnType<typeof decodesOf>>(); + /** The plan's edges are the manifest's until the render's are measured: decode wider at a clip's ends. */ + private edgesPending = false; private failed = new Set<string>(); private silent: Record<string, string> = {}; @@ -166,11 +172,19 @@ export class PlayEngine { // ---- what plays ----------------------------------------------------------- - setPlan(plan: Plan, entries: Map<string, EngineEntry>) { + setPlan(plan: Plan, entries: Map<string, EngineEntry>, { edgesPending = false }: { edgesPending?: boolean } = {}) { const was = this.plan; + if (plan === was && entries === this.entries) { + // Only the edges' state moved (measuring, then an estimate after all): the decodes, not the clock. + this.edgesPending = edgesPending; + this.decodes = this.decodePlan(); + return; + } this.plan = plan; this.entries = entries; + this.edgesPending = edgesPending; this.spans = audioSpans(plan as never); + this.decodes = this.decodePlan(); if (was.items.length && plan.items.length) { // The same moment of the same clip after a re-plan (the render's edges // arriving, a reload): by its source second when it is a clip. @@ -202,7 +216,7 @@ export class PlayEngine { /** A slot's media will not play: that clip plays as a placeholder from here on. */ slotFailed(k: number) { const i = this.elements.fail(k); - const item = this.plan.items[i]; + const item = this.plan.items[i % PIECE_SLOT]; if (!item) return; this.failed.add(item.id); this.o.onFailed(item.id, "the media did not load"); @@ -340,29 +354,70 @@ export class PlayEngine { // ---- the sound ------------------------------------------------------------------ - private spanSound(id: string): { media: MediaRef; span: { from: number; to: number } } | null { + /** + * What each clip's sound is decoded as: per kept piece of a gapped clip + * (never its gaps), padded, and while the render's edges are measured + * EDGE_SLACK wider at its two ends -- so the render's edges play from the + * same decode (audioBank.ts resolve) and nothing is asked for twice. + */ + private decodePlan() { + const byId = new Map<string, ReturnType<typeof audioSpans>>(); + for (const s of this.spans) byId.set(s.id, [...(byId.get(s.id) ?? []), s]); + const out = new Map<string, ReturnType<typeof decodesOf>>(); + for (const [id, spans] of byId) { + const m = this.entries.get(id)?.media; + if (!m) continue; + out.set(id, decodesOf(spans, { slack: this.edgesPending ? EDGE_SLACK : 0, within: { from: m.from, to: m.to } })); + } + return out; + } + + /** The decode a span of a clip plays from (its piece): the window, what it reads, and what to ask for. */ + private spanSound(id: string, piece: number) { const e = this.entries.get(id); - // A clip with gaps is several spans (one per piece that plays): ONE decode covers them all. - const all = this.spans.filter((x) => x.id === id); - if (!e?.media || !all.length) return null; - const s = { src: Math.min(...all.map((x) => x.src)), srcTo: Math.max(...all.map((x) => x.srcTo)) }; - return { media: e.media, span: decodeSpanOf(s) }; + const d = this.decodes.get(id)?.[piece]; + if (!e?.media || !d) return null; + return { media: e.media, need: d.need, ask: d.ask }; } - /** Decode the clips around the playhead; the bank lets the far ones go. */ + /** + * Decode the clips around the playhead, in the order they are due: a clip + * behind whose sound still runs past the playhead (the tail of a crossfade + * into this one) first, then the one playing, then those ahead, then the + * rest behind -- the browser runs a few requests at once and queues the + * rest. The bank lets the far ones go. + */ private prefetch() { const keys: string[] = []; - for (let i = Math.max(0, this.cur - DECODE_BEHIND); i <= Math.min(this.plan.items.length - 1, this.cur + DECODE_AHEAD); i += 1) { + const last = this.plan.items.length - 1; + const t = this.now(); + const sounding = (i: number) => { + const id = this.plan.items[i]?.id; + return this.spans.some((s) => s.id === id && s.to > t); + }; + const behind: number[] = []; + for (let i = this.cur - 1; i >= Math.max(0, this.cur - DECODE_BEHIND); i -= 1) behind.push(i); + const order: number[] = behind.filter(sounding); + for (let i = this.cur; i <= Math.min(last, this.cur + DECODE_AHEAD); i += 1) order.push(i); + order.push(...behind.filter((i) => !sounding(i))); + for (const i of order) { const it = this.plan.items[i]; - if (!it.clip) continue; - const ss = this.spanSound(it.id); - if (!ss) continue; - keys.push(AudioBank.keyOf(it.id, ss.media, ss.span)); - void this.bank.request(it.id, ss.media, ss.span).then((got) => { - if (!got && !this.silent[it.id]) { - this.silent = { ...this.silent, [it.id]: this.bank.why(it.id, ss.media, ss.span) ?? "no sound" }; - } - }); + if (!it?.clip) continue; + const ds = this.decodes.get(it.id); + const media = this.entries.get(it.id)?.media; + if (!ds || !media) continue; + // Its pieces still to sound first (a seek into a gapped clip: the piece playing before the ones behind it). + const mine = this.spans.filter((x) => x.id === it.id); + const pieces = ds.map((d, k) => ({ d, done: (mine[k]?.to ?? Infinity) <= t })); + for (const { d } of [...pieces.filter((x) => !x.done), ...pieces.filter((x) => x.done)]) { + const got = this.bank.resolve(it.id, media, d.need, d.ask); + keys.push(got.key); + void got.p.then((sound) => { + if (!sound && !this.silent[it.id]) { + this.silent = { ...this.silent, [it.id]: this.bank.why(got.key) ?? "no sound" }; + } + }); + } } this.bank.touch(keys); } @@ -380,8 +435,8 @@ export class PlayEngine { this.started.add(key); continue; } - const ss = this.spanSound(p.id); - const got = ss ? this.bank.peek(p.id, ss.media, ss.span) : "failed"; + const ss = this.spanSound(p.id, p.piece); + const got = ss ? this.bank.peek(this.bank.lookup(p.id, ss.media, ss.need)) : "failed"; // (A clip whose PICTURE failed still sounds: its sound is decoded on the server, not by the element.) if (got === "failed" || !ss) { this.started.add(key); // silent: the clock goes on @@ -462,10 +517,9 @@ export class PlayEngine { if (this.playing && this.waiting) { // Held: start again once what was due is decoded. const p = this.plannedFrom.find((x) => !this.started.has(`${x.id}|${x.atWall}`) && this.t0 + (x.atWall + x.durWall) * this.rate > this.t); - const ss = p ? this.spanSound(p.id) : null; + const ss = p ? this.spanSound(p.id, p.piece) : null; // Asked for here too: a hold far from where the prefetch looks (a seek) must not wait on nothing. - if (p && ss) void this.bank.request(p.id, ss.media, ss.span); - const got = p && ss ? this.bank.peek(p.id, ss.media, ss.span) : null; + const got = p && ss ? this.bank.peek(this.bank.resolve(p.id, ss.media, ss.need, ss.ask).key) : null; if (!p || !ss || got === "failed" || (got && got !== "loading" && this.bank.hasRate(got as ClipSound, this.rate))) { this.restart(this.t); } else if (got && got !== "loading") this.bank.atRate(got as ClipSound, this.rate); @@ -516,6 +570,14 @@ export class PlayEngine { return it && e?.media ? this.o.srcOf(it.id, e.media) : null; } + /** The decoder keys for item i at t: its piece playing, and the next piece when its join is near. */ + private pieceKeys(i: number, t: number, url: string) { + const it = this.plan.items[i]; + const e = this.entries.get(it.id); + if (!it.clip?.gaps?.length) return [{ key: url, mediaTime: this.mediaTimeOf(i, t), piece: 0 }]; + return pieceWants(it, t, e?.media?.from ?? 0, { ahead: 2 * Math.max(1, this.rate) }).map((w) => ({ key: w.piece ? `${url}#p${w.piece}` : url, mediaTime: w.mediaTime, piece: w.piece })); + } + private mediaTimeOf(i: number, t: number) { const it = this.plan.items[i]; const e = this.entries.get(it.id); @@ -538,37 +600,55 @@ export class PlayEngine { const inFootage = (i: number) => !!items[i].clip && t <= items[i].clip!.playEnd && t >= items[i].start; const layers: { i: number; alpha: number; source: CanvasImageSource | null; w: number; h: number }[] = []; const viaElement: { i: number; alpha: number }[] = []; - const codecWants: { url: string; mediaTime: number }[] = []; + const codecWants: { url: string; mediaTime: number; prime?: boolean }[] = []; + // A gapped clip decodes per kept piece (`<url>#p<k>`), the piece after the next join primed + // before it (playCut.mjs pieceWants): the picture no longer holds at a long gap's jump. + const keyOf = new Map<number, { key: string; mediaTime: number; piece: number }>(); + // On the elements too: the piece after the join waits in the second <video>, seeked, so the + // join swaps slots instead of seeking one (pieces are slots of their own: PIECE_SLOT). + let elementPrime: { i: number; piece: number; mediaTime: number } | null = null; + const pieceWantsOf = new Map<number, { key: string; mediaTime: number; piece: number }[]>(); for (const v of vis) { const url = this.mediaUrl(v.i)!; - const st = this.codecs?.status(url); - if (this.codecs && st !== "unsupported" && st !== "failed") codecWants.push({ url, mediaTime: this.mediaTimeOf(v.i, t) }); - else viaElement.push(v); + const wants = this.pieceKeys(v.i, t, url); + pieceWantsOf.set(v.i, wants); + keyOf.set(v.i, wants[0]); + const st = this.codecs?.status(wants[0].key); + if (this.codecs && st !== "unsupported" && st !== "failed") wants.forEach((w, k) => codecWants.push({ url: w.key, mediaTime: w.mediaTime, prime: k > 0 })); + else { + viaElement.push(v); + if (wants[1] && vis.length === 1) elementPrime = { i: v.i, piece: wants[1].piece, mediaTime: wants[1].mediaTime }; + } } + const slotOf = (i: number) => (keyOf.get(i)?.piece ? i + keyOf.get(i)!.piece * PIECE_SLOT : i); const nextUrl = nextI >= 0 ? this.mediaUrl(nextI) : null; const nextSt = nextUrl && this.codecs ? this.codecs.status(nextUrl) : "unsupported"; if (nextUrl && this.codecs && nextSt !== "unsupported" && nextSt !== "failed") { - codecWants.push({ url: nextUrl, mediaTime: this.mediaTimeOf(nextI, items[nextI].start) }); + codecWants.push({ url: nextUrl, mediaTime: this.mediaTimeOf(nextI, items[nextI].start), prime: true }); } this.codecs?.sync(codecWants); // The elements hold what WebCodecs does not: the clips it refused, and the next one when it refused that. const elementNext = nextI >= 0 && (!this.codecs || nextSt === "unsupported" || nextSt === "failed") ? nextI : -1; + const ep = elementPrime as { i: number; piece: number; mediaTime: number } | null; this.elements.sync( - viaElement.map((v) => ({ index: v.i, id: items[v.i].id, url: this.mediaUrl(v.i)!, mediaTime: this.mediaTimeOf(v.i, t), play: runs && inFootage(v.i) })), - elementNext >= 0 ? { index: elementNext, id: items[elementNext].id, url: this.mediaUrl(elementNext)!, mediaTime: this.mediaTimeOf(elementNext, items[elementNext].start), play: false } : null, + viaElement.map((v) => ({ index: slotOf(v.i), id: items[v.i].id, url: this.mediaUrl(v.i)!, mediaTime: keyOf.get(v.i)?.mediaTime ?? this.mediaTimeOf(v.i, t), play: runs && inFootage(v.i) })), + ep + ? { index: ep.i + ep.piece * PIECE_SLOT, id: items[ep.i].id, url: this.mediaUrl(ep.i)!, mediaTime: ep.mediaTime, play: false } + : elementNext >= 0 + ? { index: elementNext, id: items[elementNext].id, url: this.mediaUrl(elementNext)!, mediaTime: this.mediaTimeOf(elementNext, items[elementNext].start), play: false } + : null, this.rate, ); for (const v of vis) { - const url = this.mediaUrl(v.i)!; if (this.codecs && !viaElement.includes(v)) { - const want = this.mediaTimeOf(v.i, t); - const f = this.codecs.frameFor(url, want); + const { key, mediaTime: want } = keyOf.get(v.i)!; + const f = this.codecs.frameFor(key, want); if (f && runs) this.measure(items[v.i].id, f.timestamp / 1e6, want, (f.duration ?? 33_333) / 1e6); - if (runs && inFootage(v.i)) this.keepingUp(url, f ? want - f.timestamp / 1e6 : Infinity); + if (runs && inFootage(v.i)) this.keepingUp(key, f ? want - f.timestamp / 1e6 : Infinity); layers.push({ ...v, source: f, w: f?.displayWidth ?? 0, h: f?.displayHeight ?? 0 }); } else { - const el = this.elements.sourceFor(v.i); - if (el && runs && inFootage(v.i)) this.measure(items[v.i].id, this.elements.presentedFor(v.i) ?? el.currentTime, this.mediaTimeOf(v.i, t), this.elements.frameFor(v.i)); + const el = this.elements.sourceFor(slotOf(v.i)); + if (el && runs && inFootage(v.i)) this.measure(items[v.i].id, this.elements.presentedFor(slotOf(v.i)) ?? el.currentTime, this.mediaTimeOf(v.i, t), this.elements.frameFor(slotOf(v.i))); layers.push({ ...v, source: el, w: el?.videoWidth ?? 0, h: el?.videoHeight ?? 0 }); } } @@ -688,7 +768,7 @@ export class PlayEngine { /** How many clips' sound is decoded now, and the decoders open (read by the e2e through a data attribute). */ get stats() { return { - decoded: this.bank.size, bytes: this.bank.bytes, decoders: this.codecs?.open ?? 0, nodes: this.nodes.length, + decoded: this.bank.size, bytes: this.bank.bytes, decodedSeconds: this.bank.seconds, held: this.bank.held, decoders: this.codecs?.open ?? 0, nodes: this.nodes.length, scheduled: this.measured.nodes, framesDrawn: this.measured.drawn, framesOff: this.measured.off, worstFrames: this.measured.worst, offFrames: this.measured.late, contextTime: this.ctx?.currentTime ?? null, sound: this.sound, }; diff --git a/umtool/components/projects/review/playEngine/usePlayEngine.ts b/umtool/components/projects/review/playEngine/usePlayEngine.ts @@ -19,9 +19,11 @@ type Args = { bg: string; /** render.transitionStyle: how a crossfade is drawn (a dissolve, or a dip through the ground). */ style: string; + /** The plan's edges are the manifest's until the render's are measured (useRenderCuts `measuring`). */ + edgesPending?: boolean; }; -export function usePlayEngine({ plan, entries, srcOf, audioOf, blurRendered, bg, style }: Args) { +export function usePlayEngine({ plan, entries, srcOf, audioOf, blurRendered, bg, style, edgesPending = false }: Args) { const [ui, setUi] = useState<EngineUi>({ t: 0, cur: 0, playing: false, ended: false, waiting: false }); const [failed, setFailed] = useState<Record<string, string>>({}); const [info, setInfo] = useState<EngineInfo | null>(null); @@ -29,8 +31,8 @@ export function usePlayEngine({ plan, entries, srcOf, audioOf, blurRendered, bg, const eng = useRef<PlayEngine | null>(null); const fns = useRef({ srcOf, audioOf }); fns.current = { srcOf, audioOf }; - const latest = useRef({ plan, entries }); - latest.current = { plan, entries }; + const latest = useRef({ plan, entries, edgesPending }); + latest.current = { plan, entries, edgesPending }; // Elements attach before the engine exists (refs before effects): held here and handed over. const els = useRef<{ canvas: HTMLCanvasElement | null; slots: (HTMLVideoElement | null)[] }>({ canvas: null, slots: [null, null] }); @@ -53,7 +55,7 @@ export function usePlayEngine({ plan, entries, srcOf, audioOf, blurRendered, bg, }); e.attachCanvas(els.current.canvas); els.current.slots.forEach((el, k) => e.attachSlot(k, el)); - e.setPlan(latest.current.plan, latest.current.entries); + e.setPlan(latest.current.plan, latest.current.entries, { edgesPending: latest.current.edgesPending }); eng.current = e; // A handle for a console and the e2e (play-engine.spec.ts): the engine's own clock and its measurements. (window as Window & { __umtoolPlayEngine?: PlayEngine }).__umtoolPlayEngine = e; @@ -66,8 +68,8 @@ export function usePlayEngine({ plan, entries, srcOf, audioOf, blurRendered, bg, }, []); useEffect(() => { - eng.current?.setPlan(plan, entries); - }, [plan, entries]); + eng.current?.setPlan(plan, entries, { edgesPending }); + }, [plan, entries, edgesPending]); useEffect(() => { eng.current?.setRate(rate); }, [rate]); diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -23,7 +23,11 @@ Inbox cannot disagree about what is wrong with one. | `inbox [--all] [--json]` | the decisions grouped and ranked by piece (`a:<site>/<report>`, `p:<project>`): Your call, Review, Blocking, Notes, Open, Ready to finish, Quiet — one card per piece and kind, and how many sit hidden on parked or done pieces (`--all` lists them). Every decision, songs' and articles' included; runs `bin/inbox.ts` through tsx | | `folders [--json]` · `kinds [--json]` | the tree, the registry | | `window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] [--no-lock-end] [--note …]` | edit a window | +| `window <project> <clip> --start S --end E --move-stamp first\|nearest\|<s>` · `--clear-stamp` · `--move-mute nearest` · `--clear-mute` | a window edit refused because a stamp's second (`claim.at`, a mark's `at`) or the mute mark would fall outside it, with the fix in the same write: the stamp to the first second that plays, the nearest, or `<s>`, or its `at` cleared; the mute mark to the nearest second, or cleared (never inside a gap). A refused `window` names these flags ([clip-bench.md](clip-bench.md#saving)) | | `window <project> <clip> --verdict confirmed\|incorrect [--correction T]` · `window <project> <clip> --reject <why> [--note T]` | what the walk said: `--reject` is the walk's **Reject ▾** kept in place (`not-matching`/`wrong-speaker`: incorrect, the note its correction; `irrelevant`/`repeats`/`weak`/`privacy`/`other`: rejected, the note its `rejectNote`); `umtool timeline <p> reject` takes it out ([report-video.md](report-video.md#verdict--what-the-walk-said)) | +| `window <project> <clip> --walk-note T` · `--star` / `--no-star` · `--repeat-of <clip>` | what the walk said that is not a verdict: an editorial note (not a correction) and the ★ favourite, a trailer candidate (`trailer <project> --candidates [--json]` lists them as beats); a deliberate repeat ([knobs.md](knobs.md#a-clip)) | +| `links <project> [--json] [--fix]` | do the clip QRs open on their sites? `corpus.json` → the channel's manifest → `slugToPage` → the shard's record, one request at a time, shards from the cue cache; recorded in `out/links.json`, which `check` reads (`link-dead` blocking, `links-unverified`, `links-unchecked`); `--fix` rewrites a Twitch id the site serves as `v<id>`; **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)) | +| `patch-markers <project> [<file>.patch.json] [--fix] [--json]` | take patches whose deck markers name a clip not in the cut (a take made with one is refused); `--fix` gives each the `after` of the cut's marker of the same label; **exit 1** when one is left ([knobs.md](knobs.md#take-patches-follow-a-removal)) | | `window <project> <clip> --take <take> …` | a **take's** clip (walk a take): the same fields, written into the take's patch (`takes/<take>/take.json`) with an undo point first; the project's manifest is untouched ([clip-bench.md](clip-bench.md#walking-a-take)) | | `walk <project> [--take <take>] [--all] [--json]` | the clip bench's **walk**: every clip in walk order with its window, verdict and whether a fetched file holds it, and (→) the ones the walk visits — fetched and needing a verdict; `--all` every fetched one; `--take` walks a take (a draft too); the bench's address to start at | | `link <project> <site>/<report>` · `link <project> --clear` | the manifest names the article it is the video of (settles `link-ambiguous`) | @@ -51,8 +55,10 @@ Inbox cannot disagree about what is wrong with one. | `take <project> --id <id> --label L [--patch F \| …] --draft` (`--no-render`) · `take <project> --id <id> [--full \| --at S --dur S]` · `take <project> --id <id> --rebuild [--full \| --at S --dur S]` · `take <project> --id <id> --promote [--anyway] [--json]` | a **draft** take: recorded with nothing rendered, to be walked first; a draft named with no patch flags is rendered from its stored (walked) patch, and `--rebuild` takes a window flag; **make it the cut**: the take's patch applied to the manifest now, one undo point (`revisions/…-auto-before-promote-take`), refused (exit 1) when its timeline would replace a cut that changed since, until `--anyway` ([report-video.md](report-video.md#walking-a-take-drafts-edits-into-the-take-and-making-it-the-cut)) | | `take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json \| --print-token]` · `render-mode on [--for 90m] [--note T] [--print-token] -- <cmd …>` · `render-mode off [--force] [--json]` · `render-mode status [--json]` | **render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription and download lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints (`--print-token`: the token alone on stdout, the rest on stderr). **`on … -- <cmd …>` is the form for a script**: the command is spawned with the token in its environment, the hold is the command's pid, and it is released when the command exits — done, failed, or umtool signalled (the signal is passed on); umtool exits with the command's code, and inside a manual window the command joins it. A bare `on` in a script leaves the window behind (the chain trap). `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, "Render mode") | | `takes make <project> [--recipe FILE] [--only ID,ID] [--force]` · `takes make <project> --all-styles [--group G] [--at S --dur S \| --full]` | a recipe's takes, one at a time (default `takes/recipe.json`); every montage style, one take each (Make all styles); **exit 1** if any failed | -| `takes styles [--json]` · `takes effects <project> [--json]` · `takes pick <project> <take> [--anyway] [--json]` | the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway` | +| `takes styles [--json]` · `takes effects <project> [--json]` · `takes pick <project> <take> [--anyway] [--pin \| --unpin] [--json]` | the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway`; `--pin` keeps the pick when newer takes are built (each whole-cut take of the manifest is otherwise its group's pick once built), `--unpin` lets go ([report-video.md](report-video.md#takes-alternative-renders-judged-side-by-side)) | +| `takes ls <project> [--json]` · `takes relabel <project> <take> <label…>` · `takes supersede <project> <take> [--by <take>]` · `takes supersede <project> <take> --clear` · `takes delete <project> <take> [--dry-run] [--force]` | **take housekeeping** (the Takes page's ✎, **Mark superseded**, **Delete take**): first the working cut's line (`Latest: draft-22 · 28:03 · +N edits since`, and the edits in words; `--json`: `working`), then the takes with latest / picked (pinned) / superseded / RENDERING; a label fixed in `take.json` (an undo point of the take's own); a take folded away as superseded (verdicts.json, nothing deleted); a take deleted. Relabel and delete are refused (**exit 1**) while the take renders or a live render is made from it ([knobs.md](knobs.md#takes-relabel-supersede-delete)) | | `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) | +| `trailer-beats <project> [ls] [--json]` · `add <clip> [<from>-<to>] [--at N] [--label L]` · `add-raw <at> <dur>` · `set <n> <from>-<to>` · `remove <n>` · `move <n> --to <m>` · `order` · `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok>` · `xfade <s>` · `intro on\|off` · `candidates [--add]` | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips ([knobs.md](knobs.md#the-trailers-beats)) | | `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) | | `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` · `… --refetch <clipId>[,…]` · `… --refetch-video <slug>/<id>` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. `--refetch <clipId>[,<clipId>…]` evicts the cached windows that OVERLAP those clips' fetch spans first (the editor's `evict-clips` `{slug, id, covering}`, one job per video, waited for), then fetches as usual — for windows known bad (cut from a corrupt saved video); `--refetch-video <slug>/<id>` does it for every window the project asks of that video; with `--dry-run` the eviction is a dry run too and names what it would remove. Every run is recorded in `<project>/fetch-runs.json` (a refetch's evictions under `refetch`). Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) | | `prep <project> [--clips a,b] [--json]` · `prep <project> [--clips a,b] --wait` · `prep <project> --status [--json]` | **Prepare clips for the walk** (the Cut tab's): what the clip bench makes on a clip's first open — a long recording's excerpt, the waveform — made ahead ([clip-bench.md](clip-bench.md#prepared-before-you-open-it)). No flag queues it and returns (a runner starts in the background, its log `out/bench-excerpts/prep.log`); `--wait` runs it here to the end; `--status` prints ready / to prepare / failed / not fetched and the runner. One clip at a time, each in the heavy slot (estimate 400 MB), under `nice -n 19` and `ionice -c3`; a prepared clip is skipped. A fetch that lands and a write that moves or adds a clip queue it too (`UMTOOL_BENCH_PREP=0` turns that off). **Exit 1** when a clip failed (`--wait`) | @@ -61,8 +67,9 @@ Inbox cannot disagree about what is wrong with one. | `phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words \| --regex] [--samples N] [--no-cache] [--json \| --full]` | the phrase finder's search ([tools.md](tools.md#the-phrase-finder-toolsphrases)): every phrase in one pass, each with its count once folded, by year, the preferred channel's share or Rumble's, speaker changes, sample contexts. Plain words become a tolerant pattern unless the phrase holds a regular expression's characters. `--json` the numbers, `--full` every instance; `--spec FILE --out FILE --progress` is the page's job form. **Exit 1** on a bad phrase | | `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video <channel>/<id> …] [--reference-channel <slug> …] [--instances FILE] [--span phrase\|cut] [--pad S] [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]` | who is speaking, per montage clip: a local speaker-similarity score (TitaNet-small) against the host's voice → `<project>/voice-match.json` (the Cut tab's **Score the voices**); `--instances` also scores a phrase scan's instances not in the manifest; `--dry` prints the plan ([report-video.md](report-video.md#who-is-speaking-the-voice-match)) | | `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` · `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` · `clips show <project> [--json]` · `clips segments <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. `--keep-cut` proposes without touching the cut (nothing moved, removed or added; the proposals are listed). **`--scope auto`** reads the narrated video auto-scope finds in the speaker turns (`--segment sN` names one, else the longest); `segments` lists them. A chat replay beside the recording (`live_chat.cues.json`) adds chat-burst moments and the log names the chat's lag. A channel on no site gets each clip linked to its platform page (`citeUrl`). A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) | -| `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) | +| `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) | | `timeline <project> --take <take> [ls \| move <id> --to <index> \| remove <id> \| undo]` | a **take's** timeline (walk a take): the same structure checks, written into the take's patch, each write with an undo point of the take's own (`takes/<take>/revisions/`); `undo` takes the take's newest edit back, whichever writer made it | +| `timeline <project> sections [--json]` · `section-move <id>… --to-section N [--start]` · `section-add --after <id> [--label L] [--color C]` · `section-boundary <marker> --after <id>` · `section-remove <marker>` · `section-set <marker> [--label L] [--color C]` · `split <id> <second>` · `flash-forward <id> <from>-<to> (--after <id\|-> \| --to-section N [--start]) [--move] [--quote Q] [--id ID]` | **sections as sections** (the deck's markers; the Cut tab's section bars and row menus): clips moved to a section with every marker following, a section opened, a boundary moved, relabelled, removed — no section emptied, no boundary crossed (**exit 1**) — and every take patch in step synced; **split** (each half's quote from the words, the second half's cite and QR at its second, a marker after the clip following its second half); **flash-forward** a tight copy of a span elsewhere with the clip's attribution and locks, as `repeatOf` the clip (`--move`: out of the clip) ([knobs.md](knobs.md#sections-split-and-flash-forward-editing-the-cut)) | | `scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10] [--pad 30 \| --from S --to S] [--json]` | the picture's **scene cuts** (ffmpeg `scdet`, score ≥ threshold) and **black spans** (`blackdetect`) in the clip's fetched window, in SOURCE seconds — for `blur.from`/`blur.to` and trims ([knobs.md](knobs.md#a-clips-picture-blurred)). The window is the one the build would cut from (the project's `out/clips-raw`, the editor's `channels/<slug>/data/<id>/clips/`, a saved source); the extent ± `--pad` inside it is scanned. Nothing is fetched: **exit 1** with no window on disk (`fetch` first) | | `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key. Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** | | `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run) | @@ -166,6 +173,19 @@ c01: 43.12–61.48 -> 43.12–61.48 `--gap-remove 51` takes out the gap holding that second; `--gaps ''` clears them all. +An edge move that leaves the clock (`cite`) more than 5 s before what plays — or past its end — +moves it with the edge, and the QR's `t=` with it when the citeUrl names this recording +([knobs.md](knobs.md#the-cite-follows-the-edge)); the CLI says so: + +``` +$ umtool window ferret-rescue c02 --start 1600 +c02: 1522.4–1620 -> 1600–1620 + cite followed the edge: 25:22 -> 26:40 + QR followed: https://archive.example/?v=ferrets%2Fabc123&t=1600 +``` + +`check` prints a row's terminal fix under it when it knows one (`fix: umtool window … --repeat-of …`). + ## `link` names the article a project is the video of An article links to a project its iterations made, to one whose manifest names it diff --git a/umtool/docs/clip-bench.md b/umtool/docs/clip-bench.md @@ -246,6 +246,15 @@ round trips to re-find your place. The Cut tab starts the walk: one because the per-row links are the right control for "go to that one" and the wrong one for "start". +### From Play, in place + +Opened from Play the cut (**Edit this clip**, E) the bench opens IN Play's page, Play kept as it was under +it: the address is the bench's (`?from=play&at&take&order=cut`), Back and Forward step between the two, +and **‹ Back to the cut** returns to the same clip, second and take without Play starting over +([knobs.md](knobs.md#play-the-cut-the-whole-cut-or-a-take-with-no-render)). There `p` / `n` and the +header's links walk the CUT's order — the reel strip's neighbours, judged or not ("40 of 127") — not the +walk's. Opened on its own, the bench's head has **▶ Play the cut from here**. + ### What the walk skips The walk visits the clips that still **need judgement** and are **fetched**, in @@ -347,6 +356,25 @@ differs from the stored window, <kbd>y</kbd> carries `start`/`end` (and clears a cut the new extent no longer contains) in the same patch as the verdict, so walking on never loses the window you just chose. +### ★ and the walk note — not a verdict, not a correction + +<kbd>s</kbd> (or **☆ Star** beside the answers; **☆ Star** in the phone's status line) stars the +clip: a favourite, written at once (`star: true`). A starred clip is a **trailer candidate** — the +Cut tab lists them under **★ trailer candidates**, and `umtool trailer <p> --candidates [--json]` +prints them as a trailer's `--beats-json`. The **walk note** field (beside `correction`) takes an +editorial note — *this is gold*, *wants a beat of silence*, *move it to sex appeal* — as `walkNote`. +Neither touches the verdict, and neither is a `correction`: that field says the REPORT got a fact +wrong and is read by the next report pass. From a terminal: `umtool window <p> <clip> --star` +(`--no-star`), `--walk-note "…"` (`''` clears). A `correction` on a clip already confirmed (or rejected for a cut reason) is +usually such a note written in the only box there was: **move to walk note** beside it moves it in one +write (`umtool window <p> <clip> --walk-note "…" --correction ''`). A clip that re-plays another on purpose shows +**repeats `<clip>`** in the header (`repeatOf`). + +A window you save that leaves the clip's `cite` (the clock) — or its citeUrl's `t=` — more than 5 s +before what plays, or past its end, moves it to the clip's first second, and the save says so +(*saved — the cite followed the edge: 25:22 → 26:40, and the QR with it*). See +[knobs.md](knobs.md#the-cite-follows-the-edge). + A note on a clip that is already **confirmed** is just a note — why its window moved, a caveat for the writers — and writing one there leaves the verdict alone — as it does on a clip rejected for a cut reason, whose facts are right. @@ -476,6 +504,16 @@ header in the same sitting, and two writers would be two chances to lose the other's write. In the component this is why a window save no longer resets the attribution drafts and an attribution save no longer discards nudged edges. +**A save the writer refuses because a stamp's second would fall outside the new window** — `claim.at` (a +mark's `at` on a clip with several), or the mute mark — keeps your edit and offers the fix beside the +message: **Move the stamp to 5862.94 (first second)** — the first second that plays — or **(nearest)**, each +with the words it would land on, and **Clear the stamp's second (claim.at)** (the mute mark: move to the +nearest, or clear). Each is the same save again with the fix (`markFix` first | nearest | a second | clear, +`muteFix` nearest | clear), in one write; a second never lands inside a gap. The terminal's: `umtool window +<p> <clip> --start … --end … --move-stamp first|nearest|<s>` / `--clear-stamp` / `--move-mute nearest` / +`--clear-mute`, and a refused `umtool window` names those flags. The cite and its QR already follow a moved +edge ([knobs.md](knobs.md#the-cite-follows-the-edge)). + See [report-video.md](report-video.md) for the four rules the writer keeps (2 dp, the CLI's formatting, tmp+rename under a lock, an mtime token). A stale token is a **409 with both values**, never a silent overwrite: the other writer is usually diff --git a/umtool/docs/inbox.md b/umtool/docs/inbox.md @@ -64,7 +64,12 @@ on (`decisionTab`, `songTabOfSection`). | `clip-unfetchable` | blocking | the last preflight says the source is gone | Replace the source | | `clip-unchecked` | info | the last preflight could not ask: the platform refused a probe (403, 429, a bot check), so it and the platform's other sources were left `unchecked` | Re-check later | | `clip-mid-sentence` | open | the cut lands inside a cue that does not close a sentence, and `lockEnd` is unset | Trim to the sentence | -| `window-overlap` | open/info | two clips from one source overlap | Fix the windows | +| `window-overlap` | open/info | two clips from one source overlap; the row offers **It's deliberate: `<later>` repeats `<earlier>`** (`repeatOf` through the window writer) | Fix the windows | +| `clip-cite-off` | open | the clock (`cite`) or the QR's `t=` (a citeUrl naming this recording) more than 5 s before what the clip plays, or after it: "the clock and the QR point 78 s before the clip (cite 25:22, it plays 26:40–26:50)"; **Move to 26:40** | Move the cite to the clip | +| `patch-markers-stale` | open | a take patch beside the manifest (`*.patch.json`) whose deck markers name a clip not in the cut — a take made with it is refused; **Take the cut's markers** (the cut's marker of the same label) | Fix the take patch | +| `link-dead` | blocking | the recorded link check (`umtool links`, out/links.json) found clip QRs that don't open on their site — one row per site, the clips and the first reason | Fix the links | +| `links-unverified` | info | the link check could not reach a site (offline, a timeout, no corpus.json) | Check links again | +| `links-unchecked` | info | archive links never checked, or changed since the check | Check links | | `no-punctuation` | info | a source's ASR has no terminators — one row per project | Check the windows | | `clip-cue-gap` | open | the cue file ends before a clip does (`cues end 880 s · c03 needs 897 s`), one row per source | Fix the window | | `claim-unadjudicated` | blocking | a `ledger[]` entry missing any of the six adjudication fields — one row per entry | Adjudicate claim | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -22,7 +22,10 @@ that generates it ([notes.md](notes.md)). | `claim.label` — this stamp's text (≤ 20; default the verdict's stamp word) | Marks, **label** | `claim.label="2 SEIZURES"` | same | | `claim.eventDate` — `YYYY-MM-DD`, the day the event this mark counts happened when it is not the clip's (a seizure he tells of on 8 Oct that was on 22 Sep): a deck claim's window dates the mark by it ([Claim checks](#claim-checks-on-the-rail)); the stamp lands where it always did | Marks, **happened** | `claim.eventDate=2026-09-22` (`--mark <id>` for another mark) | same | | marks — more than one stamp and count on a clip (≤ 8): see [Marks](#marks) | Marks: **Add mark at playhead** (Shift+M), a mark's verdict, **Remove**, **Clear** | `mark.add=Episodes@190.2` `mark.remove=<id>` `mark.verdict=Grift` `marks=<json>` | `POST /api/report/clip-editor {op: "marks", clip, add \| remove \| mark+verdict \| set}` | -| `repeatOf` — the id of the clip this one re-plays ON PURPOSE (a closing callback, a flash-forward cut out of a longer clip): the check's `window-overlap` row and the build's de-overlap leave that pair alone. Must name another clip of the cut; empty clears it | — | `umtool window <p> <clip> --repeat-of <other>` (`--repeat-of ''` clears) | `PUT /api/report/window {project, clip, repeatOf}` | +| `repeatOf` — the id of the clip this one re-plays ON PURPOSE (a closing callback, a flash-forward cut out of a longer clip): the check's `window-overlap` row and the build's de-overlap leave that pair alone. Must name another clip of the cut; empty clears it | the project page's `window-overlap` row: **It's deliberate: `<later>` repeats `<earlier>`**; shown as **repeats `<clip>`** on the Cut tab's row and the bench | `umtool window <p> <clip> --repeat-of <other>` (`--repeat-of ''` clears) | `PUT /api/report/window {project, clip, repeatOf}` | +| `cite` — the second the deck's clock prints (default the clip's start); **follows the edge**: a window or cut save that leaves it more than 5 s before what plays, or past its end, moves it to the first played second, and a citeUrl naming this recording moves its `t=` with it ([below](#the-cite-follows-the-edge)) | clip bench, **cite**; the project page's `clip-cite-off` row: **Move to m:ss** | `umtool window <p> <clip> --cite 1600` | `PUT /api/report/window {project, clip, cite}` | +| `walkNote` — an editorial note from the walk (*this is gold*, *wants a beat of silence*); not a `correction` (a fact error), never rendered; ≤ 2000 | clip bench, **walk note**; the Cut tab's row shows it | `umtool window <p> <clip> --walk-note "…"` (`''` clears) | `PUT /api/report/window {project, clip, walkNote}` | +| `star` — `true`: the walk's favourite, a **trailer candidate** (`lib/report/trailerCandidates.mjs`); not a verdict | clip bench, **☆ Star** (`s`); the Cut tab's **★ trailer candidates** | `umtool window <p> <clip> --star` (`--no-star` clears) · `umtool trailer <p> --candidates [--json]` lists them as beats | `PUT /api/report/window {project, clip, star}` | | `audio.offset` — ms, + = the sound later (−2000…2000) | clip editor, **Audio**: **sync**, the ±10/±40 nudges, **listen** (the 3 s around the playhead) | `umtool set <p> <clip> audio.offset=-40` | `POST /api/report/clip-editor {op: "audio", clip, audio: {offset}}` | | `audio.gain` — dB (−20…20) | Audio, **gain** | `audio.gain=-3` | same | | `audio.fadeIn`, `audio.fadeOut` — seconds (0–5) | Audio, **fade in / fade out** | `audio.fadeIn=0.3` | same | @@ -41,6 +44,49 @@ clip says which one that is, and `umtool set` prints a NOTE. A window save that clip's window is refused: widen the window, or clear `claim.at`. The On-screen table's claim column edits the claim's id and verdict and keeps its knobs while the id stays the same. +## The cite follows the edge + +A clip's `cite` is the second the clock prints and its `citeUrl`'s `t=` the second the QR opens; both +were written against the window the clip had when it was found. The window writer +(`lib/report/citeFollow.mjs`, through `patchClipEntry`, so the bench, Play the cut, a take's walk and +`umtool window` all get it) moves them when an edge move leaves them **more than 5 s before** what +plays (the cut when the clip has one, else the extent) **or past its end**: the cite to the first +played second (floored), the `t=` to the cite. Up to 5 s ahead is a lead-in and is kept. A citeUrl is +moved only when it names this recording (`?v=<channel>/<id>`, Twitch's `v<id>`, or the platform's own +`watch?v=` / `youtu.be/`) — a mirror's clock is not this one's. A patch that writes `cite` itself +moves only the QR, and only when it agreed with the old clock; one that writes `citeUrl` keeps what +it wrote. The CLI prints *cite followed the edge*, the route answers `citeFollowed`. What was left +before this existed is the check's `clip-cite-off` row (open): *the clock and the QR point 78 s before +the clip*, with **Move to m:ss** (`umtool window <p> <clip> --cite N`). + +## Take patches follow a removal + +A take patch beside the manifest (`*.patch.json`, the file `umtool take --patch` reads) that carries +`render.chrome.deck.markers` carries the whole list (a merge patch replaces arrays). Every structural +write — remove, reject, wrong speaker, merge — re-anchors those markers the way it re-anchors the +manifest's (`lib/report/patchMarkers.mjs`): a marker after a removed clip moves to the clip before it, +or is dropped when there is none; `umtool timeline` prints each change (`draft-1.patch.json: deck marker +1 ("Sex appeal") moved from after ow2b to after ow2`). A patch with a `timeline` of its own is left +alone. An **undo** restores the manifest, not the patches. Anything still naming a clip that is not in +the cut is the check's `patch-markers-stale` row (open: a take made with it is refused), with **Take the +cut's markers** (`umtool patch-markers <p> [<file>] --fix`): each such marker takes the `after` of the +cut's marker with the same label; one no marker of the cut shares a label with is left, and named. + +## Do the QR links open? + +`umtool links <p> [--json] [--fix]`, or **Check links** on the project page's link rows, resolves every +clip QR the cut draws (the build's own rules, lint.mjs `qrsOf`) against the site it links: +`corpus.json` → the channel's transcripts manifest → `slugToPage[<id>]` → `page-<NNNN>.json` → the +record. One request at a time; `corpus.json` and the manifests are read fresh, a shard comes from the +cue cache (`REPORT_CACHE_DIR`, the same files the build reads) and is fetched again only when the record +it should hold is missing. A site that does not answer leaves its links **not verified**. The answer is +recorded in `out/links.json`; the check reads it and never fetches: `link-dead` (blocking, one row per +site: *12 of 124 QR links don't open on anilyzer.pages.dev (deployed 2026-10-09): …*), `links-unverified` +(info: *couldn't reach …*), `links-unchecked` (info: never checked, or a link changed since). `--fix` +(the row's **Fix N links (the site's v&lt;id&gt;)**) rewrites the dead links it knows the fix for — a Twitch id +the site serves as `v<id>`, and only a link still exactly what the check saw — through the window writer, +then checks again. A platform link (YouTube's own page) is not an archive link and is not checked. + ## Gaps inside a clip A clip may leave seconds out of its middle: you suggest one long clip and cut a gap or two out of it, rather than @@ -81,8 +127,8 @@ selection); keys `z` in, `Z` out, `f` fit, `F` to the selection. Zoomed, the whe drag it to pan, click elsewhere to centre, pinch it with two fingers. A ruler of round ticks sits over a zoomed waveform; at 20 s across or closer it also draws the measured silences (the cut-points route's, the build's own) and the pauses between words (when the project's words file is this recording's), so a gap's edge goes between two words. -At fit — the default, on every clip — the waveform is what it always was. (Play the cut's reel strip is a scrubber; -nothing is trimmed there, so it has no zoom.) +At fit — the default, on every clip — the waveform is what it always was. The same zoom is on Play the cut's reel strip, +over cut seconds ([below](#the-reel-strip-zoom-and-reorder)). ## A clip's picture, blurred @@ -186,6 +232,35 @@ the render unchanged. The two are not set together: on a migrated cut the series The default ladder: `master`, `1080p` (crf 22), `720p` (crf 23), `fit24` (at most 24 MiB). `umtool look` also sets the look's keys (`transition=0.3`, …: [report-video.md](report-video.md#the-look-captions-loudness-shorts-release-36)). +## Sections, split and flash-forward (editing the cut) + +Under the deck a cut's **sections are its markers** (`render.chrome.deck.markers`): §0 runs to the first marker's +boundary, and a marker `{after, label, color}` opens the next section right after that clip, its label and colour +the new section's. These edits move clips and boundaries together, so no section empties and no boundary crosses +another (each refused in words), and every **take patch in step** (`*.patch.json` beside the manifest whose +markers were the manifest's before the edit) is brought along; a patch whose markers already differed is left, and +named (`lib/report/sectionEdit.mjs`; `patchMarkers.mjs` syncSectionMarkers, beside the removal re-anchor). Each is a structural write: an undo point first +(**Undo last edit**, `umtool timeline <p> undo`). + +| | In umtool | From a terminal | Route | +|---|---|---|---| +| the sections | the Cut tab: a bar where each opens (colour, label, clips) | `umtool timeline <p> sections [--json]` | `GET /api/report/timeline` (`sections`) | +| move clips to a section (its end; or its start) | a row's ⋯ **move to section…**; tick rows, **move to section… → Move**; a row dragged onto a section's bar (its start) | `umtool timeline <p> section-move <id> [<id>…] --to-section N [--start]` | `POST /api/report/timeline {op: "section-move", ids, section, position?}` | +| new section here | a row's ⋯ **new section here**: label (≤ 24), colour | `umtool timeline <p> section-add --after <id> [--label L] [--color C]` | `{op: "section-add", afterId, label?, color?}` | +| move a boundary | drag a section bar's ⇕ onto the clip it should follow | `umtool timeline <p> section-boundary <marker> --after <id>` | `{op: "section-boundary", marker, afterId}` | +| relabel / recolour, remove a boundary | a bar's **edit**, **remove boundary** (the section joins the one before) | `umtool timeline <p> section-set <marker> [--label L] [--color C]` · `section-remove <marker>` | `{op: "section-set", marker, label?, color?}` · `{op: "section-remove", marker}` | +| split a clip at a second | the clip editor's **Split here** (`S`, at the playhead) | `umtool timeline <p> split <id> <second>` | `POST /api/report/clip-editor {op: "split", clip, at}` | +| flash-forward a span | the clip editor: select the span on the strip, **Flash-forward selection…**: the start of a section, or after an entry; **move it out** for a move | `umtool timeline <p> flash-forward <id> <from>-<to> (--after <id\|-> \| --to-section N [--start]) [--move] [--quote Q] [--id ID]` | `POST /api/report/clip-editor {op: "flash-forward", clip, from, to, after? \| section?, position?, move?}` | + +- **A split** keeps both halves' attribution and locks (the second half's `cite` and citeUrl `t=` move to its own + second), each half's quote read from the words; a marker after the clip follows its second half (the same + boundary). A claim stays with the first half. +- **A flash-forward** is a tight copy of the span (inside the clip's window) with the clip's title, date, channel, + `cite`/citeUrl at the new second, quote (the span's words), speakers, on-screen words, verdict and locks, marked + `repeatOf` the clip (the check's overlap row knows it is deliberate); its id is `<clip>t`. **Move** takes the span + out of the clip instead (it must sit at one of the clip's edges; the clip keeps the rest, its quote re-read); a + span in the middle is refused — split there first. A claim, the marks and the assistant's record stay with the clip. + ## The finale (the timeline in primary view) The cut's last clips with the footer's rail redrawn large across the top (every pip lit, the markers flagged, @@ -273,7 +348,8 @@ browser. **Render this clip** is the pixel-true check of all of that but the joi `/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 +render. **With no `take` it plays the LATEST take** (below), the look of the next draft; `?cut=1` plays the +manifest alone. It plays 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 every module that declares **`play`** in the module contract — the chapter cards over the first seconds of the clip each opens, the then-and-now pair strip, the @@ -283,6 +359,19 @@ own patch (a take's own `timeline` included), from `takes/<id>/take.json` or — 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. +**The working cut is the latest take** (operator, 1 Nov 2026: "most of the time I'll only really be working on the +latest cut/draft rather than the picked one"). The head names it as prominently as a take — **Latest: draft-22 · +28:03 · +3 edits since** (hover lists them: `aw3 removed`, `mc1 moved`, `ss1 gaps`) — the newest WHOLE-CUT take made +from the project (`take.json` window `full`, rendered, not quick, no montage style, no `timeline` of its own: a +*working* take, `lib/report/takes.mjs` isWorkingTake), and the edits are the project's manifest against the manifest +that take rendered (`0` when the manifest's hash is the take's `baseHash`; `lib/report/workingCut.mjs`). The other +takes are a switch beside it (pills, the rest behind **N more**), **manifest only** the bare manifest; the pick (Use +this take, below) is named small only when it is not the latest. Every edit made in Play — a reorder, Reject, the +bench — writes the PROJECT's manifest, which a working take plays as it is now, so the latest take shows it at once; +a take with its own timeline says so and offers no structural edit (its walk edits it). `umtool takes ls <p>` prints +the same line first and marks `latest`; the Takes page shows it and a **latest** badge. **Re-render the take** (the +clip editor and the clip deck) remakes the latest take — it used to need a pick when there were two whole-cut takes. + **A rejected clip is skipped.** A clip the walk rejected — a fact error (`incorrect`: doesn't match, wrong speaker; or a legacy `correction` and no verdict) or a cut reason (`rejected`: irrelevant, repeats, weak, privacy, other) — is left out of what Play plays — its neighbours meet at the seam — and the reel strip shows it struck through where it @@ -299,6 +388,17 @@ in `removed.json` — or **Reject, keep in place** writes the verdict only, for it is the same flow with its reason preset ([report-video.md](report-video.md#verdict--what-the-walk-said)). Not on a take. +**Play and the clip bench are one app.** **Edit this clip** (E) opens the bench IN PLACE: Play is hidden and paused +but never unmounted, so its composed deck, decoded sound, measured edges, the strip's zoom and the take stay as they +were (`components/projects/cutApp/CutApp.tsx`; the bench's data is `GET /api/report/bench`, the same function its own +page renders from, `lib/report/benchData.ts`). The address moves by `history.pushState` to the bench's +(`/clip/<id>?from=play&at&take&order=cut`): the browser's Back and Forward step between the two, a reload or a link is +the bench's own page, and **‹ Back to the cut** goes back the entries it pushed (no second Play in the history). Inside +Play the bench walks the CUT's order (`order=cut`: p / n are the reel strip's neighbours, judged or not, `40 of 127`; +the neighbours are read ahead). Back on Play the view is read again in place (`GET /api/report/play-view`), the deck +is composed again only when the manifest's token moved, and Play stands on the clip it left by its id and source +second. A bench opened on its own (the Cut tab's Walk, a link) has **▶ Play the cut from here** in its head. + **Play keeps its place in its URL** (`?clip=&at=&t=` and `rejected=1` — an old `incorrect=1` still works — replaced at most once a second, never a history entry of its own), so **Edit this clip** (E) and then the browser's **Back** — or the bench's **‹ Back to the cut** — lands paused on the same second of the same clip. When an edit moved that clip in the cut, Play resumes by @@ -314,12 +414,40 @@ puts the walked take over the project's manifest with one undo | | 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 | — | +| 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 and their name, in the section's colour; 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 a cell's body to scrub, a cell's Enter jumps to its start, hover names it | — | +| closer: zoom at the pointer, in, out, fit, the clip on screen, its section; pan; the whole cut under it | the strip's **zoom** row (− + Fit, **Zoom to clip**, **Zoom to section**), Ctrl/⌘ + wheel, the wheel while zoomed, the overview | z Z f F | +| move a clip: drag it to another place, into another section | drag a cell by its top band (⠿, or with Alt held); **Move <clip> to…** (a section's start or end); an **Undo** after | Alt+← → on a focused cell | | 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 | **?** | ? | +### The reel strip: zoom and reorder + +**Zoom** is the bench waveform's ([above](#the-bench-waveforms-zoom): `useWaveZoom`, `ZoomControls`, `ZoomOverview`, +`benchZoom.mjs`), over cut seconds: Ctrl/⌘ + wheel zooms at the pointer (the second under it stays), − / + / **Fit** +/ **Zoom to clip** / **Zoom to section**, keys `z` in at the playhead, `Z` out, `f` fit, `F` the clip on screen. +Zoomed, the wheel pans, an overview under the strip shows the whole cut in its sections' colours with what is shown +(drag it, click to centre), a ruler counts round ticks, each cell shows its id (and date when it has room), each seam +its section (`27 Feb 2025 §3 Leaves it open`, only the labels that fit, so twenty sections read at zoom), and while +playing the view pages on with the playhead. + +**Reorder**: grab a cell by its top band — the grip, ⠿, in the section's colour — or anywhere on it with Alt held, +and drag; a press on a cell's body still scrubs. An insertion bar in the drop's section's colour and the drop's words +follow the pointer (`c04 → §0 (the opening), after c01`): the left half of a cell lands before it, the right half +after it, so a seam's two sides are the end of one section and the start of the next — the same slot, the section +said. A zoomed strip pans at its edges while you drag, Ctrl/⌘ + wheel zooms mid-drag, Esc cancels. A drop that would +leave a section with no clip is refused in words before anything is written. The drop is ONE write — the **place** +op (`POST /api/report/timeline {op: "place", ids, before, section}`, `lib/report/sectionEdit.mjs` placeIn): the clip +lands before an entry and joins the section, every other clip keeps its own, the markers are re-anchored so that +holds (a plain `move` took the boundary with the clip a marker followed), take patches in step are synced, and each +drop is its own undo point. **Undo** (the toast) takes back exactly that drop (the structural undo with the drop's +token: an edit made since is never undone by mistake). The playhead stays on the clip it was on; until the deck is +composed again the estimate's segments play the new order. On the keyboard: Alt+← / Alt+→ on a focused cell moves it +one place (at a seam it first changes section, then moves); **Move <clip> to…** puts the clip on screen at a +section's start or end (`section-move`). The terminal's: `umtool timeline <p> place <id…> --before <id|-> [--section +N]` and `section-move`. A take with its own timeline is not reordered here (`umtool timeline <p> --take <t> move`). + **It plays the render's cut, edges first.** The build snaps every clip edge to the nearest silence within `render.snapWindow` (on the Huck cut, starts up to 1.0 s earlier and ends up to 1.0 s later than the manifest's), so Play asks where it will cut — `GET /api/report/cut-points?project=<p>[&take=<t>]`, the build's own source resolution, @@ -330,7 +458,9 @@ draws the same edges over its waveform as faint ghosts with their offset (**rend the measured silences as an edge is dragged. **The sound is on one Web Audio clock.** Each clip's sound is decoded (ffmpeg's decode of the cached window, the -bench's `/api/report/audio`; only the clips around the playhead are held) and scheduled back to back on one +bench's `/api/report/audio`; only the clips around the playhead are held) ONCE — while the render's edges are +measured, two seconds wider at the clip's ends, so the render's edges play from the same decode — and a clip with +gaps per kept piece, never its gaps (pieces under a second apart as one); it is scheduled back to back on one AudioContext, sample-exact at the render's edges: a crossfade is the build's two linear ramps over the overlap, the loudness gain, room's muted edges, the clip's own `audio` knobs and the mute mark are gain automation, and a speed time-stretches at the voice's pitch as the bench does. The clock of the whole view — the rail, the tally, the @@ -348,7 +478,7 @@ cards, teasers and images are **placeholders** with their heading for their seco drawn as a dissolve; the limiter after the loudness gain is not applied; a montage's phrase cuts are snapped as plain cuts. A clip whose source window is not on disk is a named placeholder that plays on (silent) — fetch it from the Cut tab. **Reload the cut** reads an edit made elsewhere, and the edges are measured again for what moved. **Edit this clip** (E) and the bench's **Back to the cut** come back -to the same clip by its id and then by the SOURCE second you left (`?clip=&at=`, the offset turned into a source +to the same clip — and the same take — by its id and then by the SOURCE second you left (`?clip=&at=`, the offset turned into a source second once the render's edges are in), so an edit that moves the clip's start does not move you off the word. The bench draws the render's cut over its waveform and, on a phone, on the edge strip (a faint line, and its offset under each edge). @@ -396,6 +526,41 @@ again is written over. on another OS, and from any device but the machine umtool runs on (by the request's Host, Origin and X-Forwarded-For) — use **Download** there. +## The trailer's beats + +`umtool trailer <p> --take <t> --beats <p>/promo/trailer-beats.json` cuts a trailer from a finished master; the beats +file is edited here, through one writer (`lib/report/trailerBeats.mjs`), which says before any encode each beat's +length (a clip beat's gaps out, as the master plays it), the **running length against the platform's limit** (X 2:20 by +default; Instagram 1:30, a Short 3:00, TikTok 10:00, or seconds) with the trailer's crossfades and the brand intro +(its length from the newest built take's schedule), every beat **outside its clip's window** or naming a clip no +longer in the cut, and whether the beats are in the cut's order. A beat is `{id, start, end, label?}` (source +seconds of a clip) or `{at, dur}` (master seconds), numbered from 1 as `umtool trailer` numbers them. The file keeps +its shape (an array, until a setting makes it `{limit, xfade, intro, beats}`, which `--beats` reads too) and its +indent; one that does not parse is never written over; a write over a newer file is a 409. + +| | In umtool | From a terminal | Route | +|---|---|---|---| +| the beats, the length, the limit, what to fix | the Cut tab's **Trailer** → `/projects/<p>/trailer` | `umtool trailer-beats <p> [--json]` | `GET /api/report/trailer-beats?project=<p>` | +| add a beat (in the cut's order) | the clip editor's **Add to trailer** (the selection, else the cut); the Trailer page's **add a beat** | `umtool trailer-beats <p> add <clip> [<from>-<to>] [--at N] [--label L]` · `add-raw <at> <dur>` | `POST … {op: "add", beat, at?}` | +| a beat's seconds; pull it inside its clip | the row's from–to; **fit to clip** | `umtool trailer-beats <p> set <n> <from>-<to> [--label L]` | `{op: "set", index, patch}` | +| move, remove, the cut's order | ↑ ↓ **remove**; **Order by the cut** | `move <n> --to <m>` · `remove <n>` · `order` | `{op: "move", index, to}` · `{op: "remove", index}` · `{op: "order"}` | +| the limit, the crossfade, the intro | **limit** (a platform, or seconds), **crossfade**, **open on the brand intro** | `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok\|default>` · `xfade <s>` · `intro on\|off` | `{op: "settings", limit?, xfade?, intro?}` | +| the walk's ★ clips | **★ from the walk**: each **Add** | `umtool trailer-beats <p> candidates [--add]` | `GET` (`candidates`) | + +## Takes: relabel, supersede, delete + +| | In umtool | From a terminal | Route | +|---|---|---|---| +| list | the Takes page | `umtool takes ls <p> [--json]` (picked, superseded, RENDERING) | `GET /api/report/takes` | +| relabel (take.json's `label`; an undo point in the take's `revisions/`) | a take's ✎ | `umtool takes relabel <p> <take> <label…>` | `POST /api/report/takes/housekeeping {project, take, op: "relabel", label}` | +| superseded (verdicts.json `superseded: {by, at}`; folded away in the list, nothing deleted; a pick clears it) | **Mark superseded** (by a take), **Not superseded**; **show them** in the group | `umtool takes supersede <p> <take> [--by <take>]` · `--clear` | `{op: "supersede", by?}` · `{op: "unsupersede"}` | +| delete `takes/<take>/` | **Delete take** (the plan first) | `umtool takes delete <p> <take> [--dry-run] [--force]` | `POST /api/report/takes/delete {project, take, dryRun?, force?}` | + +**What a running render names is respected**: a take whose build lock (`takes/<id>/.building.json`) is live is +rendering — its take.json is written last, from the label it started with — and a take a live build names as its +`from` is that build's base. Relabel and delete are refused for both (`force` does not pass it); a supersede mark is +not (no render writes verdicts.json). + ## Make variants, and the sync report | | In umtool | From a terminal | Route | diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -112,6 +112,20 @@ Two are checked rather than trusted: - **`citeUrl`** must be `http(s)`. A QR encoding anything else is the same class of defect as the 19 codes that shipped reading `undefined/?v=…`. +**`cite` follows the edge.** A window or cut save that leaves the clock more than +5 s before what plays, or past its end, moves `cite` to the first played second, +and a citeUrl naming this recording moves its `t=` with it; an explicit `cite` +takes the QR along when the two agreed. What is left over is the check's +`clip-cite-off` row. Whether a QR opens at all is `umtool links`: [knobs.md](knobs.md#the-cite-follows-the-edge), +[Do the QR links open?](knobs.md#do-the-qr-links-open). + +### `walkNote` and `star` — what the walk said that is not a verdict + +`walkNote` is an editorial note from the walk (*this is gold*, *wants a beat of +silence*); `star: true` is a favourite, which makes the clip a trailer candidate +(the Cut tab's ★ list, `umtool trailer <p> --candidates`). Neither is rendered, +neither touches the verdict, and neither is a `correction`. + ### `correction` — what the REPORT got wrong Free text, written while watching the clip, **never rendered and never read by @@ -1111,6 +1125,19 @@ the one the take was made from (its `baseHash`), the card says **The project cha take was made** and the pick waits for **Use anyway**. A take that does not record its base asks the same. +**The pick follows the latest take, and nothing needs one** (operator, 1 Nov 2026). The working cut is the +project's manifest and its name the newest whole-cut take made from it (`lib/report/workingCut.mjs`: +**Latest: draft-22 · +N edits since** in Play, on the Takes page and first in `umtool takes ls`); Play, +the bench and **Re-render the take** default to it. Use this take is for going BACK to an older take. +When a take is built, a *working* take (window `full`, rendered, not quick, no montage style, no +`timeline` of its own — `takes.mjs` isWorkingTake) becomes its group's pick automatically, a mark in +verdicts.json and nothing copied (the project's manifest is what it was made from), so whatever still +reads `picked` — the pruner's keep list, the Takes page's badge — follows the latest draft, an agent's +take as much as the operator's. A window preview, a draft, a quick render or a style take never does. +`umtool takes pick <p> <take> --pin` (the route's `pin: true`) pins a pick: newer takes are then not +auto-picked over it (`--unpin`, or picking another, lets go). The gate this removes: with two whole-cut +takes and none picked, Re-render the take had no target and the only way on was to pick one. + ### Render mode: giving a render the machine @@ -1287,6 +1314,9 @@ its log says so, rather than refused as emptied. pips and running tallies show the whole video's timeline, and a viewer can see the full version has more. Nothing is rendered again: it is one ffmpeg pass over the finished file. +The walk's ★ clips are the candidates: `umtool trailer <project> --candidates` lists them, +`--candidates --json` prints them as beats over what each plays, ready for `--beats-json`. + A beat is either: ``` diff --git a/umtool/e2e/cut-flash.spec.ts b/umtool/e2e/cut-flash.spec.ts @@ -0,0 +1,135 @@ +import { test, expect, type Page } from "@playwright/test"; +import { copyFileSync, existsSync, readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// The clip editor's edits on the cut (UI notes 2026-10-30, items 2 and 11): +// +// cut-flash-fixture the clip editor's three clips r001 r002 r003 on vid1 +// (their words, their windows cached), the deck on with +// a marker after r001 ("Two"), citeUrls, speakers, r002 +// end-locked; draft-1.patch.json carries the marker. +// WRITES its manifest, the patch, promo/ and revisions/. +// +// Flash-forward selection… copies a span of r002 to the start of the cut with +// its attribution and locks, as a repeat of r002; "move" takes it out of the +// clip; Add to trailer writes a beat; a split keeps r001's section boundary. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const DIR = path.join(HERE, "..", ".e2e-song", "reports", "cut-flash-fixture"); +const MANIFEST = path.join(DIR, "video.manifest.json"); +const PATCH = path.join(DIR, "draft-1.patch.json"); +const BEATS = path.join(DIR, "promo", "trailer-beats.json"); +const PROJECT = "reports/cut-flash-fixture"; + +type Clip = Record<string, unknown> & { id: string }; +const read = (file: string) => JSON.parse(readFileSync(file, "utf8")); +const clips = () => read(MANIFEST).timeline as Clip[]; +const clip = (id: string) => clips().find((c) => c.id === id) ?? null; + +test.beforeAll(() => { + for (const f of [MANIFEST, PATCH]) if (!existsSync(`${f}.pristine`)) copyFileSync(f, `${f}.pristine`); +}); +test.beforeEach(() => { + for (const f of [MANIFEST, PATCH]) copyFileSync(`${f}.pristine`, f); + rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); + rmSync(path.join(DIR, "promo"), { recursive: true, force: true }); + rmSync(path.join(DIR, "montage-rulings.json"), { force: true }); +}); + +async function openOn(page: Page, id: string) { + await page.setViewportSize({ width: 1366, height: 900 }); + await page.goto(urls.clipEditorHref(PROJECT, { clip: id })); + await expect(page.locator("[data-clip-editor]")).toHaveAttribute("data-clip-editor", id); + await expect(page.locator("[data-editor-words]")).toHaveAttribute("data-editor-words", "words", { timeout: 15_000 }); +} + +/** Drag a selection on the strip from source second `a` to `b`. */ +async function select(page: Page, a: number, b: number) { + const strip = page.locator("[data-strip]").first(); + const [from, to] = String(await strip.getAttribute("data-strip")).split("-").map(Number); + const box = (await strip.boundingBox())!; + const x = (t: number) => box.x + ((t - from) / (to - from)) * box.width; + const y = box.y + box.height * 0.8; + await page.mouse.move(x(a), y); + await page.mouse.down(); + await page.mouse.move((x(a) + x(b)) / 2, y, { steps: 4 }); + await page.mouse.move(x(b), y, { steps: 4 }); + await page.mouse.up(); +} + +test("Flash-forward selection… copies the span earlier with its attribution and locks, as a repeat", async ({ page }) => { + test.setTimeout(90_000); + await openOn(page, "r002"); + await expect(page.locator('[data-action="flash-forward"]')).toBeDisabled(); + await select(page, 4.5, 5.8); + await expect(page.locator('[data-action="flash-forward"]')).toBeEnabled(); + await page.locator('[data-action="flash-forward"]').click(); + const form = page.getByTestId("flash-forward-form"); + await expect(form).toBeVisible(); + // Its default: the start of r002's own section (§1, after r001's boundary). + await expect(page.getByTestId("ff-where-section")).toBeChecked(); + await expect(page.getByTestId("ff-section")).toHaveValue("1"); + await page.getByTestId("ff-go").click(); + await expect.poll(() => clips().map((c) => c.id)).toEqual(["r001", "r002t", "r002", "r003"]); + const t = clip("r002t")!; + expect(t.repeatOf).toBe("r002"); + expect(t.start).toBeGreaterThanOrEqual(4.4); + expect(t.end).toBeLessThanOrEqual(5.9); + expect(t.cutStart).toBe(t.start); + expect(t.title).toBe("The Fixture Stream"); + expect(t.date).toBe("2026-10-27"); + expect(t.speakers).toEqual(["Subject"]); + expect(t.lockEnd).toBe(true); + expect(String(t.citeUrl)).toMatch(new RegExp(`t=${Math.floor(Number(t.start))}$`)); + expect(String(t.quote).length).toBeGreaterThan(0); + expect(t.quote).not.toBe(clip("r002")!.quote); + // The marker stays after r001: the copy opens §1. + expect(read(MANIFEST).render.chrome.deck.markers[0].after).toBe("r001"); + expect(clip("r002")!.cutStart).toBe(4); +}); + +test("move it out: the span leaves the clip, which keeps the rest", async ({ page }) => { + test.setTimeout(90_000); + await openOn(page, "r003"); + await select(page, 7.4, 8.5); + await page.locator('[data-action="flash-forward"]').click(); + // The sections have come back (the form's default is the start of r003's section). + await expect(page.getByTestId("ff-where-section")).toBeChecked(); + await page.getByTestId("ff-where-after").check(); + await page.getByTestId("ff-after").selectOption(""); + await page.getByTestId("ff-move").check(); + await page.getByTestId("ff-go").click(); + await expect.poll(() => clips()[0]?.id).toBe("r003t"); + expect(clip("r003t")!.repeatOf).toBeUndefined(); + expect(Number(clip("r003")!.cutEnd)).toBeLessThanOrEqual(7.5); + expect(Number(clip("r003")!.cutStart)).toBe(6.5); +}); + +test("Add to trailer writes the selection (else the cut) as a beat", async ({ page }) => { + test.setTimeout(90_000); + await openOn(page, "r002"); + await page.locator('[data-action="add-to-trailer"]').click(); + await expect(page.locator("[data-editor-status]")).toContainText("Added to the trailer as beat 1"); + expect(read(BEATS)).toEqual([{ id: "r002", start: 4, end: 6 }]); + await page.keyboard.press("ArrowLeft"); + await expect(page.locator("[data-clip-editor]")).toHaveAttribute("data-clip-editor", "r001"); + await select(page, 1.2, 2.6); + await page.locator('[data-action="add-to-trailer"]').click(); + await expect.poll(() => read(BEATS).length).toBe(2); + expect(read(BEATS)[0].id).toBe("r001"); +}); + +test("a split keeps its section: the marker after r001 follows its second half, in the patch too", async ({ page }) => { + test.setTimeout(90_000); + await openOn(page, "r001"); + await page.locator('[data-word-t="2.4"]').click(); + await page.locator('[data-action="split"]').click(); + await expect.poll(() => clip("r001-2")?.cutStart).toBe(2.4); + expect(read(MANIFEST).render.chrome.deck.markers[0].after).toBe("r001-2"); + expect(read(PATCH).render.chrome.deck.markers[0].after).toBe("r001-2"); + expect(String(clip("r001-2")!.citeUrl)).toMatch(/t=2$/); +}); diff --git a/umtool/e2e/cut-integrity.spec.ts b/umtool/e2e/cut-integrity.spec.ts @@ -0,0 +1,220 @@ +import { test, expect, type Page } from "@playwright/test"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; +import { WARM_TIMEOUT, warm } from "./warm"; +import { CUT_INTEGRITY, SITE_PLACEHOLDER } from "./fixtures/cut-integrity-fixture.mjs"; + +// --------------------------------------------------------------------------- +// CUT INTEGRITY (UI notes 2026-10-30): every surface through the window +// writer, each with its terminal twin. +// +// #3 a window-overlap row's "It's deliberate: c02 repeats c01" writes +// repeatOf; the Cut tab and the bench show "repeats c01" +// #5 a clip-cite-off row's "Move to 0:06" puts the clock AND the QR back +// on the clip +// #6 a take patch whose markers name a clip that is gone is a row; removing +// a clip re-anchors the patch's markers +// #7 ★ (s) and the walk note on the bench -- neither a verdict nor a +// correction; the Cut tab's ★ trailer candidates +// #8 Check links resolves every clip QR against the site's corpus.json +// contract (this spec's own server): one dead link blocks; a site that +// does not answer leaves them "not verified" +// +// Fixture (fixtures/cut-integrity-fixture.mjs), written by this file alone. +// The tests run in order, each leaving what the next reads. +// --------------------------------------------------------------------------- + +test.describe.configure({ mode: "serial" }); + +const PROJECT = `reports/${CUT_INTEGRITY}`; +const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", CUT_INTEGRITY); +const MANIFEST = path.join(DIR, "video.manifest.json"); +type Entry = { id: string; cite?: number; citeUrl?: string; repeatOf?: string; star?: boolean; walkNote?: string; correction?: string; verdict?: string }; +const entries = () => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[] }).timeline; +const entry = (id: string) => entries().find((e) => e.id === id); +// Screenshots for the morning review, when asked for (CUT_INTEGRITY_SHOTS=<dir>). +const SHOTS = process.env.CUT_INTEGRITY_SHOTS ?? ""; +const shot = async (page: Page, name: string) => { + if (!SHOTS) return; + mkdirSync(SHOTS, { recursive: true }); + await page.screenshot({ path: path.join(SHOTS, `${name}.png`), fullPage: false }); +}; + +// The site the QRs link: corpus.json -> testchan's manifest -> page-0000.json, +// holding vid1 and vid2 (not "nope"). +let server: Server; +let origin = ""; +const asked: string[] = []; +const startSite = () => + new Promise<void>((resolve) => { + server = createServer((req, res) => { + const p = new URL(req.url ?? "/", "http://x").pathname; + asked.push(p); + const json = (doc: unknown) => { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(doc)); + }; + if (p === "/corpus.json") { + return json({ + spec: 5, + generatedAt: "2026-10-09T10:00:00.000Z", + site: { title: "Fixture archive" }, + channels: [{ slug: "testchan", manifests: { transcripts: `${origin}/transcripts/testchan/manifest.json` } }], + }); + } + if (p === "/transcripts/testchan/manifest.json") return json({ pageCount: 1, slugToPage: { vid1: 0, vid2: 0 } }); + if (p === "/transcripts/testchan/page-0000.json") return json([{ id: "vid1" }, { id: "vid2" }]); + res.writeHead(404); + res.end(); + }); + server.listen(0, "127.0.0.1", () => { + origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + resolve(); + }); + }); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + await startSite(); + // The QRs on this run's server: the placeholder origin, replaced. + writeFileSync(MANIFEST, readFileSync(MANIFEST, "utf8").split(SITE_PLACEHOLDER).join(origin)); + await warm(playwright, [urls.projectHref(PROJECT), urls.projectHref(PROJECT, { tab: "cut" }), urls.clipBenchHref(PROJECT, "c01")]); +}); +test.afterAll(() => { + server?.close(); +}); + +const row = (page: Page, kind: string, target: string) => page.locator(`[data-decision="${kind}"][data-target="${target}"]`); + +test("the check rows: an overlap, a clock and QR off the clip, a stale take patch, links never checked — each with its settle and its fix", async ({ page }) => { + await page.goto(urls.projectHref(PROJECT)); + const overlap = row(page, "window-overlap", "c01"); + await expect(overlap).toContainText("overlaps c02 by 2.0s"); + await expect(overlap.locator('[data-settle-button="c02"]')).toHaveText("It's deliberate: c02 repeats c01"); + await expect(overlap.locator("[data-fix]")).toHaveAttribute("data-fix", /^umtool window reports\/cut-integrity-fixture c02 --repeat-of c01/); + + const cite = row(page, "clip-cite-off", "c03"); + await expect(cite).toContainText("the clock and the QR point 6 s before the clip (cite 0:00, it plays 0:06–0:08)"); + await expect(cite.locator('[data-settle-button="c03"]')).toHaveText("Move to 0:06"); + await expect(cite.locator("[data-fix]")).toHaveAttribute("data-fix", "umtool window reports/cut-integrity-fixture c03 --cite 6"); + + const stale = row(page, "patch-markers-stale", "draft-1.patch.json"); + await expect(stale).toContainText('a deck marker names a clip not in the cut: "Hand-made" after gone'); + + await expect(row(page, "links-unchecked", "QR links")).toContainText("4 archive links never checked against the sites they open"); + await expect(row(page, "links-unchecked", "QR links").locator('[data-settle-button="links"]')).toHaveText("Check links"); + await shot(page, "3-5-6-8-check-rows"); +}); + +test("#3 It's deliberate: repeatOf through the writer, the row gone, the chip on the Cut tab and the bench", async ({ page }) => { + await page.goto(urls.projectHref(PROJECT)); + await row(page, "window-overlap", "c01").locator('[data-settle-button="c02"]').click(); + await expect(row(page, "window-overlap", "c01")).toHaveCount(0); + expect(entry("c02")?.repeatOf).toBe("c01"); + await page.goto(urls.projectHref(PROJECT, { tab: "cut" })); + await expect(page.locator('[data-entry="c02"] [data-repeat-of="c01"]')).toHaveText("repeats c01"); + await shot(page, "3-repeat-of-chip-cut-tab"); + await page.goto(urls.clipBenchHref(PROJECT, "c02")); + await expect(page.locator('[data-bench-repeat-of="c01"]')).toHaveText("repeats c01"); + // #7: an editorial note written as a correction on a confirmed clip moves to the walk note in one press. + await expect(async () => { + await page.locator("[data-move-to-walk-note]").click({ timeout: 2000 }); + await expect(page.locator("[data-move-to-walk-note]")).toHaveCount(0, { timeout: 2000 }); + }).toPass({ timeout: 15_000 }); + await expect.poll(() => entry("c02")?.walkNote).toBe("might want a bit of silence"); + expect(entry("c02")?.correction).toBeUndefined(); + expect(entry("c02")?.verdict).toBe("confirmed"); + await expect(page.locator('[data-attrib-field="walkNote"]')).toHaveValue("might want a bit of silence"); +}); + +test("#5 Move to 0:06: the clock and the QR back on the clip, and the row gone", async ({ page }) => { + await page.goto(urls.projectHref(PROJECT)); + await row(page, "clip-cite-off", "c03").locator('[data-settle-button="c03"]').click(); + await expect(row(page, "clip-cite-off", "c03")).toHaveCount(0); + expect(entry("c03")?.cite).toBe(6); + expect(entry("c03")?.citeUrl).toBe(`${origin}/?v=testchan%2Fvid1&t=6`); +}); + +test("#7 ★ (s) and the walk note on the bench: not a verdict, not a correction; the Cut tab's trailer candidates", async ({ page }) => { + await page.goto(urls.clipBenchHref(PROJECT, "c01")); + const star = page.locator("[data-verdict-star]"); + await expect(star).toHaveAttribute("data-verdict-star", "off"); + // The bench's keys answer once it has hydrated: `s` stars. + await expect(async () => { + await page.locator("body").press("s"); + await expect(star).toHaveAttribute("data-verdict-star", "on", { timeout: 1500 }); + }).toPass({ timeout: 15_000 }); + await expect.poll(() => entry("c01")?.star).toBe(true); + await expect(page.locator("[data-bench-star]")).toBeVisible(); + const note = page.locator('[data-attrib-field="walkNote"]'); + await note.fill("THIS IS GOLD"); + await note.press("Tab"); + await expect.poll(() => entry("c01")?.walkNote).toBe("THIS IS GOLD"); + expect(entry("c01")?.correction).toBeUndefined(); + expect(entry("c01")?.verdict).toBeUndefined(); + await shot(page, "7-star-walk-note-bench"); + + await page.goto(urls.projectHref(PROJECT, { tab: "cut" })); + await expect(page.locator('[data-entry="c01"] [data-star="c01"]')).toHaveText("★ trailer"); + await expect(page.locator('[data-walk-note-of="c01"]')).toContainText("THIS IS GOLD"); + const cands = page.locator("[data-trailer-candidates]"); + await expect(cands).toHaveAttribute("data-trailer-candidates", "1"); + await expect(cands.locator('[data-trailer-candidate="c01"]')).toContainText("0:01–0:05 (4.0 s)"); + await expect(cands).toContainText(`umtool trailer ${PROJECT} --candidates --json`); + await shot(page, "7-trailer-candidates-cut-tab"); + + // ☆ again clears it. + await page.goto(urls.clipBenchHref(PROJECT, "c01")); + await page.locator('[data-verdict-star="on"]').click(); + await expect.poll(() => entry("c01")?.star).toBeUndefined(); + await page.locator('[data-verdict-star="off"]').click(); + await expect.poll(() => entry("c01")?.star).toBe(true); +}); + +test("#8 Check links: one link dead on the site blocks, naming the clip and why; offline they are not verified", async ({ page }) => { + await page.goto(urls.projectHref(PROJECT)); + await row(page, "links-unchecked", "QR links").locator('[data-settle-button="links"]').click(); + const host = new URL(origin).host; + const dead = row(page, "link-dead", host); + await expect(dead).toBeVisible({ timeout: 30_000 }); + await expect(dead).toHaveAttribute("data-severity", "blocking"); + await expect(dead).toContainText(`1 of 4 QR links don't open on ${host} (deployed 2026-10-09): c04 — c04: "nope" is not published in testchan on ${host}`); + await expect(row(page, "links-unchecked", "QR links")).toHaveCount(0); + // Polite: corpus.json, the channel's manifest, its one page -- each once. + expect(asked.filter((p) => p === "/corpus.json")).toHaveLength(1); + expect(asked.filter((p) => p.endsWith("/page-0000.json"))).toHaveLength(1); + const doc = JSON.parse(readFileSync(path.join(DIR, "out", "links.json"), "utf8")) as { links: { clip: string; state: string }[] }; + expect(doc.links.map((l) => [l.clip, l.state])).toEqual([["c01", "ok"], ["c03", "ok"], ["c02", "ok"], ["c04", "dead"]]); + await shot(page, "8-link-dead"); + + // The site goes away: a check now cannot verify, and says so -- it does not call them dead. + await new Promise<void>((r) => server.close(() => r())); + await dead.locator('[data-settle-button="links"]').click(); + const unverified = row(page, "links-unverified", host); + await expect(unverified).toBeVisible({ timeout: 30_000 }); + await expect(unverified).toHaveAttribute("data-severity", "info"); + await expect(unverified).toContainText(`4 links not verified`); + await expect(unverified).toContainText(`couldn't reach ${host}`); + await expect(row(page, "link-dead", host)).toHaveCount(0); + await shot(page, "8-links-unverified-offline"); +}); + +test("#6 removing a clip re-anchors the take patch's markers; the hand-made one is still a row", async ({ page }) => { + await page.goto(urls.projectHref(PROJECT, { tab: "cut" })); + await page.locator('[data-row-menu="c04"]').click(); + await page.locator('[data-entry="c04"] [data-row-action="remove"]').click(); + await expect.poll(() => entries().map((e) => e.id)).toEqual(["c01", "c03", "c02"]); + const patch = JSON.parse(readFileSync(path.join(DIR, "draft-1.patch.json"), "utf8")) as { render: { chrome: { deck: { markers: { after: string; label: string }[] } } } }; + expect(patch.render.chrome.deck.markers).toEqual([{ after: "c02", label: "After four" }, { after: "gone", label: "Hand-made" }]); + await page.goto(urls.projectHref(PROJECT)); + await expect(row(page, "patch-markers-stale", "draft-1.patch.json")).toContainText('"Hand-made" after gone — a take made with --patch draft-1.patch.json is refused'); + await expect(row(page, "patch-markers-stale", "draft-1.patch.json")).not.toContainText("After four"); + await shot(page, "6-patch-markers-stale"); + // Take the cut's markers: nothing in the cut is called "Hand-made", so it is left, and said. + await row(page, "patch-markers-stale", "draft-1.patch.json").locator('[data-settle-button="draft-1.patch.json"]').click(); + await expect(page.locator("[data-settle-said]")).toContainText('0 markers moved · left by hand: "Hand-made" after gone'); +}); diff --git a/umtool/e2e/cut-sections.spec.ts b/umtool/e2e/cut-sections.spec.ts @@ -0,0 +1,134 @@ +import { test, expect, type Page } from "@playwright/test"; +import { copyFileSync, existsSync, readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// Sections edited as sections on the Cut tab (UI notes 2026-10-30, item 1): +// +// cut-sections-fixture the deck on; §0 c01 c02 | §1 "Two" c03 c04 | +// §2 "Three" c05 c06; draft-1.patch.json carries the +// same markers. WRITES its manifest, the patch and +// revisions/; every test starts from the fixture's. +// +// The section bars, "move to section…", "new section here" with a colour, a +// boundary dragged onto a clip, ticked clips moved together, a boundary +// removed -- each keeping the take patch's markers in step -- and Undo. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const DIR = path.join(HERE, "..", ".e2e-song", "reports", "cut-sections-fixture"); +const MANIFEST = path.join(DIR, "video.manifest.json"); +const PATCH = path.join(DIR, "draft-1.patch.json"); +const PROJECT = "reports/cut-sections-fixture"; + +type Marker = { after: string; label?: string; color?: string }; +const read = (file: string) => JSON.parse(readFileSync(file, "utf8")); +const order = () => (read(MANIFEST).timeline as { id: string }[]).map((e) => e.id); +const afters = () => ((read(MANIFEST).render.chrome.deck.markers ?? []) as Marker[]).map((m) => m.after); +const patchAfters = () => ((read(PATCH).render.chrome.deck.markers ?? []) as Marker[]).map((m) => m.after); + +test.beforeAll(() => { + for (const f of [MANIFEST, PATCH]) if (!existsSync(`${f}.pristine`)) copyFileSync(f, `${f}.pristine`); +}); +test.beforeEach(() => { + for (const f of [MANIFEST, PATCH]) copyFileSync(`${f}.pristine`, f); + rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); +}); + +async function open(page: Page) { + await page.goto(urls.section(PROJECT, "timeline")); + await expect(page.getByTestId("timeline-undo")).toBeEnabled(); + await page.waitForLoadState("networkidle"); +} + +test("the Cut tab draws a bar where each section opens", async ({ page }) => { + await open(page); + const bars = page.locator("li[data-section-bar]"); + await expect(bars).toHaveCount(3); + await expect(bars.nth(1)).toContainText("§1"); + await expect(bars.nth(1)).toContainText("Two"); + await expect(bars.nth(1)).toContainText("2 clips"); + // In the list order: the bar for §1 right after c02's row. + const seq = await page.locator("[data-testid=timeline-list] > li").evaluateAll((els) => els.map((e) => e.getAttribute("data-entry") ?? `§${e.getAttribute("data-section-bar")}`)); + expect(seq).toEqual(["§0", "c01", "c02", "§1", "c03", "c04", "§2", "c05", "c06"]); +}); + +test("move to section…: the clip lands at the section's end, the markers and the patch follow", async ({ page }) => { + await open(page); + await page.locator("[data-row-menu='c01']").click(); + await page.locator("[data-row-action='to-section']").click(); + await page.getByTestId("to-section-select-c01").selectOption("2"); + await expect.poll(order).toEqual(["c02", "c03", "c04", "c05", "c06", "c01"]); + expect(afters()).toEqual(["c02", "c04"]); + expect(patchAfters()).toEqual(["c02", "c04"]); + // The page has redrawn the cut (a row re-keyed by its new place loses an open menu). + await expect(page.locator("[data-testid=timeline-list] > li").last()).toHaveAttribute("data-entry", "c01"); + // c04 to §0: the "Three" boundary moves to c03, in the manifest and the patch. + await page.locator("[data-row-menu='c04']").click(); + await page.locator("[data-row-action='to-section']").click(); + await page.getByTestId("to-section-select-c04").selectOption("0"); + await expect.poll(order).toEqual(["c02", "c04", "c03", "c05", "c06", "c01"]); + expect(afters()).toEqual(["c04", "c03"]); + await expect.poll(patchAfters).toEqual(["c04", "c03"]); + // Undo takes back the burst (one undo point per op within two minutes: manifest.mjs autoSnapshot). + await page.getByTestId("timeline-undo").click(); + await expect.poll(order).toEqual(["c01", "c02", "c03", "c04", "c05", "c06"]); +}); + +test("a section left with no clip is refused in words, nothing written", async ({ page }) => { + await open(page); + const before = readFileSync(MANIFEST, "utf8"); + await page.locator("[data-select-clip='c03']").check(); + await page.locator("[data-select-clip='c04']").check(); + await expect(page.getByTestId("timeline-bulk")).toContainText("2 selected"); + await page.getByTestId("timeline-bulk-section").selectOption("0"); + await page.getByTestId("timeline-bulk-move").click(); + await expect(page.getByTestId("timeline-error")).toContainText("§1 (Two) would have no clip left"); + expect(readFileSync(MANIFEST, "utf8")).toBe(before); + // Two ticked clips that leave one behind move together. + await page.locator("[data-select-clip='c04']").uncheck(); + await page.locator("[data-select-clip='c06']").check(); + await page.getByTestId("timeline-bulk-section").selectOption("0"); + await page.getByTestId("timeline-bulk-move").click(); + await expect.poll(order).toEqual(["c01", "c02", "c03", "c06", "c04", "c05"]); + expect(afters()).toEqual(["c06", "c04"]); +}); + +test("new section here, with a label and a colour; edit and remove a boundary", async ({ page }) => { + await open(page); + await page.locator("[data-row-menu='c05']").click(); + await page.locator("[data-row-action='new-section']").click(); + await page.getByTestId("new-section-label-c05").fill("Four"); + await page.getByTestId("new-section-color-c05").fill("#3366ff"); + await page.getByTestId("new-section-add-c05").click(); + await expect.poll(() => read(MANIFEST).render.chrome.deck.markers.length).toBe(3); + expect(read(MANIFEST).render.chrome.deck.markers[2]).toEqual({ after: "c05", label: "Four", color: "#3366ff" }); + expect(read(PATCH).render.chrome.deck.markers[2]).toEqual({ after: "c05", label: "Four", color: "#3366ff" }); + await expect(page.locator("li[data-section-bar]")).toHaveCount(4); + // Edit relabels it. + await page.locator("[data-section-edit='2']").click(); + await page.getByTestId("new-section-label-m2").fill("Four, again"); + await page.getByTestId("new-section-add-m2").click(); + await expect.poll(() => read(MANIFEST).render.chrome.deck.markers[2].label).toBe("Four, again"); + // Remove boundary: §1 joins §0. + await page.locator("[data-section-remove='0']").click(); + await expect.poll(afters).toEqual(["c04", "c05"]); + expect(patchAfters()).toEqual(["c04", "c05"]); +}); + +test("a section bar dragged onto a clip moves the boundary; a clip dropped on a bar opens that section", async ({ page }) => { + await open(page); + // The "Three" boundary (marker 1, after c04) dragged onto c03. + await page.locator("[data-bar-handle='1']").dragTo(page.locator("li[data-entry='c03'][data-kind]")); + await expect.poll(afters).toEqual(["c02", "c03"]); + expect(patchAfters()).toEqual(["c02", "c03"]); + // Not past its neighbour: onto c01 is refused in words. + await page.locator("[data-bar-handle='1']").dragTo(page.locator("li[data-entry='c01'][data-kind]")); + await expect(page.getByTestId("timeline-error")).toContainText("would cross or touch"); + // c06 dropped on §1's bar: the start of §1. + await page.locator("[data-drag-handle='c06']").dragTo(page.locator("li[data-section-bar='1']")); + await expect.poll(order).toEqual(["c01", "c02", "c06", "c03", "c04", "c05"]); + expect(afters()).toEqual(["c02", "c03"]); +}); diff --git a/umtool/e2e/fixtures/cut-editing-fixture.mjs b/umtool/e2e/fixtures/cut-editing-fixture.mjs @@ -0,0 +1,113 @@ +// What the cut-editing specs act on (UI notes 2026-10-30, items 1, 2, 11, 19), +// each its own project, written by its spec alone: +// +// cut-sections-fixture the deck on, six clips c01–c06 on vid1 in three +// sections -- §0 c01 c02 | §1 "Two" c03 c04 | §2 +// "Three" c05 c06 -- and draft-1.patch.json carrying +// the same markers (in step), so a section edit syncs +// it (cut-sections.spec.ts) +// cut-flash-fixture the clip editor's three clips (clip-editor-fixture.mjs, +// its own copy) with the deck on, a marker after r001 +// and citeUrls -- Flash-forward selection…, Add to +// trailer, a split that keeps its section (cut-flash.spec.ts) +// trailer-fixture the deck's six clips with promo/trailer-beats.json: +// c01 inside its clip, c03 starting 0.5 s before its +// window, c02 after it (out of the cut's order); c04 +// and c06 starred on the walk (trailer-beats.spec.ts) +// take-housekeeping-fixture four takes: draft-9, draft-10 (labelled "draft 9: +// …", the Ember mistake), draft-11, and draft-12 whose +// build lock names a live pid -- RENDERING +// (take-housekeeping.spec.ts) +// +// Synthetic, like every fixture. +import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { makeClipEditorFixture } from "./clip-editor-fixture.mjs"; + +const json = (doc, indent = 2) => JSON.stringify(doc, null, indent) + "\n"; +const write = (dir, name, text) => { + mkdirSync(path.dirname(path.join(dir, name)), { recursive: true }); + writeFileSync(path.join(dir, name), text); +}; + +const MARKERS = [ + { after: "c02", label: "Two", color: "#ff5a5a" }, + { after: "c04", label: "Three", color: "#4fbf6a" }, +]; + +const sixClips = () => + ["c01", "c02", "c03", "c04", "c05", "c06"].map((id, i) => ({ + type: "clip", + id, + video: "vid1", + start: 1 + i * 2, + end: 2.5 + i * 2, + cite: 1 + i * 2, + citeUrl: `https://archive.example/?v=testchan%2Fvid1&t=${1 + i * 2}`, + lock: true, + title: "The Fixture Stream", + date: "2026-10-27", + quote: `the words of ${id}`, + })); + +/** + * @param {{ reports: string, manifest: Function, deckManifest: Function, cachedWindow: string, cues: Array<[number, number, string]> }} o + */ +export function makeCutEditingFixture({ reports, manifest, deckManifest, cachedWindow, cues }) { + // ---- sections -------------------------------------------------------------- + const sections = path.join(reports, "cut-sections-fixture"); + const sm = deckManifest("cut-sections-fixture", "The Cut Sections Fixture", sixClips()); + sm.render.chrome.deck.markers = MARKERS.map((m) => ({ ...m })); + write(sections, "video.manifest.json", json(sm)); + write(sections, "draft-1.patch.json", json({ render: { chrome: { deck: { markers: MARKERS } } }, title: "The Cut Sections Fixture (draft)" })); + mkdirSync(path.join(sections, "out", "clips-raw"), { recursive: true }); + copyFileSync(cachedWindow, path.join(sections, "out", "clips-raw", "vid1_0.00-9.00.mp4")); + + // ---- flash-forward, Add to trailer, split ---------------------------------- + const { dir: flash } = makeClipEditorFixture({ reports, manifest, cachedWindow, cues, name: "cut-flash-fixture", title: "The Cut Flash Fixture" }); + const ff = path.join(flash, "video.manifest.json"); + const fm = JSON.parse(readFileSync(ff, "utf8")); + fm.render = { ...fm.render, width: 1920, height: 1080, chrome: { engine: "hyperframes", layout: "deck", deck: { markers: [{ after: "r001", label: "Two", color: "#ff5a5a" }] } } }; + delete fm.render.headerHeight; + for (const e of fm.timeline) { + e.cite = e.cutStart; + e.citeUrl = `https://archive.example/?v=testchan%2Fvid1&t=${Math.floor(e.cutStart)}`; + e.title = "The Fixture Stream"; + e.date = "2026-10-27"; + e.speakers = ["Subject"]; + } + fm.timeline[1].lockEnd = true; + writeFileSync(ff, json(fm)); + write(flash, "draft-1.patch.json", json({ render: { chrome: { deck: { markers: [{ after: "r001", label: "Two", color: "#ff5a5a" }] } } } })); + + // ---- trailer beats ----------------------------------------------------------- + const trailer = path.join(reports, "trailer-fixture"); + const tm = deckManifest("trailer-fixture", "The Trailer Fixture", sixClips()); + tm.render.chrome.deck.markers = MARKERS.map((m) => ({ ...m })); + for (const e of tm.timeline) if (e.id === "c04" || e.id === "c06") Object.assign(e, { star: true, walkNote: e.id === "c04" ? "this is gold" : "the ending" }); + write(trailer, "video.manifest.json", json(tm)); + // 1-space, as the Ember file was written by hand: a write keeps it. + write(trailer, path.join("promo", "trailer-beats.json"), json([ + { id: "c01", start: 1, end: 2.5 }, + { id: "c03", start: 4.5, end: 6.5 }, + { id: "c02", start: 3, end: 4.5 }, + ], 1)); + + // ---- take housekeeping ------------------------------------------------------- + const takes = path.join(reports, "take-housekeeping-fixture"); + write(takes, "video.manifest.json", json(deckManifest("take-housekeeping-fixture", "The Take Housekeeping Fixture", sixClips().slice(0, 2)))); + const take = (id, order, label) => ({ + id, group: "takes", order, label, kind: "different", summary: "", changes: ["timeline: 2 items"], + preview: "preview.mp4", seconds: 4.5, builtAt: `2026-10-${20 + order}T12:00:00.000Z`, style: null, patch: null, window: "full", + }); + for (const [id, order, label] of [ + ["draft-9", 1, "draft 9: the first walk"], + ["draft-10", 2, "draft 9: re-walked (wrong label)"], + ["draft-11", 3, "draft 11: tightened"], + ["draft-12", 4, "draft 12: rendering"], + ]) write(path.join(takes, "takes", id), "take.json", json(take(id, order, label))); + // pid 1 is always alive; this host, so the lock reads as a render running now. + write(path.join(takes, "takes", "draft-12"), ".building.json", JSON.stringify({ pid: 1, host: os.hostname(), startedAt: "2026-10-31T23:00:00.000Z", take: "draft-12", from: "draft-11" }) + "\n"); + return { sections, flash, trailer, takes }; +} diff --git a/umtool/e2e/fixtures/cut-integrity-fixture.mjs b/umtool/e2e/fixtures/cut-integrity-fixture.mjs @@ -0,0 +1,61 @@ +// What cut-integrity.spec.ts acts on (UI notes 2026-10-30, #3 #5 #6 #7 #8): +// its own project, written by that spec alone. +// +// reports/cut-integrity-fixture/ +// video.manifest.json four clips of vid1 (the fixture corpus's cues): +// c01 1.0-5.0 cite 1 -- overlaps c02 (not next to it): window-overlap +// c03 6.8-8.6 cite 0.5, citeUrl t=0 -- the clock and the QR 6 s early: clip-cite-off +// c02 3.0-6.0 cite 3, confirmed, an editorial note in `correction` +// c04 vid2 2.0-4.0 cite 2, citeUrl naming a record the site does not have +// draft-1.patch.json deck markers after c04 and after `gone` (a clip +// nobody has): patch-markers-stale; removing c04 +// re-anchors the first +// out/clips-raw/ vid1 0.00-9.00, which holds every clip +// +// The site the QRs link is the spec's own (a local HTTP server on a free +// port): every clip's citeUrl names it, and the spec writes its origin into +// them before it opens a page. provenance.siteOrigin stays public-looking. +// +// Synthetic, like every fixture. +import { copyFileSync, mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +export const CUT_INTEGRITY = "cut-integrity-fixture"; +export const SITE_PLACEHOLDER = "http://127.0.0.1:9"; + +const write = (dir, name, doc) => { + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, name), JSON.stringify(doc, null, 2) + "\n"); +}; + +/** The fixture's manifest, its QRs on `site`. Exported so the spec writes the same thing with its server's origin. */ +export function cutIntegrityManifest(manifest, site) { + const link = (id, t) => `${site}/?v=${encodeURIComponent(`testchan/${id}`)}&t=${t}`; + const clip = (id, start, end, extra = {}) => ({ type: "clip", id, video: "vid1", start, end, lock: true, section: 0, ...extra }); + // The origin is a public-looking one (a private origin is a blocking + // manifest-invalid row that projects.spec counts); every clip carries its + // own citeUrl on `site`, so the link check walks the spec's server. + const doc = manifest(CUT_INTEGRITY, "The Cut Integrity Fixture", { siteOrigin: "https://archive.example" }, [ + clip("c01", 1.0, 5.0, { cite: 1, citeUrl: link("vid1", 1), quote: "This is a complete sentence." }), + clip("c03", 6.8, 8.6, { cite: 0.5, citeUrl: link("vid1", 0), quote: "of that it finishes here." }), + // Confirmed, with an editorial note in `correction` (the box there was): "move to walk note". + clip("c02", 3.0, 6.0, { cite: 3, citeUrl: link("vid1", 3), quote: "And this one runs on", verdict: "confirmed", correction: "might want a bit of silence" }), + clip("c04", 2.0, 4.0, { video: "vid2", cite: 2, citeUrl: link("nope", 2), quote: "a record the site does not have" }), + ]); + doc.render.fetchPad = 0; + return doc; +} + +/** + * @param {{ reports: string, manifest: Function, cachedWindow: string }} o + */ +export function makeCutIntegrityFixture({ reports, manifest, cachedWindow }) { + const dir = path.join(reports, CUT_INTEGRITY); + write(dir, "video.manifest.json", cutIntegrityManifest(manifest, SITE_PLACEHOLDER)); + write(dir, "draft-1.patch.json", { + render: { chrome: { deck: { markers: [{ after: "c04", label: "After four" }, { after: "gone", label: "Hand-made" }] } } }, + }); + mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); + copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", path.basename(cachedWindow))); + return dir; +} diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -19,6 +19,7 @@ import { symlinkSync, } from "node:fs"; import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; import path from "node:path"; import { SONG_DATA } from "../../song/paths.mjs"; import { songCapabilities } from "./song-capabilities.mjs"; @@ -34,6 +35,7 @@ import { makeMontageOpsFixture } from "./montage-ops-fixture.mjs"; import { makeClipEditorFixture } from "./clip-editor-fixture.mjs"; import { makeBenchShellFixture } from "./bench-shell-fixture.mjs"; import { makeTakeWalkFixture } from "./take-walk-fixture.mjs"; +import { makeCutIntegrityFixture } from "./cut-integrity-fixture.mjs"; import { makeYoutubeFixture } from "./youtube-fixture.mjs"; import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs"; import { makeRunTraceFixture } from "./run-trace-fixture.mjs"; @@ -44,6 +46,7 @@ import { makeModulesFixture } from "./modules-fixture.mjs"; import { makeMarksFixture } from "./marks-fixture.mjs"; import { makeLivePreviewFixture } from "./live-preview-fixture.mjs"; import { makePlayCutFixture } from "./play-cut-fixture.mjs"; +import { makeCutEditingFixture } from "./cut-editing-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")); @@ -1849,6 +1852,8 @@ makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out" makeBenchShellFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // Walk a take: a draft take of sub-windows, walked on the bench (take-walk.spec.ts). makeTakeWalkFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); +// Cut integrity (UI notes 2026-10-30): the cite following the edge, repeatOf, ★ and walk notes, take patch markers, the QR link check (cut-integrity.spec.ts). +makeCutIntegrityFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts). makeYoutubeFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // Release 36 lane D: the assistant's labels, Suggest, Ask and Apply in the clip editor (clips-suggest.spec.ts). @@ -1865,6 +1870,9 @@ makeMarksFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "cl 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") }); +// Editing the cut (UI notes 2026-10-30): sections, flash-forward, the trailer's beats, take housekeeping +// (cut-sections, cut-flash, trailer-beats and take-housekeeping specs). +makeCutEditingFixture({ reports, manifest, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 }); // Gaps inside a clip and the bench waveform's zoom (gaps-zoom.spec.ts), which WRITES (gaps cut, // undone, put back): its own project on gapvid, a recording id of its own (the fixture's vid1 // window -- tone, silences at 2.9-3.1 and 5.9-6.1 -- so nothing another spec fetches moves it). @@ -1912,6 +1920,29 @@ makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out // Reject ▾ in Play the cut (play-modules.spec.ts), which WRITES (removes c02 as irrelevant, undoes; rejects // it in place as weak, undoes): its own copy too. makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), name: "play-reject-fixture", title: "The Play Reject Fixture" }); +// Play and the bench as one app (play-walk.spec.ts), which WRITES (drops on the reel strip, +// undone; a stamp moved on the bench): play-cut-fixture's cut on vid1 with two sections -- +// §0 c01 c02 | §1 "Two" k01 c03 c04 -- and two whole-cut takes made from it: draft-1 (the +// latest: a retitle, made from the manifest as written, so "no edits since") and draft-0 (older). +{ + const { dir: pwDir } = makePlayCutFixture({ + reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), + name: "play-walk-fixture", title: "The Play Walk Fixture", video: "vid1", + chrome: { deck: { markers: [{ after: "c02", label: "Two", color: "#ff8fb1" }] } }, + }); + rmSync(path.join(pwDir, "takes"), { recursive: true, force: true }); + const text = readFileSync(path.join(pwDir, "video.manifest.json"), "utf8"); + const baseHash = createHash("sha256").update(text).digest("hex"); + const made = (id, order, builtAt, label) => { + mkdirSync(path.join(pwDir, "takes", id), { recursive: true }); + const patch = { title: `The Play Walk Fixture, ${label}` }; + writeFileSync(path.join(pwDir, "takes", id, "take.json"), JSON.stringify({ id, group: "takes", order, label, kind: "different", preview: "preview.mp4", window: "full", style: null, patch, seconds: 9.97, builtAt, baseHash }, null, 2) + "\n"); + writeFileSync(path.join(pwDir, "takes", id, "video.manifest.json"), JSON.stringify({ ...JSON.parse(text), ...patch }, null, 2) + "\n"); + }; + made("draft-0", 1, "2026-10-30T10:00:00.000Z", "draft 0"); + made("draft-1", 2, "2026-11-01T10:00:00.000Z", "draft 1"); + writeFileSync(path.join(pwDir, "takes", "verdicts.json"), JSON.stringify({ "draft-0": { verdict: null, note: "", at: "2026-10-30T11:00:00.000Z", picked: true } }, null, 2) + "\n"); +} // TWO MORE cached windows for vid1, and they are the regression rather than // decoration. diff --git a/umtool/e2e/gaps-zoom.spec.ts b/umtool/e2e/gaps-zoom.spec.ts @@ -1,5 +1,5 @@ import { test, expect, type APIRequestContext, type Page } from "@playwright/test"; -import { readFileSync } from "node:fs"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; @@ -245,15 +245,14 @@ test("the bench plays across a gap the way the cut will: the gap is skipped", as await page.locator("body").press(" "); }); -test("Play the cut plays a gapped clip as one item of jump cuts", async ({ page, request }) => { - expect((await putWindow(request, { gapAdd: "3.5-5.5" })).ok()).toBeTruthy(); - // The render's cut: the gap on the frame grid, the footage the kept seconds. - const got = await (await request.get(`/api/report/cut-points?project=${encodeURIComponent(PROJECT)}`)).json(); - const g01 = got.clips.find((c: { id: string }) => c.id === "g01"); - expect(g01).toMatchObject({ cutStart: 0.5, cutEnd: 8.5, gaps: [{ from: 3.5, to: 5.5 }], footage: 6 }); - - await page.goto(urls.playHref(PROJECT)); +/** + * Play the cut (or `take`) plays g01 -- gap 3.5-5.5 -- as one item of jump cuts: the jump + * on the reel strip 3 s in, no frame from inside the gap, two sound nodes abutting at the join. + */ +const playsJumpCut = async (page: Page, take: string | null = null) => { + await page.goto(urls.playHref(PROJECT, { take })); const root = page.locator("[data-play-cut]"); + await expect(root).toHaveAttribute("data-play-cut", take ?? ""); await expect(root).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 }); await expect(root).toHaveAttribute("data-play-item", "g01"); // The jump cut on the reel strip, 3 s into the clip. @@ -272,7 +271,7 @@ test("Play the cut plays a gapped clip as one item of jump cuts", async ({ page, return id === "g01" && t > 3.2 ? Number(at) : -1; }, { timeout: 20_000, intervals: [100] }) .toBeGreaterThan(5.5); - console.log(`gaps-zoom: drawn ${seen.join(" ")}`); + console.log(`gaps-zoom${take ? ` (take ${take})` : ""}: drawn ${seen.join(" ")}`); const inGap = seen.map((x) => x.split("=")[1]).filter((d) => d.startsWith("g01:")).map((d) => Number(d.split(":")[1])).filter((at) => at > 3.6 && at < 5.4); expect(inGap, "no frame from inside the gap").toEqual([]); // Two sound nodes for g01, abutting at the join (cut second 3), and g02 after its six seconds. @@ -287,4 +286,34 @@ test("Play the cut plays a gapped clip as one item of jump cuts", async ({ page, expect(pieces[1].from).toBeCloseTo(3, 2); expect(pieces[1].to).toBeCloseTo(6, 2); await page.keyboard.press("k"); +}; + +test("Play the cut plays a gapped clip as one item of jump cuts", async ({ page, request }) => { + expect((await putWindow(request, { gapAdd: "3.5-5.5" })).ok()).toBeTruthy(); + // The render's cut: the gap on the frame grid, the footage the kept seconds. + const got = await (await request.get(`/api/report/cut-points?project=${encodeURIComponent(PROJECT)}`)).json(); + const g01 = got.clips.find((c: { id: string }) => c.id === "g01"); + expect(g01).toMatchObject({ cutStart: 0.5, cutEnd: 8.5, gaps: [{ from: 3.5, to: 5.5 }], footage: 6 }); + await playsJumpCut(page); +}); + +// A TAKE plays its gaps too (operator, 1 Nov 2026: a gapped clip played whole in a take's +// Play the cut while the take's render left the gap out). The take is the project's cut +// with its patch -- here a retitle and the deck on, as a real take's is -- so the gap +// is the project's, written after the take was made, and the take's view must keep it. +test("Play the cut on a take plays a gapped clip's kept pieces only", async ({ page, request }) => { + expect((await putWindow(request, { gapAdd: "3.5-5.5" })).ok()).toBeTruthy(); + const dir = path.join(path.dirname(MANIFEST), "takes", "gapped"); + mkdirSync(dir, { recursive: true }); + writeFileSync( + path.join(dir, "take.json"), + `${JSON.stringify({ + id: "gapped", group: "takes", order: 1, label: "Gapped", kind: "different", summary: "", preview: "preview.mp4", window: "full", + patch: { title: "The Gaps Fixture, a take", render: { chrome: { engine: "hyperframes", layout: "deck", deck: {} } } }, + }, null, 2)}\n`, + ); + // The take's render cut names the gap as the project's does. + const got = await (await request.get(`/api/report/cut-points?project=${encodeURIComponent(PROJECT)}&take=gapped`)).json(); + expect(got.clips.find((c: { id: string }) => c.id === "g01")).toMatchObject({ cutStart: 0.5, cutEnd: 8.5, gaps: [{ from: 3.5, to: 5.5 }], footage: 6 }); + await playsJumpCut(page, "gapped"); }); diff --git a/umtool/e2e/phone-walk.spec.ts b/umtool/e2e/phone-walk.spec.ts @@ -295,7 +295,8 @@ test("Play → Edit this clip → move an edge → Back: the new bounds are what await page.keyboard.press("k"); // A take: the edit goes to the project's cut, and the bench says so; Back - // plays the PROJECT's cut (the take's render does not change). + // returns to Play as it was -- the take still playing (Play and the bench + // are one app: Play was never unmounted). await page.goto(urls.playHref(PLAY, { take: "short" })); await expect(root).toHaveAttribute("data-play-item", "c04"); // E (the key is live once hydrated, which the first render cannot show). @@ -305,8 +306,8 @@ test("Play → Edit this clip → move an edge → Back: the new bounds are what }).toPass({ timeout: 15_000 }); await expect(page.locator('[data-back-take="short"]')).toContainText("not take short"); await page.locator("[data-back-to-play]").click(); - await expect(page).toHaveURL(/\/play\?clip=c04$/, { timeout: 20_000 }); - await expect(root).toHaveAttribute("data-play-cut", ""); + await expect(page).toHaveURL(/\/play\?take=short&clip=c04/, { timeout: 20_000 }); + await expect(root).toHaveAttribute("data-play-cut", "short"); await expect(root).toHaveAttribute("data-play-item", "c04"); }); diff --git a/umtool/e2e/play-walk.spec.ts b/umtool/e2e/play-walk.spec.ts @@ -0,0 +1,271 @@ +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"; + +// --------------------------------------------------------------------------- +// Play and the clip bench as ONE app, the reel strip's zoom and drag, the +// working cut's name (operator, 1 Nov 2026; umtool/docs/knobs.md, "Play the +// cut"; clip-bench.md, "Walking the cut"). +// +// play-walk-fixture (WRITABLE, make-fixture.mjs): play-cut-fixture's cut on +// vid1 with two sections -- §0 c01 c02 | §1 "Two" k01 c03 c04 -- and two +// whole-cut takes made from the manifest as written: draft-1 (the latest) +// and draft-0 (older, picked). Every write here is undone before the test +// ends, except the stamp moved last. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const P = "reports/play-walk-fixture"; +const DIR = path.join(FIXTURE, "reports", "play-walk-fixture"); + +type Entry = { id: string; type: string; start?: number; end?: number; claim?: { at?: number } }; +const manifest = () => JSON.parse(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")) as { timeline: Entry[]; render: { chrome: { deck: { markers: { after: string }[] } } } }; +const order = () => manifest().timeline.map((e) => e.id).join(" "); +const afters = () => manifest().render.chrome.deck.markers.map((m) => m.after).join(" "); + +const root = (page: Page) => page.locator("[data-play-cut]"); +const tNow = async (page: Page) => Number(await root(page).getAttribute("data-play-t")); +const ready = async (page: Page) => { + await expect(root(page)).toHaveAttribute("data-play-state", "paused"); + await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 }); +}; +/** The cell's grip band, and a point `frac` of the way across a cell. */ +const cellAt = async (page: Page, id: string, frac = 0.5) => { + const b = (await page.locator(`[data-play-row="${id}"]`).boundingBox())!; + return { x: b.x + b.width * frac, grip: b.y + 6, body: b.y + b.height - 8 }; +}; + +test.beforeEach(() => { + test.setTimeout(120_000); +}); + +test("the working cut is the latest take: named, played by default, switched without the URL write cancelling it", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(P)); + await ready(page); + await expect(page.locator("[data-play-working]")).toHaveAttribute("data-play-working", "draft-1"); + await expect(page.locator("[data-play-working]")).toContainText("Latest"); + await expect(page.locator("[data-play-working]")).toContainText("no edits since"); + await expect(root(page)).toHaveAttribute("data-play-cut", "draft-1"); + await expect(page.locator("[data-play-take-defaulted]")).toHaveCount(1); + // The pick (draft-0, from before) is said small, beside: secondary. + await expect(page.locator('[data-play-picked="draft-0"]')).toContainText("picked: draft-0"); + await page.screenshot({ path: test.info().outputPath("play-latest-label.png") }); + + // A take link clicked WHILE PLAYING: Play's once-a-second URL write used to cancel it. + await page.locator("[data-play-toggle]").click(); + await expect.poll(() => tNow(page), { timeout: 20_000 }).toBeGreaterThan(0.3); + await page.locator('[data-play-take-link="draft-0"]').click(); + await expect(root(page)).toHaveAttribute("data-play-cut", "draft-0", { timeout: 20_000 }); + await expect(page).toHaveURL(/take=draft-0/); + await expect(page.locator("[data-play-working]")).toContainText("Latest is"); + // The manifest alone, and back to the latest. + await page.locator('[data-play-take-link=""]').click(); + await expect(root(page)).toHaveAttribute("data-play-cut", "", { timeout: 20_000 }); + await expect(page).toHaveURL(/cut=1/); + await page.locator("[data-play-latest-link]").click(); + await expect(root(page)).toHaveAttribute("data-play-cut", "draft-1", { timeout: 20_000 }); +}); + +test("the reel strip zooms like the bench waveform: at the pointer, keys, to the clip and the section, an overview", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(P)); + await ready(page); + const strip = page.locator("[data-play-strip]"); + await expect(strip).toHaveAttribute("data-strip-zoom", "fit"); + await expect(page.locator("[data-strip-overview]")).toHaveCount(0); + // Ctrl + wheel at c03: zoomed, and c03 is still under the pointer. + const c = await cellAt(page, "c03"); + await page.mouse.move(c.x, c.body); + await page.keyboard.down("Control"); + await page.mouse.wheel(0, -400); + await page.keyboard.up("Control"); + await expect(strip).not.toHaveAttribute("data-strip-zoom", "fit"); + const c2 = await cellAt(page, "c03"); + const b3 = (await page.locator('[data-play-row="c03"]').boundingBox())!; + expect(c.x).toBeGreaterThanOrEqual(b3.x - 2); + expect(c.x).toBeLessThanOrEqual(b3.x + b3.width + 2); + expect(b3.width).toBeGreaterThan(0); + expect(c2.x).toBeGreaterThan(0); + // The overview shows the whole cut under a zoomed strip; f fits again. + await expect(page.locator("[data-strip-overview] [data-zoom-overview]")).toBeVisible(); + await page.locator("body").press("f"); + await expect(strip).toHaveAttribute("data-strip-zoom", "fit"); + // z zooms in at the playhead; Zoom to section shows §1 (k01 c03 c04) and not c01. + await page.locator('[data-play-row="c03"]').press("Enter"); + await page.locator("body").press("z"); + await expect(strip).not.toHaveAttribute("data-strip-zoom", "fit"); + await page.locator("body").press("f"); + await page.locator("[data-zoom-section]").click(); + await expect(page.locator('[data-play-row="c01"]')).toHaveCount(0); + await expect(page.locator('[data-play-row="c04"]')).toHaveCount(1); + // Zoomed, a cell names its section; the seam names it above. + await expect(page.locator('[data-play-row="c03"]')).toHaveAttribute("aria-label", /§1 Two/); + await page.screenshot({ path: test.info().outputPath("strip-zoomed.png") }); + // F: the clip on screen fills the strip. + await page.locator("body").press("F"); + const z = (await strip.getAttribute("data-strip-zoom"))!.split("-").map(Number); + expect(z[1] - z[0]).toBeLessThan(4); + await page.locator("body").press("f"); +}); + +test("drag to reorder: across a seam into §0, the drop's section said, one write, Undo; a drop that empties a section is refused; Alt+→", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + const before = order(); + expect(before).toBe("c01 c02 k01 c03 c04"); + expect(afters()).toBe("c02"); + await page.goto(urls.playHref(P)); + await ready(page); + // The playhead on c02: it stays on c02 through the move. + await page.locator('[data-play-row="c02"]').press("Enter"); + await expect(root(page)).toHaveAttribute("data-play-item", "c02"); + + // Grab c04 by its grip and drag it onto the right half of c01: after c01, in §0. + const from = await cellAt(page, "c04"); + const to = await cellAt(page, "c01", 0.75); + await page.mouse.move(from.x, from.grip); + await page.mouse.down(); + await page.mouse.move(from.x - 10, from.grip, { steps: 2 }); + await page.mouse.move(to.x, to.body, { steps: 8 }); + await expect(page.locator("[data-strip-ghost]")).toHaveAttribute("data-strip-ghost", "c04"); + await expect(page.locator("[data-strip-drop]")).toHaveAttribute("data-strip-drop-section", "0"); + await expect(page.locator("[data-strip-drop]")).toContainText("c04 → §0 (the opening), after c01"); + await expect(page.locator("[data-strip-insert]")).toHaveAttribute("data-strip-insert", "c02"); + await page.screenshot({ path: test.info().outputPath("strip-mid-drag.png") }); + await page.mouse.up(); + await expect(page.locator('[data-strip-toast="done"]')).toContainText("Moved: c04 → §0 (the opening), after c01"); + await expect.poll(order).toBe("c01 c04 c02 k01 c03"); + expect(afters()).toBe("c02"); + await expect(page.locator('[data-play-row="c04"]')).toHaveAttribute("data-play-row-section", "0", { timeout: 20_000 }); + await expect(root(page)).toHaveAttribute("data-play-item", "c02"); + // The working cut's name counts the edit. + await expect(page.locator("[data-play-working]")).toContainText("+1 edit since", { timeout: 20_000 }); + await page.screenshot({ path: test.info().outputPath("strip-undo-toast.png") }); + + // §1 is down to c03: dragging it into §0 would leave §1 with no clip -- refused before any write. + const c3 = await cellAt(page, "c03"); + const c1 = await cellAt(page, "c01", 0.25); + await page.mouse.move(c3.x, c3.grip); + await page.mouse.down(); + await page.mouse.move(c3.x - 10, c3.grip, { steps: 2 }); + await page.mouse.move(c1.x, c1.body, { steps: 8 }); + await expect(page.locator("[data-strip-drop]")).toHaveAttribute("data-strip-drop-refused", ""); + await page.mouse.up(); + await expect(page.locator("[data-strip-refusal]")).toContainText("§1 Two would have no clip left"); + expect(order()).toBe("c01 c04 c02 k01 c03"); + + // Undo: exactly the drop. + await page.locator("[data-strip-undo]").click(); + await expect(page.locator('[data-strip-toast="undone"]')).toBeVisible(); + await expect.poll(order).toBe(before); + await expect(page.locator('[data-play-row="c04"]')).toHaveAttribute("data-play-row-section", "1", { timeout: 20_000 }); + + // Esc cancels a drag: nothing written. + const f4 = await cellAt(page, "c04"); + await page.mouse.move(f4.x, f4.grip); + await page.mouse.down(); + await page.mouse.move(f4.x - 120, f4.body, { steps: 6 }); + await page.keyboard.press("Escape"); + await page.mouse.up(); + expect(order()).toBe(before); + + // The keyboard: Alt+→ on c01 moves it one place (after c02, still §0); Undo. + await page.locator('[data-play-row="c01"]').focus(); + await page.keyboard.press("Alt+ArrowRight"); + await expect.poll(order).toBe("c02 c01 k01 c03 c04"); + expect(afters()).toBe("c01"); + await expect(page.locator('[data-strip-toast="done"]')).toBeVisible(); + await page.locator("[data-strip-undo]").click(); + await expect.poll(order).toBe(before); + expect(afters()).toBe("c02"); +}); + +test("Play → Edit → the bench in place → Back: the same clip, second and take, no second Play in the history", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(P)); + await ready(page); + // Into c02, a little way in (a click on a cell's body scrubs there). + const mid = await cellAt(page, "c02", 0.6); + await page.mouse.click(mid.x, mid.body); + await expect(root(page)).toHaveAttribute("data-play-item", "c02"); + const t0 = await tNow(page); + const item = "c02"; + const hist = await page.evaluate(() => history.length); + const composed = (await root(page).getAttribute("data-play-compose"))!; + await page.locator("[data-play-edit]").click(); + // In place: Play hidden (kept), the bench on the clip, its address the bench's. + await expect(page.locator(`[data-cut-app-bench="${item}"] [data-bench-shell="clip"]`)).toBeVisible({ timeout: 20_000 }); + await expect(page.locator("[data-cut-app-play]")).toHaveAttribute("data-cut-app-play", "hidden"); + await expect(page).toHaveURL(new RegExp(`/clip/${item}\\?from=play.*order=cut`)); + // The bench names the working cut it edits: the latest take, no edits since. + await expect(page.locator(`[data-cut-app-bench="${item}"] [data-working-cut]`)).toHaveAttribute("data-working-cut", "draft-1"); + await page.screenshot({ path: test.info().outputPath("app-bench-in-place.png") }); + // n: the cut's next clip (the reel strip's order), in place. + const next = "c03"; + await page.locator("body").press("n"); + await expect(page.locator(`[data-cut-app-bench="${next}"]`)).toBeVisible({ timeout: 20_000 }); + await expect(page).toHaveURL(new RegExp(`/clip/${next}\\?`)); + // Back to the cut: Play as it was -- the clip, the second, the take -- and history as it was. + await page.locator("[data-back-to-play]").click(); + await expect(page.locator("[data-cut-app-play]")).toHaveAttribute("data-cut-app-play", "shown"); + await expect(root(page)).toHaveAttribute("data-play-item", item); + expect(Math.abs((await tNow(page)) - t0)).toBeLessThan(0.15); + await expect(root(page)).toHaveAttribute("data-play-cut", "draft-1"); + await expect(page).toHaveURL(/\/play\?/); + expect(await page.evaluate(() => history.length)).toBe(hist + 2); + // ...and Play did not start over: the deck is not being composed again (nothing changed). + await expect(root(page)).toHaveAttribute("data-play-compose", composed); + expect(composed).not.toBe("composing"); +}); + +test("Back and Forward step between Play and the bench; the bench on its own goes to Play from here", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(P)); + await ready(page); + await page.locator('[data-play-row="c04"]').press("Enter"); + await expect(root(page)).toHaveAttribute("data-play-item", "c04"); + await page.locator("body").press("e"); + await expect(page.locator('[data-cut-app-bench="c04"] [data-bench-shell="clip"]')).toBeVisible({ timeout: 20_000 }); + await page.goBack(); + await expect(page.locator("[data-cut-app-play]")).toHaveAttribute("data-cut-app-play", "shown"); + await expect(root(page)).toHaveAttribute("data-play-item", "c04"); + await page.goForward(); + await expect(page.locator('[data-cut-app-bench="c04"] [data-bench-shell="clip"]')).toBeVisible({ timeout: 20_000 }); + await page.goBack(); + await expect(page.locator("[data-cut-app-play]")).toHaveAttribute("data-cut-app-play", "shown"); + // A reload of the bench's address is the bench's own page; Walk → Play from there. + await page.goto(urls.clipBenchHref(P, "c03")); + const here = page.locator("[data-play-from-here]"); + await expect(here).toHaveAttribute("href", urls.playHref(P, { clip: "c03" })); + await page.screenshot({ path: test.info().outputPath("app-walk-play-from-here.png") }); + await here.click(); + await expect(page).toHaveURL(/\/play\?clip=c03/); + await expect(root(page)).toHaveAttribute("data-play-item", "c03", { timeout: 20_000 }); +}); + +test("a window save refused for the stamp's second offers the fix: Move the stamp, in one write, the trim kept", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + // c02 is 3.5–5.5 with its stamp (k1) at 4.5. + expect(manifest().timeline.find((e) => e.id === "c02")!.claim!.at).toBe(4.5); + await page.goto(urls.clipBenchHref(P, "c02")); + await expect(page.locator('[data-bench="c02"]')).toHaveCount(1); + // The start to 4.6 (past the stamp), by the keys: } is +0.5 s, ] +0.05 s. + await page.locator("body").press("Shift+BracketRight"); + await page.locator("body").press("Shift+BracketRight"); + await page.locator("body").press("BracketRight"); + await page.locator("body").press("BracketRight"); + await page.locator("[data-save-window]").click(); + const fix = page.locator('[data-bench-fix="mark"]'); + await expect(fix).toContainText("The stamp at 4.50 would be outside 4.60–5.50"); + await expect(page.locator("[data-bench-note]")).toContainText("claim.at 4.5"); + await expect(page.locator('[data-bench-fix-move="first"]')).toContainText("Move the stamp to 4.60 (first second)"); + await expect(page.locator("[data-bench-fix-clear]")).toContainText("Clear the stamp's second"); + await page.screenshot({ path: test.info().outputPath("bench-stamp-fix.png") }); + await page.locator('[data-bench-fix-move="first"]').click(); + await expect(fix).toHaveCount(0); + await expect.poll(() => manifest().timeline.find((e) => e.id === "c02")!.start).toBe(4.6); + expect(manifest().timeline.find((e) => e.id === "c02")!.claim!.at).toBe(4.6); +}); diff --git a/umtool/e2e/take-housekeeping.spec.ts b/umtool/e2e/take-housekeeping.spec.ts @@ -0,0 +1,86 @@ +import { test, expect } from "@playwright/test"; +import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// Take housekeeping in the takes list (UI notes 2026-10-30, item 19): +// +// take-housekeeping-fixture draft-9, draft-10 (labelled "draft 9: …", the +// Ember mistake), draft-11, draft-12 RENDERING (its +// build lock names a live pid, built from draft-11). +// WRITES take.json labels, verdicts.json, revisions/. +// +// Relabel, Mark superseded (folded away, shown dimmed on request), Not +// superseded -- and a running render respected: draft-12 is not relabelled, +// neither it nor its base is deleted. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const DIR = path.join(HERE, "..", ".e2e-song", "reports", "take-housekeeping-fixture"); +const PROJECT = "reports/take-housekeeping-fixture"; +const takeFile = (id: string) => path.join(DIR, "takes", id, "take.json"); +const label = (id: string) => JSON.parse(readFileSync(takeFile(id), "utf8")).label as string; +const verdicts = () => (existsSync(path.join(DIR, "takes", "verdicts.json")) ? JSON.parse(readFileSync(path.join(DIR, "takes", "verdicts.json"), "utf8")) : {}); + +const PRISTINE = new Map<string, string>(); +test.beforeAll(() => { + for (const id of ["draft-9", "draft-10", "draft-11", "draft-12"]) PRISTINE.set(id, readFileSync(takeFile(id), "utf8")); +}); +test.beforeEach(() => { + for (const [id, text] of PRISTINE) { + writeFileSync(takeFile(id), text); + rmSync(path.join(DIR, "takes", id, "revisions"), { recursive: true, force: true }); + } + rmSync(path.join(DIR, "takes", "verdicts.json"), { force: true }); +}); + +test("relabel a take; a take that is rendering is not relabelled", async ({ page }) => { + await page.goto(urls.takesHref(PROJECT)); + const card = page.locator("[data-take='draft-10']"); + await expect(card.locator("[data-take-label]")).toContainText("draft 9: re-walked (wrong label)"); + await card.locator('[data-action="relabel"]').click(); + await card.locator("[data-take-relabel]").fill("draft 10: re-walked"); + await card.locator("[data-take-relabel]").press("Enter"); + await expect.poll(() => label("draft-10")).toBe("draft 10: re-walked"); + await expect(card.locator("[data-take-label]")).toContainText("draft 10: re-walked"); + expect(existsSync(path.join(DIR, "takes", "draft-10", "revisions"))).toBe(true); + + const busy = page.locator("[data-take='draft-12']"); + await expect(busy.locator("[data-take-held]")).toHaveText("rendering now"); + await expect(page.locator("[data-take='draft-11'] [data-take-held]")).toHaveText("a render is made from it"); + await busy.locator('[data-action="relabel"]').click(); + await busy.locator("[data-take-relabel]").fill("draft 12: renamed"); + await busy.locator('[data-action="relabel-save"]').click(); + await expect(busy).toContainText("is not relabelled: it is rendering now (pid 1"); + expect(label("draft-12")).toBe("draft 12: rendering"); +}); + +test("mark a take superseded: folded away, shown dimmed on request, and back", async ({ page }) => { + await page.goto(urls.takesHref(PROJECT)); + const card = page.locator("[data-take='draft-9']"); + await card.locator("[data-take-superseded-by='draft-9']").selectOption("draft-11"); + await card.locator('[data-action="supersede"]').click(); + await expect.poll(() => verdicts()["draft-9"]?.superseded?.by).toBe("draft-11"); + await expect(page.locator("[data-take='draft-9']")).toHaveCount(0); + await expect(page.locator("[data-superseded-count]")).toContainText("1 superseded take folded away"); + await page.locator('[data-action="show-superseded"]').click(); + const shown = page.locator("[data-take='draft-9']"); + await expect(shown).toHaveAttribute("data-superseded", "draft-11"); + await expect(shown.locator("[data-take-superseded]")).toHaveText("superseded by draft-11"); + await shown.locator('[data-action="unsupersede"]').click(); + await expect.poll(() => verdicts()["draft-9"]).toBeUndefined(); + await expect(page.locator("[data-take='draft-9']")).not.toHaveAttribute("data-superseded", /.*/); +}); + +test("delete refuses a take that is rendering, and the take it is rendered from", async ({ page }) => { + await page.goto(urls.takesHref(PROJECT)); + await page.locator("[data-take='draft-12']").getByRole("button", { name: "Delete take draft-12" }).click(); + const plan = page.getByRole("region", { name: "delete take draft-12" }); + await expect(plan).toHaveAttribute("data-delete-blocked", "yes"); + await expect(plan.getByRole("list", { name: "refused" })).toContainText("take draft-12: it is rendering now"); + await page.locator("[data-take='draft-11']").getByRole("button", { name: "Delete take draft-11" }).click(); + await expect(page.getByRole("region", { name: "delete take draft-11" }).getByRole("list", { name: "refused" })).toContainText("take draft-12 is being rendered from it"); + expect(existsSync(takeFile("draft-12"))).toBe(true); +}); diff --git a/umtool/e2e/trailer-beats.spec.ts b/umtool/e2e/trailer-beats.spec.ts @@ -0,0 +1,104 @@ +import { test, expect, type Page } from "@playwright/test"; +import { copyFileSync, existsSync, readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// The Trailer page (UI notes 2026-10-30, item 11): +// +// trailer-fixture six clips c01–c06 (1.5 s each), c04 and c06 starred on +// the walk; promo/trailer-beats.json (1-space, an array): +// c01 inside its clip, c03 starting 0.5 s before its +// window, c02 after it -- out of the cut's order. +// WRITES promo/; every test starts from the fixture's. +// +// The running length against the limit, the beat outside its clip and "fit +// to clip", Order by the cut, the platform limit, the ★ candidates, add, +// move, remove -- each through POST /api/report/trailer-beats. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const DIR = path.join(HERE, "..", ".e2e-song", "reports", "trailer-fixture"); +const BEATS = path.join(DIR, "promo", "trailer-beats.json"); +const PROJECT = "reports/trailer-fixture"; + +const doc = () => JSON.parse(readFileSync(BEATS, "utf8")); +const beats = () => { + const d = doc(); + return (Array.isArray(d) ? d : d.beats) as { id?: string; start?: number; end?: number }[]; +}; + +test.beforeAll(() => { + if (!existsSync(`${BEATS}.pristine`)) copyFileSync(BEATS, `${BEATS}.pristine`); +}); +test.beforeEach(() => { + copyFileSync(`${BEATS}.pristine`, BEATS); + rmSync(`${BEATS}.bak`, { force: true }); +}); + +async function open(page: Page) { + await page.goto(urls.trailerHref(PROJECT)); + await expect(page.getByTestId("trailer-editor")).toBeVisible(); +} + +test("the Cut tab links the Trailer page; it says the running length, the limit and the beat to fix", async ({ page }) => { + await page.goto(urls.section(PROJECT, "timeline")); + await expect(page.locator("[data-trailer-link]")).toHaveText("Trailer — 3 beats"); + await page.locator("[data-trailer-link]").click(); + await expect(page.getByTestId("trailer-editor")).toBeVisible(); + // 3 × 1.5 s, two 0.3 s crossfades. + await expect(page.getByTestId("trailer-total")).toHaveText("0:03.9"); + await expect(page.getByTestId("trailer-editor")).toContainText("of 2:20.0"); + await expect(page.getByTestId("trailer-outside")).toHaveText("1 beat to fix"); + await expect(page.locator("[data-beat-problems='2']")).toHaveText("starts 0.50 s before c03's window (5–6.5)"); + await expect(page.getByTestId("trailer-order")).toHaveText("Order by the cut"); +}); + +test("fit to clip pulls the beat inside; Order by the cut; the file keeps its shape", async ({ page }) => { + await open(page); + await page.locator("[data-beat-fit='2']").click(); + await expect.poll(() => beats()[1]).toEqual({ id: "c03", start: 5, end: 6.5 }); + await expect(page.getByTestId("trailer-outside")).toHaveCount(0); + await page.getByTestId("trailer-order").click(); + await expect.poll(() => beats().map((b) => b.id)).toEqual(["c01", "c02", "c03"]); + await expect(page.getByTestId("trailer-order")).toHaveText("in the cut's order"); + expect(readFileSync(BEATS, "utf8")).toMatch(/^\[\n \{/); +}); + +test("the platform's limit, and the ★ clips added in the cut's order until it is over", async ({ page }) => { + await open(page); + await expect(page.getByTestId("trailer-candidates")).toContainText("2 not yet beats"); + await expect(page.locator("[data-candidate='c04']")).toContainText("this is gold"); + await page.getByTestId("trailer-limit").selectOption("instagram"); + await expect.poll(() => doc().limit).toBe(90); + await expect(page.getByTestId("trailer-editor")).toContainText("of 1:30.0"); + await page.getByTestId("trailer-limit-seconds").fill("6"); + await page.getByTestId("trailer-limit-seconds").press("Enter"); + await expect.poll(() => doc().limit).toBe(6); + // c04 plays after every clip beat so far: it goes last (the cut's order). + await page.locator("[data-candidate='c04'] button").click(); + await expect.poll(() => beats().map((b) => b.id)).toEqual(["c01", "c03", "c02", "c04"]); + await expect(page.getByTestId("trailer-total")).toHaveAttribute("data-over", "0"); + await page.locator("[data-candidate='c06'] button").click(); + await expect.poll(() => beats().length).toBe(5); + await expect(page.getByTestId("trailer-total")).toHaveAttribute("data-over", "1"); + await expect(page.locator("[data-beat='5']")).toHaveAttribute("data-beat-over", "1"); + await expect(page.getByTestId("trailer-candidates")).toContainText("0 not yet beats"); +}); + +test("add a beat from a clip, edit its seconds, move it and remove it", async ({ page }) => { + await open(page); + await page.getByTestId("trailer-add-clip").selectOption("c05"); + await expect(page.getByTestId("trailer-add-from")).toHaveValue("9"); + await page.getByTestId("trailer-add-to").fill("10.25"); + await page.getByTestId("trailer-add").click(); + await expect.poll(() => beats().map((b) => b.id)).toEqual(["c01", "c03", "c02", "c05"]); + await page.locator("[data-beat-to='4']").fill("10.5"); + await page.locator("[data-beat-to='4']").press("Enter"); + await expect.poll(() => beats()[3].end).toBe(10.5); + await page.locator("[data-beat-up='4']").click(); + await expect.poll(() => beats().map((b) => b.id)).toEqual(["c01", "c03", "c05", "c02"]); + await page.locator("[data-beat-remove='1']").click(); + await expect.poll(() => beats().map((b) => b.id)).toEqual(["c03", "c05", "c02"]); +}); diff --git a/umtool/lib/decisions.ts b/umtool/lib/decisions.ts @@ -78,6 +78,20 @@ export type Decision = { severity: Severity; /** Newest evidence first. */ at: number; + /** The command that settles it from a terminal, when the reducer knows one (`umtool check` prints it). */ + fix?: string; + /** + * The one-press settle the project page offers beside the row, when the + * reducer knows one: a clip patch through the window writer (PUT + * /api/report/window -- "It's deliberate", "Move to 12:34"), or a link check + * (POST /api/report/links). `fix` is its terminal twin. + */ + settle?: + | { kind: "patch"; clip: string; patch: Record<string, unknown>; label: string } + | { kind: "check-links"; label: string; fix?: boolean } + | { kind: "patch-markers"; file: string; label: string }; + /** The clips a project-wide row is about (a site's dead links). */ + clips?: string[]; // ---- The inbox's fields (lib/inbox.ts). ADDITIVE: a row without them is // still a decision, and the reducers above never set them. ---- diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -292,6 +292,11 @@ export function claimBenchHref(project: string, claim: string, q: NoteOpt = {}): } /** Alternative renders of one part of a cut. */ +/** The trailer's beats (promo/trailer-beats.json). */ +export function trailerHref(project: string): string { + return `/projects/${encodePath(project)}/trailer`; +} + export function takesHref(project: string, q: NoteOpt = {}): string { return withQuery(`/projects/${encodePath(project)}/takes`, {}, q.note); } @@ -341,6 +346,8 @@ export function playHref( project: string, q: NoteOpt & { take?: string | null; + /** The project's manifest alone, no take's patch (`?cut=1`); without it and a take, the latest take plays. */ + bare?: boolean; /** Start on this clip, `at` seconds into what the page shows of it (the bench's Back to the cut). */ clip?: string | null; at?: number | null; @@ -348,7 +355,7 @@ export function playHref( ): string { return withQuery( `/projects/${encodePath(project)}/play`, - { take: q.take, clip: q.clip, at: q.clip && q.at != null && q.at > 0 ? q.at.toFixed(2) : null }, + { take: q.take, cut: !q.take && q.bare ? "1" : null, clip: q.clip, at: q.clip && q.at != null && q.at > 0 ? q.at.toFixed(2) : null }, q.note, ); } diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs @@ -128,6 +128,11 @@ const ACTION_LABEL = { "clip-incorrect": "Remove or fix the clip", "clip-rejected": "Take the clip out", "window-overlap": "Fix the windows", + "clip-cite-off": "Move the cite to the clip", + "patch-markers-stale": "Fix the take patch", + "link-dead": "Fix the links", + "links-unverified": "Check links again", + "links-unchecked": "Check links", "no-punctuation": "Check the windows", "manifest-invalid": "Fix the manifest", "stale-build": "Rebuild the video", diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs @@ -33,6 +33,11 @@ export const WHAT = { "clip-incorrect": "clips marked incorrect", "clip-rejected": "rejected clips still in the cut", "window-overlap": "windows overlap", + "clip-cite-off": "clock or QR off the clip", + "patch-markers-stale": "take patch names clips that are gone", + "link-dead": "QR links that don't open", + "links-unverified": "links not verified", + "links-unchecked": "links not checked", "no-punctuation": "windows without punctuation", "manifest-invalid": "manifest invalid", "stale-build": "video out of date", diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs @@ -43,6 +43,9 @@ import { widen } from "umtool-report-to-video/resolve-windows"; import { montageOn } from "umtool-report-to-video/montage"; import { validateGaps } from "umtool-report-to-video/gaps"; import { fileSig, pathCache } from "../pathCache.mjs"; +import { citeOffsets } from "../report/citeFollow.mjs"; +import { PATCH_FILE_RE, stalePatchMarkers } from "../report/patchMarkers.mjs"; +import { linkVerdicts, linksFile, readLinkCheck } from "../report/linkCheck.mjs"; // widen() and the cache's window naming are IMPORTED, never reimplemented. The // bench's "extend to sentence end" has to be the same function the CLI runs, or @@ -167,6 +170,15 @@ export function deadOriginWhy(m, qrs) { const stat0 = (p) => stat(p).then((s) => s, () => null); +/** A source second as the check rows say it: `m:ss`, or `h:mm:ss`. */ +const hmsShort = (sec) => { + const t = Math.max(0, Math.floor(Number(sec) || 0)); + const h = Math.floor(t / 3600); + const mm = Math.floor((t % 3600) / 60); + const ss = String(t % 60).padStart(2, "0"); + return h ? `${h}:${String(mm).padStart(2, "0")}:${ss}` : `${mm}:${ss}`; +}; + export const manifestPath = (dir) => path.join(dir, MANIFEST_NAME); export async function readManifest(dir) { @@ -734,14 +746,16 @@ const DRAFT_FILE = /^[a-z0-9][a-z0-9-]{0,62}-draft\.json$/; */ export async function reportSignature(dir) { const names = await readdir(dir).catch(() => []); - const drafts = names.filter((n) => DRAFT_FILE.test(n)).sort(); - const [man, out, avail, rev, review, narration, ...draftStats] = await Promise.all([ + const drafts = names.filter((n) => DRAFT_FILE.test(n) || PATCH_FILE_RE.test(n)).sort(); + const [man, out, avail, links, rev, review, narration, ...draftStats] = await Promise.all([ stat0(manifestPath(dir)), stat0(path.join(dir, "out")), // Rewritten IN PLACE by every preflight, which leaves out/'s own mtime // where it was -- so it has to be signed on its own or a re-check would // never reach the index. stat0(path.join(dir, "out", "availability.json")), + // The link check's record (linkCheck.mjs), rewritten in place the same way. + stat0(linksFile(dir)), stat0(path.join(dir, "revisions")), stat0(path.join(dir, DRAFTS_REVIEW_FILE)), stat0(path.join(dir, NARRATION_REVIEW_FILE)), @@ -753,6 +767,7 @@ export async function reportSignature(dir) { man?.size ?? 0, Math.round(out?.mtimeMs ?? 0), Math.round(avail?.mtimeMs ?? 0), + signed(links), Math.round(rev?.mtimeMs ?? 0), signed(review), signed(narration), @@ -1038,6 +1053,24 @@ export const REPORT_DECISION_KINDS = [ // Where the deliverables are disagrees with `storage.deliverables`, or a // move was cut. `open`: nothing is lost, and one command settles it. "storage-mismatch", + // The clock (`cite`) or the QR's `t=` names a second more than a lead-in + // before what the clip plays, or after it (citeFollow.mjs). `open`: the + // build does not refuse it, but the video cites a moment it does not show. + // Its action moves them to the clip. + "clip-cite-off", + // A take patch beside the manifest (`*.patch.json`) whose deck markers + // name a clip that is not in the cut (patchMarkers.mjs): a take made with + // it is refused. `open`: the project's own build is fine. + "patch-markers-stale", + // A clip QR that does not open on the site it links (linkCheck.mjs, the + // recorded check in out/links.json). BLOCKING, as a QR that resolves + // nowhere always was: one row per site, naming the clips and why. + "link-dead", + // The recorded link check could not reach a site (offline, a timeout, no + // corpus.json): those links are not verified. `info`. + "links-unverified", + // Links never checked, or changed since the check. `info`, with Check links. + "links-unchecked", ]; /** @@ -1264,17 +1297,74 @@ export async function reportDecisions(ctx, summary) { if (a.repeatOf === b.id || b.repeatOf === a.id) continue; const seam = timelineIndex.get(b) === timelineIndex.get(a) + 1 && overlap <= D + 0.01; if (seam) continue; + // "It's deliberate": the one that plays LATER in the cut re-plays the + // earlier one (a callback, a flash-forward) -- `repeatOf` through the + // window writer, which clears this row. + const [first, again] = (timelineIndex.get(a) ?? 0) <= (timelineIndex.get(b) ?? 0) ? [a, b] : [b, a]; add( "window-overlap", a.id, `overlaps ${b.id} by ${overlap.toFixed(1)}s` + (a.lockEnd ? " and has lockEnd, so nothing will trim it" : ""), a.lockEnd ? "open" : "info", - { href: clipHref(a.id) }, + { + href: clipHref(a.id), + fix: `umtool window ${id} ${again.id} --repeat-of ${first.id} # if ${again.id} re-plays ${first.id} on purpose`, + settle: { kind: "patch", clip: again.id, patch: { repeatOf: first.id }, label: `It's deliberate: ${again.id} repeats ${first.id}` }, + }, ); } } + // THE CLOCK AND THE QR NAME A SECOND THE CLIP PLAYS (citeFollow.mjs). The + // writer moves them with an edge now; this is for what was written before, + // or by hand. + for (const e of clips) { + const off = citeOffsets(e, { channelSlug: m.provenance?.channelSlug ?? null }); + if (!off) continue; + const words = (n) => (n < 0 ? `${Math.abs(n).toFixed(0)} s before the clip` : `${n.toFixed(0)} s after the clip ends`); + const what = + off.clockOff && off.qrOff && Math.sign(off.clockOff) === Math.sign(off.qrOff) + ? `the clock and the QR point ${words(off.clockOff)}` + : [off.clockOff ? `the clock points ${words(off.clockOff)}` : null, off.qrOff ? `the QR points ${words(off.qrOff)}` : null].filter(Boolean).join("; "); + const flags = [ + off.patch.cite !== undefined ? `--cite ${off.patch.cite}` : null, + off.patch.citeUrl !== undefined ? `--cite-url '${off.patch.citeUrl}'` : null, + ].filter(Boolean).join(" "); + add( + "clip-cite-off", + e.id, + `${what} (${off.clockOff ? `cite ${hmsShort(off.clock)}` : `QR t=${off.qr}`}, it plays ${hmsShort(off.from)}–${hmsShort(off.to)})`, + "open", + { + href: clipHref(e.id), + fix: `umtool window ${id} ${e.id} ${flags}`, + settle: { kind: "patch", clip: e.id, patch: off.patch, label: `Move to ${hmsShort(off.at)}` }, + }, + ); + } + + // A TAKE PATCH WHOSE MARKERS NAME A CLIP THAT IS GONE (patchMarkers.mjs). + // The structural writers re-anchor them now; this is for the rest. + for (const p of await stalePatchMarkers(dir, m)) { + if (p.error) { + add("patch-markers-stale", p.file, `does not read (${p.error}) — a take made with it is refused`, "open"); + continue; + } + const named = p.markers.map((mk) => `${mk.label ? `"${mk.label}"` : `marker ${mk.index}`} after ${mk.after}`); + add( + "patch-markers-stale", + p.file, + `${p.markers.length === 1 ? "a deck marker names a clip" : `${p.markers.length} deck markers name clips`} not in the cut: ` + + `${named.slice(0, 4).join(", ")}${named.length > 4 ? ` and ${named.length - 4} more` : ""} — a take made with --patch ${p.file} is refused`, + "open", + { + fix: `umtool patch-markers ${id} ${p.file} --fix # each takes the cut's marker of the same label; the rest by hand`, + settle: { kind: "patch-markers", file: p.file, label: "Take the cut's markers" }, + }, + ); + } + // A CLIP RULED INCORRECT STILL IN THE CUT. The walk recorded it; nothing // downstream acts on a verdict, so this is where it stops a render. for (const e of incorrectClips(clips)) { @@ -1464,6 +1554,70 @@ export async function reportDecisions(ctx, summary) { ); } + // --- do the QR links open? (linkCheck.mjs) ------------------------------- + // The recorded check, never a live one: the reducer does not fetch. + { + const doc = await readLinkCheck(dir); + const v = linkVerdicts(m, doc); + const checkSettle = { kind: "check-links", label: doc ? "Check links again" : "Check links" }; + const checkFix = `umtool links ${id}`; + if (v.archive > 0) { + const when = v.checkedAt ? ` on ${v.checkedAt.slice(0, 16).replace("T", " ")}` : ""; + const byOrigin = (rows) => { + const g = new Map(); + for (const r of rows) { + const k = r.origin ?? "?"; + if (!g.has(k)) g.set(k, []); + g.get(k).push(r); + } + return g; + }; + for (const [origin, rows] of byOrigin(v.dead)) { + const host = (() => { try { return new URL(origin).host; } catch { return origin; } })(); + const o = v.origins[origin] ?? {}; + const ids = [...new Set(rows.map((r) => r.clip))]; + add( + "link-dead", + host, + `${rows.length} of ${v.archive} QR link${v.archive === 1 ? "" : "s"} don't open on ${host}` + + `${o.generatedAt ? ` (deployed ${o.generatedAt.slice(0, 10)})` : ""}: ${ids.slice(0, 8).join(", ")}${ids.length > 8 ? ` and ${ids.length - 8} more` : ""}` + + ` — ${rows[0].clip}: ${rows[0].why}` + + (rows.some((r) => r.fix) ? `. Every clip with a fix: \`umtool links ${id} --fix\`` : ""), + "blocking", + { + fix: rows.some((r) => r.fix) ? `umtool links ${id} --fix` : checkFix, + // The links whose fix is known (a Twitch id the site serves as v<id>) are rewritten in one press. + settle: rows.some((r) => r.fix) + ? { kind: "check-links", fix: true, label: `Fix ${rows.filter((r) => r.fix).length} link${rows.filter((r) => r.fix).length === 1 ? "" : "s"} (the site's v<id>)` } + : checkSettle, + clips: ids, + }, + ); + } + for (const [origin, rows] of byOrigin(v.unverified)) { + const host = (() => { try { return new URL(origin).host; } catch { return origin; } })(); + add( + "links-unverified", + host, + `${rows.length} link${rows.length === 1 ? "" : "s"} not verified${when} — ${rows[0].why}`, + "info", + { fix: checkFix, settle: checkSettle }, + ); + } + if (!doc) { + add("links-unchecked", "QR links", `${v.archive} archive link${v.archive === 1 ? "" : "s"} never checked against the site${v.archive === 1 ? "" : "s"} they open`, "info", { fix: checkFix, settle: checkSettle }); + } else if (v.unchecked.length) { + add( + "links-unchecked", + "QR links", + `${v.unchecked.length} link${v.unchecked.length === 1 ? "" : "s"} changed since the check${when}: ${v.unchecked.slice(0, 6).map((l) => l.clip).join(", ")}${v.unchecked.length > 6 ? " …" : ""}`, + "info", + { fix: checkFix, settle: checkSettle }, + ); + } + } + } + // --- the build ----------------------------------------------------------- if (s.build.stale) { add( diff --git a/umtool/lib/report/bankTrim.mjs b/umtool/lib/report/bankTrim.mjs @@ -6,8 +6,10 @@ // budget. Letting a wanted decode go is a thrash, not a saving: the engine // asks for it again on its next tick, the clock holds on it ("loading…"), and // the next decode to land lets it go again. A neighbourhood of long gapped -// clips (each decoded whole, its gaps too) is past three minutes of PCM -// together, which is what kept nt1, lw1 and lj1 loading forever. +// clips (each decoded whole, its gaps too, as they were then) is past three +// minutes of PCM together, which is what kept nt1, lw1 and lj1 loading +// forever. (A gapped clip is decoded per kept piece now, and each clip once +// across the two sets of edges: `coveringSlot`, below.) /** * @param {{ key: string, state: string, bytes: number, used: number }[]} slots @@ -27,3 +29,28 @@ export function keysToTrim(slots, wanted, budget) { } return out; } + +/** + * The decode a node can play from: one of a clip's slots (same clip, same + * window, same bytes -- `prefix`) whose span covers the source seconds it + * reads. A decode is never asked for twice to play a span inside one already + * held: the manifest's edges and the render's (playSchedule.mjs decodesOf, + * EDGE_SLACK), a seek, a re-plan. Ready first, then one under way, then a + * failed one (so the node plays silent rather than holding the clock); the + * last used among equals. null: none covers it. + * + * @param {{ key: string, state: string, used: number, span: { from: number, to: number } }[]} slots + * @param {string} prefix + * @param {{ from: number, to: number }} need + */ +export function coveringSlot(slots, prefix, need) { + const rank = { ready: 0, loading: 1, failed: 2 }; + let best = null; + for (const s of slots) { + if (!s.key.startsWith(prefix)) continue; + if (!(s.span.from <= need.from + 1e-6 && s.span.to >= need.to - 1e-6)) continue; + const r = rank[/** @type {"ready" | "loading" | "failed"} */ (s.state)] ?? 3; + if (!best || r < best.r || (r === best.r && s.used > best.s.used)) best = { s, r }; + } + return best ? best.s.key : null; +} diff --git a/umtool/lib/report/bankTrim.test.mjs b/umtool/lib/report/bankTrim.test.mjs @@ -5,7 +5,7 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { keysToTrim } from "./bankTrim.mjs"; +import { coveringSlot, keysToTrim } from "./bankTrim.mjs"; const MB = 1024 * 1024; const slot = (key, mb, used, state = "ready") => ({ key, state, bytes: mb * MB, used }); @@ -37,3 +37,13 @@ test("stale-edge and out-of-window decodes go first, wanted ones stay", () => { test("a decode still loading is not trimmed (it has no bytes to give back)", () => { assert.deepEqual(keysToTrim([slot("a", 0, 1, "loading"), slot("b", 80, 2)], new Set(["b"]), 72 * MB), []); }); + +test("coveringSlot: a decode of the clip's window that holds the seconds; ready before loading before failed", () => { + const s = (key, state, from, to, used = 1) => ({ key, state, used, span: { from, to } }); + const slots = [s("a|w|1|9|20", "loading", 9, 20, 5), s("a|w|1|9.5|15", "ready", 9.5, 15, 1), s("b|w|1|0|100", "ready", 0, 100, 9)]; + assert.equal(coveringSlot(slots, "a|w|1|", { from: 10, to: 14 }), "a|w|1|9.5|15", "the ready one"); + assert.equal(coveringSlot(slots, "a|w|1|", { from: 10, to: 19 }), "a|w|1|9|20", "only the one under way covers it"); + assert.equal(coveringSlot(slots, "a|w|1|", { from: 8, to: 14 }), null, "none: another clip's never counts"); + assert.equal(coveringSlot([s("a|w|1|0|9", "failed", 0, 9)], "a|w|1|", { from: 1, to: 2 }), "a|w|1|0|9", "a failure plays silent, not held"); + assert.equal(coveringSlot([s("a|w|2|0|9", "ready", 0, 9)], "a|w|1|", { from: 1, to: 2 }), null, "the window's bytes replaced: another version"); +}); diff --git a/umtool/lib/report/benchData.ts b/umtool/lib/report/benchData.ts @@ -0,0 +1,300 @@ +import { notFound } from "next/navigation"; +import { projectsHref, clipBenchHref, playHref, takeClipHref, takeWalkHref, takesHref } from "@/lib/hrefs"; +import type { ClipBenchData } from "@/components/projects/ClipBench"; +import type { BenchKey, BenchLink } from "@/components/projects/bench/BenchShell"; +import { + clipVerdict, + cuesInWindow, + siblingsOf, + walkOrder, + walkReadiness, +} from "@/lib/projects/report.mjs"; +import { walkNeighbours, walkOf } from "@/lib/report/walkData.mjs"; +import { projectCache, segmentFor, windowVersion, windowsFor } from "@/lib/report/serve.mjs"; +import { FETCH_MAX_PAD } from "@/lib/report/driver.mjs"; +import { deckOn } from "umtool-report-to-video/deck"; +import { pieceHrefOfProject } from "@/lib/pieces/article"; +import { readWorkingCut } from "@/lib/report/workingCut.mjs"; +import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs"; +import type { ProjectRef } from "@/lib/project-types"; + +// THE CLIP BENCH'S DATA, in one place: what `/projects/<p>/clip/<id>` renders +// (ClipBenchPage) and what Play's in-place bench fetches (GET /api/report/bench, +// components/projects/cutApp/CutApp.tsx) -- the same function, so the bench in +// the app and the bench on its own page can never disagree. The clip id is +// validated as a MEMBER of the timeline, never as a path. +// +// `order: "cut"` (the bench opened inside Play): p / n step along the CUT -- +// the reel strip's neighbours, every clip judged or not -- not the walk's +// recording order; the walk is a different journey. + +/** BenchTop's props, as data (the server page and the app both draw it). */ +export type BenchTopSpec = { + trail: { href: string; label: string }[]; + back: { href: string; label: string }; + kind: string; + here: string; + phone?: "hidden"; + slot?: boolean; + pos: { index: number; total: number }; + prev: BenchLink | null; + next: BenchLink | null; + keys: BenchKey[]; + note: string; +}; + +/** + * @returns null when the clip is not a clip of the cut (or the take) -- the page's 404 + */ +export async function clipBenchData( + project: ProjectRef, + clipId: string, + { search = {}, take = null, order = "walk" }: { search?: Record<string, string | undefined>; take?: string | null; order?: "walk" | "cut" } = {}, +): Promise<{ data: ClipBenchData; top: BenchTopSpec } | null> { + // `?all=1`: the walk visits every fetched clip, judged or not. + const all = search.all === "1"; + let walk: Awaited<ReturnType<typeof walkOf>>; + try { + walk = await walkOf(project, { take, all }); + } catch { + return null; + } + const manifest = walk.manifest; + const detail = walk.detail; + const entry = detail.entries.find( + (e: { id: string; kind: string }) => e.id === clipId && e.kind === "clip", + ); + if (!entry) return null; + + // In WALK order (by source date, each recording's clips together): `p`/`n` + // step through the recordings, not the cut (lib/projects/report.mjs, walkOrder). + const clips = walkOrder(detail.entries) as typeof detail.entries; + const i = clips.findIndex((e: { id: string }) => e.id === clipId); + + // ---- where `p` and `n` go ------------------------------------------------ + // + // The walk visits the clips that still NEED JUDGEMENT and are FETCHED, in + // walk order (by source). A clip nobody can play is a dead end -- there is nothing to + // judge and the only move is to press `n` again -- and one already answered is + // the round trip a walk exists to remove. A URL still opens ANY clip: this + // page renders it, says what it has (or has not) got, and points its links at + // the fetched, unjudged neighbours on either side. (walkData.mjs, the + // reading `umtool walk` prints; `all` keeps the judged ones on it too.) + const readiness = walkReadiness(clips); + const walkNb = walkNeighbours(walk.order, walk.onWalk, clipId); + // In the cut's order (Play's bench): the clips either side on the timeline, judged or not. + const cutClips = ((detail.entries ?? []) as { id: string; kind: string }[]).filter((e) => e.kind === "clip"); + const ci = cutClips.findIndex((e) => e.id === clipId); + const { prev, next } = + order === "cut" ? { prev: ci > 0 ? cutClips[ci - 1].id : null, next: ci >= 0 && ci + 1 < cutClips.length ? cutClips[ci + 1].id : null } : walkNb; + + // One listing of clips-raw for the page: readClipDetail already built one to + // answer `fetched` for every clip, and this is the same question for this one. + const windows = await windowsFor(project, entry, await projectCache(project, manifest)); + // The mtime rides along so a re-render busts the browser's cache: the segment + // is written back to the SAME path, and without it the player would keep + // showing the cut from before the edit. A take's clip has none: the + // project's segments are the project's cut. + const seg = take ? null : await segmentFor(project, clipId); + const widest = windows[0] ?? null; + const view = widest + ? { from: widest.from, to: widest.to } + : { from: Math.max(0, entry.start - 20), to: entry.end + 20 }; + const cues = await cuesInWindow(project.dir, clipId, view.from, view.to, { manifest }); + + const data: ClipBenchData = { + project: project.id, + clip: { + id: entry.id, + video: entry.video, + channel: entry.channel ?? null, + start: entry.start, + end: entry.end, + cite: entry.cite ?? null, + quote: entry.quote ?? null, + note: entry.note ?? null, + correction: entry.correction ?? null, + title: entry.title ?? null, + date: entry.date ?? null, + citeUrl: entry.citeUrl ?? null, + lock: !!entry.lock, + lockStart: !!entry.lockStart, + lockEnd: !!entry.lockEnd, + cutStart: entry.cutStart ?? null, + cutEnd: entry.cutEnd ?? null, + lockCut: !!entry.lockCut, + // The mute mark, from the manifest's own entry: readClipDetail's rows + // carry the fields it reads, and this is not one of them. + muteFrom: + ((manifest.timeline ?? []) as { id: string; muteFrom?: number }[]).find((e) => e.id === clipId) + ?.muteFrom ?? null, + // Seconds cut out of its middle (gaps.mjs), likewise from the manifest's own entry. + gaps: + ((manifest.timeline ?? []) as { id: string; gaps?: { from: number; to: number }[] }[]).find((e) => e.id === clipId) + ?.gaps ?? [], + verdict: + entry.verdict === "confirmed" || entry.verdict === "incorrect" || entry.verdict === "rejected" ? entry.verdict : null, + // What the walk said that is not a verdict, and a deliberate repeat. + walkNote: typeof entry.walkNote === "string" ? entry.walkNote : null, + star: entry.star === true, + repeatOf: typeof entry.repeatOf === "string" ? entry.repeatOf : null, + // Why it was rejected (lib/report/rejectReasons.mjs), from the manifest's own entry. + ...(() => { + const own = ((manifest.timeline ?? []) as { id: string; reason?: unknown; rejectNote?: unknown }[]).find((e) => e.id === clipId); + return { + reason: typeof own?.reason === "string" ? own.reason : null, + rejectNote: typeof own?.rejectNote === "string" ? own.rejectNote : null, + }; + })(), + // From the manifest's own entry: what the on-screen panel says over this + // clip, when somebody has written it. + onscreen: + ((manifest.timeline ?? []) as { id: string; onscreen?: { title?: string; subtitle?: string } }[]).find( + (e) => e.id === clipId, + )?.onscreen ?? null, + }, + // Whether the cut is built with the on-screen panel. Decides whether the + // bench composes a preview of it; the fields are there either way. + deckOn: deckOn(manifest.render ?? {}), + generatedBy: typeof manifest.generatedBy === "string" ? manifest.generatedBy : null, + view, + // `v`: the version of each window's bytes, for the media URLs (serve.mjs, "A REPLACED FILE IS A NEW FILE"). + windows: await Promise.all( + windows.map(async (w: { name: string; from: number; to: number; path: string }) => ({ + name: w.name, + from: w.from, + to: w.to, + v: await windowVersion(w), + })), + ), + proposed: entry.proposed ?? null, + endsSentence: entry.endsSentence ?? null, + noPunctuation: !!entry.noPunctuation, + sourceDuration: entry.duration ?? null, + segment: take ? null : (seg?.rel ?? entry.segment ?? null), + segmentMtime: seg?.mtimeMs ?? null, + // What the header would say with no overrides. Shown beside the fields that + // replace it, because "the archive says 2019" is the whole reason `date` + // exists. + sourceTitle: entry.sourceTitleClean ?? null, + uploadDate: entry.uploadDate ?? null, + sourceChannel: entry.sourceChannel ?? null, + prev: prev, + next: next, + index: order === "cut" ? ci + 1 : i + 1, + total: order === "cut" ? cutClips.length : clips.length, + // The OTHERS, so the bench can add this clip's own answer to the count + // without a reload and without knowing anything about the rest of the cut. + /** The walk's own reading: fetched clips that still need an answer. */ + ready: readiness.ready, + needing: readiness.needing, + /** Is there a cached file holding THIS clip's window, end to end? */ + fetched: !!entry.fetched, + reviewedOthers: clips.filter( + (e: { id: string }) => e.id !== clipId && clipVerdict(e) !== "unreviewed", + ).length, + cues: cues?.cues ?? [], + siblings: siblingsOf(manifest, clipId), + // The project's manifest token, or -- walking a take -- the take's. + token: walk.token, + fetchPad: manifest.render?.fetchPad ?? 3, + // The widest the fetch route will go. The BUTTON has to know it: it names + // the pad it will ask for, and "that is as wide as it goes" is a different + // sentence from a number the server quietly clamps. + maxPad: FETCH_MAX_PAD, + // The widest cached RAW window: it has no chrome burned in, which is what a + // mix is looking at, and it exists as soon as the clip has been fetched + // once. start/end are the window minus the file's own start, because a mix + // spec is relative to the file it names. + mixHref: widest + ? `/tools/mix?${new URLSearchParams({ + // The window's own path; see ReportProject — a window may live in + // the corpus rather than under out/clips-raw. + body: widest.path, + start: (entry.start - widest.from).toFixed(2), + end: (entry.end - widest.from).toFixed(2), + from: project.id, + clip: clipId, + })}` + : null, + }; + + // The piece this view belongs to: the article's when an article claims the project (P4a-2). + // Walking a take, Back is the take's walk (its overview), on the Takes page's side. + const back = take ? takeWalkHref(project.id, take, { all }) : await pieceHrefOfProject(project.id, { tab: "cut" }); + // ---- opened from Play the cut ("Edit this clip") -------------------------- + // + // `?from=play` rides every walk link from here (p / n / Confirm's advance), + // so "Back to the cut" survives walking on; `at` is only ever the clip Play + // was on. Back lands on the PROJECT's cut, positioned by clip id plus the + // offset into it -- never by raw cut seconds, which the edit just moved for + // everything after this clip. A take's render does not change when the + // project's manifest does, so a take's Back is the project's cut too, and + // the bench says so (`take`). + const fromPlay = !take && search.from === "play"; + const withOrder = (h: string) => (order === "cut" ? `${h}${h.includes("?") ? "&" : "?"}order=cut` : h); + const playTake = fromPlay && search.take ? search.take : null; + const atRaw = Number(search.at); + const at = fromPlay && Number.isFinite(atRaw) && atRaw > 0 ? atRaw : 0; + const href = (id: string) => + take ? takeClipHref(project.id, take, id, { all }) : withOrder(clipBenchHref(project.id, id, fromPlay ? { play: { take: playTake } } : {})); + data.walkHrefs = { + prev: prev ? href(prev) : null, + next: next ? href(next) : null, + back, + backLabel: take ? `take ${take}` : project.name, + }; + if (take && walk.take) { + const timeline = (manifest.timeline ?? []) as { id: string }[]; + data.take = { + id: take, + label: walk.take.label, + draft: walk.take.draft, + editable: walk.take.editable, + all, + takesHref: takesHref(project.id), + walkHref: takeWalkHref(project.id, take, { all }), + toggleAllHref: takeClipHref(project.id, take, clipId, { all: !all }), + clipHref: Object.fromEntries(data.siblings.map((sb: { id: string }) => [sb.id, takeClipHref(project.id, take, sb.id, { all })])), + at: timeline.findIndex((e) => e.id === clipId), + entries: timeline.length, + }; + } + data.fromPlay = fromPlay ? { href: playHref(project.id, { take: playTake, clip: clipId, at }), take: playTake } : null; + // Walk → Play (the audit's "no way back"): the cut, from this clip. + data.playHere = take || fromPlay ? null : playHref(project.id, { clip: clipId }); + // The working cut's name: the bench edits the project's manifest, the latest take is what it was made into. + data.working = take + ? null + : await readWorkingCut(project.dir, { resolveNow: async (id) => (await resolveTakeManifest(project.dir, id)).manifest }).catch(() => null); + const top: BenchTopSpec = { + trail: take ? [{ href: projectsHref(), label: "Projects" }, { href: takesHref(project.id), label: `${project.name} · takes` }] : [{ href: projectsHref(), label: "Projects" }], + back: { href: back, label: take ? `take ${take}` : project.name }, + kind: take ? "Take walk" : order === "cut" ? "Clip bench · the cut's order" : "Clip bench", + here: clipId, + // The walk on a phone draws its own place bar (ClipBench). + phone: "hidden", + // The head's slot: Back to the cut (from Play), or Play from here. + slot: fromPlay || !take, + pos: { index: order === "cut" ? ci + 1 : i + 1, total: order === "cut" ? cutClips.length : clips.length }, + prev: prev ? { href: href(prev), label: prev, attrs: { "data-clip-nav": "prev" } } : null, + next: next ? { href: href(next), label: next, attrs: { "data-clip-nav": "next" } } : null, + keys: [ + { keys: ["y"], label: "confirm" }, + { keys: ["x"], label: "note" }, + { keys: ["[", "]", ",", "."], label: "nudge" }, + { keys: ["space"], label: "play" }, + { keys: ["p", "n"], label: order === "cut" ? "the cut" : "walk" }, + ], + // Which source is playing. + note: `${entry.video}${entry.channel ? ` · ${entry.channel}` : ""}`, + }; + return { data, top }; +} + +/** clipBenchData, or the page's 404. */ +export async function clipBenchDataOr404(...args: Parameters<typeof clipBenchData>) { + const r = await clipBenchData(...args); + if (!r) notFound(); + return r; +} diff --git a/umtool/lib/report/citeFollow.mjs b/umtool/lib/report/citeFollow.mjs @@ -0,0 +1,182 @@ +// The cite follows the edge (UI notes 2026-10-30, #5). +// +// A clip's `cite` is the second the deck's clock prints, and its `citeUrl`'s +// `t=` is the second the QR opens. Both were written when the clip was found, +// against the window it had then. Tightening moved `start` and left them +// behind: on the Ember cut the clock and the QR ran up to 78 s early on 16 +// clips, and it was caught from a still. +// +// So the window writer (manifest.mjs patchClipEntry) moves them when an edge +// move leaves them outside what plays, and the check reports any left there +// (`clip-cite-off`, lib/projects/report.mjs). One rule, here, for both. +// +// A cite a few seconds BEFORE the clip is a lead-in, not a defect: the Ember +// cut cites up to 5 s ahead on purpose (the QR lands just before the line). +// More than CITE_LEAD_MAX before, or any second after the clip ends, names a +// moment the clip does not play. +// +// A citeUrl is ours to move only when it names THIS recording -- the archive's +// `?v=<channel>/<id>` (Twitch's record id is `v<id>`), or the platform's own +// `watch?v=<id>` / `youtu.be/<id>`. A mirror's clock is not this one's, so its +// `t=` is left as written and never judged. +// +// Plain ESM: the CLI runs it under bare node. + +/** Seconds a cite may sit before the clip and still be a lead-in. */ +export const CITE_LEAD_MAX = 5; +const EPS = 0.02; + +/** What plays: the cut when the clip has the pair (the build honours the pair or neither), else the extent. */ +export function playedSpan(e) { + const cs = Number(e?.cutStart); + const ce = Number(e?.cutEnd); + if (e?.cutStart != null && e?.cutEnd != null && Number.isFinite(cs) && Number.isFinite(ce)) return { from: cs, to: ce }; + return { from: Number(e?.start), to: Number(e?.end) }; +} + +/** The clock's second: `cite`, else the clip's start (attribution.mjs's rule). */ +export const clockOf = (e) => (e?.cite ?? e?.start ?? 0); + +/** + * Where a second sits against what plays: 0 inside (a lead-in of up to + * CITE_LEAD_MAX counts as inside), negative N when it is N s too early + * (measured from the clip's first played second), positive N when N s after + * the clip ends. + */ +export function offsetFrom(at, span, lead = CITE_LEAD_MAX) { + if (!Number.isFinite(at) || !Number.isFinite(span.from) || !Number.isFinite(span.to)) return 0; + if (at < span.from - lead - EPS) return -(span.from - at); + if (at > span.to + EPS) return at - span.to; + return 0; +} + +/** A `t=` value in seconds: `123`, `123.5`, `123s`, `1h2m3s`, `2m3s`; null when it is none of those. */ +export function parseT(raw) { + const s = String(raw ?? "").trim(); + if (/^\d+(\.\d+)?s?$/.test(s)) return Number(s.replace(/s$/, "")); + const m = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(s); + if (m && (m[1] || m[2] || m[3])) return Number(m[1] ?? 0) * 3600 + Number(m[2] ?? 0) * 60 + Number(m[3] ?? 0); + return null; +} + +/** Does `u` name the clip's own recording (so the same clock)? */ +export function sameRecording(u, e, channelSlug = null) { + const vid = String(e?.video ?? ""); + if (!vid) return false; + const chan = e?.channel ?? channelSlug; + const v = u.searchParams.get("v"); + if (v != null) { + if (chan && (v === `${chan}/${vid}` || v === `${chan}/v${vid}`)) return true; + if (v === vid) return true; + } + if (/(^|\.)youtu\.be$/.test(u.hostname) && u.pathname === `/${vid}`) return true; + return false; +} + +/** + * The second the clip's citeUrl opens, when it names this recording and + * carries a `t=`; null otherwise (no citeUrl, another recording, no `t`). + */ +export function citeUrlSecond(e, channelSlug = null) { + if (!e?.citeUrl) return null; + let u; + try { + u = new URL(String(e.citeUrl)); + } catch { + return null; + } + if (!u.searchParams.has("t")) return null; + if (!sameRecording(u, e, channelSlug)) return null; + return parseT(u.searchParams.get("t")); +} + +/** + * The citeUrl with its `t=` set to `sec` (whole seconds), keeping a `123s` + * spelling as `<sec>s`. A targeted edit rather than URLSearchParams: a + * re-serialised URL rewrites every other parameter's escaping and churns the + * manifest (resolve-windows.mjs retargetCiteUrl, the same reason). + */ +export function withT(citeUrl, sec) { + const n = Math.max(0, Math.floor(sec)); + return String(citeUrl).replace(/([?&]t=)(\d+(?:\.\d+)?)(s?)(?=&|#|$)|([?&]t=)[^&#]*/, (all, p1, _num, suffix, p4) => + p1 ? `${p1}${n}${suffix}` : `${p4}${n}`, + ); +} + +/** + * After an edge move: the `cite` and the citeUrl's `t=` the clip should carry, + * when either now lies outside what plays. Mutates nothing; returns null when + * both are fine. + * + * The new second is the clip's first played second, floored -- what the + * header shows for a clip with no `cite` at all, and the second a derived QR + * opens. A citeUrl moves to the (new) cite. + * + * @param {Record<string, any>} e the entry AFTER the window patch + * @param {{ channelSlug?: string | null }} [opts] + * @returns {null | { cite?: { from: number, to: number }, citeUrl?: { from: string, to: string } }} + */ +export function citeFollow(e, { channelSlug = null } = {}) { + const span = playedSpan(e); + if (!Number.isFinite(span.from) || !Number.isFinite(span.to)) return null; + const out = {}; + let clock = clockOf(e); + if (e.cite != null && offsetFrom(Number(e.cite), span) !== 0) { + const to = Math.floor(span.from); + out.cite = { from: Number(e.cite), to }; + clock = to; + } + const t = citeUrlSecond(e, channelSlug); + if (t != null && offsetFrom(t, span) !== 0) { + const to = withT(e.citeUrl, clock); + if (to !== e.citeUrl) out.citeUrl = { from: String(e.citeUrl), to }; + } + return out.cite || out.citeUrl ? out : null; +} + +/** + * After an explicit `cite` write: the citeUrl's `t=` follows when the two + * agreed before (the QR opened at the clock's whole second). One that said + * something else was somebody's decision and is left. + * + * @param {Record<string, any>} e the entry AFTER the patch + * @param {number} oldClock the clock's second BEFORE the patch + * @param {{ channelSlug?: string | null }} [opts] + * @returns {null | { citeUrl: { from: string, to: string } }} + */ +export function qrFollowsCite(e, oldClock, { channelSlug = null } = {}) { + const t = citeUrlSecond(e, channelSlug); + if (t == null || Math.floor(t) !== Math.floor(oldClock)) return null; + const to = withT(e.citeUrl, clockOf(e)); + return to !== e.citeUrl ? { citeUrl: { from: String(e.citeUrl), to } } : null; +} + +/** + * What the check says about one clip: where its clock and its QR (when the + * citeUrl is this recording's) sit against what plays, in signed seconds (see + * offsetFrom), and the patch that puts them back (`cite`, and `citeUrl` when + * it would not follow the cite by itself). Null when both are fine. + * + * A derived QR (no citeUrl) is not judged here: it opens at the extent's + * start, which is the material somebody reviewed. + * + * @param {Record<string, any>} e + * @param {{ channelSlug?: string | null }} [opts] + */ +export function citeOffsets(e, { channelSlug = null } = {}) { + const span = playedSpan(e); + if (!Number.isFinite(span.from) || !Number.isFinite(span.to)) return null; + const clock = clockOf(e); + const clockOff = e.cite != null ? offsetFrom(Number(clock), span) : 0; + const t = citeUrlSecond(e, channelSlug); + const qrOff = t != null ? offsetFrom(t, span) : 0; + if (!clockOff && !qrOff) return null; + const at = Math.floor(span.from); + /** @type {Record<string, unknown>} */ + const patch = {}; + if (clockOff) patch.cite = at; + // The writer moves the QR with an explicit cite only when they agreed. + const follows = clockOff && t != null && Math.floor(t) === Math.floor(clock); + if (qrOff && !follows) patch.citeUrl = withT(e.citeUrl, clockOff ? at : clock); + return { clockOff, qrOff, clock, qr: t, from: span.from, to: span.to, at, patch }; +} diff --git a/umtool/lib/report/clipDeck.ts b/umtool/lib/report/clipDeck.ts @@ -2,6 +2,7 @@ import { readFile } from "node:fs/promises"; import path from "node:path"; import { channelFor, readManifest } from "@/lib/projects/report.mjs"; import { listTakes, readVerdicts } from "@/lib/report/takes.mjs"; +import { latestWorkingTake } from "@/lib/report/workingCut.mjs"; import { clipMomentKey } from "umtool-report-to-video/montage-rulings"; import { earlierRulingsOffer, montageClipsOf, readRulingsState } from "@/lib/report/montageRulings.mjs"; import type { CitedTarget } from "@/lib/clips/types"; @@ -42,7 +43,7 @@ export type ClipCard = { extent: CitedTarget | null; }; -export type RerenderTarget = { take: string; label: string; builtAt: string | null; why: "picked" | "whole cut" }; +export type RerenderTarget = { take: string; label: string; builtAt: string | null; why: "latest" | "picked" | "whole cut" }; export type ClipDeckView = { cards: ClipCard[]; @@ -142,13 +143,23 @@ export async function clipDeckView(project: { id: string; dir: string }): Promis }); } - // The take "Re-render the take" makes again: the one picked, else the one - // whole-cut take; anything else is a choice the Takes page makes. - type T = { id: string; label: string; builtAt: string | null; window?: unknown; baseHash?: string | null }; + // The take "Re-render the take" makes again: the LATEST whole-cut take of the + // manifest (operator, 1 Nov 2026 -- the working cut's name, workingCut.mjs), + // else the one picked, else the one whole-cut take. It used to be the pick + // first, and with two whole-cut takes and none picked there was no target at + // all: "Choose a take to render", which only a pick unblocked. + type T = { id: string; label: string; builtAt: string | null; window?: unknown; baseHash?: string | null; order: number }; const made = (listing.takes as T[]).filter((t) => t.baseHash); + const latest = latestWorkingTake(listing.takes as Parameters<typeof latestWorkingTake>[0]) as T | null; const picked = made.filter((t) => (verdicts as Record<string, { picked?: true }>)[t.id]?.picked); const whole = made.filter((t) => t.window === "full"); - const target = picked.length === 1 ? { t: picked[0], why: "picked" as const } : picked.length === 0 && whole.length === 1 ? { t: whole[0], why: "whole cut" as const } : null; + const target = latest + ? { t: latest, why: "latest" as const } + : picked.length === 1 + ? { t: picked[0], why: "picked" as const } + : whole.length >= 1 + ? { t: [...whole].sort((a, b) => String(b.builtAt ?? "").localeCompare(String(a.builtAt ?? "")))[0], why: "whole cut" as const } + : null; const left = offer.rulings.filter((r: { ruling: { verdict: string } }) => r.ruling.verdict !== "keep").length; return { diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs @@ -31,6 +31,7 @@ import { StructureRefused, addClip, cutOf, + flashForward, manifestToken, mergeClips, restoreClip, @@ -343,6 +344,10 @@ const num = (v, what) => { * restore { clip } the assistant's version back * split { clip, at } two clips at that second * merge { clip } with the next clip + * flash-forward { clip, from, to, after? | section?, position?, move?, quote?, id? } + * a span copied elsewhere as a repeat (or + * moved out of the clip: `move`), its quote + * read from the words (manifest.mjs flashForward) * add { video, channel?, cutStart, cutEnd } a selection on the strip * bring-in { proposal } one of the clip finder's unused proposals * ruling { clip, verdict: "keep" | "cut" | null } @@ -413,6 +418,37 @@ export async function runClipEditorOp(project, body, { now = null } = {}) { case "merge": result = await mergeClips(dir, needClip().id, { token, now }); break; + case "flash-forward": { + // A span of this clip copied somewhere else in the cut (a repeat), or + // moved out of it (`move`): its quote read from the words, as a split's. + const e = needClip(); + const a = num(body.from, "from"); + const b = num(body.to, "to"); + const move = body.move === true; + const { cutStart, cutEnd } = cutOf(e); + const [quote, restQuote] = await Promise.all([ + typeof body.quote === "string" && body.quote.trim() ? body.quote : quoteFor(project, e.id, a, b), + move ? (Math.abs(a - cutStart) <= 0.5 ? quoteFor(project, e.id, b, cutEnd) : quoteFor(project, e.id, cutStart, a)) : Promise.resolve(""), + ]); + const section = body.section === undefined || body.section === null || body.section === "" ? null : Number(body.section); + result = await flashForward( + dir, + e.id, + { + from: a, + to: b, + after: typeof body.after === "string" ? body.after : null, + section, + position: body.position === "start" ? "start" : "end", + move, + ...(quote ? { quote } : {}), + ...(restQuote ? { restQuote } : {}), + ...(typeof body.id === "string" && body.id.trim() ? { id: body.id.trim() } : {}), + }, + { token }, + ); + break; + } case "add": { const video = typeof body.video === "string" ? body.video : entry?.video; const channel = typeof body.channel === "string" ? body.channel : entry ? channelFor(manifest, entry) : null; @@ -546,7 +582,7 @@ export async function runClipEditorOp(project, body, { now = null } = {}) { break; } default: - throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling, role, label, vertical, room, claim, marks, audio, blur or onscreen"); + throw new OpError("op must be trim, restore, split, merge, flash-forward, add, bring-in, ruling, role, label, vertical, room, claim, marks, audio, blur or onscreen"); } let carried = null; if (structural) { @@ -560,7 +596,7 @@ export async function runClipEditorOp(project, body, { now = null } = {}) { function summarise(r) { if (!isObj(r)) return null; const out = {}; - for (const k of ["id", "second", "absorbed", "at"]) if (r[k] !== undefined) out[k] = r[k]; + for (const k of ["id", "second", "absorbed", "at", "source", "move", "rest", "section", "earlier", "reanchored", "patches", "sectionPatches", "snapshot"]) if (r[k] !== undefined) out[k] = r[k]; if (isObj(r.entry) && typeof r.entry.id === "string") out.id ??= r.entry.id; if (isObj(r.speaker)) out.speaker = r.speaker; if (isObj(r.claim)) out.claim = r.claim; diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts @@ -121,4 +121,4 @@ export type Neighbourhood = { }; /** The take "Render a take" makes again (the clip deck's rule), or null: the Takes page chooses. */ -export type RenderTarget = { take: string; label: string; builtAt: string | null; why: "picked" | "whole cut" } | null; +export type RenderTarget = { take: string; label: string; builtAt: string | null; why: "latest" | "picked" | "whole cut" } | null; diff --git a/umtool/lib/report/cut-integrity.test.mjs b/umtool/lib/report/cut-integrity.test.mjs @@ -0,0 +1,494 @@ +// Cut integrity (UI notes 2026-10-30, #3 #5 #6 #7 #8): the cite follows the +// edge, a take patch's markers follow a removal, repeatOf / ★ / walk notes +// through the writer, and the QR links resolved against the site's contract. +// +// Run with: pnpm test:scripts +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 { citeFollow, citeOffsets, citeUrlSecond, offsetFrom, parseT, playedSpan, withT } from "./citeFollow.mjs"; +import { patchClipEntry, removeEntry, updateClip } from "./manifest.mjs"; +import { fixStalePatchMarkers, removedAnchors, reanchorPatch, stalePatchMarkers } from "./patchMarkers.mjs"; +import { archiveLinkOf, checkLinks, linkVerdicts, linksOf, runLinkCheck } from "./linkCheck.mjs"; +import { linksCommand, patchMarkersCommand } from "./linksCli.mjs"; +import { candidateBeats, trailerCandidates } from "./trailerCandidates.mjs"; +import { decisionsFor } from "../projects/core.mjs"; +import { walkProjects } from "../projects/walk.mjs"; + +const SITE = "https://site.test"; +const url = (chan, id, t) => `${SITE}/?v=${encodeURIComponent(`${chan}/${id}`)}&t=${t}`; + +// ---- citeFollow.mjs --------------------------------------------------------- + +test("the span that plays, offsets against it, t= spellings, the same recording", () => { + assert.deepEqual(playedSpan({ start: 10, end: 20 }), { from: 10, to: 20 }); + assert.deepEqual(playedSpan({ start: 10, end: 20, cutStart: 12, cutEnd: 18 }), { from: 12, to: 18 }); + // A lead-in of up to 5 s is inside; more is N s before; past the end is N s after. + assert.equal(offsetFrom(5, { from: 10, to: 20 }), 0); + assert.equal(offsetFrom(4, { from: 10, to: 20 }), -6); + assert.equal(offsetFrom(21, { from: 10, to: 20 }), 1); + assert.equal(parseT("123"), 123); + assert.equal(parseT("123s"), 123); + assert.equal(parseT("1m2s"), 62); + assert.equal(parseT("1h0m5s"), 3605); + assert.equal(parseT("soon"), null); + assert.equal(withT("https://a.test/?v=c%2Fx&t=12", 40), "https://a.test/?v=c%2Fx&t=40"); + assert.equal(withT("https://www.youtube.com/watch?v=abc&t=12s", 40.9), "https://www.youtube.com/watch?v=abc&t=40s"); + assert.equal(withT("https://www.youtube.com/watch?t=1m2s&v=abc", 70), "https://www.youtube.com/watch?t=70&v=abc"); + // Twitch: the corpus id is bare, the site's record is v<id> -- the same recording either way. + assert.equal(citeUrlSecond({ channel: "tw", video: "290", citeUrl: url("tw", "v290", 14) }), 14); + assert.equal(citeUrlSecond({ channel: "tw", video: "290", citeUrl: url("tw", "290", 14) }), 14); + assert.equal(citeUrlSecond({ video: "abc", citeUrl: "https://www.youtube.com/watch?v=abc&t=9s" }), 9); + assert.equal(citeUrlSecond({ video: "abc", citeUrl: "https://youtu.be/abc?t=9" }), 9); + // A mirror: another recording, another clock -- never judged. + assert.equal(citeUrlSecond({ channel: "c", video: "abc", citeUrl: url("mirror", "zzz", 9) }), null); +}); + +test("citeFollow: an edge past the cite moves it (and a same-recording QR); a lead-in or a mirror stays", () => { + const e = { channel: "c", video: "v1", start: 1600, end: 1620, cite: 1523, citeUrl: url("c", "v1", 1523) }; + assert.deepEqual(citeFollow(e), { cite: { from: 1523, to: 1600 }, citeUrl: { from: url("c", "v1", 1523), to: url("c", "v1", 1600) } }); + assert.equal(citeFollow({ ...e, cite: 1596, citeUrl: url("c", "v1", 1596) }), null, "4 s ahead is a lead-in"); + assert.deepEqual(citeFollow({ ...e, citeUrl: url("mirror", "m1", 10) }), { cite: { from: 1523, to: 1600 } }); + // The cut is what plays. + assert.deepEqual(citeFollow({ start: 100, end: 200, cutStart: 150, cutEnd: 160, cite: 100 })?.cite, { from: 100, to: 150 }); + // After the end. + assert.deepEqual(citeFollow({ start: 100, end: 110, cite: 130 })?.cite, { from: 130, to: 100 }); +}); + +test("citeOffsets: the row's numbers and the patch that settles it", () => { + const e = { channel: "c", video: "v1", start: 1600, end: 1620, cite: 1522, citeUrl: url("c", "v1", 1522) }; + const off = citeOffsets(e); + assert.equal(off.clockOff, -78); + assert.equal(off.qrOff, -78); + // The writer moves the QR with an explicit cite when they agreed: the patch is the cite alone. + assert.deepEqual(off.patch, { cite: 1600 }); + // QR off alone: the citeUrl is the patch. + const q = citeOffsets({ ...e, cite: 1601 }); + assert.deepEqual(q.patch, { citeUrl: url("c", "v1", 1601) }); + assert.equal(citeOffsets({ ...e, cite: 1598, citeUrl: url("c", "v1", 1598) }), null); +}); + +// ---- the window writer -------------------------------------------------------- + +const manifestOf = (timeline, extra = {}) => ({ + schemaVersion: 1, + slug: "cut", + title: "Cut", + provenance: { channelSlug: "c", siteOrigin: SITE }, + render: { width: 1920, height: 1080, fps: 30 }, + timeline, + ...extra, +}); + +test("the writer: an edge move carries the cite and the QR along; a lead-in is kept; an explicit cite takes the QR with it", () => { + const clip = () => ({ type: "clip", id: "a", channel: "c", video: "v1", start: 1500, end: 1620, cite: 1523, citeUrl: url("c", "v1", 1523) }); + let m = manifestOf([clip()]); + const r = patchClipEntry(m, "a", { start: 1601.2 }); + assert.equal(m.timeline[0].cite, 1601); + assert.equal(m.timeline[0].citeUrl, url("c", "v1", 1601)); + assert.deepEqual(r.citeFollowed, { cite: { from: 1523, to: 1601 }, citeUrl: { from: url("c", "v1", 1523), to: url("c", "v1", 1601) } }); + + m = manifestOf([clip()]); + assert.equal(patchClipEntry(m, "a", { start: 1527 }).citeFollowed, null); + assert.equal(m.timeline[0].cite, 1523, "4 s of lead-in stays"); + + // A cut that moves past the cite carries it too. + m = manifestOf([clip()]); + patchClipEntry(m, "a", { cutStart: 1560, cutEnd: 1600 }); + assert.equal(m.timeline[0].cite, 1560); + + // An explicit cite: the QR follows because it agreed with the clock. + m = manifestOf([clip()]); + assert.deepEqual(patchClipEntry(m, "a", { cite: 1540 }).citeFollowed, { citeUrl: { from: url("c", "v1", 1523), to: url("c", "v1", 1540) } }); + assert.equal(m.timeline[0].citeUrl, url("c", "v1", 1540)); + // ...and not when it said something else. + m = manifestOf([{ ...clip(), citeUrl: url("c", "v1", 1510) }]); + patchClipEntry(m, "a", { cite: 1540 }); + assert.equal(m.timeline[0].citeUrl, url("c", "v1", 1510)); + + // A patch that writes citeUrl keeps exactly what it wrote; the cite still follows. + m = manifestOf([clip()]); + patchClipEntry(m, "a", { start: 1601, citeUrl: url("c", "v1", 1400) }); + assert.equal(m.timeline[0].citeUrl, url("c", "v1", 1400)); + assert.equal(m.timeline[0].cite, 1601); + + // No cite: the clock is the start already; a QR left behind still follows. + m = manifestOf([{ type: "clip", id: "b", channel: "c", video: "v2", start: 10, end: 90, citeUrl: url("c", "v2", 10) }]); + patchClipEntry(m, "b", { start: 40 }); + assert.equal("cite" in m.timeline[0], false); + assert.equal(m.timeline[0].citeUrl, url("c", "v2", 40)); +}); + +test("the writer: walkNote and star -- set, cleared, refused", () => { + const m = manifestOf([{ type: "clip", id: "a", video: "v1", start: 1, end: 9 }]); + patchClipEntry(m, "a", { walkNote: " THIS IS GOLD ", star: true }); + assert.equal(m.timeline[0].walkNote, "THIS IS GOLD"); + assert.equal(m.timeline[0].star, true); + assert.equal("correction" in m.timeline[0], false, "a walk note is not a correction"); + assert.equal("verdict" in m.timeline[0], false, "nor a verdict"); + patchClipEntry(m, "a", { walkNote: "", star: false }); + assert.equal("walkNote" in m.timeline[0], false); + assert.equal("star" in m.timeline[0], false); + patchClipEntry(m, "a", { star: "true" }); + assert.equal(m.timeline[0].star, true); + assert.throws(() => patchClipEntry(m, "a", { star: "maybe" }), /star must be true or false/); +}); + +// ---- take patches follow a removal ------------------------------------------ + +test("removedAnchors / reanchorPatch: the same boundary, or dropped; a patch with its own timeline is left", () => { + const before = [{ type: "clip", id: "a" }, { type: "card", id: "k" }, { type: "clip", id: "b" }, { type: "clip", id: "c" }]; + const after = [{ type: "clip", id: "a" }, { type: "card", id: "k" }, { type: "clip", id: "c" }]; + assert.deepEqual([...removedAnchors(before, after)], [["b", "a"]]); + assert.deepEqual([...removedAnchors(before, before.slice(1))], [["a", null]]); + const patch = { render: { chrome: { deck: { markers: [{ after: "b", label: "Sex appeal" }, { after: "c" }] } } } }; + assert.deepEqual(reanchorPatch(patch, new Map([["b", "a"]])), ['deck marker 0 ("Sex appeal") moved from after b to after a (the same boundary)']); + assert.equal(patch.render.chrome.deck.markers[0].after, "a"); + const own = { timeline: [], render: { chrome: { deck: { markers: [{ after: "b" }] } } } }; + assert.deepEqual(reanchorPatch(own, new Map([["b", "a"]])), []); +}); + +async function project(timeline, { files = {}, render = {} } = {}) { + const root = await mkdtemp(path.join(tmpdir(), "cut-integrity-")); + const channelsDir = path.join(root, "channels"); + const reportsRoot = path.join(root, "reports"); + for (const v of ["v1", "v2"]) { + const vdir = path.join(channelsDir, "c", "data", v); + await mkdir(vdir, { recursive: true }); + const cues = Array.from({ length: 2000 }, (_, i) => ({ start: i, end: i + 1, text: `Line ${i}.` })); + await writeFile(path.join(vdir, "transcript.cues.json"), JSON.stringify({ cues })); + } + const dir = path.join(reportsRoot, "cut"); + await mkdir(dir, { recursive: true }); + const m = manifestOf( + timeline.map((e) => ({ type: "clip", channel: "c", video: "v1", lock: true, ...e })), + { render: { width: 1920, height: 1080, fps: 30, ...render } }, + ); + m.provenance.channelsDir = path.relative(dir, channelsDir); + await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(m, null, 2)}\n`); + for (const [name, doc] of Object.entries(files)) await writeFile(path.join(dir, name), typeof doc === "string" ? doc : `${JSON.stringify(doc, null, 2)}\n`); + const decisions = async () => { + const [ref] = (await walkProjects(reportsRoot)).filter((p) => p.id === "cut"); + return decisionsFor(ref, reportsRoot); + }; + return { root, reportsRoot, dir, decisions, done: () => rm(root, { recursive: true, force: true }) }; +} + +const markersRender = (markers) => ({ chrome: { engine: "hyperframes", layout: "deck", deck: { markers } } }); + +test("removing a clip re-anchors the take patches beside the manifest; the check names what is still stale", async () => { + const p = await project( + [{ id: "a", start: 10, end: 20 }, { id: "b", start: 30, end: 40 }, { id: "c", start: 50, end: 60 }], + { + render: markersRender([{ after: "b", label: "Two" }]), + files: { + "draft-1.patch.json": { render: { chrome: { deck: { markers: [{ after: "b", label: "Two" }, { after: "c", label: "Three" }] } } } }, + "own.patch.json": { timeline: [{ type: "clip", id: "x", video: "v1", start: 1, end: 2 }], render: { chrome: { deck: { markers: [{ after: "b" }] } } } }, + "hand.patch.json": { render: { chrome: { deck: { markers: [{ after: "gone", label: "Hand" }] } } } }, + }, + }, + ); + try { + const res = await removeEntry(p.dir, "b"); + assert.deepEqual(res.patches, [{ file: "draft-1.patch.json", notes: ['deck marker 0 ("Two") moved from after b to after a (the same boundary)'] }]); + const patch = JSON.parse(await readFile(path.join(p.dir, "draft-1.patch.json"), "utf8")); + assert.deepEqual(patch.render.chrome.deck.markers, [{ after: "a", label: "Two" }, { after: "c", label: "Three" }]); + // A patch with a timeline of its own names its own clips: untouched. + const own = JSON.parse(await readFile(path.join(p.dir, "own.patch.json"), "utf8")); + assert.equal(own.render.chrome.deck.markers[0].after, "b"); + // The manifest's own markers moved the same way. + const m = JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + assert.equal(m.render.chrome.deck.markers[0].after, "a"); + // What is still stale: the hand-written one. + assert.deepEqual(await stalePatchMarkers(p.dir, m), [{ file: "hand.patch.json", markers: [{ index: 0, label: "Hand", after: "gone" }] }]); + const rows = (await p.decisions()).filter((d) => d.kind === "patch-markers-stale"); + assert.equal(rows.length, 1); + assert.equal(rows[0].target, "hand.patch.json"); + assert.equal(rows[0].severity, "open"); + assert.match(rows[0].why, /"Hand" after gone — a take made with --patch hand.patch.json is refused/); + } finally { + await p.done(); + } +}); + +test("Take the cut's markers: a stale patch marker takes the cut's marker of the same label; an unmatched one is left and named", async () => { + const p = await project( + [{ id: "a", start: 10, end: 20 }, { id: "b", start: 30, end: 40 }], + { + render: markersRender([{ after: "a", label: "Sex appeal" }]), + files: { "draft-1.patch.json": { render: { chrome: { deck: { markers: [{ after: "ow2b", label: "Sex appeal", color: "#e070d0" }, { after: "zz", label: "Nobody" }] } } } } }, + }, + ); + try { + const rows = (await p.decisions()).filter((d) => d.kind === "patch-markers-stale"); + assert.deepEqual(rows[0].settle, { kind: "patch-markers", file: "draft-1.patch.json", label: "Take the cut's markers" }); + assert.match(rows[0].fix, /^umtool patch-markers cut draft-1.patch.json --fix/); + const lines = []; + const code = await patchMarkersCommand(["cut", "--fix"], { root: p.reportsRoot, out: (s) => lines.push(s), err: (s) => lines.push(s) }); + assert.equal(code, 1, "one is left"); + assert.deepEqual(lines, [ + `draft-1.patch.json: deck marker 0 ("Sex appeal") moved from after ow2b to after a, where the cut's "Sex appeal" is`, + `draft-1.patch.json: "Nobody" is after zz, which is not in the cut`, + ]); + const patch = JSON.parse(await readFile(path.join(p.dir, "draft-1.patch.json"), "utf8")); + assert.deepEqual(patch.render.chrome.deck.markers[0], { after: "a", label: "Sex appeal", color: "#e070d0" }); + const m = JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + assert.deepEqual((await fixStalePatchMarkers(p.dir, m, "draft-1.patch.json")).left, [{ index: 1, label: "Nobody", after: "zz" }]); + await assert.rejects(fixStalePatchMarkers(p.dir, m, "../video.manifest.json"), /not a take patch/); + } finally { + await p.done(); + } +}); + +// ---- the check rows ------------------------------------------------------------ + +test("clip-cite-off: the clock and the QR N s before the clip, with the settle and the fix", async () => { + const p = await project([ + { id: "ag0", start: 1600, end: 1610, cite: 1522, citeUrl: url("c", "v1", 1522) }, + { id: "ok1", video: "v2", start: 100, end: 110, cite: 97, citeUrl: url("c", "v2", 97) }, + ]); + try { + const rows = (await p.decisions()).filter((d) => d.kind === "clip-cite-off"); + assert.equal(rows.length, 1); + const [r] = rows; + assert.equal(r.target, "ag0"); + assert.equal(r.severity, "open"); + assert.equal(r.why, "the clock and the QR point 78 s before the clip (cite 25:22, it plays 26:40–26:50)"); + assert.deepEqual(r.settle, { kind: "patch", clip: "ag0", patch: { cite: 1600 }, label: "Move to 26:40" }); + assert.equal(r.fix, "umtool window cut ag0 --cite 1600"); + // Settling it through the writer clears the row, and the QR followed. + const res = await updateClip(p.dir, "ag0", r.settle.patch); + assert.equal(res.entry.citeUrl, url("c", "v1", 1600)); + assert.equal((await p.decisions()).filter((d) => d.kind === "clip-cite-off").length, 0); + } finally { + await p.done(); + } +}); + +test("window-overlap offers It's deliberate: the later clip repeats the earlier; the writer clears the row", async () => { + const p = await project([ + { id: "tr3", start: 100, end: 140, cite: 100 }, + { id: "x", video: "v2", start: 10, end: 20, cite: 10 }, + { id: "tr3z", start: 120, end: 130, cite: 120 }, + ]); + try { + const rows = (await p.decisions()).filter((d) => d.kind === "window-overlap"); + assert.equal(rows.length, 1); + assert.deepEqual(rows[0].settle, { kind: "patch", clip: "tr3z", patch: { repeatOf: "tr3" }, label: "It's deliberate: tr3z repeats tr3" }); + assert.match(rows[0].fix, /^umtool window cut tr3z --repeat-of tr3/); + await updateClip(p.dir, "tr3z", rows[0].settle.patch); + assert.equal((await p.decisions()).filter((d) => d.kind === "window-overlap").length, 0); + } finally { + await p.done(); + } +}); + +// ---- the link check -------------------------------------------------------------- + +/** A published site: corpus.json, one channel's manifest and pages, counting what is asked. */ +function fakeSite({ channels = { c: { v1: 0, v2: 1 }, tw: { v290: 0 } }, down = false, emptyPage = null } = {}) { + const asked = []; + const pages = {}; + for (const [chan, ids] of Object.entries(channels)) { + for (const [id, n] of Object.entries(ids)) (pages[`${chan}/${n}`] ??= []).push({ id, title: id }); + } + const fetchImpl = async (u) => { + asked.push(String(u)); + if (down) throw new TypeError("fetch failed", { cause: new Error("getaddrinfo ENOTFOUND site.test") }); + const p = new URL(String(u)).pathname; + const json = (doc) => ({ ok: true, status: 200, json: async () => doc }); + if (p === "/corpus.json") { + return json({ + spec: 5, generatedAt: "2026-10-09T10:00:00.000Z", site: { title: "Site" }, + channels: Object.keys(channels).map((slug) => ({ slug, manifests: { transcripts: `${SITE}/transcripts/${slug}/manifest.json` } })), + }); + } + const m = /^\/transcripts\/([^/]+)\/(manifest\.json|page-(\d{4})\.json)$/.exec(p); + if (m && m[2] === "manifest.json") return json({ pageCount: 2, slugToPage: Object.fromEntries(Object.entries(channels[m[1]] ?? {})) }); + if (m && m[3]) { + const key = `${m[1]}/${Number(m[3])}`; + // A deploy whose shard lacks a record its slugToPage promises. + if (emptyPage === key) return json([]); + return json(pages[key] ?? []); + } + return { ok: false, status: 404, json: async () => ({}) }; + }; + return { fetchImpl, asked }; +} + +test("archiveLinkOf / linksOf: the build's own QR links; a platform link is not an archive link", () => { + assert.deepEqual(archiveLinkOf(url("tw", "v290", 14)), { origin: SITE, channel: "tw", id: "v290", t: "14" }); + assert.equal(archiveLinkOf("https://www.youtube.com/watch?v=abc&t=9s"), null); + const m = manifestOf([ + { type: "clip", id: "a", video: "v1", start: 10, end: 20 }, + { type: "clip", id: "b", video: "v2", start: 10, end: 20, citeUrl: "https://www.youtube.com/watch?v=v2&t=10s" }, + ]); + assert.deepEqual(linksOf(m), [ + { clip: "a", url: `${SITE}/?v=${encodeURIComponent("c/v1")}&t=10` }, + { clip: "b", url: "https://www.youtube.com/watch?v=v2&t=10s" }, + ]); +}); + +test("checkLinks: open, a channel not on the site, the bare Twitch id (with its fix), a stale cached shard, one request per URL", async () => { + const cacheDir = await mkdtemp(path.join(tmpdir(), "links-cache-")); + try { + const site = fakeSite(); + const links = [ + { clip: "a", url: url("c", "v1", 10) }, + { clip: "a2", url: url("c", "v1", 30) }, + { clip: "b", url: url("c", "v2", 10) }, + { clip: "q01", url: url("tw", "290", 14538) }, + { clip: "n1", url: url("nochan", "x", 1) }, + { clip: "gone", url: url("c", "v9", 1) }, + { clip: "yt", url: "https://www.youtube.com/watch?v=abc&t=9s" }, + ]; + const doc = await checkLinks(links, { fetchImpl: site.fetchImpl, cacheDir, now: () => new Date("2026-11-01T01:00:00Z"), gapMs: 0 }); + const by = Object.fromEntries(doc.links.map((l) => [l.clip, l])); + assert.equal(by.a.state, "ok"); + assert.equal(by.a2.state, "ok"); + assert.equal(by.b.state, "ok"); + assert.equal(by.q01.state, "dead"); + assert.equal(by.q01.why, `"290" is not a record on site.test; the site's record is "v290"`); + assert.equal(by.q01.fix, url("tw", "v290", 14538)); + assert.equal(by.n1.state, "dead"); + assert.match(by.n1.why, /the channel "nochan" is not on site\.test \(its deploy of 2026-10-09\)/); + assert.equal(by.gone.state, "dead"); + assert.match(by.gone.why, /"v9" is not published in c on site\.test \(deployed 2026-10-09\)/); + assert.equal(by.yt.state, "direct"); + assert.equal(doc.origins[SITE].state, "ok"); + // Polite: corpus.json once, each manifest once, each page once (+1 for the stale one). + const count = (s) => site.asked.filter((u) => u.endsWith(s)).length; + assert.equal(count("/corpus.json"), 1); + assert.equal(count("/c/manifest.json"), 1); + assert.equal(count("/c/page-0000.json"), 1); + assert.equal(count("/c/page-0001.json"), 1); + // A second check reads shards from the cache: only the contract is asked again. + const again = fakeSite(); + await checkLinks(links.slice(0, 3), { fetchImpl: again.fetchImpl, cacheDir, gapMs: 0 }); + assert.deepEqual(again.asked.map((u) => new URL(u).pathname), ["/corpus.json", "/transcripts/c/manifest.json"]); + } finally { + await rm(cacheDir, { recursive: true, force: true }); + } +}); + +test("checkLinks: a shard that lacks its record is inconsistent; a cached copy older than the deploy is read again, once", async () => { + const cacheDir = await mkdtemp(path.join(tmpdir(), "links-cache-")); + try { + const broken = fakeSite({ emptyPage: "c/1" }); + const one = await checkLinks([{ clip: "b", url: url("c", "v2", 10) }], { fetchImpl: broken.fetchImpl, cacheDir, gapMs: 0 }); + assert.equal(one.links[0].state, "dead"); + assert.match(one.links[0].why, /slugToPage puts "v2" on page 1, but no record there has that id/); + // Fetched from the network this check: never asked twice in one check. + assert.equal(broken.asked.filter((u) => u.endsWith("/page-0001.json")).length, 1); + // Redeployed: the cached shard misses, so it is read again -- once. + const fixed = fakeSite(); + const two = await checkLinks([{ clip: "b", url: url("c", "v2", 10) }], { fetchImpl: fixed.fetchImpl, cacheDir, gapMs: 0 }); + assert.equal(two.links[0].state, "ok"); + assert.deepEqual(fixed.asked.map((u) => new URL(u).pathname), ["/corpus.json", "/transcripts/c/manifest.json", "/transcripts/c/page-0001.json"]); + } finally { + await rm(cacheDir, { recursive: true, force: true }); + } +}); + +test("checkLinks offline: every link unverified, with couldn't reach; the rows say so, and a dead link blocks", async () => { + const cacheDir = await mkdtemp(path.join(tmpdir(), "links-cache-")); + const p = await project([ + { id: "a", start: 10, end: 20, cite: 10 }, + { id: "q01", start: 30, end: 40, cite: 30, citeUrl: url("tw", "290", 30) }, + ]); + try { + // Never checked. + let rows = (await p.decisions()).filter((d) => d.kind.startsWith("link")); + assert.deepEqual(rows.map((d) => [d.kind, d.severity, d.why]), [["links-unchecked", "info", "2 archive links never checked against the sites they open"]]); + assert.deepEqual(rows[0].settle, { kind: "check-links", label: "Check links" }); + assert.equal(rows[0].fix, "umtool links cut"); + + const m = JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + const off = await runLinkCheck(p.dir, m, { fetchImpl: fakeSite({ down: true }).fetchImpl, cacheDir, gapMs: 0 }); + assert.ok(off.links.every((l) => l.state === "unverified")); + assert.equal(off.origins[SITE].state, "unreachable"); + rows = (await p.decisions()).filter((d) => d.kind.startsWith("link")); + assert.equal(rows.length, 1); + assert.equal(rows[0].kind, "links-unverified"); + assert.equal(rows[0].severity, "info"); + assert.match(rows[0].why, /^2 links not verified on .* — couldn't reach site\.test \(fetch failed \(getaddrinfo ENOTFOUND site\.test\)\)$/); + + // Online: q01's bare Twitch id is dead, and that blocks. + await runLinkCheck(p.dir, m, { fetchImpl: fakeSite().fetchImpl, cacheDir, gapMs: 0 }); + rows = (await p.decisions()).filter((d) => d.kind.startsWith("link")); + assert.deepEqual(rows.map((d) => [d.kind, d.severity, d.target]), [["link-dead", "blocking", "site.test"]]); + assert.match(rows[0].why, /^1 of 2 QR links don't open on site\.test \(deployed 2026-10-09\): q01 — q01: "290" is not a record on site\.test; the site's record is "v290"\. Every clip with a fix: `umtool links cut --fix`$/); + assert.deepEqual(rows[0].clips, ["q01"]); + assert.deepEqual(rows[0].settle, { kind: "check-links", fix: true, label: "Fix 1 link (the site's v<id>)" }); + assert.equal(rows[0].fix, "umtool links cut --fix"); + + // A link changed since the check is unchecked, not judged by the old answer. + await updateClip(p.dir, "a", { citeUrl: url("c", "v2", 10) }); + const v = linkVerdicts(JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")), JSON.parse(await readFile(path.join(p.dir, "out", "links.json"), "utf8"))); + assert.deepEqual(v.unchecked.map((l) => l.clip), ["a"]); + } finally { + await p.done(); + await rm(cacheDir, { recursive: true, force: true }); + } +}); + +test("umtool links --fix: the dead link with a known fix rewritten through the writer, then checked again", async () => { + const cacheDir = await mkdtemp(path.join(tmpdir(), "links-cache-")); + const p = await project([{ id: "q01", start: 30, end: 40, cite: 30, citeUrl: url("tw", "290", 30) }]); + try { + const lines = []; + const code = await linksCommand(["cut", "--fix"], { root: p.reportsRoot, out: (s) => lines.push(s), err: (s) => lines.push(s), fetchImpl: fakeSite().fetchImpl, cacheDir, gapMs: 0 }); + assert.equal(code, 0, lines.join("\n")); + assert.match(lines.find((l) => l.startsWith("fixed ")) ?? "", /^fixed q01: .*%2F290&t=30 -> .*%2Fv290&t=30$/); + const m = JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + assert.equal(m.timeline[0].citeUrl, url("tw", "v290", 30)); + assert.equal((await p.decisions()).filter((d) => d.kind.startsWith("link")).length, 0); + } finally { + await p.done(); + await rm(cacheDir, { recursive: true, force: true }); + } +}); + +test("checkLinks paces one host: at least the gap between two requests, nothing waited on a cache hit", async () => { + const cacheDir = await mkdtemp(path.join(tmpdir(), "links-cache-")); + try { + const waits = []; + let clock = 0; + const realNow = Date.now; + Date.now = () => clock; + try { + const sleep = async (ms) => { + waits.push(ms); + clock += ms; + }; + await checkLinks([{ clip: "a", url: url("c", "v1", 10) }, { clip: "b", url: url("c", "v2", 10) }], { fetchImpl: fakeSite().fetchImpl, cacheDir, gapMs: 3000, sleep }); + // corpus, manifest, page 0, page 1: three gaps, each ≥ 3 s and < 3.75 s (upward jitter only). + assert.equal(waits.length, 3); + for (const w of waits) assert.ok(w >= 3000 && w < 3750, String(w)); + waits.length = 0; + await checkLinks([{ clip: "a", url: url("c", "v1", 10) }], { fetchImpl: fakeSite().fetchImpl, cacheDir, gapMs: 3000, sleep }); + assert.equal(waits.length, 1, "corpus.json and the manifest: one gap; the shard is a cache hit"); + } finally { + Date.now = realNow; + } + } finally { + await rm(cacheDir, { recursive: true, force: true }); + } +}); + +// ---- ★ trailer candidates ------------------------------------------------------- + +test("trailerCandidates: the starred clips in the cut's order, over what each plays; a rejected one is left out", () => { + const m = manifestOf([ + { type: "clip", id: "j01", video: "v", start: 3335.1, end: 3337.14, star: true, quote: "anime girl", walkNote: "GOLD" }, + { type: "clip", id: "b01", video: "v", start: 10, end: 30 }, + { type: "clip", id: "tr3", video: "v", start: 2980, end: 3020, cutStart: 2988.36, cutEnd: 3011.2, star: true }, + { type: "clip", id: "z", video: "v", start: 1, end: 2, star: true, verdict: "rejected", reason: "weak" }, + ]); + assert.deepEqual(trailerCandidates(m).map((b) => b.id), ["j01", "tr3"]); + assert.deepEqual(candidateBeats(m), [{ id: "j01", start: 3335.1, end: 3337.14 }, { id: "tr3", start: 2988.36, end: 3011.2 }]); + assert.equal(trailerCandidates(m)[0].walkNote, "GOLD"); +}); diff --git a/umtool/lib/report/delete.mjs b/umtool/lib/report/delete.mjs @@ -29,6 +29,7 @@ import { lstat, readFile, readdir, readlink, realpath, rm, rmdir } from "node:fs import path from "node:path"; import { MEDIA_ROOT, REPORTS_ROOT, inside } from "../paths.mjs"; import { isTakeId, takesDirOf } from "./takes.mjs"; +import { renderHolds } from "./takeHousekeeping.mjs"; const strictlyInside = (root, p) => p !== root && inside(root, p); @@ -278,6 +279,9 @@ export async function planTakeDelete(project, takeId, opts = {}) { const place = await placeProblem(project.dir, roots, "the project"); if (place) refusals.push({ reason: place, forceable: false }); if (opts.busyJob) refusals.push({ reason: `${opts.busyJob} is working in ${project.id}: wait for it, or cancel it`, forceable: false }); + // What a running render names (a `umtool take` from a terminal is no job of + // the app's): the take rendering, or the base a render is made from. + for (const why of await renderHolds(project.dir, takeId)) refusals.push({ reason: `take ${takeId}: ${why}`, forceable: false }); const [mine, theirs] = await Promise.all([ readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, "video.manifest.json"), "utf8").catch(() => null), readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"), "utf8").catch(() => null), diff --git a/umtool/lib/report/knobs.test.mjs b/umtool/lib/report/knobs.test.mjs @@ -127,6 +127,40 @@ test("updateClip: a window that leaves claim.at outside is refused", async () => await updateClip(dir, "c02", { start: 30.5 }); }); +test("updateClip: the refusal carries the fixes, and markFix / muteFix apply one in the same write", async () => { + const dir = await project(); + await updateClaimKnobs(dir, "c02", { at: 31 }); + // The refusal: a MarksOutside naming the second and where each fix would put it. + const err = await updateClip(dir, "c02", { start: 32.5, end: 39 }).catch((e) => e); + assert.equal(err.name, "MarksOutside"); + assert.equal(err.kind, "mark"); + assert.deepEqual(err.window, { start: 32.5, end: 39 }); + assert.deepEqual(err.marks, [{ index: null, id: err.marks[0].id, at: 31, first: 32.5, nearest: 32.5 }]); + // Moved to the first second that plays, in the one write that also trims. + const before = await readRaw(dir); + const r = await updateClip(dir, "c02", { start: 32.5, end: 39, markFix: "first" }); + assert.equal(r.entry.start, 32.5); + assert.equal(clip(await read(dir), "c02").claim.at, 32.5); + assert.notEqual(await readRaw(dir), before); + // A named second; then clear: the stamp keeps its verdict, loses its second. + await updateClaimKnobs(dir, "c02", { at: 33 }); + await updateClip(dir, "c02", { start: 34, markFix: 35.25 }); + assert.equal(clip(await read(dir), "c02").claim.at, 35.25); + await updateClip(dir, "c02", { start: 36, markFix: "clear" }); + assert.equal("at" in clip(await read(dir), "c02").claim, false); + assert.ok(clip(await read(dir), "c02").claim.verdict, "the stamp is still there"); + // A bad fix is refused in words. + await updateClaimKnobs(dir, "c02", { at: 36.5 }); + await assert.rejects(updateClip(dir, "c02", { start: 37, markFix: "later" }), /markFix is first, nearest, clear or a source second/); + // The mute mark: refused with its fixes, then moved to the nearest second the clip plays. + await updateClip(dir, "c02", { start: 36, muteFrom: 38.5, markFix: "nearest" }); + const m = await updateClip(dir, "c02", { end: 37.5 }).catch((e) => e); + assert.equal(m.name, "MarksOutside"); + assert.equal(m.kind, "mute"); + await updateClip(dir, "c02", { end: 37.5, muteFix: "nearest" }); + assert.equal(clip(await read(dir), "c02").muteFrom, 37.5); +}); + test("updateFactcheck: stamp scale, motion, opacity and a verdict's stampLabel; refused out of range", async () => { const dir = await project(); const r = await updateFactcheck(dir, { stamp: { scale: 1.4, motion: "pop", opacity: 0.8 }, verdicts: { CONTRADICTED: { label: "Seizures", stampLabel: "SEIZURE" } } }, { token: await manifestToken(dir) }); diff --git a/umtool/lib/report/linkCheck.mjs b/umtool/lib/report/linkCheck.mjs @@ -0,0 +1,296 @@ +// Do the cut's QR links open? (UI notes 2026-10-30, #8) +// +// On the Ember cut the Twitch links used the bare id, which the site does not +// open (its record is `v<id>`), and anilyzer's deploy was three weeks old with +// no Ember channels at all -- so most QRs were dead in drafts 1–11, and the +// fix took a headless browser. This resolves every clip's QR against the +// target site's own published contract instead: +// +// corpus.json -> channels[].manifests.transcripts -> slugToPage[<id>] +// -> page-<NNNN>.json (zero-padded to 4) -> the record whose id is <id> +// +// (report-to-video/cues.mjs walks the same contract for cues, through the same +// on-disk JSON cache, so a shard the build already read is not fetched again.) +// +// POLITE: one request at a time per host, at least LINK_GAP_MS apart (jittered +// upward, common/lib/jitter.mjs -- the operator's "≥3 s between metadata +// requests, one stream per host"), each URL at most once per check. corpus.json +// and the channel manifests are re-read every check (a deploy changes them); +// a shard page is read from the cache, and fetched again only when the record +// slugToPage promised is not in the cached copy. +// +// OFFLINE: a site that does not answer is a state, not an error -- its links +// are `unverified` with the reason, and the check row says "couldn't reach". +// +// The result is RECORDED (out/links.json), like the availability preflight's: +// the decisions reducer reads it and never fetches (lib/projects/report.mjs). +// +// Plain ESM: the CLI runs it under bare node. +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { createJsonCache, DEFAULT_CACHE_DIR, pageUrlFrom } from "umtool-report-to-video/cues"; +import { qrsOf } from "umtool-report-to-video/lint"; +import { jitterUp } from "yt-dlp-transcript-common/lib/jitter.mjs"; + +export const LINKS_FILE = "links.json"; +export const linksFile = (dir) => path.join(dir, "out", LINKS_FILE); +const FETCH_TIMEOUT_MS = 20_000; +/** The floor between two requests to one host (a cache hit asks nothing and waits for nothing). */ +export const LINK_GAP_MS = 3000; + +/** + * An archive viewer link's parts: `<origin>/?v=<channel>/<id>&t=…`, or null + * for anything else (a platform's own page, a mirror) -- which this check + * does not judge. + * + * @param {string} url + * @returns {null | { origin: string, channel: string, id: string, t: string | null }} + */ +export function archiveLinkOf(url) { + let u; + try { + u = new URL(String(url)); + } catch { + return null; + } + if (u.protocol !== "http:" && u.protocol !== "https:") return null; + const v = u.searchParams.get("v"); + if (!v || !v.includes("/")) return null; + const cut = v.indexOf("/"); + const channel = v.slice(0, cut); + const id = v.slice(cut + 1); + if (!channel || !id) return null; + return { origin: u.origin, channel, id, t: u.searchParams.get("t") }; +} + +/** + * Every clip QR the cut draws, `{ clip, url }`, by the build's own rules + * (lint.mjs qrsOf: a clip's citeUrl, else its archive moment; none when the + * cut draws no code). + * + * @param {Record<string, any>} m + */ +export function linksOf(m) { + const clips = new Set((m?.timeline ?? []).filter((e) => e?.type === "clip").map((e) => e.id)); + let qrs = []; + try { + qrs = qrsOf(m); + } catch { + qrs = []; + } + const out = []; + const seen = new Set(); + for (const q of qrs) { + if (q.source !== "entry" || !clips.has(q.id) || !q.url) continue; + const key = `${q.id}\u0000${q.url}`; + if (seen.has(key)) continue; + seen.add(key); + out.push({ clip: q.id, url: String(q.url) }); + } + return out; +} + +/** A fetch that gives up: a site that hangs is a site that does not answer. */ +function withTimeout(fetchImpl, ms) { + return (url, init = {}) => fetchImpl(url, { ...init, signal: AbortSignal.timeout(ms) }); +} + +const errText = (e) => { + const m = e instanceof Error ? e.message : String(e); + const cause = e instanceof Error && e.cause instanceof Error ? ` (${e.cause.message})` : ""; + return `${m}${cause}`; +}; + +/** + * Resolve the links. Pure over `fetchImpl` (and the cache dir). + * + * @param {Array<{ clip: string, url: string }>} links + * @param {{ fetchImpl?: typeof fetch, cacheDir?: string | null, now?: () => Date, log?: (s: string) => void, gapMs?: number, sleep?: (ms: number) => Promise<void> }} [opts] + * @returns {Promise<{ + * version: 1, checkedAt: string, fetched: number, + * origins: Record<string, { state: "ok" | "unreachable" | "no-corpus", error?: string, generatedAt?: string | null, title?: string | null }>, + * links: Array<{ clip: string, url: string, state: "ok" | "dead" | "unverified" | "direct", origin?: string, why?: string, fix?: string }>, + * }>} + */ +export async function checkLinks( + links, + { fetchImpl = globalThis.fetch, cacheDir = DEFAULT_CACHE_DIR, now = () => new Date(), log = () => {}, gapMs = LINK_GAP_MS, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}, +) { + let fetched = 0; + /** host -> when its last request was sent (ms) */ + const lastAt = new Map(); + const counting = withTimeout(async (url, init) => { + const host = new URL(String(url)).host; + const last = lastAt.get(host); + if (last != null && gapMs > 0) { + const wait = last + jitterUp(gapMs) - Date.now(); + if (wait > 0) await sleep(wait); + } + lastAt.set(host, Date.now()); + fetched += 1; + return fetchImpl(url, init); + }, FETCH_TIMEOUT_MS); + const { getJson } = createJsonCache({ cacheDir, fetchImpl: counting, log }); + /** @type {Record<string, any>} */ + const origins = {}; + const corpusOf = new Map(); + const manifestOf = new Map(); + + async function corpus(origin) { + if (corpusOf.has(origin)) return corpusOf.get(origin); + let doc = null; + try { + doc = await getJson(`${origin}/corpus.json`, { refresh: true }); + origins[origin] = { + state: "ok", + generatedAt: typeof doc?.generatedAt === "string" ? doc.generatedAt : null, + title: typeof doc?.site?.title === "string" ? doc.site.title : null, + }; + } catch (e) { + const msg = errText(e); + // A 404 is a site that answered and publishes no contract; anything + // else (DNS, refused, timeout, 5xx) is a site that did not answer. + origins[origin] = / -> 404$/.test(msg) ? { state: "no-corpus", error: msg } : { state: "unreachable", error: msg }; + doc = null; + } + corpusOf.set(origin, doc); + return doc; + } + + async function channelManifest(url) { + if (manifestOf.has(url)) return manifestOf.get(url); + let doc = null; + let error = null; + try { + doc = await getJson(url, { refresh: true }); + } catch (e) { + error = errText(e); + } + const r = { doc, error }; + manifestOf.set(url, r); + return r; + } + + const out = []; + for (const { clip, url } of links) { + const a = archiveLinkOf(url); + if (!a) { + out.push({ clip, url, state: "direct" }); + continue; + } + const host = new URL(a.origin).host; + const c = await corpus(a.origin); + if (!c) { + const o = origins[a.origin]; + out.push({ + clip, url, state: "unverified", origin: a.origin, + why: o.state === "no-corpus" ? `${host} publishes no corpus.json` : `couldn't reach ${host} (${o.error})`, + }); + continue; + } + if (c.site?.scope === "cited") { + out.push({ clip, url, state: "unverified", origin: a.origin, why: `${host} is a cited report site: it publishes no transcripts to look the record up in` }); + continue; + } + const ch = (c.channels ?? []).find((x) => x?.slug === a.channel); + if (!ch) { + out.push({ + clip, url, state: "dead", origin: a.origin, + why: `the channel "${a.channel}" is not on ${host}${origins[a.origin].generatedAt ? ` (its deploy of ${origins[a.origin].generatedAt.slice(0, 10)})` : ""} — publish the site with it, or link elsewhere`, + }); + continue; + } + const manifestUrl = ch.manifests?.transcripts; + if (typeof manifestUrl !== "string" || !manifestUrl) { + out.push({ clip, url, state: "dead", origin: a.origin, why: `${host} publishes no transcripts for "${a.channel}"` }); + continue; + } + const man = await channelManifest(manifestUrl); + if (!man.doc) { + out.push({ clip, url, state: "unverified", origin: a.origin, why: `couldn't read ${a.channel}'s manifest on ${host} (${man.error})` }); + continue; + } + const s2p = man.doc.slugToPage ?? {}; + const page = s2p[a.id]; + if (page === undefined) { + // The Twitch trap: the corpus directory is the bare id, the site's record is `v<id>`. + const alt = /^\d+$/.test(a.id) && s2p[`v${a.id}`] !== undefined ? `v${a.id}` : null; + out.push({ + clip, url, state: "dead", origin: a.origin, + why: alt + ? `"${a.id}" is not a record on ${host}; the site's record is "${alt}"` + : `"${a.id}" is not published in ${a.channel} on ${host}${origins[a.origin].generatedAt ? ` (deployed ${origins[a.origin].generatedAt.slice(0, 10)})` : ""}`, + ...(alt ? { fix: url.replace(/([?&]v=[^&#]*?)(%2F|\/)(\d+)(?=&|#|$)/i, `$1$2v$3`) } : {}), + }); + continue; + } + const pageUrl = pageUrlFrom(manifestUrl, Number(page)); + const has = (doc) => Array.isArray(doc) && doc.some((r) => r?.id === a.id || r?.slug === a.id); + let found = false; + let error = null; + try { + found = has(await getJson(pageUrl)); + // A cached shard older than the deploy: read it again, once. + if (!found) found = has(await getJson(pageUrl, { refresh: true })); + } catch (e) { + error = errText(e); + } + if (error) out.push({ clip, url, state: "unverified", origin: a.origin, why: `couldn't read ${path.posix.basename(new URL(pageUrl).pathname)} on ${host} (${error})` }); + else if (!found) out.push({ clip, url, state: "dead", origin: a.origin, why: `${host}'s slugToPage puts "${a.id}" on page ${page}, but no record there has that id — the deploy is inconsistent` }); + else out.push({ clip, url, state: "ok", origin: a.origin }); + } + return { version: 1, checkedAt: now().toISOString(), fetched, origins, links: out }; +} + +/** + * Check the project's links now and record the answer in out/links.json. + * + * @param {string} dir + * @param {Record<string, any>} manifest + * @param {{ fetchImpl?: typeof fetch, cacheDir?: string | null, now?: () => Date, log?: (s: string) => void }} [opts] + */ +export async function runLinkCheck(dir, manifest, opts = {}) { + const doc = await checkLinks(linksOf(manifest), opts); + const file = linksFile(dir); + await mkdir(path.dirname(file), { recursive: true }); + const tmp = `${file}.tmp-${process.pid}`; + await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`); + await rename(tmp, file); + return doc; +} + +/** The last recorded check, or null. */ +export async function readLinkCheck(dir) { + try { + const doc = JSON.parse(await readFile(linksFile(dir), "utf8")); + return doc && Array.isArray(doc.links) ? doc : null; + } catch { + return null; + } +} + +/** + * The recorded check read against the manifest as it is NOW: what is dead, + * what could not be verified (by site), and which of today's links the + * check never saw (a link changed since). + * + * @param {Record<string, any>} m + * @param {Awaited<ReturnType<typeof readLinkCheck>>} doc + */ +export function linkVerdicts(m, doc) { + const current = linksOf(m); + const archive = current.filter((l) => archiveLinkOf(l.url)); + const byKey = new Map((doc?.links ?? []).map((l) => [`${l.clip}\u0000${l.url}`, l])); + const dead = []; + const unverified = []; + const unchecked = []; + let ok = 0; + for (const l of archive) { + const r = byKey.get(`${l.clip}\u0000${l.url}`); + if (!r) unchecked.push(l); + else if (r.state === "dead") dead.push(r); + else if (r.state === "unverified") unverified.push(r); + else if (r.state === "ok") ok += 1; + } + return { checkedAt: doc?.checkedAt ?? null, origins: doc?.origins ?? {}, archive: archive.length, direct: current.length - archive.length, ok, dead, unverified, unchecked }; +} diff --git a/umtool/lib/report/linksCli.mjs b/umtool/lib/report/linksCli.mjs @@ -0,0 +1,161 @@ +// `umtool links <project> [--json] [--fix]`: do the cut's QR links open on the +// sites they link? (linkCheck.mjs says how, and why it is polite and cached.) +// The same check the project page's Check links runs (POST /api/report/links), +// recorded in out/links.json, which `umtool check` and the decisions read. +// +// --fix rewrite every dead link the check knows the fix for (the Twitch +// trap: `?v=<channel>/<id>` where the site's record is `v<id>`) +// through the window writer, then check again. +// +// Exit 1 when a link is dead, 0 otherwise (unverified is not dead). +// Plain ESM: the CLI runs it under bare node. +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { readManifest } from "../projects/report.mjs"; +import { kindMakesTakes } from "../projects/kinds.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { updateClip } from "./manifest.mjs"; +import { runLinkCheck } from "./linkCheck.mjs"; + +export const LINKS_USAGE = [ + "usage: umtool links <project> [--json] [--fix]", + "", + "Resolves every clip QR the cut draws against the site it links: corpus.json -> the channel's", + "transcripts manifest -> slugToPage -> page-NNNN.json -> the record. One request at a time per host,", + "at least 3 s apart (jittered); shard", + "pages from the cue cache, read again only on a miss. A site that does not answer leaves its links", + "unverified (not dead). Writes out/links.json: `umtool check` reports link-dead (blocking),", + "links-unverified and links-unchecked from it. --fix rewrites the dead links it knows the fix for", + "(a Twitch id the site serves as v<id>) through the window writer, then checks again.", + "Exit 1 when a link is dead.", +].join("\n"); + +class CliError extends Error {} + +/** One line per site and per dead or unverified link. */ +export function linksSummary(doc) { + const lines = []; + const n = (s) => doc.links.filter((l) => l.state === s).length; + lines.push( + `${doc.links.length} clip QR link(s): ${n("ok")} open · ${n("dead")} dead · ${n("unverified")} not verified · ${n("direct")} not archive links (not checked) · ${doc.fetched} request(s)`, + ); + for (const [origin, o] of Object.entries(doc.origins ?? {})) { + lines.push( + ` ${origin}: ${o.state === "ok" ? `corpus.json${o.generatedAt ? `, deployed ${o.generatedAt.slice(0, 16).replace("T", " ")}` : ""}` : o.state === "no-corpus" ? "no corpus.json" : `couldn't reach — ${o.error}`}`, + ); + } + for (const l of doc.links) { + if (l.state === "dead") lines.push(`DEAD ${l.clip} ${l.why}${l.fix ? `\n fix: ${l.fix}` : ""}`); + else if (l.state === "unverified") lines.push(`UNVERIFIED ${l.clip} ${l.why}`); + } + return lines.join("\n"); +} + +/** + * @param {string[]} args the words after `links` + * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, fetchImpl?: typeof fetch, cacheDir?: string | null, gapMs?: number }} [opts] + * @returns {Promise<number>} + */ +export async function linksCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), fetchImpl, cacheDir, gapMs } = {}) { + try { + const words = args.filter((a) => !a.startsWith("--")); + const flags = new Set(args.filter((a) => a.startsWith("--"))); + for (const f of flags) if (!["--json", "--fix", "--help"].includes(f)) throw new CliError(`unknown flag ${f}`); + if (!words[0] || flags.has("--help")) { + (flags.has("--help") ? out : err)(LINKS_USAGE); + return flags.has("--help") ? 0 : 2; + } + const r = await resolveProject(words[0], root); + if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${words[0]}"`); + const project = r.project; + if (!kindMakesTakes(project.kind)) throw new CliError(`${project.id} is a ${project.kind}, not a report video`); + const opts = { + ...(fetchImpl ? { fetchImpl } : {}), + ...(cacheDir !== undefined ? { cacheDir } : {}), + ...(gapMs !== undefined ? { gapMs } : {}), + log: flags.has("--json") ? () => {} : (s) => err(` ${s}`), + }; + let m = await readManifest(project.dir); + if (!m) throw new CliError(`${project.id} has no video.manifest.json`); + let doc = await runLinkCheck(project.dir, m, opts); + const fixed = []; + if (flags.has("--fix")) { + for (const l of doc.links) { + if (l.state !== "dead" || !l.fix) continue; + await withEditNotes(project, () => updateClip(project.dir, l.clip, { citeUrl: l.fix })); + fixed.push({ clip: l.clip, from: l.url, to: l.fix }); + } + if (fixed.length) { + m = await readManifest(project.dir); + doc = await runLinkCheck(project.dir, m, opts); + } + } + const dead = doc.links.filter((l) => l.state === "dead").length; + if (flags.has("--json")) { + out(JSON.stringify({ ok: dead === 0, project: project.id, ...doc, ...(flags.has("--fix") ? { fixed } : {}) }, null, 2)); + return dead ? 1 : 0; + } + for (const f of fixed) out(`fixed ${f.clip}: ${f.from} -> ${f.to}`); + out(`${project.id} · ${linksSummary(doc)}`); + out(`recorded in out/links.json (umtool check ${project.id} reads it)`); + return dead ? 1 : 0; + } catch (e) { + err(`umtool links: ${e instanceof Error ? e.message : String(e)}`); + return e instanceof CliError ? 2 : 1; + } +} + +export const PATCH_MARKERS_USAGE = [ + "usage: umtool patch-markers <project> [<file>.patch.json] [--fix] [--json]", + "", + "The take patches beside the manifest (*.patch.json, what `umtool take --patch` reads) whose deck markers", + "name a clip that is not in the cut -- a take made with one is refused. Structural writes re-anchor them", + "by themselves; this is for the rest. --fix: each such marker takes the `after` of the cut's marker with", + "the same label; one no marker of the cut shares a label with is left, and named. Exit 1 when one is left.", +].join("\n"); + +/** + * `umtool patch-markers …` + * @param {string[]} args the words after `patch-markers` + * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts] + * @returns {Promise<number>} + */ +export async function patchMarkersCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { + try { + const words = args.filter((a) => !a.startsWith("--")); + const flags = new Set(args.filter((a) => a.startsWith("--"))); + for (const f of flags) if (!["--json", "--fix", "--help"].includes(f)) throw new CliError(`unknown flag ${f}`); + if (!words[0] || flags.has("--help")) { + (flags.has("--help") ? out : err)(PATCH_MARKERS_USAGE); + return flags.has("--help") ? 0 : 2; + } + const r = await resolveProject(words[0], root); + if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${words[0]}"`); + const project = r.project; + const m = await readManifest(project.dir); + if (!m) throw new CliError(`${project.id} has no video.manifest.json`); + const { stalePatchMarkers, fixStalePatchMarkers } = await import("./patchMarkers.mjs"); + let stale = await stalePatchMarkers(project.dir, m); + if (words[1]) stale = stale.filter((s) => s.file === words[1]); + const fixed = []; + if (flags.has("--fix")) { + for (const s of stale) if (!s.error) fixed.push(await fixStalePatchMarkers(project.dir, m, s.file)); + stale = (await stalePatchMarkers(project.dir, m)).filter((s) => !words[1] || s.file === words[1]); + } + if (flags.has("--json")) { + out(JSON.stringify({ ok: stale.length === 0, project: project.id, stale, ...(flags.has("--fix") ? { fixed } : {}) }, null, 2)); + return stale.length ? 1 : 0; + } + for (const f of fixed) for (const n of f.notes) out(`${f.file}: ${n}`); + if (!stale.length) out(`${project.id}: every take patch's markers name clips of the cut`); + for (const s of stale) { + if (s.error) out(`${s.file}: does not read (${s.error})`); + for (const mk of s.markers) out(`${s.file}: ${mk.label ? `"${mk.label}"` : `marker ${mk.index}`} is after ${mk.after}, which is not in the cut`); + } + return stale.length ? 1 : 0; + } catch (e) { + err(`umtool patch-markers: ${e instanceof Error ? e.message : String(e)}`); + return e instanceof CliError ? 2 : 1; + } +} diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -40,7 +40,8 @@ import { verticalErrors } from "umtool-report-to-video/look"; import { LOOK_KEYS, applyLookPatch, lookOf } from "yt-dlp-transcript-common/lib/report/look.mjs"; import { validateRoom } from "umtool-report-to-video/room"; import { applySectionEnter } from "./sections.mjs"; -import { parseClipSpec } from "./clipEditorModel.mjs"; +import { citeUrlAt, parseClipSpec } from "./clipEditorModel.mjs"; +import { addSectionIn, followSplitMarkers, moveBoundaryIn, moveToSectionIn, placeIn, removeBoundaryIn, sectionModel, sectionWords, setSectionIn } from "./sectionEdit.mjs"; import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck"; import { migrateManifest } from "umtool-report-to-video/modules/migrate"; import { loadPreset, resolvePresetLayers } from "umtool-report-to-video/presets"; @@ -61,6 +62,8 @@ import { FACT_REASONS, applyVerdictPatch, rejectPatch, rejectReasonOf } from "./ import { DELIVERABLES_MODES } from "./storage.mjs"; import { createSnapshot, listSnapshots } from "./snapshots.mjs"; import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs"; +import { citeFollow, clockOf, qrFollowsCite } from "./citeFollow.mjs"; +import { syncPatchMarkers, syncSectionMarkers } from "./patchMarkers.mjs"; import { DRAFTED_MANIFEST_FIELDS, clearEditedDrafts, isEntryField, publishWarnings, pruneDrafted, validateDrafted, validatePublish, } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; @@ -164,6 +167,44 @@ export class StaleToken extends Error { } } +/** + * A window save that leaves a second the clip's marks name -- a stamp's + * `claim.at` (or a mark's `claims[k].at`), the mute mark -- outside the new + * window. The message is the sentence it always was; `marks` says what each + * could move to, so a page can offer the fix as one retried write + * (`markFix` / `muteFix` on the same patch: updateClip below) and the + * operator's unsaved trim is never lost. `umtool window … --move-stamp + * first|nearest|<s>` / `--clear-stamp` / `--move-mute nearest` / + * `--clear-mute` are the terminal's. + */ +export class MarksOutside extends Error { + /** + * @param {string} message + * @param {{ kind: "mark" | "mute", window: { start: number, end: number }, marks: Array<{ index: number | null, id: string | null, at: number, first: number, nearest: number }> }} detail + */ + constructor(message, detail) { + super(message); + this.name = "MarksOutside"; + this.kind = detail.kind; + this.window = detail.window; + this.marks = detail.marks; + } +} + +/** The first and the last second a clip plays (its cut, else its extent), and the nearest of them to `at` that is not in a gap. */ +function keptSecondNear(entry, at) { + const from = entry.cutStart ?? entry.start; + const to = entry.cutEnd ?? entry.end; + const gaps = Array.isArray(entry.gaps) ? entry.gaps : []; + const out = (v) => { + const g = gaps.find((x) => v > x.from && v < x.to); + return g ? (v - g.from <= g.to - v ? g.from : g.to) : v; + }; + const first = out(from); + const nearest = out(Math.min(to, Math.max(from, at))); + return { first: round2(first), nearest: round2(nearest) }; +} + const WINDOW_FIELDS = ["start", "end"]; const FLAG_FIELDS = ["lock", "lockStart", "lockEnd", "lockCut"]; @@ -194,7 +235,7 @@ const WIN_EPS = 0.02; * @param {string} clipId * @param {Record<string, unknown>} patch * @param {{ token?: string | null }} [opts] - * @returns {Promise<{ entry: Record<string, unknown>, before: {start:number,end:number}, token: string | null, snapshot?: Record<string, unknown> }>} + * @returns {Promise<{ entry: Record<string, unknown>, before: {start:number,end:number}, token: string | null, snapshot?: Record<string, unknown>, citeFollowed?: { cite?: { from: number, to: number }, citeUrl?: { from: string, to: string } } }>} */ export async function updateClip(dir, clipId, patch, { token = null, edit = "trim", now = null } = {}) { return withManifestLock(async () => { @@ -204,14 +245,14 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri // Re-read INSIDE the lock, every time. Nothing is held across requests. const raw = await readFile(manifestFile(dir), "utf8"); const manifest = JSON.parse(raw); - const { entry, before } = patchClipEntry(manifest, clipId, patch, { edit, now, raw, dir }); + const { entry, before, citeFollowed } = patchClipEntry(manifest, clipId, patch, { edit, now, raw, dir }); // A gap cut or removed (gaps.mjs) changes what the clip IS in the cut, as a // split does: an undo point first (`umtool timeline <p> undo`, the Cut tab's Undo). const snapshot = GAP_PATCH_KEYS.some((k) => patch[k] !== undefined) ? await autoSnapshot(dir, "gaps") : null; const nextToken = await writeManifestAtomic(dir, manifest); // A moved extent may need a new bench excerpt: queued, never waited for. if (entry.start !== before.start || entry.end !== before.end) benchPrepAfterWrite(dir, [clipId]); - return { entry, before, token: nextToken, ...(snapshot ? { snapshot } : {}) }; + return { entry, before, token: nextToken, ...(snapshot ? { snapshot } : {}), ...(citeFollowed ? { citeFollowed } : {}) }; }); } @@ -232,7 +273,9 @@ export const GAP_PATCH_KEYS = Object.freeze(["gaps", "gapAdd", "gapRemove"]); * `raw`: the manifest's text before the patch, when the caller has it (the * finale check compares against it); else it is taken here. `dir`: the * project's directory, where an `fx` screenshot written here must be. - * @returns {{ entry: Record<string, any>, before: { start: number, end: number } }} + * @returns {{ entry: Record<string, any>, before: { start: number, end: number }, citeFollowed: null | { cite?: { from: number, to: number }, citeUrl?: { from: string, to: string } } }} + * `citeFollowed`: the cite and/or the citeUrl's `t=` this patch moved with + * an edge (citeFollow.mjs), or null. */ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = null, raw = null, dir = null } = {}) { const original = patch.layout !== undefined ? (raw ?? JSON.stringify(manifest)) : null; @@ -250,6 +293,7 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n const before = { start: entry.start, end: entry.end }; const cutBefore = cutOf(entry); + const clockBefore = clockOf(entry); // The effects' fields as they were, for a check that refuses only what a // write ADDS: a window save, or an fx write, under an fx that already had // a problem is not blamed for it. @@ -378,6 +422,49 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n } } + // ---- the cite follows the edge (citeFollow.mjs) -------------------------- + // + // An edge move that leaves the clock (`cite`) more than a lead-in before + // what plays, or past its end, moves it to the clip's first played second; + // a citeUrl naming this recording whose `t=` is left outside moves with it. + // A patch that writes `cite` itself is the author deciding: then only the + // QR follows, and only when it agreed with the clock before. A patch that + // writes `citeUrl` keeps exactly what it wrote. + let citeFollowed = null; + const channelSlug = manifest?.provenance?.channelSlug ?? null; + const edgeMoved = ["start", "end", "cutStart", "cutEnd"].some((k) => patch[k] !== undefined); + if (patch.citeUrl === undefined) { + if (patch.cite === undefined && edgeMoved) citeFollowed = citeFollow(entry, { channelSlug }); + else if (patch.cite !== undefined) citeFollowed = qrFollowsCite(entry, clockBefore, { channelSlug }); + } else if (patch.cite === undefined && edgeMoved) { + const f = citeFollow({ ...entry, citeUrl: undefined }, { channelSlug }); + if (f?.cite) citeFollowed = { cite: f.cite }; + } + if (citeFollowed?.cite) entry.cite = citeFollowed.cite.to; + if (citeFollowed?.citeUrl) entry.citeUrl = citeFollowed.citeUrl.to; + + // ---- what the walk said that is not a verdict --------------------------- + // + // `walkNote`: an editorial note from the walk ("THIS IS GOLD", "might want + // a bit of silence") -- NOT `correction`, which says the REPORT got a fact + // wrong and is read by the next report pass. `star`: a favourite, which + // makes the clip a trailer candidate (trailerCandidates.mjs). Neither is + // rendered. Empty / false deletes the key. + if (patch.walkNote !== undefined) { + const v = String(patch.walkNote ?? "").trim(); + if (v.length > 2000) throw new Error("walkNote is at most 2000 characters"); + if (v) entry.walkNote = v; + else delete entry.walkNote; + } + if (patch.star !== undefined) { + const v = patch.star; + const on = v === true || v === "true" || v === 1 || v === "1" || v === "on"; + const off = v === false || v === "false" || v === 0 || v === "0" || v === "" || v === null || v === "off"; + if (!on && !off) throw new Error(`star must be true or false, not ${JSON.stringify(v)}`); + if (on) entry.star = true; + else delete entry.star; + } + // ---- a deliberate repeat ------------------------------------------------ // // `repeatOf`: the id of the clip this one re-plays on purpose -- a callback, @@ -404,6 +491,13 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n // cut, and checked against the entry AFTER the patch: a window save that // leaves the mark outside is refused rather than keeping a mark that no // longer says anything about the clip. Empty or null deletes it. + if (patch.muteFix !== undefined && patch.muteFix !== null && patch.muteFrom === undefined && entry.muteFrom != null) { + // The refused save's fix (MarksOutside), in the same write: the mark to the nearest kept second, or gone. + const fix = String(patch.muteFix); + if (fix === "clear") delete entry.muteFrom; + else if (fix === "nearest") entry.muteFrom = keptSecondNear(entry, entry.muteFrom).nearest; + else throw new Error(`muteFix is nearest or clear, not ${JSON.stringify(patch.muteFix)}`); + } if (patch.muteFrom !== undefined) { const v = parseMuteFrom(patch.muteFrom, entry.start, entry.end); if (v == null) delete entry.muteFrom; @@ -417,9 +511,10 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n try { entry.muteFrom = parseMuteFrom(entry.muteFrom, entry.start, entry.end); } catch { - throw new Error( + throw new MarksOutside( `the mute mark ${entry.muteFrom} must lie inside the window ` + `${entry.start}–${entry.end} — widen the window, or clear the mark`, + { kind: "mute", window: { start: entry.start, end: entry.end }, marks: [{ index: null, id: null, at: entry.muteFrom, ...keptSecondNear(entry, entry.muteFrom) }] }, ); } } @@ -431,12 +526,34 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n // keeping a mark that no longer says anything about the clip. if (patch.start !== undefined || patch.end !== undefined) { const many = Array.isArray(entry.claims); - rawMarksOf(entry).forEach((m, k) => { - if (!isObj(m) || typeof m.at !== "number" || (m.at >= entry.start && m.at <= entry.end)) return; + const outside = rawMarksOf(entry) + .map((m, k) => ({ m, k })) + .filter(({ m }) => isObj(m) && typeof m.at === "number" && !(m.at >= entry.start && m.at <= entry.end)); + // The refused save's fix, in the same write (MarksOutside): every stamp left outside moves to + // the first second that plays, the nearest one, a named second, or loses its `at`. + if (outside.length && patch.markFix !== undefined && patch.markFix !== null && patch.markFix !== "") { + const fix = patch.markFix; + for (const { m } of outside) { + if (fix === "clear") delete m.at; + else if (fix === "first" || fix === "nearest") m.at = keptSecondNear(entry, m.at)[fix]; + else { + const v = Number(fix); + if (!Number.isFinite(v)) throw new Error(`markFix is first, nearest, clear or a source second, not ${JSON.stringify(fix)}`); + m.at = round2(v); + } + } + } + outside.forEach(({ m, k }) => { + if (typeof m.at !== "number" || (m.at >= entry.start && m.at <= entry.end)) return; const name = many ? `the mark ${m.id}'s second (claims[${k}].at ${m.at})` : `the stamp's second (claim.at ${m.at})`; - throw new Error( + throw new MarksOutside( `${name} must lie inside the window ` + `${entry.start}–${entry.end} — widen the window, or clear ${many ? "that mark's at" : "claim.at"}`, + { + kind: "mark", + window: { start: entry.start, end: entry.end }, + marks: outside.filter((x) => typeof x.m.at === "number").map((x) => ({ index: many ? x.k : null, id: typeof x.m.id === "string" ? x.m.id : null, at: x.m.at, ...keptSecondNear(entry, x.m.at) })), + }, ); }); } @@ -665,7 +782,7 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n noteAssistEdit(entry, edit, cutBefore, at); if (edit === "restore" && isObj(entry.assist) && entry.assist.proposal) entry.assist.by = "assistant"; - return { entry, before }; + return { entry, before, citeFollowed }; } // --------------------------------------------------------------------------- @@ -811,7 +928,7 @@ const textOr = (v, fallback) => (v === undefined ? fallback : String(v ?? "").tr * @param {{ token?: string | null, quotes?: { first?: string, second?: string }, now?: string | null }} [opts] */ export async function splitClip(dir, clipId, at, { token = null, quotes = {}, now = null } = {}) { - return prepAfter(dir, (r) => [r.id, r.second], structural(dir, "split", token, (m) => { + return prepAfter(dir, (r) => [r.id, r.second], sectionWrite(dir, "split", token, (m) => { const { i, e } = clipAt(m.timeline, clipId); const t = round2(Number(at)); const { cutStart, cutEnd } = cutOf(e); @@ -839,6 +956,8 @@ export async function splitClip(dir, clipId, at, { token = null, quotes = {}, no b.start = t; if (hasCut) b.cutStart = t; if (typeof b.cite === "number") b.cite = t; + // The QR follows the clock: the second half's link opens at its own second. + if (typeof b.citeUrl === "string" && b.citeUrl) b.citeUrl = citeUrlAt(b.citeUrl, t); if (b.muteFrom != null && b.muteFrom < t) delete b.muteFrom; delete b.claim; delete b.claims; @@ -862,7 +981,10 @@ export async function splitClip(dir, clipId, at, { token = null, quotes = {}, no noteAssistEdit(b, "split", from, stamp); } m.timeline.splice(i + 1, 0, b); - return { id: e.id, second: b.id, entries: [e, b] }; + // A section boundary after the clip stays after the WHOLE of it: the + // marker follows the second half, or that half opens the next section. + const reanchored = followSplitMarkers(m, e.id, b.id); + return { id: e.id, second: b.id, entries: [e, b], reanchored }; })); } @@ -1644,11 +1766,11 @@ const ENTRY_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; * same op was taken in the last two minutes. Never fatal: an undo point that * cannot be taken is reported, and the edit still lands. */ -export async function autoSnapshot(dir, op, { now = Date.now() } = {}) { +export async function autoSnapshot(dir, op, { now = Date.now(), every = AUTO_SNAPSHOT_EVERY_MS } = {}) { const label = `${AUTO_SNAPSHOT_PREFIX}${op}`; try { - const recent = (await listSnapshots(dir)).find((s) => !s.legacy && s.label === label); - if (recent && now - recent.mtimeMs < AUTO_SNAPSHOT_EVERY_MS) return { skipped: true, rel: recent.rel }; + const recent = every > 0 ? (await listSnapshots(dir)).find((s) => !s.legacy && s.label === label) : null; + if (recent && now - recent.mtimeMs < every) return { skipped: true, rel: recent.rel }; return { skipped: false, ...(await createSnapshot(dir, { label })) }; } catch (e) { return { skipped: true, error: e instanceof Error ? e.message : String(e) }; @@ -1917,15 +2039,20 @@ export function reanchorAfterRemove(m, removed, i) { * One structural write: token, read, `mutate` (which throws to refuse), the * build's checks, the auto snapshot of the file as it still is, then the write. */ -async function structural(dir, op, token, mutate) { +async function structural(dir, op, token, mutate, { snapshotEvery = undefined } = {}) { return withManifestLock(async () => { const current = await manifestToken(dir); if (token !== null && current !== token) throw new StaleToken(token, current); const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8")); + const timelineBefore = Array.isArray(manifest.timeline) ? [...manifest.timeline] : []; const result = applyStructural(manifest, mutate); - const snapshot = await autoSnapshot(dir, op); + const snapshot = await autoSnapshot(dir, op, snapshotEvery === undefined ? {} : { every: snapshotEvery }); const nextToken = await writeManifestAtomic(dir, manifest); - return { ...result, snapshot, token: nextToken }; + // The project's take patches follow a removal as the manifest's markers + // did (patchMarkers.mjs): a marker after a clip that is gone moves to the + // same boundary, so the next `umtool take --patch` is not refused. + const patches = await syncPatchMarkers(dir, timelineBefore, manifest.timeline ?? []).catch(() => []); + return { ...result, snapshot, token: nextToken, ...(patches.length ? { patches } : {}) }; }); } @@ -2119,6 +2246,233 @@ export async function insertEntry(dir, afterId, spec, { token = null, at = null })); } +// ---- sections, edited as sections (UI notes 2026-10-30, item 1) ----------- +// +// Under the deck a cut's sections are its markers (sectionEdit.mjs): these +// writers move clips between sections, open a section, drag or remove a +// boundary and relabel one -- each a structural write (the undo point, the +// build's checks), the markers checked by the deck's own validateChrome, and +// then the take patches' markers brought along (patchMarkers.mjs syncSectionMarkers) so the next +// `umtool take --patch …` renders the same sections. `umtool timeline <p> +// section …`, the Cut tab's section bars and row menus. + +/** + * A structural write that may change the deck's markers: the markers are + * checked by validateChrome (refused only for what this edit breaks), an + * emptied list is removed, and every take patch in step is synced after. + */ +async function sectionWrite(dir, op, token, mutate, opts = {}) { + let before = []; + let after = []; + const res = await structural(dir, op, token, (m) => { + const clone = (v) => JSON.parse(JSON.stringify(v ?? null)); + const { chrome: c0, ...rest0 } = m.render ?? {}; + const already = isObj(c0) ? new Set(validateChrome(clone(c0), rest0)) : new Set(); + before = clone(m.render?.chrome?.deck?.markers ?? []); + const r = mutate(m); + const deck = m.render?.chrome?.deck; + if (isObj(deck) && Array.isArray(deck.markers) && !deck.markers.length) delete deck.markers; + const { chrome: c1, ...rest1 } = m.render ?? {}; + if (isObj(c1)) { + const errors = validateChrome(c1, rest1).filter((e) => !already.has(e)); + if (errors.length) throw new StructureRefused(errors); + } + after = clone(m.render?.chrome?.deck?.markers ?? []); + return r; + }, opts); + // `sectionPatches`: a section edit's take-patch sync (`patches` is a removal's, patchMarkers.mjs). + const sectionPatches = await syncSectionMarkers(dir, before, after); + return { ...res, sectionPatches }; +} + +/** + * Move clips `ids` to section `section` (its end; `position: "start"` its + * start), the markers following (sectionEdit.mjs moveToSectionIn). + * + * @param {string} dir + * @param {string[]} ids + * @param {number} section + * @param {{ token?: string | null, position?: "start" | "end" }} [opts] + */ +export async function moveToSection(dir, ids, section, { token = null, position = "end" } = {}) { + return sectionWrite(dir, "section-move", token, (m) => moveToSectionIn(m, ids, section, { position })); +} + +/** + * PLACE (Play's reel strip, a drop): entries `ids` land before entry `before` + * (null: the end), their clips joining section `section` (sectionEdit.mjs + * placeIn), the markers re-anchored so every other clip keeps its section. + * EVERY drop is its own undo point (no 2-minute coalescing: a drag is a + * decision, and the strip's Undo takes back exactly the one) and brings the + * take patches' markers along. + * + * @param {string} dir + * @param {string[]} ids + * @param {{ token?: string | null, before?: string | null, section?: number | null }} [opts] + */ +export async function placeEntries(dir, ids, { token = null, before = null, section = null } = {}) { + return sectionWrite(dir, "place", token, (m) => placeIn(m, ids, { before, section }), { snapshotEvery: 0 }); +} + +/** + * New section here: a marker after clip `afterId`, with a label and a colour. + * + * @param {string} dir + * @param {string} afterId + * @param {{ label?: string | null, color?: string | null }} spec + * @param {{ token?: string | null }} [opts] + */ +export async function addSection(dir, afterId, spec = {}, { token = null } = {}) { + return sectionWrite(dir, "section-add", token, (m) => addSectionIn(m, afterId, spec)); +} + +/** + * Drag a boundary: marker `marker` follows clip `afterId`, between its neighbours. + * @param {string} dir + * @param {number} marker + * @param {string} afterId + * @param {{ token?: string | null }} [opts] + */ +export async function moveSectionBoundary(dir, marker, afterId, { token = null } = {}) { + return sectionWrite(dir, "section-boundary", token, (m) => moveBoundaryIn(m, marker, afterId)); +} + +/** + * Remove a boundary: marker `marker` goes, its section joins the one before. + * @param {string} dir + * @param {number} marker + * @param {{ token?: string | null }} [opts] + */ +export async function removeSection(dir, marker, { token = null } = {}) { + return sectionWrite(dir, "section-remove", token, (m) => removeBoundaryIn(m, marker)); +} + +/** + * A section's label and/or colour (its marker's). + * @param {string} dir + * @param {number} marker + * @param {{ label?: string | null, color?: string | null }} patch + * @param {{ token?: string | null }} [opts] + */ +export async function updateSection(dir, marker, patch, { token = null } = {}) { + return sectionWrite(dir, "section-set", token, (m) => setSectionIn(m, marker, patch)); +} + +/** The sections a GET hands the Cut tab: index, label, colour, marker, clips. */ +export function sectionsOf(manifest) { + return sectionModel(manifest).sections.map((s) => ({ ...s, words: sectionWords(s) })); +} + +// ---- flash-forward (UI notes 2026-10-30, item 2) ---------------------------- + +/** + * FLASH-FORWARD A SPAN: a tight copy of clip `clipId`'s seconds `from`–`to` + * (inside its window) put somewhere else in the cut -- after entry `after` + * (null: at the start), or at the end (or start) of section `section` -- with + * the clip's attribution (title, date, channel, citeUrl moved to the new + * second, cite, quote or `quote` given, speakers, on-screen words, verdict) + * and its locks. A copy says it re-plays the clip (`repeatOf`), so the check's + * overlap row knows it is deliberate. `move: true` takes the span OUT of the + * clip instead (the v01 → v01t + the rest of v01 edit): the span must sit at + * one of its edges, and the clip keeps the rest (`restQuote` its words). + * A claim stays with the clip (one claim, one entry); so do its marks and the + * assistant's record. Mutates `m`. + * + * @param {Record<string, any>} m + * @param {string} clipId + * @param {{ from: number, to: number, after?: string | null, section?: number | null, position?: "start" | "end", move?: boolean, quote?: string, restQuote?: string, id?: string }} spec + */ +export function flashForwardIn(m, clipId, spec) { + if (!isObj(spec)) throw new Error("a flash-forward is { from, to, after | section }"); + const { i, e } = clipAt(m.timeline, clipId); + const a = round2(Number(spec.from)); + const b = round2(Number(spec.to)); + if (!Number.isFinite(a) || !Number.isFinite(b)) throw new Error("from and to are source seconds"); + if (b - a < 0.5) throw new Error(`a flash-forward is at least half a second (${a}–${b})`); + if (a < e.start - WIN_EPS || b > e.end + WIN_EPS) throw new Error(`${a}–${b} is not inside ${clipId}'s window ${e.start}–${e.end}`); + const gaps = Array.isArray(e.gaps) ? e.gaps : []; + for (const t of [a, b]) { + const g = gaps.find((x) => t > x.from && t < x.to); + if (g) throw new Error(`${t} is inside the gap ${g.from}–${g.to}, which never plays — start or end the span at its edge`); + } + const hasCut = e.cutStart != null && e.cutEnd != null; + const copy = JSON.parse(JSON.stringify(e)); + const base = typeof spec.id === "string" && ENTRY_ID_RE.test(spec.id) ? spec.id : `${clipId}t`; + copy.id = freshEntryId(m.timeline, base); + copy.start = a; + copy.end = b; + if (hasCut) { + copy.cutStart = a; + copy.cutEnd = b; + } + if (typeof copy.cite === "number") copy.cite = Math.floor(a); + if (typeof copy.citeUrl === "string" && copy.citeUrl) copy.citeUrl = citeUrlAt(copy.citeUrl, a); + if (copy.muteFrom != null && (copy.muteFrom <= a || copy.muteFrom >= b)) delete copy.muteFrom; + const inside = gaps.filter((g) => g.from >= a && g.to <= b); + if (inside.length) copy.gaps = inside; + else delete copy.gaps; + for (const k of ["claim", "claims", "marks", "assist", "sectionEnter"]) delete copy[k]; + const q = textOr(spec.quote, copy.quote ?? null); + if (q) copy.quote = q; + else delete copy.quote; + const move = spec.move === true; + if (move) delete copy.repeatOf; + else copy.repeatOf = e.id; + let rest = null; + if (move) { + const c = cutOf(e); + if (Math.abs(a - c.cutStart) <= 0.5) { + if (c.cutEnd - b < 0.5) throw new Error(`moving ${a}–${b} out of ${clipId} leaves less than half a second of it — move the whole clip instead`); + e.start = Math.max(e.start, b); + if (hasCut) e.cutStart = b; + if (typeof e.cite === "number") e.cite = Math.floor(b); + if (typeof e.citeUrl === "string" && e.citeUrl) e.citeUrl = citeUrlAt(e.citeUrl, b); + } else if (Math.abs(b - c.cutEnd) <= 0.5) { + if (a - c.cutStart < 0.5) throw new Error(`moving ${a}–${b} out of ${clipId} leaves less than half a second of it — move the whole clip instead`); + e.end = Math.min(e.end, a); + if (hasCut) e.cutEnd = a; + if (e.muteFrom != null && e.muteFrom >= a) delete e.muteFrom; + } else { + throw new Error(`${a}–${b} is in the middle of ${clipId} (${c.cutStart}–${c.cutEnd}): to move it out, split there first — or copy it (a repeat)`); + } + if (gaps.length) { + const keep = gaps.filter((g) => g.to <= e.end && g.from >= e.start); + if (keep.length) e.gaps = keep; + else delete e.gaps; + } + const rq = textOr(spec.restQuote, e.quote ?? null); + if (rq) e.quote = rq; + else delete e.quote; + rest = { start: e.start, end: e.end, ...(hasCut ? { cutStart: e.cutStart, cutEnd: e.cutEnd } : {}) }; + } + // Where it goes: after an entry (null: the start), or into a section. + const after = spec.after === undefined || spec.after === "" ? null : spec.after; + let at = 0; + if (after !== null) at = entryIndex(m.timeline, String(after)) + 1; + m.timeline.splice(at, 0, copy); + let section = null; + if (spec.section !== undefined && spec.section !== null && spec.section !== "") { + const r = moveToSectionIn(m, [copy.id], Number(spec.section), { position: spec.position === "start" ? "start" : "end", allowNoop: true }); + section = { index: r.section, label: r.label, reanchored: r.reanchored }; + at = m.timeline.findIndex((x) => x === copy); + } + const placedBefore = at <= m.timeline.indexOf(e); + return { id: copy.id, at, entry: copy, source: e.id, move, rest, section, earlier: placedBefore, sourceAt: i }; +} + +/** + * Flash-forward a span (flashForwardIn) as one structural write: the undo + * point, the build's checks, the patches' markers synced. + * + * @param {string} dir + * @param {string} clipId + * @param {Parameters<typeof flashForwardIn>[2]} spec + * @param {{ token?: string | null }} [opts] + */ +export async function flashForward(dir, clipId, spec, { token = null } = {}) { + return prepAfter(dir, (r) => [r.id, r.move ? r.source : null], sectionWrite(dir, "flash-forward", token, (m) => flashForwardIn(m, clipId, spec))); +} + const TEASER_PATCH_KEYS = ["lines", "beat", "dip", "tail", "tailWait"]; /** diff --git a/umtool/lib/report/patchMarkers.mjs b/umtool/lib/report/patchMarkers.mjs @@ -0,0 +1,265 @@ +// A take patch's deck markers follow the cut (UI notes 2026-10-30, #6). +// +// A take made with `umtool take … --patch draft-1.patch.json` merges that file +// over the manifest (RFC 7386), and a merge patch REPLACES an array: so a +// patch that carries `render.chrome.deck.markers` carries the whole list, each +// marker `after` a clip id. Removing a clip re-anchors the MANIFEST's markers +// (manifest.mjs reanchorAfterRemove) -- and left the patch's naming a clip +// that is gone, so the next take was refused ("draft-9 was refused") until the +// patch was synced by hand, after every section change. +// +// Two halves, one rule: +// - the structural writers re-anchor the project's `*.patch.json` the way +// they re-anchor the manifest: a marker after a removed clip moves to the +// clip before it (the same boundary), or is dropped when none is left; +// - the check reports a patch whose markers name a clip that is not in the +// cut (`patch-markers-stale`, lib/projects/report.mjs) -- a hand edit, a +// patch written before this existed, a clip removed by hand. +// +// Only a patch with no `timeline` of its own: one that replaces the timeline +// names ITS clips, which the manifest knows nothing about. Only the project's +// own directory (the convention: draft-1.patch.json beside the manifest). +// +// Plain ESM: the CLI runs it under bare node. +import { readdir, readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; + +export const PATCH_FILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*\.patch\.json$/; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const isClip = (e) => isObj(e) && (e.kind ?? e.type) === "clip"; + +/** The project's take patches: `*.patch.json` beside the manifest, by name. */ +export async function patchFilesOf(dir) { + const names = await readdir(dir).catch(() => []); + return names.filter((n) => PATCH_FILE_RE.test(n)).sort(); +} + +/** A patch's deck markers, or null when it carries none (or its own timeline). */ +export function patchMarkersOf(patch) { + if (!isObj(patch) || patch.timeline !== undefined) return null; + const markers = patch?.render?.chrome?.deck?.markers; + return Array.isArray(markers) ? markers : null; +} + +/** + * The clips a structural edit took out, each with the clip a marker after it + * should now follow: the nearest clip BEFORE it (in the old order) that is + * still in the cut -- reanchorAfterRemove's "same boundary" -- or null. + * + * @param {Array<Record<string, any>>} before the timeline before the edit + * @param {Array<Record<string, any>>} after the timeline after it + * @returns {Map<string, string | null>} + */ +export function removedAnchors(before, after) { + const still = new Set((after ?? []).filter(isClip).map((e) => e.id)); + const out = new Map(); + (before ?? []).forEach((e, i) => { + if (!isClip(e) || !e.id || still.has(e.id)) return; + let anchor = null; + for (let k = i - 1; k >= 0; k -= 1) { + const p = before[k]; + if (isClip(p) && still.has(p.id)) { + anchor = p.id; + break; + } + } + out.set(e.id, anchor); + }); + return out; +} + +/** + * Re-anchor one patch's markers in place. Returns one sentence per change. + * + * @param {Record<string, any>} patch + * @param {Map<string, string | null>} anchors removedAnchors()'s answer + * @returns {string[]} + */ +export function reanchorPatch(patch, anchors) { + const markers = patchMarkersOf(patch); + if (!markers || !anchors.size) return []; + const notes = []; + const next = markers.filter((mk, k) => { + const after = isObj(mk) ? String(mk.after ?? "").trim() : ""; + if (!anchors.has(after)) return true; + const to = anchors.get(after); + const name = `deck marker ${k}${mk.label ? ` ("${mk.label}")` : ""}`; + if (to) { + mk.after = to; + notes.push(`${name} moved from after ${after} to after ${to} (the same boundary)`); + return true; + } + notes.push(`${name} dropped: no clip before ${after}`); + return false; + }); + if (notes.length) patch.render.chrome.deck.markers = next; + return notes; +} + +/** + * After a structural write: re-anchor every take patch in the project whose + * markers named a clip the write took out. Each changed file is rewritten + * whole (2-space JSON and a newline, tmp + rename). Never fatal: a patch that + * does not read is reported, and the manifest's write stands. + * + * @param {string} dir + * @param {Array<Record<string, any>>} before + * @param {Array<Record<string, any>>} after + * @returns {Promise<Array<{ file: string, notes: string[], error?: string }>>} + */ +export async function syncPatchMarkers(dir, before, after) { + const anchors = removedAnchors(before, after); + if (!anchors.size) return []; + const out = []; + for (const name of await patchFilesOf(dir)) { + const file = path.join(dir, name); + let patch; + try { + patch = JSON.parse(await readFile(file, "utf8")); + } catch (e) { + out.push({ file: name, notes: [], error: `does not read: ${e instanceof Error ? e.message : String(e)}` }); + continue; + } + const notes = reanchorPatch(patch, anchors); + if (!notes.length) continue; + try { + const tmp = `${file}.tmp-${process.pid}`; + await writeFile(tmp, `${JSON.stringify(patch, null, 2)}\n`); + await rename(tmp, file); + out.push({ file: name, notes }); + } catch (e) { + out.push({ file: name, notes, error: `not written: ${e instanceof Error ? e.message : String(e)}` }); + } + } + return out; +} + +/** + * The check's half: every take patch marker after a clip that is not in the + * cut, and every patch that does not read. + * + * @param {string} dir + * @param {Record<string, any>} manifest + * @returns {Promise<Array<{ file: string, markers: Array<{ index: number, label: string | null, after: string }>, error?: string }>>} + */ +export async function stalePatchMarkers(dir, manifest) { + const ids = new Set((manifest?.timeline ?? []).filter(isClip).map((e) => e.id)); + const out = []; + for (const name of await patchFilesOf(dir)) { + let patch; + try { + patch = JSON.parse(await readFile(path.join(dir, name), "utf8")); + } catch (e) { + out.push({ file: name, markers: [], error: e instanceof Error ? e.message : String(e) }); + continue; + } + const markers = patchMarkersOf(patch); + if (!markers) continue; + const gone = []; + markers.forEach((mk, index) => { + const after = isObj(mk) ? String(mk.after ?? "").trim() : ""; + if (after && !ids.has(after)) gone.push({ index, label: typeof mk.label === "string" ? mk.label : null, after }); + }); + if (gone.length) out.push({ file: name, markers: gone }); + } + return out; +} + +/** + * Settle a stale patch: every marker after a clip that is not in the cut + * takes the `after` of the CUT's marker with the same label (the manifest's + * own markers are re-anchored by every structural write, so they say where + * that section starts now). A marker no marker of the cut shares a label with + * is left as it is, and named. The file is rewritten whole, tmp + rename. + * + * @param {string} dir + * @param {Record<string, any>} manifest + * @param {string} file a `*.patch.json` beside the manifest, by name + * @returns {Promise<{ file: string, notes: string[], left: Array<{ index: number, label: string | null, after: string }> }>} + */ +export async function fixStalePatchMarkers(dir, manifest, file) { + if (!PATCH_FILE_RE.test(String(file ?? ""))) throw new Error(`${file} is not a take patch beside the manifest (*.patch.json)`); + const full = path.join(dir, file); + const patch = JSON.parse(await readFile(full, "utf8")); + const markers = patchMarkersOf(patch); + if (!markers) return { file, notes: [], left: [] }; + const ids = new Set((manifest?.timeline ?? []).filter(isClip).map((e) => e.id)); + const cut = Array.isArray(manifest?.render?.chrome?.deck?.markers) ? manifest.render.chrome.deck.markers : []; + const byLabel = new Map(cut.filter((mk) => isObj(mk) && typeof mk.label === "string" && ids.has(String(mk.after ?? "").trim())).map((mk) => [mk.label.trim(), String(mk.after).trim()])); + const notes = []; + const left = []; + markers.forEach((mk, index) => { + const after = isObj(mk) ? String(mk.after ?? "").trim() : ""; + if (!after || ids.has(after)) return; + const label = typeof mk.label === "string" ? mk.label : null; + const to = label ? byLabel.get(label.trim()) : undefined; + if (to) { + mk.after = to; + notes.push(`deck marker ${index} ("${label}") moved from after ${after} to after ${to}, where the cut's "${label}" is`); + } else left.push({ index, label, after }); + }); + if (notes.length) { + const tmp = `${full}.tmp-${process.pid}`; + await writeFile(tmp, `${JSON.stringify(patch, null, 2)}\n`); + await rename(tmp, full); + } + return { file, notes, left }; +} + +// ---- a section edit's markers (lane/ui-cut-editing, UI notes item 1) ------- +// +// A section edit (manifest.mjs moveToSection / addSection / moveSectionBoundary / +// removeSection / updateSection / splitClip / flashForward) removes no clip, so +// removedAnchors has nothing to say: the markers themselves moved. The rule is +// deliberately narrow: a patch whose markers were IN STEP with the manifest's +// before the edit (the same list, byte for byte) gets the new list; a patch whose +// markers already differed is somebody's deliberate variant, left as it is and +// named, never rewritten by a guess. A patch with no markers, or with a timeline +// of its own (patchMarkersOf), is not touched. The patch's own indent is kept. + +/** The indent a JSON file was written with (its first nested line), else 2: a rewrite keeps it. */ +export const indentOf = (text) => /^[[{]\r?\n( +)\S/.exec(String(text ?? ""))?.[1].length ?? 2; + +/** + * Bring every in-step patch's markers to `after` (the manifest's after the + * edit; [] or null: the patch's markers removed with them). + * + * @param {string} dir the project + * @param {unknown[] | null | undefined} before the manifest's markers before the edit + * @param {unknown[] | null | undefined} after the manifest's markers after it + * @returns {Promise<{ synced: string[], skipped: { file: string, why: string }[] }>} + */ +export async function syncSectionMarkers(dir, before, after) { + const synced = []; + const skipped = []; + const was = JSON.stringify(before ?? []); + const now = JSON.stringify(after ?? []); + if (was === now) return { synced, skipped }; + for (const name of await patchFilesOf(dir)) { + const file = path.join(dir, name); + let doc; + let text = ""; + try { + text = await readFile(file, "utf8"); + doc = JSON.parse(text); + } catch (e) { + skipped.push({ file: name, why: `does not parse (${e instanceof Error ? e.message : e}): not touched` }); + continue; + } + const mine = patchMarkersOf(doc); + if (!mine) continue; + if (JSON.stringify(mine) !== was) { + skipped.push({ file: name, why: "its markers were not the manifest's before this edit (a deliberate variant?): left as they are" }); + continue; + } + const deck = doc.render.chrome.deck; + if (Array.isArray(after) && after.length) deck.markers = JSON.parse(now); + else delete deck.markers; + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, JSON.stringify(doc, null, indentOf(text)) + "\n", "utf8"); + await rename(tmp, file); + synced.push(name); + } + return { synced, skipped }; +} diff --git a/umtool/lib/report/pieceWants.test.mjs b/umtool/lib/report/pieceWants.test.mjs @@ -0,0 +1,28 @@ +// A gapped clip's picture decodes per kept piece, the next primed before its join (playCut.mjs pieceWants). +import assert from "node:assert/strict"; +import test from "node:test"; +import { gapJoins, pieceWants, playPlan } from "./playCut.mjs"; + +// One clip, 10–40 s of its recording, 15–30 cut out: it plays 10–15 then 30–40 (15 s of cut). +const entries = [{ id: "a", type: "clip", video: "v", start: 10, end: 40, gaps: [{ from: 15, to: 30 }] }]; +const plan = playPlan([{ id: "a", start: 0, duration: 15 }], entries, { leadIn: 0 }); +const it = plan.items[0]; + +test("pieceWants: the piece playing; the next one primed within `ahead` of its join", () => { + const [join] = gapJoins(it); + assert.ok(join, "the plan carries the gap"); + // The cached window starts at source 5: media time is source − 5. + const early = pieceWants(it, join.at - 3, 5, { ahead: 2 }); + assert.deepEqual(early.map((w) => w.piece), [0], "3 s before the join: only the piece playing"); + const near = pieceWants(it, join.at - 1, 5, { ahead: 2 }); + assert.deepEqual(near.map((w) => w.piece), [0, 1]); + assert.equal(near[1].mediaTime, 25, "the next piece from its first second: source 30"); + const after = pieceWants(it, join.at + 0.5, 5, { ahead: 2 }); + assert.deepEqual(after.map((w) => w.piece), [1], "past the join: the second piece, nothing after it"); + assert.ok(Math.abs(after[0].mediaTime - 25.5) < 0.05); +}); + +test("pieceWants: a clip with no gaps is one piece", () => { + const p2 = playPlan([{ id: "b", start: 0, duration: 5 }], [{ id: "b", type: "clip", video: "v", start: 0, end: 5 }], { leadIn: 0 }); + assert.deepEqual(pieceWants(p2.items[0], 1, 0).map((w) => w.piece), [0]); +}); diff --git a/umtool/lib/report/placeIn.test.mjs b/umtool/lib/report/placeIn.test.mjs @@ -0,0 +1,154 @@ +// PLACE: a drop on Play's reel strip (sectionEdit.mjs placeIn, manifest.mjs placeEntries, +// `umtool timeline <p> place`): before an entry, into a section, the markers following. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; + +import { placeIn, sectionModel } from "./sectionEdit.mjs"; +import { MANIFEST_NAME, placeEntries, undoStructural } from "./manifest.mjs"; + +const clip = (id, start, end) => ({ type: "clip", id, video: "v1", start, end }); +// §0 a b | §1 "Two" c d | card k | §2 "Three" e f +const deckCut = () => ({ + slug: "s", + provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, + render: { + width: 1920, + height: 1080, + chrome: { engine: "hyperframes", layout: "deck", deck: { markers: [{ after: "b", label: "Two" }, { after: "d", label: "Three" }] } }, + }, + timeline: [clip("a", 10, 20), clip("b", 30, 40), clip("c", 50, 60), clip("d", 70, 80), { type: "card", id: "k", seconds: 3 }, clip("e", 90, 100), clip("f", 110, 120)], +}); +const ids = (m) => m.timeline.map((e) => e.id); +const afters = (m) => m.render.chrome.deck.markers.map((mk) => mk.after); +const secs = (m) => sectionModel(m).sections.map((s) => s.clips.join("")); + +test("within a section: the order changes, no boundary moves", () => { + const m = deckCut(); + const r = placeIn(m, ["a"], { before: "c", section: 0 }); + assert.deepEqual(ids(m), ["b", "a", "c", "d", "k", "e", "f"]); + assert.deepEqual(afters(m), ["a", "d"], "the marker that followed b follows a, the clip now last in §0"); + assert.deepEqual(secs(m), ["ba", "cd", "ef"]); + assert.equal(r.section, 0); + assert.equal(r.from, 0); + assert.equal(r.to, 1); +}); + +test("moving the clip a marker follows keeps the boundary where it was", () => { + const m = deckCut(); + placeIn(m, ["b"], { before: "a" }); + assert.deepEqual(ids(m), ["b", "a", "c", "d", "k", "e", "f"]); + assert.deepEqual(secs(m), ["ba", "cd", "ef"], "c and d stay in §1 (a plain `move` took the boundary with b)"); +}); + +test("at a seam the section decides: the end of §0 or the start of §1, the same slot", () => { + const end = deckCut(); + placeIn(end, ["e"], { before: "c", section: 0 }); + assert.deepEqual(ids(end), ["a", "b", "e", "c", "d", "k", "f"]); + assert.deepEqual(secs(end), ["abe", "cd", "f"]); + const start = deckCut(); + placeIn(start, ["e"], { before: "c", section: 1 }); + assert.deepEqual(ids(start), ["a", "b", "e", "c", "d", "k", "f"]); + assert.deepEqual(secs(start), ["ab", "ecd", "f"]); + // The default is the section of the clip it lands after. + const def = deckCut(); + assert.equal(placeIn(def, ["e"], { before: "c" }).section, 0); +}); + +test("across sections, inside one: the drop's section is the slot's", () => { + const m = deckCut(); + const r = placeIn(m, ["a"], { before: "f" }); + assert.deepEqual(ids(m), ["b", "c", "d", "k", "e", "a", "f"]); + assert.deepEqual(secs(m), ["b", "cd", "eaf"]); + assert.equal(r.section, 2); + assert.deepEqual(r.fromSections, { a: 0 }); + // At the end. + const m2 = deckCut(); + placeIn(m2, ["c"], { before: null }); + assert.deepEqual(ids(m2).slice(-1), ["c"]); + assert.deepEqual(secs(m2), ["ab", "d", "efc"]); +}); + +test("refused in words: an emptied section, a section the slot cannot be in, nothing to do", () => { + const m = deckCut(); + placeIn(m, ["c"], { before: "e", section: 2 }); + assert.throws(() => placeIn(m, ["d"], { before: "a", section: 0 }), /§1 \(Two\) would have no clip left/); + assert.throws(() => placeIn(deckCut(), ["a"], { before: "f", section: 0 }), /cannot join §0 \(the opening\)/); + assert.throws(() => placeIn(deckCut(), ["a"], { before: "b", section: 0 }), /already stands there in §0/); + assert.throws(() => placeIn(deckCut(), ["a"], { before: "a" }), /one of the entries being placed/); + assert.throws(() => placeIn(deckCut(), ["zz"], { before: "a" }), /no timeline entry with id zz/); + assert.throws(() => placeIn(deckCut(), ["a"], { before: "zz" }), /no timeline entry with id zz to place before/); +}); + +test("a section's only clip may move within its own seam; a card moves to the slot", () => { + const m = deckCut(); + // §1 down to one clip (d), then d moves across the card: still §1, alone. + placeIn(m, ["c"], { before: "a", section: 0 }); + placeIn(m, ["d"], { before: "e", section: 1 }); + assert.deepEqual(secs(m), ["cab", "d", "ef"]); + const k = deckCut(); + placeIn(k, ["k"], { before: "a" }); + assert.deepEqual(ids(k), ["k", "a", "b", "c", "d", "e", "f"]); + assert.deepEqual(secs(k), ["ab", "cd", "ef"]); +}); + +test("no deck: a plain move to the slot", () => { + const m = deckCut(); + delete m.render.chrome; + const r = placeIn(m, ["f"], { before: "a", section: 2 }); + assert.deepEqual(ids(m), ["f", "a", "b", "c", "d", "k", "e"]); + assert.equal(r.section, null); +}); + +async function project() { + const dir = await mkdtemp(path.join(tmpdir(), "place-")); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(deckCut(), null, 2) + "\n"); + // A take patch in step with the manifest's markers. + await writeFile(path.join(dir, "draft-1.patch.json"), JSON.stringify({ title: "x", render: { chrome: { deck: { markers: deckCut().render.chrome.deck.markers } } } }, null, 2) + "\n"); + return dir; +} + +test("placeEntries: one write, its own undo point every time, the take patch's markers in step", async () => { + const dir = await project(); + try { + const r1 = await placeEntries(dir, ["b"], { before: "f" }); + assert.ok(r1.snapshot?.rel && !r1.snapshot.skipped, "an undo point"); + assert.deepEqual(r1.sectionPatches.synced, ["draft-1.patch.json"]); + const patch = JSON.parse(await readFile(path.join(dir, "draft-1.patch.json"), "utf8")); + assert.deepEqual(patch.render.chrome.deck.markers.map((x) => x.after), ["a", "d"], "the boundary b followed is after a now, in the patch too"); + // A second drop straight after is its own undo point (no 2-minute coalescing). + await new Promise((res) => setTimeout(res, 1100)); + const r2 = await placeEntries(dir, ["c"], { before: "a", section: 0, token: r1.token }); + assert.ok(r2.snapshot?.rel && !r2.snapshot.skipped && r2.snapshot.rel !== r1.snapshot.rel); + // Undo takes back exactly the second. + await undoStructural(dir, { token: r2.token }); + const m = JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")); + assert.deepEqual(ids(m), ["a", "c", "d", "k", "e", "b", "f"]); + const snaps = (await readdir(path.join(dir, "revisions"))).filter((n) => n.includes("place")); + assert.equal(snaps.length, 2); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("umtool timeline place: the same writer from a terminal", async () => { + const dir = await project(); + const root = path.dirname(dir); + try { + const bin = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "bin", "umtool.mjs"); + const { stdout } = await promisify(execFile)(process.execPath, [bin, "timeline", dir, "place", "e", "--before", "c", "--section", "1"], { env: { ...process.env, REPORTS_DIR: root } }); + assert.match(stdout, /placed e before c \(index 5 -> 2\) in §1 \(Two\)/); + assert.match(stdout, /undo point: revisions\//); + const m = JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")); + assert.deepEqual(secs(m), ["ab", "ecd", "f"]); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/playCut.mjs b/umtool/lib/report/playCut.mjs @@ -469,3 +469,34 @@ export function dateKeyLabel(k) { const d = k % 100; return m >= 1 && m <= 12 ? `${d} ${MON[m - 1]} ${y}` : null; } + +/** + * WHAT TO DECODE FOR A GAPPED CLIP (the picture's half of a jump cut): the + * kept piece playing at cut second t, and -- when the next join is at most + * `ahead` cut seconds away -- the piece after it, from its first second. Play + * keeps one WebCodecs decoder per piece (codecPicture.ts keys `<url>#p<k>`), + * so the piece after a long gap is decoded BEFORE the join: one decoder that + * jumped at the join had to seek to a keyframe, fetch its block and decode up + * through a long GOP, and the picture held its last frame 2-4 s while the + * sound had already jumped. `mediaTime` is in the window's own seconds + * (source minus `mediaFrom`, the cached file's first second). + * + * @param {PlayItem} item + * @param {number} t + * @param {number} mediaFrom + * @param {{ ahead?: number }} [o] + * @returns {Array<{ piece: number, mediaTime: number }>} + */ +export function pieceWants(item, t, mediaFrom, { ahead = 2 } = {}) { + const src = sourceAt(item, t) ?? item?.clip?.sourceFrom ?? 0; + const gaps = item?.clip?.gaps ?? []; + let k = 0; + for (const g of gaps) if (src >= g.to - 1e-6) k += 1; + const out = [{ piece: k, mediaTime: Math.max(0, src - mediaFrom) }]; + const g = gaps[k]; + if (g) { + const at = cutAtSource(item, g.from); + if (at >= t - 1e-6 && at - t <= ahead) out.push({ piece: k + 1, mediaTime: Math.max(0, g.to - mediaFrom) }); + } + return out; +} diff --git a/umtool/lib/report/playDecodes.test.mjs b/umtool/lib/report/playDecodes.test.mjs @@ -0,0 +1,120 @@ +// What the Play view decodes of each clip's sound (playSchedule.mjs decodesOf, +// bankTrim.mjs coveringSlot): a gapped clip per kept piece, never its gaps; +// pieces under a second apart as one; and one decode per clip across the +// manifest's edges and the render's -- the render's play from the decode made +// while they were measured, found by what it covers. +// +// Run with: node --test lib/report/playDecodes.test.mjs +import assert from "node:assert/strict"; +import test from "node:test"; + +import { coveringSlot } from "./bankTrim.mjs"; +import { playPlan } from "./playCut.mjs"; +import { EDGE_SLACK, MERGE_GAP, audioSpans, decodesOf, scheduleFrom } from "./playSchedule.mjs"; + +const WIN = { from: 0, to: 600 }; + +/** The engine's prefetch, as arithmetic: each span's decode found by what it covers, else asked for (a new slot). */ +function resolveAll(slots, id, decodes) { + const asked = []; + const keys = decodes.map((d) => { + const have = coveringSlot(slots, `${id}|`, d.need); + if (have) return have; + const key = `${id}|${d.ask.from}|${d.ask.to}`; + if (!slots.some((s) => s.key === key)) { + slots.push({ key, state: "loading", used: slots.length, span: d.ask }); + asked.push(d.ask); + } + return key; + }); + return { keys, asked }; +} +const secondsOf = (asks) => Math.round(asks.reduce((n, a) => n + (a.to - a.from), 0) * 1000) / 1000; +const spansOf = (plan, id) => audioSpans(plan).filter((s) => s.id === id); + +// lw1's shape: an 88 s span of which about 25 s plays (three gaps). +const lw1 = { id: "lw1", type: "clip", video: "v", start: 100, end: 188, gaps: [{ from: 106, to: 130 }, { from: 138, to: 160 }, { from: 166, to: 183 }] }; +const lw1Plan = (cuts = null) => playPlan([{ id: "lw1", start: 0, duration: 25 }], [lw1], { leadIn: 0, cuts }); + +test("a gapped clip is decoded per kept piece: the 25 s it plays and the pads, never its 63 s of gaps", () => { + const spans = spansOf(lw1Plan(), "lw1"); + assert.deepEqual(spans.map((s) => s.piece), [0, 1, 2, 3], "one span per piece, each carrying its piece"); + const ds = decodesOf(spans, { within: WIN }); + const { asked } = resolveAll([], "lw1", ds); + assert.equal(asked.length, 4, "four pieces, four decodes"); + assert.deepEqual(asked, [{ from: 99.75, to: 106.25 }, { from: 129.75, to: 138.25 }, { from: 159.75, to: 166.25 }, { from: 182.75, to: 188.25 }]); + assert.equal(secondsOf(asked), 25 + 4 * 0.5, "the kept seconds and a quarter second either side of each"); + // Each node reads inside its own decode. + for (const d of ds) assert.ok(d.ask.from <= d.need.from && d.ask.to >= d.need.to); +}); + +test("pieces under MERGE_GAP apart share one decode; further apart they do not", () => { + const spans = [{ src: 10, srcTo: 14 }, { src: 14.6, srcTo: 18 }, { src: 25, srcTo: 30 }]; + const ds = decodesOf(spans, { within: WIN }); + assert.ok(MERGE_GAP > 0.6 && MERGE_GAP < 7); + assert.deepEqual(ds.map((d) => d.ask), [{ from: 9.75, to: 18.25 }, { from: 9.75, to: 18.25 }, { from: 24.75, to: 30.25 }]); + assert.equal(resolveAll([], "x", ds).asked.length, 2, "two requests for three pieces"); +}); + +test("a decode stays inside the cached window (the route clamps to it), and a node's seconds with it", () => { + const ds = decodesOf([{ src: 0.1, srcTo: 5 }], { within: { from: 0.05, to: 4.9 }, slack: EDGE_SLACK }); + assert.deepEqual(ds[0].ask, { from: 0.05, to: 4.9 }); + assert.deepEqual(ds[0].need, { from: 0.1, to: 4.9 }); + assert.equal(coveringSlot([{ key: "x|a", state: "ready", used: 1, span: ds[0].ask }], "x|", ds[0].need), "x|a", "covered: never asked again"); +}); + +// The render snaps each clip's edges to a silence: up to a second or so either way (cutPoints.mjs). +const plain = { id: "nt1", type: "clip", video: "v", start: 200, end: 281 }; +const plainPlan = (cuts = null) => playPlan([{ id: "nt1", start: 0, duration: 81 }], [plain], { leadIn: 0, cuts }); + +test("measuring, then the render's edges: ONE decode of a plain clip -- the render's play from the wide one", () => { + const slots = []; + // While the render's edges are measured: the manifest's, EDGE_SLACK wider at both ends. + const first = resolveAll(slots, "nt1", decodesOf(spansOf(plainPlan(), "nt1"), { slack: EDGE_SLACK, within: WIN })); + assert.equal(first.asked.length, 1); + assert.deepEqual(first.asked[0], { from: 200 - 0.25 - EDGE_SLACK, to: 281 + 0.25 + EDGE_SLACK }); + slots[0].state = "ready"; + // The render's land: the start 1.1 s earlier, the end 1.4 s later. + const render = plainPlan(new Map([["nt1", { cutStart: 198.9, cutEnd: 282.4 }]])); + const second = resolveAll(slots, "nt1", decodesOf(spansOf(render, "nt1"), { within: WIN })); + assert.equal(second.asked.length, 0, "nothing asked for again"); + assert.deepEqual(second.keys, [slots[0].key], "the render's span plays from the manifest's decode"); + // A node from any second of it reads inside that decode (offset src − its first second, as the engine starts it). + for (const p of scheduleFrom(audioSpans(render), 30)) { + assert.ok(p.src >= slots[0].span.from && p.srcTo <= slots[0].span.to); + } +}); + +test("without the slack the render's wider edges would be a second decode (why it is there)", () => { + const slots = []; + resolveAll(slots, "nt1", decodesOf(spansOf(plainPlan(), "nt1"), { within: WIN })); + const render = plainPlan(new Map([["nt1", { cutStart: 198.9, cutEnd: 282.4 }]])); + assert.equal(resolveAll(slots, "nt1", decodesOf(spansOf(render, "nt1"), { within: WIN })).asked.length, 1); +}); + +test("a gapped clip across the two sets of edges: its pieces decoded once, the outer ones wide", () => { + const slots = []; + const first = resolveAll(slots, "lw1", decodesOf(spansOf(lw1Plan(), "lw1"), { slack: EDGE_SLACK, within: WIN })); + assert.equal(first.asked.length, 4); + assert.equal(first.asked[0].from, 100 - 0.25 - EDGE_SLACK, "the first piece wide at the clip's start"); + assert.equal(first.asked[3].to, 188 + 0.25 + EDGE_SLACK, "the last piece wide at its end"); + assert.equal(first.asked[1].from, 129.75, "an inner piece only padded: a gap's edges are exact"); + // The render's: its edges snapped, its gaps on the frame grid (within a frame of the manifest's). + const render = lw1Plan(new Map([["lw1", { + cutStart: 99.2, cutEnd: 189.1, + gaps: [{ from: 106.0, to: 130.033 }, { from: 137.967, to: 160.0 }, { from: 166.033, to: 183.0 }], + }]])); + const second = resolveAll(slots, "lw1", decodesOf(spansOf(render, "lw1"), { within: WIN })); + assert.equal(second.asked.length, 0, "every render piece inside a decode already made"); + assert.deepEqual(second.keys, first.keys); + assert.ok(secondsOf(first.asked) < 25 + 4 * 0.5 + 2 * EDGE_SLACK + 1e-9, "the kept seconds, the pads and the slack: not the 88 s span"); +}); + +test("a render that cuts differently (a montage's phrase: no gaps) asks only for what nothing covers", () => { + const slots = []; + resolveAll(slots, "lw1", decodesOf(spansOf(lw1Plan(), "lw1"), { slack: EDGE_SLACK, within: WIN })); + const render = lw1Plan(new Map([["lw1", { cutStart: 101, cutEnd: 105.5 }]])); + assert.equal(resolveAll(slots, "lw1", decodesOf(spansOf(render, "lw1"), { within: WIN })).asked.length, 0, "inside the first piece's decode"); + const wide = lw1Plan(new Map([["lw1", { cutStart: 101, cutEnd: 140 }]])); + assert.equal(resolveAll(slots, "lw1", decodesOf(spansOf(wide, "lw1"), { within: WIN })).asked.length, 1, "across a gap no piece covers: asked once"); +}); diff --git a/umtool/lib/report/playSchedule.mjs b/umtool/lib/report/playSchedule.mjs @@ -83,7 +83,10 @@ const ramp = (a, b, down = false) => (b > a ? [[a, down ? 1 : 0], [b, down ? 0 : * sourceFrom: number, sourceTo: number, playEnd: number, hold: number, * sound?: [number, number], gainDb?: number, audio?: Record<string, number>, muteFrom?: number, soundFrom?: number, * gaps?: Array<{ from: number, to: number }> } }> }} plan - * @returns {Array<{ id: string, index: number, from: number, to: number, src: number, srcTo: number, env: Envelope, gain: number }>} + * `piece` is the span's place among its clip's (0 for a clip with no gaps): + * what its decode is looked up by (decodesOf). + * + * @returns {Array<{ id: string, index: number, piece: number, from: number, to: number, src: number, srcTo: number, env: Envelope, gain: number }>} */ export function audioSpans(plan) { const items = plan?.items ?? []; @@ -125,7 +128,7 @@ export function audioSpans(plan) { const shift = fin(a.offset) ? a.offset / 1000 : 0; if (!gaps) { out.push({ - id: it.id, index: i, from, to, + id: it.id, index: i, piece: 0, from, to, src: r6(c.sourceFrom - shift), srcTo: r6(c.sourceFrom - shift + (to - from)), env: multiply(envs, from, to), gain: r6(10 ** (db / 20)), @@ -142,7 +145,7 @@ export function audioSpans(plan) { if (k > 0) joins.push(ramp(p.a, p.a + d)); if (k < pieces.length - 1) joins.push(ramp(p.b - d, p.b, true)); out.push({ - id: it.id, index: i, from: r6(p.a), to: r6(p.b), + id: it.id, index: i, piece: k, from: r6(p.a), to: r6(p.b), src: r6(p.src - shift), srcTo: r6(p.src - shift + (p.b - p.a)), env: multiply([...envs, ...joins], p.a, p.b), gain: r6(10 ** (db / 20)), @@ -175,6 +178,7 @@ export function scheduleFrom(spans, t, rate = 1, { until = Infinity } = {}) { out.push({ id: s.id, index: s.index, + piece: s.piece ?? 0, atWall: r6((begin - t) / r), durWall: r6((s.to - begin) / r), src: r6(s.src + (begin - s.from)), @@ -190,7 +194,8 @@ export function scheduleFrom(spans, t, rate = 1, { until = Infinity } = {}) { export const cutTimeAtCtx = (t0, ctxStart, now, rate = 1) => t0 + Math.max(0, now - ctxStart) * (rate > 0 ? rate : 1); /** - * Which span of a clip's source to decode for Play: its whole sound + * One span's decode (the engine's are decodesOf, below: per kept piece, and + * found by what they cover). Which span of a clip's source to decode for Play: its whole sound * (offset included) and a little either side, so a seek and a crossfade read * inside one buffer. Bounded: a clip is seconds, never a recording. * @@ -201,3 +206,63 @@ export function decodeSpanOf(span, { pad = 0.25, max = 120 } = {}) { const from = Math.max(0, span.src - pad); return { from: Math.round(from * 1000) / 1000, to: Math.round(Math.min(span.srcTo + pad, from + max) * 1000) / 1000 }; } + +/** + * How far the render may move a clip's OUTER edge from the manifest's (s): + * render.snapWindow's default (1.6, snap.mjs SNAP_DEFAULTS) and the snap's + * tail (0.18), rounded up. While the render's edges are being measured + * (useRenderCuts `measuring`) a clip's sound is decoded this much wider at + * its two ends, so the decode on the manifest's edges is the one the render's + * play from too -- found by what it covers (bankTrim.mjs coveringSlot), not + * asked for again. A cut that snaps further (a wider `snapWindow`, a montage's + * phrase cut) asks again for what it does not cover. + */ +export const EDGE_SLACK = 2; +/** Kept pieces of a gapped clip less than this far apart (source s) are decoded as one. */ +export const MERGE_GAP = 1; + +const msDown = (v) => Math.floor(v * 1000 + 1e-6) / 1000; +const msUp = (v) => Math.ceil(v * 1000 - 1e-6) / 1000; + +/** + * WHAT TO DECODE FOR ONE CLIP'S SOUND: for each of its spans (audioSpans, one + * per kept piece, in order), the source seconds its node reads (`need`) and + * the span to ask the audio route for when no decode held covers them + * (`ask`). A clip with gaps is decoded PER PIECE -- never its gaps: a clip + * that keeps 25 s of an 88 s span decodes 25 s and the pads -- except that + * pieces under `merge` apart share one decode (one request, not several + * for a few hundred ms saved). Each decode is the pieces' sound and `pad` + * either side (a seek and a crossfade read inside it), the clip's outer two + * edges `slack` more (EDGE_SLACK while the render's edges are measured, else + * 0); all of it inside the cached window (`within`: the route clamps to it + * too), at most `max` long. + * + * @param {Array<{ src: number, srcTo: number }>} spans the clip's, in order + * @param {{ pad?: number, slack?: number, merge?: number, max?: number, within?: { from: number, to: number } | null }} [opts] + * @returns {Array<{ need: { from: number, to: number }, ask: { from: number, to: number } }>} one per span + */ +export function decodesOf(spans, { pad = 0.25, slack = 0, merge = MERGE_GAP, max = 120, within = null } = {}) { + const lo = within && fin(within.from) ? within.from : 0; + const hi = within && fin(within.to) ? within.to : Infinity; + const clamp = (v) => Math.min(hi, Math.max(lo, v)); + /** @type {number[][]} */ + const groups = []; + spans.forEach((s, k) => { + const g = groups[groups.length - 1]; + if (g && s.src - spans[g[g.length - 1]].srcTo < merge) g.push(k); + else groups.push([k]); + }); + const out = new Array(spans.length); + groups.forEach((g, n) => { + const a = spans[g[0]]; + const b = spans[g[g.length - 1]]; + const from = msDown(clamp(Math.max(0, a.src - pad - (n === 0 ? slack : 0)))); + const to = msUp(Math.min(clamp(b.srcTo + pad + (n === groups.length - 1 ? slack : 0)), from + max)); + for (const k of g) { + const s = spans[k]; + const nf = clamp(s.src); + out[k] = { need: { from: r6(nf), to: r6(Math.max(nf, clamp(s.srcTo))) }, ask: { from, to } }; + } + }); + return out; +} diff --git a/umtool/lib/report/playTakeGaps.test.mjs b/umtool/lib/report/playTakeGaps.test.mjs @@ -0,0 +1,101 @@ +// Play the cut ON A TAKE with gaps inside a clip (operator, 1 Nov 2026: a +// gapped clip reported playing whole in a take's Play the cut while the take's +// render left the gap out). A take plays the project's manifest NOW with its +// patch (takeManifest.mjs), so a gap the project's clip carries -- written +// before or after the take was made -- is in the take's view, its plan and its +// sound, exactly as in the project's own: one item, one sound span per kept +// piece, on the estimate's clock and on the render's edges (the cut-points +// route's shape). A patch that turns the deck and its effects on (draft-21's) +// changes none of that. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +const GAPS = [{ from: 12, to: 13 }, { from: 15, to: 15.5 }]; +const manifest = () => ({ + slug: "t", + title: "The cut", + provenance: { channelSlug: "testchan", siteOrigin: "https://archive.example" }, + render: { width: 1920, height: 1080, fps: 30, transition: 0 }, + timeline: [ + { type: "clip", id: "a", video: "v1", start: 10, end: 18, lock: true, gaps: GAPS }, + { type: "clip", id: "b", video: "v2", start: 100, end: 103, lock: true }, + ], +}); + +async function fixture() { + const root = await mkdtemp(path.join(tmpdir(), "play-take-gaps-")); + // Never the real corpus: the play view looks for cached windows under the channels dir. + process.env.CHANNELS_DIR = path.join(root, "channels"); + const dir = path.join(root, "p"); + await mkdir(path.join(dir, "takes", "t1"), { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest())); + await writeFile( + path.join(dir, "takes", "t1", "take.json"), + JSON.stringify({ + id: "t1", group: "takes", order: 1, label: "Take one", kind: "different", preview: "preview.mp4", window: "full", + // draft-21's shape: a retitle and the deck with its effects on, no timeline of its own. + patch: { title: "The cut, a take", render: { chrome: { engine: "hyperframes", layout: "deck", deck: {}, fx: { zoom: {} } } } }, + }), + ); + return { root, project: { id: "p", dir } }; +} + +/** The render's edges as the cut-points route returns them: the cut, its gaps, the kept footage. */ +const CUTS = new Map([ + ["a", { cutStart: 10, cutEnd: 18, gaps: GAPS, footage: 6.5 }], + ["b", { cutStart: 100, cutEnd: 103, footage: 3 }], +]); + +test("a take's view, plan and sound keep the project's gaps: one item, one span per kept piece", async () => { + const { root, project } = await fixture(); + try { + const { playView } = await import("./playView.mjs"); + const { playPlan } = await import("./playCut.mjs"); + const { audioSpans } = await import("./playSchedule.mjs"); + const pieces = (view, cuts) => + audioSpans(playPlan(view.segments, view.entries, { leadIn: view.leadIn, cuts })) + .filter((s) => s.id === "a") + .map((s) => [s.src, s.srcTo]); + const cut = await playView(project); + const take = await playView(project, { take: "t1" }); + assert.equal(take.take?.id, "t1"); + assert.equal(take.title, "The cut, a take"); + assert.equal(take.deckOn, true, "the take's patch turns the deck on"); + assert.deepEqual(take.entries.find((e) => e.id === "a")?.gaps, GAPS, "the take's entry carries the project's gaps"); + // The render's edges: the kept pieces, the same for the take as for the cut. + const kept = [[10, 12], [13, 15], [15.5, 18]]; + assert.deepEqual(pieces(take, CUTS), kept); + assert.deepEqual(pieces(cut, CUTS), kept); + // The estimate's clock (before the edges are measured): one span per piece too, never the whole window. + const est = pieces(take, null); + assert.equal(est.length, 3); + assert.deepEqual(est, pieces(cut, null)); + const item = playPlan(take.segments, take.entries, { leadIn: take.leadIn, cuts: CUTS }).items.find((i) => i.id === "a"); + assert.deepEqual(item?.clip?.gaps, GAPS); + assert.equal(Math.round((item.clip.playEnd - item.start) * 1000) / 1000, 6.5, "its footage is the kept seconds"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a gap written to the project after the take was made plays in the take", async () => { + const { root, project } = await fixture(); + try { + const m = manifest(); + m.timeline[1].gaps = [{ from: 101, to: 102 }]; + await writeFile(path.join(project.dir, "video.manifest.json"), JSON.stringify(m)); + const { playView } = await import("./playView.mjs"); + const { playPlan } = await import("./playCut.mjs"); + const { audioSpans } = await import("./playSchedule.mjs"); + const take = await playView(project, { take: "t1" }); + const spans = audioSpans(playPlan(take.segments, take.entries, { leadIn: take.leadIn })).filter((s) => s.id === "b"); + assert.deepEqual(spans.map((s) => [s.src, s.srcTo]), [[100, 101], [102, 103]]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -16,6 +16,9 @@ import { rejectionOf } from "./rejectReasons.mjs"; import { dateKeyLabel } from "./playCut.mjs"; import { pickWindow, projectCache, windowVersion, windowsFor } from "./serve.mjs"; import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs"; +import { readWorkingCut } from "./workingCut.mjs"; +import { sectionModel } from "./sectionEdit.mjs"; +import { manifestToken } from "./manifest.mjs"; const fin = (v) => typeof v === "number" && Number.isFinite(v); const text = (v) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim() : ""); @@ -27,21 +30,41 @@ export function headingOf(e) { } /** + * WHAT PLAYS BY DEFAULT is the LATEST take (operator, 1 Nov 2026): with no + * `take`, the newest working take (workingCut.mjs) -- the project's manifest + * as it is now with that take's patch, so the look is the next draft's and + * every edit since shows. `bare` plays the manifest alone (`?cut=1`). The + * working cut's name rides along (`working`) for the label. + * * @param {{ id: string, dir: string }} project - * @param {{ take?: string | null }} [opts] + * @param {{ take?: string | null, bare?: boolean }} [opts] */ -export async function playView(project, { take = null } = {}) { +export async function playView(project, { take = null, bare = false } = {}) { const base = await readManifest(project.dir); if (!base) return { error: "this project has no video.manifest.json" }; + const working = await readWorkingCut(project.dir, { + resolveNow: async (id) => (await resolveTakeManifest(project.dir, id, { base })).manifest, + }).catch(() => null); + const defaulted = !take && !bare && !!working?.latest; + if (defaulted) take = working.latest.id; let manifest = base; - /** @type {null | { id: string, label: string, summary: string, made: boolean, from: string }} */ + /** @type {null | { id: string, label: string, summary: string, made: boolean, from: string, ownTimeline: boolean, defaulted: boolean }} */ let takeInfo = null; let note = null; if (take) { try { - const r = await resolveTakeManifest(project.dir, take); + const r = await resolveTakeManifest(project.dir, take, { base }); manifest = r.manifest; - takeInfo = { id: r.take.id, label: r.take.label, summary: r.take.summary, made: r.take.made, from: r.take.from }; + takeInfo = { + id: r.take.id, + label: r.take.label, + summary: r.take.summary, + made: r.take.made, + from: r.take.from, + // A patch that brings its own timeline: edits to the project's cut do not show in it (its walk edits it). + ownTimeline: Array.isArray(/** @type {any} */ (r.take.patch)?.timeline), + defaulted, + }; note = r.note; } catch (e) { return { error: e instanceof Error ? e.message : String(e) }; @@ -119,14 +142,29 @@ export async function playView(project, { take = null } = {}) { 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 : "" })) : []; + // THE SECTIONS A DROP LANDS IN: the project's manifest's (what a reorder writes), each clip's + // section and each section's label and colour (sectionEdit.mjs sectionModel) -- as many as + // the markers make, no limit assumed here. + const model = sectionModel(base); + // A take whose patch sets its OWN markers, out of step with the cut's (patchMarkers.mjs: a patch + // not synced): a drop moves the cut's clips and sections, and this take keeps showing its own. + const markersOf = (m) => JSON.stringify(m?.render?.chrome?.deck?.markers ?? null); + const sectionsDiffer = !!takeInfo && markersOf(selected) !== markersOf(selectVariant(base, DEFAULT_VARIANT)); + const sections = model.sections.map((x) => ({ index: x.index, label: x.label, color: x.color, marker: x.marker, count: x.clips.length })); return { project: project.id, title: text(manifest.title) || project.id, + sections, + sectionOf: Object.fromEntries(model.sectionOf), + sectionsDiffer, + // The manifest's token: a reorder written from a view older than the file is refused (409), not lost. + token: await manifestToken(project.dir), counter, markers, take: takeInfo, note, takes: await playableTakes(project.dir), + working, leadIn: fin(render.leadIn) ? render.leadIn : 0.4, transition: D, blurRendered: render.blur !== "off", diff --git a/umtool/lib/report/sectionEdit.mjs b/umtool/lib/report/sectionEdit.mjs @@ -0,0 +1,399 @@ +// SECTIONS OF A DECK CUT, edited as sections (UI notes 2026-10-30, item 1). +// +// Under the deck a cut's sections ARE its markers (`render.chrome.deck.markers`, +// report-to-video deck.mjs `railSections`): section 0 runs from the start to +// the first marker's boundary, and a marker `{ after: <clip>, label?, color? }` +// opens the next section right after that clip -- its label and colour are the +// NEW section's. So "move this clip to section 3" is two edits that must land +// together: the clip moves in the timeline, and every marker whose boundary the +// move crosses follows, or the clip lands in the wrong section (or a section +// ends up empty, or two markers cross). Doing that by `timeline move --to` +// index arithmetic went wrong twice on the Ember cut. +// +// Everything here is PURE: each function mutates the manifest it is handed and +// returns what it did in words. manifest.mjs runs them inside a structural +// write (the lock, the token, the build's checks, the undo point), and syncs +// the take patches' markers after (patchMarkers.mjs syncSectionMarkers). +// +// The rules, each refused in words rather than repaired silently: +// - a section never ends up with no clip (two markers on one boundary); +// - a boundary never moves past its neighbours (markers never cross); +// - a marker never follows the last clip (a section after it is empty); +// - markers stay within the deck's own limits (validateChrome says so). + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const isClip = (e) => !!e && (e.kind ?? e.type) === "clip"; + +/** The deck's markers as written (an array, maybe empty), or null without a deck. */ +function deckMarkers(m) { + const chrome = m?.render?.chrome; + if (!isObj(chrome)) return null; + const d = isObj(chrome.deck) ? chrome.deck : null; + return Array.isArray(d?.markers) ? d.markers : []; +} + +function needDeck(m) { + const chrome = m?.render?.chrome; + if (!isObj(chrome)) throw new Error("sections are the on-screen deck's markers, and this manifest has no deck — turn the deck on first"); + if (!isObj(chrome.deck)) chrome.deck = {}; + if (!Array.isArray(chrome.deck.markers)) chrome.deck.markers = []; + return chrome.deck.markers; +} + +/** + * The cut's sections, read from its markers. + * + * `sections[i]`: `{ index, label, color, marker, clips, first, last }` -- + * `marker` is the index into `deck.markers` that opens it (null for section + * 0), `clips` its clip ids in order, `first`/`last` its first and last clip. + * `sectionOf` maps a clip id to its section; `entrySection[i]` is the section + * of timeline entry i (a card belongs to the section it stands in). Markers + * naming no clip of the timeline are left out (`stray`: their indexes). + * + * @param {Record<string, any>} m + */ +export function sectionModel(m) { + const tl = Array.isArray(m?.timeline) ? m.timeline : []; + const markers = deckMarkers(m) ?? []; + const pos = new Map(); + tl.forEach((e, i) => { + if (isClip(e) && !pos.has(e.id)) pos.set(e.id, i); + }); + const placed = []; + const stray = []; + markers.forEach((mk, k) => { + const p = isObj(mk) ? pos.get(String(mk.after ?? "").trim()) : undefined; + if (p === undefined) stray.push(k); + else placed.push({ k, mk, pos: p }); + }); + placed.sort((a, b) => a.pos - b.pos || a.k - b.k); + const pal = m?.render?.palette ?? {}; + const key = m?.render?.chrome?.deck?.pip?.sectionColor0; + const color0 = typeof key === "string" && /^#[0-9a-f]{3,8}$/i.test(key) ? key : (key && pal[key]) || pal.accent || null; + const sections = [ + { index: 0, label: null, color: color0, marker: null, clips: [], first: null, last: null }, + ...placed.map((p, i) => ({ + index: i + 1, + label: typeof p.mk.label === "string" && p.mk.label.trim() ? p.mk.label.trim() : null, + color: typeof p.mk.color === "string" && p.mk.color.trim() ? p.mk.color.trim() : null, + marker: p.k, + clips: [], + first: null, + last: null, + })), + ]; + const sectionOf = new Map(); + const entrySection = []; + let s = 0; + let next = 0; + tl.forEach((e, i) => { + entrySection[i] = s; + if (isClip(e)) { + if (!sectionOf.has(e.id)) sectionOf.set(e.id, s); + sections[s].clips.push(e.id); + sections[s].first ??= e.id; + sections[s].last = e.id; + } + while (next < placed.length && placed[next].pos === i) { + next += 1; + s = next; + } + }); + return { sections, sectionOf, entrySection, stray, placed }; +} + +/** "§3 (Leaves it open)" -- how a sentence names a section. */ +export const sectionWords = (s) => `§${s.index}${s.label ? ` (${s.label})` : s.index === 0 ? " (the opening)" : ""}`; + +/** + * Each marker's `after` again, from what section each clip is in: marker + * opening section i follows the last clip of section i-1. `membership` maps a + * clip id to its section; the timeline is in section order already. Refuses a + * section left with no clip. Returns one sentence per marker that moved. + */ +function reanchorMarkers(m, model, membership) { + const tl = m.timeline; + const markers = deckMarkers(m) ?? []; + const lastIn = new Map(); + const count = new Map(); + for (const e of tl) { + if (!isClip(e) || !membership.has(e.id)) continue; + const s = membership.get(e.id); + lastIn.set(s, e.id); + count.set(s, (count.get(s) ?? 0) + 1); + } + const notes = []; + for (const sec of model.sections) { + if (!count.get(sec.index)) { + throw new Error(`${sectionWords(sec)} would have no clip left — remove its boundary first (umtool timeline <project> section-remove ${sec.marker ?? 0}), or move a clip into it`); + } + } + for (const sec of model.sections.slice(1)) { + const mk = markers[sec.marker]; + const after = lastIn.get(sec.index - 1); + if (mk.after !== after) { + notes.push(`marker ${sec.marker}${mk.label ? ` ("${mk.label}")` : ""} moved from after ${mk.after} to after ${after}`); + mk.after = after; + } + } + return notes; +} + +/** + * MOVE TO SECTION: clips `ids` (in the order they stand in the cut) to the end + * of section `target` -- or its start with `position: "start"` -- with every + * marker following so each section keeps the clips it had, plus these. + * + * @param {Record<string, any>} m + * @param {string[]} ids + * @param {number} target + * @param {{ position?: "start" | "end", allowNoop?: boolean }} [opts] `allowNoop`: a clip already there is no refusal + */ +export function moveToSectionIn(m, ids, target, { position = "end", allowNoop = false } = {}) { + const model = sectionModel(m); + if (deckMarkers(m) === null) needDeck(m); + const t = Number(target); + if (!Number.isInteger(t) || t < 0 || t >= model.sections.length) { + throw new Error(`section must be 0–${model.sections.length - 1} (§0 is before the first marker)`); + } + if (position !== "start" && position !== "end") throw new Error('position is "start" or "end"'); + const want = [...new Set((Array.isArray(ids) ? ids : [ids]).map((x) => String(x ?? "").trim()).filter(Boolean))]; + if (!want.length) throw new Error("name one or more clips to move"); + const tl = m.timeline; + for (const id of want) { + const e = tl.find((x) => x?.id === id); + if (!e) throw new Error(`no timeline entry with id ${id}`); + if (!isClip(e)) throw new Error(`${id} is a ${e.type ?? "non-clip"} entry: a section move takes clips (a card stays where it stands)`); + if (tl.filter((x) => x?.id === id).length > 1) throw new Error(`${id} is in the timeline more than once — move one twin with \`timeline move\``); + } + const membership = new Map(model.sectionOf); + const from = new Map(want.map((id) => [id, membership.get(id)])); + for (const id of want) membership.set(id, t); + const moving = new Set(want); + const moved = tl.filter((e) => isClip(e) && moving.has(e.id)); + const rest = tl.filter((e) => !(isClip(e) && moving.has(e.id))); + // The remaining clips are still in section order: the end of `t` is just + // after the last clip at or before it, its start just after the last clip + // before it (a card opening the next section stays after the moved clips). + let at = 0; + rest.forEach((e, i) => { + if (!isClip(e)) return; + const s = membership.get(e.id); + if (position === "end" ? s <= t : s < t) at = i + 1; + }); + rest.splice(at, 0, ...moved); + const before = tl.map((e) => e?.id).join("\n"); + m.timeline.splice(0, m.timeline.length, ...rest); + const reanchored = reanchorMarkers(m, model, membership); + const changed = before !== m.timeline.map((e) => e?.id).join("\n"); + if (!changed && !reanchored.length && !allowNoop) throw new Error(`${want.join(", ")} already ${want.length === 1 ? "stands" : "stand"} at the ${position} of ${sectionWords(model.sections[t])}`); + return { + ids: moved.map((e) => e.id), + section: t, + label: model.sections[t].label, + from: Object.fromEntries(from), + position, + reanchored, + }; +} + +/** + * PLACE (a drop on Play's reel strip, 1 Nov 2026): entries `ids` -- in the + * order they stand in the cut -- land right before entry `before` (null: at + * the end), and the CLIPS among them join section `section`; every other clip + * keeps the section it is in, and the markers are re-anchored so that holds. + * One edit for "drag c04 between o01 and o02" whatever the boundaries do -- + * `timeline move --to` index arithmetic moved a boundary with the clip it + * followed. + * + * `section` defaults to the section of the clip the drop lands next to (the + * one before it, else the one after). It must be one the slot can belong to: + * between a clip of §a and a clip of §b the moved clips join §a, §b, or a + * section between them that has no other clip left (a section's only clip + * moved within its own seam). Anything else is refused in words, as an emptied + * section is. A card (not a clip) is moved to the slot and belongs to no + * section of its own. + * + * The section model is the deck's markers (sectionModel): nothing here + * assumes a flat list of at most N sections, nor knows the limit. + * + * @param {Record<string, any>} m + * @param {string[] | string} ids + * @param {{ before?: string | null, section?: number | null }} [opts] + */ +export function placeIn(m, ids, { before = null, section = null } = {}) { + const tl = m.timeline; + if (!Array.isArray(tl)) throw new Error("the manifest has no timeline"); + const want = [...new Set((Array.isArray(ids) ? ids : [ids]).map((x) => String(x ?? "").trim()).filter(Boolean))]; + if (!want.length) throw new Error("name one or more entries to place"); + for (const id of want) { + const n = tl.filter((x) => x?.id === id).length; + if (!n) throw new Error(`no timeline entry with id ${id}`); + if (n > 1) throw new Error(`${id} is in the timeline more than once — move one twin with \`timeline move\``); + } + const b = before === null || before === undefined || before === "" ? null : String(before).trim(); + if (b !== null && want.includes(b)) throw new Error(`${b} is one of the entries being placed: name the entry they land before`); + if (b !== null && !tl.some((x) => x?.id === b)) throw new Error(`no timeline entry with id ${b} to place before`); + const model = sectionModel(m); + const hasDeck = deckMarkers(m) !== null; + const moving = new Set(want); + const moved = tl.filter((e) => moving.has(e?.id)); + const rest = tl.filter((e) => !moving.has(e?.id)); + const at = b === null ? rest.length : rest.findIndex((e) => e?.id === b); + const clipsMoved = moved.filter(isClip).map((e) => e.id); + const fromIndex = tl.findIndex((e) => e?.id === want[0]); + // The sections either side of the slot, among the clips that stay. + const prevClip = [...rest.slice(0, at)].reverse().find(isClip) ?? null; + const nextClip = rest.slice(at).find(isClip) ?? null; + const lo = prevClip ? model.sectionOf.get(prevClip.id) : 0; + const hi = nextClip ? model.sectionOf.get(nextClip.id) : model.sections.length - 1; + let target = section === null || section === undefined || section === "" ? (prevClip ? lo : hi) : Number(section); + if (!hasDeck || !clipsMoved.length) target = prevClip ? lo : hi; + if (!Number.isInteger(target) || target < 0 || target >= model.sections.length) { + throw new Error(`section must be 0–${model.sections.length - 1} (§0 is before the first marker)`); + } + if (clipsMoved.length && hasDeck && (target < lo || target > hi)) { + const where = prevClip && nextClip ? `between ${prevClip.id} (${sectionWords(model.sections[lo])}) and ${nextClip.id} (${sectionWords(model.sections[hi])})` : prevClip ? `after ${prevClip.id} (${sectionWords(model.sections[lo])})` : `before ${nextClip.id} (${sectionWords(model.sections[hi])})`; + throw new Error(`a clip dropped ${where} cannot join ${sectionWords(model.sections[target])} — drop it inside that section, or move it there (section-move)`); + } + const membership = new Map(model.sectionOf); + const fromSections = Object.fromEntries(clipsMoved.map((id) => [id, membership.get(id)])); + for (const id of clipsMoved) membership.set(id, target); + // A section strictly between lo and hi other than the target would be left with no clip. + rest.splice(at, 0, ...moved); + const beforeOrder = tl.map((e) => e?.id).join("\n"); + m.timeline.splice(0, m.timeline.length, ...rest); + const reanchored = hasDeck ? reanchorMarkers(m, model, membership) : []; + const changed = beforeOrder !== m.timeline.map((e) => e?.id).join("\n"); + if (!changed && !reanchored.length) { + throw new Error(`${want.join(", ")} already ${want.length === 1 ? "stands" : "stand"} there${hasDeck && clipsMoved.length ? ` in ${sectionWords(model.sections[target])}` : ""}`); + } + return { + ids: moved.map((e) => e.id), + before: b, + from: fromIndex, + to: m.timeline.findIndex((e) => e?.id === want[0]), + section: hasDeck && clipsMoved.length ? target : null, + label: hasDeck && clipsMoved.length ? model.sections[target].label : null, + fromSections, + reanchored, + }; +} + +/** + * NEW SECTION HERE: a marker right after clip `afterId`, so the clips after it + * (to the next boundary) are a section of their own, labelled and coloured. + * + * @param {Record<string, any>} m + * @param {string} afterId + * @param {{ label?: string | null, color?: string | null }} [spec] + */ +export function addSectionIn(m, afterId, { label = null, color = null } = {}) { + const markers = needDeck(m); + const model = sectionModel(m); + const id = String(afterId ?? "").trim(); + const tl = m.timeline; + const i = tl.findIndex((e) => e?.id === id); + if (i < 0) throw new Error(`no timeline entry with id ${id}`); + if (!isClip(tl[i])) throw new Error(`${id} is a ${tl[i].type ?? "non-clip"} entry: a section boundary follows a clip`); + const lastClip = [...tl].reverse().find(isClip); + if (lastClip?.id === id) throw new Error(`${id} is the last clip: a section after it would be empty`); + const already = model.placed.find((p) => p.pos === i); + if (already) throw new Error(`a section already starts after ${id} (marker ${already.k}${already.mk.label ? `, "${already.mk.label}"` : ""}) — edit that one`); + const mk = { after: id }; + const l = typeof label === "string" ? label.trim() : ""; + if (l) mk.label = l; + const c = typeof color === "string" ? color.trim() : ""; + if (c) mk.color = c; + // In the cut's order in the list too: the Markers editor lists them so. + const k = model.placed.filter((p) => p.pos < i).reduce((n, p) => Math.max(n, p.k + 1), 0); + markers.splice(k, 0, mk); + const opened = model.sections[model.entrySection[i]]; + const nextClip = tl.slice(i + 1).find(isClip); + return { marker: k, after: id, label: l || null, color: c || null, opens: nextClip?.id ?? null, splitFrom: sectionWords(opened) }; +} + +/** + * DRAG A BOUNDARY: marker `k` follows clip `afterId` now -- somewhere between + * the boundaries either side of it, so no section empties and none cross. + * + * @param {Record<string, any>} m + * @param {number} k + * @param {string} afterId + */ +export function moveBoundaryIn(m, k, afterId) { + const markers = needDeck(m); + const model = sectionModel(m); + const n = Number(k); + if (!Number.isInteger(n) || !markers[n]) throw new Error(`no marker ${k} (0–${markers.length - 1})`); + const sec = model.sections.find((s) => s.marker === n); + if (!sec) throw new Error(`marker ${n} names ${markers[n]?.after ?? "nothing"}, which is not a clip of the cut`); + const tl = m.timeline; + const id = String(afterId ?? "").trim(); + const i = tl.findIndex((e) => e?.id === id); + if (i < 0) throw new Error(`no timeline entry with id ${id}`); + if (!isClip(tl[i])) throw new Error(`${id} is a ${tl[i].type ?? "non-clip"} entry: a section boundary follows a clip`); + const me = model.placed.findIndex((p) => p.k === n); + const lo = me > 0 ? model.placed[me - 1].pos : -1; + const hi = me + 1 < model.placed.length ? model.placed[me + 1].pos : tl.length; + const clipsIn = (a, b) => tl.slice(a + 1, b + 1).filter(isClip).length; + if (i <= lo || clipsIn(lo, i) < 1) throw new Error(`after ${id} the boundary would cross or touch the one before it (${model.placed[me - 1]?.mk.after}): ${sectionWords(model.sections[sec.index - 1])} would have no clip`); + if (i >= hi || tl.slice(i + 1, hi + 1).filter(isClip).length < 1) { + throw new Error(`after ${id} ${sectionWords(sec)} would have no clip${hi < tl.length ? ` (the next boundary is after ${model.placed[me + 1].mk.after})` : " (it is the last clip)"}`); + } + const was = markers[n].after; + if (was === id) throw new Error(`marker ${n} already follows ${id}`); + markers[n].after = id; + const p0 = model.placed[me].pos; + const crossed = tl.slice(Math.min(p0, i) + 1, Math.max(p0, i) + 1).filter(isClip).map((e) => e.id); + return { + marker: n, + from: was, + after: id, + // Which clips changed section, and into which. + moved: crossed, + into: i > p0 ? sectionWords(model.sections[sec.index - 1]) : sectionWords(sec), + }; +} + +/** REMOVE A BOUNDARY: marker `k` goes, and its section joins the one before it. */ +export function removeBoundaryIn(m, k) { + const markers = needDeck(m); + const n = Number(k); + if (!Number.isInteger(n) || !markers[n]) throw new Error(`no marker ${k} (0–${markers.length - 1})`); + const [gone] = markers.splice(n, 1); + return { marker: n, removed: gone }; +} + +/** A section's label and/or colour (its marker's): null or "" removes one. */ +export function setSectionIn(m, k, patch) { + const markers = needDeck(m); + const n = Number(k); + if (!Number.isInteger(n) || !markers[n]) throw new Error(`no marker ${k} (0–${markers.length - 1})`); + if (!isObj(patch) || (!("label" in patch) && !("color" in patch))) throw new Error("send label and/or color"); + const mk = markers[n]; + for (const key of ["label", "color"]) { + if (!(key in patch)) continue; + const v = typeof patch[key] === "string" ? patch[key].trim() : ""; + if (v) mk[key] = v; + else delete mk[key]; + } + return { marker: n, entry: { ...mk } }; +} + +/** + * After clip `firstId` was split in two (the second half `secondId` right + * after it): a marker that followed the first half follows the second -- the + * same boundary, or the second half falls into the next section. + */ +export function followSplitMarkers(m, firstId, secondId) { + const markers = deckMarkers(m) ?? []; + const notes = []; + markers.forEach((mk, k) => { + if (isObj(mk) && String(mk.after ?? "").trim() === firstId) { + mk.after = secondId; + notes.push(`marker ${k}${mk.label ? ` ("${mk.label}")` : ""} follows ${secondId} now (the same boundary)`); + } + }); + return notes; +} diff --git a/umtool/lib/report/sectionEdit.test.mjs b/umtool/lib/report/sectionEdit.test.mjs @@ -0,0 +1,273 @@ +// Sections as sections (sectionEdit.mjs) and their writers in manifest.mjs: +// move to section, new section here, drag / remove a boundary, the take +// patches' markers kept in step, flash-forward a span, and a split that keeps +// its section. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { addSectionIn, moveBoundaryIn, moveToSectionIn, removeBoundaryIn, sectionModel, setSectionIn } from "./sectionEdit.mjs"; +import { syncSectionMarkers } from "./patchMarkers.mjs"; +import { + MANIFEST_NAME, + StructureRefused, + addSection, + flashForward, + flashForwardIn, + moveSectionBoundary, + moveToSection, + removeSection, + splitClip, + undoStructural, +} from "./manifest.mjs"; + +const clip = (id, start, end, extra = {}) => ({ type: "clip", id, video: "v1", start, end, ...extra }); +// §0 a b | §1 "Two" c d | card k | §2 "Three" e f +const deckCut = () => ({ + slug: "s", + provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, + render: { + width: 1920, + height: 1080, + chrome: { + engine: "hyperframes", + layout: "deck", + deck: { + markers: [ + { after: "b", label: "Two", color: "#ff0000" }, + { after: "d", label: "Three", color: "#00ff00" }, + ], + }, + }, + }, + timeline: [ + clip("a", 10, 20), + clip("b", 30, 40), + clip("c", 50, 60), + clip("d", 70, 80), + { type: "card", id: "k", seconds: 3 }, + clip("e", 90, 100), + clip("f", 110, 120), + ], +}); +const ids = (m) => m.timeline.map((e) => e.id); +const afters = (m) => (m.render.chrome.deck.markers ?? []).map((mk) => mk.after); + +test("sectionModel reads the sections off the markers", () => { + const { sections, sectionOf, entrySection } = sectionModel(deckCut()); + assert.deepEqual(sections.map((s) => [s.index, s.label, s.clips]), [[0, null, ["a", "b"]], [1, "Two", ["c", "d"]], [2, "Three", ["e", "f"]]]); + assert.equal(sectionOf.get("e"), 2); + assert.equal(entrySection[4], 2, "the card after d's boundary stands in §2"); +}); + +test("move to section: the clip lands at the section's end and the markers follow", () => { + const m = deckCut(); + const r = moveToSectionIn(m, ["a"], 1); + assert.deepEqual(ids(m), ["b", "c", "d", "a", "k", "e", "f"]); + assert.deepEqual(afters(m), ["b", "a"]); + assert.equal(r.section, 1); + assert.deepEqual(r.reanchored, ['marker 1 ("Three") moved from after d to after a']); +}); + +test("move the clip a marker follows: the marker moves to the clip before it", () => { + const m = deckCut(); + moveToSectionIn(m, ["d"], 2, { position: "start" }); + assert.deepEqual(ids(m), ["a", "b", "c", "d", "k", "e", "f"], "d is already where §2 starts — the boundary moves instead"); + assert.deepEqual(afters(m), ["b", "c"]); + const m2 = deckCut(); + moveToSectionIn(m2, ["b", "c"], 2); + assert.deepEqual(ids(m2), ["a", "d", "k", "e", "f", "b", "c"]); + assert.deepEqual(afters(m2), ["a", "d"]); +}); + +test("a section left with no clip is refused, in words", () => { + const m = deckCut(); + assert.throws(() => moveToSectionIn(m, ["c", "d"], 0), /§1 \(Two\) would have no clip left/); + assert.throws(() => moveToSectionIn(deckCut(), ["k"], 0), /a section move takes clips/); + assert.throws(() => moveToSectionIn(deckCut(), ["a"], 3), /section must be 0–2/); +}); + +test("new section here: a marker after the clip, in the cut's order, with its colour", () => { + const m = deckCut(); + const r = addSectionIn(m, "e", { label: "Four", color: "#123456" }); + assert.deepEqual(m.render.chrome.deck.markers.map((x) => [x.after, x.label ?? null]), [["b", "Two"], ["d", "Three"], ["e", "Four"]]); + assert.equal(r.opens, "f"); + assert.throws(() => addSectionIn(deckCut(), "f", { label: "x" }), /the last clip/); + assert.throws(() => addSectionIn(deckCut(), "b", { label: "x" }), /already starts after b/); + const m2 = deckCut(); + addSectionIn(m2, "a", {}); + assert.deepEqual(afters(m2), ["a", "b", "d"], "an unlabelled one first in the list too"); +}); + +test("drag a boundary: between its neighbours, never crossing them", () => { + const m = deckCut(); + const r = moveBoundaryIn(m, 1, "c"); + assert.deepEqual(afters(m), ["b", "c"]); + assert.deepEqual(r.moved, ["d"]); + assert.throws(() => moveBoundaryIn(deckCut(), 1, "b"), /would cross or touch/); + assert.throws(() => moveBoundaryIn(deckCut(), 1, "f"), /would have no clip/); + assert.throws(() => moveBoundaryIn(deckCut(), 0, "d"), /would have no clip/); + const m2 = deckCut(); + moveBoundaryIn(m2, 1, "e"); + assert.deepEqual(sectionModel(m2).sections[2].clips, ["f"]); +}); + +test("remove a boundary joins two sections; set relabels and recolours", () => { + const m = deckCut(); + removeBoundaryIn(m, 0); + assert.deepEqual(sectionModel(m).sections.map((s) => s.clips.length), [4, 2]); + const m2 = deckCut(); + setSectionIn(m2, 1, { label: "Drei", color: "" }); + assert.deepEqual(m2.render.chrome.deck.markers[1], { after: "d", label: "Drei" }); +}); + +test("a cut with no deck says so", () => { + const m = deckCut(); + delete m.render.chrome; + assert.throws(() => addSectionIn(m, "a", { label: "x" }), /no deck — turn the deck on first/); +}); + +async function project(manifest, extra = {}) { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-sections-")); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + "\n"); + for (const [name, doc] of Object.entries(extra)) await writeFile(path.join(dir, name), typeof doc === "string" ? doc : JSON.stringify(doc, null, 2) + "\n"); + return dir; +} +const read = async (dir, name = MANIFEST_NAME) => JSON.parse(await readFile(path.join(dir, name), "utf8")); +const patchOf = (markers) => ({ render: { chrome: { deck: { markers } } }, title: "T" }); + +test("the writers keep in-step take patches in step, and leave a variant alone", async () => { + const m = deckCut(); + const dir = await project(m, { + "draft-1.patch.json": patchOf(m.render.chrome.deck.markers), + "variant.patch.json": patchOf([{ after: "a", label: "Other" }]), + "plain.patch.json": { title: "no markers" }, + }); + try { + const r = await moveToSection(dir, ["a"], 1); + assert.deepEqual(r.sectionPatches.synced, ["draft-1.patch.json"]); + assert.deepEqual(r.sectionPatches.skipped.map((x) => x.file), ["variant.patch.json"]); + assert.deepEqual((await read(dir, "draft-1.patch.json")).render.chrome.deck.markers.map((x) => x.after), ["b", "a"]); + assert.deepEqual((await read(dir, "variant.patch.json")).render.chrome.deck.markers, [{ after: "a", label: "Other" }]); + assert.deepEqual(await read(dir, "plain.patch.json"), { title: "no markers" }); + const r2 = await addSection(dir, "e", { label: "Four", color: "amber" }); + assert.deepEqual(r2.sectionPatches.synced, ["draft-1.patch.json"]); + assert.equal((await read(dir, "draft-1.patch.json")).render.chrome.deck.markers.length, 3); + await moveSectionBoundary(dir, 1, "c"); + await removeSection(dir, 2); + const p = await read(dir, "draft-1.patch.json"); + assert.deepEqual(p.render.chrome.deck.markers, (await read(dir)).render.chrome.deck.markers); + // Undo restores the manifest (the patch is the operator's to re-sync: it says so in the check). + await undoStructural(dir); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a marker past the deck's limits is refused in its words, nothing written", async () => { + const m = deckCut(); + const dir = await project(m); + try { + const before = await readFile(path.join(dir, MANIFEST_NAME), "utf8"); + await assert.rejects(addSection(dir, "a", { label: "a label far longer than twenty-four characters" }), (e) => e instanceof StructureRefused && /at most 24/.test(e.message)); + assert.equal(await readFile(path.join(dir, MANIFEST_NAME), "utf8"), before); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("syncSectionMarkers keeps the patch's own indent", async () => { + const dir = await project(deckCut(), { "one.patch.json": JSON.stringify(patchOf([{ after: "b" }]), null, 1) + "\n" }); + try { + await syncSectionMarkers(dir, [{ after: "b" }], [{ after: "c" }]); + const text = await readFile(path.join(dir, "one.patch.json"), "utf8"); + assert.match(text, /^\{\n "render"/); + assert.equal(JSON.parse(text).render.chrome.deck.markers[0].after, "c"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("split keeps the section: a marker after the clip follows its second half; the QR follows the second", async () => { + const m = deckCut(); + m.timeline[1] = { ...m.timeline[1], cite: 30, citeUrl: "https://archive.example/?v=chan%2Fv1&t=30", lockEnd: true, title: "Stream", date: "2026-10-27" }; + const dir = await project(m, { "draft-1.patch.json": patchOf(m.render.chrome.deck.markers) }); + try { + const r = await splitClip(dir, "b", 35); + const after = await read(dir); + assert.deepEqual(ids(after), ["a", "b", "b-2", "c", "d", "k", "e", "f"]); + assert.deepEqual(afters(after), ["b-2", "d"]); + const b2 = after.timeline[2]; + assert.equal(b2.cite, 35); + assert.match(b2.citeUrl, /t=35$/); + assert.equal(b2.lockEnd, true); + assert.equal(b2.title, "Stream"); + assert.deepEqual(r.sectionPatches.synced, ["draft-1.patch.json"]); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("flash-forward copies a span earlier with its attribution and locks, as a repeat", () => { + const m = deckCut(); + Object.assign(m.timeline[5], { + channel: "chan", cite: 90, citeUrl: "https://archive.example/?v=chan%2Fv1&t=90", lock: true, title: "Stream", date: "2026-10-27", + quote: "the whole thing", speakers: ["Host"], claim: { id: "e", verdict: "reason" }, gaps: [{ from: 92, to: 93 }, { from: 97, to: 98 }], + }); + const r = flashForwardIn(m, "e", { from: 95.5, to: 99.25, after: "a", quote: "the tight line" }); + assert.equal(r.id, "et"); + assert.deepEqual(ids(m), ["a", "et", "b", "c", "d", "k", "e", "f"]); + const c = m.timeline[1]; + assert.equal(c.start, 95.5); + assert.equal(c.end, 99.25); + assert.equal(c.cite, 95); + assert.match(c.citeUrl, /t=95$/); + assert.equal(c.repeatOf, "e"); + assert.equal(c.lock, true); + assert.equal(c.title, "Stream"); + assert.equal(c.date, "2026-10-27"); + assert.deepEqual(c.speakers, ["Host"]); + assert.equal(c.quote, "the tight line"); + assert.equal(c.claim, undefined, "one claim, one entry"); + assert.deepEqual(c.gaps, [{ from: 97, to: 98 }]); + assert.equal(r.earlier, true); + assert.equal(m.timeline[6].end, 100, "the clip itself is untouched"); +}); + +test("flash-forward into a section, and a moved span takes the clip's edge with it", () => { + const m = deckCut(); + m.timeline[3].cite = 70; + const r = flashForwardIn(m, "d", { from: 75, to: 80, section: 0, move: true, restQuote: "the first half" }); + assert.deepEqual(ids(m), ["a", "b", "dt", "c", "d", "k", "e", "f"]); + assert.deepEqual(afters(m), ["dt", "d"]); + assert.equal(r.move, true); + assert.equal(m.timeline[2].repeatOf, undefined); + assert.deepEqual(r.rest, { start: 70, end: 75 }); + assert.equal(m.timeline[4].quote, "the first half"); + assert.throws(() => flashForwardIn(deckCut(), "d", { from: 72, to: 78, move: true }), /in the middle of d/); + assert.throws(() => flashForwardIn(deckCut(), "d", { from: 60, to: 78 }), /not inside d's window/); +}); + +test("flashForward writes once, with an undo point", async () => { + const dir = await project(deckCut()); + try { + const r = await flashForward(dir, "f", { from: 111, to: 115, after: "a" }); + assert.equal(r.id, "ft"); + assert.ok(r.snapshot?.rel?.includes("auto-before-flash-forward")); + await undoStructural(dir); + assert.deepEqual(ids(await read(dir)), ids(deckCut())); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("flash-forward to the start of §0 when the copy already lands there", () => { + const m = deckCut(); + const r = flashForwardIn(m, "c", { from: 51, to: 55, section: 0, position: "start" }); + assert.deepEqual(ids(m).slice(0, 2), ["ct", "a"]); + assert.equal(r.section.index, 0); +}); diff --git a/umtool/lib/report/stripDrag.mjs b/umtool/lib/report/stripDrag.mjs @@ -0,0 +1,165 @@ +// THE REEL STRIP'S DRAG AND ZOOM, as arithmetic (Play the cut, ReelStrip.tsx): +// where a dragged cell would land and in which section, which section labels +// fit at the zoom shown, how fast the strip pans at its edge while dragging, +// and when a zoomed strip follows the playhead. Pure: no DOM, no React, so it +// is unit-tested (stripDrag.test.mjs); the zoom itself is the bench's +// (benchZoom.mjs), on cut seconds instead of source seconds. +// +// Sections are the deck's markers (sectionEdit.mjs sectionModel), passed in +// as `sectionOf` (clip id -> section index) and `sections` ({index, label}); +// nothing here knows how many there may be. + +/** + * Each item's section: a clip's own, a card's that of the clip before it + * (else the one after), as sectionModel's entrySection stands a card. + * + * @param {Array<{ id: string, clip?: unknown }>} items + * @param {Record<string, number> | Map<string, number>} sectionOf + * @returns {number[]} + */ +export function itemSections(items, sectionOf) { + const get = (id) => (sectionOf instanceof Map ? sectionOf.get(id) : sectionOf?.[id]); + const out = items.map((it) => (it.clip ? get(it.id) : undefined)); + let last; + for (let i = 0; i < out.length; i += 1) { + if (out[i] !== undefined) last = out[i]; + else if (last !== undefined) out[i] = last; + } + let next; + for (let i = out.length - 1; i >= 0; i -= 1) { + if (items[i].clip && get(items[i].id) !== undefined) next = get(items[i].id); + else if (out[i] === undefined) out[i] = next ?? 0; + } + return out.map((s) => s ?? 0); +} + +/** "§3 Leaves it open" -- a section in the drop's words. */ +export const sectionName = (sections, k) => { + const s = (sections ?? []).find((x) => x.index === k); + return `§${k}${s?.label ? ` ${s.label}` : k === 0 ? " (the opening)" : ""}`; +}; + +/** + * Where a drag of `dragged` (ids) would land with the pointer at cut second + * `t`: next to the cell under the pointer -- its left half before it, its + * right half after it -- in that cell's section. So at a seam the two halves + * either side are the end of §k and the start of §k+1: the same slot, the + * section said. Null over the dragged cells themselves (nothing would move). + * + * `before` is the id the dragged entries land before (null: the end), what + * the place op takes; `at` the cut second of the insertion line; `refused` + * the words when the drop would leave a section with no clip. + * + * @param {Array<{ id: string, from: number, to: number, clip?: unknown }>} items + * @param {number[]} sectionsOfItems itemSections(items, …) + * @param {Array<{ index: number, label: string | null }>} sections + * @param {string[]} dragged + * @param {number} t + */ +export function dropSlot(items, sectionsOfItems, sections, dragged, t) { + if (!items.length) return null; + const moving = new Set(dragged); + let j = items.findIndex((it) => t >= it.from && t < it.to); + if (j < 0) j = t < items[0].from ? 0 : items.length - 1; + if (moving.has(items[j].id)) return null; + const it = items[j]; + const side = t < (it.from + it.to) / 2 ? "before" : "after"; + const section = sectionsOfItems[j]; + // The entry the dragged ones land before: this cell, or the next not being dragged. + let k = side === "before" ? j : j + 1; + while (k < items.length && moving.has(items[k].id)) k += 1; + const before = k < items.length ? items[k].id : null; + // Already there: the entry before the slot (skipping the dragged) is the last dragged one's + // predecessor, and the section is its own. + const draggedIdx = items.map((x, i) => (moving.has(x.id) ? i : -1)).filter((i) => i >= 0); + const firstDragged = draggedIdx[0] ?? -1; + let p = k - 1; + while (p >= 0 && moving.has(items[p].id)) p -= 1; + const prevId = p >= 0 ? items[p].id : null; + let q = firstDragged - 1; + while (q >= 0 && moving.has(items[q].id)) q -= 1; + const origPrev = q >= 0 ? items[q].id : null; + const sameSection = draggedIdx.every((i) => !items[i].clip || sectionsOfItems[i] === section); + const noop = firstDragged >= 0 && prevId === origPrev && sameSection && draggedIdx.every((i, n) => n === 0 || i === draggedIdx[n - 1] + 1); + // A section emptied: every clip of some section is being dragged out of it. + let refused = null; + const left = new Map(); + items.forEach((x, i) => { + if (!x.clip || moving.has(x.id)) return; + left.set(sectionsOfItems[i], (left.get(sectionsOfItems[i]) ?? 0) + 1); + }); + for (const i of draggedIdx) { + const s = sectionsOfItems[i]; + if (items[i].clip && s !== section && !left.get(s)) { + refused = `${sectionName(sections, s)} would have no clip left — remove its boundary first, or move another clip into it`; + break; + } + } + const at = side === "before" ? it.from : it.to; + const where = before ? `before ${before}` : "at the end"; + return { + over: it.id, + side, + before, + section, + at, + noop, + refused, + words: noop ? "already here" : `→ ${sectionName(sections, section)}, ${side === "after" ? `after ${it.id}` : where}`, + seam: side === "after" ? sectionsOfItems[j + 1] !== undefined && sectionsOfItems[j + 1] !== section : j > 0 && sectionsOfItems[j - 1] !== section, + prev: prevId, + }; +} + +/** + * Which labels fit, left to right: each `{x, w}` (px) is shown when it starts + * at least `gap` px after the last shown one ends. Returns the indexes shown. + * + * @param {Array<{ x: number, w: number }>} labels in x order + * @param {number} [gap] + */ +export function labelsThatFit(labels, gap = 6) { + const shown = []; + let end = -Infinity; + labels.forEach((l, i) => { + if (l.x >= end + gap) { + shown.push(i); + end = l.x + l.w; + } + }); + return shown; +} + +/** + * The pan speed while dragging near an edge, in widths of what is shown per + * second: 0 away from the edges, growing to `max` at (and past) the edge. + * + * @param {number} x the pointer, px from the strip's left + * @param {number} width the strip's width, px + * @param {{ edge?: number, max?: number }} [o] + */ +export function edgeSpeed(x, width, { edge = 48, max = 1.2 } = {}) { + if (!(width > 0)) return 0; + if (x < edge) return -max * Math.min(1, (edge - x) / edge); + if (x > width - edge) return max * Math.min(1, (x - (width - edge)) / edge); + return 0; +} + +/** + * A zoomed strip follows the playhead: once `t` leaves what is shown (or + * comes within `margin` of its right edge while playing), the view pages on + * so `t` sits a fifth of the way in. Null when it need not move. + * + * @param {{ from: number, to: number }} vis + * @param {{ from: number, to: number }} whole + * @param {number} t + * @param {{ margin?: number }} [o] fraction of the view + */ +export function followVis(vis, whole, t, { margin = 0.04 } = {}) { + const span = vis.to - vis.from; + if (!(span > 0) || span >= whole.to - whole.from - 1e-6) return null; + if (t >= vis.from && t <= vis.to - span * margin) return null; + let from = t - span * 0.2; + from = Math.max(whole.from, Math.min(whole.to - span, from)); + return { from, to: from + span }; +} diff --git a/umtool/lib/report/stripDrag.test.mjs b/umtool/lib/report/stripDrag.test.mjs @@ -0,0 +1,89 @@ +// The reel strip's drag and zoom arithmetic (stripDrag.mjs). +import assert from "node:assert/strict"; +import test from "node:test"; +import { dropSlot, edgeSpeed, followVis, itemSections, labelsThatFit, sectionName } from "./stripDrag.mjs"; +import { zoomAt, zoomTo } from "./benchZoom.mjs"; + +// a b | c d (k card) | e f, each 10 s. +const ids = ["a", "b", "c", "d", "k", "e", "f"]; +const items = ids.map((id, i) => ({ id, from: i * 10, to: i * 10 + 10, ...(id === "k" ? {} : { clip: {} }) })); +const sectionOf = { a: 0, b: 0, c: 1, d: 1, e: 2, f: 2 }; +const sections = [{ index: 0, label: null }, { index: 1, label: "Two" }, { index: 2, label: "Three" }]; +const secs = itemSections(items, sectionOf); + +test("itemSections: a card stands in the section of the clip before it", () => { + assert.deepEqual(secs, [0, 0, 1, 1, 1, 2, 2]); + assert.deepEqual(itemSections([{ id: "k" }, { id: "a", clip: {} }], { a: 3 }), [3, 3], "a card first takes the next clip's"); +}); + +test("dropSlot: the cell's halves; a seam's two sides are two sections of one slot", () => { + const d1 = dropSlot(items, secs, sections, ["a"], 52); // f? no: e is 50-60, left half + assert.equal(d1.over, "e"); + assert.equal(d1.side, "before"); + assert.equal(d1.before, "e"); + assert.equal(d1.section, 2); + assert.equal(d1.at, 50); + assert.equal(d1.words, "→ §2 Three, before e"); + // The right half of b (end of §0) and the left half of c (start of §1): both before c. + const end0 = dropSlot(items, secs, sections, ["f"], 18); + const start1 = dropSlot(items, secs, sections, ["f"], 21); + assert.equal(end0.before, "c"); + assert.equal(start1.before, "c"); + assert.equal(end0.section, 0); + assert.equal(start1.section, 1); + assert.equal(end0.words, "→ §0 (the opening), after b"); + assert.ok(end0.seam && start1.seam); + // Past the last cell: the end. + assert.equal(dropSlot(items, secs, sections, ["a"], 69).before, null); +}); + +test("dropSlot: over the dragged cell nothing; where it already is, a no-op", () => { + assert.equal(dropSlot(items, secs, sections, ["c"], 25), null); + const here = dropSlot(items, secs, sections, ["c"], 17); // right half of b: before c (skipping c itself)... after b, §0 + assert.equal(here.before, "d"); + assert.equal(here.noop, false, "§0 is not c's section: it would move into §0"); + const same = dropSlot(items, secs, sections, ["c"], 32); // left half of d: before d in §1, after b + assert.equal(same.noop, true); + assert.equal(same.words, "already here"); +}); + +test("dropSlot: dragging a section's only clip out of it is refused in words", () => { + const two = [items[0], items[1], items[2], items[5]]; + const s2 = itemSections(two, { a: 0, b: 0, c: 1, e: 2 }); + const r = dropSlot(two, s2, sections, ["c"], 5); + assert.equal(r.refused, "§1 Two would have no clip left — remove its boundary first, or move another clip into it"); + const ok = dropSlot(two, s2, sections, ["a"], 35); + assert.equal(ok.refused, null); +}); + +test("labelsThatFit: a label is shown when it clears the last one shown", () => { + assert.deepEqual(labelsThatFit([{ x: 0, w: 50 }, { x: 30, w: 40 }, { x: 60, w: 40 }, { x: 101, w: 10 }]), [0, 2]); + // 24 sections over 600 px with 80 px labels: one in four. + const many = Array.from({ length: 24 }, (_, i) => ({ x: i * 25, w: 80 })); + assert.deepEqual(labelsThatFit(many), [0, 4, 8, 12, 16, 20]); +}); + +test("edgeSpeed: zero in the middle, up to max at either edge", () => { + assert.equal(edgeSpeed(500, 1000), 0); + assert.equal(edgeSpeed(0, 1000), -1.2); + assert.equal(edgeSpeed(1000, 1000), 1.2); + assert.ok(edgeSpeed(980, 1000) > 0 && edgeSpeed(980, 1000) < 1.2); +}); + +test("followVis: a zoomed strip pages on when the playhead leaves it", () => { + const whole = { from: 0, to: 1680 }; + assert.equal(followVis(whole, whole, 900), null, "at fit nothing moves"); + const vis = { from: 100, to: 200 }; + assert.equal(followVis(vis, whole, 150), null); + assert.deepEqual(followVis(vis, whole, 199), { from: 179, to: 279 }); + assert.deepEqual(followVis(vis, whole, 1675), { from: 1580, to: 1680 }); +}); + +test("the bench's zoom on cut seconds: the pointer's second stays put, a clip fills the strip", () => { + const whole = { from: 0, to: 1680 }; + const v = zoomAt(null, whole, 420, 4); + assert.ok(Math.abs((420 - v.from) / (v.to - v.from) - 420 / 1680) < 1e-6); + const c = zoomTo({ from: 400, to: 412 }, whole); + assert.ok(c.from < 400 && c.to > 412 && c.to - c.from < 20); + assert.equal(sectionName(sections, 1), "§1 Two"); +}); diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs @@ -81,8 +81,17 @@ export const TAKES_USAGE = [ " [--priority] (either form: render mode for the whole batch, as `umtool take --priority`)", ` one take per montage style (writes takes/${ALL_STYLES_RECIPE})`, " umtool takes styles [--json] the montage styles: name, label, summary", - " umtool takes pick <project> <take> [--anyway] use this take: its manifest over the project's", + " umtool takes pick <project> <take> [--anyway] [--pin | --unpin] use this take: its manifest over the", + " project's (to go back to an older take); --pin keeps the pick there when newer takes are", + " made (each whole-cut take of the manifest is otherwise its group's pick once built)", " umtool takes effects <project> [--json] the overlay effects this cut offers, for --effect", + " umtool takes ls <project> [--json] the working cut (Latest: <take> · +N edits since), then", + " each take: label, length, latest / picked / superseded / rendering", + " umtool takes relabel <project> <take> <label…> take.json's label (an undo point of the take's own;", + " refused while it renders)", + " umtool takes supersede <project> <take> [--by <take>] | --clear folded away in the takes list (verdicts.json)", + " umtool takes delete <project> <take> [--dry-run] [--force] takes/<take>/ whole (refused while it renders or a", + " render is made from it; --force only past the take the project's manifest is)", ].join("\n"); class CliError extends Error {} @@ -91,7 +100,7 @@ class CliError extends Error {} function parse(args) { const valued = new Set([ "--id", "--label", "--group", "--kind", "--summary", "--style", "--patch", "--patch-json", "--set", "--effect", - "--at", "--dur", "--recipe", "--only", "--progress", "--from", + "--at", "--dur", "--recipe", "--only", "--progress", "--from", "--by", ]); /** @type {Record<string, string[]>} */ const flags = {}; @@ -345,14 +354,90 @@ export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = con else for (const x of effects) log(`${x.name.padEnd(16)} ${x.label} — ${x.summary}`); return 0; } + if (sub === "ls") { + const project = await pickProject(rest[0], reportsRoot); + const { takesOverview, takeLine } = await import("./takeHousekeeping.mjs"); + const { readWorkingCut, workingCutLine } = await import("./workingCut.mjs"); + const { resolveTakeManifest } = await import("./takeManifest.mjs"); + const [o, working] = await Promise.all([ + takesOverview(project.dir), + readWorkingCut(project.dir, { resolveNow: async (id) => (await resolveTakeManifest(project.dir, id)).manifest }), + ]); + if (p.has("--json")) log(JSON.stringify({ project: project.id, working, ...o }, null, 2)); + else { + log(workingCutLine(working) + (working.edits?.words?.length ? ` (${working.edits.words.slice(0, 8).join("; ")}${working.edits.words.length > 8 ? "; …" : ""})` : "")); + for (const r of o.rows) log(takeLine({ ...r, latest: r.id === working.latest?.id })); + for (const sk of o.skipped) err(`skipped takes/${sk.dir}: ${sk.why}`); + } + return 0; + } + if (sub === "relabel") { + const project = await pickProject(rest[0], reportsRoot); + const take = rest[1]; + const label = rest.slice(2).join(" "); + if (!take || !label) throw new CliError("umtool takes relabel <project> <take> <label…>"); + const { renderHolds } = await import("./takeHousekeeping.mjs"); + const { relabelTake } = await import("./takeEdit.mjs"); + const r = await relabelTake(project.dir, take, label, { holds: await renderHolds(project.dir, take) }); + if (p.has("--json")) log(JSON.stringify({ ok: true, ...r }, null, 2)); + else log(r.revision ? `${take}: "${r.label}" (was "${r.was}"; undo point takes/${take}/${r.revision.rel})` : `${take} is already "${r.label}"`); + return 0; + } + if (sub === "supersede") { + const project = await pickProject(rest[0], reportsRoot); + const take = rest[1]; + if (!take) throw new CliError("umtool takes supersede <project> <take> [--by <take>] | --clear"); + const { listTakes, setTakeSuperseded } = await import("./takes.mjs"); + const known = (await listTakes(project.dir)).takes.map((t) => t.id); + if (!known.includes(take)) throw new CliError(`${project.id} has no take ${take}`); + const r = await setTakeSuperseded(project.dir, take, { by: p.one("--by") ?? null, clear: p.has("--clear"), known }); + if (p.has("--json")) log(JSON.stringify({ ok: true, take, entry: r.entry }, null, 2)); + else log(p.has("--clear") ? `${take}: not superseded` : `${take}: superseded${r.entry?.superseded?.by ? ` by ${r.entry.superseded.by}` : ""} (folded away in the takes list; nothing deleted)`); + return 0; + } + if (sub === "delete") { + const project = await pickProject(rest[0], reportsRoot); + const take = rest[1]; + if (!take) throw new CliError("umtool takes delete <project> <take> [--dry-run] [--force]"); + const { DeleteRefused, deleteTake, planTakeDelete } = await import("./delete.mjs"); + const force = p.has("--force"); + const plan = await planTakeDelete(project, take, { force }); + const blocking = plan.refusals.filter((x) => !(force && x.forceable)); + if (p.has("--dry-run") || blocking.length) { + if (p.has("--json")) log(JSON.stringify({ ok: !blocking.length, dryRun: true, plan }, null, 2)); + else { + for (const x of plan.refusals) err(`${x.forceable ? "refused (--force passes it)" : "refused"}: ${x.reason}`); + for (const x of plan.remove ?? []) log(`would remove ${x.label} — ${x.what} (${x.files} file(s), ${(x.bytes / 1e6).toFixed(1)} MB)`); + for (const x of plan.kept ?? []) log(`kept: ${x.what} — ${x.why}`); + } + return blocking.length ? 1 : 0; + } + try { + const r = await deleteTake(project, take, { force }); + if (p.has("--json")) log(JSON.stringify({ ok: true, removed: r.removed, failed: r.failed }, null, 2)); + else { + for (const x of r.removed) log(`removed ${x}`); + for (const f of r.failed) err(`not removed ${f.path}: ${f.error}`); + } + return r.failed.length ? 1 : 0; + } catch (e) { + if (e instanceof DeleteRefused) { + err(e.message); + return 1; + } + throw e; + } + } if (sub === "pick") { const project = await pickProject(rest[0], reportsRoot); const take = rest[1]; if (!take) throw new CliError("which take? `umtool takes pick <project> <take>`"); try { - const r = await pickTake(project, take, { anyway: p.has("--anyway") }); + if (p.has("--pin") && p.has("--unpin")) throw new CliError("--pin or --unpin, not both"); + const pinned = p.has("--pin") ? true : p.has("--unpin") ? false : undefined; + const r = await pickTake(project, take, { anyway: p.has("--anyway"), pinned }); if (p.has("--json")) log(JSON.stringify({ ok: true, ...r }, null, 2)); - else log(`${project.id}: now ${take}'s manifest${r.snapshot?.rel ? ` (the one before is ${r.snapshot.rel})` : ""}`); + else log(`${project.id}: now ${take}'s manifest${r.snapshot?.rel ? ` (the one before is ${r.snapshot.rel})` : ""}${r.verdicts?.[take]?.pinned ? " — pinned: newer takes do not move the pick" : ""}`); return 0; } catch (e) { if (e instanceof TakeStale) { diff --git a/umtool/lib/report/takeEdit.mjs b/umtool/lib/report/takeEdit.mjs @@ -221,6 +221,39 @@ export async function removeTakeEntry(projectDir, id, entryId, { token = null, a return editTakeTimeline(projectDir, id, "remove", token, (m) => applyStructural(m, (x) => removeIn(x, entryId, at, { reanchor: false })), { now }); } +/** A take's label: one line, at most this long. */ +export const TAKE_LABEL_MAX = 200; + +/** + * RELABEL a take (UI notes 2026-10-30, item 19: "draft 9…" on draft-10): its + * take.json `label`, with an undo point of the take's own first (`umtool + * timeline <p> --take <id> undo` takes it back). Refused while the take is + * rendering: the render writes take.json LAST, from the label it started + * with, and would put the old one back (takeHousekeeping.mjs renderHolds). + * + * @param {string} projectDir + * @param {string} id + * @param {string} label + * @param {{ token?: string | null, now?: Date, holds?: string[] }} [opts] `holds`: renderHolds's sentences + */ +export async function relabelTake(projectDir, id, label, { token = null, now = new Date(), holds = [] } = {}) { + const l = typeof label === "string" ? label.replace(/\s+/g, " ").trim() : ""; + if (!l) throw new Error("a take's label is a few words, not nothing"); + if (l.length > TAKE_LABEL_MAX) throw new Error(`a take's label is at most ${TAKE_LABEL_MAX} characters (this one is ${l.length})`); + if (holds.length) throw new Error(`take ${id} is not relabelled: ${holds.join("; ")}`); + return withTakeEditLock(async () => { + const current = await takeToken(projectDir, id); + if (token !== null && current !== token) throw new StaleToken(token, current); + const { text, doc } = await readTakeDoc(projectDir, id); + const was = typeof doc.label === "string" ? doc.label : ""; + if (was === l) return { id, label: l, was, token: current, revision: null }; + const revision = await keepRevision(projectDir, id, text, `${AUTO}relabel`, now); + doc.label = l; + const nextToken = await writeTakeAtomic(projectDir, id, doc); + return { id, label: l, was, token: nextToken, revision }; + }); +} + /** * Take back the take's newest edit: its newest `auto-before-<op>` revision * restored over take.json, byte for byte (see the top of the file). diff --git a/umtool/lib/report/takeHousekeeping.mjs b/umtool/lib/report/takeHousekeeping.mjs @@ -0,0 +1,90 @@ +// TAKE HOUSEKEEPING (UI notes 2026-10-30, item 19): wrong labels ("draft 9…" +// on draft-10), cancelled and superseded takes left in the list. +// +// relabel take.json's label takeEdit.mjs relabelTake +// supersede verdicts.json's `superseded` takes.mjs setTakeSuperseded +// delete takes/<id>/ whole delete.mjs planTakeDelete / deleteTake +// +// What a running render names is respected by all three, through one reader +// (renderHolds): a take whose own build lock (`takes/<id>/.building.json`, +// takePrune.mjs) is live is RENDERING -- its take.json is written last, from +// the label it started with, and its directory is its output -- and a take +// another live build names as its `from` is that build's base. A relabel or a +// delete is refused for either, in words; a supersede mark (verdicts.json, +// which no render writes) is not. +// +// Plain ESM: the CLI runs it under bare node. +import { readdir } from "node:fs/promises"; +import path from "node:path"; +import { BUILD_LOCK, lockIsLive, readBuildLock } from "./takePrune.mjs"; +import { isTakeId, listTakes, readVerdicts, takesDirOf } from "./takes.mjs"; + +/** + * Every reason a running render has to keep take `takeId` as it is: its own + * live build, and any live build made from it. [] when none. + * + * @param {string} projectDir + * @param {string} takeId + * @param {{ host?: string, alive?: (pid: number) => boolean }} [opts] for tests + * @returns {Promise<string[]>} + */ +export async function renderHolds(projectDir, takeId, opts = {}) { + if (!isTakeId(takeId)) return []; + const root = takesDirOf(projectDir); + const holds = []; + const live = (lock) => lockIsLive(lock, opts.host || opts.alive ? { ...(opts.host ? { host: opts.host } : {}), ...(opts.alive ? { alive: opts.alive } : {}) } : undefined); + const own = await readBuildLock(path.join(root, takeId, BUILD_LOCK)); + if (own && live(own)) holds.push(`it is rendering now (pid ${own.pid}${own.startedAt ? `, since ${own.startedAt}` : ""}) — wait for it, or cancel it`); + const names = await readdir(root).catch(() => []); + for (const n of names) { + if (n === takeId || !isTakeId(n)) continue; + const lock = await readBuildLock(path.join(root, n, BUILD_LOCK)); + if (lock && lock.from === takeId && live(lock)) holds.push(`take ${n} is being rendered from it (pid ${lock.pid})`); + } + return holds; +} + +/** + * The takes as `umtool takes ls` prints them: id, label, built, picked, + * superseded (and by what), rendering now. + * + * @param {string} projectDir + */ +export async function takesOverview(projectDir) { + const [listing, verdicts] = await Promise.all([listTakes(projectDir), readVerdicts(projectDir)]); + const rows = []; + for (const t of listing.takes) { + const v = verdicts[t.id]; + const holds = await renderHolds(projectDir, t.id); + rows.push({ + id: t.id, + label: t.label, + group: t.group, + seconds: t.seconds, + builtAt: t.builtAt, + draft: t.draft, + verdict: v?.verdict ?? null, + picked: v?.picked === true, + pinned: v?.pinned === true, + superseded: v?.superseded ?? null, + rendering: holds.some((h) => h.startsWith("it is rendering")), + base: holds.some((h) => !h.startsWith("it is rendering")), + holds, + }); + } + return { rows, skipped: listing.skipped }; +} + +/** One line of `umtool takes ls`. */ +export function takeLine(r) { + const marks = [ + r.latest ? "latest" : null, + r.picked ? (r.pinned ? "picked, pinned" : "picked") : null, + r.superseded ? `superseded${r.superseded.by ? ` by ${r.superseded.by}` : ""}` : null, + r.draft ? "draft" : null, + r.rendering ? "RENDERING" : null, + r.base ? "a render is made from it" : null, + r.verdict, + ].filter(Boolean); + return `${r.id.padEnd(14)} ${typeof r.seconds === "number" ? `${r.seconds.toFixed(1)}s`.padStart(8) : " "} ${r.label}${marks.length ? ` [${marks.join(", ")}]` : ""}`; +} diff --git a/umtool/lib/report/takeHousekeeping.test.mjs b/umtool/lib/report/takeHousekeeping.test.mjs @@ -0,0 +1,110 @@ +// Take housekeeping (takeHousekeeping.mjs, takeEdit.mjs relabelTake, takes.mjs +// setTakeSuperseded, delete.mjs): relabel, supersede, delete -- and what a +// running render names is respected. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import os, { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { relabelTake } from "./takeEdit.mjs"; +import { listTakes, readVerdicts, setTakePicked, setTakeSuperseded, setTakeVerdict } from "./takes.mjs"; +import { renderHolds, takeLine, takesOverview } from "./takeHousekeeping.mjs"; +import { planTakeDelete } from "./delete.mjs"; + +const take = (id, order, extra = {}) => ({ id, group: "takes", order, label: `${id} label`, kind: "different", summary: "", changes: [], preview: "preview.mp4", seconds: 10, builtAt: "2026-10-30T10:00:00.000Z", ...extra }); + +async function project() { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-takes-hk-")); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ timeline: [] }) + "\n"); + for (const [id, order] of [["draft-9", 1], ["draft-10", 2], ["draft-11", 3]]) { + await mkdir(path.join(dir, "takes", id), { recursive: true }); + await writeFile(path.join(dir, "takes", id, "take.json"), JSON.stringify(take(id, order, id === "draft-10" ? { label: "draft 9: wrong label" } : {}), null, 2) + "\n"); + } + return dir; +} +const lock = (dir, id, doc) => writeFile(path.join(dir, "takes", id, ".building.json"), JSON.stringify({ host: os.hostname(), startedAt: "2026-10-31T23:00:00.000Z", take: id, ...doc }) + "\n"); + +test("relabel writes take.json's label with an undo point, and is refused while the take renders", async () => { + const dir = await project(); + try { + const r = await relabelTake(dir, "draft-10", " draft 10: the re-walk "); + assert.equal(r.label, "draft 10: the re-walk"); + assert.equal(r.was, "draft 9: wrong label"); + assert.ok(r.revision.rel.includes("auto-before-relabel")); + assert.equal(JSON.parse(await readFile(path.join(dir, "takes", "draft-10", "take.json"), "utf8")).label, "draft 10: the re-walk"); + assert.equal((await readdir(path.join(dir, "takes", "draft-10", "revisions"))).length, 1); + await assert.rejects(relabelTake(dir, "draft-10", ""), /not nothing/); + await assert.rejects(relabelTake(dir, "draft-10", "x", { token: "1" }), /changed since/); + await lock(dir, "draft-10", { pid: process.pid }); + const holds = await renderHolds(dir, "draft-10"); + assert.equal(holds.length, 1); + assert.match(holds[0], /it is rendering now \(pid \d+/); + await assert.rejects(relabelTake(dir, "draft-10", "another", { holds }), /is not relabelled: it is rendering now/); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("renderHolds: a stale lock holds nothing; a live build made FROM a take holds it", async () => { + const dir = await project(); + try { + await lock(dir, "draft-11", { pid: 2 ** 22 + 12345, from: "draft-9" }); + assert.deepEqual(await renderHolds(dir, "draft-11", { alive: () => false }), []); + assert.deepEqual(await renderHolds(dir, "draft-9", { alive: () => false }), []); + assert.deepEqual(await renderHolds(dir, "draft-9", { alive: () => true }), ["take draft-11 is being rendered from it (pid 4206649)"]); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a take rendering, or the base of one, is not deleted", async () => { + const dir = await project(); + try { + await lock(dir, "draft-11", { pid: process.pid, from: "draft-10" }); + const ctx = { reportsRoot: path.dirname(dir), mediaRoot: path.dirname(dir) }; + const p11 = await planTakeDelete({ id: path.basename(dir), dir }, "draft-11", ctx); + assert.ok(p11.refusals.some((r) => /draft-11: it is rendering now/.test(r.reason) && r.forceable === false)); + const p10 = await planTakeDelete({ id: path.basename(dir), dir }, "draft-10", ctx); + assert.ok(p10.refusals.some((r) => /draft-11 is being rendered from it/.test(r.reason))); + const p9 = await planTakeDelete({ id: path.basename(dir), dir }, "draft-9", ctx); + assert.ok(!p9.refusals.some((r) => /render/.test(r.reason))); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("supersede: a mark in verdicts.json beside the verdict, cleared, never on the picked take", async () => { + const dir = await project(); + try { + await setTakeVerdict(dir, "draft-9", { verdict: "maybe", note: "fine" }); + await setTakeSuperseded(dir, "draft-9", { by: "draft-11", known: ["draft-9", "draft-10", "draft-11"] }); + let v = await readVerdicts(dir); + assert.equal(v["draft-9"].superseded.by, "draft-11"); + assert.equal(v["draft-9"].verdict, "maybe", "the verdict and note are kept"); + // A verdict saved later keeps the mark. + await setTakeVerdict(dir, "draft-9", { note: "still fine" }); + assert.equal((await readVerdicts(dir))["draft-9"].superseded.by, "draft-11"); + await setTakeSuperseded(dir, "draft-10", {}); + assert.deepEqual(Object.keys((await readVerdicts(dir))["draft-10"].superseded), ["by", "at"]); + await assert.rejects(setTakeSuperseded(dir, "draft-10", { by: "draft-10" }), /by itself/); + await assert.rejects(setTakeSuperseded(dir, "draft-10", { by: "draft-99", known: ["draft-9", "draft-10"] }), /no take draft-99/); + await setTakeSuperseded(dir, "draft-10", { clear: true }); + assert.equal((await readVerdicts(dir))["draft-10"], undefined, "a row that says nothing is removed"); + await setTakePicked(dir, "draft-11", ["draft-9", "draft-10", "draft-11"]); + await assert.rejects(setTakeSuperseded(dir, "draft-11", {}), /picked take/); + // Picking a superseded take clears its mark. + await setTakePicked(dir, "draft-9", ["draft-9", "draft-10", "draft-11"]); + v = await readVerdicts(dir); + assert.equal(v["draft-9"].superseded, undefined); + assert.equal(v["draft-9"].picked, true); + const { rows } = await takesOverview(dir); + assert.deepEqual(rows.map((r) => r.id), ["draft-9", "draft-10", "draft-11"]); + assert.match(takeLine(rows[0]), /draft-9 .*\[picked, maybe\]/); + assert.equal((await listTakes(dir)).takes.length, 3, "nothing deleted"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -54,7 +54,7 @@ import { PIPELINE_DIR, RENDER_BUDGET, UMTOOL_DIR } from "./driver.mjs"; import { replaceManifest } from "./manifest.mjs"; import { incorrectClips, incorrectWhy } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; -import { isTakeId, listTakes, parseWindow, setTakePicked, takesDirOf, TAKE_FILE, TAKE_KINDS } from "./takes.mjs"; +import { autoPickTake, isTakeId, isWorkingTake, listTakes, parseWindow, setTakePicked, takesDirOf, TAKE_FILE, TAKE_KINDS } from "./takes.mjs"; export const MANIFEST = "video.manifest.json"; export const PREVIEW = "preview.mp4"; @@ -690,6 +690,11 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { const tmp = `${takeFile}.tmp-${process.pid}`; await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, takeFile); + // A whole-cut take of the manifest is its group's pick now (takes.mjs autoPickTake): mark only. + const group = ((listing ?? (await listTakes(projectDir))).takes ?? []).filter((t) => t.group === doc.group).map((t) => t.id); + const pick = await autoPickTake(projectDir, { ...doc, id: spec.id }, group).catch((e) => ({ picked: false, why: e instanceof Error ? e.message : String(e) })); + if (pick.picked) log(`${spec.id}: the working cut's take now (picked: ${pick.why})`); + else if (isWorkingTake(doc)) log(`${spec.id}: not picked — ${pick.why}`); emit({ ev: "take", id: spec.id, phase: "done", seconds: doc.seconds }); return { id: spec.id, skipped: false, take: doc }; } @@ -942,9 +947,10 @@ export async function takeIsStale(projectDir, take) { * * @param {{ id: string, dir: string, kind: string }} project * @param {string} takeId - * @param {{ anyway?: boolean, token?: string | null, now?: Date }} [opts] + * @param {{ anyway?: boolean, token?: string | null, now?: Date, pinned?: boolean }} [opts] + * `pinned`: true pins the pick (no auto-pick over it), false unpins (takes.mjs setTakePicked) */ -export async function pickTake(project, takeId, { anyway = false, token = null, now = new Date() } = {}) { +export async function pickTake(project, takeId, { anyway = false, token = null, now = new Date(), pinned = undefined } = {}) { if (!isTakeId(takeId)) throw new Error("not a take id"); const listing = await listTakes(project.dir); const take = listing.takes.find((t) => t.id === takeId); @@ -967,7 +973,7 @@ export async function pickTake(project, takeId, { anyway = false, token = null, ? { result: { snapshot: null, token: null }, editNotes: null } : await withEditNotes(project, () => replaceManifest(project.dir, manifest, { token, op: "pick-take" })); const group = listing.takes.filter((t) => t.group === take.group).map((t) => t.id); - const { verdicts } = await setTakePicked(project.dir, takeId, group, { now }); + const { verdicts } = await setTakePicked(project.dir, takeId, group, { now, pinned }); return { take: takeId, group: take.group, snapshot: result.snapshot, token: result.token, editNotes, verdicts }; } diff --git a/umtool/lib/report/takes.mjs b/umtool/lib/report/takes.mjs @@ -276,13 +276,21 @@ function cleanVerdicts(raw) { const verdict = TAKE_VERDICTS.includes(row.verdict) ? row.verdict : null; const note = typeof row.note === "string" ? row.note : ""; const at = typeof row.at === "string" ? row.at : ""; - out[id] = row.picked === true ? { verdict, note, at, picked: true } : { verdict, note, at }; + out[id] = row.picked === true ? { verdict, note, at, picked: true, ...(row.pinned === true ? { pinned: true } : {}) } : { verdict, note, at }; + const sup = supersededOf(row.superseded); + if (sup) out[id].superseded = sup; } return out; } -/** A row that says nothing: no verdict, no note, not picked. */ -const emptyRow = (row) => row.verdict === null && !row.note && row.picked !== true; +/** `superseded` as stored: `{ by: <take id> | null, at }`, else null. */ +function supersededOf(v) { + if (!v || typeof v !== "object" || Array.isArray(v)) return null; + return { by: isTakeId(v.by) ? v.by : null, at: typeof v.at === "string" ? v.at : "" }; +} + +/** A row that says nothing: no verdict, no note, not picked, not superseded. */ +const emptyRow = (row) => row.verdict === null && !row.note && row.picked !== true && !row.superseded; /** * Read verdicts.json for a write: `{}` when absent, an ERROR when present and @@ -312,7 +320,7 @@ async function writeVerdicts(file, map) { /** * @param {string} projectDir - * @returns {Promise<Record<string, { verdict: "like" | "maybe" | "no" | null, note: string, at: string, picked?: true }>>} + * @returns {Promise<Record<string, { verdict: "like" | "maybe" | "no" | null, note: string, at: string, picked?: true, superseded?: { by: string | null, at: string } }>>} */ export async function readVerdicts(projectDir) { try { @@ -351,6 +359,8 @@ export async function setTakeVerdict(projectDir, takeId, patch) { at: new Date().toISOString(), }; if (prev.picked === true) row.picked = true; + if (prev.pinned === true) row.pinned = true; + if (prev.superseded) row.superseded = prev.superseded; if (emptyRow(row)) delete map[takeId]; else map[takeId] = row; await writeVerdicts(file, map); @@ -364,30 +374,115 @@ export async function setTakeVerdict(projectDir, takeId, patch) { * of that group, the picked one included. A cleared row that then says * nothing is removed. Returns the whole file. * + * `pinned` (1 Nov 2026): `true` pins the pick -- a new full take made from the + * manifest is NOT auto-picked over it (autoPickTake); `false` unpins it; + * absent, a re-pick of the pinned take keeps its pin and any other pick is + * unpinned. + * * @param {string} projectDir * @param {string} takeId * @param {string[]} group - * @param {{ now?: Date }} [opts] + * @param {{ now?: Date, pinned?: boolean }} [opts] */ -export async function setTakePicked(projectDir, takeId, group, { now = new Date() } = {}) { +export async function setTakePicked(projectDir, takeId, group, { now = new Date(), pinned = undefined } = {}) { if (!isTakeId(takeId)) throw new Error("not a take id"); const file = verdictsFileOf(projectDir); return withTakesLock(async () => { const map = await readVerdictsForWrite(file); for (const id of group) { if (id === takeId || !map[id]?.picked) continue; - const { picked: _gone, ...rest } = map[id]; + const { picked: _gone, pinned: _pin, ...rest } = map[id]; if (emptyRow(rest)) delete map[id]; else map[id] = rest; } const prev = map[takeId] ?? { verdict: null, note: "", at: "" }; - map[takeId] = { verdict: prev.verdict, note: prev.note, at: now.toISOString(), picked: true }; + const pin = pinned === undefined ? prev.picked === true && prev.pinned === true : pinned === true; + // A take picked is not superseded any more. + map[takeId] = { verdict: prev.verdict, note: prev.note, at: now.toISOString(), picked: true, ...(pin ? { pinned: true } : {}) }; await writeVerdicts(file, map); return { entry: map[takeId], verdicts: map }; }); } /** + * A WORKING take (operator, 1 Nov 2026: "most of the time I'll only really be + * working on the latest cut/draft"): a whole-cut render of the project's + * manifest -- window `full`, rendered (not a draft), not a quick draft-quality + * render, made from the manifest (it records `baseHash`), and the manifest's + * own content: no montage style and no patch that brings a `timeline` of its + * own. The newest of them is the working cut's name (workingCut.mjs), and a + * new one is its group's pick (autoPickTake). A partial window, a style take + * or a take with its own timeline is a variant, never the cut. + * + * @param {{ window?: unknown, draft?: boolean, quick?: boolean, baseHash?: string | null, style?: string | null, patch?: Record<string, unknown> | null } | null | undefined} t + */ +export function isWorkingTake(t) { + if (!t || t.window !== "full" || t.draft === true || t.quick === true || !t.baseHash || t.style) return false; + return !(t.patch && typeof t.patch === "object" && Array.isArray(/** @type {any} */ (t.patch).timeline)); +} + +/** + * AUTO-PICK (1 Nov 2026): a working take just built becomes its group's pick + * -- a mark in verdicts.json, nothing copied: the project's manifest IS what it + * was made from -- so whatever still reads `picked` (the pruner's keep list, + * the Takes page) follows the latest draft, an agent's take as much as the + * operator's. Not when another take of the group holds a PINNED pick + * (`umtool takes pick <p> <take> --pin`). Never throws for a take that does not + * qualify: it says why. + * + * @param {string} projectDir + * @param {Parameters<typeof isWorkingTake>[0] & { id: string }} take + * @param {string[]} group the take ids of its group (it included) + * @param {{ now?: Date }} [opts] + * @returns {Promise<{ picked: boolean, why: string }>} + */ +export async function autoPickTake(projectDir, take, group, { now = new Date() } = {}) { + if (!isWorkingTake(take)) return { picked: false, why: "not a whole-cut take of the manifest (a window, a draft, a quick render, a style or its own timeline)" }; + const verdicts = await readVerdicts(projectDir); + const pinned = group.find((id) => id !== take.id && verdicts[id]?.picked && verdicts[id]?.pinned); + if (pinned) return { picked: false, why: `the pick is pinned to ${pinned} (umtool takes pick … ${pinned} --unpin)` }; + if (verdicts[take.id]?.picked) return { picked: true, why: "already the pick" }; + await setTakePicked(projectDir, take.id, group.includes(take.id) ? group : [...group, take.id], { now }); + return { picked: true, why: "the newest whole-cut take of the manifest" }; +} + +/** + * Mark take `takeId` SUPERSEDED (UI notes 2026-10-30, item 19) -- by take + * `by` when one is named -- or clear the mark (`clear: true`). The operator's + * judgement, so it lives in verdicts.json beside the verdict and the pick (a + * rebuild rewrites take.json; it never touches this). A superseded take is + * folded away in the takes list and named in `umtool takes ls`; nothing is + * deleted. Picking a take clears its mark. + * + * @param {string} projectDir + * @param {string} takeId + * @param {{ by?: string | null, clear?: boolean, known?: string[] | null, now?: Date }} [opts] + * `known`: the project's take ids, to refuse a `by` that is not one of them + */ +export async function setTakeSuperseded(projectDir, takeId, { by = null, clear = false, known = null, now = new Date() } = {}) { + if (!isTakeId(takeId)) throw new Error("not a take id"); + if (by !== null && !isTakeId(by)) throw new Error(`"${by}" is not a take id`); + if (by === takeId) throw new Error(`a take is not superseded by itself`); + if (by !== null && known && !known.includes(by)) throw new Error(`no take ${by} in this project`); + const file = verdictsFileOf(projectDir); + return withTakesLock(async () => { + const map = await readVerdictsForWrite(file); + const prev = map[takeId] ?? { verdict: null, note: "", at: "" }; + /** @type {Record<string, any>} */ + const row = { ...prev, at: now.toISOString() }; + if (clear) delete row.superseded; + else { + if (prev.picked === true) throw new Error(`${takeId} is the picked take of its group — pick another first`); + row.superseded = { by, at: now.toISOString() }; + } + if (emptyRow(row)) delete map[takeId]; + else map[takeId] = row; + await writeVerdicts(file, map); + return { entry: map[takeId] ?? null, verdicts: map }; + }); +} + +/** * Every take with its verdict, for an agent reading the conversation back * (`umtool notes`, the notes digest): label, group, summary and changes from * take.json, and the operator's verdict and note from verdicts.json. A verdict @@ -409,6 +504,7 @@ export async function takesWithVerdicts(projectDir) { note: verdicts[t.id]?.note ?? "", at: verdicts[t.id]?.at ?? "", ...(verdicts[t.id]?.picked ? { picked: /** @type {const} */ (true) } : {}), + ...(verdicts[t.id]?.superseded ? { superseded: verdicts[t.id].superseded } : {}), })); const known = new Set(out.map((t) => t.id)); for (const [id, v] of Object.entries(verdicts)) { diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -13,10 +13,17 @@ // [--id ID] [--section N] [--lock] [--lock-end] // [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U] // umtool timeline <project> move <id> --to <index> +// umtool timeline <project> place <id…> --before <id|-> [--section N] // umtool timeline <project> remove <id> | duplicate <id> // umtool timeline <project> post <json|@file> | post-remove <id> // umtool timeline <project> teaser <id> <patch-json|@file> // umtool timeline <project> undo +// umtool timeline <project> sections | section-move <id…> --to-section N [--start] +// | section-add --after <id> [--label L] [--color C] | section-boundary <k> --after <id> +// | section-remove <k> | section-set <k> [--label L] [--color C] +// umtool timeline <project> split <id> <second> +// umtool timeline <project> flash-forward <id> <from>-<to> (--after <id|-> | --to-section N [--start]) +// [--move] [--quote Q] [--id ID] // // An insert's attribution (--title, --date, --quote, --cite, --cite-url) is a // second write, through updateClip -- the writer `umtool window` and the @@ -51,8 +58,15 @@ import { insertEntry, manifestToken, moveEntry, + placeEntries, + moveSectionBoundary, + moveToSection, + addSection, removeEntry, + removeSection, rejectClip, + sectionsOf, + updateSection, removeWrongSpeaker, REMOVED_FILE, removePost, @@ -73,6 +87,10 @@ export const TIMELINE_USAGE = [ " Under the deck --title is the deck's title (onscreen.title); a cut whose deck titles", " are dates gets --date as one too. The section is <id>'s unless --section says", " umtool timeline <project> move <id> --to <index> <index> is its place AFTER the move (0 first)", + " umtool timeline <project> place <id> [<id>…] --before <id|-> [--section N] Play's drag on the reel strip:", + " before that entry (`-`: at the end), the clips joining section N (default: the section", + " of the clip they land after); every other clip keeps its section, the markers follow,", + " an emptied section is refused; each place is its own undo point", " umtool timeline <project> remove <id> | duplicate <id> (--at <index> names one of an id's twins)", " umtool timeline <project> reject <id> <why> [--note TEXT] reject it and remove it, on the record (removed.json):", ` <why> is ${REJECT_REASON_IDS.join("|")} -- not-matching and wrong-speaker are fact`, @@ -83,6 +101,17 @@ export const TIMELINE_USAGE = [ " umtool timeline <project> post-remove <id>", " umtool timeline <project> teaser <id> <patch-json|@file> lines, beat, dip, tail, tailWait (null removes one)", " umtool timeline <project> undo restore the newest automatic snapshot", + " umtool timeline <project> sections [--json] the deck's sections: §, label, colour, its marker, its clips", + " umtool timeline <project> section-move <id> [<id>…] --to-section N [--start]", + " clips to the end (--start: the start) of section N, every marker following", + " umtool timeline <project> section-add --after <id> [--label L] [--color C] new section after the clip", + " umtool timeline <project> section-boundary <marker> --after <id> drag a boundary (between its neighbours)", + " umtool timeline <project> section-remove <marker> | section-set <marker> [--label L] [--color C]", + " every section op brings the take patches' markers (*.patch.json in step with the manifest) along", + " umtool timeline <project> split <id> <second> two clips at that source second (each half's quote from the words)", + " umtool timeline <project> flash-forward <id> <from>-<to> (--after <id|-> | --to-section N [--start])", + " [--move] [--quote Q] [--id ID] a tight copy of the span elsewhere, with the clip's attribution", + " and locks, as repeatOf the clip (--move: the span leaves the clip, which keeps the rest)", " umtool timeline <project> --take <id> [ls | move <id> --to <index> | remove <id> | undo]", " a take's timeline (walk a take): written into the take's patch (takes/<id>/take.json),", " each write with an undo point of the take's own; the project's manifest is untouched", @@ -91,8 +120,9 @@ export const TIMELINE_USAGE = [ "validators, and on a generated manifest leaves an `edit` note for its generator. The Cut tab's timeline.", ].join("\n"); -const VERBS = ["ls", "insert", "move", "remove", "reject", "wrong-speaker", "duplicate", "post", "post-remove", "teaser", "undo"]; -const VALUED = new Set(["--after", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note"]); +const SECTION_VERBS = ["sections", "section-move", "section-add", "section-boundary", "section-remove", "section-set"]; +const VERBS = ["ls", "insert", "move", "place", "remove", "reject", "wrong-speaker", "duplicate", "post", "post-remove", "teaser", "undo", ...SECTION_VERBS, "split", "flash-forward"]; +const VALUED = new Set(["--after", "--before", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note", "--to-section", "--label", "--color"]); /** What `--take <id>` does on a take's timeline (takeEdit.mjs): the walk's structure and its undo. */ const TAKE_VERBS = ["ls", "move", "remove", "undo"]; @@ -338,6 +368,17 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => const manifest = await readManifest(project.dir); if (!manifest) throw new CliError(`${project.id} has no manifest`); + if (verb === "sections") { + const sections = sectionsOf(manifest); + if (json) { + out(JSON.stringify({ project: project.id, token: await manifestToken(project.dir), sections }, null, 2)); + return 0; + } + if (!deckOn(manifest.render)) throw new CliError(`${project.id} has no on-screen deck: its sections are not markers`); + for (const line of sectionLines(sections)) out(line); + return 0; + } + if (verb === "ls") { const rows = timelineRows(manifest); if (json) { @@ -421,6 +462,14 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => ({ result, editNotes } = await write((token) => removeEntry(project.dir, id, { token, at }))); break; } + case "place": { + if (!rest.length) throw new CliError("place needs one or more entry ids"); + const before = flags.get("--before"); + if (typeof before !== "string" || !before) throw new CliError("place needs --before <id> (`-`: at the end)"); + const section = intFlag(flags, "--section"); + ({ result, editNotes } = await write((token) => placeEntries(project.dir, rest, { token, before: before === "-" ? null : before, section }))); + break; + } case "reject": { const id = need(rest[0], "a clip id"); const why = need(rest[1], `why: ${REJECT_REASON_IDS.join(", ")}`); @@ -461,6 +510,67 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => ({ result, editNotes } = await write((token) => undoStructural(project.dir, { token }))); break; } + case "section-move": { + if (!rest.length) throw new CliError("section-move needs one or more clip ids"); + const section = intFlag(flags, "--to-section"); + if (section === null) throw new CliError("section-move needs --to-section N (`umtool timeline <project> sections` lists them)"); + ({ result, editNotes } = await write((token) => moveToSection(project.dir, rest, section, { token, position: flags.has("--start") ? "start" : "end" }))); + break; + } + case "section-add": { + const after = flags.get("--after"); + if (typeof after !== "string" || !after) throw new CliError("section-add needs --after <clip id>"); + const str = (k) => (typeof flags.get(k) === "string" ? String(flags.get(k)) : null); + ({ result, editNotes } = await write((token) => addSection(project.dir, after, { label: str("--label"), color: str("--color") }, { token }))); + break; + } + case "section-boundary": { + const marker = Number(need(rest[0], "a marker's number (`sections` lists them)")); + const after = flags.get("--after"); + if (typeof after !== "string" || !after) throw new CliError("section-boundary needs --after <clip id>"); + ({ result, editNotes } = await write((token) => moveSectionBoundary(project.dir, marker, after, { token }))); + break; + } + case "section-remove": { + const marker = Number(need(rest[0], "a marker's number (`sections` lists them)")); + ({ result, editNotes } = await write((token) => removeSection(project.dir, marker, { token }))); + break; + } + case "section-set": { + const marker = Number(need(rest[0], "a marker's number (`sections` lists them)")); + const patch = Object.fromEntries([["--label", "label"], ["--color", "color"]].filter(([f]) => flags.has(f)).map(([f, k]) => [k, flags.get(f) === true ? "" : flags.get(f)])); + ({ result, editNotes } = await write((token) => updateSection(project.dir, marker, patch, { token }))); + break; + } + case "split": { + const id = need(rest[0], "a clip id"); + const second = Number(need(rest[1], "the source second to split at")); + if (!Number.isFinite(second)) throw new CliError("split <id> <second>: the second is a number"); + const { runClipEditorOp } = await import("./clipEditor.mjs"); + ({ result, editNotes } = await write(async (token) => (await runClipEditorOp(project, { op: "split", clip: id, at: second, token })).result)); + break; + } + case "flash-forward": { + const id = need(rest[0], "a clip id"); + const span = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/.exec(need(rest[1], "the span: <from>-<to> in source seconds")); + if (!span) throw new CliError("flash-forward <id> <from>-<to>: source seconds, e.g. 3343.6-3356.3"); + const section = intFlag(flags, "--to-section"); + if (section === null && !flags.has("--after")) throw new CliError("flash-forward needs --after <id> (`-`: the start) or --to-section N"); + const afterArg = flags.has("--after") ? String(flags.get("--after")) : null; + const body = { + op: "flash-forward", + clip: id, + from: Number(span[1]), + to: Number(span[2]), + ...(section !== null ? { section, position: flags.has("--start") ? "start" : "end" } : { after: afterArg === "-" ? null : afterArg }), + move: flags.has("--move"), + ...(typeof flags.get("--quote") === "string" ? { quote: flags.get("--quote") } : {}), + ...(typeof flags.get("--id") === "string" ? { id: flags.get("--id") } : {}), + }; + const { runClipEditorOp } = await import("./clipEditor.mjs"); + ({ result, editNotes } = await write(async (token) => (await runClipEditorOp(project, { ...body, token })).result)); + break; + } } if (json) { @@ -469,6 +579,13 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => } out(summaryOf(verb, result, attribution)); for (const line of result.reanchored ?? []) out(` re-anchored: ${line}`); + // The take patches beside the manifest follow the same removal (patchMarkers.mjs). + for (const p of result.patches ?? []) { + for (const line of p.notes ?? []) out(` ${p.file}: ${line}`); + if (p.error) out(` ${p.file}: ${p.error}`); + } + for (const f of result.sectionPatches?.synced ?? []) out(` patch markers synced: ${f}`); + for (const f of result.sectionPatches?.skipped ?? []) out(` patch NOT synced: ${f.file} — ${f.why}`); if (result.record) out(` on record: ${REMOVED_FILE} (${result.record.reason}${result.record.correction ? `: ${result.record.correction}` : ""}${result.record.note ? `: ${result.record.note}` : ""})`); if (result.snapshot?.rel && !result.snapshot.skipped) out(` undo point: ${result.snapshot.rel}`); else if (result.snapshot?.error) out(` NO undo point: ${result.snapshot.error}`); @@ -539,8 +656,30 @@ async function takeTimeline(project, take, verb, rest, flags, { out, json }) { return 0; } +/** `sections`, one line each: §, its marker, colour, label, its clips. */ +export function sectionLines(sections) { + return sections.map((s) => { + const clips = s.clips.length > 6 ? `${s.clips.slice(0, 3).join(" ")} … ${s.clips.slice(-2).join(" ")}` : s.clips.join(" "); + return `§${String(s.index).padEnd(3)} ${s.marker === null ? " " : `m${String(s.marker).padEnd(4)} `} ${String(s.color ?? "").padEnd(8)} ${(s.label ?? (s.index === 0 ? "(the opening)" : "(no label)")).padEnd(26)} ${String(s.clips.length).padStart(3)} clip(s): ${clips}`; + }); +} + function summaryOf(verb, r, attribution) { switch (verb) { + case "section-move": + return `moved ${r.ids.join(", ")} to the ${r.position} of §${r.section}${r.label ? ` (${r.label})` : ""}`; + case "section-add": + return `new section after ${r.after} (marker ${r.marker}${r.label ? `, "${r.label}"` : ""}${r.color ? `, ${r.color}` : ""}): it opens on ${r.opens}`; + case "section-boundary": + return `marker ${r.marker} follows ${r.after} now (was ${r.from})${r.moved.length ? `: ${r.moved.join(", ")} now in ${r.into}` : ""}`; + case "section-remove": + return `removed marker ${r.marker}${r.removed?.label ? ` ("${r.removed.label}")` : ""}: its section joins the one before it`; + case "section-set": + return `marker ${r.marker}: ${JSON.stringify(r.entry)}`; + case "split": + return `split: ${r.id} | ${r.second}`; + case "flash-forward": + return `${r.move ? "moved" : "copied"} ${r.source}'s span to ${r.id} at ${r.at}${r.section ? ` (§${r.section.index}${r.section.label ? ` ${r.section.label}` : ""})` : ""}${r.move && r.rest ? `; ${r.source} keeps ${r.rest.start}–${r.rest.end}` : r.move ? "" : ` (repeatOf ${r.source})`}`; case "insert": { const e = attribution ?? r.entry; const head = `inserted ${r.id} at ${r.at}: ${e.channel ? `${e.channel}/` : ""}${e.video}@${e.start}-${e.end}`; @@ -558,6 +697,8 @@ function summaryOf(verb, r, attribution) { } case "move": return `moved ${r.id}: ${r.from} -> ${r.to}`; + case "place": + return `placed ${r.ids.join(", ")} ${r.before ? `before ${r.before}` : "at the end"} (index ${r.from} -> ${r.to})${r.section !== null ? ` in §${r.section}${r.label ? ` (${r.label})` : ""}` : ""}`; case "remove": return `removed ${r.id} (was at ${r.at})`; case "wrong-speaker": diff --git a/umtool/lib/report/trailerBeats.mjs b/umtool/lib/report/trailerBeats.mjs @@ -0,0 +1,439 @@ +// THE TRAILER'S BEATS, edited (UI notes 2026-10-30, item 11). +// +// `umtool trailer <p> --take <t> --beats promo/trailer-beats.json` cuts a +// trailer out of a finished master (report-to-video/trailer.mjs). The beats +// file was hand JSON: beats went stale after tightening (five fell outside +// their clips on the Ember cut), the X limit (under 2:20) was checked after the +// encode, and putting the beats in the cut's order needed a script. +// +// This is that file's ONE writer -- the Trailer page and `umtool trailer-beats` +// both go through it -- and its reader, which says, before any encode: +// - each beat's length (a clip beat's gaps taken out, as the master plays it) +// and the running length against the platform limit, with the trailer's +// crossfades and the brand intro counted; +// - each beat that falls outside its clip's window, or names a clip that is +// no longer in the cut; +// - whether the beats are in the cut's order (Order by the cut puts them so). +// +// The file keeps its shape: a plain array stays an array (what `--beats` has +// always read) until a setting is saved, when it becomes `{ limit, xfade, +// intro, beats }` -- parseBeats reads `{ beats }` too. Its indent is kept. A +// file that does not parse is never written over. The token is its mtime. +// +// Plain ESM: the CLI runs it under bare node. +import { copyFile, mkdir, readFile, readdir, rename, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { gappedLength, gapsOf } from "umtool-report-to-video/gaps"; +import { TRAILER_XFADE_DEFAULT, TrailerError, parseBeats } from "umtool-report-to-video/trailer"; +import { indentOf } from "./patchMarkers.mjs"; +import { sectionModel, sectionWords } from "./sectionEdit.mjs"; +import { trailerCandidates } from "./trailerCandidates.mjs"; + +export const TRAILER_BEATS_FILE = path.join("promo", "trailer-beats.json"); +/** X's video limit is 2:20; a trailer must be UNDER it. */ +export const TRAILER_LIMIT_DEFAULT = 140; +/** Platform limits a person picks from (seconds). */ +export const TRAILER_LIMITS = Object.freeze([ + { id: "x", label: "X (2:20)", seconds: 140 }, + { id: "instagram", label: "Instagram reel (1:30)", seconds: 90 }, + { id: "shorts", label: "YouTube Short (3:00)", seconds: 180 }, + { id: "tiktok", label: "TikTok (10:00)", seconds: 600 }, +]); +/** A beat edge this close to its clip's edge is on it (the build records keep 3 dp). */ +const EPS = 0.02; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const r2 = (n) => Number(Number(n).toFixed(2)); + +export class BeatsStale extends Error { + constructor(expected, got) { + super(`the trailer's beats changed since you read them (${got} vs ${expected})`); + this.name = "BeatsStale"; + this.stale = true; + } +} + +const beatsFile = (dir) => path.join(dir, TRAILER_BEATS_FILE); + +/** @typedef {{ limit?: number, xfade?: number, intro?: boolean }} TrailerSettings */ +/** @typedef {{ token?: string | null }} BeatsWriteOpts */ + +/** The file's mtime, the token a writer hands back; null when there is no file. */ +export async function beatsToken(dir) { + const st = await stat(beatsFile(dir)).catch(() => null); + return st ? String(Math.round(st.mtimeMs)) : null; +} + +/** + * The beats file, read: `{ exists, shape, beats, settings, indent }`. Missing: + * an empty array. Not JSON, or neither an array nor `{ beats }`: an error, + * so nothing writes over it. + * + * @param {string} dir + */ +export async function readTrailerBeats(dir) { + let text; + try { + text = await readFile(beatsFile(dir), "utf8"); + } catch { + return { exists: false, shape: /** @type {"array" | "object"} */ ("array"), beats: /** @type {any[]} */ ([]), settings: /** @type {TrailerSettings} */ ({}), indent: 1, token: /** @type {string | null} */ (null), doc: null }; + } + let doc; + try { + doc = JSON.parse(text); + } catch (e) { + throw new Error(`${TRAILER_BEATS_FILE} does not parse; not reading or writing it (${e instanceof Error ? e.message : e})`); + } + const beats = Array.isArray(doc) ? doc : Array.isArray(doc?.beats) ? doc.beats : null; + if (!beats) throw new Error(`${TRAILER_BEATS_FILE} is neither a list of beats nor { "beats": [...] }`); + /** @type {TrailerSettings} */ + const settings = {}; + if (isObj(doc)) { + if (typeof doc.limit === "number") settings.limit = doc.limit; + if (typeof doc.xfade === "number") settings.xfade = doc.xfade; + if (typeof doc.intro === "boolean") settings.intro = doc.intro; + } + return { exists: true, shape: /** @type {"array" | "object"} */ (Array.isArray(doc) ? "array" : "object"), beats, settings, indent: indentOf(text), token: await beatsToken(dir), doc }; +} + +/** @type {Promise<unknown>} */ +let queue = Promise.resolve(); +function withBeatsLock(fn) { + const run = queue.then(fn, fn); + queue = run.then(() => undefined, () => undefined); + return run; +} + +/** + * One write: the token, the file re-read inside the lock, `mutate(beats, + * settings)` (which throws to refuse), every beat checked by the trailer's own + * parseBeats, a `.bak` of the file as it was, then tmp + rename. + */ +async function beatsWrite(dir, token, mutate) { + return withBeatsLock(async () => { + const current = await beatsToken(dir); + if (token !== null && token !== undefined && current !== token) throw new BeatsStale(token, current); + const read = await readTrailerBeats(dir); + const beats = JSON.parse(JSON.stringify(read.beats)); + const settings = { ...read.settings }; + const result = mutate(beats, settings); + if (beats.length) { + try { + parseBeats(beats); + } catch (e) { + throw new Error(e instanceof TrailerError ? e.message : String(e)); + } + } + const hasSettings = Object.keys(settings).length > 0; + const out = read.shape === "array" && !hasSettings ? beats : { ...(isObj(read.doc) ? read.doc : {}), ...settings, beats }; + if (isObj(out)) for (const k of ["limit", "xfade", "intro"]) if (!(k in settings)) delete out[k]; + const file = beatsFile(dir); + await mkdir(path.dirname(file), { recursive: true }); + if (read.exists) await copyFile(file, `${file}.bak`).catch(() => {}); + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, JSON.stringify(out, null, read.indent) + "\n", "utf8"); + await rename(tmp, file); + return { ...result, beats, settings, token: await beatsToken(dir) }; + }); +} + +/** A beat as a person writes it: `{ id, start, end, label? }` or `{ at, dur, label? }`, rounded to 2 dp. */ +function cleanBeat(b) { + if (!isObj(b)) throw new Error("a beat is { id, start, end } or { at, dur }"); + const label = typeof b.label === "string" && b.label.trim() ? { label: b.label.trim().slice(0, 120) } : {}; + if (b.id !== undefined) return { id: String(b.id), start: r2(b.start), end: r2(b.end), ...label }; + return { at: r2(b.at), dur: r2(b.dur), ...label }; +} + +const indexIn = (beats, i, what = "beat") => { + const n = Number(i); + if (!Number.isInteger(n) || n < 0 || n >= beats.length) throw new Error(`no ${what} ${Number(i) + 1} (1–${beats.length})`); + return n; +}; + +/** + * Add a beat at index `at` (default: where the cut's order puts it, else the end). + * @param {string} dir + * @param {Record<string, unknown>} beat + * @param {{ token?: string | null, at?: number | null, manifest?: Record<string, any> | null }} [opts] + */ +export async function addTrailerBeat(dir, beat, { token = null, at = null, manifest = null } = {}) { + return beatsWrite(dir, token, (beats) => { + const b = cleanBeat(beat); + let i = beats.length; + if (at !== null && at !== undefined) { + i = Number(at); + if (!Number.isInteger(i) || i < 0 || i > beats.length) throw new Error(`at must be 0–${beats.length}`); + } else if (manifest && b.id !== undefined) { + // In the cut's order: before the first beat whose clip comes later. + const order = cutOrder(manifest); + const mine = order.get(b.id); + if (mine !== undefined) { + const k = beats.findIndex((x) => x.id !== undefined && (order.get(x.id) ?? -1) > mine); + if (k >= 0) i = k; + } + } + beats.splice(i, 0, b); + return { index: i, beat: b }; + }); +} + +/** + * Change beat `i`'s seconds or label (a key given as null removes a label). + * @param {string} dir + * @param {number} i + * @param {Record<string, unknown>} patch + * @param {BeatsWriteOpts} [opts] + */ +export async function updateTrailerBeat(dir, i, patch, { token = null } = {}) { + return beatsWrite(dir, token, (beats) => { + const n = indexIn(beats, i); + if (!isObj(patch)) throw new Error("a beat patch is { start?, end?, at?, dur?, label? }"); + const b = { ...beats[n] }; + for (const k of ["start", "end", "at", "dur"]) if (patch[k] !== undefined) b[k] = patch[k]; + if (patch.label !== undefined) { + if (patch.label === null || patch.label === "") delete b.label; + else b.label = patch.label; + } + beats[n] = cleanBeat(b); + return { index: n, beat: beats[n] }; + }); +} + +/** + * Remove beat `i`. + * @param {string} dir + * @param {number} i + * @param {BeatsWriteOpts} [opts] + */ +export async function removeTrailerBeat(dir, i, { token = null } = {}) { + return beatsWrite(dir, token, (beats) => { + const n = indexIn(beats, i); + const [gone] = beats.splice(n, 1); + return { index: n, removed: gone }; + }); +} + +/** + * Move beat `i` to index `to` (its place after the move). + * @param {string} dir + * @param {number} i + * @param {number} to + * @param {BeatsWriteOpts} [opts] + */ +export async function moveTrailerBeat(dir, i, to, { token = null } = {}) { + return beatsWrite(dir, token, (beats) => { + const n = indexIn(beats, i); + const t = Number(to); + if (!Number.isInteger(t) || t < 0 || t >= beats.length) throw new Error(`to must be 1–${beats.length}`); + const [b] = beats.splice(n, 1); + beats.splice(t, 0, b); + return { from: n, to: t }; + }); +} + +/** + * Order the beats as the cut plays them: clip beats by their clip's place in + * the timeline (then by start), a raw `{ at, dur }` beat by its master second + * among them as best it can -- kept after the clip beat before it. A beat + * naming a clip no longer in the cut goes last, and is still flagged. + * @param {string} dir + * @param {Record<string, any>} manifest + * @param {BeatsWriteOpts} [opts] + */ +export async function orderTrailerBeats(dir, manifest, { token = null } = {}) { + return beatsWrite(dir, token, (beats) => { + const order = cutOrder(manifest); + const keyed = beats.map((b, k) => ({ b, k, key: b.id !== undefined ? order.get(b.id) ?? Infinity : null })); + // A raw beat keeps its neighbour: it takes the key of the clip beat before it. + let last = -1; + for (const x of keyed) { + if (x.key === null) x.key = last; + else if (Number.isFinite(x.key)) last = x.key; + } + keyed.sort((a, b) => a.key - b.key || (a.b.id !== undefined && b.b.id !== undefined && a.b.id === b.b.id ? a.b.start - b.b.start : a.k - b.k)); + const moved = keyed.some((x, i) => x.k !== i); + beats.splice(0, beats.length, ...keyed.map((x) => x.b)); + return { moved }; + }); +} + +/** + * The trailer's settings: `limit` (seconds, the platform's), `xfade` (the + * trailer's crossfade), `intro` (opens on the brand intro). null removes one + * (its default again). + * @param {string} dir + * @param {Record<string, unknown>} patch + * @param {BeatsWriteOpts} [opts] + */ +export async function setTrailerSettings(dir, patch, { token = null } = {}) { + return beatsWrite(dir, token, (_beats, settings) => { + if (!isObj(patch)) throw new Error("settings are { limit?, xfade?, intro? }"); + for (const k of ["limit", "xfade"]) { + if (patch[k] === undefined) continue; + if (patch[k] === null || patch[k] === "") { + delete settings[k]; + continue; + } + const v = Number(patch[k]); + if (!Number.isFinite(v) || v < 0 || (k === "limit" && v < 5) || (k === "xfade" && v > 3)) { + throw new Error(k === "limit" ? "limit is the platform's limit in seconds (5 or more)" : "xfade is the crossfade in seconds (0–3)"); + } + settings[k] = r2(v); + } + if (patch.intro !== undefined) { + if (patch.intro === null) delete settings.intro; + else settings.intro = patch.intro === true; + } + return {}; + }); +} + +/** Clip id → its place among the cut's clips. */ +function cutOrder(manifest) { + const order = new Map(); + let n = 0; + for (const e of manifest?.timeline ?? []) { + if (e?.type !== "clip") continue; + if (!order.has(e.id)) order.set(e.id, n); + n += 1; + } + return order; +} + +/** "m:ss.s" */ +export function clockOf(s) { + if (!Number.isFinite(s)) return "—"; + const neg = s < 0; + const a = Math.abs(s); + const m = Math.floor(a / 60); + const r = a - m * 60; + return `${neg ? "−" : ""}${m}:${r < 10 ? "0" : ""}${r.toFixed(1)}`; +} + +/** + * The beats against the cut, before any encode. Pure. + * + * @param {Record<string, any>} manifest the project's manifest + * @param {{ beats: any[], settings?: Record<string, any> }} doc readTrailerBeats's + * @param {{ introSeconds?: number | null }} [opts] the brand intro's length in a built take, when known + */ +export function trailerView(manifest, doc, { introSeconds = null } = {}) { + const settings = doc.settings ?? {}; + const limit = typeof settings.limit === "number" ? settings.limit : TRAILER_LIMIT_DEFAULT; + const xfade = typeof settings.xfade === "number" ? settings.xfade : TRAILER_XFADE_DEFAULT; + const intro = settings.intro === true; + const tl = manifest?.timeline ?? []; + const order = cutOrder(manifest); + const model = sectionModel(manifest); + let sum = intro && Number.isFinite(introSeconds) ? Number(introSeconds) : 0; + let pieces = intro ? 1 : 0; + let lastKey = -1; + let inOrder = true; + const rows = (doc.beats ?? []).map((raw, i) => { + const problems = []; + let kind = "raw"; + let seconds = 0; + let clip = null; + if (isObj(raw) && raw.id !== undefined) { + kind = "clip"; + const e = tl.find((x) => x?.id === raw.id); + const span = Number(raw.end) - Number(raw.start); + if (!e) { + problems.push(`${raw.id} is not in the cut any more`); + seconds = Math.max(0, span); + } else if (e.type !== "clip") { + problems.push(`${raw.id} is a ${e.type ?? "non-clip"} entry: use { at, dur } for it`); + seconds = Math.max(0, span); + } else { + const lo = e.cutStart ?? e.start; + const hi = e.cutEnd ?? e.end; + if (raw.start < lo - EPS) problems.push(`starts ${(lo - raw.start).toFixed(2)} s before ${raw.id}'s window (${lo}–${hi})`); + if (raw.end > hi + EPS) problems.push(`ends ${(raw.end - hi).toFixed(2)} s after ${raw.id}'s window (${lo}–${hi})`); + const a = Math.max(raw.start, lo); + const b = Math.min(raw.end, hi); + seconds = b > a ? gappedLength(a, b, gapsOf(e)) : 0; + const k = order.get(raw.id); + if (k < lastKey) inOrder = false; + lastKey = Math.max(lastKey, k); + const sec = model.sections[model.sectionOf.get(raw.id) ?? 0]; + clip = { start: lo, end: hi, at: k, section: model.sections.length > 1 && sec ? sectionWords(sec) : null, quote: typeof e.quote === "string" ? e.quote : null }; + } + if (!(span > 0)) problems.push(`end ${raw.end} is not after start ${raw.start}`); + } else if (isObj(raw)) { + seconds = Math.max(0, Number(raw.dur) || 0); + } + pieces += 1; + sum += seconds; + const running = sum - xfade * Math.max(0, pieces - 1); + return { + n: i + 1, + kind, + ...(kind === "clip" ? { id: String(raw.id), start: raw.start, end: raw.end } : { at: raw?.at, dur: raw?.dur }), + label: typeof raw?.label === "string" ? raw.label : null, + seconds: r2(seconds), + running: r2(running), + over: running > limit, + clip, + problems, + }; + }); + const total = r2(sum - xfade * Math.max(0, pieces - 1)); + return { + file: TRAILER_BEATS_FILE, + limit, + xfade, + intro, + introSeconds: intro ? (Number.isFinite(introSeconds) ? Number(introSeconds) : null) : null, + total, + remaining: r2(limit - total), + over: total >= limit, + inOrder, + outside: rows.filter((r) => r.problems.length).length, + rows, + }; +} + +/** + * The brand intro's length, from the newest built take whose schedule has + * one (`takes/<id>/out/sourced/schedule.json`, a segment of type "intro"), + * else null. + * + * @param {string} dir + * @returns {Promise<number | null>} + */ +export async function introSecondsOf(dir) { + const takes = path.join(dir, "takes"); + const names = await readdir(takes).catch(() => []); + let best = null; + for (const n of names) { + const f = path.join(takes, n, "out", "sourced", "schedule.json"); + const st = await stat(f).catch(() => null); + if (!st || (best && best.mtime >= st.mtimeMs)) continue; + try { + const s = JSON.parse(await readFile(f, "utf8")); + const seg = (s.segments ?? []).find((x) => x?.type === "intro" || x?.id === "brand-intro"); + if (!seg) continue; + const len = Number.isFinite(seg.duration) ? seg.duration : Number.isFinite(seg.end) ? seg.end - seg.start : null; + if (Number.isFinite(len)) best = { mtime: st.mtimeMs, len }; + } catch { + // a schedule that does not read says nothing about the intro + } + } + return best ? r2(best.len) : null; +} + +/** + * The walk's ★ favourites not yet beats: the trailer's candidates -- + * lane/ui-cut-integrity's trailerCandidates (a starred clip that will play, + * as a beat over what it plays), less the clips already beats. + * + * @param {Record<string, any>} manifest + * @param {any[]} beats + */ +export function trailerCandidatesOf(manifest, beats = []) { + const used = new Set(beats.filter((b) => isObj(b) && b.id !== undefined).map((b) => b.id)); + return trailerCandidates(manifest) + .filter((c) => !used.has(c.id)) + .map((c) => ({ id: c.id, start: c.start, end: c.end, quote: c.quote ?? null, walkNote: c.walkNote ?? null })); +} diff --git a/umtool/lib/report/trailerBeats.test.mjs b/umtool/lib/report/trailerBeats.test.mjs @@ -0,0 +1,142 @@ +// The trailer's beats (trailerBeats.mjs): the one writer of promo/trailer-beats.json, +// and the reader that flags a beat outside its clip and keeps the running length. +// +// Run with: pnpm test:scripts +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 { + BeatsStale, + TRAILER_BEATS_FILE, + addTrailerBeat, + beatsToken, + introSecondsOf, + moveTrailerBeat, + orderTrailerBeats, + readTrailerBeats, + removeTrailerBeat, + setTrailerSettings, + trailerCandidatesOf, + trailerView, + updateTrailerBeat, +} from "./trailerBeats.mjs"; + +const manifest = () => ({ + timeline: [ + { type: "clip", id: "a", video: "v", start: 10, end: 20 }, + { type: "card", id: "k", seconds: 3 }, + { type: "clip", id: "b", video: "v", start: 30, end: 50, gaps: [{ from: 35, to: 40 }], star: true }, + { type: "clip", id: "c", video: "v", start: 60, end: 70, cutStart: 61, cutEnd: 69, star: true, verdict: "confirmed" }, + ], +}); + +async function project(beats) { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-beats-")); + if (beats !== undefined) { + await mkdir(path.join(dir, "promo"), { recursive: true }); + await writeFile(path.join(dir, TRAILER_BEATS_FILE), typeof beats === "string" ? beats : JSON.stringify(beats, null, 1) + "\n"); + } + return dir; +} +const fileOf = async (dir) => readFile(path.join(dir, TRAILER_BEATS_FILE), "utf8"); + +test("the view: each beat's length (gaps out), the running length, the limit, beats outside their clip", () => { + const v = trailerView(manifest(), { + beats: [ + { id: "a", start: 12, end: 18 }, + { id: "b", start: 30, end: 45 }, + { at: 100, dur: 4 }, + { id: "c", start: 60, end: 66 }, + { id: "gone", start: 1, end: 3 }, + ], + settings: { xfade: 0.5, intro: true, limit: 20 }, + }, { introSeconds: 4 }); + assert.deepEqual(v.rows.map((r) => r.seconds), [6, 10, 4, 5, 2]); + // 4 (intro) + 6 + 10 + 4 + 5 + 2 = 31, six pieces, five crossfades of 0.5 + assert.equal(v.total, 28.5); + assert.equal(v.over, true); + assert.equal(v.rows[1].running, 19, "intro + a + b, two crossfades"); + assert.equal(v.rows[1].over, false); + assert.equal(v.rows[2].over, true); + assert.deepEqual(v.rows[3].problems, ["starts 1.00 s before c's window (61–69)"]); + assert.deepEqual(v.rows[4].problems, ["gone is not in the cut any more"]); + assert.equal(v.outside, 2); + assert.equal(v.inOrder, true); +}); + +test("the view says when the beats are out of the cut's order; X's 2:20 is the default limit", () => { + const v = trailerView(manifest(), { beats: [{ id: "c", start: 62, end: 64 }, { id: "a", start: 12, end: 14 }] }); + assert.equal(v.inOrder, false); + assert.equal(v.limit, 140); + assert.equal(v.total, 3.7, "two beats, one 0.3 s crossfade"); +}); + +test("add, edit, move, remove: the file keeps its shape and indent, checked by parseBeats", async () => { + const dir = await project([{ id: "a", start: 12, end: 14 }]); + try { + const t0 = await beatsToken(dir); + const r = await addTrailerBeat(dir, { id: "c", start: 62, end: 65.555 }, { token: t0, manifest: manifest() }); + assert.equal(r.index, 1); + const r2 = await addTrailerBeat(dir, { id: "b", start: 31, end: 34 }, { manifest: manifest() }); + assert.equal(r2.index, 1, "in the cut's order: before c"); + let text = await fileOf(dir); + assert.match(text, /^\[\n \{/, "still an array, still a 1-space indent"); + assert.deepEqual(JSON.parse(text)[2], { id: "c", start: 62, end: 65.56 }); + await updateTrailerBeat(dir, 2, { end: 64, label: "the line" }); + await moveTrailerBeat(dir, 2, 0); + assert.deepEqual(JSON.parse(await fileOf(dir)).map((b) => b.id), ["c", "a", "b"]); + await removeTrailerBeat(dir, 1); + assert.deepEqual(JSON.parse(await fileOf(dir)).map((b) => b.id), ["c", "b"]); + await assert.rejects(updateTrailerBeat(dir, 0, { end: 50 }).then(() => updateTrailerBeat(dir, 0, { start: 60, end: 59 })), /not after start/); + await assert.rejects(addTrailerBeat(dir, { id: "a", start: 1, end: 2 }, { token: "1" }), (e) => e instanceof BeatsStale); + await orderTrailerBeats(dir, manifest()); + assert.deepEqual(JSON.parse(await fileOf(dir)).map((b) => b.id), ["b", "c"]); + // A setting turns the file into { limit, …, beats }, which --beats reads too. + await setTrailerSettings(dir, { limit: 90, intro: true }); + text = await fileOf(dir); + const doc = JSON.parse(text); + assert.equal(doc.limit, 90); + assert.equal(doc.intro, true); + assert.equal(doc.beats.length, 2); + const back = await readTrailerBeats(dir); + assert.equal(back.shape, "object"); + assert.deepEqual(back.settings, { limit: 90, intro: true }); + await setTrailerSettings(dir, { limit: null }); + assert.equal(JSON.parse(await fileOf(dir)).limit, undefined); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a beats file that does not parse is never written over; none at all starts one", async () => { + const bad = await project("[{ not json"); + const none = await project(); + try { + await assert.rejects(addTrailerBeat(bad, { id: "a", start: 1, end: 2 }), /does not parse/); + assert.equal(await fileOf(bad), "[{ not json"); + await addTrailerBeat(none, { id: "a", start: 12, end: 14 }); + assert.deepEqual(JSON.parse(await fileOf(none)), [{ id: "a", start: 12, end: 14 }]); + } finally { + await rm(bad, { recursive: true, force: true }); + await rm(none, { recursive: true, force: true }); + } +}); + +test("the ★ candidates are the starred clips not yet beats, over what they play", () => { + assert.deepEqual(trailerCandidatesOf(manifest(), [{ id: "b", start: 31, end: 33 }]).map((c) => [c.id, c.start, c.end]), [["c", 61, 69]]); +}); + +test("the intro's length comes from the newest built take's schedule", async () => { + const dir = await project(); + try { + assert.equal(await introSecondsOf(dir), null); + await mkdir(path.join(dir, "takes", "t1", "out", "sourced"), { recursive: true }); + await writeFile(path.join(dir, "takes", "t1", "out", "sourced", "schedule.json"), JSON.stringify({ segments: [{ id: "brand-intro", type: "intro", start: 0, duration: 4.634 }] })); + assert.equal(await introSecondsOf(dir), 4.63); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/trailerBeatsCli.mjs b/umtool/lib/report/trailerBeatsCli.mjs @@ -0,0 +1,219 @@ +// `umtool trailer-beats` (UI notes 2026-10-30, item 11): the project's trailer +// beats (promo/trailer-beats.json) from a terminal -- the same writer and the +// same reader as the Trailer page (lib/report/trailerBeats.mjs), so the running +// length, the platform limit and the beats outside their clips are said here +// before any encode. `umtool trailer <p> --take <t> --beats +// <project>/promo/trailer-beats.json` cuts the trailer from them. +// +// Beats are numbered from 1, as `umtool trailer`'s refusals number them. +// +// Plain ESM: the CLI runs under bare node. +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { readManifest } from "../projects/report.mjs"; +import { + BeatsStale, + TRAILER_BEATS_FILE, + TRAILER_LIMITS, + addTrailerBeat, + beatsToken, + clockOf, + introSecondsOf, + moveTrailerBeat, + orderTrailerBeats, + readTrailerBeats, + removeTrailerBeat, + setTrailerSettings, + trailerCandidatesOf, + trailerView, + updateTrailerBeat, +} from "./trailerBeats.mjs"; + +export const TRAILER_BEATS_USAGE = [ + "usage: umtool trailer-beats <project> [ls] [--json] the beats: length, running length against the limit,", + " beats outside their clip, the cut's order", + " umtool trailer-beats <project> add <clip> [<from>-<to>] [--at N] [--label L]", + " a clip beat (default: the clip's whole cut), in the cut's order unless --at N", + " umtool trailer-beats <project> add-raw <at> <dur> [--at N] [--label L] master seconds", + " umtool trailer-beats <project> set <n> <from>-<to> [--label L] beat n's source seconds", + " umtool trailer-beats <project> remove <n> | move <n> --to <m> | order (the cut's order)", + ` umtool trailer-beats <project> limit <seconds|m:ss|${TRAILER_LIMITS.map((l) => l.id).join("|")}> | xfade <s> | intro on|off`, + " umtool trailer-beats <project> candidates [--add] the walk's ★ clips not yet beats (--add: all of them)", + "", + `The file is <project>/${TRAILER_BEATS_FILE}; \`umtool trailer <p> --take <t> --beats <that file>\` cuts the trailer.`, +].join("\n"); + +class CliError extends Error {} + +function parse(args) { + const valued = new Set(["--at", "--to", "--label"]); + /** @type {Record<string, string>} */ + const flags = {}; + const positional = []; + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (a.startsWith("--")) { + if (valued.has(a)) { + if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); + flags[a] = args[++i]; + } else if (["--json", "--help", "--add"].includes(a)) flags[a] = ""; + else throw new CliError(`unknown flag ${a}`); + } else positional.push(a); + } + return { flags, positional, has: (n) => n in flags }; +} + +const spanOf = (s) => { + const m = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/.exec(String(s ?? "")); + if (!m) throw new CliError(`a span is <from>-<to> in source seconds (got ${s})`); + return { start: Number(m[1]), end: Number(m[2]) }; +}; +const beatNo = (s, what = "beat") => { + const n = Number(s); + if (!Number.isInteger(n) || n < 1) throw new CliError(`${what} is a beat's number, from 1 (\`umtool trailer-beats <project>\` lists them)`); + return n - 1; +}; +/** seconds, m:ss(.s), or a platform's id. */ +export function limitOf(s) { + const p = TRAILER_LIMITS.find((l) => l.id === String(s).toLowerCase()); + if (p) return p.seconds; + const m = /^(\d+):(\d{1,2}(?:\.\d+)?)$/.exec(String(s)); + if (m) return Number(m[1]) * 60 + Number(m[2]); + const n = Number(s); + if (!Number.isFinite(n)) throw new CliError(`limit is seconds, m:ss, or one of ${TRAILER_LIMITS.map((l) => l.id).join(", ")}`); + return n; +} + +/** The view as lines. */ +export function viewLines(v) { + const lines = []; + for (const r of v.rows) { + const what = r.kind === "clip" ? `${r.id.padEnd(8)} ${String(r.start).padStart(9)}–${String(r.end).padEnd(9)}` : `(master) at ${r.at} for ${r.dur}`.padEnd(29); + const flag = r.problems.length ? ` ! ${r.problems.join("; ")}` : ""; + lines.push(`${String(r.n).padStart(3)} ${what} ${`${r.seconds.toFixed(2)}s`.padStart(8)} ${clockOf(r.running).padStart(7)}${r.over ? " OVER" : ""}${r.clip?.section ? ` ${r.clip.section}` : ""}${r.label ? ` "${r.label}"` : ""}${flag}`); + } + lines.push( + `${v.rows.length} beat(s): ${clockOf(v.total)} of ${clockOf(v.limit)}${v.over ? ` — OVER by ${(v.total - v.limit).toFixed(1)} s` : ` (${v.remaining.toFixed(1)} s to spare)`}` + + ` · crossfade ${v.xfade} s${v.intro ? ` · intro ${v.introSeconds ?? "?"} s${v.introSeconds === null ? " (unknown until a take is built)" : ""}` : ""}` + + `${v.outside ? ` · ${v.outside} beat(s) to fix` : ""}${v.inOrder ? "" : " · not in the cut's order (`order`)"}`, + ); + return lines; +} + +/** + * @param {string[]} args the words after `trailer-beats` + * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts] + */ +export async function trailerBeatsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { + try { + const p = parse(args); + const [projectArg, verb = "ls", ...rest] = p.positional; + if (!projectArg || p.has("--help")) { + err(TRAILER_BEATS_USAGE); + return p.has("--help") ? 0 : 2; + } + const r = await resolveProject(projectArg, root); + if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${projectArg}"`); + const project = r.project; + const manifest = await readManifest(project.dir); + if (!manifest) throw new CliError(`${project.id} has no manifest`); + const token = await beatsToken(project.dir); + const label = p.has("--label") ? p.flags["--label"] : undefined; + const at = p.has("--at") ? beatNo(p.flags["--at"], "--at") : null; + let did = null; + switch (verb) { + case "ls": + break; + case "add": { + const id = rest[0]; + if (!id) throw new CliError("add <clip> [<from>-<to>]"); + const e = (manifest.timeline ?? []).find((x) => x?.id === id && x.type === "clip"); + if (!e) throw new CliError(`no clip ${id} in the cut`); + const span = rest[1] ? spanOf(rest[1]) : { start: e.cutStart ?? e.start, end: e.cutEnd ?? e.end }; + const res = await addTrailerBeat(project.dir, { id, ...span, ...(label ? { label } : {}) }, { token, at, manifest }); + did = `added beat ${res.index + 1}: ${id} ${res.beat.start}–${res.beat.end}`; + break; + } + case "add-raw": { + const a = Number(rest[0]); + const d = Number(rest[1]); + if (!Number.isFinite(a) || !Number.isFinite(d)) throw new CliError("add-raw <at> <dur>: master seconds"); + const res = await addTrailerBeat(project.dir, { at: a, dur: d, ...(label ? { label } : {}) }, { token, at }); + did = `added beat ${res.index + 1}: master ${a} for ${d} s`; + break; + } + case "set": { + const i = beatNo(rest[0]); + const patch = { ...(rest[1] ? spanOf(rest[1]) : {}), ...(label !== undefined ? { label } : {}) }; + if (!Object.keys(patch).length) throw new CliError("set <n> <from>-<to> [--label L]"); + const res = await updateTrailerBeat(project.dir, i, patch, { token }); + did = `beat ${i + 1}: ${JSON.stringify(res.beat)}`; + break; + } + case "remove": { + const i = beatNo(rest[0]); + const res = await removeTrailerBeat(project.dir, i, { token }); + did = `removed beat ${i + 1} (${res.removed.id ?? `master ${res.removed.at}`})`; + break; + } + case "move": { + const i = beatNo(rest[0]); + if (!p.has("--to")) throw new CliError("move <n> --to <m>"); + const to = beatNo(p.flags["--to"], "--to"); + await moveTrailerBeat(project.dir, i, to, { token }); + did = `moved beat ${i + 1} to ${to + 1}`; + break; + } + case "order": { + const res = await orderTrailerBeats(project.dir, manifest, { token }); + did = res.moved ? "the beats are in the cut's order now" : "the beats were already in the cut's order"; + break; + } + case "limit": + await setTrailerSettings(project.dir, { limit: rest[0] === "default" ? null : limitOf(rest[0]) }, { token }); + did = "limit set"; + break; + case "xfade": + await setTrailerSettings(project.dir, { xfade: rest[0] === "default" ? null : Number(rest[0]) }, { token }); + did = "crossfade set"; + break; + case "intro": + if (!["on", "off"].includes(rest[0])) throw new CliError("intro on|off"); + await setTrailerSettings(project.dir, { intro: rest[0] === "on" }, { token }); + did = `intro ${rest[0]}`; + break; + case "candidates": { + const doc = await readTrailerBeats(project.dir); + const cands = trailerCandidatesOf(manifest, doc.beats); + if (!p.has("--add")) { + if (p.has("--json")) out(JSON.stringify({ project: project.id, candidates: cands }, null, 2)); + else if (!cands.length) out("no ★ clips that are not beats already (star a clip on the walk)"); + else for (const c of cands) out(`★ ${c.id.padEnd(8)} ${c.start}–${c.end}${c.walkNote ? ` — ${c.walkNote}` : ""}${c.quote ? ` "${c.quote.slice(0, 90)}${c.quote.length > 90 ? "…" : ""}"` : ""}`); + return 0; + } + let tok = token; + for (const c of cands) tok = (await addTrailerBeat(project.dir, { id: c.id, start: c.start, end: c.end }, { token: tok, manifest })).token; + did = `added ${cands.length} ★ beat(s)`; + break; + } + default: + throw new CliError(`unknown: trailer-beats ${verb}\n${TRAILER_BEATS_USAGE}`); + } + const doc = await readTrailerBeats(project.dir); + const view = trailerView(manifest, doc, { introSeconds: doc.settings?.intro ? await introSecondsOf(project.dir) : null }); + if (p.has("--json")) { + out(JSON.stringify({ ok: true, project: project.id, ...(did ? { did } : {}), token: await beatsToken(project.dir), ...view }, null, 2)); + return 0; + } + if (did) out(did); + for (const line of viewLines(view)) out(line); + return 0; + } catch (e) { + if (e instanceof BeatsStale) { + err(`umtool trailer-beats: ${e.message} — somebody else wrote it; run it again`); + return 1; + } + err(`umtool trailer-beats: ${e instanceof Error ? e.message : String(e)}`); + return e instanceof CliError ? 2 : 1; + } +} diff --git a/umtool/lib/report/trailerCandidates.mjs b/umtool/lib/report/trailerCandidates.mjs @@ -0,0 +1,39 @@ +// ★ on the walk makes a clip a trailer candidate (UI notes 2026-10-30, #7). +// +// A favourite is not a verdict and not a correction: it is the walk saying +// "this one is gold", which is exactly the list a trailer is cut from. The +// candidates are the starred clips, in the cut's order, each as a trailer +// beat over what the clip plays (report-to-video/trailer.mjs parseBeats: +// `{ id, start, end }` in source seconds) -- so the list is a `--beats-json` +// as it stands, and whatever lists or suggests trailer beats starts from it. +// +// Plain ESM: the CLI runs it under bare node. +import { playedSpan } from "./citeFollow.mjs"; + +/** + * The cut's starred clips as trailer beats, in timeline order. A clip that + * would not play (incorrect, rejected) is left out. + * + * @param {Record<string, any>} m + * @returns {Array<{ id: string, start: number, end: number, label?: string, quote?: string, walkNote?: string }>} + */ +export function trailerCandidates(m) { + const out = []; + for (const e of m?.timeline ?? []) { + if (e?.type !== "clip" || e.star !== true) continue; + if (e.verdict === "incorrect" || e.verdict === "rejected") continue; + const { from, to } = playedSpan(e); + if (!Number.isFinite(from) || !Number.isFinite(to) || to <= from) continue; + out.push({ + id: String(e.id), + start: from, + end: to, + ...(typeof e.quote === "string" && e.quote.trim() ? { quote: e.quote.trim() } : {}), + ...(typeof e.walkNote === "string" && e.walkNote.trim() ? { walkNote: e.walkNote.trim() } : {}), + }); + } + return out; +} + +/** The candidates as `--beats-json` takes them: `{ id, start, end }` only. */ +export const candidateBeats = (m) => trailerCandidates(m).map(({ id, start, end }) => ({ id, start, end })); diff --git a/umtool/lib/report/trailerCli.mjs b/umtool/lib/report/trailerCli.mjs @@ -4,11 +4,14 @@ // // umtool trailer <project> --take <t> (--beats FILE | --beats-json JSON) // [--intro] [--finale S] [--xfade 0.3] [--out NAME] [--dry-run] [--json] +// umtool trailer <project> --candidates [--json] the walk's ★ clips as beats import { readFile } from "node:fs/promises"; import path from "node:path"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { kindMakesTakes } from "../projects/kinds.mjs"; import { takesDirOf } from "./takes.mjs"; +import { readManifest } from "../projects/report.mjs"; +import { candidateBeats, trailerCandidates } from "./trailerCandidates.mjs"; import { TRAILER_ESTIMATE_MB, TRAILER_XFADE_DEFAULT, @@ -30,6 +33,10 @@ export const TRAILER_USAGE = [ "encoded with the take's render settings, in the heavy slot. Writes takes/<t>/out/<slug>.trailer.mp4", "(--out NAME: that name there; a path: exactly there) and <name>.trailer.json beside it, what was cut.", "--dry-run prints the mapping and writes nothing.", + "", + "umtool trailer <project> --candidates [--json]: the clips starred (★) on the walk, in the cut's order, as beats", + "over what each plays -- with --json exactly what --beats-json takes:", + " umtool trailer <p> --take <t> --beats-json \"$(umtool trailer <p> --candidates --json)\"", ].join("\n"); class CliError extends Error {} @@ -45,7 +52,7 @@ function parse(args) { if (valued.has(a)) { if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); flags[a] = args[++i]; - } else if (["--intro", "--json", "--dry-run", "--help"].includes(a)) flags[a] = ""; + } else if (["--intro", "--json", "--dry-run", "--help", "--candidates"].includes(a)) flags[a] = ""; else throw new CliError(`unknown flag ${a}`); } else positional.push(a); } @@ -110,6 +117,24 @@ export async function trailerCommand(args, { reportsRoot = REPORTS_ROOT, log = c if (r.ambiguous) throw new CliError(`"${p.positional[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); if (!r.project) throw new CliError(`no project matches "${p.positional[0]}"`); if (!kindMakesTakes(r.project.kind)) throw new CliError(`${r.project.id} is a ${r.project.kind}, not a report video`); + if (p.has("--candidates")) { + const m = await readManifest(r.project.dir); + if (!m) throw new CliError(`${r.project.id} has no video.manifest.json`); + if (p.has("--json")) { + log(JSON.stringify(candidateBeats(m))); + return 0; + } + const list = trailerCandidates(m); + if (!list.length) { + log(`${r.project.id}: no clip is starred — ★ one on the walk (s), or \`umtool window <p> <clip> --star\``); + return 0; + } + log(`${r.project.id}: ${list.length} trailer candidate${list.length === 1 ? "" : "s"} (★ on the walk), ${list.reduce((n, b) => n + b.end - b.start, 0).toFixed(1)} s in all`); + for (const b of list) { + log(` ${b.id.padEnd(6)} ${b.start.toFixed(2)}–${b.end.toFixed(2)} (${(b.end - b.start).toFixed(1)} s)${b.quote ? ` “${b.quote.slice(0, 70)}${b.quote.length > 70 ? "…" : ""}”` : ""}${b.walkNote ? ` — ${b.walkNote}` : ""}`); + } + return 0; + } const take = p.flags["--take"]; if (!take) throw new CliError("--take <t>: the finished take to cut the trailer from"); if (!/^[a-z0-9][a-z0-9-]*$/.test(take)) throw new CliError(`--take ${take}: a take id`); diff --git a/umtool/lib/report/workingCut.mjs b/umtool/lib/report/workingCut.mjs @@ -0,0 +1,172 @@ +// THE WORKING CUT'S NAME (operator, 1 Nov 2026): "Most of the time I'll only +// really be working on the latest cut/draft rather than the picked one". +// +// The project's video.manifest.json IS the working cut: the bench, Play, the +// Cut tab and every agent write it, and every take is MADE FROM it (take.json +// `baseHash`, the hash of the manifest it was made from). So the cut has a +// name -- the newest WORKING take (takes.mjs isWorkingTake: a whole-cut render +// of the manifest's own content) -- and a distance from it: the edits made to +// the manifest since that take was made. +// +// latest the newest working take, by builtAt (then order) +// edits 0 when the manifest's hash is the take's baseHash; else the +// entries added, removed, moved and changed between the manifest +// the take RENDERED (takes/<id>/video.manifest.json, its patch +// applied) and the manifest now with the same patch -- in words +// ("aw3 removed", "mc1 moved"); null when the take's rendered +// manifest is gone (pruned) and the hashes differ +// picked the group pick in verdicts.json (secondary: "Use this take", +// auto-picked for each new working take unless pinned) +// +// Plain ESM: the CLI (`umtool takes ls`) reads it under bare node. +import { createHash } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { isWorkingTake, listTakes, readVerdicts, takesDirOf } from "./takes.mjs"; + +const MANIFEST = "video.manifest.json"; +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const hashText = (text) => createHash("sha256").update(text).digest("hex"); + +/** + * The newest working take of a listing (listTakes's `takes`), or null. + * + * @template {{ id: string, builtAt?: string | null, order?: number }} T + * @param {T[]} takes + * @returns {T | null} + */ +export function latestWorkingTake(takes) { + const ok = (takes ?? []).filter((t) => isWorkingTake(/** @type {any} */ (t)) && t.builtAt); + ok.sort((a, b) => String(b.builtAt).localeCompare(String(a.builtAt)) || (b.order ?? 0) - (a.order ?? 0) || b.id.localeCompare(a.id)); + return ok[0] ?? null; +} + +/** What changed on an entry, as a word: a trim, gaps, the verdict, or an edit. */ +function changeWord(a, b) { + const differs = (k) => JSON.stringify(a?.[k] ?? null) !== JSON.stringify(b?.[k] ?? null); + if (["start", "end", "cutStart", "cutEnd"].some(differs)) return "trimmed"; + if (differs("gaps")) return "gaps"; + if (["verdict", "reason", "correction"].some(differs)) return "verdict"; + return "edited"; +} + +/** + * The edits from timeline `before` to `after`, by entry id: added, removed, + * moved (not on the longest run kept in order) and changed (same id, other + * fields), plus whether anything outside the timeline changed. `count` is the + * number of entries touched (+1 for the rest of the manifest); `words` one + * phrase per entry, in the order of `after`. + * + * @param {Record<string, any>} before + * @param {Record<string, any>} after + */ +export function cutDiff(before, after) { + const A = (Array.isArray(before?.timeline) ? before.timeline : []).filter((e) => isObj(e) && typeof e.id === "string"); + const B = (Array.isArray(after?.timeline) ? after.timeline : []).filter((e) => isObj(e) && typeof e.id === "string"); + const inA = new Map(A.map((e) => [e.id, e])); + const inB = new Map(B.map((e) => [e.id, e])); + const removed = A.filter((e) => !inB.has(e.id)).map((e) => e.id); + const added = B.filter((e) => !inA.has(e.id)).map((e) => e.id); + // The longest run of common ids kept in order: everything off it moved. + const a = A.map((e) => e.id).filter((id) => inB.has(id)); + const b = B.map((e) => e.id).filter((id) => inA.has(id)); + const posA = new Map(a.map((id, i) => [id, i])); + const seq = b.map((id) => posA.get(id)); + // Patience LIS over positions. + const tails = []; + const prevIdx = new Array(seq.length).fill(-1); + const tailIdx = []; + seq.forEach((v, i) => { + let lo = 0; + let hi = tails.length; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (tails[mid] < v) lo = mid + 1; + else hi = mid; + } + tails[lo] = v; + tailIdx[lo] = i; + prevIdx[i] = lo > 0 ? tailIdx[lo - 1] : -1; + }); + const kept = new Set(); + for (let i = tailIdx[tails.length - 1] ?? -1; i >= 0; i = prevIdx[i]) kept.add(b[i]); + const moved = b.filter((id) => !kept.has(id)); + const changed = b.filter((id) => JSON.stringify(inA.get(id)) !== JSON.stringify(inB.get(id))).map((id) => ({ id, what: changeWord(inA.get(id), inB.get(id)) })); + const { timeline: _a, ...restA } = isObj(before) ? before : {}; + const { timeline: _b, ...restB } = isObj(after) ? after : {}; + const rest = JSON.stringify(restA) !== JSON.stringify(restB); + const words = []; + const movedSet = new Set(moved); + const changedOf = new Map(changed.map((c) => [c.id, c.what])); + for (const e of B) { + const parts = []; + if (!inA.has(e.id)) parts.push("added"); + else { + if (movedSet.has(e.id)) parts.push("moved"); + if (changedOf.has(e.id)) parts.push(changedOf.get(e.id)); + } + if (parts.length) words.push(`${e.id} ${parts.join(", ")}`); + } + for (const id of removed) words.push(`${id} removed`); + if (rest) words.push("the look or the deck changed"); + const touched = new Set([...added, ...removed, ...moved, ...changed.map((c) => c.id)]); + return { added, removed, moved, changed, rest, count: touched.size + (rest ? 1 : 0), words }; +} + +async function readJson(file) { + try { + return JSON.parse(await readFile(/* turbopackIgnore: true */ file, "utf8")); + } catch { + return null; + } +} + +/** + * The working cut: the newest working take, the edits since it, the pick. + * + * @param {string} projectDir + * @param {{ manifestText?: string | null, resolveNow?: ((takeId: string) => Promise<Record<string, any> | null>) | null }} [opts] + * `resolveNow`: the manifest as it is now with that take's patch (takeManifest.mjs resolveTakeManifest) -- + * compared with what the take rendered; without it the bare manifest is compared + */ +export async function readWorkingCut(projectDir, { manifestText = null, resolveNow = null } = {}) { + const [listing, verdicts] = await Promise.all([listTakes(projectDir), readVerdicts(projectDir)]); + const takes = listing.takes; + const latest = latestWorkingTake(takes); + const pickedId = Object.keys(verdicts).find((id) => verdicts[id]?.picked && takes.some((t) => t.id === id)) ?? null; + const picked = pickedId + ? { id: pickedId, at: verdicts[pickedId].at || null, pinned: verdicts[pickedId].pinned === true, label: takes.find((t) => t.id === pickedId)?.label ?? pickedId } + : null; + if (!latest) return { latest: null, edits: null, picked, takes: takes.length }; + const text = manifestText ?? (await readFile(/* turbopackIgnore: true */ path.join(projectDir, MANIFEST), "utf8").catch(() => null)); + let edits = null; + if (text !== null && hashText(text) === latest.baseHash) edits = { count: 0, words: [], same: true }; + else { + const rendered = await readJson(path.join(takesDirOf(projectDir), latest.id, MANIFEST)); + let now = null; + try { + now = resolveNow ? await resolveNow(latest.id) : text !== null ? JSON.parse(text) : null; + } catch { + now = null; + } + if (isObj(rendered) && isObj(now)) { + const d = cutDiff(rendered, now); + edits = { count: d.count, words: d.words, same: false }; + } + } + return { + latest: { id: latest.id, label: latest.label, builtAt: latest.builtAt ?? null, seconds: latest.seconds ?? null, group: latest.group }, + edits, + picked, + takes: takes.length, + }; +} + +/** "Latest: draft-22 · 28:04 · +3 edits since" -- the line `umtool takes ls` prints first, and the pages show. */ +export function workingCutLine(w) { + if (!w?.latest) return "Latest: no whole-cut take yet — the manifest is the cut"; + const s = w.latest.seconds; + const len = typeof s === "number" ? ` · ${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}` : ""; + const ed = !w.edits ? " · edits since: unknown (its rendered manifest is gone)" : w.edits.count === 0 ? " · no edits since" : ` · +${w.edits.count} edit${w.edits.count === 1 ? "" : "s"} since`; + return `Latest: ${w.latest.id}${len}${ed}`; +} diff --git a/umtool/lib/report/workingCut.test.mjs b/umtool/lib/report/workingCut.test.mjs @@ -0,0 +1,116 @@ +// The working cut's name (workingCut.mjs) and the auto-pick (takes.mjs autoPickTake). +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { test } from "node:test"; +import { autoPickTake, isWorkingTake, readVerdicts, setTakePicked } from "./takes.mjs"; +import { cutDiff, latestWorkingTake, readWorkingCut, workingCutLine } from "./workingCut.mjs"; + +const hash = (t) => createHash("sha256").update(t).digest("hex"); +const clip = (id, start = 0, end = 5) => ({ id, type: "clip", video: "v", start, end }); + +test("isWorkingTake: a whole-cut render of the manifest's own content only", () => { + const ok = { window: "full", baseHash: "h", draft: false }; + assert.equal(isWorkingTake(ok), true); + assert.equal(isWorkingTake({ ...ok, patch: { title: "x", render: {} } }), true, "a look patch is still the cut"); + assert.equal(isWorkingTake({ ...ok, window: { at: 0, dur: 30 } }), false, "a window preview"); + assert.equal(isWorkingTake({ ...ok, draft: true }), false, "a draft (not rendered)"); + assert.equal(isWorkingTake({ ...ok, quick: true }), false, "a quick render"); + assert.equal(isWorkingTake({ ...ok, style: "punchy" }), false, "a montage style"); + assert.equal(isWorkingTake({ ...ok, patch: { timeline: [] } }), false, "its own timeline"); + assert.equal(isWorkingTake({ ...ok, baseHash: null }), false, "made by hand"); +}); + +test("latestWorkingTake: the newest working take by builtAt", () => { + const t = (id, builtAt, extra = {}) => ({ id, builtAt, order: 1, window: "full", baseHash: "h", ...extra }); + const takes = [t("draft-21", "2026-10-31T10:00:00Z"), t("draft-22", "2026-11-01T14:57:00Z"), t("preview", "2026-11-01T16:00:00Z", { window: { at: 0, dur: 30 } }), t("mods", "2026-11-01T17:00:00Z", { patch: { timeline: [] } })]; + assert.equal(latestWorkingTake(takes)?.id, "draft-22"); + assert.equal(latestWorkingTake([]), null); +}); + +test("cutDiff: added, removed, moved (off the longest kept run) and changed, in words", () => { + const before = { title: "a", timeline: [clip("a"), clip("b"), clip("c"), clip("d"), clip("e")] }; + const after = { title: "a", timeline: [clip("a"), clip("c"), clip("b", 0, 4), clip("e"), clip("f")] }; + const d = cutDiff(before, after); + assert.deepEqual(d.removed, ["d"]); + assert.deepEqual(d.added, ["f"]); + assert.equal(d.moved.length, 1, "one of b/c moved, not both"); + assert.deepEqual(d.changed, [{ id: "b", what: "trimmed" }]); + assert.equal(d.rest, false); + assert.equal(d.count, 4); + assert.ok(d.words.includes("d removed") && d.words.includes("f added")); + assert.equal(cutDiff(before, before).count, 0); + assert.equal(cutDiff(before, { ...before, title: "b" }).count, 1, "the rest of the manifest counts once"); +}); + +async function project() { + const dir = await mkdtemp(path.join(os.tmpdir(), "working-cut-")); + await mkdir(path.join(dir, "takes"), { recursive: true }); + return dir; +} +async function writeTake(dir, id, doc, manifest = null) { + await mkdir(path.join(dir, "takes", id), { recursive: true }); + await writeFile(path.join(dir, "takes", id, "take.json"), JSON.stringify({ id, group: "takes", order: 1, label: id, kind: "different", preview: "preview.mp4", ...doc })); + if (manifest) await writeFile(path.join(dir, "takes", id, "video.manifest.json"), JSON.stringify(manifest)); +} + +test("readWorkingCut: the latest take, no edits when the manifest is its base, else the edits in words", async () => { + const dir = await project(); + try { + const m1 = { timeline: [clip("a"), clip("b"), clip("c")] }; + const text1 = JSON.stringify(m1); + await writeFile(path.join(dir, "video.manifest.json"), text1); + await writeTake(dir, "draft-1", { window: "full", baseHash: "old", builtAt: "2026-10-01T00:00:00Z" }); + await writeTake(dir, "draft-2", { window: "full", baseHash: hash(text1), builtAt: "2026-11-01T00:00:00Z", seconds: 125 }, m1); + let w = await readWorkingCut(dir); + assert.equal(w.latest?.id, "draft-2"); + assert.deepEqual(w.edits, { count: 0, words: [], same: true }); + assert.equal(workingCutLine(w), "Latest: draft-2 · 2:05 · no edits since"); + // An edit since: b moved after c, a removed. + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ timeline: [clip("c"), clip("b")] })); + w = await readWorkingCut(dir); + assert.equal(w.edits?.same, false); + assert.equal(w.edits?.count, 2); + assert.match(workingCutLine(w), /\+2 edits since/); + assert.ok(w.edits?.words.includes("a removed")); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("autoPickTake: a working take is picked; a pinned pick wins; a partial take never", async () => { + const dir = await project(); + try { + const group = ["draft-1", "draft-2", "prev"]; + const w1 = { id: "draft-1", window: "full", baseHash: "h1" }; + assert.deepEqual((await autoPickTake(dir, w1, group)).picked, true); + assert.equal((await readVerdicts(dir))["draft-1"]?.picked, true); + // A window preview: never picked. + const r = await autoPickTake(dir, { id: "prev", window: { at: 0, dur: 30 }, baseHash: "h2" }, group); + assert.equal(r.picked, false); + assert.equal((await readVerdicts(dir))["draft-1"]?.picked, true); + // The next working take moves the pick. + await autoPickTake(dir, { id: "draft-2", window: "full", baseHash: "h2" }, group); + let v = await readVerdicts(dir); + assert.equal(v["draft-2"]?.picked, true); + assert.equal(v["draft-1"], undefined, "a cleared row that says nothing is removed"); + // Pinned to draft-1: a newer working take does not move it. + await setTakePicked(dir, "draft-1", group, { pinned: true }); + const r3 = await autoPickTake(dir, { id: "draft-3", window: "full", baseHash: "h3" }, [...group, "draft-3"]); + assert.equal(r3.picked, false); + assert.match(r3.why, /pinned to draft-1/); + v = await readVerdicts(dir); + assert.equal(v["draft-1"]?.pinned, true); + assert.equal(v["draft-3"], undefined); + // Unpinned: the next one is picked again, and the pin is gone with the pick. + await setTakePicked(dir, "draft-1", group, { pinned: false }); + assert.equal((await autoPickTake(dir, { id: "draft-3", window: "full", baseHash: "h3" }, [...group, "draft-3"])).picked, true); + v = JSON.parse(await readFile(path.join(dir, "takes", "verdicts.json"), "utf8")); + assert.equal(v["draft-3"].picked, true); + assert.equal(v["draft-1"], undefined); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -181,6 +181,10 @@ export default defineConfig({ // SONG_DIR (release 17): its default is the user's ~/.cache, which a // suite must never write. The fixture's own, rebuilt with it every run. `UMTOOL_CACHE_DIR=${FIXTURE}/cache ` + + // The archive JSON cache (report-to-video/cues.mjs: the cue walk's, and the + // QR link check's, lib/report/linkCheck.mjs): the fixture's own, never the + // user's ~/.cache. + `REPORT_CACHE_DIR=${FIXTURE}/report-cache ` + // And never the media root: Playwright hands the app this shell's whole // environment, so a shell that exports UMTOOL_MEDIA_DIR would put every // fixture build's out/ on the real media drive. Empty is unset