Archilyzer · Source

archilyzer

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

commit 31cedd281b29d7496825441766b24537b5b50d4f
parent c8924207e623e26416db1bf8f7754ae133735e8d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 18:58:03 -0400

Merge r32/review-player: the drafts review is a swipe deck (keep / cut / edit / skip, undo, the cited span's video autoplaying, the lit line, the next card preloaded), a shared citation player with Fetch clip, and Verify quotes / Check report on the article page

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

Diffstat:
Mcommon/bin/reports-check.test.ts | 15++++++++++++++-
Mcommon/bin/reports-check.ts | 149++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------
Meditor/CHANGELOG.md | 3+++
Mplans/FACTS.md | 32++++++++++++++++++++++++++++++++
Aplans/release-32/review-player.md | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/articles/checks/route.ts | 31+++++++++++++++++++++++++++++++
Aumtool/app/api/cited/fetch/route.ts | 28++++++++++++++++++++++++++++
Aumtool/app/api/cited/play/route.ts | 21+++++++++++++++++++++
Mumtool/app/api/report/drafts/route.ts | 20+++++++++++++++++++-
Aumtool/components/articles/ArticleChecks.tsx | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/articles/ArticlePage.tsx | 2++
Mumtool/components/articles/EvidencePanel.tsx | 82++++++++++++++++++++-----------------------------------------------------------
Aumtool/components/clips/CitedClip.tsx | 361+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/MediaDrafts.tsx | 26+++++++++++++++++++++++++-
Mumtool/components/projects/ProjectView.tsx | 2+-
Mumtool/components/projects/ReviewPage.tsx | 45+++++++++++++++++++++++++++++++++++++--------
Aumtool/components/projects/review/AuditionDeck.tsx | 775+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/bench-shell.spec.ts | 2+-
Mumtool/e2e/draft-review.spec.ts | 5++++-
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Aumtool/e2e/fixtures/review-player-fixture.mjs | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/review-player.spec.ts | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/running.spec.ts | 3+++
Mumtool/e2e/visual-audit.spec.ts | 2+-
Aumtool/lib/articles/checks.ts | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/articles/evidence.ts | 39+++++++++++----------------------------
Aumtool/lib/clips/cited.test.ts | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/clips/cited.ts | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/clips/types.ts | 36++++++++++++++++++++++++++++++++++++
Aumtool/lib/clips/words.test.ts | 41+++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/clips/words.ts | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/hrefs.ts | 4++--
Aumtool/lib/report/draftEdit.mjs | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/draftEdit.test.mjs | 30++++++++++++++++++++++++++++++
Mumtool/package.json | 2+-
35 files changed, 2495 insertions(+), 153 deletions(-)

diff --git a/common/bin/reports-check.test.ts b/common/bin/reports-check.test.ts @@ -27,7 +27,7 @@ Object.assign(process.env, { after(() => rmSync(ROOT, { recursive: true, force: true })); const { getPaths } = await import("../lib/paths"); -const { checkMain, verifyQuotesMain } = await import("./reports-check"); +const { checkMain, checkReports, verifyQuotesMain } = await import("./reports-check"); const { attachVideoMain } = await import("./reports-attach-video"); const { encodePlan, encodeArgs } = await import("../publish/reportVideo"); const { CHANNELS } = await import("../testing/draft/corpus.mjs"); @@ -160,6 +160,19 @@ test("check --reports checks a draft not in site.json: a drifted quote fails it" assert.match(c.text(), /quote-drift: draft1#c1: the quote matches \d+% of what the record says there/); }); +test("checkReports: the same findings as data, for a page (umtool's Check report)", async () => { + const failed = await checkReports({ siteId: "demo", paths, reports: ["draft1"], allowMissingMedia: true }); + assert.equal(failed.status, "fail"); + const p = failed.status === "fail" ? failed.problems.find((x) => x.kind === "quote-drift") : undefined; + assert.equal(p?.where, "draft1#c1"); + assert.equal(p?.citation, "draft1#c1"); + assert.match(p?.line ?? "", /^quote-drift: draft1#c1: /); + const passed = await checkReports({ siteId: "demo", paths, allowMissingMedia: true }); + assert.equal(passed.status, "pass"); + assert.deepEqual(passed.status === "pass" ? passed.reports.find((r) => r.id === "pub1") : null, { id: "pub1", quotes: 1, lowest: 1 }); + assert.equal((await checkReports({ siteId: "nope", paths })).status, "usage"); +}); + test("check: an unknown site is a usage error", async () => { const c = capture(); assert.equal(await checkMain({ siteId: "nope", paths }, c.out), 2); diff --git a/common/bin/reports-check.ts b/common/bin/reports-check.ts @@ -59,6 +59,7 @@ import { import { fragmentOf, fullSentenceFor, type FragmentFinding } from "../lib/citations/fragment"; import { ComposeReportsError, + type ComposeReportsProblem, checkSpanQuote, formatComposeReportsProblems, quoteDriftMessage, @@ -72,18 +73,59 @@ type Out = { log: (s: string) => void; error: (s: string) => void }; // ─── reports check ─── -export async function checkMain( - opts: { - // The site, or `article` — one article id. - siteId?: string; - article?: string; - reports?: string[]; - allowMissingMedia?: boolean; - paths?: Paths; - settings?: { social?: { x?: { visibility?: unknown } } }; - }, - out: Out = console, -): Promise<number> { +// One compose problem, for a page that lists them (umtool's Check report): +// where it is and what it says, and the CLI's own line. +export type ReportsCheckProblem = { + kind: string; + where: string; + message: string; + report?: string; + citation?: string; + line: string; +}; + +// What `reports check` found, before it is printed: the CLI prints it +// (checkMain), umtool's article page draws it (release 32 R1). +export type ReportsCheckResult = + // An unknown site or article: exit 2. + | { status: "usage"; who: string; error: string } + // Nothing published to check: exit 0. + | { status: "empty"; who: string } + | { + status: "pass"; + who: string; + // Media problems let through by --allow-missing-media. + allowed: string[]; + // A gone source's moment: its words only. + warnings: string[]; + reports: { id: string; quotes: number; lowest: number | null }[]; + moments: number; + } + | { status: "fail"; who: string; problems: ReportsCheckProblem[] } + // Anything else that stopped the check: exit 1. + | { status: "error"; who: string; error: string }; + +const problemOf = (p: ComposeReportsProblem): ReportsCheckProblem => { + const line = formatComposeReportsProblems([p])[0]; + return { + kind: p.kind, + where: p.citation ?? p.moment ?? `${p.report ?? "?"}${p.path ? ` at ${p.path}` : ""}`, + message: p.message, + ...(p.report ? { report: p.report } : {}), + ...(p.citation ? { citation: p.citation } : {}), + line, + }; +}; + +export async function checkReports(opts: { + // The site, or `article` — one article id. + siteId?: string; + article?: string; + reports?: string[]; + allowMissingMedia?: boolean; + paths?: Paths; + settings?: { social?: { x?: { visibility?: unknown } } }; +}): Promise<ReportsCheckResult> { const paths = opts.paths ?? getPaths(); const who = opts.article ? `--article ${opts.article}` : String(opts.siteId); let host: ReportHost; @@ -91,22 +133,17 @@ export async function checkMain( try { host = await articlesWorkHost(paths, [opts.article]); } catch (err) { - out.error(`reports check: ${(err as Error).message}`); - return 2; + return { status: "usage", who, error: (err as Error).message }; } host = { ...host, published: [opts.article] }; } else { if (!opts.siteId || !listSiteIds(paths).includes(opts.siteId)) { - out.error(`reports check: no site "${opts.siteId}" (sites/${opts.siteId}/site.json)`); - return 2; + return { status: "usage", who, error: `no site "${opts.siteId}" (sites/${opts.siteId}/site.json)` }; } const site = getSite(opts.siteId, paths); host = siteReportHost(paths, { ...site, pages: opts.reports ?? site.pages ?? [] }); } - if (host.published.length === 0) { - out.log(`reports check ${who}: the site publishes no reports — nothing to check.`); - return 0; - } + if (host.published.length === 0) return { status: "empty", who }; try { const resolved = await resolveReports({ paths, @@ -114,34 +151,54 @@ export async function checkMain( allowMissingMedia: opts.allowMissingMedia === true, ...(opts.settings ? { settings: opts.settings } : {}), }); - for (const line of formatComposeReportsProblems(resolved.allowed)) { - out.log(` allowed (--allow-missing-media): ${line}`); - } - // A gone source's moment with no media is a warning: its words only. - for (const g of resolved.sourceGone) { - out.log(` warning: ${g.moment}: ${SOURCE_GONE_LABELS[g.state].toLowerCase()} — its words only (cited by ${g.citations.join(", ")})`); - } - for (const r of resolved.reports) { - const scores = Object.values(r.citations ?? {}) - .map((c) => (c.kind === "video" || c.kind === "audio" || c.kind === "post" ? c.verification?.quoteScore : undefined)) - .filter((s): s is number => typeof s === "number"); - const low = scores.length ? Math.min(...scores) : null; - out.log( - ` ${r.id}: ${scores.length} quote(s) checked` + (low === null ? "" : `, lowest ${low.toFixed(2)}`), - ); - } - out.log( - `reports check ${who}: ${resolved.reports.length} report(s), ${resolved.moments.length} moment(s) — compose would pass.`, - ); - return 0; + return { + status: "pass", + who, + allowed: formatComposeReportsProblems(resolved.allowed), + warnings: resolved.sourceGone.map( + (g) => `${g.moment}: ${SOURCE_GONE_LABELS[g.state].toLowerCase()} — its words only (cited by ${g.citations.join(", ")})`, + ), + reports: resolved.reports.map((r) => { + const scores = Object.values(r.citations ?? {}) + .map((c) => (c.kind === "video" || c.kind === "audio" || c.kind === "post" ? c.verification?.quoteScore : undefined)) + .filter((s): s is number => typeof s === "number"); + return { id: r.id, quotes: scores.length, lowest: scores.length ? Math.min(...scores) : null }; + }), + moments: resolved.moments.length, + }; } catch (err) { - if (!(err instanceof ComposeReportsError)) { - out.error(`reports check ${who}: ${(err as Error).message}`); + if (!(err instanceof ComposeReportsError)) return { status: "error", who, error: (err as Error).message }; + return { status: "fail", who, problems: err.problems.map(problemOf) }; + } +} + +export async function checkMain( + opts: Parameters<typeof checkReports>[0], + out: Out = console, +): Promise<number> { + const r = await checkReports(opts); + switch (r.status) { + case "usage": + out.error(`reports check: ${r.error}`); + return 2; + case "empty": + out.log(`reports check ${r.who}: the site publishes no reports — nothing to check.`); + return 0; + case "error": + out.error(`reports check ${r.who}: ${r.error}`); return 1; - } - out.error(`reports check ${who}: ${err.problems.length} problem(s) — compose would fail:`); - for (const line of formatComposeReportsProblems(err.problems)) out.error(` ${line}`); - return 1; + case "fail": + out.error(`reports check ${r.who}: ${r.problems.length} problem(s) — compose would fail:`); + for (const p of r.problems) out.error(` ${p.line}`); + return 1; + case "pass": + for (const line of r.allowed) out.log(` allowed (--allow-missing-media): ${line}`); + for (const w of r.warnings) out.log(` warning: ${w}`); + for (const rep of r.reports) { + out.log(` ${rep.id}: ${rep.quotes} quote(s) checked` + (rep.lowest === null ? "" : `, lowest ${rep.lowest.toFixed(2)}`)); + } + out.log(`reports check ${r.who}: ${r.reports.length} report(s), ${r.moments} moment(s) — compose would pass.`); + return 0; } } diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,9 @@ # Changelog ## [Unreleased] +- **umtool's drafts review is an audition deck: hear the cited moment, then keep it or cut it.** `/projects/<project>/review` shows one card per drafted field still waiting for a verdict: the drafted value large, the cited span of its clip playing (video when a window or saved video holds it, else audio marked "audio only"), and the quote under it lighting word by word as it is spoken. Swipe right, → or `k` keeps it (approves); left, ← or `x` cuts it (rejects — tap a reason chip or write a few words, never required); up, ↑ or `e` edits it on the card (on-screen text, narration, teaser lines and the YouTube title; Enter keeps it as edited); down, ↓ or `s` skips it to the back; space replays the span; `z` undoes the last keep, cut or skip. Tap a word to mark it misheard: the note says so. Every action is also a button (a bar under the thumb on a phone). The next card's media is already loading, and the deck ends with what was cut and skipped. Verdicts are the same `drafts.review.json` as before; **List** (`?view=list`) is the old list, whose reader now plays the span too. No model is needed for any of it. +- **Fetch clip wherever a citation is shown in umtool.** When nothing on disk holds a cited span — on the deck, in the list's reader, on an article's evidence panel and its evidence walk — **Fetch clip** asks the editor for those seconds exactly as the MCP's `fetch_clip` does, shows its progress, and plays the window when it lands. A rate limit says the platform is rate-limiting; a window the audio check refused says the source served corrupt audio. The evidence panel plays video first and has **Play span** (from the span's start to its end). +- **Verify quotes and Check report on an article's page.** The Article tab has **Verify quotes** (what `archilyzer reports verify-quotes --article <id>` prints: each quote's status — ok, fragment, inexact, drift, en-orig-drift — its score and track, with **Play** to hear it) and **Check report** (what `archilyzer reports check --article <id>` says: compose would pass, or each problem in its own sentence, with **Play** where it names a citation; **allow missing media** as `--allow-missing-media`). The article's respellings apply. Needs a restart of umtool. - **Every feature runs in Docker, and the whole stack runs as a service.** `pnpm archilyzer service install` installs Archilyzer as systemd user units and starts it — in Docker (one `archilyzer.service` running `docker compose up`, the default when Docker is present) or on the host (`--mode host`: `archilyzer-editor.service`, `archilyzer-umtool.service`, and `--sites <id>:<port>` for a private site's server). `service status` shows each unit, its build, its port's answer and whether the transcription lane is held; `service logs`, `service restart` and `service uninstall` do what they say; `--dry-run` prints the units and writes nothing, and units you already have under those names are adopted when identical and shown as a diff when not (`--force` replaces them). In Docker, umtool now renders report videos (its own image carries ImageMagick 7, chromium and hyperframes), the image carries gallery-dl, headless Chromium and espeak-ng, `--profile ollama` runs local models, and overlays mount the Claude API key file, your Firefox cookies and every media drive (`archilyzer service storage-overlay` writes that one). RUNNING_IN_DOCKER.md has a feature-by-install table. - **A cookies.txt works wherever a browser's cookies do.** Set cookies-from-browser (in Settings or on a channel) to `file:/path/to/cookies.txt` and yt-dlp and gallery-dl are handed `--cookies <path>` — for a container, or a machine whose browser store cannot be read. - **A fresh install's dashboard says what to do first.** With no channel yet, **First steps** lists adding a channel, whether a transcription worker has its model, syncing and transcribing, and publishing — each with what this install already has. diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9954,6 +9954,38 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri records refreshes are armed by a preview of the same settings; the playable copy (lossless, keyed by the source's sha256) is not. + +## Release 32 lane R1: the cited clip, the audition deck, the article's checks (verified 2026-10-16, branch `r32/review-player`) + +- **What plays a cited span** is `umtool/lib/clips/cited.ts` `findCitedPlay(target)`: a project clip's own cached + window first (`/api/report/raw?project&clip&file`, when the target names `project`+`clip`), then the corpus's + (`corpusPlay`: clip window → saved video → audio, through `resolveEvidenceSource`). `lib/articles/evidence.ts`'s + corpus step is `corpusPlay` (one implementation); the site's PREPARED clip still comes first there. + A target's `channel`/`video` are the corpus's DIRECTORIES — a Rumble entry's local dir is the manifest's `video`, + never `siteVideo`. The review's span is `cutStart`/`cutEnd` when the entry has both, else `start`/`end`. +- **`GET /api/cited/play?channel&video&from&to[&project&clip][&audio=1]`** → `{ play, fetchLine }`; + **`POST /api/cited/fetch`** `{channel, video, from, to, reason, report?, project?, clip?}` or `{job, …span}` → + `{state: "ready", cached, play}` | `{state: "queued", job, status}` | `{state: "failed", message, detail?}`. It calls + the MCP's `fetchClip` directly (`requestedBy: "umtool"`, default pad 3, `wait_seconds: 0`) with no research-source + lookup: the corpus's directories are the editor's. `message` is `lib/clips/words.ts` `fetchFailureSentence` (a 429 / + cooldown → "<platform> is rate-limiting fetches", the audio check's "malformed" → "corrupt audio"), `detail` the + editor's own words. +- **The drafts route's `edit` action** (`/api/report/drafts`, `{address, text, note?, token?}`): the text becomes the + field's value through `lib/report/draftEdit.mjs` `valueFromEdit` (onscreen: line 1 title, the rest subtitle; + narration: the text, other keys kept; lines: one per line, an object line keeps its keys; publish.youtube: line 1 + the title) and is written by `writeDraftedField` (the operator's after, as `use`); a field that still has a review + row after the write (a narration) is approved on its new words. Other fields refuse ("edited in its own section"). +- **`/projects/<id>/review` is the audition deck; `?view=list` is the list** (`reviewHref(p, {view: "list"})`). The + deck's CUT writes the chosen reason, else the note "cut on the deck" (the writer still requires a rejection note); + marked words append "misheard: <words>" to the note. Undo covers keep, cut and skip (20 deep), not an edit (History). + A mishearing's "fix this mishearing" link is the article's Iterations tab, `?tab=iterations&heard=<words>` + (URL-encoded) — R2's "Fix a mishearing" form reads `heard` there and prefills Heard. +- **`checkReports(opts)`** (common/bin/reports-check.ts) is `reports check` as data — `usage | empty | pass | fail | + error`, each fail's problems `{kind, where, message, report?, citation?, line}`; `checkMain` only prints it. + umtool's `lib/articles/checks.ts` runs it and `verifyReportQuotes` in-process over `sitesPaths()` (the store's + article: `--article`; a site's report: `siteId` + `reports: [id]`); `POST /api/articles/checks {site, report, what: + "quotes" | "check", allowMissingMedia?}`. + ## Release 32 lane R2: by hand, no model (verified 2026-10-16, branch `r32/by-hand`) - **Iteration kind `hand`** (`lib/report/iterations.ts` ITERATION_KINDS): written by a person, model `"hand"`, usage diff --git a/plans/release-32/review-player.md b/plans/release-32/review-player.md @@ -0,0 +1,82 @@ +# Release 32 lane R1 — verify by playing the citation: the cited clip, the audition deck, the article's checks (as shipped) + +Operator asks (2026-10-16): "can we not play the citation audio in the umtool review screen? We should be able to play +the video, even, to verify it — that's the only point it should need to hit a human"; then, for the drafts review, +"similarly to a mobile app like Tinder … move fast when auditing clips … the perfect mix of AI heavy lifting with a +human auditing ear". The release rule: every step a model can do, a person can do in the UI; verification needs no +model. Rulings followed: the drafts review becomes a one-card deck (keep → / cut ← / edit ↑ / skip ↓, undo z, space +replays), the list one toggle away; decisions through the existing `drafts.review.json` writer; the CLI's +`verify-quotes --article` and `check --article` as buttons running the same functions in-process. + +## What + +- **The cited clip** (`components/clips/CitedClip.tsx`, `lib/clips/cited.ts`): a span plays VIDEO first (a project's + cached window, a corpus clip window, a saved video), else audio labelled "audio only"; **Play span** plays from the + span's start and stops at its end; with nothing on disk, **Fetch clip** asks the editor's fetch-window exactly as + the MCP's `fetch_clip` does (`requestedBy: "umtool"`), polls, and plays what lands; a failure is said plainly (a + rate limit; corrupt audio from the audio check). Two faces: `panel` (native controls) and `card` (no chrome, tap + replays, a span-only scrubber). Its buttons never take focus and the media gives focus back, so a page's keys keep + working. Mounted in the evidence panel (so the article reader and the evidence walk get video-first and Fetch clip; + the walk's space plays the span) and in the drafts list's reader. +- **The audition deck** (`components/projects/review/AuditionDeck.tsx`), the default of `/projects/<id>/review`: one + card per field awaiting review — the drafted value (Archivo, large), the span autoplaying after the first "Start + review" gesture, the LIT LINE (the quote in the reader serif, each word underlined in Signal as playback reaches + it; `lib/clips/words.ts` `spokenWords` spreads each cue's words over its span and finds the quote's words in + order), the source and "drafted by". Swipe (30 % of the width or a 0.6 px/ms flick), key or button: KEEP approves, + CUT rejects (a reason chip or a few words, else "cut on the deck"), EDIT rewrites on-screen text / narration / + teaser lines / the YouTube title on the card (Enter keeps it as edited; other fields link the Media tab), SKIP goes + to the back, z undoes keep/cut/skip (20 deep). Tapping a word marks it misheard ("misheard: …" in the note; on Edit + a "fix this mishearing" link to the article's Iterations tab with `heard=`, where R2's form prefills it). The next card is rendered underneath with its + media preloading; the card after the next has its play lookup warmed. The decided card flies out as a picture + (160 ms; 80 ms fade with reduced motion) so no key is lost to the animation. Counter `n / N · k kept · c cut · s + skipped`; the end is a summary listing cut and skipped, "Review the skipped ones", "Review the cut ones again", + "Back to the Media tab". `?view=list` is the list (j/k, a, r), its reader now with the player. +- **The drafts route's `edit` action** (`lib/report/draftEdit.mjs`): text → value, written through + `writeDraftedField` as the operator's; a field still under review after the write (a narration) is approved. +- **Verify quotes / Check report** on the article page (`components/articles/ArticleChecks.tsx`, mounted with one line + in `ArticlePage.tsx`'s article line; `lib/articles/checks.ts`; `POST /api/articles/checks`): per quote its status, + score, track, en-orig score, message and a **Play**; check's pass/fail summary, allowed and warning lines, each + problem with its sentence and a **Play** where it names a citation; "allow missing media". In-process, no model. +- **common:** `checkReports` (reports-check.ts) returns `reports check`'s findings as data; `checkMain` prints it, + byte-for-byte as before. + +## Files + +common: `bin/reports-check.ts`, `bin/reports-check.test.ts`. umtool: `lib/clips/{types.ts, cited.ts, words.ts, +cited.test.ts, words.test.ts}`, `app/api/cited/{play,fetch}/route.ts`, `components/clips/CitedClip.tsx`, +`components/articles/{EvidencePanel.tsx, ArticleChecks.tsx, ArticlePage.tsx}`, `lib/articles/{evidence.ts, +checks.ts}`, `app/api/articles/checks/route.ts`, `components/projects/{ReviewPage.tsx, MediaDrafts.tsx, +ProjectView.tsx, review/AuditionDeck.tsx}`, `app/api/report/drafts/route.ts`, `lib/report/{draftEdit.mjs, +draftEdit.test.mjs}`, `lib/hrefs.ts` (`reviewHref(p, {view})`), `package.json` (test glob `lib/clips/*.test.ts`); +e2e `review-player.spec.ts`, `fixtures/review-player-fixture.mjs` (+ registered in make-fixture.mjs), and +`draft-review`, `bench-shell`, `running`, `visual-audit` specs opening `?view=list`. FACTS.md, CHANGELOG. + +## Interfaces + +- `GET /api/cited/play?channel&video&from&to[&project&clip][&audio=1]` → `{play: CitedPlay | null, fetchLine}`. +- `POST /api/cited/fetch` `{channel, video, from, to, reason?, report?, project?, clip?}` | `{job, …span}` → + `{state: "ready", cached, play} | {state: "queued", job, status} | {state: "failed", message, detail?, job?}`. +- `POST /api/report/drafts` `{project, action: "edit", address, text, note?, token?}`. +- `POST /api/articles/checks` `{site, report, what: "quotes" | "check", allowMissingMedia?}`. +- `checkReports(opts): Promise<ReportsCheckResult>` (common/bin/reports-check.ts). +- `/projects/<id>/review?view=list`; the deck links the article's Iterations tab with `?tab=iterations&heard=<words>` + for R2's "Fix a mishearing" form. + +## Gates + +tsc clean (all packages) before each commit and after merging `main` 45c5a583; umtool unit 42 (was 33: +6 words, ++3 cited); common 4456 tests, 4455 pass, 1 skip (after the merge; +1 `checkReports`); test:scripts 1049, 1046 pass, +3 skip (+4 draftEdit; the umtool build-trace test ran and passed); umtool `next build` with the corpus linked: +clean. After the merge: review-player + draft-review 5/5. e2e (umtool, single specs, fixture run): review-player 2/2; +draft-review + bench-shell 9/9; running + article-evidence 7/7; visual-audit + review-player 67/67. Screenshots of the +deck at 390 and 1366 px and of the checks: `$T/shots/r32r1-*.png`. + +## Decisions + +- Word timing spreads each cue's words evenly over the cue (no transcript shape in the corpus carries word offsets; + a parakeet `transcript.json` has chunk times only); fewer than half the quote's words found → even spread. +- The writer still requires a rejection note; the deck writes the chosen reason or "cut on the deck". +- An edit is not undone with z (it is a manifest write with a snapshot; the History tab restores it). +- A field without a clip has no "cited moments" chips: nothing links such a field (YouTube text, a social post) to + moments today. +- Mishearing marks are kept in the session and written into the verdict's note, not a new file. diff --git a/umtool/app/api/articles/checks/route.ts b/umtool/app/api/articles/checks/route.ts @@ -0,0 +1,31 @@ +import { articleQuoteChecks, articleReportCheck } from "@/lib/articles/checks"; +import { isReportHost } from "@/lib/articles/sites"; + +export const dynamic = "force-dynamic"; + +// POST { site, report, what: "quotes" | "check", allowMissingMedia? } +// quotes -> every video, audio and post quote against its record (the CLI's +// `reports verify-quotes --article`): status, score, track, the +// en-orig score, and what plays it +// check -> compose's own findings with nothing written (`reports check +// --article`, a site's `--reports <id>`): pass, or every problem +// lib/articles/checks.ts; read-only, no model. +export async function POST(request: Request) { + const b = (await request.json().catch(() => null)) as Record<string, unknown> | null; + const site = String(b?.site ?? ""); + const report = String(b?.report ?? ""); + if (!isReportHost(site)) return Response.json({ error: `no site ${site}` }, { status: 404 }); + if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(report)) return Response.json({ error: "report must be a report id" }, { status: 400 }); + try { + const body = + b?.what === "check" + ? await articleReportCheck(site, report, { allowMissingMedia: b?.allowMissingMedia === true }) + : b?.what === "quotes" + ? await articleQuoteChecks(site, report) + : null; + if (!body) return Response.json({ error: "what must be quotes or check" }, { status: 400 }); + return Response.json(body, { headers: { "cache-control": "no-store" } }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: (e as { status?: number })?.status ?? 500 }); + } +} diff --git a/umtool/app/api/cited/fetch/route.ts b/umtool/app/api/cited/fetch/route.ts @@ -0,0 +1,28 @@ +import { fetchCitedClip, targetOf } from "@/lib/clips/cited"; +import { SourceError } from "@/lib/research/sources"; +import { fail, ok } from "../../research/_respond"; + +export const dynamic = "force-dynamic"; + +// POST { channel, video, from, to, project?, clip?, reason, report? } +// | { job, channel?, video?, from?, to?, … } (a poll) +// -> { state: "ready", cached, play } | { state: "queued", job, status } +// | { state: "failed", message, detail?, job? } +// +// Fetch clip, from the player (lib/clips/cited.ts): the editor's fetch-window +// route exactly as fetch_clip asks for it, never yt-dlp, never waiting. A poll +// that names its span answers ready with what plays now. +export async function POST(request: Request) { + try { + const b = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!b) throw new SourceError("expected a JSON body"); + const target = typeof b.channel === "string" && b.channel ? targetOf((k) => b[k]) : undefined; + if (typeof b.job === "string" && b.job.trim()) return ok(await fetchCitedClip({ job: b.job.trim(), ...(target ? { target } : {}) })); + if (!target) throw new SourceError("channel, video, from and to are required"); + const reason = String(b.reason ?? "").trim().slice(0, 400) || "umtool: play the cited span"; + const report = typeof b.report === "string" && b.report.trim() ? b.report.trim() : undefined; + return ok(await fetchCitedClip({ target, reason, ...(report ? { report } : {}) })); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/cited/play/route.ts b/umtool/app/api/cited/play/route.ts @@ -0,0 +1,21 @@ +import { fetchClipLine } from "@/lib/articles/evidence"; +import { findCitedPlay, targetOf } from "@/lib/clips/cited"; +import { fail, ok } from "../../research/_respond"; + +export const dynamic = "force-dynamic"; + +// GET ?channel&video&from&to[&project&clip][&audio=1] +// -> { play: CitedPlay | null, fetchLine } +// +// What plays a cited span now (lib/clips/cited.ts): a project's cached +// window, a corpus clip window, a saved video, or audio -- found, never +// fetched. `fetchLine` is the MCP line for the same seconds. +export async function GET(request: Request) { + try { + const url = new URL(request.url); + const t = targetOf((k) => url.searchParams.get(k)); + return ok({ play: await findCitedPlay(t), fetchLine: fetchClipLine({ channel: t.channel, id: t.video, start: t.from, end: t.to }, url.searchParams.get("reason") || "umtool review") }); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/report/drafts/route.ts b/umtool/app/api/report/drafts/route.ts @@ -2,6 +2,8 @@ import { invalidateProjects } from "@/lib/projects"; import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, StructureRefused, manifestToken, writeDraftedField } from "@/lib/report/manifest.mjs"; import { alternativeById, draftsView } from "@/lib/report/drafts.mjs"; +import { currentFieldValue, valueFromEdit } from "@/lib/report/draftEdit.mjs"; +import { readManifest } from "@/lib/projects/report.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; import { draftsReviewRows, readDraftsReview, setDraftReview } from "umtool-report-to-video/drafts-review"; @@ -19,6 +21,11 @@ export const dynamic = "force-dynamic"; // use { alternative, token? } "Use this": the alternative (`<file>#<i>`) written // through the manifest writer as the operator's edit // (snapshot, validators, the edit-notes guard) +// edit { address, text, note?, token? } the audition deck's EDIT (release 32 R1): the +// field rewritten as text (lib/report/draftEdit.mjs), +// written the same way as `use` -- the operator's +// now -- and approved on its new words when the +// field still has a review row // // Verdicts live in <project>/drafts.review.json (report-to-video's // drafts-review.mjs); a final build refuses a drafted field not approved. @@ -58,6 +65,17 @@ export async function POST(request: Request) { const row = draftsReviewRows(r.manifest, await readDraftsReview(dir)).find((x: { address: string }) => x.address === address); if (!row) return Response.json({ error: `${address || "(no address)"} is not a field this cut has to review` }, { status: 404 }); switch (body.action) { + case "edit": { + const value = valueFromEdit(row.field, currentFieldValue(r.manifest, row), String(body.text ?? "")); + const token = typeof body.token === "string" ? body.token : null; + const w = await withEditNotes(r.project, () => writeDraftedField(dir, { entry: row.entry, field: row.field, value }, { token })); + editNotes = w.editNotes; + invalidateProjects(); + // A field the edit leaves under review (a narration) is approved on its new words. + const after = draftsReviewRows((await readManifest(dir)) ?? r.manifest, await readDraftsReview(dir)).find((x: { address: string }) => x.address === address); + if (after) await setDraftReview(dir, address, { verdict: "approved", key: after.key, text: after.text, ...(note !== undefined ? { note } : {}) }); + break; + } case "approve": await setDraftReview(dir, address, { verdict: "approved", key: row.key, text: row.text, ...(note !== undefined ? { note } : {}) }); break; @@ -71,7 +89,7 @@ export async function POST(request: Request) { await setDraftReview(dir, address, { note: note ?? "" }); break; default: - return Response.json({ error: "action must be approve, reject, clear, note or use" }, { status: 400 }); + return Response.json({ error: "action must be approve, reject, clear, note, edit or use" }, { status: 400 }); } } } catch (e) { diff --git a/umtool/components/articles/ArticleChecks.tsx b/umtool/components/articles/ArticleChecks.tsx @@ -0,0 +1,136 @@ +"use client"; + +import { useState } from "react"; +import CitedClip from "@/components/clips/CitedClip"; +import { buttonVariants } from "@/components/ui/button"; +import type { QuoteChecks, ReportCheck } from "@/lib/articles/checks"; +import type { CitedTarget } from "@/lib/clips/types"; +import { cn } from "@/lib/utils"; + +// VERIFY QUOTES and CHECK REPORT (release 32 R1): the CLI's `reports +// verify-quotes --article` and `reports check --article`, as two buttons on +// the article page (lib/articles/checks.ts runs the same functions). Every +// quote's status, score and track, every problem in its own sentence -- and a +// Play beside each, so the person rules by ear. No model. + +const WARN = new Set(["inexact", "fragment"]); +const tone = (status: string) => + status === "ok" || status === "pass" ? "text-meter" : WARN.has(status) ? "text-doubt-text" : "text-reject-text"; + +function Play({ target, why }: { target: CitedTarget; why: string }) { + const [open, setOpen] = useState(false); + return open ? ( + <CitedClip target={target} reason={why} autoPlay className="mt-1 max-w-[520px]" /> + ) : ( + <button type="button" data-check-play="" onClick={() => setOpen(true)} className={buttonVariants({ variant: "outline", size: "sm" })}> + Play + </button> + ); +} + +export default function ArticleChecks({ site, report }: { site: string; report: string }) { + const [busy, setBusy] = useState<null | "quotes" | "check">(null); + const [result, setResult] = useState<QuoteChecks | ReportCheck | null>(null); + const [error, setError] = useState<string | null>(null); + const [allowMissing, setAllowMissing] = useState(false); + + const run = async (what: "quotes" | "check") => { + setBusy(what); + setError(null); + try { + const r = await fetch("/api/articles/checks", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ site, report, what, allowMissingMedia: allowMissing }), + cache: "no-store", + }); + const j = await r.json(); + if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`); + setResult(j); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(null); + } + }; + + return ( + <div data-article-checks="" className="flex w-full flex-wrap items-center gap-2"> + <button type="button" data-check="quotes" disabled={!!busy} onClick={() => void run("quotes")} className={buttonVariants({ variant: "outline", size: "sm" })}> + {busy === "quotes" ? "Verifying…" : "Verify quotes"} + </button> + <button type="button" data-check="check" disabled={!!busy} onClick={() => void run("check")} className={buttonVariants({ variant: "outline", size: "sm" })}> + {busy === "check" ? "Checking…" : "Check report"} + </button> + <label className="flex items-center gap-1 text-[11.5px] text-muted" title="let a citation without prepared media through, as --allow-missing-media does"> + <input type="checkbox" checked={allowMissing} onChange={(e) => setAllowMissing(e.target.checked)} /> + allow missing media + </label> + {result && ( + <button type="button" onClick={() => setResult(null)} className={buttonVariants({ variant: "ghost", size: "sm" })}> + Close + </button> + )} + {error && ( + <span role="alert" className="basis-full text-[12px] text-reject-text"> + {error} + </span> + )} + {result?.what === "quotes" && ( + <section data-quote-checks={result.rows.length} className="basis-full space-y-1.5 rounded-[3px] border border-seam bg-panel px-3 py-2.5"> + <div className="micro" data-quote-counts=""> + {result.rows.length} quote(s): {Object.entries(result.counts).map(([s, n]) => `${n} ${s}`).join(", ") || "none"} + </div> + <ul className="m-0 list-none space-y-2 p-0"> + {result.rows.map((r) => ( + <li key={r.citation} data-quote-check={r.citation} data-status={r.status} className="space-y-0.5 border-t border-seam pt-1.5 first:border-t-0 first:pt-0"> + <div className="flex flex-wrap items-baseline gap-x-2.5 gap-y-0.5 text-[12.5px]"> + <span className={cn("font-mono text-[11.5px] font-semibold uppercase", tone(r.status))}>{r.status}</span> + <span className="font-mono text-[11.5px] text-text">{r.citation}</span> + {!r.cited && <span className="text-[11.5px] text-muted">not cited</span>} + {r.score !== undefined && <span className="num font-mono text-[11.5px] text-text-2">{r.score.toFixed(2)}</span>} + {r.track && <span className="font-mono text-[11px] text-muted">{r.track}</span>} + {r.enOrig !== undefined && r.track !== "transcript.en-orig.vtt" && ( + <span className="font-mono text-[11px] text-muted">en-orig {r.enOrig.toFixed(2)}</span> + )} + <span className="font-mono text-[11px] text-muted"> + {r.channel}/{r.id} + {r.start !== undefined ? ` @ ${r.start}–${r.end} s` : ""} + </span> + </div> + <p className="m-0 font-serif text-[14px] leading-snug text-text-2">“{r.quote}”</p> + {r.message && <p className="m-0 text-[12px] text-text-2">{r.message}</p>} + {r.target && <Play target={r.target} why={`umtool verify quotes ${report} ${r.citation}`} />} + </li> + ))} + </ul> + </section> + )} + {result?.what === "check" && ( + <section data-report-check={result.status} className="basis-full space-y-1.5 rounded-[3px] border border-seam bg-panel px-3 py-2.5"> + <div className={cn("text-[12.5px] font-medium", tone(result.status))} data-check-summary=""> + {result.summary} + </div> + {[...result.allowed.map((a) => `allowed (missing media): ${a}`), ...result.warnings.map((w) => `warning: ${w}`)].map((l) => ( + <div key={l} className="text-[12px] text-doubt-text"> + {l} + </div> + ))} + <ul className="m-0 list-none space-y-2 p-0"> + {result.problems.map((p, i) => ( + <li key={`${p.line}-${i}`} data-check-problem={p.kind} className="space-y-0.5 border-t border-seam pt-1.5 first:border-t-0 first:pt-0"> + <div className="flex flex-wrap items-baseline gap-x-2.5 text-[12.5px]"> + <span className="font-mono text-[11.5px] font-semibold text-reject-text">{p.kind}</span> + <span className="font-mono text-[11.5px] text-text">{p.where}</span> + </div> + <p className="m-0 text-[12.5px] text-text-2">{p.message}</p> + {p.quote && <p className="m-0 font-serif text-[14px] leading-snug text-text-2">“{p.quote}”</p>} + {p.target && <Play target={p.target} why={`umtool check report ${report} ${p.where}`} />} + </li> + ))} + </ul> + </section> + )} + </div> + ); +} diff --git a/umtool/components/articles/ArticlePage.tsx b/umtool/components/articles/ArticlePage.tsx @@ -8,6 +8,7 @@ import { hasSlides, slideLint } from "yt-dlp-transcript-common/lib/report/slides import type { Crumb } from "@/components/shell/AppHeader"; import DeleteArticle from "@/components/articles/DeleteArticle"; import { RefreshHost, RefreshMenuItem } from "@/components/articles/RefreshDialog"; +import ArticleChecks from "@/components/articles/ArticleChecks"; import ArticleOverview from "@/components/articles/ArticleOverview"; import ArticleReader from "@/components/articles/ArticleReader"; import WorkspacePanel from "@/components/articles/WorkspacePanel"; @@ -354,6 +355,7 @@ async function ArticleTab({ {p.id} (possible) </Link> ))} + {read.report && <ArticleChecks site={site} report={reportId} />} {source && ( <div className="w-full font-mono text-[11px]" title={source.how}> {source.draft && <span>draft {source.draft}</span>} diff --git a/umtool/components/articles/EvidencePanel.tsx b/umtool/components/articles/EvidencePanel.tsx @@ -1,14 +1,15 @@ "use client"; import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react"; -import CopyButton from "@/components/CopyButton"; +import CitedClip, { type CitedClipHandle } from "@/components/clips/CitedClip"; import type { Evidence } from "@/lib/articles/evidence"; import AddToVideo, { type VideoProjectLink } from "./AddToVideo"; // One citation's evidence: what it quotes, who and when, the transcript around // it with the cited cues marked, and the media that plays it -- the prepared -// clip, a fetched window or a saved file, seeked to the cited second -- or, -// when there is none on disk, the MCP line that fetches it through the editor. +// clip, a fetched window or a saved file, video first, seeked to the cited +// second, with Play span -- or, when there is none on disk, Fetch clip (and +// the MCP line for the same seconds): components/clips/CitedClip.tsx. export type EvidenceHandle = { togglePlay: () => void }; @@ -45,29 +46,14 @@ const EvidencePanel = forwardRef< { ev: Evidence | null; error: string | null; number?: number; autoPlay?: boolean; projects?: VideoProjectLink[] } >( function EvidencePanel({ ev, error, number, autoPlay = false, projects = [] }, ref) { - const media = useRef<HTMLMediaElement | null>(null); - useImperativeHandle(ref, () => ({ - togglePlay: () => { - const m = media.current; - if (!m) return; - if (m.paused) void m.play().catch(() => {}); - else m.pause(); - }, - })); + const clip = useRef<CitedClipHandle | null>(null); + const [playable, setPlayable] = useState(!!ev?.play); + useImperativeHandle(ref, () => ({ togglePlay: () => clip.current?.togglePlay() })); if (error) return <p className="text-[12px] text-[var(--color-bad)]">{error}</p>; if (!ev) return <p className="text-[12px] text-[var(--color-dim)]">loading…</p>; - const play = ev.play; - // File time of a record second: the cited span starts `offset` into the file. - const fileT = (t: number) => (play && ev.start !== undefined ? Math.max(0, t - ev.start + play.offset) : 0); - const startAt = play ? (play.kind === "prepared" ? 0 : Math.max(0, play.offset - 3)) : 0; - const seek = (t: number) => { - if (media.current) { - media.current.currentTime = fileT(t); - void media.current.play().catch(() => {}); - } - }; + const seek = (t: number) => clip.current?.seek(t); return ( <div data-evidence={ev.cite} className="space-y-2 text-[12px]"> @@ -91,44 +77,18 @@ const EvidencePanel = forwardRef< </a> )} - {play ? ( - <div data-play={play.kind}> - {play.audio ? ( - <audio - ref={(el) => { - media.current = el; - }} - controls - src={play.url} - autoPlay={autoPlay} - onLoadedMetadata={(e) => { - e.currentTarget.currentTime = startAt; - }} - className="w-full" - /> - ) : ( - <video - ref={(el) => { - media.current = el; - }} - controls - src={play.url} - autoPlay={autoPlay} - onLoadedMetadata={(e) => { - e.currentTarget.currentTime = startAt; - }} - className="aspect-video w-full rounded bg-black" - /> - )} - <div className="micro mt-0.5">{play.label}</div> - </div> - ) : ev.fetchLine ? ( - <div data-play="none" className="space-y-1 rounded border border-[var(--color-line)] bg-[var(--color-panel-2)] p-2"> - <div className="text-[var(--color-dim)]">not on disk — fetch it through the editor:</div> - <code className="block break-all font-mono text-[11px] text-[var(--color-text)]">{ev.fetchLine}</code> - <CopyButton text={ev.fetchLine} label="copy fetch_clip" /> - </div> - ) : null} + {ev.record && ev.start !== undefined && ev.end !== undefined && (ev.kind === "video" || ev.kind === "audio") && ( + <CitedClip + key={ev.cite} + ref={clip} + target={{ channel: ev.record.channel, video: ev.record.id, from: ev.start, to: ev.end, ...(ev.kind === "audio" ? { audio: true } : {}) }} + initial={ev.play} + fetchLine={ev.fetchLine} + reason={`umtool evidence ${ev.cite}`} + autoPlay={autoPlay} + onPlayable={setPlayable} + /> + )} {ev.post && ( <div data-post className="reader space-y-1 rounded-[2px] px-3.5 py-2.5"> @@ -148,7 +108,7 @@ const EvidencePanel = forwardRef< <button type="button" onClick={() => seek(c.start)} - disabled={!play} + disabled={!playable} className={`flex w-full items-baseline gap-3 border-l-[3px] px-2.5 py-px text-left ${c.cited ? "border-reader-signal bg-[color-mix(in_srgb,var(--reader-signal)_9%,transparent)] text-reader-ink" : "border-transparent text-reader-2"} enabled:hover:text-reader-ink`} > <span className={`num shrink-0 font-mono text-[10.5px] ${c.cited ? "font-semibold text-reader-signal" : "text-reader-dim"}`}>{fmt(c.start)}</span> diff --git a/umtool/components/clips/CitedClip.tsx b/umtool/components/clips/CitedClip.tsx @@ -0,0 +1,361 @@ +"use client"; + +import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react"; +import CopyButton from "@/components/CopyButton"; +import { buttonVariants } from "@/components/ui/button"; +import { citedKey, type CitedFetchAnswer, type CitedPlay, type CitedTarget } from "@/lib/clips/types"; +import { spanClock } from "@/lib/clips/words"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// THE CITED CLIP (release 32 R1): the seconds a citation names, played so a +// person can hear -- and see -- that the words are there. The one place a +// human has to verify, and it needs no model. +// +// video first a clip window or saved video covering the span, seeked to +// the cited second; "Play span" plays from the span's start +// and stops at its end; replay is the same press +// audio when only audio holds it, with an "audio only" label +// Fetch clip when nothing on disk does: one press asks the editor +// (/api/cited/fetch -> the editor's fetch-window, as the MCP's +// fetch_clip asks), shows its progress, plays when it lands; +// a failure is said plainly (a rate limit, corrupt audio) +// +// Two faces: `panel` (native controls, the evidence panel and the reader) and +// `card` (the audition deck's: no chrome, tap replays, a span-only scrubber). +// Its buttons never take focus, and the media gives it back, so a page's own +// keys (approve, reject, j/k) keep working after a play. +// --------------------------------------------------------------------------- + +export type CitedClipHandle = { + /** Play the span from its start; pause when playing. */ + togglePlay: () => void; + /** Play the span from its start, always. */ + playSpan: () => void; + /** Seek to a source second and play from there. */ + seek: (t: number) => void; +}; + +type Looked = { play: CitedPlay | null; fetchLine?: string }; +const lookups = new Map<string, Promise<Looked>>(); + +function lookup(t: CitedTarget, fresh = false): Promise<Looked> { + const key = citedKey(t); + if (fresh) lookups.delete(key); + let p = lookups.get(key); + if (!p) { + const q = new URLSearchParams({ channel: t.channel, video: t.video, from: String(t.from), to: String(t.to) }); + if (t.project && t.clip) { + q.set("project", t.project); + q.set("clip", t.clip); + } + if (t.audio) q.set("audio", "1"); + p = fetch(`/api/cited/play?${q}`, { cache: "no-store" }).then(async (r) => { + const j = await r.json(); + if (!r.ok) throw new Error(j.error ?? r.statusText); + return j as Looked; + }); + p.catch(() => lookups.delete(key)); + lookups.set(key, p); + } + return p; +} + +/** Ask what plays a span before it is shown (the card after the next). */ +export function warmCited(t: CitedTarget): void { + void lookup(t).catch(() => {}); +} + +const stopTyping = "input, textarea, select, button, a[href], [contenteditable=''], [contenteditable='true']"; + +const CitedClip = forwardRef< + CitedClipHandle, + { + target: CitedTarget; + /** Known already (the evidence route found it): undefined looks it up, null is a known miss. */ + initial?: CitedPlay | null; + fetchLine?: string; + /** Why these seconds are wanted: stored beside the window. */ + reason?: string; + report?: string; + face?: "panel" | "card"; + /** Play the span as soon as it can. */ + autoPlay?: boolean; + /** Load the media now (the card underneath). */ + preload?: boolean; + /** Space plays the span (from anywhere that is not a control). */ + keys?: boolean; + /** The source second, as it plays (the lit line follows it). */ + onTime?: (t: number) => void; + /** Whether something can play now. */ + onPlayable?: (playable: boolean) => void; + className?: string; + } +>(function CitedClip( + { target, initial, fetchLine: givenLine, reason, report, face = "panel", autoPlay = false, preload = false, keys = false, onTime, onPlayable, className }, + ref, +) { + const [play, setPlay] = useState<CitedPlay | null | undefined>(initial); + const [line, setLine] = useState<string | undefined>(givenLine); + const [lookError, setLookError] = useState<string | null>(null); + const [fetching, setFetching] = useState<CitedFetchAnswer | { state: "asking" } | null>(null); + const [now, setNow] = useState(target.from); + const [playing, setPlaying] = useState(false); + const media = useRef<HTMLMediaElement | null>(null); + const spanning = useRef(false); + const wantPlay = useRef(autoPlay); + const key = citedKey(target); + + useEffect(() => { + if (initial !== undefined) return; + let live = true; + lookup(target) + .then((l) => { + if (!live) return; + setPlay(l.play); + if (l.fetchLine && !givenLine) setLine(l.fetchLine); + }) + .catch((e) => live && setLookError(e instanceof Error ? e.message : String(e))); + return () => { + live = false; + }; + // `target` is named by its key. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key, initial]); + + useEffect(() => onPlayable?.(!!play), [play, onPlayable]); + useEffect(() => { + wantPlay.current = autoPlay; + if (autoPlay && media.current && media.current.readyState >= 1) playSpanNow(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [autoPlay]); + + // File time of a source second: the span starts `offset` into the file. + const fileT = useCallback((t: number) => (play ? Math.max(0, t - target.from + play.offset) : 0), [play, target.from]); + const sourceT = useCallback((ft: number) => (play ? ft - play.offset + target.from : target.from), [play, target.from]); + + const giveBackFocus = () => { + const a = document.activeElement as HTMLElement | null; + if (a && media.current && (a === media.current || media.current.contains(a))) a.blur(); + }; + + const playSpanNow = useCallback(() => { + const m = media.current; + if (!m) return; + m.currentTime = fileT(target.from); + spanning.current = true; + void m.play().catch(() => {}); + }, [fileT, target.from]); + + const api: CitedClipHandle = { + playSpan: playSpanNow, + togglePlay: () => { + const m = media.current; + if (!m) return; + if (m.paused) playSpanNow(); + else m.pause(); + }, + seek: (t: number) => { + const m = media.current; + if (!m) return; + m.currentTime = fileT(t); + spanning.current = t < target.to; + void m.play().catch(() => {}); + }, + }; + useImperativeHandle(ref, () => api); + + useEffect(() => { + if (!keys) return; + const onKey = (e: KeyboardEvent) => { + if (e.key !== " " || e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return; + const t = e.target as HTMLElement | null; + if (t?.closest?.(stopTyping) || t?.closest?.("dialog[open]")) return; + if (!media.current) return; + e.preventDefault(); + api.togglePlay(); + }; + document.addEventListener("keydown", onKey); + return () => document.removeEventListener("keydown", onKey); + }); + + const runFetch = async () => { + setFetching({ state: "asking" }); + const body = { ...target, reason: reason ?? "umtool: play the cited span", ...(report ? { report } : {}) }; + try { + let r = await fetch("/api/cited/fetch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + let a = (await r.json()) as CitedFetchAnswer & { error?: string }; + for (let polls = 0; r.ok && a.state === "queued" && polls < 600; polls++) { + setFetching(a); + await new Promise((res) => setTimeout(res, 1000)); + r = await fetch("/api/cited/fetch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ ...target, job: a.job }) }); + a = (await r.json()) as CitedFetchAnswer & { error?: string }; + } + if (!r.ok) { + setFetching({ state: "failed", message: a.error ?? `HTTP ${r.status}` }); + return; + } + setFetching(a); + if (a.state === "ready") { + const found = a.play ?? (await lookup(target, true)).play; + lookups.set(key, Promise.resolve({ play: found, ...(line ? { fetchLine: line } : {}) })); + wantPlay.current = true; + setPlay(found); + if (!found) setFetching({ state: "failed", message: "the editor fetched it, but nothing on this disk plays the span" }); + } + } catch (e) { + setFetching({ state: "failed", message: e instanceof Error ? e.message : String(e) }); + } + }; + + const span = Math.max(0.001, target.to - target.from); + const rel = Math.min(span, Math.max(0, now - target.from)); + const card = face === "card"; + + const status = + fetching && fetching.state !== "asking" ? ( + <span + data-fetch-state={fetching.state} + role={fetching.state === "failed" ? "alert" : "status"} + className={cn("block text-[12px]", fetching.state === "failed" ? "text-reject-text" : "text-muted")} + title={fetching.state === "failed" ? fetching.detail : undefined} + > + {fetching.state === "ready" + ? `Clip ${fetching.cached ? "already held" : "fetched"}` + : fetching.state === "queued" + ? `The editor is fetching it (${fetching.status})…` + : fetching.message} + </span> + ) : null; + + const mediaProps = { + ref: (el: HTMLMediaElement | null) => { + media.current = el; + }, + src: play?.url, + preload: preload || autoPlay ? "auto" : "metadata", + "data-player": "", + tabIndex: -1, + onLoadedMetadata: (e: React.SyntheticEvent<HTMLMediaElement>) => { + e.currentTarget.currentTime = play ? (card ? play.offset : Math.max(0, play.offset - (play.kind === "prepared" ? play.offset : 3))) : 0; + if (wantPlay.current) playSpanNow(); + }, + onTimeUpdate: (e: React.SyntheticEvent<HTMLMediaElement>) => { + const t = sourceT(e.currentTarget.currentTime); + setNow(t); + onTime?.(t); + if (spanning.current && t >= target.to) { + spanning.current = false; + e.currentTarget.pause(); + } + }, + onPlay: () => { + setPlaying(true); + giveBackFocus(); + }, + onPause: () => { + setPlaying(false); + giveBackFocus(); + }, + onSeeked: giveBackFocus, + }; + + const noFocus = (e: React.MouseEvent) => e.preventDefault(); + + return ( + <div + data-cited-clip={key} + data-play={play === undefined ? (lookError ? "error" : "looking") : play ? play.kind : "none"} + data-playing={playing ? "" : undefined} + className={cn("space-y-1.5", className)} + > + {play ? ( + <> + {play.audio ? ( + <div className={cn(card && "flex aspect-video w-full items-center justify-center rounded-[3px] bg-panel-2")}> + {card && ( + <button type="button" onMouseDown={noFocus} onClick={() => api.playSpan()} className="font-mono text-[12px] text-muted" aria-label="Replay the span"> + {playing ? "playing…" : "▶ replay"} + </button> + )} + <audio {...mediaProps} controls={!card} className={card ? "hidden" : "w-full"} /> + </div> + ) : ( + <video + {...mediaProps} + controls={!card} + playsInline + onClick={card ? () => api.playSpan() : undefined} + className={cn("aspect-video w-full rounded-[3px] bg-black", card && "cursor-pointer")} + /> + )} + <div className="flex flex-wrap items-center gap-2"> + {card ? ( + <input + type="range" + aria-label="Position in the span" + data-span-scrubber="" + min={0} + max={span} + step={0.05} + value={rel} + onChange={(e) => api.seek(target.from + Number(e.target.value))} + onPointerUp={(e) => e.currentTarget.blur()} + className="min-w-0 flex-1 accent-[var(--signal)]" + /> + ) : ( + <> + <button type="button" data-play-span="" onMouseDown={noFocus} onClick={() => api.playSpan()} className={buttonVariants({ variant: "outline", size: "sm" })}> + {playing ? "Replay span" : "Play span"} + </button> + {playing && ( + <button type="button" onMouseDown={noFocus} onClick={() => media.current?.pause()} className={buttonVariants({ variant: "ghost", size: "sm" })}> + Pause + </button> + )} + </> + )} + <span className="num font-mono text-[11px] text-muted" data-span-clock=""> + {spanClock(rel)} / {spanClock(span)} + </span> + {play.audio && ( + <span data-audio-only="" className="rounded-[3px] border border-seam-2 px-1.5 py-px text-[11px] text-text-2"> + audio only + </span> + )} + {!card && <span className="micro">{play.label}</span>} + </div> + </> + ) : play === null ? ( + <div className={cn("space-y-1.5 rounded-[3px] border border-seam bg-panel-2 p-2.5", card && "flex aspect-video w-full flex-col items-center justify-center text-center")}> + <div className="text-[12.5px] text-text-2">Not on disk</div> + <button + type="button" + data-fetch-clip="" + onMouseDown={noFocus} + disabled={!!fetching && (fetching.state === "asking" || fetching.state === "queued")} + onClick={() => void runFetch()} + className={buttonVariants({ variant: "go", size: "md" })} + > + {fetching && (fetching.state === "asking" || fetching.state === "queued") ? "Fetching…" : "Fetch clip"} + </button> + {status} + {!card && line && ( + <details className="text-[11px] text-muted"> + <summary className="cursor-pointer">or with the MCP</summary> + <code className="block break-all font-mono text-[11px] text-text-2">{line}</code> + <CopyButton text={line} label="copy fetch_clip" /> + </details> + )} + </div> + ) : ( + <div className={cn("text-[12px] text-muted", card && "flex aspect-video w-full items-center justify-center rounded-[3px] bg-panel-2")}> + {lookError ? <span className="text-reject-text">{lookError}</span> : "looking for the clip…"} + </div> + )} + {play && status} + </div> + ); +}); + +export default CitedClip; diff --git a/umtool/components/projects/MediaDrafts.tsx b/umtool/components/projects/MediaDrafts.tsx @@ -4,6 +4,8 @@ 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 CitedClip from "@/components/clips/CitedClip"; +import type { CitedTarget } from "@/lib/clips/types"; import { buttonVariants } from "@/components/ui/button"; import { LitActions, LitGroup, LitLine } from "@/components/ui/lit-line"; import { LitList, type LitDetail } from "@/components/ui/lit-list"; @@ -593,7 +595,11 @@ export type FieldEvidence = { cite: { at: number; duration: number } | null; quote: string | null; url: string | null; - cues: { start: number; text: string }[]; + cues: { start: number; end?: number; text: string }[]; + /** What plays the span (components/clips/CitedClip.tsx); null when the entry names no source. */ + target?: CitedTarget | null; + /** Who is speaking, as the burned-in header names them. */ + speaker?: string | null; }; /** @@ -606,11 +612,14 @@ export function MediaReview({ initial, provenance, evidence, + deckHref, }: { project: string; initial: DraftsView; provenance: Record<string, FieldProvenance>; evidence: Record<string, FieldEvidence>; + /** The audition deck's address (release 32 R1): the toggle back. */ + deckHref?: string; }) { const drafts = useDrafts(project, initial); const view = drafts.view ?? initial; @@ -686,6 +695,11 @@ export function MediaReview({ byline={ev.byline} cite={ev.cite ?? undefined} label="Source" + note={ + ev.target ? ( + <CitedClip key={`${row?.address}|${ev.target.from}`} target={ev.target} keys reason={`umtool drafts review ${project} ${row?.entry ?? ""}`.trim()} report={project} className="pb-1" /> + ) : undefined + } cues={ev.cues.map((c, i) => ({ t: c.start, text: c.text, @@ -703,6 +717,16 @@ export function MediaReview({ ); return ( <BenchBody verdict={verdict} reader={reader} workClassName="space-y-3"> + {deckHref && ( + <div className="flex items-center gap-2 text-[12px]"> + <Link href={deckHref} prefetch={false} data-review-view="deck" className={buttonVariants({ variant: "outline", size: "sm" })}> + Deck + </Link> + <span data-review-view-current="list" className={buttonVariants({ variant: "pressed", size: "sm" })} aria-current="page"> + List + </span> + </div> + )} <GateLine view={view} /> <MediaFields project={project} view={view} act={drafts.act} provenance={provenance} onLit={setLit} lineGo={false} /> </BenchBody> diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx @@ -61,7 +61,7 @@ export default async function ProjectView({ if (rest.length === 1 && rest[0] === "narration") return <NarrationPage project={project} />; // `/browse/<project>/review` -- every drafted field, approved / rejected // before a final build, and the alternatives a draft task kept. - if (rest.length === 1 && rest[0] === "review") return <ReviewPage project={project} />; + if (rest.length === 1 && rest[0] === "review") return <ReviewPage project={project} view={search.view} />; return notFound(); } case "sweep-report": { diff --git a/umtool/components/projects/ReviewPage.tsx b/umtool/components/projects/ReviewPage.tsx @@ -1,5 +1,5 @@ import { clock } from "@/components/ui/clock"; -import { projectsHref } from "@/lib/hrefs"; +import { projectsHref, reviewHref } from "@/lib/hrefs"; import { cuesInWindow, readClipDetail, readManifest } from "@/lib/projects/report.mjs"; import { manifestToken } from "@/lib/report/manifest.mjs"; import { draftsView } from "@/lib/report/drafts.mjs"; @@ -10,8 +10,14 @@ import type { ProjectRef } from "@/lib/project-types"; import { BenchFrame, BenchTop } from "./bench/BenchShell"; import { MediaReview, type FieldEvidence, type FieldProvenance } from "./MediaDrafts"; import type { DraftsView } from "./drafts"; +import AuditionDeck from "./review/AuditionDeck"; -// `/projects/<project>/review` -- the drafts review as a BENCH (P4b): every +// `/projects/<project>/review` -- the drafts review. By default the AUDITION +// DECK (release 32 R1, components/projects/review/AuditionDeck.tsx): one card +// per field awaiting review, its cited span playing, keep / cut / edit / skip +// as one gesture. `?view=list` is the list below, for bulk work. +// +// The list is 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 @@ -20,9 +26,18 @@ import type { DraftsView } from "./drafts"; // <project>/drafts.review.json; a final build refuses a drafted field not // approved on its current value (release 28, M0). +const spanOf = (e: { start: number; end: number; cutStart?: number; cutEnd?: number }) => { + const cut = Number.isFinite(Number(e.cutStart)) && Number.isFinite(Number(e.cutEnd)) && Number(e.cutStart) < Number(e.cutEnd); + const from = cut ? Number(e.cutStart) : Number(e.start); + const to = cut ? Number(e.cutEnd) : Number(e.end); + return Number.isFinite(from) && Number.isFinite(to) && from < to ? { from, to } : null; +}; + 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 }) { +export default async function ReviewPage({ project, view: mode }: { project: ProjectRef; view?: string }) { + // The audition deck (release 32 R1) unless `?view=list`: the same fields, one card at a time. + const list = mode === "list"; const manifest = await readManifest(project.dir); const [view, provenance, token, detail] = await Promise.all([ draftsView(project.dir, manifest ?? {}) as Promise<DraftsView>, @@ -37,7 +52,7 @@ export default async function ReviewPage({ project }: { project: ProjectRef }) { // 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 }; + type Entry = { id: string; kind: string; start: number; end: number; cutStart?: number; cutEnd?: number; cite?: number | null; quote?: string | null; video?: string; channel?: string | null; sourceChannel?: 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; @@ -48,12 +63,21 @@ export default async function ReviewPage({ project }: { project: ProjectRef }) { 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 })), + cues: (win?.cues ?? []).map((c: { start: number; end: number; text: string }) => ({ start: c.start, end: c.end, text: c.text })), + // What plays (components/clips/CitedClip.tsx): the cut's own extent when + // it has one, else the clip's; the corpus's directories -- a Rumble + // entry's local dir is `video`, never its siteVideo. + target: spanOf(e) && e.channel && e.video ? { channel: e.channel, video: e.video, ...spanOf(e)!, project: project.id, clip: e.id } : null, + speaker: e.sourceChannel ?? null, }; } // The piece this view belongs to: the article's when an article claims the project (P4a-2). const back = await pieceHrefOfProject(project.id, { tab: "media" }); + // Where a misheard word is fixed: the article's Iterations tab (R2's "Fix a mishearing" form reads `heard`), + // when an article claims the project. + const articlePage = await pieceHrefOfProject(project.id, { tab: "iterations" }); + const respell = articlePage.startsWith("/projects/") ? null : articlePage; // To review: the drafted fields awaiting a verdict (the Media tab's count, the Inbox's). const toReview = awaitingReview(view.rows, provenance).length; return ( @@ -65,16 +89,21 @@ export default async function ReviewPage({ project }: { project: ProjectRef }) { 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" }] : []} + keys={list && view.rows.length ? [{ keys: ["j", "k"], label: "field" }, { keys: ["a"], label: "approve" }, { keys: ["r"], label: "reject" }] : []} note={ - view.rows.length + // The deck keeps ONE counter and ONE hint row, its own (release 32 R1). + list && 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} /> + {list ? ( + <MediaReview project={project.id} initial={{ ...view, token }} provenance={provenance} evidence={evidence} deckHref={reviewHref(project.id)} /> + ) : ( + <AuditionDeck project={project.id} initial={{ ...view, token }} provenance={provenance} evidence={evidence} back={back} listHref={reviewHref(project.id, { view: "list" })} respell={respell} /> + )} </BenchFrame> ); } diff --git a/umtool/components/projects/review/AuditionDeck.tsx b/umtool/components/projects/review/AuditionDeck.tsx @@ -0,0 +1,775 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import CitedClip, { warmCited, type CitedClipHandle } from "@/components/clips/CitedClip"; +import { buttonVariants } from "@/components/ui/button"; +import { awaitingReview } from "@/lib/inbox/drafts.mjs"; +import { editTextOf, isEditableField } from "@/lib/report/draftEdit.mjs"; +import { litCount, spokenWords } from "@/lib/clips/words"; +import { cn } from "@/lib/utils"; +import { useDrafts, type DraftRow, type DraftsView } from "../drafts"; +import type { FieldEvidence, FieldProvenance } from "../MediaDrafts"; + +// --------------------------------------------------------------------------- +// THE AUDITION (release 32 R1; the operator's "like a swipe app"): the drafts +// review as a deck of cards, one field per card. The model did the heavy +// lifting -- it drafted the field and picked the moment; the person's one job +// is to LISTEN and rule. So the cited span is already playing, the decision is +// one gesture, and the next card is already loaded underneath. +// +// swipe → / → k KEEP approve the draft as it is +// swipe ← / ← x CUT reject it; a reason chip or a few words, never required +// swipe ↑ / ↑ e EDIT the value as text on the card; Enter keeps it as edited +// swipe ↓ / ↓ s SKIP to the back of the stack +// tap the video / space replay the span +// z / Backspace UNDO the last keep, cut or skip (20 deep) +// tap a word / m mark it MISHEARD (the note says so; the article's page fixes it) +// +// Decisions write through the drafts route (drafts.review.json), the same as +// the list view (`?view=list`). An EDIT writes the field through the +// manifest's writer and is undone from the History tab, not with z. +// --------------------------------------------------------------------------- + +type Decision = "kept" | "cut" | "edited"; +type Undo = { address: string; kind: "kept" | "cut" | "skip"; prev: { verdict: DraftRow["verdict"]; note: string } }; + +const CUT_REASONS = ["misheard", "wrong moment", "says something else", "too long", "wrong speaker"]; +const THRESHOLD = 0.3; +const FLICK = 0.6; +const UNDO_DEPTH = 20; +// The next card rises into place (120 ms); with reduced motion it does not move. +const DECK_CSS = `@keyframes deck-rise { from { transform: scale(0.97) translateY(4px); } to { transform: none; } } +.deck-rise { animation: deck-rise 120ms ease-out; } +@keyframes deck-out-right { from { transform: translate(var(--dx), var(--dy)) rotate(var(--r)); } to { transform: translate(120%, 0) rotate(8deg); opacity: 0.6; } } +@keyframes deck-out-left { from { transform: translate(var(--dx), var(--dy)) rotate(var(--r)); } to { transform: translate(-120%, 0) rotate(-8deg); opacity: 0.6; } } +@keyframes deck-out-down { from { transform: translate(var(--dx), var(--dy)); } to { transform: translate(0, 110%); opacity: 0; } } +@keyframes deck-fade { from { opacity: 1; } to { opacity: 0; } } +.deck-out-right { animation: deck-out-right 160ms ease-in forwards; } +.deck-out-left { animation: deck-out-left 160ms ease-in forwards; } +.deck-out-down { animation: deck-out-down 160ms ease-in forwards; } +.deck-fade { animation: deck-fade 80ms linear forwards; } +@media (prefers-reduced-motion: reduce) { .deck-rise { animation: none; } }`; + +// KEEP reads from the side the card leaves by: top left; CUT and SKIP top right. +const stampClass = (kind: string) => + cn( + "pointer-events-none absolute top-28 z-10 rotate-[-8deg] rounded-[4px] border-[3px] px-2.5 py-0.5 font-display text-[28px] font-bold uppercase tracking-wide", + kind === "KEEP" ? "left-4 border-signal text-signal" : kind === "CUT" ? "right-4 border-muted text-muted line-through" : "right-4 border-seam-2 text-text-2", + ); +const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']"; + +export default function AuditionDeck({ + project, + initial, + provenance, + evidence, + back, + listHref, + respell, +}: { + project: string; + initial: DraftsView; + provenance: Record<string, FieldProvenance>; + evidence: Record<string, FieldEvidence>; + /** The Media tab. */ + back: string; + listHref: string; + /** The article's page, where a mishearing is fixed (null: no article claims the cut). */ + respell: string | null; +}) { + const drafts = useDrafts(project, initial); + const view = drafts.view ?? initial; + const rowOf = useCallback((a: string) => view.rows.find((r) => r.address === a) ?? null, [view.rows]); + + const [queue, setQueue] = useState<string[]>(() => awaitingReview(initial.rows, provenance).map((r: DraftRow) => r.address)); + const [total, setTotal] = useState(queue.length); + const [decided, setDecided] = useState<Map<string, Decision>>(new Map()); + const [skipped, setSkipped] = useState<Set<string>>(new Set()); + const [undos, setUndos] = useState<Undo[]>([]); + const [started, setStarted] = useState(false); + const [editing, setEditing] = useState<string | null>(null); + const [editText, setEditText] = useState(""); + const [reason, setReason] = useState<string>(""); + const [misheard, setMisheard] = useState<Map<string, Set<number>>>(new Map()); + const [error, setError] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + const [drag, setDrag] = useState<{ dx: number; dy: number } | null>(null); + // The card that was just decided, flying out over the next one: a picture of + // it only, so a key pressed during the exit is never lost. + const [ghost, setGhost] = useState<null | { address: string; dir: "right" | "left" | "down"; dx: number; dy: number; id: number }>(null); + const [reduced, setReduced] = useState(false); + const [hints, setHints] = useState(false); + const clip = useRef<CitedClipHandle | null>(null); + const card = useRef<HTMLDivElement | null>(null); + const start = useRef<{ x: number; y: number; t: number; id: number } | null>(null); + + useEffect(() => { + const m = window.matchMedia("(prefers-reduced-motion: reduce)"); + setReduced(m.matches); + const on = () => setReduced(m.matches); + m.addEventListener("change", on); + return () => m.removeEventListener("change", on); + }, []); + + const live = queue.filter((a) => !skipped.has(a)); + const top = live[0] ?? null; + const under = live[1] ?? null; + const row = top ? rowOf(top) : null; + const ev = row?.entry ? (evidence[row.entry] ?? null) : null; + const counts = useMemo(() => { + const c = { kept: 0, cut: 0, edited: 0 }; + for (const d of decided.values()) c[d] += 1; + return c; + }, [decided]); + const done = decided.size; + // Where the deck is: every card ruled or skipped so far, then this one. + const at = Math.min(done + skipped.size + 1, total); + const hintShown = hints || done + skipped.size < 3; + + // The card after the next: ask what plays it before it is shown. + useEffect(() => { + const after = live[2]; + const e = after ? evidence[rowOf(after)?.entry ?? ""] : null; + if (e?.target) warmCited(e.target); + }, [live, evidence, rowOf]); + + const noteFor = (address: string, extra: string) => { + const words = misheard.get(address); + const quote = evidence[rowOf(address)?.entry ?? ""]?.quote ?? ""; + const marked = words?.size ? `misheard: ${[...words].map((i) => quote.split(/\s+/).filter(Boolean)[i]).filter(Boolean).join(", ")}` : ""; + return [extra, marked].filter(Boolean).join(" · "); + }; + + const remember = (u: Undo) => setUndos((s) => [...s.slice(-(UNDO_DEPTH - 1)), u]); + + const commit = useCallback( + async (kind: "kept" | "cut" | "skip", address: string) => { + const r = rowOf(address); + if (!r) return; + const prev = { verdict: r.verdict, note: r.note ?? "" }; + setError(null); + if (kind === "skip") { + setSkipped((s) => new Set(s).add(address)); + setQueue((q) => [...q.filter((a) => a !== address), address]); + remember({ address, kind, prev }); + return; + } + setQueue((q) => q.filter((a) => a !== address)); + setDecided((d) => new Map(d).set(address, kind)); + remember({ address, kind, prev }); + try { + if (kind === "kept") await drafts.act("approve", { address, note: noteFor(address, r.note ?? "") }); + else await drafts.act("reject", { address, note: noteFor(address, reason || r.note || "cut on the deck") }); + setReason(""); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + setQueue((q) => [address, ...q.filter((a) => a !== address)]); + setDecided((d) => { + const n = new Map(d); + n.delete(address); + return n; + }); + setUndos((s) => s.slice(0, -1)); + } + }, + // eslint-disable-next-line react-hooks/exhaustive-deps + [rowOf, drafts, reason, misheard, evidence], + ); + + const decide = useCallback( + (dir: "right" | "left" | "up" | "down") => { + if (!top || busy) return; + setStarted(true); + if (dir === "up") { + setDrag(null); + const r = rowOf(top); + if (!r) return; + setEditing(top); + setEditText(editTextOf(r.field, r.text)); + return; + } + const address = top; + const id = Date.now(); + setGhost({ address, dir, dx: drag?.dx ?? 0, dy: drag?.dy ?? 0, id }); + setDrag(null); + window.setTimeout(() => setGhost((g) => (g?.id === id ? null : g)), reduced ? 80 : 160); + void commit(dir === "right" ? "kept" : dir === "left" ? "cut" : "skip", address); + }, + [top, busy, drag, rowOf, commit, reduced], + ); + + const undo = useCallback(async () => { + const u = undos[undos.length - 1]; + if (!u || busy) return; + setUndos((s) => s.slice(0, -1)); + setError(null); + if (u.kind === "skip") { + setSkipped((s) => { + const n = new Set(s); + n.delete(u.address); + return n; + }); + setQueue((q) => [u.address, ...q.filter((a) => a !== u.address)]); + return; + } + setBusy(true); + try { + if (!u.prev.verdict) await drafts.act("clear", { address: u.address }); + else if (u.prev.verdict === "approved") await drafts.act("approve", { address: u.address, note: u.prev.note }); + else await drafts.act("reject", { address: u.address, note: u.prev.note || "cut on the deck" }); + setDecided((d) => { + const n = new Map(d); + n.delete(u.address); + return n; + }); + setQueue((q) => [u.address, ...q.filter((a) => a !== u.address)]); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }, [undos, busy, drafts]); + + const saveEdit = async () => { + if (!editing) return; + const address = editing; + setBusy(true); + setError(null); + try { + await drafts.act("edit", { address, text: editText, token: view.token ?? null, note: noteFor(address, "edited on the deck") }); + setEditing(null); + setQueue((q) => q.filter((a) => a !== address)); + setDecided((d) => new Map(d).set(address, "edited")); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + + const toggleWord = (address: string, i: number) => + setMisheard((m) => { + const n = new Map(m); + const s = new Set(n.get(address) ?? []); + if (s.has(i)) s.delete(i); + else s.add(i); + n.set(address, s); + return n; + }); + + // The keys. Typing (the edit, the cut's few words) and a focused word keep theirs. + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return; + const t = e.target as HTMLElement | null; + if (editing) { + if (e.key === "Escape") { + e.preventDefault(); + setEditing(null); + } + return; + } + if (t?.closest?.(TYPING)) return; + if (t?.closest?.("[data-word]") && (e.key === " " || e.key === "Enter")) return; + const k = e.key; + const act = (fn: () => void) => { + e.preventDefault(); + fn(); + }; + if (k === "ArrowRight" || k === "k") act(() => decide("right")); + else if (k === "ArrowLeft" || k === "x") act(() => decide("left")); + else if (k === "ArrowUp" || k === "e") act(() => decide("up")); + else if (k === "ArrowDown" || k === "s") act(() => decide("down")); + else if (k === "z" || k === "Backspace") act(() => void undo()); + else if (k === " ") + act(() => { + setStarted(true); + clip.current?.playSpan(); + }); + else if (k === "?") act(() => setHints((h) => !h)); + else if (k === "m") act(() => card.current?.querySelector<HTMLButtonElement>("[data-word]")?.focus()); + else if (k === "Escape") (document.activeElement as HTMLElement | null)?.blur?.(); + }; + document.addEventListener("keydown", onKey); + return () => document.removeEventListener("keydown", onKey); + }, [decide, undo, editing]); + + // The drag: past 30 % of the card's width, or a flick, decides; below it springs back. + const onPointerDown = (e: React.PointerEvent) => { + if (editing || e.button !== 0) return; + if ((e.target as HTMLElement).closest("button, a, input, textarea, select, [data-word]")) return; + start.current = { x: e.clientX, y: e.clientY, t: performance.now(), id: e.pointerId }; + }; + const onPointerMove = (e: React.PointerEvent) => { + const s = start.current; + if (!s || s.id !== e.pointerId) return; + const dx = e.clientX - s.x; + const dy = e.clientY - s.y; + if (!drag && Math.hypot(dx, dy) < 6) return; + if (!drag) (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); + setDrag({ dx, dy }); + }; + const onPointerUp = (e: React.PointerEvent) => { + const s = start.current; + start.current = null; + if (!s || !drag) return; + const w = card.current?.offsetWidth ?? 400; + const dt = Math.max(1, performance.now() - s.t); + const { dx, dy } = drag; + const horizontal = Math.abs(dx) >= Math.abs(dy); + const d = horizontal ? dx : dy; + if (Math.abs(d) > THRESHOLD * w || Math.abs(d) / dt > FLICK) { + decide(horizontal ? (dx > 0 ? "right" : "left") : dy < 0 ? "up" : "down"); + } else setDrag(null); + void e; + }; + + // The stamp the drag is heading for. + const stamp = drag + ? Math.abs(drag.dx) >= Math.abs(drag.dy) + ? { kind: drag.dx > 0 ? "KEEP" : "CUT", o: Math.min(1, Math.abs(drag.dx) / ((card.current?.offsetWidth ?? 400) * THRESHOLD)) } + : { kind: drag.dy < 0 ? "EDIT" : "SKIP", o: Math.min(1, Math.abs(drag.dy) / ((card.current?.offsetWidth ?? 400) * THRESHOLD)) } + : null; + + const transform = drag ? `translate(${drag.dx}px, ${drag.dy}px) rotate(${drag.dx * 0.04}deg)` : undefined; + + const toggle = ( + <div className="flex items-center gap-2 text-[12px]"> + <span data-review-view-current="deck" className={buttonVariants({ variant: "pressed", size: "sm" })} aria-current="page"> + Deck + </span> + <Link href={listHref} prefetch={false} data-review-view="list" className={buttonVariants({ variant: "outline", size: "sm" })}> + List + </Link> + <span data-deck-count="" className="ml-auto font-mono text-[11.5px] text-muted"> + {total ? `${at} / ${total}` : "0 / 0"} · {counts.kept} kept · {counts.cut} cut{counts.edited ? ` · ${counts.edited} edited` : ""} · {skipped.size} skipped + </span> + </div> + ); + + if (!total) { + return ( + <main data-deck="" data-deck-empty="" className="deck-main flex-1 p-4"> + <div className="mx-auto max-w-[520px] space-y-4"> + {toggle} + <p className="m-0 text-[13px] text-text-2">Nothing is waiting for a verdict.</p> + <Link href={back} prefetch={false} className={buttonVariants({ variant: "outline", size: "md" })}> + Back to the Media tab + </Link> + </div> + </main> + ); + } + + if (!top) { + const cut = [...decided].filter(([, d]) => d === "cut").map(([a]) => a); + const skip = [...skipped]; + return ( + <main data-deck="" className="deck-main flex-1 p-4"> + <div className="mx-auto max-w-[520px] space-y-4"> + {toggle} + <section data-deck-summary="" className="space-y-3 rounded-[6px] border border-seam bg-panel p-5"> + <h2 className="m-0 font-display text-[22px] font-semibold leading-tight text-text"> + {counts.kept} kept · {counts.cut} cut{counts.edited ? ` · ${counts.edited} edited` : ""} + {skip.length ? ` · ${skip.length} skipped` : ""} + </h2> + {[ + { label: "Cut", list: cut }, + { label: "Skipped", list: skip }, + ] + .filter((g) => g.list.length) + .map((g) => ( + <div key={g.label}> + <div className="micro">{g.label}</div> + <ul className="m-0 mt-1 list-none space-y-1 p-0"> + {g.list.map((a) => ( + <li key={a} data-summary-row={a} className="text-[13px] text-text-2"> + <span className="font-mono text-[11.5px] text-muted">{rowOf(a)?.entry ?? rowOf(a)?.label}</span> {rowOf(a)?.text} + {g.label === "Cut" && rowOf(a)?.note ? <span className="text-muted"> — {rowOf(a)?.note}</span> : null} + </li> + ))} + </ul> + </div> + ))} + <div className="flex flex-wrap gap-2 pt-1"> + {skip.length > 0 && ( + <button type="button" className={buttonVariants({ variant: "go", size: "md" })} onClick={() => setSkipped(new Set())}> + Review the skipped ones + </button> + )} + {cut.length > 0 && ( + <button + type="button" + className={buttonVariants({ variant: skip.length ? "outline" : "go", size: "md" })} + onClick={() => { + setQueue(cut); + setDecided((d) => { + const n = new Map(d); + for (const a of cut) n.delete(a); + return n; + }); + }} + > + Review the cut ones again + </button> + )} + <Link href={back} prefetch={false} data-deck-back="" className={buttonVariants({ variant: "outline", size: "md" })}> + Back to the Media tab + </Link> + </div> + </section> + {error && <p role="alert" className="m-0 text-[12px] text-reject-text">{error}</p>} + </div> + </main> + ); + } + + const peeks = Math.min(3, live.length - 1); + return ( + <main data-deck="" className="deck-main flex min-h-0 flex-1 flex-col p-3 pb-24 sm:p-4 md:pb-4"> + <div className="mx-auto flex w-full max-w-[520px] flex-col gap-3"> + {toggle} + <style>{DECK_CSS}</style> + <div className="relative"> + {/* The next card, underneath: its media loading already. */} + {under && ( + <div aria-hidden data-card-under={under} className="pointer-events-none absolute inset-0 z-[1] origin-top scale-[0.97] overflow-hidden rounded-[8px] border border-seam bg-panel"> + <Card address={under} row={rowOf(under)} ev={evidence[rowOf(under)?.entry ?? ""] ?? null} preload /> + </div> + )} + <div + ref={card} + key={top} + role="region" + aria-label={`${row?.label ?? "field"}${row?.entry ? ` of ${row.entry}` : ""}`} + tabIndex={-1} + data-card={top} + data-card-top="" + onPointerDown={onPointerDown} + onPointerMove={onPointerMove} + onPointerUp={onPointerUp} + onPointerCancel={() => { + start.current = null; + setDrag(null); + }} + className="deck-card deck-rise relative z-[2] touch-pan-y select-none rounded-[8px] border border-seam-2 bg-panel shadow-sm outline-none focus-visible:ring-2 focus-visible:ring-signal" + style={{ + transform, + transition: drag ? "none" : "transform 120ms ease-out", + }} + > + {stamp && stamp.o > 0.05 && ( + <span + data-stamp={stamp.kind} + aria-hidden + className={stampClass(stamp.kind)} + style={{ opacity: stamp.o }} + > + {stamp.kind} + </span> + )} + <Card + address={top} + row={row} + ev={ev} + playing={started} + clipRef={clip} + marked={misheard.get(top) ?? null} + onWord={(i) => toggleWord(top, i)} + project={project} + editing={editing === top} + editText={editText} + onEditText={setEditText} + onSaveEdit={() => void saveEdit()} + onCancelEdit={() => setEditing(null)} + back={back} + respell={respell} + busy={busy} + /> + {!started && ( + <div className="absolute inset-0 z-20 flex items-center justify-center rounded-[8px] bg-[color-mix(in_srgb,var(--ground)_55%,transparent)]"> + <button + type="button" + data-deck-start="" + className={buttonVariants({ variant: "go", size: "lg" })} + onClick={() => { + setStarted(true); + clip.current?.playSpan(); + }} + > + Start review + </button> + </div> + )} + </div> + {ghost && ( + <div + key={ghost.id} + aria-hidden + data-card-ghost={ghost.dir} + className={cn("pointer-events-none absolute inset-x-0 top-0 z-[3] overflow-hidden rounded-[8px] border border-seam-2 bg-panel shadow-sm", reduced ? "deck-fade" : `deck-out-${ghost.dir}`)} + style={{ "--dx": `${ghost.dx}px`, "--dy": `${ghost.dy}px`, "--r": `${ghost.dx * 0.04}deg` } as React.CSSProperties} + > + <span className={stampClass(ghost.dir === "right" ? "KEEP" : ghost.dir === "left" ? "CUT" : "SKIP")}>{ghost.dir === "right" ? "KEEP" : ghost.dir === "left" ? "CUT" : "SKIP"}</span> + <div className="space-y-3 p-4 sm:p-5"> + <span className="micro">{rowOf(ghost.address)?.label}</span> + <p className="m-0 font-display text-[22px] font-semibold leading-[1.2] text-text sm:text-[26px]">{rowOf(ghost.address)?.text}</p> + </div> + </div> + )} + </div> + {/* The stack's edges: as many as fields remain, up to three (depth is the truth). */} + {peeks > 0 && ( + <div aria-hidden data-deck-peeks={peeks} className="-mt-3 flex flex-col items-center"> + {Array.from({ length: peeks }, (_, i) => ( + <div key={i} className="h-[5px] rounded-b-[6px] border border-t-0 border-seam bg-panel-2" style={{ width: `${96 - i * 4}%` }} /> + ))} + </div> + )} + {/* A cut's reason: optional, one tap. */} + <div className="flex flex-wrap items-center gap-1.5" role="group" aria-label="Why cut"> + {CUT_REASONS.map((r) => ( + <button + key={r} + type="button" + data-cut-reason={r} + aria-pressed={reason === r} + onMouseDown={(e) => e.preventDefault()} + onClick={() => setReason(reason === r ? "" : r)} + className={cn( + "rounded-full border px-2 py-[2px] text-[11.5px]", + reason === r ? "border-muted bg-panel-2 text-text" : "border-seam-2 text-muted-2 hover:text-text", + )} + > + {r} + </button> + ))} + <input + value={CUT_REASONS.includes(reason) ? "" : reason} + onChange={(e) => setReason(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter") { + e.preventDefault(); + (e.target as HTMLInputElement).blur(); + decide("left"); + } + }} + placeholder="or why, in a few words" + aria-label="Why cut, in a few words" + data-cut-note="" + maxLength={300} + className="min-w-[10rem] flex-1 rounded-[3px] border border-seam-2 bg-ground px-1.5 py-[2px] text-[11.5px] text-text outline-none focus:border-signal" + /> + </div> + {error && ( + <p role="alert" data-deck-error="" className="m-0 text-[12px] text-reject-text"> + {error} + </p> + )} + {/* Every gesture is a button too: a bar under the thumb on a phone. */} + <nav + aria-label="Decide" + className="fixed inset-x-0 bottom-0 z-30 grid grid-cols-5 gap-1.5 border-t border-seam bg-ground p-2 md:static md:z-auto md:border-0 md:bg-transparent md:p-0" + > + <DeckButton action="undo" label="Undo" k="z" disabled={!undos.length || busy} onClick={() => void undo()} /> + <DeckButton action="cut" label="Cut" k="←" disabled={busy} onClick={() => decide("left")} /> + <DeckButton action="edit" label="Edit" k="↑" disabled={busy} onClick={() => decide("up")} /> + <DeckButton action="skip" label="Skip" k="↓" disabled={busy} onClick={() => decide("down")} /> + <DeckButton action="keep" label="Keep" k="→" go disabled={busy} onClick={() => decide("right")} /> + </nav> + {/* The one hint row: it fades once three cards are decided; `?` brings it back. */} + <p + data-deck-hint={hintShown ? "shown" : "hidden"} + aria-hidden={!hintShown} + className={cn("m-0 hidden text-center font-mono text-[11px] text-muted transition-opacity duration-500 md:block", hintShown ? "opacity-100" : "opacity-0")} + > + ← cut · ↑ edit · ↓ skip · keep → · space replays · z undoes · ? keys + </p> + </div> + </main> + ); +} + +function DeckButton({ action, label, k, go = false, disabled, onClick }: { action: string; label: string; k: string; go?: boolean; disabled?: boolean; onClick: () => void }) { + return ( + <button + type="button" + data-deck-action={action} + disabled={disabled} + aria-label={`${label} (${k})`} + onMouseDown={(e) => e.preventDefault()} + onClick={onClick} + className={cn(buttonVariants({ variant: go ? "go" : "outline", size: "lg" }), "flex-col gap-0 px-1 py-2 md:flex-row md:gap-1.5")} + > + <span>{label}</span> + <kbd className="hidden md:inline">{k}</kbd> + </button> + ); +} + +/** One field's card: what is judged, the span playing, the lit line, where it came from. */ +function Card({ + address, + row, + ev, + preload = false, + playing = false, + clipRef, + marked = null, + onWord, + project, + editing = false, + editText = "", + onEditText, + onSaveEdit, + onCancelEdit, + back, + respell = null, + busy = false, +}: { + address: string; + row: DraftRow | null; + ev: FieldEvidence | null; + preload?: boolean; + playing?: boolean; + clipRef?: React.Ref<CitedClipHandle>; + marked?: Set<number> | null; + onWord?: (i: number) => void; + project?: string; + editing?: boolean; + editText?: string; + onEditText?: (s: string) => void; + onSaveEdit?: () => void; + onCancelEdit?: () => void; + back?: string; + respell?: string | null; + busy?: boolean; +}) { + const [now, setNow] = useState<number | null>(null); + const t = ev?.target ?? null; + const words = useMemo(() => (ev?.quote && t ? spokenWords(ev.quote, ev.cues, t.from, t.to) : []), [ev, t]); + const lit = now === null ? 0 : litCount(words, now); + const value = row?.text ?? ""; + const editable = row ? isEditableField(row.field) : false; + const misheardWords = marked?.size ? [...marked].map((i) => words[i]?.text).filter(Boolean) : []; + + return ( + <div className="flex flex-col gap-3 p-4 sm:p-5" data-card-body={address}> + <div className="flex items-baseline gap-2"> + <span className="micro">{row?.label ?? address}</span> + {row?.entry && <span className="font-mono text-[11px] text-muted">{row.entry}</span>} + </div> + {editing && !editable ? ( + <div className="space-y-1.5" data-card-edit-elsewhere=""> + <p data-card-value="" className="m-0 whitespace-pre-line font-display text-[22px] font-semibold leading-[1.2] text-text"> + {value} + </p> + <p className="m-0 text-[12px] text-text-2"> + This field is edited in its own section:{" "} + <Link href={back ?? "#"} prefetch={false} className="ink-link"> + the Media tab + </Link> + .{" "} + <button type="button" onClick={onCancelEdit} className="ink-link"> + Back to the card + </button> + </p> + </div> + ) : editing ? ( + <div className="space-y-1.5"> + <textarea + autoFocus + data-card-edit="" + aria-label={`Edit the ${row?.label ?? "field"}`} + value={editText} + onChange={(e) => onEditText?.(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter" && !e.shiftKey) { + e.preventDefault(); + onSaveEdit?.(); + } + }} + rows={Math.max(2, editText.split("\n").length)} + className="w-full resize-y rounded-[3px] border border-signal bg-ground px-2 py-1.5 font-display text-[20px] leading-snug text-text outline-none" + /> + <div className="flex flex-wrap items-center gap-2 text-[11.5px] text-muted"> + <button type="button" data-card-save="" disabled={busy} onClick={onSaveEdit} className={buttonVariants({ variant: "go", size: "sm" })}> + Keep as edited <kbd>Enter</kbd> + </button> + <button type="button" onClick={onCancelEdit} className={buttonVariants({ variant: "ghost", size: "sm" })}> + Cancel <kbd>Esc</kbd> + </button> + <span>Shift+Enter for a new line{row?.field === "onscreen" ? " (line 2 is the subtitle)" : row?.field === "lines" ? " (one teaser line each)" : ""}</span> + {misheardWords.length > 0 && respell && ( + <a + data-fix-mishearing="" + href={`${respell}${respell.includes("?") ? "&" : "?"}heard=${encodeURIComponent(misheardWords.join(","))}`} + className="ink-link" + > + fix this mishearing + </a> + )} + </div> + </div> + ) : ( + <p data-card-value="" className="m-0 whitespace-pre-line font-display text-[22px] font-semibold leading-[1.2] text-text sm:text-[26px]"> + {value || <span className="text-muted">(empty)</span>} + </p> + )} + {t ? ( + <CitedClip + key={`${address}|${t.from}|${t.to}`} + ref={clipRef} + target={t} + face="card" + preload={preload} + autoPlay={playing && !preload} + reason={`umtool drafts review ${project ?? ""} ${row?.entry ?? ""}`.trim()} + report={project} + onTime={setNow} + /> + ) : ( + <p className="m-0 text-[12px] text-muted">{ev ? "No source on disk names this clip's recording." : "Not drawn over a clip: read it against the report."}</p> + )} + {words.length > 0 && ( + <p data-lit-quote="" className="m-0 font-serif text-[17px] leading-[1.45] text-text-2"> + “ + {words.map((w, i) => ( + <span key={i}> + <button + type="button" + data-word={i} + data-lit={i < lit ? "" : undefined} + data-misheard={marked?.has(i) ? "" : undefined} + aria-pressed={!!marked?.has(i)} + title={marked?.has(i) ? "marked misheard: tap to unmark" : "tap to mark misheard"} + onClick={() => onWord?.(i)} + className={cn( + "rounded-[2px] px-0 text-left decoration-2 underline-offset-[5px] outline-none focus-visible:ring-2 focus-visible:ring-signal", + i < lit ? "text-text underline decoration-signal" : "", + marked?.has(i) ? "bg-panel-2 line-through decoration-muted" : "", + )} + > + {w.text} + </button> + {i < words.length - 1 ? " " : ""} + </span> + ))} + ” + </p> + )} + {ev && ( + <div className="space-y-0.5 text-[12px] text-muted"> + <div className="truncate text-text-2">{ev.source}</div> + <div className="font-mono text-[11px]">{[ev.speaker, ...ev.byline].filter(Boolean).join(" · ")}</div> + </div> + )} + {row?.drafted && ( + <div className="font-mono text-[11px] text-muted" data-card-drafted=""> + drafted by {row.drafted.model} · {row.drafted.task} + </div> + )} + </div> + ); +} diff --git a/umtool/e2e/bench-shell.spec.ts b/umtool/e2e/bench-shell.spec.ts @@ -134,7 +134,7 @@ test("the claim bench: its context on the reader, the cited cue lit, j/k from an }); 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 page.goto(urls.reviewHref(REVIEW, { view: "list" })); 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]"); diff --git a/umtool/e2e/draft-review.spec.ts b/umtool/e2e/draft-review.spec.ts @@ -69,6 +69,9 @@ test("the review page: every drafted field, the narration's badge, and Use this await page.goto(urls.section(PROJECT, "review")); await page.locator("[data-review-link]").click(); await expect(page).toHaveURL(new RegExp(`/projects/${PROJECT}/review$`)); + // The review opens on the audition deck (release 32 R1); this walks the list. + await page.locator("[data-review-view=list]").click(); + await expect(page).toHaveURL(new RegExp(`/projects/${PROJECT}/review\\?view=list$`)); // The narration and the teaser are drafted; a final build would refuse them. const k01 = page.locator('[data-draft-row="narrate/k01/narration"]'); await expect(k01).toHaveAttribute("data-state", "unreviewed"); @@ -115,7 +118,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(urls.reviewHref(BUILD_PROJECT)); + await page.goto(urls.reviewHref(BUILD_PROJECT, { view: "list" })); const row = page.locator('[data-draft-row="onscreen/c02/onscreen"]'); await row.locator('[data-draft-action="approve"]').click(); await expect(row).toHaveAttribute("data-state", "approved"); diff --git a/umtool/e2e/fixtures/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 { makeReviewPlayerFixture } from "./review-player-fixture.mjs"; import { makeBenchShellFixture } from "./bench-shell-fixture.mjs"; import { makeYoutubeFixture } from "./youtube-fixture.mjs"; import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs"; @@ -1690,6 +1691,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") }); +// Release 32 R1: the audition deck, one window on disk and one fetched (review-player.spec.ts). +makeReviewPlayerFixture({ reports, channels: CHANNELS, 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). diff --git a/umtool/e2e/fixtures/review-player-fixture.mjs b/umtool/e2e/fixtures/review-player-fixture.mjs @@ -0,0 +1,65 @@ +// What review-player.spec.ts walks (release 32 R1): the drafts review's +// audition deck over a cut whose first cited window is on disk and whose +// second is not. Its own project and its own source (vid8), so a fetch here +// never makes another spec's window "already cached". +// +// reports/review-player-fixture/ +// p01 on-screen text DRAFTED over vid1 3-6 s: the project's cached window +// (out/clips-raw/vid1_0.00-9.00.mp4) plays it +// p02 on-screen text DRAFTED over vid8 3-6 s: nothing on disk until Fetch +// clip asks the editor stub, which writes the window into the corpus +// k01 a chapter card whose narration was DRAFTED: no clip, edited on the card +// +// Synthetic, like every fixture. +import { copyFileSync, mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +const AT = "2026-10-16T10:00:00.000Z"; +const P = (task, model = "qwen3:8b") => ({ task, model, at: AT, iteration: 1, attempt: 1 }); + +const write = (dir, name, doc) => { + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, name), JSON.stringify(doc, null, 2) + "\n"); +}; + +/** + * @param {{ reports: string, channels: string, manifest: Function, cachedWindow: string }} o + */ +export function makeReviewPlayerFixture({ reports, channels, manifest, cachedWindow }) { + const rows = [ + [0, 3, "The review fixture opens."], + [3, 6, "This is the sentence the second card cites."], + [6, 9, "And nothing else on the disk holds it."], + ]; + write(path.join(channels, "testchan", "data", "vid8"), "transcript.cues.json", { + title: "Fixture source vid8", + uploadDate: "20250101", + channel: "Fixture Channel", + webpageUrl: "https://example.invalid/watch?v=vid8", + duration: 9, + cues: rows.map(([start, end, text]) => ({ start, end, text })), + }); + + const dir = path.join(reports, "review-player-fixture"); + write( + dir, + "video.manifest.json", + manifest("review-player-fixture", "The Review Player Fixture", { siteOrigin: "https://archive.example" }, [ + { + type: "clip", id: "p01", video: "vid1", start: 3.0, end: 6.0, cite: 3, section: 0, lock: true, quote: "And this one runs on and because", + onscreen: { title: "On disk title" }, drafted: { onscreen: P("onscreen") }, + }, + { + type: "clip", id: "p02", video: "vid8", start: 3.0, end: 6.0, cite: 3, section: 0, lock: true, quote: "This is the sentence the second card cites.", + onscreen: { title: "Fetched title" }, drafted: { onscreen: P("onscreen", "claude-sonnet-5-5") }, + }, + { + type: "card", id: "k01", style: "chapter", seconds: "auto", heading: "Later", + narration: { text: "A drafted narration line." }, drafted: { narration: P("narrate") }, + }, + ]), + ); + mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); + copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", path.basename(cachedWindow))); + return { dir }; +} diff --git a/umtool/e2e/review-player.spec.ts b/umtool/e2e/review-player.spec.ts @@ -0,0 +1,124 @@ +import { test, expect } from "@playwright/test"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// Verify by playing the citation (release 32 R1). The drafts review is an +// audition deck: card 1's cited window is on disk and is its player's video; +// → keeps it (drafts.review.json); card 2's window is not on disk -- Fetch +// clip asks the editor stub, and the card plays what it wrote; ← cuts, z +// undoes, a reason chip rides in the note; ↑ edits the narration on the card; +// the list shows the same verdicts. And the article page's Verify quotes / +// Check report, each quote with its own Play. Fixtures: +// e2e/fixtures/review-player-fixture.mjs, sites-fixture.mjs (priv/polemic-alpha). +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const PROJECT = "reports/review-player-fixture"; +const DIR = path.join(FIXTURE, "reports", "review-player-fixture"); +const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); + +type Verdict = { verdict: string | null; note: string }; +const review = (): Record<string, Verdict> => { + const f = path.join(DIR, "drafts.review.json"); + if (!existsSync(f)) return {}; + const doc = JSON.parse(readFileSync(f, "utf8")) as { rows?: Record<string, Verdict> } & Record<string, Verdict>; + return doc.rows ?? doc; +}; +const manifest = () => JSON.parse(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")) as { timeline: { id: string; narration?: { text: string }; drafted?: unknown }[] }; + +test("the audition deck: play the span, keep, fetch a missing clip, cut, undo, edit; the list agrees", async ({ page, request }) => { + test.setTimeout(120_000); + await page.setViewportSize({ width: 1366, height: 900 }); + await page.goto(urls.reviewHref(PROJECT)); + const card = page.locator("[data-card-top]"); + await expect(card).toHaveAttribute("data-card", "onscreen/p01/onscreen"); + await expect(card.locator("[data-card-value]")).toHaveText("On disk title"); + await expect(card.locator("[data-card-drafted]")).toHaveText("drafted by qwen3:8b · onscreen"); + await expect(page.locator("[data-deck-count]")).toContainText("1 / 3 · 0 kept · 0 cut"); + // One counter and one hint row, the deck's own: none in the bench's top bar. + await expect(page.locator("[data-bench-top] [data-bench-keys]")).toHaveCount(0); + await expect(page.locator("[data-bench-top]")).not.toContainText("to review"); + await expect(page.locator("[data-deck-hint]")).toHaveAttribute("data-deck-hint", "shown"); + + // Video first: the project's cached window, served with ranges. + await expect(card.locator("[data-play]")).toHaveAttribute("data-play", "window", { timeout: 15_000 }); + const video = card.locator("video[data-player]"); + await expect(video).toHaveAttribute("src", /\/api\/report\/raw\?.*file=vid1_0\.00-9\.00\.mp4/); + const res = await request.get((await video.getAttribute("src"))!, { headers: { range: "bytes=0-99" } }); + expect(res.status()).toBe(206); + // The lit line: the quote, word by word. + await expect(card.locator("[data-lit-quote] [data-word]")).toHaveCount(7); + + // Start (the gesture that lets every card play itself), then → keeps it. + await page.locator("[data-deck-start]").click(); + await expect(page.locator("[data-deck-start]")).toHaveCount(0); + await page.keyboard.press("ArrowRight"); + await expect.poll(() => review()["onscreen/p01/onscreen"]?.verdict).toBe("approved"); + + // Card 2: nothing on disk. Fetch clip asks the editor as fetch_clip does, then plays it. + await expect(card).toHaveAttribute("data-card", "onscreen/p02/onscreen"); + await expect(card.locator("[data-play]")).toHaveAttribute("data-play", "none"); + await card.locator("[data-fetch-clip]").click(); + await expect(card.locator("[data-play]")).toHaveAttribute("data-play", "window", { timeout: 30_000 }); + await expect(card.locator("video[data-player]")).toHaveAttribute("src", /\/api\/(report\/raw|sites\/media)\?/); + const asked = (JSON.parse(readFileSync(STUB_LOG, "utf8")) as Record<string, unknown>[]).filter((q) => q.videoId === "vid8"); + expect(asked.at(-1)).toMatchObject({ channelSlug: "testchan", videoId: "vid8", from: 0, to: 9, pad: 3, requestedBy: "umtool" }); + + // A word marked misheard rides in the note; ← cuts, z undoes. + await card.locator('[data-word="0"]').click(); + await expect(card.locator('[data-word="0"]')).toHaveAttribute("data-misheard", ""); + await page.locator("body").press("ArrowLeft"); + await expect.poll(() => review()["onscreen/p02/onscreen"]?.verdict).toBe("rejected"); + expect(review()["onscreen/p02/onscreen"].note).toBe("cut on the deck · misheard: This"); + await page.locator("body").press("z"); + await expect.poll(() => review()["onscreen/p02/onscreen"]?.verdict ?? null).toBeNull(); + await expect(card).toHaveAttribute("data-card", "onscreen/p02/onscreen"); + await page.locator('[data-cut-reason="wrong moment"]').click(); + await page.locator('[data-deck-action="cut"]').click(); + await expect.poll(() => review()["onscreen/p02/onscreen"]?.note).toBe("wrong moment · misheard: This"); + + // Card 3: a narration with no clip. ↑ edits it on the card; Enter keeps it as edited. + await expect(card).toHaveAttribute("data-card", "narrate/k01/narration"); + await expect(card).toContainText("Not drawn over a clip"); + await page.locator("body").press("ArrowUp"); + const edit = card.locator("[data-card-edit]"); + await expect(edit).toHaveValue("A drafted narration line."); + await edit.fill("A narration line, said better."); + await edit.press("Enter"); + await expect.poll(() => manifest().timeline.find((e) => e.id === "k01")?.narration?.text).toBe("A narration line, said better."); + await expect.poll(() => review()["narrate/k01/narration"]?.verdict).toBe("approved"); + + // The deck's end: what was cut, and the way back. + const summary = page.locator("[data-deck-summary]"); + await expect(summary).toContainText("1 kept · 1 cut · 1 edited"); + await expect(summary.locator('[data-summary-row="onscreen/p02/onscreen"]')).toContainText("Fetched title"); + + // The list shows the same verdicts. + await page.locator("[data-review-view=list]").click(); + await expect(page).toHaveURL(/\/review\?view=list$/); + await expect(page.locator('[data-draft-row="onscreen/p01/onscreen"]')).toHaveAttribute("data-state", "approved"); + await expect(page.locator('[data-draft-row="onscreen/p02/onscreen"]')).toHaveAttribute("data-state", "rejected"); +}); + +test("the article page: Verify quotes plays each quote; Check report says what compose would", async ({ page }) => { + await page.goto(urls.articleHref({ site: "priv", id: "polemic-alpha" }, { tab: "article" })); + const checks = page.locator("[data-article-checks]"); + await checks.locator('[data-check="quotes"]').click(); + const quotes = page.locator("[data-quote-checks]"); + await expect(quotes).toHaveAttribute("data-quote-checks", "2", { timeout: 30_000 }); + const c1 = quotes.locator('[data-quote-check="c1"]'); + await expect(c1).toHaveAttribute("data-status", /.+/); + await expect(c1).toContainText("The vote was rigged and everybody knew."); + await c1.locator("[data-check-play]").click(); + await expect(c1.locator("[data-play]")).toHaveAttribute("data-play", "window", { timeout: 15_000 }); + await expect(c1.locator("video[data-player]")).toHaveAttribute("src", /corpus=.*sv1.*clips/); + + await checks.locator('[data-check="check"]').click(); + const check = page.locator("[data-report-check]"); + await expect(check).toBeVisible({ timeout: 60_000 }); + await expect(check.locator("[data-check-summary]")).toContainText(/compose would (pass|fail)/); +}); diff --git a/umtool/e2e/running.spec.ts b/umtool/e2e/running.spec.ts @@ -221,6 +221,9 @@ test.describe("drafts in the Inbox", () => { await expect(card.locator("small")).toHaveText("by qwen3:8b"); await card.locator("[data-action-link]").click(); await expect(page).toHaveURL(new RegExp(`/projects/${DRAFTS}/review$`)); + // The review opens on the audition deck (release 32 R1); the list is one toggle away. + await page.locator("[data-review-view=list]").click(); + await expect(page).toHaveURL(new RegExp(`/projects/${DRAFTS}/review\\?view=list$`)); for (const address of ["onscreen/c01/onscreen", "narrate/k01/narration", "narrate/k02/narration"]) { const row = page.locator(`[data-draft-row="${address}"]`); diff --git a/umtool/e2e/visual-audit.spec.ts b/umtool/e2e/visual-audit.spec.ts @@ -52,7 +52,7 @@ const PAGES: [string, string][] = [ ["bench-claim", urls.claimBenchHref("reports/bench-fixture", "k01")], ["bench-narration", urls.narrationHref("reports/narration-review-fixture")], ["bench-takes", urls.takesHref("reports/takes-fixture")], - ["bench-review", urls.reviewHref("reports/media-review-fixture")], + ["bench-review", urls.reviewHref("reports/media-review-fixture", { view: "list" })], ["create", urls.createHref()], ...(["research", "article", "article-board", "recurring", "video-article", "video-board", "video-recording", "video-report", "song"] as const).map( (make) => [`create-${make}`, urls.createHref({ make })] as [string, string], diff --git a/umtool/lib/articles/checks.ts b/umtool/lib/articles/checks.ts @@ -0,0 +1,98 @@ +import { checkReports, verifyReportQuotes, type QuoteResult, type ReportsCheckProblem } from "yt-dlp-transcript-common/bin/reports-check"; +import type { Report } from "yt-dlp-transcript-common/lib/report/schema"; +import type { CitedTarget } from "@/lib/clips/types"; +import { ARTICLES_KEY } from "@/lib/paths"; +import { readReportFile, sitesPaths } from "./sites"; + +// --------------------------------------------------------------------------- +// VERIFY QUOTES and CHECK REPORT on the article page (release 32 R1): the CLI's +// `archilyzer reports verify-quotes --article <id>` and `reports check +// --article <id>` (a site's report: `reports check <site> --reports <id>`), run +// in-process through the same functions (common/bin/reports-check.ts) over +// umtool's roots. No model, no subprocess. Respellings apply (the report's +// own, as the check applies them). Each quote and each problem that names a +// span carries what plays it, so a person can hear it. +// --------------------------------------------------------------------------- + +export type QuoteRow = QuoteResult & { quote: string; target: CitedTarget | null }; +export type QuoteChecks = { what: "quotes"; report: string; rows: QuoteRow[]; counts: Record<string, number>; invalid: string[] }; +export type CheckProblemRow = ReportsCheckProblem & { quote?: string; target?: CitedTarget | null }; +export type ReportCheck = { + what: "check"; + report: string; + status: "pass" | "fail" | "usage" | "empty" | "error"; + summary: string; + problems: CheckProblemRow[]; + allowed: string[]; + warnings: string[]; +}; + +type Cite = NonNullable<Report["citations"]>[string]; +const targetOfCite = (c: Cite | undefined): CitedTarget | null => + c && (c.kind === "video" || c.kind === "audio") && Number.isFinite(c.start) && Number.isFinite(c.end) && c.start < c.end + ? { channel: c.channel, video: c.id, from: c.start, to: c.end, ...(c.kind === "audio" ? { audio: true } : {}) } + : null; + +async function reportOf(site: string, reportId: string): Promise<Report> { + const read = await readReportFile(site, reportId); + if (!read.report) throw Object.assign(new Error(read.problems[0]?.message ?? "no report"), { status: 404 }); + return read.report; +} + +export async function articleQuoteChecks(site: string, reportId: string, opts: { now?: string } = {}): Promise<QuoteChecks> { + const report = await reportOf(site, reportId); + const results = await verifyReportQuotes(report, { paths: sitesPaths(), ...(opts.now ? { now: opts.now } : {}) }); + const counts: Record<string, number> = {}; + for (const r of results) counts[r.status] = (counts[r.status] ?? 0) + 1; + return { + what: "quotes", + report: reportId, + rows: results.map((r) => { + const c = report.citations?.[r.citation]; + return { ...r, quote: c?.quote ?? "", target: targetOfCite(c) }; + }), + counts, + invalid: [], + }; +} + +export async function articleReportCheck(site: string, reportId: string, opts: { allowMissingMedia?: boolean } = {}): Promise<ReportCheck> { + const report = await reportOf(site, reportId); + const paths = sitesPaths(); + const allowMissingMedia = opts.allowMissingMedia === true; + const r = + site === ARTICLES_KEY + ? await checkReports({ article: reportId, paths, allowMissingMedia }) + : await checkReports({ siteId: site, reports: [reportId], paths, allowMissingMedia }); + const base = { what: "check" as const, report: reportId, problems: [] as CheckProblemRow[], allowed: [] as string[], warnings: [] as string[] }; + switch (r.status) { + case "usage": + case "error": + return { ...base, status: r.status, summary: r.error }; + case "empty": + return { ...base, status: "empty", summary: "nothing published to check" }; + case "pass": { + const me = r.reports.find((x) => x.id === reportId); + return { + ...base, + status: "pass", + summary: + `compose would pass: ${me ? `${me.quotes} quote(s) checked${me.lowest === null ? "" : `, lowest ${me.lowest.toFixed(2)}`}` : `${r.reports.length} report(s)`}, ` + + `${r.moments} moment(s)`, + allowed: r.allowed, + warnings: r.warnings, + }; + } + case "fail": + return { + ...base, + status: "fail", + summary: `compose would fail: ${r.problems.length} problem(s)`, + problems: r.problems.map((p) => { + const cid = p.citation?.startsWith(`${reportId}#`) ? p.citation.slice(reportId.length + 1) : null; + const c = cid ? report.citations?.[cid] : undefined; + return { ...p, ...(c ? { quote: c.quote, target: targetOfCite(c) } : {}) }; + }), + }; + } +} diff --git a/umtool/lib/articles/evidence.ts b/umtool/lib/articles/evidence.ts @@ -2,10 +2,11 @@ import { readFile } from "node:fs/promises"; import path from "node:path"; import type { Report } from "yt-dlp-transcript-common/lib/report/schema"; import { momentKeyOf } from "yt-dlp-transcript-common/lib/citations/moments"; -import { evidenceSpan, resolveEvidenceSource } from "yt-dlp-transcript-common/lib/evidenceClip-server"; +import { evidenceSpan } from "yt-dlp-transcript-common/lib/evidenceClip-server"; import { storeMediaDir, storeMediaIndexFile } from "yt-dlp-transcript-common/publish/reportMedia"; import { readCues } from "@/lib/projects/report.mjs"; -import { CHANNELS_DIR } from "@/lib/paths"; +import { corpusPlay } from "@/lib/clips/cited"; +import type { CitedPlay } from "@/lib/clips/types"; import { channelPosts, corpusMediaUrl, postShotFile, recordDir, recordMeta } from "./article"; import { storeFor } from "./sites"; @@ -18,23 +19,16 @@ import { storeFor } from "./sites"; // 2. window a clip window the editor fetched into data/<id>/clips/; // 3. saved a saved video or audio file in data/<id>/ (through its media // tier link -- read, never written); -// 4. otherwise nothing to play, and the line that fetches it through the -// editor: the MCP `fetch_clip` tool. umtool's own fetch client -// (api/report/fetch) is a manifest's, so it cannot ask for a -// window no project names. Never yt-dlp. +// 4. otherwise nothing to play: the panel's player (components/clips/ +// CitedClip.tsx) offers Fetch clip -- the editor's fetch-window +// through /api/cited/fetch, as the MCP's fetch_clip asks (release +// 32 R1) -- and the MCP line for the same seconds. Never yt-dlp. export const CONTEXT_CUES = 6; export type EvidenceCue = { start: number; end: number; text: string; cited: boolean }; -export type EvidencePlay = { - kind: "prepared" | "window" | "saved" | "audio"; - url: string; - /** Seconds into the file where the cited span starts. */ - offset: number; - audio: boolean; - label: string; -}; +export type EvidencePlay = CitedPlay; export type Evidence = { cite: string; @@ -107,22 +101,11 @@ async function preparedClip(siteId: string, c: Cite): Promise<EvidencePlay | nul } } +// The corpus's own media for the span (lib/clips/cited.ts, shared with the +// review deck's player). async function corpusClip(c: Cite): Promise<EvidencePlay | null> { if (c.kind !== "video" && c.kind !== "audio") return null; - const span = { from: c.start, to: c.end }; - for (const audio of c.kind === "audio" ? [true] : [false, true]) { - const hit = await resolveEvidenceSource({ channelsDir: CHANNELS_DIR, slug: c.channel, id: c.id, span, audio }).catch(() => null); - if (!hit) continue; - const kind = hit.kind === "corpus-window" ? "window" : hit.kind === "saved-video" ? "saved" : "audio"; - return { - kind, - url: corpusMediaUrl(hit.path), - offset: Math.max(0, c.start - hit.windowStart), - audio: hit.kind === "audio", - label: kind === "window" ? `clip window ${hit.name}` : kind === "saved" ? `saved ${hit.name}` : `audio ${hit.name}`, - }; - } - return null; + return corpusPlay({ channel: c.channel, video: c.id, from: c.start, to: c.end, ...(c.kind === "audio" ? { audio: true } : {}) }); } /** The MCP line that fetches this span through the editor. */ diff --git a/umtool/lib/clips/cited.test.ts b/umtool/lib/clips/cited.test.ts @@ -0,0 +1,73 @@ +// The cited clip's server half (release 32 R1): a span's target parsed, a +// fetch asked of a fake editor exactly as fetch_clip asks, queued then polled +// to ready, and a refusal said in plain words. No network: the editor is a +// function. +// +// Run with: pnpm --filter umtool exec tsx --test lib/clips/cited.test.ts +import { before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +let lib: typeof import("./cited"); + +before(async () => { + process.env.CHANNELS_DIR = path.join(await mkdtemp(path.join(os.tmpdir(), "umtool-cited-")), "channels"); + lib = await import("./cited"); +}); + +type Call = { url: string; body: Record<string, unknown> | null }; +function editor(answers: ((c: Call) => { status: number; body: unknown })[]) { + const calls: Call[] = []; + let i = 0; + return { + calls, + deps: { + env: { ARCHILYZER_EDITOR_URL: "http://editor.invalid", WORKER_TOKEN: "t" } as unknown as NodeJS.ProcessEnv, + fetch: async (url: string, init?: { body?: string }) => { + const call = { url, body: init?.body ? JSON.parse(init.body) : null }; + calls.push(call); + const a = answers[Math.min(i++, answers.length - 1)](call); + return { status: a.status, json: async () => a.body }; + }, + sleep: async () => {}, + now: () => 0, + }, + }; +} + +test("a target: corpus directories and a span, the project's clip only as a pair", () => { + const t = lib.targetOf((k) => ({ channel: "chan", video: "v1", from: "3", to: "6.5", project: "reports/p" })[k as "channel"]); + assert.deepEqual(t, { channel: "chan", video: "v1", from: 3, to: 6.5 }); + assert.throws(() => lib.targetOf((k) => ({ channel: "..", video: "v1", from: 1, to: 2 })[k as "channel"]), /channel/); + assert.throws(() => lib.targetOf((k) => ({ channel: "c", video: "v", from: 5, to: 2 })[k as "channel"]), /from < to/); +}); + +test("fetch asks the editor as fetch_clip does (umtool, padded window), then a poll is ready", async () => { + const e = editor([() => ({ status: 202, body: { cached: false, jobId: "j1", from: 0, to: 9 } })]); + const target = { channel: "chan", video: "v1", from: 3, to: 6 }; + const q = await lib.fetchCitedClip({ target, reason: "review" }, e.deps); + assert.deepEqual(q, { state: "queued", job: "j1", status: "queued" }); + assert.equal(e.calls[0].url, "http://editor.invalid/api/media/fetch-window"); + assert.deepEqual( + { ...e.calls[0].body }, + { channelSlug: "chan", videoId: "v1", from: 0, to: 9, pad: 3, requestedBy: "umtool", reason: "review" }, + ); + const p = editor([() => ({ status: 200, body: { status: "done", file: "/x/clips/0.00-9.00.mp4", from: 0, to: 9 } })]); + const ready = await lib.fetchCitedClip({ job: "j1", target }, p.deps); + assert.equal(p.calls[0].url, "http://editor.invalid/api/media/fetch-window/j1"); + // Nothing in this empty corpus to play: ready, and the player says so. + assert.deepEqual(ready, { state: "ready", cached: false, from: 0, to: 9, play: null }); +}); + +test("a cooldown says the platform is rate-limiting; an audio-check failure says corrupt audio", async () => { + const target = { channel: "chan", video: "v1", from: 3, to: 6 }; + const c = editor([() => ({ status: 409, body: { error: "youtube is in a rate-limit cooldown (42s remaining).", cooldownMs: 42000, platform: "youtube" } })]); + const r = await lib.fetchCitedClip({ target, reason: "review" }, c.deps); + assert.equal(r.state, "failed"); + assert.equal(r.state === "failed" && r.message, "youtube is rate-limiting fetches: try again later."); + const m = editor([() => ({ status: 200, body: { status: "failed", error: "The audio check found the window 0.00–9.00 of v1 malformed" } })]); + const f = await lib.fetchCitedClip({ job: "j2", target }, m.deps); + assert.match(f.state === "failed" ? f.message : "", /corrupt audio/); +}); diff --git a/umtool/lib/clips/cited.ts b/umtool/lib/clips/cited.ts @@ -0,0 +1,148 @@ +import { + fetchClip, + validateFetchClipArgs, + type FetchClipDeps, +} from "yt-dlp-transcript-mcp/research"; +import { resolveEvidenceSource } from "yt-dlp-transcript-common/lib/evidenceClip-server"; +import { CHANNELS_DIR } from "@/lib/paths"; +import { answerOf } from "@/lib/research/fetch"; +import { SourceError } from "@/lib/research/sources"; +import { projectCache, resolveClip, windowsFor } from "@/lib/report/serve.mjs"; +import { corpusMediaUrl } from "@/lib/articles/article"; +import type { CitedFetchAnswer, CitedPlay, CitedTarget } from "./types"; +import { fetchFailureSentence } from "./words"; + +// --------------------------------------------------------------------------- +// THE CITED CLIP, server side (release 32 R1): what plays a cited span, and +// the one button that fetches it when nothing does. +// +// Playback, best first -- found, never fetched: +// 1. a project's own cached window (out/clips-raw, or a corpus window the +// project's cache counts), when the span is a project's clip: served by +// /api/report/raw, which the clip bench plays too; +// 2. a clip window the editor fetched into data/<id>/clips/; +// 3. a saved video in data/<id>/ (through its media-tier link); +// 4. audio, labelled "audio only". +// The prepared evidence clip of a site (lib/articles/evidence.ts) comes before +// all of these on the article pages; it is that module's. +// +// FETCH asks the editor's fetch-window route exactly as the MCP's fetch_clip +// asks (requestedBy "umtool"), never yt-dlp. The corpus's channel and video +// directories ARE the editor's, so no source lookup stands between: the +// editor resolves the page URL from the record. The route never waits: a +// queued fetch is polled by job id. +// --------------------------------------------------------------------------- + +const WIN_EPS = 0.02; + +/** The corpus's own media for a span: a window, a saved video, or audio. */ +export async function corpusPlay(t: CitedTarget, channelsDir: string = CHANNELS_DIR): Promise<CitedPlay | null> { + const span = { from: t.from, to: t.to }; + for (const audio of t.audio ? [true] : [false, true]) { + const hit = await resolveEvidenceSource({ channelsDir, slug: t.channel, id: t.video, span, audio }).catch(() => null); + if (!hit) continue; + const kind = hit.kind === "corpus-window" ? "window" : hit.kind === "saved-video" ? "saved" : "audio"; + return { + kind, + url: corpusMediaUrl(hit.path), + offset: Math.max(0, t.from - hit.windowStart), + audio: hit.kind === "audio", + label: kind === "window" ? `clip window ${hit.name}` : kind === "saved" ? `saved ${hit.name}` : `audio ${hit.name}`, + }; + } + return null; +} + +/** A project clip's own cached window holding the span, served through /api/report/raw. */ +async function projectPlay(t: CitedTarget): Promise<CitedPlay | null> { + if (!t.project || !t.clip || t.audio) return null; + const r = await resolveClip(t.project, t.clip).catch(() => null); + if (!r || "error" in r) return null; + const cache = await projectCache(r.project, r.manifest); + const windows = (await windowsFor(r.project, { ...r.clip, start: t.from, end: t.to }, cache)) as { name: string; from: number; to: number }[]; + const win = windows.find((w) => w.from <= t.from + WIN_EPS && w.to >= t.to - WIN_EPS); + if (!win) return null; + return { + kind: "window", + url: `/api/report/raw?${new URLSearchParams({ project: t.project, clip: t.clip, file: win.name })}`, + offset: Math.max(0, t.from - win.from), + audio: false, + label: `clip window ${win.name}`, + }; +} + +/** What plays the span now, or null (nothing on disk: offer Fetch clip). */ +export async function findCitedPlay(t: CitedTarget): Promise<CitedPlay | null> { + return (await projectPlay(t)) ?? (await corpusPlay(t)); +} + +/** Parse a target from a query string or a JSON body; throws a 400 in words. */ +export function targetOf(get: (k: string) => unknown): CitedTarget { + const s = (k: string) => { + const v = get(k); + return typeof v === "string" ? v.trim() : typeof v === "number" ? String(v) : ""; + }; + const channel = s("channel"); + const video = s("video"); + const from = Number(s("from")); + const to = Number(s("to")); + const id = /^[\w.-]+$/; + if (!id.test(channel) || channel === "." || channel === "..") throw new SourceError("channel must be a channel directory"); + if (!id.test(video) || video === "." || video === "..") throw new SourceError("video must be a video directory"); + if (!Number.isFinite(from) || !Number.isFinite(to) || from < 0 || !(from < to)) throw new SourceError("from and to must be seconds, from < to"); + const project = s("project"); + const clip = s("clip"); + return { + channel, + video, + from, + to, + ...(project && clip ? { project, clip } : {}), + ...(s("audio") === "1" || get("audio") === true ? { audio: true } : {}), + }; +} + +const deps: FetchClipDeps = { + env: process.env, + fetch: (url, init) => globalThis.fetch(url, init), + sleep: (ms) => new Promise((r) => setTimeout(r, ms)), + now: () => Date.now(), +}; + +/** + * Fetch the span through the editor (or poll a fetch already asked for). A + * ready answer carries what plays now; a failure its plain sentence. + */ +export async function fetchCitedClip( + req: { job: string; target?: CitedTarget } | { target: CitedTarget; reason: string; report?: string }, + d: FetchClipDeps = deps, +): Promise<CitedFetchAnswer> { + const args = + "job" in req + ? { job: req.job, wait_seconds: 0 } + : { + channel: req.target.channel, + video: req.target.video, + start: req.target.from, + end: req.target.to, + reason: req.reason, + ...(req.report ? { report: req.report } : {}), + wait_seconds: 0, + }; + const v = validateFetchClipArgs(args); + if (!v.ok) throw new SourceError(v.error.replace(/^fetch_clip: /, "")); + const a = answerOf(await fetchClip(v.request, d, { requestedBy: "umtool" })); + if (a.state === "failed") { + const plain = fetchFailureSentence(a.message); + return { state: "failed", message: plain.message, ...(plain.detail ? { detail: plain.detail } : {}), ...(a.job ? { job: a.job } : {}) }; + } + if (a.state === "queued") return a; + const target = req.target; + return { + state: "ready", + cached: a.cached, + ...(a.from !== undefined ? { from: a.from } : {}), + ...(a.to !== undefined ? { to: a.to } : {}), + play: target ? await findCitedPlay(target) : null, + }; +} diff --git a/umtool/lib/clips/types.ts b/umtool/lib/clips/types.ts @@ -0,0 +1,36 @@ +// The cited clip's shapes, shared by the server (lib/clips/cited.ts, the +// /api/cited routes) and the player (components/clips/CitedClip.tsx). + +/** What can play a cited span, best first: prepared, a clip window, a saved video, audio. */ +export type CitedPlay = { + kind: "prepared" | "window" | "saved" | "audio"; + url: string; + /** Seconds into the file where the cited span starts. */ + offset: number; + audio: boolean; + label: string; +}; + +/** + * The span a citation names. `channel`/`video` are the corpus's directories + * (a Rumble entry's local dir is `video`, never its `siteVideo`). With + * `project`+`clip` the project's own cached windows are asked first. + */ +export type CitedTarget = { + channel: string; + video: string; + from: number; + to: number; + project?: string; + clip?: string; + /** An audio citation: never look for a picture. */ + audio?: boolean; +}; + +/** One answer of the fetch route: ready (and what plays now), still going, or why not, in plain words. */ +export type CitedFetchAnswer = + | { state: "ready"; cached: boolean; from?: number; to?: number; play: CitedPlay | null } + | { state: "queued"; job: string; status: string } + | { state: "failed"; message: string; detail?: string; job?: string }; + +export const citedKey = (t: CitedTarget) => [t.channel, t.video, t.from, t.to, t.project ?? "", t.clip ?? "", t.audio ? "a" : ""].join("|"); diff --git a/umtool/lib/clips/words.test.ts b/umtool/lib/clips/words.test.ts @@ -0,0 +1,41 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { fetchFailureSentence, litCount, spokenWords } from "./words"; + +test("a rate limit says the platform is rate-limiting", () => { + const r = fetchFailureSentence("youtube is cooling down after a 429 (2 min): HTTP Error 429: Too Many Requests"); + assert.equal(r.message, "youtube is rate-limiting fetches: try again later."); + assert.match(r.detail ?? "", /429/); + assert.equal(fetchFailureSentence("the editor refused it (409): rumble is in a rate-limit cooldown").message, "rumble is rate-limiting fetches: try again later."); +}); + +test("an audio-check failure says the source served corrupt audio", () => { + const r = fetchFailureSentence("the editor's job failed: The audio check found the window 1.00–9.00 of abc malformed"); + assert.match(r.message, /corrupt audio/); +}); + +test("anything else is passed through", () => { + assert.deepEqual(fetchFailureSentence("the editor's job failed: no formats"), { message: "the editor's job failed: no formats" }); +}); + +test("spoken words follow the cues, word by word", () => { + const cues = [ + { start: 0, end: 4, text: "one two three four" }, + { start: 4, end: 8, text: "five six seven eight" }, + ]; + const w = spokenWords("three four five", cues, 0, 8); + assert.deepEqual(w.map((x) => x.t), [2, 3, 4]); + assert.equal(litCount(w, 3.5), 2); + assert.equal(litCount(w, 1), 0); +}); + +test("a misheard word keeps the time before it", () => { + const cues = [{ start: 10, end: 14, text: "I bought a cakeup machine" }]; + const w = spokenWords("I bought a K-Cup machine", cues, 10, 14); + assert.deepEqual(w.map((x) => x.t), [10, 10.8, 11.6, 11.6, 13.2]); +}); + +test("no cues, or a quote mostly not in them: spread evenly over the span", () => { + assert.deepEqual(spokenWords("a b", [], 0, 2).map((x) => x.t), [0, 1]); + assert.deepEqual(spokenWords("x y z w", [{ start: 0, end: 4, text: "nothing alike here" }], 0, 4).map((x) => x.t), [0, 1, 2, 3]); +}); diff --git a/umtool/lib/clips/words.ts b/umtool/lib/clips/words.ts @@ -0,0 +1,94 @@ +// Pure helpers of the cited-clip player and the audition deck (release 32 R1): +// a fetch failure in plain words, and the LIT LINE -- each word of a quote with +// the second it is spoken, so the line lights as playback reaches it. + +/** + * A fetch failure as the person reading it needs it: a rate limit says the + * platform is rate-limiting, an audio-check refusal says the source served + * corrupt audio. `detail` keeps the editor's own words. + */ +export function fetchFailureSentence(message: string): { message: string; detail?: string } { + const m = String(message ?? "").trim(); + if (/\b429\b|rate[- ]?limit|too many requests|cooling down/i.test(m)) { + const platform = /^(\w+) is cooling down/i.exec(m)?.[1] ?? /\b(youtube|rumble|odysee|twitch|kick)\b/i.exec(m)?.[1] ?? "the platform"; + return { message: `${platform} is rate-limiting fetches: try again later.`, detail: m }; + } + if (/audio check found .* malformed|malformed/i.test(m)) { + return { message: "The source served corrupt audio for these seconds (the audio check refused it twice); nothing was kept.", detail: m }; + } + if (/did not answer|ECONNREFUSED|no editor|ARCHILYZER_EDITOR_URL/i.test(m)) { + return { message: "The editor is not answering, so nothing can be fetched right now.", detail: m }; + } + return { message: m || "the fetch failed" }; +} + +export type SpokenWord = { text: string; t: number }; + +const norm = (w: string) => w.toLowerCase().replace(/[^\p{L}\p{N}']+/gu, "").replace(/'/g, ""); + +/** + * Each word of `quote` with the second it is spoken: the cues in [from, to] + * spread their words evenly across their own span, and the quote's words are + * found in that sequence in order; a word not found takes the time of the one + * before it (or the span's start). With no cues, or fewer than half the words + * found, the quote spreads evenly across the span. Word-level offsets are + * not read: no transcript shape in the corpus carries them. + */ +export function spokenWords( + quote: string, + cues: readonly { start: number; end?: number; text: string }[], + from: number, + to: number, +): SpokenWord[] { + const words = String(quote ?? "").split(/\s+/).filter(Boolean); + if (!words.length) return []; + const span = Math.max(0.001, to - from); + const timed: { n: string; t: number }[] = []; + const sorted = [...cues].sort((a, b) => a.start - b.start); + sorted.forEach((c, i) => { + const end = c.end ?? sorted[i + 1]?.start ?? c.start + 3; + if (end < from - 0.05 || c.start > to + 0.05) return; + const ws = String(c.text ?? "").split(/\s+/).filter(Boolean); + const step = ws.length ? Math.max(0, end - c.start) / ws.length : 0; + ws.forEach((w, j) => timed.push({ n: norm(w), t: c.start + j * step })); + }); + const even = () => words.map((w, i) => ({ text: w, t: from + (i * span) / words.length })); + if (!timed.length) return even(); + const out: SpokenWord[] = []; + let at = 0; + let last = from; + let hits = 0; + for (const w of words) { + const n = norm(w); + let hit = -1; + // Look ahead a little: a respelled or misheard word is skipped, not a derailment. + for (let k = at; k < Math.min(timed.length, at + 8); k++) { + if (n && timed[k].n === n) { + hit = k; + break; + } + } + if (hit >= 0) { + hits += 1; + last = Math.max(last, timed[hit].t); + at = hit + 1; + } + out.push({ text: w, t: last }); + } + // Mostly not found (another track's words, a paraphrase): spread it instead. + return hits * 2 < words.length ? even() : out; +} + +/** How many words are lit at `now` (the spoken ones). */ +export function litCount(words: readonly SpokenWord[], now: number): number { + let n = 0; + for (const w of words) if (w.t <= now + 0.05) n += 1; + return n; +} + +export const spanClock = (s: number) => { + const v = Math.max(0, s); + const m = Math.floor(v / 60); + const r = Math.floor(v % 60); + return `${m}:${String(r).padStart(2, "0")}`; +}; diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -284,8 +284,8 @@ export function narrationHref(project: string, q: NoteOpt = {}): string { } /** The drafts review (release 28). */ -export function reviewHref(project: string, q: NoteOpt = {}): string { - return withQuery(`/projects/${encodePath(project)}/review`, {}, q.note); +export function reviewHref(project: string, q: NoteOpt & { view?: "list" } = {}): string { + return withQuery(`/projects/${encodePath(project)}/review`, q.view ? { view: q.view } : {}, q.note); } /** One cut of a song; `plan` opens a plan of it, `v` a variant row. */ diff --git a/umtool/lib/report/draftEdit.mjs b/umtool/lib/report/draftEdit.mjs @@ -0,0 +1,69 @@ +// EDIT on the audition deck (release 32 R1): a drafted field rewritten by the +// person as plain text, and turned back into the field's value. One line per +// part, so the same textarea serves every field the card can edit: +// +// onscreen line 1 the title, the rest the subtitle +// narration the text +// lines one teaser line per line +// publish.youtube line 1 the title (the description stays) +// +// Any other field (flips, threads, the cut's order, a social post) is edited +// where it always was: the deck links its section. The value goes through the +// manifest's own writer (writeDraftedField), so it is the operator's after. + +export const EDITABLE_FIELDS = Object.freeze(["onscreen", "narration", "lines", "publish.youtube"]); + +/** Whether the card can edit this field in place. */ +export const isEditableField = (field) => EDITABLE_FIELDS.includes(field); + +/** The textarea's text for a field, from the words the review shows (judgedText). */ +export function editTextOf(field, judged) { + const s = typeof judged === "string" ? judged : ""; + if (field === "onscreen") return s.replace(" — ", "\n"); + if (field === "lines") return s.split(" / ").join("\n"); + return s; +} + +const linesOf = (text) => + String(text ?? "") + .split(/\r?\n/) + .map((l) => l.trim()) + .filter(Boolean); + +/** + * The field's new value from the edited text, keeping what the text does not + * say (a narration's voice, a teaser line's own keys, the description). + * Throws in words when the text cannot be the field. + */ +export function valueFromEdit(field, current, text) { + const lines = linesOf(text); + const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {}); + if (field === "onscreen") { + if (!lines.length) throw new Error("an on-screen text needs a title"); + const { title: _t, subtitle: _s, ...rest } = obj(current); + const subtitle = lines.slice(1).join(" "); + return { ...rest, title: lines[0], ...(subtitle ? { subtitle } : {}) }; + } + if (field === "narration") { + const t = String(text ?? "").trim(); + if (!t) throw new Error("a narration needs its words"); + return { ...obj(current), text: t }; + } + if (field === "lines") { + if (!lines.length) throw new Error("a teaser needs at least one line"); + const was = Array.isArray(current) ? current : []; + return lines.map((l, i) => (was[i] && typeof was[i] === "object" ? { ...was[i], text: l } : l)); + } + if (field === "publish.youtube") { + if (!lines.length) throw new Error("a YouTube title cannot be empty"); + return { ...obj(current), title: lines[0] }; + } + throw new Error(`${field} is edited in its own section, not on the card`); +} + +/** The current value of a review row's field in a manifest. */ +export function currentFieldValue(manifest, { entry, field }) { + if (entry) return (manifest?.timeline ?? []).find((e) => e?.id === entry)?.[field]; + if (field === "publish.youtube") return manifest?.publish?.youtube; + return undefined; +} diff --git a/umtool/lib/report/draftEdit.test.mjs b/umtool/lib/report/draftEdit.test.mjs @@ -0,0 +1,30 @@ +// The deck's EDIT (release 32 R1): the edited text back into each field's value. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { currentFieldValue, editTextOf, isEditableField, valueFromEdit } from "./draftEdit.mjs"; + +test("the textarea's text from the review's words, and back", () => { + assert.equal(editTextOf("onscreen", "Title — Sub"), "Title\nSub"); + assert.equal(editTextOf("lines", "a / b / c"), "a\nb\nc"); + assert.deepEqual(valueFromEdit("onscreen", { title: "Old", subtitle: "s", align: "left" }, "New title\nnew sub"), { align: "left", title: "New title", subtitle: "new sub" }); + assert.deepEqual(valueFromEdit("onscreen", { title: "Old", subtitle: "s" }, "Only a title"), { title: "Only a title" }); +}); + +test("narration keeps its voice; a teaser line keeps its own keys", () => { + assert.deepEqual(valueFromEdit("narration", { text: "old", voice: "v1" }, " new words "), { text: "new words", voice: "v1" }); + assert.deepEqual(valueFromEdit("lines", [{ text: "a", hold: 2 }, "b"], "A\nB\nC"), [{ text: "A", hold: 2 }, "B", "C"]); + assert.deepEqual(valueFromEdit("publish.youtube", { title: "t", description: "d" }, "New\nignored"), { title: "New", description: "d" }); +}); + +test("what the card cannot edit, and empty text, are refused in words", () => { + assert.equal(isEditableField("render.chrome.flips"), false); + assert.throws(() => valueFromEdit("render.chrome.flips", [], "x"), /edited in its own section/); + assert.throws(() => valueFromEdit("onscreen", {}, " \n "), /needs a title/); + assert.throws(() => valueFromEdit("lines", [], ""), /at least one line/); +}); + +test("the current value of a row's field", () => { + const m = { timeline: [{ id: "c1", onscreen: { title: "T" } }], publish: { youtube: { title: "Y" } } }; + assert.deepEqual(currentFieldValue(m, { entry: "c1", field: "onscreen" }), { title: "T" }); + assert.deepEqual(currentFieldValue(m, { entry: null, field: "publish.youtube" }), { title: "Y" }); +}); diff --git a/umtool/package.json b/umtool/package.json @@ -8,7 +8,7 @@ "build": "next build", "start": "next start --port ${UMTOOL_PORT:-3050}", "typecheck": "tsc --noEmit", - "test": "tsx --test lib/research/*.test.ts lib/inbox/*.test.ts", + "test": "tsx --test lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts", "e2e": "node ../scripts/worktree.mjs run -- node ../scripts/queue-lock.mjs --name e2e-umtool --estimate 1500 --prebuild umtool --ports UMTOOL_E2E_PORT:3051,EDITOR_STUB_PORT:3052 -- playwright test" }, "dependencies": {