"use client"; import { useRouter } from "next/navigation"; import { useEffect, useRef, useState } from "react"; import { ChannelPicker } from "@/components/articles/NewArticleForm"; import CadenceFields, { DEFAULT_CADENCE } from "@/components/series/CadenceFields"; import { Button } from "@/components/ui/button"; import { Field, Input, Select } from "@/components/ui/field"; import { useHydrated } from "@/components/ui/use-hydrated"; import { articleHref, seriesHref } from "@/lib/hrefs"; import type { CaseSummary } from "@/lib/research/case-types"; import type { Cadence } from "@/lib/schedule-types"; // --------------------------------------------------------------------------- // CREATE → "A recurring report" (plans/umtool-redesign.md, R5): a topic, its // scope (channels, or a board's), a cadence and a shape -- // // Living report one article kept current // Series a new dated edition each tick // Watch (R6) no article until a triage finds something // // R6: a living report or a series may TRIAGE FIRST (the cheap pass: only what // it flags reaches the sweep), at a threshold — "escalate on N strong flags // or N of any strength"; a watch always does, over its terms and digest // topics. // // -- then PLAN, THEN CONFIRM: "Plan the schedule" asks the editor what it // would make (its `report-schedule` create with dryRun: the first tick's time, // the model and its cap, a series' first window and title), and only "Start // the schedule" makes it. Nothing schedules itself: the editor keeps what the // operator started here. // // Labels are contracts (e2e/recurring.spec.ts): the form "a recurring // report", the radios "Living report" / "Series", the fields "topic", // "question", "window check", the scope radios "Channels" / "A board", the // board select "board", the plan region "plan recurring report", the buttons // "Plan the schedule", "Start the schedule", "Change it"; R6: the radio // "Watch", the checkbox "triage first", the fields "terms", "digest tags" // (never "topics": a name holding "topic" would match the topic field too), // "strong flags", "flags of any strength". // --------------------------------------------------------------------------- type Shape = "living" | "series" | "watch"; type Plan = { id: string; shape: Shape; article: string | null; cadence: string; tz: string; firstTick: string; firstTickWords: string; firstWindow: { from: string; to: string } | null; firstTitle: string | null; model: string; provider: "api" | "local"; capUsd: number | null; dailyCapUsd: number; existingArticle: boolean; triage: { model: string; provider: "api" | "local"; threshold: { strong: number; weak: number }; thresholdWords: string; maxEscalationsPerDay: number; topics: string[]; terms: string | null } | null; warnings: string[]; }; const SHAPES = [ { id: "living", label: "Living report", sub: "One article kept current: each tick fetches what is new and updates it." }, { id: "series", label: "Series", sub: "A new dated edition each tick, over only the window since the last one." }, { id: "watch", label: "Watch", sub: "No article until something is found: each tick triages what is new, and only what it flags is researched." }, ] as const; const usd = (n: number) => `$${n.toFixed(2)}`; // Days in a window, both ends counted. const wholeDays = (w: { from: string; to: string }) => Math.round((Date.parse(`${w.to}T00:00:00Z`) - Date.parse(`${w.from}T00:00:00Z`)) / 86_400_000) + 1; // A board's date is YYYYMMDD or YYYY-MM-DD; a schedule's is the latter. const ymd = (d: string) => (/^\d{8}$/.test(d) ? `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6)}` : d); async function post(body: Record): Promise { const r = await fetch("/api/schedules", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); const b = (await r.json().catch(() => null)) as (T & { error?: string }) | null; if (!r.ok) throw new Error(b?.error ?? `HTTP ${r.status}`); return b as T; } export default function RecurringForm({ cases, initialCase, onCancel }: { cases: CaseSummary[]; initialCase: string | null; onCancel: () => void }) { const router = useRouter(); const hydrated = useHydrated(); const boards = cases.filter((c) => (c.scope.channels ?? []).length > 0); const [shape, setShape] = useState("series"); const [triageFirst, setTriageFirst] = useState(false); const [topics, setTopics] = useState(""); const [strong, setStrong] = useState("1"); const [weak, setWeak] = useState("3"); const [topic, setTopic] = useState(""); const [question, setQuestion] = useState(""); const [scopeBy, setScopeBy] = useState<"channels" | "board">(initialCase && boards.some((c) => c.id === initialCase) ? "board" : "channels"); const [board, setBoard] = useState(initialCase && boards.some((c) => c.id === initialCase) ? initialCase : (boards[0]?.id ?? "")); const [channels, setChannels] = useState([]); const [terms, setTerms] = useState(""); const [cadence, setCadence] = useState(DEFAULT_CADENCE); const [autoCurrent, setAutoCurrent] = useState(false); const [plan, setPlan] = useState(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const confirmRef = useRef(null); useEffect(() => { if (plan) confirmRef.current?.focus(); }, [plan]); const chosen = boards.find((c) => c.id === board) ?? null; const scopeChannels = scopeBy === "board" ? (chosen?.scope.channels ?? []) : channels; // A board's terms are its query, unless the operator typed their own. const windowTerms = terms.trim() || (scopeBy === "board" ? (chosen?.scope.query ?? "") : ""); const triaged = shape === "watch" || triageFirst; const threshold = () => { const n = (v: string) => (/^\d{1,2}$/.test(v.trim()) ? Number(v.trim()) : NaN); const t = { strong: n(strong), weak: n(weak) }; return Number.isFinite(t.strong) && Number.isFinite(t.weak) ? t : null; }; const body = () => ({ action: "create", shape, ...(triageFirst && shape !== "watch" ? { triageFirst: true } : {}), ...(triaged ? { ...(threshold() && (threshold()!.strong !== 1 || threshold()!.weak !== 3) ? { threshold: threshold() } : {}), ...(topics.trim() ? { topics: topics.split(",").map((t) => t.trim()).filter(Boolean) } : {}) } : {}), topic: topic.trim(), ...(question.trim() ? { question: question.trim() } : {}), channels: scopeChannels, ...(scopeBy === "board" && chosen ? { case: chosen.id, ...(chosen.scope.dateFrom ? { from: ymd(chosen.scope.dateFrom) } : {}), ...(chosen.scope.regex && !terms.trim() ? { regex: true } : {}) } : {}), ...((shape === "series" || triaged) && windowTerms ? { terms: windowTerms } : {}), // On the editor's clock: it keeps the schedule (the plan names its zone). cadence, ...(shape === "living" && autoCurrent ? { autoMakeCurrent: true } : {}), }); const ask = async () => { if (!topic.trim()) return setError("name the topic"); if (!scopeChannels.length) return setError(scopeBy === "board" ? "that board names no channel" : "pick at least one channel"); if (triaged && !threshold()) return setError("the threshold is two whole numbers (0: that rule off)"); setBusy(true); setError(null); try { const r = await post<{ plan: Plan }>({ ...body(), dryRun: true }); setPlan(r.plan); } catch (e) { setError((e as Error).message); } finally { setBusy(false); } }; const start = async () => { setBusy(true); setError(null); try { const r = await post<{ schedule: { id: string; shape: string; article?: string } }>(body()); const s = r.schedule; router.push(s.shape === "living" ? articleHref({ site: "articles", id: s.article ?? s.id }) : seriesHref(s.id)); } catch (e) { setError((e as Error).message); setBusy(false); } }; // Any change after a plan asks for the plan again. const edit = (set: (v: T) => void) => (v: T) => { set(v); setPlan(null); }; return (
{ if (e.key === "Escape" && !e.defaultPrevented) { e.preventDefault(); if (plan) setPlan(null); else onCancel(); } }} onSubmit={(e) => { e.preventDefault(); if (plan) void start(); else void ask(); }} >
{SHAPES.map((s) => ( ))}
· week of ”" : shape === "watch" ? "What it found is titled “ · ”" : "The article's name"} className="min-w-[16rem] flex-1"> edit(setTopic)(e.target.value)} aria-label="topic" placeholder="e.g. Co-host updates" /> edit(setQuestion)(e.target.value)} aria-label="question" placeholder="the topic, unless asked" />
{scopeBy === "channels" ? ( ) : ( )}
{shape === "watch" ? ( edit(setTerms)(e.target.value)} aria-label="terms" placeholder={chosen?.scope.query ?? "e.g. co-host"} /> ) : shape === "series" ? ( edit(setTerms)(e.target.value)} aria-label="window check" placeholder={chosen?.scope.query ?? "e.g. co-host|guest"} /> ) : ( )}
{shape !== "watch" && ( )} {triaged && ( <> edit(setTopics)(e.target.value)} aria-label="digest tags" placeholder="e.g. guest, panel" /> edit(setStrong)(e.target.value)} aria-label="strong flags" inputMode="numeric" className="w-12 text-center" /> strong or edit(setWeak)(e.target.value)} aria-label="flags of any strength" inputMode="numeric" className="w-12 text-center" /> any )}
{plan && (

{plan.shape === "series" ? "Series" : plan.shape === "watch" ? "Watch" : "Living report"} {plan.id} · {plan.cadence} · first tick {plan.firstTickWords}{" "} ({plan.tz})

  • {plan.model} · {plan.provider === "local" ? "the local model: no API spend" : `up to ${usd(plan.capUsd ?? 0)} a tick`} · daily cap {usd(plan.dailyCapUsd)}
  • {plan.firstWindow && plan.firstTitle && (
  • first edition: {plan.firstTitle} ({plan.firstWindow.from} … {plan.firstWindow.to}, {wholeDays(plan.firstWindow)} whole day{wholeDays(plan.firstWindow) === 1 ? "" : "s"}); each next one starts the day after, and ends the day before its tick. A window nothing matches is quiet, $0
  • )} {plan.shape === "living" &&
  • {plan.existingArticle ? `keeps ${plan.article} current` : `a new article, ${plan.article}: its first tick is its first sweep`}
  • } {plan.triage && (
  • triage first on {plan.triage.model} ({plan.triage.provider === "local" ? "$0" : "metered"}): escalates on {plan.triage.thresholdWords} · at most {plan.triage.maxEscalationsPerDay || "any number of"} escalation {plan.triage.maxEscalationsPerDay === 1 ? "" : "s"} a day{plan.shape === "watch" ? "; no article until one does" : ""}
  • )}
{plan.warnings.length > 0 && (
    {plan.warnings.map((w) => (
  • {w}
  • ))}
)}
)}
{plan ? ( <> ) : ( )} {error && (

{error}

)}
); }