"use client"; import { useEffect, useMemo, useRef, useState } from "react"; import { readsHref } from "@/lib/hrefs"; import ReadAgain, { playNow, useAutoPlay, type Tuning } from "./read/ReadAgain"; import { useKeepForCharacter } from "./read/keepForCharacter"; import { pieceOwnOf, threadTuneMadeOf } from "@/lib/report/tuneAsk.mjs"; import { THREAD_DEFAULTS, THREAD_LIMITS, THREAD_MODES, partRoles, readPieces, threadKnobs, threadLayout, threadReadErrors } from "umtool-report-to-video/post-thread"; import { followKnobs } from "umtool-report-to-video/read-follow"; import { pickedTake } from "umtool-report-to-video/post-narration"; import type { PostPlan } from "./review/PostItemPlayer"; // --------------------------------------------------------------------------- // A POST's THREAD READ ON THE BENCH (report-to-video/post-thread.mjs; // knobs.md, "Thread reads"; operator, 4 Nov: "you're never narrating hidden // text ... show the parent in full then transition in the reply as the parent // shrinks and goes dim"): its read PIECE BY PIECE -- the text each piece reads // (the post it answers, the post it quotes, his words, an attachment's), when // it starts (click: the playhead there) -- and what each context post is on // screen (full, excerpt, context, carry, hidden), the shrink, the dim and their // seconds, the pan's. A setting that would narrate a post the card hides is // shown here, and refused by Save (the writer's guard). The knobs are the // bench's draft (its Save writes them, as hold and follow). // --------------------------------------------------------------------------- type Entry = Record & { id: string; parents?: Array>; quoted?: Record }; type Thread = Partial<{ parent: string | string[]; quoted: string; carry: "auto" | boolean; reveal: boolean; shrink: number; dim: number; seconds: number; pan: number }>; const ROLE_NAME = (r: string | null) => r === null ? "no text on the card" : r === "post" ? "his words" : r === "quoted" ? "the post it quotes" : r === "parent:0" ? "the post it answers" : r.startsWith("parent:") ? "the post that answers" : `attachment ${Number(r.slice(6)) + 1}'s words`; export default function PostThreadPanel({ project = null, entry, plan, render, before, scene = null, setS, setEntry, onEntry, }: { /** The project (its "Read without it" re-joins the take through the post-narration route). */ project?: string | null; entry: Entry; plan: PostPlan; render: Record; before: Record | null; /** The posts its run leaves on screen (post-conversation.mjs planContext). */ scene?: Record | null; setS: (s: number) => void; setEntry: (f: (e: Entry) => Entry) => void; /** The writer's answer after a Read again (the entry as it is now, the manifest's token). */ onEntry?: (e: Entry, token: string | null) => void; }) { const own = (entry.thread ?? undefined) as Thread | undefined; const k = threadKnobs(entry, render) as Required; const layout = useMemo(() => threadLayout(entry, render, { prev: before, scene }), [entry, render, before, scene]); const roles = useMemo(() => partRoles(entry) as Array<{ role: string | null; source: string }>, [entry]); const pieces = useMemo(() => readPieces(entry, roles) as Array<{ role: string | null; parts: number[] }>, [entry, roles]); const errors = useMemo(() => threadReadErrors(entry, render, { prev: before, scene, followOn: (followKnobs(entry, render) as { on: boolean }).on }) as string[], [entry, render, before, scene]); // The scene (post-conversation.mjs): the posts its run left on screen, kept on top or collapsing away. const sceneTiles = (layout.tiles as Array<{ scope: string; mode: string; action?: string; ref?: { handle?: string; author?: string; redact?: boolean } }>).filter((t) => t.mode === "scene"); const take = pickedTake(entry) as { parts?: Array<{ start: number; text?: string }> } | null; // READ WITHOUT IT (lib/report/postReread.mjs): the picked take re-joined without a context piece it reads -- its // kept parts cut from its own file, no TTS -- a new take picked (one undo point); the page reloads on it. const [rereading, setRereading] = useState(null); const [rereadError, setRereadError] = useState(null); const reread = async (role: string) => { if (!project) return; setRereading(role); setRereadError(null); try { const res = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "reread", id: entry.id, without: [role] }) }); const j = (await res.json().catch(() => ({}))) as { ok?: boolean; error?: string }; if (!res.ok || !j.ok) throw new Error(j.error ?? `HTTP ${res.status}`); window.location.reload(); } catch (err) { setRereadError(err instanceof Error ? err.message : String(err)); setRereading(null); } }; // READ THE THREAD AGAIN (lane line-rerun): every synthesized piece's next reading, a new take unpicked, played as // it lands -- `posts screen … read` / `posts narrate … --take --thread` as a umtool job (op thread-read). const playing = pickedTake(entry) as { read?: { kind?: string }; parts?: Array<{ role?: string; take?: string; reading?: number; tuning?: Tuning; tuningAsked?: true | "preset" }> } | null; // HIS piece (review 2 #4): the thread's Tune starts from how his words were last read and keeps for his character -- // never another piece's (a parent's, a screen speaker's). const postPart = threadTuneMadeOf(playing?.parts) as { tuning: Tuning | null; tuningAsked?: unknown } | null; const readsAs = useKeepForCharacter(project, entry.id, "post", postPart); const [autoplay, setAutoplay] = useAutoPlay(); const [again, setAgain] = useState<{ state: string; waiting?: string | null; error?: string | null; said?: string | null } | null>(null); const poll = useRef | null>(null); const pressing = useRef(false); useEffect(() => () => { if (poll.current) clearTimeout(poll.current); }, []); const readThreadAgain = async (tuning: Tuning | null) => { if (!project || again?.state === "running" || pressing.current) return; pressing.current = true; try { const res = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "thread-read", id: entry.id, reading: "next", ...(tuning ? { tuning } : {}) }) }).catch(() => null); const j = res ? ((await res.json().catch(() => ({}))) as { job?: { id: string }; error?: string; busy?: boolean }) : { error: "the bench is out of reach" }; if (!res?.ok || !j.job) { // Busy: said, the running one's state kept. if (j.busy) setAgain((a) => (a?.state === "running" ? a : { state: "idle", said: j.error ?? "busy" })); else setAgain({ state: "failed", error: j.error ?? `HTTP ${res?.status ?? "?"}` }); return; } setAgain({ state: "running" }); const jobId = j.job.id; let misses = 0; const tick = async () => { const r = await fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&screenJob=${encodeURIComponent(jobId)}`, { cache: "no-store" }).catch(() => null); const v = r ? ((await r.json().catch(() => ({}))) as { state?: string; error?: string | null; waiting?: string; entry?: Entry | null; token?: string | null; result?: { take?: { file: string; n: number } | null; why?: string } | null }) : null; misses = r ? 0 : misses + 1; // Still running; the bench out of reach (up to five times running) is asked again. A lost job (404, no state) failed. if ((r && v?.state === "running") || (!r && misses < 5)) { setAgain({ state: "running", waiting: v?.waiting ?? null }); poll.current = setTimeout(tick, 1500); return; } if (!r || !v?.state) return setAgain({ state: "failed", error: v?.error ?? `the job is gone${r ? ` (HTTP ${r.status})` : ""}` }); const made = v.state === "done" ? v.result?.take ?? null : null; setAgain({ state: v.state === "done" ? "done" : "failed", error: v.error ?? null, said: v.state === "done" ? (made ? `take ${made.n} made, not picked` : `nothing made -- ${v.result?.why ?? "the read already says this"}`) : null }); // Only the take THIS job made plays (review 1, finding 2). if (made && autoplay) playNow(`/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(made.file)}`); if (v.entry) onEntry?.(v.entry, v.token ?? null); }; poll.current = setTimeout(tick, 800); } finally { pressing.current = false; } }; const startOf = (part: number) => plan.follow?.blocks.find((b) => b.part === part)?.start ?? null; const setOwn = (patch: Thread) => setEntry((e) => { const next: Record = { ...((e.thread as Thread | undefined) ?? {}), ...patch }; for (const [kk, v] of Object.entries(next)) if (v === undefined || v === null || v === "") delete next[kk]; const out = { ...e }; if (Object.keys(next).length) out.thread = next; else delete out.thread; return out; }); const parents = Array.isArray(entry.parents) ? entry.parents : []; const parentMode = (i: number) => { const p = own?.parent; return Array.isArray(p) ? p[i] ?? "" : typeof p === "string" ? p : ""; }; const setParent = (i: number, v: string) => { const list = parents.map((_, j) => parentMode(j) || "auto"); list[i] = v || "auto"; setOwn({ parent: list.every((m) => m === "auto") ? undefined : list.length === 1 ? list[0] : list }); }; const modeShown = (scope: string) => layout.tiles.find((t: { scope: string; mode: string }) => t.scope === scope)?.mode ?? "—"; const num = (key: "shrink" | "dim" | "seconds" | "pan", label: string, step: number) => ( ); if (!parents.length && !entry.quoted && !sceneTiles.length) return null; return (

thread read

{layout.on ? "the card draws the conversation: each post read is shown in full, then shrinks and dims as the next comes in" : roles.length ? "his words only: the posts it answers are context" : "not narrated: the card as it is"}
{project && playing?.read?.kind === "thread" && (
void readThreadAgain(t)} madeWith={postPart?.tuning ?? null} lineOwn={pieceOwnOf(playing, "post") as Tuning | null} staleHref={project && readsAs.character ? readsHref(project, { state: "stale", character: readsAs.character.id }) : null} baseline={readsAs.baseline} madeOwn={readsAs.madeOwn} refreshBaseline={readsAs.refresh} baselineError={readsAs.error} onRetryBaseline={readsAs.retry} character={readsAs.character} keepForCharacter={readsAs.keepForCharacter} error={again?.state === "failed" ? again.error ?? "failed" : null} note={again?.said ?? null} autoplay={autoplay} onAutoplay={setAutoplay} />
)} {sceneTiles.length > 0 && (

one scene with the item before:{" "} {sceneTiles.map((t, i) => ( {i ? ", " : ""} {t.ref?.redact ? "a post" : `@${t.ref?.handle ?? "?"}`} {t.action === "keep" ? "stays on top (context)" : "collapses away"} ))}

)} {pieces.length > 0 && (
    {pieces.map((p, i) => { const at = startOf(p.parts[0]); const words = p.parts.map((n) => take?.parts?.[n]?.text ?? "").join(" ").trim(); return (
  1. {project && p.role && (p.role === "quoted" || p.role.startsWith("parent:")) && ( )}
  2. ); })}
)}
{parents.map((_, i) => ( ))} {entry.quoted && ( )} {num("shrink", "shrink", 0.02)} {num("dim", "dim", 0.05)} {num("seconds", "over", 0.1)} {num("pan", "pan", 0.1)}

full: in full while read · excerpt: only what is read · context: small and dim · carry: the item before, giving way · hidden: not drawn (never read). Hidden and excerpt redraw the card once saved.

{rereadError && (

{rereadError}

)} {errors.length > 0 && (
    {errors.map((er, i) => (
  • {er}
  • ))}
)}
); }