"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import type { CallOutcome, ModelCall, ModelCallText } from "yt-dlp-transcript-common/lib/llm/callLog"; import type { ModelLogView, ModelLogViewGroup, ModelLogViewRow } from "yt-dlp-transcript-common/lib/llm/callLogView"; // --------------------------------------------------------------------------- // THE MODEL LOG (demo epic D3; the record is common's lib/llm/callLog.ts): the // model's side of a run -- every call, grouped by phase (terms → reading → // meaning check → grouping, then any other), each row what was asked (its // first lines), what came back, what code did with it and why, and the // seconds. A row opens to the whole prompt and answer, fetched for that row // alone; a group shows a page at a time. The count header: calls, seconds, // the model(s) and route. Filter: kept / dropped / rewritten. // // LIVE while the host's run is: GET the view every `pollMs` while the tab is // visible, one request at a time (the run page's own cadence). Works with no // AI configured: with no call recorded it says what will appear. // --------------------------------------------------------------------------- export type ModelLogSourceProp = { article: string; n: number } | { job: string }; const FILTERS: { key: "all" | CallOutcome; label: string }[] = [ { key: "all", label: "All" }, { key: "kept", label: "Kept" }, { key: "dropped", label: "Dropped" }, { key: "rewritten", label: "Rewritten" }, ]; const ROUTE_LABEL: Record = { local: "local", api: "Claude API", "claude-code": "Claude Code" }; const secs = (s: number) => (s >= 60 ? `${Math.floor(s / 60)} min ${Math.round(s % 60)} s` : `${s.toFixed(1)} s`); function base(source: ModelLogSourceProp, extra: Record): string { const sp = new URLSearchParams(); if ("job" in source) sp.set("job", source.job); else { sp.set("article", source.article); sp.set("n", String(source.n)); } for (const [k, v] of Object.entries(extra)) if (v !== undefined && v !== "") sp.set(k, String(v)); return sp.toString(); } const OUTCOME_TONE: Record = { kept: "text-kept-text", dropped: "text-reject-text", rewritten: "text-doubt-text", "n/a": "text-muted-2", }; function Outcome({ o }: { o: CallOutcome }) { return {o}; } function Pre({ children, className, ...props }: { children: string; className?: string } & Omit, "children">) { return
{children}
; } function Items({ items, total }: { items: ModelCall["items"]; total: number }) { if (!items?.length) return null; return (
    {items.map((it, i) => (
  • {it.text} {it.why && {it.outcome === "kept" ? it.why : `why: ${it.why}`}}
  • ))} {total > items.length &&
  • + {total - items.length} more — open the call
  • }
); } function CallRow({ row, source }: { row: ModelLogViewRow; source: ModelLogSourceProp }) { const [open, setOpen] = useState(false); const [full, setFull] = useState<{ call: ModelCall; text: ModelCallText | null } | null>(null); const [error, setError] = useState(""); const [showSystem, setShowSystem] = useState(false); const toggle = async () => { const next = !open; setOpen(next); if (!next || full) return; try { const r = await fetch(`/api/model-log/call?${base(source, { id: row.id })}`, { cache: "no-store" }); const b = await r.json().catch(() => ({})); if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); setFull(b); } catch (e) { setError((e as Error).message); } }; const d = row.decision; return (
  • {!open && row.itemsTotal > 0 && (
    )} {open && (
    {error && (

    {error}

    )} {!full && !error &&

    Reading the call…

    } {full && ( <>
    {row.model} {ROUTE_LABEL[row.route] ?? row.route} {row.promptChars.toLocaleString("en-US")} characters asked {row.tokensIn !== undefined && ( {row.tokensIn.toLocaleString("en-US")} tokens in · {(row.tokensOut ?? 0).toLocaleString("en-US")} out )} {row.at.slice(11, 19)} UTC
    {full.text ? ( <> {full.text.system && (
    {showSystem &&
    {full.text.system}
    }
    )}
    Asked
    {full.text.prompt + (full.text.promptCut ? "\n… (cut at 40,000 characters)" : "")}
    Came back
    {(full.text.answer || "(empty)") + (full.text.answerCut ? "\n… (cut at 40,000 characters)" : "")}
    ) : (

    This call's text was not kept.

    )} )}
    )}
  • ); } function Group({ g, source, more }: { g: ModelLogViewGroup; source: ModelLogSourceProp; more: (g: ModelLogViewGroup) => Promise }) { const [busy, setBusy] = useState(false); return (

    {g.label} {g.calls} {g.calls === 1 ? "call" : "calls"} · {secs(g.seconds)}

    {g.rows.length === 0 ? (

    None matches the filter.

    ) : (
      {g.rows.map((r) => ( ))}
    )} {g.more > 0 && ( )}
    ); } export default function ModelLog({ source, task, jobId, latest, near, live = false, pollMs = 2500, emptyText, className, }: { source: ModelLogSourceProp; /** Only this task's runs (a media draft's). */ task?: string; /** Only this job's run. */ jobId?: string; /** The newest run (of `task`). */ latest?: boolean; /** The run that began nearest this ISO time (the run page's trace run). */ near?: string | null; live?: boolean; pollMs?: number; /** What the empty state says will appear. */ emptyText?: string; className?: string; }) { const [view, setView] = useState(null); const [error, setError] = useState(""); const [filter, setFilter] = useState<"all" | CallOutcome>("all"); // Rows a "N more" added, kept across polls (by phase). const extra = useRef(new Map()); const inFlight = useRef(false); // The source by value: a host passes a fresh object each render. const sourceKey = base(source, {}); const query = useCallback( (more: Record = {}) => { const sp = new URLSearchParams(sourceKey); for (const [k, v] of Object.entries({ task, jobId, latest: latest ? 1 : undefined, near: near ?? undefined, outcome: filter === "all" ? undefined : filter, ...more })) if (v !== undefined && v !== "") sp.set(k, String(v)); return sp.toString(); }, [sourceKey, task, jobId, latest, near, filter], ); const load = useCallback(async () => { if (inFlight.current) return; inFlight.current = true; try { const r = await fetch(`/api/model-log?${query()}`, { cache: "no-store" }); const b = await r.json().catch(() => ({})); if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); setView(b as ModelLogView); setError(""); } catch (e) { setError((e as Error).message); } finally { inFlight.current = false; } }, [query]); useEffect(() => { extra.current.clear(); void load(); }, [load]); useEffect(() => { if (!live) return; const t = window.setInterval(() => { if (document.visibilityState === "visible") void load(); }, pollMs); return () => window.clearInterval(t); }, [live, pollMs, load]); // A run that just ended: one last read, so the final calls are shown. const wasLive = useRef(live); useEffect(() => { if (wasLive.current && !live) void load(); wasLive.current = live; }, [live, load]); const more = useCallback( async (g: ModelLogViewGroup) => { const have = g.rows.length + (extra.current.get(g.phase)?.length ?? 0); const r = await fetch(`/api/model-log?${query({ phase: g.phase, offset: have })}`, { cache: "no-store" }); const b = (await r.json().catch(() => null)) as ModelLogView | null; const page = b?.groups.find((x) => x.phase === g.phase); if (!r.ok || !page) return; extra.current.set(g.phase, [...(extra.current.get(g.phase) ?? []), ...page.rows]); setView((v) => (v ? { ...v } : v)); }, [query], ); const groups = (view?.groups ?? []).map((g) => { const added = extra.current.get(g.phase) ?? []; const seen = new Set(g.rows.map((r) => r.id)); const rows = [...g.rows, ...added.filter((r) => !seen.has(r.id))]; return { ...g, rows, more: Math.max(0, g.calls - rows.length) }; }); const s = view?.summary; const empty = view && view.counts.all === 0; return (
    {s ? ( <> {s.calls} {s.calls === 1 ? "call" : "calls"} · {secs(s.seconds)} {s.models.length > 0 && ( <> {" "} ·{" "} m.model).join(" ")}> {s.models.map((m) => `${m.model} (${ROUTE_LABEL[m.route] ?? m.route})`).join(", ")} )} {s.failed > 0 && · {s.failed} failed} ) : ( "Model log" )}
    {error && (

    {error}

    )} {view?.full && (

    The log is full ({view.cap.calls.toLocaleString("en-US")} calls or {view.cap.megabytes} MB): calls made after that were not recorded.

    )} {empty ? (

    {emptyText ?? (live ? "No model call yet. Each call appears here as it is made: what was asked, what came back, and what code kept or dropped." : "No model call recorded. When a model works on this, each call appears here: what was asked, what came back, and what code kept or dropped.")}

    ) : ( groups.map((g) => ) )}
    ); }