commit abf350de2950c0840077d3f7f2e5137f762cb51d
parent 1df2a71eca6d3d883347c2a61cf158e02de04fcd
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 03:48:12 -0500
Merge lane/ui-editing: tighten a clip to the sentence and snap an edge to the nearest pause on the bench (sentenceEdges + the pause helper, word boxes and pauses in the zoom), Propose tight windows as a review list; Export from the clip editor as cut, with N s of context, or raw/full exchange, as heavy-slot jobs fetching through the editor; a rendering take's Cancel, Fork as variant, and two takes compared side by side
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
41 files changed, 4089 insertions(+), 130 deletions(-)
diff --git a/umtool/app/api/report/clip-export/route.ts b/umtool/app/api/report/clip-export/route.ts
@@ -1,23 +1,29 @@
+import { getJob, jobView, runningJob, startJob } from "@/lib/jobs";
import { projectRef } from "@/lib/projects";
import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
import { refuseCaller } from "@/lib/report/caller";
-import { EXPORT_KINDS, ExportRefused, exportClip } from "@/lib/report/clipExport.mjs";
+import { EXPORT_KINDS, ExportRefused, contextSeconds, exportNeeds, exportSteps, spanOf } from "@/lib/report/clipExport.mjs";
import { cannotOpen, localRequest } from "@/lib/report/openFolder.mjs";
export const dynamic = "force-dynamic";
// EXPORT ONE CLIP (umtool/docs/knobs.md, "Export one clip"): a clean mp4 of a
-// clip -- the cut's edges, its gaps out as jump cuts, its mute -- or its whole
-// fetched window (`raw`), with no deck chrome, into <project>/exports/.
+// clip, no deck chrome, into <project>/exports/ -- as the cut plays it (`cut`:
+// its edges, its gaps out as jump cuts, its mute), with N s either side
+// (`context`), or a stretch as recorded (`raw`: the fetched window, or a
+// `span` -- the full exchange).
//
-// POST { project, clip, take?, kind?: "cut" | "raw" }
-// -> { ok, name, rel, size, seconds, summary, notes, download, canOpen, openWhy? }
+// POST { project, clip, take?, kind?: "cut" | "context" | "raw", context?: N, span?: {from, to}, fetch?: true }
+// -> 202 { job } ONE umtool job on the app's runner (lib/jobs.ts: one at a
+// time, a log, Stop): `fetch: true` asks the editor first for what a
+// context or raw export needs that is not on disk (the bench's own
+// fetch-window path), then `umtool export … --progress ndjson`, which
+// runs in the machine's heavy slot. 409 when a cut's window is not on
+// disk ("fetch it first"), when a context/raw export needs a fetch and
+// `fetch` was not asked, or when another job is running.
+// GET ?job=<id> -> { job, done?: { name, rel, size, seconds, summary, notes, download, canOpen, openWhy? }, error? }
//
-// Answered when the file is written: one short clip, re-encoded once on this
-// machine (seconds, not minutes), outside the job runner and the heavy slot,
-// so it never waits behind a build. A second ask for the same file waits for
-// the first. Nothing is fetched: a clip whose window is not on disk is a 409
-// saying so. Names, never paths: a project of the scan, a clip of its cut.
+// Names, never paths: a project of the scan, a clip of its cut.
const headers = { "cache-control": "no-store" };
export async function POST(request: Request) {
@@ -31,36 +37,79 @@ export async function POST(request: Request) {
const clip = String(body.clip ?? "");
if (!clip) return Response.json({ error: "which clip?" }, { status: 400, headers });
const take = typeof body.take === "string" && body.take ? body.take : null;
- const kind = body.kind === undefined || body.kind === null || body.kind === "" ? "cut" : String(body.kind);
+ const kind = (body.kind === undefined || body.kind === null || body.kind === "" ? "cut" : String(body.kind)) as "cut" | "context" | "raw";
if (!(EXPORT_KINDS as readonly string[]).includes(kind)) {
return Response.json({ error: `kind is one of ${EXPORT_KINDS.join(", ")}` }, { status: 400, headers });
}
try {
- const r = await exportClip(project, clip, { take, kind: kind as "cut" | "raw" });
+ const context = kind === "context" ? contextSeconds(body.context) : undefined;
+ const span = kind === "raw" ? spanOf(body.span) : null;
+ const need = await exportNeeds(project, clip, { take, kind, ...(context !== undefined ? { context } : {}), span });
+ if (kind === "cut" && !need.held) {
+ throw new ExportRefused(`${clip}: its window is not on disk — fetch it first (the Cut tab's Fetch, or \`umtool fetch ${project.id}\`)`, 409);
+ }
+ if (!need.held && body.fetch !== true) {
+ throw new ExportRefused(
+ `${clip}: what this export needs is not on disk (−${need.padBefore} s / +${need.padAfter} s around the clip) — ask again with fetch, which asks the editor first`,
+ 409,
+ );
+ }
+ const running = runningJob();
+ if (running) return Response.json({ error: `a job is already running (${running.kind}) — export when it is done`, running: jobView(running) }, { status: 409, headers });
+ let manifestPath: string | null = null;
+ if (take && !need.held) {
+ const { writePlayManifest } = await import("@/lib/report/takeManifest.mjs");
+ const { readManifest } = await import("@/lib/projects/report.mjs");
+ manifestPath = await writePlayManifest(project.dir, take, await readManifest(project.dir));
+ }
+ const steps = await exportSteps(project, clip, {
+ take,
+ kind,
+ ...(context !== undefined ? { context } : {}),
+ span,
+ fetch: need.held ? null : { padBefore: need.padBefore, padAfter: need.padAfter },
+ manifestPath,
+ });
+ const job = startJob(`export ${project.id}/${clip}`, steps, { project: project.id });
+ return Response.json({ ok: true, fetching: !need.held, job: jobView(job) }, { status: 202, headers });
+ } catch (e) {
+ const status = e instanceof ExportRefused ? e.status : 500;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
+ }
+}
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const id = url.searchParams.get("job");
+ const job = id ? getJob(id) : null;
+ if (!job) return Response.json({ error: "no such job" }, { status: 404, headers });
+ const view = jobView(job, Math.max(0, job.log.length - 12));
+ const ev = [...job.events].reverse().find((e) => e.ev === "export" || e.ev === "export-failed") as Record<string, unknown> | undefined;
+ if (ev?.ev === "export" && typeof ev.name === "string" && job.project) {
const no = cannotOpen();
const local = localRequest(request.headers);
const openWhy = no ?? (local.ok ? null : `Open folder works on the machine umtool runs on: ${local.why}`);
return Response.json(
{
- ok: true,
- clip: r.clip,
- take: r.take,
- kind: r.kind,
- name: r.name,
- rel: r.rel,
- size: r.size,
- mtimeMs: r.mtimeMs,
- seconds: r.seconds,
- summary: r.summary,
- notes: r.notes,
- download: `/api/report/exports?${new URLSearchParams({ project: project.id, name: r.name, v: String(r.mtimeMs) }).toString()}`,
- canOpen: !openWhy,
- ...(openWhy ? { openWhy } : {}),
+ job: view,
+ done: {
+ clip: ev.clip,
+ kind: ev.kind,
+ name: ev.name,
+ rel: ev.rel,
+ size: ev.size,
+ mtimeMs: ev.mtimeMs,
+ seconds: ev.seconds,
+ summary: ev.summary,
+ notes: ev.notes ?? [],
+ download: `/api/report/exports?${new URLSearchParams({ project: job.project, name: ev.name, v: String(ev.mtimeMs ?? "") }).toString()}`,
+ canOpen: !openWhy,
+ ...(openWhy ? { openWhy } : {}),
+ },
},
{ headers },
);
- } catch (e) {
- const status = e instanceof ExportRefused ? e.status : 500;
- return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
}
+ const error = ev?.ev === "export-failed" ? String(ev.error ?? "the export failed") : job.state === "failed" ? (job.error ?? "the export failed") : null;
+ return Response.json({ job: view, ...(error ? { error } : {}) }, { headers });
}
diff --git a/umtool/app/api/report/takes/housekeeping/route.ts b/umtool/app/api/report/takes/housekeeping/route.ts
@@ -13,15 +13,40 @@ export const dynamic = "force-dynamic";
// refused while it renders
// POST { project, take, op: "supersede", by?: <take> } verdicts.json: folded away
// POST { project, take, op: "unsupersede" } the mark cleared
+// POST { project, take, op: "cancel" } stop its render (lib/report/takeCancel.mjs):
+// asked of the process rendering it, waited
+// for; the app's own take job is stopped by
+// the job runner when it does not answer.
+// -> { stopped, how, cancelled, renderMode, said }
+// POST { project, take, op: "fork", name? } the take as a variant: a project beside
+// this one (lib/report/variantFork.mjs)
//
-// The CLI's twins: `umtool takes relabel | supersede [--clear]`.
+// The CLI's twins: `umtool takes relabel | supersede [--clear] | cancel | fork`.
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;
+ const body = (await request.json().catch(() => null)) as { project?: string; take?: string; op?: string; label?: string; by?: string | null; name?: 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 });
+ // A first render has no take.json yet: it is cancelled by its directory.
+ if (body.op === "cancel") {
+ try {
+ const { cancelTake } = await import("@/lib/report/takeCancel.mjs");
+ const { cancelJob, runningJob } = await import("@/lib/jobs");
+ const r = await cancelTake(project, take, {
+ by: "the Takes page",
+ // The take maker did not answer: when it is the app's own take job, the job runner stops it.
+ fallback: (lock) => {
+ const job = runningJob();
+ return !!job && job.pids.includes(Number(lock.pid)) && cancelJob(job.id);
+ },
+ });
+ return Response.json({ ok: true, take, ...r }, { headers: { "cache-control": "no-store" } });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 });
+ }
+ }
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 {
@@ -34,7 +59,17 @@ export async function POST(request: Request) {
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 });
+ if (body.op === "fork") {
+ const { ForkRefused, forkTakeAsVariant } = await import("@/lib/report/variantFork.mjs");
+ try {
+ const r = await forkTakeAsVariant(project, take, { name: typeof body.name === "string" ? body.name : null });
+ return Response.json({ ok: true, take: r.take, id: r.id, name: r.name, links: r.links, copied: r.copied, variant: r.variant }, { headers: { "cache-control": "no-store" } });
+ } catch (e) {
+ if (e instanceof ForkRefused) return Response.json({ error: e.message }, { status: e.status });
+ throw e;
+ }
+ }
+ return Response.json({ error: "op must be relabel, supersede, unsupersede, cancel or fork" }, { 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/tighten/route.ts b/umtool/app/api/report/tighten/route.ts
@@ -0,0 +1,30 @@
+import { projectRef } from "@/lib/projects";
+import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
+import { proposeTightWindows } from "@/lib/report/tightPropose.mjs";
+
+export const dynamic = "force-dynamic";
+
+// PROPOSE TIGHT WINDOWS (UI notes 2026-10-30, item 4; lib/report/tightPropose.mjs):
+// every clip of the cut tightened to its sentence and each edge into its pause,
+// before and after, for review. READS ONLY -- nothing is fetched and nothing
+// is written; a row is applied by its own Apply, through the window writer
+// (PUT /api/report/window with the token this answers).
+//
+// GET ?project=<id>[&clip=<id>…][&measure=0]
+// -> { token, rows: [{ id, before, after, changed, how, said, why, fetched, locked, words, clear }], counts }
+// measure=0: no silences (the words alone) -- nothing is measured
+const headers = { "cache-control": "no-store" };
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const project = await projectRef(String(url.searchParams.get("project") ?? ""));
+ if (!project) return Response.json({ error: "no such project" }, { status: 404, headers });
+ if (!kindMakesTakes(project.kind)) return Response.json({ error: "tight windows are a report video's" }, { status: 400, headers });
+ const clips = url.searchParams.getAll("clip").filter(Boolean);
+ try {
+ const got = await proposeTightWindows(project, { clips: clips.length ? clips : null, measure: url.searchParams.get("measure") !== "0" });
+ return Response.json(got, { headers });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 422, headers });
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -55,8 +55,10 @@
// umtool snapshot <project> [--label L] copy the manifest into revisions/
// umtool diff <project> <snapshot> what changed since that snapshot
// umtool export <project> --format toc-bbcode|toc-markdown|description|chapters [--variant V] [--first TITLE]
-// umtool export <project> <clip> [--raw] [--take T] [--open] [--json] one clip, clean, into
-// <project>/exports/: the cut's edges, gaps out, mute (--raw: the whole fetched window)
+// umtool export <project> <clip> [--context N | --raw [--from S --to S]] [--fetch] [--take T] [--open] [--json]
+// one clip, clean, into <project>/exports/: the cut's edges, gaps out, mute (--context: what
+// the cut plays ± N s, as recorded; --raw: the fetched window, or a span, as recorded; --fetch:
+// ask the editor first for what is not on disk), in the heavy slot
// umtool check-sources [<project>…] prints the re-check chain
// umtool notes [<site>/<report> | <project> | --all] [--open|--resolved|--all-status] [--json]
// umtool notes reply <id> "<text>" [--resolve] | resolve | wontfix | reopen <id>
@@ -79,6 +81,8 @@
// 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 tighten <project> [--json] [--all] [--no-measure] | --apply <clip>[,<clip>…] each clip to its sentence,
+// each edge into its pause: before -> after for review; --apply writes the named rows
// 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
@@ -712,14 +716,49 @@ async function cmdExport() {
}
// One clip, clean (umtool/docs/knobs.md, "Export one clip"): the cut's edges,
-// its gaps out, its mute -- or `--raw`, the whole fetched window -- with no
-// deck chrome. Runs here, with this machine's ffmpeg; nothing is fetched.
+// its gaps out, its mute -- `--context N`, what the cut plays with N s either
+// side, as recorded -- `--raw [--from S --to S]`, a stretch as recorded (the
+// full exchange) -- with no deck chrome. Runs here, with this machine's
+// ffmpeg, in the heavy slot (a small declared estimate: it runs beside others
+// when memory allows). `--fetch` asks the editor first for what a context or
+// raw export needs that is not on disk (fetch-via-editor.mjs, the bench's own
+// path); otherwise nothing is fetched. `--progress ndjson`: one `export` event
+// on stdout at the end (the app's export job reads it).
async function cmdExportClip(p, clipId) {
- const { exportClip } = await import("../lib/report/clipExport.mjs");
+ const { EXPORT_ESTIMATE_MB, exportClip, exportNeeds } = await import("../lib/report/clipExport.mjs");
+ const ndjson = val("--progress") === "ndjson";
+ const kind = has("--raw") ? "raw" : val("--context") !== undefined ? "context" : "cut";
+ const context = val("--context");
+ const from = val("--from");
+ const to = val("--to");
+ if (kind !== "raw" && (from !== undefined || to !== undefined)) die("--from/--to are a raw export's span: add --raw");
+ if ((from === undefined) !== (to === undefined)) die("a raw span is --from S --to S, both");
+ const span = from !== undefined ? { from: Number(from), to: Number(to) } : null;
+ const take = val("--take") ?? null;
+ const say = (line) => (ndjson || json ? console.error(line) : console.log(line));
+ if (has("--fetch") && kind !== "cut") {
+ let need;
+ try {
+ need = await exportNeeds(p, clipId, { take, kind, context: context === undefined ? undefined : Number(context), span });
+ } catch (e) {
+ die(e?.message ?? String(e), 1);
+ }
+ if (!need.held) {
+ say(`fetching −${need.padBefore} s / +${need.padAfter} s around ${clipId} through the editor first`);
+ const code = await runFetchViaEditor(p, clipId, need, { take });
+ if (code !== 0) die(`the fetch did not finish (exit ${code}) — nothing exported`, 1);
+ }
+ }
+ const { withRenderSlot } = await import("../report-to-video/heavy-gate.mjs");
let r;
try {
- r = await exportClip(p, clipId, { take: val("--take") ?? null, kind: has("--raw") ? "raw" : "cut" });
+ r = await withRenderSlot(
+ ["umtool", "export", p.id, clipId, kind],
+ () => exportClip(p, clipId, { take, kind, ...(context !== undefined ? { context: Number(context) } : {}), span }),
+ { estimateMb: EXPORT_ESTIMATE_MB, say },
+ );
} catch (e) {
+ if (ndjson) console.log(JSON.stringify({ ev: "export-failed", clip: clipId, kind, error: e?.message ?? String(e) }));
die(e?.message ?? String(e), 1);
}
let opened = null;
@@ -728,13 +767,32 @@ async function cmdExportClip(p, clipId) {
opened = await openFolder({ dir: path.dirname(r.abs), file: r.abs });
}
const { plan: _plan, ...view } = r;
+ if (ndjson) return console.log(JSON.stringify({ ev: "export", ...view, abs: undefined }));
if (json) return out({ ...view, ...(opened ? { opened } : {}) });
console.log(r.abs);
- console.log(` ${r.kind === "raw" ? "raw window" : "the cut's clip"}: ${r.summary} · ${(r.size / 1e6).toFixed(1)} MB`);
+ console.log(` ${r.kind === "raw" ? "raw" : r.kind === "context" ? "with context" : "the cut's clip"}: ${r.summary} · ${(r.size / 1e6).toFixed(1)} MB`);
for (const n of r.notes) console.log(` NOTE ${n}`);
if (opened) console.log(opened.ok ? ` opened ${path.dirname(r.abs)} (${opened.how})` : ` could not open the folder: ${opened.error}`);
}
+/** The bench's own fetch (driver.mjs editorFetchSteps: fetch-via-editor.mjs --fetch-only), run here with its output on stderr. */
+async function runFetchViaEditor(p, clipId, need, { take = null } = {}) {
+ const { editorFetchSteps } = await import("../lib/report/driver.mjs");
+ let manifestPath = null;
+ if (take) {
+ const { writePlayManifest } = await import("../lib/report/takeManifest.mjs");
+ manifestPath = await writePlayManifest(p.dir, take, await readManifest(p.dir));
+ }
+ const [step] = editorFetchSteps(p, clipId, { padBefore: need.padBefore, padAfter: need.padAfter }, { manifestPath });
+ const { spawn } = await import("node:child_process");
+ return new Promise((resolve) => {
+ const argvF = step.argv.filter((a, i, all) => !(a === "--progress" || all[i - 1] === "--progress"));
+ const child = spawn(process.execPath, argvF.slice(1), { cwd: step.cwd, stdio: ["ignore", "inherit", "inherit"] });
+ child.on("error", () => resolve(127));
+ child.on("close", (code) => resolve(code ?? 1));
+ });
+}
+
async function cmdCheckSources() {
// Print, never run -- the same posture as `build`. With no arguments, the
// projects the dashboard would re-check: never checked, or older than 30 d.
@@ -857,8 +915,10 @@ function usage() {
" umtool snapshot <project> [--label L] copy the manifest into revisions/",
" umtool diff <project> <snapshot> what changed since that snapshot",
" umtool export <project> --format toc-bbcode|toc-markdown|description|chapters [--variant V] [--first TITLE]",
- " umtool export <project> <clip> [--raw] [--take T] [--open] one clip, clean, into <project>/exports/:",
- " the cut's edges, its gaps out, its mute; --raw the whole fetched window; --open shows it",
+ " umtool export <project> <clip> [--context N | --raw [--from S --to S]] [--fetch] [--take T] [--open] one clip,",
+ " clean, into <project>/exports/: the cut's edges, its gaps out, its mute; --context N what the cut",
+ " plays ± N s; --raw the whole fetched window, or a span (the full exchange), as recorded; --fetch",
+ " asks the editor first for what that needs; in the heavy slot; --open shows it",
" umtool check-sources [<project>…] prints the re-check chain (never-checked/old when no args)",
" umtool notes [<site>/<report>|<project>|--all] the operator's notes, as markdown (open ones)",
" umtool notes reply <id> \"<text>\" [--resolve] answer one; resolve | wontfix | reopen <id>",
@@ -892,6 +952,8 @@ function usage() {
" | 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 tighten <project> [--json] [--all] [--no-measure] | --apply <clip>[,<clip>…] each clip to its sentence (its",
+ " cut's, else the whole ones in its window), each edge into its pause; before -> after; --apply writes",
" 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]",
@@ -999,6 +1061,8 @@ const COMMANDS = {
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))),
+ // Tight windows: each clip to its sentence and its pauses (UI notes item 4): lib/report/tightCli.mjs.
+ tighten: async () => process.exit(await (await import("../lib/report/tightCli.mjs")).tightenCommand(argv.slice(argv.indexOf("tighten") + 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.
diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx
@@ -25,6 +25,7 @@ import EdgeStrip from "./bench/EdgeStrip";
import RenderGhosts, { useRenderEdges } from "./bench/RenderGhosts";
import { GapLayer, ZoomControls, ZoomOverview, ZoomRuler, useWaveZoom, type Span } from "./bench/GapsZoom";
import TakeWalkStrip from "./bench/TakeWalkStrip";
+import { TightenButtons, useEdgeTools, type BenchWord } from "./bench/TightenTools";
// The renderer's own line, imported rather than re-written. A preview that
// disagrees with the header by a character is worth less than no preview: you
// would only find out twenty minutes into a build.
@@ -551,6 +552,8 @@ export default function ClipBench({
// Export clip (ClipExport.tsx): this clip, clean, into the project's exports/ -- the take's clip on a take's walk.
const clipExport = useClipExport(data.project, takeId);
const [clip, setClip] = useState<Clip>(data.clip);
+ // Export ▾'s full exchange starts from the clip's saved extent.
+ const clipAround = useMemo(() => ({ start: clip.start, end: clip.end }), [clip.start, clip.end]);
const [windows, setWindows] = useState<Win[]>(data.windows);
const [cues, setCues] = useState<Cue[]>(data.cues);
const [proposed, setProposed] = useState(data.proposed);
@@ -1612,6 +1615,28 @@ export default function ClipBench({
[doSave],
);
+ // Tighten to the sentence, snap an edge to its pause (bench/TightenTools.tsx):
+ // written at once through `save`, with an Undo.
+ const readCues = useMemo(() => {
+ const seen = new Set<number>();
+ return [...cues, ...peek].filter((c) => (seen.has(c.start) ? false : (seen.add(c.start), true))).sort((a, b) => a.start - b.start);
+ }, [cues, peek]);
+ const edgeTools = useEdgeTools({
+ project: data.project,
+ clip,
+ video: clip.video,
+ sel,
+ playhead,
+ cues: readCues,
+ silences: renderEdges?.silences ?? null,
+ lo: fetchStart,
+ hi: clampTo,
+ save,
+ lastSaved,
+ play,
+ setNote,
+ });
+
/**
* Persist one attribution field, on blur or Enter, if it actually changed.
*
@@ -2004,7 +2029,7 @@ export default function ClipBench({
// whole window, today's view -- on every clip's arrival.
const zoom = useWaveZoom(view);
// Close in: the pauses between words, when the project has its words for this recording (the clip editor's).
- const [nearWords, setNearWords] = useState<{ key: string; words: { start: number; end: number }[] | null } | null>(null);
+ const [nearWords, setNearWords] = useState<{ key: string; words: BenchWord[] | null } | null>(null);
const close = zoom.vis.to - zoom.vis.from <= DETAIL_SPAN;
const wordsKey = close ? `${clip.id}|${Math.floor(zoom.vis.from / 10) * 10}|${Math.ceil(zoom.vis.to / 10) * 10}` : null;
useEffect(() => {
@@ -2013,7 +2038,7 @@ export default function ClipBench({
const [, a, b] = wordsKey.split("|");
const q = new URLSearchParams({ project: data.project, clip: clip.id, from: a, to: b, video: clip.video });
fetch(`/api/report/clip-editor?${q}`, { cache: "no-store" })
- .then((r) => (r.ok ? (r.json() as Promise<{ words?: { start: number; end: number }[] | null }>) : null))
+ .then((r) => (r.ok ? (r.json() as Promise<{ words?: BenchWord[] | null }>) : null))
.then((j) => {
if (live) setNearWords({ key: wordsKey, words: j?.words ?? null });
})
@@ -2770,7 +2795,7 @@ export default function ClipBench({
>
Play clip
</button>
- <ClipExportButtons exp={clipExport} clip={clip.id} surface="paper" why={cached ? null : "its window is not fetched — fetch it first"} unsaved={unsaved} />
+ <ClipExportButtons exp={clipExport} clip={clip.id} surface="paper" why={cached ? null : "its window is not fetched — fetch it first"} unsaved={unsaved} around={clipAround} align="end" />
<ClipExportStatus exp={clipExport} surface="paper" />
</>
}
@@ -3820,6 +3845,7 @@ export default function ClipBench({
</button>
)}
</span>
+ <TightenButtons tools={edgeTools} busy={!!busy} />
<span className="micro max-md:hidden">
<kbd>z</kbd> <kbd>Z</kbd> zoom (or Ctrl/⌘ + wheel), <kbd>f</kbd> fit, <kbd>F</kbd> to the selection ·{" "}
<kbd>g</kbd> (or Alt + drag) select a gap, <kbd>g</kbd> cut it, <kbd>G</kbd> put back the one at the playhead
diff --git a/umtool/components/projects/ClipExport.tsx b/umtool/components/projects/ClipExport.tsx
@@ -19,9 +19,16 @@ import { cn } from "@/lib/utils";
// the server says when it cannot, and why). The bench's reader footer and
// Play the cut both use it; Play exports the clip at the playhead, or the one
// a note points at, through one `useClipExport`.
+//
+// EXPORT ▾ (UI notes 2026-10-30, item 12): as cut (no chrome), with N s of
+// context, raw / full exchange (a span, fetched through the editor first when
+// it is not on disk). Every export is a umtool job (POST answers 202 and the
+// job; this polls it), in the machine's heavy slot. No "send to phone": no
+// share path exists in umtool -- Download is the phone's way.
// ---------------------------------------------------------------------------
-export type ClipExportKind = "cut" | "raw";
+export type ClipExportKind = "cut" | "context" | "raw";
+export type ClipExportOpts = { context?: number; span?: { from: number; to: number } | null; fetch?: boolean };
type Done = {
clip: string;
@@ -39,14 +46,14 @@ type Done = {
export type ClipExportState =
| { k: "idle" }
- | { k: "exporting"; clip: string; kind: ClipExportKind; since: number }
+ | { k: "exporting"; clip: string; kind: ClipExportKind; since: number; fetching?: boolean; line?: string | null }
| { k: "ready"; done: Done; open: { k: "idle" } | { k: "opening" } | { k: "opened"; how: string } | { k: "failed"; error: string } }
| { k: "failed"; clip: string; kind: ClipExportKind; error: string };
export type ClipExportHandle = {
state: ClipExportState;
busy: boolean;
- run: (clip: string, kind?: ClipExportKind) => Promise<void>;
+ run: (clip: string, kind?: ClipExportKind, opts?: ClipExportOpts) => Promise<void>;
openFolder: () => Promise<void>;
dismiss: () => void;
};
@@ -59,21 +66,51 @@ export function useClipExport(project: string, take: string | null = null): Clip
const seq = useRef(0);
const busy = state.k === "exporting";
const run = useCallback(
- async (clip: string, kind: ClipExportKind = "cut") => {
+ async (clip: string, kind: ClipExportKind = "cut", opts: ClipExportOpts = {}) => {
const mine = ++seq.current;
- setState({ k: "exporting", clip, kind, since: Date.now() });
+ const since = Date.now();
+ setState({ k: "exporting", clip, kind, since });
+ const fail = (error: string) => {
+ if (mine === seq.current) setState({ k: "failed", clip, kind, error });
+ };
try {
const r = await fetch("/api/report/clip-export", {
method: "POST",
headers: { "content-type": "application/json" },
- body: JSON.stringify({ project, clip, kind, ...(take ? { take } : {}) }),
+ body: JSON.stringify({
+ project,
+ clip,
+ kind,
+ ...(take ? { take } : {}),
+ ...(kind === "context" && opts.context != null ? { context: opts.context } : {}),
+ ...(kind === "raw" && opts.span ? { span: opts.span } : {}),
+ ...(opts.fetch ? { fetch: true } : {}),
+ }),
});
- const j = (await r.json().catch(() => ({}))) as Partial<Done> & { error?: string };
+ const j = (await r.json().catch(() => ({}))) as { error?: string; fetching?: boolean; job?: { id: string } };
if (mine !== seq.current) return;
- if (!r.ok || !j.name) setState({ k: "failed", clip, kind, error: String(j.error ?? `HTTP ${r.status}`) });
- else setState({ k: "ready", done: { ...(j as Done), clip, kind }, open: { k: "idle" } });
+ if (!r.ok || !j.job?.id) return fail(String(j.error ?? `HTTP ${r.status}`));
+ const job = j.job.id;
+ setState({ k: "exporting", clip, kind, since, fetching: !!j.fetching });
+ // The job: polled until its export event (or its failure) is in.
+ for (;;) {
+ await new Promise((res) => setTimeout(res, 700));
+ if (mine !== seq.current) return;
+ const g = await fetch(`/api/report/clip-export?job=${encodeURIComponent(job)}`, { cache: "no-store" });
+ const v = (await g.json().catch(() => ({}))) as { done?: Done; error?: string; job?: { state: string; stepIndex: number; steps: unknown[]; log: string[] } };
+ if (mine !== seq.current) return;
+ if (v.done) {
+ setState({ k: "ready", done: { ...v.done, clip, kind }, open: { k: "idle" } });
+ return;
+ }
+ if (v.error || !g.ok) return fail(String(v.error ?? `HTTP ${g.status}`));
+ if (v.job && v.job.state !== "running") return fail(v.job.state === "done" ? "the job ended without an export" : `the job ${v.job.state}`);
+ const fetching = !!j.fetching && (v.job?.stepIndex ?? 0) < (v.job?.steps.length ?? 1) - 1;
+ const line = v.job?.log.filter((l) => !l.startsWith("$ ") && !l.startsWith("---")).at(-1) ?? null;
+ setState({ k: "exporting", clip, kind, since, fetching, line });
+ }
} catch (e) {
- if (mine === seq.current) setState({ k: "failed", clip, kind, error: e instanceof Error ? e.message : String(e) });
+ fail(e instanceof Error ? e.message : String(e));
}
},
[project, take],
@@ -111,27 +148,34 @@ const btn = (surface: Surface, quiet = false) =>
? paperButtonVariants()
: buttonVariants({ variant: quiet ? "quiet" : "outline", size: "sm" });
-/** Export clip, and its raw choice, for `clip` (null: nothing to export here, `why` says so). */
+/** Export clip, its raw choice, and Export ▾, for `clip` (null: nothing to export here, `why` says so). */
export function ClipExportButtons({
exp,
clip,
surface = "panel",
why = null,
unsaved = false,
+ around = null,
+ align = "start",
}: {
exp: ClipExportHandle;
clip: string | null;
surface?: Surface;
- /** Why there is nothing to export (a card, a window not fetched): the buttons are off and say so. */
+ /** Why there is nothing to export (a card, a window not fetched): the cut and raw buttons are off and say so. */
why?: string | null;
/** The bench has an edit not saved yet: the export is of the SAVED clip. */
unsaved?: boolean;
+ /** The clip's extent (source seconds): the full exchange's span starts from it. */
+ around?: { start: number; end: number } | null;
+ /** Which edge of Export ▾ its options open from: "end" on the bench's reader, at the screen's right edge. */
+ align?: "start" | "end";
}) {
const hydrated = useHydrated();
const off = !hydrated || !clip || !!why || exp.busy;
const saved = unsaved ? " — of the SAVED window: save first to export your edit" : "";
return (
<>
+ <ExportMenu exp={exp} clip={clip} surface={surface} around={around} saved={saved} align={align} disabled={!hydrated || !clip || exp.busy} />
<button
type="button"
data-clip-export-go={clip ?? ""}
@@ -156,6 +200,124 @@ export function ClipExportButtons({
);
}
+const CONTEXT_DEFAULT = 5;
+const r1 = (n: number) => Math.round(n * 10) / 10;
+
+/**
+ * Export ▾: the three kinds (UI notes item 12) in one place -- as cut (no
+ * chrome), with N s of context, raw / full exchange over a span. Context and
+ * the full exchange are fetched through the editor first when what they need
+ * is not on disk (`fetch: true`; the job says so while it fetches).
+ */
+function ExportMenu({
+ exp,
+ clip,
+ surface,
+ around,
+ saved,
+ align,
+ disabled,
+}: {
+ exp: ClipExportHandle;
+ clip: string | null;
+ surface: Surface;
+ around: { start: number; end: number } | null;
+ saved: string;
+ align: "start" | "end";
+ disabled: boolean;
+}) {
+ const [open, setOpen] = useState(false);
+ const [ctx, setCtx] = useState(String(CONTEXT_DEFAULT));
+ const [from, setFrom] = useState("");
+ const [to, setTo] = useState("");
+ const box = useRef<HTMLDivElement | null>(null);
+ // A new clip: the span starts from its extent again.
+ useEffect(() => {
+ setFrom(around ? String(r1(Math.max(0, around.start - 30))) : "");
+ setTo(around ? String(r1(around.end + 30)) : "");
+ }, [clip, around?.start, around?.end]); // eslint-disable-line react-hooks/exhaustive-deps
+ useEffect(() => {
+ if (!open) return;
+ const away = (e: PointerEvent) => {
+ if (box.current && !box.current.contains(e.target as Node)) setOpen(false);
+ };
+ const esc = (e: KeyboardEvent) => {
+ if (e.key === "Escape") setOpen(false);
+ };
+ window.addEventListener("pointerdown", away);
+ window.addEventListener("keydown", esc);
+ return () => {
+ window.removeEventListener("pointerdown", away);
+ window.removeEventListener("keydown", esc);
+ };
+ }, [open]);
+ const n = Number(ctx);
+ const ctxOk = Number.isFinite(n) && n >= 1 && n <= 120;
+ const a = Number(from);
+ const b = Number(to);
+ const spanOk = from.trim() !== "" && to.trim() !== "" && Number.isFinite(a) && Number.isFinite(b) && a >= 0 && b - a >= 0.5;
+ const go = (kind: ClipExportKind, opts: ClipExportOpts = {}) => {
+ if (!clip) return;
+ setOpen(false);
+ void exp.run(clip, kind, opts);
+ };
+ const input = "w-16 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 font-mono text-[11px] text-[var(--color-text)]";
+ const item = buttonVariants({ variant: "outline", size: "sm" });
+ return (
+ <div ref={box} className="relative inline-flex" data-clip-export-menu-box="">
+ <button
+ type="button"
+ data-clip-export-menu={clip ?? ""}
+ aria-haspopup="menu"
+ aria-expanded={open}
+ className={btn(surface)}
+ disabled={disabled}
+ title="Export ▾: as cut (no chrome), with N s of context, raw / full exchange — each a job in the heavy slot, into exports/"
+ onClick={() => setOpen((v) => !v)}
+ >
+ Export ▾
+ </button>
+ {open && (
+ <div
+ role="menu"
+ aria-label={`export ${clip ?? ""}`}
+ data-clip-export-options=""
+ className={`absolute bottom-full ${align === "end" ? "right-0" : "left-0"} z-30 mb-1 flex w-[19rem] max-w-[calc(100vw-2rem)] flex-col gap-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-2 text-[12px] text-[var(--color-text)] shadow-lg`}
+ >
+ <div className="flex flex-col gap-0.5">
+ <button type="button" role="menuitem" data-clip-export-kind="cut" className={item} onClick={() => go("cut")} title={`the clip as the cut plays it: its edges, gaps out, its mute; no deck${saved}`}>
+ As cut (no chrome)
+ </button>
+ <span className="text-[10.5px] text-[var(--color-dim)]">its edges, gaps out as jump cuts, its mute — no rail, subtitles, QR or cards</span>
+ </div>
+ <div className="flex flex-col gap-0.5">
+ <span className="flex flex-wrap items-center gap-1.5">
+ <button type="button" role="menuitem" data-clip-export-kind="context" className={item} disabled={!ctxOk} onClick={() => go("context", { context: n, fetch: true })}>
+ With context
+ </button>
+ <input aria-label="seconds of context either side" data-clip-export-context="" className={input} inputMode="decimal" value={ctx} onChange={(e) => setCtx(e.target.value)} />
+ <span className="text-[11px] text-[var(--color-dim)]">s either side</span>
+ </span>
+ <span className="text-[10.5px] text-[var(--color-dim)]">what the cut plays and {ctxOk ? n : "N"} s around it, as recorded (1–120; fetched first if not on disk)</span>
+ </div>
+ <div className="flex flex-col gap-0.5">
+ <span className="flex flex-wrap items-center gap-1.5">
+ <button type="button" role="menuitem" data-clip-export-kind="raw" className={item} disabled={!spanOk} onClick={() => go("raw", { span: { from: r1(a), to: r1(b) }, fetch: true })}>
+ Raw / full exchange
+ </button>
+ <input aria-label="from (source seconds)" data-clip-export-from="" className={input} inputMode="decimal" value={from} onChange={(e) => setFrom(e.target.value)} />
+ <span aria-hidden>–</span>
+ <input aria-label="to (source seconds)" data-clip-export-to="" className={input} inputMode="decimal" value={to} onChange={(e) => setTo(e.target.value)} />
+ </span>
+ <span className="text-[10.5px] text-[var(--color-dim)]">source seconds, as recorded (no gaps, no mute) — what is not on disk is fetched through the editor first</span>
+ </div>
+ <span className="text-[10.5px] text-[var(--color-dim)]">named <clip>-<kind>-<date>-<words>.mp4 in the project’s exports/ · Download for a phone</span>
+ </div>
+ )}
+ </div>
+ );
+}
+
/** Exporting… / the file, Download, Open folder / failed, with the reason. */
export function ClipExportStatus({ exp, surface = "panel", className }: { exp: ClipExportHandle; surface?: Surface; className?: string }) {
const s = exp.state;
@@ -172,8 +334,10 @@ export function ClipExportStatus({ exp, surface = "panel", className }: { exp: C
if (s.k === "exporting") {
return (
<p role="status" className={cn(base, "m-0")} data-clip-export-state="exporting">
- Exporting {s.clip}
- {s.kind === "raw" ? " (raw window)" : ""}… <span className={cn("font-mono", muted)}>{Math.max(0, Math.round((Date.now() - s.since) / 1000))} s</span>
+ {s.fetching ? "Fetching what it needs through the editor, then exporting " : "Exporting "}
+ {s.clip}
+ {s.kind === "raw" ? " (raw)" : s.kind === "context" ? " (with context)" : ""}… <span className={cn("font-mono", muted)}>{Math.max(0, Math.round((Date.now() - s.since) / 1000))} s</span>
+ {s.line ? <span className={cn("ml-1 font-mono", muted)}>{s.line.slice(0, 120)}</span> : null}
</p>
);
}
diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx
@@ -7,6 +7,7 @@ import ClipBenchPage from "./ClipBenchPage";
import ClaimBenchPage from "./ClaimBenchPage";
import SweepProject from "./SweepProject";
import TakesPage from "./TakesPage";
+import TakesComparePage from "./TakesComparePage";
import NarrationPage from "./NarrationPage";
import ReviewPage from "./ReviewPage";
import ClipDeckPage from "./ClipDeckPage";
@@ -61,6 +62,9 @@ export default async function ProjectView({
// `/browse/<project>/takes` -- alternative renders of one part of the
// cut, side by side, each judged like / maybe / no.
if (rest.length === 1 && rest[0] === "takes") return <TakesPage project={project} />;
+ // `/projects/<project>/takes/compare?a=<project>:<take>&b=…` -- two takes of the project
+ // or of its variants side by side, in step, with what differs (UI notes item 19).
+ if (rest.length === 2 && rest[0] === "takes" && rest[1] === "compare") return <TakesComparePage project={project} search={search} />;
// `/projects/<project>/takes/<take>/walk` -- walk a take: its clips, and
// where the walk starts; `…/takes/<take>/clip/<id>` -- the bench on one
// of them, its saves going into the take's patch, never the manifest.
diff --git a/umtool/components/projects/TakeVariants.tsx b/umtool/components/projects/TakeVariants.tsx
@@ -0,0 +1,231 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import DeletePlan from "@/components/DeletePlan";
+import { buttonVariants } from "@/components/ui/button";
+import { takesCompareHref, takesHref } from "@/lib/hrefs";
+
+// ---------------------------------------------------------------------------
+// TAKE HOUSEKEEPING, the rest of it (UI notes 2026-10-30, item 19): Cancel a
+// take while it renders (lib/report/takeCancel.mjs), Fork as variant
+// (variantFork.mjs: a project beside this one), Compare with… (two takes of
+// the project and its variants side by side: /projects/<p>/takes/compare).
+// All through POST /api/report/takes/housekeeping, as relabel and supersede.
+// ---------------------------------------------------------------------------
+
+export type CompareOption = { ref: string; label: string };
+export type WorkDirs = {
+ rendering: Array<{ id: string; label: string | null; pid: number | null; startedAt: string | null; from: string | null }>;
+ cancelled: Array<{ id: string; label: string | null; at: string; by: string }>;
+};
+
+const sm = buttonVariants({ size: "sm" });
+const smOutline = buttonVariants({ variant: "outline", size: "sm" });
+
+async function housekeeping(body: Record<string, unknown>) {
+ const r = await fetch("/api/report/takes/housekeeping", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ cache: "no-store",
+ });
+ const j = (await r.json().catch(() => ({}))) as Record<string, unknown> & { error?: string };
+ return { ok: r.ok, j };
+}
+
+export type CancelSaid = { take: string; text: string; ok: boolean };
+
+/**
+ * Cancel: asks the process rendering the take to stop, and waits for it (up to ~25 s).
+ * The answer goes to `onSaid` -- held by a parent that outlives this button, because a
+ * render that stopped is no longer rendering, and the refresh takes the button away.
+ */
+export function CancelRender({ project, take, ready, onSaid }: { project: string; take: string; ready: boolean; onSaid: (s: CancelSaid) => void }) {
+ const router = useRouter();
+ const [busy, setBusy] = useState(false);
+ return (
+ <span className="inline-flex flex-wrap items-center gap-1.5" data-take-cancel={take}>
+ <button
+ type="button"
+ data-action="cancel-render"
+ disabled={!ready || busy}
+ className={`${buttonVariants({ variant: "outline", size: "sm" })} border-[var(--color-bad)] text-[var(--color-bad)]`}
+ title="stop this take's render: the process rendering it stops its render, marks the take cancelled and lets render mode go if the take held it"
+ onClick={async () => {
+ setBusy(true);
+ const { ok, j } = await housekeeping({ project, take, op: "cancel" });
+ setBusy(false);
+ onSaid({ take, ok: ok && j.stopped === true, text: String(j.said ?? j.error ?? (ok ? "asked" : "refused")) });
+ router.refresh();
+ }}
+ >
+ {busy ? "Cancelling…" : "Cancel render"}
+ </button>
+ </span>
+ );
+}
+
+/** What the last Cancel render said. */
+export function CancelSaidLine({ said }: { said: CancelSaid | null }) {
+ if (!said) return null;
+ return (
+ <p role="status" data-take-cancel-said={said.take} className={`m-0 text-[11.5px] ${said.ok ? "text-text-2" : "text-reject-text"}`}>
+ {said.text}
+ </p>
+ );
+}
+
+/** Fork as variant: the take as a project beside this one (default name v-<take>). */
+export function ForkVariant({ project, take, ready }: { project: string; take: string; ready: boolean }) {
+ const [open, setOpen] = useState(false);
+ const [name, setName] = useState(`v-${take}`);
+ const [busy, setBusy] = useState(false);
+ const [done, setDone] = useState<{ id: string; take: { id: string; linked: boolean } | null } | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ if (done) {
+ return (
+ <span data-take-forked={done.id} className="text-[11px] text-text-2">
+ Forked as{" "}
+ <Link href={takesHref(done.id)} className="ink-link font-mono">
+ {done.id}
+ </Link>
+ {done.take?.linked ? ` — with this take in it` : ""} ·{" "}
+ <Link href={takesCompareHref(project, `${project}:${take}`, `${done.id}:${take}`)} className="ink-link" data-take-forked-compare="">
+ compare
+ </Link>
+ </span>
+ );
+ }
+ return (
+ <span className="inline-flex flex-wrap items-center gap-1.5">
+ {!open ? (
+ <button type="button" data-action="fork" disabled={!ready} className={smOutline} title="a variant of the project made from this take: a project beside this one with its manifest, the media linked, the take in it" onClick={() => setOpen(true)}>
+ Fork as variant
+ </button>
+ ) : (
+ <>
+ <input
+ autoFocus
+ aria-label="the variant's name"
+ data-take-fork-name={take}
+ value={name}
+ maxLength={64}
+ onChange={(e) => setName(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") setOpen(false);
+ }}
+ className="w-40 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 font-mono text-[11px] text-[var(--color-text)]"
+ />
+ <button
+ type="button"
+ data-action="fork-go"
+ disabled={busy || !name.trim()}
+ className={sm}
+ onClick={async () => {
+ setBusy(true);
+ setError(null);
+ const { ok, j } = await housekeeping({ project, take, op: "fork", name: name.trim() });
+ setBusy(false);
+ if (!ok) setError(String(j.error ?? "refused"));
+ else setDone({ id: String(j.id), take: (j.take as { id: string; linked: boolean } | null) ?? null });
+ }}
+ >
+ {busy ? "Forking…" : "Fork"}
+ </button>
+ <button type="button" className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={() => setOpen(false)}>
+ Cancel
+ </button>
+ </>
+ )}
+ {error && (
+ <span role="alert" className="text-[11px] text-reject-text">
+ {error}
+ </span>
+ )}
+ </span>
+ );
+}
+
+/** Compare with…: another take of the project or of one of its variants, side by side. */
+export function CompareWith({ project, take, options }: { project: string; take: string; options: CompareOption[] }) {
+ const mine = `${project}:${take}`;
+ const others = options.filter((o) => o.ref !== mine);
+ const [other, setOther] = useState(others[0]?.ref ?? "");
+ if (!others.length) return null;
+ return (
+ <span className="inline-flex flex-wrap items-center gap-1.5 text-[11px]">
+ <select
+ data-take-compare-with={take}
+ value={other}
+ onChange={(e) => setOther(e.target.value)}
+ className="max-w-[14rem] rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 text-[11px]"
+ title="another take of this project or of its variants"
+ >
+ {others.map((o) => (
+ <option key={o.ref} value={o.ref}>
+ {o.label}
+ </option>
+ ))}
+ </select>
+ <Link href={takesCompareHref(project, mine, other)} data-action="compare" className={smOutline}>
+ Compare
+ </Link>
+ </span>
+ );
+}
+
+/**
+ * The take directories that are not takes (yet): a first render in progress,
+ * with Cancel, and first renders cancelled -- folded away, each deletable.
+ */
+export function TakeWorkDirs({ project, dirs, ready }: { project: string; dirs: WorkDirs; ready: boolean }) {
+ const router = useRouter();
+ const [show, setShow] = useState(false);
+ const [said, setSaid] = useState<CancelSaid | null>(null);
+ if (!dirs.rendering.length && !dirs.cancelled.length && !said) return null;
+ return (
+ <section data-take-workdirs="" className="space-y-1.5 text-[12px]">
+ <CancelSaidLine said={said} />
+ {dirs.rendering.map((r) => (
+ <div key={r.id} data-take-rendering={r.id} className="flex flex-wrap items-center gap-2 rounded border border-[var(--color-meter)] bg-[var(--color-panel)] px-3 py-2">
+ <span className="micro">rendering now</span>
+ <span className="font-mono">{r.id}</span>
+ {r.label && <span className="text-text-2">{r.label}</span>}
+ <span className="text-[11px] text-[var(--color-dim)]" suppressHydrationWarning>
+ {r.startedAt ? `since ${r.startedAt.slice(11, 16)}` : ""}
+ {r.pid ? ` · pid ${r.pid}` : ""}
+ {r.from ? ` · from ${r.from}` : ""} · its first render: it becomes a take when it is done
+ </span>
+ <span className="ml-auto">
+ <CancelRender project={project} take={r.id} ready={ready} onSaid={setSaid} />
+ </span>
+ </div>
+ ))}
+ {dirs.cancelled.length > 0 && (
+ <p className="m-0 text-[11px] text-[var(--color-dim)]" data-cancelled-count={dirs.cancelled.length}>
+ {dirs.cancelled.length} cancelled render{dirs.cancelled.length === 1 ? "" : "s"} {show ? "shown" : "folded away"} ·{" "}
+ <button type="button" data-action="show-cancelled" aria-pressed={show} onClick={() => setShow((v) => !v)} className="ink-link">
+ {show ? "fold them away" : "show them"}
+ </button>
+ </p>
+ )}
+ {show &&
+ dirs.cancelled.map((c) => (
+ <div key={c.id} data-take-cancelled={c.id} className="flex flex-wrap items-center gap-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-1.5 opacity-75">
+ <span className="micro">cancelled</span>
+ <span className="font-mono">{c.id}</span>
+ {c.label && <span className="text-text-2">{c.label}</span>}
+ <span className="text-[11px] text-[var(--color-dim)]" suppressHydrationWarning>
+ {c.at.slice(0, 16).replace("T", " ")}
+ {c.by ? ` · by ${c.by}` : ""} · never finished: no take
+ </span>
+ <span className="ml-auto">
+ <DeletePlan label={`Delete take ${c.id}`} subject={`the cancelled take ${c.id}`} endpoint="/api/report/takes/delete" body={{ project, take: c.id }} onDone={() => router.refresh()} />
+ </span>
+ </div>
+ ))}
+ </section>
+ );
+}
diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx
@@ -14,6 +14,7 @@ import { playHref, takeWalkHref } from "@/lib/hrefs";
import { BenchBody, VerdictBar } from "./bench/BenchShell";
import { startTakeJob } from "./NewTakePanel";
import TakeActions from "./TakeActions";
+import { CancelRender, CancelSaidLine, CompareWith, ForkVariant, TakeWorkDirs, type CancelSaid, type CompareOption, type WorkDirs } from "./TakeVariants";
// The takes of one project, a group at a time, every preview on screen at once.
//
@@ -56,6 +57,8 @@ export type Take = {
holds?: string[];
/** The newest whole-cut take of the manifest: the working cut's name (lib/report/workingCut.mjs). */
latest?: boolean;
+ /** Its last render was cancelled (takes/<id>/cancelled.json, lib/report/takeCancel.mjs): the take kept is the one before. */
+ cancelled?: { at: string; by: string } | null;
};
/** A take's work files, as `GET /api/report/takes/prune` measures them (lib/report/takePrune.mjs). */
@@ -130,10 +133,16 @@ export default function TakesBench({
initial,
head,
children,
+ compareOptions = [],
+ workDirs = null,
}: {
project: string;
groups: { group: string; takes: Take[] }[];
initial: Record<string, TakeVerdict>;
+ /** Every take of the project and of its variants (`<project>:<take>`), for Compare with… */
+ compareOptions?: CompareOption[];
+ /** First renders in progress (Cancel) and cancelled (folded away). */
+ workDirs?: WorkDirs | null;
/** Above the groups, in the work column (New take). */
head?: React.ReactNode;
/** Under the groups, in the work column (the takes the listing skipped). */
@@ -284,6 +293,7 @@ export default function TakesBench({
<BenchBody verdict={verdictBar}>
<div className="space-y-6">
{head}
+ {workDirs && <TakeWorkDirs project={project} dirs={workDirs} ready={ready} />}
<WorkSummary project={project} work={work} error={workError} ready={ready} onFreed={() => void loadWork()} />
{groups.map((g) => {
const tally = VERDICTS.map((v) => [v.id, g.takes.filter((t) => verdicts[t.id]?.verdict === v.id).length] as const)
@@ -360,6 +370,7 @@ export default function TakesBench({
onPicked={(v) => setVerdicts(v)}
work={work ? (workOf.get(t.id) ?? null) : undefined}
onFreed={() => void loadWork()}
+ compareOptions={compareOptions}
/>
))}
</div>
@@ -498,7 +509,10 @@ function TakeCard({
onPicked,
work,
onFreed,
+ compareOptions,
}: {
+ /** Every take of the project and its variants, for Compare with… */
+ compareOptions: CompareOption[];
/** The project's other takes: what "superseded by" may name. */
others: { id: string; label: string }[];
onVerdicts: (verdicts: Record<string, TakeVerdict>) => void;
@@ -531,6 +545,8 @@ function TakeCard({
}, []);
const [note, setNote] = useState(verdict?.note ?? "");
const [busy, setBusy] = useState(false);
+ // What Cancel render said: kept here, as the button goes once the render has stopped.
+ const [cancelSaid, setCancelSaid] = useState<CancelSaid | null>(null);
const [error, setError] = useState<string | null>(null);
const saved = verdict?.note ?? "";
// Adopt a server value that moved underneath (another tab, a refresh).
@@ -712,6 +728,11 @@ function TakeCard({
superseded{superseded.by ? ` by ${superseded.by}` : ""}
</span>
)}
+ {t.cancelled && !(t.holds ?? []).some((h) => h.startsWith("it is rendering")) && (
+ <span data-take-cancelled-mark="" title={`its last render was cancelled${t.cancelled.by ? ` by ${t.cancelled.by}` : ""} at ${t.cancelled.at}: this is the take from before it`} className={badgeVariants({ variant: "state", size: "sm" })}>
+ last render cancelled
+ </span>
+ )}
{t.draft && (
<span data-take-is-draft="" className={badgeVariants({ variant: "state", size: "sm" })}>
draft
@@ -844,6 +865,12 @@ function TakeCard({
</p>
)}
<TakeWorkLine project={project} work={work} ready={ready} onFreed={onFreed} />
+ {(t.holds ?? []).some((h) => h.startsWith("it is rendering")) && <CancelRender project={project} take={t.id} ready={ready} onSaid={setCancelSaid} />}
+ <CancelSaidLine said={cancelSaid} />
+ <div className="flex flex-wrap items-center gap-1.5" data-take-variants={t.id}>
+ <ForkVariant project={project} take={t.id} ready={ready} />
+ <CompareWith project={project} take={t.id} options={compareOptions} />
+ </div>
<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" })}>
diff --git a/umtool/components/projects/TakesComparePage.tsx b/umtool/components/projects/TakesComparePage.tsx
@@ -0,0 +1,168 @@
+import Link from "next/link";
+import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell";
+import { projectRef } from "@/lib/projects";
+import { projectsHref, takesCompareHref, takesHref } from "@/lib/hrefs";
+import { listTakes } from "@/lib/report/takes.mjs";
+import { compareTakes, parseTakeRef, shortValue } from "@/lib/report/takeCompare.mjs";
+import { variantFamily } from "@/lib/report/variantFork.mjs";
+import { REPORTS_ROOT } from "@/lib/paths.mjs";
+import type { ProjectRef } from "@/lib/project-types";
+import TakesComparePlayers from "./TakesComparePlayers";
+
+// `/projects/<project>/takes/compare?a=<project>:<take>&b=<project>:<take>` --
+// two takes side by side (UI notes 2026-10-30, item 19): of the project, or of
+// the project and one of its variants (lib/report/variantFork.mjs). Two
+// players kept in step (TakesComparePlayers), and what differs between the
+// takes (lib/report/takeCompare.mjs): the cut's changes A → B, the look's.
+
+type Search = Record<string, string | undefined>;
+
+export default async function TakesComparePage({ project, search }: { project: ProjectRef; search: Search }) {
+ const family = await variantFamily(project, { root: REPORTS_ROOT }).catch(() => ({ parent: project.id, members: [] as Awaited<ReturnType<typeof variantFamily>>["members"] }));
+ const all = family.members.flatMap((m) => (m.takes as Array<{ id: string; label: string; draft?: boolean }>).map((t) => ({ ref: `${m.id}:${t.id}`, project: m.id, take: t.id, label: t.label, draft: !!t.draft })));
+ const own = all.filter((x) => x.project === project.id);
+ const a = parseTakeRef(search.a, project.id) ?? (own[0] ? { project: own[0].project, take: own[0].take } : null);
+ const b = parseTakeRef(search.b, project.id) ?? (all.find((x) => !a || x.ref !== `${a.project}:${a.take}`) ?? null);
+ let error: string | null = null;
+ let c: Awaited<ReturnType<typeof compareTakes>> | null = null;
+ if (!a || !b) error = "two takes are needed to compare: this project and its variants have fewer";
+ else {
+ try {
+ const pa = a.project === project.id ? project : await projectRef(a.project);
+ const pb = b.project === project.id ? project : await projectRef(b.project);
+ if (!pa || !pb) throw new Error(`no project ${!pa ? a.project : b.project}`);
+ // Each must be a take its project lists (listTakes), as the preview route serves only those.
+ for (const [p, ref] of [[pa, a], [pb, b]] as const) {
+ if (!(await listTakes(p.dir)).takes.some((t: { id: string }) => t.id === ref.take)) throw new Error(`${p.id} has no take ${ref.take}`);
+ }
+ c = await compareTakes({ ref: { project: pa.id, take: a.take }, dir: pa.dir }, { ref: { project: pb.id, take: b.take }, dir: pb.dir });
+ } catch (e) {
+ error = e instanceof Error ? e.message : String(e);
+ }
+ }
+ const pickers = (
+ <form method="get" className="flex flex-wrap items-center gap-2 text-[12px]" data-compare-pick="">
+ {(["a", "b"] as const).map((side) => (
+ <label key={side} className="flex items-center gap-1">
+ <span className="micro">{side.toUpperCase()}</span>
+ <select
+ name={side}
+ defaultValue={side === "a" ? (a ? `${a.project}:${a.take}` : "") : b ? `${b.project}:${b.take}` : ""}
+ className="max-w-[22rem] rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 text-[12px]"
+ data-compare-select={side}
+ >
+ {all.map((x) => (
+ <option key={x.ref} value={x.ref}>
+ {x.project === project.id ? "" : `${x.project.split("/").pop()} · `}
+ {x.take} — {x.label}
+ {x.draft ? " (draft)" : ""}
+ </option>
+ ))}
+ </select>
+ </label>
+ ))}
+ <button type="submit" className="rounded border border-[var(--color-line)] px-2 py-0.5 text-[12px] hover:bg-panel-2">
+ Compare
+ </button>
+ {a && b && (
+ <Link href={takesCompareHref(project.id, `${b.project}:${b.take}`, `${a.project}:${a.take}`)} className="ink-link text-[11.5px]" data-compare-swap="">
+ swap A and B
+ </Link>
+ )}
+ </form>
+ );
+ return (
+ <BenchFrame
+ kind="takes-compare"
+ top={
+ <BenchTop
+ trail={[{ href: projectsHref(), label: "Projects" }]}
+ back={{ href: takesHref(project.id), label: `${project.id} · takes` }}
+ kind="Compare takes"
+ here="compare"
+ note={c ? `${c.a.ref} · ${c.b.ref}` : undefined}
+ />
+ }
+ >
+ <BenchBody workClassName="space-y-4">
+ {pickers}
+ {error && (
+ <p role="alert" data-compare-error="" className="text-[12px] text-reject-text">
+ {error}
+ </p>
+ )}
+ {c && (
+ <>
+ <TakesComparePlayers
+ a={{ project: c.a.project, take: c.a.take, label: c.a.label, seconds: c.a.seconds, hasPreview: c.a.hasPreview }}
+ b={{ project: c.b.project, take: c.b.take, label: c.b.label, seconds: c.b.seconds, hasPreview: c.b.hasPreview }}
+ />
+ <section data-compare-diff={c.same ? "same" : c.cut.lines.length + c.look.length} className="space-y-3">
+ <h2 className="micro">what differs, A → B</h2>
+ <dl className="grid grid-cols-[auto_1fr_1fr] gap-x-4 gap-y-0.5 text-[12px]" data-compare-facts="">
+ <dt />
+ <dd className="micro m-0">A</dd>
+ <dd className="micro m-0">B</dd>
+ {(
+ [
+ ["project", c.a.project, c.b.project],
+ ["take", c.a.take, c.b.take],
+ ["label", c.a.label, c.b.label],
+ ["length", typeof c.a.seconds === "number" ? `${c.a.seconds.toFixed(1)} s` : "not rendered", typeof c.b.seconds === "number" ? `${c.b.seconds.toFixed(1)} s` : "not rendered"],
+ ["clips", String(c.a.clips), String(c.b.clips)],
+ ["window", c.a.window === "full" ? "full cut" : c.a.window ? `${c.a.window.at}+${c.a.window.dur} s` : "—", c.b.window === "full" ? "full cut" : c.b.window ? `${c.b.window.at}+${c.b.window.dur} s` : "—"],
+ ["style", c.a.style ?? "—", c.b.style ?? "—"],
+ ["built", c.a.builtAt?.slice(0, 16).replace("T", " ") ?? "—", c.b.builtAt?.slice(0, 16).replace("T", " ") ?? "—"],
+ ] as const
+ ).map(([k, x, y]) => (
+ <div key={k} className="contents" data-compare-fact={k} data-differs={x !== y ? "" : undefined}>
+ <dt className="text-[var(--color-dim)]">{k}</dt>
+ <dd className={`m-0 font-mono text-[11.5px] ${x !== y ? "text-[var(--color-text)]" : "text-[var(--color-dim)]"}`}>{x}</dd>
+ <dd className={`m-0 font-mono text-[11.5px] ${x !== y ? "text-[var(--color-text)]" : "text-[var(--color-dim)]"}`}>{y}</dd>
+ </div>
+ ))}
+ </dl>
+ {c.seconds !== null && c.seconds !== 0 && (
+ <p className="m-0 text-[12px] text-text-2" data-compare-seconds={c.seconds}>
+ B is {Math.abs(c.seconds).toFixed(1)} s {c.seconds > 0 ? "longer" : "shorter"} than A.
+ </p>
+ )}
+ {c.same && <p className="m-0 text-[12px] text-[var(--color-dim)]">The same cut and the same look.</p>}
+ {c.cut.lines.length > 0 && (
+ <div>
+ <h3 className="micro mb-1">the cut — {c.cut.lines.length} change{c.cut.lines.length === 1 ? "" : "s"}</h3>
+ <ul className="space-y-0.5 font-mono text-[11.5px]" data-compare-cut="">
+ {c.cut.lines.map((l, i) => (
+ <li key={i}>{l}</li>
+ ))}
+ </ul>
+ </div>
+ )}
+ {c.look.length > 0 && (
+ <div>
+ <h3 className="micro mb-1">
+ the look — {c.look.length}
+ {c.lookMore ? `+${c.lookMore}` : ""} difference{c.look.length === 1 ? "" : "s"}
+ </h3>
+ <ul className="space-y-0.5 font-mono text-[11.5px]" data-compare-look="">
+ {c.look.map((d) => (
+ <li key={d.path} data-compare-look-path={d.path}>
+ {d.path}: <span className="text-[var(--color-dim)]">{shortValue(d.a)}</span> → {shortValue(d.b)}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ <p className="m-0 text-[11px] text-[var(--color-dim)]">
+ <code className="font-mono">
+ umtool takes compare {project.id} {c.a.ref} {c.b.ref}
+ </code>{" "}
+ prints the same.
+ </p>
+ </section>
+ </>
+ )}
+ </BenchBody>
+ </BenchFrame>
+ );
+}
diff --git a/umtool/components/projects/TakesComparePlayers.tsx b/umtool/components/projects/TakesComparePlayers.tsx
@@ -0,0 +1,175 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+
+// ---------------------------------------------------------------------------
+// TWO TAKES IN STEP (the compare page, UI notes item 19): A leads, B follows.
+// One transport for both -- play, pause, the seek bar, ±5 s -- because two
+// players each with its own controls drift apart the moment one is touched.
+// While they play, B is pulled back to A whenever it strays past 0.15 s (a
+// seek into a file that is only partly loaded starts late). ONE AUDIO SOURCE,
+// as on the Takes page: A or B, the other muted.
+// ---------------------------------------------------------------------------
+
+type Side = { project: string; take: string; label: string; seconds: number | null; hasPreview: boolean };
+
+const src = (s: Side) => `/api/report/takes/preview?${new URLSearchParams({ project: s.project, take: s.take })}`;
+const clock = (t: number) => {
+ const s = Math.max(0, t);
+ const m = Math.floor(s / 60);
+ return `${m}:${(s - m * 60).toFixed(1).padStart(4, "0")}`;
+};
+/** How far B may stray from A while playing before it is pulled back (s). */
+const DRIFT = 0.15;
+
+export default function TakesComparePlayers({ a, b }: { a: Side; b: Side }) {
+ const va = useRef<HTMLVideoElement | null>(null);
+ const vb = useRef<HTMLVideoElement | null>(null);
+ const [ready, setReady] = useState(false);
+ const [playing, setPlaying] = useState(false);
+ const [t, setT] = useState(0);
+ const [drift, setDrift] = useState(0);
+ const [sound, setSound] = useState<"a" | "b">("a");
+ const length = Math.max(a.seconds ?? 0, b.seconds ?? 0);
+ const [dur, setDur] = useState(length);
+ useEffect(() => setReady(true), []);
+
+ useEffect(() => {
+ if (va.current) va.current.muted = sound !== "a";
+ if (vb.current) vb.current.muted = sound !== "b";
+ }, [sound]);
+
+ const both = () => [va.current, vb.current].filter((v): v is HTMLVideoElement => !!v);
+ const seek = useCallback((to: number) => {
+ const at = Math.max(0, to);
+ for (const v of both()) v.currentTime = Math.min(at, Number.isFinite(v.duration) ? v.duration : at);
+ setT(at);
+ }, []);
+ const play = useCallback(async () => {
+ const lead = va.current ?? vb.current;
+ if (!lead) return;
+ const at = lead.currentTime;
+ for (const v of both()) if (Math.abs(v.currentTime - at) > 0.01) v.currentTime = Math.min(at, Number.isFinite(v.duration) ? v.duration : at);
+ await Promise.allSettled(both().map((v) => v.play()));
+ setPlaying(true);
+ }, []);
+ const pause = useCallback(() => {
+ for (const v of both()) v.pause();
+ setPlaying(false);
+ const lead = va.current ?? vb.current;
+ if (lead && vb.current && va.current) vb.current.currentTime = Math.min(lead.currentTime, Number.isFinite(vb.current.duration) ? vb.current.duration : lead.currentTime);
+ }, []);
+
+ // The clock and the leash, four times a second.
+ useEffect(() => {
+ const id = window.setInterval(() => {
+ const x = va.current;
+ const y = vb.current;
+ const lead = x ?? y;
+ if (!lead) return;
+ setT(lead.currentTime);
+ if (x && y) {
+ const d = Math.abs(y.currentTime - x.currentTime);
+ // B past its own end is not drift: it simply has less.
+ const past = Number.isFinite(y.duration) && x.currentTime >= y.duration - 0.05;
+ setDrift(past ? 0 : d);
+ if (!x.paused && !past && d > DRIFT) y.currentTime = x.currentTime;
+ }
+ if (lead.ended || (x?.paused && y?.paused && playing)) setPlaying(false);
+ }, 250);
+ return () => window.clearInterval(id);
+ }, [playing]);
+
+ // The keys: space plays / pauses, ← → five seconds.
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ const el = e.target as HTMLElement | null;
+ if (el?.closest?.("input, textarea, select, [contenteditable='true']")) return;
+ if (e.key === " ") {
+ e.preventDefault();
+ void (playing ? pause() : play());
+ } else if (e.key === "ArrowLeft") seek(t - 5);
+ else if (e.key === "ArrowRight") seek(t + 5);
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [playing, play, pause, seek, t]);
+
+ const player = (s: Side, side: "a" | "b") => (
+ <figure className="m-0 flex min-w-0 flex-col gap-1" data-compare-player={side} data-compare-take={`${s.project}:${s.take}`}>
+ <figcaption className="flex flex-wrap items-baseline gap-2 text-[12px]">
+ <span className="micro">{side.toUpperCase()}</span>
+ <span className="font-mono text-[11.5px]">{s.project.split("/").pop()}</span>
+ <span className="font-mono text-[11.5px]">{s.take}</span>
+ <span className="truncate text-text-2">{s.label}</span>
+ </figcaption>
+ {s.hasPreview ? (
+ <video
+ ref={side === "a" ? va : vb}
+ src={src(s)}
+ preload="auto"
+ playsInline
+ muted={sound !== side}
+ onLoadedMetadata={(e) => {
+ const d = e.currentTarget.duration;
+ if (Number.isFinite(d)) setDur((cur) => Math.max(cur, d));
+ }}
+ className="aspect-video w-full bg-black"
+ />
+ ) : (
+ <div className="flex aspect-video w-full items-center justify-center bg-black text-[12px] text-[var(--color-dim)]">a draft: nothing rendered to play</div>
+ )}
+ </figure>
+ );
+
+ return (
+ <section data-compare-players="" data-compare-time={t.toFixed(2)} data-compare-drift={drift.toFixed(2)} data-compare-state={playing ? "playing" : "paused"} className="space-y-2">
+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
+ {player(a, "a")}
+ {player(b, "b")}
+ </div>
+ <div className="flex flex-wrap items-center gap-2 text-[12px]">
+ <button type="button" data-compare-play="" disabled={!ready} className={buttonVariants({ variant: "go", size: "sm" })} onClick={() => void (playing ? pause() : play())}>
+ {playing ? "Pause both" : "Play both"}
+ </button>
+ <button type="button" data-compare-back="" disabled={!ready} className={buttonVariants({ variant: "outline", size: "sm" })} onClick={() => seek(t - 5)}>
+ −5 s
+ </button>
+ <button type="button" data-compare-fwd="" disabled={!ready} className={buttonVariants({ variant: "outline", size: "sm" })} onClick={() => seek(t + 5)}>
+ +5 s
+ </button>
+ <input
+ type="range"
+ aria-label="where both are"
+ data-compare-seek=""
+ min={0}
+ max={Math.max(0.1, dur)}
+ step={0.1}
+ value={Math.min(t, Math.max(0.1, dur))}
+ onChange={(e) => seek(Number(e.target.value))}
+ className="min-w-[10rem] flex-1"
+ />
+ <span className="num font-mono text-[11.5px]">
+ {clock(t)} / {clock(dur)}
+ </span>
+ <span className="flex items-center gap-1" role="group" aria-label="whose sound">
+ <span className="micro">sound</span>
+ {(["a", "b"] as const).map((s) => (
+ <button
+ key={s}
+ type="button"
+ data-compare-sound={s}
+ aria-pressed={sound === s}
+ className={buttonVariants({ variant: sound === s ? "pressed" : "outline", size: "sm" })}
+ onClick={() => setSound(s)}
+ >
+ {s.toUpperCase()}
+ </button>
+ ))}
+ </span>
+ <span className="text-[11px] text-[var(--color-dim)]">space plays · ← → 5 s · B follows A</span>
+ </div>
+ </section>
+ );
+}
diff --git a/umtool/components/projects/TakesPage.tsx b/umtool/components/projects/TakesPage.tsx
@@ -2,7 +2,7 @@ import { readFile } from "node:fs/promises";
import path from "node:path";
import Link from "next/link";
import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell";
-import { projectsHref } from "@/lib/hrefs";
+import { projectsHref, takesHref } from "@/lib/hrefs";
import { listTakes, readVerdicts } from "@/lib/report/takes.mjs";
import { pieceHrefOfProject } from "@/lib/pieces/article";
import type { ProjectRef } from "@/lib/project-types";
@@ -14,6 +14,10 @@ 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";
+import { readCancelled, takeWorkDirs } from "@/lib/report/takeCancel.mjs";
+import { variantFamily } from "@/lib/report/variantFork.mjs";
+import { REPORTS_ROOT } from "@/lib/paths.mjs";
+import { TakeWorkDirs, type CompareOption } from "./TakeVariants";
// `/browse/<project>/takes` -- alternative renders of one part of the cut,
// watched side by side and judged like / maybe / no.
@@ -43,7 +47,27 @@ export default async function TakesPage({ project }: { project: ProjectRef }) {
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 }));
+ // Cancel, fork, compare (UI notes item 19): first renders in progress or cancelled, each take's
+ // last-render-cancelled mark, and every take of the project and its variants (variantFork.mjs).
+ const [workDirs, cancelledMarks, family] = await Promise.all([
+ takeWorkDirs(project.dir),
+ Promise.all((listing.takes as Take[]).map(async (t) => [t.id, await readCancelled(project.dir, t.id)] as const)).then((xs) => new Map(xs)),
+ variantFamily(project, { root: REPORTS_ROOT }).catch(() => ({ parent: project.id, members: [] })),
+ ]);
+ const compareOptions: CompareOption[] = family.members.flatMap((m) =>
+ (m.takes as Array<{ id: string; label: string; draft?: boolean }>).map((t) => ({
+ ref: `${m.id}:${t.id}`,
+ label: `${m.id === project.id ? "" : `${m.id.split("/").pop()} · `}${t.id} — ${t.label}${t.draft ? " (draft)" : ""}`.slice(0, 90),
+ })),
+ );
+ const variants = family.members.filter((m) => m.id !== family.parent);
+ const parentOf = family.parent !== project.id ? family.parent : null;
+ const takes = (listing.takes as Take[]).map((t) => {
+ const c = cancelledMarks.get(t.id);
+ // A cancel after the take was last built (a rebuild stopped): the take kept is the one from before.
+ const cancelled = c && (!t.builtAt || c.at > t.builtAt) ? { at: String(c.at), by: String(c.by ?? "") } : null;
+ return { ...t, stale: t.baseHash ? t.baseHash !== current : null, holds: holds.get(t.id) ?? [], latest: t.id === working?.latest?.id, cancelled };
+ });
const byId = new Map(takes.map((t) => [t.id, t]));
const panel =
project.kind === "report-video" ? (
@@ -90,6 +114,7 @@ export default async function TakesPage({ project }: { project: ProjectRef }) {
{takes.length === 0 ? (
<BenchBody workClassName="space-y-4">
{panel}
+ <TakeWorkDirs project={project.id} dirs={workDirs} ready />
<p data-takes-empty="" className="text-[12px] text-[var(--color-dim)]">
No takes yet.{" "}
<Link href={back} className="ink-link">
@@ -103,11 +128,43 @@ 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>}
+ compareOptions={compareOptions}
+ workDirs={workDirs}
head={
<>
<p className="m-0 text-[12.5px]" data-takes-working="">
<LatestLine project={project.id} working={working} />
</p>
+ {(parentOf || variants.length > 0) && (
+ <p className="m-0 text-[12px] text-text-2" data-takes-family={family.members.length}>
+ {parentOf ? (
+ <>
+ A variant of{" "}
+ <Link href={takesHref(parentOf)} className="ink-link font-mono">
+ {parentOf}
+ </Link>
+ {family.members.find((m) => m.id === project.id)?.fromTake ? `, forked from its take ${family.members.find((m) => m.id === project.id)?.fromTake}` : ""}.{" "}
+ </>
+ ) : null}
+ {variants.filter((v) => v.id !== project.id).length > 0 && (
+ <>
+ Variants:{" "}
+ {variants
+ .filter((v) => v.id !== project.id)
+ .map((v, i) => (
+ <span key={v.id}>
+ {i > 0 ? ", " : ""}
+ <Link href={takesHref(v.id)} className="ink-link font-mono" data-takes-variant={v.id}>
+ {v.id.split("/").pop()}
+ </Link>
+ {v.fromTake ? <span className="text-[var(--color-dim)]"> (from {v.fromTake})</span> : null}
+ </span>
+ ))}
+ . Their takes are in each card’s <span className="italic">Compare</span>.
+ </>
+ )}
+ </p>
+ )}
{panel}
</>
}
diff --git a/umtool/components/projects/bench/GapsZoom.tsx b/umtool/components/projects/bench/GapsZoom.tsx
@@ -5,6 +5,7 @@ import type { Peaks } from "@/components/Waveform";
import { buttonVariants } from "@/components/ui/button";
import { alpha, usePalette } from "@/components/ui/use-palette";
import { cn } from "@/lib/utils";
+import { pauseSpans } from "umtool-report-to-video/pauses";
import {
DETAIL_SPAN, ZOOM_STEP, centreOn, clampVis, isFit, panBy, quietPoints, rulerFor, tickLabel, wheelFactor, zoomAt, zoomTo,
} from "@/lib/report/benchZoom.mjs";
@@ -22,8 +23,11 @@ import {
// strip under it, which shows the whole cached window, what is
// shown in it, the selection and the gaps; a two-finger pinch on it.
// closer a ruler of round ticks, and at DETAIL_SPAN seconds or less the
-// measured silences (the cut-points route's, the build's own) and
-// the pauses between words, so a gap's edge goes between two words.
+// measured silences (the cut-points route's, the build's own), the
+// pauses (pauses.mjs pauseSpans: those silences and the gaps
+// between timed words, merged) as bands, and a box per WORD with
+// its text (a caption word's box runs to the next word's start),
+// so a gap's edge -- or a tightened edge -- goes between two words.
// gaps each a hatched band over the waveform, `cut` on it; a click on
// one removes it. A span for a new one is dragged with Alt held
// (or after `g` / Select a gap); Cut gap (or `g`) writes it.
@@ -193,7 +197,8 @@ export function GapLayer({
selection: Span | null;
picking: boolean;
silences: Span[] | null;
- words: { start: number; end: number }[] | null;
+ /** The recording's words (the clip-editor route's): timed (`end`), or a caption word's start only. */
+ words: { start: number; end?: number; w?: string }[] | null;
busy: boolean;
onRemove: (g: Span) => void;
onSelect: (s: Span, done: boolean) => void;
@@ -203,7 +208,14 @@ export function GapLayer({
const width = (a: number, b: number) => `calc(${pct(b)} - ${pct(a)})`;
const inView = (s: Span) => s.to > vis.from && s.from < vis.to;
const close = vis.to - vis.from <= DETAIL_SPAN;
- const quiet = close ? quietPoints({ words, silences }, vis.from, vis.to) : [];
+ const timed = (words ?? []).filter((w): w is { start: number; end: number; w?: string } => typeof w.end === "number");
+ const quiet = close ? quietPoints({ words: timed, silences }, vis.from, vis.to) : [];
+ const pauses = close ? pauseSpans({ words: timed, silences }, { from: vis.from, to: vis.to }) : [];
+ // A box per word in view: its own end, else (a caption's word) the next word's start, at most a second on.
+ const sorted = close ? [...(words ?? [])].sort((a, b) => a.start - b.start) : [];
+ const boxes = sorted
+ .map((w, i) => ({ text: w.w ?? "", from: w.start, to: typeof w.end === "number" ? w.end : Math.min(w.start + 1, sorted[i + 1]?.start ?? w.start + 1) }))
+ .filter((b) => b.to > b.from && inView(b));
const drag = useRef<{ id: number; at: number } | null>(null);
const tAt = (el: HTMLElement, clientX: number) => {
const r = el.getBoundingClientRect();
@@ -221,6 +233,28 @@ export function GapLayer({
style={{ left: pct(s.from), width: width(s.from, s.to) }}
/>
))}
+ {pauses.filter(inView).map((p) => (
+ <div
+ key={`pause-${p.from}`}
+ data-wave-pause={`${p.from.toFixed(2)}-${p.to.toFixed(2)}`}
+ aria-hidden
+ className="pointer-events-none absolute top-0 h-full bg-[color-mix(in_srgb,var(--color-meter)_10%,transparent)]"
+ style={{ left: pct(p.from), width: width(p.from, p.to) }}
+ />
+ ))}
+ {boxes.map((b) => (
+ <div
+ key={`word-${b.from}`}
+ data-wave-word={b.text}
+ data-wave-word-at={`${b.from.toFixed(2)}-${b.to.toFixed(2)}`}
+ title={`“${b.text}” ${b.from.toFixed(2)}–${b.to.toFixed(2)}`}
+ aria-hidden
+ className="pointer-events-none absolute top-0 h-3.5 overflow-hidden whitespace-nowrap rounded-sm border border-[color-mix(in_srgb,var(--color-text)_30%,transparent)] bg-[color-mix(in_srgb,var(--color-panel-2)_75%,transparent)] px-0.5 font-mono text-[9px] leading-3 text-[var(--color-text)]"
+ style={{ left: pct(b.from), width: width(b.from, b.to) }}
+ >
+ {b.text}
+ </div>
+ ))}
{quiet.map((t) => (
<div key={`q-${t}`} data-wave-quiet={t} aria-hidden className="pointer-events-none absolute top-0 h-full border-l border-dotted border-[color-mix(in_srgb,var(--color-meter)_55%,transparent)]" style={{ left: pct(t) }} />
))}
diff --git a/umtool/components/projects/bench/TightenTools.tsx b/umtool/components/projects/bench/TightenTools.tsx
@@ -0,0 +1,228 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { HOW_SAID, nearestPause, snapSaid, tightWindow } from "@/lib/report/tightWindow.mjs";
+
+// ---------------------------------------------------------------------------
+// TIGHTEN TO THE SENTENCE, SNAP AN EDGE TO A PAUSE (UI notes 2026-10-30, item
+// 4), on the bench's waveform tools. lib/report/tightWindow.mjs decides where
+// the edges go -- the sentence from the cues (sentenceEdges.mjs), the pause
+// from the measured silences and the words (report-to-video/pauses.mjs) --
+// and the edit is WRITTEN AT ONCE through the bench's one window writer
+// (`save`: PUT /api/report/window, the token, the cite that follows the edge),
+// like Extend and the gaps, with an Undo that writes back what was there.
+// ---------------------------------------------------------------------------
+
+export type BenchWord = { w?: string; start: number; end?: number };
+type Span = { from: number; to: number };
+type Cue = { start: number; end: number; text: string };
+
+type ClipEdges = {
+ id: string;
+ start: number;
+ end: number;
+ cutStart: number | null;
+ cutEnd: number | null;
+ muteFrom: number | null;
+ cite: number | null;
+ citeUrl: string | null;
+};
+
+/** The words of [from, to] on this clip's recording (the clip-editor route's, the bench's zoom asks the same). */
+export async function benchWords(project: string, clip: string, video: string, from: number, to: number): Promise<BenchWord[] | null> {
+ const q = new URLSearchParams({ project, clip, video, from: String(Math.max(0, Math.floor(from))), to: String(Math.ceil(to)) });
+ try {
+ const r = await fetch(`/api/report/clip-editor?${q}`, { cache: "no-store" });
+ if (!r.ok) return null;
+ const j = (await r.json()) as { words?: BenchWord[] | null };
+ return j.words ?? null;
+ } catch {
+ return null;
+ }
+}
+
+const r2 = (n: number) => Number(n.toFixed(2));
+const toWords = (ws: BenchWord[] | null) => (ws ?? []).map((w) => ({ start: w.start, ...(typeof w.end === "number" ? { end: w.end } : {}), text: w.w ?? "" }));
+
+/**
+ * Tighten / snap / undo, over the bench's state. `save` is the bench's queued
+ * writer (it re-syncs the clip, the selection and the token, and says when
+ * the cite followed); `lastSaved` its last answer.
+ */
+export function useEdgeTools({
+ project,
+ clip,
+ video,
+ sel,
+ playhead,
+ cues,
+ silences,
+ lo,
+ hi,
+ save,
+ lastSaved,
+ play,
+ setNote,
+}: {
+ project: string;
+ clip: ClipEdges;
+ video: string;
+ sel: Span;
+ playhead: number | null;
+ cues: Cue[];
+ silences: Span[] | null;
+ lo: number;
+ hi: number;
+ save: (patch: Record<string, unknown>) => Promise<boolean>;
+ lastSaved: React.MutableRefObject<Record<string, unknown> | null>;
+ play: (from: number, to: number) => unknown;
+ setNote: (s: string | null) => void;
+}) {
+ const [undo, setUndo] = useState<{ patch: Record<string, unknown>; what: string } | null>(null);
+ const [working, setWorking] = useState<string | null>(null);
+ // Another clip: nothing to undo here.
+ useEffect(() => setUndo(null), [clip.id]);
+
+ /** Write new edges through the window writer, the cut and the mute mark cleared when they no longer fit -- as Save window does. */
+ const writeEdges = useCallback(
+ async (next: Span, what: string, moved: "start" | "end" | "both") => {
+ const start = r2(next.from);
+ const end = r2(next.to);
+ const patch: Record<string, unknown> = { start, end };
+ const cleared: string[] = [];
+ if (clip.cutStart != null && clip.cutEnd != null && (clip.cutStart < start - 0.02 || clip.cutEnd > end + 0.02)) {
+ patch.cutStart = "";
+ patch.cutEnd = "";
+ cleared.push("the cut");
+ }
+ if (clip.muteFrom != null && (clip.muteFrom < start - 0.02 || clip.muteFrom > end + 0.02)) {
+ patch.muteFrom = "";
+ cleared.push("the mute mark");
+ }
+ const before = clip;
+ const ok = await save(patch);
+ if (!ok) return false;
+ const followed = (lastSaved.current?.citeFollowed ?? null) as { cite?: unknown; citeUrl?: unknown } | null;
+ const back: Record<string, unknown> = {
+ start: before.start,
+ end: before.end,
+ ...(patch.cutStart !== undefined ? { cutStart: before.cutStart ?? "", cutEnd: before.cutEnd ?? "" } : {}),
+ ...(patch.muteFrom !== undefined ? { muteFrom: before.muteFrom ?? "" } : {}),
+ // The cite and the QR went with the edge: they come back with it.
+ ...(followed?.cite ? { cite: before.cite ?? "" } : {}),
+ ...(followed?.citeUrl ? { citeUrl: before.citeUrl ?? "" } : {}),
+ };
+ setUndo({ patch: back, what });
+ setNote(
+ `${what}${cleared.length ? ` — ${cleared.join(" and ")} no longer fitted and ${cleared.length > 1 ? "were" : "was"} cleared` : ""}` +
+ `${followed?.cite ? " — the cite followed the edge" : followed?.citeUrl ? " — the QR's t= followed the edge" : ""} · Undo puts it back`,
+ );
+ // Hear what moved.
+ if (moved === "end") play(Math.max(start, end - 4), end);
+ else play(start, Math.min(end, start + 4));
+ return true;
+ },
+ [clip, save, lastSaved, play, setNote],
+ );
+
+ const tighten = useCallback(async () => {
+ setWorking("tighten");
+ try {
+ // tightWindow decides whether the playhead is a place (not parked on an edge).
+ const at = playhead;
+ const words = await benchWords(project, clip.id, video, sel.from - 12, sel.to + 12);
+ const r = tightWindow({
+ clip: { start: sel.from, end: sel.to, cutStart: clip.cutStart, cutEnd: clip.cutEnd },
+ cues,
+ words: toWords(words),
+ silences,
+ at,
+ lo,
+ hi,
+ });
+ if (!r.ok) {
+ setNote(`not tightened: ${r.why}`);
+ return;
+ }
+ const span = `${r.start.toFixed(2)}–${r.end.toFixed(2)} (${(r.end - r.start).toFixed(2)} s, was ${(sel.to - sel.from).toFixed(2)} s)`;
+ if (!r.changed) {
+ setNote(`already tight: ${HOW_SAID[r.how]} is ${span}`);
+ return;
+ }
+ await writeEdges({ from: r.start, to: r.end }, `tightened to ${HOW_SAID[r.how]}: ${span}${r.said.length ? ` — ${r.said.join("; ")}` : ""}`, "both");
+ } finally {
+ setWorking(null);
+ }
+ }, [playhead, sel, project, clip, video, cues, silences, lo, hi, writeEdges, setNote]);
+
+ const snap = useCallback(
+ async (edge: "start" | "end") => {
+ setWorking(edge);
+ try {
+ const t = edge === "start" ? sel.from : sel.to;
+ const words = await benchWords(project, clip.id, video, t - 3, t + 3);
+ const other = edge === "start" ? sel.to : sel.from;
+ const s = nearestPause(t, {
+ words: toWords(words),
+ silences,
+ lo: edge === "start" ? lo : other + 0.5,
+ hi: edge === "start" ? other - 0.5 : hi,
+ });
+ const said = snapSaid(edge, s) ?? "";
+ if (!s.moved) {
+ setNote(`not moved: ${said}${!silences?.length && !words?.length ? " — no silences measured and no words for this recording" : ""}`);
+ return;
+ }
+ await writeEdges(edge === "start" ? { from: s.at, to: sel.to } : { from: sel.from, to: s.at }, said, edge);
+ } finally {
+ setWorking(null);
+ }
+ },
+ [sel, project, clip.id, video, silences, lo, hi, writeEdges, setNote],
+ );
+
+ const undoEdges = useCallback(async () => {
+ const u = undo;
+ if (!u) return;
+ const ok = await save(u.patch);
+ if (!ok) return;
+ setUndo(null);
+ setNote(`undone — ${u.what.split(":")[0]} is reversed`);
+ }, [undo, save, setNote]);
+
+ return { tighten, snap, undoEdges, undo, working };
+}
+
+const btn = buttonVariants({ variant: "outline", size: "sm" });
+
+/** The buttons, in the waveform's tools row. */
+export function TightenButtons({ tools, busy }: { tools: ReturnType<typeof useEdgeTools>; busy: boolean }) {
+ const off = busy || !!tools.working;
+ return (
+ <span data-edge-tools="" className="flex flex-wrap items-center gap-1.5">
+ <button
+ type="button"
+ data-tighten=""
+ className={btn}
+ disabled={off}
+ title="both edges to the sentence at the playhead (else the cut's, else the whole sentences in the window), each into its pause — saved at once, Undo puts it back"
+ onClick={() => void tools.tighten()}
+ >
+ {tools.working === "tighten" ? "Tightening…" : "Tighten to this sentence"}
+ </button>
+ <span className="micro">snap edge to nearest pause</span>
+ <button type="button" data-snap-edge="start" className={btn} disabled={off} title="the start into the middle of the nearest pause (a silence, or between two words) — at most a second" onClick={() => void tools.snap("start")}>
+ ← start
+ </button>
+ <button type="button" data-snap-edge="end" className={btn} disabled={off} title="the end into the middle of the nearest pause — at most a second" onClick={() => void tools.snap("end")}>
+ end →
+ </button>
+ {tools.undo && (
+ <button type="button" data-edge-undo="" className={btn} disabled={off} title={`undo: ${tools.undo.what}`} onClick={() => void tools.undoEdges()}>
+ Undo
+ </button>
+ )}
+ </span>
+ );
+}
diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx
@@ -12,6 +12,7 @@ import { clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, p
import { readTrailerBeats } from "@/lib/report/trailerBeats.mjs";
import { montageClipsOf, momentKeysOf, readRulingsState } from "@/lib/report/montageRulings.mjs";
import FetchUnfetchedButton from "../FetchUnfetchedButton";
+import TightWindowsPanel from "./TightWindowsPanel";
import { clipRecord, storedUrlOf } from "@/lib/clips/stored";
import { Fragment } from "react";
import { deckOn } from "umtool-report-to-video/deck";
@@ -416,6 +417,8 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
/>
)}
{fetchBody && <FetchWindowsPanel project={project.id} items={fetchBody.items} skipped={fetchBody.skipped} lastRun={fetchBody.lastRun} />}
+ {/* Tight windows: each clip to its sentence, for review (UI notes item 4) -- a button until pressed. */}
+ {clips.length > 0 && <TightWindowsPanel project={project.id} />}
</div>
{/* --- the timeline --------------------------------------------- */}
diff --git a/umtool/components/projects/report/TightWindowsPanel.tsx b/umtool/components/projects/report/TightWindowsPanel.tsx
@@ -0,0 +1,256 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useCallback, useRef, useState } from "react";
+import { badgeVariants } from "@/components/ui/badge";
+import { buttonVariants } from "@/components/ui/button";
+import { clipBenchHref } from "@/lib/hrefs";
+
+// ---------------------------------------------------------------------------
+// PROPOSE TIGHT WINDOWS (UI notes 2026-10-30, item 4): every clip of the cut
+// tightened to its sentence and each edge into its pause
+// (lib/report/tightPropose.mjs, GET /api/report/tighten), as a review list --
+// before and after, the seconds either way, what moved and why. NOTHING
+// APPLIES WITHOUT A PRESS: each row's Apply is one window save (PUT
+// /api/report/window, the token, the cite that follows the edge), and an
+// applied row offers Undo, which writes back what was there.
+// ---------------------------------------------------------------------------
+
+type Edge = { start: number; end: number; seconds: number };
+type Row = {
+ id: string;
+ quote: string | null;
+ before: Edge;
+ after: Edge | null;
+ changed: boolean;
+ how: string | null;
+ said: string[];
+ why: string | null;
+ fetched: boolean;
+ locked: boolean;
+ words: string | null;
+ clear: { cut: boolean; mute: boolean };
+ prior: { cutStart: number | null; cutEnd: number | null; muteFrom: number | null; cite: number | null; citeUrl: string | null };
+};
+type Got = { token: string | null; rows: Row[]; counts: { clips: number; proposed: number; same: number; none: number } };
+type Applied = { k: "applying" } | { k: "applied"; undo: Record<string, unknown>; note: string } | { k: "undone" } | { k: "failed"; error: string };
+
+const hms = (t: number) => {
+ const s = Math.max(0, t);
+ const m = Math.floor(s / 60);
+ return `${m}:${(s - m * 60).toFixed(2).padStart(5, "0")}`;
+};
+const signed = (d: number) => `${d > 0 ? "+" : d < 0 ? "−" : "±"}${Math.abs(d).toFixed(2)} s`;
+
+export default function TightWindowsPanel({ project }: { project: string }) {
+ const router = useRouter();
+ const [got, setGot] = useState<Got | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [all, setAll] = useState(false);
+ const [done, setDone] = useState<Record<string, Applied>>({});
+ const token = useRef<string | null>(null);
+ // One write at a time: each reads the token the last one was handed back.
+ const chain = useRef<Promise<unknown>>(Promise.resolve());
+
+ const propose = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ const r = await fetch(`/api/report/tighten?${new URLSearchParams({ project })}`, { cache: "no-store" });
+ const j = (await r.json()) as Got & { error?: string };
+ if (!r.ok) {
+ setError(j.error ?? `HTTP ${r.status}`);
+ return;
+ }
+ token.current = j.token;
+ setGot(j);
+ setDone({});
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setLoading(false);
+ }
+ }, [project]);
+
+ const put = useCallback(
+ async (clip: string, patch: Record<string, unknown>) => {
+ const r = await fetch("/api/report/window", {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, clip, token: token.current, ...patch }),
+ });
+ const j = (await r.json().catch(() => ({}))) as Record<string, unknown>;
+ if (r.ok) token.current = String(j.token ?? "");
+ return { ok: r.ok, j };
+ },
+ [project],
+ );
+
+ const apply = useCallback(
+ (row: Row) => {
+ if (!row.after) return;
+ setDone((d) => ({ ...d, [row.id]: { k: "applying" } }));
+ const after = row.after;
+ const patch: Record<string, unknown> = {
+ start: after.start,
+ end: after.end,
+ ...(row.clear.cut ? { cutStart: "", cutEnd: "" } : {}),
+ ...(row.clear.mute ? { muteFrom: "" } : {}),
+ };
+ chain.current = chain.current.then(async () => {
+ const { ok, j } = await put(row.id, patch);
+ if (!ok) {
+ setDone((d) => ({
+ ...d,
+ [row.id]: { k: "failed", error: j.stale ? "the manifest changed since these were proposed — Propose again" : String(j.error ?? "refused") },
+ }));
+ return;
+ }
+ const before = row.prior;
+ const followed = (j.citeFollowed ?? null) as { cite?: { from: number; to: number }; citeUrl?: unknown } | null;
+ const undo: Record<string, unknown> = {
+ start: row.before.start,
+ end: row.before.end,
+ ...(row.clear.cut ? { cutStart: before.cutStart ?? "", cutEnd: before.cutEnd ?? "" } : {}),
+ ...(row.clear.mute ? { muteFrom: before.muteFrom ?? "" } : {}),
+ ...(followed?.cite ? { cite: before.cite ?? "" } : {}),
+ ...(followed?.citeUrl ? { citeUrl: before.citeUrl ?? "" } : {}),
+ };
+ const note = followed?.cite ? `the cite followed: ${hms(followed.cite.from)} → ${hms(followed.cite.to)}${followed.citeUrl ? ", and the QR" : ""}` : "";
+ setDone((d) => ({ ...d, [row.id]: { k: "applied", undo, note } }));
+ router.refresh();
+ });
+ },
+ [put, router],
+ );
+
+ const undo = useCallback(
+ (row: Row) => {
+ const s = done[row.id];
+ if (s?.k !== "applied") return;
+ setDone((d) => ({ ...d, [row.id]: { k: "applying" } }));
+ chain.current = chain.current.then(async () => {
+ const { ok, j } = await put(row.id, s.undo);
+ setDone((d) => ({ ...d, [row.id]: ok ? { k: "undone" } : { k: "failed", error: j.stale ? "the manifest changed since — Propose again" : String(j.error ?? "refused") } }));
+ if (ok) router.refresh();
+ });
+ },
+ [done, put, router],
+ );
+
+ const rows = got ? got.rows.filter((r) => all || r.changed) : [];
+ // Until it is pressed, one button among the Cut tab's tools (it adds nothing to the page's
+ // height); the review list then opens on a line of its own under them.
+ const button = (
+ <button
+ type="button"
+ data-action="propose-tight"
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ disabled={loading}
+ title="each clip to its sentence (the cut's, else the whole ones in its window), each edge into its pause — a list to review; nothing changes until you Apply a row"
+ onClick={() => void propose()}
+ >
+ {loading ? "Proposing…" : got ? "Propose again" : "Propose tight windows"}
+ </button>
+ );
+ if (!got && !error) return <span data-tight-windows="">{button}</span>;
+ return (
+ <section data-tight-windows={got ? got.counts.proposed : ""} className="basis-full rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <h2 className="micro">tight windows</h2>
+ {button}
+ {got && (
+ <span data-tight-counts="" className="text-[11.5px] text-[var(--color-dim)]">
+ {got.counts.proposed} of {got.counts.clips} clips would change · {got.counts.same} already tight
+ {got.counts.none ? ` · ${got.counts.none} with nothing to go by` : ""}
+ {" · "}
+ <button type="button" data-action="tight-show-all" aria-pressed={all} className="ink-link" onClick={() => setAll((v) => !v)}>
+ {all ? "only the changes" : "show every clip"}
+ </button>
+ </span>
+ )}
+ </div>
+ {error && (
+ <p role="alert" className="mt-1 text-[12px] text-reject-text">
+ {error}
+ </p>
+ )}
+ {got && rows.length === 0 && <p className="mt-1 text-[12px] text-[var(--color-dim)]">every clip is already tight</p>}
+ {rows.length > 0 && (
+ <ul className="mt-2 space-y-1.5" aria-label="proposed tight windows">
+ {rows.map((r) => {
+ const s = done[r.id];
+ const d = r.after ? r.after.seconds - r.before.seconds : 0;
+ return (
+ <li key={r.id} data-tight-row={r.id} data-tight-state={s?.k ?? (r.changed ? "proposed" : r.after ? "same" : "none")} className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5 text-[12px] leading-snug">
+ <Link href={clipBenchHref(project, r.id)} className="ink-link font-mono text-[11px]">
+ {r.id}
+ </Link>
+ <span className="num font-mono text-[11px] text-[var(--color-dim)]" data-tight-before={`${r.before.start}-${r.before.end}`}>
+ {hms(r.before.start)}–{hms(r.before.end)} ({r.before.seconds.toFixed(2)} s)
+ </span>
+ {r.after ? (
+ <>
+ <span aria-hidden>→</span>
+ <span className="num font-mono text-[11px]" data-tight-after={`${r.after.start}-${r.after.end}`}>
+ {hms(r.after.start)}–{hms(r.after.end)} ({r.after.seconds.toFixed(2)} s)
+ </span>
+ {r.changed && (
+ <span data-tight-delta={d.toFixed(2)} className={badgeVariants({ variant: d <= 0 ? "meter" : "state", size: "sm" })}>
+ {signed(d)}
+ </span>
+ )}
+ </>
+ ) : (
+ <span className="text-[var(--color-dim)]">{r.why}</span>
+ )}
+ {r.locked && <span className={badgeVariants({ variant: "state", size: "sm" })} title="locked against the widener (resolve-windows); Apply keeps the lock">locked</span>}
+ {!r.fetched && <span className={badgeVariants({ variant: "state", size: "sm" })} title="no cached window holds it: proposed from the cues and the words, no silences">not fetched</span>}
+ {r.clear.cut && <span className={badgeVariants({ variant: "state", size: "sm" })} title="the cut would no longer fit: Apply clears it">clears the cut</span>}
+ {r.changed && r.after && (
+ <span className="ml-auto flex items-center gap-1.5">
+ {s?.k === "applied" ? (
+ <>
+ <span data-tight-applied="" className="text-[11px] text-[var(--color-dim)]">
+ applied{s.note ? ` — ${s.note}` : ""}
+ </span>
+ <button type="button" data-action="tight-undo" className={buttonVariants({ variant: "outline", size: "sm" })} onClick={() => undo(r)}>
+ Undo
+ </button>
+ </>
+ ) : s?.k === "undone" ? (
+ <span className="text-[11px] text-[var(--color-dim)]">undone</span>
+ ) : (
+ <button type="button" data-action="tight-apply" className={buttonVariants({ size: "sm" })} disabled={s?.k === "applying"} onClick={() => apply(r)}>
+ {s?.k === "applying" ? "Applying…" : "Apply"}
+ </button>
+ )}
+ {s?.k === "failed" && (
+ <span role="alert" className="text-[11px] text-reject-text">
+ {s.error}
+ </span>
+ )}
+ </span>
+ )}
+ {(r.how || r.said.length > 0) && (
+ <span className="basis-full pl-6 text-[11px] text-[var(--color-dim)]">
+ {r.how}
+ {r.said.length ? ` — ${r.said.join("; ")}` : ""}
+ {r.words ? ` · words: ${r.words}` : ""}
+ </span>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ {got && (
+ <p className="mt-2 text-[11px] text-[var(--color-dim)]">
+ <code className="font-mono">umtool tighten {project}</code> prints the same list; <code className="font-mono">--apply <clip>[,…]</code> applies rows.
+ </p>
+ )}
+ </section>
+ );
+}
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -1057,6 +1057,7 @@ export default function PlayCut({
exp={clipExport}
clip={item?.clip ? item.id : null}
why={!item?.clip ? "a card is not a clip: nothing to export" : !entry?.media ? "its window is not fetched — fetch it first" : null}
+ around={item?.clip && typeof entry?.start === "number" && typeof entry?.end === "number" ? { start: entry.start, end: entry.end } : null}
/>
<ClipExportStatus exp={clipExport} />
</div>
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -26,6 +26,7 @@ Inbox cannot disagree about what is wrong with one.
| `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)) |
+| `tighten <project> [--json] [--all] [--no-measure]` · `tighten <project> --apply <clip>[,<clip>…]` | the Cut tab's **Propose tight windows**: each clip to its sentence (the sentences its cut touches, else the whole ones inside its window) and each edge into its pause (the build's measured silences and the gaps between the recording's timed words, ≤ 1 s, inside the cached window) — before → after with the seconds, the clips that would change (`--all`: every clip); prints only. `--apply` writes the named rows through the window writer (the token, the cite that follows the edge); a lock is kept (it is against `resolve-windows`, not a person) ([knobs.md](knobs.md#tighten-to-the-sentence-snap-to-a-pause)) |
| `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)) |
@@ -45,6 +46,7 @@ Inbox cannot disagree about what is wrong with one.
| `snapshot <project> [--label L]` | copy the manifest into `revisions/` |
| `diff <project> <snapshot>` | added / removed / moved / window / retyped, by entry id |
| `export <project> --format toc-bbcode\|toc-markdown\|description\|chapters [--variant V] [--first TITLE]` | the posting artifacts, from the build's chapter offsets. A deck with markers: `chapters` are its top-level sections (subsections left out) at the second each section's first segment starts, YouTube's rules kept (0:00 first, each ≥ 10 s, at least three; what was merged is said on stderr); the opening is titled `deck.sectionTitle.first`, or `--first TITLE`, else the first section takes 0:00 |
+| `export <project> <clip> [--take T] [--open] [--json]` · `--context N` · `--raw [--from S --to S]` · `--fetch` · `--progress ndjson` | **one clip, clean** (no deck) into `<project>/exports/` as `<clip>[-ctx<N>\|-raw[-<from>-<to>]]-<date>-<words>.mp4`: as the cut plays it (its edges, gaps out, its mute); `--context N` what the cut plays ± N s (1–120), as recorded; `--raw` the fetched window, or `--from/--to` a span (the full exchange), as recorded. In the heavy slot (a 600 MB estimate). `--fetch` asks the editor first (fetch-via-editor, the bench's path) for what a context or raw export needs that is not on disk; without it nothing is fetched. `--progress ndjson`: one `export` event (the app's export job reads it) ([knobs.md](knobs.md#export-one-clip)) |
| `check-sources [<project>…]` | **prints** the re-check chain; with no args, the never-checked and >30 d projects |
| `corrections <project>` | what the report got wrong (the clip bench's sixth field) and the walk's coverage, as markdown for the next pass |
| `chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]]` | an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything) |
@@ -56,7 +58,8 @@ Inbox cannot disagree about what is wrong with one.
| `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] [--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)) |
+| `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-cancel-delete-fork-as-variant-compare)) |
+| `takes cancel <project> <take> [--json]` · `takes fork <project> <take> [--name N] [--json]` · `takes compare <project> <a> <b> [--json]` | **take housekeeping, the rest**: **Cancel render** (asked of the process rendering it, which stops its render's process group, marks the take cancelled and lets render mode go; exit 1 when it has not stopped); **Fork as variant** (a project beside this one, default `v-<take>`: the take's manifest, `variant.json`, the parent's media and assets linked, the take in it); two takes **side by side** (`<take>` or `<project>:<take>`: the facts, the cut's changes A → B, the look's differences) ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare)) |
| `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--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, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), 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)) |
diff --git a/umtool/docs/clip-bench.md b/umtool/docs/clip-bench.md
@@ -250,6 +250,15 @@ mtime is in the URL: a request whose `v` matches is immutable for an hour, and o
whose `v` does not is served `no-store` rather than handing back the cut from
before the edit.
+## Export ▾ — the clip as a file
+
+The reader's footer has **Export clip** (the clip as the cut plays it), **raw** (the fetched window) and **Export ▾**:
+**As cut (no chrome)**, **With context** (N s either side of what the cut plays, as recorded) and **Raw / full
+exchange** (a from–to span of source seconds, starting at the clip's extent ± 30 s). Each is a umtool job in the heavy
+slot, named from the clip id and its date into the project's `exports/`; what context or a full exchange needs that is
+not on disk is fetched through the editor first, in the same job, and the line under the buttons says so while it
+does. Then Download (a phone's way) and Open folder ([knobs.md](knobs.md#export-one-clip)).
+
## Walking the cut
`p` and `n` (and the links in the header line) move to the previous and next
@@ -475,6 +484,20 @@ uploads of the same event are two clocks). The bench shows them three ways:
*"already in the cut as c03"*, so reading ahead answers "is this missing?"
rather than only "what is out there?".
+## Tighten to the sentence, snap an edge to a pause
+
+Under the waveform, beside the gaps: **Tighten to this sentence** moves both edges to the sentence at the playhead (a
+playhead still parked on the start, where the bench puts it on arrival, is not a place: then every sentence the cut
+touches, else the whole sentences inside the window, else the one it is inside), each edge then into its pause — the
+start back into the quiet before its first word, the end forward into the quiet after its last — and never past the
+cached window. **Snap edge to nearest pause** (**start** / **end**) moves one edge to the middle of the closest pause,
+at most a second away. Both are WRITTEN AT ONCE through the one window writer, like Extend and the gaps — the cite and
+the QR follow the edge, a cut or mute mark the window no longer holds is cleared and said — the moved edge is heard, and
+**Undo** writes back what was there (the edges, and the cut, the mute mark, the cite and the QR when they moved). The
+words and pauses the snap reads are drawn in the zoom: a box per word, the pauses as bands
+([knobs.md](knobs.md#tighten-to-the-sentence-snap-to-a-pause)). The whole cut at once is the Cut tab's **Propose tight
+windows**: a review list, before → after per clip, each row applied by its own **Apply**.
+
## The cue rail
Every cue in view, positioned by time. Inside the selection in full contrast,
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -60,6 +60,30 @@ it wrote. The CLI prints *cite followed the edge*, the route answers `citeFollow
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`).
+## Tighten to the sentence, snap to a pause
+
+What punchy tightening took by hand (silencedetect, en-orig word times read from a VTT) is two buttons on the bench and
+a review list on the Cut tab. Nothing new decides where a sentence or a pause is: the sentence is the phone walk's
+(`lib/report/sentenceEdges.mjs`, read off the cues), the pause is L1's (`report-to-video/pauses.mjs`: the build's
+measured silences, the cut-points route's, and the gaps between the recording's **timed** words — the corpus's
+`words.json`, a whisper `transcript.json`, else the en-orig captions' word starts, `report-to-video/clip-words.mjs`),
+composed in `lib/report/tightWindow.mjs`. Every write is the window writer's (`PUT /api/report/window`, the token, the
+cite and the QR that [follow the edge](#the-cite-follows-the-edge)); a cut or a mute mark the new window no longer holds
+is cleared in the same write, and said.
+
+| | In umtool | From a terminal | Route |
+|---|---|---|---|
+| both edges to the sentence: the one at the playhead (a playhead parked on an edge does not count), else every sentence the clip's cut (its quote) touches, else the whole sentences inside the window, else the one it is inside — then the start back into the pause before its first word and the end forward into the one after its last (0.1 s of quiet, ≤ 1 s away), inside the cached window | clip bench, under the waveform: **Tighten to this sentence**; **Undo** writes back the edges (and the cut, the mute mark, the cite, the QR) it moved | — | `PUT /api/report/window {project, clip, token, start, end}` |
+| one edge to the middle of its nearest pause (≤ 1 s) | **Snap edge to nearest pause**: **start** / **end**; **Undo** | — | same |
+| the words and the pauses, drawn | the bench's zoom, at 20 s or less shown: a box per word with its text (a caption word's box runs to the next word's start), the pauses as bands, the measured silences under them | — | `GET /api/report/clip-editor?project&clip&video&from&to` (`words`, `wordsFrom`, `timed`) |
+| every clip of the cut, proposed: before → after and the seconds either way, what moved and why; **nothing applies without a press** | the Cut tab's **Propose tight windows**: each row's **Apply**, then its **Undo**; **show every clip** lists the ones already tight | `umtool tighten <p> [--json] [--all] [--no-measure]` · `--apply <clip>[,<clip>…]` | `GET /api/report/tighten?project=<p>[&clip=…][&measure=0]`, each Apply a `PUT /api/report/window` |
+
+The batch has no playhead: the cut's sentences, else the whole ones in the window. A clip with nothing on disk is
+proposed from its cues and words (no silences) and says *not fetched*; one whose recording has no cues says so and is
+left. **A lock is not a refusal**: `lock`/`lockStart`/`lockEnd` pin an edge against `resolve-windows --write`, not
+against a person, so a locked clip is proposed like any other, its row says *locked*, and Apply keeps the lock. The batch
+is the project's cut; a take's clips are tightened on the take's bench (the take's patch, as every save there).
+
## Take patches follow a removal
A take patch beside the manifest (`*.patch.json`, the file `umtool take --patch` reads) that carries
@@ -139,8 +163,11 @@ second under it stays there; **−** / **+** / **Fit** / **Zoom to selection** (
selection); keys `z` in, `Z` out, `f` fit, `F` to the selection. Zoomed, the wheel pans (either axis), and an
**overview** strip under the waveform shows the whole cached window with what is shown, the selection and the gaps:
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.
+waveform; at 20 s across or closer it also draws the measured silences (the cut-points route's, the build's own), the
+pauses (those silences and the gaps between timed words, merged) as bands, and a box per word with its text — the
+project's words file when it is this recording's, else the corpus's (`words.json`, a whisper transcript, the en-orig
+captions' word starts: `report-to-video/clip-words.mjs`) — so a gap's edge, or a tightened one
+([below](#tighten-to-the-sentence-snap-to-a-pause)), goes between two words.
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)).
@@ -535,16 +562,19 @@ Then the cut: the Build tab's **final** preset (a full build, about an hour for
## Export one clip
-A clean mp4 of ONE clip, to post or hand on: the clip's footage as the cut plays it, with none of the deck — no rail,
-subtitles, QR, cards or stamps — written to the project's **`exports/`** (beside the hand-made ones) as
-`<clip>-<YYYY-MM-DD>-<slug>.mp4` (`<clip>-raw-…` for raw): the clip's date (its `date`, else the on-screen date, else
-the upload date; today with none) and the first words of its quote (else its title, else the video id). The same name
-again is written over.
+A clean mp4 of ONE clip, to post or hand on, with none of the deck — no rail, subtitles, QR, cards or stamps — written
+to the project's **`exports/`** (beside the hand-made ones) as `<clip>[-<kind>]-<YYYY-MM-DD>-<slug>.mp4`: the clip's
+date (its `date`, else the on-screen date, else the upload date; today with none) and the first words of its quote
+(else its title, else the video id). The kind is in the name — `-ctx<N>` with context, `-raw` for the fetched window,
+`-raw-<from>-<to>` for a span (the full exchange) — so the kinds never overwrite each other; the same export again is
+written over. Three kinds (UI notes 2026-10-30, item 12), the bench's and Play's **Export ▾**:
| | In umtool | From a terminal | Route |
|---|---|---|---|
-| the clip as the cut plays it | the clip bench's reader, **Export clip** (on a phone too); Play the cut, **Export clip** under the transport (the clip at the playhead) or a note's **Export <clip>** | `umtool export <p> <clip> [--take <t>] [--json]` | `POST /api/report/clip-export {project, clip, take?, kind?: "cut"}` |
-| the whole fetched window, as recorded | **raw** beside it | `umtool export <p> <clip> --raw` | `… {kind: "raw"}` |
+| **as cut (no chrome)**: the clip as the cut plays it | **Export clip**, or Export ▾ → **As cut (no chrome)** — the clip bench's reader (on a phone too); Play the cut under the transport (the clip at the playhead) or a note's **Export <clip>** | `umtool export <p> <clip> [--take <t>] [--json]` | `POST /api/report/clip-export {project, clip, take?, kind?: "cut"}` |
+| **with N s of context**: what the cut plays and N s either side (1–120, default 5), as recorded | Export ▾ → **With context**, the seconds beside it | `umtool export <p> <clip> --context N [--fetch]` | `… {kind: "context", context: N, fetch?: true}` |
+| **raw / full exchange**: a stretch of the recording as recorded — the clip and the fetch pad (**raw**), or a span of source seconds | **raw** beside Export clip; Export ▾ → **Raw / full exchange**, from–to (starting at the clip's extent ± 30 s) | `umtool export <p> <clip> --raw [--from S --to S] [--fetch]` | `… {kind: "raw", span?: {from, to}, fetch?: true}` |
+| the export's job | the status line under the buttons (*Fetching what it needs through the editor, then exporting…*, the job's last line), then the file | — | `GET /api/report/clip-export?job=<id>` → `{job, done?, error?}` |
| the file | **Download** (an attachment; the phone's way) | the path it prints | `GET /api/report/exports?project=<p>&name=<file>` (`GET …?project=<p>` lists them) |
| `exports/` in this machine's file manager, the file selected | **Open folder** | `--open` | `POST /api/report/exports {project, name?}` |
@@ -554,19 +584,30 @@ again is written over.
its **`gaps`** out as jump cuts on the frame grid with the build's 25 ms join fades, its sound **silenced** where the
cut silences it (`muteFrom`, a locked edge: `mute.mjs` soundOnSegment), its `audio` knobs (offset, gain, fades) and
the cut's loudness gain. Not applied: a blur (the export is unblurred, and says so), a montage's phrase cut.
-- **Raw**: the clip and the build's fetch pad either side (`render.fetchPad`, 3 s), clamped to the cached file — no
- gaps, no mute, no knobs.
+- **With context, and raw**: as recorded — no gaps, no mute, no knobs — from the tightest cached window of the
+ recording that **holds** the span (a wider fetch than the build's own source, often); where none does, clamped to
+ what is there and said (*the cached window ends 8.00 s before what was asked*).
+- **A umtool job, in the heavy slot.** Every export from the app is ONE job on the app's runner (`lib/jobs.ts`: one at
+ a time — a second job is a 409 naming the first — with a log and Stop): `umtool export … --progress ndjson`, which
+ takes the machine's heavy slot itself (`report-to-video/heavy-gate.mjs`) declaring a small estimate (600 MB), so it
+ runs beside others while memory allows and waits at the door in render mode. A terminal's `umtool export` takes the
+ same slot.
+- **Fetched if needed, through the editor.** A context or raw export whose span no cached window holds is refused —
+ *not on disk (−2 s / +14 s around the clip)* — unless asked with `fetch` (Export ▾ always asks, `--fetch` from a
+ terminal): then the same job first asks the editor for the window (`fetch-via-editor.mjs --fetch-only` with those
+ pads, the bench's own path: `POST /api/media/fetch-window`, paced, cookie-aware, provenanced; `UMTOOL_LOCAL_FETCH=1`
+ the pipeline's own), and cuts from what lands. A pad is at most 120 s either side of the clip's extent. **As cut**
+ fetches nothing: a clip whose window is not on disk is refused — "fetch it first" (the Cut tab's Fetch, `umtool
+ fetch <p>`); the buttons say so before you press them. On the bench the export is of the SAVED clip: save an edge
+ you moved first.
- **The encode**: cut on the input and re-encoded, so every cut is frame-exact — libx264 crf 18, yuv420p, AAC 192k,
- `+faststart`, no metadata or chapters. A few seconds for a short clip (≈10 s for 30 s of 720p); it does not take
- the heavy slot or the job runner, so it never waits behind a build. A second ask for the same file waits for the
- first.
-- **Nothing is fetched.** A clip whose window is not on disk is refused — "fetch it first" (the Cut tab's Fetch,
- `umtool fetch <p>`); the buttons say so before you press them. On the bench the export is of the SAVED clip: save an
- edge you moved first.
+ `+faststart`, no metadata or chapters. A few seconds for a short clip (≈10 s for 30 s of 720p).
- **Open folder** asks the desktop: `org.freedesktop.FileManager1.ShowItems` over the session bus (the file
selected), else `xdg-open <exports/>` on Linux; `open -R` on macOS. Refused, with the reason, inside a container,
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.
+- **No "send to phone".** Nothing in the repo sends a file to a phone (no share path, no pairing); **Download** from the
+ phone's browser is the way, and the option was left out rather than invented.
## The trailer's beats
@@ -592,20 +633,53 @@ length here ([report-video.md](report-video.md#trailer-from-the-master)).
| 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
+## Takes: relabel, supersede, cancel, delete, fork as variant, compare
| | 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?}` |
+| **cancel a take while it renders** — its render stopped, the take marked cancelled (`takes/<take>/cancelled.json`), render mode let go if it held it | **Cancel render** on the take's card (a rebuild) or on its *rendering now* row (a first render, which has no card yet) | `umtool takes cancel <p> <take> [--json]` | `{op: "cancel"}` → `{stopped, how, cancelled, renderMode, said}` |
+| delete `takes/<take>/` | **Delete take** (the plan first) — a cancelled first render too, under **show them** | `umtool takes delete <p> <take> [--dry-run] [--force]` | `POST /api/report/takes/delete {project, take, dryRun?, force?}` |
+| **fork as variant** — the take as a project beside this one (see below) | **Fork as variant** on the card (the name, default `v-<take>`), then a link to it and **compare** | `umtool takes fork <p> <take> [--name N] [--json]` | `{op: "fork", name?}` → `{id, take, links, copied, variant}` |
+| **compare two takes side by side** — of the project or of it and its variants | **Compare with…** on the card → `/projects/<p>/takes/compare?a=<project>:<take>&b=<project>:<take>`: two players in step (one transport: **Play both**, ±5 s, the seek bar; B pulled back to A past 0.15 s; **sound A / B**), then what differs | `umtool takes compare <p> <a> <b> [--json]` (`<take>` or `<project>:<take>`) | — (the page reads `lib/report/takeCompare.mjs`) |
**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
+`from` is that build's base. Relabel, delete and fork are refused for both (`force` does not pass it); a supersede mark is
not (no render writes verdicts.json).
+**Cancel is a request the take maker answers** (`lib/report/takeCancel.mjs`). The route writes `takes/<id>/.cancel.json`
+beside a live lock on this machine (refused, in words, for a take not rendering or rendering on another host); the take
+maker — the app's take job or a `umtool take` in a terminal, whichever holds the lock — polls for it, stops its render
+(the render runs in a process group of its own, `takeRender.mjs`: TERM to the whole group — queue-lock, build-video,
+every ffmpeg — then KILL after 8 s; a signal to the take process itself is passed on the same way), removes the
+half-made manifest, writes `cancelled.json` (`{at, by, label, rebuild}`) and exits; its build lock goes, and render mode
+with it when the take held it (`--priority`). The page waits for that (15 s), then — for the app's own job that did not
+answer — stops the job; render mode is released after a holder that went without letting go. A first render cancelled
+is a work dir with no take.json: the list folds it away (**N cancelled renders folded away · show them**), each with
+**Delete take**. A rebuild cancelled keeps its last take whole, its card marked **last render cancelled**. Made again,
+the take's mark is cleared.
+
+**A variant is a project beside its parent** (a narrative variant of the cut — not the encode ladder's variants of
+[Make variants](#make-variants-and-the-sync-report)) — as the hand copies were (`emberparadox/v-a-cold-open` …), because a
+project is a leaf of the walk and cannot sit inside one — so the walk, the cut, takes and Deliver all work on it
+unchanged. `lib/report/variantFork.mjs` writes: `video.manifest.json` (the take's — the one it was rendered from; a
+draft's resolved from its patch — its `slug` the variant's name), `variant.json` (`{variantOf, fromTake, takeLabel,
+forkedAt, baseHash}`), a README, `out/clips-raw` and `out/narration` as links to the parent's (the fetched media
+reused, never copied, as a take's out/ links them), a link to each of the parent's top-level files or folders the
+manifest names by a relative path (`shots/`, `posts-media/` …), `module-config.json` copied (a variant's modules are
+its own), and the take itself under `takes/<take>/` (its preview a hard link, its take.json a reference take of the
+variant's manifest, `forkedFrom` naming where it came from). Refused while the take renders, for a name that is not one
+path segment, or one already beside it. The parent's Takes page names its variants, a variant's its parent; **Compare
+with…** lists every take of the family.
+
+**What the compare lists** (`lib/report/takeCompare.mjs`): the facts side by side (project, take, label, length, clips,
+window, style, built — the ones that differ in full contrast); the cut's changes A → B (`manifest-diff.mjs`: entries
+added, removed, moved, their windows and other fields), one line each; and every leaf of the manifests outside the
+timeline that differs (`render.crf: 30 → 34`, `slug`, a title), at most 200.
+
## Make variants, and the sync report
| | In umtool | From a terminal | Route |
diff --git a/umtool/e2e/clip-export.spec.ts b/umtool/e2e/clip-export.spec.ts
@@ -21,6 +21,9 @@ const HERE = path.dirname(fileURLToPath(import.meta.url));
const FIXTURE = path.join(HERE, "..", ".e2e-song");
const PLAY = "reports/play-cut-fixture";
const WALK = "reports/phone-walk-fixture";
+const EXPORT = "reports/export-fixture";
+const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
+const SHOTS = process.env.U3_SHOTS ?? null;
const exportsOf = (project: string) => path.join(FIXTURE, ...project.split("/"), "exports");
const OPEN_LOG = path.join(FIXTURE, "open-folder.jsonl");
@@ -29,7 +32,7 @@ test.beforeEach(() => {
});
test.afterAll(() => {
- for (const p of [PLAY, WALK]) rmSync(exportsOf(p), { recursive: true, force: true });
+ for (const p of [PLAY, WALK, EXPORT]) rmSync(exportsOf(p), { recursive: true, force: true });
});
const ready = async (page: Page) => {
@@ -107,3 +110,49 @@ test("the bench on a phone: Export clip in the reader, then Download", async ({
expect(await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth)).toBeLessThanOrEqual(0);
await page.screenshot({ path: test.info().outputPath("bench-export-390.png") });
});
+
+test("Export ▾ on the bench: with N s of context, and the full exchange fetched through the editor first", async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ await page.goto(urls.clipBenchHref(EXPORT, "x01"));
+ await expect(page.locator('[data-bench="x01"]')).toHaveCount(1);
+ const menu = page.locator('[data-clip-export-menu="x01"]');
+ await menu.scrollIntoViewIfNeeded();
+ await expect(menu).toBeEnabled();
+ await menu.click();
+ const options = page.locator("[data-clip-export-options]");
+ await expect(options).toBeVisible();
+ await expect(options.locator('[data-clip-export-kind="cut"]')).toHaveText("As cut (no chrome)");
+ // The full exchange starts from the clip's extent ± 30 s (the recording starts at 0).
+ await expect(options.locator("[data-clip-export-from]")).toHaveValue("0");
+ await expect(options.locator("[data-clip-export-to]")).toHaveValue("36");
+ await page.screenshot({ path: test.info().outputPath("bench-export-menu.png") });
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "u3-3-export-menu.png") });
+
+ // With 2 s of context: the cached 0–9 window holds it, nothing is fetched.
+ await options.locator("[data-clip-export-context]").fill("2");
+ await options.locator('[data-clip-export-kind="context"]').click();
+ const state = page.locator("[data-clip-export-state]");
+ await expect(state).toHaveAttribute("data-clip-export-state", "ready", { timeout: 60_000 });
+ await expect(state).toHaveAttribute("data-clip-export-name", "x01-ctx2-2026-07-22-the-full-exchange.mp4");
+ await expect(state).toContainText("the cut with 2 s either side, as recorded");
+ expect(existsSync(path.join(exportsOf(EXPORT), "x01-ctx2-2026-07-22-the-full-exchange.mp4"))).toBe(true);
+
+ // A context the cache does not hold, asked without `fetch`: refused, with what it needs.
+ const no = await page.request.post("/api/report/clip-export", { data: { project: EXPORT, clip: "x01", kind: "context", context: 20 } });
+ expect(no.status()).toBe(409);
+ expect(((await no.json()) as { error: string }).error).toContain("not on disk");
+
+ // The full exchange, 0–20 s: past the cached 9 s, so the job asks the editor first (fetch-window), then cuts it.
+ await menu.click();
+ await options.locator("[data-clip-export-from]").fill("0");
+ await options.locator("[data-clip-export-to]").fill("20");
+ await options.locator('[data-clip-export-kind="raw"]').click();
+ await expect(state).toHaveAttribute("data-clip-export-name", "x01-raw-0-20-2026-07-22-the-full-exchange.mp4", { timeout: 90_000 });
+ await expect(state).toContainText("the span asked for, as recorded");
+ const asked = JSON.parse(readFileSync(STUB_LOG, "utf8")) as { videoId?: string; clipId?: string; from?: number; to?: number }[];
+ const fetchAsk = asked.filter((r) => r.videoId === "exportvid").at(-1);
+ expect(fetchAsk?.clipId).toBe("x01");
+ expect(fetchAsk?.from).toBe(0);
+ expect(fetchAsk?.to).toBe(20);
+ expect(existsSync(path.join(exportsOf(EXPORT), "x01-raw-0-20-2026-07-22-the-full-exchange.mp4"))).toBe(true);
+});
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -798,6 +798,14 @@ const CUES = {
// widen every vid1 cache -- and the phone walk asserts where its cache ENDS
// (a sentence past it is offered as a fetch). Source isolation, as vid3/vid4.
CUES.walk1 = CUES.vid1.map((r) => [...r]);
+// The tighten spec's source (tighten.spec.ts): vid1's words under a name of its own, with a
+// words.json sidecar of TIMED words written below -- what the bench's word boxes draw and what the
+// pause snap reads (report-to-video clip-words.mjs) -- laid on the tone window's silences
+// (2.9-3.1, 5.9-6.1).
+CUES.tightvid = CUES.vid1.map((r) => [...r]);
+// The clip-export spec's Export ▾ source (clip-export.spec.ts): a recording nothing else fetches, so
+// its full-exchange fetch (through the editor stub) moves no other spec's cache.
+CUES.exportvid = CUES.vid1.map((r) => [...r]);
for (const [vid, rows] of Object.entries(CUES)) {
const dir = path.join(CHANNELS, "testchan", "data", vid);
mkdirSync(dir, { recursive: true });
@@ -1489,6 +1497,17 @@ if (argv.includes("--version")) {
process.stdout.write("qrencode version 0.0.0-fixture\\n");
process.exit(0);
}
+// A RENDER IN PROGRESS, on demand (take-variants.spec.ts cancels one): while
+// <bin>/qrencode.stall-ms exists the stub records its pid beside it and sleeps
+// that long first -- a build that is plainly rendering, for as long as asked.
+{
+ const { existsSync, readFileSync, writeFileSync } = await import("node:fs");
+ const stall = ${JSON.stringify(path.join(BIN, "qrencode.stall-ms"))};
+ if (existsSync(stall)) {
+ writeFileSync(${JSON.stringify(path.join(BIN, "qrencode.stall.pid"))}, String(process.pid));
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Number(readFileSync(stall, "utf8")) || 0);
+ }
+}
const i = argv.indexOf("-o");
if (i < 0) process.exit(2);
const out = argv[i + 1];
@@ -1890,6 +1909,43 @@ makeCutEditingFixture({ reports, manifest, deckManifest, cachedWindow: path.join
mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "gapvid_0.00-9.00.mp4"));
}
+// Tighten to the sentence, snap an edge to its pause, and the batch's proposals (tighten.spec.ts),
+// which WRITES (the spec puts the manifest back before each test): its own project on tightvid
+// (vid1's cues; sentences 0-3, 3-9, 9-12), the tone window cached as tightvid_0.00-9.00.mp4, and
+// the recording's timed words in the corpus (data/tightvid/words.json).
+// t01 tightvid 1.2-7.4 both edges mid-sentence: tightens to the sentence 3-9 (bounded by the cache's 9)
+// t02 tightvid 3.0-9.0 already the sentence: already tight
+// t03 tightvid 0.5-8.6 a cut 3.5-5.0 inside it (the quote): the cut's sentence, 3-9
+{
+ const g = manifest("tight-fixture", "The Tight Fixture", { siteOrigin: "https://archive.example" }, [
+ { type: "clip", id: "t01", video: "tightvid", start: 1.2, end: 7.4, cite: 1, section: 0, quote: "and this one runs on and because" },
+ { type: "clip", id: "t02", video: "tightvid", start: 3.0, end: 9.0, cite: 3, section: 0, quote: "and this one runs on and because of that it finishes here" },
+ { type: "clip", id: "t03", video: "tightvid", start: 0.5, end: 8.6, cutStart: 3.5, cutEnd: 5.0, cite: 0, section: 0, quote: "runs on and because" },
+ ]);
+ g.render.fetchPad = 0;
+ const dir = writeProject("tight-fixture", g);
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "tightvid_0.00-9.00.mp4"));
+ const words = [
+ ["This", 0.2, 0.5], ["is", 0.55, 0.7], ["a", 0.75, 0.8], ["complete", 0.9, 1.6], ["sentence.", 1.7, 2.8],
+ ["And", 3.2, 3.5], ["this", 3.55, 3.8], ["one", 3.85, 4.1], ["runs", 4.15, 4.5], ["on", 4.55, 4.7], ["and", 4.75, 5], ["because", 5.1, 5.85],
+ ["of", 6.2, 6.4], ["that", 6.45, 6.8], ["it", 6.85, 7], ["finishes", 7.1, 7.9], ["here.", 8, 8.8],
+ ["Another", 9.2, 9.8], ["whole", 9.9, 10.3], ["sentence", 10.4, 11], ["entirely.", 11.1, 11.8],
+ ].map(([w, start, end]) => ({ w, start, end }));
+ writeFileSync(path.join(CHANNELS, "testchan", "data", "tightvid", "words.json"), JSON.stringify({ words }, null, 1));
+}
+// Export ▾ (clip-export.spec.ts, UI notes item 12): with context and the full exchange, which WRITES
+// exports/ and -- through the editor stub's fetch-window -- a wider window of exportvid in the corpus.
+// x01 exportvid 2.0-6.0, the tone window cached as exportvid_0.00-9.00.mp4
+{
+ const g = manifest("export-fixture", "The Export Fixture", { siteOrigin: "https://archive.example" }, [
+ { type: "clip", id: "x01", video: "exportvid", start: 2.0, end: 6.0, cite: 2, section: 0, date: "2026-07-22", quote: "the full exchange" },
+ ]);
+ g.render.fetchPad = 0;
+ const dir = writeProject("export-fixture", g);
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "exportvid_0.00-9.00.mp4"));
+}
// A clip fetched PER KEPT PIECE (pieced.spec.ts, fetch-per-piece): no window holds its extent, the
// pieces do. READ-ONLY (the spec writes nothing), so one project serves it.
// pc01 pcvid 1-98, gap 8-91 (83 s out): both pieces on disk -- raw windows 0-9 and 90-99
@@ -2158,6 +2214,36 @@ take("intro-a", { group: "opening", order: 5, label: "Cold open", kind: "similar
take("bad-kind", { group: "finale", order: 4, label: "Bad", kind: "maybe" });
mkdirSync(path.join(TAKES, "takes", "current", "out"), { recursive: true });
+// variants-fixture: take housekeeping, the rest (take-variants.spec.ts, UI notes item 19) -- Cancel a
+// take while it renders (a real render, held in the qrencode stub's stall), Fork as variant (a
+// project made beside it: v-draft-2, removed by the spec), two takes compared. WRITES takes/.
+// m01 vid1 3-6, its window cached; two takes rendered by hand:
+// draft-1 the manifest as it is (a 330 Hz preview)
+// draft-2 m01 tightened to 3.5-6, render.crf 34 (a 440 Hz preview)
+{
+ const base = manifest("variants-fixture", "The Variants Fixture", { siteOrigin: "https://archive.example" }, [
+ { type: "clip", id: "m01", video: "vid1", start: 3, end: 6, cite: 3, section: 0, lock: true, quote: "and because" },
+ ]);
+ const dir = writeProject("variants-fixture", base);
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "vid1_0.00-9.00.mp4"));
+ const tight = { ...base, render: { ...base.render, crf: 34 }, timeline: [{ ...base.timeline[0], start: 3.5 }] };
+ const vtake = (id, doc, m, hz) => {
+ const tdir = path.join(dir, "takes", id);
+ mkdirSync(tdir, { recursive: true });
+ writeFileSync(path.join(tdir, "take.json"), JSON.stringify({ id, preview: "preview.mp4", group: "drafts", kind: "different", seconds: 2, window: "full", ...doc }, null, 2));
+ writeFileSync(path.join(tdir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n");
+ ff([
+ "-f", "lavfi", "-i", "testsrc=size=320x180:rate=15:duration=2",
+ "-f", "lavfi", "-i", `sine=frequency=${hz}:duration=2`,
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", "-movflags", "+faststart",
+ path.join(tdir, "preview.mp4"),
+ ]);
+ };
+ vtake("draft-1", { order: 1, label: "draft 1", kind: "reference", builtAt: "2026-10-30T10:00:00Z" }, base, 330);
+ vtake("draft-2", { order: 2, label: "draft 2: tighter", builtAt: "2026-10-31T10:00:00Z", changes: ["m01 3.5-6 (was 3-6)", "render.crf: 34 (was 30)"] }, tight, 440);
+}
+
// takes-make-fixture: a project the take MAKER makes takes of (takes.spec.ts:
// New take -> the take appears -> Use this take). One clip, its window cached
// in out/clips-raw (the take links it, never fetches), no takes/ yet. Its own
diff --git a/umtool/e2e/take-variants.spec.ts b/umtool/e2e/take-variants.spec.ts
@@ -0,0 +1,163 @@
+import { test, expect, type Page } 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, the rest (UI notes 2026-10-30, item 19):
+//
+// - Cancel a take while it renders: a REAL render (the take maker's job,
+// `umtool take … --priority`), held in the qrencode stub's stall; Cancel
+// render on the Takes page asks the take maker, which stops its render's
+// process group, writes takes/<id>/cancelled.json, never a take.json, and
+// lets render mode go (lib/report/takeCancel.mjs)
+// - Fork as variant: the take as a project beside this one -- its manifest,
+// variant.json, the media linked, the take in it (variantFork.mjs)
+// - two takes side by side, of the project and of its variant: two players
+// in step, the differences listed (takeCompare.mjs, TakesComparePlayers)
+//
+// Fixture: variants-fixture (make-fixture.mjs), which this spec WRITES: m01
+// vid1 3-6; takes draft-1 (the manifest) and draft-2 (m01 3.5-6, crf 34).
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const SONG = path.join(HERE, "..", ".e2e-song");
+const PROJECT = "reports/variants-fixture";
+const DIR = path.join(SONG, "reports", "variants-fixture");
+const VARIANT_DIR = path.join(SONG, "reports", "v-draft-2");
+const STALL = path.join(SONG, "bin", "qrencode.stall-ms");
+const STALL_PID = path.join(SONG, "bin", "qrencode.stall.pid");
+const STATE = path.join(SONG, "render-priority.json");
+const SHOTS = process.env.U3_SHOTS ?? null;
+
+const shot = async (page: Page, name: string) => {
+ await page.screenshot({ path: test.info().outputPath(name) });
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, name) });
+};
+const alive = (pid: number) => {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+test.afterAll(() => {
+ rmSync(STALL, { force: true });
+ rmSync(VARIANT_DIR, { recursive: true, force: true });
+});
+
+test("two takes side by side: two players in step, and what differs A → B", async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ await page.goto(urls.takesCompareHref(PROJECT, `${PROJECT}:draft-1`, `${PROJECT}:draft-2`));
+ const players = page.locator("[data-compare-players]");
+ await expect(players.locator("[data-compare-player='a']")).toHaveAttribute("data-compare-take", `${PROJECT}:draft-1`);
+ await expect(players.locator("[data-compare-player='b']")).toHaveAttribute("data-compare-take", `${PROJECT}:draft-2`);
+ await expect(page.locator("[data-compare-cut]")).toContainText("~ m01 window: 3–6 -> 3.5–6");
+ await expect(page.locator("[data-compare-look-path='render.crf']")).toContainText("render.crf: 30 → 34");
+ await expect(page.locator("[data-compare-fact='label']")).toHaveAttribute("data-differs", "");
+ // Both play from one transport, and stay together.
+ await page.locator("[data-compare-play]").click();
+ await expect(players).toHaveAttribute("data-compare-state", "playing");
+ await expect.poll(async () => Number(await players.getAttribute("data-compare-time")), { timeout: 10_000 }).toBeGreaterThan(0.6);
+ const times = await page.locator("[data-compare-players] video").evaluateAll((vs) => (vs as HTMLVideoElement[]).map((v) => v.currentTime));
+ expect(times.length).toBe(2);
+ expect(Math.abs(times[0] - times[1])).toBeLessThan(0.3);
+ // One sound: A's, until B's is asked for.
+ const muted = () => page.locator("[data-compare-players] video").evaluateAll((vs) => (vs as HTMLVideoElement[]).map((v) => v.muted));
+ expect(await muted()).toEqual([false, true]);
+ await page.locator("[data-compare-sound='b']").click();
+ expect(await muted()).toEqual([true, false]);
+ await page.locator("[data-compare-play]").click();
+ await expect(players).toHaveAttribute("data-compare-state", "paused");
+});
+
+test("Fork as variant: a project beside this one, with the take in it; compared across the two", async ({ page }) => {
+ rmSync(VARIANT_DIR, { recursive: true, force: true });
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ await page.goto(urls.takesHref(PROJECT));
+ const card = page.locator("[data-take='draft-2']");
+ await card.locator("[data-action='fork']").click();
+ await expect(card.locator("[data-take-fork-name='draft-2']")).toHaveValue("v-draft-2");
+ await card.locator("[data-action='fork-go']").click();
+ await expect(card.locator("[data-take-forked='reports/v-draft-2']")).toBeVisible();
+ const variant = JSON.parse(readFileSync(path.join(VARIANT_DIR, "variant.json"), "utf8")) as { variantOf: string; fromTake: string };
+ expect(variant).toMatchObject({ variantOf: PROJECT, fromTake: "draft-2" });
+ const m = JSON.parse(readFileSync(path.join(VARIANT_DIR, "video.manifest.json"), "utf8")) as { slug: string; timeline: { start: number }[] };
+ expect(m.slug).toBe("v-draft-2");
+ expect(m.timeline[0].start).toBe(3.5);
+ expect(existsSync(path.join(VARIANT_DIR, "takes", "draft-2", "preview.mp4"))).toBe(true);
+
+ // The project's Takes page names its variant; the variant's names its parent.
+ await page.reload();
+ await expect(page.locator("[data-takes-variant='reports/v-draft-2']")).toBeVisible();
+ await page.goto(urls.takesHref("reports/v-draft-2"));
+ await expect(page.locator("[data-takes-family]")).toContainText(`A variant of ${PROJECT}, forked from its take draft-2`);
+
+ // Compare with…: the parent's draft-1 against the variant's draft-2.
+ await page.goto(urls.takesHref(PROJECT));
+ const one = page.locator("[data-take='draft-1']");
+ await one.locator("[data-take-compare-with='draft-1']").selectOption("reports/v-draft-2:draft-2");
+ await one.locator("[data-action='compare']").click();
+ await expect(page.locator("[data-compare-player='b']")).toHaveAttribute("data-compare-take", "reports/v-draft-2:draft-2");
+ await expect(page.locator("[data-compare-look-path='slug']")).toContainText("variants-fixture → v-draft-2");
+ await page.locator("[data-compare-play]").click();
+ await expect.poll(async () => Number(await page.locator("[data-compare-players]").getAttribute("data-compare-time")), { timeout: 10_000 }).toBeGreaterThan(0.5);
+ await page.locator("[data-compare-play]").click();
+ await shot(page, "u3-5-compare-side-by-side.png");
+});
+
+test("Cancel a take while it renders: its render stops, it is marked cancelled, render mode lets go", async ({ page, request }) => {
+ test.setTimeout(240_000);
+ rmSync(STATE, { force: true });
+ rmSync(STALL_PID, { force: true });
+ writeFileSync(STALL, "120000");
+ let id = "";
+ try {
+ // A real take, through the app's take job, with Give renders the machine.
+ const r = await request.post("/api/report/takes/make", { data: { project: PROJECT, take: { label: "Slow render", window: "full" }, priority: true } });
+ expect(r.status(), await r.text()).toBe(200);
+ const made = (await r.json()) as { takes: string[]; job: { id: string } };
+ id = made.takes[0];
+ // It is rendering: its build lock, render mode held for it, the stub stalled inside the build.
+ await expect.poll(() => existsSync(STALL_PID), { timeout: 120_000 }).toBe(true);
+ const stubPid = Number(readFileSync(STALL_PID, "utf8"));
+ expect(alive(stubPid)).toBe(true);
+ expect(existsSync(path.join(DIR, "takes", id, ".building.json"))).toBe(true);
+ expect((JSON.parse(readFileSync(STATE, "utf8")) as { holder?: { take?: string } }).holder?.take).toBe(id);
+
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ await page.goto(urls.takesHref(PROJECT));
+ const row = page.locator(`[data-take-rendering='${id}']`);
+ await expect(row).toContainText("Slow render");
+ await shot(page, "u3-4-cancel-rendering-take.png");
+ await row.locator("[data-action='cancel-render']").click();
+ // The answer stays on the page after the refresh takes the row away (it is not rendering any more).
+ await expect(page.locator(`[data-take-cancel-said='${id}']`)).toContainText("its render stopped (the take maker)", { timeout: 60_000 });
+
+ // Stopped cleanly: the render's process gone, no take.json, the mark, the lock gone, render mode off.
+ await expect.poll(() => alive(stubPid), { timeout: 15_000 }).toBe(false);
+ expect(existsSync(path.join(DIR, "takes", id, "take.json"))).toBe(false);
+ expect(JSON.parse(readFileSync(path.join(DIR, "takes", id, "cancelled.json"), "utf8"))).toMatchObject({ by: "the Takes page", label: "Slow render", rebuild: false });
+ expect(existsSync(path.join(DIR, "takes", id, ".building.json"))).toBe(false);
+ await expect.poll(() => existsSync(STATE), { timeout: 15_000 }).toBe(false);
+ await expect
+ .poll(async () => ((await (await request.get(`/api/report/takes/make?job=${made.job.id}`)).json()) as { state: string }).state, { timeout: 30_000 })
+ .toBe("failed");
+
+ // The list: no longer rendering; folded away as cancelled, deletable.
+ await expect(page.locator(`[data-take-rendering='${id}']`)).toHaveCount(0);
+ await shot(page, "u3-4b-cancelled.png");
+ await page.reload();
+ await expect(page.locator(`[data-take-rendering='${id}']`)).toHaveCount(0);
+ await expect(page.locator("[data-cancelled-count]")).toContainText("1 cancelled render folded away");
+ await page.locator("[data-action='show-cancelled']").click();
+ await expect(page.locator(`[data-take-cancelled='${id}']`)).toContainText("never finished: no take");
+ } finally {
+ rmSync(STALL, { force: true });
+ if (id) rmSync(path.join(DIR, "takes", id), { recursive: true, force: true });
+ rmSync(STATE, { force: true });
+ }
+});
diff --git a/umtool/e2e/tighten.spec.ts b/umtool/e2e/tighten.spec.ts
@@ -0,0 +1,126 @@
+import { test, expect, type Page } from "@playwright/test";
+import { readFileSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// Tighten to the sentence, snap an edge to its pause, and Propose tight
+// windows (UI notes 2026-10-30, item 4; lib/report/tightWindow.mjs,
+// tightPropose.mjs, components/projects/bench/TightenTools.tsx,
+// report/TightWindowsPanel.tsx):
+//
+// - the bench's zoom draws a box per WORD (the corpus's words.json for the
+// recording) and the pauses (the silences and the gaps between words)
+// - Tighten to this sentence writes both edges through the window writer,
+// Undo puts them back; Snap edge (start / end) moves one edge to the
+// middle of its nearest pause
+// - the Cut tab's Propose tight windows lists before/after per clip and
+// writes NOTHING until a row's Apply; an applied row's Undo restores it
+//
+// Fixture: tight-fixture (make-fixture.mjs), which this spec WRITES and puts
+// back before each test: t01 tightvid 1.2-7.4, t02 3.0-9.0 (already the
+// sentence), t03 0.5-8.6 with a cut 3.5-5.0; vid1's cues (sentences 0-3, 3-9,
+// 9-12), the tone window cached as 0-9, timed words in the corpus.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const PROJECT = "reports/tight-fixture";
+const MANIFEST = path.join(HERE, "..", ".e2e-song", "reports", "tight-fixture", "video.manifest.json");
+const SHOTS = process.env.U3_SHOTS ?? null;
+type Clip = { id: string; start: number; end: number; cutStart?: number; cutEnd?: number; cite?: number };
+const clipOf = (id: string) => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Clip[] }).timeline.find((e) => e.id === id)!;
+
+let PRISTINE = "";
+test.beforeAll(() => {
+ PRISTINE = readFileSync(MANIFEST, "utf8");
+});
+test.beforeEach(() => {
+ test.setTimeout(120_000);
+ writeFileSync(MANIFEST, PRISTINE);
+});
+
+const shot = async (page: Page, name: string) => {
+ await page.screenshot({ path: test.info().outputPath(name) });
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, name) });
+};
+
+const openBench = async (page: Page, clip = "t01") => {
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ await page.goto(urls.clipBenchHref(PROJECT, clip));
+ await page.locator("[data-wave-box]").scrollIntoViewIfNeeded();
+ await expect(page.locator("[data-wave-box]")).toBeInViewport();
+};
+
+test("the zoom draws the recording's words as boxes and its pauses", async ({ page }) => {
+ await openBench(page);
+ // A 9 s window is close enough at fit: the words and the pauses are drawn.
+ const word = page.locator("[data-wave-word='because']");
+ await expect(word).toHaveCount(1, { timeout: 20_000 });
+ await expect(word).toHaveAttribute("data-wave-word-at", "5.10-5.85");
+ expect(await page.locator("[data-wave-word]").count()).toBeGreaterThanOrEqual(10);
+ // The pause between "sentence." and "And" (the words' gap, 2.80-3.20, merged with the measured silence).
+ await expect(page.locator("[data-wave-pause]").first()).toBeAttached();
+ const pauses = await page.locator("[data-wave-pause]").evaluateAll((els) => els.map((e) => e.getAttribute("data-wave-pause")));
+ expect(pauses.some((p) => { const [a, b] = String(p).split("-").map(Number); return a <= 2.81 && b >= 3.19; })).toBe(true);
+ await page.locator("[data-zoom-in]").click();
+ await page.locator("[data-wave-box]").scrollIntoViewIfNeeded();
+ await expect(word).toBeVisible();
+ await shot(page, "u3-1-word-boxes-and-pauses.png");
+});
+
+test("Tighten to this sentence writes both edges through the window writer; Undo puts them back", async ({ page }) => {
+ await openBench(page);
+ await page.locator("[data-tighten]").click();
+ // No playhead: the window 1.2-7.4 holds no whole sentence, so the one it is inside (3-9), the end at the cache's 9.
+ await expect.poll(() => [clipOf("t01").start, clipOf("t01").end]).toEqual([3, 9]);
+ await expect(page.locator("body")).toContainText("tightened to the sentence the window is inside");
+ await page.locator("[data-edge-undo]").click();
+ await expect.poll(() => [clipOf("t01").start, clipOf("t01").end]).toEqual([1.2, 7.4]);
+ await expect(page.locator("body")).toContainText("undone");
+});
+
+test("Snap edge: the start, then the end, each to the middle of its nearest pause", async ({ page }) => {
+ await openBench(page);
+ await page.locator("[data-snap-edge='start']").click();
+ // 1.2 sits between "a" (…0.8) / "complete" (0.9…) and "complete" (…1.6) / "sentence." (1.7…): the nearer pause is 0.8-0.9.
+ await expect.poll(() => clipOf("t01").start).toBe(0.85);
+ await expect(page.locator("[data-edge-undo]")).toBeVisible();
+ await page.locator("[data-snap-edge='end']").click();
+ // 7.4: "it" (…7.0) / "finishes" (7.1…) is nearer than "finishes" (…7.9) / "here." (8.0…).
+ await expect.poll(() => clipOf("t01").end).toBe(7.05);
+ expect(clipOf("t01").start).toBe(0.85);
+});
+
+test("Propose tight windows: a review list, nothing written until Apply; Apply and Undo per row", async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 1100 });
+ await page.goto(urls.section(PROJECT, "cut"));
+ const panel = page.locator("[data-tight-windows]");
+ await panel.scrollIntoViewIfNeeded();
+ await panel.locator("[data-action='propose-tight']").click();
+ const t01 = panel.locator("[data-tight-row='t01']");
+ await expect(t01).toBeVisible({ timeout: 60_000 });
+ await expect(t01.locator("[data-tight-before]")).toHaveAttribute("data-tight-before", "1.2-7.4");
+ await expect(t01.locator("[data-tight-after]")).toHaveAttribute("data-tight-after", "3-9");
+ await expect(t01.locator("[data-tight-delta]")).toHaveAttribute("data-tight-delta", "-0.20");
+ // t03's cut (its quote, 3.5-5.0) anchors it: the sentence 3-9.
+ await expect(panel.locator("[data-tight-row='t03'] [data-tight-after]")).toHaveAttribute("data-tight-after", "3-9");
+ // t02 is already the sentence: not listed until every clip is shown.
+ await expect(panel.locator("[data-tight-row='t02']")).toHaveCount(0);
+ await expect(panel.locator("[data-tight-counts]")).toContainText("2 of 3 clips would change · 1 already tight");
+ // Proposing wrote nothing.
+ expect(readFileSync(MANIFEST, "utf8")).toBe(PRISTINE);
+ await shot(page, "u3-2-propose-tight-review.png");
+
+ await t01.locator("[data-action='tight-apply']").click();
+ await expect(t01).toHaveAttribute("data-tight-state", "applied");
+ await expect.poll(() => [clipOf("t01").start, clipOf("t01").end]).toEqual([3, 9]);
+ // Only that row: t03 is as it was.
+ expect([clipOf("t03").start, clipOf("t03").end]).toEqual([0.5, 8.6]);
+ await t01.locator("[data-action='tight-undo']").click();
+ await expect(t01).toHaveAttribute("data-tight-state", "undone");
+ await expect.poll(() => [clipOf("t01").start, clipOf("t01").end]).toEqual([1.2, 7.4]);
+
+ await panel.locator("[data-action='tight-show-all']").click();
+ await expect(panel.locator("[data-tight-row='t02']")).toHaveAttribute("data-tight-state", "same");
+});
diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts
@@ -301,6 +301,11 @@ export function takesHref(project: string, q: NoteOpt = {}): string {
return withQuery(`/projects/${encodePath(project)}/takes`, {}, q.note);
}
+/** Two takes side by side -- of the project or of its variants (`<project>:<take>` each). */
+export function takesCompareHref(project: string, a: string, b: string, q: NoteOpt = {}): string {
+ return withQuery(`/projects/${encodePath(project)}/takes/compare`, { a, b }, q.note);
+}
+
/**
* Walk a take: the take's clips, the walk's start (an overview of every clip,
* and where the walk begins). `all`: the walk visits every fetched clip, judged
diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs
@@ -25,7 +25,7 @@
import { readFile, stat } from "node:fs/promises";
import path from "node:path";
import { clipMomentKey } from "umtool-report-to-video/montage-rulings";
-import { channelFor, clipsOf, cuesInWindow, readManifest } from "../projects/report.mjs";
+import { channelFor, channelsDirFor, clipsOf, cuesInWindow, hasShadowChannels, readManifest } from "../projects/report.mjs";
import {
StaleToken,
StructureRefused,
@@ -263,7 +263,22 @@ const overlapping = (list, from, to) =>
export async function clipNeighbourhood(project, { clip, from, to, video = null }) {
if (!fin(from) || !fin(to) || to <= from) throw new Error("from and to must be seconds, from < to");
const { doc } = await readReactions(project.dir);
- const words = video && doc?.source?.video !== video ? null : await readWords(project.dir, doc);
+ let words = video && doc?.source?.video !== video ? null : await readWords(project.dir, doc);
+ // The bench, zoomed in, on a recording the project has no words file for:
+ // the corpus's words for it (report-to-video clip-words.mjs -- a words
+ // sidecar, a whisper transcript, else the en-orig captions' word starts),
+ // the same ones the trailer's pause snap reads. Never a cue spread by its
+ // characters: a box drawn there would be a made-up place.
+ let wordsFrom = words?.length ? "project" : null;
+ let timed = words?.length ? true : null;
+ if (video && !words?.length && clip) {
+ const corpus = await corpusWords(project.dir, clip, video, from, to).catch(() => null);
+ if (corpus?.words?.length) {
+ words = corpus.words.map((w) => ({ w: w.text, start: w.start, ...(fin(w.end) ? { end: w.end } : {}) }));
+ wordsFrom = corpus.from;
+ timed = corpus.timed;
+ }
+ }
const turns = overlapping(doc?.turns, from, to).map((t) => ({ start: t.start, end: t.end, speaker: t.speaker }));
const laughs = overlapping(doc?.laughs, from, to).map((l) => ({ start: l.start, end: l.end, score: fin(l.score) ? l.score : null, speaker: fin(l.speaker) ? l.speaker : null }));
let cues = null;
@@ -278,12 +293,33 @@ export async function clipNeighbourhood(project, { clip, from, to, video = null
to,
turns,
laughs,
- words: words?.length ? words.filter((w) => w.end >= from && w.start <= to).map((w) => ({ w: String(w.w ?? w.word ?? w.text ?? ""), start: w.start, end: w.end })) : null,
+ words: words?.length
+ ? words
+ .filter((w) => (fin(w.end) ? w.end : w.start) >= from && w.start <= to)
+ .map((w) => ({ w: String(w.w ?? w.word ?? w.text ?? ""), start: w.start, ...(fin(w.end) ? { end: w.end } : {}) }))
+ : null,
+ // Where the words came from (the project's words file, words.json /
+ // transcript.json / captions in the corpus), and whether they carry their
+ // ends (captions' words have only their starts).
+ ...(video ? { wordsFrom, timed } : {}),
cues,
duration,
};
}
+/**
+ * A recording's words from the corpus (clip-words.mjs), for the bench's zoom:
+ * the clip named, on THAT recording.
+ */
+async function corpusWords(dir, clipId, video, from, to) {
+ const manifest = await readManifest(dir);
+ const entry = clipsOf(manifest).find((e) => e.id === clipId);
+ if (!entry || entry.video !== video) return null;
+ const { clipWords } = await import("umtool-report-to-video/clip-words");
+ const channelsDir = channelsDirFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) });
+ return clipWords(entry, manifest.provenance, from, to, { channelsDir });
+}
+
/** The words of a span around one clip (for a quote), from words or cues. */
async function quoteFor(project, clipId, from, to) {
const n = await clipNeighbourhood(project, { clip: clipId, from: Math.max(0, from - 1), to: to + 1 }).catch(() => null);
diff --git a/umtool/lib/report/clipExport.mjs b/umtool/lib/report/clipExport.mjs
@@ -4,7 +4,8 @@
// `exports/`, where the operator keeps the hand-made ones
// (`exports/tr3-2026-08-12-deal-with-it-autogynephiliac.mp4`).
//
-// TWO KINDS.
+// THREE KINDS (UI notes 2026-10-30, item 12: "as cut (no chrome)", "with N s
+// context", "raw / full exchange (fetch if needed)").
//
// cut the clip as the cut plays it: the render's edges (cutPoints.mjs --
// the build's own source, snap and room; the muted room at an edge is
@@ -15,14 +16,26 @@
// its `audio` knobs (offset, gain, fades) and the cut's loudness gain.
// When the edges cannot be measured, the manifest's play window
// (noted). A blur, a montage's phrase cut and the deck are not applied.
-// raw the whole fetched window -- the clip and the build's fetch pad
-// either side, clamped to the file -- as recorded: no gaps, no mute,
-// no knobs.
+// context what the cut plays (its play window: the lead-in, the cut) with
+// N seconds either side (`context`, 1-120, default 5), as recorded: no
+// gaps, no mute, no knobs -- "what was said around it".
+// raw a stretch of the recording as recorded: `span` {from, to} in
+// source seconds (the full exchange), else the clip and the build's
+// fetch pad either side. No gaps, no mute, no knobs.
+//
+// Each cuts from a cached window that HOLDS what it asks for (the build's own
+// source for a cut; for context and raw the tightest window of the recording
+// holding the span), clamped to the file and said when none does.
+// `exportNeeds` says what a context or raw export needs that is not on disk,
+// as the pads the editor's fetch-window takes (POST /api/report/clip-export
+// with `fetch: true` runs that fetch first, in the same job).
//
// Re-encoded, never stream-copied, so every cut is on the asked-for frame:
-// libx264 crf 18, AAC 192k, +faststart. Light work (one short clip), so it
-// does not take the heavy slot. Nothing is fetched: a clip with no window on
-// disk is refused with "fetch it first".
+// libx264 crf 18, AAC 192k, +faststart. Run as a umtool job (the route) or
+// from a terminal (`umtool export`), and either way through the machine's
+// heavy slot (the CLI takes it: report-to-video/heavy-gate.mjs, a small
+// declared estimate, so it runs beside others when memory allows). Nothing is
+// fetched here: a cut with no window on disk is refused with "fetch it first".
//
// The pure half (names, the plan's ffmpeg arguments) is tested in
// clipExport.test.mjs; `exportClip` runs it.
@@ -36,8 +49,12 @@ import { AUDIO_ON_CLOCK, clipAudioFilters, clipAudioOf, offsetWindow } from "umt
/** The folder under a project that exports go into. */
export const EXPORTS_DIR = "exports";
-/** The two kinds of export. */
-export const EXPORT_KINDS = Object.freeze(["cut", "raw"]);
+/** The kinds of export. */
+export const EXPORT_KINDS = Object.freeze(["cut", "context", "raw"]);
+/** Seconds of context either side (the `context` kind): the default, and the bounds (the editor's fetch pad cap). */
+export const EXPORT_CONTEXT = Object.freeze({ default: 5, min: 1, max: 120 });
+/** What an export declares to the heavy slot (MB): one short re-encode. */
+export const EXPORT_ESTIMATE_MB = 600;
/** What a name under exports/ may be: one plain file name, an mp4. */
export const EXPORT_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,180}\.mp4$/;
@@ -94,26 +111,79 @@ export function exportDate(entry) {
}
/**
- * The export's file name: `<clipId>[-raw]-<YYYY-MM-DD>-<slug>.mp4`, the
- * shape of the hand-made ones (`ss1-raw-2026-07-22-side-scrollers-full-exchange.mp4`).
+ * The export's file name: `<clipId>[-ctx<N> | -raw[-<from>-<to>]]-<YYYY-MM-DD>-<slug>.mp4`,
+ * the shape of the hand-made ones (`ss1-raw-2026-07-22-side-scrollers-full-exchange.mp4`).
* The slug is the quote's first words, else the title's, else the video id;
- * the date the clip's, else `today` (YYYY-MM-DD).
+ * the date the clip's, else `today` (YYYY-MM-DD). A raw export of a span of
+ * its own (the full exchange) carries the span's whole seconds, so two
+ * exchanges of one clip are two files.
*
* @param {Record<string, any>} entry
- * @param {{ kind?: "cut" | "raw", today?: string }} [opts]
+ * @param {{ kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null, today?: string }} [opts]
*/
-export function exportName(entry, { kind = "cut", today = new Date().toISOString().slice(0, 10) } = {}) {
+export function exportName(entry, { kind = "cut", context = EXPORT_CONTEXT.default, span = null, today = new Date().toISOString().slice(0, 10) } = {}) {
const id = exportSlug(String(entry?.id ?? "clip"), { words: 8, max: 40 }) || "clip";
const date = exportDate(entry) ?? today;
const slug = exportSlug(entry?.quote) || exportSlug(entry?.onscreen?.title) || exportSlug(entry?.title) || exportSlug(entry?.video);
- return `${[id, kind === "raw" ? "raw" : null, date, slug || null].filter(Boolean).join("-")}.mp4`;
+ const tag =
+ kind === "raw"
+ ? span && fin(span.from) && fin(span.to)
+ ? `raw-${Math.floor(span.from)}-${Math.ceil(span.to)}`
+ : "raw"
+ : kind === "context"
+ ? `ctx${Math.round(context)}`
+ : null;
+ return `${[id, tag, date, slug || null].filter(Boolean).join("-")}.mp4`;
+}
+
+/** `context` as seconds inside EXPORT_CONTEXT's bounds, or an error naming them. */
+export function contextSeconds(v) {
+ if (v === undefined || v === null || v === "") return EXPORT_CONTEXT.default;
+ const n = Number(v);
+ if (!Number.isFinite(n) || n < EXPORT_CONTEXT.min || n > EXPORT_CONTEXT.max) {
+ throw new ExportRefused(`context is ${EXPORT_CONTEXT.min}–${EXPORT_CONTEXT.max} seconds either side (got ${String(v)})`, 400);
+ }
+ return Math.round(n * 10) / 10;
+}
+
+/** A raw export's span `{from, to}` (source seconds), checked; null when none is asked for. */
+export function spanOf(v) {
+ if (v === undefined || v === null) return null;
+ const from = Number(v?.from);
+ const to = Number(v?.to);
+ if (!Number.isFinite(from) || !Number.isFinite(to) || from < 0 || to - from < 0.5) {
+ throw new ExportRefused("a raw span is {from, to}: source seconds, from ≥ 0, at least half a second", 400);
+ }
+ if (to - from > 1800) throw new ExportRefused("a raw span is at most 30 minutes", 400);
+ return { from: Math.round(from * 100) / 100, to: Math.round(to * 100) / 100 };
+}
+
+/**
+ * The SOURCE seconds an export asks for, before the file clamps it: a cut's
+ * is its play window (the render may snap it a second either way), a context
+ * export's that ± N, a raw one's its span or the clip ± the fetch pad.
+ *
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} render
+ * @param {{ kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null }} opts
+ */
+export function exportSpan(entry, render, { kind = "cut", context = EXPORT_CONTEXT.default, span = null } = {}) {
+ if (kind === "raw") {
+ if (span) return { from: span.from, to: span.to };
+ const pad = fin(render?.fetchPad) ? render.fetchPad : 3;
+ return { from: Math.max(0, entry.start - pad), to: entry.end + pad };
+ }
+ const pw = playEdges(entry, render ?? {});
+ if (kind === "context") return { from: Math.max(0, pw.from - context), to: pw.to + context };
+ return { from: pw.from, to: pw.to };
}
/**
* What one export cuts, in SOURCE seconds -- the arithmetic, no I/O.
*
* @typedef {{
- * kind: "cut" | "raw",
+ * kind: "cut" | "context" | "raw",
+ * context?: number, span?: { from: number, to: number },
* file: string, fetchStart: number, duration?: number | null, hasVideo?: boolean,
* from: number, to: number,
* gaps: Array<{ from: number, to: number }>,
@@ -133,10 +203,11 @@ export function exportName(entry, { kind = "cut", today = new Date().toISOString
* (cutPoints.mjs; null or an errored row falls back to the manifest's edges).
*
* @param {{ entry: Record<string, any>, render?: Record<string, any>, source: { path: string, fetchStart: number },
- * media?: { duration?: number | null, hasVideo?: boolean }, row?: Record<string, any> | null, kind?: "cut" | "raw" }} o
+ * media?: { duration?: number | null, hasVideo?: boolean }, row?: Record<string, any> | null, kind?: "cut" | "context" | "raw",
+ * context?: number, span?: { from: number, to: number } | null }} o
* @returns {ExportPlan}
*/
-export function planExport({ entry, render = {}, source, media = {}, row = null, kind = "cut" }) {
+export function planExport({ entry, render = {}, source, media = {}, row = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null }) {
const fps = fin(render.fps) && render.fps > 0 ? render.fps : 30;
const fileFrom = source.fetchStart;
const fileTo = fin(media.duration) ? source.fetchStart + /** @type {number} */ (media.duration) : Infinity;
@@ -145,11 +216,23 @@ export function planExport({ entry, render = {}, source, media = {}, row = null,
kind, file: source.path, fetchStart: source.fetchStart, duration: media.duration ?? null,
hasVideo: media.hasVideo !== false, fps, notes,
};
- if (kind === "raw") {
- const pad = fin(render.fetchPad) ? render.fetchPad : 3;
- const from = Math.max(fileFrom, Math.max(0, entry.start - pad));
- const to = Math.min(fileTo, entry.end + pad);
- return { ...base, from, to, gaps: [], mute: null, soundFrom: null, audio: null, gainDb: null, edges: "window" };
+ if (kind === "raw" || kind === "context") {
+ // As recorded: the span asked for (raw: the full exchange, else the clip
+ // and the fetch pad; context: what the cut plays ± N -- the render's
+ // edges when measured), clamped to the file and said.
+ let want = exportSpan(entry, render, { kind, context, span });
+ if (kind === "context" && row && !row.missing && !row.error && fin(row.cutStart) && fin(row.cutEnd)) {
+ want = { from: Math.max(0, row.cutStart - context), to: row.cutEnd + context };
+ }
+ let from = Math.max(fileFrom, want.from);
+ let to = Math.min(fileTo, want.to);
+ if (want.from < fileFrom - 0.05) notes.push(`the cached window starts ${(fileFrom - want.from).toFixed(2)} s after what was asked: from its first frame`);
+ if (want.to > fileTo + 0.05) notes.push(`the cached window ends ${(want.to - fileTo).toFixed(2)} s before what was asked: to its last frame`);
+ if (to < from) to = from;
+ return {
+ ...base, from, to, gaps: [], mute: null, soundFrom: null, audio: null, gainDb: null, edges: "window",
+ ...(kind === "context" ? { context } : {}), ...(kind === "raw" && span ? { span } : {}),
+ };
}
let from;
let to;
@@ -249,7 +332,15 @@ export function planSummary(plan) {
if (plan.mute != null) parts.push(`muted from ${n3(plan.mute)} s`);
if (plan.soundFrom != null) parts.push(`sound from ${n3(plan.soundFrom)} s`);
parts.push(`${n3(planSeconds(plan))} s`);
- parts.push(plan.kind === "raw" ? "the whole window" : plan.edges === "render" ? "the render's edges" : "the manifest's edges");
+ parts.push(
+ plan.kind === "raw"
+ ? plan.span ? "the span asked for, as recorded" : "the whole window"
+ : plan.kind === "context"
+ ? `the cut with ${plan.context ?? EXPORT_CONTEXT.default} s either side, as recorded`
+ : plan.edges === "render"
+ ? "the render's edges"
+ : "the manifest's edges",
+ );
return parts.join(" · ");
}
@@ -285,29 +376,72 @@ export class ExportRefused extends Error {
const inflight = new Map();
/**
+ * What a context or raw export of this clip asks for, and whether a cached
+ * window holds it: `{ entry, want, held, padBefore, padAfter }`, the pads as
+ * the editor's fetch-window takes them (from the clip's extent, whole
+ * seconds, at most EXPORT_CONTEXT.max). A cut asks for what its own source
+ * holds (`held` is whether there is one).
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {string} clipId
+ * @param {{ take?: string | null, kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null }} [opts]
+ */
+export async function exportNeeds(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null } = {}) {
+ const { clipSourceOf } = await import("./cutPoints.mjs");
+ const got = await clipSourceOf(project, clipId, { take });
+ if (!got.entry) throw new ExportRefused(`no clip ${clipId} in ${take ? `take ${take} of ` : ""}${project.id}`, 404);
+ const e = got.entry;
+ if (kind === "cut") return { entry: e, want: null, held: !!got.source, padBefore: 0, padAfter: 0 };
+ const want = exportSpan(e, got.render, { kind, context, span });
+ const held = !!(await heldWindow(project, e, want));
+ const pad = (v) => Math.min(EXPORT_CONTEXT.max, Math.max(0, Math.ceil(v)));
+ return { entry: e, want, held, padBefore: pad(e.start - want.from), padAfter: pad(want.to - e.end) };
+}
+
+/** The tightest cached window of the clip's recording holding [want.from, want.to] (projectCache: out/clips-raw and the corpus's windows). */
+async function heldWindow(project, entry, want) {
+ const { projectCache } = await import("./serve.mjs");
+ const cache = await projectCache(project);
+ return cache.containing(entry.video, want.from + 0.02, want.to - 0.02) ?? null;
+}
+
+/**
* Export one clip of a project's cut (or of a take) into `<project>/exports/`.
*
* @param {{ id: string, dir: string }} project
* @param {string} clipId
- * @param {{ take?: string | null, kind?: "cut" | "raw", ffmpeg?: string, today?: string }} [opts]
- * @returns {Promise<{ project: string, clip: string, take: string | null, kind: "cut" | "raw", name: string, rel: string,
+ * @param {{ take?: string | null, kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null,
+ * ffmpeg?: string, today?: string }} [opts]
+ * @returns {Promise<{ project: string, clip: string, take: string | null, kind: "cut" | "context" | "raw", name: string, rel: string,
* abs: string, size: number, mtimeMs: number, seconds: number, summary: string, notes: string[], plan: ExportPlan }>}
*/
-export async function exportClip(project, clipId, { take = null, kind = "cut", ffmpeg, today } = {}) {
+export async function exportClip(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null, ffmpeg, today } = {}) {
if (!EXPORT_KINDS.includes(kind)) throw new ExportRefused(`an export is one of ${EXPORT_KINDS.join(", ")}`, 400);
+ const ctx = kind === "context" ? contextSeconds(context) : EXPORT_CONTEXT.default;
+ const sp = kind === "raw" ? spanOf(span) : null;
const { clipSourceOf, cutPointsFor } = await import("./cutPoints.mjs");
- const { FFMPEG_BIN, probeMedia } = await import("umtool-report-to-video/build-video");
+ const { FFMPEG_BIN, alignedClipSource, probeMedia } = await import("umtool-report-to-video/build-video");
const got = await clipSourceOf(project, clipId, { take });
if (!got.entry) throw new ExportRefused(`no clip ${clipId} in ${take ? `take ${take} of ` : ""}${project.id}`, 404);
- if (!got.source) {
+ // A context or raw export is cut from the window that holds what it asks for -- a wider fetch
+ // than the build's own source, often (the full exchange) -- when there is one.
+ /** @type {{ path: string, fetchStart: number, pieced?: { entry: Record<string, any> } } | null} */
+ let source = got.source;
+ if (kind !== "cut") {
+ const want = exportSpan(got.entry, got.render, { kind, context: ctx, span: sp });
+ const win = await heldWindow(project, got.entry, want);
+ if (win) source = await alignedClipSource({ path: win.path, fetchStart: win.from }).then((x) => ({ path: x.path, fetchStart: x.fetchStart }), () => ({ path: win.path, fetchStart: win.from }));
+ }
+ if (!source) {
throw new ExportRefused(
- `${clipId}: its window is not on disk — fetch it first (the Cut tab's Fetch, or \`umtool fetch ${project.id}\`)`,
+ `${clipId}: its window is not on disk — fetch it first (the Cut tab's Fetch, or \`umtool fetch ${project.id}\`)` +
+ (kind === "cut" ? "" : `; \`umtool export ${project.id} ${clipId} … --fetch\` asks the editor for what this export needs`),
409,
);
}
- const media = await probeMedia(got.source.path).catch(() => ({ hasVideo: true, duration: null }));
+ const media = await probeMedia(source.path).catch(() => ({ hasVideo: true, duration: null }));
let row = null;
- if (kind === "cut") {
+ if (kind === "cut" || kind === "context") {
try {
row = (await cutPointsFor(project, { take, clips: [clipId] })).clips?.[0] ?? null;
} catch (e) {
@@ -316,13 +450,13 @@ export async function exportClip(project, clipId, { take = null, kind = "cut", f
}
// A clip cut from its pieces (cutPoints.mjs piecedDiskSourceOf) is a file on its own clock:
// the plan is made on that clock -- the clip and the cut's numbers as the build sees them.
- const pieced = got.source.pieced ?? null;
+ const pieced = source.pieced ?? null;
const planRow = pieced && row && !row.error && !row.missing && row.pieced
? { ...row, cutStart: row.pieced.cutStart, cutEnd: row.pieced.cutEnd, gaps: row.pieced.gaps }
: row;
- const plan = planExport({ entry: pieced ? pieced.entry : got.entry, render: got.render, source: got.source, media, row: planRow, kind });
+ const plan = planExport({ entry: pieced ? pieced.entry : got.entry, render: got.render, source, media, row: planRow, kind, context: ctx, span: sp });
if (!(planSeconds(plan) > 0.05)) throw new ExportRefused(`${clipId}: nothing to export (${planSummary(plan)})`, 422);
- const name = exportName(got.entry, { kind, ...(today ? { today } : {}) });
+ const name = exportName(got.entry, { kind, context: ctx, span: sp, ...(today ? { today } : {}) });
const dir = path.join(/* turbopackIgnore: true */ project.dir, EXPORTS_DIR);
const abs = path.join(/* turbopackIgnore: true */ dir, name);
const run = inflight.get(abs) ?? (async () => {
@@ -350,6 +484,37 @@ export async function exportClip(project, clipId, { take = null, kind = "cut", f
}
/**
+ * The job that makes an export (the route's): the editor's fetch first when
+ * `fetch` names the pads a context or raw export still needs (driver.mjs
+ * editorFetchSteps, the bench's own; fetchSteps under UMTOOL_LOCAL_FETCH=1),
+ * then `umtool export … --progress ndjson`, which takes the heavy slot itself
+ * and ends with one `export` event.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {string} clipId
+ * @param {{ take?: string | null, kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null,
+ * fetch?: { padBefore: number, padAfter: number } | null, manifestPath?: string | null }} o
+ */
+export async function exportSteps(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null, fetch = null, manifestPath = null } = {}) {
+ const { UMTOOL_DIR, editorFetchSteps, fetchSteps, localFetch } = await import("./driver.mjs");
+ const steps = [];
+ if (fetch) {
+ const pads = { padBefore: fetch.padBefore, padAfter: fetch.padAfter };
+ steps.push(...(localFetch() ? fetchSteps(project, clipId, pads, { manifestPath }) : editorFetchSteps(project, clipId, pads, { manifestPath })));
+ }
+ const kindArgs = kind === "context" ? ["--context", String(context)] : kind === "raw" ? ["--raw", ...(span ? ["--from", String(span.from), "--to", String(span.to)] : [])] : [];
+ steps.push({
+ cwd: UMTOOL_DIR,
+ env: {},
+ label: `export ${clipId}${kind === "context" ? ` with ${context} s either side` : kind === "raw" ? (span ? ` ${span.from}–${span.to} s, as recorded` : " raw") : ""}`,
+ argv: [process.execPath, path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"), "export", project.id, clipId, ...kindArgs, ...(take ? ["--take", take] : []), "--progress", "ndjson"],
+ ndjson: true,
+ timeoutMs: 15 * 60_000,
+ });
+ return steps;
+}
+
+/**
* The exports a project holds, newest first: `{name, size, mtimeMs}`.
*
* @param {string} projectDir
diff --git a/umtool/lib/report/clipExport.test.mjs b/umtool/lib/report/clipExport.test.mjs
@@ -19,7 +19,8 @@ process.env.CHANNELS_DIR = CORPUS;
process.env.UMTOOL_CACHE_DIR = CACHE;
const {
- exportArgs, exportClip, exportDate, exportFileOf, exportName, exportSlug, listExports, planExport, planSeconds, planSummary,
+ EXPORT_CONTEXT, contextSeconds, exportArgs, exportClip, exportDate, exportFileOf, exportName, exportNeeds, exportSlug, exportSpan, exportSteps,
+ listExports, planExport, planSeconds, planSummary, spanOf,
} = await import("./clipExport.mjs");
const { cannotOpen, hostName, isLoopbackHost, localRequest, openFolder, openersFor } = await import("./openFolder.mjs");
@@ -203,8 +204,23 @@ test("export a clip: the kept seconds land in exports/ under the clip's name; ra
const rawExp = await exportClip(project, "c1", { kind: "raw" });
assert.equal(rawExp.name, "c1-raw-2026-08-12-deal-with-it.mp4");
near(probeDuration(rawExp.abs), 9, "1 s pad either side of 2–9 s, no gap", 0.12);
+ // With context: what the cut plays (2–9) and 1 s either side, as recorded -- no gap taken out.
+ const ctx = await exportClip(project, "c1", { kind: "context", context: 1 });
+ assert.equal(ctx.name, "c1-ctx1-2026-08-12-deal-with-it.mp4");
+ near(probeDuration(ctx.abs), 9, "1 s either side of 2–9 s, as recorded", 0.15);
+ // The full exchange: a span of its own, its seconds in the name; one past the file is clamped and said.
+ const full = await exportClip(project, "c1", { kind: "raw", span: { from: 0.5, to: 11.5 } });
+ assert.equal(full.name, "c1-raw-0-12-2026-08-12-deal-with-it.mp4");
+ near(probeDuration(full.abs), 11, "0.5–11.5 s", 0.15);
+ const past = await exportClip(project, "c1", { kind: "raw", span: { from: 6, to: 20 } });
+ assert.match(past.notes.join(" "), /ends 8\.00 s before what was asked/);
+ // What a context export needs that is not on disk: 30 s either side is past the 0–12 window.
+ const need = await exportNeeds(project, "c1", { kind: "context", context: 30 });
+ assert.equal(need.held, false);
+ // The pads are from the clip's extent (2–9), as the editor's fetch-window takes them; the recording starts at 0.
+ assert.deepEqual([need.padBefore, need.padAfter], [2, 30]);
const listed = await listExports(root);
- assert.deepEqual(listed.map((x) => x.name).sort(), [cut.name, rawExp.name].sort());
+ assert.deepEqual(listed.map((x) => x.name).sort(), [cut.name, rawExp.name, ctx.name, full.name, past.name].sort());
assert.deepEqual(readdirSync(path.join(root, "exports")).filter((n) => n.startsWith(".")), [], "no part file left");
await assert.rejects(exportClip(project, "nope"), /no clip nope/);
});
@@ -219,6 +235,35 @@ test("export a clip whose window is not on disk: refused, fetch it first", async
await assert.rejects(exportClip({ id: "exp2", dir: root }, "c9"), (e) => e.status === 409 && /fetch it first/.test(e.message));
});
+test("context and a raw span: their bounds, the span they ask for, and the job that makes them", async () => {
+ assert.equal(contextSeconds(undefined), EXPORT_CONTEXT.default);
+ assert.equal(contextSeconds("12"), 12);
+ for (const bad of [0, 121, "x", -1]) assert.throws(() => contextSeconds(bad), (e) => e.status === 400);
+ assert.equal(spanOf(undefined), null);
+ assert.deepEqual(spanOf({ from: 1.234, to: 9 }), { from: 1.23, to: 9 });
+ for (const bad of [{ from: 5, to: 5.2 }, { from: -1, to: 4 }, { from: 0, to: 4000 }, {}]) assert.throws(() => spanOf(bad), (e) => e.status === 400);
+ const e = { id: "c1", start: 103, end: 137, cutStart: 110, cutEnd: 130 };
+ assert.deepEqual(exportSpan(e, { leadIn: 0.4 }, { kind: "cut" }), { from: 109.6, to: 130 });
+ assert.deepEqual(exportSpan(e, { leadIn: 0.4 }, { kind: "context", context: 10 }), { from: 99.6, to: 140 });
+ assert.deepEqual(exportSpan(e, { fetchPad: 3 }, { kind: "raw" }), { from: 100, to: 140 });
+ assert.deepEqual(exportSpan(e, {}, { kind: "raw", span: { from: 50, to: 200 } }), { from: 50, to: 200 });
+ // Names: the kind in the name, so the three never overwrite each other.
+ const named = { id: "ss1", date: "2026-07-22", quote: "side scrollers full exchange" };
+ assert.equal(exportName(named, { kind: "context", context: 10 }), "ss1-ctx10-2026-07-22-side-scrollers-full-exchange.mp4");
+ assert.equal(exportName(named, { kind: "raw", span: { from: 1832.4, to: 1910.2 } }), "ss1-raw-1832-1911-2026-07-22-side-scrollers-full-exchange.mp4");
+ // The job: the editor's fetch first when asked (its pads), then `umtool export … --progress ndjson`.
+ const steps = await exportSteps({ id: "reports/x", dir: "/r/x" }, "c1", { kind: "context", context: 10, fetch: { padBefore: 14, padAfter: 9 } });
+ assert.equal(steps.length, 2);
+ assert.ok(steps[0].argv.some((a) => String(a).endsWith("fetch-via-editor.mjs")), "the editor's fetch-window path");
+ assert.deepEqual(steps[0].argv.slice(-6), ["--pad-before", "14", "--pad-after", "9", "--progress", "ndjson"]);
+ assert.deepEqual(steps[1].argv.slice(2), ["export", "reports/x", "c1", "--context", "10", "--progress", "ndjson"]);
+ assert.equal(steps[1].ndjson, true);
+ const raw = await exportSteps({ id: "reports/x", dir: "/r/x" }, "c1", { kind: "raw", span: { from: 5, to: 50 }, take: "t1" });
+ assert.equal(raw.length, 1, "nothing to fetch: the export alone");
+ assert.deepEqual(raw[0].argv.slice(2), ["export", "reports/x", "c1", "--raw", "--from", "5", "--to", "50", "--take", "t1", "--progress", "ndjson"]);
+ assert.match(planSummary({ kind: "context", context: 10, from: 0, to: 30, gaps: [], mute: null, soundFrom: null, edges: "window" }), /the cut with 10 s either side, as recorded/);
+});
+
// ---- open folder ----------------------------------------------------------------
test("who may ask to open a folder: this machine, by the headers a browser sends", () => {
diff --git a/umtool/lib/report/takeCancel.mjs b/umtool/lib/report/takeCancel.mjs
@@ -0,0 +1,245 @@
+// CANCEL A TAKE WHILE IT RENDERS (UI notes 2026-10-30, item 19: "a cancel
+// button while it renders").
+//
+// The render belongs to whichever process holds the take's build lock
+// (`takes/<id>/.building.json`, takePrune.mjs): the app's take job (a `umtool
+// take` the job runner spawned), or a `umtool take` an agent started in a
+// terminal. Nothing outside that process can stop its render CLEANLY -- a
+// signal from here would leave its scratch behind, or reach a process group it
+// does not own -- so a cancel is a REQUEST the take maker answers:
+//
+// requestCancel writes `takes/<id>/.cancel.json` {at, by, pid} beside a
+// LIVE build lock on this machine (a take that is not
+// rendering, or renders on another host, is refused in words)
+// watchCancel the take maker polls for it while it holds the lock; seen,
+// it stops its render (takeRender.mjs: the render's whole
+// process group, TERM then KILL), removes the half-made
+// render manifest, and
+// markCancelled writes `takes/<id>/cancelled.json` {at, by, label, rebuild}
+// -- what the list shows: a first render cancelled is a work
+// dir with this and no take.json (folded away, deletable), a
+// rebuild cancelled keeps its last take whole and says so
+//
+// The take maker then rejects with TakeCancelled; its build lock goes in its
+// own `finally`, and so does render mode when this take held it
+// (renderMode.mjs withRenderHold's `finally`). `releaseTakeHold` is the
+// belt-and-braces for a process that went without letting go.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { readdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { BUILD_LOCK, lockIsLive, readBuildLock } from "./takePrune.mjs";
+import { isTakeId, takesDirOf, TAKE_FILE } from "./takes.mjs";
+
+export const CANCEL_FILE = ".cancel.json";
+export const CANCELLED_FILE = "cancelled.json";
+/** How often the take maker looks for a cancel request (ms). */
+export const CANCEL_POLL_MS = 400;
+
+export class TakeCancelled extends Error {
+ /** @param {string} take @param {string} [by] */
+ constructor(take, by = "") {
+ super(`take ${take} was cancelled${by ? ` (${by})` : ""} — its render stopped; nothing was written over a finished take`);
+ this.take = take;
+ this.cancelled = true;
+ }
+}
+
+const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null);
+async function writeJson(file, doc) {
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8");
+ await rename(tmp, file);
+}
+
+/**
+ * Ask the render of take `takeId` to stop. Refused unless its build lock is
+ * live and on this machine.
+ *
+ * @param {string} projectDir
+ * @param {string} takeId
+ * @param {{ by?: string, now?: () => Date, host?: string, alive?: (pid: number) => boolean }} [opts]
+ * @returns {Promise<{ lock: Record<string, any>, file: string }>}
+ */
+export async function requestCancel(projectDir, takeId, { by = "the Takes page", now = () => new Date(), host = os.hostname(), alive } = {}) {
+ if (!isTakeId(takeId)) throw new Error("not a take id");
+ const dir = path.join(takesDirOf(projectDir), takeId);
+ const lock = await readBuildLock(path.join(dir, BUILD_LOCK));
+ if (!lock || !lockIsLive(lock, { host, ...(alive ? { alive } : {}) })) throw new Error(`take ${takeId} is not rendering — nothing to cancel`);
+ if (lock.host && lock.host !== host) throw new Error(`take ${takeId} is rendering on ${lock.host}: cancel it there`);
+ const file = path.join(dir, CANCEL_FILE);
+ await writeJson(file, { at: now().toISOString(), by, pid: lock.pid ?? null });
+ return { lock, file };
+}
+
+/**
+ * Poll for a cancel request in `takeDir`; call `onCancel(request)` once when one
+ * appears. A request older than the watch (left by a crashed run) is cleared
+ * first. Returns stop().
+ *
+ * @param {string} takeDir
+ * @param {(req: Record<string, any>) => void} onCancel
+ * @param {{ intervalMs?: number }} [opts]
+ */
+export function watchCancel(takeDir, onCancel, { intervalMs = CANCEL_POLL_MS } = {}) {
+ const file = path.join(takeDir, CANCEL_FILE);
+ let done = false;
+ let busy = false;
+ const ready = unlink(file).catch(() => {});
+ const timer = setInterval(() => {
+ if (done || busy) return;
+ busy = true;
+ void ready
+ .then(() => readJson(file))
+ .then((req) => {
+ if (req && !done) {
+ done = true;
+ clearInterval(timer);
+ onCancel(req);
+ }
+ })
+ .finally(() => {
+ busy = false;
+ });
+ }, intervalMs);
+ timer.unref?.();
+ return () => {
+ done = true;
+ clearInterval(timer);
+ };
+}
+
+/**
+ * Record that take `takeId`'s render was cancelled (and clear the request).
+ *
+ * @param {string} projectDir
+ * @param {string} takeId
+ * @param {{ by?: string, label?: string | null, rebuild?: boolean, at?: string, now?: () => Date }} info
+ */
+export async function markCancelled(projectDir, takeId, { by = "", label = null, rebuild = false, at, now = () => new Date() } = {}) {
+ const dir = path.join(takesDirOf(projectDir), takeId);
+ const doc = { at: at ?? now().toISOString(), by, label, rebuild };
+ await writeJson(path.join(dir, CANCELLED_FILE), doc);
+ await unlink(path.join(dir, CANCEL_FILE)).catch(() => {});
+ return doc;
+}
+
+/** A take's cancelled.json, or null. */
+export async function readCancelled(projectDir, takeId) {
+ if (!isTakeId(takeId)) return null;
+ const doc = await readJson(path.join(takesDirOf(projectDir), takeId, CANCELLED_FILE));
+ return doc && typeof doc === "object" && typeof doc.at === "string" ? doc : null;
+}
+
+/**
+ * The take directories that are not (or not yet) takes: a first render in
+ * progress (a live build lock, no take.json) and a first render cancelled
+ * (cancelled.json, no take.json). What the Takes page lists beside the takes:
+ * the first with Cancel, the second folded away with Delete.
+ *
+ * @param {string} projectDir
+ * @param {{ host?: string, alive?: (pid: number) => boolean }} [opts]
+ * @returns {Promise<{ rendering: Array<{ id: string, label: string | null, pid: number | null, startedAt: string | null, from: string | null }>, cancelled: Array<{ id: string, label: string | null, at: string, by: string }> }>}
+ */
+export async function takeWorkDirs(projectDir, opts = {}) {
+ const root = takesDirOf(projectDir);
+ const names = await readdir(root).catch(() => []);
+ const rendering = [];
+ const cancelled = [];
+ for (const id of names.sort()) {
+ if (!isTakeId(id)) continue;
+ const dir = path.join(root, id);
+ const hasTake = await readFile(path.join(dir, TAKE_FILE), "utf8").then(() => true, () => false);
+ if (hasTake) continue;
+ const lock = await readBuildLock(path.join(dir, BUILD_LOCK));
+ if (lock && lockIsLive(lock, opts.host || opts.alive ? { ...(opts.host ? { host: opts.host } : {}), ...(opts.alive ? { alive: opts.alive } : {}) } : undefined)) {
+ rendering.push({ id, label: typeof lock.label === "string" ? lock.label : null, pid: Number(lock.pid) || null, startedAt: lock.startedAt ?? null, from: lock.from ?? null });
+ continue;
+ }
+ const c = await readCancelled(projectDir, id);
+ if (c) cancelled.push({ id, label: c.label ?? null, at: c.at, by: c.by ?? "" });
+ }
+ return { rendering, cancelled };
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/**
+ * Release render mode when take `takeId` of `projectId` holds it and its
+ * holder is gone (the take maker's own `finally` normally does this; a process
+ * killed outright cannot). Returns the lanes released, or null when the take
+ * held nothing.
+ *
+ * @param {string} projectId
+ * @param {string} takeId
+ * @param {{ file?: string, lanes?: any, isAlive?: (pid: number) => boolean }} [opts]
+ */
+export async function releaseTakeHold(projectId, takeId, opts = {}) {
+ const { editorLanes, renderModeFile } = await import("./renderMode.mjs");
+ const { editorConfig } = await import("./fetchWindows.mjs");
+ const { readRenderPriorityState, renderModeOff } = await import("yt-dlp-transcript-common/lib/renderPriority.mjs");
+ const file = opts.file ?? renderModeFile();
+ const st = readRenderPriorityState(file);
+ const h = st?.holder;
+ if (!st || st.ended || !h || h.take !== takeId || (h.project && h.project !== projectId)) return null;
+ const alive = opts.isAlive ?? ((pid) => {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+ });
+ if (Number(h.pid) > 0 && alive(Number(h.pid))) return null;
+ const off = await renderModeOff({ file, token: st.token, lanes: opts.lanes !== undefined ? opts.lanes : editorLanes(editorConfig(process.env)) });
+ return { released: off.released ?? [], failed: off.failed ?? [] };
+}
+
+/**
+ * Cancel take `takeId`'s render and wait for it to stop: the request
+ * (requestCancel), the take maker answering it within `waitMs`, then -- when
+ * it has not, and `fallback` can stop the process that holds the lock (the
+ * app's job runner, for a take it spawned) -- that. Render mode is let go if
+ * this take held it and did not let go itself.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {string} takeId
+ * @param {{ by?: string, waitMs?: number, pollMs?: number, fallback?: (lock: Record<string, any>) => boolean, isAlive?: (pid: number) => boolean, renderModeFile?: string, lanes?: any }} [opts]
+ * @returns {Promise<{ stopped: boolean, how: "the take maker" | "the job runner" | null, cancelled: Record<string, any> | null, renderMode: { released: string[], failed: unknown[] } | null, said: string }>}
+ */
+export async function cancelTake(project, takeId, { by = "the Takes page", waitMs = 15_000, pollMs = 250, fallback, isAlive, renderModeFile: rmFile, lanes } = {}) {
+ const { lock } = await requestCancel(project.dir, takeId, { by, ...(isAlive ? { alive: isAlive } : {}) });
+ const lockFile = path.join(takesDirOf(project.dir), takeId, BUILD_LOCK);
+ const gone = async () => {
+ const l = await readBuildLock(lockFile);
+ return !l || Number(l.pid) !== Number(lock.pid) || !lockIsLive(l, isAlive ? { alive: isAlive } : undefined);
+ };
+ let how = null;
+ const until = Date.now() + waitMs;
+ while (Date.now() < until) {
+ if (await gone()) {
+ how = "the take maker";
+ break;
+ }
+ await sleep(pollMs);
+ }
+ if (!how && fallback && fallback(lock)) {
+ const late = Date.now() + 10_000;
+ while (Date.now() < late) {
+ if (await gone()) {
+ how = "the job runner";
+ break;
+ }
+ await sleep(pollMs);
+ }
+ }
+ const renderMode = await releaseTakeHold(project.id, takeId, { ...(rmFile ? { file: rmFile } : {}), ...(lanes !== undefined ? { lanes } : {}), ...(isAlive ? { isAlive } : {}) }).catch(() => null);
+ // A take stopped by the job runner never wrote its own mark: this one does.
+ let cancelled = await readCancelled(project.dir, takeId);
+ if (how === "the job runner" && !cancelled) cancelled = await markCancelled(project.dir, takeId, { by, label: lock.label ?? null }).catch(() => null);
+ const said = how
+ ? `take ${takeId}: its render stopped (${how})${renderMode?.released?.length ? ` — render mode off, lanes released: ${renderMode.released.join(", ")}` : renderMode ? " — render mode off" : ""}`
+ : `take ${takeId}: asked to stop (pid ${lock.pid}); it has not yet — it stops at its next check, or cancel it where it runs`;
+ return { stopped: !!how, how, cancelled, renderMode, said };
+}
diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs
@@ -92,6 +92,14 @@ export const TAKES_USAGE = [
" 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)",
+ " umtool takes cancel <project> <take> [--json] stop the take's render (it renders now: its build lock is live",
+ " here): asked of the process rendering it, which stops its render, marks the take cancelled",
+ " (takes/<take>/cancelled.json) and lets render mode go if the take held it",
+ " umtool takes fork <project> <take> [--name N] [--json] the take as a VARIANT: a project beside this one",
+ " (default name v-<take>) with the take's manifest, variant.json naming where it came from, the",
+ " parent's fetched media linked, and the take itself (its preview hard-linked)",
+ " umtool takes compare <project> <a> <b> [--json] two takes side by side: <take> of this project or",
+ " <project>:<take> (a variant's): the facts, the cut's changes A → B, the look's differences",
].join("\n");
class CliError extends Error {}
@@ -100,7 +108,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", "--by",
+ "--at", "--dur", "--recipe", "--only", "--progress", "--from", "--by", "--name",
]);
/** @type {Record<string, string[]>} */
const flags = {};
@@ -395,6 +403,56 @@ export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = con
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 === "cancel") {
+ const project = await pickProject(rest[0], reportsRoot);
+ const take = rest[1];
+ if (!take) throw new CliError("umtool takes cancel <project> <take>");
+ const { cancelTake } = await import("./takeCancel.mjs");
+ const r = await cancelTake(project, take, { by: "umtool takes cancel" });
+ if (p.has("--json")) log(JSON.stringify({ ok: r.stopped, ...r }, null, 2));
+ else log(r.said);
+ return r.stopped ? 0 : 1;
+ }
+ if (sub === "fork") {
+ const project = await pickProject(rest[0], reportsRoot);
+ const take = rest[1];
+ if (!take) throw new CliError("umtool takes fork <project> <take> [--name N]");
+ const { ForkRefused, forkTakeAsVariant } = await import("./variantFork.mjs");
+ try {
+ const r = await forkTakeAsVariant(project, take, { name: p.one("--name") ?? null });
+ if (p.has("--json")) log(JSON.stringify({ ok: true, ...r }, null, 2));
+ else {
+ log(`${r.id}: a variant of ${project.id}, forked from its take ${take}`);
+ if (r.links.length) log(` linked from ${project.id}: ${r.links.join(", ")}`);
+ if (r.copied.length) log(` copied: ${r.copied.join(", ")}`);
+ log(r.take ? (r.take.linked ? ` its take ${take} is there too (the preview hard-linked)` : ` its take ${take}: the preview could not be hard-linked (another filesystem) — render it there`) : ` no rendered take to bring: render one there`);
+ log(` walk it: /projects/${r.id}/takes · compare: umtool takes compare ${project.id} ${take} ${r.id}:${take}`);
+ }
+ return 0;
+ } catch (e) {
+ if (e instanceof ForkRefused) {
+ err(e.message);
+ return 1;
+ }
+ throw e;
+ }
+ }
+ if (sub === "compare") {
+ const project = await pickProject(rest[0], reportsRoot);
+ if (!rest[1] || !rest[2]) throw new CliError("umtool takes compare <project> <a> <b> (<take> or <project>:<take>)");
+ const { compareLines, compareTakes, parseTakeRef } = await import("./takeCompare.mjs");
+ const refs = [rest[1], rest[2]].map((x) => parseTakeRef(x, project.id));
+ if (refs.some((x) => !x)) throw new CliError("a take is <take> or <project>:<take>");
+ const sides = [];
+ for (const ref of /** @type {Array<{ project: string, take: string }>} */ (refs)) {
+ const pr = ref.project === project.id ? project : await pickProject(ref.project, reportsRoot);
+ sides.push({ ref: { project: pr.id, take: ref.take }, dir: pr.dir });
+ }
+ const c = await compareTakes(sides[0], sides[1]);
+ if (p.has("--json")) log(JSON.stringify(c, null, 2));
+ else for (const l of compareLines(c)) log(l);
+ return 0;
+ }
if (sub === "delete") {
const project = await pickProject(rest[0], reportsRoot);
const take = rest[1];
diff --git a/umtool/lib/report/takeCompare.mjs b/umtool/lib/report/takeCompare.mjs
@@ -0,0 +1,149 @@
+// TWO TAKES SIDE BY SIDE -- of one project, or of a project and its variants
+// (UI notes 2026-10-30, item 19; variantFork.mjs): what each is, and what
+// differs between them.
+//
+// a take ref `<take>` (of the project asked about) or `<project>:<take>`
+// -- a take id has no colon, and neither has a project id
+// the facts label, project, length, built, window, style, quick
+// the cut lib/report/manifest-diff.mjs over the two manifests (entries
+// added, removed, moved, their windows and fields), one line each
+// the look every leaf of the manifests outside the timeline (render.*,
+// title, subtitle …) that differs, a before and an after
+//
+// The manifests are the ones each take was rendered from (takes/<id>/
+// video.manifest.json), a draft's resolved from its patch (takeManifest.mjs).
+// Reads only.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { diffManifests, formatChange } from "./manifest-diff.mjs";
+import { MANIFEST } from "./takeMaker.mjs";
+import { isTakeId, listTakes, takesDirOf } from "./takes.mjs";
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+/** How many look differences are listed at most. */
+export const LOOK_LIMIT = 200;
+
+/**
+ * `<take>` or `<project>:<take>` as `{ project, take }` (project defaulting to `defaultProject`); null when malformed.
+ * @param {unknown} s
+ * @param {string} defaultProject
+ */
+export function parseTakeRef(s, defaultProject) {
+ const v = String(s ?? "").trim();
+ if (!v) return null;
+ const i = v.lastIndexOf(":");
+ const project = i >= 0 ? v.slice(0, i) : defaultProject;
+ const take = i >= 0 ? v.slice(i + 1) : v;
+ if (!project || !isTakeId(take)) return null;
+ return { project, take };
+}
+
+/** A ref back to its string: `<project>:<take>`. */
+export const takeRefOf = (r) => `${r.project}:${r.take}`;
+
+/**
+ * Every leaf of `obj` as `[dotted path, value]`; arrays are leaves (their JSON).
+ * @param {unknown} obj
+ * @param {string} [prefix]
+ * @returns {Array<[string, unknown]>}
+ */
+export function leaves(obj, prefix = "") {
+ if (!isObj(obj)) return prefix ? [[prefix, obj]] : [];
+ const keys = Object.keys(obj);
+ if (!keys.length) return prefix ? [[prefix, {}]] : [];
+ return keys.flatMap((k) => leaves(/** @type {any} */ (obj)[k], prefix ? `${prefix}.${k}` : k));
+}
+
+/** A value for a difference line: short. */
+export function shortValue(v) {
+ if (v === undefined) return "—";
+ const s = typeof v === "string" ? v : JSON.stringify(v);
+ return s.length > 80 ? `${s.slice(0, 79)}…` : s;
+}
+
+/**
+ * What differs between two manifests outside the timeline: `[{ path, a, b }]`, sorted by path.
+ * @param {Record<string, any>} a
+ * @param {Record<string, any>} b
+ */
+export function lookDiff(a, b) {
+ const skip = (p) => p === "timeline" || p.startsWith("timeline.") || p === "generatedOn" || p === "timelineNodes" || p.startsWith("timelineNodes.");
+ const la = new Map(leaves(a).filter(([p]) => !skip(p)));
+ const lb = new Map(leaves(b).filter(([p]) => !skip(p)));
+ const out = [];
+ for (const p of [...new Set([...la.keys(), ...lb.keys()])].sort()) {
+ const x = la.get(p);
+ const y = lb.get(p);
+ if (JSON.stringify(x) !== JSON.stringify(y)) out.push({ path: p, a: x, b: y });
+ }
+ return out;
+}
+
+/** A take's manifest: the one it was rendered from, else resolved from its patch. */
+async function manifestOf(dir, take) {
+ try {
+ const m = JSON.parse(await readFile(path.join(takesDirOf(dir), take, MANIFEST), "utf8"));
+ if (isObj(m)) return m;
+ } catch {
+ /* a draft, or a take made by hand */
+ }
+ const { resolveTakeManifest } = await import("./takeManifest.mjs");
+ return (await resolveTakeManifest(dir, take)).manifest;
+}
+
+/**
+ * Two takes, compared.
+ *
+ * @param {{ ref: { project: string, take: string }, dir: string }} a
+ * @param {{ ref: { project: string, take: string }, dir: string }} b
+ */
+export async function compareTakes(a, b) {
+ const side = async (s) => {
+ const t = (await listTakes(s.dir)).takes.find((x) => x.id === s.ref.take);
+ if (!t) throw new Error(`${s.ref.project} has no take ${s.ref.take}`);
+ const manifest = await manifestOf(s.dir, s.ref.take);
+ return {
+ ref: takeRefOf(s.ref),
+ project: s.ref.project,
+ take: t.id,
+ label: t.label,
+ seconds: t.seconds,
+ builtAt: t.builtAt,
+ window: t.window,
+ style: t.style,
+ quick: t.quick === true,
+ draft: t.draft === true,
+ hasPreview: !t.draft,
+ clips: (manifest.timeline ?? []).filter((e) => isObj(e) && e.type === "clip").length,
+ entries: (manifest.timeline ?? []).length,
+ manifest,
+ };
+ };
+ const [x, y] = await Promise.all([side(a), side(b)]);
+ const cut = diffManifests(x.manifest, y.manifest);
+ const look = lookDiff(x.manifest, y.manifest);
+ const strip = ({ manifest: _m, ...rest }) => rest;
+ return {
+ a: strip(x),
+ b: strip(y),
+ cut: { changes: cut.changes, lines: cut.changes.map(formatChange), counts: cut.counts },
+ look: look.slice(0, LOOK_LIMIT),
+ lookMore: Math.max(0, look.length - LOOK_LIMIT),
+ seconds: typeof x.seconds === "number" && typeof y.seconds === "number" ? Number((y.seconds - x.seconds).toFixed(2)) : null,
+ same: cut.same && look.length === 0,
+ };
+}
+
+/** The comparison as lines (`umtool takes compare`). */
+export function compareLines(c) {
+ const lines = [];
+ const fact = (s) => `${s.ref} "${s.label}" ${typeof s.seconds === "number" ? `${s.seconds.toFixed(1)} s` : "not rendered"} ${s.clips} clips${s.style ? ` style ${s.style}` : ""}${s.window && s.window !== "full" ? ` window ${s.window.at}+${s.window.dur}` : ""}`;
+ lines.push(`A ${fact(c.a)}`, `B ${fact(c.b)}`);
+ if (c.seconds !== null) lines.push(`length: ${c.seconds > 0 ? "+" : ""}${c.seconds} s (B against A)`);
+ if (c.same) lines.push("the same cut and the same look");
+ if (c.cut.lines.length) lines.push(`the cut — ${c.cut.lines.length} change(s), A → B:`, ...c.cut.lines.map((l) => ` ${l}`));
+ if (c.look.length) lines.push(`the look — ${c.look.length}${c.lookMore ? `+${c.lookMore}` : ""} difference(s):`, ...c.look.map((d) => ` ${d.path}: ${shortValue(d.a)} → ${shortValue(d.b)}`));
+ return lines;
+}
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -409,7 +409,9 @@ export function normalizeWindow(w) {
* manifestPath: string, outDir: string, slug: string, full: boolean, xfade: boolean,
* keepFrames?: boolean, estimateMb?: number | null,
* emit: (ev: Record<string, unknown>) => void, log: (line: string) => void,
+ * signal?: AbortSignal,
* }} RenderJob
+ * `signal`: a cancel (takeCancel.mjs) -- the render stops its process group and rejects.
* @typedef {(job: RenderJob) => Promise<{ file: string }>} RenderFn
*/
@@ -496,16 +498,44 @@ export async function linkSharedOut(projectDir, takeOut) {
*/
export async function makeTake(projectDir, rawSpec, opts = {}) {
const prune = await import("./takePrune.mjs");
+ const cancel = await import("./takeCancel.mjs");
let lockFile = null;
+ // CANCEL (takeCancel.mjs): while the take holds its build lock it answers a
+ // cancel request -- its render stopped, the take marked cancelled.
+ const abort = new AbortController();
+ /** @type {Record<string, any> | null} */
+ let asked = null;
+ let stopWatch = null;
+ let rebuild = false;
+ const label = typeof rawSpec?.label === "string" ? rawSpec.label : null;
const onTakeDir = async (takeDir, id) => {
- lockFile = await prune.writeBuildLock(takeDir, { take: id, from: opts.from ?? null }).catch(() => null);
+ lockFile = await prune.writeBuildLock(takeDir, { take: id, from: opts.from ?? null, ...(label ? { label } : {}) }).catch(() => null);
+ rebuild = await stat(path.join(takeDir, TAKE_FILE)).then(() => true, () => false);
+ stopWatch = cancel.watchCancel(takeDir, (req) => {
+ asked = req;
+ (opts.log ?? (() => {}))(`${id}: cancel asked${req?.by ? ` by ${req.by}` : ""} — stopping the render`);
+ abort.abort();
+ });
};
let r;
try {
- r = await makeTakeLocked(projectDir, rawSpec, { ...opts, onTakeDir });
+ r = await makeTakeLocked(projectDir, rawSpec, { ...opts, onTakeDir, signal: abort.signal });
+ } catch (e) {
+ if (abort.signal.aborted && typeof rawSpec?.id === "string") {
+ const by = String(asked?.by ?? "");
+ await cancel.markCancelled(projectDir, rawSpec.id, { by, label, rebuild }).catch(() => {});
+ throw new cancel.TakeCancelled(rawSpec.id, by);
+ }
+ throw e;
} finally {
+ stopWatch?.();
if (lockFile) await prune.removeBuildLock(lockFile);
}
+ // Made: a cancel asked too late to stop it is moot, and an earlier cancelled run's mark is history.
+ if (!r.skipped) {
+ const dir = path.join(takesDirOf(projectDir), r.id);
+ await Promise.all([unlink(path.join(dir, cancel.CANCEL_FILE)).catch(() => {}), unlink(path.join(dir, cancel.CANCELLED_FILE)).catch(() => {})]);
+ }
if (!r.skipped && opts.pruneAfter !== false) {
const log = opts.log ?? (() => {});
await prune.pruneAfterBuild(projectDir, { built: r.id, log: (line) => log(`${r.id}: ${line}`) });
@@ -641,6 +671,8 @@ async function makeTakeLocked(projectDir, rawSpec, opts) {
emit({ ev: "take", id: spec.id, phase: "render", window: spec.window, entries: covered?.ids ?? null, basis: covered?.basis ?? null });
let file;
try {
+ // A cancel asked while the take was being set up: no render at all.
+ if (opts.signal?.aborted) throw new Error(`${spec.id}: cancelled before its render started`);
const render = opts.render ?? (await import("./takeRender.mjs")).renderTake;
({ file } = await render({
manifestPath: renderPath,
@@ -651,7 +683,12 @@ async function makeTakeLocked(projectDir, rawSpec, opts) {
keepFrames: opts.keepFrames === true,
emit,
log,
+ ...(opts.signal ? { signal: opts.signal } : {}),
}));
+ } catch (e) {
+ // Stopped by a cancel: the half-made manifest goes too (a finished take's own is untouched).
+ if (opts.signal?.aborted) await rm(nextManifest, { force: true });
+ throw e;
} finally {
await rm(renderPath, { force: true });
}
diff --git a/umtool/lib/report/takeRender.mjs b/umtool/lib/report/takeRender.mjs
@@ -36,6 +36,9 @@ import { PIPELINE_DIR, UMTOOL_DIR } from "./driver.mjs";
const execFileP = promisify(execFile);
+/** How long a stopped render's group gets after TERM before KILL (ms). */
+const RENDER_KILL_GRACE_MS = 8000;
+
/** The checkout's heavy-slot CLI, when this umtool sits in the checkout. */
export function queueLockScript() {
const file = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "..", "scripts", "queue-lock.mjs");
@@ -103,12 +106,48 @@ export async function takeEstimateMb({ manifestPath, xfade }, env = process.env)
export async function renderTake(job) {
const argv = renderArgv({ ...job, estimateMb: job.estimateMb !== undefined ? job.estimateMb : await takeEstimateMb(job) });
job.log(`$ ${argv.join(" ")}`);
+ if (job.signal?.aborted) throw new Error("the render was cancelled before it started");
return new Promise((resolve, reject) => {
const child = spawn(argv[0], argv.slice(1), {
// In the checkout, so queue-lock finds the checkout's lock.
cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."),
stdio: ["ignore", "pipe", "pipe"],
+ // ITS OWN PROCESS GROUP, so a cancel (takeCancel.mjs) stops the whole
+ // render -- queue-lock, build-video and every ffmpeg under it -- and
+ // nothing else: this process's group may be a terminal's or a script's.
+ detached: true,
});
+ // Stopping it: TERM to the group, KILL a grace later. A signal to THIS
+ // process (the job runner's Stop, Ctrl-C) is passed on to the group too --
+ // the render no longer shares this process's group, and must not outlive it.
+ /** @type {string | null} */
+ let stopped = null;
+ const killGroup = (sig) => {
+ try {
+ if (child.pid) process.kill(-child.pid, sig);
+ } catch {
+ /* already gone */
+ }
+ };
+ const stop = (why) => {
+ if (stopped) return;
+ stopped = why;
+ killGroup("SIGTERM");
+ setTimeout(() => killGroup("SIGKILL"), RENDER_KILL_GRACE_MS).unref();
+ };
+ const onAbort = () => stop("cancelled");
+ job.signal?.addEventListener("abort", onAbort, { once: true });
+ /** @type {Array<[NodeJS.Signals, () => void]>} */
+ const forward = [];
+ for (const sig of /** @type {NodeJS.Signals[]} */ (["SIGINT", "SIGTERM", "SIGHUP"])) {
+ const h = () => stop(sig);
+ forward.push([sig, h]);
+ process.on(sig, h);
+ }
+ const settle = () => {
+ job.signal?.removeEventListener("abort", onAbort);
+ for (const [sig, h] of forward) process.off(sig, h);
+ };
const failed = [];
let buf = "";
child.stdout.on("data", (b) => {
@@ -133,8 +172,16 @@ export async function renderTake(job) {
child.stderr.on("data", (b) => {
for (const line of b.toString().split("\n")) if (line.trim()) job.log(line);
});
- child.on("error", reject);
+ child.on("error", (e) => {
+ settle();
+ reject(e);
+ });
child.on("close", (code) => {
+ settle();
+ if (stopped) {
+ reject(new Error(stopped === "cancelled" ? "the render was cancelled" : `the render was stopped (${stopped})`));
+ return;
+ }
if (code === 0 && !failed.length) {
resolve({ file: variantPaths(job.outDir, job.slug, DEFAULT_VARIANT).final });
return;
diff --git a/umtool/lib/report/takeVariants.test.mjs b/umtool/lib/report/takeVariants.test.mjs
@@ -0,0 +1,200 @@
+// Take housekeeping, the rest (UI notes item 19): Cancel a take while it
+// renders (takeCancel.mjs, the take maker answering it), Fork as variant
+// (variantFork.mjs) and two takes compared (takeCompare.mjs).
+//
+// Run with: node --test lib/report/takeVariants.test.mjs
+import assert from "node:assert/strict";
+import { lstat, mkdir, mkdtemp, readFile, readlink, stat, writeFile } from "node:fs/promises";
+import os, { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { CANCEL_FILE, CANCELLED_FILE, TakeCancelled, cancelTake, markCancelled, readCancelled, releaseTakeHold, requestCancel, takeWorkDirs, watchCancel } from "./takeCancel.mjs";
+import { compareLines, compareTakes, leaves, lookDiff, parseTakeRef } from "./takeCompare.mjs";
+import { makeTake } from "./takeMaker.mjs";
+import { listTakes } from "./takes.mjs";
+import { ForkRefused, VARIANT_FILE, forkTakeAsVariant, readVariant, referencedAssets, variantFamily } from "./variantFork.mjs";
+
+const clip = (id, start, end, extra = {}) => ({ type: "clip", id, video: `v-${id}`, start, end, cite: start, section: 0, ...extra });
+const MANIFEST = {
+ schemaVersion: 1,
+ slug: "fixture",
+ title: "Fixture",
+ render: { width: 640, height: 360, fps: 15, transition: 0, crf: 30, chrome: { fx: { zoom: {} } } },
+ timeline: [clip("s01", 0, 10, { fx: { zoom: { shot: "shots/a.png", focus: [0, 0, 1, 1] } } }), clip("s02", 20, 25), clip("s03", 40, 50)],
+};
+
+async function project() {
+ const root = await mkdtemp(path.join(tmpdir(), "takevariants-"));
+ const reports = path.join(root, "reports");
+ const dir = path.join(reports, "case", "proj");
+ await mkdir(path.join(dir, "out", "clips-raw"), { recursive: true });
+ await mkdir(path.join(dir, "shots"), { recursive: true });
+ await writeFile(path.join(dir, "shots", "a.png"), "png");
+ await writeFile(path.join(dir, "module-config.json"), "{}\n");
+ await writeFile(path.join(dir, "out", "clips-raw", "v-s01_0.00-13.00.mp4"), "media");
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(MANIFEST, null, 2) + "\n");
+ return { root, reports, dir, ref: { id: "case/proj", dir } };
+}
+
+/** A renderer that writes the file, or -- `hold` -- waits until its signal aborts and rejects. */
+function render({ hold = false } = {}) {
+ return async (job) => {
+ if (hold) {
+ await new Promise((resolve, reject) => {
+ if (job.signal?.aborted) return reject(new Error("the render was cancelled"));
+ job.signal?.addEventListener("abort", () => reject(new Error("the render was cancelled")), { once: true });
+ setTimeout(resolve, 20_000).unref();
+ });
+ }
+ const doc = JSON.parse(await readFile(job.manifestPath, "utf8"));
+ const file = path.join(job.outDir, `${job.slug}.mp4`);
+ await writeFile(file, `render of ${doc.timeline.map((e) => e.id).join(",")}`);
+ return { file };
+ };
+}
+const opts = (extra = {}) => ({ styles: {}, probe: async () => 30, now: () => new Date("2026-11-02T10:00:00Z"), pruneAfter: false, ...extra });
+
+test("a take answers a cancel: its render stopped, no take.json, marked cancelled, its lock gone; the list shows it", async () => {
+ const p = await project();
+ const run = makeTake(p.dir, { id: "draft-2", label: "draft 2: the cold open", window: "full", patch: { title: "B" } }, opts({ render: render({ hold: true }) }));
+ const ended = run.then(() => null, (e) => e);
+ // While it renders: its directory is a work dir with a live lock (this process), listed as rendering.
+ const lock = path.join(p.dir, "takes", "draft-2", ".building.json");
+ for (let i = 0; i < 100 && !(await stat(lock).then(() => true, () => false)); i += 1) await new Promise((r) => setTimeout(r, 20));
+ const dirs = await takeWorkDirs(p.dir);
+ assert.deepEqual(dirs.rendering.map((r) => [r.id, r.label]), [["draft-2", "draft 2: the cold open"]]);
+ const r = await cancelTake(p.ref, "draft-2", { by: "a test", pollMs: 50, waitMs: 8000, lanes: null, renderModeFile: path.join(p.root, "rm.json") });
+ const e = await ended;
+ assert.ok(e instanceof TakeCancelled && /cancelled/.test(e.message), String(e));
+ assert.equal(r.stopped, true);
+ assert.equal(r.how, "the take maker");
+ assert.match(r.said, /its render stopped/);
+ const mark = await readCancelled(p.dir, "draft-2");
+ assert.equal(mark?.by, "a test");
+ assert.equal(mark?.label, "draft 2: the cold open");
+ assert.equal(mark?.rebuild, false);
+ assert.equal(await stat(path.join(p.dir, "takes", "draft-2", "take.json")).then(() => true, () => false), false, "never a take");
+ assert.equal(await stat(lock).then(() => true, () => false), false, "the lock is gone");
+ assert.equal(await stat(path.join(p.dir, "takes", "draft-2", CANCEL_FILE)).then(() => true, () => false), false, "the request is cleared");
+ assert.equal(await stat(path.join(p.dir, "takes", "draft-2", ".next.video.manifest.json")).then(() => true, () => false), false, "no half-made manifest");
+ const after = await takeWorkDirs(p.dir);
+ assert.deepEqual(after.rendering, []);
+ assert.deepEqual(after.cancelled.map((c) => c.id), ["draft-2"]);
+ // Made again, the take is a take and its mark is history.
+ await makeTake(p.dir, { id: "draft-2", label: "draft 2", window: "full", patch: { title: "B" } }, opts({ render: render(), force: true }));
+ assert.equal(await readCancelled(p.dir, "draft-2"), null);
+ assert.deepEqual((await takeWorkDirs(p.dir)).cancelled, []);
+});
+
+test("a cancel is refused for a take that is not rendering, or renders on another machine", async () => {
+ const p = await project();
+ await makeTake(p.dir, { id: "t1", label: "one", window: "full" }, opts({ render: render() }));
+ await assert.rejects(requestCancel(p.dir, "t1"), /is not rendering/);
+ await writeFile(path.join(p.dir, "takes", "t1", ".building.json"), JSON.stringify({ pid: 1, host: "elsewhere", startedAt: "x" }));
+ await assert.rejects(requestCancel(p.dir, "t1"), /rendering on elsewhere/);
+});
+
+test("watchCancel calls back once a request appears, and clears one a crashed run left", async () => {
+ const p = await project();
+ const dir = path.join(p.dir, "takes", "w");
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, CANCEL_FILE), JSON.stringify({ at: "old" }));
+ let got = null;
+ const stop = watchCancel(dir, (req) => (got = req), { intervalMs: 20 });
+ await new Promise((r) => setTimeout(r, 120));
+ assert.equal(got, null, "the stale request was cleared, not answered");
+ await writeFile(path.join(dir, CANCEL_FILE), JSON.stringify({ at: "now", by: "x" }));
+ for (let i = 0; i < 50 && !got; i += 1) await new Promise((r) => setTimeout(r, 20));
+ stop();
+ assert.equal(got?.by, "x");
+ const m = await markCancelled(p.dir, "w", { by: "x", label: "L", rebuild: true, at: "2026-11-02T00:00:00.000Z" });
+ assert.deepEqual(m, { at: "2026-11-02T00:00:00.000Z", by: "x", label: "L", rebuild: true });
+ assert.equal(await stat(path.join(dir, CANCELLED_FILE)).then(() => true, () => false), true);
+});
+
+test("render mode is let go when the cancelled take held it and is gone; another's hold is left", async () => {
+ const p = await project();
+ const file = path.join(p.root, "render-priority.json");
+ const state = (holder) => JSON.stringify({ token: "tok", since: "2026-11-02T10:00:00Z", until: "2099-01-01T00:00:00Z", holder, lanesHeld: [] });
+ await writeFile(file, state({ pid: 999999, project: "case/proj", take: "draft-2", cmd: "umtool take" }));
+ assert.equal(await releaseTakeHold("case/proj", "other", { file, lanes: null, isAlive: () => false }), null);
+ assert.equal(await releaseTakeHold("case/proj", "draft-2", { file, lanes: null, isAlive: () => true }), null, "still alive: its own finally lets go");
+ const r = await releaseTakeHold("case/proj", "draft-2", { file, lanes: null, isAlive: () => false });
+ assert.deepEqual(r, { released: [], failed: [] });
+});
+
+test("fork as variant: a project beside this one -- the take's manifest, variant.json, the media and assets linked, the take in it", async () => {
+ const p = await project();
+ await makeTake(p.dir, { id: "cold-open", label: "A cold open", window: "full", patch: { title: "Cold open" } }, opts({ render: render() }));
+ const r = await forkTakeAsVariant(p.ref, "cold-open", { name: "v-a-cold-open", now: () => new Date("2026-11-02T11:00:00Z") });
+ assert.equal(r.id, "case/v-a-cold-open");
+ const vdir = path.join(p.reports, "case", "v-a-cold-open");
+ const m = JSON.parse(await readFile(path.join(vdir, "video.manifest.json"), "utf8"));
+ assert.equal(m.title, "Cold open");
+ assert.equal(m.slug, "v-a-cold-open");
+ const v = await readVariant(vdir);
+ assert.equal(v?.variantOf, "case/proj");
+ assert.equal(v?.fromTake, "cold-open");
+ assert.equal(v?.takeLabel, "A cold open");
+ assert.match(await readFile(path.join(vdir, "README.md"), "utf8"), /A variant of `case\/proj`, forked 2026-11-02 from its take `cold-open`/);
+ assert.equal(await readlink(path.join(vdir, "out", "clips-raw")), path.join(p.dir, "out", "clips-raw"));
+ assert.equal(await readlink(path.join(vdir, "shots")), path.join(p.dir, "shots"), "the manifest's shots/ still resolve");
+ assert.equal((await lstat(path.join(vdir, "module-config.json"))).isFile(), true, "copied, not linked");
+ assert.deepEqual(r.links.sort(), ["out/clips-raw", "shots"]);
+ // The take came with it, its preview the same inode.
+ const [a, b] = await Promise.all([stat(path.join(p.dir, "takes", "cold-open", "preview.mp4")), stat(path.join(vdir, "takes", "cold-open", "preview.mp4"))]);
+ assert.equal(a.ino, b.ino);
+ const listed = await listTakes(vdir);
+ assert.deepEqual(listed.takes.map((t) => [t.id, t.kind]), [["cold-open", "reference"]]);
+ assert.deepEqual(listed.skipped, []);
+ // Refusals: the name taken, a bad name, a take that is not there.
+ await assert.rejects(forkTakeAsVariant(p.ref, "cold-open", { name: "v-a-cold-open" }), (e) => e instanceof ForkRefused && /exists/.test(e.message));
+ await assert.rejects(forkTakeAsVariant(p.ref, "cold-open", { name: "a/b" }), (e) => e instanceof ForkRefused && e.status === 400);
+ await assert.rejects(forkTakeAsVariant(p.ref, "nope"), (e) => e instanceof ForkRefused && e.status === 404);
+ // The family, from either side.
+ const fam = await variantFamily(p.ref, { root: p.reports });
+ assert.equal(fam.parent, "case/proj");
+ assert.deepEqual(fam.members.map((x) => x.id), ["case/proj", "case/v-a-cold-open"]);
+ const fam2 = await variantFamily({ id: "case/v-a-cold-open", dir: vdir }, { root: p.reports });
+ assert.deepEqual(fam2.members.map((x) => [x.id, x.fromTake]), [["case/proj", null], ["case/v-a-cold-open", "cold-open"]]);
+});
+
+test("a take rendering now is not forked", async () => {
+ const p = await project();
+ await makeTake(p.dir, { id: "t1", label: "one", window: "full" }, opts({ render: render() }));
+ await writeFile(path.join(p.dir, "takes", "t1", ".building.json"), JSON.stringify({ pid: process.pid, host: os.hostname(), startedAt: "x" }));
+ await assert.rejects(forkTakeAsVariant(p.ref, "t1"), /not forked: it is rendering now/);
+});
+
+test("two takes compared: refs, the cut's changes A → B, the look's differences", async () => {
+ const p = await project();
+ await makeTake(p.dir, { id: "a1", label: "plain", window: "full" }, opts({ render: render() }));
+ await makeTake(
+ p.dir,
+ { id: "b1", label: "tight", window: "full", patch: { render: { crf: 34 }, timeline: [clip("s02", 20, 24), clip("s01", 0, 10), clip("s09", 5, 9)] } },
+ opts({ render: render() }),
+ );
+ assert.deepEqual(parseTakeRef("b1", "case/proj"), { project: "case/proj", take: "b1" });
+ assert.deepEqual(parseTakeRef("case/v-x:a1", "case/proj"), { project: "case/v-x", take: "a1" });
+ assert.equal(parseTakeRef("Not A Take", "p"), null);
+ const c = await compareTakes({ ref: { project: "case/proj", take: "a1" }, dir: p.dir }, { ref: { project: "case/proj", take: "b1" }, dir: p.dir });
+ assert.equal(c.a.label, "plain");
+ assert.equal(c.b.clips, 3);
+ const lines = c.cut.lines.join("\n");
+ assert.match(lines, /- s03 {2}removed/);
+ assert.match(lines, /\+ s09 {2}added/);
+ assert.match(lines, /~ s02 {2}window: 20–25 -> 20–24/);
+ assert.deepEqual(c.look.map((d) => [d.path, d.a, d.b]), [["render.crf", 30, 34]]);
+ assert.equal(c.same, false);
+ assert.match(compareLines(c).join("\n"), /the look — 1 difference\(s\):\n {2}render\.crf: 30 → 34/);
+ assert.deepEqual(lookDiff({ a: { b: 1 }, timeline: [1] }, { a: { b: 1 }, timeline: [2] }), []);
+ assert.deepEqual(leaves({ x: { y: [1, 2], z: null } }), [["x.y", [1, 2]], ["x.z", null]]);
+});
+
+test("referencedAssets: the project's entries a manifest names by a relative path, its own state left out", () => {
+ const entries = new Set(["shots", "posts-media", "out", "takes", "module-config.json", "README.md"]);
+ const m = { a: "shots/x.png", b: ["posts-media/p.jpg", "out/clips-raw/a.mp4"], c: { d: "https://x/shots/y", e: "/abs/shots/z", f: "../shots/q" }, g: "takes/t/preview.mp4" };
+ assert.deepEqual(referencedAssets(m, entries), ["posts-media", "shots"]);
+ assert.equal(VARIANT_FILE, "variant.json");
+});
diff --git a/umtool/lib/report/tightCli.mjs b/umtool/lib/report/tightCli.mjs
@@ -0,0 +1,92 @@
+// `umtool tighten <project> [--json] [--no-measure] [--all] [--apply <clip>[,<clip>…]]`:
+// the Cut tab's "Propose tight windows" (lib/report/tightPropose.mjs) from a
+// terminal -- every clip of the cut tightened to its sentence and each edge
+// into its pause, before and after. Prints only; `--apply` writes the named
+// rows through the window writer (the token, the cite that follows the edge,
+// an edit note on a generated manifest), re-proposed first.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { kindMakesTakes } from "../projects/kinds.mjs";
+import { applyTightWindows, proposeTightWindows } from "./tightPropose.mjs";
+
+export const TIGHTEN_USAGE = [
+ "usage: umtool tighten <project> [--json] [--all] [--no-measure]",
+ " umtool tighten <project> --apply <clip>[,<clip>…]",
+ "",
+ "Each clip of the cut to its sentence -- the sentences its cut (its quote) touches, else the whole",
+ "sentences inside its window -- and each edge into its pause (the build's measured silences and the",
+ "gaps between the recording's timed words, at most 1 s away, inside the cached window). Prints the",
+ "clips that would change, before -> after with the seconds (--all: every clip). --no-measure skips",
+ "the silences (the words alone). --apply writes those rows through the window writer; a locked edge",
+ "is proposed like any other (a lock is against resolve-windows) and the lock is kept.",
+].join("\n");
+
+class CliError extends Error {}
+
+const hms = (t) => {
+ const m = Math.floor(t / 60);
+ return `${m}:${(t - m * 60).toFixed(2).padStart(5, "0")}`;
+};
+
+/** One row as a line. */
+export function tightLine(r) {
+ const b = `${hms(r.before.start)}–${hms(r.before.end)} (${r.before.seconds.toFixed(2)} s)`;
+ if (!r.after) return `${r.id.padEnd(8)} ${b} — ${r.why}`;
+ const a = `${hms(r.after.start)}–${hms(r.after.end)} (${r.after.seconds.toFixed(2)} s)`;
+ const d = r.after.seconds - r.before.seconds;
+ const marks = [r.locked ? "locked" : null, r.fetched ? null : "not fetched", r.clear.cut ? "clears the cut" : null].filter(Boolean);
+ return `${r.id.padEnd(8)} ${b} → ${a} ${r.changed ? `${d > 0 ? "+" : "−"}${Math.abs(d).toFixed(2)} s` : "already tight"}${marks.length ? ` [${marks.join(", ")}]` : ""}` +
+ (r.changed ? `\n ${r.how}${r.said.length ? ` — ${r.said.join("; ")}` : ""}` : "");
+}
+
+/**
+ * @param {string[]} args the words after `tighten`
+ * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts]
+ * @returns {Promise<number>}
+ */
+export async function tightenCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+ try {
+ const flags = new Set();
+ const words = [];
+ let apply = null;
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (a === "--apply") {
+ apply = String(args[i + 1] ?? "").split(",").map((s) => s.trim()).filter(Boolean);
+ i += 1;
+ if (!apply.length) throw new CliError("--apply names clips: --apply c01,c02");
+ } else if (a.startsWith("--")) {
+ if (!["--json", "--all", "--no-measure", "--help"].includes(a)) throw new CliError(`unknown flag ${a}`);
+ flags.add(a);
+ } else words.push(a);
+ }
+ if (!words[0] || flags.has("--help")) {
+ (flags.has("--help") ? out : err)(TIGHTEN_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`);
+ if (apply) {
+ const done = await applyTightWindows(project, apply);
+ if (flags.has("--json")) out(JSON.stringify({ applied: done }, null, 2));
+ else for (const d of done) out(`${d.ok ? "applied" : "NOT applied"} ${d.id}: ${d.said}`);
+ return done.every((d) => d.ok) ? 0 : 1;
+ }
+ const got = await proposeTightWindows(project, { measure: !flags.has("--no-measure") });
+ if (flags.has("--json")) {
+ out(JSON.stringify(got, null, 2));
+ return 0;
+ }
+ out(`${got.counts.proposed} of ${got.counts.clips} clips would change · ${got.counts.same} already tight${got.counts.none ? ` · ${got.counts.none} with nothing to go by` : ""}`);
+ for (const row of got.rows) if (flags.has("--all") || row.changed) out(tightLine(row));
+ if (got.counts.proposed) out(`\napply: umtool tighten ${project.id} --apply ${got.rows.filter((x) => x.changed).map((x) => x.id).join(",")}`);
+ return 0;
+ } catch (e) {
+ err(e instanceof Error ? e.message : String(e));
+ return e instanceof CliError ? 2 : 1;
+ }
+}
diff --git a/umtool/lib/report/tightCli.test.mjs b/umtool/lib/report/tightCli.test.mjs
@@ -0,0 +1,41 @@
+// The pure halves of the batch: the window patch an Apply writes
+// (tightPropose.mjs applyPatchOf) and a row as `umtool tighten` prints it.
+//
+// Run with: node --test lib/report/tightCli.test.mjs
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { tightLine } from "./tightCli.mjs";
+import { applyPatchOf } from "./tightPropose.mjs";
+
+const row = (o = {}) => ({
+ id: "t01",
+ quote: "and because of that",
+ section: 0,
+ before: { start: 1.2, end: 7.4, seconds: 6.2 },
+ after: { start: 3.0, end: 9.0, seconds: 6 },
+ changed: true,
+ how: "the sentences the cut (its quote) touches",
+ said: ["start 3.00 → 3.01, into the pause before “And”"],
+ why: null,
+ fetched: true,
+ locked: false,
+ words: "words.json",
+ clear: { cut: false, mute: false },
+ prior: { cutStart: null, cutEnd: null, muteFrom: null, cite: null, citeUrl: null },
+ ...o,
+});
+
+test("applyPatchOf: the edges, and the cut / mute mark cleared only when they no longer fit", () => {
+ assert.deepEqual(applyPatchOf(row()), { start: 3, end: 9 });
+ assert.deepEqual(applyPatchOf(row({ clear: { cut: true, mute: true } })), { start: 3, end: 9, cutStart: "", cutEnd: "", muteFrom: "" });
+ assert.equal(applyPatchOf(row({ after: null })), null);
+});
+
+test("tightLine: before → after with the seconds, the marks, and why", () => {
+ const l = tightLine(row({ locked: true, fetched: false }));
+ assert.match(l, /^t01 +0:01\.20–0:07\.40 \(6\.20 s\) → 0:03\.00–0:09\.00 \(6\.00 s\) {2}−0\.20 s {2}\[locked, not fetched\]/);
+ assert.match(l, /into the pause before/);
+ assert.match(tightLine(row({ after: null, changed: false, why: "no cues" })), /— no cues$/);
+ assert.match(tightLine(row({ changed: false, after: { start: 1.2, end: 7.4, seconds: 6.2 } })), /already tight/);
+});
diff --git a/umtool/lib/report/tightPropose.mjs b/umtool/lib/report/tightPropose.mjs
@@ -0,0 +1,211 @@
+// PROPOSE TIGHT WINDOWS for a cut (UI notes 2026-10-30, item 4: "a batch
+// 'propose tight windows' that shows before/after durations for review").
+//
+// For every clip of the project's cut, lib/report/tightWindow.mjs over what
+// this machine already has -- nothing is fetched, nothing is written:
+//
+// cues the recording's cue file (projects/report.mjs cuesInWindow),
+// 60 s either side, for where a sentence starts and ends
+// words the project's words file when it is THAT recording's, else the
+// corpus's (report-to-video clip-words.mjs: a words sidecar, a
+// whisper transcript, the en-orig captions' starts)
+// silences the build's own, measured on the build's own file and cached
+// (lib/report/cutPoints.mjs -- the bench's ghosts and Play read the
+// same); a clip with nothing on disk goes by its words alone
+// the bound the cached window holding the clip, when there is one: a
+// proposal never reaches past what the bench could play
+//
+// with no playhead: the cut's sentences when the clip has a cut (its quote),
+// else the whole sentences inside the window. Each row is before and after,
+// what moved and why; the review list (the Cut tab) applies a row only when
+// its Apply is pressed -- PUT /api/report/window, the token, the cite that
+// follows the edge -- and `umtool tighten <p> --apply <clip>` does the same
+// through the same writer.
+//
+// A LOCK IS NOT A REFUSAL HERE. `lock`/`lockStart`/`lockEnd` pin an edge
+// against `resolve-windows --write` (the widener), not against a person: five
+// of six real cuts are fully locked. A locked clip is proposed like any other
+// and its row says it is locked; Apply leaves the locks as they are.
+
+import { clipWords } from "umtool-report-to-video/clip-words";
+import { hasLocalMedia } from "umtool-report-to-video/local-media";
+import { channelsDirFor, clipsOf, cuesInWindow, hasShadowChannels, readManifest } from "../projects/report.mjs";
+import { readWords } from "./clipEditor.mjs";
+import { readReactions } from "./clipEditorBridge.mjs";
+import { withEditNotes } from "./edit-guard.mjs";
+import { manifestToken, updateClip } from "./manifest.mjs";
+import { projectCache, windowsFor } from "./serve.mjs";
+import { HOW_SAID, tightWindow } from "./tightWindow.mjs";
+
+/** How far either side of a clip its cues are read (seconds). */
+const CUE_REACH = 60;
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const r2 = (v) => Math.round(v * 100) / 100;
+
+/**
+ * @typedef {{
+ * id: string, quote: string | null, section: unknown,
+ * before: { start: number, end: number, seconds: number },
+ * after: { start: number, end: number, seconds: number } | null,
+ * changed: boolean, how: string | null, said: string[], why: string | null,
+ * fetched: boolean, locked: boolean, words: string | null,
+ * clear: { cut: boolean, mute: boolean },
+ * prior: { cutStart: number | null, cutEnd: number | null, muteFrom: number | null, cite: number | null, citeUrl: string | null },
+ * }} TightRow
+ */
+
+/**
+ * The proposals for a project's cut (or the named clips).
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {{ clips?: string[] | null, measure?: boolean }} [opts]
+ * `measure: false` skips the silences (the words alone), for a cut whose sources are not on disk
+ * @returns {Promise<{ token: string | null, rows: TightRow[], counts: { clips: number, proposed: number, same: number, none: number } }>}
+ */
+export async function proposeTightWindows(project, { clips = null, measure = true } = {}) {
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new Error("no manifest");
+ const want = clips ? new Set(clips) : null;
+ const entries = clipsOf(manifest).filter((e) => fin(e.start) && fin(e.end) && typeof e.video === "string" && !hasLocalMedia(e) && (!want || want.has(e.id)));
+ const token = await manifestToken(project.dir);
+ const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) });
+ const { doc: reactions } = await readReactions(project.dir);
+ const projectWords = await readWords(project.dir, reactions).catch(() => null);
+ const cache = await projectCache(project, manifest);
+
+ // The build's silences per clip (cached on disk; the first read measures).
+ /** @type {Map<string, Array<{ from: number, to: number }>>} */
+ const silences = new Map();
+ if (measure && entries.length) {
+ try {
+ const { cutPointsFor } = await import("./cutPoints.mjs");
+ const got = await cutPointsFor(project, { clips: entries.map((e) => e.id) });
+ for (const row of got.clips ?? []) {
+ if (!row || row.missing || row.error || !Array.isArray(row.silences) || !fin(row.fetchStart)) continue;
+ silences.set(row.id, row.silences.map((x) => ({ from: row.fetchStart + x.s, to: row.fetchStart + x.e })));
+ }
+ } catch {
+ /* the words alone */
+ }
+ }
+
+ /** @type {TightRow[]} */
+ const rows = [];
+ for (const e of entries) {
+ const before = { start: e.start, end: e.end, seconds: r2(e.end - e.start) };
+ const base = {
+ id: e.id,
+ quote: typeof e.quote === "string" ? e.quote : null,
+ section: e.section ?? null,
+ before,
+ locked: !!(e.lock || e.lockStart || e.lockEnd),
+ // What an Undo of an applied row writes back besides the edges (the writer answers only the edges' `before`).
+ prior: {
+ cutStart: fin(e.cutStart) ? e.cutStart : null,
+ cutEnd: fin(e.cutEnd) ? e.cutEnd : null,
+ muteFrom: fin(e.muteFrom) ? e.muteFrom : null,
+ cite: fin(e.cite) ? e.cite : null,
+ citeUrl: typeof e.citeUrl === "string" ? e.citeUrl : null,
+ },
+ };
+ const wins = /** @type {Array<{ from: number, to: number }>} */ (await windowsFor(project, e, cache).catch(() => []));
+ const holds = wins.find((w) => w.from <= e.start + 0.02 && w.to >= e.end - 0.02) ?? null;
+ const c = await cuesInWindow(project.dir, e.id, e.start - CUE_REACH, e.end + CUE_REACH, { manifest }).catch(() => null);
+ let words = null;
+ let wordsFrom = null;
+ if (projectWords?.length && reactions?.source?.video === e.video) {
+ words = projectWords.filter((w) => w.end >= e.start - CUE_REACH && w.start <= e.end + CUE_REACH).map((w) => ({ start: w.start, end: w.end, text: String(w.w ?? w.word ?? w.text ?? "") }));
+ wordsFrom = "project";
+ } else {
+ const cw = await clipWords(e, manifest.provenance, e.start - CUE_REACH, e.end + CUE_REACH, { channelsDir }).catch(() => null);
+ if (cw?.words?.length) {
+ words = cw.words;
+ wordsFrom = cw.from;
+ }
+ }
+ const r = tightWindow({
+ clip: { start: e.start, end: e.end, cutStart: fin(e.cutStart) ? e.cutStart : null, cutEnd: fin(e.cutEnd) ? e.cutEnd : null },
+ cues: c?.cues ?? [],
+ words,
+ silences: silences.get(e.id) ?? null,
+ at: null,
+ ...(holds ? { lo: holds.from, hi: holds.to } : { lo: 0 }),
+ });
+ if (!r.ok) {
+ rows.push({ ...base, after: null, changed: false, how: null, said: [], why: r.why, fetched: !!holds, words: wordsFrom, clear: { cut: false, mute: false } });
+ continue;
+ }
+ const cutOut = fin(e.cutStart) && fin(e.cutEnd) && (e.cutStart < r.start - 0.02 || e.cutEnd > r.end + 0.02);
+ const muteOut = fin(e.muteFrom) && (e.muteFrom < r.start - 0.02 || e.muteFrom > r.end + 0.02);
+ rows.push({
+ ...base,
+ after: { start: r.start, end: r.end, seconds: r2(r.end - r.start) },
+ changed: r.changed,
+ how: HOW_SAID[r.how],
+ said: r.said,
+ why: null,
+ fetched: !!holds,
+ words: wordsFrom,
+ clear: { cut: !!cutOut, mute: !!muteOut },
+ });
+ }
+ const proposed = rows.filter((x) => x.changed).length;
+ const none = rows.filter((x) => !x.after).length;
+ return { token, rows, counts: { clips: rows.length, proposed, same: rows.length - proposed - none, none } };
+}
+
+/**
+ * The window patch that applies one row: its edges, and the cut / the mute
+ * mark cleared when they no longer fit (as the bench's Save window does).
+ *
+ * @param {TightRow} row
+ */
+export function applyPatchOf(row) {
+ if (!row.after) return null;
+ return {
+ start: row.after.start,
+ end: row.after.end,
+ ...(row.clear.cut ? { cutStart: "", cutEnd: "" } : {}),
+ ...(row.clear.mute ? { muteFrom: "" } : {}),
+ };
+}
+
+/**
+ * Apply proposals by clip id through the window writer (the terminal's
+ * `umtool tighten <p> --apply <ids>`), one write each, re-proposed first so a
+ * row is never applied from a stale reading.
+ *
+ * @param {{ id: string, dir: string, kind: string }} project
+ * @param {string[]} ids
+ * @returns {Promise<Array<{ id: string, ok: boolean, said: string }>>}
+ */
+export async function applyTightWindows(project, ids) {
+ const { rows } = await proposeTightWindows(project, { clips: ids });
+ const out = [];
+ for (const id of ids) {
+ const row = rows.find((x) => x.id === id);
+ if (!row) {
+ out.push({ id, ok: false, said: "not a clip of the cut with a window" });
+ continue;
+ }
+ const patch = applyPatchOf(row);
+ if (!patch || !row.changed) {
+ out.push({ id, ok: false, said: row.why ?? "already tight" });
+ continue;
+ }
+ try {
+ const token = await manifestToken(project.dir);
+ const { result: res } = await withEditNotes(project, () => updateClip(project.dir, id, patch, { token }));
+ const f = res.citeFollowed;
+ out.push({
+ id,
+ ok: true,
+ said: `${row.before.start}–${row.before.end} → ${row.after?.start}–${row.after?.end} (${row.before.seconds} s → ${row.after?.seconds} s)` +
+ `${f?.cite ? `; cite ${f.cite.from} → ${f.cite.to}` : ""}${f?.citeUrl ? "; the QR's t= with it" : ""}`,
+ });
+ } catch (e) {
+ out.push({ id, ok: false, said: e instanceof Error ? e.message : String(e) });
+ }
+ }
+ return out;
+}
diff --git a/umtool/lib/report/tightWindow.mjs b/umtool/lib/report/tightWindow.mjs
@@ -0,0 +1,198 @@
+// TIGHTEN A CLIP TO ITS SENTENCE, and an edge into the nearest pause (UI notes
+// 2026-10-30, item 4: "punchy tightening meant silencedetect by hand and
+// en-orig word times read from VTT").
+//
+// Two existing rules, composed -- nothing here detects a pause or a sentence
+// of its own:
+//
+// the sentence lib/report/sentenceEdges.mjs (the phone walk's strip, the
+// pre-cut's rule): a start edge lands on a sentence START,
+// an end edge on a sentence END, read off the cues;
+// the pause report-to-video/pauses.mjs (L1's helper, the trailer's
+// snap): the measured silences and the gaps between timed
+// words, and `snapEdge` -- a start back into the pause
+// before its first word, an end forward into the one after
+// its last, "nearest" to the middle of the closest one.
+//
+// WHICH SENTENCE ("the sentence around the playhead or the current window"):
+//
+// at the playhead, when it is inside the clip (more than AT_MARGIN from
+// either edge: a playhead parked on the start, where the bench puts it
+// on arrival, is not a place somebody chose): the one sentence it is in
+// cut else the clip's cut (the quote's span): every sentence it touches,
+// whole -- the quote finished, nothing more
+// window else the whole sentences inside the window: a partial sentence at
+// either edge is dropped
+// middle a window inside one sentence: that sentence
+//
+// then each edge into its pause (a hard cut's SNAP_HARD_ROOM of quiet, at most
+// SNAP_MAX_SHIFT away, never past `lo`/`hi`: the cached window on the bench).
+// What moved and why comes back to be said; nothing here writes. The bench
+// writes through the window writer (PUT /api/report/window, the token, the cite
+// that follows the edge), and so does each Apply of the batch's proposals
+// (tightPropose.mjs).
+//
+// PURE: no fs, no DOM -- the bench imports it.
+
+import { sentenceBoundaries } from "./sentenceEdges.mjs";
+import { pauseSpans, snapEdge } from "umtool-report-to-video/pauses";
+
+/** Two seconds closer than this are the same boundary (sentenceEdges' SAME). */
+const SAME = 0.05;
+/** A playhead this close to an edge is parked there, not placed (seconds). */
+export const AT_MARGIN = 0.25;
+/** How far past the sentence the pauses are read (seconds): a snap moves at most SNAP_MAX_SHIFT. */
+const PAUSE_REACH = 2;
+
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const r2 = (v) => Math.round(v * 100) / 100;
+
+/**
+ * The sentence(s) around the span [a, b]: the last sentence start at or
+ * before `a` and the first sentence end at or after `b`. null when the cues
+ * hold no such boundary on either side.
+ *
+ * @param {Array<{ start: number, end: number, text: string }>} cues
+ * @param {number} a
+ * @param {number} b
+ * @returns {{ start: number, end: number } | null}
+ */
+export function sentenceAround(cues, a, b) {
+ const { starts, ends } = sentenceBoundaries(cues);
+ let start = null;
+ for (const s of starts) if (s <= a + SAME) start = s;
+ const end = ends.find((e) => e >= b - SAME && e > (start ?? -Infinity) + SAME) ?? null;
+ return start !== null && end !== null ? { start, end } : null;
+}
+
+/**
+ * The whole sentences inside [from, to]: the first sentence start at or after
+ * `from`, the last sentence end at or before `to`. null when no whole sentence
+ * fits.
+ *
+ * @param {Array<{ start: number, end: number, text: string }>} cues
+ * @param {number} from
+ * @param {number} to
+ */
+export function sentencesInside(cues, from, to) {
+ const { starts, ends } = sentenceBoundaries(cues);
+ const start = starts.find((s) => s >= from - SAME) ?? null;
+ let end = null;
+ for (const e of ends) if (e <= to + SAME) end = e;
+ return start !== null && end !== null && end > start + SAME ? { start, end } : null;
+}
+
+/**
+ * The pauses around [from, to] (pauses.mjs pauseSpans): the measured silences
+ * and the gaps between timed words.
+ *
+ * @param {{ words?: Array<{ start: number, end?: number }> | null, silences?: Array<{ from: number, to: number }> | null }} o
+ * @param {number} from
+ * @param {number} to
+ */
+export function pausesNear({ words = null, silences = null }, from, to) {
+ return pauseSpans({ words, silences }, { from: from - PAUSE_REACH, to: to + PAUSE_REACH });
+}
+
+/** One snap in words: "start 12.40 → 12.95, into the pause before “So”". */
+export function snapSaid(edge, snap) {
+ if (!snap) return null;
+ if (!snap.moved) {
+ const why = snap.reason === "fits" ? "already in a pause" : snap.reason === "far" ? "the nearest pause is more than a second away" : snap.reason === "bound" ? "the pause is past the cached window" : "no pause near it";
+ return `${edge} stays at ${snap.at.toFixed(2)} (${why})`;
+ }
+ const word = snap.word ? ` ${snap.side === "start" ? "before" : snap.side === "end" ? "after" : "by"} “${snap.word}”` : "";
+ return `${edge} ${snap.from.toFixed(2)} → ${snap.at.toFixed(2)}, into the pause${word}${snap.bounded ? " (as far as the cached window)" : ""}`;
+}
+
+/**
+ * An edge into the pause nearest it (pauses.mjs snapEdge "nearest"): what the
+ * bench's "Snap edge to nearest pause" does.
+ *
+ * @param {number} t
+ * @param {{ words?: Array<{ start: number, end?: number, text?: string }> | null, silences?: Array<{ from: number, to: number }> | null, lo?: number, hi?: number }} o
+ */
+export function nearestPause(t, { words = null, silences = null, lo = -Infinity, hi = Infinity }) {
+ const pauses = pausesNear({ words, silences }, t, t);
+ return snapEdge(t, "nearest", { pauses, words, lo, hi });
+}
+
+/**
+ * Tighten a clip to its sentence (see the header).
+ *
+ * @param {{
+ * clip: { start: number, end: number, cutStart?: number | null, cutEnd?: number | null },
+ * cues: Array<{ start: number, end: number, text: string }>,
+ * words?: Array<{ start: number, end?: number, text?: string }> | null,
+ * silences?: Array<{ from: number, to: number }> | null,
+ * at?: number | null,
+ * lo?: number, hi?: number,
+ * snap?: boolean,
+ * }} o
+ * @returns {{ ok: true, start: number, end: number, how: "at" | "cut" | "window" | "middle",
+ * sentence: { start: number, end: number }, snaps: { start: any, end: any } | null, changed: boolean, said: string[] }
+ * | { ok: false, why: string }}
+ */
+export function tightWindow({ clip, cues, words = null, silences = null, at = null, lo = -Infinity, hi = Infinity, snap = true }) {
+ if (!clip || !fin(clip.start) || !fin(clip.end)) return { ok: false, why: "the clip has no window" };
+ const cs = (cues ?? []).filter((c) => c && fin(c.start) && fin(c.end));
+ if (!cs.length) return { ok: false, why: "no cues for this recording: nothing says where a sentence is" };
+ const hasCut = fin(clip.cutStart) && fin(clip.cutEnd);
+ /** @type {"at" | "cut" | "window" | "middle"} */
+ let how;
+ let s = null;
+ if (fin(at) && at > clip.start + AT_MARGIN && at < clip.end - AT_MARGIN) {
+ how = "at";
+ s = sentenceAround(cs, /** @type {number} */ (at), /** @type {number} */ (at));
+ } else if (hasCut) {
+ how = "cut";
+ s = sentenceAround(cs, /** @type {number} */ (clip.cutStart), /** @type {number} */ (clip.cutEnd));
+ } else {
+ how = "window";
+ s = sentencesInside(cs, clip.start, clip.end);
+ if (!s) {
+ how = "middle";
+ const mid = (clip.start + clip.end) / 2;
+ s = sentenceAround(cs, mid, mid);
+ }
+ }
+ if (!s) return { ok: false, why: "the cues around it hold no sentence boundary" };
+ // The cached window bounds the sentence itself, not only the snap: an edge
+ // past it is clamped to it (and said).
+ const said = [];
+ let start = s.start;
+ let end = s.end;
+ if (start < lo - 1e-6) {
+ said.push(`the sentence starts at ${start.toFixed(2)}, before the cached window: from ${lo.toFixed(2)}`);
+ start = lo;
+ }
+ if (end > hi + 1e-6) {
+ said.push(`the sentence ends at ${end.toFixed(2)}, past the cached window: to ${hi.toFixed(2)}`);
+ end = hi;
+ }
+ let snaps = null;
+ if (snap) {
+ const pauses = pausesNear({ words, silences }, start, end);
+ if (pauses.length) {
+ const a = snapEdge(start, "start", { pauses, words, lo, hi: end });
+ const b = snapEdge(end, "end", { pauses, words, lo: start, hi });
+ snaps = { start: a, end: b };
+ if (a.moved) start = a.at;
+ if (b.moved) end = b.at;
+ for (const [edge, x] of /** @type {const} */ ([["start", a], ["end", b]])) if (x.moved) said.push(/** @type {string} */ (snapSaid(edge, x)));
+ }
+ }
+ start = r2(start);
+ end = r2(end);
+ if (!(end - start >= 0.5)) return { ok: false, why: "the sentence is shorter than half a second" };
+ const changed = Math.abs(start - clip.start) > 0.02 || Math.abs(end - clip.end) > 0.02;
+ return { ok: true, start, end, how, sentence: { start: r2(s.start), end: r2(s.end) }, snaps, changed, said };
+}
+
+/** What the anchor was, in words. */
+export const HOW_SAID = Object.freeze({
+ at: "the sentence at the playhead",
+ cut: "the sentences the cut (its quote) touches",
+ window: "the whole sentences inside the window",
+ middle: "the sentence the window is inside",
+});
diff --git a/umtool/lib/report/tightWindow.test.mjs b/umtool/lib/report/tightWindow.test.mjs
@@ -0,0 +1,109 @@
+// tightWindow.mjs: a clip tightened to its sentence (sentenceEdges.mjs) and
+// each edge into its pause (report-to-video/pauses.mjs) -- which sentence (the
+// playhead's, the cut's, the whole ones inside the window, the one it is
+// inside), the cache as a bound, and an edge to the nearest pause.
+//
+// Run with: node --test lib/report/tightWindow.test.mjs
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { HOW_SAID, nearestPause, pausesNear, sentenceAround, sentencesInside, snapSaid, tightWindow } from "./tightWindow.mjs";
+
+// The e2e fixture's vid1 cues (e2e/fixtures/make-fixture.mjs): sentences 0-3, 3-9, 9-12, 12-15, 15-21.
+const VID1 = [
+ [0, 3, "This is a complete sentence."],
+ [3, 6, "And this one runs on and because"],
+ [6, 9, "of that it finishes here."],
+ [9, 12, "Another whole sentence entirely."],
+ [12, 15, "A fourth one, done."],
+ [15, 18, "trailing off and then"],
+ [18, 21, "it lands at last."],
+].map(([start, end, text]) => ({ start, end, text }));
+
+// Timed words over it (the tight fixture's words.json), with the silences of the fixture's tone window.
+const WORDS = [
+ ["This", 0.2, 0.5], ["is", 0.55, 0.7], ["a", 0.75, 0.8], ["complete", 0.9, 1.6], ["sentence.", 1.7, 2.8],
+ ["And", 3.2, 3.5], ["this", 3.55, 3.8], ["one", 3.85, 4.1], ["runs", 4.15, 4.5], ["on", 4.55, 4.7], ["and", 4.75, 5], ["because", 5.1, 5.85],
+ ["of", 6.2, 6.4], ["that", 6.45, 6.8], ["it", 6.85, 7], ["finishes", 7.1, 7.9], ["here.", 8, 8.8],
+ ["Another", 9.2, 9.8], ["whole", 9.9, 10.3], ["sentence", 10.4, 11], ["entirely.", 11.1, 11.8],
+].map(([text, start, end]) => ({ text, start, end }));
+const SILENCES = [{ from: 2.9, to: 3.11 }, { from: 5.92, to: 6.11 }, { from: 8.85, to: 9.15 }];
+
+test("sentenceAround: the last start at or before, the first end at or after", () => {
+ assert.deepEqual(sentenceAround(VID1, 4.5, 4.5), { start: 3, end: 9 });
+ assert.deepEqual(sentenceAround(VID1, 1, 10), { start: 0, end: 12 });
+ // On a boundary: the sentence that starts there.
+ assert.deepEqual(sentenceAround(VID1, 3, 3), { start: 3, end: 9 });
+ assert.equal(sentenceAround([{ start: 0, end: 3, text: "no end" }], 1, 1), null);
+});
+
+test("sentencesInside: partial sentences at either edge are dropped", () => {
+ assert.deepEqual(sentencesInside(VID1, 1.2, 12.4), { start: 3, end: 12 });
+ assert.equal(sentencesInside(VID1, 3.5, 8), null, "inside one sentence: nothing whole");
+});
+
+test("at the playhead: that sentence, each edge into its pause", () => {
+ const r = tightWindow({ clip: { start: 1.2, end: 10.5 }, cues: VID1, words: WORDS, silences: SILENCES, at: 4.4 });
+ assert.equal(r.ok, true);
+ if (!r.ok) return;
+ assert.equal(r.how, "at");
+ assert.deepEqual(r.sentence, { start: 3, end: 9 });
+ // The start goes back into the 2.9-3.2 pause (the hard cut's 0.1 s of quiet before "And");
+ // the end is already in the pause after "here." (8.8-9.2), and stays.
+ assert.ok(r.start >= 2.9 && r.start <= 3.2, `start ${r.start}`);
+ assert.ok(r.end >= 8.8 && r.end <= 9.2, `end ${r.end}`);
+ assert.equal(r.changed, true);
+});
+
+test("the cut anchors it when the playhead is elsewhere: every sentence the quote touches", () => {
+ const r = tightWindow({ clip: { start: 0.5, end: 11.9, cutStart: 4, cutEnd: 7.5 }, cues: VID1, at: null, snap: false });
+ assert.equal(r.ok && r.how, "cut");
+ assert.equal(r.ok && r.start, 3);
+ assert.equal(r.ok && r.end, 9);
+});
+
+test("no playhead, no cut: the whole sentences inside the window, else the one it is inside", () => {
+ const a = tightWindow({ clip: { start: 1.2, end: 12.4 }, cues: VID1, snap: false });
+ assert.equal(a.ok && a.how, "window");
+ assert.deepEqual(a.ok && [a.start, a.end], [3, 12]);
+ const b = tightWindow({ clip: { start: 3.5, end: 8 }, cues: VID1, snap: false });
+ assert.equal(b.ok && b.how, "middle");
+ assert.deepEqual(b.ok && [b.start, b.end], [3, 9]);
+ assert.match(HOW_SAID.middle, /inside/);
+});
+
+test("the cached window bounds it, and says so", () => {
+ const r = tightWindow({ clip: { start: 1.2, end: 7.4 }, cues: VID1, at: 4, lo: 0, hi: 7.5, snap: false });
+ assert.equal(r.ok, true);
+ if (!r.ok) return;
+ assert.equal(r.end, 7.5);
+ assert.match(r.said.join(" "), /past the cached window/);
+});
+
+test("already tight: unchanged", () => {
+ const r = tightWindow({ clip: { start: 3, end: 9 }, cues: VID1, snap: false });
+ assert.equal(r.ok && r.changed, false);
+});
+
+test("refusals: no cues, no boundary, a window with no edges", () => {
+ assert.equal(tightWindow({ clip: { start: 1, end: 2 }, cues: [] }).ok, false);
+ assert.equal(tightWindow({ clip: { start: 1, end: 2 }, cues: [{ start: 0, end: 3, text: "no end" }] }).ok, false);
+ assert.equal(tightWindow({ clip: /** @type {any} */ ({}), cues: VID1 }).ok, false);
+});
+
+test("nearestPause: the middle of the closest pause, within a second; bounded; said", () => {
+ const n = nearestPause(5.7, { words: WORDS, silences: SILENCES });
+ assert.equal(n.moved, true);
+ assert.ok(n.at > 5.85 && n.at < 6.2, `at ${n.at}`);
+ assert.match(String(snapSaid("end", n)), /^end 5\.70 → 6\.\d\d, into the pause/);
+ const far = nearestPause(20, { words: WORDS, silences: SILENCES });
+ assert.equal(far.moved, false);
+ assert.match(String(snapSaid("start", far)), /stays/);
+ assert.ok(pausesNear({ words: WORDS, silences: SILENCES }, 4, 5).length >= 1);
+});
+
+test("a playhead parked on an edge is not the place: the window decides", () => {
+ const r = tightWindow({ clip: { start: 1.2, end: 7.4 }, cues: VID1, at: 1.2, snap: false });
+ assert.equal(r.ok && r.how, "middle");
+ assert.deepEqual(r.ok && [r.start, r.end], [3, 9]);
+});
diff --git a/umtool/lib/report/variantFork.mjs b/umtool/lib/report/variantFork.mjs
@@ -0,0 +1,244 @@
+// FORK A TAKE AS A VARIANT, and the takes of a project's variants side by
+// side (UI notes 2026-10-30, item 19: "variants as separate project copies"
+// -- `emberparadox/v-a-cold-open` … `v-d-bookends`, each copied by hand from
+// the walked cut, a README saying what it was).
+//
+// HOW A VARIANT IS STORED, as those were: a project of its own BESIDE its
+// parent (a project is a leaf of the walk, lib/projects/walk.mjs, so it
+// cannot sit inside one), so every tool -- the walk, the cut, takes, Deliver
+// -- works on it unchanged. What the fork adds is the record the hand copies
+// carried only in prose:
+//
+// <folder>/<name>/video.manifest.json the take's manifest (the one it was
+// rendered from; a draft's, resolved),
+// its `slug` the variant's name
+// <folder>/<name>/variant.json { variantOf, fromTake, takeLabel,
+// forkedAt, baseHash } -- what makes it
+// a variant of <parent>, and of which take
+// <folder>/<name>/README.md the hand copies' sentence, written
+// <folder>/<name>/out/clips-raw, LINKS to the parent's (a take's own
+// out/narration out/ links them the same way): the
+// fetched media is reused, never copied
+// <folder>/<name>/<asset> a link to the parent's, for each of its
+// top-level files or folders the manifest
+// names by a relative path (shots/, posts-
+// media/ …), so those paths still resolve;
+// module-config.json is COPIED (a variant's
+// modules are its own to change)
+// <folder>/<name>/takes/<take>/ the take itself, its preview a HARD
+// LINK (no copy of the bytes), its
+// take.json naming where it came from --
+// so the variant opens with the take it
+// was forked from, already rendered
+//
+// Refused: a take that is rendering now (its manifest is being written), a
+// name that is not one path segment or is already taken.
+//
+// `variantFamily` reads it back: the parent and every project beside it whose
+// variant.json names it -- whose takes the compare page lays side by side.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { copyFile, link, lstat, mkdir, readdir, readFile, rename, stat, symlink, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { isSegment, walkProjects } from "../projects/walk.mjs";
+import { renderHolds } from "./takeHousekeeping.mjs";
+import { MANIFEST, PREVIEW, SHARED_OUT, hashText } from "./takeMaker.mjs";
+import { isTakeId, listTakes, takesDirOf, TAKE_FILE } from "./takes.mjs";
+
+export const VARIANT_FILE = "variant.json";
+/** Copied, never linked: what a variant may change of its own. */
+const COPIED = ["module-config.json"];
+/** Never linked or copied: the project's own state. */
+const OWN = new Set(["out", "takes", "revisions", "exports", "notes.json", MANIFEST, VARIANT_FILE, "README.md", ...COPIED]);
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null);
+const exists = (p) => lstat(p).then(() => true, () => false);
+async function writeAtomic(file, text) {
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(tmp, text, "utf8");
+ await rename(tmp, file);
+}
+
+export class ForkRefused extends Error {
+ /** @param {string} message @param {number} [status] */
+ constructor(message, status = 409) {
+ super(message);
+ this.status = status;
+ }
+}
+
+/** A project's variant.json, checked, or null. */
+export async function readVariant(dir) {
+ const v = await readJson(path.join(dir, VARIANT_FILE));
+ return isObj(v) && typeof v.variantOf === "string" && v.variantOf ? v : null;
+}
+
+/** The default name for a fork of `take`: `v-<take>`. */
+export const defaultVariantName = (take) => `v-${take}`.slice(0, 64);
+
+/**
+ * Every relative path a manifest names whose first segment is an entry of the
+ * project directory (`shots/x.png` → `shots`), the project's own state left out.
+ *
+ * @param {unknown} manifest
+ * @param {Set<string>} entries the project directory's entries
+ */
+export function referencedAssets(manifest, entries) {
+ const out = new Set();
+ const walk = (v) => {
+ if (typeof v === "string") {
+ if (!v || v.length > 512 || path.isAbsolute(v) || /^[a-z]+:\/\//i.test(v) || v.includes("..")) return;
+ const first = v.split(/[\\/]/)[0];
+ if (first && entries.has(first) && !OWN.has(first)) out.add(first);
+ return;
+ }
+ if (Array.isArray(v)) for (const x of v) walk(x);
+ else if (isObj(v)) for (const x of Object.values(v)) walk(x);
+ };
+ walk(manifest);
+ return [...out].sort();
+}
+
+/**
+ * Fork take `takeId` of `project` as a variant: a project beside it (see the header).
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {string} takeId
+ * @param {{ name?: string | null, now?: () => Date }} [opts]
+ * @returns {Promise<{ id: string, dir: string, name: string, take: { id: string, linked: boolean } | null, links: string[], copied: string[], variant: Record<string, unknown> }>}
+ */
+export async function forkTakeAsVariant(project, takeId, { name = null, now = () => new Date() } = {}) {
+ if (!isTakeId(takeId)) throw new ForkRefused("not a take id", 400);
+ const listing = await listTakes(project.dir);
+ const take = listing.takes.find((t) => t.id === takeId);
+ if (!take) throw new ForkRefused(`${project.id} has no take ${takeId}`, 404);
+ const holds = (await renderHolds(project.dir, takeId)).filter((h) => h.startsWith("it is rendering"));
+ if (holds.length) throw new ForkRefused(`take ${takeId} is not forked: ${holds[0]}`);
+ const vname = String(name ?? "").trim() || defaultVariantName(takeId);
+ if (!isSegment(vname) || vname.length > 64) throw new ForkRefused(`"${vname}" is not a project name: letters, digits, . _ - (one segment)`, 400);
+ const parentDir = path.dirname(project.dir);
+ const dir = path.join(parentDir, vname);
+ if (await exists(dir)) throw new ForkRefused(`${vname} exists beside ${project.id} — name the variant something else`);
+ const folder = path.posix.dirname(project.id);
+ const id = folder === "." ? vname : `${folder}/${vname}`;
+
+ // The take's manifest: the one it was rendered from, else (a draft) resolved from its patch.
+ const takeDir = path.join(takesDirOf(project.dir), takeId);
+ let manifest = await readJson(path.join(takeDir, MANIFEST));
+ if (!isObj(manifest)) {
+ const { resolveTakeManifest } = await import("./takeManifest.mjs");
+ manifest = (await resolveTakeManifest(project.dir, takeId)).manifest;
+ }
+ if (!isObj(manifest) || !Array.isArray(manifest.timeline)) throw new ForkRefused(`take ${takeId} has no manifest to fork`, 422);
+ const doc = { ...manifest, slug: vname };
+ const text = JSON.stringify(doc, null, 2) + "\n";
+
+ await mkdir(dir);
+ await writeAtomic(path.join(dir, MANIFEST), text);
+ const variant = {
+ variantOf: project.id,
+ fromTake: takeId,
+ takeLabel: take.label,
+ forkedAt: now().toISOString(),
+ baseHash: hashText(text),
+ };
+ await writeAtomic(path.join(dir, VARIANT_FILE), JSON.stringify(variant, null, 2) + "\n");
+ await writeAtomic(
+ path.join(dir, "README.md"),
+ `# ${vname}\n\nA variant of \`${project.id}\`, forked ${variant.forkedAt.slice(0, 10)} from its take \`${takeId}\` (${take.label}).\n` +
+ `Its manifest is that take's; its clips' media is the parent's (out/clips-raw is a link).\n`,
+ );
+
+ // The fetched media and the voices, linked as a take's out/ links them.
+ const links = [];
+ await mkdir(path.join(dir, "out"), { recursive: true });
+ for (const n of SHARED_OUT) {
+ const src = path.join(project.dir, "out", n);
+ if (!(await stat(src).then((s) => s.isDirectory(), () => false))) continue;
+ await symlink(src, path.join(dir, "out", n));
+ links.push(`out/${n}`);
+ }
+ // The project's files the manifest names by a relative path, linked; its own config copied.
+ const entries = new Set(await readdir(project.dir).catch(() => []));
+ for (const seg of referencedAssets(doc, entries)) {
+ await symlink(path.join(project.dir, seg), path.join(dir, seg));
+ links.push(seg);
+ }
+ const copied = [];
+ for (const n of COPIED) {
+ if (!entries.has(n)) continue;
+ await copyFile(path.join(project.dir, n), path.join(dir, n));
+ copied.push(n);
+ }
+
+ // The take itself: its preview hard-linked (a rendered take), its manifest and take.json beside it.
+ let forkedTake = null;
+ const preview = path.join(takeDir, take.preview || PREVIEW);
+ if (!take.draft && (await stat(preview).then((s) => s.isFile(), () => false))) {
+ const dst = path.join(takesDirOf(dir), takeId);
+ await mkdir(dst, { recursive: true });
+ let linked = true;
+ try {
+ await link(preview, path.join(dst, PREVIEW));
+ } catch {
+ linked = false;
+ }
+ if (linked) {
+ await writeAtomic(path.join(dst, MANIFEST), text);
+ const raw = (await readJson(path.join(takeDir, TAKE_FILE))) ?? {};
+ const tj = {
+ ...raw,
+ id: takeId,
+ preview: PREVIEW,
+ // The variant's manifest IS this take's: nothing patched over it.
+ kind: "reference",
+ patch: null,
+ style: null,
+ changes: [],
+ baseHash: variant.baseHash,
+ forkedFrom: { project: project.id, take: takeId },
+ };
+ delete tj.draft;
+ await writeAtomic(path.join(dst, TAKE_FILE), JSON.stringify(tj, null, 2) + "\n");
+ }
+ forkedTake = { id: takeId, linked };
+ }
+ return { id, dir, name: vname, take: forkedTake, links, copied, variant };
+}
+
+/**
+ * A project's variant family: its parent (itself, when it is no variant) and
+ * every project beside the parent whose variant.json names it, each with its
+ * takes. `self` is the project asked about.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {{ root: string }} o the reports root (the walk)
+ * @returns {Promise<{ parent: string, members: Array<{ id: string, dir: string, variantOf: string | null, fromTake: string | null, takeLabel: string | null, forkedAt: string | null, takes: Array<Record<string, any>> }> }>}
+ */
+export async function variantFamily(project, { root }) {
+ const own = await readVariant(project.dir);
+ const parentId = own?.variantOf ?? project.id;
+ const all = await walkProjects(root);
+ const parent = all.find((p) => p.id === parentId) ?? null;
+ const folder = path.posix.dirname(parentId);
+ const beside = all.filter((p) => path.posix.dirname(p.id) === folder);
+ const members = [];
+ for (const p of beside) {
+ const v = p.id === parentId ? null : await readVariant(p.dir);
+ if (p.id !== parentId && v?.variantOf !== parentId) continue;
+ const listing = await listTakes(p.dir).catch(() => ({ takes: [] }));
+ members.push({
+ id: p.id,
+ dir: p.dir,
+ variantOf: v?.variantOf ?? null,
+ fromTake: typeof v?.fromTake === "string" ? v.fromTake : null,
+ takeLabel: typeof v?.takeLabel === "string" ? v.takeLabel : null,
+ forkedAt: typeof v?.forkedAt === "string" ? v.forkedAt : null,
+ takes: listing.takes,
+ });
+ }
+ // The parent first, then its variants by name.
+ members.sort((a, b) => (a.id === parentId ? -1 : b.id === parentId ? 1 : a.id.localeCompare(b.id)));
+ return { parent: parent ? parentId : parentId, members };
+}
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -27,6 +27,7 @@
"./claims": "./claims.mjs",
"./clip-audio": "./clip-audio.mjs",
"./clip-blur": "./clip-blur.mjs",
+ "./clip-words": "./clip-words.mjs",
"./compose-chrome": "./compose-chrome.mjs",
"./counter": "./counter.mjs",
"./cues": "./cues.mjs",