"use client"; import { useEffect, useRef, useState } from "react"; import type { ActivityMeter } from "@/lib/activity-types"; import { editorProgress, queueText, spendFromLog } from "@/lib/running.mjs"; import { cn } from "@/lib/utils"; import { Button } from "./button"; // --------------------------------------------------------------------------- // ONE JOB PROGRESS (plans/umtool-redesign.md, P4b) for every job umtool shows: // a chain (Make the video, Draft everything), a build, an editor job (a media // draft, a narration, an iteration). The parts are the same everywhere -- // // head the job's state in words ("running", "queued · 1 ahead", // "failed: …"), the current step ("step 3/15: draft-onscreen"), // the spend so far in Meter, and Cancel where the job supports it // bar a 2 px Meter bar, only when the job reports a fraction (an empty // bar would read as "0% done") // steps the step list, each with its state; the current one in ink // log the last lines, when asked for // // -- so a Running row in the rail, a draft row on the Media tab and the build // on the Build tab read the same way. The Running row uses the two smallest // parts (JobProgressText, JobProgressBar). Colour: Meter for measurement (the bar, the spend), the // verdict text steps only for an ended job's outcome; never Signal. // --------------------------------------------------------------------------- export type JobStepState = "pending" | "running" | "done" | "failed" | "skipped" | "cancelled"; export type JobStep = { /** A stable key (the step's name). */ id: string; label: string; state: JobStepState; /** A line under it: why it was skipped, what it wrote. */ detail?: string | null; /** Marked as where a run starts (a resume). */ start?: boolean; /** Optional steps read in italic. */ optional?: boolean; /** The step's own data attributes (the specs' handles). */ attrs?: Record; }; const STEP_TONE: Record = { pending: "text-muted-2", running: "text-text font-semibold", done: "text-text-2", failed: "text-reject-text", skipped: "text-muted-2", cancelled: "text-muted-2", }; const STEP_MARK: Record = { pending: "○", running: "▸", done: "✓", failed: "✕", skipped: "–", cancelled: "–", }; /** The few words of a row (the rail's): "2/4", "3/12 turns", "queued · next". */ export function JobProgressText({ meter, className }: { meter?: ActivityMeter | null; className?: string }) { if (!meter?.text) return null; return ( {meter.text} ); } /** The 2 px Meter bar; nothing when the job reports no fraction. */ export function JobProgressBar({ meter, className }: { meter?: ActivityMeter | null; className?: string }) { if (meter?.fraction === null || meter?.fraction === undefined) return null; const pct = Math.round(Math.max(0, Math.min(1, meter.fraction)) * 100); return ( ); } const usd = (n: number) => `$${n < 10 ? n.toFixed(2) : n.toFixed(0)}`; export function JobProgress({ label, state, status, current, meter, spend, steps, stepColumns = false, log, logLabel, onCancel, cancelLabel = "Cancel", cancelName, error, className, children, ...props }: Omit, "children"> & { /** What the job is, in words ("Draft everything", "the cut"). Omitted where the context says it. */ label?: React.ReactNode; /** The job's state, for the data attribute and the tone. */ state: "asking" | "queued" | "running" | "done" | "failed" | "cancelled" | string; /** The state in words, when it says more than `state` ("queued · 1 ahead"). */ status?: React.ReactNode; /** The current step, in words ("step 3/15: draft-onscreen"). */ current?: React.ReactNode; meter?: ActivityMeter | null; /** USD so far, when the job says (a generation job's log). */ spend?: number | null; steps?: JobStep[]; /** The steps in columns (a chain's fifteen) rather than one wrapped row. */ stepColumns?: boolean; log?: string[]; logLabel?: string; /** Present when the job can be cancelled. */ onCancel?: () => void; cancelLabel?: string; /** The Cancel button's accessible name, when the label alone is ambiguous. */ cancelName?: string; error?: React.ReactNode; children?: React.ReactNode; }) { const live = state === "running" || state === "queued" || state === "asking"; const ended = state === "failed" || state === "cancelled"; return (
{label && {label}} {status ?? state} {current && {current}} {meter?.text && } {spend != null && ( {usd(spend)} )} {onCancel && live && ( )}
{live && } {steps && steps.length > 0 && (
    {steps.map((s, i) => (
  1. v !== undefined))} > {stepColumns && {i + 1}} {STEP_MARK[s.state]} {s.label} {s.state !== "pending" && s.state !== "running" && {s.state}} {s.detail && s.state !== "pending" && s.state !== "running" && ( {s.detail} )}
  2. ))}
)} {children} {log && log.length > 0 && (
          {log.join("\n")}
        
)} {error &&

{error}

}
); } // ---- an editor job, followed ------------------------------------------------ export type EditorJob = { id: string; kind: string | null; status: string; queue: { key?: string; position?: number } | null; progress: { metric: string; current: number; target: number } | null; tail: string[]; }; const ENDED = ["done", "failed", "cancelled"]; /** * Follow one editor job through umtool's `/api/articles/job` (every 2 s, never * faster), telling `onEnd` once when it ends. `null` id: nothing followed. */ export function useEditorJob( jobId: string | null, { tail = 6, onEnd }: { tail?: number; onEnd?: (job: EditorJob) => void } = {}, ): { job: EditorJob | null; error: string; cancel: () => Promise } { const [job, setJob] = useState(null); const [error, setError] = useState(""); const ended = useRef(onEnd); ended.current = onEnd; const told = useRef(null); useEffect(() => { setJob(null); if (!jobId) return; let alive = true; let stop = false; const tick = async () => { if (stop) return; try { const r = await fetch(`/api/articles/job?id=${encodeURIComponent(jobId)}&tail=${tail}`, { cache: "no-store" }); const b = await r.json(); if (!alive) return; if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); setJob(b.job); setError(""); if (ENDED.includes(b.job.status)) { stop = true; if (told.current !== jobId) { told.current = jobId; ended.current?.(b.job); } } } catch (e) { if (alive) setError((e as Error).message); } }; void tick(); const t = setInterval(tick, 2000); return () => { alive = false; clearInterval(t); }; }, [jobId, tail]); const cancel = async () => { if (!jobId) return; const r = await fetch("/api/articles/job", { method: "POST", body: JSON.stringify({ cancel: jobId }) }); if (!r.ok) setError(((await r.json().catch(() => ({}))) as { error?: string }).error ?? `HTTP ${r.status}`); }; return { job, error, cancel }; } /** An editor job's state, progress and spend, as JobProgress reads them. */ export function editorJobView(job: EditorJob | null): { state: string; status: string; meter: ActivityMeter | null; spend: number | null; } { if (!job) return { state: "asking", status: "asking the editor…", meter: null, spend: null }; const queued = job.status === "queued" || (job.queue?.position ?? 0) > 0; const p = editorProgress(job.progress ? { metric: job.progress.metric, current: job.progress.current, target: job.progress.target } : null); const status = queued ? `${queueText(job.queue)}${job.queue?.key ? ` on ${job.queue.key}` : ""}` : job.status; return { state: queued ? "queued" : job.status, status, meter: p ? { fraction: p.fraction, text: p.text } : null, spend: spendFromLog(job.tail), }; } /** * An editor job, followed and drawn: its state, its place in a queue, its * progress and spend, its log's last lines (when `log`), and Cancel. What the * Media tab's draft rows and the Iterations tab's jobs show. */ export function EditorJobProgress({ jobId, label, onEnd, tail = 6, log = false, cancelName, className, ...props }: Omit, "children"> & { jobId: string; label?: React.ReactNode; onEnd?: (job: EditorJob | null) => void; tail?: number; /** Show the log's last lines (the Iterations tab's), else only the last line in the status. */ log?: boolean; logLabel?: string; cancelName?: string; }) { const { logLabel, ...rest } = props; const { job, error, cancel } = useEditorJob(jobId, { tail, onEnd: (j) => onEnd?.(j) }); const v = editorJobView(job); const last = job?.tail.filter((l) => !l.startsWith("@@")).slice(-1)[0]; return ( void cancel().then(() => { onEnd?.(job); }) } cancelName={cancelName} error={error || undefined} className={className} {...rest} /> ); }