commit 34cebdc294a72932380fe3e8f55be50fd29e1b61 parent a8d2357c34b82498b866e64dfa909d07457ee103 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Mon, 9 Nov 2026 17:38:20 -0500 umtool: Play plays the draft; a version plays read-only with Open in draft; Save version on the head (L3 S3) The working draft is what plays: playViewWith drops the "latest take by default" branch -- no take is the project's manifest, where every edit lands. The head reads "Draft · from v5 · 3 edits" / "Draft · unsaved" (workingCut draftLine), the switch is Draft then the versions. `?take=X` plays X's frozen manifest read-only: no reorder, Reject or Add a clip on it, an **Open in draft** button, **Watch render** when it has an mp4, and Edit this clip (E) goes to the new Open in draft page (/projects/<p>/takes/<t>/open) -- it asks ("Open v1 in draft? Your draft (2 edits since v2) is saved as v4 first.") and posts a plain form; the draft's own parent with no edits goes straight on (308) to the draft's bench. The primary row: ▶ Play the draft, Walk = the draft's first clip, and a new Save version (POST /api/report/takes/save; "no edits since v1: nothing to save" / "saved as v3"). Present names the draft or a version. L2's per-version "No intro" toggle, made right for frozen versions: off writes render.intro: null into the version's patch; on now DELETES the key (takeEdit.mjs editTakePatch, the take writer that can delete), so the version opens on its own base's intro (a legacy take: the draft's) with no stale copy. `umtool intro --take <t> --off|--on` is the same. e2e: draft-versions (Play, Open in draft, Save version), play-walk (the draft by default), play-take-edit (Edit on a version asks, then the DRAFT's bench: the manifest changes, take.json does not; the parent with no edits is a 308), play-cut (a saved version plays its frozen base; play-cut-fixture gains v1), phone-walk and intro-play updated. knobs.md: "The working draft and saved versions". Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
31 files changed, 675 insertions(+), 279 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/components/projects/OpenInDraftPage.tsx b/umtool/components/projects/OpenInDraftPage.tsx @@ -0,0 +1,103 @@ +import Link from "next/link"; +import { notFound, permanentRedirect } 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 } 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 <take> is the draft's +// parent with no edits since, there is nothing to copy: a 308 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; + if (working.parent?.id === take && edits === 0) permanentRedirect(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'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/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 @@ -17,6 +17,7 @@ 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"; @@ -76,6 +77,8 @@ export default async function ProjectView({ // `/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. + // `/projects/<project>/takes/<take>/open` -- open a saved version in the draft (it asks first, L3). + if (rest.length === 3 && rest[0] === "takes" && rest[2] === "open") return <OpenInDraftPage project={project} take={rest[1]} search={search} />; if (rest.length === 3 && rest[0] === "takes" && rest[2] === "walk") return <TakeWalkPage project={project} take={rest[1]} search={search} />; if (rest.length === 4 && rest[0] === "takes" && rest[2] === "clip") { if (!isTakeId(rest[1])) return notFound(); 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/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/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"; @@ -148,8 +149,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 +300,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 +317,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 +635,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 +700,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 +732,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 +742,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 +857,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 +1172,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 +1190,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’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’s manifest alone — no take’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 +1375,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 +1441,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/knobs.md b/umtool/docs/knobs.md @@ -591,35 +591,65 @@ 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). Opening the draft's own parent with no edits writes nothing — its + Open in draft page goes straight on (308) to the draft's bench. +- **The pick is not touched.** Neither saving nor opening moves or unpins the pick in `verdicts.json` (**Use this + take** still does). + ## 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 diff --git a/umtool/e2e/draft-versions.spec.ts b/umtool/e2e/draft-versions.spec.ts @@ -2,6 +2,7 @@ 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"; @@ -76,3 +77,49 @@ test("the CLI twin's contract: a stale token is refused, the draft untouched", a 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/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/intro-play.spec.ts b/umtool/e2e/intro-play.spec.ts @@ -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) }); @@ -124,7 +124,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 +132,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,57 +22,63 @@ 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(); - // An edge: the end +0.05 s (`.`), saved. - const save = bench.locator("[data-save-window]"); + // 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 -- 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 }) => { @@ -85,15 +90,18 @@ test("a reload of the take's bench from Play is the take's bench page: Back to t await expect(page).toHaveURL(new RegExp(`/play\\?take=${TAKE}&clip=t01c&at=0\\.50`)); }); -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 (308) 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(308); + 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/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 (308) 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/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/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] @@ -140,25 +143,32 @@ export async function playViewWith(project, { take = null, bare = false, postFor const base = await readManifest(project.dir); if (!base) return { error: "this project has no video.manifest.json" }; const working = await readWorkingCut(project.dir).catch(() => null); - const defaulted = !take && !bare && !!working?.latest; - if (defaulted) take = working.latest.id; + 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) { @@ -286,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/takeEdit.mjs b/umtool/lib/report/takeEdit.mjs @@ -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/takes.mjs b/umtool/lib/report/takes.mjs @@ -59,13 +59,20 @@ const str = (v) => (typeof v === "string" ? v.trim() : ""); * 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 } | null>} + * @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 }; + 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; } diff --git a/umtool/lib/report/versions.mjs b/umtool/lib/report/versions.mjs @@ -55,11 +55,13 @@ export class VersionRefused extends Error { export const readDraft = readDraftFile; /** - * Write takes/draft.json (tmp + rename). `from` null removes it. + * 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 }} d + * @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 }) { +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 }); @@ -67,7 +69,7 @@ export async function writeDraft(projectDir, { from, hash = null, at = 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() }; + 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); @@ -244,7 +246,8 @@ export async function openVersion(project, id, { token = null, now = new Date() 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"); - await writeDraft(project.dir, { from: id, hash: hashText(written), at: now.toISOString() }); + // 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). diff --git a/umtool/lib/report/versions.test.mjs b/umtool/lib/report/versions.test.mjs @@ -154,6 +154,12 @@ test("openVersion of a legacy take: a rendered one is the manifest it rendered; 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 }); } diff --git a/umtool/lib/report/workingCut.mjs b/umtool/lib/report/workingCut.mjs @@ -25,7 +25,9 @@ import { createHash } from "node:crypto"; import { readFile } from "node:fs/promises"; import path from "node:path"; -import { isWorkingTake, listTakes, readDraftFile, readVerdicts } 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); @@ -169,7 +171,15 @@ export async function readWorkingCut(projectDir, { manifestText = null } = {}) { let edits = null; const h = text !== null ? hashText(text) : null; if (h !== null && ((fromDraft && draft?.hash === h) || parentTake.baseHash === h)) edits = { count: 0, words: [], same: true }; - else if (text !== null) { + else if (text !== null && fromDraft && draft?.base && !(await hasFrozenBase(projectDir, parentTake.id))) { + // A legacy take opened by merging its patch: the edits since the open, against what it wrote. + try { + const d = cutDiff(draft.base, JSON.parse(text)); + edits = { count: d.count, words: d.words, same: d.count === 0 }; + } catch { + edits = null; + } + } else if (text !== null) { const { frozenManifestOf, resolveTakeManifest } = await import("./takeManifest.mjs"); const frozen = await frozenManifestOf(projectDir, parentTake.id); let now = null;