"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; // --------------------------------------------------------------------------- // "Fetch windows" (release 35 O1): every clip's window asked of the editor as // ONE fetch-windows batch (lib/report/fetchWindows.mjs; `umtool fetch` is the // same body from a terminal). The dry run first — the groups per platform, // what is already on disk, what a job already fetches, what the editor cannot // resolve — then Start: one paced job per platform queue, followed here until // each ends, and the windows a job refused named. The editor does the fetching; // this page never touches the network itself. // --------------------------------------------------------------------------- type Summary = { dryRun: boolean; groups: { platform: string; queueKey: string | null; items: number; storedUrlItems?: number }[]; cached: string[]; inFlight: { clipId: string; jobId: string }[]; unresolved: { clipId: string; error: string }[]; refused: { platform: string; items: number; error: string }[]; jobs: { platform: string; jobId: string; items: number }[]; }; type Failure = { clipId: string | null; slug: string; id: string; class: string; message: string }; type JobState = { jobId: string; status: string; platform: string | null; progress?: { done?: number; total?: number }; queue?: { position?: number }; failed?: Failure[] }; type LastRun = { at: string; jobIds: string[]; jobs?: Record } | null; const ENDED = new Set(["done", "failed", "cancelled", "interrupted"]); export default function FetchWindowsPanel({ project, items, skipped = 0, lastRun = null, onSettled, }: { project: string; /** How many windows the body asks for. */ items: number; /** How many clips it leaves out (ruled out, no video). */ skipped?: number; /** The last run that started jobs (fetch-runs.json), to follow on load. */ lastRun?: LastRun; /** Called once every job has ended, with the windows they failed. */ onSettled?: (failed: Failure[]) => void; }) { const [plan, setPlan] = useState(null); const [started, setStarted] = useState(null); const [jobs, setJobs] = useState(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const alive = useRef(true); useEffect(() => () => void (alive.current = false), []); const post = async (action: string) => { const r = await fetch("/api/report/fetch-windows", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, action }), cache: "no-store", }); const j = await r.json().catch(() => ({})); if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`); return j; }; const follow = useCallback(async () => { for (;;) { if (!alive.current) return; let j: { jobs: JobState[] }; try { j = await post("follow"); } catch (e) { setError(e instanceof Error ? e.message : String(e)); return; } setJobs(j.jobs); if (j.jobs.every((s) => ENDED.has(s.status))) { onSettled?.(j.jobs.flatMap((s) => s.failed ?? [])); return; } await new Promise((r) => setTimeout(r, 3000)); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [project]); // A run still going when the page opened: follow it. useEffect(() => { if (lastRun && lastRun.jobIds.some((id) => !ENDED.has(lastRun.jobs?.[id]?.status ?? ""))) void follow(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); async function dryRun() { setBusy(true); setError(null); setStarted(null); try { setPlan((await post("dry-run")).summary); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); } } async function start() { setBusy(true); setError(null); try { const j = await post("start"); setStarted(j.summary); setPlan(null); if (j.summary.jobs.length) void follow(); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); } } const running = !!jobs && !jobs.every((s) => ENDED.has(s.status)); const failed = (jobs ?? []).flatMap((s) => s.failed ?? []); return (
{items} window{items === 1 ? "" : "s"} {skipped ? ` · ${skipped} skipped` : ""}
{plan && (
)} {started && (
)} {jobs && (
    {jobs.map((s) => (
  • {s.platform ?? "job"} · {s.jobId} · {s.status} {s.progress && Number.isFinite(Number(s.progress.done)) ? ` · ${s.progress.done}/${s.progress.total ?? "?"}` : ""} {s.queue && Number(s.queue.position) > 0 ? ` · queued, position ${s.queue.position}` : ""}
  • ))}
)} {failed.length > 0 && (
    {failed.map((f) => (
  • {f.clipId ?? `${f.slug}/${f.id}`}: {f.class} — {f.message}
  • ))}
)} {error && ( {error} )}
); } function Lines({ s }: { s: Summary }) { return ( <> {s.groups.map((g) => (

{g.platform}: {g.items} window{g.items === 1 ? "" : "s"} to fetch{g.storedUrlItems ? ` (${g.storedUrlItems} from a stored media URL)` : ""}

))}

{s.cached.length} already on disk

{s.inFlight.length > 0 && (

{s.inFlight.length} already being fetched ({[...new Set(s.inFlight.map((f) => f.jobId))].join(", ")})

)} {s.unresolved.map((u) => (

{u.clipId}: {u.error}

))} {s.refused.map((r) => (

{r.platform}: {r.items} not started — {r.error}

))} ); }