"use client"; import { useCallback, useEffect, useState } from "react"; import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; import { MANIFEST_CHANGED, announceManifestChanged } from "./timelineApi"; // The drafts review on the page (release 28, M0): who drafted a field, its // review state, Approve / Reject (with a note), and the alternatives a draft // task kept for a field it was not allowed to replace, each with "Use this". // // One view per section (`useDrafts`), read from /api/report/drafts and // re-read after any write to the manifest (MANIFEST_CHANGED) or the review // (DRAFTS_CHANGED), so a badge in the On-screen table and one on the review // page agree. The server is the word on every state: each action answers with // the whole view. export type Provenance = { task: string; model: string; at: string; iteration?: number; attempt: number }; export type DraftRow = { address: string; entry: string | null; field: string; label: string; drafted: Provenance | null; text: string; state: "approved" | "rejected" | "edited" | "unreviewed"; verdict: "approved" | "rejected" | null; note: string; judgedText: string; judgedAt: string; }; export type DraftAlternative = { id: string; file: string; address: string; entry: string | null; field: string; label: string; text: string; value: unknown; provenance: Provenance | null; reason: string; inUse: boolean; }; /** Where a drafted field came from (lib/report/draft-provenance.mjs): its draft file, the attempts, the rules broken. */ export type FieldProvenance = { file: string; model: string | null; at: string | null; attempts: number; chosen: number | null; repaired: boolean; failed: { attempt: number; hard: string[] }[]; soft: string[]; }; export type DraftsView = { file: string; exists: boolean; error: string | null; rows: DraftRow[]; alternatives: DraftAlternative[]; counts: Record; drafted: number; gate: { errors: string[]; warnings: string[] }; token?: string | null; /** * Every drafted field's provenance, by address, as /api/report/drafts reads it beside the rows -- so a row * re-read after a draft is complete on first paint, with no wait on the page's own refresh. * Absent on a view the page rendered (the page passes its own). */ provenance?: Record; }; export const DRAFTS_CHANGED = "umtool:drafts-changed"; export function announceDraftsChanged(project: string) { window.dispatchEvent(new CustomEvent(DRAFTS_CHANGED, { detail: { project } })); } export type DraftAct = (action: string, extra?: Record) => Promise; /** The project's drafts view, kept fresh; `act` runs one action and adopts the answer. */ export function useDrafts(project: string, initial: DraftsView | null = null): { view: DraftsView | null; act: DraftAct; reload: () => Promise } { const [view, setView] = useState(initial); const reload = useCallback(async () => { const r = await fetch(`/api/report/drafts?project=${encodeURIComponent(project)}`, { cache: "no-store" }); if (r.ok) setView((await r.json()) as DraftsView); }, [project]); useEffect(() => { if (!initial) void reload(); const on = (e: Event) => { if ((e as CustomEvent).detail?.project === project) void reload(); }; window.addEventListener(MANIFEST_CHANGED, on); window.addEventListener(DRAFTS_CHANGED, on); return () => { window.removeEventListener(MANIFEST_CHANGED, on); window.removeEventListener(DRAFTS_CHANGED, on); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [project, reload]); const act = useCallback( async (action, extra = {}) => { const r = await fetch("/api/report/drafts", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, action, ...extra }), cache: "no-store", }); const j = (await r.json().catch(() => ({ error: `HTTP ${r.status}` }))) as DraftsView & { ok?: boolean; error?: string; errors?: string[] }; if (!r.ok || !j.ok) throw new Error(j.errors?.length ? j.errors.join("; ") : (j.error ?? `HTTP ${r.status}`)); setView(j); // A taken alternative changed the manifest: every editor re-reads it. if (action === "use") announceManifestChanged(project); else announceDraftsChanged(project); }, [project], ); return { view, act, reload }; } const STATE: Record = { approved: { label: "approved", tone: "meter" }, rejected: { label: "rejected", tone: "blocking" }, edited: { label: "changed since approved", tone: "on" }, unreviewed: { label: "not reviewed", tone: "open" }, }; /** * "drafted by ", its review state, and Approve / Reject (+ note) for the * field at `address`. Nothing when the field is not drafted. */ export function DraftBadge({ address, view, act, compact = false }: { address: string; view: DraftsView | null; act: DraftAct; compact?: boolean }) { const row = view?.rows.find((r) => r.address === address && r.drafted) ?? null; const [note, setNote] = useState(row?.note ?? ""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [ready, setReady] = useState(false); useEffect(() => setReady(true), []); useEffect(() => setNote(row?.note ?? ""), [row?.note]); if (!row || !row.drafted) return null; const run = async (action: string, extra: Record = {}) => { setBusy(true); setError(null); try { await act(action, { address, ...extra }); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); } }; const s = STATE[row.state]; return (
drafted by {row.drafted.model} {s.label} setNote(e.target.value)} onBlur={() => { if (note.trim() !== row.note && row.verdict) void run("note", { note }); }} disabled={!ready || busy} placeholder="note (a rejection needs one)" aria-label={`note on the draft of ${address}`} data-draft-note="" maxLength={2000} className="min-w-0 flex-1 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[11px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]" /> {error && ( {error} )}
); } /** The alternatives kept for the field at `address`, each with "Use this". */ export function DraftAlternatives({ address, view, act }: { address: string; view: DraftsView | null; act: DraftAct }) { const alts = (view?.alternatives ?? []).filter((a) => a.address === address && !a.inUse); const [busy, setBusy] = useState(null); const [error, setError] = useState(null); const [ready, setReady] = useState(false); useEffect(() => setReady(true), []); if (!alts.length) return null; return (
{alts.map((a) => (
alternative{a.provenance ? ` · ${a.provenance.model}` : ""} {a.text || "(empty)"}
))} {error && (

{error}

)}
); }