Archilyzer · Source

archilyzer

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

commit e124d3cfc54be7e61a14818bd5cb2af1fbf747ad
parent 6aad1b4bd144a3bc28f332168fed02e63479a946
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 10:26:15 -0400

umtool: the Media tab, one surface for every drafted field (P4b)

components/projects/MediaDrafts.tsx: every drafted field of the cut as one
lit list grouped by its section, each line its words, its provenance (the
draft file, when and by what model, the attempt chosen, the rule a refused
attempt broke), its review, Approve draft / Reject with a note and its kept
alternatives; each section headed by its Draft with <model> (DraftPanel.tsx's
DraftControl on the ONE JobProgress); Approve all, Draft everything (the
draft-all chain), section chips. a / r approve or reject the lit field. The
on-screen panel moves from Build to Media whole; the review page is a bench
(the field list, the verdict bar on the lit field, the clip it is drawn over
on the reader); DraftsReview is gone. The Iterations tab's Narrate, media
drafts and Draft everything become a Media drafts link (IterationRow gains
projectId). SECTION_TAB.onscreen is media.

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

Diffstat:
Mumtool/components/articles/IterationsTab.tsx | 91+++++++++++++-------------------------------------------------------------------
Mumtool/components/projects/DraftPanel.tsx | 301++++++++++++++++++++++---------------------------------------------------------
Dumtool/components/projects/DraftsReview.tsx | 90-------------------------------------------------------------------------------
Aumtool/components/projects/MediaDrafts.tsx | 685+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/ReviewPage.tsx | 89++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------
Mumtool/components/projects/report/BuildTab.tsx | 22+++++-----------------
Mumtool/components/projects/report/MediaTab.tsx | 99++++++++++++++++++++++++++++++++++---------------------------------------------
Mumtool/lib/articles/generation.ts | 12++++++++++++
Mumtool/lib/pieces/tabs.mjs | 8+++++---
Mumtool/lib/pieces/tabs.test.mjs | 2+-
10 files changed, 908 insertions(+), 491 deletions(-)

diff --git a/umtool/components/articles/IterationsTab.tsx b/umtool/components/articles/IterationsTab.tsx @@ -4,6 +4,7 @@ import Link from "next/link"; import { useCallback, useEffect, useState } from "react"; import { Button, buttonVariants } from "@/components/ui/button"; import { hasRunPage, runHref } from "@/lib/research/runs-hrefs"; +import { projectHref } from "@/lib/hrefs"; import { badgeVariants } from "@/components/ui/badge"; import ChainPanel from "@/components/articles/ChainPanel"; import { EditorJobProgress } from "@/components/ui/job-progress"; @@ -31,17 +32,6 @@ const STATUS_VARIANT: Record<string, "on" | "blocking" | "open" | "info" | "neut cancelled: "info", }; -// The media drafts beside narrate (release 28): each a report-draft STEP on a -// done iteration's video manifest. -const MEDIA_TASKS: { task: string; label: string }[] = [ - { task: "cut", label: "the cut" }, - { task: "onscreen", label: "on-screen titles" }, - { task: "teaser", label: "the teaser" }, - { task: "flips", label: "flips" }, - { task: "threads", label: "threads" }, - { task: "youtube", label: "YouTube text" }, -]; - // The report-draft task that made an iteration of this kind (a copy re-runs it). const TASK_OF: Record<string, string | null> = { sweep: "sweep", "revise-report": "revise-report", "revise-video": "revise-video", research: "research" }; @@ -162,17 +152,9 @@ function IterationCard({ comparing: boolean; onCompare: (on: boolean) => void; }) { - const [open, setOpen] = useState<"new" | "chain" | "draft-all" | null>(null); + const [open, setOpen] = useState<"new" | "chain" | null>(null); const g = ctx.policy?.generation; - const routeModel = (t: string) => (g?.routes[t as keyof typeof g.routes] === "api" ? g?.models.api : g?.models.local) ?? ""; - const [mediaTask, setMediaTask] = useState(MEDIA_TASKS[0].task); - const [mediaModel, setMediaModel] = useState(() => routeModel(MEDIA_TASKS[0].task)); - const [mediaForce, setMediaForce] = useState(false); - const [allModel, setAllModel] = useState(() => routeModel("onscreen")); - // Each press of Draft everything mounts a fresh panel that starts it. - const [allRun, setAllRun] = useState(0); const [copyModel, setCopyModel] = useState(() => ctx.allModels.find((m) => m !== it.model) ?? it.model); - const [narrateModel, setNarrateModel] = useState(g?.routes.narrate === "api" ? g.models.api : (g?.models.local ?? "")); const [copyExtractor, setCopyExtractor] = useState(g?.models.extractor ?? ""); const done = it.status === "done"; const active = it.status === "queued" || it.status === "running"; @@ -319,60 +301,18 @@ function IterationCard({ </Button> </span> )} - {done && it.hasManifest && !runningStep && ( - <span className="flex items-center gap-1"> - <ModelSelect label={`narration model for ${it.label}`} value={narrateModel} onChange={setNarrateModel} models={ctx.allModels} /> - <Button size="sm" onClick={() => void ctx.post({ task: "narrate", article: ctx.article, iteration: it.n, model: narrateModel })}> - Narrate - </Button> - </span> - )} - {done && it.hasManifest && !runningStep && ( - <span className="flex items-center gap-1" data-media-draft={it.n}> - <select - aria-label={`draft task for ${it.label}`} - className={field} - value={mediaTask} - onChange={(e) => { - setMediaTask(e.target.value); - setMediaModel(routeModel(e.target.value)); - }} - > - {MEDIA_TASKS.map((t) => ( - <option key={t.task} value={t.task}> - {t.label} - </option> - ))} - </select> - <ModelSelect label={`draft model for ${it.label}`} value={mediaModel} onChange={setMediaModel} models={ctx.allModels} /> - <label className="flex items-center gap-1 text-[11px] text-[var(--color-dim)]" title="re-draft fields a model drafted; a field you wrote or edited is never replaced"> - <input type="checkbox" checked={mediaForce} onChange={(e) => setMediaForce(e.target.checked)} aria-label={`force: re-draft drafted fields of ${it.label}`} /> - force - </label> - <Button - size="sm" - onClick={() => - void ctx.post({ task: mediaTask, article: ctx.article, iteration: it.n, model: mediaModel, ...(mediaForce ? { force: true } : {}) }) - } - > - Draft - </Button> - </span> - )} - {done && it.reportFrom !== null && ( - <span className="flex items-center gap-1"> - <ModelSelect label={`Draft everything model for ${it.label}`} value={allModel} onChange={setAllModel} models={ctx.allModels} /> - <Button - size="sm" - aria-expanded={open === "draft-all"} - onClick={() => { - setOpen("draft-all"); - setAllRun((k) => k + 1); - }} - > - Draft everything - </Button> - </span> + {/* The media drafts -- narration, on-screen, the cut, the teaser, + flips, threads, YouTube, and Draft everything -- are the Media + tab's (P4b): ONE surface per video. */} + {done && it.hasManifest && it.projectId && ( + <Link + href={projectHref(it.projectId, { tab: "media" })} + prefetch={false} + data-media-link={it.n} + className={buttonVariants({ variant: "outline", size: "sm" })} + > + Media drafts → + </Link> )} {done && it.reportFrom !== null && ( <Button size="sm" aria-expanded={open === "chain"} onClick={() => setOpen(open === "chain" ? null : "chain")}> @@ -407,9 +347,6 @@ function IterationCard({ </div> {open === "new" && <NewIterationForm it={it} ctx={ctx} onDone={() => setOpen(null)} />} {open === "chain" && <ChainPanel article={ctx.article} n={it.n} label={it.label} />} - {open === "draft-all" && ( - <ChainPanel key={allRun} article={ctx.article} n={it.n} label={it.label} mode="draft-all" model={allModel} autoStart={allRun > 0} /> - )} </article> ); } diff --git a/umtool/components/projects/DraftPanel.tsx b/umtool/components/projects/DraftPanel.tsx @@ -1,33 +1,57 @@ "use client"; -import Link from "next/link"; -import { useRouter } from "next/navigation"; -import { useCallback, useEffect, useRef, useState } from "react"; -import { badgeVariants } from "@/components/ui/badge"; +import { useEffect, useState } from "react"; import { Button } from "@/components/ui/button"; -import { reviewHref } from "@/lib/hrefs"; -import { DraftAlternatives, DraftBadge, announceDraftsChanged, useDrafts } from "./drafts"; -import { announceManifestChanged } from "./timelineApi"; +import { EditorJobProgress, type EditorJob } from "@/components/ui/job-progress"; import type { DraftRowView, DraftRunSummary, ProjectIteration } from "@/lib/articles/projectDraft"; -// DRAFT WITH <MODEL> (release 28 M9): each draftable section of the cut — -// the cut, on-screen, teaser, flips, threads, narration, YouTube — drafted by -// a model as a `report-draft` step on the iteration the project was made -// from (umtool's /api/articles/generate → the editor). The models are the -// policy's, the task's route preselected; `force` re-drafts only fields a -// model drafted (a field you wrote or edited is never replaced — its draft is -// kept as an alternative); a per-entry task may be limited to the entries -// ticked. While the job runs its progress shows; when it ends the page is -// re-read: the badges, the alternatives with Use this, and what the task's -// draft file says it wrote, skipped and refused. +// DRAFT WITH <MODEL> (release 28 M9; the Media tab's section heads since P4b): +// a draftable section of the cut — the cut, on-screen, teaser, flips, +// threads, narration, YouTube — drafted by a model as a `report-draft` step +// on the iteration the project was made from (umtool's /api/articles/generate +// → the editor). The models are the policy's, the task's route preselected; +// `force` re-drafts only fields a model drafted (a field you wrote or edited +// is never replaced — its draft is kept as an alternative); a per-entry task +// may be limited to the entries ticked. While the job runs it is the ONE +// JobProgress; when it ends the surface is re-read, and the row says what the +// task's draft file says it wrote, skipped and refused. -type Policy = { generation: { routes: Record<string, string>; models: { api: string; local: string } }; models: { api: string[]; local: string[] } }; -type JobView = { status: string; queue: { key?: string; position?: number } | null; progress: { metric: string; current: number; target: number } | null; tail: string[] }; +export type Policy = { generation: { routes: Record<string, string>; models: { api: string; local: string } }; models: { api: string[]; local: string[] } }; -const field = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)]"; +/** The generation policy, asked of the editor once (null until it answers; the error says why not). */ +export function usePolicy(enabled: boolean): { policy: Policy | null; error: string } { + const [policy, setPolicy] = useState<Policy | null>(null); + const [error, setError] = useState(""); + useEffect(() => { + if (!enabled) return; + let alive = true; + void (async () => { + const r = await fetch("/api/articles/policy", { cache: "no-store" }).catch(() => null); + const b = r ? await r.json().catch(() => ({})) : {}; + if (!alive) return; + if (r?.ok && b.policy) setPolicy(b.policy as Policy); + else setError(b.error ?? "the editor did not answer"); + })(); + return () => { + alive = false; + }; + }, [enabled]); + return { policy, error }; +} + +/** The models a task may draft with, its route's first. */ +export function modelsFor(policy: Policy | null, task: string): { route: string; models: string[] } { + const g = policy?.generation; + const route = g ? (g.routes[task] === "api" ? g.models.api : g.models.local) : ""; + const models = policy ? [...new Set([route, ...policy.models.api, ...policy.models.local].filter(Boolean))] : []; + return { route, models }; +} + +const field = "rounded-[3px] border border-seam-2 bg-ground px-1.5 py-0.5 text-[12px] text-text"; const ENDED = ["done", "failed", "cancelled"]; -function RunLine({ run }: { run: DraftRunSummary }) { +/** What the task's last run here left in its draft file. */ +export function RunLine({ run }: { run: DraftRunSummary }) { const c = run.counts; const parts = [ c.applied ? `${c.applied} written` : "", @@ -39,18 +63,18 @@ function RunLine({ run }: { run: DraftRunSummary }) { const failing = run.checks.filter((ch) => !ch.ok); const problems = run.units.filter((u) => u.outcome === "refused" || u.outcome === "kept" || u.outcome === "none"); return ( - <div data-draft-run={run.task} className="mt-1 text-[11px] text-[var(--color-dim)]"> + <div data-draft-run={run.task} className="text-[11.5px] text-muted"> <span> last run{run.model ? <span className="font-mono"> {run.model}</span> : null} {run.at ? `, ${new Date(run.at).toLocaleString()}` : ""}: {parts.join(" · ") || "nothing"} </span> {failing.map((ch) => ( - <p key={ch.name} data-draft-check={ch.name} className="text-[var(--color-dirty)]"> + <p key={ch.name} data-draft-check={ch.name} className="m-0 text-doubt-text"> check {ch.name}: {ch.detail ?? "failed"} </p> ))} {problems.length > 0 && ( - <ul className="list-disc pl-4"> + <ul className="m-0 list-disc pl-4"> {problems.slice(0, 8).map((u) => ( <li key={u.id} data-draft-unit={u.id} data-draft-outcome={u.outcome}> <span className="font-mono">{u.label ?? u.id}</span>: {u.why ?? u.outcome} @@ -63,28 +87,26 @@ function RunLine({ run }: { run: DraftRunSummary }) { ); } -function DraftRow({ - project, +/** + * One section's "Draft with <model>": the button, the model, force, the + * entries; then the job, followed; then the last run. + */ +export function DraftControl({ row, link, policy, run, runningJob, - view, onEnded, }: { - project: string; row: DraftRowView; link: Extract<ProjectIteration, { ok: true }>; policy: Policy | null; run: DraftRunSummary | undefined; runningJob: string | null; - view: ReturnType<typeof useDrafts>; onEnded: () => void | Promise<void>; }) { - const g = policy?.generation; - const routeModel = g ? (g.routes[row.task] === "api" ? g.models.api : g.models.local) : ""; - const models = policy ? [...new Set([routeModel, ...policy.models.api, ...policy.models.local].filter(Boolean))] : []; + const { route: routeModel, models } = modelsFor(policy, row.task); const [model, setModel] = useState(routeModel); useEffect(() => { if (!model && routeModel) setModel(routeModel); @@ -92,7 +114,7 @@ function DraftRow({ const [force, setForce] = useState(false); const [picked, setPicked] = useState<string[]>([]); const [jobId, setJobId] = useState<string | null>(runningJob); - const [job, setJob] = useState<JobView | null>(null); + const [ended, setEnded] = useState<EditorJob | null>(null); const [error, setError] = useState(""); const [sending, setSending] = useState(false); @@ -100,43 +122,7 @@ function DraftRow({ if (runningJob) setJobId(runningJob); }, [runningJob]); - // The latest callback, so the poll below depends on the job alone; and each - // job's end is told once (a re-render after the refresh must not tell it again). - const ended = useRef(onEnded); - ended.current = onEnded; - const told = useRef<string | null>(null); - useEffect(() => { - if (!jobId) return; - let alive = true; - let stop = false; - const tick = async () => { - if (stop) return; - try { - const r = await fetch(`/api/articles/job?id=${encodeURIComponent(jobId)}&tail=6`, { cache: "no-store" }); - const b = await r.json(); - if (!alive) return; - if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); - setJob(b.job); - if (ENDED.includes(b.job.status)) { - stop = true; - if (told.current !== jobId) { - told.current = jobId; - void ended.current(); - } - } - } catch (e) { - if (alive) setError((e as Error).message); - } - }; - void tick(); - const t = setInterval(tick, 2000); - return () => { - alive = false; - clearInterval(t); - }; - }, [jobId]); - - const active = !!jobId && !!job && !ENDED.includes(job.status); + const active = !!jobId && !ended; const start = async () => { setError(""); setSending(true); @@ -152,7 +138,7 @@ function DraftRow({ const r = await fetch("/api/articles/generate", { method: "POST", body: JSON.stringify(body) }); const b = await r.json().catch(() => ({})); if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); - setJob(null); + setEnded(null); setJobId(String(b.jobId)); } catch (e) { setError((e as Error).message); @@ -160,30 +146,16 @@ function DraftRow({ setSending(false); } }; - const cancel = async () => { - if (!jobId) return; - const r = await fetch("/api/articles/job", { method: "POST", body: JSON.stringify({ cancel: jobId }) }); - if (!r.ok) setError(((await r.json().catch(() => ({}))) as { error?: string }).error ?? `HTTP ${r.status}`); - }; - const p = job?.progress; - const queued = job?.status === "queued" && (job.queue?.position ?? 0) > 0; return ( - <li data-draft-task={row.task} data-draft-job={job?.status ?? (jobId ? "asking" : "")} className="border-t border-[var(--color-line)] py-1.5 first:border-t-0"> - <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1"> - <h3 className="text-[13px] text-[var(--color-text)]">{row.label}</h3> - <span className="text-[11px] text-[var(--color-dim)]">{row.writes}</span> - <span data-draft-state="" className="ml-auto text-[11px]"> - {row.state} - </span> - </div> + <div data-draft-task={row.task} data-draft-job={ended?.status ?? (jobId ? "running" : "")} className="space-y-1.5"> {row.blocked ? ( - <p data-draft-blocked="" className="text-[11px] text-[var(--color-dim)]"> + <p data-draft-blocked="" className="m-0 text-[12px] text-muted"> {row.blocked} </p> ) : ( - <div className="mt-1 flex flex-wrap items-center gap-2"> - <Button size="sm" variant="primary" aria-label={`Draft ${row.label}`} disabled={!policy || sending || active} onClick={() => void start()}> + <div className="flex flex-wrap items-center gap-2"> + <Button size="sm" variant="outline" aria-label={`Draft ${row.label}`} disabled={!policy || sending || active} onClick={() => void start()}> Draft with </Button> <select aria-label={`model for ${row.label}`} className={`${field} font-mono`} value={model} onChange={(e) => setModel(e.target.value)} disabled={!policy}> @@ -194,13 +166,13 @@ function DraftRow({ </option> ))} </select> - <label className="flex items-center gap-1 text-[11px] text-[var(--color-dim)]"> + <label className="flex items-center gap-1 text-[11.5px] text-muted" title="re-drafts only what a model drafted; a field you wrote or edited is never replaced"> <input type="checkbox" checked={force} onChange={(e) => setForce(e.target.checked)} aria-label={`force: re-draft ${row.label}`} /> - force — re-drafts only what a model drafted; a field you wrote or edited is never replaced + force </label> {row.entries && row.entries.length > 0 && ( - <details className="text-[11px]"> - <summary className="cursor-pointer text-[var(--color-dim)]">{picked.length ? `${picked.length} of ${row.entries.length} entries` : `every entry (${row.entries.length})`}</summary> + <details className="text-[11.5px]"> + <summary className="cursor-pointer text-muted">{picked.length ? `${picked.length} of ${row.entries.length} entries` : `every entry (${row.entries.length})`}</summary> <div className="mt-1 flex max-h-40 flex-col gap-0.5 overflow-auto"> {row.entries.map((e) => ( <label key={e.id} className="flex items-center gap-1"> @@ -218,139 +190,30 @@ function DraftRow({ )} </div> )} - {jobId && job && !ENDED.includes(job.status) && ( - <div data-draft-progress={row.task} className="mt-1 flex flex-wrap items-center gap-2 text-[11px]"> - <span role="status" className="text-[var(--color-dirty)]"> - {queued ? `queued, ${job.queue?.position} ahead on ${job.queue?.key}` : job.status} - {p ? ` — ${p.metric} ${p.current}/${p.target}` : ""} - </span> - {job.tail.length > 0 && <span className="truncate font-mono text-[var(--color-dim)]">{job.tail[job.tail.length - 1]}</span>} - <Button size="sm" variant="destructive" aria-label={`Cancel the ${row.label} draft`} onClick={() => void cancel()}> - Cancel - </Button> - </div> + {jobId && !ended && ( + <EditorJobProgress + data-draft-progress={row.task} + jobId={jobId} + cancelName={`Cancel the ${row.label} draft`} + onEnd={(j) => { + // A Cancel answers before the editor has said so: it is cancelled. + setEnded(j && ENDED.includes(j.status) ? j : { id: jobId, kind: null, status: "cancelled", queue: null, progress: null, tail: j?.tail ?? [] }); + void onEnded(); + }} + /> )} - {jobId && job && ENDED.includes(job.status) && ( - <p data-draft-ended={job.status} className={`mt-1 text-[11px] ${job.status === "done" ? "text-[var(--color-dim)]" : "text-[var(--color-bad)]"}`}> - the draft {job.status === "done" ? "is done" : job.status} - {job.status !== "done" && job.tail.length ? `: ${job.tail.filter((l) => !l.startsWith("@@")).slice(-1)[0] ?? ""}` : ""} + {jobId && ended && ENDED.includes(ended.status) && ( + <p data-draft-ended={ended.status} className={`m-0 text-[11.5px] ${ended.status === "done" ? "text-muted" : "text-reject-text"}`}> + the draft {ended.status === "done" ? "is done" : ended.status} + {ended.status !== "done" && ended.tail.length ? `: ${ended.tail.filter((l) => !l.startsWith("@@")).slice(-1)[0] ?? ""}` : ""} </p> )} {run && <RunLine run={run} />} - {row.address && ( - <div className="mt-1"> - <DraftBadge address={row.address} view={view.view} act={view.act} compact /> - <DraftAlternatives address={row.address} view={view.view} act={view.act} /> - </div> - )} - {!row.address && run && run.alternatives > 0 && ( - <Link href={reviewHref(project)} className="ink-link text-[11px]"> - {run.alternatives} alternative(s) kept — review them - </Link> - )} {error && ( - <p role="alert" className="mt-1 text-[11px] text-[var(--color-bad)]"> + <p role="alert" className="m-0 text-[11.5px] text-reject-text"> {error} </p> )} - </li> - ); -} - -export default function DraftPanel({ - project, - link, - rows, - runs: initialRuns, -}: { - project: string; - link: ProjectIteration; - rows: DraftRowView[]; - runs: Partial<Record<string, DraftRunSummary>>; -}) { - const router = useRouter(); - const view = useDrafts(project); - const [policy, setPolicy] = useState<Policy | null>(null); - const [policyError, setPolicyError] = useState(""); - const [runs, setRuns] = useState(initialRuns); - const [running, setRunning] = useState<Record<string, string>>(link.ok ? link.running : {}); - - useEffect(() => { - if (!link.ok) return; - let alive = true; - void (async () => { - const r = await fetch("/api/articles/policy", { cache: "no-store" }).catch(() => null); - const b = r ? await r.json().catch(() => ({})) : {}; - if (!alive) return; - if (r?.ok && b.policy) setPolicy(b.policy as Policy); - else setPolicyError(b.error ?? "the editor did not answer"); - })(); - return () => { - alive = false; - }; - }, [link.ok]); - - // A draft ended: the manifest changed under every section — re-read it all. - const onEnded = useCallback(async (): Promise<void> => { - const r = await fetch(`/api/articles/draft?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null); - if (r?.ok) { - const b = await r.json(); - setRuns(b.runs ?? {}); - if (b.link?.ok) setRunning(b.link.running ?? {}); - } - announceManifestChanged(project); - announceDraftsChanged(project); - router.refresh(); - }, [project, router]); - - return ( - <section aria-label="draft with a model" data-draft-panel={link.ok ? `${link.article}/i${link.n}` : ""} className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"> - <div className="mb-1 flex flex-wrap items-baseline gap-3"> - <h2 className="micro">draft</h2> - {link.ok && ( - <span className="text-[11px] text-[var(--color-dim)]"> - steps on{" "} - <Link href={`/articles/${link.article}?tab=iterations`} className="ink-link font-mono"> - {link.article} i{link.n} - </Link> - </span> - )} - {link.ok && ( - <span className={badgeVariants({ variant: "info", size: "sm" })}>a final build refuses a draft nobody approved</span> - )} - </div> - {!link.ok ? ( - <p data-draft-unlinked="" className="text-[12px] text-[var(--color-dim)]"> - {link.why} - </p> - ) : link.status !== "done" ? ( - <p data-draft-unlinked="" className="text-[12px] text-[var(--color-dim)]"> - {link.article} i{link.n} is {link.status}: a draft runs over a done iteration - </p> - ) : ( - <> - {policyError && ( - <p role="alert" className="text-[12px] text-[var(--color-bad)]"> - {policyError}: drafting needs the editor - </p> - )} - <ul> - {rows.map((row) => ( - <DraftRow - key={row.task} - project={project} - row={row} - link={link} - policy={policy} - run={runs[row.task]} - runningJob={running[row.task] ?? null} - view={view} - onEnded={onEnded} - /> - ))} - </ul> - </> - )} - </section> + </div> ); } diff --git a/umtool/components/projects/DraftsReview.tsx b/umtool/components/projects/DraftsReview.tsx @@ -1,90 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { narrationHref, projectHref } from "@/lib/hrefs"; -import { DraftAlternatives, DraftBadge, useDrafts, type DraftsView } from "./drafts"; - -// `/browse/<project>/review`'s list (release 28, M0): every drafted field of -// the cut -- who drafted it, its value as words, its review -- and every -// alternative a draft task kept, with "Use this". A narration's words are -// edited and played on the narration page; here they are judged like any -// other draft. - -export default function DraftsReview({ project, initial }: { project: string; initial: DraftsView }) { - const { view, act } = useDrafts(project, initial); - const v = view ?? initial; - const drafted = v.rows.filter((r) => r.drafted); - const shown = new Set(drafted.map((r) => r.address)); - // Alternatives for fields that are not drafted (the operator's), by field. - const loose = [...new Set(v.alternatives.filter((a) => !a.inUse && !shown.has(a.address)).map((a) => a.address))]; - const where = (entry: string | null, field: string) => (entry ? `${entry}` : field); - return ( - <div className="space-y-3"> - <p - data-drafts-gate={v.gate.errors.length ? "refuses" : "passes"} - data-gate-errors={v.gate.errors.length} - className="text-[11px] text-[var(--color-dim)]" - > - {v.error ? ( - <span className="text-[var(--color-bad)]">{v.error}</span> - ) : v.gate.errors.length ? ( - <> - A final build refuses {v.gate.errors.length} field{v.gate.errors.length === 1 ? "" : "s"} until approved ( - <code className="font-mono">--drafts-unreviewed</code> builds the unapproved anyway; never a rejected one). - </> - ) : ( - <>A final build takes every draft as it is.</> - )}{" "} - Verdicts in <code className="font-mono">{v.file}</code>. - </p> - {drafted.length === 0 && loose.length === 0 && ( - <p data-drafts-empty="" className="text-[12px] text-[var(--color-dim)]"> - Nothing in this cut was drafted.{" "} - <Link href={projectHref(project, { tab: "media" })} className="ink-link"> - back to {project} - </Link> - </p> - )} - {drafted.map((r) => ( - <article - key={r.address} - data-draft-row={r.address} - data-state={r.state} - className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2" - > - <div className="mb-1 flex flex-wrap items-center gap-2"> - <span className="font-mono text-[12px] text-[var(--color-text)]">{where(r.entry, r.field)}</span> - <span className="micro">{r.label}</span> - {r.field === "narration" && ( - <Link href={narrationHref(project)} className="ink-link text-[11px]"> - edit and play on the narration page - </Link> - )} - </div> - <p data-draft-text="" className="mb-1 whitespace-pre-wrap text-[13px] text-[var(--color-text)]"> - {r.text || "—"} - </p> - {r.state === "edited" && r.judgedText && ( - <p className="mb-1 text-[11px] text-[var(--color-dim)]"> - {r.verdict} on: <span className="italic">{r.judgedText}</span> - </p> - )} - <DraftBadge address={r.address} view={v} act={act} /> - <DraftAlternatives address={r.address} view={v} act={act} /> - </article> - ))} - {loose.map((address) => { - const a = v.alternatives.find((x) => x.address === address)!; - return ( - <article key={address} data-draft-row={address} data-state="operator" className="rounded border border-[var(--color-line)] px-3 py-2"> - <div className="mb-1 flex flex-wrap items-center gap-2"> - <span className="font-mono text-[12px] text-[var(--color-text)]">{where(a.entry, a.field)}</span> - <span className="micro">{a.label} · yours; a draft was kept aside</span> - </div> - <DraftAlternatives address={address} view={v} act={act} /> - </article> - ); - })} - </div> - ); -} diff --git a/umtool/components/projects/MediaDrafts.tsx b/umtool/components/projects/MediaDrafts.tsx @@ -0,0 +1,685 @@ +"use client"; + +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import ChainPanel from "@/components/articles/ChainPanel"; +import { buttonVariants } from "@/components/ui/button"; +import { LitActions, LitGroup, LitLine } from "@/components/ui/lit-line"; +import { LitList, type LitDetail } from "@/components/ui/lit-list"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import { clock } from "@/components/ui/clock"; +import { ReaderPane } from "@/components/ui/reader-pane"; +import { narrationHref, reviewHref } from "@/lib/hrefs"; +import { citationText } from "@/lib/research/facets.mjs"; +import type { DraftRowView, DraftRunSummary, ProjectIteration } from "@/lib/articles/projectDraft"; +import { DraftControl, modelsFor, usePolicy } from "./DraftPanel"; +import { DraftAlternatives, announceDraftsChanged, useDrafts, type DraftAct, type DraftRow, type DraftsView } from "./drafts"; +import { announceManifestChanged } from "./timelineApi"; +import { BenchBody, VerdictBar } from "./bench/BenchShell"; +import CopyCitation from "./bench/CopyCitation"; + +// --------------------------------------------------------------------------- +// THE MEDIA SURFACE (plans/umtool-redesign.md, P4b; canvas "Piece · Media"): +// every drafted field of the cut, one line each -- what it says, where it came +// from (the model, the attempts, the rule a refused attempt broke), its review +// -- grouped by the section that drafts it, each section headed by its "Draft +// with <model>". Approve or reject per field, Approve all, Draft everything. +// It absorbs release 28's review page (DraftsReview), the project page's Draft +// panel and the Iterations tab's media drafts: the Media tab draws it with +// the sections' controls, the review bench (`…/review`) draws its field list +// alone, one field at a time, with the verdict bar and the reader. +// +// The fields are ONE lit list (j/k from anywhere); `a` approves the lit field +// as it is, `r` rejects it (the note is the answer: the cursor goes there +// first). Signal is the lit field's Approve draft only. +// --------------------------------------------------------------------------- + +export type FieldProvenance = { + file: string; + model: string | null; + at: string | null; + attempts: number; + chosen: number | null; + repaired: boolean; + failed: { attempt: number; hard: string[] }[]; + soft: string[]; +}; + +/** The sections, in Draft everything's order: a field's address starts with its section's task. */ +export const MEDIA_SECTIONS: { task: string; label: string }[] = [ + { task: "cut", label: "Cut" }, + { task: "onscreen", label: "On-screen" }, + { task: "teaser", label: "Teaser" }, + { task: "flips", label: "Flips" }, + { task: "threads", label: "Threads" }, + { task: "narrate", label: "Narration" }, + { task: "youtube", label: "YouTube" }, +]; +const sectionOf = (address: string) => address.split("/")[0]; + +const STATE_WORDS: Record<DraftRow["state"], string> = { + approved: "approved", + rejected: "rejected", + edited: "changed since approved", + unreviewed: "not reviewed", +}; +const STATE_TONE: Record<DraftRow["state"], string> = { + approved: "text-meter", + rejected: "text-reject-text", + edited: "text-doubt-text", + unreviewed: "text-muted-2", +}; + +const day = (iso: string | null) => { + if (!iso) return null; + const d = new Date(iso); + return Number.isNaN(d.getTime()) ? null : `${d.toISOString().slice(0, 10)} ${d.toISOString().slice(11, 16)}`; +}; + +/** The provenance line: the file, when and by what, the attempts, the rules refused attempts broke, the review. */ +export function ProvenanceLine({ row, prov }: { row: DraftRow; prov: FieldProvenance | null }) { + const by = row.drafted?.model ?? prov?.model ?? null; + const at = day(row.drafted?.at ?? prov?.at ?? null); + const parts: React.ReactNode[] = []; + if (prov) parts.push(prov.file); + if (row.drafted || prov) parts.push(`drafted${at ? ` ${at}` : ""}${by ? ` by ${by}` : ""}`); + else parts.push("written by hand"); + if (prov) { + if (prov.repaired) parts.push(`repaired from ${prov.attempts} attempt${prov.attempts === 1 ? "" : "s"}`); + else if (prov.chosen) parts.push(`attempt ${prov.chosen} of ${prov.attempts}${prov.attempts > 1 ? " chosen" : ""}`); + for (const f of prov.failed.filter((x) => x.attempt !== prov.chosen)) { + parts.push( + <span key={`f${f.attempt}`}> + attempt {f.attempt} failed: <span className="text-reject-text">✕ {f.hard.join("; ")}</span> + </span>, + ); + } + if (prov.failed.length === 0 && prov.chosen) parts.push("no rule broken"); + if (prov.soft.length) parts.push(<span key="soft" className="text-doubt-text">flag: {prov.soft.join("; ")}</span>); + } else if (row.drafted) { + parts.push(`attempt ${row.drafted.attempt}`); + } + parts.push(<span key="state" className={STATE_TONE[row.state]}>{STATE_WORDS[row.state]}</span>); + return ( + <div data-draft-prov="" className="mt-1.5 font-mono text-[11px] leading-snug text-muted-2"> + {parts.map((p, i) => ( + <span key={i}> + {i > 0 && " · "} + {p} + </span> + ))} + </div> + ); +} + +/** One drafted field: its name, its words and provenance, Approve draft / Reject (+ note), its alternatives. */ +function FieldLine({ + row, + prov, + view, + act, + lit, + noteRef, +}: { + row: DraftRow; + prov: FieldProvenance | null; + view: DraftsView; + act: DraftAct; + lit: boolean; + noteRef?: (el: HTMLInputElement | null) => void; +}) { + const [note, setNote] = useState(row.note ?? ""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + useEffect(() => setNote(row.note ?? ""), [row.note]); + const run = async (action: string, extra: Record<string, unknown> = {}) => { + setBusy(true); + setError(null); + try { + await act(action, { address: row.address, ...extra }); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + const where = row.entry ? `${sectionLabel(row.address)} · ${row.entry}` : `${sectionLabel(row.address)} · ${row.field}`; + return ( + <LitLine id={row.address} data-draft-row={row.address} data-state={row.state} className="grid gap-x-3.5 gap-y-1 md:grid-cols-[150px_minmax(0,1fr)_auto]"> + <div className="text-[12.5px] font-medium"> + {row.entry ?? row.label} + <small className="mt-0.5 block font-mono text-[11px] font-normal text-muted-2">{where}</small> + </div> + <div className="min-w-0"> + <p data-draft-text="" className={`m-0 max-w-[72ch] whitespace-pre-wrap text-[13.5px] leading-normal ${lit ? "text-text" : ""}`}> + {row.text || "—"} + </p> + {row.state === "edited" && row.judgedText && ( + <p className="m-0 mt-1 text-[11.5px] text-muted"> + {row.verdict} on: <span className="italic">{row.judgedText}</span> + </p> + )} + <ProvenanceLine row={row} prov={prov} /> + <DraftAlternatives address={row.address} view={view} act={act} /> + {error && ( + <p data-draft-error="" className="m-0 mt-1 text-[11.5px] text-reject-text"> + {error} + </p> + )} + </div> + <LitActions className="flex-wrap items-start md:w-[240px] md:justify-end"> + <button + type="button" + data-draft-action="approve" + aria-pressed={row.state === "approved"} + disabled={busy} + title={row.state === "approved" ? "take the approval back" : "approve this draft as it is now"} + className={buttonVariants({ variant: row.state === "approved" ? "outline" : lit ? "go" : "outline", size: "sm" })} + onClick={() => void run(row.state === "approved" ? "clear" : "approve", row.state === "approved" ? {} : { note })} + > + {row.state === "approved" ? "Approved" : "Approve draft"} + </button> + <button + type="button" + data-draft-action="reject" + aria-pressed={row.state === "rejected"} + disabled={busy} + title="reject this draft; the note says what is wrong" + className={buttonVariants({ variant: row.state === "rejected" ? "destructive" : "outline", size: "sm" })} + onClick={() => void run(row.state === "rejected" ? "clear" : "reject", row.state === "rejected" ? {} : { note })} + > + {row.state === "rejected" ? "Rejected" : "Reject"} + </button> + {row.field === "narration" && row.entry && ( + <Link href={narrationHref(viewProject(view))} className="ink-link self-center text-[11.5px]"> + edit and play + </Link> + )} + <input + ref={noteRef} + value={note} + onChange={(e) => setNote(e.target.value)} + onBlur={() => { + if (note.trim() !== (row.note ?? "") && row.verdict) void run("note", { note }); + }} + disabled={busy} + placeholder="note (a rejection needs one)" + aria-label={`note on the draft of ${row.address}`} + data-draft-note="" + maxLength={2000} + className="w-full min-w-0 rounded-[3px] border border-seam-2 bg-ground px-1.5 py-0.5 text-[11.5px] text-text" + /> + </LitActions> + </LitLine> + ); +} + +// The project id rides on the view so a line can link its narration page. +const viewProject = (v: DraftsView) => (v as DraftsView & { project?: string }).project ?? ""; +const sectionLabel = (address: string) => MEDIA_SECTIONS.find((s) => s.task === sectionOf(address))?.label ?? sectionOf(address); + +/** A field that is the operator's, with a draft kept aside for it. */ +function LooseLine({ address, view, act }: { address: string; view: DraftsView; act: DraftAct }) { + const a = view.alternatives.find((x) => x.address === address)!; + return ( + <LitLine id={address} data-draft-row={address} data-state="operator" className="grid gap-x-3.5 gap-y-1 md:grid-cols-[150px_minmax(0,1fr)]"> + <div className="text-[12.5px] font-medium"> + {a.entry ?? a.label} + <small className="mt-0.5 block font-mono text-[11px] font-normal text-muted-2">yours · a draft kept aside</small> + </div> + <div className="min-w-0"> + <DraftAlternatives address={address} view={view} act={act} /> + </div> + </LitLine> + ); +} + +export type MediaFieldsProps = { + project: string; + view: DraftsView; + act: DraftAct; + provenance: Record<string, FieldProvenance>; + /** The sections' heads: the Media tab's "Draft with" per task; the bench has none. */ + heads?: Partial<Record<string, React.ReactNode>>; + /** Only these sections (a chip's filter). */ + only?: string | null; + onLit?: (address: string | null) => void; +}; + +/** The field list: one lit list, grouped by section, `a` / `r` on the lit field. */ +export function MediaFields({ project, view, act, provenance, heads, only = null, onLit }: MediaFieldsProps) { + const rows = view.rows; + const shown = new Set(rows.map((r) => r.address)); + const loose = [...new Set(view.alternatives.filter((a) => !a.inUse && !shown.has(a.address)).map((a) => a.address))]; + const [lit, setLit] = useState<string | null>(null); + const notes = useRef(new Map<string, HTMLInputElement>()); + const box = useRef<HTMLDivElement>(null); + const v = useMemo(() => ({ ...view, project }) as DraftsView, [view, project]); + + const sections = MEDIA_SECTIONS.filter((s) => !only || s.task === only) + .map((s) => ({ + ...s, + rows: rows.filter((r) => sectionOf(r.address) === s.task), + loose: loose.filter((a) => sectionOf(a) === s.task), + })) + .filter((s) => heads?.[s.task] || s.rows.length || s.loose.length); + + const onLight = useCallback( + (d: LitDetail) => { + setLit(d.id); + onLit?.(d.id); + }, + [onLit], + ); + + // `a` approves the lit field as it is; `r` rejects it -- with its note, or + // the cursor goes to the note first (the note is the answer). + const hydrated = useHydrated(); + useEffect(() => { + if (!hydrated) return; + const onKey = (e: KeyboardEvent) => { + if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return; + if ((e.target as HTMLElement | null)?.closest?.("input, textarea, select, video, audio, [contenteditable='true'], dialog[open]")) return; + if (e.key !== "a" && e.key !== "r") return; + const row = rows.find((r) => r.address === lit); + if (!row) return; + e.preventDefault(); + if (e.key === "a") { + if (row.state !== "approved") void act("approve", { address: row.address, note: row.note ?? "" }).catch(() => {}); + return; + } + const input = notes.current.get(row.address); + if (input && !input.value.trim()) { + input.focus(); + return; + } + void act("reject", { address: row.address, note: input?.value ?? row.note ?? "" }).catch(() => input?.focus()); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [hydrated, rows, lit, act]); + + if (sections.length === 0) { + return ( + <p data-drafts-empty="" className="text-[12.5px] text-muted"> + Nothing in this cut was drafted. + </p> + ); + } + return ( + <div ref={box}> + <LitList label="Drafted fields" global onLight={onLight}> + {sections.map((s) => ( + <LitGroup + key={s.task} + data-media-section={s.task} + id={`media-${s.task}`} + title={s.label} + count={s.rows.length || undefined} + className="pt-1" + > + {heads?.[s.task] && <div className="border-b border-seam px-0 py-2.5">{heads[s.task]}</div>} + {s.rows.map((r) => ( + <FieldLine + key={r.address} + row={r} + prov={provenance[r.address] ?? null} + view={v} + act={act} + lit={lit === r.address} + noteRef={(el) => { + if (el) notes.current.set(r.address, el); + else notes.current.delete(r.address); + }} + /> + ))} + {s.loose.map((a) => ( + <LooseLine key={a} address={a} view={v} act={act} /> + ))} + </LitGroup> + ))} + </LitList> + </div> + ); +} + +/** The gate line: what a final build would say of the review. */ +export function GateLine({ view }: { view: DraftsView }) { + return ( + <p data-drafts-gate={view.gate.errors.length ? "refuses" : "passes"} data-gate-errors={view.gate.errors.length} className="m-0 text-[12px] text-muted"> + {view.error ? ( + <span className="text-reject-text">{view.error}</span> + ) : view.gate.errors.length ? ( + <> + A final build refuses {view.gate.errors.length} field{view.gate.errors.length === 1 ? "" : "s"} until approved ( + <code className="font-mono">--drafts-unreviewed</code> builds the unapproved anyway; never a rejected one). + </> + ) : ( + <>A final build takes every draft as it is.</> + )}{" "} + Verdicts in <code className="font-mono">{view.file}</code>. + </p> + ); +} + +/** Approve every field still to review, one after another. */ +export function ApproveAll({ view, act }: { view: DraftsView; act: DraftAct }) { + const hydrated = useHydrated(); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + const todo = view.rows.filter((r) => r.state === "unreviewed" || r.state === "edited"); + if (!todo.length) return null; + return ( + <> + <button + type="button" + data-approve-all={todo.length} + disabled={!hydrated || busy} + className={buttonVariants({ variant: "outline", size: "md" })} + title="approve every field not yet reviewed, as it is now" + onClick={async () => { + setBusy(true); + setError(null); + try { + for (const r of todo) await act("approve", { address: r.address, note: r.note ?? "" }); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }} + > + {busy ? "approving…" : `Approve all ${todo.length}`} + </button> + {error && <span className="text-[12px] text-reject-text">{error}</span>} + </> + ); +} + +// ─── the Media tab ─────────────────────────────────────────────────────────── + +export default function MediaDrafts({ + project, + initial, + provenance, + link, + rows, + runs: initialRuns, + narrated, +}: { + project: string; + initial: DraftsView; + provenance: Record<string, FieldProvenance>; + link: ProjectIteration; + rows: DraftRowView[]; + runs: Partial<Record<string, DraftRunSummary>>; + /** Narrated cards: the narration bench's link. */ + narrated: number; +}) { + const router = useRouter(); + const drafts = useDrafts(project, initial); + const view = drafts.view ?? initial; + const linked = link.ok && link.status === "done"; + const { policy, error: policyError } = usePolicy(linked); + const [runs, setRuns] = useState(initialRuns); + const [running, setRunning] = useState<Record<string, string>>(link.ok ? link.running : {}); + const [only, setOnly] = useState<string | null>(null); + const [allModel, setAllModel] = useState(""); + const [allRun, setAllRun] = useState(0); + const allModels = modelsFor(policy, "onscreen"); + useEffect(() => { + if (!allModel && allModels.route) setAllModel(allModels.route); + }, [allModels.route, allModel]); + + // A draft ended: the manifest changed under every section -- re-read it all. + const onEnded = useCallback(async (): Promise<void> => { + const r = await fetch(`/api/articles/draft?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null); + if (r?.ok) { + const b = await r.json(); + setRuns(b.runs ?? {}); + if (b.link?.ok) setRunning(b.link.running ?? {}); + } + announceManifestChanged(project); + announceDraftsChanged(project); + router.refresh(); + }, [project, router]); + + const heads: Record<string, React.ReactNode> = {}; + for (const row of rows) { + heads[row.task] = ( + <div className="space-y-1"> + <div className="flex flex-wrap items-baseline gap-x-3 gap-y-0.5 text-[12px]"> + <span className="text-muted">{row.writes}</span> + <span data-draft-state="" className="ml-auto font-mono text-[11.5px] text-muted-2"> + {row.state} + </span> + </div> + {linked ? ( + <DraftControl row={row} link={link as Extract<ProjectIteration, { ok: true }>} policy={policy} run={runs[row.task]} runningJob={running[row.task] ?? null} onEnded={onEnded} /> + ) : null} + {row.task === "narrate" && narrated > 0 && ( + <Link href={narrationHref(project)} data-narration-link={narrated} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Narration — {narrated}: edit and play the words → + </Link> + )} + </div> + ); + } + + const counts = view.counts; + const total = view.rows.length; + const chips = MEDIA_SECTIONS.map((s) => ({ ...s, n: view.rows.filter((r) => sectionOf(r.address) === s.task).length })); + return ( + <section aria-label="Media drafts" data-draft-panel={link.ok ? `${link.article}/i${link.n}` : ""} className="space-y-3"> + <div className="flex flex-wrap items-center gap-x-3 gap-y-2"> + <span className="font-mono text-[12px] text-meter" data-media-counts=""> + {total} field{total === 1 ? "" : "s"} · {counts.approved} approved + {counts.rejected ? ` · ${counts.rejected} rejected` : ""} + {counts.unreviewed + counts.edited ? ` · ${counts.unreviewed + counts.edited} to review` : ""} + </span> + {link.ok && ( + <span className="text-[12px] text-muted"> + drafts are steps on{" "} + <Link href={`/articles/${link.article}?tab=iterations`} className="ink-link font-mono"> + {link.article} i{link.n} + </Link> + </span> + )} + <span className="ml-auto flex flex-wrap items-center gap-2"> + {total > 0 && ( + <Link href={reviewHref(project)} data-review-link={view.drafted} className={buttonVariants({ variant: "quiet", size: "md" })}> + Review drafts — {view.drafted} + </Link> + )} + {linked && ( + <> + <select aria-label="Draft everything model" className="rounded-[3px] border border-seam-2 bg-ground px-1.5 py-1 font-mono text-[12px]" value={allModel} onChange={(e) => setAllModel(e.target.value)} disabled={!policy}> + {allModels.models.map((m) => ( + <option key={m} value={m}> + {m} + </option> + ))} + </select> + <button + type="button" + data-draft-everything="" + className={buttonVariants({ variant: "outline", size: "md" })} + disabled={!policy} + onClick={() => setAllRun((k) => k + 1)} + > + Draft everything + </button> + </> + )} + <ApproveAll view={view} act={drafts.act} /> + </span> + </div> + <GateLine view={view} /> + {!link.ok ? ( + <p data-draft-unlinked="" className="m-0 text-[12px] text-muted"> + {link.why} + </p> + ) : link.status !== "done" ? ( + <p data-draft-unlinked="" className="m-0 text-[12px] text-muted"> + {link.article} i{link.n} is {link.status}: a draft runs over a done iteration + </p> + ) : ( + policyError && ( + <p role="alert" className="m-0 text-[12px] text-reject-text"> + {policyError}: drafting needs the editor + </p> + ) + )} + {link.ok && allRun > 0 && <ChainPanel key={allRun} article={link.article} n={link.n} label={`i${link.n}`} mode="draft-all" model={allModel} autoStart />} + <div className="flex flex-wrap gap-1.5" role="group" aria-label="Sections"> + <button type="button" data-media-chip="all" aria-pressed={only === null} onClick={() => setOnly(null)} className={chipClass(only === null)}> + All <span className="font-mono text-[11px] text-meter">{total}</span> + </button> + {chips.map((c) => ( + <button key={c.task} type="button" data-media-chip={c.task} aria-pressed={only === c.task} onClick={() => setOnly(only === c.task ? null : c.task)} className={chipClass(only === c.task)}> + {c.label} + {c.n > 0 && <span className="font-mono text-[11px] text-meter">{c.n}</span>} + </button> + ))} + </div> + <MediaFields project={project} view={view} act={drafts.act} provenance={provenance} heads={heads} only={only} /> + </section> + ); +} + +const chipClass = (on: boolean) => + `inline-flex items-center gap-1.5 whitespace-nowrap rounded-[3px] border px-2 py-[3px] text-[12px] ${on ? "border-muted bg-panel-2 text-text" : "border-seam-2 text-text-2 hover:border-muted"}`; + +// ─── the review bench (`…/review`) ─────────────────────────────────────────── + +export type FieldEvidence = { + /** The clip's source, on the reader. */ + source: string; + byline: string[]; + cite: { at: number; duration: number } | null; + quote: string | null; + url: string | null; + cues: { start: number; text: string }[]; +}; + +/** + * The drafts review as a bench: the field list as the work, ONE question on + * the lit field in the verdict bar, and -- for a field drawn over a clip -- + * that clip's source on the reader, its cited cue lit. + */ +export function MediaReview({ + project, + initial, + provenance, + evidence, +}: { + project: string; + initial: DraftsView; + provenance: Record<string, FieldProvenance>; + evidence: Record<string, FieldEvidence>; +}) { + const drafts = useDrafts(project, initial); + const view = drafts.view ?? initial; + const [lit, setLit] = useState<string | null>(null); + const hydrated = useHydrated(); + const row = view.rows.find((r) => r.address === lit) ?? null; + const todo = view.rows.filter((r) => r.state === "unreviewed" || r.state === "edited"); + const ev = row?.entry ? (evidence[row.entry] ?? null) : null; + const [error, setError] = useState<string | null>(null); + const approve = async () => { + if (!row) return; + setError(null); + try { + await drafts.act("approve", { address: row.address, note: row.note ?? "" }); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } + }; + const reject = () => { + if (!row) return; + const input = document.querySelector<HTMLInputElement>(`[data-draft-row="${CSS.escape(row.address)}"] [data-draft-note]`); + if (input && !input.value.trim()) { + input.focus(); + return; + } + setError(null); + drafts.act("reject", { address: row.address, note: input?.value ?? "" }).catch((e) => setError(e instanceof Error ? e.message : String(e))); + }; + const where = row ? (row.entry ? `${row.label} of ${row.entry}` : row.label) : ""; + const verdict = ( + <VerdictBar + data-verdict-for={row?.address ?? ""} + question={ + row ? ( + row.state === "approved" ? ( + <>The {where} is approved.</> + ) : ( + <>Approve the drafted {where}?</> + ) + ) : ( + <>Nothing to review.</> + ) + } + consequence={ + !row + ? undefined + : row.state === "approved" + ? todo.length + ? `${todo.length} still to review.` + : "Every field is approved: a final build takes them as they are." + : row.state === "rejected" + ? `Rejected${row.note ? `: ${row.note}` : ""} — a final build refuses it.` + : "A final build refuses it until it is approved." + } + > + {row && row.state !== "approved" && ( + <button type="button" data-verdict-approve={row.address} disabled={!hydrated} className={buttonVariants({ variant: "go", size: "md" })} onClick={() => void approve()}> + Approve draft <kbd>a</kbd> + </button> + )} + {row && row.state !== "rejected" && ( + <button type="button" data-verdict-reject={row.address} disabled={!hydrated} className={buttonVariants({ size: "md" })} onClick={reject}> + Reject with a note <kbd>r</kbd> + </button> + )} + {error && <span className="text-[12px] text-reject-text">{error}</span>} + </VerdictBar> + ); + const reader = ev ? ( + <ReaderPane + className="h-full" + source={ev.source} + byline={ev.byline} + cite={ev.cite ?? undefined} + label="Source" + cues={ev.cues.map((c, i) => ({ + t: c.start, + text: c.text, + lit: ev.cite ? i === litCueOf(ev.cues, ev.cite.at) : i === 0, + }))} + footer={ev.quote ? <CopyCitation text={citationText({ quote: ev.quote, title: ev.source, clock: ev.cite ? clock(ev.cite.at) : undefined, url: ev.url ?? undefined })} /> : undefined} + fine={ev.quote ? `“${ev.quote}”` : undefined} + /> + ) : ( + <ReaderPane className="h-full" source={row ? where : "Drafts review"} byline={row ? [row.entry ? "not drawn over a clip" : "the whole cut"] : []}> + <p className="m-0 text-[13px] text-reader-dim"> + {row ? "No source window for this field: it is the cut's own words. Read it against the report." : "Light a field to see its source."} + </p> + </ReaderPane> + ); + return ( + <BenchBody verdict={verdict} reader={reader} workClassName="space-y-3"> + <GateLine view={view} /> + <MediaFields project={project} view={view} act={drafts.act} provenance={provenance} onLit={setLit} /> + </BenchBody> + ); +} + +const litCueOf = (cues: { start: number }[], at: number) => { + let best = 0; + cues.forEach((c, i) => { + if (c.start <= at + 0.02) best = i; + }); + return best; +}; diff --git a/umtool/components/projects/ReviewPage.tsx b/umtool/components/projects/ReviewPage.tsx @@ -1,43 +1,76 @@ -import BrowseHeader from "@/components/BrowseHeader"; +import { clock } from "@/components/ui/clock"; import { projectsHref } from "@/lib/hrefs"; -import { readManifest } from "@/lib/projects/report.mjs"; +import { cuesInWindow, readClipDetail, readManifest } from "@/lib/projects/report.mjs"; import { manifestToken } from "@/lib/report/manifest.mjs"; import { draftsView } from "@/lib/report/drafts.mjs"; +import { readFieldProvenance } from "@/lib/report/draft-provenance.mjs"; import { pieceHrefOfProject } from "@/lib/pieces/article"; import type { ProjectRef } from "@/lib/project-types"; -import DraftsReview from "./DraftsReview"; +import { BenchFrame, BenchTop } from "./bench/BenchShell"; +import { MediaReview, type FieldEvidence, type FieldProvenance } from "./MediaDrafts"; import type { DraftsView } from "./drafts"; -// `/browse/<project>/review` -- every drafted field of the cut, approved or -// rejected before a final build (release 28, M0). Verdicts are +// `/projects/<project>/review` -- the drafts review as a BENCH (P4b): every +// drafted field of the cut, walked one at a time -- `j`/`k` light a field, +// `a` approves it, `r` rejects it with its note -- the verdict bar asking +// about the lit field, the reader showing the clip it is drawn over. The +// Media tab draws the same list with each section's "Draft with" (one +// component, components/projects/MediaDrafts.tsx). Verdicts are // <project>/drafts.review.json; a final build refuses a drafted field not -// approved on its current value. The narration page is the narration's own -// view of the same verdicts. +// approved on its current value (release 28, M0). + +const ymd = (d: string | null | undefined) => (d && /^\d{8}$/.test(d) ? `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}` : (d ?? null)); + export default async function ReviewPage({ project }: { project: ProjectRef }) { const manifest = await readManifest(project.dir); - const view = { ...((await draftsView(project.dir, manifest ?? {})) as DraftsView), token: await manifestToken(project.dir) }; + const [view, provenance, token, detail] = await Promise.all([ + draftsView(project.dir, manifest ?? {}) as Promise<DraftsView>, + readFieldProvenance(project.dir, manifest ?? {}) as Promise<Record<string, FieldProvenance>>, + manifestToken(project.dir), + manifest ? readClipDetail(project.dir, { manifest }) : Promise.resolve(null), + ]); const { counts } = view; + + // The source of every clip a drafted field is drawn over: the reader's. + const evidence: Record<string, FieldEvidence> = {}; + const wanted = new Set(view.rows.map((r) => r.entry).filter((e): e is string => !!e)); + type Entry = { id: string; kind: string; start: number; end: number; cite?: number | null; quote?: string | null; video?: string; channel?: string | null; sourceTitleClean?: string | null; title?: string | null; uploadDate?: string | null; date?: string | null; duration?: number | null; citeUrl?: string | null }; + for (const e of ((detail?.entries ?? []) as Entry[]).filter((x) => x.kind === "clip" && wanted.has(x.id))) { + const win = await cuesInWindow(project.dir, e.id, e.start - 20, e.end + 20).catch(() => null); + const at = e.cite ?? e.start; + const duration = e.duration ?? win?.duration ?? null; + evidence[e.id] = { + source: e.sourceTitleClean || e.title || e.video || e.id, + byline: [e.channel, e.date ?? ymd(e.uploadDate), `transcript${duration ? ` · ${clock(duration)}` : ""}`].filter((x): x is string => !!x), + cite: duration ? { at, duration } : null, + quote: e.quote ?? null, + url: e.citeUrl ?? null, + cues: (win?.cues ?? []).map((c: { start: number; text: string }) => ({ start: c.start, text: c.text })), + }; + } + // The piece this view belongs to: the article's when an article claims the project (P4a-2). - const back = await pieceHrefOfProject(project.id); + const back = await pieceHrefOfProject(project.id, { tab: "media" }); + const toReview = counts.edited + counts.unreviewed; return ( - <div className="flex h-full flex-col"> - <BrowseHeader - crumbs={[ - { href: projectsHref(), label: "projects" }, - { href: back, label: project.id }, - { label: "review" }, - ]} - note={ - view.drafted - ? `${view.drafted} drafted · ${counts.approved} approved` + - (counts.rejected ? ` · ${counts.rejected} rejected` : "") + - (counts.edited + counts.unreviewed ? ` · ${counts.edited + counts.unreviewed} to review` : "") - : undefined - } - /> - <main className="deck-main flex-1 space-y-4 p-4"> - <DraftsReview project={project.id} initial={view} /> - </main> - </div> + <BenchFrame + kind="review" + top={ + <BenchTop + trail={[{ href: projectsHref(), label: "projects" }]} + back={{ href: back, label: project.id }} + kind="Drafts review" + here="review" + keys={view.rows.length ? [{ keys: ["j", "k"], label: "field" }, { keys: ["a"], label: "approve" }, { keys: ["r"], label: "reject" }] : []} + note={ + view.rows.length + ? `${view.rows.length} fields · ${counts.approved} approved` + (counts.rejected ? ` · ${counts.rejected} rejected` : "") + (toReview ? ` · ${toReview} to review` : "") + : undefined + } + /> + } + > + <MediaReview project={project.id} initial={{ ...view, token }} provenance={provenance} evidence={evidence} /> + </BenchFrame> ); } diff --git a/umtool/components/projects/report/BuildTab.tsx b/umtool/components/projects/report/BuildTab.tsx @@ -1,16 +1,15 @@ import Link from "next/link"; import { fmtAgo, fmtBytes } from "@/lib/format"; import { mixHref } from "@/lib/hrefs"; -import OnscreenSection from "../OnscreenSection"; import ReportBuildChain from "../ReportBuildChain"; import type { ReportTabProps } from "./shared"; -// The Build tab: the final video, the build chain, and the on-screen panel -- -// OnscreenSection parked here WHOLE until P4b gives on-screen its own Media -// surface. Moved from ReportProject unchanged (P4a-1). +// The Build tab: the final video and the build chain (its job on the ONE +// JobProgress). The on-screen panel was parked here until P4b moved it to +// the Media tab. export default function BuildTab({ project, detail }: ReportTabProps) { - const { manifest: m, build, entries } = detail; + const { build, entries } = detail; return ( <> {build.built && ( @@ -36,18 +35,7 @@ export default function BuildTab({ project, detail }: ReportTabProps) { entries={entries.map((e) => ({ id: e.id, kind: e.kind }))} /> - {/* --- what is drawn over it --------------------------------------- */} - {/* The on-screen panel: its settings, its words and a live preview of - both. After the build chain, because "re-render on-screen" is a run - of that chain over segments it already built; before Deliver, - because the panel is part of the video that gets delivered. */} - <OnscreenSection - project={project.id} - generatedBy={typeof m.generatedBy === "string" ? m.generatedBy : null} - entries={entries.map((e) => ({ id: e.id, kind: e.kind, segment: !!e.segment }))} - built={!!build.built} - /> - + {/* The on-screen panel moved to the Media tab (P4b). */} </> ); } diff --git a/umtool/components/projects/report/MediaTab.tsx b/umtool/components/projects/report/MediaTab.tsx @@ -1,70 +1,57 @@ -import Link from "next/link"; import { narrationsOf } from "umtool-report-to-video/narration"; -import { draftedFields, isCodeDraft } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; -import { readAlternatives } from "@/lib/report/drafts.mjs"; +import { draftsView } from "@/lib/report/drafts.mjs"; +import { readFieldProvenance } from "@/lib/report/draft-provenance.mjs"; +import { manifestToken } from "@/lib/report/manifest.mjs"; import { draftRowsOf, draftRuns, projectIteration } from "@/lib/articles/projectDraft"; -import { buttonVariants } from "@/components/ui/button"; -import { narrationHref, reviewHref } from "@/lib/hrefs"; -import DraftPanel from "../DraftPanel"; +import MediaDrafts, { type FieldProvenance } from "../MediaDrafts"; +import OnscreenSection from "../OnscreenSection"; import YoutubeSection from "../YoutubeSection"; +import type { DraftsView } from "../drafts"; import type { ReportTabProps } from "./shared"; -// The Media tab: release 28's drafts as they were on the project page -- the -// narration script and the drafts review, the "Draft with" panel, the upload's -// text. Moved from ReportProject unchanged (P4a-1); P4b absorbs them into one -// Media surface. +// THE MEDIA TAB (P4b; canvas "Piece · Media"): ONE surface for what the cut +// says over its footage -- every drafted field with its provenance and +// review, each section's "Draft with <model>", Draft everything and Approve +// all (components/projects/MediaDrafts.tsx); then the on-screen panel whole +// (moved out of Build) and the upload's text. 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). export default async function MediaTab({ project, detail }: ReportTabProps) { - const { manifest: m } = detail; - const narrated = narrationsOf(m).length; - // The drafts review (release 28): drafted fields, and alternatives kept. - // (A field a code path made — the converter's timeline — is not a draft to review.) - const draftedCount = draftedFields(m).filter((d) => !isCodeDraft(d.provenance)).length; - const alternativesCount = (await readAlternatives(project.dir)).length; - // "Draft with" (release 28 M9): the iteration the project was made from, and - // each media task's last run here. - const draftLink = await projectIteration(project.dir); - const draftRunsNow = draftLink.ok ? await draftRuns(project.dir) : {}; - + const { manifest: m, build, entries } = detail; + const [view, provenance, link, token] = await Promise.all([ + draftsView(project.dir, m) as Promise<DraftsView>, + readFieldProvenance(project.dir, m) as Promise<Record<string, FieldProvenance>>, + projectIteration(project.dir), + manifestToken(project.dir), + ]); + const runs = link.ok ? await draftRuns(project.dir) : {}; return ( <> - {(narrated > 0 || draftedCount > 0 || alternativesCount > 0) && ( - <div className="flex flex-wrap items-start gap-3"> - {/* The narration script, card by card, before synthesis -- only when - some card carries one. */} - {narrated > 0 && ( - <Link - href={narrationHref(project.id)} - data-narration-link={narrated} - className={buttonVariants({ size: "lg" })} - > - Narration — {narrated} - </Link> - )} - {/* Every drafted field, judged before a final build -- only when a - draft task wrote one, or kept an alternative. */} - {(draftedCount > 0 || alternativesCount > 0) && ( - <Link - href={reviewHref(project.id)} - data-review-link={draftedCount} - className={buttonVariants({ size: "lg" })} - > - Review drafts — {draftedCount} - </Link> - )} - </div> - )} - - {/* --- drafting it ----------------------------------------------- */} - {/* Each draftable section drafted by a model, as a step on the - iteration the project was made from. After the build chain (a - draft changes what the next build makes), before the sections it - writes into. */} - <DraftPanel project={project.id} link={draftLink} rows={draftRowsOf(m as Record<string, unknown>)} runs={draftRunsNow} /> + <MediaDrafts + project={project.id} + initial={{ ...view, token }} + provenance={provenance} + link={link} + rows={draftRowsOf(m as Record<string, unknown>)} + runs={runs} + narrated={narrationsOf(m).length} + /> - {/* --- the upload's text (out/youtube.txt, or its preview) --------- */} - <YoutubeSection dir={project.dir} manifest={m as Record<string, unknown>} /> + {/* --- 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 + on-screen" still runs the build over the segments it already built. */} + <OnscreenSection + project={project.id} + generatedBy={typeof m.generatedBy === "string" ? m.generatedBy : null} + entries={entries.map((e) => ({ id: e.id, kind: e.kind, segment: !!e.segment }))} + built={!!build.built} + /> + {/* --- the upload's text (out/youtube.txt, or its preview) --------- */} + <YoutubeSection dir={project.dir} manifest={m as Record<string, unknown>} /> </> ); } diff --git a/umtool/lib/articles/generation.ts b/umtool/lib/articles/generation.ts @@ -25,6 +25,7 @@ import { agentToken } from "@/lib/annotations/agentAuth.mjs"; import { DEFAULT_PROJECTS_ROOT, REPO_ROOT, chainStart, chainStepsOf, doneSteps } from "@/lib/report/chain.mjs"; import { recentJobs, type Job } from "@/lib/jobs"; import { sitesPaths } from "./sites"; +import { REPORTS_ROOT } from "@/lib/paths.mjs"; // GENERATION, AS UMTOOL SEES IT (release 27 S8): an article's iterations, the // policy, the editor's channels, and the editor's report-draft jobs. @@ -340,11 +341,21 @@ export type IterationRow = { /** The iteration whose report it carries (itself, or the nearest ancestor that made one). */ reportFrom: number | null; projectDir: string | null; + /** The project's id (its path under REPORTS_ROOT), or null when it is not under it (P4b: the Media tab's link). */ + projectId: string | null; hasManifest: boolean; currentReport: boolean; currentVideo: boolean; }; +/** A project directory's id: its path under REPORTS_ROOT, posix, or null outside it. */ +function projectIdOfDir(dir: string | null): string | null { + if (!dir) return null; + const rel = path.relative(REPORTS_ROOT, path.resolve(dir)); + if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return null; + return rel.split(path.sep).join("/"); +} + export type ChainMode = "video" | "draft-all"; export type ChainView = { mode: ChainMode; @@ -415,6 +426,7 @@ function rowOf(it: Iteration, hasReport: Map<number, boolean>, byN: Map<number, hasReport: hasReport.get(it.n) ?? false, reportFrom, projectDir, + projectId: projectIdOfDir(projectDir), hasManifest: projectDir ? exists(path.join(/* turbopackIgnore: true */ projectDir, "video.manifest.json")) : false, currentReport: current.report === it.n, currentVideo: current.video === it.n, diff --git a/umtool/lib/pieces/tabs.mjs b/umtool/lib/pieces/tabs.mjs @@ -114,14 +114,16 @@ export const SECTION_TAB = { cut: "cut", takes: "cut", corrections: "cut", - // Media: r28's drafts (the panel, the review and narration links) and the upload's text. + // Media: every drafted field and each section's Draft with (P4b's one surface), + // the review and narration benches' links, the on-screen panel (moved from + // Build in P4b) and the upload's text. drafts: "media", review: "media", narration: "media", youtube: "media", - // Build: the build chain, the on-screen panel (parked whole until P4b), the final mp4. + onscreen: "media", + // Build: the build chain and the final mp4. build: "build", - onscreen: "build", final: "build", // Deliver: the deliver panel and the exports. deliver: "deliver", diff --git a/umtool/lib/pieces/tabs.test.mjs b/umtool/lib/pieces/tabs.test.mjs @@ -47,7 +47,7 @@ test("a note opens where its anchor is drawn", () => { test("every section is on a real tab; an unknown one throws", () => { for (const [name, tab] of Object.entries(SECTION_TAB)) assert.ok(PIECE_TAB_IDS.includes(tab), name); - assert.equal(tabOfSection("onscreen"), "build"); + assert.equal(tabOfSection("onscreen"), "media"); // moved from Build in P4b assert.equal(tabOfSection("deliver"), "deliver"); assert.throws(() => tabOfSection("nope"), /no section "nope"/); });