"use client"; import { useCallback, useEffect, useMemo, useState } from "react"; import { useRouter } from "next/navigation"; import { Button } from "@/components/ui/button"; import PolicyPanel, { type Today } from "@/components/articles/PolicyPanel"; import ExtractorSelect, { extractorBody } from "@/components/articles/ExtractorSelect"; import { estimateOf, estimateText } from "@/lib/create/estimate.mjs"; import type { EditorChannel, PolicyView } from "@/lib/articles/generation"; // /articles/new (release 27 S8): a question over channels becomes an article's // first iteration — a `report-draft` sweep the editor runs and writes. The // sweep is the agent on a Claude model, or the code-driven pipeline on the // local model; the cap starts at the policy's per-job default and goes down. // // Or it starts with RESEARCH (release 27 S11): a run that finds what the // archive lacks for the question and proposes acquisitions, under the // autonomy chosen here (propose, limits, auto); its queue is on the article's // Iterations tab, and a sweep continues it from there. // // Or it starts BLANK, by hand (release 32 R2): no model and no editor -- an // article in the making whose first iteration (kind `hand`) is a titled report // with no sections, filled on its Iterations tab ("Add a claim"). // // It lives on Create (/create?make=article, P5) as "Article from a question": // there the policy is a chip linking /settings/generation (`showPolicy` // false), Escape is Cancel, and the ESTIMATE is said before Start -- what such // runs on the chosen model have spent (the ledger, `history`), under the cap // (lib/create/estimate.mjs). const field = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-2 py-1 text-[13px] text-[var(--color-text)] focus-visible:border-[var(--color-sel)] focus-visible:outline-none"; const ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; type Task = "agent" | "pipeline"; type Start = "sweep" | "research" | "blank"; type Autonomy = "propose" | "limits" | "auto"; const AUTONOMY_SAYS: Record = { propose: "every acquisition waits for your yes or no", limits: "imports into existing channels under the caps run; the rest waits", auto: "everything runs through the editor until a cap; past it, it waits", }; // Exported for Create's recurring form (R5): the same picker, the same channels. // `source` (demo epic D1): a published archive's handle lists ITS channels // (its corpus.json); none, the editor's own. export function ChannelPicker({ value, onChange, source = "" }: { value: string[]; onChange: (v: string[]) => void; source?: string }) { const [all, setAll] = useState(null); const [error, setError] = useState(""); const [q, setQ] = useState(""); useEffect(() => { setAll(null); setError(""); fetch(source ? `/api/articles/channels?source=${encodeURIComponent(source)}` : "/api/articles/channels", { cache: "no-store" }) .then(async (r) => { const b = await r.json(); if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); setAll(b.channels); }) .catch((e) => setError((e as Error).message)); }, [source]); const shown = useMemo(() => { const k = q.trim().toLowerCase(); return (all ?? []).filter((c) => !k || c.slug.includes(k) || c.name.toLowerCase().includes(k)).slice(0, 80); }, [all, q]); const toggle = (slug: string) => onChange(value.includes(slug) ? value.filter((s) => s !== slug) : [...value, slug]); const nameOf = (slug: string) => all?.find((c) => c.slug === slug)?.name ?? slug; return (
{value.map((s) => ( ))} setQ(e.target.value)} />
{error && (

channels: {error}

)} {q && (
    {shown.map((c) => (
  • ))} {shown.length === 0 &&
  • {all ? "no channel matches" : "loading channels…"}
  • }
)}
); } export default function NewArticleForm({ initialPolicy, today, taken, showPolicy = true, framed = true, history = {}, onCancel, }: { initialPolicy: PolicyView | null; today: Today | null; taken: string[]; /** The policy panel above the form (Create shows a chip instead). */ showPolicy?: boolean; /** Its own border (Create's line region frames it instead). */ framed?: boolean; /** task -> model -> per-job USD from the ledger, for the estimate. */ history?: Record>; onCancel?: () => void; }) { const router = useRouter(); const [policy, setPolicy] = useState(initialPolicy); const onPolicy = useCallback((p: PolicyView) => setPolicy(p), []); const defaultTask: Task = policy?.generation.routes.sweep === "local" ? "pipeline" : "agent"; const [task, setTask] = useState(defaultTask); const [begin, setBegin] = useState("sweep"); const [autonomy, setAutonomy] = useState(policy?.generation.research?.autonomy ?? "propose"); const researchModel = policy?.generation.routes.research === "local" ? policy.generation.models.local : policy?.generation.models.api; const models = begin === "research" ? [...(policy?.models.api ?? []), ...(policy?.models.local ?? [])] : task === "agent" ? (policy?.models.api ?? []) : (policy?.models.local ?? []); const routeModel = begin === "research" ? researchModel : task === "agent" ? policy?.generation.models.api : policy?.generation.models.local; const [model, setModel] = useState(routeModel ?? ""); const [extractor, setExtractor] = useState(policy?.generation.models.extractor ?? ""); // A cap is a Claude run's: the agent, or research on a Claude model. const capped = begin === "blank" ? false : begin === "research" ? model.startsWith("claude-") : task === "agent"; const capDefault = policy?.generation.caps.sweep ?? 5; const [cap, setCap] = useState(String(capDefault)); const [id, setId] = useState(""); const [question, setQuestion] = useState(""); const [channels, setChannels] = useState([]); // The corpus the sweep reads and cites (demo epic D1): "" the editor's own, // else a published archive's handle. Preselected when the editor holds no // channel and an archive is connected (/api/articles/sources). const [sources, setSources] = useState<{ handle: string; label: string; detail?: string }[] | null>(null); const [source, setSource] = useState(""); useEffect(() => { fetch("/api/articles/sources", { cache: "no-store" }) .then(async (r) => { const b = await r.json(); if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); setSources(b.sources); if (b.preselect) setSource(b.preselect); }) .catch(() => setSources([])); }, []); const [from, setFrom] = useState(""); const [to, setTo] = useState(""); const [title, setTitle] = useState(""); const [reportKind, setReportKind] = useState<"factcheck" | "sweep">("factcheck"); const [error, setError] = useState(""); const [sending, setSending] = useState(false); useEffect(() => { if (begin === "research") setModel(researchModel ?? ""); else setModel(task === "agent" ? (policy?.generation.models.api ?? "") : (policy?.generation.models.local ?? "")); }, [task, begin, policy, researchModel]); const estimate = estimateText( estimateOf(history, { task: begin, model, cap: capped ? Number(cap) || null : null, local: !model.startsWith("claude-") }), ); const idProblem = !id ? null : !ID_RE.test(id) ? "a lowercase slug: a-z, 0-9 and -" : taken.includes(id) ? "an article by that id exists — add an iteration on its page" : null; async function start(e: React.FormEvent) { e.preventDefault(); setError(""); if (idProblem) return setError(`article id: ${idProblem}`); if (begin === "blank") { if (!title.trim()) return setError("give the article a title"); setSending(true); try { const r = await fetch("/api/articles/by-hand", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ action: "blank", article: id, title, kind: reportKind }) }); const b = await r.json(); if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); router.push(`/articles/${id}?tab=iterations`); } catch (err) { setError((err as Error).message); setSending(false); } return; } if (begin === "sweep" && !channels.length) return setError("pick at least one channel"); const maxUsd = Number(cap); if (capped && !(maxUsd > 0 && maxUsd <= capDefault)) return setError(`the cap is above $0 and at most the policy's $${capDefault}`); setSending(true); try { const r = await fetch("/api/articles/generate", { method: "POST", body: JSON.stringify({ task: begin, article: id, question, ...(channels.length ? { channels } : {}), ...(source ? { source } : {}), model, ...(begin === "sweep" ? extractorBody(model, extractor, policy?.generation.models.extractor) : {}), ...(from ? { from } : {}), ...(to ? { to } : {}), ...(capped ? { maxUsd } : {}), ...(begin === "research" ? { autonomy } : {}), }), }); const b = await r.json(); if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); router.push(`/articles/${id}?tab=iterations`); } catch (err) { setError((err as Error).message); setSending(false); } } return (
{policy ? ( showPolicy && ) : (

The editor did not answer, so the policy and the channels are unknown. Start it, then reload.

)}
{ if (e.key === "Escape" && onCancel) { e.preventDefault(); onCancel(); } }} > {begin === "blank" ? ( ) : (