Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 342fe2e3466172c9a941c6bf525008218f743f6f
parent bd75770dd9a695f6bce08d97c5cf3470a2e1acf0
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 10:10:42 -0400

umtool: one JobProgress for chain, build and editor jobs (P4b)

components/ui/job-progress.tsx: the state in words, the current step, the
Meter bar and spend, the step list, the log and Cancel; useEditorJob and
EditorJobProgress follow an editor job. The chain panel, the build chain and
the Iterations tab's job view draw on it; the Running row's two parts are
re-exported from it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/components/articles/ChainPanel.tsx | 134+++++++++++++++++++++++++++++++++++++------------------------------------------
Mumtool/components/articles/IterationsTab.tsx | 69+++++++++++----------------------------------------------------------
Mumtool/components/projects/ReportBuildChain.tsx | 74++++++++++++++++++++++++++++++++++----------------------------------------
Mumtool/components/shell/JobProgress.tsx | 37++++---------------------------------
Aumtool/components/ui/job-progress.tsx | 343+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 455 insertions(+), 202 deletions(-)

diff --git a/umtool/components/articles/ChainPanel.tsx b/umtool/components/articles/ChainPanel.tsx @@ -2,21 +2,15 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { Button } from "@/components/ui/button"; -import { badgeVariants } from "@/components/ui/badge"; +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"; // 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. -const STATUS_VARIANT: Record<string, "on" | "blocking" | "open" | "info" | "neutral"> = { - done: "on", - failed: "blocking", - running: "open", - cancelled: "info", - skipped: "neutral", -}; export default function ChainPanel({ article, @@ -95,83 +89,81 @@ export default function ChainPanel({ } 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; + const done = job ? chain!.steps.filter((s) => s.status === "done" || s.status === "skipped" || s.status === "failed").length : 0; return ( <section aria-label={`${label} ${draftAll ? "Draft everything" : "video chain"}`} data-chain={label} data-chain-mode={mode} - className="mt-2 rounded border border-[var(--color-line)] bg-[var(--color-ink)] p-2 text-[12px]" + className="mt-2 space-y-2 rounded-[3px] border border-seam-2 bg-panel p-3 text-[12px]" > {draftAll && ( - <p className="mb-1 text-[11px] text-[var(--color-dim)]"> + <p className="text-[11.5px] text-muted"> {model ? <span className="font-mono">{model}</span> : "each task's route"} · a draft that fails does not stop the chain · the build is the fast one · review the drafts before a final build </p> )} {chain && ( - <ol className={`grid gap-x-4 gap-y-0.5 sm:grid-flow-col ${draftAll ? "sm:grid-rows-8" : "sm:grid-rows-5"}`}> - {chain.steps.map((s, i) => ( - <li key={s.name} data-chain-step={s.name} data-step-status={s.status} title={s.detail ?? undefined} className="flex items-center gap-2"> - <span className="num w-5 text-right text-[var(--color-dim)]">{i + 1}</span> - <span className={s.name === startAt && !running ? "font-semibold text-[var(--color-text)]" : s.optional ? "italic" : ""}>{s.label}</span> - {s.status !== "pending" && ( - <span className={badgeVariants({ variant: STATUS_VARIANT[s.status] ?? "neutral", size: "sm" })}>{s.status}</span> - )} - {s.optional && s.status !== "pending" && s.status !== "running" && s.detail && ( - <span data-chain-step-detail="" className="truncate text-[11px] text-[var(--color-dim)]"> - {s.detail} - </span> - )} - </li> - ))} - </ol> + <JobProgress + state={running ? "running" : (job?.state ?? "pending")} + status={ + running + ? `step ${(job?.stepIndex ?? 0) + 1}/${job?.of}: ${job?.label}` + : job + ? `last run ${job.state}${job.error ? `: ${job.error}` : ""}` + : chain.resumeAt + ? `not run · starts at ${chain.resumeAt}` + : "every step done" + } + meter={running && job ? { fraction: job.of ? done / job.of : null, text: `${done}/${job.of} steps` } : null} + spend={job ? spendFromLog(job.log) : null} + steps={steps} + stepColumns + onCancel={running ? () => void cancel() : undefined} + cancelLabel="Cancel the chain" + log={job?.log} + logLabel={`${label} chain log`} + data-chain-progress={job?.state ?? "none"} + > + {job && !running && ( + <span data-chain-job={job.state} hidden /> + )} + </JobProgress> )} - <div className="mt-2 flex flex-wrap items-center gap-2"> - {running ? ( - <> - <span role="status" className="text-[var(--color-dirty)]"> - step {(chain?.job?.stepIndex ?? 0) + 1}/{chain?.job?.of}: {chain?.job?.label} - </span> - <Button size="sm" variant="destructive" onClick={cancel}> - Cancel the chain - </Button> - </> - ) : ( - <> - <label className="flex items-center gap-1"> - <span className="text-[var(--color-dim)]">from</span> - <select - aria-label={`${label} chain from step`} - className="rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5" - value={from} - onChange={(e) => setFrom(e.target.value)} - > - <option value="">{chain?.resumeAt ? `resume (${chain.resumeAt})` : "every step done"}</option> - {chain?.steps.map((s) => ( - <option key={s.name} value={s.name}> - {s.name} - </option> - ))} - </select> - </label> - <Button size="sm" variant="primary" disabled={sending || (!from && !chain?.resumeAt)} onClick={() => void start()}> - {draftAll ? "Run Draft everything" : "Run the chain"} - </Button> - </> - )} - {chain?.job && !running && ( - <span data-chain-job={chain.job.state} className={chain.job.state === "failed" ? "text-[var(--color-bad)]" : "text-[var(--color-dim)]"}> - last run {chain.job.state} - {chain.job.error ? `: ${chain.job.error}` : ""} - </span> - )} - </div> - {chain?.job && chain.job.log.length > 0 && ( - <pre aria-label={`${label} chain log`} className="mt-2 max-h-48 overflow-auto rounded bg-[var(--color-panel)] p-2 font-mono text-[11px] leading-snug whitespace-pre-wrap text-[var(--color-dim)]"> - {chain.job.log.join("\n")} - </pre> + {!running && ( + <div className="flex flex-wrap items-center gap-2"> + <label className="flex items-center gap-1"> + <span className="text-muted">from</span> + <select + aria-label={`${label} chain from step`} + className="rounded-[3px] border border-seam-2 bg-ground px-1 py-0.5" + value={from} + onChange={(e) => setFrom(e.target.value)} + > + <option value="">{chain?.resumeAt ? `resume (${chain.resumeAt})` : "every step done"}</option> + {chain?.steps.map((s) => ( + <option key={s.name} value={s.name}> + {s.name} + </option> + ))} + </select> + </label> + <Button size="sm" variant="outline" disabled={sending || (!from && !chain?.resumeAt)} onClick={() => void start()}> + {draftAll ? "Run Draft everything" : "Run the chain"} + </Button> + </div> )} {error && ( - <p role="alert" className="mt-1 text-[var(--color-bad)]"> + <p role="alert" className="text-reject-text"> {error} </p> )} diff --git a/umtool/components/articles/IterationsTab.tsx b/umtool/components/articles/IterationsTab.tsx @@ -6,6 +6,7 @@ import { Button, buttonVariants } from "@/components/ui/button"; import { hasRunPage, runHref } from "@/lib/research/runs-hrefs"; import { badgeVariants } from "@/components/ui/badge"; import ChainPanel from "@/components/articles/ChainPanel"; +import { EditorJobProgress } from "@/components/ui/job-progress"; import ResearchSlot from "@/components/articles/ResearchSlot"; import ExtractorSelect, { extractorBody } from "@/components/articles/ExtractorSelect"; import DeletePlan from "@/components/DeletePlan"; @@ -71,66 +72,18 @@ function ModelSelect({ value, onChange, label, models }: { value: string; onChan ); } -/** The editor job behind a queued or running iteration (or step): its place, its log, cancel. */ +/** The editor job behind a queued or running iteration (or step): its place, its log, cancel (the ONE JobProgress). */ function JobProgress({ jobId, label, onEnd }: { jobId: string; label: string; onEnd: () => void }) { - const [job, setJob] = useState<DraftJobView | null>(null); - const [error, setError] = useState(""); - useEffect(() => { - let alive = true; - let ended = false; - const tick = async () => { - try { - const r = await fetch(`/api/articles/job?id=${encodeURIComponent(jobId)}&tail=12`, { 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 && ["done", "failed", "cancelled"].includes(b.job.status)) { - ended = true; - onEnd(); - } - } catch (e) { - if (alive) setError((e as Error).message); - } - }; - void tick(); - const t = setInterval(tick, 2500); - return () => { - alive = false; - clearInterval(t); - }; - }, [jobId, onEnd]); - const queued = job?.queue && (job.queue.position ?? 0) > 0; return ( - <div className="mt-2 rounded border border-[var(--color-line)] bg-[var(--color-ink)] p-2" data-job={jobId} data-job-status={job?.status ?? "unknown"}> - <div className="flex flex-wrap items-center gap-2 text-[11px]"> - <span className="font-mono text-[var(--color-dim)]">{jobId}</span> - <span role="status" className="text-[var(--color-dirty)]"> - {job ? (queued ? `queued, ${job.queue?.position} ahead on ${job.queue?.key}` : job.status) : "asking the editor…"} - </span> - <Button - size="sm" - variant="destructive" - className="ml-auto" - aria-label={`Cancel ${label}`} - onClick={async () => { - const r = await fetch("/api/articles/job", { method: "POST", body: JSON.stringify({ cancel: jobId }) }); - const b = await r.json().catch(() => ({})); - if (!r.ok) setError(b.error ?? `HTTP ${r.status}`); - onEnd(); - }} - > - Cancel - </Button> - </div> - {job && job.tail.length > 0 && ( - <pre role="log" aria-label={`${label} progress`} className="mt-1 max-h-40 overflow-auto font-mono text-[11px] leading-snug whitespace-pre-wrap text-[var(--color-dim)]"> - {job.tail.join("\n")} - </pre> - )} - {error && <p className="mt-1 text-[11px] text-[var(--color-bad)]">{error}</p>} - </div> + <EditorJobProgress + jobId={jobId} + tail={12} + log + logLabel={`${label} progress`} + cancelName={`Cancel ${label}`} + onEnd={() => onEnd()} + className="mt-2 rounded-[3px] border border-seam bg-ground p-2" + /> ); } diff --git a/umtool/components/projects/ReportBuildChain.tsx b/umtool/components/projects/ReportBuildChain.tsx @@ -1,7 +1,7 @@ "use client"; import { useCallback, useEffect, useRef, useState } from "react"; -import { badgeVariants } from "@/components/ui/badge"; +import { JobProgress, type JobStepState } from "@/components/ui/job-progress"; import { buttonVariants } from "@/components/ui/button"; // --------------------------------------------------------------------------- @@ -187,7 +187,7 @@ export default function ReportBuildChain({ <button type="button" data-action="run" - className={buttonVariants({ variant: "primary", size: "sm" })} + className={buttonVariants({ variant: "outline", size: "sm" })} disabled={busy || job?.state === "running"} onClick={async () => { const j = await post(""); @@ -324,37 +324,37 @@ export default function ReportBuildChain({ )} {job && ( - <div className="space-y-2"> - <ol className="flex flex-wrap gap-1.5"> - {job.steps.map((s, i) => ( - <li - key={s.label} - data-step={i} - data-step-state={ - job.state !== "running" && i <= job.stepIndex - ? job.state - : i < job.stepIndex - ? "done" - : i === job.stepIndex - ? "running" - : "pending" + <JobProgress + state={job.state} + status={job.state === "running" ? `step ${job.stepIndex + 1}/${job.steps.length}: ${job.steps[job.stepIndex]?.label ?? ""}` : `${job.state}${job.error ? ` — ${job.error}` : ""}`} + meter={ + job.state === "running" && entries.length + ? { + fraction: [...clipStates.values()].filter((st) => st === "done").length / entries.length, + text: `${[...clipStates.values()].filter((st) => st === "done").length}/${entries.length} entries`, } - className={badgeVariants({ - variant: - i < job.stepIndex || (job.state === "done" && i <= job.stepIndex) - ? "meter" - : i === job.stepIndex && job.state === "running" - ? "on" - : job.state === "failed" && i === job.stepIndex - ? "blocking" - : "neutral", - })} - > - {s.label} - </li> - ))} - </ol> - + : null + } + steps={job.steps.map((s, i) => { + const st = + job.state !== "running" && i <= job.stepIndex + ? job.state + : i < job.stepIndex + ? "done" + : i === job.stepIndex + ? "running" + : "pending"; + return { + id: `${i}-${s.label}`, + label: s.label, + state: (st === "done" || st === "failed" || st === "running" ? st : "pending") as JobStepState, + attrs: { "data-step": i, "data-step-state": st }, + }; + })} + log={job.log.slice(-120)} + logLabel="build log" + data-build-job={job.id} + > {/* One box per entry, lit by the pipeline's own events. "Step 3 of 4, running" is not progress when step 3 is twenty minutes long. */} <div className="flex flex-wrap gap-1"> @@ -381,16 +381,10 @@ export default function ReportBuildChain({ quietly missing a citation looks complete. </p> )} - - <pre className="max-h-56 overflow-auto rounded border border-[var(--color-line)] bg-[var(--color-ink)] p-2 font-mono text-[11px] text-[var(--color-dim)]"> - {job.log.slice(-120).join("\n")} - </pre> - - <div className="micro" data-job-state={job.state}> + <div className="micro" data-job-state={job.state} hidden> {job.state} - {job.error ? ` — ${job.error}` : ""} </div> - </div> + </JobProgress> )} </section> ); diff --git a/umtool/components/shell/JobProgress.tsx b/umtool/components/shell/JobProgress.tsx @@ -1,33 +1,4 @@ -import type { ActivityMeter } from "@/lib/activity-types"; - -// ONE presentation of a job's progress, for every Running row (umtool's own -// chain or render, the editor's draft, sync or acquisition): a few words in -// mono and a 2 px Meter bar under the row. A job that reports no fraction -// draws no bar -- an empty bar would read as "0% done". P4b moves the chain's -// and the editor's job panels onto it too. - -export function JobProgressText({ meter, className }: { meter?: ActivityMeter | null; className?: string }) { - if (!meter?.text) return null; - return ( - <span className={className} data-job-progress-text=""> - {meter.text} - </span> - ); -} - -export function JobProgressBar({ meter }: { meter?: ActivityMeter | null }) { - if (meter?.fraction === null || meter?.fraction === undefined) return null; - const pct = Math.round(Math.max(0, Math.min(1, meter.fraction)) * 100); - return ( - <span - className="relative col-span-2 h-0.5 overflow-hidden bg-seam" - role="progressbar" - aria-valuemin={0} - aria-valuemax={100} - aria-valuenow={pct} - data-job-progress={pct} - > - <i className="absolute inset-y-0 left-0 bg-meter" style={{ width: `${pct}%` }} /> - </span> - ); -} +// The Running row's progress: the two smallest parts of the ONE job progress +// (components/ui/job-progress.tsx, P4b), which the Media tab's drafts, Draft +// everything, the Build tab and the Iterations tab's jobs use whole. +export { JobProgressBar, JobProgressText } from "@/components/ui/job-progress"; diff --git a/umtool/components/ui/job-progress.tsx b/umtool/components/ui/job-progress.tsx @@ -0,0 +1,343 @@ +"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); `components/shell/JobProgress.tsx` +// re-exports them. 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<string, string | number | undefined>; +}; + +const STEP_TONE: Record<JobStepState, string> = { + 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<JobStepState, string> = { + 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 ( + <span className={className} data-job-progress-text=""> + {meter.text} + </span> + ); +} + +/** 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 ( + <span + className={cn("relative col-span-2 block h-0.5 overflow-hidden bg-seam", className)} + role="progressbar" + aria-valuemin={0} + aria-valuemax={100} + aria-valuenow={pct} + data-job-progress={pct} + > + <i className="absolute inset-y-0 left-0 bg-meter" style={{ width: `${pct}%` }} /> + </span> + ); +} + +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<React.ComponentProps<"div">, "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 ( + <div data-job-progress-of={state} className={cn("space-y-1.5 text-[12px]", className)} {...props}> + <div className="flex flex-wrap items-center gap-x-3 gap-y-1"> + {label && <span className="text-text">{label}</span>} + <span + role="status" + data-job-state-words="" + className={state === "failed" ? "text-reject-text" : live ? "text-text-2" : "text-muted"} + > + {status ?? state} + </span> + {current && <span className="font-mono text-[11.5px] text-text-2">{current}</span>} + {meter?.text && <JobProgressText meter={meter} className="font-mono text-[11.5px] text-muted-2" />} + {spend != null && ( + <span data-job-spend={spend.toFixed(2)} className="font-mono text-[11.5px] text-meter"> + {usd(spend)} + </span> + )} + {onCancel && live && ( + <Button size="sm" variant="destructive" className="ml-auto" aria-label={cancelName} onClick={onCancel}> + {cancelLabel} + </Button> + )} + </div> + {live && <JobProgressBar meter={meter} />} + {steps && steps.length > 0 && ( + <ol + className={cn( + "gap-x-4 gap-y-0.5", + stepColumns ? "grid sm:grid-flow-col sm:grid-rows-8" : "flex flex-wrap gap-x-3", + )} + > + {steps.map((s, i) => ( + <li + key={s.id} + title={s.detail ?? undefined} + className={cn("flex min-w-0 items-baseline gap-1.5", STEP_TONE[s.state])} + {...Object.fromEntries(Object.entries(s.attrs ?? {}).filter(([, v]) => v !== undefined))} + > + {stepColumns && <span className="w-5 shrink-0 text-right font-mono text-[11px] text-muted-2">{i + 1}</span>} + <span aria-hidden className="font-mono text-[11px]"> + {STEP_MARK[s.state]} + </span> + <span className={cn(s.optional && "italic", s.start && "underline decoration-seam-2 underline-offset-2")}>{s.label}</span> + {s.state !== "pending" && s.state !== "running" && <span className="sr-only">{s.state}</span>} + {s.detail && s.state !== "pending" && s.state !== "running" && ( + <span data-job-step-detail="" className="truncate text-[11px] text-muted-2"> + {s.detail} + </span> + )} + </li> + ))} + </ol> + )} + {children} + {log && log.length > 0 && ( + <pre + role="log" + aria-label={logLabel} + className="max-h-48 overflow-auto rounded-[2px] border border-seam bg-ground p-2 font-mono text-[11px] leading-snug whitespace-pre-wrap text-muted" + > + {log.join("\n")} + </pre> + )} + {error && <p className={cn("text-[11.5px]", ended || state === "failed" ? "text-reject-text" : "text-doubt-text")}>{error}</p>} + </div> + ); +} + +// ---- 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<void> } { + const [job, setJob] = useState<EditorJob | null>(null); + const [error, setError] = useState(""); + const ended = useRef(onEnd); + ended.current = onEnd; + const told = useRef<string | null>(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<React.ComponentProps<"div">, "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 ( + <JobProgress + data-job={jobId} + data-job-status={job?.status ?? "unknown"} + label={label} + state={v.state} + status={v.status} + meter={v.meter} + spend={v.spend} + current={!log && last && !ENDED.includes(job?.status ?? "") ? last : undefined} + log={log ? job?.tail : undefined} + logLabel={logLabel} + onCancel={() => + void cancel().then(() => { + onEnd?.(job); + }) + } + cancelName={cancelName} + error={error || undefined} + className={className} + {...rest} + /> + ); +}