commit 4bf3f1c6c297d02ea326b838f5b2a27060838d90
parent 873569b08432da857ca86a5822817a3884db907b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 05:43:13 -0400
Merge ux/integration (P2b, 498f76e6) into ux/r2
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
19 files changed, 1558 insertions(+), 70 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -48,6 +48,9 @@
- **umtool: Work lists every piece.** `/work` is every article (with the video projects made from it) and every project no article claims, one lit line each: its stage on a four-step bar, what it is, its lifecycle and how many calls wait on it, with **Park**, **Mark done** and **Reactivate** on the line. Facets: stage, kind, site, lifecycle (active by default) and a search (`/` puts the cursor there); **By site** groups by site, each site's name linking its page. It reads the old lists' keys, so an old link lands on the same set.
- **umtool's addresses moved, and every old one redirects.** `/browse` → `/work`; `/browse/<project>[/…]` → `/projects/<project>[/…]` (cuts, clip and claim benches, takes, narration, review); `/browse/decisions` → `/`; `/browse/find`, `/browse/faces`, `/browse/sources`, `/browse/trim/<set>` → `/tools/…`; `/mix` → `/tools/mix`; `/sort`, `/salvage`, `/verify`, `/keeps` → `/tools/song/<pile>`; `/bench` → `/tools/bench`; `/articles` → `/work?kind=article&site=articles` (the store's articles, as before); `/sites` → `/work?by=site`. Redirects are temporary (307) and keep the query string, so a decision's `…?note=<id>` link and every bookmark still land. `/projects` is the project grid by folder (the old `/browse` page, with **+ new project**); `/tools` and `/tools/song` list the tools; `/sites/<site>` and the article pages are unchanged. A project named `find`, `faces`, `sources`, `trim` or `decisions` is no longer shadowed by a tool page; only `at` (`/projects/at?path=`, for a name that cannot be a URL) is reserved.
- **umtool: the rail is Inbox · Research · Work · Tools · Settings, and ⌘K jumps anywhere.** Inbox and Work show their counts; Tools opens into its tools (find, mix, the song piles, faces, sources, the verdict bench) while you are in one; Settings is `/settings/system`, which holds the old dashboard's panels (tools and disk, recent jobs, project states, sources, deliverables) and links the generation policy. ⌘K (or Ctrl+K), from any page including a bench, opens a jump list of every piece, place, tool and create action: type to narrow, ↑ / ↓, Enter. Research is linked ahead of its page. The "resume" chip on the Inbox offers where an old remembered address lands now.
+- **umtool's rail shows what is running, the editor's jobs too, and what it costs.** The foot of the rail lists umtool's own job and the editor's live ones (`GET /api/ops/jobs?active=1`): each with what it is, what it works on, how far it is, queued or running, and a report draft's spend so far; the label row says **Running N** and the day's Claude API spend. A row links to its article when it has one, else to the editor's `/jobs`. Queued syncs and the editor's lane runners fold into one line ("+ 140 queued · 3 lanes"). When the editor's jobs cannot be read the rail says why — **Editor unreachable**, **Editor's WORKER_TOKEN not set** (it answered 503) — and never just "nothing running". It asks every 8 s, and not while the tab is hidden.
+- **umtool's Inbox has a card for drafts nobody has reviewed.** A report video whose fields a model drafted (narration, on-screen text, the teaser, the cut, flips, threads, the YouTube text) and that are not approved is one card under **Review** ("Narration draft · 5 fields · by qwen3:8b"); **Review drafts** opens the project's review page, and the card goes once they are approved. The decisions API carries them as `drafts-unreviewed` rows, one per field.
+- **umtool waits at most 5 s for the editor.** A read from the editor's ops API is given 5 s (a write 30 s) and a read is kept 2 s, so the rail, a page and a poll asking at once ask once; an editor that does not answer is said to be unreachable rather than hanging the page.
- **Articles, iterations, report-video projects and takes can be deleted, and every delete shows its plan first.** `archilyzer reports delete <id>` prints what would go — each path with its size, what is kept and why, and anything that stops it — and deletes nothing until `--apply`; `--iteration <n>` deletes one iteration. Deleting an article removes its directory (report, video, history, notes, iterations), each iteration's video project under `settings.generation.projectsRoot` and its staged exports. A published article is refused unless `--force`, which unpublishes it first; an article with a running iteration is always refused. An iteration is refused while it is the current article or video, the one the article's report came from, running, or the parent or original of another iteration, and its number is never given out again. The usage ledger, the shared prepared-media cache and the corpus's git history are kept. The same deletes run over HTTP as `pnpm ops delete-article {id, force?, dryRun?}` and `pnpm ops delete-iteration {id, n, dryRun?}`, which answer a refusal as a 409 with the plan.
- **umtool: Delete article, `Delete i<n>`, Delete project and `Delete take <id>`.** Each button reads the plan, shows it (what goes with sizes, what is kept, what refuses) and deletes only on **Confirm delete**; **Keep it** closes it. **Delete article** is on an article's page (one in the making too) and returns to `/articles`, which says what went; `Delete i<n>` is on each iteration of the Iterations tab. **Delete project** on a report-video project removes its directory, and its `out/` or deliverables on the media drive when they are its own copy; it is refused while a job works in the project, for an article's current video, and — unless you tick **delete anyway** — for a project whose manifest names an article with a video attached. `Delete take <id>` removes `takes/<id>/`; the take whose manifest is the project's own needs **delete anyway**, and its verdict and notes are kept.
- **Reports and their revisions can be generated by the editor: `pnpm ops report-draft`.** `{"task": "sweep", "article", "question", "channels"}` drafts a new report of an article as its next iteration; `{"task": "revise-report" | "revise-video", "article", "iteration", "feedback"}` revises one; `{"task": "narrate", "article", "iteration"}` drafts the narration of an iteration's video cut; `"copyOf": N` runs iteration N again on another `"model"`. Each is a **Report draft** job on /jobs, on the Claude API (`draft:api`) or the local model (`draft:local`) by the model, and `pnpm ops job cancel` stops one. Every quote a model writes must be the transcript's words within 90 seconds of its link, or the finding is dropped; links cite the archive, never the platform. The answer names the job and the iteration; the job's log ends with the outcome. Needs a restart of the editor.
diff --git a/plans/umtool-redesign.md b/plans/umtool-redesign.md
@@ -350,10 +350,11 @@ P0 design ─► P1 foundation ─┬─► P3 inbox/work/tools/URLs ─┬─
| P1 foundation | `ux/p1` → `main` `37354f70` | LIVE 2026-10-14 (umtool BUILD_ID LQxTh16Pe…) |
| R1 research | `ux/r1` → `main` `01120bfe` | LIVE 2026-10-14 |
| P3 inbox/work/tools/URLs | `ux/p3` → `main` `01120bfe` | LIVE 2026-10-14 (umtool BUILD_ID q7e29Em…) |
-| P2b jobs + drafts | `ux/p2b` | in progress |
+| P2b jobs + drafts | `ux/p2b` → `main` `44c7b758` | LIVE 2026-10-14 (umtool BUILD_ID J2YDbFuc…) |
| R2 research boards | `ux/r2` | gates green, not merged (record below) |
| P5 create + settings | — | after R2 (consumes the board API) |
-| P4a piece page | — | after P2b |
+| P4a-1 piece frame | `ux/p4a` | in progress |
+| P4a-2, P4a-3 | — | after P4a-1 |
| R3, P4b, P6 | — | after R2 / P4a / all |
### P2a, as shipped
@@ -902,6 +903,132 @@ the article-new memo miss — both fixed in `b7c49fb5`), 6 skipped; **at `b7c49f
- No `.umtool/` state written yet.
- **Inbox on the real reports:** 51 calls waiting, against the old 518 "blocking".
+### P2b, as shipped
+
+**What.** What is running, in the rail, with spend; drafts nobody has reviewed, in the Inbox. Built on P3's rail
+and P2a's inbox engine; no P3 behaviour changed.
+
+- **`askEditor`** (`lib/articles/generation.ts`): a GET is given 5 s and its answer kept 2 s per URL, on globalThis
+ (the promise is kept, so callers asking at once share one request; a refusal is kept as long as an answer). A
+ POST is given 30 s (it may have written by the time it is late), never kept, and drops every kept GET. `fresh`
+ asks again. `EditorError` gains a `reason`: `no-token` (umtool has none, 400), `unreachable` (refused, reset, or
+ no answer in time: 502 / 504), `editor-token` (the editor answered 503: its own WORKER_TOKEN is unset), `denied`
+ (401: the tokens differ), `refused` (its words).
+- **The Running list** (`lib/activity.ts` `readRunning`, `GET /api/running`, `components/shell/RunningList.tsx`):
+ - Source: umtool's own running jobs (a chain and a render may run at once) and the editor's
+ `GET /api/ops/jobs?active=1&limit=200` — no `kind`; the choosing is umtool's.
+ - `lib/running.mjs` (pure, `node --test`): rank 0 generation (`report-draft`, `bench-verdicts`, `tts-file`),
+ rank 1 a research run's acquisition (its job id is a proposal's) or a clip window umtool asked for, rank 2 the
+ rest. Rows: every running job (umtool's own first, then by rank, oldest first), then the queued rank-0/1 jobs,
+ at most 5. The rest folds into one foot line, "+ 2 running · 140 queued · 3 lanes". The lane runners
+ (`auto-download`, `auto-transcribe`, `auto-digest`, `auto-backfill`, `auto-publish`) are never rows: they run as
+ long as the editor does.
+ - A row: the kind in words (common's `jobKindLabel`; umtool's chain is "Make the video", draft-all "Draft
+ everything"), the target (an article's iteration, a channel, a project), queued or running ("queued · 1 ahead"),
+ progress (the editor's snapshot: the runner's `current`, else `initial`, over `target`), and a generation job's
+ spend in Meter. One `JobProgress` presentation (`components/shell/JobProgress.tsx`): the words and a 2 px bar,
+ no bar when a job reports no fraction.
+ - Placing a report draft: the iteration whose `jobId` (or a step's) is the job's, from the article store, kept
+ 10 s and read only when an editor job that is not a lane is live; else the log's first line
+ (`sweep of <article> i<n> on <model>`). Such a row links the article's iterations; any other links the editor's
+ `/jobs`.
+ - Spend: a running draft's log (`~$0.41`, the agent tasks' per-turn line; `GET /api/ops/job/<id>?tail=200`), else
+ the ledger by job id; a chain sums the ledger's rows for its iteration since it started. The label row says the
+ day's total from the ledger ("$0.42 today").
+ - Three sentences, never one: **Editor unreachable**, **Editor's WORKER_TOKEN not set** (503), **Nothing running**
+ (plus **WORKER_TOKEN not set here** and **WORKER_TOKEN does not match the editor's**). The editor's words are
+ the line's tooltip.
+ - Polling: on mount, then every 8 s while the tab is visible, none while hidden, one request at a time. The server
+ renders the last view if it is under 15 s old, else umtool's own jobs and "Asking the editor…" — a page never
+ waits on the editor.
+- **Drafts as decisions** (`lib/inbox.ts`, `lib/inbox/drafts.mjs`): `drafts-unreviewed`, one row per drafted field a
+ final build would refuse for want of an approval (`unreviewed`, or `edited`: changed since approved), from r28's
+ `draftsView()`, for every project with a manifest. Kept per project against `reportSignature`. Group **Review**
+ (ranked after `iteration-ready`), one card per piece ("Narration draft · 5 fields · by qwen3:8b"), action
+ **Review drafts** → `/projects/<p>/review`. `reportSignature` (`lib/projects/report.mjs`) now signs
+ `drafts.review.json`, `narration.review.json` and every `<task>-draft.json` (mtime and size), so an approve —
+ which writes only the review file — refreshes it and the project caches keyed on it.
+- `verdict-proposed` (r28 M8) is not built: M8 waits for the operator's bench bar (`plans/release-28.md`).
+- **The editor stub**: `GET /api/ops/jobs` (the active filter, `limit`) answers the jobs a spec sets through
+ `POST /__stub/ops-jobs {mode, jobs, live}` (no token, the stub's own door) plus its own live drafts unless
+ `live: false`; mode `editor-token` answers 503, `unreachable` drops the socket. A set job's `log` is its
+ `GET /api/ops/job/<id>?tail=N`. The poll is not recorded in the stub's request log.
+
+| Commit | What |
+| --- | --- |
+| `892ae991` | `askEditor` timeout, memo and reasons; `readRunning`, `lib/running.mjs` + tests, `/api/running`, `RunningList`, `JobProgress`; the stub's jobs route |
+| `6ff36c1f` | `drafts-unreviewed` (`lib/inbox/drafts.mjs` + tests, the inbox source, the group rules); `reportSignature` signs the review and draft files; `e2e/running.spec.ts` |
+| `46bc0c84` | a row's percent on the right, its progress words under it |
+| `4c3ddd9b` | running.spec leaves the stub's own drafts out (`live: false`) |
+| `3a33905b` | a drafts card names up to three kinds of field |
+
+**Gates.**
+
+| Gate | Result |
+| --- | --- |
+| repo-wide `tsc --noEmit` | clean at every commit |
+| `pnpm --filter umtool typecheck` | clean |
+| umtool unit (`node --test umtool/lib/*.test.mjs umtool/lib/*/*.test.mjs umtool/report-to-video/*.test.mjs`) | 814 tests, 812 pass, 2 skipped, 0 fail (10 new: `running.test.mjs` 6, `inbox/drafts.test.mjs` 4, the second a `reportSignature` test on a temp dir) |
+| `pnpm --filter umtool test` | 11/11 |
+| `pnpm run test:scripts` (reads the capped build) | 965 tests, 962–963 pass, 2–3 skipped, 0 fail |
+| mcp | 363/363 (not touched) |
+| capped umtool `next build` (corpus linked, `MemoryMax=5G`) | exit 0, compiled 9.6 s, 31.4 s wall, 1.38 GB max RSS; the link removed |
+| full umtool e2e, run 1 (`46bc0c84`) | 390 tests: 382 passed, 2 failed, 6 skipped, 7.6 min. Both reds were `running.spec`: a report draft another spec had left running in the stub was counted (`Running 3`, not 2) — fixed in `4c3ddd9b` (`live: false`); then `running.spec` + `article-iterations.spec` 7/7 |
+| full umtool e2e, run 2 (`3a33905b`) | **390 tests: 384 passed, 0 failed, 6 skipped** (the song-data capability skips), 9.6 min |
+
+`e2e/running.spec.ts` (3): the rail with stub jobs — two lanes, a running draft (its kind, `zeta i7 · 3/12 turns`
+placed by its log, `$0.31` from it, a 25% bar, linking `/articles/zeta?tab=iterations`), a running sync (its
+channel, `2/8 downloads`, 25%, linking the editor's `/jobs`), a queued draft (`queued · 1 ahead`, no bar), three
+queued syncs folded (`+ 3 queued · 2 lanes`), `Running 2`, `$0.42 today`, the API's counts and no token in it;
+"Nothing running" with "1 lane", then the 503 (**Editor's WORKER_TOKEN not set**, the editor's words as the
+tooltip), then a dropped socket (**Editor unreachable**, the day's spend still said); a project with three drafted
+fields written in the spec — three `drafts-unreviewed` rows in Review on the API, one card of 3 on the Inbox,
+**Review drafts** to `/projects/reports/p2b-drafts/review`, three approves there, and the card gone from the Inbox
+and the API on the next read.
+
+**Screenshots** (job scratch `p2b-shots/`): the Inbox and `/tools` at 1366×768, dark and light, on the e2e fixture
+with stub jobs set (a running draft with spend, a sync at 62%, a post walk, a queued draft, three queued jobs and
+three lanes folded) and a five-narration drafts project. Against the canvas's rail foot: the label row with the
+count and "$0.42 today" in Meter, rows of kind and target with the Meter bar, the folded line. The Inbox's Review
+group shows the drafts cards beside the iteration cards.
+
+**The real reports and editor, read-only (offline tsx, a scratch copy of the umtool cache, 2026-10-14).**
+- **Drafts cards today: 0.** The walk finds two projects with draft files: `articles/r28-smoke/i1` has 18 drafted
+ fields, all 18 approved in its `drafts.review.json` (release 28's live smoke); `articles/piratesoftware-ai-friends/i1`
+ has a release-25 `narration-draft.json` and no drafted mark in its manifest. The Review group is the three
+ `iteration-ready` cards it had. `draftsDecisionsAll` 4.2 s cold (every project's signature and manifest), 85 ms warm.
+- **The live editor's `GET /api/ops/jobs?active=1`** (one read-only GET, WORKER_TOKEN from `editor/.env`): 3 jobs,
+ all lane runners (`auto-publish`, `auto-download`, `auto-transcribe`), 624 bytes in 9 ms. The rail would say
+ **Running 0 · $5.73 today** (15 jobs in the ledger today), **Nothing running**, and "3 lanes". `readRunning` 63 ms.
+
+**Found and left.**
+- A running job's spend is known only where the job says it: the agent tasks (sweep, research, the revisions) log
+ `~$x` per turn; a media draft or a narration logs none until it ends, so its row shows no spend while it runs and
+ the ledger has it after. The day's total is the ledger's (finished jobs), so it does not count a running job's.
+- A `report-draft` step queued behind another (a narration, a media draft) is not placed on its article until it
+ starts: no iteration names its job id before then, and a queued job has no log. It links the editor's `/jobs`.
+- The editor's `GET /api/ops/jobs` carries no spec, so a research acquisition is found only by the `jobId` its
+ proposal records in `proposals.json`; a job the editor enqueued for it any other way ranks with the rest.
+- A stub draft another spec leaves running (`article-iterations`' cancel aside, a media draft whose article is
+ deleted mid-run) stays `running` in the stub; specs that count the editor's jobs pass `live: false`.
+- Not touched: `JobProgress` on the project page's chain panel and the Iterations tab's job view (P4b unifies them),
+ `verdict-proposed` (M8 not built).
+- **Follow-up (review, 2026-10-14):** rulings: lanes stay out of the Running count, queued syncs only ever fold, a
+ drafts card counts unreviewed and edited fields. A drafts card is titled by what was drafted ("… · Narration draft
+ · 5 fields", the model under it): a decision may carry its card's `what` (`summarizeGroups` keeps it), else the
+ kind's `WHAT` label (`drafts-unreviewed`: "drafts to review"). Gates: tsc and typecheck clean; unit 814, 0 fail;
+ `running.spec` + `inbox.spec` + `inbox-engine.spec` 20/20 through the umtool e2e entry.
+
+### P2b rollout (orchestrator, 2026-10-14)
+
+Rulings: lane runners stay out of "Running N"; queued syncs only in the "+ N queued" line; a drafts card counts
+unreviewed and changed-since-approved fields, not rejected ones; the card is titled by what was drafted (follow-up
+`bec88600`). Gates on `44c7b758`: repo-wide tsc clean; full umtool e2e 384 passed, 0 failed, 6 skipped (7.2 min);
+test:scripts 965, 962 pass, 0 fail. `main` fast-forwarded to `44c7b758`; umtool built (41 s) and restarted
+(`scripts/p2b-umtool.sh`). Live: `/`, `/work`, `/research`, `/tools` 200; `/api/rail` inbox 53, work 60; decisions API
+828 rows, 0 `drafts-unreviewed` (as predicted), notes' hrefs intact; `/api/running` against the live editor: nothing
+running, "+ 3 lanes", $5.73 today over 15 jobs, editor reachable.
+
### R2, as shipped
**What.** Research boards: a case is a question being researched — its scope, the quotes pinned from Research as
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/app/page.tsx b/umtool/app/page.tsx
@@ -40,6 +40,7 @@ const WHAT: Record<string, string> = {
"research-proposal": "research proposal",
"iteration-failed": "run failed",
"iteration-ready": "iteration ready",
+ "drafts-unreviewed": "drafts to review",
"open-note": "open notes",
"unreadable-notes": "notes.json does not read",
"link-ambiguous": "video not linked",
@@ -103,8 +104,10 @@ function toCard(group: string, c: GroupCard, lifecycle: LifecycleState, muted =
piece: c.piece,
title: c.title,
kind: c.kind,
- what: whatOf(c.kind),
- why: c.why,
+ // A card that names itself (drafts: "Narration draft · 5 fields") is
+ // titled so, and its sentence under it is the rest; else the kind's label.
+ what: c.what ?? whatOf(c.kind),
+ why: c.what && c.why.startsWith(c.what) ? c.why.slice(c.what.length).replace(/^ · /, "") : c.why,
count: c.count,
severity: c.severity,
action: c.action,
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,161 @@
+"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 spend = i.generation && typeof i.spend === "number" ? usd(i.spend) : null;
+ const pct = !queued && typeof i.meter?.fraction === "number" ? `${Math.round(i.meter.fraction * 100)}%` : null;
+ // The right cell: a generation job's spend (Meter), else how far it is, else
+ // where it waits. The words of its progress go on the line under it.
+ const right = spend ? (
+ <span className="font-mono text-[11.5px] font-medium text-meter" data-running-spend={i.spend}>
+ {spend}
+ </span>
+ ) : queued ? (
+ <JobProgressText meter={i.meter} className="font-mono text-[11px] text-muted-2" />
+ ) : pct ? (
+ <span className="font-mono text-[11px] text-muted-2" data-running-pct="">
+ {pct}
+ </span>
+ ) : null;
+ const words = !queued && i.meter?.text ? i.meter : null;
+ const body = (
+ <>
+ <span className={queued ? "truncate text-muted-2" : "truncate"} data-running-kind="">
+ {i.kindLabel ?? i.label}
+ </span>
+ {right ?? <span />}
+ {(i.target || words) && (
+ <small className="col-span-2 truncate font-mono text-[11px] text-muted-2" data-running-target="">
+ {i.target}
+ {i.target && words ? " · " : null}
+ {words && <JobProgressText meter={words} />}
+ </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.meter?.text, 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,19 @@ 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. `live: false` leaves the stub's own
+// drafts out (a "slow" one another spec left running would be counted). `{}`
+// resets to "ok", none, live.
+const opsJobs = { mode: "ok", jobs: [], live: true };
+
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 +630,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 +741,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) => opsJobs.live && (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 +797,17 @@ 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 : [];
+ opsJobs.live = body?.live !== false;
+ return json(res, 200, { ok: true, mode, jobs: opsJobs.jobs.length, live: opsJobs.live });
+ });
+ }
+
const auth = req.headers.authorization ?? "";
if (!TOKEN || auth !== `Bearer ${TOKEN}`) {
req.resume();
diff --git a/umtool/e2e/running.spec.ts b/umtool/e2e/running.spec.ts
@@ -0,0 +1,216 @@
+import { test, expect, type APIRequestContext, type Page } from "@playwright/test";
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs";
+
+// ---------------------------------------------------------------------------
+// P2b: what is running, in the rail, and drafts as decisions in the Inbox.
+//
+// The Running list (components/shell/RunningList.tsx, lib/activity.ts) is
+// umtool's own jobs and the editor's live ones, from the editor stub's
+// `GET /api/ops/jobs?active=1`, which a spec controls through the stub's own
+// door (`POST /__stub/ops-jobs {mode, jobs}`, e2e/fixtures/editor-stub.mjs).
+// The editor's three ways of not answering -- unreachable, its WORKER_TOKEN
+// unset (503), and nothing running -- are three different sentences.
+//
+// The drafts card (lib/inbox.ts, lib/inbox/drafts.mjs) is written here: a
+// project whose fields a model drafted, one card in Review, its action the
+// review page; once every field is approved there, the card is gone on the
+// next read -- the approve writes only drafts.review.json, which
+// reportSignature now signs.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const STUB = `http://127.0.0.1:${portFor("EDITOR_STUB_PORT")}`;
+
+// `live: false`: the stub's own drafts stay out of the list (a "slow" one an
+// earlier spec left running would be counted).
+async function editorJobs(request: APIRequestContext, mode: "ok" | "editor-token" | "unreachable", jobs: Record<string, unknown>[] = [], live = false) {
+ const r = await request.post(`${STUB}/__stub/ops-jobs`, { data: { mode, jobs, live } });
+ expect(r.ok(), await r.text()).toBeTruthy();
+ // Ask again now, so the page's first read is not the 2 s memo of the last test.
+ const fresh = await request.get("/api/running?fresh=1");
+ expect(fresh.ok()).toBeTruthy();
+}
+
+const running = (page: Page) => page.locator("[data-app-rail] [data-rail-section=running]");
+
+test.afterEach(async ({ request }) => {
+ await editorJobs(request, "ok", [], true);
+});
+
+const NOW = Date.now();
+const JOBS = [
+ { id: "e2e-lane-dl", kind: "auto-download", status: "running", queuedAt: NOW - 9e5, startedAt: NOW - 9e5, queueKey: "" },
+ { id: "e2e-lane-tx", kind: "auto-transcribe", status: "running", queuedAt: NOW - 9e5, startedAt: NOW - 9e5, queueKey: "" },
+ {
+ id: "e2e-draft-run",
+ kind: "report-draft",
+ status: "running",
+ queuedAt: NOW - 60_000,
+ startedAt: NOW - 60_000,
+ progress: { metric: "turns", initial: 0, current: 3, target: 12 },
+ log: [
+ "sweep of zeta i7 on claude-sonnet-5-5 (the Claude API, cap $5)",
+ "turn 1: search_transcripts — ~$0.04",
+ "turn 3: get_transcripts — ~$0.31",
+ ],
+ },
+ {
+ id: "e2e-sync",
+ kind: "download-missing",
+ channelSlug: "sitechan",
+ status: "running",
+ queuedAt: NOW - 30_000,
+ startedAt: NOW - 30_000,
+ progress: { metric: "downloads", initial: 2, target: 8 },
+ },
+ { id: "e2e-draft-queued", kind: "report-draft", status: "queued", queuedAt: NOW - 10_000, queue: { key: "draft:api", position: 2, queued: 2 } },
+ { id: "e2e-q1", kind: "download-missing", channelSlug: "otherchan", status: "queued", queuedAt: NOW - 5000, queue: { key: "youtube", position: 1, queued: 3 } },
+ { id: "e2e-q2", kind: "download-missing", channelSlug: "otherchan", status: "queued", queuedAt: NOW - 4000, queue: { key: "youtube", position: 2, queued: 3 } },
+ { id: "e2e-q3", kind: "download-missing", channelSlug: "otherchan", status: "queued", queuedAt: NOW - 3000, queue: { key: "youtube", position: 3, queued: 3 } },
+];
+
+test("the rail lists the editor's running and queued jobs, a draft's spend, and the day's", async ({ page, request }) => {
+ await editorJobs(request, "ok", JOBS);
+ await page.goto("/tools");
+ const r = running(page);
+ await expect(r).toHaveAttribute("data-editor-state", "ok");
+ await expect(r.locator("[data-running-count]")).toHaveAttribute("data-running-count", "2");
+ // The fixture's ledger holds today's $0.42 (iterations-fixture.mjs).
+ await expect(r.locator("[data-today-spend]")).toHaveText("$0.42 today");
+
+ // A running draft: its kind in words, its article (from the log's first
+ // line: no iteration names the job), its live spend in Meter, its turns,
+ // a bar -- and a link to the article's iterations, not the editor.
+ const draft = r.locator("[data-running=e2e-draft-run]");
+ await expect(draft).toHaveAttribute("data-running-state", "running");
+ await expect(draft.locator("[data-running-kind]")).toHaveText("Report draft");
+ await expect(draft.locator("[data-running-spend]")).toHaveText("$0.31");
+ await expect(draft.locator("[data-running-target]")).toHaveText("zeta i7 · 3/12 turns");
+ await expect(draft.locator("[data-job-progress]")).toHaveAttribute("data-job-progress", "25");
+ await expect(draft.locator("a")).toHaveAttribute("href", "/articles/zeta?tab=iterations");
+
+ // A sync: its channel, its count; it has no piece, so it links the editor's /jobs.
+ const sync = r.locator("[data-running=e2e-sync]");
+ await expect(sync.locator("[data-running-kind]")).toHaveText("Download missing");
+ await expect(sync.locator("[data-running-target]")).toHaveText("sitechan · 2/8 downloads");
+ await expect(sync.locator("[data-job-progress-text]")).toHaveText("2/8 downloads");
+ await expect(sync.locator("[data-running-pct]")).toHaveText("25%");
+ await expect(sync.locator("a")).toHaveAttribute("href", `${STUB}/jobs`);
+
+ // A queued draft is a row, said as queued; queued syncs and the lanes fold.
+ const queued = r.locator("[data-running=e2e-draft-queued]");
+ await expect(queued).toHaveAttribute("data-running-state", "queued");
+ await expect(queued.locator("[data-job-progress-text]")).toHaveText("queued · 1 ahead");
+ await expect(queued.locator("[data-job-progress]")).toHaveCount(0);
+ await expect(queued.locator("[data-running-target]")).toHaveCount(0);
+ await expect(r.locator("[data-running=e2e-q1]")).toHaveCount(0);
+ await expect(r.locator("[data-running=e2e-lane-dl]")).toHaveCount(0);
+ await expect(r.locator("[data-running-more]")).toHaveText("+ 3 queued · 2 lanes");
+ await expect(r.locator("[data-running-more]")).toHaveAttribute("href", `${STUB}/jobs`);
+ // Rows in order: running (generation first), then the queued draft.
+ await expect(r.locator("[data-running]")).toHaveCount(3);
+ expect(await r.locator("[data-running]").evaluateAll((els) => els.map((e) => e.getAttribute("data-running")))).toEqual([
+ "e2e-draft-run",
+ "e2e-sync",
+ "e2e-draft-queued",
+ ]);
+ await expect(r.locator("[data-running-empty], [data-running-editor]")).toHaveCount(0);
+
+ // The API says the same, with no tokens in it.
+ const api = await (await request.get("/api/running")).json();
+ expect(api.running).toBe(2);
+ expect(api.queued).toBe(4);
+ expect(api.more).toMatchObject({ running: 0, queued: 3, lanes: 2 });
+ expect(JSON.stringify(api)).not.toContain("umtool-e2e-token");
+});
+
+test("nothing running, the editor's token unset, and an editor that does not answer are three sentences", async ({ page, request }) => {
+ await editorJobs(request, "ok", [{ id: "e2e-lane-only", kind: "auto-publish", status: "running", queuedAt: NOW, startedAt: NOW }]);
+ await page.goto("/tools");
+ const r = running(page);
+ await expect(r).toHaveAttribute("data-editor-state", "ok");
+ await expect(r.locator("[data-running-empty]")).toHaveText("Nothing running");
+ await expect(r.locator("[data-running-more]")).toHaveText("1 lane");
+ await expect(r.locator("[data-running-count]")).toHaveAttribute("data-running-count", "0");
+
+ await editorJobs(request, "editor-token");
+ await page.reload();
+ await expect(r).toHaveAttribute("data-editor-state", "editor-token");
+ await expect(r.locator("[data-running-editor]")).toHaveText("Editor's WORKER_TOKEN not set");
+ await expect(r.locator("[data-running-editor]")).toHaveAttribute("title", /worker endpoint disabled/);
+ await expect(r.locator("[data-running-empty]")).toHaveCount(0);
+
+ await editorJobs(request, "unreachable");
+ await page.reload();
+ await expect(r).toHaveAttribute("data-editor-state", "unreachable");
+ await expect(r.locator("[data-running-editor]")).toHaveText("Editor unreachable");
+ await expect(r.locator("[data-running-empty]")).toHaveCount(0);
+ // The day's spend is the ledger's: it is said whatever the editor does.
+ await expect(r.locator("[data-today-spend]")).toHaveText("$0.42 today");
+});
+
+// ─── Drafts as decisions ────────────────────────────────────────────────────
+
+const DRAFTS = "reports/p2b-drafts";
+const DRAFTS_DIR = path.join(FIXTURE, "reports", "p2b-drafts");
+const P = (task: string, model = "qwen3:8b") => ({ task, model, at: "2026-10-14T10:00:00.000Z", iteration: 1, attempt: 1 });
+
+test.describe("drafts in the Inbox", () => {
+ test.beforeAll(() => {
+ // The build fixture's manifest as the template (nothing rewrites it), with a
+ // timeline of three drafted fields: one on-screen text, two narrations.
+ const template = JSON.parse(readFileSync(path.join(FIXTURE, "reports", "draft-review-build-fixture", "video.manifest.json"), "utf8"));
+ const manifest = {
+ ...template,
+ slug: "p2b-drafts",
+ title: "The P2b Drafts Fixture",
+ timeline: [
+ { type: "clip", id: "c01", video: "vid1", start: 3.0, end: 6.0, cite: 3, section: 0, lock: true, quote: "and because", onscreen: { title: "A drafted title" }, drafted: { onscreen: P("onscreen") } },
+ { type: "card", id: "k01", style: "chapter", seconds: "auto", heading: "One", narration: { text: "The first line." }, drafted: { narration: P("narrate") } },
+ { type: "card", id: "k02", style: "chapter", seconds: "auto", heading: "Two", narration: { text: "The second line." }, drafted: { narration: P("narrate") } },
+ ],
+ };
+ rmSync(DRAFTS_DIR, { recursive: true, force: true });
+ mkdirSync(DRAFTS_DIR, { recursive: true });
+ writeFileSync(path.join(DRAFTS_DIR, "video.manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
+ });
+ test.afterAll(() => {
+ rmSync(DRAFTS_DIR, { recursive: true, force: true });
+ });
+
+ test("a cut with unreviewed drafts is one Review card; approving them on the review page clears it", async ({ page, request }) => {
+ // The API: one row per drafted field, in Review, the action the review page.
+ const rows = ((await (await request.get("/api/browse/decisions")).json()) as {
+ items: { kind: string; project: string; group: string; target: string; action: { label: string; href: string } }[];
+ }).items.filter((d) => d.kind === "drafts-unreviewed" && d.project === DRAFTS);
+ expect(rows.map((d) => d.target).sort()).toEqual(["narrate/k01/narration", "narrate/k02/narration", "onscreen/c01/onscreen"]);
+ expect(rows.every((d) => d.group === "review")).toBe(true);
+ expect(rows[0].action).toEqual({ label: "Review drafts", href: `/projects/${DRAFTS}/review` });
+
+ await page.goto("/");
+ const card = page.locator("[data-group=review] [data-card=drafts-unreviewed]").filter({ hasText: "The P2b Drafts Fixture" });
+ await expect(card).toHaveCount(1);
+ await expect(card.locator("[data-count]")).toHaveText("3");
+ // Titled like the canvas: the piece, then what was drafted and how many; who drafted it under that.
+ await expect(card.locator("[data-card-title]")).toHaveText("The P2b Drafts Fixture · On-screen text and narration drafts · 3 fields");
+ await expect(card.locator("small")).toHaveText("by qwen3:8b");
+ await card.locator("[data-action-link]").click();
+ await expect(page).toHaveURL(new RegExp(`/projects/${DRAFTS}/review$`));
+
+ for (const address of ["onscreen/c01/onscreen", "narrate/k01/narration", "narrate/k02/narration"]) {
+ const row = page.locator(`[data-draft-row="${address}"]`);
+ await row.locator('[data-draft-action="approve"]').click();
+ await expect(row).toHaveAttribute("data-state", "approved");
+ }
+
+ // Only drafts.review.json was written; the card is gone on the next read.
+ await page.goto("/");
+ await expect(page.locator("[data-group=review] [data-card=drafts-unreviewed]").filter({ hasText: "The P2b Drafts Fixture" })).toHaveCount(0);
+ const after = ((await (await request.get("/api/browse/decisions")).json()) as { items: { kind: string; project: string }[] }).items;
+ expect(after.filter((d) => d.kind === "drafts-unreviewed" && d.project === DRAFTS)).toEqual([]);
+ });
+});
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/inbox.ts b/umtool/lib/inbox.ts
@@ -5,7 +5,11 @@ import { ARTICLES_KEY } from "./paths";
import { readArticleIterations, type IterationRow } from "./articles/generation";
import { sitesPaths } from "./articles/sites";
import { decisionsForSong, type Decision } from "./decisions";
-import { openDecisions } from "./projects";
+import { openDecisions, projectRefs, summariseProject, type ProjectRef } from "./projects";
+import { readManifest, reportSignature } from "./projects/report.mjs";
+import { draftsView } from "./report/drafts.mjs";
+import { reviewHref } from "./hrefs";
+import { draftsDecisions } from "./inbox/drafts.mjs";
import { pieceOfDecision, readPieceGraph, type Piece, type PieceGraph } from "./pieces";
import { lifecycleOf, readLifecycle, type LifecycleRead } from "./lifecycle";
import { isMuted, readMutes } from "./mutes";
@@ -26,14 +30,19 @@ import { GROUPS, annotate, rankDecisions, summarizeGroups } from "./inbox/groups
// link-ambiguous an article whose video only a slug suggests
// looks-done a piece every signal says is finished (a suggestion:
// it never sets the lifecycle)
+// drafts-unreviewed a report cut's field a model drafted that nobody has
+// reviewed (r28's draftsView; lib/inbox/drafts.mjs), one
+// row per field, kept per project against
+// reportSignature -- which signs the review files, so an
+// approve drops the card on the next read
//
// -- each row given its piece, category, group, one action, lifecycle and
// `hidden` (lib/inbox/groups.mjs), ranked. One row per decision, never dropped:
// the MCP reads `items[]` (mcp/src/archivalTools.ts).
//
// No editor call anywhere here: there is no "waiting on a cap" state (the daily
-// cap refuses at start, a per-job cap ends the run), and running jobs are
-// P2b's.
+// cap refuses at start, a per-job cap ends the run), and running jobs are the
+// rail's (lib/activity.ts readRunning).
//
// SERVER ONLY.
// ---------------------------------------------------------------------------
@@ -46,6 +55,8 @@ export type GroupCard = {
severity: Decision["severity"];
count: number;
why: string;
+ /** The card's own title when its decisions name one (drafts), else null: the page labels it by kind. */
+ what: string | null;
action: { label: string; href: string };
at: number;
};
@@ -218,11 +229,48 @@ async function spendByJob(): Promise<Map<string, number>> {
return out;
}
-/** The decisions read from disk beside openDecisions(): iterations, research, links, looks-done. */
+// One project's drafts decisions, kept against its reportSignature (on
+// globalThis: one cache per process, not per Next bundle).
+type DraftsMemo = Map<string, { sig: string; value: Decision[] }>;
+const gd = globalThis as typeof globalThis & { __umtoolDraftsMemo?: DraftsMemo };
+const draftsMemo: DraftsMemo = (gd.__umtoolDraftsMemo ??= new Map());
+
+async function projectDrafts(ref: ProjectRef): Promise<Decision[]> {
+ const sig = String(await reportSignature(ref.dir));
+ const hit = draftsMemo.get(ref.id);
+ if (hit && hit.sig === sig) return hit.value;
+ let value: Decision[] = [];
+ const manifest = await readManifest(ref.dir);
+ if (manifest) {
+ const view = await draftsView(ref.dir, manifest);
+ if (view.rows.some((r) => r.drafted && (r.state === "unreviewed" || r.state === "edited"))) {
+ const title = (await summariseProject(ref)).title;
+ // When: the manifest's mtime (reportSignature's first field) -- a draft is written there.
+ const at = Number(sig.split(":")[0]) || Date.now();
+ value = draftsDecisions({ project: ref.id, projectTitle: title, href: reviewHref(ref.id), at, view }).map((d) => ({
+ ...d,
+ projectKind: ref.kind,
+ })) as Decision[];
+ }
+ }
+ draftsMemo.set(ref.id, { sig, value });
+ return value;
+}
+
+/** Every project's unreviewed drafts. A project that cannot be read adds nothing. */
+export async function draftsDecisionsAll(): Promise<Decision[]> {
+ const refs = await projectRefs();
+ const live = new Set(refs.map((r) => r.id));
+ for (const id of draftsMemo.keys()) if (!live.has(id)) draftsMemo.delete(id);
+ const per = await Promise.all(refs.map((r) => projectDrafts(r).catch(() => [] as Decision[])));
+ return per.flat();
+}
+
+/** The decisions read from disk beside openDecisions(): iterations, research, links, looks-done, drafts. */
export async function diskDecisions(graph: PieceGraph, life: LifecycleRead): Promise<Decision[]> {
- const spend = await spendByJob();
+ const [spend, drafts] = await Promise.all([spendByJob(), draftsDecisionsAll().catch(() => [] as Decision[])]);
const perArticle = await Promise.all(storeArticles(graph).map((p) => iterationDecisions(p, spend)));
- return [...perArticle.flat(), ...pieceDecisions(graph, life)];
+ return [...perArticle.flat(), ...pieceDecisions(graph, life), ...drafts];
}
/**
diff --git a/umtool/lib/inbox/drafts.mjs b/umtool/lib/inbox/drafts.mjs
@@ -0,0 +1,69 @@
+// DRAFTS AS DECISIONS (plans/umtool-redesign.md, P2b): a report project whose
+// fields a model drafted and nobody has reviewed is a call in the Inbox's
+// Review group -- one row per field (the API keeps one row per decision), one
+// card per piece ("narration draft · 5 fields"), its action the project's
+// review page. Pure: lib/inbox.ts reads r28's draftsView() and hands its rows
+// here.
+//
+// "Not yet reviewed" is what a final build would refuse for want of an
+// approval: `unreviewed` (never judged) and `edited` (judged, then the field
+// changed under the verdict). A rejected draft is a ruling already made.
+
+/** The review states that wait on the operator. */
+export const WAITING = new Set(["unreviewed", "edited"]);
+
+/**
+ * What a drafts card is about, the canvas's card title: which kinds of field
+ * and how many ("Narration draft · 5 fields").
+ *
+ * @param {{ label: string }[]} rows the waiting rows
+ */
+export function draftsWhat(rows) {
+ const labels = [...new Set(rows.map((r) => r.label))];
+ const named = labels.length <= 3 ? labels : [...labels.slice(0, 2), `${labels.length - 2} more`];
+ const list = named.length === 1 ? named[0] : `${named.slice(0, -1).join(", ")} and ${named[named.length - 1]}`;
+ const head = `${list} draft${labels.length === 1 ? "" : "s"}`;
+ const n = rows.length;
+ return `${head[0].toUpperCase()}${head.slice(1)} · ${n} field${n === 1 ? "" : "s"}`;
+}
+
+/**
+ * The card's whole sentence: what (draftsWhat), who drafted it, and how many
+ * changed since they were approved. The API row's `why`; the Inbox shows the
+ * `what` as the card's title and the rest under it.
+ *
+ * @param {{ label: string, state: string, drafted: { model?: string } | null }[]} rows the waiting rows
+ */
+export function draftsWhy(rows) {
+ const models = [...new Set(rows.map((r) => r.drafted?.model).filter(Boolean))];
+ const edited = rows.filter((r) => r.state === "edited").length;
+ return [draftsWhat(rows), models.length ? `by ${models.join(", ")}` : null, edited ? `${edited} changed since approved` : null]
+ .filter(Boolean)
+ .join(" · ");
+}
+
+/**
+ * The `drafts-unreviewed` rows of one project.
+ *
+ * @param {{
+ * project: string, projectTitle: string, href: string, at: number,
+ * view: { rows: { address: string, label: string, state: string, drafted: { model?: string } | null }[] },
+ * }} o
+ */
+export function draftsDecisions({ project, projectTitle, href, at, view }) {
+ const waiting = (view?.rows ?? []).filter((r) => r.drafted && WAITING.has(r.state));
+ if (!waiting.length) return [];
+ const what = draftsWhat(waiting);
+ const why = draftsWhy(waiting);
+ return waiting.map((r) => ({
+ project,
+ projectTitle,
+ kind: "drafts-unreviewed",
+ target: r.address,
+ what,
+ why,
+ href,
+ severity: "open",
+ at,
+ }));
+}
diff --git a/umtool/lib/inbox/drafts.test.mjs b/umtool/lib/inbox/drafts.test.mjs
@@ -0,0 +1,86 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, rm, writeFile, utimes } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { draftsDecisions, draftsWhy } from "./drafts.mjs";
+import { annotate, summarizeGroups } from "./groups.mjs";
+import { reportSignature } from "../projects/report.mjs";
+
+const row = (address, label, state, model = "qwen3:8b") => ({ address, label, state, drafted: { model } });
+
+test("one row per waiting field; approved, rejected and the operator's own are not waiting", () => {
+ const view = {
+ rows: [
+ row("narrate/k01/narration", "narration", "unreviewed"),
+ row("narrate/k02/narration", "narration", "edited"),
+ row("onscreen/c02/onscreen", "on-screen text", "approved"),
+ row("teaser/t01/lines", "teaser lines", "rejected"),
+ { address: "narrate/k03/narration", label: "narration", state: "unreviewed", drafted: null },
+ ],
+ };
+ const out = draftsDecisions({ project: "reports/x", projectTitle: "X", href: "/projects/reports/x/review", at: 5, view });
+ assert.deepEqual(out.map((d) => d.target), ["narrate/k01/narration", "narrate/k02/narration"]);
+ assert.ok(out.every((d) => d.kind === "drafts-unreviewed" && d.severity === "open" && d.href === "/projects/reports/x/review"));
+ assert.equal(out[0].why, "Narration draft · 2 fields · by qwen3:8b · 1 changed since approved");
+ assert.equal(out[0].what, "Narration draft · 2 fields");
+ assert.deepEqual(draftsDecisions({ project: "p", projectTitle: "p", href: "/", at: 0, view: { rows: [row("a", "narration", "approved")] } }), []);
+});
+
+test("the sentence names the kinds of field and the models", () => {
+ assert.equal(draftsWhy([row("a", "narration", "unreviewed")]), "Narration draft · 1 field · by qwen3:8b");
+ assert.equal(
+ draftsWhy([row("a", "narration", "unreviewed"), row("b", "on-screen text", "unreviewed", "claude-sonnet-5-5")]),
+ "Narration and on-screen text drafts · 2 fields · by qwen3:8b, claude-sonnet-5-5",
+ );
+ assert.equal(
+ draftsWhy([row("a", "narration", "unreviewed"), row("b", "teaser lines", "unreviewed"), row("c", "flips", "unreviewed")]),
+ "Narration, teaser lines and flips drafts · 3 fields · by qwen3:8b",
+ );
+ assert.equal(
+ draftsWhy([row("a", "narration", "unreviewed"), row("b", "teaser lines", "unreviewed"), row("c", "flips", "unreviewed"), row("d", "threads", "unreviewed")]),
+ "Narration, teaser lines and 2 more drafts · 4 fields · by qwen3:8b",
+ );
+});
+
+test("drafts are Review calls: one card per piece, the action Review drafts", () => {
+ const view = { rows: [row("narrate/k01/narration", "narration", "unreviewed"), row("narrate/k02/narration", "narration", "unreviewed")] };
+ const rows = annotate(draftsDecisions({ project: "reports/x", projectTitle: "X", href: "/projects/reports/x/review", at: 1, view }), {
+ pieceOf: () => "p:reports/x",
+ lifecycleOf: () => "active",
+ });
+ assert.ok(rows.every((d) => d.group === "review" && d.category === "review"));
+ assert.deepEqual(rows[0].action, { label: "Review drafts", href: "/projects/reports/x/review" });
+ const review = summarizeGroups(rows).find((g) => g.id === "review");
+ assert.equal(review.cards.length, 1);
+ assert.equal(review.cards[0].count, 2);
+ // The card names itself: its title is the drafts' what, not the kind.
+ assert.equal(review.cards[0].what, "Narration draft · 2 fields");
+});
+
+test("reportSignature moves when a review or a draft file is written, not only the manifest", async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "umtool-sig-"));
+ try {
+ await writeFile(path.join(dir, "video.manifest.json"), "{}\n");
+ const a = await reportSignature(dir);
+ await writeFile(path.join(dir, "drafts.review.json"), '{"rows":{}}\n');
+ const b = await reportSignature(dir);
+ assert.notEqual(b, a, "drafts.review.json");
+ await writeFile(path.join(dir, "narration.review.json"), "{}\n");
+ const c = await reportSignature(dir);
+ assert.notEqual(c, b, "narration.review.json");
+ await writeFile(path.join(dir, "onscreen-draft.json"), "{}\n");
+ const d = await reportSignature(dir);
+ assert.notEqual(d, c, "a <task>-draft.json");
+ // A rewrite of the same size is still seen: the mtime is signed.
+ const later = new Date(Date.now() + 5000);
+ await utimes(path.join(dir, "drafts.review.json"), later, later);
+ assert.notEqual(await reportSignature(dir), d, "the review's mtime");
+ // A file that only looks like one is not signed.
+ const e = await reportSignature(dir);
+ await writeFile(path.join(dir, "notes-draft.txt"), "x");
+ assert.equal(await reportSignature(dir), e);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs
@@ -8,8 +8,8 @@
//
// your-call research proposals, then failed runs: money is waiting
// on a yes or no ("spend")
-// review a finished iteration that is not current (r28's drafts
-// join here in P2b)
+// review a finished iteration that is not current; a cut whose
+// drafted fields nobody has reviewed (r28's drafts, P2b)
// blocking something downstream would lie, on an ACTIVE piece
// notes the operator's open notes
// open every other open decision (a variant with no verdict, a
@@ -43,6 +43,7 @@ const KIND_CATEGORY = {
"research-proposal": "spend",
"iteration-failed": "spend",
"iteration-ready": "review",
+ "drafts-unreviewed": "review",
"open-note": "note",
"unreadable-notes": "fix",
"link-ambiguous": "choose",
@@ -75,7 +76,7 @@ export function groupOf(d) {
// Within a group: the brief's order first (proposals before failed runs), then
// everything else as equals.
-const KIND_RANK = { "research-proposal": 0, "iteration-failed": 1, "iteration-ready": 0, "unreadable-notes": 0 };
+const KIND_RANK = { "research-proposal": 0, "iteration-failed": 1, "iteration-ready": 0, "drafts-unreviewed": 1, "unreadable-notes": 0 };
const SEVERITY_RANK = { blocking: 0, open: 1, info: 2 };
// ONE primary action per decision, its button copy naming the result.
@@ -83,6 +84,7 @@ const ACTION_LABEL = {
"research-proposal": "Approve acquisition",
"iteration-failed": "Retry run",
"iteration-ready": (d) => `Make ${d.target} current`,
+ "drafts-unreviewed": "Review drafts",
"open-note": "Answer note",
"unreadable-notes": "Repair notes.json",
"link-ambiguous": "Link the video",
@@ -215,6 +217,9 @@ export function summarizeGroups(items) {
severity: d.severity,
count: 0,
why: d.why,
+ // A decision that names its own card title (drafts: "Narration draft ·
+ // 5 fields"); else the page labels the card by its kind.
+ what: d.what ?? null,
action: d.action ?? actionOf(d),
at: d.at ?? 0,
};
diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs
@@ -19,6 +19,7 @@ import { deliverablesState, finishCommand, outDirState, leftoversOf } from "../r
import { CHANNELS_DIR, inside } from "../paths.mjs";
import { channelName, cleanTitle } from "umtool-report-to-video/attribution";
import { teaserTitle } from "umtool-report-to-video/deck";
+import { DRAFTS_REVIEW_FILE, NARRATION_REVIEW_FILE } from "umtool-report-to-video/drafts-review";
/**
* Where a build's per-entry segments live.
@@ -489,9 +490,22 @@ export async function buildStateOf(dir, manifest) {
};
}
-/** The signature the summary and the decisions are cached against. */
+/** A task's draft file beside the manifest (lib/report/drafts.mjs DRAFT_FILE_RE). */
+const DRAFT_FILE = /^[a-z0-9][a-z0-9-]{0,62}-draft\.json$/;
+
+/**
+ * The signature the summary and the decisions are cached against.
+ *
+ * It signs the drafts review too (release 28; P2b): `drafts.review.json`,
+ * release 25's `narration.review.json` and every `<task>-draft.json`. An
+ * approve on the review page writes only the first, never the manifest -- so
+ * without them a cache keyed on this would keep a card for drafts that were
+ * approved a minute ago.
+ */
export async function reportSignature(dir) {
- const [man, out, avail, rev] = await Promise.all([
+ const names = await readdir(dir).catch(() => []);
+ const drafts = names.filter((n) => DRAFT_FILE.test(n)).sort();
+ const [man, out, avail, rev, review, narration, ...draftStats] = await Promise.all([
stat0(manifestPath(dir)),
stat0(path.join(dir, "out")),
// Rewritten IN PLACE by every preflight, which leaves out/'s own mtime
@@ -499,13 +513,20 @@ export async function reportSignature(dir) {
// never reach the index.
stat0(path.join(dir, "out", "availability.json")),
stat0(path.join(dir, "revisions")),
+ stat0(path.join(dir, DRAFTS_REVIEW_FILE)),
+ stat0(path.join(dir, NARRATION_REVIEW_FILE)),
+ ...drafts.map((n) => stat0(path.join(dir, n))),
]);
+ const signed = (s) => `${Math.round(s?.mtimeMs ?? 0)}.${s?.size ?? 0}`;
return [
Math.round(man?.mtimeMs ?? 0),
man?.size ?? 0,
Math.round(out?.mtimeMs ?? 0),
Math.round(avail?.mtimeMs ?? 0),
Math.round(rev?.mtimeMs ?? 0),
+ signed(review),
+ signed(narration),
+ drafts.map((n, i) => `${n}@${signed(draftStats[i])}`).join(","),
].join(":");
}
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);
+});