Archilyzer · Source

archilyzer

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

commit 0d83a7f5e69294db504e6e98f6e25573715824b9
parent 986646c70247675aee021160d4119089f0bb5015
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 12:00:31 -0400

merge main 651b36e5 (P4a-3, P4b) into ux/r4

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

Diffstat:
Meditor/CHANGELOG.md | 7+++++++
Mplans/umtool-redesign.md | 368+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/app/work/page.tsx | 2+-
Mumtool/components/articles/ArticlePage.tsx | 2+-
Mumtool/components/articles/ChainPanel.tsx | 134+++++++++++++++++++++++++++++++++++++------------------------------------------
Mumtool/components/articles/IterationsTab.tsx | 160+++++++++++++------------------------------------------------------------------
Mumtool/components/piece/PieceFrame.tsx | 2+-
Mumtool/components/projects/ClaimBench.tsx | 153++++++++++++++++++++++++++++++++++++++++++++++---------------------------------
Mumtool/components/projects/ClaimBenchPage.tsx | 39+++++++++++++++++++++------------------
Mumtool/components/projects/ClipBench.tsx | 516++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------
Mumtool/components/projects/ClipBenchPage.tsx | 50++++++++++++++++++++++++++++++--------------------
Mumtool/components/projects/CutPage.tsx | 69++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Mumtool/components/projects/DraftPanel.tsx | 301++++++++++++++++++++++---------------------------------------------------------
Dumtool/components/projects/DraftsReview.tsx | 90-------------------------------------------------------------------------------
Aumtool/components/projects/MediaDrafts.tsx | 705+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/NarrationPage.tsx | 53+++++++++++++++++++++++++++++------------------------
Mumtool/components/projects/NarrationReview.tsx | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/components/projects/OnscreenSection.tsx | 8++++----
Mumtool/components/projects/ProjectView.tsx | 5+++--
Mumtool/components/projects/ReportBuildChain.tsx | 74++++++++++++++++++++++++++++++++++----------------------------------------
Mumtool/components/projects/ReportProject.tsx | 2+-
Mumtool/components/projects/ReviewPage.tsx | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------
Mumtool/components/projects/SongProject.tsx | 298+++++++++++++++----------------------------------------------------------------
Mumtool/components/projects/TakesBench.tsx | 83++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/components/projects/TakesPage.tsx | 78++++++++++++++++++++++++++++++++++++++++++------------------------------------
Aumtool/components/projects/bench/BenchShell.tsx | 235+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/bench/CopyCitation.tsx | 39+++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/drafts.tsx | 2+-
Mumtool/components/projects/report/BuildTab.tsx | 22+++++-----------------
Mumtool/components/projects/report/MediaTab.tsx | 99++++++++++++++++++++++++++++++++++---------------------------------------------
Mumtool/components/projects/report/ReportTabBody.tsx | 11+++++++----
Aumtool/components/projects/song/CoverTab.tsx | 24++++++++++++++++++++++++
Aumtool/components/projects/song/CutsTab.tsx | 174+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/song/NotesTab.tsx | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/song/OverviewTab.tsx | 189+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/song/SongFrame.tsx | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/song/SpecTab.tsx | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/shell/JobProgress.tsx | 37++++---------------------------------
Mumtool/components/ui/cite-thread.tsx | 16+++++++++++-----
Aumtool/components/ui/job-progress.tsx | 343+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/ui/reader-pane.tsx | 34++++++++++++++++++++++++++++++----
Mumtool/e2e/article-iterations.spec.ts | 15+++++++++++----
Aumtool/e2e/bench-shell.spec.ts | 179+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/browse.spec.ts | 13+++++++------
Mumtool/e2e/claim-bench.spec.ts | 3++-
Mumtool/e2e/clip-bench.spec.ts | 4++--
Mumtool/e2e/draft-review.spec.ts | 4++--
Mumtool/e2e/faces.spec.ts | 4+++-
Aumtool/e2e/fixtures/bench-shell-fixture.mjs | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 4++++
Mumtool/e2e/media-surfaces.spec.ts | 42+++++++++++++++++++++++-------------------
Mumtool/e2e/onscreen.spec.ts | 2+-
Mumtool/e2e/piece.spec.ts | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/projects.spec.ts | 10+++++++++-
Aumtool/e2e/song-piece.spec.ts | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/takes.spec.ts | 4++--
Mumtool/e2e/urls.ts | 10++++++++++
Mumtool/lib/articles/generation.ts | 12++++++++++++
Aumtool/lib/cite-thread.mjs | 21+++++++++++++++++++++
Aumtool/lib/cite-thread.test.mjs | 18++++++++++++++++++
Mumtool/lib/decisions.ts | 16++++++++++------
Mumtool/lib/inbox.ts | 9++++++---
Mumtool/lib/inbox/drafts.mjs | 22++++++++++++++++++++--
Mumtool/lib/inbox/drafts.test.mjs | 6+++++-
Mumtool/lib/pieces.ts | 28++++++++++++++++++++++++++--
Mumtool/lib/pieces/frame.ts | 25+++++++++++++++++++------
Aumtool/lib/pieces/song-tabs.mjs | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/pieces/song-tabs.test.mjs | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/pieces/tabs.mjs | 39+++++++++++++++++++++++++++++++++------
Mumtool/lib/pieces/tabs.test.mjs | 2+-
Mumtool/lib/projects/kinds.mjs | 13++++++++++++-
Mumtool/lib/projects/song.mjs | 12++++++++++++
Aumtool/lib/report/draft-provenance.mjs | 133+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/draft-provenance.test.mjs | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/work.ts | 13+++++++++----
Mumtool/lib/work/facets.mjs | 27+++++++++++++++++++++++++--
76 files changed, 4799 insertions(+), 1427 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. @@ -68,6 +72,9 @@ - **The generation policy is a chip on the article's page.** Its preset, the API model and the day's spend against the daily cap, linking `/settings/generation`. - **umtool: an article's "+ note", its citations and "+ whole article" wait until the page is ready.** A click before then did nothing; they are now disabled until it is. - **umtool: links on a project page are ink, not Signal.** The teal is kept for the lit line and the one primary action (the Next card's, **Walk the cut**); the drafts panel, the review and narration pages, the iterations and the new-article form follow. +- **umtool: a song's page is a piece page.** `/projects/<song>` has the head — the title, **Active ▾**, **⋯** and the stage stepper **Spec → Cuts → Done** (Spec with a `spec.json`, Cuts with one cut built, Done with all four, which is also when the song looks done) — then five tabs: **Overview** (the **Next** card, the song's decisions, its four cut slots, what it is, **copy this song**, the README, and links to the song piles, find, mix, sources and the hook trimmer, which stay in Tools), **Cuts** (the cut cards, their verdicts, notes and variants, and what matches no cut), **Spec** (the spec sheet and the plans), **Cover** (the cover bench) and **Notes** (the note on the song and every other note on it, each linking its tab). `1`–`5` open the tabs and `n` runs the Next card. A cut's page, `/projects/<song>/<cut>`, keeps its address and is drawn inside the song with **Cuts** current and the four cuts beside the title. `?tab=` picks the tab and `?note=<target>` opens the tab that note is written on; `/browse/<song>` lands on the Overview. +- **A song's calls open where they are settled.** A spec problem or an unnamed plan opens **Spec**, a variant that matches no cut **Cuts**, an unaccepted cover **Cover**; a cut's calls still open the cut's page. +- **Work files a song by its own stepper.** A song's row shows its three steps (spec, cuts, done) and the stage facet files it with the stage its step stands for: Spec with Article, Cuts with Video, Done with Deliver, the same rule its page lights. - **Articles, iterations, report-video projects and takes can be deleted, and every delete shows its plan first.** `archilyzer reports delete <id>` prints what would go — each path with its size, what is kept and why, and anything that stops it — and deletes nothing until `--apply`; `--iteration <n>` deletes one iteration. Deleting an article removes its directory (report, video, history, notes, iterations), each iteration's video project under `settings.generation.projectsRoot` and its staged exports. A published article is refused unless `--force`, which unpublishes it first; an article with a running iteration is always refused. An iteration is refused while it is the current article or video, the one the article's report came from, running, or the parent or original of another iteration, and its number is never given out again. The usage ledger, the shared prepared-media cache and the corpus's git history are kept. The same deletes run over HTTP as `pnpm ops delete-article {id, force?, dryRun?}` and `pnpm ops delete-iteration {id, n, dryRun?}`, which answer a refusal as a 409 with the plan. - **umtool: Delete article, `Delete i<n>`, Delete project and `Delete take <id>`.** Each button reads the plan, shows it (what goes with sizes, what is kept, what refuses) and deletes only on **Confirm delete**; **Keep it** closes it. **Delete article** is on an article's page (one in the making too) and returns to `/articles`, which says what went; `Delete i<n>` is on each iteration of the Iterations tab. **Delete project** on a report-video project removes its directory, and its `out/` or deliverables on the media drive when they are its own copy; it is refused while a job works in the project, for an article's current video, and — unless you tick **delete anyway** — for a project whose manifest names an article with a video attached. `Delete take <id>` removes `takes/<id>/`; the take whose manifest is the project's own needs **delete anyway**, and its verdict and notes are kept. - **Reports and their revisions can be generated by the editor: `pnpm ops report-draft`.** `{"task": "sweep", "article", "question", "channels"}` drafts a new report of an article as its next iteration; `{"task": "revise-report" | "revise-video", "article", "iteration", "feedback"}` revises one; `{"task": "narrate", "article", "iteration"}` drafts the narration of an iteration's video cut; `"copyOf": N` runs iteration N again on another `"model"`. Each is a **Report draft** job on /jobs, on the Claude API (`draft:api`) or the local model (`draft:local`) by the model, and `pnpm ops job cancel` stops one. Every quote a model writes must be the transcript's words within 90 seconds of its link, or the finding is dropped; links cite the archive, never the platform. The answer names the job and the iteration; the job's log ends with the outcome. Needs a restart of the editor. diff --git a/plans/umtool-redesign.md b/plans/umtool-redesign.md @@ -185,10 +185,11 @@ Each phase: its own branch from `main` (or the current integration branch), gate NOW (beside r28) AFTER r28 IS ON main P0 design ─► P1 foundation ─┬─► P3 inbox/work/tools/URLs ─┬─► P2b jobs+drafts ─► P4a-1 ─► P4a-2 ─► P4a-3 ─► P4b ─┐ P2a engine ────┘ ├─► P5 create+settings (after P3) ├─► P6 - └─► R1 research: search+reader+inventory ─► R2 boards ─► R3 transparent runs ─► R4 refresh ─► R5 recurring ─┘ + └─► R1 research: search+reader+inventory ─► R2 boards ─► R3 transparent runs ─► R4 refresh ─► R5 recurring ─► R6 triage ─┘ ``` -R4 and R5 were added 2026-10-14 at the operator's request (see their sections). R4 runs beside P4a-3/P4b; its -Iterations-tab entry waits for P4b. R5 builds on R4 and on P5's Create. +R4, R5 and R6 were added 2026-10-14 at the operator's request (see their sections), and the operator approved +building all three and the co-host pilot. R4 runs beside P4a-3/P4b; its Iterations-tab entry waits for P4b. R5 builds +on R4 and on P5's Create; R6 on R4 and R5. The pilot runs after R6. ### P0 — Design (no app code; operator sign-off gates P1) - Use the frontend-design skill: @@ -346,6 +347,37 @@ The same topic, updated at an interval — e.g. a daily or weekly report of co-h - The existing hand-kept co-host timeline (`quartering-leads`, `cohosts/UPDATE.md`) is the first candidate series — a pilot after R5 ships, with the operator's go. +### R6 — Triage first: a cheap pass that flags what is worth researching (operator, 2026-10-14) +A consistent fetch, a cheap or local model that flags what is worth a look, and the better model with tools only on +what it flags. Facts it builds on (surveyed 2026-10-14): per-video **digests** already exist (chapters + topic tags, +local `qwen2.5:7b`, the `digest` lane yielding the GPU to transcription; `ai-digest.json`); the **local sweep pipeline** +(`sweep-pipeline.ts`) is code around a small local model that already judges each window `relevant`/`on_topic`; the API +sweep already splits a cheap extractor (`models.extractor`, Haiku) under the main model; there is no watch/saved-search +concept and no standing relevance filter yet. +- **Tier 0 — code, $0:** after R4's fetch + local build, the candidates are the recordings new since the last tick in + scope that match the watch's terms/aliases (enumerate) OR whose digest topic tags match the watch's topics. +- **Tier 1 — the local model, $0 marginal:** the sweep pipeline's window judge, run over the candidates' matching + windows only (`draft:local`, through the GPU arbiter, yielding to transcription; ticks default to overnight). Each + flag: recording, window, a verbatim line (code-checked), a score and one-line reason. Dismissals are kept too. +- **Escalation rule:** any flag at or above the watch's threshold (default: one strong flag, or N weak ones) → **Tier 2: + the better model with tools** — an API sweep restricted to the flagged ids (R4's `ids` restriction), within the caps, + running on its own (the operator's R4 ruling). Below threshold → the tick ends with its triage log, $0 API spend. +- **Where the result goes**, per shape: a **living report** → R4's update (an iteration-ready card); a **series** → the + edition; a **watch** (R5's third shape: no article until something is found) → an Inbox **"Worth researching"** card + with the flags and the escalated findings, plus a board (R2 case) with the flags pinned `by: "triage"`, whose + hand-offs make an article or a video. +- **Transparent and tunable:** the run page (R3) shows the tiers — candidates, each flag and dismissal with its reason, + what escalated and why, the spend per tier. The operator can mark a flag right or wrong; the watch keeps its precision + and suggests a threshold. Settings: the triage model (local by default; `models.extractor` allowed), the threshold, the + daily escalation cap. +- **Engine:** a `report-draft` step `triage` (the window judge as a standalone pass over given ids, structured flags), + reused by R5's scheduler; `trace.jsonl` gains `triage {candidates, flagged, dismissed}`. + +**Pilot (operator-approved 2026-10-14), after R6:** the hand-kept co-host timeline (`quartering-leads`, +`cohosts/UPDATE.md`; the co-host attribution hazard applies — a triage flag on a co-host line is a speaker check, not a +finding) becomes a weekly **series** with triage first: one tick run end to end on the live corpus, its triage log and +edition reviewed with the operator before the schedule is left on. + ### P6 — Cleanup, docs, audit - Redirects become 308. - Delete `/drafts`, `BrowseHeader`, the dashboard panels and dead components. @@ -404,12 +436,14 @@ The same topic, updated at an interval — e.g. a daily or weekly report of co-h | P4a-1 piece frame | `ux/p4a` → `main` `a92251aa` | LIVE 2026-10-14 (umtool ErWqdPdg…) | | P5 create + settings | `ux/p5` → `main` `20ee628a` | LIVE 2026-10-14 (umtool ZfQXZuNF…) | | P4a-2 article-rooted merge | `ux/p4a2` → `main` `d84cf4d7` | LIVE 2026-10-14 (umtool UFg8z3yd…) | -| P4a-3 song pieces | `ux/p4a3` | in progress | +| 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 | -| P6 cleanup, docs, audit | — | after P4a-3, P4b, R4, R5 | +| R6 triage first | — | after R5 | +| Co-host pilot | — | after R6 (operator-approved) | +| P6 cleanup, docs, audit | — | after P4a-3, P4b, R4–R6 | ### P2a, as shipped @@ -2003,3 +2037,325 @@ the reader's note and citation buttons wait for hydration; the Iterations tab li and its `?tab=iterations|cut|media` 200; the claimed project `/projects/articles/piratesoftware-ai-friends/i1?tab=cut` 307 → the article's Cut tab; its clip bench stays 200 at the project URL; the Iterations tab links `/research/runs/piratesoftware-ai-friends/1`; decisions API 828 rows, notes' hrefs intact. + +### P4a-3, as shipped + +**What.** A song's page (`/projects/<song>`) is a piece page: the P4a frame around one of five tabs, Overview · Cuts · +Spec · Cover · Notes, with the stepper **Spec → Cuts → Done**. A cut's page (`/projects/<song>/<cut>`) keeps its address +and is drawn inside the song with Cuts current. The song deck and the `/tools/song/<mode>` piles stay in Tools; the +Overview links them. + +- **The frame** (`components/projects/song/SongFrame.tsx`) hands P4a-1's kind-blind `PieceFrame` the trail (`projects / + <project id>`, the title as the `<h1>`), the five tabs with their `?tab=` addresses (`projectHref(project.id, { tab })`), + the counts in Meter (Cuts: cuts built; Cover: covers on offer; Notes: notes written), the status line + (`4/4 cuts · 3 variants`, the old header's) and **⋯** (the project id; a song had no Delete before and has none now). + The lifecycle chip, the Undo bar, `1`–`5` and `n` come with the frame unchanged. +- **One stage rule, a song's flow** (`lib/pieces/song-tabs.mjs`, pure, unit-tested). The song kind declares its stepper + in the registry (`lib/projects/kinds.mjs` `piece: { flow: SONG_FLOW, reached: songReached }`, `kindPieceFlow`); the + pieces graph copies the flow onto the piece (`Piece.flow`: `article`, `project`, or a kind's) with the facts that light + it (`Reached` gains `spec`, `cuts`, `done`). **`pieceSteps` and `stageOfPiece` switch on it** (`lib/pieces/tabs.mjs`, + an additive kind switch: `songSteps`, `bucketOfSongStep(songStepOf)`), and `stepOfPiece` is the frame's + `data-piece-stage` (a song's `spec` / `cuts` / `done`; the four-stage pieces' unchanged). The rule is the one rule: the + furthest stage reached is current, a skipped one is to do with its reason ("no spec.json"), a piece marked done has done + them all. Spec is reached with a `spec.json`, Cuts with one cut built, Done with all four (the derived `shipped`, which + is also P2a's looks-done suggestion: Done is current, Signal-ringed, until the operator marks it done). +- **Work agrees.** `stageOf` reads the piece's flow: a song's bucket is the one its current step stands for — **Spec → + article, Cuts → video, Done → deliver** (the spec is a song's written stage, as an article is a report video's) — and + `stageBar` (`lib/work/facets.mjs`) draws a song's own three steps on its row with the step's word (`cuts`, `done`) + where a project's state used to be. The four-stage rows are unchanged. Unit-tested: for every combination of facts the + stepper's current step, `stepOfPiece`, `stageOf`'s bucket, `stageOfPiece` and the bar agree. +- **The page reads its own facts fresh**: `readPieceFrame(project, { reached })` takes the song's facts from the + `readSong` the page did anyway (one stat for `spec.json`), over the graph's 15 s memo, so a promote shows at once; a song + the graph has not listed yet still walks the song's stepper (`kindPieceFlow`). +- **The Next card** is P4a-1's, kind-blind: the song's top Inbox card (an unnamed plan, an unjudged variant, a missing cut, + a stale recipe … or **Mark done** when looking done is all that is left). +- **A song's calls open their tab** (`lib/decisions.ts`, by `songTabOfSection`): `spec-problem` and `no-plan` → Spec, + `unattributed` → Cuts, `thumb-unaccepted` → Cover (`/projects/<song>?tab=…`); a cut's calls (`missing-cut`, + `unjudged-variant` with its `?v=`, `stale-recipe`, `no-recipe`, `loudness`) keep the cut page's href. +- **Addresses.** No `tab` is the Overview; a bad `tab` is the Overview; `?note=<target>` opens the tab that note is + written on (a song's notes are keyed by target, `lib/notes.ts`): `song` → Notes; `cut:`, `file:`, `moment:`, + `source:`, `clip:` → Cuts; `plan:` → Spec; `thumb:` → Cover. `/browse/<song>` rides P3's redirect to the Overview, + `/browse/<song>/<cut>` to the cut's page. The cut page's own keys (`?v=`, `?plan=`, `?notes=all`) are unchanged. + +**Section → tab** (SongProject's two columns and head row, CutPage's body; `SONG_SECTION_TAB` names each for +`e2e/urls.ts` `songSection(song, name)`): + +| Section (its attribute) | Tab | +|---|---| +| Header: crumbs `songs / <id>`, note `N/4 cuts · N variants` | head (trail `projects / <id>`, the title, the same status line) | +| Head row: the song's note (`NoteField target="song"`) | Notes | +| Head row: **copy this song** (`CopyButton`, `/api/browse/context?song=`) | Overview (`data-song-copy`) | +| Left: the four cut cards (`data-cut`, `data-present`, `data-variant`, `data-variant-tag`, `VerdictChip`, the slot's and the file's notes) | Cuts | +| Left: matches no cut name (`data-unattributed`, new attribute) | Cuts | +| Aside: `ThumbBench` (`data-judge-faces` …) | Cover (says "No cover generated" when the bench would draw nothing) | +| Aside: `SpecSheet` (`data-op` …) | Spec | +| Aside: README | Overview (`data-readme`) | +| Aside: plans, their notes, clips.csv (`data-song-plans`, new) | Spec | +| CutPage: `CutBench`, `LoudnessTable`, `ProvenancePanel` | Cuts (the cut's page, a view of it; `bare`, unpadded as before) | +| CutPage: crumbs `songs / <id> / <cut>`, note duration · bytes | head: trail with the id linking the song, the four cuts beside the title (`data-song-cut-picker`), the same note | +| new: the Next card, the song's decisions (P4a-1's `ProjectDecisions`), the four cut slots (`data-song-slot`), This song (cuts, variants, verdicts, plans, cover, looks done — `data-song-looks-done`), Song tools (`data-song-pile`, `data-song-trim`, song piles, find, mix, sources) | Overview | +| new: every other note on the song, each linking its tab (`data-song-notes`, `data-song-note-target`) | Notes | + +The sections live in `components/projects/song/{SongFrame,OverviewTab,CutsTab,SpecTab,CoverTab,NotesTab}.tsx`; +`SongProject.tsx` reads the song once, picks the tab and renders the frame; `CutPage.tsx` keeps its body and draws it +through `SongFrame`. `ProjectView`'s song case hands both the project (it handed the basename). Only the tab on show is +read: the Cuts tab's ffprobes and the spec's validation cost nothing on the Overview. A cut card's name is an ink link +(it wore Signal on hover). `[data-nav-group=song]` and every `data-testid` are untouched. + +**Shared files, additive only.** `lib/pieces/tabs.mjs`: the import, the kind switch in `pieceSteps` and +`stageOfPiece`, the new `stepOfPiece`. `PieceFrame`: no change. `lib/pieces/frame.ts`: `readPieceFrame`'s optional +`reached`, the flow from the piece or the registry, `stepOfPiece` for `stage`. `lib/pieces.ts`: `Piece.flow`, `Reached`, +a project piece's declared facts. `lib/work.ts`/`lib/work/facets.mjs`/`app/work/page.tsx`: the flow, `stageBar`, the +row's `steps`. `lib/projects/kinds.mjs`: the song's `piece`, `kindPieceFlow`; `lib/projects/song.mjs`: `songReached`. +`lib/decisions.ts`: the song-wide hrefs' tab. `e2e/urls.ts`: `songSection`. + +| sha | what | +|---|---| +| `aa8739d9` | the song piece: `lib/pieces/song-tabs.mjs` (+ unit tests), the flow switch in `pieceSteps`/`stageOfPiece`, `stepOfPiece`, the registry's `piece` and `songReached`, `Piece.flow`/`Reached`, `readPieceFrame`'s fresh facts, Work's `stageBar`, `components/projects/song/*`, `SongProject`/`CutPage` through `SongFrame`, the song-wide hrefs' tab | +| `56a1fe72` | specs: `browse`/`faces`/`projects` through `urls.songSection`, `e2e/song-piece.spec.ts` (9); a cut card's name an ink link | + +**Gates** (at `56a1fe72`). + +| Gate | Result | +|---|---| +| repo-wide `tsc --noEmit` | clean at both commits (umtool typecheck clean) | +| umtool unit (`node --test umtool/lib/*.test.mjs umtool/lib/*/*.test.mjs umtool/report-to-video/*.test.mjs`) | 850 tests, 848 pass, 2 skipped, 0 fail (new: `song-tabs.test.mjs` 4 — the tabs and sections, the address → tab rules and `?note=<target>`, the stepper by what exists, the stepper against Work's facet and bar) | +| `pnpm --filter umtool test` | 24/24 | +| `pnpm run test:scripts` (reads the capped build's traces) | 1001 tests, 999 pass, 2 skipped, 0 fail | +| capped umtool `next build` (corpus linked, `MemoryMax=5G`) | exit 0, compiled 12.4 s, 39 s wall, 1.48 GB max RSS; the link removed | +| song specs, dev mode (`E2E_MODE=dev`, the song specs' filter) | 102 tests: 96 passed, 1 failed, 5 skipped, 6.4 min; `song-piece.spec` 9/9. Red: `projects.spec:219` (the tool pages under `/browse`: a dev-mode `ERR_ABORTED` on first compile; green in both start-mode runs) | +| full umtool e2e, run 1 (`56a1fe72`) | 446 tests: 437 passed, 3 failed, 6 skipped. Reds: `board.spec:102` (`e` did not focus the claim field) and the two after it that build on its sections (`:164`, `:186`) — the run started after 12 minutes waiting at the heavy slot for memory (a sibling dev server at 3.8 GB, 2.2–3.4 GB available); `board.spec` + `song-piece.spec` alone: 16/16 | +| full umtool e2e, run 2 (`56a1fe72`) | **446 tests: 440 passed, 0 failed, 6 skipped** (the song-data capability skips), 10.9 min; `song-piece.spec` 9/9 | + +**Spec churn:** `browse.spec` (6 gotos through `urls.songSection`: the cut cards, verdicts and a hole on Cuts, the trim +operation on Spec), `faces.spec` (the bench on Cover), `projects.spec` ("the song URLs that already existed": `/browse/alpha` +is the Overview with the cut slots, the Cuts tab has the cards, `/browse/alpha/wide` is the cut's page with Cuts current, +the canonical path is the Overview). No `data-testid` renamed. New `e2e/song-piece.spec.ts` (9): the frame (title, trail, +status line, stepper at Done, five tabs, the Overview alone); a song with a hole at Cuts and Work's row (bucket, word, +looks done) agreeing with both steppers; the Next card = the Inbox's top card for the song; a song's calls' hrefs; the +tab as the URL (`?tab=`, a bad tab, `?note=song|plan:|cut:`, `/browse/alpha`); the cut's page (frame, picker, the +loudness table, the trail back, a hop to `wide-short`); the keys (`2`, `5`, `1`, `n`); marked done (all done, the +suggestion gone, the Next card's Reactivate); 1366×768 with no horizontal scroll on four addresses. + +**Screenshots** (job scratch `p4a3-shots/final/`, 17): `alpha` (all four cuts, at Done) on Overview, Cuts and Spec at +1366×768 and 1440×900, dark and light; and, dark at 1366×768, the cut page `alpha/wide`, Cover, Notes, `beta`'s Overview +(at Cuts, two holes) and Work filtered to songs — on the e2e start build over the fixture. Against the canvas's Piece · +Overview, in a song's words: the head (title in Archivo, the chip and ⋯ on the right, the status line), the three-step +stepper with Done Signal-ringed, the five tabs with Meter counts and the Signal underline, the Next card with its Signal +edge and one filled action ("Name the plan" → Spec), the two columns (decisions and the four cut slots | This song and +the song tools), the README under them. Work's row for Mortal Kombat in the canvas reads step 2 "Cuts"; a song's row now +reads its own three bars with `cuts` lit second, as drawn there. + +**Found and left.** +- **On the real reports** (a read-only listing): all five songs have a `spec.json`; `mario-rpg`, `metal-slug`, + `mortal-kombat` and `yoshi` have three of the four cuts and stand at Cuts, `pokemon` has all four and stands at Done + with P2a's looks-done suggestion. The fixture's alpha has no `spec.json` until browse.spec writes one, so its Spec + reads to do ("no spec.json") on a fresh fixture. +- **Spec → article** in Work's stage facet is a ruling to confirm: a song with a spec and no cut is filed under Article + (the written stage). The alternatives were Video (a song is a video piece) or Research; Article keeps the three steps + on three different buckets, so a song moves along the facet as it moves along its stepper. +- **`urls.songSection`, not `urls.section`**: a song's section names overlap the report's (`notes`, `readme`, + `decisions`, `next`) on different tabs, so the song has its own table and builder rather than a fall-through. +- The song bench's own controls (CutBench, ProvenancePanel, LoudnessTable, SpecSheet, ThumbBench, NoteField, VerdictChip) + keep P1's Signal-outline `primary` buttons and their Signal states; only the cut card's name link changed. They live + outside `components/projects/` and were moved, not restyled. + +### P4a-3 rollout (orchestrator, 2026-10-14) + +Rulings: a song with a spec and no cut sits under Article in Work's stage facet; specs use `urls.songSection`; Work +draws a song's three bars, as its stepper does (one stage rule over the canvas mock's four); the song benches' Signal-outline +buttons stay until P6's audit. Gates on `56a1fe72` (the merge of `main` brought plan text only): full umtool e2e 440 +passed, 0 failed, 6 skipped (10.9 min); test:scripts 999 pass, 0 fail; capped build ok. `main` fast-forwarded to +`3d69d6c6`; umtool built (171 s) and restarted (`scripts/p4a3-umtool.sh`). Live: the five songs under +`/projects/quartering-uh-song/videos/`, pokemon at Done and mario-rpg at Cuts; pokemon's five tabs and four cut pages 200; +`/browse/quartering-uh-song/videos/pokemon` 307 → the Overview; decisions API 828 rows, notes' hrefs end `note=<id>`. +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/app/work/page.tsx b/umtool/app/work/page.tsx @@ -263,7 +263,7 @@ function Row({ r }: { r: WorkRow }) { </LitActions> </div> <span className="flex items-center gap-[3px]" title={r.looksDone.join("; ") || undefined}> - {[1, 2, 3, 4].map((i) => ( + {Array.from({ length: r.steps }, (_, k) => k + 1).map((i) => ( <i key={i} className={cn("h-1 w-[22px] rounded-[1px]", i < r.step ? "bg-text-2" : i === r.step ? "bg-signal" : "bg-seam-2")} diff --git a/umtool/components/articles/ArticlePage.tsx b/umtool/components/articles/ArticlePage.tsx @@ -134,7 +134,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&rsquo;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/CutPage.tsx b/umtool/components/projects/CutPage.tsx @@ -1,6 +1,5 @@ import Link from "next/link"; import { notFound } from "next/navigation"; -import BrowseHeader from "@/components/BrowseHeader"; import CutBench from "@/components/CutBench"; import ProvenancePanel from "@/components/ProvenancePanel"; import { isCutName, probeAll, readSong } from "@/lib/browse"; @@ -13,21 +12,32 @@ import LoudnessTable from "@/components/LoudnessTable"; import { cachedLoudness } from "@/lib/loudness"; import { DEFAULT_TARGET } from "@/lib/loudness-types"; import { readSpec } from "@/lib/spec"; -import { resolveRendition } from "@/lib/browse"; +import { resolveRendition, thumbAliasesFor } from "@/lib/browse"; +import { cutHref, projectHref } from "@/lib/hrefs"; +import { thumbView } from "@/lib/thumbs"; +import type { ProjectRef } from "@/lib/project-types"; +import SongFrame, { readSongFrame, songCounts } from "./song/SongFrame"; // Moved out of app/browse/[song]/[cut]/page.tsx unchanged. `/browse/<song>/wide` // is now a project id plus a VIEW, resolved by the registry rather than by a // route segment -- the URL is byte-identical either way, which is the point. +// +// Since P4a-3 a cut's page is a view of the song piece's Cuts tab: the song's +// frame (components/projects/song/SongFrame.tsx) with Cuts current, the four +// cuts beside the title, and the bench, the loudness and the provenance under +// it, unchanged. export default async function CutPage({ - id, + project, cutName, search, }: { - id: string; + project: ProjectRef; cutName: string; search: { v?: string; plan?: string; notes?: string }; }) { + // Keyed by BASENAME, as every song route is (lib/browse.ts songDir). + const id = project.name; const { v, plan, notes: notesParam } = search; if (!isCutName(cutName)) notFound(); @@ -68,26 +78,44 @@ export default async function CutPage({ truePeak: spec.loudness?.truePeak ?? DEFAULT_TARGET.truePeak, }; + const [frame, thumbs] = await Promise.all([readSongFrame(project, song), thumbView(id, thumbAliasesFor(id))]); + return ( - <div className="flex h-full flex-col"> - <BrowseHeader - crumbs={[ - { href: "/projects", label: "songs" }, - { href: `/projects/${song.id}`, label: song.id }, - { label: cutName }, - ]} - note={ - cut.shipped - ? `${fmtDur(durations[cut.shipped.rel] ?? 0)} · ${fmtBytes(cut.shipped.size)}` - : "not built" - } - /> - <main className="deck-main flex-1"> + <SongFrame + project={project} + song={song} + frame={frame} + tab="cuts" + bare + idHref={projectHref(project.id)} + counts={songCounts(song, notes, thumbs.candidates.length)} + note={ + cut.shipped + ? `${fmtDur(durations[cut.shipped.rel] ?? 0)} · ${fmtBytes(cut.shipped.size)}` + : "not built" + } + meta={ + <span className="flex flex-wrap items-baseline gap-x-2.5" data-song-cut-picker={cutName}> + <span className="micro">cut</span> + {song.cuts.map((c) => + c.name === cutName ? ( + <span key={c.name} aria-current="page" className="font-mono text-[12.5px] font-semibold text-text"> + {c.name} + </span> + ) : ( + <Link key={c.name} href={cutHref(project.id, c.name)} prefetch={false} className="ink-link font-mono text-[12.5px]"> + {c.name} + </Link> + ), + )} + </span> + } + > {!cut.shipped && cut.variants.length === 0 ? ( <div className="p-4 text-[12px] text-[var(--color-dim)]"> Nothing here yet — no <code className="font-mono">{cutName}.mp4</code> and no variants named for it.{" "} - <Link href={`/projects/${song.id}`} className="ink-link"> + <Link href={projectHref(project.id, { tab: "cuts" })} className="ink-link"> back to {song.id} </Link> </div> @@ -119,7 +147,6 @@ export default async function CutPage({ </div> </> )} - </main> - </div> + </SongFrame> ); } 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/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx @@ -36,8 +36,9 @@ export default async function ProjectView({ }) { switch (project.kind) { case "song": { - if (rest.length === 0) return <SongProject id={project.name} />; - if (rest.length === 1) return <CutPage id={project.name} cutName={rest[0]} search={search} />; + // The song piece (P4a-3), and a cut's page: a view of its Cuts tab. + if (rest.length === 0) return <SongProject project={project} search={search} />; + if (rest.length === 1) return <CutPage project={project} cutName={rest[0]} search={search} />; return notFound(); } case "report-video": { 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/SongProject.tsx b/umtool/components/projects/SongProject.tsx @@ -1,255 +1,67 @@ -import Link from "next/link"; import { notFound } from "next/navigation"; -import BrowseHeader from "@/components/BrowseHeader"; -import VerdictChip from "@/components/VerdictChip"; -import SpecSheet from "@/components/SpecSheet"; -import NoteField from "@/components/NoteField"; -import CopyButton from "@/components/CopyButton"; -import { readSong, probeAll, thumbAliasesFor, type Cut, type Song } from "@/lib/browse"; -import ThumbBench from "@/components/ThumbBench"; +import { readSong, thumbAliasesFor } from "@/lib/browse"; import { thumbView } from "@/lib/thumbs"; -import { fmtAgo, fmtBytes, fmtDur } from "@/lib/format"; -import { Markdown } from "@/lib/markdown"; -import { operationsFor, readSpec, validateSpec } from "@/lib/spec"; -import { readNotes, type NoteMap } from "@/lib/notes"; -import { TRIM_SETS } from "@/lib/trim"; +import { readNotes } from "@/lib/notes"; +import { songTabOf } from "@/lib/pieces/song-tabs.mjs"; +import type { ProjectRef } from "@/lib/project-types"; +import SongFrame, { readSongFrame, songCounts } from "./song/SongFrame"; +import OverviewTab from "./song/OverviewTab"; +import CutsTab from "./song/CutsTab"; +import SpecTab from "./song/SpecTab"; +import CoverTab from "./song/CoverTab"; +import NotesTab from "./song/NotesTab"; -// Moved out of app/browse/[song]/page.tsx unchanged, because [song] and -// [...path] cannot both be dynamic segments at the same level. The dispatcher -// in ProjectView.tsx hands it an id; nothing else about the page differs. +// --------------------------------------------------------------------------- +// A song, as a PIECE PAGE (plans/umtool-redesign.md, P4a-3). +// +// Moved out of app/browse/[song]/page.tsx unchanged in P3, because [song] and +// [...path] cannot both be dynamic segments at the same level; the dispatcher +// in ProjectView.tsx hands it the project. Since P4a-3 it is the piece frame +// (components/projects/song/SongFrame.tsx: head, Spec → Cuts → Done stepper, +// lifecycle, Next card, tabs, keys) around ONE tab, and the sections it drew in +// two columns live in the tabs (components/projects/song/*), moved unchanged: +// +// head row: the song's note → Notes; "copy this song" → Overview +// the cut cards, what matches no cut → Cuts +// the cover bench → Cover +// the spec sheet, the plans → Spec +// the README → Overview +// +// Which section is on which tab is lib/pieces/song-tabs.mjs SONG_SECTION_TAB. +// Only the tab on show is read: the Cuts tab's ffprobes and the spec's +// validation cost nothing on the Overview. +// --------------------------------------------------------------------------- -export default async function SongProject({ id }: { id: string }) { +export default async function SongProject({ + project, + search, +}: { + project: ProjectRef; + search: Record<string, string | undefined>; +}) { + // Keyed by BASENAME, as every song route is (lib/browse.ts songDir). + const id = project.name; const song = await readSong(id); if (!song) notFound(); - // Durations are worth an ffprobe HERE but not on the index: this page is a - // handful of files and "which of these is the short cut" is exactly the - // question it answers. Memoised by mtime in lib/browse.ts. - const rels = [ - ...song.cuts.flatMap((c) => [c.shipped?.rel, ...c.variants.map((v) => v.rel)]), - ...song.unattributed.map((v) => v.rel), - ].filter((r): r is string => !!r); - const info = await probeAll(id, rels); - - const spec = await readSpec(id); - const problems = await validateSpec(spec); - const notes = await readNotes(id); - // Two small JSON reads, no probing -- the bench draws what the manifests say. - const thumbs = await thumbView(id, thumbAliasesFor(id)); + const tab = songTabOf(search); + // Two small JSON reads each, no probing. + const [frame, notes, thumbs] = await Promise.all([readSongFrame(project, song), readNotes(id), thumbView(id, thumbAliasesFor(id))]); return ( - <div className="flex h-full flex-col"> - <BrowseHeader - crumbs={[{ href: "/projects", label: "songs" }, { label: song.id }]} - note={`${song.present}/${song.cuts.length} cuts · ${song.variantCount} variants`} - /> - <div className="flex flex-wrap items-start gap-3 border-b border-[var(--color-line)] px-4 py-2"> - <div className="min-w-0 flex-1"> - {/* The one obvious place to write about the song, open by default -- - everything else on the page is collapsed until asked for. */} - <NoteField song={id} target="song" initial={notes.song ?? null} label="notes on this song" /> - </div> - <CopyButton - label="copy this song" - title="this song as markdown — spec, cuts, verdicts, notes and resolved marks" - url={`/api/browse/context?song=${encodeURIComponent(id)}`} - /> - </div> - <main className="deck-main flex-1"> - <div className="grid gap-4 p-4 xl:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]"> - <div className="space-y-3"> - {song.cuts.map((cut) => ( - <CutCard key={cut.name} song={song} cut={cut} info={info} notes={notes} /> - ))} - - {song.unattributed.length > 0 && ( - <section className="rounded border border-[var(--color-dirty)]/40 bg-[var(--color-panel)] p-3"> - <div className="micro mb-2"> - matches no cut name — attribute by renaming, never by guessing - </div> - <ul className="space-y-1"> - {song.unattributed.map((v) => ( - <li key={v.rel} className="num text-[12px] text-[var(--color-dim)]"> - <span className="font-mono text-[var(--color-text)]">{v.rel}</span>{" "} - {fmtBytes(v.size)} - </li> - ))} - </ul> - </section> - )} - </div> - - <aside className="space-y-4"> - <ThumbBench song={song.id} view={thumbs} notes={notes} /> - <SpecSheet - song={song.id} - initial={spec} - problems={problems} - operations={operationsFor(spec, song)} - plans={song.plans.map((p) => p.name)} - trimSets={Object.values(TRIM_SETS).map((t) => ({ id: t.id, label: t.label }))} - /> - {song.readme && ( - <section className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3"> - <Markdown text={song.readme} /> - </section> - )} - <section className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3"> - <div className="micro mb-2">plans</div> - {song.plans.length === 0 ? ( - <p className="text-[12px] text-[var(--color-dim)]">no plan/ directory</p> - ) : ( - <ul className="space-y-0.5"> - {song.plans.map((p) => ( - <li key={p.name} className="num text-[11px] text-[var(--color-dim)]"> - <span className="flex gap-2"> - <span className="truncate font-mono text-[var(--color-text)]">{p.name}</span> - <span className="ml-auto shrink-0">{fmtBytes(p.size)}</span> - </span> - <NoteField - song={song.id} - target={`plan:${p.name}`} - initial={notes[`plan:${p.name}`] ?? null} - label="what this plan is" - rows={3} - /> - </li> - ))} - </ul> - )} - {song.hasClipsCsv && <div className="micro mt-2">clips.csv present</div>} - </section> - </aside> - </div> - </main> - </div> - ); -} - -function CutCard({ - song, - cut, - info, - notes, -}: { - song: Song; - cut: Cut; - info: Record<string, { duration: number; width: number; height: number }>; - notes: NoteMap; -}) { - const shipped = cut.shipped; - const live = cut.variants.filter((v) => !v.retired); - const retired = cut.variants.filter((v) => v.retired); - - return ( - <section - data-cut={cut.name} - data-present={shipped ? "1" : "0"} - className="rounded border border-[var(--color-line)] bg-[var(--color-panel)]" + <SongFrame + project={project} + song={song} + frame={frame} + tab={tab} + counts={songCounts(song, notes, thumbs.candidates.length)} + note={`${song.present}/${song.cuts.length} cuts · ${song.variantCount} variants`} > - <div className="flex items-start gap-3 p-3"> - {shipped ? ( - /* eslint-disable-next-line @next/next/no-img-element */ - <img - src={`/api/browse/poster?song=${encodeURIComponent(song.id)}&rel=${encodeURIComponent(shipped.rel)}&w=320`} - alt="" - width={160} - height={90} - className="w-40 shrink-0 rounded bg-[var(--color-panel-2)] object-cover" - /> - ) : ( - <div className="flex h-[90px] w-40 shrink-0 items-center justify-center rounded border border-dashed border-[var(--color-line)] text-[11px] text-[var(--color-dim)]"> - not built - </div> - )} - - <div className="min-w-0 flex-1 space-y-1"> - <div className="flex flex-wrap items-baseline gap-2"> - <Link - href={`/projects/${song.id}/${cut.name}`} - className="font-mono text-[13px] text-[var(--color-text)] hover:text-[var(--color-sel)]" - > - {cut.name} - </Link> - {shipped ? ( - <span className="num text-[11px] text-[var(--color-meter)]"> - {fmtDur(info[shipped.rel]?.duration ?? 0)} - </span> - ) : ( - <span className="text-[11px] text-[var(--color-dim)]">— a hole in the set</span> - )} - {shipped && info[shipped.rel] && ( - <span className="num text-[11px] text-[var(--color-dim)]"> - {info[shipped.rel].width}×{info[shipped.rel].height} - </span> - )} - <span className="num ml-auto text-[11px] text-[var(--color-dim)]"> - {shipped ? `${fmtBytes(shipped.size)} · ${fmtAgo(shipped.mtimeMs)}` : ""} - </span> - </div> - - {shipped && ( - <VerdictChip song={song.id} rel={shipped.rel} initial={shipped.verdict} /> - )} - - {/* Two different notes, deliberately. The `cut:` one is about the SLOT - -- it survives a promote and can be written about a cut that has - not been built. The `file:` one is about these bytes. */} - <NoteField - song={song.id} - target={`cut:${cut.name}`} - initial={notes[`cut:${cut.name}`] ?? null} - label={`notes on ${cut.name}`} - rows={3} - /> - {shipped && ( - <NoteField - song={song.id} - target={`file:${shipped.rel}`} - initial={notes[`file:${shipped.rel}`] ?? null} - label="notes on this file" - rows={3} - /> - )} - - {live.length > 0 && ( - <ul className="space-y-1 pt-1"> - {live.map((v) => ( - <li - key={v.rel} - data-variant={v.rel} - data-variant-tag={v.tag} - className="flex flex-wrap items-center gap-2 rounded bg-[var(--color-panel-2)] px-2 py-1" - > - <span className="font-mono text-[12px] text-[var(--color-text)]">{v.tag}</span> - <span className="num text-[11px] text-[var(--color-meter)]"> - {fmtDur(info[v.rel]?.duration ?? 0)} - </span> - <span className="num text-[11px] text-[var(--color-dim)]">{fmtBytes(v.size)}</span> - <div className="ml-auto"> - <VerdictChip song={song.id} rel={v.rel} initial={v.verdict} /> - </div> - <div className="w-full"> - <NoteField - song={song.id} - target={`file:${v.rel}`} - initial={notes[`file:${v.rel}`] ?? null} - label={`notes on ${v.tag}`} - rows={3} - /> - </div> - </li> - ))} - </ul> - )} - - {retired.length > 0 && ( - <div className="micro pt-1" data-retired={retired.length}> - {retired.length} retired: {retired.map((v) => v.tag).join(", ")} - </div> - )} - </div> - </div> - </section> + {tab === "overview" && <OverviewTab project={project} song={song} frame={frame} covers={thumbs} />} + {tab === "cuts" && <CutsTab song={song} notes={notes} />} + {tab === "spec" && <SpecTab song={song} notes={notes} />} + {tab === "cover" && <CoverTab song={song} view={thumbs} notes={notes} />} + {tab === "notes" && <NotesTab projectId={project.id} song={song} notes={notes} />} + </SongFrame> ); } 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/projects/song/CoverTab.tsx b/umtool/components/projects/song/CoverTab.tsx @@ -0,0 +1,24 @@ +import ThumbBench from "@/components/ThumbBench"; +import type { Song } from "@/lib/browse"; +import type { NoteMap } from "@/lib/notes"; +import type { ThumbView } from "@/lib/thumbs"; + +// The Cover tab: the cover-art bench -- the candidates, the corners each would +// spend, accepting one, the way to the face judger -- SongProject's aside, +// moved unchanged (P4a-3). The bench draws nothing when there is nothing to +// judge, so the tab says so. + +export default function CoverTab({ song, view, notes }: { song: Song; view: ThumbView; notes: NoteMap }) { + if (!view.candidates.length && !view.accepted) { + return ( + <p className="text-[12.5px] text-muted" data-song-cover-empty=""> + No cover generated for {song.id} yet — nothing in the thumb manifest names it. + </p> + ); + } + return ( + <div className="max-w-[1100px]"> + <ThumbBench song={song.id} view={view} notes={notes} /> + </div> + ); +} diff --git a/umtool/components/projects/song/CutsTab.tsx b/umtool/components/projects/song/CutsTab.tsx @@ -0,0 +1,174 @@ +import Link from "next/link"; +import VerdictChip from "@/components/VerdictChip"; +import NoteField from "@/components/NoteField"; +import { probeAll, type Cut, type Song } from "@/lib/browse"; +import { fmtAgo, fmtBytes, fmtDur } from "@/lib/format"; +import type { NoteMap } from "@/lib/notes"; + +// The Cuts tab: the four cut cards (poster, verdicts, the slot's and the +// file's notes, the variants) and what matches no cut -- SongProject's left +// column, moved unchanged (P4a-3). A cut's own page (/projects/<song>/<cut>, +// CutPage) is this tab's view of one cut. + +export default async function CutsTab({ song, notes }: { song: Song; notes: NoteMap }) { + // Durations are worth an ffprobe HERE but not on the index: this page is a + // handful of files and "which of these is the short cut" is exactly the + // question it answers. Memoised by mtime in lib/browse.ts. + const rels = [ + ...song.cuts.flatMap((c) => [c.shipped?.rel, ...c.variants.map((v) => v.rel)]), + ...song.unattributed.map((v) => v.rel), + ].filter((r): r is string => !!r); + const info = await probeAll(song.id, rels); + + return ( + <div className="max-w-[1100px] space-y-3" data-song-cuts=""> + {song.cuts.map((cut) => ( + <CutCard key={cut.name} song={song} cut={cut} info={info} notes={notes} /> + ))} + + {song.unattributed.length > 0 && ( + <section className="rounded border border-[var(--color-dirty)]/40 bg-[var(--color-panel)] p-3" data-unattributed={song.unattributed.length}> + <div className="micro mb-2"> + matches no cut name — attribute by renaming, never by guessing + </div> + <ul className="space-y-1"> + {song.unattributed.map((v) => ( + <li key={v.rel} className="num text-[12px] text-[var(--color-dim)]"> + <span className="font-mono text-[var(--color-text)]">{v.rel}</span>{" "} + {fmtBytes(v.size)} + </li> + ))} + </ul> + </section> + )} + </div> + ); +} + +function CutCard({ + song, + cut, + info, + notes, +}: { + song: Song; + cut: Cut; + info: Record<string, { duration: number; width: number; height: number }>; + notes: NoteMap; +}) { + const shipped = cut.shipped; + const live = cut.variants.filter((v) => !v.retired); + const retired = cut.variants.filter((v) => v.retired); + + return ( + <section + data-cut={cut.name} + data-present={shipped ? "1" : "0"} + className="rounded border border-[var(--color-line)] bg-[var(--color-panel)]" + > + <div className="flex items-start gap-3 p-3"> + {shipped ? ( + /* eslint-disable-next-line @next/next/no-img-element */ + <img + src={`/api/browse/poster?song=${encodeURIComponent(song.id)}&rel=${encodeURIComponent(shipped.rel)}&w=320`} + alt="" + width={160} + height={90} + className="w-40 shrink-0 rounded bg-[var(--color-panel-2)] object-cover" + /> + ) : ( + <div className="flex h-[90px] w-40 shrink-0 items-center justify-center rounded border border-dashed border-[var(--color-line)] text-[11px] text-[var(--color-dim)]"> + not built + </div> + )} + + <div className="min-w-0 flex-1 space-y-1"> + <div className="flex flex-wrap items-baseline gap-2"> + <Link + href={`/projects/${song.id}/${cut.name}`} + className="ink-link font-mono text-[13px]" + > + {cut.name} + </Link> + {shipped ? ( + <span className="num text-[11px] text-[var(--color-meter)]"> + {fmtDur(info[shipped.rel]?.duration ?? 0)} + </span> + ) : ( + <span className="text-[11px] text-[var(--color-dim)]">— a hole in the set</span> + )} + {shipped && info[shipped.rel] && ( + <span className="num text-[11px] text-[var(--color-dim)]"> + {info[shipped.rel].width}×{info[shipped.rel].height} + </span> + )} + <span className="num ml-auto text-[11px] text-[var(--color-dim)]"> + {shipped ? `${fmtBytes(shipped.size)} · ${fmtAgo(shipped.mtimeMs)}` : ""} + </span> + </div> + + {shipped && ( + <VerdictChip song={song.id} rel={shipped.rel} initial={shipped.verdict} /> + )} + + {/* Two different notes, deliberately. The `cut:` one is about the SLOT + -- it survives a promote and can be written about a cut that has + not been built. The `file:` one is about these bytes. */} + <NoteField + song={song.id} + target={`cut:${cut.name}`} + initial={notes[`cut:${cut.name}`] ?? null} + label={`notes on ${cut.name}`} + rows={3} + /> + {shipped && ( + <NoteField + song={song.id} + target={`file:${shipped.rel}`} + initial={notes[`file:${shipped.rel}`] ?? null} + label="notes on this file" + rows={3} + /> + )} + + {live.length > 0 && ( + <ul className="space-y-1 pt-1"> + {live.map((v) => ( + <li + key={v.rel} + data-variant={v.rel} + data-variant-tag={v.tag} + className="flex flex-wrap items-center gap-2 rounded bg-[var(--color-panel-2)] px-2 py-1" + > + <span className="font-mono text-[12px] text-[var(--color-text)]">{v.tag}</span> + <span className="num text-[11px] text-[var(--color-meter)]"> + {fmtDur(info[v.rel]?.duration ?? 0)} + </span> + <span className="num text-[11px] text-[var(--color-dim)]">{fmtBytes(v.size)}</span> + <div className="ml-auto"> + <VerdictChip song={song.id} rel={v.rel} initial={v.verdict} /> + </div> + <div className="w-full"> + <NoteField + song={song.id} + target={`file:${v.rel}`} + initial={notes[`file:${v.rel}`] ?? null} + label={`notes on ${v.tag}`} + rows={3} + /> + </div> + </li> + ))} + </ul> + )} + + {retired.length > 0 && ( + <div className="micro pt-1" data-retired={retired.length}> + {retired.length} retired: {retired.map((v) => v.tag).join(", ")} + </div> + )} + </div> + </div> + </section> + ); +} diff --git a/umtool/components/projects/song/NotesTab.tsx b/umtool/components/projects/song/NotesTab.tsx @@ -0,0 +1,51 @@ +import Link from "next/link"; +import NoteField from "@/components/NoteField"; +import type { Song } from "@/lib/browse"; +import { projectHref } from "@/lib/hrefs"; +import type { NoteMap } from "@/lib/notes"; +import { SONG_PIECE_TABS, songTabOfNote } from "@/lib/pieces/song-tabs.mjs"; + +// The Notes tab: the note on the song as a whole -- the one obvious place to +// write about it, SongProject's head row, moved unchanged (P4a-3) -- and, under +// it, every other note on the song, each linking the tab it is written on (a +// cut's, a file's or a mark's on Cuts, a plan's on Spec, a cover's on Cover). + +const TAB_LABEL = Object.fromEntries(SONG_PIECE_TABS.map((t) => [t.id, t.label])); + +export default function NotesTab({ projectId, song, notes }: { projectId: string; song: Song; notes: NoteMap }) { + const others = Object.entries(notes) + .filter(([target, n]) => target !== "song" && n && typeof n.note === "string" && n.note.trim()) + .sort(([a], [b]) => a.localeCompare(b)); + return ( + <div className="max-w-[900px] space-y-5"> + <section data-song-note=""> + <NoteField song={song.id} target="song" initial={notes.song ?? null} label="notes on this song" /> + </section> + + <section data-song-notes={others.length}> + <h2 className="micro mb-1.5"> + Every other note · <span className="font-mono text-meter">{others.length}</span> + </h2> + {others.length === 0 ? ( + <p className="text-[12.5px] text-muted">None yet. Notes on a cut, a file, a plan or a cover show here.</p> + ) : ( + <ul className="divide-y divide-seam border-y border-seam"> + {others.map(([target, n]) => { + const tab = songTabOfNote(target); + const first = n.note.split("\n").find((l) => l.trim()) ?? ""; + return ( + <li key={target} data-song-note-target={target} className="flex items-baseline gap-3 py-1.5 text-[12.5px]"> + <span className="w-[260px] shrink-0 truncate font-mono text-[11.5px] text-text-2">{target}</span> + <span className="min-w-0 flex-1 truncate text-text">{first}</span> + <Link href={projectHref(projectId, { tab })} prefetch={false} className="ink-link shrink-0 text-[12px]"> + {TAB_LABEL[tab] ?? tab} + </Link> + </li> + ); + })} + </ul> + )} + </section> + </div> + ); +} diff --git a/umtool/components/projects/song/OverviewTab.tsx b/umtool/components/projects/song/OverviewTab.tsx @@ -0,0 +1,189 @@ +import Link from "next/link"; +import { Suspense } from "react"; +import CopyButton from "@/components/CopyButton"; +import NextCard, { NextCardShell } from "@/components/piece/NextCard"; +import { ProjectDecisions } from "@/components/projects/report/OverviewTab"; +import { PILE_WHAT } from "@/components/dashboard/ToolList"; +import { CUT_NAMES, type Song } from "@/lib/browse"; +import { decisionsForProject } from "@/lib/projects"; +import { fmtBytes } from "@/lib/format"; +import { cutHref, findHref, mixHref, pileHref, projectHref, songToolsHref, sourcesHref, trimHref } from "@/lib/hrefs"; +import { Markdown } from "@/lib/markdown"; +import type { PieceFrame } from "@/lib/pieces/frame"; +import type { ProjectRef } from "@/lib/project-types"; +import { readSpec } from "@/lib/spec"; +import { MODES } from "@/lib/types"; +import type { ThumbView } from "@/lib/thumbs"; + +// The Overview tab of a song piece (P4a-3; canvas "Piece · Overview" in a +// song's words): the Next card -- the song's top Inbox call, an unjudged +// variant, a missing cut, a stale recipe -- then the song's decisions and its +// four cut slots beside what the song is, the paste ("copy this song", from +// SongProject's head row), and the song tools, which stay in Tools (the four +// judging piles, find, mix, sources, the hook trimmer). The README is +// SongProject's, unchanged. + +export default async function OverviewTab({ + project, + song, + frame, + covers, +}: { + project: ProjectRef; + song: Song; + frame: PieceFrame; + covers: ThumbView; +}) { + const [decisions, spec] = await Promise.all([decisionsForProject(project), readSpec(song.id)]); + const looksDone = (frame.piece?.looksDone ?? []).map((w) => w.replace(`${project.id}: `, "")); + if (!looksDone.length && song.present === CUT_NAMES.length) looksDone.push("every cut shipped"); + const trimSet = spec.hooks?.trimSet ?? null; + + return ( + <> + <Suspense + fallback={ + <NextCardShell pending> + <span className="text-[12.5px] text-muted">Reading the Inbox…</span> + </NextCardShell> + } + > + <NextCard pieceId={frame.pieceId} title={frame.piece?.title ?? song.title} lifecycle={frame.lifecycle} /> + </Suspense> + + <div className="grid grid-cols-1 gap-[22px] lg:grid-cols-[minmax(0,1.25fr)_minmax(0,1fr)]"> + <div className="min-w-0 space-y-4"> + {/* --- what is wrong, first ------------------------------------- */} + <ProjectDecisions project={project.id} decisions={decisions} /> + + <section data-song-slots={song.present}> + <div className="mb-1.5 flex items-baseline gap-3"> + <h2 className="micro"> + Cuts · <span className="font-mono text-meter">{song.present}</span> of {song.cuts.length} + </h2> + <Link href={projectHref(project.id, { tab: "cuts" })} prefetch={false} className="ink-link ml-auto text-[12px]"> + All cuts → + </Link> + </div> + <ul className="border-y border-seam"> + {song.cuts.map((cut) => { + const live = cut.variants.filter((v) => !v.retired).length; + return ( + <li + key={cut.name} + data-song-slot={cut.name} + data-present={cut.shipped ? "1" : "0"} + className="flex items-baseline gap-3 border-b border-seam py-1.5 text-[13px] last:border-b-0" + > + <Link href={cutHref(project.id, cut.name)} prefetch={false} className="ink-link font-mono text-[12.5px]"> + {cut.name} + </Link> + <span className="text-[12px] text-muted"> + {cut.shipped ? `built · ${fmtBytes(cut.shipped.size)}` : "a hole in the set"} + </span> + <span className="ml-auto font-mono text-[11.5px] text-meter"> + {live ? `${live} variant${live === 1 ? "" : "s"}` : ""} + </span> + </li> + ); + })} + </ul> + </section> + </div> + + <div className="min-w-0 space-y-4"> + <section data-piece-stats=""> + <div className="mb-1.5 flex items-baseline gap-3"> + <h2 className="micro">This song</h2> + <span className="ml-auto" data-song-copy=""> + <CopyButton + label="copy this song" + title="this song as markdown — spec, cuts, verdicts, notes and resolved marks" + url={`/api/browse/context?song=${encodeURIComponent(song.id)}`} + /> + </span> + </div> + <ul className="text-[13px] text-text-2"> + <li className="flex gap-2.5 border-b border-seam py-1.5"> + cuts built + <span className="ml-auto font-mono text-[11.5px] text-meter"> + {song.present} / {song.cuts.length} + {song.missing.length ? ` · no ${song.missing.join(", ")}` : ""} + </span> + </li> + <li className="flex gap-2.5 border-b border-seam py-1.5"> + variants + <span className="ml-auto font-mono text-[11.5px] text-meter">{song.variantCount}</span> + </li> + <li className="flex gap-2.5 border-b border-seam py-1.5"> + verdicts + <span className="ml-auto font-mono text-[11.5px] text-meter"> + {song.counts.keep} keep · {song.counts.reject} reject · {song.counts.undecided} undecided + </span> + </li> + <li className="flex gap-2.5 border-b border-seam py-1.5"> + plans + <span className="ml-auto font-mono text-[11.5px] text-meter">{song.plans.length}</span> + </li> + <li className="flex gap-2.5 border-b border-seam py-1.5"> + cover + <span className="ml-auto text-[12px] text-text-2"> + {covers.accepted ? `accepted · ${covers.accepted.name}` : covers.candidates.length ? `${covers.candidates.length} on offer, none accepted` : "none generated"} + </span> + </li> + {looksDone.length > 0 && frame.lifecycle === "active" && ( + <li className="flex gap-2.5 border-b border-seam py-1.5" data-song-looks-done=""> + looks done + <span className="ml-auto text-[12px] text-muted">{looksDone.join("; ")}</span> + </li> + )} + </ul> + </section> + + <section data-song-tools=""> + <h2 className="micro mb-1.5">Song tools</h2> + <ul className="text-[13px]"> + {MODES.map((m) => ( + <li key={m} className="flex gap-2.5 border-b border-seam py-1.5"> + <Link href={pileHref(m)} prefetch={false} className="ink-link" data-song-pile={m}> + {m} + </Link> + <span className="ml-auto truncate text-[12px] text-muted">{PILE_WHAT[m]}</span> + </li> + ))} + {trimSet && ( + <li className="flex gap-2.5 border-b border-seam py-1.5"> + <Link href={trimHref(trimSet)} prefetch={false} className="ink-link" data-song-trim={trimSet}> + trim {trimSet} + </Link> + <span className="ml-auto truncate text-[12px] text-muted">the hook trimmer, for the spec&apos;s hooks</span> + </li> + )} + </ul> + <p className="mt-1.5 flex flex-wrap gap-x-3 text-[12px]"> + <Link href={songToolsHref()} prefetch={false} className="ink-link"> + song piles + </Link> + <Link href={findHref()} prefetch={false} className="ink-link"> + find + </Link> + <Link href={mixHref()} prefetch={false} className="ink-link"> + mix + </Link> + <Link href={sourcesHref()} prefetch={false} className="ink-link"> + sources + </Link> + </p> + </section> + </div> + </div> + + {/* --- the song's own account of itself ---------------------------- */} + {song.readme && ( + <section data-readme="" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3"> + <Markdown text={song.readme} /> + </section> + )} + </> + ); +} diff --git a/umtool/components/projects/song/SongFrame.tsx b/umtool/components/projects/song/SongFrame.tsx @@ -0,0 +1,95 @@ +import { stat } from "node:fs/promises"; +import PieceFrame from "@/components/piece/PieceFrame"; +import type { Crumb } from "@/components/shell/AppHeader"; +import { CUT_NAMES, type Song } from "@/lib/browse"; +import { projectHref, projectsHref } from "@/lib/hrefs"; +import type { NoteMap } from "@/lib/notes"; +import { readPieceFrame, type PieceFrame as Frame } from "@/lib/pieces/frame"; +import { SONG_PIECE_TABS } from "@/lib/pieces/song-tabs.mjs"; +import { specFile } from "@/lib/spec"; +import type { ProjectRef } from "@/lib/project-types"; + +// --------------------------------------------------------------------------- +// A SONG PIECE's frame (plans/umtool-redesign.md, P4a-3): the P4a frame +// (components/piece/PieceFrame.tsx -- head, stepper, lifecycle, Next, tabs, +// keys) around one of a song's five tabs, Overview · Cuts · Spec · Cover · +// Notes (lib/pieces/song-tabs.mjs). The song page and a cut's page (a view of +// the Cuts tab) both draw through it. +// +// The stepper is Spec → Cuts → Done, by the one stage rule (lib/pieces/tabs.mjs +// pieceSteps on the flow the song kind declares). The page has the song in +// hand, so the facts that light it are read fresh here (a promote shows at +// once); Work's facet reads the same facts off the pieces graph. +// --------------------------------------------------------------------------- + +/** What a song piece has reached, from the song the page already read (one stat for spec.json). */ +export async function songReachedNow(song: Song): Promise<{ spec: boolean; cuts: boolean; done: boolean }> { + const spec = await stat(specFile(song.id)).then( + () => true, + () => false, + ); + return { spec, cuts: song.present > 0, done: song.present === CUT_NAMES.length }; +} + +export async function readSongFrame(project: ProjectRef, song: Song): Promise<Frame> { + return readPieceFrame(project, { reached: await songReachedNow(song) }); +} + +/** A song tab's count, in Meter: cuts built, covers on offer, notes written. */ +export function songCounts(song: Song, notes: NoteMap, covers: number): Partial<Record<string, number>> { + const written = Object.values(notes).filter((n) => n && typeof n.note === "string" && n.note.trim()).length; + return { cuts: song.present, cover: covers, notes: written }; +} + +export default function SongFrame({ + project, + song, + frame, + tab, + counts, + note, + meta, + idHref, + bare = false, + children, +}: { + project: ProjectRef; + song: Song; + frame: Frame; + tab: string; + counts: Partial<Record<string, number>>; + /** The head's status line. */ + note?: React.ReactNode; + /** A line beside the title (a cut's page: which cut). */ + meta?: React.ReactNode; + /** Link the trail's project id (a cut's page: back to the song). */ + idHref?: string; + /** The body pads itself (a cut's page: the bench is edge to edge). */ + bare?: boolean; + children: React.ReactNode; +}) { + const title = frame.piece?.title ?? song.title; + const crumbs: Crumb[] = [ + { href: projectsHref(), label: "projects" }, + { label: project.id, ...(idHref ? { href: idHref } : {}) }, + { label: title }, + ]; + return ( + <div className="flex h-full flex-col" data-song-piece={song.id}> + <PieceFrame + crumbs={crumbs} + frame={frame} + tab={tab} + tabs={SONG_PIECE_TABS.map((t) => ({ ...t, href: projectHref(project.id, { tab: t.id }) }))} + counts={counts} + note={note} + meta={meta} + more={<span className="px-2 pb-1 pt-0.5 font-mono text-[11px] text-muted">{project.id}</span>} + > + <main className={bare ? "deck-main flex-1" : "deck-main flex-1 space-y-4 p-4"} data-piece-tab={tab}> + {children} + </main> + </PieceFrame> + </div> + ); +} diff --git a/umtool/components/projects/song/SpecTab.tsx b/umtool/components/projects/song/SpecTab.tsx @@ -0,0 +1,57 @@ +import SpecSheet from "@/components/SpecSheet"; +import NoteField from "@/components/NoteField"; +import type { Song } from "@/lib/browse"; +import { fmtBytes } from "@/lib/format"; +import type { NoteMap } from "@/lib/notes"; +import { operationsFor, readSpec, validateSpec } from "@/lib/spec"; +import { TRIM_SETS } from "@/lib/trim"; + +// The Spec tab: the spec sheet (what the song is made of, and so the +// operations it can run) and the plans in plan/ with their notes -- +// SongProject's aside, moved unchanged (P4a-3). + +export default async function SpecTab({ song, notes }: { song: Song; notes: NoteMap }) { + const spec = await readSpec(song.id); + const problems = await validateSpec(spec); + return ( + <div className="grid grid-cols-1 gap-4 lg:grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)]"> + <div className="min-w-0"> + <SpecSheet + song={song.id} + initial={spec} + problems={problems} + operations={operationsFor(spec, song)} + plans={song.plans.map((p) => p.name)} + trimSets={Object.values(TRIM_SETS).map((t) => ({ id: t.id, label: t.label }))} + /> + </div> + <div className="min-w-0"> + <section className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3" data-song-plans={song.plans.length}> + <div className="micro mb-2">plans</div> + {song.plans.length === 0 ? ( + <p className="text-[12px] text-[var(--color-dim)]">no plan/ directory</p> + ) : ( + <ul className="space-y-0.5"> + {song.plans.map((p) => ( + <li key={p.name} className="num text-[11px] text-[var(--color-dim)]"> + <span className="flex gap-2"> + <span className="truncate font-mono text-[var(--color-text)]">{p.name}</span> + <span className="ml-auto shrink-0">{fmtBytes(p.size)}</span> + </span> + <NoteField + song={song.id} + target={`plan:${p.name}`} + initial={notes[`plan:${p.name}`] ?? null} + label="what this plan is" + rows={3} + /> + </li> + ))} + </ul> + )} + {song.hasClipsCsv && <div className="micro mt-2">clips.csv present</div>} + </section> + </div> + </div> + ); +} 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/browse.spec.ts b/umtool/e2e/browse.spec.ts @@ -1,5 +1,6 @@ import { test, expect } from "@playwright/test"; import { caps, NO_SONG_DATA } from "./capabilities"; +import * as urls from "./urls"; // The browse pages, against the synthesised videos/ tree in make-fixture.mjs: // @@ -33,7 +34,7 @@ test("the index lists both songs, and says which cuts are missing", async ({ pag // to `wide-short`; a plain startsWith() over an unordered cut list binds it to // `wide`, and then every short's variants collect under the long one. test("a variant binds to the LONGEST matching cut name", async ({ page }) => { - await page.goto("/browse/alpha"); + await page.goto(urls.songSection("alpha", "variants")); const wide = page.locator("[data-cut=wide]"); const wideShort = page.locator("[data-cut='wide-short']"); @@ -55,7 +56,7 @@ test("a variant binds to the LONGEST matching cut name", async ({ page }) => { }); test("a song with a hole shows the hole", async ({ page }) => { - await page.goto("/browse/beta"); + await page.goto(urls.songSection("beta", "cuts")); await expect(page.locator("[data-cut=wide]")).toHaveAttribute("data-present", "1"); await expect(page.locator("[data-cut=vertical]")).toHaveAttribute("data-present", "0"); await expect(page.locator("[data-cut='vertical-short']")).toHaveAttribute("data-present", "0"); @@ -97,7 +98,7 @@ test("a verdict round-trips and survives a reload", async ({ page, request }) => }); expect(post.ok()).toBe(true); - await page.goto("/browse/alpha"); + await page.goto(urls.songSection("alpha", "verdicts")); const chip = page.locator("[data-verdict-for='variants/wide-nokit.mp4']"); await expect(chip.locator("[data-verdict=keep]")).toHaveAttribute("data-on", "1"); await expect(chip.getByText("the kit is wrong")).toBeVisible(); @@ -132,7 +133,7 @@ test("promote MOVES, and the outgoing cut survives as a variant", async ({ reque test("the demoted cut comes back under the SAME cut, with the right length", async ({ page }) => { // Runs after the promote above (the suite is serial, workers: 1). - await page.goto("/browse/alpha"); + await page.goto(urls.songSection("alpha", "cuts")); const wideShort = page.locator("[data-cut='wide-short']"); // The shipped file is now the 4s variant... @@ -243,7 +244,7 @@ test("the song page links to the trim editor once hooks are declared", async ({ await request.put("/api/browse/spec", { data: { song: "alpha", spec: { version: 1, song: "alpha", hooks: { trimSet: "mk-hooks" } } }, }); - await page.goto("/browse/alpha"); + await page.goto(urls.songSection("alpha", "operations")); await expect(page.locator("[data-op=trim-hooks]")).toHaveAttribute("data-blocked", "0"); await page.locator("[data-op=trim-hooks]").getByRole("link").click(); await expect(page).toHaveURL(/\/tools\/trim\/mk-hooks/); @@ -346,7 +347,7 @@ test("a new song gets the shape but NO cut files", async ({ request, page }) => expect(r.ok()).toBe(true); expect((await r.json()).href).toBe("/projects/gamma"); - await page.goto("/browse/gamma"); + await page.goto(urls.songSection("gamma", "cuts")); // Every cut must read as a hole. A zero-byte wide.mp4 would read as built. for (const cut of ["wide", "wide-short", "vertical", "vertical-short"]) { await expect(page.locator(`[data-cut=${cut}]`)).toHaveAttribute("data-present", "0"); 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/faces.spec.ts b/umtool/e2e/faces.spec.ts @@ -3,6 +3,7 @@ import { readFileSync } from "node:fs"; import path from "node:path"; import { autoCrop, scaleOf, CORNER_PX, SHOVE_FLOOR, type Box } from "../lib/face-types"; import { caps, NO_FACEDET, NO_SOURCE_MEDIA } from "./capabilities"; +import * as urls from "./urls"; // The face judger, against the REAL episodes the fixture symlinks -- make-fixture // derives its cover corners from media/ precisely so the frame and detect routes @@ -95,7 +96,8 @@ test("/browse/faces is the face judger, at /tools/faces", async ({ page }) => { // The way in is the cover-art bench, not a tenth nav item -- AppNav is at nine // and says a tenth wraps the header on a laptop. test("the bench links to the judger and the nav does not", async ({ page }) => { - await page.goto("/browse/alpha"); + // The cover bench is the song piece's Cover tab (P4a-3). + await page.goto(urls.songSection("alpha", "faces")); const link = page.locator("[data-judge-faces]").first(); await expect(link).toBeVisible(); const cover = (await link.getAttribute("data-judge-faces")) ?? ""; 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/projects.spec.ts b/umtool/e2e/projects.spec.ts @@ -194,7 +194,12 @@ test("the song URLs that already existed still mean the same thing", async ({ pa test.skip(!caps.song, NO_SONG_DATA); // A project id is a path now, but /browse/alpha and /browse/alpha/wide are // the URLs in every decision href, every spec, and whatever anybody has open. + // The song is a piece page since P4a-3: the bare address is its Overview, + // with the cut set at a glance; the cut cards are the Cuts tab. await page.goto("/browse/alpha"); + await expect(page).toHaveURL(/\/projects\/alpha$/); + await expect(page.locator("[data-song-slot=wide]")).toBeVisible(); + await page.goto(urls.songSection("alpha", "cuts")); await expect(page.locator("[data-cut=wide]")).toBeVisible(); await page.goto("/browse/alpha/wide"); // The old address rides its redirect to the same view. @@ -203,9 +208,12 @@ test("the song URLs that already existed still mean the same thing", async ({ pa // resolved rather than the project page having been served for both URLs. await expect(page.getByText(/^every note \(\d+\)$/)).toBeVisible(); + // The cut's page is a view of the Cuts tab. + await expect(page.locator("[data-piece-tabs]")).toHaveAttribute("data-piece-tabs", "cuts"); + // And the canonical path works too. await page.goto("/browse/reports/videos/alpha"); - await expect(page.locator("[data-cut=wide]")).toBeVisible(); + await expect(page.locator("[data-song-slot=wide]")).toBeVisible(); }); test("every tool page that was under /browse still answers, at /tools", async ({ page }) => { diff --git a/umtool/e2e/song-piece.spec.ts b/umtool/e2e/song-piece.spec.ts @@ -0,0 +1,207 @@ +import { test, expect, type Page } from "@playwright/test"; +import * as urls from "./urls"; +import { SONG_SECTION_TAB } from "../lib/pieces/song-tabs.mjs"; + +// --------------------------------------------------------------------------- +// The song piece (plans/umtool-redesign.md, P4a-3): a song's page is the P4a +// frame -- the head, the Spec → Cuts → Done stepper, the lifecycle chip, the +// Next card -- around ONE of five tabs, Overview · Cuts · Spec · Cover · Notes, +// and a cut's page is a view of the Cuts tab. Against make-fixture.mjs's songs: +// +// alpha all four cuts (the derived `shipped`: Done, and it looks done) +// beta wide and wide-short only (at Cuts) +// +// browse.spec runs first and promotes, notes and re-specs alpha; nothing here +// depends on which file ships, only on the set being whole. +// --------------------------------------------------------------------------- + +const ALPHA = "reports/videos/alpha"; +const BETA = "reports/videos/beta"; +const PIECE = `p:${ALPHA}`; + +const tab = (page: Page, id: string) => page.getByTestId(`piece-tab-${id}`); +const keysReady = (page: Page) => expect(page.locator("[data-piece-keys=ready]")).toBeAttached(); +const steps = (page: Page) => page.getByRole("list", { name: "Stage" }).locator("li"); + +test("the frame: title, trail, the Spec → Cuts → Done stepper, five tabs, the Overview alone", async ({ page }) => { + const res = await page.goto(urls.projectHref("alpha")); + expect(res?.status()).toBe(200); + const crumbs = page.getByRole("navigation", { name: "Breadcrumb" }); + await expect(crumbs.locator("h1")).toHaveText(/Alpha/); + await expect(crumbs).toContainText(ALPHA); + await expect(page.locator("header .micro").last()).toHaveText(/4\/4 cuts · \d+ variants/i); + + // Every cut built: at Done (a suggestion -- the lifecycle is still Active). + const frame = page.locator(`[data-piece-frame="${PIECE}"]`); + await expect(frame).toHaveAttribute("data-piece-stage", "done"); + await expect(frame).toHaveAttribute("data-piece-lifecycle", "active"); + await expect(steps(page)).toHaveText([/^Spec/, /^Cuts/, /^Done/]); + await expect(steps(page).nth(2)).toHaveAttribute("aria-current", "step"); + await expect(steps(page).nth(1)).toHaveAttribute("data-step", "done"); + + const tabs = page.getByRole("navigation", { name: "Piece" }).getByRole("link"); + await expect(tabs).toHaveText([/^Overview/, /^Cuts/, /^Spec/, /^Cover/, /^Notes/]); + await expect(tab(page, "overview")).toHaveAttribute("aria-current", "page"); + await expect(tab(page, "cuts")).toHaveText("Cuts4"); + await expect(tab(page, "cuts")).toHaveAttribute("href", urls.projectHref(ALPHA, { tab: "cuts" })); + + // The Overview: the Next card, the decisions, the cut set at a glance, the + // looks-done suggestion, the song tools -- and none of the other tabs' sections. + await expect(page.locator("[data-next]:visible")).toBeVisible(); + await expect(page.locator("[data-song-slot]")).toHaveCount(4); + await expect(page.locator("[data-song-slot][data-present='0']")).toHaveCount(0); + await expect(page.locator("[data-song-looks-done]")).toContainText("every cut shipped"); + await expect(page.locator("[data-song-pile=sort]")).toHaveAttribute("href", urls.pileHref("sort")); + await expect(page.locator("[data-song-copy]")).toBeVisible(); + await expect(page.locator("[data-cut]")).toHaveCount(0); + await expect(page.locator("[data-op]")).toHaveCount(0); + await expect(page.locator("[data-note-for=song]")).toHaveCount(0); +}); + +test("a song with a hole is at Cuts, and Work files it where its stepper says", async ({ page }) => { + await page.goto(urls.projectHref(BETA)); + await expect(page.locator(`[data-piece-frame="p:${BETA}"]`)).toHaveAttribute("data-piece-stage", "cuts"); + await expect(steps(page).nth(1)).toHaveAttribute("aria-current", "step"); + await expect(steps(page).nth(2)).toHaveAttribute("data-step", "todo"); + await expect(page.locator("[data-song-slot=vertical]")).toHaveAttribute("data-present", "0"); + await expect(page.locator("[data-song-looks-done]")).toHaveCount(0); + + // Work: the song's own three steps on its bar; its bucket is the one the step stands in for. + await page.goto(urls.workHref({ life: "all" })); + const beta = page.locator(`[data-lit-line][data-piece='p:${BETA}']`); + await expect(beta).toHaveAttribute("data-stage", "video"); + await expect(beta).toContainText("cuts"); + const alpha = page.locator(`[data-lit-line][data-piece='${PIECE}']`); + await expect(alpha).toHaveAttribute("data-stage", "deliver"); + await expect(alpha).toContainText("done"); + await expect(alpha).toContainText("looks done"); +}); + +test("the Next card is the song's top Inbox call, and its one action goes where the Inbox's does", async ({ page, request }) => { + const inbox = (await (await request.get("/api/browse/decisions")).json()) as { + groups: { id: string; cards: { piece: string | null; kind: string; action: { label: string; href: string } }[] }[]; + }; + const top = inbox.groups.filter((g) => g.id !== "quiet").flatMap((g) => g.cards).find((c) => c.piece === PIECE); + expect(top, "the fixture's alpha has a call waiting").toBeTruthy(); + + await page.goto(urls.projectHref(ALPHA)); + const next = page.locator("[data-next]:visible"); + await expect(next.locator("[data-next-kind]")).toHaveAttribute("data-next-kind", top!.kind); + const action = next.locator("[data-next-action] > :is(a, button):visible"); + await expect(action).toHaveText(top!.action.label); +}); + +test("a song's calls land on their tab: the spec's on Spec, a cover's on Cover, a cut's on its page", async ({ request }) => { + const items = ((await (await request.get("/api/browse/decisions?project=alpha")).json()) as { items: { kind: string; href: string }[] }).items; + const WHERE: Record<string, string> = { "spec-problem": "spec", "no-plan": "spec", unattributed: "cuts", "thumb-unaccepted": "cover" }; + const songWide = items.filter((d) => WHERE[d.kind]); + expect(songWide.length, "alpha names no plan, so at least that call").toBeGreaterThan(0); + for (const d of songWide) expect(d.href, d.kind).toBe(`/projects/alpha?tab=${WHERE[d.kind]}`); + for (const d of items.filter((x) => x.kind === "unjudged-variant" || x.kind === "stale-recipe")) { + expect(d.href, d.kind).toMatch(/^\/projects\/alpha\/(wide|wide-short|vertical|vertical-short)(\?|$)/); + } +}); + +test("the tab is the URL: ?tab=, a note's target, a bad tab the Overview, and the old addresses land", async ({ page }) => { + // Every section a spec names is on the tab the table says. + expect(SONG_SECTION_TAB.cuts).toBe("cuts"); + + await page.goto(urls.songSection("alpha", "cuts")); + await expect(tab(page, "cuts")).toHaveAttribute("aria-current", "page"); + await expect(page.locator("[data-cut]")).toHaveCount(4); + await expect(page.locator("[data-song-slot]")).toHaveCount(0); + + await page.goto(urls.songSection("alpha", "spec")); + await expect(page.locator("[data-op=trim-hooks]")).toBeVisible(); + await expect(page.locator("[data-song-plans]")).toBeVisible(); + + await page.goto(urls.songSection("alpha", "cover")); + await expect(page.locator("[data-judge-faces]").first()).toBeVisible(); + + await page.goto(urls.songSection("alpha", "notes")); + await expect(page.locator("[data-note-for=song]").first()).toBeVisible(); + await expect(page.locator("[data-song-notes]")).toBeVisible(); + + await page.goto(urls.projectHref(ALPHA, { tab: "nonsense" })); + await expect(tab(page, "overview")).toHaveAttribute("aria-current", "page"); + + // A song's notes are keyed by target: `?note=` opens the tab it is written on. + await page.goto(urls.projectHref("alpha", { note: "song" })); + await expect(tab(page, "notes")).toHaveAttribute("aria-current", "page"); + await page.goto(urls.projectHref("alpha", { note: "plan:alpha.plan.json" })); + await expect(tab(page, "spec")).toHaveAttribute("aria-current", "page"); + await page.goto(urls.projectHref("alpha", { note: "cut:vertical" })); + await expect(tab(page, "cuts")).toHaveAttribute("aria-current", "page"); + + // The old address rides P3's redirect to the Overview. + await page.goto("/browse/alpha"); + await expect(page).toHaveURL(/\/projects\/alpha$/); + await expect(tab(page, "overview")).toHaveAttribute("aria-current", "page"); +}); + +test("a cut's page is a view of the Cuts tab: the frame, the four cuts beside the title, the bench under it", async ({ page }) => { + const res = await page.goto("/browse/alpha/wide"); + expect(res?.status()).toBe(200); + await expect(page).toHaveURL(/\/projects\/alpha\/wide$/); + await expect(tab(page, "cuts")).toHaveAttribute("aria-current", "page"); + await expect(page.locator(`[data-piece-frame="${PIECE}"]`)).toBeVisible(); + const picker = page.locator("[data-song-cut-picker=wide]"); + await expect(picker.locator("[aria-current=page]")).toHaveText("wide"); + await expect(page.locator("[data-loudness='wide.mp4']")).toBeVisible(); + // The trail's project id is the way back to the song. + await expect(page.getByRole("navigation", { name: "Breadcrumb" }).getByRole("link", { name: ALPHA })).toHaveAttribute( + "href", + urls.projectHref(ALPHA), + ); + await picker.getByRole("link", { name: "wide-short" }).click(); + await expect(page).toHaveURL(new RegExp(`/projects/${ALPHA}/wide-short$`)); + await expect(page.locator("[data-song-cut-picker=wide-short]")).toBeVisible(); +}); + +test("keys: 1–5 open the tabs, n runs the Next card's action", async ({ page }) => { + await page.goto(urls.projectHref(ALPHA)); + await keysReady(page); + await page.keyboard.press("2"); + await expect(page).toHaveURL(/\?tab=cuts$/); + await keysReady(page); + await page.keyboard.press("5"); + await expect(page).toHaveURL(/\?tab=notes$/); + await expect(tab(page, "notes")).toHaveAttribute("aria-current", "page"); + await keysReady(page); + await page.keyboard.press("1"); + await expect(tab(page, "overview")).toHaveAttribute("aria-current", "page"); + + await keysReady(page); + const action = page.locator("[data-next-action] > a:visible"); + if ((await action.count()) > 0) { + const href = await action.getAttribute("href"); + await page.keyboard.press("n"); + await expect(page).toHaveURL(new RegExp(`${href!.replace(/[?]/g, "\\?")}$`)); + } +}); + +test("marked done, every stage is done; the lifecycle chip says so", async ({ page, request }) => { + try { + expect((await request.post("/api/pieces/lifecycle", { data: { piece: PIECE, state: "done" } })).ok()).toBe(true); + await page.goto(urls.projectHref(ALPHA)); + await expect(page.locator("[data-lifecycle-chip]")).toHaveAttribute("data-lifecycle-chip", "done"); + for (let i = 0; i < 3; i += 1) await expect(steps(page).nth(i)).toHaveAttribute("data-step", "done"); + // The suggestion is spent once the piece is marked done. + await expect(page.locator("[data-song-looks-done]")).toHaveCount(0); + await expect(page.locator("[data-next-kind=lifecycle]")).toContainText("Marked done"); + } finally { + await request.post("/api/pieces/lifecycle", { data: { piece: PIECE, state: "active" } }); + } +}); + +test("fits 1366×768: the head, the five tabs and the Next card's action without a horizontal scroll", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + for (const href of [urls.projectHref(ALPHA), urls.projectHref(ALPHA, { tab: "cuts" }), urls.projectHref(ALPHA, { tab: "spec" }), "/projects/alpha/wide"]) { + await page.goto(href); + await expect(tab(page, "notes")).toBeInViewport(); + const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + expect(overflow, href).toBeLessThanOrEqual(0); + } + await page.goto(urls.projectHref(ALPHA)); + await expect(page.locator("[data-next-action] > :is(a, button):visible")).toBeInViewport(); +}); 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/e2e/urls.ts b/umtool/e2e/urls.ts @@ -9,6 +9,7 @@ // value here too, so a URL change is one edit in lib/hrefs.ts. import { projectHref } from "../lib/hrefs"; import { tabOfSection } from "../lib/pieces/tabs.mjs"; +import { songTabOfSection } from "../lib/pieces/song-tabs.mjs"; export * from "../lib/hrefs"; export { REDIRECTS } from "../redirects.mjs"; @@ -22,3 +23,12 @@ export { REDIRECTS } from "../redirects.mjs"; export function section(project: string, name: string, q: { all?: boolean; note?: string } = {}): string { return projectHref(project, { tab: tabOfSection(name), ...q }); } + +/** + * A song piece's tab that holds `name` (lib/pieces/song-tabs.mjs + * SONG_SECTION_TAB): `songSection("alpha", "cuts")` is `/projects/alpha?tab=cuts`. + * The song counterpart of `section` -- a song's sections are its own (P4a-3). + */ +export function songSection(song: string, name: string, q: { note?: string } = {}): string { + return projectHref(song, { tab: songTabOfSection(name), ...q }); +} 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. @@ -341,11 +342,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; @@ -416,6 +427,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/decisions.ts b/umtool/lib/decisions.ts @@ -7,6 +7,7 @@ import { readNotes, type NoteMap } from "./notes"; import { listNotesFiles } from "./annotations/targets.mjs"; import { acceptedFor, readThumbAccepted, readThumbManifest, thumbNamesFor } from "./thumbs"; import { articleHrefOf } from "./articles/href"; +import { songTabOfSection } from "./pieces/song-tabs.mjs"; // --------------------------------------------------------------------------- // Everything undecided, in one worklist. @@ -135,7 +136,10 @@ export async function decisionsForSong(id: string): Promise<Decision[]> { ]); const out: Decision[] = []; - const songHref = `/projects/${id}`; + // A song-wide call opens the song piece's tab its section is on (P4a-3, + // lib/pieces/song-tabs.mjs): the spec's on Spec, a stray variant on Cuts, a + // cover on Cover. A cut's call opens the cut's page (the Cuts tab's view). + const songHref = (section: string) => `/projects/${id}?tab=${songTabOfSection(section)}`; const cutHref = (cut: string) => `/projects/${id}/${cut}`; const target = { lufs: spec.loudness?.targetLufs ?? DEFAULT_TARGET.lufs, @@ -149,7 +153,7 @@ export async function decisionsForSong(id: string): Promise<Decision[]> { project: id, target: p.where, why: p.message, - href: songHref, + href: songHref("spec"), // `pending` is the sheet being right about a file you have not rendered // yet, which is a normal state to save from -- so it is not a decision. severity: p.level === "error" ? "blocking" : "info", @@ -254,7 +258,7 @@ export async function decisionsForSong(id: string): Promise<Decision[]> { project: id, target: v.rel, why: "matches no cut name — attribute it by renaming, never by guessing", - href: songHref, + href: songHref("unattributed"), severity: "open", at: v.mtimeMs, }); @@ -268,7 +272,7 @@ export async function decisionsForSong(id: string): Promise<Decision[]> { project: id, target: named, why: `spec names plan/${named}, which is not there — provenance cannot resolve`, - href: songHref, + href: songHref("plans"), severity: "open", at: song.newestMtimeMs, }); @@ -280,7 +284,7 @@ export async function decisionsForSong(id: string): Promise<Decision[]> { why: `${song.plans.length} plan${song.plans.length > 1 ? "s" : ""} in plan/ and none named — ` + "which one shipped is not recorded, so it is not guessed", - href: songHref, + href: songHref("plans"), // Three of the five songs here have a 2-voice and a 3-voice arrangement // of the same tune. Nothing on disk says which shipped; only a person // can, and until they do every provenance figure is unattributed. @@ -297,7 +301,7 @@ export async function decisionsForSong(id: string): Promise<Decision[]> { project: id, target: candidates.join(", "), why: `${candidates.length} generated cover${candidates.length > 1 ? "s" : ""}, none accepted`, - href: songHref, + href: songHref("cover"), severity: "info", at: song.newestMtimeMs, }); 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"; @@ -247,11 +248,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.ts b/umtool/lib/pieces.ts @@ -13,6 +13,7 @@ import { lifecycleOf, readLifecycle, type LifecycleRead, type LifecycleState } f import { boardOfArticle, boardOfProject } from "./pieces/board.mjs"; import { readCases } from "./pieces/cases"; import { stageOfPiece } from "./pieces/tabs.mjs"; +import { kindById } from "./projects/kinds.mjs"; import type { Decision } from "./decisions"; export { articlePieceId, casePieceId, formatPieceId, isPieceId, parsePieceId, projectPieceId } from "./pieces/ids.mjs"; @@ -74,8 +75,14 @@ export type Piece = { * facet reads `reached` for it too. */ stage: string; + /** + * The stepper the piece walks (lib/pieces/tabs.mjs pieceSteps' `kind`): `article`, + * `project` (a report video's four stages), or the flow its project's kind + * declares (a song's Spec → Cuts → Done, lib/pieces/song-tabs.mjs). + */ + flow: string; /** What the piece has reached, the one stage rule's facts (lib/pieces/tabs.mjs pieceSteps). */ - reached: { research: boolean; article: boolean; video: boolean; deliver: boolean }; + reached: Reached; projects: PieceProject[]; /** Slug matches nobody has chosen between (link-ambiguous). */ possible: { id: string; title: string }[]; @@ -86,6 +93,17 @@ export type Piece = { newestMs: number; }; +/** The one stage rule's facts: the four stages, and a song's own three (lib/pieces/song-tabs.mjs). */ +export type Reached = { + research: boolean; + article: boolean; + video: boolean; + deliver: boolean; + spec?: boolean; + cuts?: boolean; + done?: boolean; +}; + export type PieceWithLifecycle = Piece & { lifecycle: LifecycleState; lifecycleAt: string | null; lifecycleBy: string | null }; export type PieceGraph = { @@ -292,6 +310,7 @@ async function buildGraph(): Promise<PieceGraph> { pieces.push({ id, kind: "article", + flow: "article", title: a.title, site: a.site, report: a.id, @@ -312,9 +331,14 @@ async function buildGraph(): Promise<PieceGraph> { for (const p of summaries) { if (pieceOfProject.has(p.id)) continue; const why = await looksDoneOf(p.id); + // The stepper the project's kind declares (a song's Spec → Cuts → Done) and + // the facts that light it; else a report video's four stages. + const declared = (kindById(p.kind) as { piece?: { flow: string; reached?: (s: ProjectSummary) => Promise<Partial<Reached>> } } | null)?.piece; + const own = declared?.reached ? await declared.reached(p).catch(() => ({})) : {}; pieces.push({ id: projectPieceId(p.id), kind: "project", + flow: declared?.flow ?? "project", title: p.title, site: null, report: null, @@ -323,7 +347,7 @@ async function buildGraph(): Promise<PieceGraph> { status: null, audience: null, stage: p.state, - reached: { research: !!boardOfProject(p.id, cases), article: false, video: true, deliver: !!why || p.state === "shipped" }, + reached: { research: !!boardOfProject(p.id, cases), article: false, video: true, deliver: !!why || p.state === "shipped", ...own }, projects: [], possible: [], unreachable: [], diff --git a/umtool/lib/pieces/frame.ts b/umtool/lib/pieces/frame.ts @@ -3,7 +3,9 @@ import { summarizeGroups } from "../inbox/groups.mjs"; import { whatOf } from "../inbox/what.mjs"; import { lifecycleOf, readLifecycle, type LifecycleState } from "../lifecycle"; import { projectPieceId, readPieceGraph, type Piece } from "../pieces"; -import { pieceSteps, stageOfPiece } from "./tabs.mjs"; +import { pieceSteps, stepOfPiece } from "./tabs.mjs"; +import { kindPieceFlow } from "../projects/kinds.mjs"; +import type { Reached } from "../pieces"; import { boardOfProject } from "./board.mjs"; import { readCases } from "./cases"; import type { Decision } from "../decisions"; @@ -37,7 +39,7 @@ export type PieceFrame = { steps: { label: string; state: StepState; title?: string }[]; /** The research board (R2 case) this project was scaffolded from, when a case's video hand-off names it. */ board: { id: string; title: string; at: string | null } | null; - /** The bucket the stepper lights (research … deliver). */ + /** The step the stepper has current (research … deliver; a song's spec, cuts or done). */ stage: string; }; @@ -48,7 +50,15 @@ async function boardOf(projectId: string): Promise<PieceFrame["board"]> { return boardOfProject(projectId, await readCases()); } -export async function readPieceFrame(project: { id: string; state?: string | null }): Promise<PieceFrame> { +/** + * @param project the project the page is + * @param opts.reached facts the page read fresh (a song page reads the song + * anyway), over the graph's memoised ones -- a promote shows at once + */ +export async function readPieceFrame( + project: { id: string; kind?: string; state?: string | null }, + opts: { reached?: Partial<Reached> } = {}, +): Promise<PieceFrame> { const [graph, life, board] = await Promise.all([readPieceGraph(), readLifecycle(), boardOf(project.id)]); const pieceId = graph.pieceOfProject.get(project.id) ?? projectPieceId(project.id); const piece = graph.byId.get(pieceId) ?? null; @@ -60,11 +70,14 @@ export async function readPieceFrame(project: { id: string; state?: string | nul : null; // The one stage rule (lib/pieces/tabs.mjs pieceSteps): the graph's facts, so // the stepper here and Work's stage facet read the same answer. - const kind = piece?.kind ?? "project"; + // The stepper is the piece's flow: an article's, a report video's, or the one + // its project's kind declares (a song's), also for a project the graph has + // not listed yet (one scaffolded within the memo's 15 s). + const kind = piece?.flow ?? (project.kind ? kindPieceFlow(project.kind) : null) ?? "project"; // The board is read fresh (the graph is memoised): a board's hand-off shows at once. - const reached = { ...(piece?.reached ?? { video: true }), ...(board ? { research: true } : {}) }; + const reached = { ...(piece?.reached ?? { video: true }), ...opts.reached, ...(board ? { research: true } : {}) }; const steps = pieceSteps({ kind, reached, lifecycle }) as PieceFrame["steps"]; - const stage = stageOfPiece({ kind, reached }); + const stage = stepOfPiece({ kind, reached }); return { piece, pieceId, article, board, lifecycle, lifecycleError: life.error ?? null, steps, stage }; } diff --git a/umtool/lib/pieces/song-tabs.mjs b/umtool/lib/pieces/song-tabs.mjs @@ -0,0 +1,149 @@ +// A SONG PIECE's tabs and stepper (plans/umtool-redesign.md, P4a-3). Pure, no +// imports, beside lib/pieces/tabs.mjs (the report video's and the article's): +// the page, Work's facet and an e2e spec (e2e/urls.ts `songSection`) read the +// same table. +// +// A song walks its own three stages, Spec → Cuts → Done, not the report's four. +// The registry declares which stepper a kind walks (lib/projects/kinds.mjs, the +// song kind's `piece.flow`), so nothing here branches on a kind id: the flow is +// a name the pieces graph copies onto the piece. +// +// The tab is the URL's `?tab=`, as on every piece page. A song's cut page +// (`/projects/<song>/<cut>`, the CutBench, its loudness and provenance) is a +// VIEW of the Cuts tab: the frame draws it with Cuts current. + +/** The stepper a kind declares to walk Spec → Cuts → Done. */ +export const SONG_FLOW = "song"; + +/** + * A song's three stages, each with the Work bucket (lib/work/facets.mjs STAGES) + * it stands in for, so Work's stage facet and the song's stepper agree: the + * spec is a song's written stage (a report video's article), its cuts its + * video, and a full set of cuts its delivery. + */ +export const SONG_STEPS = [ + { id: "spec", label: "Spec", bucket: "article" }, + { id: "cuts", label: "Cuts", bucket: "video" }, + { id: "done", label: "Done", bucket: "deliver" }, +]; + +const SKIPPED = { spec: "no spec.json", cuts: "no cut built" }; + +/** + * The song's stepper, by the one stage rule (lib/pieces/tabs.mjs pieceSteps): + * the furthest stage reached is current, the ones before it done (or to do with + * the reason, when skipped), a piece marked done has done them all. + * + * Spec reached with a spec.json + * Cuts reached with one cut built + * Done reached with every cut built (the song's derived `shipped`, which is + * also its looks-done suggestion, lib/pieces.ts) + * + * @param {{ reached: { spec?: boolean, cuts?: boolean, done?: boolean }, lifecycle: string }} p + * @returns {{ id: string, label: string, state: "done" | "current" | "todo", title?: string }[]} + */ +export function songSteps({ reached, lifecycle }) { + const has = reached ?? {}; + let at = 0; + SONG_STEPS.forEach((s, i) => { + if (has[s.id]) at = i; + }); + return SONG_STEPS.map((s, i) => { + if (lifecycle === "done") return { id: s.id, label: s.label, state: "done" }; + if (i === at) return { id: s.id, label: s.label, state: "current" }; + if (i < at && has[s.id]) return { id: s.id, label: s.label, state: "done" }; + if (i < at) return { id: s.id, label: s.label, state: "todo", title: SKIPPED[s.id] }; + return { id: s.id, label: s.label, state: "todo" }; + }); +} + +/** The song stage that is current (lifecycle aside): `spec`, `cuts` or `done`. */ +export function songStepOf({ reached }) { + return songSteps({ reached, lifecycle: "active" }).find((s) => s.state === "current")?.id ?? "spec"; +} + +/** The Work bucket a song stage stands in for. */ +export function bucketOfSongStep(step) { + return SONG_STEPS.find((s) => s.id === step)?.bucket ?? "video"; +} + +/** The tabs of a song piece, in order; the key that opens each is its position (`1`–`5`). */ +export const SONG_PIECE_TABS = [ + { id: "overview", label: "Overview" }, + { id: "cuts", label: "Cuts" }, + { id: "spec", label: "Spec" }, + { id: "cover", label: "Cover" }, + { id: "notes", label: "Notes" }, +]; + +export const SONG_PIECE_TAB_IDS = SONG_PIECE_TABS.map((t) => t.id); + +/** + * Every section the song page drew (components/projects/SongProject.tsx and + * CutPage.tsx before P4a-3), by the name a spec says, and the tab it is on. + */ +export const SONG_SECTION_TAB = { + // Overview: the Next card, the song's decisions, the cut set at a glance, + // the paste, the README, the song tools. + next: "overview", + decisions: "overview", + slots: "overview", + copy: "overview", + readme: "overview", + tools: "overview", + // Cuts: the four cut cards (poster, verdicts, notes, variants), what matches + // no cut, and a cut's own page (the bench, loudness, provenance). + cuts: "cuts", + variants: "cuts", + verdicts: "cuts", + unattributed: "cuts", + bench: "cuts", + loudness: "cuts", + provenance: "cuts", + // Spec: the spec sheet and its operations, the plans. + spec: "spec", + operations: "spec", + plans: "spec", + // Cover: the cover-art bench (and its way to the face judger). + cover: "cover", + thumbs: "cover", + faces: "cover", + // Notes: the note on the song as a whole, and every other note on it. + notes: "notes", +}; + +/** The tab a song section is on; throws on a name nobody declared (a spec's typo should fail loudly). */ +export function songTabOfSection(name) { + const tab = SONG_SECTION_TAB[name]; + if (!tab) throw new Error(`no section "${name}" on a song piece (lib/pieces/song-tabs.mjs SONG_SECTION_TAB)`); + return tab; +} + +/** + * Where a song note is drawn (lib/notes.ts: a song's notes are keyed by their + * TARGET): the song's own on Notes, a cut's, a file's, a mark's, a source's or + * a clip's with the cuts, a plan's on Spec, a cover's on Cover. + * + * @param {string | undefined | null} target + */ +export function songTabOfNote(target) { + const t = String(target ?? ""); + if (t === "song") return "notes"; + if (/^(cut|file|moment|source|clip):/.test(t)) return "cuts"; + if (t.startsWith("plan:")) return "spec"; + if (t.startsWith("thumb:")) return "cover"; + return "overview"; +} + +/** + * The tab a song piece's address opens: `?tab=`; else a `?note=<target>` where + * that note is drawn; else the Overview. + * + * @param {{ tab?: string, note?: string }} search + */ +export function songTabOf(search) { + const t = search?.tab; + if (t && SONG_PIECE_TAB_IDS.includes(t)) return t; + if (search?.note) return songTabOfNote(search.note); + return "overview"; +} diff --git a/umtool/lib/pieces/song-tabs.test.mjs b/umtool/lib/pieces/song-tabs.test.mjs @@ -0,0 +1,98 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + SONG_FLOW, + SONG_PIECE_TAB_IDS, + SONG_STEPS, + bucketOfSongStep, + songStepOf, + songSteps, + songTabOf, + songTabOfNote, + songTabOfSection, +} from "./song-tabs.mjs"; +import { STAGE_STEPS, pieceSteps, stageOfPiece, stepOfPiece } from "./tabs.mjs"; +import { STAGES, stageBar, stageOf } from "../work/facets.mjs"; + +const states = (steps) => steps.map((s) => s.state); + +test("a song piece: five tabs, Overview first; every section on one of them", () => { + assert.deepEqual(SONG_PIECE_TAB_IDS, ["overview", "cuts", "spec", "cover", "notes"]); + assert.equal(songTabOfSection("cuts"), "cuts"); + assert.equal(songTabOfSection("unattributed"), "cuts"); + assert.equal(songTabOfSection("bench"), "cuts"); + assert.equal(songTabOfSection("operations"), "spec"); + assert.equal(songTabOfSection("plans"), "spec"); + assert.equal(songTabOfSection("faces"), "cover"); + assert.equal(songTabOfSection("notes"), "notes"); + assert.equal(songTabOfSection("slots"), "overview"); + assert.equal(songTabOfSection("tools"), "overview"); + assert.throws(() => songTabOfSection("timeline"), /no section "timeline" on a song piece/); +}); + +test("a song piece's address picks the tab: ?tab=, else a note's target where it is drawn, else the Overview", () => { + assert.equal(songTabOf({}), "overview"); + assert.equal(songTabOf({ tab: "spec" }), "spec"); + assert.equal(songTabOf({ tab: "build" }), "overview"); + assert.equal(songTabOf({ tab: "cover", note: "song" }), "cover"); + assert.equal(songTabOf({ note: "song" }), "notes"); + for (const t of ["cut:vertical", "file:wide.mp4", "file:variants/wide-nokit.mp4", "moment:wide.mp4@2.00", "source:abc123", "clip:abc@1.5"]) { + assert.equal(songTabOfNote(t), "cuts", t); + assert.equal(songTabOf({ note: t }), "cuts", t); + } + assert.equal(songTabOf({ note: "plan:alpha.plan.json" }), "spec"); + assert.equal(songTabOf({ note: "thumb:alpha-1" }), "cover"); + assert.equal(songTabOf({ note: "n-1234" }), "overview"); +}); + +test("a song walks Spec → Cuts → Done by the one stage rule", () => { + assert.deepEqual(SONG_STEPS.map((s) => s.label), ["Spec", "Cuts", "Done"]); + // Scaffolded: a spec.json, no cut yet. + assert.deepEqual(states(songSteps({ reached: { spec: true }, lifecycle: "active" })), ["current", "todo", "todo"]); + // Nothing at all (a directory with only verdicts.json): the Spec is where it starts. + assert.deepEqual(states(songSteps({ reached: {}, lifecycle: "active" })), ["current", "todo", "todo"]); + // Some cuts built. + assert.deepEqual(states(songSteps({ reached: { spec: true, cuts: true }, lifecycle: "active" })), ["done", "current", "todo"]); + // Cuts with no spec.json: the Spec is to do, and says why. + const nospec = songSteps({ reached: { cuts: true }, lifecycle: "active" }); + assert.deepEqual(states(nospec), ["todo", "current", "todo"]); + assert.equal(nospec[0].title, "no spec.json"); + // Every cut built (the derived `shipped`): at Done -- a suggestion, not the lifecycle. + assert.deepEqual(states(songSteps({ reached: { spec: true, cuts: true, done: true }, lifecycle: "active" })), ["done", "done", "current"]); + // Marked done: every stage done. + assert.deepEqual(states(songSteps({ reached: { cuts: true }, lifecycle: "done" })), ["done", "done", "done"]); + // The shared rule switches on the flow the kind declares. + assert.deepEqual(pieceSteps({ kind: SONG_FLOW, reached: { spec: true, cuts: true }, lifecycle: "active" }).map((s) => s.id), ["spec", "cuts", "done"]); + // ...and the four-stage pieces are untouched by it. + assert.deepEqual(pieceSteps({ kind: "project", reached: { video: true }, lifecycle: "active" }).map((s) => s.id), STAGE_STEPS.map((s) => s.id)); +}); + +test("the song's stepper and Work's stage facet give the same answer", () => { + for (const reached of [ + { spec: true }, + { spec: true, cuts: true }, + { cuts: true }, + { spec: true, cuts: true, done: true }, + { research: false, article: false, video: true, deliver: true, spec: true, cuts: true, done: true }, + ]) { + const piece = { kind: SONG_FLOW, reached }; + const current = pieceSteps({ ...piece, lifecycle: "active" }).find((s) => s.state === "current").id; + assert.equal(songStepOf(piece), current); + assert.equal(stepOfPiece(piece), current); + // Work's bucket is the one the song's current step stands in for -- from the piece page's rule. + const bucket = stageOf({ kind: SONG_FLOW, stage: "built", looksDone: [], reached }); + assert.equal(bucket, bucketOfSongStep(current)); + assert.equal(stageOfPiece(piece), bucket); + assert.ok(STAGES.includes(bucket)); + // Work's bar is the song's own: three steps, the current one lit, its word. + const bar = stageBar(piece, bucket); + assert.equal(bar.steps, 3); + assert.equal(SONG_STEPS[bar.step - 1].id, current); + assert.equal(bar.label, SONG_STEPS[bar.step - 1].label.toLowerCase()); + } + assert.equal(stageOf({ kind: SONG_FLOW, stage: "draft", looksDone: [], reached: { spec: true } }), "article"); + assert.equal(stageOf({ kind: SONG_FLOW, stage: "built", looksDone: [], reached: { spec: true, cuts: true } }), "video"); + assert.equal(stageOf({ kind: SONG_FLOW, stage: "shipped", looksDone: ["x: every cut shipped"], reached: { cuts: true, done: true } }), "deliver"); + // A four-stage piece's bar is unchanged: four bars at its bucket, the caller's word. + assert.deepEqual(stageBar({ kind: "project", reached: { video: true } }, "video"), { step: 3, steps: 4, label: null }); +}); diff --git a/umtool/lib/pieces/tabs.mjs b/umtool/lib/pieces/tabs.mjs @@ -14,6 +14,12 @@ // answered that only make sense on one tab: `?all=1` (the cut's "show every // quote") opens the Cut, and `?note=<id>` opens the tab its anchor is drawn on // (a timeline row's note on the Cut, a timed note on the final video on Build). +// +// A SONG walks its own stepper and has its own tabs (lib/pieces/song-tabs.mjs, +// P4a-3); pieceSteps and stageOfPiece switch to it on the flow the registry +// declares, so the one stage rule stays one function. + +import { SONG_FLOW, bucketOfSongStep, songStepOf, songSteps } from "./song-tabs.mjs"; /** The stepper's four stages, by Work's buckets (lib/work/facets.mjs STAGES). */ export const STAGE_STEPS = [ @@ -45,10 +51,14 @@ export const STAGE_STEPS = [ * nor a board (a site's hand-written report) has no Research recorded here. A * piece marked done has done every stage that applies. * - * @param {{ kind: string, reached: { research?: boolean, article?: boolean, video?: boolean, deliver?: boolean }, lifecycle: string }} p + * A song (`kind` the flow its kind declares, SONG_FLOW) walks Spec → Cuts → + * Done by the same rule (lib/pieces/song-tabs.mjs songSteps). + * + * @param {{ kind: string, reached: { research?: boolean, article?: boolean, video?: boolean, deliver?: boolean, spec?: boolean, cuts?: boolean, done?: boolean }, lifecycle: string }} p * @returns {{ id: string, label: string, state: "done" | "current" | "todo" | "na", title?: string }[]} */ export function pieceSteps({ kind, reached, lifecycle }) { + if (kind === SONG_FLOW) return songSteps({ reached, lifecycle }); const project = kind !== "article"; const has = { ...reached, ...(project ? { video: true, article: false } : {}) }; const na = project @@ -74,14 +84,29 @@ export function pieceSteps({ kind, reached, lifecycle }) { /** * A piece's stage: the step that is current, by the one rule (lifecycle aside -- - * a parked or done piece keeps the stage it is at). + * a parked or done piece keeps the stage it is at). Always one of Work's four + * buckets: a song's stage is the bucket its step stands in for (Spec → article, + * Cuts → video, Done → deliver). * - * @param {{ kind: string, reached: { research?: boolean, article?: boolean, video?: boolean, deliver?: boolean } }} p + * @param {{ kind: string, reached: { research?: boolean, article?: boolean, video?: boolean, deliver?: boolean, spec?: boolean, cuts?: boolean, done?: boolean } }} p */ export function stageOfPiece({ kind, reached }) { + if (kind === SONG_FLOW) return bucketOfSongStep(songStepOf({ reached })); return pieceSteps({ kind, reached, lifecycle: "active" }).find((s) => s.state === "current")?.id ?? "video"; } +/** + * The step a piece's stepper has current, by its own ids (lifecycle aside): one + * of the four stages, or a song's `spec` / `cuts` / `done`. The piece page's + * `data-piece-stage`. + * + * @param {{ kind: string, reached: object }} p + */ +export function stepOfPiece({ kind, reached }) { + if (kind === SONG_FLOW) return songStepOf({ reached }); + return stageOfPiece({ kind, reached }); +} + /** The tabs of a report-video piece, in order; the key that opens each is its position. */ export const PIECE_TABS = [ { id: "overview", label: "Overview" }, @@ -114,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/projects/kinds.mjs b/umtool/lib/projects/kinds.mjs @@ -16,7 +16,8 @@ // rule, and it is what stops `if (kind === "report-video")` appearing in a page. import { BRAND_CHOICES } from "umtool-report-to-video/brand-ids"; import { MANIFEST_NAME, REPORT_DECISION_KINDS, reportDecisions, reportSignature, summariseReport } from "./report.mjs"; -import { CUT_NAMES, songSignature, summariseSong } from "./song.mjs"; +import { CUT_NAMES, songReached, songSignature, summariseSong } from "./song.mjs"; +import { SONG_FLOW } from "../pieces/song-tabs.mjs"; import { sweepSignature, summariseSweep } from "./sweep.mjs"; /** @@ -143,6 +144,10 @@ export const PROJECT_KINDS = [ // `/browse/<song>/wide` -- today's cut page, unchanged. views: CUT_NAMES, scaffold: { fields: [] }, + // Its piece walks Spec → Cuts → Done, not the report's four stages + // (lib/pieces/song-tabs.mjs, P4a-3): the flow its stepper and Work's stage + // facet read, and the facts that light it, from the project's summary. + piece: { flow: SONG_FLOW, reached: songReached }, }, { id: "sweep-report", @@ -194,6 +199,12 @@ export const kindById = (id) => PROJECT_KINDS.find((k) => k.id === id) ?? null; /** Does a project of this kind keep a notes.json (lib/annotations)? Declared on the kind, never branched on its id. */ export const kindTakesNotes = (id) => kindById(id)?.notes === true; +/** + * The stepper a project piece of this kind walks (lib/pieces/tabs.mjs + * pieceSteps): its declared `piece.flow`, else a report video's. + */ +export const kindPieceFlow = (id) => kindById(id)?.piece?.flow ?? null; + /** Can a project of this kind be an article's video (lib/articles/links.mjs)? Declared on the kind. */ export const kindLinksArticles = (id) => kindById(id)?.linksArticles === true; diff --git a/umtool/lib/projects/song.mjs b/umtool/lib/projects/song.mjs @@ -105,3 +105,15 @@ export async function summariseSong(ctx) { }; } +/** + * What a song piece has reached, for its Spec → Cuts → Done stepper + * (lib/pieces/song-tabs.mjs songSteps): a spec.json (one stat), a cut built, + * every cut built (the derived `shipped`). + * + * @param {{ dir: string, state?: string | null, attrs?: Record<string, string> }} p a song's summary + */ +export async function songReached(p) { + const spec = !!(await stat0(path.join(p.dir, "spec.json"))); + const built = Number(p.attrs?.cuts ?? 0); + return { spec, cuts: built > 0 || p.state === "built" || p.state === "shipped", done: p.state === "shipped" }; +} 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 }); + } +}); diff --git a/umtool/lib/work.ts b/umtool/lib/work.ts @@ -2,7 +2,7 @@ import { readInbox, type Inbox } from "./inbox"; import { readLifecycle } from "./lifecycle"; import { KINDS, listProjects } from "./projects"; import { listPieces, type PieceWithLifecycle } from "./pieces"; -import { stageOf, stepOf } from "./work/facets.mjs"; +import { stageBar, stageOf } from "./work/facets.mjs"; // --------------------------------------------------------------------------- // WORK, AS DATA: every piece (lib/pieces.ts) as one row for the Work list -- @@ -32,7 +32,9 @@ export type PieceCounts = { export type WorkRow = PieceWithLifecycle & { /** research | article | video | deliver. */ bucket: string; + /** The current step on the row's stage bar, 1-based, of `steps` (four, or a song's three). */ step: number; + steps: number; /** What the stage bar says: an article's stage, a project's own state. */ stageLabel: string; /** `article` and/or project kind ids. */ @@ -89,12 +91,15 @@ export async function readWork(): Promise<{ rows: WorkRow[]; lifecycleError?: st : "article" : (projectKinds.map((k) => label.get(k) ?? k).join(", ") || "project"); const projectState = own?.state ?? null; - const bucket = stageOf({ kind: p.kind, stage: p.stage, looksDone: p.looksDone, projectState, reached: p.reached }); + // The piece's flow, so a song's bucket is its own stepper's (Spec → Cuts → Done). + const bucket = stageOf({ kind: p.flow, stage: p.stage, looksDone: p.looksDone, projectState, reached: p.reached }); + const bar = stageBar({ kind: p.flow, reached: p.reached }, bucket); return { ...p, bucket, - step: stepOf(bucket), - stageLabel: p.kind === "article" ? bucket : (projectState ?? p.stage), + step: bar.step, + steps: bar.steps, + stageLabel: bar.label ?? (p.kind === "article" ? bucket : (projectState ?? p.stage)), kinds, kindLabel, templates: [...new Set(mine.map((x) => x.template))], diff --git a/umtool/lib/work/facets.mjs b/umtool/lib/work/facets.mjs @@ -16,7 +16,8 @@ // of every project linked to it, a project piece is its project's kind. So the // old `/browse?kind=<a video kind>` still finds the article whose video it is. -import { stageOfPiece } from "../pieces/tabs.mjs"; +import { pieceSteps, stageOfPiece } from "../pieces/tabs.mjs"; +import { SONG_FLOW } from "../pieces/song-tabs.mjs"; /** The four stages a piece walks, in order (canvas "Work", the stage bar). */ export const STAGES = ["research", "article", "video", "deliver"]; @@ -31,7 +32,10 @@ export const LIFECYCLES = ["active", "parked", "done"]; * article's own stage; a project's `deliver` when it looks done (or ships), * else `video`. * - * @param {{ kind: string, stage: string, looksDone: string[], projectState?: string | null, reached?: { research: boolean, article: boolean, video: boolean, deliver: boolean } }} p + * `kind` is the piece's flow (lib/pieces.ts `flow`): `article`, `project`, or + * a song's, whose bucket is the one its current step stands in for. + * + * @param {{ kind: string, stage: string, looksDone: string[], projectState?: string | null, reached?: { research: boolean, article: boolean, video: boolean, deliver: boolean, spec?: boolean, cuts?: boolean, done?: boolean } }} p */ export function stageOf(p) { if (p.reached) return stageOfPiece({ kind: p.kind, reached: p.reached }); @@ -43,6 +47,25 @@ export function stageOf(p) { /** 1-based position on the stage bar. */ export const stepOf = (bucket) => STAGES.indexOf(bucket) + 1; +/** + * A row's stage bar: how many steps it has, which is current, and its word. A + * piece on the four stages is its bucket on four bars; a song (P4a-3) is its + * own stepper, Spec → Cuts → Done, on three -- the same steps its page draws, + * while its bucket (`stageOf`) is the one Work's stage facet files it under. + * + * @param {{ kind: string, reached?: object }} p `kind` the piece's flow + * @param {string} bucket + * @returns {{ step: number, steps: number, label: string | null }} `label` null: the caller's own word + */ +export function stageBar(p, bucket) { + if (p.kind === SONG_FLOW && p.reached) { + const steps = pieceSteps({ kind: p.kind, reached: p.reached, lifecycle: "active" }); + const at = steps.findIndex((s) => s.state === "current"); + return { step: at + 1, steps: steps.length, label: steps[at]?.label.toLowerCase() ?? null }; + } + return { step: stepOf(bucket), steps: STAGES.length, label: null }; +} + /** `life`: one of the three, `all`, or (absent) active. */ export function lifeFilter(life) { if (life === "all") return null;