"use client";
import Link from "next/link";
import { useCallback, useEffect, useRef, useState } from "react";
import AppHeader from "@/components/shell/AppHeader";
import { buttonVariants } from "@/components/ui/button";
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 { ARTICLES_KEY } from "@/lib/articles/key.mjs";
import { articleHref } from "@/lib/hrefs";
import { researchCaseHref, researchHref } from "@/lib/research/hrefs";
import { runApi, runBoardApi, runHref, runsHref } from "@/lib/research/runs-hrefs";
import type { RunCheck, RunCite, RunStep, RunView as View } from "@/lib/research/runs-types";
import { cn } from "@/lib/utils";
import SpendChart, { type SpendPoint } from "./SpendChart";
import ModelLog from "@/components/model-log/ModelLog";
// ---------------------------------------------------------------------------
// A TRANSPARENT RUN (plans/umtool-redesign.md, R3; canvas "Transparent run"):
// the head -- the question, the model and extractor, the scope, the time, the
// spend, the checks -- then ONE lit list of the run's steps (scope, each turn
// or batch, findings, the quote checks kept and dropped, the end) with the
// running spend on each, and beside it the lit step's detail: the ids, the
// extractor's own lines on the reader surface, the quotes kept and dropped
// with why, and the spend chart.
//
// LIVE while the run is (the view's `live`): GET the view every POLL_MS while
// the tab is visible, one request at a time; the lit line follows the newest
// step until the operator moves it. REPLAY when it is done: `r` (or Replay)
// lights the steps one after another from the first.
// ---------------------------------------------------------------------------
export const POLL_MS = 2500;
const REPLAY_MS = 650;
const money = (v: number | null | undefined) => (typeof v === "number" ? `$${v.toFixed(2)}` : "—");
const thousands = (n: number) => n.toLocaleString("en-US");
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}`;
};
function prettyModel(id: string | null | undefined): string | null {
if (!id) return null;
const m = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?$/.exec(id);
return m ? `${m[1]![0]!.toUpperCase()}${m[1]!.slice(1)} ${m[2]}${m[3] ? `.${m[3]}` : ""}` : id;
}
function when(iso: string | null): string {
if (!iso) return "";
const d = new Date(iso);
return Number.isNaN(d.getTime()) ? "" : `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC`;
}
function citeLine(c: RunCite): string {
return [c.label ?? null, c.channel && c.video ? `${c.channel}/${c.video}` : (c.video ?? null), typeof c.start === "number" ? mmss(c.start) : null, c.citation ?? null].filter(Boolean).join(" · ");
}
function Ids({ ids, max = 160 }: { ids: string[]; max?: number }) {
const [all, setAll] = useState(false);
const shown = all ? ids : ids.slice(0, max);
return (
{shown.map((id, i) => (
{id}
))}
{ids.length > shown.length && (
setAll(true)}>
+ {thousands(ids.length - shown.length)} more
)}
);
}
/** Source words (the extractor's lines, a quote): the reader surface. */
function Paper({ children, className, ...props }: React.ComponentProps<"div">) {
return (
{children}
);
}
function CheckRow({ c }: { c: RunCheck }) {
const tone = c.ok ? "kept" : c.dropped ? "dropped" : "refused";
return (
{tone}
{c.round ? ` · r${c.round}` : ""}
{c.quote && (
“{c.quote}”
{citeLine(c.cite)}
)}
{c.claim &&
claim: {c.claim}
}
{c.reason && (
{c.ok ? c.reason : `why: ${c.reason}`}
)}
);
}
function Checks({ checks }: { checks: RunCheck[] }) {
const dropped = checks.filter((c) => c.dropped);
const refused = checks.filter((c) => !c.ok && !c.dropped);
const kept = checks.filter((c) => c.ok && c.stage === "final");
const extractKept = checks.filter((c) => c.ok && c.stage === "extract");
const group = (title: string, list: RunCheck[], key: string) =>
list.length > 0 && (
{title} {list.length}
{list.map((c, i) => (
))}
);
return (
{group("Dropped", dropped, "dropped")}
{group("Refused by a strict check", refused, "refused")}
{group("Kept", kept, "kept")}
{!kept.length && group("Kept in their windows", extractKept, "extract")}
);
}
function Detail({ step }: { step: RunStep }) {
const d = step.detail;
return (
{step.t !== "—" ? `${step.t} · ` : ""}
{step.label}
{step.stepUsd !== null ? ` · ${money(step.stepUsd)} this step` : ""}
{d.facts.length > 0 && (
{d.facts.map(([k, v]) => (
{k}
{v}
))}
)}
{d.triage && (
{d.triage.flagged.length > 0 && }
Triage {d.triage.owner} · run {d.triage.k}
)}
{d.text &&
{d.text}
}
{d.calls.length > 0 && (
{d.calls.map((c, i) => (
{c.name}
{c.summary ? ` ${c.summary}` : ""}
{c.chars !== null ? → {thousands(c.chars)} chars : null}
{c.error ? (error) : null}
))}
)}
{d.enumerations.map((e, i) => (
enumerate {e.query ? `“${e.query}”` : ""} · {thousands(e.n)} matched
{e.total !== null && e.total !== e.n ? ` of ${thousands(e.total)}` : ""}
{e.posts ? ` (${e.posts} posts)` : ""}
{e.partial ? · COVERAGE PARTIAL : null}
{e.unreached.length ? · never reached: {e.unreached.join(", ")} : null}
{e.ids.length > 0 && }
))}
{d.batches.map((b, i) => (
batch {b.k}
{b.of ? ` of ${b.of}` : ""} · {b.ids.length} ids{b.model ? ` · ${prettyModel(b.model)}` : ""}
{b.usd !== null ? ` · ${money(b.usd)}` : ""}
{b.cut ? · cut at the extractor's input cap : null}
{b.lines === null ? (
The extractor's lines were not kept (a run before the trace).
) : b.lines.length ? (
{b.lines.map((l, k) => (
{l}
))}
) : (
The extractor returned nothing for this batch.
)}
))}
{d.reads.length > 0 && (
read
{d.reads.map((r, i) => (
{r.tool}
))}
)}
{d.findings.length > 0 && (
{d.findings.map((f, i) => (
{f.section}
{f.claim}
{f.cites.filter((c) => c.quote).map((c, k) => (
“{c.quote}”
{citeLine(c)}
))}
))}
)}
{d.checks.length > 0 &&
}
{d.notes.map((n, i) => (
{n}
))}
);
}
export type RunPane = "steps" | "model";
export default function RunView({ initial, initialPane = "steps" }: { initial: View; initialPane?: RunPane }) {
const hydrated = useHydrated();
const [view, setView] = useState(initial);
// The steps (the trace) or the model log (every call, demo epic D3); `?view=model` in the address.
const [pane, setPane] = useState(initialPane);
const choosePane = useCallback((p: RunPane) => {
setPane(p);
try {
const u = new URL(window.location.href);
if (p === "model") u.searchParams.set("view", "model");
else u.searchParams.delete("view");
window.history.replaceState(window.history.state, "", u);
} catch {
// the address is a convenience
}
}, []);
const [litId, setLitId] = useState(null);
const [replaying, setReplaying] = useState(false);
const [status, setStatus] = useState<{ text: string; tone: "ok" | "error"; href?: string } | null>(null);
const [busy, setBusy] = useState(false);
const [updated, setUpdated] = useState(null);
const listRef = useRef(null);
const follow = useRef(initial.live);
const inflight = useRef(false);
// Live: poll while the run is, and while the tab is visible.
useEffect(() => {
if (!view.live) return;
let live = true;
const tick = async () => {
if (inflight.current || document.visibilityState === "hidden") return;
inflight.current = true;
try {
const r = await fetch(runApi(view.article, view.n, { run: view.run }), { cache: "no-store" });
const next = r.ok ? ((await r.json()) as View) : null;
if (live && next?.steps) {
setView(next);
setUpdated(new Date().toISOString());
}
} catch {
// the next tick asks again
} finally {
inflight.current = false;
}
};
const timer = window.setInterval(tick, POLL_MS);
const onVisible = () => {
if (document.visibilityState === "visible") void tick();
};
document.addEventListener("visibilitychange", onVisible);
return () => {
live = false;
window.clearInterval(timer);
document.removeEventListener("visibilitychange", onVisible);
};
}, [view.live, view.article, view.n, view.run]);
const lineOf = useCallback((id: string) => listRef.current?.querySelector(`[data-lit-line][data-lit-id="${CSS.escape(id)}"]`) ?? null, []);
// Following a live run: the newest step is lit as it lands (a click lights
// without taking focus), until the operator moves the light.
const lastId = view.steps.at(-1)?.id ?? null;
useEffect(() => {
if (!follow.current || !lastId) return;
lineOf(lastId)?.click();
}, [lastId, lineOf]);
const onLight = useCallback(
(d: LitDetail) => {
setLitId(d.id);
if (d.id !== lastId) follow.current = false;
else if (view.live) follow.current = true;
},
[lastId, view.live],
);
// Replay: light every step in turn from the first.
useEffect(() => {
if (!replaying) return;
const ids = view.steps.map((s) => s.id);
let i = 0;
follow.current = false;
const go = () => {
const el = lineOf(ids[i]!);
if (el) {
el.focus({ preventScroll: true });
el.scrollIntoView({ block: "nearest" });
}
i++;
if (i >= ids.length) setReplaying(false);
};
go();
const timer = window.setInterval(go, REPLAY_MS);
const stop = (e: Event) => {
if (e instanceof KeyboardEvent && (e.key === "r" || e.key === "R")) return;
setReplaying(false);
};
window.addEventListener("pointerdown", stop);
window.addEventListener("keydown", stop);
return () => {
window.clearInterval(timer);
window.removeEventListener("pointerdown", stop);
window.removeEventListener("keydown", stop);
};
}, [replaying, view.steps, lineOf]);
const openBoard = useCallback(async () => {
setBusy(true);
setStatus(null);
try {
const r = await fetch(runBoardApi(view.article, view.n), { 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 ? "quote" : "quotes"} added${j.already ? `, ${j.already} already on it` : ""}`,
});
setView((v) => ({ ...v, board: { id: j.id!, quotes: (v.board?.quotes ?? 0) + (j.added ?? 0) } }));
} catch (e) {
setStatus({ tone: "error", text: (e as Error).message });
} finally {
setBusy(false);
}
}, [view.article, view.n]);
// Keys: r replays, b opens the board. Never while typing or with a modifier.
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 (e.key === "r" && !view.live && view.steps.length) {
e.preventDefault();
setReplaying((x) => !x);
} else if (e.key === "b" && view.findings > 0 && !busy) {
e.preventDefault();
void openBoard();
}
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [view.live, view.steps.length, view.findings, busy, openBoard]);
const h = view.header;
const lit = view.steps.find((s) => s.id === litId) ?? view.steps[0] ?? null;
const points: SpendPoint[] = view.steps.filter((s) => s.usd !== null && s.kind !== "end").map((s) => ({ id: s.id, t: s.t === "—" ? s.kind : s.t, label: s.label, usd: s.usd! }));
const batches = view.steps.flatMap((s) => s.detail.batches);
const findingSteps = view.steps.find((s) => s.kind === "findings");
const sections = findingSteps ? new Set(findingSteps.detail.findings.map((f) => f.section)).size : 0;
const cov = h.coverage;
const checkNames = h.checks.map((c) => (
{c.name} {c.ok ? "ok" : "failed"}
));
const meta: React.ReactNode[] = [
view.kind,
[prettyModel(h.model), h.extractor ? `${prettyModel(h.extractor)} extractor` : null].filter(Boolean).join(" · "),
h.channels.join(", "),
h.dateFrom || h.dateTo ? `${h.dateFrom ?? "…"} – ${h.dateTo ?? "…"}` : null,
h.sourceLabel,
when(h.startedAt),
h.minutes !== null ? `${h.minutes} min` : null,
].filter(Boolean);
return (
<>
Run · {view.live ? "live" : "replay"}
{view.live && updated ? ` · updated ${updated.slice(11, 19)}` : ""}
{view.from === "turns" ? " · from turns.jsonl" : ""}
}
actions={
<>
{(["steps", "model"] as const).map((p) => (
choosePane(p)}
className={cn(buttonVariants({ variant: pane === p ? "pressed" : "quiet", size: "sm" }))}
>
{p === "steps" ? "Steps" : "Model log"}
))}
{view.runs.length > 1 && (
Run
{view.runs.map((r) => (
{r.index}
))}
)}
setReplaying((x) => !x)}
data-replay={replaying ? "on" : "off"}
>
{replaying ? "Stop" : "Replay"} r
void openBoard()} data-open-board="">
{view.board ? "Update the board" : "Open as a board"} b
>
}
below={
{meta.map((m, i) => (
{i > 0 && · }
{m}
))}
·
{money(h.usd)} this run
{view.runs.length > 1 || (h.usd !== null && Math.abs((h.usd ?? 0) - h.iterationUsd) >= 0.01) ? (
<>
{" "}· {money(h.iterationUsd)} on the iteration
>
) : null}
{(h.kept !== null || h.dropped !== null) && (
·
{h.kept !== null ? `${h.kept} kept` : ""}
{h.kept !== null && h.dropped !== null ? " · " : ""}
{h.dropped !== null ? {h.dropped} dropped : null}
)}
{checkNames.length > 0 && (
·
{checkNames}
)}
·
{view.status}
{(view.notes.length > 0 || h.error) && (
{view.notes.map((n) => (
{n}
))}
{h.error &&
{h.error}
}
)}
}
/>
{pane === "model" ? (
) : view.steps.length === 0 ? (
{view.live ? "The run has not written a step yet." : "This iteration recorded no run (no trace.jsonl, no turns.jsonl)."}
) : (
// On a phone the steps, then the lit step's detail, one column the page scrolls.
{view.steps.map((s) => (
{s.t}
{s.label}
{s.sub && {s.sub} }
{s.gap ? "—" : s.usd !== null ? money(s.usd) : ""}
))}
Batches
{batches.length ? (
<>
{batches.length}
{batches.some((b) => b.of) ? ` of ${Math.max(...batches.map((b) => b.of ?? 0))}` : ""} returned
{batches.every((b) => b.lines) ? ` · ${thousands(batches.reduce((n, b) => n + (b.lines?.length ?? 0), 0))} lines` : " · lines not kept"}
>
) : (
"none"
)}
Findings
{findingSteps ? `${findingSteps.detail.findings.length} findings · ${sections} sections · ${view.findings} quotes` : view.live ? "not yet" : "none kept"}
Coverage
{cov ? (
<>
{thousands(cov.matched)} matched · {thousands(cov.read)} read ·{" "}
{cov.partial ? partial : "complete"}
{cov.unreached.length ? ` · not reached: ${cov.unreached.join(", ")}` : ""}
>
) : (
"not recorded (a run before the trace)"
)}
{lit &&
}
Spend by step, cumulative
{
const el = lineOf(id);
el?.focus({ preventScroll: true });
el?.scrollIntoView({ block: "nearest" });
}}
/>
)}
step
replay
open as a board
{view.article} · iterations
{view.board && (
Board · {view.board.quotes} {view.board.quotes === 1 ? "quote" : "quotes"}
)}
{status && (
{status.text}
{status.href && (
<>
{" · "}
Open the board
>
)}
)}
>
);
}