"use client"; import { useEffect, useState } from "react"; import { Button } from "@/components/ui/button"; import { EditorJobProgress, type EditorJob } from "@/components/ui/job-progress"; import ModelLog from "@/components/model-log/ModelLog"; import type { DraftRowView, DraftRunSummary, ProjectIteration } from "@/lib/articles/projectDraft"; // DRAFT WITH (release 28 M9; the Media tab's section heads since P4b): // a draftable section of the cut — the cut, on-screen, teaser, flips, // threads, narration, YouTube — drafted by a model as a `report-draft` step // on the iteration the project was made from (umtool's /api/articles/generate // → the editor). The models are the policy's, the task's route preselected; // `force` re-drafts only fields a model drafted (a field you wrote or edited // is never replaced — its draft is kept as an alternative); a per-entry task // may be limited to the entries ticked. While the job runs it is the ONE // JobProgress; when it ends the surface is re-read, and the row says what the // task's draft file says it wrote, skipped and refused. export type Policy = { generation: { routes: Record; models: { api: string; local: string } }; models: { api: string[]; local: string[] } }; /** The generation policy, asked of the editor once (null until it answers; the error says why not). */ export function usePolicy(enabled: boolean): { policy: Policy | null; error: string } { const [policy, setPolicy] = useState(null); const [error, setError] = useState(""); useEffect(() => { if (!enabled) return; let alive = true; void (async () => { const r = await fetch("/api/articles/policy", { cache: "no-store" }).catch(() => null); const b = r ? await r.json().catch(() => ({})) : {}; if (!alive) return; if (r?.ok && b.policy) setPolicy(b.policy as Policy); else setError(b.error ?? "the editor did not answer"); })(); return () => { alive = false; }; }, [enabled]); return { policy, error }; } /** The models a task may draft with, its route's first. */ export function modelsFor(policy: Policy | null, task: string): { route: string; models: string[] } { const g = policy?.generation; const route = g ? (g.routes[task] === "api" ? g.models.api : g.models.local) : ""; const models = policy ? [...new Set([route, ...policy.models.api, ...policy.models.local].filter(Boolean))] : []; return { route, models }; } const field = "rounded-[3px] border border-seam-2 bg-ground px-1.5 py-0.5 text-[12px] text-text"; const ENDED = ["done", "failed", "cancelled"]; /** What the task's last run here left in its draft file. */ export function RunLine({ run }: { run: DraftRunSummary }) { const c = run.counts; const parts = [ c.applied ? `${c.applied} written` : "", c.kept ? `${c.kept} kept as an alternative` : "", c.refused ? `${c.refused} refused by a check` : "", c.skipped ? `${c.skipped} skipped` : "", c.none ? `${c.none} with no draft` : "", ].filter(Boolean); const failing = run.checks.filter((ch) => !ch.ok); const problems = run.units.filter((u) => u.outcome === "refused" || u.outcome === "kept" || u.outcome === "none"); return (
last run{run.model ? {run.model} : null} {run.at ? `, ${new Date(run.at).toLocaleString()}` : ""}: {parts.join(" · ") || "nothing"} {failing.map((ch) => (

check {ch.name}: {ch.detail ?? "failed"}

))} {problems.length > 0 && (
    {problems.slice(0, 8).map((u) => (
  • {u.label ?? u.id}: {u.why ?? u.outcome}
  • ))} {problems.length > 8 &&
  • … and {problems.length - 8} more ({run.file})
  • }
)}
); } /** * One section's "Draft with ": the button, the model, force, the * entries; then the job, followed; then the last run. */ export function DraftControl({ row, link, policy, run, runningJob, onEnded, }: { row: DraftRowView; link: Extract; policy: Policy | null; run: DraftRunSummary | undefined; runningJob: string | null; onEnded: () => void | Promise; }) { const { route: routeModel, models } = modelsFor(policy, row.task); const [model, setModel] = useState(routeModel); useEffect(() => { if (!model && routeModel) setModel(routeModel); }, [routeModel, model]); const [force, setForce] = useState(false); const [picked, setPicked] = useState([]); const [jobId, setJobId] = useState(runningJob); const [ended, setEnded] = useState(null); const [error, setError] = useState(""); const [sending, setSending] = useState(false); const [logOpen, setLogOpen] = useState(false); useEffect(() => { if (runningJob) setJobId(runningJob); }, [runningJob]); const active = !!jobId && !ended; const start = async () => { setError(""); setSending(true); try { const body = { task: row.task, article: link.article, iteration: link.n, ...(model ? { model } : {}), ...(force ? { force: true } : {}), ...(picked.length ? { entries: picked } : {}), }; const r = await fetch("/api/articles/generate", { method: "POST", body: JSON.stringify(body) }); const b = await r.json().catch(() => ({})); if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); setEnded(null); setJobId(String(b.jobId)); } catch (e) { setError((e as Error).message); } finally { setSending(false); } }; return (
{row.blocked ? (

{row.blocked}

) : (
{/* "Draft with ": the button names the result, the model is chosen beside it. */} with {row.entries && row.entries.length > 0 && (
{picked.length ? `${picked.length} of ${row.entries.length} entries` : `every entry (${row.entries.length})`}
{row.entries.map((e) => ( ))}
)}
)} {jobId && !ended && ( { // A Cancel answers before the editor has said so: it is cancelled. setEnded(j && ENDED.includes(j.status) ? j : { id: jobId, kind: null, status: "cancelled", queue: null, progress: null, tail: j?.tail ?? [] }); void onEnded(); }} /> )} {jobId && ended && ENDED.includes(ended.status) && (

the draft {ended.status === "done" ? "is done" : ended.status} {ended.status !== "done" && ended.tail.length ? `: ${ended.tail.filter((l) => !l.startsWith("@@")).slice(-1)[0] ?? ""}` : ""}

)} {run && } {/* The model log (demo epic D3): this task's calls -- the running job's, else its last run's. */} {/* A button, not a
: the entries' is this row's only one (media-surfaces.spec). */}
{logOpen && ( )}
{error && (

{error}

)}
); }