Archilyzer · Source

archilyzer

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

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

umtool: one bench shell for the clip, claim, narration and takes benches (P4b)

components/projects/bench/BenchShell.tsx: the top bar (the mark, ← the
piece, the bench, N of M, ‹ prev / next ›, the keys), the work column, the
verdict bar (one question, the consequence, the actions named by result) and
the reader on the right. The clip bench's transcript is its reader pane, the
cited cue lit, the cite thread and Copy citation; its verdict bar asks to
extend a clip that ends mid-sentence (what it would cover) before the walk's
yes/no. The claim bench's context is its reader (j/k, the cited cue lit) and
Save ruling its verdict bar. Narration and takes ask about the card or take in
hand, with keys. ReaderPane gains bodyProps, bare, onLight, global and a cue's
attrs (additive). lib/report/draft-provenance.mjs: where a drafted field came
from (attempts, the chosen one, the rules refused attempts broke).

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

Diffstat:
Mumtool/components/projects/ClaimBench.tsx | 148+++++++++++++++++++++++++++++++++++++++++++++----------------------------------
Mumtool/components/projects/ClaimBenchPage.tsx | 39+++++++++++++++++++++------------------
Mumtool/components/projects/ClipBench.tsx | 450+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
Mumtool/components/projects/ClipBenchPage.tsx | 50++++++++++++++++++++++++++++++--------------------
Mumtool/components/projects/NarrationPage.tsx | 53+++++++++++++++++++++++++++++------------------------
Mumtool/components/projects/NarrationReview.tsx | 92++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/components/projects/TakesBench.tsx | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/TakesPage.tsx | 78++++++++++++++++++++++++++++++++++++++++++------------------------------------
Aumtool/components/projects/bench/BenchShell.tsx | 235+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/bench/CopyCitation.tsx | 39+++++++++++++++++++++++++++++++++++++++
Mumtool/components/ui/reader-pane.tsx | 34++++++++++++++++++++++++++++++----
Aumtool/lib/report/draft-provenance.mjs | 119+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/draft-provenance.test.mjs | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
13 files changed, 1147 insertions(+), 351 deletions(-)

diff --git a/umtool/components/projects/ClaimBench.tsx b/umtool/components/projects/ClaimBench.tsx @@ -2,6 +2,11 @@ import Link from "next/link"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { ReaderPane } from "@/components/ui/reader-pane"; +import { citationText } from "@/lib/research/facets.mjs"; +import { BenchBody, VerdictBar } from "./bench/BenchShell"; +import CopyCitation from "./bench/CopyCitation"; import { POPULATIONS, SCOPES, @@ -270,27 +275,87 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) { window.location.reload(); }, [data.project, claim.id, data.pad]); - const paragraph = useMemo( - () => - cues.map((c, i) => ( - <span - key={`${c.start}-${i}`} - data-cited={c.cited ? "1" : undefined} - onClick={() => seekTo(c.start)} - className={ - "cursor-pointer " + - (c.cited - ? "bg-[color-mix(in_srgb,var(--reader-signal)_14%,transparent)] text-reader-ink" - : "text-reader-2 hover:text-reader-ink") - } - > - {c.text}{" "} - </span> - )), - [cues, seekTo], + // ---- the bench shell's verdict bar and reader (P4b) ------------------------ + const missing = [ + !scope && "scope", + !confidence && "scope confidence", + !population && "population", + !valueKind && "value kind", + !basis.trim() && "scope basis", + ].filter(Boolean) as string[]; + const verdictBar = ( + <VerdictBar + data-verdict-for={claim.id} + question={<>Save the ruling on {claim.id}?</>} + consequence={ + missing.length + ? `Still missing ${missing.join(", ")} — it stays blocking.` + : dirty + ? "Every field is set: it leaves the blocking list." + : "Nothing changed since it was saved." + } + > + <button + type="button" + data-testid="claim-save" + disabled={!dirty || !!busy || !roles.ok} + onClick={() => void save()} + className={buttonVariants({ variant: "go", size: "md" })} + > + {busy ?? "Save ruling"} + </button> + {data.next && ( + <Link href={`/projects/${data.project}/claim/${data.next}`} className={buttonVariants({ variant: "quiet", size: "md" })}> + Next claim ({data.next}) + </Link> + )} + </VerdictBar> + ); + const firstCited = cues.findIndex((c) => c.cited); + const reader = ( + <ReaderPane + className="h-full" + source={data.source?.title ?? claim.video ?? claim.id} + byline={[ + claim.channel, + data.source?.uploadDate + ? `${data.source.uploadDate.slice(0, 4)}-${data.source.uploadDate.slice(4, 6)}-${data.source.uploadDate.slice(6, 8)}` + : claim.date, + <span key="t" className="font-mono"> + transcript{data.source?.duration ? ` · ${hms(data.source.duration)}` : ""} + </span>, + ]} + cite={at != null && data.source?.duration ? { at, duration: data.source.duration } : undefined} + note={`±${data.pad}s of context · ${hms(view.from)}–${hms(view.to)}${at != null ? ` · cited at ${hms(at)}` : ""}`} + label="Context" + global + bodyProps={{ "data-testid": "claim-context" }} + cues={ + data.noCues + ? undefined + : cues.map((c, i) => ({ + t: c.start, + text: c.text, + lit: i === firstCited, + attrs: { "data-cited": c.cited ? "1" : undefined }, + })) + } + onLight={(d) => { + const c = cues[d.index]; + if (c && d.index !== firstCited) seekTo(c.start); + }} + footer={claim.quote ? <CopyCitation text={citationText({ quote: claim.quote, title: data.source?.title ?? claim.video ?? claim.id, clock: at != null ? hms(at) : undefined, url: data.source?.webpageUrl ?? undefined })} /> : undefined} + fine={[claim.label, claim.src].filter(Boolean).join(" · ") || undefined} + > + <p className="text-[12px] text-reader-dim"> + no transcript.cues.json for {claim.channel}/{claim.video} — on Rumble, check the directory is the URL slug and + not the site id + </p> + </ReaderPane> ); return ( + <BenchBody verdict={verdictBar} reader={reader}> <div className="space-y-3" data-claim={claim.id}> <div className="flex items-baseline gap-3"> <div className="font-mono text-[13px] text-[var(--color-fg)]">{claim.id}</div> @@ -298,17 +363,6 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) { <div className="text-[13px] text-[var(--color-meter)]"> {claim.display ?? (claim.value == null ? "—" : String(claim.value))} </div> - <div className="flex-1" /> - {data.prev ? ( - <Link className="text-[11px] ink-link" href={`/projects/${data.project}/claim/${data.prev}`}> - ← {data.prev} - </Link> - ) : null} - {data.next ? ( - <Link className="text-[11px] ink-link" href={`/projects/${data.project}/claim/${data.next}`}> - {data.next} → - </Link> - ) : null} </div> <div className="grid gap-3 lg:grid-cols-[minmax(0,1fr)_360px]"> @@ -337,27 +391,6 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) { </div> )} - {/* The source's words, on the READER (app/globals.css). */} - <div className="reader rounded-[2px] px-4 py-3"> - <div className="micro mb-2"> - ±{data.pad}s of context · {hms(view.from)}–{hms(view.to)} - {at != null ? ` · cited at ${hms(at)}` : ""} - </div> - {data.noCues ? ( - <div className="text-[12px] text-reader-dim"> - no transcript.cues.json for {claim.channel}/{claim.video} — on Rumble, check the - directory is the URL slug and not the site id - </div> - ) : ( - <p - data-testid="claim-context" - className="max-h-[320px] overflow-y-auto font-serif text-[15px] leading-relaxed" - > - {paragraph} - </p> - )} - </div> - <div className="reader rounded-[2px] px-4 py-3 text-[12px]"> <div className="micro mb-1">as recorded</div> <div className="font-serif text-[16px] leading-snug text-reader-ink">“{claim.quote}”</div> @@ -460,23 +493,10 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) { </div> ) : null} - <div className="flex items-center gap-2"> - <button - type="button" - data-testid="claim-save" - disabled={!dirty || !!busy || !roles.ok} - onClick={() => void save()} - className="rounded border border-[var(--color-sel)] px-3 py-1 text-[11px] text-[var(--color-sel)] disabled:opacity-40" - > - {busy ?? "save ruling"} - </button> - {!complete ? ( - <span className="text-[10px] text-[var(--color-dim)]">all six fields, or it stays blocking</span> - ) : null} - </div> {note ? <div data-testid="claim-note" className="text-[11px] text-[var(--color-dim)]">{note}</div> : null} </div> </div> </div> + </BenchBody> ); } diff --git a/umtool/components/projects/ClaimBenchPage.tsx b/umtool/components/projects/ClaimBenchPage.tsx @@ -1,6 +1,6 @@ import { notFound } from "next/navigation"; -import AppShell from "@/components/shell/AppShell"; -import { browseHref } from "@/lib/hrefs"; +import { browseHref, claimBenchHref } from "@/lib/hrefs"; +import { BenchFrame, BenchTop } from "./bench/BenchShell"; import ClaimBench, { type ClaimBenchData } from "./ClaimBench"; import { manifestToken } from "@/lib/report/manifest.mjs"; import { readClaimDetail, readManifest } from "@/lib/projects/report.mjs"; @@ -87,22 +87,25 @@ export default async function ClaimBenchPage({ // The piece this view belongs to: the article's when an article claims the project (P4a-2). const back = await pieceHrefOfProject(project.id, { tab: "cut" }); + const href = (id: string) => claimBenchHref(project.id, id); return ( - <div className="flex h-full flex-col"> - {/* A bench: the rail collapses and the work takes the width. */} - <AppShell - active="browse" - rail="collapsed" - crumbs={[ - { href: browseHref(), label: "projects" }, - { href: back, label: project.name }, - { label: claimId }, - ]} - note={`claim ${i + 1} of ${ledger.length} · ${outstanding} unadjudicated`} - /> - <main className="deck-main flex-1 p-4"> - <ClaimBench data={data} /> - </main> - </div> + <BenchFrame + kind="claim" + top={ + <BenchTop + trail={[{ href: browseHref(), label: "projects" }]} + back={{ href: back, label: project.name }} + kind="Claim bench" + here={claimId} + pos={{ index: i + 1, total: ledger.length }} + prev={data.prev ? { href: href(data.prev), label: data.prev } : null} + next={data.next ? { href: href(data.next), label: data.next } : null} + keys={[{ keys: ["j", "k"], label: "cue" }]} + note={`${outstanding} unadjudicated`} + /> + } + > + <ClaimBench data={data} /> + </BenchFrame> ); } diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -9,6 +9,10 @@ import { useRouter } from "next/navigation"; import Waveform, { type Peaks } from "@/components/Waveform"; import { badgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; +import { ReaderPane, paperButtonVariants } from "@/components/ui/reader-pane"; +import { citationText } from "@/lib/research/facets.mjs"; +import { BenchBody, VerdictBar } from "./bench/BenchShell"; +import CopyCitation from "./bench/CopyCitation"; // The renderer's own line, imported rather than re-written. A preview that // disagrees with the header by a character is worth less than no preview: you // would only find out twenty minutes into a build. @@ -1843,6 +1847,268 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { const overlayT = deckSeg ? deckSeg.start + Math.min(segT ?? deckSeg.duration / 4, deckSeg.duration) : 0; const showOverlay = data.deckOn && !!deckPreview && renderedOpen; + // ---- the verdict bar: ONE question, its consequence, the actions ---------- + // + // The bench shell's foot (components/projects/bench/BenchShell.tsx). A clip + // that ends mid-sentence asks the one question that decides its window -- + // extend to the sentence's end, and what that would cover -- before the + // walk's own question; otherwise the walk's: is this clip what the report + // says it is. `y` and `x` answer the walk's either way. + const sentenceEnd = (() => { + if (!midSentence || !endCue) return null; + const pool = [...(peek.length ? peek : cues)].filter((c) => c.start >= endCue.start - 0.02).sort((x, y) => x.start - y.start); + return pool.find((c) => c.endsSentence)?.end ?? null; + })(); + const covered = + sentenceEnd == null ? [] : siblings.filter((sb) => sb.start < sentenceEnd - 0.02 && sb.end > sel.to + 0.02); + const coveredWhole = covered.filter((sb) => sb.start >= sel.to - 0.02 && sb.end <= sentenceEnd! + 0.02); + const pastCache = sentenceEnd != null && sentenceEnd > clampTo + 0.02; + const extendTo = (t: number) => { + const to = round2(t); + void save({ start: round2(sel.from), end: to }).then((ok) => { + if (ok) setNote(`saved — ${clip.id} now ends at ${hms(to)}, the end of the sentence`); + }); + }; + const verdictBar = ( + <VerdictBar + data-verdict-for={clip.id} + question={ + sentenceEnd != null ? ( + <>Extend {clip.id} to the end of the sentence?</> + ) : ( + <>Is {clip.id} what the report says it is?</> + ) + } + consequence={ + sentenceEnd != null + ? `It would end at ${hms(sentenceEnd)} (+${(sentenceEnd - sel.to).toFixed(1)} s)` + + (coveredWhole.length + ? `, covering all of ${coveredWhole.map((sb) => sb.id).join(", ")}` + : covered.length + ? `, overlapping ${covered.map((sb) => sb.id).join(", ")}` + : "") + + (pastCache ? " — past what is fetched." : ".") + : needNote && !draft.correction.trim() + ? "The note is the answer — type it, then blur or Enter." + : verdict === "unreviewed" + ? data.next + ? `Confirming saves it${windowMoved || muteMoved ? " with the window you moved" : ""} and opens ${data.next}.` + : `Confirming saves it${windowMoved || muteMoved ? " with the window you moved" : ""}; it is the walk's last.` + : undefined + } + > + {sentenceEnd != null && + (pastCache ? ( + <button + type="button" + data-verdict-extend="fetch" + className={buttonVariants({ variant: "go", size: "md" })} + disabled={!!busy || atMaxPad} + onClick={() => void fetchMore(padsForCue({ start: endCue!.start, end: sentenceEnd, text: "", endsSentence: true }))} + > + Fetch to {hms(sentenceEnd)} + </button> + ) : ( + <button + type="button" + data-verdict-extend={sentenceEnd} + className={buttonVariants({ variant: "go", size: "md" })} + disabled={!!busy} + onClick={() => extendTo(sentenceEnd)} + > + Extend to {hms(sentenceEnd)} + </button> + ))} + {sentenceEnd != null && ( + <button + type="button" + data-verdict-keep="" + className={buttonVariants({ size: "md" })} + disabled={!!busy} + title="lockEnd: you meant to cut here; the walk stops asking" + onClick={() => void save({ lockEnd: true })} + > + Keep the cut here + </button> + )} + <button + type="button" + data-verdict-yes="" + className={buttonVariants({ variant: sentenceEnd != null ? "outline" : "go", size: "md" })} + disabled={!!busy} + onClick={() => void confirmClip()} + > + Yes, confirmed <kbd>y</kbd> + </button> + <button type="button" data-verdict-no="" className={buttonVariants({ size: "md" })} onClick={rejectClip}> + No, note what is wrong <kbd>x</kbd> + </button> + <span + data-verdict-state="" + className={ + verdict === "confirmed" + ? "text-[12px] text-[var(--color-good)]" + : verdict === "incorrect" + ? "text-[12px] text-[var(--color-dirty)]" + : "text-[12px] text-[var(--color-dim)]" + } + > + {verdictLabel(clip)} + </span> + </VerdictBar> + ); + + // ---- the reader: the source's words, the cited cue lit ------------------- + // + // The transcript, as something you can actually read: the export site's + // transcript viewer's layout (a monospace m:ss column, the text beside it, + // the line playing lit), now the bench shell's reader pane -- the source on + // the reader surface, its cite thread, Copy citation. A cue in the cut + // already is tagged with its clip; a dimmed one is not fetched (click to + // fetch it). The cited cue is lit until something plays. + const citeAt = clip.cite ?? clip.start; + const citedCue = railCues.find((c) => citeAt >= c.start - 0.02 && citeAt < c.end) ?? null; + const citation = citationText({ + quote: draft.quote.trim() || undefined, + title: data.sourceTitle || clip.title || clip.video, + clock: clock(citeAt), + url: clip.citeUrl ?? undefined, + }); + const readerPane = ( + <ReaderPane + className="h-full" + source={data.sourceTitle || clip.title || clip.video} + byline={[ + data.sourceChannel || clip.channel, + clip.date || (data.uploadDate ? `${data.uploadDate.slice(0, 4)}-${data.uploadDate.slice(4, 6)}-${data.uploadDate.slice(6, 8)}` : null), + <span key="t" className="font-mono"> + transcript{data.sourceDuration ? ` · ${clock(data.sourceDuration)}` : ""} + </span>, + ]} + cite={data.sourceDuration ? { at: citeAt, duration: data.sourceDuration } : undefined} + bare + bodyProps={{ ref: transcriptBox, "data-transcript": "", className: "relative py-0 pr-0" }} + footer={ + <> + <CopyCitation text={citation} /> + <button + type="button" + data-reader-play="" + className={paperButtonVariants()} + disabled={!cached} + onClick={() => void play(sel.from, sel.to)} + > + Play clip + </button> + </> + } + fine={`cites ${clock(citeAt)}${cached ? ` · clip window cached in ${cached.name}` : " · not fetched"}`} + > + <ul> + {railCues.map((c, i) => { + const outside = c.start < view.from - 0.02 || c.end > view.to + 0.02; + const prev = railCues[i - 1]; + const prevOutside = prev + ? prev.start < view.from - 0.02 || prev.end > view.to + 0.02 + : outside; + // The cache edge, drawn once, where the material stops being + // on disk. Reading past it is free; playing past it is not. + const rule = i > 0 && prevOutside !== outside; + const inSel = c.end > sel.from && c.start < sel.to; + const playing = playhead != null && playhead >= c.start && playhead < c.end; + // The cited cue is the lit line until something plays; then the head follows the player. + const lit = playing || (playhead == null && c === citedCue); + const owner = siblingAt(c); + return ( + <li key={`t-${c.start}-${c.end}`}> + {rule && ( + <div + data-cache-rule={outside ? "end" : "start"} + className="flex items-center gap-2 border-t border-dashed border-reader-2 px-2 py-0.5 text-[10px] uppercase tracking-wider text-reader-dim" + > + {outside ? "not fetched — reading only" : "cached from here"} + </div> + )} + <button + type="button" + data-tcue={c.start} + data-peek={outside ? "1" : "0"} + data-in-sibling={owner ? owner.id : ""} + data-cited={c === citedCue ? "1" : undefined} + data-lit={lit ? "" : undefined} + title={ + outside + ? `not fetched — click to fetch to ${padLabelForCue(c)}` + : "click to play from here" + } + onClick={() => { + if (outside) { + if (!atMaxPad) void fetchMore(padsForCue(c)); + return; + } + void play(c.start, Math.min(c.end + 4, view.to)); + }} + className={`flex w-full items-baseline gap-3 px-2.5 py-[3px] text-left hover:bg-[color-mix(in_srgb,var(--reader-signal)_6%,transparent)] ${ + inSel ? "bg-[color-mix(in_srgb,var(--reader-signal)_11%,transparent)]" : "" + } ${lit ? "border-l-[3px] border-reader-signal" : "border-l-[3px] border-transparent"}`} + > + <span + className={`num w-10 shrink-0 font-mono text-[10.5px] ${ + lit ? "font-semibold text-reader-signal" : "text-reader-dim" + }`} + > + {clock(c.start)} + </span> + <span + className={`min-w-0 font-serif text-[15px] leading-snug ${ + outside ? "text-reader-dim opacity-70" : inSel || lit ? "text-reader-ink" : "text-reader-2" + }`} + > + {owner && ( + <span + className="mr-1.5 rounded-[2px] border border-reader-2 px-1 font-mono text-[10px] text-reader-ink" + title={`already in the cut as ${owner.id} (${owner.where})`} + > + {owner.id} + </span> + )} + {c.endsSentence && ( + <span className="mr-1 font-mono text-[11px] text-reader-dim" aria-hidden> + ¶ + </span> + )} + {c.text} + </span> + </button> + </li> + ); + })} + </ul> + + {/* ---- the pane's own footer ---- + The controls that act on this pane live in it, stuck to the + bottom of its scrollport: they cost the pane a line and the + left column nothing, and "peek further" ends up beside the + dimmed lines it widens. Opaque, because it sits over text. */} + <div className="micro sticky bottom-0 z-10 flex flex-wrap items-center gap-2 border-t border-reader-seam bg-reader px-2.5 py-1"> + <span>click a line to play it</span> + {peek.length > 0 && ( + <> + <span>· dimmed lines are not fetched — click to fetch</span> + <button + type="button" + data-peek-further="" + className="ml-auto text-reader-signal hover:underline" + onClick={() => setPeekPad((n) => n + PEEK_STEP)} + > + peek further (±{peekPad + PEEK_STEP} s) + </button> + </> + )} + </div> + </ReaderPane> + ); + return ( // ONE SCREEN, at a desk. // @@ -1854,6 +2120,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { // scrolls, and what does not earn its height is folded rather than cut. // Below lg it is a single scrolling column -- a phone cannot hold this and // pretending otherwise would cost the desk case something. + <BenchBody verdict={verdictBar} reader={readerPane} workClassName="lg:overflow-hidden"> <div data-bench={clip.id} data-verdict={verdict} @@ -1862,10 +2129,6 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { <GeneratedBanner generatedBy={data.generatedBy} /> {/* ---- where you are, where you can go, and what will be burned in ---- */} <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px]"> - <span className="num font-mono text-[var(--color-text)]"> - clip {data.index} of {data.total} ·{" "} - <span className="text-[var(--color-sel)]">{clip.id}</span> - </span> <span className="micro" data-review-progress=""> {reviewed} reviewed </span> @@ -1879,31 +2142,6 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { not fetched yet </span> )} - {data.prev ? ( - <Link - data-clip-nav="prev" - href={`/projects/${data.project}/clip/${data.prev}`} - className="ink-link" - > - ← {data.prev} - </Link> - ) : ( - <span className="text-[var(--color-dim)]">← first</span> - )} - {data.next ? ( - <Link - data-clip-nav="next" - href={`/projects/${data.project}/clip/${data.next}`} - className="ink-link" - > - {data.next} → - </Link> - ) : ( - <span className="text-[var(--color-dim)]">last →</span> - )} - <span className="micro"> - <kbd>p</kbd> <kbd>n</kbd> walk - </span> {/* The renderer's own line, live. It used to sit four hundred pixels down the page; it is the one string this bench exists to get right, so it heads the screen. */} @@ -2426,120 +2664,6 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { ); })} </div> - {/* ---- THE TRANSCRIPT, as something you can actually read ---- - The rail is a timeline: it squeezes every cue into a column a few - characters wide, which is right for dragging an edge against and - useless for reading. The words are why anybody peeks ahead, so - they also run here in reading order -- the export site's - transcript viewer's layout (a monospace m:ss column, the text - beside it, the active line lit), because somebody reading a - transcript in this repo should not have to learn a second one. */} - <div - data-transcript="" - ref={transcriptBox} - // On the READER: these are the source's words (app/globals.css). - className="reader relative flex h-48 min-h-0 flex-col overflow-y-auto rounded-[2px] lg:h-auto lg:flex-[2_1_0%]" - > - <ul> - {railCues.map((c, i) => { - const outside = c.start < view.from - 0.02 || c.end > view.to + 0.02; - const prev = railCues[i - 1]; - const prevOutside = prev - ? prev.start < view.from - 0.02 || prev.end > view.to + 0.02 - : outside; - // The cache edge, drawn once, where the material stops being - // on disk. Reading past it is free; playing past it is not. - const rule = i > 0 && prevOutside !== outside; - const inSel = c.end > sel.from && c.start < sel.to; - const playing = playhead != null && playhead >= c.start && playhead < c.end; - const owner = siblingAt(c); - return ( - <li key={`t-${c.start}-${c.end}`}> - {rule && ( - <div - data-cache-rule={outside ? "end" : "start"} - className="flex items-center gap-2 border-t border-dashed border-reader-2 px-2 py-0.5 text-[10px] uppercase tracking-wider text-reader-dim" - > - {outside ? "not fetched — reading only" : "cached from here"} - </div> - )} - <button - type="button" - data-tcue={c.start} - data-peek={outside ? "1" : "0"} - data-in-sibling={owner ? owner.id : ""} - title={ - outside - ? `not fetched — click to fetch to ${padLabelForCue(c)}` - : "click to play from here" - } - onClick={() => { - if (outside) { - if (!atMaxPad) void fetchMore(padsForCue(c)); - return; - } - void play(c.start, Math.min(c.end + 4, view.to)); - }} - className={`flex w-full items-baseline gap-3 px-2.5 py-[3px] text-left hover:bg-[color-mix(in_srgb,var(--reader-signal)_6%,transparent)] ${ - inSel ? "bg-[color-mix(in_srgb,var(--reader-signal)_11%,transparent)]" : "" - } ${playing ? "border-l-[3px] border-reader-signal" : "border-l-[3px] border-transparent"}`} - > - <span - className={`num w-10 shrink-0 font-mono text-[10.5px] ${ - playing ? "font-semibold text-reader-signal" : "text-reader-dim" - }`} - > - {clock(c.start)} - </span> - <span - className={`min-w-0 font-serif text-[15px] leading-snug ${ - outside ? "text-reader-dim opacity-70" : inSel || playing ? "text-reader-ink" : "text-reader-2" - }`} - > - {owner && ( - <span - className="mr-1.5 rounded-[2px] border border-reader-2 px-1 font-mono text-[10px] text-reader-ink" - title={`already in the cut as ${owner.id} (${owner.where})`} - > - {owner.id} - </span> - )} - {c.endsSentence && ( - <span className="mr-1 font-mono text-[11px] text-reader-dim" aria-hidden> - ¶ - </span> - )} - {c.text} - </span> - </button> - </li> - ); - })} - </ul> - - {/* ---- the pane's own footer ---- - The controls that act on this pane live in it, stuck to the - bottom of its scrollport: they cost the pane a line and the - left column nothing, and "peek further" ends up beside the - dimmed lines it widens. Opaque, because it sits over text. */} - <div className="micro sticky bottom-0 z-10 flex flex-wrap items-center gap-2 border-t border-reader-seam bg-reader px-2.5 py-1"> - <span>click a line to play it</span> - {peek.length > 0 && ( - <> - <span>· dimmed lines are not fetched — click to fetch</span> - <button - type="button" - data-peek-further="" - className="ml-auto text-reader-signal hover:underline" - onClick={() => setPeekPad((n) => n + PEEK_STEP)} - > - peek further (±{peekPad + PEEK_STEP} s) - </button> - </> - )} - </div> - </div> - {/* ---- the warnings ---- Still unfolded, and deliberately: a warning behind a summary is a warning nobody reads. They are one line each instead. */} @@ -2825,45 +2949,6 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { {/* ---- THE ANSWER: on screen for every clip, never scrolled to ---- */} <div data-clip-answer="" className="flex flex-col gap-2 lg:flex-none"> - <div className="flex flex-wrap items-center gap-2"> - <span className="text-[var(--color-text)]">Is this accurate?</span> - <button - type="button" - data-verdict-yes="" - className={buttonVariants({ variant: "primary", size: "sm" })} - disabled={!!busy} - onClick={() => void confirmClip()} - > - Yes, confirmed <kbd>y</kbd> - </button> - <button - type="button" - data-verdict-no="" - className={buttonVariants({ size: "sm" })} - onClick={rejectClip} - > - No, note what is wrong <kbd>x</kbd> - </button> - <span - data-verdict-state="" - className={ - verdict === "confirmed" - ? "text-[var(--color-good)]" - : verdict === "incorrect" - ? "text-[var(--color-dirty)]" - : "text-[var(--color-dim)]" - } - > - {verdictLabel(clip)} - </span> - {needNote && !draft.correction.trim() && ( - <span className="text-[11px] text-[var(--color-dirty)]"> - the note is the answer — type it below, then blur or <kbd>Enter</kbd>. Saving - stays here, so you can read it back against the clip. - </span> - )} - </div> - {data.sourceTitle == null && ( <div className="text-[11px] leading-snug text-[var(--color-dirty)]"> No cue file was found for this source, so the archived record&rsquo;s own title and @@ -3050,5 +3135,6 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { </div> </div> </div> + </BenchBody> ); } diff --git a/umtool/components/projects/ClipBenchPage.tsx b/umtool/components/projects/ClipBenchPage.tsx @@ -1,6 +1,6 @@ import { notFound } from "next/navigation"; -import AppShell from "@/components/shell/AppShell"; -import { browseHref } from "@/lib/hrefs"; +import { browseHref, clipBenchHref } from "@/lib/hrefs"; +import { BenchFrame, BenchTop } from "./bench/BenchShell"; import ClipBench, { type ClipBenchData } from "./ClipBench"; import { manifestToken } from "@/lib/report/manifest.mjs"; import { @@ -167,24 +167,34 @@ export default async function ClipBenchPage({ // The piece this view belongs to: the article's when an article claims the project (P4a-2). const back = await pieceHrefOfProject(project.id, { tab: "cut" }); + const href = (id: string) => clipBenchHref(project.id, id); return ( - <div className="flex h-full flex-col"> - {/* A bench: the rail collapses and the work takes the width. */} - <AppShell - active="browse" - rail="collapsed" - crumbs={[ - { href: browseHref(), label: "projects" }, - { href: back, label: project.name }, - { label: clipId }, - ]} - // The progress reading moved INTO the bench, where pressing `y` can - // move it. What is left here is which source is playing. - note={`${entry.video}${entry.channel ? ` · ${entry.channel}` : ""}`} - /> - <main className="deck-main flex-1 p-4"> - <ClipBench data={data} /> - </main> - </div> + // The bench shell (P4b): its top bar here, the body -- the work, the + // verdict bar, the reader -- in ClipBench, which owns their state. + <BenchFrame + kind="clip" + top={ + <BenchTop + trail={[{ href: browseHref(), label: "projects" }]} + back={{ href: back, label: project.name }} + kind="Clip bench" + here={clipId} + pos={{ index: i + 1, total: clips.length }} + prev={prev ? { href: href(prev), label: prev, attrs: { "data-clip-nav": "prev" } } : null} + next={next ? { href: href(next), label: next, attrs: { "data-clip-nav": "next" } } : null} + keys={[ + { keys: ["y"], label: "confirm" }, + { keys: ["x"], label: "note" }, + { keys: ["[", "]", ",", "."], label: "nudge" }, + { keys: ["space"], label: "play" }, + { keys: ["p", "n"], label: "walk" }, + ]} + // Which source is playing. + note={`${entry.video}${entry.channel ? ` · ${entry.channel}` : ""}`} + /> + } + > + <ClipBench data={data} /> + </BenchFrame> ); } diff --git a/umtool/components/projects/NarrationPage.tsx b/umtool/components/projects/NarrationPage.tsx @@ -1,5 +1,5 @@ import Link from "next/link"; -import BrowseHeader from "@/components/BrowseHeader"; +import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell"; import { projectsHref } from "@/lib/hrefs"; import { readManifest } from "@/lib/projects/report.mjs"; import { manifestToken } from "@/lib/report/manifest.mjs"; @@ -20,35 +20,40 @@ export default async function NarrationPage({ project }: { project: ProjectRef } const token = await manifestToken(project.dir); const { counts } = view; // The piece this view belongs to: the article's when an article claims the project (P4a-2). - const [back, media] = await Promise.all([pieceHrefOfProject(project.id), pieceHrefOfProject(project.id, { tab: "media" })]); + const media = await pieceHrefOfProject(project.id, { tab: "media" }); return ( - <div className="flex h-full flex-col"> - <BrowseHeader - crumbs={[ - { href: projectsHref(), label: "projects" }, - { href: back, label: project.id }, - { label: "narration" }, - ]} - note={ - view.rows.length - ? `${view.rows.length} narrated · ${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"> - {view.rows.length === 0 ? ( + // The bench shell (P4b): the top bar here; NarrationReview owns the verdict bar. + <BenchFrame + kind="narration" + top={ + <BenchTop + trail={[{ href: projectsHref(), label: "projects" }]} + back={{ href: media, label: project.id }} + kind="Narration" + here="narration" + keys={view.rows.length ? [{ keys: ["j", "k"], label: "card" }, { keys: ["a"], label: "approve" }, { keys: ["r"], label: "reject" }] : []} + note={ + view.rows.length + ? `${view.rows.length} narrated · ${counts.approved} approved` + + (counts.rejected ? ` · ${counts.rejected} rejected` : "") + + (counts.edited + counts.unreviewed ? ` · ${counts.edited + counts.unreviewed} to review` : "") + : undefined + } + /> + } + > + {view.rows.length === 0 ? ( + <BenchBody> <p data-narration-empty="" className="text-[12px] text-[var(--color-dim)]"> No card in this cut carries a narration.{" "} <Link href={media} className="ink-link"> back to {project.id} </Link> </p> - ) : ( - <NarrationReview project={project.id} initial={view} token={token} /> - )} - </main> - </div> + </BenchBody> + ) : ( + <NarrationReview project={project.id} initial={view} token={token} /> + )} + </BenchFrame> ); } diff --git a/umtool/components/projects/NarrationReview.tsx b/umtool/components/projects/NarrationReview.tsx @@ -4,6 +4,7 @@ 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 { BenchBody, VerdictBar } from "./bench/BenchShell"; import { DraftAlternatives, useDrafts, type DraftAct, type DraftsView } from "./drafts"; // The narration script of one cut, card by card (release 25, T5). @@ -95,8 +96,88 @@ export default function NarrationReview({ project, initial, token: initialToken return j; }; + // ---- the bench shell's verdict bar (P4b) ---------------------------------- + // + // ONE question, on the card in hand: the one focused (a click or Tab inside + // it, or `j` / `k`), else the first still to review. `a` approves its words + // as saved; `r` rejects -- the note is the answer, so it puts the cursor + // there. + const [focus, setFocus] = useState<string | null>(null); + const toReview = view.rows.filter((r) => r.state !== "approved"); + const card = view.rows.find((r) => r.id === focus) ?? toReview[0] ?? null; + const [barError, setBarError] = useState<string | null>(null); + const approve = async (r: NarrationRow) => { + setBarError(null); + try { + await act(r.id, "approve", { note: r.note }); + } catch (e) { + setBarError(e instanceof Error ? e.message : String(e)); + } + }; + const toNote = (r: NarrationRow) => { + setFocus(r.id); + const el = document.querySelector<HTMLInputElement>(`[data-narration-card="${CSS.escape(r.id)}"] [data-narration-note]`); + el?.focus(); + }; + const move = (by: number) => { + const at = card ? view.rows.findIndex((r) => r.id === card.id) : -1; + const to = view.rows[Math.max(0, Math.min(view.rows.length - 1, at + by))]; + if (!to) return; + setFocus(to.id); + document.querySelector(`[data-narration-card="${CSS.escape(to.id)}"]`)?.scrollIntoView({ block: "nearest" }); + }; + useEffect(() => { + if (!ready) 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, audio, [contenteditable='true'], dialog[open]")) return; + if (e.key === "j") move(1); + else if (e.key === "k") move(-1); + else if (e.key === "a" && card) void approve(card); + else if (e.key === "r" && card) toNote(card); + else return; + e.preventDefault(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }); + const verdictBar = ( + <VerdictBar + data-verdict-for={card?.id ?? ""} + question={card ? <>Approve the narration of <span className="font-mono">{card.id}</span>?</> : <>Every narrated card is approved.</>} + consequence={ + !card + ? "A build takes them as they are." + : card.state === "approved" + ? `Approved${toReview.length ? ` — ${toReview.length} still to review` : ""}.` + : card.state === "rejected" + ? `Rejected${card.note ? `: ${card.note}` : ""} — a build refuses it until new words are approved.` + : `A build refuses it until it is approved${card.drafted ? " (drafted by " + card.drafted.model + ")" : ""}. The verdict is on the words as saved.` + } + > + {card && card.state !== "approved" && ( + <button type="button" data-narration-approve={card.id} disabled={!ready} className={buttonVariants({ variant: "go", size: "md" })} onClick={() => void approve(card)}> + Approve <kbd>a</kbd> + </button> + )} + {card && ( + <button type="button" data-narration-reject={card.id} disabled={!ready} className={buttonVariants({ size: "md" })} onClick={() => toNote(card)}> + Reject with a note <kbd>r</kbd> + </button> + )} + {barError && <span className="text-[12px] text-reject-text">{barError}</span>} + </VerdictBar> + ); + return ( - <div className="space-y-3"> + <BenchBody verdict={verdictBar}> + <div + className="space-y-3" + onFocus={(e) => { + const id = (e.target as HTMLElement).closest<HTMLElement>("[data-narration-card]")?.dataset.narrationCard; + if (id) setFocus(id); + }} + > <p data-review-file={view.exists ? "present" : "absent"} className="text-[11px] text-[var(--color-dim)]"> {view.error ? ( <span className="text-[var(--color-bad)]">{view.error}</span> @@ -114,9 +195,10 @@ export default function NarrationReview({ project, initial, token: initialToken )} </p> {view.rows.map((r) => ( - <NarrationCard key={r.id} project={project} row={r} ready={ready} act={act} refresh={refresh} drafts={drafts.view} draftAct={drafts.act} /> + <NarrationCard key={r.id} project={project} row={r} ready={ready} act={act} refresh={refresh} drafts={drafts.view} draftAct={drafts.act} lit={card?.id === r.id} /> ))} </div> + </BenchBody> ); } @@ -128,6 +210,7 @@ function NarrationCard({ refresh, drafts, draftAct, + lit = false, }: { project: string; row: NarrationRow; @@ -136,6 +219,8 @@ function NarrationCard({ refresh: () => Promise<NarrationView | null>; drafts: DraftsView | null; draftAct: DraftAct; + /** The card the verdict bar asks about: the lit line's edge (P4b). */ + lit?: boolean; }) { const [text, setText] = useState(r.text); const [note, setNote] = useState(r.note); @@ -204,7 +289,8 @@ function NarrationCard({ <article data-narration-card={r.id} data-state={r.state} - className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2" + data-lit={lit ? "" : undefined} + className={`rounded border bg-[var(--color-panel)] px-3 py-2 ${lit ? "border-l-[3px] border-[var(--color-line)] border-l-signal" : "border-[var(--color-line)]"}`} > <div className="mb-1.5 flex flex-wrap items-center gap-2"> <span className="font-mono text-[12px] text-[var(--color-text)]">{r.id}</span> diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx @@ -9,6 +9,7 @@ import TimedNotes from "@/components/notes/TimedNotes"; import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; import { fmtAgo } from "@/lib/format"; +import { BenchBody, VerdictBar } from "./bench/BenchShell"; // The takes of one project, a group at a time, every preview on screen at once. // @@ -86,10 +87,13 @@ export default function TakesBench({ project, groups, initial, + children, }: { project: string; groups: { group: string; takes: Take[] }[]; initial: Record<string, TakeVerdict>; + /** Under the groups, in the work column (the takes the listing skipped). */ + children?: React.ReactNode; }) { const [verdicts, setVerdicts] = useState(initial); const [listen, setListen] = useState<string | null>(null); @@ -132,8 +136,83 @@ export default function TakesBench({ setVerdicts(j.verdicts); }; + // ---- the bench shell's verdict bar (P4b) ---------------------------------- + // + // ONE question: the take being listened to -- like, maybe or no -- with the + // keys `l`, `m`, `x`; `n` / `p` move the listening to the next or previous + // take. With nothing being listened to, it says how to start and what is left. + const all = groups.flatMap((g) => g.takes); + const judged = all.filter((t) => verdicts[t.id]?.verdict).length; + const current = all.find((t) => t.id === listen) ?? null; + const [verdictError, setVerdictError] = useState<string | null>(null); + const judge = useCallback( + (v: Verdict) => { + if (!current) return; + setVerdictError(null); + const on = verdicts[current.id]?.verdict === v; + save(current.id, { verdict: on ? null : v }).catch((e) => setVerdictError(e instanceof Error ? e.message : String(e))); + }, + // eslint-disable-next-line react-hooks/exhaustive-deps + [current, verdicts], + ); + useEffect(() => { + if (!ready) return; + const onKey = (e: KeyboardEvent) => { + if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return; + const el = e.target as HTMLElement | null; + if (el?.closest?.("input, textarea, select, video, [contenteditable='true'], dialog[open]")) return; + const at = all.findIndex((t) => t.id === listenRef.current); + if (e.key === "n" || e.key === "p") { + const to = all[Math.max(0, Math.min(all.length - 1, at < 0 ? 0 : at + (e.key === "n" ? 1 : -1)))]; + if (to) { + setListen(to.id); + document.querySelector(`[data-take="${CSS.escape(to.id)}"]`)?.scrollIntoView({ block: "nearest" }); + } + } else if (e.key === "l") judge("like"); + else if (e.key === "m") judge("maybe"); + else if (e.key === "x") judge("no"); + else return; + e.preventDefault(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [ready, all, judge]); + + const verdictBar = ( + <VerdictBar + data-verdict-for={current?.id ?? ""} + question={ + current ? ( + <> + Is <span className="font-mono">{current.label}</span> the take for {current.group}? + </> + ) : ( + <>Listen to a take to judge it: like, maybe or no.</> + ) + } + consequence={`${judged} of ${all.length} judged${all.length - judged ? `, ${all.length - judged} to go` : ""}.`} + > + {current && + VERDICTS.map((v, i) => ( + <button + key={v.id} + type="button" + data-verdict-take={v.id} + aria-pressed={verdicts[current.id]?.verdict === v.id} + disabled={!ready} + className={buttonVariants({ variant: i === 0 ? "go" : "outline", size: "md" })} + onClick={() => judge(v.id)} + > + {v.label} <kbd>{v.id === "like" ? "l" : v.id === "maybe" ? "m" : "x"}</kbd> + </button> + ))} + {verdictError && <span className="text-[12px] text-reject-text">{verdictError}</span>} + </VerdictBar> + ); + return ( <NotesProvider target={{ project }}> + <BenchBody verdict={verdictBar}> <div className="space-y-6"> {groups.map((g) => { const tally = VERDICTS.map((v) => [v.id, g.takes.filter((t) => verdicts[t.id]?.verdict === v.id).length] as const) @@ -200,7 +279,9 @@ export default function TakesBench({ </section> ); })} + {children} </div> + </BenchBody> </NotesProvider> ); } diff --git a/umtool/components/projects/TakesPage.tsx b/umtool/components/projects/TakesPage.tsx @@ -1,5 +1,5 @@ import Link from "next/link"; -import AppShell from "@/components/shell/AppShell"; +import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell"; import { browseHref } from "@/lib/hrefs"; import { listTakes, readVerdicts } from "@/lib/report/takes.mjs"; import { pieceHrefOfProject } from "@/lib/pieces/article"; @@ -19,47 +19,53 @@ export default async function TakesPage({ project }: { project: ProjectRef }) { // The piece this view belongs to: the article's when an article claims the project (P4a-2). const back = await pieceHrefOfProject(project.id, { tab: "cut" }); + const skipped = + listing.skipped.length > 0 ? ( + <section data-takes-skipped="" className="text-[11px] text-[var(--color-dim)]"> + <h2 className="micro mb-1">skipped — {listing.skipped.length}</h2> + <ul className="space-y-0.5"> + {listing.skipped.map((s) => ( + <li key={s.dir} data-skipped={s.dir}> + <code className="font-mono text-[var(--color-text)]">takes/{s.dir}</code> — {s.why} + </li> + ))} + </ul> + </section> + ) : null; return ( - <div className="flex h-full flex-col"> - {/* A bench: the rail collapses and the work takes the width. */} - <AppShell - active="browse" - rail="collapsed" - crumbs={[ - { href: browseHref(), label: "projects" }, - { href: back, label: project.id }, - { label: "takes" }, - ]} - note={takes.length ? `${takes.length} takes · ${judged} judged` : undefined} - /> - <main className="deck-main flex-1 space-y-4 p-4"> - {takes.length === 0 ? ( + // The bench shell (P4b): the top bar here; TakesBench owns the verdict bar. + <BenchFrame + kind="takes" + top={ + <BenchTop + trail={[{ href: browseHref(), label: "projects" }]} + back={{ href: back, label: project.id }} + kind="Takes" + here="takes" + keys={takes.length ? [{ keys: ["n", "p"], label: "listen" }, { keys: ["l", "m", "x"], label: "like · maybe · no" }] : []} + note={takes.length ? `${takes.length} takes · ${judged} judged` : undefined} + /> + } + > + {takes.length === 0 ? ( + <BenchBody workClassName="space-y-4"> <p data-takes-empty="" className="text-[12px] text-[var(--color-dim)]"> No takes yet.{" "} <Link href={back} className="ink-link"> back to {project.id} </Link> </p> - ) : ( - <TakesBench - project={project.id} - groups={listing.groups.map((g) => ({ group: g.group, takes: g.takes as Take[] }))} - initial={verdicts as Record<string, TakeVerdict>} - /> - )} - {listing.skipped.length > 0 && ( - <section data-takes-skipped="" className="text-[11px] text-[var(--color-dim)]"> - <h2 className="micro mb-1">skipped — {listing.skipped.length}</h2> - <ul className="space-y-0.5"> - {listing.skipped.map((s) => ( - <li key={s.dir} data-skipped={s.dir}> - <code className="font-mono text-[var(--color-text)]">takes/{s.dir}</code> — {s.why} - </li> - ))} - </ul> - </section> - )} - </main> - </div> + {skipped} + </BenchBody> + ) : ( + <TakesBench + project={project.id} + groups={listing.groups.map((g) => ({ group: g.group, takes: g.takes as Take[] }))} + initial={verdicts as Record<string, TakeVerdict>} + > + {skipped} + </TakesBench> + )} + </BenchFrame> ); } diff --git a/umtool/components/projects/bench/BenchShell.tsx b/umtool/components/projects/bench/BenchShell.tsx @@ -0,0 +1,235 @@ +import Link from "next/link"; +import { Mark } from "@/components/shell/Wordmark"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// THE BENCH SHELL (plans/umtool-redesign.md, P4b; canvas "Clip bench"): one +// frame for every human-piloted walk -- the clip bench, the claim bench, the +// narration script, the takes and the drafts review. +// +// top ← the piece · what bench this is · where you are ("c04 · 1 of 3") +// · ‹ prev / next › · the keys, in one row (canvas `.benchtop`). +// It IS the page's head: the mark links home (the rail is +// collapsed), the trail is a Breadcrumb nav, `data-app-header=bench`. +// work the bench's own working area (its player, its fields) +// verdict ONE question, the actions named by what they do, and the +// consequence stated before you choose (canvas `.verdictbar`) +// reader the source on the reader surface, the cited cue lit, the cite +// thread (components/ui/reader-pane.tsx) +// +// Fits 1366×768: the frame is the viewport, only its columns scroll. Below lg +// it is one scrolling column (a phone cannot hold a bench; pretending would +// cost the desk). +// +// No hooks and no server imports: a client bench (ClipBench) composes +// BenchBody itself, so its verdict bar and reader can read its own state; a +// server page renders BenchFrame + BenchTop around it. +// --------------------------------------------------------------------------- + +export type BenchLink = { href: string; label: string; attrs?: Record<`data-${string}`, string> }; +export type BenchKey = { keys: string[]; label: string }; + +/** The page: the top bar over the body, the viewport's height. */ +export function BenchFrame({ + kind, + top, + children, + className, +}: { + /** `data-bench-shell`: clip, claim, narration, takes, review. */ + kind: string; + top: React.ReactNode; + children: React.ReactNode; + className?: string; +}) { + return ( + <div data-bench-shell={kind} className={cn("flex h-full min-h-0 flex-col overflow-auto lg:overflow-hidden", className)}> + {top} + {children} + </div> + ); +} + +/** The bench's head (canvas `.benchtop`). */ +export function BenchTop({ + back, + trail = [], + kind, + here, + pos, + prev, + next, + keys = [], + note, +}: { + /** The piece this bench belongs to: "← <its name>". */ + back: BenchLink; + /** Crumbs before the piece ("projects"), small. */ + trail?: BenchLink[]; + /** What bench this is, in words ("Clip bench", "Drafts review"). */ + kind: string; + /** What is on it: the clip id, "narration". */ + here: string; + /** Where you are in the walk. */ + pos?: { index: number; total: number; of?: string } | null; + prev?: BenchLink | null; + next?: BenchLink | null; + keys?: BenchKey[]; + /** The bench's one-line status, the head's last `.micro`. */ + note?: React.ReactNode; +}) { + return ( + <header + data-app-header="bench" + data-bench-top="" + className="flex flex-wrap items-center gap-x-3 gap-y-1.5 border-b border-seam bg-panel px-4 py-2" + > + <Link href="/" prefetch={false} aria-label="umtool home" className="shrink-0"> + <Mark size={18} /> + </Link> + <nav aria-label="Breadcrumb" className="flex min-w-0 items-center gap-1.5 text-[12.5px]"> + {trail.map((c) => ( + <span key={c.href} className="hidden items-center gap-1.5 xl:flex"> + <Link href={c.href} prefetch={false} className="text-muted-2 hover:text-text"> + {c.label} + </Link> + <span className="text-seam-2">/</span> + </span> + ))} + <Link href={back.href} prefetch={false} data-bench-back="" className="truncate text-muted-2 hover:text-text" {...back.attrs}> + <span aria-hidden>← </span> + {back.label} + </Link> + <span className="text-seam-2">/</span> + <span aria-current="page" className="font-mono text-[13px] font-medium text-text"> + {here} + </span> + </nav> + <span className="micro" data-bench-kind=""> + {kind} + </span> + {pos && ( + <span data-bench-pos={`${pos.index}/${pos.total}`} className="font-mono text-[12.5px] font-medium text-text-2"> + {pos.index} of {pos.total} + {pos.of ? ` ${pos.of}` : ""} + </span> + )} + {(prev !== undefined || next !== undefined) && ( + <span className="flex items-center gap-1"> + {prev ? ( + <Link + href={prev.href} + prefetch={false} + data-bench-nav="prev" + className="rounded-[3px] px-2 py-[3px] text-[11.5px] text-muted-2 hover:bg-panel-2 hover:text-text" + {...prev.attrs} + > + ‹ {prev.label} + </Link> + ) : ( + <span className="px-2 py-[3px] text-[11.5px] text-muted-2 opacity-50">‹ first</span> + )} + {next ? ( + <Link + href={next.href} + prefetch={false} + data-bench-nav="next" + className="rounded-[3px] px-2 py-[3px] text-[11.5px] text-muted-2 hover:bg-panel-2 hover:text-text" + {...next.attrs} + > + {next.label} › + </Link> + ) : ( + <span className="px-2 py-[3px] text-[11.5px] text-muted-2 opacity-50">last ›</span> + )} + </span> + )} + {(keys.length > 0 || note) && ( + <span className="ml-auto flex flex-wrap items-center gap-x-2.5 gap-y-1"> + {keys.length > 0 && ( + <span data-bench-keys="" className="hidden flex-wrap items-center gap-x-2.5 md:flex"> + {keys.map((k) => ( + <span key={k.label} className="inline-flex items-center gap-1 text-[11.5px] text-muted-2"> + {k.keys.map((key) => ( + <kbd key={key}>{key}</kbd> + ))} + <span>{k.label}</span> + </span> + ))} + </span> + )} + {note && <span className="micro">{note}</span>} + </span> + )} + </header> + ); +} + +/** The body: the work column (its verdict bar at the foot) and the reader on the right. */ +export function BenchBody({ + verdict, + reader, + children, + workClassName, +}: { + verdict?: React.ReactNode; + reader?: React.ReactNode; + children: React.ReactNode; + workClassName?: string; +}) { + return ( + <div + data-bench-body="" + className={cn( + "flex min-h-0 flex-1 flex-col lg:grid", + reader ? "lg:grid-cols-[minmax(0,1fr)_minmax(340px,30%)]" : "lg:grid-cols-[minmax(0,1fr)]", + )} + > + <div className="flex min-h-0 min-w-0 flex-col"> + <main data-bench-work="" className={cn("deck-main min-h-0 flex-1 p-4", workClassName)}> + {children} + </main> + {verdict} + </div> + {reader && <div className="flex min-h-[320px] flex-col border-t border-seam lg:min-h-0 lg:border-t-0">{reader}</div>} + </div> + ); +} + +/** + * The verdict bar (canvas `.verdictbar`): the one question, its consequence in + * bold, then the actions -- each named by what it does, the first the screen's + * one filled action. + */ +export function VerdictBar({ + question, + consequence, + children, + className, + ...props +}: Omit<React.ComponentProps<"div">, "children"> & { + question: React.ReactNode; + consequence?: React.ReactNode; + children?: React.ReactNode; +}) { + return ( + <div + data-verdict-bar="" + className={cn("flex shrink-0 flex-wrap items-center gap-2 border-t border-seam bg-ground px-4 pb-3 pt-2.5", className)} + {...props} + > + <p data-verdict-question="" className="m-0 basis-full text-[14px] leading-snug text-text"> + {question} + {consequence && ( + <> + {" "} + <b data-verdict-consequence="" className="font-semibold"> + {consequence} + </b> + </> + )} + </p> + {children} + </div> + ); +} diff --git a/umtool/components/projects/bench/CopyCitation.tsx b/umtool/components/projects/bench/CopyCitation.tsx @@ -0,0 +1,39 @@ +"use client"; + +import { useState } from "react"; +import { paperButtonVariants } from "@/components/ui/reader-pane"; +import { useHydrated } from "@/components/ui/use-hydrated"; + +// The reader's Copy citation (a bench's reader pane): the house citation +// (`"quote" [title @ m:ss](url)`, lib/research/facets.mjs) on the clipboard. +// A copy the browser refuses shows the text to select instead -- a copy that +// silently does nothing is the worst failure for this button. +export default function CopyCitation({ text, label = "Copy citation" }: { text: string; label?: string }) { + const hydrated = useHydrated(); + const [state, setState] = useState<"idle" | "done" | "failed">("idle"); + return ( + <> + <button + type="button" + data-copy-citation="" + className={paperButtonVariants()} + disabled={!hydrated} + title={text} + onClick={async () => { + try { + await navigator.clipboard.writeText(text); + setState("done"); + setTimeout(() => setState("idle"), 1600); + } catch { + setState("failed"); + } + }} + > + {state === "done" ? "Copied" : label} + </button> + {state === "failed" && ( + <input readOnly value={text} aria-label="citation" className="min-w-0 flex-1 rounded-[2px] border border-reader-2 bg-transparent px-1.5 py-0.5 font-mono text-[11px]" onFocus={(e) => e.currentTarget.select()} /> + )} + </> + ); +} diff --git a/umtool/components/ui/reader-pane.tsx b/umtool/components/ui/reader-pane.tsx @@ -2,7 +2,7 @@ import { cva } from "class-variance-authority"; import { cn } from "@/lib/utils"; import { ReaderThread } from "./cite-thread"; import { clock } from "./clock"; -import { LitList } from "./lit-list"; +import { LitList, type LitDetail } from "./lit-list"; import { LitLine } from "./lit-line"; // --------------------------------------------------------------------------- @@ -17,11 +17,22 @@ import { LitLine } from "./lit-line"; // speaker when the transcript knows one // footer the actions (paperButtonVariants), and a fine line (the citation) // +// A bench (P4b) passes its own handle and ref on the body (`bodyProps`), its own +// cue rows unwrapped (`bare`), or follows the lit cue (`onLight`). +// // Rules from the canvas critique: no verdict colour on the reader, ever; the // reader's own Signal is `--reader-signal`, a teal dark enough for the paper. // --------------------------------------------------------------------------- -export type Cue = { t: number; text: React.ReactNode; turn?: boolean; lit?: boolean; id?: string }; +export type Cue = { + t: number; + text: React.ReactNode; + turn?: boolean; + lit?: boolean; + id?: string; + /** The line's own data attributes (a bench's handles; P4b). */ + attrs?: Record<`data-${string}`, string | undefined>; +}; export const paperButtonVariants = cva( "inline-flex items-center justify-center gap-1.5 whitespace-nowrap rounded-[3px] border px-[11px] py-[5px] text-[12.5px] font-medium transition-[color,background-color,border-color,text-decoration-color,fill,stroke] disabled:pointer-events-none disabled:opacity-50", @@ -45,6 +56,10 @@ export function ReaderPane({ label = "Transcript", footer, fine, + bodyProps, + bare = false, + onLight, + global = false, className, children, ...props @@ -64,6 +79,14 @@ export function ReaderPane({ fine?: React.ReactNode; /** Instead of cues: anything else the source said (a post, a quote). */ children?: React.ReactNode; + /** Onto the scrolling body (a bench's handle, its ref; P4b). */ + bodyProps?: React.ComponentProps<"div"> & Record<`data-${string}`, string | undefined>; + /** `children` as they are, without the reader-text column (a bench's own cue rows; P4b). */ + bare?: boolean; + /** The lit cue moved (a bench seeks its player to it; P4b). */ + onLight?: (d: LitDetail) => void; + /** `j`/`k` from anywhere on the page move the cues (the page's one list: a bench; P4b). */ + global?: boolean; }) { const parts = (byline ?? []).filter(Boolean); return ( @@ -83,9 +106,9 @@ export function ReaderPane({ {cite && <ReaderThread at={cite.at} duration={cite.duration} />} </div> {note && <div className="px-[22px] pt-2 text-[11.5px] text-reader-dim">{note}</div>} - <div className="min-h-0 flex-1 overflow-auto py-2 pr-2.5"> + <div {...bodyProps} className={cn("min-h-0 flex-1 overflow-auto py-2 pr-2.5", bodyProps?.className)}> {cues ? ( - <LitList label={label}> + <LitList label={label} onLight={onLight} global={global}> {cues.map((c, i) => ( <LitLine key={c.id ?? `${c.t}-${i}`} @@ -93,12 +116,15 @@ export function ReaderPane({ initial={c.lit} className="reader-cue" data-turn={c.turn ? "" : undefined} + {...c.attrs} > <span className="reader-t">{clock(c.t)}</span> <p>{c.text}</p> </LitLine> ))} </LitList> + ) : bare ? ( + children ) : ( <div className="reader-text px-[22px]">{children}</div> )} diff --git a/umtool/lib/report/draft-provenance.mjs b/umtool/lib/report/draft-provenance.mjs @@ -0,0 +1,119 @@ +// WHERE A DRAFTED FIELD CAME FROM (plans/umtool-redesign.md, P4b): for every +// field a media task drafted, the task's own audit file beside the manifest +// (`<task>-draft.json`, narrate's `narration-draft.json`) says how many +// attempts it took, which one was kept, and the rule each refused attempt +// broke (`attempts[].hard`). The Media tab shows it under the field: "attempt +// 2 of 2 chosen · attempt 1 failed: ✕ text in quotation marks". +// +// Two shapes are read: +// - release 28's scaffold (common/lib/report/draft/tasks/media.ts): +// `{ task, model, at, units: { <id>: { target: {entry?, field}, attempts: +// [{value, hard, soft}], chosen, applied? | skipped? } } }`; +// - release 25's narrate file: the units at the top level, keyed by card id, +// `{ heading, attempts: [{text, hard, soft}], chosen }`, no model. +// +// Plain ESM: `node --test` runs it with no TypeScript. Read only. +import { readdir, readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { draftedFields, reviewAddress, stableStringify } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; +import { DRAFT_FILE_RE } from "./drafts.mjs"; + +const strings = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []); +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); + +/** + * One unit's attempts, as the field shows them. + * + * @param {any} unit + * @param {number | null} markAttempt the attempt the manifest's mark names, if any + */ +export function attemptsOf(unit, markAttempt = null) { + const attempts = Array.isArray(unit?.attempts) ? unit.attempts.filter(isObj) : []; + if (!attempts.length) return null; + let chosen = null; + if (isObj(unit.chosen)) { + const key = stableStringify(unit.chosen.value ?? unit.chosen.text ?? null); + const i = attempts.findIndex((a) => stableStringify(a.value ?? a.text ?? null) === key); + if (i >= 0) chosen = i + 1; + } + if (chosen === null && Number.isInteger(markAttempt) && markAttempt >= 1 && markAttempt <= attempts.length) chosen = markAttempt; + return { + attempts: attempts.length, + chosen, + // A repaired value (narrate removes the failing sentences) is none of the attempts. + repaired: isObj(unit.chosen) && chosen === null, + failed: attempts + .map((a, i) => ({ attempt: i + 1, hard: strings(a.hard) })) + .filter((a) => a.hard.length > 0), + soft: strings((isObj(unit.chosen) ? unit.chosen : attempts[(chosen ?? 1) - 1])?.soft), + }; +} + +/** + * Every field's provenance from a project's draft files. + * + * @param {{ file: string, doc: any, mtimeMs?: number | null }[]} files + * @param {any} manifest the whole manifest (its `drafted` marks pick between two files claiming one field) + * @returns {Record<string, { file: string, model: string | null, at: string | null, attempts: number, chosen: number | null, repaired: boolean, failed: { attempt: number, hard: string[] }[], soft: string[] }>} + */ +export function provenanceFrom(files, manifest) { + const marks = markIndex(manifest); + /** @type {Record<string, any>} */ + const out = {}; + for (const { file, doc, mtimeMs } of files) { + if (!isObj(doc)) continue; + const model = typeof doc.model === "string" ? doc.model : null; + const at = typeof doc.at === "string" ? doc.at : mtimeMs ? new Date(mtimeMs).toISOString() : null; + const units = isObj(doc.units) + ? Object.values(doc.units).map((u) => ({ u, target: isObj(u?.target) && typeof u.target.field === "string" ? u.target : null })) + : // release 25: the narrate file's units at the top level, keyed by card id. + file === "narration-draft.json" + ? Object.entries(doc).map(([id, u]) => ({ u, target: isObj(u) && Array.isArray(u.attempts) ? { entry: id, field: "narration" } : null })) + : []; + for (const { u, target } of units) { + if (!target) continue; + const address = reviewAddress({ entry: typeof target.entry === "string" && target.entry ? target.entry : null, field: target.field }); + const mark = marks.get(address) ?? null; + const a = attemptsOf(u, mark?.attempt ?? null); + if (!a) continue; + const prev = out[address]; + // Two files claim it: the one the mark's task wrote wins. + const mine = mark && file === (mark.task === "narrate" ? "narration-draft.json" : `${mark.task}-draft.json`); + if (prev && !mine) continue; + out[address] = { file, model: model ?? mark?.model ?? null, at: mark?.at ?? at, ...a }; + } + } + return out; +} + +/** The manifest's drafted marks by review address. */ +function markIndex(manifest) { + return new Map(draftedFields(manifest).map((d) => [reviewAddress(d), d.provenance])); +} + +/** + * Read a project's draft files and answer `provenanceFrom` over them. A file + * that does not parse is skipped (its task wrote it; not this view's to repair). + * + * @param {string} projectDir + * @param {any} manifest + */ +export async function readFieldProvenance(projectDir, manifest) { + let names = []; + try { + names = (await readdir(projectDir)).filter((n) => DRAFT_FILE_RE.test(n)).sort(); + } catch { + return {}; + } + const files = []; + for (const file of names) { + const p = path.join(projectDir, file); + try { + const [text, st] = await Promise.all([readFile(p, "utf8"), stat(p)]); + files.push({ file, doc: JSON.parse(text), mtimeMs: st.mtimeMs }); + } catch { + /* skipped */ + } + } + return provenanceFrom(files, manifest); +} diff --git a/umtool/lib/report/draft-provenance.test.mjs b/umtool/lib/report/draft-provenance.test.mjs @@ -0,0 +1,80 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { attemptsOf, provenanceFrom, readFieldProvenance } from "./draft-provenance.mjs"; + +test("attemptsOf: the chosen attempt by value, the refused ones with their rules", () => { + const u = { + attempts: [ + { value: { title: "A" }, hard: ["title over 60 chars"], soft: [] }, + { value: { title: "B" }, hard: [], soft: ["no name grounded"] }, + ], + chosen: { value: { title: "B" }, hard: [], soft: ["no name grounded"] }, + }; + assert.deepEqual(attemptsOf(u), { + attempts: 2, + chosen: 2, + repaired: false, + failed: [{ attempt: 1, hard: ["title over 60 chars"] }], + soft: ["no name grounded"], + }); + // No attempts: nothing to say. A clean first attempt: chosen 1, nothing failed. + assert.equal(attemptsOf({ skipped: "has a value" }), null); + assert.deepEqual(attemptsOf({ attempts: [{ value: "x", hard: [], soft: [] }], chosen: { value: "x", hard: [], soft: [] } }).failed, []); + // A repaired value is none of the attempts; the mark's attempt is the fallback when there is no chosen. + assert.equal(attemptsOf({ attempts: [{ text: "a", hard: ["q"] }], chosen: { text: "fixed" } }).repaired, true); + assert.equal(attemptsOf({ attempts: [{ value: 1, hard: [] }, { value: 2, hard: [] }] }, 2).chosen, 2); +}); + +test("provenanceFrom: release 28's units by target, release 25's narrate file by card id", () => { + const manifest = { + timeline: [ + { id: "c01", type: "clip", onscreen: { title: "T" }, drafted: { onscreen: { task: "onscreen", model: "qwen3:8b", at: "2026-10-13T00:00:00Z", attempt: 2 } } }, + { id: "k01", type: "card", narration: { text: "Words." } }, + ], + }; + const files = [ + { + file: "onscreen-draft.json", + doc: { + task: "onscreen", + model: "qwen3:8b", + at: "2026-10-13T00:00:00Z", + units: { + c01: { target: { entry: "c01", field: "onscreen" }, attempts: [{ value: { title: "Too long" }, hard: ["title over 60"], soft: [] }, { value: { title: "T" }, hard: [], soft: [] }], chosen: { value: { title: "T" }, hard: [], soft: [] } }, + c02: { target: { entry: "c02", field: "onscreen" }, skipped: "has a value" }, + }, + }, + }, + { + file: "narration-draft.json", + mtimeMs: Date.UTC(2026, 9, 12, 20, 54), + doc: { k01: { heading: "H", attempts: [{ text: "\"q\"", hard: ["text in quotation marks: no quotes in narration"], soft: [] }, { text: "Words.", hard: [], soft: [] }], chosen: { text: "Words.", hard: [], soft: [] } } }, + }, + ]; + const p = provenanceFrom(files, manifest); + assert.deepEqual(Object.keys(p).sort(), ["narrate/k01/narration", "onscreen/c01/onscreen"]); + assert.equal(p["onscreen/c01/onscreen"].chosen, 2); + assert.deepEqual(p["onscreen/c01/onscreen"].failed, [{ attempt: 1, hard: ["title over 60"] }]); + assert.equal(p["onscreen/c01/onscreen"].model, "qwen3:8b"); + assert.equal(p["narrate/k01/narration"].file, "narration-draft.json"); + assert.equal(p["narrate/k01/narration"].model, null); + assert.equal(p["narrate/k01/narration"].at, "2026-10-12T20:54:00.000Z"); + assert.deepEqual(p["narrate/k01/narration"].failed[0].hard, ["text in quotation marks: no quotes in narration"]); +}); + +test("readFieldProvenance reads the draft files beside the manifest and skips one that does not parse", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "prov-")); + try { + writeFileSync(path.join(dir, "cut-draft.json"), JSON.stringify({ model: "m", at: "a", units: { cut: { target: { field: "timeline" }, attempts: [{ value: ["c01"], hard: [], soft: [] }], chosen: { value: ["c01"], hard: [], soft: [] } } } })); + writeFileSync(path.join(dir, "teaser-draft.json"), "{ not json"); + writeFileSync(path.join(dir, "notes.json"), "{}"); + const p = await readFieldProvenance(dir, { timeline: [] }); + assert.deepEqual(Object.keys(p), ["cut/*/timeline"]); + assert.equal(p["cut/*/timeline"].attempts, 1); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +});