Archilyzer · Source

archilyzer

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

commit 5b1fd6cbfbdfcbb458377784b9f462aee20ba1e8
parent 1ca90779d58eb2193992d2bd437b683c1bc3339b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 20 Oct 2026 14:44:05 -0400

umtool: the Ask box — proposals as a diff, Apply through the manifest's writers, Dismiss; Preview join; the Look panel's slide and room numbers

The Look panel (with Preview join and the project's notes) and the clip editor's
side column ask the editor's video-assist job; the proposals show as a diff list
with Apply, Apply all and Dismiss; Apply re-checks each op and writes it through
updateRender, the clip editor's trim/room or updateChrome, token-guarded; Dismiss
writes only the marks. A whole-project note can be asked; the reply's assist
proposal carries an Apply all. build-video --join-preview renders the first four
joins in the saved look to out/join-preview.mp4 (heavy slot), played under the box.
The Look panel gains Travel / Smear / Grain and the room's Tail up to / Silence gap.
e2e video-assist.spec.ts on the editor stub.

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

Diffstat:
Aumtool/app/api/report/join-preview/route.ts | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/video-assist/route.ts | 139+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/report/AssistBox.tsx | 462+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/report/LookPanel.tsx | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/components/projects/review/ClipEditor.tsx | 16++++++++++++++++
Mumtool/components/projects/review/ClipSuggest.tsx | 1+
Mumtool/docs/report-video.md | 79++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/e2e/fixtures/editor-stub.mjs | 68+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Aumtool/e2e/fixtures/video-assist-fixture.mjs | 18++++++++++++++++++
Aumtool/e2e/video-assist.spec.ts | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/annotations/shape.mjs | 12++++++++++--
Mumtool/lib/annotations/types.ts | 4+++-
Mumtool/lib/create/policy.mjs | 1+
Aumtool/lib/report/joinPreview.mjs | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/videoAssist.mjs | 238+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/videoAssist.test.mjs | 139+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/build-video.mjs | 26++++++++++++++++++++++++++
Aumtool/report-to-video/join-preview.mjs | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/join-preview.test.mjs | 35+++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 1+
21 files changed, 1627 insertions(+), 13 deletions(-)

diff --git a/umtool/app/api/report/join-preview/route.ts b/umtool/app/api/report/join-preview/route.ts @@ -0,0 +1,82 @@ +import { stat } from "node:fs/promises"; +import { cancelJob, getJob, jobView, runningJob, startJob } from "@/lib/jobs"; +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { clipsOf, readManifest } from "@/lib/projects/report.mjs"; +import { rangeResponse } from "@/lib/report/serve.mjs"; +import { joinPreviewFile, joinPreviewSteps, readJoinPreview } from "@/lib/report/joinPreview.mjs"; + +export const dynamic = "force-dynamic"; + +// THE JOIN PREVIEW (release 38 lane E): `<project>/out/join-preview.mp4`, the +// first few joins of the cut in its current look (build-video.mjs +// --join-preview, in the heavy slot), as ONE job on the app's runner +// (lib/jobs.ts) -- the Look panel's Preview join. +// +// GET ?project=<id> { preview, running } +// GET ?project=<id>&file=1 the mp4 (ranges) +// GET ?job=<id>[&since=&sinceEvent=] that job +// POST { project, from? } make it (from that clip, else the first) +// ?cancel=<job> stop it +const headers = { "cache-control": "no-store" }; +const isPreviewJob = (kind: string) => /^join preview /.test(kind); + +async function reportProject(id: unknown) { + const project = await projectRef(String(id ?? "")); + if (!project) return { error: Response.json({ error: "no such project" }, { status: 404, headers }) }; + if (!kindMakesTakes(project.kind)) return { error: Response.json({ error: "a join preview is a report video's" }, { status: 400, headers }) }; + return { project }; +} + +export async function GET(request: Request) { + const url = new URL(request.url); + const jobId = url.searchParams.get("job"); + if (jobId) { + const job = getJob(jobId); + if (!job) return Response.json({ error: "no such job" }, { status: 404, headers }); + return Response.json(jobView(job, Number(url.searchParams.get("since") ?? 0), Number(url.searchParams.get("sinceEvent") ?? 0)), { headers }); + } + const r = await reportProject(url.searchParams.get("project")); + if ("error" in r) return r.error; + if (url.searchParams.get("file")) { + const abs = joinPreviewFile(r.project.dir); + const st = await stat(abs).catch(() => null); + if (!st?.isFile()) return new Response("no join preview", { status: 404 }); + return rangeResponse(request, { + abs, + size: st.size, + headers: { "content-type": "video/mp4", "accept-ranges": "bytes", "cache-control": "private, no-store" }, + }); + } + const manifest = await readManifest(r.project.dir); + const running = runningJob(); + return Response.json( + { + preview: await readJoinPreview(r.project.dir, manifest), + running: running && running.project === r.project.id && isPreviewJob(running.kind) ? jobView(running) : null, + }, + { headers }, + ); +} + +export async function POST(request: Request) { + const url = new URL(request.url); + const cancel = url.searchParams.get("cancel"); + if (cancel) return Response.json({ cancelled: cancelJob(cancel) }, { headers }); + 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, headers }); + const r = await reportProject(body.project); + if ("error" in r) return r.error; + const manifest = await readManifest(r.project.dir); + if (!manifest) return Response.json({ error: "no manifest" }, { status: 400, headers }); + const from = body.from === undefined || body.from === null || body.from === "" ? null : String(body.from); + if (from && !clipsOf(manifest).some((e: { id: string }) => e.id === from)) return Response.json({ error: `no clip with id ${from}` }, { status: 400, headers }); + const running = runningJob(); + if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409, headers }); + try { + const job = startJob(`join preview ${r.project.id}`, joinPreviewSteps(r.project, from), { project: r.project.id }); + return Response.json({ ok: true, job: jobView(job) }, { headers }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409, headers }); + } +} diff --git a/umtool/app/api/report/video-assist/route.ts b/umtool/app/api/report/video-assist/route.ts @@ -0,0 +1,139 @@ +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { askEditor, cancelDraftJob, EditorError, readDraftJob, readPolicy } from "@/lib/articles/generation"; +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, manifestToken } from "@/lib/report/manifest.mjs"; +import { + AssistRequestError, + applyAssistOps, + assistJobView, + assistRouteOf, + clearAssistJob, + dismissAssistOps, + draftBodyOf, + parseAssistRequest, + proposalsView, + readAssistJob, + writeAssistJob, +} from "@/lib/report/videoAssist.mjs"; + +export const dynamic = "force-dynamic"; + +// THE VIDEO ASSISTANT (release 38 lane E) -- optional, every part of it. An +// Ask (a request in words, or a note on the whole project) starts the +// EDITOR's `report-draft` job, task `video-assist`, routed by +// settings.generation (local by default, through the GPU arbiter); its +// proposals land in `<project>/assist-proposals.json`. This route asks with +// the shared WORKER_TOKEN (lib/articles/generation.ts askEditor), follows the +// job, and APPLIES on the operator's click: each op re-checked and written +// through the manifest's writers (lib/report/videoAssist.mjs), token-guarded. +// +// GET ?project=<id> { proposals, error, route, editorError, job, token } +// GET ?project=<id>&job=<jobId> that job (ended: forgotten) +// POST { project, request | note, scope? } → { jobId, job } +// POST { project, action: "apply", ids?, token, at? } → { applied, failed, token, proposals } | 409 +// POST { project, action: "dismiss", ids?, at? } → { dismissed, proposals } +// POST ?cancel=<jobId>&project=<id> stop it +const headers = { "cache-control": "no-store" }; + +async function assistProject(id: unknown) { + const project = await projectRef(String(id ?? "")); + if (!project) return { error: Response.json({ error: "no such project" }, { status: 404, headers }) }; + if (!kindMakesTakes(project.kind)) return { error: Response.json({ error: "the assistant works on a report video's cut" }, { status: 400, headers }) }; + return { project }; +} + +const failed = (e: unknown) => { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409, headers }); + const status = e instanceof EditorError ? e.status : e instanceof AssistRequestError ? ((e as AssistRequestError & { status?: number }).status ?? 400) : 500; + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers }); +}; + +async function jobOf(dir: string, id: string) { + const rec = await readAssistJob(dir); + const job = await readDraftJob(id, 40); + const view = assistJobView(rec && rec.jobId === id ? rec : null, job); + if (view.ended) await clearAssistJob(dir, id); + return view; +} + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await assistProject(url.searchParams.get("project")); + if ("error" in r) return r.error; + const dir = r.project.dir; + const id = url.searchParams.get("job"); + if (id) { + try { + return Response.json(await jobOf(dir, id), { headers }); + } catch (e) { + return failed(e); + } + } + const view = await proposalsView(dir); + // The route and the followed job need the editor; without one the proposals still show. + const policy = await readPolicy().catch((e: unknown) => e as Error); + const rec = await readAssistJob(dir); + let job = null; + if (rec) { + job = await jobOf(dir, rec.jobId).catch(async (e: unknown) => { + if (e instanceof EditorError && e.status === 404) await clearAssistJob(dir, rec.jobId); + return null; + }); + } + return Response.json( + { + ...view, + route: policy instanceof Error ? null : assistRouteOf(policy.generation, dir), + editorError: policy instanceof Error ? policy.message : null, + job, + token: await manifestToken(dir), + }, + { headers }, + ); +} + +export async function POST(request: Request) { + const url = new URL(request.url); + const cancel = url.searchParams.get("cancel"); + if (cancel) { + const r = await assistProject(url.searchParams.get("project")); + if ("error" in r) return r.error; + try { + await cancelDraftJob(cancel); + return Response.json({ cancelled: true }, { headers }); + } catch (e) { + return failed(e); + } + } + 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, headers }); + const r = await assistProject(body.project); + if ("error" in r) return r.error; + const dir = r.project.dir; + const ids = Array.isArray(body.ids) ? body.ids.map(String) : null; + const at = typeof body.at === "string" ? body.at : null; + try { + if (body.action === "apply") { + const token = body.token === undefined || body.token === null ? null : String(body.token); + const { result, editNotes } = await withEditNotes(r.project, () => applyAssistOps(r.project, { ids, token, at })); + return Response.json({ ok: true, ...result, editNotes }, { headers }); + } + if (body.action === "dismiss") return Response.json({ ok: true, ...(await dismissAssistOps(dir, { ids, at })) }, { headers }); + if (body.action !== undefined && body.action !== "ask") return Response.json({ error: 'action is "ask", "apply" or "dismiss"' }, { status: 400, headers }); + const req = parseAssistRequest(body); + const running = await readAssistJob(dir); + if (running) { + const view = await jobOf(dir, running.jobId).catch(() => null); + if (view && !view.ended) return Response.json({ error: "the assistant is already working on this project", job: view }, { status: 409, headers }); + } + const answer = await askEditor<{ jobId?: string }>("/api/ops/report-draft", { method: "POST", body: draftBodyOf(dir, req) }); + const jobId = String(answer.jobId ?? ""); + if (!jobId) return Response.json({ error: "the editor started no job" }, { status: 502, headers }); + await writeAssistJob(dir, { jobId, ...(req.note ? { note: req.note } : { request: req.request }), scope: req.scope, at: new Date().toISOString() }); + const job = await jobOf(dir, jobId).catch(() => ({ id: jobId, status: "queued", ended: false, queue: null, last: null, summary: null })); + return Response.json({ ok: true, jobId, job }, { headers }); + } catch (e) { + return failed(e); + } +} diff --git a/umtool/components/projects/report/AssistBox.tsx b/umtool/components/projects/report/AssistBox.tsx @@ -0,0 +1,462 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { badgeVariants } from "@/components/ui/badge"; +import { buttonVariants } from "@/components/ui/button"; +import { useSharedNotes } from "@/components/notes/NotesProvider"; +import { NoteThread } from "@/components/notes/NoteThread"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// THE ASK BOX (release 38 lane E): the video assistant, optional in every +// part. A request in words ("make the joins 0.15 s with less smear") starts +// the editor's `video-assist` job (routed by settings.generation: local by +// default, through the GPU arbiter); its PROPOSALS come back as a diff list +// -- Apply all, Apply one, Dismiss -- and nothing is written until Apply, +// which re-checks each op and writes through the manifest's own writers +// (/api/report/video-assist, lib/report/videoAssist.mjs). A note on the whole +// project can be asked too: the assistant replies on it, with an Apply. +// Preview join renders the first joins in the current look (the heavy slot). +// With generation routed elsewhere or no editor the box says so; the panel it +// sits in is the manual path. +// --------------------------------------------------------------------------- + +type Scope = "look" | "clips" | "fx" | "all"; +type ProposedOp = { id: string; op: Record<string, unknown>; diff: string; warning?: string; status: "proposed" | "applied" | "dismissed" | "failed"; error?: string; now?: string | null; diffNow?: string | null }; +type Proposals = { at: string; model: string; request: string; scope: string; note?: string; reply?: string; ops: ProposedOp[]; refused: { op: Record<string, unknown>; why: string }[] }; +type Job = { id: string; status: string; ended: boolean; queue: { key?: string; position?: number } | null; last: string | null; summary: string | null; note?: string; request?: string }; +type View = { + proposals: Proposals | null; + error: string | null; + route: { route: "code" | "api" | "local" | null; model: string | null; why: string | null } | null; + editorError: string | null; + job: Job | null; + token: string | null; +}; +type Preview = { size: number; mtimeMs: number; stale: boolean; record: { clips?: string[] } | null } | null; +type PreviewJob = { id: string; state: string; error: string | null }; + +const routeLine = (v: View): string => { + if (!v.route) return `The assistant needs the editor${v.editorError ? ` (${v.editorError})` : ""}. Every setting here is a field you can change by hand.`; + if (v.route.why) return `${v.route.why}. Every setting here is a field you can change by hand.`; + if (v.route.route === "local") return `On the local model${v.route.model ? ` (${v.route.model})` : ""}, through the GPU: it waits while a transcription runs. Nothing changes until you Apply.`; + return `On the Claude API${v.route.model ? ` (${v.route.model})` : ""}. Nothing changes until you Apply.`; +}; + +const jobLine = (j: Job): string => { + if (j.ended) return j.status === "done" ? (j.summary ?? "Done") : `The ask ${j.status}${j.last ? ` — ${j.last}` : ""}`; + if (j.status === "queued") { + const gpu = j.queue?.key === "draft:local"; + return `Queued${j.queue?.position ? ` (${j.queue.position} in line)` : ""}${gpu ? " — waiting for the GPU (a transcription runs first)" : ""}`; + } + return `Asking the assistant${j.last ? ` · ${j.last}` : ""}`; +}; + +const STATUS_WORD: Record<ProposedOp["status"], string> = { proposed: "proposed", applied: "applied", dismissed: "dismissed", failed: "not applied" }; + +export function useAssist(project: string) { + const [view, setView] = useState<View | null>(null); + const [job, setJob] = useState<Job | null>(null); + const [error, setError] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + const [ended, setEnded] = useState(0); + const load = useCallback(async () => { + const r = await fetch(`/api/report/video-assist?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null); + if (!r) return; + const j = (await r.json().catch(() => null)) as (View & { error?: string }) | null; + if (!r.ok || !j) { + setError(j?.error ?? `HTTP ${r.status}`); + return; + } + setView(j); + if (j.job && !j.job.ended) setJob(j.job); + }, [project]); + useEffect(() => { + void load(); + }, [load]); + const live = job && !job.ended ? job.id : null; + useEffect(() => { + if (!live) return; + const t = setInterval(async () => { + const r = await fetch(`/api/report/video-assist?project=${encodeURIComponent(project)}&job=${encodeURIComponent(live)}`, { cache: "no-store" }).catch(() => null); + if (!r?.ok) return; + const j = (await r.json()) as Job; + setJob(j); + if (j.ended) { + setEnded((n) => n + 1); + await load(); + } + }, 1500); + return () => clearInterval(t); + }, [live, project, load]); + const post = useCallback( + async (body: Record<string, unknown>) => { + setBusy(true); + setError(null); + try { + const r = await fetch("/api/report/video-assist", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, ...body }) }); + const j = (await r.json().catch(() => ({}))) as Record<string, unknown>; + return { ok: r.ok, status: r.status, json: j }; + } finally { + setBusy(false); + } + }, + [project], + ); + const ask = useCallback( + async (body: { request: string; scope: Scope } | { note: string; scope: Scope }) => { + // The last ask's line goes: what shows next is this one's. + setJob(null); + const r = await post(body); + if (r.json.job) setJob(r.json.job as Job); + if (!r.ok) setError(String(r.json.error ?? `HTTP ${r.status}`)); + return r.ok; + }, + [post], + ); + const apply = useCallback( + async (ids: string[] | null, at?: string) => { + const r = await post({ action: "apply", token: view?.token ?? null, ...(ids ? { ids } : {}), ...(at ? { at } : {}) }); + if (r.status === 409) { + await load(); + setError(`${String(r.json.error ?? "the cut changed")} — reloaded; check and apply again`); + return false; + } + if (!r.ok) setError(String(r.json.error ?? `HTTP ${r.status}`)); + await load(); + return r.ok && Array.isArray(r.json.applied) && (r.json.applied as unknown[]).length > 0; + }, + [post, view?.token, load], + ); + const dismiss = useCallback( + async (ids: string[] | null) => { + const r = await post({ action: "dismiss", ...(ids ? { ids } : {}), ...(view?.proposals ? { at: view.proposals.at } : {}) }); + if (!r.ok) setError(String(r.json.error ?? `HTTP ${r.status}`)); + await load(); + }, + [post, view?.proposals, load], + ); + const cancel = useCallback(async () => { + if (!job) return; + await fetch(`/api/report/video-assist?cancel=${encodeURIComponent(job.id)}&project=${encodeURIComponent(project)}`, { method: "POST" }).catch(() => null); + }, [job, project]); + return { view, job, error, busy, ended, load, ask, apply, dismiss, cancel }; +} + +/** The proposals as a diff list: Apply one, Apply all, Dismiss. */ +function ProposalList({ p, busy, onApply, onDismiss }: { p: Proposals; busy: boolean; onApply: (ids: string[] | null) => void; onDismiss: () => void }) { + const waiting = p.ops.filter((o) => o.status === "proposed" || o.status === "failed"); + const applicable = waiting.filter((o) => !o.now); + return ( + <section data-assist-proposals={p.ops.length} data-assist-at={p.at} className="space-y-1.5 rounded-[3px] border border-seam bg-panel-2 px-2.5 py-2"> + <p className="m-0 text-[11.5px] text-muted" data-assist-request=""> + &ldquo;{p.request}&rdquo; — {p.model} · {new Date(p.at).toLocaleString()} + </p> + {p.reply && ( + <p className="m-0 text-[12px] text-text-2" data-assist-reply=""> + {p.reply} + </p> + )} + {p.ops.length === 0 && <p className="m-0 text-[12px] text-muted">No edit proposed.</p>} + {p.ops.length > 0 && ( + <ul className="m-0 list-none space-y-1 p-0"> + {p.ops.map((o) => ( + <li key={o.id} data-assist-op={o.id} data-assist-status={o.status} className={cn("flex flex-wrap items-baseline gap-2 text-[12.5px]", o.status === "dismissed" && "opacity-60")}> + <span className={cn("font-mono text-text", o.status === "applied" && "text-kept-text")}>{o.status === "proposed" && o.diffNow && o.diffNow !== o.diff ? o.diffNow : o.diff}</span> + {o.status !== "proposed" && <span className={badgeVariants({ variant: o.status === "applied" ? "on" : o.status === "failed" ? "blocking" : "info", size: "sm" })}>{STATUS_WORD[o.status]}</span>} + {(o.status === "proposed" || o.status === "failed") && ( + <button type="button" data-assist-apply={o.id} disabled={busy || !!o.now} title={o.now ?? "write it now, through the look's (or the clip's) own writer"} onClick={() => onApply([o.id])} className={buttonVariants({ variant: "outline", size: "sm" })}> + Apply + </button> + )} + {o.warning && <span className="text-[11.5px] text-doubt-text">{o.warning}</span>} + {o.now && (o.status === "proposed" || o.status === "failed") && ( + <span className="text-[11.5px] text-muted" data-assist-now=""> + now: {o.now} + </span> + )} + {o.error && o.status === "failed" && !o.now && <span className="text-[11.5px] text-reject-text">{o.error}</span>} + </li> + ))} + </ul> + )} + {p.refused.length > 0 && ( + <ul className="m-0 list-none space-y-0.5 p-0" data-assist-refused-list=""> + {p.refused.map((r, i) => ( + <li key={i} data-assist-refused="" className="text-[11.5px] text-muted"> + not proposed: {r.why} + </li> + ))} + </ul> + )} + {waiting.length > 0 && ( + <div className="flex flex-wrap items-center gap-2 pt-0.5"> + <button type="button" data-assist-apply-all="" disabled={busy || !applicable.length} onClick={() => onApply(null)} className={buttonVariants({ variant: "go", size: "sm" })}> + Apply all + </button> + <button type="button" data-assist-dismiss="" disabled={busy} onClick={onDismiss} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Dismiss + </button> + </div> + )} + </section> + ); +} + +/** Preview join: the first joins in the look as saved (a render in the heavy slot), played here. */ +function JoinPreview({ project, version }: { project: string; version: string }) { + const [preview, setPreview] = useState<Preview>(null); + const [job, setJob] = useState<PreviewJob | null>(null); + const [error, setError] = useState<string | null>(null); + const load = useCallback(async () => { + const r = await fetch(`/api/report/join-preview?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null); + if (!r?.ok) return; + const j = (await r.json()) as { preview: Preview; running: PreviewJob | null }; + setPreview(j.preview); + if (j.running) setJob(j.running); + }, [project]); + useEffect(() => { + void load(); + }, [load, version]); + const running = job?.state === "running"; + useEffect(() => { + if (!job || job.state !== "running") return; + const t = setInterval(async () => { + const r = await fetch(`/api/report/join-preview?job=${job.id}`, { cache: "no-store" }).catch(() => null); + if (!r?.ok) return; + const j = (await r.json()) as PreviewJob; + setJob(j); + if (j.state !== "running") await load(); + }, 1500); + return () => clearInterval(t); + }, [job, load]); + const start = async () => { + setError(null); + const r = await fetch("/api/report/join-preview", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project }) }); + const j = (await r.json().catch(() => ({}))) as { job?: PreviewJob; error?: string }; + if (!r.ok || !j.job) setError(j.error ?? `HTTP ${r.status}`); + else setJob(j.job); + }; + return ( + <div className="space-y-1.5" data-join-preview={preview ? (preview.stale ? "stale" : "fresh") : "none"}> + <div className="flex flex-wrap items-center gap-2"> + <button type="button" data-assist-preview="" disabled={running} onClick={() => void start()} className={buttonVariants({ size: "sm" })} title="the first joins of the cut, a few seconds either side, in the look as saved (a render, in the machine's heavy slot)"> + {running ? "Rendering the preview…" : preview ? "Preview join again" : "Preview join"} + </button> + {running && ( + <button type="button" onClick={() => void fetch(`/api/report/join-preview?cancel=${job!.id}`, { method: "POST" })} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Stop + </button> + )} + {preview?.stale && <span className="text-[11.5px] text-doubt-text">the look changed since this preview</span>} + {job && !running && job.state !== "done" && <span className="text-[11.5px] text-reject-text">preview {job.state}{job.error ? `: ${job.error}` : ""}</span>} + {error && ( + <span role="alert" className="text-[11.5px] text-reject-text"> + {error} + </span> + )} + </div> + {preview && ( + <video + data-assist-preview-video="" + key={preview.mtimeMs} + src={`/api/report/join-preview?project=${encodeURIComponent(project)}&file=1&v=${preview.mtimeMs}`} + controls + loop + className="max-h-[240px] w-full max-w-[480px] rounded-[3px] border border-seam bg-ground" + /> + )} + </div> + ); +} + +/** The project-level notes, each with Ask the assistant; an agent reply's proposals with Apply all. */ +function ProjectNotes({ project, a, scope, apply }: { project: string; a: ReturnType<typeof useAssist>; scope: Scope; apply: (ids: string[] | null, at?: string) => Promise<boolean> }) { + const notes = useSharedNotes({ project }); + const reloadNotes = notes.reload; + useEffect(() => { + if (a.ended) void reloadNotes(); + }, [a.ended, reloadNotes]); + const [text, setText] = useState(""); + const whole = notes.notes.filter((n) => n.anchor.kind === "whole"); + const blocked = a.view?.route?.why ?? (a.view && !a.view.route ? "the assistant needs the editor" : null); + const asking = a.job && !a.job.ended ? a.job.note : null; + const p = a.view?.proposals ?? null; + const add = async () => { + if (!text.trim()) return; + const n = await notes.write({ op: "add", text, anchor: { kind: "whole" } }); + if (n) setText(""); + }; + return ( + <section data-assist-notes={whole.length} className="space-y-1.5"> + <h3 className="micro m-0">Notes on the project{whole.length ? ` — ${whole.filter((n) => n.status === "open").length} open` : ""}</h3> + {whole.map((n) => ( + <NoteThread + key={n.id} + note={n} + write={notes.write} + busy={notes.busy} + actions={ + n.status === "open" ? ( + <button + type="button" + data-note-action="assist" + disabled={notes.busy || a.busy || !!blocked || !!asking} + title={blocked ?? "the assistant reads this note as a request and replies here; what it proposes waits for your Apply"} + onClick={() => void a.ask({ note: n.id, scope })} + className="ink-link disabled:opacity-40" + > + {asking === n.id ? "Asking…" : "Ask the assistant"} + </button> + ) : null + } + afterReply={(r) => { + const pr = r.proposal; + if (!pr || pr.kind !== "assist" || r.author !== "agent") return null; + const current = !!p && p.at === pr.at; + const waiting = current ? p!.ops.filter((o) => o.status === "proposed" && !o.now).length : 0; + return ( + <div data-reply-proposal="assist" className="ml-4 flex flex-wrap items-center gap-1.5 text-[11px] text-text-2"> + <span className={badgeVariants({ variant: "meter", size: "sm" })}>proposes</span> + <span> + {pr.ops} edit{pr.ops === 1 ? "" : "s"} + </span> + {!current ? ( + <span className="text-muted">a newer ask replaced these</span> + ) : waiting ? ( + <button + type="button" + data-apply-proposal="assist" + disabled={a.busy} + onClick={() => + void apply(null, pr.at).then((ok) => { + if (ok) void notes.write({ op: "reply", id: n.id, text: "Applied the assistant's edits" }); + }) + } + className={buttonVariants({ variant: "go", size: "sm" })} + > + Apply all + </button> + ) : ( + <span className="text-muted">nothing waiting</span> + )} + </div> + ); + }} + /> + ))} + <div className="flex flex-wrap items-start gap-2"> + <textarea + data-assist-note-input="" + value={text} + rows={1} + onChange={(e) => setText(e.target.value)} + placeholder="a note on the whole project — for you or the assistant" + className="min-w-[14rem] flex-1 resize-y rounded border border-seam-2 bg-ground px-1.5 py-1 text-[12.5px] text-text outline-none focus:border-signal" + /> + <button type="button" data-assist-note-add="" disabled={notes.busy || !text.trim()} onClick={() => void add()} className={buttonVariants({ size: "sm" })}> + Add note + </button> + </div> + </section> + ); +} + +/** + * The Ask box. `scope`: what an ask may touch here (the Look panel: the look; + * the clip editor: the clips). `onApplied`: the page re-reads what Apply + * wrote. `version`: changes when the page wrote the manifest itself (the box + * re-reads its token). `subject`: the clip the page has selected -- a request + * that names no clip is sent as about it ("… (on clip r002)"). + */ +export default function AssistBox({ + project, + scope, + placeholder, + onApplied, + version = 0, + subject, + preview = false, + notes = false, +}: { + project: string; + scope: Scope; + placeholder?: string; + onApplied?: () => void; + version?: number | string; + subject?: string; + preview?: boolean; + notes?: boolean; +}) { + const a = useAssist(project); + const [text, setText] = useState(""); + const { load } = a; + const first = useRef(true); + useEffect(() => { + if (first.current) { + first.current = false; + return; + } + void load(); + }, [version, load]); + const v = a.view; + const blocked = !v ? "reading…" : (v.route?.why ?? (!v.route ? "no editor" : null)); + const running = !!a.job && !a.job.ended; + const submit = async () => { + if (!text.trim()) return; + // A clip id is letters, digits, ".", "_" and "-": only the dot needs escaping. + const id = subject ? subject.replace(/\./g, "\\.") : ""; + const named = !!subject && new RegExp(`(^|[^A-Za-z0-9_-])${id}([^A-Za-z0-9_-]|$)`).test(text); + const request = subject && !named ? `${text.trim()} (on clip ${subject})` : text; + if (await a.ask({ request, scope })) setText(""); + }; + const apply = async (ids: string[] | null, at = v?.proposals?.at) => { + const ok = await a.apply(ids, at); + if (ok) onApplied?.(); + return ok; + }; + return ( + <div data-assist-box={scope} data-assist-route={v?.route?.route ?? "none"} className="space-y-2"> + <div className="flex flex-wrap items-start gap-2"> + <textarea + data-assist-input="" + value={text} + rows={2} + disabled={!!blocked || running} + onChange={(e) => setText(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) void submit(); + }} + placeholder={placeholder ?? "ask in words — “make the joins 0.15 s with less smear”"} + className="min-w-[16rem] flex-1 resize-y rounded border border-seam-2 bg-ground px-1.5 py-1 text-[12.5px] text-text outline-none focus:border-signal disabled:opacity-60" + /> + <button type="button" data-assist-ask="" disabled={!!blocked || running || a.busy || !text.trim()} onClick={() => void submit()} className={buttonVariants({ variant: text.trim() ? "go" : "outline", size: "md" })}> + {running ? "Asking…" : "Ask"} + </button> + {running && ( + <button type="button" data-assist-cancel="" onClick={() => void a.cancel()} className={buttonVariants({ variant: "quiet", size: "md" })}> + Stop + </button> + )} + </div> + {v && ( + <p className="m-0 text-[11.5px] text-muted" data-assist-status=""> + {routeLine(v)} + </p> + )} + {a.job && ( + <p className="m-0 text-[11.5px] text-text-2" data-assist-job={a.job.status}> + {jobLine(a.job)} + </p> + )} + {(a.error || v?.error) && ( + <p role="alert" className="m-0 text-[11.5px] text-reject-text" data-assist-error=""> + {a.error ?? v?.error} + </p> + )} + {v?.proposals && <ProposalList p={v.proposals} busy={a.busy} onApply={(ids) => void apply(ids)} onDismiss={() => void a.dismiss(null)} />} + {preview && <JoinPreview project={project} version={`${version}:${a.ended}`} />} + {notes && <ProjectNotes project={project} a={a} scope={scope} apply={apply} />} + </div> + ); +} diff --git a/umtool/components/projects/report/LookPanel.tsx b/umtool/components/projects/report/LookPanel.tsx @@ -4,6 +4,8 @@ import { useCallback, useEffect, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { Field, Input, Select } from "@/components/ui/field"; import { Panel } from "@/components/ui/panel"; +import { ROOM, ROOM_BOUNDS, SLIDE_BOUNDS, SLIDE_DEFAULTS } from "yt-dlp-transcript-common/lib/report/look.mjs"; +import AssistBox from "./AssistBox"; // THE LOOK (release 36 lane C): the render keys a person sets for a cut with // no deck -- the header, the timeline footer, the QR, the crossfade's length @@ -12,6 +14,11 @@ import { Panel } from "@/components/ui/panel"; // /api/report/render (lib/report/manifest.mjs updateRender, the build's own // checks). Nothing here calls a model. A deck cut keeps its own settings // (the Media tab); a montage levels with render.montage. +// Release 38 lane E: the blur slide's knobs (travel, smear, grain) and the +// room's numbers (how far the tail may run, the silence that ends it) are +// fields too, so every op the video assistant can propose is one here; the +// assistant's Ask box (AssistBox: optional, its proposals applied only on +// Apply) and Preview join sit under the fields. type Look = { headerHeight?: number; @@ -22,6 +29,7 @@ type Look = { loudness?: { target: number } | null; captions?: { style: "speakers"; labels?: { host?: string | null; subject?: string | null } | null; size?: "m" | "l" } | null; room?: { tail?: boolean; head?: boolean; minGap?: number; maxS?: number } | null; + slide?: { travel?: number; blur?: number; grain?: number } | null; }; type View = { look: Look; deck: boolean; montage: boolean; styles: string[]; errors: string[]; token: string | null }; @@ -41,6 +49,11 @@ type Draft = { size: "m" | "l"; roomTail: boolean; roomHead: boolean; + roomMaxS: string; + roomMinGap: string; + travel: string; + smear: string; + grain: string; }; function draftOf(l: Look): Draft { @@ -59,9 +72,20 @@ function draftOf(l: Look): Draft { size: l.captions?.size ?? "m", roomTail: l.room?.tail === true, roomHead: l.room?.head === true, + roomMaxS: String(l.room?.maxS ?? ROOM.maxS), + roomMinGap: String(l.room?.minGap ?? ROOM.minGap), + travel: String(l.slide?.travel ?? SLIDE_DEFAULTS.travel), + smear: String(l.slide?.blur ?? SLIDE_DEFAULTS.blur), + grain: String(l.slide?.grain ?? SLIDE_DEFAULTS.grain), }; } +const SLIDE_KEYS = [ + ["travel", "travel"], + ["blur", "smear"], + ["grain", "grain"], +] as const; + /** The patch that takes the saved look to the draft: only what changed, `null` to remove a key. */ function patchOf(was: Look, d: Draft, view: View): Record<string, unknown> { const p: Record<string, unknown> = {}; @@ -84,10 +108,29 @@ function patchOf(was: Look, d: Draft, view: View): Record<string, unknown> { // Room at the clips' edges (release 36 lane E): its settings kept as written. const was0 = was.room ?? null; const on = d.roomTail || d.roomHead; - const next = on ? { ...(was0 ?? {}), tail: d.roomTail, head: d.roomHead } : null; - const same = (was0?.tail === true) === d.roomTail && (was0?.head === true) === d.roomHead; + // The numbers (release 38): written only when they differ from the build's defaults. + const nums: Record<string, number> = {}; + const maxS = Number(d.roomMaxS); + const minGap = Number(d.roomMinGap); + if (maxS !== ROOM.maxS || was0?.maxS !== undefined) nums.maxS = maxS; + if (minGap !== ROOM.minGap || was0?.minGap !== undefined) nums.minGap = minGap; + const { maxS: _m, minGap: _g, ...edges } = was0 ?? {}; + const next = on ? { ...edges, tail: d.roomTail, head: d.roomHead, ...nums } : null; + const same = + (was0?.tail === true) === d.roomTail && + (was0?.head === true) === d.roomHead && + (!on || ((was0?.maxS ?? ROOM.maxS) === maxS && (was0?.minGap ?? ROOM.minGap) === minGap)); if (!same) p.room = next; } + // The blur slide's knobs (release 38): only the ones off their defaults are written. + { + const cur = { travel: Number(d.travel), blur: Number(d.smear), grain: Number(d.grain) }; + const had = { ...SLIDE_DEFAULTS, ...(was.slide ?? {}) }; + if (SLIDE_KEYS.some(([k]) => cur[k] !== had[k])) { + const next = Object.fromEntries(SLIDE_KEYS.filter(([k]) => cur[k] !== SLIDE_DEFAULTS[k]).map(([k]) => [k, cur[k]])); + p.slide = Object.keys(next).length ? next : null; + } + } return p; } @@ -97,6 +140,8 @@ export default function LookPanel({ project }: { project: string }) { const [busy, setBusy] = useState(false); const [error, setError] = useState<string | null>(null); const [status, setStatus] = useState<string | null>(null); + // Bumped when this panel writes the manifest, so the Ask box re-reads its token. + const [version, setVersion] = useState(0); const load = useCallback(async () => { const r = await fetch(`/api/report/render?project=${encodeURIComponent(project)}`, { cache: "no-store" }); @@ -139,6 +184,7 @@ export default function LookPanel({ project }: { project: string }) { } setView({ ...view, look: j.look ?? {}, token: j.token ?? null, errors: [] }); setDraft(draftOf(j.look ?? {})); + setVersion((n) => n + 1); setStatus("Saved — the next render uses it"); } finally { setBusy(false); @@ -197,6 +243,40 @@ export default function LookPanel({ project }: { project: string }) { {check("roomTail", "Tail: sound to the first silence, then muted", "data-look-room-tail", Number(draft.transition) === 0)} {check("roomHead", "Head: muted lead-in", "data-look-room-head", Number(draft.transition) === 0)} {Number(draft.transition) === 0 && <span className="text-[12px] text-muted">no join to make room for</span>} + {(draft.roomTail || draft.roomHead) && Number(draft.transition) !== 0 && ( + <span className="flex flex-wrap items-end gap-3"> + <Field label="Tail up to, s"> + <Input data-look-room-max="" type="number" min={ROOM_BOUNDS.maxS[0]} max={ROOM_BOUNDS.maxS[1]} step={0.1} value={draft.roomMaxS} disabled={busy || !draft.roomTail} onChange={(e) => set({ roomMaxS: e.target.value })} className="w-[5.5em]" /> + </Field> + <Field label="Silence gap, s"> + <Input data-look-room-gap="" type="number" min={ROOM_BOUNDS.minGap[0]} max={ROOM_BOUNDS.minGap[1]} step={0.05} value={draft.roomMinGap} disabled={busy || !draft.roomTail} onChange={(e) => set({ roomMinGap: e.target.value })} className="w-[5.5em]" /> + </Field> + </span> + )} + </div> + )} + {draft.style === "blurslide" && Number(draft.transition) !== 0 && ( + <div className="mt-3 flex flex-wrap items-end gap-4" data-look-slide=""> + <span className="text-[12.5px] text-text-2">Blur slide</span> + {SLIDE_KEYS.map(([k, word]) => { + const field = k === "blur" ? "smear" : k; + const [lo, hi] = SLIDE_BOUNDS[k]; + return ( + <Field key={k} label={word[0]!.toUpperCase() + word.slice(1)}> + <Input + {...{ [`data-look-slide-${word}`]: "" }} + type="number" + min={lo} + max={hi} + step={k === "grain" ? 1 : k === "travel" ? 0.01 : 0.1} + value={draft[field]} + disabled={busy} + onChange={(e) => set({ [field]: e.target.value } as Partial<Draft>)} + className="w-[5.5em]" + /> + </Field> + ); + })} </div> )} <div className="mt-3 space-y-2"> @@ -247,6 +327,11 @@ export default function LookPanel({ project }: { project: string }) { ) : null} </span> </div> + {/* --- the assistant (release 38): optional; its proposals wait for Apply */} + <div className="mt-4 border-t border-seam pt-3" data-look-assist=""> + <h3 className="micro m-0 mb-2">Ask the assistant</h3> + <AssistBox project={project} scope="all" version={version} onApplied={() => void load().catch((e) => setError(e instanceof Error ? e.message : String(e)))} preview notes /> + </div> </Panel> ); } diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx @@ -13,6 +13,7 @@ import type { EditorClip, EditorView, Neighbourhood, Proposal, RenderTarget, Spe import { cn } from "@/lib/utils"; import { ROOM, roomShade } from "umtool-report-to-video/room"; import { startTakeJob } from "../NewTakePanel"; +import AssistBox from "../report/AssistBox"; // Release 36 lane D: the assistant's labels, Suggest, Ask and Apply (all optional). import type { ReplyProposal } from "@/lib/annotations/types"; import { proposalWords, ReplyProposalRow, SuggestLabel, SuggestPanel, SuggestWhy, useClipSuggest, type ClipSuggest } from "./ClipSuggest"; @@ -313,12 +314,15 @@ export default function ClipEditor({ // An agent reply's proposal, applied ON THE OPERATOR'S CLICK through the // writer every other edit here uses (release 36 lane D). const canApply = (p: ReplyProposal): string | null => { + // The video assistant's proposals (release 38) are applied in its Ask box, not here. + if (p.kind === "assist") return "apply it in the assistant's box"; const at = clips.findIndex((c) => c.id === p.clip); if (at < 0) return `${p.clip} is no longer in the cut`; if (p.kind === "merge" && clips[at + 1]?.id !== p.with) return `${p.with} is no longer the next clip`; return null; }; const applyProposal = async (p: ReplyProposal): Promise<boolean> => { + if (p.kind === "assist") return false; await flush(); const j = p.kind === "trim" @@ -628,6 +632,18 @@ export default function ClipEditor({ {/* ---- the list, the proposals, the speakers, the take --------------- */} <aside className="flex min-h-0 flex-col gap-3 overflow-auto border-t border-seam bg-panel p-3 lg:border-l lg:border-t-0" data-editor-side=""> <SuggestPanel s={assistant} sorted={byRank} onSort={setByRank} /> + {/* Release 38: the video assistant — a request in words, its proposals applied only on Apply. */} + <section data-editor-assist=""> + <h2 className="micro m-0 mb-1">Ask the assistant</h2> + <AssistBox + project={project} + scope="all" + subject={clip.id} + version={view.token ?? ""} + onApplied={() => void reload().catch((e) => setError(e instanceof Error ? e.message : String(e)))} + placeholder={`ask in words — “cut the first 2 s”, “no room on this clip”, “quicker joins”`} + /> + </section> <section> <h2 className="micro mb-1"> {plural(clips.length, "clip")} · {clips.filter((c) => c.ruling === "keep").length} kept · {clips.filter((c) => c.ruling === "cut").length} cut diff --git a/umtool/components/projects/review/ClipSuggest.tsx b/umtool/components/projects/review/ClipSuggest.tsx @@ -214,6 +214,7 @@ export function SuggestPanel({ s, sorted, onSort }: { s: ClipSuggest; sorted: bo /** What an agent reply proposes, in words. */ export function proposalWords(p: ReplyProposal): string { + if (p.kind === "assist") return `${p.ops} edit${p.ops === 1 ? "" : "s"} of the look or the cut (the Ask box)`; if (p.kind === "trim") return `trim ${p.clip} to ${edgeClock(p.from)}–${edgeClock(p.to)} (${(p.to - p.from).toFixed(1)} s)`; if (p.kind === "merge") return `merge ${p.clip} with ${p.with}`; return `cut ${p.clip}`; diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -1268,9 +1268,12 @@ head: true}` (lane B's seed, with lane E's join and room). **The Look panel** (the Build tab, `/api/report/render`) sets them by hand: **Header**, **Timeline footer**, **QR code**, the length **Between clips** (0 is a hard cut) and the **Join** (crossfade, dip to black, dip to white, dissolve, -blur slide), **Room at the clips' edges** (Tail, Head — below), -**Loudness** (as recorded, −16 LUFS, or a custom target) and **Speaker -captions** with each role's name and the size. **Save the look** writes only +blur slide), **Room at the clips' edges** (Tail, Head, and with the tail on +**Tail up to, s** — `maxS` — and **Silence gap, s** — `minGap`; below), the +**Blur slide**'s **Travel**, **Smear** (`slide.blur`) and **Grain** when the +join is a blur slide, **Loudness** (as recorded, −16 LUFS, or a custom target) +and **Speaker captions** with each role's name and the size — so every edit +the video assistant can propose is also a field here (release 38). **Save the look** writes only what changed (`lib/report/manifest.mjs` `updateRender`: token-guarded, the build's own checks, atomic; `null` puts a key back to the build's default). It never touches `render.chrome` (the deck's own settings, the Media tab); a deck @@ -1356,6 +1359,76 @@ own time. `render.slide` = `{travel: 0.08, blur: 0.5, grain: 2}` by default length is `render.transition` (the seed's 0.22 s). A dip, a THEN/NOW wipe and a whip keep their own look. With room at both edges the slide runs over muted picture. +## The video assistant: Ask, Apply, Preview join (release 38) + +"Make the joins 0.15 s with less smear" — a small change to a cut in words, +on the local model when Claude Code is not at hand. Optional in every part: +with generation routed elsewhere, or no editor, the box says so, and the Look +panel above it is the same panel. + +**The Ask box** sits under the Look panel's fields (the Build tab) and in the +clip editor's side column (where a request that names no clip is sent as about +the selected one: "… (on clip r002)"). An ask is one editor job, `report-draft` +task **`video-assist`** (`common/controller/videoAssist.ts`), routed by +`settings.generation.routes["video-assist"]` — **local in every preset but +`api`**: on `draft:local`, through the GPU arbiter, so it waits while a +transcription runs (the box says so), and ollama is unloaded after; on the API +the narration cap and the daily cap hold it and its usage is a ledger row; +`code` = a Claude Code session answers the request (`/gen`, the MCP's +`generate`). The task asks once, schema-bound — `{ops: [{op, id, key, value}], +reply}` — over the project's compact view: the look now, the blur slide's +knobs, the room, the clips with their cuts and the window each may move in, +and the declared params of the compositions the cut draws, trimmed to the +prompt cap (the clips the request names first). + +**The ops** (`common/lib/report/videoAssistOps.mjs`), each checked against the +manifest as it is, with its diff line: + +| Op | What | Checked by | +|---|---|---| +| `look` | a LOOK_KEYS render key (`transition`, `transitionStyle`, `qr`, `loudness`, `captions`, `headerHeight`, …) | `applyLookPatch` — the same function `updateRender` writes with (common `lib/report/look.mjs`, whose validators the build and the lint call too) | +| `slide` | `travel` / `blur` (the smear) / `grain` | within `SLIDE_BOUNDS` (0–0.5, 0–2, 0–20) | +| `room` | `tail` / `head` (on or off), `maxS` (how far the tail runs, 0–10 s), `minGap` (0.1–2 s); a number for the tail turns it on up to that ("keep 2 s after the last word") | `ROOM_BOUNDS`, `validateRoom` | +| `clip_edges` | a clip's cut, `start` / `end` in seconds on its recording | inside the clip's source window (its extent; a clip with no cut, its edges widened by `fetchPad`), at least 0.5 s, and an edge moves at most 3 s unless the request names more seconds | +| `clip_room` | one clip's room: `tail` / `head`, `off` (none), `reset` (the cut's again) | `validateRoom` | +| `fx` | a composition's DECLARED param (`deck`, `stats`, `fx.<effect>`): e.g. the deck's `motion.in`, the glitch's `seconds` | its declaration's bounds (`common/lib/report/fxParams.mjs`; `fx-params.test.mjs` holds each to `validateChrome`); never free HTML | + +An op the checks refuse is not proposed: it is listed with its reason +("render.transition must be a number of seconds from 0 (a hard cut) to 3"). +The job writes **`<project>/assist-proposals.json`** — the request, the model, +the kept ops with their diff lines, the refused with their reasons — and +**nothing else**: no manifest, no clip, no note. + +**Apply** (one op, or **Apply all**) re-checks each op against the manifest as +it is then and writes it through the manifest's own writer — `updateRender` for +the look, the slide and the room; the clip editor's `trim` and `room` for a +clip (an assistant's clip becomes the operator's, as any trim makes it); +`updateChrome` for a composition's param — token-guarded, the token carried +from one write to the next (`/api/report/video-assist`, +`lib/report/videoAssist.mjs`). A token that went stale stops it (reload); an op +the manifest no longer allows fails with the reason (the list says so before +the click: "now: …"). **Dismiss** marks the waiting ops and writes nothing +else. An applied op is marked applied. + +**A note on the whole project** (the box's **Notes on the project**): **Ask the +assistant** sends the note's text as the request; the proposals are posted back +to it as the agent's reply, carrying an **Apply all** while they are the +latest. + +**Preview join** renders the first four joins of the cut in the look as saved — +each clip cut to the last 3 s of its cut (the last clip, its first 3 s), every +other entry left out, the windows untouched so the fetched media is reused — +to `out/join-preview.mp4` (and `out/join-preview.json`, what it was made +from), and plays it under the box; it says when the look has changed since. A +job on umtool's runner (`/api/report/join-preview`), `build-video.mjs +<manifest> --join-preview [--join-from <clip>]` inside the heavy slot; the +cut's own `out/` files (its segments, chapters, YouTube text) are not touched. +Not for a deck cut, a montage or hard cuts. + +From a terminal: `pnpm ops report-draft '{"task": "video-assist", "project": +"<dir>", "request": "quicker joins", "dryRun": true}'` (the prompt and its +estimate), then without `dryRun`. + ## Operator notes, timed notes and the generated-manifest guard Notes on a project live in `<project>/notes.json` (shape and CLI: diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -25,6 +25,8 @@ import { fileURLToPath } from "node:url"; import { fetchWindowsRoute } from "./editor-stub-fetch-windows.mjs"; import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; import { readSuggestions, suggestionsDocOf, writeSuggestions } from "yt-dlp-transcript-common/lib/clips/suggest.mjs"; +import { checkAssistOps } from "yt-dlp-transcript-common/lib/report/videoAssistOps.mjs"; +import { proposalsDocOf, writeAssistProposals } from "yt-dlp-transcript-common/lib/report/videoAssistProposals.mjs"; const PORT = portFor("EDITOR_STUB_PORT"); const CHANNELS = process.env.CHANNELS_DIR ?? ""; @@ -134,11 +136,12 @@ function writeWindow(dir, name, seconds) { // startCannedDraft) — every isStepTask step answered. const ARTICLES = process.env.ARTICLES_DIR ?? ""; const GEN_PROJECTS = process.env.E2E_GEN_PROJECTS ?? ""; +// Release 38 lane E: video-assist is local in every preset but api, as the editor's. const PRESETS = { - code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code" }, - balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api" }, - api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api" }, - local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local" }, + code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", "video-assist": "local" }, + balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", "video-assist": "local" }, + api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", "video-assist": "api" }, + local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", "video-assist": "local" }, }; const generation = { preset: "balanced", @@ -846,6 +849,53 @@ function finishRefresh(job, parent, p) { job.log.push(`refresh: ${summary}`, `@@report-draft ${JSON.stringify({ article, iteration: n, task: "refresh", status: "done", summary, refresh: patch.refresh })}`); } +// A `video-assist` report-draft (release 38 lane E): a canned "model" reads +// the request's words (0.15 → the join, "smear" → the slide's blur, "QR" → +// off, "louder" → -14 LUFS, "5 seconds" → a join the checks refuse) and the +// ops are checked and written through common's own checker and writer, as +// the real task does; a note's Ask (body.note) reads its text from +// notes.json and posts no reply (the stub cannot reach umtool). +const ASSIST_CANNED = [ + [/0\.15/, { op: "look", id: "", key: "transition", value: 0.15 }], + [/smear/i, { op: "slide", id: "", key: "blur", value: 0.3 }], + [/\bqr\b/i, { op: "look", id: "", key: "qr", value: false }], + [/louder/i, { op: "look", id: "", key: "loudness", value: -14 }], + [/5 seconds/i, { op: "look", id: "", key: "transition", value: 5 }], +]; +function startVideoAssist(body) { + if (typeof body.project !== "string" || !body.project.startsWith("/")) throw new Error('"project" is the video project\'s absolute directory'); + let request = typeof body.request === "string" ? body.request : ""; + if (typeof body.note === "string") { + const notes = JSON.parse(readFileSync(path.join(body.project, "notes.json"), "utf8")); + const n = (notes.notes ?? []).find((x) => x.id === body.note); + if (!n) throw new Error(`no note ${body.note}`); + request = n.text; + } + if (!request.trim()) throw new Error("the assistant needs a request"); + const id = `stub-assist-${nextJob++}`; + const job = { id, article: null, n: 0, task: "video-assist", status: "queued", at: Date.now(), log: [`report-draft video-assist (stub)`], timers: [] }; + draftJobs.set(id, job); + job.timers.push(setTimeout(() => { job.status = "running"; job.log.push("asking the stub model"); }, 300)); + job.timers.push( + setTimeout(async () => { + try { + const manifest = JSON.parse(readFileSync(path.join(body.project, "video.manifest.json"), "utf8")); + const ops = ASSIST_CANNED.filter(([re]) => re.test(request)).map(([, op]) => op); + const checked = checkAssistOps(manifest, ops, { request, scope: body.scope ?? "all" }); + const doc = proposalsDocOf({ at: new Date().toISOString(), model: generation.models.local, request, scope: body.scope ?? "all", note: body.note ?? null, reply: ops.length ? "Done as asked." : "Nothing I can change for that.", checked }); + await writeAssistProposals(body.project, doc); + const summary = `${doc.ops.length} edit${doc.ops.length === 1 ? "" : "s"} proposed${doc.ops.length ? ` (${doc.diff.join("; ")})` : ""}${doc.refused.length ? `, ${doc.refused.length} refused` : ""} on ${generation.models.local}`; + job.log.push(summary, `@@report-draft ${JSON.stringify({ article: "", iteration: 0, task: "video-assist", project: body.project, status: "done", summary, usd: 0, assist: { at: doc.at, proposed: doc.ops.length, refused: doc.refused.length, diff: doc.diff } })}`); + job.status = "done"; + } catch (err) { + job.log.push(String(err.message)); + job.status = "failed"; + } + }, 1500), + ); + return { jobId: id, iteration: 0 }; +} + function cancelDraft(id) { const job = draftJobs.get(id); if (!job || !["queued", "running"].includes(job.status)) return false; @@ -853,7 +903,7 @@ function cancelDraft(id) { job.status = "cancelled"; job.log.push("cancelled"); job.child?.kill(); - if (job.task === "clips-suggest") return true; + if (job.task === "clips-suggest" || job.task === "video-assist") return true; const it = readIt(job.article, job.n); if (job.task === "narrate" || MEDIA_RUN.has(job.task) || MEDIA_TASKS.has(job.task)) { patchIt(job.article, job.n, { steps: it.steps.map((s) => (s.jobId === id ? { ...s, status: "cancelled" } : s)) }); @@ -923,6 +973,14 @@ function generationRoute(req, res, url, auth) { return json(res, 400, { ok: false, error: String(err.message) }); } } + // Release 38 lane E: the video assistant (a project, not an article). + if (body?.task === "video-assist") { + try { + return json(res, 202, { ok: true, ...startVideoAssist(body) }); + } catch (err) { + return json(res, 400, { ok: false, error: String(err.message) }); + } + } if (!body || !body.task || !body.article) return json(res, 400, { ok: false, error: "task and article are required" }); if (body.feedback === "refuse") return json(res, 400, { ok: false, error: "the stub refuses this feedback" }); try { diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -37,6 +37,7 @@ import { makeYoutubeFixture } from "./youtube-fixture.mjs"; import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs"; import { makeRunTraceFixture } from "./run-trace-fixture.mjs"; import { makeClipsSuggestFixture } from "./clips-suggest-fixture.mjs"; +import { makeVideoAssistFixture } from "./video-assist-fixture.mjs"; const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song"); const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song")); @@ -1819,6 +1820,8 @@ makeBenchShellFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out" makeYoutubeFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // Release 36 lane D: the assistant's labels, Suggest, Ask and Apply in the clip editor (clips-suggest.spec.ts). makeClipsSuggestFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 }); +// Release 38 lane E: the video assistant's Ask box, Apply and Dismiss on the Look panel (video-assist.spec.ts). +makeVideoAssistFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 }); // TWO MORE cached windows for vid1, and they are the regression rather than // decoration. diff --git a/umtool/e2e/fixtures/video-assist-fixture.mjs b/umtool/e2e/fixtures/video-assist-fixture.mjs @@ -0,0 +1,18 @@ +// What video-assist.spec.ts reads and writes (release 38 lane E): the clip +// editor's three clips (clip-editor-fixture.mjs, copied under its own name so +// no two specs edit one project), with a quick blur slide as its look — the +// cut the Ask box proposes edits of. The editor stub's canned "model" +// (editor-stub.mjs startVideoAssist) answers from the request's words. +// Synthetic, like every fixture. +import { readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { makeClipEditorFixture } from "./clip-editor-fixture.mjs"; + +/** @param {{ reports: string, manifest: Function, cachedWindow: string, cues: Array<[number, number, string]> }} o */ +export function makeVideoAssistFixture(o) { + makeClipEditorFixture({ ...o, name: "video-assist-fixture", title: "The Video Assist Fixture" }); + const file = path.join(o.reports, "video-assist-fixture", "video.manifest.json"); + const doc = JSON.parse(readFileSync(file, "utf8")); + doc.render = { ...doc.render, transition: 0.22, transitionStyle: "blurslide", qr: false, headerHeight: 0 }; + writeFileSync(file, JSON.stringify(doc, null, 2) + "\n"); +} diff --git a/umtool/e2e/video-assist.spec.ts b/umtool/e2e/video-assist.spec.ts @@ -0,0 +1,118 @@ +import { test, expect } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// The video assistant (release 38 lane E) on the Build tab's Look panel. An +// Ask ("make the joins 0.15 s with less smear") starts the editor's +// `video-assist` job (the editor stub's canned model answers through common's +// own checker and writer); its proposals come back as a diff list; nothing in +// the manifest moves until Apply, which writes through updateRender; the +// panel's fields read the new look. A second ask ("louder, and 5 seconds +// between clips") shows its refusal with the reason, and Dismiss changes +// nothing but the marks. A note on the whole project, asked, is the request +// too; the agent's reply carries an Apply. Fixture: +// e2e/fixtures/video-assist-fixture.mjs. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const PROJECT = "reports/video-assist-fixture"; +const DIR = path.join(FIXTURE, "reports", "video-assist-fixture"); +const TOKEN = "umtool-e2e-token"; + +const json = (name: string) => { + try { + return JSON.parse(readFileSync(path.join(DIR, name), "utf8")); + } catch { + return null; + } +}; +const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8"); +const render = () => json("video.manifest.json")?.render ?? {}; +const stubRequests = (): { route: string; task?: string; project?: string; request?: string; note?: string }[] => { + try { + return JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8")); + } catch { + return []; + } +}; + +test("Ask on the Look panel: the diff, Apply through the look's writer, a refusal shown, Dismiss writes nothing; a project note asked", async ({ page, request }) => { + test.setTimeout(120_000); + await page.setViewportSize({ width: 1366, height: 900 }); + await page.goto(urls.section(PROJECT, "build")); + await expect(page.locator("[data-look-panel]")).toHaveAttribute("data-look-panel", ""); + const box = page.locator('[data-assist-box="all"]'); + await expect(box).toHaveAttribute("data-assist-route", "local"); + await expect(box.locator("[data-assist-status]")).toContainText("On the local model (qwen3:8b), through the GPU: it waits while a transcription runs."); + // The manual path is right there: the slide's knobs are fields. + await expect(page.locator("[data-look-slide-smear]")).toHaveValue("0.5"); + + // ---- an ask: the proposals, nothing applied --------------------------------- + const before = manifestText(); + await box.locator("[data-assist-input]").fill("make the joins 0.15 s with less smear"); + await box.locator("[data-assist-ask]").click(); + await expect(box.locator("[data-assist-job]")).toHaveAttribute("data-assist-job", "done", { timeout: 20_000 }); + expect(stubRequests().filter((r) => r.route === "report-draft" && r.task === "video-assist").map((r) => [r.project, r.request])).toEqual([[DIR, "make the joins 0.15 s with less smear"]]); + const list = box.locator("[data-assist-proposals]"); + await expect(list).toHaveAttribute("data-assist-proposals", "2"); + await expect(list.locator('[data-assist-op="a1"]')).toContainText("join 0.22 s → 0.15 s"); + await expect(list.locator('[data-assist-op="a2"]')).toContainText("smear 0.5 → 0.3"); + await expect(list.locator("[data-assist-reply]")).toHaveText("Done as asked."); + expect(manifestText()).toBe(before); + + // ---- Apply one, then the rest: through updateRender; the panel reads it back + await list.locator('[data-assist-apply="a1"]').click(); + await expect(list.locator('[data-assist-op="a1"]')).toHaveAttribute("data-assist-status", "applied"); + expect(render().transition).toBe(0.15); + expect(render().slide).toBeUndefined(); + await expect(page.locator("[data-look-transition]")).toHaveValue("0.15"); + await list.locator("[data-assist-apply-all]").click(); + await expect(list.locator('[data-assist-op="a2"]')).toHaveAttribute("data-assist-status", "applied"); + expect(render().slide).toEqual({ blur: 0.3 }); + await expect(page.locator("[data-look-slide-smear]")).toHaveValue("0.3"); + expect(json("assist-proposals.json")?.ops?.map((o: { status: string }) => o.status)).toEqual(["applied", "applied"]); + await expect(list.locator("[data-assist-apply-all]")).toHaveCount(0); + + // ---- a second ask: one proposed, one refused with the reason; Dismiss ---- + await box.locator("[data-assist-input]").fill("louder, and 5 seconds between clips"); + await box.locator("[data-assist-ask]").click(); + await expect(box.locator("[data-assist-job]")).toHaveAttribute("data-assist-job", "done", { timeout: 20_000 }); + await expect(list).toHaveAttribute("data-assist-proposals", "1"); + await expect(list.locator('[data-assist-op="a1"]')).toContainText("loudness as recorded → -14 LUFS"); + await expect(list.locator("[data-assist-refused]")).toHaveText("not proposed: render.transition must be a number of seconds from 0 (a hard cut) to 3"); + const applied = manifestText(); + await list.locator("[data-assist-dismiss]").click(); + await expect(list.locator('[data-assist-op="a1"]')).toHaveAttribute("data-assist-status", "dismissed"); + expect(manifestText()).toBe(applied); + expect(render().loudness).toBeUndefined(); + + // ---- a note on the whole project, asked: its text is the request ---------- + await box.locator("[data-assist-note-input]").fill("no QR, please"); + await box.locator("[data-assist-note-add]").click(); + const thread = box.locator("[data-assist-notes] [data-note-id]"); + await expect(thread).toHaveCount(1); + const noteId = (await thread.getAttribute("data-note-id"))!; + await thread.locator('[data-note-action="assist"]').click(); + await expect(box.locator("[data-assist-job]")).toHaveAttribute("data-assist-job", "done", { timeout: 20_000 }); + expect(stubRequests().filter((r) => r.task === "video-assist" && r.note).map((r) => [r.project, r.note])).toEqual([[DIR, noteId]]); + // The QR is already off in this cut: the checks say so (nothing proposed). + await expect(list).toHaveAttribute("data-assist-proposals", "0"); + await expect(list.locator("[data-assist-refused]")).toHaveText("not proposed: QR code is already that"); + + // The agent's reply with an assist proposal (posted here: the stub cannot reach umtool) shows its Apply only while current. + const at = json("assist-proposals.json").at as string; + const read = await (await request.get(`/api/notes?project=${encodeURIComponent(PROJECT)}`)).json(); + const replied = await request.post(`/api/notes?project=${encodeURIComponent(PROJECT)}`, { + headers: { authorization: `Bearer ${TOKEN}` }, + data: { token: read.token, op: { op: "reply", id: noteId, text: "No edit proposed.", proposal: { kind: "assist", at, ops: 1 } } }, + }); + expect(replied.ok()).toBe(true); + await page.reload(); + const reply = page.locator('[data-assist-notes] [data-reply-proposal="assist"]'); + await expect(reply).toContainText("1 edit"); + await expect(reply).toContainText("nothing waiting"); +}); diff --git a/umtool/lib/annotations/shape.mjs b/umtool/lib/annotations/shape.mjs @@ -117,7 +117,7 @@ export function validateAnchor(raw) { } } -export const REPLY_PROPOSAL_KINDS = ["trim", "merge", "cut"]; +export const REPLY_PROPOSAL_KINDS = ["trim", "merge", "cut", "assist"]; /** * An agent reply's proposal (release 36 lane D, "Ask the assistant"): ONE @@ -126,6 +126,9 @@ export const REPLY_PROPOSAL_KINDS = ["trim", "merge", "cut"]; * { kind: "merge", clip, with, basis? } the clip and the next one, joined * { kind: "cut", clip, basis? } the clip ruled out * `basis` is the clip's cut when the agent read it ({ cutStart, cutEnd }). + * Release 38 lane E, the video assistant on a note on the whole project: + * { kind: "assist", at, ops } the proposals in assist-proposals.json + * made at `at` (their Apply is the Ask box's) * Never applied by whoever writes it. `{ proposal }` or `{ error }`. * @param {unknown} raw */ @@ -133,8 +136,13 @@ export function validateReplyProposal(raw) { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { error: "proposal is not an object" }; const p = /** @type {Record<string, unknown>} */ (raw); if (!REPLY_PROPOSAL_KINDS.includes(/** @type {string} */ (p.kind))) return { error: `proposal kind must be one of ${REPLY_PROPOSAL_KINDS.join(", ")}` }; - if (!short(p.clip, 128) || !ID.test(p.clip)) return { error: "proposal needs the clip's id" }; const fin = (v) => typeof v === "number" && Number.isFinite(v); + if (p.kind === "assist") { + if (!short(p.at, 40) || !p.at || Number.isNaN(Date.parse(/** @type {string} */ (p.at)))) return { error: "an assist proposal names its proposals' time (at)" }; + if (!Number.isInteger(p.ops) || /** @type {number} */ (p.ops) < 1 || /** @type {number} */ (p.ops) > 40) return { error: "an assist proposal counts its ops (1 to 40)" }; + return { proposal: { kind: "assist", at: p.at, ops: p.ops } }; + } + if (!short(p.clip, 128) || !ID.test(p.clip)) return { error: "proposal needs the clip's id" }; const out = { kind: p.kind, clip: p.clip }; if (p.kind === "trim") { if (!fin(p.from) || !fin(p.to) || p.from < 0 || p.to - p.from < 0.5) return { error: "a trim proposal needs from ≥ 0 and to at least half a second after it" }; diff --git a/umtool/lib/annotations/types.ts b/umtool/lib/annotations/types.ts @@ -48,7 +48,9 @@ export type AnchorKind = Anchor["kind"]; export type ReplyProposal = | { kind: "trim"; clip: string; from: number; to: number; basis?: { cutStart: number; cutEnd: number } } | { kind: "merge"; clip: string; with: string; basis?: { cutStart: number; cutEnd: number } } - | { kind: "cut"; clip: string; basis?: { cutStart: number; cutEnd: number } }; + | { kind: "cut"; clip: string; basis?: { cutStart: number; cutEnd: number } } + /** Release 38 lane E: the video assistant's proposals (assist-proposals.json, made at `at`), applied in the Ask box. */ + | { kind: "assist"; at: string; ops: number }; export type NoteReply = { author: NoteAuthor; text: string; at: string; proposal?: ReplyProposal }; diff --git a/umtool/lib/create/policy.mjs b/umtool/lib/create/policy.mjs @@ -29,6 +29,7 @@ const TASK_WORD = { youtube: "YouTube drafts", social: "social post drafts", "clips-suggest": "clip labels", + "video-assist": "the video assistant", }; /** diff --git a/umtool/lib/report/joinPreview.mjs b/umtool/lib/report/joinPreview.mjs @@ -0,0 +1,58 @@ +// THE JOIN PREVIEW, umtool's half (release 38 lane E): `<project>/out/join- +// preview.mp4`, the first few joins of the cut in its current look +// (report-to-video/join-preview.mjs; build-video.mjs `--join-preview`, which +// runs in the machine's heavy slot), as ONE job on the app's runner +// (lib/jobs.ts: one at a time, a log, Cancel) -- the Look panel's and the Ask +// box's Preview join. Its record (`out/join-preview.json`) says what it was +// made from, so the page can say when the look has moved since. +import { readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { lookOf } from "yt-dlp-transcript-common/lib/report/look.mjs"; +import { JOIN_PREVIEW_FILE, JOIN_PREVIEW_RECORD } from "umtool-report-to-video/join-preview"; +import { PIPELINE_DIR } from "./driver.mjs"; + +/** A preview is a few seconds of four clips: minutes at most. */ +export const JOIN_PREVIEW_TIMEOUT_MS = 15 * 60_000; +const CLIP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$/; + +const outOf = (dir) => path.join(/* turbopackIgnore: true */ dir, "out"); +export const joinPreviewFile = (dir) => path.join(/* turbopackIgnore: true */ outOf(dir), JOIN_PREVIEW_FILE); + +/** + * The job's one step: build-video `--join-preview` (from `from`, else the + * first clip), NDJSON progress. No path or argv from a client. + * @param {{ dir: string }} project + * @param {string | null} [from] + */ +export function joinPreviewSteps(project, from = null) { + if (from !== null && !CLIP_ID.test(from)) throw new Error(`not a clip id: ${from}`); + return [ + { + cwd: PIPELINE_DIR, + env: {}, + label: `preview the joins${from ? ` from ${from}` : ""}`, + argv: [ + "node", path.join(/* turbopackIgnore: true */ PIPELINE_DIR, "build-video.mjs"), + path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"), + "--out", outOf(project.dir), + "--join-preview", ...(from ? ["--join-from", from] : []), "--progress", "ndjson", + ], + ndjson: true, + timeoutMs: JOIN_PREVIEW_TIMEOUT_MS, + }, + ]; +} + +/** + * The preview on disk, or null: `{ size, mtimeMs, record, stale }` -- + * `stale` when the look (lookOf the render) is not what it was made with. + * @param {string} dir + * @param {any} [manifest] + */ +export async function readJoinPreview(dir, manifest = null) { + const st = await stat(joinPreviewFile(dir)).catch(() => null); + if (!st?.isFile()) return null; + const record = await readFile(path.join(/* turbopackIgnore: true */ outOf(dir), JOIN_PREVIEW_RECORD), "utf8").then(JSON.parse, () => null); + const stale = !!manifest && !!record && JSON.stringify(record.look ?? {}) !== JSON.stringify(lookOf(manifest.render ?? {})); + return { size: st.size, mtimeMs: Math.round(st.mtimeMs), record, stale }; +} diff --git a/umtool/lib/report/videoAssist.mjs b/umtool/lib/report/videoAssist.mjs @@ -0,0 +1,238 @@ +// THE VIDEO ASSISTANT, umtool's half (release 38 lane E): the Ask box's +// request to the editor, the job the page follows, the proposals file read +// for the page, and APPLY -- the one place a proposed op becomes a write. +// +// assist-proposals.json written by the EDITOR's `report-draft` task +// `video-assist` (common lib/report/videoAssistProposals.mjs); +// its ops' status marked here (applied / dismissed / failed) +// .video-assist-job.json the editor job the page follows, so a reload shows it; +// umtool's own file, cleared when the job is seen to end +// +// Apply re-checks each op against the manifest AS IT IS (common +// videoAssistOps.mjs checkAssistOps -- the look's rules, the clip's window, +// the declared params), then writes through the manifest's own writers: +// updateRender (the look, the slide, the room), the clip editor's +// runClipEditorOp (trim, room), updateChrome (a composition's param) -- each +// token-guarded, the token carried from one write to the next. A stale token +// stops it (409: reload); a refusal fails that op only, with its reason. +// Never a raw manifest write, never free HTML. Dismiss marks ops and writes +// nothing else. +// +// Everything is optional: with no editor, no model, or generation routed to +// Claude Code, the Look panel and the clip editor are the same as before. +import { readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { checkAssistOps } from "yt-dlp-transcript-common/lib/report/videoAssistOps.mjs"; +import { chromeWithParam } from "yt-dlp-transcript-common/lib/report/fxParams.mjs"; +import { markProposals, readAssistProposals, writeAssistProposals } from "yt-dlp-transcript-common/lib/report/videoAssistProposals.mjs"; +import { readManifest } from "../projects/report.mjs"; +import { StaleToken, manifestToken, updateChrome, updateRender } from "./manifest.mjs"; +import { runClipEditorOp } from "./clipEditor.mjs"; + +export const ASSIST_TASK = "video-assist"; +export const ASSIST_JOB_FILE = ".video-assist-job.json"; +export const ASSIST_SCOPES = Object.freeze(["look", "clips", "fx", "all"]); +export const ASSIST_REQUEST_MAX = 2000; +const JOB_RE = /^[A-Za-z0-9_-]+$/; +const NOTE_RE = /^n_[a-z0-9]{4,32}$/; +const OP_ID_RE = /^a\d{1,3}$/; +const RESULT_MARKER = "@@report-draft "; +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +export class AssistRequestError extends Error { + constructor(message, status = 400) { + super(message); + this.status = status; + } +} + +/** + * A POST's ask, judged: `{ request, scope? }` (the Ask box) or `{ note, scope? }` + * (Ask the assistant on a note on the whole project). + * @param {unknown} body + */ +export function parseAssistRequest(body) { + if (!isObj(body)) throw new AssistRequestError("a body is { project, request | note, scope? }"); + const scope = body.scope === undefined || body.scope === null ? "all" : String(body.scope); + if (!ASSIST_SCOPES.includes(scope)) throw new AssistRequestError(`scope is ${ASSIST_SCOPES.join(", ")}`); + if (body.note !== undefined && body.note !== null) { + if (typeof body.note !== "string" || !NOTE_RE.test(body.note)) throw new AssistRequestError("a note's Ask names the note (n_…)"); + if (body.request !== undefined && body.request !== null) throw new AssistRequestError("give a request or a note, not both"); + return { note: body.note, scope }; + } + const request = typeof body.request === "string" ? body.request.replace(/\s+/g, " ").trim() : ""; + if (!request) throw new AssistRequestError("say what to change"); + if (request.length > ASSIST_REQUEST_MAX) throw new AssistRequestError(`a request is at most ${ASSIST_REQUEST_MAX} characters`); + return { request, scope }; +} + +/** The editor's `report-draft` body for an ask on a project directory. */ +export function draftBodyOf(dir, req) { + return { task: ASSIST_TASK, project: dir, ...(req.note ? { note: req.note } : { request: req.request }), ...(req.scope && req.scope !== "all" ? { scope: req.scope } : {}) }; +} + +const jobFileOf = (dir) => path.join(/* turbopackIgnore: true */ dir, ASSIST_JOB_FILE); + +/** The job the page follows, or null: `{ jobId, request?, note?, scope, at }`. */ +export async function readAssistJob(dir) { + try { + const j = JSON.parse(await readFile(jobFileOf(dir), "utf8")); + return isObj(j) && typeof j.jobId === "string" && JOB_RE.test(j.jobId) ? j : null; + } catch { + return null; + } +} + +/** Remember the job an Ask started (tmp + rename). */ +export async function writeAssistJob(dir, rec) { + const file = jobFileOf(dir); + const tmp = `${file}.${process.pid}.tmp`; + await writeFile(tmp, `${JSON.stringify(rec)}\n`); + await rename(tmp, file); +} + +/** Forget it — only when it is still that job. */ +export async function clearAssistJob(dir, jobId) { + const cur = await readAssistJob(dir); + if (cur && cur.jobId === jobId) await rm(jobFileOf(dir), { force: true }); +} + +export const ENDED = Object.freeze(["done", "failed", "cancelled", "interrupted"]); + +/** The job's `@@report-draft` result in its log tail, or null. */ +export function assistMarkerOf(tail) { + for (let i = (tail?.length ?? 0) - 1; i >= 0; i--) { + const at = String(tail[i]).indexOf(RESULT_MARKER); + if (at < 0) continue; + try { + return JSON.parse(String(tail[i]).slice(at + RESULT_MARKER.length)); + } catch { + return null; + } + } + return null; +} + +/** What the page shows of a job: its state, where it waits, its last line, and its result once it ended. */ +export function assistJobView(rec, job) { + const marker = assistMarkerOf(job.tail); + const last = [...(job.tail ?? [])].reverse().find((l) => !String(l).includes(RESULT_MARKER)) ?? null; + return { + id: job.id, + ...(rec?.note ? { note: rec.note } : {}), + ...(rec?.request ? { request: rec.request } : {}), + status: job.status, + ended: ENDED.includes(job.status), + queue: job.queue ?? null, + last: last === null ? null : String(last).slice(0, 300), + summary: typeof marker?.summary === "string" ? marker.summary : null, + }; +} + +/** + * How the task is routed, for the box: `{ route, model, why }` from the + * policy's generation block, or null without one. `why` is set when the box + * cannot start a job here (routed to Claude Code, or no route). + */ +export function assistRouteOf(generation, dir) { + if (!isObj(generation) || !isObj(generation.routes)) return null; + const route = generation.routes[ASSIST_TASK] ?? null; + if (route === "code") return { route, model: null, why: `routed to Claude Code — in a session: /gen on ${dir}: <what to change>` }; + const model = route === "api" ? generation.models?.api : route === "local" ? generation.models?.local : null; + return { route, model: typeof model === "string" ? model : null, why: route ? null : "the editor's policy routes no video-assist" }; +} + +/** + * The proposals for the page: each op with whether it would still apply to + * the manifest as it is (`now: null` when it would, else the reason). + * @param {string} dir + */ +export async function proposalsView(dir) { + const [{ doc, error }, manifest] = await Promise.all([readAssistProposals(dir), readManifest(dir)]); + if (!doc) return { proposals: null, error }; + const ops = doc.ops.map((o) => { + if (o.status !== "proposed" && o.status !== "failed") return { ...o, now: null }; + const r = checkAssistOps(manifest ?? {}, [o.op], { request: doc.request, scope: doc.scope }); + return { ...o, now: r.refused[0]?.why ?? null, diffNow: r.ops[0]?.diff ?? null }; + }); + return { proposals: { ...doc, ops }, error: null }; +} + +/** + * Apply proposed ops (`ids`, or every one still proposed) in the file's + * order, each re-checked against the manifest as the ones before it left it. + * `token` is the manifest's as the page read it (null: unguarded — the CLI). + * `at`, when given, is the proposals the caller saw: a newer ask's file is a + * 409, not a silent apply of other ops. + * + * @param {{ id: string, dir: string, kind: string }} project + * @param {{ ids?: string[] | null, token?: string | null, at?: string | null, now?: string | null }} [o] + * @returns {Promise<{ applied: string[], failed: { id: string, error: string }[], token: string | null, proposals: unknown }>} + */ +export async function applyAssistOps(project, { ids = null, token = null, at = null, now = null } = {}) { + const dir = project.dir; + const { doc, error } = await readAssistProposals(dir); + if (!doc) throw new AssistRequestError(error ?? "no proposals to apply", 404); + if (at && doc.at !== at) throw new AssistRequestError("these proposals were replaced by a newer ask — read them again", 409); + if (ids && !ids.every((id) => typeof id === "string" && OP_ID_RE.test(id))) throw new AssistRequestError("ids is a list of op ids (a1, a2, …)"); + const wanted = doc.ops.filter((o) => (ids ? ids.includes(o.id) : o.status === "proposed") && (o.status === "proposed" || o.status === "failed")); + if (!wanted.length) throw new AssistRequestError(ids ? "those ops are not waiting (applied or dismissed already)" : "nothing is waiting to apply"); + let cur = await manifestToken(dir); + if (token !== null && cur !== token) throw new StaleToken(token, cur); + const stamp = now ?? new Date().toISOString(); + /** @type {Record<string, { status: "applied" | "failed", error?: string }>} */ + const marks = {}; + const applied = []; + const failed = []; + for (const o of wanted) { + const manifest = await readManifest(dir); + const r = checkAssistOps(manifest ?? {}, [o.op], { request: doc.request, scope: doc.scope }); + if (r.refused.length) { + marks[o.id] = { status: "failed", error: r.refused[0].why }; + failed.push({ id: o.id, error: r.refused[0].why }); + continue; + } + const a = r.ops[0].apply; + try { + if (a.writer === "render") cur = (await updateRender(dir, a.patch, { token: cur })).token; + else if (a.writer === "chrome") { + const chrome = chromeWithParam(manifest.render, a.id, a.param, a.value); + cur = (await updateChrome(dir, chrome, { token: cur })).token; + } else { + const res = await runClipEditorOp(project, { ...a.body, token: cur }); + cur = res?.view?.token ?? (await manifestToken(dir)); + } + marks[o.id] = { status: "applied" }; + applied.push(o.id); + } catch (e) { + // Another writer got in between: stop, say so; what was applied stays applied. + if (e instanceof StaleToken) { + await writeAssistProposals(dir, markProposals(doc, marks, stamp)); + throw e; + } + const msg = e instanceof Error ? (Array.isArray(e.errors) ? e.errors.join("; ") : e.message) : String(e); + marks[o.id] = { status: "failed", error: msg }; + failed.push({ id: o.id, error: msg }); + } + } + const next = markProposals(doc, marks, stamp); + await writeAssistProposals(dir, next); + return { applied, failed, token: cur, proposals: next }; +} + +/** + * Dismiss ops (`ids`, or every one still waiting): marked, nothing else written. + * @param {string} dir + * @param {{ ids?: string[] | null, at?: string | null, now?: string | null }} [o] + */ +export async function dismissAssistOps(dir, { ids = null, at = null, now = null } = {}) { + const { doc, error } = await readAssistProposals(dir); + if (!doc) throw new AssistRequestError(error ?? "no proposals to dismiss", 404); + if (at && doc.at !== at) throw new AssistRequestError("these proposals were replaced by a newer ask — read them again", 409); + const marks = Object.fromEntries( + doc.ops.filter((o) => (ids ? ids.includes(o.id) : true) && (o.status === "proposed" || o.status === "failed")).map((o) => [o.id, { status: "dismissed" }]), + ); + const next = markProposals(doc, marks, now ?? new Date().toISOString()); + await writeAssistProposals(dir, next); + return { dismissed: Object.keys(marks), proposals: next }; +} diff --git a/umtool/lib/report/videoAssist.test.mjs b/umtool/lib/report/videoAssist.test.mjs @@ -0,0 +1,139 @@ +// The video assistant in umtool (release 38 lane E): the Ask's request, the +// job the page follows, and APPLY — each proposed op re-checked and written +// through the manifest's own writers (updateRender, the clip editor's trim and +// room, updateChrome), token-guarded; Dismiss writes nothing but the marks. +// Synthetic (common/testing/clips/assistProject.mjs). +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { assistDeckManifest, assistManifest } from "yt-dlp-transcript-common/testing/clips/assistProject.mjs"; +import { writeReactionProject } from "yt-dlp-transcript-common/testing/clips/reactionProject.mjs"; +import { checkAssistOps } from "yt-dlp-transcript-common/lib/report/videoAssistOps.mjs"; +import { proposalsDocOf, readAssistProposals, writeAssistProposals } from "yt-dlp-transcript-common/lib/report/videoAssistProposals.mjs"; +import { MANIFEST_NAME, StaleToken, manifestToken, updateRender } from "./manifest.mjs"; +import { + AssistRequestError, + applyAssistOps, + assistJobView, + assistRouteOf, + dismissAssistOps, + draftBodyOf, + parseAssistRequest, + proposalsView, +} from "./videoAssist.mjs"; + +const AT = "2026-10-20T00:00:00.000Z"; + +async function project({ deck = false, ops }) { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-assist-")); + writeReactionProject(dir); + const manifest = deck ? assistDeckManifest() : assistManifest(); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + "\n"); + const checked = checkAssistOps(manifest, ops, { request: "the request" }); + await writeAssistProposals(dir, proposalsDocOf({ at: AT, model: "qwen3:8b", request: "the request", checked })); + return { id: "reports/assist", dir, kind: "report" }; +} +const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")); + +test("an Ask's request: words or a note, a scope; the editor's body", () => { + assert.deepEqual(parseAssistRequest({ request: " quicker joins " }), { request: "quicker joins", scope: "all" }); + assert.deepEqual(parseAssistRequest({ note: "n_abcd1234", scope: "look" }), { note: "n_abcd1234", scope: "look" }); + assert.throws(() => parseAssistRequest({ request: " " }), AssistRequestError); + assert.throws(() => parseAssistRequest({ request: "x", scope: "everything" }), /scope is look, clips, fx, all/); + assert.throws(() => parseAssistRequest({ note: "n_abcd1234", request: "x" }), /not both/); + assert.deepEqual(draftBodyOf("/r/p", { request: "quicker joins", scope: "all" }), { task: "video-assist", project: "/r/p", request: "quicker joins" }); + assert.deepEqual(draftBodyOf("/r/p", { note: "n_abcd1234", scope: "look" }), { task: "video-assist", project: "/r/p", note: "n_abcd1234", scope: "look" }); + assert.deepEqual(assistRouteOf({ routes: { "video-assist": "local" }, models: { local: "qwen3:8b" } }, "/r/p"), { route: "local", model: "qwen3:8b", why: null }); + assert.match(assistRouteOf({ routes: { "video-assist": "code" }, models: {} }, "/r/p").why, /routed to Claude Code — in a session: \/gen on \/r\/p/); + const v = assistJobView({ jobId: "j1", request: "quicker" }, { id: "j1", status: "done", tail: ["one ask", '@@report-draft {"task":"video-assist","status":"done","summary":"1 edit proposed"}'] }); + assert.deepEqual([v.ended, v.summary, v.last, v.request], [true, "1 edit proposed", "one ask", "quicker"]); +}); + +test("Apply all: each op re-checked and written by its own writer, in order, the token carried; the ops marked applied", async () => { + const p = await project({ + ops: [ + { op: "look", id: "", key: "transition", value: 0.15 }, + { op: "slide", id: "", key: "blur", value: 0.3 }, + { op: "clip_edges", id: "r002", key: "start", value: 90 }, + { op: "clip_room", id: "r003", key: "off", value: true }, + ], + }); + try { + const token = await manifestToken(p.dir); + const r = await applyAssistOps(p, { token, now: AT }); + assert.deepEqual(r.applied, ["a1", "a2", "a3", "a4"]); + assert.deepEqual(r.failed, []); + assert.equal(r.token, await manifestToken(p.dir)); + const m = await read(p.dir); + assert.equal(m.render.transition, 0.15); + assert.deepEqual(m.render.slide, { blur: 0.3 }); + const r002 = m.timeline.find((e) => e.id === "r002"); + assert.deepEqual([r002.cutStart, r002.cutEnd], [90, 99]); + assert.equal(r002.assist.by, "operator", "the clip editor's writer: an edit of an assistant's clip is the operator's"); + assert.equal(m.timeline.find((e) => e.id === "r003").room, false); + const { doc } = await readAssistProposals(p.dir); + assert.deepEqual(doc.ops.map((o) => [o.id, o.status, o.at]), [["a1", "applied", AT], ["a2", "applied", AT], ["a3", "applied", AT], ["a4", "applied", AT]]); + await assert.rejects(applyAssistOps(p, {}), /nothing is waiting to apply/); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("Apply one; a stale token is a 409 before anything is written; newer proposals are refused by `at`", async () => { + const p = await project({ ops: [{ op: "look", id: "", key: "qr", value: false }, { op: "look", id: "", key: "loudness", value: -14 }] }); + try { + const before = await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"); + await assert.rejects(applyAssistOps(p, { token: "123" }), StaleToken); + assert.equal(await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"), before); + await assert.rejects(applyAssistOps(p, { at: "2026-01-01T00:00:00.000Z" }), (e) => e instanceof AssistRequestError && e.status === 409); + const r = await applyAssistOps(p, { ids: ["a2"], token: await manifestToken(p.dir) }); + assert.deepEqual(r.applied, ["a2"]); + const m = await read(p.dir); + assert.deepEqual([m.render.qr, m.render.loudness], [undefined, { target: -14 }]); + assert.deepEqual((await readAssistProposals(p.dir)).doc.ops.map((o) => o.status), ["proposed", "applied"]); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("an op the manifest no longer allows fails at Apply with the reason; the view says so before", async () => { + const p = await project({ ops: [{ op: "clip_edges", id: "r001", key: "end", value: 48 }, { op: "look", id: "", key: "transition", value: 0.15 }] }); + try { + // Somebody narrowed r001's window meanwhile, and set the join themselves. + const m = await read(p.dir); + m.timeline[0].end = 47.5; + await writeFile(path.join(p.dir, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n"); + await updateRender(p.dir, { transition: 0.15 }); + const v = await proposalsView(p.dir); + assert.match(v.proposals.ops[0].now, /outside the clip's source window \(38\.5–47\.5 s\)/); + assert.match(v.proposals.ops[1].now, /join is already that/); + const r = await applyAssistOps(p, {}); + assert.deepEqual(r.applied, []); + assert.deepEqual(r.failed.map((f) => f.id), ["a1", "a2"]); + assert.deepEqual((await readAssistProposals(p.dir)).doc.ops.map((o) => o.status), ["failed", "failed"]); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("a composition's param through updateChrome; Dismiss changes nothing but the marks", async () => { + const p = await project({ deck: true, ops: [{ op: "fx", id: "deck", key: "motion.in", value: 0.6 }, { op: "fx", id: "fx.glitch", key: "seconds", value: 0.8 }] }); + try { + const r = await applyAssistOps(p, { ids: ["a1"] }); + assert.deepEqual(r.applied, ["a1"]); + const m = await read(p.dir); + assert.deepEqual(m.render.chrome.deck, { qr: { show: false }, motion: { in: 0.6 } }); + const before = await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"); + const d = await dismissAssistOps(p.dir, { at: AT }); + assert.deepEqual(d.dismissed, ["a2"]); + assert.equal(await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"), before, "Dismiss writes no manifest"); + assert.deepEqual((await readAssistProposals(p.dir)).doc.ops.map((o) => o.status), ["applied", "dismissed"]); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -165,6 +165,8 @@ import { applyMontageRulings, readMontageRulings, rulingsLines } from "./montage import { validateDrafted, validatePublish } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs"; import { blurSlideEdges, validateTransitionStyle, xfadeTransitionOf } from "./transition.mjs"; +import { JOIN_PREVIEW_FILE, JOIN_PREVIEW_RECORD, joinPreviewTimeline } from "./join-preview.mjs"; +import { lookOf } from "yt-dlp-transcript-common/lib/report/look.mjs"; // The look of a highlights cut (release 36 lane C): render.captions, // render.loudness, a clip's vertical crop and the short made from it -- pure, // in look.mjs. Every hook below runs only when its key is set. @@ -5144,6 +5146,13 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly if (e.type !== "clip") throw new Error(`${opts.short} is a ${e.type ?? "non-clip"} entry: a short is made from a clip`); manifest.render = shortRender(manifest.render ?? {}); } + // A join preview (release 38, join-preview.mjs): the first few joins of + // the cut, each clip shortened to a few seconds at the join, in the cut's look. + if (opts.joinPreview) { + if (only || fetchOnly) throw new Error("--join-preview builds the joins: not with --only, --short or --fetch-only"); + manifest.timeline = joinPreviewTimeline(manifest, { from: opts.joinPreview.from ?? null }); + EMIT("note", { message: `join preview: ${manifest.timeline.map((e) => e.id).join(", ")}` }); + } for (const message of rulingsLines(ruled)) EMIT("note", { message }); const { render, provenance } = manifest; // A `src` clip's file and cues, checked and measured before anything else. @@ -5220,6 +5229,11 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly const dirs = variantPaths(outRoot, manifest.slug, variant); // A short's work is its own: the cut's segments are never overwritten by one. if (opts.short) dirs.dir = path.join(outRoot, "shorts-work"); + // A join preview's too: its own work dir and file, the cut's out/ untouched. + if (opts.joinPreview) { + dirs.dir = path.join(outRoot, "join-preview-work"); + dirs.final = path.join(outRoot, JOIN_PREVIEW_FILE); + } const outDir = dirs.dir; // Where media may already be on disk. The channels tree is the one the clip // bench reads for this project (sources.mjs channelsDirFor): the manifest's @@ -5829,6 +5843,16 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // shortest=1), and a hang means an unbounded -loop 1. if (railPlan) await assertConcatLength(final, railPlan.total, render.fps, "rail build"); + // A join preview ends here: no chapters, no YouTube text, no thumbnail -- + // those are the cut's. A record beside it says what it was made from. + if (opts.joinPreview) { + await pruneFrames(); + const record = { version: 1, madeAt: new Date().toISOString(), clips: manifest.timeline.map((e) => e.id), look: lookOf(render) }; + await replaceFile(path.join(outRoot, JOIN_PREVIEW_RECORD), JSON.stringify(record, null, 2) + "\n"); + EMIT("done", { out: final, failures: [], joinPreview: true }); + return { out: final, failures }; + } + const muxed = opts.noChapters ? null : await muxChapters(final, entries, segments, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); @@ -5975,6 +5999,7 @@ async function main() { console.error( "usage: build-video.mjs <manifest.json> [--out <dir>] [--variant sourced|full]\n" + " [--only <id>] [--fetch-only <id>] [--short <id>] (a vertical short of one clip: <project>/shorts/<id>.mp4)\n" + + " [--join-preview [--join-from <id>]] (the first few joins, a few seconds each side: out/join-preview.mp4)\n" + " [--pad <s>] [--pad-before <s>] [--pad-after <s>] [--skip-fetch] [--no-network] [--audio-fallback] [--no-xfade] [--no-chapters] [--chapters-only]\n" + " [--progress ndjson] [--continue-on-error] [--no-reuse]\n" + " [--no-rail] [--rail-only] [--preview <start> <dur>]\n" + @@ -6023,6 +6048,7 @@ async function main() { final: argv.includes("--final"), draftsUnreviewed: argv.includes("--drafts-unreviewed"), short: flag("--short") ?? null, + joinPreview: argv.includes("--join-preview") ? { from: flag("--join-from") ?? null } : null, }; try { Object.assign(opts, chromeFlags(argv)); diff --git a/umtool/report-to-video/join-preview.mjs b/umtool/report-to-video/join-preview.mjs @@ -0,0 +1,51 @@ +// A JOIN PREVIEW (release 38 lane E): a few seconds either side of the first +// few joins of a cut, in the cut's own look -- the quick render the video +// assistant's Ask box and the Look panel play to judge a join's length, +// style, slide and room before a full build. `build-video.mjs <manifest> +// --join-preview [--join-from <clip id>]` writes out/join-preview.mp4 (and +// out/join-preview.json, what it was made from) through the heavy slot, as a +// full build does; nothing of the cut's own out/ files is touched. +// +// The cut: JOIN_PREVIEW_CLIPS consecutive clips (from `from`, else the first), +// every other entry left out; each clip keeps the last JOIN_PREVIEW_SECONDS +// of its cut (so its tail -- where room and the join act -- is its own), the +// last one the first JOIN_PREVIEW_SECONDS. The windows are untouched, so the +// media already fetched for the cut is what the preview cuts from. +// +// PURE: the manifest in, a timeline out. + +export const JOIN_PREVIEW_CLIPS = 4; +export const JOIN_PREVIEW_SECONDS = 3; +export const JOIN_PREVIEW_FILE = "join-preview.mp4"; +export const JOIN_PREVIEW_RECORD = "join-preview.json"; + +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const r2 = (n) => Math.round(n * 100) / 100; + +/** + * The preview's timeline, or a thrown reason it cannot be made. + * + * @param {{ render?: Record<string, unknown>, timeline?: Record<string, unknown>[] }} manifest + * @param {{ from?: string | null, clips?: number, seconds?: number }} [o] + */ +export function joinPreviewTimeline(manifest, { from = null, clips = JOIN_PREVIEW_CLIPS, seconds = JOIN_PREVIEW_SECONDS } = {}) { + const render = manifest?.render ?? {}; + if (render.chrome !== undefined && render.chrome !== null) throw new Error("a join preview is a plain cut's: this one is drawn under the deck (a full build or --chrome-preview shows its joins)"); + if (render.montage !== undefined && render.montage !== null) throw new Error("a join preview is a plain cut's: a montage cuts to its phrases"); + if (!(fin(render.transition) ? render.transition > 0 : true)) throw new Error("this cut has hard cuts (render.transition 0): there is no join to preview"); + const all = (manifest?.timeline ?? []).filter((e) => e?.type === "clip"); + const at = from ? all.findIndex((e) => e.id === from) : 0; + if (at < 0) throw new Error(`no clip ${from} in the cut`); + const picked = all.slice(at, at + clips); + if (picked.length < 2) throw new Error("a join preview needs two clips after it starts"); + return picked.map((e, i) => { + const a = fin(e.cutStart) && fin(e.cutEnd) ? e.cutStart : e.start; + const b = fin(e.cutStart) && fin(e.cutEnd) ? e.cutEnd : e.end; + if (!fin(a) || !fin(b) || b - a <= seconds) return { ...e }; + const last = i === picked.length - 1; + const cut = last ? { cutStart: r2(a), cutEnd: r2(a + seconds) } : { cutStart: r2(b - seconds), cutEnd: r2(b) }; + // A mute mark stays: before the shortened cut it mutes all of it, as it + // mutes that stretch of the full cut; past it, nothing, as in the cut. + return { ...e, ...cut }; + }); +} diff --git a/umtool/report-to-video/join-preview.test.mjs b/umtool/report-to-video/join-preview.test.mjs @@ -0,0 +1,35 @@ +// The join preview's cut (release 38 lane E, join-preview.mjs). +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; +import { JOIN_PREVIEW_SECONDS, joinPreviewTimeline } from "./join-preview.mjs"; + +const clip = (id, a, b, extra = {}) => ({ type: "clip", id, channel: "ch", video: "v1", start: a - 1.5, end: b + 1.5, cutStart: a, cutEnd: b, ...extra }); +const M = (timeline, render = {}) => ({ render: { transition: 0.22, transitionStyle: "blurslide", ...render }, timeline }); + +test("four clips from the first: each keeps the last seconds of its cut, the last its first seconds; cards left out", () => { + const tl = [{ type: "card", id: "t0" }, clip("a", 10, 20), clip("b", 30, 32), clip("c", 40, 50, { muteFrom: 41 }), clip("d", 60, 70), clip("e", 80, 90)]; + const out = joinPreviewTimeline(M(tl)); + assert.deepEqual(out.map((e) => [e.id, e.cutStart, e.cutEnd, e.start, e.end]), [ + ["a", 20 - JOIN_PREVIEW_SECONDS, 20, 8.5, 21.5], + ["b", 30, 32, 28.5, 33.5], + ["c", 47, 50, 38.5, 51.5], + ["d", 60, 63, 58.5, 71.5], + ]); + assert.equal(out[2].muteFrom, 41, "a mute mark before the shortened cut stays (it mutes all of it, as in the cut)"); + // From a named clip. + assert.deepEqual(joinPreviewTimeline(M(tl), { from: "c" }).map((e) => e.id), ["c", "d", "e"]); + // A clip with no cut fields is shortened the same way, inside its edges. + const plain = joinPreviewTimeline(M([{ type: "clip", id: "x", start: 0, end: 10 }, { type: "clip", id: "y", start: 20, end: 30 }])); + assert.deepEqual(plain.map((e) => [e.cutStart, e.cutEnd]), [[7, 10], [20, 23]]); +}); + +test("refused: a deck, a montage, hard cuts, fewer than two clips, an unknown clip", () => { + const tl = [clip("a", 10, 20), clip("b", 30, 40)]; + assert.throws(() => joinPreviewTimeline(M(tl, { chrome: { engine: "hyperframes", layout: "deck" } })), /plain cut's: this one is drawn under the deck/); + assert.throws(() => joinPreviewTimeline(M(tl, { montage: {} })), /a montage cuts to its phrases/); + assert.throws(() => joinPreviewTimeline(M(tl, { transition: 0 })), /no join to preview/); + assert.throws(() => joinPreviewTimeline(M(tl), { from: "b" }), /needs two clips/); + assert.throws(() => joinPreviewTimeline(M(tl), { from: "zz" }), /no clip zz/); +}); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -34,6 +34,7 @@ "./montage-rulings": "./montage-rulings.mjs", "./lint": "./lint.mjs", "./local-media": "./local-media.mjs", + "./join-preview": "./join-preview.mjs", "./look": "./look.mjs", "./mute": "./mute.mjs", "./narration": "./narration.mjs",