commit 31a948b6357fd72f522b4345b0035de0df569293
parent fb7c3588fbca56ed84a7411cdb086eb972a1d3db
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 25 Oct 2026 01:22:14 -0400
Merge lane/whisper-handoff: a whisper-video holds the platform queue only for its download (the transcription is handed off to the video's own transcribe-one queue); ops transcribe-one runs held audio on that queue; a YouTube video with captions asked for ASR fetches the captions instead unless asr: true; a download that lands over a saved container keeps both, flagged for a check
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
39 files changed, 1878 insertions(+), 203 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -145,7 +145,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `tags` | tags edits the curated-tag vocabulary through its one writer: {"op": "define", "tag": {...}} (the WHOLE definition: id, label, rules and "sites", the sites it exists on, absent = every site) or {"op": "remove", "tag": "<id>"}. `get tags [<id>]` reads it. | `pnpm ops tags --json '{"op":"define","tag":{"id":"eva-collab","label":"Collab"}}'` |
| `tag-videos` | tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos in ONE write: {"tag", "op": "add" \| "remove" \| "suppress" \| "unsuppress", "videos": \[{"slug", "id"}, ...\]}. "remove" unpins only — a rule's hit survives; "suppress" rejects it. The write records who asked (ARCHILYZER\_AGENT); a big list goes in --file. | `pnpm ops tag-videos --file ids.json` |
| `keep-videos` | keep-videos sets the "Do not clean" marker on every held video of a channel whose title or description matches a download-filter pattern: {"slug", "match", "fields"?: \["title" \| "description"\], "note"?, "dryRun"?}. A match not held is reported in "notDownloaded", never created; a fresh channel wants metadata-scan first. Or by id: {"slug", "ids": \[...\], "note"?, "dryRun"?} — a held video is marked now, one not held yet (a live stream, a VOD not fetched) is PENDING and marked when its record is first written (a download, an import, a recording); "pendingAll" lists the channel's pending ids. | `pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'` |
-| `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` |
+| `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. Over a copy already in the store (an import, an attach, a live recording or an earlier download) the download becomes the active one and the old copy is kept beside it, flagged for a check (`get saved-alternates`); nothing is deleted. | `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". "minGapSeconds" (items only, 30–3600) sets this run's pause between two fetches in place of the platform's floor (Rumble's 120 s); still jittered up to half again. Shorter than the default risks Rumble's IP-wide Cloudflare challenge; a Retry keeps it. A window on a whole-recording platform (settings.clips .wholeRecordingPlatforms, default Rumble) is not seeked: the video is saved whole once, as "Persist source video" saves it, on the platform's download queue, and its windows are cut from it — a remote Rumble seek put the picture 1-4 s off the sound. A failed whole download fails its windows with the download's message. "wholeRecording": false fetches every window of the run by a remote seek instead. A fetched window whose picture still runs off its sound is set aside (<from>-<to>.desynced.<ext>) and fails; a held one is set aside and fetched again (check-windows). | `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. "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` |
@@ -156,7 +156,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `dismiss-service` | — | |
| `rerun-service-jobs` | — | |
| `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. "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)"). | |
+| `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. Only a download waits on the platform's queue: the transcription runs as a transcribe-one job on the video's own queue (transcribe-one:<slug>:<id>), at once when nothing is downloaded, else handed off by the whisper-video once the audio is down. A job; --wait follows it through the hand-off to the end of the transcription. "queueKey" names another queue. A youtube-handling video with no audio whose metadata lists English captions has those fetched instead ({"instead": "captions", "message"}, the job the caption download), one with an English caption track on disk is refused; "asr": true transcribes it anyway (no "file"). "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` |
@@ -203,6 +203,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait]
pnpm ops job wait <id>... [--wait-timeout <seconds>]
pnpm ops get settings [<key>]
pnpm ops get storage | sites | workers | auto-queue | scheduler
+ pnpm ops get saved-alternates [<slug>]
pnpm ops get services
pnpm ops get cleanup <slug>
pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]
@@ -237,6 +238,13 @@ job <verb> <id>... is a /jobs row's button: cancel (a running job is
get settings [<key>] is settings.json as the editor reads it (migrated and
defaulted; a secret is "<redacted>"), or one top-level key of it.
get storage is /storage: each location, mounted or not, free space, tiers.
+get saved-alternates [<slug>] lists every saved video holding two copies:
+ a download over a container already in the store keeps both — an
+ explicit persist (persist-videos, Persist source video, a whole-recording
+ fetch) makes the download active, any other keeps the saved one unless
+ the download is longer — and the other stays beside it as
+ source-media.alt-<h>p-<stamp>.<ext>, flagged for a check. Each video:
+ its line, the active copy, the alternates (height, seconds, origin).
get sites lists every site: id, title, siteUrl, Pages project, audience,
listed, search, publish policy, channels, citedChannels. (`get publish`
is the status.)
diff --git a/common/controller/archiveOrgDownload.ts b/common/controller/archiveOrgDownload.ts
@@ -474,6 +474,7 @@ export async function downloadArchiveOrgManaged(
origin: opts.persistOrigin,
extractAudio: !keepTranscript,
sourceFilename: sourceName,
+ explicitPersist: opts.explicitPersist,
onLog: opts.onLog,
signal: opts.signal,
});
diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts
@@ -344,6 +344,7 @@ async function saveWholeRecordingManaged(o: SaveWholeRecordingOpts): Promise<Sav
appendArchive: true,
keepSourceVideoOverride: true,
forceMedia: true,
+ explicitPersist: true,
persistOrigin: o.origin,
persistFormatPreset: resolveSourceVideoQuality({
channel: o.config.sourceVideoQuality,
diff --git a/common/controller/findClips.ts b/common/controller/findClips.ts
@@ -248,8 +248,10 @@ export type FindClipsDeps = {
// 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>;
+ // An editor job's state (researchRuns.ts jobOfPaths) — its WORK's: a job
+ // that handed its work on (a whisper-video's transcription, queued as its own
+ // transcribe-one job) answers with that job's state, `via` naming it.
+ jobOf: (id: string) => Promise<{ status: string; via?: string } | null>;
umtoolUrl?: string | null;
workerToken?: string;
fetch?: typeof fetch;
@@ -299,9 +301,14 @@ async function waitForJob(
const pollMs = deps.pollMs ?? 2000;
let misses = 0;
let last = "";
+ let via = "";
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?.via && j.via !== via) {
+ via = j.via;
+ onLog(` job ${jobId} handed off to job ${via}`);
+ }
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) {
diff --git a/common/controller/landMedia.test.ts b/common/controller/landMedia.test.ts
@@ -34,7 +34,8 @@ const { loadSavedVideo } = await import("../lib/savedVideo-server");
const { isDoNotClean } = await import("../lib/doNotClean-server");
const { addPendingKeep, applyPendingKeep, loadPendingKeep } = await import("../lib/pendingKeep-server");
const { keepVideosByIds } = await import("./keepVideosMatching");
-const { prepareLandedGuard, settleLandedGuard, landedContainerWins } = await import("../ytdlp/landedGuard");
+const { prepareLandedGuard, settleLandedGuard } = await import("../ytdlp/landedGuard");
+const { planSavedContainer } = await import("../ytdlp/savedAlternates");
const paths = getPaths();
test.after(() => rm(ROOT, { recursive: true, force: true }));
@@ -280,9 +281,11 @@ test("a later download shorter than the landed recording does not clobber it; a
assert.match(await readFile(path.join(dir, "audio.mp3"), "utf8"), /seconds=4000/);
const prov = await mediaImportSidecar.load(dir);
assert.deepEqual(prov?.challenges?.map((c) => c.kept), ["landed", "download"]);
- // The container: a shorter downloaded one loses.
+ // The container: a shorter download does not become the active one (it is
+ // kept beside it — ytdlp/savedAlternates.test.ts); an explicit persist does.
const newer = await fake("source-media.mp4", "mov,mp4", 100, dir);
- assert.equal(await landedContainerWins(dir, newer, { measure }, onLog), true);
+ assert.equal((await planSavedContainer({ videoDir: dir, newContainer: newer, explicit: false, deps: { measure } }))?.active, "existing");
+ assert.equal((await planSavedContainer({ videoDir: dir, newContainer: newer, explicit: true, deps: { measure } }))?.active, "download");
// A video that was never landed is an ordinary download.
assert.equal(await prepareLandedGuard(await record("plain"), onLog), null);
});
diff --git a/common/controller/persistVideos.test.ts b/common/controller/persistVideos.test.ts
@@ -10,17 +10,20 @@ import type { DiskGateStatus } from "../lib/diskSpace";
import type { DownloadOutcomeRecord } from "../lib/downloadOutcome";
import { loadSavedVideo, persistSourceVideo } from "../lib/savedVideo-server";
import {
+ PERSIST_VIDEOS_DOWNLOAD,
persistVideos,
type PersistVideoDownload,
type PersistVideosDeps,
} from "./persistVideos";
+import { finalizeAppExtraction } from "../ytdlp/finalizeAppExtraction";
// Run with:
// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/persistVideos.test.ts
//
// Every dependency that would reach the network, the clock or the machine's
-// memory is injected: the download writes a fake container and persists it the
-// way downloadOneManaged does, sleeps are recorded, MemAvailable is scripted.
+// memory is injected: the download writes a fake container and finalizes it the
+// way downloadOneManaged does (finalizeAppExtraction, as an explicit persist
+// over a transcript), sleeps are recorded, MemAvailable is scripted.
const CONFIG: ChannelConfig = {
handling: "transcribe",
@@ -135,12 +138,22 @@ function harness(
const dir = videoDir(paths, o.channelSlug, id);
const file = over.file ?? "source-media.mp4";
await writeFile(path.join(dir, file), `new ${id}`);
- await persistSourceVideo({
+ await finalizeAppExtraction({
+ paths,
+ channelSlug: o.channelSlug,
+ channelConfig: o.channelConfig,
videoDir: dir,
- sourceFilename: file,
- storeDir: path.join(paths.savedVideosDir, o.channelSlug, id),
- keepReason: "override",
+ videoId: id,
+ fmt: "mp3",
+ persist: true,
+ category: "override",
+ extractAudio: false,
format: { preset: o.quality, height: over.height ?? 720 },
+ sourceFilename: file,
+ explicitPersist: PERSIST_VIDEOS_DOWNLOAD.explicitPersist,
+ alternatesDeps: { measure: async () => null, height: async () => null },
+ onLog: () => {},
+ signal: o.signal,
});
return {
videoId: id,
@@ -170,6 +183,12 @@ function harness(
};
}
+test("every download is an explicit persist: forced media, the source kept, the download active", () => {
+ assert.equal(PERSIST_VIDEOS_DOWNLOAD.explicitPersist, true);
+ assert.equal(PERSIST_VIDEOS_DOWNLOAD.forceMedia, true);
+ assert.equal(PERSIST_VIDEOS_DOWNLOAD.keepSourceVideoOverride, true);
+});
+
test("already-saved items are skipped; the rest are fetched in order", async () => {
await withPaths(async (paths) => {
await seedSaved(paths, "demo-channel", "aaa111");
@@ -285,12 +304,18 @@ test("above-height replaces a too-tall or unmeasured container, keeping its prov
assert.equal(nohgt?.keepReason, "pin");
assert.deepEqual(nohgt?.origin, { requestedBy: "umtool" });
assert.equal(nohgt?.format?.height, 720);
- // The old, differently-named container went only after the new one landed.
+ // Nothing is deleted: the old container stays beside the new one under an
+ // alternate name, flagged on the pointer for a check.
await assert.rejects(stat(path.join(oldTall!.dir, oldTall!.file)));
assert.equal(
await readFile(path.join(tall!.dir, tall!.file), "utf8"),
"new tall111",
);
+ const alt = tall?.alternates?.[0];
+ assert.match(alt?.file ?? "", /^source-media\.alt-1080p-\d{14}\.webm$/);
+ assert.equal(alt?.height, 1080);
+ assert.equal(await readFile(path.join(tall!.dir, alt!.file), "utf8"), "old tall111");
+ assert.match(nohgt?.alternates?.[0]?.file ?? "", /^source-media\.alt-\d{14}\.mp4$/);
});
});
diff --git a/common/controller/persistVideos.ts b/common/controller/persistVideos.ts
@@ -1,5 +1,5 @@
import path from "node:path";
-import { readFile, rm, stat } from "node:fs/promises";
+import { readFile, stat } from "node:fs/promises";
import type { Paths } from "../lib/paths";
import type { ChannelConfig } from "../lib/channelConfig";
import type { SiteSettings } from "../lib/settings";
@@ -7,10 +7,7 @@ import { getSettings } from "../lib/settings";
import { diskGate, type DiskGateStatus } from "../lib/diskSpace";
import { resolveCookiePolicy } from "../lib/cookiePolicy";
import type { DownloadOutcomeRecord } from "../lib/downloadOutcome";
-import {
- savedVideoPath,
- type SavedVideoPointer,
-} from "../lib/savedVideo";
+import type { SavedVideoPointer } from "../lib/savedVideo";
import {
loadSavedVideo,
restoreSavedVideoProvenance,
@@ -56,12 +53,13 @@ import { recordDownloadBackoff } from "../jobs/downloadBackoff";
// (`minFreeMemMb`), and the disk floor. Cancel and drain are honoured between
// videos; the one in flight is a cancel's business, as everywhere else.
//
-// REPLACING NEVER DELETES FIRST. `replace: "above-height"` re-fetches a saved
-// video whose recorded height is unknown or above the requested quality's
-// ceiling. The old container stays where it is until the new pointer is
-// written; only then is it removed (when its path differs — a same-named one
-// was already replaced by the store's atomic move). The replacement keeps the
-// old pointer's `keepReason` and `origin`, so a keep-latest container stays
+// REPLACING NEVER DELETES. `replace: "above-height"` re-fetches a saved video
+// whose recorded height is unknown or above the requested quality's ceiling.
+// The download becomes the ACTIVE copy and the old one is kept beside it as an
+// alternate, flagged on the pointer for a later check
+// (ytdlp/savedAlternates.ts — this run's downloads are `explicitPersist`).
+// The replacement keeps the old pointer's `keepReason` and `origin` (a landed
+// copy's origin stays with that copy), so a keep-latest container stays
// evictable and a requested one keeps its requester.
export type PersistVideoItem = { slug: string; id: string };
@@ -138,12 +136,22 @@ export type PersistVideosDeps = {
paths: Paths,
failureClass: "rate_limit" | "network",
) => Promise<void>;
- removeFile: (file: string) => Promise<void>;
};
// How often the memory wait re-reads /proc/meminfo.
export const MEM_POLL_MS = 10_000;
+// What every item's download asks of downloadOneManaged.
+export const PERSIST_VIDEOS_DOWNLOAD = {
+ appendArchive: true,
+ keepSourceVideoOverride: true,
+ // Persist means persist — see persistKept.
+ forceMedia: true,
+ // An operator's list: over a copy already saved, the download becomes the
+ // active one and the old copy is kept beside it (ytdlp/savedAlternates.ts).
+ explicitPersist: true,
+} as const;
+
const defaultDownload: PersistVideoDownload = (o) =>
downloadOneManaged({
channelSlug: o.channelSlug,
@@ -155,10 +163,7 @@ const defaultDownload: PersistVideoDownload = (o) =>
cookiePolicy: resolveCookiePolicy(o.settings, o.channelConfig),
inlineTranscribeOnFallback: o.settings.inlineTranscribeOnFallback,
globalSkipLiveDownloads: o.settings.skipLiveDownloads,
- appendArchive: true,
- keepSourceVideoOverride: true,
- // Persist means persist — see persistKept.
- forceMedia: true,
+ ...PERSIST_VIDEOS_DOWNLOAD,
persistFormatPreset: o.quality,
});
@@ -196,7 +201,6 @@ const DEFAULT_DEPS: PersistVideosDeps = {
readChannelConfig,
onPlatformBackoff: (platform, paths, failureClass) =>
recordDownloadBackoff(platform, paths, failureClass),
- removeFile: (file) => rm(file, { force: true }),
};
// The tallest height a quality accepts, or null for "original" (no ceiling).
@@ -500,14 +504,17 @@ export async function persistVideos({
continue;
}
if (p.pointer) {
- // The same video's container, so it keeps the old pointer's retention
- // class and requester: the forced persist writes "override", which
- // would make a keep-latest container permanent.
- await restoreSavedVideoProvenance(videoDir, p.pointer);
- const oldFile = savedVideoPath(p.pointer);
- if (oldFile !== savedVideoPath(pointer)) {
- await deps.removeFile(oldFile).catch(() => {});
- log(` ${label(p)}: removed the replaced container ${oldFile}.`);
+ const kept = pointer.alternates?.find((a) => a.storedAt === p.pointer!.storedAt);
+ if (kept) {
+ // The persist kept the old copy beside the new one and carried its
+ // provenance over itself (ytdlp/savedAlternates.ts).
+ log(` ${label(p)}: the replaced container stays beside it as ${kept.file}, flagged for a check.`);
+ } else {
+ // The old file was already gone: the same video's container, so it
+ // keeps the old pointer's retention class and requester — the forced
+ // persist writes "override", which would make a keep-latest container
+ // permanent.
+ await restoreSavedVideoProvenance(videoDir, p.pointer);
}
result.replaced.push({ slug: p.slug, id: p.id });
}
diff --git a/common/controller/pruneSavedVideos.ts b/common/controller/pruneSavedVideos.ts
@@ -63,6 +63,15 @@ export async function pruneSavedVideos({
if (pointer.keepReason !== "keep-latest") continue;
if (keptIds.has(id)) continue; // still inside the window
if (await isDoNotClean(videoDir)) continue; // pinned -> keep forever
+ // Two copies kept for a check (ytdlp/savedAlternates.ts): the prune never
+ // removes a flagged alternate, so it leaves the whole video for the check.
+ if (pointer.alternates?.length) {
+ log(
+ `Kept saved video ${id} although it rolled out of the keep-latest window: ` +
+ `it holds ${pointer.alternates.length} alternate cop${pointer.alternates.length === 1 ? "y" : "ies"} flagged for a check.`,
+ );
+ continue;
+ }
const bytes = await dropSavedVideo(videoDir);
bytesFreed += bytes;
pruned++;
diff --git a/common/controller/refreshVideoMetadata.ts b/common/controller/refreshVideoMetadata.ts
@@ -71,6 +71,7 @@ import {
type AttemptOutcome,
} from "../ytdlp/runOneYtdlp";
import { findVideoSourceUrl } from "./undownloadedVideos";
+import { englishCaptionTracks } from "../lib/listedCaptions-server";
const INFO_JSON = "metadata.info.json";
@@ -259,12 +260,8 @@ function describeAudioFormat(f: Json): string {
}
// The English track names of a caption map (en, en-US, en-orig, …), sorted.
-function englishTracks(map: unknown): string[] {
- if (!isObject(map)) return [];
- return Object.keys(map)
- .filter((k) => /^en(-|$)/i.test(k))
- .sort();
-}
+// lib/listedCaptions-server.ts: the one rule for an English caption track.
+const englishTracks = englishCaptionTracks;
function list(values: string[]): string {
return values.length ? values.join(", ") : "none";
diff --git a/common/controller/researchRuns.ts b/common/controller/researchRuns.ts
@@ -50,11 +50,26 @@ export class ResearchInputError extends Error {}
type StorePaths = Pick<Paths, "articlesDir" | "exportIndexDir" | "jobsDir">;
-// An editor job's state, from the registry or its `.jobs` sidecar.
+// An editor job's state, from the registry or its `.jobs` sidecar — THE
+// WORK's state: a job that ended `done` having handed its work on to another
+// (`handedOffTo`: a whisper-video's transcription, queued as a transcribe-one
+// job once the audio is down) answers with that job's state, followed to the
+// end of the chain (`via` names the job answering). A caller asking "is the
+// transcript there" would otherwise read `done` while it still waits for a
+// worker.
export function jobOfPaths(paths: Pick<Paths, "jobsDir">): JobOf {
return async (id) => {
- const e = await getJobEntry(paths as Paths, id);
- return e ? { status: e.status, ...(e.endedAt ? { endedAt: e.endedAt } : {}) } : null;
+ let e = await getJobEntry(paths as Paths, id);
+ let via: string | undefined;
+ for (let hops = 0; e && e.status === "done" && e.handedOffTo && hops < 5; hops++) {
+ const next = await getJobEntry(paths as Paths, e.handedOffTo);
+ if (!next) return { status: "archived", via: e.handedOffTo };
+ via = next.id;
+ e = next;
+ }
+ return e
+ ? { status: e.status, ...(e.endedAt ? { endedAt: e.endedAt } : {}), ...(via ? { via } : {}) }
+ : null;
};
}
diff --git a/common/controller/savedVideoInventory.ts b/common/controller/savedVideoInventory.ts
@@ -3,7 +3,11 @@ import fs from "fs-extra";
import type { Paths } from "../lib/paths";
import { mapConcurrent } from "../lib/concurrency";
import { loadSavedVideo } from "../lib/savedVideo-server";
-import { savedVideoPath, type SavedVideoPointer } from "../lib/savedVideo";
+import {
+ savedVideoBytes,
+ savedVideoPath,
+ type SavedVideoPointer,
+} from "../lib/savedVideo";
import {
isDriveNotAnswering,
onDrive,
@@ -115,6 +119,16 @@ export async function listSavedVideos({
return out;
}
+// Every saved video holding alternates (ytdlp/savedAlternates.ts): the flag a
+// later check reads. The same pointer walk as listSavedVideos.
+export async function listSavedAlternates(opts: {
+ paths: Paths;
+ channelSlug?: string;
+ notAnswering?: string[];
+}): Promise<SavedVideoEntry[]> {
+ return (await listSavedVideos(opts)).filter((e) => (e.pointer.alternates?.length ?? 0) > 0);
+}
+
export type SavedVideoTotals = {
count: number;
bytes: number;
@@ -129,6 +143,6 @@ export async function savedVideoTotals(opts: {
}): Promise<SavedVideoTotals> {
const entries = await listSavedVideos(opts);
let bytes = 0;
- for (const e of entries) bytes += e.pointer.bytes;
+ for (const e of entries) bytes += savedVideoBytes(e.pointer);
return { count: entries.length, bytes };
}
diff --git a/common/jobs/handOff.test.ts b/common/jobs/handOff.test.ts
@@ -0,0 +1,75 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { handOffSlot, type StartedJob } from "./handOff";
+import type { JobDoneResult } from "./streamCommand";
+
+// A started job whose log is `lines` and whose `done` settles when `finish`
+// is called.
+function fakeJob(jobId: string, lines: string[]) {
+ let finish!: (status: JobDoneResult["status"]) => void;
+ const done = new Promise<JobDoneResult>((res) => {
+ finish = (status) => res({ status, jobId });
+ });
+ let cancelled = false;
+ const stream = new ReadableStream<string>({
+ start(c) {
+ for (const l of lines) c.enqueue(l);
+ c.close();
+ },
+ cancel() {
+ cancelled = true;
+ },
+ });
+ const job: StartedJob = { ok: true, jobId, stream, done };
+ return { job, finish, wasCancelled: () => cancelled };
+}
+
+async function readAll(stream: ReadableStream<string>): Promise<string> {
+ const reader = stream.getReader();
+ let out = "";
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) return out;
+ out += value;
+ }
+}
+
+test("the caller reads both jobs' logs as one, and done settles with the second", async () => {
+ const slot = handOffSlot();
+ const parent = fakeJob("w1", ["downloading\n", "handed off\n"]);
+ const child = fakeJob("t1", ["Transcribe v done\n"]);
+ const wrapped = slot.wrap(parent.job);
+ assert.equal(wrapped.jobId, "w1");
+ slot.set(child.job);
+ parent.finish("done");
+ assert.equal(await readAll(wrapped.stream), "downloading\nhanded off\nTranscribe v done\n");
+ let settled = false;
+ const d = wrapped.done.then((r) => {
+ settled = true;
+ return r;
+ });
+ await new Promise((r) => setTimeout(r, 10));
+ assert.equal(settled, false, "the download is done, the work is not");
+ child.finish("failed");
+ assert.deepEqual(await d, { status: "failed", jobId: "t1" });
+});
+
+test("a first job that fails, or hands nothing off, is the whole answer", async () => {
+ const slot = handOffSlot();
+ const parent = fakeJob("w2", ["no url\n"]);
+ const wrapped = slot.wrap(parent.job);
+ parent.finish("failed");
+ assert.equal(await readAll(wrapped.stream), "no url\n");
+ assert.deepEqual(await wrapped.done, { status: "failed", jobId: "w2" });
+});
+
+test("a consumer that goes away cancels the second stream too, even before it exists", async () => {
+ const slot = handOffSlot();
+ const parent = fakeJob("w3", ["downloading\n"]);
+ const wrapped = slot.wrap(parent.job);
+ await wrapped.stream.cancel();
+ assert.equal(parent.wasCancelled(), true);
+ const child = fakeJob("t3", ["long log\n"]);
+ slot.set(child.job);
+ assert.equal(child.wasCancelled(), true, "an unread transcription log is not buffered");
+});
diff --git a/common/jobs/handOff.ts b/common/jobs/handOff.ts
@@ -0,0 +1,92 @@
+// A JOB THAT HANDS ITS WORK ON TO ANOTHER, AS ITS CALLER SEES IT.
+//
+// A whisper-video downloads the audio on its platform's queue, then queues the
+// transcription as a transcribe-one job of its own and ends — so the platform
+// queue is free the moment the bytes are down, while the transcription waits
+// for a worker (videoActions.ts whisperVideoAction). The job records where
+// the work went (JobRunContext.handOff → `handedOffTo`); this is the other
+// half, for the caller holding the action's result: ONE stream, the first
+// job's log and then the second's, and a `done` that settles when the work
+// does — so a run panel reads "… Transcribe <id> done" as it did when the two
+// were one job.
+//
+// const slot = handOffSlot();
+// const r = await runManagedFunction({ …, fn: async (…, ctx) => {
+// const child = await queueTheRest();
+// if (child.ok) { ctx.handOff(child.jobId); slot.set(child); }
+// } });
+// return r.ok ? slot.wrap(r) : r;
+//
+// A consumer that goes away (the ops route cancels the stream at once) cancels
+// the second stream too, the moment it exists: an unread job stream would
+// otherwise buffer a long transcription's whole log. Cancelling a stream never
+// stops a job (streamCommand.ts).
+
+import { getRegistry } from "./registry";
+import type { JobDoneResult, StreamActionResult } from "./streamCommand";
+
+export type StartedJob = Extract<StreamActionResult, { ok: true }>;
+
+export type HandOffSlot = {
+ // Inside the first job: the job it handed its work on to.
+ set: (child: StartedJob) => void;
+ // The first job's result, as its caller should hold it.
+ wrap: (parent: StartedJob) => StartedJob;
+};
+
+export function handOffSlot(): HandOffSlot {
+ let child: StartedJob | null = null;
+ let consumerGone = false;
+ return {
+ set(c) {
+ child = c;
+ if (consumerGone) void c.stream.cancel().catch(() => {});
+ },
+ wrap(parent) {
+ let current = parent.stream.getReader();
+ let onChild = false;
+ const stream = new ReadableStream<string>({
+ async pull(controller) {
+ for (;;) {
+ const { value, done } = await current.read();
+ if (!done) {
+ controller.enqueue(value);
+ return;
+ }
+ if (!onChild && child) {
+ onChild = true;
+ current = child.stream.getReader();
+ continue;
+ }
+ controller.close();
+ return;
+ }
+ },
+ cancel() {
+ consumerGone = true;
+ void current.cancel().catch(() => {});
+ if (child && !onChild) void child.stream.cancel().catch(() => {});
+ },
+ });
+ const done: Promise<JobDoneResult> = parent.done.then((r) =>
+ r.status === "done" && child ? child.done : r,
+ );
+ return { ...parent, stream, done };
+ },
+ };
+}
+
+// The job doing `id`'s work now: `id` itself, or — while it ended `done`
+// having handed its work on — the job it named, followed down the chain. What
+// a run panel's Cancel cancels (jobs/actions.ts cancelJobAction): the panel is
+// still showing the transcription the whisper-video handed off.
+export function jobDoingTheWork(id: string): string {
+ const registry = getRegistry();
+ let target = id;
+ for (let hops = 0; hops < 5; hops++) {
+ const r = registry.get(target);
+ if (r?.status !== "done" || !r.handedOffTo) break;
+ target = r.handedOffTo;
+ }
+ return target;
+}
diff --git a/common/jobs/jobMeta.ts b/common/jobs/jobMeta.ts
@@ -35,6 +35,8 @@ export type JobMeta = {
// LIVE process owns right now — `archilyzer run` writes into the same
// `.jobs/`. Absent on metas written before release 17.
pid?: number;
+ // The job this one handed its work on to (JobRecord.handedOffTo).
+ handedOffTo?: string;
};
export function metaPath(paths: Paths, id: string): string {
@@ -62,6 +64,7 @@ export async function writeJobMeta(
exitCode: record.exitCode,
spec: record.spec,
pid: process.pid,
+ ...(record.handedOffTo ? { handedOffTo: record.handedOffTo } : {}),
};
await writeFile(metaPath(paths, record.id), JSON.stringify(meta), "utf8");
} catch {
@@ -90,6 +93,7 @@ export async function readJobMeta(
// Sanitize the replay descriptor: drop it if malformed so a stale sidecar
// can't surface an un-runnable Retry.
meta.spec = m.spec === undefined ? undefined : (parseJobSpec(m.spec) ?? undefined);
+ if (m.handedOffTo !== undefined && typeof m.handedOffTo !== "string") delete meta.handedOffTo;
return meta;
} catch {
return null;
diff --git a/common/jobs/listJobs.ts b/common/jobs/listJobs.ts
@@ -35,6 +35,8 @@ export type JobListEntry = {
// e.g. "server restarted; the scheduler re-derives syncs". From the sidecar;
// absent on every other job.
cancelReason?: string;
+ // The job this one handed its work on to (JobRecord.handedOffTo).
+ handedOffTo?: string;
};
export type JobsPage = {
@@ -114,6 +116,7 @@ async function buildEntry(
inRegistry: true,
replayable: Boolean(live_.spec),
detail: jobSpecDetail(live_.kind, live_.spec),
+ ...(live_.handedOffTo ? { handedOffTo: live_.handedOffTo } : {}),
logPath,
logSize,
};
@@ -145,6 +148,7 @@ async function buildEntry(
...(meta.status === "cancelled" && meta.cancelReason
? { cancelReason: meta.cancelReason }
: {}),
+ ...(meta.handedOffTo ? { handedOffTo: meta.handedOffTo } : {}),
logPath,
logSize,
};
diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts
@@ -159,6 +159,13 @@ export type JobRecord = {
// begins. The /jobs row draws "waiting 4m12s: …" from it.
pacedUntil?: number;
pacedReason?: string;
+ // THE JOB THIS ONE HANDED ITS WORK ON TO (JobRunContext.handOff): a
+ // whisper-video downloads the audio on its platform queue, then queues the
+ // transcription as its own transcribe-one job and ends, so the platform
+ // queue is free while the transcription waits for a worker. A caller that
+ // waits for the work rather than the job follows it (researchRuns.ts
+ // jobOfPaths, `pnpm ops --wait`).
+ handedOffTo?: string;
};
// Store a progress snapshot on the record, stamping `progressAt` only when the
diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts
@@ -112,6 +112,10 @@ export type JobRunContext = {
) => void;
removeTask: (taskId: string) => void;
recordTaskDone: (durationMs: number, audioSeconds?: number) => void;
+ // This job's work goes on in another job (`jobId`), which this one queued:
+ // recorded on the record and its sidecar as `handedOffTo`, so a caller
+ // waiting for the work follows it there.
+ handOff: (jobId: string) => void;
};
export type RunManagedFunctionOpts = CommonOpts & {
@@ -462,6 +466,10 @@ export async function runManagedFunction(
// coalesces sub-operations that finish close together.
requestSnapshotOnFinish(id, opts);
},
+ handOff: (jobId) => {
+ record.handedOffTo = jobId;
+ persistMeta();
+ },
};
// THE GUARD AGAIN, NOW THAT THE QUEUE HAS STARTED THE JOB (see
diff --git a/common/lib/listedCaptions-server.ts b/common/lib/listedCaptions-server.ts
@@ -0,0 +1,60 @@
+import path from "node:path";
+import { readFile } from "node:fs/promises";
+
+// THE CAPTION TRACKS A VIDEO'S metadata.info.json LISTS: yt-dlp's
+// `subtitles` (uploaded by the channel) and `automatic_captions` (YouTube's
+// speech recognition). `live_chat` is left out — yt-dlp files YouTube's chat
+// replay under `subtitles`, and it is not a transcript of speech.
+//
+// The one rule for "this video has captions to fetch": the managed download's
+// no-subs fallback (downloadOneManaged: audio + whisper only when none is
+// listed), and a Transcribe asked of a youtube-handling video with no audio
+// (videoActions.ts whisperVideoAction: its English captions are fetched
+// instead, unless `asr: true`).
+
+type CaptionMaps = {
+ subtitles?: unknown;
+ automatic_captions?: unknown;
+};
+
+// Every listed track, null when the metadata cannot say (not an object, or a
+// map that is not one).
+export function listedCaptionTracks(meta: unknown): string[] | null {
+ if (!meta || typeof meta !== "object") return null;
+ const m = meta as CaptionMaps;
+ const subs = m.subtitles ?? {};
+ const auto = m.automatic_captions ?? {};
+ if (typeof subs !== "object" || typeof auto !== "object") return null;
+ const tracks = new Set<string>();
+ for (const k of Object.keys(subs as object)) if (k !== "live_chat") tracks.add(k);
+ for (const k of Object.keys(auto as object)) if (k !== "live_chat") tracks.add(k);
+ return [...tracks];
+}
+
+// The listed tracks of the video in `videoDir`; null with no readable
+// metadata.info.json.
+export async function readListedCaptionTracks(videoDir: string): Promise<string[] | null> {
+ let raw: string;
+ try {
+ raw = await readFile(path.join(videoDir, "metadata.info.json"), "utf8");
+ } catch {
+ return null;
+ }
+ try {
+ return listedCaptionTracks(JSON.parse(raw));
+ } catch {
+ return null;
+ }
+}
+
+// An English track key — `en`, `en-orig`, `en-US`, … (yt-dlp's language
+// codes; `es-en` is a Spanish track, not this).
+export function isEnglishCaptionTrack(track: string): boolean {
+ return /^en(-|$)/i.test(track);
+}
+
+// The English keys of one caption map, sorted.
+export function englishCaptionTracks(map: unknown): string[] {
+ if (!map || typeof map !== "object" || Array.isArray(map)) return [];
+ return Object.keys(map).filter(isEnglishCaptionTrack).sort();
+}
diff --git a/common/lib/mediaImport.ts b/common/lib/mediaImport.ts
@@ -70,7 +70,11 @@ export type MediaImportChallenge = {
what: "audio" | "container";
newSeconds: number | null;
landedSeconds: number | null;
+ // Audio: the copy kept. A container: the ACTIVE copy — the other one is
+ // kept too, as `alternate` in the store (ytdlp/savedAlternates.ts).
kept: "landed" | "download";
+ alternate?: string;
+ explicit?: boolean;
};
export type MediaImportRecord = { entries: MediaImportEntry[]; challenges?: MediaImportChallenge[] };
diff --git a/common/lib/report/draft/research/state.ts b/common/lib/report/draft/research/state.ts
@@ -142,7 +142,9 @@ export async function writeResearchState(article: string, n: number, state: Rese
// ─── jobs ───
// One editor job as the refresh needs it (common/jobs/listJobs getJobEntry).
-export type JobState = { status: string; endedAt?: number };
+// `via`: the job that answered, when the one asked handed its work on to it
+// (researchRuns.ts jobOfPaths).
+export type JobState = { status: string; endedAt?: number; via?: string };
export type JobOf = (id: string) => Promise<JobState | null>;
export const jobIdsOf = (p: Pick<Proposal, "jobId">): string[] =>
diff --git a/common/lib/savedVideo-server.ts b/common/lib/savedVideo-server.ts
@@ -10,6 +10,7 @@ import {
import {
SAVED_VIDEO_POINTER_FILENAME,
parseSavedVideoPointer,
+ savedVideoBytes,
savedVideoPath,
type SavedVideoFormat,
type SavedVideoKeepReason,
@@ -40,7 +41,7 @@ export async function isSavedVideo(videoDir: string): Promise<boolean> {
return (await loadSavedVideo(videoDir)) !== null;
}
-async function writePointer(
+export async function writePointer(
videoDir: string,
pointer: SavedVideoPointer,
): Promise<void> {
@@ -68,7 +69,7 @@ export async function rewriteSavedVideoDir(
// one filesystem; EXDEV (the store is on a different disk) falls back to a
// copy-to-temp + atomic rename + unlink so a crash mid-copy never leaves a
// partial file under the final name.
-async function moveFileCrossDevice(src: string, dest: string): Promise<void> {
+export async function moveFileCrossDevice(src: string, dest: string): Promise<void> {
await mkdir(path.dirname(dest), { recursive: true });
try {
await rename(src, dest);
@@ -135,6 +136,11 @@ export async function persistSourceVideo(opts: {
const src = opts.sourcePath ?? path.join(opts.videoDir, opts.sourceFilename);
const dest = path.join(opts.storeDir, opts.sourceFilename);
const st = await stat(src);
+ // The copies kept beside the one this replaces (savedVideo.ts `alternates`)
+ // are still in that dir: the new pointer carries them, or they would be
+ // files no pointer names.
+ const before = await loadSavedVideo(opts.videoDir);
+ const alternates = before?.dir === opts.storeDir ? before.alternates : undefined;
await moveFileCrossDevice(src, dest);
const pointer: SavedVideoPointer = {
storedAt: new Date().toISOString(),
@@ -145,6 +151,7 @@ export async function persistSourceVideo(opts: {
...(opts.sha256 ? { sha256: opts.sha256 } : {}),
...(opts.origin ? { origin: opts.origin } : {}),
...(opts.format ? { format: opts.format } : {}),
+ ...(alternates?.length ? { alternates } : {}),
};
await writePointer(opts.videoDir, pointer);
return pointer;
@@ -208,18 +215,28 @@ export async function unpersistSavedVideo(
} catch {
// The stored container is already gone; just drop the dangling pointer.
}
+ // Its alternates come back too, under their own names (no reader takes one
+ // for a source): with the pointer gone, nothing would name them in the store.
+ for (const alt of pointer.alternates ?? []) {
+ await moveFileCrossDevice(path.join(pointer.dir, alt.file), path.join(videoDir, alt.file)).catch(() => {});
+ }
await rm(savedVideoPointerPath(videoDir), { force: true });
await pruneEmptyStoreDirs(pointer.dir);
return true;
}
// Permanently delete a video's persisted container + pointer (retention prune of
-// a video that rolled out of the keep-latest window). Returns bytes freed.
+// a video that rolled out of the keep-latest window). Returns bytes freed. The
+// whole video goes, its alternates with it — the prune itself never calls this
+// for a video that holds any (pruneSavedVideos leaves those for the check).
export async function dropSavedVideo(videoDir: string): Promise<number> {
const pointer = await loadSavedVideo(videoDir);
if (!pointer) return 0;
await rm(savedVideoPath(pointer), { force: true });
+ for (const alt of pointer.alternates ?? []) {
+ await rm(path.join(pointer.dir, alt.file), { force: true });
+ }
await rm(savedVideoPointerPath(videoDir), { force: true });
await pruneEmptyStoreDirs(pointer.dir);
- return pointer.bytes;
+ return savedVideoBytes(pointer);
}
diff --git a/common/lib/savedVideo.ts b/common/lib/savedVideo.ts
@@ -61,6 +61,34 @@ export type SavedVideoPointer = {
// every pointer written before this; `height`/`vcodec` absent when yt-dlp
// did not report them.
format?: SavedVideoFormat;
+ // TWO COPIES OF ONE VIDEO, BOTH KEPT (finalizeAppExtraction, the download
+ // over a container already in the store — ytdlp/savedAlternates.ts). `file`
+ // stays the ACTIVE copy, the one every reader uses; each other copy sits in
+ // the same `dir` under a name no reader takes for a source
+ // (`source-media.alt-<h>p-<stamp>.<ext>`), listed here so a later check can
+ // decide between them. Absent on every pointer with one copy.
+ alternates?: SavedVideoAlternate[];
+ // The active copy's own measured length and height, written when an
+ // alternate was recorded beside it (a landed container has no `format`).
+ probed?: SavedVideoProbe;
+};
+
+export type SavedVideoProbe = { seconds?: number; height?: number };
+
+export type SavedVideoAlternate = {
+ // Basename in the pointer's `dir`.
+ file: string;
+ bytes: number;
+ // When this copy first entered the store, and when it stopped being active.
+ storedAt: string;
+ setAsideAt: string;
+ seconds?: number;
+ height?: number;
+ vcodec?: string;
+ // Who brought this copy: a landed one keeps its import/attach provenance.
+ origin?: SavedVideoOrigin;
+ // A download's copy: the quality it asked for.
+ preset?: SourceVideoQuality;
};
export type SavedVideoFormat = {
@@ -152,6 +180,67 @@ function parseOrigin(raw: unknown): SavedVideoOrigin | null {
return out;
}
+function positive(v: unknown): number | undefined {
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined;
+}
+
+function parseProbe(raw: unknown): SavedVideoProbe | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const r = raw as Record<string, unknown>;
+ const out: SavedVideoProbe = {};
+ const seconds = positive(r.seconds);
+ const height = positive(r.height);
+ if (seconds !== undefined) out.seconds = seconds;
+ if (height !== undefined) out.height = height;
+ return Object.keys(out).length ? out : null;
+}
+
+function parseAlternate(raw: unknown): SavedVideoAlternate | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const r = raw as Record<string, unknown>;
+ if (typeof r.file !== "string" || r.file === "" || r.file.includes("/")) return null;
+ const out: SavedVideoAlternate = {
+ file: r.file,
+ bytes: typeof r.bytes === "number" && Number.isFinite(r.bytes) ? r.bytes : 0,
+ storedAt: typeof r.storedAt === "string" ? r.storedAt : "",
+ setAsideAt: typeof r.setAsideAt === "string" ? r.setAsideAt : "",
+ };
+ const seconds = positive(r.seconds);
+ const height = positive(r.height);
+ if (seconds !== undefined) out.seconds = seconds;
+ if (height !== undefined) out.height = height;
+ if (typeof r.vcodec === "string" && r.vcodec !== "") out.vcodec = r.vcodec;
+ const origin = parseOrigin(r.origin);
+ if (origin) out.origin = origin;
+ if (isSourceVideoQuality(r.preset)) out.preset = r.preset;
+ return out;
+}
+
+// One line for a video holding alternates, for the review listing:
+// "2 saved copies: active 720p, 4696.5 s (download); alternate 360p, 4696.6 s
+// (attach-media, source-media.alt-360p-20261023172312.mp4)".
+export function savedAlternatesLine(pointer: SavedVideoPointer): string {
+ const facts = (height: number | undefined, seconds: number | undefined, by: string) =>
+ `${height ? `${height}p` : "height unknown"}, ${seconds !== undefined ? `${seconds.toFixed(1)} s` : "length unknown"} (${by}`;
+ const alts = pointer.alternates ?? [];
+ const active = facts(
+ pointer.format?.height ?? pointer.probed?.height,
+ pointer.probed?.seconds,
+ pointer.origin?.requestedBy ?? "download",
+ );
+ return (
+ `${alts.length + 1} saved copies: active ${active}); ` +
+ alts
+ .map((a) => `alternate ${facts(a.height, a.seconds, a.origin?.requestedBy ?? "download")}, ${a.file})`)
+ .join("; ")
+ );
+}
+
+// Every byte a pointer accounts for: the active copy and its alternates.
+export function savedVideoBytes(pointer: SavedVideoPointer): number {
+ return pointer.bytes + (pointer.alternates ?? []).reduce((n, a) => n + a.bytes, 0);
+}
+
function isKeepReason(v: unknown): v is SavedVideoKeepReason {
return v === "keep-latest" || v === "pin" || v === "override";
}
@@ -203,5 +292,13 @@ export function parseSavedVideoPointer(raw: unknown): SavedVideoPointer | null {
// Same rule: a pointer without `format` (every one before it) parses as before.
const format = parseFormat(r.format);
if (format) pointer.format = format;
+ // And again: a pointer without `alternates` parses as before. An entry that
+ // does not name a file is dropped; the file itself is never touched here.
+ const alternates = Array.isArray(r.alternates)
+ ? r.alternates.map(parseAlternate).filter((a): a is SavedVideoAlternate => a !== null)
+ : [];
+ if (alternates.length) pointer.alternates = alternates;
+ const probed = parseProbe(r.probed);
+ if (probed) pointer.probed = probed;
return pointer;
}
diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts
@@ -116,6 +116,7 @@ import {
type StoredUrlWhy,
} from "../lib/storedMediaUrl";
import { storedMediaUrl } from "../lib/storedMediaUrl-server";
+import { readListedCaptionTracks } from "../lib/listedCaptions-server";
import { fullAudioLine, fullAudioState } from "../lib/fullAudioFirst";
import type { DownloadFailureClass } from "../lib/availability";
import { platformGapRemainingMs, waitForPlatformGap } from "../jobs/platformGap";
@@ -211,6 +212,13 @@ export type ManagedDownloadOpts = {
// never by the download lane, re-acquire or import. Transcribe handling
// already downloads, so it is unaffected.
forceMedia?: boolean;
+ // A PERSON ASKED FOR THIS CONTAINER: over a copy already in the saved-video
+ // store, the download becomes the ACTIVE one and the other is kept beside it
+ // as an alternate (ytdlp/savedAlternates.ts); without it the copy in the
+ // store stays active unless the download is longer. Neither is discarded
+ // either way. Set by "Persist source video", persist-videos and the
+ // whole-recording fetch; never by an automatic download.
+ explicitPersist?: boolean;
// Per-run override of channelConfig.audioFormat for the extracted audio.
audioFormatOverride?: AudioFormat;
// Resolved yt-dlp `-f` download-format preset (override > channel > global),
@@ -659,36 +667,13 @@ async function hasAnyTranscriptOnDisk(videoDir: string): Promise<boolean> {
});
}
+// Listed, none of them (lib/listedCaptions-server.ts — the one rule): the
+// no-subs fallback's reason to fetch audio. No readable metadata says nothing.
async function metadataReportsNoCaptions(
videoDir: string,
): Promise<boolean> {
- let raw: string;
- try {
- raw = await readFile(
- path.join(videoDir, "metadata.info.json"),
- "utf8",
- );
- } catch {
- return false;
- }
- let parsed: {
- subtitles?: Record<string, unknown>;
- automatic_captions?: Record<string, unknown>;
- };
- try {
- parsed = JSON.parse(raw);
- } catch {
- return false;
- }
- const subs = parsed.subtitles ?? {};
- const auto = parsed.automatic_captions ?? {};
- if (typeof subs !== "object" || typeof auto !== "object") return false;
- // live_chat is YouTube's chat replay, not a caption track. yt-dlp places
- // it under `subtitles`, so a video whose only listed track is live_chat
- // should be treated as having no captions for fallback purposes.
- const realSubs = Object.keys(subs).filter((k) => k !== "live_chat");
- const realAuto = Object.keys(auto).filter((k) => k !== "live_chat");
- return realSubs.length === 0 && realAuto.length === 0;
+ const listed = await readListedCaptionTracks(videoDir);
+ return listed !== null && listed.length === 0;
}
function trimError(stderrTail: string): string | undefined {
@@ -1675,6 +1660,7 @@ async function runManagedDownload(
category: plan.category,
origin: opts.persistOrigin,
format: persistedFormat(),
+ explicitPersist: opts.explicitPersist,
onLog: opts.onLog,
signal: opts.signal,
});
@@ -1813,6 +1799,7 @@ async function runManagedDownload(
category: plan.category,
origin: opts.persistOrigin,
format: persistedFormat(),
+ explicitPersist: opts.explicitPersist,
extractAudio: false,
onLog: opts.onLog,
signal: opts.signal,
@@ -1834,6 +1821,7 @@ async function runManagedDownload(
category: plan.category,
origin: opts.persistOrigin,
format: persistedFormat(),
+ explicitPersist: opts.explicitPersist,
onLog: opts.onLog,
signal: opts.signal,
});
diff --git a/common/ytdlp/finalizeAppExtraction.ts b/common/ytdlp/finalizeAppExtraction.ts
@@ -18,8 +18,13 @@ import {
type SavedVideoOrigin,
} from "../lib/savedVideo";
import { persistSourceVideo } from "../lib/savedVideo-server";
-import { probeMediaDurationSec } from "./ffprobeDuration";
-import { landedContainerWins } from "./landedGuard";
+import { probeMediaDurationSec, probeVideoHeight } from "./ffprobeDuration";
+import {
+ keepDownloadAsAlternate,
+ persistOverExisting,
+ planSavedContainer,
+ type SavedAlternatesDeps,
+} from "./savedAlternates";
// After an app-mode transcribe download, produce audio.<fmt> from the downloaded
// source-media.<ext> container via ffmpeg. When the video is persisted the
@@ -54,6 +59,11 @@ export async function finalizeAppExtraction(opts: {
// The container's name in videoDir, when the caller knows it (the
// archive.org fetch). Absent: the sorted first source-media.<ext> there.
sourceFilename?: string;
+ // A PERSON ASKED FOR THIS CONTAINER (ManagedDownloadOpts.explicitPersist):
+ // over a copy already in the store, the download becomes the active one.
+ explicitPersist?: boolean;
+ // Test seam: how the two copies are measured. Production passes none.
+ alternatesDeps?: SavedAlternatesDeps;
onLog: (s: string) => void;
signal: AbortSignal;
}): Promise<void> {
@@ -66,17 +76,39 @@ export async function finalizeAppExtraction(opts: {
);
return;
}
- // A LANDED RECORDING AS LONG OR LONGER STAYS (ytdlp/landedGuard.ts): the
- // download's container is discarded, and nothing is extracted from it.
- if (
- await landedContainerWins(
- opts.videoDir,
- path.join(opts.videoDir, source),
- { measure: (file) => probeMediaDurationSec({ ffprobeBin: opts.paths.ffprobeBin, file }) },
- opts.onLog,
- )
- ) {
- await removeMediaFile(opts.videoDir, source);
+ // A COPY ALREADY IN THE STORE IS NEVER DISCARDED, NOR IS THE DOWNLOAD
+ // (ytdlp/savedAlternates.ts): both are kept, one active. When the one in the
+ // store stays active the download goes beside it and nothing is extracted
+ // from it.
+ const alternatesDeps: SavedAlternatesDeps = opts.alternatesDeps ?? {
+ measure: (file) => probeMediaDurationSec({ ffprobeBin: opts.paths.ffprobeBin, file }),
+ height: (file) => probeVideoHeight({ ffprobeBin: opts.paths.ffprobeBin, file }),
+ };
+ const plan = opts.persist
+ ? await planSavedContainer({
+ videoDir: opts.videoDir,
+ newContainer: path.join(opts.videoDir, source),
+ ...(opts.format?.height ? { newHeight: opts.format.height } : {}),
+ explicit: opts.explicitPersist === true,
+ deps: alternatesDeps,
+ })
+ : null;
+ if (plan?.active === "existing") {
+ try {
+ await keepDownloadAsAlternate(plan, {
+ sourceFilename: source,
+ origin: opts.origin,
+ format: opts.format,
+ paths: opts.paths,
+ deps: alternatesDeps,
+ onLog: opts.onLog,
+ });
+ } catch (err) {
+ opts.onLog(
+ `Failed to keep ${source} beside the saved container (${(err as Error).message}); leaving it in the data dir.
+`,
+ );
+ }
return;
}
if (opts.extractAudio === false) {
@@ -118,21 +150,32 @@ export async function finalizeAppExtraction(opts: {
opts.channelSlug,
opts.videoId,
);
+ const keepReason = opts.category === "none" ? undefined : opts.category;
try {
- const pointer = await persistSourceVideo({
- videoDir: opts.videoDir,
- sourceFilename: source,
- storeDir,
- keepReason: opts.category === "none" ? undefined : opts.category,
- origin: opts.origin,
- ...(opts.format ? { format: opts.format } : {}),
- // The store-in-transition guard. A move of the saved-video store is a
- // multi-hour copy, and a container landing in the middle of it is lost
- // three different ways — see lib/savedVideoStore.ts. The catch below is
- // already the right handling: the container stays in the data dir with a
- // line in the log, and the next persist (after the move) picks it up.
- paths: opts.paths,
- });
+ const pointer = plan
+ ? await persistOverExisting(plan, {
+ sourceFilename: source,
+ keepReason,
+ origin: opts.origin,
+ format: opts.format,
+ paths: opts.paths,
+ deps: alternatesDeps,
+ onLog: opts.onLog,
+ })
+ : await persistSourceVideo({
+ videoDir: opts.videoDir,
+ sourceFilename: source,
+ storeDir,
+ keepReason,
+ origin: opts.origin,
+ ...(opts.format ? { format: opts.format } : {}),
+ // The store-in-transition guard. A move of the saved-video store is a
+ // multi-hour copy, and a container landing in the middle of it is lost
+ // three different ways — see lib/savedVideoStore.ts. The catch below is
+ // already the right handling: the container stays in the data dir with a
+ // line in the log, and the next persist (after the move) picks it up.
+ paths: opts.paths,
+ });
opts.onLog(
`Persisted source video to ${path.join(pointer.dir, pointer.file)} (${pointer.bytes} bytes).\n`,
);
diff --git a/common/ytdlp/landedGuard.ts b/common/ytdlp/landedGuard.ts
@@ -14,10 +14,10 @@
// (KEEP_LONGER_TOLERANCE_SECONDS of slack; a tie keeps the landed
// one) and the other is removed with removeMediaFile. No new file
// (a failed or skipped download): the aside one goes back.
-// container finalizeAppExtraction asks `landedContainerWins` before it
-// extracts or persists: when the store holds a landed container
-// as long or longer than the new one, the new one is discarded,
-// and so is its audio extraction.
+// container NEITHER COPY IS DISCARDED (ytdlp/savedAlternates.ts, asked by
+// finalizeAppExtraction for any video with a container already
+// in the store): both are kept, one active, the other an
+// alternate flagged on the pointer for a later check.
//
// Every decision is appended to media-import.json's `challenges`.
@@ -27,7 +27,6 @@ import { KEEP_LONGER_TOLERANCE_SECONDS, type MediaImportChallenge } from "../lib
import { isRealAudioFile, pickPreferredAudio } from "../lib/mediaFiles";
import { mediaImportSidecar } from "../lib/mediaImport-server";
import { removeMediaFile, renameMediaFile } from "../lib/mediaTier-server";
-import { savedVideoPath } from "../lib/savedVideo";
import { loadSavedVideo } from "../lib/savedVideo-server";
export const LANDED_KEPT_SUFFIX = ".landed-kept";
@@ -42,7 +41,7 @@ export type LandedGuardPlan = { videoDir: string; asides: string[] };
// attach-media too: a container attached from a local archive is a recording
// somebody kept on purpose (keepReason "pin"), as an import is.
-const LANDED_BY: ReadonlySet<string> = new Set(["import-media", "record-live", "attach-media"]);
+export const LANDED_BY: ReadonlySet<string> = new Set(["import-media", "record-live", "attach-media"]);
// Was this video's source landed (rather than downloaded)?
export async function isLandedVideo(videoDir: string): Promise<boolean> {
@@ -51,7 +50,7 @@ export async function isLandedVideo(videoDir: string): Promise<boolean> {
return pointer?.origin?.requestedBy !== undefined && LANDED_BY.has(pointer.origin.requestedBy);
}
-async function recordChallenge(videoDir: string, c: MediaImportChallenge): Promise<void> {
+export async function recordChallenge(videoDir: string, c: MediaImportChallenge): Promise<void> {
const prev = await mediaImportSidecar.load(videoDir);
if (!prev) return;
await mediaImportSidecar.write(videoDir, { ...prev, challenges: [...(prev.challenges ?? []), c].slice(-50) });
@@ -126,33 +125,3 @@ export async function settleLandedGuard(
kept: newWins ? "download" : "landed",
});
}
-
-// Before a downloaded container is extracted and persisted: does a landed
-// container in the store, as long or longer, win? Then the caller discards the
-// new one (and extracts nothing from it).
-export async function landedContainerWins(
- videoDir: string,
- newContainer: string,
- deps: LandedGuardDeps,
- onLog: (s: string) => void,
-): Promise<boolean> {
- const pointer = await loadSavedVideo(videoDir);
- if (!pointer?.origin?.requestedBy || !LANDED_BY.has(pointer.origin.requestedBy)) return false;
- const landedSeconds = await deps.measure(savedVideoPath(pointer));
- if (landedSeconds === null) return false;
- const newSeconds = await deps.measure(newContainer);
- const landedWins = newSeconds === null || newSeconds <= landedSeconds + KEEP_LONGER_TOLERANCE_SECONDS;
- onLog(
- `The store holds a landed ${pointer.file} (${landedSeconds} s); the download's container is ${newSeconds ?? "?"} s: ` +
- `${landedWins ? "the landed one stays and the download's is discarded" : "the download's is longer and replaces it"}.\n`,
- );
- await recordChallenge(videoDir, {
- at: (deps.now?.() ?? new Date()).toISOString(),
- by: "download",
- what: "container",
- newSeconds,
- landedSeconds,
- kept: landedWins ? "landed" : "download",
- });
- return landedWins;
-}
diff --git a/common/ytdlp/savedAlternates.test.ts b/common/ytdlp/savedAlternates.test.ts
@@ -0,0 +1,320 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import type { SavedVideoPointer } from "../lib/savedVideo";
+import { savedAlternatesLine } from "../lib/savedVideo";
+import {
+ dropSavedVideo,
+ loadSavedVideo,
+ persistSourceVideo,
+ resolveSavedVideo,
+ unpersistSavedVideo,
+} from "../lib/savedVideo-server";
+import { findSourceMedia, isSourceMediaFile } from "../lib/mediaFiles";
+import { wholeContainersOf } from "../lib/evidenceClip.mjs";
+import { isDoNotClean, setDoNotClean } from "../lib/doNotClean-server";
+import { mediaImportSidecar } from "../lib/mediaImport-server";
+import { listSavedAlternates, savedVideoTotals } from "../controller/savedVideoInventory";
+import { pruneSavedVideos } from "../controller/pruneSavedVideos";
+import { finalizeAppExtraction } from "./finalizeAppExtraction";
+import { alternateName, persistOverExisting, planSavedContainer, type SavedAlternatesDeps } from "./savedAlternates";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/savedAlternates.test.ts
+//
+// A download over a container already in the saved-video store keeps BOTH
+// (ytdlp/savedAlternates.ts): which is active, what the pointer flags, that no
+// reader takes the alternate for a source, and that nothing deletes one
+// silently. A temp corpus; a "container" is a text file whose content names
+// its length and height, read by injected measure/height deps.
+
+const CONFIG = { handling: "transcribe", platform: "rumble", url: "https://rumble.com/c/Synth" } as ChannelConfig;
+const SLUG = "synth-rumble";
+const NOW = new Date("2026-10-23T17:23:12.000Z");
+
+async function withCorpus(fn: (paths: Paths) => Promise<void>): Promise<void> {
+ const dir = await mkdtemp(path.join(tmpdir(), "saved-alternates-"));
+ const paths = {
+ transcriptsDir: dir,
+ channelsDir: path.join(dir, "channels"),
+ savedVideosDir: path.join(dir, "saved-videos"),
+ ffprobeBin: "/nonexistent/ffprobe",
+ ffmpegBin: "/nonexistent/ffmpeg",
+ } as Paths;
+ try {
+ await fn(paths);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+}
+
+function fakeMedia(tag: string, seconds: number, height: number): string {
+ return `${tag};seconds=${seconds};height=${height}`;
+}
+const deps: SavedAlternatesDeps = {
+ measure: async (f) => {
+ const m = /seconds=([\d.]+)/.exec(await readFile(f, "utf8").catch(() => ""));
+ return m ? Number(m[1]) : null;
+ },
+ height: async (f) => {
+ const m = /height=(\d+)/.exec(await readFile(f, "utf8").catch(() => ""));
+ return m ? Number(m[1]) : null;
+ },
+ now: () => NOW,
+};
+
+function videoDirOf(paths: Paths, id: string): string {
+ return path.join(paths.channelsDir, SLUG, "data", id);
+}
+
+// A video whose container is already in the store: landed (import-media, a
+// pin, with media-import.json) or an ordinary download.
+async function seed(
+ paths: Paths,
+ id: string,
+ opts: { landed?: boolean; seconds?: number; height?: number; keepReason?: "pin" | "keep-latest"; requestedBy?: string } = {},
+): Promise<string> {
+ const dir = videoDirOf(paths, id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "source-media.mp4"), fakeMedia("old", opts.seconds ?? 4696.629777, opts.height ?? 360));
+ await persistSourceVideo({
+ videoDir: dir,
+ sourceFilename: "source-media.mp4",
+ storeDir: path.join(paths.savedVideosDir, SLUG, id),
+ keepReason: opts.keepReason ?? (opts.landed ? "pin" : "keep-latest"),
+ ...(opts.landed
+ ? { origin: { requestedBy: "import-media", kind: "local-archive" as const, archive: "/x/cap.zip", entry: "cap.mp4" } }
+ : opts.requestedBy
+ ? { origin: { requestedBy: opts.requestedBy } }
+ : {}),
+ ...(opts.landed ? {} : { format: { preset: "original" as const, height: opts.height ?? 360 } }),
+ });
+ if (opts.landed) {
+ await mediaImportSidecar.write(dir, {
+ entries: [
+ {
+ at: "2026-10-22T00:00:00.000Z",
+ via: "import-media",
+ source: { path: "/x/cap.mp4", name: "cap.mp4", bytes: 10 },
+ finalized: "copied",
+ container: { file: "source-media.mp4", seconds: 4696.629777, bytes: 10 },
+ kept: "new",
+ audio: "skipped",
+ },
+ ],
+ });
+ }
+ return dir;
+}
+
+// The download's container, as yt-dlp leaves it in data/<id>/, finalized as a
+// forced persist over a transcript (no audio extracted).
+async function download(
+ paths: Paths,
+ dir: string,
+ opts: { explicit: boolean; seconds?: number; height?: number },
+): Promise<string> {
+ await writeFile(path.join(dir, "source-media.mp4"), fakeMedia("new", opts.seconds ?? 4696.479777, opts.height ?? 720));
+ const log: string[] = [];
+ await finalizeAppExtraction({
+ paths,
+ channelSlug: SLUG,
+ channelConfig: CONFIG,
+ videoDir: dir,
+ videoId: path.basename(dir),
+ fmt: "mp3",
+ persist: true,
+ category: "override",
+ extractAudio: false,
+ format: { preset: "video_720", height: opts.height ?? 720, vcodec: "avc1" },
+ explicitPersist: opts.explicit,
+ alternatesDeps: deps,
+ onLog: (s) => void log.push(s),
+ signal: new AbortController().signal,
+ });
+ return log.join("");
+}
+
+const ALT_360 = "source-media.alt-360p-20261023172312.mp4";
+const ALT_720 = "source-media.alt-720p-20261023172312.mp4";
+
+async function storeFiles(p: SavedVideoPointer): Promise<string[]> {
+ return (await readdir(p.dir)).sort();
+}
+
+test("an explicit persist over a landed copy: both kept, the download active, the landed one flagged; the pin stays", async () => {
+ await withCorpus(async (paths) => {
+ const dir = await seed(paths, "v7h6xzw", { landed: true });
+ await setDoNotClean(dir, true, "keep");
+ const log = await download(paths, dir, { explicit: true });
+ assert.match(
+ log,
+ /Kept both copies: the download \(720p, 4696\.5 s\) is now the active source; the landed one \(360p, 4696\.6 s\) stays as source-media\.alt-360p-20261023172312\.mp4\. Flagged for a check\.\n/,
+ );
+ const p = (await loadSavedVideo(dir))!;
+ assert.equal(p.file, "source-media.mp4");
+ assert.match(await readFile(path.join(p.dir, p.file), "utf8"), /^new/);
+ assert.deepEqual(await storeFiles(p), [ALT_360, "source-media.mp4"]);
+ assert.match(await readFile(path.join(p.dir, ALT_360), "utf8"), /^old/);
+ // A pin stays a pin; the do-not-clean marker is untouched.
+ assert.equal(p.keepReason, "pin");
+ assert.ok(await isDoNotClean(dir));
+ // The landed provenance moved to the alternate; the active one is a download.
+ assert.equal(p.origin, undefined);
+ assert.equal(p.format?.height, 720);
+ assert.deepEqual(p.probed, { seconds: 4696.479777, height: 720 });
+ assert.equal(p.alternates?.length, 1);
+ const alt = p.alternates![0]!;
+ assert.equal(alt.file, ALT_360);
+ assert.equal(alt.height, 360);
+ assert.equal(alt.seconds, 4696.629777);
+ assert.equal(alt.origin?.requestedBy, "import-media");
+ assert.equal(alt.origin?.kind, "local-archive");
+ assert.equal(alt.setAsideAt, NOW.toISOString());
+ // The flag in the landing's own history.
+ const c = (await mediaImportSidecar.load(dir))?.challenges?.at(-1);
+ assert.equal(c?.kept, "download");
+ assert.equal(c?.alternate, ALT_360);
+ assert.equal(c?.explicit, true);
+ assert.equal(
+ savedAlternatesLine(p),
+ "2 saved copies: active 720p, 4696.5 s (download); alternate 360p, 4696.6 s (import-media, source-media.alt-360p-20261023172312.mp4)",
+ );
+ });
+});
+
+test("an explicit persist much shorter than the landed copy still becomes active; nothing is deleted", async () => {
+ await withCorpus(async (paths) => {
+ const dir = await seed(paths, "vshort", { landed: true });
+ const log = await download(paths, dir, { explicit: true, seconds: 4696.629777 - 300 });
+ assert.match(log, /the download \(720p, 4396\.6 s\) is now the active source/);
+ const p = (await loadSavedVideo(dir))!;
+ assert.deepEqual(await storeFiles(p), [ALT_360, "source-media.mp4"]);
+ // A second one: the first download joins the alternates, which accumulate.
+ await download(paths, dir, { explicit: true, height: 1080 });
+ const p2 = (await loadSavedVideo(dir))!;
+ assert.deepEqual(p2.alternates?.map((a) => a.file), [ALT_360, ALT_720]);
+ assert.deepEqual(await storeFiles(p2), [ALT_360, ALT_720, "source-media.mp4"]);
+ assert.equal(p2.keepReason, "pin");
+ });
+});
+
+test("an automatic download over a landed copy of the same length: both kept, the landed one stays active", async () => {
+ await withCorpus(async (paths) => {
+ const dir = await seed(paths, "vauto", { landed: true });
+ await setDoNotClean(dir, true);
+ const log = await download(paths, dir, { explicit: false });
+ assert.match(
+ log,
+ /Kept both copies: the landed one \(360p, 4696\.6 s\) stays the active source \(an automatic download takes over only when it is longer\); the download \(720p, 4696\.5 s\) is kept as source-media\.alt-720p-20261023172312\.mp4\. Flagged for a check\.\n/,
+ );
+ const p = (await loadSavedVideo(dir))!;
+ assert.equal(p.file, "source-media.mp4");
+ assert.match(await readFile(path.join(p.dir, p.file), "utf8"), /^old/);
+ assert.match(await readFile(path.join(p.dir, ALT_720), "utf8"), /^new/);
+ assert.equal(p.origin?.requestedBy, "import-media", "the active copy keeps its own provenance");
+ assert.equal(p.keepReason, "pin");
+ assert.ok(await isDoNotClean(dir));
+ assert.deepEqual(p.alternates?.map((a) => [a.file, a.height, a.preset, a.vcodec]), [[ALT_720, 720, "video_720", "avc1"]]);
+ assert.ok(!(await readdir(dir)).includes("source-media.mp4"), "the download left the data dir");
+ assert.equal((await mediaImportSidecar.load(dir))?.challenges?.at(-1)?.kept, "landed");
+ });
+});
+
+test("an automatic download longer than the copy in the store becomes active; the other is kept", async () => {
+ await withCorpus(async (paths) => {
+ const dir = await seed(paths, "vlong", { requestedBy: "umtool" });
+ const log = await download(paths, dir, { explicit: false, seconds: 5000 });
+ assert.match(log, /the download \(720p, 5000\.0 s\) is now the active source \(it is longer\); the saved one \(360p, 4696\.6 s\) stays as source-media\.alt-360p-20261023172312\.mp4/);
+ const p = (await loadSavedVideo(dir))!;
+ // An ordinary copy's requester and keep-latest class carry over.
+ assert.equal(p.keepReason, "keep-latest");
+ assert.equal(p.origin?.requestedBy, "umtool");
+ assert.deepEqual(await storeFiles(p), [ALT_360, "source-media.mp4"]);
+ });
+});
+
+test("no copy in the store: an ordinary persist, no alternates", async () => {
+ await withCorpus(async (paths) => {
+ const dir = videoDirOf(paths, "vfresh");
+ await mkdir(dir, { recursive: true });
+ const log = await download(paths, dir, { explicit: true });
+ assert.doesNotMatch(log, /Kept both/);
+ const p = (await loadSavedVideo(dir))!;
+ assert.equal(p.alternates, undefined);
+ assert.equal(p.keepReason, "override");
+ });
+});
+
+test("readers never take an alternate for the source", async () => {
+ await withCorpus(async (paths) => {
+ const dir = await seed(paths, "vread", { landed: true });
+ await download(paths, dir, { explicit: true });
+ const p = (await loadSavedVideo(dir))!;
+ assert.equal(await resolveSavedVideo(dir), path.join(p.dir, "source-media.mp4"));
+ for (const name of [ALT_360, "source-media.alt-20261023172312.webm", "source-media.alt-720p-20261023172312-2.mkv"]) {
+ assert.equal(isSourceMediaFile(name), false, name);
+ }
+ assert.equal(findSourceMedia([ALT_360]), null);
+ // Even in the data dir (where unpersist puts it back), the clip tier's
+ // whole-container list does not name it.
+ await writeFile(path.join(dir, ALT_360), "x");
+ assert.deepEqual((await wholeContainersOf(dir)).map((c) => c.name), ["source-media.mp4"]);
+ });
+});
+
+test("the inventory counts and lists alternates; the prune never removes one; drop and unpersist take them along", async () => {
+ await withCorpus(async (paths) => {
+ const dir = await seed(paths, "vprune", { keepReason: "keep-latest" });
+ await download(paths, dir, { explicit: true });
+ const p = (await loadSavedVideo(dir))!;
+ assert.equal(p.keepReason, "keep-latest");
+ const totals = await savedVideoTotals({ paths, channelSlug: SLUG });
+ assert.equal(totals.bytes, p.bytes + p.alternates![0]!.bytes);
+ assert.deepEqual((await listSavedAlternates({ paths })).map((e) => e.videoId), ["vprune"]);
+ // Rolled out of a keep-latest window of 0: kept, with a line saying why.
+ await writeFile(path.join(paths.channelsDir, SLUG, "config.json"), JSON.stringify(CONFIG));
+ const lines: string[] = [];
+ const r = await pruneSavedVideos({ paths, channelSlug: SLUG, onLog: (l) => void lines.push(l) });
+ assert.equal(r.pruned, 0);
+ assert.match(lines.join("\n"), /Kept saved video vprune .* 1 alternate copy flagged for a check/);
+ assert.deepEqual(await storeFiles(p), [ALT_360, "source-media.mp4"]);
+ // Unpersist brings both back to the data dir.
+ assert.equal(await unpersistSavedVideo(dir), true);
+ const back = (await readdir(dir)).sort();
+ assert.ok(back.includes(ALT_360) && back.includes("source-media.mp4"));
+ // Drop (a deliberate whole-video delete) removes both and counts both.
+ const dir2 = await seed(paths, "vdrop", {});
+ await download(paths, dir2, { explicit: true });
+ const p2 = (await loadSavedVideo(dir2))!;
+ assert.equal(await dropSavedVideo(dir2), p2.bytes + p2.alternates![0]!.bytes);
+ assert.deepEqual(await readdir(p2.dir).catch(() => []), []);
+ });
+});
+
+test("a persist that fails after the rename puts the old name back", async () => {
+ await withCorpus(async (paths) => {
+ const dir = await seed(paths, "vfail", { landed: true });
+ await writeFile(path.join(dir, "source-media.mp4"), fakeMedia("new", 4696, 720));
+ const plan = (await planSavedContainer({ videoDir: dir, newContainer: path.join(dir, "source-media.mp4"), explicit: true, deps }))!;
+ await rm(path.join(dir, "source-media.mp4"));
+ await assert.rejects(
+ persistOverExisting(plan, { sourceFilename: "source-media.mp4", deps, onLog: () => {} }),
+ );
+ const p = (await loadSavedVideo(dir))!;
+ assert.deepEqual(await storeFiles(p), ["source-media.mp4"]);
+ assert.equal(p.alternates, undefined);
+ });
+});
+
+test("alternate names: height when known, a numbered suffix on a clash", () => {
+ assert.equal(alternateName("source-media.webm", null, NOW), "source-media.alt-20261023172312.webm");
+ assert.equal(
+ alternateName("source-media.mp4", 720, NOW, [ALT_720]),
+ "source-media.alt-720p-20261023172312-2.mp4",
+ );
+});
diff --git a/common/ytdlp/savedAlternates.ts b/common/ytdlp/savedAlternates.ts
@@ -0,0 +1,274 @@
+// A DOWNLOAD OVER A CONTAINER ALREADY IN THE STORE KEEPS BOTH (operator ruling
+// 2026-10-23: "if you download a format that's different just keep both and
+// flag for a later diagnostic check").
+//
+// Until this, a landed recording (an import, a live recording, an attach — see
+// ytdlp/landedGuard.ts) as long or longer than a later download made the
+// download's container be DISCARDED, so an explicit 720p persist over a 360p
+// capture of the same stream could never land; and any other saved container
+// was overwritten by a re-download. Now finalizeAppExtraction asks here before
+// it extracts or persists, and neither copy is ever removed:
+//
+// which is ACTIVE an explicit persist (persist-videos, "Persist source
+// video", the whole-recording fetch) makes the download
+// active. Any other download keeps the copy in the store
+// active unless the download is longer
+// (KEEP_LONGER_TOLERANCE_SECONDS of slack, a tie keeps
+// what is there; an unmeasurable copy in the store loses).
+// the OTHER copy stays in the same store dir as
+// `source-media.alt-<h>p-<YYYYMMDDHHMMSS>.<ext>` — a name
+// no reader takes for a source (lib/mediaFiles.ts,
+// lib/evidenceClip.mjs anchor on `source-media.<ext>`) —
+// and is listed in the pointer's `alternates` with its
+// length, height and provenance: the flag a later check
+// reads (`pnpm ops get saved-alternates`, /saved-videos).
+// the pointer keeps its `keepReason` (a pin stays a pin) and the
+// do-not-clean marker is not touched. Its `origin` is the
+// download's requester, else the old one's — never a
+// landed copy's, which now describes the alternate.
+//
+// Audio is not part of this: the landed guard's audio half still keeps the
+// longer audio.<fmt> (a transcript was made from it), as before.
+
+import path from "node:path";
+import { readdir, rename, stat } from "node:fs/promises";
+import { KEEP_LONGER_TOLERANCE_SECONDS } from "../lib/mediaImport";
+import {
+ savedVideoPath,
+ type SavedVideoFormat,
+ type SavedVideoKeepReason,
+ type SavedVideoOrigin,
+ type SavedVideoPointer,
+ type SavedVideoProbe,
+} from "../lib/savedVideo";
+import {
+ loadSavedVideo,
+ moveFileCrossDevice,
+ persistSourceVideo,
+ writePointer,
+} from "../lib/savedVideo-server";
+import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore";
+import type { Paths } from "../lib/paths";
+import { LANDED_BY, recordChallenge } from "./landedGuard";
+
+export type SavedAlternatesDeps = {
+ // Seconds of a media file (null: not measurable).
+ measure: (file: string) => Promise<number | null>;
+ // Pixel height of its first video stream (null: none or not measurable).
+ height?: (file: string) => Promise<number | null>;
+ now?: () => Date;
+};
+
+export type SavedContainerPlan = {
+ videoDir: string;
+ existing: SavedVideoPointer;
+ landed: boolean;
+ explicit: boolean;
+ active: "download" | "existing";
+ newSeconds: number | null;
+ newHeight: number | null;
+ oldSeconds: number | null;
+ oldHeight: number | null;
+};
+
+async function exists(file: string): Promise<boolean> {
+ return stat(file).then(
+ () => true,
+ () => false,
+ );
+}
+
+// Before a downloaded container is extracted and persisted: is there a copy in
+// the store already, and which of the two will be active? Null when the store
+// holds none (no pointer, or its file is gone) — the persist is an ordinary one.
+export async function planSavedContainer(opts: {
+ videoDir: string;
+ newContainer: string;
+ // The download's height as yt-dlp reported it, when it did.
+ newHeight?: number;
+ explicit: boolean;
+ deps: SavedAlternatesDeps;
+}): Promise<SavedContainerPlan | null> {
+ const existing = await loadSavedVideo(opts.videoDir);
+ if (!existing) return null;
+ const oldFile = savedVideoPath(existing);
+ if (!(await exists(oldFile))) return null;
+ const { deps } = opts;
+ const newSeconds = await deps.measure(opts.newContainer);
+ const oldSeconds = await deps.measure(oldFile);
+ const newHeight = opts.newHeight ?? (await deps.height?.(opts.newContainer)) ?? null;
+ const oldHeight =
+ existing.format?.height ?? existing.probed?.height ?? (await deps.height?.(oldFile)) ?? null;
+ const longer =
+ newSeconds !== null &&
+ (oldSeconds === null || newSeconds > oldSeconds + KEEP_LONGER_TOLERANCE_SECONDS);
+ return {
+ videoDir: opts.videoDir,
+ existing,
+ landed: existing.origin?.requestedBy !== undefined && LANDED_BY.has(existing.origin.requestedBy),
+ explicit: opts.explicit,
+ active: opts.explicit || longer ? "download" : "existing",
+ newSeconds,
+ newHeight,
+ oldSeconds,
+ oldHeight,
+ };
+}
+
+function stampOf(at: Date): string {
+ return at.toISOString().replace(/\D/g, "").slice(0, 14);
+}
+
+// `source-media.alt-<h>p-<stamp>.<ext>`, unique in `taken`.
+export function alternateName(file: string, height: number | null, at: Date, taken: Iterable<string> = []): string {
+ const ext = path.extname(file);
+ const stem = `source-media.alt-${height ? `${height}p-` : ""}${stampOf(at)}`;
+ const names = new Set(taken);
+ let name = `${stem}${ext}`;
+ for (let n = 2; names.has(name); n++) name = `${stem}-${n}${ext}`;
+ return name;
+}
+
+function describe(height: number | null, seconds: number | null): string {
+ return `${height ? `${height}p` : "height unknown"}, ${seconds !== null ? `${seconds.toFixed(1)} s` : "length unknown"}`;
+}
+
+function probeOf(seconds: number | null, height: number | null): SavedVideoProbe | undefined {
+ const p: SavedVideoProbe = {};
+ if (seconds !== null) p.seconds = seconds;
+ if (height !== null) p.height = height;
+ return Object.keys(p).length ? p : undefined;
+}
+
+async function flag(plan: SavedContainerPlan, alternate: string, at: Date): Promise<void> {
+ if (!plan.landed) return;
+ await recordChallenge(plan.videoDir, {
+ at: at.toISOString(),
+ by: "download",
+ what: "container",
+ newSeconds: plan.newSeconds,
+ landedSeconds: plan.oldSeconds,
+ kept: plan.active === "download" ? "download" : "landed",
+ alternate,
+ ...(plan.explicit ? { explicit: true } : {}),
+ });
+}
+
+// The copy in the store stays active: the download's container moves into the
+// same store dir under an alternate name, and the pointer lists it.
+export async function keepDownloadAsAlternate(
+ plan: SavedContainerPlan,
+ opts: {
+ sourceFilename: string;
+ origin?: SavedVideoOrigin;
+ format?: SavedVideoFormat | null;
+ paths?: Pick<Paths, "transcriptsDir" | "savedVideosDir">;
+ deps: SavedAlternatesDeps;
+ onLog: (s: string) => void;
+ },
+): Promise<string> {
+ const { existing, videoDir } = plan;
+ if (opts.paths) await assertSavedVideosStoreWritable(opts.paths, existing.dir);
+ const at = opts.deps.now?.() ?? new Date();
+ const src = path.join(videoDir, opts.sourceFilename);
+ const alt = alternateName(opts.sourceFilename, plan.newHeight, at, await readdir(existing.dir).catch(() => []));
+ const { size } = await stat(src);
+ await moveFileCrossDevice(src, path.join(existing.dir, alt));
+ const probed = probeOf(plan.oldSeconds, plan.oldHeight);
+ await writePointer(videoDir, {
+ ...existing,
+ ...(probed ? { probed } : {}),
+ alternates: [
+ ...(existing.alternates ?? []),
+ {
+ file: alt,
+ bytes: size,
+ storedAt: at.toISOString(),
+ setAsideAt: at.toISOString(),
+ ...(plan.newSeconds !== null ? { seconds: plan.newSeconds } : {}),
+ ...(plan.newHeight !== null ? { height: plan.newHeight } : {}),
+ ...(opts.format?.vcodec ? { vcodec: opts.format.vcodec } : {}),
+ ...(opts.origin ? { origin: opts.origin } : {}),
+ ...(opts.format?.preset ? { preset: opts.format.preset } : {}),
+ },
+ ],
+ });
+ const which = plan.landed ? "landed" : "saved";
+ opts.onLog(
+ `Kept both copies: the ${which} one (${describe(plan.oldHeight, plan.oldSeconds)}) stays the active source ` +
+ `(an automatic download takes over only when it is longer); the download (${describe(plan.newHeight, plan.newSeconds)}) ` +
+ `is kept as ${alt}. Flagged for a check.\n`,
+ );
+ await flag(plan, alt, at);
+ return alt;
+}
+
+// The download becomes active: the copy in the store is renamed to an
+// alternate name in its own dir, the download is persisted beside it (same
+// dir, so the two stay together), and the pointer lists the old one. A persist
+// that fails puts the old name back, so the pointer never names a missing file.
+export async function persistOverExisting(
+ plan: SavedContainerPlan,
+ opts: {
+ sourceFilename: string;
+ keepReason?: SavedVideoKeepReason;
+ origin?: SavedVideoOrigin;
+ format?: SavedVideoFormat | null;
+ paths?: Pick<Paths, "transcriptsDir" | "savedVideosDir">;
+ deps: SavedAlternatesDeps;
+ onLog: (s: string) => void;
+ },
+): Promise<SavedVideoPointer> {
+ const { videoDir } = plan;
+ // Re-read: an extraction ran since the plan.
+ const old = (await loadSavedVideo(videoDir)) ?? plan.existing;
+ if (opts.paths) await assertSavedVideosStoreWritable(opts.paths, old.dir);
+ const at = opts.deps.now?.() ?? new Date();
+ const alt = alternateName(old.file, plan.oldHeight, at, await readdir(old.dir).catch(() => []));
+ await rename(path.join(old.dir, old.file), path.join(old.dir, alt));
+ const keptOrigin = old.origin && !LANDED_BY.has(old.origin.requestedBy) ? old.origin : undefined;
+ let pointer: SavedVideoPointer;
+ try {
+ pointer = await persistSourceVideo({
+ videoDir,
+ sourceFilename: opts.sourceFilename,
+ storeDir: old.dir,
+ // A pin stays a pin; a keep-latest container stays evictable.
+ keepReason: old.keepReason ?? opts.keepReason,
+ origin: opts.origin ?? keptOrigin,
+ ...(opts.format ? { format: opts.format } : {}),
+ ...(opts.paths ? { paths: opts.paths } : {}),
+ });
+ } catch (err) {
+ await rename(path.join(old.dir, alt), path.join(old.dir, old.file)).catch(() => {});
+ throw err;
+ }
+ const probed = probeOf(plan.newSeconds, plan.newHeight);
+ pointer = {
+ ...pointer,
+ ...(probed ? { probed } : {}),
+ alternates: [
+ ...(pointer.alternates ?? []),
+ {
+ file: alt,
+ bytes: old.bytes,
+ storedAt: old.storedAt,
+ setAsideAt: at.toISOString(),
+ ...(plan.oldSeconds !== null ? { seconds: plan.oldSeconds } : {}),
+ ...(plan.oldHeight !== null ? { height: plan.oldHeight } : {}),
+ ...(old.format?.vcodec ? { vcodec: old.format.vcodec } : {}),
+ ...(old.origin ? { origin: old.origin } : {}),
+ ...(old.format?.preset ? { preset: old.format.preset } : {}),
+ },
+ ],
+ };
+ await writePointer(videoDir, pointer);
+ const which = plan.landed ? "landed" : "saved";
+ const why = plan.explicit ? "" : " (it is longer)";
+ opts.onLog(
+ `Kept both copies: the download (${describe(plan.newHeight, plan.newSeconds)}) is now the active source${why}; ` +
+ `the ${which} one (${describe(plan.oldHeight, plan.oldSeconds)}) stays as ${alt}. Flagged for a check.\n`,
+ );
+ await flag(plan, alt, at);
+ return pointer;
+}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,8 +1,10 @@
# Changelog
## [Unreleased]
+- **A Transcribe holds the platform's queue only while it downloads.** The video page's Audio + Whisper and `pnpm ops transcribe-one` used to keep YouTube's (or any platform's) download queue for the whole transcription, so nothing else downloaded on that platform while it waited for a worker and transcribed. Now the audio download runs on the platform's queue and the transcription runs as its own job on the video's queue (`transcribe-one:<slug>:<id>`); with the audio already on disk it starts there at once. The run panel and `pnpm ops … --wait` follow both jobs to the end of the transcription, and the first job's log names the second. `pnpm ops transcribe-one` with `"file"` now runs on the video's own queue unless a download is owed, takes `"queueKey"`, and for a YouTube video whose captions are listed and that has no audio fetches the captions instead (says so, and refuses when the captions are already on disk) unless `"asr": true` is passed. Needs a restart of the editor.
- **A report video can set a subject's own claims against the record on its timeline.** A count claim (`“less than ten” in a year`) draws a band over the dates it is about on the on-screen panel's timeline, dims the rest of the timeline, lights each clip that carries the counter's stamps in date order with its count under it, and counts up to the total under his words in the panel (`19 seizures on camera`). With a **per** (a day, a week, a month) it lights every span that holds that many or more instead (`12 in a day`, `4 in a week`). A goalpost (`“3–5 weeks”` → `“6–8 weeks”`) draws a hollow bracket over the dates each deadline implies; when he moves it, the old one stays dashed and a copy of it moves to the new dates, off the timeline's end with the dates written when they are past its last clip. The finale's large timeline shows every claim at the end. A stamp can be dated by the day the event happened rather than the clip's day (**happened** in the clip editor's Marks). In umtool: the On-screen section's **claim checks** (beside the markers), with **use the playhead** and the build's own checks shown as each field is typed. From a terminal: `umtool look <project> deck.claims='[…]'` and `umtool set <project> <clip> claim.eventDate=2026-09-22`. When the record does not contradict a claim the build prints a note. A video without claims builds exactly as before. Needs a restart of umtool and a rebuild of the video.
- **umtool plays a whole report video, or one take of it, in the browser without rendering it, and takes timecoded notes as it plays.** The Cut tab's **Play the cut** (and **Play** beside each take on the takes page) opens `/projects/<project>/play`: every clip plays in order from its fetched window, with the on-screen panel, the tally, the stamps, the markers and the finale drawn over it as the live preview draws them, on one clock across the whole cut, the next clip loaded behind the one playing. A take plays the project's video as it is now with the take's changes, including a take with its own clip list and one a recipe names that was never rendered; **Blurred clips: uncensored** on a take plays its clips as recorded. Under the picture, the **reel strip** shows the whole cut at once: a cell per clip or card as wide as it plays, shaded by the recording's date, hatched when its media is not fetched, the sections' boundaries with their first date, the counter (the tally) drawn as a staircase with its total at the end and at the playhead, and each note as a pin; click or drag on it to move through the cut. Under the strip, **Now** shows what the clip on screen says with the spoken line lit, and which clip comes next. Space plays and pauses, J K L go back, pause and play (L again is faster, at the voice's own pitch), ← and → move 5 seconds, N and P move between clips, [ and ] between notes, and ? lists the keys. A line under the picture lists what it does not do: each crossfade is a hard cut at its middle, cards and teasers are placeholders with their heading, edges are not snapped to silence, and the sound is the recording's. A clip with nothing fetched says "No media for this clip — fetch it" and the video plays on. M (or **Note at 09:44**) saves a note at that second of the cut, naming the clip on screen, its second in the recording, the take, and what it asks for (Trim, Cut, Move, Fact, Look or Other); playback pauses while you write and goes on when it is saved (**Pause while I write**). The notes list in cut order (open, all or resolved), a timecode plays from there, `umtool notes <project>` prints each with where it was taken and what it asks for, and **Send to the assistant** on a note (or **Send N open notes to the assistant**) asks the video assistant, whose reply lands on the note and whose edits wait for **Apply all**. With no assistant configured the button says why. Needs a restart of umtool.
+- **A download over a copy already saved keeps both, and flags them for a check.** An import, an attach or a live recording that was as long as a later download used to make that download be thrown away, so asking for a 720p copy of a stream already held as a 360p capture (`pnpm ops persist-videos` with `"format": "video_720"`) downloaded it and then discarded it. Now no copy is deleted. **Persist source video**, `persist-videos` and a whole-recording fetch make the download the copy everything uses; any other download keeps the saved copy in use unless it is longer. The other copy stays beside it in the saved-video store as `source-media.alt-<height>p-<date>.<ext>`, which no reader takes for the source, and the log says so: "Kept both copies: the download (720p, 4696.5 s) is now the active source; the landed one (360p, 4696.6 s) stays as source-media.alt-360p-20261023172312.mp4. Flagged for a check." A pinned video stays pinned, and `"replace": "above-height"` keeps the taller copy beside the new one rather than removing it. /saved-videos lists every video with two copies, with both copies' height, length and origin, and counts both in its sizes; `pnpm ops get saved-alternates [<slug>]` lists the same. The keep-latest prune leaves such a video alone. Needs a restart of the editor.
- **umtool's clip walk goes through the recordings in date order.** `p`/`n` and the Cut tab's walk used to follow the cut, which can open on a finale and end years earlier. The walk now goes by each clip's date (its on-screen date, else the recording's upload date), with a recording's clips together in the order they come in it, so what is left out between two clips, or split off into a clip of its own, comes up next. The cut's own order is unchanged.
- **A clip from a stream captured live can be trimmed again in umtool's clip editor.** Such a stream's record has no length, which umtool passed on as zero, so every drag of a clip's edge snapped back to the left with "that is the edge of what is cached". An unknown length is now treated as unknown.
- **umtool's clip editor opens a clip from a whole saved recording as a short excerpt.** When the only file holding a clip was the whole recording (hours long), the editor used all of it as its view: a waveform of the whole stream with the clip a sliver in it, and a video seeking hours into a large file. It now cuts the clip and 45 seconds either side from the recording once, on the umtool machine, and works on that; the cut starts when the clip is opened and is kept for the next time. The rendered video still cuts from the whole recording.
diff --git a/editor/app/api/jobs/[id]/log/route.ts b/editor/app/api/jobs/[id]/log/route.ts
@@ -58,5 +58,8 @@ export async function GET(
status,
queueKey,
queuePosition,
+ // The job its work went on in (JobRecord.handedOffTo): `pnpm ops --wait`
+ // follows it there.
+ ...(record?.handedOffTo ? { handedOffTo: record.handedOffTo } : {}),
});
}
diff --git a/editor/app/api/ops/_read.test.ts b/editor/app/api/ops/_read.test.ts
@@ -46,7 +46,7 @@ const route = async (name: string) => (await import(`./${name}/route`)).GET as G
test.after(() => corpus.cleanup());
test("every read route is behind the token", async () => {
- for (const name of ["settings", "storage", "sites", "workers", "auto-queue", "scheduler"]) {
+ for (const name of ["settings", "storage", "sites", "workers", "auto-queue", "scheduler", "saved-alternates"]) {
const res = await callGet(await route(name), undefined, {}, {});
assert.equal(res.status, 401, name);
}
@@ -135,6 +135,18 @@ test("get workers, auto-queue, scheduler and storage answer their pages' payload
assert.equal(storage.status, 200, JSON.stringify(storage.body));
});
+test("get saved-alternates lists the saved videos holding two copies (none here); a bad slug is a 400", async () => {
+ const get = await route("saved-alternates");
+ const all = await callGet(get);
+ assert.equal(all.status, 200, JSON.stringify(all.body));
+ assert.equal(all.body.count, 0);
+ assert.deepEqual(all.body.videos, []);
+ const one = await callGet(get, "http://localhost/api/ops/saved-alternates?slug=test-youtube");
+ assert.equal(one.status, 200, JSON.stringify(one.body));
+ const bad = await callGet(get, "http://localhost/api/ops/saved-alternates?slug=../x");
+ assert.equal(bad.status, 400);
+});
+
test("/api/auto-queue/control is behind the ops token now", async () => {
const { POST } = await import("../auto-queue/control/route");
const anon = await callPost(POST, { kind: "download", action: "stop" }, {});
diff --git a/editor/app/api/ops/saved-alternates/route.ts b/editor/app/api/ops/saved-alternates/route.ts
@@ -0,0 +1,48 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { savedAlternatesLine } from "yt-dlp-transcript-common/lib/savedVideo";
+import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels";
+import { listSavedAlternates } from "yt-dlp-transcript-common/controller/savedVideoInventory";
+import { readRoute } from "../_read";
+import { opsFail } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// GET [?slug=<channel>]
+// -> { ok, count, videos: [{ slug, id, line, dir, active: { file, bytes,
+// height?, seconds?, origin?, storedAt }, alternates: [...] }],
+// notAnswering: [slug] }
+//
+// Every saved video that holds two copies (ytdlp/savedAlternates.ts): a
+// download over a container already in the store keeps both, one active and
+// the other flagged here for a check. The /saved-videos page lists the same.
+// Pointers only — no container is opened. Nothing is written.
+export async function GET(request: Request) {
+ return readRoute(request, ["slug"], async (q) => {
+ const slug = q.get("slug")?.trim() || undefined;
+ if (slug && !isValidChannelSlug(slug)) return opsFail(`"${slug}" is not a valid channel slug`);
+ const notAnswering: string[] = [];
+ const entries = await listSavedAlternates({ paths: getPaths(), channelSlug: slug, notAnswering });
+ return {
+ count: entries.length,
+ videos: entries.map((e) => ({
+ slug: e.slug,
+ id: e.videoId,
+ line: savedAlternatesLine(e.pointer),
+ dir: e.pointer.dir,
+ active: {
+ file: e.pointer.file,
+ bytes: e.pointer.bytes,
+ ...((e.pointer.format?.height ?? e.pointer.probed?.height)
+ ? { height: e.pointer.format?.height ?? e.pointer.probed?.height }
+ : {}),
+ ...(e.pointer.probed?.seconds ? { seconds: e.pointer.probed.seconds } : {}),
+ ...(e.pointer.keepReason ? { keepReason: e.pointer.keepReason } : {}),
+ ...(e.pointer.origin ? { origin: e.pointer.origin } : {}),
+ storedAt: e.pointer.storedAt,
+ },
+ alternates: e.pointer.alternates ?? [],
+ })),
+ notAnswering: notAnswering.sort(),
+ };
+ });
+}
diff --git a/editor/app/api/ops/transcribe-one/route.test.ts b/editor/app/api/ops/transcribe-one/route.test.ts
@@ -0,0 +1,216 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { callPost, setupOpsCorpus } from "../_testCorpus";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/transcribe-one/route.test.ts"
+//
+// `pnpm ops transcribe-one` against a temp corpus, the fake yt-dlp and the
+// fake whisper (e2e/fixtures/bin) — nothing here asks a real platform:
+//
+// - the whisper-video HANDS OFF: once its audio download is done, the
+// platform's queue is free — a download queued behind it runs while the
+// transcription it handed off still waits for a worker;
+// - with audio on disk the job is a transcribe-one on the video's own queue
+// (`transcribe-one:<slug>:<id>`), "file" or not;
+// - a youtube-handling video with English captions listed and no audio has
+// its captions fetched instead; "asr": true transcribes it anyway.
+
+const corpus = await setupOpsCorpus(null);
+const SLUG = "handoff-yt";
+await corpus.writeSettings({ minFreeDiskGB: 0, pacing: { jobGapSeconds: { youtube: 0, default: 0 } } });
+await corpus.writeChannelConfig(SLUG, {
+ handling: "youtube",
+ platform: "youtube",
+ url: "https://www.youtube.com/@handoff",
+ audioFormat: "mp3",
+});
+
+type Post = Parameters<typeof callPost>[0];
+const POST = (await import("./route")).POST as Post;
+const { downloadVideoPipelineAction } = await import("../../../channels/[slug]/videos/[id]/videoActions");
+const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry");
+const { getWorkerPool } = await import("yt-dlp-transcript-common/jobs/workerPool");
+test.after(async () => {
+ getWorkerPool().resumeAll();
+ await corpus.cleanup();
+});
+
+const dataDir = (id: string) => path.join(corpus.transcripts, "channels", SLUG, "data", id);
+const exists = (p: string) => stat(p).then(() => true, () => false);
+
+async function video(id: string, meta: Record<string, unknown> = {}, files: Record<string, string> = {}) {
+ const dir = dataDir(id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(
+ path.join(dir, "metadata.info.json"),
+ JSON.stringify({ id, title: id, webpage_url: `https://www.youtube.com/watch?v=${id}`, ...meta }),
+ );
+ for (const [name, text] of Object.entries(files)) await writeFile(path.join(dir, name), text);
+}
+
+const job = (id: string) => {
+ const r = getRegistry().get(id);
+ if (!r) throw new Error(`no job ${id} in the registry`);
+ return r;
+};
+
+async function until(what: string, ok: () => boolean | Promise<boolean>, ms = 30_000): Promise<void> {
+ const end = Date.now() + ms;
+ while (!(await ok())) {
+ if (Date.now() > end) throw new Error(`timed out waiting for ${what}`);
+ await new Promise((r) => setTimeout(r, 50));
+ }
+}
+
+const ended = (id: string) => ["done", "failed", "cancelled"].includes(job(id).status);
+const logOf = (id: string) => readFile(job(id).logPath, "utf8").catch(() => "");
+
+test("a whisper-video frees platform:youtube once its download is done; a download behind it runs while the transcription waits for a worker", async () => {
+ await video("handoffAAAA");
+ await video("behindBBBBB");
+ // The one GPU worker is busy elsewhere: the transcription parks on it.
+ getWorkerPool().pauseAll();
+ try {
+ const res = await callPost(POST, { slug: SLUG, id: "handoffAAAA" });
+ assert.equal(res.status, 200, JSON.stringify(res.body));
+ const w = String(res.body.jobId);
+ assert.equal(job(w).kind, "whisper-video");
+ assert.equal(job(w).queueKey, "platform:youtube");
+
+ // Queued behind it, on the same platform queue.
+ const d = await downloadVideoPipelineAction(SLUG, "behindBBBBB");
+ if (!d.ok) throw new Error(d.error);
+ void d.stream.cancel();
+ assert.equal(job(d.jobId).queueKey, "platform:youtube");
+
+ await until("the download behind it to end", () => ended(d.jobId));
+ assert.equal(job(d.jobId).status, "done", await logOf(d.jobId));
+ assert.equal(job(w).status, "done", await logOf(w));
+ assert.ok(await exists(path.join(dataDir("handoffAAAA"), "audio.mp3")), "the audio is down");
+
+ // The transcription: its own job, on the video's own queue, still waiting.
+ const t = job(w).handedOffTo;
+ assert.ok(t, "the whisper-video names the job it handed off to");
+ assert.equal(job(t).kind, "transcribe-one");
+ assert.equal(job(t).queueKey, `transcribe-one:${SLUG}:handoffAAAA`);
+ assert.ok(!ended(t), `the transcription is still waiting for a worker (${job(t).status})`);
+ assert.ok(!(await exists(path.join(dataDir("handoffAAAA"), "transcript.json"))));
+ assert.match(await logOf(w), /Transcription handed off to transcribe-one job \S+ \(queue transcribe-one:handoff-yt:handoffAAAA\); platform:youtube is free/);
+ // The sidecar says it too, for a caller that reads it after the registry forgot.
+ const meta = JSON.parse(await readFile(path.join(corpus.transcripts, ".jobs", `${w}.meta.json`), "utf8"));
+ assert.equal(meta.handedOffTo, t);
+ // And researchRuns' jobOf (find-clips, research proposals) follows it.
+ const { jobOfPaths } = await import("yt-dlp-transcript-common/controller/researchRuns");
+ const state = await jobOfPaths({ jobsDir: path.join(corpus.transcripts, ".jobs") })(w);
+ assert.deepEqual({ status: state?.status, via: state?.via }, { status: "running", via: t });
+
+ getWorkerPool().resumeAll();
+ await until("the transcription to end", () => ended(t));
+ assert.equal(job(t).status, "done", await logOf(t));
+ assert.ok(await exists(path.join(dataDir("handoffAAAA"), "transcript.json")));
+ } finally {
+ getWorkerPool().resumeAll();
+ }
+});
+
+test("the run panel's Cancel, after the hand-off, cancels the transcription", async () => {
+ // cancelJobAction (jobs/actions.ts) is registry.cancel(jobDoingTheWork(id))
+ // and a revalidation, which needs a request.
+ const { jobDoingTheWork } = await import("yt-dlp-transcript-common/jobs/handOff");
+ await video("cancelHHHHH");
+ getWorkerPool().pauseAll();
+ try {
+ const res = await callPost(POST, { slug: SLUG, id: "cancelHHHHH" });
+ assert.equal(res.status, 200, JSON.stringify(res.body));
+ const w = String(res.body.jobId);
+ await until("the audio download", () => ended(w));
+ const t = job(w).handedOffTo;
+ assert.ok(t);
+ assert.equal(jobDoingTheWork(w), t);
+ assert.equal(getRegistry().cancel(jobDoingTheWork(w)), true);
+ await until("the transcription to stop", () => ended(t));
+ assert.equal(job(t).status, "cancelled");
+ assert.equal(job(w).status, "done", "the download it did stays done");
+ } finally {
+ getWorkerPool().resumeAll();
+ }
+});
+
+test("with audio on disk the job is a transcribe-one on the video's own queue, with \"file\" or without", async () => {
+ await video("ondiskCCCCC", {}, { "audio.mp3": "fake audio\n" });
+ const withFile = await callPost(POST, { slug: SLUG, id: "ondiskCCCCC", file: "audio.mp3" });
+ assert.equal(withFile.status, 200, JSON.stringify(withFile.body));
+ const a = String(withFile.body.jobId);
+ assert.equal(job(a).kind, "transcribe-one");
+ assert.equal(job(a).queueKey, `transcribe-one:${SLUG}:ondiskCCCCC`);
+ await until("the file's transcription", () => ended(a));
+ assert.equal(job(a).status, "done", await logOf(a));
+
+ await video("ondiskDDDDD", {}, { "audio.mp3": "fake audio\n" });
+ const without = await callPost(POST, { slug: SLUG, id: "ondiskDDDDD" });
+ assert.equal(without.status, 200, JSON.stringify(without.body));
+ const b = String(without.body.jobId);
+ assert.equal(job(b).kind, "transcribe-one", "no whisper-video: nothing to download");
+ assert.equal(job(b).queueKey, `transcribe-one:${SLUG}:ondiskDDDDD`);
+ await until("the transcription", () => ended(b));
+ assert.equal(job(b).status, "done", await logOf(b));
+ assert.match(await logOf(b), /Audio already on disk for ondiskDDDDD; skipping download\./);
+ assert.ok(await exists(path.join(dataDir("ondiskDDDDD"), "transcript.json")));
+
+ // A named queue is the caller's.
+ await video("ondiskEEEEE", {}, { "audio.mp3": "fake audio\n" });
+ const named = await callPost(POST, { slug: SLUG, id: "ondiskEEEEE", file: "audio.mp3", queueKey: "my-queue" });
+ assert.equal(named.status, 200, JSON.stringify(named.body));
+ assert.equal(job(String(named.body.jobId)).queueKey, "my-queue");
+ await until("the named-queue transcription", () => ended(String(named.body.jobId)));
+});
+
+test("English captions listed and no audio: the captions are fetched instead; asr: true transcribes it anyway", async () => {
+ const captions = { automatic_captions: { en: [{ ext: "vtt", url: "https://example.invalid/en.vtt" }] } };
+ await video("captionFFFF", captions);
+ const res = await callPost(POST, { slug: SLUG, id: "captionFFFF" });
+ assert.equal(res.status, 200, JSON.stringify(res.body));
+ assert.equal(res.body.instead, "captions");
+ assert.equal(
+ res.body.message,
+ "captionFFFF has YouTube captions; fetching those instead — pass asr: true to transcribe it anyway.",
+ );
+ const d = String(res.body.jobId);
+ assert.equal(job(d).kind, "download-one-pipeline");
+ assert.equal(job(d).queueKey, "platform:youtube");
+ await until("the caption download", () => ended(d));
+ assert.equal(job(d).status, "done", await logOf(d));
+ assert.match(await logOf(d), /^captionFFFF has YouTube captions; fetching those instead/);
+ assert.ok(await exists(path.join(dataDir("captionFFFF"), "transcript.en.vtt")), "the captions are on disk");
+ assert.ok(!(await exists(path.join(dataDir("captionFFFF"), "audio.mp3"))), "no audio was fetched");
+
+ // Asked again with the captions on disk: refused, nothing queued.
+ const before = (await corpus.listJobIds()).length;
+ const again = await callPost(POST, { slug: SLUG, id: "captionFFFF" });
+ assert.equal(again.status, 400);
+ assert.match(String(again.body.error), /captionFFFF already has YouTube captions on disk \(transcript\.en\.vtt\); pass asr: true/);
+ assert.equal((await corpus.listJobIds()).length, before);
+
+ // asr: true: the audio, then the transcription.
+ await video("captionGGGG", captions);
+ const asr = await callPost(POST, { slug: SLUG, id: "captionGGGG", asr: true });
+ assert.equal(asr.status, 200, JSON.stringify(asr.body));
+ assert.equal(asr.body.instead, undefined);
+ const w = String(asr.body.jobId);
+ assert.equal(job(w).kind, "whisper-video");
+ await until("the audio download", () => ended(w));
+ assert.equal(job(w).status, "done", await logOf(w));
+ const t = job(w).handedOffTo;
+ assert.ok(t);
+ await until("the transcription", () => ended(t));
+ assert.equal(job(t).status, "done", await logOf(t));
+ assert.ok(await exists(path.join(dataDir("captionGGGG"), "transcript.json")));
+
+ // "asr" is a boolean, checked at the door.
+ const bad = await callPost(POST, { slug: SLUG, id: "captionGGGG", asr: "yes" });
+ assert.equal(bad.status, 400);
+ assert.match(String(bad.body.error), /"asr" must be a boolean/);
+});
diff --git a/editor/app/api/ops/transcribe-one/route.ts b/editor/app/api/ops/transcribe-one/route.ts
@@ -2,22 +2,37 @@ import {
transcribeOneAction,
whisperVideoAction,
} from "../../../channels/[slug]/videos/[id]/videoActions";
+import { NextResponse } from "next/server";
import { jobResponse, ops, opsFail, optBool, optString, reqSlug, reqVideoId } from "../_lib";
import { optStoredUrlMode } from "../_storedUrl";
export const dynamic = "force-dynamic";
-// POST { slug, id, file?, salvage? }
+// POST { slug, id, file?, salvage?, storedUrl?, whilePaused?, queueKey?, asr? }
//
// One video, transcribed — the video page's two buttons:
// - with "file" (an audio file in the video's dir, e.g. "audio.mp3"): that
// file, through the worker pool (transcribeOneAction — the per-file
-// Transcribe on the Files list);
+// Transcribe on the Files list), with the row's own default queue: audio
+// that owes no download runs at once on the video's own queue
+// (`transcribe-one:<slug>:<id>`), one that owes one waits the channel's
+// platform queue;
// - without: the page's Transcribe (whisperVideoAction), which uses the audio
// on disk, or first downloads it through the channel's managed path when
-// there is none (the disk floor applies to that download only).
-// A job on the video's platform queue: { ok, jobId }, so --wait follows it.
+// there is none (the disk floor applies to that download only). Only the
+// download runs on the platform's queue: the transcription is then handed
+// off to a transcribe-one job on the video's own queue, and with nothing
+// to download it is that job at once.
+// { ok, jobId }, so --wait follows it — through the hand-off, to the end of
+// the transcription.
// The file name is one path segment; a refused one is the action's sentence.
+// "queueKey": the queue the job runs on instead (a named queue; "" = the
+// default described above).
+// "asr" (no "file"): a youtube-handling video with no audio whose metadata
+// lists English captions has those fetched instead — the designated
+// pipeline's caption download, answered { ok, jobId, instead: "captions",
+// message } — and one with an English caption track on disk is refused;
+// "asr": true transcribes it anyway.
// "salvage" (release 30, lane Q): true decodes the audio with error tolerance
// and transcribes what decodes, its gaps recorded (transcribeOne's salvage);
// false forbids it; absent, a corrupt-full-source video is salvaged and any
@@ -33,25 +48,37 @@ export const dynamic = "force-dynamic";
// 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", "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`);
- }
- // One path segment, checked at the door as reqVideoId checks an id: the
- // name is joined under the video's directory.
- if (file !== undefined && (file === "" || /[/\\\0]/.test(file) || file.startsWith("."))) {
- return opsFail(`"${file}" is not a file name in the video's directory`);
- }
- return jobResponse(
- file !== undefined
- ? await transcribeOneAction(slug, id, file, undefined, salvage, whilePaused)
- : await whisperVideoAction(slug, id, undefined, salvage, storedUrl, whilePaused),
- );
- });
+ return ops(
+ request,
+ ["slug", "id", "file", "salvage", "storedUrl", "whilePaused", "queueKey", "asr"],
+ 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;
+ const queueKey = optString(body, "queueKey");
+ const asr = optBool(body, "asr") === true;
+ if (storedUrl !== undefined && file !== undefined) {
+ return opsFail(`"storedUrl" is for a download; with "file" nothing is downloaded`);
+ }
+ // One path segment, checked at the door as reqVideoId checks an id: the
+ // name is joined under the video's directory.
+ if (file !== undefined && (file === "" || /[/\\\0]/.test(file) || file.startsWith("."))) {
+ return opsFail(`"${file}" is not a file name in the video's directory`);
+ }
+ if (file !== undefined) {
+ // The row's "now": the action picks the video's own queue or the
+ // platform's (transcribeOneQueueKey).
+ return jobResponse(await transcribeOneAction(slug, id, file, queueKey ?? "", salvage, whilePaused));
+ }
+ const r = await whisperVideoAction(slug, id, queueKey, salvage, storedUrl, whilePaused, asr);
+ if (r.ok && "instead" in r) {
+ void r.stream.cancel();
+ return NextResponse.json({ ok: true, jobId: r.jobId, instead: r.instead, message: r.message });
+ }
+ return jobResponse(r);
+ },
+ );
}
diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/RedownloadSection.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/RedownloadSection.tsx
@@ -73,7 +73,9 @@ export function RedownloadSection({
: "Running pipeline…";
const actionLabel = `${verb} for ${videoId}`;
const trigger = mode === "whisper"
- ? () => whisperVideoAction(slug, videoId, queueKey, undefined, stored)
+ ? // The mode IS the ask for speech recognition (asr: true): a video whose
+ // captions are listed is transcribed anyway, as chosen.
+ () => whisperVideoAction(slug, videoId, queueKey, undefined, stored, undefined, true)
: () =>
downloadVideoPipelineAction(
slug,
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -22,11 +22,16 @@ import { diskGate } from "yt-dlp-transcript-common/lib/diskSpace";
import { formatBytes } from "yt-dlp-transcript-common/lib/format";
import {
audioFilesToRemove,
+ englishVttsByPreference,
isRealAudioFile,
isTranscriptVtt,
VTT_FILENAME,
} from "yt-dlp-transcript-common/lib/videoStatus";
import {
+ isEnglishCaptionTrack,
+ readListedCaptionTracks,
+} from "yt-dlp-transcript-common/lib/listedCaptions-server";
+import {
clipWindowQueueKey,
downloadQueueKey,
resolveQueueKey,
@@ -139,6 +144,7 @@ import {
} from "yt-dlp-transcript-common/jobs/streamCommand";
import { requestChannelSnapshot } from "yt-dlp-transcript-common/jobs/snapshotScheduler";
import { makeTaskTracker } from "yt-dlp-transcript-common/jobs/taskHooks";
+import { handOffSlot } from "yt-dlp-transcript-common/jobs/handOff";
import { fixIncompleteTranscriptOne } from "../../lib/fixIncompleteTranscript";
import { writeFileAtomic, writeJsonAtomic } from "yt-dlp-transcript-common/lib/jsonFile-server";
import { formValues, type FormErrorState } from "../../../../lib/formState";
@@ -168,7 +174,7 @@ async function transcribeOneQueueKey(
...(config.storedUrlDownloads ? { mode: config.storedUrlDownloads } : {}),
})
: null;
- return owed && !owed.exhausted ? downloadQueueKey(config) : `transcribe-one:${slug}:${videoId}`;
+ return owed && !owed.exhausted ? downloadQueueKey(config) : ownTranscribeQueue(slug, videoId);
}
function videoDirOf(slug: string, videoId: string): string {
@@ -245,30 +251,67 @@ export async function transcribeOneAction(
): Promise<StreamActionResult> {
const r = await loadConfigOrError(slug);
if (!r.ok) return r;
+ return queueTranscribeOne({
+ slug,
+ videoId,
+ config: r.config,
+ audioFilename,
+ queueKey: await transcribeOneQueueKey(slug, videoId, r.config, queueKey, salvage),
+ fullAudioFirst: salvage === undefined,
+ ...(salvage !== undefined ? { salvage } : {}),
+ ...(whilePaused ? { whilePaused: true } : {}),
+ });
+}
+
+// The video's own transcription queue: one transcription of a video at a time,
+// beside every other video's, never behind a platform's downloads.
+function ownTranscribeQueue(slug: string, videoId: string): string {
+ return `transcribe-one:${slug}:${videoId}`;
+}
+
+// ONE TRANSCRIPTION AS A transcribe-one JOB on `queueKey` (resolved by the
+// caller): transcribeOneAction's, and whisper-video's once nothing it does
+// asks the network any more (whisperVideoAction). `fullAudioFirst` makes the
+// stored-URL downloads a salvage still owes first (fullAudioBeforeSalvage) —
+// false when the caller made them or nothing is owed. `prelude`: lines the
+// job's log opens with (what the whisper-video found on disk).
+async function queueTranscribeOne(o: {
+ slug: string;
+ videoId: string;
+ config: ChannelConfig;
+ audioFilename: string;
+ queueKey: string;
+ fullAudioFirst: boolean;
+ salvage?: boolean;
+ whilePaused?: boolean;
+ prelude?: string[];
+}): Promise<StreamActionResult> {
+ const { slug, videoId, salvage, whilePaused } = o;
const paths = getPaths();
const videoDir = videoDirOf(slug, videoId);
return runManagedFunction({
kind: "transcribe-one",
- queueKey: await transcribeOneQueueKey(slug, videoId, r.config, queueKey, salvage),
+ queueKey: o.queueKey,
paths,
channelSlug: slug,
videoId,
fn: async (onLog, signal, _setProgress, ctx) => {
- if (salvage === undefined) {
- await fullAudioBeforeSalvage({ slug, videoId, config: r.config, paths, onLog, signal });
+ for (const line of o.prelude ?? []) onLog(line);
+ if (o.fullAudioFirst) {
+ await fullAudioBeforeSalvage({ slug, videoId, config: o.config, paths, onLog, signal });
}
await transcribeWithWorker({
paths,
videoDir,
videoId,
- audioFilename,
+ audioFilename: o.audioFilename,
tracker: makeTaskTracker(ctx, onLog),
onLog,
signal,
...(salvage !== undefined ? { salvage } : {}),
...(whilePaused ? { whilePaused: true } : {}),
});
- safeRevalidate([`/channels/${slug}/videos/${videoId}`]);
+ safeRevalidate([`/channels/${slug}/videos/${videoId}`, `/channels/${slug}`]);
},
});
}
@@ -285,6 +328,31 @@ export async function downloadVideoPipelineAction(
): Promise<StreamActionResult> {
const r = await loadConfigOrError(slug);
if (!r.ok) return r;
+ return queuePipelineDownload({
+ slug,
+ videoId,
+ config: r.config,
+ ...(queueKey !== undefined ? { queueKey } : {}),
+ ...(downloadFormat !== undefined ? { downloadFormat } : {}),
+ ...(storedUrl !== undefined ? { storedUrl } : {}),
+ });
+}
+
+// The designated pipeline for one video as a download-one-pipeline job
+// (downloadVideoPipelineAction's): on a youtube-handling channel the caption
+// download, with audio + whisper only when none is listed. `prelude`: lines
+// its log opens with (why a Transcribe was turned into it).
+async function queuePipelineDownload(o: {
+ slug: string;
+ videoId: string;
+ config: ChannelConfig;
+ queueKey?: string;
+ downloadFormat?: string;
+ storedUrl?: string;
+ prelude?: string[];
+}): Promise<StreamActionResult> {
+ const { slug, videoId, queueKey, downloadFormat, storedUrl } = o;
+ const r = { config: o.config };
const paths = getPaths();
// This action fetches a full container. Its sibling redownloadToArchiveAction
// has always preflighted the disk; this one never did.
@@ -310,6 +378,7 @@ export async function downloadVideoPipelineAction(
channelSlug: slug,
videoId,
fn: async (onLog, signal, _setProgress, ctx) => {
+ for (const line of o.prelude ?? []) onLog(line);
const task = makeTaskTracker(ctx, onLog).start({
id: videoId,
label: videoId,
@@ -531,6 +600,10 @@ async function archiveSourceVideo(
// skip it. Without this a youtube-handling video with a transcript
// got two subtitle passes and no file (release 10 slice N).
forceMedia: true,
+ // A person's click (or the tool's request for a whole recording):
+ // over a copy already saved, the download becomes the active one
+ // and the other is kept beside it (ytdlp/savedAlternates.ts).
+ explicitPersist: true,
persistOrigin,
persistFormatPreset,
});
@@ -578,6 +651,47 @@ async function lowDiskError(
};
}
+// What whisperVideoAction answers: the job it started — and, when a
+// Transcribe of a youtube-handling video with English captions listed and no
+// audio was turned into the caption download, `instead: "captions"` with the
+// sentence that says so (the started job is then that download).
+export type WhisperVideoResult =
+ | StreamActionResult
+ | (Extract<StreamActionResult, { ok: true }> & { instead: "captions"; message: string });
+
+// A queue the caller NAMED for the transcription, else null: no override, the
+// immediate "", and the platform's own queue (the page's default) all mean
+// "wherever it belongs" — the video's own transcription queue.
+function namedTranscribeQueue(config: ChannelConfig, override: string | undefined): string | null {
+ const q = override?.trim();
+ if (!q || q === downloadQueueKey(config)) return null;
+ return q;
+}
+
+// THE PAGE'S TRANSCRIBE ("Audio + Whisper"), and `pnpm ops transcribe-one`
+// with no "file": the audio on disk, else downloaded first.
+//
+// ONLY WHAT ASKS THE NETWORK RUNS ON THE PLATFORM'S QUEUE. The audio download
+// (plain or through the stored media URL) and the full-audio attempts a
+// salvage still owes run as a whisper-video job on `videoQueueKey`; the
+// transcription is then HANDED OFF — queued as a transcribe-one job on the
+// video's own queue (`transcribe-one:<slug>:<id>`), its id recorded as the
+// job's `handedOffTo` — and the whisper-video ends, so the platform's queue is
+// free the moment the bytes are down. It used to hold it for the whole
+// transcription: 20–40 minutes of waiting for the one GPU worker and
+// transcribing, during which no other download on that platform ran.
+// When nothing is owed at all (audio on disk with no full-audio attempt owed,
+// or a container to transcribe from) no whisper-video is queued: the
+// transcription job is the answer, at once.
+//
+// The returned stream is the whisper-video's log and then the transcription's
+// (jobs/handOff.ts), and `done` settles when the transcription does.
+//
+// CAPTIONS FIRST: a youtube-handling video with no audio on disk whose
+// metadata lists English captions (lib/listedCaptions-server.ts) has those
+// fetched instead — the designated pipeline's caption download — and one
+// with an English caption track already on disk is refused, unless `asr` is
+// true.
export async function whisperVideoAction(
slug: string,
videoId: string,
@@ -592,19 +706,91 @@ export async function whisperVideoAction(
storedUrl?: StoredUrlMode,
// See transcribeOneAction's `whilePaused`.
whilePaused?: boolean,
-): Promise<StreamActionResult> {
+ // true: speech recognition even for a youtube-handling video that lists
+ // English captions (the page's "Audio + Whisper" is that ask).
+ asr?: boolean,
+): Promise<WhisperVideoResult> {
const r = await loadConfigOrError(slug);
if (!r.ok) return r;
const paths = getPaths();
const videoDir = videoDirOf(slug, videoId);
- return runManagedFunction({
+ const audioFormat = r.config.audioFormat ?? "mp3";
+ const audioFilename = `audio.${audioFormat}`;
+ const transcribeQueue = namedTranscribeQueue(r.config, queueKey) ?? ownTranscribeQueue(slug, videoId);
+ const opts = {
+ ...(salvage !== undefined ? { salvage } : {}),
+ ...(whilePaused ? { whilePaused: true } : {}),
+ };
+ const firstEntries = await readdir(videoDir).catch(() => [] as string[]);
+ const audioOnDisk = firstEntries.some(isRealAudioFile);
+
+ if (!audioOnDisk && asr !== true && r.config.handling === "youtube") {
+ const onDisk = englishVttsByPreference(firstEntries);
+ if (onDisk.length > 0) {
+ return {
+ ok: false,
+ error: `${videoId} already has YouTube captions on disk (${onDisk[0]}); pass asr: true to transcribe it anyway.`,
+ };
+ }
+ const listed = (await readListedCaptionTracks(videoDir)) ?? [];
+ if (listed.some(isEnglishCaptionTrack)) {
+ const message = `${videoId} has YouTube captions; fetching those instead — pass asr: true to transcribe it anyway.`;
+ const dl = await queuePipelineDownload({
+ slug,
+ videoId,
+ config: r.config,
+ ...(queueKey !== undefined ? { queueKey } : {}),
+ ...(storedUrl !== undefined ? { storedUrl } : {}),
+ prelude: [message],
+ });
+ return dl.ok ? { ...dl, instead: "captions", message } : dl;
+ }
+ }
+
+ // NOTHING OWED TO THE NETWORK: the transcription itself.
+ if (audioOnDisk) {
+ const mode = storedUrl ?? r.config.storedUrlDownloads;
+ const owed =
+ salvage === undefined
+ ? await fullAudioGate(videoDir, { handling: r.config.handling, ...(mode ? { mode } : {}) })
+ : null;
+ if (!owed || owed.exhausted) {
+ return queueTranscribeOne({
+ slug,
+ videoId,
+ config: r.config,
+ audioFilename,
+ queueKey: transcribeQueue,
+ fullAudioFirst: false,
+ ...opts,
+ prelude: [`Audio already on disk for ${videoId}; skipping download.`],
+ });
+ }
+ } else {
+ const held = await transcriptionContainer({ paths, slug, videoDir, entries: firstEntries });
+ if (held?.kind === "container") {
+ return queueTranscribeOne({
+ slug,
+ videoId,
+ config: r.config,
+ audioFilename,
+ queueKey: transcribeQueue,
+ fullAudioFirst: false,
+ ...opts,
+ prelude: [containerLine(videoId, held)],
+ });
+ }
+ }
+
+ const platformQueue = videoQueueKey(r.config, queueKey);
+ const slot = handOffSlot();
+ const res = await runManagedFunction({
kind: "whisper-video",
- queueKey: videoQueueKey(r.config, queueKey),
+ queueKey: platformQueue,
paths,
channelSlug: slug,
videoId,
fn: async (onLog, signal, _setProgress, ctx) => {
- const audioFormat = r.config.audioFormat ?? "mp3";
const entries = await readdir(videoDir).catch(() => [] as string[]);
const hasAudio = entries.some(isRealAudioFile);
// NO AUDIO, BUT A CONTAINER (release 23 F2): a source-media.<ext> here or
@@ -612,17 +798,14 @@ export async function whisperVideoAction(
// resolves it (resolveAudioFile) — and nothing is downloaded. A pointer
// whose container cannot be read is refused with the media guard's
// sentence, never downloaded around; a container with no sound takes the
- // download path below.
+ // download path below. (One found before the job was queued never gets
+ // here: its transcription was queued at once, above.)
const held = hasAudio
? null
: await transcriptionContainer({ paths, slug, videoDir, entries });
if (held?.kind === "unreadable") throw new Error(held.error);
if (held?.kind === "container") {
- onLog(
- `No audio on disk for ${videoId}; transcribing from ` +
- `${held.from === "saved-video" ? "the saved container" : "the source container"} ` +
- `${held.file} — nothing downloaded.`,
- );
+ onLog(containerLine(videoId, held));
} else if (!hasAudio) {
if (held?.kind === "no-audio") {
onLog(`The container ${held.file} has no sound; downloading the audio instead.`);
@@ -693,23 +876,42 @@ export async function whisperVideoAction(
await fullAudioBeforeSalvage({ slug, videoId, config: r.config, paths, onLog, signal, storedUrl });
}
}
- await transcribeWithWorker({
- paths,
- videoDir,
+ if (signal.aborted) return;
+ // THE HAND-OFF: everything after this line asks no platform anything.
+ const child = await queueTranscribeOne({
+ slug,
videoId,
- audioFilename: `audio.${audioFormat}`,
- tracker: makeTaskTracker(ctx, onLog),
- onLog,
- signal,
- ...(salvage !== undefined ? { salvage } : {}),
- ...(whilePaused ? { whilePaused: true } : {}),
+ config: r.config,
+ audioFilename,
+ queueKey: transcribeQueue,
+ fullAudioFirst: false,
+ ...opts,
});
+ if (!child.ok) {
+ throw new Error(`The audio is on disk, but its transcription was not queued: ${child.error}`);
+ }
+ ctx.handOff(child.jobId);
+ onLog(
+ `Transcription handed off to transcribe-one job ${child.jobId} (queue ${transcribeQueue}); ` +
+ `${platformQueue} is free for the next download.`,
+ );
+ slot.set(child);
safeRevalidate([
`/channels/${slug}/videos/${videoId}`,
`/channels/${slug}`,
]);
},
});
+ return res.ok ? slot.wrap(res) : res;
+}
+
+// The release 23 F2 sentence: what a container-only video is transcribed from.
+function containerLine(videoId: string, held: { from: string; file: string }): string {
+ return (
+ `No audio on disk for ${videoId}; transcribing from ` +
+ `${held.from === "saved-video" ? "the saved container" : "the source container"} ` +
+ `${held.file} — nothing downloaded.`
+ );
}
// Fix a truncated transcript: the audio download silently stopped early, so the
diff --git a/editor/app/jobs/actions.ts b/editor/app/jobs/actions.ts
@@ -15,6 +15,7 @@ import {
} from "yt-dlp-transcript-common/controller/autoRunner";
import { pruneJobLogs } from "yt-dlp-transcript-common/jobs/listJobs";
import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import { jobDoingTheWork } from "yt-dlp-transcript-common/jobs/handOff";
import { readJobMeta } from "yt-dlp-transcript-common/jobs/jobMeta";
import type { JobSpec } from "yt-dlp-transcript-common/jobs/jobSpec";
import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
@@ -22,7 +23,10 @@ import { runJobSpec } from "./runJobSpec";
import { stuckJobIds } from "./active/buildActiveJobs";
export async function cancelJobAction(id: string): Promise<{ ok: boolean }> {
- const ok = getRegistry().cancel(id);
+ // A run panel's Cancel names the job it started. One that ended handing its
+ // work on (a whisper-video, once its audio is down: JobRecord.handedOffTo)
+ // cancels the job doing that work now — the panel is still showing it.
+ const ok = getRegistry().cancel(jobDoingTheWork(id));
revalidatePath("/jobs");
return { ok };
}
diff --git a/editor/app/saved-videos/page.tsx b/editor/app/saved-videos/page.tsx
@@ -4,6 +4,10 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
import { formatBytes } from "yt-dlp-transcript-common/lib/format";
import { listSavedVideos } from "yt-dlp-transcript-common/controller/savedVideoInventory";
+import {
+ savedAlternatesLine,
+ savedVideoBytes,
+} from "yt-dlp-transcript-common/lib/savedVideo";
import { readSchedulerState } from "yt-dlp-transcript-common/jobs/syncSchedulerState";
import { SavedVideosControls } from "./components/SavedVideosControls";
import { PersistVideoListControl } from "./components/PersistVideoListControl";
@@ -38,14 +42,17 @@ export default async function SavedVideosPage() {
byChannel.get(e.slug) ??
{ slug: e.slug, count: 0, bytes: 0, verified: 0 };
row.count += 1;
- row.bytes += e.pointer.bytes;
+ row.bytes += savedVideoBytes(e.pointer);
if (e.pointer.sha256) {
row.verified += 1;
totalVerified += 1;
}
byChannel.set(e.slug, row);
- totalBytes += e.pointer.bytes;
+ totalBytes += savedVideoBytes(e.pointer);
}
+ // Two copies of one video, both kept (ytdlp/savedAlternates.ts): flagged
+ // for a check. Off the same pointer walk, so free.
+ const withAlternates = entries.filter((e) => (e.pointer.alternates?.length ?? 0) > 0);
const channels = [...byChannel.values()].sort((a, b) =>
a.slug.localeCompare(b.slug),
);
@@ -158,6 +165,30 @@ export default async function SavedVideosPage() {
)}
</section>
+ {withAlternates.length > 0 && (
+ <section aria-label="saved videos with two copies" className="flex flex-col gap-2">
+ <h2 className="text-base font-semibold">
+ Two saved copies ({withAlternates.length})
+ </h2>
+ <ul className="flex flex-col gap-1 text-sm">
+ {withAlternates.map((e) => (
+ <li key={`${e.slug}/${e.videoId}`} aria-label={`two copies ${e.slug}/${e.videoId}`}>
+ <Link
+ href={`/channels/${e.slug}/videos/${encodeURIComponent(e.videoId)}`}
+ className="underline hover:no-underline"
+ >
+ {e.slug}/{e.videoId}
+ </Link>
+ <span className="text-muted-foreground">
+ {" "}
+ — {savedAlternatesLine(e.pointer)}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </section>
+ )}
+
<section aria-label="backups" className="flex flex-col gap-2">
<h2 className="text-base font-semibold">Backups</h2>
<SavedVideosControls
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -244,6 +244,10 @@ const GETTERS = {
key ? `/api/ops/settings?key=${encodeURIComponent(key)}` : "/api/ops/settings",
// The /storage page: each location, mounted or not, its free space and tiers.
storage: () => "/api/ops/storage",
+ // Saved videos holding two copies (a download over a container already in
+ // the store keeps both): each one's active copy and its flagged alternates.
+ "saved-alternates": (slug) =>
+ slug ? `/api/ops/saved-alternates?slug=${encodeURIComponent(slug)}` : "/api/ops/saved-alternates",
// Every site: id, title, siteUrl, Pages project, audience, policy, channels.
sites: () => "/api/ops/sites",
// The transcription workers and what each is running.
@@ -298,6 +302,7 @@ const GET_ARG_OPTIONAL = new Set([
"jobs",
"settings",
"storage",
+ "saved-alternates",
"sites",
"workers",
"auto-queue",
@@ -930,6 +935,7 @@ export function usage() {
" pnpm ops job wait <id>... [--wait-timeout <seconds>]",
" pnpm ops get settings [<key>]",
" pnpm ops get storage | sites | workers | auto-queue | scheduler",
+ " pnpm ops get saved-alternates [<slug>]",
" pnpm ops get services",
" pnpm ops get cleanup <slug>",
" pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]",
@@ -966,6 +972,13 @@ export function usage() {
"get settings [<key>] is settings.json as the editor reads it (migrated and",
" defaulted; a secret is \"<redacted>\"), or one top-level key of it.",
"get storage is /storage: each location, mounted or not, free space, tiers.",
+ "get saved-alternates [<slug>] lists every saved video holding two copies:",
+ " a download over a container already in the store keeps both — an",
+ " explicit persist (persist-videos, Persist source video, a whole-recording",
+ " fetch) makes the download active, any other keeps the saved one unless",
+ " the download is longer — and the other stays beside it as",
+ " source-media.alt-<h>p-<stamp>.<ext>, flagged for a check. Each video:",
+ " its line, the active copy, the alternates (height, seconds, origin).",
"get sites lists every site: id, title, siteUrl, Pages project, audience,",
" listed, search, publish policy, channels, citedChannels. (`get publish`",
" is the status.)",
@@ -1075,7 +1088,16 @@ export function usage() {
'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',
+ ' managed path. Only a download waits on the platform\'s queue: the',
+ ' transcription runs as a transcribe-one job on the video\'s own queue',
+ ' (transcribe-one:<slug>:<id>), at once when nothing is downloaded, else',
+ ' handed off by the whisper-video once the audio is down. A job; --wait',
+ ' follows it through the hand-off to the end of the transcription.',
+ ' "queueKey" names another queue. A youtube-handling video with no audio',
+ ' whose metadata lists English captions has those fetched instead',
+ ' ({"instead": "captions", "message"}, the job the caption download), one',
+ ' with an English caption track on disk is refused; "asr": true',
+ ' transcribes it anyway (no "file"). "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',
@@ -1373,7 +1395,10 @@ export function usage() {
' "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.",
+ " again resumes — saved videos are skipped. Over a copy already in the",
+ " store (an import, an attach, a live recording or an earlier download) the",
+ " download becomes the active one and the old copy is kept beside it,",
+ " flagged for a check (`get saved-alternates`); nothing is deleted.",
"",
'import-archive-org imports archive.org media into a channel, as one job on',
' archive.org\'s queue: {"slug", "item", "files": [...] | "match": "<regex>"}',
@@ -2125,7 +2150,28 @@ export function tokenHint(status, sources, url = baseUrl()) {
// `--wait-timeout` bounds the whole thing for a caller that cannot hang (CI,
// an agent). Default none, because the honest default for a queue that may hold
// a job behind hours of other work is to wait.
+//
+// A JOB THAT HANDED ITS WORK ON is followed to where the work went: a
+// whisper-video (`transcribe-one` with no "file") downloads the audio on the
+// platform's queue and queues the transcription as a job of its own, and its
+// log route and job route then name that job (`handedOffTo`). Ending `done`
+// there is not the transcript being written, so the follow goes on in the
+// next job ("[j1] handed off to job j2") and ends with how that one ended.
export async function followJob(jobId, quiet, opts = {}) {
+ let handedOffTo = null;
+ const status = await followOne(jobId, quiet, opts, (next) => {
+ handedOffTo = next;
+ });
+ const hops = opts.hops ?? 0;
+ if (status === "done" && handedOffTo && handedOffTo !== jobId && hops < 5) {
+ const say = opts.say ?? ((line) => process.stderr.write(`${line}\n`));
+ if (!quiet) say(`[${jobId}] handed off to job ${handedOffTo}`);
+ return followJob(handedOffTo, quiet, { ...opts, hops: hops + 1 });
+ }
+ return status;
+}
+
+async function followOne(jobId, quiet, opts, noteHandOff) {
const doFetch = opts.fetch ?? fetch;
const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
const now = opts.now ?? (() => Date.now());
@@ -2167,6 +2213,7 @@ export async function followJob(jobId, quiet, opts = {}) {
// Only advance once the chunk is in hand: a poll that failed halfway
// must re-ask for the same offset.
from = payload.nextOffset ?? from;
+ if (typeof payload.handedOffTo === "string") noteHandOff(payload.handedOffTo);
notePlace(payload.status, payload.queueKey, payload.queuePosition);
return payload.status ?? null;
} catch {
@@ -2184,6 +2231,7 @@ export async function followJob(jobId, quiet, opts = {}) {
if (!payload || typeof payload !== "object") return null;
if (res.status === 404 && payload.ok === false) return "gone";
if (!res.ok || !payload.job) return null;
+ if (typeof payload.job.handedOffTo === "string") noteHandOff(payload.job.handedOffTo);
return payload.job.status ?? null;
} catch {
return null;
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -288,6 +288,35 @@ test("'archived' is not an outcome: the sidecar's status is", async () => {
assert.equal(await follow("j1", unknown), "archived");
});
+test("a job that handed its work on is followed to the job it named", async () => {
+ // whisper-video downloads on the platform queue and hands the transcription
+ // to a transcribe-one job: `done` on the first is not the transcript.
+ const logs = {
+ j1: [{ content: "downloaded\n", nextOffset: 11, status: "done", handedOffTo: "j2" }],
+ j2: [
+ { content: "", nextOffset: 0, status: "running" },
+ { content: "transcribed\n", nextOffset: 12, status: "failed" },
+ ],
+ };
+ const seen = { j1: 0, j2: 0 };
+ const lines = [];
+ const doFetch = async (url) => {
+ const id = /\/api\/jobs\/([^/]+)\/log/.exec(url)?.[1];
+ const seq = logs[id];
+ const body = seq[Math.min(seen[id]++, seq.length - 1)];
+ return { ok: true, status: 200, json: async () => body };
+ };
+ const status = await followJob("j1", false, {
+ fetch: doFetch,
+ sleep: async () => {},
+ baseUrl: "http://editor",
+ say: (l) => lines.push(l),
+ });
+ assert.equal(status, "failed", "the follow ends with how the handed-off job ended");
+ assert.ok(seen.j2 >= 2);
+ assert.deepEqual(lines, ["[j1] handed off to job j2"]);
+});
+
test("a waiting job's queue position is said once per change", async () => {
const lines = [];
const editor = fakeEditor({