commit 52425e315c573c872ab4e787a9f6dcedff860e31 parent aeac3589de4cb655e5033069dc1f92ba6292f151 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Thu, 5 Nov 2026 05:04:50 -0500 Merge lane/ui-simplify: every umtool page leads with its next step -- Play one press from anywhere a cut or take is named (the head on every tab, each Cut row at its item, takes, the walk, Jobs, the Inbox, Recent cuts in the rail), + Add a clip as one flow (find in this cut's recordings, the archive or a pasted link; in/out from the cues; placed by date; fetched through the editor at once; from the head, the Cut tab, Play at the play head or a take only), the rest in remembered Options and Advanced panels; buttons for what only the CLI could do (import items into a take, lint, draft from a take, take-only edits, pronunciation and voices, redaction and the slur filter, add posts, re-join/re-time/raise caps, refetch, output files with local paths); every control from before kept (CONTROL-DIFF: 2807 in place, 34 folded, 0 removed, 430 new) (operator, 5 Nov: "Focus on the happy path and have options/advanced panels for everything else, keeping all current features exposed and adding missing ones"; "adding new clips to a cut really sucks, sometimes going to the play screen for a cut is hard to do without just entering the /play page") Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
71 files changed, 2951 insertions(+), 227 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **umtool: Play is one press from anywhere, a clip is added without its spec, and every page leads with its next step.** A cut or a take named anywhere now carries a Play that opens the newest take (at the item when there is one): the project's head on every tab (with Walk, + Add a clip and the status `latest <take> · <length> · rendered <day> · <n> open notes`), every Cut tab row, every take card, the take walk, `/jobs`' renders (with the mp4's local path and Copy), the Inbox's cards and the rail's Recent cuts; a cut of posts showed no Play at all. **+ Add a clip** finds the words in the recordings the cut draws on (or the archive, or a pasted link with a time), sets the in and out on the moment's cues, places it after a row (by date when the cut is in date order) and fetches its window through the editor; from the Cut tab, from Play at the playhead and from a take ("to this take only": `umtool timeline <p> --take <t> insert <spec> --after <id>`). **+ Add posts** is `posts reel` with a preview; **Reads and voices** edits the pronunciation lexicon and the voice map with Try it; also the redacted words, the slur filter and the cut's narration mix, and queues the cut-wide passes (every script, every missing read, context from captures, conversations) as queue steps. A take has **Check before render** (`lint --take`), **Check the joins**, **New draft from this take** and **Add items from another project** (with a preview); New take has **Save as a draft**; the post bench's **edits go to: take <t> only** writes the take's patch (`--in-take`) and its **Re-join the read** re-times, drops parts or URLs and raises the caps; the clip bench can **Fetch this window again**; the reel cut takes a finale, a file name and a dry run; the Deliver tab opens on **Output files**, absolute paths with Copy. The rest of each page sits under one **Options** / **Advanced** disclosure, its open state remembered per viewer; nothing was removed. - **A report video renders 9:16 too: vertical shorts of clips, post reads and side posts, in one format.** `render.format: "vertical"` builds the same timeline 1080x1920 at its fps (no deck, header, QR or intro), and `umtool vertical <p> --take <t> --reel <r>` (or `umtool trailer … --vertical`) builds a short of a take's items without touching the cut: each clip cut again in its layout -- full (a 9:16 crop, big captions lit word by word, a source tag), framed (the whole picture in the middle third over a blurred enlargement, a hook from the cut's own titles above) or quote (the picture in the top 40 %, the line set large below, cited) -- and each post item drawn again in a portrait box (card, stack or media-first). A clip can carry a SIDE POST (`umtool set <p> <clip> side.item=… side.from=… side.to=…`): a post shown beside it while it plays, never read, the clip's sound running -- split or overlay in a vertical cut, a panel sliding in at the side in 16:9. Text keeps out of the platforms' buttons (top 8 %, bottom 20 %, right 12 %, knobs), the short is brought to -14 LUFS and said when it runs over 60 s; `--reframe` recomposes a finished 16:9 master instead (the footage box, the post's card over its attachment, the deck's date line), the cheapest for any cut. A clip's crop and layout are `umtool set … vertical.crop=… vertical.layout=…`; no `format` key and the 16:9 render is byte for byte what it was. umtool/docs/cli.md "Make a vertical short", knobs.md "Vertical shorts". - **A take can carry items of other projects, and be edited without touching the project.** A cut assembled as a take of one project from the items of several (the mid cut: a take of the full cut, items from the full cut and a staging project) needed a script to clone the entries, hard-link their narration in and copy each re-read into the take's patch by hand. `umtool take <p> --id <t> --import-item <project>:<item>[,<item>…] [--after|--before <entry>]` now clones the items with their narration and its pick, hard-links every file they name into the take's project (another file already at a path: linked under `imports/<source>/` instead, never written over), places them, and is safe to run again (`updated`, or `unchanged` with no write). `posts set-item`, `roles`, `narrate`, `reread` and `fx` take `--in-take <take>`: the same edit lands in the take's patch with an undo point of the take's own (`umtool timeline <p> --take <t> undo`), the project's manifest untouched. `umtool take … --draft --from <take>` starts a draft from another take's patch, and `umtool lint <p> [--take <t>]` runs the build's lint on a take and checks that every file its items name is in the project. `posts narrate --thread` finds the editor's WORKER_TOKEN in `editor/.env` as umtool's other editor calls do. A cut whose posts carry the progress bar (`posts progress auto`) no longer fails its lint (`render.posts.progress is not a knob`), nor does one with the clock, panel, join, link-visit or branch-map knobs. - **Every umtool take render records itself, and umtool runs a queue of steps in order.** A render that died at exit 1 behind a filtered shell chain left no trace (`take.json` kept `builtAt: null`, no log), and the next chain read the chain's own DONE as success. Now every render, whoever starts it, writes `takes/<id>/render.json` (running, waiting at the heavy slot, done, failed or cancelled; its stage; on failure the first error line and the log's last 40 lines; on done the mp4 and its seconds) and the full `takes/<id>/render.log`; done needs exit 0 and a non-empty mp4, and a record whose process is gone reads failed. `umtool take status <p> --id <t>` exits 0 done, 3 still going, 1 failed. `umtool queue add [--after <qid>] -- <command…>` queues a umtool command that the umtool app runs, one step at a time, surviving the session, a restart or a ship: a failure blocks what waits on it, `retry` puts both back, a step that was running when the app died is failed with its log and never re-run. `umtool queue ls|status|wait|log|cancel|retry` and `umtool jobs` poll them; `/jobs` (the rail's *Running*) and the Takes page show the queue and the records, with the error and the log. umtool/docs/cli.md, "Queue and poll instead of scripting". diff --git a/umtool/app/api/report/add-posts/route.ts b/umtool/app/api/report/add-posts/route.ts @@ -0,0 +1,51 @@ +import { projectRef } from "@/lib/projects"; +import { refuseCaller } from "@/lib/report/caller"; +import { StaleToken, StructureRefused } from "@/lib/report/manifest.mjs"; +import { postsReel } from "@/lib/report/postReel.mjs"; + +export const dynamic = "force-dynamic"; + +// ADD POSTS to a cut of posts (lane/ui-simplify, 5 Nov; terminal-only before: `umtool posts reel`): the +// channel archive's posts the cut does not play yet, as post items, in one write (postReel.mjs postsReel, +// the CLI's own). `dryRun` answers what it would add. +// +// POST { project, channels: [slug…], own?, since?, until?, withMedia?, after?, limit?, dryRun? } +// -> { added, selected, already, entries: [{ id, date, text, … }], dryRun } +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/add-posts"); + if (refused) return refused; + const b = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!b) return Response.json({ error: "bad json" }, { status: 400 }); + const project = await projectRef(String(b.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const channels = Array.isArray(b.channels) ? b.channels.filter((c): c is string => typeof c === "string" && c.length > 0) : []; + if (!channels.length) return Response.json({ error: "name a channel whose posts to add" }, { status: 400 }); + const str = (k: string) => (typeof b[k] === "string" && b[k] ? (b[k] as string) : null); + const limit = Number.isInteger(b.limit) && (b.limit as number) > 0 ? (b.limit as number) : null; + try { + const r = await postsReel(project, { + channels, + since: str("since"), + until: str("until"), + own: b.own === true, + withMedia: b.withMedia === true, + replies: "include", + order: "chrono", + limit, + after: str("after"), + dryRun: b.dryRun === true, + }); + const entries = ((r.entries ?? []) as Record<string, unknown>[]).map((e) => ({ + id: e.id, + date: typeof e.date === "string" ? e.date.slice(0, 10) : null, + handle: e.handle ?? null, + text: String(e.text ?? "").replace(/\s+/g, " ").slice(0, 140), + media: Array.isArray(e.media) ? e.media.length : 0, + })); + return Response.json({ ok: true, added: r.added, selected: r.selected, already: r.already, dryRun: !!r.dryRun, entries }, { headers: { "cache-control": "no-store" } }); + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); + if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} diff --git a/umtool/app/api/report/find-moment/route.ts b/umtool/app/api/report/find-moment/route.ts @@ -0,0 +1,47 @@ +import { resolveReport } from "@/lib/report/serve.mjs"; +import { cuesForSource } from "@/lib/projects/report.mjs"; + +export const dynamic = "force-dynamic"; + +// ADD A CLIP's "find the moment" in the recordings the cut already draws on +// (lane/ui-simplify, 5 Nov): every word of `q` (any order, any case) in one +// cue of a recording a clip of the cut is on, read from the cue files the cut +// reads (cuesForSource, lib/projects/report.mjs), never the network. The +// archive-wide search is /api/research/search; a pasted link needs neither. +// +// GET ?project&q -> { recordings, hits: [{ channel, video, title, date, t, end, text }] } (at most 80) +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const words = (url.searchParams.get("q") ?? "") + .toLowerCase() + .split(/\s+/) + .map((w) => w.replace(/[^\p{L}\p{N}'-]/gu, "")) + .filter((w) => w.length > 0); + if (!words.length) return Response.json({ error: "type a word or two to find" }, { status: 400 }); + type Rec = { channel: string | null; video: string; title: string | null; date: string | null }; + const recs = new Map<string, Rec>(); + for (const e of (r.manifest.timeline ?? []) as Record<string, unknown>[]) { + if (e?.type !== "clip" || typeof e.video !== "string") continue; + const channel = typeof e.channel === "string" && e.channel ? e.channel : null; + const key = `${channel ?? ""}/${e.video}`; + if (recs.has(key)) continue; + const onscreen = (e.onscreen ?? null) as { title?: unknown } | null; + const title = typeof e.streamTitle === "string" ? e.streamTitle : typeof onscreen?.title === "string" ? onscreen.title : typeof e.title === "string" ? e.title : null; + recs.set(key, { channel, video: e.video, title, date: typeof e.date === "string" ? e.date.slice(0, 10) : null }); + } + const hits: (Rec & { t: number; end: number; text: string })[] = []; + for (const rec of recs.values()) { + if (hits.length >= 80) break; + const got = await cuesForSource(r.project.dir, { video: rec.video, channel: rec.channel }, 0, Number.MAX_SAFE_INTEGER).catch(() => null); + for (const c of got?.cues ?? []) { + const text = String(c.text ?? "").toLowerCase(); + if (words.every((w) => text.includes(w))) { + hits.push({ ...rec, t: c.start, end: c.end, text: String(c.text ?? "").replace(/\s+/g, " ").trim() }); + if (hits.length >= 80) break; + } + } + } + return Response.json({ recordings: recs.size, hits }, { headers: { "cache-control": "no-store" } }); +} diff --git a/umtool/app/api/report/post-combo/route.ts b/umtool/app/api/report/post-combo/route.ts @@ -7,6 +7,8 @@ import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, StructureRefused, updatePostCombo, updatePostComboRender } from "@/lib/report/manifest.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; import { refuseCaller } from "@/lib/report/caller"; +import { withTakeScope } from "@/lib/report/takeScope.mjs"; +import { isTakeId } from "@/lib/report/takes.mjs"; export const dynamic = "force-dynamic"; @@ -41,7 +43,27 @@ export async function GET(request: Request) { } } +// "Edit this take only" (lane/ui-simplify): a body naming `inTake` runs the same write under takeScope.mjs +// withTakeScope -- the take's manifest read, the write into its patch, the project's manifest untouched (the +// CLI's `--in-take`). The token is then the take's (take.json's), so a client's project token is not checked. export async function POST(request: Request) { + const text = await request.text(); + let parsed: Record<string, unknown> | null = null; + try { + parsed = JSON.parse(text); + } catch { + parsed = null; + } + const take = parsed && typeof parsed.inTake === "string" && parsed.inTake ? parsed.inTake : null; + const again = (body: string) => new Request(request.url, { method: "POST", headers: request.headers, body }); + if (!take || !parsed) return postHere(again(text)); + if (!isTakeId(take)) return Response.json({ error: "inTake must be a take id" }, { status: 400 }); + const rr = await resolveReport(String(parsed.project ?? "")); + if ("error" in rr) return Response.json({ error: rr.error }, { status: rr.status }); + return withTakeScope(rr.project.dir, take, () => postHere(again(JSON.stringify({ ...parsed, token: null })))); +} + +async function postHere(request: Request) { const refused = refuseCaller(request, "/api/report/post-combo"); if (refused) return refused; let body: Record<string, unknown>; diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts @@ -18,6 +18,8 @@ import { recognizedOf, takeWordSources, wordsFileOf } from "@/lib/report/postFxC import { rangeResponse, resolveReport } from "@/lib/report/serve.mjs"; import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs"; import { refuseCaller } from "@/lib/report/caller"; +import { withTakeScope } from "@/lib/report/takeScope.mjs"; +import { isTakeId } from "@/lib/report/takes.mjs"; import { projectRedaction } from "@/lib/report/postRedaction.mjs"; export const dynamic = "force-dynamic"; @@ -260,7 +262,27 @@ export async function GET(request: Request) { return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", ...noStore } }); } +// "Edit this take only" (lane/ui-simplify): a body naming `inTake` runs the same write under takeScope.mjs +// withTakeScope -- the take's manifest read, the write into its patch, the project's manifest untouched (the +// CLI's `--in-take`). The token is then the take's (take.json's), so a client's project token is not checked. export async function POST(request: Request) { + const text = await request.text(); + let parsed: Record<string, unknown> | null = null; + try { + parsed = JSON.parse(text); + } catch { + parsed = null; + } + const take = parsed && typeof parsed.inTake === "string" && parsed.inTake ? parsed.inTake : null; + const again = (body: string) => new Request(request.url, { method: "POST", headers: request.headers, body }); + if (!take || !parsed) return postHere(again(text)); + if (!isTakeId(take)) return Response.json({ error: "inTake must be a take id" }, { status: 400 }); + const rr = await resolveReport(String(parsed.project ?? "")); + if ("error" in rr) return Response.json({ error: rr.error }, { status: rr.status }); + return withTakeScope(rr.project.dir, take, () => postHere(again(JSON.stringify({ ...parsed, token: null })))); +} + +async function postHere(request: Request) { const refused = refuseCaller(request, "/api/report/post-item"); if (refused) return refused; let body: Record<string, unknown>; diff --git a/umtool/app/api/report/pronunciation/route.ts b/umtool/app/api/report/pronunciation/route.ts @@ -0,0 +1,114 @@ +import { projectRef } from "@/lib/projects"; +import { refuseCaller } from "@/lib/report/caller"; +import { sayCommand, voicesCommand } from "@/lib/report/postSay.mjs"; +import { postsCommand } from "@/lib/report/postsCli.mjs"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { addStep } from "@/lib/queue/store.mjs"; +import { kickQueue, queueDir } from "@/lib/queue/runner"; + +export const dynamic = "force-dynamic"; + +// A POST PROJECT's PRONUNCIATION LEXICON and VOICE MAP in the app (lane/ui-simplify, 5 Nov; terminal-only +// before: `umtool posts say` / `umtool posts voices`). The CLI's own commands (lib/report/postSay.mjs), run +// here with --json -- the files' one writer each (narration/lexicon.json, narration/voices.json). +// +// GET ?project -> { lexicon: say ls, voices: voices ls, stale: say stale, redact: posts redact ls, +// slurs: posts slurs ls } (the redaction and the slur filter: their own commands) +// POST { project, op: "say-add", word, say, case?, item?, note? } posts say <p> add <word> "<say>" [--case] [--item] [--note] +// { project, op: "say-remove", n } posts say <p> remove <n> (1-based, as ls lists it) +// { project, op: "say-try", text, item? } posts say <p> try "<text>" +// { project, op: "voices-set", handle, voice } posts voices <p> set <handle|*> <voice> +// { project, op: "voices-remove", handle } posts voices <p> remove <handle|*> +// { project, op: "mix-cut", key, value } posts narrate <p> --cut <key>=<value> (render.postNarration) +// { project, op: "redact-add", term, substring?, note? } posts redact <p> add "<term>" [--substring] [--note] +// { project, op: "redact-remove", n } posts redact <p> remove <n> +// { project, op: "slurs", verb: on|off|level|visual|voice|add|except|remove, value? } posts slurs <p> <verb> [value] +// { project, op: "queue-narrate", what: "scripts" | "takes" | "context" | "threads" } QUEUED (lib/queue/, /jobs): posts narrate <p> --all +// --draft-scripts | --all --take -- long, so a step of +// the queue, never a request held open; the argv is built +// here, never taken from the page +type Flags = Map<string, string | true>; + +async function run(fn: (out: (s: string) => void) => Promise<number>) { + const out: string[] = []; + try { + const exit = await fn((s) => out.push(s)); + return { exit, json: JSON.parse(out.join("\n") || "null") as Record<string, unknown> | null }; + } catch (e) { + return { exit: 1, json: null, error: e instanceof Error ? e.message : String(e) }; + } +} +const say = (project: NonNullable<Awaited<ReturnType<typeof projectRef>>>, rest: string[], flags: Flags = new Map()) => + run((out) => sayCommand(project, rest, { flags, str: (k: string) => String(flags.get(k) ?? ""), json: true, out })); +// `umtool posts <verb> <p> …` in this process (postsCli.mjs postsCommand), --json. +const posts = async (args: string[]) => { + const said: string[] = []; + const r: { exit: number; json: Record<string, unknown> | null; error?: string } = await run((out) => postsCommand([...args, "--json"], { out, err: (x: string) => said.push(x) })); + if (r.exit !== 0 && !r.error) r.error = said.join("\n") || `posts ${args[0]} refused`; + return r; +}; +const voices = (project: NonNullable<Awaited<ReturnType<typeof projectRef>>>, rest: string[]) => run((out) => voicesCommand(project, rest, { json: true, out })); + +export async function GET(request: Request) { + const project = await projectRef(new URL(request.url).searchParams.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const manifest = (await readManifest(project.dir).catch(() => null)) as { render?: { postNarration?: unknown } } | null; + const [lexicon, voiceMap, stale, redact, slurs] = await Promise.all([ + say(project, ["ls"]), + voices(project, ["ls"]), + say(project, ["stale"]), + posts(["redact", project.id, "ls"]), + posts(["slurs", project.id, "ls"]), + ]); + return Response.json({ lexicon, voices: voiceMap, stale, redact, slurs, mix: manifest?.render?.postNarration ?? {} }, { headers: { "cache-control": "no-store" } }); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/pronunciation"); + if (refused) return refused; + const b = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!b) return Response.json({ error: "bad json" }, { status: 400 }); + const project = await projectRef(String(b.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const s = (k: string) => (typeof b[k] === "string" ? (b[k] as string) : ""); + const flags: Flags = new Map(); + if (s("item")) flags.set("--item", s("item")); + let r; + if (b.op === "say-add") { + if (b.case === true) flags.set("--case", true); + if (s("note")) flags.set("--note", s("note")); + r = await say(project, ["add", s("word"), s("say")], flags); + } else if (b.op === "say-remove") r = await say(project, ["remove", String(Number(b.n))], flags); + else if (b.op === "say-try") r = await say(project, ["try", s("text")], flags); + else if (b.op === "voices-set") r = await voices(project, ["set", s("handle"), s("voice")]); + else if (b.op === "voices-remove") r = await voices(project, ["remove", s("handle")]); + // The cut's narration mix (posts narrate <p> --cut k=v): one knob a press; the CLI's own words refuse a wrong one. + else if (b.op === "mix-cut") r = await posts(["narrate", project.id, "--cut", `${s("key")}=${s("value")}`]); + else if (b.op === "redact-add") r = await posts(["redact", project.id, "add", s("term"), ...(b.substring === true ? ["--substring"] : []), ...(s("note") ? ["--note", s("note")] : [])]); + else if (b.op === "redact-remove") r = await posts(["redact", project.id, "remove", String(Number(b.n))]); + else if (b.op === "slurs") { + const verb = s("verb"); + if (!["on", "off", "level", "visual", "voice", "add", "except", "remove"].includes(verb)) return Response.json({ error: "slurs: on, off, level, visual, voice, add, except or remove" }, { status: 400 }); + r = await posts(["slurs", project.id, verb, ...(verb === "on" || verb === "off" ? [] : [s("value")])]); + } else if (b.op === "queue-narrate") { + // Also the cut-wide post passes that are terminal-only otherwise: fill each item's context from its capture + // (posts context), gather each conversation together (timeline threads --write). + const what = b.what === "takes" ? "takes" : b.what === "context" ? "context" : b.what === "threads" ? "threads" : "scripts"; + const argv = + what === "context" ? ["posts", "context", project.id] : what === "threads" ? ["timeline", project.id, "threads", "--write"] : ["posts", "narrate", project.id, "--all", what === "takes" ? "--take" : "--draft-scripts"]; + const words = { scripts: "draft every post script", takes: "read every missing post take", context: "fill every post's context from its capture", threads: "gather each conversation" }[what]; + try { + const step = (await addStep(queueDir(), { + argv, + label: `${words} of ${project.id}`, + target: { project: project.id, take: null }, + by: "the umtool app (Reads and voices)", + })) as { qid: string }; + kickQueue(); + return Response.json({ exit: 0, json: { queued: step.qid } }, { headers: { "cache-control": "no-store" } }); + } catch (e) { + return Response.json({ exit: 1, json: null, error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } + } else return Response.json({ error: "op must be say-add, say-remove, say-try, voices-set, voices-remove or queue-narrate" }, { status: 400 }); + return Response.json(r, { status: r.exit === 0 ? 200 : 400, headers: { "cache-control": "no-store" } }); +} diff --git a/umtool/app/api/report/reel/route.ts b/umtool/app/api/report/reel/route.ts @@ -17,7 +17,7 @@ export const dynamic = "force-dynamic"; // takes with masters, the reels, and the // cut job running for this project, if any // GET ?job=<id>[&since=&sinceEvent=] that job, as the take jobs show one -// POST { project, reel, take } cut it: `umtool trailer <p> --reel <r> +// POST { project, reel, take, finale?, out?, dryRun? } cut it (finale: the master's last S s; out: a NAME; dryRun): `umtool trailer <p> --reel <r> // --take <t>` on the runner (one job at a // time; the CLI takes the heavy slot) // ?cancel=<job> stop it @@ -71,7 +71,13 @@ export async function POST(request: Request) { if (!view.beats && !view.introAsked) return Response.json({ error: `the reel ${reel} has no beats yet` }, { status: 400 }); const running = runningJob(); if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 }); - const plan = reelCutSteps(r.project, reel, take, { umtoolDir: UMTOOL_DIR }); + const finale = Number(body.finale); + const plan = reelCutSteps(r.project, reel, take, { + umtoolDir: UMTOOL_DIR, + finale: Number.isFinite(finale) && finale > 0 && finale <= 60 ? finale : null, + out: typeof body.out === "string" && body.out ? body.out : null, + dryRun: body.dryRun === true, + }); try { const job = startJob(plan.kind, plan.steps, { project: r.project.id }); return Response.json({ ok: true, job: jobView(job) }, { headers: noStore }); diff --git a/umtool/app/api/report/takes/timeline/route.ts b/umtool/app/api/report/takes/timeline/route.ts @@ -1,7 +1,8 @@ import { projectRef } from "@/lib/projects"; import { refuseCaller } from "@/lib/report/caller"; import { StaleToken, StructureRefused } from "@/lib/report/manifest.mjs"; -import { moveTakeEntry, removeTakeEntry, undoTakeEdit } from "@/lib/report/takeEdit.mjs"; +import { insertTakeEntry, moveTakeEntry, removeTakeEntry, takeToken, undoTakeEdit } from "@/lib/report/takeEdit.mjs"; +import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs"; import { isTakeId } from "@/lib/report/takes.mjs"; export const dynamic = "force-dynamic"; @@ -15,8 +16,36 @@ export const dynamic = "force-dynamic"; // move { id, toIndex, at? } toIndex is the index AFTER the move // remove { id, at? } // undo {} the take's newest edit taken back +// insert { afterId: id | null, entry: "<channel>/<video>@<start>-<end>" | { type, … } } "add to this take only" +// +// GET ?project&take -> { token, timeline: [{ id, type, date, video, channel, words }] }: the take's resolved +// timeline, as the project's GET /api/report/timeline lists it (Add a clip's place picker, on a take). // // A stale token is a 409; a structure the build would refuse is a 400 with its sentences. +export async function GET(request: Request) { + const url = new URL(request.url); + const take = url.searchParams.get("take"); + if (!isTakeId(take)) return Response.json({ error: "take must be a take id" }, { status: 400 }); + const project = await projectRef(url.searchParams.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + try { + const { manifest } = await resolveTakeManifest(project.dir, take); + const str = (v: unknown) => (typeof v === "string" && v ? v : null); + const timeline = ((manifest.timeline ?? []) as Record<string, unknown>[]).map((e) => ({ + id: String(e.id), + type: String(e.type ?? "entry"), + date: str(e.date)?.slice(0, 10) ?? null, + video: str(e.video), + channel: str(e.channel), + words: (str(e.quote) ?? str(e.text) ?? str(e.title) ?? "").replace(/\s+/g, " ").slice(0, 60), + })); + return Response.json({ take, token: await takeToken(project.dir, take), timeline }, { headers: { "cache-control": "no-store" } }); + } catch (e) { + const message = e instanceof Error ? e.message : String(e); + return Response.json({ error: message }, { status: /^no take /.test(message) ? 404 : 400 }); + } +} + export async function POST(request: Request) { const refused = refuseCaller(request, "/api/report/takes/timeline"); if (refused) return refused; @@ -39,8 +68,11 @@ export async function POST(request: Request) { r = await removeTakeEntry(project.dir, take, id, { token, at }); } else if (body.op === "undo") { r = await undoTakeEdit(project.dir, take, { token }); + } else if (body.op === "insert") { + if (!body.entry) return Response.json({ error: "insert needs an entry" }, { status: 400 }); + r = await insertTakeEntry(project.dir, take, typeof body.afterId === "string" && body.afterId ? body.afterId : null, body.entry, { token, at }); } else { - return Response.json({ error: "op must be move, remove or undo" }, { status: 400 }); + return Response.json({ error: "op must be move, remove, undo or insert" }, { status: 400 }); } return Response.json({ ok: true, op: body.op, take, ...r }, { headers: { "cache-control": "no-store" } }); } catch (e) { diff --git a/umtool/app/api/report/takes/tools/route.ts b/umtool/app/api/report/takes/tools/route.ts @@ -0,0 +1,123 @@ +import { projectRef } from "@/lib/projects"; +import { refuseCaller } from "@/lib/report/caller"; +import { lintCommand } from "@/lib/report/lintCli.mjs"; +import { takeCommand } from "@/lib/report/takeCli.mjs"; +import { isTakeId, listTakes } from "@/lib/report/takes.mjs"; +import { REPORTS_ROOT } from "@/lib/paths"; +import { addStep } from "@/lib/queue/store.mjs"; +import { kickQueue, queueDir } from "@/lib/queue/runner"; + +export const dynamic = "force-dynamic"; + +// THE TAKE TOOLS a person had only from a terminal (slice C of "the apps do the +// work", 4 Nov), on a take's card and its walk (lane/ui-simplify, 5 Nov). Each +// runs the CLI's own function in this process -- never a shelled-out CLI -- with +// --json, and answers with what it printed: +// +// POST { project, take?, op: "lint" } umtool lint <p> [--take <t>] --json +// -> { exit, report: { ok, errors[], warnings[], entries } } +// POST { project, take, op: "draft-from", id?, label? } umtool take <p> --id <id> --draft --from <take> --json +// -> { exit, id, report } (id: the next free `<take>-d<n>` when none is given) +// POST { project, take, op: "import", refs: "<project>:<item>[,…]", after?, before?, dryRun? } +// umtool take <p> --id <take> --import-item … [--dry-run] --json +// -> { exit, report } +// POST { project, op: "draft-new", label, group?, style?, patch?, window? } +// umtool take <p> --id <slug of label> --label L --draft +// -> { exit, id, report } [--group G] [--style S] [--patch-json P] [--full | --at A --dur D] +// POST { project, take?, op: "queue-refetch", clip } QUEUED: umtool fetch <p> --refetch <clip> [--take <t>] (its +// -> { exit: 0, queued: <qid> } cached windows evicted through the editor, then fetched again) +// POST { project, take, op: "queue-check-joins" } QUEUED: umtool check-joins <p> --take <t> (the measured +// -> { exit: 0, queued: <qid> } SSIM over the master is long: a queue step, its table in +// the step's log on Jobs) +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/takes/tools"); + if (refused) return refused; + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 }); + const project = await projectRef(String(body.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const take = body.take === undefined || body.take === null || body.take === "" ? null : body.take; + if (take !== null && !isTakeId(take)) return Response.json({ error: "take must be a take id" }, { status: 400 }); + const out: string[] = []; + const err: string[] = []; + const io = { reportsRoot: REPORTS_ROOT, log: (s: string) => out.push(s), err: (s: string) => err.push(s) }; + const answer = (exit: number, extra: Record<string, unknown> = {}) => { + let report: unknown = null; + try { + report = out.length ? JSON.parse(out.join("\n")) : null; + } catch { + report = null; + } + const status = exit === 2 ? 400 : 200; + return Response.json({ exit, report, said: [...err, ...(report === null ? out : [])].join("\n"), ...extra }, { status, headers: { "cache-control": "no-store" } }); + }; + try { + if (body.op === "lint") { + const exit = await lintCommand([project.id, ...(take ? ["--take", take] : []), "--json"], io); + return answer(exit); + } + if (body.op === "draft-new") { + // A draft from the New take form: recorded, nothing rendered (`umtool take … --draft`), walked before it renders. + const label = typeof body.label === "string" ? body.label.replace(/\s+/g, " ").trim() : ""; + if (!label) return Response.json({ error: "a draft needs a label" }, { status: 400 }); + const have = new Set(((await listTakes(project.dir)).takes as { id: string }[]).map((t) => t.id)); + const base = label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "draft"; + let id = base; + for (let n = 2; have.has(id) && n < 1000; n++) id = `${base}-${n}`; + if (!isTakeId(id)) return Response.json({ error: `"${id}" is not a take id` }, { status: 400 }); + const w = body.window as { at?: number; dur?: number } | "full" | undefined; + const args = [project.id, "--id", id, "--label", label, "--draft", "--json"]; + if (typeof body.group === "string" && body.group) args.push("--group", body.group); + if (typeof body.style === "string" && body.style) args.push("--style", body.style); + if (body.patch && typeof body.patch === "object") args.push("--patch-json", JSON.stringify(body.patch)); + if (w === "full") args.push("--full"); + else if (w && typeof w === "object" && Number.isFinite(w.at) && Number.isFinite(w.dur)) args.push("--at", String(w.at), "--dur", String(w.dur)); + const exit = await takeCommand(args, io); + return answer(exit, { id }); + } + if (body.op === "queue-refetch") { + const clip = typeof body.clip === "string" ? body.clip : ""; + if (!/^[A-Za-z0-9._-]{1,80}$/.test(clip)) return Response.json({ error: "queue-refetch needs a clip id" }, { status: 400 }); + const step = (await addStep(queueDir(), { + argv: ["fetch", project.id, "--refetch", clip, ...(take ? ["--take", take] : [])], + label: `fetch ${clip}'s window again (${project.id}${take ? ` take ${take}` : ""})`, + target: { project: project.id, take }, + by: "the umtool app (the clip bench)", + })) as { qid: string }; + kickQueue(); + return Response.json({ exit: 0, queued: step.qid }, { headers: { "cache-control": "no-store" } }); + } + if (!take) return Response.json({ error: `${String(body.op)} needs a take` }, { status: 400 }); + if (body.op === "draft-from") { + let id = typeof body.id === "string" && body.id ? body.id : null; + if (!id) { + const have = new Set(((await listTakes(project.dir)).takes as { id: string }[]).map((t) => t.id)); + for (let n = 1; n < 1000 && !id; n++) if (!have.has(`${take}-d${n}`)) id = `${take}-d${n}`; + } + if (!id || !isTakeId(id)) return Response.json({ error: "no free draft id" }, { status: 400 }); + const label = typeof body.label === "string" && body.label.trim() ? ["--label", body.label.trim()] : []; + const exit = await takeCommand([project.id, "--id", id, "--draft", "--from", take, ...label, "--json"], io); + return answer(exit, { id }); + } + if (body.op === "queue-check-joins") { + const step = (await addStep(queueDir(), { + argv: ["check-joins", project.id, "--take", take], + label: `check the joins of ${project.id} take ${take}`, + target: { project: project.id, take }, + by: "the umtool app (take tools)", + })) as { qid: string }; + kickQueue(); + return Response.json({ exit: 0, queued: step.qid }, { headers: { "cache-control": "no-store" } }); + } + if (body.op === "import") { + const refs = typeof body.refs === "string" ? body.refs.trim() : ""; + if (!refs) return Response.json({ error: "import needs <project>:<item>[,<item>…]" }, { status: 400 }); + const place = typeof body.after === "string" && body.after ? ["--after", body.after] : typeof body.before === "string" && body.before ? ["--before", body.before] : []; + const exit = await takeCommand([project.id, "--id", take, ...refs.split(/\s+/).flatMap((r) => ["--import-item", r]), ...place, ...(body.dryRun ? ["--dry-run"] : []), "--json"], io); + return answer(exit); + } + return Response.json({ error: "op must be lint, draft-from, draft-new, import or queue-check-joins" }, { status: 400 }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500 }); + } +} diff --git a/umtool/app/api/report/timeline/route.ts b/umtool/app/api/report/timeline/route.ts @@ -86,7 +86,16 @@ export async function GET(request: Request) { const r = await resolveReport(url.searchParams.get("project") ?? ""); if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); const entries = (r.manifest.timeline ?? []) as Record<string, unknown>[]; - const timeline = entries.map((e) => ({ id: String(e.id), type: String(e.type ?? "entry") })); + // Each entry's day, recording and first words too: Add a clip's place picker (after <row>, the date order). + const str = (v: unknown) => (typeof v === "string" && v ? v : null); + const timeline = entries.map((e) => ({ + id: String(e.id), + type: String(e.type ?? "entry"), + date: str(e.date)?.slice(0, 10) ?? null, + video: str(e.video), + channel: str(e.channel), + words: (str(e.quote) ?? str(e.text) ?? str(e.title) ?? str(e.heading) ?? "").replace(/\s+/g, " ").slice(0, 60), + })); // What the structure editors edit: each teaser as written, the posts, and // the fact-check block with every default filled (the form's placeholders). const teasers = entries diff --git a/umtool/app/page.tsx b/umtool/app/page.tsx @@ -12,6 +12,7 @@ import { headlineNote, inboxHeadline } from "@/lib/inbox/headline.mjs"; import { whatOf } from "@/lib/inbox/what.mjs"; import type { Decision } from "@/lib/decisions"; import type { LifecycleState } from "@/lib/lifecycle"; +import { playHrefOfPiece } from "@/components/projects/playable"; export const dynamic = "force-dynamic"; @@ -121,6 +122,10 @@ export default async function Inbox({ extra.push({ id: "hidden", label: "Hidden", note: "on parked and done pieces", collapsed: false, decisions: parkedN, hidden: 0, cards }); } + // ▶ Play beside every card of a report video (at its note, for a note card): lane/ui-simplify. + const all = [...groups, ...extra]; + await Promise.all(all.flatMap((g) => g.cards.map(async (c) => (c.play = await playHrefOfPiece(c.piece, c.action.href))))); + return ( <div className="flex h-full flex-col"> <AppShell @@ -177,7 +182,7 @@ export default async function Inbox({ </span> </div> - <InboxList groups={[...groups, ...extra]} /> + <InboxList groups={all} /> </main> <UndoBar /> </div> diff --git a/umtool/components/inbox/InboxList.tsx b/umtool/components/inbox/InboxList.tsx @@ -43,6 +43,8 @@ export type InboxCard = { muted?: boolean; /** Mark done is the action (POST), not a link. */ finish?: boolean; + /** A report video's Play address (at the card's note), when the piece has one. */ + play?: string | null; }; export type InboxGroup = { @@ -149,6 +151,11 @@ function Card({ card: c }: { card: InboxCard }) { {c.action.label} </Link> )} + {c.play && ( + <Link href={c.play} prefetch={false} data-play-link="note" aria-label={`play ${c.title}`} title="play the newest take (at this note)" className="ml-1 text-[12px] text-signal-text hover:underline"> + ▶ + </Link> + )} </span> <LitActions className="ml-auto gap-0.5 sm:ml-0 max-md:hidden"> {!parked && !c.muted && c.piece && ( diff --git a/umtool/components/piece/PieceFrame.tsx b/umtool/components/piece/PieceFrame.tsx @@ -51,6 +51,7 @@ export default function PieceFrame({ meta, head, more, + primary, schedule, edition, children, @@ -74,6 +75,8 @@ export default function PieceFrame({ note?: React.ReactNode; /** The ⋯ menu's items (Delete project …). */ more?: React.ReactNode; + /** The head's primary action row (a report video's Play, Walk, + Add a clip): on the stepper's row, on every tab. */ + primary?: React.ReactNode; /** A living report's schedule (R5): the cadence chip, Pause/Resume, Tick now. */ schedule?: { id: string; shape: string; chip: string; paused: boolean; cadence: Cadence; running: boolean } | null; /** The series this article is an edition of (R5). */ @@ -116,6 +119,12 @@ export default function PieceFrame({ below={ <div className="flex flex-wrap items-center gap-x-6 gap-y-2" data-piece-frame={frame.pieceId} data-piece-stage={frame.stage} data-piece-lifecycle={frame.lifecycle}> <Stepper steps={frame.steps} className="max-md:hidden" /> + {/* The head's primary row (lane/ui-simplify): beside the stepper, so the title's row keeps its actions inline. */} + {primary && ( + <span className="inline-flex flex-wrap items-center gap-1.5 md:order-last md:ml-auto" data-piece-primary=""> + {primary} + </span> + )} <StagePips steps={frame.steps} lifecycle={frame.lifecycle} className="md:hidden" /> {frame.board && ( <span className="text-[12.5px] text-muted" data-piece-from-board={frame.board.id}> diff --git a/umtool/components/projects/AddClip.tsx b/umtool/components/projects/AddClip.tsx @@ -0,0 +1,542 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { newClipEntry, quoteFromCues } from "@/lib/report/clipEditorModel.mjs"; +import { cn } from "@/lib/utils"; +import { announceManifestChanged, refusalOf, timelineOp, type TimelineResult } from "./timelineApi"; + +// --------------------------------------------------------------------------- +// ADD A CLIP, AS ONE FLOW (lane/ui-simplify, 5 Nov; the operator: "adding new +// clips to a cut really sucks"). +// +// 1 Find the words, in the recordings the cut already draws on +// (/api/report/find-moment) or across the archive +// (/api/research/search); or paste a link with a time +// 2 In/out on the moment's cues: click a line to start there, shift-click +// to end there; nudge ±0.5 s; the quote is read from the cues +// 3 Place after <row> -- by default where the clip's date falls when the +// cut is in date order, else after the row it was opened from +// 4 Add the timeline's own insert (the project's, or with `take` the +// take's patch only: "add to this take only"), then the clip's +// window fetched through the editor's paced fetch +// (POST /api/report/fetch) -- never yt-dlp by hand +// +// Opened from the Cut tab, from Play at the playhead's item ("Add a clip +// here") and from a take. The old one-line spec form stays as the Cut +// tab's "Add by spec". +// --------------------------------------------------------------------------- + +type Entry = { id: string; type: string; date?: string | null; video?: string | null; channel?: string | null; words?: string }; +type Moment = { channel: string | null; video: string; title: string | null; date: string | null; t: number; text?: string }; +type Cue = { start: number; end: number; text: string; endsSentence?: boolean }; +type FetchState = { state: "idle" } | { state: "running"; msg: string } | { state: "done"; msg: string } | { state: "failed"; msg: string }; + +const r2 = (n: number) => Math.round(n * 100) / 100; +const clock = (s: number) => { + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const sec = Math.floor(s % 60); + return h ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}` : `${m}:${String(sec).padStart(2, "0")}`; +}; + +/** `1:02:32`, `62m32s`, `3752`, `1h2m32s` → seconds; null when it is not a time. */ +export function parseTime(v: string | null | undefined): number | null { + const s = String(v ?? "").trim(); + if (!s) return null; + if (/^\d+(\.\d+)?s?$/.test(s)) return Number(s.replace(/s$/, "")); + const hms = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?$/.exec(s); + if (hms && (hms[1] || hms[2] || hms[3])) return Number(hms[1] ?? 0) * 3600 + Number(hms[2] ?? 0) * 60 + Number(hms[3] ?? 0); + const parts = s.split(":").map(Number); + if (parts.length >= 2 && parts.length <= 3 && parts.every((n) => Number.isFinite(n))) return parts.reduce((a, n) => a * 60 + n, 0); + return null; +} + +/** A pasted link or a short form → `{ video, t, channel? }`: a YouTube link (`v=`, youtu.be, /live/, /shorts/) with t= or start=, `<channel>/<video>@<time>`, `<video>@<time>`. */ +export function parseMomentLink(raw: string): { video: string; t: number; channel: string | null } | null { + const s = raw.trim(); + const short = /^(?:([A-Za-z0-9][A-Za-z0-9._-]*)\/)?([A-Za-z0-9_-]{2,})@([0-9:hms.]+)$/.exec(s); + if (short) { + const t = parseTime(short[3]); + return t === null ? null : { channel: short[1] ?? null, video: short[2], t }; + } + let u: URL; + try { + u = new URL(/^https?:\/\//.test(s) ? s : `https://${s}`); + } catch { + return null; + } + let video: string | null = u.searchParams.get("v"); + if (!video && /youtu\.be$/.test(u.hostname)) video = u.pathname.slice(1).split("/")[0] || null; + if (!video) { + const m = /\/(?:live|shorts|embed|v)\/([A-Za-z0-9_-]{6,})/.exec(u.pathname); + video = m ? m[1] : null; + } + if (!video) return null; + const t = parseTime(u.searchParams.get("t") ?? u.searchParams.get("start") ?? (u.hash.match(/t=([0-9hms:.]+)/)?.[1] ?? "0")) ?? 0; + return { video, t, channel: null }; +} + +/** Where a clip of `date` goes in a cut in date order: after the last dated entry on or before it; null when the cut is not in date order. */ +export function dateOrderAfter(entries: Entry[], date: string | null): string | null | undefined { + if (!date) return undefined; + const dated = entries.filter((e) => e.date); + if (dated.length < 2) return undefined; + for (let i = 1; i < dated.length; i++) if (String(dated[i].date) < String(dated[i - 1].date)) return undefined; + let after: string | null = null; + for (const e of entries) if (e.date && String(e.date) <= date) after = e.id; + return after; +} + +export default function AddClip({ + project, + take = null, + after: afterProp = null, + onClose, + onAdded, + className, +}: { + project: string; + /** "Add to this take only": the take's patch, never the project's manifest. */ + take?: string | null; + /** The row it was opened from (Play's playhead item): the default place when the cut is not in date order. */ + after?: string | null; + onClose?: () => void; + onAdded?: (id: string) => void; + className?: string; +}) { + const router = useRouter(); + const [entries, setEntries] = useState<Entry[]>([]); + const [token, setToken] = useState<string | null>(null); + const [mode, setMode] = useState<"cut" | "archive" | "link">("cut"); + const [q, setQ] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + const [hits, setHits] = useState<Moment[] | null>(null); + const [link, setLink] = useState(""); + const [moment, setMoment] = useState<Moment | null>(null); + const [cues, setCues] = useState<Cue[] | null>(null); + const [cueNote, setCueNote] = useState<string | null>(null); + const [start, setStart] = useState<number | null>(null); + const [end, setEnd] = useState<number | null>(null); + const [quote, setQuote] = useState(""); + const [quoteTyped, setQuoteTyped] = useState(false); + const [after, setAfter] = useState<string>(""); + const [placeWhy, setPlaceWhy] = useState<string>(""); + const [added, setAdded] = useState<string | null>(null); + const [fetchState, setFetchState] = useState<FetchState>({ state: "idle" }); + const cueList = useRef<HTMLOListElement | null>(null); + // The moment's line in view when its cues arrive (the list opens 40 s before it). + useEffect(() => { + const box = cueList.current; + const first = box?.querySelector("[data-inside]") as HTMLElement | null; + if (box && first) box.scrollTop = Math.max(0, first.offsetTop - box.offsetTop - 24); + }, [cues]); + + const loadEntries = useCallback(async () => { + const url = take + ? `/api/report/takes/timeline?project=${encodeURIComponent(project)}&take=${encodeURIComponent(take)}` + : `/api/report/timeline?project=${encodeURIComponent(project)}`; + const r = await fetch(url, { cache: "no-store" }); + const j = await r.json().catch(() => ({})); + if (!r.ok) { + setError(String(j.error ?? `HTTP ${r.status}`)); + return null; + } + setEntries(Array.isArray(j.timeline) ? j.timeline : []); + setToken(typeof j.token === "string" ? j.token : null); + return j as { token?: string }; + }, [project, take]); + useEffect(() => { + void loadEntries(); + }, [loadEntries]); + + const channels = useMemo(() => [...new Set(entries.map((e) => e.channel).filter((c): c is string => !!c))], [entries]); + + // ---- 1 find ------------------------------------------------------------- + const find = async () => { + if (!q.trim()) return; + setBusy(true); + setError(null); + setHits(null); + try { + if (mode === "cut") { + const r = await fetch(`/api/report/find-moment?project=${encodeURIComponent(project)}&q=${encodeURIComponent(q)}`, { cache: "no-store" }); + const j = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(String(j.error ?? `HTTP ${r.status}`)); + setHits(j.hits ?? []); + } else { + const sr = await fetch("/api/research/sources", { cache: "no-store" }); + const sj = await sr.json().catch(() => ({})); + const source = (sj.sources ?? [])[0]?.handle; + if (!source) throw new Error("no archive to search: set up a source on Research"); + const r = await fetch("/api/research/search", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ q, source, ...(channels.length ? { channels } : {}) }), + }); + const j = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(String(j.error ?? `HTTP ${r.status}`)); + const out: Moment[] = []; + for (const h of (j.hits ?? []) as { kind: string; videoId: string; channelSlug: string; title: string; uploadDate: string; snippets: { t: number; text: string }[] }[]) { + if (h.kind !== "video") continue; + for (const s of h.snippets ?? []) if (Number.isFinite(s.t)) out.push({ channel: h.channelSlug, video: h.videoId, title: h.title, date: h.uploadDate?.slice(0, 10) ?? null, t: s.t, text: s.text }); + if (out.length > 80) break; + } + setHits(out); + } + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + + const fromLink = () => { + const p = parseMomentLink(link); + if (!p) { + setError("not a link with a video and a time (a YouTube link with t=, or <channel>/<video>@1:02:32)"); + return; + } + const known = entries.find((e) => e.video === p.video); + setError(null); + pick({ channel: p.channel ?? known?.channel ?? channels[0] ?? null, video: p.video, title: null, date: known?.date ?? null, t: p.t }); + }; + + // ---- 2 in/out ----------------------------------------------------------- + const pick = (m: Moment) => { + setMoment(m); + setAdded(null); + setFetchState({ state: "idle" }); + setQuoteTyped(false); + setCues(null); + setCueNote(null); + const from = Math.max(0, m.t - 40); + const to = m.t + 50; + const qs = new URLSearchParams({ project, video: m.video, from: String(from), to: String(to) }); + if (m.channel) qs.set("channel", m.channel); + void fetch(`/api/report/cues?${qs}`, { cache: "no-store" }) + .then(async (r) => { + if (!r.ok) { + setCueNote("no transcript for this recording here: set the in and out by number, and type the quote"); + setStart(r2(m.t)); + setEnd(r2(m.t + 8)); + return; + } + const j = (await r.json()) as { cues?: Cue[] }; + const list = j.cues ?? []; + setCues(list); + const at = list.find((c) => c.end > m.t) ?? list[0]; + setStart(r2(at ? at.start : m.t)); + // To the end of the sentence the moment is in (the first cue that closes one), at most three cues on (an unpunctuated source). + const i = at ? list.indexOf(at) : -1; + const close = i >= 0 ? list.slice(i).find((c, k) => c.endsSentence || k >= 2) : null; + setEnd(r2(close ? close.end : m.t + 8)); + }) + .catch(() => setCueNote("the cues could not be read")); + // 3 place: by date when the cut is in date order, else after the row it was opened from, else the end. + const byDate = dateOrderAfter(entries, m.date); + if (byDate !== undefined) { + setAfter(byDate ?? ""); + setPlaceWhy(`by date (${m.date}): the cut is in date order`); + } else { + setAfter(afterProp ?? entries[entries.length - 1]?.id ?? ""); + setPlaceWhy(afterProp ? "after the item playing" : "at the end"); + } + }; + useEffect(() => { + if (quoteTyped || !cues || start === null || end === null) return; + setQuote(quoteFromCues(cues, start, end)); + }, [cues, start, end, quoteTyped]); + + // Click: start on this line. Shift-click: end on it (or, above the start, start there and keep the end). + const onCue = (c: Cue, e: React.MouseEvent) => { + if (e.shiftKey && start !== null) { + if (c.end > start + 0.05) setEnd(r2(c.end)); + else setStart(r2(c.start)); + return; + } + setStart(r2(c.start)); + if (end === null || end <= c.start + 0.05) setEnd(r2(c.end)); + }; + + // ---- 4 add, then fetch -------------------------------------------------- + const valid = moment && start !== null && end !== null && end - start >= 0.5; + const add = async () => { + if (!moment || !valid || start === null || end === null) return; + setBusy(true); + setError(null); + const entry: Record<string, unknown> = newClipEntry({ video: moment.video, ownChannel: moment.channel }, { start, end, quote }); + if (moment.date) entry.date = moment.date; + let res: TimelineResult; + if (take) { + const r = await fetch("/api/report/takes/timeline", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, take, token, op: "insert", afterId: after || null, entry }), + }); + res = { ok: r.ok, status: r.status, json: await r.json().catch(() => ({ error: `HTTP ${r.status}` })) }; + } else { + res = await timelineOp(project, token ?? ((await loadEntries())?.token ?? null), "insert", { afterId: after || null, entry }); + } + setBusy(false); + if (!res.ok) { + setError(refusalOf(res)); + if (res.json.stale) await loadEntries(); + return; + } + const id = typeof res.json.id === "string" ? res.json.id : null; + setAdded(id); + if (!take) announceManifestChanged(project); + await loadEntries(); + router.refresh(); + if (id) { + onAdded?.(id); + void fetchWindow(id); + } + }; + const fetchWindow = async (id: string) => { + setFetchState({ state: "running", msg: `fetching ${id}'s window through the editor…` }); + try { + const r = await fetch("/api/report/fetch", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, clip: id, padBefore: 20, padAfter: 20, ...(take ? { take } : {}) }), + }); + const j = (await r.json().catch(() => ({}))) as { error?: string; job?: { id: string }; cachedBefore?: number; cachedPad?: number }; + if (r.status === 409 && (j.cachedBefore !== undefined || j.cachedPad !== undefined)) return setFetchState({ state: "done", msg: "already fetched" }); + if (!r.ok || !j.job?.id) throw new Error(j.error ?? `HTTP ${r.status}`); + for (;;) { + await new Promise((ok) => setTimeout(ok, 1000)); + const pr = await fetch(`/api/report/fetch?job=${encodeURIComponent(j.job.id)}`, { cache: "no-store" }); + const pj = (await pr.json().catch(() => ({}))) as { job: { state: string; error?: string | null; progress?: string | null } | null }; + if (!pj.job) throw new Error("the fetch job was forgotten"); + if (pj.job.state === "running") { + setFetchState({ state: "running", msg: `fetching ${id}… ${pj.job.progress ?? ""}` }); + continue; + } + if (pj.job.state === "done") { + setFetchState({ state: "done", msg: `${id} fetched` }); + router.refresh(); + return; + } + throw new Error(pj.job.error ?? `the fetch ${pj.job.state}`); + } + } catch (e) { + setFetchState({ state: "failed", msg: e instanceof Error ? e.message : String(e) }); + } + }; + + const input = "rounded-[3px] border border-seam-2 bg-ground px-1.5 py-[3px] text-[12px] text-text outline-none focus:border-signal"; + const tab = (m: typeof mode, label: string) => ( + <button type="button" data-add-clip-mode={m} aria-pressed={mode === m} onClick={() => (setMode(m), setHits(null), setError(null))} className={buttonVariants({ variant: mode === m ? "pressed" : "quiet", size: "sm" })}> + {label} + </button> + ); + const nudge = (which: "in" | "out", d: number) => (which === "in" ? setStart((s) => (s === null ? s : r2(Math.max(0, s + d)))) : setEnd((s) => (s === null ? s : r2(s + d)))); + + return ( + <section data-add-clip={take ?? "cut"} className={cn("space-y-2 rounded border border-seam bg-panel p-3 text-[12px]", className)}> + <div className="flex flex-wrap items-center gap-2"> + <h2 className="micro m-0">{take ? `Add a clip to take ${take} only` : "Add a clip"}</h2> + <span className="text-muted">1 find · 2 in/out · 3 place · 4 add</span> + {onClose && ( + <button type="button" data-add-clip-close="" onClick={onClose} className={cn(buttonVariants({ variant: "quiet", size: "sm" }), "ml-auto")}> + Close + </button> + )} + </div> + + {/* 1 FIND */} + <div className="flex flex-wrap items-center gap-1.5"> + {tab("cut", "In this cut's recordings")} + {tab("archive", "The archive")} + {tab("link", "Paste a link")} + </div> + {mode === "link" ? ( + <div className="flex flex-wrap items-center gap-2"> + <input data-add-clip-link="" value={link} onChange={(e) => setLink(e.target.value)} onKeyDown={(e) => e.key === "Enter" && fromLink()} placeholder="https://youtu.be/<id>?t=3752 · <channel>/<video>@1:02:32" className={cn(input, "w-[28rem] max-w-full font-mono")} /> + <button type="button" data-add-clip-open-link="" onClick={fromLink} className={buttonVariants({ variant: "outline", size: "sm" })}> + Open the moment + </button> + </div> + ) : ( + <div className="flex flex-wrap items-center gap-2"> + <input data-add-clip-q="" value={q} onChange={(e) => setQ(e.target.value)} onKeyDown={(e) => e.key === "Enter" && void find()} placeholder={mode === "cut" ? "words said in a recording this cut uses" : "words, across the archive (this cut's channels)"} className={cn(input, "w-[24rem] max-w-full")} /> + <button type="button" data-add-clip-find="" disabled={busy || !q.trim()} onClick={() => void find()} className={buttonVariants({ variant: "outline", size: "sm" })}> + Find + </button> + {hits && <span className="text-muted" data-add-clip-hits={hits.length}>{hits.length ? `${hits.length} moment${hits.length === 1 ? "" : "s"}` : "nothing found"}</span>} + </div> + )} + {hits && hits.length > 0 && !moment && ( + <ol className="m-0 max-h-56 list-none space-y-0.5 overflow-auto p-0" data-add-clip-results=""> + {hits.map((h, i) => ( + <li key={`${h.video}@${h.t}:${i}`}> + <button type="button" data-add-clip-hit={`${h.video}@${h.t}`} onClick={() => pick(h)} className="flex w-full items-baseline gap-2 rounded-[2px] px-1.5 py-0.5 text-left hover:bg-panel-2"> + <span className="shrink-0 font-mono text-[11px] text-signal-text">{clock(h.t)}</span> + <span className="shrink-0 font-mono text-[11px] text-muted">{h.date ?? ""} {h.video}</span> + <span className="min-w-0 truncate text-text-2">{h.text}</span> + </button> + </li> + ))} + </ol> + )} + + {/* 2 IN / OUT */} + {moment && ( + <div className="space-y-1.5" data-add-clip-moment={`${moment.channel ?? ""}/${moment.video}@${moment.t}`}> + <div className="flex flex-wrap items-center gap-2"> + <span className="font-mono text-[11.5px] text-text"> + {moment.channel ? `${moment.channel}/` : ""} + {moment.video} + </span> + {moment.title && <span className="text-text-2">{moment.title}</span>} + {moment.date && <span className="font-mono text-[11px] text-muted">{moment.date}</span>} + {!moment.channel && ( + <label className="inline-flex items-center gap-1"> + channel + <input data-add-clip-channel="" value={moment.channel ?? ""} onChange={(e) => setMoment({ ...moment, channel: e.target.value || null })} className={cn(input, "w-36 font-mono")} /> + </label> + )} + <button type="button" onClick={() => (setMoment(null), setCues(null))} className={buttonVariants({ variant: "quiet", size: "sm" })}> + another moment + </button> + </div> + {cues && cues.length > 0 && ( + <ol ref={cueList} className="m-0 max-h-52 list-none overflow-auto rounded-[2px] border border-seam bg-ground p-1 font-serif text-[13px] leading-snug" data-add-clip-cues={cues.length}> + {cues.map((c) => { + const inside = start !== null && end !== null && c.end > start + 0.05 && c.start < end - 0.05; + return ( + <li key={c.start}> + <button + type="button" + data-add-clip-cue={c.start} + data-inside={inside ? "" : undefined} + onClick={(e) => onCue(c, e)} + title="click: start here · shift-click: end here" + className={cn("flex w-full gap-2 rounded-[2px] px-1 text-left", inside ? "bg-panel-2 text-text" : "text-muted hover:text-text")} + > + <span className="shrink-0 font-mono text-[10.5px] leading-[20px] text-muted">{clock(c.start)}</span> + <span>{c.text}</span> + </button> + </li> + ); + })} + </ol> + )} + {cueNote && <p className="m-0 text-muted">{cueNote}</p>} + <div className="flex flex-wrap items-center gap-2"> + {(["in", "out"] as const).map((w) => ( + <span key={w} className="inline-flex items-center gap-1"> + <span className="micro">{w}</span> + <button type="button" onClick={() => nudge(w, -0.5)} className={buttonVariants({ variant: "quiet", size: "sm" })} aria-label={`${w} 0.5 s earlier`}> + − + </button> + <input + data-add-clip-edge={w} + value={w === "in" ? (start ?? "") : (end ?? "")} + onChange={(e) => { + const v = parseTime(e.target.value); + if (v !== null) (w === "in" ? setStart : setEnd)(r2(v)); + }} + className={cn(input, "w-20 font-mono")} + /> + <button type="button" onClick={() => nudge(w, 0.5)} className={buttonVariants({ variant: "quiet", size: "sm" })} aria-label={`${w} 0.5 s later`}> + + + </button> + </span> + ))} + {start !== null && end !== null && ( + <span className="font-mono text-[11px] text-muted" data-add-clip-span=""> + {clock(start)}–{clock(end)} · {(end - start).toFixed(1)} s + </span> + )} + </div> + <textarea + data-add-clip-quote="" + value={quote} + rows={2} + placeholder="the quote (read from the cues)" + onChange={(e) => (setQuoteTyped(true), setQuote(e.target.value))} + className={cn(input, "w-full")} + /> + + {/* 3 PLACE + 4 ADD */} + <div className="flex flex-wrap items-center gap-2"> + <label className="inline-flex items-center gap-1"> + after + <select data-add-clip-after="" value={after} onChange={(e) => (setAfter(e.target.value), setPlaceWhy("picked"))} className={cn(input, "max-w-[26rem]")}> + <option value="">(the start)</option> + {entries.map((e, i) => ( + <option key={`${e.id}:${i}`} value={e.id}> + {i + 1}. {e.id} + {e.date ? ` · ${e.date}` : ""} + {e.words ? ` · ${e.words.slice(0, 40)}` : ""} + </option> + ))} + </select> + </label> + {placeWhy && <span className="text-muted" data-add-clip-place-why="">{placeWhy}</span>} + <button type="button" data-add-clip-submit="" disabled={busy || !valid} onClick={() => void add()} className={buttonVariants({ variant: "go", size: "sm" })}> + {take ? `Add to ${take} only` : "Add to the cut"} + </button> + </div> + </div> + )} + + {error && ( + <p role="alert" className="m-0 text-reject-text" data-add-clip-error=""> + {error} + </p> + )} + {added && ( + <p className="m-0 flex flex-wrap items-center gap-2 text-text-2" data-add-clip-added={added} data-add-clip-fetch={fetchState.state}> + <span> + Added <b className="font-mono">{added}</b> + {take ? ` to take ${take}` : ""}. + </span> + {fetchState.state !== "idle" && <span className={fetchState.state === "failed" ? "text-reject-text" : "text-muted"}>{fetchState.msg}</span>} + {fetchState.state === "failed" && ( + <button type="button" data-add-clip-refetch="" onClick={() => void fetchWindow(added)} className={buttonVariants({ variant: "outline", size: "sm" })}> + Retry the fetch + </button> + )} + </p> + )} + </section> + ); +} + +/** "+ Add a clip": the button and, pressed, the panel (open from the start with `open`, e.g. the head's `?add=1`). */ +export function AddClipToggle({ + project, + take = null, + after = null, + open: initiallyOpen = false, + label, + where, + onAdded, + className, +}: { + project: string; + take?: string | null; + after?: string | null; + onAdded?: (id: string) => void; + open?: boolean; + label?: string; + /** The surface: `data-add-clip-open="<where>"`. */ + where: string; + className?: string; +}) { + const [open, setOpen] = useState(initiallyOpen); + return ( + <> + <button type="button" data-add-clip-open={where} aria-expanded={open} onClick={() => setOpen((o) => !o)} className={cn(buttonVariants({ variant: open ? "pressed" : "outline", size: "sm" }), className)}> + {label ?? (take ? `+ Add a clip to ${take} only` : "+ Add a clip")} + </button> + {open && <AddClip project={project} take={take} after={after} onAdded={onAdded} onClose={() => setOpen(false)} className="basis-full" />} + </> + ); +} diff --git a/umtool/components/projects/AddPosts.tsx b/umtool/components/projects/AddPosts.tsx @@ -0,0 +1,121 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { announceManifestChanged } from "./timelineApi"; + +// --------------------------------------------------------------------------- +// ADD POSTS to a cut of posts (lane/ui-simplify, 5 Nov): the channel's +// archived posts the cut does not play yet, as post items -- `umtool posts reel` +// in the app (POST /api/report/add-posts, postReel.mjs postsReel). Preview +// lists what it would add; Add writes them in one undoable write. +// --------------------------------------------------------------------------- + +type Row = { id: string; date: string | null; handle: string | null; text: string; media: number }; +type Answer = { ok?: boolean; error?: string; added?: number; selected?: number; already?: number; dryRun?: boolean; entries?: Row[] }; + +export default function AddPosts({ project, channels: known }: { project: string; channels: string[] }) { + const router = useRouter(); + const [open, setOpen] = useState(false); + const [channel, setChannel] = useState(known[0] ?? ""); + const [own, setOwn] = useState(true); + const [since, setSince] = useState(""); + const [until, setUntil] = useState(""); + const [busy, setBusy] = useState(false); + const [plan, setPlan] = useState<Answer | null>(null); + const [done, setDone] = useState<Answer | null>(null); + const go = async (dryRun: boolean) => { + setBusy(true); + const r = await fetch("/api/report/add-posts", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, channels: [channel.trim()], own, since: since || null, until: until || null, dryRun }), + }); + const j = (await r.json().catch(() => ({ error: `HTTP ${r.status}` }))) as Answer; + setBusy(false); + if (!r.ok) j.error ??= `HTTP ${r.status}`; + if (dryRun) { + setPlan(j); + setDone(null); + } else { + setDone(j); + setPlan(null); + if (r.ok) { + announceManifestChanged(project); + router.refresh(); + } + } + }; + const input = "rounded-[3px] border border-seam-2 bg-ground px-1.5 py-[3px] text-[12px] text-text outline-none focus:border-signal"; + return ( + <> + <button type="button" data-add-posts-open="" aria-expanded={open} onClick={() => setOpen((o) => !o)} className={buttonVariants({ variant: open ? "pressed" : "outline", size: "sm" })}> + + Add posts + </button> + {open && ( + <section data-add-posts="" className="basis-full space-y-2 rounded border border-seam bg-panel p-3 text-[12px]"> + <div className="flex flex-wrap items-center gap-2"> + <h2 className="micro m-0">Add posts</h2> + <span className="text-muted">the archive's posts this cut does not play yet</span> + </div> + <div className="flex flex-wrap items-center gap-2"> + <label className="inline-flex items-center gap-1"> + channel + <input data-add-posts-channel="" list="add-posts-channels" value={channel} onChange={(e) => setChannel(e.target.value)} className={cn(input, "w-44 font-mono")} /> + <datalist id="add-posts-channels"> + {known.map((c) => ( + <option key={c} value={c} /> + ))} + </datalist> + </label> + <label className="inline-flex items-center gap-1"> + <input type="checkbox" data-add-posts-own="" checked={own} onChange={(e) => setOwn(e.target.checked)} /> + their own posts only + </label> + <label className="inline-flex items-center gap-1"> + from + <input type="date" data-add-posts-since="" value={since} onChange={(e) => setSince(e.target.value)} className={input} /> + </label> + <label className="inline-flex items-center gap-1"> + to + <input type="date" data-add-posts-until="" value={until} onChange={(e) => setUntil(e.target.value)} className={input} /> + </label> + <button type="button" data-add-posts-preview="" disabled={busy || !channel.trim()} onClick={() => void go(true)} className={buttonVariants({ variant: "outline", size: "sm" })}> + Preview + </button> + <button type="button" data-add-posts-go="" disabled={busy || !channel.trim() || (plan !== null && !plan.added)} onClick={() => void go(false)} className={buttonVariants({ variant: "go", size: "sm" })}> + {plan?.added ? `Add ${plan.added} post${plan.added === 1 ? "" : "s"}` : "Add"} + </button> + </div> + {[plan, done].map((a, k) => + a ? ( + <div key={k} data-add-posts-result={k === 0 ? "plan" : "done"} data-add-posts-added={a.added ?? 0}> + {a.error ? ( + <p className="m-0 text-reject-text">{a.error}</p> + ) : ( + <> + <p className="m-0 text-text-2"> + {k === 0 ? "would add" : "added"} {a.added} post item{a.added === 1 ? "" : "s"} ({a.selected} selected, {a.already} already in the cut) + </p> + <ol className="m-0 max-h-48 list-none space-y-0.5 overflow-auto p-0"> + {(a.entries ?? []).map((e) => ( + <li key={e.id} data-add-posts-row={e.id} className="flex gap-2"> + <span className="shrink-0 font-mono text-[11px] text-muted">{e.date}</span> + <span className="shrink-0 font-mono text-[11px]">{e.id}</span> + <span className="min-w-0 truncate text-text-2">{e.text}</span> + {e.media > 0 && <span className="text-muted">+{e.media}</span>} + </li> + ))} + </ol> + </> + )} + </div> + ) : null, + )} + </section> + )} + </> + ); +} diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -1,5 +1,6 @@ "use client"; +import RefetchButton from "./RefetchButton"; import RejectClip, { type RejectClipControl } from "./review/RejectClip"; import { rejectionOf } from "@/lib/report/rejectReasons.mjs"; import AnchoredNotes, { notesOn } from "@/components/notes/AnchoredNotes"; @@ -3099,6 +3100,8 @@ export default function ClipBench({ > Fetch whole source via editor </button> + {/* A window known bad, evicted and fetched again: a queue step (lane/ui-simplify). */} + <RefetchButton project={data.project} clip={clip.id} take={takeId} disabled={!!busy} /> {storedOffered && ( <StoredUrlCheckbox checked={fromStored} onChange={setFromStored} disabled={!!busy} compact /> )} diff --git a/umtool/components/projects/NewTakePanel.tsx b/umtool/components/projects/NewTakePanel.tsx @@ -3,6 +3,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { useRouter } from "next/navigation"; import { buttonVariants } from "@/components/ui/button"; +import { takeWalkHref } from "@/lib/hrefs"; import { Field, Input, Select, Textarea } from "@/components/ui/field"; import { JobProgress, type JobStepState } from "@/components/ui/job-progress"; import RenderModeBanner, { renderPriorityPref } from "./RenderModeBanner"; @@ -153,6 +154,24 @@ export default function NewTakePanel({ if (r.error) setError(r.error); }; + // Save as a draft (lane/ui-simplify): the take recorded with nothing rendered (POST /api/report/takes/tools, draft-new). + const [drafted, setDrafted] = useState<string | null>(null); + const saveDraft = async () => { + setBusy(true); + setError(null); + const r = await fetch("/api/report/takes/tools", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, op: "draft-new", label, group, style: style || null, patch, window: windowOf() }), + }); + const j = (await r.json().catch(() => ({}))) as { exit?: number; id?: string; said?: string; error?: string }; + setBusy(false); + if (r.ok && j.exit === 0 && j.id) { + setDrafted(j.id); + router.refresh(); + } else setError(j.error ?? j.said ?? `HTTP ${r.status}`); + }; + const takeEvents = (job?.events ?? []).filter((e) => e.ev === "take"); const takeIds = [...new Set(takeEvents.map((e) => String(e.id)))]; const stateOf = (id: string) => { @@ -292,6 +311,16 @@ export default function NewTakePanel({ </button> <button type="button" + data-action="save-draft" + disabled={!ready || busy || running || !label.trim() || !!patchError || windowBad} + className={buttonVariants({ variant: "quiet", size: "sm" })} + title={`umtool take ${project} --id <label> --label … --draft: recorded, nothing rendered — walk it, then render it`} + onClick={() => void saveDraft()} + > + Save as a draft + </button> + <button + type="button" data-action="make-all-styles" disabled={!ready || busy || running || !styles.length || windowBad} className={buttonVariants({ size: "sm" })} @@ -310,6 +339,14 @@ export default function NewTakePanel({ </div> </form> </details> + {drafted && ( + <p data-take-drafted-new={drafted} className="text-[12px] text-text-2"> + draft <b className="font-mono">{drafted}</b> recorded, nothing rendered:{" "} + <a href={takeWalkHref(project, drafted)} className="ink-link"> + walk it + </a> + </p> + )} {error && ( <p data-take-error="" role="alert" className="text-[12px] text-reject-text"> {error} diff --git a/umtool/components/projects/PlayCutPage.tsx b/umtool/components/projects/PlayCutPage.tsx @@ -7,6 +7,7 @@ import { NotesProvider } from "@/components/notes/NotesProvider"; import { BenchFrame, BenchTop } from "./bench/BenchShell"; import PlayCut, { type PlayViewData } from "./review/PlayCut"; import CutApp from "./cutApp/CutApp"; +import { RememberCut } from "@/components/shell/RecentCuts"; // `/projects/<project>/play` (and `?take=<id>`) -- THE PLAY VIEW // (umtool/docs/knobs.md, "Play the cut"): the whole cut, or a take, played in the browser in @@ -62,6 +63,7 @@ export default async function PlayCutPage({ // Play and the clip bench as ONE app (cutApp/CutApp.tsx): Play stays mounted, the bench opens in place. return ( <CutApp project={project.id} playTop={top}> + <RememberCut project={project.id} title={project.name ?? project.id} /> <NotesProvider target={{ project: project.id }}> <PlayCut view={view as PlayViewData} diff --git a/umtool/components/projects/PlayLink.tsx b/umtool/components/projects/PlayLink.tsx @@ -0,0 +1,74 @@ +import Link from "next/link"; +import { buttonVariants } from "@/components/ui/button"; +import { playHref } from "@/lib/hrefs"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// PLAY, FROM ANYWHERE A CUT OR A TAKE IS NAMED (lane/ui-simplify, 5 Nov; the +// operator: "sometimes going to the play screen for a cut is hard to do without +// 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 +// 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`, +// `note`): `data-play-link="<where>"`, the e2e's handle. +// --------------------------------------------------------------------------- + +export type PlayLinkVariant = "primary" | "header" | "button" | "link" | "icon"; + +export default function PlayLink({ + project, + take = null, + clip = null, + at = null, + note = null, + where, + variant = "button", + label, + title, + className, +}: { + project: string; + /** A take id; null plays the newest take. */ + take?: string | null; + /** Start on this item (a clip or a post item's id). */ + clip?: string | null; + at?: number | null; + note?: string | null; + where: string; + variant?: PlayLinkVariant; + label?: React.ReactNode; + title?: string; + className?: string; +}) { + const href = playHref(project, { take, clip, at, note }); + const words = label ?? (variant === "icon" ? "▶" : clip ? "▶ Play here" : take ? `▶ Play ${take}` : "▶ Play"); + const look = + variant === "primary" + ? buttonVariants({ variant: "go", size: "md" }) + : variant === "header" + ? buttonVariants({ variant: "outline", size: "md" }) + : variant === "button" + ? buttonVariants({ variant: "outline", size: "sm" }) + : variant === "icon" + ? "inline-flex items-center rounded-[3px] px-1 text-[11px] text-signal-text hover:bg-panel-2" + : "ink-link text-[11.5px]"; + return ( + <Link + href={href} + prefetch={false} + data-play-link={where} + 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")} + className={cn(look, className)} + > + {words} + </Link> + ); +} diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -1,5 +1,6 @@ "use client"; +import { inTakeBody, useInTake } from "./inTake"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -105,6 +106,7 @@ export default function PostBench({ /** The posts its conversation's run leaves on screen (post-conversation.mjs planContext): kept on top or collapsed away. It wins the card over a media scene. */ conversation?: Record<string, unknown> | null; }) { + const inTake = useInTake(); const router = useRouter(); const [entry, setEntry] = useState<Entry>(initial); const [saved, setSaved] = useState<Entry>(initial); @@ -232,7 +234,7 @@ export default function PostBench({ const res = await fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, - body: JSON.stringify({ project, op: "set", id: entry.id, patch: patchOf(entry), token }), + body: JSON.stringify({ project, op: "set", id: entry.id, patch: patchOf(entry), token, ...inTakeBody(inTake) }), }); const j = (await res.json().catch(() => ({}))) as { entry?: Entry; token?: string; error?: string; errors?: string[] }; if (!res.ok || !j.entry) { @@ -252,7 +254,7 @@ export default function PostBench({ const [jobs, setJobs] = useState<Record<number, { job: string; state: string; error?: string }>>({}); const transcribe = async (i: number) => { setError(null); - const res = await fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "transcribe", id: entry.id, media: i }) }); + const res = await fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "transcribe", id: entry.id, media: i, ...inTakeBody(inTake) }) }); const j = (await res.json().catch(() => ({}))) as { jobId?: string; error?: string }; if (!res.ok || !j.jobId) { setJobs((x) => ({ ...x, [i]: { job: "", state: "failed", error: j.error ?? `HTTP ${res.status}` } })); diff --git a/umtool/components/projects/PostBenchPage.tsx b/umtool/components/projects/PostBenchPage.tsx @@ -4,6 +4,12 @@ import PostBench from "./PostBench"; import { channelsDirFor, readManifest } from "@/lib/projects/report.mjs"; import { manifestToken } from "@/lib/report/manifest.mjs"; import { projectHref, playHref } from "@/lib/hrefs"; +import PlayLink from "./PlayLink"; +import Link from "next/link"; +import { InTakeProvider } from "./inTake"; +import { postBenchHref } from "@/lib/hrefs"; +import { withTakeScope } from "@/lib/report/takeScope.mjs"; +import { isTakeId, listTakes } from "@/lib/report/takes.mjs"; import { deckGeometry, deckOn, feedGeometry, feedOn } from "umtool-report-to-video/deck"; import { postItemPlan, panelEntry } from "umtool-report-to-video/post-item"; import { planContext } from "umtool-report-to-video/post-conversation"; @@ -20,7 +26,21 @@ import type { ComboInfo } from "./review/ComboBadge"; // words through the editor's transcription. Every save is updatePostItem // (POST /api/report/post-item {op: "set"}), the writer `umtool posts set-item` runs. +// "EDIT THIS TAKE ONLY" (lane/ui-simplify): `?inTake=<take>` reads the item as the take has it and scopes every +// write of the bench to the take's patch (takeScope.mjs, the CLI's `--in-take`); the project's cut is untouched. export default async function PostBenchPage({ project, id, search = {} }: { project: ProjectRef; id: string; search?: Record<string, string | undefined> }) { + const inTake = search.inTake && isTakeId(search.inTake) ? search.inTake : null; + const takes = ((await listTakes(project.dir)).takes as { id: string; builtAt?: string | null; draft?: boolean }[]) + .filter((t) => t.builtAt || t.draft) + .sort((a, b) => String(b.builtAt ?? "").localeCompare(String(a.builtAt ?? ""))) + .slice(0, 6) + .map((t) => t.id); + if (inTake && !takes.includes(inTake)) takes.unshift(inTake); + const body = () => postBenchBody({ project, id, search, inTake, takes }); + return inTake ? withTakeScope(project.dir, inTake, body) : body(); +} + +async function postBenchBody({ project, id, search, inTake, takes }: { project: ProjectRef; id: string; search: Record<string, string | undefined>; inTake: string | null; takes: string[] }) { const m = (await readManifest(project.dir)) as Record<string, unknown> | null; if (!m) notFound(); const tl = (Array.isArray(m.timeline) ? m.timeline : []) as Array<Record<string, unknown> & { id: string; type?: string }>; @@ -42,15 +62,30 @@ export default async function PostBenchPage({ project, id, search = {} }: { proj const combo = combos[id] ?? null; // Its media scene (post-media-scene.mjs): its neighbours with the same attachment, by the combo's groups. const scene = mediaSceneOf(tl, at, counted.groups, render); - const back = fromPlay ? playHref(project.id, { clip: id, at: Number(search.at ?? 0) || null }) : projectHref(project.id, { tab: "cut" }); + const back = fromPlay ? playHref(project.id, { take: inTake, clip: id, at: Number(search.at ?? 0) || null }) : projectHref(project.id, { tab: "cut" }); return ( <div className="flex h-full flex-col"> <AppShell active="projects" crumbs={[{ href: "/projects", label: "Projects" }, { href: projectHref(project.id), label: project.name }, { label: `post ${id}` }]} note={`post item ${k + 1} of ${neighbours.length} · ${String(entry.post ?? "")}`} + actions={<PlayLink project={project.id} take={inTake} clip={id} where="post-bench" variant="header" label="▶ Play from here" />} /> <main className="deck-main flex-1 overflow-auto p-4"> + {/* Where the bench's edits go: the cut, or one take only. */} + <p className="mb-2 flex flex-wrap items-center gap-2 text-[12px]" data-post-bench-scope={inTake ?? "cut"}> + <span className="micro">edits go to</span> + <Link href={postBenchHref(project.id, id)} aria-current={!inTake ? "page" : undefined} className={!inTake ? "font-medium text-text" : "ink-link"} data-post-bench-scope-link=""> + the cut + </Link> + {takes.map((t) => ( + <Link key={t} href={`${postBenchHref(project.id, id)}?inTake=${encodeURIComponent(t)}`} aria-current={inTake === t ? "page" : undefined} className={inTake === t ? "font-medium text-text" : "ink-link"} data-post-bench-scope-link={t}> + take {t} only + </Link> + ))} + {inTake && <span className="text-doubt-text">editing take {inTake} only — the cut and its other takes are untouched; reads are re-made on the cut's bench</span>} + </p> + <InTakeProvider take={inTake}> <PostBench project={project.id} entry={entry} @@ -67,6 +102,7 @@ export default async function PostBenchPage({ project, id, search = {} }: { proj next={k < neighbours.length - 1 ? neighbours[k + 1] : null} fromPlay={fromPlay} /> + </InTakeProvider> </main> </div> ); diff --git a/umtool/components/projects/PostComboPanel.tsx b/umtool/components/projects/PostComboPanel.tsx @@ -1,5 +1,6 @@ "use client"; +import { inTakeBody, useInTake } from "./inTake"; import Link from "next/link"; import { useState } from "react"; import { postBenchHref } from "@/lib/hrefs"; @@ -28,6 +29,7 @@ export default function PostComboPanel({ render: Record<string, unknown>; onEntry: (entry: Record<string, unknown> & { id: string }, token: string | null) => void; }) { + const inTake = useInTake(); const [error, setError] = useState<string | null>(null); const [busy, setBusy] = useState(false); // The box follows the click at once; the write's answer settles it (a refusal puts it back). @@ -42,7 +44,7 @@ export default function PostComboPanel({ const res = await fetch("/api/report/post-combo", { method: "POST", headers: { "content-type": "application/json" }, - body: JSON.stringify({ project, op: "set", id: entry.id, combo: on ? null : false, token }), + body: JSON.stringify({ project, op: "set", id: entry.id, combo: on ? null : false, token, ...inTakeBody(inTake) }), }); const j = (await res.json().catch(() => ({}))) as { entry?: Record<string, unknown> & { id: string }; token?: string; error?: string; errors?: string[] }; setBusy(false); diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx @@ -1,5 +1,7 @@ "use client"; +import { Options } from "@/components/ui/disclosure"; +import { useInTake } from "./inTake"; import Link from "next/link"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import Waveform from "@/components/Waveform"; @@ -60,12 +62,16 @@ export default function PostNarrationPanel({ next: string | null; fromPlay: boolean; }) { + const inTake = useInTake(); const n = entry.narration ?? {}; const takes = n.takes ?? []; const picked = pickedTake(entry) as (Take & { index: number }) | null; const k = postNarrationKnobs(entry, render) as typeof POST_NARRATION_DEFAULTS & Record<string, unknown>; const [error, setError] = useState<string | null>(null); const [status, setStatus] = useState<string | null>(null); + const [rereadTempo, setRereadTempo] = useState(""); + const [rereadDrop, setRereadDrop] = useState(""); + const [rereadUrls, setRereadUrls] = useState(false); const btn = cn(buttonVariants({ variant: "outline", size: "sm" })); const post = useCallback( @@ -329,6 +335,13 @@ export default function PostNarrationPanel({ </label> ); + // A take-scoped bench (?inTake): a read is made for the cut here; a take's own read is \`umtool posts narrate … --in-take <t>\`. + if (inTake) + return ( + <p className="m-0 text-[12px] text-muted" data-post-bench-in-take-note=""> + Narration is edited on the cut's bench (edits go to: the cut); take {inTake} keeps the reads it has. + </p> + ); return ( <div className="space-y-3 text-[12.5px]" data-post-narration={entry.id} data-post-narration-plays={picked ? (picked.engine === "recorded" ? "recorded" : "synthesized") : "none"}> {/* The cut's reading: how far along, and where next. */} @@ -709,6 +722,35 @@ export default function PostNarrationPanel({ {mixKnob("attach", "attachment", { options: ["under", "after"] })} {mixKnob("clip", "clip", { options: ["read", "full"] })} </section> + {/* RE-JOIN THE PICKED READ, no TTS (postReread.mjs; terminal-only before: posts reread --tempo / --drop-parts / + --drop-urls, posts yell): its parts re-timed, some left out, the URLs dropped, the caps raised -- a new take, picked. */} + {picked && picked.engine !== "recorded" && ( + <Options id="post-reread" label="Re-join the read (no TTS)" hint="re-time parts · drop parts or URLs · raise the caps"> + <span className="flex flex-wrap items-center gap-1.5"> + <label className="inline-flex items-center gap-1"> + re-time + <input value={rereadTempo} onChange={(e) => setRereadTempo(e.target.value)} placeholder="4-16=1.35,21-25=1.3" className="w-40 rounded border border-seam bg-ground px-1 py-0.5 font-mono text-[11px]" data-post-reread-tempo="" /> + </label> + <button type="button" className={btn} disabled={!rereadTempo.trim()} onClick={() => void post({ op: "reread", tempo: rereadTempo.trim() }).then((j) => j && setStatus("re-timed: a new take, picked"))} data-post-reread-tempo-go=""> + Re-time + </button> + <label className="inline-flex items-center gap-1"> + leave out parts + <input value={rereadDrop} onChange={(e) => setRereadDrop(e.target.value)} placeholder="3,7" className="w-20 rounded border border-seam bg-ground px-1 py-0.5 font-mono text-[11px]" data-post-reread-drop="" /> + </label> + <label className="inline-flex items-center gap-1"> + <input type="checkbox" checked={rereadUrls} onChange={(e) => setRereadUrls(e.target.checked)} data-post-reread-urls="" /> + drop the URLs + </label> + <button type="button" className={btn} disabled={!rereadDrop.trim() && !rereadUrls} onClick={() => void post({ op: "reread", dropParts: rereadDrop.trim() || undefined, dropUrls: rereadUrls || undefined }).then((j) => j && setStatus("re-joined: a new take, picked"))} data-post-reread-drop-go=""> + Re-join + </button> + <button type="button" className={btn} onClick={() => void post({ op: "reread", yell: true }).then((j) => j && setStatus("the caps raised: a new take, picked"))} data-post-reread-yell=""> + Raise the CAPS + </button> + </span> + </Options> + )} {status && <p className="m-0 text-text-2" data-post-narration-status="">{status}</p>} {error && ( <p className="m-0 text-[var(--color-blocking,#c33)]" data-post-narration-error=""> diff --git a/umtool/components/projects/PostThreadPanel.tsx b/umtool/components/projects/PostThreadPanel.tsx @@ -1,5 +1,6 @@ "use client"; +import { useInTake } from "./inTake"; import { useMemo, useState } from "react"; import { THREAD_DEFAULTS, THREAD_LIMITS, THREAD_MODES, partRoles, readPieces, threadKnobs, threadLayout, threadReadErrors } from "umtool-report-to-video/post-thread"; import { followKnobs } from "umtool-report-to-video/read-follow"; @@ -39,6 +40,7 @@ export default function PostThreadPanel({ setS: (s: number) => void; setEntry: (f: (e: Entry) => Entry) => void; }) { + const inTake = useInTake(); const own = (entry.thread ?? undefined) as Thread | undefined; const k = threadKnobs(entry, render) as Required<Thread>; const layout = useMemo(() => threadLayout(entry, render, { prev: before, scene }), [entry, render, before, scene]); @@ -104,6 +106,13 @@ export default function PostThreadPanel({ </label> ); if (!parents.length && !entry.quoted && !sceneTiles.length) return null; + // A take-scoped bench (?inTake): a read is made for the cut here; a take's own read is \`umtool posts narrate … --in-take <t>\`. + if (inTake) + return ( + <p className="m-0 text-[12px] text-muted" data-post-bench-in-take-note=""> + The thread read is edited on the cut's bench (edits go to: the cut); take {inTake} keeps the reads it has. + </p> + ); return ( <section className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3 text-[12px]" data-post-thread-panel="" data-threaded={layout.on ? "1" : "0"}> <div className="mb-2 flex flex-wrap items-center gap-2"> diff --git a/umtool/components/projects/PostZoomPanel.tsx b/umtool/components/projects/PostZoomPanel.tsx @@ -1,5 +1,6 @@ "use client"; +import { inTakeBody, useInTake } from "./inTake"; import { useEffect, useMemo, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; @@ -40,6 +41,7 @@ export default function PostZoomPanel({ setS: (s: number) => void; onEntry: (e: Entry, token: string | null) => void; }) { + const inTake = useInTake(); const btn = cn(buttonVariants({ variant: "outline", size: "sm" })); const [error, setError] = useState<string | null>(null); const [status, setStatus] = useState<string | null>(null); @@ -69,7 +71,7 @@ export default function PostZoomPanel({ const send = async (fx: Record<string, unknown>) => { setError(null); - const res = await fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "fx", id: entry.id, fx, token }) }); + const res = await fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "fx", id: entry.id, fx, token, ...inTakeBody(inTake) }) }); const j = (await res.json().catch(() => ({}))) as { entry?: Entry; token?: string; error?: string; errors?: string[] }; if (!res.ok || !j.entry) { setError(j.errors?.join("; ") ?? j.error ?? `HTTP ${res.status}`); diff --git a/umtool/components/projects/ProjectPrimary.tsx b/umtool/components/projects/ProjectPrimary.tsx @@ -0,0 +1,69 @@ +import Link from "next/link"; +import { buttonVariants } from "@/components/ui/button"; +import { clipBenchHref, projectHref, takeWalkHref } from "@/lib/hrefs"; +import PlayLink from "./PlayLink"; +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. +// --------------------------------------------------------------------------- + +type Working = { latest: { id: string; seconds: number | null; builtAt: string | null } | 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). */ +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. */ +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; +} + +export default function ProjectPrimary({ project, detail, latest, words = null }: { project: string; detail: ClipDetail; latest: string | null; words?: string | null }) { + const entries = detail.entries; + if (entries.length === 0) { + return ( + <Link href={projectHref(project, { tab: "cut" }) + "&add=1"} prefetch={false} data-primary-add-clip="" className={buttonVariants({ variant: "outline", size: "md" })}> + + Add a clip + </Link> + ); + } + 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"} /> + {words && ( + <span className="font-mono text-[11px] text-muted" data-primary-latest={latest ?? ""}> + {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" })}> + Walk + </Link> + ) : null} + <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/PronunciationPanel.tsx b/umtool/components/projects/PronunciationPanel.tsx @@ -0,0 +1,294 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { jobsHref } from "@/lib/hrefs"; + +// --------------------------------------------------------------------------- +// READS AND VOICES for a cut of posts (lane/ui-simplify, 5 Nov): the +// pronunciation lexicon (`umtool posts say`) and the voice map (`umtool posts +// voices`) as two small tables, with "try it" -- what a voice would be asked to +// say -- and the picked reads that still say an entry the old way. Every write +// is POST /api/report/pronunciation, the CLI's own commands. +// --------------------------------------------------------------------------- + +type Lex = { word: string; say: string; case?: boolean; item?: string; note?: string }; +type Author = { handle: string; items: number; context: number; voice: string; mapped: boolean }; +type View = { + lexicon: { json: { lexicon?: Lex[] } | null; error?: string }; + voices: { json: { voices?: Record<string, string>; narrator?: string; engine?: string; authors?: Author[] } | null; error?: string }; + stale: { json: { reads?: { id: string; take: string; entries: { word: string; say: string }[]; fix: string }[] } | null }; + redact?: { json: { redact?: (string | { term: string; substring?: boolean; note?: string })[]; corpusTerms?: number; markedPosts?: number } | null; error?: string }; + mix?: Record<string, unknown>; + slurs?: { json: { on?: boolean; level?: string; visual?: string; voice?: string; listed?: number; add?: number; except?: number; total?: number } | null; error?: string }; +}; + +export default function PronunciationPanel({ project }: { project: string }) { + const [view, setView] = useState<View | null>(null); + const [error, setError] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + const [word, setWord] = useState(""); + const [sayAs, setSayAs] = useState(""); + const [tryText, setTryText] = useState(""); + const [tried, setTried] = useState<string | null>(null); + const [handle, setHandle] = useState(""); + const [voice, setVoice] = useState(""); + const [queued, setQueued] = useState<string | null>(null); + const [term, setTerm] = useState(""); + const [slurWord, setSlurWord] = useState(""); + const [mixKey, setMixKey] = useState("rate"); + const [mixValue, setMixValue] = useState(""); + const load = useCallback(async () => { + const r = await fetch(`/api/report/pronunciation?project=${encodeURIComponent(project)}`, { cache: "no-store" }); + const j = await r.json().catch(() => null); + if (!r.ok || !j) setError(j?.error ?? `HTTP ${r.status}`); + else setView(j as View); + }, [project]); + useEffect(() => { + void load(); + }, [load]); + const post = async (body: Record<string, unknown>) => { + setBusy(true); + setError(null); + const r = await fetch("/api/report/pronunciation", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, ...body }) }); + const j = (await r.json().catch(() => ({}))) as { error?: string; json?: { said?: string } | null }; + setBusy(false); + if (!r.ok) { + setError(j.error ?? `HTTP ${r.status}`); + return null; + } + if (body.op !== "say-try") await load(); + return j; + }; + const lex = view?.lexicon.json?.lexicon ?? []; + const v = view?.voices.json; + const stale = view?.stale.json?.reads ?? []; + const input = "rounded-[3px] border border-seam-2 bg-ground px-1.5 py-[3px] text-[11.5px] text-text outline-none focus:border-signal"; + const cell = "border-t border-seam px-1.5 py-0.5 align-top"; + return ( + <div className="grid basis-full grid-cols-1 gap-4 text-[12px] lg:grid-cols-2" data-pronunciation-panel=""> + <section data-lexicon={lex.length}> + <h3 className="micro mb-1">Pronunciation · {lex.length}</h3> + <table className="w-full border-collapse"> + <tbody> + {lex.map((x, i) => ( + <tr key={`${x.word}:${x.item ?? ""}:${i}`} data-lexicon-row={x.word}> + <td className={cn(cell, "font-mono")}>{x.word}</td> + <td className={cell}>→ {x.say}</td> + <td className={cn(cell, "text-muted")}> + {x.case ? "with case " : ""} + {x.item ? `${x.item} only` : ""} + {x.note ? ` · ${x.note}` : ""} + </td> + <td className={cn(cell, "text-right")}> + <button type="button" data-lexicon-remove={i + 1} disabled={busy} onClick={() => void post({ op: "say-remove", n: i + 1 })} className={buttonVariants({ variant: "quiet", size: "sm" })} aria-label={`remove ${x.word}`}> + ✕ + </button> + </td> + </tr> + ))} + </tbody> + </table> + <div className="mt-1 flex flex-wrap items-center gap-1.5"> + <input data-lexicon-word="" value={word} onChange={(e) => setWord(e.target.value)} placeholder="word or phrase (tbh)" className={cn(input, "w-36 font-mono")} /> + <input data-lexicon-say="" value={sayAs} onChange={(e) => setSayAs(e.target.value)} placeholder="said as (T-B-H)" className={cn(input, "w-36")} /> + <button + type="button" + data-lexicon-add="" + disabled={busy || !word.trim() || !sayAs.trim()} + onClick={() => void post({ op: "say-add", word, say: sayAs }).then((ok) => ok && (setWord(""), setSayAs("")))} + className={buttonVariants({ variant: "outline", size: "sm" })} + > + Add + </button> + </div> + <div className="mt-1.5 flex flex-wrap items-center gap-1.5"> + <input data-lexicon-try="" value={tryText} onChange={(e) => setTryText(e.target.value)} placeholder="try it: text a voice would read" className={cn(input, "w-64")} /> + <button type="button" data-lexicon-try-go="" disabled={busy || !tryText.trim()} onClick={() => void post({ op: "say-try", text: tryText }).then((j) => setTried(j?.json?.said ?? null))} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Try it + </button> + {tried !== null && ( + <span className="text-text-2" data-lexicon-tried=""> + said: “{tried}” + </span> + )} + </div> + {stale.length > 0 && ( + <div className="mt-1.5 text-[11.5px] text-doubt-text" data-lexicon-stale={stale.length}> + {stale.length} picked read{stale.length === 1 ? "" : "s"} still say an entry the old way: {stale.map((s) => s.id).join(", ")} — re-read on each post's bench. + </div> + )} + </section> + <section data-voice-map={Object.keys(v?.voices ?? {}).length}> + <h3 className="micro mb-1"> + Voices · the narrator {v?.engine ?? ""} {v?.narrator ?? ""} + </h3> + <table className="w-full border-collapse"> + <tbody> + {Object.entries(v?.voices ?? {}).map(([h, voiceName]) => ( + <tr key={h} data-voice-map-row={h}> + <td className={cn(cell, "font-mono")}>{h === "*" ? "* everyone else" : `@${h}`}</td> + <td className={cell}>{voiceName}</td> + <td className={cn(cell, "text-right")}> + <button type="button" data-voice-map-remove={h} disabled={busy} onClick={() => void post({ op: "voices-remove", handle: h })} className={buttonVariants({ variant: "quiet", size: "sm" })} aria-label={`remove ${h}`}> + ✕ + </button> + </td> + </tr> + ))} + {(v?.authors ?? []) + .filter((a) => !a.mapped) + .slice(0, 8) + .map((a) => ( + <tr key={a.handle} className="text-muted" data-voice-author={a.handle}> + <td className={cn(cell, "font-mono")}>@{a.handle}</td> + <td className={cell}> + {a.voice} (default) · {a.items} item{a.items === 1 ? "" : "s"}, {a.context} context + </td> + <td className={cn(cell, "text-right")}> + <button type="button" onClick={() => setHandle(a.handle)} className={buttonVariants({ variant: "quiet", size: "sm" })}> + set + </button> + </td> + </tr> + ))} + </tbody> + </table> + <div className="mt-1 flex flex-wrap items-center gap-1.5"> + <input data-voice-map-handle="" value={handle} onChange={(e) => setHandle(e.target.value)} placeholder="handle (or *)" className={cn(input, "w-36 font-mono")} /> + <input data-voice-map-voice="" value={voice} onChange={(e) => setVoice(e.target.value)} placeholder="voice (tara)" className={cn(input, "w-28")} /> + <button + type="button" + data-voice-map-set="" + disabled={busy || !handle.trim() || !voice.trim()} + onClick={() => void post({ op: "voices-set", handle, voice }).then((ok) => ok && (setHandle(""), setVoice("")))} + className={buttonVariants({ variant: "outline", size: "sm" })} + > + Set + </button> + </div> + </section> + {/* What the cut publishes blanked (posts redact) and the slur filter (posts slurs): their own commands. */} + <section data-redact={(view?.redact?.json?.redact ?? []).length}> + <h3 className="micro mb-1">Redacted words · {(view?.redact?.json?.redact ?? []).length}</h3> + <table className="w-full border-collapse"> + <tbody> + {(view?.redact?.json?.redact ?? []).map((x, i) => { + const t = typeof x === "string" ? { term: x } : x; + return ( + <tr key={`${t.term}:${i}`} data-redact-row={i + 1}> + <td className={cn(cell, "font-mono")}>{t.term}</td> + <td className={cn(cell, "text-muted")}> + {t.substring ? "inside words too " : ""} + {t.note ?? ""} + </td> + <td className={cn(cell, "text-right")}> + <button type="button" data-redact-remove={i + 1} disabled={busy} onClick={() => void post({ op: "redact-remove", n: i + 1 })} className={buttonVariants({ variant: "quiet", size: "sm" })} aria-label={`remove redaction ${i + 1}`}> + ✕ + </button> + </td> + </tr> + ); + })} + </tbody> + </table> + <div className="mt-1 flex flex-wrap items-center gap-1.5"> + <input data-redact-term="" value={term} onChange={(e) => setTerm(e.target.value)} placeholder="a word or phrase to blank" className={cn(input, "w-48")} /> + <button type="button" data-redact-add="" disabled={busy || !term.trim()} onClick={() => void post({ op: "redact-add", term }).then((ok) => ok && setTerm(""))} className={buttonVariants({ variant: "outline", size: "sm" })}> + Blank it + </button> + <span className="text-muted">a bar on the card, out of the read and the captions</span> + </div> + </section> + <section data-slurs={view?.slurs?.json?.on ? "on" : "off"}> + <h3 className="micro mb-1"> + Slur filter · {view?.slurs?.json?.on ? "on" : "off"} · {view?.slurs?.json?.total ?? 0} masked + </h3> + <div className="flex flex-wrap items-center gap-1.5"> + <button type="button" data-slurs-toggle="" disabled={busy || !view?.slurs?.json} onClick={() => void post({ op: "slurs", verb: view?.slurs?.json?.on ? "off" : "on" })} className={buttonVariants({ variant: view?.slurs?.json?.on ? "pressed" : "outline", size: "sm" })} aria-pressed={!!view?.slurs?.json?.on}> + {view?.slurs?.json?.on ? "On" : "Off"} + </button> + {( + [ + ["level", ["strong", "all"]], + ["visual", ["blackout", "placeholder"]], + ["voice", ["skip", "beep", "placeholder"]], + ] as const + ).map(([k, opts]) => ( + <label key={k} className="inline-flex items-center gap-1"> + {k} + <select data-slurs-knob={k} value={String((view?.slurs?.json as Record<string, unknown> | null | undefined)?.[k] ?? "")} disabled={busy} onChange={(e) => void post({ op: "slurs", verb: k, value: e.target.value })} className={input}> + {opts.map((o) => ( + <option key={o} value={o}> + {o} + </option> + ))} + </select> + </label> + ))} + </div> + <div className="mt-1 flex flex-wrap items-center gap-1.5"> + <input data-slurs-word="" value={slurWord} onChange={(e) => setSlurWord(e.target.value)} placeholder="a word" className={cn(input, "w-32")} /> + {(["add", "except", "remove"] as const).map((v) => ( + <button key={v} type="button" data-slurs-word-op={v} disabled={busy || !slurWord.trim()} onClick={() => void post({ op: "slurs", verb: v, value: slurWord }).then((ok) => ok && setSlurWord(""))} className={buttonVariants({ variant: "quiet", size: "sm" })}> + {v === "add" ? "Mask it" : v === "except" ? "Never mask it" : "Back to the list"} + </button> + ))} + <span className="text-muted"> + {view?.slurs?.json?.add ?? 0} added · {view?.slurs?.json?.except ?? 0} excepted + </span> + </div> + </section> + {/* The cut's narration mix (posts narrate --cut): what every post reads with unless it says otherwise. */} + <section className="lg:col-span-2" data-mix-cut=""> + <h3 className="micro mb-1">The cut's narration mix</h3> + <p className="m-0 font-mono text-[11px] text-text-2" data-mix-cut-now=""> + {Object.keys(view?.mix ?? {}).length ? JSON.stringify(view?.mix) : "the defaults"} + </p> + <div className="mt-1 flex flex-wrap items-center gap-1.5"> + <select data-mix-cut-key="" value={mixKey} onChange={(e) => setMixKey(e.target.value)} className={input}> + {["rate", "wet", "lead", "tail", "ramp", "linger", "pace", "duck", "engine", "voice", "follow", "follow.dim", "follow.ease", "lufs"].map((k) => ( + <option key={k} value={k}> + {k} + </option> + ))} + </select> + <input data-mix-cut-value="" value={mixValue} onChange={(e) => setMixValue(e.target.value)} placeholder="value (or default)" className={cn(input, "w-36 font-mono")} /> + <button type="button" data-mix-cut-set="" disabled={busy || !mixValue.trim()} onClick={() => void post({ op: "mix-cut", key: mixKey, value: mixValue.trim() }).then((ok) => ok && setMixValue(""))} className={buttonVariants({ variant: "outline", size: "sm" })}> + Set for the cut + </button> + </div> + </section> + {/* The whole cut's reads, long: steps of the queue (/jobs: their state, Retry, Cancel). */} + <section className="flex flex-wrap items-center gap-1.5 lg:col-span-2" data-narrate-all=""> + <span className="micro">every post</span> + <button type="button" data-narrate-all-queue="scripts" disabled={busy} onClick={() => void post({ op: "queue-narrate", what: "scripts" }).then((j) => setQueued((j?.json as { queued?: string } | null)?.queued ?? null))} className={buttonVariants({ variant: "outline", size: "sm" })} title="umtool posts narrate <p> --all --draft-scripts, as a queue step"> + Queue: draft every script + </button> + <button type="button" data-narrate-all-queue="takes" disabled={busy} onClick={() => void post({ op: "queue-narrate", what: "takes" }).then((j) => setQueued((j?.json as { queued?: string } | null)?.queued ?? null))} className={buttonVariants({ variant: "outline", size: "sm" })} title="umtool posts narrate <p> --all --take, as a queue step (resumable)"> + Queue: read every missing take + </button> + <button type="button" data-narrate-all-queue="context" disabled={busy} onClick={() => void post({ op: "queue-narrate", what: "context" }).then((j) => setQueued((j?.json as { queued?: string } | null)?.queued ?? null))} className={buttonVariants({ variant: "quiet", size: "sm" })} title="umtool posts context <p>, as a queue step: each item's quoted and replied-to posts from its capture"> + Queue: fill context from captures + </button> + <button type="button" data-narrate-all-queue="threads" disabled={busy} onClick={() => void post({ op: "queue-narrate", what: "threads" }).then((j) => setQueued((j?.json as { queued?: string } | null)?.queued ?? null))} className={buttonVariants({ variant: "quiet", size: "sm" })} title="umtool timeline <p> threads --write, as a queue step: each conversation's posts together"> + Queue: gather conversations + </button> + {queued && ( + <span className="text-text-2" data-narrate-all-queued={queued}> + queued {queued} —{" "} + <a href={jobsHref()} className="ink-link"> + its state on Jobs + </a> + </span> + )} + </section> + {error && ( + <p role="alert" className="m-0 text-reject-text lg:col-span-2" data-pronunciation-error=""> + {error} + </p> + )} + </div> + ); +} diff --git a/umtool/components/projects/RefetchButton.tsx b/umtool/components/projects/RefetchButton.tsx @@ -0,0 +1,41 @@ +"use client"; + +import Link from "next/link"; +import { useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { jobsHref } from "@/lib/hrefs"; + +// FETCH THIS WINDOW AGAIN (lane/ui-simplify, 5 Nov; terminal-only before: `umtool fetch <p> --refetch <clip>`): +// a window known bad -- a cut that froze, the wrong rendition -- evicted through the editor and fetched again, +// as a step of the queue (its state, Retry and Cancel on Jobs). POST /api/report/takes/tools {op: "queue-refetch"}. +export default function RefetchButton({ project, clip, take = null, disabled = false }: { project: string; clip: string; take?: string | null; disabled?: boolean }) { + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<{ queued?: string; error?: string } | null>(null); + const go = async () => { + setBusy(true); + const r = await fetch("/api/report/takes/tools", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, take, op: "queue-refetch", clip }), + }); + const j = (await r.json().catch(() => ({}))) as { queued?: string; error?: string }; + setBusy(false); + setSaid(r.ok ? j : { error: j.error ?? `HTTP ${r.status}` }); + }; + return ( + <span className="inline-flex flex-wrap items-center gap-1.5" data-refetch={clip}> + <button type="button" data-action="refetch" disabled={disabled || busy} onClick={() => void go()} className={buttonVariants({ variant: "quiet", size: "sm" })} title={`umtool fetch ${project} --refetch ${clip}${take ? ` --take ${take}` : ""}, as a queue step: the cached window evicted, then fetched again`}> + Fetch this window again + </button> + {said?.queued && ( + <span className="text-[11.5px] text-text-2" data-refetch-queued={said.queued}> + queued {said.queued} —{" "} + <Link href={jobsHref()} className="ink-link"> + Jobs + </Link> + </span> + )} + {said?.error && <span className="text-[11.5px] text-reject-text">{said.error}</span>} + </span> + ); +} diff --git a/umtool/components/projects/ReportProject.tsx b/umtool/components/projects/ReportProject.tsx @@ -8,6 +8,11 @@ import type { ProjectRef } from "@/lib/project-types"; import DeleteProject from "./DeleteProject"; import ReportTabBody, { reportCounts, reportStatus } from "./report/ReportTabBody"; import { readClipDetail } from "@/lib/projects/report.mjs"; +import path from "node:path"; +import { readNotes } from "@/lib/annotations/store.mjs"; +import { readWorkingCut } from "@/lib/report/workingCut.mjs"; +import ProjectPrimary, { latestWords, primaryStatus } from "./ProjectPrimary"; +import { RememberCut } from "@/components/shell/RecentCuts"; // --------------------------------------------------------------------------- // A report video, as a PIECE PAGE (plans/umtool-redesign.md, P4a-1). @@ -54,6 +59,13 @@ export default async function ReportProject({ const m = detail.manifest; const tab = tabOf(search, { noteTab: !search.tab ? await projectNoteTab(project.dir, search.note) : null }); const frame = await readPieceFrame(project); + // The head's one primary row (lane/ui-simplify): Play the newest take, on every tab, and the status line + // "▶ Play mid-14 38:56 · rendered 4 Nov" on the primary row, "0 open notes · …" in the status. + const [working, notes] = await Promise.all([ + readWorkingCut(project.dir).catch(() => null), + readNotes(path.join(project.dir, "notes.json")).catch(() => ({ doc: null })), + ]); + const openNotes = (notes.doc?.notes ?? []).filter((n: { status?: string }) => (n.status ?? "open") === "open").length; return ( <div className="flex h-full flex-col"> @@ -63,7 +75,8 @@ export default async function ReportProject({ tab={tab} tabs={PIECE_TABS.map((t) => ({ ...t, href: projectHref(project.id, { tab: t.id }) }))} counts={await reportCounts(detail, project.dir)} - note={reportStatus(detail)} + note={primaryStatus(working, openNotes, reportStatus(detail))} + primary={<ProjectPrimary project={project.id} detail={detail} latest={working?.latest?.id ?? null} words={latestWords(working)} />} more={ <> <span className="px-2 pb-1 pt-0.5 font-mono text-[11px] text-muted">{project.id}</span> @@ -71,6 +84,7 @@ export default async function ReportProject({ </> } > + <RememberCut project={project.id} title={typeof m.title === "string" && m.title ? m.title : project.id} /> <ReportTabBody project={project} detail={detail} search={search} tab={tab} frame={frame} /> </PieceFrame> </div> diff --git a/umtool/components/projects/TakeTools.tsx b/umtool/components/projects/TakeTools.tsx @@ -0,0 +1,232 @@ +"use client"; + +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useEffect, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { jobsHref, takeWalkHref } from "@/lib/hrefs"; +import { cn } from "@/lib/utils"; +import PlayLink from "./PlayLink"; + +// --------------------------------------------------------------------------- +// A TAKE's TOOLS that were terminal-only (slice C, 4 Nov), on its card and its +// walk (lane/ui-simplify, 5 Nov). Each is one POST /api/report/takes/tools, +// which runs the CLI's own function with --json: +// +// Check before render umtool lint <p> --take <t> +// New draft from this take umtool take <p> --id <t>-d<n> --draft --from <t> +// Add items from another umtool take <p> --id <t> --import-item <src>:<a,b> [--after|--before <e>] +// project [--dry-run]: Preview shows the plan, Import does it +// --------------------------------------------------------------------------- + +type Tools = { exit: number; report: Record<string, unknown> | null; said?: string; id?: string; error?: string }; + +async function tool(body: Record<string, unknown>): Promise<Tools> { + const r = await fetch("/api/report/takes/tools", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), cache: "no-store" }); + const j = (await r.json().catch(() => ({ error: `HTTP ${r.status}` }))) as Tools; + if (!r.ok && j.exit === undefined) return { exit: 1, report: null, error: j.error ?? `HTTP ${r.status}` }; + return j; +} + +/** Check before render: the manifest lint (and the files the posts name) on the take, or on the project's cut. */ +export function LintButton({ project, take = null, className }: { project: string; take?: string | null; className?: string }) { + const [busy, setBusy] = useState(false); + const [res, setRes] = useState<Tools | null>(null); + const rep = res?.report as { ok?: boolean; errors?: string[]; warnings?: string[]; entries?: number } | null | undefined; + return ( + <span className={cn("inline-flex flex-wrap items-center gap-1.5", className)} data-take-lint={take ?? ""} data-take-lint-state={res ? (rep?.ok ? "ok" : "errors") : busy ? "running" : "idle"}> + <button type="button" data-action="lint" disabled={busy} onClick={() => (setBusy(true), void tool({ project, take, op: "lint" }).then((r) => (setRes(r), setBusy(false))))} className={buttonVariants({ variant: "outline", size: "sm" })} title={`umtool lint ${project}${take ? ` --take ${take}` : ""}`}> + {busy ? "Checking…" : "Check before render"} + </button> + {res && (res.error || !rep) && <span className="text-[11.5px] text-reject-text">{res.error ?? res.said ?? "the check said nothing"}</span>} + {rep && ( + <span className={cn("text-[11.5px]", rep.ok ? "text-kept-text" : "text-reject-text")} data-take-lint-result={rep.ok ? "ok" : String(rep.errors?.length ?? 0)}> + {rep.ok ? `✓ ready to render · ${rep.entries ?? 0} entries` : `✕ ${rep.errors?.length ?? 0} error${rep.errors?.length === 1 ? "" : "s"}`} + {(rep.warnings?.length ?? 0) > 0 && ` · ${rep.warnings!.length} warning${rep.warnings!.length === 1 ? "" : "s"}`} + </span> + )} + {rep && ((rep.errors?.length ?? 0) > 0 || (rep.warnings?.length ?? 0) > 0) && ( + <ul className="m-0 basis-full list-disc space-y-0.5 pl-4 text-[11px]" data-take-lint-lines=""> + {(rep.errors ?? []).map((e, i) => ( + <li key={`e${i}`} className="text-reject-text"> + {e} + </li> + ))} + {(rep.warnings ?? []).slice(0, 8).map((w, i) => ( + <li key={`w${i}`} className="text-text-2"> + {w} + </li> + ))} + </ul> + )} + </span> + ); +} + +/** New draft from this take: its style and patch, a timeline of its own to walk and edit. */ +export function DraftFromButton({ project, take }: { project: string; take: string }) { + const router = useRouter(); + const [busy, setBusy] = useState(false); + const [res, setRes] = useState<Tools | null>(null); + const go = async () => { + setBusy(true); + const r = await tool({ project, take, op: "draft-from" }); + setRes(r); + setBusy(false); + if (r.exit === 0) router.refresh(); + }; + return ( + <span className="inline-flex flex-wrap items-center gap-1.5" data-take-draft-from={take}> + <button type="button" data-action="draft-from" disabled={busy} onClick={() => void go()} className={buttonVariants({ variant: "outline", size: "sm" })} title={`umtool take ${project} --id ${take}-d<n> --draft --from ${take}`}> + New draft from this take + </button> + {res?.exit === 0 && res.id && ( + <span className="text-[11.5px] text-text-2" data-take-drafted={res.id}> + draft <b className="font-mono">{res.id}</b>:{" "} + <Link href={takeWalkHref(project, res.id)} className="ink-link"> + walk it + </Link>{" "} + <PlayLink project={project} take={res.id} where="drafted" variant="icon" /> + </span> + )} + {res && res.exit !== 0 && <span className="text-[11.5px] text-reject-text">{res.error ?? res.said ?? "refused"}</span>} + </span> + ); +} + +type Entry = { id: string; type: string; words?: string }; + +/** Add items from another project: cloned into this take only, their files hard-linked in; Preview first. */ +export function ImportItems({ project, take }: { project: string; take: string }) { + const router = useRouter(); + const [open, setOpen] = useState(false); + const [source, setSource] = useState(""); + const [items, setItems] = useState(""); + const [where, setWhere] = useState<"auto" | "after" | "before">("auto"); + const [anchor, setAnchor] = useState(""); + const [entries, setEntries] = useState<Entry[]>([]); + const [projects, setProjects] = useState<string[]>([]); + const [busy, setBusy] = useState(false); + const [plan, setPlan] = useState<Tools | null>(null); + const [done, setDone] = useState<Tools | null>(null); + useEffect(() => { + if (!open) return; + void fetch(`/api/report/takes/timeline?project=${encodeURIComponent(project)}&take=${encodeURIComponent(take)}`, { cache: "no-store" }) + .then((r) => r.json()) + .then((j) => setEntries(Array.isArray(j.timeline) ? j.timeline : [])) + .catch(() => {}); + void fetch("/api/jump", { cache: "no-store" }) + .then((r) => r.json()) + .then((j) => setProjects(((j.pieces ?? []) as { id: string; kind: string }[]).filter((p) => p.kind === "project" && p.id.startsWith("p:")).map((p) => p.id.slice(2)))) + .catch(() => {}); + }, [open, project, take]); + const refs = items.trim() ? `${source.trim()}:${items.replace(/\s+/g, "")}` : ""; + const run = async (dryRun: boolean) => { + setBusy(true); + const r = await tool({ project, take, op: "import", refs, ...(where === "after" && anchor ? { after: anchor } : where === "before" && anchor ? { before: anchor } : {}), dryRun }); + setBusy(false); + if (dryRun) { + setPlan(r); + setDone(null); + } else { + setDone(r); + setPlan(null); + if (r.exit === 0) router.refresh(); + } + }; + const input = "rounded-[3px] border border-seam-2 bg-ground px-1.5 py-[3px] text-[11.5px] text-text outline-none focus:border-signal"; + const rows = (t: Tools | null) => ((t?.report as { items?: { id: string; action: string; at?: { index?: number; after?: string | null; before?: string | null } }[] } | null)?.items ?? []); + return ( + <span className="inline-flex basis-full flex-col gap-1.5" data-take-import={take}> + <button type="button" data-action="import-open" aria-expanded={open} onClick={() => setOpen((o) => !o)} className={cn(buttonVariants({ variant: open ? "pressed" : "outline", size: "sm" }), "self-start")}> + Add items from another project + </button> + {open && ( + <span className="flex flex-wrap items-center gap-1.5 rounded border border-seam p-2 text-[11.5px]"> + <input data-import-source="" list={`import-projects-${take}`} value={source} onChange={(e) => setSource(e.target.value)} placeholder="project (e.g. emberparadox/mr-obvious-unhinged)" className={cn(input, "w-72 font-mono")} /> + <datalist id={`import-projects-${take}`}> + {projects.filter((p) => p !== project).map((p) => ( + <option key={p} value={p} /> + ))} + </datalist> + <input data-import-items="" value={items} onChange={(e) => setItems(e.target.value)} placeholder="item ids, comma-separated" className={cn(input, "w-64 font-mono")} /> + <select data-import-where="" value={where} onChange={(e) => setWhere(e.target.value as typeof where)} className={input}> + <option value="auto">by date (else at the end)</option> + <option value="after">after</option> + <option value="before">before</option> + </select> + {where !== "auto" && ( + <select data-import-anchor="" value={anchor} onChange={(e) => setAnchor(e.target.value)} className={cn(input, "max-w-64")}> + <option value="">(pick an entry)</option> + {entries.map((e, i) => ( + <option key={`${e.id}:${i}`} value={e.id}> + {i + 1}. {e.id} + {e.words ? ` · ${e.words.slice(0, 30)}` : ""} + </option> + ))} + </select> + )} + <button type="button" data-action="import-preview" disabled={busy || !refs || !source.trim()} onClick={() => void run(true)} className={buttonVariants({ variant: "outline", size: "sm" })}> + Preview + </button> + <button type="button" data-action="import-go" disabled={busy || !refs || !source.trim()} onClick={() => void run(false)} className={buttonVariants({ variant: "go", size: "sm" })}> + Import into {take} + </button> + </span> + )} + {[plan, done].map((t, k) => + t ? ( + <span key={k} className="text-[11.5px]" data-import-result={k === 0 ? "plan" : "done"} data-import-exit={t.exit}> + {t.exit !== 0 ? ( + <span className="text-reject-text">{t.error ?? t.said ?? "refused"}</span> + ) : ( + <> + <span className="text-text-2">{k === 0 ? "would do: " : "done: "}</span> + {rows(t).map((r) => ( + <span key={r.id} className="mr-2 font-mono" data-import-row={r.id}> + {r.id} {r.action} + {r.at?.after ? ` after ${r.at.after}` : r.at?.before ? ` before ${r.at.before}` : typeof r.at?.index === "number" ? ` at ${r.at.index}` : ""} + </span> + ))} + </> + )} + </span> + ) : null, + )} + </span> + ); +} + +/** Check the joins of a rendered take (umtool check-joins), queued: its table is the step's log on Jobs. */ +export function CheckJoinsButton({ project, take }: { project: string; take: string }) { + const [busy, setBusy] = useState(false); + const [res, setRes] = useState<(Tools & { queued?: string }) | null>(null); + return ( + <span className="inline-flex flex-wrap items-center gap-1.5" data-take-check-joins={take}> + <button type="button" data-action="check-joins" disabled={busy} onClick={() => (setBusy(true), void tool({ project, take, op: "queue-check-joins" }).then((r) => (setRes(r), setBusy(false))))} className={buttonVariants({ variant: "outline", size: "sm" })} title={`umtool check-joins ${project} --take ${take}, as a queue step`}> + Check the joins + </button> + {res?.queued && ( + <span className="text-[11.5px] text-text-2" data-take-check-joins-queued={res.queued}> + queued {res.queued} —{" "} + <Link href={jobsHref()} className="ink-link"> + its table on Jobs + </Link> + </span> + )} + {res && !res.queued && <span className="text-[11.5px] text-reject-text">{res.error ?? res.said ?? "refused"}</span>} + </span> + ); +} + +/** The take's tools, as a take card's or a take walk's row. */ +export default function TakeTools({ project, take, editable = true, rendered = false }: { project: string; take: string; editable?: boolean; rendered?: boolean }) { + return ( + <span className="flex flex-wrap items-start gap-1.5" data-take-tools={take}> + <LintButton project={project} take={take} /> + {rendered && <CheckJoinsButton project={project} take={take} />} + <DraftFromButton project={project} take={take} /> + {editable && <ImportItems project={project} take={take} />} + </span> + ); +} diff --git a/umtool/components/projects/TakeWalkPage.tsx b/umtool/components/projects/TakeWalkPage.tsx @@ -8,6 +8,10 @@ import { isTakeId } from "@/lib/report/takes.mjs"; import { walkOf } from "@/lib/report/walkData.mjs"; import type { ProjectRef } from "@/lib/project-types"; import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell"; +import PlayLink from "./PlayLink"; +import { AddClipToggle } from "./AddClip"; +import TakeTools from "./TakeTools"; +import { Options } from "@/components/ui/disclosure"; import TakeActions from "./TakeActions"; import BenchPrepPanel from "./report/BenchPrepPanel"; @@ -76,15 +80,24 @@ export default async function TakeWalkPage({ {all ? "Nothing fetched to walk." : "Every fetched clip has a verdict."} </span> )} + <PlayLink project={project.id} take={take} where="walk" variant="button" /> <Link href={takeWalkHref(project.id, take, { all: !all })} data-take-walk-all={all ? "1" : "0"} className="text-[12px] ink-link"> {all ? "walk only the clips needing a verdict" : "walk every clip (judged ones too)"} </Link> </div> + {w.take?.editable && ( + <div className="flex flex-wrap items-start gap-2"> + <AddClipToggle project={project.id} take={take} where="take" /> + </div> + )} {/* The take's own prep: its clips' excerpts and waveforms made before the walk opens them. */} <BenchPrepPanel project={project.id} take={take} /> {w.take?.editable && ( <TakeActions project={project.id} take={take} draft={!!w.take?.draft} walkHref={null} edited compact /> )} + <Options id="take-walk" hint="check before render · new draft from it · add items from another project"> + <TakeTools project={project.id} take={take} editable={!!w.take?.editable} /> + </Options> </section> <table data-take-walk-clips="" className="w-full border-collapse text-[12px]"> <thead> @@ -106,6 +119,7 @@ export default async function TakeWalkPage({ {c.id} </Link> {c.onWalk && <span className="ml-1 text-meter" title="on the walk">→</span>} + <PlayLink project={project.id} take={take} clip={c.id} where="walk-row" variant="icon" /> </td> <td className="num py-1 pr-2 whitespace-nowrap"> {hms(c.start)}–{hms(c.end)} diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx @@ -10,12 +10,15 @@ import TimedNotes from "@/components/notes/TimedNotes"; import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; import { fmtAgo, fmtBytes } from "@/lib/format"; +import { cn } from "@/lib/utils"; import { playHref, takeWalkHref } from "@/lib/hrefs"; import RenderRecord from "@/components/queue/RenderRecord"; import type { RenderView } from "@/lib/queue/view"; import { BenchBody, VerdictBar } from "./bench/BenchShell"; import { startTakeJob } from "./NewTakePanel"; import TakeActions from "./TakeActions"; +import TakeTools from "./TakeTools"; +import { Advanced, Options, PanelSlot } from "@/components/ui/disclosure"; import { CancelRender, CancelSaidLine, CompareWith, ForkVariant, TakeWorkDirs, type CancelSaid, type CompareOption, type WorkDirs } from "./TakeVariants"; // The takes of one project, a group at a time, every preview on screen at once. @@ -301,8 +304,12 @@ export default function TakesBench({ <BenchBody verdict={verdictBar}> <div className="space-y-6"> {head} + {/* Renders in progress, failed or cancelled before a take was made: status, in the open. */} {workDirs && <TakeWorkDirs project={project} dirs={workDirs} ready={ready} />} - <WorkSummary project={project} work={work} error={workError} ready={ready} onFreed={() => void loadWork()} /> + {/* The takes' work files (what the renders left, what can be freed): rare, so Advanced (lane/ui-simplify). */} + <Advanced id="takes" label="Work files" hint="what the renders left, and what can be freed"> + <WorkSummary project={project} work={work} error={workError} ready={ready} onFreed={() => void loadWork()} /> + </Advanced> {groups.map((g) => { const tally = VERDICTS.map((v) => [v.id, g.takes.filter((t) => verdicts[t.id]?.verdict === v.id).length] as const) .filter(([, n]) => n > 0) @@ -754,10 +761,11 @@ function TakeCard({ <Link href={playHref(project, { take: t.id })} data-play-take={t.id} - className="ml-auto text-[11px] ink-link" + data-play-link="take-card" + className={cn(buttonVariants({ variant: "outline", size: "sm" }), "ml-auto")} title="play this take's whole cut in the browser, in its final look, without rendering it" > - Play + ▶ Play </Link> <button type="button" @@ -824,31 +832,8 @@ function TakeCard({ compact /> )} - <div className="flex flex-wrap items-center gap-1.5"> - {!t.draft && ( - <button - type="button" - data-action="pick" - disabled={!ready || busy} - className={buttonVariants({ size: "sm" })} - title="the manifest this take was RENDERED from, over the project's" - onClick={() => void pick(false)} - > - Use this take - </button> - )} - {t.baseHash && !t.draft && ( - <button - type="button" - data-action="rebuild" - disabled={!ready || busy} - className={buttonVariants({ size: "sm" })} - onClick={() => void rebuild()} - > - Rebuild - </button> - )} - </div> + {(t.holds ?? []).some((h) => h.startsWith("it is rendering")) && <CancelRender project={project} take={t.id} ready={ready} onSaid={setCancelSaid} />} + <CancelSaidLine said={cancelSaid} /> {pickState?.stale && ( <div data-take-stale="" className="flex flex-wrap items-center gap-1.5 text-[11.5px] text-doubt-text"> <span>{pickState.stale}.</span> @@ -873,43 +858,73 @@ function TakeCard({ )} </p> )} - <TakeWorkLine project={project} work={work} ready={ready} onFreed={onFreed} /> - {(t.holds ?? []).some((h) => h.startsWith("it is rendering")) && <CancelRender project={project} take={t.id} ready={ready} onSaid={setCancelSaid} />} - <CancelSaidLine said={cancelSaid} /> - <div className="flex flex-wrap items-center gap-1.5" data-take-variants={t.id}> - <ForkVariant project={project} take={t.id} ready={ready} /> - <CompareWith project={project} take={t.id} options={compareOptions} /> - </div> - <div className="flex flex-wrap items-center gap-1.5 text-[11px]" data-take-housekeeping={t.id}> - {superseded ? ( - <button type="button" data-action="unsupersede" disabled={!ready || busy} onClick={() => void housekeeping({ op: "unsupersede" })} className={buttonVariants({ size: "sm" })}> - Not superseded + {/* Everything but play, judge, walk and render, folded (lane/ui-simplify): Options the common, Advanced the rare. */} + <Options id="take-card" hint="use · rebuild · check · draft · import · fork · compare"> + <div className="flex flex-wrap items-center gap-1.5"> + {!t.draft && ( + <button + type="button" + data-action="pick" + disabled={!ready || busy} + className={buttonVariants({ size: "sm" })} + title="the manifest this take was RENDERED from, over the project's" + onClick={() => void pick(false)} + > + Use this take </button> - ) : ( - <> - <select data-take-superseded-by={t.id} value={supBy} disabled={!ready || busy || !!verdict?.picked} onChange={(e) => setSupBy(e.target.value)} className="rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 text-[11px]" title={verdict?.picked ? "the picked take is not superseded" : "which take replaces this one"}> - <option value="">by (any later take)</option> - {others.map((o) => ( - <option key={o.id} value={o.id}> - {o.id} - </option> - ))} - </select> - <button type="button" data-action="supersede" disabled={!ready || busy || !!verdict?.picked} onClick={() => void housekeeping({ op: "supersede", by: supBy || null })} className={buttonVariants({ size: "sm" })}> - Mark superseded + )} + {t.baseHash && !t.draft && ( + <button + type="button" + data-action="rebuild" + disabled={!ready || busy} + className={buttonVariants({ size: "sm" })} + onClick={() => void rebuild()} + > + Rebuild </button> - </> - )} - </div> - <div className="flex flex-wrap"> - <DeletePlan - label={`Delete take ${t.id}`} - subject={`take ${t.id}`} - endpoint="/api/report/takes/delete" - body={{ project, take: t.id }} - onDone={() => router.refresh()} - /> - </div> + )} + </div> + <TakeTools project={project} take={t.id} editable={walkable} rendered={!!t.builtAt && !t.draft} /> + <div className="flex flex-wrap items-center gap-1.5" data-take-variants={t.id}> + <ForkVariant project={project} take={t.id} ready={ready} /> + <CompareWith project={project} take={t.id} options={compareOptions} /> + </div> + <PanelSlot name="take-card-vertical" /> + </Options> + <Advanced id="take-card" hint="supersede · delete · work files"> + <div className="flex flex-wrap items-center gap-1.5 text-[11px]" data-take-housekeeping={t.id}> + {superseded ? ( + <button type="button" data-action="unsupersede" disabled={!ready || busy} onClick={() => void housekeeping({ op: "unsupersede" })} className={buttonVariants({ size: "sm" })}> + Not superseded + </button> + ) : ( + <> + <select data-take-superseded-by={t.id} value={supBy} disabled={!ready || busy || !!verdict?.picked} onChange={(e) => setSupBy(e.target.value)} className="rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 text-[11px]" title={verdict?.picked ? "the picked take is not superseded" : "which take replaces this one"}> + <option value="">by (any later take)</option> + {others.map((o) => ( + <option key={o.id} value={o.id}> + {o.id} + </option> + ))} + </select> + <button type="button" data-action="supersede" disabled={!ready || busy || !!verdict?.picked} onClick={() => void housekeeping({ op: "supersede", by: supBy || null })} className={buttonVariants({ size: "sm" })}> + Mark superseded + </button> + </> + )} + </div> + <div className="flex flex-wrap"> + <DeletePlan + label={`Delete take ${t.id}`} + subject={`take ${t.id}`} + endpoint="/api/report/takes/delete" + body={{ project, take: t.id }} + onDone={() => router.refresh()} + /> + </div> + <TakeWorkLine project={project} work={work} ready={ready} onFreed={onFreed} /> + </Advanced> {t.previewSize != null && ( <TimedNotes notes={notes} file={`takes/${t.id}/${t.preview}`} video={el} take={t.id} resolveProject={project} /> )} diff --git a/umtool/components/projects/TakesPage.tsx b/umtool/components/projects/TakesPage.tsx @@ -13,6 +13,7 @@ import NewTakePanel from "./NewTakePanel"; import TakesBench, { type Take, type TakeVerdict } from "./TakesBench"; import { LatestLine } from "./review/WhatPlays"; import { readWorkingCut } from "@/lib/report/workingCut.mjs"; +import PlayLink from "./PlayLink"; import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs"; import { readCancelled, takeWorkDirs } from "@/lib/report/takeCancel.mjs"; import { variantFamily } from "@/lib/report/variantFork.mjs"; @@ -154,8 +155,9 @@ export default async function TakesPage({ project }: { project: ProjectRef }) { workDirs={workDirs} head={ <> - <p className="m-0 text-[12.5px]" data-takes-working=""> + <p className="m-0 flex flex-wrap items-center gap-2 text-[12.5px]" data-takes-working=""> <LatestLine project={project.id} working={working} /> + {working?.latest && <PlayLink project={project.id} where="takes-head" variant="button" label={`▶ Play ${working.latest.id}`} />} </p> {(parentOf || variants.length > 0) && ( <p className="m-0 text-[12px] text-text-2" data-takes-family={family.members.length}> diff --git a/umtool/components/projects/TimelineEditor.tsx b/umtool/components/projects/TimelineEditor.tsx @@ -141,8 +141,8 @@ export function TimelineList({ project, count, groupCount = 0, children }: { pro <button type="button" data-testid="timeline-undo" disabled={busy} onClick={() => void run("undo", {})} className={buttonVariants({ size: "sm" })}> Undo last edit </button> - <button type="button" data-testid="timeline-add-clip" aria-expanded={adding} disabled={busy} onClick={() => setAdding((a) => !a)} className={buttonVariants({ size: "sm" })}> - Add clip + <button type="button" data-testid="timeline-add-clip" aria-expanded={adding} disabled={busy} onClick={() => setAdding((a) => !a)} className={buttonVariants({ variant: "quiet", size: "sm" })} title="type a clip as <channel>/<video>@<start>-<end> (+ Add a clip above finds the moment for you)"> + Add by spec </button> <span className="text-[var(--color-dim)]"> drag ⠿ or <kbd>alt</kbd>+<kbd>↑</kbd>/<kbd>↓</kbd> to move{sections.length > 1 ? "; drag a section bar onto a clip to move its boundary, a clip onto a bar to move it into that section" : ""} diff --git a/umtool/components/projects/inTake.tsx b/umtool/components/projects/inTake.tsx @@ -0,0 +1,16 @@ +"use client"; + +import { createContext, useContext } from "react"; + +// "EDIT THIS TAKE ONLY" on the post bench (lane/ui-simplify, 5 Nov): the take every write of the bench is scoped +// to (`?inTake=<t>`; the routes run the writer under takeScope.mjs withTakeScope, as `umtool posts set-item … --in-take` +// does), or null for the project's cut. A writer adds `...inTakeBody(take)` to its POST body. +const Ctx = createContext<string | null>(null); + +export function InTakeProvider({ take, children }: { take: string | null; children: React.ReactNode }) { + return <Ctx.Provider value={take}>{children}</Ctx.Provider>; +} + +export const useInTake = () => useContext(Ctx); + +export const inTakeBody = (take: string | null) => (take ? { inTake: take } : {}); diff --git a/umtool/components/projects/playable.ts b/umtool/components/projects/playable.ts @@ -0,0 +1,21 @@ +import { resolveProjectPath } from "@/lib/projects"; +import { playHref } from "@/lib/hrefs"; + +// Which pieces have a Play view (a report video), for surfaces outside +// components/projects/ that name a piece -- the Inbox's cards -- and may not +// name a kind themselves (the registry rule: kind ids stay in lib/projects/ +// and components/projects/). `p:<project>` → its Play address, at the note +// when the card's action points at one; null for anything else. +export async function playHrefOfPiece(piece: string | null, actionHref?: string | null): Promise<string | null> { + if (!piece || !piece.startsWith("p:")) return null; + const id = piece.slice(2); + const r = await resolveProjectPath(id.split("/")).catch(() => null); + if (!r || !("project" in r) || !r.project || r.rest.length || r.project.kind !== "report-video") return null; + let note: string | null = null; + try { + note = actionHref ? new URL(actionHref, "http://umtool").searchParams.get("note") : null; + } catch { + note = null; + } + return playHref(r.project.id, { note }); +} diff --git a/umtool/components/projects/reel/ReelCutPanel.tsx b/umtool/components/projects/reel/ReelCutPanel.tsx @@ -1,5 +1,6 @@ "use client"; +import { Options } from "@/components/ui/disclosure"; import Link from "next/link"; import { useCallback, useEffect, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; @@ -71,10 +72,15 @@ export default function ReelCutPanel({ project, reel }: { project: string; reel: }; }, [job, load]); + // The cut's Options (lane/ui-simplify): umtool trailer's --finale, --out and --dry-run. + const [finaleS, setFinaleS] = useState(""); + const [outName, setOutName] = useState(""); + const [dryRun, setDryRun] = useState(false); + const cutOptions = { ...(Number(finaleS) > 0 ? { finale: Number(finaleS) } : {}), ...(outName.trim() ? { out: outName.trim() } : {}), ...(dryRun ? { dryRun: true } : {}) }; const cut = async () => { if (!view?.take) return; setError(null); - const r = await fetch("/api/report/reel", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, reel, take: view.take.id }) }); + const r = await fetch("/api/report/reel", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, reel, take: view.take.id, ...cutOptions }) }); const j = await r.json().catch(() => ({})); if (!r.ok) { setError(String(j.error ?? `HTTP ${r.status}`)); @@ -132,6 +138,21 @@ export default function ReelCutPanel({ project, reel }: { project: string; reel: <button type="button" data-reel-cut="" disabled={running || !!view.busy || !(view.beats || view.introAsked)} onClick={() => void cut()} className={buttonVariants({ size: "sm" })} title={view.busy ? `the runner is busy: ${view.busy}` : `umtool trailer ${project} --reel ${reel} --take ${t}`}> {running ? "Cutting…" : "Cut the trailer"} </button> + <Options id="reel-cut" hint="finale · file name · dry run"> + <label className="inline-flex items-center gap-1"> + close on the master's last + <input data-reel-finale="" value={finaleS} onChange={(e) => setFinaleS(e.target.value.replace(/[^0-9.]/g, ""))} placeholder="0" className="w-12 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 font-mono text-[11px]" /> + s + </label> + <label className="inline-flex items-center gap-1"> + file name + <input data-reel-out="" value={outName} onChange={(e) => setOutName(e.target.value)} placeholder={`${reel} (default)`} className="w-36 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 font-mono text-[11px]" /> + </label> + <label className="inline-flex items-center gap-1"> + <input type="checkbox" data-reel-dry-run="" checked={dryRun} onChange={(e) => setDryRun(e.target.checked)} /> + dry run (the mapping only, in the log) + </label> + </Options> {running && ( <button type="button" data-reel-cancel="" onClick={() => void cancel()} className={buttonVariants({ variant: "quiet", size: "sm" })}> Cancel diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -12,6 +12,12 @@ import { narrationRecordHref, postBenchHref, clipBenchHref, clipDeckHref, clipEd import { readTrailerBeats } from "@/lib/report/trailerBeats.mjs"; import { montageClipsOf, momentKeysOf, readRulingsState } from "@/lib/report/montageRulings.mjs"; import FetchUnfetchedButton from "../FetchUnfetchedButton"; +import PlayLink from "../PlayLink"; +import { AddClipToggle } from "../AddClip"; +import { Advanced, Options } from "@/components/ui/disclosure"; +import PronunciationPanel from "../PronunciationPanel"; +import AddPosts from "../AddPosts"; +import { LintButton } from "../TakeTools"; import TightWindowsPanel from "./TightWindowsPanel"; import { clipRecord, storedUrlOf } from "@/lib/clips/stored"; import { Fragment } from "react"; @@ -71,6 +77,9 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor ) ).filter(Boolean).length; const walkStart = (readiness.readyIds[0] as string | undefined) ?? clips[0]?.id; + // Add posts (posts reel) leads on a cut of posts or an empty one; on a cut of clips it waits under Options. + const postsFirst = entries.length === 0 || entries.some((x) => x.kind === "post"); + const postChannels = [...new Set(entries.filter((x) => x.kind === "post" && typeof x.post === "string").map((x) => String(x.post).split("/")[0]))]; const showAll = search.all === "1"; // The candidates inbox (UI notes item 14): its panel once a sweep has proposed something; until // then one line in the timeline's heading says how proposals come in (no panel, no height). @@ -205,6 +214,7 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor <span className="num micro ml-auto" data-post-seconds=""> {postItemSeconds(e).toFixed(1)}s{typeof e.hold === "number" ? " (hold)" : ""} </span> + <PlayLink project={project.id} clip={e.id} where="row" variant="icon" /> <Link href={postBenchHref(project.id, e.id)} className="ink-link text-[11px]" data-post-bench-link={e.id}> bench </Link> @@ -232,6 +242,7 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor {e.heading ?? e.title ?? e.label ?? ""} </span> {e.seconds != null && <span className="num micro ml-auto">{e.seconds}s</span>} + <PlayLink project={project.id} clip={e.id} where="row" variant="icon" className={e.seconds != null ? "" : "ml-auto"} /> <div className="basis-full"> <RowNotes id={e.id} project={project.id} /> </div> @@ -308,6 +319,7 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor </Pill> )} <span className="ml-auto flex items-center gap-2"> + <PlayLink project={project.id} clip={e.id} where="row" variant="icon" /> {mixHref(e) ? ( <Link href={mixHref(e)!} @@ -398,38 +410,18 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor ready {readiness.ready} of {readiness.needing} needing judgement </span> </span> - {/* The bench's first-open work (a long recording's excerpt, the - waveform), made ahead in the background (lib/report/benchPrep.mjs). */} - <BenchPrepPanel project={project.id} /> </div> )} {/* The whole cut played in the browser in its final look, no render (the Play view). */} - {clips.length > 0 && ( + {entries.length > 0 && ( <Link href={playHref(project.id)} data-play-cut-link="" className={buttonVariants({ size: "lg" })} title="play the whole cut here, chrome and all, without rendering it; notes at the playhead"> Play the cut </Link> )} - {/* A montage's instances, ruled by ear before a render (release 34). */} - {montage.length > 0 && ( - <Link - href={clipDeckHref(project.id)} - data-clip-deck-link={unruled} - className={buttonVariants({ size: "lg" })} - > - Clips — {unruled ? `${unruled} of ${montage.length} to rule` : `${montage.length} ruled`} - </Link> - )} - {/* Any other cut's clips -- an assistant's above all -- adjusted by a person (release 35 C2). */} - {montage.length === 0 && clips.length > 0 && ( - <Link - href={clipEditorHref(project.id)} - data-clip-editor-link={assisted.length} - className={buttonVariants({ size: "lg" })} - > - Clip editor — {clips.length} clip{clips.length === 1 ? "" : "s"} - {assisted.length ? ` · ${assisted.length} by the assistant${assistedByYou ? `, ${assistedByYou} edited by you` : ""}` : ""} - </Link> - )} + {/* Add a clip, as one flow (lane/ui-simplify): find, in/out on the cues, place, add, fetched. */} + <AddClipToggle project={project.id} where="cut" open={search.add === "1"} className="self-center" /> + {/* A cut of posts (or an empty one): the archive's posts it does not play yet (posts reel); else under Options. */} + {postsFirst && <AddPosts project={project.id} channels={postChannels} />} {/* Alternative renders of part of the cut, judged on their own page -- where the first one is made, too (release 33's take maker). */} {takes.exists ? ( @@ -445,37 +437,84 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor Make takes </Link> )} - {/* The trailer's beats: the running length against the platform's limit (UI notes item 11). */} - {clips.length > 0 && ( - <Link href={trailerHref(project.id)} data-trailer-link={trailerBeats ?? ""} className={buttonVariants({ variant: trailerBeats ? "outline" : "quiet", size: trailerBeats ? "lg" : "sm" })}> - {trailerBeats ? `Trailer — ${trailerBeats} beat${trailerBeats === 1 ? "" : "s"}` : trailerBeats === null ? "Trailer (beats file unreadable)" : "Trailer beats"} - </Link> - )} - {/* Walk a take: the drafts first -- a draft exists to be walked before it is rendered. */} - {takes.takes.some((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash) && ( - <span data-walk-takes="" className="flex flex-wrap items-center gap-1.5 text-[11.5px]"> - <span className="micro">walk a take</span> - {[...takes.takes] - .filter((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash) - .sort((a: { draft?: boolean }, b: { draft?: boolean }) => Number(!!b.draft) - Number(!!a.draft)) - .slice(0, 6) - .map((t: { id: string; label: string; draft?: boolean }) => ( - <Link key={t.id} href={takeWalkHref(project.id, t.id)} data-walk-take={t.id} className="ink-link" title={t.label}> - {t.id} - {t.draft ? " (draft)" : ""} - </Link> - ))} - </span> - )} - {clips.length > 0 && ( - <VoiceMatchPanel - project={project.id} - summary={voiceMatchSummary(voices)} - /> + </div> + {/* Everything else, folded (lane/ui-simplify): Options the common, Advanced the rare; open state remembered per viewer. */} + <div className="flex flex-wrap items-start gap-x-4 gap-y-1.5" data-cut-panels=""> + <Options id="cut" hint="clip editor · trailer · walk a take · fetch · check"> + {!postsFirst && <AddPosts project={project.id} channels={postChannels} />} + {/* Check before render, on the cut itself (umtool lint <p>): the build's lint and the files its posts name. */} + {entries.length > 0 && <LintButton project={project.id} />} + {/* A montage's instances, ruled by ear before a render (release 34). */} + {montage.length > 0 && ( + <Link + href={clipDeckHref(project.id)} + data-clip-deck-link={unruled} + className={buttonVariants({ size: "lg" })} + > + Clips — {unruled ? `${unruled} of ${montage.length} to rule` : `${montage.length} ruled`} + </Link> + )} + {/* Any other cut's clips -- an assistant's above all -- adjusted by a person (release 35 C2). */} + {montage.length === 0 && clips.length > 0 && ( + <Link + href={clipEditorHref(project.id)} + data-clip-editor-link={assisted.length} + className={buttonVariants({ size: "lg" })} + > + Clip editor — {clips.length} clip{clips.length === 1 ? "" : "s"} + {assisted.length ? ` · ${assisted.length} by the assistant${assistedByYou ? `, ${assistedByYou} edited by you` : ""}` : ""} + </Link> + )} + {/* The trailer's beats: the running length against the platform's limit (UI notes item 11). */} + {clips.length > 0 && ( + <Link href={trailerHref(project.id)} data-trailer-link={trailerBeats ?? ""} className={buttonVariants({ variant: trailerBeats ? "outline" : "quiet", size: trailerBeats ? "lg" : "sm" })}> + {trailerBeats ? `Trailer — ${trailerBeats} beat${trailerBeats === 1 ? "" : "s"}` : trailerBeats === null ? "Trailer (beats file unreadable)" : "Trailer beats"} + </Link> + )} + {/* Walk a take: the drafts first -- a draft exists to be walked before it is rendered. */} + {takes.takes.some((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash) && ( + <span data-walk-takes="" className="flex flex-wrap items-center gap-1.5 text-[11.5px]"> + <span className="micro">walk a take</span> + {[...takes.takes] + .filter((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash) + .sort((a: { draft?: boolean }, b: { draft?: boolean }) => Number(!!b.draft) - Number(!!a.draft)) + .slice(0, 6) + .map((t: { id: string; label: string; draft?: boolean }) => ( + <span key={t.id} className="inline-flex items-center"> + <Link href={takeWalkHref(project.id, t.id)} data-walk-take={t.id} className="ink-link" title={t.label}> + {t.id} + {t.draft ? " (draft)" : ""} + </Link> + <PlayLink project={project.id} take={t.id} where="walk-chip" variant="icon" /> + </span> + ))} + </span> + )} + {fetchBody && <FetchWindowsPanel project={project.id} items={fetchBody.items} skipped={fetchBody.skipped} lastRun={fetchBody.lastRun} />} + </Options> + {/* A cut of posts: what the voices say (the lexicon) and who reads whom (the voice map). */} + {entries.some((x) => x.kind === "post") && ( + <Options id="cut-reads" label="Reads and voices" hint="pronunciation · voice map · try it"> + <PronunciationPanel project={project.id} /> + </Options> )} - {fetchBody && <FetchWindowsPanel project={project.id} items={fetchBody.items} skipped={fetchBody.skipped} lastRun={fetchBody.lastRun} />} - {/* Tight windows: each clip to its sentence, for review (UI notes item 4) -- a button until pressed. */} - {clips.length > 0 && <TightWindowsPanel project={project.id} />} + <Advanced id="cut" hint="voices · tight windows · bench prep"> + {clips.length > 0 && ( + <VoiceMatchPanel + project={project.id} + summary={voiceMatchSummary(voices)} + /> + )} + {/* Tight windows: each clip to its sentence, for review (UI notes item 4) -- a button until pressed. */} + {clips.length > 0 && <TightWindowsPanel project={project.id} />} + {clips.length > 0 && ( + <div className="basis-full"> + {/* The bench's first-open work (a long recording's excerpt, the + waveform), made ahead in the background (lib/report/benchPrep.mjs). */} + <BenchPrepPanel project={project.id} /> + </div> + )} + </Advanced> </div> {/* --- the timeline --------------------------------------------- */} diff --git a/umtool/components/projects/report/DeliverTab.tsx b/umtool/components/projects/report/DeliverTab.tsx @@ -5,6 +5,7 @@ import DeliverSection from "../DeliverSection"; import PodcastExport from "../PodcastExport"; import ShortsList from "./ShortsList"; import VariantsPanel from "./VariantsPanel"; +import OutputFiles from "./OutputFiles"; import type { ReportTabProps } from "./shared"; // The Deliver tab: the deliver panel (cuts, share batches, rulings applied, @@ -29,6 +30,8 @@ export default async function DeliverTab({ project, detail }: ReportTabProps) { {/* After the build chain, because that is the order the work happens in: the video is one deliverable and the written report with its own clip files is the other, and both wait on the same walk. */} + {/* The rendered files, as local paths with Copy (lane/ui-simplify): the newest take's first. */} + <OutputFiles project={project.id} dir={project.dir} /> <DeliverSection project={project} manifest={m} entries={entries} /> {/* --- the shorts: one clip each, 1080x1920 (release 36) ---------- */} diff --git a/umtool/components/projects/report/OutputFiles.tsx b/umtool/components/projects/report/OutputFiles.tsx @@ -0,0 +1,78 @@ +import { readdir, stat } from "node:fs/promises"; +import path from "node:path"; +import CopyButton from "@/components/CopyButton"; +import { fmtBytes } from "@/lib/format"; +import { latestWorkingTake } from "@/lib/report/workingCut.mjs"; +import { listTakes } from "@/lib/report/takes.mjs"; +import PlayLink from "../PlayLink"; + +// --------------------------------------------------------------------------- +// OUTPUT FILES, AS LOCAL PATHS (lane/ui-simplify, 5 Nov; the operator's rule: +// "output files get local paths (absolute), never an /api/... download URL +// shown as the place a file is"). The newest take's rendered mp4s first -- +// takes/<t>/out/<slug>.mp4 and its ladder -- then the newest few other takes', +// then the build's out/<slug>.mp4: each an absolute path with Copy. +// --------------------------------------------------------------------------- + +type File = { path: string; bytes: number; mtimeMs: number }; + +async function mp4sIn(dir: string): Promise<File[]> { + const names = await readdir(dir).catch(() => [] as string[]); + const out: File[] = []; + for (const n of names) { + if (!n.endsWith(".mp4")) continue; + const f = path.join(dir, n); + const st = await stat(f).catch(() => null); + if (st?.isFile() && st.size > 0) out.push({ path: f, bytes: st.size, mtimeMs: st.mtimeMs }); + } + return out.sort((a, b) => a.path.localeCompare(b.path)); +} + +export default async function OutputFiles({ project, dir }: { project: string; dir: string }) { + const listing = await listTakes(dir); + const takes = (listing.takes as { id: string; builtAt?: string | null; label?: string }[]).filter((t) => t.builtAt).sort((a, b) => String(b.builtAt).localeCompare(String(a.builtAt))); + const latest = latestWorkingTake(listing.takes as never[]) as { id: string } | null; + const order = latest ? [takes.find((t) => t.id === latest.id)!, ...takes.filter((t) => t.id !== latest.id)].filter(Boolean) : takes; + const rows = await Promise.all(order.slice(0, 4).map(async (t) => ({ take: t, files: await mp4sIn(path.join(dir, "takes", t.id, "out")) }))); + const build = await mp4sIn(path.join(dir, "out")); + const shown = rows.filter((r) => r.files.length > 0); + return ( + <section data-output-files="" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"> + <h2 className="micro mb-1">Output files</h2> + {shown.length === 0 && build.length === 0 && <p className="m-0 text-[12px] text-muted">No rendered file yet: render a take (Takes, or the take card's Render full).</p>} + {shown.map(({ take, files }) => ( + <div key={take.id} className="mb-1.5" data-output-take={take.id}> + <div className="flex flex-wrap items-center gap-2 text-[12px]"> + <span className="font-mono text-text">{take.id}</span> + {latest?.id === take.id && <span className="micro text-signal-text">latest</span>} + {take.label && <span className="truncate text-text-2">{take.label}</span>} + <PlayLink project={project} take={take.id} where="outputs" variant="icon" /> + </div> + <ul className="m-0 list-none space-y-0.5 p-0"> + {files.map((f) => ( + <li key={f.path} className="flex flex-wrap items-center gap-2 font-mono text-[11px] text-text-2" data-output-file={f.path}> + <span className="break-all">{f.path}</span> + <span className="text-muted">{fmtBytes(f.bytes)}</span> + <CopyButton text={f.path} label="copy path" /> + </li> + ))} + </ul> + </div> + ))} + {build.length > 0 && ( + <div data-output-build=""> + <div className="text-[12px] text-text-2">the build</div> + <ul className="m-0 list-none space-y-0.5 p-0"> + {build.map((f) => ( + <li key={f.path} className="flex flex-wrap items-center gap-2 font-mono text-[11px] text-text-2" data-output-file={f.path}> + <span className="break-all">{f.path}</span> + <span className="text-muted">{fmtBytes(f.bytes)}</span> + <CopyButton text={f.path} label="copy path" /> + </li> + ))} + </ul> + </div> + )} + </section> + ); +} diff --git a/umtool/components/projects/report/OverviewTab.tsx b/umtool/components/projects/report/OverviewTab.tsx @@ -20,6 +20,7 @@ import SourceBacklog from "./SourceBacklog"; import ProjectSites from "./ProjectSites"; import LinkPolicyPanel from "./LinkPolicyPanel"; import { manifestToken } from "@/lib/report/manifest.mjs"; +import { Options } from "@/components/ui/disclosure"; // The Overview tab (canvas "Piece · Overview"): the Next card, then the // piece's decisions and -- when it is an article's video -- the article and @@ -157,11 +158,13 @@ export default async function OverviewTab({ project, detail, frame }: ReportTabP {/* --- the author's own account of the cut ------------------------- */} {readme && ( - <section data-readme="" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"> - <div className="max-h-[40vh] overflow-y-auto"> - <Markdown text={readme} /> - </div> - </section> + <Options id="overview-readme" label="README" hint="the author's account of the cut"> + <section data-readme="" className="basis-full rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"> + <div className="max-h-[40vh] overflow-y-auto"> + <Markdown text={readme} /> + </div> + </section> + </Options> )} </> ); @@ -176,28 +179,45 @@ export function ProjectDecisions({ project, decisions, token = null }: { project <h2 className="micro mb-1.5"> {decisions.filter((d) => d.severity !== "info").length} waiting of {decisions.length} </h2> - <ul className="space-y-1"> - {decisions.map((d, i) => ( - <li - key={`${d.kind}-${d.target}-${i}`} - data-decision={d.kind} - data-severity={d.severity} - data-target={d.target} - className="flex flex-wrap items-baseline gap-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-1.5" - > - <span className={badgeVariants({ variant: TONE[d.severity], size: "sm" })}> - {d.severity} - </span> - <span className="font-mono text-[12px] text-[var(--color-text)]">{d.target}</span> - <span className="text-[12px] text-[var(--color-dim)]">{d.why}</span> - {/* The one-press settle, when the row knows one; `fix` is its terminal twin. */} - {d.settle && <DecisionSettle project={project} settle={d.settle} token={token} />} - <span className="micro ml-auto" data-fix={d.fix ?? undefined} title={d.fix ? `from a terminal: ${d.fix}` : undefined}> - {d.kind} - </span> - </li> - ))} - </ul> + {/* A kind with many rows (68 clips with no cues): its first five, the rest folded (lane/ui-simplify). */} + {(() => { + const row = (d: Decision, i: number) => ( + <li + key={`${d.kind}-${d.target}-${i}`} + data-decision={d.kind} + data-severity={d.severity} + data-target={d.target} + className="flex flex-wrap items-baseline gap-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-1.5" + > + <span className={badgeVariants({ variant: TONE[d.severity], size: "sm" })}> + {d.severity} + </span> + <span className="font-mono text-[12px] text-[var(--color-text)]">{d.target}</span> + <span className="text-[12px] text-[var(--color-dim)]">{d.why}</span> + {/* The one-press settle, when the row knows one; `fix` is its terminal twin. */} + {d.settle && <DecisionSettle project={project} settle={d.settle} token={token} />} + <span className="micro ml-auto" data-fix={d.fix ?? undefined} title={d.fix ? `from a terminal: ${d.fix}` : undefined}> + {d.kind} + </span> + </li> + ); + const byKind = new Map<string, Decision[]>(); + for (const d of decisions) byKind.set(d.kind, [...(byKind.get(d.kind) ?? []), d]); + const folded = new Set<Decision>(); + for (const list of byKind.values()) if (list.length > 8) list.slice(5).forEach((d) => folded.add(d)); + return ( + <> + <ul className="space-y-1">{decisions.filter((d) => !folded.has(d)).map(row)}</ul> + {[...byKind.entries()] + .filter(([, list]) => list.length > 8) + .map(([kind, list]) => ( + <Options key={kind} id={`decisions-${kind}`} label={`${list.length - 5} more ${kind}`} className="mt-1" bodyClassName="block"> + <ul className="space-y-1">{list.slice(5).map(row)}</ul> + </Options> + ))} + </> + ); + })()} </section> )} {decisions.length === 0 && ( diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -28,6 +28,8 @@ import WhatPlays, { type WorkingCut } from "./WhatPlays"; import { useCutApp } from "../cutApp/CutApp"; import { ClipExportButtons, ClipExportStatus, useClipExport } from "../ClipExport"; import AddPost from "./AddPost"; +import { AddClipToggle } from "../AddClip"; +import { Options, PanelSlot } from "@/components/ui/disclosure"; import PostItemPlayer, { postItemAssets, type PostPlan } from "./PostItemPlayer"; import SidePostOverlay from "./SidePostOverlay"; import ComboBadge, { type ComboInfo } from "./ComboBadge"; @@ -650,7 +652,11 @@ export default function PlayCut({ const e = now(); 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") return postBenchHref(project, it.id, { play: { at: Math.round(Math.max(0, e.t - it.from) * 100) / 100 } }); + 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; + } 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). @@ -1272,30 +1278,52 @@ export default function PlayCut({ </button> </p> )} - {/* Export clip: the clip on screen as the cut plays it (or raw), no deck, into exports/; Download, Open folder. */} - <div className="flex flex-wrap items-center gap-1.5 text-[12px]" data-play-export=""> - <ClipExportButtons - exp={clipExport} - clip={item?.clip ? item.id : null} - why={!item?.clip ? "a card is not a clip: nothing to export" : !entry?.media ? "its window is not fetched — fetch it first" : null} - around={item?.clip && typeof entry?.start === "number" && typeof entry?.end === "number" ? { start: entry.start, end: entry.end } : null} - /> - <ClipExportStatus exp={clipExport} /> - </div> - {/* Add post (UI notes item 13): a card from the channel's posts archive, captured through the editor, on the clip on screen. */} - {editable && ( - <AddPost + {/* Play's Options (lane/ui-simplify): the export of the clip on screen; lane/vertical's slots. */} + <Options id="play" hint="export the clip on screen" bodyClassName="flex-col"> + {/* Export clip: the clip on screen as the cut plays it (or raw), no deck, into exports/; Download, Open folder. */} + <div className="flex flex-wrap items-center gap-1.5 text-[12px]" data-play-export=""> + <ClipExportButtons + exp={clipExport} + clip={item?.clip ? item.id : null} + why={!item?.clip ? "a card is not a clip: nothing to export" : !entry?.media ? "its window is not fetched — fetch it first" : null} + around={item?.clip && typeof entry?.start === "number" && typeof entry?.end === "number" ? { start: entry.start, end: entry.end } : null} + /> + </div> + <PanelSlot name="play-vertical" /> + <PanelSlot name="play-side-tweet" /> + </Options> + {/* Where an export is (a note's Export too, Options folded or not). */} + <ClipExportStatus exp={clipExport} /> + {/* Add post and Add a clip here, one row (lane/ui-simplify). */} + <div className="flex flex-wrap items-center gap-1.5 text-[12px]" data-play-add-clip=""> + {/* Add post (UI notes item 13): a card from the channel's posts archive, captured through the editor, on the clip on screen. */} + {editable && ( + <AddPost + project={project} + clip={item?.clip ? item.id : null} + onAdded={(p) => { + setPlaying(false); + // Its card plays at the end of the clip it rides on: the playhead goes there, the deck recomposed. + const it = planRef.current.items.find((x) => x.id === (p.attachTo ?? item?.id)); + void reloadView(); + if (it) seekTo(Math.max(it.from, it.to - 1)); + }} + /> + )} + {/* 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} - clip={item?.clip ? item.id : null} - onAdded={(p) => { + 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); - // Its card plays at the end of the clip it rides on: the playhead goes there, the deck recomposed. - const it = planRef.current.items.find((x) => x.id === (p.attachTo ?? item?.id)); void reloadView(); - if (it) seekTo(Math.max(it.from, it.to - 1)); }} /> - )} + </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 && ( <RejectClip diff --git a/umtool/components/queue/RenderRecord.tsx b/umtool/components/queue/RenderRecord.tsx @@ -1,4 +1,6 @@ import Link from "next/link"; +import CopyButton from "@/components/CopyButton"; +import PlayLink from "@/components/projects/PlayLink"; import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; import { takeRenderLogHref, takesHref } from "@/lib/hrefs"; import type { RenderView } from "@/lib/queue/view"; @@ -34,6 +36,8 @@ export default function RenderRecord({ compact?: boolean; }) { const live = rec.state === "running" || rec.state === "waiting"; + // The output file as a local path (never an /api/ URL shown as where a file is). + const mp4Path = rec.mp4 ? (rec.mp4.startsWith("/") ? rec.mp4 : rec.projectDir ? `${rec.projectDir}/takes/${rec.take}/${rec.mp4}` : `takes/${rec.take}/${rec.mp4}`) : null; const bad = rec.state === "failed" || rec.state === "cancelled"; return ( <div @@ -52,6 +56,7 @@ export default function RenderRecord({ </Link> )} <span className="font-mono">{rec.take}</span> + {showProject && project && <PlayLink project={project} take={rec.take} where="jobs" variant="icon" />} {rec.label && !compact && <span className="text-text-2">{rec.label}</span>} {live && ( <span className="text-text-2" data-render-stage=""> @@ -70,6 +75,12 @@ export default function RenderRecord({ log </a> </div> + {rec.state === "done" && mp4Path && ( + <p className="m-0 flex flex-wrap items-center gap-1.5 font-mono text-[11px] text-text-2" data-render-mp4={mp4Path}> + {mp4Path} + <CopyButton text={mp4Path} label="copy path" /> + </p> + )} {rec.error && ( <p className="m-0 font-mono text-[11px] text-reject-text" data-render-error=""> {rec.error} diff --git a/umtool/components/shell/AppRail.tsx b/umtool/components/shell/AppRail.tsx @@ -8,6 +8,7 @@ import CreateMenu from "./CreateMenu"; import JumpButton from "./JumpButton"; import PhoneDock from "./PhoneDock"; import RunningList from "./RunningList"; +import RecentCuts from "./RecentCuts"; import ThemeControl from "./ThemeControl"; import { Mark, Wordmark } from "./Wordmark"; @@ -53,6 +54,8 @@ export default async function AppRail({ active }: { active: string }) { <p className="px-5 text-[12px] text-muted-2">Nothing pinned</p> </section> + <RecentCuts /> + <RunningList initial={initialRunning()} /> <div data-rail-section="theme" className="px-4 pb-4 pt-3"> diff --git a/umtool/components/shell/RecentCuts.tsx b/umtool/components/shell/RecentCuts.tsx @@ -0,0 +1,75 @@ +"use client"; + +import { usePathname } from "next/navigation"; +import { useEffect, useState } from "react"; +import PlayLink from "@/components/projects/PlayLink"; +import Link from "next/link"; +import { projectHref } from "@/lib/hrefs"; + +// --------------------------------------------------------------------------- +// THE RAIL'S RECENT CUTS (lane/ui-simplify, 5 Nov): the last report videos this +// viewer opened, each with ▶ Play (the newest take) -- so Play is one click from +// any page. A per-viewer convenience, so localStorage (wrapped: a private +// window or blocked storage just shows nothing); <RememberCut> on a project's +// page and on Play writes it. +// --------------------------------------------------------------------------- + +const KEY = "umtool.recentCuts"; +const MAX = 4; +type Recent = { project: string; title: string }; + +function read(): Recent[] { + try { + const v = JSON.parse(window.localStorage.getItem(KEY) ?? "[]"); + return Array.isArray(v) ? v.filter((x) => x && typeof x.project === "string").slice(0, MAX) : []; + } catch { + return []; + } +} + +/** Remember a report video as just opened (no UI). */ +export function RememberCut({ project, title }: { project: string; title: string }) { + useEffect(() => { + try { + const next = [{ project, title }, ...read().filter((r) => r.project !== project)].slice(0, MAX); + window.localStorage.setItem(KEY, JSON.stringify(next)); + window.dispatchEvent(new Event("umtool:recent-cuts")); + } catch { + // storage refused: nothing to remember + } + }, [project, title]); + return null; +} + +export default function RecentCuts() { + const [all, setList] = useState<Recent[]>([]); + // Not the one on screen (its own page has its Play), and named by its id's last part (the page names its title). + const here = usePathname() ?? ""; + const list = all.filter((r) => !here.startsWith(projectHref(r.project))); + useEffect(() => { + const on = () => setList(read()); + on(); + window.addEventListener("umtool:recent-cuts", on); + window.addEventListener("storage", on); + return () => { + window.removeEventListener("umtool:recent-cuts", on); + window.removeEventListener("storage", on); + }; + }, []); + if (!list.length) return null; + return ( + <section data-rail-section="recent-cuts" aria-label="Recent cuts"> + <h2 className="micro px-5 pb-1.5 pt-4">Recent cuts</h2> + <ul className="m-0 list-none space-y-0.5 px-4 p-0"> + {list.map((r) => ( + <li key={r.project} data-recent-cut={r.project} className="flex items-center gap-1 px-1 text-[12px]"> + <Link href={projectHref(r.project)} prefetch={false} className="min-w-0 flex-1 truncate text-text-2 no-underline hover:text-text" title={`${r.title} (${r.project})`}> + {r.project.split("/").pop()} + </Link> + <PlayLink project={r.project} where="rail" variant="icon" /> + </li> + ))} + </ul> + </section> + ); +} diff --git a/umtool/components/ui/disclosure.tsx b/umtool/components/ui/disclosure.tsx @@ -0,0 +1,104 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// OPTIONS / ADVANCED (lane/ui-simplify, 5 Nov; the operator: "focus on the +// happy path and have options/advanced panels for everything else, keeping all +// current features exposed"). +// +// A page shows ONE primary row for the happy path's next step; everything else +// sits in an Options disclosure (common, secondary) or an Advanced one (rare, +// expert). One shell for every page, so they look and behave the same: +// +// <Options id="cut">…</Options> <Advanced id="cut">…</Advanced> +// +// A `<details>`: what is inside stays in the page (a link keeps its address, a +// spec finds it by its data-*), only folded. Whether it is open is remembered +// per viewer and per panel (`umtool.panel.<id>.<kind>` in localStorage, +// wrapped: a private window just starts folded). e2e opens one through +// e2e/panels.ts openPanel(page, kind, id). +// --------------------------------------------------------------------------- + +export type PanelKind = "options" | "advanced"; + +const keyOf = (id: string, kind: PanelKind) => `umtool.panel.${id}.${kind}`; + +export function Disclosure({ + kind, + id, + label, + hint, + defaultOpen = false, + className, + bodyClassName, + children, +}: { + kind: PanelKind; + /** The page or panel this belongs to (`cut`, `take-card`, `play`): the remembered state's key. */ + id: string; + label?: React.ReactNode; + /** A few words after the label, folded or not (what is inside: "voices · fetch · tighten"). */ + hint?: React.ReactNode; + defaultOpen?: boolean; + className?: string; + bodyClassName?: string; + children: React.ReactNode; +}) { + const [open, setOpen] = useState(defaultOpen); + useEffect(() => { + try { + const v = window.localStorage.getItem(keyOf(id, kind)); + if (v === "1" || v === "0") setOpen(v === "1"); + } catch { + // storage refused: folded as the page drew it + } + }, [id, kind]); + return ( + <details + open={open} + data-panel-disclosure={kind} + data-panel-id={id} + onToggle={(e) => { + const now = (e.currentTarget as HTMLDetailsElement).open; + setOpen(now); + try { + window.localStorage.setItem(keyOf(id, kind), now ? "1" : "0"); + } catch { + // not remembered; still toggles + } + }} + className={cn("group/disclosure min-w-0", className)} + > + <summary + data-panel-summary={kind} + className={cn( + "inline-flex cursor-pointer select-none list-none items-center gap-1.5 rounded-[3px] px-1.5 py-0.5 text-[11.5px] text-muted-2 hover:bg-panel-2 hover:text-text [&::-webkit-details-marker]:hidden", + kind === "advanced" && "text-muted", + )} + > + <span aria-hidden className="inline-block transition-transform group-open/disclosure:rotate-90">▸</span> + <span className="font-medium">{label ?? (kind === "options" ? "Options" : "Advanced")}</span> + {hint && <span className="text-muted">{hint}</span>} + </summary> + <div className={cn("mt-1.5 flex flex-wrap items-start gap-2", bodyClassName)}>{children}</div> + </details> + ); +} + +export function Options(props: Omit<React.ComponentProps<typeof Disclosure>, "kind">) { + return <Disclosure kind="options" {...props} />; +} + +export function Advanced(props: Omit<React.ComponentProps<typeof Disclosure>, "kind">) { + return <Disclosure kind="advanced" {...props} />; +} + +/** + * A marked place for a control another lane owns (lane/vertical's vertical and side-tweet knobs): empty + * here, `data-panel-slot="<name>"` so it is found and filled there. + */ +export function PanelSlot({ name }: { name: string }) { + return <span data-panel-slot={name} hidden />; +} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -81,7 +81,7 @@ Inbox cannot disagree about what is wrong with one. | `timeline <project> insert (--to-section N \| --group G) <channel>/<video>@<start>-<end> [--id ID] [--lock] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` | a clip at the **end of section N**, or **after group G's last clip and one of its clips** (the run stays together): one write, the marker that followed that last clip re-anchored after the new one, so the clip lands in the section and every other clip keeps its own; the attribution as `insert --after`'s. The Candidates panel's Insert is this ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press)) | | `candidates <project> [ls] [--all] [--json]` · `candidates <project> import <sweep.md> [--dry-run] [--json]` · `candidates <project> add <json\|@file> [--json]` | the **candidates inbox** (`<project>/candidates.json`): proposals only — `import` reads a sweep's bullets (`- [verdict] [title @ time](link) (date) "quote" — why`, under their headings; a Top N section marks what it restates; a bullet with no verdict or link is skipped and said), `add` an agent's (`{channel?, video, t, quote?, why?, verdict?, score?, section?}` or `{link, …}`); the same moment again changes nothing it holds. Insert and Not this are the Cut tab's Candidates panel's ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press)) | | `timeline <project> groups [ls] [--json]` · `groups import <file> [--skip-missing] [--drop-empty]` · `groups set <gid\|-> <id…> [--claim C]` · `groups move <gid> --to <index>` · `groups move <gid> --to after <gid>` · `groups label <gid> <claim…>` · `groups promote <gid> [--label L]` · `groups remove <gid>` · `order <file\|@file\|id…>` | **claim groups** (`groups` beside the timeline; the Cut tab's group bars): runs of clips inside one section making one claim — `ls` by section, each group's id, claim and clips (`--json` with the token); `import` a claim-groups file (`{sections: [{label, groups: [{claim, ids}]}]}`) in ONE write — the cut re-ordered to it, its groups the cut's, the markers following; a file section is the deck section of its name, else the one most of its clips are in; **exit 1** for an id the cut lacks (`--skip-missing`) or a section left with no clip (`--drop-empty` removes its marker); `set` (the clips already together), `label`, `remove` (ungroup), `move` the whole group (before the group at that index, or after one, in its section), `promote` (a level-2 marker at its first clip titled with its claim — the one group edit the render sees; `--label` when the claim is over 24); `order` the named entries in the places they hold (every clip keeping its section). A clip moved out of its group's run leaves it; moved alone into the middle of one, it joins. Every write an undo point (`undo`) ([knobs.md](knobs.md#claim-groups-runs-of-clips-that-make-one-claim)) | -| `timeline <project> --take <take> [ls \| move <id> --to <index> \| remove <id> \| undo]` | a **take's** timeline (walk a take): the same structure checks, written into the take's patch, each write with an undo point of the take's own (`takes/<take>/revisions/`); `undo` takes the take's newest edit back, whichever writer made it | +| `timeline <project> --take <take> [ls \| move <id> --to <index> \| remove <id> \| undo \| insert <spec> --after <id>\|-]` | a **take's** timeline (walk a take): the same structure checks, written into the take's patch, each write with an undo point of the take's own (`takes/<take>/revisions/`); `undo` takes the take's newest edit back, whichever writer made it. `insert` puts a clip (`<channel>/<video>@<start>-<end>`) into the take only (`takeEdit.mjs insertTakeEntry`) -- the app's **+ Add a clip to <take> only** on the take walk page, and Play's **+ Add a clip here** on a take with its own timeline | | `timeline <project> sections [--json]` · `section-move <id>… --to-section N [--start]` · `section-add --after <id> [--label L] [--color C]` · `section-boundary <marker> --after <id>` · `section-remove <marker>` · `section-set <marker> [--label L] [--color C]` · `split <id> <second>` · `flash-forward <id> <from>-<to> (--after <id\|-> \| --to-section N [--start]) [--move] [--quote Q] [--id ID]` | **sections as sections** (the deck's markers; the Cut tab's section bars and row menus): clips moved to a section with every marker following, a section opened, a boundary moved, relabelled, removed — no section emptied, no boundary crossed (**exit 1**) — and every take patch in step synced; **split** (each half's quote from the words, the second half's cite and QR at its second, a marker after the clip following its second half); **flash-forward** a tight copy of a span elsewhere with the clip's attribution and locks, as `repeatOf` the clip (`--move`: out of the clip) ([knobs.md](knobs.md#sections-split-and-flash-forward-editing-the-cut)) | | `scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10] [--pad 30 \| --from S --to S] [--json]` | the picture's **scene cuts** (ffmpeg `scdet`, score ≥ threshold) and **black spans** (`blackdetect`) in the clip's fetched window, in SOURCE seconds — for `blur.from`/`blur.to` and trims ([knobs.md](knobs.md#a-clips-picture-blurred)). The window is the one the build would cut from (the project's `out/clips-raw`, the editor's `channels/<slug>/data/<id>/clips/`, a saved source); the extent ± `--pad` inside it is scanned. Nothing is fetched: **exit 1** with no window on disk (`fetch` first) | | `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [crop=<px>\|off] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key.; `crop=<px>` the post's own crop of its screenshot (`shotMaxHeight`, 120–1080: its top that tall, never panned; `off` removes it) ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)). Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** | diff --git a/umtool/docs/clip-bench.md b/umtool/docs/clip-bench.md @@ -441,7 +441,7 @@ on first open — from the take's manifest as the walk reads it (a draft's too, take's own status, queue and runner (`out/bench-excerpts/takes/<take>/`), so a take's clip that carries the cut's id with other bounds never shares the cut's prep state. A save on the take's walk that moves an edge queues it as the cut's writes do. `umtool fetch <project> --take <take>` asks the editor for the take's -windows (a clip only the take has included) as the Cut tab's **Fetch windows** asks for the cut's. +windows (a clip only the take has included) as the Cut tab's **Fetch windows** (under Options) asks for the cut's. **`?all=1` walks every clip.** A take's clips often carry the verdict of the clip they were cut from, so the default walk — fetched and still needing a verdict — would skip them. **walk every diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -76,7 +76,7 @@ is cleared in the same write, and said. | both edges to the sentence: the one at the playhead (a playhead parked on an edge does not count), else every sentence the clip's cut (its quote) touches, else the whole sentences inside the window, else the one it is inside — then the start back into the pause before its first word and the end forward into the one after its last (0.1 s of quiet, ≤ 1 s away), inside the cached window | clip bench, under the waveform: **Tighten to this sentence**; **Undo** writes back the edges (and the cut, the mute mark, the cite, the QR) it moved | — | `PUT /api/report/window {project, clip, token, start, end}` | | one edge to the middle of its nearest pause (≤ 1 s) | **Snap edge to nearest pause**: **start** / **end**; **Undo** | — | same | | the words and the pauses, drawn | the bench's zoom, at 20 s or less shown: a box per word with its text (a caption word's box runs to the next word's start), the pauses as bands, the measured silences under them | — | `GET /api/report/clip-editor?project&clip&video&from&to` (`words`, `wordsFrom`, `timed`) | -| every clip of the cut, proposed: before → after and the seconds either way, what moved and why; **nothing applies without a press** | the Cut tab's **Propose tight windows**: each row's **Apply**, then its **Undo**; **show every clip** lists the ones already tight | `umtool tighten <p> [--json] [--all] [--no-measure]` · `--apply <clip>[,<clip>…]` | `GET /api/report/tighten?project=<p>[&clip=…][&measure=0]`, each Apply a `PUT /api/report/window` | +| every clip of the cut, proposed: before → after and the seconds either way, what moved and why; **nothing applies without a press** | the Cut tab's Advanced → **Propose tight windows**: each row's **Apply**, then its **Undo**; **show every clip** lists the ones already tight | `umtool tighten <p> [--json] [--all] [--no-measure]` · `--apply <clip>[,<clip>…]` | `GET /api/report/tighten?project=<p>[&clip=…][&measure=0]`, each Apply a `PUT /api/report/window` | The batch has no playhead: the cut's sentences, else the whole ones in the window. A clip with nothing on disk is proposed from its cues and words (no silences) and says *not fetched*; one whose recording has no cues says so and is @@ -672,9 +672,9 @@ its knobs are one writer, `updatePostItem` (`lib/report/manifest.mjs`), refused | | In umtool | From a terminal | Route | |---|---|---|---| -| a posts reel: the archive's posts as post items, re-run to add only what is new (one write, one undo point) | — | `umtool posts reel <p> --channel <slug> [--channel …] [--since D] [--until D] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run]` | — | +| a posts reel: the archive's posts as post items, re-run to add only what is new (one write, one undo point) | the Cut tab's **+ Add posts** (a channel, their own only, from–to; **Preview**, then **Add N posts**) | `umtool posts reel <p> --channel <slug> [--channel …] [--since D] [--until D] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run]` | — | | one post item among clips | — | `umtool timeline <p> insert --after <id\|-> post:<channel>/<postId> [--id ID]` (or `--to-section N`, `--group G`) | `POST /api/report/timeline {op: "insert", …}` with an entry | -| its `quoted` and `parents` the archive row lacks, from the capture's `context` (the post's page, read by `capture-posts`): filled when the entry is made, and into a cut made before (one write, one undo point; the archive's own never replaced) | — | `umtool posts context <p> [--dry-run]` (no context yet: `pnpm ops capture-posts --json '{"slug":…,"ids":[…],"contextOnly":true}' --wait` first) | — | +| its `quoted` and `parents` the archive row lacks, from the capture's `context` (the post's page, read by `capture-posts`): filled when the entry is made, and into a cut made before (one write, one undo point; the archive's own never replaced) | the Cut tab's Options → **Reads and voices** → **Queue: fill context from captures** (a queue step) | `umtool posts context <p> [--dry-run]` (no context yet: `pnpm ops capture-posts --json '{"slug":…,"ids":[…],"contextOnly":true}' --wait` first) | — | | move, remove, a section, a group | the Cut tab's row (⠿, ⋯, the section bars), Play's reel strip | `umtool timeline <p> move\|remove\|section-move\|section-add …` | as a clip's | | the card's page, an attachment, the faces | Play the cut, the post bench | — | `GET /api/report/post-item?project&id&w&h[&phase][&take]` · `?project&file=posts-media/…` · `?project&font=regular\|bold` | @@ -701,7 +701,7 @@ the shape, the mix, recordings, parts, the best part). One writer for a post's n | `lead`, `tail`, `ramp`, `linger`, `wet`, `lowpassHz`, `duck`, `short` (`hold`\|`loop`), `clip` (`read`\|`full`), `attach` (`under`\|`after`), `lufs`, `rate` — this post's mix | post bench, **the mix** (`rate`: **read rate**); the read lane's voice block dragged sets `lead` | `umtool posts narrate <p> <item> lead=0.6 wet=0.25 short=loop rate=1.1 …` (`k=` back to the cut's) · `umtool posts set-item <p> <item> narration.rate=1.1` (any mix knob as `narration.<k>=`) | `patch: {…}` | | `rate` — the READ's speed, 0.8–1.5 (default 1): the voice sped up, its pitch kept (the build's `atempo`; Play's `playbackRate` with `preservesPitch`), the attachment untouched; the item's length, the muffle and the parts follow the faster read (take ÷ rate), and so does a video's out point `posts fit` chose (its `window`); one set by hand stays | post bench, **the mix**, **read rate**; the read lane says `read in <s> at <r>×` | the cut's: `umtool posts narrate <p> --cut rate=1.08` · a post's: `… <item> rate=1.1` or `posts set-item <p> <item> narration.rate=1.1` | `patch: {rate}` | | the attachment's window — its in and out for the read; why it was chosen (`narration.window`) | post bench, the attachment lane's handles; **Re-pick best**; **Play whole attachment** | `umtool posts fit <p> --all \| <item>… [--linger s]` · `posts set-item <p> <item> fit=read[:<linger>]` | `op: "fit", linger?` · the handles: `POST /api/report/post-item {op: "set", patch: {media}}` | -| `render.postNarration` — the cut's mix (every key above but `attach`, and `engine`, `voice`) | — | `umtool posts narrate <p> --cut wet=0.25 clip=full rate=1.08 …` | — | +| `render.postNarration` — the cut's mix (every key above but `attach`, and `engine`, `voice`) | the Cut tab's Options → **Reads and voices** → **The cut's narration mix** (a knob, a value, **Set for the cut**) | `umtool posts narrate <p> --cut wet=0.25 clip=full rate=1.08 …` | — | | undo the last write | post bench, **Undo last change** | `umtool timeline <p> undo` | `op: "undo"` | | the hand-made batch | — | `umtool posts narrate <p> --import` (`narration/posts/index.json`, a take's `take-<n>.parts.json`) | — | | the authors' pictures (`postAvatars`) | drawn on every card | `umtool posts avatar <p> <handle> <image>` (`off`) · `umtool posts avatars <p>` | — | @@ -731,7 +731,7 @@ published card never pushes in on a blank. | Knob | In umtool | From a terminal | Route | |---|---|---|---| -| `render.posts.redact` — the project's list, `[{term, wholeWord?, note?}]` (at most 200; one writer, `updatePostRedact`, refused in the build's words) | Play the cut, **As published** (the cards as the video draws them) | `umtool posts redact <p> ls` · `add "<term>" [--substring] [--note "…"]` · `remove <n>` (n as `ls` numbers them) | `GET /api/report/post-item?…&published=1` (the card's page, as published) | +| `render.posts.redact` — the project's list, `[{term, wholeWord?, note?}]` (at most 200; one writer, `updatePostRedact`, refused in the build's words) | the Cut tab's Options → **Reads and voices** → **Redacted words** (the list, **Blank it**, ✕); Play the cut, **As published** (the cards as the video draws them) | `umtool posts redact <p> ls` · `add "<term>" [--substring] [--note "…"]` · `remove <n>` (n as `ls` numbers them) | `GET /api/report/post-item?…&published=1` (the card's page, as published) | | the corpus's list — `transcripts/redactions.json`, the same shape (or `{terms: […]}`): blanked in every project | — | read by every build; the editor's to write | — | | one post's markup — `transcripts/channels/<slug>/posts-markup.json`, `{"<postId>": {redact?: [{term, wholeWord?, scope?} \| {start, end, scope?, index?}], censor?: [{media, blur?}]}}`: a term in a `scope` (`text`, `parent`, `quoted`; absent, the whole post), or a span of the archived text in code units (`index`: which parent, nearest first); `censor` blurs the post's attachment `media` (its index; `blur` as `media[i].blur`'s keys, absent the whole frame) in every project | — | read by every build of a cut playing the post; the editor's to write | — | @@ -770,12 +770,12 @@ snapshot and every script keep their words. | Knob | In umtool | From a terminal | Route | |---|---|---|---| -| `render.posts.slurs.on` — `true` (default) \| `false`: the uncensored cut | Play the cut, **As published** + **Uncensored** | `umtool posts slurs <p> on` · `off` · `umtool take <p> --id <id> … --uncensored` · build-video `--uncensored` | `GET /api/report/post-item?…&published=1&uncensored=1` | -| `render.posts.slurs.level` — `all` (default: strong and mild) \| `strong` | — | `umtool posts slurs <p> level strong\|all` | — | -| `render.posts.slurs.visual` — `placeholder` (default) \| `blackout` | Play, **As published** | `umtool posts slurs <p> visual blackout\|placeholder` | — | -| `render.posts.slurs.voice` — `beep` (default) \| `skip` \| `placeholder` | — | `umtool posts slurs <p> voice skip\|beep\|placeholder` | — | -| `render.posts.slurs.add` — the project's own words (always masked; a word, or `{word, forms?, mask?, say?}`) · `.except` — never masked here (a form, a slur's word or its id) | — | `umtool posts slurs <p> add <word>` · `except <word>` · `remove <word>` (one writer, `updatePostSlurs`) | — | -| what the cut masks | — | `umtool posts slurs <p> ls [--json]`: per slur (its mask, never the word) and per post, and each read that needs word timings | — | +| `render.posts.slurs.on` — `true` (default) \| `false`: the uncensored cut | the Cut tab's Options → **Reads and voices** → **Slur filter** On/Off; Play the cut, **As published** + **Uncensored** | `umtool posts slurs <p> on` · `off` · `umtool take <p> --id <id> … --uncensored` · build-video `--uncensored` | `GET /api/report/post-item?…&published=1&uncensored=1` | +| `render.posts.slurs.level` — `all` (default: strong and mild) \| `strong` | the Cut tab's Options → **Reads and voices** → Slur filter, **level** | `umtool posts slurs <p> level strong\|all` | — | +| `render.posts.slurs.visual` — `placeholder` (default) \| `blackout` | the Cut tab's Options → **Reads and voices** → Slur filter, **visual**; Play, **As published** | `umtool posts slurs <p> visual blackout\|placeholder` | — | +| `render.posts.slurs.voice` — `beep` (default) \| `skip` \| `placeholder` | the Cut tab's Options → **Reads and voices** → Slur filter, **voice** | `umtool posts slurs <p> voice skip\|beep\|placeholder` | — | +| `render.posts.slurs.add` — the project's own words (always masked; a word, or `{word, forms?, mask?, say?}`) · `.except` — never masked here (a form, a slur's word or its id) | the Cut tab's Options → **Reads and voices** → Slur filter: a word, **Mask it** · **Never mask it** · **Back to the list** | `umtool posts slurs <p> add <word>` · `except <word>` · `remove <word>` (one writer, `updatePostSlurs`) | — | +| what the cut masks | the Cut tab's Options → **Reads and voices** → Slur filter (how many masked) | `umtool posts slurs <p> ls [--json]`: per slur (its mask, never the word) and per post, and each read that needs word timings | — | ## Pronunciation and voices (the lexicon, the voice map, a thread read) @@ -817,10 +817,10 @@ was not synthesized (the parts made stay cached: run it again), 2 a usage error; | Knob | In umtool | From a terminal | Route | |---|---|---|---| -| the lexicon -- `[{word, say, case?, item?, note?}]` (at most 500) | the bench's re-take applies it | `umtool posts say <p> add tbh "T-B-H"` · `add atm "at the moment" --item p-…` · `add US "U.S." --case` · `ls [--item <id>]` · `remove tbh [--item <id>]` (or its number) | — (`POST /api/report/post-narration {op: "take"}` applies it) | -| what a voice would be asked to say (the lexicon, the redaction, the slur filter) | — | `umtool posts say <p> try "tbh @grok atm" [--item <id>]` | — | -| the picked reads that say an entry the old way, each with the command that re-reads it | — | `umtool posts say <p> stale [--json]` | — | -| the voice map | — | `umtool posts voices <p> set kirscheverstahl tara` · `set '*' leo` · `remove <handle>` · `ls` (each author the cut carries, and the voice each gets) | — | +| the lexicon -- `[{word, say, case?, item?, note?}]` (at most 500) | the Cut tab's Options → **Reads and voices**: the list, **Add** a word and how it is said, ✕ removes; the bench's re-take applies it | `umtool posts say <p> add tbh "T-B-H"` · `add atm "at the moment" --item p-…` · `add US "U.S." --case` · `ls [--item <id>]` · `remove tbh [--item <id>]` (or its number) | — (`POST /api/report/post-narration {op: "take"}` applies it) | +| what a voice would be asked to say (the lexicon, the redaction, the slur filter) | **Reads and voices** → **Try it** | `umtool posts say <p> try "tbh @grok atm" [--item <id>]` | — | +| the picked reads that say an entry the old way, each with the command that re-reads it | **Reads and voices** names them | `umtool posts say <p> stale [--json]` | — | +| the voice map | **Reads and voices**: the map, **Set** a handle (or `*`) and a voice, ✕ removes; the cut's authors with the voice each gets | `umtool posts voices <p> set kirscheverstahl tara` · `set '*' leo` · `remove <handle>` · `ls` (each author the cut carries, and the voice each gets) | — | | a thread read -- `takes[i].read: {kind: "thread", parents, skip?, quoted?, linked?, seen?, voiceFor?, voice?}` | the post bench plays and picks it like any take | `umtool posts narrate <p> <item> --take --thread` (parent 0) · `--parents all` (every ancestor) · `--parents none` · `--skip-parent <id>` (repeat) · `--no-quoted` · `--no-linked` · `--read-seen` · `--voice-for Movail2=leah` · `--voice leo` · `--force` · `--dry-run` · `--json` | — | Recipes (copy them; `<p>` is the project, `<item>` the post item's id or its post's id): @@ -957,10 +957,10 @@ gathers them). | `render.postNarration.thread.shrink` — a context post's size, 0.3–1 (default 0.62) · `.dim` — its opacity, 0.15–1 (default 0.5) · `.seconds` — the change, 0–3 s (default 0.7) · `.pan` — the column's move, 0.1–3 s (default 0.7) | — | `umtool posts narrate <p> --cut thread.shrink=0.55 thread.dim=0.4 thread.seconds=0.9 thread.pan=1` | — | | `thread` on a post item — `{parent?, quoted?, carry?, reveal?, shrink?, dim?, seconds?, pan?}` over the cut's (`parent` one mode, or a list, nearest parent first) | post bench, **thread read**: the post it answers / its parent / the quoted post (the cut's, or a mode), **carry**, **shrink**, **dim**, **over**, **pan**; the guard's refusals listed before Save | `umtool posts set-item <p> <item> thread.parent=excerpt` · `thread.parent.1=hidden` · `thread.quoted=context` · `thread.carry=off` · `thread.shrink=0.5` … · `thread=auto` (the cut's) | `POST /api/report/post-item {project, op: "set", id, patch: {thread}, token}` (an object merges; `null` clears) | | a part's role — the text it reads: `parent:<i>`, `quoted`, `post`, `media:<i>` (stored, else inferred) | post bench, **thread read**: the read piece by piece (click one: the playhead at its start; `·` marks an inferred role) | `umtool posts roles <p> [<item> …]` (list, with the guard's verdict and the warnings: a link said aloud, a text cut short) · `--write` (store the inferred roles) · `<item> --set 3=parent:0,4=post` (`off`: inferred again) | — (`updatePostNarration {partRoles: {take, roles}}`) | -| a read RE-JOINED without a piece (no TTS) — the picked take's kept parts cut from its own file and joined with the read's pauses: a derived take (`steps: [{op: "rejoin", drop}]`), picked | post bench, **thread read**: **Read without it** on a context piece the take reads | `umtool posts reread <p> <item> --without parent:0` (`parent:1`, `quoted`) · `--drop-parts 3,4` · `--drop-urls` · `--dry-run`; `umtool posts set-item <p> <item> thread.parent.0=context` re-joins first when the take reads it (the knob alone when it does not; `--no-reread`: refused) | `POST /api/report/post-narration {project, op: "reread", id, without: ["parent:0"], dropParts?, dropUrls?}` | -| a read's PARTS RE-TIMED (no TTS) — the parts named read at a tempo of 1–1.6 (pitch kept: ffmpeg `atempo`, or `rubberband`), the rest untouched, joined with the read's pauses; the words scaled with their part (read-follow, zooms, captions, slams, beeps keep their place); a derived take (`steps: [{op: "tempo", tempo: {"4-16": 1.35}, params: {stretch}}]`, each part's `tempo` stored), picked. A tempo is ABSOLUTE: on a re-timed take it re-cuts from the take before (each part stretched once) | — | `umtool posts reread <p> <item> --tempo-for "4-16=1.35,21-25=1.3"` · `--tempo 1.3 --parts 4-16,21-25` · `--stretch rubberband` · `--dry-run`; `umtool posts set-item <p> <item> narration.tempo="4-16=1.35"` (the same) | `POST /api/report/post-narration {project, op: "reread", id, tempo: "4-16=1.35", stretch?}` | -| a read's CAPS YELLED (no TTS) — the words he wrote in ALL CAPS (his post, or the piece a part reads) found in the take's word timings and raised: +5.5 dB measured over the spans, a presence lift, compressed, gently saturated, limited, 50 ms ramps; acronyms (`YELL_ACRONYMS`, any caps word with no vowel) and masked slurs left flat; timings kept; loudness within 1 LU of its source; a derived take (`steps: [{op: "yell", spans, params: {gain, style}}]`), picked. Needs the take's word timings (`posts narrate --words`) | — | `umtool posts reread <p> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise\|shout\|loud] [--dry-run]` · the cut's: `umtool posts yell <p> --all \| <item …> [--dry-run]` (the dry run lists each item's caps, the ones left flat and why, and the items with no word timings) | `POST /api/report/post-narration {project, op: "reread", id, yell: true, yellGain?, yellStyle?}` | -| the cut's conversations — one run is one scene; `threads --write` gathers each in tree order (a post after what it answers, sibling branches by date, never across a section) | — | `umtool timeline <p> threads [--json]` · `threads --write [--conversation <id>]` (one undo point) | — (`orderEntries`) | +| a read RE-JOINED without a piece (no TTS) — the picked take's kept parts cut from its own file and joined with the read's pauses: a derived take (`steps: [{op: "rejoin", drop}]`), picked | post bench, **thread read**: **Read without it** on a context piece the take reads; the post bench's Options → **Re-join the read (no TTS)**: **leave out parts**, **drop the URLs**, **Re-join** | `umtool posts reread <p> <item> --without parent:0` (`parent:1`, `quoted`) · `--drop-parts 3,4` · `--drop-urls` · `--dry-run`; `umtool posts set-item <p> <item> thread.parent.0=context` re-joins first when the take reads it (the knob alone when it does not; `--no-reread`: refused) | `POST /api/report/post-narration {project, op: "reread", id, without: ["parent:0"], dropParts?, dropUrls?}` | +| a read's PARTS RE-TIMED (no TTS) — the parts named read at a tempo of 1–1.6 (pitch kept: ffmpeg `atempo`, or `rubberband`), the rest untouched, joined with the read's pauses; the words scaled with their part (read-follow, zooms, captions, slams, beeps keep their place); a derived take (`steps: [{op: "tempo", tempo: {"4-16": 1.35}, params: {stretch}}]`, each part's `tempo` stored), picked. A tempo is ABSOLUTE: on a re-timed take it re-cuts from the take before (each part stretched once) | the post bench's Options → **Re-join the read (no TTS)**: **re-time** `4-16=1.35`, **Re-time** | `umtool posts reread <p> <item> --tempo-for "4-16=1.35,21-25=1.3"` · `--tempo 1.3 --parts 4-16,21-25` · `--stretch rubberband` · `--dry-run`; `umtool posts set-item <p> <item> narration.tempo="4-16=1.35"` (the same) | `POST /api/report/post-narration {project, op: "reread", id, tempo: "4-16=1.35", stretch?}` | +| a read's CAPS YELLED (no TTS) — the words he wrote in ALL CAPS (his post, or the piece a part reads) found in the take's word timings and raised: +5.5 dB measured over the spans, a presence lift, compressed, gently saturated, limited, 50 ms ramps; acronyms (`YELL_ACRONYMS`, any caps word with no vowel) and masked slurs left flat; timings kept; loudness within 1 LU of its source; a derived take (`steps: [{op: "yell", spans, params: {gain, style}}]`), picked. Needs the take's word timings (`posts narrate --words`) | the post bench's Options → **Re-join the read (no TTS)**: **Raise the CAPS** | `umtool posts reread <p> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise\|shout\|loud] [--dry-run]` · the cut's: `umtool posts yell <p> --all \| <item …> [--dry-run]` (the dry run lists each item's caps, the ones left flat and why, and the items with no word timings) | `POST /api/report/post-narration {project, op: "reread", id, yell: true, yellGain?, yellStyle?}` | +| the cut's conversations — one run is one scene; `threads --write` gathers each in tree order (a post after what it answers, sibling branches by date, never across a section) | the Cut tab's Options → **Reads and voices** → **Queue: gather conversations** (`--write`, a queue step) | `umtool timeline <p> threads [--json]` · `threads --write [--conversation <id>]` (one undo point) | — (`orderEntries`) | | a post item's `conversation` (the archive row's threadId) and `quoted.via: "link"` (a status link resolved to an archived post) | — | `umtool posts context <p> [--dry-run]` | — (`setPostItemsContext`) | ## Thread scenes (the join, whole threads, manual threads, wide attachments, context media, link visits, the branch map) @@ -1054,7 +1054,7 @@ written over. Three kinds (UI notes 2026-10-30, item 12), the bench's and Play's | | In umtool | From a terminal | Route | |---|---|---|---| -| **as cut (no chrome)**: the clip as the cut plays it | **Export clip**, or Export ▾ → **As cut (no chrome)** — the clip bench's reader (on a phone too); Play the cut under the transport (the clip at the playhead) or a note's **Export <clip>** | `umtool export <p> <clip> [--take <t>] [--json]` | `POST /api/report/clip-export {project, clip, take?, kind?: "cut"}` | +| **as cut (no chrome)**: the clip as the cut plays it | **Export clip**, or Export ▾ → **As cut (no chrome)** — the clip bench's reader (on a phone too); Play the cut under the transport, in its Options (the clip at the playhead) or a note's **Export <clip>** | `umtool export <p> <clip> [--take <t>] [--json]` | `POST /api/report/clip-export {project, clip, take?, kind?: "cut"}` | | **with N s of context**: what the cut plays and N s either side (1–120, default 5), as recorded | Export ▾ → **With context**, the seconds beside it | `umtool export <p> <clip> --context N [--fetch]` | `… {kind: "context", context: N, fetch?: true}` | | **raw / full exchange**: a stretch of the recording as recorded — the clip and the fetch pad (**raw**), or a span of source seconds | **raw** beside Export clip; Export ▾ → **Raw / full exchange**, from–to (starting at the clip's extent ± 30 s) | `umtool export <p> <clip> --raw [--from S --to S] [--fetch]` | `… {kind: "raw", span?: {from, to}, fetch?: true}` | | the export's job | the status line under the buttons (*Fetching what it needs through the editor, then exporting…*, the job's last line), then the file | — | `GET /api/report/clip-export?job=<id>` → `{job, done?, error?}` | @@ -1137,7 +1137,7 @@ Its cut is `takes/<t>/out/<slug>.<name>.mp4` (the trailer reel: `<slug>.trailer. | walk a beat: the reel's own editor on the clip bench's parts -- the master's waveform (its envelope, on the clip's source clock) with the zoom (`z`/`Z`/`f`/`F`, Ctrl/⌘ + wheel; ruler, overview, close-in pauses and words), the handles and nudges (`[` `]` in, `,` `.` out, Shift 0.5 s; `I`/`O` at the playhead) held to what the master rendered of the clip (said when a handle hits it), exact playback (`Space`, `-`/`=` speed), tighten to the sentence and snap an edge to a pause; saved in the clip's source seconds (`Enter`), `R` puts back, `B` back to the reel | **Walk it** / `E` → `/projects/<p>/trailer/walk?reel=&take=&beat=n` | `trailer-beats <p> --reel R set <n> <from>-<to> [--take <t>]` | `{op: "set", index, patch: {start, end}, take?}` · the master: `GET /api/report/file?project&path&v` · its envelope `GET /api/report/peaks?project&path&from&to` · its sound `GET /api/report/audio?project&path&from&to` | | a beat's **gaps**: seconds cut out of its middle, in the clip's source seconds -- two moments of one clip as one beat of jump cuts (the clip gap rule: ≥ 0.2 s each, 0.5 s kept before, between and after, at most 12); cut as the clip's gap renders (hard cuts, the sound faded 0.025 s), never the beat-to-beat crossfade; Play the reel skips them and its clock counts kept seconds; a gap wholly inside one the master already cut out of the clip is refused | the walk: `Alt` + drag on the waveform (or **Select a gap** / `g`), **Cut gap** (`g`), **Hear it**, a click on a gap's band puts it back, `G` the one at the playhead, **Undo** | `trailer-beats <p> --reel R gap <n> add <from>-<to>` · `gap <n> remove <second>` · `gap <n> clear` | `{op: "set", index, patch: {gaps: [{from, to}…]}}` | | a beat's verdict: `confirmed` (Y, and on to the next) or `note` (a note left on it) | the walk's **Confirm (Y)** · **Note (M)** · **Clear verdict** | `trailer-beats <p> --reel R verdict <n> confirmed\|note\|clear` | `{op: "set", index, patch: {verdict}}` | -| cut it: a job on umtool's runner (one at a time, the heavy slot, its log, **Cancel**), the result playing with its local path; its record names the take's build, the master's mtime and the reel's version, so the Cut panel says when the master was re-rendered or the reel edited since | the Trailer page's **Cut the trailer** | `umtool trailer <p> --reel <name> [--take <t>]` | `POST /api/report/reel {project, reel, take}` · `?cancel=<job>` · `GET ?job=<id>` · the file: `…/reel/media?what=cut&reel=` | +| cut it: a job on umtool's runner (one at a time, the heavy slot, its log, **Cancel**), the result playing with its local path; its record names the take's build, the master's mtime and the reel's version, so the Cut panel says when the master was re-rendered or the reel edited since | the Trailer page's **Cut the trailer**; its **Options**: close on the master's last S s (`--finale`), a file name (`--out`, a name only), a dry run | `umtool trailer <p> --reel <name> [--take <t>] [--finale S] [--out NAME] [--dry-run]` | `POST /api/report/reel {project, reel, take, finale?, out?, dryRun?}` · `?cancel=<job>` · `GET ?job=<id>` · the file: `…/reel/media?what=cut&reel=` | ### Reels track their source @@ -1195,6 +1195,13 @@ has the recipe. | an effect | `umtool posts fx <p> <item> add caption … --in-take <t>` | the take's entry's `fx` | | look, check, take back | `umtool timeline <p> --take <t>` · `umtool lint <p> --take <t>` (exit 0 clean) · `umtool timeline <p> --take <t> undo` | — / — / the take's newest edit, byte for byte | +**In umtool** (lane/ui-simplify): a take card's Options and the take walk's have **Check before render** (the lint), +**New draft from this take** (the next free `<take>-d<n>`) and **Add items from another project** (the project, the +items, by date or after/before an entry; **Preview** is `--dry-run`, then **Import into <take>**); New take has **Save +as a draft**. The post bench's **edits go to: take <t> only** scopes its set-item, fx and combo writes to the take +(`--in-take`); a read for the take is still the terminal's. A clip into a take only is the take walk's **+ Add a clip to +<take> only** (`umtool timeline <p> --take <t> insert <spec> --after <id>`). + Each edit is an undo point of the take's (`takes/<t>/revisions/`). An edit that changes nothing writes nothing. A take that is rendering is not edited (exit 1). The narration's lexicon and voice map a new read uses are `<p>`'s (`umtool posts say <p>`, `posts voices <p>`), not the @@ -1242,10 +1249,10 @@ attachments are left off. Play the cut shows the side post over the clip for its |---|---|---|---| | list | the Takes page | `umtool takes ls <p> [--json]` (picked, superseded, RENDERING) | `GET /api/report/takes` | | relabel (take.json's `label`; an undo point in the take's `revisions/`) | a take's ✎ | `umtool takes relabel <p> <take> <label…>` | `POST /api/report/takes/housekeeping {project, take, op: "relabel", label}` | -| superseded (verdicts.json `superseded: {by, at}`; folded away in the list, nothing deleted; a pick clears it) | **Mark superseded** (by a take), **Not superseded**; **show them** in the group | `umtool takes supersede <p> <take> [--by <take>]` · `--clear` | `{op: "supersede", by?}` · `{op: "unsupersede"}` | +| superseded (verdicts.json `superseded: {by, at}`; folded away in the list, nothing deleted; a pick clears it) | the take card's Advanced → **Mark superseded** (by a take), **Not superseded**; **show them** in the group | `umtool takes supersede <p> <take> [--by <take>]` · `--clear` | `{op: "supersede", by?}` · `{op: "unsupersede"}` | | **cancel a take while it renders** — its render stopped, the take marked cancelled (`takes/<take>/cancelled.json`), render mode let go if it held it | **Cancel render** on the take's card (a rebuild) or on its *rendering now* row (a first render, which has no card yet) | `umtool takes cancel <p> <take> [--json]` | `{op: "cancel"}` → `{stopped, how, cancelled, renderMode, said}` | -| delete `takes/<take>/` | **Delete take** (the plan first) — a cancelled first render too, under **show them** | `umtool takes delete <p> <take> [--dry-run] [--force]` | `POST /api/report/takes/delete {project, take, dryRun?, force?}` | -| **fork as variant** — the take as a project beside this one (see below) | **Fork as variant** on the card (the name, default `v-<take>`), then a link to it and **compare** | `umtool takes fork <p> <take> [--name N] [--json]` | `{op: "fork", name?}` → `{id, take, links, copied, variant}` | +| delete `takes/<take>/` | the take card's Advanced → **Delete take** (the plan first) — a cancelled first render too, under **show them** | `umtool takes delete <p> <take> [--dry-run] [--force]` | `POST /api/report/takes/delete {project, take, dryRun?, force?}` | +| **fork as variant** — the take as a project beside this one (see below) | **Fork as variant** in the card's Options (the name, default `v-<take>`), then a link to it and **compare** | `umtool takes fork <p> <take> [--name N] [--json]` | `{op: "fork", name?}` → `{id, take, links, copied, variant}` | | **compare two takes side by side** — of the project or of it and its variants | **Compare with…** on the card → `/projects/<p>/takes/compare?a=<project>:<take>&b=<project>:<take>`: two players in step (one transport: **Play both**, ±5 s, the seek bar; B pulled back to A past 0.15 s; **sound A / B**), then what differs | `umtool takes compare <p> <a> <b> [--json]` (`<take>` or `<project>:<take>`) | — (the page reads `lib/report/takeCompare.mjs`) | **What a running render names is respected**: a take whose build lock (`takes/<id>/.building.json`) is live is diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -1235,7 +1235,7 @@ same attachment: held through), is as before. `posts set-item … media.<i>.ente back with the item. Only an item that enters later carries `enter` in its segment key; Play and the bench lay it the same (`plan.enter`). -**Checking it** (`umtool check-joins <project> --take <id> [--json] [--all] [--limit <n>]`, +**Checking it** (`umtool check-joins <project> --take <id> [--json] [--all] [--limit <n>]`; in the app, a rendered take card's Options → **Check the joins**, a queue step whose table is its log on Jobs; `report-to-video/check-joins.mjs`, read-only): every boundary of a rendered take's master where the next post item draws a post the one before showed (its post, a parent, the quote, a linked post, a scene tile), its relation (self-reply, reply to it, quotes it, manual thread, same thread…), its planned join, and over the post box (the deck @@ -1928,7 +1928,7 @@ labelled `built-<file>`, so the file and its description stay paired. ## Notes have a home -`README.md` renders on the Overview tab. Provenance (the History tab) splits by +`README.md` renders on the Overview tab, under its **README** disclosure. Provenance (the History tab) splits by shape: scalars and URLs stay in the table; any string over ~120 characters or containing a newline (`coverage`, `transcriptGapNote`, `qrNote`, `revisionNote`, `asrCaveat`, …) reads as a titled paragraph under **Notes**. Other `*.md` files @@ -2141,7 +2141,7 @@ manifest as it is now. A recipe is `{ group, window, quick?, takes: [{ id, label summary?, kind?, quick? }] }` (a take's own `group`/`window`/`quick` win), run one take at a time, carrying on past a failure; Make all styles writes `takes/all-styles.recipe.json`. -**Use this take** (`POST /api/report/takes/pick`, `umtool takes pick`) copies the take's +**Use this take** (in the take card's Options; `POST /api/report/takes/pick`, `umtool takes pick`) copies the take's `video.manifest.json` over the project's through the manifest writer (`replaceManifest`: the automatic snapshot `auto-before-pick-take` first, the generated-manifest guard, the drafted-mark rule), marks it **picked** in verdicts.json (one pick per group) and links the History tab's @@ -2309,9 +2309,9 @@ the prune rather than guess. - `umtool prune <project>` / `umtool prune --all`: the plan, per take — work and what it frees, or `kept because …` — and the totals. A dry run unless `--yes` ([cli.md](cli.md)). -- **The Takes page**: the head says the takes' work in all and what the policy would free, with - **Free work files** for the project; each card says its work and why it is kept or that it is - prunable, with its own **Free work files**. Both show the plan (each take, its work paths and +- **The Takes page**: its **Advanced → Work files** says the takes' work in all and what the policy + would free, with **Free work files** for the project; each card's **Advanced** says its work and why + it is kept or that it is prunable, with its own **Free work files**. Both show the plan (each take, its work paths and sizes, what is kept and why) and free only on **Free them** (`POST /api/report/takes/prune`, a dry run first, as every delete on the page). - **After a take is made** (`umtool take`, the page's New take and Rebuild, `takes make`): the @@ -2572,7 +2572,7 @@ earlier rulings**. The same writer is `umtool rulings` ([cli.md](cli.md)). ### Fetching the windows, and stand-ins A phrase seed's every clip needs its window on disk before anything plays or -renders. **Fetch windows** (the Cut tab, the clip deck; `umtool fetch <project>`) +renders. **Fetch windows** (the Cut tab's Options, the clip deck; `umtool fetch <project>`) asks the editor for all of them as one `fetch-windows` batch — the body is `{requestedBy: "umtool:<project>", manifest: <its path>, storedUrl: "fallback", items: [{slug, id, from, to, clipId, pad, reason}]}`, the window the build would @@ -2586,7 +2586,7 @@ recorded in `fetch-runs.json` beside the manifest. A window on disk that is BAD (cut from a saved video that turned out corrupt) is a cache hit all the same, so a plain fetch keeps it. `umtool fetch <project> ---refetch z01,w01` evicts first: each named clip's fetch span — the very +--refetch z01,w01` (the clip bench's **Fetch this window again**, a queue step) evicts first: each named clip's fetch span — the very `from`–`to` the body asks for, pad included — goes to the editor's `evict-clips` as `{slug, id, covering: [{from, to}]}`, which removes every cached window of that video OVERLAPPING the span (a wider window the dedup would have served it @@ -2623,7 +2623,7 @@ at least one for each year; the rest are in `phrase-scan.json` as A montage of one phrase is also a montage of everyone who said it near the host: a co-host's "slow news day", a guest's answer, a post read aloud. **Score the -voices** on the clip deck or the Cut tab (or `umtool voice-match <project>`) scores every clip's +voices** on the clip deck or the Cut tab's Advanced (or `umtool voice-match <project>`) scores every clip's voice against the host's, locally, and writes `voice-match.json` beside the manifest; each row then shows `voice 0.43 · unsure`. It is an aid to the ear: the audition deck puts the doubtful clips first and the ruling is still yours. @@ -2914,8 +2914,14 @@ keep / cut and comments work the same. Nothing in it calls a model. first whole second and `citeUrl` this clip's with `t=` moved there (one with no `t=` is kept as it is: it may cite a mirror). The editor then opens the new clip; its window may need **Fetch this clip's window** first. The project - page's timeline has the same as **Add clip** (a `<channel>/<video>@<start>-<end>` - spec, after which entry, the quote from the recording's cues). + page's timeline has the same as **Add by spec** (a `<channel>/<video>@<start>-<end>` + spec, after which entry, the quote from the recording's cues) -- and **+ Add a clip** + (the project head, the Cut tab, Play's **+ Add a clip here**, a take walk's **+ Add a + clip to <take> only**) does it without the spec: find the words in the recordings + the cut draws on (or the archive, or paste a link with a time), click a cue to + start there and shift-click one to end there, the place after a row (by date when + the cut is in date order), **Add to the cut** -- and its window is fetched through + the editor's paced fetch at once (lane/ui-simplify). - **Blur** (on every clip): the clip's picture blurred at the encode — see [knobs.md](knobs.md#a-clips-picture-blurred). diff --git a/umtool/e2e/add-clip.spec.ts b/umtool/e2e/add-clip.spec.ts @@ -0,0 +1,78 @@ +import { test, expect } from "@playwright/test"; +import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// ADD A CLIP, AS ONE FLOW (lane/ui-simplify, 5 Nov; acceptance test A): find +// the words in a recording the cut draws on, the in and out from its cues, +// placed after a row, added -- and its window fetched through the editor's +// paced fetch (the stub editor here). Fixture: add-clip-fixture, a copy of the +// clip editor's cut on testchan/vid1 (its cues: e2e/fixtures/make-fixture.mjs +// CUES.vid1). The old spec form stays (clip-blur.spec.ts, "Add by spec"). +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const P = "reports/add-clip-fixture"; +const DIR = path.join(HERE, "..", ".e2e-song", "reports", "add-clip-fixture"); +type Entry = Record<string, unknown> & { id: string; type: string }; +const timeline = (): Entry[] => JSON.parse(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")).timeline; +// Where the stub editor writes the fetched window: the fixture corpus other specs read (the walk fixture's +// clips are on the same recording), so the window this spec fetched is taken away again when it ends. +const CLIPS = path.join(HERE, "..", ".e2e-song", "channels", "testchan", "data", "vid1", "clips"); +const clipFiles = () => (existsSync(CLIPS) ? readdirSync(CLIPS) : []); +let had: Set<string> | null = null; +test.afterEach(() => { + if (had) for (const f of clipFiles()) if (!had.has(f)) rmSync(path.join(CLIPS, f), { force: true }); + had = null; +}); + +test("Add a clip: find the words, in and out on the cues, after a row, added and fetched", async ({ page }) => { + test.setTimeout(120_000); + // The head's + Add a clip lands on the Cut tab with the panel open. + await page.goto(urls.projectHref(P)); + await page.locator("[data-primary-add-clip]").click(); + await expect(page.locator('[data-add-clip="cut"]')).toBeVisible(); + + await page.locator("[data-add-clip-q]").fill("fourth one"); + await page.locator("[data-add-clip-find]").click(); + await expect(page.locator("[data-add-clip-hits]")).toHaveAttribute("data-add-clip-hits", "1"); + await page.locator('[data-add-clip-hit="vid1@12"]').click(); + // The moment's cue, lit: in 12, out at the end of its sentence (the same cue closes one). + await expect(page.locator('[data-add-clip-edge="in"]')).toHaveValue("12"); + await expect(page.locator('[data-add-clip-edge="out"]')).toHaveValue("15"); + await expect(page.locator("[data-add-clip-quote]")).toHaveValue("A fourth one, done."); + // Shift-click a later line: the out moves to its end, the quote follows. + await page.locator('[data-add-clip-cue="18"]').click({ modifiers: ["Shift"] }); + await expect(page.locator('[data-add-clip-edge="out"]')).toHaveValue("21"); + await expect(page.locator("[data-add-clip-quote]")).toHaveValue(/A fourth one, done\..*it lands at last\./); + // Nudge the in half a second later. + await page.getByRole("button", { name: "in 0.5 s later" }).click(); + await expect(page.locator('[data-add-clip-edge="in"]')).toHaveValue("12.5"); + + had = new Set(clipFiles()); + const first = timeline()[0].id; + await page.locator("[data-add-clip-after]").selectOption(first); + await page.locator("[data-add-clip-submit]").click(); + const added = page.locator("[data-add-clip-added]"); + await expect(added).toBeVisible(); + const id = await added.getAttribute("data-add-clip-added"); + await expect.poll(() => timeline().map((e) => e.id).indexOf(id!)).toBe(1); + const e = timeline()[1]; + expect(e).toMatchObject({ type: "clip", video: "vid1", start: 12.5, end: 21 }); + // Its window, through the editor's paced fetch: the job runs and ends (done, or the stub's own answer). + await expect(added).not.toHaveAttribute("data-add-clip-fetch", "running", { timeout: 60_000 }); + await expect(added).not.toHaveAttribute("data-add-clip-fetch", "idle"); +}); + +test("Add a clip from a pasted link: the recording the cut already carries, at its time", async ({ page }) => { + await page.goto(urls.projectHref(P, { tab: "cut" })); + await page.locator('[data-add-clip-open="cut"]').click(); + await page.locator('[data-add-clip-mode="link"]').click(); + await page.locator("[data-add-clip-link]").fill("testchan/vid1@0:09"); + await page.locator("[data-add-clip-open-link]").click(); + await expect(page.locator("[data-add-clip-moment]")).toHaveAttribute("data-add-clip-moment", "testchan/vid1@9"); + await expect(page.locator('[data-add-clip-edge="in"]')).toHaveValue("9"); + await expect(page.locator("[data-add-clip-quote]")).toHaveValue("Another whole sentence entirely."); +}); diff --git a/umtool/e2e/article-delete.spec.ts b/umtool/e2e/article-delete.spec.ts @@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url"; import { WARM_TIMEOUT, warm } from "./warm"; import { makeOmega } from "./fixtures/delete-fixture.mjs"; import * as urls from "./urls"; +import { openPanel } from "./panels"; // --------------------------------------------------------------------------- // Deleting (release 27 follow-up): every delete shows its PLAN — what goes, @@ -123,6 +124,8 @@ test("an article in the making is deleted from its page, and Work says so", asyn test("a take the project's manifest is, is refused until forced; another take and then the project go", async ({ page }) => { await page.goto("/browse/reports/delete-fixture/takes"); + // Delete take is in the take card's Advanced (lane/ui-simplify). + await openPanel(page, "advanced", "take-card"); const keep = page.locator("[data-take='keep']"); await keep.getByRole("button", { name: "Delete take keep" }).click(); const refused = page.getByRole("region", { name: "delete take keep" }); diff --git a/umtool/e2e/bench-prep.spec.ts b/umtool/e2e/bench-prep.spec.ts @@ -3,6 +3,7 @@ import { copyFileSync, existsSync, mkdirSync, rmSync, writeFileSync } from "node import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; +import { openPanel } from "./panels"; // --------------------------------------------------------------------------- // Preparing the walk (lib/report/benchPrep.mjs): the Cut tab's "Prepare clips @@ -58,6 +59,8 @@ test("Prepare clips for the walk makes the excerpt and the waveforms, and the be // ...which is made a moment later, and opened at once. makeProject(); await page.goto(urls.section(PROJECT, "timeline")); + await openPanel(page, "options", "cut"); + await openPanel(page, "advanced", "cut"); const panel = page.locator("[data-bench-prep]"); await expect(panel.locator("[data-bench-prep-status]")).toHaveText("0 of 2 ready to open · 2 to prepare"); expect(existsSync(EXCERPT)).toBe(false); diff --git a/umtool/e2e/clip-deck.spec.ts b/umtool/e2e/clip-deck.spec.ts @@ -3,6 +3,7 @@ import { existsSync, readFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; +import { openPanel } from "./panels"; // --------------------------------------------------------------------------- // The montage clip deck (release 34 N1): every instance ruled by ear. The @@ -45,6 +46,8 @@ test("the clip deck: import, doubtful first, swipe keep, cut + undo, not him, re // The Cut tab says the montage has clips to rule and links the deck. await page.goto(urls.section(PROJECT, "cut")); + await openPanel(page, "options", "cut"); + await openPanel(page, "advanced", "cut"); const link = page.locator("[data-clip-deck-link]"); await expect(link).toHaveAttribute("data-clip-deck-link", "6"); await expect(link).toHaveAttribute("href", urls.clipDeckHref(PROJECT)); @@ -142,6 +145,8 @@ test("the clip deck: import, doubtful first, swipe keep, cut + undo, not him, re // The Cut tab counts them ruled. await page.goto(urls.section(PROJECT, "cut")); + await openPanel(page, "options", "cut"); + await openPanel(page, "advanced", "cut"); await expect(page.locator("[data-clip-deck-link]")).toHaveText("Clips — 6 ruled"); }); diff --git a/umtool/e2e/clip-editor.spec.ts b/umtool/e2e/clip-editor.spec.ts @@ -3,6 +3,7 @@ import { readFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; +import { openPanel } from "./panels"; // --------------------------------------------------------------------------- // The clip editor (release 35 C2): a person hops in on an assistant's clips. @@ -39,6 +40,8 @@ test("the clip editor: trim, keep (the ruling follows), split, merge, restore, c // The Cut tab links the editor for a cut that is not a montage. await page.goto(urls.section(PROJECT, "cut")); + await openPanel(page, "options", "cut"); + await openPanel(page, "advanced", "cut"); const link = page.locator("[data-clip-editor-link]"); await expect(link).toHaveAttribute("data-clip-editor-link", "3"); await expect(link).toContainText("Clip editor — 3 clips · 3 by the assistant"); diff --git a/umtool/e2e/clip-export.spec.ts b/umtool/e2e/clip-export.spec.ts @@ -3,6 +3,7 @@ import { existsSync, readFileSync, rmSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; +import { openPanel } from "./panels"; // --------------------------------------------------------------------------- // Export one clip (umtool/docs/knobs.md, "Export one clip"): Play the cut's @@ -47,6 +48,7 @@ test("Play the cut: Export clip writes the clip at the playhead to exports/; Dow await ready(page); await expect(page.locator("[data-play-cut]")).toHaveAttribute("data-play-item", "c01"); + await openPanel(page, "options", "play"); const go = page.locator('[data-clip-export-go="c01"]'); await expect(go).toBeEnabled(); await go.click(); diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -54,6 +54,7 @@ import { makeCutEditingFixture } from "./cut-editing-fixture.mjs"; import { makeReelFixture } from "./reel-fixture.mjs"; import { makeIntakeFixture } from "./intake-fixture.mjs"; import { makePostItemsFixture } from "./post-items-fixture.mjs"; +import { makePostHappyFixture } from "./post-happy-fixture.mjs"; import { makePostNarrationFixture } from "./post-narration-fixture.mjs"; import { makeTakeItemsFixture } from "./take-items-fixture.mjs"; import { makePlayPreloadFixture } from "./play-preload-fixture.mjs"; @@ -1877,6 +1878,8 @@ makeMontageOpsFixture({ reports, channels: CHANNELS, manifest }); makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 }); // A clip's picture blurred, New clip from selection and the timeline's Add clip (clip-blur.spec.ts). makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1, name: "clip-blur-fixture", title: "The Clip Blur Fixture" }); +// Add a clip as one flow (lane/ui-simplify; e2e/add-clip.spec.ts): the same cut, its own copy. +makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1, name: "add-clip-fixture", title: "The Add Clip Fixture" }); // Release 36 lane C: the Look panel, a short's framing and Make a short (clip-look.spec.ts). makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1, name: "clip-look-fixture", title: "The Clip Look Fixture" }); // P4b: the bench shell's own clips, and the Media tab's fields with their draft files. @@ -1915,6 +1918,7 @@ makeReelFixture({ reports, deckManifest }); makeIntakeFixture({ reports, channels: CHANNELS, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // Post items (report-to-video/post-item.mjs): a cut mixing a clip and posts played as items, a synthesized posts archive (post-items.spec.ts). makePostItemsFixture({ reports, channels: CHANNELS, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); +makePostHappyFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // Narrated post items (report-to-video/post-narration.mjs): a take read over a video, four pictures cycling (post-narration.spec.ts). makePostNarrationFixture({ reports, deckManifest }); // A take's own items (takeImport.mjs, takeScope.mjs): a post imported from another project into a draft take, edited in the take only (take-items.spec.ts). diff --git a/umtool/e2e/fixtures/post-happy-fixture.mjs b/umtool/e2e/fixtures/post-happy-fixture.mjs @@ -0,0 +1,22 @@ +// THE POST VIDEO's HAPPY PATH, by clicking (lane/ui-simplify, 5 Nov; e2e/post-happy-path.spec.ts): a cut of one +// cut with nothing in it yet, on the post-items fixture's archive (postchan-x, made by post-items-fixture.mjs first). +// The spec adds the posts (Add posts), sets a pronunciation (Reads and voices), plays it (the head's Play) and +// queues a take's render -- every step a press, nothing from a terminal. +import { copyFileSync, mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { POST_CHANNEL } from "./post-items-fixture.mjs"; + +export function makePostHappyFixture({ reports, deckManifest, cachedWindow }) { + const name = "post-happy-fixture"; + const dir = path.join(reports, name); + mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); + copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", "playvid_0.00-9.00.mp4")); + // An empty cut: a post video starts from its posts. + const timeline = []; + const m = deckManifest(name, "The Post Happy Path", timeline); + m.provenance = { ...m.provenance, channelSlug: POST_CHANNEL }; + m.render.fetchPad = 0; + m.render.lockedEdges = false; + writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + return { dir }; +} diff --git a/umtool/e2e/panels.ts b/umtool/e2e/panels.ts @@ -0,0 +1,14 @@ +import type { Page } from "@playwright/test"; + +// The Options / Advanced disclosures (components/ui/disclosure.tsx, lane/ui-simplify): a control +// folded into one is clicked after the panel is opened. `id` narrows to one page's panel ("cut", +// "take-card", "play"); without it every folded panel of that kind on the page opens. +export async function openPanel(page: Page, kind: "options" | "advanced", id?: string) { + const sel = `details[data-panel-disclosure="${kind}"]${id ? `[data-panel-id="${id}"]` : ""}`; + await page.locator(sel).first().waitFor({ state: "attached" }); + const n = await page.locator(sel).count(); + for (let i = 0; i < n; i++) { + const d = page.locator(sel).nth(i); + if (!(await d.evaluate((el) => (el as HTMLDetailsElement).open))) await d.locator(":scope > summary").click(); + } +} diff --git a/umtool/e2e/post-happy-path.spec.ts b/umtool/e2e/post-happy-path.spec.ts @@ -0,0 +1,78 @@ +import { test, expect } from "@playwright/test"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; +import { openPanel } from "./panels"; + +// --------------------------------------------------------------------------- +// THE POST VIDEO, END TO END BY CLICKING (lane/ui-simplify, 5 Nov; the operator: +// "a person can make a video end to end in umtool with no agent"). Fixture: +// e2e/fixtures/post-happy-fixture.mjs -- an empty cut on the postchan-x +// archive. Every step is a press: +// +// Cut tab → + Add posts → Preview → Add N posts (posts reel) +// Options "Reads and voices" → a pronunciation → Try it (posts say) +// the head's ▶ Play → Play of the cut (no /play typed) +// Takes → New take → Make it → its render queued (the take maker) +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const P = "reports/post-happy-fixture"; +const DIR = path.join(HERE, "..", ".e2e-song", "reports", "post-happy-fixture"); +const timeline = () => (JSON.parse(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")).timeline as { id: string; type: string }[]); + +test("a post video from Add posts to a queued render, all by clicking", async ({ page }) => { + test.setTimeout(240_000); + await page.goto(urls.projectHref(P, { tab: "cut" })); + + // 1. Add posts: what the archive holds that the cut does not play, previewed, then added in one write. + await page.locator("[data-add-posts-open]").click(); + await page.locator("[data-add-posts-channel]").fill("postchan-x"); + await page.locator("[data-add-posts-preview]").click(); + const plan = page.locator('[data-add-posts-result="plan"]'); + await expect(plan).toBeVisible(); + const n = Number(await plan.getAttribute("data-add-posts-added")); + expect(n).toBeGreaterThan(0); + await page.locator("[data-add-posts-go]").click(); + await expect(page.locator('[data-add-posts-result="done"]')).toHaveAttribute("data-add-posts-added", String(n)); + await expect.poll(() => timeline().filter((e) => e.type === "post").length).toBe(n); + await expect(page.locator('li[data-kind="post"]')).toHaveCount(n); + // The head now offers Play (the newest take; none yet, so the cut). + await expect(page.locator('[data-play-link="header"]')).toHaveAttribute("href", urls.playHref(P)); + // Every row plays from itself. + await expect(page.locator('li[data-kind="post"]').first().locator('[data-play-link="row"]')).toBeVisible(); + + // 2. Reads and voices: a pronunciation, tried. + await openPanel(page, "options", "cut-reads"); + await page.locator("[data-lexicon-word]").fill("atm"); + await page.locator("[data-lexicon-say]").fill("A-T-M"); + await page.locator("[data-lexicon-add]").click(); + await expect(page.locator('[data-lexicon-row="atm"]')).toBeVisible(); + expect(existsSync(path.join(DIR, "narration", "lexicon.json"))).toBe(true); + await page.locator("[data-lexicon-try]").fill("it is atm now"); + await page.locator("[data-lexicon-try-go]").click(); + await expect(page.locator("[data-lexicon-tried]")).toContainText("A-T-M"); + + // 3. Play, from the head: no /play typed. + await page.locator('[data-play-link="header"]').click(); + await expect(page).toHaveURL(/\/play$/); + await expect(page.locator("[data-play-cut]")).toBeVisible(); + + // 5. A take, rendered: the take maker's job starts from a press. + await page.goto(urls.takesHref(P)); + await page.locator("[data-action='new-take-open']").click(); + const style = page.locator("[data-take-style]"); + await expect(style).toBeEnabled(); + await style.selectOption("e2e-crisp"); + await page.locator("[data-take-window='full']").check(); + await page.locator("[data-action='make-take']").click(); + const job = page.locator("[data-take-job]"); + await expect(job).toBeVisible(); + await expect(page.locator('[data-take-step="crisp"]')).toBeAttached(); + await expect(job).toHaveAttribute("data-job-progress-of", "running"); + // Queued and rendering is the happy path's end here (a whole cut of posts renders for minutes; takes.spec.ts judges + // a finished take). Stopped by its own press, so it is not left running for the next spec. + await job.getByRole("button", { name: "Stop" }).click(); + await expect(job).not.toHaveAttribute("data-job-progress-of", "running", { timeout: 90_000 }); +}); diff --git a/umtool/e2e/take-housekeeping.spec.ts b/umtool/e2e/take-housekeeping.spec.ts @@ -3,6 +3,7 @@ import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; +import { openPanel } from "./panels"; // --------------------------------------------------------------------------- // Take housekeeping in the takes list (UI notes 2026-10-30, item 19): @@ -60,6 +61,7 @@ test("relabel a take; a take that is rendering is not relabelled", async ({ page test("mark a take superseded: folded away, shown dimmed on request, and back", async ({ page }) => { await page.goto(urls.takesHref(PROJECT)); const card = page.locator("[data-take='draft-9']"); + await openPanel(page, "advanced", "take-card"); await card.locator("[data-take-superseded-by='draft-9']").selectOption("draft-11"); await card.locator('[data-action="supersede"]').click(); await expect.poll(() => verdicts()["draft-9"]?.superseded?.by).toBe("draft-11"); @@ -69,6 +71,7 @@ test("mark a take superseded: folded away, shown dimmed on request, and back", a const shown = page.locator("[data-take='draft-9']"); await expect(shown).toHaveAttribute("data-superseded", "draft-11"); await expect(shown.locator("[data-take-superseded]")).toHaveText("superseded by draft-11"); + await openPanel(page, "advanced", "take-card"); await shown.locator('[data-action="unsupersede"]').click(); await expect.poll(() => verdicts()["draft-9"]).toBeUndefined(); await expect(page.locator("[data-take='draft-9']")).not.toHaveAttribute("data-superseded", /.*/); @@ -76,10 +79,12 @@ test("mark a take superseded: folded away, shown dimmed on request, and back", a test("delete refuses a take that is rendering, and the take it is rendered from", async ({ page }) => { await page.goto(urls.takesHref(PROJECT)); + await openPanel(page, "advanced", "take-card"); await page.locator("[data-take='draft-12']").getByRole("button", { name: "Delete take draft-12" }).click(); const plan = page.getByRole("region", { name: "delete take draft-12" }); await expect(plan).toHaveAttribute("data-delete-blocked", "yes"); await expect(plan.getByRole("list", { name: "refused" })).toContainText("take draft-12: it is rendering now"); + await openPanel(page, "advanced", "take-card"); await page.locator("[data-take='draft-11']").getByRole("button", { name: "Delete take draft-11" }).click(); await expect(page.getByRole("region", { name: "delete take draft-11" }).getByRole("list", { name: "refused" })).toContainText("take draft-12 is being rendered from it"); expect(existsSync(takeFile("draft-12"))).toBe(true); diff --git a/umtool/e2e/take-variants.spec.ts b/umtool/e2e/take-variants.spec.ts @@ -3,6 +3,7 @@ import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; +import { openPanel } from "./panels"; // --------------------------------------------------------------------------- // Take housekeeping, the rest (UI notes 2026-10-30, item 19): @@ -79,6 +80,7 @@ test("Fork as variant: a project beside this one, with the take in it; compared await page.setViewportSize({ width: 1440, height: 1000 }); await page.goto(urls.takesHref(PROJECT)); const card = page.locator("[data-take='draft-2']"); + await openPanel(page, "options", "take-card"); await card.locator("[data-action='fork']").click(); await expect(card.locator("[data-take-fork-name='draft-2']")).toHaveValue("v-draft-2"); await card.locator("[data-action='fork-go']").click(); @@ -99,6 +101,7 @@ test("Fork as variant: a project beside this one, with the take in it; compared // Compare with…: the parent's draft-1 against the variant's draft-2. await page.goto(urls.takesHref(PROJECT)); const one = page.locator("[data-take='draft-1']"); + await openPanel(page, "options", "take-card"); await one.locator("[data-take-compare-with='draft-1']").selectOption("reports/v-draft-2:draft-2"); await one.locator("[data-action='compare']").click(); await expect(page.locator("[data-compare-player='b']")).toHaveAttribute("data-compare-take", "reports/v-draft-2:draft-2"); diff --git a/umtool/e2e/takes.spec.ts b/umtool/e2e/takes.spec.ts @@ -3,6 +3,7 @@ import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; +import { openPanel } from "./panels"; // --------------------------------------------------------------------------- // Takes: alternative renders of part of a cut, side by side, judged. @@ -207,6 +208,7 @@ test("the take maker: New take with a style, the take appears, Use this take mak expect(JSON.parse(readText("takes/crisp/video.manifest.json")).render.crf).toBe(34); // Use this take: the project's manifest is the take's, the badge shows. + await openPanel(page, "options", "take-card"); await card.locator("[data-action='pick']").click(); await expect(card.locator("[data-take-used]")).toBeVisible(); await expect(card.locator("[data-take-picked]")).toBeVisible(); @@ -228,6 +230,7 @@ test("the take maker: New take with a style, the take appears, Use this take mak writeFileSync(path.join(MAKE_DIR, "video.manifest.json"), JSON.stringify({ ...m, title: "Moved on" }, null, 2) + "\n"); await page.reload(); const soft = page.locator("[data-take='soft']"); + await openPanel(page, "options", "take-card"); await soft.locator("[data-action='pick']").click(); await expect(soft.locator("[data-take-stale]")).toContainText("The project changed since this take was made"); expect(JSON.parse(readText("video.manifest.json")).title).toBe("Moved on"); @@ -309,5 +312,6 @@ test("the Takes page with the New take form open fits a phone", async ({ page }) client: document.documentElement.clientWidth, })); expect(scroll).toBeLessThanOrEqual(client); + await openPanel(page, "options", "take-card"); await expect(page.locator("[data-action='pick']").first()).toBeVisible(); }); diff --git a/umtool/e2e/tighten.spec.ts b/umtool/e2e/tighten.spec.ts @@ -3,6 +3,7 @@ import { readFileSync, writeFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; +import { openPanel } from "./panels"; // --------------------------------------------------------------------------- // Tighten to the sentence, snap an edge to its pause, and Propose tight @@ -95,6 +96,8 @@ test("Snap edge: the start, then the end, each to the middle of its nearest paus test("Propose tight windows: a review list, nothing written until Apply; Apply and Undo per row", async ({ page }) => { await page.setViewportSize({ width: 1440, height: 1100 }); await page.goto(urls.section(PROJECT, "cut")); + await openPanel(page, "options", "cut"); + await openPanel(page, "advanced", "cut"); const panel = page.locator("[data-tight-windows]"); await panel.scrollIntoViewIfNeeded(); await panel.locator("[data-action='propose-tight']").click(); diff --git a/umtool/e2e/trailer-beats.spec.ts b/umtool/e2e/trailer-beats.spec.ts @@ -3,6 +3,7 @@ import { copyFileSync, existsSync, readFileSync, rmSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; +import { openPanel } from "./panels"; // --------------------------------------------------------------------------- // The Trailer page (UI notes 2026-10-30, item 11): @@ -44,6 +45,8 @@ async function open(page: Page) { test("the Cut tab links the Trailer page; it says the running length, the limit and the beat to fix", async ({ page }) => { await page.goto(urls.section(PROJECT, "timeline")); + await openPanel(page, "options", "cut"); + await openPanel(page, "advanced", "cut"); await expect(page.locator("[data-trailer-link]")).toHaveText("Trailer — 3 beats"); await page.locator("[data-trailer-link]").click(); await expect(page.getByTestId("trailer-editor")).toBeVisible(); diff --git a/umtool/e2e/voice-match.spec.ts b/umtool/e2e/voice-match.spec.ts @@ -3,6 +3,7 @@ import { readFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; +import { openPanel } from "./panels"; // --------------------------------------------------------------------------- // Who is speaking, per montage clip (release 34): the Cut tab's "Score the @@ -21,6 +22,8 @@ const FILE = path.join(HERE, "..", ".e2e-song", "reports", "voice-fixture", "voi test("Score the voices: a job writes voice-match.json and each clip row shows its score", async ({ page }) => { await page.goto(urls.section(PROJECT, "cut")); + await openPanel(page, "options", "cut"); + await openPanel(page, "advanced", "cut"); const panel = page.locator("[data-voice-match-panel]"); await expect(panel).toBeVisible(); await expect(page.locator("[data-voice-summary]")).toHaveCount(0); diff --git a/umtool/lib/queue/view.ts b/umtool/lib/queue/view.ts @@ -42,6 +42,8 @@ export type RenderView = { error: string | null; tail: string[]; mp4: string | null; + /** The project's directory (the jobs' pointer, or the take's reader): the mp4's absolute path is projectDir/takes/<take>/<mp4>. */ + projectDir?: string | null; seconds: number | null; pid: number; gone?: boolean; @@ -81,5 +83,6 @@ export async function rendersView(): Promise<RenderView[]> { /** One take's render record, resolved, or null. */ export async function takeRender(projectDir: string, take: string): Promise<RenderView | null> { - return (await readRenderRecord(path.join(/* turbopackIgnore: true */ projectDir, "takes", take))) as RenderView | null; + const rec = (await readRenderRecord(path.join(/* turbopackIgnore: true */ projectDir, "takes", take))) as RenderView | null; + return rec ? { ...rec, projectDir } : null; } diff --git a/umtool/lib/report/reelPlay.mjs b/umtool/lib/report/reelPlay.mjs @@ -361,14 +361,21 @@ export const REEL_CUT_TIMEOUT_MS = 45 * 60 * 1000; * @param {{ id: string }} project * @param {string} reel * @param {string} take - * @param {{ umtoolDir: string }} o + * @param {{ umtoolDir: string, finale?: number | null, out?: string | null, dryRun?: boolean }} o */ -export function reelCutSteps(project, reel, take, { umtoolDir }) { +export function reelCutSteps(project, reel, take, { umtoolDir, finale = null, out = null, dryRun = false }) { + // The cut's options (lane/ui-simplify, the reel panel's Options): --finale S (the master's last S seconds to close + // on), --out NAME (a NAME only -- never a path from a page), --dry-run (the mapping, nothing written). + const extra = [ + ...(Number.isFinite(finale) && finale > 0 ? ["--finale", String(finale)] : []), + ...(typeof out === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(out) ? ["--out", out] : []), + ...(dryRun ? ["--dry-run"] : []), + ]; return { - kind: `trailer ${project.id} ${reel} (${take})`, + kind: `trailer ${project.id} ${reel} (${take})${dryRun ? " (dry run)" : ""}`, steps: [{ - label: `cut the reel ${reel} from take ${take}'s master`, - argv: ["node", path.join(/* turbopackIgnore: true */ umtoolDir, "bin", "umtool.mjs"), "trailer", project.id, "--reel", reel, "--take", take], + label: `cut the reel ${reel} from take ${take}'s master${dryRun ? " (dry run)" : ""}`, + argv: ["node", path.join(/* turbopackIgnore: true */ umtoolDir, "bin", "umtool.mjs"), "trailer", project.id, "--reel", reel, "--take", take, ...extra], cwd: umtoolDir, env: {}, timeoutMs: REEL_CUT_TIMEOUT_MS, diff --git a/umtool/lib/report/takeEdit.mjs b/umtool/lib/report/takeEdit.mjs @@ -40,6 +40,8 @@ import path from "node:path"; import { StaleToken, applyStructural, + entryFromSpec, + entryIndex, moveIn, patchClipEntry, removeIn, @@ -316,6 +318,35 @@ export async function removeTakeEntry(projectDir, id, entryId, { token = null, a return editTakeTimeline(projectDir, id, "remove", token, (m) => applyStructural(m, (x) => removeIn(x, entryId, at, { reanchor: false })), { now }); } +/** + * INSERT an entry into ONE TAKE's timeline (lane/ui-simplify, 5 Nov: "add to this take only"): a clip + * `<channel>/<video>@<start>-<end>` or an entry object, as the project's insertEntry takes it + * (manifest.mjs entryFromSpec: a fresh id unless it names one), after `afterId` (null: at the start). + * Written into the take's patch with an undo point of the take's own; the project's manifest is untouched. + * The CLI twin is `umtool timeline <p> --take <id> insert <spec> --after <id>`. + * @param {string} projectDir + * @param {string} id the take + * @param {string | null} afterId + * @param {unknown} spec + * @param {{ token?: string | null, at?: number | null, now?: Date }} [opts] + */ +export async function insertTakeEntry(projectDir, id, afterId, spec, { token = null, at = null, now = new Date() } = {}) { + return editTakeTimeline( + projectDir, + id, + "insert", + token, + (m) => + applyStructural(m, (x) => { + const i = afterId ? entryIndex(x.timeline, afterId, at) + 1 : 0; + const entry = entryFromSpec(x.timeline, spec); + x.timeline.splice(i, 0, entry); + return { id: entry.id, at: i, entry }; + }), + { now }, + ); +} + /** A take's label: one line, at most this long. */ export const TAKE_LABEL_MAX = 200; diff --git a/umtool/lib/report/takeEdit.test.mjs b/umtool/lib/report/takeEdit.test.mjs @@ -304,7 +304,17 @@ test("the CLI twins: umtool walk --take, umtool timeline --take, umtool take --p assert.equal(await timelineCommand(["proj", "--take", "tight", "move", "t03a", "--to", "0"], io), 0, err.join("\n")); assert.match(out.join("\n"), /take tight: moved t03a: 3 -> 0/); assert.equal(await timelineCommand(["proj", "--take", "tight", "undo"], io), 0, err.join("\n")); - assert.equal(await timelineCommand(["proj", "--take", "tight", "insert", "--after", "-", "chan/vid@1-5"], io), 2, "only ls, move, remove, undo on a take"); + // "Add to this take only" (lane/ui-simplify): a clip into the take's timeline, never the project's. + const masterBefore = await masterText(dir); + out.length = 0; + assert.equal(await timelineCommand(["proj", "--take", "tight", "insert", "--after", "-", "chan/vid@1-5"], io), 0, err.join("\n")); + assert.match(out.join("\n"), /take tight: inserted/); + assert.equal(await masterText(dir), masterBefore, "the project's manifest is untouched"); + out.length = 0; + assert.equal(await timelineCommand(["proj", "--take", "tight", "ls"], io), 0, err.join("\n")); + assert.match(out.join("\n"), /5 entries in take tight of proj/); + assert.equal(await timelineCommand(["proj", "--take", "tight", "undo"], io), 0, err.join("\n")); + assert.equal(await timelineCommand(["proj", "--take", "tight", "insert", "chan/vid@1-5"], io), 2, "insert needs --after"); out.length = 0; assert.equal(await timelineCommand(["proj", "--take", "tight", "ls"], io), 0, err.join("\n")); assert.match(out.join("\n"), /4 entries in take tight of proj$/, "the move was undone: nothing left to undo"); diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -165,7 +165,7 @@ export const TIMELINE_USAGE = [ " umtool timeline <project> groups promote <gid> [--label L] the group opens a subsection: a level-2 marker at", " its first clip titled with its claim (--label when it is over 24); the render sees only this", " A clip moved out of its group's run leaves the group; moved alone into the middle of a run, it joins it", - " umtool timeline <project> --take <id> [ls | move <id> --to <index> | remove <id> | undo]", + " umtool timeline <project> --take <id> [ls | move <id> --to <index> | remove <id> | undo | insert <spec> --after <id>|-]", " a take's timeline (walk a take): written into the take's patch (takes/<id>/take.json),", " each write with an undo point of the take's own; the project's manifest is untouched", "", @@ -178,7 +178,7 @@ const VERBS = ["ls", "insert", "move", "place", "remove", "reject", "wrong-speak const GROUP_VERBS = ["ls", "import", "set", "move", "label", "promote", "remove"]; const VALUED = new Set(["--group", "--after", "--before", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note", "--to-section", "--label", "--color", "--level", "--claim", "--conversation"]); /** What `--take <id>` does on a take's timeline (takeEdit.mjs): the walk's structure and its undo. */ -const TAKE_VERBS = ["ls", "move", "remove", "undo"]; +const TAKE_VERBS = ["ls", "move", "remove", "undo", "insert"]; class CliError extends Error {} @@ -888,6 +888,13 @@ async function takeTimeline(project, take, verb, rest, flags, { out, json }) { const id = rest[0]; if (!id) throw new CliError("remove needs an entry id"); result = await edit.removeTakeEntry(project.dir, take, id, { token, at }); + } else if (verb === "insert") { + // "Add to this take only" (the Add a clip panel on a take): a clip spec into the take's timeline. + const spec = rest[0]; + if (!spec) throw new CliError("insert needs a clip: <channel>/<video>@<start>-<end>"); + if (!flags.has("--after")) throw new CliError("insert needs --after <id> (or --after - for the start)"); + const afterArg = String(flags.get("--after")); + result = await edit.insertTakeEntry(project.dir, take, afterArg === "-" || afterArg === "" ? null : afterArg, spec, { token, at }); } else { result = await edit.undoTakeEdit(project.dir, take, { token }); }