Archilyzer · Source

archilyzer

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

commit bb69d565cad59b964e71f5ce2b8be54d4f8b0d99
parent a7c20abf8e606abafe1927fd175a15f0b60ca8d3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 01:49:11 -0500

umtool: cancel a take while it renders, fork a take as a variant, compare takes side by side (UI notes item 19)

Cancel. A take's render is the process that holds its build lock -- the app's
take job or a terminal's `umtool take` -- so a cancel is a request it answers
(lib/report/takeCancel.mjs): the route writes takes/<id>/.cancel.json beside a
live lock on this machine; the take maker polls for it, stops its render,
removes the half-made manifest, writes takes/<id>/cancelled.json and exits;
its lock goes and so does render mode when the take held it (--priority).
takeRender.mjs now runs the render in a process group of its own, so a stop
reaches queue-lock, build-video and every ffmpeg under it and nothing else;
a signal to the take process is passed on to that group. The page waits for
the take maker, falls back to the job runner for the app's own job, and lets
go of render mode after a holder that went without doing so. A first render
(no take.json, no card yet) shows as "rendering now" with Cancel render, and
once cancelled is folded away and deletable; a cancelled rebuild keeps its
take, marked "last render cancelled".

Fork as variant (lib/report/variantFork.mjs). Variants were project copies
made by hand beside the parent (emberparadox/v-a-cold-open ...); the fork
makes the same thing and records what the copies said in prose: the take's
manifest (slug = the variant's name), variant.json {variantOf, fromTake,
takeLabel, forkedAt, baseHash}, a README, the parent's out/clips-raw and
out/narration linked, each top-level asset the manifest names linked,
module-config.json copied, and the take itself (its preview hard-linked).
The Takes page names a project's variants and a variant's parent.

Compare (lib/report/takeCompare.mjs, /projects/<p>/takes/compare?a=&b=):
any two takes of the project and its variants, two players on one transport
(B kept within 0.15 s of A, one sound), the facts side by side, the cut's
changes A -> B (manifest-diff.mjs) and the look's differences.

CLI: `umtool takes cancel | fork [--name N] | compare <a> <b>`; routes:
housekeeping ops "cancel" and "fork". Fixture variants-fixture (and a
qrencode stub stall, so a real render can be caught in progress) and
e2e/take-variants.spec.ts; takeVariants.test.mjs; docs in knobs.md, cli.md.

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

Diffstat:
Mumtool/app/api/report/takes/housekeeping/route.ts | 41++++++++++++++++++++++++++++++++++++++---
Mumtool/components/projects/ProjectView.tsx | 4++++
Aumtool/components/projects/TakeVariants.tsx | 217+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/TakesBench.tsx | 24++++++++++++++++++++++++
Aumtool/components/projects/TakesComparePage.tsx | 168+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/TakesComparePlayers.tsx | 175+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/TakesPage.tsx | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/docs/cli.md | 3++-
Mumtool/docs/knobs.md | 38+++++++++++++++++++++++++++++++++++---
Mumtool/e2e/fixtures/make-fixture.mjs | 41+++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/take-variants.spec.ts | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/hrefs.ts | 5+++++
Aumtool/lib/report/takeCancel.mjs | 245+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/takeCli.mjs | 60+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Aumtool/lib/report/takeCompare.mjs | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/takeMaker.mjs | 41+++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/takeRender.mjs | 49++++++++++++++++++++++++++++++++++++++++++++++++-
Aumtool/lib/report/takeVariants.test.mjs | 200+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/variantFork.mjs | 244+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
19 files changed, 1912 insertions(+), 13 deletions(-)

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/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,217 @@ +"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 }; +} + +/** Cancel: asks the process rendering the take to stop, and waits for it (up to ~25 s). */ +export function CancelRender({ project, take, ready }: { project: string; take: string; ready: boolean }) { + const router = useRouter(); + const [state, setState] = useState<{ k: "idle" } | { k: "cancelling" } | { k: "done"; said: string; ok: boolean }>({ k: "idle" }); + 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 || state.k === "cancelling" || (state.k === "done" && state.ok)} + 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 () => { + setState({ k: "cancelling" }); + const { ok, j } = await housekeeping({ project, take, op: "cancel" }); + setState({ k: "done", ok: ok && j.stopped === true, said: String(j.said ?? j.error ?? (ok ? "asked" : "refused")) }); + router.refresh(); + }} + > + {state.k === "cancelling" ? "Cancelling…" : "Cancel render"} + </button> + {state.k === "done" && ( + <span role="status" data-take-cancel-said="" className={`text-[11px] ${state.ok ? "text-[var(--color-dim)]" : "text-reject-text"}`}> + {state.said} + </span> + )} + </span> + ); +} + +/** 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); + if (!dirs.rendering.length && !dirs.cancelled.length) return null; + return ( + <section data-take-workdirs="" className="space-y-1.5 text-[12px]"> + {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} /> + </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, CompareWith, ForkVariant, TakeWorkDirs, 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; @@ -712,6 +726,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 +863,11 @@ 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} />} + <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&rsquo;s <span className="italic">Compare</span>. + </> + )} + </p> + )} {panel} </> } diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -58,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/knobs.md b/umtool/docs/knobs.md @@ -605,20 +605,52 @@ 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** — 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/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -1497,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]; @@ -2203,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,160 @@ +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(); + await expect(row.locator("[data-take-cancel-said]")).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 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/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/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/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 }; +}