import { mkdir, readFile, rename, stat } from "node:fs/promises";
import path from "node:path";
import { resolveReport } from "@/lib/report/serve.mjs";
import { refuseCaller } from "@/lib/report/caller";
import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
import { StaleToken, StructureRefused } from "@/lib/report/manifest.mjs";
import { clearSession, discardPart, finishSession, partFile, readSession, savePart, sessionParts } from "@/lib/report/recordSession.mjs";
import { discardPreview, keepPreview, preparePreview, previewFile, previewView, readPreview } from "@/lib/report/recordPreview.mjs";
import { readLayers } from "@/lib/report/characterLayers.mjs";
import { derivePitchOf } from "@/lib/report/derivePitch.mjs";
import { UMTOOL_DIR } from "@/lib/report/driver.mjs";
import { PARTS_CACHE, partKey } from "@/lib/report/postThreadRead.mjs";
import { projectRedaction } from "@/lib/report/postRedaction.mjs";
import { cancelJob, getJob, jobView, recentJobs, runningJob, startJob, type Job } from "@/lib/jobs";
import { editorCall, jobState, startJob as startEditorJob } from "@/lib/research/case-editor";
import { CAST_PITCH_ENGINES, characterSpeed, characterVoice, projectCharactersOf, recordedPresetOf, shownNameOf, voiceRefOf } from "umtool-report-to-video/cast";
import { spokenRead } from "umtool-report-to-video/post-redact";
export const dynamic = "force-dynamic";
// THE RECORDING SESSION (lib/report/recordSession.mjs; /projects/
/narration/record):
// a person's read of one post item, part by part, each part on disk the moment it is kept.
//
// GET ?project&id[&label] the session: the parts kept so far (a reload resumes)
// GET ?project&id&n[&label] one kept part's audio (play it back)
// POST multipart {project, id, n, count, text, para, label?, part} keep part n of count (a recording, or a
// sound file chosen for it)
// POST {project, op: "discard", id, n, label?} drop part n (redo it)
// POST {project, op: "finish", id, label?, script?, spans?} every part in: one recorded take, cut at the
// marks (`spans`, per part) else trimmed, joined,
// levelled, PICKED
//
// RECORD -> FILTER -> PREVIEW (lib/report/recordPreview.mjs): the session's parts run through the character's
// recorded preset into a SCRATCH DIR (narration/.record-preview/./), no take made, listened to beside
// the raw read, then kept or recorded again.
//
// GET ?project&id&preview[&label] who it is read as (its direction, convert, clean, trim), the preview as
// it stands (each part's waveform and marks, what was made), the Filter
// job running or last run
// GET ?project&id&preview&file=raw|clean|filtered|part[&n] one of its sounds
// GET ?project&id&job= the Filter job: its state, the stage it is at (and whether it WAITS --
// queued, or at the heavy slot for memory: the gate, not an error)
// GET ?project&id&stock&job=&key a stock read asked for: running | done {file} | failed
// POST {project, op: "prepare", id} the parts decoded: lengths, waveforms, the auto trim's marks (no editor)
// POST {project, op: "filter", id, spans?, pitch?, semitones?} THE CHAIN as one job (`umtool posts narrate
// - --preview --events`): clean, cut, convert -- a step whose inputs
// stand is not run again (another pitch: the convert alone)
// POST {project, op: "cancel", id, job} stop that job AND the editor's job it waits on (its engine holds the
// heavy slot otherwise); `editor.note` when that one was not known yet
// keep, again, discard-preview, finish, discard and a part's upload answer 409 while the item's Filter runs
// POST {project, op: "keep", id, filtered, spans?, script?} filtered: the preview's files made the takes
// (recorded, cleaned, converted; the last picked) -- nothing converted
// again; else the recorded take alone (finish). The session and the
// scratch dir are cleared.
// POST {project, op: "again", id, n?} the preview dropped (and part n, to record it again)
// POST {project, op: "discard-preview", id} the scratch dir removed (the page is left; a beacon)
// POST {project, op: "stock", id, text} the character's SYNTHETIC preset voice reading the line: the cached read when there
// is one (narration/parts-cache/, a thread read's), else asked of the
// editor's tts op (a job) -- only when a person asks
const noStore = { "cache-control": "no-store" };
type Entry = Record
& { id: string; type?: string };
const fail = (e: unknown) => {
if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 });
if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 });
const status = (e as { status?: number }).status ?? 400;
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status });
};
function itemOf(manifest: Record, id: string): Entry | null {
const tl = (Array.isArray(manifest.timeline) ? manifest.timeline : []) as Entry[];
return tl.find((e) => e?.type === "post" && e.id === id) ?? null;
}
const TYPES: Record = { webm: "audio/webm", ogg: "audio/ogg", wav: "audio/wav", m4a: "audio/mp4", mp3: "audio/mpeg", flac: "audio/flac" };
/** The Filter job of one post item (lib/jobs.ts: one job at a time, its log, Cancel). */
const filterKind = (project: string, id: string) => `record-filter ${project} ${id}`;
/** Is that item's Filter running now? Its scratch dir and its session are the job's until it ends. */
const filterRunning = (project: string, id: string) => runningJob()?.kind === filterKind(project, id);
const busy = () => Response.json({ error: "its Filter is still running: wait for it, or Cancel it", busy: true }, { status: 409 });
type Stage = { stage?: string; state?: string; message?: string; line?: string; job?: string };
const WAITS = ["queued", "memory", "slot"];
/**
* The Filter job as the record page reads it: its state, the STAGE it is at (the chain's last `stage` event:
* recordPreview.mjs runPreview), every stage's last word, and whether it is WAITING -- `queued` behind the editor's
* other jobs, `memory` / `slot` at the machine's heavy slot. A wait is the gate working: it is never an error here.
*/
function filterJobView(job: Job) {
const stages = (job.events as Array).filter((x) => x.ev === "stage");
const at = stages.at(-1) ?? null;
const last: Record = {};
for (const x of stages) if (x.stage) last[x.stage] = { state: x.state, message: x.message };
const failed = job.state === "failed";
return {
id: job.id, state: job.state, startedAt: job.startedAt, endedAt: job.endedAt,
stage: at?.stage ?? null, stageState: at?.state ?? null, message: at?.message ?? null,
waiting: at && job.state === "running" && WAITS.includes(String(at.state)) ? at.state : null,
// Every wait it went through, in order (said after the fact too: "waited for memory").
waited: [...new Set(stages.filter((x) => WAITS.includes(String(x.state))).map((x) => String(x.state)))],
stages: last,
// The editor's job it waits on now (the clean, the convert): what Cancel stops there too. null: none known yet.
editorJob: job.state === "running" ? (stages.filter((x) => typeof x.job === "string").at(-1)?.job ?? null) : null,
// A failure in the CLI's own words (its last line), not "exited 1".
error: failed ? (job.log.filter((l) => !l.startsWith("**") && !l.startsWith("$ ") && !l.startsWith("---")).at(-1) ?? job.error) : null,
};
}
/** Who a recording of `e` is read as, and that character's recorded preset (cast.mjs characterForRead, recordedPresetOf). */
async function whoOf(dir: string, e: Entry) {
const layers = await readLayers(dir);
const who = layers.characterForRead(e);
const c = who?.character ?? null;
const preset = c ? recordedPresetOf(c) : null;
// Where a change to it is written: this video's own characters, else the cast.
const own = c ? projectCharactersOf(layers.project).some((x: { id: string }) => x.id === c.id) : false;
return {
character: c ? { id: c.id as string, name: shownNameOf(c) as string, layer: who.layer as string, scope: own ? "project" : "cast" } : null,
convert: preset ? preset.convert : null,
recorded: preset ? { enhance: preset.enhance, trim: preset.trim, direction: preset.direction } : null,
// The voice it reads in when it is SYNTHESIZED (the synthetic preset: the cheap one to hear the line in).
synthetic: c && characterVoice(c) ? { voice: String(characterVoice(c)), speed: characterSpeed(c) as number | null } : null,
pitchEngines: CAST_PITCH_ENGINES,
};
}
/** The file a stock read of `text` is cached at (a thread read's part: postThreadRead.mjs partKey), project-relative. */
const stockRel = (key: string) => `${PARTS_CACHE}/${key}.wav`;
const isKey = (k: string) => /^[0-9a-f]{40}$/.test(k);
/** A stock read asked of the editor: where its job is; done, its file is put in the cache. */
async function stockPoll(dir: string, job: string, key: string) {
if (!isKey(key)) return Response.json({ error: "which read?" }, { status: 400 });
const abs = path.join(dir, ...stockRel(key).split("/"));
const st = await jobState(job);
if (!st.done) return Response.json({ state: "running", status: st.status }, { headers: noStore });
if (st.status !== "done") return Response.json({ state: "failed", error: st.tail.slice(-3).join(" / ") }, { headers: noStore });
const tmp = `${abs}.pending.tmp.wav`;
if (await stat(tmp).catch(() => null)) await rename(tmp, abs);
if (!(await stat(abs).catch(() => null))?.isFile()) return Response.json({ state: "failed", error: "the job is done but its read is not there" }, { headers: noStore });
return Response.json({ state: "done", file: stockRel(key) }, { headers: noStore });
}
export async function GET(request: Request) {
const q = new URL(request.url).searchParams;
const r = await resolveReport(q.get("project") ?? "");
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
const e = itemOf(r.manifest as Record, q.get("id") ?? "");
if (!e) return Response.json({ error: `no post item ${q.get("id")}` }, { status: 404 });
const label = q.get("label") ?? "operator";
try {
if (q.get("stock") !== null) return await stockPoll(r.project.dir, String(q.get("job") ?? ""), String(q.get("key") ?? ""));
if (q.get("job") !== null) {
const job = getJob(String(q.get("job")));
if (!job || job.kind !== filterKind(r.project.id, e.id)) return Response.json({ error: "no such job" }, { status: 404 });
return Response.json({ ok: true, job: filterJobView(job), ...(job.state === "done" ? { preview: previewView(await readPreview(r.project.dir, e, label)) } : {}) }, { headers: noStore });
}
if (q.get("preview") !== null) {
const which = q.get("file");
if (which !== null) {
const f = await previewFile(r.project.dir, e, which, { label, n: q.get("n") === null ? null : Number(q.get("n")) });
if (!f) return new Response("no such sound", { status: 404 });
return new Response(new Uint8Array(await readFile(f)), { headers: { "content-type": "audio/wav", ...noStore } });
}
const mine = [runningJob(), ...recentJobs(20)].find((j) => j && j.kind === filterKind(r.project.id, e.id)) ?? null;
return Response.json({ ok: true, ...(await whoOf(r.project.dir, e)), preview: previewView(await readPreview(r.project.dir, e, label)), job: mine ? filterJobView(mine) : null }, { headers: noStore });
}
const n = q.get("n");
if (n !== null) {
const f = await partFile(r.project.dir, e, Number(n), label);
if (!f || !(await stat(f).catch(() => null))) return new Response("no such part", { status: 404 });
const body = await readFile(f);
return new Response(new Uint8Array(body), { headers: { "content-type": TYPES[f.split(".").pop() ?? ""] ?? "application/octet-stream", ...noStore } });
}
return Response.json({ ok: true, session: await readSession(r.project.dir, e, label) }, { headers: noStore });
} catch (err) {
return fail(err);
}
}
export async function POST(request: Request) {
// OUTSIDE THE PROXY (an upload: lib/report/writeGuard.mjs EXEMPT), so crossSiteRefusal here, before the body, on
// EVERY call, a browser's or not: a Host / X-Forwarded-Host not this machine (nor UMTOOL_ALLOWED_HOSTS) is refused
// even from curl, and so is a write from another site's page.
const cross = crossSiteRefusal(request.headers);
if (cross) return Response.json({ error: cross }, { status: 403 });
const refused = refuseCaller(request, "/api/report/post-narration/record");
if (refused) return refused;
if ((request.headers.get("content-type") ?? "").startsWith("multipart/form-data")) {
let form: FormData;
try {
form = await request.formData();
} catch {
return Response.json({ error: "expected a multipart part" }, { status: 400 });
}
const r = await resolveReport(String(form.get("project") ?? ""));
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
const e = itemOf(r.manifest as Record, String(form.get("id") ?? ""));
if (!e) return Response.json({ error: `no post item ${String(form.get("id"))}` }, { status: 404 });
const blob = form.get("part");
if (!blob || typeof blob === "string") return Response.json({ error: "no part" }, { status: 400 });
if (filterRunning(r.project.id, e.id)) return busy();
try {
const session = await savePart(r.project.dir, e, {
n: Number(form.get("n")), count: Number(form.get("count")), text: String(form.get("text") ?? ""), para: Number(form.get("para")),
bytes: new Uint8Array(await blob.arrayBuffer()), type: blob.type || "audio/webm", label: String(form.get("label") ?? "operator").toLowerCase(),
});
// Another recording than the one a preview was made from: that preview goes (it must never be kept for this one).
await discardPreview(r.project.dir, e, String(form.get("label") ?? "operator").toLowerCase());
return Response.json({ ok: true, session }, { headers: noStore });
} catch (err) {
return fail(err);
}
}
let body: Record;
try {
body = await request.json();
} catch {
return Response.json({ error: "expected JSON or a part" }, { status: 400 });
}
const r = await resolveReport(String(body.project ?? ""));
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
const e = itemOf(r.manifest as Record, String(body.id ?? ""));
if (!e) return Response.json({ error: `no post item ${String(body.id)}` }, { status: 404 });
const label = String(body.label ?? "operator").toLowerCase();
try {
if (body.op === "discard") return Response.json({ ok: true, session: await discardPart(r.project.dir, e, Number(body.n), label) }, { headers: noStore });
const script = typeof body.script === "string" ? body.script : null;
const spans = spansOf(body.spans);
if (body.op === "finish") {
const kept = await finishSession(r.project, e, { label, manifest: r.manifest as Record, script, spans });
await discardPreview(r.project.dir, e, label);
return Response.json({ ok: true, take: kept.take, gain: kept.gain, entry: kept.result.entry, token: kept.result.token }, { headers: noStore });
}
if (body.op === "prepare") {
// The parts decoded into the scratch dir: their waveforms and the auto trim's marks. No editor, no take.
const who = await whoOf(r.project.dir, e);
const doc = await preparePreview(r.project, e, await sessionParts(r.project.dir, e, label), { label, trim: who.recorded?.trim ?? null });
return Response.json({ ok: true, ...who, preview: previewView(doc) }, { headers: noStore });
}
if (body.op === "filter") {
// THE CHAIN, as one job of umtool's (its log, Cancel): the CLI's own command over the session's parts.
const running = runningJob();
if (running) return Response.json({ error: `umtool is running another job (${running.kind}): Filter when it is done`, busy: true }, { status: 409 });
await sessionParts(r.project.dir, e, label);
const checked = derivePitchOf({ pitch: body.pitch, semitones: body.semitones });
if (!checked.ok) return Response.json({ error: checked.error }, { status: 400 });
const pitched: { pitch?: string; semitones?: number } = checked.value ?? {};
const cliPath = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs");
const argv = [
process.execPath, cliPath, "posts", "narrate", r.project.id, e.id, "--preview", "--events", "--label", label,
...(spans ?? []).flatMap((sp, k) => (sp ? ["--trim-span", `${k + 1}=${sp.from}-${sp.to}`] : [])),
...(pitched.pitch ? ["--pitch", pitched.pitch] : []),
...(typeof pitched.semitones === "number" && pitched.pitch !== "target" ? ["--semitones", String(pitched.semitones)] : []),
];
const job = startJob(filterKind(r.project.id, e.id), [{ label: `${e.id}: its recording cleaned, cut, converted (a preview: no take)`, argv, cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, timeoutMs: 45 * 60 * 1000, ndjson: true }], { project: r.project.id });
return Response.json({ ok: true, job: filterJobView(job) }, { headers: noStore });
}
if (body.op === "cancel") {
const job = getJob(String(body.job ?? ""));
if (!job || job.kind !== filterKind(r.project.id, e.id)) return Response.json({ error: "no such job" }, { status: 404 });
// The editor's job too: its engine holds (or waits at) the heavy slot whether or not umtool still follows it.
const editorJob = filterJobView(job).editorJob;
const cancelled = cancelJob(job.id);
let editor: { job: string | null; cancelled: boolean; note?: string } = { job: editorJob, cancelled: false };
if (editorJob) {
const a = await editorCall("/api/ops/job", { method: "POST", body: { verb: "cancel", ids: [editorJob] } }).catch((err: Error) => ({ ok: false, status: 502, body: { error: err.message } as Record }));
editor = a.ok ? { job: editorJob, cancelled: true } : { job: editorJob, cancelled: false, note: `the editor's job ${editorJob} was not cancelled (${String(a.body.error ?? `HTTP ${a.status}`)}): cancel it on the editor's /jobs` };
} else if (cancelled) editor = { job: null, cancelled: false, note: "the editor's job was not known yet: if one started, cancel it on the editor's /jobs" };
return Response.json({ ok: true, cancelled, editor }, { headers: noStore });
}
if (["keep", "again", "discard-preview", "finish", "discard"].includes(String(body.op)) && filterRunning(r.project.id, e.id)) return busy();
if (body.op === "keep") {
if (body.filtered === true) {
// The preview's files made the takes: it must be OF this recording and these marks (nothing is converted here).
const doc = await readPreview(r.project.dir, e, label);
const view = previewView(doc);
if (!view?.raw) return Response.json({ error: "there is no preview to keep: Filter it first" }, { status: 409 });
if (spans && view.parts.some((p: { span: { from: number; to: number } | null }, k: number) => spans[k] && p.span && (Math.abs(p.span.from - spans[k]!.from) > 0.002 || Math.abs(p.span.to - spans[k]!.to) > 0.002))) {
return Response.json({ error: "the cut marks moved since the Filter: Filter again, or keep the recording alone" }, { status: 409 });
}
// Of the session as it is NOW: a part recorded again since the Filter is another recording (409, nothing kept).
const kept = await keepPreview(r.project, e, { label, script, parts: doc?.session ? await sessionParts(r.project.dir, e, label) : null });
if (kept.session) await clearSession(r.project.dir, e, label);
return Response.json({ ok: true, takes: kept.takes, picked: kept.picked, notes: kept.notes, disclosure: kept.disclosure, entry: kept.entry, token: kept.token }, { headers: noStore });
}
const kept = await finishSession(r.project, e, { label, manifest: r.manifest as Record, script, spans });
await discardPreview(r.project.dir, e, label);
return Response.json({ ok: true, takes: [{ step: "recorded", file: kept.take.file }], picked: kept.take.file, notes: [], entry: kept.result.entry, token: kept.result.token }, { headers: noStore });
}
if (body.op === "again") {
await discardPreview(r.project.dir, e, label);
const session = body.n === undefined || body.n === null ? await readSession(r.project.dir, e, label) : await discardPart(r.project.dir, e, Number(body.n), label);
return Response.json({ ok: true, session }, { headers: noStore });
}
if (body.op === "discard-preview") {
await discardPreview(r.project.dir, e, label);
return Response.json({ ok: true }, { headers: noStore });
}
if (body.op === "stock") {
// The character's stock voice reading the line -- what the redaction, the slur filter and the lexicon leave of it.
const who = await whoOf(r.project.dir, e);
const ref = voiceRefOf(who.synthetic?.voice ?? "") as { engine: string | null; voice: string } | null;
const speed = ref?.engine && ref.engine !== "orpheus" && typeof who.synthetic?.speed === "number" ? who.synthetic.speed : null;
if (!ref?.engine) return Response.json({ error: "this post's character has no synthetic voice to hear" }, { status: 400 });
const text = String(body.text ?? "").trim();
if (!text) return Response.json({ error: "no line to read" }, { status: 400 });
const red = await projectRedaction(r.project.dir, r.manifest as Record);
const spoken = String(spokenRead(text, e, red, { voice: red?.slurs?.voice === "beep" ? "skip" : undefined }).text);
const key = partKey(ref.engine, ref.voice, spoken, speed) as string;
const abs = path.join(r.project.dir, ...stockRel(key).split("/"));
if ((await stat(abs).catch(() => null))?.isFile()) return Response.json({ ok: true, cached: true, file: stockRel(key), voice: who.synthetic?.voice }, { headers: noStore });
if (body.cachedOnly === true) return Response.json({ ok: true, cached: false, voice: who.synthetic?.voice }, { headers: noStore });
await mkdir(path.dirname(abs), { recursive: true });
// The job writes BESIDE the cache; its poll renames it in (a half-written read is never a cached part).
const jobId = await startEditorJob("/api/ops/tts", { text: spoken, engine: ref.engine, voice: ref.voice, out: `${abs}.pending.tmp.wav`, ...(speed ? { speed } : {}) });
return Response.json({ ok: true, cached: false, jobId, key, voice: who.synthetic?.voice }, { headers: noStore });
}
return Response.json({ error: "op is discard, finish, prepare, filter, cancel, keep, again, discard-preview or stock" }, { status: 400 });
} catch (err) {
return fail(err);
}
}
/** A body's `spans` as cut marks per part: `[{from, to} | null]`, or null when it gives none. */
function spansOf(v: unknown): Array<{ from: number; to: number } | null> | null {
if (!Array.isArray(v) || !v.length || v.length > 200) return null;
const out = v.map((x) => {
const sp = x as { from?: unknown; to?: unknown } | null;
return sp && typeof sp.from === "number" && typeof sp.to === "number" && Number.isFinite(sp.from) && Number.isFinite(sp.to) && sp.to - sp.from >= 0.2 && sp.from >= 0 ? { from: Math.round(sp.from * 1000) / 1000, to: Math.round(sp.to * 1000) / 1000 } : null;
});
return out.some(Boolean) ? out : null;
}