"use client"; import { useCallback, useEffect, useState } from "react"; import { Button } from "@/components/ui/button"; import ExtractorSelect, { extractorBody } from "@/components/articles/ExtractorSelect"; import { badgeVariants } from "@/components/ui/badge"; import type { IterationRow } from "@/lib/articles/generation"; import type { ResearchProposal, ResearchView } from "@/lib/articles/research"; // THE RESEARCH QUEUE of an iteration of kind `research` (release 27 S11): each // acquisition the run proposed, with its reason, its evidence and its // estimate; a yes or no for each that waits (the editor runs a yes through its // own action, past the run's autonomy and caps, never past a standing rule); // the live state of each enqueued one's editor job; and, once nothing is // pending, Continue — a sweep over the run's channels and every channel it // acquired into (`report-draft {task: "sweep", iteration: n}`). // // The run is read through the editor's research-approve (umtool's // /api/articles/research), which refreshes the enqueued acquisitions from // their jobs; it is re-read every 4 s while the run's job or an acquisition's // is going. // // An `auto` run continues by itself once its acquisitions settle (release 28 // F1, the editor's researchAutoContinue): the queue says "continued // automatically" with the channels it left out, or why it has not (held for // a build, refused by a cap). const field = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)]"; const STATUS_VARIANT: Record = { proposed: "state", approved: "state", enqueued: "meter", done: "on", failed: "blocking", rejected: "info", }; const PHASE_SAYS: Record = { discover: "discovering", wait: "waiting", ready: "ready to continue", continued: "continued", }; // An `auto` run's own continuation: done (by which sweep, and what it left // out), or why not yet. function AutoContinued({ ac }: { ac: NonNullable }) { if (ac.status === "continued") { return (
continued automatically{ac.by ? ` by i${ac.by}` : ""} {(ac.warnings ?? []).map((w, i) => ( {w} ))}
); } if (ac.status === "claimed") return continuing automatically…; return (

{ac.status === "held" ? "not continued automatically yet" : "not continued automatically today"}: {ac.reason}

); } // What an acquisition is for, in one line: its channel and what it fetches. function target(p: ResearchProposal): string { const a = p.args; const s = (k: string) => (typeof a[k] === "string" && a[k] ? (a[k] as string) : null); const parts: string[] = []; if (p.action === "create-channel") { const f = (a.fields ?? {}) as Record; if (typeof f.name === "string") parts.push(f.name); if (typeof f.url === "string") parts.push(f.url); } if (s("slug")) parts.push(s("slug")!); if (s("item")) parts.push(s("item")!); if (Array.isArray(a.files)) parts.push((a.files as unknown[]).map(String).join(", ")); if (s("match")) parts.push(`/${s("match")}/`); if (s("url")) parts.push(s("url")!); if (s("id")) parts.push(s("id")!); if (Array.isArray(a.ids)) parts.push(`${(a.ids as unknown[]).length} post(s)`); if (Array.isArray(a.items)) parts.push(`${(a.items as unknown[]).length} item(s)`); if (a.older === true) parts.push("older walk"); if (a.full === true) parts.push("full walk"); return parts.join(" · "); } function estimateOf(p: ResearchProposal): string { const e = p.estimate; if (!e) return ""; return [e.items !== undefined && `${e.items} item(s)`, e.gb !== undefined && `${e.gb} GB`, e.transcribeHours !== undefined && `${e.transcribeHours} h`] .filter(Boolean) .join(", "); } /** One editor job's status, read while it goes. */ function JobState({ id }: { id: string }) { const [status, setStatus] = useState("asking…"); useEffect(() => { let alive = true; let t: ReturnType | null = null; const tick = async () => { try { const r = await fetch(`/api/articles/job?id=${encodeURIComponent(id)}&tail=1`, { cache: "no-store" }); const b = await r.json(); if (!alive) return; const s = r.ok ? String(b.job?.status ?? "unknown") : String(b.error ?? `HTTP ${r.status}`); setStatus(s); if (r.ok && ["done", "failed", "cancelled", "archived"].includes(s) && t) clearInterval(t); } catch (e) { if (alive) setStatus((e as Error).message); } }; void tick(); t = setInterval(tick, 4000); return () => { alive = false; if (t) clearInterval(t); }; }, [id]); return ( {id} {status} ); } function ProposalRow({ p, canDecide, busy, decide, }: { p: ResearchProposal; canDecide: boolean; busy: boolean; decide: (id: string, approve: boolean, note?: string) => void; }) { const [why, setWhy] = useState(""); const waits = p.status === "proposed" || p.status === "approved"; const est = estimateOf(p); return (
  • {p.id} {p.action} {target(p)} {est && ({est})} {p.status}
    {p.reason &&

    {p.reason}

    } {p.evidence.length > 0 && (
      {p.evidence.map((href) => (
    • {href}
    • ))}
    )} {p.note && (

    {p.note}

    )} {p.status === "enqueued" && p.jobId && (
    {p.jobId .split(",") .filter(Boolean) .map((id) => ( ))}
    )} {p.status === "done" && p.channel &&

    channel {p.channel}

    } {waits && canDecide && (
    setWhy(e.target.value)} />
    )}
  • ); } export default function ResearchSlot({ article, iteration, post, models, sweepModel, apiModels = [], extractor, }: { article: string; iteration: IterationRow; /** Start a report-draft job (the continuation). */ post: (body: Record) => Promise; models: string[]; /** The sweep route's model, the continuation's default. */ sweepModel: string; /** Claude's models, and the policy's extractor: a continuation on Claude may name its own (release 28 F2). */ apiModels?: string[]; extractor?: string; }) { const n = iteration.n; const [view, setView] = useState(null); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const [model, setModel] = useState(sweepModel); const [extractorModel, setExtractorModel] = useState(extractor ?? ""); const active = iteration.status === "queued" || iteration.status === "running"; const load = useCallback(async () => { try { const r = await fetch(`/api/articles/research?article=${encodeURIComponent(article)}&n=${n}`, { cache: "no-store" }); const b = await r.json(); if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); setView(b.research); setError(""); } catch (e) { setError((e as Error).message); } }, [article, n]); // Read when the iteration's status moves (a queued run has nothing yet); // re-read while its job or an acquisition's is going. useEffect(() => { if (iteration.status === "queued") return; void load(); }, [load, iteration.status]); const going = active || (view?.waitingOn.jobs.length ?? 0) > 0; useEffect(() => { if (!going) return; const t = setInterval(() => void load(), 4000); return () => clearInterval(t); }, [going, load]); const decide = useCallback( async (id: string, approve: boolean, note?: string) => { setBusy(true); setError(""); try { const r = await fetch("/api/articles/research", { method: "POST", body: JSON.stringify({ article, n, ids: [id], approve, ...(note?.trim() ? { note } : {}) }), }); const b = await r.json(); if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); setView(b.research); const failed = (b.outcomes as { id: string; error?: string }[]).find((o) => o.error); if (failed) setError(`${failed.id}: ${failed.error}`); } catch (e) { setError((e as Error).message); } finally { setBusy(false); } }, [article, n], ); const canContinue = iteration.status === "done" && (view?.phase === "ready" || view?.phase === "continued"); return (
    research {view ? PHASE_SAYS[view.phase] : active ? "discovering" : iteration.status} {view && ( <> autonomy {view.autonomy} {view.spent.items} of {view.limits.maxItemsPerRun} items · {view.spent.gb.toFixed(1)} of {view.limits.maxGbPerRun} GB ·{" "} {view.spent.transcribeHours.toFixed(1)} of {view.limits.maxTranscribeHours} h {view.waitingOn.approval.length > 0 && {view.waitingOn.approval.length} waiting for you} {view.continuedBy.length > 0 && ( continued by {view.continuedBy.map((c) => `i${c}`).join(", ")} )} )}
    {view?.autoContinue && } {view?.notes &&

    {view.notes}

    } {view && view.proposals.length === 0 && !active &&

    no acquisitions proposed

    } {view && view.proposals.length > 0 && (
      {view.proposals.map((p) => ( ))}
    )} {canContinue && (
    {model.startsWith("claude-") && ( )}
    )} {error && (

    {error}

    )}
    ); }