"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { useRouter } from "next/navigation"; import { buttonVariants } from "@/components/ui/button"; import { openInDraftHref, playHref } from "@/lib/hrefs"; import { Field, Input, Select, Textarea } from "@/components/ui/field"; import { JobProgress, type JobStepState } from "@/components/ui/job-progress"; import RenderModeBanner, { renderPriorityPref } from "./RenderModeBanner"; import RenderQueuePanel from "./RenderQueuePanel"; // New take, Make all styles -- and the job either starts (or a card's Rebuild // starts), watched here until it ends, then the page re-reads the takes. // // Everything a model could do here a person does by hand: pick a style (or // none), say the window, optionally write the patch. Nothing on this page // calls a model. export type MontageStyle = { name: string; label: string; summary: string }; /** An effect preset (report-to-video/fx.mjs `fxPresetsFor`): a merge patch the patch box takes. */ export type EffectPreset = { name: string; label: string; summary: string; patch: Record }; type StepView = { label: string; argv: string[] }; type Ev = Record & { ev: string; id?: string; phase?: string }; type JobView = { id: string; kind: string; state: "running" | "done" | "failed"; stepIndex: number; steps: StepView[]; error: string | null; log: string[]; next: number; events: Ev[]; nextEvent: number; }; /** A card's Rebuild (or anything else on the page) announces the job it started. */ export const TAKE_JOB_EVENT = "umtool:take-job"; export function announceTakeJob(job: unknown) { window.dispatchEvent(new CustomEvent(TAKE_JOB_EVENT, { detail: job })); } /** * POST /api/report/takes/make; the job, or the error in words. "Give renders * the machine" (RenderModeBanner) adds `priority` unless the body says. */ export async function startTakeJob(body: Record): Promise<{ job?: JobView; error?: string }> { const r = await fetch("/api/report/takes/make", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body.priority === undefined && renderPriorityPref() ? { ...body, priority: true } : body), cache: "no-store", }); const j = (await r.json().catch(() => ({}))) as { job?: JobView; error?: string }; if (!r.ok || !j.job) return { error: j.error ?? `HTTP ${r.status}` }; announceTakeJob(j.job); return { job: j.job }; } /** The patch textarea's words: "" is no patch; anything else must be a JSON object. */ function readPatch(text: string): { patch: Record | null; error: string | null } { if (!text.trim()) return { patch: null, error: null }; try { const v = JSON.parse(text); if (!v || typeof v !== "object" || Array.isArray(v)) return { patch: null, error: "The patch is a JSON object: { \"render\": { … } }" }; return { patch: v, error: null }; } catch (e) { return { patch: null, error: `Not JSON: ${e instanceof Error ? e.message : String(e)}` }; } } export default function NewTakePanel({ project, styles, stylesError, effects = [], group: initialGroup, window: initialWindow = { at: 0, dur: 60 }, }: { project: string; styles: MontageStyle[]; stylesError?: string | null; effects?: EffectPreset[]; group: string; window?: { at: number; dur: number }; }) { const router = useRouter(); const [ready, setReady] = useState(false); const [style, setStyle] = useState(""); const [effect, setEffect] = useState(""); const [label, setLabel] = useState(""); const [labelTouched, setLabelTouched] = useState(false); const [group, setGroup] = useState(initialGroup); const [full, setFull] = useState(false); const [at, setAt] = useState(String(initialWindow.at)); const [dur, setDur] = useState(String(initialWindow.dur)); const [patchText, setPatchText] = useState(""); const [force, setForce] = useState(false); // On by default: an audition compares cuts, and a quick encode is minutes sooner. const [quick, setQuick] = useState(true); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [job, setJob] = useState(null); const since = useRef(0); const sinceEvent = useRef(0); useEffect(() => setReady(true), []); // Adopt a take job already running (a reload, another tab), and any job a // card starts. const adopt = useCallback((j: JobView) => { since.current = j.next ?? 0; sinceEvent.current = j.nextEvent ?? 0; setJob(j); }, []); useEffect(() => { void fetch(`/api/report/takes/make?project=${encodeURIComponent(project)}`, { cache: "no-store" }) .then((r) => r.json()) .then((j) => j.running && adopt(j.running as JobView)) .catch(() => {}); const on = (e: Event) => adopt((e as CustomEvent).detail as JobView); window.addEventListener(TAKE_JOB_EVENT, on); return () => window.removeEventListener(TAKE_JOB_EVENT, on); }, [project, adopt]); useEffect(() => { if (!job || job.state !== "running") return; const t = setInterval(async () => { const r = await fetch(`/api/report/takes/make?job=${job.id}&since=${since.current}&sinceEvent=${sinceEvent.current}`, { cache: "no-store" }); if (!r.ok) return; const j = (await r.json()) as JobView; since.current = j.next; sinceEvent.current = j.nextEvent; setJob((prev) => (prev ? { ...j, log: [...prev.log, ...j.log], events: [...prev.events, ...j.events] } : j)); // The new take is on disk: read the takes again. if (j.state !== "running") router.refresh(); }, 800); return () => clearInterval(t); }, [job, router]); const picked = styles.find((s) => s.name === style) ?? null; const pickedEffect = effects.find((x) => x.name === effect) ?? null; const { patch, error: patchError } = readPatch(patchText); const windowOf = () => (full ? "full" : { at: Number(at), dur: Number(dur) }); const windowBad = !full && !(Number(at) >= 0 && Number(dur) > 0); const running = job?.state === "running"; const submit = async (body: Record) => { setBusy(true); setError(null); const r = await startTakeJob({ project, force, ...body }); setBusy(false); if (r.error) setError(r.error); }; // Save as a draft (lane/ui-simplify): the take recorded with nothing rendered (POST /api/report/takes/tools, draft-new). const [drafted, setDrafted] = useState(null); const saveDraft = async () => { setBusy(true); setError(null); const r = await fetch("/api/report/takes/tools", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "draft-new", label, group, style: style || null, patch, window: windowOf() }), }); const j = (await r.json().catch(() => ({}))) as { exit?: number; id?: string; said?: string; error?: string }; setBusy(false); if (r.ok && j.exit === 0 && j.id) { setDrafted(j.id); router.refresh(); } else setError(j.error ?? j.said ?? `HTTP ${r.status}`); }; const takeEvents = (job?.events ?? []).filter((e) => e.ev === "take"); const takeIds = [...new Set(takeEvents.map((e) => String(e.id)))]; const stateOf = (id: string) => { const last = takeEvents.filter((e) => e.id === id).at(-1)?.phase; return last === "done" ? "made" : last === "skipped" ? "skipped" : last === "failed" ? "failed" : "rendering"; }; return (
New take
{ e.preventDefault(); void submit({ take: { label, group, style: style || null, patch, window: windowOf(), quick } }); }} > {effects.length ? ( ) : null} { setLabel(e.target.value); setLabelTouched(true); }} /> setGroup(e.target.value)} />
Window
setAt(e.target.value)} data-take-at="" aria-label="window starts at, seconds" className="w-20" /> s for setDur(e.target.value)} data-take-dur="" aria-label="window length, seconds" className="w-20" /> s