"use client"; import { useEffect, useMemo, useState } from "react"; import type { KeepForCharacter, TuneBaseline, Tuning } from "./ReadAgain"; import { madeOwnOf } from "@/lib/report/tuneAsk.mjs"; // --------------------------------------------------------------------------- // A PIECE's CHARACTER ON THE BENCH (lane character-tuning; ReadAgain.tsx's seam): who reads each piece of an item now // and with what tuning -- ONE call per item (GET /api/report/post-narration?reads=all, the playing read's voice // overrides kept), shared by every panel that mounts a Read again for it, read again after a Keep. It gives each // Tune its BASELINE (what a plain press reads the piece with now) and its "Keep for ": the numbers kept as // the character's through its command (`umtool cast set …` for a cast character, `cast project

set …` // for this video's own: /api/report/voices op "character-set"), then what that leaves stale (`umtool cast stale`). // --------------------------------------------------------------------------- export type ReadCharacter = { id: string; name: string; layer: "cast" | "project" }; type Piece = { character: ReadCharacter | null; tuning: Tuning | null }; type Pieces = Record; type Slot = { data: Pieces | null; error: string | null; loading: Promise | null; subs: Set<() => void> }; const store = new Map(); const keyOf = (project: string, id: string) => `${project}\u0000${id}`; function slot(project: string, id: string) { const k = keyOf(project, id); let s = store.get(k); if (!s) { s = { data: null, error: null, loading: null, subs: new Set() }; store.set(k, s); } return s; } /** * Read an item's pieces again (on every mount, after a Keep, before a press that asks a sampler value of its own): * every panel of it is told. The value kept meanwhile is the last one read; a read that fails leaves it as it was and * says why (`error`) -- never "no characters". Returns the pieces as they are now (null: not known). */ export function refreshReads(project: string, id: string): Promise { const s = slot(project, id); if (s.loading) return s.loading; const tell = () => { for (const f of s.subs) f(); }; s.loading = (async () => { type Answer = { pieces?: Record; error?: string }; let r = null as Response | null; let j = null as Answer | null; try { r = await fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}&id=${encodeURIComponent(id)}&reads=all`, { cache: "no-store" }); j = (await r.json().catch(() => null)) as Answer | null; } catch (e) { s.error = `umtool could not be reached (${e instanceof Error ? e.message : String(e)})`; } if (r?.ok && j && typeof j.pieces === "object" && j.pieces) { const pieces: Pieces = {}; for (const [role, p] of Object.entries(j.pieces)) { const c = p?.character; pieces[role] = { character: c && (c.layer === "cast" || c.layer === "project") ? c : null, tuning: p?.tuning ?? null }; } s.data = pieces; s.error = null; } else if (r) s.error = j?.error ?? `HTTP ${r.status}`; s.loading = null; tell(); return s.data; })(); tell(); return s.loading; } /** An item's pieces as the bench reads them (null until known), why they could not be read, and a retry. */ export function useReads(project: string | null | undefined, id: string): { pieces: Pieces | null; error: string | null; retry: () => void } { const [, setTick] = useState(0); useEffect(() => { if (!project) return; const s = slot(project, id); const f = () => setTick((n) => n + 1); s.subs.add(f); // Read again on EVERY mount (review 3 #1): a character changed on the Voices page or in another tab is seen; the // value kept meanwhile is the last one read. void refreshReads(project, id); return () => { s.subs.delete(f); }; }, [project, id]); const s = project ? store.get(keyOf(project, id)) : undefined; return { pieces: s?.data ?? null, error: s?.error ?? null, retry: () => void (project ? refreshReads(project, id) : null) }; } const words = (t: Tuning) => Object.entries(t).map(([k, v]) => `${k.replace("_", " ")} ${v}`).join(", ") || "the defaults"; /** * The seam's function for one character: keep `tuning` as its own -- exactly these numbers (a sampler value left out * is its default; takes left out is the editor's setting) -- and say what was kept and what that leaves stale, this * item first. A refusal is said in the command's words ("not kept: …"). */ export function keepTuningFor(project: string, item: string, c: ReadCharacter): KeepForCharacter { return async (t) => { const tuning = { temperature: t.temperature ?? null, top_p: t.top_p ?? null, repeat_penalty: t.repeat_penalty ?? null, takes: t.takes ?? null, ...(t.top_k !== undefined ? { top_k: t.top_k } : {}), ...(t.min_p !== undefined ? { min_p: t.min_p } : {}) }; const r = await fetch("/api/report/voices", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "character-set", scope: c.layer, id: c.id, tuning }) }).catch(() => null); const j = (await r?.json().catch(() => null)) as { error?: string; notes?: string[] } | null; if (!r?.ok) return `not kept: ${j?.error ?? (r ? `HTTP ${r.status}` : "umtool could not be reached")}`; // Every panel of this item reads its baseline again: the character's tuning is the new one now. void refreshReads(project, item); const where = c.layer === "cast" ? "the cast: every project" : "this video only"; const s = (await fetch(`/api/report/voices?project=${encodeURIComponent(project)}&stale=${encodeURIComponent(c.id)}`, { cache: "no-store" }).then((x) => (x.ok ? x.json() : null)).catch(() => null)) as { count?: number; items?: string[] } | null; const items = s?.items ?? []; const stale = !s ? "" : items.length ? ` · ${items.includes(item) ? "this read was" : `${items.length} read${items.length === 1 ? " was" : "s were"}`} made with other settings${items.includes(item) && items.length > 1 ? ` (and ${items.length - 1} more: ${items.filter((x) => x !== item).join(", ")})` : items.includes(item) ? "" : `: ${items.join(", ")}`}` : " · every read of theirs is made with these"; return `kept for ${c.name} (${where}): ${words(t)}${(j?.notes ?? []).map((n) => ` · ${n}`).join("")}${stale}`; }; } /** * One piece of one item (`role`): its character and keeper (none: no button), and its Tune's baseline from how it was * last made (`made`: its recorded tuning and `tuningAsked`) -- null until the item's pieces are known. */ export function useKeepForCharacter(project: string | null | undefined, id: string, role = "post", made: { tuning?: Tuning | null; tuningAsked?: unknown } | null = null): { character: ReadCharacter | null; keepForCharacter: KeepForCharacter | undefined; baseline: TuneBaseline | null; madeOwn: boolean; error: string | null; retry: () => void; refresh: () => Promise; } { const { pieces, error, retry } = useReads(project, id); const piece = pieces?.[role] ?? null; const character = piece?.character ?? null; const keepForCharacter = useMemo(() => (project && character ? keepTuningFor(project, id, character) : undefined), [project, id, character]); const madeOwn = madeOwnOf(made?.tuning ?? null, made?.tuningAsked); const tuningKey = JSON.stringify(piece?.tuning ?? null); const baseline = useMemo( () => (pieces ? { character: character ? { name: character.name, tuning: piece?.tuning ?? null } : null, madeOwn } : null), // eslint-disable-next-line react-hooks/exhaustive-deps [pieces, character?.id, character?.name, tuningKey, madeOwn], ); // The baseline as it is NOW (read again): a press that asks a sampler value of its own checks it first. const refresh = async (): Promise => { if (!project) return null; const p = await refreshReads(project, id); if (!p) return null; const c = p[role]?.character ?? null; return { character: c ? { name: c.name, tuning: p[role]?.tuning ?? null } : null, madeOwn }; }; return { character, keepForCharacter, baseline, madeOwn, error, retry, refresh }; }