Archilyzer · Source

archilyzer

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

commit 23121878c4c7cb5fd9d5225b5bf46b6ee57db595
parent 532273d46a2b9ca3323a0bdb5947de85129f2a82
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 17:06:20 -0400

umtool: Fill empty fields by hand on the Media tab — every empty media field (clips' on-screen titles, teasers' lines, YouTube, X, Bluesky) a blank, and the flips or threads whole (no other editor had them); saved through the manifest writer as the operator's edit, no drafted mark, so a cut reaches a buildable manifest with no model (lib/report/hand-fill.mjs, /api/report/hand-fill)

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

Diffstat:
Aumtool/app/api/report/hand-fill/route.ts | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/HandFill.tsx | 370+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/report/MediaTab.tsx | 8+++++++-
Mumtool/e2e/by-hand.spec.ts | 32++++++++++++++++++++++++++++++--
Aumtool/lib/report/hand-fill.mjs | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/hand-fill.test.mjs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 655 insertions(+), 3 deletions(-)

diff --git a/umtool/app/api/report/hand-fill/route.ts b/umtool/app/api/report/hand-fill/route.ts @@ -0,0 +1,50 @@ +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { invalidateProjects } from "@/lib/projects"; +import { withEditNotes } from "@/lib/report/guard"; +import { MANIFEST_NAME, StaleToken, manifestToken } from "@/lib/report/manifest.mjs"; +import { applyHandFill, handFillView } from "@/lib/report/hand-fill.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; + +export const dynamic = "force-dynamic"; + +// FILL BY HAND (release 32 R2; lib/report/hand-fill.mjs): the Media tab's blanks +// for every empty media field, written as the operator's -- no model, no mark. +// +// GET ?project=<id> the view: the empty fields, the clips, +// the deck, the flips and threads as they +// stand, and the write token +// POST {project, token?, fills: [{field, entry?, value}]} +// each fill through the manifest writer; +// -> {written, refused, token} + +const noStore = { "cache-control": "no-store" }; + +async function rawManifest(dir: string): Promise<unknown> { + return JSON.parse(await readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, MANIFEST_NAME), "utf8")); +} + +export async function GET(request: Request) { + const r = await resolveReport(new URL(request.url).searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status, headers: noStore }); + return Response.json({ ...handFillView(await rawManifest(r.project.dir)), token: await manifestToken(r.project.dir) }, { headers: noStore }); +} + +export async function POST(request: Request) { + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body) return Response.json({ error: "expected JSON" }, { status: 400, headers: noStore }); + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status, headers: noStore }); + try { + const token = typeof body.token === "string" ? body.token : null; + const { result, editNotes } = await withEditNotes(r.project, () => applyHandFill(r.project.dir, body.fills as unknown[], { token })); + if (result.written.length) invalidateProjects(); + return Response.json( + { ok: !result.refused, ...result, editNotes, ...handFillView(await rawManifest(r.project.dir)), token: await manifestToken(r.project.dir) }, + { status: result.refused && !result.written.length ? 400 : 200, headers: noStore }, + ); + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409, headers: noStore }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400, headers: noStore }); + } +} diff --git a/umtool/components/projects/HandFill.tsx b/umtool/components/projects/HandFill.tsx @@ -0,0 +1,370 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Field, Input, Select, Textarea } from "@/components/ui/field"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import { announceManifestChanged } from "./timelineApi"; + +// --------------------------------------------------------------------------- +// FILL BY HAND (release 32 R2): beside Draft everything, the cut's EMPTY media +// fields as blanks a person fills -- each clip's on-screen title, a teaser's +// lines, the YouTube title and description, the X and Bluesky posts -- and the +// flips or the threads (no other editor has them), so a cut reaches a buildable +// manifest with no model. Saved through the manifest writer as the operator's +// edit (lib/report/hand-fill.mjs): no drafted mark, "written by hand", never +// replaced by a draft. Only what is filled is written; a blank stays empty. +// +// Labels are contracts: the toggle "Fill empty fields by hand", the region +// "fill by hand", "Save what is filled"; each field's box is named for it +// ("on-screen title of <clip>", "teaser lines of <id>", "YouTube title", …). +// --------------------------------------------------------------------------- + +type EmptyField = { address: string; entry: string | null; field: string; label: string; context: string }; +type Clip = { id: string; label: string; thread: string | null }; +type Side = { entry: string; when: string; words: string }; +type Pair = { id: string; topic: string; then: Side; now: Side }; +type Thread = { id: string; label: string; outcome?: { verdict: string; label?: string } }; +export type HandFillView = { + empty: EmptyField[]; + clips: Clip[]; + deck: boolean; + flips: { pairs: Pair[] } | null; + threads: { list: Thread[]; clips: Record<string, string> } | null; + token: string | null; +}; + +const VERDICTS = ["CORROBORATED", "PARTLY", "CONTRADICTED", "NOT_FOUND", "UNTESTABLE"]; +const slug = (s: string, at: number, prefix: string) => { + const v = s + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 40); + return v || `${prefix}${at + 1}`; +}; +const blankSide = (entry = ""): Side => ({ entry, when: "", words: "" }); + +function FlipsEditor({ clips, pairs, setPairs }: { clips: Clip[]; pairs: Pair[]; setPairs: (p: Pair[]) => void }) { + const set = (i: number, p: Pair) => setPairs(pairs.map((x, j) => (j === i ? p : x))); + const side = (i: number, which: "then" | "now", key: keyof Side, v: string) => set(i, { ...pairs[i]!, [which]: { ...pairs[i]![which], [key]: v } }); + return ( + <div className="grid gap-2" data-hand-flips={pairs.length}> + {pairs.map((p, i) => ( + <div key={i} className="grid gap-1.5 rounded-[3px] border border-seam-2 p-2"> + <div className="flex flex-wrap items-end gap-2"> + <Field label="Topic"> + <Input aria-label={`flip ${i + 1} topic`} value={p.topic} maxLength={32} onChange={(e) => set(i, { ...p, topic: e.target.value })} className="w-48" /> + </Field> + <Button type="button" size="sm" variant="quiet" onClick={() => setPairs(pairs.filter((_, j) => j !== i))}> + Remove pair + </Button> + </div> + {(["then", "now"] as const).map((w) => ( + <div key={w} className="flex flex-wrap items-end gap-2"> + <span className="micro w-10 pb-1.5">{w}</span> + <Field label="Clip"> + <Select aria-label={`flip ${i + 1} ${w} clip`} value={p[w].entry} onChange={(e) => side(i, w, "entry", e.target.value)}> + <option value="">pick a clip</option> + {clips.map((c) => ( + <option key={c.id} value={c.id}> + {c.id} — {c.label} + </option> + ))} + </Select> + </Field> + <Field label="When"> + <Input aria-label={`flip ${i + 1} ${w} when`} value={p[w].when} maxLength={18} onChange={(e) => side(i, w, "when", e.target.value)} className="w-28" placeholder="2019" /> + </Field> + <Field label="Words" className="min-w-0 flex-1"> + <Input aria-label={`flip ${i + 1} ${w} words`} value={p[w].words} maxLength={110} onChange={(e) => side(i, w, "words", e.target.value)} /> + </Field> + </div> + ))} + </div> + ))} + <div> + <Button type="button" size="sm" variant="outline" onClick={() => setPairs([...pairs, { id: "", topic: "", then: blankSide(), now: blankSide() }])}> + Add a pair + </Button> + </div> + </div> + ); +} + +function ThreadsEditor({ + clips, + list, + setList, + assign, + setAssign, +}: { + clips: Clip[]; + list: Thread[]; + setList: (l: Thread[]) => void; + assign: Record<string, string>; + setAssign: (a: Record<string, string>) => void; +}) { + return ( + <div className="grid gap-2" data-hand-threads={list.length}> + {list.map((t, i) => ( + <div key={i} className="flex flex-wrap items-end gap-2"> + <Field label="Thread"> + <Input aria-label={`thread ${i + 1} label`} value={t.label} maxLength={32} onChange={(e) => setList(list.map((x, j) => (j === i ? { ...x, label: e.target.value } : x)))} className="w-56" /> + </Field> + <Field label="Outcome"> + <Select + aria-label={`thread ${i + 1} outcome`} + value={t.outcome?.verdict ?? ""} + onChange={(e) => setList(list.map((x, j) => (j === i ? { ...x, outcome: e.target.value ? { ...(x.outcome ?? {}), verdict: e.target.value } : undefined } : x)))} + > + <option value="">none</option> + {VERDICTS.map((v) => ( + <option key={v} value={v}> + {v.toLowerCase().replace("_", " ")} + </option> + ))} + </Select> + </Field> + <Button type="button" size="sm" variant="quiet" onClick={() => setList(list.filter((_, j) => j !== i))}> + Remove thread + </Button> + </div> + ))} + <div> + <Button type="button" size="sm" variant="outline" onClick={() => setList([...list, { id: "", label: "" }])}> + Add a thread + </Button> + </div> + {list.length > 0 && ( + <div className="grid gap-0.5"> + <span className="micro">each clip&apos;s thread</span> + {clips.map((c) => ( + <label key={c.id} className="flex min-w-0 items-center gap-2 text-[12px]"> + <span className="w-16 shrink-0 font-mono text-[11px] text-muted">{c.id}</span> + <select + aria-label={`thread of ${c.id}`} + value={assign[c.id] ?? ""} + onChange={(e) => { + const next = { ...assign }; + if (e.target.value) next[c.id] = e.target.value; + else delete next[c.id]; + setAssign(next); + }} + className="rounded-[3px] border border-seam-2 bg-panel px-1.5 py-0.5 text-[12px]" + > + <option value="">none</option> + {list.map((t, i) => ( + <option key={i} value={t.id || slug(t.label, i, "t")}> + {t.label || `thread ${i + 1}`} + </option> + ))} + </select> + <span className="truncate text-text-2">{c.label}</span> + </label> + ))} + </div> + )} + </div> + ); +} + +export default function HandFill({ project, initial }: { project: string; initial: HandFillView }) { + const router = useRouter(); + const hydrated = useHydrated(); + const [view, setView] = useState(initial); + const [open, setOpen] = useState(false); + const [text, setText] = useState<Record<string, string>>({}); + const [pairs, setPairs] = useState<Pair[]>(initial.flips?.pairs ?? []); + const [list, setList] = useState<Thread[]>(initial.threads?.list ?? []); + const [assign, setAssign] = useState<Record<string, string>>(initial.threads?.clips ?? {}); + const [panelDirty, setPanelDirty] = useState<"flips" | "threads" | null>(null); + const [busy, setBusy] = useState(false); + const [status, setStatus] = useState<{ ok: boolean; text: string; errors: string[] } | null>(null); + const val = (k: string) => text[k] ?? ""; + const put = (k: string) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => setText({ ...text, [k]: e.target.value }); + // A cut has flips or threads, never both: the one it has, else either. + const panel: "flips" | "threads" | "either" = view.flips ? "flips" : view.threads ? "threads" : "either"; + const empties = view.empty.length; + + const fills = () => { + const out: { field: string; entry?: string; value: unknown }[] = []; + for (const f of view.empty) { + if (f.field === "onscreen") { + const title = val(`${f.address}:title`).trim(); + const subtitle = val(`${f.address}:subtitle`).trim(); + if (title || subtitle) out.push({ field: "onscreen", entry: f.entry!, value: { ...(title ? { title } : {}), ...(subtitle ? { subtitle } : {}) } }); + } else if (f.field === "lines") { + const lines = val(f.address).split("\n").map((l) => l.trim()).filter(Boolean); + if (lines.length) out.push({ field: "lines", entry: f.entry!, value: lines }); + } else if (f.field === "publish.youtube") { + const title = val("youtube:title").trim(); + const description = val("youtube:description").trim(); + if (title || description) out.push({ field: f.field, value: { title, description } }); + } else if (f.field === "publish.x" || f.field === "publish.bluesky") { + const post = val(f.field).trim(); + if (post) out.push({ field: f.field, value: { post } }); + } + } + if (panelDirty === "flips" && pairs.length) { + out.push({ + field: "render.chrome.flips", + value: { pairs: pairs.map((p, i) => ({ id: p.id || slug(p.topic, i, "p"), topic: p.topic.trim(), then: { ...p.then, when: p.then.when.trim(), words: p.then.words.trim() }, now: { ...p.now, when: p.now.when.trim(), words: p.now.words.trim() } })) }, + }); + } + if (panelDirty === "threads" && list.length) { + out.push({ + field: "render.chrome.threads", + value: { list: list.map((t, i) => ({ id: t.id || slug(t.label, i, "t"), label: t.label.trim(), ...(t.outcome?.verdict ? { outcome: t.outcome } : {}) })), clips: assign }, + }); + } + return out; + }; + + const save = async () => { + const f = fills(); + if (!f.length) return setStatus({ ok: false, text: "nothing filled yet", errors: [] }); + setBusy(true); + setStatus(null); + try { + const r = await fetch("/api/report/hand-fill", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, token: view.token, fills: f }), cache: "no-store" }); + const b = (await r.json().catch(() => ({}))) as Partial<HandFillView> & { written?: string[]; refused?: { field: string; error: string; errors: string[] } | null; error?: string }; + if (b.written?.length) { + announceManifestChanged(project); + router.refresh(); + } + if (b.empty) { + setView(b as HandFillView); + setText({}); + setPanelDirty(null); + } + if (!r.ok && !b.refused) throw new Error(b.error ?? `HTTP ${r.status}`); + setStatus( + b.refused + ? { ok: false, text: `${b.written?.length ? `wrote ${b.written.join(", ")}; ` : ""}${b.refused.field} was refused: ${b.refused.error}`, errors: b.refused.errors } + : { ok: true, text: `written by hand: ${(b.written ?? []).join(", ")}`, errors: [] }, + ); + } catch (e) { + setStatus({ ok: false, text: (e as Error).message, errors: [] }); + } finally { + setBusy(false); + } + }; + + const onscreen = view.empty.filter((f) => f.field === "onscreen"); + const teasers = view.empty.filter((f) => f.field === "lines"); + const has = (field: string) => view.empty.some((f) => f.field === field); + + return ( + <section aria-label="fill by hand" data-hand-fill={empties} className="rounded-[3px] border border-seam bg-panel px-4 py-3"> + <div className="flex flex-wrap items-center gap-2"> + <h2 className="micro mr-1">by hand</h2> + <Button size="sm" variant={open ? "pressed" : "outline"} aria-expanded={open} disabled={!hydrated} onClick={() => setOpen(!open)} data-hand-fill-toggle=""> + Fill empty fields by hand + </Button> + <span className="font-mono text-[11.5px] text-muted-2"> + {empties} empty field{empties === 1 ? "" : "s"} + </span> + </div> + {open && ( + <form + className="mt-3 grid gap-4" + onSubmit={(e) => { + e.preventDefault(); + void save(); + }} + > + {onscreen.length > 0 && ( + <fieldset className="grid gap-1.5" aria-label="on-screen titles"> + <legend className="micro mb-1">on-screen titles</legend> + {onscreen.map((f) => ( + <div key={f.address} className="flex min-w-0 flex-wrap items-center gap-2" data-hand-field={f.address}> + <span className="w-16 shrink-0 font-mono text-[11px] text-muted">{f.entry}</span> + <Input aria-label={`on-screen title of ${f.entry}`} placeholder="title" value={val(`${f.address}:title`)} onChange={put(`${f.address}:title`)} className="w-60" /> + <Input aria-label={`on-screen subtitle of ${f.entry}`} placeholder="subtitle (optional)" value={val(`${f.address}:subtitle`)} onChange={put(`${f.address}:subtitle`)} className="w-60" /> + {f.context && <span className="min-w-0 flex-1 truncate font-serif text-[12px] text-text-2">“{f.context}”</span>} + </div> + ))} + </fieldset> + )} + {teasers.map((f) => ( + <Field key={f.address} label={`Teaser ${f.entry}: its lines, one a row`}> + <Textarea aria-label={`teaser lines of ${f.entry}`} rows={3} value={val(f.address)} onChange={put(f.address)} /> + </Field> + ))} + {has("publish.youtube") && ( + <fieldset className="grid gap-1.5" aria-label="YouTube"> + <legend className="micro mb-1">youtube</legend> + <Input aria-label="YouTube title" placeholder="title (at most 100)" maxLength={100} value={val("youtube:title")} onChange={put("youtube:title")} /> + <Textarea aria-label="YouTube description" rows={3} placeholder="description" value={val("youtube:description")} onChange={put("youtube:description")} /> + </fieldset> + )} + {(has("publish.x") || has("publish.bluesky")) && ( + <fieldset className="grid gap-1.5 md:grid-cols-2" aria-label="social posts"> + <legend className="micro mb-1">social posts</legend> + {has("publish.x") && <Textarea aria-label="X post" rows={3} placeholder="X post" value={val("publish.x")} onChange={put("publish.x")} />} + {has("publish.bluesky") && <Textarea aria-label="Bluesky post" rows={3} placeholder="Bluesky post" value={val("publish.bluesky")} onChange={put("publish.bluesky")} />} + </fieldset> + )} + {view.deck ? ( + <> + {panel !== "threads" && ( + <fieldset className="grid gap-1.5" aria-label="flips" onChange={() => setPanelDirty("flips")}> + <legend className="micro mb-1">flips{view.flips ? " (as they stand)" : ""}</legend> + <FlipsEditor + clips={view.clips} + pairs={pairs} + setPairs={(p) => { + setPairs(p); + setPanelDirty("flips"); + }} + /> + </fieldset> + )} + {panel !== "flips" && ( + <fieldset className="grid gap-1.5" aria-label="threads" onChange={() => setPanelDirty("threads")}> + <legend className="micro mb-1">threads{view.threads ? " (as they stand)" : ""}</legend> + <ThreadsEditor + clips={view.clips} + list={list} + setList={(l) => { + setList(l); + setPanelDirty("threads"); + }} + assign={assign} + setAssign={(a) => { + setAssign(a); + setPanelDirty("threads"); + }} + /> + </fieldset> + )} + {panel === "either" && <p className="m-0 text-[12px] text-muted">a cut has flips or threads, not both: the one you edit last is saved</p>} + </> + ) : ( + <p className="m-0 text-[12px] text-muted">Flips and threads are drawn by the on-screen deck: turn it on under On-screen to write them.</p> + )} + <div className="flex items-center gap-2"> + <Button type="submit" variant="go" disabled={!hydrated || busy}> + {busy ? "Saving…" : "Save what is filled"} + </Button> + <span className="text-[12px] text-muted">saved as yours: no draft replaces it</span> + </div> + {status && ( + <div role={status.ok ? "status" : "alert"} data-hand-fill-status={status.ok ? "ok" : "refused"} className={`text-[12px] ${status.ok ? "text-text-2" : "text-reject-text"}`}> + {status.text} + {status.errors.length > 0 && ( + <ul className="m-0 mt-0.5 list-disc pl-5"> + {status.errors.map((x, i) => ( + <li key={i}>{x}</li> + ))} + </ul> + )} + </div> + )} + </form> + )} + </section> + ); +} diff --git a/umtool/components/projects/report/MediaTab.tsx b/umtool/components/projects/report/MediaTab.tsx @@ -7,6 +7,8 @@ import MediaDrafts, { type FieldProvenance } from "../MediaDrafts"; import OnscreenSection from "../OnscreenSection"; import YoutubeSection from "../YoutubeSection"; import SocialPostSection from "../SocialPostSection"; +import HandFill, { type HandFillView } from "../HandFill"; +import { handFillView } from "@/lib/report/hand-fill.mjs"; import type { DraftsView } from "../drafts"; import type { ReportTabProps } from "./shared"; @@ -17,7 +19,9 @@ import type { ReportTabProps } from "./shared"; // (moved out of Build), the upload's text and the promotion posts. Release 28's review page, // Draft panel and the Iterations tab's media drafts are this now; the // narration's words are edited and played on its bench (…/narration), the -// fields walked one at a time on the review bench (…/review). +// fields walked one at a time on the review bench (…/review). Under the drafts, +// Fill by hand (release 32 R2): the empty fields as blanks a person fills, no +// model (components/projects/HandFill.tsx). export default async function MediaTab({ project, detail }: ReportTabProps) { const { manifest: m, build, entries } = detail; @@ -40,6 +44,8 @@ export default async function MediaTab({ project, detail }: ReportTabProps) { narrated={narrationsOf(m).length} /> + <HandFill project={project.id} initial={{ ...(handFillView(m) as Omit<HandFillView, "token">), token }} /> + {/* --- what is drawn over it --------------------------------------- */} {/* The on-screen panel: its settings, its words and a live preview of both, whole (P4a-1 parked it on Build; its words are media). "Re-render diff --git a/umtool/e2e/by-hand.spec.ts b/umtool/e2e/by-hand.spec.ts @@ -20,8 +20,12 @@ import * as urls from "./urls"; // The record is hand-chan/hv1, written here as the corpus has // one (metadata + an English VTT), which the quote check reads. // -// WRITES articles/hand-respell/, articles/hand-blank/, channels/hand-chan/ -// (removed after) +// hand-fill-e2e a report-video project made here (an empty timeline): Fill +// empty fields by hand on its Media tab writes the YouTube text +// and an X post as the operator's, no drafted mark +// +// WRITES articles/hand-respell/, articles/hand-blank/, channels/hand-chan/, +// hand-fill-e2e/ (removed after) // --------------------------------------------------------------------------- const HERE = path.dirname(fileURLToPath(import.meta.url)); @@ -31,6 +35,7 @@ const RESPELL = "hand-respell"; const BLANK = "hand-blank"; const AT = "2026-10-16T10:00:00.000Z"; const CHANNEL = path.join(FIXTURE, "channels", "hand-chan"); +const FILL = "hand-fill-e2e"; const ts = (s: number) => new Date(s * 1000).toISOString().slice(11, 23); const VTT = @@ -101,6 +106,7 @@ test.beforeAll(async ({ playwright }) => { test.afterAll(() => { for (const id of [RESPELL, BLANK]) rmSync(path.join(ARTICLES, id), { recursive: true, force: true }); rmSync(CHANNEL, { recursive: true, force: true }); + rmSync(path.join(FIXTURE, FILL), { recursive: true, force: true }); }); test("Fix a mishearing: the preview's word hunks per file, then Apply writes both reports and lists the backups", async ({ page }) => { @@ -192,3 +198,25 @@ test("start blank on Create, then add a claim by hand: a new section, a verdict, await expect(page.locator("[data-current-report='1']")).toBeVisible(); expect(json(path.join(ARTICLES, BLANK, "report.json")).sections[0].claims[0].verdict).toBe("CORROBORATED"); }); + +test("Fill empty fields by hand on the Media tab: the YouTube text and an X post, written as yours (no drafted mark)", async ({ page, request }) => { + rmSync(path.join(FIXTURE, FILL), { recursive: true, force: true }); + const made = await request.post("/api/projects/new", { data: { kind: "report-video", slug: FILL, title: "Hand fill" } }); + expect(made.status()).toBe(200); + const id = (await made.json()).id as string; + await page.goto(urls.projectHref(id, { tab: "media" })); + const fill = page.getByRole("region", { name: "fill by hand" }); + await expect(fill).toHaveAttribute("data-hand-fill", "3"); + await fill.getByRole("button", { name: "Fill empty fields by hand" }).click(); + // No deck: the flips and threads say where they come from. + await expect(fill).toContainText("drawn by the on-screen deck"); + await fill.getByRole("textbox", { name: "YouTube title" }).fill("A Synthetic Title"); + await fill.getByRole("textbox", { name: "YouTube description" }).fill("A synthetic description."); + await fill.getByRole("textbox", { name: "X post" }).fill("A synthetic post."); + await fill.getByRole("button", { name: "Save what is filled" }).click(); + await expect(fill.locator("[data-hand-fill-status='ok']")).toContainText("written by hand: publish.youtube, publish.x"); + await expect(fill).toHaveAttribute("data-hand-fill", "1"); + const m = json(path.join(FIXTURE, FILL, "video.manifest.json")); + expect(m.publish).toEqual({ youtube: { title: "A Synthetic Title", description: "A synthetic description." }, x: { post: "A synthetic post." } }); + expect(m.drafted ?? {}).toEqual({}); +}); diff --git a/umtool/lib/report/hand-fill.mjs b/umtool/lib/report/hand-fill.mjs @@ -0,0 +1,120 @@ +// FILL BY HAND (release 32 R2): beside Draft everything on the Media tab, every +// media field the cut leaves EMPTY offered as a blank a person fills -- the +// clips' on-screen titles, the teasers' lines, the flips or the threads, the +// YouTube title and description, the X and Bluesky posts -- so a run with no +// compute at all reaches a buildable manifest. +// +// What a person writes goes through the manifest writer as the operator's edit +// (manifest.mjs writeDraftedField: the field's own validators, a snapshot, the +// write token) and carries NO drafted mark: by the drafted-fields contract +// (common/lib/report/drafted.mjs) a non-empty field with no mark is the +// operator's -- "written by hand" -- and no draft ever replaces it. A blank is +// a form field, never a placeholder written into the manifest: an empty value +// is nobody's (a draft may fill it), and a placeholder would ship in a build. +// +// The flips and the threads have no other hand editor, so they are offered +// whole (their pairs or list as they stand) whenever the deck draws them. +// +// Plain ESM: `node --test` runs it. +import { isEmptyField } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; +import { FIELD_LABELS } from "umtool-report-to-video/drafts-review"; +import { writeDraftedField } from "./manifest.mjs"; + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +/** The fields Fill by hand writes, in the order it saves them. */ +export const HAND_FIELDS = Object.freeze(["onscreen", "lines", "render.chrome.flips", "render.chrome.threads", "publish.youtube", "publish.x", "publish.bluesky"]); + +const firstOf = (timeline, type) => { + const seen = new Set(); + return timeline.filter((e) => isObj(e) && e.type === type && typeof e.id === "string" && !seen.has(e.id) && seen.add(e.id)); +}; + +const readPath = (m, field) => field.split(".").reduce((o, k) => (isObj(o) ? o[k] : undefined), m); + +/** + * What Fill by hand offers for a manifest: + * empty every empty field: { address, entry, field, label, context } + * clips the cut's clips (id, a label), for the flips' and threads' selects + * deck whether the on-screen deck is on (the flips and threads need it) + * flips the flips as they stand, else null; threads likewise, with each + * clip's thread (`clips`) + * + * @param {any} manifest + */ +export function handFillView(manifest) { + const m = isObj(manifest) ? manifest : {}; + const timeline = Array.isArray(m.timeline) ? m.timeline : []; + const empty = []; + for (const e of firstOf(timeline, "clip")) { + if (!isEmptyField("onscreen", e.onscreen)) continue; + empty.push({ + address: `onscreen/${e.id}`, + entry: e.id, + field: "onscreen", + label: FIELD_LABELS.onscreen, + context: [typeof e.quote === "string" ? e.quote : "", typeof e.chapter === "string" ? e.chapter : ""].filter(Boolean).join(" · "), + }); + } + for (const e of firstOf(timeline, "teaser")) { + if (!isEmptyField("lines", e.lines)) continue; + empty.push({ address: `teaser/${e.id}/lines`, entry: e.id, field: "lines", label: FIELD_LABELS.lines, context: "" }); + } + const chrome = isObj(m.render?.chrome) ? m.render.chrome : null; + const flips = chrome && !isEmptyField("render.chrome.flips", chrome.flips) ? chrome.flips : null; + const threadsList = chrome && !isEmptyField("render.chrome.threads", chrome.threads) ? chrome.threads.list : null; + for (const field of ["publish.youtube", "publish.x", "publish.bluesky"]) { + if (isEmptyField(field, readPath(m, field))) empty.push({ address: field, entry: null, field, label: FIELD_LABELS[field] ?? field, context: "" }); + } + const clips = firstOf(timeline, "clip").map((e) => ({ + id: e.id, + label: [e.onscreen?.title, typeof e.quote === "string" ? e.quote.slice(0, 60) : ""].find((x) => typeof x === "string" && x.trim()) ?? e.id, + thread: typeof e.thread === "string" && e.thread ? e.thread : null, + })); + return { + empty, + clips, + deck: !!chrome, + flips: flips ? { pairs: flips.pairs } : null, + threads: threadsList ? { list: threadsList, clips: Object.fromEntries(clips.filter((c) => c.thread).map((c) => [c.id, c.thread])) } : null, + }; +} + +/** A fill as the form sends it, checked for shape (the writer checks the rest). */ +function cleanFill(f, i) { + if (!isObj(f)) throw new Error(`fill ${i + 1} is an object`); + const field = String(f.field ?? ""); + if (!HAND_FIELDS.includes(field)) throw new Error(`fill ${i + 1}: ${field || "(no field)"} is not a field filled by hand`); + const onEntry = field === "onscreen" || field === "lines"; + const entry = onEntry ? String(f.entry ?? "") : null; + if (onEntry && !entry) throw new Error(`fill ${i + 1}: ${field} names its entry`); + return { entry, field, value: f.value }; +} + +/** + * Write the fills, one field at a time through writeDraftedField (each its own + * checked, snapshotted write; the token carried from one to the next). Stops at + * the first refusal: what was written before it stays, and is said. + * + * @param {string} dir + * @param {unknown[]} fills + * @param {{ token?: string | null }} [opts] + * @returns {Promise<{ written: string[], token: string | null, refused: { field: string, entry: string | null, error: string, errors: string[] } | null }>} + */ +export async function applyHandFill(dir, fills, { token = null } = {}) { + if (!Array.isArray(fills) || !fills.length) throw new Error("nothing to write: fill a field first"); + const clean = fills.map(cleanFill).sort((a, b) => HAND_FIELDS.indexOf(a.field) - HAND_FIELDS.indexOf(b.field)); + const written = []; + let t = token; + for (const f of clean) { + try { + const w = await writeDraftedField(dir, { entry: f.entry, field: f.field, value: f.value }, { token: t }); + t = w.token ?? null; + written.push(f.entry ? `${f.field}/${f.entry}` : f.field); + } catch (e) { + if (e?.name === "StaleToken") throw e; + return { written, token: t, refused: { field: f.field, entry: f.entry, error: e instanceof Error ? e.message : String(e), errors: Array.isArray(e?.errors) ? e.errors : [] } }; + } + } + return { written, token: t, refused: null }; +} diff --git a/umtool/lib/report/hand-fill.test.mjs b/umtool/lib/report/hand-fill.test.mjs @@ -0,0 +1,78 @@ +// Fill by hand (release 32 R2): every empty media field offered, and what a +// person writes saved through the manifest writer with no drafted mark (the +// operator's: no draft replaces it). Over the S0 kit's synthetic manifests. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +import { MANIFEST_NAME } from "./manifest.mjs"; +import { applyHandFill, handFillView } from "./hand-fill.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const kit = (name) => JSON.parse(readFileSync(path.join(HERE, `../../../common/testing/draft/manifests/${name}.video.manifest.json`), "utf8")); + +async function project(t, manifest) { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-hand-fill-")); + t.after(() => rm(dir, { recursive: true, force: true })); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + "\n"); + return { dir, read: async () => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")) }; +} + +test("handFillView: each empty field once — clips' on-screen text, the publish texts; the threads as they stand", () => { + const v = handFillView(kit("full")); + assert.deepEqual( + v.empty.map((f) => f.address), + ["onscreen/c02", "onscreen/c03", "onscreen/c05", "onscreen/c06", "onscreen/c07", "publish.youtube", "publish.x", "publish.bluesky"], + ); + assert.equal(v.deck, true); + assert.equal(v.flips, null); + assert.deepEqual(v.threads.list.map((x) => x.id), ["bakery", "contest"]); + assert.equal(v.threads.clips.c04, "contest"); + assert.equal(v.clips.length, 7); + // A teaser with no lines is offered; a cut with no deck says so. + const m = kit("full"); + m.timeline.find((e) => e.id === "fin").lines = []; + delete m.render.chrome; + const w = handFillView(m); + assert.ok(w.empty.some((f) => f.address === "teaser/fin/lines")); + assert.deepEqual([w.deck, w.threads], [false, null]); +}); + +test("applyHandFill: written unmarked (the operator's), in the field order; a refusal stops and is said", async (t) => { + const p = await project(t, kit("full")); + const out = await applyHandFill(p.dir, [ + { field: "publish.youtube", value: { title: "The bakery and the contest", description: "Synthetic description." } }, + { field: "onscreen", entry: "c02", value: { title: "The oven" } }, + { field: "publish.x", value: { post: "A synthetic post." } }, + ]); + assert.equal(out.refused, null); + assert.deepEqual(out.written, ["onscreen/c02", "publish.youtube", "publish.x"]); + const m = await p.read(); + assert.deepEqual(m.timeline.find((e) => e.id === "c02").onscreen, { title: "The oven" }); + assert.equal(m.publish.youtube.title, "The bakery and the contest"); + assert.equal(m.drafted?.["publish.youtube"], undefined); + assert.equal(m.timeline.find((e) => e.id === "c02").drafted?.onscreen, undefined); + // Now filled: no longer offered. + assert.deepEqual(handFillView(m).empty.map((f) => f.address).filter((a) => a.startsWith("publish")), ["publish.bluesky"]); + + // Threads by hand, with each clip's thread; then a pair of flips is refused (a cut has one or the other). + const th = await applyHandFill(p.dir, [{ field: "render.chrome.threads", value: { list: [{ id: "all", label: "All of it" }], clips: { c01: "all", c02: "all" } } }]); + assert.equal(th.refused, null); + const m2 = await p.read(); + assert.deepEqual(m2.timeline.filter((e) => e.thread).map((e) => [e.id, e.thread]), [["c01", "all"], ["c02", "all"]]); + const bad = await applyHandFill(p.dir, [ + { field: "onscreen", entry: "c03", value: { title: "Kept" } }, + { field: "render.chrome.flips", value: { pairs: [{ id: "p1", topic: "Ovens", then: { entry: "c01", when: "2019", words: "a" }, now: { entry: "c02", when: "2025", words: "b" } }] } }, + ]); + assert.deepEqual(bad.written, ["onscreen/c03"]); + assert.equal(bad.refused?.field, "render.chrome.flips"); + assert.ok(bad.refused?.error); + await assert.rejects(applyHandFill(p.dir, [{ field: "timeline", value: [] }]), /not a field filled by hand/); + await assert.rejects(applyHandFill(p.dir, []), /nothing to write/); +});