Archilyzer · Source

archilyzer

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

commit db8fa4a151d09e1776d10ccc1d90f104183c5715
parent 23e0a8393f041ee46c05a68674ddb4ea34f44918
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 19 Oct 2026 04:14:41 -0400

Merge r35/clip-editor: the clip editor -- trim, split, merge, add, restore, keep/cut, comments, This is the host + Re-propose, over the assistant's clips

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

Diffstat:
Meditor/CHANGELOG.md | 1+
Mplans/FACTS.md | 33+++++++++++++++++++++++++++++++++
Aplans/release-35/clip-editor.md | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/clip-editor/route.ts | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/ClipDeckPage.tsx | 10+++++++++-
Aumtool/components/projects/ClipEditorPage.tsx | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/ProjectView.tsx | 5+++--
Mumtool/components/projects/report/CutTab.tsx | 18+++++++++++++++++-
Aumtool/components/projects/review/ClipEditor.tsx | 1083+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/notes.md | 2+-
Mumtool/docs/report-video.md | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/clip-editor.spec.ts | 140+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/clip-editor-fixture.mjs | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 4++++
Mumtool/lib/hrefs.test.mjs | 6++++++
Mumtool/lib/hrefs.ts | 9+++++++++
Aumtool/lib/report/clipEditor.mjs | 361+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/clipEditor.test.mjs | 343+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/clipEditorBridge.mjs | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/clipEditorModel.mjs | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/clipEditorTypes.ts | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 226++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
22 files changed, 2859 insertions(+), 6 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **Hop in on an assistant's clips in umtool: trim, split, merge, keep or cut them, and comment.** A report video whose cut is not a montage has a **Clip editor** on its Cut tab (`/projects/<id>/clips`). It loops the selected clip from what is on disk, and under it shows the clip's neighbourhood (± 60 s, or closer): the speaker turns coloured host and subject, the laughs, the words, the other clips, and the cut with a handle at each edge. Move the edges by dragging, typing, nudging (±0.1, ±0.5, ±2 s) or **Snap to words**; **Keep** / **Cut**; **Split here** at the playhead; **Merge with next**; **Add a clip** from a span dragged on the strip; **Restore the assistant's version**; **Bring in** a proposal the assistant left out. Each clip says whether it is "by the assistant" (with its score and why) or "edited by you", with its edit history. A comment on a clip is a note anchored to it, so an agent reading `umtool notes` can act on it and its reply shows in the clip's thread. **This is the host** on a speaker's turn corrects which voice is the host. Keys: space, J/L, I/O, S, M, K, X, ←/→. A keep or cut follows its clip when an edit moves the clip's start. It works on any report video; a cut without the clip finder's speakers simply has no colours. - **Fetch a montage's windows from umtool, and swap in another upload when Rumble refuses one.** A report video's Cut tab and its clip deck have **Fetch windows**: one button asks the editor for every clip's window (a dry run first — how many per platform, how many already on disk — then Start, with each job followed to its end and each refused window named); `umtool fetch <project>` does the same from a terminal. When a window is refused for good (a Rumble video whose lookup answers 403 every time, a deleted recording), the clip deck offers a **stand-in** — the same moment in the stream's YouTube upload (or Odysee) — and **Use stand-in** switches the clip, noting where it came from; **Restore** puts it back. `umtool fallback <project>` is the terminal form. Every run is kept in the project's `fetch-runs.json`. - **Cap a phrase montage at N clips, spread across the years.** `umtool new … --seed phrase --max N`, the New project form's **Max** and the phrase finder's **Max clips** keep N instances, each year's share in proportion to how often it was said there (at least one per year), preferring clips with no speaker change in the captions and spread through each year. The rest are listed in `phrase-scan.json`. - **umtool proposes highlights from a long recording.** Create → **Highlights from a recording** (or the new-project form's seed "highlights", or `umtool new <slug> --seed reactions --from <channel>/<id> --target 600`) takes a stream or podcast whose speakers the editor has found (its diarization) and proposes clips: each runs from the line that set it up, through the host's laugh or comment, to the next pause. The host is the speaker who interjects all the way through (you can say otherwise: `--host N`, or the clip editor's "This is the host"). Laughs are heard by a small local sound model (CED-mini, installed under `.diarize/models/`), and without it read from the transcript ("[laughter]", "haha") and the host's loud wordless moments. The clips are ranked into the target length, put in the video manifest in time order with hard cuts, and each is marked as proposed by the assistant, with its score and why; the rest stay listed in `reactions.json` beside the manifest to bring in by hand. `umtool clips analyze <project>` runs the scans on the recording's sound (a few minutes for a 2.5-hour stream, kept for the next run) and proposes again; `umtool clips propose` proposes again after a change of host or length, and never moves or removes a clip you edited, ruled, locked or added. Each laugh is also checked against the host's and the narrator's voices, so a laugh voice-acted in the video he is watching is not taken for his. `--scope FROM:TO` (or the form's From/To) reads only part of a recording — a stream that reacts to two videos, one at a time — and the laugh bar is `--laugh-min` (the form's **Laugh min**). Proposals under five seconds or with a low score are listed but never put in the cut. A recording with no diarization is refused with the command that makes it. Nothing calls an AI model, and nothing leaves the machine. Needs a restart of umtool. diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -10751,3 +10751,36 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri --effect` / `umtool takes effects` read it. - A montage still refuses `render.chrome` (and so the effects). +## Release 35 lane C2: the clip editor (verified 2026-10-19, branch `r35/clip-editor`) + +- **Where**: `/projects/<id>/clips` on a report video whose manifest has NO montage clip (`hasMontageClips` false) → + `components/projects/ClipEditorPage.tsx` + `review/ClipEditor.tsx`; a montage keeps the release-34 deck unchanged; + `?mode=edit` forces the editor, `?clip=<id>` selects one (`clipEditorHref(p, {clip?, mode?})`). The Cut tab's + `[data-clip-editor-link=<n assisted>]` shows for a non-montage cut with clips. +- **The writers** (all in `umtool/lib/report/manifest.mjs`): `updateClip(dir, id, patch, {token, edit = "trim", now})` + now appends to a clip's `assist` (when the clip HAS `assist` and its cut moved): `assist.by = "operator"`, + `assist.edits.push({at, by: "operator", what, from: {cutStart, cutEnd}, to: {cutStart, cutEnd}})` (newest 200; + `cutOf(e)` = cut, else extent). A clip with no `assist` is edited exactly as before. `restoreClip` (= updateClip with + the `RESTORE_PATCH` sentinel: `assist.original` read inside the lock) sets `by` back to `"assistant"` when the clip + has a `proposal`. `splitClip(dir, id, at, {quotes})`, `mergeClips(dir, id, {quote})`, `addClip(dir, spec)` are + `structural` (auto snapshot `auto-before-split|merge|add`, structureErrors). Split: first half keeps id + `original`, + second = `freshEntryId(timeline, id)` (`r001-2`) with `assist {by: "operator", proposal?, score?, why?, edits}`, no + `original`, no `claim`. Merge: with the NEXT timeline entry, which must be a clip of the same channel+video. Add: `id` + default `<video>-<floor(cutStart)>`, placed after the last clip of the same recording whose cut starts ≤ it; `assist + {by: "operator", proposal?, score?, why?, original? (a proposal brought in), edits: [{what: "add", from: null}]}`. +- **The operations**: `umtool/lib/report/clipEditor.mjs` `runClipEditorOp(project, body)` — trim (a clip with a cut + moves its cut and widens the extent to hold it; one without moves start/end; an assisted clip's `quote` becomes the + words of the new span), restore, split (each half's quote from the words), merge, add, bring-in (a `reactions.json` + proposal → addClip with `proposal`), ruling (`keep`|`cut`|null via `setMontageRuling`, key `clipMomentKey`), role. + After every manifest op `carryRulings(dir, beforeKeys, afterKeys)`: a ruling whose clip's moment key changed moves to + the new key (unless that key is ruled already); a ruling whose clip is gone is removed (unless another clip sits on + that moment). `GET /api/report/clip-editor?project` (the view), `?project&clip&from&to` (the strip: turns, laughs, + words — `reactions.source.words` else `<project>/words.json`, `[{w|word|text, start, end}]` or `{words: […]}` — + else the clip's cues), `POST {project, op, token, …}` (409 stale token; 400 + `errors` for StructureRefused). +- **"Unused proposals"** = `reactions.json` proposals that NO manifest clip's `assist.proposal` names (not the file's own + `used`, which is what the last propose did). Bring-in: the proposal's start/end is the CUT, the window + `WINDOW_PAD_S` (1.5 s, common/lib/clips/assist.mjs) wider each side inside the duration, `original` all four. The + editor writes reactions.json only through `umtool/lib/report/clipEditorBridge.mjs`, which re-exports the clip + finder's `setSpeakerRole` (common/lib/clips/reactions.mjs: one host / one subject, `rolesChangedAt`) beside a lenient + reader (`{doc, error}`). Re-propose = `POST /api/report/clips {project, mode: "propose"}` (a job), offered while + `rolesChangedAt > proposedAt` (the view carries both). diff --git a/plans/release-35/clip-editor.md b/plans/release-35/clip-editor.md @@ -0,0 +1,91 @@ +# Release 35 lane C2 — `r35/clip-editor`: a person hops in on an assistant's clips (as shipped) + +The operator: "Add the ability in the UI for an easy way for a human to hop in and either comment or manually adjust +clips created by an assistant." This lane is that surface: the clip editor at `/projects/<id>/clips` for a report video +whose cut is not a montage — the clip finder's highlights above all (lane C1 writes them, each with `assist`), and any +other report video's clips. Rulings followed: the UI works with no model (nothing here calls one; every proposal the +assistant makes a person can make, undo or adjust); every review step is a umtool surface; comments are notes +(`notes.json`, anchored to the clip, the `umtool notes` agent loop); the montage deck stays as it is; plain words, no +lead paragraphs; role tokens and the redesign's primitives; synthetic fixtures only. + +## What + +1. **The writers** — `umtool/lib/report/manifest.mjs`, the one manifest writer: + - `updateClip(dir, id, patch, {token, edit = "trim", now})`: a clip that carries `assist` and whose cut moved gets + `assist.by = "operator"` and an appended edit `{at, by: "operator", what, from: {cutStart, cutEnd}, to: {cutStart, + cutEnd}}` (newest 200 kept). A trim that leaves the cut where it was records nothing; a clip with no `assist` is + edited exactly as before (the clip bench's edits of an assistant's clip are recorded the same way). + - `restoreClip(dir, id)`: `assist.original` back (read inside the lock), an edit `restore`, and `by` the + assistant's again. + - `splitClip(dir, id, at, {quotes})`, `mergeClips(dir, id, {quote})`, `addClip(dir, spec)`: structural — an + `auto-before-<op>` snapshot first (the Cut tab's Undo takes it back) and the build's structure checks after (with + C1's `validateAssist` once both lanes are merged). Split: at a second half a second inside the cut; the first half + keeps the id and `original`, the second is `<id>-2` (the operator's, no `original`, no `claim`). Merge: with the + next timeline entry, which must be a clip of the same recording (a card between them refuses). Add: in time order + among the recording's clips, `assist {by: "operator", edits: [add]}`; a proposal brought in also keeps `proposal`, + `score`, `why` and the proposal's edges as `original`. +2. **The operations** — `umtool/lib/report/clipEditor.mjs` `runClipEditorOp`: trim (a clip with a cut moves the cut and + widens its extent to hold it; one without moves its extent; an assistant's clip's `quote` becomes the words of the new + span), restore, split (each half quoted from the words), merge, add, bring-in, ruling (`keep` | `cut` | clear, in + `montage-rulings.json` through the release-34 writer, keyed `clipMomentKey`), role. **Rulings follow their clips**: + after every manifest operation a ruling whose clip's moment key changed moves to the new key, and one whose clip is + gone (merged away) is removed. `clipEditorView` (the clips, the token, the speakers, the proposals not in the cut) and + `clipNeighbourhood` (turns, laughs, words — the project's `words.json` or `reactions.source.words` — else the clip's + cues) feed the page. `GET/POST /api/report/clip-editor`. +3. **The page** — `/projects/<id>/clips`: `ClipDeckPage` renders `ClipEditorPage` when the manifest has no montage clip + (or `?mode=edit`); `?clip=<id>` selects. The Cut tab's **Clip editor — n clips · k by the assistant**. + - The player loops the cut from what `/api/cited/play` finds (the neighbourhood, else the extent): a saved video, a + clip window, or audio. It is looked up by the clip's extent, so a trim does not reload it. + - The strip: ± 60 / 20 / 6 s; turns in two lanes coloured host (Signal) and subject (Meter), laughs (Doubt), word + ticks, the other clips (a click opens one), the cut with two drag handles, the playhead; a drag selects a span + (**Add a clip**); a click seeks. The words under it (the cut's lit, the one playing marked; a click seeks). + - Edges: a number field each, nudges ±0.1 / ±0.5 / ±2 s, **at playhead**, **Snap to words** (word gaps, the edges of + a silence between turns, else cue boundaries, within 1.5 s). Drafted locally, written once after 450 ms. + - Keep / Cut (toggle), Split here, Merge with next, Restore the assistant's version, Bring in (the proposals no clip + names), This is the host / Not the host (a click on a turn, or the Speakers list), Re-propose (offered after a role + change: the clip finder's proposal pass as a job), Render (the picked or whole-cut take again, else the + Takes page). + - Provenance: "by the assistant · 0.83 · why" / "edited by you · …" / "added by you" / "brought in by you", and the + edit history. + - Comments: the clip's notes (`{kind: "entry", entry}`), their threads with an agent's replies, Resolve / Won't fix + / Reopen / Reply, a box for another (no autofocus, so the keys keep working). + - Keys: space, `j` / `l`, `i` / `o`, `s`, `m`, `k`, `x`, ← / →. +4. **The seam onto C1** — `umtool/lib/report/clipEditorBridge.mjs` holds `readReactions` (lenient: `{doc, error}`) and + re-exports C1's `setSpeakerRole` (until C1 merged it held a local stand-in; wired after the merge of main + 151d7c55). Re-propose posts `/api/report/clips {project, mode: "propose"}` and follows the job, offered while + `rolesChangedAt > proposedAt`; a bring-in uses C1's shape (the proposal is the cut, the window `WINDOW_PAD_S` wider). + +## Files + +umtool: `lib/report/manifest.mjs` (updateClip's assist edits; `restoreClip`, `splitClip`, `mergeClips`, `addClip`, +`noteAssistEdit`, `cutOf`, `RESTORE_PATCH`, `ASSIST_EDITS_MAX`), `lib/report/clipEditor.mjs` (new), +`lib/report/clipEditorBridge.mjs` (new), `lib/report/clipEditorModel.mjs` (new, pure), `lib/report/clipEditorTypes.ts` +(new), `lib/report/clipEditor.test.mjs` (new, 13 tests), `lib/hrefs.ts` (`clipEditorHref`; + test 1), +`app/api/report/clip-editor/route.ts` (new), `components/projects/ClipEditorPage.tsx` (new), +`components/projects/review/ClipEditor.tsx` (new), `components/projects/ClipDeckPage.tsx` (the editor for a +non-montage cut), `components/projects/ProjectView.tsx` (`mode`, `clip`), `components/projects/report/CutTab.tsx` (the +link), `e2e/clip-editor.spec.ts` (new), `e2e/fixtures/clip-editor-fixture.mjs` (new), `e2e/fixtures/make-fixture.mjs`, +`docs/report-video.md` ("Reviewing assistant clips: the clip editor"), `docs/notes.md`. `editor/CHANGELOG.md`, +`plans/FACTS.md` ("Release 35 lane C2"). + +## Gates + +All on the final tip (after merging main with C1 151d7c55 and O2 c921d0a5), through the session lock: +- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit` — clean (also clean before each code commit: + umtool's tsc per commit, the full workspace before the record). +- `pnpm run test:scripts` — 1251 tests, 1247 pass, 4 skipped, 0 fail (main at the lane's start, before C1/O2: 1175 / + 1171 / 4; this lane adds 14: `lib/report/clipEditor.test.mjs` 13, `lib/hrefs.test.mjs` +1; the rest is C1's and O2's). +- `pnpm --filter umtool test` — 45 / 45 (unchanged). +- e2e `pnpm --filter umtool run e2e clip-editor.spec.ts` (on 86351e2a, after the C1 wiring): **1 passed, 0 failed**, + spec 5.8 s, wall 14.9 s (the start-mode build 1186 s; most of the hour was the machine's heavy queue). +- Read-only check against the live `~/reports/nik-drop-clips` through `clipEditorView` / `clipNeighbourhood`: 20 clips, + 7 speakers, 92 of 112 proposals not in the cut, a neighbourhood of 29 turns, 2 laughs, 287 words. +- Not run: `clip-deck.spec.ts` (the deck's only change is the guarded early return for a non-montage cut) — the full + suite covers it. + +## Found and left + +- A clip merged away leaves its notes anchored to an id no clip has; they still list under `umtool notes` (the anchor + resolves to nothing). Not migrated. +- The unused-proposal list is every proposal no clip names, best first — 92 on the live nik-drop-clips project. No + paging yet; it scrolls in the side column. diff --git a/umtool/app/api/report/clip-editor/route.ts b/umtool/app/api/report/clip-editor/route.ts @@ -0,0 +1,61 @@ +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { OpError, StaleToken, StructureRefused, clipEditorView, clipNeighbourhood, runClipEditorOp } from "@/lib/report/clipEditor.mjs"; + +export const dynamic = "force-dynamic"; + +// THE CLIP EDITOR (release 35 C2): `/projects/<id>/clips` on a report video +// whose cut is not a montage -- an assistant's clips (the clip finder's), or +// any report video's, adjusted by a person. lib/report/clipEditor.mjs is the +// one place each write goes through. +// +// GET ?project=<id> the view: clips, token, speakers, unused proposals +// GET ?project=<id>&clip=<id>&from=<s>&to=<s> the strip for a span: turns, laughs, words | cues +// POST { project, op, token?, … } one operation (clipEditor.mjs runClipEditorOp): +// trim | restore | split | merge | add | bring-in | ruling | role +// -> { op, result, carried, view }; 409 on a stale token (reload), 400 with +// the sentence on a refusal (the build's own, for a structural one) +const headers = { "cache-control": "no-store" }; + +async function editorProject(id: unknown) { + const project = await projectRef(String(id ?? "")); + if (!project) return { error: Response.json({ error: "no such project" }, { status: 404, headers }) }; + if (!kindMakesTakes(project.kind)) return { error: Response.json({ error: "the clip editor is a report video's" }, { status: 400, headers }) }; + return { project }; +} + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await editorProject(url.searchParams.get("project")); + if ("error" in r) return r.error; + try { + if (url.searchParams.has("from")) { + const n = await clipNeighbourhood(r.project, { + clip: url.searchParams.get("clip"), + from: Number(url.searchParams.get("from")), + to: Number(url.searchParams.get("to")), + }); + return Response.json(n, { headers }); + } + const view = await clipEditorView(r.project); + if (!view) return Response.json({ error: "no manifest" }, { status: 400, headers }); + return Response.json(view, { headers }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400, headers }); + } +} + +export async function POST(request: Request) { + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); + const r = await editorProject(body.project); + if ("error" in r) return r.error; + try { + return Response.json(await runClipEditorOp(r.project, body), { headers }); + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message }, { status: 409, headers }); + if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400, headers }); + const status = e instanceof OpError ? e.status : 400; + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers }); + } +} diff --git a/umtool/components/projects/ClipDeckPage.tsx b/umtool/components/projects/ClipDeckPage.tsx @@ -9,6 +9,9 @@ import VoiceMatchPanel from "./report/VoiceMatchPanel"; import MontageFetchTools from "./report/MontageFetchTools"; import { lastStartedRun, projectFetchBody, readFetchRuns } from "@/lib/report/fetchWindows.mjs"; import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { hasMontageClips } from "@/lib/report/montageRulings.mjs"; +import ClipEditorPage from "./ClipEditorPage"; // `/projects/<project>/clips` -- THE CLIP DECK (release 34 N1): a montage's // every instance, one card at a time, its cut playing, ruled by ear: keep, cut, @@ -18,7 +21,12 @@ import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/ // here calls a model; release 34 N2's voice-match.json, when it is there, // only orders the doubtful first and shows its score. -export default async function ClipDeckPage({ project, show }: { project: ProjectRef; show?: string }) { +export default async function ClipDeckPage({ project, show, mode, clip }: { project: ProjectRef; show?: string; mode?: string; clip?: string }) { + // A cut that is not a montage -- an assistant's clips, any report video's -- + // gets the clip editor (release 35 C2); `?mode=edit` opens it on a montage. + // The montage deck below is unchanged. + const manifest = await readManifest(project.dir); + if (mode === "edit" || (manifest && !hasMontageClips(manifest))) return <ClipEditorPage project={project} clip={clip} />; const view = await clipDeckView(project); const back = await pieceHrefOfProject(project.id, { tab: "cut" }); const top = <BenchTop trail={[{ href: projectsHref(), label: "Projects" }]} back={{ href: back, label: project.id }} kind="Clip deck" here="clips" />; diff --git a/umtool/components/projects/ClipEditorPage.tsx b/umtool/components/projects/ClipEditorPage.tsx @@ -0,0 +1,58 @@ +import Link from "next/link"; +import { projectsHref, takesHref } from "@/lib/hrefs"; +import { clipDeckView } from "@/lib/report/clipDeck"; +import { clipEditorView } from "@/lib/report/clipEditor.mjs"; +import type { EditorView } from "@/lib/report/clipEditorTypes"; +import { pieceHrefOfProject } from "@/lib/pieces/article"; +import type { ProjectRef } from "@/lib/project-types"; +import { NotesProvider } from "@/components/notes/NotesProvider"; +import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell"; +import ClipEditor from "./review/ClipEditor"; + +// `/projects/<project>/clips` on a cut that is not a montage -- THE CLIP +// EDITOR (release 35 C2): a person hops in on the clips an assistant made +// (the clip finder's, `assist` on each) or on any report video's clips, and +// trims, splits, merges, adds, restores, keeps or cuts them, comments on +// them (notes.json, anchored to the clip) and says which voice is the host. +// lib/report/clipEditor.mjs is every write. Nothing here calls a model. + +const KEYS = [ + { keys: ["Space"], label: "play" }, + { keys: ["J", "L"], label: "∓2 s" }, + { keys: ["I", "O"], label: "in / out" }, + { keys: ["S"], label: "split" }, + { keys: ["M"], label: "merge" }, + { keys: ["K", "X"], label: "keep / cut" }, + { keys: ["←", "→"], label: "clip" }, +]; + +export default async function ClipEditorPage({ project, clip }: { project: ProjectRef; clip?: string }) { + const [view, deck, back] = await Promise.all([ + clipEditorView(project) as Promise<EditorView | null>, + clipDeckView(project).catch(() => null), + pieceHrefOfProject(project.id, { tab: "cut" }), + ]); + const top = <BenchTop trail={[{ href: projectsHref(), label: "Projects" }]} back={{ href: back, label: project.id }} kind="Clip editor" here="clips" keys={KEYS} />; + if (!view || !view.clips.length) { + return ( + <BenchFrame kind="clip-editor" top={top}> + <BenchBody workClassName="space-y-3"> + <p data-clip-editor-empty="" className="text-[12px] text-muted"> + No clips in this cut.{" "} + <Link href={back} className="ink-link"> + back to {project.id} + </Link> + </p> + </BenchBody> + </BenchFrame> + ); + } + const initial = view.clips.some((c) => c.id === clip) ? (clip as string) : view.clips[0].id; + return ( + <BenchFrame kind="clip-editor" top={top}> + <NotesProvider target={{ project: project.id }}> + <ClipEditor project={project.id} initialView={view} initialClip={initial} takesHref={takesHref(project.id)} render={deck?.rerender ?? null} takes={deck?.takes ?? 0} /> + </NotesProvider> + </BenchFrame> + ); +} diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx @@ -64,8 +64,9 @@ export default async function ProjectView({ // before a final build, and the alternatives a draft task kept. if (rest.length === 1 && rest[0] === "review") return <ReviewPage project={project} view={search.view} />; // `/projects/<project>/clips` -- the montage's instances, ruled by ear - // keep / cut / not him / read aloud (release 34), applied at render. - if (rest.length === 1 && rest[0] === "clips") return <ClipDeckPage project={project} show={search.show} />; + // keep / cut / not him / read aloud (release 34), applied at render; + // on a cut that is not a montage, the clip editor (release 35 C2). + if (rest.length === 1 && rest[0] === "clips") return <ClipDeckPage project={project} show={search.show} mode={search.mode} clip={search.clip} />; return notFound(); } case "sweep-report": { diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -8,7 +8,7 @@ import { } from "@/lib/projects/report.mjs"; import { listTakes } from "@/lib/report/takes.mjs"; import { buttonVariants } from "@/components/ui/button"; -import { clipBenchHref, clipDeckHref, mixHref as toolsMixHref, projectHref, takesHref } from "@/lib/hrefs"; +import { clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, projectHref, takesHref } from "@/lib/hrefs"; import { montageClipsOf, momentKeysOf, readRulingsState } from "@/lib/report/montageRulings.mjs"; import FetchUnfetchedButton from "../FetchUnfetchedButton"; import { clipRecord, storedUrlOf } from "@/lib/clips/stored"; @@ -68,6 +68,11 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor return montage.filter((e) => !doc.rulings[keys.get(e.id) ?? ""]).length; }) : 0; + // The clip editor (release 35 C2): a cut that is not a montage -- how many + // of its clips the clip finder proposed (`assist`), and how many a person + // has edited since. + const assisted = (m?.timeline ?? []).filter((e: { type?: string; assist?: unknown }) => e?.type === "clip" && e.assist && typeof e.assist === "object") as { assist: { by?: string } }[]; + const assistedByYou = assisted.filter((e) => e.assist.by === "operator").length; // Fetch windows (release 35): the body the button sends, sized here; a run // still going is followed when the page opens. A rulings file that does not // parse leaves the button out (the clip deck says what is wrong with it). @@ -162,6 +167,17 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor Clips — {unruled ? `${unruled} of ${montage.length} to rule` : `${montage.length} ruled`} </Link> )} + {/* Any other cut's clips -- an assistant's above all -- adjusted by a person (release 35 C2). */} + {montage.length === 0 && clips.length > 0 && ( + <Link + href={clipEditorHref(project.id)} + data-clip-editor-link={assisted.length} + className={buttonVariants({ size: "lg" })} + > + Clip editor — {clips.length} clip{clips.length === 1 ? "" : "s"} + {assisted.length ? ` · ${assisted.length} by the assistant${assistedByYou ? `, ${assistedByYou} edited by you` : ""}` : ""} + </Link> + )} {/* Alternative renders of part of the cut, judged on their own page -- where the first one is made, too (release 33's take maker). */} {takes.exists ? ( diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx @@ -0,0 +1,1083 @@ +"use client"; + +import Link from "next/link"; +import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react"; +import { badgeVariants } from "@/components/ui/badge"; +import { buttonVariants } from "@/components/ui/button"; +import { useSharedNotes } from "@/components/notes/NotesProvider"; +import { notesOn } from "@/components/notes/AnchoredNotes"; +import { NoteThread } from "@/components/notes/NoteThread"; +import type { CitedPlay } from "@/lib/clips/types"; +import { edgeClock, provenanceWords, quoteBetween, roleOf, snapCut, snapPoints } from "@/lib/report/clipEditorModel.mjs"; +import type { EditorClip, EditorView, Neighbourhood, Proposal, RenderTarget, Speaker, Turn } from "@/lib/report/clipEditorTypes"; +import { cn } from "@/lib/utils"; +import { startTakeJob } from "../NewTakePanel"; + +// --------------------------------------------------------------------------- +// THE CLIP EDITOR (release 35 C2): a person hops in on an assistant's clips. +// +// the player loops the selected clip's cut (a saved video, a clip +// window, or audio -- what /api/cited/play finds) +// the strip the clip's neighbourhood (± 60 s, or closer): the speaker +// turns coloured by role (host / subject, reactions.json), +// laugh marks, the words, the other clips, the cut with drag +// handles; a drag on the strip selects a span to add +// the edges numeric fields, nudges ±0.1 / ±0.5 / ±2 s, Snap to the +// nearest word gap or silence +// the decisions Keep / Cut (montage-rulings.json, keyed by the moment), +// Split here, Merge with next, Restore the assistant's +// version, Add a clip from the selection, Bring in a proposal +// the comments a note on the clip (notes.json, anchored to it), its thread +// and an agent's replies, resolve / reopen +// +// Every write is one POST to /api/report/clip-editor; the answer is the whole +// view again, so the page never guesses what the server did. Edge edits are +// drafted locally and written after a short pause, so a run of nudges is one +// edit. Nothing here calls a model. +// --------------------------------------------------------------------------- + +const REACHES = [60, 20, 6] as const; +const NUDGES = [-2, -0.5, -0.1, 0.1, 0.5, 2] as const; +const COMMIT_MS = 450; +const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']"; +const ROLE_FILL: Record<string, string> = { host: "bg-signal", subject: "bg-meter", other: "bg-muted" }; +const ROLE_WORD: Record<string, string> = { host: "host", subject: "subject", other: "other" }; +const r2 = (n: number) => Math.round(n * 100) / 100; +const cutOf = (c: EditorClip) => ({ cutStart: c.cutStart ?? c.start, cutEnd: c.cutEnd ?? c.end }); +const rulingBadge = (r: string) => (r === "keep" ? cn(badgeVariants({ variant: "neutral", size: "sm" }), "border-kept-text text-kept-text") : badgeVariants({ variant: "blocking", size: "sm" })); +const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? "" : "s"}`; + +type Cut = { cutStart: number; cutEnd: number }; + +async function post(body: Record<string, unknown>): Promise<{ ok: boolean; status: number; json: Record<string, unknown> }> { + const r = await fetch("/api/report/clip-editor", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const json = (await r.json().catch(() => ({}))) as Record<string, unknown>; + return { ok: r.ok, status: r.status, json }; +} + +export default function ClipEditor({ + project, + initialView, + initialClip, + takesHref, + render, + takes, +}: { + project: string; + initialView: EditorView; + initialClip: string; + takesHref: string; + render: RenderTarget; + takes: number; +}) { + const [view, setView] = useState<EditorView>(initialView); + const [selected, setSelected] = useState(initialClip); + const [draft, setDraft] = useState<Cut | null>(null); + const [reach, setReach] = useState<number>(REACHES[0]); + const [hood, setHood] = useState<Neighbourhood | null>(null); + const [playhead, setPlayhead] = useState<number | null>(null); + const [playing, setPlaying] = useState(false); + const [selection, setSelection] = useState<Cut | null>(null); + const [speakerPick, setSpeakerPick] = useState<number | null>(null); + const [rolesChanged, setRolesChanged] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + const [status, setStatus] = useState<string | null>(null); + const token = useRef<string | null>(initialView.token); + const chain = useRef<Promise<unknown>>(Promise.resolve()); + const timer = useRef<ReturnType<typeof setTimeout> | null>(null); + const pending = useRef<{ clip: string; cut: Cut } | null>(null); + const player = useRef<PlayerHandle | null>(null); + + const clips = view.clips; + const index = Math.max(0, clips.findIndex((c) => c.id === selected)); + const clip = clips[index] ?? clips[0]; + const committed = cutOf(clip); + const cut = draft ?? committed; + const speakers = view.reactions?.speakers ?? []; + + // The page's address names the clip, so a reload (or a link) lands on it. + useEffect(() => { + const u = new URL(window.location.href); + if (u.searchParams.get("clip") === clip.id) return; + u.searchParams.set("clip", clip.id); + window.history.replaceState(null, "", u.toString()); + }, [clip.id]); + + // ---- writes --------------------------------------------------------------- + const reload = useCallback(async () => { + const r = await fetch(`/api/report/clip-editor?project=${encodeURIComponent(project)}`, { cache: "no-store" }); + const j = (await r.json()) as EditorView & { error?: string }; + if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`); + token.current = j.token; + setView(j); + }, [project]); + + const write = useCallback( + (body: Record<string, unknown>, done?: string) => { + const run = async () => { + setBusy(true); + try { + const r = await post({ project, token: token.current, ...body }); + if (r.status === 409) { + await reload(); + setError(`${String(r.json.error ?? "the cut changed")} — reloaded; check and try again`); + return null; + } + if (!r.ok) { + setError(String(r.json.error ?? `HTTP ${r.status}`)); + return null; + } + const next = r.json.view as EditorView; + token.current = next.token; + setView(next); + setError(null); + if (done) setStatus(done); + return r.json; + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + return null; + } finally { + setBusy(false); + } + }; + const p = chain.current.then(run, run); + chain.current = p; + return p; + }, + [project, reload], + ); + + const flush = useCallback(() => { + if (timer.current) clearTimeout(timer.current); + timer.current = null; + const p = pending.current; + pending.current = null; + if (!p) return chain.current; + return write({ op: "trim", clip: p.clip, cutStart: p.cut.cutStart, cutEnd: p.cut.cutEnd }, "Saved the edges").then(() => setDraft(null)); + }, [write]); + + /** Move the edges now; write them after a short pause (a run of nudges is one edit). */ + const setEdges = useCallback( + (next: Cut, { now = false }: { now?: boolean } = {}) => { + const a = r2(Math.max(0, next.cutStart)); + const b = r2(next.cutEnd); + if (b - a < 0.5) { + setError("a clip must be at least half a second"); + return; + } + setError(null); + setDraft({ cutStart: a, cutEnd: b }); + pending.current = { clip: clip.id, cut: { cutStart: a, cutEnd: b } }; + if (timer.current) clearTimeout(timer.current); + if (now) void flush(); + else timer.current = setTimeout(() => void flush(), COMMIT_MS); + }, + [clip.id, flush], + ); + + const choose = useCallback( + (id: string) => { + void flush(); + setSelected(id); + setDraft(null); + setSelection(null); + setSpeakerPick(null); + setPlayhead(null); + setStatus(null); + }, + [flush], + ); + useEffect(() => () => { + if (timer.current) clearTimeout(timer.current); + }, []); + + // ---- the neighbourhood ---------------------------------------------------- + const duration = hood?.duration ?? view.reactions?.source?.duration ?? null; + const viewFrom = Math.max(0, Math.floor(committed.cutStart - reach)); + const viewTo = Math.ceil(duration ? Math.min(duration, committed.cutEnd + reach) : committed.cutEnd + reach); + useEffect(() => { + let live = true; + const q = new URLSearchParams({ project, clip: clip.id, from: String(viewFrom), to: String(viewTo) }); + void fetch(`/api/report/clip-editor?${q}`, { cache: "no-store" }) + .then(async (r) => { + const j = await r.json(); + if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`); + if (live) setHood(j as Neighbourhood); + }) + .catch((e) => live && setError(e instanceof Error ? e.message : String(e))); + return () => { + live = false; + }; + }, [project, clip.id, viewFrom, viewTo]); + const hoodHere = hood && hood.from === viewFrom && hood.to === viewTo ? hood : null; + const points = useMemo(() => (hoodHere ? snapPoints({ words: hoodHere.words, turns: hoodHere.turns, cues: hoodHere.cues }) : []), [hoodHere]); + + // ---- decisions ------------------------------------------------------------ + const rule = (verdict: "keep" | "cut" | null) => { + void flush().then(() => write({ op: "ruling", clip: clip.id, verdict }, verdict ? `Ruled ${verdict}` : "Ruling cleared")); + }; + const splitHere = () => { + const at = playhead; + if (at === null || at - cut.cutStart < 0.5 || cut.cutEnd - at < 0.5) { + setError("put the playhead inside the cut (half a second from either edge) to split there"); + return; + } + void flush().then(() => write({ op: "split", clip: clip.id, at: r2(at) }, `Split at ${edgeClock(at)}`)); + }; + const next = clips[index + 1] ?? null; + const mergeNext = () => { + if (!next) return; + void flush().then(() => write({ op: "merge", clip: clip.id }, `Merged ${next.id} into ${clip.id}`)); + }; + const restore = () => { + void flush().then(() => write({ op: "restore", clip: clip.id }, "Restored the assistant's version")); + }; + const addSelection = () => { + if (!selection) return; + void flush() + .then(() => write({ op: "add", clip: clip.id, cutStart: r2(selection.cutStart), cutEnd: r2(selection.cutEnd) }, "Added a clip")) + .then((j) => { + const id = (j?.result as { id?: string } | undefined)?.id; + setSelection(null); + if (id) choose(id); + }); + }; + const bringIn = (p: Proposal) => { + void flush() + .then(() => write({ op: "bring-in", proposal: p.id }, `Brought in ${p.id}`)) + .then((j) => { + const id = (j?.result as { id?: string } | undefined)?.id; + if (id) choose(id); + }); + }; + const setRole = (speaker: number, role: "host" | "subject" | "other") => { + void write({ op: "role", speaker, role }, `Speaker ${speaker} is the ${ROLE_WORD[role]}`).then((j) => { + if (j) setRolesChanged(true); + }); + }; + // Re-propose: the clip finder's proposal pass as a job (`umtool clips + // propose`, /api/report/clips); clips a person edited are never touched. + const [proposing, setProposing] = useState<{ id: string; state: string; error: string | null } | null>(null); + const repropose = async () => { + await flush(); + setError(null); + const r = await fetch("/api/report/clips", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, mode: "propose" }) }); + const j = (await r.json().catch(() => ({}))) as { job?: { id: string; state: string; error: string | null }; error?: string }; + if (!r.ok || !j.job) setError(j.error ?? `HTTP ${r.status}`); + else setProposing({ id: j.job.id, state: j.job.state, error: j.job.error }); + }; + useEffect(() => { + if (!proposing || proposing.state !== "running") return; + const t = setInterval(async () => { + const r = await fetch(`/api/report/clips?job=${proposing.id}`, { cache: "no-store" }).catch(() => null); + if (!r?.ok) return; + const j = (await r.json()) as { id: string; state: string; error: string | null }; + setProposing({ id: j.id, state: j.state, error: j.error }); + if (j.state !== "running") { + await reload().catch(() => {}); + setRolesChanged(false); + setStatus(j.state === "done" ? "Re-proposed: the assistant's untouched clips follow the new roles" : `Re-propose ${j.state}${j.error ? `: ${j.error}` : ""}`); + } + }, 1500); + return () => clearInterval(t); + }, [proposing, reload]); + const rx = view.reactions; + const rolesStale = rolesChanged || (!!rx?.rolesChangedAt && (!rx.proposedAt || rx.rolesChangedAt > rx.proposedAt)); + const snap = () => { + if (!points.length) { + setError("nothing to snap to here: no words, cues or turns in this span"); + return; + } + const s = snapCut(cut, points); + setEdges(s, { now: true }); + }; + const nudge = (edge: "in" | "out", d: number) => setEdges(edge === "in" ? { cutStart: cut.cutStart + d, cutEnd: cut.cutEnd } : { cutStart: cut.cutStart, cutEnd: cut.cutEnd + d }); + const setAtPlayhead = (edge: "in" | "out") => { + if (playhead === null) return; + nudge(edge, playhead - (edge === "in" ? cut.cutStart : cut.cutEnd)); + }; + const seek = (t: number) => { + setPlayhead(t); + player.current?.seek(t); + }; + + // ---- keys ----------------------------------------------------------------- + const keyRef = useRef<(e: KeyboardEvent) => void>(() => {}); + keyRef.current = (e: KeyboardEvent) => { + if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return; + const t = e.target as HTMLElement | null; + if (t?.closest?.(TYPING) || t?.closest?.("dialog[open]")) return; + const k = e.key.length === 1 ? e.key.toLowerCase() : e.key; + const act: Record<string, () => void> = { + " ": () => player.current?.toggle(), + j: () => seek(Math.max(0, (playhead ?? cut.cutStart) - 2)), + l: () => seek((playhead ?? cut.cutStart) + 2), + i: () => setAtPlayhead("in"), + o: () => setAtPlayhead("out"), + s: splitHere, + m: mergeNext, + k: () => rule("keep"), + x: () => rule("cut"), + ArrowLeft: () => index > 0 && choose(clips[index - 1].id), + ArrowRight: () => index + 1 < clips.length && choose(clips[index + 1].id), + }; + const f = act[k]; + if (!f) return; + e.preventDefault(); + f(); + }; + useEffect(() => { + const on = (e: KeyboardEvent) => keyRef.current(e); + document.addEventListener("keydown", on); + return () => document.removeEventListener("keydown", on); + }, []); + + // ---- what plays ----------------------------------------------------------- + // Named by the clip's EXTENT, not its cut: a trim inside the extent must + // not send the player looking again (and reload the picture) on every save. + const targets = useMemo(() => { + if (!clip.channel) return []; + const base = { channel: clip.channel, video: clip.video, project, clip: clip.id }; + const far = REACHES[0]; + const spans: [number, number][] = [ + [Math.max(0, Math.floor(clip.start - far)), Math.ceil(duration ? Math.min(duration, clip.end + far) : clip.end + far)], + [clip.start, clip.end], + ]; + return spans.filter(([a, b], i) => b > a && spans.findIndex(([x, y]) => x === a && y === b) === i).map(([from, to]) => ({ ...base, from, to })); + }, [clip.channel, clip.video, clip.id, clip.start, clip.end, project, duration]); + + const assist = clip.assist; + const prov = provenanceWords(assist); + const canRestore = !!assist?.original && (assist.original.cutStart ?? assist.original.start) !== undefined; + const edits = assist?.edits ?? []; + const quoteNow = hoodHere ? quoteBetween({ words: hoodHere.words, cues: hoodHere.cues }, cut.cutStart, cut.cutEnd) : null; + const pickRole = speakerPick !== null ? roleOf(speakers, speakerPick) : null; + + return ( + <div data-clip-editor={clip.id} data-clip-editor-busy={busy ? "" : undefined} className="flex min-h-0 flex-1 flex-col lg:grid lg:grid-cols-[minmax(0,1fr)_minmax(300px,26%)]"> + <main data-bench-work="" className="deck-main min-h-0 space-y-3 overflow-auto p-4"> + {/* ---- the clip ---------------------------------------------------- */} + <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1"> + <h1 className="m-0 font-mono text-[15px] font-semibold text-text" data-editor-clip-id=""> + {clip.id} + </h1> + <span className="num font-mono text-[12.5px] text-text-2" data-editor-cut={`${cut.cutStart}-${cut.cutEnd}`}> + {edgeClock(cut.cutStart)} – {edgeClock(cut.cutEnd)} · {(cut.cutEnd - cut.cutStart).toFixed(1)} s + </span> + {draft && <span className="micro" data-editor-unsaved="">unsaved</span>} + {clip.ruling && ( + <span data-editor-ruling={clip.ruling} className={rulingBadge(clip.ruling)}> + {clip.ruling === "keep" ? "kept" : "cut"} + </span> + )} + <span className="text-[12px] text-muted"> + {index + 1} of {clips.length} + </span> + </div> + {prov && ( + <p data-editor-provenance={assist?.by ?? ""} className="m-0 text-[12.5px] text-text-2"> + {prov} + </p> + )} + {(quoteNow ?? clip.quote) && ( + <p data-editor-quote="" className="m-0 max-w-[70ch] text-[13px] leading-snug text-text"> + {quoteNow || clip.quote} + </p> + )} + + <Player ref={player} clipId={clip.id} targets={targets} cut={cut} onTime={setPlayhead} onPlaying={setPlaying} /> + + {/* ---- the strip --------------------------------------------------- */} + <div className="space-y-1"> + <div className="flex flex-wrap items-center gap-2 text-[11.5px] text-muted"> + <span className="micro">around the clip</span> + {REACHES.map((r) => ( + <button + key={r} + type="button" + data-reach={r} + aria-pressed={reach === r} + onClick={() => setReach(r)} + className={buttonVariants({ variant: reach === r ? "pressed" : "quiet", size: "sm" })} + > + ± {r} s + </button> + ))} + {speakers.length > 0 ? ( + <span className="flex flex-wrap items-center gap-2" data-strip-legend=""> + <span className="inline-flex items-center gap-1"> + <span className="inline-block h-2 w-3 rounded-[1px] bg-signal" /> host + </span> + <span className="inline-flex items-center gap-1"> + <span className="inline-block h-2 w-3 rounded-[1px] bg-meter" /> subject + </span> + <span className="inline-flex items-center gap-1"> + <span className="inline-block h-2 w-1 rounded-[1px] bg-doubt" /> laugh + </span> + </span> + ) : ( + <span data-strip-no-speakers="">no speakers for this cut (no reactions.json)</span> + )} + {playhead !== null && <span className="num ml-auto font-mono">{edgeClock(playhead)}{playing ? " ▶" : ""}</span>} + </div> + <Strip + from={viewFrom} + to={viewTo} + cut={cut} + hood={hoodHere} + speakers={speakers} + others={clips.filter((c) => c.id !== clip.id && c.video === clip.video && c.channel === clip.channel)} + playhead={playhead} + selection={selection} + speakerPick={speakerPick} + onSeek={seek} + onEdge={(edge, t, done) => { + const nextCut = edge === "in" ? { cutStart: t, cutEnd: cut.cutEnd } : { cutStart: cut.cutStart, cutEnd: t }; + if (done) setEdges(nextCut, { now: true }); + else if (nextCut.cutEnd - nextCut.cutStart >= 0.5) setDraft({ cutStart: r2(nextCut.cutStart), cutEnd: r2(nextCut.cutEnd) }); + }} + onSelect={setSelection} + onTurn={(t) => setSpeakerPick(t.speaker)} + onOther={choose} + /> + {speakerPick !== null && ( + <div data-speaker-pick={speakerPick} className="flex flex-wrap items-center gap-2 text-[12px] text-text-2"> + <span> + Speaker {speakerPick} · {pickRole ? ROLE_WORD[pickRole] ?? pickRole : "no role"} + {speakers.find((s) => s.index === speakerPick)?.how === "operator" ? " (you said)" : ""} + </span> + {pickRole !== "host" && ( + <button type="button" data-set-host={speakerPick} disabled={busy} onClick={() => setRole(speakerPick, "host")} className={buttonVariants({ size: "sm" })}> + This is the host + </button> + )} + {pickRole === "host" && ( + <button type="button" data-set-subject={speakerPick} disabled={busy} onClick={() => setRole(speakerPick, "subject")} className={buttonVariants({ size: "sm" })}> + Not the host + </button> + )} + <button type="button" onClick={() => setSpeakerPick(null)} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Close + </button> + </div> + )} + {(rolesStale || proposing) && view.reactions && ( + <div data-repropose={proposing?.state ?? ""} className="flex flex-wrap items-center gap-2 text-[12px] text-text-2"> + {rolesStale && <span>The roles changed since the clips were proposed.</span>} + <button + type="button" + data-repropose-button="" + disabled={!view.repropose.available || busy || proposing?.state === "running"} + title={view.repropose.why ?? "the proposal pass again with the new roles; clips you edited stay as they are"} + onClick={() => void repropose()} + className={buttonVariants({ size: "sm" })} + > + {proposing?.state === "running" ? "Re-proposing…" : "Re-propose"} + </button> + {!view.repropose.available && view.repropose.why && <span className="text-muted" data-repropose-why="">{view.repropose.why}</span>} + </div> + )} + <Words hood={hoodHere} cut={cut} playhead={playhead} onSeek={seek} /> + </div> + + {/* ---- the edges --------------------------------------------------- */} + <div className="grid gap-2 sm:grid-cols-2" data-editor-edges=""> + {(["in", "out"] as const).map((edge) => ( + <EdgeControl key={edge} edge={edge} value={edge === "in" ? cut.cutStart : cut.cutEnd} onNudge={(d) => nudge(edge, d)} onSet={(v) => nudge(edge, v - (edge === "in" ? cut.cutStart : cut.cutEnd))} onPlayhead={playhead === null ? null : () => setAtPlayhead(edge)} /> + ))} + </div> + + {/* ---- the decisions ----------------------------------------------- */} + <div className="flex flex-wrap items-center gap-2" data-editor-actions=""> + <button type="button" data-rule="keep" aria-pressed={clip.ruling === "keep"} disabled={busy} onClick={() => rule(clip.ruling === "keep" ? null : "keep")} className={buttonVariants({ variant: clip.ruling === "keep" ? "pressed" : "outline", size: "md" })}> + Keep <kbd>K</kbd> + </button> + <button type="button" data-rule="cut" aria-pressed={clip.ruling === "cut"} disabled={busy} onClick={() => rule(clip.ruling === "cut" ? null : "cut")} className={buttonVariants({ variant: clip.ruling === "cut" ? "pressed" : "outline", size: "md" })}> + Cut <kbd>X</kbd> + </button> + <button type="button" data-action="snap" disabled={busy} onClick={snap} className={buttonVariants({ size: "md" })}> + Snap to words + </button> + <button type="button" data-action="split" disabled={busy} onClick={splitHere} className={buttonVariants({ size: "md" })}> + Split here <kbd>S</kbd> + </button> + <button type="button" data-action="merge" disabled={busy || !next} onClick={mergeNext} className={buttonVariants({ size: "md" })} title={next ? `merge with ${next.id}` : "the last clip"}> + Merge with next <kbd>M</kbd> + </button> + {canRestore && ( + <button type="button" data-action="restore" disabled={busy || assist?.by === "assistant"} onClick={restore} className={buttonVariants({ size: "md" })}> + Restore the assistant&rsquo;s version + </button> + )} + {selection && ( + <button type="button" data-action="add" disabled={busy} onClick={addSelection} className={buttonVariants({ variant: "go", size: "md" })}> + Add a clip {edgeClock(selection.cutStart)}–{edgeClock(selection.cutEnd)} + </button> + )} + </div> + <div aria-live="polite" className="min-h-[1.2em] text-[12px]"> + {error ? ( + <span role="alert" data-editor-error="" className="text-reject-text"> + {error} + </span> + ) : status ? ( + <span data-editor-status="" className="text-muted"> + {status} + </span> + ) : null} + </div> + + {/* ---- comments and history ---------------------------------------- */} + <ClipNotes project={project} clipId={clip.id} /> + {edits.length > 0 && ( + <details data-editor-history={edits.length} className="text-[12px] text-text-2"> + <summary className="cursor-pointer text-muted">{plural(edits.length, "edit")} to this clip</summary> + <ol className="m-0 mt-1 space-y-0.5 pl-5"> + {edits.map((e, i) => ( + <li key={i} data-edit={e.what} className="num font-mono text-[11.5px]"> + {e.what} · {e.from ? `${edgeClock(e.from.cutStart)}–${edgeClock(e.from.cutEnd)} → ` : ""} + {edgeClock(e.to.cutStart)}–{edgeClock(e.to.cutEnd)} · {new Date(e.at).toLocaleString()} + </li> + ))} + </ol> + </details> + )} + </main> + + {/* ---- the list, the proposals, the speakers, the take --------------- */} + <aside className="flex min-h-0 flex-col gap-3 overflow-auto border-t border-seam bg-panel p-3 lg:border-l lg:border-t-0" data-editor-side=""> + <section> + <h2 className="micro mb-1"> + {plural(clips.length, "clip")} · {clips.filter((c) => c.ruling === "keep").length} kept · {clips.filter((c) => c.ruling === "cut").length} cut + </h2> + <ol className="m-0 list-none space-y-0.5 p-0" data-editor-list=""> + {clips.map((c) => { + const cc = cutOf(c); + return ( + <li key={c.id}> + <button + type="button" + data-editor-row={c.id} + aria-current={c.id === clip.id ? "true" : undefined} + onClick={() => choose(c.id)} + className={cn("flex w-full items-baseline gap-2 rounded-[3px] px-1.5 py-1 text-left text-[12px]", c.id === clip.id ? "bg-panel-2 text-text" : "text-text-2 hover:bg-panel-2")} + > + <span className="font-mono text-[11.5px]">{c.id}</span> + <span className="num font-mono text-[11px] text-muted"> + {edgeClock(cc.cutStart)} · {(cc.cutEnd - cc.cutStart).toFixed(0)} s + </span> + <span className="ml-auto flex gap-1"> + {c.assist?.by === "operator" && <span className={badgeVariants({ variant: "info", size: "sm" })}>you</span>} + {c.ruling && <span className={rulingBadge(c.ruling)}>{c.ruling}</span>} + </span> + </button> + </li> + ); + })} + </ol> + </section> + + {view.reactions && ( + <section data-editor-proposals={view.reactions.proposals.length}> + <h2 className="micro mb-1"> + Not in the cut — {plural(view.reactions.proposals.length, "proposal")} of {view.reactions.proposalCount} + </h2> + {view.reactions.proposals.length === 0 ? ( + <p className="m-0 text-[12px] text-muted">Every proposal is in the cut.</p> + ) : ( + <ul className="m-0 list-none space-y-1 p-0"> + {view.reactions.proposals.map((p) => ( + <li key={p.id} data-proposal={p.id} className="flex items-baseline gap-2 text-[12px] text-text-2"> + <span className="font-mono text-[11.5px]">{p.id}</span> + <span className="num font-mono text-[11px] text-muted"> + {edgeClock(p.start)} · {(p.end - p.start).toFixed(0)} s{typeof p.score === "number" ? ` · ${p.score.toFixed(2)}` : ""} + </span> + <span className="min-w-0 flex-1 truncate" title={p.why}> + {p.why} + </span> + <button type="button" data-bring-in={p.id} disabled={busy} onClick={() => bringIn(p)} className={buttonVariants({ size: "sm" })}> + Bring in + </button> + </li> + ))} + </ul> + )} + </section> + )} + + {speakers.length > 0 && ( + <section data-editor-speakers=""> + <h2 className="micro mb-1">Speakers</h2> + <ul className="m-0 list-none space-y-1 p-0"> + {speakers.map((s) => ( + <li key={s.index} data-speaker={s.index} data-speaker-role={s.role ?? ""} className="flex items-center gap-2 text-[12px] text-text-2"> + <span className={cn("inline-block h-2 w-3 rounded-[1px]", ROLE_FILL[s.role ?? "other"] ?? "bg-muted")} /> + <span> + {s.index} · {s.role ? ROLE_WORD[s.role] : "no role"} + {s.how === "operator" ? " (you said)" : s.how === "auto" ? " (auto)" : ""} + {typeof s.sameAs === "number" ? ` · same voice as ${s.sameAs}` : ""} + </span> + <span className="num font-mono text-[11px] text-muted">{typeof s.seconds === "number" ? `${Math.round(s.seconds)} s` : ""}</span> + {s.role !== "host" && ( + <button type="button" data-speaker-host={s.index} disabled={busy} onClick={() => setRole(s.index, "host")} className={cn(buttonVariants({ variant: "quiet", size: "sm" }), "ml-auto")}> + This is the host + </button> + )} + </li> + ))} + </ul> + </section> + )} + {view.reactionsError && <p className="m-0 text-[12px] text-reject-text">{view.reactionsError}</p>} + {view.rulingsError && <p className="m-0 text-[12px] text-reject-text">{view.rulingsError}</p>} + + <RenderTake project={project} render={render} takes={takes} takesHref={takesHref} /> + </aside> + </div> + ); +} + +// --------------------------------------------------------------------------- +// The player: what /api/cited/play finds for the neighbourhood, else the +// clip's extent, else its cut; loops the cut. +// --------------------------------------------------------------------------- + +type PlayerHandle = { toggle: () => void; seek: (t: number) => void }; +type Target = { channel: string; video: string; from: number; to: number; project: string; clip: string }; + + +const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut: Cut; onTime: (t: number) => void; onPlaying: (p: boolean) => void }>(function Player({ clipId, targets, cut, onTime, onPlaying }, ref) { + const [found, setFound] = useState<{ play: CitedPlay; from: number } | null | undefined>(undefined); + const media = useRef<HTMLMediaElement | null>(null); + // The seek to the cut on load is the player's own, not a person's: it must + // not move the playhead somebody just set by clicking a word. + const ownSeek = useRef(false); + const cutRef = useRef(cut); + cutRef.current = cut; + const key = targets.map((t) => `${t.clip}|${t.from}|${t.to}`).join(","); + + useEffect(() => { + let live = true; + // The same file at the same clock keeps playing: only a different answer + // replaces the media element. + const settle = (next: { play: CitedPlay; from: number } | null) => + setFound((was) => (was && next && was.play.url === next.play.url && was.play.offset - was.from === next.play.offset - next.from ? was : next)); + (async () => { + for (const t of targets) { + const q = new URLSearchParams({ channel: t.channel, video: t.video, from: String(t.from), to: String(t.to), project: t.project, clip: t.clip }); + const r = await fetch(`/api/cited/play?${q}`, { cache: "no-store" }).catch(() => null); + const j = r?.ok ? ((await r.json()) as { play: CitedPlay | null }) : null; + if (j?.play) { + if (live) settle({ play: j.play, from: t.from }); + return; + } + } + if (live) settle(null); + })(); + return () => { + live = false; + }; + // `targets` is named by its key. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key]); + + // Another clip on the same file: go to its cut, paused. + useEffect(() => { + const m = media.current; + if (!m || m.readyState < 1 || !found) return; + m.pause(); + ownSeek.current = true; + m.currentTime = Math.max(0, cutRef.current.cutStart - found.from + found.play.offset); + // Only a change of clip moves the picture. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [clipId]); + + const fileT = (t: number) => (found ? Math.max(0, t - found.from + found.play.offset) : 0); + const sourceT = (ft: number) => (found ? ft - found.play.offset + found.from : 0); + + useImperativeHandle(ref, () => ({ + toggle: () => { + const m = media.current; + if (!m) return; + if (!m.paused) return m.pause(); + const t = sourceT(m.currentTime); + if (t < cutRef.current.cutStart - 0.05 || t >= cutRef.current.cutEnd - 0.05) m.currentTime = fileT(cutRef.current.cutStart); + void m.play().catch(() => {}); + }, + seek: (t: number) => { + const m = media.current; + if (!m) return; + ownSeek.current = true; + m.currentTime = fileT(t); + }, + })); + + if (found === undefined) return <div data-editor-player="looking" className="flex aspect-video w-full max-w-[720px] items-center justify-center rounded-[3px] bg-panel-2 text-[12px] text-muted">looking for the clip…</div>; + if (found === null) + return ( + <div data-editor-player="none" className="flex aspect-video w-full max-w-[720px] flex-col items-center justify-center gap-1 rounded-[3px] bg-panel-2 text-center text-[12px] text-muted"> + <span>Nothing on disk plays this clip.</span> + <span>Fetch its window from the Cut tab (Fetch windows), then come back.</span> + </div> + ); + const props = { + ref: (el: HTMLMediaElement | null) => { + media.current = el; + }, + src: found.play.url, + preload: "auto", + "data-player": "", + tabIndex: -1, + controls: true, + onLoadedMetadata: (e: React.SyntheticEvent<HTMLMediaElement>) => { + ownSeek.current = true; + e.currentTarget.currentTime = fileT(cutRef.current.cutStart); + }, + onSeeked: (e: React.SyntheticEvent<HTMLMediaElement>) => { + if (ownSeek.current) ownSeek.current = false; + else onTime(sourceT(e.currentTarget.currentTime)); + }, + onTimeUpdate: (e: React.SyntheticEvent<HTMLMediaElement>) => { + if (e.currentTarget.paused) return; + const t = sourceT(e.currentTarget.currentTime); + onTime(t); + // Loop the cut while it plays inside it. + if (!e.currentTarget.paused && t >= cutRef.current.cutEnd && t < cutRef.current.cutEnd + 0.6) e.currentTarget.currentTime = fileT(cutRef.current.cutStart); + }, + onPlay: () => onPlaying(true), + onPause: () => onPlaying(false), + onFocus: (e: React.FocusEvent<HTMLMediaElement>) => e.currentTarget.blur(), + }; + return ( + <div data-editor-player={found.play.kind} className="w-full max-w-[720px]"> + {found.play.audio ? <audio {...props} className="w-full" /> : <video {...props} playsInline className="aspect-video w-full rounded-[3px] bg-black" />} + <span className="micro">{found.play.label}</span> + </div> + ); +}); + +// --------------------------------------------------------------------------- +// The strip: [from, to] across the width. Turns by role, laughs, word ticks, +// the other clips, the cut with two handles, the playhead, a selection. +// --------------------------------------------------------------------------- + +function Strip({ + from, + to, + cut, + hood, + speakers, + others, + playhead, + selection, + speakerPick, + onSeek, + onEdge, + onSelect, + onTurn, + onOther, +}: { + from: number; + to: number; + cut: Cut; + hood: Neighbourhood | null; + speakers: Speaker[]; + others: EditorClip[]; + playhead: number | null; + selection: Cut | null; + speakerPick: number | null; + onSeek: (t: number) => void; + onEdge: (edge: "in" | "out", t: number, done: boolean) => void; + onSelect: (s: Cut | null) => void; + onTurn: (t: Turn) => void; + onOther: (id: string) => void; +}) { + const box = useRef<HTMLDivElement | null>(null); + const span = Math.max(0.001, to - from); + const pct = (t: number) => `${(Math.min(Math.max(t, from), to) - from) / span * 100}%`; + const width = (a: number, b: number) => `${Math.max(0, Math.min(b, to) - Math.max(a, from)) / span * 100}%`; + const tAt = (clientX: number) => { + const r = box.current!.getBoundingClientRect(); + return r2(from + ((clientX - r.left) / Math.max(1, r.width)) * span); + }; + const drag = useRef<{ kind: "in" | "out" | "select"; x0: number; t0: number } | null>(null); + + const down = (kind: "in" | "out" | "select") => (e: React.PointerEvent) => { + if (e.button !== 0) return; + e.stopPropagation(); + (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); + drag.current = { kind, x0: e.clientX, t0: tAt(e.clientX) }; + }; + const move = (e: React.PointerEvent) => { + const d = drag.current; + if (!d) return; + const t = tAt(e.clientX); + if (d.kind === "select") { + if (Math.abs(e.clientX - d.x0) > 4) onSelect({ cutStart: Math.min(d.t0, t), cutEnd: Math.max(d.t0, t) }); + } else onEdge(d.kind, t, false); + }; + const up = (e: React.PointerEvent) => { + const d = drag.current; + drag.current = null; + if (!d) return; + const t = tAt(e.clientX); + if (d.kind === "select") { + if (Math.abs(e.clientX - d.x0) <= 4) { + onSelect(null); + onSeek(t); + } else if (Math.abs(t - d.t0) < 0.5) onSelect(null); + } else onEdge(d.kind, t, true); + }; + + const turns = hood?.turns ?? []; + const role = (sp: number) => roleOf(speakers, sp); + return ( + <div + ref={box} + data-strip={`${from}-${to}`} + onPointerDown={down("select")} + onPointerMove={move} + onPointerUp={up} + className="relative h-[86px] w-full touch-none select-none overflow-hidden rounded-[3px] border border-seam bg-panel-2" + > + {/* turns, top lane */} + {turns.map((t, i) => { + const r = role(t.speaker); + return ( + <button + key={i} + type="button" + data-turn={i} + data-turn-speaker={t.speaker} + data-turn-role={r ?? ""} + title={`speaker ${t.speaker}${r ? ` · ${ROLE_WORD[r] ?? r}` : ""} · ${edgeClock(t.start)}–${edgeClock(t.end)}`} + onPointerDown={(e) => e.stopPropagation()} + onClick={() => onTurn(t)} + style={{ left: pct(t.start), width: width(t.start, t.end) }} + className={cn( + "absolute top-1 h-4 rounded-[1px] opacity-80 hover:opacity-100", + r ? ROLE_FILL[r] ?? "bg-muted" : "bg-muted", + speakerPick === t.speaker && "outline outline-1 outline-text", + r === "subject" && "top-6", + )} + /> + ); + })} + {/* laughs */} + {(hood?.laughs ?? []).map((l, i) => ( + <span key={i} data-laugh={i} title={`laugh${l.score !== null ? ` · ${l.score.toFixed(2)}` : ""}`} style={{ left: pct(l.start), width: width(l.start, l.end) }} className="pointer-events-none absolute top-[44px] h-2 min-w-[3px] rounded-[1px] bg-doubt" /> + ))} + {/* word ticks */} + {(hood?.words ?? hood?.cues ?? []).map((w, i) => ( + <span key={i} style={{ left: pct(w.start) }} className="pointer-events-none absolute bottom-1 h-2 w-px bg-muted-2 opacity-60" /> + ))} + {/* the other clips */} + {others.map((c) => { + const cc = cutOf(c); + if (cc.cutEnd < from || cc.cutStart > to) return null; + return ( + <button + key={c.id} + type="button" + data-other-clip={c.id} + title={`${c.id} — open it`} + onPointerDown={(e) => e.stopPropagation()} + onClick={() => onOther(c.id)} + style={{ left: pct(cc.cutStart), width: width(cc.cutStart, cc.cutEnd) }} + className="absolute bottom-0 h-[14px] rounded-t-[2px] border border-b-0 border-seam-2 bg-[color-mix(in_srgb,var(--text)_8%,transparent)] font-mono text-[9px] text-muted" + > + {c.id} + </button> + ); + })} + {/* the selection to add */} + {selection && <span data-selection={`${selection.cutStart}-${selection.cutEnd}`} style={{ left: pct(selection.cutStart), width: width(selection.cutStart, selection.cutEnd) }} className="pointer-events-none absolute inset-y-0 border-x border-dashed border-text bg-[color-mix(in_srgb,var(--text)_10%,transparent)]" />} + {/* the cut */} + <span data-strip-cut="" style={{ left: pct(cut.cutStart), width: width(cut.cutStart, cut.cutEnd) }} className="pointer-events-none absolute inset-y-0 border-y-2 border-signal bg-[color-mix(in_srgb,var(--signal)_14%,transparent)]" /> + {(["in", "out"] as const).map((edge) => ( + <span + key={edge} + role="slider" + aria-label={edge === "in" ? "In point" : "Out point"} + aria-valuemin={from} + aria-valuemax={to} + aria-valuenow={edge === "in" ? cut.cutStart : cut.cutEnd} + data-handle={edge} + onPointerDown={down(edge)} + style={{ left: pct(edge === "in" ? cut.cutStart : cut.cutEnd) }} + className="absolute inset-y-0 z-10 w-3 -translate-x-1/2 cursor-ew-resize" + > + <span className="absolute inset-y-0 left-1/2 w-[3px] -translate-x-1/2 rounded bg-signal" /> + </span> + ))} + {playhead !== null && playhead >= from && playhead <= to && <span data-playhead={playhead} style={{ left: pct(playhead) }} className="pointer-events-none absolute inset-y-0 w-px bg-text" />} + </div> + ); +} + +/** The words of the neighbourhood as text: the cut's lit, the one playing marked; a click seeks there. */ +function Words({ hood, cut, playhead, onSeek }: { hood: Neighbourhood | null; cut: Cut; playhead: number | null; onSeek: (t: number) => void }) { + if (!hood) return <p className="m-0 text-[12px] text-muted">reading the words…</p>; + const list = hood.words?.length ? hood.words.map((w) => ({ text: w.w, start: w.start, end: w.end })) : (hood.cues ?? []).map((c) => ({ text: c.text, start: c.start, end: c.end })); + if (!list.length) return <p className="m-0 text-[12px] text-muted">No words or cues for this span.</p>; + return ( + <p data-editor-words={hood.words?.length ? "words" : "cues"} className="m-0 max-h-[9.5em] overflow-auto text-[13px] leading-relaxed text-muted"> + {list.map((w, i) => { + const mid = (w.start + w.end) / 2; + const inCut = mid >= cut.cutStart && mid <= cut.cutEnd; + const now = playhead !== null && playhead >= w.start && playhead < w.end; + return ( + <span key={i}> + <button + type="button" + data-word={i} + data-word-t={w.start} + data-in-cut={inCut ? "" : undefined} + onMouseDown={(e) => e.preventDefault()} + onClick={() => onSeek(w.start)} + className={cn("rounded-[2px] px-[1px] hover:bg-panel-2", inCut && "text-text", now && "bg-[color-mix(in_srgb,var(--signal)_30%,transparent)]")} + > + {w.text} + </button>{" "} + </span> + ); + })} + </p> + ); +} + +function EdgeControl({ edge, value, onNudge, onSet, onPlayhead }: { edge: "in" | "out"; value: number; onNudge: (d: number) => void; onSet: (v: number) => void; onPlayhead: (() => void) | null }) { + const [text, setText] = useState(String(value)); + useEffect(() => setText(String(value)), [value]); + const commit = () => { + const v = Number(text); + if (Number.isFinite(v) && v !== value) onSet(v); + else setText(String(value)); + }; + return ( + <div data-edge={edge} className="flex flex-wrap items-center gap-1 rounded-[3px] border border-seam bg-panel p-2"> + <label className="micro mr-1" htmlFor={`edge-${edge}`}> + {edge === "in" ? "In" : "Out"} + </label> + <input + id={`edge-${edge}`} + data-edge-input={edge} + type="number" + step={0.01} + min={0} + value={text} + onChange={(e) => setText(e.target.value)} + onBlur={commit} + onKeyDown={(e) => { + if (e.key === "Enter") { + commit(); + (e.target as HTMLInputElement).blur(); + } + if (e.key === "Escape") { + setText(String(value)); + (e.target as HTMLInputElement).blur(); + } + }} + className="num w-[6.5em] rounded border border-seam-2 bg-ground px-1.5 py-0.5 font-mono text-[12px] text-text outline-none focus:border-signal" + /> + {NUDGES.map((d) => ( + <button key={d} type="button" data-nudge={`${edge}:${d}`} onMouseDown={(e) => e.preventDefault()} onClick={() => onNudge(d)} className={buttonVariants({ variant: "quiet", size: "sm" })}> + {d > 0 ? `+${d}` : `−${Math.abs(d)}`} + </button> + ))} + <button type="button" data-edge-playhead={edge} disabled={!onPlayhead} onMouseDown={(e) => e.preventDefault()} onClick={() => onPlayhead?.()} className={buttonVariants({ variant: "quiet", size: "sm" })} title="set at the playhead"> + at playhead <kbd>{edge === "in" ? "I" : "O"}</kbd> + </button> + </div> + ); +} + +/** The notes on one clip: its thread (an agent's replies too), resolve / reopen, a box for another. */ +function ClipNotes({ project, clipId }: { project: string; clipId: string }) { + const notes = useSharedNotes({ project }); + const [text, setText] = useState(""); + const mine = notesOn(notes.notes, { kind: "entry", entry: clipId }).filter((n) => n.anchor.kind !== "moment"); + const open = mine.filter((n) => n.status === "open").length; + const add = async () => { + if (!text.trim()) return; + const n = await notes.write({ op: "add", text, anchor: { kind: "entry", entry: clipId } }); + if (n) setText(""); + }; + return ( + <section data-clip-notes={clipId} data-open-notes={open} className="space-y-1.5 rounded-[3px] border border-seam bg-panel p-2.5"> + <h2 className="micro m-0">Comments{mine.length ? ` — ${open} open of ${mine.length}` : ""}</h2> + {mine.map((n) => ( + <NoteThread key={n.id} note={n} write={notes.write} busy={notes.busy} head={n.anchor.kind === "edit" ? <span className={badgeVariants({ variant: "info", size: "sm" })}>edit · {n.anchor.field}</span> : null} /> + ))} + <div className="flex flex-wrap items-start gap-2"> + <textarea + data-clip-note-input="" + value={text} + rows={2} + onChange={(e) => setText(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) void add(); + if (e.key === "Escape") (e.target as HTMLTextAreaElement).blur(); + }} + placeholder={`a comment on ${clipId} — for you or the assistant`} + className="min-w-[16rem] flex-1 resize-y rounded border border-seam-2 bg-ground px-1.5 py-1 text-[12.5px] text-text outline-none focus:border-signal" + /> + <button type="button" data-clip-note-add="" disabled={notes.busy || !text.trim()} onClick={() => void add()} className={buttonVariants({ size: "md" })}> + Add comment + </button> + </div> + {notes.error && <div className="text-[12px] text-reject-text">{notes.error}</div>} + </section> + ); +} + +/** Render a take: the picked (or the whole-cut) take made again, else the Takes page. */ +function RenderTake({ project, render, takes, takesHref }: { project: string; render: RenderTarget; takes: number; takesHref: string }) { + const [job, setJob] = useState<{ id: string; state: string; error: string | null } | null>(null); + const [err, setErr] = useState<string | null>(null); + useEffect(() => { + if (!job || job.state !== "running") return; + const t = setInterval(async () => { + const r = await fetch(`/api/report/takes/make?job=${job.id}`, { cache: "no-store" }).catch(() => null); + if (!r?.ok) return; + const j = (await r.json()) as { id: string; state: string; error: string | null }; + setJob({ id: j.id, state: j.state, error: j.error }); + }, 1500); + return () => clearInterval(t); + }, [job]); + const remake = async () => { + if (!render) return; + setErr(null); + const r = await startTakeJob({ project, rebuild: render.take }); + if (r.error || !r.job) setErr(r.error ?? "the take did not start"); + else setJob({ id: r.job.id, state: r.job.state, error: r.job.error }); + }; + return ( + <section data-editor-render="" className="space-y-1.5"> + <h2 className="micro m-0">Render</h2> + {render ? ( + <button type="button" data-render-take={render.take} disabled={job?.state === "running"} onClick={() => void remake()} className={buttonVariants({ variant: "go", size: "md" })}> + Render the take again — {render.label} + </button> + ) : ( + <Link href={takesHref} prefetch={false} data-render-takes="" className={buttonVariants({ variant: "go", size: "md" })}> + {takes ? "Choose a take to render" : "Make a take"} + </Link> + )} + {job && ( + <p data-render-job={job.state} className="m-0 text-[12px] text-text-2"> + {job.state === "running" ? "Rendering" : job.state === "done" ? "Rendered" : `Failed${job.error ? `: ${job.error}` : ""}`} —{" "} + <Link href={takesHref} prefetch={false} className="ink-link"> + the Takes page + </Link> + </p> + )} + {err && ( + <p role="alert" className="m-0 text-[12px] text-reject-text"> + {err} + </p> + )} + </section> + ); +} diff --git a/umtool/docs/notes.md b/umtool/docs/notes.md @@ -5,7 +5,7 @@ | On | Where in umtool | |---|---| | an article (the store's `/articles/<id>`, or a site's `/sites/<site>/<report>`) | the piece's **Article** tab: a passage, a section, a citation, the whole article ([piece.md](piece.md#reading-and-noting-the-article-tab)); a timed note on its video | -| a report-video project | the **Cut** tab's rows and the clip bench (`entry`), the takes bench (`take`), the **Build** tab's final video and a take's preview (`moment`), an edit to a generated manifest (`edit`) | +| a report-video project | the **Cut** tab's rows, the clip bench and the clip editor's **Comments** on a clip (`entry`, [report-video.md](report-video.md#reviewing-assistant-clips-the-clip-editor)), the takes bench (`take`), the **Build** tab's final video and a take's preview (`moment`), an edit to a generated manifest (`edit`) | | a song | the song piece's **Notes** tab and the notes beside each cut and file (a song's own `notes.json`, not this store) | A note is saved where the agent that made the thing can read it back, act on the right SOURCE file, and reply or diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -1075,6 +1075,76 @@ rolesChangedAt?}`. The clip editor changes only a speaker's role, through `setSpeakerRole` (`yt-dlp-transcript-common/lib/clips/reactions.mjs`), which records `rolesChangedAt` so the page can offer Re-propose. +## Reviewing assistant clips: the clip editor + +When an assistant made the clips (the clip finder's highlights, release 35: +each clip carries `assist`), a person hops in on them at +`/projects/<id>/clips` — the **Clip editor** button on the Cut tab of any cut +that is not a montage (a montage's clips keep the clip deck above; `?mode=edit` +opens the editor on one too). It works on every report video; with no +`reactions.json` the strip has no speaker colours or laughs, and trimming, +keep / cut and comments work the same. Nothing in it calls a model. + +- **The player** loops the selected clip's cut, from what is on disk: a saved + video, a clip window, or audio (the cited clip's own lookup). Nothing on disk: + fetch the windows from the Cut tab first. +- **The strip** under it is the clip's neighbourhood, ± 60 s (± 20 s, ± 6 s to + look closer): the speaker turns coloured host / subject (`reactions.json`), + the laughs, a tick per word, the other clips (a click opens one), and the cut + with a handle at each edge to drag. A drag on the strip selects a span: **Add a + clip** from it. A click puts the playhead there; so does a click on a word in + the words under the strip (the project's word timings, else the cues; the + cut's words are lit). +- **The edges:** a number field each, nudges ±0.1 / ±0.5 / ±2 s, **at + playhead**, and **Snap to words** (each edge to the nearest gap between two + words, the edge of a silence between turns, or with no word timings a cue + boundary, within 1.5 s). A run of nudges is written once, after a short pause. + A cut that grows past its extent widens the extent; an assistant's clip's + quote follows its words. +- **The decisions:** **Keep** / **Cut** (`montage-rulings.json`, the deck's + file, keyed by the moment — a render leaves a cut clip out), **Split here** + (at the playhead, half a second inside the cut), **Merge with next** (the next + clip of the same recording; a card between them refuses), **Restore the + assistant's version** (`assist.original`), and **Bring in** one of the + proposals not in the cut. A ruling follows its clip: an edit that moves the + clip's start moves its keep / cut to the new moment, and a clip merged away + takes its ruling with it. +- **Provenance:** "by the assistant · 0.83 · why", or "edited by you · 3 + edits" / "added by you" / "brought in by you", and the edit history. +- **Comments** are notes anchored to the clip (`{kind: "entry", entry: + <clip id>}` in `notes.json`), with their thread — an agent's replies too — + and Resolve / Reopen: the same notes `umtool notes` reads and answers. +- **Speakers:** a click on a turn says whose it is; **This is the host** (or + **Not the host**) writes that speaker's role into `reactions.json` through the + clip finder's writer (`how: "operator"`; the speaker who held the role is + handed back as "other"), and while the roles changed after the last proposal + pass (`rolesChangedAt` later than `proposedAt`) **Re-propose** is offered: the + clip finder's `umtool clips propose` as a job, which never touches a clip a + person edited. +- **Render:** the picked take (or the one whole-cut take) made again, else the + Takes page. + +Keys: space play / pause, `j` / `l` back / on 2 s, `i` / `o` in / out at the +playhead, `s` split, `m` merge, `k` keep, `x` cut, ← / → the previous / next +clip. + +What a person's edit writes into the clip's `assist` (the clip finder's key): +the first edit of its cut flips `by` to `"operator"` (a re-propose never +touches it again) and every edit appends `{at, by: "operator", what: "trim" | +"split" | "merge" | "add" | "restore", from: {cutStart, cutEnd} | null, to: +{cutStart, cutEnd}}` to `edits` (the newest 200 kept). **Restore** puts +`original` back and makes the clip the assistant's again (`by: "assistant"`). +A split's first half keeps the id and `original`; the second is a fresh id +(`r004-2`), the operator's, with no `original`. A merge keeps the first clip's +id. A clip added from the strip is `{by: "operator", edits: [add]}`; a proposal +brought in also keeps `proposal`, `score`, `why` and the proposal's edges as +`original` (a proposal's start/end is the cut; the window is 1.5 s wider each +side). Split, merge and add are structural edits: each takes an +`auto-before-<op>` snapshot first, so the Cut tab's **Undo last edit** takes it +back. The writers are `lib/report/manifest.mjs` (`updateClip`, `restoreClip`, +`splitClip`, `mergeClips`, `addClip`); the editor's operations are +`lib/report/clipEditor.mjs` behind `/api/report/clip-editor`. + ## Operator notes, timed notes and the generated-manifest guard Notes on a project live in `<project>/notes.json` (shape and CLI: diff --git a/umtool/e2e/clip-editor.spec.ts b/umtool/e2e/clip-editor.spec.ts @@ -0,0 +1,140 @@ +import { test, expect } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// The clip editor (release 35 C2): a person hops in on an assistant's clips. +// The Cut tab links it; the strip colours the turns by role and marks the +// laughs; a nudge trims (the clip is "edited by you"); K keeps and the ruling +// follows the clip when its start moves; a word click puts the playhead there +// and Split here cuts the clip in two; Merge with next joins them; Restore +// puts the assistant's version back; X cuts; a comment is a note anchored to +// the clip and an agent's reply shows in its thread; an unused proposal is +// brought in; "This is the host" writes the speaker's role (the clip +// finder's writer) and offers Re-propose. Fixture: e2e/fixtures/clip-editor-fixture.mjs. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const PROJECT = "reports/clip-editor-fixture"; +const DIR = path.join(FIXTURE, "reports", "clip-editor-fixture"); + +type Clip = { id: string; start: number; end: number; cutStart?: number; cutEnd?: number; quote?: string; assist?: { by: string; proposal?: string; edits: { what: string }[] } }; +const json = (name: string) => { + try { + return JSON.parse(readFileSync(path.join(DIR, name), "utf8")); + } catch { + return null; + } +}; +const clips = (): Clip[] => (json("video.manifest.json")?.timeline ?? []).filter((e: { type: string }) => e.type === "clip"); +const clip = (id: string) => clips().find((c) => c.id === id) ?? null; +const ruling = (at: string) => (json("montage-rulings.json")?.rulings ?? {})[`testchan/vid1@${at}`]?.verdict ?? null; + +test("the clip editor: trim, keep (the ruling follows), split, merge, restore, cut, comment + an agent's reply, bring in, the host", async ({ page, request }) => { + test.setTimeout(150_000); + await page.setViewportSize({ width: 1366, height: 900 }); + + // The Cut tab links the editor for a cut that is not a montage. + await page.goto(urls.section(PROJECT, "cut")); + const link = page.locator("[data-clip-editor-link]"); + await expect(link).toHaveAttribute("data-clip-editor-link", "3"); + await expect(link).toContainText("Clip editor — 3 clips · 3 by the assistant"); + await link.click(); + + const editor = page.locator("[data-clip-editor]"); + await expect(editor).toHaveAttribute("data-clip-editor", "r001"); + await expect(page.locator("[data-editor-provenance]")).toHaveText("by the assistant · 0.80 · host laughs at the line"); + await expect(page.locator("[data-editor-player]")).not.toHaveAttribute("data-editor-player", "looking", { timeout: 15_000 }); + // The strip: turns by role, laughs, the words. + await expect(page.locator('[data-turn-role="host"]')).toHaveCount(3); + await expect(page.locator('[data-turn-role="subject"]')).toHaveCount(3); + await expect(page.locator("[data-laugh]")).toHaveCount(2); + await expect(page.locator("[data-editor-words]")).toHaveAttribute("data-editor-words", "words"); + await expect(page.locator("[data-editor-proposals]")).toHaveAttribute("data-editor-proposals", "2"); + + // A nudge trims: out +0.5. The clip is the operator's now. + await page.locator('[data-nudge="out:0.5"]').click(); + await expect.poll(() => clip("r001")?.cutEnd).toBe(3.5); + expect(clip("r001")?.assist?.by).toBe("operator"); + await expect(page.locator("[data-editor-provenance]")).toContainText("edited by you · the assistant scored it 0.80 · 1 edit"); + + // K keeps; moving the in point moves the ruling with the clip. + await page.keyboard.press("k"); + await expect.poll(() => ruling("1.00")).toBe("keep"); + await page.locator('[data-nudge="in:0.5"]').click(); + await expect.poll(() => ruling("1.50")).toBe("keep"); + expect(ruling("1.00")).toBeNull(); + await expect(page.locator("[data-editor-ruling]")).toHaveAttribute("data-editor-ruling", "keep"); + + // A word puts the playhead there; Split here. + await page.locator('[data-word-t="2.4"]').click(); + await expect(page.locator("[data-playhead]")).toHaveCount(1); + await page.locator('[data-action="split"]').click(); + await expect.poll(() => clip("r001-2")?.cutStart).toBe(2.4); + expect(clip("r001")?.cutEnd).toBe(2.4); + expect(clip("r001-2")?.quote).toBe("sentence. And"); + await expect(page.locator('[data-editor-row="r001-2"]')).toHaveCount(1); + + // Merge with next joins them again. + await page.locator('[data-action="merge"]').click(); + await expect.poll(() => clip("r001-2")).toBeNull(); + expect([clip("r001")?.cutStart, clip("r001")?.cutEnd]).toEqual([1.5, 3.5]); + + // Restore the assistant's version: the edges, and the clip is the assistant's again. + await page.locator('[data-action="restore"]').click(); + await expect.poll(() => clip("r001")?.cutStart).toBe(1); + expect(clip("r001")?.cutEnd).toBe(3); + expect(clip("r001")?.assist?.by).toBe("assistant"); + expect(clip("r001")?.assist?.edits.map((e) => e.what)).toEqual(["trim", "trim", "split", "merge", "restore"]); + await expect.poll(() => ruling("1.00")).toBe("keep"); + await expect(page.locator("[data-editor-provenance]")).toHaveText("by the assistant · 0.80 · host laughs at the line"); + + // → the next clip; X cuts it. + await page.keyboard.press("ArrowRight"); + await expect(editor).toHaveAttribute("data-clip-editor", "r002"); + await page.keyboard.press("x"); + await expect.poll(() => ruling("4.00")).toBe("cut"); + + // A comment: a note anchored to the clip. + await page.locator("[data-clip-note-input]").fill("tighten the start, he breathes first"); + await page.locator("[data-clip-note-add]").click(); + await expect(page.locator('[data-clip-notes="r002"] [data-note-id]')).toHaveCount(1); + type Note = { id: string; status: string; anchor: { kind: string; entry?: string }; replies: { author: string; text: string }[] }; + const notes = (): Note[] => json("notes.json")?.notes ?? []; + await expect.poll(() => notes().length).toBe(1); + expect(notes()[0].anchor).toEqual({ kind: "entry", entry: "r002" }); + // An agent replies (as the MCP's notes tool does); the thread shows it. + const read = await (await request.get(`/api/notes?project=${encodeURIComponent(PROJECT)}`)).json(); + const replied = await request.post(`/api/notes?project=${encodeURIComponent(PROJECT)}`, { + headers: { authorization: "Bearer umtool-e2e-token" }, + data: { token: read.token, op: { op: "reply", id: notes()[0].id, text: "moved the in point to the breath" } }, + }); + expect(replied.ok()).toBe(true); + await page.reload(); + await expect(editor).toHaveAttribute("data-clip-editor", "r002"); + const thread = page.locator('[data-clip-notes="r002"] [data-note-id]'); + await expect(thread.locator("[data-note-reply]")).toContainText("moved the in point to the breath"); + await thread.locator('[data-note-action="resolve"]').click(); + await expect.poll(() => notes()[0].status).toBe("resolved"); + await expect(page.locator('[data-clip-notes="r002"]')).toHaveAttribute("data-open-notes", "0"); + + // Bring in an unused proposal: it is a clip, the operator's, and leaves the list. + await page.locator('[data-bring-in="p004"]').click(); + await expect(editor).toHaveAttribute("data-clip-editor", "vid1-9"); + await expect(page.locator("[data-editor-proposals]")).toHaveAttribute("data-editor-proposals", "1"); + expect(clip("vid1-9")).toMatchObject({ start: 7.5, end: 13.5, cutStart: 9, cutEnd: 12, assist: { by: "operator", proposal: "p004" } }); + expect(clips().map((c) => c.id)).toEqual(["r001", "r002", "r003", "vid1-9"]); + + // "This is the host" on a subject turn: the role is the operator's; Re-propose is offered. + await page.locator('[data-turn-speaker="1"]').first().click(); + await page.locator('[data-set-host="1"]').click(); + await expect.poll(() => json("reactions.json")?.speakers?.[1]).toMatchObject({ index: 1, role: "host", how: "operator" }); + // The clip finder's writer: one host, so the other speaker is handed back as "other". + expect(json("reactions.json")?.speakers?.[0]?.role).toBe("other"); + await expect(page.locator("[data-repropose-button]")).toBeEnabled(); + await expect(page.locator('[data-turn-role="subject"]')).toHaveCount(0); + await expect(page.locator('[data-turn-role="other"]')).toHaveCount(3); +}); diff --git a/umtool/e2e/fixtures/clip-editor-fixture.mjs b/umtool/e2e/fixtures/clip-editor-fixture.mjs @@ -0,0 +1,77 @@ +// What clip-editor.spec.ts edits (release 35 C2): a report video of three +// clips an assistant proposed (the clip finder's `assist` on each) on one +// synthetic source (vid1, its cues the fixture corpus's), the source's +// reactions.json (two speakers, host and subject, their turns, two laughs, +// five proposals -- two not in the cut) and its word timings (the cue text +// spread evenly over each cue), and every clip's window cached in the +// project's out/clips-raw (a copy of vid1's 0-9 s). Its own project: the spec +// writes the manifest, montage-rulings.json, notes.json and reactions.json. +// +// r001 1.0-3.0 (p001) r002 4.0-6.0 (p002) r003 6.5-8.5 (p003) +// unused: p004 9-12, p005 13-15 +// +// Synthetic, like every fixture. +import { copyFileSync, mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +const write = (dir, name, doc) => { + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, name), JSON.stringify(doc, null, 2) + "\n"); +}; + +/** + * @param {{ reports: string, manifest: Function, cachedWindow: string, cues: Array<[number, number, string]> }} o + */ +export function makeClipEditorFixture({ reports, manifest, cachedWindow, cues }) { + const dir = path.join(reports, "clip-editor-fixture"); + const assist = (p, s, e, cs, ce, score, why) => ({ by: "assistant", proposal: p, score, why, original: { start: s, end: e, cutStart: cs, cutEnd: ce }, edits: [] }); + const clip = (id, s, e, cs, ce, p, score, why, quote) => ({ type: "clip", id, video: "vid1", start: s, end: e, cutStart: cs, cutEnd: ce, quote, assist: assist(p, s, e, cs, ce, score, why) }); + const doc = manifest("clip-editor-fixture", "The Clip Editor Fixture", { siteOrigin: "https://archive.example" }, [ + clip("r001", 0.5, 3.5, 1, 3, "p001", 0.8, "host laughs at the line", "This is a complete sentence."), + clip("r002", 4, 6, 4, 6, "p002", 0.7, "a comment", "And this one runs on"), + clip("r003", 6.5, 8.5, 6.5, 8.5, "p003", 0.6, "a short comment", "of that it finishes here."), + ]); + doc.render.fetchPad = 0; + write(dir, "video.manifest.json", doc); + + const words = []; + for (const [start, end, text] of cues) { + const ws = text.split(/\s+/).filter(Boolean); + const step = (end - start) / ws.length; + ws.forEach((w, i) => words.push({ w, start: +(start + i * step).toFixed(2), end: +(start + (i + 0.8) * step).toFixed(2) })); + } + write(dir, "words.json", { words }); + write(dir, "reactions.json", { + version: 1, + source: { channel: "testchan", video: "vid1", duration: 21, words: "words.json", diarization: { generatedAt: "2026-01-01T00:00:00.000Z", engine: "sherpa-onnx" } }, + params: { target: 600, laughMin: 0.25, mergeGap: 6, setupMax: 20, clipMax: 75 }, + proposedAt: "2026-01-01T00:00:00.000Z", + speakers: [ + { index: 0, role: "host", label: "Host", seconds: 9, turns: 4, how: "auto" }, + { index: 1, role: "subject", label: "Subject", seconds: 12, turns: 3, how: "auto" }, + ], + turns: [ + { start: 0, end: 2.2, speaker: 1 }, + { start: 2.4, end: 3.8, speaker: 0 }, + { start: 4, end: 6.2, speaker: 1 }, + { start: 6.4, end: 9, speaker: 0 }, + { start: 9.2, end: 15, speaker: 1 }, + { start: 15.2, end: 21, speaker: 0 }, + ], + laughs: [ + { start: 2.6, end: 3.2, score: 0.71, speaker: 0 }, + { start: 7.0, end: 7.6, score: 0.44, speaker: 0 }, + ], + moments: [], + proposals: [ + { id: "p001", start: 1, end: 3, score: 0.8, moments: [], used: true, clipId: "r001", why: "host laughs at the line" }, + { id: "p002", start: 4, end: 6, score: 0.7, moments: [], used: true, clipId: "r002", why: "a comment" }, + { id: "p003", start: 6.5, end: 8.5, score: 0.6, moments: [], used: true, clipId: "r003", why: "a short comment" }, + { id: "p004", start: 9, end: 12, score: 0.5, moments: [], used: false, clipId: null, why: "a long comment" }, + { id: "p005", start: 13, end: 15, score: 0.3, moments: [], used: false, clipId: null, why: "a chuckle" }, + ], + }); + mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); + copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", "vid1_0.00-9.00.mp4")); + return { dir }; +} diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -31,6 +31,7 @@ import { makeDraftReviewFixture } from "./draft-review-fixture.mjs"; import { makeReviewPlayerFixture } from "./review-player-fixture.mjs"; import { makeClipDeckFixture } from "./clip-deck-fixture.mjs"; import { makeMontageOpsFixture } from "./montage-ops-fixture.mjs"; +import { makeClipEditorFixture } from "./clip-editor-fixture.mjs"; import { makeBenchShellFixture } from "./bench-shell-fixture.mjs"; import { makeYoutubeFixture } from "./youtube-fixture.mjs"; import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs"; @@ -1807,6 +1808,8 @@ makeReviewPlayerFixture({ reports, channels: CHANNELS, manifest, cachedWindow: p makeClipDeckFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // Release 35 O1: Fetch windows, a refused window and its stand-in (montage-ops.spec.ts). makeMontageOpsFixture({ reports, channels: CHANNELS, manifest }); +// Release 35 C2: the clip editor, an assistant's clips adjusted by hand (clip-editor.spec.ts). +makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 }); // 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). @@ -2143,6 +2146,7 @@ console.log(` deliver-stop-fixture (writable: six confirmed clips to console.log(` takes-fixture (writable: takes/ with 4 takes over 2 groups, 1 skipped)`); console.log(` takes-make-fixture (writable: one clip, its window cached, no takes/ -- the take maker's)`); console.log(` clip-deck-fixture (writable: six montage clips, windows cached, edits.json + voice-match.json -- the clip deck's)`); +console.log(` clip-editor-fixture (writable: three assistant clips, reactions.json + words.json, windows cached -- the clip editor's)`); console.log(` narration-fixture (writable: a narrated card, voiced by the editor stub's tone)`); console.log(` narration-review-fixture (writable: two narrated cards, nothing judged)`); console.log(` draft-review-fixture (writable: drafted on-screen, narration, teaser; an alternative), draft-review-build-fixture`); diff --git a/umtool/lib/hrefs.test.mjs b/umtool/lib/hrefs.test.mjs @@ -28,6 +28,12 @@ test("the clip deck: /projects/<p>/clips, its filter in `show`", () => { assert.equal(H.clipDeckHref("a/b", { show: "unruled" }), "/projects/a/b/clips?show=unruled"); }); +test("the clip editor: the deck's address, `mode=edit` and the clip; note last", () => { + assert.equal(H.clipEditorHref("a/b"), "/projects/a/b/clips"); + assert.equal(H.clipEditorHref("a/b", { clip: "r001" }), "/projects/a/b/clips?clip=r001"); + assert.equal(H.clipEditorHref("a/b", { mode: "edit", clip: "r 2", note: "n" }), "/projects/a/b/clips?mode=edit&clip=r+2&note=n"); +}); + test("withNote re-points an href and keeps note last, and the fragment after it", () => { assert.equal(H.withNote("/articles/x?note=old&tab=source", "new"), "/articles/x?tab=source&note=new"); assert.equal(H.withNote("/projects/p", "n"), "/projects/p?note=n"); diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -288,6 +288,15 @@ export function clipDeckHref(project: string, q: NoteOpt & { show?: ClipDeckShow return withQuery(`/projects/${encodePath(project)}/clips`, q.show ? { show: q.show } : {}, q.note); } +/** + * The clip editor (release 35 C2): the same address as the deck. A cut with + * no montage opens it; `mode: "edit"` opens it on a montage too; `clip` + * selects one clip. + */ +export function clipEditorHref(project: string, q: NoteOpt & { clip?: string; mode?: "edit" } = {}): string { + return withQuery(`/projects/${encodePath(project)}/clips`, { ...(q.mode ? { mode: q.mode } : {}), ...(q.clip ? { clip: q.clip } : {}) }, q.note); +} + /** The narration script, card by card. */ export function narrationHref(project: string, q: NoteOpt = {}): string { return withQuery(`/projects/${encodePath(project)}/narration`, {}, q.note); diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs @@ -0,0 +1,361 @@ +// THE CLIP EDITOR, server side (release 35 C2): a person hops in on the clips +// an assistant made -- or on any report video's clips -- and trims, splits, +// merges, adds, restores, keeps or cuts them, and says which voice is the +// host. +// +// the view every clip of the cut with its edges, quote, `assist` +// (the clip finder's provenance) and keep/cut ruling; +// the clip finder's speakers and the proposals NOT in the +// cut (reactions.json, when there is one) +// the neighbourhood what the strip under the player draws for a span: the +// speaker turns, the laughs, the words (a words file in +// the project) or else the cues +// the operations ONE writer each, all here: the manifest through +// lib/report/manifest.mjs (updateClip / restoreClip / +// splitClip / mergeClips / addClip), the rulings through +// lib/report/montageRulings.mjs, a speaker's role through +// ./clipEditorBridge.mjs (the clip finder's writer) +// +// A ruling is keyed by the clip's moment (`clipMomentKey`: its cutStart), so an +// edit that moves a clip's start would orphan its keep/cut. After every edit +// the rulings FOLLOW their clips: a ruling whose clip's key changed moves to +// the new key; one whose clip is gone (merged away) is removed. +// +// Nothing here calls a model. +import { readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { clipMomentKey } from "umtool-report-to-video/montage-rulings"; +import { channelFor, clipsOf, cuesInWindow, readManifest } from "../projects/report.mjs"; +import { + StaleToken, + StructureRefused, + addClip, + cutOf, + manifestToken, + mergeClips, + restoreClip, + splitClip, + updateClip, +} from "./manifest.mjs"; +import { momentKeysOf, readRulingsState, setMontageRuling } from "./montageRulings.mjs"; +import { readReactions, reproposeAvailable, REPROPOSE_UNAVAILABLE, setSpeakerRole, SPEAKER_ROLES } from "./clipEditorBridge.mjs"; +import { quoteBetween, unusedProposals, wordsOf } from "./clipEditorModel.mjs"; +import { WINDOW_PAD_S } from "yt-dlp-transcript-common/lib/clips/assist.mjs"; + +export { StaleToken, StructureRefused }; + +/** How far the strip reaches either side of a clip. */ +export const NEIGHBOURHOOD = 60; +/** The verdicts the clip editor offers (the montage deck has four). */ +export const EDITOR_VERDICTS = Object.freeze(["keep", "cut"]); +export const WORDS_FILE = "words.json"; + +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); + +/** A project-relative file the project names (a words file): never absolute, never `..`. */ +function projectFile(dir, rel) { + if (typeof rel !== "string" || !rel || path.isAbsolute(rel) || rel.split(/[\\/]/).some((s) => s === ".." || s === "")) return null; + return path.join(/* turbopackIgnore: true */ dir, rel); +} + +const wordsMemo = new Map(); +/** The project's word timings (`reactions.source.words`, else words.json), or null. Memoised on mtime. */ +export async function readWords(dir, reactions = null) { + const rel = typeof reactions?.source?.words === "string" ? reactions.source.words : WORDS_FILE; + const file = projectFile(dir, rel); + if (!file) return null; + const st = await stat(file).catch(() => null); + if (!st?.isFile()) return null; + const key = `${file}|${Math.round(st.mtimeMs)}|${st.size}`; + const hit = wordsMemo.get(file); + if (hit && hit.key === key) return hit.words; + let words = null; + try { + words = wordsOf(JSON.parse(await readFile(file, "utf8"))); + } catch { + words = null; + } + wordsMemo.set(file, { key, words }); + return words; +} + +/** + * @typedef {{ id: string, channel: string | null, video: string, start: number, end: number, + * cutStart: number | null, cutEnd: number | null, quote: string | null, title: string | null, + * assist: Record<string, unknown> | null, key: string | null, ruling: "keep" | "cut" | string | null, montage: boolean }} EditorClip + */ + +/** The page's data: the clips, the token, the clip finder's speakers and unused proposals. */ +export async function clipEditorView(project) { + const manifest = await readManifest(project.dir); + if (!manifest) return null; + const [token, rulings, reactions] = await Promise.all([manifestToken(project.dir), readRulingsState(project.dir), readReactions(project.dir)]); + /** @type {EditorClip[]} */ + const clips = clipsOf(manifest) + .filter((e) => typeof e.video === "string" && fin(e.start) && fin(e.end)) + .map((e) => { + const key = clipMomentKey(e, manifest); + return { + id: e.id, + channel: channelFor(manifest, e), + video: e.video, + start: e.start, + end: e.end, + cutStart: fin(e.cutStart) ? e.cutStart : null, + cutEnd: fin(e.cutEnd) ? e.cutEnd : null, + quote: typeof e.quote === "string" ? e.quote : null, + title: typeof e.title === "string" ? e.title : typeof e.onscreen?.title === "string" ? e.onscreen.title : null, + assist: isObj(e.assist) ? e.assist : null, + key, + ruling: key ? (rulings.doc.rulings[key]?.verdict ?? null) : null, + montage: isObj(e.montage), + }; + }); + const doc = reactions.doc; + return { + clips, + token, + rulingsError: rulings.error, + reactionsError: reactions.error, + reactions: doc + ? { + source: isObj(doc.source) ? doc.source : null, + params: isObj(doc.params) ? doc.params : null, + speakers: Array.isArray(doc.speakers) ? doc.speakers.filter(isObj) : [], + proposals: unusedProposals(doc, clips), + proposalCount: Array.isArray(doc.proposals) ? doc.proposals.length : 0, + proposedAt: typeof doc.proposedAt === "string" ? doc.proposedAt : null, + rolesChangedAt: typeof doc.rolesChangedAt === "string" ? doc.rolesChangedAt : null, + } + : null, + repropose: { available: reproposeAvailable, why: reproposeAvailable ? null : REPROPOSE_UNAVAILABLE }, + }; +} + +const overlapping = (list, from, to) => + (Array.isArray(list) ? list : []).filter((x) => isObj(x) && fin(x.start) && fin(x.end) && x.end >= from && x.start <= to); + +/** + * What the strip draws for [from, to] around one clip: turns, laughs, words + * (or cues when the project has no word timings), and the source's length + * when known. + */ +export async function clipNeighbourhood(project, { clip, from, to }) { + if (!fin(from) || !fin(to) || to <= from) throw new Error("from and to must be seconds, from < to"); + const { doc } = await readReactions(project.dir); + const words = await readWords(project.dir, doc); + const turns = overlapping(doc?.turns, from, to).map((t) => ({ start: t.start, end: t.end, speaker: t.speaker })); + const laughs = overlapping(doc?.laughs, from, to).map((l) => ({ start: l.start, end: l.end, score: fin(l.score) ? l.score : null, speaker: fin(l.speaker) ? l.speaker : null })); + let cues = null; + let duration = fin(doc?.source?.duration) ? doc.source.duration : null; + if (!words?.length || duration === null) { + const c = clip ? await cuesInWindow(project.dir, clip, from, to).catch(() => null) : null; + if (!words?.length) cues = c?.cues?.map((x) => ({ start: x.start, end: x.end, text: x.text })) ?? null; + if (duration === null && fin(c?.duration)) duration = c.duration; + } + return { + from, + to, + turns, + laughs, + words: words?.length ? words.filter((w) => w.end >= from && w.start <= to).map((w) => ({ w: String(w.w ?? w.word ?? w.text ?? ""), start: w.start, end: w.end })) : null, + cues, + duration, + }; +} + +/** The words of a span around one clip (for a quote), from words or cues. */ +async function quoteFor(project, clipId, from, to) { + const n = await clipNeighbourhood(project, { clip: clipId, from: Math.max(0, from - 1), to: to + 1 }).catch(() => null); + if (!n) return ""; + return quoteBetween({ words: n.words, cues: n.cues }, from, to); +} + +/** + * Make the rulings follow their clips after an edit: a moved key moves its + * ruling; a clip gone takes its ruling with it (unless another clip still + * sits on that moment). Returns what it did, as counts. + */ +export async function carryRulings(dir, beforeKeys, afterKeys) { + const state = await readRulingsState(dir); + if (state.error) return { moved: 0, removed: 0, error: state.error }; + const rulings = state.doc.rulings; + const live = new Set(afterKeys.values()); + let moved = 0; + let removed = 0; + for (const [id, k0] of beforeKeys) { + const r = rulings[k0]; + if (!r) continue; + const k1 = afterKeys.get(id); + if (k1 && k1 !== k0) { + if (!rulings[k1]) { + await setMontageRuling(dir, k1, { verdict: r.verdict, reason: r.reason, ...(r.match ? { match: r.match } : {}) }); + moved += 1; + } + if (!live.has(k0)) await setMontageRuling(dir, k0, null); + } else if (!k1 && !live.has(k0)) { + await setMontageRuling(dir, k0, null); + removed += 1; + } + } + return { moved, removed, error: null }; +} + +class OpError extends Error { + constructor(message, status = 400) { + super(message); + this.status = status; + } +} +export { OpError }; + +const num = (v, what) => { + const x = Number(v); + if (v === null || v === undefined || v === "" || !Number.isFinite(x)) throw new OpError(`${what} must be a number of seconds`); + return x; +}; + +/** + * One operation of the clip editor. `body.op` is one of + * trim { clip, cutStart, cutEnd } the clip's rendered span (its cut, or its + * extent when it has no cut); the extent widens + * to hold a cut; an assistant's clip's quote + * follows its words + * restore { clip } the assistant's version back + * split { clip, at } two clips at that second + * merge { clip } with the next clip + * add { video, channel?, cutStart, cutEnd } a selection on the strip + * bring-in { proposal } one of the clip finder's unused proposals + * ruling { clip, verdict: "keep" | "cut" | null } + * role { speaker, role | null } reactions.json, through the clip finder's writer + * with `token` (the manifest's, from the view) on every manifest edit. + * Returns `{ op, result, carried, view }`. + */ +export async function runClipEditorOp(project, body, { now = null } = {}) { + if (!isObj(body)) throw new OpError("a body is { op, … }"); + const dir = project.dir; + const token = typeof body.token === "string" ? body.token : null; + const manifest = await readManifest(dir); + if (!manifest) throw new OpError("no manifest", 404); + const beforeKeys = momentKeysOf(manifest); + const clipId = typeof body.clip === "string" ? body.clip : null; + const entry = clipId ? clipsOf(manifest).find((e) => e.id === clipId) : null; + const needClip = () => { + if (!entry) throw new OpError(`no clip ${clipId ?? "(none named)"}`, 404); + return entry; + }; + let result; + let structural = true; + switch (body.op) { + case "trim": { + const e = needClip(); + const a = num(body.cutStart, "cutStart"); + const b = num(body.cutEnd, "cutEnd"); + if (b - a < 0.5) throw new OpError("a clip must be at least half a second"); + if (a < 0) throw new OpError("a clip cannot start before the recording"); + const hasCut = fin(e.cutStart) && fin(e.cutEnd); + const patch = hasCut ? { cutStart: a, cutEnd: b, start: Math.min(e.start, a), end: Math.max(e.end, b) } : { start: a, end: b }; + if (isObj(e.assist)) { + const q = await quoteFor(project, e.id, a, b); + if (q) patch.quote = q; + } + result = await updateClip(dir, e.id, patch, { token, edit: "trim", now }); + break; + } + case "restore": + result = await restoreClip(dir, needClip().id, { token, now }); + break; + case "split": { + const e = needClip(); + const at = num(body.at, "at"); + const { cutStart, cutEnd } = cutOf(e); + const [first, second] = await Promise.all([quoteFor(project, e.id, cutStart, at), quoteFor(project, e.id, at, cutEnd)]); + result = await splitClip(dir, e.id, at, { token, now, quotes: { ...(first ? { first } : {}), ...(second ? { second } : {}) } }); + break; + } + case "merge": + result = await mergeClips(dir, needClip().id, { token, now }); + break; + case "add": { + const video = typeof body.video === "string" ? body.video : entry?.video; + const channel = typeof body.channel === "string" ? body.channel : entry ? channelFor(manifest, entry) : null; + if (!video) throw new OpError("add needs the video"); + const a = num(body.cutStart, "cutStart"); + const b = num(body.cutEnd, "cutEnd"); + const near = entry ?? clipsOf(manifest).find((e) => e.video === video); + const quote = near ? await quoteFor(project, near.id, a, b) : ""; + result = await addClip(dir, { video, ...(channel && channel !== manifest.provenance?.channelSlug ? { channel } : {}), cutStart: a, cutEnd: b, ...(quote ? { quote } : {}) }, { token, now }); + break; + } + case "bring-in": { + const { doc, error } = await readReactions(dir); + if (error) throw new OpError(error); + const p = (Array.isArray(doc?.proposals) ? doc.proposals : []).find((x) => isObj(x) && x.id === body.proposal); + if (!p || !fin(p.start) || !fin(p.end)) throw new OpError(`no proposal ${String(body.proposal ?? "")}`, 404); + const video = doc?.source?.video; + const channel = doc?.source?.channel; + if (typeof video !== "string") throw new OpError("reactions.json names no source video"); + // A proposal's start/end IS the cut; the window leaves the clip finder's + // WINDOW_PAD_S either side for trimming, inside the recording. + const cut = { cutStart: p.start, cutEnd: p.end }; + const dur = fin(doc?.source?.duration) ? doc.source.duration : Infinity; + const win = { start: Math.max(0, p.start - WINDOW_PAD_S), end: Math.max(p.end, Math.min(dur, p.end + WINDOW_PAD_S)) }; + const near = clipsOf(manifest).find((e) => e.video === video); + const quote = near ? await quoteFor(project, near.id, cut.cutStart, cut.cutEnd) : typeof p.text === "string" ? p.text : ""; + result = await addClip( + dir, + { + video, + ...(typeof channel === "string" && channel !== manifest.provenance?.channelSlug ? { channel } : {}), + ...cut, + start: win.start, + end: win.end, + ...(typeof p.clipId === "string" ? { id: p.clipId } : {}), + ...(quote ? { quote } : {}), + proposal: { id: p.id, ...(fin(p.score) ? { score: p.score } : {}), ...(typeof p.why === "string" ? { why: p.why } : {}), start: win.start, end: win.end }, + }, + { token, now }, + ); + break; + } + case "ruling": { + const e = needClip(); + const key = clipMomentKey(e, manifest); + if (!key) throw new OpError(`${e.id} has no moment to rule (no channel?)`); + const v = body.verdict; + if (v !== null && !EDITOR_VERDICTS.includes(v)) throw new OpError(`verdict must be ${EDITOR_VERDICTS.join(" or ")}, or null to clear it`); + result = await setMontageRuling(dir, key, v === null ? null : { verdict: v, reason: typeof body.reason === "string" ? body.reason : "" }); + structural = false; + break; + } + case "role": { + const index = Number(body.speaker); + if (!Number.isInteger(index) || index < 0) throw new OpError("speaker is a speaker's index"); + if (body.role !== null && !SPEAKER_ROLES.includes(body.role)) throw new OpError(`role must be one of ${SPEAKER_ROLES.join(", ")}, or null`); + const doc = await setSpeakerRole(dir, index, body.role); + result = { speaker: doc.speakers.find((x) => x?.index === index) ?? null }; + structural = false; + break; + } + default: + throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling or role"); + } + let carried = null; + if (structural) { + const after = await readManifest(dir); + carried = await carryRulings(dir, beforeKeys, momentKeysOf(after)); + } + return { op: body.op, result: summarise(result), carried, view: await clipEditorView(project) }; +} + +/** What a route sends back of a writer's result: ids, never the whole doc. */ +function summarise(r) { + if (!isObj(r)) return null; + const out = {}; + for (const k of ["id", "second", "absorbed", "at"]) if (r[k] !== undefined) out[k] = r[k]; + if (isObj(r.entry) && typeof r.entry.id === "string") out.id ??= r.entry.id; + if (isObj(r.speaker)) out.speaker = r.speaker; + if (r.ruling !== undefined) out.ruling = r.ruling; + return out; +} diff --git a/umtool/lib/report/clipEditor.test.mjs b/umtool/lib/report/clipEditor.test.mjs @@ -0,0 +1,343 @@ +// The clip editor (release 35 C2): the manifest operations (updateClip's +// assist edits, restore, split, merge, add), the operations as the route runs +// them (rulings follow their clips; a speaker's role), and the pure rules +// (snap points, quotes, unused proposals, provenance in words). Synthetic. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { MANIFEST_NAME, StaleToken, StructureRefused, addClip, manifestToken, mergeClips, restoreClip, splitClip, updateClip } from "./manifest.mjs"; +import { carryRulings, clipEditorView, clipNeighbourhood, runClipEditorOp } from "./clipEditor.mjs"; +import { readReactions, setSpeakerRole } from "./clipEditorBridge.mjs"; +import { nearestPoint, provenanceWords, quoteBetween, snapCut, snapPoints, unusedProposals, wordsOf } from "./clipEditorModel.mjs"; +import { momentKeysOf, setMontageRuling } from "./montageRulings.mjs"; + +const NOW = "2026-10-18T22:00:00.000Z"; +const assist = (proposal, original) => ({ by: "assistant", proposal, score: 0.8, why: "host laughs", original, edits: [] }); + +const manifest = () => ({ + schemaVersion: 1, + slug: "rx", + provenance: { channelSlug: "chan", siteOrigin: "https://example.test" }, + render: { width: 640, height: 360, fps: 15 }, + timeline: [ + { type: "clip", id: "r001", video: "v1", start: 10, end: 20, cutStart: 11, cutEnd: 19, quote: "q one", assist: assist("p001", { start: 10, end: 20, cutStart: 11, cutEnd: 19 }) }, + { type: "clip", id: "r002", video: "v1", start: 30, end: 40, cutStart: 31, cutEnd: 39, quote: "q two", assist: assist("p002", { start: 30, end: 40, cutStart: 31, cutEnd: 39 }) }, + { type: "card", id: "k1", heading: "between" }, + { type: "clip", id: "r003", video: "v1", start: 50, end: 60, cutStart: 51, cutEnd: 59, quote: "q three" }, + { type: "clip", id: "plain", video: "v2", start: 5, end: 9 }, + ], +}); + +// Words every second from 0 to 70: "w0" … "w69", each 0.8 s long (a 0.2 s gap). +const WORDS = { words: Array.from({ length: 70 }, (_, i) => ({ w: `w${i}`, start: i, end: i + 0.8 })) }; +const REACTIONS = { + version: 1, + source: { channel: "chan", video: "v1", duration: 80, words: "words.json", diarization: { generatedAt: NOW, engine: "sherpa-onnx" } }, + params: { target: 600, laughMin: 0.25, mergeGap: 6, setupMax: 20, clipMax: 75 }, + speakers: [ + { index: 0, role: "host", label: "Host", seconds: 30, turns: 12, how: "auto" }, + { index: 1, role: "subject", label: "Subject", seconds: 50, turns: 3, how: "auto" }, + ], + turns: [ + { start: 0, end: 9, speaker: 1 }, + { start: 9.5, end: 12, speaker: 0 }, + { start: 12.5, end: 30, speaker: 1 }, + { start: 31, end: 33, speaker: 0 }, + ], + laughs: [{ start: 15, end: 16.5, score: 0.7, speaker: 0 }], + moments: [], + proposals: [ + { id: "p001", start: 11, end: 19, score: 0.8, moments: [], used: true, clipId: "r001", why: "host laughs" }, + { id: "p002", start: 31, end: 39, score: 0.7, moments: [], used: true, clipId: "r002", why: "a comment" }, + { id: "p003", start: 62, end: 68, score: 0.5, moments: [], used: false, why: "a short laugh" }, + { id: "p004", start: 70, end: 75, score: 0.6, moments: [], used: false, why: "a long comment" }, + ], +}; + +async function project({ withReactions = true } = {}) { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-clip-editor-")); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest(), null, 2) + "\n"); + if (withReactions) { + await writeFile(path.join(dir, "reactions.json"), JSON.stringify(REACTIONS, null, 2) + "\n"); + await writeFile(path.join(dir, "words.json"), JSON.stringify(WORDS)); + } + return { id: "reports/rx", dir }; +} +const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")); +const clip = (m, id) => m.timeline.find((e) => e.id === id); +const rulingsOf = async (dir) => JSON.parse(await readFile(path.join(dir, "montage-rulings.json"), "utf8")).rulings; + +test("updateClip: the first human edit of an assistant's cut flips assist.by and appends the edit; a no-op trim records nothing", async () => { + const { dir } = await project({ withReactions: false }); + try { + await updateClip(dir, "r001", { cutStart: 11, cutEnd: 19 }, { now: NOW }); + let e = clip(await read(dir), "r001"); + assert.equal(e.assist.by, "assistant"); + assert.deepEqual(e.assist.edits, []); + await updateClip(dir, "r001", { cutStart: 11.5 + 0.004, cutEnd: 18 }, { now: NOW }); + e = clip(await read(dir), "r001"); + assert.equal(e.assist.by, "operator"); + assert.deepEqual(e.assist.edits, [{ at: NOW, by: "operator", what: "trim", from: { cutStart: 11, cutEnd: 19 }, to: { cutStart: 11.5, cutEnd: 18 } }]); + // A clip with no assist is edited as it always was: no assist appears. + await updateClip(dir, "plain", { start: 5.5 }, { now: NOW }); + assert.equal(clip(await read(dir), "plain").assist, undefined); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("restoreClip: the assistant's original comes back, by is the assistant's again, the restore is in the edits", async () => { + const { dir } = await project({ withReactions: false }); + try { + await updateClip(dir, "r001", { cutStart: 12, cutEnd: 15, start: 10, end: 20 }, { now: NOW }); + await restoreClip(dir, "r001", { now: NOW }); + const e = clip(await read(dir), "r001"); + assert.deepEqual([e.start, e.end, e.cutStart, e.cutEnd], [10, 20, 11, 19]); + assert.equal(e.assist.by, "assistant"); + assert.deepEqual(e.assist.edits.map((x) => x.what), ["trim", "restore"]); + await assert.rejects(restoreClip(dir, "r003"), /no assistant's version/); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("splitClip: two clips at the second, the first keeps id + original, the second is the operator's; quotes per half; refused near an edge", async () => { + const { dir } = await project({ withReactions: false }); + try { + const r = await splitClip(dir, "r001", 15, { now: NOW, quotes: { first: "first half", second: "second half" } }); + assert.equal(r.second, "r001-2"); + const m = await read(dir); + assert.deepEqual(m.timeline.map((e) => e.id), ["r001", "r001-2", "r002", "k1", "r003", "plain"]); + const a = clip(m, "r001"); + const b = clip(m, "r001-2"); + assert.deepEqual([a.start, a.end, a.cutStart, a.cutEnd, a.quote], [10, 15, 11, 15, "first half"]); + assert.deepEqual([b.start, b.end, b.cutStart, b.cutEnd, b.quote], [15, 20, 15, 19, "second half"]); + assert.equal(a.assist.by, "operator"); + assert.ok(a.assist.original); + assert.equal(b.assist.original, undefined); + assert.equal(b.assist.proposal, "p001"); + assert.deepEqual(b.assist.edits.at(-1), { at: NOW, by: "operator", what: "split", from: { cutStart: 11, cutEnd: 19 }, to: { cutStart: 15, cutEnd: 19 } }); + await assert.rejects(splitClip(dir, "r001", 14.8), /half a second inside the cut/); + // An undo point was taken first. + assert.ok(r.snapshot); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("mergeClips: with the next clip -- the union, quotes joined, the next removed; a card between, the last clip, another video are refused", async () => { + const { dir } = await project({ withReactions: false }); + try { + const r = await mergeClips(dir, "r001", { now: NOW }); + assert.equal(r.absorbed, "r002"); + const m = await read(dir); + const e = clip(m, "r001"); + assert.deepEqual([e.start, e.end, e.cutStart, e.cutEnd, e.quote], [10, 40, 11, 39, "q one q two"]); + assert.equal(clip(m, "r002"), undefined); + assert.deepEqual(e.assist.edits.at(-1).what, "merge"); + await assert.rejects(mergeClips(dir, "r001"), /a card stands between/); + await assert.rejects(mergeClips(dir, "plain"), /the last clip/); + await assert.rejects(mergeClips(dir, "r003"), /different recordings/); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("addClip: in time order among the recording's clips, the operator's; a proposal brought in keeps its original", async () => { + const { dir } = await project({ withReactions: false }); + try { + const a = await addClip(dir, { video: "v1", cutStart: 22, cutEnd: 25, quote: "a new one" }, { now: NOW }); + let m = await read(dir); + assert.deepEqual(m.timeline.map((e) => e.id), ["r001", "v1-22", "r002", "k1", "r003", "plain"]); + assert.equal(a.id, "v1-22"); + assert.deepEqual(clip(m, "v1-22").assist, { by: "operator", edits: [{ at: NOW, by: "operator", what: "add", from: null, to: { cutStart: 22, cutEnd: 25 } }] }); + await addClip(dir, { video: "v1", cutStart: 62, cutEnd: 68, start: 61, end: 69, proposal: { id: "p003", score: 0.5, why: "a short laugh", start: 61, end: 69 } }, { now: NOW }); + m = await read(dir); + assert.equal(m.timeline.at(-2).id, "v1-62"); + assert.deepEqual(m.timeline.at(-2).assist.original, { start: 61, end: 69, cutStart: 62, cutEnd: 68 }); + assert.equal(m.timeline.at(-2).assist.proposal, "p003"); + await assert.rejects(addClip(dir, { video: "v1", cutStart: 5, cutEnd: 5.2 }), /half a second/); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a stale token is refused by every operation and writes nothing", async () => { + const { dir } = await project({ withReactions: false }); + try { + const before = await readFile(path.join(dir, MANIFEST_NAME), "utf8"); + for (const p of [ + updateClip(dir, "r001", { cutStart: 12, cutEnd: 18 }, { token: "1" }), + splitClip(dir, "r001", 15, { token: "1" }), + mergeClips(dir, "r001", { token: "1" }), + addClip(dir, { video: "v1", cutStart: 1, cutEnd: 2 }, { token: "1" }), + restoreClip(dir, "r001", { token: "1" }), + ]) await assert.rejects(p, StaleToken); + assert.equal(await readFile(path.join(dir, MANIFEST_NAME), "utf8"), before); + assert.ok(StructureRefused); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("runClipEditorOp: trim keeps the ruling with its clip (the key moves), widens the extent, the quote follows the words", async () => { + const p = await project(); + try { + let view = await clipEditorView(p); + await runClipEditorOp(p, { op: "ruling", clip: "r001", verdict: "keep" }); + assert.equal((await rulingsOf(p.dir))["chan/v1@11.00"].verdict, "keep"); + const out = await runClipEditorOp(p, { op: "trim", clip: "r001", cutStart: 9.1, cutEnd: 12.9, token: view.token }, { now: NOW }); + const e = clip(await read(p.dir), "r001"); + assert.deepEqual([e.start, e.end, e.cutStart, e.cutEnd], [9.1, 20, 9.1, 12.9]); + assert.equal(e.quote, "w9 w10 w11 w12"); + const rulings = await rulingsOf(p.dir); + assert.equal(rulings["chan/v1@11.00"], undefined); + assert.equal(rulings["chan/v1@9.10"].verdict, "keep"); + assert.deepEqual(out.carried, { moved: 1, removed: 0, error: null }); + assert.equal(out.view.clips.find((c) => c.id === "r001").ruling, "keep"); + // A plain clip (no cut) is trimmed by its extent, and its quote is left alone. + view = out.view; + await runClipEditorOp(p, { op: "trim", clip: "plain", cutStart: 6, cutEnd: 8, token: view.token }); + const plain = clip(await read(p.dir), "plain"); + assert.deepEqual([plain.start, plain.end, plain.cutStart, plain.quote], [6, 8, undefined, undefined]); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("runClipEditorOp: split quotes each half from the words; merge takes the absorbed clip's ruling away; restore; cut", async () => { + const p = await project(); + try { + await runClipEditorOp(p, { op: "split", clip: "r001", at: 15 }, { now: NOW }); + let m = await read(p.dir); + assert.equal(clip(m, "r001").quote, "w11 w12 w13 w14"); + assert.equal(clip(m, "r001-2").quote, "w15 w16 w17 w18"); + await runClipEditorOp(p, { op: "ruling", clip: "r001-2", verdict: "cut" }); + assert.equal((await rulingsOf(p.dir))["chan/v1@15.00"].verdict, "cut"); + const merged = await runClipEditorOp(p, { op: "merge", clip: "r001" }, { now: NOW }); + assert.deepEqual(merged.carried, { moved: 0, removed: 1, error: null }); + assert.equal((await rulingsOf(p.dir))["chan/v1@15.00"], undefined); + await runClipEditorOp(p, { op: "restore", clip: "r001" }, { now: NOW }); + m = await read(p.dir); + assert.deepEqual([clip(m, "r001").cutStart, clip(m, "r001").cutEnd], [11, 19]); + await assert.rejects(runClipEditorOp(p, { op: "ruling", clip: "r001", verdict: "not-him" }), /keep or cut/); + await assert.rejects(runClipEditorOp(p, { op: "nope" }), /op must be/); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("runClipEditorOp: bring in an unused proposal (it leaves the list); add from a selection; set a speaker's role", async () => { + const p = await project(); + try { + let view = await clipEditorView(p); + assert.deepEqual(view.reactions.proposals.map((x) => x.id), ["p004", "p003"]); + const out = await runClipEditorOp(p, { op: "bring-in", proposal: "p003", token: view.token }, { now: NOW }); + view = out.view; + assert.deepEqual(view.reactions.proposals.map((x) => x.id), ["p004"]); + const brought = view.clips.find((c) => c.assist?.proposal === "p003"); + assert.equal(brought.quote, "w62 w63 w64 w65 w66 w67"); + assert.equal(brought.assist.by, "operator"); + // The proposal is the cut; the window leaves 1.5 s either side. + assert.deepEqual([brought.cutStart, brought.cutEnd, brought.start, brought.end], [62, 68, 60.5, 69.5]); + assert.deepEqual(brought.assist.original, { start: 60.5, end: 69.5, cutStart: 62, cutEnd: 68 }); + await runClipEditorOp(p, { op: "add", clip: "r002", cutStart: 41, cutEnd: 44 }, { now: NOW }); + const m = await read(p.dir); + assert.deepEqual(m.timeline.map((e) => e.id).slice(0, 4), ["r001", "r002", "v1-41", "k1"]); + await runClipEditorOp(p, { op: "role", speaker: 1, role: "host" }); + const { doc } = await readReactions(p.dir); + assert.deepEqual(doc.speakers[1], { index: 1, role: "host", label: "Host", seconds: 50, turns: 3, how: "operator" }); + // The clip finder's writer: one host -- the other speaker who held it is handed back as "other". + assert.equal(doc.speakers[0].role, "other"); + assert.ok(doc.rolesChangedAt); + const after = await clipEditorView(p); + assert.equal(after.reactions.rolesChangedAt, doc.rolesChangedAt); + await assert.rejects(setSpeakerRole(p.dir, 9, "host"), /no speaker 9/); + await assert.rejects(runClipEditorOp(p, { op: "bring-in", proposal: "p999" }), /no proposal p999/); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("clipNeighbourhood: turns, laughs and words in the span; cues and no colours with no reactions.json", async () => { + const p = await project(); + try { + const n = await clipNeighbourhood(p, { clip: "r001", from: 8, to: 14 }); + assert.deepEqual(n.turns.map((t) => t.speaker), [1, 0, 1]); + assert.deepEqual(n.laughs, []); + assert.equal(n.words[0].w, "w8"); + assert.equal(n.duration, 80); + assert.equal(n.cues, null); + const none = await project({ withReactions: false }); + try { + const v = await clipEditorView(none); + assert.equal(v.reactions, null); + const m = await clipNeighbourhood(none, { clip: "r001", from: 8, to: 14 }); + assert.deepEqual([m.turns, m.laughs, m.words], [[], [], null]); + } finally { + await rm(none.dir, { recursive: true, force: true }); + } + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("carryRulings: a moved key moves its ruling, a gone clip takes its ruling, a ruled new key is not overwritten", async () => { + const p = await project({ withReactions: false }); + try { + await setMontageRuling(p.dir, "chan/v1@11.00", { verdict: "keep" }); + await setMontageRuling(p.dir, "chan/v1@31.00", { verdict: "cut" }); + await setMontageRuling(p.dir, "chan/v1@51.00", { verdict: "cut" }); + await setMontageRuling(p.dir, "chan/v1@52.00", { verdict: "keep" }); + const before = momentKeysOf(await read(p.dir)); + const after = new Map(before); + after.set("r001", "chan/v1@12.00"); + after.delete("r002"); + after.set("r003", "chan/v1@52.00"); + const r = await carryRulings(p.dir, before, after); + const rulings = await rulingsOf(p.dir); + assert.deepEqual(r, { moved: 1, removed: 1, error: null }); + assert.equal(rulings["chan/v1@12.00"].verdict, "keep"); + assert.equal(rulings["chan/v1@11.00"], undefined); + assert.equal(rulings["chan/v1@31.00"], undefined); + assert.equal(rulings["chan/v1@52.00"].verdict, "keep"); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("the pure rules: snap points, snapping a cut, a span's words, unused proposals, provenance in words", () => { + const words = wordsOf(WORDS); + const pts = snapPoints({ words: words.slice(0, 4), turns: [{ start: 0, end: 1.5, speaker: 0 }, { start: 2.5, end: 4, speaker: 1 }] }); + assert.deepEqual(pts, [0, 0.9, 1.5, 1.9, 2.5, 2.9, 3.8]); + assert.equal(nearestPoint(1.6, pts), 1.5); + assert.equal(nearestPoint(10, pts), null); + assert.deepEqual(snapCut({ cutStart: 0.95, cutEnd: 3.7 }, pts), { cutStart: 0.9, cutEnd: 3.8 }); + assert.deepEqual(snapCut({ cutStart: 1.5, cutEnd: 1.8 }, [1.6, 1.7]), { cutStart: 1.5, cutEnd: 1.8 }); + assert.deepEqual(snapPoints({ cues: [{ start: 0, end: 3, text: "a" }, { start: 3, end: 6, text: "b" }] }), [0, 3, 6]); + assert.equal(quoteBetween({ words }, 2, 4), "w2 w3"); + assert.equal(quoteBetween({ cues: [{ start: 0, end: 3, text: "one" }, { start: 3, end: 6, text: "two" }] }, 1, 3), "one"); + assert.deepEqual(unusedProposals(REACTIONS, [{ assist: { proposal: "p001" } }, { assist: { proposal: "p002" } }]).map((x) => x.id), ["p004", "p003"]); + assert.equal(unusedProposals(null, []).length, 0); + assert.equal(provenanceWords({ by: "assistant", score: 0.834, why: "host laughs" }), "by the assistant · 0.83 · host laughs"); + assert.equal(provenanceWords({ by: "operator", proposal: "p1", score: 0.5, edits: [{ what: "trim" }] }), "edited by you · the assistant scored it 0.50 · 1 edit"); + assert.equal(provenanceWords({ by: "operator", edits: [{ what: "add" }] }), "added by you · 1 edit"); + assert.equal(provenanceWords(null), null); +}); + +test("manifestToken changes with every operation (the page's next write carries the new one)", async () => { + const p = await project({ withReactions: false }); + try { + const t0 = await manifestToken(p.dir); + await new Promise((r) => setTimeout(r, 15)); + const out = await runClipEditorOp(p, { op: "merge", clip: "r001", token: t0 }); + assert.notEqual(out.view.token, t0); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/clipEditorBridge.mjs b/umtool/lib/report/clipEditorBridge.mjs @@ -0,0 +1,53 @@ +// THE CLIP EDITOR's seam onto the clip finder (release 35 C2 → C1). +// +// `<project>/reactions.json` is the clip finder's (lane C1, `common/lib/clips/`; +// the shape is plans/release-35/clip-finder.md). The clip editor READS it and +// writes exactly one thing into it -- a speaker's role, when the operator says +// "This is the host" on the strip -- through C1's exported `setSpeakerRole`. +// +// `readReactions` here is lenient and says WHY a file is unreadable (the +// clip finder's own reader answers null); the role writer is the clip +// finder's. Every caller in umtool imports from here. +import { readFile } from "node:fs/promises"; +import path from "node:path"; + +export const REACTIONS_FILE = "reactions.json"; +export const SPEAKER_ROLES = Object.freeze(["host", "subject", "other"]); + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); + +/** + * The project's reactions.json: `{ doc, error }`. No file is `{ doc: null, + * error: null }` (a report video the clip finder never ran on); a file that + * does not parse, or is not version 1, is an error and never read as empty. + * @param {string} dir + */ +export async function readReactions(dir) { + let text; + try { + text = await readFile(path.join(/* turbopackIgnore: true */ dir, REACTIONS_FILE), "utf8"); + } catch (err) { + if (/** @type {NodeJS.ErrnoException} */ (err)?.code === "ENOENT") return { doc: null, error: null }; + return { doc: null, error: String(err) }; + } + try { + const doc = JSON.parse(text); + if (!isObj(doc) || doc.version !== 1) return { doc: null, error: `${REACTIONS_FILE} is not version 1` }; + return { doc, error: null }; + } catch (e) { + return { doc: null, error: `${REACTIONS_FILE} does not parse: ${e instanceof Error ? e.message : String(e)}` }; + } +} + +/** + * Set one speaker's role, the operator's -- THE CLIP FINDER'S WRITER + * (common/lib/clips/reactions.mjs): marking a host or a subject takes that + * role off any other speaker that held it; `null` hands the speaker back to + * the analysis; `rolesChangedAt` is stamped, so the page offers Re-propose + * while it is later than `proposedAt`. Returns the document as written. + */ +export { setSpeakerRole } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; + +/** Re-propose is the clip finder's proposal pass: POST /api/report/clips {project, mode: "propose"} (`umtool clips propose`, a job). */ +export const reproposeAvailable = true; +export const REPROPOSE_UNAVAILABLE = null; diff --git a/umtool/lib/report/clipEditorModel.mjs b/umtool/lib/report/clipEditorModel.mjs @@ -0,0 +1,148 @@ +// THE CLIP EDITOR's pure rules (release 35 C2), shared by the page and the +// server: snap points, a span's words, the proposals not in the cut, and a +// clip's provenance in words. No node imports -- a client component holds the +// same rules as the route. + +/** @typedef {{ w?: string, word?: string, text?: string, start: number, end: number }} Word */ +/** @typedef {{ start: number, end: number, text: string }} Cue */ +/** @typedef {{ start: number, end: number, speaker: number }} Turn */ + +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const r2 = (n) => Math.round(n * 100) / 100; + +/** A word's text, whichever key the transcriber used. */ +export const wordText = (w) => String(w?.w ?? w?.word ?? w?.text ?? "").trim(); + +/** A list of words from what a words file may hold: an array, or `{ words: [...] }`. Kept: timed ones, in time order. */ +export function wordsOf(raw) { + const list = Array.isArray(raw) ? raw : Array.isArray(raw?.words) ? raw.words : []; + return list.filter((w) => w && fin(w.start) && fin(w.end) && w.end >= w.start && wordText(w)).sort((a, b) => a.start - b.start); +} + +/** + * Where an edge may snap to: the middle of every gap between two words (a + * word gap), every edge of a silence between turns, and -- with no words -- + * every cue boundary. Sorted, 2 dp, no repeats. + * @param {{ words?: Word[] | null, turns?: Turn[] | null, cues?: Cue[] | null, minGap?: number }} o + */ +export function snapPoints({ words = null, turns = null, cues = null, minGap = 0.05 } = {}) { + const out = new Set(); + const ws = Array.isArray(words) ? words : []; + for (let i = 0; i + 1 < ws.length; i++) { + const a = ws[i].end; + const b = ws[i + 1].start; + if (fin(a) && fin(b) && b - a >= minGap) out.add(r2((a + b) / 2)); + } + if (ws.length) { + out.add(r2(ws[0].start)); + out.add(r2(ws[ws.length - 1].end)); + } + const ts = (Array.isArray(turns) ? turns : []).filter((t) => fin(t.start) && fin(t.end)).sort((a, b) => a.start - b.start); + for (let i = 0; i + 1 < ts.length; i++) { + if (ts[i + 1].start - ts[i].end >= minGap) { + out.add(r2(ts[i].end)); + out.add(r2(ts[i + 1].start)); + } + } + if (!ws.length) { + for (const c of Array.isArray(cues) ? cues : []) { + if (fin(c.start)) out.add(r2(c.start)); + if (fin(c.end)) out.add(r2(c.end)); + } + } + return [...out].sort((a, b) => a - b); +} + +/** The snap point nearest `t`, within `max` seconds, or null. */ +export function nearestPoint(t, points, max = 1.5) { + let best = null; + for (const p of points) { + if (Math.abs(p - t) <= max && (best === null || Math.abs(p - t) < Math.abs(best - t))) best = p; + } + return best; +} + +/** + * Both edges of a cut snapped to their nearest points, keeping it at least + * half a second long; an edge with no point within `max` stays. + * @param {{ cutStart: number, cutEnd: number }} cut + * @param {number[]} points + */ +export function snapCut(cut, points, max = 1.5) { + const a = nearestPoint(cut.cutStart, points, max) ?? cut.cutStart; + const b = nearestPoint(cut.cutEnd, points, max) ?? cut.cutEnd; + if (b - a < 0.5) return { cutStart: cut.cutStart, cutEnd: cut.cutEnd }; + return { cutStart: r2(a), cutEnd: r2(b) }; +} + +/** + * The words spoken in [from, to]: from the word timings when there are any + * (a word counts when its middle is inside), else the cues overlapping it. + * @param {{ words?: Word[] | null, cues?: Cue[] | null }} o + */ +export function quoteBetween({ words = null, cues = null }, from, to) { + if (Array.isArray(words) && words.length) { + return words + .filter((w) => (w.start + w.end) / 2 >= from && (w.start + w.end) / 2 <= to) + .map(wordText) + .join(" ") + .replace(/\s+/g, " ") + .trim(); + } + return (Array.isArray(cues) ? cues : []) + .filter((c) => c.end > from + 0.05 && c.start < to - 0.05) + .map((c) => String(c.text ?? "").trim()) + .join(" ") + .replace(/\s+/g, " ") + .trim(); +} + +/** + * The clip finder's proposals NOT in the cut: no clip's `assist.proposal` + * names them. (reactions.json's own `used` says what the last propose did; + * the manifest says what the cut holds now, after a person brought one in or + * removed one.) Ranked best first. + * @param {{ proposals?: Array<{ id: string, score?: number }> } | null} reactions + * @param {Array<{ assist?: { proposal?: string } }>} clips + */ +export function unusedProposals(reactions, clips) { + const inCut = new Set(clips.map((c) => c?.assist?.proposal).filter((p) => typeof p === "string")); + return (Array.isArray(reactions?.proposals) ? reactions.proposals : []) + .filter((p) => p && typeof p.id === "string" && fin(p.start) && fin(p.end) && !inCut.has(p.id)) + .sort((a, b) => (b.score ?? 0) - (a.score ?? 0)); +} + +/** A speaker's role from reactions.json's speakers, or null. */ +export function roleOf(speakers, index) { + const s = (Array.isArray(speakers) ? speakers : []).find((x) => x && x.index === index); + return s && typeof s.role === "string" ? s.role : null; +} + +/** + * A clip's provenance in words: "by the assistant · 0.83 · host laughs …", + * "edited by you · 3 edits", "added by you" -- or null for a clip the clip + * finder never touched. + * @param {{ by?: string, proposal?: string, score?: number, why?: string, edits?: unknown[] } | null | undefined} assist + */ +export function provenanceWords(assist) { + if (!assist || typeof assist !== "object") return null; + const edits = Array.isArray(assist.edits) ? assist.edits : []; + const n = edits.length; + if (assist.by === "assistant") { + return ["by the assistant", fin(assist.score) ? assist.score.toFixed(2) : null, assist.why || null].filter(Boolean).join(" · "); + } + const added = edits.some((e) => e && /** @type {{ what?: string }} */ (e).what === "add"); + const head = added ? (assist.proposal ? "brought in by you" : "added by you") : "edited by you"; + return [head, assist.proposal && fin(assist.score) ? `the assistant scored it ${assist.score.toFixed(2)}` : null, n ? `${n} edit${n === 1 ? "" : "s"}` : null] + .filter(Boolean) + .join(" · "); +} + +/** m:ss.s, for edges. */ +export function edgeClock(s) { + const v = Math.max(0, Number(s) || 0); + const h = Math.floor(v / 3600); + const m = Math.floor((v % 3600) / 60); + const sec = (v % 60).toFixed(1).padStart(4, "0"); + return h ? `${h}:${String(m).padStart(2, "0")}:${sec}` : `${m}:${sec}`; +} diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts @@ -0,0 +1,66 @@ +// The clip editor's shapes (release 35 C2), as lib/report/clipEditor.mjs +// returns them and components/projects/review/ClipEditor.tsx reads them. + +export type AssistEdit = { at: string; by: string; what: string; from: { cutStart: number; cutEnd: number } | null; to: { cutStart: number; cutEnd: number } }; +export type Assist = { + by: "assistant" | "operator"; + proposal?: string; + score?: number; + why?: string; + original?: { start: number; end: number; cutStart?: number; cutEnd?: number }; + edits?: AssistEdit[]; +}; + +export type EditorClip = { + id: string; + channel: string | null; + video: string; + start: number; + end: number; + cutStart: number | null; + cutEnd: number | null; + quote: string | null; + title: string | null; + assist: Assist | null; + key: string | null; + ruling: string | null; + montage: boolean; +}; + +export type Speaker = { index: number; role?: "host" | "subject" | "other"; label?: string; seconds?: number; turns?: number; how?: "auto" | "operator"; sameAs?: number }; +export type Proposal = { id: string; start: number; end: number; score?: number; why?: string; moments?: string[]; used?: boolean; clipId?: string | null }; + +export type EditorView = { + clips: EditorClip[]; + token: string | null; + rulingsError: string | null; + reactionsError: string | null; + reactions: { + source: { channel?: string; video?: string; duration?: number; words?: string | null } | null; + params: Record<string, number> | null; + speakers: Speaker[]; + proposals: Proposal[]; + proposalCount: number; + proposedAt: string | null; + rolesChangedAt: string | null; + } | null; + repropose: { available: boolean; why: string | null }; +}; + +export type Turn = { start: number; end: number; speaker: number }; +export type Laugh = { start: number; end: number; score: number | null; speaker: number | null }; +export type TimedWord = { w: string; start: number; end: number }; +export type Cue = { start: number; end: number; text: string }; + +export type Neighbourhood = { + from: number; + to: number; + turns: Turn[]; + laughs: Laugh[]; + words: TimedWord[] | null; + cues: Cue[] | null; + duration: number | null; +}; + +/** The take "Render a take" makes again (the clip deck's rule), or null: the Takes page chooses. */ +export type RenderTarget = { take: string; label: string; builtAt: string | null; why: "picked" | "whole cut" } | null; diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -165,7 +165,7 @@ const WIN_EPS = 0.02; * @param {{ token?: string | null }} [opts] * @returns {Promise<{ entry: Record<string, unknown>, before: {start:number,end:number}, token: string | null }>} */ -export async function updateClip(dir, clipId, patch, { token = null } = {}) { +export async function updateClip(dir, clipId, patch, { token = null, edit = "trim", now = null } = {}) { return withManifestLock(async () => { const current = await manifestToken(dir); if (token !== null && current !== token) throw new StaleToken(token, current); @@ -179,8 +179,14 @@ export async function updateClip(dir, clipId, patch, { token = null } = {}) { // real manifest carries `scroll` and `chart` entries -- and the card-only // check would have let a window be written onto one of those. if (entry.type !== "clip") throw new Error(`${clipId} is a ${entry.type ?? "non-clip"} entry, not a clip`); + // Restore (release 35 C2): the assistant's own edges, read inside the lock. + if (patch === RESTORE_PATCH) { + patch = restorePatchOf(entry); + edit = "restore"; + } const before = { start: entry.start, end: entry.end }; + const cutBefore = cutOf(entry); for (const k of WINDOW_FIELDS) { if (patch[k] === undefined) continue; const v = Number(patch[k]); @@ -374,11 +380,229 @@ export async function updateClip(dir, clipId, patch, { token = null } = {}) { // and a row saved from the On-screen table cannot store different shapes. if (patch.onscreen !== undefined) setOnscreen(entry, patch.onscreen); + // ---- an assistant's clip, edited by a person (release 35 C2) ------------- + // + // A clip the clip finder proposed carries `assist`. The first human edit + // of its cut flips `assist.by` to "operator" (a re-propose never touches + // it again) and every edit is appended to `assist.edits`. Restore puts the + // assistant's `original` back, and the clip is the assistant's again. + const at = now ?? new Date().toISOString(); + noteAssistEdit(entry, edit, cutBefore, at); + if (edit === "restore" && isObj(entry.assist) && entry.assist.proposal) entry.assist.by = "assistant"; + const nextToken = await writeManifestAtomic(dir, manifest); return { entry, before, token: nextToken }; }); } +// --------------------------------------------------------------------------- +// The clip editor's operations (release 35 C2): an assistant's clips, adjusted +// by a person -- trim (updateClip above), restore, split, merge, add. The +// manifest clip's `assist` key is the clip finder's (plans/release-35/ +// clip-finder.md): `{ by, proposal?, score?, why?, original?, edits[] }`. +// Split, merge and add are structural (an auto snapshot first, so the Cut +// tab's Undo takes one back; the build's structure checks after). +// --------------------------------------------------------------------------- + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +/** How many edits a clip keeps; the oldest go first. */ +export const ASSIST_EDITS_MAX = 200; +/** What updateClip restores from (a sentinel: the edges are read inside the lock). */ +export const RESTORE_PATCH = Object.freeze({ restore: true }); + +/** The span a clip renders: its cut, else its extent. */ +export const cutOf = (e) => ({ cutStart: e.cutStart ?? e.start, cutEnd: e.cutEnd ?? e.end }); + +function restorePatchOf(entry) { + const o = isObj(entry.assist) ? entry.assist.original : null; + if (!isObj(o)) throw new Error(`${entry.id} has no assistant's version to restore`); + const n = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null); + const cutStart = n(o.cutStart); + const cutEnd = n(o.cutEnd); + const start = n(o.start) ?? cutStart; + const end = n(o.end) ?? cutEnd; + if (start === null || end === null) throw new Error(`${entry.id}'s assistant's version has no edges`); + return { start, end, cutStart, cutEnd }; +} + +/** + * Append one operator edit to a clip's `assist` and flip `by` -- when the clip + * has `assist` and its cut moved (a trim that leaves the cut where it was is + * no edit). Mutates; returns whether it recorded one. + */ +export function noteAssistEdit(entry, what, from, at = new Date().toISOString()) { + if (!isObj(entry.assist)) return false; + const to = cutOf(entry); + if ((what === "trim" || what === "restore") && from && from.cutStart === to.cutStart && from.cutEnd === to.cutEnd) return false; + entry.assist.by = "operator"; + const edits = Array.isArray(entry.assist.edits) ? entry.assist.edits : []; + edits.push({ at, by: "operator", what, from: from ?? null, to }); + entry.assist.edits = edits.slice(-ASSIST_EDITS_MAX); + return true; +} + +/** Restore the assistant's version of a clip (`assist.original`). */ +export async function restoreClip(dir, clipId, { token = null, now = null } = {}) { + return updateClip(dir, clipId, RESTORE_PATCH, { token, now }); +} + +function clipAt(timeline, id) { + const i = entryIndex(timeline, id); + const e = timeline[i]; + if (e?.type !== "clip") throw new Error(`${id} is a ${e?.type ?? "non-clip"} entry, not a clip`); + return { i, e }; +} + +const textOr = (v, fallback) => (v === undefined ? fallback : String(v ?? "").trim() || null); + +/** + * Split a clip in two at source second `at` (inside its cut, half a second + * from either edge). The first half keeps the id, the ruling's moment and the + * assistant's `original`; the second is a fresh id after it, the operator's. + * `quotes` ({ first, second }) replace each half's quote (the words in it). + * + * @param {string} dir + * @param {string} clipId + * @param {number} at + * @param {{ token?: string | null, quotes?: { first?: string, second?: string }, now?: string | null }} [opts] + */ +export async function splitClip(dir, clipId, at, { token = null, quotes = {}, now = null } = {}) { + return structural(dir, "split", token, (m) => { + const { i, e } = clipAt(m.timeline, clipId); + const t = round2(Number(at)); + const { cutStart, cutEnd } = cutOf(e); + if (!Number.isFinite(t) || t - cutStart < 0.5 || cutEnd - t < 0.5) { + throw new Error(`split at a second at least half a second inside the cut (${cutStart}–${cutEnd})`); + } + const stamp = now ?? new Date().toISOString(); + const from = cutOf(e); + const hasCut = e.cutStart != null && e.cutEnd != null; + const b = JSON.parse(JSON.stringify(e)); + // The first half: up to the split. + e.end = t; + if (hasCut) e.cutEnd = t; + if (e.muteFrom != null && e.muteFrom >= t) delete e.muteFrom; + const qa = textOr(quotes.first, e.quote ?? null); + if (qa) e.quote = qa; + else delete e.quote; + // The second: from the split, a fresh id. + b.id = freshEntryId(m.timeline, e.id); + b.start = t; + if (hasCut) b.cutStart = t; + if (typeof b.cite === "number") b.cite = t; + if (b.muteFrom != null && b.muteFrom < t) delete b.muteFrom; + delete b.claim; + const qb = textOr(quotes.second, b.quote ?? null); + if (qb) b.quote = qb; + else delete b.quote; + if (isObj(e.assist)) { + const prior = Array.isArray(e.assist.edits) ? e.assist.edits : []; + b.assist = { by: "operator", ...pick(e.assist, ["proposal", "score", "why"]), edits: prior.slice() }; + noteAssistEdit(e, "split", from, stamp); + noteAssistEdit(b, "split", from, stamp); + } + m.timeline.splice(i + 1, 0, b); + return { id: e.id, second: b.id, entries: [e, b] }; + }); +} + +const pick = (o, keys) => Object.fromEntries(keys.filter((k) => o[k] !== undefined).map((k) => [k, o[k]])); + +/** + * Merge a clip with the NEXT clip in the timeline (same source; nothing but + * clips between them is refused -- a card between two clips is a decision). + * The first keeps its id; the merged span runs from the earlier edge to the + * later; the quotes join (or `quote` replaces them). + * + * @param {string} dir + * @param {string} clipId + * @param {{ token?: string | null, quote?: string, now?: string | null }} [opts] + */ +export async function mergeClips(dir, clipId, { token = null, quote, now = null } = {}) { + return structural(dir, "merge", token, (m) => { + const { i, e } = clipAt(m.timeline, clipId); + const j = m.timeline.findIndex((x, k) => k > i && x?.type === "clip"); + if (j < 0) throw new Error(`${clipId} is the last clip: nothing to merge it with`); + if (j !== i + 1) throw new Error(`a ${m.timeline[i + 1]?.type ?? "entry"} stands between ${clipId} and ${m.timeline[j].id}`); + const b = m.timeline[j]; + const chan = (x) => x.channel ?? m.provenance?.channelSlug ?? null; + if (chan(e) !== chan(b) || e.video !== b.video) throw new Error(`${clipId} and ${b.id} are cut from different recordings`); + const stamp = now ?? new Date().toISOString(); + const from = cutOf(e); + const cb = cutOf(b); + const hasCut = (e.cutStart != null && e.cutEnd != null) || (b.cutStart != null && b.cutEnd != null); + e.start = round2(Math.min(e.start, b.start)); + e.end = round2(Math.max(e.end, b.end)); + if (hasCut) { + e.cutStart = round2(Math.min(from.cutStart, cb.cutStart)); + e.cutEnd = round2(Math.max(from.cutEnd, cb.cutEnd)); + } + if (e.muteFrom != null) delete e.muteFrom; + if (b.muteFrom != null) e.muteFrom = b.muteFrom; + const q = quote !== undefined ? textOr(quote, null) : [e.quote, b.quote].filter((x) => typeof x === "string" && x.trim()).join(" ") || null; + if (q) e.quote = q; + else delete e.quote; + if (!isObj(e.assist) && isObj(b.assist)) e.assist = { by: "operator", ...pick(b.assist, ["proposal", "score", "why"]), edits: [] }; + noteAssistEdit(e, "merge", from, stamp); + m.timeline.splice(j, 1); + return { id: e.id, absorbed: b.id, entry: e }; + }); +} + +/** + * Add a clip the operator chose (a selection on the strip, or one of the + * clip finder's unused proposals brought in), in time order among the clips + * of the same recording. `proposal` ({ id, score?, why?, start?, end? }) marks + * it the assistant's proposal, its `original` the proposal's edges; either + * way a person put it in, so `assist.by` is "operator". + * + * @param {string} dir + * @param {{ channel?: string, video: string, cutStart: number, cutEnd: number, start?: number, end?: number, quote?: string, title?: string, id?: string, proposal?: { id: string, score?: number, why?: string, start?: number, end?: number } }} spec + * @param {{ token?: string | null, now?: string | null }} [opts] + */ +export async function addClip(dir, spec, { token = null, now = null } = {}) { + return structural(dir, "add", token, (m) => { + if (!isObj(spec)) throw new Error("a clip to add is { video, cutStart, cutEnd }"); + if (typeof spec.video !== "string" || !/^[\w.-]+$/.test(spec.video)) throw new Error("a clip needs its video id"); + const num = (k, v) => { + const x = Number(v); + if (!Number.isFinite(x) || x < 0) throw new Error(`${k} must be a number ≥ 0`); + return round2(x); + }; + const cutStart = num("cutStart", spec.cutStart); + const cutEnd = num("cutEnd", spec.cutEnd); + if (cutEnd - cutStart < 0.5) throw new Error(`a clip must be at least half a second (${cutStart}–${cutEnd})`); + const start = Math.min(spec.start === undefined ? cutStart : num("start", spec.start), cutStart); + const end = Math.max(spec.end === undefined ? cutEnd : num("end", spec.end), cutEnd); + const channel = typeof spec.channel === "string" && spec.channel ? spec.channel : null; + const p = isObj(spec.proposal) ? spec.proposal : null; + const base = typeof spec.id === "string" && ENTRY_ID_RE.test(spec.id) ? spec.id : `${spec.video}-${Math.floor(cutStart)}`; + const entry = { type: "clip", id: freshEntryId(m.timeline, base), ...(channel ? { channel } : {}), video: spec.video, start, end, cutStart, cutEnd }; + const quote = typeof spec.quote === "string" ? spec.quote.trim() : ""; + if (quote) entry.quote = quote.slice(0, 2000); + const title = typeof spec.title === "string" ? spec.title.trim() : ""; + if (title) entry.title = title.slice(0, 300); + const stamp = now ?? new Date().toISOString(); + entry.assist = { + by: "operator", + ...(p ? pick({ proposal: typeof p.id === "string" ? p.id : undefined, score: typeof p.score === "number" ? p.score : undefined, why: typeof p.why === "string" ? p.why : undefined }, ["proposal", "score", "why"]) : {}), + ...(p ? { original: { start: num("start", p.start ?? cutStart), end: num("end", p.end ?? cutEnd), cutStart, cutEnd } } : {}), + edits: [{ at: stamp, by: "operator", what: "add", from: null, to: { cutStart, cutEnd } }], + }; + // In time order among the same recording's clips; else at the end. + const chan = (x) => x.channel ?? m.provenance?.channelSlug ?? null; + const mine = chan(entry); + const same = m.timeline.map((x, k) => ({ x, k })).filter(({ x }) => x?.type === "clip" && x.video === entry.video && chan(x) === mine); + let at = m.timeline.length; + if (same.length) { + const before = same.filter(({ x }) => cutOf(x).cutStart <= cutStart); + at = before.length ? before[before.length - 1].k + 1 : same[0].k; + } + m.timeline.splice(at, 0, entry); + return { id: entry.id, at, entry }; + }); +} + // --------------------------------------------------------------------------- // Writing an ADJUDICATION back into a ledger entry.