Archilyzer · Source

archilyzer

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

commit 18b643e46bb1b12402ae6d3a5cdd902f9ce4396d
parent 5cc00608c2b9765a79fa5988b489fbf3afc188f9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 04:48:55 -0400

umtool: the rail's Running list — the editor's live jobs beside umtool's own, with spend

askEditor gives a GET 5 s and keeps its answer 2 s per URL (a POST 30 s, never
kept, and it drops the kept GETs), and says why it failed: unreachable, the
editor's WORKER_TOKEN unset (503), umtool's unset, the tokens differing, or a
refusal. lib/activity.ts readRunning merges GET /api/ops/jobs?active=1 (no kind)
with umtool's own jobs; lib/running.mjs (pure, tested) ranks them — generation,
then research acquisitions and umtool's clip windows, then the rest — and folds
queued work and the lane runners into one foot line. A report draft is placed on
its article by the iteration (or its log's first line) and shows its live spend
from the log; a chain sums the ledger; the label row shows the day's spend.
RunningList polls /api/running every 8 s while the tab is visible. The editor
stub answers GET /api/ops/jobs from a list a spec sets (POST /__stub/ops-jobs).

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

Diffstat:
Aumtool/app/api/running/route.ts | 17+++++++++++++++++
Mumtool/components/shell/AppRail.tsx | 40++++++----------------------------------
Aumtool/components/shell/JobProgress.tsx | 33+++++++++++++++++++++++++++++++++
Aumtool/components/shell/RunningList.tsx | 151++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/editor-stub.mjs | 58+++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/activity-types.ts | 4++--
Mumtool/lib/activity.ts | 327++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/lib/articles/generation.ts | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Aumtool/lib/running.mjs | 194+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/running.test.mjs | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
10 files changed, 952 insertions(+), 55 deletions(-)

diff --git a/umtool/app/api/running/route.ts b/umtool/app/api/running/route.ts @@ -0,0 +1,17 @@ +import { readRunning } from "@/lib/activity"; + +export const dynamic = "force-dynamic"; + +// The rail's Running list (lib/activity.ts readRunning): umtool's own jobs and +// the editor's live ones, the rows chosen, the rest folded, spend and the day's +// total. Never an error status for the editor's sake: an editor that cannot be +// asked is `editor.reason` in a 200, and umtool's own jobs still list. +// `?fresh=1` asks the editor again instead of taking its answer of the last 2 s. +export async function GET(request: Request) { + const fresh = new URL(request.url).searchParams.get("fresh") === "1"; + try { + return Response.json(await readRunning({ fresh }), { headers: { "cache-control": "no-store" } }); + } catch (err) { + return Response.json({ error: (err as Error).message }, { status: 500, headers: { "cache-control": "no-store" } }); + } +} diff --git a/umtool/components/shell/AppRail.tsx b/umtool/components/shell/AppRail.tsx @@ -1,11 +1,12 @@ import Link from "next/link"; import { cookies } from "next/headers"; import AppNav from "@/components/AppNav"; -import { runningActivity } from "@/lib/activity"; +import { initialRunning } from "@/lib/activity"; import { homeHref } from "@/lib/hrefs"; import { THEME_COOKIE, parseTheme } from "@/lib/theme"; import CreateMenu from "./CreateMenu"; import JumpButton from "./JumpButton"; +import RunningList from "./RunningList"; import ThemeControl from "./ThemeControl"; import { Mark, Wordmark } from "./Wordmark"; @@ -22,13 +23,13 @@ import { Mark, Wordmark } from "./Wordmark"; // // What is not built yet says so plainly rather than pretending: // - Pinned has no store until the piece page (P4a); it is empty. -// - Running lists umtool's own job (a build, a fetch, a render). The editor's -// jobs and their spend join it in P2b. +// - Running (RunningList.tsx) is umtool's own jobs and the editor's live ones +// with spend (lib/activity.ts readRunning, P2b). The server draws the last +// view it has, never waiting on the editor; the browser asks after load. // --------------------------------------------------------------------------- export default async function AppRail({ active }: { active: string }) { const theme = parseTheme((await cookies()).get(THEME_COOKIE)?.value); - const running = runningActivity(); return ( <div className="app-rail" data-app-rail=""> <Link href={homeHref()} prefetch={false} aria-label="umtool home" className="flex items-center gap-[9px] px-4 pb-3.5 pt-4 no-underline"> @@ -47,36 +48,7 @@ export default async function AppRail({ active }: { active: string }) { <p className="px-5 text-[12px] text-muted-2">Nothing pinned</p> </section> - <section - data-rail-section="running" - aria-label="Running" - className="mt-auto border-t border-seam pb-2 pt-3" - > - <h2 className="micro flex justify-between px-5 pb-2"> - <span>Running</span> - <span className="font-mono normal-case tracking-normal text-meter">{running ? 1 : 0}</span> - </h2> - {running ? ( - <Link href={running.href} prefetch={false} data-running={running.id} className="grid grid-cols-[1fr_auto] gap-x-2 gap-y-0.5 px-5 text-[12px] text-text-2 no-underline hover:text-text"> - <span className="truncate">{running.label}</span> - {running.progress && ( - <span className="font-mono text-[11px] text-muted-2"> - {running.progress.step}/{running.progress.of} - </span> - )} - {running.progress && ( - <span className="relative col-span-2 h-0.5 overflow-hidden bg-seam"> - <i - className="absolute inset-y-0 left-0 bg-meter" - style={{ width: `${Math.round((running.progress.step / Math.max(1, running.progress.of)) * 100)}%` }} - /> - </span> - )} - </Link> - ) : ( - <p className="px-5 text-[12px] text-muted-2">No umtool job running</p> - )} - </section> + <RunningList initial={initialRunning()} /> <div className="px-4 pb-4 pt-3"> <ThemeControl initial={theme} /> diff --git a/umtool/components/shell/JobProgress.tsx b/umtool/components/shell/JobProgress.tsx @@ -0,0 +1,33 @@ +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> + ); +} diff --git a/umtool/components/shell/RunningList.tsx b/umtool/components/shell/RunningList.tsx @@ -0,0 +1,151 @@ +"use client"; + +import Link from "next/link"; +import { useEffect, useRef, useState } from "react"; +import type { ActivityItem, RunningView } from "@/lib/activity-types"; +import { JobProgressBar, JobProgressText } from "./JobProgress"; + +// --------------------------------------------------------------------------- +// The rail's foot (canvas `.running`): what is running, umtool's own and the +// editor's, with spend. The label row is "Running N" and the day's API spend +// in Meter; then a row per job (lib/running.mjs chooses them) -- kind, target, +// progress, queued or running, and a generation job's spend -- each linking to +// its piece when it has one, else to the editor's /jobs; then the folded rest +// ("+ 140 queued · 3 lanes"). +// +// Three different things to say when there are no rows: the editor did not +// answer, the editor's WORKER_TOKEN is not set (it answered 503), and nothing +// is running. They are never the same sentence. +// +// The server renders the last view it has (or umtool's own jobs alone); this +// asks GET /api/running on mount, then every POLL_MS while the tab is visible, +// and not at all while it is hidden. One request at a time. +// --------------------------------------------------------------------------- + +export const POLL_MS = 8000; + +const usd = (n: number) => `$${n.toFixed(2)}`; + +function Row({ item: i }: { item: ActivityItem }) { + const queued = i.state === "queued"; + const right = i.generation && typeof i.spend === "number" ? usd(i.spend) : null; + const small = [i.target, right && i.meter?.text && !queued ? i.meter.text : null].filter(Boolean).join(" · "); + const body = ( + <> + <span className={queued ? "truncate text-muted-2" : "truncate"} data-running-kind=""> + {i.kindLabel ?? i.label} + </span> + {right ? ( + <span className="font-mono text-[11.5px] font-medium text-meter" data-running-spend={i.spend}> + {right} + </span> + ) : ( + <JobProgressText meter={i.meter} className="font-mono text-[11px] text-muted-2" /> + )} + {small && ( + <small className="col-span-2 truncate font-mono text-[11px] text-muted-2" data-running-target=""> + {small} + </small> + )} + {!queued && <JobProgressBar meter={i.meter} />} + </> + ); + const cls = "grid grid-cols-[minmax(0,1fr)_auto] gap-x-2 gap-y-0.5 text-[12px] text-text-2 no-underline hover:text-text"; + const title = [i.kindLabel ?? i.label, i.target, i.state].filter(Boolean).join(" · "); + return ( + <li data-running={i.id} data-running-state={i.state} data-running-source={i.source}> + {i.external ? ( + <a href={i.href} className={cls} title={title} data-running-external=""> + {body} + </a> + ) : ( + <Link href={i.href} prefetch={false} className={cls} title={title}> + {body} + </Link> + )} + </li> + ); +} + +export default function RunningList({ initial }: { initial: RunningView }) { + const [view, setView] = useState<RunningView>(initial); + const inflight = useRef(false); + + useEffect(() => { + let live = true; + const tick = async () => { + if (inflight.current || document.visibilityState === "hidden") return; + inflight.current = true; + try { + const r = await fetch("/api/running", { cache: "no-store" }); + const next = r.ok ? ((await r.json()) as RunningView) : null; + if (live && next && Array.isArray(next.rows)) setView(next); + } catch { + // the next tick asks again; the last view stays drawn + } finally { + inflight.current = false; + } + }; + void tick(); + const timer = window.setInterval(tick, POLL_MS); + const onVisible = () => { + if (document.visibilityState === "visible") void tick(); + }; + document.addEventListener("visibilitychange", onVisible); + return () => { + live = false; + window.clearInterval(timer); + document.removeEventListener("visibilitychange", onVisible); + }; + }, []); + + const { rows, editor, more, today } = view; + const state = editor.reason ?? (editor.pending ? "pending" : "ok"); + return ( + <section + data-rail-section="running" + aria-label="Running" + data-editor-state={state} + className="mt-auto border-t border-seam pb-2 pt-3" + > + <h2 className="micro flex justify-between px-5 pb-2"> + <span> + Running{" "} + <span className="font-mono normal-case tracking-normal text-meter" data-running-count={view.running}> + {view.running} + </span> + </span> + {today && ( + <span + className="font-mono normal-case tracking-normal text-meter" + data-today-spend={today.usd} + title={`Claude API spend today (${today.day}, UTC): ${today.jobs} job${today.jobs === 1 ? "" : "s"}, from the usage ledger`} + > + {usd(today.usd)} today + </span> + )} + </h2> + {rows.length > 0 && ( + <ul className="grid gap-1.5 px-5" data-running-list=""> + {rows.map((i) => ( + <Row key={`${i.source}:${i.id}`} item={i} /> + ))} + </ul> + )} + {editor.text ? ( + <p className="mt-1.5 px-5 text-[12px] text-text-2" data-running-editor={editor.reason ?? ""} title={editor.detail ?? undefined}> + {editor.text} + </p> + ) : rows.length === 0 ? ( + <p className="px-5 text-[12px] text-muted-2" data-running-empty={editor.pending ? "pending" : ""}> + {editor.pending ? "Asking the editor…" : "Nothing running"} + </p> + ) : null} + {more.text && ( + <a href={editor.jobsHref} className="mt-1.5 block px-5 text-[11.5px] text-muted-2 no-underline hover:text-text" data-running-more=""> + {rows.length ? more.text : more.text.replace(/^\+ /, "")} + </a> + )} + </section> + ); +} diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -103,6 +103,10 @@ function writeWindow(dir, name, seconds) { // never an LLM // GET /api/ops/job/<id>?tail=N that job's state and log // POST /api/ops/job {verb: cancel, ids} cancelled, its iteration too +// GET /api/ops/jobs?active=1 the live head (umtool's Running +// list, P2b): the stub's own queued +// and running drafts, plus the jobs a +// spec put there (POST /__stub/ops-jobs) // POST /api/ops/research-approve a research run's queue (release 27 // S11): its proposals refreshed from // the stub's acquisition jobs, then @@ -141,6 +145,17 @@ const presetOf = (routes) => Object.keys(PRESETS).find((p) => Object.keys(PRESETS[p]).every((t) => routes[t] === PRESETS[p][t])) ?? "custom"; const draftJobs = new Map(); +// THE LIVE JOB LIST, CONTROLLED (P2b). A spec posts `POST /__stub/ops-jobs +// {mode, jobs}` (no token: the stub's own door, like /health) and the editor's +// `GET /api/ops/jobs` answers from it: +// mode "ok" { ok, jobs: [...the spec's, ...the stub's live drafts] } +// mode "editor-token" 503, the editor's words when its WORKER_TOKEN is unset +// mode "unreachable" the socket is dropped: no answer at all +// A spec's job is OpsJobView-shaped ({id, kind, status, queuedAt, startedAt, +// queue, progress, detail, channelSlug}); `log` (lines) is what its +// `GET /api/ops/job/<id>?tail=N` answers. `{}` resets to "ok" with none. +const opsJobs = { mode: "ok", jobs: [] }; + const itDir = (article, n) => path.join(ARTICLES, article, "iterations", String(n)); const readIt = (article, n) => JSON.parse(readFileSync(path.join(itDir(article, n), "iteration.json"), "utf8")); const writeIt = (it) => writeFileSync(path.join(itDir(it.article, it.n), "iteration.json"), JSON.stringify(it, null, 2) + "\n"); @@ -613,7 +628,7 @@ function startDraft(body) { } } const slow = /slow/.test(String(body.question ?? body.feedback ?? "")); - const job = { id, article, n, task, autonomy: body.autonomy, status: "queued", log: [`report-draft ${task} ${article} i${n} (stub)`], timers: [] }; + const job = { id, article, n, task, autonomy: body.autonomy, status: "queued", at: Date.now(), log: [`report-draft ${task} ${article} i${n} (stub)`], timers: [] }; draftJobs.set(id, job); job.timers.push( setTimeout(() => { @@ -724,6 +739,37 @@ function generationRoute(req, res, url, auth) { return json(res, ok ? 200 : 400, { ok, results, ...(ok ? {} : { error: "not queued or running (or unknown)" }) }); }); } + if (req.method === "GET" && url.pathname === "/api/ops/jobs") { + req.resume(); + // Not recorded in `requests`: the rail polls it on every page, and specs + // read that list's last entries. + if (opsJobs.mode === "unreachable") return req.socket.destroy(); + if (opsJobs.mode === "editor-token") return json(res, 503, { ok: false, error: "worker endpoint disabled (set WORKER_TOKEN to enable)" }); + const active = url.searchParams.get("active") === "1"; + const live = [...draftJobs.values()] + .filter((j) => j.status === "queued" || j.status === "running") + .map((j) => ({ + id: j.id, + kind: j.kind ?? "report-draft", + status: j.status, + queuedAt: j.at ?? Date.now(), + ...(j.status === "running" ? { startedAt: j.at ?? Date.now() } : { queue: { key: "draft:api", position: 1, queued: 1 } }), + inRegistry: true, + replayable: false, + logSize: 0, + })); + const all = [...opsJobs.jobs.map(({ log: _log, ...j }) => j), ...live].filter((j) => !active || j.status === "queued" || j.status === "running"); + const limit = Number(url.searchParams.get("limit") ?? 50) || 50; + return json(res, 200, { ok: true, jobs: all.slice(0, limit), scanned: all.length, total: all.length }); + } + const injected = /^\/api\/ops\/job\/([^/]+)$/.exec(url.pathname); + const spec = injected && opsJobs.jobs.find((j) => j.id === injected[1]); + if (req.method === "GET" && spec) { + req.resume(); + const tail = Number(url.searchParams.get("tail") ?? 0); + const { log = [], ...job } = spec; + return json(res, 200, { ok: true, job, ...(tail ? { tail: log.slice(-tail) } : {}) }); + } const m = /^\/api\/ops\/job\/([^/]+)$/.exec(url.pathname); if (req.method === "GET" && m && draftJobs.has(m[1])) { req.resume(); @@ -749,6 +795,16 @@ const server = http.createServer((req, res) => { if (url.pathname === "/health") return json(res, 200, { ok: true }); + if (req.method === "POST" && url.pathname === "/__stub/ops-jobs") { + return readBody(req, (body) => { + const mode = body?.mode ?? "ok"; + if (!["ok", "editor-token", "unreachable"].includes(mode)) return json(res, 400, { error: `mode "${mode}" is not one of ok, editor-token, unreachable` }); + opsJobs.mode = mode; + opsJobs.jobs = Array.isArray(body?.jobs) ? body.jobs : []; + return json(res, 200, { ok: true, mode, jobs: opsJobs.jobs.length }); + }); + } + const auth = req.headers.authorization ?? ""; if (!TOKEN || auth !== `Bearer ${TOKEN}`) { req.resume(); diff --git a/umtool/lib/activity-types.ts b/umtool/lib/activity-types.ts @@ -1,3 +1,3 @@ -// Types only, for the client panel. The values live in lib/activity.ts, which +// Types only, for the client panels. The values live in lib/activity.ts, which // reaches both job registries and therefore `node:child_process`. -export type { ActivityItem, ActivityProgress } from "./activity"; +export type { ActivityItem, ActivityMeter, ActivityProgress, RunningView } from "./activity"; diff --git a/umtool/lib/activity.ts b/umtool/lib/activity.ts @@ -1,10 +1,33 @@ +import { readdir } from "node:fs/promises"; import path from "node:path"; +import { readIterations } from "yt-dlp-transcript-common/lib/report/iterations"; +import { readResearchState } from "yt-dlp-transcript-common/lib/report/draft/research/state"; +import { readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; +import { jobKindLabel } from "yt-dlp-transcript-common/jobs/jobKinds"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { askEditor, EditorError, editorUrl, type EditorErrorReason } from "./articles/generation"; +import { ARTICLES_KEY } from "./articles/key.mjs"; +import { sitesPaths } from "./articles/sites"; +import { articleHref, mixHref, projectHref } from "./hrefs"; import { recentJobs as recentChainJobs, runningJob, type Job } from "./jobs"; import { recentJobs as recentRenders, type RenderJob } from "./mix"; import { labelFor } from "./paths"; +import { + draftTargetFromLog, + editorProgress, + editorStateText, + foldRunning, + isLane, + moreText, + ownJobLabel, + queueText, + rankOf, + spendFromLog, +} from "./running.mjs"; // --------------------------------------------------------------------------- -// One activity list over the two job registries. +// One activity list over umtool's two job registries -- and, for the rail's +// Running list (P2b), the editor's live jobs beside them. // // Chain jobs (lib/jobs.ts: report builds, clip fetches, the song recipes) and // mix renders (lib/mix.ts) are kept in SEPARATE registries on purpose -- their @@ -13,6 +36,14 @@ import { labelFor } from "./paths"; // that does not care what else runs. This file does not merge the registries; // it merges their VIEWS, so the dashboard has one "now" and one "recent". // +// The editor's jobs come from `GET /api/ops/jobs?active=1` (askEditor: 5 s, kept +// 2 s), with no `kind`: a research run's acquisitions are downloads, imports +// and post walks. Which become rows is lib/running.mjs's (pure, tested). A +// report draft is placed on its article by the iteration that carries its job +// id (or its log's first line); a research acquisition by the proposal that +// does. Spend is the job's log (`~$0.41`, live) or the usage ledger +// (finished); the day's total is the ledger's. +// // SERVER ONLY, like everything that reaches the registries. // --------------------------------------------------------------------------- @@ -27,17 +58,39 @@ export type ActivityProgress = { entries?: Record<string, "fetching" | "cutting" | "done" | "failed">; }; +/** One progress presentation for every row (components/shell/JobProgress.tsx). */ +export type ActivityMeter = { + /** 0..1, or null when the job reports none (no bar is drawn). */ + fraction: number | null; + /** A few words: "2/4", "3/12 turns", "queued · next". */ + text: string | null; +}; + export type ActivityItem = { id: string; - source: "chain" | "render"; + /** chain / render: umtool's own registries; editor: the editor's. */ + source: "chain" | "render" | "editor"; + /** The registry's own label (a chain job's kind string). The dashboard prints it. */ label: string; - state: "running" | "done" | "failed"; + /** What kind of work, in words ("Report draft", "Make the video"). */ + kindLabel?: string; + /** What it works on: a channel, an article's iteration, a project. */ + target?: string | null; + /** `queued`: the editor holds it in a queue; umtool's own never queue. */ + state: "queued" | "running" | "done" | "failed"; startedAt: number; endedAt: number | null; error: string | null; progress?: ActivityProgress; - /** Where to go to see it: the project page for a chain, /mix for a render. */ + meter?: ActivityMeter; + /** A generation job: it may spend. */ + generation?: boolean; + /** USD so far (a running draft's log) or in all (the ledger), when known. */ + spend?: number | null; + /** Where to go to see it: its piece when it has one, else the editor's /jobs. */ href: string; + /** The href is the editor's, not a page here. */ + external?: boolean; }; /** @@ -59,39 +112,54 @@ export function entryStates(events: Record<string, unknown>[]): ActivityProgress return out; } +const storeArticleHref = (article: string) => articleHref({ site: ARTICLES_KEY, id: article }, { tab: "iterations" }); + function fromChain(j: Job): ActivityItem { const entries = entryStates(j.events); const start = j.events.find((e) => e.ev === "start") as { entries?: number } | undefined; const clipsOf = typeof start?.entries === "number" ? start.entries : undefined; const clipsDone = Object.values(entries ?? {}).filter((s) => s === "done").length; + const step = Math.min(j.stepIndex + 1, j.steps.length); + const of = j.steps.length; + const own = ownJobLabel(j.kind, j.project); return { id: j.id, source: "chain", label: j.kind, + kindLabel: own.label, + target: own.target, state: j.state, startedAt: j.startedAt, endedAt: j.endedAt, error: j.error, progress: { - step: Math.min(j.stepIndex + 1, j.steps.length), - of: j.steps.length, + step, + of, ...(clipsOf !== undefined ? { clipsOf, clipsDone } : {}), entries, }, - href: j.project ? `/projects/${j.project}` : "/work", + meter: clipsOf + ? { fraction: clipsDone / Math.max(1, clipsOf), text: `${clipsDone}/${clipsOf} clips` } + : { fraction: step / Math.max(1, of), text: `${step}/${of}` }, + ...(own.generation ? { generation: true } : {}), + href: j.project ? projectHref(j.project) : own.article ? storeArticleHref(own.article) : "/work", }; } function fromRender(r: RenderJob): ActivityItem { + const name = r.label || labelFor(r.out) || path.basename(r.out); return { id: r.id, source: "render", - label: `render ${r.label || labelFor(r.out) || path.basename(r.out)}`, + label: `render ${name}`, + kindLabel: "Render", + target: name, state: r.state, startedAt: r.startedAt, endedAt: r.endedAt, error: r.error, - href: "/tools/mix", + meter: { fraction: null, text: null }, + href: mixHref(), }; } @@ -108,3 +176,244 @@ export function runningActivity(): ActivityItem | null { const render = recentRenders(4).find((r) => r.state === "running"); return render ? fromRender(render) : null; } + +/** Everything of umtool's own that is running now (a chain and a render may run at once). */ +export function ownRunning(): ActivityItem[] { + const out: ActivityItem[] = []; + const chain = runningJob(); + if (chain) out.push(fromChain(chain)); + for (const r of recentRenders(8)) if (r.state === "running") out.push(fromRender(r)); + return out; +} + +// ─── The editor's jobs ─────────────────────────────────────────────────────── + +/** A row of `GET /api/ops/jobs` (editor/app/api/ops/_jobs.ts OpsJobView), as far as this reads it. */ +type EditorJob = { + id: string; + kind?: string; + channelSlug?: string; + status: string; + queuedAt: number; + startedAt?: number; + detail?: string; + queue?: { key?: string; position?: number; queued?: number }; + progress?: { metric?: string; initial?: number; current?: number; target?: number }; + background?: boolean; +}; + +type JobPlace = { article: string; n: number; task: string; research?: boolean }; + +/** + * Job id -> where it works: every iteration's `jobId`, every step's, and every + * research proposal's. Read from the article store (common's readers), kept + * 10 s on globalThis, and read only when an editor job needs placing. + */ +type JobIndex = { at: number; map: Map<string, JobPlace>; research: Set<string> }; +const ga = globalThis as typeof globalThis & { __umtoolJobIndex?: JobIndex | null }; +const INDEX_MS = 10_000; + +async function jobIndex(): Promise<JobIndex> { + const hit = ga.__umtoolJobIndex; + if (hit && Date.now() - hit.at < INDEX_MS) return hit; + const paths = sitesPaths(); + const map = new Map<string, JobPlace>(); + const research = new Set<string>(); + let names: string[] = []; + try { + names = (await readdir(/* turbopackIgnore: true */ paths.articlesDir, { withFileTypes: true })) + .filter((d) => d.isDirectory() && !d.name.startsWith(".")) + .map((d) => d.name); + } catch { + names = []; + } + await Promise.all( + names.map(async (article) => { + const read = await readIterations(article, paths).catch(() => null); + for (const it of read?.iterations ?? []) { + if (it.jobId) map.set(it.jobId, { article, n: it.n, task: it.kind }); + for (const s of it.steps ?? []) if (s.jobId) map.set(s.jobId, { article, n: it.n, task: s.task }); + if (it.kind !== "research") continue; + const state = await readResearchState(article, it.n, paths).catch(() => null); + for (const p of state?.proposals ?? []) { + if (!p.jobId) continue; + research.add(p.jobId); + map.set(p.jobId, { article, n: it.n, task: p.action, research: true }); + } + } + }), + ); + const out = { at: Date.now(), map, research }; + ga.__umtoolJobIndex = out; + return out; +} + +type UsageRows = Awaited<ReturnType<typeof readGenerationUsage>>; + +/** The ledger's spend per job id, and its rows (a chain sums its iteration's). */ +async function ledger(): Promise<{ byJob: Map<string, number>; rows: UsageRows; ok: boolean }> { + try { + const rows = await readGenerationUsage(getPaths().generationUsageFile); + const byJob = new Map<string, number>(); + for (const r of rows) if (r.jobId) byJob.set(r.jobId, (byJob.get(r.jobId) ?? 0) + r.usd); + return { byJob, rows, ok: true }; + } catch { + return { byJob: new Map(), rows: [], ok: false }; + } +} + +const round4 = (n: number) => Math.round(n * 10_000) / 10_000; + +export type RunningView = { + /** When this was read (ms); 0 for a server render's first guess. */ + at: number; + /** The rows, in order: running (umtool's own first), then queued generation and acquisitions. */ + rows: ActivityItem[]; + /** Running jobs, rows or not (lanes not counted). */ + running: number; + queued: number; + /** What the rows leave out, said once on the foot line. */ + more: { running: number; queued: number; lanes: number; text: string | null }; + editor: { + /** null: the editor answered (or was not asked yet). Else why its jobs are not in the list. */ + reason: EditorErrorReason | null; + /** The line the rail shows for it, or null. */ + text: string | null; + /** The words behind it, for the tooltip. */ + detail: string | null; + /** The editor's /jobs page. */ + jobsHref: string; + /** It has not been asked yet (a server render's first guess). */ + pending?: boolean; + }; + /** The day's API spend (UTC) from the usage ledger, or null when it is not read. */ + today: { day: string; usd: number; jobs: number } | null; +}; + +type Ranked = ActivityItem & { own?: boolean; rank: number; lane: boolean }; + +function editorItem(j: EditorJob, place: JobPlace | null, rank: number, spend: number | null, jobsHref: string): Ranked { + const queued = j.status === "queued"; + const p = editorProgress(j.progress); + const kind = j.kind ?? "job"; + const target = place + ? `${place.article} i${place.n}${place.task && place.task !== "sweep" ? ` · ${place.task}` : ""}` + : (j.detail ?? j.channelSlug ?? null); + return { + id: j.id, + source: "editor", + label: kind, + kindLabel: place?.research ? `Acquisition · ${jobKindLabel(kind)}` : jobKindLabel(kind), + target, + state: queued ? "queued" : "running", + startedAt: j.startedAt ?? j.queuedAt, + endedAt: null, + error: null, + meter: queued ? { fraction: null, text: queueText(j.queue) } : { fraction: p?.fraction ?? null, text: p?.text ?? null }, + ...(rank === 0 ? { generation: true, spend } : {}), + href: place ? storeArticleHref(place.article) : jobsHref, + ...(place ? {} : { external: true }), + rank, + lane: isLane(j.kind), + }; +} + +// The last view, for a server render that must not wait on the editor. +const gv = globalThis as typeof globalThis & { __umtoolRunning?: RunningView | null }; +const PEEK_MS = 15_000; + +/** The last Running view if it is fresh enough to draw (never asks the editor), else null. */ +export function peekRunning(): RunningView | null { + const v = gv.__umtoolRunning; + return v && Date.now() - v.at < PEEK_MS ? v : null; +} + +const strip = ({ own: _o, rank: _r, lane: _l, ...rest }: Ranked): ActivityItem => rest; + +/** + * The rail's Running list: umtool's own jobs and the editor's live ones, the + * rows chosen and the rest folded (lib/running.mjs), with spend. Never throws: + * an editor that cannot be asked is a `reason`, and umtool's own jobs still list. + */ +export async function readRunning({ fresh = false }: { fresh?: boolean } = {}): Promise<RunningView> { + const jobsHref = `${editorUrl()}/jobs`; + const own: Ranked[] = ownRunning().map((i) => ({ ...i, own: true, rank: 0, lane: false })); + let reason: EditorErrorReason | null = null; + let detail: string | null = null; + let jobs: EditorJob[] = []; + try { + const answer = await askEditor<{ jobs?: EditorJob[] }>("/api/ops/jobs?active=1&limit=200", { fresh }); + jobs = Array.isArray(answer.jobs) ? answer.jobs : []; + } catch (err) { + reason = err instanceof EditorError ? err.reason : "refused"; + detail = (err as Error).message; + } + + const { byJob, rows: usage, ok: ledgerOk } = await ledger(); + // Only an editor job that is not a lane needs placing; the index is read then. + const index = jobs.some((j) => !isLane(j.kind)) + ? await jobIndex() + : { map: new Map<string, JobPlace>(), research: new Set<string>() }; + + const items = await Promise.all( + jobs.map(async (j) => { + const rank = rankOf(j, index.research); + let place = index.map.get(j.id) ?? null; + let spend: number | null = byJob.has(j.id) ? round4(byJob.get(j.id) as number) : null; + // A running draft's log: its live spend, and its article when no + // iteration names the job yet. Asked only for a draft that runs. + if (j.kind === "report-draft" && j.status === "running") { + const tail = await askEditor<{ tail?: string[] }>(`/api/ops/job/${encodeURIComponent(j.id)}?tail=200`, { fresh }).catch(() => null); + const lines = Array.isArray(tail?.tail) ? tail.tail.map(String) : []; + spend = spendFromLog(lines) ?? spend; + if (!place) { + const t = draftTargetFromLog(lines); + if (t) place = { article: t.article, n: t.n, task: t.task }; + } + } + return editorItem(j, place, rank, spend, jobsHref); + }), + ); + + // A chain's spend: the ledger's rows for its iteration since it started. + for (const o of own) { + const chain = /^(?:chain|draft-all) (\S+) i(\d+)$/.exec(o.label); + if (!chain) continue; + const since = new Date(o.startedAt).toISOString(); + o.spend = round4( + usage.filter((r) => r.article === chain[1] && r.iteration === Number(chain[2]) && r.at >= since).reduce((s, r) => s + r.usd, 0), + ); + } + + const fold = foldRunning([...own, ...items]); + const day = utcDay(); + const todayRows = usage.filter((r) => r.day === day); + const view: RunningView = { + at: Date.now(), + rows: fold.rows.map(strip), + running: fold.running, + queued: fold.queued, + more: { ...fold.more, text: moreText(fold.more) }, + editor: { reason, text: editorStateText(reason), detail, jobsHref }, + today: ledgerOk ? { day, usd: round4(todayRows.reduce((s, r) => s + r.usd, 0)), jobs: new Set(todayRows.map((r) => r.jobId)).size } : null, + }; + gv.__umtoolRunning = view; + return view; +} + +/** What a server render draws before the browser asks: the last view, else umtool's own jobs alone. */ +export function initialRunning(): RunningView { + const peek = peekRunning(); + if (peek) return peek; + const own = ownRunning(); + const fold = foldRunning(own.map((i) => ({ ...i, own: true, rank: 0, lane: false }))); + return { + at: 0, + rows: own, + running: fold.running, + queued: 0, + more: { ...fold.more, text: null }, + editor: { reason: null, text: null, detail: null, jobsHref: `${editorUrl()}/jobs`, pending: true }, + today: null, + }; +} diff --git a/umtool/lib/articles/generation.ts b/umtool/lib/articles/generation.ts @@ -47,28 +47,57 @@ export function editorUrl(): string { return (process.env.ARCHILYZER_EDITOR_URL ?? DEFAULT_EDITOR).replace(/\/+$/, ""); } +/** + * Why the editor could not be asked, or what it said no with: + * no-token umtool has no WORKER_TOKEN, so it never asked + * unreachable nothing answered (refused, reset, or no answer in time) + * editor-token the editor answered 503: its own WORKER_TOKEN is not set, so + * its ops surface is off + * denied the editor answered 401: the two tokens differ + * refused the editor answered and said no (its words are the message) + */ +export type EditorErrorReason = "no-token" | "unreachable" | "editor-token" | "denied" | "refused"; + export class EditorError extends Error { constructor( message: string, readonly status: number, + readonly reason: EditorErrorReason = "refused", ) { super(message); } } +/** A GET's answer is kept this long per URL: a page and the rail asking at once ask once. */ +export const EDITOR_MEMO_MS = 2000; +/** A GET that has not answered in this long is an editor that is not answering. */ +export const EDITOR_GET_TIMEOUT_MS = 5000; /** - * Ask the editor's ops API. Answers its JSON; an editor that refuses (`ok: - * false`, or a non-2xx) throws an EditorError carrying its words and status. + * A POST waits longer: it may have done its write when the answer is late, and + * calling that "unreachable" invites a second click that writes twice. */ -export async function askEditor<T = Record<string, unknown>>( - route: string, - init: { method?: "GET" | "POST"; body?: unknown } = {}, -): Promise<T> { +export const EDITOR_POST_TIMEOUT_MS = 30_000; + +// The memo, ON globalThis (one per process, not one per Next bundle -- the +// lesson of P2a's project cache). It holds the PROMISE, so two callers in the +// same moment share one request, and a refusal is kept as long as an answer: +// an editor that is down is asked once per 2 s, not once per caller. +type Memo = Map<string, { at: number; p: Promise<unknown> }>; +const gm = globalThis as typeof globalThis & { __umtoolEditorMemo?: Memo }; +const memo: Memo = (gm.__umtoolEditorMemo ??= new Map()); + +/** Forget every kept answer (a write went through; the next read asks again). */ +export function clearEditorMemo(): void { + memo.clear(); +} + +async function askOnce<T>(route: string, init: { method?: "GET" | "POST"; body?: unknown }, timeoutMs: number): Promise<T> { const token = agentToken(); if (!token) { throw new EditorError( "WORKER_TOKEN is not set, so the editor cannot be asked. Set it to the same value the editor runs with.", 400, + "no-token", ); } let res: Response; @@ -78,18 +107,63 @@ export async function askEditor<T = Record<string, unknown>>( headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}), cache: "no-store", + signal: AbortSignal.timeout(timeoutMs), }); } catch (err) { - throw new EditorError(`could not reach the editor at ${editorUrl()}: ${(err as Error).message}`, 502); + const e = err as Error; + if (e.name === "TimeoutError" || e.name === "AbortError") { + throw new EditorError(`the editor at ${editorUrl()} did not answer in ${Math.round(timeoutMs / 1000)} s`, 504, "unreachable"); + } + throw new EditorError(`could not reach the editor at ${editorUrl()}: ${e.message}`, 502, "unreachable"); + } + let body: Record<string, unknown>; + try { + body = (await res.json()) as Record<string, unknown>; + } catch (err) { + // The answer started and then stopped (or was not JSON). A timeout here is + // still an editor that did not answer. + const e = err as Error; + if (e.name === "TimeoutError" || e.name === "AbortError") { + throw new EditorError(`the editor at ${editorUrl()} did not answer in ${Math.round(timeoutMs / 1000)} s`, 504, "unreachable"); + } + body = {}; } - const body = (await res.json().catch(() => ({}))) as Record<string, unknown>; if (!res.ok || body.ok === false) { const status = res.status >= 400 ? res.status : 400; - throw new EditorError(String(body.error ?? `the editor answered HTTP ${res.status}`), status); + const reason: EditorErrorReason = res.status === 503 ? "editor-token" : res.status === 401 ? "denied" : "refused"; + throw new EditorError(String(body.error ?? `the editor answered HTTP ${res.status}`), status, reason); } return body as T; } +/** + * Ask the editor's ops API. Answers its JSON; an editor that refuses (`ok: + * false`, or a non-2xx) throws an EditorError carrying its words, status and + * reason. A GET is given 5 s and kept 2 s per URL (`fresh` asks again); a POST + * is given 30 s, never kept, and drops every kept GET -- what it wrote may be + * what the next read is for. + */ +export async function askEditor<T = Record<string, unknown>>( + route: string, + init: { method?: "GET" | "POST"; body?: unknown; fresh?: boolean } = {}, +): Promise<T> { + const method = init.method ?? "GET"; + if (method !== "GET") { + clearEditorMemo(); + return askOnce<T>(route, init, EDITOR_POST_TIMEOUT_MS); + } + const key = `${editorUrl()}${route}`; + const now = Date.now(); + for (const [k, v] of memo) if (now - v.at >= EDITOR_MEMO_MS) memo.delete(k); + const hit = memo.get(key); + if (hit && !init.fresh) return hit.p as Promise<T>; + const p = askOnce<T>(route, init, EDITOR_GET_TIMEOUT_MS); + memo.set(key, { at: now, p }); + // The kept promise is never an unhandled rejection; each caller sees it. + p.catch(() => {}); + return p; +} + /** A route's answer for an error: the editor's status and words, else a 500. */ export function errorResponse(err: unknown): Response { const status = err instanceof EditorError ? err.status : 500; diff --git a/umtool/lib/running.mjs b/umtool/lib/running.mjs @@ -0,0 +1,194 @@ +// THE RAIL'S RUNNING LIST, AS DATA (plans/umtool-redesign.md, P2b): which of +// the editor's live jobs become rows, in what order, what folds into the foot +// line, and how a job's progress and spend read. Pure -- no disk, no clock, no +// fetch -- so `node --test` pins the rules; lib/activity.ts does the reading. +// +// The editor is asked for EVERY live job (`GET /api/ops/jobs?active=1`, no +// `kind`): a research run's acquisitions are downloads, imports and post +// walks, kinds no filter could name in advance. The choosing happens here: +// +// lanes the auto-queue runners (auto-download, auto-transcribe, …) run +// for as long as the editor does. They are counted on the foot +// line, never a row: a row that never ends says nothing. +// rank 0 generation (a report draft, the verdict bench, a voice) +// rank 1 ours: an acquisition a research run asked for, a clip window +// umtool asked for +// rank 2 anything else the editor runs (a sync, a transcription) +// +// Rows: every running job (umtool's own first, then by rank, oldest first), +// then the QUEUED jobs of rank 0 and 1 -- at most MAX_ROWS. The rest folds: +// "+ N running · M queued · K lanes". A queued rank-2 job is never a row; the +// editor's queue can hold hundreds of them. + +/** The editor's lane runners: long-lived loops that enqueue the real work. */ +export const LANE_KINDS = new Set(["auto-download", "auto-transcribe", "auto-digest", "auto-backfill", "auto-publish"]); + +/** Generation: model calls, and the voices a narration is spoken with. */ +export const GENERATION_KINDS = new Set(["report-draft", "bench-verdicts", "tts-file"]); + +/** Clip windows: umtool asks for them (`requestedBy: "umtool"`, the job's detail says so). */ +const WINDOW_KINDS = new Set(["fetch-window", "fetch-windows"]); + +export const MAX_ROWS = 5; + +/** @param {string | undefined} kind */ +export const isLane = (kind) => typeof kind === "string" && LANE_KINDS.has(kind); + +/** + * A job's rank (lower shows first). `research` is the set of job ids a research + * run's proposals name. + * + * @param {{ id: string, kind?: string, detail?: string }} job + * @param {Set<string>} [research] + */ +export function rankOf(job, research = new Set()) { + if (job.kind && GENERATION_KINDS.has(job.kind)) return 0; + if (research.has(job.id)) return 1; + if (job.kind && WINDOW_KINDS.has(job.kind) && /^umtool\b/.test(job.detail ?? "")) return 1; + return 2; +} + +/** + * The spend a generation job's log reports so far: the last `~$0.41` in it + * (the agent tasks write one per turn, `turn 3: … — ~$0.41`), or null. + * + * @param {string[]} lines + */ +export function spendFromLog(lines) { + let out = null; + for (const line of lines ?? []) { + for (const m of String(line).matchAll(/~\$(\d+(?:\.\d+)?)/g)) out = Number(m[1]); + } + return out !== null && Number.isFinite(out) ? out : null; +} + +/** + * The article, iteration and task a report-draft job's FIRST log line names + * (`sweep of <article> i3 on <model> (…)`), or null. The fallback when no + * iteration on disk carries the job's id yet. + * + * @param {string[]} lines + */ +export function draftTargetFromLog(lines) { + for (const line of lines ?? []) { + const m = /^([a-z-]+) of ([a-z0-9][a-z0-9-]*) i(\d+) on /.exec(String(line)); + if (m) return { task: m[1], article: m[2], n: Number(m[3]) }; + } + return null; +} + +/** + * The editor's progress snapshot as one fraction and a few words, or null. + * `current` is the runner's own count when it keeps one; else the snapshot's + * `initial` (the editor re-counts the rest from disk for its own page only). + * + * @param {{ metric?: string, initial?: number, current?: number, target?: number } | null | undefined} p + */ +export function editorProgress(p) { + if (!p || typeof p.target !== "number" || !(p.target > 0)) return null; + const done = typeof p.current === "number" ? p.current : typeof p.initial === "number" ? p.initial : 0; + const fraction = Math.max(0, Math.min(1, done / p.target)); + return { fraction, text: `${done}/${p.target}${p.metric ? ` ${p.metric}` : ""}` }; +} + +/** + * Where a queued job waits, in words. + * + * @param {{ position?: number, queued?: number } | null | undefined} q + */ +export function queueText(q) { + if (!q || typeof q.position !== "number" || q.position <= 0) return "queued"; + return q.position === 1 ? "queued · next" : `queued · ${q.position - 1} ahead`; +} + +/** + * What one of umtool's own jobs is, from its kind string: `chain <article> i2` + * is "Make the video" of that iteration, `draft-all …` "Draft everything", and + * any other (`build <project> (final)`, `narrate <project> <card>`, …) its + * first word, the rest as the target. `project` is the job's own, when stamped. + * + * @param {string} kind + * @param {string | null} [project] + */ +export function ownJobLabel(kind, project = null) { + const chain = /^(chain|draft-all) (\S+) i(\d+)$/.exec(kind); + if (chain) { + return { + label: chain[1] === "draft-all" ? "Draft everything" : "Make the video", + target: `${chain[2]} i${chain[3]}`, + article: chain[2], + n: Number(chain[3]), + generation: true, + }; + } + const [head, ...rest] = kind.split(" "); + const word = head ? head[0].toUpperCase() + head.slice(1).replace(/-/g, " ") : kind; + return { label: word, target: project ?? (rest.join(" ") || null), article: null, n: null, generation: false }; +} + +/** + * Choose the rows and fold the rest. + * + * @template {{ state: string, own?: boolean, lane?: boolean, rank?: number, startedAt: number }} I + * @param {I[]} items + * @param {number} [max] + * @returns {{ rows: I[], more: { running: number, queued: number, lanes: number }, running: number, queued: number }} + */ +export function foldRunning(items, max = MAX_ROWS) { + const lanes = items.filter((i) => i.lane && i.state === "running").length; + const live = items.filter((i) => !i.lane && (i.state === "running" || i.state === "queued")); + const order = (a, b) => + Number(!a.own) - Number(!b.own) || (a.rank ?? 2) - (b.rank ?? 2) || a.startedAt - b.startedAt; + const running = live.filter((i) => i.state === "running").sort(order); + const queued = live.filter((i) => i.state === "queued").sort(order); + const candidates = [...running, ...queued.filter((i) => (i.rank ?? 2) <= 1)]; + const rows = candidates.slice(0, max); + const shown = new Set(rows); + return { + rows, + more: { + running: running.filter((i) => !shown.has(i)).length, + queued: queued.filter((i) => !shown.has(i)).length, + lanes, + }, + running: running.length, + queued: queued.length, + }; +} + +/** + * The foot line under the rows, or null: "+ 2 running · 140 queued · 3 lanes". + * + * @param {{ running: number, queued: number, lanes: number }} more + */ +export function moreText(more) { + const parts = []; + if (more.running) parts.push(`+ ${more.running} running`); + if (more.queued) parts.push(`${parts.length ? "" : "+ "}${more.queued} queued`); + if (more.lanes) parts.push(`${parts.length ? "" : "+ "}${more.lanes} lane${more.lanes === 1 ? "" : "s"}`); + return parts.length ? parts.join(" · ") : null; +} + +/** + * The line that says why the editor's jobs are not listed, by reason + * (lib/articles/generation.ts EditorErrorReason), or null when they are. + * + * @param {string | null} reason + */ +export function editorStateText(reason) { + switch (reason) { + case null: + case undefined: + return null; + case "unreachable": + return "Editor unreachable"; + case "editor-token": + return "Editor's WORKER_TOKEN not set"; + case "no-token": + return "WORKER_TOKEN not set here"; + case "denied": + return "WORKER_TOKEN does not match the editor's"; + default: + return "Editor's jobs could not be read"; + } +} diff --git a/umtool/lib/running.test.mjs b/umtool/lib/running.test.mjs @@ -0,0 +1,91 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + draftTargetFromLog, + editorProgress, + editorStateText, + foldRunning, + isLane, + moreText, + ownJobLabel, + queueText, + rankOf, + spendFromLog, +} from "./running.mjs"; + +test("rank: generation first, then what umtool or a research run asked for, then the rest", () => { + const research = new Set(["acq1"]); + assert.equal(rankOf({ id: "a", kind: "report-draft" }, research), 0); + assert.equal(rankOf({ id: "b", kind: "tts-file" }, research), 0); + assert.equal(rankOf({ id: "acq1", kind: "import-archive-org" }, research), 1); + assert.equal(rankOf({ id: "c", kind: "fetch-window", detail: "umtool · reports/x/c01" }, research), 1); + assert.equal(rankOf({ id: "d", kind: "fetch-window", detail: "mcp · x" }, research), 2); + assert.equal(rankOf({ id: "e", kind: "download-missing" }, research), 2); + assert.ok(isLane("auto-download")); + assert.ok(!isLane("auto-download-unit")); +}); + +test("spend and target from a draft's log", () => { + const log = [ + "sweep of api-shondo i2 on claude-opus-5-5 (the Claude API, cap $5)", + "turn 1: search_transcripts — ~$0.04", + "turn 2: get_transcripts, get_transcripts — ~$0.41", + ]; + assert.equal(spendFromLog(log), 0.41); + assert.equal(spendFromLog(["no money here"]), null); + assert.deepEqual(draftTargetFromLog(log), { task: "sweep", article: "api-shondo", n: 2 }); + assert.equal(draftTargetFromLog(["corpus local"]), null); +}); + +test("progress and queue in words", () => { + assert.deepEqual(editorProgress({ metric: "turns", initial: 0, current: 3, target: 12 }), { fraction: 0.25, text: "3/12 turns" }); + assert.deepEqual(editorProgress({ metric: "downloads", initial: 4, target: 8 }), { fraction: 0.5, text: "4/8 downloads" }); + assert.equal(editorProgress({ metric: "x", initial: 0, target: 0 }), null); + assert.equal(editorProgress(undefined), null); + assert.equal(queueText({ position: 1 }), "queued · next"); + assert.equal(queueText({ position: 4 }), "queued · 3 ahead"); + assert.equal(queueText(undefined), "queued"); +}); + +test("umtool's own kinds in words", () => { + assert.deepEqual(ownJobLabel("chain zeta i2"), { label: "Make the video", target: "zeta i2", article: "zeta", n: 2, generation: true }); + assert.equal(ownJobLabel("draft-all zeta i3").label, "Draft everything"); + assert.deepEqual(ownJobLabel("build reports/x (final)", "reports/x"), { label: "Build", target: "reports/x", article: null, n: null, generation: false }); + assert.equal(ownJobLabel("check-sources (2 projects)").label, "Check sources"); +}); + +test("fold: running rows first (umtool's own on top), then queued generation; the rest is counted", () => { + const at = (n) => 1000 + n; + const items = [ + { id: "lane1", state: "running", lane: true, rank: 2, startedAt: at(0) }, + { id: "lane2", state: "running", lane: true, rank: 2, startedAt: at(0) }, + { id: "sync", state: "running", rank: 2, startedAt: at(1) }, + { id: "draft", state: "running", rank: 0, startedAt: at(5) }, + { id: "own", state: "running", own: true, rank: 0, startedAt: at(9) }, + { id: "q-draft", state: "queued", rank: 0, startedAt: at(2) }, + { id: "q-dl1", state: "queued", rank: 2, startedAt: at(3) }, + { id: "q-dl2", state: "queued", rank: 2, startedAt: at(4) }, + { id: "done", state: "done", rank: 0, startedAt: at(0) }, + ]; + const f = foldRunning(items, 5); + assert.deepEqual(f.rows.map((r) => r.id), ["own", "draft", "sync", "q-draft"]); + assert.deepEqual(f.more, { running: 0, queued: 2, lanes: 2 }); + assert.equal(f.running, 3); + assert.equal(f.queued, 3); + assert.equal(moreText(f.more), "+ 2 queued · 2 lanes"); + + const tight = foldRunning(items, 2); + assert.deepEqual(tight.rows.map((r) => r.id), ["own", "draft"]); + assert.deepEqual(tight.more, { running: 1, queued: 3, lanes: 2 }); + assert.equal(moreText(tight.more), "+ 1 running · 3 queued · 2 lanes"); + assert.equal(moreText({ running: 0, queued: 0, lanes: 1 }), "+ 1 lane"); + assert.equal(moreText({ running: 0, queued: 0, lanes: 0 }), null); +}); + +test("the three ways the editor's jobs are missing are three sentences", () => { + const said = ["unreachable", "editor-token", "no-token", "denied", "refused"].map(editorStateText); + assert.equal(new Set(said).size, said.length); + assert.equal(editorStateText("unreachable"), "Editor unreachable"); + assert.equal(editorStateText("editor-token"), "Editor's WORKER_TOKEN not set"); + assert.equal(editorStateText(null), null); +});