"use client"; import Link from "next/link"; import { useCallback, useEffect, useMemo, useState } from "react"; import AppHeader from "@/components/shell/AppHeader"; import { badgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; import { Dialog } from "@/components/ui/dialog"; import { Field, Input, Select, Textarea } from "@/components/ui/field"; import { Panel } from "@/components/ui/panel"; import { Table, TD, TH } from "@/components/ui/table"; import { useHydrated } from "@/components/ui/use-hydrated"; import { privateNameHashWeb, privateTermProblem } from "yt-dlp-transcript-common/lib/research/casePipeline"; import type { CaseStage, CaseStageRun } from "yt-dlp-transcript-common/lib/research/caseTypes"; import { researchCaseHref, researchCasePipelineApi, researchHref } from "@/lib/research/hrefs"; import type { PipelineView } from "@/lib/research/pipeline-types"; import { cn } from "@/lib/utils"; import EvidencePanel from "./stages/EvidencePanel"; import LeadsPanel from "./stages/LeadsPanel"; import VerifyPanel from "./stages/VerifyPanel"; import type { CaseStagePanels } from "./stages/types"; // --------------------------------------------------------------------------- // THE CASE PIPELINE (plans/release-38/research-cases-and-assist.md, lane A): one panel per stage, in order, each // with its manual path (what a person does by hand) and its buttons. Every change is the API's // (app/api/research/cases/[id]/pipeline/**) and the page redraws from what it answers; a long stage runs in the // background and the page follows its record (stages.json) until it ends -- a run from `archilyzer case …` shows // here the same way. // // PRIVATE NAMES never leave this page as text: a typed name is hashed here (Web Crypto) and only the hash is // posted; the field is a password field, so a screenshot shows dots. What the page shows of them is a count, and // what the gate blocked as counts and row ids. // // Stage 4 (the read: the candidate deck, the case-read task, the quote check) is lane B's: until it lands, its // panel is the manual path -- the reader prompts to copy and a box for finding rows. // --------------------------------------------------------------------------- const nf = new Intl.NumberFormat("en-US"); const plural = (n: number, w: string) => `${nf.format(n)} ${w}${n === 1 ? "" : "s"}`; const STAGE_NAV: { id: string; label: string }[] = [ { id: "define", label: "Define" }, { id: "coverage", label: "1 Coverage" }, { id: "candidates", label: "2 Candidates" }, { id: "batches", label: "3 Batches" }, { id: "read", label: "4 Read" }, { id: "merge", label: "5 Merge" }, { id: "privacy", label: "6 Privacy" }, { id: "verify", label: "7 Verify" }, { id: "leads", label: "8 Leads" }, { id: "export", label: "Export" }, { id: "date-checks", label: "9 Date checks" }, { id: "evidence", label: "10 Evidence" }, ]; async function call(url: string, method: string, body?: unknown): Promise { const r = await fetch(url, { method, headers: { "content-type": "application/json" }, ...(body !== undefined ? { body: JSON.stringify(body) } : {}), cache: "no-store" }); const j = (await r.json().catch(() => null)) as (T & { error?: string }) | null; if (!r.ok) throw new Error(j?.error ?? `HTTP ${r.status}`); return j as T; } function RunState({ run }: { run?: CaseStageRun }) { if (!run) return not run; const when = (run.endedAt ?? run.startedAt).replace("T", " ").slice(0, 16); return ( {run.state} {when} · {run.by} ); } function StageLog({ run }: { run?: CaseStageRun }) { if (!run || (!run.log.length && !run.error)) return null; return (
{run.log.slice(-8).map((l, i) => (
{l}
))} {run.error && (
{run.error}
)}
); } function Manual({ children }: { children: React.ReactNode }) { return

By hand: {children}

; } function Counts({ title, of }: { title: string; of: Record }) { const e = Object.entries(of); return (
{title}
{e.length ? (
    {e.map(([k, n]) => (
  • {k} {nf.format(n)}
  • ))}
) : ( none )}
); } type Plan = { title: string; what: string; detail?: unknown; confirm: () => Promise }; /** The editable part of a definition, as the editor's JSON shows it (never the private-name hashes). */ function editable(def: PipelineView["definition"]) { return { subjects: def.subjects, scope: def.scope, eras: def.eras, groups: def.groups, readerPrompts: def.readerPrompts, keyDates: def.keyDates ?? [], status: def.status, privateNames: { note: def.privateNames.note }, }; } export default function CasePipeline({ initial, panels }: { initial: PipelineView; panels?: CaseStagePanels | null }) { const hydrated = useHydrated(); const [view, setView] = useState(initial); const [busy, setBusy] = useState(null); const [status, setStatus] = useState<{ text: string; tone?: "error" } | null>(null); const [plan, setPlan] = useState(null); const [batchShown, setBatchShown] = useState<{ id: string; text: string } | null>(null); const [defText, setDefText] = useState(() => JSON.stringify(editable(initial.definition), null, 2)); const [defError, setDefError] = useState(null); const [term, setTerm] = useState(""); const [rowsText, setRowsText] = useState(""); const [summaryText, setSummaryText] = useState(initial.summary?.text ?? ""); const [W, setW] = useState("30"); const [budget, setBudget] = useState("60000"); const [minRel, setMinRel] = useState("2"); const id = view.case.id; const api = useCallback((op?: string) => researchCasePipelineApi(id, op), [id]); const refresh = useCallback(async () => { const v = await call(api(), "GET"); setView(v); return v; }, [api]); const anyRunning = Object.values(view.stages).some((s) => s?.state === "running"); useEffect(() => { if (!anyRunning) return; const t = setInterval(() => void refresh().catch(() => {}), 1200); return () => clearInterval(t); }, [anyRunning, refresh]); const act = useCallback( async (label: string, fn: () => Promise) => { setBusy(label); setStatus(null); try { const text = await fn(); if (text) setStatus({ text }); } catch (e) { setStatus({ text: (e as Error).message, tone: "error" }); } finally { setBusy(null); } }, [], ); const runStage = (stage: CaseStage, body: Record = {}) => act(stage, async () => { let r: { started: boolean; view: PipelineView }; try { r = await call<{ started: boolean; view: PipelineView }>(api(stage), "POST", body); } catch (e) { // A refused stage still left its record (a failed run): draw it. await refresh().catch(() => {}); throw e; } setView(r.view); const run = r.view.stages[stage]; if (run?.state === "failed") throw new Error(run.error ?? `${stage} failed`); return r.started ? `${stage}: started` : `${stage}: done`; }); const saveDefinition = () => act("define", async () => { let body: unknown; try { body = JSON.parse(defText); } catch (e) { setDefError(`not JSON: ${(e as Error).message}`); return; } try { const v = await call(api(), "PUT", body); setView(v); setDefText(JSON.stringify(editable(v.definition), null, 2)); setDefError(null); return "definition saved"; } catch (e) { setDefError((e as Error).message); } }); const privateNames = (op: "add" | "remove" | "clear") => act("private", async () => { let body: Record = { clear: true }; if (op !== "clear") { const problem = privateTermProblem(term); if (problem) throw new Error(problem); body = { [op]: [await privateNameHashWeb(term)] }; } const r = await call<{ count: number; changed: number; withheld: number }>(api("private-names"), "POST", body); setTerm(""); await refresh(); return op === "add" ? r.changed ? `added: ${plural(r.count, "private name")} (hashed)${r.withheld ? `; withheld in ${plural(r.withheld, "place")} of the candidates and batches` : ""}` : `already there: ${plural(r.count, "private name")}` : op === "remove" ? (r.changed ? `removed: ${r.count} left` : "that name was not there") : "every private name removed"; }); const addRows = () => act("findings", async () => { const rows = rowsText .split("\n") .filter((l) => l.trim()) .map((l, i) => { try { return JSON.parse(l) as unknown; } catch { throw new Error(`line ${i + 1} is not JSON`); } }); const r = await call<{ rows: { row: string }[] }>(api("findings"), "POST", { rows }); setRowsText(""); await refresh(); return `${r.rows.length} ${r.rows.length === 1 ? "row" : "rows"} added: ${r.rows.map((x) => x.row).join(", ")}`; }); const saveSummary = () => act("summary", async () => { await call(api("summary"), "POST", { text: summaryText }); await refresh(); return "summary saved as yours"; }); const showBatch = (b: string) => act("batch", async () => { const r = await fetch(`${api("batch")}?batch=${encodeURIComponent(b)}`, { cache: "no-store" }); if (!r.ok) throw new Error((await r.json().catch(() => null))?.error ?? `HTTP ${r.status}`); setBatchShown({ id: b, text: await r.text() }); }); const askGap = (action: "download-missing" | "transcribe" | "persist" | "focus", slug = "") => act("gap", async () => { const r = await call<{ plan: { route: string; request: unknown; what: string; dryRun?: unknown; dryRunError?: string } }>(api("gap"), "POST", { action, slug }); setPlan({ title: action === "focus" ? "Focus the case" : `${action} · ${slug}`, what: r.plan.what, detail: { route: r.plan.route, request: r.plan.request, ...(r.plan.dryRun ? { dryRun: r.plan.dryRun } : {}), ...(r.plan.dryRunError ? { dryRunError: r.plan.dryRunError } : {}) }, confirm: async () => { await call(api("gap"), "POST", { action, slug, confirm: true }); setStatus({ text: `asked the editor: ${r.plan.route.replace("/api/ops/", "")}${slug ? ` ${slug}` : ""}` }); }, }); }); const askHandoff = () => act("handoff", async () => { const r = await call<{ plan: { findings: number; sections: { label: string; rows: number }[]; quarantinedLeftOut: number; blocked: { hits: number; rows: string[] } | null } }>(api("handoff"), "POST", { minRelevance: Number(minRel) }); if (r.plan.blocked) throw new Error(`the privacy gate blocks the hand-off: ${r.plan.blocked.hits} private-name hits in ${r.plan.blocked.rows.length} rows (${r.plan.blocked.rows.join(", ")})`); setPlan({ title: "Hand off to the board", what: `Pin ${r.plan.findings} ${r.plan.findings === 1 ? "finding" : "findings"} to the board, one section per reader group${r.plan.quarantinedLeftOut ? `; ${r.plan.quarantinedLeftOut} quarantined left out` : ""}. The board's own hand-offs then draft the article or start the video.`, detail: r.plan.sections, confirm: async () => { const c = await call<{ pinned: number; duplicates: number }>(api("handoff"), "POST", { confirm: true, minRelevance: Number(minRel) }); setStatus({ text: `pinned ${c.pinned} to the board${c.duplicates ? ` (${c.duplicates} already there)` : ""}` }); }, }); }); const s = view.stages; const def = view.definition; const counts = view.candidates.counts; const keyYears = useMemo(() => new Set(view.keyYears), [view.keyYears]); const gateFindings = view.gate.findings; const shownFindings = view.merge?.sections.reduce((n, x) => n + x.rows.length, 0) ?? 0; const dis = !hydrated || busy !== null; return ( <> Research · case pipeline {view.defined ? `${plural(def.subjects.length, "subject")} · ${plural(def.eras.length, "era")} · ${plural(def.groups.length, "reader group")} · ${plural(view.channels.slugs.length, "channel")} · status ${def.status}` : "not defined yet"} } actions={ The board } below={ } />
{status && (
{status.text}
)} {/* ── Define ── */} {view.stored}pipeline.json}> the subjects (and their own channels), the scope (channels, site:group groups, sites), the eras with their term families (regex; a strict family for a subject's own late material), the reader groups (a list of channels, "subject" or "coverage"), the reader prompts and the key dates. Or archilyzer case define {id} --file pipeline.json.