commit ed8b67ed00cf8c652a9bd5ed95230fe6d0dd44c5
parent 1a2097e4433f6c2cfcb412b18aff79285b7a032a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 12:03:19 -0400
Merge main (P4b live, 651b36e5) into ux/r5
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
52 files changed, 3301 insertions(+), 1123 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,10 @@
# Changelog
## [Unreleased]
+- **umtool's benches are one shell.** The clip bench, the claim bench, the narration script, the takes and the drafts review share one frame that fits 1366×768 with no rail: a top bar (← the piece, which bench, **N of M**, ‹ prev / next ›, the keys), the work, a **verdict bar** asking ONE question with its consequence before you choose, and the source on the reader at the right. On the clip bench the transcript is the reader — the cited cue lit, its cite thread, **Copy citation**, **Play clip** — and a clip that ends mid-sentence asks "Extend c04 to the end of the sentence? It would end at 4:31:21 (+12.1 s), covering all of c05." with **Extend to 4:31:21** (or **Fetch to …** past what is fetched) and **Keep the cut here** (lockEnd) before the walk's **Yes, confirmed** / **No, note what is wrong**. The claim bench's context is its reader (`j`/`k` move the lit cue and seek the player) and **Save ruling** its verdict bar, saying what is still missing. Narration asks about the card in hand (`j`/`k`, `a` approve, `r` reject with its note); takes about the take being listened to (`n`/`p`, `l` like, `m` maybe, `x` no). Needs a restart of umtool.
+- **A report video's Media tab is one surface for every drafted field.** Each field is a line — its words, **where it came from** (the draft file, when, by what model, which attempt was kept, and the rule a refused attempt broke: "attempt 2 of 2 chosen · attempt 1 failed: ✕ text in quotation marks"), its review — with **Approve draft** and **Reject** (a note), the drafts kept aside with **Use this**, grouped by section (cut, on-screen, teaser, flips, threads, narration, YouTube), each headed by its **Draft with <model>**; **Approve all N**, **Draft everything** (the draft-all chain, on the model chosen) and section chips above. `j`/`k` light a field, `a` approves it, `r` rejects it. The on-screen panel moved here from Build, whole. A release-25 narration (no mark in the manifest) shows its `narration-draft.json` attempts too. Needs a restart of umtool.
+- **The drafts review is a bench: `/projects/<p>/review`.** The same field list, walked one field at a time: the verdict bar asks about the lit field ("Approve the drafted on-screen text of m01? A final build refuses it until it is approved."), the reader shows the clip it is drawn over with its cited cue lit. The Iterations tab's **Narrate**, media drafts and **Draft everything** are now a **Media drafts →** link to the iteration's video's Media tab.
+- **One job progress for chains, builds and editor jobs.** The state in words, the current step, a Meter bar and the spend so far, the step list, the log and **Cancel** where the job allows it — on the Media tab's drafts and Draft everything, the Build tab's build, the Iterations tab's jobs and the rail's Running rows.
- **umtool has Create: `/create`, "What are you making?"** One list of lines — Research a question · an article from a question or from a board · a video from an article, a board, a recording or a sweep report · a song — each opening its form under it, each a shell over a writer that already existed: a case (the board opens), a sweep (r27's new-article form, with the **estimate** said before Start: what earlier runs on that model spent, from the usage ledger, and the cap it stops at), a board's hand-off (its plan, then the confirm), the video chain over an article's iteration (its steps listed first), a project from a recording or a report on disk, a song. Keys: `j`/`k` the lines, Enter opens a form on its first field, Escape closes it back to the line. The policy is a chip — "Generation: balanced · Claude Code: sweeps · API: report revisions, research · local: video revisions, drafts" — linking Settings. The rail's **+ Create** is a link to it, ⌘K's create actions open its lines (`/create?make=…`), and Work has one **+ Create**. Needs a restart of umtool.
- **The editor's "Make a video" lands on Create.** `/?from=<channel>/<id>` (VideoPanel, VideoNavStrip) now redirects to `/create?from=…`, which opens "Video from a recording" prefilled; `/articles/new` redirects to `/create?make=article`. The Inbox no longer carries the new-project form.
- **Settings · generation, `/settings/generation`.** The generation policy — routes per task, the presets, the models (the extractor among them), the caps, whether the API key's file is there (its path, never the key) — moved here from the new-article form, written through the editor's settings action as before; beside it the day's API spend job by job (task, article and iteration, the models, what it cost) and the last seven days, from the editor's usage ledger.
diff --git a/plans/umtool-redesign.md b/plans/umtool-redesign.md
@@ -438,7 +438,7 @@ edition reviewed with the operator before the schedule is left on.
| P4a-2 article-rooted merge | `ux/p4a2` → `main` `d84cf4d7` | LIVE 2026-10-14 (umtool UFg8z3yd…) |
| P4a-3 song pieces | `ux/p4a3` → `main` `3d69d6c6` | LIVE 2026-10-14 (umtool oN73I6F3…) |
| R3 transparent runs | `ux/r3` → `main` `6362cf40` | LIVE 2026-10-14 (editor HqcZW4aJ…, umtool 85Ultdj2…) |
-| P4b benches + Media | `ux/p4b` | in progress |
+| P4b benches + Media | `ux/p4b` → `main` `e66dd702` | LIVE 2026-10-14 (umtool ktVxkFBl…) |
| R4 refresh | `ux/r4` | in progress |
| R5 recurring reports | — | after R4 |
| R6 triage first | — | after R5 |
@@ -2172,3 +2172,190 @@ passed, 0 failed, 6 skipped (10.9 min); test:scripts 999 pass, 0 fail; capped bu
P6 audit: a cut card links `/projects/<song id>/<cut>` (the short id) while the song's page is the full path — both
resolve; P6 picks one canonical address. The ochre `OPEN` chips on a song's decisions are a verdict colour on a state.
+### P4b, as shipped
+
+**What.** The human-piloted walks are one bench shell, a report video's drafted fields are one Media surface, and
+every job umtool shows is one `JobProgress`. Built on P4a-2's piece frame (`ux/p4a2` `d84cf4d7`); no URL moved.
+
+- **The bench shell** (`components/projects/bench/BenchShell.tsx`, no hooks, server- and client-safe):
+ - `BenchFrame` (the viewport; below `lg` one scrolling column), `BenchTop` (canvas `.benchtop`, one row: the mark
+ linking home, a Breadcrumb nav — "projects /" from `xl`, **← the piece** (`data-bench-back`, its Cut, Media or
+ Overview through `pieceHrefOfProject`), the bench's place — the bench's kind (`data-bench-kind`), **N of M**
+ (`data-bench-pos`), ‹ prev / next › (`data-bench-nav`, a bench's own attributes kept: the clip bench's
+ `data-clip-nav`), the key legend (`data-bench-keys`) and the status `.micro`; it IS the head:
+ `data-app-header="bench"`); `BenchBody` (the work column with the verdict bar at its foot, the reader on the
+ right at `minmax(320px, 28%)`); `VerdictBar` (canvas `.verdictbar`: the question, the consequence in bold
+ (`data-verdict-question`, `data-verdict-consequence`), the actions).
+ - **Clip** (`ClipBench` keeps its internals; its return is re-laid onto the shell): the transcript pane is the
+ reader (`ReaderPane`: the source, channel · date · transcript length, the cite thread, the same cue rows — click
+ to play, dimmed to fetch, peek further — with the **cited cue lit** until something plays, **Copy citation** in
+ the house format, **Play clip**, the window file as fine print). The verdict bar asks ONE question: a clip that
+ ends mid-sentence (and is not locked) asks "Extend c04 to the end of the sentence?" with what it would do
+ ("It would end at 0:09.00 (+3.0 s), covering all of s02." — a sibling inside the extension is *covered*, one
+ across its end *overlapped*, past the cache "past what is fetched"), **Extend to m:ss** (saves the window) or
+ **Fetch to m:ss**, and **Keep the cut here** (lockEnd); otherwise "Is c04 what the report says it is?" with what
+ a confirmation does. **Yes, confirmed** / **No, note what is wrong** (`y`/`x`) are always there; the filled one
+ is the question's first action. The position and prev/next moved to the top bar; the picture column scrolls on
+ its own before the picture drops under 200 px; the answer column is 20–23 rem.
+ - **Claim**: the ±90 s context is the reader (cues as a lit list, `j`/`k` from anywhere, the cue the cite starts
+ in lit, a light seeks the player), **Save ruling** is the verdict bar's action with what is missing ("it stays
+ blocking") or that every field is set; "as recorded" stays under the player.
+ - **Narration**: the verdict bar asks about the card in hand (focused, else the first not approved): **Approve**
+ (`a`) its words as saved, **Reject with a note** (`r`, the cursor to its note); `j`/`k` move between cards (the
+ card in hand wears the Signal edge).
+ - **Takes**: about the take being listened to — "Is <take> the take for <group>?" — **Like / Maybe / No** (`l`,
+ `m`, `x`), `n`/`p` move the listening; "0 of 4 judged, 4 to go".
+ - **Review**: below.
+- **`ReaderPane`, additive** (P1's primitive): `bodyProps` (a handle and a ref on the scrolling body), `bare`
+ (children without the reader-text column), `onLight`, `global` (j/k from anywhere), a cue's `attrs`.
+- **The Media tab** (`components/projects/MediaDrafts.tsx`; `report/MediaTab.tsx` reads; canvas "Piece · Media"):
+ - every field `draftsView()` lists — the drafted ones and a narration written by hand — as ONE lit list grouped
+ by its section (the address's task: cut, on-screen, teaser, flips, threads, narration, YouTube), each line
+ `data-draft-row` with its words, its **provenance** (`lib/report/draft-provenance.mjs`, unit-tested: the draft
+ file, when, by what model, "attempt 2 of 2 chosen", each refused attempt's `hard` rules in the reject colour,
+ soft flags, "repaired" when narrate's repair made the value, its review state), **Approve draft** / **Reject**
+ with the note (`data-draft-action`, toggling as r28's did), the alternatives with **Use this**; a field that is
+ the operator's with a draft kept aside is its own line;
+ - release 25's `narration-draft.json` (units at the top level, keyed by card id, no model) is read as well as
+ release 28's `units[].target`; two files claiming one field: the one the mark's task wrote;
+ - each section is headed by what it writes, what it holds and its **Draft with <model>** (`DraftPanel.tsx`'s
+ `DraftControl`: the button, the model, force, the entries, the job on `EditorJobProgress`, the last run) — only
+ on a project made from a done iteration; otherwise the line why, and only the narration's head (its bench link);
+ - above: the counts (Meter), "drafts are steps on <article> i<n>", **Review drafts — N** (the bench), the Draft
+ everything model and **Draft everything** (opens the draft-all chain panel and starts it), **Approve all N**,
+ the final gate's line (`data-drafts-gate`), section chips (`data-media-chip`) that narrow the list;
+ - keys: `j`/`k` light a field, `a` approves it, `r` rejects it (the cursor to its note first) — from the list or
+ the page, never from another control on the tab. Signal: the lit field's **Approve draft** only;
+ - then **OnscreenSection, whole** (moved from Build; `SECTION_TAB.onscreen` is `media`) and `YoutubeSection`.
+- **The review bench** (`ReviewPage.tsx` → `MediaReview`): the same field list in the shell, one field at a time —
+ the verdict bar asks about the lit field ("Approve the drafted on-screen text of m01? A final build refuses it
+ until it is approved."; the field's Approve draft is an outline there, the bar's is the filled one), the reader
+ shows the clip it is drawn over (its cues ±20 s, the cite's cue lit, Copy citation) or says it has no source
+ window. `DraftsReview.tsx` is gone; `/browse/<p>/review` (r28's hard-coded link) rides P3's redirect to it.
+- **The Iterations tab's media drafts** (Narrate, the task select, Draft, Draft everything) are a **Media drafts →**
+ link (`data-media-link`) to the iteration's video's Media tab (`IterationRow.projectId`, new: the project dir
+ under `REPORTS_ROOT`); its job view is `EditorJobProgress`.
+- **One `JobProgress`** (`components/ui/job-progress.tsx`): the state in words, the current step, the Meter bar
+ (only with a fraction), the spend in Meter, the step list (✓ ▸ ✕ –, each step's own data attributes kept:
+ `data-chain-step`/`data-step-status`, the build's `data-step`/`data-step-state`), children, the log, **Cancel**
+ where the job allows it; `useEditorJob` + `EditorJobProgress` follow an editor job every 2 s (queue words and
+ progress from `lib/running.mjs`, spend from the log's `~$`). Used by the chain panel (Make the video, Draft
+ everything: "running: 6/15 draft the cut…", "5/15 steps"), the build chain, the Media tab's drafts, the
+ Iterations tab's jobs; the rail's Running row uses its two small parts (`components/shell/JobProgress.tsx`
+ re-exports them).
+- **Signal-outline (`primary`) buttons** in the benches, the on-screen panel, the badges and the takes are outlines
+ (a pressed toggle wears the panel ground); the filled action per screen is the verdict bar's or the lit field's.
+
+| sha | what |
+|---|---|
+| `71e1eeb4` | `components/ui/job-progress.tsx`; ChainPanel, ReportBuildChain and the Iterations tab's job view on it; the rail's parts re-exported |
+| `4d5a49bb` | the bench shell; clip, claim, narration, takes on it; ReaderPane's additive props; `lib/report/draft-provenance.mjs` + test |
+| `456f987d` | the Media tab (`MediaDrafts`), `DraftControl`, the review bench, on-screen moved to Media, the Iterations tab's link, `IterationRow.projectId`, `SECTION_TAB.onscreen` |
+| `1eb35db7` | `e2e/bench-shell.spec.ts`, piece.spec's Media test, media-surfaces / article-iterations onto the Media tab, `fixtures/bench-shell-fixture.mjs`; primary → outline |
+| `1d55a5a4` | the chain's progress over all its steps; the bench specs through the href builders |
+| `3e988fd7` | the Media tab's `a`/`r` from the list only |
+
+**Gates.**
+
+| Gate | Result |
+|---|---|
+| repo-wide `tsc --noEmit` | clean (umtool typecheck clean at every commit) |
+| umtool unit (`node --test umtool/lib/*.test.mjs umtool/lib/*/*.test.mjs umtool/report-to-video/*.test.mjs`) | 849 tests, 847 pass, 2 skipped, 0 fail (new: `draft-provenance.test.mjs` 3; `tabs.test.mjs` onscreen → media) |
+| `pnpm --filter umtool test` | 24/24 |
+| `pnpm run test:scripts` (reads the capped build's traces) | 1000 tests, 998 pass, 2 skipped, 0 fail |
+| capped umtool `next build` (corpus linked, `MemoryMax=5G`) | exit 0, compiled 15.9 s, 54 s wall, 1.46 GB max RSS; the link removed |
+| full umtool e2e (`3e988fd7`, one run) | **443 tests: 437 passed, 0 failed, 6 skipped** (the song-data capability skips), 8.7 min |
+
+**Spec churn.** New `e2e/bench-shell.spec.ts` (5): the clip bench at 1366×768 (the top bar — home, the piece's Cut,
+"Clip bench", "1 of 2", no prev, next s02, the keys —, no rail; the extension question and its exact consequence,
+**Extend to 0:09.00** the filled action, Yes as an outline, Keep the cut here; the reader's lit cited cue, Copy
+citation, "cites 0:03"; the correction box on screen; no page scroll either way); `n`/`p` and the walk's question on
+s02; the claim bench (reader, cited cue lit, `j` from the page, Save ruling); the review bench (three fields, the
+question and consequence on m01, its provenance, `j` → m02, `a` approves it, `j` → the narration with "no source
+window", `r` to its note); narration and takes in the shell. `piece.spec` +1 (15): the Media tab on
+`media-tab-fixture` (Media 2, three rows, provenance words for m01 and the release-25 narration, one filled Approve,
+the narration chip, approve one, **Approve all 2**, the gate passes, on-screen here and not on Build).
+`media-surfaces`: the region "Media drafts", the cut's field line (provenance, approve), YouTube's alternative in its
+section, Draft everything from i2's Media tab (reached by the Iterations tab's link). `article-iterations`: narrate
+from the Media tab's narration section, the step then done on the Iterations tab. `claim-bench`, `clip-bench`,
+`draft-review`, `onscreen`, `takes` open their pages through `urls.*Href`. New fixtures
+(`fixtures/bench-shell-fixture.mjs`): `bench-shell-fixture` (read-only), `media-tab-fixture`,
+`media-review-fixture`. No `data-testid` renamed; `data-draft-badge` stays the in-place badge's (OnscreenSection,
+StructureEditors), the list's lines are `data-draft-row`.
+
+**Screenshots** (job scratch `p4b-shots/final/`, dev server on the e2e fixture): the clip bench (s01), the claim bench
+(k01), the Media tab with drafts (media-tab-fixture), the review bench, the narration bench — 1366×768 and 1440×900,
+dark and light — and `JobProgress` mid-run: a section's Draft with queued on the editor's lane (both sizes, both
+themes) and Draft everything at step 6 of 15 (light, 1440×900). Against the canvas: the bench's one-row top bar, the
+verdict bar's question + bold consequence + filled first action, the reader on the right with the lit cue and the
+cite thread; the Media list's `170px | words + provenance | actions` lines with the Signal edge on the lit field,
+the chips, Draft everything / Approve all at the top right. Differences: the clip bench keeps its answer column
+(attribution, on-screen, notes) between the work and the reader, and its player is the cached window's `<video>`
+rather than the canvas's timeline strip; the Media tab's chips filter rather than switch, and Thumbnail (a canvas
+chip) is not a drafted field. **Keyboard-only** (dev, 1366×768): the top bar's stops (home, projects, ← the piece,
+next) then the work, each with the 2 px Signal ring; the review list's lit line takes its dashed mark, its Approve
+draft, Reject and note the ring; `j`/`k` move the verdict bar's field; `--glide` is 0 s under reduced motion.
+
+**Found and left.**
+- **Merge c04 + c05 and Park** (the canvas's other two clip-bench actions) are not built: merging two timeline
+ entries and parking one clip are new writes; the bar states the overlap instead ("covering all of c05"), and
+ **Extend** saves the longer window without dropping the covered clip.
+- The clip bench's own key hint paragraph under the waveform stays (its internals); the top bar's legend is the
+ short form.
+- Narration and takes have no reader: neither has a cited source window (a card narrates the report, a take is our
+ render).
+- The Media tab's count in the tab bar is the drafted fields (P4a-1's); the list also holds narrations written by
+ hand, so "Media 2" can sit over three lines.
+- `IterationsTab`'s **Use this iteration** and **New iteration**'s submit are still P1's `primary` (not the media
+ drafts part of that file).
+- Draft everything's spend is what the chain's log says (`~$`); a chain's ledger total is the Running row's.
+
+**Follow-up (review, 2026-10-14).** Rulings: the review bench keeps every field on the page and asks about the lit one
+(the lit-line model); **Extend to …** saves at once (the button names its result; `y` still records the verdict), and
+**Reset undoes it**. Changes:
+- **One number for "awaiting review"** (`lib/inbox/drafts.mjs` `awaitingReview`): a field a model drafted — its
+ `drafted` mark, or a task's draft file records it (release 25's `narration-draft.json` carries no mark) — whose
+ verdict is not given on its current value (`unreviewed`, `edited`). The Inbox's `drafts-unreviewed` card
+ (`lib/inbox.ts` now reads the draft files' provenance), the piece's **Media** tab count (`reportCounts` is async:
+ `awaitingReviewOf(dir, manifest)`), the Media header's "to review", **Approve all N** and the review bench's status
+ all read it. A narration written by hand is still listed and can be judged, but nothing waits on it. On the fixture:
+ `media-tab-fixture` reads Media 3 · "3 fields · 0 approved · 3 to review" · Approve all 3 · three `drafts-unreviewed`
+ rows. The final gate's line ("refuses 2 fields") stays the build's own rule (drafted marks only). Live, read only:
+ one project waits — `articles/piratesoftware-ai-friends/i1`'s five release-25 narrations, now an Inbox Review card
+ (the canvas's "Review the narration draft"); before, 0.
+- **Reset undoes a saved Extend**: the clip bench keeps the window an Extend replaced; Reset (the button, `R`) with
+ nothing unsaved writes it back and says so; a window saved by hand forgets it.
+- **Cite thread labels** (`components/ui/cite-thread.tsx` `ReaderThread`, `lib/cite-thread.mjs` pure + test): the
+ cite's label is held clear of 0:00 and the length, measured in `ch` (the labels are mono): `clamp(<0:00>+1ch,
+ pct − half, 100% − <end>+1ch+<cite>)`; an end still gives way near it (under 12 %, over 80 %). Was "0:000:03".
+- **The Media tab's unlinked line** is a status: "Not from an article iteration — Draft with is off here." (the why in
+ its `title`); a running iteration: "<article> i<n> is running — Draft with waits for it to finish."
+
+| sha | what |
+|---|---|
+| `00b10cde` | `awaitingReview` everywhere; Reset undoes Extend (`bench-extend-fixture`, a test); `threadLabels`; the terse line; specs |
+| `298450f7` | this follow-up's record |
+| `3498801b` | merge `main` `c103181d` (P4a-3 LIVE); one conflict, this plan (P4a-2/P4a-3 rollout records, then this one; one status row per phase) |
+
+Gates at `3498801b` (the merged tip): repo-wide tsc clean; umtool unit 854 tests, 852 pass, 2 skipped, 0 fail (new:
+`cite-thread.test.mjs` 1, `drafts.test.mjs` +3 assertions); `pnpm --filter umtool test` 24/24; test:scripts 1005, 1003
+pass, 2 skipped, 0 fail; capped build exit 0 (14.2 s compile, 61 s wall, 1.53 GB); **full umtool e2e 453 tests: 447
+passed, 0 failed, 6 skipped** (the song-data skips), 11.3 min (`bench-shell.spec` 6 with the Extend-and-Reset test;
+`piece.spec`'s Media test asserts Media 3, "3 to review" and three `drafts-unreviewed` rows, then none and no count).
+Re-shot (job scratch `p4b-shots/review/`, dev server at `00b10cde`): `clip-dark-1366x768` (the thread reads
+"0:00 0:03 … 0:21"), `review-dark-1366x768`, `media-light-1440x900` (Media 3 · 3 to review · Approve all 3).
+
+### P4b rollout (orchestrator, 2026-10-14)
+
+Rulings: the review bench keeps every field on the page and asks about the lit one; ONE "awaiting review" count
+(`awaitingReview`, `lib/inbox/drafts.mjs`) for the Inbox card, the Media tab count, the header, Approve all and the
+review bench; **Extend to …** saves at once (the button names its result) and Reset undoes it. Review fixes: the cite
+thread's labels kept clear of its ends (`lib/cite-thread.mjs`), the unlinked-project line made a status line. Gates on
+`3498801b` (main `c103181d` merged): full umtool e2e 447 passed, 0 failed, 6 skipped (11.3 min); test:scripts 1003 pass,
+0 fail; capped build ok. `main` fast-forwarded to `e66dd702`; umtool built (450 s, waiting on the heavy slot for memory)
+and restarted (`scripts/p4b-umtool.sh`). Live: `/articles/piratesoftware-ai-friends` Overview, Media ("5 to review",
+Approve all 5 — release 25's five drafted narrations, newly counted), Build and Iterations 200; its project's review and
+narration benches and clip benches c01/c03 200 with the bench head; `/drafts` 307; decisions API 833 rows (the five
+`drafts-unreviewed` rows are new), notes' hrefs end `note=<id>`. P6 audit: "Draft with is off here" reads clipped — name
+the action whole.
+
diff --git a/umtool/components/articles/ArticlePage.tsx b/umtool/components/articles/ArticlePage.tsx
@@ -130,7 +130,7 @@ export default async function ArticlePage({
const tabHref: TabHref = (t, q = {}) =>
articleHref(a, { tab: t, all: q.all, project: q.project === undefined ? project : q.project || undefined });
const title = r?.title || frame.piece?.title || reportId;
- const counts = { ...(detail ? reportCounts(detail) : {}), ...(iterations ? { iterations } : {}) };
+ const counts = { ...(detail && videoRef ? await reportCounts(detail, videoRef.dir) : {}), ...(iterations ? { iterations } : {}) };
const openNotes = notes.doc?.notes.filter((n) => n.status === "open").length ?? 0;
const gitDir = path.join(/* turbopackIgnore: true */ reportDirFor(site, reportId), REPORT_HISTORY_GIT_DIRNAME);
const head = await readRevisionHead(gitDir).catch(() => null);
diff --git a/umtool/components/articles/ChainPanel.tsx b/umtool/components/articles/ChainPanel.tsx
@@ -2,21 +2,15 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
-import { badgeVariants } from "@/components/ui/badge";
+import { JobProgress, type JobStep, type JobStepState } from "@/components/ui/job-progress";
import type { ChainMode, ChainView } from "@/lib/articles/generation";
+import { spendFromLog } from "@/lib/running.mjs";
// MAKE THE VIDEO for one iteration (release 27 S8): the pipeline chain's ten
// steps (lib/report/chain.mjs) as a umtool job — what each step last did, where
// a start resumes, the running step's log, cancel. A step the chain records
// done is skipped by a resume; "from" re-runs from a named step.
-const STATUS_VARIANT: Record<string, "on" | "blocking" | "open" | "info" | "neutral"> = {
- done: "on",
- failed: "blocking",
- running: "open",
- cancelled: "info",
- skipped: "neutral",
-};
export default function ChainPanel({
article,
@@ -95,83 +89,81 @@ export default function ChainPanel({
}
const startAt = from || chain?.resumeAt || "";
+ const steps: JobStep[] = (chain?.steps ?? []).map((s) => ({
+ id: s.name,
+ label: s.label,
+ state: (["pending", "running", "done", "failed", "skipped", "cancelled"].includes(s.status) ? s.status : "pending") as JobStepState,
+ detail: s.optional ? s.detail : null,
+ start: s.name === startAt && !running,
+ optional: s.optional,
+ attrs: { "data-chain-step": s.name, "data-step-status": s.status },
+ }));
+ const job = chain?.job ?? null;
+ const done = job ? chain!.steps.filter((s) => s.status === "done" || s.status === "skipped" || s.status === "failed").length : 0;
return (
<section
aria-label={`${label} ${draftAll ? "Draft everything" : "video chain"}`}
data-chain={label}
data-chain-mode={mode}
- className="mt-2 rounded border border-[var(--color-line)] bg-[var(--color-ink)] p-2 text-[12px]"
+ className="mt-2 space-y-2 rounded-[3px] border border-seam-2 bg-panel p-3 text-[12px]"
>
{draftAll && (
- <p className="mb-1 text-[11px] text-[var(--color-dim)]">
+ <p className="text-[11.5px] text-muted">
{model ? <span className="font-mono">{model}</span> : "each task's route"} · a draft that fails does not stop the chain · the build is the fast one · review the drafts before a final build
</p>
)}
{chain && (
- <ol className={`grid gap-x-4 gap-y-0.5 sm:grid-flow-col ${draftAll ? "sm:grid-rows-8" : "sm:grid-rows-5"}`}>
- {chain.steps.map((s, i) => (
- <li key={s.name} data-chain-step={s.name} data-step-status={s.status} title={s.detail ?? undefined} className="flex items-center gap-2">
- <span className="num w-5 text-right text-[var(--color-dim)]">{i + 1}</span>
- <span className={s.name === startAt && !running ? "font-semibold text-[var(--color-text)]" : s.optional ? "italic" : ""}>{s.label}</span>
- {s.status !== "pending" && (
- <span className={badgeVariants({ variant: STATUS_VARIANT[s.status] ?? "neutral", size: "sm" })}>{s.status}</span>
- )}
- {s.optional && s.status !== "pending" && s.status !== "running" && s.detail && (
- <span data-chain-step-detail="" className="truncate text-[11px] text-[var(--color-dim)]">
- {s.detail}
- </span>
- )}
- </li>
- ))}
- </ol>
+ <JobProgress
+ state={running ? "running" : (job?.state ?? "pending")}
+ status={
+ running
+ ? `running: ${job?.label}`
+ : job
+ ? `last run ${job.state}${job.error ? `: ${job.error}` : ""}`
+ : chain.resumeAt
+ ? `not run · starts at ${chain.resumeAt}`
+ : "every step done"
+ }
+ meter={running && steps.length ? { fraction: done / steps.length, text: `${done}/${steps.length} steps` } : null}
+ spend={job ? spendFromLog(job.log) : null}
+ steps={steps}
+ stepColumns
+ onCancel={running ? () => void cancel() : undefined}
+ cancelLabel="Cancel the chain"
+ log={job?.log}
+ logLabel={`${label} chain log`}
+ data-chain-progress={job?.state ?? "none"}
+ >
+ {job && !running && (
+ <span data-chain-job={job.state} hidden />
+ )}
+ </JobProgress>
)}
- <div className="mt-2 flex flex-wrap items-center gap-2">
- {running ? (
- <>
- <span role="status" className="text-[var(--color-dirty)]">
- step {(chain?.job?.stepIndex ?? 0) + 1}/{chain?.job?.of}: {chain?.job?.label}
- </span>
- <Button size="sm" variant="destructive" onClick={cancel}>
- Cancel the chain
- </Button>
- </>
- ) : (
- <>
- <label className="flex items-center gap-1">
- <span className="text-[var(--color-dim)]">from</span>
- <select
- aria-label={`${label} chain from step`}
- className="rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5"
- value={from}
- onChange={(e) => setFrom(e.target.value)}
- >
- <option value="">{chain?.resumeAt ? `resume (${chain.resumeAt})` : "every step done"}</option>
- {chain?.steps.map((s) => (
- <option key={s.name} value={s.name}>
- {s.name}
- </option>
- ))}
- </select>
- </label>
- <Button size="sm" variant="primary" disabled={sending || (!from && !chain?.resumeAt)} onClick={() => void start()}>
- {draftAll ? "Run Draft everything" : "Run the chain"}
- </Button>
- </>
- )}
- {chain?.job && !running && (
- <span data-chain-job={chain.job.state} className={chain.job.state === "failed" ? "text-[var(--color-bad)]" : "text-[var(--color-dim)]"}>
- last run {chain.job.state}
- {chain.job.error ? `: ${chain.job.error}` : ""}
- </span>
- )}
- </div>
- {chain?.job && chain.job.log.length > 0 && (
- <pre aria-label={`${label} chain log`} className="mt-2 max-h-48 overflow-auto rounded bg-[var(--color-panel)] p-2 font-mono text-[11px] leading-snug whitespace-pre-wrap text-[var(--color-dim)]">
- {chain.job.log.join("\n")}
- </pre>
+ {!running && (
+ <div className="flex flex-wrap items-center gap-2">
+ <label className="flex items-center gap-1">
+ <span className="text-muted">from</span>
+ <select
+ aria-label={`${label} chain from step`}
+ className="rounded-[3px] border border-seam-2 bg-ground px-1 py-0.5"
+ value={from}
+ onChange={(e) => setFrom(e.target.value)}
+ >
+ <option value="">{chain?.resumeAt ? `resume (${chain.resumeAt})` : "every step done"}</option>
+ {chain?.steps.map((s) => (
+ <option key={s.name} value={s.name}>
+ {s.name}
+ </option>
+ ))}
+ </select>
+ </label>
+ <Button size="sm" variant="outline" disabled={sending || (!from && !chain?.resumeAt)} onClick={() => void start()}>
+ {draftAll ? "Run Draft everything" : "Run the chain"}
+ </Button>
+ </div>
)}
{error && (
- <p role="alert" className="mt-1 text-[var(--color-bad)]">
+ <p role="alert" className="text-reject-text">
{error}
</p>
)}
diff --git a/umtool/components/articles/IterationsTab.tsx b/umtool/components/articles/IterationsTab.tsx
@@ -4,8 +4,10 @@ import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { Button, buttonVariants } from "@/components/ui/button";
import { hasRunPage, runHref } from "@/lib/research/runs-hrefs";
+import { projectHref } from "@/lib/hrefs";
import { badgeVariants } from "@/components/ui/badge";
import ChainPanel from "@/components/articles/ChainPanel";
+import { EditorJobProgress } from "@/components/ui/job-progress";
import ResearchSlot from "@/components/articles/ResearchSlot";
import ExtractorSelect, { extractorBody } from "@/components/articles/ExtractorSelect";
import DeletePlan from "@/components/DeletePlan";
@@ -30,17 +32,6 @@ const STATUS_VARIANT: Record<string, "on" | "blocking" | "open" | "info" | "neut
cancelled: "info",
};
-// The media drafts beside narrate (release 28): each a report-draft STEP on a
-// done iteration's video manifest.
-const MEDIA_TASKS: { task: string; label: string }[] = [
- { task: "cut", label: "the cut" },
- { task: "onscreen", label: "on-screen titles" },
- { task: "teaser", label: "the teaser" },
- { task: "flips", label: "flips" },
- { task: "threads", label: "threads" },
- { task: "youtube", label: "YouTube text" },
-];
-
// The report-draft task that made an iteration of this kind (a copy re-runs it).
const TASK_OF: Record<string, string | null> = { sweep: "sweep", "revise-report": "revise-report", "revise-video": "revise-video", research: "research" };
@@ -71,66 +62,18 @@ function ModelSelect({ value, onChange, label, models }: { value: string; onChan
);
}
-/** The editor job behind a queued or running iteration (or step): its place, its log, cancel. */
+/** The editor job behind a queued or running iteration (or step): its place, its log, cancel (the ONE JobProgress). */
function JobProgress({ jobId, label, onEnd }: { jobId: string; label: string; onEnd: () => void }) {
- const [job, setJob] = useState<DraftJobView | null>(null);
- const [error, setError] = useState("");
- useEffect(() => {
- let alive = true;
- let ended = false;
- const tick = async () => {
- try {
- const r = await fetch(`/api/articles/job?id=${encodeURIComponent(jobId)}&tail=12`, { cache: "no-store" });
- const b = await r.json();
- if (!alive) return;
- if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
- setJob(b.job);
- setError("");
- if (!ended && ["done", "failed", "cancelled"].includes(b.job.status)) {
- ended = true;
- onEnd();
- }
- } catch (e) {
- if (alive) setError((e as Error).message);
- }
- };
- void tick();
- const t = setInterval(tick, 2500);
- return () => {
- alive = false;
- clearInterval(t);
- };
- }, [jobId, onEnd]);
- const queued = job?.queue && (job.queue.position ?? 0) > 0;
return (
- <div className="mt-2 rounded border border-[var(--color-line)] bg-[var(--color-ink)] p-2" data-job={jobId} data-job-status={job?.status ?? "unknown"}>
- <div className="flex flex-wrap items-center gap-2 text-[11px]">
- <span className="font-mono text-[var(--color-dim)]">{jobId}</span>
- <span role="status" className="text-[var(--color-dirty)]">
- {job ? (queued ? `queued, ${job.queue?.position} ahead on ${job.queue?.key}` : job.status) : "asking the editor…"}
- </span>
- <Button
- size="sm"
- variant="destructive"
- className="ml-auto"
- aria-label={`Cancel ${label}`}
- onClick={async () => {
- const r = await fetch("/api/articles/job", { method: "POST", body: JSON.stringify({ cancel: jobId }) });
- const b = await r.json().catch(() => ({}));
- if (!r.ok) setError(b.error ?? `HTTP ${r.status}`);
- onEnd();
- }}
- >
- Cancel
- </Button>
- </div>
- {job && job.tail.length > 0 && (
- <pre role="log" aria-label={`${label} progress`} className="mt-1 max-h-40 overflow-auto font-mono text-[11px] leading-snug whitespace-pre-wrap text-[var(--color-dim)]">
- {job.tail.join("\n")}
- </pre>
- )}
- {error && <p className="mt-1 text-[11px] text-[var(--color-bad)]">{error}</p>}
- </div>
+ <EditorJobProgress
+ jobId={jobId}
+ tail={12}
+ log
+ logLabel={`${label} progress`}
+ cancelName={`Cancel ${label}`}
+ onEnd={() => onEnd()}
+ className="mt-2 rounded-[3px] border border-seam bg-ground p-2"
+ />
);
}
@@ -209,17 +152,9 @@ function IterationCard({
comparing: boolean;
onCompare: (on: boolean) => void;
}) {
- const [open, setOpen] = useState<"new" | "chain" | "draft-all" | null>(null);
+ const [open, setOpen] = useState<"new" | "chain" | null>(null);
const g = ctx.policy?.generation;
- const routeModel = (t: string) => (g?.routes[t as keyof typeof g.routes] === "api" ? g?.models.api : g?.models.local) ?? "";
- const [mediaTask, setMediaTask] = useState(MEDIA_TASKS[0].task);
- const [mediaModel, setMediaModel] = useState(() => routeModel(MEDIA_TASKS[0].task));
- const [mediaForce, setMediaForce] = useState(false);
- const [allModel, setAllModel] = useState(() => routeModel("onscreen"));
- // Each press of Draft everything mounts a fresh panel that starts it.
- const [allRun, setAllRun] = useState(0);
const [copyModel, setCopyModel] = useState(() => ctx.allModels.find((m) => m !== it.model) ?? it.model);
- const [narrateModel, setNarrateModel] = useState(g?.routes.narrate === "api" ? g.models.api : (g?.models.local ?? ""));
const [copyExtractor, setCopyExtractor] = useState(g?.models.extractor ?? "");
const done = it.status === "done";
const active = it.status === "queued" || it.status === "running";
@@ -366,60 +301,18 @@ function IterationCard({
</Button>
</span>
)}
- {done && it.hasManifest && !runningStep && (
- <span className="flex items-center gap-1">
- <ModelSelect label={`narration model for ${it.label}`} value={narrateModel} onChange={setNarrateModel} models={ctx.allModels} />
- <Button size="sm" onClick={() => void ctx.post({ task: "narrate", article: ctx.article, iteration: it.n, model: narrateModel })}>
- Narrate
- </Button>
- </span>
- )}
- {done && it.hasManifest && !runningStep && (
- <span className="flex items-center gap-1" data-media-draft={it.n}>
- <select
- aria-label={`draft task for ${it.label}`}
- className={field}
- value={mediaTask}
- onChange={(e) => {
- setMediaTask(e.target.value);
- setMediaModel(routeModel(e.target.value));
- }}
- >
- {MEDIA_TASKS.map((t) => (
- <option key={t.task} value={t.task}>
- {t.label}
- </option>
- ))}
- </select>
- <ModelSelect label={`draft model for ${it.label}`} value={mediaModel} onChange={setMediaModel} models={ctx.allModels} />
- <label className="flex items-center gap-1 text-[11px] text-[var(--color-dim)]" title="re-draft fields a model drafted; a field you wrote or edited is never replaced">
- <input type="checkbox" checked={mediaForce} onChange={(e) => setMediaForce(e.target.checked)} aria-label={`force: re-draft drafted fields of ${it.label}`} />
- force
- </label>
- <Button
- size="sm"
- onClick={() =>
- void ctx.post({ task: mediaTask, article: ctx.article, iteration: it.n, model: mediaModel, ...(mediaForce ? { force: true } : {}) })
- }
- >
- Draft
- </Button>
- </span>
- )}
- {done && it.reportFrom !== null && (
- <span className="flex items-center gap-1">
- <ModelSelect label={`Draft everything model for ${it.label}`} value={allModel} onChange={setAllModel} models={ctx.allModels} />
- <Button
- size="sm"
- aria-expanded={open === "draft-all"}
- onClick={() => {
- setOpen("draft-all");
- setAllRun((k) => k + 1);
- }}
- >
- Draft everything
- </Button>
- </span>
+ {/* The media drafts -- narration, on-screen, the cut, the teaser,
+ flips, threads, YouTube, and Draft everything -- are the Media
+ tab's (P4b): ONE surface per video. */}
+ {done && it.hasManifest && it.projectId && (
+ <Link
+ href={projectHref(it.projectId, { tab: "media" })}
+ prefetch={false}
+ data-media-link={it.n}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ >
+ Media drafts →
+ </Link>
)}
{done && it.reportFrom !== null && (
<Button size="sm" aria-expanded={open === "chain"} onClick={() => setOpen(open === "chain" ? null : "chain")}>
@@ -454,9 +347,6 @@ function IterationCard({
</div>
{open === "new" && <NewIterationForm it={it} ctx={ctx} onDone={() => setOpen(null)} />}
{open === "chain" && <ChainPanel article={ctx.article} n={it.n} label={it.label} />}
- {open === "draft-all" && (
- <ChainPanel key={allRun} article={ctx.article} n={it.n} label={it.label} mode="draft-all" model={allModel} autoStart={allRun > 0} />
- )}
</article>
);
}
diff --git a/umtool/components/piece/PieceFrame.tsx b/umtool/components/piece/PieceFrame.tsx
@@ -52,7 +52,7 @@ export default function PieceFrame({
meta?: React.ReactNode;
/** More of the head's foot row, after the stepper (the policy chip). */
head?: React.ReactNode;
- /** A count beside a tab's name, in Meter (Cut: clips, Media: drafted fields, Sources: recordings). */
+ /** A count beside a tab's name, in Meter (Cut: clips, Media: fields awaiting review, Sources: recordings). */
counts: Partial<Record<string, number>>;
/** The page's one-line status, the head's last `.micro`. */
note?: React.ReactNode;
diff --git a/umtool/components/projects/ClaimBench.tsx b/umtool/components/projects/ClaimBench.tsx
@@ -2,6 +2,11 @@
import Link from "next/link";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { ReaderPane } from "@/components/ui/reader-pane";
+import { citationText } from "@/lib/research/facets.mjs";
+import { BenchBody, VerdictBar } from "./bench/BenchShell";
+import CopyCitation from "./bench/CopyCitation";
import {
POPULATIONS,
SCOPES,
@@ -270,27 +275,92 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) {
window.location.reload();
}, [data.project, claim.id, data.pad]);
- const paragraph = useMemo(
- () =>
- cues.map((c, i) => (
- <span
- key={`${c.start}-${i}`}
- data-cited={c.cited ? "1" : undefined}
- onClick={() => seekTo(c.start)}
- className={
- "cursor-pointer " +
- (c.cited
- ? "bg-[color-mix(in_srgb,var(--reader-signal)_14%,transparent)] text-reader-ink"
- : "text-reader-2 hover:text-reader-ink")
- }
- >
- {c.text}{" "}
- </span>
- )),
- [cues, seekTo],
+ // ---- the bench shell's verdict bar and reader (P4b) ------------------------
+ const missing = [
+ !scope && "scope",
+ !confidence && "scope confidence",
+ !population && "population",
+ !valueKind && "value kind",
+ !basis.trim() && "scope basis",
+ ].filter(Boolean) as string[];
+ const verdictBar = (
+ <VerdictBar
+ data-verdict-for={claim.id}
+ question={<>Save the ruling on {claim.id}?</>}
+ consequence={
+ missing.length
+ ? `Still missing ${missing.join(", ")} — it stays blocking.`
+ : dirty
+ ? "Every field is set: it leaves the blocking list."
+ : "Nothing changed since it was saved."
+ }
+ >
+ <button
+ type="button"
+ data-testid="claim-save"
+ disabled={!dirty || !!busy || !roles.ok}
+ onClick={() => void save()}
+ className={buttonVariants({ variant: "go", size: "md" })}
+ >
+ {busy ?? "Save ruling"}
+ </button>
+ {data.next && (
+ <Link href={`/projects/${data.project}/claim/${data.next}`} className={buttonVariants({ variant: "quiet", size: "md" })}>
+ Next claim ({data.next})
+ </Link>
+ )}
+ </VerdictBar>
+ );
+ // The cue the cited second falls in: a cite on a boundary marks both cues
+ // around it, and the line is the one it STARTS (the later of the two).
+ let firstCited = -1;
+ cues.forEach((c, i) => {
+ if (c.cited) firstCited = i;
+ });
+ const reader = (
+ <ReaderPane
+ className="h-full"
+ source={data.source?.title ?? claim.video ?? claim.id}
+ byline={[
+ claim.channel,
+ data.source?.uploadDate
+ ? `${data.source.uploadDate.slice(0, 4)}-${data.source.uploadDate.slice(4, 6)}-${data.source.uploadDate.slice(6, 8)}`
+ : claim.date,
+ <span key="t" className="font-mono">
+ transcript{data.source?.duration ? ` · ${hms(data.source.duration)}` : ""}
+ </span>,
+ ]}
+ cite={at != null && data.source?.duration ? { at, duration: data.source.duration } : undefined}
+ note={`±${data.pad}s of context · ${hms(view.from)}–${hms(view.to)}${at != null ? ` · cited at ${hms(at)}` : ""}`}
+ label="Context"
+ global
+ bodyProps={{ "data-testid": "claim-context" }}
+ cues={
+ data.noCues
+ ? undefined
+ : cues.map((c, i) => ({
+ t: c.start,
+ text: c.text,
+ lit: i === firstCited,
+ attrs: { "data-cited": c.cited ? "1" : undefined },
+ }))
+ }
+ onLight={(d) => {
+ const c = cues[d.index];
+ if (c && d.index !== firstCited) seekTo(c.start);
+ }}
+ footer={claim.quote ? <CopyCitation text={citationText({ quote: claim.quote, title: data.source?.title ?? claim.video ?? claim.id, clock: at != null ? hms(at) : undefined, url: data.source?.webpageUrl ?? undefined })} /> : undefined}
+ fine={[claim.label, claim.src].filter(Boolean).join(" · ") || undefined}
+ >
+ <p className="text-[12px] text-reader-dim">
+ no transcript.cues.json for {claim.channel}/{claim.video} — on Rumble, check the directory is the URL slug and
+ not the site id
+ </p>
+ </ReaderPane>
);
return (
+ <BenchBody verdict={verdictBar} reader={reader}>
<div className="space-y-3" data-claim={claim.id}>
<div className="flex items-baseline gap-3">
<div className="font-mono text-[13px] text-[var(--color-fg)]">{claim.id}</div>
@@ -298,17 +368,6 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) {
<div className="text-[13px] text-[var(--color-meter)]">
{claim.display ?? (claim.value == null ? "—" : String(claim.value))}
</div>
- <div className="flex-1" />
- {data.prev ? (
- <Link className="text-[11px] ink-link" href={`/projects/${data.project}/claim/${data.prev}`}>
- ← {data.prev}
- </Link>
- ) : null}
- {data.next ? (
- <Link className="text-[11px] ink-link" href={`/projects/${data.project}/claim/${data.next}`}>
- {data.next} →
- </Link>
- ) : null}
</div>
<div className="grid gap-3 lg:grid-cols-[minmax(0,1fr)_360px]">
@@ -337,27 +396,6 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) {
</div>
)}
- {/* The source's words, on the READER (app/globals.css). */}
- <div className="reader rounded-[2px] px-4 py-3">
- <div className="micro mb-2">
- ±{data.pad}s of context · {hms(view.from)}–{hms(view.to)}
- {at != null ? ` · cited at ${hms(at)}` : ""}
- </div>
- {data.noCues ? (
- <div className="text-[12px] text-reader-dim">
- no transcript.cues.json for {claim.channel}/{claim.video} — on Rumble, check the
- directory is the URL slug and not the site id
- </div>
- ) : (
- <p
- data-testid="claim-context"
- className="max-h-[320px] overflow-y-auto font-serif text-[15px] leading-relaxed"
- >
- {paragraph}
- </p>
- )}
- </div>
-
<div className="reader rounded-[2px] px-4 py-3 text-[12px]">
<div className="micro mb-1">as recorded</div>
<div className="font-serif text-[16px] leading-snug text-reader-ink">“{claim.quote}”</div>
@@ -460,23 +498,10 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) {
</div>
) : null}
- <div className="flex items-center gap-2">
- <button
- type="button"
- data-testid="claim-save"
- disabled={!dirty || !!busy || !roles.ok}
- onClick={() => void save()}
- className="rounded border border-[var(--color-sel)] px-3 py-1 text-[11px] text-[var(--color-sel)] disabled:opacity-40"
- >
- {busy ?? "save ruling"}
- </button>
- {!complete ? (
- <span className="text-[10px] text-[var(--color-dim)]">all six fields, or it stays blocking</span>
- ) : null}
- </div>
{note ? <div data-testid="claim-note" className="text-[11px] text-[var(--color-dim)]">{note}</div> : null}
</div>
</div>
</div>
+ </BenchBody>
);
}
diff --git a/umtool/components/projects/ClaimBenchPage.tsx b/umtool/components/projects/ClaimBenchPage.tsx
@@ -1,6 +1,6 @@
import { notFound } from "next/navigation";
-import AppShell from "@/components/shell/AppShell";
-import { browseHref } from "@/lib/hrefs";
+import { browseHref, claimBenchHref } from "@/lib/hrefs";
+import { BenchFrame, BenchTop } from "./bench/BenchShell";
import ClaimBench, { type ClaimBenchData } from "./ClaimBench";
import { manifestToken } from "@/lib/report/manifest.mjs";
import { readClaimDetail, readManifest } from "@/lib/projects/report.mjs";
@@ -87,22 +87,25 @@ export default async function ClaimBenchPage({
// The piece this view belongs to: the article's when an article claims the project (P4a-2).
const back = await pieceHrefOfProject(project.id, { tab: "cut" });
+ const href = (id: string) => claimBenchHref(project.id, id);
return (
- <div className="flex h-full flex-col">
- {/* A bench: the rail collapses and the work takes the width. */}
- <AppShell
- active="browse"
- rail="collapsed"
- crumbs={[
- { href: browseHref(), label: "projects" },
- { href: back, label: project.name },
- { label: claimId },
- ]}
- note={`claim ${i + 1} of ${ledger.length} · ${outstanding} unadjudicated`}
- />
- <main className="deck-main flex-1 p-4">
- <ClaimBench data={data} />
- </main>
- </div>
+ <BenchFrame
+ kind="claim"
+ top={
+ <BenchTop
+ trail={[{ href: browseHref(), label: "projects" }]}
+ back={{ href: back, label: project.name }}
+ kind="Claim bench"
+ here={claimId}
+ pos={{ index: i + 1, total: ledger.length }}
+ prev={data.prev ? { href: href(data.prev), label: data.prev } : null}
+ next={data.next ? { href: href(data.next), label: data.next } : null}
+ keys={[{ keys: ["j", "k"], label: "cue" }]}
+ note={`${outstanding} unadjudicated`}
+ />
+ }
+ >
+ <ClaimBench data={data} />
+ </BenchFrame>
);
}
diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx
@@ -9,6 +9,10 @@ import { useRouter } from "next/navigation";
import Waveform, { type Peaks } from "@/components/Waveform";
import { badgeVariants } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
+import { ReaderPane, paperButtonVariants } from "@/components/ui/reader-pane";
+import { citationText } from "@/lib/research/facets.mjs";
+import { BenchBody, VerdictBar } from "./bench/BenchShell";
+import CopyCitation from "./bench/CopyCitation";
// The renderer's own line, imported rather than re-written. A preview that
// disagrees with the header by a character is worth less than no preview: you
// would only find out twenty minutes into a build.
@@ -419,6 +423,11 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
// it has something in it. An incorrect verdict with no note is a complaint
// nobody can act on, so the bench asks for the note before it writes one.
const [needNote, setNeedNote] = useState(false);
+ // The window an Extend (the verdict bar's) saved over, so Reset can put it
+ // back: Extend saves at once -- its button names its result -- and Reset is
+ // its undo. Null once undone, or after any other window save.
+ const [extendedFrom, setExtendedFrom] = useState<{ start: number; end: number } | null>(null);
+ const resetRef = useRef<() => void>(() => {});
// Defaults on the server and on the first paint, then whatever this browser
// remembers. Reading localStorage during render would be a hydration
// mismatch on the one prop that changes what you hear.
@@ -1387,10 +1396,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
break;
case "r":
case "R":
- setSel({ from: clip.start, to: clip.end });
- setDirty(false);
- setMute(clip.muteFrom);
- muteRef.current = clip.muteFrom;
+ resetRef.current();
break;
// Walking the cut. Reviewing a whole video is nineteen clips in a row,
// and going back to the project page between each one is nineteen round
@@ -1703,6 +1709,8 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
const patch = windowPatch();
void save(patch).then((ok) => {
if (!ok) return;
+ // A window saved by hand is the one Reset keeps from now on.
+ setExtendedFrom(null);
const cleared = [
patch.cutStart !== undefined ? "the cut" : null,
patch.muteFrom === "" && mute != null ? "the mute mark" : null,
@@ -1843,6 +1851,288 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
const overlayT = deckSeg ? deckSeg.start + Math.min(segT ?? deckSeg.duration / 4, deckSeg.duration) : 0;
const showOverlay = data.deckOn && !!deckPreview && renderedOpen;
+ // ---- the verdict bar: ONE question, its consequence, the actions ----------
+ //
+ // The bench shell's foot (components/projects/bench/BenchShell.tsx). A clip
+ // that ends mid-sentence asks the one question that decides its window --
+ // extend to the sentence's end, and what that would cover -- before the
+ // walk's own question; otherwise the walk's: is this clip what the report
+ // says it is. `y` and `x` answer the walk's either way.
+ const sentenceEnd = (() => {
+ if (!midSentence || !endCue) return null;
+ const pool = [...(peek.length ? peek : cues)].filter((c) => c.start >= endCue.start - 0.02).sort((x, y) => x.start - y.start);
+ return pool.find((c) => c.endsSentence)?.end ?? null;
+ })();
+ const covered =
+ sentenceEnd == null ? [] : siblings.filter((sb) => sb.start < sentenceEnd - 0.02 && sb.end > sel.to + 0.02);
+ const coveredWhole = covered.filter((sb) => sb.start >= sel.to - 0.02 && sb.end <= sentenceEnd! + 0.02);
+ const pastCache = sentenceEnd != null && sentenceEnd > clampTo + 0.02;
+ const extendTo = (t: number) => {
+ const to = round2(t);
+ const was = { start: clip.start, end: clip.end };
+ void save({ start: round2(sel.from), end: to }).then((ok) => {
+ if (!ok) return;
+ setExtendedFrom(was);
+ setNote(`saved — ${clip.id} now ends at ${hms(to)}, the end of the sentence; R undoes it`);
+ });
+ };
+ // Reset: an unsaved edit goes back to the saved window; with none, a saved
+ // Extend goes back to the window it replaced.
+ resetRef.current = () => {
+ if (unsaved || !extendedFrom) {
+ setSel({ from: clip.start, to: clip.end });
+ setDirty(false);
+ setMute(clip.muteFrom);
+ muteRef.current = clip.muteFrom;
+ return;
+ }
+ const back = extendedFrom;
+ void save({ start: back.start, end: back.end }).then((ok) => {
+ if (!ok) return;
+ setExtendedFrom(null);
+ setNote(`the extension is undone — ${clip.id} ends at ${hms(back.end)} again`);
+ });
+ };
+ const verdictBar = (
+ <VerdictBar
+ data-verdict-for={clip.id}
+ question={
+ sentenceEnd != null ? (
+ <>Extend {clip.id} to the end of the sentence?</>
+ ) : (
+ <>Is {clip.id} what the report says it is?</>
+ )
+ }
+ consequence={
+ sentenceEnd != null
+ ? `It would end at ${hms(sentenceEnd)} (+${(sentenceEnd - sel.to).toFixed(1)} s)` +
+ (coveredWhole.length
+ ? `, covering all of ${coveredWhole.map((sb) => sb.id).join(", ")}`
+ : covered.length
+ ? `, overlapping ${covered.map((sb) => sb.id).join(", ")}`
+ : "") +
+ (pastCache ? " — past what is fetched." : ".")
+ : needNote && !draft.correction.trim()
+ ? "The note is the answer — type it, then blur or Enter."
+ : verdict === "unreviewed"
+ ? data.next
+ ? `Confirming saves it${windowMoved || muteMoved ? " with the window you moved" : ""} and opens ${data.next}.`
+ : `Confirming saves it${windowMoved || muteMoved ? " with the window you moved" : ""}; it is the walk's last.`
+ : undefined
+ }
+ >
+ {sentenceEnd != null &&
+ (pastCache ? (
+ <button
+ type="button"
+ data-verdict-extend="fetch"
+ className={buttonVariants({ variant: "go", size: "md" })}
+ disabled={!!busy || atMaxPad}
+ onClick={() => void fetchMore(padsForCue({ start: endCue!.start, end: sentenceEnd, text: "", endsSentence: true }))}
+ >
+ Fetch to {hms(sentenceEnd)}
+ </button>
+ ) : (
+ <button
+ type="button"
+ data-verdict-extend={sentenceEnd}
+ className={buttonVariants({ variant: "go", size: "md" })}
+ disabled={!!busy}
+ onClick={() => extendTo(sentenceEnd)}
+ >
+ Extend to {hms(sentenceEnd)}
+ </button>
+ ))}
+ {sentenceEnd != null && (
+ <button
+ type="button"
+ data-verdict-keep=""
+ className={buttonVariants({ size: "md" })}
+ disabled={!!busy}
+ title="lockEnd: you meant to cut here; the walk stops asking"
+ onClick={() => void save({ lockEnd: true })}
+ >
+ Keep the cut here
+ </button>
+ )}
+ <button
+ type="button"
+ data-verdict-yes=""
+ className={buttonVariants({ variant: sentenceEnd != null ? "outline" : "go", size: "md" })}
+ disabled={!!busy}
+ onClick={() => void confirmClip()}
+ >
+ Yes, confirmed <kbd>y</kbd>
+ </button>
+ <button type="button" data-verdict-no="" className={buttonVariants({ size: "md" })} onClick={rejectClip}>
+ No, note what is wrong <kbd>x</kbd>
+ </button>
+ <span
+ data-verdict-state=""
+ className={
+ verdict === "confirmed"
+ ? "text-[12px] text-[var(--color-good)]"
+ : verdict === "incorrect"
+ ? "text-[12px] text-[var(--color-dirty)]"
+ : "text-[12px] text-[var(--color-dim)]"
+ }
+ >
+ {verdictLabel(clip)}
+ </span>
+ </VerdictBar>
+ );
+
+ // ---- the reader: the source's words, the cited cue lit -------------------
+ //
+ // The transcript, as something you can actually read: the export site's
+ // transcript viewer's layout (a monospace m:ss column, the text beside it,
+ // the line playing lit), now the bench shell's reader pane -- the source on
+ // the reader surface, its cite thread, Copy citation. A cue in the cut
+ // already is tagged with its clip; a dimmed one is not fetched (click to
+ // fetch it). The cited cue is lit until something plays.
+ const citeAt = clip.cite ?? clip.start;
+ const citedCue = railCues.find((c) => citeAt >= c.start - 0.02 && citeAt < c.end) ?? null;
+ const citation = citationText({
+ quote: draft.quote.trim() || undefined,
+ title: data.sourceTitle || clip.title || clip.video,
+ clock: clock(citeAt),
+ url: clip.citeUrl ?? undefined,
+ });
+ const readerPane = (
+ <ReaderPane
+ className="h-full"
+ source={data.sourceTitle || clip.title || clip.video}
+ byline={[
+ data.sourceChannel || clip.channel,
+ clip.date || (data.uploadDate ? `${data.uploadDate.slice(0, 4)}-${data.uploadDate.slice(4, 6)}-${data.uploadDate.slice(6, 8)}` : null),
+ <span key="t" className="font-mono">
+ transcript{data.sourceDuration ? ` · ${clock(data.sourceDuration)}` : ""}
+ </span>,
+ ]}
+ cite={data.sourceDuration ? { at: citeAt, duration: data.sourceDuration } : undefined}
+ bare
+ bodyProps={{ ref: transcriptBox, "data-transcript": "", className: "relative py-0 pr-0" }}
+ footer={
+ <>
+ <CopyCitation text={citation} />
+ <button
+ type="button"
+ data-reader-play=""
+ className={paperButtonVariants()}
+ disabled={!cached}
+ onClick={() => void play(sel.from, sel.to)}
+ >
+ Play clip
+ </button>
+ </>
+ }
+ fine={`cites ${clock(citeAt)}${cached ? ` · clip window cached in ${cached.name}` : " · not fetched"}`}
+ >
+ <ul>
+ {railCues.map((c, i) => {
+ const outside = c.start < view.from - 0.02 || c.end > view.to + 0.02;
+ const prev = railCues[i - 1];
+ const prevOutside = prev
+ ? prev.start < view.from - 0.02 || prev.end > view.to + 0.02
+ : outside;
+ // The cache edge, drawn once, where the material stops being
+ // on disk. Reading past it is free; playing past it is not.
+ const rule = i > 0 && prevOutside !== outside;
+ const inSel = c.end > sel.from && c.start < sel.to;
+ const playing = playhead != null && playhead >= c.start && playhead < c.end;
+ // The cited cue is the lit line until something plays; then the head follows the player.
+ const lit = playing || (playhead == null && c === citedCue);
+ const owner = siblingAt(c);
+ return (
+ <li key={`t-${c.start}-${c.end}`}>
+ {rule && (
+ <div
+ data-cache-rule={outside ? "end" : "start"}
+ className="flex items-center gap-2 border-t border-dashed border-reader-2 px-2 py-0.5 text-[10px] uppercase tracking-wider text-reader-dim"
+ >
+ {outside ? "not fetched — reading only" : "cached from here"}
+ </div>
+ )}
+ <button
+ type="button"
+ data-tcue={c.start}
+ data-peek={outside ? "1" : "0"}
+ data-in-sibling={owner ? owner.id : ""}
+ data-cited={c === citedCue ? "1" : undefined}
+ data-lit={lit ? "" : undefined}
+ title={
+ outside
+ ? `not fetched — click to fetch to ${padLabelForCue(c)}`
+ : "click to play from here"
+ }
+ onClick={() => {
+ if (outside) {
+ if (!atMaxPad) void fetchMore(padsForCue(c));
+ return;
+ }
+ void play(c.start, Math.min(c.end + 4, view.to));
+ }}
+ className={`flex w-full items-baseline gap-3 px-2.5 py-[3px] text-left hover:bg-[color-mix(in_srgb,var(--reader-signal)_6%,transparent)] ${
+ inSel ? "bg-[color-mix(in_srgb,var(--reader-signal)_11%,transparent)]" : ""
+ } ${lit ? "border-l-[3px] border-reader-signal" : "border-l-[3px] border-transparent"}`}
+ >
+ <span
+ className={`num w-10 shrink-0 font-mono text-[10.5px] ${
+ lit ? "font-semibold text-reader-signal" : "text-reader-dim"
+ }`}
+ >
+ {clock(c.start)}
+ </span>
+ <span
+ className={`min-w-0 font-serif text-[15px] leading-snug ${
+ outside ? "text-reader-dim opacity-70" : inSel || lit ? "text-reader-ink" : "text-reader-2"
+ }`}
+ >
+ {owner && (
+ <span
+ className="mr-1.5 rounded-[2px] border border-reader-2 px-1 font-mono text-[10px] text-reader-ink"
+ title={`already in the cut as ${owner.id} (${owner.where})`}
+ >
+ {owner.id}
+ </span>
+ )}
+ {c.endsSentence && (
+ <span className="mr-1 font-mono text-[11px] text-reader-dim" aria-hidden>
+ ¶
+ </span>
+ )}
+ {c.text}
+ </span>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+
+ {/* ---- the pane's own footer ----
+ The controls that act on this pane live in it, stuck to the
+ bottom of its scrollport: they cost the pane a line and the
+ left column nothing, and "peek further" ends up beside the
+ dimmed lines it widens. Opaque, because it sits over text. */}
+ <div className="micro sticky bottom-0 z-10 flex flex-wrap items-center gap-2 border-t border-reader-seam bg-reader px-2.5 py-1">
+ <span>click a line to play it</span>
+ {peek.length > 0 && (
+ <>
+ <span>· dimmed lines are not fetched — click to fetch</span>
+ <button
+ type="button"
+ data-peek-further=""
+ className="ml-auto text-reader-signal hover:underline"
+ onClick={() => setPeekPad((n) => n + PEEK_STEP)}
+ >
+ peek further (±{peekPad + PEEK_STEP} s)
+ </button>
+ </>
+ )}
+ </div>
+ </ReaderPane>
+ );
+
return (
// ONE SCREEN, at a desk.
//
@@ -1854,6 +2144,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
// scrolls, and what does not earn its height is folded rather than cut.
// Below lg it is a single scrolling column -- a phone cannot hold this and
// pretending otherwise would cost the desk case something.
+ <BenchBody verdict={verdictBar} reader={readerPane} workClassName="lg:overflow-hidden">
<div
data-bench={clip.id}
data-verdict={verdict}
@@ -1862,10 +2153,6 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
<GeneratedBanner generatedBy={data.generatedBy} />
{/* ---- where you are, where you can go, and what will be burned in ---- */}
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px]">
- <span className="num font-mono text-[var(--color-text)]">
- clip {data.index} of {data.total} ·{" "}
- <span className="text-[var(--color-sel)]">{clip.id}</span>
- </span>
<span className="micro" data-review-progress="">
{reviewed} reviewed
</span>
@@ -1879,31 +2166,6 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
not fetched yet
</span>
)}
- {data.prev ? (
- <Link
- data-clip-nav="prev"
- href={`/projects/${data.project}/clip/${data.prev}`}
- className="ink-link"
- >
- ← {data.prev}
- </Link>
- ) : (
- <span className="text-[var(--color-dim)]">← first</span>
- )}
- {data.next ? (
- <Link
- data-clip-nav="next"
- href={`/projects/${data.project}/clip/${data.next}`}
- className="ink-link"
- >
- {data.next} →
- </Link>
- ) : (
- <span className="text-[var(--color-dim)]">last →</span>
- )}
- <span className="micro">
- <kbd>p</kbd> <kbd>n</kbd> walk
- </span>
{/* The renderer's own line, live. It used to sit four hundred pixels
down the page; it is the one string this bench exists to get right,
so it heads the screen. */}
@@ -1916,9 +2178,12 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
</span>
</div>
- <div className="grid min-h-0 flex-1 gap-3 lg:grid-cols-[minmax(0,1fr)_minmax(22rem,26rem)]">
+ <div className="grid min-h-0 flex-1 gap-3 lg:grid-cols-[minmax(0,1fr)_minmax(20rem,23rem)]">
{/* ================= the picture, and its edges ================= */}
- <div className="flex min-h-0 flex-col gap-2">
+ {/* Since P4b the words are the bench's reader pane: this column is the
+ picture and everything that moves its edges, and it scrolls on its
+ own before the picture shrinks below a usable height. */}
+ <div className="flex min-h-0 flex-col gap-2 lg:overflow-y-auto">
{cached ? (
<video
ref={video}
@@ -1930,12 +2195,12 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
// than either taking a fixed number of pixels: a laptop and a
// 1080p screen have very different amounts to give away, and a
// 130px player is not a player.
- className="aspect-video w-full rounded border border-[var(--color-line)] bg-black object-contain lg:aspect-auto lg:min-h-0 lg:flex-[3_1_0%]"
+ className="aspect-video w-full rounded border border-[var(--color-line)] bg-black object-contain lg:aspect-auto lg:min-h-[200px] lg:flex-[3_1_0%]"
preload="metadata"
controls
/>
) : (
- <div className="flex aspect-video w-full items-center justify-center rounded border border-dashed border-[var(--color-line)] text-[12px] text-[var(--color-dim)] lg:aspect-auto lg:min-h-0 lg:flex-[3_1_0%]">
+ <div className="flex aspect-video w-full items-center justify-center rounded border border-dashed border-[var(--color-line)] text-[12px] text-[var(--color-dim)] lg:aspect-auto lg:min-h-[200px] lg:flex-[3_1_0%]">
nothing fetched for this clip yet
</div>
)}
@@ -1960,7 +2225,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
<button
type="button"
data-save-window=""
- className={buttonVariants({ variant: "primary", size: "sm" })}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
disabled={!unsaved || !!busy}
onClick={saveWindow}
>
@@ -1977,13 +2242,10 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
<button
type="button"
className={buttonVariants({ size: "sm" })}
- disabled={!unsaved}
- onClick={() => {
- setSel({ from: clip.start, to: clip.end });
- setDirty(false);
- setMute(clip.muteFrom);
- muteRef.current = clip.muteFrom;
- }}
+ data-reset=""
+ disabled={!unsaved && !extendedFrom}
+ title={!unsaved && extendedFrom ? `undo the extension: back to ${hms(extendedFrom.start)} – ${hms(extendedFrom.end)}` : undefined}
+ onClick={() => resetRef.current()}
>
reset
</button>
@@ -2026,7 +2288,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
data-auto-audition={playback.auto ? "on" : "off"}
aria-pressed={playback.auto}
className={buttonVariants({
- variant: playback.auto ? "primary" : "outline",
+ variant: "outline",
size: "sm",
})}
onClick={() => choosePlayback((pb) => ({ ...pb, auto: !pb.auto }))}
@@ -2146,7 +2408,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
type="button"
data-mute-pick={mutePick ? "armed" : ""}
aria-pressed={mutePick}
- className={buttonVariants({ variant: mutePick ? "primary" : "outline", size: "sm" })}
+ className={`${buttonVariants({ variant: "outline", size: "sm" })}${mutePick ? " bg-panel-2 border-muted" : ""}`}
title="the next click on the waveform places the mute mark (Esc cancels)"
onClick={() => setMutePick((v) => !v)}
>
@@ -2274,7 +2536,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
<button
type="button"
data-fetch-after={nextAfter}
- className={buttonVariants({ variant: "primary", size: "sm" })}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
disabled={!!busy}
onClick={() => void fetchMore({ padBefore: keepBefore, padAfter: nextAfter })}
>
@@ -2426,120 +2688,6 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
);
})}
</div>
- {/* ---- THE TRANSCRIPT, as something you can actually read ----
- The rail is a timeline: it squeezes every cue into a column a few
- characters wide, which is right for dragging an edge against and
- useless for reading. The words are why anybody peeks ahead, so
- they also run here in reading order -- the export site's
- transcript viewer's layout (a monospace m:ss column, the text
- beside it, the active line lit), because somebody reading a
- transcript in this repo should not have to learn a second one. */}
- <div
- data-transcript=""
- ref={transcriptBox}
- // On the READER: these are the source's words (app/globals.css).
- className="reader relative flex h-48 min-h-0 flex-col overflow-y-auto rounded-[2px] lg:h-auto lg:flex-[2_1_0%]"
- >
- <ul>
- {railCues.map((c, i) => {
- const outside = c.start < view.from - 0.02 || c.end > view.to + 0.02;
- const prev = railCues[i - 1];
- const prevOutside = prev
- ? prev.start < view.from - 0.02 || prev.end > view.to + 0.02
- : outside;
- // The cache edge, drawn once, where the material stops being
- // on disk. Reading past it is free; playing past it is not.
- const rule = i > 0 && prevOutside !== outside;
- const inSel = c.end > sel.from && c.start < sel.to;
- const playing = playhead != null && playhead >= c.start && playhead < c.end;
- const owner = siblingAt(c);
- return (
- <li key={`t-${c.start}-${c.end}`}>
- {rule && (
- <div
- data-cache-rule={outside ? "end" : "start"}
- className="flex items-center gap-2 border-t border-dashed border-reader-2 px-2 py-0.5 text-[10px] uppercase tracking-wider text-reader-dim"
- >
- {outside ? "not fetched — reading only" : "cached from here"}
- </div>
- )}
- <button
- type="button"
- data-tcue={c.start}
- data-peek={outside ? "1" : "0"}
- data-in-sibling={owner ? owner.id : ""}
- title={
- outside
- ? `not fetched — click to fetch to ${padLabelForCue(c)}`
- : "click to play from here"
- }
- onClick={() => {
- if (outside) {
- if (!atMaxPad) void fetchMore(padsForCue(c));
- return;
- }
- void play(c.start, Math.min(c.end + 4, view.to));
- }}
- className={`flex w-full items-baseline gap-3 px-2.5 py-[3px] text-left hover:bg-[color-mix(in_srgb,var(--reader-signal)_6%,transparent)] ${
- inSel ? "bg-[color-mix(in_srgb,var(--reader-signal)_11%,transparent)]" : ""
- } ${playing ? "border-l-[3px] border-reader-signal" : "border-l-[3px] border-transparent"}`}
- >
- <span
- className={`num w-10 shrink-0 font-mono text-[10.5px] ${
- playing ? "font-semibold text-reader-signal" : "text-reader-dim"
- }`}
- >
- {clock(c.start)}
- </span>
- <span
- className={`min-w-0 font-serif text-[15px] leading-snug ${
- outside ? "text-reader-dim opacity-70" : inSel || playing ? "text-reader-ink" : "text-reader-2"
- }`}
- >
- {owner && (
- <span
- className="mr-1.5 rounded-[2px] border border-reader-2 px-1 font-mono text-[10px] text-reader-ink"
- title={`already in the cut as ${owner.id} (${owner.where})`}
- >
- {owner.id}
- </span>
- )}
- {c.endsSentence && (
- <span className="mr-1 font-mono text-[11px] text-reader-dim" aria-hidden>
- ¶
- </span>
- )}
- {c.text}
- </span>
- </button>
- </li>
- );
- })}
- </ul>
-
- {/* ---- the pane's own footer ----
- The controls that act on this pane live in it, stuck to the
- bottom of its scrollport: they cost the pane a line and the
- left column nothing, and "peek further" ends up beside the
- dimmed lines it widens. Opaque, because it sits over text. */}
- <div className="micro sticky bottom-0 z-10 flex flex-wrap items-center gap-2 border-t border-reader-seam bg-reader px-2.5 py-1">
- <span>click a line to play it</span>
- {peek.length > 0 && (
- <>
- <span>· dimmed lines are not fetched — click to fetch</span>
- <button
- type="button"
- data-peek-further=""
- className="ml-auto text-reader-signal hover:underline"
- onClick={() => setPeekPad((n) => n + PEEK_STEP)}
- >
- peek further (±{peekPad + PEEK_STEP} s)
- </button>
- </>
- )}
- </div>
- </div>
-
{/* ---- the warnings ----
Still unfolded, and deliberately: a warning behind a summary is a
warning nobody reads. They are one line each instead. */}
@@ -2573,7 +2721,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
</span>
<button
type="button"
- className={buttonVariants({ variant: "primary", size: "sm" })}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
onClick={() =>
void save({
start: round2(sel.from),
@@ -2690,7 +2838,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
<button
type="button"
data-rerender=""
- className={buttonVariants({ variant: "primary", size: "sm" })}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
disabled={!!busy}
onClick={() => void rerender()}
>
@@ -2825,45 +2973,6 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
{/* ---- THE ANSWER: on screen for every clip, never scrolled to ---- */}
<div data-clip-answer="" className="flex flex-col gap-2 lg:flex-none">
- <div className="flex flex-wrap items-center gap-2">
- <span className="text-[var(--color-text)]">Is this accurate?</span>
- <button
- type="button"
- data-verdict-yes=""
- className={buttonVariants({ variant: "primary", size: "sm" })}
- disabled={!!busy}
- onClick={() => void confirmClip()}
- >
- Yes, confirmed <kbd>y</kbd>
- </button>
- <button
- type="button"
- data-verdict-no=""
- className={buttonVariants({ size: "sm" })}
- onClick={rejectClip}
- >
- No, note what is wrong <kbd>x</kbd>
- </button>
- <span
- data-verdict-state=""
- className={
- verdict === "confirmed"
- ? "text-[var(--color-good)]"
- : verdict === "incorrect"
- ? "text-[var(--color-dirty)]"
- : "text-[var(--color-dim)]"
- }
- >
- {verdictLabel(clip)}
- </span>
- {needNote && !draft.correction.trim() && (
- <span className="text-[11px] text-[var(--color-dirty)]">
- the note is the answer — type it below, then blur or <kbd>Enter</kbd>. Saving
- stays here, so you can read it back against the clip.
- </span>
- )}
- </div>
-
{data.sourceTitle == null && (
<div className="text-[11px] leading-snug text-[var(--color-dirty)]">
No cue file was found for this source, so the archived record’s own title and
@@ -3050,5 +3159,6 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
</div>
</div>
</div>
+ </BenchBody>
);
}
diff --git a/umtool/components/projects/ClipBenchPage.tsx b/umtool/components/projects/ClipBenchPage.tsx
@@ -1,6 +1,6 @@
import { notFound } from "next/navigation";
-import AppShell from "@/components/shell/AppShell";
-import { browseHref } from "@/lib/hrefs";
+import { browseHref, clipBenchHref } from "@/lib/hrefs";
+import { BenchFrame, BenchTop } from "./bench/BenchShell";
import ClipBench, { type ClipBenchData } from "./ClipBench";
import { manifestToken } from "@/lib/report/manifest.mjs";
import {
@@ -167,24 +167,34 @@ export default async function ClipBenchPage({
// The piece this view belongs to: the article's when an article claims the project (P4a-2).
const back = await pieceHrefOfProject(project.id, { tab: "cut" });
+ const href = (id: string) => clipBenchHref(project.id, id);
return (
- <div className="flex h-full flex-col">
- {/* A bench: the rail collapses and the work takes the width. */}
- <AppShell
- active="browse"
- rail="collapsed"
- crumbs={[
- { href: browseHref(), label: "projects" },
- { href: back, label: project.name },
- { label: clipId },
- ]}
- // The progress reading moved INTO the bench, where pressing `y` can
- // move it. What is left here is which source is playing.
- note={`${entry.video}${entry.channel ? ` · ${entry.channel}` : ""}`}
- />
- <main className="deck-main flex-1 p-4">
- <ClipBench data={data} />
- </main>
- </div>
+ // The bench shell (P4b): its top bar here, the body -- the work, the
+ // verdict bar, the reader -- in ClipBench, which owns their state.
+ <BenchFrame
+ kind="clip"
+ top={
+ <BenchTop
+ trail={[{ href: browseHref(), label: "projects" }]}
+ back={{ href: back, label: project.name }}
+ kind="Clip bench"
+ here={clipId}
+ pos={{ index: i + 1, total: clips.length }}
+ prev={prev ? { href: href(prev), label: prev, attrs: { "data-clip-nav": "prev" } } : null}
+ next={next ? { href: href(next), label: next, attrs: { "data-clip-nav": "next" } } : null}
+ keys={[
+ { keys: ["y"], label: "confirm" },
+ { keys: ["x"], label: "note" },
+ { keys: ["[", "]", ",", "."], label: "nudge" },
+ { keys: ["space"], label: "play" },
+ { keys: ["p", "n"], label: "walk" },
+ ]}
+ // Which source is playing.
+ note={`${entry.video}${entry.channel ? ` · ${entry.channel}` : ""}`}
+ />
+ }
+ >
+ <ClipBench data={data} />
+ </BenchFrame>
);
}
diff --git a/umtool/components/projects/DraftPanel.tsx b/umtool/components/projects/DraftPanel.tsx
@@ -1,33 +1,57 @@
"use client";
-import Link from "next/link";
-import { useRouter } from "next/navigation";
-import { useCallback, useEffect, useRef, useState } from "react";
-import { badgeVariants } from "@/components/ui/badge";
+import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
-import { reviewHref } from "@/lib/hrefs";
-import { DraftAlternatives, DraftBadge, announceDraftsChanged, useDrafts } from "./drafts";
-import { announceManifestChanged } from "./timelineApi";
+import { EditorJobProgress, type EditorJob } from "@/components/ui/job-progress";
import type { DraftRowView, DraftRunSummary, ProjectIteration } from "@/lib/articles/projectDraft";
-// DRAFT WITH <MODEL> (release 28 M9): each draftable section of the cut —
-// the cut, on-screen, teaser, flips, threads, narration, YouTube — drafted by
-// a model as a `report-draft` step on the iteration the project was made
-// from (umtool's /api/articles/generate → the editor). The models are the
-// policy's, the task's route preselected; `force` re-drafts only fields a
-// model drafted (a field you wrote or edited is never replaced — its draft is
-// kept as an alternative); a per-entry task may be limited to the entries
-// ticked. While the job runs its progress shows; when it ends the page is
-// re-read: the badges, the alternatives with Use this, and what the task's
-// draft file says it wrote, skipped and refused.
+// DRAFT WITH <MODEL> (release 28 M9; the Media tab's section heads since P4b):
+// a draftable section of the cut — the cut, on-screen, teaser, flips,
+// threads, narration, YouTube — drafted by a model as a `report-draft` step
+// on the iteration the project was made from (umtool's /api/articles/generate
+// → the editor). The models are the policy's, the task's route preselected;
+// `force` re-drafts only fields a model drafted (a field you wrote or edited
+// is never replaced — its draft is kept as an alternative); a per-entry task
+// may be limited to the entries ticked. While the job runs it is the ONE
+// JobProgress; when it ends the surface is re-read, and the row says what the
+// task's draft file says it wrote, skipped and refused.
-type Policy = { generation: { routes: Record<string, string>; models: { api: string; local: string } }; models: { api: string[]; local: string[] } };
-type JobView = { status: string; queue: { key?: string; position?: number } | null; progress: { metric: string; current: number; target: number } | null; tail: string[] };
+export type Policy = { generation: { routes: Record<string, string>; models: { api: string; local: string } }; models: { api: string[]; local: string[] } };
-const field = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)]";
+/** The generation policy, asked of the editor once (null until it answers; the error says why not). */
+export function usePolicy(enabled: boolean): { policy: Policy | null; error: string } {
+ const [policy, setPolicy] = useState<Policy | null>(null);
+ const [error, setError] = useState("");
+ useEffect(() => {
+ if (!enabled) return;
+ let alive = true;
+ void (async () => {
+ const r = await fetch("/api/articles/policy", { cache: "no-store" }).catch(() => null);
+ const b = r ? await r.json().catch(() => ({})) : {};
+ if (!alive) return;
+ if (r?.ok && b.policy) setPolicy(b.policy as Policy);
+ else setError(b.error ?? "the editor did not answer");
+ })();
+ return () => {
+ alive = false;
+ };
+ }, [enabled]);
+ return { policy, error };
+}
+
+/** The models a task may draft with, its route's first. */
+export function modelsFor(policy: Policy | null, task: string): { route: string; models: string[] } {
+ const g = policy?.generation;
+ const route = g ? (g.routes[task] === "api" ? g.models.api : g.models.local) : "";
+ const models = policy ? [...new Set([route, ...policy.models.api, ...policy.models.local].filter(Boolean))] : [];
+ return { route, models };
+}
+
+const field = "rounded-[3px] border border-seam-2 bg-ground px-1.5 py-0.5 text-[12px] text-text";
const ENDED = ["done", "failed", "cancelled"];
-function RunLine({ run }: { run: DraftRunSummary }) {
+/** What the task's last run here left in its draft file. */
+export function RunLine({ run }: { run: DraftRunSummary }) {
const c = run.counts;
const parts = [
c.applied ? `${c.applied} written` : "",
@@ -39,18 +63,18 @@ function RunLine({ run }: { run: DraftRunSummary }) {
const failing = run.checks.filter((ch) => !ch.ok);
const problems = run.units.filter((u) => u.outcome === "refused" || u.outcome === "kept" || u.outcome === "none");
return (
- <div data-draft-run={run.task} className="mt-1 text-[11px] text-[var(--color-dim)]">
+ <div data-draft-run={run.task} className="text-[11.5px] text-muted">
<span>
last run{run.model ? <span className="font-mono"> {run.model}</span> : null}
{run.at ? `, ${new Date(run.at).toLocaleString()}` : ""}: {parts.join(" · ") || "nothing"}
</span>
{failing.map((ch) => (
- <p key={ch.name} data-draft-check={ch.name} className="text-[var(--color-dirty)]">
+ <p key={ch.name} data-draft-check={ch.name} className="m-0 text-doubt-text">
check {ch.name}: {ch.detail ?? "failed"}
</p>
))}
{problems.length > 0 && (
- <ul className="list-disc pl-4">
+ <ul className="m-0 list-disc pl-4">
{problems.slice(0, 8).map((u) => (
<li key={u.id} data-draft-unit={u.id} data-draft-outcome={u.outcome}>
<span className="font-mono">{u.label ?? u.id}</span>: {u.why ?? u.outcome}
@@ -63,28 +87,26 @@ function RunLine({ run }: { run: DraftRunSummary }) {
);
}
-function DraftRow({
- project,
+/**
+ * One section's "Draft with <model>": the button, the model, force, the
+ * entries; then the job, followed; then the last run.
+ */
+export function DraftControl({
row,
link,
policy,
run,
runningJob,
- view,
onEnded,
}: {
- project: string;
row: DraftRowView;
link: Extract<ProjectIteration, { ok: true }>;
policy: Policy | null;
run: DraftRunSummary | undefined;
runningJob: string | null;
- view: ReturnType<typeof useDrafts>;
onEnded: () => void | Promise<void>;
}) {
- const g = policy?.generation;
- const routeModel = g ? (g.routes[row.task] === "api" ? g.models.api : g.models.local) : "";
- const models = policy ? [...new Set([routeModel, ...policy.models.api, ...policy.models.local].filter(Boolean))] : [];
+ const { route: routeModel, models } = modelsFor(policy, row.task);
const [model, setModel] = useState(routeModel);
useEffect(() => {
if (!model && routeModel) setModel(routeModel);
@@ -92,7 +114,7 @@ function DraftRow({
const [force, setForce] = useState(false);
const [picked, setPicked] = useState<string[]>([]);
const [jobId, setJobId] = useState<string | null>(runningJob);
- const [job, setJob] = useState<JobView | null>(null);
+ const [ended, setEnded] = useState<EditorJob | null>(null);
const [error, setError] = useState("");
const [sending, setSending] = useState(false);
@@ -100,43 +122,7 @@ function DraftRow({
if (runningJob) setJobId(runningJob);
}, [runningJob]);
- // The latest callback, so the poll below depends on the job alone; and each
- // job's end is told once (a re-render after the refresh must not tell it again).
- const ended = useRef(onEnded);
- ended.current = onEnded;
- const told = useRef<string | null>(null);
- useEffect(() => {
- if (!jobId) return;
- let alive = true;
- let stop = false;
- const tick = async () => {
- if (stop) return;
- try {
- const r = await fetch(`/api/articles/job?id=${encodeURIComponent(jobId)}&tail=6`, { cache: "no-store" });
- const b = await r.json();
- if (!alive) return;
- if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
- setJob(b.job);
- if (ENDED.includes(b.job.status)) {
- stop = true;
- if (told.current !== jobId) {
- told.current = jobId;
- void ended.current();
- }
- }
- } catch (e) {
- if (alive) setError((e as Error).message);
- }
- };
- void tick();
- const t = setInterval(tick, 2000);
- return () => {
- alive = false;
- clearInterval(t);
- };
- }, [jobId]);
-
- const active = !!jobId && !!job && !ENDED.includes(job.status);
+ const active = !!jobId && !ended;
const start = async () => {
setError("");
setSending(true);
@@ -152,7 +138,7 @@ function DraftRow({
const r = await fetch("/api/articles/generate", { method: "POST", body: JSON.stringify(body) });
const b = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
- setJob(null);
+ setEnded(null);
setJobId(String(b.jobId));
} catch (e) {
setError((e as Error).message);
@@ -160,30 +146,16 @@ function DraftRow({
setSending(false);
}
};
- const cancel = async () => {
- if (!jobId) return;
- const r = await fetch("/api/articles/job", { method: "POST", body: JSON.stringify({ cancel: jobId }) });
- if (!r.ok) setError(((await r.json().catch(() => ({}))) as { error?: string }).error ?? `HTTP ${r.status}`);
- };
- const p = job?.progress;
- const queued = job?.status === "queued" && (job.queue?.position ?? 0) > 0;
return (
- <li data-draft-task={row.task} data-draft-job={job?.status ?? (jobId ? "asking" : "")} className="border-t border-[var(--color-line)] py-1.5 first:border-t-0">
- <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
- <h3 className="text-[13px] text-[var(--color-text)]">{row.label}</h3>
- <span className="text-[11px] text-[var(--color-dim)]">{row.writes}</span>
- <span data-draft-state="" className="ml-auto text-[11px]">
- {row.state}
- </span>
- </div>
+ <div data-draft-task={row.task} data-draft-job={ended?.status ?? (jobId ? "running" : "")} className="space-y-1.5">
{row.blocked ? (
- <p data-draft-blocked="" className="text-[11px] text-[var(--color-dim)]">
+ <p data-draft-blocked="" className="m-0 text-[12px] text-muted">
{row.blocked}
</p>
) : (
- <div className="mt-1 flex flex-wrap items-center gap-2">
- <Button size="sm" variant="primary" aria-label={`Draft ${row.label}`} disabled={!policy || sending || active} onClick={() => void start()}>
+ <div className="flex flex-wrap items-center gap-2">
+ <Button size="sm" variant="outline" aria-label={`Draft ${row.label}`} disabled={!policy || sending || active} onClick={() => void start()}>
Draft with
</Button>
<select aria-label={`model for ${row.label}`} className={`${field} font-mono`} value={model} onChange={(e) => setModel(e.target.value)} disabled={!policy}>
@@ -194,13 +166,13 @@ function DraftRow({
</option>
))}
</select>
- <label className="flex items-center gap-1 text-[11px] text-[var(--color-dim)]">
+ <label className="flex items-center gap-1 text-[11.5px] text-muted" title="re-drafts only what a model drafted; a field you wrote or edited is never replaced">
<input type="checkbox" checked={force} onChange={(e) => setForce(e.target.checked)} aria-label={`force: re-draft ${row.label}`} />
- force — re-drafts only what a model drafted; a field you wrote or edited is never replaced
+ force
</label>
{row.entries && row.entries.length > 0 && (
- <details className="text-[11px]">
- <summary className="cursor-pointer text-[var(--color-dim)]">{picked.length ? `${picked.length} of ${row.entries.length} entries` : `every entry (${row.entries.length})`}</summary>
+ <details className="text-[11.5px]">
+ <summary className="cursor-pointer text-muted">{picked.length ? `${picked.length} of ${row.entries.length} entries` : `every entry (${row.entries.length})`}</summary>
<div className="mt-1 flex max-h-40 flex-col gap-0.5 overflow-auto">
{row.entries.map((e) => (
<label key={e.id} className="flex items-center gap-1">
@@ -218,139 +190,30 @@ function DraftRow({
)}
</div>
)}
- {jobId && job && !ENDED.includes(job.status) && (
- <div data-draft-progress={row.task} className="mt-1 flex flex-wrap items-center gap-2 text-[11px]">
- <span role="status" className="text-[var(--color-dirty)]">
- {queued ? `queued, ${job.queue?.position} ahead on ${job.queue?.key}` : job.status}
- {p ? ` — ${p.metric} ${p.current}/${p.target}` : ""}
- </span>
- {job.tail.length > 0 && <span className="truncate font-mono text-[var(--color-dim)]">{job.tail[job.tail.length - 1]}</span>}
- <Button size="sm" variant="destructive" aria-label={`Cancel the ${row.label} draft`} onClick={() => void cancel()}>
- Cancel
- </Button>
- </div>
+ {jobId && !ended && (
+ <EditorJobProgress
+ data-draft-progress={row.task}
+ jobId={jobId}
+ cancelName={`Cancel the ${row.label} draft`}
+ onEnd={(j) => {
+ // A Cancel answers before the editor has said so: it is cancelled.
+ setEnded(j && ENDED.includes(j.status) ? j : { id: jobId, kind: null, status: "cancelled", queue: null, progress: null, tail: j?.tail ?? [] });
+ void onEnded();
+ }}
+ />
)}
- {jobId && job && ENDED.includes(job.status) && (
- <p data-draft-ended={job.status} className={`mt-1 text-[11px] ${job.status === "done" ? "text-[var(--color-dim)]" : "text-[var(--color-bad)]"}`}>
- the draft {job.status === "done" ? "is done" : job.status}
- {job.status !== "done" && job.tail.length ? `: ${job.tail.filter((l) => !l.startsWith("@@")).slice(-1)[0] ?? ""}` : ""}
+ {jobId && ended && ENDED.includes(ended.status) && (
+ <p data-draft-ended={ended.status} className={`m-0 text-[11.5px] ${ended.status === "done" ? "text-muted" : "text-reject-text"}`}>
+ the draft {ended.status === "done" ? "is done" : ended.status}
+ {ended.status !== "done" && ended.tail.length ? `: ${ended.tail.filter((l) => !l.startsWith("@@")).slice(-1)[0] ?? ""}` : ""}
</p>
)}
{run && <RunLine run={run} />}
- {row.address && (
- <div className="mt-1">
- <DraftBadge address={row.address} view={view.view} act={view.act} compact />
- <DraftAlternatives address={row.address} view={view.view} act={view.act} />
- </div>
- )}
- {!row.address && run && run.alternatives > 0 && (
- <Link href={reviewHref(project)} className="ink-link text-[11px]">
- {run.alternatives} alternative(s) kept — review them
- </Link>
- )}
{error && (
- <p role="alert" className="mt-1 text-[11px] text-[var(--color-bad)]">
+ <p role="alert" className="m-0 text-[11.5px] text-reject-text">
{error}
</p>
)}
- </li>
- );
-}
-
-export default function DraftPanel({
- project,
- link,
- rows,
- runs: initialRuns,
-}: {
- project: string;
- link: ProjectIteration;
- rows: DraftRowView[];
- runs: Partial<Record<string, DraftRunSummary>>;
-}) {
- const router = useRouter();
- const view = useDrafts(project);
- const [policy, setPolicy] = useState<Policy | null>(null);
- const [policyError, setPolicyError] = useState("");
- const [runs, setRuns] = useState(initialRuns);
- const [running, setRunning] = useState<Record<string, string>>(link.ok ? link.running : {});
-
- useEffect(() => {
- if (!link.ok) return;
- let alive = true;
- void (async () => {
- const r = await fetch("/api/articles/policy", { cache: "no-store" }).catch(() => null);
- const b = r ? await r.json().catch(() => ({})) : {};
- if (!alive) return;
- if (r?.ok && b.policy) setPolicy(b.policy as Policy);
- else setPolicyError(b.error ?? "the editor did not answer");
- })();
- return () => {
- alive = false;
- };
- }, [link.ok]);
-
- // A draft ended: the manifest changed under every section — re-read it all.
- const onEnded = useCallback(async (): Promise<void> => {
- const r = await fetch(`/api/articles/draft?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null);
- if (r?.ok) {
- const b = await r.json();
- setRuns(b.runs ?? {});
- if (b.link?.ok) setRunning(b.link.running ?? {});
- }
- announceManifestChanged(project);
- announceDraftsChanged(project);
- router.refresh();
- }, [project, router]);
-
- return (
- <section aria-label="draft with a model" data-draft-panel={link.ok ? `${link.article}/i${link.n}` : ""} className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2">
- <div className="mb-1 flex flex-wrap items-baseline gap-3">
- <h2 className="micro">draft</h2>
- {link.ok && (
- <span className="text-[11px] text-[var(--color-dim)]">
- steps on{" "}
- <Link href={`/articles/${link.article}?tab=iterations`} className="ink-link font-mono">
- {link.article} i{link.n}
- </Link>
- </span>
- )}
- {link.ok && (
- <span className={badgeVariants({ variant: "info", size: "sm" })}>a final build refuses a draft nobody approved</span>
- )}
- </div>
- {!link.ok ? (
- <p data-draft-unlinked="" className="text-[12px] text-[var(--color-dim)]">
- {link.why}
- </p>
- ) : link.status !== "done" ? (
- <p data-draft-unlinked="" className="text-[12px] text-[var(--color-dim)]">
- {link.article} i{link.n} is {link.status}: a draft runs over a done iteration
- </p>
- ) : (
- <>
- {policyError && (
- <p role="alert" className="text-[12px] text-[var(--color-bad)]">
- {policyError}: drafting needs the editor
- </p>
- )}
- <ul>
- {rows.map((row) => (
- <DraftRow
- key={row.task}
- project={project}
- row={row}
- link={link}
- policy={policy}
- run={runs[row.task]}
- runningJob={running[row.task] ?? null}
- view={view}
- onEnded={onEnded}
- />
- ))}
- </ul>
- </>
- )}
- </section>
+ </div>
);
}
diff --git a/umtool/components/projects/DraftsReview.tsx b/umtool/components/projects/DraftsReview.tsx
@@ -1,90 +0,0 @@
-"use client";
-
-import Link from "next/link";
-import { narrationHref, projectHref } from "@/lib/hrefs";
-import { DraftAlternatives, DraftBadge, useDrafts, type DraftsView } from "./drafts";
-
-// `/browse/<project>/review`'s list (release 28, M0): every drafted field of
-// the cut -- who drafted it, its value as words, its review -- and every
-// alternative a draft task kept, with "Use this". A narration's words are
-// edited and played on the narration page; here they are judged like any
-// other draft.
-
-export default function DraftsReview({ project, initial }: { project: string; initial: DraftsView }) {
- const { view, act } = useDrafts(project, initial);
- const v = view ?? initial;
- const drafted = v.rows.filter((r) => r.drafted);
- const shown = new Set(drafted.map((r) => r.address));
- // Alternatives for fields that are not drafted (the operator's), by field.
- const loose = [...new Set(v.alternatives.filter((a) => !a.inUse && !shown.has(a.address)).map((a) => a.address))];
- const where = (entry: string | null, field: string) => (entry ? `${entry}` : field);
- return (
- <div className="space-y-3">
- <p
- data-drafts-gate={v.gate.errors.length ? "refuses" : "passes"}
- data-gate-errors={v.gate.errors.length}
- className="text-[11px] text-[var(--color-dim)]"
- >
- {v.error ? (
- <span className="text-[var(--color-bad)]">{v.error}</span>
- ) : v.gate.errors.length ? (
- <>
- A final build refuses {v.gate.errors.length} field{v.gate.errors.length === 1 ? "" : "s"} until approved (
- <code className="font-mono">--drafts-unreviewed</code> builds the unapproved anyway; never a rejected one).
- </>
- ) : (
- <>A final build takes every draft as it is.</>
- )}{" "}
- Verdicts in <code className="font-mono">{v.file}</code>.
- </p>
- {drafted.length === 0 && loose.length === 0 && (
- <p data-drafts-empty="" className="text-[12px] text-[var(--color-dim)]">
- Nothing in this cut was drafted.{" "}
- <Link href={projectHref(project, { tab: "media" })} className="ink-link">
- back to {project}
- </Link>
- </p>
- )}
- {drafted.map((r) => (
- <article
- key={r.address}
- data-draft-row={r.address}
- data-state={r.state}
- className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"
- >
- <div className="mb-1 flex flex-wrap items-center gap-2">
- <span className="font-mono text-[12px] text-[var(--color-text)]">{where(r.entry, r.field)}</span>
- <span className="micro">{r.label}</span>
- {r.field === "narration" && (
- <Link href={narrationHref(project)} className="ink-link text-[11px]">
- edit and play on the narration page
- </Link>
- )}
- </div>
- <p data-draft-text="" className="mb-1 whitespace-pre-wrap text-[13px] text-[var(--color-text)]">
- {r.text || "—"}
- </p>
- {r.state === "edited" && r.judgedText && (
- <p className="mb-1 text-[11px] text-[var(--color-dim)]">
- {r.verdict} on: <span className="italic">{r.judgedText}</span>
- </p>
- )}
- <DraftBadge address={r.address} view={v} act={act} />
- <DraftAlternatives address={r.address} view={v} act={act} />
- </article>
- ))}
- {loose.map((address) => {
- const a = v.alternatives.find((x) => x.address === address)!;
- return (
- <article key={address} data-draft-row={address} data-state="operator" className="rounded border border-[var(--color-line)] px-3 py-2">
- <div className="mb-1 flex flex-wrap items-center gap-2">
- <span className="font-mono text-[12px] text-[var(--color-text)]">{where(a.entry, a.field)}</span>
- <span className="micro">{a.label} · yours; a draft was kept aside</span>
- </div>
- <DraftAlternatives address={address} view={v} act={act} />
- </article>
- );
- })}
- </div>
- );
-}
diff --git a/umtool/components/projects/MediaDrafts.tsx b/umtool/components/projects/MediaDrafts.tsx
@@ -0,0 +1,705 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import ChainPanel from "@/components/articles/ChainPanel";
+import { buttonVariants } from "@/components/ui/button";
+import { LitActions, LitGroup, LitLine } from "@/components/ui/lit-line";
+import { LitList, type LitDetail } from "@/components/ui/lit-list";
+import { useHydrated } from "@/components/ui/use-hydrated";
+import { clock } from "@/components/ui/clock";
+import { ReaderPane } from "@/components/ui/reader-pane";
+import { narrationHref, reviewHref } from "@/lib/hrefs";
+import { citationText } from "@/lib/research/facets.mjs";
+import type { DraftRowView, DraftRunSummary, ProjectIteration } from "@/lib/articles/projectDraft";
+import { awaitingReview } from "@/lib/inbox/drafts.mjs";
+import { DraftControl, modelsFor, usePolicy } from "./DraftPanel";
+import { DraftAlternatives, announceDraftsChanged, useDrafts, type DraftAct, type DraftRow, type DraftsView } from "./drafts";
+import { announceManifestChanged } from "./timelineApi";
+import { BenchBody, VerdictBar } from "./bench/BenchShell";
+import CopyCitation from "./bench/CopyCitation";
+
+// ---------------------------------------------------------------------------
+// THE MEDIA SURFACE (plans/umtool-redesign.md, P4b; canvas "Piece · Media"):
+// every drafted field of the cut, one line each -- what it says, where it came
+// from (the model, the attempts, the rule a refused attempt broke), its review
+// -- grouped by the section that drafts it, each section headed by its "Draft
+// with <model>". Approve or reject per field, Approve all, Draft everything.
+// It absorbs release 28's review page (DraftsReview), the project page's Draft
+// panel and the Iterations tab's media drafts: the Media tab draws it with
+// the sections' controls, the review bench (`…/review`) draws its field list
+// alone, one field at a time, with the verdict bar and the reader.
+//
+// The fields are ONE lit list (j/k from anywhere); `a` approves the lit field
+// as it is, `r` rejects it (the note is the answer: the cursor goes there
+// first). Signal is the lit field's Approve draft only.
+// ---------------------------------------------------------------------------
+
+export type FieldProvenance = {
+ file: string;
+ model: string | null;
+ at: string | null;
+ attempts: number;
+ chosen: number | null;
+ repaired: boolean;
+ failed: { attempt: number; hard: string[] }[];
+ soft: string[];
+};
+
+/** The sections, in Draft everything's order: a field's address starts with its section's task. */
+export const MEDIA_SECTIONS: { task: string; label: string }[] = [
+ { task: "cut", label: "Cut" },
+ { task: "onscreen", label: "On-screen" },
+ { task: "teaser", label: "Teaser" },
+ { task: "flips", label: "Flips" },
+ { task: "threads", label: "Threads" },
+ { task: "narrate", label: "Narration" },
+ { task: "youtube", label: "YouTube" },
+];
+const sectionOf = (address: string) => address.split("/")[0];
+
+const STATE_WORDS: Record<DraftRow["state"], string> = {
+ approved: "approved",
+ rejected: "rejected",
+ edited: "changed since approved",
+ unreviewed: "not reviewed",
+};
+const STATE_TONE: Record<DraftRow["state"], string> = {
+ approved: "text-meter",
+ rejected: "text-reject-text",
+ edited: "text-doubt-text",
+ unreviewed: "text-muted-2",
+};
+
+const day = (iso: string | null) => {
+ if (!iso) return null;
+ const d = new Date(iso);
+ return Number.isNaN(d.getTime()) ? null : `${d.toISOString().slice(0, 10)} ${d.toISOString().slice(11, 16)}`;
+};
+
+/** The provenance line: the file, when and by what, the attempts, the rules refused attempts broke, the review. */
+export function ProvenanceLine({ row, prov }: { row: DraftRow; prov: FieldProvenance | null }) {
+ const by = row.drafted?.model ?? prov?.model ?? null;
+ const at = day(row.drafted?.at ?? prov?.at ?? null);
+ const parts: React.ReactNode[] = [];
+ if (prov) parts.push(prov.file);
+ if (row.drafted || prov) parts.push(`drafted${at ? ` ${at}` : ""}${by ? ` by ${by}` : ""}`);
+ else parts.push("written by hand");
+ if (prov) {
+ if (prov.repaired) parts.push(`repaired from ${prov.attempts} attempt${prov.attempts === 1 ? "" : "s"}`);
+ else if (prov.chosen) parts.push(`attempt ${prov.chosen} of ${prov.attempts}${prov.attempts > 1 ? " chosen" : ""}`);
+ for (const f of prov.failed.filter((x) => x.attempt !== prov.chosen)) {
+ parts.push(
+ <span key={`f${f.attempt}`}>
+ attempt {f.attempt} failed: <span className="text-reject-text">✕ {f.hard.join("; ")}</span>
+ </span>,
+ );
+ }
+ if (prov.failed.length === 0 && prov.chosen) parts.push("no rule broken");
+ if (prov.soft.length) parts.push(<span key="soft" className="text-doubt-text">flag: {prov.soft.join("; ")}</span>);
+ } else if (row.drafted) {
+ parts.push(`attempt ${row.drafted.attempt}`);
+ }
+ parts.push(<span key="state" className={STATE_TONE[row.state]}>{STATE_WORDS[row.state]}</span>);
+ return (
+ <div data-draft-prov="" className="mt-1.5 font-mono text-[11px] leading-snug text-muted-2">
+ {parts.map((p, i) => (
+ <span key={i}>
+ {i > 0 && " · "}
+ {p}
+ </span>
+ ))}
+ </div>
+ );
+}
+
+/** One drafted field: its name, its words and provenance, Approve draft / Reject (+ note), its alternatives. */
+function FieldLine({
+ row,
+ prov,
+ view,
+ act,
+ lit,
+ go,
+ noteRef,
+}: {
+ row: DraftRow;
+ prov: FieldProvenance | null;
+ view: DraftsView;
+ act: DraftAct;
+ lit: boolean;
+ /** The lit line's Approve draft is the screen's one filled action (the tab); a bench's is its verdict bar's. */
+ go: boolean;
+ noteRef?: (el: HTMLInputElement | null) => void;
+}) {
+ const [note, setNote] = useState(row.note ?? "");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ useEffect(() => setNote(row.note ?? ""), [row.note]);
+ const run = async (action: string, extra: Record<string, unknown> = {}) => {
+ setBusy(true);
+ setError(null);
+ try {
+ await act(action, { address: row.address, ...extra });
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+ const where = row.entry ? `${sectionLabel(row.address)} · ${row.entry}` : `${sectionLabel(row.address)} · ${row.field}`;
+ return (
+ <LitLine id={row.address} data-draft-row={row.address} data-state={row.state} className="grid gap-x-3.5 gap-y-1 md:grid-cols-[150px_minmax(0,1fr)_auto]">
+ <div className="text-[12.5px] font-medium">
+ {row.entry ?? row.label}
+ <small className="mt-0.5 block font-mono text-[11px] font-normal text-muted-2">{where}</small>
+ </div>
+ <div className="min-w-0">
+ <p data-draft-text="" className={`m-0 max-w-[72ch] whitespace-pre-wrap text-[13.5px] leading-normal ${lit ? "text-text" : ""}`}>
+ {row.text || "—"}
+ </p>
+ {row.state === "edited" && row.judgedText && (
+ <p className="m-0 mt-1 text-[11.5px] text-muted">
+ {row.verdict} on: <span className="italic">{row.judgedText}</span>
+ </p>
+ )}
+ <ProvenanceLine row={row} prov={prov} />
+ <DraftAlternatives address={row.address} view={view} act={act} />
+ {error && (
+ <p data-draft-error="" className="m-0 mt-1 text-[11.5px] text-reject-text">
+ {error}
+ </p>
+ )}
+ </div>
+ <LitActions className="flex-wrap items-start md:w-[240px] md:justify-end">
+ <button
+ type="button"
+ data-draft-action="approve"
+ aria-pressed={row.state === "approved"}
+ disabled={busy}
+ title={row.state === "approved" ? "take the approval back" : "approve this draft as it is now"}
+ className={buttonVariants({ variant: row.state !== "approved" && lit && go ? "go" : "outline", size: "sm" })}
+ onClick={() => void run(row.state === "approved" ? "clear" : "approve", row.state === "approved" ? {} : { note })}
+ >
+ {row.state === "approved" ? "Approved" : "Approve draft"}
+ </button>
+ <button
+ type="button"
+ data-draft-action="reject"
+ aria-pressed={row.state === "rejected"}
+ disabled={busy}
+ title="reject this draft; the note says what is wrong"
+ className={buttonVariants({ variant: row.state === "rejected" ? "destructive" : "outline", size: "sm" })}
+ onClick={() => void run(row.state === "rejected" ? "clear" : "reject", row.state === "rejected" ? {} : { note })}
+ >
+ {row.state === "rejected" ? "Rejected" : "Reject"}
+ </button>
+ {row.field === "narration" && row.entry && (
+ <Link href={narrationHref(viewProject(view))} className="ink-link self-center text-[11.5px]">
+ edit and play
+ </Link>
+ )}
+ <input
+ ref={noteRef}
+ value={note}
+ onChange={(e) => setNote(e.target.value)}
+ onBlur={() => {
+ if (note.trim() !== (row.note ?? "") && row.verdict) void run("note", { note });
+ }}
+ disabled={busy}
+ placeholder="note (a rejection needs one)"
+ aria-label={`note on the draft of ${row.address}`}
+ data-draft-note=""
+ maxLength={2000}
+ className="w-full min-w-0 rounded-[3px] border border-seam-2 bg-ground px-1.5 py-0.5 text-[11.5px] text-text"
+ />
+ </LitActions>
+ </LitLine>
+ );
+}
+
+// The project id rides on the view so a line can link its narration page.
+const viewProject = (v: DraftsView) => (v as DraftsView & { project?: string }).project ?? "";
+const sectionLabel = (address: string) => MEDIA_SECTIONS.find((s) => s.task === sectionOf(address))?.label ?? sectionOf(address);
+
+/** A field that is the operator's, with a draft kept aside for it. */
+function LooseLine({ address, view, act }: { address: string; view: DraftsView; act: DraftAct }) {
+ const a = view.alternatives.find((x) => x.address === address)!;
+ return (
+ <LitLine id={address} data-draft-row={address} data-state="operator" className="grid gap-x-3.5 gap-y-1 md:grid-cols-[150px_minmax(0,1fr)]">
+ <div className="text-[12.5px] font-medium">
+ {a.entry ?? a.label}
+ <small className="mt-0.5 block font-mono text-[11px] font-normal text-muted-2">yours · a draft kept aside</small>
+ </div>
+ <div className="min-w-0">
+ <DraftAlternatives address={address} view={view} act={act} />
+ </div>
+ </LitLine>
+ );
+}
+
+export type MediaFieldsProps = {
+ project: string;
+ view: DraftsView;
+ act: DraftAct;
+ provenance: Record<string, FieldProvenance>;
+ /** The sections' heads: the Media tab's "Draft with" per task; the bench has none. */
+ heads?: Partial<Record<string, React.ReactNode>>;
+ /** Only these sections (a chip's filter). */
+ only?: string | null;
+ onLit?: (address: string | null) => void;
+ /** The lit field's Approve draft is filled (false on a bench: the verdict bar's is). */
+ lineGo?: boolean;
+};
+
+/** The field list: one lit list, grouped by section, `a` / `r` on the lit field. */
+export function MediaFields({ project, view, act, provenance, heads, only = null, onLit, lineGo = true }: MediaFieldsProps) {
+ const rows = view.rows;
+ const shown = new Set(rows.map((r) => r.address));
+ const loose = [...new Set(view.alternatives.filter((a) => !a.inUse && !shown.has(a.address)).map((a) => a.address))];
+ const [lit, setLit] = useState<string | null>(null);
+ const notes = useRef(new Map<string, HTMLInputElement>());
+ const box = useRef<HTMLDivElement>(null);
+ const v = useMemo(() => ({ ...view, project }) as DraftsView, [view, project]);
+
+ const sections = MEDIA_SECTIONS.filter((s) => !only || s.task === only)
+ .map((s) => ({
+ ...s,
+ rows: rows.filter((r) => sectionOf(r.address) === s.task),
+ loose: loose.filter((a) => sectionOf(a) === s.task),
+ }))
+ .filter((s) => heads?.[s.task] || s.rows.length || s.loose.length);
+
+ const onLight = useCallback(
+ (d: LitDetail) => {
+ setLit(d.id);
+ onLit?.(d.id);
+ },
+ [onLit],
+ );
+
+ // `a` approves the lit field as it is; `r` rejects it -- with its note, or
+ // the cursor goes to the note first (the note is the answer).
+ const hydrated = useHydrated();
+ useEffect(() => {
+ if (!hydrated) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return;
+ const t = e.target as HTMLElement | null;
+ if (t?.closest?.("input, textarea, select, video, audio, [contenteditable='true'], dialog[open]")) return;
+ // From the list itself or from nowhere in particular -- never from a
+ // control elsewhere on the tab (the on-screen panel's).
+ if (t && t !== document.body && !box.current?.contains(t)) return;
+ if (e.key !== "a" && e.key !== "r") return;
+ const row = rows.find((r) => r.address === lit);
+ if (!row) return;
+ e.preventDefault();
+ if (e.key === "a") {
+ if (row.state !== "approved") void act("approve", { address: row.address, note: row.note ?? "" }).catch(() => {});
+ return;
+ }
+ const input = notes.current.get(row.address);
+ if (input && !input.value.trim()) {
+ input.focus();
+ return;
+ }
+ void act("reject", { address: row.address, note: input?.value ?? row.note ?? "" }).catch(() => input?.focus());
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [hydrated, rows, lit, act]);
+
+ if (sections.length === 0) {
+ return (
+ <p data-drafts-empty="" className="text-[12.5px] text-muted">
+ Nothing in this cut was drafted.
+ </p>
+ );
+ }
+ return (
+ <div ref={box}>
+ <LitList label="Drafted fields" global onLight={onLight}>
+ {sections.map((s) => (
+ <LitGroup
+ key={s.task}
+ data-media-section={s.task}
+ id={`media-${s.task}`}
+ title={s.label}
+ count={s.rows.length || undefined}
+ className="pt-1"
+ >
+ {heads?.[s.task] && <div className="border-b border-seam px-0 py-2.5">{heads[s.task]}</div>}
+ {s.rows.map((r) => (
+ <FieldLine
+ key={r.address}
+ row={r}
+ prov={provenance[r.address] ?? null}
+ view={v}
+ act={act}
+ lit={lit === r.address}
+ go={lineGo}
+ noteRef={(el) => {
+ if (el) notes.current.set(r.address, el);
+ else notes.current.delete(r.address);
+ }}
+ />
+ ))}
+ {s.loose.map((a) => (
+ <LooseLine key={a} address={a} view={v} act={act} />
+ ))}
+ </LitGroup>
+ ))}
+ </LitList>
+ </div>
+ );
+}
+
+/** The gate line: what a final build would say of the review. */
+export function GateLine({ view }: { view: DraftsView }) {
+ return (
+ <p data-drafts-gate={view.gate.errors.length ? "refuses" : "passes"} data-gate-errors={view.gate.errors.length} className="m-0 text-[12px] text-muted">
+ {view.error ? (
+ <span className="text-reject-text">{view.error}</span>
+ ) : view.gate.errors.length ? (
+ <>
+ A final build refuses {view.gate.errors.length} field{view.gate.errors.length === 1 ? "" : "s"} until approved (
+ <code className="font-mono">--drafts-unreviewed</code> builds the unapproved anyway; never a rejected one).
+ </>
+ ) : (
+ <>A final build takes every draft as it is.</>
+ )}{" "}
+ Verdicts in <code className="font-mono">{view.file}</code>.
+ </p>
+ );
+}
+
+/** Approve every field still to review, one after another. */
+export function ApproveAll({ view, act, provenance }: { view: DraftsView; act: DraftAct; provenance: Record<string, FieldProvenance> }) {
+ const hydrated = useHydrated();
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const todo = awaitingReview(view.rows, provenance);
+ if (!todo.length) return null;
+ return (
+ <>
+ <button
+ type="button"
+ data-approve-all={todo.length}
+ disabled={!hydrated || busy}
+ className={buttonVariants({ variant: "outline", size: "md" })}
+ title="approve every drafted field awaiting review, as it is now"
+ onClick={async () => {
+ setBusy(true);
+ setError(null);
+ try {
+ for (const r of todo) await act("approve", { address: r.address, note: r.note ?? "" });
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setBusy(false);
+ }
+ }}
+ >
+ {busy ? "approving…" : `Approve all ${todo.length}`}
+ </button>
+ {error && <span className="text-[12px] text-reject-text">{error}</span>}
+ </>
+ );
+}
+
+// ─── the Media tab ───────────────────────────────────────────────────────────
+
+export default function MediaDrafts({
+ project,
+ initial,
+ provenance,
+ link,
+ rows,
+ runs: initialRuns,
+ narrated,
+}: {
+ project: string;
+ initial: DraftsView;
+ provenance: Record<string, FieldProvenance>;
+ link: ProjectIteration;
+ rows: DraftRowView[];
+ runs: Partial<Record<string, DraftRunSummary>>;
+ /** Narrated cards: the narration bench's link. */
+ narrated: number;
+}) {
+ const router = useRouter();
+ const drafts = useDrafts(project, initial);
+ const view = drafts.view ?? initial;
+ const linked = link.ok && link.status === "done";
+ const { policy, error: policyError } = usePolicy(linked);
+ const [runs, setRuns] = useState(initialRuns);
+ const [running, setRunning] = useState<Record<string, string>>(link.ok ? link.running : {});
+ const [only, setOnly] = useState<string | null>(null);
+ const [allModel, setAllModel] = useState("");
+ const [allRun, setAllRun] = useState(0);
+ const allModels = modelsFor(policy, "onscreen");
+ useEffect(() => {
+ if (!allModel && allModels.route) setAllModel(allModels.route);
+ }, [allModels.route, allModel]);
+
+ // A draft ended: the manifest changed under every section -- re-read it all.
+ const onEnded = useCallback(async (): Promise<void> => {
+ const r = await fetch(`/api/articles/draft?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null);
+ if (r?.ok) {
+ const b = await r.json();
+ setRuns(b.runs ?? {});
+ if (b.link?.ok) setRunning(b.link.running ?? {});
+ }
+ announceManifestChanged(project);
+ announceDraftsChanged(project);
+ router.refresh();
+ }, [project, router]);
+
+ // A section's head: what it writes, what it holds, its Draft with. A cut
+ // made from no iteration drafts nothing, so only the narration's head (its
+ // bench's link) is drawn there.
+ const heads: Record<string, React.ReactNode> = {};
+ for (const row of rows) {
+ if (!linked && !(row.task === "narrate" && narrated > 0)) continue;
+ heads[row.task] = (
+ <div className="space-y-1">
+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-0.5 text-[12px]">
+ <span className="text-muted">{row.writes}</span>
+ <span data-draft-state="" className="ml-auto font-mono text-[11.5px] text-muted-2">
+ {row.state}
+ </span>
+ </div>
+ {linked ? (
+ <DraftControl row={row} link={link as Extract<ProjectIteration, { ok: true }>} policy={policy} run={runs[row.task]} runningJob={running[row.task] ?? null} onEnded={onEnded} />
+ ) : null}
+ {row.task === "narrate" && narrated > 0 && (
+ <Link href={narrationHref(project)} data-narration-link={narrated} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Narration — {narrated}: edit and play the words →
+ </Link>
+ )}
+ </div>
+ );
+ }
+
+ // Every field on the list, drafted or a narration written by hand (the
+ // view's own counts are the drafted fields', the final gate's).
+ const total = view.rows.length;
+ const counts = { approved: 0, rejected: 0, edited: 0, unreviewed: 0 };
+ for (const r of view.rows) counts[r.state] += 1;
+ // To review: the drafted fields awaiting a verdict -- the tab's count and the Inbox's (awaitingReview).
+ const waiting = awaitingReview(view.rows, provenance).length;
+ const chips = MEDIA_SECTIONS.map((s) => ({ ...s, n: view.rows.filter((r) => sectionOf(r.address) === s.task).length }));
+ return (
+ <section aria-label="Media drafts" data-draft-panel={link.ok ? `${link.article}/i${link.n}` : ""} className="space-y-3">
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">
+ <span className="font-mono text-[12px] text-meter" data-media-counts="">
+ {total} field{total === 1 ? "" : "s"} · {counts.approved} approved
+ {counts.rejected ? ` · ${counts.rejected} rejected` : ""}
+ {waiting ? ` · ${waiting} to review` : ""}
+ </span>
+ {link.ok && (
+ <span className="text-[12px] text-muted">
+ drafts are steps on{" "}
+ <Link href={`/articles/${link.article}?tab=iterations`} className="ink-link font-mono">
+ {link.article} i{link.n}
+ </Link>
+ </span>
+ )}
+ <span className="ml-auto flex flex-wrap items-center gap-2">
+ {total > 0 && (
+ <Link href={reviewHref(project)} data-review-link={total} className={buttonVariants({ variant: "quiet", size: "md" })}>
+ Review drafts — {total}
+ </Link>
+ )}
+ {linked && (
+ <>
+ <select aria-label="Draft everything model" className="rounded-[3px] border border-seam-2 bg-ground px-1.5 py-1 font-mono text-[12px]" value={allModel} onChange={(e) => setAllModel(e.target.value)} disabled={!policy}>
+ {allModels.models.map((m) => (
+ <option key={m} value={m}>
+ {m}
+ </option>
+ ))}
+ </select>
+ <button
+ type="button"
+ data-draft-everything=""
+ className={buttonVariants({ variant: "outline", size: "md" })}
+ disabled={!policy}
+ onClick={() => setAllRun((k) => k + 1)}
+ >
+ Draft everything
+ </button>
+ </>
+ )}
+ <ApproveAll view={view} act={drafts.act} provenance={provenance} />
+ </span>
+ </div>
+ <GateLine view={view} />
+ {!link.ok ? (
+ <p data-draft-unlinked="" title={link.why} className="m-0 text-[12px] text-muted">
+ Not from an article iteration — Draft with is off here.
+ </p>
+ ) : link.status !== "done" ? (
+ <p data-draft-unlinked="" className="m-0 text-[12px] text-muted">
+ {link.article} i{link.n} is {link.status} — Draft with waits for it to finish.
+ </p>
+ ) : (
+ policyError && (
+ <p role="alert" className="m-0 text-[12px] text-reject-text">
+ {policyError}: drafting needs the editor
+ </p>
+ )
+ )}
+ {link.ok && allRun > 0 && <ChainPanel key={allRun} article={link.article} n={link.n} label={`i${link.n}`} mode="draft-all" model={allModel} autoStart />}
+ <div className="flex flex-wrap gap-1.5" role="group" aria-label="Sections">
+ <button type="button" data-media-chip="all" aria-pressed={only === null} onClick={() => setOnly(null)} className={chipClass(only === null)}>
+ All <span className="font-mono text-[11px] text-meter">{total}</span>
+ </button>
+ {chips.map((c) => (
+ <button key={c.task} type="button" data-media-chip={c.task} aria-pressed={only === c.task} onClick={() => setOnly(only === c.task ? null : c.task)} className={chipClass(only === c.task)}>
+ {c.label}
+ {c.n > 0 && <span className="font-mono text-[11px] text-meter">{c.n}</span>}
+ </button>
+ ))}
+ </div>
+ <MediaFields project={project} view={view} act={drafts.act} provenance={provenance} heads={heads} only={only} />
+ </section>
+ );
+}
+
+const chipClass = (on: boolean) =>
+ `inline-flex items-center gap-1.5 whitespace-nowrap rounded-[3px] border px-2 py-[3px] text-[12px] ${on ? "border-muted bg-panel-2 text-text" : "border-seam-2 text-text-2 hover:border-muted"}`;
+
+// ─── the review bench (`…/review`) ───────────────────────────────────────────
+
+export type FieldEvidence = {
+ /** The clip's source, on the reader. */
+ source: string;
+ byline: string[];
+ cite: { at: number; duration: number } | null;
+ quote: string | null;
+ url: string | null;
+ cues: { start: number; text: string }[];
+};
+
+/**
+ * The drafts review as a bench: the field list as the work, ONE question on
+ * the lit field in the verdict bar, and -- for a field drawn over a clip --
+ * that clip's source on the reader, its cited cue lit.
+ */
+export function MediaReview({
+ project,
+ initial,
+ provenance,
+ evidence,
+}: {
+ project: string;
+ initial: DraftsView;
+ provenance: Record<string, FieldProvenance>;
+ evidence: Record<string, FieldEvidence>;
+}) {
+ const drafts = useDrafts(project, initial);
+ const view = drafts.view ?? initial;
+ const [lit, setLit] = useState<string | null>(null);
+ const hydrated = useHydrated();
+ const row = view.rows.find((r) => r.address === lit) ?? null;
+ const todo = awaitingReview(view.rows, provenance);
+ const ev = row?.entry ? (evidence[row.entry] ?? null) : null;
+ const [error, setError] = useState<string | null>(null);
+ const approve = async () => {
+ if (!row) return;
+ setError(null);
+ try {
+ await drafts.act("approve", { address: row.address, note: row.note ?? "" });
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ }
+ };
+ const reject = () => {
+ if (!row) return;
+ const input = document.querySelector<HTMLInputElement>(`[data-draft-row="${CSS.escape(row.address)}"] [data-draft-note]`);
+ if (input && !input.value.trim()) {
+ input.focus();
+ return;
+ }
+ setError(null);
+ drafts.act("reject", { address: row.address, note: input?.value ?? "" }).catch((e) => setError(e instanceof Error ? e.message : String(e)));
+ };
+ const where = row ? (row.entry ? `${row.label} of ${row.entry}` : row.label) : "";
+ const verdict = (
+ <VerdictBar
+ data-verdict-for={row?.address ?? ""}
+ question={
+ row ? (
+ row.state === "approved" ? (
+ <>The {where} is approved.</>
+ ) : (
+ <>Approve the drafted {where}?</>
+ )
+ ) : (
+ <>Nothing to review.</>
+ )
+ }
+ consequence={
+ !row
+ ? undefined
+ : row.state === "approved"
+ ? todo.length
+ ? `${todo.length} still to review.`
+ : "Every field is approved: a final build takes them as they are."
+ : row.state === "rejected"
+ ? `Rejected${row.note ? `: ${row.note}` : ""} — a final build refuses it.`
+ : "A final build refuses it until it is approved."
+ }
+ >
+ {row && row.state !== "approved" && (
+ <button type="button" data-verdict-approve={row.address} disabled={!hydrated} className={buttonVariants({ variant: "go", size: "md" })} onClick={() => void approve()}>
+ Approve draft <kbd>a</kbd>
+ </button>
+ )}
+ {row && row.state !== "rejected" && (
+ <button type="button" data-verdict-reject={row.address} disabled={!hydrated} className={buttonVariants({ size: "md" })} onClick={reject}>
+ Reject with a note <kbd>r</kbd>
+ </button>
+ )}
+ {error && <span className="text-[12px] text-reject-text">{error}</span>}
+ </VerdictBar>
+ );
+ const reader = ev ? (
+ <ReaderPane
+ className="h-full"
+ source={ev.source}
+ byline={ev.byline}
+ cite={ev.cite ?? undefined}
+ label="Source"
+ cues={ev.cues.map((c, i) => ({
+ t: c.start,
+ text: c.text,
+ lit: ev.cite ? i === litCueOf(ev.cues, ev.cite.at) : i === 0,
+ }))}
+ footer={ev.quote ? <CopyCitation text={citationText({ quote: ev.quote, title: ev.source, clock: ev.cite ? clock(ev.cite.at) : undefined, url: ev.url ?? undefined })} /> : undefined}
+ fine={ev.quote ? `“${ev.quote}”` : undefined}
+ />
+ ) : (
+ <ReaderPane className="h-full" source={row ? where : "Drafts review"} byline={row ? [row.entry ? "not drawn over a clip" : "the whole cut"] : []}>
+ <p className="m-0 text-[13px] text-reader-dim">
+ {row ? "No source window for this field: it is the cut's own words. Read it against the report." : "Light a field to see its source."}
+ </p>
+ </ReaderPane>
+ );
+ return (
+ <BenchBody verdict={verdict} reader={reader} workClassName="space-y-3">
+ <GateLine view={view} />
+ <MediaFields project={project} view={view} act={drafts.act} provenance={provenance} onLit={setLit} lineGo={false} />
+ </BenchBody>
+ );
+}
+
+const litCueOf = (cues: { start: number }[], at: number) => {
+ let best = 0;
+ cues.forEach((c, i) => {
+ if (c.start <= at + 0.02) best = i;
+ });
+ return best;
+};
diff --git a/umtool/components/projects/NarrationPage.tsx b/umtool/components/projects/NarrationPage.tsx
@@ -1,5 +1,5 @@
import Link from "next/link";
-import BrowseHeader from "@/components/BrowseHeader";
+import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell";
import { projectsHref } from "@/lib/hrefs";
import { readManifest } from "@/lib/projects/report.mjs";
import { manifestToken } from "@/lib/report/manifest.mjs";
@@ -20,35 +20,40 @@ export default async function NarrationPage({ project }: { project: ProjectRef }
const token = await manifestToken(project.dir);
const { counts } = view;
// The piece this view belongs to: the article's when an article claims the project (P4a-2).
- const [back, media] = await Promise.all([pieceHrefOfProject(project.id), pieceHrefOfProject(project.id, { tab: "media" })]);
+ const media = await pieceHrefOfProject(project.id, { tab: "media" });
return (
- <div className="flex h-full flex-col">
- <BrowseHeader
- crumbs={[
- { href: projectsHref(), label: "projects" },
- { href: back, label: project.id },
- { label: "narration" },
- ]}
- note={
- view.rows.length
- ? `${view.rows.length} narrated · ${counts.approved} approved` +
- (counts.rejected ? ` · ${counts.rejected} rejected` : "") +
- (counts.edited + counts.unreviewed ? ` · ${counts.edited + counts.unreviewed} to review` : "")
- : undefined
- }
- />
- <main className="deck-main flex-1 space-y-4 p-4">
- {view.rows.length === 0 ? (
+ // The bench shell (P4b): the top bar here; NarrationReview owns the verdict bar.
+ <BenchFrame
+ kind="narration"
+ top={
+ <BenchTop
+ trail={[{ href: projectsHref(), label: "projects" }]}
+ back={{ href: media, label: project.id }}
+ kind="Narration"
+ here="narration"
+ keys={view.rows.length ? [{ keys: ["j", "k"], label: "card" }, { keys: ["a"], label: "approve" }, { keys: ["r"], label: "reject" }] : []}
+ note={
+ view.rows.length
+ ? `${view.rows.length} narrated · ${counts.approved} approved` +
+ (counts.rejected ? ` · ${counts.rejected} rejected` : "") +
+ (counts.edited + counts.unreviewed ? ` · ${counts.edited + counts.unreviewed} to review` : "")
+ : undefined
+ }
+ />
+ }
+ >
+ {view.rows.length === 0 ? (
+ <BenchBody>
<p data-narration-empty="" className="text-[12px] text-[var(--color-dim)]">
No card in this cut carries a narration.{" "}
<Link href={media} className="ink-link">
back to {project.id}
</Link>
</p>
- ) : (
- <NarrationReview project={project.id} initial={view} token={token} />
- )}
- </main>
- </div>
+ </BenchBody>
+ ) : (
+ <NarrationReview project={project.id} initial={view} token={token} />
+ )}
+ </BenchFrame>
);
}
diff --git a/umtool/components/projects/NarrationReview.tsx b/umtool/components/projects/NarrationReview.tsx
@@ -4,6 +4,7 @@ import { useEffect, useRef, useState } from "react";
import { badgeVariants, type BadgeVariants } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import { MANIFEST_CHANGED } from "./timelineApi";
+import { BenchBody, VerdictBar } from "./bench/BenchShell";
import { DraftAlternatives, useDrafts, type DraftAct, type DraftsView } from "./drafts";
// The narration script of one cut, card by card (release 25, T5).
@@ -95,8 +96,88 @@ export default function NarrationReview({ project, initial, token: initialToken
return j;
};
+ // ---- the bench shell's verdict bar (P4b) ----------------------------------
+ //
+ // ONE question, on the card in hand: the one focused (a click or Tab inside
+ // it, or `j` / `k`), else the first still to review. `a` approves its words
+ // as saved; `r` rejects -- the note is the answer, so it puts the cursor
+ // there.
+ const [focus, setFocus] = useState<string | null>(null);
+ const toReview = view.rows.filter((r) => r.state !== "approved");
+ const card = view.rows.find((r) => r.id === focus) ?? toReview[0] ?? null;
+ const [barError, setBarError] = useState<string | null>(null);
+ const approve = async (r: NarrationRow) => {
+ setBarError(null);
+ try {
+ await act(r.id, "approve", { note: r.note });
+ } catch (e) {
+ setBarError(e instanceof Error ? e.message : String(e));
+ }
+ };
+ const toNote = (r: NarrationRow) => {
+ setFocus(r.id);
+ const el = document.querySelector<HTMLInputElement>(`[data-narration-card="${CSS.escape(r.id)}"] [data-narration-note]`);
+ el?.focus();
+ };
+ const move = (by: number) => {
+ const at = card ? view.rows.findIndex((r) => r.id === card.id) : -1;
+ const to = view.rows[Math.max(0, Math.min(view.rows.length - 1, at + by))];
+ if (!to) return;
+ setFocus(to.id);
+ document.querySelector(`[data-narration-card="${CSS.escape(to.id)}"]`)?.scrollIntoView({ block: "nearest" });
+ };
+ useEffect(() => {
+ if (!ready) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return;
+ if ((e.target as HTMLElement | null)?.closest?.("input, textarea, select, audio, [contenteditable='true'], dialog[open]")) return;
+ if (e.key === "j") move(1);
+ else if (e.key === "k") move(-1);
+ else if (e.key === "a" && card) void approve(card);
+ else if (e.key === "r" && card) toNote(card);
+ else return;
+ e.preventDefault();
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ });
+ const verdictBar = (
+ <VerdictBar
+ data-verdict-for={card?.id ?? ""}
+ question={card ? <>Approve the narration of <span className="font-mono">{card.id}</span>?</> : <>Every narrated card is approved.</>}
+ consequence={
+ !card
+ ? "A build takes them as they are."
+ : card.state === "approved"
+ ? `Approved${toReview.length ? ` — ${toReview.length} still to review` : ""}.`
+ : card.state === "rejected"
+ ? `Rejected${card.note ? `: ${card.note}` : ""} — a build refuses it until new words are approved.`
+ : `A build refuses it until it is approved${card.drafted ? " (drafted by " + card.drafted.model + ")" : ""}. The verdict is on the words as saved.`
+ }
+ >
+ {card && card.state !== "approved" && (
+ <button type="button" data-narration-approve={card.id} disabled={!ready} className={buttonVariants({ variant: "go", size: "md" })} onClick={() => void approve(card)}>
+ Approve <kbd>a</kbd>
+ </button>
+ )}
+ {card && (
+ <button type="button" data-narration-reject={card.id} disabled={!ready} className={buttonVariants({ size: "md" })} onClick={() => toNote(card)}>
+ Reject with a note <kbd>r</kbd>
+ </button>
+ )}
+ {barError && <span className="text-[12px] text-reject-text">{barError}</span>}
+ </VerdictBar>
+ );
+
return (
- <div className="space-y-3">
+ <BenchBody verdict={verdictBar}>
+ <div
+ className="space-y-3"
+ onFocus={(e) => {
+ const id = (e.target as HTMLElement).closest<HTMLElement>("[data-narration-card]")?.dataset.narrationCard;
+ if (id) setFocus(id);
+ }}
+ >
<p data-review-file={view.exists ? "present" : "absent"} className="text-[11px] text-[var(--color-dim)]">
{view.error ? (
<span className="text-[var(--color-bad)]">{view.error}</span>
@@ -114,9 +195,10 @@ export default function NarrationReview({ project, initial, token: initialToken
)}
</p>
{view.rows.map((r) => (
- <NarrationCard key={r.id} project={project} row={r} ready={ready} act={act} refresh={refresh} drafts={drafts.view} draftAct={drafts.act} />
+ <NarrationCard key={r.id} project={project} row={r} ready={ready} act={act} refresh={refresh} drafts={drafts.view} draftAct={drafts.act} lit={card?.id === r.id} />
))}
</div>
+ </BenchBody>
);
}
@@ -128,6 +210,7 @@ function NarrationCard({
refresh,
drafts,
draftAct,
+ lit = false,
}: {
project: string;
row: NarrationRow;
@@ -136,6 +219,8 @@ function NarrationCard({
refresh: () => Promise<NarrationView | null>;
drafts: DraftsView | null;
draftAct: DraftAct;
+ /** The card the verdict bar asks about: the lit line's edge (P4b). */
+ lit?: boolean;
}) {
const [text, setText] = useState(r.text);
const [note, setNote] = useState(r.note);
@@ -204,7 +289,8 @@ function NarrationCard({
<article
data-narration-card={r.id}
data-state={r.state}
- className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"
+ data-lit={lit ? "" : undefined}
+ className={`rounded border bg-[var(--color-panel)] px-3 py-2 ${lit ? "border-l-[3px] border-[var(--color-line)] border-l-signal" : "border-[var(--color-line)]"}`}
>
<div className="mb-1.5 flex flex-wrap items-center gap-2">
<span className="font-mono text-[12px] text-[var(--color-text)]">{r.id}</span>
@@ -274,7 +360,7 @@ function NarrationCard({
aria-pressed={r.state === "approved"}
disabled={!ready || busy || dirty}
title={dirty ? "save the words first: a verdict is on the words as saved" : "approve these words in this voice"}
- className={buttonVariants({ variant: r.state === "approved" ? "primary" : "outline", size: "sm" })}
+ className={`${buttonVariants({ variant: "outline", size: "sm" })}${r.state === "approved" ? " bg-panel-2 border-muted" : ""}`}
onClick={() => void run(() => act(r.id, r.state === "approved" ? "clear" : "approve", r.state === "approved" ? {} : { note }))}
>
{r.state === "approved" ? "Approved" : "Approve"}
diff --git a/umtool/components/projects/OnscreenSection.tsx b/umtool/components/projects/OnscreenSection.tsx
@@ -1343,7 +1343,7 @@ export default function OnscreenSection({
<button
type="button"
data-testid="onscreen-save"
- className={`${buttonVariants({ variant: "primary", size: "sm" })} ml-auto`}
+ className={`${buttonVariants({ variant: "outline", size: "sm" })} ml-auto`}
disabled={!!busy || dirtyIds.length === 0}
onClick={() => void saveRows()}
>
@@ -1522,7 +1522,7 @@ export default function OnscreenSection({
<button
type="button"
data-testid="onscreen-posts-save"
- className={`${buttonVariants({ variant: "primary", size: "sm" })} ml-auto`}
+ className={`${buttonVariants({ variant: "outline", size: "sm" })} ml-auto`}
disabled={!!busy || dirtyPostIds.length === 0}
onClick={() => void savePosts()}
>
@@ -1929,7 +1929,7 @@ export default function OnscreenSection({
<button
type="button"
data-testid="onscreen-rerender"
- className={buttonVariants({ variant: "primary", size: "sm" })}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
// Over the segments a build left, so there must have been one.
disabled={job?.state === "running" || finalV === "none"}
onClick={() => void rerender()}
@@ -2010,7 +2010,7 @@ export default function OnscreenSection({
<button
type="button"
data-testid="onscreen-settings-save"
- className={`${buttonVariants({ variant: "primary", size: "sm" })} ml-auto`}
+ className={`${buttonVariants({ variant: "outline", size: "sm" })} ml-auto`}
disabled={!!busy || !formDirty}
onClick={() => void saveSettings()}
>
diff --git a/umtool/components/projects/ReportBuildChain.tsx b/umtool/components/projects/ReportBuildChain.tsx
@@ -1,7 +1,7 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
-import { badgeVariants } from "@/components/ui/badge";
+import { JobProgress, type JobStepState } from "@/components/ui/job-progress";
import { buttonVariants } from "@/components/ui/button";
// ---------------------------------------------------------------------------
@@ -187,7 +187,7 @@ export default function ReportBuildChain({
<button
type="button"
data-action="run"
- className={buttonVariants({ variant: "primary", size: "sm" })}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
disabled={busy || job?.state === "running"}
onClick={async () => {
const j = await post("");
@@ -324,37 +324,37 @@ export default function ReportBuildChain({
)}
{job && (
- <div className="space-y-2">
- <ol className="flex flex-wrap gap-1.5">
- {job.steps.map((s, i) => (
- <li
- key={s.label}
- data-step={i}
- data-step-state={
- job.state !== "running" && i <= job.stepIndex
- ? job.state
- : i < job.stepIndex
- ? "done"
- : i === job.stepIndex
- ? "running"
- : "pending"
+ <JobProgress
+ state={job.state}
+ status={job.state === "running" ? `step ${job.stepIndex + 1}/${job.steps.length}: ${job.steps[job.stepIndex]?.label ?? ""}` : `${job.state}${job.error ? ` — ${job.error}` : ""}`}
+ meter={
+ job.state === "running" && entries.length
+ ? {
+ fraction: [...clipStates.values()].filter((st) => st === "done").length / entries.length,
+ text: `${[...clipStates.values()].filter((st) => st === "done").length}/${entries.length} entries`,
}
- className={badgeVariants({
- variant:
- i < job.stepIndex || (job.state === "done" && i <= job.stepIndex)
- ? "meter"
- : i === job.stepIndex && job.state === "running"
- ? "on"
- : job.state === "failed" && i === job.stepIndex
- ? "blocking"
- : "neutral",
- })}
- >
- {s.label}
- </li>
- ))}
- </ol>
-
+ : null
+ }
+ steps={job.steps.map((s, i) => {
+ const st =
+ job.state !== "running" && i <= job.stepIndex
+ ? job.state
+ : i < job.stepIndex
+ ? "done"
+ : i === job.stepIndex
+ ? "running"
+ : "pending";
+ return {
+ id: `${i}-${s.label}`,
+ label: s.label,
+ state: (st === "done" || st === "failed" || st === "running" ? st : "pending") as JobStepState,
+ attrs: { "data-step": i, "data-step-state": st },
+ };
+ })}
+ log={job.log.slice(-120)}
+ logLabel="build log"
+ data-build-job={job.id}
+ >
{/* One box per entry, lit by the pipeline's own events. "Step 3 of 4,
running" is not progress when step 3 is twenty minutes long. */}
<div className="flex flex-wrap gap-1">
@@ -381,16 +381,10 @@ export default function ReportBuildChain({
quietly missing a citation looks complete.
</p>
)}
-
- <pre className="max-h-56 overflow-auto rounded border border-[var(--color-line)] bg-[var(--color-ink)] p-2 font-mono text-[11px] text-[var(--color-dim)]">
- {job.log.slice(-120).join("\n")}
- </pre>
-
- <div className="micro" data-job-state={job.state}>
+ <div className="micro" data-job-state={job.state} hidden>
{job.state}
- {job.error ? ` — ${job.error}` : ""}
</div>
- </div>
+ </JobProgress>
)}
</section>
);
diff --git a/umtool/components/projects/ReportProject.tsx b/umtool/components/projects/ReportProject.tsx
@@ -62,7 +62,7 @@ export default async function ReportProject({
frame={frame}
tab={tab}
tabs={PIECE_TABS.map((t) => ({ ...t, href: projectHref(project.id, { tab: t.id }) }))}
- counts={reportCounts(detail)}
+ counts={await reportCounts(detail, project.dir)}
note={reportStatus(detail)}
more={
<>
diff --git a/umtool/components/projects/ReviewPage.tsx b/umtool/components/projects/ReviewPage.tsx
@@ -1,43 +1,80 @@
-import BrowseHeader from "@/components/BrowseHeader";
+import { clock } from "@/components/ui/clock";
import { projectsHref } from "@/lib/hrefs";
-import { readManifest } from "@/lib/projects/report.mjs";
+import { cuesInWindow, readClipDetail, readManifest } from "@/lib/projects/report.mjs";
import { manifestToken } from "@/lib/report/manifest.mjs";
import { draftsView } from "@/lib/report/drafts.mjs";
+import { readFieldProvenance } from "@/lib/report/draft-provenance.mjs";
import { pieceHrefOfProject } from "@/lib/pieces/article";
+import { awaitingReview } from "@/lib/inbox/drafts.mjs";
import type { ProjectRef } from "@/lib/project-types";
-import DraftsReview from "./DraftsReview";
+import { BenchFrame, BenchTop } from "./bench/BenchShell";
+import { MediaReview, type FieldEvidence, type FieldProvenance } from "./MediaDrafts";
import type { DraftsView } from "./drafts";
-// `/browse/<project>/review` -- every drafted field of the cut, approved or
-// rejected before a final build (release 28, M0). Verdicts are
+// `/projects/<project>/review` -- the drafts review as a BENCH (P4b): every
+// drafted field of the cut, walked one at a time -- `j`/`k` light a field,
+// `a` approves it, `r` rejects it with its note -- the verdict bar asking
+// about the lit field, the reader showing the clip it is drawn over. The
+// Media tab draws the same list with each section's "Draft with" (one
+// component, components/projects/MediaDrafts.tsx). Verdicts are
// <project>/drafts.review.json; a final build refuses a drafted field not
-// approved on its current value. The narration page is the narration's own
-// view of the same verdicts.
+// approved on its current value (release 28, M0).
+
+const ymd = (d: string | null | undefined) => (d && /^\d{8}$/.test(d) ? `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}` : (d ?? null));
+
export default async function ReviewPage({ project }: { project: ProjectRef }) {
const manifest = await readManifest(project.dir);
- const view = { ...((await draftsView(project.dir, manifest ?? {})) as DraftsView), token: await manifestToken(project.dir) };
- const { counts } = view;
+ const [view, provenance, token, detail] = await Promise.all([
+ draftsView(project.dir, manifest ?? {}) as Promise<DraftsView>,
+ readFieldProvenance(project.dir, manifest ?? {}) as Promise<Record<string, FieldProvenance>>,
+ manifestToken(project.dir),
+ manifest ? readClipDetail(project.dir, { manifest }) : Promise.resolve(null),
+ ]);
+ // Every field on the list, drafted or a narration written by hand.
+ const counts = { approved: 0, rejected: 0, edited: 0, unreviewed: 0 };
+ for (const r of view.rows) counts[r.state] += 1;
+
+ // The source of every clip a drafted field is drawn over: the reader's.
+ const evidence: Record<string, FieldEvidence> = {};
+ const wanted = new Set(view.rows.map((r) => r.entry).filter((e): e is string => !!e));
+ type Entry = { id: string; kind: string; start: number; end: number; cite?: number | null; quote?: string | null; video?: string; channel?: string | null; sourceTitleClean?: string | null; title?: string | null; uploadDate?: string | null; date?: string | null; duration?: number | null; citeUrl?: string | null };
+ for (const e of ((detail?.entries ?? []) as Entry[]).filter((x) => x.kind === "clip" && wanted.has(x.id))) {
+ const win = await cuesInWindow(project.dir, e.id, e.start - 20, e.end + 20).catch(() => null);
+ const at = e.cite ?? e.start;
+ const duration = e.duration ?? win?.duration ?? null;
+ evidence[e.id] = {
+ source: e.sourceTitleClean || e.title || e.video || e.id,
+ byline: [e.channel, e.date ?? ymd(e.uploadDate), `transcript${duration ? ` · ${clock(duration)}` : ""}`].filter((x): x is string => !!x),
+ cite: duration ? { at, duration } : null,
+ quote: e.quote ?? null,
+ url: e.citeUrl ?? null,
+ cues: (win?.cues ?? []).map((c: { start: number; text: string }) => ({ start: c.start, text: c.text })),
+ };
+ }
+
// The piece this view belongs to: the article's when an article claims the project (P4a-2).
- const back = await pieceHrefOfProject(project.id);
+ const back = await pieceHrefOfProject(project.id, { tab: "media" });
+ // To review: the drafted fields awaiting a verdict (the Media tab's count, the Inbox's).
+ const toReview = awaitingReview(view.rows, provenance).length;
return (
- <div className="flex h-full flex-col">
- <BrowseHeader
- crumbs={[
- { href: projectsHref(), label: "projects" },
- { href: back, label: project.id },
- { label: "review" },
- ]}
- note={
- view.drafted
- ? `${view.drafted} drafted · ${counts.approved} approved` +
- (counts.rejected ? ` · ${counts.rejected} rejected` : "") +
- (counts.edited + counts.unreviewed ? ` · ${counts.edited + counts.unreviewed} to review` : "")
- : undefined
- }
- />
- <main className="deck-main flex-1 space-y-4 p-4">
- <DraftsReview project={project.id} initial={view} />
- </main>
- </div>
+ <BenchFrame
+ kind="review"
+ top={
+ <BenchTop
+ trail={[{ href: projectsHref(), label: "projects" }]}
+ back={{ href: back, label: project.id }}
+ kind="Drafts review"
+ here="review"
+ keys={view.rows.length ? [{ keys: ["j", "k"], label: "field" }, { keys: ["a"], label: "approve" }, { keys: ["r"], label: "reject" }] : []}
+ note={
+ view.rows.length
+ ? `${view.rows.length} fields · ${counts.approved} approved` + (counts.rejected ? ` · ${counts.rejected} rejected` : "") + (toReview ? ` · ${toReview} to review` : "")
+ : undefined
+ }
+ />
+ }
+ >
+ <MediaReview project={project.id} initial={{ ...view, token }} provenance={provenance} evidence={evidence} />
+ </BenchFrame>
);
}
diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx
@@ -9,6 +9,7 @@ import TimedNotes from "@/components/notes/TimedNotes";
import { badgeVariants, type BadgeVariants } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import { fmtAgo } from "@/lib/format";
+import { BenchBody, VerdictBar } from "./bench/BenchShell";
// The takes of one project, a group at a time, every preview on screen at once.
//
@@ -86,10 +87,13 @@ export default function TakesBench({
project,
groups,
initial,
+ children,
}: {
project: string;
groups: { group: string; takes: Take[] }[];
initial: Record<string, TakeVerdict>;
+ /** Under the groups, in the work column (the takes the listing skipped). */
+ children?: React.ReactNode;
}) {
const [verdicts, setVerdicts] = useState(initial);
const [listen, setListen] = useState<string | null>(null);
@@ -132,8 +136,83 @@ export default function TakesBench({
setVerdicts(j.verdicts);
};
+ // ---- the bench shell's verdict bar (P4b) ----------------------------------
+ //
+ // ONE question: the take being listened to -- like, maybe or no -- with the
+ // keys `l`, `m`, `x`; `n` / `p` move the listening to the next or previous
+ // take. With nothing being listened to, it says how to start and what is left.
+ const all = groups.flatMap((g) => g.takes);
+ const judged = all.filter((t) => verdicts[t.id]?.verdict).length;
+ const current = all.find((t) => t.id === listen) ?? null;
+ const [verdictError, setVerdictError] = useState<string | null>(null);
+ const judge = useCallback(
+ (v: Verdict) => {
+ if (!current) return;
+ setVerdictError(null);
+ const on = verdicts[current.id]?.verdict === v;
+ save(current.id, { verdict: on ? null : v }).catch((e) => setVerdictError(e instanceof Error ? e.message : String(e)));
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [current, verdicts],
+ );
+ useEffect(() => {
+ if (!ready) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return;
+ const el = e.target as HTMLElement | null;
+ if (el?.closest?.("input, textarea, select, video, [contenteditable='true'], dialog[open]")) return;
+ const at = all.findIndex((t) => t.id === listenRef.current);
+ if (e.key === "n" || e.key === "p") {
+ const to = all[Math.max(0, Math.min(all.length - 1, at < 0 ? 0 : at + (e.key === "n" ? 1 : -1)))];
+ if (to) {
+ setListen(to.id);
+ document.querySelector(`[data-take="${CSS.escape(to.id)}"]`)?.scrollIntoView({ block: "nearest" });
+ }
+ } else if (e.key === "l") judge("like");
+ else if (e.key === "m") judge("maybe");
+ else if (e.key === "x") judge("no");
+ else return;
+ e.preventDefault();
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [ready, all, judge]);
+
+ const verdictBar = (
+ <VerdictBar
+ data-verdict-for={current?.id ?? ""}
+ question={
+ current ? (
+ <>
+ Is <span className="font-mono">{current.label}</span> the take for {current.group}?
+ </>
+ ) : (
+ <>Listen to a take to judge it: like, maybe or no.</>
+ )
+ }
+ consequence={`${judged} of ${all.length} judged${all.length - judged ? `, ${all.length - judged} to go` : ""}.`}
+ >
+ {current &&
+ VERDICTS.map((v, i) => (
+ <button
+ key={v.id}
+ type="button"
+ data-verdict-take={v.id}
+ aria-pressed={verdicts[current.id]?.verdict === v.id}
+ disabled={!ready}
+ className={buttonVariants({ variant: i === 0 ? "go" : "outline", size: "md" })}
+ onClick={() => judge(v.id)}
+ >
+ {v.label} <kbd>{v.id === "like" ? "l" : v.id === "maybe" ? "m" : "x"}</kbd>
+ </button>
+ ))}
+ {verdictError && <span className="text-[12px] text-reject-text">{verdictError}</span>}
+ </VerdictBar>
+ );
+
return (
<NotesProvider target={{ project }}>
+ <BenchBody verdict={verdictBar}>
<div className="space-y-6">
{groups.map((g) => {
const tally = VERDICTS.map((v) => [v.id, g.takes.filter((t) => verdicts[t.id]?.verdict === v.id).length] as const)
@@ -152,7 +231,7 @@ export default function TakesBench({
type="button"
data-action="play-all"
disabled={!ready}
- className={buttonVariants({ variant: "primary", size: "sm" })}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
onClick={() => void playAll(g)}
>
Play all from start
@@ -200,7 +279,9 @@ export default function TakesBench({
</section>
);
})}
+ {children}
</div>
+ </BenchBody>
</NotesProvider>
);
}
diff --git a/umtool/components/projects/TakesPage.tsx b/umtool/components/projects/TakesPage.tsx
@@ -1,5 +1,5 @@
import Link from "next/link";
-import AppShell from "@/components/shell/AppShell";
+import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell";
import { browseHref } from "@/lib/hrefs";
import { listTakes, readVerdicts } from "@/lib/report/takes.mjs";
import { pieceHrefOfProject } from "@/lib/pieces/article";
@@ -19,47 +19,53 @@ export default async function TakesPage({ project }: { project: ProjectRef }) {
// The piece this view belongs to: the article's when an article claims the project (P4a-2).
const back = await pieceHrefOfProject(project.id, { tab: "cut" });
+ const skipped =
+ listing.skipped.length > 0 ? (
+ <section data-takes-skipped="" className="text-[11px] text-[var(--color-dim)]">
+ <h2 className="micro mb-1">skipped — {listing.skipped.length}</h2>
+ <ul className="space-y-0.5">
+ {listing.skipped.map((s) => (
+ <li key={s.dir} data-skipped={s.dir}>
+ <code className="font-mono text-[var(--color-text)]">takes/{s.dir}</code> — {s.why}
+ </li>
+ ))}
+ </ul>
+ </section>
+ ) : null;
return (
- <div className="flex h-full flex-col">
- {/* A bench: the rail collapses and the work takes the width. */}
- <AppShell
- active="browse"
- rail="collapsed"
- crumbs={[
- { href: browseHref(), label: "projects" },
- { href: back, label: project.id },
- { label: "takes" },
- ]}
- note={takes.length ? `${takes.length} takes · ${judged} judged` : undefined}
- />
- <main className="deck-main flex-1 space-y-4 p-4">
- {takes.length === 0 ? (
+ // The bench shell (P4b): the top bar here; TakesBench owns the verdict bar.
+ <BenchFrame
+ kind="takes"
+ top={
+ <BenchTop
+ trail={[{ href: browseHref(), label: "projects" }]}
+ back={{ href: back, label: project.id }}
+ kind="Takes"
+ here="takes"
+ keys={takes.length ? [{ keys: ["n", "p"], label: "listen" }, { keys: ["l", "m", "x"], label: "like · maybe · no" }] : []}
+ note={takes.length ? `${takes.length} takes · ${judged} judged` : undefined}
+ />
+ }
+ >
+ {takes.length === 0 ? (
+ <BenchBody workClassName="space-y-4">
<p data-takes-empty="" className="text-[12px] text-[var(--color-dim)]">
No takes yet.{" "}
<Link href={back} className="ink-link">
back to {project.id}
</Link>
</p>
- ) : (
- <TakesBench
- project={project.id}
- groups={listing.groups.map((g) => ({ group: g.group, takes: g.takes as Take[] }))}
- initial={verdicts as Record<string, TakeVerdict>}
- />
- )}
- {listing.skipped.length > 0 && (
- <section data-takes-skipped="" className="text-[11px] text-[var(--color-dim)]">
- <h2 className="micro mb-1">skipped — {listing.skipped.length}</h2>
- <ul className="space-y-0.5">
- {listing.skipped.map((s) => (
- <li key={s.dir} data-skipped={s.dir}>
- <code className="font-mono text-[var(--color-text)]">takes/{s.dir}</code> — {s.why}
- </li>
- ))}
- </ul>
- </section>
- )}
- </main>
- </div>
+ {skipped}
+ </BenchBody>
+ ) : (
+ <TakesBench
+ project={project.id}
+ groups={listing.groups.map((g) => ({ group: g.group, takes: g.takes as Take[] }))}
+ initial={verdicts as Record<string, TakeVerdict>}
+ >
+ {skipped}
+ </TakesBench>
+ )}
+ </BenchFrame>
);
}
diff --git a/umtool/components/projects/bench/BenchShell.tsx b/umtool/components/projects/bench/BenchShell.tsx
@@ -0,0 +1,235 @@
+import Link from "next/link";
+import { Mark } from "@/components/shell/Wordmark";
+import { cn } from "@/lib/utils";
+
+// ---------------------------------------------------------------------------
+// THE BENCH SHELL (plans/umtool-redesign.md, P4b; canvas "Clip bench"): one
+// frame for every human-piloted walk -- the clip bench, the claim bench, the
+// narration script, the takes and the drafts review.
+//
+// top ← the piece · what bench this is · where you are ("c04 · 1 of 3")
+// · ‹ prev / next › · the keys, in one row (canvas `.benchtop`).
+// It IS the page's head: the mark links home (the rail is
+// collapsed), the trail is a Breadcrumb nav, `data-app-header=bench`.
+// work the bench's own working area (its player, its fields)
+// verdict ONE question, the actions named by what they do, and the
+// consequence stated before you choose (canvas `.verdictbar`)
+// reader the source on the reader surface, the cited cue lit, the cite
+// thread (components/ui/reader-pane.tsx)
+//
+// Fits 1366×768: the frame is the viewport, only its columns scroll. Below lg
+// it is one scrolling column (a phone cannot hold a bench; pretending would
+// cost the desk).
+//
+// No hooks and no server imports: a client bench (ClipBench) composes
+// BenchBody itself, so its verdict bar and reader can read its own state; a
+// server page renders BenchFrame + BenchTop around it.
+// ---------------------------------------------------------------------------
+
+export type BenchLink = { href: string; label: string; attrs?: Record<`data-${string}`, string> };
+export type BenchKey = { keys: string[]; label: string };
+
+/** The page: the top bar over the body, the viewport's height. */
+export function BenchFrame({
+ kind,
+ top,
+ children,
+ className,
+}: {
+ /** `data-bench-shell`: clip, claim, narration, takes, review. */
+ kind: string;
+ top: React.ReactNode;
+ children: React.ReactNode;
+ className?: string;
+}) {
+ return (
+ <div data-bench-shell={kind} className={cn("flex h-full min-h-0 flex-col overflow-auto lg:overflow-hidden", className)}>
+ {top}
+ {children}
+ </div>
+ );
+}
+
+/** The bench's head (canvas `.benchtop`). */
+export function BenchTop({
+ back,
+ trail = [],
+ kind,
+ here,
+ pos,
+ prev,
+ next,
+ keys = [],
+ note,
+}: {
+ /** The piece this bench belongs to: "← <its name>". */
+ back: BenchLink;
+ /** Crumbs before the piece ("projects"), small. */
+ trail?: BenchLink[];
+ /** What bench this is, in words ("Clip bench", "Drafts review"). */
+ kind: string;
+ /** What is on it: the clip id, "narration". */
+ here: string;
+ /** Where you are in the walk. */
+ pos?: { index: number; total: number; of?: string } | null;
+ prev?: BenchLink | null;
+ next?: BenchLink | null;
+ keys?: BenchKey[];
+ /** The bench's one-line status, the head's last `.micro`. */
+ note?: React.ReactNode;
+}) {
+ return (
+ <header
+ data-app-header="bench"
+ data-bench-top=""
+ className="flex flex-wrap items-center gap-x-3 gap-y-1.5 border-b border-seam bg-panel px-4 py-2"
+ >
+ <Link href="/" prefetch={false} aria-label="umtool home" className="shrink-0">
+ <Mark size={18} />
+ </Link>
+ <nav aria-label="Breadcrumb" className="flex min-w-0 items-center gap-1.5 text-[12.5px]">
+ {trail.map((c) => (
+ <span key={c.href} className="hidden items-center gap-1.5 xl:flex">
+ <Link href={c.href} prefetch={false} className="text-muted-2 hover:text-text">
+ {c.label}
+ </Link>
+ <span className="text-seam-2">/</span>
+ </span>
+ ))}
+ <Link href={back.href} prefetch={false} data-bench-back="" className="truncate text-muted-2 hover:text-text" {...back.attrs}>
+ <span aria-hidden>← </span>
+ {back.label}
+ </Link>
+ <span className="text-seam-2">/</span>
+ <span aria-current="page" className="font-mono text-[13px] font-medium text-text">
+ {here}
+ </span>
+ </nav>
+ <span className="micro" data-bench-kind="">
+ {kind}
+ </span>
+ {pos && (
+ <span data-bench-pos={`${pos.index}/${pos.total}`} className="font-mono text-[12.5px] font-medium text-text-2">
+ {pos.index} of {pos.total}
+ {pos.of ? ` ${pos.of}` : ""}
+ </span>
+ )}
+ {(prev !== undefined || next !== undefined) && (
+ <span className="flex items-center gap-1">
+ {prev ? (
+ <Link
+ href={prev.href}
+ prefetch={false}
+ data-bench-nav="prev"
+ className="rounded-[3px] px-2 py-[3px] text-[11.5px] text-muted-2 hover:bg-panel-2 hover:text-text"
+ {...prev.attrs}
+ >
+ ‹ {prev.label}
+ </Link>
+ ) : (
+ <span className="px-2 py-[3px] text-[11.5px] text-muted-2 opacity-50">‹ first</span>
+ )}
+ {next ? (
+ <Link
+ href={next.href}
+ prefetch={false}
+ data-bench-nav="next"
+ className="rounded-[3px] px-2 py-[3px] text-[11.5px] text-muted-2 hover:bg-panel-2 hover:text-text"
+ {...next.attrs}
+ >
+ {next.label} ›
+ </Link>
+ ) : (
+ <span className="px-2 py-[3px] text-[11.5px] text-muted-2 opacity-50">last ›</span>
+ )}
+ </span>
+ )}
+ {(keys.length > 0 || note) && (
+ <span className="ml-auto flex flex-wrap items-center gap-x-2.5 gap-y-1">
+ {keys.length > 0 && (
+ <span data-bench-keys="" className="hidden flex-wrap items-center gap-x-2.5 md:flex">
+ {keys.map((k) => (
+ <span key={k.label} className="inline-flex items-center gap-1 text-[11.5px] text-muted-2">
+ {k.keys.map((key) => (
+ <kbd key={key}>{key}</kbd>
+ ))}
+ <span>{k.label}</span>
+ </span>
+ ))}
+ </span>
+ )}
+ {note && <span className="micro">{note}</span>}
+ </span>
+ )}
+ </header>
+ );
+}
+
+/** The body: the work column (its verdict bar at the foot) and the reader on the right. */
+export function BenchBody({
+ verdict,
+ reader,
+ children,
+ workClassName,
+}: {
+ verdict?: React.ReactNode;
+ reader?: React.ReactNode;
+ children: React.ReactNode;
+ workClassName?: string;
+}) {
+ return (
+ <div
+ data-bench-body=""
+ className={cn(
+ "flex min-h-0 flex-1 flex-col lg:grid",
+ reader ? "lg:grid-cols-[minmax(0,1fr)_minmax(320px,28%)]" : "lg:grid-cols-[minmax(0,1fr)]",
+ )}
+ >
+ <div className="flex min-h-0 min-w-0 flex-col">
+ <main data-bench-work="" className={cn("deck-main min-h-0 flex-1 p-4", workClassName)}>
+ {children}
+ </main>
+ {verdict}
+ </div>
+ {reader && <div className="flex min-h-[320px] flex-col border-t border-seam lg:min-h-0 lg:border-t-0">{reader}</div>}
+ </div>
+ );
+}
+
+/**
+ * The verdict bar (canvas `.verdictbar`): the one question, its consequence in
+ * bold, then the actions -- each named by what it does, the first the screen's
+ * one filled action.
+ */
+export function VerdictBar({
+ question,
+ consequence,
+ children,
+ className,
+ ...props
+}: Omit<React.ComponentProps<"div">, "children"> & {
+ question: React.ReactNode;
+ consequence?: React.ReactNode;
+ children?: React.ReactNode;
+}) {
+ return (
+ <div
+ data-verdict-bar=""
+ className={cn("flex shrink-0 flex-wrap items-center gap-2 border-t border-seam bg-ground px-4 pb-3 pt-2.5", className)}
+ {...props}
+ >
+ <p className="m-0 basis-full text-[14px] leading-snug text-text">
+ <span data-verdict-question="">{question}</span>
+ {consequence && (
+ <>
+ {" "}
+ <b data-verdict-consequence="" className="font-semibold">
+ {consequence}
+ </b>
+ </>
+ )}
+ </p>
+ {children}
+ </div>
+ );
+}
diff --git a/umtool/components/projects/bench/CopyCitation.tsx b/umtool/components/projects/bench/CopyCitation.tsx
@@ -0,0 +1,39 @@
+"use client";
+
+import { useState } from "react";
+import { paperButtonVariants } from "@/components/ui/reader-pane";
+import { useHydrated } from "@/components/ui/use-hydrated";
+
+// The reader's Copy citation (a bench's reader pane): the house citation
+// (`"quote" [title @ m:ss](url)`, lib/research/facets.mjs) on the clipboard.
+// A copy the browser refuses shows the text to select instead -- a copy that
+// silently does nothing is the worst failure for this button.
+export default function CopyCitation({ text, label = "Copy citation" }: { text: string; label?: string }) {
+ const hydrated = useHydrated();
+ const [state, setState] = useState<"idle" | "done" | "failed">("idle");
+ return (
+ <>
+ <button
+ type="button"
+ data-copy-citation=""
+ className={paperButtonVariants()}
+ disabled={!hydrated}
+ title={text}
+ onClick={async () => {
+ try {
+ await navigator.clipboard.writeText(text);
+ setState("done");
+ setTimeout(() => setState("idle"), 1600);
+ } catch {
+ setState("failed");
+ }
+ }}
+ >
+ {state === "done" ? "Copied" : label}
+ </button>
+ {state === "failed" && (
+ <input readOnly value={text} aria-label="citation" className="min-w-0 flex-1 rounded-[2px] border border-reader-2 bg-transparent px-1.5 py-0.5 font-mono text-[11px]" onFocus={(e) => e.currentTarget.select()} />
+ )}
+ </>
+ );
+}
diff --git a/umtool/components/projects/drafts.tsx b/umtool/components/projects/drafts.tsx
@@ -151,7 +151,7 @@ export function DraftBadge({ address, view, act, compact = false }: { address: s
aria-pressed={row.state === "approved"}
disabled={!ready || busy}
title="approve this draft as it is now"
- className={buttonVariants({ variant: row.state === "approved" ? "primary" : "outline", size: "sm" })}
+ className={`${buttonVariants({ variant: "outline", size: "sm" })}${row.state === "approved" ? " bg-panel-2 border-muted" : ""}`}
onClick={() => void run(row.state === "approved" ? "clear" : "approve", row.state === "approved" ? {} : { note })}
>
{row.state === "approved" ? "Approved" : "Approve"}
diff --git a/umtool/components/projects/report/BuildTab.tsx b/umtool/components/projects/report/BuildTab.tsx
@@ -1,16 +1,15 @@
import Link from "next/link";
import { fmtAgo, fmtBytes } from "@/lib/format";
import { mixHref } from "@/lib/hrefs";
-import OnscreenSection from "../OnscreenSection";
import ReportBuildChain from "../ReportBuildChain";
import type { ReportTabProps } from "./shared";
-// The Build tab: the final video, the build chain, and the on-screen panel --
-// OnscreenSection parked here WHOLE until P4b gives on-screen its own Media
-// surface. Moved from ReportProject unchanged (P4a-1).
+// The Build tab: the final video and the build chain (its job on the ONE
+// JobProgress). The on-screen panel was parked here until P4b moved it to
+// the Media tab.
export default function BuildTab({ project, detail }: ReportTabProps) {
- const { manifest: m, build, entries } = detail;
+ const { build, entries } = detail;
return (
<>
{build.built && (
@@ -36,18 +35,7 @@ export default function BuildTab({ project, detail }: ReportTabProps) {
entries={entries.map((e) => ({ id: e.id, kind: e.kind }))}
/>
- {/* --- what is drawn over it --------------------------------------- */}
- {/* The on-screen panel: its settings, its words and a live preview of
- both. After the build chain, because "re-render on-screen" is a run
- of that chain over segments it already built; before Deliver,
- because the panel is part of the video that gets delivered. */}
- <OnscreenSection
- project={project.id}
- generatedBy={typeof m.generatedBy === "string" ? m.generatedBy : null}
- entries={entries.map((e) => ({ id: e.id, kind: e.kind, segment: !!e.segment }))}
- built={!!build.built}
- />
-
+ {/* The on-screen panel moved to the Media tab (P4b). */}
</>
);
}
diff --git a/umtool/components/projects/report/MediaTab.tsx b/umtool/components/projects/report/MediaTab.tsx
@@ -1,70 +1,57 @@
-import Link from "next/link";
import { narrationsOf } from "umtool-report-to-video/narration";
-import { draftedFields, isCodeDraft } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
-import { readAlternatives } from "@/lib/report/drafts.mjs";
+import { draftsView } from "@/lib/report/drafts.mjs";
+import { readFieldProvenance } from "@/lib/report/draft-provenance.mjs";
+import { manifestToken } from "@/lib/report/manifest.mjs";
import { draftRowsOf, draftRuns, projectIteration } from "@/lib/articles/projectDraft";
-import { buttonVariants } from "@/components/ui/button";
-import { narrationHref, reviewHref } from "@/lib/hrefs";
-import DraftPanel from "../DraftPanel";
+import MediaDrafts, { type FieldProvenance } from "../MediaDrafts";
+import OnscreenSection from "../OnscreenSection";
import YoutubeSection from "../YoutubeSection";
+import type { DraftsView } from "../drafts";
import type { ReportTabProps } from "./shared";
-// The Media tab: release 28's drafts as they were on the project page -- the
-// narration script and the drafts review, the "Draft with" panel, the upload's
-// text. Moved from ReportProject unchanged (P4a-1); P4b absorbs them into one
-// Media surface.
+// THE MEDIA TAB (P4b; canvas "Piece · Media"): ONE surface for what the cut
+// says over its footage -- every drafted field with its provenance and
+// review, each section's "Draft with <model>", Draft everything and Approve
+// all (components/projects/MediaDrafts.tsx); then the on-screen panel whole
+// (moved out of Build) and the upload's text. Release 28's review page,
+// Draft panel and the Iterations tab's media drafts are this now; the
+// narration's words are edited and played on its bench (…/narration), the
+// fields walked one at a time on the review bench (…/review).
export default async function MediaTab({ project, detail }: ReportTabProps) {
- const { manifest: m } = detail;
- const narrated = narrationsOf(m).length;
- // The drafts review (release 28): drafted fields, and alternatives kept.
- // (A field a code path made — the converter's timeline — is not a draft to review.)
- const draftedCount = draftedFields(m).filter((d) => !isCodeDraft(d.provenance)).length;
- const alternativesCount = (await readAlternatives(project.dir)).length;
- // "Draft with" (release 28 M9): the iteration the project was made from, and
- // each media task's last run here.
- const draftLink = await projectIteration(project.dir);
- const draftRunsNow = draftLink.ok ? await draftRuns(project.dir) : {};
-
+ const { manifest: m, build, entries } = detail;
+ const [view, provenance, link, token] = await Promise.all([
+ draftsView(project.dir, m) as Promise<DraftsView>,
+ readFieldProvenance(project.dir, m) as Promise<Record<string, FieldProvenance>>,
+ projectIteration(project.dir),
+ manifestToken(project.dir),
+ ]);
+ const runs = link.ok ? await draftRuns(project.dir) : {};
return (
<>
- {(narrated > 0 || draftedCount > 0 || alternativesCount > 0) && (
- <div className="flex flex-wrap items-start gap-3">
- {/* The narration script, card by card, before synthesis -- only when
- some card carries one. */}
- {narrated > 0 && (
- <Link
- href={narrationHref(project.id)}
- data-narration-link={narrated}
- className={buttonVariants({ size: "lg" })}
- >
- Narration — {narrated}
- </Link>
- )}
- {/* Every drafted field, judged before a final build -- only when a
- draft task wrote one, or kept an alternative. */}
- {(draftedCount > 0 || alternativesCount > 0) && (
- <Link
- href={reviewHref(project.id)}
- data-review-link={draftedCount}
- className={buttonVariants({ size: "lg" })}
- >
- Review drafts — {draftedCount}
- </Link>
- )}
- </div>
- )}
-
- {/* --- drafting it ----------------------------------------------- */}
- {/* Each draftable section drafted by a model, as a step on the
- iteration the project was made from. After the build chain (a
- draft changes what the next build makes), before the sections it
- writes into. */}
- <DraftPanel project={project.id} link={draftLink} rows={draftRowsOf(m as Record<string, unknown>)} runs={draftRunsNow} />
+ <MediaDrafts
+ project={project.id}
+ initial={{ ...view, token }}
+ provenance={provenance}
+ link={link}
+ rows={draftRowsOf(m as Record<string, unknown>)}
+ runs={runs}
+ narrated={narrationsOf(m).length}
+ />
- {/* --- the upload's text (out/youtube.txt, or its preview) --------- */}
- <YoutubeSection dir={project.dir} manifest={m as Record<string, unknown>} />
+ {/* --- what is drawn over it --------------------------------------- */}
+ {/* The on-screen panel: its settings, its words and a live preview of
+ both, whole (P4a-1 parked it on Build; its words are media). "Re-render
+ on-screen" still runs the build over the segments it already built. */}
+ <OnscreenSection
+ project={project.id}
+ generatedBy={typeof m.generatedBy === "string" ? m.generatedBy : null}
+ entries={entries.map((e) => ({ id: e.id, kind: e.kind, segment: !!e.segment }))}
+ built={!!build.built}
+ />
+ {/* --- the upload's text (out/youtube.txt, or its preview) --------- */}
+ <YoutubeSection dir={project.dir} manifest={m as Record<string, unknown>} />
</>
);
}
diff --git a/umtool/components/projects/report/ReportTabBody.tsx b/umtool/components/projects/report/ReportTabBody.tsx
@@ -2,7 +2,7 @@ import GeneratedBanner from "@/components/notes/GeneratedBanner";
import { NotesProvider } from "@/components/notes/NotesProvider";
import { channelFor, clipsOf } from "@/lib/projects/report.mjs";
import type { PieceFrame } from "@/lib/pieces/frame";
-import { draftedFields, isCodeDraft } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
+import { awaitingReviewOf } from "@/lib/report/draft-provenance.mjs";
import BuildTab from "./BuildTab";
import CutTab from "./CutTab";
import DeliverTab from "./DeliverTab";
@@ -17,11 +17,14 @@ import { hms, type ClipDetail, type ReportTabProps } from "./shared";
// article piece that claims it (components/articles/ArticlePage.tsx). The
// project's notes are the target of everything under it.
-/** The tabs' counts: cheap, from the manifest already read (Cut: clips, Media: drafted fields, Sources: recordings). */
-export function reportCounts(detail: ClipDetail): { cut: number; media: number; sources: number } {
+/**
+ * The tabs' counts (Cut: clips, Media: the fields awaiting review -- the Inbox's
+ * drafts card's number, lib/inbox/drafts.mjs awaitingReview -- Sources: recordings).
+ */
+export async function reportCounts(detail: ClipDetail, dir: string): Promise<{ cut: number; media: number; sources: number }> {
const m = detail.manifest;
const clips = detail.entries.filter((e) => e.kind === "clip").length;
- const media = draftedFields(m).filter((d) => !isCodeDraft(d.provenance)).length;
+ const media = (await awaitingReviewOf(dir, m)).length;
const sources = new Set(clipsOf(m).map((e: { video: string }) => `${channelFor(m, e)}/${e.video}`)).size;
return { cut: clips, media, sources };
}
diff --git a/umtool/components/shell/JobProgress.tsx b/umtool/components/shell/JobProgress.tsx
@@ -1,33 +1,4 @@
-import type { ActivityMeter } from "@/lib/activity-types";
-
-// ONE presentation of a job's progress, for every Running row (umtool's own
-// chain or render, the editor's draft, sync or acquisition): a few words in
-// mono and a 2 px Meter bar under the row. A job that reports no fraction
-// draws no bar -- an empty bar would read as "0% done". P4b moves the chain's
-// and the editor's job panels onto it too.
-
-export function JobProgressText({ meter, className }: { meter?: ActivityMeter | null; className?: string }) {
- if (!meter?.text) return null;
- return (
- <span className={className} data-job-progress-text="">
- {meter.text}
- </span>
- );
-}
-
-export function JobProgressBar({ meter }: { meter?: ActivityMeter | null }) {
- if (meter?.fraction === null || meter?.fraction === undefined) return null;
- const pct = Math.round(Math.max(0, Math.min(1, meter.fraction)) * 100);
- return (
- <span
- className="relative col-span-2 h-0.5 overflow-hidden bg-seam"
- role="progressbar"
- aria-valuemin={0}
- aria-valuemax={100}
- aria-valuenow={pct}
- data-job-progress={pct}
- >
- <i className="absolute inset-y-0 left-0 bg-meter" style={{ width: `${pct}%` }} />
- </span>
- );
-}
+// The Running row's progress: the two smallest parts of the ONE job progress
+// (components/ui/job-progress.tsx, P4b), which the Media tab's drafts, Draft
+// everything, the Build tab and the Iterations tab's jobs use whole.
+export { JobProgressBar, JobProgressText } from "@/components/ui/job-progress";
diff --git a/umtool/components/ui/cite-thread.tsx b/umtool/components/ui/cite-thread.tsx
@@ -1,4 +1,5 @@
import { cn } from "@/lib/utils";
+import { threadLabels } from "@/lib/cite-thread.mjs";
import { clock } from "./clock";
// Where a cited second sits in its source (canvas `.cthread` / `.pthread`): a
@@ -32,16 +33,21 @@ export function CiteThread({
);
}
-/** The reader's version: start, cite and end under the line. */
+/** The reader's version: start, cite and end under the line; the cite's label never on an end's (lib/cite-thread.mjs). */
export function ReaderThread({ at, duration, className }: { at: number; duration: number; className?: string }) {
const pct = duration > 0 ? Math.min(100, Math.max(0, (at / duration) * 100)) : 0;
+ const cite = clock(at);
+ const end = clock(duration);
+ const l = threadLabels({ pct, citeChars: cite.length, startChars: "0:00".length, endChars: end.length });
return (
- <div className={cn("cite-thread mt-2.5", className)} role="img" aria-label={`Cited at ${clock(at)} of ${clock(duration)}`} data-cite-at={at}>
+ <div className={cn("cite-thread mt-2.5", className)} role="img" aria-label={`Cited at ${cite} of ${end}`} data-cite-at={at}>
<i style={{ left: `${pct}%` }} />
{/* The ends give way when the cite's own label would sit on them. */}
- {pct >= 12 && <span style={{ left: 0 }}>0:00</span>}
- <span style={{ left: `clamp(0px, calc(${pct}% - 22px), calc(100% - 56px))` }}>{clock(at)}</span>
- {pct <= 80 && <span style={{ left: "auto", right: 0 }}>{clock(duration)}</span>}
+ {l.showStart && <span style={{ left: 0 }}>0:00</span>}
+ <span data-cite-label="" style={{ left: l.citeLeft }}>
+ {cite}
+ </span>
+ {l.showEnd && <span style={{ left: "auto", right: 0 }}>{end}</span>}
</div>
);
}
diff --git a/umtool/components/ui/job-progress.tsx b/umtool/components/ui/job-progress.tsx
@@ -0,0 +1,343 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import type { ActivityMeter } from "@/lib/activity-types";
+import { editorProgress, queueText, spendFromLog } from "@/lib/running.mjs";
+import { cn } from "@/lib/utils";
+import { Button } from "./button";
+
+// ---------------------------------------------------------------------------
+// ONE JOB PROGRESS (plans/umtool-redesign.md, P4b) for every job umtool shows:
+// a chain (Make the video, Draft everything), a build, an editor job (a media
+// draft, a narration, an iteration). The parts are the same everywhere --
+//
+// head the job's state in words ("running", "queued · 1 ahead",
+// "failed: …"), the current step ("step 3/15: draft-onscreen"),
+// the spend so far in Meter, and Cancel where the job supports it
+// bar a 2 px Meter bar, only when the job reports a fraction (an empty
+// bar would read as "0% done")
+// steps the step list, each with its state; the current one in ink
+// log the last lines, when asked for
+//
+// -- so a Running row in the rail, a draft row on the Media tab and the build
+// on the Build tab read the same way. The Running row uses the two smallest
+// parts (JobProgressText, JobProgressBar); `components/shell/JobProgress.tsx`
+// re-exports them. Colour: Meter for measurement (the bar, the spend), the
+// verdict text steps only for an ended job's outcome; never Signal.
+// ---------------------------------------------------------------------------
+
+export type JobStepState = "pending" | "running" | "done" | "failed" | "skipped" | "cancelled";
+export type JobStep = {
+ /** A stable key (the step's name). */
+ id: string;
+ label: string;
+ state: JobStepState;
+ /** A line under it: why it was skipped, what it wrote. */
+ detail?: string | null;
+ /** Marked as where a run starts (a resume). */
+ start?: boolean;
+ /** Optional steps read in italic. */
+ optional?: boolean;
+ /** The step's own data attributes (the specs' handles). */
+ attrs?: Record<string, string | number | undefined>;
+};
+
+const STEP_TONE: Record<JobStepState, string> = {
+ pending: "text-muted-2",
+ running: "text-text font-semibold",
+ done: "text-text-2",
+ failed: "text-reject-text",
+ skipped: "text-muted-2",
+ cancelled: "text-muted-2",
+};
+const STEP_MARK: Record<JobStepState, string> = {
+ pending: "○",
+ running: "▸",
+ done: "✓",
+ failed: "✕",
+ skipped: "–",
+ cancelled: "–",
+};
+
+/** The few words of a row (the rail's): "2/4", "3/12 turns", "queued · next". */
+export function JobProgressText({ meter, className }: { meter?: ActivityMeter | null; className?: string }) {
+ if (!meter?.text) return null;
+ return (
+ <span className={className} data-job-progress-text="">
+ {meter.text}
+ </span>
+ );
+}
+
+/** The 2 px Meter bar; nothing when the job reports no fraction. */
+export function JobProgressBar({ meter, className }: { meter?: ActivityMeter | null; className?: string }) {
+ if (meter?.fraction === null || meter?.fraction === undefined) return null;
+ const pct = Math.round(Math.max(0, Math.min(1, meter.fraction)) * 100);
+ return (
+ <span
+ className={cn("relative col-span-2 block h-0.5 overflow-hidden bg-seam", className)}
+ role="progressbar"
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={pct}
+ data-job-progress={pct}
+ >
+ <i className="absolute inset-y-0 left-0 bg-meter" style={{ width: `${pct}%` }} />
+ </span>
+ );
+}
+
+const usd = (n: number) => `$${n < 10 ? n.toFixed(2) : n.toFixed(0)}`;
+
+export function JobProgress({
+ label,
+ state,
+ status,
+ current,
+ meter,
+ spend,
+ steps,
+ stepColumns = false,
+ log,
+ logLabel,
+ onCancel,
+ cancelLabel = "Cancel",
+ cancelName,
+ error,
+ className,
+ children,
+ ...props
+}: Omit<React.ComponentProps<"div">, "children"> & {
+ /** What the job is, in words ("Draft everything", "the cut"). Omitted where the context says it. */
+ label?: React.ReactNode;
+ /** The job's state, for the data attribute and the tone. */
+ state: "asking" | "queued" | "running" | "done" | "failed" | "cancelled" | string;
+ /** The state in words, when it says more than `state` ("queued · 1 ahead"). */
+ status?: React.ReactNode;
+ /** The current step, in words ("step 3/15: draft-onscreen"). */
+ current?: React.ReactNode;
+ meter?: ActivityMeter | null;
+ /** USD so far, when the job says (a generation job's log). */
+ spend?: number | null;
+ steps?: JobStep[];
+ /** The steps in columns (a chain's fifteen) rather than one wrapped row. */
+ stepColumns?: boolean;
+ log?: string[];
+ logLabel?: string;
+ /** Present when the job can be cancelled. */
+ onCancel?: () => void;
+ cancelLabel?: string;
+ /** The Cancel button's accessible name, when the label alone is ambiguous. */
+ cancelName?: string;
+ error?: React.ReactNode;
+ children?: React.ReactNode;
+}) {
+ const live = state === "running" || state === "queued" || state === "asking";
+ const ended = state === "failed" || state === "cancelled";
+ return (
+ <div data-job-progress-of={state} className={cn("space-y-1.5 text-[12px]", className)} {...props}>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ {label && <span className="text-text">{label}</span>}
+ <span
+ role="status"
+ data-job-state-words=""
+ className={state === "failed" ? "text-reject-text" : live ? "text-text-2" : "text-muted"}
+ >
+ {status ?? state}
+ </span>
+ {current && <span className="font-mono text-[11.5px] text-text-2">{current}</span>}
+ {meter?.text && <JobProgressText meter={meter} className="font-mono text-[11.5px] text-muted-2" />}
+ {spend != null && (
+ <span data-job-spend={spend.toFixed(2)} className="font-mono text-[11.5px] text-meter">
+ {usd(spend)}
+ </span>
+ )}
+ {onCancel && live && (
+ <Button size="sm" variant="destructive" className="ml-auto" aria-label={cancelName} onClick={onCancel}>
+ {cancelLabel}
+ </Button>
+ )}
+ </div>
+ {live && <JobProgressBar meter={meter} />}
+ {steps && steps.length > 0 && (
+ <ol
+ className={cn(
+ "gap-x-4 gap-y-0.5",
+ stepColumns ? "grid sm:grid-flow-col sm:grid-rows-8" : "flex flex-wrap gap-x-3",
+ )}
+ >
+ {steps.map((s, i) => (
+ <li
+ key={s.id}
+ title={s.detail ?? undefined}
+ className={cn("flex min-w-0 items-baseline gap-1.5", STEP_TONE[s.state])}
+ {...Object.fromEntries(Object.entries(s.attrs ?? {}).filter(([, v]) => v !== undefined))}
+ >
+ {stepColumns && <span className="w-5 shrink-0 text-right font-mono text-[11px] text-muted-2">{i + 1}</span>}
+ <span aria-hidden className="font-mono text-[11px]">
+ {STEP_MARK[s.state]}
+ </span>
+ <span className={cn(s.optional && "italic", s.start && "underline decoration-seam-2 underline-offset-2")}>{s.label}</span>
+ {s.state !== "pending" && s.state !== "running" && <span className="sr-only">{s.state}</span>}
+ {s.detail && s.state !== "pending" && s.state !== "running" && (
+ <span data-job-step-detail="" className="truncate text-[11px] text-muted-2">
+ {s.detail}
+ </span>
+ )}
+ </li>
+ ))}
+ </ol>
+ )}
+ {children}
+ {log && log.length > 0 && (
+ <pre
+ role="log"
+ aria-label={logLabel}
+ className="max-h-48 overflow-auto rounded-[2px] border border-seam bg-ground p-2 font-mono text-[11px] leading-snug whitespace-pre-wrap text-muted"
+ >
+ {log.join("\n")}
+ </pre>
+ )}
+ {error && <p className={cn("text-[11.5px]", ended || state === "failed" ? "text-reject-text" : "text-doubt-text")}>{error}</p>}
+ </div>
+ );
+}
+
+// ---- an editor job, followed ------------------------------------------------
+
+export type EditorJob = {
+ id: string;
+ kind: string | null;
+ status: string;
+ queue: { key?: string; position?: number } | null;
+ progress: { metric: string; current: number; target: number } | null;
+ tail: string[];
+};
+const ENDED = ["done", "failed", "cancelled"];
+
+/**
+ * Follow one editor job through umtool's `/api/articles/job` (every 2 s, never
+ * faster), telling `onEnd` once when it ends. `null` id: nothing followed.
+ */
+export function useEditorJob(
+ jobId: string | null,
+ { tail = 6, onEnd }: { tail?: number; onEnd?: (job: EditorJob) => void } = {},
+): { job: EditorJob | null; error: string; cancel: () => Promise<void> } {
+ const [job, setJob] = useState<EditorJob | null>(null);
+ const [error, setError] = useState("");
+ const ended = useRef(onEnd);
+ ended.current = onEnd;
+ const told = useRef<string | null>(null);
+ useEffect(() => {
+ setJob(null);
+ if (!jobId) return;
+ let alive = true;
+ let stop = false;
+ const tick = async () => {
+ if (stop) return;
+ try {
+ const r = await fetch(`/api/articles/job?id=${encodeURIComponent(jobId)}&tail=${tail}`, { cache: "no-store" });
+ const b = await r.json();
+ if (!alive) return;
+ if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
+ setJob(b.job);
+ setError("");
+ if (ENDED.includes(b.job.status)) {
+ stop = true;
+ if (told.current !== jobId) {
+ told.current = jobId;
+ ended.current?.(b.job);
+ }
+ }
+ } catch (e) {
+ if (alive) setError((e as Error).message);
+ }
+ };
+ void tick();
+ const t = setInterval(tick, 2000);
+ return () => {
+ alive = false;
+ clearInterval(t);
+ };
+ }, [jobId, tail]);
+ const cancel = async () => {
+ if (!jobId) return;
+ const r = await fetch("/api/articles/job", { method: "POST", body: JSON.stringify({ cancel: jobId }) });
+ if (!r.ok) setError(((await r.json().catch(() => ({}))) as { error?: string }).error ?? `HTTP ${r.status}`);
+ };
+ return { job, error, cancel };
+}
+
+/** An editor job's state, progress and spend, as JobProgress reads them. */
+export function editorJobView(job: EditorJob | null): {
+ state: string;
+ status: string;
+ meter: ActivityMeter | null;
+ spend: number | null;
+} {
+ if (!job) return { state: "asking", status: "asking the editor…", meter: null, spend: null };
+ const queued = job.status === "queued" || (job.queue?.position ?? 0) > 0;
+ const p = editorProgress(job.progress ? { metric: job.progress.metric, current: job.progress.current, target: job.progress.target } : null);
+ const status = queued
+ ? `${queueText(job.queue)}${job.queue?.key ? ` on ${job.queue.key}` : ""}`
+ : job.status;
+ return {
+ state: queued ? "queued" : job.status,
+ status,
+ meter: p ? { fraction: p.fraction, text: p.text } : null,
+ spend: spendFromLog(job.tail),
+ };
+}
+
+/**
+ * An editor job, followed and drawn: its state, its place in a queue, its
+ * progress and spend, its log's last lines (when `log`), and Cancel. What the
+ * Media tab's draft rows and the Iterations tab's jobs show.
+ */
+export function EditorJobProgress({
+ jobId,
+ label,
+ onEnd,
+ tail = 6,
+ log = false,
+ cancelName,
+ className,
+ ...props
+}: Omit<React.ComponentProps<"div">, "children"> & {
+ jobId: string;
+ label?: React.ReactNode;
+ onEnd?: (job: EditorJob | null) => void;
+ tail?: number;
+ /** Show the log's last lines (the Iterations tab's), else only the last line in the status. */
+ log?: boolean;
+ logLabel?: string;
+ cancelName?: string;
+}) {
+ const { logLabel, ...rest } = props;
+ const { job, error, cancel } = useEditorJob(jobId, { tail, onEnd: (j) => onEnd?.(j) });
+ const v = editorJobView(job);
+ const last = job?.tail.filter((l) => !l.startsWith("@@")).slice(-1)[0];
+ return (
+ <JobProgress
+ data-job={jobId}
+ data-job-status={job?.status ?? "unknown"}
+ label={label}
+ state={v.state}
+ status={v.status}
+ meter={v.meter}
+ spend={v.spend}
+ current={!log && last && !ENDED.includes(job?.status ?? "") ? last : undefined}
+ log={log ? job?.tail : undefined}
+ logLabel={logLabel}
+ onCancel={() =>
+ void cancel().then(() => {
+ onEnd?.(job);
+ })
+ }
+ cancelName={cancelName}
+ error={error || undefined}
+ className={className}
+ {...rest}
+ />
+ );
+}
diff --git a/umtool/components/ui/reader-pane.tsx b/umtool/components/ui/reader-pane.tsx
@@ -2,7 +2,7 @@ import { cva } from "class-variance-authority";
import { cn } from "@/lib/utils";
import { ReaderThread } from "./cite-thread";
import { clock } from "./clock";
-import { LitList } from "./lit-list";
+import { LitList, type LitDetail } from "./lit-list";
import { LitLine } from "./lit-line";
// ---------------------------------------------------------------------------
@@ -17,11 +17,22 @@ import { LitLine } from "./lit-line";
// speaker when the transcript knows one
// footer the actions (paperButtonVariants), and a fine line (the citation)
//
+// A bench (P4b) passes its own handle and ref on the body (`bodyProps`), its own
+// cue rows unwrapped (`bare`), or follows the lit cue (`onLight`).
+//
// Rules from the canvas critique: no verdict colour on the reader, ever; the
// reader's own Signal is `--reader-signal`, a teal dark enough for the paper.
// ---------------------------------------------------------------------------
-export type Cue = { t: number; text: React.ReactNode; turn?: boolean; lit?: boolean; id?: string };
+export type Cue = {
+ t: number;
+ text: React.ReactNode;
+ turn?: boolean;
+ lit?: boolean;
+ id?: string;
+ /** The line's own data attributes (a bench's handles; P4b). */
+ attrs?: Record<`data-${string}`, string | undefined>;
+};
export const paperButtonVariants = cva(
"inline-flex items-center justify-center gap-1.5 whitespace-nowrap rounded-[3px] border px-[11px] py-[5px] text-[12.5px] font-medium transition-[color,background-color,border-color,text-decoration-color,fill,stroke] disabled:pointer-events-none disabled:opacity-50",
@@ -45,6 +56,10 @@ export function ReaderPane({
label = "Transcript",
footer,
fine,
+ bodyProps,
+ bare = false,
+ onLight,
+ global = false,
className,
children,
...props
@@ -64,6 +79,14 @@ export function ReaderPane({
fine?: React.ReactNode;
/** Instead of cues: anything else the source said (a post, a quote). */
children?: React.ReactNode;
+ /** Onto the scrolling body (a bench's handle, its ref; P4b). */
+ bodyProps?: React.ComponentProps<"div"> & Record<`data-${string}`, string | undefined>;
+ /** `children` as they are, without the reader-text column (a bench's own cue rows; P4b). */
+ bare?: boolean;
+ /** The lit cue moved (a bench seeks its player to it; P4b). */
+ onLight?: (d: LitDetail) => void;
+ /** `j`/`k` from anywhere on the page move the cues (the page's one list: a bench; P4b). */
+ global?: boolean;
}) {
const parts = (byline ?? []).filter(Boolean);
return (
@@ -83,9 +106,9 @@ export function ReaderPane({
{cite && <ReaderThread at={cite.at} duration={cite.duration} />}
</div>
{note && <div className="px-[22px] pt-2 text-[11.5px] text-reader-dim">{note}</div>}
- <div className="min-h-0 flex-1 overflow-auto py-2 pr-2.5">
+ <div {...bodyProps} className={cn("min-h-0 flex-1 overflow-auto py-2 pr-2.5", bodyProps?.className)}>
{cues ? (
- <LitList label={label}>
+ <LitList label={label} onLight={onLight} global={global}>
{cues.map((c, i) => (
<LitLine
key={c.id ?? `${c.t}-${i}`}
@@ -93,12 +116,15 @@ export function ReaderPane({
initial={c.lit}
className="reader-cue"
data-turn={c.turn ? "" : undefined}
+ {...c.attrs}
>
<span className="reader-t">{clock(c.t)}</span>
<p>{c.text}</p>
</LitLine>
))}
</LitList>
+ ) : bare ? (
+ children
) : (
<div className="reader-text px-[22px]">{children}</div>
)}
diff --git a/umtool/e2e/article-iterations.spec.ts b/umtool/e2e/article-iterations.spec.ts
@@ -72,14 +72,21 @@ test("an article in the making: listed as such on Work, opened as its piece, its
});
test("narrate an iteration's cut on a model: a step, its job followed to done", async ({ page }) => {
+ // The Iterations tab links a cut's media drafts (P4b); narration is drafted
+ // on the Media tab, its job followed on the ONE JobProgress.
await page.goto(urls.articleHref(ZETA, { tab: "iterations" }));
const one = card(page, 1);
- await one.getByRole("combobox", { name: "narration model for i1" }).selectOption("claude-sonnet-5-5");
- await one.getByRole("button", { name: "Narrate" }).click();
- await expect(page.getByRole("status").filter({ hasText: "i1 started" })).toBeVisible();
- await expect(one.locator("[data-step='narrate']")).toHaveAttribute("data-step-status", "done", { timeout: 20_000 });
+ await expect(one.locator("[data-media-link]")).toHaveAttribute("href", urls.projectHref("gen-projects/zeta/i1", { tab: "media" }));
+ await one.locator("[data-media-link]").click();
+ await expect(page).toHaveURL(new RegExp(`${urls.articleHref(ZETA, { tab: "media", project: "gen-projects/zeta/i1" }).replace(/[?]/g, "\\?")}$`));
+ const narrate = page.locator("[data-media-section='narrate'] [data-draft-task='narrate']");
+ await narrate.getByRole("combobox", { name: "model for narration" }).selectOption("claude-sonnet-5-5");
+ await narrate.getByRole("button", { name: "Draft narration" }).click();
+ await expect(narrate).toHaveAttribute("data-draft-job", "done", { timeout: 20_000 });
const asked = stubAsked("report-draft").at(-1)!;
expect(asked).toMatchObject({ task: "narrate", article: "zeta", iteration: 1, model: "claude-sonnet-5-5", authorization: "Bearer umtool-e2e-token" });
+ await page.goto(urls.articleHref(ZETA, { tab: "iterations" }));
+ await expect(one.locator("[data-step='narrate']")).toHaveAttribute("data-step-status", "done", { timeout: 20_000 });
});
test("use, revise, copy with model, cancel: each through the editor, the list following its jobs", async ({ page, request }) => {
diff --git a/umtool/e2e/bench-shell.spec.ts b/umtool/e2e/bench-shell.spec.ts
@@ -0,0 +1,179 @@
+import { test, expect, type Page } from "@playwright/test";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// THE BENCH SHELL (plans/umtool-redesign.md, P4b; canvas "Clip bench"): one
+// frame for the clip, claim, narration, takes and drafts-review benches --
+// the top bar ← the piece · the bench · N of M · ‹ prev / next › · keys
+// the verdict bar ONE question, its consequence, the actions by result
+// the reader the source's cues, the cited one lit, the cite thread
+// -- fitting 1366×768, no rail, no page scroll.
+//
+// Fixtures (fixtures/bench-shell-fixture.mjs): bench-shell-fixture (READ-ONLY:
+// s01 ends mid-sentence, s02 is the rest of the sentence), media-review-fixture
+// (three fields to review, written by the review test alone); bench-fixture's
+// ledger for the claim bench (read here, never written); takes-fixture.
+// ---------------------------------------------------------------------------
+
+const SHELL = "reports/bench-shell-fixture";
+const REVIEW = "reports/media-review-fixture";
+const BENCH = "reports/bench-fixture";
+const EXTEND = "reports/bench-extend-fixture";
+const FIXTURE = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song");
+const endOf = (id: string) =>
+ (JSON.parse(readFileSync(path.join(FIXTURE, "reports", "bench-extend-fixture", "video.manifest.json"), "utf8")) as { timeline: { id: string; end: number }[] }).timeline.find(
+ (e) => e.id === id,
+ )!.end;
+
+/** The page fits the laptop: no horizontal scroll, no vertical page scroll. */
+async function fits(page: Page) {
+ const { w, h } = await page.evaluate(() => ({
+ w: document.documentElement.scrollWidth,
+ h: document.documentElement.scrollHeight,
+ }));
+ expect(w).toBeLessThanOrEqual(1366);
+ expect(h).toBeLessThanOrEqual(768);
+}
+
+test.beforeEach(async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 768 });
+});
+
+test("the clip bench: the top bar, the one question with its consequence, the reader with the cited cue lit", async ({ page }) => {
+ await page.goto(urls.clipBenchHref(SHELL, "s01"));
+ const top = page.locator("[data-bench-top]");
+ // The head: home, the piece (its Cut), the bench, where you are, the walk, the keys.
+ await expect(top).toHaveAttribute("data-app-header", "bench");
+ await expect(top.getByRole("link", { name: "umtool home" })).toHaveAttribute("href", "/");
+ await expect(top.locator("[data-bench-back]")).toHaveAttribute("href", urls.projectHref(SHELL, { tab: "cut" }));
+ await expect(top.locator("[data-bench-kind]")).toHaveText("Clip bench");
+ await expect(top.locator("[data-bench-pos]")).toHaveText("1 of 2");
+ await expect(top.locator("[data-clip-nav=prev]")).toHaveCount(0);
+ await expect(top.locator("[data-clip-nav=next]")).toHaveText(/s02/);
+ await expect(top.locator("[data-bench-keys]")).toContainText("confirm");
+ // No rail on a bench.
+ await expect(page.locator(".app-rail")).toHaveCount(0);
+
+ // ONE question: s01 ends mid-sentence, so the bar asks to extend it -- and
+ // says what that would cover before you choose.
+ const bar = page.locator("[data-verdict-bar]");
+ await expect(bar.locator("[data-verdict-question]")).toContainText("Extend s01 to the end of the sentence?");
+ await expect(bar.locator("[data-verdict-consequence]")).toHaveText("It would end at 0:09.00 (+3.0 s), covering all of s02.");
+ const extend = bar.locator("[data-verdict-extend]");
+ await expect(extend).toHaveText("Extend to 0:09.00");
+ await expect(extend).toHaveClass(/bg-signal/);
+ // The walk's own answers stay, as outlines while the extension is the question.
+ await expect(bar.locator("[data-verdict-yes]")).not.toHaveClass(/bg-signal/);
+ await expect(bar.locator("[data-verdict-keep]")).toHaveText("Keep the cut here");
+
+ // The reader: the source on the reader surface, the cited cue (3 s) lit, Copy citation.
+ const reader = page.getByRole("complementary", { name: "Reader" });
+ await expect(reader).toBeVisible();
+ await expect(reader.locator("[data-transcript] [data-tcue][data-lit]")).toHaveAttribute("data-tcue", "3");
+ await expect(reader.locator("[data-tcue='3']")).toHaveAttribute("data-cited", "1");
+ await expect(reader.locator("[data-copy-citation]")).toBeVisible();
+ await expect(reader).toContainText("cites 0:03");
+
+ // The answer column still holds the last field on screen.
+ const box = await page.locator("[data-attrib-field=correction]").boundingBox();
+ expect(box!.y + box!.height).toBeLessThanOrEqual(768);
+ await fits(page);
+});
+
+test("the clip bench's keys walk the cut: n and p", async ({ page }) => {
+ await page.goto(urls.clipBenchHref(SHELL, "s01"));
+ // Live once the bench's own keys answer: `x` puts the cursor in the note.
+ const note = page.locator("[data-attrib-field=correction]");
+ await expect(async () => {
+ await page.locator("body").press("x");
+ await expect(note).toBeFocused({ timeout: 500 });
+ }).toPass({ timeout: 10_000 });
+ await note.blur();
+ await page.locator("body").press("n");
+ await expect(page.locator("[data-bench=s02]")).toBeVisible();
+ await expect(page.locator("[data-bench-pos]")).toHaveText("2 of 2");
+ // s02 ends the sentence and is locked: the bar asks the walk's question.
+ await expect(page.locator("[data-verdict-question]")).toHaveText("Is s02 what the report says it is?");
+ await expect(page.locator("[data-verdict-yes]")).toHaveClass(/bg-signal/);
+ await page.locator("body").press("p");
+ await expect(page.locator("[data-bench=s01]")).toBeVisible();
+});
+
+test("Extend saves the sentence's end at once, and Reset puts the window back", async ({ page }) => {
+ await page.goto(urls.clipBenchHref(EXTEND, "s01"));
+ const bar = page.locator("[data-verdict-bar]");
+ await bar.locator("[data-verdict-extend]").click();
+ await expect.poll(() => endOf("s01")).toBe(9);
+ // The clip now ends the sentence: the bar asks the walk's question.
+ await expect(bar.locator("[data-verdict-question]")).toHaveText("Is s01 what the report says it is?");
+ await expect(page.locator("[data-bench-note]")).toContainText("R undoes it");
+ // Reset (the button, as R) undoes the saved extension.
+ await page.locator("[data-reset]").click();
+ await expect.poll(() => endOf("s01")).toBe(6);
+ await expect(bar.locator("[data-verdict-question]")).toHaveText("Extend s01 to the end of the sentence?");
+ await expect(page.locator("[data-reset]")).toBeDisabled();
+});
+
+test("the claim bench: its context on the reader, the cited cue lit, j/k from anywhere, Save ruling in the verdict bar", async ({ page }) => {
+ await page.goto(urls.claimBenchHref(BENCH, "k01"));
+ await expect(page.locator("[data-bench-top] [data-bench-kind]")).toHaveText("Claim bench");
+ await expect(page.locator("[data-bench-pos]")).toHaveText("1 of 3");
+ const ctx = page.getByTestId("claim-context");
+ const lit = ctx.locator("[data-lit-line][data-lit]");
+ await expect(lit).toHaveAttribute("data-cited", "1");
+ await expect(page.locator("[data-verdict-question]")).toHaveText("Save the ruling on k01?");
+ await expect(page.getByTestId("claim-save")).toHaveText("Save ruling");
+ // j moves the lit cue, from anywhere on the page that is not a field.
+ const first = await lit.textContent();
+ await page.locator("body").press("j");
+ await expect(lit).not.toHaveText(first ?? "");
+ await fits(page);
+});
+
+test("the drafts review is a bench: j/k light a field, the bar asks about it, a approves, r goes to the note", async ({ page }) => {
+ await page.goto(urls.reviewHref(REVIEW));
+ await expect(page.locator("[data-bench-top] [data-bench-kind]")).toHaveText("Drafts review");
+ await expect(page.locator("[data-bench-back]")).toHaveAttribute("href", urls.projectHref(REVIEW, { tab: "media" }));
+ const rows = page.locator("[data-draft-row]");
+ await expect(rows).toHaveCount(3);
+ const bar = page.locator("[data-verdict-bar]");
+ // The first field is lit: m01's on-screen text, the clip it is drawn over on the reader.
+ await expect(bar.locator("[data-verdict-question]")).toHaveText("Approve the drafted on-screen text of m01?");
+ await expect(bar.locator("[data-verdict-consequence]")).toHaveText("A final build refuses it until it is approved.");
+ const reader = page.getByRole("complementary", { name: "Reader" });
+ await expect(reader.locator("[data-lit-line][data-lit]")).toBeVisible();
+ // Its provenance: the second attempt kept, the first's broken rule said.
+ await expect(page.locator("[data-draft-row='onscreen/m01/onscreen'] [data-draft-prov]")).toContainText("attempt 2 of 2 chosen");
+ await expect(page.locator("[data-draft-row='onscreen/m01/onscreen'] [data-draft-prov]")).toContainText("title over 60 characters");
+
+ // Live once the list has hydrated; then j, a.
+ await expect(page.getByRole("group", { name: "Drafted fields" })).toHaveAttribute("data-hydrated", "");
+ await page.locator("body").press("j");
+ await expect(bar).toHaveAttribute("data-verdict-for", "onscreen/m02/onscreen");
+ await page.locator("body").press("a");
+ await expect(page.locator("[data-draft-row='onscreen/m02/onscreen']")).toHaveAttribute("data-state", "approved");
+ await expect(bar.locator("[data-verdict-question]")).toHaveText("The on-screen text of m02 is approved.");
+
+ // The narration card: no clip under it -- the reader says so; r puts the cursor in its note.
+ await page.locator("body").press("j");
+ await expect(bar).toHaveAttribute("data-verdict-for", "narrate/k01/narration");
+ await expect(reader).toContainText("No source window for this field");
+ await page.locator("body").press("r");
+ await expect(page.locator("[data-draft-row='narrate/k01/narration'] [data-draft-note]")).toBeFocused();
+ await fits(page);
+});
+
+test("narration and takes wear the same shell: the top bar back to the piece, and one question", async ({ page }) => {
+ await page.goto(urls.narrationHref("reports/narration-review-fixture"));
+ await expect(page.locator("[data-bench-shell=narration] [data-bench-kind]")).toHaveText("Narration");
+ await expect(page.locator("[data-verdict-question]")).toContainText("narration of");
+ await fits(page);
+
+ await page.goto(urls.takesHref("reports/takes-fixture"));
+ await expect(page.locator("[data-bench-shell=takes] [data-bench-kind]")).toHaveText("Takes");
+ await expect(page.locator("[data-verdict-question]")).toHaveText("Listen to a take to judge it: like, maybe or no.");
+ await expect(page.locator("[data-bench-keys]")).toContainText("listen");
+});
diff --git a/umtool/e2e/claim-bench.spec.ts b/umtool/e2e/claim-bench.spec.ts
@@ -2,6 +2,7 @@ import { test, expect } from "@playwright/test";
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
// ---------------------------------------------------------------------------
// The claim bench, and the two decision kinds that drive it.
@@ -22,7 +23,7 @@ const UMTOOL = path.join(HERE, "..");
const FIXTURE = path.join(UMTOOL, ".e2e-song");
const PROJECT = "reports/bench-fixture";
const MANIFEST = path.join(FIXTURE, "reports", "bench-fixture", "video.manifest.json");
-const claimPage = (id: string) => `/browse/${PROJECT}/claim/${id}`;
+const claimPage = (id: string) => urls.claimBenchHref(PROJECT, id);
type Claim = {
id: string;
diff --git a/umtool/e2e/clip-bench.spec.ts b/umtool/e2e/clip-bench.spec.ts
@@ -41,8 +41,8 @@ const PROJECT = "reports/bench-fixture";
// walk-fixture in make-fixture.mjs.
const WALK = "reports/walk-fixture";
const MANIFEST = path.join(FIXTURE, "reports", "bench-fixture", "video.manifest.json");
-const bench = (clip: string) => `/browse/${PROJECT}/clip/${clip}`;
-const walkBench = (clip: string) => `/browse/${WALK}/clip/${clip}`;
+const bench = (clip: string) => urls.clipBenchHref(PROJECT, clip);
+const walkBench = (clip: string) => urls.clipBenchHref(WALK, clip);
const readClipIn = (project: string, id: string) => {
const file = path.join(FIXTURE, ...project.split("/"), "video.manifest.json");
diff --git a/umtool/e2e/draft-review.spec.ts b/umtool/e2e/draft-review.spec.ts
@@ -88,7 +88,7 @@ test("the review page: every drafted field, the narration's badge, and Use this
// Approve the narration here; the narration page shows who drafted it, and its state.
await k01.locator('[data-draft-action="approve"]').click();
await expect(k01).toHaveAttribute("data-state", "approved");
- await page.goto(`/browse/${PROJECT}/narration`);
+ await page.goto(urls.narrationHref(PROJECT));
const card = page.locator('[data-narration-card="k01"]');
await expect(card.locator("[data-narration-drafted]")).toHaveText("drafted by qwen3:8b");
await expect(card).toHaveAttribute("data-state", "approved");
@@ -115,7 +115,7 @@ test("a final build refuses an unapproved draft, and builds once it is approved"
expect(JSON.stringify(refused)).toContain("timeline c02: its on-screen text (drafted by qwen3:8b) is not approved");
expect(existsSync(path.join(BUILD_DIR, "out", "draft-review-build-fixture.mp4"))).toBe(false);
- await page.goto(`/browse/${BUILD_PROJECT}/review`);
+ await page.goto(urls.reviewHref(BUILD_PROJECT));
const row = page.locator('[data-draft-row="onscreen/c02/onscreen"]');
await row.locator('[data-draft-action="approve"]').click();
await expect(row).toHaveAttribute("data-state", "approved");
diff --git a/umtool/e2e/fixtures/bench-shell-fixture.mjs b/umtool/e2e/fixtures/bench-shell-fixture.mjs
@@ -0,0 +1,116 @@
+// What bench-shell.spec.ts and piece.spec.ts's Media test act on (P4b): their
+// own projects, so the other specs' writes never move what they assert.
+//
+// reports/bench-shell-fixture/ READ-ONLY (bench-extend-fixture, the same, is
+// written by the Extend-and-Reset test). vid1's run-on cue (3-6 s) and the
+// sentence that closes at 9 s:
+// s01 3.00-6.00 ends mid-sentence: the verdict bar asks to extend it
+// to 0:09.00, which would cover all of s02
+// s02 6.00-9.00 locked
+// reports/media-tab-fixture/ writable by piece.spec's Media test: three
+// reports/media-review-fixture/ fields to review, and the same for the
+// review bench (bench-shell.spec), each with the draft files that say
+// where they came from:
+// m01 on-screen text drafted by qwen3:8b on its SECOND attempt; the
+// first broke "title over 60 characters" (onscreen-draft.json)
+// m02 on-screen text drafted on its first attempt
+// k01 a card's narration from release 25's narrate (narration-draft.json,
+// its units at the top level, no mark in the manifest): attempt 1
+// broke "text in quotation marks", attempt 2 was kept
+//
+// Synthetic, like every fixture.
+import { copyFileSync, mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+const AT = "2026-10-13T10:00:00.000Z";
+const P = (task, attempt) => ({ task, model: "qwen3:8b", at: AT, iteration: 1, attempt });
+
+const write = (dir, name, doc) => {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, name), JSON.stringify(doc, null, 2) + "\n");
+};
+
+/**
+ * @param {{ reports: string, manifest: Function, cachedWindow: string }} o
+ * `manifest` is make-fixture's manifest(slug, title, provenance, timeline);
+ * `cachedWindow` the vid1 0-9 s window the build fixtures share.
+ */
+export function makeBenchShellFixture({ reports, manifest, cachedWindow }) {
+ // bench-shell-fixture is read-only; bench-extend-fixture, the same two clips,
+ // is written by the Extend-and-Reset test alone.
+ let bench = null;
+ for (const slug of ["bench-shell-fixture", "bench-extend-fixture"]) {
+ const dir = path.join(reports, slug);
+ write(
+ dir,
+ "video.manifest.json",
+ manifest(slug, "The Bench Shell Fixture", { siteOrigin: "https://archive.example" }, [
+ { type: "clip", id: "s01", video: "vid1", start: 3.0, end: 6.0, cite: 3, section: 0, quote: "and because" },
+ { type: "clip", id: "s02", video: "vid1", start: 6.0, end: 9.0, cite: 6, section: 0, lock: true, quote: "the rest of it" },
+ ]),
+ );
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", path.basename(cachedWindow)));
+ bench ??= dir;
+ }
+
+ const made = [];
+ for (const slug of ["media-tab-fixture", "media-review-fixture"]) {
+ const dir = path.join(reports, slug);
+ write(
+ dir,
+ "video.manifest.json",
+ manifest(slug, "The Media Tab Fixture", { siteOrigin: "https://archive.example" }, [
+ {
+ type: "clip", id: "m01", video: "vid1", start: 3.0, end: 6.0, cite: 3, section: 0, lock: true, quote: "and because",
+ onscreen: { title: "She will not sell" }, drafted: { onscreen: P("onscreen", 2) },
+ },
+ {
+ type: "clip", id: "m02", video: "vid1", start: 9.0, end: 12.0, cite: 9, section: 0, lock: true, quote: "another whole sentence",
+ onscreen: { title: "The county voted" }, drafted: { onscreen: P("onscreen", 1) },
+ },
+ { type: "card", id: "k01", style: "chapter", seconds: "auto", heading: "The county", narration: { text: "Half a year on, the county said yes." } },
+ ]),
+ );
+ write(dir, "onscreen-draft.json", {
+ task: "onscreen",
+ model: "qwen3:8b",
+ at: AT,
+ article: "media-tab",
+ iteration: 1,
+ units: {
+ m01: {
+ target: { entry: "m01", field: "onscreen" },
+ label: "m01",
+ attempts: [
+ { value: { title: "She says she would never, ever sell the family bakery to any chain" }, hard: ["title over 60 characters"], soft: [] },
+ { value: { title: "She will not sell" }, hard: [], soft: [] },
+ ],
+ chosen: { value: { title: "She will not sell" }, hard: [], soft: [] },
+ applied: "applied",
+ },
+ m02: {
+ target: { entry: "m02", field: "onscreen" },
+ label: "m02",
+ attempts: [{ value: { title: "The county voted" }, hard: [], soft: [] }],
+ chosen: { value: { title: "The county voted" }, hard: [], soft: [] },
+ applied: "applied",
+ },
+ },
+ checks: [{ name: "onscreen", ok: true, detail: "2 field(s) drafted" }],
+ alternatives: [],
+ });
+ write(dir, "narration-draft.json", {
+ k01: {
+ heading: "The county",
+ attempts: [
+ { text: "\"Yes,\" said the county.", hard: ["text in quotation marks: no quotes in narration"], soft: [] },
+ { text: "Half a year on, the county said yes.", hard: [], soft: [] },
+ ],
+ chosen: { text: "Half a year on, the county said yes.", hard: [], soft: [] },
+ },
+ });
+ made.push(dir);
+ }
+ return { bench, media: made };
+}
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -28,6 +28,7 @@ import { makeMediaDraftFixture } from "./media-draft-fixture.mjs";
import { makeMediaSurfacesFixture } from "./media-surfaces-fixture.mjs";
import { makeDeleteFixture } from "./delete-fixture.mjs";
import { makeDraftReviewFixture } from "./draft-review-fixture.mjs";
+import { makeBenchShellFixture } from "./bench-shell-fixture.mjs";
import { makeYoutubeFixture } from "./youtube-fixture.mjs";
import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs";
import { makeRunTraceFixture } from "./run-trace-fixture.mjs";
@@ -1661,6 +1662,8 @@ for (const dir of [BENCH, BUILD, ONSCREEN, ONSCREEN_BUILD, ONSCREEN_POSTS, ONSCR
// Release 28: drafted fields to review, and a final build they hold
// (draft-review.spec.ts).
makeDraftReviewFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
+// P4b: the bench shell's own clips, and the Media tab's fields with their draft files.
+makeBenchShellFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts).
makeYoutubeFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
@@ -1978,5 +1981,6 @@ console.log(` takes-fixture (writable: takes/ with 4 takes over 2 gro
console.log(` narration-fixture (writable: a narrated card, voiced by the editor stub's tone)`);
console.log(` narration-review-fixture (writable: two narrated cards, nothing judged)`);
console.log(` draft-review-fixture (writable: drafted on-screen, narration, teaser; an alternative), draft-review-build-fixture`);
+console.log(` bench-shell-fixture (read-only: s01 mid-sentence), media-tab-fixture, media-review-fixture (three fields with draft files)`);
console.log(` youtube-fixture (writable: a drafted publish.youtube, built fast to out/youtube.txt)`);
console.log(` ${taken} candidate files copied, 2 mix tracks synthesised`);
diff --git a/umtool/e2e/media-surfaces.spec.ts b/umtool/e2e/media-surfaces.spec.ts
@@ -6,13 +6,14 @@ import { WARM_TIMEOUT, warm } from "./warm";
import * as urls from "./urls";
// ---------------------------------------------------------------------------
-// Release 28 M9, the surfaces of the media drafts:
-// - "Draft with <model>" per section on a project page: the job asked of the
-// editor (its model, its entries, its force), followed to its end; then
-// the section re-read — the badge, the last run, the alternative kept for
-// the operator's field and Use this; a project made from no iteration
-// offers none, and says why;
-// - Draft everything on the Iterations tab: the chain with its drafts, a
+// Release 28 M9, the surfaces of the media drafts -- since P4b ONE surface,
+// the Media tab:
+// - "Draft with <model>" per section: the job asked of the editor (its
+// model, its entries, its force), followed to its end; then the section
+// re-read — the field's line with its provenance and review, the last
+// run, the alternative kept for the operator's field and Use this; a
+// project made from no iteration offers none, and says why;
+// - Draft everything on the Media tab: the chain with its drafts, a
// refused draft recorded failed and passed, the panels skipped, the
// voices, the fast build and the podcast, then the YouTube draft and
// out/youtube.txt.
@@ -33,13 +34,13 @@ const asked = () =>
test.beforeAll(async ({ playwright }) => {
test.setTimeout(WARM_TIMEOUT);
- await warm(playwright, [`/browse/${PROJECT}`, `/api/articles/draft?project=${encodeURIComponent(PROJECT)}`, "/api/articles/policy", `/articles/${ARTICLE}?tab=iterations`]);
+ await warm(playwright, [urls.section(PROJECT, "drafts"), urls.section(`gen-projects/${ARTICLE}/i2`, "drafts"), `/api/articles/draft?project=${encodeURIComponent(PROJECT)}`, "/api/articles/policy", `/articles/${ARTICLE}?tab=iterations`]);
});
test("Draft with <model> per section: the job followed, the badge, the last run, an alternative and Use this", async ({ page }) => {
test.setTimeout(180_000);
await page.goto(urls.section(PROJECT, "drafts"));
- const panel = page.getByRole("region", { name: "draft with a model" });
+ const panel = page.getByRole("region", { name: "Media drafts" });
await expect(panel).toHaveAttribute("data-draft-panel", `${ARTICLE}/i1`);
// Seven sections; flips and threads say why they cannot draft on this cut.
await expect(panel.locator("[data-draft-task]")).toHaveCount(7);
@@ -53,11 +54,14 @@ test("Draft with <model> per section: the job followed, the badge, the last run,
await cut.getByRole("button", { name: "Draft the cut" }).click();
await expect(cut).toHaveAttribute("data-draft-job", "done", { timeout: 30_000 });
expect(asked().at(-1)).toMatchObject({ task: "cut", article: ARTICLE, iteration: 1, model: "claude-sonnet-5-5", authorization: "Bearer umtool-e2e-token" });
- await expect(cut.locator("[data-draft-badge='cut/*/timeline'] [data-draft-by]")).toHaveText("drafted by claude-sonnet-5-5");
+ // The field's line: its provenance (the draft file, by what model, the attempt) and its review.
+ const order = panel.locator("[data-draft-row='cut/*/timeline']");
+ await expect(order.locator("[data-draft-prov]")).toContainText("by claude-sonnet-5-5");
+ await expect(order.locator("[data-draft-prov]")).toContainText("cut-draft.json");
await expect(cut.locator("[data-draft-run='cut']")).toContainText("1 written");
expect(manifestOf(1).timeline.filter((e: { type: string }) => e.type === "clip").map((e: { id: string }) => e.id)).toEqual(["c02", "c01"]);
- await cut.locator("[data-draft-badge='cut/*/timeline']").getByRole("button", { name: "Approve" }).click();
- await expect(cut.locator("[data-draft-badge='cut/*/timeline']")).toHaveAttribute("data-state", "approved");
+ await order.locator("[data-draft-action='approve']").click();
+ await expect(order).toHaveAttribute("data-state", "approved");
// On-screen, limited to the entry ticked.
const onscreen = panel.locator("[data-draft-task='onscreen']");
@@ -84,7 +88,7 @@ test("Draft with <model> per section: the job followed, the badge, the last run,
await expect(yt.locator("[data-draft-run='youtube']")).toContainText("1 kept as an alternative", { timeout: 30_000 });
expect(asked().at(-1)).toMatchObject({ task: "youtube", force: true });
expect(manifestOf(1).publish.youtube.title).toBe("The operator's own title");
- const alt = yt.locator("[data-draft-alternatives='youtube/*/publish.youtube']");
+ const alt = panel.locator("[data-media-section='youtube'] [data-draft-alternatives='youtube/*/publish.youtube']");
await expect(alt).toContainText("The county vote, as the channel told it");
await alt.getByRole("button", { name: "Use this" }).click();
await expect.poll(() => manifestOf(1).publish.youtube.title, { timeout: 15_000 }).toBe("The county vote, as the channel told it");
@@ -93,18 +97,18 @@ test("Draft with <model> per section: the job followed, the badge, the last run,
// A project made from no iteration offers no draft, and says why.
await page.goto(urls.section("reports/youtube-fixture", "drafts"));
- await expect(page.getByRole("region", { name: "draft with a model" }).locator("[data-draft-unlinked]")).toContainText("not made from an article's iteration");
+ await expect(page.getByRole("region", { name: "Media drafts" }).locator("[data-draft-unlinked]")).toHaveText("Not from an article iteration — Draft with is off here.");
});
test("Draft everything: every draft in order on the model chosen, a refused one passed, the panels skipped, then the fast build, the podcast and out/youtube.txt", async ({ page }) => {
test.setTimeout(420_000);
+ // On i2's cut's Media tab (P4b): the Iterations tab links it.
await page.goto(urls.articleHref({ site: "articles", id: ARTICLE }, { tab: "iterations" }));
- const two = page.locator("[data-iteration='2']");
- // The Iterations tab's per-step drafts, beside Narrate.
- await expect(two.getByRole("combobox", { name: "draft task for i2" })).toBeVisible();
- await two.getByRole("combobox", { name: "Draft everything model for i2" }).selectOption("qwen3:8b");
+ await page.locator("[data-iteration='2'] [data-media-link]").click();
+ await expect(page.getByRole("region", { name: "Media drafts" })).toHaveAttribute("data-draft-panel", `${ARTICLE}/i2`);
+ await page.getByRole("combobox", { name: "Draft everything model" }).selectOption("qwen3:8b");
const before = asked().length;
- await two.getByRole("button", { name: "Draft everything" }).click();
+ await page.getByRole("button", { name: "Draft everything" }).click();
const chain = page.getByRole("region", { name: "i2 Draft everything" });
await expect(chain.locator("[data-chain-step]")).toHaveCount(15);
const step = (name: string) => chain.locator(`[data-chain-step='${name}']`);
diff --git a/umtool/e2e/onscreen.spec.ts b/umtool/e2e/onscreen.spec.ts
@@ -333,7 +333,7 @@ test("the clip bench's on-screen fields preview live and save through the window
}) => {
await putChrome(request, PROJECT, DECK_ON);
await putOnscreen(request, PROJECT, { c01: null });
- await page.goto(`/browse/${PROJECT}/clip/c01`);
+ await page.goto(urls.clipBenchHref(PROJECT, "c01"));
await expect(page.getByTestId("bench-onscreen")).toHaveAttribute("data-deck-on", "1");
await expect(page.getByTestId("bench-deck-strip")).toHaveAttribute("data-deck-ready", "1", { timeout: 30_000 });
diff --git a/umtool/e2e/piece.spec.ts b/umtool/e2e/piece.spec.ts
@@ -360,3 +360,73 @@ test("an article drafted from a research board: at Research (its sweep running,
rmSync(path.join(FIXTURE, "articles", article), { recursive: true, force: true });
}
});
+
+// ---------------------------------------------------------------------------
+// The Media tab (P4b; canvas "Piece · Media"): ONE surface for every drafted
+// field -- its words, where it came from (the draft file, the model, the
+// attempt kept, the rule a refused attempt broke), approve or reject per
+// field and all at once -- with the on-screen panel moved in from Build.
+// fixtures/bench-shell-fixture.mjs: media-tab-fixture, written here alone.
+// ---------------------------------------------------------------------------
+test("the Media tab: every drafted field with where it came from, approve per field and all, on-screen moved from Build", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 768 });
+ const P = "reports/media-tab-fixture";
+ await page.goto(urls.projectHref(P, { tab: "media" }));
+ await expect(tab(page, "media")).toHaveAttribute("aria-current", "page");
+ // One number: the fields awaiting review -- the two drafted titles and the release-25 narration its
+ // draft file records -- on the tab, in the header and on the Inbox's drafts card.
+ await expect(tab(page, "media")).toHaveText("Media3");
+ const media = page.getByRole("region", { name: "Media drafts" });
+ await expect(media.locator("[data-media-counts]")).toHaveText("3 fields · 0 approved · 3 to review");
+ await expect(media.locator("[data-draft-row]")).toHaveCount(3);
+ // Made from no iteration, it drafts nothing: the sections with fields, in Draft everything's order.
+ await expect(media.locator("[data-media-section]")).toHaveCount(2);
+ await expect(media.locator("[data-draft-unlinked]")).toHaveText("Not from an article iteration — Draft with is off here.");
+
+ const m01 = media.locator("[data-draft-row='onscreen/m01/onscreen']");
+ await expect(m01.locator("[data-draft-text]")).toContainText("She will not sell");
+ const prov = m01.locator("[data-draft-prov]");
+ for (const words of ["onscreen-draft.json", "by qwen3:8b", "attempt 2 of 2 chosen", "attempt 1 failed", "title over 60 characters", "not reviewed"]) {
+ await expect(prov).toContainText(words);
+ }
+ // A release-25 narration: no mark in the manifest, its file says how it was made.
+ const k01 = media.locator("[data-draft-row='narrate/k01/narration']").locator("[data-draft-prov]");
+ await expect(k01).toContainText("narration-draft.json");
+ await expect(k01).toContainText("text in quotation marks");
+ // Signal on the lit field's Approve draft only.
+ await expect(media.locator("[data-draft-action=approve].bg-signal")).toHaveCount(1);
+
+ // A chip narrows the list to its section.
+ await media.locator("[data-media-chip=narrate]").click();
+ await expect(media.locator("[data-media-section]")).toHaveCount(1);
+ await expect(media.locator("[data-draft-row]")).toHaveCount(1);
+ await media.locator("[data-media-chip=all]").click();
+ await expect(media.locator("[data-draft-row]")).toHaveCount(3);
+
+ // The Inbox's drafts card counts the same three fields.
+ const before = (await (await page.request.get("/api/browse/decisions")).json()) as { items: { kind: string; project?: string }[] };
+ expect(before.items.filter((d) => d.kind === "drafts-unreviewed" && d.project === P)).toHaveLength(3);
+
+ // Approve one, then all the rest.
+ const m02 = media.locator("[data-draft-row='onscreen/m02/onscreen']");
+ await m02.locator("[data-draft-action=approve]").click();
+ await expect(m02).toHaveAttribute("data-state", "approved");
+ await expect(media.locator("[data-approve-all]")).toHaveText("Approve all 2");
+ await media.locator("[data-approve-all]").click();
+ await expect(media.locator("[data-draft-row][data-state=approved]")).toHaveCount(3);
+ await expect(media.locator("[data-drafts-gate]")).toHaveAttribute("data-drafts-gate", "passes");
+ await expect(media.locator("[data-approve-all]")).toHaveCount(0);
+ // Nothing awaits review: the tab says no number, and the Inbox has no drafts card for it.
+ await page.reload();
+ await expect(tab(page, "media")).toHaveText("Media");
+ const inbox = (await (await page.request.get("/api/browse/decisions")).json()) as { items: { kind: string; project?: string }[] };
+ expect(inbox.items.filter((d) => d.kind === "drafts-unreviewed" && d.project === P)).toEqual([]);
+
+ // The on-screen panel is Media's now; the Build tab is the build.
+ await expect(page.getByTestId("onscreen-section")).toBeVisible();
+ const w = await page.evaluate(() => document.documentElement.scrollWidth);
+ expect(w).toBeLessThanOrEqual(1366);
+ await page.goto(urls.projectHref(P, { tab: "build" }));
+ await expect(page.getByTestId("onscreen-section")).toHaveCount(0);
+ await expect(page.locator("[data-build-options]")).toBeVisible();
+});
diff --git a/umtool/e2e/takes.spec.ts b/umtool/e2e/takes.spec.ts
@@ -16,10 +16,10 @@ import * as urls from "./urls";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const PROJECT_DIR = path.join(HERE, "..", ".e2e-song", "reports", "takes-fixture");
const VERDICTS = path.join(PROJECT_DIR, "takes", "verdicts.json");
-const PAGE = "/projects/reports/takes-fixture/takes";
+const PAGE = urls.takesHref("reports/takes-fixture");
test("a project with no takes/ says so, and its page has no takes link", async ({ page }) => {
- const res = await page.goto("/browse/reports/report-fixture/takes");
+ const res = await page.goto(urls.takesHref("reports/report-fixture"));
expect(res?.status()).toBe(200);
await expect(page.locator("[data-takes-empty]")).toContainText("No takes yet");
diff --git a/umtool/lib/articles/generation.ts b/umtool/lib/articles/generation.ts
@@ -25,6 +25,7 @@ import { agentToken } from "@/lib/annotations/agentAuth.mjs";
import { DEFAULT_PROJECTS_ROOT, REPO_ROOT, chainStart, chainStepsOf, doneSteps } from "@/lib/report/chain.mjs";
import { recentJobs, type Job } from "@/lib/jobs";
import { sitesPaths } from "./sites";
+import { REPORTS_ROOT } from "@/lib/paths.mjs";
// GENERATION, AS UMTOOL SEES IT (release 27 S8): an article's iterations, the
// policy, the editor's channels, and the editor's report-draft jobs.
@@ -340,11 +341,21 @@ export type IterationRow = {
/** The iteration whose report it carries (itself, or the nearest ancestor that made one). */
reportFrom: number | null;
projectDir: string | null;
+ /** The project's id (its path under REPORTS_ROOT), or null when it is not under it (P4b: the Media tab's link). */
+ projectId: string | null;
hasManifest: boolean;
currentReport: boolean;
currentVideo: boolean;
};
+/** A project directory's id: its path under REPORTS_ROOT, posix, or null outside it. */
+function projectIdOfDir(dir: string | null): string | null {
+ if (!dir) return null;
+ const rel = path.relative(REPORTS_ROOT, path.resolve(dir));
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return null;
+ return rel.split(path.sep).join("/");
+}
+
export type ChainMode = "video" | "draft-all";
export type ChainView = {
mode: ChainMode;
@@ -415,6 +426,7 @@ function rowOf(it: Iteration, hasReport: Map<number, boolean>, byN: Map<number,
hasReport: hasReport.get(it.n) ?? false,
reportFrom,
projectDir,
+ projectId: projectIdOfDir(projectDir),
hasManifest: projectDir ? exists(path.join(/* turbopackIgnore: true */ projectDir, "video.manifest.json")) : false,
currentReport: current.report === it.n,
currentVideo: current.video === it.n,
diff --git a/umtool/lib/cite-thread.mjs b/umtool/lib/cite-thread.mjs
@@ -0,0 +1,21 @@
+// The reader's cite thread labels (components/ui/cite-thread.tsx ReaderThread):
+// 0:00 at the left, the cite under its notch, the length at the right -- and
+// the cite's label never on top of an end's (P4b: "0:000:03" in a bench's
+// reader). An end label gives way when the cite sits close to it; otherwise
+// the cite's label is held clear of it, measured in `ch` (the labels are mono).
+//
+// Pure: `node --test` runs it.
+
+/**
+ * @param {{ pct: number, citeChars: number, startChars: number, endChars: number }} o
+ * pct: the cite's place, 0..100; the *Chars: each label's length
+ * @returns {{ showStart: boolean, showEnd: boolean, citeLeft: string }}
+ */
+export function threadLabels({ pct, citeChars, startChars, endChars }) {
+ const showStart = pct >= 12;
+ const showEnd = pct <= 80;
+ const gap = 1;
+ const lo = showStart ? `${startChars + gap}ch` : "0px";
+ const hi = showEnd ? `calc(100% - ${endChars + gap + citeChars}ch)` : `calc(100% - ${citeChars}ch)`;
+ return { showStart, showEnd, citeLeft: `clamp(${lo}, calc(${pct}% - ${citeChars / 2}ch), ${hi})` };
+}
diff --git a/umtool/lib/cite-thread.test.mjs b/umtool/lib/cite-thread.test.mjs
@@ -0,0 +1,18 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { threadLabels } from "./cite-thread.mjs";
+
+test("the cite's label is held clear of the end labels it shares the line with", () => {
+ // 0:03 of 0:21 (a bench's reader): 0:00 shows, and the cite starts past it.
+ const near = threadLabels({ pct: (3 / 21) * 100, citeChars: 4, startChars: 4, endChars: 4 });
+ assert.equal(near.showStart, true);
+ assert.equal(near.showEnd, true);
+ assert.match(near.citeLeft, /^clamp\(5ch, calc\(14\.2\d+% - 2ch\), calc\(100% - 9ch\)\)$/);
+ // At the very start the 0:00 gives way and the cite may sit at the edge.
+ assert.equal(threadLabels({ pct: 3, citeChars: 4, startChars: 4, endChars: 7 }).showStart, false);
+ assert.match(threadLabels({ pct: 3, citeChars: 4, startChars: 4, endChars: 7 }).citeLeft, /^clamp\(0px,/);
+ // Near the end the length gives way.
+ const end = threadLabels({ pct: 98, citeChars: 7, startChars: 4, endChars: 7 });
+ assert.equal(end.showEnd, false);
+ assert.match(end.citeLeft, /calc\(100% - 7ch\)\)$/);
+});
diff --git a/umtool/lib/inbox.ts b/umtool/lib/inbox.ts
@@ -9,7 +9,8 @@ import { openDecisions, projectRefs, summariseProject, type ProjectRef } from ".
import { readManifest, reportSignature } from "./projects/report.mjs";
import { draftsView } from "./report/drafts.mjs";
import { reviewHref } from "./hrefs";
-import { draftsDecisions } from "./inbox/drafts.mjs";
+import { awaitingReview, draftsDecisions } from "./inbox/drafts.mjs";
+import { readFieldProvenance } from "./report/draft-provenance.mjs";
import { pieceOfDecision, readPieceGraph, type Piece, type PieceGraph } from "./pieces";
import { lifecycleOf, readLifecycle, type LifecycleRead } from "./lifecycle";
import { isMuted, readMutes } from "./mutes";
@@ -243,11 +244,13 @@ async function projectDrafts(ref: ProjectRef): Promise<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"))) {
+ // Who drafted a field with no mark: its task's draft file (release 25's narration).
+ const provenance = view.rows.some((r) => r.state === "unreviewed" || r.state === "edited") ? await readFieldProvenance(ref.dir, manifest) : {};
+ if (awaitingReview(view.rows, provenance).length) {
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) => ({
+ value = draftsDecisions({ project: ref.id, projectTitle: title, href: reviewHref(ref.id), at, view, provenance }).map((d) => ({
...d,
projectKind: ref.kind,
})) as Decision[];
diff --git a/umtool/lib/inbox/drafts.mjs b/umtool/lib/inbox/drafts.mjs
@@ -13,6 +13,23 @@
export const WAITING = new Set(["unreviewed", "edited"]);
/**
+ * THE fields awaiting review (P4b: one number, one meaning -- the Inbox's
+ * drafts card, the piece's Media tab count and its "to review"): a field a
+ * model drafted -- its `drafted` mark, or a task's draft file records it
+ * (release 25's narration-draft.json carries no mark) -- whose verdict is not
+ * given on its current value. A narration written by hand is listed and can
+ * be judged, but nothing waits on it.
+ *
+ * @template {{ address: string, state: string, drafted: unknown }} R
+ * @param {R[]} rows draftsView()'s rows
+ * @param {Record<string, unknown>} [provenance] readFieldProvenance()'s, by address
+ * @returns {R[]}
+ */
+export function awaitingReview(rows, provenance = {}) {
+ return (rows ?? []).filter((r) => WAITING.has(r.state) && (!!r.drafted || !!provenance?.[r.address]));
+}
+
+/**
* What a drafts card is about, the canvas's card title: which kinds of field
* and how many ("Narration draft · 5 fields").
*
@@ -48,10 +65,11 @@ export function draftsWhy(rows) {
* @param {{
* project: string, projectTitle: string, href: string, at: number,
* view: { rows: { address: string, label: string, state: string, drafted: { model?: string } | null }[] },
+ * provenance?: Record<string, unknown>,
* }} o
*/
-export function draftsDecisions({ project, projectTitle, href, at, view }) {
- const waiting = (view?.rows ?? []).filter((r) => r.drafted && WAITING.has(r.state));
+export function draftsDecisions({ project, projectTitle, href, at, view, provenance = {} }) {
+ const waiting = awaitingReview(view?.rows ?? [], provenance);
if (!waiting.length) return [];
const what = draftsWhat(waiting);
const why = draftsWhy(waiting);
diff --git a/umtool/lib/inbox/drafts.test.mjs b/umtool/lib/inbox/drafts.test.mjs
@@ -3,7 +3,7 @@ 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 { awaitingReview, draftsDecisions, draftsWhy } from "./drafts.mjs";
import { annotate, summarizeGroups } from "./groups.mjs";
import { reportSignature } from "../projects/report.mjs";
@@ -25,6 +25,10 @@ test("one row per waiting field; approved, rejected and the operator's own are n
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")] } }), []);
+ // A narration with no mark that a task's draft file records (release 25's narrate) waits too (P4b).
+ const withFile = draftsDecisions({ project: "reports/x", projectTitle: "X", href: "/", at: 5, view, provenance: { "narrate/k03/narration": { file: "narration-draft.json" } } });
+ assert.deepEqual(withFile.map((d) => d.target), ["narrate/k01/narration", "narrate/k02/narration", "narrate/k03/narration"]);
+ assert.deepEqual(awaitingReview(view.rows).map((r) => r.address), ["narrate/k01/narration", "narrate/k02/narration"]);
});
test("the sentence names the kinds of field and the models", () => {
diff --git a/umtool/lib/pieces/tabs.mjs b/umtool/lib/pieces/tabs.mjs
@@ -139,14 +139,16 @@ export const SECTION_TAB = {
cut: "cut",
takes: "cut",
corrections: "cut",
- // Media: r28's drafts (the panel, the review and narration links) and the upload's text.
+ // Media: every drafted field and each section's Draft with (P4b's one surface),
+ // the review and narration benches' links, the on-screen panel (moved from
+ // Build in P4b) and the upload's text.
drafts: "media",
review: "media",
narration: "media",
youtube: "media",
- // Build: the build chain, the on-screen panel (parked whole until P4b), the final mp4.
+ onscreen: "media",
+ // Build: the build chain and the final mp4.
build: "build",
- onscreen: "build",
final: "build",
// Deliver: the deliver panel and the exports.
deliver: "deliver",
diff --git a/umtool/lib/pieces/tabs.test.mjs b/umtool/lib/pieces/tabs.test.mjs
@@ -47,7 +47,7 @@ test("a note opens where its anchor is drawn", () => {
test("every section is on a real tab; an unknown one throws", () => {
for (const [name, tab] of Object.entries(SECTION_TAB)) assert.ok(PIECE_TAB_IDS.includes(tab), name);
- assert.equal(tabOfSection("onscreen"), "build");
+ assert.equal(tabOfSection("onscreen"), "media"); // moved from Build in P4b
assert.equal(tabOfSection("deliver"), "deliver");
assert.throws(() => tabOfSection("nope"), /no section "nope"/);
});
diff --git a/umtool/lib/report/draft-provenance.mjs b/umtool/lib/report/draft-provenance.mjs
@@ -0,0 +1,133 @@
+// WHERE A DRAFTED FIELD CAME FROM (plans/umtool-redesign.md, P4b): for every
+// field a media task drafted, the task's own audit file beside the manifest
+// (`<task>-draft.json`, narrate's `narration-draft.json`) says how many
+// attempts it took, which one was kept, and the rule each refused attempt
+// broke (`attempts[].hard`). The Media tab shows it under the field: "attempt
+// 2 of 2 chosen · attempt 1 failed: ✕ text in quotation marks".
+//
+// Two shapes are read:
+// - release 28's scaffold (common/lib/report/draft/tasks/media.ts):
+// `{ task, model, at, units: { <id>: { target: {entry?, field}, attempts:
+// [{value, hard, soft}], chosen, applied? | skipped? } } }`;
+// - release 25's narrate file: the units at the top level, keyed by card id,
+// `{ heading, attempts: [{text, hard, soft}], chosen }`, no model.
+//
+// Plain ESM: `node --test` runs it with no TypeScript. Read only.
+import { readdir, readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import { draftedFields, reviewAddress, stableStringify } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
+import { DRAFT_FILE_RE, draftsView } from "./drafts.mjs";
+import { awaitingReview } from "../inbox/drafts.mjs";
+
+const strings = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+
+/**
+ * One unit's attempts, as the field shows them.
+ *
+ * @param {any} unit
+ * @param {number | null} markAttempt the attempt the manifest's mark names, if any
+ */
+export function attemptsOf(unit, markAttempt = null) {
+ const attempts = Array.isArray(unit?.attempts) ? unit.attempts.filter(isObj) : [];
+ if (!attempts.length) return null;
+ let chosen = null;
+ if (isObj(unit.chosen)) {
+ const key = stableStringify(unit.chosen.value ?? unit.chosen.text ?? null);
+ const i = attempts.findIndex((a) => stableStringify(a.value ?? a.text ?? null) === key);
+ if (i >= 0) chosen = i + 1;
+ }
+ if (chosen === null && Number.isInteger(markAttempt) && markAttempt >= 1 && markAttempt <= attempts.length) chosen = markAttempt;
+ return {
+ attempts: attempts.length,
+ chosen,
+ // A repaired value (narrate removes the failing sentences) is none of the attempts.
+ repaired: isObj(unit.chosen) && chosen === null,
+ failed: attempts
+ .map((a, i) => ({ attempt: i + 1, hard: strings(a.hard) }))
+ .filter((a) => a.hard.length > 0),
+ soft: strings((isObj(unit.chosen) ? unit.chosen : attempts[(chosen ?? 1) - 1])?.soft),
+ };
+}
+
+/**
+ * Every field's provenance from a project's draft files.
+ *
+ * @param {{ file: string, doc: any, mtimeMs?: number | null }[]} files
+ * @param {any} manifest the whole manifest (its `drafted` marks pick between two files claiming one field)
+ * @returns {Record<string, { file: string, model: string | null, at: string | null, attempts: number, chosen: number | null, repaired: boolean, failed: { attempt: number, hard: string[] }[], soft: string[] }>}
+ */
+export function provenanceFrom(files, manifest) {
+ const marks = markIndex(manifest);
+ /** @type {Record<string, any>} */
+ const out = {};
+ for (const { file, doc, mtimeMs } of files) {
+ if (!isObj(doc)) continue;
+ const model = typeof doc.model === "string" ? doc.model : null;
+ const at = typeof doc.at === "string" ? doc.at : mtimeMs ? new Date(mtimeMs).toISOString() : null;
+ const units = isObj(doc.units)
+ ? Object.values(doc.units).map((u) => ({ u, target: isObj(u?.target) && typeof u.target.field === "string" ? u.target : null }))
+ : // release 25: the narrate file's units at the top level, keyed by card id.
+ file === "narration-draft.json"
+ ? Object.entries(doc).map(([id, u]) => ({ u, target: isObj(u) && Array.isArray(u.attempts) ? { entry: id, field: "narration" } : null }))
+ : [];
+ for (const { u, target } of units) {
+ if (!target) continue;
+ const address = reviewAddress({ entry: typeof target.entry === "string" && target.entry ? target.entry : null, field: target.field });
+ const mark = marks.get(address) ?? null;
+ const a = attemptsOf(u, mark?.attempt ?? null);
+ if (!a) continue;
+ const prev = out[address];
+ // Two files claim it: the one the mark's task wrote wins.
+ const mine = mark && file === (mark.task === "narrate" ? "narration-draft.json" : `${mark.task}-draft.json`);
+ if (prev && !mine) continue;
+ out[address] = { file, model: model ?? mark?.model ?? null, at: mark?.at ?? at, ...a };
+ }
+ }
+ return out;
+}
+
+/** The manifest's drafted marks by review address. */
+function markIndex(manifest) {
+ return new Map(draftedFields(manifest).map((d) => [reviewAddress(d), d.provenance]));
+}
+
+/**
+ * Read a project's draft files and answer `provenanceFrom` over them. A file
+ * that does not parse is skipped (its task wrote it; not this view's to repair).
+ *
+ * @param {string} projectDir
+ * @param {any} manifest
+ */
+export async function readFieldProvenance(projectDir, manifest) {
+ let names = [];
+ try {
+ names = (await readdir(projectDir)).filter((n) => DRAFT_FILE_RE.test(n)).sort();
+ } catch {
+ return {};
+ }
+ const files = [];
+ for (const file of names) {
+ const p = path.join(projectDir, file);
+ try {
+ const [text, st] = await Promise.all([readFile(p, "utf8"), stat(p)]);
+ files.push({ file, doc: JSON.parse(text), mtimeMs: st.mtimeMs });
+ } catch {
+ /* skipped */
+ }
+ }
+ return provenanceFrom(files, manifest);
+}
+
+/**
+ * The fields of a project awaiting review (lib/inbox/drafts.mjs awaitingReview):
+ * the number the piece's Media tab shows, the same the Inbox's drafts card counts.
+ *
+ * @param {string} projectDir
+ * @param {any} manifest
+ */
+export async function awaitingReviewOf(projectDir, manifest) {
+ const view = await draftsView(projectDir, manifest);
+ if (!view.rows.some((r) => r.state === "unreviewed" || r.state === "edited")) return [];
+ return awaitingReview(view.rows, await readFieldProvenance(projectDir, manifest));
+}
diff --git a/umtool/lib/report/draft-provenance.test.mjs b/umtool/lib/report/draft-provenance.test.mjs
@@ -0,0 +1,80 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { attemptsOf, provenanceFrom, readFieldProvenance } from "./draft-provenance.mjs";
+
+test("attemptsOf: the chosen attempt by value, the refused ones with their rules", () => {
+ const u = {
+ attempts: [
+ { value: { title: "A" }, hard: ["title over 60 chars"], soft: [] },
+ { value: { title: "B" }, hard: [], soft: ["no name grounded"] },
+ ],
+ chosen: { value: { title: "B" }, hard: [], soft: ["no name grounded"] },
+ };
+ assert.deepEqual(attemptsOf(u), {
+ attempts: 2,
+ chosen: 2,
+ repaired: false,
+ failed: [{ attempt: 1, hard: ["title over 60 chars"] }],
+ soft: ["no name grounded"],
+ });
+ // No attempts: nothing to say. A clean first attempt: chosen 1, nothing failed.
+ assert.equal(attemptsOf({ skipped: "has a value" }), null);
+ assert.deepEqual(attemptsOf({ attempts: [{ value: "x", hard: [], soft: [] }], chosen: { value: "x", hard: [], soft: [] } }).failed, []);
+ // A repaired value is none of the attempts; the mark's attempt is the fallback when there is no chosen.
+ assert.equal(attemptsOf({ attempts: [{ text: "a", hard: ["q"] }], chosen: { text: "fixed" } }).repaired, true);
+ assert.equal(attemptsOf({ attempts: [{ value: 1, hard: [] }, { value: 2, hard: [] }] }, 2).chosen, 2);
+});
+
+test("provenanceFrom: release 28's units by target, release 25's narrate file by card id", () => {
+ const manifest = {
+ timeline: [
+ { id: "c01", type: "clip", onscreen: { title: "T" }, drafted: { onscreen: { task: "onscreen", model: "qwen3:8b", at: "2026-10-13T00:00:00Z", attempt: 2 } } },
+ { id: "k01", type: "card", narration: { text: "Words." } },
+ ],
+ };
+ const files = [
+ {
+ file: "onscreen-draft.json",
+ doc: {
+ task: "onscreen",
+ model: "qwen3:8b",
+ at: "2026-10-13T00:00:00Z",
+ units: {
+ c01: { target: { entry: "c01", field: "onscreen" }, attempts: [{ value: { title: "Too long" }, hard: ["title over 60"], soft: [] }, { value: { title: "T" }, hard: [], soft: [] }], chosen: { value: { title: "T" }, hard: [], soft: [] } },
+ c02: { target: { entry: "c02", field: "onscreen" }, skipped: "has a value" },
+ },
+ },
+ },
+ {
+ file: "narration-draft.json",
+ mtimeMs: Date.UTC(2026, 9, 12, 20, 54),
+ doc: { k01: { heading: "H", attempts: [{ text: "\"q\"", hard: ["text in quotation marks: no quotes in narration"], soft: [] }, { text: "Words.", hard: [], soft: [] }], chosen: { text: "Words.", hard: [], soft: [] } } },
+ },
+ ];
+ const p = provenanceFrom(files, manifest);
+ assert.deepEqual(Object.keys(p).sort(), ["narrate/k01/narration", "onscreen/c01/onscreen"]);
+ assert.equal(p["onscreen/c01/onscreen"].chosen, 2);
+ assert.deepEqual(p["onscreen/c01/onscreen"].failed, [{ attempt: 1, hard: ["title over 60"] }]);
+ assert.equal(p["onscreen/c01/onscreen"].model, "qwen3:8b");
+ assert.equal(p["narrate/k01/narration"].file, "narration-draft.json");
+ assert.equal(p["narrate/k01/narration"].model, null);
+ assert.equal(p["narrate/k01/narration"].at, "2026-10-12T20:54:00.000Z");
+ assert.deepEqual(p["narrate/k01/narration"].failed[0].hard, ["text in quotation marks: no quotes in narration"]);
+});
+
+test("readFieldProvenance reads the draft files beside the manifest and skips one that does not parse", async () => {
+ const dir = mkdtempSync(path.join(tmpdir(), "prov-"));
+ try {
+ writeFileSync(path.join(dir, "cut-draft.json"), JSON.stringify({ model: "m", at: "a", units: { cut: { target: { field: "timeline" }, attempts: [{ value: ["c01"], hard: [], soft: [] }], chosen: { value: ["c01"], hard: [], soft: [] } } } }));
+ writeFileSync(path.join(dir, "teaser-draft.json"), "{ not json");
+ writeFileSync(path.join(dir, "notes.json"), "{}");
+ const p = await readFieldProvenance(dir, { timeline: [] });
+ assert.deepEqual(Object.keys(p), ["cut/*/timeline"]);
+ assert.equal(p["cut/*/timeline"].attempts, 1);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});