"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { Button } from "@/components/ui/button"; import { JobProgress, type JobStep, type JobStepState } from "@/components/ui/job-progress"; import type { ChainMode, ChainView } from "@/lib/articles/generation"; import { spendFromLog } from "@/lib/running.mjs"; import { WHOLE_RECORDING_REFUSED } from "yt-dlp-transcript-common/lib/remoteArchives"; // MAKE THE VIDEO for one iteration (release 27 S8): the pipeline chain's ten // steps (lib/report/chain.mjs) as a umtool job — what each step last did, where // a start resumes, the running step's log, cancel. A step the chain records // done is skipped by a resume; "from" re-runs from a named step. export default function ChainPanel({ article, n, label, mode = "video", model, deck = false, autoStart = false, }: { article: string; n: number; label: string; mode?: ChainMode; model?: string; /** Draft everything with its deck step (release 29 G1). */ deck?: boolean; autoStart?: boolean; }) { const draftAll = mode === "draft-all"; const started = useRef(false); const [chain, setChain] = useState(null); const [from, setFrom] = useState(""); const [error, setError] = useState(""); const [sending, setSending] = useState(false); // Stop before render (demo epic D1): this run ends before the voices. const [stopBefore, setStopBefore] = useState(false); const load = useCallback(async () => { const r = await fetch(`/api/articles/chain?article=${encodeURIComponent(article)}&n=${n}${draftAll ? `&mode=draft-all${deck ? "&deck=1" : ""}` : ""}`, { cache: "no-store" }); const b = await r.json(); if (!r.ok) { setError(b.error ?? `HTTP ${r.status}`); return null; } setChain(b.chain); return b.chain as ChainView; }, [article, n, draftAll, deck]); const running = chain?.job?.state === "running"; useEffect(() => { void load(); }, [load]); useEffect(() => { if (!running) return; const t = setInterval(() => void load(), 2500); return () => clearInterval(t); }, [running, load]); const start = useCallback(async (extra: { from?: string; allowWholeRecording?: boolean } = {}) => { setError(""); setSending(true); try { const at = extra.from ?? from; const r = await fetch("/api/articles/chain", { method: "POST", body: JSON.stringify({ article, n, ...(at ? { from: at } : {}), ...(draftAll ? { draftAll: true, ...(model ? { model } : {}), ...(deck ? { deck: true } : {}) } : {}), ...(stopBefore ? { stopBeforeRender: true } : {}), ...(extra.allowWholeRecording ? { allowWholeRecording: true } : {}), }), }); const b = await r.json(); if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); if (b.chain) setChain(b.chain); else await load(); } catch (e) { setError((e as Error).message); } finally { setSending(false); } }, [article, n, from, draftAll, model, deck, stopBefore, load]); useEffect(() => { if (!autoStart || started.current) return; started.current = true; void start(); // Once, on mount: a re-render must not start it again. // eslint-disable-next-line react-hooks/exhaustive-deps }, [autoStart]); async function cancel() { if (!chain?.job) return; await fetch("/api/articles/chain", { method: "POST", body: JSON.stringify({ cancel: chain.job.id }) }); await load(); } const startAt = from || chain?.resumeAt || ""; const steps: JobStep[] = (chain?.steps ?? []).map((s) => ({ id: s.name, label: s.label, state: (["pending", "running", "done", "failed", "skipped", "cancelled"].includes(s.status) ? s.status : "pending") as JobStepState, detail: s.optional ? s.detail : null, start: s.name === startAt && !running, optional: s.optional, attrs: { "data-chain-step": s.name, "data-step-status": s.status }, })); const job = chain?.job ?? null; // A windows step a remote-only channel's whole recording refused, with its // size (demo epic D1): one press fetches them and goes on from there. const wholeRefused = chain?.steps.find((s) => s.status === "failed" && (s.detail ?? "").startsWith(WHOLE_RECORDING_REFUSED)) ?? null; const done = job ? chain!.steps.filter((s) => s.status === "done" || s.status === "skipped" || s.status === "failed").length : 0; return (
{draftAll && (

{model ? {model} : "each task's route"} {deck ? " · with the deck" : ""} · a draft that fails does not stop the chain · the build is the fast one · review the drafts before a final build

)} {chain && ( void cancel() : undefined} cancelLabel="Cancel the chain" log={job?.log} logLabel={`${label} chain log`} data-chain-progress={job?.state ?? "none"} > {job && !running && ( )} {!running && wholeRefused && (

{wholeRefused.detail}

)} {!running && (
)} {error && (

{error}

)}
); }