Archilyzer · Source

archilyzer

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

commit 5f567a33ba5bf6d4732def0b697a1ea9c7ef0f0b
parent 8b91abae71cbbc10aeb38ef38e40cd6439656c5c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 23:53:48 -0400

Merge r32/owed-ui: "Cut from the stored media URL" on every fetch surface (editor, umtool, the single route, MCP fetch_clip), the Inbox wraps at phone width, and buttons for channel-wide media attach and playable copies and bulk persist

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

Diffstat:
Mcommon/lib/storedMediaUrl.ts | 16++++++++++++++++
Meditor/CHANGELOG.md | 4++++
Aeditor/app/api/media/fetch-window/route.storedUrl.test.ts | 154+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/media/fetch-window/route.ts | 18++++++++++++++++++
Aeditor/app/channels/[slug]/components/ChannelMediaTools.tsx | 213+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/components/stages/CleanupStage.tsx | 2++
Aeditor/app/channels/[slug]/lib/mediaToolsWords.test.ts | 39+++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/lib/mediaToolsWords.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/videos/[id]/videoActions.ts | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Meditor/app/jobs/jobReplayRegistry.ts | 1+
Aeditor/app/saved-videos/components/PersistVideoListControl.tsx | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/saved-videos/lib/videoList.test.ts | 35+++++++++++++++++++++++++++++++++++
Aeditor/app/saved-videos/lib/videoList.ts | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/saved-videos/page.tsx | 3+++
Aeditor/app/saved-videos/persistListAction.ts | 43+++++++++++++++++++++++++++++++++++++++++++
Meditor/app/sites/components/FetchMissingEvidenceButton.tsx | 57++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Aeditor/e2e/owed-ui.spec.ts | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmcp/src/fetchClip.test.ts | 20++++++++++++++++++++
Mmcp/src/fetchClip.tool.test.ts | 2+-
Mmcp/src/fetchClip.ts | 21++++++++++++++++++++-
Mmcp/src/server.ts | 11+++++++++++
Mplans/FACTS.md | 31+++++++++++++++++++++++++++++++
Aplans/release-32/owed-ui.md | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/cited/fetch/route.ts | 8++++++--
Aumtool/app/api/cited/stored/route.ts | 19+++++++++++++++++++
Mumtool/app/api/report/fetch/route.ts | 18+++++++++++++++++-
Mumtool/app/api/research/fetch/route.ts | 4+++-
Mumtool/components/clips/CitedClip.tsx | 21+++++++++++++++++++--
Aumtool/components/clips/StoredUrlOption.tsx | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/inbox/InboxList.tsx | 18+++++++++++-------
Mumtool/components/projects/ClaimBench.tsx | 18++++++++++++++++--
Mumtool/components/projects/ClipBench.tsx | 15++++++++++++++-
Mumtool/components/projects/FetchUnfetchedButton.tsx | 19+++++++++++++++++++
Mumtool/components/projects/report/CutTab.tsx | 12++++++++++++
Mumtool/components/research/Reader.tsx | 15+++++++++++++++
Mumtool/components/research/ResearchView.tsx | 7++++++-
Mumtool/e2e/fixtures/make-fixture.mjs | 43+++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/stored-url.spec.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/clips/cited.test.ts | 10++++++++++
Mumtool/lib/clips/cited.ts | 6+++++-
Aumtool/lib/clips/stored.test.ts | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/clips/stored.ts | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/driver.mjs | 8+++++++-
Mumtool/lib/research/fetch.ts | 12++++++++++--
Mumtool/report-to-video/fetch-via-editor.mjs | 18+++++++++++++++++-
Mumtool/report-to-video/fetch-via-editor.test.mjs | 17+++++++++++++++++
46 files changed, 1771 insertions(+), 50 deletions(-)

diff --git a/common/lib/storedMediaUrl.ts b/common/lib/storedMediaUrl.ts @@ -37,6 +37,22 @@ export function isStoredUrlPlatform(v: unknown): v is StoredUrlPlatform { return (STORED_URL_PLATFORMS as readonly unknown[]).includes(v); } +// THE UI'S WORDS (release 32 R6): every surface that offers the stored URL — the +// editor's Fetch missing evidence, umtool's Fetch clip and the benches — says it +// with this label and this help, and asks with STORED_URL_UI_MODE. A person's +// tick asks "fallback": the page first, as always, and the stored file only when +// the platform refuses the lookup (or is held or cooling down) — so ticking it +// for a platform that is answering changes nothing. `only` stays for the CLI and +// the MCP, which can say why they skip the page. +export const STORED_URL_LABEL = "Cut from the stored media URL"; +export const STORED_URL_UI_MODE: StoredUrlMode = "fallback"; +const PLATFORM_NAMES: Readonly<Record<StoredUrlPlatform, string>> = { odysee: "Odysee" }; +export const STORED_URL_HELP = + `${STORED_URL_PLATFORMS.map((p) => PLATFORM_NAMES[p]).join(", ")} only. When the platform refuses ` + + "the page lookup (a rate limit, or it is on hold), the seconds are cut straight from the video file " + + "address the archive saved with the record, the way the platform's own player reads it. " + + "Off: the page is asked as usual, and a refusal stops the fetch."; + // Per platform: which hosts are its CDN, and the Referer its player sends (the // stored format's own `http_headers.Referer`, pinned here rather than read from // the file). diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,10 @@ # Changelog ## [Unreleased] +- **"Cut from the stored media URL" wherever a clip window is fetched.** When Odysee refuses its page lookup, a window can be cut from the video file address the record already stores. The option sits beside the editor's **Fetch missing evidence** (Reports and Articles tabs — offered once a preview finds Odysee windows with a stored address, and the preview says how many) and umtool's **Fetch clip** (articles, the drafts deck, the research reader), the clip and claim benches and **Fetch N unfetched clips** — only where the record stores one, off by default. Ticked, the page is asked first as always, and the stored file is used only when Odysee refuses. `POST /api/media/fetch-window` and the MCP's `fetch_clip` take `storedUrl` (`"fallback"` or `"only"`). +- **The Inbox reads on a phone.** At narrow widths each row wraps: the piece, what and why on top, the count and its action underneath. Before, at about 380 px the rows showed only the count and the button. +- **Attach a whole local archive and make playable copies from the channel page.** The Cleanup stage's **Media for the whole channel** has **Attach media from a local archive** (a folder, a .zip or a .7z; only names matching, create records for videos the channel does not hold, replace files already saved) and **Playable copies** (trackers, folder) — what `archilyzer media attach` and `media playable` did for a channel. Each previews first, the run is armed by a preview of the same settings, and the result is said in plain words with the job linked. +- **Save a list of videos to the store from the Saved videos page.** **Save these videos** takes one video per line (`channel/video-id` or a video page link), the quality and whether to replace a taller one; **Preview** says what a run would do with each (to download, already saved, no source address, not found) and **Save videos** starts one job per channel and links each — `pnpm ops persist-videos` in the UI. - **A clip window can be cut from the media URL an Odysee record already stores, when Odysee's lookup is rate-limited.** `pnpm ops fetch-windows` takes `"storedUrl"`: `"fallback"` tries the page as before and, when the lookup answers 429, cuts the window from the file the record's `metadata.info.json` names on Odysee's CDN (`*.odycdn.com`) instead; `"only"` goes straight to that file and asks the page nothing. A held or cooling Odysee no longer refuses those windows — only the ones with no stored file are refused or left for a later run. Same queue, same gaps between fetches, the audio check still applies, and the window's provenance says `source: "stored-media-url"` with the host. The default, `"never"`, changes nothing; only Odysee is allowed. Needs a restart of the editor. - **umtool's drafts review is an audition deck: hear the cited moment, then keep it or cut it.** `/projects/<project>/review` shows one card per drafted field still waiting for a verdict: the drafted value large, the cited span of its clip playing (video when a window or saved video holds it, else audio marked "audio only"), and the quote under it lighting word by word as it is spoken. Swipe right, → or `k` keeps it (approves); left, ← or `x` cuts it (rejects — tap a reason chip or write a few words, never required); up, ↑ or `e` edits it on the card (on-screen text, narration, teaser lines and the YouTube title; Enter keeps it as edited); down, ↓ or `s` skips it to the back; space replays the span; `z` undoes the last keep, cut or skip. Tap a word to mark it misheard: the note says so. Every action is also a button (a bar under the thumb on a phone). The next card's media is already loading, and the deck ends with what was cut and skipped. Verdicts are the same `drafts.review.json` as before; **List** (`?view=list`) is the old list, whose reader now plays the span too. No model is needed for any of it. - **Fetch clip wherever a citation is shown in umtool.** When nothing on disk holds a cited span — on the deck, in the list's reader, on an article's evidence panel and its evidence walk — **Fetch clip** asks the editor for those seconds exactly as the MCP's `fetch_clip` does, shows its progress, and plays the window when it lands. A rate limit says the platform is rate-limiting; a window the audio check refused says the source served corrupt audio. The evidence panel plays video first and has **Play span** (from the span's start to its end). diff --git a/editor/app/api/media/fetch-window/route.storedUrl.test.ts b/editor/app/api/media/fetch-window/route.storedUrl.test.ts @@ -0,0 +1,154 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/media/fetch-window/route.storedUrl.test.ts" +// +// `storedUrl` on the single-window route (release 32 R6) — the fetch-windows +// batch's rule for one window. yt-dlp and ffmpeg are fakes (YTDLP_BIN, +// FFMPEG_BIN): an odysee.com page answers 429, a cut from an http input is +// written. In order: a fallback with the platform answering (the page 429s, the +// window is cut from the stored URL — and the 429 leaves Odysee cooling), then +// the cooling platform: never refuses, fallback without a stored URL refuses, +// only and fallback with one cut it without asking the page. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetch-window-stored-")); +const SLUG = "demo-odysee"; +const ARGS_LOG = path.join(ROOT, "argv.jsonl"); +const YTDLP = path.join(ROOT, "fake-ytdlp.mjs"); +const FFMPEG = path.join(ROOT, "fake-ffmpeg.mjs"); +await writeFile( + YTDLP, + `#!/usr/bin/env node +import { appendFileSync, writeFileSync } from "node:fs"; +const args = process.argv.slice(2); +appendFileSync(${JSON.stringify(ARGS_LOG)}, JSON.stringify(args) + "\\n"); +const url = args[args.length - 1]; +if (url.startsWith("https://odysee.com/")) { process.stderr.write("ERROR: [lbry] x: Unable to download webpage: HTTP Error 429: Too Many Requests\\n"); process.exit(1); } +writeFileSync(args[args.indexOf("-o") + 1], "mp4"); +`, +); +await writeFile( + FFMPEG, + `#!/usr/bin/env node +import { appendFileSync, writeFileSync } from "node:fs"; +const args = process.argv.slice(2); +const input = args[args.indexOf("-i") + 1] ?? ""; +if (input.startsWith("http")) { + appendFileSync(${JSON.stringify(ARGS_LOG)}, JSON.stringify([...args, input]) + "\\n"); + writeFileSync(args[args.length - 1], "mp4"); +} +process.exit(0); +`, +); +await chmod(YTDLP, 0o755); +await chmod(FFMPEG, 0o755); +process.env.WORKER_TOKEN = "test-token"; +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +process.env.YTDLP_BIN = YTDLP; +process.env.FFMPEG_BIN = FFMPEG; +// The fallback's pause, as on the e2e server. +process.env.E2E_CLIP_WINDOW_GAP_MS = "0"; +await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 })); +await mkdir(path.join(ROOT, "channels", SLUG), { recursive: true }); +await writeFile( + path.join(ROOT, "channels", SLUG, "config.json"), + JSON.stringify({ name: "Demo", handling: "youtube", url: "https://odysee.com/@demo", platform: "odysee" }), +); +const page = (id: string) => `https://odysee.com/@demo:1/stream-${id}:${id}`; +const cdn = (id: string) => `https://player.odycdn.com/v6/streams/${id}/f0.mp4`; +async function video(id: string, withStored: boolean): Promise<string> { + const dir = path.join(ROOT, "channels", SLUG, "data", id); + await mkdir(dir, { recursive: true }); + await writeFile( + path.join(dir, "metadata.info.json"), + JSON.stringify({ + id, + webpage_url: page(id), + ...(withStored ? { formats: [{ format_id: "original", url: cdn(id), protocol: "https", ext: "mp4" }] } : {}), + }), + ); + return dir; +} +const S1 = await video("s1", true); +const S2 = await video("s2", true); +await video("n1", false); + +const { POST } = await import("./route"); +const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +function post(body: Record<string, unknown>): Promise<Response> { + return POST( + new Request("http://localhost/api/media/fetch-window", { + method: "POST", + headers: { authorization: "Bearer test-token", "content-type": "application/json" }, + body: JSON.stringify(body), + }), + ); +} +const ask = (videoId: string, extra: Record<string, unknown> = {}) => + post({ channelSlug: SLUG, videoId, requestedBy: "test", from: 1, to: 3, ...extra }); + +const targets = async () => + (await readFile(ARGS_LOG, "utf8").catch(() => "")) + .trim() + .split("\n") + .filter(Boolean) + .map((l) => (JSON.parse(l) as string[]).at(-1)); + +async function settle(jobId: string): Promise<string | undefined> { + const reg = getRegistry(); + for (let i = 0; i < 200; i++) { + const s = reg.get(jobId)?.status; + if (s !== "queued" && s !== "running") break; + await new Promise((res) => setTimeout(res, 50)); + } + return reg.get(jobId)?.status; +} + +test("a storedUrl that is not a mode is refused with 400", async () => { + const res = await ask("s1", { storedUrl: "always" }); + assert.equal(res.status, 400); + assert.match(((await res.json()) as { error: string }).error, /storedUrl must be one of "never", "fallback", "only"/); +}); + +test("fallback, the platform answering: the page 429s, then the window is cut from the stored URL", async () => { + const res = await ask("s1", { storedUrl: "fallback" }); + assert.equal(res.status, 202); + const { jobId } = (await res.json()) as { jobId: string }; + assert.equal(await settle(jobId), "done"); + assert.equal(getRegistry().get(jobId)?.spec?.params?.storedUrl, "fallback", "a Retry keeps the mode"); + assert.deepEqual(await targets(), [page("s1"), cdn("s1")], "the page first, then the stored file"); + const sidecar = JSON.parse(await readFile(path.join(S1, "clips", "1.00-3.00.json"), "utf8")); + assert.equal(sidecar.source, "stored-media-url"); + assert.equal(sidecar.sourceHost, "player.odycdn.com"); +}); + +test("never (the default), the platform cooling after that 429: refused with 409", async () => { + const res = await ask("s2"); + assert.equal(res.status, 409); + const body = (await res.json()) as { error: string; platform: string }; + assert.equal(body.platform, "odysee"); + assert.match(body.error, /rate-limit cooldown/); +}); + +test("fallback with no stored URL, the platform cooling: refused as before", async () => { + const res = await ask("n1", { storedUrl: "fallback" }); + assert.equal(res.status, 409); +}); + +test("only, the platform cooling: cut from the stored URL with no page request", async () => { + const before = (await targets()).length; + const res = await ask("s2", { storedUrl: "only" }); + assert.equal(res.status, 202); + const { jobId } = (await res.json()) as { jobId: string }; + assert.equal(await settle(jobId), "done"); + assert.deepEqual((await targets()).slice(before), [cdn("s2")]); + const sidecar = JSON.parse(await readFile(path.join(S2, "clips", "1.00-3.00.json"), "utf8")); + assert.equal(sidecar.source, "stored-media-url"); +}); diff --git a/editor/app/api/media/fetch-window/route.ts b/editor/app/api/media/fetch-window/route.ts @@ -9,6 +9,10 @@ import { } from "yt-dlp-transcript-common/lib/clipWindow"; import { sourceVideoQualityForMaxHeight } from "yt-dlp-transcript-common/ytdlp/downloadFormat"; import { + STORED_URL_MODES, + isStoredUrlMode, +} from "yt-dlp-transcript-common/lib/storedMediaUrl"; +import { fetchFullSourceAction, fetchWindowAction, type FetchMediaOutcome, @@ -54,6 +58,7 @@ type Body = { pad?: unknown; full?: unknown; maxHeight?: unknown; + storedUrl?: unknown; }; const str = (v: unknown): string | undefined => @@ -169,6 +174,18 @@ export async function POST(request: Request) { ); } + // CUT FROM THE STORED MEDIA URL (release 32 R6): "never" (default) | + // "fallback" | "only" — the fetch-windows batch's rule for one window + // (lib/storedMediaUrl.ts). A window only: a whole recording ignores it. + const storedUrl = + body.storedUrl === undefined || body.storedUrl === null ? undefined : body.storedUrl; + if (storedUrl !== undefined && !isStoredUrlMode(storedUrl)) { + return NextResponse.json( + { error: `storedUrl must be one of ${STORED_URL_MODES.map((m) => `"${m}"`).join(", ")}` }, + { status: 400 }, + ); + } + if (body.full === true) { // A cap at or under 720 asks for "video_720"; one above it asks for // "original" in so many words. No cap: the channel's, else the global, @@ -221,6 +238,7 @@ export async function POST(request: Request) { to, provenance, maxHeight, + ...(storedUrl ? { storedUrl } : {}), }), ); } diff --git a/editor/app/channels/[slug]/components/ChannelMediaTools.tsx b/editor/app/channels/[slug]/components/ChannelMediaTools.tsx @@ -0,0 +1,213 @@ +"use client"; + +import Link from "next/link"; +import { useState } from "react"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import { cancelJobAction } from "../../../jobs/actions"; +import { attachMediaAction } from "../attachMediaActions"; +import { preparePlayableAction } from "../playableActions"; +import { readResultMarker } from "../../../lib/resultMarker"; +import { + MEDIA_SUMMARY_MARKER, + attachSummaryWords, + playableSummaryWords, + type AttachSummary, + type PlayableSummary, +} from "../lib/mediaToolsWords"; + +// The channel-wide media operations that were CLI-only (release 32 R6), beside +// the saved-video store they write into: +// +// Attach media from a local archive `archilyzer media attach <slug> +// <source>` — every held video's file out of a directory, a .zip or a +// .7z into the store (`--match`, `--create-records`, `--replace`) +// Playable copies `archilyzer media playable <slug>` — +// every saved container remuxed to a browser-playable copy with its +// torrent (`--trackers`, `--root`) +// +// Each previews first (the job's dry run, which writes nothing) and the run is +// armed by a preview of the same settings. Both jobs end their log with a +// `summary: {json}` line: the result is said from it in plain words, and the +// job is linked. + +function Outcome({ label, jobId, lines }: { label: string; jobId: string | null; lines: string[] | null }) { + return ( + <div role="status" aria-label={label} className="flex flex-col gap-0.5 text-sm"> + {lines ? lines.map((l) => <p key={l}>{l}</p>) : <p className="text-muted-foreground">The job left no summary; see its log.</p>} + {jobId && ( + <p className="text-xs text-muted-foreground"> + <Link href={`/jobs/${jobId}`} className="underline font-mono"> + job {jobId} + </Link> + </p> + )} + </div> + ); +} + +export function ChannelMediaTools({ slug }: { slug: string }) { + return ( + <details aria-label="channel media tools" className="rounded border border-border p-3"> + <summary className="cursor-pointer text-sm font-semibold">Media for the whole channel</summary> + <div className="mt-3 flex flex-col gap-5"> + <AttachArchive slug={slug} /> + <PlayableCopies slug={slug} /> + </div> + </details> + ); +} + +function AttachArchive({ slug }: { slug: string }) { + const [source, setSource] = useState(""); + const [match, setMatch] = useState(""); + const [createRecords, setCreateRecords] = useState(false); + const [replace, setReplace] = useState(false); + const key = JSON.stringify([source.trim(), match.trim(), createRecords, replace]); + const [previewed, setPreviewed] = useState<string | null>(null); + const [out, setOut] = useState<{ what: "preview" | "run"; jobId: string | null; lines: string[] | null } | null>(null); + const opts = (dryRun: boolean) => ({ + source: source.trim(), + ...(match.trim() ? { match: match.trim() } : {}), + ...(createRecords ? { createRecords: true } : {}), + ...(replace ? { replace: true } : {}), + ...(dryRun ? { dryRun: true } : {}), + }); + const settle = (what: "preview" | "run") => (started: boolean, o: { log: string; jobId: string | null }) => { + if (!started) return; + const s = readResultMarker<AttachSummary>(o.log, MEDIA_SUMMARY_MARKER); + setOut({ what, jobId: o.jobId, lines: s ? attachSummaryWords(s) : null }); + if (what === "preview") setPreviewed(key); + }; + return ( + <div className="flex flex-col gap-2" aria-label="attach media from a local archive"> + <h4 className="text-sm font-semibold">Attach media from a local archive</h4> + <p className="text-xs text-muted-foreground"> + Every video this channel holds gets its file from the archive — matched by the id in the folder or file name — + copied into the saved-video store with where it came from. Nothing is downloaded. + </p> + <div className="flex flex-wrap gap-3 text-sm"> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Archive (absolute path: a folder, a .zip or a .7z)</span> + <input + value={source} + onChange={(e) => setSource(e.target.value)} + aria-label="archive path" + placeholder="/mnt/archive/channel-backup.zip" + className="rounded border border-border bg-card px-2 py-1 text-sm font-mono w-96 max-w-full" + /> + </label> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Only names matching (optional regex)</span> + <input + value={match} + onChange={(e) => setMatch(e.target.value)} + aria-label="attach files matching" + className="rounded border border-border bg-card px-2 py-1 text-sm font-mono w-56 max-w-full" + /> + </label> + </div> + <div className="flex flex-wrap gap-4 text-sm"> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={createRecords} onChange={(e) => setCreateRecords(e.target.checked)} /> + Create records for videos the channel does not hold + </label> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={replace} onChange={(e) => setReplace(e.target.checked)} /> + Replace files already saved + </label> + </div> + <StreamActionLog + trigger={() => attachMediaAction(slug, opts(true))} + cancelAction={cancelJobAction} + buttonLabel="Preview attach" + runningLabel="Reading the archive…" + label={`Preview attach into ${slug}`} + disabled={!source.trim()} + onSettled={settle("preview")} + /> + <StreamActionLog + trigger={() => attachMediaAction(slug, opts(false))} + cancelAction={cancelJobAction} + buttonLabel="Attach" + runningLabel="Attaching…" + label={`Attach media into ${slug}`} + disabled={previewed !== key} + onSettled={settle("run")} + /> + {previewed !== key && <p className="text-xs text-muted-foreground">Preview these settings first.</p>} + {out && <Outcome label={out.what === "preview" ? "attach preview" : "attach result"} jobId={out.jobId} lines={out.lines} />} + </div> + ); +} + +function PlayableCopies({ slug }: { slug: string }) { + const [trackers, setTrackers] = useState(""); + const [root, setRoot] = useState(""); + const trackerList = trackers + .split(/[\s,]+/) + .map((t) => t.trim()) + .filter(Boolean); + const key = JSON.stringify([trackerList, root.trim()]); + const [previewed, setPreviewed] = useState<string | null>(null); + const [out, setOut] = useState<{ what: "preview" | "run"; jobId: string | null; lines: string[] | null } | null>(null); + const opts = (dryRun: boolean) => ({ + ...(trackerList.length > 0 ? { trackers: trackerList } : {}), + ...(root.trim() ? { root: root.trim() } : {}), + ...(dryRun ? { dryRun: true } : {}), + }); + const settle = (what: "preview" | "run") => (started: boolean, o: { log: string; jobId: string | null }) => { + if (!started) return; + const s = readResultMarker<PlayableSummary>(o.log, MEDIA_SUMMARY_MARKER); + setOut({ what, jobId: o.jobId, lines: s ? playableSummaryWords(s) : null }); + if (what === "preview") setPreviewed(key); + }; + return ( + <div className="flex flex-col gap-2" aria-label="playable copies"> + <h4 className="text-sm font-semibold">Playable copies</h4> + <p className="text-xs text-muted-foreground"> + Every saved container is copied, without re-encoding, into a file a browser can play (mp4 or webm), each with + a torrent. A copy already made from the same file is skipped. + </p> + <div className="flex flex-wrap gap-3 text-sm"> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Trackers (optional, comma or space separated)</span> + <input + value={trackers} + onChange={(e) => setTrackers(e.target.value)} + aria-label="torrent trackers" + placeholder="wss://tracker.example/announce" + className="rounded border border-border bg-card px-2 py-1 text-sm font-mono w-96 max-w-full" + /> + </label> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Folder (optional absolute path; default beside the store)</span> + <input + value={root} + onChange={(e) => setRoot(e.target.value)} + aria-label="playable folder" + className="rounded border border-border bg-card px-2 py-1 text-sm font-mono w-72 max-w-full" + /> + </label> + </div> + <StreamActionLog + trigger={() => preparePlayableAction(slug, opts(true))} + cancelAction={cancelJobAction} + buttonLabel="Preview playable copies" + runningLabel="Checking…" + label={`Preview playable copies of ${slug}`} + onSettled={settle("preview")} + /> + <StreamActionLog + trigger={() => preparePlayableAction(slug, opts(false))} + cancelAction={cancelJobAction} + buttonLabel="Make playable copies" + runningLabel="Remuxing…" + label={`Playable copies of ${slug}`} + disabled={previewed !== key} + onSettled={settle("run")} + /> + {previewed !== key && <p className="text-xs text-muted-foreground">Preview these settings first.</p>} + {out && <Outcome label={out.what === "preview" ? "playable preview" : "playable result"} jobId={out.jobId} lines={out.lines} />} + </div> + ); +} diff --git a/editor/app/channels/[slug]/components/stages/CleanupStage.tsx b/editor/app/channels/[slug]/components/stages/CleanupStage.tsx @@ -2,6 +2,7 @@ import { useState } from "react"; import { KeepMatchingControl } from "../KeepMatchingControl"; +import { ChannelMediaTools } from "../ChannelMediaTools"; import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; import { formatBytes } from "yt-dlp-transcript-common/lib/format"; import { QueueControl } from "../../../../components/QueueControl"; @@ -82,6 +83,7 @@ export function CleanupStage({ defaultQueueKey={defaultQueueKey} /> )} + <ChannelMediaTools slug={slug} /> {diarizationEnabled && ( <div className="flex flex-col gap-2"> <Heading diff --git a/editor/app/channels/[slug]/lib/mediaToolsWords.test.ts b/editor/app/channels/[slug]/lib/mediaToolsWords.test.ts @@ -0,0 +1,39 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { attachSummaryWords, playableSummaryWords } from "./mediaToolsWords"; + +// Run with: pnpm -C editor exec tsx --test "app/channels/*/lib/mediaToolsWords.test.ts" + +const attach = { + dryRun: true, + counts: { attach: 2, create: 1 }, + attached: 0, + created: [], + failed: [], + notHeld: ["x9"], + lost: 0, + unmatched: [], + ambiguous: [], + alreadyAttached: 1, + heldWithoutMedia: [], +}; + +test("an attach preview and run, said in plain words", () => { + assert.deepEqual(attachSummaryWords(attach), [ + "Would attach 2 held videos and write 1 new record.", + "1 video already had a saved file (left alone; tick Replace to swap).", + "1 file for videos this channel does not hold (tick Create records to add them).", + ]); + const run = attachSummaryWords({ ...attach, dryRun: false, attached: 1, created: [], alreadyAttached: 0, notHeld: [], failed: [{ id: "a1", error: "disk" }], stopped: "low-disk" }); + assert.deepEqual(run, ["Attached 1 video.", "1 video failed: a1 (disk).", "Stopped (low-disk): run it again to continue."]); +}); + +test("a playable preview and run, said in plain words", () => { + const s = { dryRun: true, root: "/store/playable", prepared: 1, unchanged: 2, unplayable: [{ id: "v1", reason: "hevc in webm" }], noContainer: [], failed: [] }; + assert.deepEqual(playableSummaryWords(s), [ + "Would make 1 playable copy; 2 already up to date.", + "Under /store/playable.", + "1 video cannot be made playable without re-encoding: v1 (hevc in webm).", + ]); + assert.match(playableSummaryWords({ ...s, dryRun: false, prepared: 3, unplayable: [] })[0]!, /^Made 3 playable copies with their torrents/); +}); diff --git a/editor/app/channels/[slug]/lib/mediaToolsWords.ts b/editor/app/channels/[slug]/lib/mediaToolsWords.ts @@ -0,0 +1,75 @@ +// The channel media tools' results in plain words (release 32 R6, +// components/ChannelMediaTools.tsx): an attach-media or prepare-playable job's +// `summary: {json}` line, said as sentences. Client-safe and pure. + +// The last line of an attach-media and a prepare-playable job's log +// (controller/attachMedia.ts summaryOf, controller/preparePlayable.ts). +export const MEDIA_SUMMARY_MARKER = "summary: "; + +export type AttachSummary = { + dryRun: boolean; + counts: Record<string, number>; + attached: number; + created: string[]; + failed: { id: string; error: string }[]; + notHeld: string[]; + lost: number; + unmatched: string[]; + ambiguous: string[]; + alreadyAttached: number; + heldWithoutMedia: string[] | null; + stopped?: string; +}; + +export type PlayableSummary = { + dryRun: boolean; + root: string; + prepared: number; + unchanged: number; + unplayable: { id: string; reason: string }[]; + noContainer: string[]; + failed: { id: string; error: string }[]; + stopped?: string; +}; + +const n = (k: number, one: string, many = `${one}s`) => `${k} ${k === 1 ? one : many}`; + +export function attachSummaryWords(s: AttachSummary): string[] { + const c = s.counts ?? {}; + const lines: string[] = []; + if (s.dryRun) { + lines.push( + `Would attach ${n(c.attach ?? 0, "held video")}` + + ((c.create ?? 0) > 0 ? ` and write ${n(c.create ?? 0, "new record")}` : "") + + ".", + ); + } else { + lines.push( + `Attached ${n(s.attached, "video")}` + (s.created.length > 0 ? ` (${n(s.created.length, "new record")})` : "") + ".", + ); + } + if (s.alreadyAttached > 0) lines.push(`${n(s.alreadyAttached, "video")} already had a saved file (left alone; tick Replace to swap).`); + if (s.notHeld.length > 0) lines.push(`${n(s.notHeld.length, "file")} for videos this channel does not hold (tick Create records to add them).`); + if (s.unmatched.length > 0) lines.push(`${n(s.unmatched.length, "file")} with no video id in the name.`); + if (s.ambiguous.length > 0) lines.push(`${n(s.ambiguous.length, "video")} with more than one candidate file: ${s.ambiguous.slice(0, 5).join(", ")}${s.ambiguous.length > 5 ? "…" : ""}.`); + if (s.lost > 0) lines.push(`${n(s.lost, "folder")} marked lost (never attached).`); + if (s.heldWithoutMedia && s.heldWithoutMedia.length > 0) lines.push(`${n(s.heldWithoutMedia.length, "held video")} with no file in the archive.`); + if (s.failed.length > 0) lines.push(`${n(s.failed.length, "video")} failed: ${s.failed.slice(0, 3).map((f) => `${f.id} (${f.error})`).join("; ")}.`); + if (s.stopped) lines.push(`Stopped (${s.stopped}): run it again to continue.`); + return lines; +} + +export function playableSummaryWords(s: PlayableSummary): string[] { + const lines = [ + s.dryRun + ? `Would make ${n(s.prepared, "playable copy", "playable copies")}; ${s.unchanged} already up to date.` + : `Made ${n(s.prepared, "playable copy", "playable copies")} with their torrents; ${s.unchanged} already up to date.`, + `Under ${s.root}.`, + ]; + if (s.unplayable.length > 0) lines.push(`${n(s.unplayable.length, "video")} cannot be made playable without re-encoding: ${s.unplayable.slice(0, 3).map((u) => `${u.id} (${u.reason})`).join("; ")}.`); + if (s.noContainer.length > 0) lines.push(`${n(s.noContainer.length, "video")} with no saved container.`); + if (s.failed.length > 0) lines.push(`${n(s.failed.length, "video")} failed: ${s.failed.slice(0, 3).map((f) => `${f.id} (${f.error})`).join("; ")}.`); + if (s.stopped) lines.push(`Stopped (${s.stopped}): run it again to continue.`); + return lines; +} + diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -86,9 +86,18 @@ import { savedWindowSource, } from "yt-dlp-transcript-common/lib/savedVideoWindow-server"; import { + FetchWindowError, fetchWindowManaged, type FetchWindowProvenance, } from "yt-dlp-transcript-common/ytdlp/fetchWindowManaged"; +import { + isStoredUrlPlatform, + type StoredMediaUrl, + type StoredUrlMode, + type StoredUrlWhy, +} from "yt-dlp-transcript-common/lib/storedMediaUrl"; +import { storedMediaUrl } from "yt-dlp-transcript-common/lib/storedMediaUrl-server"; +import { CLIP_WINDOW_MIN_GAP_SECONDS } from "yt-dlp-transcript-common/controller/fetchWindows"; import { probeVideoHeight } from "yt-dlp-transcript-common/ytdlp/ffprobeDuration"; import { detectPlatform } from "yt-dlp-transcript-common/lib/platform"; import { channelConfigPlatform } from "yt-dlp-transcript-common/lib/videoId"; @@ -1098,6 +1107,9 @@ export async function fetchWindowAction(req: { // Hand back the StreamActionResult instead of detaching it. Set by Retry, // which renders the log; the HTTP route leaves it off and polls. stream?: boolean; + // CUT FROM THE STORED MEDIA URL (release 32 R6; the batch's rule, release 32 + // R5, controller/fetchWindows.ts): "never" (default) | "fallback" | "only". + storedUrl?: StoredUrlMode; }): Promise<FetchMediaOutcome> { const { slug, from, to } = req; // THE CAP IS CHECKED HERE TOO, not only at the HTTP door. Retry re-runs from @@ -1250,13 +1262,26 @@ export async function fetchWindowAction(req: { // handful of seconds, but a 429 is a fact about the SOURCE, not about the // size of the request. const platform = detectPlatform(url) ?? "unknown"; + // THE STORED MEDIA URL (release 32 R6), the batch's rule for one window: asked + // only when the request opted in, for an allowlisted platform whose page the + // URL is. `only` cuts from it without asking the page; a held or cooling + // platform does not refuse a window that has one (it asks no page); without + // one, the window goes the usual way. + const storedMode = req.storedUrl ?? "never"; + const stored: StoredMediaUrl | null = + storedMode !== "never" && isStoredUrlPlatform(platform) + ? await storedMediaUrl(videoDir).then((s) => (s && s.platform === platform ? s : null)) + : null; // A held platform's refusal names the hold and the next probe (release 17). const held = await heldPlatformRefusal(platform, "This fetch", paths); const cooldownMs = await platformCooldownRemainingMs(platform, paths); - if (held && cooldownMs > 0) { + let via: StoredUrlWhy | null = stored && storedMode === "only" ? "only" : null; + if (!via && stored && (held || cooldownMs > 0)) via = held ? "held" : "rate-limited"; + if (via) { + // No page is asked: neither the hold nor the cooldown is this fetch's. + } else if (held && cooldownMs > 0) { return { ok: false, status: 409, cooldownMs, platform, error: held }; - } - if (cooldownMs > 0) { + } else if (cooldownMs > 0) { return { ok: false, status: 409, @@ -1297,29 +1322,56 @@ export async function fetchWindowAction(req: { webpageUrl: url, queueKey: req.queueKey, ...(req.maxHeight !== undefined ? { maxHeight: req.maxHeight } : {}), + // A Retry keeps the mode it was asked with. + ...(storedMode !== "never" ? { storedUrl: storedMode } : {}), ...req.provenance, }, }, fn: async (onLog, signal) => { onLog(`${requesterLine(req.provenance)}\n`); - await fetchWindowManaged({ - channelSlug: slug, - channelConfig: r.config, - paths, - videoDir, - videoId, - videoUrl: url, - // The channel root, as every other yt-dlp invocation here runs. - cwd: path.join(paths.channelsDir, slug), - from, - to, - provenance: req.provenance, - maxHeight: req.maxHeight, - cookiePolicy: resolveCookiePolicy(settings, r.config), - onLog, - signal, - onPlatformBackoff: () => recordDownloadBackoff(platform, paths), - }); + const once = (target: (StoredMediaUrl & { why: StoredUrlWhy }) | null) => + fetchWindowManaged({ + channelSlug: slug, + channelConfig: r.config, + paths, + videoDir, + videoId, + videoUrl: url, + ...(target ? { storedMedia: target } : {}), + // The channel root, as every other yt-dlp invocation here runs. + cwd: path.join(paths.channelsDir, slug), + from, + to, + provenance: req.provenance, + maxHeight: req.maxHeight, + cookiePolicy: resolveCookiePolicy(settings, r.config), + onLog, + signal, + onPlatformBackoff: () => recordDownloadBackoff(platform, paths), + }); + if (via && stored) { + await once({ ...stored, why: via }); + } else { + try { + await once(null); + } catch (e) { + // FALLBACK: the page lookup rate-limited (the backoff is already + // recorded) and the record stores its media URL — cut from that, + // after the clip gap: one stream, real gaps. + if ( + !(stored && storedMode === "fallback" && e instanceof FetchWindowError && e.failureClass === "rate_limit") + ) { + throw e; + } + const gapMs = storedFallbackGapMs(); + onLog( + `${platform} rate-limited the page lookup — cutting from the stored media URL ` + + `(${stored.host}) instead, after ${Math.round(gapMs / 1000)}s.\n`, + ); + await abortableSleep(gapMs, signal); + await once({ ...stored, why: "rate-limited" }); + } + } safeRevalidate([`/channels/${slug}/videos/${videoId}`]); }, }); @@ -1342,6 +1394,31 @@ export async function fetchWindowAction(req: { }; } +// The pause before a single window's stored-URL fallback: the batch's clip gap +// (CLIP_WINDOW_MIN_GAP_SECONDS), or E2E_CLIP_WINDOW_GAP_MS on the e2e server. +function storedFallbackGapMs(): number { + const raw = Number(process.env.E2E_CLIP_WINDOW_GAP_MS); + return process.env.E2E_CLIP_WINDOW_GAP_MS !== undefined && Number.isFinite(raw) && raw >= 0 + ? raw + : CLIP_WINDOW_MIN_GAP_SECONDS * 1000; +} + +function abortableSleep(ms: number, signal: AbortSignal): Promise<void> { + if (ms <= 0) return Promise.resolve(); + return new Promise((resolve, reject) => { + if (signal.aborted) return reject(new Error("Cancelled")); + const t = setTimeout(() => { + signal.removeEventListener("abort", onAbort); + resolve(); + }, ms); + const onAbort = () => { + clearTimeout(t); + reject(new Error("Cancelled")); + }; + signal.addEventListener("abort", onAbort, { once: true }); + }); +} + // Retry, from the /jobs page. A replayed fetch re-derives from the CURRENT // disk: a window somebody has since fetched (or that a wider one now covers) // replays as a neutral "already there" rather than downloading it twice. @@ -1354,6 +1431,7 @@ export async function replayFetchWindowAction(req: { provenance: FetchWindowProvenance; queueKey?: string; maxHeight?: number; + storedUrl?: StoredUrlMode; }): Promise<StreamActionResult> { const r = await fetchWindowAction({ ...req, stream: true }); if (!r.ok) return { ok: false, error: r.error, info: r.status === 409 }; diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -210,6 +210,7 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { }, queueKey, maxHeight: num(p.maxHeight), + ...(isStoredUrlMode(p.storedUrl) ? { storedUrl: p.storedUrl } : {}), }); }, // A batch of windows. Replay re-runs the same list on the same queue; the diff --git a/editor/app/saved-videos/components/PersistVideoListControl.tsx b/editor/app/saved-videos/components/PersistVideoListControl.tsx @@ -0,0 +1,136 @@ +"use client"; + +import Link from "next/link"; +import { useState, useTransition } from "react"; +import { Button } from "yt-dlp-transcript-common/components/ui/button"; +import { SOURCE_VIDEO_QUALITY_LABELS } from "yt-dlp-transcript-common/ytdlp/downloadFormat"; +import type { PersistVideosActionResult } from "../../channels/[slug]/persistActions"; +import { persistVideoListAction } from "../persistListAction"; + +// "Save these videos" (release 32 R6): `pnpm ops persist-videos` from the UI — +// a list of videos across channels saved to this store. Preview says what a run +// would do with each (the plan's buckets) and starts nothing; Save is armed by +// a preview of the same list and settings, and links the job per channel. + +type Format = "" | "original" | "video_720"; + +const sameKey = (text: string, format: Format, replace: boolean) => JSON.stringify([text.trim(), format, replace]); + +export function PersistVideoListControl() { + const [text, setText] = useState(""); + const [format, setFormat] = useState<Format>(""); + const [replace, setReplace] = useState(false); + const [previewed, setPreviewed] = useState<string | null>(null); + const [result, setResult] = useState<PersistVideosActionResult | null>(null); + const [pending, start] = useTransition(); + const key = sameKey(text, format, replace); + const run = (dryRun: boolean) => + start(async () => { + const r = await persistVideoListAction({ + text, + ...(format ? { format } : {}), + ...(replace ? { replace: "above-height" as const } : {}), + dryRun, + }); + setResult(r); + if (dryRun && r.ok) setPreviewed(key); + }); + return ( + <section aria-label="save these videos" className="flex flex-col gap-2 rounded border border-border p-3"> + <h2 className="text-base font-semibold">Save these videos</h2> + <p className="text-xs text-muted-foreground"> + One per line: <span className="font-mono">channel/video-id</span>, or a video page&apos;s link. Each channel&apos;s + videos are downloaded whole into the store, paced like any download; a video already saved is skipped. + </p> + <textarea + value={text} + onChange={(e) => setText(e.target.value)} + aria-label="videos to save" + rows={5} + placeholder={"demo-channel/dQw4w9WgXcQ\nother-channel/abc123"} + className="rounded border border-border bg-card px-2 py-1 font-mono text-sm" + /> + <div className="flex flex-wrap items-center gap-4 text-sm"> + <label className="flex items-center gap-2"> + <span className="text-muted-foreground">Quality</span> + <select + value={format} + onChange={(e) => setFormat(e.target.value as Format)} + aria-label="quality to save" + className="rounded border border-border bg-card px-2 py-1 text-sm" + > + <option value="">each channel&apos;s own</option> + <option value="original">{SOURCE_VIDEO_QUALITY_LABELS.original}</option> + <option value="video_720">{SOURCE_VIDEO_QUALITY_LABELS.video_720}</option> + </select> + </label> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={replace} onChange={(e) => setReplace(e.target.checked)} /> + Also replace a saved one taller than that quality, or of unknown height + </label> + </div> + <div className="flex flex-wrap items-center gap-2"> + <Button type="button" variant="outline" disabled={pending || !text.trim()} onClick={() => run(true)}> + Preview + </Button> + <Button type="button" disabled={pending || previewed !== key} onClick={() => run(false)}> + {pending ? "Working…" : "Save videos"} + </Button> + {previewed !== key && <span className="text-xs text-muted-foreground">Preview this list first.</span>} + </div> + {result && <PersistOutcome result={result} />} + </section> + ); +} + +const BUCKETS: { key: "saved" | "toFetch" | "wrongHeight" | "noUrl" | "unknown"; words: string }[] = [ + { key: "toFetch", words: "to download" }, + { key: "saved", words: "already saved" }, + { key: "wrongHeight", words: "saved, but taller than asked or of unknown height" }, + { key: "noUrl", words: "with no source address to download from" }, + { key: "unknown", words: "not found (no such channel or video)" }, +]; + +function PersistOutcome({ result }: { result: PersistVideosActionResult }) { + if (!result.ok) { + return ( + <p role="alert" className="text-sm text-destructive"> + {result.error} + </p> + ); + } + const plan = result.plan; + return ( + <div role="status" aria-label={result.dryRun ? "save preview" : "save result"} className="flex flex-col gap-1 text-sm"> + <p> + {result.dryRun ? "A run would download " : "Downloading "} + {plan.willFetch} video{plan.willFetch === 1 ? "" : "s"}. + </p> + <ul className="list-disc pl-5 text-muted-foreground"> + {BUCKETS.filter((b) => plan[b.key].count > 0).map((b) => ( + <li key={b.key} data-bucket={b.key}> + {plan[b.key].count} {b.words} + {plan[b.key].count <= 8 && ( + <span className="font-mono text-xs"> — {plan[b.key].items.map((i) => `${i.slug}/${i.id}`).join(", ")}</span> + )} + </li> + ))} + </ul> + {!result.dryRun && + result.jobs.map((j) => ( + <p key={j.jobId}> + {j.slug}:{" "} + <Link href={`/jobs/${j.jobId}`} className="font-mono underline"> + job {j.jobId} + </Link> + </p> + ))} + {!result.dryRun && + result.skipped.map((s) => ( + <p key={s.slug} className="text-destructive"> + {s.slug}: not started — {s.reason} + </p> + ))} + </div> + ); +} diff --git a/editor/app/saved-videos/lib/videoList.test.ts b/editor/app/saved-videos/lib/videoList.test.ts @@ -0,0 +1,35 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { parseVideoList } from "./videoList"; + +// Run with: pnpm -C editor exec tsx --test "app/saved-videos/lib/videoList.test.ts" + +test("slug/id, slug id, slug,id and an editor video link; blanks and # comments skipped; repeats once", () => { + const r = parseVideoList( + [ + "demo-channel/dQw4w9WgXcQ", + " other-chan abc_123 ", + "", + "# a comment", + "third,v-1.2", + "http://localhost:3001/channels/demo-channel/videos/dQw4w9WgXcQ?tab=x", + "https://editor.example/channels/fourth/videos/zz9", + ].join("\n"), + ); + assert.deepEqual(r.items, [ + { slug: "demo-channel", id: "dQw4w9WgXcQ" }, + { slug: "other-chan", id: "abc_123" }, + { slug: "third", id: "v-1.2" }, + { slug: "fourth", id: "zz9" }, + ]); + assert.deepEqual(r.bad, []); +}); + +test("a line that names no channel and video is reported with its line number", () => { + const r = parseVideoList("ok/one\njust-one-word\na b c\n../etc passwd\nhttps://youtube.com/watch?v=x"); + assert.deepEqual(r.items, [{ slug: "ok", id: "one" }]); + assert.deepEqual( + r.bad.map((b) => b.line), + [2, 3, 4, 5], + ); +}); diff --git a/editor/app/saved-videos/lib/videoList.ts b/editor/app/saved-videos/lib/videoList.ts @@ -0,0 +1,49 @@ +// A LIST OF VIDEOS, typed or pasted (release 32 R6: the Saved videos page's +// "Save these videos", `pnpm ops persist-videos` from the UI). One video per +// line, any of: +// +// <slug>/<id> demo-channel/dQw4w9WgXcQ +// <slug> <id> <slug>,<id> (space, tab or comma between) +// an editor video link http://localhost:3001/channels/demo-channel/videos/dQw4w9WgXcQ +// +// Blank lines and lines starting with # are skipped; a repeat is listed once. +// Pure: the action checks the channels and the records. + +export type ListedVideo = { slug: string; id: string }; +export type VideoListParse = { items: ListedVideo[]; bad: { line: number; text: string }[] }; + +const NAME = /^[\w.-]+$/; +const ok = (v: string) => NAME.test(v) && v !== "." && v !== ".."; + +function one(raw: string): ListedVideo | null { + const link = /\/channels\/([^/\s?#]+)\/videos\/([^/\s?#]+)/.exec(raw); + if (link) { + const slug = decodeURIComponent(link[1]!); + const id = decodeURIComponent(link[2]!); + return ok(slug) && ok(id) ? { slug, id } : null; + } + const parts = raw.split(/[\s,/]+/).filter(Boolean); + if (parts.length !== 2) return null; + const [slug, id] = parts as [string, string]; + return ok(slug) && ok(id) ? { slug, id } : null; +} + +export function parseVideoList(text: string): VideoListParse { + const items: ListedVideo[] = []; + const bad: { line: number; text: string }[] = []; + const seen = new Set<string>(); + text.split(/\r?\n/).forEach((l, i) => { + const raw = l.trim(); + if (!raw || raw.startsWith("#")) return; + const v = one(raw); + if (!v) { + bad.push({ line: i + 1, text: raw }); + return; + } + const key = `${v.slug}/${v.id}`; + if (seen.has(key)) return; + seen.add(key); + items.push(v); + }); + return { items, bad }; +} diff --git a/editor/app/saved-videos/page.tsx b/editor/app/saved-videos/page.tsx @@ -6,6 +6,7 @@ import { formatBytes } from "yt-dlp-transcript-common/lib/format"; import { listSavedVideos } from "yt-dlp-transcript-common/controller/savedVideoInventory"; import { readSchedulerState } from "yt-dlp-transcript-common/jobs/syncSchedulerState"; import { SavedVideosControls } from "./components/SavedVideosControls"; +import { PersistVideoListControl } from "./components/PersistVideoListControl"; export const dynamic = "force-dynamic"; @@ -95,6 +96,8 @@ export default async function SavedVideosPage() { </div> </section> + <PersistVideoListControl /> + <section aria-label="per-channel saved videos" className="flex flex-col gap-2"> <h2 className="text-base font-semibold">By channel</h2> {notAnswering.length > 0 && ( diff --git a/editor/app/saved-videos/persistListAction.ts b/editor/app/saved-videos/persistListAction.ts @@ -0,0 +1,43 @@ +"use server"; + +import { persistVideosAction, type PersistVideosActionResult } from "../channels/[slug]/persistActions"; +import type { PersistReplacePolicy } from "yt-dlp-transcript-common/controller/persistVideos"; +import { isSourceVideoQuality, type SourceVideoQuality } from "yt-dlp-transcript-common/ytdlp/downloadFormat"; +import { parseVideoList } from "./lib/videoList"; + +// "Save these videos" on the Saved videos page (release 32 R6): `pnpm ops +// persist-videos` from the UI. The typed list is read (lib/videoList.ts) and +// handed to persistVideosAction as the ops route hands it: a preview answers +// with the plan's buckets and starts nothing; a run starts one persist-videos +// job per channel with something to fetch. +// +// NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use server" file). + +export async function persistVideoListAction(input: { + text: string; + format?: string; + replace?: PersistReplacePolicy; + dryRun: boolean; +}): Promise<PersistVideosActionResult> { + const { items, bad } = parseVideoList(input.text); + if (bad.length > 0) { + return { + ok: false, + error: + `${bad.length} line(s) name no channel and video (slug/id, or a video page link): ` + + bad + .slice(0, 5) + .map((b) => `line ${b.line} "${b.text.slice(0, 60)}"`) + .join(", ") + + (bad.length > 5 ? "…" : ""), + }; + } + if (items.length === 0) return { ok: false, error: "No videos listed." }; + const format: SourceVideoQuality | undefined = isSourceVideoQuality(input.format) ? input.format : undefined; + return persistVideosAction({ + items, + dryRun: input.dryRun, + ...(format ? { format } : {}), + ...(input.replace === "above-height" ? { replace: "above-height" as const } : {}), + }); +} diff --git a/editor/app/sites/components/FetchMissingEvidenceButton.tsx b/editor/app/sites/components/FetchMissingEvidenceButton.tsx @@ -1,9 +1,15 @@ "use client"; import Link from "next/link"; -import { useState, useTransition } from "react"; +import { useId, useState, useTransition } from "react"; import { Button } from "yt-dlp-transcript-common/components/ui/button"; import { + STORED_URL_HELP, + STORED_URL_LABEL, + STORED_URL_UI_MODE, + isStoredUrlPlatform, +} from "yt-dlp-transcript-common/lib/storedMediaUrl"; +import { fetchMissingArticleEvidenceAction, fetchMissingEvidenceAction, type FetchMissingEvidenceResult, @@ -15,16 +21,29 @@ import { // anything. It is not a streamed log because a run can start two jobs (YouTube // and Rumble side by side); each is linked, and its log is on /jobs. // `articles` instead of a site: the published articles' (release 26). +// +// "Cut from the stored media URL" (release 32 R6; fetch-windows `storedUrl`, +// lib/storedMediaUrl.ts) is offered once a preview or a run shows windows on a +// platform that has one (Odysee): the preview always counts them (a dry run asks +// with the mode, which starts nothing), and a refused group of such a platform +// offers it too. Off by default; ticked, the run asks "fallback". export function FetchMissingEvidenceButton(props: { siteId: string } | { articles: true }) { const [pending, start] = useTransition(); const [result, setResult] = useState<FetchMissingEvidenceResult | null>(null); + const [offer, setOffer] = useState(false); + const [stored, setStored] = useState(false); + const helpId = useId(); const run = (dryRun: boolean) => { start(async () => { - setResult( + // A preview counts the stored URLs whatever the box says; a run asks + // with them only when it is ticked. + const storedUrl = dryRun || (offer && stored) ? STORED_URL_UI_MODE : undefined; + const r = "siteId" in props - ? await fetchMissingEvidenceAction(props.siteId, { dryRun }) - : await fetchMissingArticleEvidenceAction({ dryRun }), - ); + ? await fetchMissingEvidenceAction(props.siteId, { dryRun, storedUrl }) + : await fetchMissingArticleEvidenceAction({ dryRun, storedUrl }); + setResult(r); + if (offersStoredUrl(r)) setOffer(true); }); }; return ( @@ -37,11 +56,38 @@ export function FetchMissingEvidenceButton(props: { siteId: string } | { article {pending ? "Working…" : "Fetch missing evidence"} </Button> </div> + {offer && ( + <label className="flex max-w-prose items-start gap-2 text-sm" data-stored-url-option=""> + <input + type="checkbox" + className="mt-1" + checked={stored} + onChange={(e) => setStored(e.target.checked)} + aria-describedby={helpId} + /> + <span> + {STORED_URL_LABEL} + <span id={helpId} className="block text-xs text-muted-foreground"> + {STORED_URL_HELP} + </span> + </span> + </label> + )} {result && <FetchSummary result={result} />} </div> ); } +// Windows on a stored-URL platform: a group with stored URLs, or a refused group +// of such a platform (the run was asked without the box). +function offersStoredUrl(r: FetchMissingEvidenceResult): boolean { + if (!r.ok) return false; + return ( + r.groups.some((g) => (g.storedUrlItems ?? 0) > 0) || + r.refused.some((x) => isStoredUrlPlatform(x.platform)) + ); +} + function FetchSummary({ result }: { result: FetchMissingEvidenceResult }) { if (!result.ok) { return ( @@ -62,6 +108,7 @@ function FetchSummary({ result }: { result: FetchMissingEvidenceResult }) { ? result.groups.map((g) => ( <p key={g.queueKey} className="text-muted-foreground"> {g.platform}: {g.items.length} window(s) on {g.queueKey} + {(g.storedUrlItems ?? 0) > 0 && <> · {g.storedUrlItems} with a stored media URL</>} </p> )) : result.jobs.map((j) => ( diff --git a/editor/e2e/owed-ui.spec.ts b/editor/e2e/owed-ui.spec.ts @@ -0,0 +1,116 @@ +import { test, expect } from "@playwright/test"; +import { mkdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { channelStage, resetData, testPaths } from "./helpers"; + +// Release 32 lane R6: the owed UI. "Cut from the stored media URL" offered on +// the Articles tab's Fetch missing evidence once a preview finds a window on +// an Odysee record that stores its CDN file (off by default); the channel's +// whole-channel media tools (attach from a local archive, playable copies) +// previewed from the Cleanup stage; and "Save these videos" on the Saved videos +// page previewed and armed. Synthetic records only; nothing is fetched. + +const SLUG = "test-transcribe"; // an Odysee channel (one-transcribe-channel) +const STORED = "v6stored01"; +// Eleven characters: the archive names a file by a YouTube-shaped id (lib/attachMediaPlan.ts). +const HELD = "v6held01abc"; +const page = (id: string) => `https://odysee.com/@example:1/synthetic-${id}:1`; +const channelDir = () => join(testPaths().transcriptsDir, "channels", SLUG); + +async function record(id: string, stored: boolean) { + const dir = join(channelDir(), "data", id); + await mkdir(dir, { recursive: true }); + await writeFile( + join(dir, "metadata.info.json"), + JSON.stringify({ + id, + title: `Synthetic ${id}`, + webpage_url: page(id), + duration: 600, + ...(stored ? { formats: [{ format_id: "original", url: `https://player.odycdn.com/v6/streams/${id}/f0.mp4`, protocol: "https", ext: "mp4" }] } : {}), + }), + ); +} + +test.beforeEach(async () => { + await resetData("one-transcribe-channel"); +}); + +test("Fetch missing evidence offers the stored media URL once a preview finds an Odysee window that has one", async ({ page: p }) => { + await record(STORED, true); + const reports = join(testPaths().transcriptsDir, "reports"); + await mkdir(join(reports, "fixture-stored"), { recursive: true }); + await writeFile( + join(reports, "fixture-stored", "report.json"), + JSON.stringify({ + format: "archilyzer-report", + version: 1, + id: "fixture-stored", + kind: "sweep", + title: "Fixture stored article", + sections: [{ id: "s1", title: "One", claims: [{ id: "k01", text: "It is said: \"a synthetic line\"", citations: ["c01"] }] }], + citations: { c01: { kind: "video", channel: SLUG, id: STORED, start: 10, end: 14, quote: "a synthetic line" } }, + }), + ); + await writeFile(join(reports, "index.json"), JSON.stringify({ published: ["fixture-stored"] })); + + await p.goto("/sites/articles"); + await expect(p.locator("[data-stored-url-option]")).toHaveCount(0); + await p.getByRole("button", { name: "Preview missing evidence" }).click(); + const summary = p.getByLabel("Missing evidence"); + await expect(summary).toContainText("odysee: 1 window(s) on clips:odysee · 1 with a stored media URL", { timeout: 30_000 }); + const option = p.locator("[data-stored-url-option]"); + await expect(option).toBeVisible(); + await expect(option).toContainText("Cut from the stored media URL"); + await expect(option).toContainText("Odysee only."); + await expect(option.getByRole("checkbox")).not.toBeChecked(); +}); + +test("the channel's media tools: attach from a local archive and playable copies, each previewed first", async ({ page: p }) => { + test.setTimeout(90_000); + await record(HELD, false); + // Inside the test corpus, which resetData clears. + const archive = join(testPaths().transcriptsDir, "r32r6-archive"); + await mkdir(archive, { recursive: true }); + await writeFile(join(archive, `Synthetic held recording [${HELD}].mp4`), "synthetic media bytes\n"); + + await p.goto(channelStage(SLUG, "cleanup")); + const tools = p.getByRole("group", { name: "channel media tools" }); + await tools.locator("summary").click(); + const attach = tools.getByLabel("attach media from a local archive"); + await expect(attach.getByRole("button", { name: "Attach", exact: true })).toBeDisabled(); + await attach.getByLabel("archive path").fill(archive); + await attach.getByRole("button", { name: "Preview attach" }).click(); + await expect(attach.getByRole("status", { name: "attach preview" })).toContainText("Would attach 1 held video.", { timeout: 30_000 }); + await expect(attach.getByRole("status", { name: "attach preview" }).getByRole("link", { name: /^job / })).toBeVisible(); + await expect(attach.getByRole("button", { name: "Attach", exact: true })).toBeEnabled(); + // Other settings than the preview's disarm it. + await attach.getByText("Replace files already saved").click(); + await expect(attach.getByRole("button", { name: "Attach", exact: true })).toBeDisabled(); + + const playable = tools.getByLabel("playable copies", { exact: true }); + await playable.getByRole("button", { name: "Preview playable copies" }).click(); + await expect(playable.getByRole("status", { name: "playable preview" })).toContainText("Would make 0 playable copies", { timeout: 30_000 }); + await expect(playable.getByRole("button", { name: "Make playable copies" })).toBeEnabled(); +}); + +test("Save these videos: a preview buckets the list and arms the run; a line that names no video is refused", async ({ page: p }) => { + await record(HELD, false); + await p.goto("/saved-videos"); + const box = p.getByRole("region", { name: "save these videos" }); + const save = box.getByRole("button", { name: "Save videos" }); + await box.getByLabel("videos to save").fill("just-one-word"); + await box.getByRole("button", { name: "Preview" }).click(); + await expect(box.getByRole("alert")).toContainText('line 1 "just-one-word"'); + await expect(save).toBeDisabled(); + + await box.getByLabel("videos to save").fill(`${SLUG}/${HELD}\nno-such-channel/x1`); + await box.getByRole("button", { name: "Preview" }).click(); + const preview = box.getByRole("status", { name: "save preview" }); + await expect(preview).toContainText("A run would download 1 video."); + await expect(preview.locator('[data-bucket="toFetch"]')).toContainText(`${SLUG}/${HELD}`); + await expect(preview.locator('[data-bucket="unknown"]')).toContainText("no-such-channel/x1"); + await expect(save).toBeEnabled(); + await box.getByLabel("quality to save").selectOption("video_720"); + await expect(save).toBeDisabled(); +}); diff --git a/mcp/src/fetchClip.test.ts b/mcp/src/fetchClip.test.ts @@ -823,3 +823,23 @@ test("full: a finished recording taller than maxHeight says why", async () => { assert.equal(r.isError, false); assert.match(r.text, /\nheight: 1080p — taller than the maxHeight 720 asked for; a whole recording is saved at 720p/); }); + +// ─── storedUrl (release 32 R6) ─── + +test("storedUrl: fallback and only ride on a window's target and its POST; never and absent send nothing", async () => { + const base = { channel: "chan", video: "vid", start: 10, end: 20, reason: "why" }; + const bad = validateFetchClipArgs({ ...base, storedUrl: "always" }); + assert.equal(bad.ok ? "" : bad.error, 'fetch_clip: storedUrl "always" must be one of "never", "fallback", "only"'); + for (const [given, sent] of [["fallback", "fallback"], ["only", "only"], ["never", undefined], [undefined, undefined]] as const) { + const { deps, calls } = editor( + seq({ status: 202, body: { cached: false, jobId: "j9", file: null, from: 0, to: 0 } }), + ); + await fetchClip({ ...windowRequest(given ? { storedUrl: given } : {}), waitSeconds: 0 } as FetchClipRequest, deps); + const body = calls[0].body as Record<string, unknown>; + assert.equal(body.storedUrl, sent, String(given)); + assert.equal("storedUrl" in body, sent !== undefined); + } + // A whole recording has no window to cut: the field is not carried. + const full = validateFetchClipArgs({ ...base, full: true, storedUrl: "only" }); + assert.ok(full.ok && "target" in full.request && !("storedUrl" in full.request.target)); +}); diff --git a/mcp/src/fetchClip.tool.test.ts b/mcp/src/fetchClip.tool.test.ts @@ -265,7 +265,7 @@ test("the tool is advertised with job-only calls allowed", async () => { assert.ok(tool, "fetch_clip is listed"); assert.deepEqual(tool.inputSchema.required ?? [], []); const props = Object.keys(tool.inputSchema.properties ?? {}); - for (const p of ["source", "channel", "video", "start", "end", "pad", "full", "maxHeight", "reason", "report", "wait_seconds", "job"]) { + for (const p of ["source", "channel", "video", "start", "end", "pad", "full", "maxHeight", "storedUrl", "reason", "report", "wait_seconds", "job"]) { assert.ok(props.includes(p), `has ${p}`); } assert.match(tool.description ?? "", /NEVER run yt-dlp/); diff --git a/mcp/src/fetchClip.ts b/mcp/src/fetchClip.ts @@ -4,6 +4,11 @@ import { MIN_FETCH_MAX_HEIGHT, isFetchMaxHeight, } from "yt-dlp-transcript-common/lib/clipWindow"; +import { + STORED_URL_MODES, + isStoredUrlMode, + type StoredUrlMode, +} from "yt-dlp-transcript-common/lib/storedMediaUrl"; // ─── fetch_clip: ask the local Archilyzer editor for a clip's media ─── // @@ -160,6 +165,9 @@ export type ClipTarget = to: number; pad: number; maxHeight?: number; + // Cut from the record's stored media URL (release 32 R6; the editor's + // fetch-window `storedUrl`): "fallback" | "only". Absent is "never". + storedUrl?: Exclude<StoredUrlMode, "never">; } | { kind: "full"; channel: string; video: string; maxHeight?: number }; @@ -258,7 +266,17 @@ export function validateFetchClipArgs( } const w = planWindow({ video, start: times.start, end: times.end, pad }); if ("error" in w) return { ok: false, error: w.error }; - target = { kind: "window", channel, video, from: w.from, to: w.to, pad, ...capped }; + const rawStored = args.storedUrl; + if (rawStored !== undefined && rawStored !== null && !isStoredUrlMode(rawStored)) { + return { + ok: false, + error: + `fetch_clip: storedUrl "${String(rawStored)}" must be one of ` + + STORED_URL_MODES.map((m) => `"${m}"`).join(", "), + }; + } + const stored = isStoredUrlMode(rawStored) && rawStored !== "never" ? { storedUrl: rawStored } : {}; + target = { kind: "window", channel, video, from: w.from, to: w.to, pad, ...capped, ...stored }; } const reason = trimmed(args.reason); @@ -530,6 +548,7 @@ export async function fetchClip( to: target.to, pad: target.pad, ...capped, + ...(target.storedUrl ? { storedUrl: target.storedUrl } : {}), ...provenance, }; const res = await call(`${editor.url}/api/media/fetch-window`, { diff --git a/mcp/src/server.ts b/mcp/src/server.ts @@ -882,6 +882,17 @@ export const TOOLS: Tool[] = [ "file already on disk is returned as it is, and the answer gives " + "its height, so a taller one can be seen.", }, + storedUrl: { + type: "string", + enum: ["never", "fallback", "only"], + description: + "Optional, a window only: cut it from the media file address the " + + "record stored when it was archived (Odysee only), the way the " + + "platform's own player reads it. \"fallback\": the page first, and " + + "the stored file when the platform refuses the lookup (a rate limit, " + + "a hold or a cooldown). \"only\": no page request. Default " + + "\"never\". A record with no stored address is fetched as usual.", + }, reason: { type: "string", description: diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -10086,3 +10086,34 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri `cut from the stored media URL (<host>) — <platform> lookup rate-limited|held` or `(asked: only)`. - Not wired: the single `/api/media/fetch-window` route and the MCP's `fetch_clip` (which posts to that route, not to fetch-windows), and any UI toggle. + +## Release 32 lane R6: the owed UI (verified 2026-10-17, branch `r32/owed-ui`) + +- **The stored media URL in the UI.** `lib/storedMediaUrl.ts` holds the UI's words: `STORED_URL_LABEL`, + `STORED_URL_HELP`, and `STORED_URL_UI_MODE = "fallback"` — every surface's tick asks `fallback`; `only` stays for the + CLI and the MCP. Offered only where it can do something: the editor's Fetch missing evidence once a preview (which + always asks with the mode — a dry run starts nothing — so `storedUrlItems` is counted) or a refused run shows a + stored-URL platform's windows; umtool's surfaces when `GET /api/cited/stored?(channel&video | project&clip)` answers + `{stored: true}` (`lib/clips/stored.ts`: `storedMediaUrl()` over CHANNELS_DIR; a project clip's record is the clip's + `channel` else `provenance.channelSlug`, and `video` — a timeline clip's or a ledger claim's, as fetch-via-editor.mjs). + CutTab counts the pending clips with one (`storedUrlClips` on FetchUnfetchedButton). +- **The single window takes it too.** `POST /api/media/fetch-window {storedUrl}` (400 on anything but the three modes) + → `fetchWindowAction({storedUrl})`: `only` + a stored URL → no page request; a held or cooling platform does not + refuse a window with one (`why` held | rate-limited); `fallback` + a page `FetchWindowError` of class `rate_limit` → + the clip gap (`CLIP_WINDOW_MIN_GAP_SECONDS`, or `E2E_CLIP_WINDOW_GAP_MS`) → the stored-URL cut. Without a stored URL + the window goes the usual way, refusals included. `spec.params.storedUrl` keeps the mode for Retry. MCP `fetch_clip` + takes `storedUrl` (`fallback` | `only`; a window only — a whole recording drops it). umtool: `/api/cited/fetch` and + `/api/research/fetch` pass it as fetch_clip's field; `/api/report/fetch {storedUrl}` → `editorFetchSteps({…, + storedUrl})` → `fetch-via-editor.mjs --stored-url <mode>` (both its single and `--all` bodies; refused with `--full`; + the route refuses it with a whole recording or `UMTOOL_LOCAL_FETCH=1`). +- **Channel-wide media tools** (`app/channels/[slug]/components/ChannelMediaTools.tsx`, the Cleanup stage): the + existing `attachMediaAction(slug, {source, match?, createRecords?, replace?, dryRun?})` and + `preparePlayableAction(slug, {trackers?, root?, dryRun?})`, no ids — the whole channel. Both jobs' logs end with + `summary: {json}` (attachMedia's `summaryOf`, preparePlayable's own); `lib/mediaToolsWords.ts` reads it into + sentences. attach-media matches a file to a record only by an ELEVEN-character YouTube-shaped id (folder `(<id>)`, + file `<id>.ext`, `-<id>.ext` or `[<id>].ext`). +- **Save these videos** (`/saved-videos`, `persistListAction.ts`): `lib/videoList.ts` reads one video per line + (`slug/id`, `slug id`, `slug,id`, or any URL containing `/channels/<slug>/videos/<id>`; `#` and blank lines skipped, + repeats once, a bad line refuses the whole list with its line number) → `persistVideosAction` exactly as the ops + route calls it. + diff --git a/plans/release-32/owed-ui.md b/plans/release-32/owed-ui.md @@ -0,0 +1,94 @@ +# Release 32 lane R6: the owed UI (as shipped) + +Branch `r32/owed-ui` from `main` `23ea764b`. Brief: `r32r6-brief.md` (the plan of record for this lane). FACTS: +"Release 32 lane R6: the owed UI". + +## What and why + +The operator's rule for the release: everything a model or the CLI can do, a person can do in the UI. Three items +were owed after R5 and the release's smoke. + +- **"Cut from the stored media URL" wherever a window is fetched** (R5 shipped `fetch-windows {storedUrl}` with no UI). + One label, one help line and one mode for every surface (`lib/storedMediaUrl.ts`: `STORED_URL_LABEL`, + `STORED_URL_HELP`, `STORED_URL_UI_MODE = "fallback"`). Off by default, offered only where it can do something: + - the editor's **Fetch missing evidence** (Reports and Articles tabs): once a preview — which now always counts the + stored URLs, "odysee: N window(s) on clips:odysee · M with a stored media URL" — or a refused run shows windows on + a stored-URL platform; + - umtool's **Fetch clip** (`CitedClip`: the article evidence panel, the drafts deck, the audition deck), the + research reader's Fetch clip, the clip bench's fetch-more row, the claim bench's fetch, and **Fetch N unfetched + clips** on the Cut tab — each when the record stores one (`GET /api/cited/stored`, `lib/clips/stored.ts`). + - `POST /api/media/fetch-window` takes `storedUrl` (the batch's rule for one window; fallback waits the clip gap + after the page's 429), and the MCP's `fetch_clip` passes it through. `instructions.ts` lists no tool fields, so + it is unchanged; the tool's schema describes the field. +- **The Inbox at ~380 px**: a row's four fixed columns (56 + 190 + 112 px and gaps) left the title no width. Under `sm` + the row now wraps — the title and why on the first row (two lines each at most), the count, the action and + Park/Mute on the second; from `sm` up, the grid as before. Shots: `$T/shots/r32r6-inbox-{380,520}-{before,after}.png` + and `r32r6-inbox-1366-after.png` (the e2e fixture's inbox). +- **The bulk CLI-only rows get buttons where their object lives**: + - the channel's Cleanup stage, **Media for the whole channel**: **Attach media from a local archive** (`media + attach <slug> <source>` — only names matching, create records, replace) and **Playable copies** (`media playable + <slug>` — trackers, folder). Both preview first (the job's dry run), the run is armed by a preview of the same + settings, and the job's `summary:` line is said in plain words with the job linked. + - **Save these videos** on `/saved-videos` (`persist-videos`): one video per line (`slug/id` or a video page + link), quality, replace a taller one; Preview answers with the plan's buckets, Save starts one job per channel + and links each. + +| Commit | What | +| --- | --- | +| `632ec204` | editor: the option on Fetch missing evidence; `storedUrl` on the single fetch-window route (+ Retry); the UI's words in common | +| `0e98e714` | mcp: `fetch_clip` takes `storedUrl` | +| `93c9ee69` | umtool: the option beside every window fetch; `/api/cited/stored`; `fetch-via-editor.mjs --stored-url` | +| `c7709fb0` | umtool: the Inbox's rows wrap under `sm`; `e2e/stored-url.spec.ts` and its fixture | +| `f3b26188` | editor: channel-wide attach and playable copies, Save these videos | +| (this commit) | `e2e/owed-ui.spec.ts`, this record, FACTS, CHANGELOG | + +## Gates (from the worktree root, every heavy step through the shared lock) + +- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean. +- common: 4508 (4507 + 1 skipped) before and after (only constants added). +- editor unit: 331 → 340, all pass (`api/media/fetch-window/route.storedUrl.test.ts` 5, + `saved-videos/lib/videoList.test.ts` 2, `channels/[slug]/lib/mediaToolsWords.test.ts` 2). +- mcp: 377 → 378 (`fetchClip.test.ts` +1; the tool-schema test lists `storedUrl`). +- umtool: 42 → 45 (`lib/clips/stored.test.ts` 2, `cited.test.ts` +1). +- test:scripts: 1052 → 1053 (1049 + 4 skipped; `fetch-via-editor.test.mjs` +1). +- `docs env --check`, `docs files --check`, `docs cli --check`, `settings example --check`: clean (no CLI row, ops + key, env or settings key changed). +- e2e, umtool: `stored-url.spec.ts` 2/2 (with the before shots, 4/4 in 14.8 s); `inbox.spec.ts` 13/13 with the after + shots (15/15 in 22.4 s); on the final tree `stored-url.spec.ts` 2/2 with the 380/520/1366 shots (5/5 in 14.7 s). + The shots spec was a scratch file, not committed. +- e2e, editor: `owed-ui.spec.ts` — run 1: 2 passed, 1 failed (the attach preview found no id: the spec's id was not + the eleven characters attach-media matches, and its archive was written outside the test corpus — both fixed in + the spec); run 2: **3/3 in 10.8 s**. + +## Decisions + +- **A person's tick asks `fallback`, never `only`.** Fallback asks the page first and uses the stored file only when + the platform refuses (or is held or cooling, when it goes straight to the file), so a tick on a platform that is + answering changes nothing. `only` stays for the CLI and the MCP. +- **Offered per record, not per platform.** umtool asks whether the record stores a trusted URL (which implies an + allowlisted platform); the editor's batch offers it when the preview counted windows with one, or a refused group + is on an allowlisted platform. A Preview always asks with the mode — a dry run starts nothing — so R5's + "storedUrlItems only when a mode was asked" contract stands. +- **The single window's fallback waits `CLIP_WINDOW_MIN_GAP_SECONDS`** (30 s; `E2E_CLIP_WINDOW_GAP_MS` in tests) + between the page's 429 and the stored-URL cut, the batch's least clip gap. The single route has no gap state of + its own; this is the "one stream, real gaps" rule for its one retry. +- **The research reader got the option too** (not named in the brief, but it fetches windows): only when the cited + record is in the editor's own corpus and stores a URL. +- **Bulk tools live with the store.** Channel-wide attach and playable copies are on the Cleanup stage beside + "Retention & persistence" (both write into, or beside, the saved-video store; the Download stage is hidden for a + channel with no URL, which is exactly the channel a local archive serves). The cross-channel persist list is on + `/saved-videos`. + +## Not done + +- No new video-page window fetch in the editor (there is none to put the option on; the batch and the single route + cover the paths). +- The full editor and umtool suites (the orchestrator's). + +## Live after merge (the orchestrator) + +No data step is owed. Rebuild and restart both apps through their units; then smoke: `/sites/articles` → Preview +missing evidence (an Odysee window with a stored URL shows the count and the option); an umtool article's evidence +for an Odysee citation not on disk shows the option under Fetch clip; `/saved-videos` → Save these videos → Preview +with one `slug/id`; a channel's Cleanup stage → Media for the whole channel → Preview playable copies; the Inbox at a +phone width. diff --git a/umtool/app/api/cited/fetch/route.ts b/umtool/app/api/cited/fetch/route.ts @@ -1,10 +1,11 @@ +import { isStoredUrlMode } from "yt-dlp-transcript-common/lib/storedMediaUrl"; import { fetchCitedClip, targetOf } from "@/lib/clips/cited"; import { SourceError } from "@/lib/research/sources"; import { fail, ok } from "../../research/_respond"; export const dynamic = "force-dynamic"; -// POST { channel, video, from, to, project?, clip?, reason, report? } +// POST { channel, video, from, to, project?, clip?, reason, report?, storedUrl? } // | { job, channel?, video?, from?, to?, … } (a poll) // -> { state: "ready", cached, play } | { state: "queued", job, status } // | { state: "failed", message, detail?, job? } @@ -21,7 +22,10 @@ export async function POST(request: Request) { if (!target) throw new SourceError("channel, video, from and to are required"); const reason = String(b.reason ?? "").trim().slice(0, 400) || "umtool: play the cited span"; const report = typeof b.report === "string" && b.report.trim() ? b.report.trim() : undefined; - return ok(await fetchCitedClip({ target, reason, ...(report ? { report } : {}) })); + // "Cut from the stored media URL" (release 32 R6): the editor's mode, as given. + if (b.storedUrl !== undefined && !isStoredUrlMode(b.storedUrl)) throw new SourceError('storedUrl must be "never", "fallback" or "only"'); + const storedUrl = isStoredUrlMode(b.storedUrl) && b.storedUrl !== "never" ? b.storedUrl : undefined; + return ok(await fetchCitedClip({ target, reason, ...(report ? { report } : {}), ...(storedUrl ? { storedUrl } : {}) })); } catch (e) { return fail(e); } diff --git a/umtool/app/api/cited/stored/route.ts b/umtool/app/api/cited/stored/route.ts @@ -0,0 +1,19 @@ +import { storedUrlFor } from "@/lib/clips/stored"; +import { fail, ok } from "../../research/_respond"; + +export const dynamic = "force-dynamic"; + +// GET ?project&clip | ?channel&video -> { stored, host?, platform? } +// +// Whether the span's record stores a media file address the editor can cut a +// window from (release 32 R6, lib/clips/stored.ts). Every umtool fetch surface +// asks before it offers "Cut from the stored media URL". +export async function GET(request: Request) { + try { + const u = new URL(request.url); + const g = (k: string) => u.searchParams.get(k)?.trim() || undefined; + return ok(await storedUrlFor({ project: g("project"), clip: g("clip"), channel: g("channel"), video: g("video") })); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/report/fetch/route.ts b/umtool/app/api/report/fetch/route.ts @@ -51,6 +51,22 @@ export async function POST(request: Request) { // nowhere to put a full source that anything else would find. const wantFull = body.full === true; + // CUT FROM THE STORED MEDIA URL (release 32 R6): the editor's `storedUrl`, + // for a window asked of the editor ("fallback" | "only"). The local fetch and + // a whole recording have no such thing; asking for one with them is refused + // rather than quietly ignored. + const storedUrl = + body.storedUrl === "fallback" || body.storedUrl === "only" ? body.storedUrl : null; + if (body.storedUrl !== undefined && body.storedUrl !== null && body.storedUrl !== "never" && !storedUrl) { + return Response.json({ error: 'storedUrl must be "never", "fallback" or "only"' }, { status: 400 }); + } + if (storedUrl && (wantFull || localFetch())) { + return Response.json( + { error: wantFull ? "the stored media URL cuts a window, not the whole recording" : "the stored media URL is the editor's; this umtool fetches locally" }, + { status: 400 }, + ); + } + const r = await resolveClip(projectId, clipId); if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); @@ -125,7 +141,7 @@ export async function POST(request: Request) { ? editorFullSourceSteps(r.project, clipId, { manifest: r.manifest }) : localFetch() ? fetchSteps(r.project, clipId, { padBefore, padAfter }) - : editorFetchSteps(r.project, clipId, { padBefore, padAfter }); + : editorFetchSteps(r.project, clipId, { padBefore, padAfter, storedUrl }); const job = startJob( wantFull ? `fetch whole source ${projectId}/${clipId}` diff --git a/umtool/app/api/research/fetch/route.ts b/umtool/app/api/research/fetch/route.ts @@ -4,7 +4,7 @@ import { fail, ok } from "../_respond"; export const dynamic = "force-dynamic"; -// POST { source, channel, video, start, end, reason } | { job } +// POST { source, channel, video, start, end, reason, storedUrl? } | { job } // -> { state: "ready", file, from, to, cached } | { state: "queued", job, status } // | { state: "failed", message, job? } // @@ -26,6 +26,8 @@ export async function POST(request: Request) { start, end, reason: String(b.reason ?? "").slice(0, 400), + // "Cut from the stored media URL" (release 32 R6): fetch_clip's field. + ...(b.storedUrl === "fallback" || b.storedUrl === "only" ? { storedUrl: b.storedUrl } : {}), }), ); } catch (e) { diff --git a/umtool/components/clips/CitedClip.tsx b/umtool/components/clips/CitedClip.tsx @@ -6,6 +6,8 @@ import { buttonVariants } from "@/components/ui/button"; import { citedKey, type CitedFetchAnswer, type CitedPlay, type CitedTarget } from "@/lib/clips/types"; import { spanClock } from "@/lib/clips/words"; import { cn } from "@/lib/utils"; +import { STORED_URL_UI_MODE } from "yt-dlp-transcript-common/lib/storedMediaUrl"; +import StoredUrlOption from "./StoredUrlOption"; // --------------------------------------------------------------------------- // THE CITED CLIP (release 32 R1): the seconds a citation names, played so a @@ -19,7 +21,9 @@ import { cn } from "@/lib/utils"; // Fetch clip when nothing on disk does: one press asks the editor // (/api/cited/fetch -> the editor's fetch-window, as the MCP's // fetch_clip asks), shows its progress, plays when it lands; -// a failure is said plainly (a rate limit, corrupt audio) +// a failure is said plainly (a rate limit, corrupt audio); +// beside it, "Cut from the stored media URL" when the record +// stores one (release 32 R6, StoredUrlOption) // // Two faces: `panel` (native controls, the evidence panel and the reader) and // `card` (the audition deck's: no chrome, tap replays, a span-only scrubber). @@ -99,6 +103,7 @@ const CitedClip = forwardRef< const [line, setLine] = useState<string | undefined>(givenLine); const [lookError, setLookError] = useState<string | null>(null); const [fetching, setFetching] = useState<CitedFetchAnswer | { state: "asking" } | null>(null); + const [fromStored, setFromStored] = useState(false); const [now, setNow] = useState(target.from); const [playing, setPlaying] = useState(false); const media = useRef<HTMLMediaElement | null>(null); @@ -181,7 +186,12 @@ const CitedClip = forwardRef< const runFetch = async () => { setFetching({ state: "asking" }); - const body = { ...target, reason: reason ?? "umtool: play the cited span", ...(report ? { report } : {}) }; + const body = { + ...target, + reason: reason ?? "umtool: play the cited span", + ...(report ? { report } : {}), + ...(fromStored ? { storedUrl: STORED_URL_UI_MODE } : {}), + }; try { let r = await fetch("/api/cited/fetch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); let a = (await r.json()) as CitedFetchAnswer & { error?: string }; @@ -339,6 +349,13 @@ const CitedClip = forwardRef< > {fetching && (fetching.state === "asking" || fetching.state === "queued") ? "Fetching…" : "Fetch clip"} </button> + <StoredUrlOption + query={{ channel: target.channel, video: target.video }} + checked={fromStored} + onChange={setFromStored} + disabled={!!fetching && (fetching.state === "asking" || fetching.state === "queued")} + compact={card} + /> {status} {!card && line && ( <details className="text-[11px] text-muted"> diff --git a/umtool/components/clips/StoredUrlOption.tsx b/umtool/components/clips/StoredUrlOption.tsx @@ -0,0 +1,103 @@ +"use client"; + +import { useEffect, useId, useState } from "react"; +import { STORED_URL_HELP, STORED_URL_LABEL } from "yt-dlp-transcript-common/lib/storedMediaUrl"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// "Cut from the stored media URL" (release 32 R6), umtool's half: a checkbox +// beside a fetch button, shown only when the span's record stores a media file +// address the editor can cut from (GET /api/cited/stored — Odysee's CDN file). +// Off by default; ticked, the fetch asks the editor with STORED_URL_UI_MODE +// ("fallback": the page first, the stored file when the platform refuses). +// --------------------------------------------------------------------------- + +export type StoredUrlQuery = { project: string; clip: string } | { channel: string; video: string }; + +const answers = new Map<string, Promise<boolean>>(); + +function keyOf(q: StoredUrlQuery): string { + return "project" in q ? `p|${q.project}|${q.clip}` : `c|${q.channel}|${q.video}`; +} + +function lookup(q: StoredUrlQuery): Promise<boolean> { + const key = keyOf(q); + let p = answers.get(key); + if (!p) { + p = fetch(`/api/cited/stored?${new URLSearchParams(q)}`, { cache: "no-store" }) + .then((r) => (r.ok ? r.json() : { stored: false })) + .then((j: { stored?: boolean }) => j.stored === true) + .catch(() => false); + answers.set(key, p); + } + return p; +} + +/** Whether the option is offered for `q` (null while asking, or with no query). */ +export function useStoredUrlOffered(q: StoredUrlQuery | null): boolean { + const [offered, setOffered] = useState(false); + const key = q ? keyOf(q) : ""; + useEffect(() => { + if (!q) return; + let live = true; + void lookup(q).then((v) => live && setOffered(v)); + return () => { + live = false; + }; + // `q` is named by its key. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key]); + return offered; +} + +/** The checkbox itself, for a caller that already knows it is offered. */ +export function StoredUrlCheckbox({ + checked, + onChange, + disabled, + compact, + className, +}: { + checked: boolean; + onChange: (v: boolean) => void; + disabled?: boolean; + /** One line; the help on hover only. */ + compact?: boolean; + className?: string; +}) { + const helpId = useId(); + return ( + <label + data-stored-url-option="" + title={STORED_URL_HELP} + className={cn("flex max-w-prose cursor-pointer items-start gap-1.5 text-left text-[12px] text-text-2", className)} + > + <input + type="checkbox" + className="mt-[3px] accent-[var(--signal)]" + checked={checked} + disabled={disabled} + onChange={(e) => onChange(e.target.checked)} + aria-describedby={compact ? undefined : helpId} + /> + <span> + {STORED_URL_LABEL} + {!compact && ( + <span id={helpId} className="block text-[11px] text-muted"> + {STORED_URL_HELP} + </span> + )} + </span> + </label> + ); +} + +/** Asks whether it is offered, and renders nothing when it is not. */ +export default function StoredUrlOption({ + query, + ...rest +}: { query: StoredUrlQuery | null } & Parameters<typeof StoredUrlCheckbox>[0]) { + const offered = useStoredUrlOffered(query); + if (!offered) return null; + return <StoredUrlCheckbox {...rest} />; +} diff --git a/umtool/components/inbox/InboxList.tsx b/umtool/components/inbox/InboxList.tsx @@ -115,18 +115,22 @@ function Card({ card: c }: { card: InboxCard }) { data-piece={c.piece ?? undefined} data-severity={c.severity} data-muted={c.muted ? "" : undefined} - className="grid grid-cols-[minmax(0,1fr)_56px_190px_112px] items-center gap-x-3.5" + // NARROW FIRST (release 32 R6): under `sm` the line wraps — the title and + // why take the whole first row (two lines each at most), and the count, + // the action and Park/Mute share the second. The four columns from `sm` + // up: at ~380 px their fixed 400 px left the title no room at all. + className="flex flex-wrap items-center gap-x-3.5 gap-y-1.5 sm:grid sm:grid-cols-[minmax(0,1fr)_56px_190px_112px] sm:gap-y-0" > - <div className="min-w-0"> - <b className="block truncate font-medium text-inherit" data-card-title=""> + <div className="min-w-0 basis-full sm:basis-auto"> + <b className="line-clamp-2 font-medium text-inherit sm:block sm:truncate" data-card-title=""> {c.title} <span className="font-normal text-muted-2">·</span> {c.what} </b> - <small className="block truncate text-[12px] text-muted-2">{c.why}</small> + <small className="line-clamp-2 text-[12px] text-muted-2 sm:block sm:truncate">{c.why}</small> </div> - <span className="text-right font-mono text-[12.5px] font-medium text-meter" data-count={c.count}> + <span className="font-mono text-[12.5px] font-medium text-meter sm:text-right" data-count={c.count}> {c.count} </span> - <span className="justify-self-end"> + <span className="sm:justify-self-end"> {c.muted && c.piece ? ( <MuteButton piece={c.piece} kind={c.kind} title={c.title} muted variant="outline" size="md" className="lit-go" /> ) : parked && c.piece ? ( @@ -139,7 +143,7 @@ function Card({ card: c }: { card: InboxCard }) { </Link> )} </span> - <LitActions className="gap-0.5"> + <LitActions className="ml-auto gap-0.5 sm:ml-0"> {!parked && !c.muted && c.piece && ( <> <LifecycleButton piece={c.piece} title={c.title} from={c.lifecycle} to="parked" label="Park" /> diff --git a/umtool/components/projects/ClaimBench.tsx b/umtool/components/projects/ClaimBench.tsx @@ -3,6 +3,8 @@ import Link from "next/link"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; +import { StoredUrlCheckbox, useStoredUrlOffered } from "@/components/clips/StoredUrlOption"; +import { STORED_URL_UI_MODE } from "yt-dlp-transcript-common/lib/storedMediaUrl"; import { ReaderPane } from "@/components/ui/reader-pane"; import { citationText } from "@/lib/research/facets.mjs"; import { BenchBody, VerdictBar } from "./bench/BenchShell"; @@ -249,13 +251,22 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) { setNote(gaps.length ? `saved — still missing ${gaps.join(", ")}` : "saved — adjudicated"); }, [data.project, claim.id, token, scope, confidence, population, valueKind, basis, flagText, roles]); + // "Cut from the stored media URL" (release 32 R6): offered when the claim's + // record stores one (Odysee). + const storedOffered = useStoredUrlOffered(claim.video ? { project: data.project, clip: claim.id } : null); + const [fromStored, setFromStored] = useState(false); const fetchWindow = useCallback(async () => { setFetching(true); setNote(null); const r = await fetch("/api/report/fetch", { method: "POST", headers: { "content-type": "application/json" }, - body: JSON.stringify({ project: data.project, clip: claim.id, pad: data.pad + 5 }), + body: JSON.stringify({ + project: data.project, + clip: claim.id, + pad: data.pad + 5, + ...(storedOffered && fromStored ? { storedUrl: STORED_URL_UI_MODE } : {}), + }), }); const j = (await r.json()) as Record<string, unknown>; if (!r.ok) { @@ -273,7 +284,7 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) { } setFetching(false); window.location.reload(); - }, [data.project, claim.id, data.pad]); + }, [data.project, claim.id, data.pad, storedOffered, fromStored]); // ---- the bench shell's verdict bar and reader (P4b) ------------------------ const missing = [ @@ -393,6 +404,9 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) { > {fetching ? "fetching…" : `fetch ±${data.pad}s`} </button> + {storedOffered && ( + <StoredUrlCheckbox checked={fromStored} onChange={setFromStored} disabled={fetching} compact /> + )} </div> )} diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -9,6 +9,8 @@ import { useRouter } from "next/navigation"; import Waveform, { type Peaks } from "@/components/Waveform"; import { badgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; +import { StoredUrlCheckbox, useStoredUrlOffered } from "@/components/clips/StoredUrlOption"; +import { STORED_URL_UI_MODE } from "yt-dlp-transcript-common/lib/storedMediaUrl"; import { ReaderPane, paperButtonVariants } from "@/components/ui/reader-pane"; import { citationText } from "@/lib/research/facets.mjs"; import { BenchBody, VerdictBar } from "./bench/BenchShell"; @@ -1511,6 +1513,11 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { // its pad from what is on disk RIGHT NOW and says which number it will ask // for; the route refuses a window it can already serve; and a job that ran // still has to show a wider file before this claims anything arrived. + // "Cut from the stored media URL" (release 32 R6): offered when the clip's + // record stores one (Odysee); every window fetch below asks with it when ticked. + const storedOffered = useStoredUrlOffered({ project: data.project, clip: clip.id }); + const [fromStored, setFromStored] = useState(false); + const storedAsk = storedOffered && fromStored ? { storedUrl: STORED_URL_UI_MODE } : {}; const fetchMore = useCallback( async (pads: { padBefore: number; padAfter: number }) => { const had = windows[0] ?? null; @@ -1524,6 +1531,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { clip: clip.id, padBefore: round2(pads.padBefore), padAfter: round2(pads.padAfter), + ...storedAsk, }), }); if (!r.ok) { @@ -1563,7 +1571,9 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { setBusy(null); setNote("the fetch is still running; reload to pick it up"); }, - [data.project, clip.id, refresh, windows], + // `storedAsk` is named by what it is made of. + // eslint-disable-next-line react-hooks/exhaustive-deps + [data.project, clip.id, refresh, windows, storedOffered, fromStored], ); // ---- the whole recording -------------------------------------------------- @@ -2554,6 +2564,9 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { > Fetch whole source via editor </button> + {storedOffered && ( + <StoredUrlCheckbox checked={fromStored} onChange={setFromStored} disabled={!!busy} compact /> + )} </div> )} diff --git a/umtool/components/projects/FetchUnfetchedButton.tsx b/umtool/components/projects/FetchUnfetchedButton.tsx @@ -2,6 +2,8 @@ import { useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; +import { StoredUrlCheckbox } from "@/components/clips/StoredUrlOption"; +import { STORED_URL_UI_MODE } from "yt-dlp-transcript-common/lib/storedMediaUrl"; // --------------------------------------------------------------------------- // "Fetch the clips nobody can watch yet." @@ -19,6 +21,10 @@ import { buttonVariants } from "@/components/ui/button"; // // STOP ABANDONS, IT DOES NOT KILL. The in-flight fetch is already paid for and // its bytes are worth keeping; what Stop means is "start no more". +// +// "Cut from the stored media URL" (release 32 R6) is offered when some of the +// clips' records store one (`storedUrlClips`, counted on the server); ticked, +// every fetch asks with it — a clip with none is fetched as usual. // --------------------------------------------------------------------------- type Pending = { id: string; padBefore: number; padAfter: number }; @@ -28,13 +34,17 @@ type JobView = { id: string; state: "running" | "done" | "failed"; error: string export default function FetchUnfetchedButton({ project, pending, + storedUrlClips = 0, }: { project: string; // The clips that need judgement and have nothing cached holding them, in // walk order. Computed on the server, where `fetched` already is. pending: Pending[]; + // How many of them store a media URL the editor can cut from. + storedUrlClips?: number; }) { const [running, setRunning] = useState(false); + const [fromStored, setFromStored] = useState(false); const [done, setDone] = useState(0); const [msg, setMsg] = useState<string | null>(null); const [failed, setFailed] = useState(false); @@ -88,6 +98,7 @@ export default function FetchUnfetchedButton({ clip: clip.id, padBefore: clip.padBefore, padAfter: clip.padAfter, + ...(storedUrlClips > 0 && fromStored ? { storedUrl: STORED_URL_UI_MODE } : {}), }), }); const body = (await res.json().catch(() => ({}))) as { @@ -174,6 +185,14 @@ export default function FetchUnfetchedButton({ stop </button> )} + {storedUrlClips > 0 && ( + <StoredUrlCheckbox + checked={fromStored} + onChange={setFromStored} + disabled={running} + className="basis-full" + /> + )} {msg && ( <span data-fetch-unfetched-msg="" diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -10,6 +10,7 @@ import { listTakes } from "@/lib/report/takes.mjs"; import { buttonVariants } from "@/components/ui/button"; import { clipBenchHref, mixHref as toolsMixHref, projectHref, takesHref } from "@/lib/hrefs"; import FetchUnfetchedButton from "../FetchUnfetchedButton"; +import { clipRecord, storedUrlOf } from "@/lib/clips/stored"; import { RowControls, RowNotes, TimelineList } from "../TimelineEditor"; import { Pill, TONE, hms, type ReportTabProps } from "./shared"; @@ -39,6 +40,16 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor // What the walk is waiting on: the same clips the rows below mark "not // fetched yet". const pendingFetch = unfetchedNeedingJudgement(clips) as string[]; + // How many of them store a media URL the editor can cut from (release 32 R6): + // the button offers "Cut from the stored media URL" only when some do. + const storedPending = ( + await Promise.all( + pendingFetch.map(async (id) => { + const rec = clipRecord(m, id); + return rec ? (await storedUrlOf(rec.channel, rec.video)).stored : false; + }), + ) + ).filter(Boolean).length; const walkStart = (readiness.readyIds[0] as string | undefined) ?? clips[0]?.id; const showAll = search.all === "1"; const takes = await listTakes(project.dir); @@ -140,6 +151,7 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor <FetchUnfetchedButton project={project.id} pending={pendingFetch.map((id) => ({ id, padBefore: 20, padAfter: 20 }))} + storedUrlClips={storedPending} /> </div> )} diff --git a/umtool/components/research/Reader.tsx b/umtool/components/research/Reader.tsx @@ -1,5 +1,6 @@ "use client"; +import StoredUrlOption from "@/components/clips/StoredUrlOption"; import Link from "next/link"; import { useEffect, useRef, useState } from "react"; import { VIDEO_STATE_LABELS, type VideoState } from "yt-dlp-transcript-common/lib/availability"; @@ -68,6 +69,8 @@ export default function Reader({ onCopy, fetchState, onFetch, + fromStored = false, + onFromStored, onPin, pinning, pinned, @@ -88,6 +91,9 @@ export default function Reader({ onCopy: () => void; fetchState: FetchAnswer | { state: "asking" } | null; onFetch: () => void; + /** "Cut from the stored media URL" (release 32 R6): offered when the record stores one. */ + fromStored?: boolean; + onFromStored?: (v: boolean) => void; }) { const [playing, setPlaying] = useState<LocalMedia | null>(null); const video = useRef<HTMLVideoElement>(null); @@ -191,6 +197,15 @@ export default function Reader({ {fetching ? "Fetching…" : "Fetch clip"} </button> )} + {(!file || file.kind !== "window") && onFromStored && ( + <StoredUrlOption + query={{ channel: win.channelSlug, video: win.videoId }} + checked={fromStored} + onChange={onFromStored} + disabled={!!fetching} + compact + /> + )} <span className="ml-auto inline-flex items-center gap-1"> <button type="button" aria-label="Narrower window" className={paperButtonVariants()} disabled={span <= 15} onClick={() => onSpan(Math.max(15, Math.round(span / 2)))}> − diff --git a/umtool/components/research/ResearchView.tsx b/umtool/components/research/ResearchView.tsx @@ -1,5 +1,6 @@ "use client"; +import { STORED_URL_UI_MODE } from "yt-dlp-transcript-common/lib/storedMediaUrl"; import Link from "next/link"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; @@ -115,6 +116,7 @@ export default function ResearchView({ const [winLoading, setWinLoading] = useState(false); const [copied, setCopied] = useState(false); const [fetchState, setFetchState] = useState<FetchAnswer | { state: "asking" } | null>(null); + const [fromStored, setFromStored] = useState(false); const [cases, setCases] = useState<CaseSummary[]>(initialCases); const [board, setBoard] = useState<string | null>(initialCase && initialCases.some((c) => c.id === initialCase) ? initialCase : null); const [pinAsk, setPinAsk] = useState<"pin" | "new" | null>(null); @@ -373,6 +375,7 @@ export default function ResearchView({ start, end, reason: `umtool research: "${res.query}" @ ${win.citation.text.match(/@ ([\d:]+)\]/)?.[1] ?? start}`, + ...(fromStored ? { storedUrl: STORED_URL_UI_MODE } : {}), }), }), ); @@ -395,7 +398,7 @@ export default function ResearchView({ } catch (e) { setFetchState({ state: "failed", message: (e as Error).message }); } - }, [res, litHit, win]); + }, [res, litHit, win, fromStored]); // ── pin to a board (R2) ── const pinTo = useCallback( @@ -671,6 +674,8 @@ export default function ResearchView({ onCopy={copy} fetchState={fetchState} onFetch={fetchClip} + fromStored={fromStored} + onFromStored={setFromStored} onPin={pin} pinning={pinWorking} pinned={pinned} diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -1035,6 +1035,49 @@ writeProject( ]), ); +// A RECORD THAT STORES ITS MEDIA URL (release 32 R6): an Odysee record whose +// metadata.info.json names its one CDN format, so "Cut from the stored media +// URL" is offered beside its fetch (lib/clips/stored.ts). Its own channel and a +// project of one clip on it; the stub records the `storedUrl` the fetch sent. +{ + const dir = path.join(CHANNELS, "testchan-odysee", "data", "odv1"); + mkdirSync(dir, { recursive: true }); + writeFileSync( + path.join(CHANNELS, "testchan-odysee", "config.json"), + JSON.stringify({ name: "Fixture Odysee", handling: "youtube", url: "https://odysee.com/@fixture", platform: "odysee" }) + "\n", + ); + writeFileSync( + path.join(dir, "metadata.info.json"), + JSON.stringify({ + id: "odv1", + title: "Fixture Odysee source", + webpage_url: "https://odysee.com/@fixture:1/odv1:1", + formats: [{ format_id: "original", url: "https://player.odycdn.com/v6/streams/odv1/f0.mp4", protocol: "https", ext: "mp4" }], + }) + "\n", + ); + writeFileSync( + path.join(dir, "transcript.cues.json"), + JSON.stringify({ + title: "Fixture Odysee source", + uploadDate: "20250101", + channel: "Fixture Odysee", + webpageUrl: "https://odysee.com/@fixture:1/odv1:1", + duration: 9, + cues: [ + { start: 0, end: 3, text: "The stored fixture begins." }, + { start: 3, end: 6, text: "Its file address is on record." }, + { start: 6, end: 9, text: "That is all it says." }, + ], + }) + "\n", + ); +} +writeProject( + "stored-url-fixture", + manifest("stored-url-fixture", "The Stored URL Fixture", { siteOrigin: "https://archive.example", channelSlug: "testchan-odysee" }, [ + { type: "clip", id: "s01", video: "odv1", start: 3.0, end: 6.0, cite: 3, section: 0, lock: true, quote: "its file address is on record" }, + ]), +); + // -- THE TAG FIXTURE ---------------------------------------------------------- // // Cited videos over TWO SECTIONS, for "tag cited videos as …". Nothing here is diff --git a/umtool/e2e/stored-url.spec.ts b/umtool/e2e/stored-url.spec.ts @@ -0,0 +1,58 @@ +import { test, expect } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// "Cut from the stored media URL" (release 32 R6) in umtool: offered beside a +// window fetch only when the record stores a media file address the editor can +// cut from (an Odysee record's CDN file: e2e/fixtures/make-fixture.mjs, +// stored-url-fixture on testchan-odysee/odv1), off by default, and ticked it +// rides to the editor as `storedUrl: "fallback"` (the editor stub records it). +// A project whose records store none offers nothing. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const STORED = "reports/stored-url-fixture"; +const PLAIN = "reports/editor-fetch-many-fixture"; +const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); +const asked = (): Record<string, unknown>[] => { + try { + return JSON.parse(readFileSync(STUB_LOG, "utf8")) as Record<string, unknown>[]; + } catch { + return []; + } +}; + +test("the stored-URL answer: a record that stores its CDN file, one that does not", async ({ request, baseURL }) => { + const yes = await request.get(`${baseURL}/api/cited/stored?channel=testchan-odysee&video=odv1`); + expect(await yes.json()).toEqual({ stored: true, host: "player.odycdn.com", platform: "odysee" }); + const clip = await request.get(`${baseURL}/api/cited/stored?project=${encodeURIComponent(STORED)}&clip=s01`); + expect((await clip.json()).stored).toBe(true); + const no = await request.get(`${baseURL}/api/cited/stored?channel=testchan&video=vid4`); + expect(await no.json()).toEqual({ stored: false }); +}); + +test("Fetch unfetched clips offers it only where a record stores one; ticked, the editor is asked with it", async ({ page }) => { + test.setTimeout(120_000); + // No stored URL among the clips: no option. + await page.goto(urls.section(PLAIN, "timeline")); + await expect(page.getByRole("button", { name: /unfetched clip/i })).toBeVisible(); + await expect(page.locator("[data-stored-url-option]")).toHaveCount(0); + + await page.goto(urls.section(STORED, "timeline")); + const option = page.locator("[data-stored-url-option]"); + await expect(option).toBeVisible(); + await expect(option).toContainText("Cut from the stored media URL"); + await expect(option).toContainText("Odysee only"); + const box = option.getByRole("checkbox"); + await expect(box).not.toBeChecked(); + await box.check(); + const before = asked().length; + await page.getByRole("button", { name: /fetch 1 unfetched clip/i }).click(); + await expect(page.locator("[data-fetch-unfetched-msg]")).toContainText(/fetched 1 clip/, { timeout: 90_000 }); + const ask = asked().slice(before).find((a) => a.manifest === "stored-url-fixture"); + expect(ask).toMatchObject({ channelSlug: "testchan-odysee", videoId: "odv1", storedUrl: "fallback", requestedBy: "umtool" }); +}); diff --git a/umtool/lib/clips/cited.test.ts b/umtool/lib/clips/cited.test.ts @@ -71,3 +71,13 @@ test("a cooldown says the platform is rate-limiting; an audio-check failure says const f = await lib.fetchCitedClip({ job: "j2", target }, m.deps); assert.match(f.state === "failed" ? f.message : "", /corrupt audio/); }); + +test("Cut from the stored media URL rides on the fetch as fetch_clip's storedUrl (release 32 R6)", async () => { + const e = editor([() => ({ status: 202, body: { cached: false, jobId: "j3", from: 0, to: 9 } })]); + const target = { channel: "chan", video: "v1", from: 3, to: 6 }; + await lib.fetchCitedClip({ target, reason: "review", storedUrl: "fallback" }, e.deps); + assert.equal(e.calls[0].body?.storedUrl, "fallback"); + const plain = editor([() => ({ status: 202, body: { cached: false, jobId: "j4", from: 0, to: 9 } })]); + await lib.fetchCitedClip({ target, reason: "review" }, plain.deps); + assert.equal("storedUrl" in (plain.calls[0].body ?? {}), false); +}); diff --git a/umtool/lib/clips/cited.ts b/umtool/lib/clips/cited.ts @@ -114,7 +114,9 @@ const deps: FetchClipDeps = { * ready answer carries what plays now; a failure its plain sentence. */ export async function fetchCitedClip( - req: { job: string; target?: CitedTarget } | { target: CitedTarget; reason: string; report?: string }, + req: + | { job: string; target?: CitedTarget } + | { target: CitedTarget; reason: string; report?: string; storedUrl?: "fallback" | "only" }, d: FetchClipDeps = deps, ): Promise<CitedFetchAnswer> { const args = @@ -127,6 +129,8 @@ export async function fetchCitedClip( end: req.target.to, reason: req.reason, ...(req.report ? { report: req.report } : {}), + // Cut from the stored media URL (release 32 R6): fetch_clip's field. + ...(req.storedUrl ? { storedUrl: req.storedUrl } : {}), wait_seconds: 0, }; const v = validateFetchClipArgs(args); diff --git a/umtool/lib/clips/stored.test.ts b/umtool/lib/clips/stored.test.ts @@ -0,0 +1,56 @@ +// "Cut from the stored media URL" (release 32 R6): umtool offers it only for a +// record that stores a media file address the editor can cut from — an Odysee +// record with its one CDN format — and finds a project clip's record the way +// fetch-via-editor.mjs does. A synthetic corpus in a temp dir; no network. +// +// Run with: pnpm --filter umtool exec tsx --test lib/clips/stored.test.ts +import { before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +let lib: typeof import("./stored"); +let channels: string; + +async function record(slug: string, id: string, info: Record<string, unknown>) { + const dir = path.join(channels, slug, "data", id); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(info)); +} + +before(async () => { + channels = path.join(await mkdtemp(path.join(os.tmpdir(), "umtool-stored-")), "channels"); + process.env.CHANNELS_DIR = channels; + lib = await import("./stored"); + await record("od", "s1", { + webpage_url: "https://odysee.com/@demo:1/s1:1", + formats: [{ url: "https://player.odycdn.com/v6/streams/s1/f0.mp4", protocol: "https" }], + }); + await record("od", "n1", { webpage_url: "https://odysee.com/@demo:1/n1:1" }); + await record("yt", "y1", { + webpage_url: "https://www.youtube.com/watch?v=y1", + formats: [{ url: "https://player.odycdn.com/v6/streams/y1/f0.mp4", protocol: "https" }], + }); +}); + +test("offered only for a record on an allowlisted platform that stores its CDN file", async () => { + assert.deepEqual(await lib.storedUrlOf("od", "s1", channels), { stored: true, host: "player.odycdn.com", platform: "odysee" }); + assert.deepEqual(await lib.storedUrlOf("od", "n1", channels), { stored: false }); + assert.deepEqual(await lib.storedUrlOf("yt", "y1", channels), { stored: false }, "not an allowlisted platform"); + assert.deepEqual(await lib.storedUrlOf("od", "missing", channels), { stored: false }); + assert.deepEqual(await lib.storedUrlOf("..", "s1", channels), { stored: false }); +}); + +test("a project clip's record: the clip's channel, else the manifest's; a ledger claim's too", () => { + const m = { + provenance: { channelSlug: "od" }, + timeline: [{ id: "c1", video: "s1" }, { id: "c2", channel: "yt", video: "y1" }, { id: "t1", type: "card" }], + ledger: [{ id: "l1", video: "n1" }], + }; + assert.deepEqual(lib.clipRecord(m, "c1"), { channel: "od", video: "s1" }); + assert.deepEqual(lib.clipRecord(m, "c2"), { channel: "yt", video: "y1" }); + assert.deepEqual(lib.clipRecord(m, "l1"), { channel: "od", video: "n1" }); + assert.equal(lib.clipRecord(m, "t1"), null); + assert.equal(lib.clipRecord(m, "nope"), null); +}); diff --git a/umtool/lib/clips/stored.ts b/umtool/lib/clips/stored.ts @@ -0,0 +1,56 @@ +import path from "node:path"; +import { storedMediaUrl } from "yt-dlp-transcript-common/lib/storedMediaUrl-server"; +import { CHANNELS_DIR } from "@/lib/paths"; +import { SourceError } from "@/lib/research/sources"; +import { resolveClip } from "@/lib/report/serve.mjs"; + +// --------------------------------------------------------------------------- +// "Cut from the stored media URL" (release 32 R6): whether a span's record +// stores a media file address the editor may cut a window from +// (lib/storedMediaUrl.ts — Odysee's CDN file only). Every fetch surface asks +// this before it offers the option, so it is shown only where it can do +// something. The editor's corpus is CHANNELS_DIR: the fetch is the editor's. +// --------------------------------------------------------------------------- + +export type StoredUrlAnswer = { stored: boolean; host?: string; platform?: string }; + +const ID = /^[\w.-]+$/; +const isDir = (v: string) => ID.test(v) && v !== "." && v !== ".."; + +/** The record `channel`/`video` names, in the editor's corpus. */ +export async function storedUrlOf(channel: string, video: string, channelsDir: string = CHANNELS_DIR): Promise<StoredUrlAnswer> { + if (!isDir(channel) || !isDir(video)) return { stored: false }; + const s = await storedMediaUrl(path.join(/* turbopackIgnore: true */ channelsDir, channel, "data", video)); + return s ? { stored: true, host: s.host, platform: s.platform } : { stored: false }; +} + +/** + * The channel and video a project clip's fetch asks the editor for — the rule + * fetch-via-editor.mjs follows: a timeline clip's `channel` (else the + * manifest's provenance.channelSlug) and `video`, or a ledger claim's. + */ +export function clipRecord( + manifest: { provenance?: { channelSlug?: string }; timeline?: unknown[]; ledger?: unknown[] }, + clipId: string, +): { channel: string; video: string } | null { + type E = { id?: unknown; channel?: unknown; video?: unknown }; + const entry = + ((manifest.timeline ?? []) as E[]).find((e) => e?.id === clipId) ?? + ((manifest.ledger ?? []) as E[]).find((e) => e?.id === clipId); + if (!entry) return null; + const channel = typeof entry.channel === "string" && entry.channel ? entry.channel : manifest.provenance?.channelSlug; + const video = typeof entry.video === "string" ? entry.video : ""; + return channel && video ? { channel, video } : null; +} + +/** For a project clip (the benches) or a channel + video (the cited player). */ +export async function storedUrlFor(q: { project?: string; clip?: string; channel?: string; video?: string }): Promise<StoredUrlAnswer> { + if (q.project && q.clip) { + const r = await resolveClip(q.project, q.clip); + if ("error" in r) throw new SourceError(String(r.error), Number(r.status) || 404); + const rec = clipRecord(r.manifest, q.clip); + return rec ? storedUrlOf(rec.channel, rec.video) : { stored: false }; + } + if (q.channel && q.video) return storedUrlOf(q.channel, q.video); + throw new SourceError("project and clip, or channel and video, are required"); +} diff --git a/umtool/lib/report/driver.mjs b/umtool/lib/report/driver.mjs @@ -313,12 +313,17 @@ export function fetchSteps(project, clipId, pad) { * * @param {{ dir: string }} project * @param {string} clipId - * @param {number | { padBefore: number, padAfter: number }} pad + * @param {number | { padBefore: number, padAfter: number, storedUrl?: "fallback" | "only" | null }} pad * @returns {import("../trim").Step[]} */ export function editorFetchSteps(project, clipId, pad) { const before = typeof pad === "object" && pad ? Number(pad.padBefore) : Number(pad); const after = typeof pad === "object" && pad ? Number(pad.padAfter) : Number(pad); + // Cut from the stored media URL (release 32 R6): `--stored-url <mode>`. + const storedUrl = + typeof pad === "object" && pad && (pad.storedUrl === "fallback" || pad.storedUrl === "only") + ? pad.storedUrl + : null; return [ { cwd: PIPELINE_DIR, @@ -338,6 +343,7 @@ export function editorFetchSteps(project, clipId, pad) { String(before), "--pad-after", String(after), + ...(storedUrl ? ["--stored-url", storedUrl] : []), "--progress", "ndjson", ], diff --git a/umtool/lib/research/fetch.ts b/umtool/lib/research/fetch.ts @@ -53,13 +53,21 @@ export function answerOf(o: FetchClipOutcome): FetchAnswer { export type FetchRequest = | { job: string } - | { source: string; channel: string; video: string; start: number; end: number; reason: string }; + | { source: string; channel: string; video: string; start: number; end: number; reason: string; storedUrl?: "fallback" | "only" }; export async function fetchForReader(req: FetchRequest): Promise<FetchAnswer> { const args = "job" in req ? { job: req.job, wait_seconds: 0 } - : { channel: req.channel, video: req.video, start: req.start, end: req.end, reason: req.reason, wait_seconds: 0 }; + : { + channel: req.channel, + video: req.video, + start: req.start, + end: req.end, + reason: req.reason, + ...(req.storedUrl ? { storedUrl: req.storedUrl } : {}), + wait_seconds: 0, + }; const v = validateFetchClipArgs(args); if (!v.ok) throw new SourceError(v.error.replace(/^fetch_clip: /, "")); if (!("job" in req)) { diff --git a/umtool/report-to-video/fetch-via-editor.mjs b/umtool/report-to-video/fetch-via-editor.mjs @@ -75,7 +75,7 @@ const clipId = flag("--fetch-only") ?? flag("--clip"); // streak and the 429 stop live there, not in a shell loop here. const wantAll = argv.includes("--all"); if (!manifestPath || (!clipId && !wantAll) || (clipId && wantAll)) { - die("usage: fetch-via-editor.mjs <manifest.json> (--fetch-only <clipId> [--full] | --all) [--max-height N] [--pad N] [--pad-before N] [--pad-after N] [--progress ndjson]"); + die("usage: fetch-via-editor.mjs <manifest.json> (--fetch-only <clipId> [--full] | --all) [--max-height N] [--stored-url fallback|only] [--pad N] [--pad-before N] [--pad-after N] [--progress ndjson]"); } // THE WHOLE RECORDING INSTEAD OF A WINDOW. For a clip whose windows would tile @@ -105,6 +105,20 @@ if ( ); } +// CUT FROM THE STORED MEDIA URL (release 32 R6): the editor's `storedUrl` — +// "fallback" (the page first, the record's stored media file when the platform +// refuses the lookup) or "only" (no page request). Odysee only, and only a +// record that stores one; any other is fetched as usual. Windows only. +const STORED_URL_MODES = ["never", "fallback", "only"]; +const storedUrlArg = flag("--stored-url"); +if (storedUrlArg !== undefined && !STORED_URL_MODES.includes(storedUrlArg)) { + die(`--stored-url ${storedUrlArg} must be one of ${STORED_URL_MODES.join(", ")}`); +} +if (storedUrlArg !== undefined && storedUrlArg !== "never" && argv.includes("--full")) { + die("--stored-url cuts a window; --full is the whole recording"); +} +const storedUrl = storedUrlArg && storedUrlArg !== "never" ? { storedUrl: storedUrlArg } : {}; + const editorUrl = (process.env.ARCHILYZER_EDITOR_URL ?? DEFAULT_EDITOR).replace(/\/+$/, ""); const token = process.env.WORKER_TOKEN ?? ""; if (!token) { @@ -242,6 +256,7 @@ if (wantAll) { requestedBy: "umtool", manifest: manifestId, ...(maxHeight !== undefined ? { maxHeight } : {}), + ...storedUrl, }), }); const body = await res.json().catch(() => ({})); @@ -357,6 +372,7 @@ const res = await ask(`${editorUrl}/api/media/fetch-window`, { webpageUrl: entry.webpageUrl ?? undefined, ...(wantFull ? { full: true } : { from, to, pad: Math.max(padBefore, padAfter) }), ...(maxHeight !== undefined ? { maxHeight } : {}), + ...storedUrl, requestedBy: "umtool", manifest: manifestId, clipId: entry.id, diff --git a/umtool/report-to-video/fetch-via-editor.test.mjs b/umtool/report-to-video/fetch-via-editor.test.mjs @@ -119,6 +119,23 @@ test("no --max-height sends none; a bad one is refused before any request", asyn } }); +test("--stored-url rides on a window request; never sends none; a bad one or one with --full is refused", async () => { + const ed = await stubEditor(CACHED(720)); + try { + assert.equal((await run(ed.url, ["--stored-url", "fallback"])).code, 0); + assert.equal(ed.posts[0].storedUrl, "fallback"); + assert.equal((await run(ed.url, ["--stored-url", "never"])).code, 0); + assert.equal("storedUrl" in ed.posts[1], false); + for (const args of [["--stored-url", "always"], ["--full", "--stored-url", "only"]]) { + const { code } = await run(ed.url, args); + assert.equal(code, 1, args.join(" ")); + } + assert.equal(ed.posts.length, 2); + } finally { + await ed.close(); + } +}); + // ---- the wait ------------------------------------------------------------------ /**