commit 9887d8c4244f9bd7f5bafea55d5f9eb28dc2c440
parent 58d4f6c0b7233c611d8b7974577f56bd64d15a48
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 19 Oct 2026 15:15:23 -0400
Merge r36/find-clips: run while paused, fetch-chat, the find-clips job + ops action + the video page's Find clips panel
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
# Conflicts:
# plans/FACTS.md
Diffstat:
43 files changed, 2950 insertions(+), 21 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -141,12 +141,12 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `persist-videos` | persist-videos saves specific videos, across channels, to the saved-video store: {"items": \[{"slug", "id"}, ...\]}. "format": "original" \| "video\_720" (default: each channel's own). "replace": "above-height" also re-fetches a saved one whose height is unknown or above that quality (default "never"). "gapMs" pauses between downloads (default the batch gap), "minFreeMemMb" waits for that much free memory before each. "dryRun": true answers with the buckets (saved, wrongHeight, toFetch, noUrl, unknown) and starts nothing. One job per channel, on its download queue; a low disk or a rate limit stops it, and running the same body again resumes — saved videos are skipped. | `pnpm ops persist-videos --file list.json --wait` |
| `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?, "force"?}, ...\], "requestedBy", "manifest"?} fetches a list. A window of a recording whose availability says deleted or private is refused (unresolved) unless the item names a "webpageUrl" (a copy: find-copy) or "force": true (a stale reading; or check its availability again on the channel page's Diagnostics). "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. "storedUrl": "fallback" \| "only" (default "never") cuts a window from the media URL its record's metadata.info.json stores — Odysee's CDN file (\*.odycdn.com), the only platform allowed — when the page lookup is rate-limited ("fallback": after a 429) or without asking the page at all ("only"). A held or cooling platform still runs its windows that have one; the rest are refused or left for a later run. Same queue, same gaps; the window's provenance says source "stored-media-url". | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` |
| `cut-release` | cut-release turns a changelog's \[Unreleased\] into "## \[<version>\] - <date>": {"workspace": "editor" \| "export" \| "all", "version": "X.Y.Z" \| "next" \| "next-minor", "commit": boolean (default false), "date": "YYYY-MM-DD" (default today)}. "all" cuts both with ONE version and commits each ("Release <workspace> <version>") — or neither: every check runs before either file is written. Only an editor built from release 10 or later has the route (an older one answers 404); with no editor running, `archilyzer release cut` does the same locally. | `pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'` |
-| `transcribe` | transcribe runs ONE local file through a local transcription worker, as a job: {"path": "/abs/file"} (audio or video), "start"/"end" (seconds) for a window, "workerId" (a settings worker id; default: the one auto-transcribe would get), "out" (an absolute path for the result JSON, never inside the corpus). The result is {path, window, worker: {id, appId, model, device}, cues: \[{start, end, text}\], text, ...}, cue times on the file's own clock. "words": true adds words: \[{w, start, end, conf?}\] on the same clock -- from parakeet, which keeps its word timestamps; \[\] from an engine that does not. With --wait it is printed on stdout (the response and the log go to stderr), so `pnpm ops transcribe ... --wait \| jq -r .text` works. | `pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait`<br>`pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait` |
+| `transcribe` | transcribe runs ONE local file through a local transcription worker, as a job: {"path": "/abs/file"} (audio or video), "start"/"end" (seconds) for a window, "workerId" (a settings worker id; default: the one auto-transcribe would get), "out" (an absolute path for the result JSON, never inside the corpus). The result is {path, window, worker: {id, appId, model, device}, cues: \[{start, end, text}\], text, ...}, cue times on the file's own clock. "words": true adds words: \[{w, start, end, conf?}\] on the same clock -- from parakeet, which keeps its word timestamps; \[\] from an engine that does not. "whilePaused": true runs it during a pause-all on a worker the pause alone switched off (never one drained, degraded or disabled by hand); the pause stays on. With --wait it is printed on stdout (the response and the log go to stderr), so `pnpm ops transcribe ... --wait \| jq -r .text` works. | `pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait`<br>`pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait` |
| `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| orpheus \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...; orpheus: leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). The expressive tags <laugh> <chuckle> <sigh> <cough> <sniffle> <groan> <yawn> <gasp> are performed by orpheus and stripped for the others; any other <...> is refused. Numbers, years, money and times are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro and orpheus need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU (a local llama-server the editor starts and stops) and waits while a transcription holds it. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait` |
| `settings` | settings patches settings.json through the editor's one writer: {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` |
| `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | |
| `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` |
-| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. A job; --wait follows it. "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. | |
+| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. A job; --wait follows it. "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. "whilePaused": true runs this one transcription during a pause-all on a worker the pause alone switched off; the pause stays on (the video page's "Transcribe now (workers paused)"). | |
| `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. | |
| `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true}; "keep": false removes it. (keep-videos is the bulk form.) | |
| `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait` |
@@ -165,6 +165,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `mirror-scan` | mirror-scan pairs a mirror channel with the creator it copies: {"slug", "dryRun"?} -> {jobId}. The channel's config names the creator's channels (mirror.of; channel-config's "mirrorOf"); refused without them. Each of the mirror's videos, dated by its recorded date (else its upload date), is matched with the creator's videos uploaded one day before to two after, by title words and duration (the index's records; no media, no network); per video the matches and a status: only-copy (no creator platform has it public), creator-deleted (removed on one platform, public on another), never-uploaded (missing on one platform, public on the rest) or creator-public. The other way: the creator's removed (deleted or private) uploads dated inside the mirror's window, and which the mirror holds. Written to transcripts/mirrors/<slug>.json (private: never published); the channel page's Mirror stage shows it. dryRun writes nothing. The log ends with @@mirror-scan {slug, dryRun, file?, of, missing?, window, videos, matched, byStatus, byPlatform, creatorRemoved: {inWindow, held, byChannel}}. | `pnpm ops mirror-scan --json '{"slug":"demo-vod-archive","dryRun":true}' --wait`<br>`pnpm ops mirror-scan --json '{"slug":"demo-vod-archive"}' --wait` |
| `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias" \| "add-spelling", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. add-spelling {"id", "spelling", "means"} adds a spelling by hand (no model): "means" is one of the names the terms watch; it is counted in scope and its proving line found by code, and kept (source hand) only when it occurs; a removed spelling added by hand is no longer blocked. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'` |
| `audio-audit` | audio-audit decodes every audio file a channel holds, with error tolerance, and writes the verdict beside it in audio-integrity.json: {"slug" \| "platform" (every channel on it, e.g. "odysee"), "scope"? ("untranscribed", the default: videos with no transcript yet; "all": every video holding audio), "max"? (files decoded across the run), "force"? (decode again a file whose record is still its own)} -> {jobIds, channels, refused}. One audio-audit job per channel on the audio-audit queue: one file at a time machine-wide, at idle I/O priority and nice 19. The verdict is clean, damaged (a gap, or under 98% of the container's duration decodes) or undecodable, with the decoded seconds, the gaps, the file's size and mtime and ffmpeg's version. The same body again resumes (a file whose record matches is skipped). A channel whose media is unreachable is refused; a drive that stops answering mid-run ends that channel's job with the sentence (failed), as do two decodes in a row past their deadline (a minute plus a tenth of the audio's length). Corrupt full sources are left to their retry. Damaged untranscribed files (and their salvage transcripts) are the report's corruptHeldAudio bucket, held out of the transcription lane: retry-bucket {"bucket": "corruptHeldAudio"} refetches them; a transcription of one salvages automatically. Each log ends with @@audio-audit {slug, scope, held, fresh, planned, checked, clean, damaged, undecodable, unmeasured, timedOut, corruptFullSource, stopped?}. | `pnpm ops audio-audit --json '{"platform":"odysee","scope":"untranscribed"}' --wait`<br>`pnpm ops audio-audit --json '{"slug":"demo-odysee","scope":"all","max":50}'` |
+| `fetch-chat` | fetch-chat fetches ONE video's live chat replay and nothing else: {"slug", "id"} — the chat-only yt-dlp pass (the channel's cookies, the platform's pace) on the platform's download queue, then live\_chat.cues.json. YouTube only: another platform answers "no chat fetcher for <platform>" (info, no job), as do a chat already here and fresh and a video never live. A pass that finds no replay ends done and says so. | `pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait` |
+| `find-clips` | find-clips runs the clip finder's chain for ONE video as one job: {"slug", "id", "target"? (the cut's seconds), "segment"? (one umtool found, "s2"), "project"? (the umtool project a run makes), "whilePaused"?, "dryRun"?}. Persist the source video, the corpus transcript, word timings (data/<id>/words.json), the chat replay (YouTube), diarization — each step skipped when its output exists, named in the log — then umtool's clip finder (POST UMTOOL\_URL/api/report/clips {mode: "new"}), followed to the end. "whilePaused": true runs this one video past the holds: the two transcriptions during a pause-all on a worker the pause alone switched off, and its diarization in the job when the backfill lane is held. "dryRun": true answers each step's plan and starts nothing. With --wait the result — {project, url, created, segments: \[{id, from, to, why}\], steps} — is printed on stdout. | `pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait` |
### Usage, flags and environment
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -90,7 +90,7 @@ Tokens, credentials and knobs a running process reads. Most configuration is not
| `UMTOOL_MEDIA_DIR` | unset (no media root: a project link's target is kept) | umtool's media root, where a tiered project's `out/` (and its deliverables) are linked to. Read by `archilyzer reports delete` and the editor's `delete-article` / `delete-iteration` too: an iteration project's link that is exactly its mirror there is removed with its target. Its other uses are documented in [umtool/docs](umtool/docs/README.md). | common/lib/report/delete.ts, umtool (lib/paths.mjs) |
| `REPORTS_DIR` | `~/reports` (or the parent of `SONG_REPORTS_DIR`) | umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete. | common/lib/report/delete.ts, umtool (lib/paths.mjs) |
| `SONG_REPORTS_DIR` | unset | umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete reads (as umtool does). | common/lib/report/delete.ts, umtool (song/paths.mjs) |
-| `UMTOOL_URL` | unset (no link; the MCP's `notes` off) | umtool's front door; when set, the video page links to it, and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). | editor/app/channels/[slug]/videos/[id]/page.tsx, mcp/src/archivalTools.ts |
+| `UMTOOL_URL` | unset (no link; the MCP's `notes` off) | umtool's front door; when set, the video page links to it, its Find clips hands the recording to umtool's clip finder (the `find-clips` job posts to `/api/report/clips` with WORKER_TOKEN), and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). Unset: Find clips is disabled. | editor/app/channels/[slug]/videos/[id]/page.tsx, common/lib/umtoolUrl.ts, mcp/src/archivalTools.ts |
| `TRANSCRIPT_SITE_URL` | — | MCP server: one published archive to read over HTTP. | mcp/src/sources.ts |
| `TRANSCRIPT_HUB_URL` | — | MCP server: a hub, federating every archive it lists. | mcp/src/sources.ts |
| `TRANSCRIPT_LOCAL_DIR` | — | MCP server: a composed public dir on disk. | mcp/src/sources.ts |
@@ -233,6 +233,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one
| `E2E_BACKOFF_BASE_MS` | `60000` (the real base) | The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse. | common/jobs/platformBackoff.ts |
| `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts |
| `E2E_ODYSEE_PAGE_FIXTURE` | unset (a headless browser) | A JSON file of recorded Odysee page reads keyed by page URL (`"*"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`). | common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts |
+| `E2E_UMTOOL_ORIGIN_FILE` | unset (UMTOOL_URL) | A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored. | common/lib/umtoolUrl.ts |
| `E2E_BLUESKY_ORIGIN_FILE` | unset (the real Bluesky) | A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored. | common/social/blueskyEndpoints.ts |
| `E2E_AUDIO_CHECK_DEBUG_PAUSE_MS` | off | A debugging pause inside the audio check. | common/ytdlp/audioCheckedDownload.ts |
| `E2E_FAKE_YTDLP_AUDIO_CHECK_MODE` | — | Fake yt-dlp: which audio-check scenario to act out. | editor/e2e/fixtures/bin/fake-ytdlp.mjs |
diff --git a/OPERATING.md b/OPERATING.md
@@ -113,6 +113,28 @@ pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150
- `transcribe` runs one local file (or a window of it) through the corpus's own engine and model; the result JSON
(cues, text, and with `"words": true` the word timings parakeet keeps) is printed on stdout with `--wait`.
`"out"` writes it to a file outside the corpus.
+- With the workers paused, `"whilePaused": true` on `transcribe` or `transcribe-one` runs that one job on a worker
+ the pause alone switched off (never one drained, degraded or disabled by hand); the pause stays on. The video
+ page's Transcribe row says **Transcribe now (workers paused)**.
+
+## Find clips in a recording
+
+```sh
+pnpm ops find-clips --json '{"slug":"example","id":"<videoId>","dryRun":true}'
+pnpm ops find-clips --json '{"slug":"example","id":"<videoId>","target":600}' --wait
+pnpm ops find-clips --json '{"slug":"example","id":"<videoId>","segment":"s2"}' --wait
+pnpm ops fetch-chat --json '{"slug":"example","id":"<videoId>"}' --wait
+```
+
+- `find-clips` (the video page's **Find clips**) runs the clip finder's chain as one job: persist the source video,
+ the corpus transcript, word timings (`data/<id>/words.json`), the chat replay (YouTube), diarization — each
+ skipped when its output exists, each named in the log — then umtool's clip finder, which finds the narrated-video
+ segments and proposes the clips. The result names the umtool project and the segments; `"segment"` (the page's
+ **Find clips in this part**) finds clips in one of them. Needs `UMTOOL_URL` and `WORKER_TOKEN` on the editor.
+- A paused pool, diarization switched off or a held backfill lane fails the step that needs it, saying so;
+ `"whilePaused": true` (the page's **Run while paused**) runs this one video's steps past the holds.
+- `fetch-chat` fetches one video's live chat replay alone (paced, YouTube only) into `live_chat.cues.json`; the
+ video page's Media tools → **Fetch live chat**.
## Tag
diff --git a/common/controller/fetchLiveChat.test.ts b/common/controller/fetchLiveChat.test.ts
@@ -0,0 +1,224 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, utimes, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { ChannelConfig } from "../lib/channelConfig";
+import type { AttemptOutcome } from "../ytdlp/runOneYtdlp";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fetchLiveChat.test.ts
+//
+// One video's chat replay (release 36, lane A). The yt-dlp runner is a stub
+// that records its argv and writes the JSON-lines replay where the
+// `subtitle:` template says — no yt-dlp, no network. Every case is a temp
+// corpus; the job cases run through the real registry over it.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "fetch-chat-"));
+const CORPUS = path.join(ROOT, "transcripts");
+process.env.TRANSCRIPTS_DIR = CORPUS;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await mkdir(CORPUS, { recursive: true });
+await writeFile(process.env.SETTINGS_FILE, "{}");
+
+const { getPaths } = await import("../lib/paths");
+const {
+ CHAT_PLATFORMS,
+ fetchLiveChat,
+ liveChatPlan,
+ noChatFetcherSentence,
+ runFetchChatJob,
+} = await import("./fetchLiveChat");
+const { liveChatOnlyArgs } = await import("../ytdlp/downloadOneManaged");
+
+const paths = getPaths();
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const SLUG = "synth-stream";
+const CONFIG = { handling: "transcribe", url: "https://www.youtube.com/@synth/streams", name: "Synth" } as ChannelConfig;
+const NO_COOKIES = { cookies: undefined, mode: "when-required" } as const;
+
+function chatLine(sec: number, author: string, text: string): string {
+ return JSON.stringify({
+ replayChatItemAction: {
+ actions: [
+ {
+ addChatItemAction: {
+ item: {
+ liveChatTextMessageRenderer: { message: { runs: [{ text }] }, authorName: { simpleText: author } },
+ },
+ },
+ },
+ ],
+ videoOffsetTimeMsec: String(sec * 1000),
+ },
+ });
+}
+const REPLAY = [chatLine(12, "viewer1", "lol"), chatLine(14, "viewer2", "LMAO"), chatLine(30, "viewer3", "W")].join("\n") + "\n";
+
+async function video(id: string, meta: Record<string, unknown>): Promise<string> {
+ const dir = path.join(CORPUS, "channels", SLUG, "data", id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG));
+ await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id, title: "Synth stream", ...meta }));
+ return dir;
+}
+
+// The stub: records the argv, writes the replay under the subtitle template.
+function stubRunner(o: { writes?: string | null; exitCode?: number; stderr?: string } = {}) {
+ const calls: { cwd: string; args: string[] }[] = [];
+ const run = async (cwd: string, args: string[]): Promise<AttemptOutcome> => {
+ calls.push({ cwd, args });
+ const i = args.findIndex((a) => a.startsWith("subtitle:"));
+ if (o.writes !== null && (o.exitCode ?? 0) === 0) {
+ const base = args[i + 0].slice("subtitle:".length);
+ await writeFile(path.join(cwd, `${base}.live_chat.json`), o.writes ?? REPLAY);
+ }
+ return { exitCode: o.exitCode ?? 0, stderrTail: o.stderr ?? "", archiveLine: null, formatLine: null };
+ };
+ return { run, calls };
+}
+
+const log = () => {
+ const lines: string[] = [];
+ return { lines, onLog: (s: string) => lines.push(s) };
+};
+
+test("the chat pass is the managed download's chat-only command line, paced", () => {
+ const url = "https://www.youtube.com/watch?v=abc";
+ const args = liveChatOnlyArgs(CONFIG, undefined, url, 7);
+ assert.deepEqual(args.slice(0, 2), ["--ignore-config", "--restrict-filenames"]);
+ assert.ok(args.includes("--skip-download"));
+ assert.deepEqual(args.slice(args.indexOf("--sub-langs"), args.indexOf("--sub-langs") + 2), ["--sub-langs", "live_chat"]);
+ assert.ok(args.includes("--no-write-info-json"), "the metadata on disk is never rewritten");
+ assert.equal(args[args.indexOf("--sleep-requests") + 1], "7", "the platform's pace");
+ assert.deepEqual(args.slice(-2), ["--", url]);
+ assert.ok(CHAT_PLATFORMS.has("youtube"));
+});
+
+test("plan: YouTube fetches; another platform has no fetcher; a never-live video has no replay", async () => {
+ await video("yt1", { webpage_url: "https://www.youtube.com/watch?v=yt1", was_live: true });
+ assert.deepEqual(await liveChatPlan(paths, SLUG, "yt1", CONFIG), {
+ kind: "fetch",
+ url: "https://www.youtube.com/watch?v=yt1",
+ platform: "youtube",
+ });
+ await video("tw1", { webpage_url: "https://www.twitch.tv/videos/123" });
+ const tw = await liveChatPlan(paths, SLUG, "tw1", CONFIG);
+ assert.deepEqual(tw, { kind: "no-fetcher", platform: "twitch" });
+ assert.equal(noChatFetcherSentence("twitch"), "no chat fetcher for twitch: only YouTube's chat replay is fetched");
+ await video("nl1", { webpage_url: "https://www.youtube.com/watch?v=nl1", live_status: "not_live" });
+ assert.equal((await liveChatPlan(paths, SLUG, "nl1", CONFIG)).kind, "not-live");
+ assert.equal((await liveChatPlan(paths, SLUG, "nope", CONFIG)).kind, "refused");
+ assert.equal((await liveChatPlan(paths, SLUG, "../x", CONFIG)).kind, "refused");
+});
+
+test("a fetch writes the replay and its cues; a second plan says fresh", async () => {
+ const dir = await video("yt2", { webpage_url: "https://www.youtube.com/watch?v=yt2", was_live: true });
+ const { run, calls } = stubRunner();
+ const l = log();
+ const r = await fetchLiveChat({
+ paths,
+ slug: SLUG,
+ videoId: "yt2",
+ videoUrl: "https://www.youtube.com/watch?v=yt2",
+ channelConfig: CONFIG,
+ cookiePolicy: NO_COOKIES,
+ onLog: l.onLog,
+ signal: new AbortController().signal,
+ run,
+ paceSeconds: 3,
+ });
+ assert.equal(r.status, "fetched");
+ assert.equal(r.status === "fetched" && r.messages, 3);
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].cwd, path.join(CORPUS, "channels", SLUG));
+ const cues = JSON.parse(await readFile(path.join(dir, "live_chat.cues.json"), "utf8"));
+ assert.equal(cues.source, "live_chat");
+ assert.equal(cues.cues.length, 3);
+ assert.equal(cues.cues[0].start, 12);
+ assert.match(l.lines.join(""), /3 message\(s\) in live_chat\.cues\.json/);
+ assert.equal((await liveChatPlan(paths, SLUG, "yt2", CONFIG)).kind, "fresh");
+});
+
+test("a pass that writes nothing is an answer, not a failure", async () => {
+ const dir = await video("yt3", { webpage_url: "https://www.youtube.com/watch?v=yt3" });
+ const { run } = stubRunner({ writes: null });
+ const l = log();
+ const r = await fetchLiveChat({
+ paths, slug: SLUG, videoId: "yt3", videoUrl: "https://www.youtube.com/watch?v=yt3",
+ channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: l.onLog, signal: new AbortController().signal, run,
+ });
+ assert.deepEqual(r, { status: "none" });
+ assert.match(l.lines.join(""), /No chat replay for yt3/);
+ assert.deepEqual((await readdir(dir)).sort(), ["metadata.info.json"]);
+});
+
+test("a rate-limited pass records the cooldown and fails; an auth gate retries once with cookies", async () => {
+ await video("yt4", { webpage_url: "https://www.youtube.com/watch?v=yt4" });
+ let backoffs = 0;
+ const limited = stubRunner({ exitCode: 1, stderr: "ERROR: [youtube] yt4: HTTP Error 429: Too Many Requests" });
+ await assert.rejects(
+ fetchLiveChat({
+ paths, slug: SLUG, videoId: "yt4", videoUrl: "https://www.youtube.com/watch?v=yt4",
+ channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: () => {}, signal: new AbortController().signal,
+ run: limited.run, onPlatformBackoff: () => void backoffs++,
+ }),
+ /rate-limited the chat fetch/,
+ );
+ assert.equal(backoffs, 1);
+
+ const calls: string[][] = [];
+ const authThenOk = async (cwd: string, args: string[]): Promise<AttemptOutcome> => {
+ calls.push(args);
+ if (calls.length === 1) {
+ return { exitCode: 1, stderrTail: "ERROR: [youtube] yt4: Sign in to confirm your age", archiveLine: null, formatLine: null };
+ }
+ const base = args[args.findIndex((a) => a.startsWith("subtitle:"))].slice("subtitle:".length);
+ await writeFile(path.join(cwd, `${base}.live_chat.json`), REPLAY);
+ return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null };
+ };
+ const r = await fetchLiveChat({
+ paths, slug: SLUG, videoId: "yt4", videoUrl: "https://www.youtube.com/watch?v=yt4",
+ channelConfig: CONFIG, cookiePolicy: { cookies: "firefox", mode: "when-required" },
+ onLog: () => {}, signal: new AbortController().signal, run: authThenOk,
+ });
+ assert.equal(r.status, "fetched");
+ assert.equal(calls.length, 2);
+ assert.ok(!calls[0].includes("--cookies-from-browser"));
+ assert.ok(calls[1].includes("--cookies-from-browser"));
+});
+
+test("the job: refusals before any job (info for a skip), a fetch job, a normalize-only job", async () => {
+ await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG));
+ const tw = await runFetchChatJob({ paths, slug: SLUG, videoId: "tw1", channelConfig: CONFIG, cookiePolicy: NO_COOKIES });
+ assert.deepEqual(tw, { ok: false, info: true, error: "no chat fetcher for twitch: only YouTube's chat replay is fetched" });
+ const fresh = await runFetchChatJob({ paths, slug: SLUG, videoId: "yt2", channelConfig: CONFIG, cookiePolicy: NO_COOKIES });
+ assert.ok(!fresh.ok && fresh.info && /already here/.test(fresh.error));
+ const missing = await runFetchChatJob({ paths, slug: SLUG, videoId: "nope", channelConfig: CONFIG, cookiePolicy: NO_COOKIES });
+ assert.ok(!missing.ok && !missing.info);
+
+ const dir = await video("yt5", { webpage_url: "https://www.youtube.com/watch?v=yt5", was_live: true });
+ const { run, calls } = stubRunner();
+ const job = await runFetchChatJob({ paths, slug: SLUG, videoId: "yt5", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run });
+ assert.ok(job.ok, JSON.stringify(job));
+ void job.stream.cancel();
+ const done = await job.done;
+ assert.equal(done.status, "done");
+ assert.equal(calls.length, 1);
+ assert.ok((await readdir(dir)).includes("live_chat.cues.json"));
+
+ // The raw replay on disk with stale cues: normalized, no spawn.
+ const dir6 = await video("yt6", { webpage_url: "https://www.youtube.com/watch?v=yt6", was_live: true });
+ await writeFile(path.join(dir6, "transcript.live_chat.json"), REPLAY);
+ await writeFile(path.join(dir6, "live_chat.cues.json"), "{}");
+ const old = new Date(Date.now() - 60_000);
+ await utimes(path.join(dir6, "live_chat.cues.json"), old, old);
+ const spawn = stubRunner();
+ const norm = await runFetchChatJob({ paths, slug: SLUG, videoId: "yt6", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run: spawn.run });
+ assert.ok(norm.ok);
+ void norm.stream.cancel();
+ assert.equal((await norm.done).status, "done");
+ assert.equal(spawn.calls.length, 0, "no network for a replay already here");
+ assert.equal(JSON.parse(await readFile(path.join(dir6, "live_chat.cues.json"), "utf8")).cues.length, 3);
+});
diff --git a/common/controller/fetchLiveChat.ts b/common/controller/fetchLiveChat.ts
@@ -0,0 +1,312 @@
+// ONE VIDEO'S LIVE CHAT REPLAY, AND NOTHING ELSE — `pnpm ops fetch-chat
+// {slug, id}` (release 36, lane A), and the chat step of the find-clips job.
+//
+// The chat-only yt-dlp pass already existed, but only inside the managed
+// download's filter branch (a channel whose `rejectedLivestreams` is
+// "chat-only"): a video already archived for its media had no way to fetch
+// its chat alone. This runs THE SAME command line (downloadOneManaged.ts
+// liveChatOnlyArgs: the channel's args, its cookies and the platform's live
+// pace, then the refusals that keep it from fetching anything else), then
+// normalizes what landed into live_chat.cues.json (normalizeLiveChat — which
+// also tiers the raw replay, the one big file here, into media/).
+//
+// PACED LIKE EVERY YOUTUBE REQUEST: the job sits on the platform's DOWNLOAD
+// queue, so it waits behind a sync or a download on that platform rather than
+// bursting beside one; the argv carries the platform's live `--sleep-requests`;
+// a held platform or one in a rate-limit cooldown is refused before any job
+// exists (`info: true` — nothing is wrong, the source is resting); a
+// rate-limited pass records the platform's cooldown; a clean one settles it.
+// Cookies follow the channel's policy exactly as the metadata refresh's do:
+// up front for "always", once on an auth failure for "when-required".
+//
+// WHAT IS NOT A FAILURE:
+// - a video on another platform: no fetcher for its chat ("no chat fetcher
+// for twitch") — refused before a job, `info: true`;
+// - the chat already here and fresh (isLiveChatCuesFresh) — the same;
+// - a raw replay already here whose cues are stale: normalized, no network;
+// - a pass that writes nothing: chat replay is off for that stream, or it
+// was never live. The job ends `done` and says so.
+//
+// `needsMedia` (jobs/jobKinds.ts): it WRITES the raw replay, which is a
+// tierable big file, and the normalizer moves it into the channel's media/.
+
+import path from "node:path";
+import { readFile, readdir, stat } from "node:fs/promises";
+import {
+ AUTH_RETRY_CLASSES,
+ classifyDownloadFailure,
+ parseUnavailableFromStderr,
+} from "../lib/availability";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { assertChannelTextReadable } from "../lib/channelMedia";
+import {
+ DEFAULT_COOKIE_MODE,
+ alwaysCookies,
+ authRetryCookies,
+ type ResolvedCookiePolicy,
+} from "../lib/cookiePolicy";
+import { detectPlatform } from "../lib/platform";
+import type { Paths } from "../lib/paths";
+import { downloadQueueKey, resolveQueueKey } from "../lib/queueKeys";
+import { LIVE_CHAT_CUES_FILENAME, LIVE_CHAT_FILENAME, META_FILENAME } from "../lib/videoStatus";
+import {
+ heldPlatformRefusal,
+ platformCooldownRemainingMs,
+ recordDownloadBackoff,
+ recordPlatformClean,
+} from "../jobs/downloadBackoff";
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import { liveChatOnlyArgs } from "../ytdlp/downloadOneManaged";
+import { runOneYtdlp, type AttemptOutcome } from "../ytdlp/runOneYtdlp";
+import { isLiveChatCuesFresh, normalizeLiveChat, readNormalizedLiveChat } from "./normalizeLiveChat";
+import { isVideoIdSegment, notFetchedRefusal } from "./refreshVideoMetadata";
+import { findVideoSourceUrl } from "./undownloadedVideos";
+
+export const FETCH_CHAT_JOB_KIND = "fetch-chat";
+
+// The platforms whose chat replay a fetcher exists for. yt-dlp writes a
+// `live_chat` subtitle track for YouTube only.
+export const CHAT_PLATFORMS: ReadonlySet<string> = new Set(["youtube"]);
+
+/** What the chat of one video needs, from the disk and its metadata alone. */
+export type LiveChatPlan =
+ | { kind: "fresh"; cuesPath: string }
+ // The raw replay is here; its cues are missing or stale: normalize only.
+ | { kind: "normalize" }
+ | { kind: "no-fetcher"; platform: string }
+ // The metadata says the video was never live: there is no replay to ask for.
+ | { kind: "not-live"; liveStatus: string }
+ | { kind: "fetch"; url: string; platform: string }
+ | { kind: "refused"; error: string };
+
+async function isDirectory(p: string): Promise<boolean> {
+ return stat(p).then((s) => s.isDirectory(), () => false);
+}
+
+async function liveStatusOf(videoDir: string): Promise<string | null> {
+ try {
+ const meta = JSON.parse(await readFile(path.join(videoDir, META_FILENAME), "utf8")) as {
+ live_status?: unknown;
+ was_live?: unknown;
+ };
+ if (meta.was_live === true) return "was_live";
+ return typeof meta.live_status === "string" ? meta.live_status : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The sentence for a video whose chat has no fetcher. */
+export function noChatFetcherSentence(platform: string): string {
+ return `no chat fetcher for ${platform}: only YouTube's chat replay is fetched`;
+}
+
+export async function liveChatPlan(
+ paths: Paths,
+ slug: string,
+ videoId: string,
+ config: ChannelConfig,
+): Promise<LiveChatPlan> {
+ if (!isVideoIdSegment(videoId)) {
+ return { kind: "refused", error: `"${videoId}" is not a video id (one path segment)` };
+ }
+ const videoDir = path.join(paths.channelsDir, slug, "data", videoId);
+ if (!(await isDirectory(videoDir))) return { kind: "refused", error: notFetchedRefusal(videoId, slug) };
+ const fresh = await isLiveChatCuesFresh(videoDir);
+ if (fresh.fresh) return { kind: "fresh", cuesPath: fresh.cuesPath };
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ if (entries.includes(LIVE_CHAT_FILENAME) && entries.includes(META_FILENAME)) return { kind: "normalize" };
+ const url = await findVideoSourceUrl(paths, slug, videoId, config);
+ if (!url) {
+ return {
+ kind: "refused",
+ error: "Could not determine the video URL: no metadata.info.json and the playlist does not contain a matching entry.",
+ };
+ }
+ const platform = detectPlatform(url) ?? "unknown";
+ if (!CHAT_PLATFORMS.has(platform)) return { kind: "no-fetcher", platform };
+ const live = await liveStatusOf(videoDir);
+ if (live === "not_live") return { kind: "not-live", liveStatus: live };
+ return { kind: "fetch", url, platform };
+}
+
+function succeeded(exitCode: number | null): boolean {
+ // yt-dlp: 0 = clean, 101 = a clean stop.
+ return exitCode === 0 || exitCode === 101;
+}
+
+function tail(stderr: string): string {
+ return stderr.trim().split("\n").slice(-3).join(" / ");
+}
+
+export type ChatRunner = (cwd: string, args: string[]) => Promise<AttemptOutcome>;
+
+export type FetchLiveChatOpts = {
+ paths: Paths;
+ slug: string;
+ videoId: string;
+ videoUrl: string;
+ channelConfig: ChannelConfig;
+ cookiePolicy?: ResolvedCookiePolicy;
+ onLog: (s: string) => void;
+ signal: AbortSignal;
+ onPlatformBackoff?: () => Promise<void> | void;
+ onPlatformClean?: () => Promise<string | null> | string | null;
+ // Test seams: the spawn, and the platform pace in the argv.
+ run?: ChatRunner;
+ paceSeconds?: number;
+};
+
+export type FetchLiveChatResult =
+ | { status: "fetched"; messages: number; cuesPath: string }
+ | { status: "none" };
+
+/** The pass, then the normalize. Throws on a failed pass (the job ends `failed`). */
+export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise<FetchLiveChatResult> {
+ const channelDir = path.join(opts.paths.channelsDir, opts.slug);
+ const videoDir = path.join(channelDir, "data", opts.videoId);
+ const policy: ResolvedCookiePolicy = opts.cookiePolicy ?? { cookies: undefined, mode: DEFAULT_COOKIE_MODE };
+ const run: ChatRunner =
+ opts.run ??
+ ((cwd, args) => runOneYtdlp({ ytdlpBin: opts.paths.ytdlpBin, onLog: opts.onLog, signal: opts.signal }, cwd, args));
+ if (!(await isDirectory(videoDir))) throw new Error(notFetchedRefusal(opts.videoId, opts.slug));
+ const pass = (cookies: string | undefined) =>
+ run(channelDir, liveChatOnlyArgs(opts.channelConfig, cookies, opts.videoUrl, opts.paceSeconds));
+
+ opts.onLog(`Fetching the live chat replay of ${opts.videoId} from ${opts.videoUrl} (no media)\n`);
+ const firstCookies = alwaysCookies(policy);
+ let outcome = await pass(firstCookies);
+ if (!succeeded(outcome.exitCode) && !opts.signal.aborted) {
+ const cls = parseUnavailableFromStderr(outcome.stderrTail);
+ const retryCookies = authRetryCookies(policy);
+ if (
+ classifyDownloadFailure(outcome.stderrTail, cls) !== "rate_limit" &&
+ AUTH_RETRY_CLASSES.has(cls) &&
+ retryCookies !== undefined &&
+ !firstCookies
+ ) {
+ opts.onLog(`The chat fetch needs a login (${cls}); retrying with --cookies-from-browser ${retryCookies}\n`);
+ outcome = await pass(retryCookies);
+ }
+ }
+ if (opts.signal.aborted) throw new Error("Cancelled");
+ if (!succeeded(outcome.exitCode)) {
+ const cls = parseUnavailableFromStderr(outcome.stderrTail);
+ if (classifyDownloadFailure(outcome.stderrTail, cls) === "rate_limit") {
+ await opts.onPlatformBackoff?.();
+ throw new Error(
+ `The source rate-limited the chat fetch of ${opts.videoId}; a per-platform cooldown has been recorded. ` +
+ `(${tail(outcome.stderrTail)})`,
+ );
+ }
+ throw new Error(`yt-dlp could not fetch the chat of ${opts.videoId} (exit ${outcome.exitCode ?? "null"}): ${tail(outcome.stderrTail)}`);
+ }
+ try {
+ const line = await opts.onPlatformClean?.();
+ if (line) opts.onLog(line);
+ } catch {
+ /* shared-state write is best-effort */
+ }
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ if (!entries.includes(LIVE_CHAT_FILENAME)) {
+ opts.onLog(`No chat replay for ${opts.videoId}: the source has none (chat replay off, or never live). Nothing written.\n`);
+ return { status: "none" };
+ }
+ return normalizeChat(opts, videoDir);
+}
+
+async function normalizeChat(
+ opts: Pick<FetchLiveChatOpts, "slug" | "videoId" | "channelConfig" | "onLog">,
+ videoDir: string,
+): Promise<FetchLiveChatResult> {
+ const out = await normalizeLiveChat({
+ videoDir,
+ channelSlug: opts.slug,
+ ...(opts.channelConfig.name ? { configName: opts.channelConfig.name } : {}),
+ force: true,
+ log: (m) => opts.onLog(`${m}\n`),
+ });
+ if (out.status === "skipped") {
+ throw new Error(`the chat of ${opts.videoId} could not be normalized (${out.reason})`);
+ }
+ const doc = await readNormalizedLiveChat(out.cuesPath);
+ const messages = doc?.cues?.length ?? 0;
+ opts.onLog(`Live chat of ${opts.videoId}: ${messages} message(s) in ${LIVE_CHAT_CUES_FILENAME}\n`);
+ return { status: "fetched", messages, cuesPath: out.cuesPath };
+}
+
+export type FetchChatJobOpts = {
+ paths: Paths;
+ slug: string;
+ videoId: string;
+ channelConfig: ChannelConfig;
+ cookiePolicy: ResolvedCookiePolicy;
+ queueKey?: string;
+ afterRun?: () => void | Promise<void>;
+ run?: ChatRunner;
+};
+
+// Every refusal before any job, in the sentences the rest of the app uses.
+export async function runFetchChatJob(opts: FetchChatJobOpts): Promise<StreamActionResult> {
+ const { paths, slug, videoId, channelConfig } = opts;
+ try {
+ await assertChannelTextReadable(paths, slug, channelConfig);
+ } catch (err) {
+ return { ok: false, error: (err as Error).message };
+ }
+ const plan = await liveChatPlan(paths, slug, videoId, channelConfig);
+ switch (plan.kind) {
+ case "refused":
+ return { ok: false, error: plan.error };
+ case "fresh":
+ return { ok: false, info: true, error: `the live chat of ${videoId} is already here (${LIVE_CHAT_CUES_FILENAME}, fresh)` };
+ case "no-fetcher":
+ return { ok: false, info: true, error: noChatFetcherSentence(plan.platform) };
+ case "not-live":
+ return { ok: false, info: true, error: `${videoId} was never live (live_status ${plan.liveStatus}): there is no chat replay` };
+ case "normalize":
+ case "fetch":
+ break;
+ }
+ if (plan.kind === "fetch") {
+ const held = await heldPlatformRefusal(plan.platform, "The chat fetch", paths);
+ if (held) return { ok: false, info: true, error: held };
+ const remainingMs = await platformCooldownRemainingMs(plan.platform, paths);
+ if (remainingMs > 0) {
+ return {
+ ok: false,
+ info: true,
+ error: `${plan.platform} is in a rate-limit cooldown (${Math.ceil(remainingMs / 1000)}s remaining). Fetch the chat once the cooldown lapses.`,
+ };
+ }
+ }
+ const videoDir = path.join(paths.channelsDir, slug, "data", videoId);
+ return runManagedFunction({
+ kind: FETCH_CHAT_JOB_KIND,
+ queueKey: resolveQueueKey(downloadQueueKey(channelConfig), opts.queueKey),
+ paths,
+ channelSlug: slug,
+ videoId,
+ fn: async (onLog, signal) => {
+ if (plan.kind === "normalize") {
+ onLog(`The chat replay of ${videoId} is on disk; normalizing it (no network).`);
+ await normalizeChat({ slug, videoId, channelConfig, onLog }, videoDir);
+ } else {
+ await fetchLiveChat({
+ paths,
+ slug,
+ videoId,
+ videoUrl: plan.url,
+ channelConfig,
+ cookiePolicy: opts.cookiePolicy,
+ onLog,
+ signal,
+ onPlatformBackoff: () => recordDownloadBackoff(plan.platform, paths),
+ onPlatformClean: () => recordPlatformClean(plan.platform, paths),
+ ...(opts.run ? { run: opts.run } : {}),
+ });
+ }
+ await opts.afterRun?.();
+ },
+ });
+}
diff --git a/common/controller/findClips.test.ts b/common/controller/findClips.test.ts
@@ -0,0 +1,420 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { ChannelConfig } from "../lib/channelConfig";
+import type { TranscribeFileRequest, TranscribeFileResult } from "./transcribeFile";
+import type { FindClipsDeps } from "./findClips";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/findClips.test.ts
+//
+// THE CHAIN END TO END WITH STUBS (release 36, lane A): the editor's ops
+// actions (a door that writes what each job would leave), the job registry
+// (every job done), the word timings (a fake engine result), diarization (a
+// started job that writes diarization.json) and umtool (a fetch that answers
+// the clips route's contract). No yt-dlp, no engine, no network. Every case
+// is its own video in one temp corpus.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "find-clips-"));
+const CORPUS = path.join(ROOT, "transcripts");
+process.env.TRANSCRIPTS_DIR = CORPUS;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await mkdir(CORPUS, { recursive: true });
+await writeFile(process.env.SETTINGS_FILE, "{}");
+
+const { getPaths } = await import("../lib/paths");
+const { getSettings } = await import("../lib/settings");
+const {
+ FIND_CLIPS_RESULT_MARKER,
+ enqueueFindClips,
+ parseFindClipsBody,
+ planFindClipsSteps,
+ inspectFindClips,
+ projectSlugFor,
+ runFindClips,
+} = await import("./findClips");
+const { loadFindClipsRecord } = await import("../lib/findClipsRecord-server");
+
+const paths = getPaths();
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const SLUG = "synth-react";
+const CONFIG = { handling: "transcribe", url: "https://www.youtube.com/@synth/streams", name: "Synth" } as ChannelConfig;
+await mkdir(path.join(CORPUS, "channels", SLUG), { recursive: true });
+await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG));
+
+const SETTINGS_ON = () => {
+ const s = getSettings();
+ return {
+ ...s,
+ diarization: { ...s.diarization, enabled: true, segModel: "/m/seg.onnx", embModel: "/m/emb.onnx" },
+ autoQueue: { ...s.autoQueue, backfill: { ...s.autoQueue.backfill, held: false } },
+ };
+};
+const SEGMENTS = [
+ { id: "s1", from: 290, to: 6300, subject: 4, host: 1, why: "subject 4 holds 81% of long-turn time" },
+ { id: "s2", from: 6500, to: 9278, subject: 16, host: 1, why: "subject 16 holds 77% of long-turn time" },
+];
+
+async function video(id: string, platformUrl = `https://www.youtube.com/watch?v=${id}`): Promise<string> {
+ const dir = path.join(CORPUS, "channels", SLUG, "data", id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id, title: "Synth stream", webpage_url: platformUrl, was_live: true }));
+ return dir;
+}
+
+// Everything a finished chain leaves on disk, so every step is skipped.
+async function complete(dir: string) {
+ await writeFile(path.join(dir, "source-media.mp4"), "container");
+ await writeFile(path.join(dir, "audio.mp3"), "audio");
+ await writeFile(path.join(dir, "transcript.json"), JSON.stringify({ transcription: [] }));
+ await writeFile(path.join(dir, "words.json"), JSON.stringify({ version: 1, words: [{ w: "hello", start: 1, end: 1.4 }] }));
+ await writeFile(path.join(dir, "transcript.live_chat.json"), "\n");
+ await writeFile(path.join(dir, "live_chat.cues.json"), JSON.stringify({ version: 1, source: "live_chat", cues: [] }));
+ await writeFile(path.join(dir, "diarization.json"), JSON.stringify({ speakers: [] }));
+}
+
+type Harness = {
+ deps: FindClipsDeps;
+ actions: { action: string; args: Record<string, unknown> }[];
+ umtoolCalls: { method: string; url: string; body?: unknown; auth?: string | null }[];
+ words: TranscribeFileRequest[];
+ diarized: number;
+ log: string[];
+};
+
+function harness(dir: string, o: { umtool?: "ok" | "down" | "refuses" | "fails" | "busy" | "exists"; paused?: boolean; pauseHeld?: string[]; chatFails?: boolean } = {}): Harness {
+ const h: Harness = { actions: [], umtoolCalls: [], words: [], diarized: 0, log: [], deps: null as unknown as FindClipsDeps };
+ let n = 0;
+ const editor = {
+ async run(action: string, args: Record<string, unknown>) {
+ h.actions.push({ action, args });
+ if (action === "persist-videos") await writeFile(path.join(dir, "source-media.mp4"), "container");
+ if (action === "transcribe-one") await writeFile(path.join(dir, "transcript.json"), JSON.stringify({ transcription: [] }));
+ if (action === "fetch-chat") {
+ if (o.chatFails) throw new Error("youtube is in a rate-limit cooldown (300s remaining)");
+ await writeFile(path.join(dir, "transcript.live_chat.json"), "\n");
+ await writeFile(path.join(dir, "live_chat.cues.json"), JSON.stringify({ version: 1, source: "live_chat", cues: [] }));
+ }
+ return { ok: true, jobId: `j${++n}` };
+ },
+ };
+ let polls = 0;
+ const fetchStub = (async (input: string | URL | Request, init?: RequestInit) => {
+ const url = String(input);
+ const method = init?.method ?? "GET";
+ const auth = new Headers(init?.headers).get("authorization");
+ h.umtoolCalls.push({ method, url, ...(init?.body ? { body: JSON.parse(String(init.body)) } : {}), auth });
+ if (o.umtool === "down") throw new TypeError("fetch failed (ECONNREFUSED)");
+ if (method === "POST") {
+ if (o.umtool === "refuses") return Response.json({ error: "no diarization.json for synth-react/v" }, { status: 400 });
+ if (o.umtool === "exists") return Response.json({ error: "project v-clips already exists" }, { status: 409 });
+ if (o.umtool === "busy" && h.umtoolCalls.filter((c) => c.method === "POST").length < 3) {
+ return Response.json({ error: "a job is already running (clips-analyze)", running: { id: "u0" } }, { status: 409 });
+ }
+ return Response.json({
+ ok: true,
+ jobId: "u1",
+ job: { id: "u1" },
+ project: "v-clips",
+ created: true,
+ segments: SEGMENTS,
+ segment: "s1",
+ scope: [290, 6300],
+ href: "/projects/v-clips/clips",
+ notes: ["words.json copied in"],
+ });
+ }
+ polls++;
+ if (polls === 1) return Response.json({ state: "running", log: ["analyze: laughs 12"], next: 1 });
+ if (o.umtool === "fails") return Response.json({ state: "failed", error: "CED-mini exited 1", log: [], next: 1 });
+ return Response.json({ state: "done", log: ["propose: 18 clips, 612 s"], next: 2 });
+ }) as typeof fetch;
+ h.deps = {
+ paths,
+ editor,
+ jobOf: async () => ({ status: "done" }),
+ umtoolUrl: "http://127.0.0.1:9",
+ workerToken: "tok",
+ fetch: fetchStub,
+ settings: SETTINGS_ON,
+ pool: {
+ isPaused: () => o.paused === true,
+ enabledIds: () => (o.paused ? [] : ["gpu"]),
+ pauseHeldIds: () => o.pauseHeld ?? (o.paused ? ["gpu"] : []),
+ },
+ transcribeWords: async (req) => {
+ h.words.push(req);
+ return {
+ version: 1,
+ path: req.path,
+ window: null,
+ worker: { id: "gpu", name: "GPU", appId: "parakeet", model: "m.gguf", device: null },
+ transcriptFormat: "chough-json",
+ transcribedAt: "2026-10-19T00:00:00.000Z",
+ durationMs: 10,
+ waitedMs: 0,
+ cues: [{ start: 1, end: 2, text: "hello world" }],
+ text: "hello world",
+ words: [
+ { w: "hello", start: 1, end: 1.4 },
+ { w: "world", start: 1.5, end: 2 },
+ ],
+ } satisfies TranscribeFileResult;
+ },
+ diarize: async () => {
+ h.diarized++;
+ await writeFile(path.join(dir, "diarization.json"), JSON.stringify({ speakers: [] }));
+ return { ok: true, jobId: "d1", stream: new ReadableStream<string>(), done: Promise.resolve({ status: "done" as const, jobId: "d1" }) };
+ },
+ pollMs: 1,
+ sleep: async () => {},
+ };
+ return h;
+}
+
+const run = (h: Harness, id: string, extra: Record<string, unknown> = {}) =>
+ runFindClips({ slug: SLUG, id, ...extra }, h.deps, {
+ config: CONFIG,
+ onLog: (l) => h.log.push(l),
+ signal: new AbortController().signal,
+ });
+
+test("the body: slug and id required; target, segment, project and the flags checked", () => {
+ assert.match((parseFindClipsBody({}) as { error: string }).error, /"slug" is required/);
+ assert.match((parseFindClipsBody({ slug: SLUG }) as { error: string }).error, /"id" is required/);
+ assert.match((parseFindClipsBody({ slug: SLUG, id: "v", target: 3 }) as { error: string }).error, /"target"/);
+ assert.match((parseFindClipsBody({ slug: SLUG, id: "v", segment: "s 2" }) as { error: string }).error, /"segment"/);
+ assert.match((parseFindClipsBody({ slug: SLUG, id: "v", project: "Bad_Slug" }) as { error: string }).error, /"project"/);
+ assert.match((parseFindClipsBody({ slug: SLUG, id: "v", whilePaused: "yes" }) as { error: string }).error, /"whilePaused"/);
+ assert.deepEqual(parseFindClipsBody({ slug: SLUG, id: "v", target: 600.4, segment: "s2", whilePaused: true, dryRun: false }), {
+ ok: true,
+ value: { slug: SLUG, id: "v", target: 600, segment: "s2", whilePaused: true },
+ });
+ assert.equal(projectSlugFor("fGSRhEWc9M4"), "fgsrhewc9m4-clips");
+ assert.equal(projectSlugFor("fGSRhEWc9M4", "s2"), "fgsrhewc9m4-clips-s2");
+});
+
+test("every step run: each in order, named in the log, outputs written, umtool followed", async () => {
+ const id = "runAll00001";
+ const dir = await video(id);
+ const h = harness(dir);
+ const r = await run(h, id, { target: 600, whilePaused: true });
+ assert.deepEqual(
+ h.actions.map((a) => a.action),
+ ["persist-videos", "transcribe-one", "fetch-chat"],
+ );
+ assert.deepEqual(h.actions[0].args, { items: [{ slug: SLUG, id }] });
+ assert.deepEqual(h.actions[1].args, { slug: SLUG, id, whilePaused: true });
+ assert.equal(h.words.length, 1);
+ assert.equal(h.words[0].words, true);
+ assert.equal(h.words[0].whilePaused, true);
+ assert.equal(h.words[0].path, path.join(dir, "source-media.mp4"), "the container when no audio file is here");
+ assert.equal(h.diarized, 1);
+ // words.json: the result without cues and text.
+ const words = JSON.parse(await readFile(path.join(dir, "words.json"), "utf8"));
+ assert.equal(words.words.length, 2);
+ assert.ok(!("cues" in words) && !("text" in words));
+ // umtool: the contract's body, the worker token, then the job followed.
+ const post = h.umtoolCalls[0];
+ assert.equal(post.method, "POST");
+ assert.equal(post.url, "http://127.0.0.1:9/api/report/clips");
+ assert.equal(post.auth, "Bearer tok");
+ assert.deepEqual(post.body, {
+ mode: "new",
+ slug: "runall00001-clips",
+ from: `${SLUG}/${id}`,
+ target: 600,
+ scope: "auto",
+ wordsPath: path.join(dir, "words.json"),
+ });
+ assert.match(h.umtoolCalls[1].url, /\?job=u1&since=0$/);
+ assert.match(h.umtoolCalls[2].url, /\?job=u1&since=1$/);
+ const text = h.log.join("\n");
+ for (const line of [
+ /running: saved video — no saved video/,
+ /running: corpus transcript — no corpus transcript/,
+ /running: word timings — transcribing source-media\.mp4 with word timings/,
+ /running: chat replay — fetching the chat replay/,
+ /running: diarization — no diarization\.json/,
+ /running: umtool — finding the segments and the clips/,
+ /umtool: analyze: laughs 12/,
+ /umtool: propose: 18 clips, 612 s/,
+ ]) {
+ assert.match(text, line);
+ }
+ assert.equal(r.project, "v-clips");
+ assert.equal(r.url, "http://127.0.0.1:9/projects/v-clips/clips");
+ assert.equal(r.created, true);
+ assert.equal(r.segment, "s1", "the segment auto-scope chose");
+ assert.match(text, /umtool: made project v-clips \(segment s1\) \(job u1\)/);
+ assert.match(text, /umtool: note: words\.json copied in/);
+ assert.deepEqual(r.segments.map((s) => s.id), ["s1", "s2"]);
+ assert.deepEqual(r.steps.map((s) => s.action), ["ran", "ran", "ran", "ran", "ran", "ran"]);
+});
+
+test("every step skipped: nothing asked of the editor or an engine; umtool still asked", async () => {
+ const id = "skipAll0001";
+ const dir = await video(id);
+ await complete(dir);
+ const h = harness(dir);
+ const r = await run(h, id, { segment: "s2" });
+ assert.deepEqual(h.actions, []);
+ assert.equal(h.words.length, 0);
+ assert.equal(h.diarized, 0);
+ const text = h.log.join("\n");
+ for (const line of [
+ /skipped: saved video — saved video present/,
+ /skipped: corpus transcript — transcript\.json present/,
+ /skipped: word timings — words\.json present \(1 words\)/,
+ /skipped: chat replay — live_chat\.cues\.json present/,
+ /skipped: diarization — diarization\.json present/,
+ /running: umtool — finding clips in segment s2/,
+ ]) {
+ assert.match(text, line);
+ }
+ assert.deepEqual(h.umtoolCalls[0].body, {
+ mode: "new",
+ slug: "skipall0001-clips-s2",
+ from: `${SLUG}/${id}`,
+ segment: "s2",
+ wordsPath: path.join(dir, "words.json"),
+ });
+ assert.equal(r.segment, "s2");
+ assert.deepEqual(r.steps.map((s) => s.action), ["skipped", "skipped", "skipped", "skipped", "skipped", "ran"]);
+});
+
+test("umtool down, refusing, or failing: a clear failure naming the step", async () => {
+ for (const [mode, re] of [
+ ["down", /^step umtool: umtool at http:\/\/127\.0\.0\.1:9 did not answer \(fetch failed \(ECONNREFUSED\)\) — is it running\?$/],
+ ["refuses", /^step umtool: umtool refused the clips request \(HTTP 400\): no diarization\.json/],
+ ["fails", /^step umtool: umtool job u1 failed: CED-mini exited 1$/],
+ ["exists", /^step umtool: umtool refused the clips request \(HTTP 409\): project v-clips already exists$/],
+ ] as const) {
+ const id = `um${mode}`.padEnd(11, "0");
+ const dir = await video(id);
+ await complete(dir);
+ await assert.rejects(run(harness(dir, { umtool: mode }), id), { message: re });
+ }
+});
+
+test("a busy umtool (409 naming its running job) is waited for, then asked again", async () => {
+ const id = "umbusy00001";
+ const dir = await video(id);
+ await complete(dir);
+ const h = harness(dir, { umtool: "busy" });
+ const r = await run(h, id);
+ assert.equal(r.project, "v-clips");
+ assert.equal(h.umtoolCalls.filter((c) => c.method === "POST").length, 3);
+ assert.equal(h.log.filter((l) => /umtool is busy \(a job is already running \(clips-analyze\)\); waiting for it/.test(l)).length, 1);
+});
+
+test("a twitch video skips the chat with the sentence; a refused chat fetch is logged and the chain goes on", async () => {
+ const tw = await video("twitch00001", "https://www.twitch.tv/videos/123");
+ await complete(tw);
+ await rm(path.join(tw, "live_chat.cues.json"));
+ await rm(path.join(tw, "transcript.live_chat.json"));
+ const h = harness(tw);
+ await run(h, "twitch00001");
+ assert.match(h.log.join("\n"), /skipped: chat replay — no chat fetcher for twitch: only YouTube's chat replay is fetched/);
+ assert.deepEqual(h.actions, []);
+
+ const yt = await video("chatfail001");
+ await complete(yt);
+ await rm(path.join(yt, "live_chat.cues.json"));
+ await rm(path.join(yt, "transcript.live_chat.json"));
+ const h2 = harness(yt, { chatFails: true });
+ const r = await run(h2, "chatfail001");
+ assert.match(h2.log.join("\n"), /the chat was not fetched \(step chat replay: fetch-chat refused: youtube is in a rate-limit cooldown/);
+ assert.equal(r.project, "v-clips", "the chain finished without the chat");
+});
+
+test("a paused pool fails the transcription step at once unless the run is whilePaused", async () => {
+ const id = "paused00001";
+ const dir = await video(id);
+ await writeFile(path.join(dir, "source-media.mp4"), "container");
+ await assert.rejects(run(harness(dir, { paused: true }), id), { message: /^step corpus transcript: the transcription workers are paused — run it with "while paused"/ });
+ // Paused, flagged, but no worker the pause alone switched off.
+ await assert.rejects(
+ run(harness(dir, { paused: true, pauseHeld: [] }), id, { whilePaused: true }),
+ { message: /^step corpus transcript: the workers are paused and none was switched off by the pause alone/ },
+ );
+ const h = harness(dir, { paused: true });
+ await run(h, id, { whilePaused: true });
+ assert.equal(h.actions.find((a) => a.action === "transcribe-one")?.args.whilePaused, true);
+ assert.equal(h.words[0].whilePaused, true);
+});
+
+test("diarization off or the backfill lane held fails the step with where to fix it", async () => {
+ const id = "diar0000001";
+ const dir = await video(id);
+ await complete(dir);
+ await rm(path.join(dir, "diarization.json"));
+ const off = harness(dir);
+ off.deps.settings = () => getSettings();
+ await assert.rejects(run(off, id), { message: /^step diarization: diarization is switched off, or its models are not set — set it up on \/operations\/diarization$/ });
+ const held = harness(dir);
+ held.deps.settings = () => {
+ const s = SETTINGS_ON();
+ return { ...s, autoQueue: { ...s.autoQueue, backfill: { ...s.autoQueue.backfill, held: true } } };
+ };
+ await assert.rejects(run(held, id), { message: /^step diarization: the backfill lane is held, and it holds a diarization run too — run Find clips "while paused"/ });
+
+ // whilePaused: the one-video diarization in this job, the lane left held.
+ let inline = 0;
+ held.deps.diarizeInline = async () => {
+ inline++;
+ await writeFile(path.join(dir, "diarization.json"), JSON.stringify({ speakers: [] }));
+ return "diarized";
+ };
+ await run(held, id, { whilePaused: true });
+ assert.equal(inline, 1);
+ assert.equal(held.diarized, 0, "the lane job was not asked");
+ assert.match(held.log.join("\n"), /running: diarization — no diarization\.json: diarizing this one video in this job \(the backfill lane stays held\)/);
+ // An engine that fails names its outcome.
+ await rm(path.join(dir, "diarization.json"));
+ held.deps.diarizeInline = async () => "failed";
+ await assert.rejects(run(held, id, { whilePaused: true }), { message: /^step diarization: the one-video diarization ended "failed"$/ });
+});
+
+test("the dry run plans every step from the disk; the job writes find-clips.json and ends with the marker", async () => {
+ const id = "dryrun00001";
+ const dir = await video(id);
+ await writeFile(path.join(dir, "transcript.json"), "{}");
+ const state = await inspectFindClips(paths, SLUG, id, CONFIG);
+ assert.deepEqual(
+ planFindClipsSteps(state, {}).map((s) => [s.id, s.run]),
+ [["persist", true], ["transcript", false], ["words", true], ["chat", true], ["diarization", true], ["umtool", true]],
+ );
+ const h = harness(dir);
+ const dry = await enqueueFindClips({ slug: SLUG, id, dryRun: true }, h.deps);
+ assert.ok(dry.dryRun);
+ assert.equal(dry.plan.steps.length, 6);
+ assert.deepEqual(h.actions, [], "a dry run asks nothing");
+
+ // Refusals before a job.
+ const noUmtool = await enqueueFindClips({ slug: SLUG, id }, { ...h.deps, umtoolUrl: null });
+ assert.ok(!noUmtool.dryRun && !noUmtool.result.ok && /UMTOOL_URL is not set/.test(noUmtool.result.error));
+ const noVideo = await enqueueFindClips({ slug: SLUG, id: "nope" }, h.deps);
+ assert.ok(!noVideo.dryRun && !noVideo.result.ok && /not a video of synth-react/.test(noVideo.result.error));
+ const noChannel = await enqueueFindClips({ slug: "no-such-channel", id }, h.deps);
+ assert.ok(!noChannel.dryRun && !noChannel.result.ok && /not found/.test(noChannel.result.error));
+
+ const out = await enqueueFindClips({ slug: SLUG, id }, h.deps);
+ assert.ok(!out.dryRun && out.result.ok, JSON.stringify(out));
+ void out.result.stream.cancel();
+ const done = await out.result.done;
+ assert.equal(done.status, "done");
+ const record = await loadFindClipsRecord(dir);
+ assert.ok(record);
+ assert.equal(record.project, "v-clips");
+ assert.equal(record.url, "http://127.0.0.1:9/projects/v-clips/clips");
+ assert.equal(record.jobId, out.result.jobId);
+ assert.deepEqual(record.segments.map((s) => s.id), ["s1", "s2"]);
+ const log = await readFile(path.join(paths.jobsDir, `${out.result.jobId}.log`), "utf8");
+ const line = log.split("\n").find((l) => l.startsWith(FIND_CLIPS_RESULT_MARKER));
+ assert.ok(line, log);
+ assert.equal(JSON.parse(line.slice(FIND_CLIPS_RESULT_MARKER.length)).umtoolJob, "u1");
+});
diff --git a/common/controller/findClips.ts b/common/controller/findClips.ts
@@ -0,0 +1,718 @@
+// FIND CLIPS — the clip finder's whole chain for ONE video, as one job
+// (release 36, lane A): the video page's Find clips, `pnpm ops find-clips`.
+//
+// Release 35 ran this from a shell, step by step: persist the source video,
+// the corpus transcript, word timings (`pnpm ops transcribe {words:true}`),
+// diarization, then `umtool new --seed reactions` and `umtool clips
+// analyze`. Each of those is already an editor operation; what was missing
+// is the chain. This job runs it, in order, and SKIPS EVERY STEP WHOSE OUTPUT
+// IS ALREADY ON DISK, naming each in its log ("skipped: saved video — …",
+// "running: word timings — …"):
+//
+// persist no saved video (and no source container in the dir) →
+// `persist-videos {items: [{slug, id}]}`, waited on
+// transcript no corpus transcript (transcript.json or an English
+// caption track) → `transcribe-one {slug, id}`, waited on
+// words no words.json beside it → the file transcription with word
+// timestamps (transcribeFile.ts runTranscribeFile, words) IN
+// THIS JOB on a worker lease, written to data/<id>/words.json
+// (lib/wordTimings-server.ts) — reusable, so skippable
+// chat a YouTube video whose chat replay is not here and fresh →
+// `fetch-chat {slug, id}` (fetchLiveChat.ts), waited on; any
+// other platform is skipped with "no chat fetcher for …". The
+// chat is a signal, not a requirement: a refused or failed
+// fetch is logged and the chain goes on without it
+// diarization no diarization.json → the backfill lane's one-video run
+// (operationJobs.ts runBackfillChannelJob, the panel's Run),
+// waited on; with the lane HELD and a `whilePaused` run, the
+// one-video diarization in this job instead (diarizeOne.ts),
+// the hold left on
+// umtool `POST ${UMTOOL_URL}/api/report/clips {mode: "new", slug,
+// from, target?, scope: "auto" | segment, wordsPath}` with
+// `Authorization: Bearer WORKER_TOKEN` → {jobId, project,
+// created, segments}; then `GET ?job=<id>` followed to the end,
+// its log relayed here line by line
+//
+// The editor-side steps go through THE EDITOR'S OWN OPS ACTIONS IN PROCESS
+// (deps.editor — editor/app/api/ops/_researchEditor.ts findClipsEditor, the
+// research run's door): the same body checks, refusals and queues a `pnpm
+// ops` caller meets. Each is its own job on its own queue (the platform's
+// download queue, the transcription pool, the backfill queue), and this job
+// waits on it from the `find-clips` queue — never on a queue a step needs.
+//
+// WHAT HOLDS IT IS SAID, NOT WAITED ON FOREVER. A paused transcription pool
+// would park a transcription step until someone resumed it: unless the run
+// asked `whilePaused` (then the two transcriptions run on a worker the pause
+// alone switched off — workerPool.ts pauseHeld — and the pause stays on),
+// the step fails at once with the sentence. Diarization switched off fails
+// the same way, and so does a held backfill lane unless the run is
+// `whilePaused` ("this one video, past the holds"). umtool not answering
+// fails the umtool step with its URL.
+//
+// THE RESULT: the log ends with `@@find-clips {json}` (how `pnpm ops
+// find-clips --wait` prints it), and data/<id>/find-clips.json records it for
+// the video page — the project, its clip editor's URL, the segments umtool
+// found, and what each step did.
+
+import path from "node:path";
+import { readdir, stat } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import type { SiteSettings } from "../lib/settings";
+import { getSettings } from "../lib/settings";
+import { assertChannelTextReadable } from "../lib/channelMedia";
+import { findSourceMedia, isRealAudioFile, pickPreferredAudio } from "../lib/mediaFiles";
+import { DIARIZATION_FILENAME, englishVttsByPreference, WHISPER_FILENAME } from "../lib/videoStatus";
+import { loadSavedVideo, resolveSavedVideo } from "../lib/savedVideo-server";
+import { backfillLaneOperations, DIARIZATION_OPERATION_ID } from "../lib/operations";
+import { isGateHeld } from "../lib/pauseGates";
+import { getWorkerToken } from "../lib/workerToken";
+import { umtoolUrl as resolveUmtoolUrl } from "../lib/umtoolUrl";
+import { loadWordTimings, writeWordTimings, wordTimingsSidecar, type WordTimingsRecord } from "../lib/wordTimings-server";
+import {
+ writeFindClipsRecord,
+ type FindClipsRecord,
+ type FindClipsSegment,
+ type FindClipsStepRecord,
+} from "../lib/findClipsRecord-server";
+import type { ResearchEditor } from "../lib/report/draft/research/tools";
+import { getWorkerPool, type WorkerPool } from "../jobs/workerPool";
+import { runManagedFunction, type JobRunContext, type StreamActionResult } from "../jobs/streamCommand";
+import { readChannelConfig, isValidChannelSlug } from "./channels";
+import { isVideoIdSegment } from "./refreshVideoMetadata";
+import { liveChatPlan, noChatFetcherSentence, type LiveChatPlan } from "./fetchLiveChat";
+import { runBackfillChannelJob, type BackfillChannelJobOptions } from "./operationJobs";
+import { diarizeOneVideo, type DiarizeOneOutcome } from "./diarizeOne";
+import { runTranscribeFile, type TranscribeFileRequest, type TranscribeFileResult } from "./transcribeFile";
+
+export const FIND_CLIPS_JOB_KIND = "find-clips";
+// Its own queue, one at a time: two chains over one machine would contend for
+// the same worker and the same umtool runner (which runs one job at a time).
+export const FIND_CLIPS_QUEUE = "find-clips";
+export const FIND_CLIPS_RESULT_MARKER = "@@find-clips ";
+export const FIND_CLIPS_BODY_KEYS = ["slug", "id", "target", "segment", "project", "whilePaused", "dryRun"] as const;
+// The editor actions the chain asks its door for.
+export const FIND_CLIPS_EDITOR_ACTIONS = ["persist-videos", "transcribe-one", "fetch-chat"] as const;
+
+export type FindClipsStepId = "persist" | "transcript" | "words" | "chat" | "diarization" | "umtool";
+
+export const FIND_CLIPS_STEP_LABELS: Record<FindClipsStepId, string> = {
+ persist: "saved video",
+ transcript: "corpus transcript",
+ words: "word timings",
+ chat: "chat replay",
+ diarization: "diarization",
+ umtool: "umtool",
+};
+
+export type FindClipsRequest = {
+ slug: string;
+ id: string;
+ // The cut's target length, seconds (umtool's default when absent).
+ target?: number;
+ // A segment umtool found ("s2"): find clips in that part only.
+ segment?: string;
+ // The umtool project's slug when one is made (default: from the id).
+ project?: string;
+ // Run the two transcriptions during a pause-all (workerPool.ts pauseHeld).
+ whilePaused?: boolean;
+ dryRun?: boolean;
+};
+
+type Check<T> = { ok: true; value: T } | { ok: false; error: string };
+
+const SEGMENT_RE = /^[a-z0-9][a-z0-9-]{0,31}$/i;
+const PROJECT_RE = /^[a-z0-9][a-z0-9-]{0,79}$/;
+
+/** The body's shape, judged without touching the disk. */
+export function parseFindClipsBody(body: Record<string, unknown>): Check<FindClipsRequest> {
+ const slug = body.slug;
+ if (typeof slug !== "string" || !isValidChannelSlug(slug)) {
+ return { ok: false, error: '"slug" is required: a channel slug' };
+ }
+ const id = body.id;
+ if (typeof id !== "string" || !isVideoIdSegment(id)) {
+ return { ok: false, error: '"id" is required: a video id (one path segment)' };
+ }
+ const out: FindClipsRequest = { slug, id };
+ if (body.target !== undefined) {
+ if (typeof body.target !== "number" || !Number.isFinite(body.target) || body.target < 10 || body.target > 6 * 3600) {
+ return { ok: false, error: '"target" is the cut\'s length in seconds (10 to 21600)' };
+ }
+ out.target = Math.round(body.target);
+ }
+ if (body.segment !== undefined) {
+ if (typeof body.segment !== "string" || !SEGMENT_RE.test(body.segment)) {
+ return { ok: false, error: '"segment" is a segment id umtool found ("s2")' };
+ }
+ out.segment = body.segment;
+ }
+ if (body.project !== undefined) {
+ if (typeof body.project !== "string" || !PROJECT_RE.test(body.project)) {
+ return { ok: false, error: '"project" is a umtool project slug (lowercase letters, digits and dashes)' };
+ }
+ out.project = body.project;
+ }
+ for (const key of ["whilePaused", "dryRun"] as const) {
+ const v = body[key];
+ if (v !== undefined && typeof v !== "boolean") return { ok: false, error: `"${key}" must be true or false` };
+ if (v === true) out[key] = true;
+ }
+ return { ok: true, value: out };
+}
+
+/** The umtool project slug a run makes when none is named: the id, lowercased, and the segment. */
+export function projectSlugFor(id: string, segment?: string): string {
+ const base = id.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "video";
+ return `${base}-clips${segment ? `-${segment.toLowerCase()}` : ""}`.slice(0, 80);
+}
+
+/** The umtool clip editor of `project`. */
+export function umtoolProjectUrl(umtool: string, project: string): string {
+ return `${umtool}/projects/${encodeURIComponent(project)}/clips`;
+}
+
+// ─── what is on disk ───
+
+export type FindClipsState = {
+ // A saved-video pointer, or a source container in the video dir.
+ saved: boolean;
+ // What the word timings read: the preferred audio file, else the source
+ // container, else the saved video. Null when there is nothing to read.
+ audioPath: string | null;
+ // The corpus transcript's file name, or null.
+ transcript: string | null;
+ // Words in words.json, or null when it is absent.
+ words: number | null;
+ chat: LiveChatPlan;
+ diarization: boolean;
+};
+
+export async function inspectFindClips(
+ paths: Paths,
+ slug: string,
+ id: string,
+ config: ChannelConfig,
+): Promise<FindClipsState> {
+ const videoDir = path.join(paths.channelsDir, slug, "data", id);
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ const pointer = await loadSavedVideo(videoDir).catch(() => null);
+ const container = findSourceMedia(entries);
+ const audio = pickPreferredAudio(entries.filter(isRealAudioFile));
+ let audioPath: string | null = audio ? path.join(videoDir, audio) : container ? path.join(videoDir, container) : null;
+ if (!audioPath && pointer) audioPath = await resolveSavedVideo(videoDir).catch(() => null);
+ const transcript = entries.includes(WHISPER_FILENAME) ? WHISPER_FILENAME : (englishVttsByPreference(entries)[0] ?? null);
+ const words = await loadWordTimings(videoDir).catch(() => null);
+ return {
+ saved: pointer !== null || container !== null,
+ audioPath,
+ transcript,
+ words: words ? words.words.length : null,
+ chat: await liveChatPlan(paths, slug, id, config),
+ diarization: entries.includes(DIARIZATION_FILENAME),
+ };
+}
+
+export type FindClipsPlanStep = { id: FindClipsStepId; label: string; run: boolean; why: string };
+
+/** What each step would do over `state` — the dry run, and the log's first lines. */
+export function planFindClipsSteps(state: FindClipsState, req: Pick<FindClipsRequest, "segment" | "target">): FindClipsPlanStep[] {
+ const step = (id: FindClipsStepId, run: boolean, why: string): FindClipsPlanStep => ({ id, label: FIND_CLIPS_STEP_LABELS[id], run, why });
+ const chat = state.chat;
+ return [
+ step("persist", !state.saved, state.saved ? "saved video present" : "no saved video: persist the source"),
+ step("transcript", state.transcript === null, state.transcript ? `${state.transcript} present` : "no corpus transcript: transcribe it"),
+ step("words", state.words === null, state.words !== null ? `words.json present (${state.words} words)` : "no words.json: transcribe with word timings"),
+ chat.kind === "fetch" || chat.kind === "normalize"
+ ? step("chat", true, chat.kind === "fetch" ? "no chat replay here: fetch it (YouTube)" : "the chat replay is here: normalize it")
+ : step(
+ "chat",
+ false,
+ chat.kind === "fresh"
+ ? "live_chat.cues.json present"
+ : chat.kind === "no-fetcher"
+ ? noChatFetcherSentence(chat.platform)
+ : chat.kind === "not-live"
+ ? "never live: no chat replay"
+ : chat.error,
+ ),
+ step("diarization", !state.diarization, state.diarization ? "diarization.json present" : "no diarization.json: diarize it"),
+ step("umtool", true, req.segment ? `find clips in segment ${req.segment}` : "find the segments and the clips"),
+ ];
+}
+
+// ─── the deps ───
+
+export type FindClipsDeps = {
+ paths: Paths;
+ // The editor's ops actions, in process (editor: _researchEditor.ts
+ // findClipsEditor). A refusal throws with the action's sentence.
+ editor: ResearchEditor;
+ // An editor job's state (researchRuns.ts jobOfPaths).
+ jobOf: (id: string) => Promise<{ status: string } | null>;
+ umtoolUrl?: string | null;
+ workerToken?: string;
+ fetch?: typeof fetch;
+ settings?: () => SiteSettings;
+ pool?: Pick<WorkerPool, "isPaused" | "enabledIds" | "pauseHeldIds">;
+ transcribeWords?: (
+ request: TranscribeFileRequest,
+ o: { onLog: (line: string) => void; signal: AbortSignal; ctx?: JobRunContext },
+ ) => Promise<TranscribeFileResult>;
+ diarize?: (o: BackfillChannelJobOptions) => Promise<StreamActionResult>;
+ // The one-video diarization in this job, for a held backfill lane and a
+ // whilePaused run (diarizeOne.ts diarizeOneVideo).
+ diarizeInline?: (o: { onLog: (line: string) => void; signal: AbortSignal }) => Promise<DiarizeOneOutcome>;
+ pollMs?: number;
+ // The pause before asking a busy umtool again (default 30 s).
+ busyWaitMs?: number;
+ sleep?: (ms: number) => Promise<void>;
+ now?: () => Date;
+ // Called inside the job after the record is written (the editor revalidates
+ // the video page here).
+ onDone?: () => void | Promise<void>;
+};
+
+const TERMINAL = new Set(["done", "failed", "cancelled"]);
+// How many times a busy umtool (409 naming its running job) is asked again,
+// `busyWaitMs` (30 s) apart: an hour.
+const UMTOOL_BUSY_TRIES = 120;
+
+class StepError extends Error {
+ constructor(step: FindClipsStepId, message: string) {
+ super(`step ${FIND_CLIPS_STEP_LABELS[step]}: ${message}`);
+ }
+}
+
+function sleeper(deps: FindClipsDeps): (ms: number) => Promise<void> {
+ return deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
+}
+
+async function waitForJob(
+ deps: FindClipsDeps,
+ step: FindClipsStepId,
+ jobId: string,
+ signal: AbortSignal,
+ onLog: (line: string) => void,
+): Promise<string> {
+ const sleep = sleeper(deps);
+ const pollMs = deps.pollMs ?? 2000;
+ let misses = 0;
+ let last = "";
+ for (;;) {
+ if (signal.aborted) throw new StepError(step, `cancelled while job ${jobId} ran (it keeps running)`);
+ const j = await deps.jobOf(jobId).catch(() => null);
+ if (j && TERMINAL.has(j.status)) return j.status;
+ if (!j && ++misses > 30) throw new StepError(step, `job ${jobId} is not in the registry`);
+ if (j && j.status !== last) {
+ last = j.status;
+ if (j.status === "queued") onLog(` job ${jobId} is queued behind other work on its queue`);
+ }
+ await sleep(pollMs);
+ }
+}
+
+// Why a transcription step would park forever right now; null when it runs.
+function transcriptionBlocked(deps: FindClipsDeps, whilePaused: boolean): string | null {
+ const pool = deps.pool ?? getWorkerPool();
+ if (pool.isPaused()) {
+ if (!whilePaused) {
+ return "the transcription workers are paused — run it with \"while paused\" (whilePaused: true), or resume them on /workers";
+ }
+ if (pool.pauseHeldIds().length === 0) {
+ return "the workers are paused and none was switched off by the pause alone (a worker drained, degraded or disabled by hand is never used) — enable one on /workers";
+ }
+ return null;
+ }
+ if (pool.enabledIds().length === 0) return "no transcription worker is enabled — enable one on /workers";
+ return null;
+}
+
+function jobIdsOf(body: Record<string, unknown>): string[] {
+ if (Array.isArray(body.jobIds)) return body.jobIds.filter((x): x is string => typeof x === "string");
+ return typeof body.jobId === "string" ? [body.jobId] : [];
+}
+
+// One ops action through the door, then every job it started, waited on.
+async function runAction(
+ deps: FindClipsDeps,
+ step: FindClipsStepId,
+ action: (typeof FIND_CLIPS_EDITOR_ACTIONS)[number],
+ args: Record<string, unknown>,
+ signal: AbortSignal,
+ onLog: (line: string) => void,
+): Promise<void> {
+ let body: Record<string, unknown>;
+ try {
+ body = await deps.editor.run(action, args);
+ } catch (e) {
+ throw new StepError(step, `${action} refused: ${(e as Error).message}`);
+ }
+ for (const jobId of jobIdsOf(body)) {
+ onLog(` ${action}: job ${jobId}`);
+ const status = await waitForJob(deps, step, jobId, signal, onLog);
+ if (status !== "done") throw new StepError(step, `${action} job ${jobId} ended ${status} — its log on /jobs says why`);
+ onLog(` ${action}: job ${jobId} done`);
+ }
+}
+
+// ─── umtool ───
+
+type UmtoolNew = {
+ jobId: string;
+ project: string;
+ created: boolean;
+ segments: FindClipsSegment[];
+ // The segment umtool chose (the one asked, else auto-scope's), and the
+ // clip editor's path ("/projects/<id>/clips").
+ segment?: string;
+ href?: string;
+};
+
+function segmentsOf(v: unknown): FindClipsSegment[] {
+ if (!Array.isArray(v)) return [];
+ return v
+ .filter((s): s is Record<string, unknown> => !!s && typeof s === "object")
+ .filter((s) => typeof s.id === "string" && typeof s.from === "number" && typeof s.to === "number")
+ .map((s) => ({
+ id: s.id as string,
+ from: s.from as number,
+ to: s.to as number,
+ ...(typeof s.subject === "number" || typeof s.subject === "string" ? { subject: s.subject } : {}),
+ ...(typeof s.host === "number" || typeof s.host === "string" ? { host: s.host } : {}),
+ ...(typeof s.why === "string" ? { why: s.why } : {}),
+ }));
+}
+
+async function umtoolJson(res: Response): Promise<Record<string, unknown>> {
+ try {
+ const j = (await res.json()) as unknown;
+ return j && typeof j === "object" && !Array.isArray(j) ? (j as Record<string, unknown>) : {};
+ } catch {
+ return {};
+ }
+}
+
+async function runUmtool(
+ deps: FindClipsDeps,
+ o: { umtool: string; token: string; body: Record<string, unknown>; signal: AbortSignal; onLog: (line: string) => void },
+): Promise<UmtoolNew & { state: string }> {
+ const doFetch = deps.fetch ?? fetch;
+ const endpoint = `${o.umtool}/api/report/clips`;
+ const headers = { authorization: `Bearer ${o.token}`, "content-type": "application/json" };
+ const sleep = sleeper(deps);
+ let res!: Response;
+ let posted: Record<string, unknown> = {};
+ // umtool runs one job at a time: a 409 that names the running job is a
+ // wait, not a refusal (the run is retried until umtool is free); any other
+ // 409 (the project's slug exists) is a refusal.
+ for (let tries = 0; ; tries++) {
+ try {
+ res = await doFetch(endpoint, { method: "POST", headers, body: JSON.stringify(o.body), signal: o.signal });
+ } catch (e) {
+ if (o.signal.aborted) throw new StepError("umtool", "cancelled");
+ throw new StepError("umtool", `umtool at ${o.umtool} did not answer (${(e as Error).message}) — is it running?`);
+ }
+ posted = await umtoolJson(res);
+ if (res.status !== 409 || !posted.running || tries >= UMTOOL_BUSY_TRIES) break;
+ if (tries === 0) o.onLog(`umtool is busy (${typeof posted.error === "string" ? posted.error : "a job is running"}); waiting for it`);
+ await sleep(deps.busyWaitMs ?? 30_000);
+ if (o.signal.aborted) throw new StepError("umtool", "cancelled while waiting for umtool");
+ }
+ if (!res.ok) {
+ const why = typeof posted.error === "string" ? posted.error : `HTTP ${res.status}`;
+ throw new StepError("umtool", `umtool refused the clips request (HTTP ${res.status}): ${why}`);
+ }
+ const job = posted.job as { id?: unknown } | undefined;
+ const jobId = typeof posted.jobId === "string" ? posted.jobId : typeof job?.id === "string" ? job.id : null;
+ const project = typeof posted.project === "string" ? posted.project : null;
+ if (!jobId || !project) throw new StepError("umtool", `umtool's answer named no job or project: ${JSON.stringify(posted).slice(0, 300)}`);
+ const created = posted.created !== false;
+ let segments = segmentsOf(posted.segments);
+ const segment = typeof posted.segment === "string" && posted.segment ? posted.segment : undefined;
+ const href = typeof posted.href === "string" && posted.href.startsWith("/") ? posted.href : undefined;
+ o.onLog(`umtool: ${created ? "made" : "re-analyzing"} project ${project}${segment ? ` (segment ${segment})` : ""} (job ${jobId})`);
+ if (Array.isArray(posted.notes)) {
+ for (const n of posted.notes) if (typeof n === "string" && n.trim()) o.onLog(`umtool: note: ${n}`);
+ }
+ if (segments.length) o.onLog(`umtool: segments ${segments.map((s) => `${s.id} ${Math.round(s.from)}–${Math.round(s.to)} s`).join(", ")}`);
+
+ const pollMs = deps.pollMs ?? 2000;
+ let since = 0;
+ let failures = 0;
+ for (;;) {
+ if (o.signal.aborted) {
+ await doFetch(`${endpoint}?cancel=${encodeURIComponent(jobId)}`, { method: "POST", headers }).catch(() => null);
+ throw new StepError("umtool", `cancelled; umtool job ${jobId} was asked to stop`);
+ }
+ let view: Record<string, unknown> | null = null;
+ try {
+ const r = await doFetch(`${endpoint}?job=${encodeURIComponent(jobId)}&since=${since}`, { headers, signal: o.signal });
+ if (r.status === 404) throw new StepError("umtool", `umtool no longer knows job ${jobId} (restarted?)`);
+ if (r.ok) view = await umtoolJson(r);
+ } catch (e) {
+ if (e instanceof StepError) throw e;
+ }
+ if (!view) {
+ if (++failures >= 15) throw new StepError("umtool", `umtool at ${o.umtool} stopped answering while job ${jobId} ran`);
+ } else {
+ failures = 0;
+ const log = Array.isArray(view.log) ? view.log.filter((l): l is string => typeof l === "string") : [];
+ for (const line of log) o.onLog(`umtool: ${line.replace(/\n$/, "")}`);
+ if (typeof view.next === "number") since = view.next;
+ else since += log.length;
+ if (Array.isArray(view.segments)) segments = segmentsOf(view.segments);
+ const state = typeof view.state === "string" ? view.state : "running";
+ if (state !== "running") {
+ if (state !== "done") {
+ const why = typeof view.error === "string" && view.error ? view.error : `the job ended ${state}`;
+ throw new StepError("umtool", `umtool job ${jobId} failed: ${why}`);
+ }
+ return { jobId, project, created, segments, state, ...(segment ? { segment } : {}), ...(href ? { href } : {}) };
+ }
+ }
+ await sleep(pollMs);
+ }
+}
+
+// ─── the chain ───
+
+export type FindClipsResult = Omit<FindClipsRecord, "version" | "at" | "jobId"> & { umtoolJob: string };
+
+export async function runFindClips(
+ req: FindClipsRequest,
+ deps: FindClipsDeps,
+ o: { config: ChannelConfig; onLog: (line: string) => void; signal: AbortSignal; ctx?: JobRunContext },
+): Promise<FindClipsResult> {
+ const { paths } = deps;
+ const { onLog, signal } = o;
+ const { slug, id } = req;
+ const videoDir = path.join(paths.channelsDir, slug, "data", id);
+ const whilePaused = req.whilePaused === true;
+ const settings = (deps.settings ?? getSettings)();
+ const umtool = deps.umtoolUrl === undefined ? resolveUmtoolUrl() : deps.umtoolUrl;
+ const token = deps.workerToken ?? getWorkerToken();
+ if (!umtool) throw new StepError("umtool", "UMTOOL_URL is not set on the editor");
+ if (!token) throw new StepError("umtool", "WORKER_TOKEN is not set on the editor");
+ const steps: FindClipsStepRecord[] = [];
+ const skip = (s: FindClipsStepId, why: string) => {
+ steps.push({ id: s, label: FIND_CLIPS_STEP_LABELS[s], action: "skipped", why });
+ onLog(`skipped: ${FIND_CLIPS_STEP_LABELS[s]} — ${why}`);
+ };
+ const running = (s: FindClipsStepId, why: string) => {
+ steps.push({ id: s, label: FIND_CLIPS_STEP_LABELS[s], action: "ran", why });
+ onLog(`running: ${FIND_CLIPS_STEP_LABELS[s]} — ${why}`);
+ };
+ const inspect = () => inspectFindClips(paths, slug, id, o.config);
+ onLog(`Find clips in ${slug}/${id}${req.segment ? ` (segment ${req.segment})` : ""}${whilePaused ? " — while paused" : ""}`);
+
+ // 1. the saved video
+ let state = await inspect();
+ if (state.saved) skip("persist", "saved video present");
+ else {
+ running("persist", "no saved video: persisting the source");
+ await runAction(deps, "persist", "persist-videos", { items: [{ slug, id }] }, signal, onLog);
+ state = await inspect();
+ if (!state.saved) throw new StepError("persist", "the source video is still not saved after persist-videos");
+ }
+
+ // 2. the corpus transcript
+ if (state.transcript) skip("transcript", `${state.transcript} present`);
+ else {
+ const held = transcriptionBlocked(deps, whilePaused);
+ if (held) throw new StepError("transcript", held);
+ running("transcript", "no corpus transcript: transcribing");
+ await runAction(deps, "transcript", "transcribe-one", { slug, id, ...(whilePaused ? { whilePaused: true } : {}) }, signal, onLog);
+ state = await inspect();
+ if (!state.transcript) throw new StepError("transcript", "transcribe-one ended without a transcript");
+ }
+
+ // 3. word timings
+ let wordsPath: string | null = null;
+ if (state.words !== null) {
+ skip("words", `words.json present (${state.words} words)`);
+ wordsPath = wordTimingsSidecar.path(videoDir);
+ } else {
+ if (!state.audioPath) throw new StepError("words", "no audio, source container or saved video to read");
+ const held = transcriptionBlocked(deps, whilePaused);
+ if (held) throw new StepError("words", held);
+ running("words", `transcribing ${path.basename(state.audioPath)} with word timings`);
+ const transcribe =
+ deps.transcribeWords ??
+ ((request, t) => runTranscribeFile({ paths, request, onLog: t.onLog, signal: t.signal, ...(t.ctx ? { ctx: t.ctx } : {}) }));
+ let r: TranscribeFileResult;
+ try {
+ r = await transcribe(
+ { path: state.audioPath, words: true, ...(whilePaused ? { whilePaused: true } : {}) },
+ { onLog, signal, ...(o.ctx ? { ctx: o.ctx } : {}) },
+ );
+ } catch (e) {
+ throw new StepError("words", (e as Error).message);
+ }
+ const words = r.words ?? [];
+ if (words.length === 0) {
+ onLog(` ${r.worker.appId} [${r.worker.id}] keeps no word timestamps: the clips' edges sit on the transcript's cues`);
+ } else {
+ const { cues: _cues, text: _text, ...rest } = r;
+ const record: WordTimingsRecord = { ...rest, words } as WordTimingsRecord;
+ await writeWordTimings(videoDir, record);
+ wordsPath = wordTimingsSidecar.path(videoDir);
+ onLog(` ${words.length} words → words.json (${r.worker.appId} [${r.worker.id}])`);
+ }
+ }
+
+ // 4. the chat replay (a signal, never a requirement)
+ const chat = state.chat;
+ if (chat.kind === "fetch" || chat.kind === "normalize") {
+ running("chat", chat.kind === "fetch" ? "fetching the chat replay (YouTube, paced)" : "normalizing the chat replay on disk");
+ try {
+ await runAction(deps, "chat", "fetch-chat", { slug, id }, signal, onLog);
+ } catch (e) {
+ if (signal.aborted) throw e;
+ onLog(` the chat was not fetched (${(e as Error).message}) — going on without it`);
+ }
+ } else {
+ skip(
+ "chat",
+ chat.kind === "fresh"
+ ? "live_chat.cues.json present"
+ : chat.kind === "no-fetcher"
+ ? noChatFetcherSentence(chat.platform)
+ : chat.kind === "not-live"
+ ? "never live: no chat replay"
+ : chat.error,
+ );
+ }
+
+ // 5. diarization
+ if (state.diarization) skip("diarization", "diarization.json present");
+ else {
+ if (!backfillLaneOperations(settings).some((op) => op.id === DIARIZATION_OPERATION_ID)) {
+ throw new StepError("diarization", "diarization is switched off, or its models are not set — set it up on /operations/diarization");
+ }
+ const laneHeld = isGateHeld(settings, "backfill");
+ if (laneHeld && !whilePaused) {
+ throw new StepError(
+ "diarization",
+ "the backfill lane is held, and it holds a diarization run too — run Find clips \"while paused\" (whilePaused: true) to diarize this one video in this job, or lift the hold",
+ );
+ }
+ if (laneHeld) {
+ // PAST THE HOLD, for this one video: the one-video diarization in this
+ // job (diarizeOne.ts — what a transcription's inline pass runs), the
+ // lane's hold left on.
+ running("diarization", "no diarization.json: diarizing this one video in this job (the backfill lane stays held)");
+ const diarizeInline =
+ deps.diarizeInline ??
+ ((d: { onLog: (l: string) => void; signal: AbortSignal }) =>
+ diarizeOneVideo({ paths, videoDir, videoId: id, settings: settings.diarization, onLog: d.onLog, signal: d.signal }));
+ const outcome = await diarizeInline({ onLog, signal });
+ if (outcome !== "diarized" && outcome !== "already-exists") {
+ throw new StepError("diarization", `the one-video diarization ended "${outcome}"`);
+ }
+ } else {
+ running("diarization", "no diarization.json: diarizing (the backfill lane's one-video run)");
+ const diarize = deps.diarize ?? runBackfillChannelJob;
+ const started = await diarize({ paths, channelSlug: slug, kindIds: [DIARIZATION_OPERATION_ID], ids: [id] });
+ if (!started.ok) throw new StepError("diarization", started.error);
+ void started.stream.cancel();
+ onLog(` backfill-channel: job ${started.jobId}`);
+ const done = await started.done;
+ if (done.status !== "done") throw new StepError("diarization", `job ${started.jobId} ended ${done.status}`);
+ }
+ state = await inspect();
+ if (!state.diarization) throw new StepError("diarization", "no diarization.json was written — the log above says why");
+ }
+
+ // 6. umtool
+ const project = req.project ?? projectSlugFor(id, req.segment);
+ running("umtool", req.segment ? `finding clips in segment ${req.segment}` : "finding the segments and the clips");
+ const u = await runUmtool(deps, {
+ umtool,
+ token,
+ signal,
+ onLog,
+ body: {
+ mode: "new",
+ slug: project,
+ from: `${slug}/${id}`,
+ ...(req.target !== undefined ? { target: req.target } : {}),
+ ...(req.segment ? { segment: req.segment } : { scope: "auto" }),
+ ...(wordsPath ? { wordsPath } : {}),
+ },
+ });
+ return {
+ project: u.project,
+ url: u.href ? `${umtool}${u.href}` : umtoolProjectUrl(umtool, u.project),
+ created: u.created,
+ ...(req.segment ?? u.segment ? { segment: req.segment ?? u.segment } : {}),
+ segments: u.segments,
+ steps,
+ umtoolJob: u.jobId,
+ };
+}
+
+// ─── the job ───
+
+export type FindClipsPlan = {
+ slug: string;
+ id: string;
+ umtoolUrl: string | null;
+ workersPaused: boolean;
+ steps: FindClipsPlanStep[];
+};
+
+export type FindClipsEnqueued =
+ | { dryRun: true; plan: FindClipsPlan }
+ | { dryRun: false; result: StreamActionResult };
+
+/** Validate; a dry run's plan; else the job. Every refusal is `{ok: false}` before a job exists. */
+export async function enqueueFindClips(body: Record<string, unknown>, deps: FindClipsDeps): Promise<FindClipsEnqueued> {
+ const refuse = (error: string): FindClipsEnqueued => ({ dryRun: false, result: { ok: false, error } });
+ const parsed = parseFindClipsBody(body);
+ if (!parsed.ok) return refuse(parsed.error);
+ const req = parsed.value;
+ const { paths } = deps;
+ const config = await readChannelConfig(paths, req.slug);
+ if (!config) return refuse(`Channel "${req.slug}" not found`);
+ try {
+ await assertChannelTextReadable(paths, req.slug, config);
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+ const videoDir = path.join(paths.channelsDir, req.slug, "data", req.id);
+ if (!(await stat(videoDir).then((s) => s.isDirectory(), () => false))) {
+ return refuse(`"${req.id}" is not a video of ${req.slug} (no data/${req.id}/): import or sync it first`);
+ }
+ const state = await inspectFindClips(paths, req.slug, req.id, config);
+ const umtool = deps.umtoolUrl === undefined ? resolveUmtoolUrl() : deps.umtoolUrl;
+ const pool = deps.pool ?? getWorkerPool();
+ if (req.dryRun) {
+ return {
+ dryRun: true,
+ plan: { slug: req.slug, id: req.id, umtoolUrl: umtool, workersPaused: pool.isPaused(), steps: planFindClipsSteps(state, req) },
+ };
+ }
+ if (!umtool) return refuse("UMTOOL_URL is not set on the editor: Find clips hands the recording to umtool's clip finder (e.g. UMTOOL_URL=http://localhost:3050)");
+ if (!(deps.workerToken ?? getWorkerToken())) return refuse("WORKER_TOKEN is not set on the editor: umtool's clips route is asked with it");
+ const now = deps.now ?? (() => new Date());
+ return {
+ dryRun: false,
+ result: await runManagedFunction({
+ kind: FIND_CLIPS_JOB_KIND,
+ queueKey: FIND_CLIPS_QUEUE,
+ paths,
+ channelSlug: req.slug,
+ videoId: req.id,
+ fn: async (onLog, signal, _setProgress, ctx) => {
+ const r = await runFindClips(req, { ...deps, umtoolUrl: umtool }, { config, onLog, signal, ctx });
+ const { umtoolJob: _u, ...kept } = r;
+ const record: FindClipsRecord = { version: 1, at: now().toISOString(), jobId: ctx.jobId, ...kept };
+ await writeFindClipsRecord(path.join(paths.channelsDir, req.slug, "data", req.id), record);
+ onLog(`Done: ${r.segments.length} segment(s); the clips are in ${r.url}`);
+ onLog(`${FIND_CLIPS_RESULT_MARKER}${JSON.stringify({ ...record, umtoolJob: r.umtoolJob })}`);
+ await deps.onDone?.();
+ },
+ }),
+ };
+}
diff --git a/common/controller/transcribeFile.test.ts b/common/controller/transcribeFile.test.ts
@@ -552,3 +552,41 @@ test("a short file goes ahead of parked transcriptions — the lane's and a manu
// before it got it after, in their own order (manual before the lane).
assert.deepEqual(order, ["batch after the file", "lane after the file"]);
});
+
+// --- run while paused (release 36, lane A) -------------------------------------
+
+test("whilePaused is a boolean, kept only when true", () => {
+ const parsed = (b: Record<string, unknown>) => parseTranscribeFileBody({ path: MEDIA, ...b });
+ assert.match((parsed({ whilePaused: 1 }) as { error: string }).error, /"whilePaused" must be true or false/);
+ const on = parsed({ whilePaused: true });
+ assert.ok(on.ok && on.value.whilePaused === true);
+ const off = parsed({ whilePaused: false });
+ assert.ok(off.ok && !("whilePaused" in off.value));
+});
+
+test("a named worker the pause alone switched off is not refused when the request runs whilePaused", async () => {
+ const workerStates = new Map([
+ ["gpu", { state: "disabled", degraded: false }],
+ ["cpu", { state: "disabled", degraded: false }],
+ ]);
+ const pauseHeldIds = new Set(["gpu"]);
+ assert.equal(await check({ workerId: "gpu", whilePaused: true }, { workerStates, pauseHeldIds }), null);
+ assert.match((await check({ workerId: "gpu" }, { workerStates, pauseHeldIds }))!, /"gpu" is disabled/);
+ // cpu was switched off by hand: never a pause-held worker.
+ assert.match((await check({ workerId: "cpu", whilePaused: true }, { workerStates, pauseHeldIds }))!, /"cpu" is disabled/);
+});
+
+test("a paused pool runs a whilePaused file job on a pause-held worker and stays paused", async () => {
+ const pool = getWorkerPool();
+ pool.pauseAll();
+ try {
+ const run = await runJob({ path: MEDIA, workerId: "gpu", whilePaused: true });
+ assert.equal(run.status, "done", run.log);
+ assert.equal(run.result.worker.id, "gpu");
+ assert.match(run.log, /The workers are paused: this one transcription may run on a worker the pause holds/);
+ assert.ok(pool.isPaused(), "the pause stays on");
+ assert.equal(pool.summary().find((w) => w.id === "gpu")?.state, "disabled");
+ } finally {
+ pool.resumeAll();
+ }
+});
diff --git a/common/controller/transcribeFile.ts b/common/controller/transcribeFile.ts
@@ -76,6 +76,7 @@ export const TRANSCRIBE_FILE_BODY_KEYS = [
"workerId",
"out",
"words",
+ "whilePaused",
] as const;
const AUDIO_NAME = "audio.wav";
@@ -113,6 +114,10 @@ export type TranscribeFileRequest = {
// True returns the engine's word timestamps as well as the cues. Only an
// engine that keeps them (parakeet) answers with any; the rest give none.
words?: boolean;
+ // True runs it during a pause-all on a worker the pause alone switched off
+ // (release 36, lane A; the pool's acquire `whilePaused`). Outside a pause it
+ // changes nothing.
+ whilePaused?: boolean;
};
// One word as the engine timed it, on the source file's clock (seconds).
@@ -196,6 +201,10 @@ export function parseTranscribeFileBody(
if (words !== undefined && typeof words !== "boolean") {
return { ok: false, error: '"words" must be true or false' };
}
+ const whilePaused = body.whilePaused;
+ if (whilePaused !== undefined && typeof whilePaused !== "boolean") {
+ return { ok: false, error: '"whilePaused" must be true or false' };
+ }
return {
ok: true,
value: {
@@ -205,6 +214,7 @@ export function parseTranscribeFileBody(
...(typeof workerId === "string" ? { workerId: workerId.trim() } : {}),
...(typeof out === "string" ? { out: path.resolve(out) } : {}),
...(words === true ? { words: true } : {}),
+ ...(whilePaused === true ? { whilePaused: true } : {}),
},
};
}
@@ -301,6 +311,9 @@ export type TranscribeFileContext = {
// The pool's runtime view (id → state). A named worker switched off on the
// Workers page is refused rather than waited for: the wait would be forever.
workerStates?: ReadonlyMap<string, { state: string; degraded: boolean }>;
+ // The workers the pause-all ALONE switched off (the pool's pauseHeldIds): a
+ // named one is not refused when the request runs `whilePaused`.
+ pauseHeldIds?: ReadonlySet<string>;
};
export async function checkTranscribeFileRequest(
@@ -369,7 +382,8 @@ export async function checkTranscribeFileRequest(
};
}
const runtime = ctx.workerStates?.get(req.workerId);
- if (runtime && (runtime.state !== "enabled" || runtime.degraded)) {
+ const heldByPause = req.whilePaused === true && ctx.pauseHeldIds?.has(req.workerId) === true;
+ if (runtime && !heldByPause && (runtime.state !== "enabled" || runtime.degraded)) {
return {
ok: false,
error: `worker "${req.workerId}" is ${
@@ -522,6 +536,7 @@ export async function runTranscribeFile(
},
skipInlineDiarization: true,
...(req.words ? { words: true } : {}),
+ ...(req.whilePaused ? { whilePaused: true } : {}),
});
const finished = Date.now();
const worker = used.worker;
@@ -573,6 +588,7 @@ export async function enqueueTranscribeFile(
workers: settings.workers,
locations: settings.storage?.locations ?? [],
workerStates,
+ pauseHeldIds: new Set(pool.pauseHeldIds()),
});
if (!checked.ok) return checked;
const req = checked.value;
diff --git a/common/controller/transcribeOne.ts b/common/controller/transcribeOne.ts
@@ -589,6 +589,10 @@ export type TranscribeWithWorkerOptions = {
words?: boolean;
// See TranscribeOneOptions.salvage.
salvage?: boolean;
+ // RUN WHILE PAUSED (release 36, lane A): during a pause-all, this one manual
+ // transcription may take a worker the pause alone switched off (the pool's
+ // acquire `whilePaused`). Never passed by a lane or batch.
+ whilePaused?: boolean;
};
// Acquire a worker from the global pool and transcribe one video through it,
@@ -607,6 +611,9 @@ export async function transcribeWithWorker(
opts.signal && opts.drainSignal
? AbortSignal.any([opts.signal, opts.drainSignal])
: (opts.signal ?? opts.drainSignal);
+ if (opts.whilePaused && pool.isPaused()) {
+ log("The workers are paused: this one transcription may run on a worker the pause holds (whilePaused); the pause stays on.");
+ }
let lastErr: unknown;
for (let attempt = 0; attempt < MAX_WORKER_ATTEMPTS; attempt++) {
if (opts.signal?.aborted || opts.drainSignal?.aborted) throw abortError();
@@ -616,6 +623,7 @@ export async function transcribeWithWorker(
background: opts.background,
...(opts.tier ? { tier: opts.tier } : {}),
...(opts.only ? { only: opts.only } : {}),
+ ...(opts.whilePaused ? { whilePaused: true } : {}),
});
} catch (err) {
// An `only` no configured worker passes is refused at once — that is
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -681,6 +681,40 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
needsMedia: false,
needsText: true,
},
+ // ONE VIDEO'S LIVE CHAT REPLAY (release 36 lane A, controller/
+ // fetchLiveChat.ts — `pnpm ops fetch-chat`, and the find-clips job's chat
+ // step): the chat-only yt-dlp pass, then live_chat.cues.json. On the
+ // platform download queue, paced and cookie-aware like the metadata
+ // refresh. `needsMedia`: it WRITES the raw replay, a tierable big file the
+ // normalizer moves into media/. An ingest kind: the index reads the cues.
+ // Not replayable: a retry is the same ops call, which re-asks the plan.
+ "fetch-chat": {
+ kind: "fetch-chat",
+ label: "Fetch live chat",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "platform",
+ needsMedia: true,
+ },
+ // FIND CLIPS (release 36 lane A, controller/findClips.ts — the video page's
+ // Find clips, `pnpm ops find-clips`): the clip finder's chain for one video,
+ // each step skipped when its output exists — persist the source, the corpus
+ // transcript, word timings, the chat replay, diarization — then umtool's
+ // `POST /api/report/clips {mode: "new"}`, followed to the end. Its steps
+ // are jobs of their own (persist-videos, transcribe-one, fetch-chat,
+ // backfill-channel) on their own queues, waited on from here; the word
+ // timings run in this job on a worker lease. Its own queue (`find-clips`),
+ // so it never holds a queue its steps need. `needsMedia`: the word timings
+ // read the audio. Not replayable: the button asks again, and the steps
+ // already done are skipped.
+ "find-clips": {
+ kind: "find-clips",
+ label: "Find clips",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ needsMedia: true,
+ },
// An Odysee video's record (or the channel's listing) read from its page in
// a headless browser (release 32 R9, controller/browserLookupJob.ts), when
// yt-dlp's lookup is refused. On the platform download queue, so it never
@@ -1243,6 +1277,9 @@ const INGEST_KINDS: ReadonlySet<string> = new Set([
"prepare-playable",
// A gone video's audio from a copy, and the copy's provenance (release 31).
"fetch-copies",
+ // One video's live chat replay, normalized into the cues the index reads
+ // (release 36 lane A).
+ "fetch-chat",
]);
export function isIngestKind(kind: string | undefined): boolean {
diff --git a/common/jobs/workerPool.ts b/common/jobs/workerPool.ts
@@ -73,6 +73,10 @@ export type WorkerSummary = {
// GPU worker beside two explicitly CPU-pinned ones, and treating those as GPU
// contention stopped the digest lane dead for work that used no shaders at all.
device?: string;
+ // During a pause-all: this worker was switched off by the pause ALONE, so a
+ // `whilePaused` acquire may take it (release 36 lane A; see pauseHeld).
+ // Absent outside a pause and for every other worker.
+ pauseHeld?: true;
};
type PoolEntry = {
@@ -104,6 +108,9 @@ type Waiter = {
// A further restriction on WHICH worker may serve this waiter (acquire's
// opts.only). Matched alongside `requires`, never instead of it.
only?: WorkerFilter;
+ // acquire's opts.whilePaused: during a pause-all this waiter may also be
+ // served by a worker the pause alone switched off (see pauseHeld).
+ whilePaused?: boolean;
};
// Narrows an acquire to particular workers — by id, by kind — on top of the
@@ -324,13 +331,43 @@ export class WorkerPool {
return this.pausedSnapshot !== null;
}
+ // RUN WHILE PAUSED (release 36, lane A): a worker the pause-all ALONE
+ // switched off — the pool is paused, the worker is disabled, and the state
+ // the pause recorded for it is `enabled`. Such a worker may serve ONE manual
+ // acquire that asked with `whilePaused` (the video page's "Transcribe now
+ // (workers paused)", the find-clips job). Never a worker drained, degraded
+ // or turned off by hand: those record `disabled` in the snapshot (the
+ // runtime controls' syncSnapshot), or a degrade mark the eligibility check
+ // refuses on its own. The snapshot is only READ here: the lease leaves the
+ // worker `disabled`, so when it releases the worker is still paused, and
+ // resumeAll restores it exactly as before.
+ private pauseHeld(id: string, entry: PoolEntry): boolean {
+ return (
+ this.pausedSnapshot !== null &&
+ entry.state === "disabled" &&
+ this.pausedSnapshot.get(id) === "enabled"
+ );
+ }
+
+ // The ids of every worker pauseHeld would lease to a whilePaused acquire
+ // right now (busy or not) — what a refusal of a named worker asks, and what
+ // the page asks before it offers "Transcribe now (workers paused)".
+ pauseHeldIds(): string[] {
+ this.ensureInit();
+ return Array.from(this.entries.entries())
+ .filter(([id, e]) => this.pauseHeld(id, e) && !e.degraded)
+ .map(([id]) => id);
+ }
+
private eligible(
entry: PoolEntry,
requires?: readonly string[],
only?: WorkerFilter,
+ whilePaused?: boolean,
): boolean {
return (
- entry.state === "enabled" &&
+ (entry.state === "enabled" ||
+ (whilePaused === true && this.pauseHeld(entry.config.id, entry))) &&
!entry.degraded &&
!entry.busy &&
workerMatches(entry.config, requires) &&
@@ -343,10 +380,11 @@ export class WorkerPool {
private pickFree(
requires?: readonly string[],
only?: WorkerFilter,
+ whilePaused?: boolean,
): PoolEntry | null {
let best: PoolEntry | null = null;
for (const entry of this.entries.values()) {
- if (!this.eligible(entry, requires, only)) continue;
+ if (!this.eligible(entry, requires, only, whilePaused)) continue;
if (!best || entry.config.priority < best.config.priority) best = entry;
}
return best;
@@ -381,7 +419,7 @@ export class WorkerPool {
let granted = false;
for (let i = 0; i < this.waiters.length; i++) {
const waiter = this.waiters[i];
- const entry = this.pickFree(waiter.requires, waiter.only);
+ const entry = this.pickFree(waiter.requires, waiter.only, waiter.whilePaused);
if (!entry) continue;
this.waiters.splice(i, 1);
waiter.onAbort?.();
@@ -423,6 +461,9 @@ export class WorkerPool {
// caller should treat the work as unrunnable rather than wedge.
// opts.only narrows the lease further, to the workers the filter accepts (see
// WorkerFilter); a filter no configured worker passes rejects the same way.
+ // opts.whilePaused lets a MANUAL acquire run during a pause-all on a worker
+ // the pause alone switched off (see pauseHeld); outside a pause it changes
+ // nothing. Background (lane) acquires never pass it.
acquire(
signal?: AbortSignal,
opts?: {
@@ -430,6 +471,7 @@ export class WorkerPool {
background?: boolean;
requires?: readonly string[];
only?: WorkerFilter;
+ whilePaused?: boolean;
},
): Promise<Lease> {
this.ensureInit();
@@ -459,14 +501,22 @@ export class WorkerPool {
);
}
}
- const entry = this.pickFree(requires, only);
+ const whilePaused = opts?.whilePaused === true;
+ const entry = this.pickFree(requires, only, whilePaused);
if (entry && this.waiters.length === 0) {
return Promise.resolve(this.grant(entry));
}
const tier: SchedulerTier =
opts?.tier ?? (opts?.background ? "background" : "foreground");
return new Promise<Lease>((resolve, reject) => {
- const waiter: Waiter = { resolve, reject, tier, requires, only };
+ const waiter: Waiter = {
+ resolve,
+ reject,
+ tier,
+ requires,
+ only,
+ ...(whilePaused ? { whilePaused: true } : {}),
+ };
if (signal) {
const onAbort = () => {
const idx = this.waiters.indexOf(waiter);
@@ -701,6 +751,7 @@ export class WorkerPool {
? { tags: [...e.config.tags] }
: {}),
device: e.config.config?.device,
+ ...(this.pauseHeld(e.config.id, e) && !e.degraded ? { pauseHeld: true as const } : {}),
}))
.sort((a, b) => a.priority - b.priority || a.id.localeCompare(b.id));
}
diff --git a/common/jobs/workerPool.whilePaused.test.ts b/common/jobs/workerPool.whilePaused.test.ts
@@ -0,0 +1,143 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import type { Worker } from "../lib/workers";
+import { WorkerPool, type Lease } from "./workerPool";
+
+// RUN WHILE PAUSED (release 36, lane A): a manual acquire with `whilePaused`
+// may take a worker the pause-all alone switched off — never one drained,
+// degraded or disabled by hand — and the pause's snapshot is never touched.
+//
+// Each test builds a fresh pool seeded with reconfigure(…, {applyEnabled}),
+// as workerPool.test.ts does, so settings.json is never read.
+
+function worker(id: string, priority = 0, enabled = true): Worker {
+ return { id, name: id, kind: "local", enabled, priority };
+}
+
+function snapshotOf(pool: WorkerPool): string {
+ const snap = (pool as unknown as { pausedSnapshot: Map<string, string> | null }).pausedSnapshot;
+ return JSON.stringify(snap ? [...snap.entries()] : null);
+}
+
+function stateOf(pool: WorkerPool, id: string) {
+ const w = pool.summary().find((s) => s.id === id);
+ assert.ok(w, id);
+ return { state: w.state, busy: w.busy, degraded: w.degraded };
+}
+
+// Settles a promise race: the lease if it resolved within a tick, else null.
+async function settledWithin<T>(p: Promise<T>, ms = 20): Promise<T | null> {
+ return Promise.race([p, new Promise<null>((r) => setTimeout(() => r(null), ms))]);
+}
+
+test("a paused pool + whilePaused leases a pause-disabled worker; the snapshot is untouched", async () => {
+ const pool = new WorkerPool();
+ pool.reconfigure([worker("gpu", 0), worker("cpu", 1)], { applyEnabled: true });
+ pool.pauseAll();
+ const before = snapshotOf(pool);
+ assert.deepEqual(pool.pauseHeldIds().sort(), ["cpu", "gpu"]);
+ assert.deepEqual(pool.summary().map((w) => [w.id, w.pauseHeld ?? false]), [["gpu", true], ["cpu", true]]);
+
+ const lease = (await settledWithin(pool.acquire(undefined, { whilePaused: true }))) as Lease | null;
+ assert.ok(lease, "granted at once");
+ assert.equal(lease.worker.id, "gpu", "the highest-priority pause-held worker");
+ // Still disabled by the pause while it runs: it never left the paused set.
+ assert.deepEqual(stateOf(pool, "gpu"), { state: "disabled", busy: true, degraded: false });
+ assert.equal(snapshotOf(pool), before);
+
+ lease.release();
+ assert.deepEqual(stateOf(pool, "gpu"), { state: "disabled", busy: false, degraded: false });
+ assert.equal(snapshotOf(pool), before, "byte-equal after the job");
+ assert.ok(pool.isPaused());
+
+ // And the pause lifts exactly as it would have.
+ pool.resumeAll();
+ assert.equal(stateOf(pool, "gpu").state, "enabled");
+ assert.equal(stateOf(pool, "cpu").state, "enabled");
+});
+
+test("a worker disabled by hand before the pause is never leased while paused", async () => {
+ const pool = new WorkerPool();
+ pool.reconfigure([worker("gpu", 0), worker("cpu", 1)], { applyEnabled: true });
+ pool.disableWorker("gpu"); // by hand, before the pause
+ pool.pauseAll();
+ assert.deepEqual(pool.pauseHeldIds(), ["cpu"]);
+ const lease = (await settledWithin(pool.acquire(undefined, { whilePaused: true }))) as Lease | null;
+ assert.ok(lease);
+ assert.equal(lease.worker.id, "cpu");
+ lease.release();
+});
+
+test("hand-disabled, drained or degraded workers are never leased, even with the flag", async () => {
+ const pool = new WorkerPool();
+ pool.reconfigure([worker("a", 0), worker("b", 1), worker("c", 2), worker("off", 3, false)], {
+ applyEnabled: true,
+ });
+ pool.pauseAll();
+ pool.disableWorker("a"); // by hand DURING the pause: the snapshot says disabled
+ pool.drainWorker("b"); // drained during the pause
+ pool.markDegraded("c");
+ const before = snapshotOf(pool);
+ assert.deepEqual(pool.pauseHeldIds(), [], "'off' was disabled in settings, not by the pause");
+ assert.ok(pool.summary().every((w) => !("pauseHeld" in w)), "the summary marks none");
+
+ const ac = new AbortController();
+ const p = pool.acquire(ac.signal, { whilePaused: true });
+ assert.equal(await settledWithin(p), null, "parks: nothing it may take");
+ ac.abort();
+ await assert.rejects(p, { name: "AbortError" });
+ assert.equal(snapshotOf(pool), before);
+});
+
+test("without the flag a paused pool holds the acquire, as today", async () => {
+ const pool = new WorkerPool();
+ pool.reconfigure([worker("gpu", 0)], { applyEnabled: true });
+ pool.pauseAll();
+ const before = snapshotOf(pool);
+ const held = pool.acquire();
+ const heldBg = pool.acquire(undefined, { background: true });
+ assert.equal(await settledWithin(held), null);
+ assert.equal(await settledWithin(heldBg), null);
+
+ // A whilePaused acquire arriving later is served — the held ones stay parked.
+ const lease = (await settledWithin(pool.acquire(undefined, { whilePaused: true }))) as Lease | null;
+ assert.ok(lease, "the flagged acquire runs past the held ones");
+ lease.release();
+ assert.equal(await settledWithin(held), null, "still held after the flagged job ended");
+ assert.equal(await settledWithin(heldBg), null);
+ assert.equal(snapshotOf(pool), before);
+
+ // Resume releases the held ones in tier order.
+ pool.resumeAll();
+ const l1 = (await held) as Lease;
+ l1.release();
+ const l2 = (await heldBg) as Lease;
+ l2.release();
+});
+
+test("a parked whilePaused waiter takes the pause-held worker when its lease frees", async () => {
+ const pool = new WorkerPool();
+ pool.reconfigure([worker("gpu", 0)], { applyEnabled: true });
+ pool.pauseAll();
+ const first = (await pool.acquire(undefined, { whilePaused: true })) as Lease;
+ const second = pool.acquire(undefined, { whilePaused: true });
+ const bg = pool.acquire(undefined, { background: true });
+ assert.equal(await settledWithin(second), null, "one slot");
+ first.release();
+ const l2 = (await settledWithin(second)) as Lease | null;
+ assert.ok(l2, "the flagged waiter, not the background one");
+ l2.release();
+ assert.equal(await settledWithin(bg), null, "the lane stays held");
+ pool.resumeAll();
+ ((await bg) as Lease).release();
+});
+
+test("outside a pause the flag changes nothing", async () => {
+ const pool = new WorkerPool();
+ pool.reconfigure([worker("gpu", 0), worker("cpu", 1)], { applyEnabled: true });
+ pool.disableWorker("gpu");
+ assert.deepEqual(pool.pauseHeldIds(), []);
+ const lease = (await pool.acquire(undefined, { whilePaused: true })) as Lease;
+ assert.equal(lease.worker.id, "cpu", "a hand-disabled worker stays off");
+ lease.release();
+});
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -126,7 +126,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "UMTOOL_MEDIA_DIR", audience: "runtime", default: "unset (no media root: a project link's target is kept)", readBy: "common/lib/report/delete.ts, umtool (lib/paths.mjs)", doc: "umtool's media root, where a tiered project's `out/` (and its deliverables) are linked to. Read by `archilyzer reports delete` and the editor's `delete-article` / `delete-iteration` too: an iteration project's link that is exactly its mirror there is removed with its target. Its other uses are documented in [umtool/docs](umtool/docs/README.md)." },
{ name: "REPORTS_DIR", audience: "runtime", default: "`~/reports` (or the parent of `SONG_REPORTS_DIR`)", readBy: "common/lib/report/delete.ts, umtool (lib/paths.mjs)", doc: "umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete." },
{ name: "SONG_REPORTS_DIR", audience: "runtime", default: "unset", readBy: "common/lib/report/delete.ts, umtool (song/paths.mjs)", doc: "umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete reads (as umtool does)." },
- { name: "UMTOOL_URL", audience: "runtime", default: "unset (no link; the MCP's `notes` off)", readBy: "editor/app/channels/[slug]/videos/[id]/page.tsx, mcp/src/archivalTools.ts", doc: "umtool's front door; when set, the video page links to it, and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`)." },
+ { name: "UMTOOL_URL", audience: "runtime", default: "unset (no link; the MCP's `notes` off)", readBy: "editor/app/channels/[slug]/videos/[id]/page.tsx, common/lib/umtoolUrl.ts, mcp/src/archivalTools.ts", doc: "umtool's front door; when set, the video page links to it, its Find clips hands the recording to umtool's clip finder (the `find-clips` job posts to `/api/report/clips` with WORKER_TOKEN), and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). Unset: Find clips is disabled." },
{ name: "TRANSCRIPT_SITE_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: one published archive to read over HTTP." },
{ name: "TRANSCRIPT_HUB_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a hub, federating every archive it lists." },
{ name: "TRANSCRIPT_LOCAL_DIR", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a composed public dir on disk." },
@@ -230,6 +230,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "E2E_BACKOFF_BASE_MS", audience: "test", default: "`60000` (the real base)", readBy: "common/jobs/platformBackoff.ts", doc: "The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse." },
{ name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts", doc: "The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." },
{ name: "E2E_ODYSEE_PAGE_FIXTURE", audience: "test", default: "unset (a headless browser)", readBy: "common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts", doc: "A JSON file of recorded Odysee page reads keyed by page URL (`\"*\"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`)." },
+ { name: "E2E_UMTOOL_ORIGIN_FILE", audience: "test", default: "unset (UMTOOL_URL)", readBy: "common/lib/umtoolUrl.ts", doc: "A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored." },
{ name: "E2E_BLUESKY_ORIGIN_FILE", audience: "test", default: "unset (the real Bluesky)", readBy: "common/social/blueskyEndpoints.ts", doc: "A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored." },
{ name: "E2E_AUDIO_CHECK_DEBUG_PAUSE_MS", audience: "test", default: "off", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "A debugging pause inside the audio check." },
{ name: "E2E_FAKE_YTDLP_AUDIO_CHECK_MODE", audience: "test", default: "—", readBy: "editor/e2e/fixtures/bin/fake-ytdlp.mjs", doc: "Fake yt-dlp: which audio-check scenario to act out." },
diff --git a/common/lib/findClipsRecord-server.ts b/common/lib/findClipsRecord-server.ts
@@ -0,0 +1,56 @@
+// WHAT THE LAST "FIND CLIPS" FOUND — `data/<id>/find-clips.json` (release 36,
+// lane A). Written by the find-clips job when umtool's clip finder finished
+// (controller/findClips.ts); read by the video page's Find clips panel, which
+// links the umtool project and lists the narrated-video segments umtool found,
+// each with its own "Find clips in this part". Overwritten by the next run
+// (the newest run is the one the panel describes; a per-segment run names its
+// segment). A small text sidecar on the corpus disk; never published.
+
+import { sidecar, sidecarField } from "./sidecar-server";
+
+export const FIND_CLIPS_FILENAME = "find-clips.json";
+
+export type FindClipsSegment = {
+ id: string;
+ from: number;
+ to: number;
+ subject?: number | string;
+ host?: number | string;
+ why?: string;
+};
+
+export type FindClipsStepRecord = {
+ id: string;
+ label: string;
+ action: "ran" | "skipped";
+ why: string;
+};
+
+export type FindClipsRecord = {
+ version: 1;
+ at: string;
+ jobId: string;
+ // The umtool project, its clip editor's URL, and whether umtool made it now
+ // (false: it re-analyzed the project already cut from this recording).
+ project: string;
+ url: string;
+ created: boolean;
+ // The segment this run was scoped to: the one asked for, else the one
+ // umtool's auto-scope chose (its answer's `segment`).
+ segment?: string;
+ // Every narrated-video segment umtool found in the recording.
+ segments: FindClipsSegment[];
+ steps: FindClipsStepRecord[];
+};
+
+function coerce(value: unknown): FindClipsRecord | null {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const v = value as Record<string, unknown>;
+ if (v.version !== 1 || typeof v.project !== "string" || typeof v.url !== "string") return null;
+ if (!Array.isArray(v.segments) || !Array.isArray(v.steps)) return null;
+ return value as FindClipsRecord;
+}
+
+export const findClipsSidecar = sidecar(FIND_CLIPS_FILENAME, sidecarField(coerce), { indent: 2 });
+export const loadFindClipsRecord = findClipsSidecar.load;
+export const writeFindClipsRecord = findClipsSidecar.write;
diff --git a/common/lib/sidecar-server.test.ts b/common/lib/sidecar-server.test.ts
@@ -15,6 +15,8 @@ import "./frameScan-server";
import "./metadataHistory-server";
import "./transcriptPin-server";
import "./wayback-server";
+import "./wordTimings-server";
+import "./findClipsRecord-server";
import {
availabilitySidecar,
loadAvailability,
@@ -46,7 +48,7 @@ async function scratch(): Promise<string> {
return mkdtemp(path.join(os.tmpdir(), "sidecar-"));
}
-test("every declared sidecar filename escapes SUB_FILE_RE, and all fifteen are declared", () => {
+test("every declared sidecar filename escapes SUB_FILE_RE, and all seventeen are declared", () => {
assert.deepEqual([...SIDECAR_FILENAMES].sort(), [
"ai-digest.json",
"ai-digest.overrides.json",
@@ -58,11 +60,13 @@ test("every declared sidecar filename escapes SUB_FILE_RE, and all fifteen are d
"do-not-clean.json",
"download-outcome.json",
"exclude-truncated-check.json",
+ "find-clips.json",
"frame-scan.poker.json",
"metadata.history.json",
"transcribe-outcome.json",
"transcript-pin.json",
"wayback.json",
+ "words.json",
]);
for (const name of SIDECAR_FILENAMES) {
assert.ok(!SUB_FILE_RE.test(name), name);
diff --git a/common/lib/umtoolUrl.test.ts b/common/lib/umtoolUrl.test.ts
@@ -0,0 +1,24 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { umtoolUrl } from "./umtoolUrl";
+
+test("umtoolUrl: UMTOOL_URL without its trailing slashes, null when unset; a test's loopback origin from the file", async () => {
+ assert.equal(umtoolUrl({}), null);
+ assert.equal(umtoolUrl({ UMTOOL_URL: " " }), null);
+ assert.equal(umtoolUrl({ UMTOOL_URL: "http://localhost:3050//" }), "http://localhost:3050");
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-url-"));
+ try {
+ const file = path.join(dir, ".fake-umtool-origin");
+ const env = { E2E_UMTOOL_ORIGIN_FILE: file, UMTOOL_URL: "http://localhost:3050" };
+ assert.equal(umtoolUrl(env), "http://localhost:3050", "no file yet");
+ await writeFile(file, "http://127.0.0.1:41234/\n");
+ assert.equal(umtoolUrl(env), "http://127.0.0.1:41234");
+ await writeFile(file, "https://umtool.example.com");
+ assert.equal(umtoolUrl(env), "http://localhost:3050", "not loopback: ignored");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/lib/umtoolUrl.ts b/common/lib/umtoolUrl.ts
@@ -0,0 +1,31 @@
+// WHERE UMTOOL IS, for the editor's side of the clip finder (release 36, lane
+// A): `UMTOOL_URL`, trailing slashes dropped; null when unset. The video page
+// links to it and the find-clips job posts to its `/api/report/clips`.
+//
+// TEST-ONLY: E2E_UMTOOL_ORIGIN_FILE names a file holding ONE loopback origin
+// (`http://127.0.0.1:<port>`). While that file exists, umtool is that origin —
+// the stub umtool an editor e2e spec starts (find-clips.spec) and names in the
+// file after the test server booted; it is read per call. Anything but a
+// loopback origin in it is ignored. Unset everywhere but the editor's e2e
+// server (the Bluesky fake's pattern, social/blueskyEndpoints.ts).
+
+import { readFileSync } from "node:fs";
+
+const LOOPBACK_ORIGIN = /^http:\/\/(?:127\.0\.0\.1|localhost)(?::\d{1,5})?$/;
+
+export function umtoolUrl(
+ env: Readonly<Record<string, string | undefined>> = process.env,
+): string | null {
+ const file = env.E2E_UMTOOL_ORIGIN_FILE;
+ if (file) {
+ let origin = "";
+ try {
+ origin = readFileSync(file, "utf8").trim().replace(/\/+$/, "");
+ } catch {
+ origin = "";
+ }
+ if (LOOPBACK_ORIGIN.test(origin)) return origin;
+ }
+ const url = env.UMTOOL_URL?.trim().replace(/\/+$/, "");
+ return url ? url : null;
+}
diff --git a/common/lib/wordTimings-server.ts b/common/lib/wordTimings-server.ts
@@ -0,0 +1,59 @@
+// A VIDEO'S WORD TIMINGS — `data/<id>/words.json` (release 36, lane A).
+//
+// The clip finder cuts on words: a clip's edges snap to the word the speaker
+// starts or finishes on, never to a caption line's wrap. Release 35 made them
+// by hand (`pnpm ops transcribe {path, words: true, out: <project>/words.json}`)
+// into one umtool project. The find-clips job makes them ONCE per video,
+// here, beside the transcript they belong to, so every project cut from this
+// recording reads the same file (umtool copies it in as `<project>/words.json`)
+// and the step is skipped the next time.
+//
+// THE SHAPE IS THE TRANSCRIBE RESULT'S (controller/transcribeFile.ts
+// TranscribeFileResult) without its cues and text — {version, path, window,
+// worker, transcriptFormat, transcribedAt, durationMs, waitedMs, words} — so a
+// release-35 words.json and this file read the same (umtool reads
+// `doc.words`, umtool/lib/report/reactions.mjs loadRecording). A file with no
+// words array reads as absent; one with an EMPTY array is never written (an
+// engine that keeps no word timestamps — the job says so and goes on).
+//
+// TEXT, not media: it stays in the real data/<id>/ on the corpus disk and is
+// never tiered (lib/mediaTier.ts tiers by name; this name is not one).
+
+import { sidecar, sidecarField } from "./sidecar-server";
+
+export const WORD_TIMINGS_FILENAME = "words.json";
+
+export type TimedWord = { w: string; start: number; end: number; conf?: number };
+
+export type WordTimingsRecord = {
+ version: 1;
+ // The file the engine read (the video's audio or saved container).
+ path: string;
+ window: { start: number; end: number | null } | null;
+ worker: { id: string; name: string; appId: string; model: string | null; device: string | null };
+ transcriptFormat: string;
+ transcribedAt: string;
+ durationMs: number;
+ waitedMs: number;
+ words: TimedWord[];
+};
+
+function isWord(w: unknown): w is TimedWord {
+ if (!w || typeof w !== "object") return false;
+ const o = w as Record<string, unknown>;
+ return typeof o.w === "string" && typeof o.start === "number" && typeof o.end === "number";
+}
+
+export function coerceWordTimings(value: unknown): WordTimingsRecord | null {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const v = value as Record<string, unknown>;
+ if (!Array.isArray(v.words) || v.words.length === 0 || !v.words.every(isWord)) return null;
+ return value as WordTimingsRecord;
+}
+
+export const wordTimingsSidecar = sidecar(WORD_TIMINGS_FILENAME, sidecarField(coerceWordTimings), {
+ indent: 0,
+});
+
+export const loadWordTimings = wordTimingsSidecar.load;
+export const writeWordTimings = wordTimingsSidecar.write;
diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts
@@ -546,10 +546,29 @@ async function fetchLiveChatOnly(
channelDir: string,
cookies: string | undefined,
): Promise<AttemptOutcome> {
- return runOneYtdlp(opts, channelDir, [
+ return runOneYtdlp(
+ opts,
+ channelDir,
+ liveChatOnlyArgs(opts.channelConfig, cookies, opts.videoUrl),
+ );
+}
+
+// The chat-only pass's argv, run in the channel dir: the channel's own args
+// (its cookies and the platform's live pace) and then the refusals. Exported
+// for the one-video chat fetch (release 36 lane A, controller/fetchLiveChat.ts
+// — `pnpm ops fetch-chat`), so the two passes are one command line.
+export function liveChatOnlyArgs(
+ channelConfig: ChannelConfig,
+ cookies: string | undefined,
+ videoUrl: string,
+ paceSeconds?: number,
+): string[] {
+ return [
"--ignore-config",
"--restrict-filenames",
- ...channelConfigArgs(opts.channelConfig, cookies),
+ ...(paceSeconds !== undefined
+ ? channelConfigArgs(channelConfig, cookies, paceSeconds)
+ : channelConfigArgs(channelConfig, cookies)),
"--skip-download",
"--write-subs",
"--no-write-auto-subs",
@@ -559,10 +578,10 @@ async function fetchLiveChatOnly(
"--no-write-description",
"--no-write-thumbnail",
"--no-download-archive",
- ...outputArgsForUrl(opts.videoUrl),
+ ...outputArgsForUrl(videoUrl),
"--",
- opts.videoUrl,
- ]);
+ videoUrl,
+ ];
}
// Did the chat pass actually leave a chat behind? A stream with chat replay
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,9 @@
# Changelog
## [Unreleased]
+- **Find clips: the clip finder from one button on the video page.** A video page's **Find clips** runs the whole chain umtool's clip finder needs, as one job: it saves the source video, transcribes the recording, makes its word timings (kept beside the transcript as `words.json`, so a second project from the same recording reuses them), fetches the stream's chat replay (YouTube), finds who speaks when, and then asks umtool to find the narrated-video segments and propose the clips. Each step whose output is already on disk is skipped, and the job's log says which ran and which were skipped. When it is done the panel links the umtool project and lists the segments it found, each with **Find clips in this part**. A target length can be given. When the workers are paused or the backfill lane is held, the step that needs them stops with a sentence saying so, and **Run while paused** runs this one video past them. The button is off, with a line saying why, when the editor has no `UMTOOL_URL`. The same from a terminal: `pnpm ops find-clips --json '{"slug","id"}'` (a `dryRun` lists what each step would do). Needs a restart of the editor.
+- **Transcribe one video while the workers are paused.** With the transcription workers paused, the video page's Transcribe row offers **Transcribe now (workers paused)**: that one transcription runs on a worker the pause alone switched off, and the pause stays on — the worker is paused again when it finishes. A worker you drained, disabled by hand or that is marked degraded is never used, and the lanes stay held. `pnpm ops transcribe` and `transcribe-one` take `"whilePaused": true`.
+- **Fetch a stream's chat replay on its own.** Media tools → **Fetch live chat** on a video page (`pnpm ops fetch-chat`) fetches the video's live chat and nothing else, paced like every YouTube request and on the platform's download queue, into the chat cues the index and the clip finder read. A video on another platform says there is no chat fetcher for it, as does a chat already fetched or a video that was never live.
- **The clip finder finds each narrated video in a reaction stream, and listens to the chat.** A stream that reacts to one video and then another no longer needs its scope read off the speakers by hand: `umtool new <slug> --seed reactions --from <channel>/<id> --scope auto` reads the narrated video the speaker turns show (`--segment s2` names one, else the longest), with the host's reaction after the video kept and the roles found for that video alone; `umtool clips segments <project>` lists them. When the stream's chat replay is on disk, the moments the chat laughs together (lol, KEKW, 😂, a wall of W) become proposals too, moved back by how late the chat types — found by lining the chat up against the laughs heard in the sound, else 6 seconds — and always ranked below the host's own laugh; the analysis says the delay it found. Without a chat replay nothing changes. Needs a restart of umtool.
- **Highlights of a channel that is on no site link the source and start with a clean look.** Each proposed clip links its platform page at its second (YouTube, Twitch, Rumble…), the channel's name is filled in from the video, and the cut starts with no header, no QR code, half-second fades through black and a −16 LUFS loudness target — no edits to the manifest needed. umtool's clips job also answers the editor directly (its `WORKER_TOKEN`), so the editor's Find clips makes or re-analyzes the project in one call; asking again for a video already cut analyzes that project again and leaves its cut exactly as it is, listing the new proposals (the chat's among them) for you to bring in.
- **Set a report video's look in umtool, with captions that say who is speaking and even loudness.** The Build tab has a **Look** panel: the header, the timeline footer and the QR code on or off, the length between clips and how they join (crossfade, dip to black, dip to white, dissolve), the loudness (as recorded, −16 LUFS, or your own target) and **Speaker captions** — burned in, two to six words a line, the host's in amber on the left and the other voice's in blue on the right, broken where they pause and never across a change of speaker (from the clip finder's speakers, or the transcript's words). Voices are told apart by colour; give one a name in the panel, or beside a speaker in the clip editor's Speakers list, and its lines say it. Even loudness measures each clip and brings it to the target with a limiter, as montages already did. **Save the look** writes only what you changed; a cut with the on-screen deck keeps its own settings. A manifest without the new keys renders exactly as before. Needs a restart of umtool.
diff --git a/editor/app/api/ops/_door.test.ts b/editor/app/api/ops/_door.test.ts
@@ -108,6 +108,8 @@ test("a traversing slug is refused at the door, on every route that takes one",
["fetch-posts", { slug: "../../escape", older: true }],
["capture-posts", { slug: "../../escape", ids: ["1"] }],
["persist-videos", { items: [{ slug: "../../escape", id: "abc123" }] }],
+ ["fetch-chat", { slug: "../../escape", id: "abc123" }],
+ ["find-clips", { slug: "../../escape", id: "abc123" }],
];
for (const [action, data] of cases) {
const { status, body } = await callPost((await route(action)).POST!, data);
diff --git a/editor/app/api/ops/_findClips.ts b/editor/app/api/ops/_findClips.ts
@@ -0,0 +1,20 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { jobOfPaths } from "yt-dlp-transcript-common/controller/researchRuns";
+import type { FindClipsDeps } from "yt-dlp-transcript-common/controller/findClips";
+import { safeRevalidate } from "../../lib/safeRevalidate";
+import { findClipsEditor } from "./_researchEditor";
+
+// THE EDITOR'S SIDE OF FIND CLIPS (release 36 lane A): the chain's deps — its
+// steps through this editor's own ops actions in process (findClipsEditor),
+// its jobs from this registry, and the video page revalidated when the record
+// lands. Shared by `POST /api/ops/find-clips` and the video page's button
+// (findClipsActions.ts), so the two run one chain.
+export function findClipsDeps(slug: string, id: string): FindClipsDeps {
+ const paths = getPaths();
+ return {
+ paths,
+ editor: findClipsEditor,
+ jobOf: jobOfPaths(paths),
+ onDone: () => safeRevalidate([`/channels/${slug}/videos/${id}`]),
+ };
+}
diff --git a/editor/app/api/ops/_researchEditor.ts b/editor/app/api/ops/_researchEditor.ts
@@ -86,3 +86,16 @@ export const refreshEditor: ResearchEditor = {
return refreshDoor.run(action, args);
},
};
+
+// FIND CLIPS' EDITOR (release 36 lane A, controller/findClips.ts): the steps
+// the chain hands to the editor's own ops actions — persist the source, the
+// corpus transcript, the chat replay — through the same door.
+const FIND_CLIPS_ROUTES: Record<string, () => Promise<{ POST: Post }>> = {
+ "persist-videos": () => import("./persist-videos/route"),
+ "transcribe-one": () => import("./transcribe-one/route"),
+ "fetch-chat": () => import("./fetch-chat/route"),
+};
+
+export const FIND_CLIPS_DOOR_ACTIONS = Object.keys(FIND_CLIPS_ROUTES);
+
+export const findClipsEditor: ResearchEditor = inProcessEditor(FIND_CLIPS_ROUTES, "find-clips");
diff --git a/editor/app/api/ops/fetch-chat/route.ts b/editor/app/api/ops/fetch-chat/route.ts
@@ -0,0 +1,23 @@
+import { fetchChatAction } from "../../../channels/[slug]/videos/[id]/mediaToolsActions";
+import { jobResponse, ops, optString, reqSlug, reqVideoId } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, id, queueKey? } -> { ok: true, jobId }
+//
+// ONE video's live chat replay, and nothing else (release 36, lane A;
+// controller/fetchLiveChat.ts): the chat-only yt-dlp pass the managed download
+// runs for a chat-only channel — the channel's cookies and the platform's live
+// pace — on the platform's download queue, then live_chat.cues.json. The video
+// page's Media tools → "Fetch live chat", and the find-clips job's chat step.
+//
+// Answered without a job, `info: true` (a skip, not an error): a video on a
+// platform with no chat fetcher ("no chat fetcher for twitch"), a chat already
+// here and fresh, a video that was never live, a held platform or one in a
+// rate-limit cooldown. Refused: an id with no data/<id>/, a channel whose text
+// cannot be read. A pass that finds no replay ends `done` and says so.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "id", "queueKey"], async (body) =>
+ jobResponse(await fetchChatAction(reqSlug(body, "slug"), reqVideoId(body, "id"), optString(body, "queueKey"))),
+ );
+}
diff --git a/editor/app/api/ops/find-clips/route.ts b/editor/app/api/ops/find-clips/route.ts
@@ -0,0 +1,34 @@
+import { NextResponse } from "next/server";
+import { FIND_CLIPS_BODY_KEYS, enqueueFindClips } from "yt-dlp-transcript-common/controller/findClips";
+import { findClipsDeps } from "../_findClips";
+import { jobResponse, ops, reqSlug, reqVideoId } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, id, target?, segment?, project?, whilePaused?, dryRun? }
+// dryRun -> { ok: true, dryRun: true, plan: { steps: [{id, label, run, why}], umtoolUrl, workersPaused } }
+// else -> { ok: true, jobId }
+//
+// FIND CLIPS (release 36, lane A; controller/findClips.ts): the clip finder's
+// chain for ONE video as one job — persist the source video, the corpus
+// transcript, word timings (data/<id>/words.json), the chat replay (YouTube),
+// diarization — each step skipped when its output exists and named in the
+// log — then umtool's clips route (`mode: "new"`, `scope: "auto"`, or the
+// `segment` asked), followed to the end. The log ends `@@find-clips {json}`:
+// the project, its clip editor's URL, the segments umtool found and what each
+// step did; data/<id>/find-clips.json keeps it for the video page.
+//
+// `target` is the cut's length in seconds; `segment` a segment id umtool
+// found ("s2"); `project` names the umtool project a run makes (default from
+// the id); `whilePaused` runs the two transcriptions during a pause-all on a
+// worker the pause alone switched off. Refused before a job: an unknown
+// channel or video, UMTOOL_URL or WORKER_TOKEN unset on the editor.
+export async function POST(request: Request) {
+ return ops(request, FIND_CLIPS_BODY_KEYS, async (body) => {
+ const slug = reqSlug(body, "slug");
+ const id = reqVideoId(body, "id");
+ const out = await enqueueFindClips(body, findClipsDeps(slug, id));
+ if (out.dryRun) return NextResponse.json({ ok: true, dryRun: true, plan: out.plan });
+ return jobResponse(out.result);
+ });
+}
diff --git a/editor/app/api/ops/transcribe-one/route.ts b/editor/app/api/ops/transcribe-one/route.ts
@@ -28,13 +28,18 @@ export const dynamic = "force-dynamic";
// disk, the download reads the media URL the record stores, the way the
// platform's player does (the managed path: the audio check, the outcome
// sidecar). Absent = the channel's `storedUrlDownloads`. Not with "file".
+// "whilePaused" (release 36, lane A): true lets this one transcription run
+// during a pause-all on a worker the pause alone switched off (never one
+// drained, degraded or disabled by hand); the pause stays on. Absent or false
+// = held by the pause, as before.
export async function POST(request: Request) {
- return ops(request, ["slug", "id", "file", "salvage", "storedUrl"], async (body) => {
+ return ops(request, ["slug", "id", "file", "salvage", "storedUrl", "whilePaused"], async (body) => {
const slug = reqSlug(body, "slug");
const id = reqVideoId(body, "id");
const file = optString(body, "file");
const salvage = optBool(body, "salvage");
const storedUrl = optStoredUrlMode(body);
+ const whilePaused = optBool(body, "whilePaused") === true;
if (storedUrl !== undefined && file !== undefined) {
return opsFail(`"storedUrl" is for a download; with "file" nothing is downloaded`);
}
@@ -45,8 +50,8 @@ export async function POST(request: Request) {
}
return jobResponse(
file !== undefined
- ? await transcribeOneAction(slug, id, file, undefined, salvage)
- : await whisperVideoAction(slug, id, undefined, salvage, storedUrl),
+ ? await transcribeOneAction(slug, id, file, undefined, salvage, whilePaused)
+ : await whisperVideoAction(slug, id, undefined, salvage, storedUrl, whilePaused),
);
});
}
diff --git a/editor/app/api/ops/transcribe/route.ts b/editor/app/api/ops/transcribe/route.ts
@@ -7,7 +7,7 @@ import { jobResponse, ops } from "../_lib";
export const dynamic = "force-dynamic";
-// POST { path, start?, end?, workerId?, out? } -> { ok: true, jobId }
+// POST { path, start?, end?, workerId?, out?, words?, whilePaused? } -> { ok: true, jobId }
//
// Transcribe ONE local file — or the window [start, end) seconds of it — on a
// local transcription worker, as a job on /jobs: the engine, model and
@@ -26,6 +26,8 @@ export const dynamic = "force-dynamic";
// — a relative or unreadable `path`, `end` not after `start`, an unknown or
// non-local `workerId`, a named worker switched off, an `out` inside the corpus
// (resolved through symlinks) or in a directory that does not exist.
+// `whilePaused: true` (release 36, lane A) runs it during a pause-all on a
+// worker the pause alone switched off; the pause stays on.
export async function POST(request: Request) {
return ops(request, TRANSCRIBE_FILE_BODY_KEYS, async (body) =>
jobResponse(await enqueueTranscribeFile(body, { paths: getPaths() })),
diff --git a/editor/app/channels/[slug]/videos/[id]/components/FindClipsPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/FindClipsPanel.tsx
@@ -0,0 +1,148 @@
+"use client";
+
+// FIND CLIPS (release 36, lane A): the clip finder's whole chain for this
+// video, one button — the same job as `pnpm ops find-clips`
+// (controller/findClips.ts). Each step it skips or runs is in the job's log;
+// what the last run found (data/<id>/find-clips.json) is drawn below it: the
+// umtool project, linked, and the narrated-video segments umtool found, each
+// with its own "Find clips in this part".
+//
+// TYPE-ONLY from lib/findClipsRecord-server (it reaches node:fs through
+// sidecar-server): the record arrives as a prop, read by the page.
+
+import { useState } from "react";
+import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
+import type { FindClipsRecord } from "yt-dlp-transcript-common/lib/findClipsRecord-server";
+import { cancelJobAction } from "../../../../../jobs/actions";
+import { findClipsAction } from "../findClipsActions";
+
+const input = "rounded border border-border bg-card px-2 py-1 text-sm";
+
+function clock(seconds: number): string {
+ const s = Math.max(0, Math.round(seconds));
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const sec = s % 60;
+ return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}` : `${m}:${String(sec).padStart(2, "0")}`;
+}
+
+export function FindClipsPanel({
+ slug,
+ videoId,
+ umtoolUrl,
+ holds,
+ record,
+}: {
+ slug: string;
+ videoId: string;
+ // UMTOOL_URL on the editor (lib/umtoolUrl.ts), read by the page. Null: the
+ // button is disabled and the status line says why.
+ umtoolUrl: string | null;
+ // What would hold a step right now ("the transcription workers are paused",
+ // "the backfill lane is held"), read by the page. Any: the "while paused"
+ // checkbox is offered — this one video's steps run past them.
+ holds: string[];
+ record: FindClipsRecord | null;
+}) {
+ const [minutes, setMinutes] = useState("");
+ const [whilePaused, setWhilePaused] = useState(false);
+ const target = Number(minutes) > 0 ? Math.round(Number(minutes) * 60) : undefined;
+ const opts = (segment?: string) => ({
+ ...(target !== undefined ? { target } : {}),
+ ...(segment ? { segment } : {}),
+ ...(holds.length > 0 && whilePaused ? { whilePaused: true } : {}),
+ });
+ const status = !umtoolUrl
+ ? "off"
+ : record
+ ? `last run ${record.at.slice(0, 10)}: ${record.segments.length} segment${record.segments.length === 1 ? "" : "s"}`
+ : "not run yet";
+ return (
+ <section aria-label="find-clips panel" className="flex flex-col gap-4 rounded border border-border p-3">
+ <div className="flex flex-wrap items-baseline justify-between gap-2">
+ <h2 className="text-lg font-semibold">Find clips</h2>
+ <span aria-label="find-clips status" className="text-xs text-muted-foreground">
+ {status}
+ </span>
+ </div>
+ {!umtoolUrl && (
+ <p role="status" aria-label="find-clips off" className="text-sm text-muted-foreground">
+ UMTOOL_URL is not set on the editor: Find clips hands the recording to umtool's clip finder.
+ </p>
+ )}
+ <div className="flex flex-wrap items-end gap-3 text-sm">
+ <label className="flex flex-col gap-0.5">
+ <span className="text-xs text-muted-foreground">Target length (minutes; empty = umtool's default)</span>
+ <input
+ type="number"
+ min={1}
+ step={1}
+ inputMode="numeric"
+ value={minutes}
+ onChange={(e) => setMinutes(e.target.value)}
+ aria-label="target length (minutes)"
+ className={`${input} w-28`}
+ />
+ </label>
+ {holds.length > 0 && (
+ <label className="flex items-center gap-2">
+ <input
+ type="checkbox"
+ checked={whilePaused}
+ onChange={(e) => setWhilePaused(e.target.checked)}
+ aria-label="run while paused"
+ />
+ Run while paused (this video only)
+ </label>
+ )}
+ </div>
+ {holds.length > 0 && (
+ <p role="status" aria-label="find-clips holds" className="text-xs text-muted-foreground">
+ {holds.join("; ").replace(/^./, (c) => c.toUpperCase())}.
+ </p>
+ )}
+ <StreamActionLog
+ trigger={() => findClipsAction(slug, videoId, opts())}
+ cancelAction={cancelJobAction}
+ buttonLabel="Find clips"
+ runningLabel="Finding clips…"
+ label={`Find clips in ${videoId}`}
+ disabled={!umtoolUrl}
+ />
+ {record && (
+ <div aria-label="find-clips result" className="flex flex-col gap-2 text-sm">
+ <p>
+ Clips:{" "}
+ <a href={record.url} className="underline font-mono" data-find-clips-project>
+ {record.project}
+ </a>{" "}
+ <span className="text-muted-foreground">
+ ({record.created ? "new project" : "re-analyzed"}
+ {record.segment ? `, segment ${record.segment}` : ""})
+ </span>
+ </p>
+ {record.segments.length > 0 && (
+ <ul aria-label="segments found" className="flex flex-col gap-2">
+ {record.segments.map((s) => (
+ <li key={s.id} className="flex flex-col gap-1 rounded border border-border p-2">
+ <span>
+ <span className="font-mono">{s.id}</span> {clock(s.from)}–{clock(s.to)}
+ {s.why ? <span className="text-muted-foreground"> — {s.why}</span> : null}
+ </span>
+ <StreamActionLog
+ trigger={() => findClipsAction(slug, videoId, opts(s.id))}
+ cancelAction={cancelJobAction}
+ buttonLabel="Find clips in this part"
+ runningLabel="Finding clips…"
+ label={`Find clips in segment ${s.id}`}
+ disabled={!umtoolUrl}
+ />
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoMediaTools.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoMediaTools.tsx
@@ -8,6 +8,7 @@ import { cancelJobAction } from "../../../../../jobs/actions";
import {
archiveOrgRefreshAction,
attachVideoMediaAction,
+ fetchChatAction,
playableVideoAction,
waybackRefreshAction,
type RecordsRefreshResult,
@@ -41,6 +42,16 @@ export function VideoMediaTools({
<summary className="cursor-pointer text-sm font-semibold">Media tools</summary>
<div className="mt-3 flex flex-col gap-4">
<AttachFromArchive slug={slug} videoId={videoId} saved={saved} />
+ <div className="flex flex-col gap-2">
+ <h4 className="text-sm font-semibold">Live chat replay</h4>
+ <StreamActionLog
+ trigger={() => fetchChatAction(slug, videoId)}
+ cancelAction={cancelJobAction}
+ buttonLabel="Fetch live chat"
+ runningLabel="Fetching the chat…"
+ label={`Fetch live chat of ${videoId}`}
+ />
+ </div>
{saved && (
<div className="flex flex-col gap-2">
<h4 className="text-sm font-semibold">Playable copy</h4>
diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx
@@ -108,6 +108,9 @@ type Props = {
// The umtool front door, when UMTOOL_URL is set on the editor. One link:
// "open in umtool" scaffolds a report video from this exact video.
umtoolUrl?: string | null;
+ // The transcription pool is paused (getWorkerPool().isPaused(), read by the
+ // page): the Transcribe rows offer "Transcribe now (workers paused)".
+ workersPaused?: boolean;
};
export function VideoPanel({
@@ -135,6 +138,7 @@ export function VideoPanel({
umtoolUrl = null,
storedMediaHost = null,
channelStoredUrl,
+ workersPaused = false,
}: Props) {
const audioFiles = files.filter((f) => isAudioFile(f.name));
const transcodeSources = files.filter((f) => isTranscodeSource(f.name));
@@ -357,6 +361,7 @@ export function VideoPanel({
hasTranscript={hasTranscript && !autoSubsOnly}
replaceAutoSubs={autoSubsOnly}
fullAudio={fullAudioOwed}
+ workersPaused={workersPaused}
/>
))}
</div>
diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/PerFileTranscribeRow.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/PerFileTranscribeRow.tsx
@@ -19,6 +19,7 @@ export function PerFileTranscribeRow({
hasTranscript,
replaceAutoSubs = false,
fullAudio = null,
+ workersPaused = false,
}: {
slug: string;
videoId: string;
@@ -32,6 +33,10 @@ export function PerFileTranscribeRow({
// (lib/fullAudioFirst.ts). Transcribe makes them first; Salvage now makes
// the partial transcript from this file at once.
fullAudio?: FullAudioState | null;
+ // The transcription pool is paused (the pool's live state, read by the page).
+ // Release 36 lane A: "Transcribe now (workers paused)" runs this one file on
+ // a worker the pause alone switched off; the pause stays on.
+ workersPaused?: boolean;
}) {
const [transcribeQueue, setTranscribeQueue] = useState("");
// `hasTranscript` is SERVER-derived (VideoPanel, the Transcribe card) and this row's own run
@@ -103,6 +108,19 @@ export function PerFileTranscribeRow({
}
/>
)}
+ {workersPaused && !hasTranscript && (
+ <StreamActionLog
+ key="transcribe-paused-run"
+ trigger={() => {
+ setRanHere(true);
+ return transcribeOneAction(slug, videoId, file.name, transcribeQueue, undefined, true);
+ }}
+ cancelAction={cancelJobAction}
+ buttonLabel="Transcribe now (workers paused)"
+ runningLabel="Transcribing…"
+ label={`Transcribe ${file.name} while paused`}
+ />
+ )}
{fullAudio && !hasTranscript && (
<StreamActionLog
key="salvage-run"
diff --git a/editor/app/channels/[slug]/videos/[id]/findClipsActions.ts b/editor/app/channels/[slug]/videos/[id]/findClipsActions.ts
@@ -0,0 +1,29 @@
+"use server";
+
+// The video page's Find clips (release 36 lane A): the same chain as `pnpm ops
+// find-clips` (controller/findClips.ts), through the same deps
+// (api/ops/_findClips.ts). NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use
+// server" file).
+
+import { enqueueFindClips } from "yt-dlp-transcript-common/controller/findClips";
+import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
+import { findClipsDeps } from "../../../../api/ops/_findClips";
+
+export async function findClipsAction(
+ slug: string,
+ videoId: string,
+ opts: { target?: number; segment?: string; whilePaused?: boolean } = {},
+): Promise<StreamActionResult> {
+ const out = await enqueueFindClips(
+ {
+ slug,
+ id: videoId,
+ ...(opts.target !== undefined ? { target: opts.target } : {}),
+ ...(opts.segment ? { segment: opts.segment } : {}),
+ ...(opts.whilePaused ? { whilePaused: true } : {}),
+ },
+ findClipsDeps(slug, videoId),
+ );
+ if (out.dryRun) return { ok: false, error: "a dry run starts no job" };
+ return out.result;
+}
diff --git a/editor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts b/editor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts
@@ -14,6 +14,9 @@
// this record with it; answered in the request
// archiveOrg `archilyzer archive-org refresh <slug>` — the channel's
// archive.org file records (offline); answered in the request
+// chat `pnpm ops fetch-chat` (release 36 lane A) — this video's live
+// chat replay alone, paced, into live_chat.cues.json — the
+// `fetch-chat` job
//
// NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use server" file).
@@ -22,7 +25,11 @@ import { revalidatePath } from "next/cache";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { refreshWaybackRecords } from "yt-dlp-transcript-common/controller/waybackRefresh";
import { refreshArchiveOrgRecords } from "yt-dlp-transcript-common/controller/archiveOrgRefresh";
-import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels";
+import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
+import { runFetchChatJob } from "yt-dlp-transcript-common/controller/fetchLiveChat";
+import { resolveCookiePolicy } from "yt-dlp-transcript-common/lib/cookiePolicy";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { safeRevalidate } from "../../../../lib/safeRevalidate";
import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
import { attachMediaAction } from "../../attachMediaActions";
import { preparePlayableAction } from "../../playableActions";
@@ -46,6 +53,22 @@ export async function attachVideoMediaAction(
});
}
+export async function fetchChatAction(slug: string, videoId: string, queueKey?: string): Promise<StreamActionResult> {
+ if (!isValidChannelSlug(slug)) return { ok: false, error: `"${slug}" is not a channel slug` };
+ const paths = getPaths();
+ const config = await readChannelConfig(paths, slug);
+ if (!config) return { ok: false, error: `Channel "${slug}" not found` };
+ return runFetchChatJob({
+ paths,
+ slug,
+ videoId,
+ channelConfig: config,
+ cookiePolicy: resolveCookiePolicy(getSettings(), config),
+ ...(queueKey !== undefined ? { queueKey } : {}),
+ afterRun: () => safeRevalidate([`/channels/${slug}/videos/${videoId}`]),
+ });
+}
+
export async function playableVideoAction(slug: string, videoId: string, dryRun = false): Promise<StreamActionResult> {
return preparePlayableAction(slug, { ids: [videoId], ...(dryRun ? { dryRun: true } : {}) });
}
diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx
@@ -37,6 +37,8 @@ import {
queueKeyForUrl,
} from "yt-dlp-transcript-common/lib/platform";
import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import { getWorkerPool } from "yt-dlp-transcript-common/jobs/workerPool";
+import { isGateHeld } from "yt-dlp-transcript-common/lib/pauseGates";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
import { resolveSourceVideoQuality } from "yt-dlp-transcript-common/ytdlp/downloadFormat";
import { liveJobRows } from "../../../../jobs/active/buildActiveJobs";
@@ -45,6 +47,9 @@ import { VideoPanel, type VideoFile } from "./components/VideoPanel";
import { OperationPanel } from "./components/OperationPanel";
import { TagsPanel } from "./components/TagsPanel";
import { FrameScanPanel } from "./components/FrameScanPanel";
+import { FindClipsPanel } from "./components/FindClipsPanel";
+import { loadFindClipsRecord } from "yt-dlp-transcript-common/lib/findClipsRecord-server";
+import { umtoolUrl as resolveUmtoolUrl } from "yt-dlp-transcript-common/lib/umtoolUrl";
import { frameScanView } from "./lib/frameScanView";
import { loadFrameScans } from "yt-dlp-transcript-common/lib/frameScan-server";
import { MetadataHistoryDetails } from "./components/MetadataHistoryDetails";
@@ -220,6 +225,9 @@ export default async function VideoDetailPage({
// profile, on the corpus disk.
const frameScans = await loadFrameScans(videoDir);
+ // What the last Find clips found (release 36 lane A): one small sidecar.
+ const findClips = await loadFindClipsRecord(videoDir);
+
// The curated tags on this video, with each one's provenance. Reads tags.json
// plus (for rule hits) ONE key out of the transcript index — not a scan.
const tagsView = await loadVideoTags(slug, id);
@@ -245,6 +253,7 @@ export default async function VideoDetailPage({
panels,
tagsView,
frameScans,
+ findClips,
};
};
const drive = config.dataDir?.trim();
@@ -279,6 +288,7 @@ export default async function VideoDetailPage({
panels,
tagsView,
frameScans,
+ findClips,
} = loaded;
const registry = getRegistry();
@@ -417,6 +427,7 @@ export default async function VideoDetailPage({
coverage={coverage}
storedMediaHost={storedMediaHost}
channelStoredUrl={config.storedUrlDownloads}
+ workersPaused={getWorkerPool().isPaused()}
/>
<TagsPanel view={tagsView} />
@@ -440,6 +451,18 @@ export default async function VideoDetailPage({
readingT={readingT}
/>
+ {/* The clip finder's chain for this video (release 36 lane A). */}
+ <FindClipsPanel
+ slug={slug}
+ videoId={id}
+ umtoolUrl={resolveUmtoolUrl()}
+ holds={[
+ ...(getWorkerPool().isPaused() ? ["the transcription workers are paused"] : []),
+ ...(isGateHeld(getSettings(), "backfill") ? ["the backfill lane is held"] : []),
+ ]}
+ record={findClips}
+ />
+
{/* The external operations' per-video surface is the pipeline stage
cards INSIDE VideoPanel above (download, transcode, transcription).
These are the registry's — one panel per entry, and a fifth entry
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -207,6 +207,9 @@ export async function transcribeOneAction(
// true forces it, false forbids it, undefined leaves it automatic (a
// corrupt-full-source video is salvaged).
salvage?: boolean,
+ // Release 36 lane A: during a pause-all, run on a worker the pause alone
+ // switched off ("Transcribe now (workers paused)"; the pool's whilePaused).
+ whilePaused?: boolean,
): Promise<StreamActionResult> {
const r = await loadConfigOrError(slug);
if (!r.ok) return r;
@@ -231,6 +234,7 @@ export async function transcribeOneAction(
onLog,
signal,
...(salvage !== undefined ? { salvage } : {}),
+ ...(whilePaused ? { whilePaused: true } : {}),
});
safeRevalidate([`/channels/${slug}/videos/${videoId}`]);
},
@@ -554,6 +558,8 @@ export async function whisperVideoAction(
// outcome sidecar, the corrupt-source refetch — instead of the plain
// one-video download.
storedUrl?: StoredUrlMode,
+ // See transcribeOneAction's `whilePaused`.
+ whilePaused?: boolean,
): Promise<StreamActionResult> {
const r = await loadConfigOrError(slug);
if (!r.ok) return r;
@@ -664,6 +670,7 @@ export async function whisperVideoAction(
onLog,
signal,
...(salvage !== undefined ? { salvage } : {}),
+ ...(whilePaused ? { whilePaused: true } : {}),
});
safeRevalidate([
`/channels/${slug}/videos/${videoId}`,
diff --git a/editor/e2e/find-clips.spec.ts b/editor/e2e/find-clips.spec.ts
@@ -0,0 +1,139 @@
+import { test, expect } from "@playwright/test";
+import http from "node:http";
+import type { AddressInfo } from "node:net";
+import { mkdir, rm, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { resetData, testPaths, writeSettings } from "./helpers";
+import { umtoolOriginFile } from "./servers";
+
+// FIND CLIPS (release 36, lane A) on the video page, end to end over a STUB
+// umtool started here and named to the test server through
+// E2E_UMTOOL_ORIGIN_FILE (e2e/servers.ts, common/lib/umtoolUrl.ts). The
+// fixture video already holds everything the chain makes — the source
+// container, the transcript, words.json, the chat replay, diarization.json —
+// so every editor step is skipped (each named in the log) and the job goes
+// straight to umtool's clips route: the worker token, the contract's body,
+// the job followed. Then the panel links the project and lists the segments,
+// and "Find clips in this part" posts again with that segment.
+
+const SLUG = "test-transcribe";
+const ID = "vidFC";
+
+type Call = { method: string; url: string; auth: string | undefined; body: Record<string, unknown> | null };
+
+let server: http.Server;
+let origin = "";
+const calls: Call[] = [];
+
+test.beforeAll(async () => {
+ server = http.createServer((req, res) => {
+ let raw = "";
+ req.on("data", (c) => (raw += c));
+ req.on("end", () => {
+ const body = raw ? (JSON.parse(raw) as Record<string, unknown>) : null;
+ calls.push({ method: req.method ?? "", url: req.url ?? "", auth: req.headers.authorization, body });
+ res.setHeader("content-type", "application/json");
+ if (req.method === "POST" && req.url === "/api/report/clips") {
+ const segment = typeof body?.segment === "string" ? body.segment : null;
+ res.end(
+ JSON.stringify({
+ ok: true,
+ jobId: segment ? "u2" : "u1",
+ job: { id: segment ? "u2" : "u1" },
+ project: segment ? `vidfc-clips-${segment}` : "vidfc-clips",
+ created: true,
+ segment: segment ?? "s1",
+ href: `/projects/${segment ? `vidfc-clips-${segment}` : "vidfc-clips"}/clips`,
+ notes: [],
+ segments: [
+ { id: "s1", from: 290, to: 6300, why: "subject 4 holds 81% of long-turn time" },
+ { id: "s2", from: 6500, to: 9278, why: "subject 16 holds 77% of long-turn time" },
+ ],
+ }),
+ );
+ return;
+ }
+ if (req.method === "GET" && req.url?.startsWith("/api/report/clips?job=")) {
+ res.end(JSON.stringify({ state: "done", log: ["propose: 9 clips, 598 s"], next: 1 }));
+ return;
+ }
+ res.statusCode = 404;
+ res.end(JSON.stringify({ error: "no such route" }));
+ });
+ });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+});
+
+test.afterAll(async () => {
+ await rm(umtoolOriginFile(testPaths().transcriptsDir), { force: true });
+ await new Promise<void>((r) => server.close(() => r()));
+});
+
+test("Find clips: every step skipped, umtool asked with the token, the project linked and its segments listed", async ({ page }) => {
+ test.setTimeout(120_000);
+ await resetData("one-transcribe-channel");
+ await writeSettings({ minFreeDiskGB: 0 });
+ const videoDir = join(testPaths().transcriptsDir, "channels", SLUG, "data", ID);
+ await mkdir(videoDir, { recursive: true });
+ await writeFile(
+ join(videoDir, "metadata.info.json"),
+ JSON.stringify({ id: ID, title: "Synthetic reaction stream", webpage_url: `https://www.youtube.com/watch?v=${ID}`, was_live: true, duration: 9278 }),
+ );
+ await writeFile(join(videoDir, "source-media.mp4"), "container");
+ await writeFile(join(videoDir, "transcript.json"), JSON.stringify({ transcription: [] }));
+ await writeFile(join(videoDir, "words.json"), JSON.stringify({ version: 1, words: [{ w: "hello", start: 1, end: 1.4 }] }));
+ await writeFile(join(videoDir, "transcript.live_chat.json"), "\n");
+ await writeFile(join(videoDir, "live_chat.cues.json"), JSON.stringify({ version: 1, source: "live_chat", cues: [] }));
+ await writeFile(join(videoDir, "diarization.json"), JSON.stringify({ speakers: [], turns: [] }));
+ await writeFile(umtoolOriginFile(testPaths().transcriptsDir), origin);
+
+ await page.goto(`/channels/${SLUG}/videos/${ID}`);
+ const panel = page.getByRole("region", { name: "find-clips panel" });
+ await expect(panel.getByLabel("find-clips status")).toHaveText("not run yet");
+ await panel.getByLabel("target length (minutes)").fill("10");
+ await panel.getByRole("button", { name: "Find clips", exact: true }).click();
+ const out = page.getByLabel(`Find clips in ${ID} output`);
+ await expect(out).toContainText("@@find-clips", { timeout: 60_000 });
+ for (const line of [
+ "skipped: saved video — saved video present",
+ "skipped: corpus transcript — transcript.json present",
+ "skipped: word timings — words.json present (1 words)",
+ "skipped: chat replay — live_chat.cues.json present",
+ "skipped: diarization — diarization.json present",
+ "running: umtool — finding the segments and the clips",
+ "umtool: propose: 9 clips, 598 s",
+ ]) {
+ await expect(out).toContainText(line);
+ }
+
+ // umtool was asked as the contract says.
+ const post = calls.find((c) => c.method === "POST");
+ expect(post?.auth).toBe("Bearer test-worker-token");
+ expect(post?.body).toEqual({
+ mode: "new",
+ slug: "vidfc-clips",
+ from: `${SLUG}/${ID}`,
+ target: 600,
+ scope: "auto",
+ wordsPath: join(videoDir, "words.json"),
+ });
+
+ await page.reload();
+ const result = panel.getByLabel("find-clips result");
+ await expect(result.getByRole("link", { name: "vidfc-clips", exact: true })).toHaveAttribute("href", `${origin}/projects/vidfc-clips/clips`);
+ const segments = panel.getByRole("list", { name: "segments found" });
+ await expect(segments.getByRole("listitem")).toHaveCount(2);
+ await expect(segments).toContainText("s1 4:50–1:45:00");
+ await expect(segments).toContainText("s2 1:48:20–2:34:38");
+ await expect(panel.getByLabel("find-clips status")).toContainText("2 segments");
+
+ // One part: posts again with that segment (the target typed again: a
+ // reload clears the field).
+ await panel.getByLabel("target length (minutes)").fill("10");
+ await segments.getByRole("listitem").nth(1).getByRole("button", { name: "Find clips in this part", exact: true }).click();
+ await expect(page.getByLabel("Find clips in segment s2 output")).toContainText("@@find-clips", { timeout: 60_000 });
+ const second = calls.filter((c) => c.method === "POST")[1];
+ expect(second?.body).toMatchObject({ mode: "new", slug: "vidfc-clips-s2", segment: "s2", target: 600 });
+ expect(second?.body).not.toHaveProperty("scope");
+});
diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts
@@ -52,6 +52,11 @@ export function blueskyOriginFile(transcriptsDir: string): string {
return join(transcriptsDir, ".fake-bluesky-origin");
}
+/** The file naming a slot's stub umtool (common/lib/umtoolUrl.ts; find-clips.spec). */
+export function umtoolOriginFile(transcriptsDir: string): string {
+ return join(transcriptsDir, ".fake-umtool-origin");
+}
+
/** The slot's recorded Odysee page reads (browser-lookup.spec writes it). */
export function odyseePageFixtureFile(transcriptsDir: string): string {
return join(transcriptsDir, ".fake-odysee-pages.json");
@@ -205,6 +210,8 @@ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env)
// Where a spec names its fake Bluesky's origin (capture-posts.spec): the
// slot's own test data, so two slots never share one.
editorEnv.E2E_BLUESKY_ORIGIN_FILE = blueskyOriginFile(paths.transcriptsDir);
+ // The same for the stub umtool find-clips.spec starts (lib/umtoolUrl.ts).
+ editorEnv.E2E_UMTOOL_ORIGIN_FILE = umtoolOriginFile(paths.transcriptsDir);
// The browser lookup's recorded page reads (browser-lookup.spec): set on
// every slot, so the e2e server never opens a headless browser on the
// network — the player-page opener refuses under it too.
diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts
@@ -34,6 +34,10 @@ import { currentSlot } from "./e2e/testPaths";
// writes its fake Bluesky's loopback origin into,
// which the AppView, bsky.app and the image CDN
// then are (common/social/blueskyEndpoints.ts)
+// E2E_UMTOOL_ORIGIN_FILE set per slot (e2e/servers.ts): the file a spec
+// writes its stub umtool's loopback origin into,
+// which Find clips then posts to
+// (common/lib/umtoolUrl.ts; find-clips.spec)
// E2E_ODYSEE_PAGE_FIXTURE set per slot (e2e/servers.ts): the file of
// recorded Odysee page reads the browser lookup
// answers from (browser-lookup.spec); while it is
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -10889,3 +10889,56 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
(`?replace=1` with `--replace`) on `--url` > `UMTOOL_URL` > `http://localhost:3050`, Bearer `WORKER_TOKEN` when set;
polls `?job=&since=&sinceEvent=` every 1.5 s printing the log; SIGINT posts `?cancel=<job>` (a second Ctrl-C exits
130); exit 0 only for `done`. Without `--run` unchanged (prints the chain).
+
+
+## Release 36 lane A: Find clips, run while paused, one video's chat (verified 2026-10-19, branch `r36/find-clips`)
+
+- **Run while paused**: `WorkerPool.acquire(signal, {whilePaused: true})` may lease a worker that is `disabled`
+ while `pausedSnapshot.get(id) === "enabled"` (the pause ALONE switched it off; `pauseHeld`), still `!degraded`,
+ `!busy`. The snapshot is only read: the lease leaves `state: "disabled"`, so release leaves it paused and
+ `resumeAll` restores it as before. A hand disable/drain during a pause writes `disabled` into the snapshot
+ (`syncSnapshot`), so it is never leased. `pauseHeldIds()` lists them. Carried by `transcribeWithWorker
+ ({whilePaused})`, `transcribe-file` body `whilePaused` (TRANSCRIBE_FILE_BODY_KEYS; a named worker in
+ `pauseHeldIds` is not refused), `transcribe-one` body `whilePaused` (→ `transcribeOneAction`/`whisperVideoAction`
+ 6th arg). Lanes/batches never pass it.
+- **`fetch-chat {slug, id, queueKey?}`** (`common/controller/fetchLiveChat.ts`): `liveChatPlan` →
+ `fresh` (isLiveChatCuesFresh) | `normalize` (raw `transcript.live_chat.json` + metadata here, cues stale: no
+ network) | `no-fetcher` (detectPlatform(url) ∉ {youtube} → `"no chat fetcher for <platform>: only YouTube's chat
+ replay is fetched"`) | `not-live` (metadata `live_status: "not_live"` and not `was_live`) | `fetch` | `refused`.
+ The job (`fetch-chat`, platform download queue, `needsMedia`, ingest) runs `liveChatOnlyArgs(config, cookies, url,
+ pace?)` — exported from `ytdlp/downloadOneManaged.ts`, the chat-only pass's argv (channelExtraArgs: cookies + live
+ `--sleep-requests`) — with the metadata refresh's cookie retry, backoff on rate_limit, `recordPlatformClean`, then
+ `normalizeLiveChat({force: true})`. fresh / no-fetcher / not-live / held / cooldown are `{ok: false, info: true}`
+ before a job; a pass that writes nothing ends `done` ("No chat replay for <id>").
+- **`find-clips {slug, id, target?, segment?, project?, whilePaused?, dryRun?}`** (`common/controller/findClips.ts`,
+ job kind `find-clips`, queue `find-clips`, `needsMedia`). Steps in order, each `skipped:`/`running: <label> — why`:
+ `persist` (saved-video pointer or a source container → skip; else `persist-videos {items}`), `transcript`
+ (transcript.json or an English VTT → skip; else `transcribe-one {slug, id, whilePaused?}`), `words`
+ (`data/<id>/words.json` with ≥1 word → skip; else `runTranscribeFile({path: audio|container|saved, words: true,
+ whilePaused?})` IN the job, written without `cues`/`text`; 0 words → not written, no `wordsPath`), `chat`
+ (liveChatPlan fetch/normalize → `fetch-chat`; a refusal/failure is logged and the chain goes on), `diarization`
+ (`diarization.json` → skip; off/unconfigured → fail; backfill lane held and !whilePaused → fail; held + whilePaused
+ → `diarizeOneVideo` in the job; else `runBackfillChannelJob({kindIds: ["diarization"], ids: [id]})` awaited),
+ `umtool`. The editor steps go through `findClipsEditor` (`editor/app/api/ops/_researchEditor.ts`, the in-process
+ ops door) and are waited on via `jobOfPaths`. A paused pool without whilePaused, or paused with no
+ `pauseHeldIds`, fails the transcription steps at once.
+- **The umtool call** (lane B's route): `POST ${umtoolUrl()}/api/report/clips` with `authorization: Bearer
+ WORKER_TOKEN`, body `{mode: "new", slug: <project ?? projectSlugFor(id, segment)>, from: "<slug>/<id>", target?,
+ segment? | scope: "auto", wordsPath?}` → reads `jobId` (or `job.id`), `project`, `created` (≠ false), `segments`
+ `[{id, from, to, subject?, host?, why?}]`, `segment` (the chosen one, recorded when none was asked), `href`
+ (`/projects/<id>/clips`, the record's url), `notes[]` (logged `umtool: note: …`); a 409 carrying `running` (umtool
+ busy) is asked again every 30 s up to an hour, any other 409 (slug exists) refuses; then `GET ?job=<id>&since=<n>` every 2 s, relaying `log[]` as
+ `umtool: <line>`, `next` the cursor, until `state !== "running"` (`done` ok, else `error`); 15 failed polls or a
+ 404 fail the step; cancel posts `?cancel=<job>`. `projectSlugFor("fGSRhEWc9M4", "s2")` = `fgsrhewc9m4-clips-s2`.
+ `umtoolUrl()` (`common/lib/umtoolUrl.ts`) = `UMTOOL_URL` minus trailing slashes, or the loopback origin in
+ `E2E_UMTOOL_ORIGIN_FILE` (test only).
+- **Two new sidecars** (in `SIDECAR_FILENAMES`, 17 now): `words.json` (`lib/wordTimings-server.ts`; the
+ TranscribeFileResult shape minus cues/text — umtool reads `doc.words`) and `find-clips.json`
+ (`lib/findClipsRecord-server.ts`: `{version: 1, at, jobId, project, url (<umtool>/projects/<p>/clips), created,
+ segment?, segments, steps: [{id, label, action: "ran"|"skipped", why}]}`, overwritten per run). The log ends
+ `@@find-clips {record…, umtoolJob}` (FIND_CLIPS_RESULT_MARKER; `pnpm ops find-clips --wait` prints it).
+- **The video page**: `FindClipsPanel` (section `find-clips panel`, after the frame scan, before the registry
+ panels): target minutes, "Run while paused" when `holds` (pool paused, backfill held) is non-empty, `Find clips`
+ (disabled + `find-clips off` line without umtoolUrl), then the record's project link and `segments found` with
+ `Find clips in this part` each. The Transcribe row's `Transcribe now (workers paused)` shows while the pool is
+ paused. Media tools → `Fetch live chat`.
diff --git a/plans/release-36/find-clips.md b/plans/release-36/find-clips.md
@@ -0,0 +1,114 @@
+# Release 36 lane A — `r36/find-clips`: one button on the video page (as shipped)
+
+Release 35 ran the clip finder's chain from a shell, step by step, and forced two transcriptions through a PAUSED
+worker pool by hand. This lane makes the chain one job and one button: **Find clips** on the video page (`pnpm ops
+find-clips`), a run-while-paused path for one manual transcription, and a chat-replay fetch for one video. Rulings
+followed: the UI works with no model (nothing here calls one); every CLI operation added has a button; no yt-dlp or
+ASR by hand (every step is an editor job or a worker lease); paced YouTube requests; plain words, no lead paragraphs;
+synthetic fixtures only; commits end with the one Co-Authored-By trailer.
+
+## What
+
+1. **Run while paused** — `common/jobs/workerPool.ts`: `acquire(signal, {whilePaused: true})` may lease a worker the
+ pause-all ALONE switched off: the pool is paused, the worker is `disabled`, and its `pausedSnapshot` entry is
+ `enabled` (`pauseHeld`). Never one drained, degraded or disabled by hand (a hand control during a pause writes
+ `disabled` into the snapshot; a degrade mark fails eligibility on its own). The snapshot is only read: the lease
+ leaves the worker `disabled`, so when it releases the worker is still paused and `resumeAll` restores it exactly as
+ before. `pauseHeldIds()` lists them. The flag rides `transcribeWithWorker({whilePaused})`, the `transcribe-file`
+ body (`pnpm ops transcribe`; a NAMED worker the pause holds is not refused when the request is whilePaused) and the
+ `transcribe-one` body (both of its forms). Lane and batch acquires never pass it. The video page's Transcribe row
+ shows **Transcribe now (workers paused)** while the pool is paused.
+2. **Chat replay for one video** — `common/controller/fetchLiveChat.ts`, `pnpm ops fetch-chat {slug, id}`, Media
+ tools → **Fetch live chat**. `liveChatPlan` decides from the disk and the metadata: fresh cues → skip; the raw
+ replay here with stale cues → normalize only (no network); a platform other than YouTube → "no chat fetcher for
+ <platform>: only YouTube's chat replay is fetched"; `live_status: "not_live"` → never live. A fetch runs the
+ managed download's chat-only argv (`liveChatOnlyArgs`, now exported from `ytdlp/downloadOneManaged.ts`: the
+ channel's cookies and the platform's live pace) on the platform's DOWNLOAD queue, with the held-platform and
+ cooldown refusals, the cookie retry, the backoff record and the clean-pass settle the metadata refresh uses, then
+ `normalizeLiveChat`. The skips are `{ok: false, info: true}` before any job; a pass that writes nothing ends `done`.
+3. **Find clips** — `common/controller/findClips.ts`, job kind `find-clips` on its own `find-clips` queue. In order,
+ each step skipped when its output exists and named in the log (`skipped: <step> — why` / `running: <step> — why`):
+ persist the source (`persist-videos`), the corpus transcript (`transcribe-one`, whilePaused passed), word timings
+ (the file transcription with words IN the job, into `data/<id>/words.json`), the chat replay (`fetch-chat`; a
+ refusal or failure is logged and the chain goes on), diarization (the backfill lane's one-video run; past a held
+ lane only with whilePaused, in the job), then umtool: `POST ${UMTOOL_URL}/api/report/clips` with the worker token,
+ `{mode: "new", slug: <project>, from: "<slug>/<id>", target?, scope: "auto" | segment, wordsPath}`, and `GET
+ ?job=<id>` followed to the end with its log relayed. The editor steps go through the editor's own ops actions in
+ process (`findClipsEditor`, the research run's door) and are waited on; the job never sits on a queue a step needs.
+ What would park a step forever fails it at once with where to fix it: a paused pool without whilePaused (or with
+ no worker the pause alone holds), diarization switched off or unconfigured, a held backfill lane without
+ whilePaused. umtool down, refusing or failing fails the umtool step naming the URL or umtool's error. The log ends
+ `@@find-clips {json}`; `data/<id>/find-clips.json` keeps the project, its clip editor URL (umtool's `href`), the
+ segment (the one asked, else auto-scope's), the segments and the steps for the page. A `dryRun` answers each
+ step's plan. Lane B's final route: a 409 naming umtool's running job is asked again every 30 s (up to an hour);
+ any other 409 (the slug exists) refuses; its `notes` are logged. `pnpm ops get workers` marks the workers a
+ whilePaused job may take (`pauseHeld: true`).
+4. **The video page** — `FindClipsPanel`: a target length (minutes), **Run while paused (this video only)** when
+ something holds a step (the pool paused, the backfill lane held — named in a status line), **Find clips**
+ (disabled with "UMTOOL_URL is not set on the editor…" without one), and after a run the project linked and the
+ segments found, each with **Find clips in this part** (posts again with `segment`).
+
+## Interfaces
+
+- `WorkerPool.acquire(…, {whilePaused?})`, `WorkerPool.pauseHeldIds()`; `TranscribeWithWorkerOptions.whilePaused`;
+ `TranscribeFileRequest.whilePaused`, `TRANSCRIBE_FILE_BODY_KEYS` + `"whilePaused"`; `transcribeOneAction(…,
+ salvage, whilePaused)`, `whisperVideoAction(…, storedUrl, whilePaused)`.
+- `liveChatOnlyArgs(config, cookies, url, pace?)`; `liveChatPlan`, `fetchLiveChat`, `runFetchChatJob`,
+ `FETCH_CHAT_JOB_KIND`, `CHAT_PLATFORMS`, `noChatFetcherSentence`.
+- `parseFindClipsBody`, `inspectFindClips`, `planFindClipsSteps`, `runFindClips`, `enqueueFindClips`,
+ `projectSlugFor`, `umtoolProjectUrl`, `FIND_CLIPS_JOB_KIND`, `FIND_CLIPS_QUEUE`, `FIND_CLIPS_RESULT_MARKER`,
+ `FIND_CLIPS_BODY_KEYS`; `umtoolUrl()` (`common/lib/umtoolUrl.ts`); sidecars `words.json`
+ (`lib/wordTimings-server.ts`) and `find-clips.json` (`lib/findClipsRecord-server.ts`).
+- Routes: `POST /api/ops/fetch-chat`, `POST /api/ops/find-clips`; `transcribe` / `transcribe-one` take
+ `whilePaused`. umtool's clips route is lane B's; this lane calls it exactly as the plan's contract says.
+
+## Files
+
+common: `jobs/workerPool.ts`, `jobs/workerPool.whilePaused.test.ts`, `jobs/jobKinds.ts` (fetch-chat, find-clips),
+`controller/transcribeOne.ts`, `controller/transcribeFile.ts` (+ test), `controller/fetchLiveChat.ts` (+ test),
+`controller/findClips.ts` (+ test), `ytdlp/downloadOneManaged.ts` (the argv builder exported), `lib/umtoolUrl.ts`,
+`lib/wordTimings-server.ts`, `lib/findClipsRecord-server.ts`, `lib/sidecar-server.test.ts`, `lib/envVars.ts`.
+editor: `app/api/ops/{fetch-chat,find-clips}/route.ts`, `app/api/ops/_findClips.ts`, `app/api/ops/_researchEditor.ts`
+(findClipsEditor), `app/api/ops/{transcribe,transcribe-one}/route.ts`, `app/api/ops/_door.test.ts`, the video page
+(`page.tsx`, `videoActions.ts`, `mediaToolsActions.ts`, `findClipsActions.ts`, `components/FindClipsPanel.tsx`,
+`components/VideoMediaTools.tsx`, `components/VideoPanel.tsx`, `components/cards/PerFileTranscribeRow.tsx`),
+`e2e/find-clips.spec.ts`, `e2e/servers.ts` (E2E_UMTOOL_ORIGIN_FILE), `playwright.config.ts`.
+scripts: `archilyzer-ops.mjs` (+ test). Docs: COMMANDS.md, ENVIRONMENT.md (regenerated), OPERATING.md ("Find clips in
+a recording"), editor/CHANGELOG.md, plans/FACTS.md.
+
+## Gates
+
+All from the worktree root, through the session lock. Counts at the branch's start (main `0d471989`) → before the
+merge of main (lane B, `8938a5dd`) → after it:
+
+| Gate | Start | Before merge | After merge |
+|---|---|---|---|
+| tsc (`pnpm -r … exec tsc --noEmit`) | — | clean | clean |
+| common (`pnpm --filter yt-dlp-transcript-common test`) | 4657 (4655 pass, 2 skipped) | 4674 (4672 pass, 2 skipped) | 4688 (4686 pass, 2 skipped) |
+| editor unit (`pnpm --filter editor test`) | 346 | 346 | 346 |
+| test:scripts | 1255 (1251 pass, 4 skipped) | 1256 (1252 pass, 4 skipped) | 1264 (1260 pass, 4 skipped) |
+| docs cli / env / files, settings example `--check` | — | clean (COMMANDS.md, ENVIRONMENT.md regenerated) | clean |
+
+New unit tests: `jobs/workerPool.whilePaused.test.ts` (6), `controller/fetchLiveChat.test.ts` (6),
+`controller/findClips.test.ts` (9: every step run, every step skipped, umtool down / refusing / failing / slug taken,
+umtool busy then free, twitch chat skip + refused chat fetch, paused pool, diarization off / lane held / whilePaused
+inline / inline failure, dry run + refusals + the job's record and marker), `lib/umtoolUrl.test.ts` (1), three in
+`transcribeFile.test.ts` (whilePaused parse, the named pause-held worker, a paused pool running a whilePaused job),
+the sidecar enumeration (17), the door's traversing slug for fetch-chat and find-clips, the ops client's usage and
+marker.
+
+Editor e2e (start mode; the e2e build 894 s including the wait for the machine's heavy slot):
+`find-clips.spec.ts` 1 passed (17.5 s); `video-page.spec.ts` + `workers.spec.ts` 30 passed (57.6 s);
+after the merge of main (lane B) and the contract alignment, `find-clips.spec.ts` again: 1 passed (11.4 s; the
+rebuild took 2210 s, nearly all of it waiting for the machine's heavy slot).
+
+A common-suite run once hung over 11 minutes in `controller/seeder.test.ts` (webtorrent); it was stopped and the
+next run was clean. Not this lane's file.
+
+## Found and left
+
+- The word-timings transcription cuts its 16 kHz WAV under the OS temp dir (`runTranscribeFile`, as `pnpm ops
+ transcribe` always has): about 300 MB for a 2.5-hour recording, in RAM where `/tmp` is a tmpfs, for the length of the
+ transcription. Not changed here; the live editor's `TMPDIR` decides.
+- The backfill lane's one-video run (the diarization panel's Run) is held by the lane's gate like the sweep is; Find
+ clips says so and offers whilePaused rather than waiting. The panel's own Run is unchanged.
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -41,6 +41,10 @@
// pnpm ops sync --json '{"slug":"the-quartering"}' --wait
// pnpm ops metadata-scan --json '{"slug":"the-quartering"}'
// pnpm ops refresh-metadata --json '{"slug":"the-quartering","id":"<videoId>"}' --wait
+// pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait
+// pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'
+// pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait
+// pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait
// pnpm ops browser-lookup --json '{"slug":"demo-odysee","ids":["<claimId>"]}' --wait
// pnpm ops browser-lookup --json '{"slug":"demo-odysee","listing":true,"scrolls":5}' --wait
// pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait
@@ -491,6 +495,15 @@ const ACTIONS = [
// scope?, max?, force?}); one audio-audit job per channel. The damaged ones
// are the report's corruptHeldAudio bucket, which retry-bucket refetches.
"audio-audit",
+ // THE CLIP FINDER, ROUND TWO (release 36, lane A): one video's live chat
+ // replay alone ({slug, id}), paced, into live_chat.cues.json, as a fetch-chat
+ // job on the platform's download queue. And the clip finder's chain for one
+ // video ({slug, id, target?, segment?, project?, whilePaused?, dryRun?}):
+ // persist, transcript, word timings, chat, diarization, umtool — each step
+ // skipped when its output exists — as a find-clips job. With --wait the
+ // result JSON (the project, its URL, the segments) is what stdout carries.
+ "fetch-chat",
+ "find-clips",
];
// The log line a transcribe job ends with: this marker, then the result as
@@ -518,6 +531,9 @@ export const MIRROR_SCAN_RESULT_MARKER = "@@mirror-scan ";
// The same for a remote listing (REMOTE_LISTING_RESULT_MARKER in
// common/controller/remoteListing.ts).
export const REMOTE_LISTING_RESULT_MARKER = "@@remote-listing ";
+// The same for Find clips (FIND_CLIPS_RESULT_MARKER in
+// common/controller/findClips.ts).
+export const FIND_CLIPS_RESULT_MARKER = "@@find-clips ";
// The provenance a tag write from this CLI carries. Everything else ignores it.
function agentSource() {
@@ -745,6 +761,7 @@ export function parseArgs(argv) {
...(action === "bench-verdicts" ? { resultMarker: BENCH_VERDICTS_RESULT_MARKER } : {}),
...(action === "frame-scan" ? { resultMarker: FRAME_SCAN_RESULT_MARKER } : {}),
...(action === "mirror-scan" ? { resultMarker: MIRROR_SCAN_RESULT_MARKER } : {}),
+ ...(action === "find-clips" ? { resultMarker: FIND_CLIPS_RESULT_MARKER } : {}),
...(action === "report-schedule" ? { resultMarker: REPORT_TICK_RESULT_MARKER } : {}),
wait,
quiet,
@@ -968,6 +985,9 @@ export function usage() {
' reads it — no page request with "only", the page first with "fallback" —',
' through the audio check; one new file per platform per 20 min. Absent =',
' the channel\'s storedUrlDownloads.',
+ ' "whilePaused": true runs this one transcription during a pause-all on a',
+ ' worker the pause alone switched off; the pause stays on (the video page\'s',
+ ' "Transcribe now (workers paused)").',
"",
'delete-file deletes one file of one video, as its Files list does:',
' {"slug", "id", "file"}. A tiered media file goes with its bytes on the',
@@ -1128,6 +1148,27 @@ export function usage() {
' {"slug", "confirm"} — "confirm" must repeat the slug. No undo outside the',
' transcripts/ repo\'s own history.',
"",
+ 'fetch-chat fetches ONE video\'s live chat replay and nothing else: {"slug",',
+ ' "id"} — the chat-only yt-dlp pass (the channel\'s cookies, the platform\'s',
+ " pace) on the platform's download queue, then live_chat.cues.json. YouTube",
+ ' only: another platform answers "no chat fetcher for <platform>" (info, no',
+ " job), as do a chat already here and fresh and a video never live. A pass",
+ " that finds no replay ends done and says so.",
+ "",
+ 'find-clips runs the clip finder\'s chain for ONE video as one job: {"slug",',
+ ' "id", "target"? (the cut\'s seconds), "segment"? (one umtool found, "s2"),',
+ ' "project"? (the umtool project a run makes), "whilePaused"?, "dryRun"?}.',
+ " Persist the source video, the corpus transcript, word timings",
+ " (data/<id>/words.json), the chat replay (YouTube), diarization — each step",
+ " skipped when its output exists, named in the log — then umtool's clip",
+ ' finder (POST UMTOOL_URL/api/report/clips {mode: "new"}), followed to the',
+ " end. \"whilePaused\": true runs this one video past the holds: the two",
+ " transcriptions during a pause-all on a worker the pause alone switched",
+ " off, and its diarization in the job when the backfill lane is held.",
+ " \"dryRun\": true answers each step's",
+ " plan and starts nothing. With --wait the result — {project, url, created,",
+ " segments: [{id, from, to, why}], steps} — is printed on stdout.",
+ "",
'refresh-metadata re-reads ONE video\'s metadata.info.json from its source',
' (no subtitles, no media) on the platform\'s queue: {"slug", "id"}. The',
' job\'s log ends with what the source now says — live_status, formats,',
@@ -1291,6 +1332,9 @@ export function usage() {
" cues: [{start, end, text}], text, ...}, cue times on the file's own clock.",
' "words": true adds words: [{w, start, end, conf?}] on the same clock -- from',
" parakeet, which keeps its word timestamps; [] from an engine that does not.",
+ ' "whilePaused": true runs it during a pause-all on a worker the pause alone',
+ " switched off (never one drained, degraded or disabled by hand); the pause",
+ " stays on.",
" With --wait it is printed on stdout (the response and the log go to",
" stderr), so `pnpm ops transcribe ... --wait | jq -r .text` works.",
"",
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -6,6 +6,7 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
+ FIND_CLIPS_RESULT_MARKER,
REMOTE_LISTING_RESULT_MARKER,
TRANSCRIBE_RESULT_MARKER,
TTS_RESULT_MARKER,
@@ -810,6 +811,21 @@ test("the archival writes are POSTs to their routes, each named in the usage", (
assert.match(usage(), /"publish", "enabled"\?, "held"\?, "action"\?/);
});
+// RELEASE 36 LANE A: the clip finder's chain and one video's chat replay.
+test("fetch-chat and find-clips are POSTs named in the usage; find-clips --wait carries its marker", () => {
+ for (const action of ["fetch-chat", "find-clips"]) {
+ const p = parseArgs([action, "--json", '{"slug":"x","id":"y"}']);
+ assert.equal(p.method, "POST", action);
+ assert.equal(p.path, `/api/ops/${action}`, action);
+ assert.match(usage(), new RegExp(`^${action} `, "m"), action);
+ }
+ const w = parseArgs(["find-clips", "--json", '{"slug":"x","id":"y"}', "--wait"]);
+ assert.equal(w.resultMarker, FIND_CLIPS_RESULT_MARKER);
+ assert.equal(FIND_CLIPS_RESULT_MARKER, "@@find-clips ");
+ assert.match(usage(), /"whilePaused": true runs this one video past the holds/);
+ assert.match(usage(), /no chat fetcher for <platform>/);
+});
+
test("get remote-listing posts the job, waits, and carries the result marker", () => {
const r = parseArgs(["get", "remote-listing", "demo-odysee"]);
assert.equal(r.method, "POST");