"use client"; import { useEffect, useRef, useState } from "react"; import ReadAgain, { madeWithText, playNow, useAutoPlay, type Tuning } from "./read/ReadAgain"; 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). // // Each narrated card: what it shows on screen, the words it will speak (edited // in place), the engine and voice, and a verdict -- Approve, or Reject with a // note saying what is wrong -- on THOSE words. Saving new words clears the // verdict; the server is the word on every state, and each action answers with // the whole view. Play asks the editor to synthesize that one card // (narrate-via-editor --only, a job followed by id) and plays it. // // Buttons stay disabled until mount, as TakesBench's do: a click before // hydration sends nothing, and a verdict lost that way looks like one never given. export type NarrationRow = { id: string; at: number; text: string; engine: string; voice: string; speed: number; words: number; 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; judgedText: string; judgedAt: string; kept: { seconds: number; disclosure: string; mtimeMs: number } | null; /** Its key now, reading and tuning, and every reading kept for it (lane line-rerun). */ key?: string; reading?: number; tuning?: Tuning | null; madeWith?: Tuning | null; readings?: Array<{ key: string; text: string; reading: number; tuning: Tuning | null; seconds: number; createdAt: string | null }>; }; export type NarrationView = { file: string; exists: boolean; error: string | null; rows: NarrationRow[]; counts: Record; }; const STATE: Record = { approved: { label: "approved", tone: "meter" }, rejected: { label: "rejected", tone: "blocking" }, edited: { label: "edited since approved", tone: "on" }, unreviewed: { label: "not reviewed", tone: "neutral" }, }; const audioSrc = (project: string, r: NarrationRow) => `/api/report/narration/audio?${new URLSearchParams({ project, card: r.id, v: String(r.kept?.mtimeMs ?? 0) })}`; export default function NarrationReview({ project, initial, token: initialToken }: { project: string; initial: NarrationView; token: string | null }) { const [view, setView] = useState(initial); 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 = {}) => { const r = await fetch("/api/report/narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, card, action, ...(action === "edit" ? { token } : {}), ...extra }), cache: "no-store", }); const j = (await r.json()) as NarrationView & { error?: string; token?: string | null; ok?: boolean }; if (!r.ok || !j.ok) throw new Error(j.error ?? `HTTP ${r.status}`); setView(j); if (j.token !== undefined) setToken(j.token); }; const refresh = async () => { const r = await fetch(`/api/report/narration?project=${encodeURIComponent(project)}`, { cache: "no-store" }); if (!r.ok) return null; const j = (await r.json()) as NarrationView & { token?: string | null }; setView(j); if (j.token !== undefined) setToken(j.token); 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(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(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(`[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 = ( Approve the narration of {card.id}? : <>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" && ( )} {card && ( )} {barError && {barError}} ); return (
{ const id = (e.target as HTMLElement).closest("[data-narration-card]")?.dataset.narrationCard; if (id) setFocus(id); }} >

{view.error ? ( {view.error} ) : view.exists ? ( <> Verdicts in {view.file}: a build refuses any narrated card not approved on its current words — a drafted one, a final build (--narration-unreviewed{" "} builds them anyway; never a rejected one). ) : ( <> Nothing judged yet. The first verdict writes {view.file}, and from then on a build refuses any narrated card not approved (a drafted one: a final build, judged or not). )}

{view.rows.map((r) => ( ))}
); } function NarrationCard({ project, row: r, ready, act, refresh, drafts, draftAct, lit = false, }: { project: string; row: NarrationRow; ready: boolean; act: (card: string, action: string, extra?: Record) => Promise; refresh: () => Promise; 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); const [busy, setBusy] = useState(false); const [playing, setPlaying] = useState(false); const [error, setError] = useState(null); const audio = useRef(null); const autoplay = useRef(false); // Adopt server values that moved underneath (a save, another tab). useEffect(() => setText(r.text), [r.text]); useEffect(() => setNote(r.note), [r.note]); useEffect(() => { if (autoplay.current && r.kept && audio.current) { autoplay.current = false; void audio.current.play().catch(() => {}); } }, [r.kept]); const run = async (fn: () => Promise) => { setBusy(true); setError(null); try { await fn(); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); } }; const play = () => run(async () => { if (r.kept && audio.current) { await audio.current.play().catch(() => {}); return; } setPlaying(true); try { const res = await fetch("/api/report/narration/play", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, card: r.id }), }); const j = (await res.json()) as { error?: string; job?: { id: string } }; if (!res.ok || !j.job) throw new Error(j.error ?? `HTTP ${res.status}`); for (;;) { await new Promise((ok) => setTimeout(ok, 600)); const p = await fetch(`/api/report/build?job=${encodeURIComponent(j.job.id)}`, { cache: "no-store" }); if (!p.ok) continue; const s = (await p.json()) as { state: string; error: string | null }; if (s.state === "running") continue; if (s.state !== "done") throw new Error(s.error ?? "the narration was not synthesized"); break; } autoplay.current = true; await refresh(); } finally { setPlaying(false); } }); const dirty = text.trim() !== r.text; const screen = [r.screen.kicker, r.screen.heading, r.screen.sub].filter(Boolean); // ---- READ AGAIN (lane line-rerun): a reading kept for the card, the card not changed; Pick makes it play ---- const [auto, setAuto] = useAutoPlay(); const [reading, setReading] = useState<{ waiting: string | null } | null>(null); const readingUrl = (key: string) => `/api/report/narration/audio?${new URLSearchParams({ project, card: r.id, key })}`; const readAgain = (tuning: Tuning | null, words: string | null) => run(async () => { if (words !== null) await act(r.id, "edit", { text: words }); const before = new Set((r.readings ?? []).map((x) => x.key)); const res = await fetch("/api/report/narration/play", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, card: r.id, again: true, reading: "next", ...(tuning ? { tuning } : {}) }) }); const j = (await res.json()) as { error?: string; job?: { id: string }; waiting?: string }; if (!res.ok || !j.job) throw new Error(j.error ?? `HTTP ${res.status}`); setReading({ waiting: j.waiting ?? null }); try { // A lost job (404, no state) failed; the bench out of reach is asked again, five times running at most // (review 1, finding 5) -- nothing is played for a reading that did not end done. let misses = 0; for (;;) { await new Promise((ok) => setTimeout(ok, 600)); const p = await fetch(`/api/report/build?job=${encodeURIComponent(j.job.id)}`, { cache: "no-store" }).catch(() => null); if (!p) { if ((misses += 1) >= 5) throw new Error("the bench did not answer"); continue; } misses = 0; const st = (await p.json().catch(() => ({}))) as { state?: string; error?: string | null }; if (!p.ok || !st.state) throw new Error(st.error ?? `the job is gone (HTTP ${p.status})`); if (st.state === "running") continue; if (st.state !== "done") throw new Error(st.error ?? "the reading was not made"); break; } } finally { setReading(null); } const v = await refresh(); const fresh = v?.rows.find((x) => x.id === r.id)?.readings?.find((x) => !before.has(x.key)); if (fresh && auto) playNow(readingUrl(fresh.key)); }); return (
{r.id} {STATE[r.state].label} {r.drafted && ( drafted by {r.drafted.model} )} {r.engine} · {r.voice} {r.speed !== 1 ? ` · ×${r.speed}` : ""} {r.words} words · ~{r.estimate.toFixed(1)} s{r.kept ? ` · voiced ${r.kept.seconds.toFixed(1)} s` : ""} {typeof r.seconds === "number" ? ` · card ${r.seconds} s` : r.seconds === "auto" ? " · card auto" : ""}
on screen{r.screen.style ? ` · ${r.screen.style}` : ""}
{screen.length ? ( screen.map((line, i) => (
{line}
)) ) : (
—
)} {r.screen.title &&
deck title: {r.screen.title}
}