"use client";
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";
// ---------------------------------------------------------------------------
// A SCREEN LINE IN THE OPERATOR's VOICE, on the post bench's screens section (lib/report/screenLineRecord.mjs; the
// CLI's `umtool posts screen
record --recording `): Record / Stop / play back / Redo / Keep
// per read line -- Keep one umtool JOB (recorded, cleaned, converted to the speaker's character's stock voice, none
// picked) -- and the select that CHOOSES which take, if any, is read in the line's place (the screen's `lineTakes`,
// saved with the bench's Save: `set take.=`). "Make the read" is `posts screen
read`, as a job.
// Recording is off while the draft differs from what is saved: a line is recorded as it is SAVED.
// ---------------------------------------------------------------------------
const LABEL_KEY = "umtool.post-narration.label";
type Job = { id: string; what: string; role?: string; state: string; message?: string | null; error?: string | null; waiting?: string | null };
type Part = { role?: string; file?: string; text?: string; reading?: number; tuning?: Tuning };
type TakeLike = { file?: string; parts?: Part[]; read?: { kind?: string } };
const fileUrl = (project: string, rel: string) => `/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(rel)}`;
export type VoiceEntry = Record & { id: string };
/** The section's voice: one microphone, one take at a time, one job at a time. */
export function useScreenVoice({ project, id, onEntry, unsaved }: { project: string; id: string; onEntry: (e: VoiceEntry, token: string | null) => void; unsaved: () => boolean }) {
const mic = useMic();
const [at, setAt] = useState(null);
const [phase, setPhase] = useState<"idle" | "recording">("idle");
const [takes, setTakes] = useState>({});
const [job, setJob] = useState(null);
const [status, setStatus] = useState(null);
const [prompts, setPrompts] = useState>({});
const poll = useRef | null>(null);
const misses = useRef(0);
// One press at a time, synchronously (review 1, finding 4): a second press before the first's answer is ignored.
const pressing = useRef(false);
useEffect(() => () => {
if (poll.current) clearTimeout(poll.current);
}, []);
// What each read line says, as the read says it (the server's: its masks, the redaction, an anonymous handle's shown name).
const loadPrompts = useCallback(async () => {
const r = await fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}&id=${encodeURIComponent(id)}&linePrompts=1`, { cache: "no-store" }).catch(() => null);
const j = r && r.ok ? ((await r.json().catch(() => null)) as { prompts?: Record } | null) : null;
setPrompts(j?.prompts ?? {});
}, [project, id]);
useEffect(() => {
void loadPrompts();
}, [loadPrompts]);
const follow = useCallback(
(j: Job) => {
// Each job its own count of missed polls (review 2, finding 5).
misses.current = 0;
setJob(j);
const tick = async () => {
const r = await fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}&id=${encodeURIComponent(id)}&screenJob=${encodeURIComponent(j.id)}`, { cache: "no-store" }).catch(() => null);
const v = r ? ((await r.json().catch(() => ({}))) as { state?: string; message?: string; error?: string; waiting?: string; entry?: VoiceEntry | null; token?: string | null; result?: { takes?: Array<{ n: number; step: string }>; notes?: string[]; upToDate?: boolean; why?: string; take?: { file: string; n: number; parts?: Array<{ role: string | null; file: string | null }> } | null } | null }) : {};
// A lost job (404, an answer with no state) has failed; the editor out of reach five times running too.
misses.current = r ? 0 : misses.current + 1;
const state = v.state ?? (r ? "failed" : misses.current >= 5 ? "failed" : "running");
if (!v.state && r) v.error ??= `the job is gone (HTTP ${r.status})`;
setJob({ ...j, state, message: v.message ?? null, error: v.error ?? null, waiting: v.waiting ?? null });
if (state === "running") {
poll.current = setTimeout(tick, 1500);
return;
}
// The entry as the job left it -- never over edits made meanwhile (they are kept; Save, then reload to see it).
const kept = unsaved();
if (v.entry && !kept) onEntry(v.entry, v.token ?? null);
if (state === "done") {
if (j.what === "line" && j.role) {
setTakes((t) => {
const { [j.role as string]: gone, ...rest } = t;
if (gone) URL.revokeObjectURL(gone.url);
return rest;
});
const made = v.result?.takes ?? [];
setStatus(`${j.role}: ${made.map((x) => `take ${x.n} ${x.step}`).join(", ")} -- none picked; choose one for the line, Save, then make the read${(v.result?.notes ?? []).length ? ` (${(v.result?.notes ?? []).join("; ")})` : ""}`);
} else if (j.what === "again" && j.role) {
// A LINE READ AGAIN (lane line-rerun): the take THIS JOB made (its result), unpicked; its line's part plays
// as it lands. None made: said, and nothing plays (review 1, finding 2).
const made = v.result?.take ?? null;
if (!made) setStatus(`${j.role}: nothing made -- ${v.result?.why ?? "the read already says this"}`);
else {
const part = made.parts?.find((p) => p.role === j.role && p.file);
setLanded({ role: j.role, take: made.n - 1 });
if (part?.file && autoplayNow.current) playNow(fileUrl(project, part.file));
setStatus(`${j.role}: read again -- take ${made.n}, not picked; Pick makes it the one`);
}
} else setStatus(v.result?.take ? `the read is made: take ${v.result.take.n} (picked)` : `nothing made -- ${v.result?.why ?? "the read already says this"}`);
if (kept) setStatus((x) => `${x ?? ""} -- your unsaved edits are kept: Save, then reload the bench to see it`);
void loadPrompts();
}
};
poll.current = setTimeout(tick, 800);
},
[project, id, onEntry, loadPrompts, unsaved],
);
const record = async (role: string) => {
if (phase !== "idle" || job?.state === "running") return;
if (!(await mic.start())) return;
setAt(role);
setPhase("recording");
};
const stop = async () => {
if (phase !== "recording" || !at) return;
const blob = await mic.stop();
setPhase("idle");
if (!blob) return;
const role = at;
setTakes((t) => {
if (t[role]) URL.revokeObjectURL(t[role].url);
return { ...t, [role]: { blob, url: URL.createObjectURL(blob) } };
});
};
const redo = (role: string) =>
setTakes((t) => {
const { [role]: gone, ...rest } = t;
if (gone) URL.revokeObjectURL(gone.url);
return rest;
});
const keep = async (role: string) => {
const t = takes[role];
if (!t) return;
setStatus(null);
const fd = new FormData();
fd.set("project", project);
fd.set("id", id);
fd.set("line", role);
fd.set("label", ls.get(LABEL_KEY) ?? "operator");
fd.append("part", t.blob, `line${/ogg/.test(t.blob.type) ? ".ogg" : ".webm"}`);
const r = await fetch("/api/report/post-narration", { method: "POST", body: fd });
const j = (await r.json().catch(() => ({}))) as { job?: { id: string; state: string }; error?: string };
if (!r.ok || !j.job) {
setJob({ id: "", what: "line", role, state: "failed", error: j.error ?? `HTTP ${r.status}` });
return;
}
follow({ id: j.job.id, what: "line", role, state: j.job.state });
};
// ---- READ A LINE AGAIN (lane line-rerun): `posts screen
read --for --reading next --no-pick` ----
const [autoplay, setAutoplay] = useAutoPlay();
const autoplayNow = useRef(autoplay);
autoplayNow.current = autoplay;
const [landed, setLanded] = useState<{ role: string; take: number } | null>(null);
const readLine = async (role: string, tuning: Tuning | null) => {
if (job?.state === "running" || pressing.current) return;
pressing.current = true;
setStatus(null);
try {
const r = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "screen-read", id, for: role, reading: "next", keepPick: true, ...(tuning ? { tuning } : {}) }) }).catch(() => null);
const j = r ? ((await r.json().catch(() => ({}))) as { job?: { id: string; state: string }; error?: string; busy?: boolean }) : { error: "the bench is out of reach" };
if (!r?.ok || !j.job) {
// Busy (another job runs): said, without taking the running one's place.
if (j.busy) setStatus(j.error ?? "busy");
else setJob({ id: "", what: "again", role, state: "failed", error: j.error ?? `HTTP ${r?.status ?? "?"}` });
return;
}
follow({ id: j.job.id, what: "again", role, state: j.job.state });
} finally {
pressing.current = false;
}
};
const pickTake = async (index: number) => {
const r = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "set", id, patch: { pick: index } }) });
const j = (await r.json().catch(() => ({}))) as { entry?: VoiceEntry; token?: string; error?: string };
if (!r.ok || !j.entry) setStatus(j.error ?? `HTTP ${r.status}`);
else onEntry(j.entry, j.token ?? null);
};
const makeRead = async () => {
setStatus(null);
const r = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "screen-read", id }) });
const j = (await r.json().catch(() => ({}))) as { job?: { id: string; state: string }; error?: string };
if (!r.ok || !j.job) {
setJob({ id: "", what: "read", state: "failed", error: j.error ?? `HTTP ${r.status}` });
return;
}
follow({ id: j.job.id, what: "read", state: j.job.state });
};
return { mic, at, phase, takes, job, status, prompts, record, stop, redo, keep, makeRead, readLine, pickTake, landed, autoplay, setAutoplay, project, id };
}
export type ScreenVoice = ReturnType;
/** The recordings of one line, as the select offers them: `{ id, label, current }`. */
export type LineTakeOption = { id: string; label: string; current: boolean };
/** One synthesized reading of a line: the take it is in (index), its part's file, words, reading and tuning. */
export type LineReading = { take: number; picked: boolean; file: string | null; text: string; reading: number; tuning: Tuning | null; tuningAsked?: true | "preset"; own?: Tuning | null };
/** The readings of a line (`role`) in an item's takes: each take whose parts read it, synthesized. */
export function lineReadings(entry: Record, role: string): LineReading[] {
const n = (entry.narration ?? {}) as { takes?: TakeLike[]; pick?: number };
const pick = Number.isInteger(n.pick) ? (n.pick as number) : 0;
return (n.takes ?? []).flatMap((t, i) => {
const p = (t.parts ?? []).find((x) => x.role === role && !(x as { take?: string }).take);
const asked = (p as { tuningAsked?: unknown } | undefined)?.tuningAsked;
return p ? [{ take: i, picked: i === pick, file: p.file ?? null, text: String(p.text ?? ""), reading: Number.isInteger(p.reading) ? (p.reading as number) : 0, tuning: p.tuning ?? null, ...(asked === true || asked === "preset" ? { tuningAsked: asked } : {}), own: pieceOwnOf(t, role) as Tuning | null }] : [];
});
}
/** ONE READ LINE's voice cell: Record / Stop / play back / Redo / Keep, and the take chosen for it. */
export function ScreenLineVoice({ role, n, voice, dirty, options, chosen, onChoose, readings = [], edited = false }: { role: string; n: number; voice: ScreenVoice; dirty: boolean; options: LineTakeOption[]; chosen: string | undefined; onChoose: (id: string | undefined) => void; readings?: LineReading[]; edited?: boolean }) {
const mine = voice.at === role && voice.phase === "recording";
// The character whose synthetic preset reads this line (its speaker's; lane character-tuning): a Tune is kept for it.
const playedLine = readings.find((x) => x.picked) ?? null;
const readsAs = useKeepForCharacter(voice.project, voice.id, role, playedLine ? { tuning: playedLine.tuning, tuningAsked: playedLine.tuningAsked } : null);
const t = voice.takes[role];
const busy = voice.job?.state === "running";
const other = voice.phase === "recording" && voice.at !== role;
const btn = "ink-link disabled:opacity-40";
return (