commit b028855a0234fe94662ceb858a3922f6f2b93bc2 parent ae84839f11cf8d89ff4656fb7c196e3786188bef Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Tue, 17 Nov 2026 16:00:18 -0500 the Reads page: Find, Replace in two scopes, Re-read on the queue, Listen through -- and the links to it /projects/<p>/reads (ReadsPage, ReadsPanel; /api/report/reads runs `umtool reads`'s own commands in-process): every line a voice reads with what it says, its state and a Play; filters All / Stale / a character; Find over the spoken text only (case, whole word, a count of matches and lines); Replace with These reads (a preview list, line before -> after, each line ticked; what is not changed and why; what goes; what the build would refuse; Apply; Undo the replace) or Everywhere, from now on (the entry, the reads it makes stale, the cards it does not reach; whole words, said where it applies; Remove the entry); Re-read N changed lines (or the ticked ones) on the app's queue, its rows filling in, the reason they wait in one line, Stop, Retry; Listen through the re-reads, each with what played before, Pick new / Pick before, play in the cut; Pick every new read. Every control has an aria-label; no lead paragraphs. Links: the preset's and the Voices page's "made with other settings" lines (Re-read them / Reads, at that character's stale reads), the bench's Keep note beside "made with other settings", the post bench and the Voices page header. The bench's single-post take answers 409, in a sentence, while that post's re-read runs in the queue. e2e: reads-find.spec.ts and its fixture (reports/reads-fixture: posts, a recorded read, a card). Co-Authored-By: Claude <noreply@anthropic.com> Diffstat:
19 files changed, 760 insertions(+), 9 deletions(-)
diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -409,6 +409,10 @@ async function postHere(request: Request) { // ONE READ OF A POST AT A TIME: a second press while one is made is refused, never asked twice. The marker is // TAKEN before the editor is asked (created exclusively: two presses at once cannot both take it; review 1, // finding 4); a marker whose job ended, or one never given a job within two minutes, is stale and taken over. + // ITS RE-READ IN THE READS QUEUE (lane reads-find): while that step runs, a press here would make a second read + // of the same post -- said, as a sentence, never asked. + const queued = await (await import("@/lib/report/readsQueue.mjs")).rereadRunningFor(r.project.id, id, { queueDir: (await import("@/lib/queue/runner")).queueDir() }).catch(() => null); + if (queued) return Response.json({ error: `this post is being re-read by the Reads queue (${queued.qid}): read it again when that lands`, busy: true }, { status: 409 }); const pendingFile = pendingFileOf(r.project.dir, e); await mkdir(path.dirname(pendingFile), { recursive: true }); const claim = () => writeFile(pendingFile, JSON.stringify({ starting: true, at: new Date().toISOString() }), { flag: "wx" }).then(() => true, () => false); @@ -436,7 +440,7 @@ async function postHere(request: Request) { engine: typeof body.engine === "string" && body.engine ? body.engine : null, voice: typeof body.voice === "string" && body.voice ? body.voice : null, speed: body.speed === undefined || body.speed === null ? null : Number(body.speed), - tuning: tuned?.ok ? tuned.value : null, reading, red, slurVoice: benchSlurVoice(red), + tuning: tuned?.ok ? tuned.value : null, reading: reading === null ? null : Number(reading), red, slurVoice: benchSlurVoice(red), }); const { engine, voice, tuning, tuningAsked } = A; const pid = postIdOf(e); diff --git a/umtool/app/api/report/reads/route.ts b/umtool/app/api/report/reads/route.ts @@ -0,0 +1,117 @@ +import { projectRef } from "@/lib/projects"; +import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; +import { REPORTS_ROOT } from "@/lib/projects/core.mjs"; +import { readsCommand } from "@/lib/report/readsCli.mjs"; +import { postsCommand } from "@/lib/report/postsCli.mjs"; +import { queueView } from "@/lib/report/readsQueue.mjs"; +import { kickQueue, queueDir, queueRunnerStatus } from "@/lib/queue/runner"; + +export const dynamic = "force-dynamic"; + +// A VIDEO's READS (lane reads-find; the Reads page, components/projects/ReadsPanel.tsx): every write is the CLI's own +// command (`umtool reads …`, lib/report/readsCli.mjs), run here in-process with --json. +// +// GET ?project[&find&case=1&word=1&stale=1&character=<id>] the reads (and Find's matches), and the queue +// POST {project, op: "preview", from, to, scope: "reads"|"say", case?, word?, only?} replace --dry-run [--say-only] +// POST {project, op: "replace", …the same} replace (These reads: one undo point; Everywhere: an entry) +// POST {project, op: "undo"} reads undo (the newest replace) +// POST {project, op: "unsay", word} posts say remove <word> (an Everywhere taken back) +// POST {project, op: "reread", only?} reads reread [--only] -- steps of the app's queue +// POST {project, op: "stop"} reads queue --stop +// POST {project, op: "retry", read} reads queue --retry <read> +// POST {project, op: "pick", which: "new"|"old", only?} reads pick +const headers = { "cache-control": "no-store" }; + +async function cli(args: string[], { posts = false }: { posts?: boolean } = {}) { + const out: string[] = []; + const err: string[] = []; + const code = posts + ? await postsCommand([...args, "--json"], { root: REPORTS_ROOT, out: (s: string) => out.push(s), err: (s: string) => err.push(s) }) + : await readsCommand([...args, "--json"], { root: REPORTS_ROOT, out: (s: string) => out.push(s), err: (s: string) => err.push(s), queueDir: queueDir() }); + let json: Record<string, unknown> | null = null; + try { + json = JSON.parse(out.join("\n") || "null"); + } catch { + json = null; + } + return { code, json, error: code === 0 ? null : (json?.error as string | undefined) ?? (err.join("\n") || "refused") }; +} + +/** The queue as the page shows it, its waiting sentence completed with the app's own runner (its job runner busy). */ +async function queueOf(project: { id: string; dir: string }) { + const v = await queueView(project, { reportsRoot: REPORTS_ROOT, queueDir: queueDir() }); + const st = queueRunnerStatus(); + const waiting = v.waiting ?? (v.counts.waiting && st.waiting ? `waiting: ${st.waiting}` : v.counts.waiting && !st.armed ? "waiting: this umtool app does not run the queue (UMTOOL_QUEUE_RUNNER is off) -- the app that holds the lease runs it" : null); + return { ...v, waiting }; +} + +export async function GET(request: Request) { + const url = new URL(request.url); + const project = await projectRef(String(url.searchParams.get("project") ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const q = url.searchParams; + const args = [project.id]; + const find = q.get("find"); + if (find && find.trim()) args.push("--find", find); + if (q.get("case") === "1") args.push("--case"); + if (q.get("word") === "1") args.push("--word"); + if (q.get("stale") === "1") args.push("--stale"); + const character = q.get("character"); + if (character && /^[a-z0-9][a-z0-9_-]{0,63}$/i.test(character)) args.push("--character", character); + try { + const r = await cli(args); + if (r.code !== 0) return Response.json({ error: r.error }, { status: 400, headers }); + return Response.json({ ...r.json, queue: await queueOf(project) }, { headers }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500, headers }); + } +} + +const idsOf = (v: unknown) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string" && /^[a-z0-9][a-z0-9:/_-]{0,80}$/i.test(x)) : []); + +export async function POST(request: Request) { + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); + const refused = refuseCaller(request, "/api/report/reads"); + if (refused) return refused; + const b = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!b) return Response.json({ error: "bad json" }, { status: 400 }); + const project = await projectRef(String(b.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const op = String(b.op ?? ""); + const only = idsOf(b.only); + const onlyArgs = only.length ? ["--only", only.join(",")] : []; + let args: string[] | null = null; + let posts = false; + if (op === "preview" || op === "replace") { + const from = typeof b.from === "string" ? b.from : ""; + const to = typeof b.to === "string" ? b.to : ""; + if (!from.trim()) return Response.json({ error: "find what? (the words to replace)" }, { status: 400 }); + args = [project.id, "replace", from, to, ...(b.case === true ? ["--case"] : []), ...(b.word === true ? ["--word"] : []), ...(b.scope === "say" ? ["--say-only"] : []), ...onlyArgs, ...(op === "preview" ? ["--dry-run"] : [])]; + if (b.scope === "say" && b.word !== true) return Response.json({ error: "Everywhere, from now on matches whole words only (a pronunciation entry): turn Whole word on" }, { status: 400, headers }); + } else if (op === "undo") args = [project.id, "undo"]; + else if (op === "unsay") { + const word = typeof b.word === "string" ? b.word.trim() : ""; + if (!word) return Response.json({ error: "which entry?" }, { status: 400 }); + args = ["say", project.id, "remove", word]; + posts = true; + } else if (op === "reread") args = [project.id, "reread", ...onlyArgs]; + else if (op === "stop") args = [project.id, "queue", "--stop"]; + else if (op === "retry") { + const read = idsOf([b.read])[0]; + if (!read) return Response.json({ error: "which read?" }, { status: 400 }); + args = [project.id, "queue", "--retry", read]; + } else if (op === "pick") { + if (b.which !== "new" && b.which !== "old") return Response.json({ error: "pick which: new or old" }, { status: 400 }); + args = [project.id, "pick", `--${b.which}`, ...onlyArgs]; + } else return Response.json({ error: `no op ${op}` }, { status: 400 }); + try { + const r = await cli(args, { posts }); + if (r.code !== 0) return Response.json({ error: r.error }, { status: 400, headers }); + if (op === "reread" || op === "retry") kickQueue(); + return Response.json({ ok: true, ...r.json, queue: await queueOf(project) }, { headers }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500, headers }); + } +} diff --git a/umtool/components/projects/CharacterTuning.tsx b/umtool/components/projects/CharacterTuning.tsx @@ -3,7 +3,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; -import { postBenchHref } from "@/lib/hrefs"; +import { postBenchHref, readsHref } from "@/lib/hrefs"; import { ORPHEUS_TUNING_NAMED, ORPHEUS_TUNING_NAMES, TTS_TUNING_RANGES, ttsTuningNameOf, type TtsTuningName } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; // --------------------------------------------------------------------------- @@ -320,6 +320,8 @@ export function CharacterTuning({ <a href={postBenchHref(project, x)} className="ink-link font-mono" data-tuning-stale-item={x}>{x}</a> </span> ))} + {" · "} + <a href={readsHref(project, { state: "stale", character: id })} className="ink-link" data-tuning-stale-reads="" aria-label={`Re-read ${name}'s stale reads in the Reads view`}>Re-read them</a> </span> ) : ( <span className="text-muted">no read by this character was made with other settings</span> diff --git a/umtool/components/projects/PostBenchPage.tsx b/umtool/components/projects/PostBenchPage.tsx @@ -1,7 +1,7 @@ import { notFound } from "next/navigation"; import AppShell from "@/components/shell/AppShell"; import PostBench from "./PostBench"; -import { projectHref, playHref } from "@/lib/hrefs"; +import { projectHref, playHref, readsHref } from "@/lib/hrefs"; import PlayLink from "./PlayLink"; import { postBenchData } from "@/lib/report/postBenchData"; import type { ProjectRef } from "@/lib/project-types"; @@ -39,6 +39,8 @@ async function postBenchBody({ project, id, search }: { project: ProjectRef; id: <p className="mb-2 flex flex-wrap items-center gap-2 text-[12px]" data-post-bench-scope="cut"> <span className="micro">edits go to</span> <span className="font-medium text-text">the draft</span> + <span className="text-muted">·</span> + <a href={readsHref(project.id)} className="ink-link" data-post-bench-reads="" aria-label="Every read of this video: find, replace, re-read">Reads</a> </p> <PostBench project={project.id} diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx @@ -6,7 +6,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import Waveform from "@/components/Waveform"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; -import { postBenchHref } from "@/lib/hrefs"; +import { postBenchHref, readsHref } from "@/lib/hrefs"; import { CAST_CONVERT_ENGINES, CAST_CONVERT_PITCH, CAST_PITCH_ENGINES, CAST_SEMITONES_MAX, convertPitchLabel } from "umtool-report-to-video/cast"; import { POST_DERIVE_OPS, POST_NARRATION_DEFAULTS, mixPhaseAt, pickedTake, postNarrationKnobs, scriptParts, takeIdOf, takeSourceOf } from "umtool-report-to-video/post-narration"; import { projectFileMedia } from "./bench/benchMedia"; @@ -824,6 +824,7 @@ export default function PostNarrationPanel({ onReadEdited={(t) => void press(() => readEdited(t))} madeWith={madeWith} lineOwn={lineOwnOf(madeTake as Parameters<typeof lineOwnOf>[0]) 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} diff --git a/umtool/components/projects/PostThreadPanel.tsx b/umtool/components/projects/PostThreadPanel.tsx @@ -1,6 +1,7 @@ "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"; @@ -177,6 +178,7 @@ export default function PostThreadPanel({ onReadAgain={(t) => 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} diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx @@ -13,6 +13,7 @@ import TakesComparePage from "./TakesComparePage"; import NarrationPage from "./NarrationPage"; import RecordPage from "./RecordPage"; import VoicesPage from "./VoicesPage"; +import ReadsPage from "./ReadsPage"; import ReviewPage from "./ReviewPage"; import ClipDeckPage from "./ClipDeckPage"; import PlayCutPage from "./PlayCutPage"; @@ -94,6 +95,8 @@ export default async function ProjectView({ if (rest.length === 2 && rest[0] === "narration" && rest[1] === "record") return <RecordPage project={project} search={search} />; // `/projects/<project>/voices` -- each character's voice, auditions, the cast (lib/report/castCli.mjs). if (rest.length === 1 && rest[0] === "voices") return <VoicesPage project={project} search={search} />; + // `/projects/<project>/reads` -- every line a voice reads: Find, Replace, the re-read queue (lib/report/readsCli.mjs). + if (rest.length === 1 && rest[0] === "reads") return <ReadsPage project={project} search={search} />; // `/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} view={search.view} />; diff --git a/umtool/components/projects/ReadsPage.tsx b/umtool/components/projects/ReadsPage.tsx @@ -0,0 +1,29 @@ +import { notFound } from "next/navigation"; +import AppShell from "@/components/shell/AppShell"; +import ReadsPanel from "./ReadsPanel"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { projectHref } from "@/lib/hrefs"; +import type { ProjectRef } from "@/lib/project-types"; + +// THE READS PAGE (lane reads-find, S4 of plans/orpheus-retune.md): /projects/<p>/reads -- every line a synthetic voice +// reads in the video (posts, thread pieces, screen lines, cards), Find over what is SPOKEN, Replace in two stated +// scopes, the re-read queue and Listen through. A page of its own beside /voices (which is per character): this is +// per line, across posts and cards, and the bench's and the preset's "made with other settings" lines link here +// filtered (`?state=stale&character=<id>`). The routes: /api/report/reads (`umtool reads`'s own commands). +export default async function ReadsPage({ project, search = {} }: { project: ProjectRef; search?: Record<string, string | undefined> }) { + const m = await readManifest(project.dir); + if (!m) notFound(); + return ( + <div className="flex h-full flex-col"> + <AppShell + active="projects" + crumbs={[{ href: "/projects", label: "Projects" }, { href: projectHref(project.id, { tab: "cut" }), label: project.name }, { label: "reads" }]} + note="every line a voice reads · find · replace · re-read" + actions={<a href={`/projects/${project.id.split("/").map(encodeURIComponent).join("/")}/voices`} className="ink-link text-[12px]" data-reads-voices="">Voices</a>} + /> + <main className="deck-main flex-1 overflow-auto p-4"> + <ReadsPanel project={project.id} initialState={search.state === "stale" ? "stale" : "all"} initialCharacter={search.character ?? null} /> + </main> + </div> + ); +} diff --git a/umtool/components/projects/ReadsPanel.tsx b/umtool/components/projects/ReadsPanel.tsx @@ -0,0 +1,361 @@ +"use client"; + +import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { narrationHref, playHref, postBenchHref } from "@/lib/hrefs"; + +// --------------------------------------------------------------------------- +// THE READS PANEL (lane reads-find): every line a voice reads in this video, from GET /api/report/reads (`umtool +// reads <p> --json`). Find searches what is SPOKEN only; Replace offers two scopes, each previewed before it is +// applied, and neither synthesizes; Re-read queues the changed lines on the app's queue (one step per item, each the +// bench's own command); Listen through plays the re-reads one after another, each with what played before one press +// away and a Pick on either. Every button is a form and a job; nothing here asks a model. +// --------------------------------------------------------------------------- + +type Take = { index: number | null; file: string | null; key: string | null; reading: number; tuning: Record<string, number> | null; tunedBy: string | null } | null; +type Read = { + id: string; kind: "post" | "thread" | "screen" | "card"; item: string; role: string | null; character: { id: string; name: string } | null; voice: string | null; + spoken: string; said: string | null; storedAt: string | null; editable: boolean; why: string | null; state: string; because: string[]; take: Take; newTake: Take; matches?: { start: number; end: number }[]; +}; +type QueueRow = { read: string; item: string; kind: string; qid: string; state: string; error: string | null; before: Take; batch: string }; +type Queue = { rows: QueueRow[]; waiting: string | null; counts: Record<string, number>; batch: string | null }; +type View = { counts: Record<string, number>; reads: Read[]; find?: { matches: number; lines: number }; queue: Queue }; +type Line = { id: string; kind: string; item: string; before: string; after: string; creates: string | null }; +type Preview = + | { scope: "reads"; lines: Line[]; skipped: { id: string; why: string }[]; notes: Record<string, string[]>; refused: Record<string, string[]>; matches: number } + | { scope: "say"; entry: { word: string; say: string }; was: string | null; stale: { id: string }[]; cards: string[]; matches: number }; + +const KIND: Record<Read["kind"], string> = { post: "post script", thread: "thread part", screen: "screen line", card: "card narration" }; +const BECAUSE: Record<string, string> = { words: "other words", lexicon: "the lexicon", settings: "other settings", voice: "another voice" }; +const STATE_CLASS: Record<string, string> = { fresh: "text-text-2", stale: "text-doubt-text", unpicked: "text-[var(--color-sel)]", none: "text-muted", recorded: "text-muted" }; +const btn = buttonVariants({ variant: "outline", size: "sm" }); + +async function post(body: Record<string, unknown>) { + const r = await fetch("/api/report/reads", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }).catch(() => null); + const j = (await r?.json().catch(() => null)) as Record<string, unknown> | null; + if (!r?.ok) throw new Error(String(j?.error ?? (r ? `HTTP ${r.status}` : "umtool could not be reached"))); + return j ?? {}; +} + +/** A read's spoken text with its matches marked. */ +function Marked({ text, matches }: { text: string; matches?: { start: number; end: number }[] }) { + if (!matches?.length) return <>{text}</>; + const out: React.ReactNode[] = []; + let at = 0; + matches.forEach((m, i) => { + out.push(text.slice(at, m.start)); + out.push(<mark key={i} className="rounded-sm bg-[var(--color-sel)]/25 text-text" data-reads-match="">{text.slice(m.start, m.end)}</mark>); + at = m.end; + }); + out.push(text.slice(at)); + return <>{out.map((x, i) => <Fragment key={i}>{x}</Fragment>)}</>; +} + +export default function ReadsPanel({ project, initialState = "all", initialCharacter = null }: { project: string; initialState?: "all" | "stale"; initialCharacter?: string | null }) { + const [view, setView] = useState<View | null>(null); + const [error, setError] = useState<string | null>(null); + const [notice, setNotice] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + const [state, setState] = useState<"all" | "stale">(initialState); + const [character, setCharacter] = useState<string | null>(initialCharacter); + const [find, setFind] = useState(""); + const [matchCase, setMatchCase] = useState(false); + const [word, setWord] = useState(false); + const [to, setTo] = useState(""); + const [preview, setPreview] = useState<Preview | null>(null); + const [skip, setSkip] = useState<Set<string>>(new Set()); + const [undo, setUndo] = useState<{ scope: "reads" } | { scope: "say"; word: string } | null>(null); + const [ticked, setTicked] = useState<Set<string>>(new Set()); + const [characters, setCharacters] = useState<{ id: string; name: string }[]>([]); + + const load = useCallback(async () => { + const q = new URLSearchParams({ project }); + if (find.trim()) q.set("find", find); + if (matchCase) q.set("case", "1"); + if (word) q.set("word", "1"); + if (state === "stale") q.set("stale", "1"); + if (character) q.set("character", character); + const r = await fetch(`/api/report/reads?${q}`, { cache: "no-store" }).catch(() => null); + const j = (await r?.json().catch(() => null)) as (View & { error?: string }) | null; + if (!r?.ok || !j) { + setError(j?.error ?? "the reads could not be read"); + return; + } + setError(null); + setView(j); + setCharacters((had) => { + const all = new Map(had.map((c) => [c.id, c])); + for (const x of j.reads) if (x.character) all.set(x.character.id, x.character); + return [...all.values()].sort((a, b) => a.name.localeCompare(b.name)); + }); + }, [project, find, matchCase, word, state, character]); + useEffect(() => { + const t = setTimeout(() => void load(), find ? 250 : 0); + return () => clearTimeout(t); + }, [load, find]); + // The queue fills in as each re-read lands: polled while anything waits or runs. + const going = !!view && (view.queue.counts.waiting > 0 || view.queue.counts.running > 0); + useEffect(() => { + if (!going) return; + const t = setInterval(() => void load(), 2500); + return () => clearInterval(t); + }, [going, load]); + // A new find or replace text: the preview is of other words now. + useEffect(() => setPreview(null), [find, to, matchCase, word]); + + const run = async (what: () => Promise<void>) => { + if (busy) return; + setBusy(true); + setError(null); + setNotice(null); + try { + await what(); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + void load(); + } + }; + const ask = (scope: "reads" | "say") => run(async () => { + const j = await post({ project, op: "preview", from: find, to, scope, case: matchCase, word }); + setPreview({ ...(j as object), scope } as Preview); + setSkip(new Set()); + }); + const apply = () => run(async () => { + if (!preview) return; + const only = preview.scope === "reads" ? preview.lines.map((l) => l.id).filter((id) => !skip.has(id)) : []; + if (preview.scope === "reads" && !only.length) throw new Error("no line is ticked"); + await post({ project, op: "replace", from: find, to, scope: preview.scope, case: matchCase, word, ...(preview.scope === "reads" ? { only } : {}) }); + setUndo(preview.scope === "reads" ? { scope: "reads" } : { scope: "say", word: preview.entry.word }); + setNotice(preview.scope === "reads" ? `rewritten: ${only.length} read${only.length === 1 ? "" : "s"} (the shown text untouched) -- they are stale now` : `"${preview.entry.word}" is said "${preview.entry.say}" in every read of a post now -- ${preview.stale.length} read${preview.stale.length === 1 ? "" : "s"} stale`); + setPreview(null); + }); + const takeBack = () => run(async () => { + if (!undo) return; + await post(undo.scope === "reads" ? { project, op: "undo" } : { project, op: "unsay", word: undo.word }); + setUndo(null); + setNotice(undo.scope === "reads" ? "the replace is taken back: every line as it was" : "the pronunciation entry is removed"); + }); + + const reads = useMemo(() => view?.reads ?? [], [view]); + const changed = reads.filter((r) => r.state === "stale"); + const toQueue = ticked.size ? [...ticked] : changed.map((r) => r.id); + const reread = () => run(async () => { + const j = (await post({ project, op: "reread", ...(ticked.size ? { only: [...ticked] } : {}) })) as { steps?: { reads: string[] }[]; skipped?: { id: string; why: string }[] }; + const n = (j.steps ?? []).reduce((a, s) => a + s.reads.length, 0); + setNotice(n ? `${n} line${n === 1 ? "" : "s"} queued, one item at a time, in cut order -- each joins its list unpicked` : `nothing queued${j.skipped?.length ? `: ${j.skipped.map((s) => `${s.id} (${s.why})`).join(", ")}` : ""}`); + setTicked(new Set()); + }); + + // ---- Listen through: the newest batch's re-reads, played one after another ---- + const queue = view?.queue ?? null; + const batchRows = (queue?.rows ?? []).filter((r) => r.batch === queue?.batch); + const byId = useMemo(() => new Map(reads.map((r) => [r.id, r])), [reads]); + const audioOf = (item: string, t: Take) => (!t ? null : t.key ? `/api/report/narration/audio?${new URLSearchParams({ project, card: item, key: t.key })}` : t.file ? `/api/report/file?${new URLSearchParams({ project, path: t.file })}` : null); + const newOf = (q: QueueRow) => { + const r = byId.get(q.read); + return r ? (r.state === "unpicked" ? r.newTake : r.take) : null; + }; + const player = useRef<HTMLAudioElement | null>(null); + const [playing, setPlaying] = useState<string | null>(null); + const playOne = (key: string, url: string | null, then?: () => void) => { + player.current?.pause(); + if (!url) return then?.(); + const a = new Audio(url); + player.current = a; + setPlaying(key); + a.onended = () => { + setPlaying(null); + then?.(); + }; + void a.play().catch(() => setPlaying(null)); + }; + const listenThrough = () => { + const list = batchRows.filter((q) => q.state === "done").map((q) => ({ key: `${q.read}:new`, url: audioOf(q.item, newOf(q)) })).filter((x) => x.url); + const next = (i: number) => (i < list.length ? playOne(list[i].key, list[i].url, () => next(i + 1)) : setPlaying(null)); + next(0); + }; + const pick = (which: "new" | "old", only?: string[]) => run(async () => { + const j = (await post({ project, op: "pick", which, ...(only ? { only } : {}) })) as { picked?: { item: string }[] }; + setNotice(`picked (${which === "new" ? "the new reads" : "what played before"}): ${(j.picked ?? []).map((x) => x.item).join(", ")}`); + }); + + if (!view) return <p className="text-[12px] text-muted" data-reads-loading="">{error ?? "reading…"}</p>; + const c = view.counts; + const unpicked = reads.filter((r) => r.state === "unpicked").length; + + return ( + <div className="space-y-4 text-[12.5px]" data-reads={project}> + <div className="flex flex-wrap items-center gap-2" data-reads-filters=""> + <span className="tabular-nums text-text-2" data-reads-counts={JSON.stringify(c)}> + {Object.entries(c).filter(([, n]) => n).map(([k, n]) => `${n} ${k}`).join(" · ") || "no reads"} + </span> + <div className="flex gap-1" role="group" aria-label="Which reads"> + {(["all", "stale"] as const).map((s) => ( + <button key={s} type="button" className={buttonVariants({ variant: state === s ? "pressed" : "outline", size: "sm" })} aria-pressed={state === s} aria-label={s === "all" ? "Show every read" : "Show the stale reads"} data-reads-state={s} onClick={() => setState(s)}> + {s === "all" ? "All" : "Stale"} + </button> + ))} + </div> + <select className="rounded border border-seam bg-transparent px-1 py-0.5" aria-label="Character" value={character ?? ""} onChange={(e) => setCharacter(e.target.value || null)} data-reads-character=""> + <option value="">every character</option> + {characters.map((x) => <option key={x.id} value={x.id}>{x.name}</option>)} + {character && !characters.some((x) => x.id === character) && <option value={character}>{character}</option>} + </select> + </div> + + <form className="flex flex-wrap items-center gap-2" onSubmit={(e) => e.preventDefault()} data-reads-find-form=""> + <input type="search" value={find} onChange={(e) => setFind(e.target.value)} placeholder="find in what is said" aria-label="Find in spoken text" className="min-w-48 flex-1 rounded border border-seam bg-transparent px-2 py-1" data-reads-find="" /> + <label className="flex items-center gap-1"><input type="checkbox" checked={matchCase} onChange={(e) => setMatchCase(e.target.checked)} aria-label="Match case" data-reads-case="" /> case</label> + <label className="flex items-center gap-1"><input type="checkbox" checked={word} onChange={(e) => setWord(e.target.checked)} aria-label="Whole word" data-reads-word="" /> whole word</label> + {find.trim() && ( + <span className="tabular-nums text-text-2" data-reads-found={view.find?.matches ?? 0}> + {view.find?.matches ?? 0} match{view.find?.matches === 1 ? "" : "es"} in {view.find?.lines ?? 0} line{view.find?.lines === 1 ? "" : "s"} · spoken text only + </span> + )} + </form> + + {find.trim() && ( + <div className="flex flex-wrap items-center gap-2" data-reads-replace-form=""> + <input type="text" value={to} onChange={(e) => setTo(e.target.value)} placeholder="say instead" aria-label="Replace with" className="min-w-48 flex-1 rounded border border-seam bg-transparent px-2 py-1" data-reads-to="" /> + <button type="button" className={btn} disabled={busy || !view.find?.matches} onClick={() => void ask("reads")} aria-label="Replace in these reads" data-reads-scope="reads" title="the matched lines' spoken text, one undo point; the shown text untouched">These reads</button> + <button type="button" className={btn} disabled={busy || !to.trim() || !word} onClick={() => void ask("say")} aria-label="Add a pronunciation entry" data-reads-scope="say">Everywhere, from now on</button> + <span className="text-[11px] text-muted" data-reads-say-limit="">{word ? "Everywhere: whole words, every read of a post; never a card" : "Everywhere needs Whole word (a pronunciation entry is whole words)"}</span> + </div> + )} + + {preview && ( + <div className="rounded border border-seam p-2" data-reads-preview={preview.scope}> + {preview.scope === "reads" ? ( + <> + <p className="m-0 mb-1 text-text">These reads: {preview.lines.length} line{preview.lines.length === 1 ? "" : "s"} rewritten in what is SAID, one undo point -- the shown text is never changed; nothing is read until you press Re-read</p> + <ul className="m-0 list-none space-y-1 p-0"> + {preview.lines.map((l) => ( + <li key={l.id} className="flex flex-wrap items-baseline gap-2" data-reads-preview-line={l.id}> + <input type="checkbox" checked={!skip.has(l.id)} onChange={(e) => setSkip((s) => { const n = new Set(s); if (e.target.checked) n.delete(l.id); else n.add(l.id); return n; })} aria-label={`Rewrite ${l.id}`} /> + <span className="font-mono">{l.id}</span> + <span className="text-text-2 line-through decoration-1">{l.before}</span> + <span>→</span> + <span className="text-text">{l.after}</span> + {l.creates && <span className="text-[11px] text-muted">({l.creates})</span>} + {(preview.notes[l.item] ?? []).map((n) => <span key={n} className="text-[11px] text-doubt-text" data-reads-preview-note="">{n}</span>)} + </li> + ))} + {preview.skipped.map((s) => ( + <li key={s.id} className="text-[11px] text-muted" data-reads-preview-skipped={s.id}><span className="font-mono">{s.id}</span>: not changed -- {s.why}</li> + ))} + {Object.entries(preview.refused).map(([i, es]) => ( + <li key={i} className="text-[11px] text-doubt-text" data-reads-preview-refused={i}>{i}: refused -- {es.join("; ")} (untick it)</li> + ))} + </ul> + </> + ) : ( + <p className="m-0 text-text" data-reads-preview-say=""> + Everywhere, from now on: “{preview.entry.word}” said “{preview.entry.say}”{preview.was ? ` (now "${preview.was}")` : ""} in every read of a post, present and future (a pronunciation entry) -- {preview.stale.length} read{preview.stale.length === 1 ? "" : "s"} made stale{preview.stale.length ? `: ${preview.stale.map((s) => s.id).join(", ")}` : ""} + {preview.cards.length > 0 && <span className="block text-[11px] text-muted" data-reads-preview-cards="">cards are not said through the lexicon: use These reads for {preview.cards.join(", ")}</span>} + </p> + )} + <div className="mt-2 flex gap-2"> + <button type="button" className={buttonVariants({ variant: "go", size: "sm" })} disabled={busy || (preview.scope === "reads" && Object.keys(preview.refused).some((i) => preview.lines.some((l) => l.item === i && !skip.has(l.id))))} onClick={() => void apply()} aria-label="Apply the replace" data-reads-apply="">Apply</button> + <button type="button" className={btn} onClick={() => setPreview(null)} aria-label="Close the preview">Close</button> + </div> + </div> + )} + + {(notice || error || undo) && ( + <p className="m-0 flex flex-wrap items-center gap-2" data-reads-notice=""> + {notice && <span className="text-text-2">{notice}</span>} + {error && <span className="text-doubt-text" data-reads-error="">{error}</span>} + {undo && <button type="button" className="ink-link" disabled={busy} onClick={() => void takeBack()} aria-label={undo.scope === "reads" ? "Undo the replace" : "Remove the pronunciation entry"} data-reads-undo={undo.scope}>{undo.scope === "reads" ? "Undo the replace" : "Remove the entry"}</button>} + </p> + )} + + <div className="flex flex-wrap items-center gap-2" data-reads-reread-bar=""> + <button type="button" className={buttonVariants({ variant: "go", size: "sm" })} disabled={busy || !toQueue.length} onClick={() => void reread()} aria-label={`Re-read ${toQueue.length} changed line${toQueue.length === 1 ? "" : "s"}`} data-reads-reread={toQueue.length}> + Re-read {toQueue.length} {ticked.size ? "ticked" : "changed"} line{toQueue.length === 1 ? "" : "s"} + </button> + {unpicked > 0 && <button type="button" className={btn} disabled={busy} onClick={() => void pick("new")} aria-label="Pick every new read" data-reads-pick-all="">Pick every new read ({unpicked})</button>} + </div> + + {queue && queue.rows.length > 0 && ( + <div className="rounded border border-seam p-2" data-reads-queue={queue.batch ?? ""}> + <div className="mb-1 flex flex-wrap items-center gap-2"> + <span className="tabular-nums text-text-2" data-reads-queue-counts={JSON.stringify(queue.counts)}>{Object.entries(queue.counts).filter(([, n]) => n).map(([k, n]) => `${n} ${k}`).join(" · ")}</span> + {(queue.counts.waiting > 0) && <button type="button" className={btn} disabled={busy} onClick={() => void run(async () => { await post({ project, op: "stop" }); })} aria-label="Stop the re-reads not started" data-reads-stop="">Stop</button>} + {batchRows.some((q) => q.state === "done") && <button type="button" className={btn} onClick={listenThrough} aria-label="Listen through the re-read lines" data-reads-listen="">Listen through</button>} + </div> + {queue.waiting && <p className="m-0 mb-1 text-[11.5px] text-doubt-text" data-reads-waiting="">{queue.waiting}</p>} + <ul className="m-0 list-none space-y-1 p-0"> + {queue.rows.map((q) => { + const fresh = newOf(q); + return ( + <li key={`${q.batch}:${q.read}`} className="flex flex-wrap items-center gap-2" data-reads-queue-row={q.read} data-state={q.state}> + <span className={cn("w-16", q.state === "failed" ? "text-doubt-text" : "text-text-2")}>{q.state}</span> + <span className="font-mono">{q.read}</span> + {q.error && <span className="text-[11px] text-doubt-text" data-reads-queue-error="">{q.error}</span>} + {(q.state === "failed" || q.state === "stopped") && <button type="button" className="ink-link" disabled={busy} onClick={() => void run(async () => { await post({ project, op: "retry", read: q.read }); })} aria-label={`Retry ${q.read}`} data-reads-retry={q.read}>Retry</button>} + {q.state === "done" && q.batch === queue.batch && ( + <> + <button type="button" className="ink-link" onClick={() => playOne(`${q.read}:new`, audioOf(q.item, fresh))} aria-label={`Play the new read of ${q.read}`} data-reads-play-new={q.read} data-playing={playing === `${q.read}:new` ? "1" : undefined}>▶ new</button> + <button type="button" className="ink-link" disabled={!q.before} onClick={() => playOne(`${q.read}:old`, audioOf(q.item, q.before))} aria-label={`Play what ${q.read} said before`} data-reads-play-old={q.read} data-playing={playing === `${q.read}:old` ? "1" : undefined}>▶ before</button> + <button type="button" className="ink-link" disabled={busy || byId.get(q.read)?.state !== "unpicked"} onClick={() => void pick("new", [q.read])} aria-label={`Pick the new read of ${q.read}`} data-reads-pick-new={q.read}>Pick new</button> + <button type="button" className="ink-link" disabled={busy || !q.before} onClick={() => void pick("old", [q.read])} aria-label={`Pick what ${q.read} said before`} data-reads-pick-old={q.read}>Pick before</button> + <a className="ink-link" href={playHref(project, { clip: q.item })} aria-label={`Play ${q.item} in the cut`} data-reads-play-cut={q.item}>play in the cut</a> + </> + )} + </li> + ); + })} + </ul> + </div> + )} + + <table className="w-full border-collapse" data-reads-rows={reads.length}> + <thead> + <tr className="text-left text-[11px] text-muted"> + <th className="px-1 font-normal"><span className="sr-only">re-read</span></th> + <th className="px-2 font-normal">read</th> + <th className="px-2 font-normal">character</th> + <th className="px-2 font-normal">what is said</th> + <th className="px-2 font-normal">state</th> + <th className="px-2 font-normal">plays</th> + </tr> + </thead> + <tbody> + {reads.map((r) => { + const cell = "border-t border-seam px-2 py-1 align-top"; + const href = r.kind === "card" ? narrationHref(project) : postBenchHref(project, r.item); + const url = audioOf(r.item, r.take); + return ( + <tr key={r.id} data-read={r.id} data-read-state={r.state}> + <td className={cn(cell, "px-1")}> + {(r.state === "stale" || r.state === "unpicked" || r.state === "none") && ( + <input type="checkbox" checked={ticked.has(r.id)} onChange={(e) => setTicked((s) => { const n = new Set(s); if (e.target.checked) n.add(r.id); else n.delete(r.id); return n; })} aria-label={`Re-read ${r.id}`} data-read-tick={r.id} /> + )} + </td> + <td className={cell}> + <a href={href} className="ink-link font-mono" aria-label={`${r.id}'s bench`}>{r.id}</a> + <span className="block text-[11px] text-muted">{KIND[r.kind]}</span> + </td> + <td className={cn(cell, "text-text-2")}>{r.character?.name ?? <span className="text-muted">—</span>}</td> + <td className={cn(cell, "max-w-[42ch]")} data-read-spoken={r.id}> + <Marked text={r.spoken} matches={r.matches} /> + {r.said && r.said !== r.spoken && <span className="block text-[11px] text-muted">said as: {r.said}</span>} + {r.kind === "card" && r.state === "stale" && r.because.includes("words") && <span className="block text-[11px] text-doubt-text">its words changed with the replace: Re-read makes them play</span>} + </td> + <td className={cn(cell, STATE_CLASS[r.state])} data-read-because={r.because.join(",")}> + {r.state}{r.because.length ? <span className="block text-[11px]">{r.because.map((b) => BECAUSE[b] ?? b).join(", ")}</span> : null} + </td> + <td className={cell}> + {url ? <button type="button" className="ink-link" onClick={() => playOne(`${r.id}:take`, url)} aria-label={`Play what ${r.id} plays now`} data-read-play={r.id}>▶ play</button> : <span className="text-muted">—</span>} + </td> + </tr> + ); + })} + </tbody> + </table> + </div> + ); +} diff --git a/umtool/components/projects/ScreenLineVoice.tsx b/umtool/components/projects/ScreenLineVoice.tsx @@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { useMic, ls } from "./useMic"; +import { readsHref } from "@/lib/hrefs"; import ReadAgain, { playNow, useAutoPlay, type Tuning } from "./read/ReadAgain"; import { useKeepForCharacter } from "./read/keepForCharacter"; import { pieceOwnOf } from "@/lib/report/tuneAsk.mjs"; @@ -251,6 +252,7 @@ export function ScreenLineVoice({ role, n, voice, dirty, options, chosen, onChoo onReadEdited={(t) => void voice.readLine(role, t)} madeWith={playedLine?.tuning ?? null} lineOwn={playedLine?.own ?? null} + staleHref={voice.project && readsAs.character ? readsHref(voice.project, { state: "stale", character: readsAs.character.id }) : null} baseline={readsAs.baseline} madeOwn={readsAs.madeOwn} refreshBaseline={readsAs.refresh} diff --git a/umtool/components/projects/VoicesPage.tsx b/umtool/components/projects/VoicesPage.tsx @@ -2,7 +2,7 @@ import { notFound } from "next/navigation"; import AppShell from "@/components/shell/AppShell"; import VoicesPanel from "./VoicesPanel"; import { readManifest } from "@/lib/projects/report.mjs"; -import { projectHref } from "@/lib/hrefs"; +import { projectHref, readsHref } from "@/lib/hrefs"; import type { ProjectRef } from "@/lib/project-types"; // THE VOICES PAGE (operator, 6 Nov 2026: "pick different voices for different characters, and in UI alone be able @@ -25,6 +25,7 @@ export default async function VoicesPage({ project, search = {} }: { project: Pr active="projects" crumbs={[{ href: "/projects", label: "Projects" }, { href: projectHref(project.id, { tab: "cut" }), label: project.name }, { label: "voices" }]} note="each character's voice · auditions · the cast" + actions={<a href={readsHref(project.id)} className="ink-link text-[12px]" data-voices-reads="" aria-label="Every read of this video: find, replace, re-read">Reads</a>} /> <main className="deck-main flex-1 overflow-auto p-4"> <VoicesPanel project={project.id} posts={posts} initialWho={search.who ?? null} /> diff --git a/umtool/components/projects/VoicesPanel.tsx b/umtool/components/projects/VoicesPanel.tsx @@ -3,7 +3,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; -import { jobsHref, postBenchHref } from "@/lib/hrefs"; +import { jobsHref, postBenchHref, readsHref } from "@/lib/hrefs"; import { PresetEditor, ProjectCharacters, recordedWords, type ItemCharacter, type PresetCharacter } from "./CharacterPresets"; import type { StaleRead } from "./CharacterTuning"; import { ProposedCharacters, type Proposal } from "./ProposedCharacters"; @@ -346,7 +346,8 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro )} {c.stale && c.stale.length > 0 && ( <div className="text-[11px] text-doubt-text" data-voice-stale={new Set(c.stale.map((d) => d.id)).size} title={c.stale.map((d) => `${d.id} ${d.role}: made with temperature ${d.made.temperature}, top_p ${d.made.top_p}, repeat penalty ${d.made.repeat_penalty}, takes ${d.made.takes}`).join("\n")}> - {new Set(c.stale.map((d) => d.id)).size} made with other settings + {new Set(c.stale.map((d) => d.id)).size} made with other settings{" · "} + <a href={readsHref(project, { state: "stale", character: c.character?.id ?? null })} className="ink-link" data-voice-stale-reads={c.character?.id ?? ""} aria-label={`${c.name}'s stale reads in the Reads view`}>Reads</a> </div> )} </td> diff --git a/umtool/components/projects/read/ReadAgain.tsx b/umtool/components/projects/read/ReadAgain.tsx @@ -94,7 +94,7 @@ export function madeWithText(t: { reading?: number | null; tuning?: Tuning | nul } export default function ReadAgain({ - what = "", busy = false, waiting = null, canReadAgain = true, edited = false, onReadAgain, onReadEdited, madeWith = null, lineOwn = null, baseline = undefined, madeOwn = false, refreshBaseline, baselineError = null, onRetryBaseline, character = null, keepForCharacter, error = null, note = null, autoplay, onAutoplay, + what = "", busy = false, waiting = null, canReadAgain = true, edited = false, onReadAgain, onReadEdited, madeWith = null, lineOwn = null, staleHref = null, baseline = undefined, madeOwn = false, refreshBaseline, baselineError = null, onRetryBaseline, character = null, keepForCharacter, error = null, note = null, autoplay, onAutoplay, }: { /** What is read, in the controls' names: "" (the post), "line 2", "the thread", "the card". */ what?: string; @@ -122,6 +122,8 @@ export default function ReadAgain({ * take's every value when it asked true) -- a plain press passes back only these; the rest is resolved now. */ lineOwn?: Tuning | null; + /** The Reads view at this character's stale reads (lane reads-find): linked beside a Keep that leaves reads stale. */ + staleHref?: string | null; /** The baseline as it is NOW: a press asking a sampler value of its own checks it first (review 3 #1). */ refreshBaseline?: () => Promise<TuneBaseline | null>; /** Why the baseline could not be read, and a retry: said in place. */ @@ -301,6 +303,9 @@ export default function ReadAgain({ )} </div> {kept && <span className="text-text-2" data-read-tune-kept="">{kept}</span>} + {kept && staleHref && / made with other settings/.test(kept) && ( + <a href={staleHref} className="ink-link" data-read-tune-stale-reads="" aria-label={character ? `Re-read ${character.name}'s stale reads in the Reads view` : "Re-read the stale reads in the Reads view"}>Re-read them</a> + )} </div> </details> <label className="flex items-center gap-1 text-text-2"> diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -40,6 +40,7 @@ import { makeCutIntegrityFixture } from "./cut-integrity-fixture.mjs"; import { makeUiOpsFixture } from "./ui-ops-fixture.mjs"; import { makeVoicesFixture } from "./voices-fixture.mjs"; import { makeTuningFixture } from "./tuning-fixture.mjs"; +import { makeReadsFixture } from "./reads-fixture.mjs"; import { makeRecordFilterFixture } from "./record-filter-fixture.mjs"; import { makeYoutubeFixture } from "./youtube-fixture.mjs"; import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs"; @@ -1934,6 +1935,8 @@ makeUiOpsFixture({ reports, channels: CHANNELS, manifest, cachedWindow: path.joi makeVoicesFixture({ reports, channels: CHANNELS, manifest, ff }); // A character's Orpheus tuning on the Voices page (character-tuning.spec.ts): its own character, three reads. makeTuningFixture({ reports, manifest, ff }); +// A video's reads (reads-find.spec.ts): Find, Replace, the re-read queue, Listen through -- posts, a recorded read, a card. +makeReadsFixture({ reports, manifest, ff }); // Record -> filter -> preview on the record page (record-filter.spec.ts): three one-part post items, no cast. makeRecordFilterFixture({ reports, manifest }); // Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts). diff --git a/umtool/e2e/fixtures/reads-fixture.mjs b/umtool/e2e/fixtures/reads-fixture.mjs @@ -0,0 +1,58 @@ +// A VIDEO's READS (reads-find.spec.ts; components/projects/ReadsPanel.tsx, lib/report/readsCli.mjs): two post items read +// by this video's own "ferry" character (orpheus · tara), one recorded read, and a narrated card whose reading is kept +// beside the build -- the words "north pier" in three of them, so Find counts, Replace rewrites what is SAID, and the +// re-read queue re-reads through the suite's editor stub (no real synthesis). +// +// reports/reads-fixture/ +// p-1 @invented_ferry_reads picked take orpheus · tara (made with the defaults): "… the north pier …" twice +// p-2 @invented_ferry_reads picked take orpheus · tara: no match +// p-3 @invented_pier_reads picked take RECORDED: "… north pier …" -- found, never replaced +// c-1 a card, its narration "… the north pier reopened." (orpheus · leo), its reading kept in out/narration/ +// +// Invented people, like every fixture. +import { mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { narrationsOf } from "../../report-to-video/narration.mjs"; + +export const READS = "reads-fixture"; +export const READS_P1 = "The ferry leaves the north pier at noon.\n\nBring a coat for the north pier wind."; + +const write = (dir, name, doc) => { + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, name), typeof doc === "string" ? doc : JSON.stringify(doc, null, 2) + "\n"); +}; + +/** @param {{ reports: string, manifest: Function, ff: (args: string[]) => void }} o */ +export function makeReadsFixture({ reports, manifest, ff }) { + const dir = path.join(reports, READS); + const made = { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3 }; + const post = (id, handle, text, take) => ({ + type: "post", id: `p-${id}`, post: `readsx/${id}`, platform: "x", author: handle === "invented_ferry_reads" ? "Ferry Teller" : "Pier Watch", handle, date: `2026-10-30T1${id}:00:00.000Z`, text, + url: `https://x.com/${handle}/status/${id}`, engagement: { likes: 1 }, section: 0, + narration: { script: text, takes: [{ seconds: 2, script: text, at: "2026-11-02T00:00:00.000Z", ...take }], pick: 0 }, + }); + const tone = (abs) => { + mkdirSync(path.dirname(abs), { recursive: true }); + ff(["-f", "lavfi", "-i", "sine=frequency=262:sample_rate=48000:duration=2", "-ac", "1", "-c:a", "pcm_s16le", abs]); + }; + const timeline = [ + post("1", "invented_ferry_reads", READS_P1, { file: "narration/posts/1/take-1.orpheus-tara.wav", engine: "orpheus", voice: "tara", tuning: made, reading: 0 }), + post("2", "invented_ferry_reads", "The ferry fares go up in the spring.", { file: "narration/posts/2/take-1.orpheus-tara.wav", engine: "orpheus", voice: "tara", tuning: made, reading: 0 }), + post("3", "invented_pier_reads", "The north pier is closed today.", { file: "narration/posts/3/take-1.recorded.wav", engine: "recorded", voice: "operator" }), + { type: "card", id: "c-1", seconds: "auto", heading: "Later", narration: { text: "Six months later, the north pier reopened.", engine: "orpheus", voice: "leo" } }, + ]; + for (const e of timeline) for (const t of e.narration?.takes ?? []) tone(path.join(dir, ...t.file.split("/"))); + const m = manifest(READS, "The Reads Fixture", {}, timeline); + write(dir, "video.manifest.json", m); + // The card's reading, kept beside the build as narrate-via-editor keeps it (out/narration/<key>.{wav,json}). + for (const n of narrationsOf(m)) { + const store = path.join(dir, "out", "narration"); + tone(path.join(store, `${n.key}.wav`)); + write(store, `${n.key}.json`, { id: n.id, key: n.key, text: n.text, engine: n.engine, voice: n.voice, speed: 1, seconds: 2, createdAt: "2026-11-02T00:00:00.000Z" }); + } + write(path.join(dir, "narration"), "characters.json", { + format: "umtool-project-characters", version: 1, + characters: [{ id: "ferry", name: "Ferry Teller", handles: ["invented_ferry_reads"], synthetic: { voice: "orpheus:tara" } }], + }); + return dir; +} diff --git a/umtool/e2e/reads-find.spec.ts b/umtool/e2e/reads-find.spec.ts @@ -0,0 +1,137 @@ +import { test, expect } from "@playwright/test"; +import { copyFileSync, existsSync, readFileSync, readdirSync, rmSync } from "node:fs"; +import { createHash } from "node:crypto"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; +import { READS_P1 } from "./fixtures/reads-fixture.mjs"; + +// --------------------------------------------------------------------------- +// A VIDEO's READS (lane reads-find, S4 of plans/orpheus-retune.md; components/projects/ReadsPanel.tsx, +// /api/report/reads, lib/report/readsCli.mjs). Fixture: e2e/fixtures/reads-fixture.mjs -- two post items read by this +// video's "ferry" character, a recorded read, a narrated card; "north pier" in three of them. Every step a press: +// +// every control there (aria-labels); Find "north pier": a count of matches and of lines, spoken text only +// Replace -> These reads: a preview (line, before -> after; the recorded read not changed), Apply -> the changed +// rows stale, nothing synthesized, every drawn card byte-identical +// Re-read 2 changed lines -> the app's queue runs them one at a time through the editor STUB to done: the post's +// re-read unpicked, the card's playing; Listen through plays; Pick new -> fresh; the cards still drawn the same +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const P = "reports/reads-fixture"; +const DIR = path.join(FIXTURE, "reports", "reads-fixture"); +const MANIFEST = path.join(DIR, "video.manifest.json"); +const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); + +type Tts = { route: string; text?: string; voice?: string }; +const ttsAsks = () => (existsSync(STUB_LOG) ? (JSON.parse(readFileSync(STUB_LOG, "utf8")) as Tts[]) : []).filter((r) => r.route === "tts"); +const sha = (s: string) => createHash("sha1").update(s).digest("hex"); +const files = (d: string) => (existsSync(d) ? readdirSync(d, { recursive: true }).map(String).sort() : []); +/** Every post item's card as drawn (plain and following) and its plan, and every other entry but its narration. */ +const drawn = async () => { + const { postCardHtml, postItemPlan } = (await import("../report-to-video/post-item.mjs")) as unknown as { + postCardHtml: (e: unknown, o: Record<string, unknown>) => string; postItemPlan: (e: unknown, r?: unknown) => unknown; + }; + const m = JSON.parse(readFileSync(MANIFEST, "utf8")) as { render?: unknown; timeline: Array<Record<string, unknown>> }; + return m.timeline.map((e) => (e.type === "post" + ? sha(JSON.stringify([postCardHtml(e, { width: 1080, height: 1350 }), postCardHtml(e, { width: 1080, height: 1350, follow: true }), postItemPlan(e, m.render)])) + : sha(JSON.stringify(Object.fromEntries(Object.entries(e).filter(([k]) => k !== "narration")))))); +}; +const pristine = { takes: [] as string[], readings: [] as string[] }; + +test.beforeAll(() => { + if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`); + pristine.takes = files(path.join(DIR, "narration", "posts")); + pristine.readings = files(path.join(DIR, "out", "narration")); +}); +const reset = () => { + copyFileSync(`${MANIFEST}.pristine`, MANIFEST); + rmSync(path.join(DIR, "narration", "reads"), { recursive: true, force: true }); + rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); + for (const f of files(path.join(DIR, "narration", "posts"))) if (!pristine.takes.includes(f) && f.endsWith(".wav")) rmSync(path.join(DIR, "narration", "posts", f), { force: true }); + for (const f of files(path.join(DIR, "out", "narration"))) if (!pristine.readings.includes(f)) rmSync(path.join(DIR, "out", "narration", f), { force: true }); +}; +test.beforeEach(() => { + test.setTimeout(240_000); + reset(); +}); +test.afterAll(reset); + +test("Find, Replace these reads, Re-read the changed lines on the queue, Listen through, Pick -- what is shown never changes", async ({ page }) => { + const cardsBefore = await drawn(); + const takesBefore = files(path.join(DIR, "narration", "posts")); + const asksBefore = ttsAsks().length; + + await page.goto(urls.readsHref(P)); + const panel = page.locator(`[data-reads="${P}"]`); + await expect(panel.locator("[data-reads-rows]")).toHaveAttribute("data-reads-rows", "4", { timeout: 30_000 }); + // Every control, by its name. + for (const name of ["Find in spoken text", "Match case", "Whole word", "Show every read", "Show the stale reads", "Character"]) await expect(panel.getByLabel(name, { exact: true }).or(panel.getByRole("button", { name, exact: true })).first()).toBeVisible(); + await expect(panel.getByRole("button", { name: "Re-read 0 changed lines" })).toBeDisabled(); + await expect(panel.locator('[data-read="p-3"]')).toHaveAttribute("data-read-state", "recorded"); + + // FIND: a count of matches and of lines -- the spoken text only. + await panel.getByLabel("Find in spoken text").fill("north pier"); + await expect(panel.locator("[data-reads-found]")).toHaveAttribute("data-reads-found", "4"); + await expect(panel.locator("[data-reads-found]")).toContainText("4 matches in 3 lines · spoken text only"); + await expect(panel.locator('[data-read="p-1"] [data-reads-match]')).toHaveCount(2); + + // REPLACE, these reads: previewed first, then applied -- nothing synthesized, the shown text untouched. + await panel.getByLabel("Replace with").fill("northern pier"); + await expect(panel.locator("[data-reads-say-limit]")).toContainText("Everywhere needs Whole word"); + await panel.getByRole("button", { name: "Replace in these reads" }).click(); + const preview = panel.locator('[data-reads-preview="reads"]'); + await expect(preview).toBeVisible(); + await expect(preview.locator("[data-reads-preview-line]")).toHaveCount(2); + await expect(preview.locator('[data-reads-preview-line="p-1"]')).toContainText("northern pier"); + await expect(preview.locator('[data-reads-preview-skipped="p-3"]')).toContainText("a recorded read is yours"); + expect(readFileSync(MANIFEST, "utf8")).toBe(readFileSync(`${MANIFEST}.pristine`, "utf8")); + await panel.getByRole("button", { name: "Apply the replace" }).click(); + await expect(panel.locator('[data-reads-undo="reads"]')).toBeVisible(); + await panel.getByLabel("Find in spoken text").fill(""); + await expect(panel.locator('[data-read="p-1"]')).toHaveAttribute("data-read-state", "stale"); + await expect(panel.locator('[data-read="c-1"]')).toHaveAttribute("data-read-state", "stale"); + await expect(panel.locator('[data-read="c-1"]')).toContainText("its words changed with the replace"); + await expect(panel.locator('[data-read="p-2"]')).toHaveAttribute("data-read-state", "fresh"); + const m = JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<{ id: string; text?: string; narration?: { script?: string; forReading?: boolean; text?: string } }> }; + expect(m.timeline[0].narration?.script).toBe(READS_P1.replaceAll("north pier", "northern pier")); + expect(m.timeline[0].narration?.forReading).toBe(true); + expect(m.timeline[0].text).toBe(READS_P1); + expect(await drawn()).toEqual(cardsBefore); + expect(files(path.join(DIR, "narration", "posts"))).toEqual(takesBefore); + expect(ttsAsks().length).toBe(asksBefore); + + // RE-READ the changed lines: the app's queue runs them, one at a time, through the editor stub. + await panel.getByRole("button", { name: "Re-read 2 changed lines" }).click(); + await expect(panel.locator("[data-reads-queue]")).toBeVisible(); + await expect(panel.locator('[data-reads-queue-row="p-1"]')).toHaveAttribute("data-state", "done", { timeout: 120_000 }); + await expect(panel.locator('[data-reads-queue-row="c-1"]')).toHaveAttribute("data-state", "done", { timeout: 120_000 }); + const asks = ttsAsks().slice(asksBefore); + expect(asks.some((a) => /northern pier/.test(a.text ?? "") && a.voice === "tara")).toBe(true); + expect(asks.some((a) => /closed today/.test(a.text ?? ""))).toBe(false); + // The post's re-read joined its list UNPICKED; the card's words play. + await expect(panel.locator('[data-read="p-1"]')).toHaveAttribute("data-read-state", "unpicked", { timeout: 20_000 }); + await expect(panel.locator('[data-read="c-1"]')).toHaveAttribute("data-read-state", "fresh"); + expect((JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<{ narration?: { pick?: number } }> }).timeline[0].narration?.pick).toBe(0); + + // LISTEN THROUGH: the re-reads played one after another (the new one of p-1 first), what played before a press away. + await panel.getByRole("button", { name: "Listen through the re-read lines" }).click(); + await expect(panel.locator('[data-reads-play-new="p-1"][data-playing="1"]')).toBeVisible({ timeout: 10_000 }); + await expect(panel.getByRole("button", { name: "Play what p-1 said before" })).toBeEnabled(); + await expect(panel.locator('[data-reads-play-cut="p-1"]')).toHaveAttribute("href", urls.playHref(P, { clip: "p-1" })); + + // PICK the new read: fresh; the cards still drawn as before. + await panel.getByRole("button", { name: "Pick the new read of p-1" }).click(); + await expect(panel.locator('[data-read="p-1"]')).toHaveAttribute("data-read-state", "fresh", { timeout: 20_000 }); + expect((JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<{ narration?: { pick?: number } }> }).timeline[0].narration?.pick).toBe(1); + expect(await drawn()).toEqual(cardsBefore); +}); + +test("the bench links here: the Voices page and a post's bench", async ({ page }) => { + await page.goto(urls.voicesHref(P)); + await expect(page.locator("[data-voices-reads]").first()).toHaveAttribute("href", urls.readsHref(P)); + await page.goto(urls.postBenchHref(P, "p-1")); + await expect(page.locator("[data-post-bench-reads]")).toHaveAttribute("href", urls.readsHref(P)); +}); diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -494,6 +494,11 @@ export function presentHref(project: string, q: { take?: string | null; bare?: b return workspaceHref(project, { mode: "present", take: q.take ?? null, slide: q.slide ?? null }); } +/** A video's READS (lane reads-find): every line a voice reads, Find / Replace, the re-read queue -- filtered by state or character. */ +export function readsHref(project: string, q: { state?: "stale" | null; character?: string | null } = {}): string { + return withQuery(`/projects/${encodePath(project)}/reads`, { ...(q.state ? { state: q.state } : {}), ...(q.character ? { character: q.character } : {}) }); +} + /** The narration script, card by card. */ export function narrationHref(project: string, q: NoteOpt = {}): string { return withQuery(`/projects/${encodePath(project)}/narration`, {}, q.note); diff --git a/umtool/lib/report/readsCli.mjs b/umtool/lib/report/readsCli.mjs @@ -45,7 +45,11 @@ class ReadsUsage extends Error {} const VALUED = new Set(["--find", "--character", "--only", "--one", "--retry", "--timeout"]); -/** `umtool reads …` */ +/** + * `umtool reads …` + * @param {string[]} args + * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, sleep?: (ms: number) => Promise<void>, queueDir?: string }} [o] + */ export async function readsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), queueDir = undefined } = {}) { const flags = new Map(); const words = []; diff --git a/umtool/lib/report/readsQueue.mjs b/umtool/lib/report/readsQueue.mjs @@ -300,3 +300,17 @@ export async function pickReads(project, { which = "new", only = null, token = n }, { snapshotEvery: 0 })); return { picked: [...picks.values()], result }; } + +/** + * The re-read step RUNNING now for one item of a project, or null -- the bench's single-post take op says it instead + * of asking a second read of the same post (lane reads-find): `{ qid, label }`. + */ +export async function rereadRunningFor(projectId, item, o = {}) { + const qdir = queueDirFor(o); + for (const s of await listSteps(qdir)) { + const r = resolveStep(s); + if (r.state !== "running" || r.argv?.[0] !== "reads" || r.argv?.[1] !== projectId) continue; + if (r.argv[r.argv.indexOf("--one") + 1] === item) return { qid: r.qid, label: r.label }; + } + return null; +}