"use client"; import Link from "next/link"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import AppHeader from "@/components/shell/AppHeader"; import { buttonVariants } from "@/components/ui/button"; import { badgeVariants } from "@/components/ui/badge"; import { KeyHint } from "@/components/ui/kbd"; import { LitList, type LitDetail } from "@/components/ui/lit-list"; import { LitLine } from "@/components/ui/lit-line"; import { useHydrated } from "@/components/ui/use-hydrated"; import { triageHref } from "@/lib/hrefs"; import type { FlagMark, TriageRunView } from "@/lib/research/triage-types"; import { partialWords, thresholdWords, type TriageDismissal, type TriageFlag } from "yt-dlp-transcript-common/lib/report/draft/triage/types"; import { cn } from "@/lib/utils"; // --------------------------------------------------------------------------- // ONE TRIAGE RUN (plans/umtool-redesign.md, R6): the tiers of a recurring // report's cheap pass, transparent -- // // tier 0 code, $0: what was new (by id since the last run), which of it // matched the terms or the digest topics -- the candidates // tier 1 the window judge (the local model, or the extractor): each FLAG // with its verbatim line on the reader surface, its cite and the // judge's reason; each DISMISSAL with why (not relevant, not // verbatim, a mention only) // tier 2 what escalated and why: the sweep of the flagged recordings (its // run page, its findings, its spend) -- or that nothing did // // ONE lit list of the flags then the dismissals; `y` / `x` marks the lit flag // right or wrong (`u` unmarks), kept per schedule: the schedule's precision // and the threshold the marks suggest (a suggestion, never applied). `b` opens // the flags as a research board (`by: triage`). The editor wrote the run; // umtool writes only the marks and the board. // --------------------------------------------------------------------------- const money = (v: number | null | undefined) => (typeof v === "number" ? `$${v.toFixed(2)}` : "—"); const mmss = (s: number) => { const t = Math.floor(s); const h = Math.floor(t / 3600); const m = Math.floor((t % 3600) / 60); const ss = String(t % 60).padStart(2, "0"); return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`; }; const when = (iso: string | null | undefined) => (iso ? `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC` : ""); const pct = (v: number | null) => (v === null ? "—" : `${Math.round(v * 100)}%`); const STAGE_WORDS: Record = { judge: "not relevant", verbatim: "not verbatim", score: "too weak", read: "not read" }; /** Source words: the reader surface. */ function Paper({ children, className, ...props }: React.ComponentProps<"div">) { return (
{children}
); } type Lit = { kind: "flag"; flag: TriageFlag } | { kind: "dismissal"; d: TriageDismissal; i: number }; export default function TriageView({ initial }: { initial: TriageRunView }) { const hydrated = useHydrated(); const [view, setView] = useState(initial); const [litId, setLitId] = useState(null); const [busy, setBusy] = useState(false); const [status, setStatus] = useState<{ text: string; tone: "ok" | "error"; href?: string } | null>(null); const listRef = useRef(null); const f = view.file; const flags = useMemo(() => [...(f.tier1?.flags ?? [])].sort((a, b) => b.score - a.score || Number(a.f.slice(1)) - Number(b.f.slice(1))), [f.tier1]); const dismissed = f.tier1?.dismissed ?? []; const items: { id: string; lit: Lit }[] = useMemo( () => [...flags.map((x) => ({ id: x.f, lit: { kind: "flag" as const, flag: x } })), ...dismissed.map((d, i) => ({ id: `d${i + 1}`, lit: { kind: "dismissal" as const, d, i } }))], [flags, dismissed], ); const lit = items.find((x) => x.id === litId)?.lit ?? items[0]?.lit ?? null; const onLight = useCallback((d: LitDetail) => setLitId(d.id), []); const mark = useCallback( async (flag: TriageFlag, verdict: "right" | "wrong" | null) => { setBusy(true); setStatus(null); try { const r = await fetch(`/api/research/triage/${encodeURIComponent(view.schedule.id)}/${view.k}/marks`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ f: flag.f, verdict }), }); const j = (await r.json().catch(() => null)) as { error?: string; marks?: Record; precision?: TriageRunView["precision"]; suggestion?: TriageRunView["suggestion"] } | null; if (!r.ok || !j?.marks) throw new Error(j?.error ?? `HTTP ${r.status}`); setView((v) => ({ ...v, marks: j.marks!, precision: j.precision!, suggestion: j.suggestion! })); setStatus({ tone: "ok", text: verdict ? `${flag.f} marked ${verdict}` : `${flag.f} unmarked` }); } catch (e) { setStatus({ tone: "error", text: (e as Error).message }); } finally { setBusy(false); } }, [view.schedule.id, view.k], ); const openBoard = useCallback(async () => { setBusy(true); setStatus(null); try { const r = await fetch(`/api/research/triage/${encodeURIComponent(view.schedule.id)}/${view.k}/board`, { method: "POST" }); const j = (await r.json().catch(() => null)) as { error?: string; id?: string; href?: string; created?: boolean; added?: number; already?: number } | null; if (!r.ok || !j?.href) throw new Error(j?.error ?? `HTTP ${r.status}`); setStatus({ tone: "ok", href: j.href, text: `${j.created ? "Board made" : "Board updated"}: ${j.added ?? 0} ${j.added === 1 ? "flag" : "flags"} added${j.already ? `, ${j.already} already on it` : ""}` }); setView((v) => ({ ...v, board: { ...v.board, exists: true, quotes: v.board.quotes + (j.added ?? 0) } })); } catch (e) { setStatus({ tone: "error", text: (e as Error).message }); } finally { setBusy(false); } }, [view.schedule.id, view.k]); // Keys: y right, x wrong, u unmark (the lit flag); b opens the board. useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return; if ((e.target as HTMLElement | null)?.closest?.("input, textarea, select, [contenteditable], dialog")) return; if (busy) return; if (e.key === "b" && flags.length) { e.preventDefault(); void openBoard(); return; } if (lit?.kind !== "flag") return; const verdict = e.key === "y" ? "right" : e.key === "x" ? "wrong" : e.key === "u" ? null : undefined; if (verdict === undefined) return; e.preventDefault(); void mark(lit.flag, verdict); }; document.addEventListener("keydown", onKey); return () => document.removeEventListener("keydown", onKey); }, [busy, flags.length, lit, mark, openBoard]); const t0 = f.tier0; const t1 = f.tier1; const esc = f.escalation; const t2 = view.tier2; const capped = view.tick?.triage?.capped ?? null; const p = view.precision; return ( <> Triage · {view.schedule.shape} · {f.status} } actions={ <> {view.runs.length > 1 && ( )} } below={

{f.question}

{f.model} · {f.scope.channels.join(", ")} {f.terms && ( <> · {f.terms} )} {f.topics.length > 0 && ( <> · topics {f.topics.join(", ")} )} · {when(f.startedAt ?? f.createdAt)} · threshold {thresholdWords(f.threshold)}
{(f.warnings.length > 0 || f.error) && (
{f.warnings.map((w) => (

{w}

))} {f.error &&

{f.error}

}
)}
} />
{items.length === 0 ? (

{f.status === "done" ? (t0?.candidates.length ? "The judge flagged and dismissed nothing." : "No candidate: nothing new matched.") : `The run is ${f.status}.`}

) : ( {flags.length > 0 &&

Flags {flags.length}

} {flags.map((x) => { const m = view.marks[x.f]; return ( {x.f} “{x.line}” {x.title ?? x.id} @ {mmss(x.at)} · {x.reason} {x.strength} {m && {m.verdict}} ); })} {dismissed.length > 0 &&

Dismissed {dismissed.length}

} {dismissed.map((d, i) => ( d{i + 1} {d.line ? `“${d.line}”` : `${d.title ?? d.id}${d.window ? ` @ ${mmss(d.window.start)}–${mmss(d.window.end)}` : ""}`} {d.reason} {STAGE_WORDS[d.stage]} ))}
)}
Tier 0 · code {money(f.cost.tier0)}

{t0 ? ( <> {t0.candidates.length} candidate{t0.candidates.length === 1 ? "" : "s"} of{" "} {t0.newCount} new{" "} {t0.newBy === "id" ? "by id since the last run" : t0.newBy === "date" ? `since ${f.since ?? "the start"}` : "named"} {t0.scanned ? ` · ${t0.scanned} in scope` : ""} {t0.untranscribed ? ( {" "} · {t0.untranscribed} without a transcript yet ) : null} {t0.learned?.spellings.length ? ( `“${x}”`).join(", ")}> {" "} · terms + {t0.learned.spellings.length} learned ({t0.learned.matched} by a learned spelling alone) ) : null} {t0.cut.length ? · {t0.cut.length} past the cap : null} {t0.partial ? ( {" "} · partial — {partialWords(t0)} ) : null} ) : ( "not run" )}

Tier 1 · {f.provider === "local" ? "local model" : "extractor"} {money(f.cost.tier1)}

{t1 ? ( <> {t1.flags.length} flagged · {t1.dismissed.length} dismissed · {t1.read} read, {t1.chunks} window {t1.chunks === 1 ? "" : "s"} judged ) : ( "not run" )}

Tier 2 · sweep {money(t2?.usd ?? view.tick?.triage?.usd.tier2 ?? 0)}

{t2 ? ( <> {t2.article} i{t2.n} {" "} · {t2.status ?? "?"} {t2.findings !== null ? ` · ${t2.findings} finding${t2.findings === 1 ? "" : "s"}` : ""} ) : capped ? ( held: {capped} ) : esc?.escalate ? ( "escalated (the step did not make an iteration)" ) : ( "not escalated: $0 API" )}

{esc ? (esc.escalate ? (capped ? "Would escalate" : "Escalated") : "Below the threshold") : f.summary} {esc ? ` — ${esc.why}` : ""} {view.tick ? · the tick ended {view.tick.status}, {money(view.tick.usd)} in all : null}

{lit?.kind === "flag" && (
{lit.flag.f} · {lit.flag.strength} flag · score {lit.flag.score} · checked {lit.flag.checked === "cues" ? "against the cues" : "in its window"}

“{lit.flag.line}”

{lit.flag.url ? ( {lit.flag.title ?? lit.flag.id} @ {mmss(lit.flag.at)} ) : ( `${lit.flag.title ?? lit.flag.id} @ ${mmss(lit.flag.at)}` )}{" "} · {lit.flag.channel}/{lit.flag.id} {lit.flag.date ? ` · ${lit.flag.date}` : ""} · window {mmss(lit.flag.window.start)}–{mmss(lit.flag.window.end)}

why: {lit.flag.reason}

{view.marks[lit.flag.f] && ( )}
)} {lit?.kind === "dismissal" && (
d{lit.i + 1} · dismissed · {STAGE_WORDS[lit.d.stage]} {lit.d.line && (

“{lit.d.line}”

{lit.d.title ?? lit.d.id} {lit.d.at !== undefined ? ` @ ${mmss(lit.d.at)}` : ""}
)} {!lit.d.line && (

{lit.d.title ?? lit.d.id} {lit.d.window ? ` · window ${mmss(lit.d.window.start)}–${mmss(lit.d.window.end)}` : ""}

)}

why: {lit.d.reason}

)}
Candidates {t0?.candidates.length ?? 0} {t0?.candidates.length ? (
    {t0.candidates.map((c) => (
  • {c.id} {c.title ?? ""} {c.date ?? ""} ·{" "} {c.by.map((x) => (x === "learned" && c.learned?.length ? `learned ${c.learned.map((l) => `“${l}”`).join(", ")}` : x)).join(" + ")} {c.tags?.length ? ` (${c.tags.join(", ")})` : ""} {c.matches ? ` · ${c.matches} line${c.matches === 1 ? "" : "s"}` : ""}
  • ))}
) : (

none

)}
Precision · {view.schedule.id}

{p.marked ? ( <> {pct(p.precision)} right over {p.marked} marked flag{p.marked === 1 ? "" : "s"} (strong {p.byStrength.strong.right}/ {p.byStrength.strong.right + p.byStrength.strong.wrong}, weak {p.byStrength.weak.right}/{p.byStrength.weak.right + p.byStrength.weak.wrong}) ) : ( "no flag marked yet" )}

{view.suggestion.changed ? ( <> Suggested threshold: {thresholdWords(view.suggestion.threshold)} (now {thresholdWords(view.schedule.threshold)}) — {view.suggestion.why}. A suggestion: the schedule's threshold is changed on its page. ) : ( view.suggestion.why )}

flag right wrong unmark open as a board {view.schedule.topic} {view.board.exists && ( Board · {view.board.quotes} {view.board.quotes === 1 ? "quote" : "quotes"} )} {status && ( {status.text} {status.href && ( <> {" · "} Open the board )} )}
); }