Archilyzer · Source

archilyzer

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

commit 3cf594404ec65c5cb3fb9dab0f5e6d61fbbc1ca5
parent 1fa201ef21b6f5fc3b4499396151451361ce71f8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 21:27:04 -0400

umtool: drafted badges, alternatives with Use this, and the review page

Beside each drafted field umtool renders -- an On-screen row's title, a
teaser's lines, a card's narration -- "drafted by <model>", its review state
and Approve / Reject (with a note); under a field a draft task could not
replace, its alternatives with "Use this". `/browse/<project>/review` lists
every drafted field of the cut and what a final build would refuse; the
project page links it ("Review drafts — N"). The narration page stays (it
edits and plays the words) and writes the drafts review.

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

Diffstat:
Aumtool/components/projects/DraftsReview.tsx | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/NarrationReview.tsx | 37+++++++++++++++++++++++++++++++++----
Mumtool/components/projects/OnscreenSection.tsx | 8++++++++
Mumtool/components/projects/ProjectView.tsx | 4++++
Mumtool/components/projects/ReportProject.tsx | 16++++++++++++++++
Aumtool/components/projects/ReviewPage.tsx | 39+++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/StructureEditors.tsx | 28++++++++++++++++++++++++++--
Aumtool/components/projects/drafts.tsx | 233+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/drafts.test.mjs | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9 files changed, 507 insertions(+), 6 deletions(-)

diff --git a/umtool/components/projects/DraftsReview.tsx b/umtool/components/projects/DraftsReview.tsx @@ -0,0 +1,89 @@ +"use client"; + +import Link from "next/link"; +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={`/browse/${project}`} className="text-[var(--color-sel)] hover:underline"> + 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={`/browse/${project}/narration`} className="text-[11px] text-[var(--color-sel)] hover:underline"> + 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/NarrationReview.tsx b/umtool/components/projects/NarrationReview.tsx @@ -3,6 +3,8 @@ import { useEffect, useRef, useState } from "react"; import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; +import { MANIFEST_CHANGED } from "./timelineApi"; +import { DraftAlternatives, useDrafts, type DraftAct, type DraftsView } from "./drafts"; // The narration script of one cut, card by card (release 25, T5). // @@ -27,6 +29,8 @@ export type NarrationRow = { estimate: number; seconds: number | string | null; screen: { kicker: string | null; heading: string | null; sub: string | null; title: string | null; style: string | null }; + /** Who drafted these words (release 28); null: written by hand. */ + drafted: { task: string; model: string; at: string; iteration?: number; attempt: number } | null; state: "approved" | "rejected" | "edited" | "unreviewed"; verdict: "approved" | "rejected" | null; note: string; @@ -57,6 +61,17 @@ export default function NarrationReview({ project, initial, token: initialToken const [token, setToken] = useState(initialToken); const [ready, setReady] = useState(false); useEffect(() => setReady(true), []); + // The alternatives a draft task kept for a card whose words are the + // operator's (release 28); "Use this" rewrites the manifest, so re-read. + const drafts = useDrafts(project); + useEffect(() => { + const on = (e: Event) => { + if ((e as CustomEvent).detail?.project === project) void refresh(); + }; + window.addEventListener(MANIFEST_CHANGED, on); + return () => window.removeEventListener(MANIFEST_CHANGED, on); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [project]); const act = async (card: string, action: string, extra: Record<string, unknown> = {}) => { const r = await fetch("/api/report/narration", { @@ -88,18 +103,18 @@ export default function NarrationReview({ project, initial, token: initialToken ) : view.exists ? ( <> Verdicts in <code className="font-mono">{view.file}</code>: a build refuses any narrated card not approved on - its current words (<code className="font-mono">--narration-unreviewed</code> builds them anyway; never a - rejected one). + its current words — a drafted one, a final build (<code className="font-mono">--narration-unreviewed</code>{" "} + builds them anyway; never a rejected one). </> ) : ( <> Nothing judged yet. The first verdict writes <code className="font-mono">{view.file}</code>, and from then on a - build refuses any narrated card not approved. + build refuses any narrated card not approved (a drafted one: a final build, judged or not). </> )} </p> {view.rows.map((r) => ( - <NarrationCard key={r.id} project={project} row={r} ready={ready} act={act} refresh={refresh} /> + <NarrationCard key={r.id} project={project} row={r} ready={ready} act={act} refresh={refresh} drafts={drafts.view} draftAct={drafts.act} /> ))} </div> ); @@ -111,12 +126,16 @@ function NarrationCard({ ready, act, refresh, + drafts, + draftAct, }: { project: string; row: NarrationRow; ready: boolean; act: (card: string, action: string, extra?: Record<string, unknown>) => Promise<void>; refresh: () => Promise<NarrationView | null>; + drafts: DraftsView | null; + draftAct: DraftAct; }) { const [text, setText] = useState(r.text); const [note, setNote] = useState(r.note); @@ -192,6 +211,15 @@ function NarrationCard({ <span data-narration-state="" className={badgeVariants({ variant: STATE[r.state].tone, size: "sm" })}> {STATE[r.state].label} </span> + {r.drafted && ( + <span + data-narration-drafted={r.drafted.model} + className={badgeVariants({ variant: "info", size: "sm" })} + title={`drafted by ${r.drafted.task} on ${r.drafted.model}, ${r.drafted.at}`} + > + drafted by {r.drafted.model} + </span> + )} <span className="font-mono text-[11px] text-[var(--color-dim)]" data-narration-voice=""> {r.engine} · {r.voice} {r.speed !== 1 ? ` · ×${r.speed}` : ""} @@ -290,6 +318,7 @@ function NarrationCard({ <audio ref={audio} controls preload="none" src={audioSrc(project, r)} data-narration-audio="" className="h-8 w-full" /> )} {r.kept && <p className="text-[11px] text-[var(--color-dim)]">{r.kept.disclosure}</p>} + <DraftAlternatives address={`narrate/${r.id}/narration`} view={drafts} act={draftAct} /> {error && ( <p data-narration-error="" className="text-[11px] text-[var(--color-bad)]"> {error} diff --git a/umtool/components/projects/OnscreenSection.tsx b/umtool/components/projects/OnscreenSection.tsx @@ -4,6 +4,7 @@ import GeneratedBanner from "@/components/notes/GeneratedBanner"; import { TimedVideo } from "@/components/notes/TimedNotes"; import StructureEditors from "./StructureEditors"; import { MANIFEST_CHANGED } from "./timelineApi"; +import { DraftAlternatives, DraftBadge, announceDraftsChanged, useDrafts } from "./drafts"; import { announceNotesChanged, wroteNotes } from "@/components/notes/NotesProvider"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { badgeVariants } from "@/components/ui/badge"; @@ -835,6 +836,9 @@ export default function OnscreenSection({ // The switch as pressed, while its write is in flight: the box follows the // hand at once and falls back to the manifest's answer if the write fails. const [switching, setSwitching] = useState<boolean | null>(null); + // The drafts review (release 28): a drafted title's badge, and the + // alternatives kept for a title that is the operator's. + const review = useDrafts(project); // One token for the manifest, shared by both writers here: a settings save // moves it, and the table's next save must carry the moved one. A ref, as // in the clip bench, because two saves can be in flight before a render. @@ -1133,6 +1137,8 @@ export default function OnscreenSection({ return next; }); setNote(`saved ${Object.keys(saved).length} row${Object.keys(saved).length === 1 ? "" : "s"}`); + // An edited draft is the operator's now: the badges re-read. + announceDraftsChanged(project); }), [queued, dirtyIds, project, draftMap, rows], ); @@ -1415,6 +1421,8 @@ export default function OnscreenSection({ }} className={`${field} w-full ${over(shown) ? "border-[var(--color-dirty)]" : "border-[var(--color-line)]"}`} /> + <DraftBadge address={`onscreen/${row.id}/onscreen`} view={review.view} act={review.act} compact /> + <DraftAlternatives address={`onscreen/${row.id}/onscreen`} view={review.view} act={review.act} /> </td> <td className={`num px-1.5 py-1 text-right font-mono text-[11px] ${over(shown) ? "text-[var(--color-dirty)]" : "text-[var(--color-dim)]"}`} diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx @@ -8,6 +8,7 @@ import ClaimBenchPage from "./ClaimBenchPage"; import SweepProject from "./SweepProject"; import TakesPage from "./TakesPage"; import NarrationPage from "./NarrationPage"; +import ReviewPage from "./ReviewPage"; // --------------------------------------------------------------------------- // The one place a kind id is matched against a component. @@ -57,6 +58,9 @@ export default async function ProjectView({ // `/browse/<project>/narration` -- the narration script, card by card, // approved / edited / rejected before synthesis. if (rest.length === 1 && rest[0] === "narration") return <NarrationPage project={project} />; + // `/browse/<project>/review` -- every drafted field, approved / rejected + // before a final build, and the alternatives a draft task kept. + if (rest.length === 1 && rest[0] === "review") return <ReviewPage project={project} />; return notFound(); } case "sweep-report": { diff --git a/umtool/components/projects/ReportProject.tsx b/umtool/components/projects/ReportProject.tsx @@ -20,6 +20,8 @@ import { listSnapshots, readSnapshot } from "@/lib/report/snapshots.mjs"; import { listTakes } from "@/lib/report/takes.mjs"; import { podcastFor } from "@/lib/report/serve.mjs"; import { narrationsOf } from "umtool-report-to-video/narration"; +import { draftedFields } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; +import { readAlternatives } from "@/lib/report/drafts.mjs"; import DeliverSection from "./DeliverSection"; import FetchUnfetchedButton from "./FetchUnfetchedButton"; import OnscreenSection from "./OnscreenSection"; @@ -149,6 +151,9 @@ export default async function ReportProject({ const podcasts = new Map(await Promise.all(variants.map(async (v) => [v, await podcastOf(v)] as const))); const takes = await listTakes(project.dir); const narrated = narrationsOf(m).length; + // The drafts review (release 28): drafted fields, and alternatives kept. + const draftedCount = draftedFields(m).length; + const alternativesCount = (await readAlternatives(project.dir)).length; // Provenance splits by SHAPE: a scalar or a URL stays in the table; a long // string, or one with a newline, is prose the author wrote and reads as a @@ -261,6 +266,17 @@ export default async function ReportProject({ 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={`/browse/${project.id}/review`} + data-review-link={draftedCount} + className={buttonVariants({ size: "lg" })} + > + Review drafts — {draftedCount} + </Link> + )} {takes.exists && ( <Link href={`/browse/${project.id}/takes`} diff --git a/umtool/components/projects/ReviewPage.tsx b/umtool/components/projects/ReviewPage.tsx @@ -0,0 +1,39 @@ +import BrowseHeader from "@/components/BrowseHeader"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { manifestToken } from "@/lib/report/manifest.mjs"; +import { draftsView } from "@/lib/report/drafts.mjs"; +import type { ProjectRef } from "@/lib/project-types"; +import DraftsReview from "./DraftsReview"; +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 +// <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. +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 { counts } = view; + return ( + <div className="flex h-full flex-col"> + <BrowseHeader + crumbs={[ + { href: "/browse", label: "projects" }, + { href: `/browse/${project.id}`, 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> + ); +} diff --git a/umtool/components/projects/StructureEditors.tsx b/umtool/components/projects/StructureEditors.tsx @@ -5,6 +5,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { announceNotesChanged, wroteNotes } from "@/components/notes/NotesProvider"; import { buttonVariants } from "@/components/ui/button"; import { MANIFEST_CHANGED, announceManifestChanged, refusalOf, timelineOp } from "./timelineApi"; +import { DraftAlternatives, DraftBadge, useDrafts, type DraftAct, type DraftsView } from "./drafts"; // The parts of the cut that are lists, edited in place: each teaser's lines // and timing, the posts, and the fact-check's labels and colours. Every save @@ -34,6 +35,8 @@ export default function StructureEditors({ project }: { project: string }) { const [doc, setDoc] = useState<Doc | null>(null); const [error, setError] = useState<string | null>(null); const [busy, setBusy] = useState(false); + // The drafts review (release 28): a drafted teaser's badge and alternatives. + const drafts = useDrafts(project); const load = useCallback(async () => { const r = await fetch(`/api/report/timeline?project=${encodeURIComponent(project)}`, { cache: "no-store" }); @@ -79,7 +82,14 @@ export default function StructureEditors({ project }: { project: string }) { </p> )} {doc.teasers.map((t) => ( - <TeaserEditor key={`${t.id}@${t.at}`} teaser={t} busy={busy} save={(patch) => run("teaser", { id: t.id, at: t.at, patch })} /> + <TeaserEditor + key={`${t.id}@${t.at}`} + teaser={t} + busy={busy} + save={(patch) => run("teaser", { id: t.id, at: t.at, patch })} + drafts={drafts.view} + act={drafts.act} + /> ))} <PostsEditor posts={doc.posts} busy={busy} save={(post) => run("post", { post })} remove={(id) => run("post-remove", { id })} /> {doc.deckOn && <FactcheckEditor doc={doc} busy={busy} save={(factcheck) => run("factcheck", { factcheck })} />} @@ -87,7 +97,19 @@ export default function StructureEditors({ project }: { project: string }) { ); } -function TeaserEditor({ teaser: t, busy, save }: { teaser: Teaser; busy: boolean; save: (patch: Record<string, unknown>) => Promise<boolean> }) { +function TeaserEditor({ + teaser: t, + busy, + save, + drafts, + act, +}: { + teaser: Teaser; + busy: boolean; + save: (patch: Record<string, unknown>) => Promise<boolean>; + drafts: DraftsView | null; + act: DraftAct; +}) { // Plain lines edit as one per row; a teaser whose lines carry settings // (break, role, replace…) edits as the JSON it is, so nothing is dropped. const plain = t.lines.every((l) => typeof l === "string"); @@ -147,6 +169,8 @@ function TeaserEditor({ teaser: t, busy, save }: { teaser: Teaser; busy: boolean </button> {local && <span className="text-[var(--color-bad)]">{local}</span>} </div> + <DraftBadge address={`teaser/${t.id}/lines`} view={drafts} act={act} /> + <DraftAlternatives address={`teaser/${t.id}/lines`} view={drafts} act={act} /> </div> ); } diff --git a/umtool/components/projects/drafts.tsx b/umtool/components/projects/drafts.tsx @@ -0,0 +1,233 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; +import { buttonVariants } from "@/components/ui/button"; +import { MANIFEST_CHANGED, announceManifestChanged } from "./timelineApi"; + +// The drafts review on the page (release 28, M0): who drafted a field, its +// review state, Approve / Reject (with a note), and the alternatives a draft +// task kept for a field it was not allowed to replace, each with "Use this". +// +// One view per section (`useDrafts`), read from /api/report/drafts and +// re-read after any write to the manifest (MANIFEST_CHANGED) or the review +// (DRAFTS_CHANGED), so a badge in the On-screen table and one on the review +// page agree. The server is the word on every state: each action answers with +// the whole view. + +export type Provenance = { task: string; model: string; at: string; iteration?: number; attempt: number }; +export type DraftRow = { + address: string; + entry: string | null; + field: string; + label: string; + drafted: Provenance | null; + text: string; + state: "approved" | "rejected" | "edited" | "unreviewed"; + verdict: "approved" | "rejected" | null; + note: string; + judgedText: string; + judgedAt: string; +}; +export type DraftAlternative = { + id: string; + file: string; + address: string; + entry: string | null; + field: string; + label: string; + text: string; + value: unknown; + provenance: Provenance | null; + reason: string; + inUse: boolean; +}; +export type DraftsView = { + file: string; + exists: boolean; + error: string | null; + rows: DraftRow[]; + alternatives: DraftAlternative[]; + counts: Record<DraftRow["state"], number>; + drafted: number; + gate: { errors: string[]; warnings: string[] }; + token?: string | null; +}; + +export const DRAFTS_CHANGED = "umtool:drafts-changed"; +export function announceDraftsChanged(project: string) { + window.dispatchEvent(new CustomEvent(DRAFTS_CHANGED, { detail: { project } })); +} + +export type DraftAct = (action: string, extra?: Record<string, unknown>) => Promise<void>; + +/** The project's drafts view, kept fresh; `act` runs one action and adopts the answer. */ +export function useDrafts(project: string, initial: DraftsView | null = null): { view: DraftsView | null; act: DraftAct; reload: () => Promise<void> } { + const [view, setView] = useState<DraftsView | null>(initial); + const reload = useCallback(async () => { + const r = await fetch(`/api/report/drafts?project=${encodeURIComponent(project)}`, { cache: "no-store" }); + if (r.ok) setView((await r.json()) as DraftsView); + }, [project]); + useEffect(() => { + if (!initial) void reload(); + const on = (e: Event) => { + if ((e as CustomEvent).detail?.project === project) void reload(); + }; + window.addEventListener(MANIFEST_CHANGED, on); + window.addEventListener(DRAFTS_CHANGED, on); + return () => { + window.removeEventListener(MANIFEST_CHANGED, on); + window.removeEventListener(DRAFTS_CHANGED, on); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [project, reload]); + const act = useCallback<DraftAct>( + async (action, extra = {}) => { + const r = await fetch("/api/report/drafts", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, action, ...extra }), + cache: "no-store", + }); + const j = (await r.json().catch(() => ({ error: `HTTP ${r.status}` }))) as DraftsView & { ok?: boolean; error?: string; errors?: string[] }; + if (!r.ok || !j.ok) throw new Error(j.errors?.length ? j.errors.join("; ") : (j.error ?? `HTTP ${r.status}`)); + setView(j); + // A taken alternative changed the manifest: every editor re-reads it. + if (action === "use") announceManifestChanged(project); + else announceDraftsChanged(project); + }, + [project], + ); + return { view, act, reload }; +} + +const STATE: Record<DraftRow["state"], { label: string; tone: BadgeVariants["variant"] }> = { + approved: { label: "approved", tone: "meter" }, + rejected: { label: "rejected", tone: "blocking" }, + edited: { label: "changed since approved", tone: "on" }, + unreviewed: { label: "not reviewed", tone: "open" }, +}; + +/** + * "drafted by <model>", its review state, and Approve / Reject (+ note) for the + * field at `address`. Nothing when the field is not drafted. + */ +export function DraftBadge({ address, view, act, compact = false }: { address: string; view: DraftsView | null; act: DraftAct; compact?: boolean }) { + const row = view?.rows.find((r) => r.address === address && r.drafted) ?? null; + const [note, setNote] = useState(row?.note ?? ""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + const [ready, setReady] = useState(false); + useEffect(() => setReady(true), []); + useEffect(() => setNote(row?.note ?? ""), [row?.note]); + if (!row || !row.drafted) return null; + const run = async (action: string, extra: Record<string, unknown> = {}) => { + setBusy(true); + setError(null); + try { + await act(action, { address, ...extra }); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + const s = STATE[row.state]; + return ( + <div data-draft-badge={address} data-state={row.state} className={`flex flex-wrap items-center gap-1 ${compact ? "mt-0.5" : ""} text-[11px]`}> + <span + data-draft-by="" + className={badgeVariants({ variant: "info", size: "sm" })} + title={`drafted by ${row.drafted.task} on ${row.drafted.model}, ${row.drafted.at}${row.drafted.iteration ? ` (i${row.drafted.iteration})` : ""}, attempt ${row.drafted.attempt}`} + > + drafted by {row.drafted.model} + </span> + <span data-draft-state="" className={badgeVariants({ variant: s.tone, size: "sm" })}> + {s.label} + </span> + <button + type="button" + data-draft-action="approve" + aria-pressed={row.state === "approved"} + disabled={!ready || busy} + title="approve this draft as it is now" + className={buttonVariants({ variant: row.state === "approved" ? "primary" : "outline", size: "sm" })} + onClick={() => void run(row.state === "approved" ? "clear" : "approve", row.state === "approved" ? {} : { note })} + > + {row.state === "approved" ? "Approved" : "Approve"} + </button> + <button + type="button" + data-draft-action="reject" + aria-pressed={row.state === "rejected"} + disabled={!ready || 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> + <input + value={note} + onChange={(e) => setNote(e.target.value)} + onBlur={() => { + if (note.trim() !== row.note && row.verdict) void run("note", { note }); + }} + disabled={!ready || busy} + placeholder="note (a rejection needs one)" + aria-label={`note on the draft of ${address}`} + data-draft-note="" + maxLength={2000} + className="min-w-0 flex-1 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[11px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]" + /> + {error && ( + <span data-draft-error="" className="basis-full text-[var(--color-bad)]"> + {error} + </span> + )} + </div> + ); +} + +/** The alternatives kept for the field at `address`, each with "Use this". */ +export function DraftAlternatives({ address, view, act }: { address: string; view: DraftsView | null; act: DraftAct }) { + const alts = (view?.alternatives ?? []).filter((a) => a.address === address && !a.inUse); + const [busy, setBusy] = useState<string | null>(null); + const [error, setError] = useState<string | null>(null); + const [ready, setReady] = useState(false); + useEffect(() => setReady(true), []); + if (!alts.length) return null; + return ( + <div data-draft-alternatives={address} className="mt-0.5 space-y-0.5 text-[11px]"> + {alts.map((a) => ( + <div key={a.id} data-draft-alternative={a.id} className="flex flex-wrap items-center gap-1.5 text-[var(--color-dim)]"> + <span className="micro">alternative{a.provenance ? ` · ${a.provenance.model}` : ""}</span> + <span data-draft-alternative-text="" className="italic text-[var(--color-text)]"> + {a.text || "(empty)"} + </span> + <button + type="button" + data-draft-use="" + disabled={!ready || busy !== null} + title="write this instead of what the field holds, as your own edit" + className={buttonVariants({ size: "sm" })} + onClick={() => { + setBusy(a.id); + setError(null); + act("use", { alternative: a.id }) + .catch((e) => setError(e instanceof Error ? e.message : String(e))) + .finally(() => setBusy(null)); + }} + > + {busy === a.id ? "writing…" : "Use this"} + </button> + </div> + ))} + {error && ( + <p data-draft-error="" className="text-[var(--color-bad)]"> + {error} + </p> + )} + </div> + ); +} diff --git a/umtool/lib/report/drafts.test.mjs b/umtool/lib/report/drafts.test.mjs @@ -0,0 +1,59 @@ +// The drafts review's umtool view (release 28, M0): the drafted rows, the +// alternatives read from every `<task>-draft.json`, "in use" once taken, and +// what a final build would say. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +import { draftsView, readAlternatives } from "./drafts.mjs"; +import { MANIFEST_NAME, writeDraftedField } from "./manifest.mjs"; +import { setDraftReview } from "umtool-report-to-video/drafts-review"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const full = () => JSON.parse(readFileSync(path.join(HERE, "../../../common/testing/draft/manifests/full.video.manifest.json"), "utf8")); +const P = (task) => ({ task, model: "qwen3:8b", at: "2026-10-13T10:00:00.000Z", iteration: 1, attempt: 1 }); + +test("the view: drafted rows, alternatives from the draft files, in use once taken, the final gate", async (t) => { + const dir = mkdtempSync(path.join(tmpdir(), "umtool-drafts-view-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const m = full(); + m.timeline.find((e) => e.id === "c02").onscreen = { title: "The oven" }; + m.timeline.find((e) => e.id === "c02").drafted = { onscreen: P("onscreen") }; + writeFileSync(path.join(dir, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n"); + writeFileSync( + path.join(dir, "onscreen-draft.json"), + JSON.stringify({ task: "onscreen", alternatives: [{ target: { entry: "c01", field: "onscreen" }, value: { title: "Not for sale?" }, provenance: P("onscreen"), reason: "operator" }] }), + ); + writeFileSync(path.join(dir, "broken-draft.json"), "{ nope"); + writeFileSync(path.join(dir, "notes.json"), JSON.stringify({ alternatives: [{ target: { field: "onscreen" }, value: 1 }] })); + const alts = await readAlternatives(dir); + assert.deepEqual(alts.map((a) => [a.id, a.address]), [["onscreen-draft.json#0", "onscreen/c01/onscreen"]], "only <task>-draft.json files, and only those that parse"); + + const v = await draftsView(dir, m); + assert.equal(v.drafted, 1); + // The rows: c02's drafted text, and the contest card's hand-written narration. + assert.deepEqual(v.rows.map((r) => [r.address, r.drafted?.model ?? null, r.state]), [ + ["onscreen/c02/onscreen", "qwen3:8b", "unreviewed"], + ["narrate/the-contest/narration", null, "unreviewed"], + ]); + assert.equal(v.alternatives[0].text, "Not for sale?"); + assert.equal(v.alternatives[0].inUse, false); + assert.equal(v.gate.errors.length, 1); + assert.match(v.gate.errors[0], /timeline c02: its on-screen text \(drafted by qwen3:8b\) is not approved/); + + // Approved: the gate passes. + await setDraftReview(dir, "onscreen/c02/onscreen", { verdict: "approved", key: v.rows[0].key, text: v.rows[0].text }); + const ok = await draftsView(dir, m); + assert.deepEqual(ok.gate.errors, []); + assert.equal(ok.counts.approved, 1); + + // Use this: the alternative is the field's value now, and in use. + await writeDraftedField(dir, { entry: "c01", field: "onscreen", value: { title: "Not for sale?" } }); + const after = JSON.parse(readFileSync(path.join(dir, MANIFEST_NAME), "utf8")); + assert.equal((await draftsView(dir, after)).alternatives[0].inUse, true); +});