Archilyzer · Source

archilyzer

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

commit 0322c2868ab9d58a8f1a2fc11023f38e7d186111
parent f2e4c7f7337b0068d37178b53363105ee02b6281
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  9 Nov 2026 19:09:19 -0500

Merge lane/working-draft: one place every edit lands -- the project's manifest is the working draft, a take is a frozen saved version, opening one saves the draft first, one undo stack (redesign L3; the kirsche-7 kr1 bug, 2 Nov)

S1 frozen versions (takes/vN/base.manifest.json, takes/draft.json parent pointer; `umtool takes save|open|freeze`).
S2 POST /api/report/takes/open|save (same-origin only). S3 Play plays the draft ("Draft · from v5 · 3 edits"); a version
plays read-only with Open in draft; Save version on the head. S4 the UI writes no take patch any more; old take walk and
bench URLs go to an Open in draft page (307 when opening would change nothing). S5 every UI edit is its own undo point
(app process only), auto-before-* pruned to the newest 200. Legacy takes resolve and render exactly as before; opening
one keeps the draft's preset named. Two reviews (Opus); the blocker and every should-fix fixed with tests.

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

Diffstat:
Mumtool/app/api/report/play-view/route.ts | 2+-
Aumtool/app/api/report/takes/open/route.ts | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/takes/save/route.ts | 32++++++++++++++++++++++++++++++++
Mumtool/components/projects/AddClip.tsx | 46++++++++++++++--------------------------------
Mumtool/components/projects/ClipBench.tsx | 15+--------------
Mumtool/components/projects/NewTakePanel.tsx | 12++++++++----
Aumtool/components/projects/OpenInDraftPage.tsx | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/PlayCutPage.tsx | 4++--
Mumtool/components/projects/PlayLink.tsx | 9++++-----
Mumtool/components/projects/PostAttachmentLane.tsx | 2+-
Mumtool/components/projects/PostBench.tsx | 6++----
Mumtool/components/projects/PostBenchPage.tsx | 42++++++++++--------------------------------
Mumtool/components/projects/PostComboPanel.tsx | 4+---
Mumtool/components/projects/PostNarrationPanel.tsx | 35++++-------------------------------
Mumtool/components/projects/PostThreadPanel.tsx | 9---------
Mumtool/components/projects/PostZoomPanel.tsx | 4+---
Mumtool/components/projects/ProjectPrimary.tsx | 49+++++++++++++++++++++++--------------------------
Mumtool/components/projects/ProjectView.tsx | 12++++++------
Aumtool/components/projects/SaveVersionButton.tsx | 45+++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/TakeActions.tsx | 24+++++++++++++++---------
Mumtool/components/projects/TakeTools.tsx | 16+++++++++-------
Dumtool/components/projects/TakeWalkPage.tsx | 161-------------------------------------------------------------------------------
Mumtool/components/projects/TakesBench.tsx | 18+++++++++---------
Mumtool/components/projects/TakesPage.tsx | 3+--
Dumtool/components/projects/bench/TakeWalkStrip.tsx | 140-------------------------------------------------------------------------------
Dumtool/components/projects/inTake.tsx | 16----------------
Mumtool/components/projects/present/PresentView.tsx | 2+-
Mumtool/components/projects/report/CutTab.tsx | 19+++++++++----------
Mumtool/components/projects/review/PlayCut.tsx | 127++++++++++++++++++++++++++++++++++++++++++-------------------------------------
Mumtool/components/projects/review/WhatPlays.tsx | 102+++++++++++++++++++++++++++++++++++++------------------------------------------
Mumtool/docs/cli.md | 1+
Mumtool/docs/clip-bench.md | 166+++++++------------------------------------------------------------------------
Mumtool/docs/knobs.md | 115++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------
Mumtool/docs/report-video.md | 5+++++
Mumtool/e2e/cut-sections.spec.ts | 9++++++++-
Aumtool/e2e/draft-versions.spec.ts | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 19+++++++++++++++++++
Mumtool/e2e/fixtures/play-cut-fixture.mjs | 24+++++++++++++++++++++++-
Mumtool/e2e/fixtures/take-walk-fixture.mjs | 19++++++++++++++++++-
Mumtool/e2e/intro-play.spec.ts | 22++++++++++------------
Mumtool/e2e/phone-walk.spec.ts | 18+++++++++---------
Mumtool/e2e/play-cut.spec.ts | 13+++++++++++++
Mumtool/e2e/play-take-edit.spec.ts | 118+++++++++++++++++++++++++++++++++++++++++++------------------------------------
Mumtool/e2e/play-walk.spec.ts | 42++++++++++++++++++++++--------------------
Mumtool/e2e/post-items.spec.ts | 20++++++++++----------
Mumtool/e2e/post-narration.spec.ts | 25++++++++-----------------
Mumtool/e2e/take-walk.spec.ts | 92++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mumtool/e2e/undo.spec.ts | 28++++++++++++++++++++++++++++
Mumtool/instrumentation.ts | 10++++++++++
Mumtool/lib/hrefs.ts | 24++++++++++++++++++++++++
Mumtool/lib/report/benchData.ts | 3+--
Mumtool/lib/report/introCli.mjs | 5+++--
Mumtool/lib/report/introEdit.mjs | 43+++++++++++++++++++++++++++++++------------
Mumtool/lib/report/introEdit.test.mjs | 6++++++
Mumtool/lib/report/manifest.mjs | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Mumtool/lib/report/playView.mjs | 38++++++++++++++++++++++++--------------
Mumtool/lib/report/present.mjs | 2+-
Mumtool/lib/report/present.test.mjs | 2+-
Mumtool/lib/report/presentCli.mjs | 4++--
Aumtool/lib/report/sameOrigin.mjs | 27+++++++++++++++++++++++++++
Aumtool/lib/report/sameOrigin.test.mjs | 17+++++++++++++++++
Mumtool/lib/report/snapshots.mjs | 30++++++++++++++++++++++++------
Mumtool/lib/report/takeCli.mjs | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/takeEdit.mjs | 35++++++++++++++++++++++++++++++++++-
Mumtool/lib/report/takeMaker.mjs | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mumtool/lib/report/takeManifest.mjs | 80++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mumtool/lib/report/takes.mjs | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/takes.test.mjs | 2++
Aumtool/lib/report/versions.mjs | 484+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/versions.test.mjs | 498+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/workingCut.mjs | 146++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
71 files changed, 2618 insertions(+), 1124 deletions(-)

diff --git a/umtool/app/api/report/play-view/route.ts b/umtool/app/api/report/play-view/route.ts @@ -5,7 +5,7 @@ export const dynamic = "force-dynamic"; // PLAY'S VIEW as JSON (lib/report/playView.mjs): what `/projects/<p>/play` renders, read again // in place after an edit (components/projects/review/PlayCut.tsx reloadView) rather than by a -// router refresh. GET ?project=<id>[&take=<id> | &cut=1]; no take: the latest take. +// router refresh. GET ?project=<id>[&take=<id> | &cut=1]; no take: the draft (the manifest). export async function GET(request: Request) { const q = new URL(request.url).searchParams; const project = await projectRef(q.get("project") ?? ""); diff --git a/umtool/app/api/report/takes/open/route.ts b/umtool/app/api/report/takes/open/route.ts @@ -0,0 +1,60 @@ +import { invalidateProjects, projectRef } from "@/lib/projects"; +import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; +import { StaleToken, StructureRefused } from "@/lib/report/manifest.mjs"; +import { isTakeId } from "@/lib/report/takes.mjs"; +import { VersionRefused, openVersion } from "@/lib/report/versions.mjs"; + +export const dynamic = "force-dynamic"; + +// OPEN A VERSION IN THE DRAFT (lib/report/versions.mjs openVersion; the CLI +// twin is `umtool takes open <p> <take>`). The draft is saved first as the +// next version when it has edits since its parent; the version is then +// written over the draft with one undo point ("Undo open <take>": the Cut +// tab's Undo last edit, `umtool timeline <p> undo`). The pick is untouched. +// +// POST JSON { project, take, token? } -> { ok, opened, how, saved, snapshot, token } +// POST a FORM (the Open in draft page's button, no script needed) with +// project, take, token, next (where to land: a /projects/… address), back +// -> 303 to `next`; refused -> 303 to `back` with `?error=<why>`. +// +// A stale token is a 409 (the draft changed since the page was read). +const isForm = (request: Request) => /application\/x-www-form-urlencoded|multipart\/form-data/.test(request.headers.get("content-type") ?? ""); +const local = (v: unknown) => (typeof v === "string" && v.startsWith("/projects/") && !v.startsWith("//") ? v : null); + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/takes/open"); + if (refused) return refused; + // A plain form carries no token: a write another site's page posts is refused (lib/report/sameOrigin.mjs). + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); + const form = isForm(request); + let body: Record<string, unknown> | null = null; + if (form) { + const f = await request.formData().catch(() => null); + body = f ? Object.fromEntries([...f.entries()].map(([k, v]) => [k, typeof v === "string" ? v : ""])) : null; + } else body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return Response.json({ error: "bad body" }, { status: 400 }); + const back = local(body.back); + const fail = (status: number, error: string, extra: Record<string, unknown> = {}) => { + if (form && back) return new Response(null, { status: 303, headers: { location: `${back}${back.includes("?") ? "&" : "?"}error=${encodeURIComponent(error)}` } }); + return Response.json({ error, ...extra }, { status }); + }; + if (!isTakeId(body.take)) return fail(400, "take must be a take id"); + const project = await projectRef(String(body.project ?? "")); + if (!project) return fail(404, "no such project"); + const token = body.token === undefined || body.token === null || body.token === "" ? null : String(body.token); + try { + const r = await openVersion(project, body.take, { token }); + invalidateProjects(); + const next = local(body.next); + if (form) return new Response(null, { status: 303, headers: { location: next ?? `/projects/${project.id}/play` } }); + return Response.json({ ok: true, ...r }, { headers: { "cache-control": "no-store" } }); + } catch (e) { + if (e instanceof StaleToken) return fail(409, "the draft changed since this page was read — look again", { stale: true }); + if (e instanceof StructureRefused) return fail(400, e.message, { errors: (e as unknown as { errors?: string[] }).errors ?? [] }); + const message = e instanceof Error ? e.message : String(e); + if (e instanceof VersionRefused) return fail(/^no take /.test(message) ? 404 : 400, message); + return fail(500, message); + } +} diff --git a/umtool/app/api/report/takes/save/route.ts b/umtool/app/api/report/takes/save/route.ts @@ -0,0 +1,32 @@ +import { invalidateProjects, projectRef } from "@/lib/projects"; +import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; +import { VersionRefused, saveVersion } from "@/lib/report/versions.mjs"; + +export const dynamic = "force-dynamic"; + +// SAVE THE DRAFT AS A VERSION (lib/report/versions.mjs saveVersion; the CLI +// twin is `umtool takes save <p> [--label L] [--force]`): video.manifest.json +// frozen byte for byte as the next v<N>, named the draft's parent. Nothing is +// saved when the draft has no edits since its parent (`saved: false`) unless +// `force`. The pick is never touched. +// +// POST { project, label?, force? } -> { ok, saved, id, label?, why? } +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/takes/save"); + if (refused) return refused; + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); + const body = (await request.json().catch(() => null)) as { project?: unknown; label?: unknown; force?: unknown } | null; + if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 }); + const project = await projectRef(String(body.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + try { + const r = await saveVersion(project, { label: typeof body.label === "string" ? body.label : null, force: body.force === true }); + invalidateProjects(); + return Response.json({ ok: true, ...r }, { headers: { "cache-control": "no-store" } }); + } catch (e) { + const message = e instanceof Error ? e.message : String(e); + return Response.json({ error: message }, { status: e instanceof VersionRefused ? 400 : 500 }); + } +} diff --git a/umtool/components/projects/AddClip.tsx b/umtool/components/projects/AddClip.tsx @@ -18,13 +18,13 @@ import { announceManifestChanged, refusalOf, timelineOp, type TimelineResult } f // to end there; nudge ±0.5 s; the quote is read from the cues // 3 Place after <row> -- by default where the clip's date falls when the // cut is in date order, else after the row it was opened from -// 4 Add the timeline's own insert (the project's, or with `take` the -// take's patch only: "add to this take only"), then the clip's +// 4 Add the timeline's own insert -- the draft's (L3: a take is a +// frozen version; "add to this take only" is retired), then the clip's // window fetched through the editor's paced fetch // (POST /api/report/fetch) -- never yt-dlp by hand // // Opened from the Cut tab, from Play at the playhead's item ("Add a clip -// here") and from a take. The old one-line spec form stays as the Cut +// here"). The old one-line spec form stays as the Cut // tab's "Add by spec". // --------------------------------------------------------------------------- @@ -91,15 +91,12 @@ export function dateOrderAfter(entries: Entry[], date: string | null): string | export default function AddClip({ project, - take = null, after: afterProp = null, onClose, onAdded, className, }: { project: string; - /** "Add to this take only": the take's patch, never the project's manifest. */ - take?: string | null; /** The row it was opened from (Play's playhead item): the default place when the cut is not in date order. */ after?: string | null; onClose?: () => void; @@ -135,9 +132,7 @@ export default function AddClip({ }, [cues]); const loadEntries = useCallback(async () => { - const url = take - ? `/api/report/takes/timeline?project=${encodeURIComponent(project)}&take=${encodeURIComponent(take)}` - : `/api/report/timeline?project=${encodeURIComponent(project)}`; + const url = `/api/report/timeline?project=${encodeURIComponent(project)}`; const r = await fetch(url, { cache: "no-store" }); const j = await r.json().catch(() => ({})); if (!r.ok) { @@ -147,7 +142,7 @@ export default function AddClip({ setEntries(Array.isArray(j.timeline) ? j.timeline : []); setToken(typeof j.token === "string" ? j.token : null); return j as { token?: string }; - }, [project, take]); + }, [project]); useEffect(() => { void loadEntries(); }, [loadEntries]); @@ -269,17 +264,7 @@ export default function AddClip({ setError(null); const entry: Record<string, unknown> = newClipEntry({ video: moment.video, ownChannel: moment.channel }, { start, end, quote }); if (moment.date) entry.date = moment.date; - let res: TimelineResult; - if (take) { - const r = await fetch("/api/report/takes/timeline", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ project, take, token, op: "insert", afterId: after || null, entry }), - }); - res = { ok: r.ok, status: r.status, json: await r.json().catch(() => ({ error: `HTTP ${r.status}` })) }; - } else { - res = await timelineOp(project, token ?? ((await loadEntries())?.token ?? null), "insert", { afterId: after || null, entry }); - } + const res: TimelineResult = await timelineOp(project, token ?? ((await loadEntries())?.token ?? null), "insert", { afterId: after || null, entry }); setBusy(false); if (!res.ok) { setError(refusalOf(res)); @@ -288,7 +273,7 @@ export default function AddClip({ } const id = typeof res.json.id === "string" ? res.json.id : null; setAdded(id); - if (!take) announceManifestChanged(project); + announceManifestChanged(project); await loadEntries(); router.refresh(); if (id) { @@ -302,7 +287,7 @@ export default function AddClip({ const r = await fetch("/api/report/fetch", { method: "POST", headers: { "content-type": "application/json" }, - body: JSON.stringify({ project, clip: id, padBefore: 20, padAfter: 20, ...(take ? { take } : {}) }), + body: JSON.stringify({ project, clip: id, padBefore: 20, padAfter: 20 }), }); const j = (await r.json().catch(() => ({}))) as { error?: string; job?: { id: string }; cachedBefore?: number; cachedPad?: number }; if (r.status === 409 && (j.cachedBefore !== undefined || j.cachedPad !== undefined)) return setFetchState({ state: "done", msg: "already fetched" }); @@ -337,9 +322,9 @@ export default function AddClip({ const nudge = (which: "in" | "out", d: number) => (which === "in" ? setStart((s) => (s === null ? s : r2(Math.max(0, s + d)))) : setEnd((s) => (s === null ? s : r2(s + d)))); return ( - <section data-add-clip={take ?? "cut"} className={cn("space-y-2 rounded border border-seam bg-panel p-3 text-[12px]", className)}> + <section data-add-clip="cut" className={cn("space-y-2 rounded border border-seam bg-panel p-3 text-[12px]", className)}> <div className="flex flex-wrap items-center gap-2"> - <h2 className="micro m-0">{take ? `Add a clip to take ${take} only` : "Add a clip"}</h2> + <h2 className="micro m-0">Add a clip</h2> <span className="text-muted">1 find · 2 in/out · 3 place · 4 add</span> {onClose && ( <button type="button" data-add-clip-close="" onClick={onClose} className={cn(buttonVariants({ variant: "quiet", size: "sm" }), "ml-auto")}> @@ -480,7 +465,7 @@ export default function AddClip({ </label> {placeWhy && <span className="text-muted" data-add-clip-place-why="">{placeWhy}</span>} <button type="button" data-add-clip-submit="" disabled={busy || !valid} onClick={() => void add()} className={buttonVariants({ variant: "go", size: "sm" })}> - {take ? `Add to ${take} only` : "Add to the cut"} + Add to the cut </button> </div> </div> @@ -494,8 +479,7 @@ export default function AddClip({ {added && ( <p className="m-0 flex flex-wrap items-center gap-2 text-text-2" data-add-clip-added={added} data-add-clip-fetch={fetchState.state}> <span> - Added <b className="font-mono">{added}</b> - {take ? ` to take ${take}` : ""}. + Added <b className="font-mono">{added}</b>. </span> {fetchState.state !== "idle" && <span className={fetchState.state === "failed" ? "text-reject-text" : "text-muted"}>{fetchState.msg}</span>} {fetchState.state === "failed" && ( @@ -512,7 +496,6 @@ export default function AddClip({ /** "+ Add a clip": the button and, pressed, the panel (open from the start with `open`, e.g. the head's `?add=1`). */ export function AddClipToggle({ project, - take = null, after = null, open: initiallyOpen = false, label, @@ -521,7 +504,6 @@ export function AddClipToggle({ className, }: { project: string; - take?: string | null; after?: string | null; onAdded?: (id: string) => void; open?: boolean; @@ -534,9 +516,9 @@ export function AddClipToggle({ return ( <> <button type="button" data-add-clip-open={where} aria-expanded={open} onClick={() => setOpen((o) => !o)} className={cn(buttonVariants({ variant: open ? "pressed" : "outline", size: "sm" }), className)}> - {label ?? (take ? `+ Add a clip to ${take} only` : "+ Add a clip")} + {label ?? "+ Add a clip"} </button> - {open && <AddClip project={project} take={take} after={after} onAdded={onAdded} onClose={() => setOpen(false)} className="basis-full" />} + {open && <AddClip project={project} after={after} onAdded={onAdded} onClose={() => setOpen(false)} className="basis-full" />} </> ); } diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -25,7 +25,6 @@ import { ClipExportButtons, ClipExportStatus, useClipExport } from "./ClipExport import EdgeStrip from "./bench/EdgeStrip"; import RenderGhosts, { useRenderEdges } from "./bench/RenderGhosts"; import { ZoomControls, ZoomOverview, ZoomRuler, useWaveZoom, type Span } from "./bench/GapsZoom"; -import TakeWalkStrip from "./bench/TakeWalkStrip"; import { TightenButtons, useEdgeTools, type BenchWord } from "./bench/TightenTools"; // The renderer's own line, imported rather than re-written. A preview that // disagrees with the header by a character is worth less than no preview: you @@ -2967,19 +2966,7 @@ export default function ClipBench({ <GeneratedBanner generatedBy={data.generatedBy} /> </div> )} - {/* Walking a take: what is being walked, where the edits go, and the take's own structure. */} - {data.take && ( - <TakeWalkStrip - className="max-md:order-[22]" - project={data.project} - take={data.take} - clipId={clip.id} - index={data.take.at} - total={data.take.entries} - nextHref={hrefOf("next")} - getToken={() => token.current} - /> - )} + {/* A take's clip is never benched from the UI now (L3: Open in draft first); `umtool window --take` edits one. */} {/* ---- where you are, where you can go, and what will be burned in ---- */} <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] max-md:contents"> {/* On a phone both counts are the place bar's `50/51` and its hairline. */} diff --git a/umtool/components/projects/NewTakePanel.tsx b/umtool/components/projects/NewTakePanel.tsx @@ -3,7 +3,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { useRouter } from "next/navigation"; import { buttonVariants } from "@/components/ui/button"; -import { takeWalkHref } from "@/lib/hrefs"; +import { openInDraftHref, playHref } from "@/lib/hrefs"; import { Field, Input, Select, Textarea } from "@/components/ui/field"; import { JobProgress, type JobStepState } from "@/components/ui/job-progress"; import RenderModeBanner, { renderPriorityPref } from "./RenderModeBanner"; @@ -314,7 +314,7 @@ export default function NewTakePanel({ data-action="save-draft" disabled={!ready || busy || running || !label.trim() || !!patchError || windowBad} className={buttonVariants({ variant: "quiet", size: "sm" })} - title={`umtool take ${project} --id <label> --label … --draft: recorded, nothing rendered — walk it, then render it`} + title={`umtool take ${project} --id <label> --label … --draft: recorded, nothing rendered — play it, open it in the draft, render it`} onClick={() => void saveDraft()} > Save as a draft @@ -342,8 +342,12 @@ export default function NewTakePanel({ {drafted && ( <p data-take-drafted-new={drafted} className="text-[12px] text-text-2"> draft <b className="font-mono">{drafted}</b> recorded, nothing rendered:{" "} - <a href={takeWalkHref(project, drafted)} className="ink-link"> - walk it + <a href={playHref(project, { take: drafted })} className="ink-link"> + play it + </a>{" "} + ·{" "} + <a href={openInDraftHref(project, drafted)} className="ink-link"> + open in draft </a> </p> )} diff --git a/umtool/components/projects/OpenInDraftPage.tsx b/umtool/components/projects/OpenInDraftPage.tsx @@ -0,0 +1,105 @@ +import Link from "next/link"; +import { notFound, redirect } from "next/navigation"; +import { buttonVariants } from "@/components/ui/button"; +import { clipBenchHref, openInDraftHref, playHref, postBenchHref, projectsHref } from "@/lib/hrefs"; +import type { ProjectRef } from "@/lib/project-types"; +import { manifestToken } from "@/lib/report/manifest.mjs"; +import { isTakeId, listTakes } from "@/lib/report/takes.mjs"; +import { nextVersionId, openIsNoop } from "@/lib/report/versions.mjs"; +import { readWorkingCut } from "@/lib/report/workingCut.mjs"; +import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell"; + +// `/projects/<project>/takes/<take>/open` -- OPEN A VERSION IN THE DRAFT (umtool redesign L3; +// lib/report/versions.mjs openVersion). Every edit lands in the draft (the project's manifest); a saved +// version is frozen, so editing one means copying it into the draft first. When the draft already holds what +// <take> is, there is nothing to copy: a 307 straight on to the draft's bench on `clip` +// (a post item's with `post=1`), else to Play of the draft. Otherwise it asks -- "Open v1 in draft? Your +// draft (2 edits) is saved as v4 first." -- and the button is a plain form POST (no script needed) to +// /api/report/takes/open, which lands on the same place. +// +// The take walk's and the take bench's old addresses (`…/takes/<take>/walk`, `…/takes/<take>/clip/<id>`) +// are served by this page too: the walk and the bench of a version are the draft's now. + +export default async function OpenInDraftPage({ + project, + take, + clip = null, + search = {}, +}: { + project: ProjectRef; + take: string; + clip?: string | null; + search?: Record<string, string | undefined>; +}) { + if (!isTakeId(take)) notFound(); + const { takes } = await listTakes(project.dir); + const t = takes.find((x) => x.id === take); + if (!t) notFound(); + const fromPlay = search.from === "play"; + const at = Number(search.at); + const atS = Number.isFinite(at) && at > 0 ? at : null; + const where = clip ?? search.clip ?? null; + const post = search.post === "1"; + const dest = where + ? post + ? postBenchHref(project.id, where, fromPlay ? { play: { at: atS } } : {}) + : clipBenchHref(project.id, where, fromPlay ? { play: { at: atS, take: null } } : {}) + : playHref(project.id); + const working = await readWorkingCut(project.dir); + const edits = working.edits?.count ?? null; + // Nothing to copy (the draft already holds what the take is): straight on. A 307, not a 308 -- the answer + // depends on the draft as it is now, and a browser must never remember it. + if (await openIsNoop(project.dir, take)) redirect(dest); + const willSave = !working.parent || working.edits === null || (edits ?? 0) > 0; + const next = await nextVersionId(project.dir); + const here = openInDraftHref(project.id, take, { clip: where, post, play: fromPlay ? { at: atS } : null }); + const draftWords = !working.parent + ? "Your draft (never saved)" + : edits === null + ? `Your draft (from ${working.parent.id}, its edits unknown)` + : `Your draft (${edits} edit${edits === 1 ? "" : "s"} since ${working.parent.id})`; + return ( + <BenchFrame + kind="open-draft" + top={<BenchTop trail={[{ href: projectsHref(), label: "Projects" }]} back={{ href: playHref(project.id, { take }), label: `${project.name} · ${take}` }} kind="Open in draft" here={take} />} + > + <BenchBody workClassName="space-y-3 overflow-y-auto"> + <section data-open-draft={take} data-open-draft-saves={willSave ? next : ""} className="max-w-[640px] space-y-3"> + <h1 className="text-[16px] font-semibold text-text">Open {take} in draft?</h1> + <p className="text-[13px] text-text-2" data-open-draft-said=""> + {willSave ? ( + <> + {draftWords} is saved as <span className="font-mono font-medium text-text">{next}</span> first. + </> + ) : ( + <>Your draft has no edits since {working.parent?.id} — nothing to save.</> + )}{" "} + Then <span className="font-mono">{take}</span> — “{t.label}” — is copied into the draft{where ? <>, and the bench opens on <span className="font-mono">{where}</span></> : ""}. One undo + (the Cut tab&apos;s Undo last edit) puts the draft back as it was. + </p> + {search.error && ( + <p className="text-[12px] text-reject-text" data-open-draft-error=""> + {search.error} + </p> + )} + <form method="post" action="/api/report/takes/open" className="flex flex-wrap items-center gap-2"> + <input type="hidden" name="project" value={project.id} /> + <input type="hidden" name="take" value={take} /> + <input type="hidden" name="token" value={(await manifestToken(project.dir)) ?? ""} /> + <input type="hidden" name="next" value={dest} /> + <input type="hidden" name="back" value={here} /> + <button type="submit" data-open-draft-confirm="" className={buttonVariants({ variant: "go", size: "md" })}> + Open {take} in draft + </button> + <Link href={playHref(project.id, { take })} data-open-draft-cancel="" className={buttonVariants({ variant: "quiet", size: "md" })}> + Cancel — play {take} + </Link> + </form> + <p className="text-[11.5px] text-muted"> + The same from a terminal: <code className="font-mono">umtool takes open {project.id} {take}</code> + </p> + </section> + </BenchBody> + </BenchFrame> + ); +} diff --git a/umtool/components/projects/PlayCutPage.tsx b/umtool/components/projects/PlayCutPage.tsx @@ -28,7 +28,7 @@ export default async function PlayCutPage({ }: { project: ProjectRef; take?: string; - /** `?cut=1`: the project's manifest alone, no take's patch (the default is the latest take). */ + /** `?cut=1`: the draft, the project's manifest (the default as well, since saved versions). */ bare?: boolean; note?: string; /** `?clip=<id>&at=<s>`: start on that clip, that far into it (the clip bench's "Back to the cut"). */ @@ -41,7 +41,7 @@ export default async function PlayCutPage({ trail={[{ href: projectsHref(), label: "Projects" }]} back={{ href: back, label: project.id }} kind="Play the cut" - here={"error" in view || !view.take ? "the manifest" : view.take.defaulted ? `latest · ${view.take.id}` : `take ${view.take.id}`} + here={"error" in view ? "the draft" : view.take ? `version ${view.take.id} · read-only` : (view.draft?.line ?? "the draft")} /> ); if ("error" in view) { diff --git a/umtool/components/projects/PlayLink.tsx b/umtool/components/projects/PlayLink.tsx @@ -9,9 +9,8 @@ import { cn } from "@/lib/utils"; // just entering the /play page"). // // One link, one address builder (lib/hrefs.ts playHref): with no take it lands -// on Play of the NEWEST take (the working cut, lib/report/workingCut.mjs -- -// "the latest draft is the working cut"), with a take on that take, with a clip -// at that item. Every surface that names a cut or a take wears this rather +// on Play of THE DRAFT (the project's manifest, where every edit lands -- L3), +// with a take on that saved version (read-only), with a clip at that item. Every surface that names a cut or a take wears this rather // than a hand-built `/play` link, so no surface leaves the operator typing it. // // `where` is the surface (`header`, `row`, `take-card`, `walk`, `jobs`, `rail`, @@ -33,7 +32,7 @@ export default function PlayLink({ className, }: { project: string; - /** A take id; null plays the newest take. */ + /** A version's id; null plays the draft. */ take?: string | null; /** Start on this item (a clip or a post item's id). */ clip?: string | null; @@ -65,7 +64,7 @@ export default function PlayLink({ data-play-link-take={take ?? ""} data-play-link-clip={clip ?? ""} aria-label={variant === "icon" ? (clip ? `play from ${clip}` : take ? `play ${take}` : "play the newest take") : undefined} - title={title ?? (clip ? `play the newest take from ${clip}` : take ? `play take ${take} in the browser, no render` : "play the newest take in the browser, no render")} + title={title ?? (clip ? `play the draft from ${clip}` : take ? `play version ${take} in the browser, read-only, no render` : "play the working draft in the browser, no render")} className={cn(look, className)} > {words} diff --git a/umtool/components/projects/PostAttachmentLane.tsx b/umtool/components/projects/PostAttachmentLane.tsx @@ -14,7 +14,7 @@ import type { PostPlan } from "./review/PostItemPlayer"; // as the waveform's two handles, the part the item plays dashed, and the playhead. // // The handles move `media[i].start` / `.end` as the number fields do (the bench's -// draft, saved by its Save -- the take's patch on ?inTake=), never closer than +// draft, saved by its Save), never closer than // POST_MEDIA_MIN_SPAN and never past the file. While a handle moves, the bench's // clock follows the edge, so the player shows its frame. Keys, with the lane // focused: [ ] the in, , . the out (0.05 s; Shift 0.5 s, the clip bench's), and diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -1,6 +1,5 @@ "use client"; -import { inTakeBody, useInTake } from "./inTake"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -113,7 +112,6 @@ export default function PostBench({ /** The posts its conversation's run leaves on screen (post-conversation.mjs planContext): kept on top or collapsed away. It wins the card over a media scene. */ conversation?: Record<string, unknown> | null; }) { - const inTake = useInTake(); const router = useRouter(); const [entry, setEntry] = useState<Entry>(initial); const [saved, setSaved] = useState<Entry>(initial); @@ -243,7 +241,7 @@ export default function PostBench({ const res = await fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, - body: JSON.stringify({ project, op: "set", id: entry.id, patch: patchOf(entry), token, ...inTakeBody(inTake) }), + body: JSON.stringify({ project, op: "set", id: entry.id, patch: patchOf(entry), token }), }); const j = (await res.json().catch(() => ({}))) as { entry?: Entry; token?: string; error?: string; errors?: string[] }; if (!res.ok || !j.entry) { @@ -263,7 +261,7 @@ export default function PostBench({ const [jobs, setJobs] = useState<Record<number, { job: string; state: string; error?: string }>>({}); const transcribe = async (i: number) => { setError(null); - const res = await fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "transcribe", id: entry.id, media: i, ...inTakeBody(inTake) }) }); + const res = await fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "transcribe", id: entry.id, media: i }) }); const j = (await res.json().catch(() => ({}))) as { jobId?: string; error?: string }; if (!res.ok || !j.jobId) { setJobs((x) => ({ ...x, [i]: { job: "", state: "failed", error: j.error ?? `HTTP ${res.status}` } })); diff --git a/umtool/components/projects/PostBenchPage.tsx b/umtool/components/projects/PostBenchPage.tsx @@ -5,11 +5,6 @@ import { channelsDirFor, readManifest } from "@/lib/projects/report.mjs"; import { manifestToken } from "@/lib/report/manifest.mjs"; import { projectHref, playHref } from "@/lib/hrefs"; import PlayLink from "./PlayLink"; -import Link from "next/link"; -import { InTakeProvider } from "./inTake"; -import { postBenchHref } from "@/lib/hrefs"; -import { withTakeScope } from "@/lib/report/takeScope.mjs"; -import { isTakeId, listTakes } from "@/lib/report/takes.mjs"; import { deckGeometry, deckOn, feedGeometry, feedOn } from "umtool-report-to-video/deck"; import { postItemPlan, panelEntry } from "umtool-report-to-video/post-item"; import { planContext } from "umtool-report-to-video/post-conversation"; @@ -26,21 +21,14 @@ import type { ComboInfo } from "./review/ComboBadge"; // words through the editor's transcription. Every save is updatePostItem // (POST /api/report/post-item {op: "set"}), the writer `umtool posts set-item` runs. -// "EDIT THIS TAKE ONLY" (lane/ui-simplify): `?inTake=<take>` reads the item as the take has it and scopes every -// write of the bench to the take's patch (takeScope.mjs, the CLI's `--in-take`); the project's cut is untouched. +// THE BENCH EDITS THE DRAFT (umtool redesign L3): every save lands in the project's manifest. The take-only +// scope (lane/ui-simplify's "edit this take only" query) is retired from the page -- an old address with it is +// the draft's bench -- and stays for agents as the CLI's `--in-take`. export default async function PostBenchPage({ project, id, search = {} }: { project: ProjectRef; id: string; search?: Record<string, string | undefined> }) { - const inTake = search.inTake && isTakeId(search.inTake) ? search.inTake : null; - const takes = ((await listTakes(project.dir)).takes as { id: string; builtAt?: string | null; draft?: boolean }[]) - .filter((t) => t.builtAt || t.draft) - .sort((a, b) => String(b.builtAt ?? "").localeCompare(String(a.builtAt ?? ""))) - .slice(0, 6) - .map((t) => t.id); - if (inTake && !takes.includes(inTake)) takes.unshift(inTake); - const body = () => postBenchBody({ project, id, search, inTake, takes }); - return inTake ? withTakeScope(project.dir, inTake, body) : body(); + return postBenchBody({ project, id, search }); } -async function postBenchBody({ project, id, search, inTake, takes }: { project: ProjectRef; id: string; search: Record<string, string | undefined>; inTake: string | null; takes: string[] }) { +async function postBenchBody({ project, id, search }: { project: ProjectRef; id: string; search: Record<string, string | undefined> }) { const m = (await readManifest(project.dir)) as Record<string, unknown> | null; if (!m) notFound(); const tl = (Array.isArray(m.timeline) ? m.timeline : []) as Array<Record<string, unknown> & { id: string; type?: string }>; @@ -62,30 +50,21 @@ async function postBenchBody({ project, id, search, inTake, takes }: { project: const combo = combos[id] ?? null; // Its media scene (post-media-scene.mjs): its neighbours with the same attachment, by the combo's groups. const scene = mediaSceneOf(tl, at, counted.groups, render); - const back = fromPlay ? playHref(project.id, { take: inTake, clip: id, at: Number(search.at ?? 0) || null }) : projectHref(project.id, { tab: "cut" }); + const back = fromPlay ? playHref(project.id, { clip: id, at: Number(search.at ?? 0) || null }) : projectHref(project.id, { tab: "cut" }); return ( <div className="flex h-full flex-col"> <AppShell active="projects" crumbs={[{ href: "/projects", label: "Projects" }, { href: projectHref(project.id), label: project.name }, { label: `post ${id}` }]} note={`post item ${k + 1} of ${neighbours.length} · ${String(entry.post ?? "")}`} - actions={<PlayLink project={project.id} take={inTake} clip={id} where="post-bench" variant="header" label="▶ Play from here" />} + actions={<PlayLink project={project.id} clip={id} where="post-bench" variant="header" label="▶ Play from here" />} /> <main className="deck-main flex-1 overflow-auto p-4"> - {/* Where the bench's edits go: the cut, or one take only. */} - <p className="mb-2 flex flex-wrap items-center gap-2 text-[12px]" data-post-bench-scope={inTake ?? "cut"}> + {/* Where the bench's edits go: the draft. */} + <p className="mb-2 flex flex-wrap items-center gap-2 text-[12px]" data-post-bench-scope="cut"> <span className="micro">edits go to</span> - <Link href={postBenchHref(project.id, id)} aria-current={!inTake ? "page" : undefined} className={!inTake ? "font-medium text-text" : "ink-link"} data-post-bench-scope-link=""> - the cut - </Link> - {takes.map((t) => ( - <Link key={t} href={`${postBenchHref(project.id, id)}?inTake=${encodeURIComponent(t)}`} aria-current={inTake === t ? "page" : undefined} className={inTake === t ? "font-medium text-text" : "ink-link"} data-post-bench-scope-link={t}> - take {t} only - </Link> - ))} - {inTake && <span className="text-doubt-text">editing take {inTake} only — the cut and its other takes are untouched; reads are re-made on the cut&apos;s bench</span>} + <span className="font-medium text-text">the draft</span> </p> - <InTakeProvider take={inTake}> <PostBench project={project.id} entry={entry} @@ -102,7 +81,6 @@ async function postBenchBody({ project, id, search, inTake, takes }: { project: next={k < neighbours.length - 1 ? neighbours[k + 1] : null} fromPlay={fromPlay} /> - </InTakeProvider> </main> </div> ); diff --git a/umtool/components/projects/PostComboPanel.tsx b/umtool/components/projects/PostComboPanel.tsx @@ -1,6 +1,5 @@ "use client"; -import { inTakeBody, useInTake } from "./inTake"; import Link from "next/link"; import { useState } from "react"; import { postBenchHref } from "@/lib/hrefs"; @@ -29,7 +28,6 @@ export default function PostComboPanel({ render: Record<string, unknown>; onEntry: (entry: Record<string, unknown> & { id: string }, token: string | null) => void; }) { - const inTake = useInTake(); const [error, setError] = useState<string | null>(null); const [busy, setBusy] = useState(false); // The box follows the click at once; the write's answer settles it (a refusal puts it back). @@ -44,7 +42,7 @@ export default function PostComboPanel({ const res = await fetch("/api/report/post-combo", { method: "POST", headers: { "content-type": "application/json" }, - body: JSON.stringify({ project, op: "set", id: entry.id, combo: on ? null : false, token, ...inTakeBody(inTake) }), + body: JSON.stringify({ project, op: "set", id: entry.id, combo: on ? null : false, token }), }); const j = (await res.json().catch(() => ({}))) as { entry?: Record<string, unknown> & { id: string }; token?: string; error?: string; errors?: string[] }; setBusy(false); diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx @@ -1,7 +1,6 @@ "use client"; import { Options } from "@/components/ui/disclosure"; -import { inTakeBody, useInTake } from "./inTake"; import Link from "next/link"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import Waveform from "@/components/Waveform"; @@ -25,8 +24,7 @@ import PostAttachmentLane from "./PostAttachmentLane"; // handles, PostAttachmentLane: the bench's draft, as its number // fields; Re-pick best: posts fit's scan), and the read on the // item's clock -- the take's waveform from its lead (drag it), -// the muffle under it, the ramp back to clean. On the take-only -// bench (?inTake) too, every write the take's +// the muffle under it, the ramp back to clean // record THE RECORDING SESSION (operator, 2 Nov: "I think I'll record my // voice"): the mic, a level meter, a 3-2-1 count-in, the script as // a teleprompter PART BY PART (Record / Stop / Redo part / Next @@ -67,7 +65,6 @@ export default function PostNarrationPanel({ next: string | null; fromPlay: boolean; }) { - const inTake = useInTake(); const n = entry.narration ?? {}; const takes = n.takes ?? []; const picked = pickedTake(entry) as (Take & { index: number }) | null; @@ -82,7 +79,7 @@ export default function PostNarrationPanel({ const post = useCallback( async (body: Record<string, unknown>) => { setError(null); - const res = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, id: entry.id, token, ...body, ...inTakeBody(inTake) }) }); + const res = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, id: entry.id, token, ...body }) }); const j = (await res.json().catch(() => ({}))) as { entry?: Entry; token?: string; error?: string; errors?: string[]; jobId?: string; file?: string; untouched?: boolean; why?: string; window?: Narration["window"] }; if (!res.ok) { setError(j.errors?.join("; ") ?? j.error ?? `HTTP ${res.status}`); @@ -91,7 +88,7 @@ export default function PostNarrationPanel({ if (j.entry) onEntry(j.entry, j.token ?? null); return j; }, - [project, entry.id, token, onEntry, inTake], + [project, entry.id, token, onEntry], ); const set = (patch: Record<string, unknown>) => post({ op: "set", patch }).then((j) => j && setStatus("saved")); @@ -336,8 +333,7 @@ export default function PostNarrationPanel({ </label> ); - // THE LANES: each attachment's window, the read on the item's clock -- on the take-only bench too (every write - // through the take: the trim is the bench's draft, saved with inTake; the lead and Re-pick best post inTake). + // THE LANES: each attachment's window, the read on the item's clock (every write the draft's). const lanes = timed.length || (sch && picked) ? ( <section className="space-y-1.5 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3" data-post-lanes=""> @@ -412,29 +408,6 @@ export default function PostNarrationPanel({ </section> ) : null; - // A take-scoped bench (?inTake): a read is made for the cut here; a take's own read is \`umtool posts narrate … --in-take <t>\`. - // Pauses in the picked read (postPause.mjs) are no TTS, so they are made here too, on the take's own read. - if (inTake) - return ( - <div className="space-y-2 text-[12.5px]" data-post-narration-in-take={inTake}> - <p className="m-0 text-[12px] text-muted" data-post-bench-in-take-note=""> - Recording, re-takes and the mix are made on the cut&apos;s bench (edits go to: the cut); take {inTake} keeps the reads it has. The lanes, the pauses and a re-voiced phrase here edit the take. - </p> - {lanes} - {picked && ( - <Options id="post-reread" label="Re-join the read (no TTS)" hint="pauses after words · re-voice a phrase"> - <PauseAfter post={post} hasWords={!!picked.words?.length} setStatus={setStatus} /> - {picked.engine !== "recorded" && <RevoicePhrase post={post} hasWords={!!picked.words?.length} setStatus={setStatus} />} - </Options> - )} - {status && <p className="m-0 text-text-2" data-post-narration-status="">{status}</p>} - {error && ( - <p className="m-0 text-[var(--color-blocking,#c33)]" data-post-narration-error=""> - {error} - </p> - )} - </div> - ); return ( <div className="space-y-3 text-[12.5px]" data-post-narration={entry.id} data-post-narration-plays={picked ? (picked.engine === "recorded" ? "recorded" : "synthesized") : "none"}> {/* The cut's reading: how far along, and where next. */} diff --git a/umtool/components/projects/PostThreadPanel.tsx b/umtool/components/projects/PostThreadPanel.tsx @@ -1,6 +1,5 @@ "use client"; -import { useInTake } from "./inTake"; import { useMemo, useState } from "react"; import { THREAD_DEFAULTS, THREAD_LIMITS, THREAD_MODES, partRoles, readPieces, threadKnobs, threadLayout, threadReadErrors } from "umtool-report-to-video/post-thread"; import { followKnobs } from "umtool-report-to-video/read-follow"; @@ -40,7 +39,6 @@ export default function PostThreadPanel({ setS: (s: number) => void; setEntry: (f: (e: Entry) => Entry) => void; }) { - const inTake = useInTake(); const own = (entry.thread ?? undefined) as Thread | undefined; const k = threadKnobs(entry, render) as Required<Thread>; const layout = useMemo(() => threadLayout(entry, render, { prev: before, scene }), [entry, render, before, scene]); @@ -106,13 +104,6 @@ export default function PostThreadPanel({ </label> ); if (!parents.length && !entry.quoted && !sceneTiles.length) return null; - // A take-scoped bench (?inTake): a read is made for the cut here; a take's own read is \`umtool posts narrate … --in-take <t>\`. - if (inTake) - return ( - <p className="m-0 text-[12px] text-muted" data-post-bench-in-take-note=""> - The thread read is edited on the cut&apos;s bench (edits go to: the cut); take {inTake} keeps the reads it has. - </p> - ); return ( <section className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3 text-[12px]" data-post-thread-panel="" data-threaded={layout.on ? "1" : "0"}> <div className="mb-2 flex flex-wrap items-center gap-2"> diff --git a/umtool/components/projects/PostZoomPanel.tsx b/umtool/components/projects/PostZoomPanel.tsx @@ -1,6 +1,5 @@ "use client"; -import { inTakeBody, useInTake } from "./inTake"; import { useEffect, useMemo, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; @@ -41,7 +40,6 @@ export default function PostZoomPanel({ setS: (s: number) => void; onEntry: (e: Entry, token: string | null) => void; }) { - const inTake = useInTake(); const btn = cn(buttonVariants({ variant: "outline", size: "sm" })); const [error, setError] = useState<string | null>(null); const [status, setStatus] = useState<string | null>(null); @@ -71,7 +69,7 @@ export default function PostZoomPanel({ const send = async (fx: Record<string, unknown>) => { setError(null); - const res = await fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "fx", id: entry.id, fx, token, ...inTakeBody(inTake) }) }); + const res = await fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "fx", id: entry.id, fx, token }) }); const j = (await res.json().catch(() => ({}))) as { entry?: Entry; token?: string; error?: string; errors?: string[] }; if (!res.ok || !j.entry) { setError(j.errors?.join("; ") ?? j.error ?? `HTTP ${res.status}`); diff --git a/umtool/components/projects/ProjectPrimary.tsx b/umtool/components/projects/ProjectPrimary.tsx @@ -1,36 +1,36 @@ import Link from "next/link"; import { buttonVariants } from "@/components/ui/button"; -import { clipBenchHref, projectHref, takeWalkHref, presentHref } from "@/lib/hrefs"; +import { clipBenchHref, projectHref, presentHref } from "@/lib/hrefs"; import PlayLink from "./PlayLink"; +import SaveVersionButton from "./SaveVersionButton"; import type { ClipDetail } from "./report/shared"; // --------------------------------------------------------------------------- // A report video's ONE PRIMARY ROW, in the piece head on every tab -// (lane/ui-simplify, 5 Nov): Play the newest take, Walk it, Add a clip. The -// status line beside the title says what the working cut is (primaryStatus). -// Everything else lives on the tabs, under their Options / Advanced. +// (lane/ui-simplify, 5 Nov; the working draft, L3): Play the draft, Walk its +// clips, Save version, Add a clip. Every edit lands in the draft (the +// project's manifest); a saved version is frozen and played read-only from +// Play's version switch. `words` says what the draft is from ("from v5 · 3 edits"). // --------------------------------------------------------------------------- -type Working = { latest: { id: string; seconds: number | null; builtAt: string | null } | null } | null; +type Working = { + latest: { id: string; seconds: number | null; builtAt: string | null } | null; + parent?: { id: string } | null; + edits?: { count: number } | null; +} | null; -const mmss = (s: number | null | undefined) => (typeof s === "number" ? `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}` : null); -const day = (iso: string | null | undefined) => { - if (!iso) return null; - const d = new Date(iso); - return Number.isNaN(d.getTime()) ? null : d.toLocaleDateString("en-GB", { day: "numeric", month: "short" }); -}; - -/** The head's status: "7 open notes · <the cut's own status>" (the newest take is named on the primary row). */ +/** The head's status: "7 open notes · <the cut's own status>". */ export function primaryStatus(working: Working, openNotes: number, cut: string): string { void working; return `${openNotes} open note${openNotes === 1 ? "" : "s"} · ${cut}`; } -/** "29:50 · rendered 1 Nov": the newest take, beside its Play. */ +/** "from v5 · 3 edits" / "unsaved": the draft, beside its Play. */ export function latestWords(working: Working): string | null { - const l = working?.latest; - if (!l) return null; - return [mmss(l.seconds), day(l.builtAt) ? `rendered ${day(l.builtAt)}` : null].filter(Boolean).join(" · ") || null; + const p = working?.parent ?? null; + if (!p) return working ? "unsaved" : null; + const e = working?.edits; + return `from ${p.id} · ${!e ? "edits unknown" : e.count === 0 ? "no edits" : `${e.count} edit${e.count === 1 ? "" : "s"}`}`; } export default function ProjectPrimary({ project, detail, latest, words = null }: { project: string; detail: ClipDetail; latest: string | null; words?: string | null }) { @@ -45,25 +45,22 @@ export default function ProjectPrimary({ project, detail, latest, words = null } const firstClip = entries.find((e) => e.kind === "clip")?.id ?? null; return ( <> - <PlayLink project={project} where="header" variant="header" label={latest ? `▶ Play ${latest}` : "▶ Play the cut"} /> + <PlayLink project={project} where="header" variant="header" label="▶ Play the draft" title="the working draft: every edit lands here" /> <Link href={presentHref(project)} prefetch={false} data-present-link="header" className={buttonVariants({ variant: "quiet", size: "md" })} title="the cut as slides, one at a time, navigated like a deck (present mode)"> Present </Link> {words && ( - <span className="font-mono text-[11px] text-muted" data-primary-latest={latest ?? ""}> + <span className="font-mono text-[11px] text-muted" data-primary-latest={latest ?? ""} data-primary-draft=""> {words} </span> )} - {/* A walk is of clips: a cut of posts alone has none to walk. */} - {latest && firstClip ? ( - <Link href={takeWalkHref(project, latest)} prefetch={false} data-primary-walk={latest} className={buttonVariants({ variant: "quiet", size: "md" })} title={`walk take ${latest}: its clips, a verdict each`}> - Walk - </Link> - ) : firstClip ? ( - <Link href={clipBenchHref(project, firstClip)} prefetch={false} data-primary-walk="" className={buttonVariants({ variant: "quiet", size: "md" })}> + {/* A walk is of clips: a cut of posts alone has none to walk. The draft's first clip. */} + {firstClip ? ( + <Link href={clipBenchHref(project, firstClip)} prefetch={false} data-primary-walk="" className={buttonVariants({ variant: "quiet", size: "md" })} title="walk the draft's clips on the bench, a verdict each"> Walk </Link> ) : null} + <SaveVersionButton project={project} /> <Link href={projectHref(project, { tab: "cut" }) + "&add=1"} prefetch={false} data-primary-add-clip="" className={buttonVariants({ variant: "quiet", size: "md" })} title="find a moment, set its in and out, place it in the cut; fetched through the editor"> + Add a clip </Link> diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx @@ -16,7 +16,7 @@ import ReviewPage from "./ReviewPage"; import ClipDeckPage from "./ClipDeckPage"; import PlayCutPage from "./PlayCutPage"; import PresentPage from "./present/PresentPage"; -import TakeWalkPage from "./TakeWalkPage"; +import OpenInDraftPage from "./OpenInDraftPage"; import ReelPlayPage from "./reel/ReelPlayPage"; import ReelWalkPage from "./reel/ReelWalkPage"; import TrailerPage from "./TrailerPage"; @@ -73,13 +73,13 @@ export default async function ProjectView({ // `/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. - if (rest.length === 3 && rest[0] === "takes" && rest[2] === "walk") return <TakeWalkPage project={project} take={rest[1]} search={search} />; + // `/projects/<project>/takes/<take>/open` -- open a saved version in the draft (it asks first, L3). + // The take walk's and a take's bench's old addresses (`…/takes/<take>/walk`, `…/takes/<take>/clip/<id>`) + // are that page too: every edit lands in the draft, so a version is opened in it before its clips are walked. + if (rest.length === 3 && rest[0] === "takes" && (rest[2] === "open" || rest[2] === "walk")) return <OpenInDraftPage project={project} take={rest[1]} search={search} />; if (rest.length === 4 && rest[0] === "takes" && rest[2] === "clip") { if (!isTakeId(rest[1])) return notFound(); - return <ClipBenchPage project={project} clipId={rest[3]} take={rest[1]} search={search} />; + return <OpenInDraftPage project={project} take={rest[1]} clip={rest[3]} search={search} />; } // `/browse/<project>/narration` -- the narration script, card by card, // approved / edited / rejected before synthesis. diff --git a/umtool/components/projects/SaveVersionButton.tsx b/umtool/components/projects/SaveVersionButton.tsx @@ -0,0 +1,45 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// SAVE VERSION (umtool redesign L3; lib/report/versions.mjs saveVersion; the +// CLI twin is `umtool takes save <p> [--label L]`): the working draft frozen +// as the next v<N>. Nothing is saved when the draft has no edits since its +// parent -- said, beside the button. The pick is never touched. +// --------------------------------------------------------------------------- + +export default function SaveVersionButton({ project, className }: { project: string; className?: string }) { + const router = useRouter(); + const [state, setState] = useState<{ busy: boolean; said: string | null; error: string | null }>({ busy: false, said: null, error: null }); + const save = async () => { + setState({ busy: true, said: null, error: null }); + const r = await fetch("/api/report/takes/save", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project }) }); + const j = (await r.json().catch(() => ({}))) as { saved?: boolean; id?: string; why?: string; error?: string }; + if (!r.ok) return setState({ busy: false, said: null, error: j.error ?? `HTTP ${r.status}` }); + setState({ busy: false, said: j.saved ? `saved as ${j.id}` : (j.why ?? "nothing to save"), error: null }); + router.refresh(); + }; + return ( + <span className="inline-flex items-center gap-1.5"> + <button + type="button" + onClick={() => void save()} + disabled={state.busy} + data-save-version="" + className={cn(buttonVariants({ variant: "quiet", size: "md" }), className)} + title="freeze the working draft as the next version (v1, v2, …): it never changes after, and Open in draft brings it back" + > + {state.busy ? "Saving…" : "Save version"} + </button> + {(state.said || state.error) && ( + <span className={cn("text-[11px]", state.error ? "text-reject-text" : "text-muted")} data-save-version-said={state.error ? "error" : "ok"} role="status"> + {state.error ?? state.said} + </span> + )} + </span> + ); +} diff --git a/umtool/components/projects/TakeActions.tsx b/umtool/components/projects/TakeActions.tsx @@ -5,12 +5,16 @@ import Link from "next/link"; import { useRouter } from "next/navigation"; import { buttonVariants } from "@/components/ui/button"; import { startTakeJob } from "./NewTakePanel"; +import PlayLink from "./PlayLink"; -// What a take offers once it can be walked (walk a take): walk it, render it -// (a draft's first render, or a walked take's again), and make it the cut. -// The Takes page's cards and the take's walk page both draw this; each button -// is the CLI's own command run the app's way: +// What a take offers (a saved version, or a legacy take): play it read-only, +// open it in the draft to edit it (L3: every edit lands in the draft), render +// it (a draft's first render, or a walked take's again), and make it the cut. +// The Takes page's cards draw this; each button is the CLI's own command run +// the app's way: // +// Play · Open in draft /projects/<p>/play?take=<t> · /projects/<p>/takes/<t>/open +// = umtool takes open <p> <t> // Render full / Render 60 s POST /api/report/takes/make { rebuild, window } // = umtool take <p> --id <t> --rebuild [--full | --at 0 --dur 60] // Make this the cut POST /api/report/takes/promote @@ -20,14 +24,15 @@ export default function TakeActions({ project, take, draft, - walkHref, + openHref, edited, compact = false, }: { project: string; take: string; draft: boolean; - walkHref: string | null; + /** Open in draft (OpenInDraftPage): it asks, saves the draft first when it has edits, copies the take in. */ + openHref: string | null; /** Edited by the walk since its render (or never rendered). */ edited: boolean; compact?: boolean; @@ -73,9 +78,10 @@ export default function TakeActions({ const size = compact ? "sm" : "md"; return ( <div data-take-actions={take} className="flex flex-wrap items-center gap-1.5 text-[11.5px]"> - {walkHref && ( - <Link href={walkHref} data-take-walk-link={take} className={buttonVariants({ variant: draft ? "go" : "outline", size })}> - Walk this take + <PlayLink project={project} take={take} where="take-actions" variant={compact ? "button" : "header"} label="Play" /> + {openHref && ( + <Link href={openHref} data-take-open-draft={take} className={buttonVariants({ variant: draft ? "go" : "outline", size })} title={`copy ${take} into the draft to edit it (it asks first) — umtool takes open ${project} ${take}`}> + Open in draft </Link> )} <button diff --git a/umtool/components/projects/TakeTools.tsx b/umtool/components/projects/TakeTools.tsx @@ -4,7 +4,7 @@ import Link from "next/link"; import { useRouter } from "next/navigation"; import { useEffect, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; -import { jobsHref, takeWalkHref } from "@/lib/hrefs"; +import { jobsHref, openInDraftHref } from "@/lib/hrefs"; import { cn } from "@/lib/utils"; import PlayLink from "./PlayLink"; @@ -83,10 +83,11 @@ export function DraftFromButton({ project, take }: { project: string; take: stri {res?.exit === 0 && res.id && ( <span className="text-[11.5px] text-text-2" data-take-drafted={res.id}> draft <b className="font-mono">{res.id}</b>:{" "} - <Link href={takeWalkHref(project, res.id)} className="ink-link"> - walk it - </Link>{" "} - <PlayLink project={project} take={res.id} where="drafted" variant="icon" /> + <PlayLink project={project} take={res.id} where="drafted" variant="link" label="Play" />{" "} + ·{" "} + <Link href={openInDraftHref(project, res.id)} className="ink-link" data-take-open-draft={res.id}> + Open in draft + </Link> </span> )} {res && res.exit !== 0 && <span className="text-[11.5px] text-reject-text">{res.error ?? res.said ?? "refused"}</span>} @@ -111,9 +112,10 @@ export function ImportItems({ project, take }: { project: string; take: string } const [done, setDone] = useState<Tools | null>(null); useEffect(() => { if (!open) return; - void fetch(`/api/report/takes/timeline?project=${encodeURIComponent(project)}&take=${encodeURIComponent(take)}`, { cache: "no-store" }) + // The take's entries as Play reads them (its frozen manifest, or its patch over the draft): where an item lands. + void fetch(`/api/report/play-view?${new URLSearchParams({ project, take })}`, { cache: "no-store" }) .then((r) => r.json()) - .then((j) => setEntries(Array.isArray(j.timeline) ? j.timeline : [])) + .then((j) => setEntries(Array.isArray(j.entries) ? (j.entries as { id: string; type: string; heading?: string }[]).map((e) => ({ id: e.id, type: e.type, words: e.heading })) : [])) .catch(() => {}); void fetch("/api/jump", { cache: "no-store" }) .then((r) => r.json()) diff --git a/umtool/components/projects/TakeWalkPage.tsx b/umtool/components/projects/TakeWalkPage.tsx @@ -1,161 +0,0 @@ -import Link from "next/link"; -import { notFound } from "next/navigation"; -import { hms } from "umtool-report-to-video/attribution"; -import { badgeVariants } from "@/components/ui/badge"; -import { buttonVariants } from "@/components/ui/button"; -import { projectsHref, takeClipHref, takeWalkHref, takesHref } from "@/lib/hrefs"; -import { isTakeId } from "@/lib/report/takes.mjs"; -import { walkOf } from "@/lib/report/walkData.mjs"; -import type { ProjectRef } from "@/lib/project-types"; -import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell"; -import PlayLink from "./PlayLink"; -import { AddClipToggle } from "./AddClip"; -import TakeTools from "./TakeTools"; -import { Options } from "@/components/ui/disclosure"; -import TakeActions from "./TakeActions"; -import BenchPrepPanel from "./report/BenchPrepPanel"; - -// `/projects/<project>/takes/<take>/walk` -- WALK A TAKE: the take's clips -// (the project's manifest with the take's patch applied, a draft too) in walk -// order, each with its verdict and whether a fetched file holds it, and where -// the walk starts. Each clip opens the clip bench on the TAKE -// (`…/takes/<take>/clip/<id>`), whose saves go into the take's patch. -// `umtool walk <project> --take <take>` prints the same reading. - -const VERDICT_TONE = { confirmed: "on", incorrect: "meter", rejected: "meter", unreviewed: "state" } as const; - -export default async function TakeWalkPage({ - project, - take, - search = {}, -}: { - project: ProjectRef; - take: string; - search?: Record<string, string | undefined>; -}) { - if (!isTakeId(take)) notFound(); - const all = search.all === "1"; - let w: Awaited<ReturnType<typeof walkOf>>; - try { - w = await walkOf(project, { take, all }); - } catch { - notFound(); - } - const start = w.first ? takeClipHref(project.id, take, w.first, { all }) : null; - const unfetched = w.clips.filter((c) => !c.fetched).length; - return ( - <BenchFrame - kind="take-walk" - top={ - <BenchTop - trail={[{ href: projectsHref(), label: "Projects" }]} - back={{ href: takesHref(project.id), label: `${project.name} · takes` }} - kind="Take walk" - here={take} - next={start ? { href: start, label: w.first ?? "", attrs: { "data-take-walk-start": w.first ?? "" } } : null} - note={`${w.total} clips · ${hms(w.seconds)} · ${w.reviewed} reviewed`} - /> - } - > - <BenchBody workClassName="space-y-3 overflow-y-auto"> - <section data-take-walk-head={take} className="space-y-1.5"> - <div className="flex flex-wrap items-center gap-2"> - <h1 className="text-[15px] text-text">{w.take?.label ?? take}</h1> - {w.take?.draft && <span className={badgeVariants({ variant: "state", size: "sm" })}>draft — not rendered</span>} - {!w.take?.editable && <span className={badgeVariants({ variant: "meter", size: "sm" })}>read only — a recipe&apos;s take, not made</span>} - </div> - <p className="text-[12px] text-text-2"> - Edits made while walking go into this take&apos;s patch (<code className="font-mono">takes/{take}/take.json</code>), never the - project&apos;s manifest. {w.needing} need a verdict, {w.ready} of them fetched - {unfetched ? ` · ${unfetched} not fetched` : ""}. - </p> - {w.note && <p className="text-[12px] text-doubt-text">{w.note}</p>} - <div className="flex flex-wrap items-center gap-2"> - {start ? ( - <Link href={start} data-take-walk-go="" className={buttonVariants({ variant: "go", size: "md" })}> - Walk → start at {w.first} - </Link> - ) : ( - <span className="text-[12px] text-[var(--color-dim)]"> - {all ? "Nothing fetched to walk." : "Every fetched clip has a verdict."} - </span> - )} - <PlayLink project={project.id} take={take} where="walk" variant="button" /> - <Link href={takeWalkHref(project.id, take, { all: !all })} data-take-walk-all={all ? "1" : "0"} className="text-[12px] ink-link"> - {all ? "walk only the clips needing a verdict" : "walk every clip (judged ones too)"} - </Link> - </div> - {w.take?.editable && ( - <div className="flex flex-wrap items-start gap-2"> - <AddClipToggle project={project.id} take={take} where="take" /> - </div> - )} - {/* The take's own prep: its clips' excerpts and waveforms made before the walk opens them. */} - <BenchPrepPanel project={project.id} take={take} /> - {w.take?.editable && ( - <TakeActions project={project.id} take={take} draft={!!w.take?.draft} walkHref={null} edited compact /> - )} - <Options id="take-walk" hint="check before render · new draft from it · add items from another project"> - <TakeTools project={project.id} take={take} editable={!!w.take?.editable} /> - </Options> - </section> - <table data-take-walk-clips="" className="w-full border-collapse text-[12px]"> - <thead> - <tr className="micro text-left"> - <th className="py-1 pr-2">#</th> - <th className="py-1 pr-2">clip</th> - <th className="py-1 pr-2">window</th> - <th className="py-1 pr-2 text-right">s</th> - <th className="py-1 pr-2">verdict</th> - <th className="py-1 pr-2">quote</th> - </tr> - </thead> - <tbody> - {/* The intro the take opens on, first: watched in Play, not judged (it has no verdict). */} - {w.intro && ( - <tr data-take-walk-intro={w.intro.style} className="border-t border-seam align-top"> - <td className="num py-1 pr-2 text-[var(--color-dim)]">0</td> - <td className="py-1 pr-2"> - <span className="font-mono text-text-2">intro</span> - <PlayLink project={project.id} take={take} clip={w.intro.id} where="walk-row" variant="icon" /> - </td> - <td className="py-1 pr-2 whitespace-nowrap text-text-2">{w.intro.style}</td> - <td className="num py-1 pr-2 text-right">{w.intro.seconds.toFixed(1)}</td> - <td className="py-1 pr-2"> - <span className={badgeVariants({ variant: "state", size: "sm" })}>watched, not judged</span> - </td> - <td className="py-1 pr-2 text-text-2">{[w.intro.title, ...w.intro.lines].filter(Boolean).join(" · ")}</td> - </tr> - )} - {w.clips.map((c) => ( - <tr key={c.id} data-take-walk-clip={c.id} data-on-walk={c.onWalk ? "1" : "0"} className="border-t border-seam align-top"> - <td className="num py-1 pr-2 text-[var(--color-dim)]">{c.cut}</td> - <td className="py-1 pr-2"> - <Link href={takeClipHref(project.id, take, c.id, { all })} className="font-mono ink-link"> - {c.id} - </Link> - {c.onWalk && <span className="ml-1 text-meter" title="on the walk">→</span>} - <PlayLink project={project.id} take={take} clip={c.id} where="walk-row" variant="icon" /> - </td> - <td className="num py-1 pr-2 whitespace-nowrap"> - {hms(c.start)}–{hms(c.end)} - {!c.fetched && <span className={`ml-1 ${badgeVariants({ variant: "state", size: "sm" })}`}>not fetched</span>} - </td> - <td className="num py-1 pr-2 text-right">{c.seconds.toFixed(1)}</td> - <td className="py-1 pr-2"> - <span className={badgeVariants({ variant: VERDICT_TONE[c.verdict as keyof typeof VERDICT_TONE] ?? "state", size: "sm" })}> - {c.rejected ? `${c.verdict} — ${c.rejected.label}` : c.verdict} - </span> - {(c.rejected?.fact ? c.correction : (c.rejected?.why ?? c.correction)) && ( - <span className="block text-[11px] text-doubt-text">{c.rejected?.fact ? c.correction : c.rejected ? c.rejected.why : c.correction}</span> - )} - </td> - <td className="py-1 pr-2 text-text-2">{c.quote}</td> - </tr> - ))} - </tbody> - </table> - </BenchBody> - </BenchFrame> - ); -} diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx @@ -11,7 +11,7 @@ import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; import { fmtAgo, fmtBytes } from "@/lib/format"; import { cn } from "@/lib/utils"; -import { playHref, takeWalkHref, presentHref } from "@/lib/hrefs"; +import { openInDraftHref, playHref, presentHref } from "@/lib/hrefs"; import RenderRecord from "@/components/queue/RenderRecord"; import type { RenderView } from "@/lib/queue/view"; import { BenchBody, VerdictBar } from "./bench/BenchShell"; @@ -56,8 +56,10 @@ export type Take = { quick?: boolean; /** The project's manifest is not the one it was made from (null: it does not say). */ stale?: boolean | null; - /** Recorded, not rendered (`umtool take … --draft`): walk it, then render it. */ + /** Recorded, not rendered (`umtool take … --draft`, or a saved version): play it, open it in the draft, render it. */ draft?: boolean; + /** A saved version (lib/report/versions.mjs): frozen in takes/<id>/base.manifest.json. */ + version?: boolean; /** The walk's last edit to its patch (later than builtAt: the render is older than the take). */ editedAt?: string | null; /** What a running render names (takeHousekeeping.mjs renderHolds): it is rendering, or a render is made from it. */ @@ -645,8 +647,8 @@ function TakeCard({ }; const superseded = verdict?.superseded ?? null; const windowWords = t.window === "full" ? "full cut" : t.window ? `${t.window.at}–${t.window.at + t.window.dur} s` : null; - // Walk a take: a draft is walked before it is rendered; a rendered take - // walked since says its render is older than it (editedAt after builtAt). + // A take edited since its render (a legacy walk, or the CLI's take-scoped edits) says its render is older + // than it (editedAt after builtAt). Every UI edit lands in the draft now (Open in draft first). const editedSinceRender = !!t.editedAt && (!t.builtAt || t.editedAt > t.builtAt); const walkable = !!t.draft || !!t.baseHash; @@ -677,10 +679,8 @@ function TakeCard({ data-take-draft={t.id} className="flex aspect-video w-full flex-col items-center justify-center gap-1 bg-black px-3 text-center text-[12px] text-[var(--color-dim)]" > - <span className="text-text-2">draft — walk / render</span> - <span className="text-[11px]"> - nothing rendered yet: walk its clips on the bench (edits go into this take), then render it - </span> + <span className="text-text-2">{t.version ? "saved version — not rendered" : "draft — not rendered"}</span> + <span className="text-[11px]">play it read-only, open it in the draft to edit it, or render it</span> </div> ) : ( <div data-no-preview="" className="flex aspect-video w-full items-center justify-center bg-black text-[11px] text-[var(--color-dim)]"> @@ -838,7 +838,7 @@ function TakeCard({ project={project} take={t.id} draft={!!t.draft} - walkHref={takeWalkHref(project, t.id)} + openHref={openInDraftHref(project, t.id)} edited={!!t.draft || editedSinceRender} compact /> diff --git a/umtool/components/projects/TakesPage.tsx b/umtool/components/projects/TakesPage.tsx @@ -14,7 +14,6 @@ import TakesBench, { type Take, type TakeVerdict } from "./TakesBench"; import { LatestLine } from "./review/WhatPlays"; import { readWorkingCut } from "@/lib/report/workingCut.mjs"; import PlayLink from "./PlayLink"; -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"; @@ -50,7 +49,7 @@ export default async function TakesPage({ project }: { project: ProjectRef }) { // What a running render names (take housekeeping): the card says so, and relabel/delete refuse. const holds = new Map(await Promise.all((listing.takes as Take[]).map(async (t) => [t.id, await renderHolds(project.dir, t.id)] as const))); // The working cut's name: the latest whole-cut take and the edits since it (lib/report/workingCut.mjs). - const working = await readWorkingCut(project.dir, { manifestText, resolveNow: async (id) => (await resolveTakeManifest(project.dir, id)).manifest }).catch(() => null); + const working = await readWorkingCut(project.dir, { manifestText }).catch(() => null); // 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). // Every render records itself (lib/report/renderRecord.mjs), and the queue holds what waits to run (lib/queue/). diff --git a/umtool/components/projects/bench/TakeWalkStrip.tsx b/umtool/components/projects/bench/TakeWalkStrip.tsx @@ -1,140 +0,0 @@ -"use client"; - -import { useEffect, useState } from "react"; -import Link from "next/link"; -import { badgeVariants } from "@/components/ui/badge"; -import { buttonVariants } from "@/components/ui/button"; -import { cn } from "@/lib/utils"; - -// WALKING A TAKE: the line that says so, on the clip bench, and the take's -// own structure -- this clip out of the take, earlier or later in it, and the -// take's last edit taken back. Every one is POST /api/report/takes/timeline -// (lib/report/takeEdit.mjs), the writer `umtool timeline <p> --take <id>` -// runs; the project's manifest is never written from here. -// -// After a structural edit the page is LOADED again rather than refreshed: the -// bench holds its token and its drafts in state, and a remount is the honest -// way to show the take as it now is. - -export default function TakeWalkStrip({ - project, - take, - clipId, - index, - total, - nextHref, - getToken, - className, -}: { - project: string; - take: { id: string; label: string; draft: boolean; editable: boolean; all: boolean; takesHref: string; walkHref: string; toggleAllHref: string }; - clipId: string; - /** This clip's place in the take's timeline, 0-based, and the timeline's length. */ - index: number; - total: number; - /** Where the walk goes after this clip is removed. */ - nextHref: string | null; - getToken: () => string | null; - className?: string; -}) { - const [ready, setReady] = useState(false); - const [busy, setBusy] = useState(false); - const [said, setSaid] = useState<string | null>(null); - useEffect(() => setReady(true), []); - - const run = async (op: "move" | "remove" | "undo", extra: Record<string, unknown> = {}, then: string | null = null) => { - setBusy(true); - setSaid(null); - try { - const r = await fetch("/api/report/takes/timeline", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ project, take: take.id, op, token: getToken(), ...extra }), - cache: "no-store", - }); - const j = (await r.json().catch(() => ({}))) as { error?: string; errors?: string[]; stale?: boolean }; - if (!r.ok) { - setSaid(j.stale ? "the take changed since this page was read — reload" : (j.errors?.join("; ") ?? j.error ?? `HTTP ${r.status}`)); - return; - } - window.location.assign(then ?? window.location.href); - } finally { - setBusy(false); - } - }; - - const off = !ready || busy || !take.editable; - return ( - <div - data-take-walk={take.id} - className={cn( - "flex flex-wrap items-center gap-x-2 gap-y-1 rounded border border-[var(--color-sel)] bg-[var(--color-panel)] px-2 py-1 text-[11.5px]", - className, - )} - > - <span className="micro">walking take</span> - <span className="font-mono text-[var(--color-text)]">{take.id}</span> - <span className="truncate text-text-2">{take.label}</span> - {take.draft && <span className={badgeVariants({ variant: "state", size: "sm" })}>draft</span>} - <span className="text-[var(--color-dim)]"> - {take.editable ? "edits go to the take, not the cut" : "a recipe's take, not made yet: read only"} - </span> - <span className="ml-auto flex flex-wrap items-center gap-1.5"> - <span className="num text-[var(--color-dim)]"> - {index + 1}/{total} in the take - </span> - <button - type="button" - data-take-move="earlier" - disabled={off || index <= 0} - className={buttonVariants({ variant: "outline", size: "sm" })} - title="one place earlier in the take" - onClick={() => void run("move", { id: clipId, toIndex: index - 1 })} - > - ← earlier - </button> - <button - type="button" - data-take-move="later" - disabled={off || index >= total - 1} - className={buttonVariants({ variant: "outline", size: "sm" })} - title="one place later in the take" - onClick={() => void run("move", { id: clipId, toIndex: index + 1 })} - > - later → - </button> - <button - type="button" - data-take-remove={clipId} - disabled={off} - className={buttonVariants({ variant: "outline", size: "sm" })} - title="take this clip out of the take (Undo puts it back)" - onClick={() => void run("remove", { id: clipId }, nextHref ?? take.takesHref)} - > - Remove from take - </button> - <button - type="button" - data-take-undo="" - disabled={off} - className={buttonVariants({ size: "sm" })} - title="take back the take's last edit -- a verdict, a trim, a move or a removal" - onClick={() => void run("undo")} - > - Undo take edit - </button> - <Link href={take.toggleAllHref} data-take-walk-all={take.all ? "1" : "0"} className="ink-link"> - {take.all ? "walk the unjudged only" : "walk every clip"} - </Link> - <Link href={take.takesHref} className="ink-link"> - Takes - </Link> - </span> - {said && ( - <span data-take-said="" className="basis-full text-[var(--color-bad)]"> - {said} - </span> - )} - </div> - ); -} diff --git a/umtool/components/projects/inTake.tsx b/umtool/components/projects/inTake.tsx @@ -1,16 +0,0 @@ -"use client"; - -import { createContext, useContext } from "react"; - -// "EDIT THIS TAKE ONLY" on the post bench (lane/ui-simplify, 5 Nov): the take every write of the bench is scoped -// to (`?inTake=<t>`; the routes run the writer under takeScope.mjs withTakeScope, as `umtool posts set-item … --in-take` -// does), or null for the project's cut. A writer adds `...inTakeBody(take)` to its POST body. -const Ctx = createContext<string | null>(null); - -export function InTakeProvider({ take, children }: { take: string | null; children: React.ReactNode }) { - return <Ctx.Provider value={take}>{children}</Ctx.Provider>; -} - -export const useInTake = () => useContext(Ctx); - -export const inTakeBody = (take: string | null) => (take ? { inTake: take } : {}); diff --git a/umtool/components/projects/present/PresentView.tsx b/umtool/components/projects/present/PresentView.tsx @@ -786,7 +786,7 @@ function SettingsDrawer({ <div className="flex flex-col gap-1 border-t border-white/10 pt-2 text-[12px]"> <span className="text-white/60"> {payload.title} - {payload.take ? ` · ${payload.take.defaulted ? "latest " : "take "}${payload.take.id}` : " · the manifest"} + {payload.take ? ` · version ${payload.take.id}` : " · the draft"} </span> <Link href={playHref} className="text-amber-300 hover:underline" data-present-play-link=""> ▶ Play the cut diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -8,7 +8,7 @@ import { } from "@/lib/projects/report.mjs"; import { listTakes } from "@/lib/report/takes.mjs"; import { buttonVariants } from "@/components/ui/button"; -import { narrationRecordHref, postBenchHref, clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, playHref, projectHref, takeWalkHref, takesHref, trailerHref } from "@/lib/hrefs"; +import { narrationRecordHref, postBenchHref, clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, playHref, projectHref, openInDraftHref, takesHref, trailerHref } from "@/lib/hrefs"; import { readTrailerBeats } from "@/lib/report/trailerBeats.mjs"; import { montageClipsOf, momentKeysOf, readRulingsState } from "@/lib/report/montageRulings.mjs"; import FetchUnfetchedButton from "../FetchUnfetchedButton"; @@ -441,7 +441,7 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor </div> {/* Everything else, folded (lane/ui-simplify): Options the common, Advanced the rare; open state remembered per viewer. */} <div className="flex flex-wrap items-start gap-x-4 gap-y-1.5" data-cut-panels=""> - <Options id="cut" hint="clip editor · trailer · walk a take · fetch · check"> + <Options id="cut" hint="clip editor · trailer · versions · fetch · check"> {!postsFirst && <AddPosts project={project.id} channels={postChannels} />} {/* Check before render, on the cut itself (umtool lint <p>): the build's lint and the files its posts name. */} {entries.length > 0 && <LintButton project={project.id} />} @@ -472,21 +472,20 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor {trailerBeats ? `Trailer — ${trailerBeats} beat${trailerBeats === 1 ? "" : "s"}` : trailerBeats === null ? "Trailer (beats file unreadable)" : "Trailer beats"} </Link> )} - {/* Walk a take: the drafts first -- a draft exists to be walked before it is rendered. */} + {/* The saved versions and takes: each played read-only, or opened in the draft to edit (L3). */} {takes.takes.some((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash) && ( <span data-walk-takes="" className="flex flex-wrap items-center gap-1.5 text-[11.5px]"> - <span className="micro">walk a take</span> + <span className="micro">versions</span> {[...takes.takes] .filter((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash) - .sort((a: { draft?: boolean }, b: { draft?: boolean }) => Number(!!b.draft) - Number(!!a.draft)) + .sort((a: { order?: number }, b: { order?: number }) => (b.order ?? 0) - (a.order ?? 0)) .slice(0, 6) .map((t: { id: string; label: string; draft?: boolean }) => ( - <span key={t.id} className="inline-flex items-center"> - <Link href={takeWalkHref(project.id, t.id)} data-walk-take={t.id} className="ink-link" title={t.label}> - {t.id} - {t.draft ? " (draft)" : ""} + <span key={t.id} className="inline-flex items-center gap-1"> + <PlayLink project={project.id} take={t.id} where="walk-chip" variant="link" label={t.id} /> + <Link href={openInDraftHref(project.id, t.id)} data-walk-take={t.id} className="ink-link text-muted" title={`open ${t.id} (“${t.label}”) in the draft — it asks first`}> + open </Link> - <PlayLink project={project.id} take={t.id} where="walk-chip" variant="icon" /> </span> ))} </span> diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -2,11 +2,12 @@ import { useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import Link from "next/link"; import { buttonVariants } from "@/components/ui/button"; import { useSharedNotes } from "@/components/notes/NotesProvider"; import { NoteThread } from "@/components/notes/NoteThread"; import type { Anchor, CutAsk, Note } from "@/lib/annotations/types"; -import { clipBenchHref, postBenchHref, takeClipHref } from "@/lib/hrefs"; +import { clipBenchHref, openInDraftHref, postBenchHref } from "@/lib/hrefs"; import { cn } from "@/lib/utils"; import { footageAt } from "@/lib/report/footage-move.mjs"; import { finaleUp, stampAt, tallyAt } from "@/lib/report/liveClock.mjs"; @@ -92,14 +93,13 @@ import CopyShareLine from "../CopyShareLine"; // bench's "Back to the cut" lands here as `?clip=<id>&at=<offset>`. By clip id // and offset, never by raw cut seconds: the edit just changed this clip's // length, which moves every cut second after it. The page is a fresh server -// render of the manifest (force-dynamic), so the new edges are what plays. A -// take WITHOUT a timeline of its own plays the project's cut as it is now, so -// its Edit goes to the project's manifest, and the bench says so. A take WITH -// its own timeline (`ownTimeline`: its patch replaces the timeline) is a cut -// of its own: its Edit opens the TAKE's bench on the clip (`…/takes/<take>/ -// clip/<id>?from=play`), whose saves go into takes/<take>/take.json, and -// Back plays that take -- never the project's clip of the same id (2 Nov: an -// edge fixed on `kirsche-7`'s kr1 landed in the project's cut). +// render of the manifest (force-dynamic), so the new edges are what plays. +// Every edit lands in THE DRAFT (umtool redesign L3): a saved version +// (`?take=`) is played read-only, and its Edit goes to the Open in draft page +// (`…/takes/<take>/open?clip=<id>&from=play`) -- it asks, saves the draft +// first when it has edits, copies the version in -- then the draft's bench; +// Back plays the draft. (2 Nov: an edge fixed from Play on `kirsche-7`'s kr1 +// landed where the operator did not expect: there is one place now.) // // ON A PHONE (the phone design brief): one document, the player pinned at the // top -- a strip once the transport has scrolled under it -- the strip, Now @@ -148,8 +148,10 @@ export type PlayEntry = { export type PlayViewData = { project: string; title: string; - take: { id: string; label: string; summary: string; made: boolean; from: string; ownTimeline?: boolean; defaulted?: boolean } | null; + take: { id: string; label: string; summary: string; made: boolean; from: string; ownTimeline?: boolean; version?: boolean; frozen?: boolean; parent?: boolean; render?: string | null } | null; note: string | null; + /** The draft's header (lib/report/workingCut.mjs draftLine): "Draft · from v5 · 3 edits", "Draft · unsaved". */ + draft?: { line: string; parent: string | null; edits: number | null }; takes: { id: string; label: string; made: boolean }[]; /** The working cut's name: the latest whole-cut take, the edits since, the pick (lib/report/workingCut.mjs). */ working?: WorkingCut; @@ -297,8 +299,7 @@ export default function PlayCut({ const reloadView = useCallback(async () => { const mine = ++reloadSeq.current; const q = new URLSearchParams({ project: served.project }); - if (view.take && !view.take.defaulted) q.set("take", view.take.id); - else if (!view.take) q.set("cut", "1"); + if (view.take) q.set("take", view.take.id); try { const r = await fetch(`/api/report/play-view?${q.toString()}`, { cache: "no-store" }); const j = (await r.json()) as PlayViewData & { error?: string }; @@ -315,13 +316,12 @@ export default function PlayCut({ shownRef.current = shown; const project = view.project; const take = view.take?.id ?? null; - // Edits made here (Reject, a reorder, the bench) write the PROJECT'S manifest, which a take - // without a timeline of its own plays as it is now -- the latest take follows them. A take - // with its own timeline does not: nothing structural is offered on it (its walk edits it). - const editable = !view.take?.ownTimeline; - // A note taken on the latest take (the default) is a note on the cut: the manifest is the - // file to edit. On a take chosen by name it is that take's, as it always was. - const noteTake = view.take && !view.take.defaulted ? take : null; + // Edits made here (Reject, a reorder, the bench) write THE DRAFT, the project's manifest -- what + // plays with no take. A saved version (`?take=`) is played read-only: Edit opens it in the draft + // first (OpenInDraftPage), and nothing structural is offered on it. + const editable = !view.take; + // A note taken on the draft is a note on the cut; on a version it is that version's. + const noteTake = take; // Export clip (ClipExport.tsx): the clip at the playhead -- or the one a note points at -- clean, into exports/. const clipExport = useClipExport(project, take); @@ -634,9 +634,9 @@ export default function PlayCut({ const mine = useMemo( () => notes.notes - .filter((n) => n.anchor.kind === "cut" && ((n.anchor.take ?? null) === noteTake || (view.take?.defaulted && (n.anchor.take ?? null) === take))) + .filter((n) => n.anchor.kind === "cut" && (n.anchor.take ?? null) === noteTake) .sort((a, b) => (a.anchor as CutAnchor).t - (b.anchor as CutAnchor).t), - [notes.notes, take, noteTake, view.take?.defaulted], + [notes.notes, noteTake], ); // A note's second on this clock: by its clip and source second when it has them (the // render's edges re-time the cut; a note stays on the word it was taken on), else its t. @@ -699,16 +699,17 @@ export default function PlayCut({ const it = planRef.current.items[e.cur]; // A post item: its own bench (the post's attachments' trims, its hold and crop). if (it?.type === "post") { - const href = postBenchHref(project, it.id, { play: { at: Math.round(Math.max(0, e.t - it.from) * 100) / 100 } }); - // A take with its own timeline: the bench edits that take only (?inTake, lane/ui-simplify). - return take && view.take?.ownTimeline ? `${href}${href.includes("?") ? "&" : "?"}inTake=${encodeURIComponent(take)}` : href; + const at = Math.round(Math.max(0, e.t - it.from) * 100) / 100; + // A version: opened in the draft first (it asks), then the draft's bench. + if (take) return openInDraftHref(project, take, { clip: it.id, post: true, play: { at } }); + return postBenchHref(project, it.id, { play: { at } }); } if (!it?.clip) return null; const at = Math.round(Math.max(0, e.t - it.from) * 100) / 100; - // A take with its own timeline: ITS bench, its patch (never the project's clip of the same id). - if (take && view.take?.ownTimeline) return takeClipHref(project, take, it.id, { play: { at } }); - return clipBenchHref(project, it.id, { play: { at, take: view.take?.defaulted ? null : take } }); - }, [project, take, now, view.take?.defaulted, view.take?.ownTimeline]); + // A version is never edited in place: Open in draft (it asks), then the draft's bench on this clip. + if (take) return openInDraftHref(project, take, { clip: it.id, play: { at } }); + return clipBenchHref(project, it.id, { play: { at, take: null } }); + }, [project, take, now]); /** Play's place as its own URL: the clip on screen, the offset into it, the cut second, the toggle. */ const placeHref = useCallback(() => { const e = now(); @@ -730,7 +731,8 @@ export default function PlayCut({ setPlaying(false); // Where Back lands: this place, written now (the one push is the bench's). window.history.replaceState(window.history.state, "", placeHref()); - if (app && planRef.current.items[now().cur]?.clip) { + // A version opens in the draft first: its own page (it asks), never the bench in place. + if (app && !take && planRef.current.items[now().cur]?.clip) { // In place: Play stays as it is; on the way back the clip (and the source second) is found again. const e = now(); const it = planRef.current.items[e.cur]; @@ -739,7 +741,7 @@ export default function PlayCut({ return; } router.push(h); - }, [editHref, router, setPlaying, placeHref, app, now]); + }, [editHref, router, setPlaying, placeHref, app, now, take]); const lastPlace = useRef(0); // A navigation in flight (a take link, Play the latest): Play's own URL write would land on // top of it and cancel it (the audit's "a take link clicked while playing is cancelled"), so @@ -854,7 +856,7 @@ export default function PlayCut({ void reloadView(); }, [edit.done, timelineWrite, holdPlace, reloadView]); const editableWhy = !editable - ? `take ${take} has its own timeline: reorder it on its walk (umtool timeline <p> --take ${take} move)` + ? `version ${take} is played read-only: Open in draft to edit it (umtool takes open <p> ${take})` : null; // ---- the keys ---------------------------------------------------------------------- @@ -1169,7 +1171,7 @@ export default function PlayCut({ {/* ---- the head: the cut's title, what plays, the running time ---- */} <header className="flex flex-wrap items-center gap-x-4 gap-y-1.5 border-b border-seam px-4 py-2 max-md:-mx-4"> <h1 className="m-0 min-w-0 truncate font-display text-[17px] font-semibold tracking-[-0.01em] text-text">{view.title}</h1> - <WhatPlays project={project} take={view.take} takes={view.takes} working={view.working ?? null} onNavigate={onNavigate} /> + <WhatPlays project={project} take={view.take} takes={view.takes} working={view.working ?? null} draft={view.draft ?? null} onNavigate={onNavigate} /> {/* Fast feedback on the take playing (takePreview.mjs): its preview render and its changes reel, queued. */} {view.take && ( <details data-play-fast="" className="relative text-[11.5px]"> @@ -1187,16 +1189,24 @@ export default function PlayCut({ </button> </header> {view.take ? ( - <p className="m-0 border-b border-seam px-4 py-1 text-[11.5px] text-text-2 max-md:-mx-4 max-md:-mt-3" data-play-take={view.take.id} data-play-take-defaulted={view.take.defaulted ? "" : undefined}> - {view.take.defaulted ? "the latest take, " : ""}take “{view.take.label}”: the project&rsquo;s cut as it is now with its patch ({view.take.from}){view.take.made ? "" : " — not rendered yet"} - {view.take.summary ? ` · ${view.take.summary}` : ""} - {view.take.ownTimeline - ? " — it has its own timeline: edits to the cut do not show in it; Edit this clip opens the take's own bench (its patch)" - : " · edits here go to the cut, and show at once"} + <p className="m-0 flex flex-wrap items-center gap-x-2 gap-y-1 border-b border-seam px-4 py-1 text-[11.5px] text-text-2 max-md:-mx-4 max-md:-mt-3" data-play-take={view.take.id} data-play-take-frozen={view.take.frozen ? "" : undefined}> + <span> + {view.take.version ? "version" : "take"} “{view.take.label}”, read-only:{" "} + {view.take.frozen ? "frozen as it was saved" : "the draft as it is now with its patch"} ({view.take.from}){view.take.made ? "" : " — not rendered yet"} + {view.take.summary ? ` · ${view.take.summary}` : ""} + </span> + <Link href={openInDraftHref(project, view.take.id)} prefetch={false} data-play-open-draft={view.take.id} className={cn(buttonVariants({ variant: "outline", size: "sm" }))} title={`copy ${view.take.id} into the draft to edit it (it asks first; your draft is saved as a version when it has edits)`}> + Open in draft + </Link> + {view.take.render && ( + <a href={view.take.render} target="_blank" rel="noreferrer" data-play-watch-render={view.take.id} className="ink-link" title="the rendered mp4 of this version"> + Watch render + </a> + )} </p> ) : ( - <p className="m-0 border-b border-seam px-4 py-1 text-[11.5px] text-text-2 max-md:-mx-4 max-md:-mt-3" data-play-take=""> - the project&rsquo;s manifest alone — no take&rsquo;s look (title, deck and effects patches are not applied) + <p className="m-0 border-b border-seam px-4 py-1 text-[11.5px] text-text-2 max-md:-mx-4 max-md:-mt-3" data-play-take="" data-play-draft-note=""> + the working draft — every edit here lands in it ({view.draft?.line ?? "Draft"}) </p> )} @@ -1364,17 +1374,15 @@ export default function PlayCut({ {/* The clip on the bench, and back here after (E). */} <button type="button" - data-play-edit={take && view.take?.ownTimeline ? "take" : ""} + data-play-edit={take ? "open" : ""} disabled={!item?.clip && !postNow} onClick={editHere} className={cn(buttonVariants({ variant: "outline", size: "sm" }))} title={ item?.clip - ? take && view.take?.ownTimeline - ? `edit this clip on take ${take}'s bench (E): the edit goes to the take's own timeline (takes/${take}/take.json), never the project's cut; Back plays this take` - : take - ? "edit this clip on the bench (E): the edit goes to the project's cut, not this take's render; Back plays the project's cut" - : "edit this clip on the bench (E); Back to the cut returns here" + ? take + ? `open version ${take} in the draft first (E: it asks; your draft is saved as a version when it has edits), then edit this clip on the draft's bench` + : "edit this clip on the bench (E): the edit lands in the draft; Back to the cut returns here" : postNow ? "open this post item's bench (E): its attachments' trims, sound and crop, its hold; Back returns here" : "a card is not edited on the clip bench" @@ -1432,19 +1440,20 @@ export default function PlayCut({ }} /> )} - {/* Add a clip here (lane/ui-simplify): find a moment, in/out on its cues, placed after the item on screen; the - cut's, or this take's only when the take keeps its own timeline. */} - <AddClipToggle - project={project} - take={editable ? null : take} - after={item?.id ?? null} - where="play" - label={editable ? "+ Add a clip here" : `+ Add a clip here (${take} only)`} - onAdded={() => { - setPlaying(false); - void reloadView(); - }} - /> + {/* Add a clip here (lane/ui-simplify): find a moment, in/out on its cues, placed after the item on screen -- + in the draft. A version is read-only: Open in draft first. */} + {editable && ( + <AddClipToggle + project={project} + after={item?.id ?? null} + where="play" + label="+ Add a clip here" + onAdded={() => { + setPlaying(false); + void reloadView(); + }} + /> + )} </div> {/* Reject ▾ (x): the clip on screen out of the cut for a reason, on record, with an undo (the project's cut: not on a take). */} {editable && ( diff --git a/umtool/components/projects/review/WhatPlays.tsx b/umtool/components/projects/review/WhatPlays.tsx @@ -5,57 +5,58 @@ import { playHref, takesHref } from "@/lib/hrefs"; import { cn } from "@/lib/utils"; // --------------------------------------------------------------------------- -// WHAT PLAYS (operator, 1 Nov 2026): the working cut's NAME, as prominent as a -// take's -- "Latest: draft-22 · 28:03 · +3 edits since" -- and the switch to an -// older take or to the manifest alone. The latest take is the newest -// whole-cut take made from the project (lib/report/workingCut.mjs); the edits -// since it are the project's manifest against what that take rendered. The -// pick (verdicts.json) is secondary: named small, only when it is not the -// latest. Every switch is a link (`?take=`, `?cut=1`, nothing for the latest); -// `onNavigate` lets Play stop writing its own URL while one is in flight. +// WHAT PLAYS (umtool redesign L3): THE DRAFT, named first -- "Draft · from v5 +// · 3 edits" / "Draft · unsaved" (lib/report/workingCut.mjs draftLine): the +// project's manifest, where every edit lands -- and the switch to a saved +// version, played read-only (`?take=`). The pick (verdicts.json) is +// secondary: named small. Every switch is a link (nothing for the draft, +// `?take=` for a version); `onNavigate` lets Play stop writing its own URL +// while one is in flight. // --------------------------------------------------------------------------- export type WorkingCut = { latest: { id: string; label: string; builtAt: string | null; seconds: number | null } | null; + /** The draft's parent: what it was last saved as or opened from (takes/draft.json), else the latest. */ + parent?: { id: string; label: string; version?: boolean; via?: string } | null; edits: { count: number; words: string[]; same: boolean } | null; picked: { id: string; at: string | null; pinned: boolean; label: string } | null; } | null; -export type WhatPlaysTake = { id: string; label: string; summary: string; made: boolean; from: string; ownTimeline?: boolean; defaulted?: boolean } | null; +export type WhatPlaysTake = { id: string; label: string; summary: string; made: boolean; from: string; ownTimeline?: boolean; version?: boolean; frozen?: boolean } | null; +export type DraftLine = { line: string; parent: string | null; edits: number | null } | null; -const mmss = (s: number | null) => (typeof s === "number" ? `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}` : null); const day = (iso: string | null) => { if (!iso) return null; const d = new Date(iso); return Number.isNaN(d.getTime()) ? null : d.toLocaleDateString(undefined, { day: "numeric", month: "short" }); }; -/** "+3 edits since" / "no edits since" / "edits since: unknown". */ +/** "3 edits" / "no edits" / "edits unknown": the draft's distance from its parent. */ export function editsLine(w: WorkingCut) { - if (!w?.latest) return ""; - if (!w.edits) return "edits since: unknown"; - return w.edits.count === 0 ? "no edits since" : `+${w.edits.count} edit${w.edits.count === 1 ? "" : "s"} since`; + if (!w?.parent && !w?.latest) return ""; + if (!w.edits) return "edits unknown"; + return w.edits.count === 0 ? "no edits" : `${w.edits.count} edit${w.edits.count === 1 ? "" : "s"}`; } -/** The working cut's line, alone (the bench's head, the Takes page). */ +/** The draft's line, alone (the bench's head, the Takes page): "Draft · from v5 · 3 edits" / "Draft · unsaved". */ export function LatestLine({ project, working, className }: { project: string; working: WorkingCut; className?: string }) { if (!working) return null; - const l = working.latest; + const p = working.parent ?? (working.latest ? { id: working.latest.id, label: working.latest.label } : null); return ( - <span data-working-cut={l?.id ?? ""} data-working-edits={working.edits?.count ?? ""} className={cn("inline-flex flex-wrap items-baseline gap-x-1.5", className)}> - {l ? ( + <span data-working-cut={p?.id ?? ""} data-working-edits={working.edits?.count ?? ""} className={cn("inline-flex flex-wrap items-baseline gap-x-1.5", className)}> + <span className="micro">Draft</span> + {p ? ( <> - <span className="micro">Latest</span> - <Link href={playHref(project)} className="font-mono font-medium text-text hover:underline" title={l.label}> - {l.id} + <span className="text-muted">from</span> + <Link href={playHref(project, { take: p.id })} className="font-mono font-medium text-text hover:underline" title={`${p.label} — play it read-only`}> + {p.id} </Link> - {mmss(l.seconds) && <span className="font-mono text-muted">{mmss(l.seconds)}</span>} <span className="text-muted" title={working.edits?.words.join("\n") || undefined} data-working-edit-words={working.edits?.words.join("; ") ?? ""}> · {editsLine(working)} </span> </> ) : ( - <span className="text-muted">no whole-cut take yet — the manifest is the cut</span> + <span className="text-muted">· unsaved</span> )} </span> ); @@ -66,70 +67,63 @@ export default function WhatPlays({ take, takes, working, + draft = null, onNavigate, }: { project: string; take: WhatPlaysTake; takes: { id: string; label: string; made: boolean }[]; working: WorkingCut; + draft?: DraftLine; onNavigate?: () => void; }) { - const latest = working?.latest ?? null; const current = take?.id ?? null; - const isLatest = !!latest && current === latest.id; - // A few takes are pills; many are a list (the latest and the one playing stay pills). + const parent = draft?.parent ?? working?.parent?.id ?? null; + // A few versions are pills; many are a list (the draft's parent and the one playing stay pills). const many = takes.length > 4; - const pills = many ? takes.filter((t) => t.id === current || t.id === latest?.id) : takes; + const pills = many ? takes.filter((t) => t.id === current || t.id === parent) : takes; const rest = many ? takes.filter((t) => !pills.includes(t)) : []; const link = (t: { id: string | null; label: string; made: boolean }, label: string) => { const on = t.id === null ? take === null : t.id === current; - const href = t.id === null ? playHref(project, { bare: true }) : t.id === latest?.id ? playHref(project) : playHref(project, { take: t.id }); + const href = t.id === null ? playHref(project) : playHref(project, { take: t.id }); return ( <Link - key={t.id ?? "cut"} + key={t.id ?? "draft"} href={href} onClick={onNavigate} aria-current={on ? "page" : undefined} data-play-take-link={t.id ?? ""} - title={t.id ? `${t.label}${t.made ? "" : " (not rendered yet)"}` : "the project's manifest alone: no take's look"} + title={t.id ? `${t.label} — played read-only${t.made ? "" : " (not rendered yet)"}` : "the working draft: the project's manifest, where every edit lands"} className={cn("rounded-[2px] px-2 py-0.5", on ? "bg-panel-2 font-medium text-text" : "text-muted-2 hover:text-text", !t.made && "italic")} > {label} </Link> ); }; + const line = draft?.line ?? "Draft"; return ( <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1"> - {/* The working cut's name, first and largest. */} + {/* The draft's name, first and largest: where every edit lands. */} <span - data-play-working={latest?.id ?? ""} - data-play-working-edits={working?.edits?.count ?? ""} + data-play-draft={parent ?? ""} + data-play-draft-edits={draft?.edits ?? ""} + data-play-working={working?.latest?.id ?? ""} className="inline-flex flex-wrap items-baseline gap-x-1.5 text-[13px]" + title={working?.edits?.words.join("\n") || undefined} > - {latest ? ( - <> - <span className="micro">{isLatest ? "Latest" : "Latest is"}</span> - {isLatest ? ( - <span className="font-mono font-semibold text-text" title={latest.label}> - {latest.id} - </span> - ) : ( - <Link href={playHref(project)} onClick={onNavigate} className="font-mono font-semibold text-text underline decoration-dotted" title={`${latest.label} — play it`} data-play-latest-link=""> - {latest.id} - </Link> - )} - {mmss(latest.seconds) && <span className="font-mono text-[12px] text-muted">{mmss(latest.seconds)}</span>} - <span className="text-[12px] text-muted" title={working?.edits?.words.join("\n") || undefined} data-play-edit-words={working?.edits?.words.join("; ") ?? ""}> - · {editsLine(working)} - </span> - </> + {take ? ( + <Link href={playHref(project)} onClick={onNavigate} className="font-semibold text-text underline decoration-dotted" data-play-draft-link="" title="play the working draft"> + {line} + </Link> ) : ( - <span className="text-[12px] text-muted">no whole-cut take yet — the manifest is the cut</span> + <span className="font-semibold text-text" data-play-edit-words={working?.edits?.words.join("; ") ?? ""}> + {line} + </span> )} </span> <nav aria-label="What plays" className="flex flex-wrap items-center rounded-[3px] border border-seam-2 p-0.5 text-[12px]" data-play-takes=""> + {link({ id: null, label: "the working draft", made: true }, "Draft")} {pills.map((t) => link(t, t.id))} - {link({ id: null, label: "the manifest alone", made: true }, "manifest only")} {rest.length > 0 && ( <details className="relative" data-play-more-takes=""> <summary className="cursor-pointer list-none rounded-[2px] px-2 py-0.5 text-muted-2 hover:text-text">{rest.length} more ▾</summary> @@ -147,8 +141,8 @@ export default function WhatPlays({ </details> )} </nav> - {working?.picked && working.picked.id !== latest?.id && ( - <Link href={takesHref(project)} className="text-[11px] text-muted-2 hover:text-text" data-play-picked={working.picked.id} title={`“Use this take” last copied ${working.picked.id} over the manifest${working.picked.pinned ? " (pinned)" : ""}`}> + {working?.picked && ( + <Link href={takesHref(project)} className="text-[11px] text-muted-2 hover:text-text" data-play-picked={working.picked.id} title={`the pick: “Use this take” last copied ${working.picked.id} over the manifest${working.picked.pinned ? " (pinned)" : ""}`}> picked: {working.picked.id} {day(working.picked.at) ? ` (${day(working.picked.at)})` : ""} {working.picked.pinned ? ", pinned" : ""} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -70,6 +70,7 @@ Inbox cannot disagree about what is wrong with one. | `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-cancel-delete-fork-as-variant-compare)) | +| `takes save <project> [--label L] [--force] [--json]` · `takes open <project> <take> [--json]` · `takes freeze <project> [<take>… \| --all] [--apply] [--json]` | **the working draft and its saved versions** (Play's **Save version** and **Open in draft**): `save` freezes the draft (`video.manifest.json`) as the next `v<N>` — `takes/v<N>/base.manifest.json` byte for byte, `take.json` `version: true` — and names it the draft's parent (`takes/draft.json`); nothing is saved when the draft has no edits since its parent, unless `--force`. `open` copies a version into the draft — the draft saved first as the next `v<N>` when it has edits since its parent — with one undo point (`umtool timeline <p> undo` puts the draft and its parent back); a legacy take with its own timeline opens by its patch over the draft (as `take --promote`), another legacy take as the manifest it was rendered from (as `takes pick`). Neither touches the pick or its pin. `freeze` gives legacy takes a frozen base (the manifest each was rendered from, else the draft now) — a dry run unless `--apply`, each take's difference from how it resolves today said. Version ids are `v1`, `v2`, … — one above every `v<N>` directory under `takes/`, never reused ([knobs.md](knobs.md#the-working-draft-and-saved-versions)) | | `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)) · `--reel <name> [--take <t>]`: a **beat reel** -- its own beats file (`promo/<name>-beats.json`), crossfade, intro (one rendered for the reel when the master has none, or the reel's own) and outro card (the title, the call to action, an image, the site's name; faded in from the last beat, held to the end), written to `<slug>.<name>.mp4`; no `--take`: its pinned take, else the one it was last cut from, else the latest finished master ([report-video.md](report-video.md#beat-reels)) | | `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\|'<render.intro JSON>'` · `outro on\|off\|none\|'{title,text,image,seconds}'` · `candidates [--add]` · `verdict <n> confirmed\|note\|clear` · `title <text>\|none` · `take <t>\|none` · `undo` · `reels [--json]` · `new-reel <name> [--from <reel>] [--title T]` · `gap <n> add <from>-<to>\|remove <s>\|clear` · `status [--take <t>] [--json]` · `anchor [<n>…] --take <t>` · `clamp <n>` · `repoint <n> <clip>` · `history [--json]` · `--take <t>` on an edit · `--reel <name>` on any | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads) or another **beat reel's** (`--reel`: `promo/<name>-beats.json`): 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; the reel's own intro and its outro card (`ls`: `· outro 3.5 s`, counted in the length); every write an undo point and a history entry; a beat's gaps (two moments of one clip as one beat of jump cuts); each beat read against the take now -- what it was cut against, what changed (`status`), and the fixes ([knobs.md](knobs.md#the-trailers-beats), [reels track their source](knobs.md#reels-track-their-source)) | diff --git a/umtool/docs/clip-bench.md b/umtool/docs/clip-bench.md @@ -307,162 +307,22 @@ and **‹ Back to the cut** returns to the same clip, second and take without Pl header's links walk the CUT's order — the reel strip's neighbours, judged or not ("40 of 127") — not the walk's. Opened on its own, the bench's head has **▶ Play the cut from here**. -Play on a take WITH ITS OWN TIMELINE (its patch replaces the timeline — a tight version, a spin-off) opens -the take's bench instead ([Walking a take](#walking-a-take), `…/takes/<take>/clip/<id>?from=play`): the -save goes into the take's patch, never the project's clip of the same id, the head says **edits go to take -`<take>`, not the project's cut**, and **‹ Back to the cut** plays the take. A take without a timeline of its -own plays the project's cut as it is now, so its Edit stays the project's bench, as it says. - -### What the walk skips - -The walk visits the clips that still **need judgement** and are **fetched**, in -timeline order — so `p`, `n`, both header links, the start button and the jump -<kbd>y</kbd> makes after it confirms all go to the nearest one of those. - -- **Needs judgement** means no verdict: the same rule `N reviewed` counts by. - Walking back onto a clip somebody already answered is the round trip the walk - exists to remove. -- **Fetched** means some file in `out/clips-raw` holds this clip's own window - end to end (a clip with gaps fetched per piece: every kept piece is in some file). Not the *padded* window a build would download, and not an - overlap: a half-covered clip cannot be watched through, so there is nothing - to judge. Landing on one is a dead end whose only move is `n` again. - -A **URL still opens any clip**, judged or unfetched — the bench renders it, says -*"nothing fetched for this clip yet"* and carries a **not fetched yet** pill, -and its two links point at the fetched, unjudged neighbours either side. The -per-row link on the Cut tab is that URL, so "go to that one" is unchanged. - -Both pages read **`ready N of M needing judgement`**: `M` is the clips with no -verdict, `N` the ones among them that can be judged today. The gap between the -two is what is waiting on a download rather than on you — every row the project -page marks **not fetched yet**. - -### Prepared before you open it - -A clip whose source is a long recording (a saved whole stream, any window over -10 minutes) is opened on an **excerpt**: the clip and 45 s either side, edges -rounded out to 15 s, cut once into `out/bench-excerpts/<video>/<from>-<to>.excerpt.mp4` -(`lib/report/serve.mjs`). Cut on first open, that is 10–35 s of ffmpeg with the -bench saying "decoding the audio…", and then the waveform is decoded. - -So the walk is prepared ahead: **Prepare clips for the walk** under the Cut -tab's walk button (with `N of M ready to open` beside it, and what it is on while -it runs), `umtool prep <project>`, and on their own after a fetch lands a window -and after a write that moves a clip's extent or adds one (an excerpt is cut -only then; a waveform is made too after a fetch). It makes exactly what the -first open would: the excerpt, by the same name, and the waveform in the cache -`/api/report/peaks` reads. A clip already prepared is skipped (its excerpt cut -from its recording as it is now, its waveform cached). **Not "newer than its -recording"**: the cut records the recording's identity in -`<excerpt>.src.json`, and an excerpt whose record does not match the recording -today — or that has none — is cut again. A good copy replacing a corrupt one -under an older mtime used to leave the corrupt excerpts playing. Not the decoded audio: once the -excerpt exists `/api/report/audio` decodes the first span in a fraction of a -second. - -It runs as a background runner per project (`umtool prep <project> --run`), one -clip at a time, each in the machine's **heavy slot** with a declared estimate -of 400 MB (so it runs beside a render while the memory floor holds, and waits -when it does not), under `nice -n 19` and `ionice -c3`. Its progress is -`out/bench-excerpts/prep-status.json`, its log `prep.log` beside it. A clip you -open before it gets there is cut by the bench as before; a cut already running -in the other process is waited for, not repeated. `UMTOOL_BENCH_PREP=0` queues -nothing (`umtool prep --wait` still runs). - -### Keep it in the cut? - -A clip is a **claim** — the report said somebody said this, here — so the right -column opens with what this clip is *supposed to be* (its `quote`, and its -`note`: why it is in the cut) and then asks the one question the walk exists to -answer: **Keep c04 in the cut?** - -<kbd>y</kbd> confirms and **advances** — to the next clip on the walk, which is -the next one that needs an answer and has something to play — because in the yes -case that clip is what you want and a walk of sixty clips should be one finger. - -<kbd>x</kbd> is **Reject ▾**: the reasons a clip comes out, and *doesn't match* is -only one of them (operator, 2026-10-30: "I tend to want to reject clips not -because they don't match, but are irrelevant"). A digit picks one: - -| key | reason | what it means | stored | -|---|---|---|---| -| <kbd>1</kbd> | doesn't match | what is said doesn't match the quote or claim | `incorrect` + `correction` (required) | -| <kbd>2</kbd> | wrong speaker | somebody else is talking | `incorrect`, `reason: "wrong-speaker"` | -| <kbd>3</kbd> | irrelevant | accurate, but not relevant to this cut | `rejected`, `reason: "irrelevant"` | -| <kbd>4</kbd> | repeats | covered by an earlier clip (the note: which) | `rejected`, `reason: "repeats"` | -| <kbd>5</kbd> | weak | accurate and relevant, not strong enough | `rejected`, `reason: "weak"` | -| <kbd>6</kbd> | privacy | holds something that must not be published | `rejected`, `reason: "privacy"` | -| <kbd>7</kbd> | other | anything else (the note is required) | `rejected`, `reason: "other"` | - -The first two are FACT errors — corrections for the next report pass, blocking in -`umtool check`; the rest say the report is right and the clip just does not belong -here, and are never read as a correction. Picking one asks in the page — the clip, -the reason, a note — and then **Remove c04** takes it out of the cut in one write -(an undo point first, on record in `removed.json` with the reason and the note, -**Undo** and **Next clip ›** after), or **Reject, keep in place** writes the -verdict only, for removal later. **Wrong speaker** beside **Reject ▾** is the same -flow with its reason preset. On a phone the dock's **Reject…** opens the same -choice in a sheet. On a take's walk only *keep in place* is offered: a take's -timeline is a patch. - -Typing a `correction` on a clip nobody has judged still marks it **incorrect** in -the same patch (`{correction, verdict: "incorrect"}`), so the manifest never holds -a complaint with no verdict. - -An edge you nudged but never saved is confirmed WITH the clip: if the selection -differs from the stored window, <kbd>y</kbd> carries `start`/`end` (and clears a -cut the new extent no longer contains) in the same patch as the verdict, so -walking on never loses the window you just chose. - -### ★ and the walk note — not a verdict, not a correction - -<kbd>s</kbd> (or **☆ Star** beside the answers; **☆ Star** in the phone's status line) stars the -clip: a favourite, written at once (`star: true`). A starred clip is a **trailer candidate** — the -Cut tab lists them under **★ trailer candidates**, and `umtool trailer <p> --candidates [--json]` -prints them as a trailer's `--beats-json`. The **walk note** field (beside `correction`) takes an -editorial note — *this is gold*, *wants a beat of silence*, *move it to sex appeal* — as `walkNote`. -Neither touches the verdict, and neither is a `correction`: that field says the REPORT got a fact -wrong and is read by the next report pass. From a terminal: `umtool window <p> <clip> --star` -(`--no-star`), `--walk-note "…"` (`''` clears). A `correction` on a clip already confirmed (or rejected for a cut reason) is -usually such a note written in the only box there was: **move to walk note** beside it moves it in one -write (`umtool window <p> <clip> --walk-note "…" --correction ''`). A clip that re-plays another on purpose shows -**repeats `<clip>`** in the header (`repeatOf`). - -A window you save that leaves the clip's `cite` (the clock) — or its citeUrl's `t=` — more than 5 s -before what plays, or past its end, moves it to the clip's first second, and the save says so -(*saved — the cite followed the edge: 25:22 → 26:40, and the QR with it*). See -[knobs.md](knobs.md#the-cite-follows-the-edge). - -A note on a clip that is already **confirmed** is just a note — why its window -moved, a caveat for the writers — and writing one there leaves the verdict -alone — as it does on a clip rejected for a cut reason, whose facts are right. -The state line reads *not yet reviewed*, *confirmed*, *confirmed · with note*, -*incorrect — doesn't match* / *incorrect — wrong speaker* or *rejected — irrelevant* -(and the rest), and the header counts how much of the cut has been -reviewed. See -[report-video.md](report-video.md#verdict--what-the-walk-said) for what is -stored and what the writer refuses. +Play on a saved version (`?take=`) is read-only: its **Edit this clip** goes to **Open in draft** first +([knobs.md](knobs.md#the-working-draft-and-saved-versions)) — it asks, saves the draft as a version when it +has edits, copies the version in — then this bench on the DRAFT's clip. Every save here lands in the draft. ## Walking a take -`/projects/<project>/takes/<take>/walk` — from **Walk this take** on the take's card, or **walk a -take** on the Cut tab — lists the take's clips in walk order: each clip's window, length, verdict, -whether a fetched file holds it, and (→) the ones the walk visits, with **Walk → start at -`<clip>`**. A take is the project's manifest with its patch applied (a draft too: -[report-video.md](report-video.md#walking-a-take-drafts-edits-into-the-take-and-making-it-the-cut)), -so its clips may be windows the project's cut does not have — a tight version's sub-windows. Each -plays from the cached windows of its recording: a sub-window inside a fetched window plays without -a new fetch. - -`/projects/<project>/takes/<take>/clip/<id>` is this bench on the take's clip. Everything works as -on the project's cut, and **every save goes into the take's patch** (`takes/<take>/take.json`), -never the project's manifest: the verdict (`y`, `x` — kept in place), the edges, the attribution, the mute mark, -cut to quote, a wider fetch (the job is pointed at the take's manifest, written beside the -project's; the bytes land where every fetch's do). A strip at the top says **walking take -`<take>` — edits go to the take, not the cut**, with **← earlier**, **later →**, **Remove from -take** and **Undo take edit** (the take's newest edit taken back, whichever it was). The one-clip -re-render is not offered: a take is rendered whole (**Render full** on the Takes page, or `umtool -take <p> --id <take> --full`). +The take walk (`/projects/<project>/takes/<take>/walk`) and a take's bench +(`/projects/<project>/takes/<take>/clip/<id>`) are the **Open in draft** page now (umtool redesign L3: every +edit lands in the draft): it asks — *Open tight in draft? Your draft (2 edits since v3) is saved as v4 +first.* — copies the take into the draft (a take with its own timeline by its patch over the draft, as +**Make this the cut** merges it), then opens THIS bench on the draft's clip. When the take is the draft's +the draft already holds what the take is (its parent with no edits), the address goes straight on (307). Nothing in the UI writes a take's patch. + +A take's clips are still walked from a terminal, every save into the take's patch (`takes/<take>/take.json`), +never the project's manifest: `umtool walk <p> --take <take>`, `umtool window <p> <clip> --take <take> …` and +`umtool timeline <p> --take <take> move|remove|undo|insert` ([cli.md](cli.md)). **Prepared before you open it, per take.** The take's walk page carries **Prepare clips for the walk**, and `umtool prep <project> --take <take>` makes the same excerpts and waveforms the take's bench would make diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -591,35 +591,82 @@ build does that the preview does not: it snaps each edge to a silence (the deck' (here the clip plays alone), it applies room's muted edges and the clip's Audio knobs, and it draws in the render's browser. **Render this clip** is the pixel-true check of all of that but the joins. +## The working draft and saved versions + +**Every edit lands in the draft.** The project's `video.manifest.json` IS the working draft: the bench, Play, the Cut +tab, Add a clip and every agent write it, and nothing in the UI writes a take's patch any more (umtool redesign L3, +after the kirsche-7 kr1 bug of 2 Nov: an edge made "in a take" landed in the take's patch while the operator +expected the cut). A take is a **saved version** — FROZEN: + +| Knob | UI | CLI twin | +|---|---|---| +| save the draft as the next version | the head's **Save version** (says *saved as v3*, or *no edits since v2: nothing to save*) | `umtool takes save <p> [--label L] [--force] [--json]` | +| play a version, read-only | Play's version switch (`?take=v2`): **Open in draft**, **Watch render** when it has an mp4 | `umtool present <p> --take v2` (read) | +| open a version in the draft | **Open in draft** (it asks: *Open v1 in draft? Your draft (2 edits since v2) is saved as v4 first.*) | `umtool takes open <p> <take> [--json]` | +| undo an open | the Cut tab's **Undo last edit** (the undo point `auto-before-open-<take>`) | `umtool timeline <p> undo` | +| freeze legacy takes | — | `umtool takes freeze <p> [<take>… \| --all] [--apply] [--json]` | + +- **A version is frozen.** `takes save` copies the draft byte for byte to `takes/v<N>/base.manifest.json` and writes + `take.json` `{version: true, draft: true, patch: null, window: "full", baseHash}` (the base's hash). Play, Present, + a render (`umtool take <p> --id v3 --full`, `--rebuild`, `--preview`) and every take reader lay a version over ITS + base, never over the draft as it is now (`lib/report/takeManifest.mjs` resolveTakeManifest, takeMaker composeTake). + A version rendered stays a version (its mp4 is the frozen bytes). A take made before versions — no + `base.manifest.json` — resolves exactly as it always did (its patch over the draft now) until `takes freeze`. +- **Version ids** are `v1`, `v2`, … — one above every `v<N>` directory under `takes/` (made or not), so a name is never + reused and never collides with a take named by hand (`lib/report/versions.mjs` nextVersionId). +- **The draft's parent** is `takes/draft.json` `{from, hash, at}`: the version it was last saved as or opened from + (a whole-cut take rendered from the draft becomes it too), else the newest working take. Play's head reads + **Draft · from v5 · 3 edits** (hover lists them: `aw3 removed`, `mc1 moved`) or **Draft · unsaved**; the bench and + the Takes page say the same; `umtool takes ls` prints it first. The edits are counted by `cutDiff` (a hash only + short-cuts 0): the draft against the parent frozen — a version's base, a legacy take's rendered manifest, or what + an open of a legacy take wrote (`lib/report/workingCut.mjs`). +- **Opening never loses the draft.** `takes open` (and **Open in draft**) saves the draft first as the next version + when it has edits since its parent (or none at all), then writes the version over it through the manifest writer, + under the manifest lock, with an undo point taken EVERY time; **Undo** puts the draft back as it was and its parent + with it (a sidecar of the snapshot). A legacy take with its own timeline opens by its patch over the draft (as + `take --promote` merges it: a walk made since its render is what opens), another legacy take as the manifest it + was rendered from (as `takes pick` copies it) — unless its patch was edited since that render, when it opens by its + patch too. Version ids are claimed with an exclusive mkdir (the CLI beside the app never gets the same one), and a + number a draft pointer or an undo point's sidecar still names is never reused. Opening a version the draft already holds (compared by content: a version's "No intro" since its save is a difference) writes nothing — its + Open in draft page goes straight on (307: it depends on the draft now) to the draft's bench. +- **One undo stack.** In the app every edit is its own undo point (`revisions/<stamp>-auto-before-<op>`, the server + process sets it for itself at boot — a step it spawns keeps the terminal's throttle) — a clip's edges included (`auto-before-trim`) — so two trims a minute apart + are two **Undo last edit**s; from a terminal the old throttle stands (one per op every two minutes, so an agent's + burst is one step back). Two undo points in one second are two files (the stamp gains its milliseconds, + `20261109-143012.457-auto-before-trim`), and only the newest 200 `auto-before-*` are kept. A verdict alone is not an + undo point (the bench's own Undo takes it back). +- **A preset stays named.** Opening a legacy take never writes a preset-resolved manifest into the draft: the + rendered file's `presetApplied` goes back to `preset`, the keys that are the preset's own taken out (an override + stays), and a merge lays the patch over the draft without resolving anything. A legacy take that is the draft's + parent with no edits opens as nothing (main's rule), so its 307 straight-on holds in a project naming a preset. +- **Open in draft and Save version refuse another site's post** (`Sec-Fetch-Site`, `Origin` against the request's + host). A proxy that rewrites `Host` must set `X-Forwarded-Host` (Caddy keeps `Host`). +- **The pick is not touched.** Neither saving nor opening moves or unpins the pick in `verdicts.json` (**Use this + take** still does). +- **Old addresses.** The take walk (`/projects/<p>/takes/<t>/walk`) and a take's bench (`…/takes/<t>/clip/<id>`) are + the Open in draft page now — then the draft's bench. The take-scoped CLI (`--in-take`, `umtool timeline <p> --take`, + `umtool window --take`, `/api/report/takes/timeline`) stays for agents. + ## Play the cut (the whole cut, or a take, with no render) -`/projects/<p>/play` — the Cut tab's **Play the cut**, or a take's **Play** on the takes page +`/projects/<p>/play` — the head's **▶ Play the draft**, or a version's **Play** on the takes page (`/projects/<p>/play?take=<id>`) — plays the WHOLE cut in this browser in its final look, for iterating without a -render. **With no `take` it plays the LATEST take** (below), the look of the next draft; `?cut=1` plays the -manifest alone. It plays every entry in timeline order, each clip from its cached source window (the bench's media route, an +render. **With no `take` it plays THE DRAFT** (above), where every edit lands; `?cut=1` is the same. It plays every entry in timeline order, each clip from its cached source window (the bench's media route, an excerpt of a long recording), the live preview's chrome over it on ONE cut clock — the rail's pip, the tally, the stamps, the markers and the finale advance as in the render, and every module that declares **`play`** in the module contract — the chapter cards over the first seconds of the clip each opens, the then-and-now pair strip, the status ledger, the stats, the effects, the side panel, the flips — laid at its region in the build's z order, up -only where the build lays it ([Modules](#modules), "Play the cut and the live preview") — at the render's own edges (below). A take plays the project's manifest **as it is now** with the take's style patch and its -own patch (a take's own `timeline` included), from `takes/<id>/take.json` or — not rendered yet — a recipe that +only where the build lays it ([Modules](#modules), "Play the cut and the live preview") — at the render's own edges (below). A version plays its frozen base with its style and patch; a legacy take plays the draft +**as it is now** with the take's style patch and its own patch (a take's own `timeline` included), from `takes/<id>/take.json` or — not rendered yet — a recipe that names it; its pages are composed under `takes/<id>/out/`, never over the project's. `render.blur: "off"` on the take plays its blurred clips as recorded. -**The working cut is the latest take** (operator, 1 Nov 2026: "most of the time I'll only really be working on the -latest cut/draft rather than the picked one"). The head names it as prominently as a take — **Latest: draft-22 · -28:03 · +3 edits since** (hover lists them: `aw3 removed`, `mc1 moved`, `ss1 gaps`) — the newest WHOLE-CUT take made -from the project (`take.json` window `full`, rendered, not quick, no montage style, no `timeline` of its own: a -*working* take, `lib/report/takes.mjs` isWorkingTake), and the edits are the project's manifest against the manifest -that take rendered (`0` when the manifest's hash is the take's `baseHash`; `lib/report/workingCut.mjs`). The other -takes are a switch beside it (pills, the rest behind **N more**), **manifest only** the bare manifest; the pick (Use -this take, below) is named small only when it is not the latest. Every edit made in Play — a reorder, Reject, the -bench — writes the PROJECT's manifest, which a working take plays as it is now, so the latest take shows it at once; -a take with its own timeline says so and offers no structural edit (its walk edits it), and its **Edit this clip** -opens the TAKE's bench on the clip (`/projects/<p>/takes/<take>/clip/<id>?from=play`): the save goes into -`takes/<take>/take.json`, never the project's clip of the same id, and **‹ Back to the cut** plays that take. `umtool takes ls <p>` prints -the same line first and marks `latest`; the Takes page shows it and a **latest** badge. **Re-render the take** (the -clip editor and the clip deck) remakes the latest take — it used to need a pick when there were two whole-cut takes. +**A version is played read-only.** The head names the draft first — **Draft · from v5 · 3 edits** — then the switch: +**Draft**, the versions (pills, the rest behind **N more**); the pick (Use this take) is named small. On a version +nothing structural is offered (no reorder, Reject or Add a clip), and **Edit this clip** (E) goes to **Open in +draft** for that clip — it asks, saves the draft first when it has edits, copies the version in — then the DRAFT's +bench on the clip; **‹ Back to the cut** plays the draft. **Re-render the take** (the clip editor and the clip deck) +remakes the latest take. **A rejected clip is skipped.** A clip the walk rejected — a fact error (`incorrect`: doesn't match, wrong speaker; or a legacy `correction` and no verdict) or a cut reason (`rejected`: irrelevant, repeats, weak, privacy, other) — is @@ -641,8 +688,7 @@ take. but never unmounted, so its composed deck, decoded sound, measured edges, the strip's zoom and the take stay as they were (`components/projects/cutApp/CutApp.tsx`; the bench's data is `GET /api/report/bench`, the same function its own page renders from, `lib/report/benchData.ts`). The address moves by `history.pushState` to the bench's -(`/clip/<id>?from=play&at&take&order=cut`; on a take with its own timeline, the take's bench, -`/takes/<take>/clip/<id>?from=play&at&order=cut`): the browser's Back and Forward step between the two, a reload or a link is +(`/clip/<id>?from=play&at&order=cut`; on a saved version, Edit goes to **Open in draft** first, a page of its own): the browser's Back and Forward step between the two, a reload or a link is the bench's own page, and **‹ Back to the cut** goes back the entries it pushed (no second Play in the history). Inside Play the bench walks the CUT's order (`order=cut`: p / n are the reel strip's neighbours, judged or not, `40 of 127`; the neighbours are read ahead). Back on Play the view is read again in place (`GET /api/report/play-view`), the deck @@ -654,11 +700,10 @@ history entry of its own), so **Edit this clip** (E) and then the browser's **Ba cut** — lands paused on the same second of the same clip. When an edit moved that clip in the cut, Play resumes by the clip and the offset into it, and says **Back at c02 · 00:03.0 (the cut changed)**. -**To judge a take clip by clip, walk it** (`/projects/<p>/takes/<id>/walk`, **Walk this take** on its card): -the clip bench on the take's own clips, whose verdicts, trims and removals go into the take's patch, never the -project's manifest; `umtool walk <p> --take <id>`, `umtool window <p> <clip> --take <id> …` and `umtool timeline -<p> --take <id> move|remove|undo` are the terminal's. **Make this the cut** (`umtool take <p> --id <id> --promote`) -puts the walked take over the project's manifest with one undo +**To judge a version clip by clip, open it in the draft** (**Open in draft** on its card or in Play) and walk the +draft; a take's clips are walked from a terminal only (`umtool walk <p> --take <id>`, `umtool window <p> <clip> +--take <id> …`, `umtool timeline <p> --take <id> move|remove|undo`), their saves into the take's patch. **Make this +the cut** (`umtool take <p> --id <id> --promote`) puts the take over the project's manifest with one undo ([report-video.md](report-video.md#walking-a-take-drafts-edits-into-the-take-and-making-it-the-cut)). | | In umtool | Keys | @@ -1546,19 +1591,17 @@ has the recipe. | the read's pieces, in the take | `umtool posts roles <p> <item> --set n=role --in-take <t>` | the take's entry's take parts | | the pick, a new read, a thread read, the mix | `umtool posts narrate <p> <item> --pick <n> \| --take [--thread …] \| --script "…" \| k=v --in-take <t>` | the take's entry; a new read's file in `<p>/narration/` under a number no file or entry has | | a re-join (no TTS) | `umtool posts reread <p> <item> --without parent:0 … --in-take <t>` | the take's entry, the new take picked there (the project keeps its pick) | -| pauses after words of the read (no TTS) | `umtool posts reread <p> <item> --pause "20=0.45,10=0.45" --in-take <t>` · the post bench's **pause after** on `?inTake=<t>` | the take's entry, the new take picked there (the project keeps its pick) | -| one phrase of the read re-voiced (TTS for that phrase only) | `umtool posts reread <p> <item> --revoice "20 10 4 0" --say "20... 10... 4... 0..." --in-take <t>` · the post bench's **re-voice a phrase** on `?inTake=<t>` | the take's entry, the new take picked there (the project keeps its pick); the piece in the project's `narration/parts-cache/` | +| pauses after words of the read (no TTS) | `umtool posts reread <p> <item> --pause "20=0.45,10=0.45" --in-take <t>` | the take's entry, the new take picked there (the project keeps its pick) | +| one phrase of the read re-voiced (TTS for that phrase only) | `umtool posts reread <p> <item> --revoice "20 10 4 0" --say "20... 10... 4... 0..." --in-take <t>` | the take's entry, the new take picked there (the project keeps its pick); the piece in the project's `narration/parts-cache/` | | an effect | `umtool posts fx <p> <item> add caption … --in-take <t>` | the take's entry's `fx` | | look, check, take back | `umtool timeline <p> --take <t>` · `umtool lint <p> --take <t>` (exit 0 clean) · `umtool timeline <p> --take <t> undo` | — / — / the take's newest edit, byte for byte | -**In umtool** (lane/ui-simplify): a take card's Options and the take walk's have **Check before render** (the lint), -**New draft from this take** (the next free `<take>-d<n>`) and **Add items from another project** (the project, the -items, by date or after/before an entry; **Preview** is `--dry-run`, then **Import into <take>**); New take has **Save -as a draft**. The post bench's **edits go to: take <t> only** scopes its set-item, fx and combo writes to the take -(`--in-take`), and its lanes: an attachment's in and out (the lane's handles, saved with **Save**), the read's lead -(dragged) and **Re-pick best** (`POST /api/report/post-narration {op: "set" | "fit" | "reread", inTake}`); recording a -read, a re-take and the mix are still the cut's bench's, and a read for the take is still the terminal's. A clip into a take only is the take walk's **+ Add a clip to -<take> only** (`umtool timeline <p> --take <t> insert <spec> --after <id>`). +**In umtool** (lane/ui-simplify): a take card's Options have **Check before render** (the lint), **New draft from this +take** (the next free `<take>-d<n>`) and **Add items from another project** (the project, the items, by date or +after/before an entry; **Preview** is `--dry-run`, then **Import into <take>**); New take has **Save as a draft**. The +post bench's take-only scope and the take walk's **+ Add a clip to <take> only** are RETIRED (umtool redesign L3: +every UI edit lands in the draft — open the take in the draft first); their writes are the terminal's (`--in-take`, +`umtool timeline <p> --take <t> insert <spec> --after <id>`, `POST /api/report/post-narration {…, inTake}`). Each edit is an undo point of the take's (`takes/<t>/revisions/`). An edit that changes nothing writes nothing. A take that is rendering is not edited (exit 1). The narration's lexicon and diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -2544,6 +2544,11 @@ touched. A pruned take rebuilt, or used as a `--from` base, renders its work aga ### Walking a take: drafts, edits into the take, and making it the cut +> **The UI walks the draft only** (umtool redesign L3, [knobs.md](knobs.md#the-working-draft-and-saved-versions)): +> every UI edit lands in the project's manifest, a saved version is frozen, and the take walk's addresses are the +> **Open in draft** page. What follows is the TERMINAL's take walk (`umtool walk|window|timeline --take`), kept for +> agents. + A take can be **walked** on the clip bench like the project's own cut — its clips, played from the cached windows (a sub-window inside a fetched window plays without a new fetch), each confirmed, noted, trimmed, removed or moved — and every one of those edits goes into the **take's patch**, diff --git a/umtool/e2e/cut-sections.spec.ts b/umtool/e2e/cut-sections.spec.ts @@ -72,7 +72,9 @@ test("move to section…: the clip lands at the section's end, the markers and t await expect.poll(order).toEqual(["c02", "c04", "c03", "c05", "c06", "c01"]); expect(afters()).toEqual(["c04", "c03"]); await expect.poll(patchAfters).toEqual(["c04", "c03"]); - // Undo takes back the burst (one undo point per op within two minutes: manifest.mjs autoSnapshot). + // Undo takes back one move at a time (one undo stack, L3: in the app every op is its own undo point). + await page.getByTestId("timeline-undo").click(); + await expect.poll(order).toEqual(["c02", "c03", "c04", "c05", "c06", "c01"]); await page.getByTestId("timeline-undo").click(); await expect.poll(order).toEqual(["c01", "c02", "c03", "c04", "c05", "c06"]); }); @@ -124,6 +126,11 @@ test("a section bar dragged onto a clip moves the boundary; a clip dropped on a await page.locator("[data-bar-handle='1']").dragTo(page.locator("li[data-entry='c03'][data-kind]")); await expect.poll(afters).toEqual(["c02", "c03"]); expect(patchAfters()).toEqual(["c02", "c03"]); + // The page has redrawn the bars where the file now has them (a drag on the old rows would land nowhere). + await expect + .poll(() => page.locator("[data-testid=timeline-list] > li").evaluateAll((els) => els.map((e) => e.getAttribute("data-entry") ?? `§${e.getAttribute("data-section-bar")}`))) + .toEqual(["§0", "c01", "c02", "§1", "c03", "§2", "c04", "c05", "c06"]); + await page.waitForLoadState("networkidle"); // Not past its neighbour: onto c01 is refused in words. await page.locator("[data-bar-handle='1']").dragTo(page.locator("li[data-entry='c01'][data-kind]")); await expect(page.getByTestId("timeline-error")).toContainText("would cross or touch"); diff --git a/umtool/e2e/draft-versions.spec.ts b/umtool/e2e/draft-versions.spec.ts @@ -0,0 +1,125 @@ +import { test, expect } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// THE WORKING DRAFT AND ITS SAVED VERSIONS (umtool/docs/knobs.md, "The working draft and saved versions"; +// lib/report/versions.mjs): every edit lands in video.manifest.json (the draft); a saved version is frozen; +// opening a version saves the draft first when it has edits, and one Undo puts the draft -- and its parent -- +// back. +// +// draft-versions-fixture (WRITES; make-fixture.mjs): play-cut-fixture's cut on vid1 (c01 c02 k01 c03 c04), +// no takes. The tests run in order, each leaving what the next reads. +// --------------------------------------------------------------------------- + +test.describe.configure({ mode: "serial" }); + +const P = "reports/draft-versions-fixture"; +const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "draft-versions-fixture"); +const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8"); +const order = () => (JSON.parse(manifestText()) as { timeline: { id: string }[] }).timeline.map((e) => e.id).join(" "); +const draftFrom = () => (JSON.parse(readFileSync(path.join(DIR, "takes", "draft.json"), "utf8")) as { from: string }).from; +const base = (id: string) => readFileSync(path.join(DIR, "takes", id, "base.manifest.json"), "utf8"); +const takeDoc = (id: string) => JSON.parse(readFileSync(path.join(DIR, "takes", id, "take.json"), "utf8")) as Record<string, unknown>; + +test("edit → save v1 → edit → open v1: the draft saved as v2 first, v1 back byte for byte; Undo restores the pre-open draft and its parent", async ({ request }) => { + expect(order()).toBe("c01 c02 k01 c03 c04"); + const original = manifestText(); + // An edit, then saved as v1: frozen byte for byte. + let r = await request.post("/api/report/timeline", { data: { project: P, op: "move", id: "c04", toIndex: 0 } }); + expect(r.ok(), await r.text()).toBe(true); + const edited = manifestText(); + expect(edited).not.toBe(original); + r = await request.post("/api/report/takes/save", { data: { project: P, label: "First pass" } }); + expect(r.ok(), await r.text()).toBe(true); + expect(await r.json()).toMatchObject({ saved: true, id: "v1", label: "First pass" }); + expect(base("v1")).toBe(edited); + expect(takeDoc("v1")).toMatchObject({ version: true, draft: true, patch: null, window: "full" }); + expect(draftFrom()).toBe("v1"); + // Saving again with no edits saves nothing. + r = await request.post("/api/report/takes/save", { data: { project: P } }); + expect(await r.json()).toMatchObject({ saved: false, id: "v1" }); + + // Another edit: v1 does not follow it. + r = await request.post("/api/report/timeline", { data: { project: P, op: "move", id: "c01", toIndex: 4 } }); + expect(r.ok(), await r.text()).toBe(true); + const preOpen = manifestText(); + expect(order()).toBe("c04 c02 k01 c03 c01"); + expect(base("v1")).toBe(edited); + + // Open v1: the draft (1 edit) is saved as v2 first, then v1 is the draft. + r = await request.post("/api/report/takes/open", { data: { project: P, take: "v1" } }); + expect(r.ok(), await r.text()).toBe(true); + const o = await r.json(); + expect(o).toMatchObject({ opened: "v1", saved: "v2", how: "frozen" }); + expect(base("v2")).toBe(preOpen); + expect(takeDoc("v2")).toMatchObject({ version: true, draftedFrom: "v1" }); + expect(manifestText()).toBe(edited); + expect(draftFrom()).toBe("v1"); + // Opening it again writes nothing. + r = await request.post("/api/report/takes/open", { data: { project: P, take: "v1" } }); + expect(await r.json()).toMatchObject({ unchanged: true }); + + // Undo: exactly the open -- the pre-open draft, and its parent (v2, what it was saved as). + r = await request.post("/api/report/timeline", { data: { project: P, op: "undo" } }); + expect(r.ok(), await r.text()).toBe(true); + expect((await r.json()).op).toBe("open-v1"); + expect(manifestText()).toBe(preOpen); + expect(draftFrom()).toBe("v2"); +}); + +test("the CLI twin's contract: a stale token is refused, the draft untouched", async ({ request }) => { + const before = manifestText(); + const r = await request.post("/api/report/takes/open", { data: { project: P, take: "v1", token: "1" } }); + expect(r.status()).toBe(409); + expect((await r.json()).stale).toBe(true); + expect(manifestText()).toBe(before); +}); + +test("Play is the draft, named by its parent; a version plays read-only; Open in draft asks, then lands on the draft; Save version on the head", async ({ page, request }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + // After the undo above: the draft is v2's content, from v2, no edits. + await page.goto(urls.playHref(P)); + const root = page.locator("[data-play-cut]"); + await expect(root).toHaveAttribute("data-play-state", "paused", { timeout: 30_000 }); + await expect(root).toHaveAttribute("data-play-cut", ""); + await expect(page.locator("[data-play-draft]")).toHaveAttribute("data-play-draft", "v2"); + await expect(page.locator("[data-play-draft]")).toContainText("Draft · from v2 · no edits"); + await page.screenshot({ path: test.info().outputPath("play-draft.png") }); + + // v1, read-only, with Open in draft. + await page.locator('[data-play-take-link="v1"]').click(); + await expect(root).toHaveAttribute("data-play-cut", "v1", { timeout: 20_000 }); + await expect(page.locator('[data-play-take="v1"]')).toHaveAttribute("data-play-take-frozen", ""); + await expect(page.locator('[data-play-take="v1"]')).toContainText("read-only"); + await expect(page.locator("[data-play-watch-render]")).toHaveCount(0); + await page.screenshot({ path: test.info().outputPath("play-version.png") }); + await page.locator('[data-play-open-draft="v1"]').click(); + const ask = page.locator('[data-open-draft="v1"]'); + await expect(ask.locator("[data-open-draft-said]")).toContainText("no edits since v2 — nothing to save"); + await expect(ask).toHaveAttribute("data-open-draft-saves", ""); + await page.screenshot({ path: test.info().outputPath("open-in-draft.png") }); + await ask.locator("[data-open-draft-confirm]").click(); + await expect(page).toHaveURL(/\/projects\/reports\/draft-versions-fixture\/play$/); + await expect(page.locator("[data-play-draft]")).toContainText("Draft · from v1 · no edits", { timeout: 20_000 }); + expect(manifestText()).toBe(base("v1")); + expect(draftFrom()).toBe("v1"); + + // The head's Save version: nothing at no edits; after an edit, v3. + await page.goto(urls.projectHref(P, { tab: "cut" })); + await expect(page.locator('[data-play-link="header"]')).toHaveAttribute("href", urls.playHref(P)); + await expect(page.locator("[data-primary-draft]")).toContainText("from v1 · no edits"); + await page.locator("[data-save-version]").click(); + await expect(page.locator("[data-save-version-said]")).toContainText("no edits since v1"); + const r = await request.post("/api/report/timeline", { data: { project: P, op: "move", id: "c02", toIndex: 0 } }); + expect(r.ok(), await r.text()).toBe(true); + await page.reload(); + await expect(page.locator("[data-primary-draft]")).toContainText("from v1 · 1 edit"); + await page.locator("[data-save-version]").click(); + await expect(page.locator("[data-save-version-said]")).toContainText("saved as v3"); + await page.screenshot({ path: test.info().outputPath("head-save-version.png") }); + expect(base("v3")).toBe(manifestText()); + expect(draftFrom()).toBe("v3"); +}); diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -2134,6 +2134,25 @@ makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out writeFileSync(path.join(pwDir, "takes", "verdicts.json"), JSON.stringify({ "draft-0": { verdict: null, note: "", at: "2026-10-30T11:00:00.000Z", picked: true } }, null, 2) + "\n"); } +// The working draft and its saved versions (draft-versions.spec.ts, WRITES): play-cut-fixture's cut on vid1, +// no takes -- the spec saves v1, edits, opens v1 (the draft saved as v2 first) and undoes it. +{ + const { dir: dvDir } = makePlayCutFixture({ + reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), + name: "draft-versions-fixture", title: "The Draft Versions Fixture", video: "vid1", + }); + rmSync(path.join(dvDir, "takes"), { recursive: true, force: true }); +} + +// One undo stack (undo.spec.ts, WRITES): two trims a moment apart, then two undos -- its own copy. +{ + const { dir: unDir } = makePlayCutFixture({ + reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), + name: "undo-trim-fixture", title: "The Undo Trim Fixture", video: "vid1", + }); + rmSync(path.join(unDir, "takes"), { recursive: true, force: true }); +} + // TWO MORE cached windows for vid1, and they are the regression rather than // decoration. // diff --git a/umtool/e2e/fixtures/play-cut-fixture.mjs b/umtool/e2e/fixtures/play-cut-fixture.mjs @@ -6,7 +6,8 @@ // window on the estimate's clock -- with a card between clips, a clip whose // source was never fetched (a placeholder, not a stall), and two takes: one // made (takes/short/take.json, its own timeline: c04 then c01) and one only -// a recipe names (quick-joins, a hard-cut look). And play-engine-fixture, the +// a recipe names (quick-joins, a hard-cut look), and a saved version, v1 (its +// frozen base: c01 c02 c04). And play-engine-fixture, the // same cut for play-engine.spec.ts, which writes. // // c01 playvid 1.0-3.0 c02 playvid 3.5-5.5 (k1 at 4.5) k01 card 1.5 s @@ -14,6 +15,7 @@ // sections 0 (c01, c02) and 1 (c03, c04); one counter, "Seizures" // // Synthetic, like every fixture. +import { createHash } from "node:crypto"; import { copyFileSync, mkdirSync, writeFileSync } from "node:fs"; import path from "node:path"; @@ -74,6 +76,26 @@ export function makePlayCutFixture({ reports, deckManifest, cachedWindow, name = writeFileSync(path.join(eng, "video.manifest.json"), JSON.stringify({ ...m, slug: "play-engine-fixture", title: "The Play Engine Fixture" }, null, 2) + "\n"); copyFileSync(cachedWindow, path.join(eng, "out", "clips-raw", `${video}_0.00-9.00.mp4`)); } + // A SAVED VERSION (lib/report/versions.mjs), play-cut-fixture's own: the cut frozen without c03 and the card, + // as `umtool takes save` writes one -- Play ?take=v1 plays its base, never the manifest as it is now. + if (name === "play-cut-fixture") { + const vdir = path.join(dir, "takes", "v1"); + mkdirSync(vdir, { recursive: true }); + const baseText = JSON.stringify({ ...m, render: { ...m.render, lockedEdges: false }, timeline: [timeline[0], timeline[1], timeline[4]] }, null, 2) + "\n"; + writeFileSync(path.join(vdir, "base.manifest.json"), baseText); + writeFileSync( + path.join(vdir, "take.json"), + JSON.stringify( + { + id: "v1", group: "takes", order: 2, label: "Saved draft", kind: "reference", summary: "", changes: [], preview: "preview.mp4", + seconds: null, builtAt: null, style: null, patch: null, window: "full", version: true, draft: true, + draftedAt: "2026-11-09T10:00:00.000Z", savedAt: "2026-11-09T10:00:00.000Z", baseHash: createHash("sha256").update(baseText).digest("hex"), + }, + null, + 2, + ) + "\n", + ); + } // A take only a recipe names: never rendered, still playable. writeFileSync( path.join(dir, "takes", "recipe.json"), diff --git a/umtool/e2e/fixtures/take-walk-fixture.mjs b/umtool/e2e/fixtures/take-walk-fixture.mjs @@ -12,7 +12,8 @@ // t01b 3.50-6.00 no verdict -- where the walk starts // t01c 6.20-8.50 no verdict // -// Synthetic, like every fixture. +// take-walk-fixture also has a saved version v1 of the master (base.manifest.json) and the draft pointer +// naming it (takes/draft.json). Synthetic, like every fixture. // // `name`/`title`: the same project under another name, for a spec that must // not share it -- play-take-edit-fixture (play-take-edit.spec.ts: Play on the @@ -73,5 +74,21 @@ export function makeTakeWalkFixture({ reports, manifest, cachedWindow, name = "t baseHash, }), ); + // A SAVED VERSION of the master (lib/report/versions.mjs), take-walk-fixture's own: its frozen base, and the + // draft's parent (takes/draft.json) -- so the draft starts "from v1, no edits". + if (name === "take-walk-fixture") { + const text = readFileSync(path.join(dir, "video.manifest.json"), "utf8"); + write(path.join(dir, "takes", "v1"), "base.manifest.json", text); + write( + path.join(dir, "takes", "v1"), + "take.json", + json({ + id: "v1", group: "takes", order: 2, label: "Saved draft", kind: "reference", summary: "", changes: [], preview: "preview.mp4", + seconds: null, builtAt: null, style: null, patch: null, window: "full", version: true, draft: true, + draftedAt: "2026-11-09T10:00:00.000Z", savedAt: "2026-11-09T10:00:00.000Z", baseHash, + }), + ); + write(path.join(dir, "takes"), "draft.json", json({ from: "v1", hash: baseHash, at: "2026-11-09T10:00:00.000Z" })); + } return dir; } diff --git a/umtool/e2e/intro-play.spec.ts b/umtool/e2e/intro-play.spec.ts @@ -8,7 +8,7 @@ import * as urls from "./urls"; // THE INTRO AS A REAL, PLAYABLE BLOCK (lane intro-play; operator, 8 Nov 2026: "more first-class intro support (view // in play the cut)"; umtool/docs/knobs.md, "The intro, played and edited"): the cut's render.intro plays as the build // draws it -- its own page (report-to-video intro.mjs introPageHtml, composed by POST /api/report/chrome/intro) and -// its sound -- in Play, as Present's first slide, first on the walk; and the Cut tab's intro row opens an editor whose +// its sound -- in Play, as Present's first slide, first on the walk's stops; and the Cut tab's intro row opens an editor whose // live preview follows the unsaved knobs and whose Save writes the manifest. // // Fixture: e2e/fixtures/intro-play-fixture.mjs -- the Play cut opening on a title-card intro (the project's title, @@ -23,7 +23,7 @@ const PROJECT = "reports/intro-play-fixture"; const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "intro-play-fixture"); const SHOTS = process.env.INTRO_SHOTS ?? null; const manifest = () => JSON.parse(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")) as { render: { intro?: unknown } }; -const takeDoc = (id: string) => JSON.parse(readFileSync(path.join(DIR, "takes", id, "take.json"), "utf8")) as { patch: { render?: { intro?: unknown } } }; +const takeDoc = (id: string) => JSON.parse(readFileSync(path.join(DIR, "takes", id, "take.json"), "utf8")) as { patch: { render?: { intro?: unknown } } | null }; const shot = async (page: Page, name: string) => { await page.screenshot({ path: test.info().outputPath(name) }); @@ -75,14 +75,10 @@ test("Present opens the deck on the intro slide, playing the build's page", asyn await expect(root).not.toHaveAttribute("data-present-slide", "brand-intro"); }); -test("the walk lists the intro first: the take walk's first row, and the walk's stops", async ({ page, request }) => { +test("the walk lists the intro first: the walk's stops (a version's old walk address is Open in draft, L3)", async ({ page, request }) => { + // v1 is the cut as written (its rendered manifest is the draft's bytes): nothing to copy, straight on to Play. await page.goto(urls.takeWalkHref(PROJECT, "v1")); - const rows = page.locator("[data-take-walk-clips] tbody tr"); - await expect(rows.first()).toHaveAttribute("data-take-walk-intro", "title-card"); - await expect(rows.first()).toContainText("watched, not judged"); - await expect(rows.first()).toContainText("29 October 2026"); - await expect(rows.nth(1)).toHaveAttribute("data-take-walk-clip", /c0\d/); - await shot(page, "intro-walk.png"); + await expect(page).toHaveURL(new RegExp(`/projects/${PROJECT}/play$`)); const w = (await (await request.get(`/api/report/walk?project=${encodeURIComponent(PROJECT)}`)).json()) as { stops: string[]; intro: { style: string } | null; first: string | null }; expect(w.stops[0]).toBe("brand-intro"); expect(w.intro?.style).toBe("title-card"); @@ -124,7 +120,7 @@ test("the Cut tab's intro row: Edit opens the knobs and a live preview; a new ti const v1 = editor.locator('[data-intro-version="v1"]'); await expect(v1).toBeChecked(); await v1.uncheck(); - await expect.poll(() => takeDoc("v1").patch.render?.intro, { timeout: 10_000 }).toBeNull(); + await expect.poll(() => takeDoc("v1").patch?.render?.intro, { timeout: 10_000 }).toBeNull(); await expect(v1).not.toBeChecked(); expect((manifest().render.intro as { title?: string }).title).toBe("A title of its own"); await expect(row.locator("[data-intro-versions-off]")).toContainText("v1"); @@ -132,11 +128,13 @@ test("the Cut tab's intro row: Edit opens the knobs and a live preview; a new ti await page.goto(urls.playHref(PROJECT, { take: "v1" })); await expect(page.locator("[data-play-cut]")).toHaveAttribute("data-play-item", "c01", { timeout: 30_000 }); await expect(page.locator("[data-play-intro]")).toHaveCount(0); - // Back on: it opens on the cut's intro again. + // Back on: the key comes OFF its patch (no stale copy of the cut's intro) -- it opens on the intro again. await page.goto(urls.projectHref(PROJECT, { tab: "cut" })); await page.locator("[data-intro-edit]").click(); await page.locator('[data-intro-version="v1"]').check(); - await expect.poll(() => JSON.stringify(takeDoc("v1").patch.render?.intro), { timeout: 10_000 }).toBe(JSON.stringify(manifest().render.intro)); + await expect.poll(() => JSON.stringify(takeDoc("v1").patch?.render?.intro ?? "absent"), { timeout: 10_000 }).toBe(JSON.stringify("absent")); await expect(page.locator('[data-intro-version="v1"]')).toBeChecked(); await expect(page.locator("[data-intro-versions-off]")).toHaveCount(0); + await page.goto(urls.playHref(PROJECT, { take: "v1" })); + await expect(page.locator("[data-play-intro]")).toHaveCount(1, { timeout: 30_000 }); }); diff --git a/umtool/e2e/phone-walk.spec.ts b/umtool/e2e/phone-walk.spec.ts @@ -294,22 +294,22 @@ test("Play → Edit this clip → move an edge → Back: the new bounds are what await expect(root).toHaveAttribute("data-play-item", "c02"); await page.keyboard.press("k"); - // A take with its own timeline (`short`: c04 then c01): the edit goes to - // THE TAKE, on its own bench, and the bench says so; Back returns to Play - // as it was -- the take still playing (Play and the bench are one app: Play - // was never unmounted). play-take-edit.spec.ts proves the save lands there. + // A saved version or a take (`short`: c04 then c01) is played read-only: E asks to open it in the draft + // first (L3: every edit lands in the draft); Cancel goes back to Play of it, nothing written. + // play-take-edit.spec.ts follows the open through to the draft's bench. + const before = readFileSync(path.join(FIXTURE, ...PLAY.split("/"), "video.manifest.json"), "utf8"); await page.goto(urls.playHref(PLAY, { take: "short" })); await expect(root).toHaveAttribute("data-play-item", "c04"); // E (the key is live once hydrated, which the first render cannot show). await expect(async () => { await page.keyboard.press("e"); - await expect(page).toHaveURL(/\/takes\/short\/clip\/c04\?from=play/, { timeout: 1500 }); + await expect(page).toHaveURL(/\/takes\/short\/open\?clip=c04&from=play/, { timeout: 1500 }); }).toPass({ timeout: 15_000 }); - await expect(page.locator('[data-back-take="short"]')).toContainText("edits go to take short, not the project"); - await page.locator("[data-back-to-play]").click(); - await expect(page).toHaveURL(/\/play\?take=short&clip=c04/, { timeout: 20_000 }); + await expect(page.locator('[data-open-draft="short"]')).toContainText("Open short in draft?"); + await page.locator("[data-open-draft-cancel]").click(); + await expect(page).toHaveURL(/\/play\?take=short/, { timeout: 20_000 }); await expect(root).toHaveAttribute("data-play-cut", "short"); - await expect(root).toHaveAttribute("data-play-item", "c04"); + expect(readFileSync(path.join(FIXTURE, ...PLAY.split("/"), "video.manifest.json"), "utf8")).toBe(before); }); test("Play → Edit this clip → move an edge → Back: the new bounds are what plays (phone)", async ({ page }) => { diff --git a/umtool/e2e/play-cut.spec.ts b/umtool/e2e/play-cut.spec.ts @@ -239,6 +239,19 @@ test("a take plays its own timeline (its patch over the project's manifest); a r expect(await tNow(page)).toBeCloseTo(2.133, 2); }); +test("a saved version plays its frozen manifest, read-only, with Open in draft -- never the manifest as it is now", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(PROJECT, { take: "v1" })); + await expect(root(page)).toHaveAttribute("data-play-cut", "v1"); + await expect(page.locator('[data-play-take="v1"]')).toHaveAttribute("data-play-take-frozen", ""); + await expect(page.locator('[data-play-take="v1"]')).toContainText("frozen as it was saved"); + expect(await rows(page).evaluateAll((els) => els.map((e) => e.getAttribute("data-play-row")))).toEqual(["c01", "c02", "c04"]); + await expect(page.locator('[data-play-open-draft="v1"]')).toHaveAttribute("href", `/projects/${PROJECT}/takes/v1/open`); + // The draft (the manifest) still has all five. + await page.goto(urls.playHref(PROJECT)); + await expect(rows(page)).toHaveCount(5); +}); + test("opened at ?clip=&at=, the clock never jumps back there when the render's edges and the deck arrive while it plays", async ({ page }) => { await page.setViewportSize({ width: 1366, height: 1000 }); // The late data, held until the clock has run on from the place: the render's edges diff --git a/umtool/e2e/play-take-edit.spec.ts b/umtool/e2e/play-take-edit.spec.ts @@ -5,16 +5,15 @@ import { fileURLToPath } from "node:url"; import * as urls from "./urls"; // --------------------------------------------------------------------------- -// PLAY'S EDIT ON A TAKE WITH ITS OWN TIMELINE edits THAT TAKE (2 Nov: an edge -// fixed from Play on `kirsche-7`'s kr1 landed in the project's -// video.manifest.json, the cut's clip of the same id, not in the take). +// EDIT ON A VERSION OPENS IT IN THE DRAFT (umtool redesign L3; was: Play's edit on a take with its own +// timeline edits that take -- 2 Nov, an edge fixed from Play on `kirsche-7`'s kr1 landed where the +// operator did not expect). Every edit lands in the draft now: Edit on a version goes to the Open in +// draft page, which saves the draft first and copies the version in; the edge is then saved on the +// DRAFT's bench -- the project's manifest changes and the take's take.json does not. // -// play-take-edit-fixture (fixtures/take-walk-fixture.mjs, written for this -// file alone): the master is one clip, w01 1.00-8.00; the DRAFT take `tight` -// replaces the timeline (its own timeline) with t01a, t01b 3.50-6.00 and -// t01c, all inside the cached vid1 0-9 s window. Edit from Play on the take -// opens the TAKE's bench in place; an edge saved there lands in -// takes/tight/take.json and the project's manifest stays byte for byte. +// play-take-edit-fixture (fixtures/take-walk-fixture.mjs, written for this file alone): the master is +// one clip, w01 1.00-8.00; the legacy DRAFT take `tight` replaces the timeline (its own timeline) with +// t01a, t01b 3.50-6.00 and t01c, all inside the cached vid1 0-9 s window. // --------------------------------------------------------------------------- test.describe.configure({ mode: "serial" }); @@ -23,77 +22,88 @@ const P = "reports/play-take-edit-fixture"; const TAKE = "tight"; const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "play-take-edit-fixture"); const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8"); -const takeClip = (id: string) => - (JSON.parse(readFileSync(path.join(DIR, "takes", TAKE, "take.json"), "utf8")).patch.timeline as { id: string; start: number; end: number }[]).find( - (e) => e.id === id, - )!; +const takeText = () => readFileSync(path.join(DIR, "takes", TAKE, "take.json"), "utf8"); +const draftClip = (id: string) => (JSON.parse(manifestText()).timeline as { id: string; start: number; end: number }[]).find((e) => e.id === id)!; test.beforeEach(() => { test.setTimeout(120_000); }); -test("Play on a take with its own timeline → Edit opens the TAKE's bench; an edge saved there is the take's, the manifest untouched; Back plays the take", async ({ page }) => { - const before = manifestText(); - expect(takeClip("t01b").end).toBe(6); +test("Play on a version → Edit asks to open it in the draft (the draft saved first) → the DRAFT's bench; the edge lands in the manifest, take.json untouched; Back plays the draft", async ({ page }) => { + const takeBefore = takeText(); + const masterBefore = manifestText(); + expect(JSON.parse(masterBefore).timeline.map((e: { id: string }) => e.id)).toEqual(["w01"]); await page.setViewportSize({ width: 1366, height: 1000 }); await page.goto(urls.playHref(P, { take: TAKE })); const root = page.locator("[data-play-cut]"); await expect(root).toHaveAttribute("data-play-state", "paused", { timeout: 30_000 }); - await expect(page.locator(`[data-play-take="${TAKE}"]`)).toContainText("Edit this clip opens the take's own bench"); + await expect(page.locator(`[data-play-take="${TAKE}"]`)).toContainText("read-only"); await page.locator('[data-play-row="t01b"]').press("Enter"); await expect(root).toHaveAttribute("data-play-item", "t01b"); const edit = page.locator("[data-play-edit]"); - await expect(edit).toHaveAttribute("data-play-edit", "take"); - await expect(edit).toHaveAttribute("title", /takes\/tight\/take\.json/); + await expect(edit).toHaveAttribute("data-play-edit", "open"); await edit.click(); - // In place, on the take's bench: its address, its note, its edits. - const bench = page.locator('[data-cut-app-bench="t01b"]'); - await expect(bench.locator('[data-bench-shell="clip"]')).toBeVisible({ timeout: 20_000 }); - await expect(page).toHaveURL(new RegExp(`/takes/${TAKE}/clip/t01b\\?from=play.*order=cut`)); - await expect(bench.locator("[data-bench-kind]")).toHaveText("Take walk"); - await expect(bench.locator(`[data-back-take="${TAKE}"]`)).toHaveAttribute("data-back-take-edits", "take"); - await expect(bench.locator(`[data-back-take="${TAKE}"]`)).toContainText(`edits go to take ${TAKE}, not the project`); - await page.screenshot({ path: test.info().outputPath("play-take-edit-bench.png") }); + // The question first: the draft (never saved) is saved as v1, then tight is copied in. + await expect(page).toHaveURL(new RegExp(`/takes/${TAKE}/open\\?clip=t01b&from=play`)); + const ask = page.locator(`[data-open-draft="${TAKE}"]`); + await expect(ask).toHaveAttribute("data-open-draft-saves", "v1"); + await expect(ask.locator("[data-open-draft-said]")).toContainText("is saved as v1 first"); + await page.screenshot({ path: test.info().outputPath("open-in-draft.png") }); + expect(manifestText(), "nothing written by asking").toBe(masterBefore); + await ask.locator("[data-open-draft-confirm]").click(); + + // The draft's bench on t01b, from Play: the draft is tight's timeline now, v1 the draft before. + await expect(page).toHaveURL(/\/projects\/reports\/play-take-edit-fixture\/clip\/t01b\?from=play/); + const bench = page.locator('[data-bench="t01b"]'); + await expect(bench).toBeVisible({ timeout: 20_000 }); + expect(JSON.parse(manifestText()).timeline.map((e: { id: string }) => e.id)).toEqual(["t01a", "t01b", "t01c"]); + expect(readFileSync(path.join(DIR, "takes", "v1", "base.manifest.json"), "utf8")).toBe(masterBefore); + expect(takeText(), "the take is byte-identical").toBe(takeBefore); + await expect(page.locator("[data-bench-kind]")).toContainText("Clip bench"); - // An edge: the end +0.05 s (`.`), saved. - const save = bench.locator("[data-save-window]"); + // An edge: the end +0.05 s (`.`), saved -- into the draft. + const save = page.locator("[data-save-window]"); await expect(async () => { await page.locator("body").press("."); await expect(save).toBeEnabled({ timeout: 500 }); }).toPass({ timeout: 10_000 }); await save.click(); - await expect.poll(() => takeClip("t01b").end).toBeGreaterThan(6); - expect(takeClip("t01b").start).toBe(3.5); - expect(manifestText(), "the project's manifest is byte-identical").toBe(before); + await expect.poll(() => draftClip("t01b").end).toBeGreaterThan(6); + expect(draftClip("t01b").start).toBe(3.5); + expect(takeText(), "the take is byte-identical").toBe(takeBefore); - // Back to the cut: Play on the same take, the same clip. - await bench.locator("[data-back-to-play]").click(); - await expect(page.locator("[data-cut-app-play]")).toHaveAttribute("data-cut-app-play", "shown"); - await expect(page).toHaveURL(new RegExp(`/play\\?take=${TAKE}`)); - await expect(root).toHaveAttribute("data-play-item", "t01b"); - await expect(page.locator(`[data-play-take="${TAKE}"]`)).toBeVisible(); - expect(manifestText()).toBe(before); + // Back to the cut: Play of the draft, the same clip; the draft is from tight, one edit. + await page.locator("[data-back-to-play]").click(); + await expect(page).toHaveURL(/\/play\?clip=t01b/); + await expect(root).toHaveAttribute("data-play-item", "t01b", { timeout: 20_000 }); + await expect(root).toHaveAttribute("data-play-cut", ""); + await expect(page.locator("[data-play-draft]")).toContainText(`Draft · from ${TAKE} · 1 edit`); }); -test("a reload of the take's bench from Play is the take's bench page: Back to the cut plays the take", async ({ page }) => { +test("a take's old bench address from Play asks first: the draft (1 edit since tight) would be saved as v2; Cancel plays the take", async ({ page }) => { + const before = manifestText(); await page.goto(urls.takeClipHref(P, TAKE, "t01c", { play: { at: 0.5 } })); - await expect(page.locator('[data-walk-take-edits="take"]')).toContainText("never the project’s cut"); - const back = page.locator("[data-back-to-play]"); - await expect(back).toBeVisible(); - await back.click(); - await expect(page).toHaveURL(new RegExp(`/play\\?take=${TAKE}&clip=t01c&at=0\\.50`)); + const ask = page.locator(`[data-open-draft="${TAKE}"]`); + await expect(ask).toHaveAttribute("data-open-draft-saves", "v2"); + await expect(ask.locator("[data-open-draft-said]")).toContainText(`Your draft (1 edit since ${TAKE}) is saved as v2 first`); + await ask.locator("[data-open-draft-cancel]").click(); + await expect(page).toHaveURL(new RegExp(`/play\\?take=${TAKE}`)); + expect(manifestText()).toBe(before); }); -test("a take WITHOUT its own timeline keeps today's Edit: the project's bench", async ({ page }) => { - // play-walk-fixture's draft-1 is a whole-cut take (no timeline in its patch). - await page.goto(urls.playHref("reports/play-walk-fixture", { take: "draft-1" })); +test("Edit on the draft's own parent with no edits goes straight on (307) to the draft's bench", async ({ page, request }) => { + // Saved: the draft is v2 now, no edits since. + const r = await request.post("/api/report/takes/save", { data: { project: P } }); + expect(await r.json()).toMatchObject({ saved: true, id: "v2" }); + const res = await request.get(`/projects/${P}/takes/v2/open?clip=t01c&from=play&at=0.50`, { maxRedirects: 0 }); + expect(res.status()).toBe(307); + expect(res.headers()["location"]).toMatch(/\/projects\/reports\/play-take-edit-fixture\/clip\/t01c\?from=play&at=0\.50/); + await page.goto(urls.playHref(P, { take: "v2" })); const root = page.locator("[data-play-cut]"); await expect(root).toHaveAttribute("data-play-state", "paused", { timeout: 30_000 }); - await page.locator('[data-play-row="c02"]').press("Enter"); - const edit = page.locator("[data-play-edit]"); - await expect(edit).toHaveAttribute("data-play-edit", ""); - await edit.click(); - await expect(page.locator('[data-cut-app-bench="c02"] [data-bench-shell="clip"]')).toBeVisible({ timeout: 20_000 }); - await expect(page).toHaveURL(/\/projects\/reports\/play-walk-fixture\/clip\/c02\?from=play/); + await page.locator('[data-play-row="t01c"]').press("Enter"); + await page.locator("[data-play-edit]").click(); + await expect(page.locator('[data-bench="t01c"]')).toBeVisible({ timeout: 20_000 }); + await expect(page).toHaveURL(/\/projects\/reports\/play-take-edit-fixture\/clip\/t01c\?from=play/); }); diff --git a/umtool/e2e/play-walk.spec.ts b/umtool/e2e/play-walk.spec.ts @@ -11,8 +11,9 @@ import * as urls from "./urls"; // // play-walk-fixture (WRITABLE, make-fixture.mjs): play-cut-fixture's cut on // vid1 with two sections -- §0 c01 c02 | §1 "Two" k01 c03 c04 -- and two -// whole-cut takes made from the manifest as written: draft-1 (the latest) -// and draft-0 (older, picked). Every write here is undone before the test +// whole-cut takes made from the manifest as written: draft-1 (the latest, so +// the draft's parent) and draft-0 (older, picked). Play plays THE DRAFT (the +// manifest) by default (L3). Every write here is undone before the test // ends, except the stamp moved last. // --------------------------------------------------------------------------- @@ -42,32 +43,33 @@ test.beforeEach(() => { test.setTimeout(120_000); }); -test("the working cut is the latest take: named, played by default, switched without the URL write cancelling it", async ({ page }) => { +test("the draft plays by default, named by its parent; a version plays read-only, switched without the URL write cancelling it", async ({ page }) => { await page.setViewportSize({ width: 1366, height: 1000 }); await page.goto(urls.playHref(P)); await ready(page); - await expect(page.locator("[data-play-working]")).toHaveAttribute("data-play-working", "draft-1"); - await expect(page.locator("[data-play-working]")).toContainText("Latest"); - await expect(page.locator("[data-play-working]")).toContainText("no edits since"); - await expect(root(page)).toHaveAttribute("data-play-cut", "draft-1"); - await expect(page.locator("[data-play-take-defaulted]")).toHaveCount(1); + // No draft pointer yet: the draft's parent is the newest working take, draft-1, and nothing changed since. + await expect(page.locator("[data-play-draft]")).toHaveAttribute("data-play-draft", "draft-1"); + await expect(page.locator("[data-play-draft]")).toContainText("Draft · from draft-1 · no edits"); + await expect(root(page)).toHaveAttribute("data-play-cut", ""); + await expect(page.locator('[data-play-take=""]')).toContainText("the working draft"); // The pick (draft-0, from before) is said small, beside: secondary. await expect(page.locator('[data-play-picked="draft-0"]')).toContainText("picked: draft-0"); - await page.screenshot({ path: test.info().outputPath("play-latest-label.png") }); + await page.screenshot({ path: test.info().outputPath("play-draft-label.png") }); - // A take link clicked WHILE PLAYING: Play's once-a-second URL write used to cancel it. + // A version link clicked WHILE PLAYING: Play's once-a-second URL write used to cancel it. await page.locator("[data-play-toggle]").click(); await expect.poll(() => tNow(page), { timeout: 20_000 }).toBeGreaterThan(0.3); await page.locator('[data-play-take-link="draft-0"]').click(); await expect(root(page)).toHaveAttribute("data-play-cut", "draft-0", { timeout: 20_000 }); await expect(page).toHaveURL(/take=draft-0/); - await expect(page.locator("[data-play-working]")).toContainText("Latest is"); - // The manifest alone, and back to the latest. - await page.locator('[data-play-take-link=""]').click(); + await expect(page.locator('[data-play-take="draft-0"]')).toContainText("read-only"); + await expect(page.locator('[data-play-open-draft="draft-0"]')).toHaveAttribute("href", "/projects/reports/play-walk-fixture/takes/draft-0/open"); + // Read-only: Edit goes by Open in draft. + await expect(page.locator("[data-play-edit]")).toHaveAttribute("data-play-edit", "open"); + // Back to the draft. + await page.locator("[data-play-draft-link]").click(); await expect(root(page)).toHaveAttribute("data-play-cut", "", { timeout: 20_000 }); - await expect(page).toHaveURL(/cut=1/); - await page.locator("[data-play-latest-link]").click(); - await expect(root(page)).toHaveAttribute("data-play-cut", "draft-1", { timeout: 20_000 }); + await expect(page).not.toHaveURL(/take=/); }); test("the reel strip zooms like the bench waveform: at the pointer, keys, to the clip and the section, an overview", async ({ page }) => { @@ -141,8 +143,8 @@ test("drag to reorder: across a seam into §0, the drop's section said, one writ expect(afters()).toBe("c02"); await expect(page.locator('[data-play-row="c04"]')).toHaveAttribute("data-play-row-section", "0", { timeout: 20_000 }); await expect(root(page)).toHaveAttribute("data-play-item", "c02"); - // The working cut's name counts the edit. - await expect(page.locator("[data-play-working]")).toContainText("+1 edit since", { timeout: 20_000 }); + // The draft's name counts the edit. + await expect(page.locator("[data-play-draft]")).toContainText("Draft · from draft-1 · 1 edit", { timeout: 20_000 }); await page.screenshot({ path: test.info().outputPath("strip-undo-toast.png") }); // §1 is down to c03: dragging it into §0 would leave §1 with no clip -- refused before any write. @@ -200,7 +202,7 @@ test("Play → Edit → the bench in place → Back: the same clip, second and t await expect(page.locator(`[data-cut-app-bench="${item}"] [data-bench-shell="clip"]`)).toBeVisible({ timeout: 20_000 }); await expect(page.locator("[data-cut-app-play]")).toHaveAttribute("data-cut-app-play", "hidden"); await expect(page).toHaveURL(new RegExp(`/clip/${item}\\?from=play.*order=cut`)); - // The bench names the working cut it edits: the latest take, no edits since. + // The bench names the draft it edits: from the latest take, no edits since. await expect(page.locator(`[data-cut-app-bench="${item}"] [data-working-cut]`)).toHaveAttribute("data-working-cut", "draft-1"); await page.screenshot({ path: test.info().outputPath("app-bench-in-place.png") }); // n: the cut's next clip (the reel strip's order), in place. @@ -213,7 +215,7 @@ test("Play → Edit → the bench in place → Back: the same clip, second and t await expect(page.locator("[data-cut-app-play]")).toHaveAttribute("data-cut-app-play", "shown"); await expect(root(page)).toHaveAttribute("data-play-item", item); expect(Math.abs((await tNow(page)) - t0)).toBeLessThan(0.15); - await expect(root(page)).toHaveAttribute("data-play-cut", "draft-1"); + await expect(root(page)).toHaveAttribute("data-play-cut", ""); await expect(page).toHaveURL(/\/play\?/); expect(await page.evaluate(() => history.length)).toBe(hist + 2); // ...and Play did not start over: the deck is not being composed again (nothing changed). diff --git a/umtool/e2e/post-items.spec.ts b/umtool/e2e/post-items.spec.ts @@ -227,8 +227,8 @@ test("the post bench trims the video attachment and saves it; the cut's seconds await expect(page.locator('[data-entry="p-vid"] [data-post-seconds]')).toHaveText("4.7s"); }); -test("the take-only bench draws the attachment's lane: its out edge dragged into the take's patch, the field and the plan following, the project untouched; a GIF's lane has no sound and still drags", async ({ page }) => { - // A draft take of the cut (no patch yet: the project's timeline until its first edit), written here alone. +test("the post bench draws the attachment's lane: its out edge dragged into the DRAFT (an old take-only address is the draft's bench now), the field and the plan following; a GIF's lane has no sound and still drags", async ({ page }) => { + // The take-only scope is retired (L3: every edit lands in the draft): an old `?inTake=` address is the draft's bench. const takes = path.join(DIR, "takes"); rmSync(takes, { recursive: true, force: true }); const projectText = readFileSync(MANIFEST, "utf8"); @@ -237,15 +237,16 @@ test("the take-only bench draws the attachment's lane: its out edge dragged into id: "t1", group: "takes", order: 1, label: "Take one", kind: "different", summary: "", changes: [], preview: "preview.mp4", seconds: null, builtAt: null, style: null, patch: null, window: null, draft: true, draftedAt: "2026-11-05T00:00:00.000Z", baseHash: createHash("sha256").update(projectText).digest("hex"), }, null, 2) + "\n"); + const takeText = readFileSync(path.join(takes, "t1", "take.json"), "utf8"); try { await page.setViewportSize({ width: 1366, height: 1000 }); await page.goto(`${urls.postBenchHref(PROJECT, "p-vid")}?inTake=t1`); - await expect(page.locator('[data-post-bench-scope="t1"]')).toBeVisible(); - await expect(page.locator("[data-post-narration-in-take=t1] [data-post-bench-in-take-note]")).toBeVisible(); + await expect(page.locator('[data-post-bench-scope="cut"]')).toContainText("the draft"); const lane = page.locator('[data-post-lane="attachment"][data-post-lane-media="0"]'); await expect(lane).toBeVisible(); await expect(lane).toHaveAttribute("data-post-lane-kind", "video"); - await expect(lane).toHaveAttribute("data-post-lane-sel", "0.00-4.00"); + const start0 = (JSON.parse(projectText).timeline as Entry[]).find((e) => e.id === "p-vid")?.media?.[0]; + await expect(lane).toHaveAttribute("data-post-lane-sel", `${Number(start0?.start ?? 0).toFixed(2)}-${Number(start0?.end ?? 4).toFixed(2)}`); // Its sound's envelope arrives (the peaks route over the project file). await expect(lane).toHaveAttribute("data-post-lane-peaks", "on"); // Drag the out handle from the file's end to half way: 2 s. @@ -274,13 +275,12 @@ test("the take-only bench draws the attachment's lane: its out edge dragged into } await page.locator("[data-post-bench-save]").click(); await expect(page.locator("[data-post-bench-status]")).toHaveText("saved"); - const take = JSON.parse(readFileSync(path.join(takes, "t1", "take.json"), "utf8")) as { patch?: { timeline?: Entry[] } }; - const vid = (take.patch?.timeline ?? []).find((e) => e.id === "p-vid"); + const vid = (JSON.parse(readFileSync(MANIFEST, "utf8")).timeline as Entry[]).find((e) => e.id === "p-vid"); expect(vid?.media?.[0]?.end).toBeCloseTo(dragged + 0.1, 2); - expect(vid?.media?.[0]?.start).toBeUndefined(); - // The project's manifest byte for byte the same. - expect(readFileSync(MANIFEST, "utf8")).toBe(projectText); + // The take byte for byte the same; the draft put back for the specs after. + expect(readFileSync(path.join(takes, "t1", "take.json"), "utf8")).toBe(takeText); } finally { + writeFileSync(MANIFEST, projectText); rmSync(takes, { recursive: true, force: true }); } // A GIF (the combo fixture's p-c1, 2 s, no sound): the lane draws a flat line and its in handle still drags. diff --git a/umtool/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts @@ -397,9 +397,10 @@ test("RE-VOICE A PHRASE (operator, 5 Nov: the countdown gabbled, pauses cut into expect(n.takes[1].seconds).toBeCloseTo(n.takes[0].seconds + delta, 1); }); -test("RE-VOICE ON THE TAKE-ONLY BENCH (?inTake=): the phrase re-voiced into the take's patch, the project's manifest untouched", async ({ page }) => { +test("THE TAKE-ONLY BENCH IS RETIRED (L3): an old ?inTake= address is the draft's bench -- the re-voice lands in the draft, the take's take.json untouched", async ({ page }) => { // p-11's take timed (as Get word timings leaves it), then a draft take of the cut with no patch yet. - const doc = JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<Entry & { narration?: { takes?: Array<Take & { words?: unknown }> } }> }; + const original = readFileSync(MANIFEST, "utf8"); + const doc = JSON.parse(original) as { timeline: Array<Entry & { narration?: { takes?: Array<Take & { words?: unknown }> } }> }; const words = [["The", 0.1, 0.3], ["video", 0.35, 0.7], ["speaks", 0.75, 1.1], ["for", 1.15, 1.3], ["itself.", 1.35, 1.8]].map(([w, start, end]) => ({ w, start, end })); doc.timeline.find((e) => e.id === "p-11")!.narration!.takes![0].words = words; writeFileSync(MANIFEST, JSON.stringify(doc, null, 2)); @@ -411,25 +412,15 @@ test("RE-VOICE ON THE TAKE-ONLY BENCH (?inTake=): the phrase re-voiced into the id: "t1", group: "takes", order: 1, label: "Take one", kind: "different", summary: "", changes: [], preview: "preview.mp4", seconds: null, builtAt: null, style: null, patch: null, window: null, draft: true, draftedAt: "2026-11-05T00:00:00.000Z", baseHash: createHash("sha256").update(projectText).digest("hex"), }, null, 2) + "\n"); + const takeText = readFileSync(path.join(takes, "t1", "take.json"), "utf8"); try { await page.setViewportSize({ width: 1500, height: 1100 }); await page.goto(`${urls.postBenchHref(PROJECT, "p-11")}?inTake=t1`); - await expect(page.locator("[data-post-narration-in-take=t1]")).toBeVisible(); - const opts = page.locator('[data-panel-id="post-reread"]'); - await opts.locator("summary").click(); - const row = opts.locator("[data-post-reread-revoice-row]"); - await row.locator("[data-post-reread-revoice]").fill("speaks"); - await row.locator("[data-post-reread-revoice-say]").fill("talks loudly"); - await row.locator("[data-post-reread-revoice-go]").click(); - const status = page.locator("[data-post-narration-status]"); - await expect(status).toContainText("a new take, picked", { timeout: 30_000 }); - const t1 = JSON.parse(readFileSync(path.join(takes, "t1", "take.json"), "utf8")) as { patch?: { timeline?: Entry[] } }; - const n = t1.patch?.timeline?.find((e) => e?.id === "p-11")?.narration as { takes: Array<Take & { steps?: Array<{ op: string }> }>; pick?: number }; - expect(n.takes).toHaveLength(2); - expect(n.pick).toBe(1); - expect(n.takes[1].steps?.[0]?.op).toBe("revoice"); - expect(readFileSync(MANIFEST, "utf8")).toBe(projectText); + await expect(page.locator('[data-post-bench-scope="cut"]')).toContainText("the draft"); + await expect(page.locator("[data-post-narration-in-take]")).toHaveCount(0); } finally { + expect(readFileSync(path.join(takes, "t1", "take.json"), "utf8")).toBe(takeText); + writeFileSync(MANIFEST, original); rmSync(takes, { recursive: true, force: true }); } }); diff --git a/umtool/e2e/take-walk.spec.ts b/umtool/e2e/take-walk.spec.ts @@ -5,14 +5,16 @@ import { fileURLToPath } from "node:url"; import * as urls from "./urls"; // --------------------------------------------------------------------------- -// WALK A TAKE (umtool/docs/clip-bench.md, "Walking a take"): a draft take -- -// recorded, not rendered -- walked on the clip bench, every edit landing in -// the take's patch and none in the project's manifest; then made the cut. +// THE TAKE WALK'S OLD ADDRESSES (umtool redesign L3; was "walk a take": a draft take walked on the clip +// bench, every edit landing in its patch). Every edit lands in the draft now: the take walk +// (`…/takes/<t>/walk`) and a take's bench (`…/takes/<t>/clip/<id>`) are the Open in draft page -- it asks, +// saves the draft first, copies the take in -- then the DRAFT's bench; the take's take.json is never +// written. The walk's data route and `umtool walk --take` still read a take. // -// Fixture (fixtures/take-walk-fixture.mjs), written by this file alone: -// take-walk-fixture's master is one clip, w01; its draft take `tight` replaces -// the timeline with t01a (confirmed), t01b and t01c, all inside the cached -// vid1 0-9 s window. The tests run in order, each leaving what the next reads. +// Fixture (fixtures/take-walk-fixture.mjs), written by this file alone: take-walk-fixture's master is one +// clip, w01; its legacy draft take `tight` replaces the timeline with t01a (confirmed), t01b and t01c, all +// inside the cached vid1 0-9 s window; and a saved version `v1` of the master (its frozen base). The tests +// run in order, each leaving what the next reads. // --------------------------------------------------------------------------- test.describe.configure({ mode: "serial" }); @@ -21,10 +23,10 @@ const PROJECT = "reports/take-walk-fixture"; const TAKE = "tight"; const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "take-walk-fixture"); const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8"); -const takeDoc = () => JSON.parse(readFileSync(path.join(DIR, "takes", TAKE, "take.json"), "utf8")); -const takeClip = (id: string) => (takeDoc().patch.timeline as { id: string; verdict?: string }[]).find((e) => e.id === id); +const takeText = () => readFileSync(path.join(DIR, "takes", TAKE, "take.json"), "utf8"); +const draftClip = (id: string) => (JSON.parse(manifestText()).timeline as { id: string; verdict?: string }[]).find((e) => e.id === id); -/** The bench's keys answer once it has hydrated (`x` focuses the note box). */ +/** The bench's keys answer once it has hydrated. */ const keyboardLive = async (page: import("@playwright/test").Page) => { // Live once the bench's own keys answer: `x` opens Reject ▾'s reasons, Escape closes them unasked. const menu = page.locator("[data-reject-menu]"); @@ -37,28 +39,32 @@ const keyboardLive = async (page: import("@playwright/test").Page) => { }; let masterBefore = ""; +let takeBefore = ""; test.beforeAll(() => { masterBefore = manifestText(); + takeBefore = takeText(); }); -test("the Takes page shows the draft as `draft — walk / render`, with Walk this take", async ({ page }) => { +test("the Takes page: the draft take and the saved version each Play and Open in draft -- no walk", async ({ page }) => { await page.goto(urls.takesHref(PROJECT)); const card = page.locator(`[data-take="${TAKE}"]`); - await expect(card.locator(`[data-take-draft="${TAKE}"]`)).toContainText("draft — walk / render"); - await expect(card.locator("[data-take-is-draft]")).toBeVisible(); - await expect(card.locator(`[data-take-walk-link="${TAKE}"]`)).toHaveAttribute("href", urls.takeWalkHref(PROJECT, TAKE)); + await expect(card.locator(`[data-take-draft="${TAKE}"]`)).toContainText("draft — not rendered"); + await expect(card.locator(`[data-take-open-draft="${TAKE}"]`)).toHaveAttribute("href", urls.openInDraftHref(PROJECT, TAKE)); + await expect(card.locator('[data-play-link="take-actions"]')).toHaveAttribute("href", urls.playHref(PROJECT, { take: TAKE })); + await expect(page.locator("[data-take-walk-link]")).toHaveCount(0); // Nothing rendered to use: the draft is made the cut, not "used". await expect(card.locator("[data-action=pick]")).toHaveCount(0); await expect(card.locator("[data-take-promote]")).toBeVisible(); + await expect(page.locator('[data-take="v1"] [data-take-draft="v1"]')).toContainText("saved version — not rendered"); }); -test("the take's walk: its clips in walk order, the walk starting at the first one needing a verdict", async ({ page, request }) => { +test("the walk's old address asks to open the take in the draft; the walk's data route still reads the take", async ({ page, request }) => { await page.goto(urls.takeWalkHref(PROJECT, TAKE)); - await expect(page.locator("[data-take-walk-clip]")).toHaveCount(3); - await expect(page.locator("[data-take-walk-go]")).toHaveAttribute("href", urls.takeClipHref(PROJECT, TAKE, "t01b")); - await page.locator("[data-take-walk-all]").click(); - await expect(page.locator("[data-take-walk-go]")).toHaveAttribute("href", urls.takeClipHref(PROJECT, TAKE, "t01a", { all: true })); - // The data route: the same reading. + const ask = page.locator(`[data-open-draft="${TAKE}"]`); + await expect(ask).toContainText(`Open ${TAKE} in draft?`); + // The draft (from v1, the master unchanged: no edits) has nothing to save. + await expect(ask.locator("[data-open-draft-said]")).toContainText("no edits since v1 — nothing to save"); + // The data route (and `umtool walk --take`): the same reading as before. const j = (await (await request.get(`/api/report/walk?project=${encodeURIComponent(PROJECT)}&take=${TAKE}`)).json()) as { first: string; take: { draft: boolean }; @@ -71,38 +77,32 @@ test("the take's walk: its clips in walk order, the walk starting at the first o ["t01b", true, true], ["t01c", true, true], ]); + expect(manifestText()).toBe(masterBefore); }); -test("confirming on the bench writes the take's patch, never the manifest, and walks on", async ({ page }) => { +test("a take's old bench address: asked, opened, then the DRAFT's bench on the clip -- a verdict lands in the draft, take.json untouched", async ({ page }) => { await page.goto(urls.takeClipHref(PROJECT, TAKE, "t01b")); - await expect(page.locator(`[data-take-walk="${TAKE}"]`)).toContainText("edits go to the take, not the cut"); - await expect(page.locator("[data-bench-kind]")).toHaveText("Take walk"); - // A take renders whole: no one-clip re-render of the project's segment here. - await expect(page.locator("[data-rerender]")).toHaveCount(0); + const ask = page.locator(`[data-open-draft="${TAKE}"]`); + await expect(ask).toContainText("the bench opens on t01b"); + await ask.locator("[data-open-draft-confirm]").click(); + await expect(page).toHaveURL(/\/projects\/reports\/take-walk-fixture\/clip\/t01b$/); + await expect(page.locator("[data-bench=t01b]")).toBeVisible({ timeout: 20_000 }); + expect((JSON.parse(manifestText()).timeline as { id: string }[]).map((e) => e.id)).toEqual(["t01a", "t01b", "t01c"]); + expect(takeText(), "the take is never written").toBe(takeBefore); await keyboardLive(page); await page.locator("body").press("y"); await expect(page.locator("[data-bench=t01c]")).toBeVisible(); - await expect.poll(() => takeClip("t01b")?.verdict).toBe("confirmed"); - expect(manifestText()).toBe(masterBefore); - expect(takeDoc().draft).toBe(true); + await expect.poll(() => draftClip("t01b")?.verdict).toBe("confirmed"); + expect(takeText()).toBe(takeBefore); }); -test("remove from the take, then undo the take's edit", async ({ page }) => { - await page.goto(urls.takeClipHref(PROJECT, TAKE, "t01c")); - await expect(page.locator(`[data-take-walk="${TAKE}"]`)).toBeVisible(); - await page.locator("[data-take-remove=t01c]").click(); - await expect.poll(() => (takeDoc().patch.timeline as { id: string }[]).map((e) => e.id)).toEqual(["t01a", "t01b"]); - await page.goto(urls.takeClipHref(PROJECT, TAKE, "t01b")); - await page.locator("[data-take-undo]").click(); - await expect.poll(() => (takeDoc().patch.timeline as { id: string }[]).map((e) => e.id)).toEqual(["t01a", "t01b", "t01c"]); - expect(manifestText()).toBe(masterBefore); -}); - -test("Make this the cut: the take's walked timeline becomes the project's", async ({ page }) => { - await page.goto(urls.takeWalkHref(PROJECT, TAKE)); - await page.locator(`[data-take-actions="${TAKE}"] [data-take-promote]`).click(); - await expect(page.locator("[data-take-promoted]")).toBeVisible(); - const m = JSON.parse(manifestText()) as { timeline: { id: string; verdict?: string }[] }; - expect(m.timeline.map((e) => e.id)).toEqual(["t01a", "t01b", "t01c"]); - expect(m.timeline[1].verdict).toBe("confirmed"); +test("the draft's own parent with no edits: the old bench address goes straight on (307)", async ({ request }) => { + const r = await request.post("/api/report/takes/save", { data: { project: PROJECT } }); + expect(await r.json()).toMatchObject({ saved: true, id: "v2" }); + const res = await request.get(urls.takeClipHref(PROJECT, "v2", "t01c"), { maxRedirects: 0 }); + expect(res.status()).toBe(307); + expect(res.headers()["location"]).toMatch(/\/projects\/reports\/take-walk-fixture\/clip\/t01c$/); + // A take that is not the parent still asks. + const asks = await request.get(urls.takeWalkHref(PROJECT, TAKE), { maxRedirects: 0 }); + expect(asks.status()).toBe(200); }); diff --git a/umtool/e2e/undo.spec.ts b/umtool/e2e/undo.spec.ts @@ -1,4 +1,7 @@ import { test, expect } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; import { caps, NO_SONG_DATA } from "./capabilities"; // Undo, and the window a card is left on. @@ -141,3 +144,28 @@ test("a card remembers the window it was left on, and R returns it to the server await page.keyboard.press("r"); await expect.poll(async () => (await selText.textContent())!).toBe(original); }); + +// ONE UNDO STACK (umtool redesign L3, S5): in the app every edit is its own undo point -- two trims a moment +// apart (well inside the terminal's two-minute throttle) are two Undos on the Cut tab's Undo last edit +// (POST /api/report/timeline {op: "undo"}; the trims are PUT /api/report/window, the bench's save), each putting back exactly the one before. undo-trim-fixture +// (make-fixture.mjs) is this test's own. +test("two trims a moment apart, then two undos: each undo takes back one trim", async ({ request }) => { + const P = "reports/undo-trim-fixture"; + const FILE = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "undo-trim-fixture", "video.manifest.json"); + const c01 = () => (JSON.parse(readFileSync(FILE, "utf8")).timeline as { id: string; start: number; end: number }[]).find((e) => e.id === "c01")!; + const t0 = readFileSync(FILE, "utf8"); + expect(c01().end).toBe(3); + let r = await request.put("/api/report/window", { data: { project: P, clip: "c01", end: 2.8 } }); + expect(r.ok(), await r.text()).toBe(true); + const t1 = readFileSync(FILE, "utf8"); + r = await request.put("/api/report/window", { data: { project: P, clip: "c01", end: 2.6 } }); + expect(r.ok(), await r.text()).toBe(true); + expect(c01().end).toBe(2.6); + r = await request.post("/api/report/timeline", { data: { project: P, op: "undo" } }); + expect(r.ok(), await r.text()).toBe(true); + expect((await r.json()).op).toBe("trim"); + expect(readFileSync(FILE, "utf8")).toBe(t1); + r = await request.post("/api/report/timeline", { data: { project: P, op: "undo" } }); + expect(r.ok(), await r.text()).toBe(true); + expect(readFileSync(FILE, "utf8")).toBe(t0); +}); diff --git a/umtool/instrumentation.ts b/umtool/instrumentation.ts @@ -1,4 +1,5 @@ // Next.js instrumentation hook: register() runs once when the server starts. +// It says every app edit is its own undo point (manifest.mjs setUndoEveryMs), and // umtool arms ONE thing here, the durable queue's runner (lib/queue/runner.ts), // so the steps an agent queued (`umtool queue add`) run in the app -- the live // unit -- and survive the session that queued them. A step that was running @@ -12,6 +13,15 @@ import { isIdleBoot } from "yt-dlp-transcript-common/lib/idleBoot"; export async function register() { if (process.env.NEXT_RUNTIME !== "nodejs") return; + // ONE UNDO STACK (umtool redesign L3): every edit made in the app is its own undo point (lib/report/manifest.mjs + // autoSnapshot; a terminal keeps the two-minute throttle). A process global, not the environment: the steps + // the app spawns (lib/jobs.ts) must keep the terminal's throttle. Set before anything else, idle boot included. + try { + const { setUndoEveryMs } = await import("./lib/report/manifest.mjs"); + setUndoEveryMs(0); + } catch (e) { + console.error(`umtool: per-edit undo points not set: ${e instanceof Error ? e.message : String(e)}`); + } if (isIdleBoot()) return; try { const { queueRunnerEnabled, startQueueRunner } = await import("./lib/queue/runner"); diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -376,6 +376,30 @@ export function takeClipHref( ); } +/** + * OPEN A VERSION IN THE DRAFT (umtool redesign L3; components/projects/OpenInDraftPage.tsx): the page that + * asks first -- "Open v1 in draft? Your draft (N edits) is saved as vN+1 first." -- or, when the version is + * the draft's parent with no edits, goes straight on (307) to the draft's bench on `clip` (a post item's when + * `post`), else to Play of the draft. `play`: opened from Play (the bench's Back returns to Play, `at` seconds + * into the clip). + */ +export function openInDraftHref( + project: string, + take: string, + q: NoteOpt & { clip?: string | null; post?: boolean; play?: { at?: number | null } | null } = {}, +): string { + const play = q.play; + return withQuery( + `/projects/${encodePath(project)}/takes/${encodeURIComponent(take)}/open`, + { + clip: q.clip ?? null, + post: q.clip && q.post ? "1" : null, + ...(play ? { from: "play", at: play.at != null && play.at > 0 ? play.at.toFixed(2) : null } : {}), + }, + q.note, + ); +} + /** What the clip deck (release 34) walks: every instance, the unruled, the doubtful first, the ruled. */ export const CLIP_DECK_SHOWS = ["all", "unruled", "doubtful", "ruled"] as const; export type ClipDeckShow = (typeof CLIP_DECK_SHOWS)[number]; diff --git a/umtool/lib/report/benchData.ts b/umtool/lib/report/benchData.ts @@ -16,7 +16,6 @@ import { gapWalls } from "umtool-report-to-video/gaps"; import { deckOn } from "umtool-report-to-video/deck"; import { pieceHrefOfProject } from "@/lib/pieces/article"; import { readWorkingCut } from "@/lib/report/workingCut.mjs"; -import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs"; import type { ProjectRef } from "@/lib/project-types"; // THE CLIP BENCH'S DATA, in one place: what `/projects/<p>/clip/<id>` renders @@ -275,7 +274,7 @@ export async function clipBenchData( // The working cut's name: the bench edits the project's manifest, the latest take is what it was made into. data.working = take ? null - : await readWorkingCut(project.dir, { resolveNow: async (id) => (await resolveTakeManifest(project.dir, id)).manifest }).catch(() => null); + : await readWorkingCut(project.dir).catch(() => null); const top: BenchTopSpec = { trail: take ? [{ href: projectsHref(), label: "Projects" }, { href: takesHref(project.id), label: `${project.name} · takes` }] : [{ href: projectsHref(), label: "Projects" }], back: { href: back, label: take ? `take ${take}` : project.name }, diff --git a/umtool/lib/report/introCli.mjs b/umtool/lib/report/introCli.mjs @@ -20,7 +20,8 @@ export const INTRO_USAGE = [ ` style: ${INTRO_STYLES.join(" ")} · seconds 3.5–8 · mark none|draw|chime · sound=<file>|false`, " title=<one line, ≤ 80> · lines='29 October 2026|Part one' (≤ 3, or a JSON list) · site=auto|<id>|none", "--take <t> --off: that version opens on no intro (its patch's render.intro: null; the cut's untouched);", - "--on: it opens on the cut's intro again. Play, Present and the Cut tab show the intro as the build draws it.", + "--on: the key comes off its patch -- it opens on the intro it was saved with (a legacy take: the draft's). Play,", + "Present and the Cut tab show the intro as the build draws it.", ].join("\n"); class CliError extends Error {} @@ -84,7 +85,7 @@ export async function introCommand(args, { root = REPORTS_ROOT, out = (s) => con if (pairs.length) throw new CliError("--take sets a version's on/off only (--off or --on); its own knobs are a take's patch (umtool take … --set render.intro.<key>=…)"); if (flags.has("--off") === flags.has("--on")) throw new CliError("--take needs --off or --on"); const res = await setVersionIntro(project.dir, take, flags.has("--on")); - done.push(`${take}: ${flags.has("--on") ? "the cut's intro" : "no intro"}${res.unchanged ? " (already)" : res.revision ? ` · undo point ${res.revision.rel}` : ""}`); + done.push(`${take}: ${flags.has("--on") ? "its intro again" : "no intro"}${res.unchanged ? " (already)" : res.revision ? ` · undo point ${res.revision.rel}` : ""}`); } else if (flags.has("--off")) { if (pairs.length) throw new CliError("--off takes the intro off; key=value writes one -- one or the other"); const { editNotes } = await withEditNotes(project, () => writeIntro(project.dir, null)); diff --git a/umtool/lib/report/introEdit.mjs b/umtool/lib/report/introEdit.mjs @@ -164,11 +164,12 @@ export async function writeIntro(dir, value, { token = null } = {}) { } /** - * A VERSION (a made take) with or without the cut's intro: off writes `render.intro: null` into its - * patch (a style variant: the cut opens on no intro in that version only), on puts the cut's intro - * back. Through the take's own writer (editTakeManifest: its token, an undo point, the project's - * manifest untouched). On is the cut's intro as it is now, copied into the patch -- the take writer - * composes, it never deletes a key -- so the version opens on what the cut opens on. + * A VERSION (a made take) with or without its intro (umtool redesign L3: a saved version is frozen, so + * its intro is a STYLE of the version -- a field of its patch over the frozen base, never a copy of + * anything). Off writes `render.intro: null` into its patch: that version opens on no intro, the draft + * untouched. On REMOVES the key from its patch (takeEdit.mjs editTakePatch: the take writer that can + * delete), so the version opens on the intro of what it is laid over -- a saved version's own frozen + * base, a legacy take's draft -- with no stale copy left behind. Refused when that has no intro to open on. * * @param {string} dir * @param {string} take @@ -178,13 +179,31 @@ export async function writeIntro(dir, value, { token = null } = {}) { export async function setVersionIntro(dir, take, on, { token = null } = {}) { const manifest = await readManifest(dir); if (!manifest) throw new Error("the project has no video.manifest.json"); - const cut = manifest.render?.intro ?? null; - if (on && (cut === null || cut === undefined)) throw new Error("the cut has no intro to put back: write one first (umtool intro <p> style=…)"); - const { editTakeManifest } = await import("./takeEdit.mjs"); - return editTakeManifest(dir, take, on ? "intro-on" : "intro-off", token, (m) => { + if (on) { + const { frozenBaseText } = await import("./takes.mjs"); + const baseText = await frozenBaseText(dir, take); + const under = baseText !== null ? JSON.parse(baseText) : manifest; + const intro = under?.render?.intro ?? null; + if (intro === null || intro === undefined) { + throw new Error( + baseText !== null + ? `version ${take} was saved with no intro: nothing to put back (the draft's intro is written with umtool intro <p> style=…)` + : "the cut has no intro to put back: write one first (umtool intro <p> style=…)", + ); + } + } + const { editTakeManifest, editTakePatch } = await import("./takeEdit.mjs"); + if (on) { + const r = await editTakePatch(dir, take, "intro-on", token, (p) => { + if (!isObj(p.render) || !("intro" in p.render)) return; + delete p.render.intro; + if (!Object.keys(p.render).length) delete p.render; + }); + return { ...r, intro: "cut" }; + } + return editTakeManifest(dir, take, "intro-off", token, (m) => { m.render = isObj(m.render) ? m.render : {}; - if (on) m.render.intro = clone(cut); - else delete m.render.intro; - return { intro: on ? "cut" : "off" }; + delete m.render.intro; + return { intro: "off" }; }); } diff --git a/umtool/lib/report/introEdit.test.mjs b/umtool/lib/report/introEdit.test.mjs @@ -90,6 +90,12 @@ test("a version without the intro: its patch carries render.intro: null (the pro assert.equal((await setVersionIntro(dir, "v1", false)).unchanged, true, "off twice writes nothing"); await setVersionIntro(dir, "v1", true); assert.equal((await resolveTakeManifest(dir, "v1")).manifest.render.intro, "boot-dark"); + // On deletes the key (no stale copy of the cut's intro): the version follows what it is laid over. + const onDoc = JSON.parse(await readFile(path.join(dir, "takes", "v1", "take.json"), "utf8")); + assert.ok(!onDoc.patch || !("intro" in (onDoc.patch.render ?? {})), "no render.intro left in the patch"); + assert.equal((await setVersionIntro(dir, "v1", true)).unchanged, true, "on twice writes nothing"); + await writeIntro(dir, { style: "title-card" }); + assert.equal((await resolveTakeManifest(dir, "v1")).manifest.render.intro, "title-card", "a legacy take follows the draft's intro"); await writeIntro(dir, null); await assert.rejects(setVersionIntro(dir, "v1", true), /the cut has no intro to put back/); } finally { diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -21,7 +21,7 @@ // a silent overwrite -- somebody may have run `resolve-windows --write` in // between, and losing that is losing human judgement. import { statSync } from "node:fs"; -import { copyFile, readFile, rename, stat, writeFile } from "node:fs/promises"; +import { copyFile, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { POPULATIONS, @@ -118,7 +118,7 @@ let queue = Promise.resolve(); * @param {() => Promise<T>} fn * @returns {Promise<T>} */ -function withManifestLock(fn) { +export function withManifestLock(fn) { const run = queue.then(fn, fn); queue = run.then( () => undefined, @@ -287,8 +287,11 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri const manifest = JSON.parse(raw); const { entry, before, citeFollowed } = patchClipEntry(manifest, clipId, patch, { edit, now, raw, dir }); // A gap cut or removed (gaps.mjs) changes what the clip IS in the cut, as a - // split does: an undo point first (`umtool timeline <p> undo`, the Cut tab's Undo). - const snapshot = GAP_PATCH_KEYS.some((k) => patch[k] !== undefined) ? await autoSnapshot(dir, "gaps") : null; + // split does, and so does a moved edge (one undo stack, L3 S5): an undo point + // first (`umtool timeline <p> undo`, the Cut tab's Undo). + const gaps = GAP_PATCH_KEYS.some((k) => patch[k] !== undefined); + const moved = !!before && (entry.start !== before.start || entry.end !== before.end); + const snapshot = gaps ? await autoSnapshot(dir, "gaps") : moved ? await autoSnapshot(dir, "trim") : null; const nextToken = await writeManifestAtomic(dir, manifest); // A moved extent may need a new bench excerpt: queued, never waited for. if (entry.start !== before.start || entry.end !== before.end) benchPrepAfterWrite(dir, [clipId]); @@ -2078,11 +2081,19 @@ const ARTICLE_SEGMENT_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; // // Every writer above changes the fields of something already in the manifest. // These change WHAT IS IN IT -- the order of the timeline, which entries it -// holds, a teaser's lines, the posts, the fact-check's labels -- so they are -// the edits a person wants to take back. Each one snapshots the manifest into -// revisions/ first (`auto-before-<op>`, at most one per op every two minutes, -// so a burst of drags is one step back), and `undoStructural` restores the -// newest of those. +// holds, a teaser's lines, the posts, the fact-check's labels, a clip's edges +// -- so they are the edits a person wants to take back. Each one snapshots the +// manifest into revisions/ first (`auto-before-<op>`), and `undoStructural` +// restores the newest of those. +// +// ONE UNDO STACK (umtool redesign L3, S5): in the APP every op takes its own +// undo point (`every: 0` -- instrumentation.ts calls setUndoEveryMs(0) for the +// app's own process; a step it spawns keeps the terminal's throttle), +// so two trims a minute apart are two Undos; from a terminal the old throttle +// stands (at most one per op every two minutes: an agent's burst is one step +// back). Two in one second are two files (snapshots.mjs stamps the +// milliseconds), and only the newest AUTO_SNAPSHOT_KEEP `auto-before-*` are +// kept -- the oldest pruned as a new one is taken. // // Same four rules as the rest of the file: the mtime token, tmp + rename under // the lock, 2 dp, and validation by the BUILD's own checks (deck.mjs, @@ -2095,7 +2106,24 @@ const ARTICLE_SEGMENT_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; // --------------------------------------------------------------------------- export const AUTO_SNAPSHOT_PREFIX = "auto-before-"; +/** The terminal's throttle; the app sets it to 0 for its own process (every op its own undo point). */ const AUTO_SNAPSHOT_EVERY_MS = 2 * 60 * 1000; +/** + * The undo-point throttle of THIS process (instrumentation.ts sets 0 in the app). A process global, never an + * environment variable: a step the app spawns (lib/jobs.ts, a queued `umtool window --align` over 150 clips) + * must keep the terminal's throttle, or its burst would take 150 undo points and prune the operator's own. + */ +export const UNDO_EVERY_KEY = Symbol.for("umtool.undoEveryMs"); +/** @param {number | null} ms */ +export function setUndoEveryMs(ms) { + /** @type {any} */ (globalThis)[UNDO_EVERY_KEY] = ms; +} +/** The undo points kept: the newest this many `auto-before-*` snapshots (older ones are pruned). */ +export const AUTO_SNAPSHOT_KEEP = 200; +export const undoEveryMs = () => { + const n = /** @type {any} */ (globalThis)[UNDO_EVERY_KEY]; + return typeof n === "number" && Number.isFinite(n) && n >= 0 ? n : AUTO_SNAPSHOT_EVERY_MS; +}; const ENTRY_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; /** @@ -2103,17 +2131,36 @@ const ENTRY_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; * same op was taken in the last two minutes. Never fatal: an undo point that * cannot be taken is reported, and the edit still lands. */ -export async function autoSnapshot(dir, op, { now = Date.now(), every = AUTO_SNAPSHOT_EVERY_MS } = {}) { +export async function autoSnapshot(dir, op, { now = Date.now(), every = undoEveryMs(), keep = AUTO_SNAPSHOT_KEEP } = {}) { const label = `${AUTO_SNAPSHOT_PREFIX}${op}`; try { const recent = every > 0 ? (await listSnapshots(dir)).find((s) => !s.legacy && s.label === label) : null; if (recent && now - recent.mtimeMs < every) return { skipped: true, rel: recent.rel }; - return { skipped: false, ...(await createSnapshot(dir, { label })) }; + const made = await createSnapshot(dir, { label }); + await pruneAutoSnapshots(dir, keep).catch(() => {}); + return { skipped: false, ...made }; } catch (e) { return { skipped: true, error: e instanceof Error ? e.message : String(e) }; } } +/** + * Keep the newest `keep` undo points (`auto-before-*` snapshots in + * revisions/), removing the older ones and their draft-pointer sidecars + * (versions.mjs openVersion). Named snapshots, `undo-saved` and `undone-*` + * are never touched. Returns the names removed. + */ +export async function pruneAutoSnapshots(dir, keep = AUTO_SNAPSHOT_KEEP) { + const auto = (await listSnapshots(dir)).filter((x) => !x.legacy && x.label?.startsWith(AUTO_SNAPSHOT_PREFIX)); + const gone = []; + for (const x of auto.slice(Math.max(0, keep))) { + await rm(path.join(dir, x.rel), { force: true }); + await rm(path.join(dir, x.rel.replace(/\.manifest\.json$/, ".draft.json")), { force: true }); + gone.push(x.name); + } + return gone; +} + /** The index of entry `id`: `at` when it names it, else the only entry with that id. */ export function entryIndex(timeline, id, at = null) { if (at !== null && at !== undefined) { @@ -4605,16 +4652,28 @@ export async function updateVariants(dir, variants, { token = null } = {}) { * @param {{ token?: string | null, op?: string }} [opts] */ export async function replaceManifest(dir, manifest, { token = null, op = "replace" } = {}) { + return withManifestLock(() => replaceManifestLocked(dir, manifest, { token, op })); +} + +/** + * replaceManifest's body, for a caller that ALREADY holds the manifest lock + * (withManifestLock; versions.mjs openVersion saves the draft and opens a + * version in one hold). `every`: the undo point's throttle (autoSnapshot); + * 0 takes one whatever was taken before. + * + * @param {string} dir + * @param {Record<string, unknown>} manifest + * @param {{ token?: string | null, op?: string, every?: number }} [opts] + */ +export async function replaceManifestLocked(dir, manifest, { token = null, op = "replace", every = undefined } = {}) { if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) throw new Error("a manifest is an object"); if (!/^[a-z0-9-]{1,40}$/.test(op)) throw new Error(`not an op name: ${op}`); - return withManifestLock(async () => { - const current = await manifestToken(dir); - if (token !== null && current !== token) throw new StaleToken(token, current); - const next = JSON.parse(JSON.stringify(manifest)); - const snapshot = await autoSnapshot(dir, op); - const nextToken = await writeManifestAtomic(dir, next); - return { snapshot, token: nextToken }; - }); + const current = await manifestToken(dir); + if (token !== null && current !== token) throw new StaleToken(token, current); + const next = JSON.parse(JSON.stringify(manifest)); + const snapshot = await autoSnapshot(dir, op, every === undefined ? {} : { every }); + const nextToken = await writeManifestAtomic(dir, next); + return { snapshot, token: nextToken }; } /** @@ -4680,6 +4739,24 @@ export async function undoStructural(dir, { token = null } = {}) { await rename(tmp, file); const undone = target.rel.replace(`-${target.label}.manifest.json`, `-undone-${op}.manifest.json`); await rename(path.join(dir, target.rel), path.join(dir, undone)).catch(() => {}); - return { restored: target.rel, op, saved, token: await manifestToken(dir) }; + // An undo point that carries the DRAFT POINTER as it was (versions.mjs openVersion: `<snapshot>.draft.json`): + // the draft's parent goes back with the manifest, so "Undo open v1" leaves the draft named as it was. + const sidecar = path.join(dir, target.rel.replace(/\.manifest\.json$/, ".draft.json")); + const side = await readFile(sidecar, "utf8").then((t) => JSON.parse(t), () => undefined); + let draft = undefined; + if (side !== undefined) { + const draftFile = path.join(dir, "takes", "draft.json"); + if (side && typeof side === "object" && typeof side.from === "string" && side.from) { + const tmpD = `${draftFile}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmpD, JSON.stringify(side, null, 2) + "\n", "utf8"); + await rename(tmpD, draftFile); + draft = side; + } else { + await rm(draftFile, { force: true }); + draft = null; + } + await rename(sidecar, path.join(dir, undone.replace(/\.manifest\.json$/, ".draft.json"))).catch(() => {}); + } + return { restored: target.rel, op, saved, token: await manifestToken(dir), ...(draft !== undefined ? { draft } : {}) }; }); } diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -21,7 +21,8 @@ import { clockPlan } from "umtool-report-to-video/post-clock"; import { progressPlan } from "umtool-report-to-video/post-progress"; import { pickWindow, projectCache, windowVersion, windowsFor } from "./serve.mjs"; import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs"; -import { readWorkingCut } from "./workingCut.mjs"; +import { draftLine, readWorkingCut } from "./workingCut.mjs"; +import { listTakes, previewFile } from "./takes.mjs"; import { sectionModel } from "./sectionEdit.mjs"; import { manifestToken } from "./manifest.mjs"; import { projectCombos } from "umtool-report-to-video/post-combo-prints"; @@ -112,11 +113,13 @@ export function videoPlayEntry(e, D) { } /** - * WHAT PLAYS BY DEFAULT is the LATEST take (operator, 1 Nov 2026): with no - * `take`, the newest working take (workingCut.mjs) -- the project's manifest - * as it is now with that take's patch, so the look is the next draft's and - * every edit since shows. `bare` plays the manifest alone (`?cut=1`). The - * working cut's name rides along (`working`) for the label. + * WHAT PLAYS BY DEFAULT is THE DRAFT (umtool redesign L3: every edit lands in + * the project's manifest, the working draft; a take is a frozen saved + * version): with no `take`, the project's manifest as it is now. `take` plays + * that version read-only -- its frozen manifest (lib/report/versions.mjs), or + * a legacy take's patch over the manifest as it always did -- with Open in + * draft beside it. `bare` (`?cut=1`) is the draft too, said the old way. The + * draft's parent and its edits ride along (`working`, `draft`) for the header. * * @param {{ id: string, dir: string }} project * @param {{ take?: string | null, bare?: boolean }} [opts] @@ -139,28 +142,33 @@ export async function playView(project, { take = null, bare = false } = {}) { export async function playViewWith(project, { take = null, bare = false, postFor = null } = {}) { const base = await readManifest(project.dir); if (!base) return { error: "this project has no video.manifest.json" }; - const working = await readWorkingCut(project.dir, { - resolveNow: async (id) => (await resolveTakeManifest(project.dir, id, { base })).manifest, - }).catch(() => null); - const defaulted = !take && !bare && !!working?.latest; - if (defaulted) take = working.latest.id; + const working = await readWorkingCut(project.dir).catch(() => null); + void bare; let manifest = base; - /** @type {null | { id: string, label: string, summary: string, made: boolean, from: string, ownTimeline: boolean, defaulted: boolean }} */ + /** @type {null | { id: string, label: string, summary: string, made: boolean, from: string, ownTimeline: boolean, version: boolean, frozen: boolean, parent: boolean, render: string | null }} */ let takeInfo = null; let note = null; if (take) { try { const r = await resolveTakeManifest(project.dir, take, { base }); manifest = r.manifest; + const listed = r.take.made ? (await listTakes(project.dir)).takes.find((t) => t.id === take) ?? null : null; + const file = listed ? await previewFile(project.dir, listed) : null; takeInfo = { id: r.take.id, label: r.take.label, summary: r.take.summary, made: r.take.made, from: r.take.from, - // A patch that brings its own timeline: edits to the project's cut do not show in it (its walk edits it). + // A patch that brings its own timeline (a legacy take walked): Open in draft merges it (versions.mjs). ownTimeline: Array.isArray(/** @type {any} */ (r.take.patch)?.timeline), - defaulted, + // A saved version (frozen base), or a legacy take that follows the draft. + version: listed?.version === true, + frozen: r.frozen === true, + // The draft's parent: opening it with no edits writes nothing. + parent: working?.parent?.id === take, + // Its render, when there is one ("Watch render"). + render: file ? `/api/report/takes/preview?${new URLSearchParams({ project: project.id, take, v: String(file.mtimeMs) })}` : null, }; note = r.note; } catch (e) { @@ -288,6 +296,8 @@ export async function playViewWith(project, { take = null, bare = false, postFor note, takes: await playableTakes(project.dir), working, + // The draft's header: "Draft · from v5 · 3 edits", "Draft · unsaved" (workingCut.mjs draftLine). + draft: { line: draftLine(working), parent: working?.parent?.id ?? null, edits: working?.edits?.count ?? null }, leadIn: basic ? 0 : fin(render.leadIn) ? render.leadIn : 0.4, transition: D, blurRendered: render.blur !== "off", diff --git a/umtool/lib/report/present.mjs b/umtool/lib/report/present.mjs @@ -420,7 +420,7 @@ export function presentFrom({ view, manifest, red, canUncensor = true }) { return { version: PRESENT_VERSION, project: view.project, - take: view.take ? { id: view.take.id, label: view.take.label, defaulted: !!view.take.defaulted } : null, + take: view.take ? { id: view.take.id, label: view.take.label, defaulted: false } : null, title: view.title, capabilities: { canUncensor: !!canUncensor }, settings: PRESENT_DEFAULTS, diff --git a/umtool/lib/report/present.test.mjs b/umtool/lib/report/present.test.mjs @@ -202,7 +202,7 @@ test("umtool present: the address, the slides, --json the payload, --public cens const run = (args) => presentCommand(args, { root: path.join(ROOT, "reports"), out: (s) => lines.push(s), err: (s) => errs.push(s), env: { UMTOOL_URL: "http://umtool.test:9/" }, open: (u) => lines.push(`OPEN ${u}`) }); assert.equal(await run(["cli", "--open"]), 0, errs.join("\n")); assert.equal(lines[0], "http://umtool.test:9/projects/cli/present"); - assert.match(lines[1], /cli · the manifest · 6 slide\(s\), 2 post\(s\) · 2 section\(s\)/); + assert.match(lines[1], /cli · the draft · 6 slide\(s\), 2 post\(s\) · 2 section\(s\)/); assert.ok(lines.some((l) => /post +subj-x\/1 +Oct 30 .*\[2 names, 1 slurs, 1 authors, 1 pictures\]/.test(l)), lines.join("\n")); assert.equal(lines.at(-1), "OPEN http://umtool.test:9/projects/cli/present"); lines.length = 0; diff --git a/umtool/lib/report/presentCli.mjs b/umtool/lib/report/presentCli.mjs @@ -16,7 +16,7 @@ export const PRESENT_USAGE = [ "viewer's address and the slides (each one's id, kind, section and date); --json the whole payload (its url", "beside it): every slide in cut order -- a post item's card as Play draws it, its excerpt, its narration take", "and its censor data by kind; a clip's spans from its cached window and the deck's words; section and day", - "dividers. With no --take the latest take (the working cut), as Play; --cut the manifest alone. --public: the", + "dividers. With no --take the working draft (the manifest), as Play; --take a saved version; --cut the same as none. --public: the", "payload a public page would carry (the posts censored, no reveal data). --open opens the address (xdg-open).", "A slide opens as <url>#<slide id>. UMTOOL_URL (else http://localhost:3050) or --url is the app's origin.", ].join("\n"); @@ -67,7 +67,7 @@ export async function presentCommand(args, { root = REPORTS_ROOT, out = (s) => c const url = `${umtoolBase(flags.get("--url"), env)}${presentPath(project.id, { take, bare })}`; if (flags.has("--json")) out(JSON.stringify({ url, ...payload }, null, 2)); else { - const what = payload.take ? `${payload.take.defaulted ? "latest take" : "take"} ${payload.take.id}` : "the manifest"; + const what = payload.take ? `version ${payload.take.id}` : "the draft"; const posts = payload.slides.filter((s) => s.kind === "post").length; out(`${url}`); out(`${project.id} · ${what} · ${payload.slides.length} slide(s), ${posts} post(s) · ${payload.sections.length} section(s)`); diff --git a/umtool/lib/report/sameOrigin.mjs b/umtool/lib/report/sameOrigin.mjs @@ -0,0 +1,27 @@ +// A WRITE FROM THIS APP'S OWN PAGES, NOT ANOTHER SITE'S (umtool redesign L3 review): a plain form POST (the Open +// in draft page's button) carries no token, so a page on another site could post the same form. The browser says +// where a request comes from -- `Sec-Fetch-Site`, and `Origin` on a POST -- and a write that says another site is +// refused. A terminal or an agent (curl, the CLI, Playwright's request) sends neither and is not refused here +// (its Authorization is lib/report/caller.ts's business). +// +// Plain ESM so `node --test` reads it. + +/** + * The sentence to refuse with, or null for a same-origin (or non-browser) request. + * @param {{ get(name: string): string | null }} headers + */ +export function crossSiteRefusal(headers) { + const site = (headers.get("sec-fetch-site") ?? "").trim().toLowerCase(); + if (site && site !== "same-origin" && site !== "none") return `refused: a ${site} request may not write here`; + const origin = (headers.get("origin") ?? "").trim(); + if (!origin) return null; + if (origin === "null") return "refused: a request from an opaque origin may not write here"; + const host = (headers.get("x-forwarded-host") ?? headers.get("host") ?? "").split(",")[0].trim().toLowerCase(); + let from = ""; + try { + from = new URL(origin).host.toLowerCase(); + } catch { + return "refused: the request's origin does not parse"; + } + return host && from !== host ? `refused: a request from ${from} may not write to ${host}` : null; +} diff --git a/umtool/lib/report/sameOrigin.test.mjs b/umtool/lib/report/sameOrigin.test.mjs @@ -0,0 +1,17 @@ +// Writes from another site are refused (sameOrigin.mjs): the Open in draft form and Save version. +import assert from "node:assert/strict"; +import test from "node:test"; +import { crossSiteRefusal } from "./sameOrigin.mjs"; + +const h = (o) => ({ get: (k) => o[k.toLowerCase()] ?? null }); + +test("crossSiteRefusal: same-origin and non-browser requests pass; another site, a sibling site and an opaque origin do not", () => { + assert.equal(crossSiteRefusal(h({})), null, "curl, the CLI, Playwright's request"); + assert.equal(crossSiteRefusal(h({ "sec-fetch-site": "same-origin", origin: "http://localhost:3050", host: "localhost:3050" })), null); + assert.equal(crossSiteRefusal(h({ "sec-fetch-site": "none" })), null, "typed into the address bar"); + assert.match(String(crossSiteRefusal(h({ "sec-fetch-site": "cross-site", origin: "https://evil.example", host: "localhost:3050" }))), /cross-site/); + assert.match(String(crossSiteRefusal(h({ "sec-fetch-site": "same-site", origin: "http://localhost:3001", host: "localhost:3050" }))), /same-site/); + assert.match(String(crossSiteRefusal(h({ origin: "https://evil.example", host: "localhost:3050" }))), /evil\.example/); + assert.match(String(crossSiteRefusal(h({ origin: "null", host: "localhost:3050" }))), /opaque/); + assert.equal(crossSiteRefusal(h({ origin: "https://umtool.lan", host: "127.0.0.1:3050", "x-forwarded-host": "umtool.lan" })), null, "behind the proxy"); +}); diff --git a/umtool/lib/report/snapshots.mjs b/umtool/lib/report/snapshots.mjs @@ -9,6 +9,7 @@ // unlabelled snapshots. Reported, never renamed, never guessed at. // // Plain ESM: `umtool snapshot` and `umtool diff` run from a terminal. +import { constants as fsConstants } from "node:fs"; import { copyFile, mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { MANIFEST_NAME } from "../projects/report.mjs"; @@ -23,9 +24,15 @@ export function stampOf(d = new Date()) { const LABEL_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; -/** A snapshot's file name, or null when the name is not one. */ +/** + * A snapshot's file name, or null when the name is not one. The stamp is the + * second (`20260825-143012`), and -- when another snapshot already took that + * second -- its milliseconds and a counter after a dot (`20260825-143012.457`, + * `20260825-143012.457.2`): two undo points in one second are two files, never + * one lost (createSnapshot). + */ export function parseSnapshotName(name) { - const m = name.match(/^(\d{8}-\d{6})(?:-(.+))?\.manifest\.json$/); + const m = name.match(/^(\d{8}-\d{6}(?:\.\d{3}(?:\.\d+)?)?)(?:-(.+))?\.manifest\.json$/); if (!m) return null; return { stamp: m[1], label: m[2] ?? null }; } @@ -68,7 +75,8 @@ export async function listSnapshots(dir) { if (!st?.isFile()) continue; out.push({ rel: name, name, stamp: null, label: p.label, legacy: true, mtimeMs: st.mtimeMs, size: st.size }); } - return out.sort((a, b) => b.mtimeMs - a.mtimeMs || a.name.localeCompare(b.name)); + // Newest first; two in the same instant by their stamp (the later name is the later snapshot). + return out.sort((a, b) => b.mtimeMs - a.mtimeMs || (b.stamp ?? "").localeCompare(a.stamp ?? "", "en", { numeric: true }) || a.name.localeCompare(b.name)); } /** Resolve a project-relative snapshot name to a path, refusing anything else. */ @@ -95,10 +103,20 @@ export async function createSnapshot(dir, { label = null, now = new Date() } = { const src = path.join(dir, MANIFEST_NAME); if (!(await stat(src).then((s) => s.isFile(), () => false))) throw new Error(`no ${MANIFEST_NAME} in ${dir}`); await mkdir(path.join(dir, REVISIONS_DIR), { recursive: true }); - const name = `${stampOf(now)}${label ? `-${label}` : ""}.manifest.json`; + // A second another snapshot already took: its milliseconds, then a counter (parseSnapshotName). + const taken = new Set(await readdir(path.join(dir, REVISIONS_DIR)).catch(() => [])); + const tail = `${label ? `-${label}` : ""}.manifest.json`; + const sec = stampOf(now); + const secTaken = [...taken].some((n) => parseSnapshotName(n)?.stamp.slice(0, 15) === sec); + let stamp = sec; + if (secTaken) { + const ms = `${sec}.${String(now.getMilliseconds()).padStart(3, "0")}`; + stamp = ms; + for (let n = 2; taken.has(`${stamp}${tail}`) || [...taken].some((x) => parseSnapshotName(x)?.stamp === stamp); n += 1) stamp = `${ms}.${n}`; + } + const name = `${stamp}${tail}`; const dst = path.join(dir, REVISIONS_DIR, name); - if (await stat(dst).then(() => true, () => false)) throw new Error(`${name} already exists — wait a second`); - await copyFile(src, dst); + await copyFile(src, dst, fsConstants.COPYFILE_EXCL); return { rel: path.posix.join(REVISIONS_DIR, name), name }; } diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs @@ -15,6 +15,7 @@ // umtool takes make <project> --all-styles [--group G] [--at S --dur S | --full] [--force] // umtool takes styles [--json] // umtool takes pick <project> <take> [--anyway] [--json] +// umtool takes save <project> [--label L] · open <project> <take> · freeze <project> [<take>…|--all] [--apply] import { mkdir, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; @@ -127,6 +128,14 @@ export const TAKES_USAGE = [ " 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", + " umtool takes save <project> [--label L] [--force] [--json] the working draft (video.manifest.json) saved", + " as the next version v<N>, frozen (takes/v<N>/base.manifest.json); nothing when it has no edits", + " since its parent unless --force; the pick is never touched", + " umtool takes open <project> <take> [--json] that version copied into the draft: the draft saved first as", + " the next v<N> when it has edits since its parent; one undo point (`umtool timeline <p> undo`)", + " umtool takes freeze <project> [<take>… | --all] [--apply] [--json] legacy takes given a frozen base (the", + " manifest each was rendered from, else the draft now): a dry run unless --apply, each take's", + " difference from how it resolves today said", ].join("\n"); class CliError extends Error {} @@ -451,6 +460,64 @@ async function importItems(project, id, p, { reportsRoot, log, err }) { } } +/** + * `umtool takes save|open|freeze` (versions.mjs): the working draft and its saved versions. + * EXIT 0 done (or nothing to do) · 1 refused · 2 usage. + */ +async function versionsCommand(sub, rest, p, { reportsRoot, log, err }) { + const project = await pickProject(rest[0], reportsRoot); + const v = await import("./versions.mjs"); + const json = p.has("--json"); + try { + if (sub === "save") { + if (rest.length > 1) throw new CliError("umtool takes save <project> [--label L] [--force]: the label is --label"); + const r = await v.saveVersion(project, { label: p.one("--label") ?? null, force: p.has("--force") }); + if (json) log(JSON.stringify({ ok: true, project: project.id, ...r }, null, 2)); + else if (!r.saved) log(`${project.id}: ${r.why} (--force saves it all the same)`); + else log(`${project.id}: the draft saved as ${r.id} — "${r.label}"${r.parent ? ` (from ${r.parent}${r.edits ? `, ${r.edits.count} edit${r.edits.count === 1 ? "" : "s"}` : ""})` : ""}; frozen in takes/${r.id}/base.manifest.json`); + return 0; + } + if (sub === "open") { + const take = rest[1]; + if (!take) throw new CliError("which version? `umtool takes open <project> <take>`"); + const r = await v.openVersion(project, take); + if (json) log(JSON.stringify({ ok: true, project: project.id, ...r }, null, 2)); + else if (r.unchanged) log(`${project.id}: the draft is ${take} already (no edits since) — nothing written`); + else { + if (r.saved) log(`${project.id}: the draft (${r.edits ?? "?"} edit${r.edits === 1 ? "" : "s"}) saved first as ${r.saved}`); + log(`${project.id}: ${take} opened in the draft (${r.how === "frozen" ? "its frozen manifest" : r.how === "rendered" ? "the manifest it was rendered from" : "its patch over the draft"})${r.snapshot?.rel ? `; undo: umtool timeline ${project.id} undo (${r.snapshot.rel})` : ""}`); + } + return 0; + } + // freeze + const ids = rest.slice(1); + if (!ids.length && !p.has("--all")) throw new CliError("which takes? `umtool takes freeze <project> <take>… | --all [--apply]`"); + if (ids.length && p.has("--all")) throw new CliError("<take>… or --all, not both"); + const r = await v.freezeTakes(project, { ids: ids.length ? ids : null, apply: p.has("--apply") }); + if (json) log(JSON.stringify({ ok: !r.missing.length, ...r }, null, 2)); + else { + for (const x of r.rows) { + if (x.action === "already") log(`${x.id}: frozen already`); + else if (x.action === "refused") err(`${x.id}: not frozen — ${x.why}`); + else { + const what = x.source === "rendered" ? "the manifest it was rendered from" : "the draft as it is now"; + const diff = x.differs ? ` — resolves differently from today: ${x.differs} change${x.differs === 1 ? "" : "s"} (${(x.words ?? []).slice(0, 6).join("; ")}${(x.words ?? []).length > 6 ? "; …" : ""})` : " — resolves as it does today"; + log(`${x.id}: ${x.action === "frozen" ? "frozen on" : "would freeze on"} ${what}${diff}`); + } + } + for (const m of r.missing) err(`${m}: no such take`); + if (!r.apply) log("a dry run: nothing written (--apply freezes them)"); + } + return r.missing.length ? 1 : 0; + } catch (e) { + if (e instanceof v.VersionRefused) { + err(e.message); + return 1; + } + throw e; + } +} + /** `umtool take <p> --id X --promote [--anyway]`: make the take the cut (takeEdit.mjs promoteTake). */ async function promote(project, id, p, log, err) { const { PromoteStale, promoteTake } = await import("./takeEdit.mjs"); @@ -511,10 +578,9 @@ export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = con const project = await pickProject(rest[0], reportsRoot); const { takesOverview, takeLine } = await import("./takeHousekeeping.mjs"); const { readWorkingCut, workingCutLine } = await import("./workingCut.mjs"); - const { resolveTakeManifest } = await import("./takeManifest.mjs"); const [o, working] = await Promise.all([ takesOverview(project.dir), - readWorkingCut(project.dir, { resolveNow: async (id) => (await resolveTakeManifest(project.dir, id)).manifest }), + readWorkingCut(project.dir), ]); if (p.has("--json")) log(JSON.stringify({ project: project.id, working, ...o }, null, 2)); else { @@ -631,6 +697,7 @@ export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = con throw e; } } + if (sub === "save" || sub === "open" || sub === "freeze") return await versionsCommand(sub, rest, p, { reportsRoot, log, err }); if (sub === "pick") { const project = await pickProject(rest[0], reportsRoot); const take = rest[1]; diff --git a/umtool/lib/report/takeEdit.mjs b/umtool/lib/report/takeEdit.mjs @@ -81,7 +81,7 @@ let queue = Promise.resolve(); * @param {() => Promise<T>} fn * @returns {Promise<T>} */ -function withTakeEditLock(fn) { +export function withTakeEditLock(fn) { const run = queue.then(fn, fn); queue = run.then( () => undefined, @@ -270,6 +270,39 @@ export async function editTakeManifest(projectDir, id, op, token, mutate, { now } /** + * ONE WRITE TO A TAKE'S PATCH ITSELF (not to what it resolves to): `mutate` + * gets a copy of take.json's patch (`{}` when it has none) and changes it in + * place -- it may DELETE a key, which editTakeManifest's composed patch never + * does (a merge patch only sets and nulls). An empty patch is stored as null. + * The token, an undo point of the take's own (`auto-before-<op>`), the + * project's manifest untouched. Nothing changed: no write, `unchanged: true`. + * + * @param {string} projectDir + * @param {string} id + * @param {string} op + * @param {string | null} token + * @param {(patch: Record<string, any>) => void} mutate + * @param {{ now?: Date }} [opts] + */ +export async function editTakePatch(projectDir, id, op, token, mutate, { now = new Date() } = {}) { + return withTakeEditLock(async () => { + const current = await takeToken(projectDir, id); + if (token !== null && current !== token) throw new StaleToken(token, current); + const { text, doc } = await readTakeDoc(projectDir, id); + const before = isObj(doc.patch) ? doc.patch : null; + const patch = before ? clone(before) : {}; + mutate(patch); + const next = Object.keys(patch).length ? patch : null; + if (JSON.stringify(next) === JSON.stringify(before)) return { take: id, token: current, revision: null, unchanged: true, snapshot: null }; + const revision = await keepRevision(projectDir, id, text, `${AUTO}${op}`, now); + doc.patch = next; + doc.editedAt = now.toISOString(); + const nextToken = await writeTakeAtomic(projectDir, id, doc); + return { take: id, token: nextToken, revision, unchanged: false, snapshot: null }; + }); +} + +/** * The bench's save, on a take: one clip's window, locks, attribution, * verdict and the rest -- updateClip's whitelist and its rules * (patchClipEntry), written into the take's patch. diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -58,7 +58,7 @@ import { REPORTS_ROOT } from "../paths.mjs"; import { replaceManifest } from "./manifest.mjs"; import { incorrectClips, incorrectWhy } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; -import { autoPickTake, isTakeId, isWorkingTake, listTakes, parseWindow, setTakePicked, takesDirOf, TAKE_FILE, TAKE_KINDS } from "./takes.mjs"; +import { autoPickTake, frozenBaseText, isTakeId, isWorkingTake, listTakes, parseWindow, setTakePicked, takesDirOf, BASE_FILE, DRAFT_FILE, TAKE_FILE, TAKE_KINDS } from "./takes.mjs"; export const MANIFEST = "video.manifest.json"; export const PREVIEW = "preview.mp4"; @@ -606,7 +606,10 @@ export async function makeTake(projectDir, rawSpec, opts = {}) { */ export async function composeTake(projectDir, spec, opts = {}) { const log = opts.log ?? (() => {}); - const baseText = await readFile(path.join(projectDir, MANIFEST), "utf8"); + // A SAVED VERSION renders its frozen manifest (takes/<id>/base.manifest.json), never the draft as it is now. + const frozenText = await frozenBaseText(projectDir, spec.id); + const baseText = frozenText ?? (await readFile(path.join(projectDir, MANIFEST), "utf8")); + if (frozenText !== null) log(`${spec.id}: a saved version — rendering its frozen ${BASE_FILE}, not the draft`); const base = JSON.parse(baseText); const styles = opts.styles ?? (spec.style ? (await loadMontageStyles()).styles : {}); let stylePatch = null; @@ -661,7 +664,7 @@ export async function composeTake(projectDir, spec, opts = {}) { if (!ids.length) throw new Error(`${spec.id}: the patch or the clip rulings removed every entry the window covers (${covered.ids.join(", ")})`); renderDoc = windowManifest(ruled.manifest, ids); } - return { baseText, base, styles, manifest, changes, kind, patches, ruled, renderDoc, covered }; + return { baseText, base, styles, manifest, changes, kind, patches, ruled, renderDoc, covered, frozen: frozenText !== null }; } /** makeTake's body; `onTakeDir` is called once the take's directory exists, before anything is linked or rendered. */ @@ -682,7 +685,7 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { const fromTake = opts.from ? await import("./takeFrom.mjs") : null; if (fromTake) await fromTake.fromTakeSourced(projectDir, spec.id, opts.from); - const { baseText, styles, manifest, changes, kind, patches, renderDoc: composed, covered } = await composeTake(projectDir, spec, { styles: opts.styles, log }); + const { baseText, styles, manifest, changes, kind, patches, renderDoc: composed, covered, frozen } = await composeTake(projectDir, spec, { styles: opts.styles, log }); let renderDoc = composed; if (spec.quick) renderDoc = /** @type {Record<string, any>} */ (mergePatch(renderDoc, QUICK_RENDER)); // A clip ruled incorrect (the walk's verdict) still in what would render: @@ -747,6 +750,9 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { const preview = path.join(takeDir, PREVIEW); await unlinkIfSameFile(path.join(takeOut, `${String(manifest.slug ?? "")}.mp4`), preview); + // The draft pointer as the render starts (versions.mjs): a working take repoints it when it is made, but + // only if nothing moved it meanwhile (an Open in draft during a long render keeps what was opened). + const draftPointerAtStart = frozen ? null : await readFile(path.join(takesDirOf(projectDir), DRAFT_FILE), "utf8").catch(() => ""); const transition = Number(manifest.render?.transition ?? 0); const xfade = patches.some((p) => getPath(p, "render.transition") !== undefined) && transition > 0; emit({ ev: "take", id: spec.id, phase: "render", window: spec.window, entries: covered?.ids ?? null, basis: covered?.basis ?? null }); @@ -825,10 +831,26 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { renderSeconds, // Which cut its post items are (post-slurs.mjs): censored, or the uncensored one (`umtool take … --uncensored`). ...(cutSlurState(manifest) ? { slurs: cutSlurState(manifest) } : {}), + // A SAVED VERSION rendered (versions.mjs): still that version -- its frozen base is what was rendered. + ...(previous?.version === true + ? { + version: true, + ...(typeof previous.savedAt === "string" ? { savedAt: previous.savedAt } : {}), + ...(typeof previous.draftedFrom === "string" && previous.draftedFrom ? { draftedFrom: previous.draftedFrom } : {}), + } + : {}), }; const tmp = `${takeFile}.tmp-${process.pid}`; await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, takeFile); + // A whole-cut take of the DRAFT as it is (not a frozen version re-rendered) is the draft's parent now (versions.mjs). + if (!frozen && isWorkingTake(doc)) { + const nowPointer = await readFile(path.join(takesDirOf(projectDir), DRAFT_FILE), "utf8").catch(() => ""); + if (nowPointer === draftPointerAtStart) { + const { writeDraft } = await import("./versions.mjs"); + await writeDraft(projectDir, { from: spec.id, hash: doc.baseHash, at: doc.builtAt }).catch(() => {}); + } else log(`${spec.id}: the draft was opened or saved while this rendered — its parent is left as that made it`); + } // A whole-cut take of the manifest is its group's pick now (takes.mjs autoPickTake): mark only. const group = ((listing ?? (await listTakes(projectDir))).takes ?? []).filter((t) => t.group === doc.group).map((t) => t.id); const pick = await autoPickTake(projectDir, { ...doc, id: spec.id }, group).catch((e) => ({ picked: false, why: e instanceof Error ? e.message : String(e) })); @@ -1077,6 +1099,30 @@ export async function takeIsStale(projectDir, take) { } /** + * A SAVED VERSION's manifest as the draft would hold it: its frozen base + * (takes/<id>/base.manifest.json) byte for byte, or -- when a style or a patch + * was laid over the version since (a "No intro" toggle) -- the base with them + * merged (RFC 7386, no preset resolved: the draft names its preset as the base + * did). null for a take with no frozen base. + * + * @param {string} projectDir + * @param {string} takeId + * @returns {Promise<null | { text: string, manifest: Record<string, any>, exact: boolean }>} + */ +export async function versionManifestOf(projectDir, takeId) { + const baseText = await frozenBaseText(projectDir, takeId); + if (baseText === null) return null; + const base = JSON.parse(baseText); + const doc = await readJson(path.join(takesDirOf(projectDir), takeId, TAKE_FILE)); + let stylePatch = null; + if (typeof doc?.style === "string" && doc.style.trim()) stylePatch = (await loadMontageStyles()).styles[doc.style.trim()]?.patch ?? null; + const patches = [stylePatch, isObj(doc?.patch) ? doc.patch : null].filter(Boolean); + if (!patches.length) return { text: baseText, manifest: base, exact: true }; + const manifest = /** @type {Record<string, any>} */ (patches.reduce((m, p) => mergePatch(m, p), base)); + return { text: serialise(manifest), manifest, exact: false }; +} + +/** * "Use this take": the take's video.manifest.json over the project's, through * the manifest writer (replaceManifest: the auto snapshot `auto-before-pick-take`, * so "Undo last edit" takes it back) inside withEditNotes, then the pick in @@ -1096,9 +1142,11 @@ export async function pickTake(project, takeId, { anyway = false, token = null, const listing = await listTakes(project.dir); const take = listing.takes.find((t) => t.id === takeId); if (!take) throw new Error(`no take ${takeId}`); + // A SAVED VERSION (versions.mjs) is its frozen base, rendered or not: that is what a pick copies. + const frozen = await versionManifestOf(project.dir, takeId); // A draft has no rendered manifest to use: "Make this the cut" (takeEdit.mjs promoteTake) applies its patch. - if (take.draft) throw new Error(`take ${takeId} is a draft — nothing rendered to use; make it the cut (umtool take ${project.id} --id ${takeId} --promote)`); - const text = await readFile(path.join(takesDirOf(project.dir), takeId, MANIFEST), "utf8").catch(() => null); + if (take.draft && !frozen) throw new Error(`take ${takeId} is a draft — nothing rendered to use; make it the cut (umtool take ${project.id} --id ${takeId} --promote)`); + const text = frozen ? frozen.text : await readFile(path.join(takesDirOf(project.dir), takeId, MANIFEST), "utf8").catch(() => null); if (text === null) throw new Error(`take ${takeId} has no ${MANIFEST} to use`); const manifest = JSON.parse(text); if (!isObj(manifest) || !Array.isArray(manifest.timeline)) throw new Error(`take ${takeId}'s ${MANIFEST} is not a manifest`); diff --git a/umtool/lib/report/takeManifest.mjs b/umtool/lib/report/takeManifest.mjs @@ -9,6 +9,11 @@ // takes/recipe.json, a take not made yet: its spec in a recipe // takes/all-styles.recipe.json (parseRecipe's shape) // +// A SAVED VERSION (versions.mjs) is frozen: when takes/<id>/base.manifest.json +// is there, the take resolves over THAT -- the draft as it was when it was +// saved -- and never over the project's manifest as it is now. A legacy take +// (no base) resolves exactly as it always did. +// // A style that is no longer installed falls back to the take's own // takes/<id>/video.manifest.json (the manifest it was rendered from), and // says so; a take with neither is an error. Nothing here writes but @@ -20,7 +25,9 @@ import { resolvePresetLayers } from "umtool-report-to-video/presets"; import { readFile, stat, writeFile, rename } from "node:fs/promises"; import path from "node:path"; import { ALL_STYLES_RECIPE, MANIFEST, RECIPE_FILE, loadMontageStyles, mergePatch, parseRecipe } from "./takeMaker.mjs"; -import { isTakeId, listTakes, parseTake, takesDirOf, TAKE_FILE } from "./takes.mjs"; +import { BASE_FILE, frozenBaseText, isTakeId, listTakes, parseTake, takesDirOf, TAKE_FILE } from "./takes.mjs"; + +export { frozenBaseText }; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); @@ -98,20 +105,35 @@ export async function playableTakes(projectDir) { } /** - * The take's manifest: the project's manifest now + the style's patch + the - * take's patch. Throws (an Error whose message is the reason) when the take - * is not named anywhere or the project has no manifest. + * The take's manifest: its base + the style's patch + the take's patch. The + * base is the version's frozen manifest when it has one (`frozen`, the + * default), else the project's manifest now (`base`, when the caller has read + * it already). Throws (an Error whose message is the reason) when the take is + * not named anywhere or there is no manifest to lay it on. + * + * `frozen: false` lays the take over the project's manifest even when it is a + * frozen version: "this take's patch, over the draft as it is now" -- what + * the working cut's edit count compares (workingCut.mjs). * * @param {string} projectDir * @param {string} id - * @param {{ styles?: Record<string, { patch: Record<string, unknown> }> | null, base?: Record<string, unknown> | null }} [opts] - * @returns {Promise<{ manifest: Record<string, any>, take: NonNullable<Awaited<ReturnType<typeof takeSpecOf>>>, note: string | null }>} + * @param {{ styles?: Record<string, { patch: Record<string, unknown> }> | null, base?: Record<string, unknown> | null, frozen?: boolean }} [opts] + * @returns {Promise<{ manifest: Record<string, any>, take: NonNullable<Awaited<ReturnType<typeof takeSpecOf>>>, note: string | null, frozen: boolean }>} */ -export async function resolveTakeManifest(projectDir, id, { styles = null, base = null } = {}) { +export async function resolveTakeManifest(projectDir, id, { styles = null, base = null, frozen: preferFrozen = true } = {}) { if (!isTakeId(id)) throw new Error(`"${id}" is not a take id`); const take = await takeSpecOf(projectDir, id); if (!take) throw new Error(`no take ${id} (no takes/${id}/${TAKE_FILE}, and no recipe names it)`); - const project = base ?? (await readJson(path.join(projectDir, MANIFEST))); + const frozenText = preferFrozen && take.made ? await frozenBaseText(projectDir, id) : null; + let frozenDoc = null; + if (frozenText !== null) { + try { + frozenDoc = JSON.parse(frozenText); + } catch (e) { + throw new Error(`take ${id}: its takes/${id}/${BASE_FILE} does not parse (${e instanceof Error ? e.message : e})`); + } + } + const project = frozenDoc ?? base ?? (await readJson(path.join(projectDir, MANIFEST))); if (!isObj(project)) throw new Error(`the project has no ${MANIFEST}`); let stylePatch = null; let note = null; @@ -120,15 +142,45 @@ export async function resolveTakeManifest(projectDir, id, { styles = null, base stylePatch = all[take.style]?.patch ?? null; if (!stylePatch) { // The style is gone: the manifest the take was rendered from, as it was. - const frozen = take.made ? await readJson(path.join(takesDirOf(projectDir), id, MANIFEST)) : null; - if (!isObj(frozen)) throw new Error(`take ${id}: its style "${take.style}" is not installed, and it has no rendered manifest`); - return { manifest: frozen, take, note: `the style "${take.style}" is not installed: playing the manifest the take was rendered from` }; + // A frozen version keeps its own base; only the style is gone. + if (frozenDoc) { + const m = resolvePresetLayers(frozenDoc, [take.patch]); + if (!isObj(m) || !Array.isArray(m.timeline)) throw new Error(`take ${id}: the patched manifest has no timeline`); + return { manifest: /** @type {Record<string, any>} */ (m), take, note: `the style "${take.style}" is not installed: playing the version without it`, frozen: true }; + } + const rendered = take.made ? await readJson(path.join(takesDirOf(projectDir), id, MANIFEST)) : null; + if (!isObj(rendered)) throw new Error(`take ${id}: its style "${take.style}" is not installed, and it has no rendered manifest`); + return { manifest: rendered, take, note: `the style "${take.style}" is not installed: playing the manifest the take was rendered from`, frozen: true }; } } // preset → manifest → style → take patch (presets.mjs). const manifest = resolvePresetLayers(project, [stylePatch, take.patch]); if (!isObj(manifest) || !Array.isArray(manifest.timeline)) throw new Error(`take ${id}: the patched manifest has no timeline`); - return { manifest: /** @type {Record<string, any>} */ (manifest), take, note }; + return { manifest: /** @type {Record<string, any>} */ (manifest), take, note, frozen: frozenDoc !== null }; +} + +/** + * A take FROZEN, as it plays: a saved version's frozen base with its patches + * (resolveTakeManifest), else -- a legacy take -- the manifest it was rendered + * from (takes/<id>/video.manifest.json, the fallback the working cut has + * always compared with). null when it has neither (a legacy draft never + * rendered: it follows the project's manifest). + * + * @param {string} projectDir + * @param {string} id + * @returns {Promise<null | { manifest: Record<string, any>, source: "base" | "rendered" }>} + */ +export async function frozenManifestOf(projectDir, id) { + if (!isTakeId(id)) return null; + if ((await frozenBaseText(projectDir, id)) !== null) { + try { + return { manifest: (await resolveTakeManifest(projectDir, id)).manifest, source: "base" }; + } catch { + return null; + } + } + const rendered = await readJson(path.join(takesDirOf(projectDir), id, MANIFEST)); + return isObj(rendered) ? { manifest: rendered, source: "rendered" } : null; } // One merged manifest per (take, the files it is made from), for the media @@ -141,7 +193,9 @@ const mtimeOf = (f) => stat(/* turbopackIgnore: true */ f).then((s) => s.mtimeMs export async function cachedTakeManifest(projectDir, id) { const dir = takesDirOf(projectDir); const key = ( - await Promise.all([path.join(projectDir, MANIFEST), path.join(dir, id, TAKE_FILE), path.join(dir, RECIPE_FILE), path.join(dir, ALL_STYLES_RECIPE)].map(mtimeOf)) + await Promise.all( + [path.join(projectDir, MANIFEST), path.join(dir, id, TAKE_FILE), path.join(dir, id, BASE_FILE), path.join(dir, RECIPE_FILE), path.join(dir, ALL_STYLES_RECIPE)].map(mtimeOf), + ) ).join("|"); const slot = `${projectDir}\0${id}`; const hit = memo.get(slot); diff --git a/umtool/lib/report/takes.mjs b/umtool/lib/report/takes.mjs @@ -23,6 +23,15 @@ import { inside } from "../paths.mjs"; export const TAKES_DIR = "takes"; export const TAKE_FILE = "take.json"; export const VERDICTS_FILE = "verdicts.json"; +/** + * A SAVED VERSION's frozen manifest (lib/report/versions.mjs): the project's + * video.manifest.json as it was when the version was saved, byte for byte. + * When it is there, the take resolves over IT (takeManifest.mjs), never over + * the project's manifest as it is now. + */ +export const BASE_FILE = "base.manifest.json"; +/** The working draft's parent pointer (versions.mjs): `takes/draft.json` -- a file, so never listed as a take. */ +export const DRAFT_FILE = "draft.json"; /** A take id is its directory's name, and one url-safe segment. */ export const TAKE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/; @@ -44,6 +53,38 @@ export const verdictsFileOf = (projectDir) => path.join(takesDirOf(projectDir), const str = (v) => (typeof v === "string" ? v.trim() : ""); /** + * The working draft's parent pointer, takes/draft.json `{ from, hash, at }` + * (versions.mjs writes it): the version the draft was last saved as or opened + * from, the hash of the manifest it wrote, when. null when absent or not that + * shape -- the working cut then falls back to the newest working take. + * + * @param {string} projectDir + * @returns {Promise<{ from: string, hash: string | null, at: string | null, base?: Record<string, any> } | null>} + */ +export async function readDraftFile(projectDir) { + try { + const j = JSON.parse(await readFile(path.join(takesDirOf(projectDir), DRAFT_FILE), "utf8")); + if (!j || typeof j !== "object" || !isTakeId(j.from)) return null; + return { + from: j.from, + hash: typeof j.hash === "string" && j.hash ? j.hash : null, + at: typeof j.at === "string" && j.at ? j.at : null, + // A legacy take opened by merging its patch (versions.mjs openVersion) has no frozen form of its own: the + // manifest the open wrote, which the draft's edits are counted from. + ...(j.base && typeof j.base === "object" && !Array.isArray(j.base) ? { base: j.base } : {}), + }; + } catch { + return null; + } +} + +/** A saved version's frozen manifest (takes/<id>/base.manifest.json) as text, or null when the take has none. */ +export async function frozenBaseText(projectDir, id) { + if (!isTakeId(id)) return null; + return readFile(path.join(takesDirOf(projectDir), id, BASE_FILE), "utf8").catch(() => null); +} + +/** * One take.json, checked. `{ take }` or `{ error }` -- never a partial take. * * Required: id (== the directory), group, order, label, kind, preview. @@ -101,6 +142,9 @@ export function parseTake(dirName, raw) { // render is older than the take. if (j.draft !== undefined && typeof j.draft !== "boolean") return { error: "draft is not true or false" }; if (j.editedAt !== undefined && j.editedAt !== null && typeof j.editedAt !== "string") return { error: "editedAt is not a string" }; + // A SAVED VERSION (versions.mjs): the draft frozen into takes/<id>/base.manifest.json. + if (j.version !== undefined && typeof j.version !== "boolean") return { error: "version is not true or false" }; + if (j.savedAt !== undefined && j.savedAt !== null && typeof j.savedAt !== "string") return { error: "savedAt is not a string" }; return { take: { id: dirName, @@ -120,6 +164,8 @@ export function parseTake(dirName, raw) { quick: j.quick === true, draft: j.draft === true, editedAt: typeof j.editedAt === "string" && j.editedAt ? j.editedAt : null, + version: j.version === true, + savedAt: typeof j.savedAt === "string" && j.savedAt ? j.savedAt : null, }, }; } @@ -440,11 +486,17 @@ export async function setTakePicked(projectDir, takeId, group, { now = new Date( * new one is its group's pick (autoPickTake). A partial window, a style take * or a take with its own timeline is a variant, never the cut. * - * @param {{ window?: unknown, draft?: boolean, quick?: boolean, baseHash?: string | null, style?: string | null, patch?: Record<string, unknown> | null } | null | undefined} t + * A SAVED VERSION (versions.mjs, `version: true`) is one too, rendered or + * not: it IS the draft as it was, frozen -- unless a style or a timeline of + * its own was laid over it since. + * + * @param {{ window?: unknown, draft?: boolean, quick?: boolean, baseHash?: string | null, style?: string | null, patch?: Record<string, unknown> | null, version?: boolean } | null | undefined} t */ export function isWorkingTake(t) { + const ownTimeline = !!(t?.patch && typeof t.patch === "object" && Array.isArray(/** @type {any} */ (t.patch).timeline)); + if (t?.version === true) return t.window === "full" && !t.style && !ownTimeline && t.quick !== true; if (!t || t.window !== "full" || t.draft === true || t.quick === true || !t.baseHash || t.style) return false; - return !(t.patch && typeof t.patch === "object" && Array.isArray(/** @type {any} */ (t.patch).timeline)); + return !ownTimeline; } /** diff --git a/umtool/lib/report/takes.test.mjs b/umtool/lib/report/takes.test.mjs @@ -73,6 +73,8 @@ test("parseTake accepts the contract and fills the optional fields", () => { quick: false, draft: false, editedAt: null, + version: false, + savedAt: null, }); const min = parseTake("x", { id: "x", group: "g", order: 0, label: "X", kind: "reference", preview: "p.mp4" }); assert.ok("take" in min); diff --git a/umtool/lib/report/versions.mjs b/umtool/lib/report/versions.mjs @@ -0,0 +1,484 @@ +// THE WORKING DRAFT AND ITS SAVED VERSIONS (umtool redesign, lane L3; operator, +// 1 Nov 2026: "Most of the time I'll only really be working on the latest +// cut/draft rather than the picked one"). +// +// The project's video.manifest.json IS the draft: every UI edit lands in it. +// A take is a SAVED VERSION of it, frozen: +// +// takes/<id>/base.manifest.json the draft as it was, byte for byte -- the +// version resolves over THIS, never over the +// draft as it is now (takeManifest.mjs) +// takes/<id>/take.json `version: true, draft: true, patch: null, +// window: "full"`, its baseHash the base's +// takes/draft.json the draft's PARENT `{ from, hash, at }`: the +// version it was last saved as or opened from +// (a file, so listTakes never lists it) +// +// saveVersion(project, { label }) the draft frozen as the next `v<N>` +// openVersion(project, id) a version copied INTO the draft -- the +// draft saved first when it has edits +// since its parent, one undo point +// freezeTakes(project, { apply }) legacy takes given a frozen base +// (opt-in, a dry run by default) +// +// VERSION IDS are `v1`, `v2`, … -- the next number above every `v<N>` +// directory under takes/ (made or not), so a name is never reused and never +// collides with a take an agent named by hand. +// +// Both writers hold the MANIFEST LOCK (manifest.mjs withManifestLock), the one +// every manifest write takes in this process, so a save and an open are each +// one step against the bench's edits; across processes the token is the guard. +// +// Plain ESM: `umtool takes save|open|freeze` runs it under bare node. +import { createHash } from "node:crypto"; +import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { applyStructural, manifestToken, replaceManifestLocked, StaleToken, withManifestLock } from "./manifest.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { BASE_FILE, DRAFT_FILE, frozenBaseText, isTakeId, listTakes, readDraftFile, takesDirOf, TAKE_FILE } from "./takes.mjs"; +import { readWorkingCut } from "./workingCut.mjs"; + +const MANIFEST = "video.manifest.json"; +export const VERSION_RE = /^v(\d{1,6})$/; +const hashText = (text) => createHash("sha256").update(text).digest("hex"); +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); + +export class VersionRefused extends Error { + /** @param {string} message */ + constructor(message) { + super(message); + this.name = "VersionRefused"; + } +} + +/** The draft's parent pointer (takes/draft.json), or null. */ +export const readDraft = readDraftFile; + +/** + * Write takes/draft.json (tmp + rename). `from` null removes it. `base`: the + * manifest an open wrote when the version opened has no frozen form of its + * own (a legacy take merged) -- what the draft's edits are counted from. + * @param {string} projectDir + * @param {{ from: string | null, hash?: string | null, at?: string | null, base?: Record<string, any> | null }} d + */ +export async function writeDraft(projectDir, { from, hash = null, at = null, base = null }) { + const file = path.join(takesDirOf(projectDir), DRAFT_FILE); + if (!from) { + await rm(file, { force: true }); + return null; + } + if (!isTakeId(from)) throw new Error(`"${from}" is not a take id`); + await mkdir(path.dirname(file), { recursive: true }); + const doc = { from, hash, at: at ?? new Date().toISOString(), ...(base ? { base } : {}) }; + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); + await rename(tmp, file); + return doc; +} + +/** + * Every version number in use or ever pointed at: each `v<N>` directory under + * takes/ (made or not), the draft pointer's `from`, and each undo point's + * pointer sidecar (revisions/*.draft.json) -- so a version deleted while an + * Undo could still name it as the draft's parent is never reborn as another. + */ +async function usedVersionNumbers(projectDir) { + const nums = new Set(); + const add = (id) => { + const m = VERSION_RE.exec(String(id ?? "")); + if (m) nums.add(Number(m[1])); + }; + for (const x of await readdir(takesDirOf(projectDir)).catch(() => [])) add(x); + add((await readDraftFile(projectDir))?.from); + const rev = path.join(projectDir, "revisions"); + for (const x of await readdir(rev).catch(() => [])) { + if (!x.endsWith(".draft.json")) continue; + add(await readFile(path.join(rev, x), "utf8").then((t) => JSON.parse(t)?.from, () => null)); + } + return nums; +} + +/** The next free version id: `v<N+1>` over every version number in use or ever pointed at (usedVersionNumbers). */ +export async function nextVersionId(projectDir) { + const used = await usedVersionNumbers(projectDir); + return `v${Math.max(0, ...used) + 1}`; +} + +/** + * CLAIM the next version id: its directory made with a non-recursive mkdir, + * which only one process can win -- on EEXIST (another process, the CLI beside + * the app, took it first) the next number is tried. Returns the id and its dir. + */ +export async function claimVersionId(projectDir) { + const root = takesDirOf(projectDir); + await mkdir(root, { recursive: true }); + let n = Math.max(0, ...(await usedVersionNumbers(projectDir))) + 1; + for (;;) { + const dir = path.join(root, `v${n}`); + try { + await mkdir(dir); + return { id: `v${n}`, dir }; + } catch (e) { + if (/** @type {any} */ (e)?.code !== "EEXIST") throw e; + n += 1; + } + } +} + +async function writeAtomic(file, text) { + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, text, "utf8"); + await rename(tmp, file); +} + +/** + * saveVersion's body, inside the manifest lock: the draft's text copied byte + * for byte to takes/<id>/base.manifest.json, then take.json (LAST: until then + * the directory is a work dir the listing ignores), then draft.json. + * + * @param {string} projectDir + * @param {{ label?: string | null, now?: Date, force?: boolean, why?: string | null }} opts + */ +async function saveVersionLocked(projectDir, { label = null, now = new Date(), force = false, why = null } = {}) { + const text = await readFile(path.join(projectDir, MANIFEST), "utf8").catch(() => null); + if (text === null) throw new VersionRefused(`the project has no ${MANIFEST} to save`); + try { + if (!isObj(JSON.parse(text))) throw new Error("not an object"); + } catch (e) { + throw new VersionRefused(`${MANIFEST} does not parse; not saving it (${e instanceof Error ? e.message : e})`); + } + const working = await readWorkingCut(projectDir, { manifestText: text }); + if (!force && working.parent && working.edits?.count === 0) { + return { saved: false, id: working.parent.id, why: `no edits since ${working.parent.id}: nothing to save`, edits: working.edits, parent: working.parent.id }; + } + const { id, dir } = await claimVersionId(projectDir); + const { takes } = await listTakes(projectDir); + const parentTake = working.parent ? takes.find((t) => t.id === working.parent?.id) : null; + const group = parentTake?.group ?? takes.filter((t) => t.window === "full").at(-1)?.group ?? "takes"; + const order = Math.max(0, ...takes.map((t) => t.order)) + 1; + const l = typeof label === "string" ? label.replace(/\s+/g, " ").trim().slice(0, 200) : ""; + const iso = now.toISOString(); + const baseHash = hashText(text); + await writeAtomic(path.join(dir, BASE_FILE), text); + const doc = { + id, + group, + order, + label: l || (why ? why : working.parent ? `Saved draft (from ${working.parent.id})` : "Saved draft"), + kind: "reference", + summary: "", + changes: working.edits?.words?.length ? working.edits.words.slice(0, 40) : [], + preview: "preview.mp4", + seconds: null, + builtAt: null, + style: null, + patch: null, + window: "full", + version: true, + draft: true, + draftedAt: iso, + savedAt: iso, + baseHash, + ...(working.parent ? { draftedFrom: working.parent.id } : {}), + }; + await writeAtomic(path.join(dir, TAKE_FILE), JSON.stringify(doc, null, 2) + "\n"); + await writeDraft(projectDir, { from: id, hash: baseHash, at: iso }); + return { saved: true, id, label: doc.label, edits: working.edits, parent: working.parent?.id ?? null, baseHash }; +} + +/** + * SAVE THE DRAFT AS A VERSION: the next `v<N>`, frozen. Nothing is saved when + * the draft has no edits since its parent (`saved: false`, naming it) unless + * `force`. The pick (verdicts.json) is never touched: saving never unpins. + * + * @param {{ id: string, dir: string }} project + * @param {{ label?: string | null, now?: Date, force?: boolean }} [opts] + */ +export async function saveVersion(project, { label = null, now = new Date(), force = false } = {}) { + return withManifestLock(() => saveVersionLocked(project.dir, { label, now, force })); +} + +/** + * What opening take `id` would write into the draft, and how: + * "frozen" a saved version: its base (with any patch laid over it since) + * "rendered" a legacy rendered take of the cut's own timeline: the manifest it was + * rendered from (pickTake's copy, "Use this take") + * "merge" a legacy take with a timeline of its own, or one never rendered: its + * patch over the draft as it is now (promoteTake's merge) -- so a walk + * made since its render is what opens + * + * @param {string} projectDir + * @param {string} id + * @param {Record<string, any>} draft the draft, parsed + */ +export async function openedManifestOf(projectDir, id, draft) { + const { loadMontageStyles, mergePatch, versionManifestOf } = await import("./takeMaker.mjs"); + const v = await versionManifestOf(projectDir, id); + if (v) return { manifest: v.manifest, how: /** @type {const} */ ("frozen") }; + const { takeSpecOf } = await import("./takeManifest.mjs"); + const spec = await takeSpecOf(projectDir, id); + if (!spec) throw new VersionRefused(`no take ${id}`); + if (!spec.made) throw new VersionRefused(`take ${id} is only named by a recipe — nothing made to open`); + const ownTimeline = isObj(spec.patch) && Array.isArray(spec.patch.timeline); + const doc = JSON.parse(await readFile(path.join(takesDirOf(projectDir), id, TAKE_FILE), "utf8")); + // The manifest it rendered is what it IS only while its patch has not been edited since the render (a walk, + // a CLI take-scoped edit: `editedAt` after `builtAt`) -- Play ?take= plays the patch, so the open merges it. + const editedSince = typeof doc.editedAt === "string" && doc.editedAt && !(typeof doc.builtAt === "string" && doc.builtAt && doc.editedAt <= doc.builtAt); + const renderedText = doc.draft === true || editedSince ? null : await readFile(path.join(takesDirOf(projectDir), id, MANIFEST), "utf8").catch(() => null); + const rendered = renderedText !== null ? JSON.parse(renderedText) : null; + // NEVER a preset resolved into the draft: the rendered file has its preset laid in (presetApplied); it goes + // back to naming it, as the draft did (unresolvePreset), so the draft keeps following its preset. + if (!ownTimeline && isObj(rendered) && Array.isArray(rendered.timeline)) return { manifest: await unresolvePreset(rendered), how: /** @type {const} */ ("rendered") }; + // The take's style and patch merged over the draft as it is (promoteTake's merge) -- RFC 7386 only, the + // draft's `preset` left named, never resolved. + let stylePatch = null; + if (spec.style) { + stylePatch = (await loadMontageStyles()).styles[spec.style]?.patch ?? null; + if (!stylePatch) { + if (isObj(rendered) && Array.isArray(rendered.timeline)) return { manifest: await unresolvePreset(rendered), how: /** @type {const} */ ("rendered") }; + throw new VersionRefused(`take ${id}: its style "${spec.style}" is not installed, and it has no rendered manifest`); + } + } + const merged = [stylePatch, spec.patch].filter(Boolean).reduce((m, p) => mergePatch(m, p), draft); + if (!isObj(merged) || !Array.isArray(merged.timeline)) throw new VersionRefused(`take ${id}: the patched manifest has no timeline`); + // The build's structure rules, over the draft becoming the take's (promoteTake's check). + const next = JSON.parse(JSON.stringify(draft)); + applyStructural(next, (m) => { + for (const k of Object.keys(m)) delete m[k]; + Object.assign(m, JSON.parse(JSON.stringify(merged))); + }); + return { manifest: next, how: /** @type {const} */ ("merge") }; +} + +/** + * A manifest with its preset RESOLVED (resolvePresetLayers: `preset` deleted, `presetApplied` set, the + * preset's render keys laid in) back to NAMING it: `preset` again, and every render leaf whose value is the + * preset's own taken out (the preset puts it back). It resolves to what it was; an override stays. A manifest + * not resolved is returned as it is. + * + * @param {Record<string, any>} m + */ +export async function unresolvePreset(m) { + if (!isObj(m) || typeof m.presetApplied !== "string" || !m.presetApplied) return m; + const { loadPreset } = await import("umtool-report-to-video/presets"); + let preset; + try { + preset = loadPreset(m.presetApplied); + } catch { + return m; // a preset gone: the resolved manifest is all there is + } + const strip = (node, pre) => { + for (const k of Object.keys(pre)) { + if (!(k in node)) continue; + if (isObj(pre[k]) && isObj(node[k])) { + strip(node[k], pre[k]); + if (!Object.keys(node[k]).length) delete node[k]; + } else if (sameContent(node[k], pre[k])) delete node[k]; + } + }; + const { presetApplied, ...rest } = JSON.parse(JSON.stringify(m)); + const out = { preset: presetApplied, ...rest }; + if (isObj(out.render) && isObj(preset.render)) { + strip(out.render, preset.render); + if (!Object.keys(out.render).length) delete out.render; + } + return out; +} + +/** Deep equality that ignores key order (a manifest written by another writer orders its keys its own way). */ +export function sameContent(a, b) { + const canon = (v) => (Array.isArray(v) ? v.map(canon) : isObj(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, canon(v[k])])) : v); + return JSON.stringify(canon(a)) === JSON.stringify(canon(b)); +} + +/** + * Would opening `id` write nothing? When the draft already holds what it is (by content), or -- main's rule + * for a LEGACY take -- it is the draft's parent with no edits since (its rendered file is preset-resolved and + * carries its look patch; the draft is the same cut, naming its preset). + * + * @param {string} projectDir + * @param {string} id + * @param {Record<string, any>} draft + * @param {Awaited<ReturnType<typeof readWorkingCut>>} working + * @param {Record<string, any>} opened what openedManifestOf would write + */ +async function noopOpen(projectDir, id, draft, working, opened) { + if (sameContent(opened, draft)) return true; + const legacy = (await frozenBaseText(projectDir, id)) === null; + if (!legacy || working.parent?.id !== id || working.edits?.count !== 0) return false; + // Opened before (the pointer keeps what that open wrote): the content says it, not the rule. + const pointer = await readDraftFile(projectDir); + return !(pointer?.from === id && pointer.base); +} + +/** The undo point's sidecar: the draft pointer as it was before the write the snapshot takes back. */ +export const draftSidecarOf = (snapshotRel) => snapshotRel.replace(/\.manifest\.json$/, ".draft.json"); + +/** + * OPEN A VERSION IN THE DRAFT, under the manifest lock: + * 1. the draft saved as the next version first when it has edits since its + * parent (or has no parent at all) -- nothing in it is lost; + * 2. the version's manifest written over the draft (openedManifestOf), through + * the manifest writer with an undo point taken EVERY time (`every: 0`, + * `auto-before-open-<id>`; "Undo open <id>" restores the draft as it was, + * and the draft pointer beside it); + * 3. takes/draft.json naming the opened version. + * The pick and the pins (verdicts.json) are never touched: opening is not + * "Use this take". Opening a version the draft already holds (by content) writes nothing; a write from another process since the start is a StaleToken, and a failed open removes the version it saved and puts the pointer back. + * + * @param {{ id: string, dir: string, kind?: string }} project + * @param {string} id + * @param {{ token?: string | null, now?: Date }} [opts] + */ +export async function openVersion(project, id, { token = null, now = new Date(), _beforeWrite = null } = {}) { + if (!isTakeId(id)) throw new VersionRefused(`"${id}" is not a take id`); + const run = () => + withManifestLock(async () => { + const current = await manifestToken(project.dir); + if (token !== null && current !== token) throw new StaleToken(token, current); + const { takes } = await listTakes(project.dir); + if (!takes.some((t) => t.id === id)) throw new VersionRefused(`no take ${id} in this project`); + const text = await readFile(path.join(project.dir, MANIFEST), "utf8"); + const draft = JSON.parse(text); + const working = await readWorkingCut(project.dir, { manifestText: text }); + // What opening it would write, decided BEFORE anything is saved (a refusal leaves nothing behind). + const { manifest, how } = await openedManifestOf(project.dir, id, draft); + // Unchanged: the draft already holds what the version is, by content (a version's "No intro" since its + // save is not; it opens) -- or a legacy take that is the draft's parent with no edits (main's rule). The + // pointer is set when it named another. + if (await noopOpen(project.dir, id, draft, working, manifest)) { + if (working.parent?.id !== id || working.parent?.via !== "draft") { + await writeDraft(project.dir, { from: id, hash: hashText(text), at: now.toISOString(), base: how === "frozen" ? null : draft }); + } + return { opened: id, how: "unchanged", saved: null, snapshot: null, token: current, unchanged: true, edits: 0 }; + } + const edits = working.edits?.count ?? null; + const pointerBeforeSave = await readDraftFile(project.dir); + let saved = null; + // Nothing is lost when the draft IS a version's frozen base byte for byte (only that version's patch + // differs since -- a "No intro"): no second, byte-identical copy of it. + const parentBase = working.parent ? await frozenBaseText(project.dir, working.parent.id) : null; + const openedBase = await frozenBaseText(project.dir, id); + const kept = parentBase === text || openedBase === text; + if (!kept && (!working.parent || working.edits === null || working.edits.count > 0)) { + const r = await saveVersionLocked(project.dir, { now, force: true, why: `Draft before opening ${id}` }); + saved = r.saved ? r.id : null; + } + const draftBefore = await readDraftFile(project.dir); + const op = `open-${id}`.slice(0, 40).replace(/-+$/, ""); + let r; + try { + if (_beforeWrite) await _beforeWrite(); + // The token read at the start: a write from another process (the CLI) since is a StaleToken, never lost. + r = await replaceManifestLocked(project.dir, manifest, { op, every: 0, token: current }); + } catch (e) { + // The open did not happen: no stray version, the draft named as it was. + if (saved) await rm(path.join(takesDirOf(project.dir), saved), { recursive: true, force: true }).catch(() => {}); + await writeDraft(project.dir, pointerBeforeSave ?? { from: null }).catch(() => {}); + throw e; + } + // The undo point remembers the draft pointer, so Undo puts the parent back too (manifest.mjs undoStructural). + const rel = /** @type {any} */ (r.snapshot)?.rel; + if (rel && !(/** @type {any} */ (r.snapshot).skipped)) { + await writeFile(path.join(project.dir, draftSidecarOf(rel)), JSON.stringify(draftBefore ?? { from: null }, null, 2) + "\n", "utf8").catch(() => {}); + } + const written = await readFile(path.join(project.dir, MANIFEST), "utf8"); + // Not a frozen version: the draft's edits are counted from what was written (readWorkingCut). + await writeDraft(project.dir, { from: id, hash: hashText(written), at: now.toISOString(), base: how === "frozen" ? null : JSON.parse(written) }); + return { opened: id, how, saved, snapshot: r.snapshot, token: r.token, unchanged: false, edits, undo: `Undo open ${id}` }; + }); + // The generated-manifest guard, as every whole-manifest writer runs inside (edit-guard.mjs). + if (project.kind) { + const { result, editNotes } = await withEditNotes(/** @type {any} */ (project), run); + return { ...result, editNotes }; + } + return run(); +} + +/** Would opening `id` write nothing -- the draft already holds what it is? (OpenInDraftPage's straight-on.) */ +export async function openIsNoop(projectDir, id) { + try { + const text = await readFile(path.join(projectDir, MANIFEST), "utf8"); + const draft = JSON.parse(text); + const { manifest } = await openedManifestOf(projectDir, id, draft); + return await noopOpen(projectDir, id, draft, await readWorkingCut(projectDir, { manifestText: text }), manifest); + } catch { + return false; + } +} + +/** + * FREEZE LEGACY TAKES (opt-in; a dry run unless `apply`): a take made before + * versions follows the project's manifest as it is now (its patch over it). + * Frozen, it gets a base of its own -- the manifest it was RENDERED from + * (takes/<id>/video.manifest.json) when it has one, else the draft as it is + * now -- and `version: true`; its style and patch stay, laid over the base. + * Each row says what the take resolves to today against what it would + * resolve to frozen (cutDiff, in words), so nothing changes unseen. + * + * @param {{ id: string, dir: string }} project + * @param {{ ids?: string[] | null, apply?: boolean, now?: Date }} [opts] `ids` null: every take + */ +export async function freezeTakes(project, { ids = null, apply = false, now = new Date() } = {}) { + return withManifestLock(async () => { + const { takes, skipped } = await listTakes(project.dir); + const { resolveTakeManifest } = await import("./takeManifest.mjs"); + const { resolvePresetLayers } = await import("umtool-report-to-video/presets"); + const { loadMontageStyles } = await import("./takeMaker.mjs"); + const { cutDiff } = await import("./workingCut.mjs"); + const draftText = await readFile(path.join(project.dir, MANIFEST), "utf8").catch(() => null); + const wanted = ids ? takes.filter((t) => ids.includes(t.id)) : takes; + const missing = ids ? ids.filter((x) => !takes.some((t) => t.id === x)) : []; + /** @type {Array<{ id: string, action: "frozen" | "would-freeze" | "already" | "refused", source?: "rendered" | "draft", differs?: number, words?: string[], why?: string }>} */ + const rows = []; + let styles = null; + for (const t of wanted) { + if ((await frozenBaseText(project.dir, t.id)) !== null) { + rows.push({ id: t.id, action: "already" }); + continue; + } + const rendered = t.draft ? null : await readFile(path.join(takesDirOf(project.dir), t.id, MANIFEST), "utf8").catch(() => null); + const baseText = rendered ?? draftText; + if (baseText === null) { + rows.push({ id: t.id, action: "refused", why: "no rendered manifest, and the project has no manifest" }); + continue; + } + let today = null; + try { + today = (await resolveTakeManifest(project.dir, t.id)).manifest; + } catch (e) { + today = null; + } + let after = null; + try { + let stylePatch = null; + if (t.style) { + styles ??= (await loadMontageStyles()).styles; + stylePatch = styles[t.style]?.patch ?? null; + } + after = resolvePresetLayers(JSON.parse(baseText), [stylePatch, t.patch]); + } catch (e) { + rows.push({ id: t.id, action: "refused", why: `its base does not resolve: ${e instanceof Error ? e.message : e}` }); + continue; + } + const d = today && after ? cutDiff(today, after) : null; + const row = { id: t.id, action: /** @type {"frozen" | "would-freeze"} */ (apply ? "frozen" : "would-freeze"), source: /** @type {"rendered" | "draft"} */ (rendered !== null ? "rendered" : "draft"), differs: d ? d.count : 0, words: d ? d.words : [] }; + if (apply) { + const dir = path.join(takesDirOf(project.dir), t.id); + const takeFile = path.join(dir, TAKE_FILE); + // take.json under the take writer's own lock (takeEdit.mjs): a take-scoped edit in this process waits. + const { withTakeEditLock } = await import("./takeEdit.mjs"); + await withTakeEditLock(async () => { + const doc = JSON.parse(await readFile(takeFile, "utf8")); + await writeAtomic(path.join(dir, BASE_FILE), baseText); + doc.version = true; + doc.frozenAt = now.toISOString(); + doc.frozenFrom = row.source; + await writeAtomic(takeFile, JSON.stringify(doc, null, 2) + "\n"); + }); + } + rows.push(row); + } + return { project: project.id, apply, rows, missing, skipped }; + }); +} diff --git a/umtool/lib/report/versions.test.mjs b/umtool/lib/report/versions.test.mjs @@ -0,0 +1,498 @@ +// The working draft and its saved versions (versions.mjs): a version freezes, +// the draft knows its parent, opening a version never loses the draft or an +// undo point, and a legacy take resolves exactly as it always did. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { spawnSync } from "node:child_process"; + +import { freezeTakes, nextVersionId, openVersion, readDraft, saveVersion } from "./versions.mjs"; +import { composeTake, checkSpec, makeTake, pickTake } from "./takeMaker.mjs"; +import { resolveTakeManifest } from "./takeManifest.mjs"; +import { isWorkingTake, listTakes, readVerdicts, setTakePicked } from "./takes.mjs"; +import { draftLine, readWorkingCut, workingCutLine } from "./workingCut.mjs"; +import { createSnapshot, listSnapshots } from "./snapshots.mjs"; +import { moveEntry, undoStructural, updateClip } from "./manifest.mjs"; +import { PROJECT_KINDS } from "../projects/kinds.mjs"; +import { takesCommand } from "./takeCli.mjs"; + +const KIND = PROJECT_KINDS.find((k) => k.makesTakes).id; +const hash = (t) => createHash("sha256").update(t).digest("hex"); +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 }, + timeline: [clip("a", 0, 10), clip("b", 20, 25), clip("c", 40, 50)], +}; + +async function project(manifest = MANIFEST) { + const root = await mkdtemp(path.join(tmpdir(), "versions-")); + const dir = path.join(root, "reports", "proj"); + await mkdir(path.join(dir, "out", "clips-raw"), { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest, null, 2) + "\n"); + return { root, dir, proj: { id: "proj", dir, kind: KIND }, reportsRoot: path.join(root, "reports") }; +} +const text = (dir) => readFile(path.join(dir, "video.manifest.json"), "utf8"); +const json = async (f) => JSON.parse(await readFile(f, "utf8")); +const ids = async (dir) => (await json(path.join(dir, "video.manifest.json"))).timeline.map((e) => e.id).join(" "); + +test("saveVersion: v1 is the draft byte for byte, frozen; the draft knows it is from v1; an edit counts; no edits saves nothing", async () => { + const { root, dir, proj } = await project(); + try { + let w = await readWorkingCut(dir); + assert.equal(w.parent, null); + assert.equal(draftLine(w), "Draft · unsaved"); + const before = await text(dir); + const r = await saveVersion(proj, { label: "First pass" }); + assert.equal(r.saved, true); + assert.equal(r.id, "v1"); + assert.equal(await readFile(path.join(dir, "takes", "v1", "base.manifest.json"), "utf8"), before); + const doc = await json(path.join(dir, "takes", "v1", "take.json")); + assert.deepEqual([doc.version, doc.draft, doc.patch, doc.window, doc.baseHash, doc.label], [true, true, null, "full", hash(before), "First pass"]); + assert.equal(isWorkingTake(doc), true, "a version is the cut, rendered or not"); + assert.deepEqual(await readDraft(dir), { from: "v1", hash: hash(before), at: doc.savedAt }); + w = await readWorkingCut(dir); + assert.equal(w.parent?.id, "v1"); + assert.equal(w.latest, null, "a version not rendered is not the latest render"); + assert.equal(draftLine(w), "Draft · from v1 · no edits"); + assert.match(workingCutLine(w), /Draft from v1 · no edits since/); + // Nothing to save at no edits; --force saves anyway. + const none = await saveVersion(proj); + assert.equal(none.saved, false); + assert.equal(none.id, "v1"); + // An edit to the draft: v1 does not follow it. + await moveEntry(dir, "c", 0); + w = await readWorkingCut(dir); + assert.equal(w.edits?.count, 1); + assert.equal(draftLine(w), "Draft · from v1 · 1 edit"); + const v1 = (await resolveTakeManifest(dir, "v1")).manifest; + assert.deepEqual(v1.timeline.map((e) => e.id), ["a", "b", "c"], "the version is frozen"); + const r2 = await saveVersion(proj); + assert.equal(r2.id, "v2"); + assert.equal((await json(path.join(dir, "takes", "v2", "take.json"))).draftedFrom, "v1"); + assert.deepEqual((await listTakes(dir)).takes.map((t) => t.id), ["v1", "v2"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("nextVersionId: above every v<N> directory, made or not; never a name in use", async () => { + const { root, dir } = await project(); + try { + assert.equal(await nextVersionId(dir), "v1"); + await mkdir(path.join(dir, "takes", "v3"), { recursive: true }); + await mkdir(path.join(dir, "takes", "v10-tight"), { recursive: true }); + assert.equal(await nextVersionId(dir), "v4"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("openVersion: the draft saved first as the next version, the version copied in, one undo point that puts the draft AND its parent back", async () => { + const { root, dir, proj } = await project(); + try { + await saveVersion(proj); // v1: a b c + const v1Text = await text(dir); + await moveEntry(dir, "c", 0); // c a b + // A pinned pick elsewhere survives. + await mkdir(path.join(dir, "takes", "old"), { recursive: true }); + await writeFile(path.join(dir, "takes", "old", "take.json"), JSON.stringify({ id: "old", group: "takes", order: 0, label: "Old", kind: "reference", preview: "preview.mp4", window: "full", baseHash: "x" })); + await setTakePicked(dir, "old", ["old", "v1"], { pinned: true }); + const preOpen = await text(dir); + const r = await openVersion(proj, "v1"); + assert.equal(r.saved, "v2", "the draft's edit is kept as v2"); + assert.equal(r.how, "frozen"); + assert.equal(await readFile(path.join(dir, "takes", "v2", "base.manifest.json"), "utf8"), preOpen); + assert.equal(await text(dir), v1Text, "the draft is v1 again, byte for byte"); + assert.equal((await readDraft(dir))?.from, "v1"); + assert.match(r.snapshot.rel, /auto-before-open-v1\.manifest\.json$/); + let w = await readWorkingCut(dir); + assert.equal(w.parent?.id, "v1"); + assert.equal(w.edits?.count, 0); + const v = await readVerdicts(dir); + assert.deepEqual([v.old?.picked, v.old?.pinned], [true, true], "opening never moves or unpins the pick"); + // Opening it again: nothing written. + assert.equal((await openVersion(proj, "v1")).unchanged, true); + // Undo: the pre-open draft, and the draft's parent is v2 (what it was saved as). + const u = await undoStructural(dir); + assert.equal(u.op, "open-v1"); + assert.equal(await text(dir), preOpen); + assert.equal((await readDraft(dir))?.from, "v2"); + w = await readWorkingCut(dir); + assert.equal(w.edits?.count, 0); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("openVersion of a legacy take: a rendered one is the manifest it rendered; one with its own timeline merges its patch (promote)", async () => { + const { root, dir, proj } = await project(); + try { + const t0 = await text(dir); + const mk = async (id, doc, rendered = null) => { + await mkdir(path.join(dir, "takes", id), { recursive: true }); + await writeFile(path.join(dir, "takes", id, "take.json"), JSON.stringify({ id, group: "takes", order: 1, label: id, kind: "different", preview: "preview.mp4", window: "full", baseHash: hash(t0), ...doc })); + if (rendered) await writeFile(path.join(dir, "takes", id, "video.manifest.json"), JSON.stringify(rendered, null, 2) + "\n"); + }; + // Rendered from an older manifest (its baseHash is not the draft's), with a look patch. + await mk("rendered", { builtAt: "2026-11-01T00:00:00Z", baseHash: "older", patch: { title: "Rendered" } }, { ...MANIFEST, title: "Rendered", timeline: [clip("a", 0, 10)] }); + await mk("own", { draft: true, patch: { timeline: [clip("b", 21, 24), clip("z", 1, 2)] } }); + // Legacy takes resolve as they always did: their patch over the project's manifest now. + assert.deepEqual((await resolveTakeManifest(dir, "rendered")).manifest.timeline.map((e) => e.id), ["a", "b", "c"]); + const r = await openVersion(proj, "rendered"); + assert.equal(r.how, "rendered"); + assert.equal(r.saved, "v1", "the draft differs from its parent (the latest render): saved first"); + assert.equal(await ids(dir), "a"); + assert.equal((await json(path.join(dir, "video.manifest.json"))).title, "Rendered"); + const o = await openVersion(proj, "own"); + assert.equal(o.how, "merge"); + assert.equal(await ids(dir), "b z"); + assert.equal((await json(path.join(dir, "takes", "own", "take.json"))).patch.timeline.length, 2, "the take itself is untouched"); + // Its edits are counted from what the open wrote (it has no frozen form of its own). + let w = await readWorkingCut(dir); + assert.deepEqual([w.parent?.id, w.edits?.count], ["own", 0]); + await moveEntry(dir, "z", 0); + w = await readWorkingCut(dir); + assert.deepEqual([w.parent?.id, w.edits?.count], ["own", 1]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a version renders its frozen base, and pickTake uses an unrendered version", async () => { + const { root, dir, proj } = await project(); + try { + await saveVersion(proj); // v1: a b c + await moveEntry(dir, "c", 0); + const c = await composeTake(dir, checkSpec({ id: "v1", label: "v1", window: "full" })); + assert.equal(c.frozen, true); + assert.deepEqual(c.manifest.timeline.map((e) => e.id), ["a", "b", "c"]); + // Rendered with a stub: still a version, its baseHash the base's, its frozen manifest what it rendered. + const calls = []; + const render = async (job) => { + const doc = JSON.parse(await readFile(job.manifestPath, "utf8")); + calls.push(doc.timeline.map((e) => e.id).join(" ")); + const file = path.join(job.outDir, `${job.slug}.mp4`); + await writeFile(file, "mp4"); + return { file }; + }; + const base = await readFile(path.join(dir, "takes", "v1", "base.manifest.json"), "utf8"); + await makeTake(dir, { id: "v1", label: "v1", window: "full" }, { force: true, render, styles: {}, probe: async () => 9, record: false, pruneAfter: false }); + assert.deepEqual(calls, ["a b c"]); + const doc = await json(path.join(dir, "takes", "v1", "take.json")); + assert.deepEqual([doc.version, doc.baseHash, doc.draft], [true, hash(base), undefined]); + assert.equal((await readDraft(dir))?.from, "v1", "a frozen version re-rendered does not move the draft's parent"); + // An unrendered version is picked from its base. + await saveVersion(proj); // v2: c a b + await moveEntry(dir, "a", 0); + await pickTake(proj, "v2", { anyway: true }); + assert.equal(await ids(dir), "c a b"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("freezeTakes: a dry run writes nothing; --apply gives a legacy take the base it was rendered from", async () => { + const { root, dir, proj } = await project(); + try { + const t0 = await text(dir); + await mkdir(path.join(dir, "takes", "d1"), { recursive: true }); + await writeFile(path.join(dir, "takes", "d1", "take.json"), JSON.stringify({ id: "d1", group: "takes", order: 1, label: "d1", kind: "reference", preview: "preview.mp4", window: "full", baseHash: hash(t0), builtAt: "2026-11-01T00:00:00Z" })); + await writeFile(path.join(dir, "takes", "d1", "video.manifest.json"), t0); + await moveEntry(dir, "c", 0); + const dry = await freezeTakes(proj, { ids: null }); + assert.deepEqual(dry.rows.map((x) => [x.id, x.action, x.source, x.differs]), [["d1", "would-freeze", "rendered", 1]]); + await assert.rejects(stat(path.join(dir, "takes", "d1", "base.manifest.json"))); + assert.deepEqual((await resolveTakeManifest(dir, "d1")).manifest.timeline.map((e) => e.id), ["c", "a", "b"], "unfrozen, it follows the draft"); + const done = await freezeTakes(proj, { ids: ["d1"], apply: true }); + assert.equal(done.rows[0].action, "frozen"); + assert.equal(await readFile(path.join(dir, "takes", "d1", "base.manifest.json"), "utf8"), t0); + assert.deepEqual((await resolveTakeManifest(dir, "d1")).manifest.timeline.map((e) => e.id), ["a", "b", "c"]); + assert.equal((await freezeTakes(proj, { ids: ["d1"] })).rows[0].action, "already"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("snapshots in one second are two undo points, newest first", async () => { + const { root, dir } = await project(); + try { + const now = new Date("2026-11-09T10:00:00.120Z"); + const a = await createSnapshot(dir, { label: "auto-before-trim", now }); + const b = await createSnapshot(dir, { label: "auto-before-trim", now: new Date("2026-11-09T10:00:00.480Z") }); + const c = await createSnapshot(dir, { label: "auto-before-move", now: new Date("2026-11-09T10:00:00.480Z") }); + assert.notEqual(a.name, b.name); + assert.notEqual(b.name, c.name); + const list = await listSnapshots(dir); + assert.deepEqual(list.map((s) => s.name), [c.name, b.name, a.name]); + assert.equal(list[0].label, "auto-before-move"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("umtool takes save | open | freeze, with --json", async () => { + const { root, dir, reportsRoot } = await project(); + try { + const out = []; + const err = []; + const run = (args) => takesCommand(args, { reportsRoot, log: (s) => out.push(s), err: (s) => err.push(s) }); + assert.equal(await run(["save", "proj", "--label", "Pass one", "--json"]), 0); + assert.equal(JSON.parse(out.pop()).id, "v1"); + await updateClip(dir, "a", { end: 9 }); + assert.equal(await run(["save", "proj"]), 0); + assert.match(out.pop(), /saved as v2/); + assert.equal(await run(["open", "proj", "v1", "--json"]), 0); + const o = JSON.parse(out.pop()); + assert.deepEqual([o.opened, o.saved], ["v1", null]); + assert.equal(await run(["freeze", "proj", "--all"]), 0); + assert.equal(await run(["freeze", "proj"]), 2); + assert.deepEqual((await readdir(path.join(dir, "takes"))).sort(), ["draft.json", "v1", "v2"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("one undo stack: in the app (setUndoEveryMs(0)) two trims a moment apart are two undo points, undone one by one; the terminal -- and a step the app spawns -- keeps the throttle", async () => { + const { root, dir } = await project(); + const { setUndoEveryMs } = await import("./manifest.mjs"); + try { + const t0 = await text(dir); + // The terminal: the second trim of a burst takes no undo point of its own. + setUndoEveryMs(null); + const a = await updateClip(dir, "a", { end: 9 }); + const b = await updateClip(dir, "a", { end: 8 }); + assert.equal(a.snapshot?.skipped, false); + assert.equal(b.snapshot?.skipped, true); + await writeFile(path.join(dir, "video.manifest.json"), t0); + await rm(path.join(dir, "revisions"), { recursive: true, force: true }); + // The app: each its own. + setUndoEveryMs(0); + // ...and a child process the app spawns (lib/jobs.ts passes process.env) does NOT inherit it. + assert.equal(process.env.UMTOOL_UNDO_EVERY_MS, undefined); + const child = spawnSync(process.execPath, ["--input-type=module", "-e", `import("${new URL("./manifest.mjs", import.meta.url).href}").then((m) => console.log(m.undoEveryMs()))`], { env: process.env, encoding: "utf8" }); + assert.equal(child.stdout.trim(), "120000", child.stderr); + await updateClip(dir, "a", { end: 9 }); + const t1 = await text(dir); + await updateClip(dir, "a", { end: 8 }); + // A verdict alone is not an undo point (the bench keeps its own undo for those). + const v = await updateClip(dir, "b", { verdict: "confirmed" }, { edit: "verdict" }); + assert.equal(v.snapshot, undefined); + await undoStructural(dir); + const back1 = JSON.parse(await text(dir)); + assert.equal(back1.timeline[0].end, 9); + assert.deepEqual(JSON.parse(t1).timeline[0], back1.timeline[0]); + await undoStructural(dir); + assert.equal(JSON.parse(await text(dir)).timeline[0].end, 10); + } finally { + setUndoEveryMs(null); + await rm(root, { recursive: true, force: true }); + } +}); + +test("undo points are pruned to the newest N; a named snapshot is never pruned", async () => { + const { root, dir } = await project(); + try { + const { autoSnapshot, pruneAutoSnapshots } = await import("./manifest.mjs"); + const named = await createSnapshot(dir, { label: "keep-me" }); + for (let i = 0; i < 5; i += 1) await autoSnapshot(dir, `op${i}`, { every: 0, keep: 1000 }); + assert.equal((await listSnapshots(dir)).length, 6); + const gone = await pruneAutoSnapshots(dir, 3); + assert.equal(gone.length, 2); + const left = await listSnapshots(dir); + assert.deepEqual(left.filter((x) => x.label?.startsWith("auto-before-")).map((x) => x.label), ["auto-before-op4", "auto-before-op3", "auto-before-op2"]); + assert.ok(left.some((x) => x.name === named.name)); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +// ---- the review's fixes (L3 review, 9 Nov) ---- + +test("a version's patch never masks a draft edit: v2 'No intro' and an intro in the draft is an edit; open(v2) brings its No intro in (no byte-identical save of its base); open(v1) after another intro saves it first", async () => { + const { root, dir, proj } = await project(); + const setIntro = async (on) => { + const m = JSON.parse(await text(dir)); + if (on) m.render.intro = "boot-dark"; + else delete m.render.intro; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + }; + try { + await saveVersion(proj); // v1: no intro + await moveEntry(dir, "c", 0); + await setIntro(true); + await saveVersion(proj); // v2: with the intro + // v2 "No intro" since (its patch): the draft still has the intro -- that IS a difference from v2. + const v2doc = await json(path.join(dir, "takes", "v2", "take.json")); + v2doc.patch = { render: { intro: null } }; + await writeFile(path.join(dir, "takes", "v2", "take.json"), JSON.stringify(v2doc, null, 2) + "\n"); + let w = await readWorkingCut(dir); + assert.equal(w.parent?.id, "v2"); + assert.equal(w.edits?.count, 1, "the draft's intro is not masked by v2's patch"); + const withIntro = await text(dir); + const o2 = await openVersion(proj, "v2"); + assert.equal(o2.unchanged, false, "not 'unchanged': v2's No intro is not in the draft"); + assert.equal(o2.saved, null, "the draft IS v2's base byte for byte: no second copy of it"); + assert.equal(await readFile(path.join(dir, "takes", "v2", "base.manifest.json"), "utf8"), withIntro, "kept there"); + assert.ok(!("intro" in JSON.parse(await text(dir)).render), "v2's No intro reached the draft"); + assert.equal((await openVersion(proj, "v2")).unchanged, true, "now the draft holds it"); + w = await readWorkingCut(dir); + assert.deepEqual([w.parent?.id, w.edits?.count], ["v2", 0]); + // The intro added to the draft again: an edit (v2's patch does not hide it) -- but the draft is v2's base + // byte for byte, so open(v1) keeps no second copy of it. + await setIntro(true); + assert.equal((await readWorkingCut(dir)).edits?.count, 1); + assert.equal(await text(dir), withIntro); + assert.equal((await openVersion(proj, "v1")).saved, null); + // A real edit since v1: saved first. + await moveEntry(dir, "a", 2); + const edited = await text(dir); + const o1 = await openVersion(proj, "v1"); + assert.equal(o1.saved, "v3"); + assert.equal(await readFile(path.join(dir, "takes", "v3", "base.manifest.json"), "utf8"), edited); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a legacy rendered take whose patch was edited after its render opens by its patch, not the stale render", async () => { + const { root, dir, proj } = await project(); + try { + await mkdir(path.join(dir, "takes", "r"), { recursive: true }); + await writeFile(path.join(dir, "takes", "r", "video.manifest.json"), JSON.stringify({ ...MANIFEST, title: "Rendered" }, null, 2)); + const doc = { id: "r", group: "takes", order: 1, label: "r", kind: "different", preview: "preview.mp4", window: "full", baseHash: "x", builtAt: "2026-11-01T00:00:00Z", patch: { title: "Walked since" } }; + await writeFile(path.join(dir, "takes", "r", "take.json"), JSON.stringify({ ...doc, editedAt: "2026-11-02T00:00:00Z" })); + const o = await openVersion(proj, "r"); + assert.equal(o.how, "merge"); + assert.equal(JSON.parse(await text(dir)).title, "Walked since"); + // Not edited since its render: the rendered manifest, as before. + await writeFile(path.join(dir, "takes", "r", "take.json"), JSON.stringify({ ...doc, editedAt: "2026-10-31T00:00:00Z" })); + const o2 = await openVersion(proj, "r"); + assert.equal(o2.how, "rendered"); + assert.equal(JSON.parse(await text(dir)).title, "Rendered"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("version ids: claimed exclusively (two claims at once get two ids); a number a pointer or an undo sidecar names is never reused", async () => { + const { root, dir } = await project(); + try { + const { claimVersionId } = await import("./versions.mjs"); + const [a, b] = await Promise.all([claimVersionId(dir), claimVersionId(dir)]); + assert.notEqual(a.id, b.id); + assert.deepEqual([a.id, b.id].sort(), ["v1", "v2"]); + // v5 deleted, but an undo point's sidecar still names it: never v5 again. + await mkdir(path.join(dir, "revisions"), { recursive: true }); + await writeFile(path.join(dir, "revisions", "20261109-100000-auto-before-open-v1.draft.json"), JSON.stringify({ from: "v5" })); + assert.equal(await nextVersionId(dir), "v6"); + await writeFile(path.join(dir, "takes", "draft.json"), JSON.stringify({ from: "v9" })); + assert.equal((await claimVersionId(dir)).id, "v10"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("openVersion: a write from another process between its read and its write is a StaleToken -- nothing lost, the version it saved removed, the pointer put back", async () => { + const { root, dir, proj } = await project(); + try { + await saveVersion(proj); // v1 + await moveEntry(dir, "c", 0); // an edit: open(v1) saves first + const pointer = await readDraft(dir); + let theirs = ""; + await assert.rejects( + openVersion(proj, "v1", { + _beforeWrite: async () => { + // The CLI, another process: a write the lock cannot see (its mtime moves the token). + await new Promise((r) => setTimeout(r, 20)); + const m = JSON.parse(await text(dir)); + m.title = "Written by the CLI"; + theirs = JSON.stringify(m, null, 2) + "\n"; + await writeFile(path.join(dir, "video.manifest.json"), theirs); + }, + }), + (e) => e?.name === "StaleToken", + ); + assert.equal(await text(dir), theirs, "the other write stands"); + await assert.rejects(stat(path.join(dir, "takes", "v2")), "no stray v2"); + assert.deepEqual(await readDraft(dir), pointer, "the pointer as it was"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a working take rendered while the draft was opened leaves the opened pointer alone", async () => { + const { root, dir, proj } = await project(); + try { + const render = async (job) => { + // Mid-render, somebody opens a version (the pointer moves). + await writeFile(path.join(dir, "takes", "draft.json"), JSON.stringify({ from: "v1", hash: null, at: "2026-11-09T00:00:00Z" })); + const file = path.join(job.outDir, `${job.slug}.mp4`); + await writeFile(file, "mp4"); + return { file }; + }; + await mkdir(path.join(dir, "takes"), { recursive: true }); + await makeTake(dir, { id: "full-1", label: "Full", window: "full" }, { render, styles: {}, probe: async () => 9, record: false, pruneAfter: false }); + assert.equal((await readDraft(dir))?.from, "v1", "the open's pointer stands"); + // Nothing moved it this time: the new working take is the draft's parent. + await makeTake(dir, { id: "full-2", label: "Full 2", window: "full" }, { render: async (job) => { + const file = path.join(job.outDir, `${job.slug}.mp4`); + await writeFile(file, "mp4"); + return { file }; + }, styles: {}, probe: async () => 9, record: false, pruneAfter: false }); + assert.equal((await readDraft(dir))?.from, "full-2"); + void proj; + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a project naming a PRESET: its latest legacy take with no edits opens as nothing (straight on); opened after an edit, the draft keeps naming the preset -- never the resolved manifest", async () => { + const { resolvePresetLayers } = await import("umtool-report-to-video/presets"); + const { openIsNoop, sameContent } = await import("./versions.mjs"); + const { root, dir, proj } = await project({ ...MANIFEST, preset: "plain-deck", render: { crf: 30 } }); + try { + const render = async (job) => { + const file = path.join(job.outDir, `${job.slug}.mp4`); + await writeFile(file, "mp4"); + return { file }; + }; + await makeTake(dir, { id: "d1", label: "Draft 1", window: "full" }, { render, styles: {}, probe: async () => 9, record: false, pruneAfter: false }); + const rendered = await json(path.join(dir, "takes", "d1", "video.manifest.json")); + assert.equal(rendered.presetApplied, "plain-deck", "the render's file is preset-resolved"); + // Make the pointer "latest" again (main's shape: no draft.json), the draft untouched since the render. + await rm(path.join(dir, "takes", "draft.json"), { force: true }); + let w = await readWorkingCut(dir); + assert.deepEqual([w.parent?.id, w.edits?.count], ["d1", 0]); + assert.equal(await openIsNoop(dir, "d1"), true, "the 307 straight-on is kept"); + const before = await text(dir); + assert.equal((await openVersion(proj, "d1")).unchanged, true); + assert.equal(await text(dir), before, "nothing written over the draft"); + // An edit, then open d1: the rendered cut comes back NAMING its preset. + await moveEntry(dir, "c", 0); + const o = await openVersion(proj, "d1"); + assert.equal(o.how, "rendered"); + const now = JSON.parse(await text(dir)); + assert.equal(now.preset, "plain-deck"); + assert.equal(now.presetApplied, undefined); + assert.deepEqual(now.render, { crf: 30 }, "the draft's override stays; the preset's keys are the preset's"); + assert.deepEqual(now.timeline.map((e) => e.id), ["a", "b", "c"]); + assert.ok(sameContent(resolvePresetLayers(now), rendered), "it resolves to exactly what was rendered"); + // A legacy take with its own timeline, merged: the preset stays named too. + await mkdir(path.join(dir, "takes", "own"), { recursive: true }); + await writeFile(path.join(dir, "takes", "own", "take.json"), JSON.stringify({ id: "own", group: "takes", order: 5, label: "own", kind: "different", preview: "preview.mp4", draft: true, patch: { timeline: [clip("b", 21, 24)] } })); + const m = await openVersion(proj, "own"); + assert.equal(m.how, "merge"); + const after = JSON.parse(await text(dir)); + assert.deepEqual([after.preset, after.presetApplied, after.render], ["plain-deck", undefined, { crf: 30 }]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/workingCut.mjs b/umtool/lib/report/workingCut.mjs @@ -1,20 +1,24 @@ // THE WORKING CUT'S NAME (operator, 1 Nov 2026): "Most of the time I'll only // really be working on the latest cut/draft rather than the picked one". // -// The project's video.manifest.json IS the working cut: the bench, Play, the -// Cut tab and every agent write it, and every take is MADE FROM it (take.json -// `baseHash`, the hash of the manifest it was made from). So the cut has a -// name -- the newest WORKING take (takes.mjs isWorkingTake: a whole-cut render -// of the manifest's own content) -- and a distance from it: the edits made to -// the manifest since that take was made. +// The project's video.manifest.json IS the working cut -- the DRAFT: the +// bench, Play, the Cut tab and every agent write it, and every take is MADE +// FROM it (take.json `baseHash`, the hash of the manifest it was made from). +// A saved version (versions.mjs) is the draft frozen. So the cut has a name +// and a distance from it: // -// latest the newest working take, by builtAt (then order) -// edits 0 when the manifest's hash is the take's baseHash; else the -// entries added, removed, moved and changed between the manifest -// the take RENDERED (takes/<id>/video.manifest.json, its patch -// applied) and the manifest now with the same patch -- in words -// ("aw3 removed", "mc1 moved"); null when the take's rendered -// manifest is gone (pruned) and the hashes differ +// latest the newest working take RENDERED (takes.mjs isWorkingTake), by +// builtAt (then order) +// parent what the draft was last saved as or opened from: takes/draft.json +// `from` (versions.mjs), else `latest` +// edits since the parent, in words ("aw3 removed", "mc1 moved"): a saved +// version as the draft would hold it (versionManifestOf: its base +// with any patch merged) against the draft AS IT IS; a legacy take +// opened in the draft, what the open wrote against the draft as it +// is; any other legacy take (main's rule), the manifest it RENDERED +// against the draft with its patch -- 0 at once when a hash says the +// draft is what was written; null when there is nothing frozen to +// compare (a legacy take's rendered manifest pruned) // picked the group pick in verdicts.json (secondary: "Use this take", // auto-picked for each new working take unless pinned) // @@ -22,7 +26,9 @@ import { createHash } from "node:crypto"; import { readFile } from "node:fs/promises"; import path from "node:path"; -import { isWorkingTake, listTakes, readVerdicts, takesDirOf } from "./takes.mjs"; +import { frozenBaseText, isWorkingTake, listTakes, readDraftFile, readVerdicts } from "./takes.mjs"; + +const hasFrozenBase = async (dir, id) => (await frozenBaseText(dir, id)) !== null; const MANIFEST = "video.manifest.json"; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); @@ -122,51 +128,113 @@ async function readJson(file) { } /** - * The working cut: the newest working take, the edits since it, the pick. + * The working cut: the newest working take, the draft's PARENT and the edits + * since it, the pick. + * + * THE PARENT (lib/report/versions.mjs): the version the draft was last saved + * as or opened from -- takes/draft.json `from` while that take exists -- else + * the newest working take, as it always was. `latestWorkingTake` cannot name + * it once an older version has been opened. + * + * THE EDITS are counted by cutDiff, never by a hash alone: re-serialising a + * manifest changes its bytes and not what it says. A hash that matches (the + * draft.json hash, or the parent's baseHash) is 0 edits at once; otherwise + * the parent frozen (its version's base, or the manifest a legacy take was + * rendered from) against the draft with the parent's patch laid over it. * * @param {string} projectDir - * @param {{ manifestText?: string | null, resolveNow?: ((takeId: string) => Promise<Record<string, any> | null>) | null }} [opts] - * `resolveNow`: the manifest as it is now with that take's patch (takeManifest.mjs resolveTakeManifest) -- - * compared with what the take rendered; without it the bare manifest is compared + * @param {{ manifestText?: string | null }} [opts] */ -export async function readWorkingCut(projectDir, { manifestText = null, resolveNow = null } = {}) { - const [listing, verdicts] = await Promise.all([listTakes(projectDir), readVerdicts(projectDir)]); +export async function readWorkingCut(projectDir, { manifestText = null } = {}) { + const [listing, verdicts, draft] = await Promise.all([listTakes(projectDir), readVerdicts(projectDir), readDraftFile(projectDir)]); const takes = listing.takes; const latest = latestWorkingTake(takes); const pickedId = Object.keys(verdicts).find((id) => verdicts[id]?.picked && takes.some((t) => t.id === id)) ?? null; const picked = pickedId ? { id: pickedId, at: verdicts[pickedId].at || null, pinned: verdicts[pickedId].pinned === true, label: takes.find((t) => t.id === pickedId)?.label ?? pickedId } : null; - if (!latest) return { latest: null, edits: null, picked, takes: takes.length }; + const fromDraft = draft ? takes.find((t) => t.id === draft.from) ?? null : null; + const parentTake = fromDraft ?? latest; + const latestOut = latest ? { id: latest.id, label: latest.label, builtAt: latest.builtAt ?? null, seconds: latest.seconds ?? null, group: latest.group } : null; + if (!parentTake) return { latest: null, parent: null, edits: null, picked, takes: takes.length }; + const parent = { + id: parentTake.id, + label: parentTake.label, + builtAt: parentTake.builtAt ?? null, + seconds: parentTake.seconds ?? null, + group: parentTake.group, + version: parentTake.version === true, + rendered: !!parentTake.builtAt, + // Why it is the parent: the draft pointer, or (no pointer) the newest working take. + via: fromDraft ? "draft" : "latest", + }; const text = manifestText ?? (await readFile(/* turbopackIgnore: true */ path.join(projectDir, MANIFEST), "utf8").catch(() => null)); let edits = null; - if (text !== null && hashText(text) === latest.baseHash) edits = { count: 0, words: [], same: true }; - else { - const rendered = await readJson(path.join(takesDirOf(projectDir), latest.id, MANIFEST)); + const h = text !== null ? hashText(text) : null; + const diffOf = (a, b) => { + const d = cutDiff(a, b); + return { count: d.count, words: d.words, same: d.count === 0 }; + }; + if (text !== null && (await hasFrozenBase(projectDir, parentTake.id))) { + // A SAVED VERSION: the version as the draft would hold it (its base, with any patch laid over it since -- a + // "No intro" toggle) against the draft AS IT IS. Never the version's patch over the draft: a key the patch + // sets would mask the draft's own edit of it. + try { + const { versionManifestOf } = await import("./takeMaker.mjs"); + const v = await versionManifestOf(projectDir, parentTake.id); + edits = v && v.exact && hashText(v.text) === h ? { count: 0, words: [], same: true } : v ? diffOf(v.manifest, JSON.parse(text)) : null; + } catch { + edits = null; + } + } else if (text !== null && fromDraft && draft?.base) { + // A legacy take opened in the draft: the edits since the open, against what it wrote (as it is, no patch). + try { + edits = draft.hash === h ? { count: 0, words: [], same: true } : diffOf(draft.base, JSON.parse(text)); + } catch { + edits = null; + } + } else if (h !== null && ((fromDraft && draft?.hash === h) || parentTake.baseHash === h)) edits = { count: 0, words: [], same: true }; + else if (text !== null) { + // A legacy take (main's rule): the manifest it rendered against the draft with its patch laid over it. + const { frozenManifestOf, resolveTakeManifest } = await import("./takeManifest.mjs"); + const frozen = await frozenManifestOf(projectDir, parentTake.id); let now = null; try { - now = resolveNow ? await resolveNow(latest.id) : text !== null ? JSON.parse(text) : null; + now = (await resolveTakeManifest(projectDir, parentTake.id, { base: JSON.parse(text), frozen: false })).manifest; } catch { now = null; } - if (isObj(rendered) && isObj(now)) { - const d = cutDiff(rendered, now); - edits = { count: d.count, words: d.words, same: false }; - } + if (frozen && isObj(now)) edits = diffOf(frozen.manifest, now); } - return { - latest: { id: latest.id, label: latest.label, builtAt: latest.builtAt ?? null, seconds: latest.seconds ?? null, group: latest.group }, - edits, - picked, - takes: takes.length, - }; + return { latest: latestOut, parent, edits, picked, takes: takes.length }; } -/** "Latest: draft-22 · 28:04 · +3 edits since" -- the line `umtool takes ls` prints first, and the pages show. */ +/** + * "Latest: draft-22 · 28:04 · +3 edits since" -- the line `umtool takes ls` + * prints first, and the pages show. When the draft's parent is not the newest + * working take (an older version opened): "… · the draft is from v5, +2 edits since". + */ export function workingCutLine(w) { - if (!w?.latest) return "Latest: no whole-cut take yet — the manifest is the cut"; + const edWords = (e) => (!e ? "edits since: unknown (its rendered manifest is gone)" : e.count === 0 ? "no edits since" : `+${e.count} edit${e.count === 1 ? "" : "s"} since`); + const p = w?.parent ?? null; + if (!w?.latest) { + if (p) return `Draft from ${p.id} · ${edWords(w.edits)} (no whole-cut take rendered yet)`; + return "Latest: no whole-cut take yet — the manifest is the cut"; + } const s = w.latest.seconds; const len = typeof s === "number" ? ` · ${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}` : ""; - const ed = !w.edits ? " · edits since: unknown (its rendered manifest is gone)" : w.edits.count === 0 ? " · no edits since" : ` · +${w.edits.count} edit${w.edits.count === 1 ? "" : "s"} since`; - return `Latest: ${w.latest.id}${len}${ed}`; + if (p && p.id !== w.latest.id) return `Latest: ${w.latest.id}${len} · the draft is from ${p.id}, ${edWords(w.edits)}`; + return `Latest: ${w.latest.id}${len} · ${edWords(w.edits)}`; +} + +/** + * The draft's own line (Play's header, the bench): "Draft · from v5 · 3 edits", + * "Draft · from v5 · no edits", or "Draft · unsaved" (no version yet). + */ +export function draftLine(w) { + const p = w?.parent ?? null; + if (!p) return "Draft · unsaved"; + const e = w.edits; + const n = !e ? "edits unknown" : e.count === 0 ? "no edits" : `${e.count} edit${e.count === 1 ? "" : "s"}`; + return `Draft · from ${p.id} · ${n}`; }