commit 25de404681a00c663f71997977cbb6e2e482749e
parent 65ccbb9c51cd0615c8ffe03f8cf4e7d2bf7aa92c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 17 Oct 2026 02:02:44 -0400
Merge branch 'main' into r32/rulings
# Conflicts:
# editor/CHANGELOG.md
# plans/FACTS.md
Diffstat:
58 files changed, 3876 insertions(+), 29 deletions(-)
diff --git a/CHANNEL.md b/CHANNEL.md
@@ -47,6 +47,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f
| `sleepBetweenDownloadsSeconds` | config | Per-channel override for the global pause between downloads. Absent = inherit; 0 = no sleep; floored and capped at 600. |
| `audioCheck` | config | Audio-integrity checking for sources that intermittently serve corrupt audio mid-download: the managed downloader periodically validates the in-progress `.part` file and rolls back to the last known-good snapshot on corruption (transcribe handling), and a clip window gets the same final probe, fetched once more when malformed and never kept when malformed twice. ON BY DEFAULT for an Odysee video (`audioCheck: {"enabled": false}` turns it off); the channel's opt-in for any other platform. See [`audioCheck`](#audiocheck). |
| `storedUrlDownloads` | config | Whether a full download (transcribe handling) reads the media URL the record's `metadata.info.json` already stores, the way the platform's own player reads it — ranged requests with the page's Referer and Origin, no yt-dlp — through the same audio check. `"never"` (the default: the page, as always), `"fallback"` (the page first; on a rate limit, or a held platform, the stored URL) or `"only"` (the stored URL and no page request; a video without one fails, asking nothing). Odysee only (its CDN hosts). Two such downloads on one platform are at least 20 minutes apart: the CDN allows one new file per rest. A request's own `storedUrl` overrides it. |
+| `browserLookup` | config | `true`, with `storedUrlDownloads` `fallback` or `only`: when a video's record stores no media URL — `only`, or a `fallback` whose yt-dlp lookup was refused (a 429) — the managed download opens the video's page in a headless browser, reads the record from the page's own API answers and writes `metadata.info.json` (marked `_source: "browser"`), then downloads from the media URL the page named. Odysee only; one page a minute; the channel's `--match-filter title~='…'` and download filters still decide. Absent = off. The video page's **Read from the page** and the channel's **List from the page** ask for it once, whatever this says. |
| `recordedDate` | config | For a channel that MIRRORS another's streams (a VOD archive): how to read the date a video was RECORDED from its title, since its `upload_date` is the date of the copy. The index stores the result as the record's `recordedDate` (`YYYYMMDD`), which coverage reads before the upload date. A title it does not match, a date that is not a real day, or one after the upload date gives none. Changing the rule re-derives the channel's records on the next index build. An object without a usable `titlePattern` is dropped. See [`recordedDate`](#recordeddate). |
| `mirror` | config | For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped. See [`mirror`](#mirror). |
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -40,6 +40,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi
| `archilyzer reports bench-verdicts` | `--models <a,b,…> [--report <id,…>] [--window <s>] [--window-mode seconds\|turn] [--max-usd <n>] [--limit <n>] [--items-from <run>] [--dedupe] [--run <id>] [--dry] [--here] [--wait] [--json]` | the verdict bench (release 28; release 29 V1): every claim of the registry's fact-checks (or of --report) with the operator's verdict and a citation with cues, asked of each model one claim per call — the report's title, the claim's section, the claim, its quotes (their speaker and the recording's date) and the transcript within --window seconds (default 60) of each cited span, or with --window-mode turn the cited speaker's turn bounded by --window, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT\_FOUND recall, not-CORROBORATED precision and recall, against an always-CORROBORATED baseline). --limit takes a stratified sample (by the operator's verdict: every verdict kept); --items-from takes an earlier run's exact items (no --report, --window, --window-mode, --limit or --dedupe with it); --dedupe asks a claim that repeats an earlier one (the same text over the same cited spans) once — without it every claim is asked. The run records its prompt version and its items' hash. --dry lists the items, the skipped claims and the dropped citations and estimates the cost, asking nothing. Otherwise through the editor (`pnpm ops bench-verdicts`; a local model through the GPU arbiter; --wait follows the job), or --here in this process for API models only. The run stops at --max-usd (default 5, the whole run); a --run that exists continues with this invocation's --models only (refused under another prompt version). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /tools/bench) (exit 1 when the run stopped early or was refused; 2 for usage) |
| `archilyzer reports import-local-runs` | `[--apply] [--runs <dir>] [--only <run,…>] [--move-projects] [--generation <file>]` | ONE-OFF (release 27): the stopgap's kept runs (--runs: its directory, default ~/reports/local-reports; --only: those runs, default piratesoftware-ai-friends and api-shondo-recent) become i1 of their article through the iterations store — made current only when the run's report.json is the article's; a run with no article becomes an article in the making — and each video project is copied (--move-projects: moved) to the generation projects root; ~/.config/archilyzer/generation.json, when there is one, becomes settings.generation's routes and models. Lists the stopgap's test runs, projects and drafts to delete after the operator's OK (deletes nothing). A dry run printing the plan unless --apply (exit 1 when a run is refused) |
| `archilyzer frames rederive` | `<slug>/<id> [--profile poker] [--hero <name>] [--dry] [--json]` | work a frame scan's derived timeline (tournaments, series, events, flags) out again from the readings frame-scan.<profile>.json already holds and the video's cues — no model, no frame, no editor — and write it back (--dry: print what would change, write nothing). Not while a scan of the video is running (it writes the same file): with an editor up, `pnpm ops frame-scan --json '{"slug","id","rederive":true}'` checks that (exit 1 when there is no sidecar; 2 for usage) |
+| `archilyzer reports import-sweep` | `<report.json> --article <id> --question <question> [--sweep <sweep.md>] [--channels <a,b>] [--model <m>] [--from <where>] [--minutes <n>] [--apply]` | a report made outside the editor's report-draft jobs (a Claude Code session's /sweep, a task routed to code) becomes the next iteration of its article through the iterations store: kind sweep, status done, $0, its question, channels and minutes, `imported` naming where it came from (--from, default claude-code; --model default claude-code); its report.json the file given (id set to the article's, audience dropped), refused unless it parses as a report; never made current (umtool's Iterations tab, or `umtool chain <id> <n>`); a new id makes an article in the making. A dry run printing the plan unless --apply (exit 1 when refused; 2 for usage) |
| `archilyzer gen policy` | `[--json]` | the generation policy: where each task runs (code = Claude Code, api = the Claude API, local = the local model), the models, the caps and the day's Claude API spend — from the editor, or settings.json when none answers |
| `archilyzer gen preset` | `<code\|balanced\|api\|local>` | route every generation task by a preset (its routes are written; settings.generation.routes) |
| `archilyzer gen set` | `<task> <code\|api\|local>` | route one generation task (sweep, revise-report, revise-video, research; the media drafts cut, onscreen, teaser, flips, threads, narrate, youtube, social) |
@@ -108,6 +109,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `delete-channel` | delete-channel removes a channel's whole directory, as Danger → Delete does: {"slug", "confirm"} — "confirm" must repeat the slug. No undo outside the transcripts/ repo's own history. | `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` |
| `metadata-scan` | metadata-scan reads every listed video's title, date and description into the channel's scan file, fetching no media: {"slug"}. Not held by the download pause and needs no disk floor; one request per video, so it respects the platform's cooldown and records one when pushed back. | `pnpm ops metadata-scan --json '{"slug":"the-quartering"}'` |
| `refresh-metadata` | refresh-metadata re-reads ONE video's metadata.info.json from its source (no subtitles, no media) on the platform's queue: {"slug", "id"}. The job's log ends with what the source now says — live\_status, formats, audio-only formats and whether any is non-fragmented, English captions, the keys that changed. An id with no data/<id>/ is refused (a refresh re-reads a video already archived), as are archive.org and Wayback records. | `pnpm ops refresh-metadata --json '{"slug":"the-quartering","id":"<videoId>"}' --wait` |
+| `browser-lookup` | browser-lookup reads Odysee records from their pages in a headless browser, for when yt-dlp's lookup answers 429: {"slug", "ids": \[...\]} (at most 50) writes each record (none yet: whole, `_source: "browser"`) or completes it (the keys it lacks, and the one media file the page's player asked for); "listing": true (with "scrolls", default 5, at most 40) adds the uploads the channel page shows to the playlist, newest first, through the title match filter. One page a minute; not refused for a held platform. The log ends with a `summary: {...}` line. | `pnpm ops browser-lookup --json '{"slug":"demo-odysee","ids":["<claimId>"]}' --wait`<br>`pnpm ops browser-lookup --json '{"slug":"demo-odysee","listing":true,"scrolls":5}' --wait` |
| `import-video` | import-video imports one video by URL into a channel: {"slug", "url"}. An archive.org URL becomes its canonical item or file (an item of several media files is refused — see import-archive-org); a BitChute or Odysee URL runs on that platform's queue at its pace, refused while it is held or cooling down, and refused when already on disk; a Wayback capture is named by what it copies. | `pnpm ops import-video --json '{"slug":"demo-archive","url":"https://archive.org/details/example-item"}'` |
| `import-archive-org` | import-archive-org imports archive.org media into a channel, as one job on archive.org's queue: {"slug", "item", "files": \[...\] \| "match": "<regex>"} for one item; {"slug", "items": \["<id>" \| {"item", "files"? \| "match"?}, ...\]} for many (a bare id takes "match", else every media original); or {"slug", "query": "<archive.org search>", "limit"?: 100} for the first items a search finds (at most 500). One file at a time, a jittered pause between files and between items; a record already held (on disk, or in the saved-video store) is skipped. "dryRun": true lists each file as held, RESTRICTED (archive.org marks it not for download: a fetch would answer 401/403) or would get, and fetches nothing. A 401/403 skips the rest of its item; three such items in a row, a 429 or three failures in a row stop the job. The log ends with a summary: line; a re-run resumes. | `pnpm ops import-archive-org --json '{"slug":"demo-archive","item":"example-item","match":"\\.mp4$"}' --wait`<br>`pnpm ops import-archive-org --json '{"slug":"demo-archive","query":"collection:example-collection","dryRun":true}' --wait` |
| `remote-listing` | remote-listing lists an Odysee or BitChute channel upstream and diffs it against what it holds: {"slug"}. One flat-playlist read on the platform's queue (refused while it is held or cooling down; a 429 backs it off), nothing written. `get remote-listing <slug>` waits for the job and prints {listed, held, notHeld: \[{id, url}\], heldNotListed: \[id\], ...} on stdout. | |
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -220,7 +220,8 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one
| `E2E_AUDIO_CHECK_RECOVER_STEP_MS` | the real step | Likewise, the recovery step. | common/ytdlp/audioCheckedDownload.ts |
| `E2E_AUDIO_CHECK_RECOVER_AFTER` | the real count | Likewise, the recovery count. | common/ytdlp/audioCheckedDownload.ts |
| `E2E_BACKOFF_BASE_MS` | `60000` (the real base) | The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse. | common/jobs/platformBackoff.ts |
-| `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch. The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts |
+| `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts |
+| `E2E_ODYSEE_PAGE_FIXTURE` | unset (a headless browser) | A JSON file of recorded Odysee page reads keyed by page URL (`"*"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`). | common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts |
| `E2E_BLUESKY_ORIGIN_FILE` | unset (the real Bluesky) | A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored. | common/social/blueskyEndpoints.ts |
| `E2E_AUDIO_CHECK_DEBUG_PAUSE_MS` | off | A debugging pause inside the audio check. | common/ytdlp/audioCheckedDownload.ts |
| `E2E_FAKE_YTDLP_AUDIO_CHECK_MODE` | — | Fake yt-dlp: which audio-check scenario to act out. | editor/e2e/fixtures/bin/fake-ytdlp.mjs |
diff --git a/OPERATING.md b/OPERATING.md
@@ -248,6 +248,10 @@ pnpm ops get generation-usage
- `gen run` exits 3 and runs nothing for a task routed to `code`. In Claude Code, `/gen` and the MCP's `generate`
run a routed task through the editor and review what it made; `generation_policy` reads the policy and moves it
when you ask. `/sweep` follows the policy too.
+- A report made in Claude Code (a task routed to `code`) enters the registry as the article's next iteration with
+ `pnpm archilyzer reports import-sweep <report.json> --article <id> --question "…" [--sweep sweep.md] [--channels a,b]
+ [--model m] [--minutes n] --apply` (a dry run without `--apply`): kind sweep, done, $0, `imported` naming where it
+ came from; never made current — **Use this iteration** in umtool, or `umtool chain <id> <n>`.
- **Caps (USD, Claude API only):** a job's `maxUsd`, else $5 a sweep or research run, $2 a revision, $1 a narration;
never above `caps.max` ($10). The editor refuses a job once the day's API spend (UTC) reaches `caps.daily` ($20),
naming the day's total; a job already running stops at its own cap. The ledger is `.generation/usage.jsonl` in
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -452,6 +452,15 @@ export const COMMANDS: Command[] = [
maxPositionals: 1,
run: async ({ positionals, flags }) => (await import("./frames-rederive")).framesRederiveRow({ positionals, flags }),
},
+ {
+ path: ["reports", "import-sweep"],
+ usage:
+ "<report.json> --article <id> --question <question> [--sweep <sweep.md>] [--channels <a,b>] [--model <m>] [--from <where>] [--minutes <n>] [--apply] a report made outside the editor's report-draft jobs (a Claude Code session's /sweep, a task routed to code) becomes the next iteration of its article through the iterations store: kind sweep, status done, $0, its question, channels and minutes, `imported` naming where it came from (--from, default claude-code; --model default claude-code); its report.json the file given (id set to the article's, audience dropped), refused unless it parses as a report; never made current (umtool's Iterations tab, or `umtool chain <id> <n>`); a new id makes an article in the making. A dry run printing the plan unless --apply (exit 1 when refused; 2 for usage)",
+ flags: { article: "string", question: "string", sweep: "string", channels: "string", model: "string", from: "string", minutes: "string", apply: "boolean" },
+ maxPositionals: 1,
+ run: async ({ positionals, flags }) =>
+ (await import("./reports-import-sweep")).importSweepRow(positionals[0], flags as Parameters<typeof import("./reports-import-sweep").importSweepRow>[1]),
+ },
// The generation balance (release 27 S9; bin/gen.ts): settings.generation
// through the editor's ops API, or settings.json when no editor answers.
{
diff --git a/common/bin/reports-import-sweep.test.ts b/common/bin/reports-import-sweep.test.ts
@@ -0,0 +1,130 @@
+// `archilyzer reports import-sweep`: a report made outside the editor's
+// report-draft jobs becomes the next iteration of its article, a dry run by
+// default. A temp corpus only — never the real store.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test bin/reports-import-sweep.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "import-sweep-"));
+Object.assign(process.env, {
+ TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"),
+ SITES_DIR: path.join(ROOT, "transcripts", "sites"),
+ SETTINGS_FILE: path.join(ROOT, "settings.json"),
+ EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"),
+});
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { writeArticle } = await import("../lib/report/registry");
+const { currentIteration, readIteration, readIterationFile } = await import("../lib/report/iterations");
+const imp = await import("./reports-import-sweep");
+
+const paths = getPaths();
+const KIT = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "testing", "draft");
+const BASIC = JSON.parse(readFileSync(path.join(KIT, "reports", "basic.report.json"), "utf8")) as Record<string, unknown>;
+const SWEEP = readFileSync(path.join(KIT, "sweeps", "basic.md"), "utf8");
+const IN = path.join(ROOT, "in");
+mkdirSync(IN, { recursive: true });
+const reportFile = path.join(IN, "report.json");
+writeFileSync(reportFile, JSON.stringify({ ...BASIC, id: "some-other-id", audience: "public" }));
+const sweepFile = path.join(IN, "sweep.md");
+writeFileSync(sweepFile, SWEEP);
+
+const silent = () => {
+ const lines: string[] = [];
+ return { lines, out: { log: (s: string) => lines.push(s), error: (s: string) => lines.push(s) } };
+};
+const base = { reportFile, question: "What does the baker say about the bakery?", paths } as const;
+
+test("a dry run plans the next iteration and writes nothing", async () => {
+ const { lines, out } = silent();
+ const code = await imp.importSweepMain({ ...base, article: "baker-sweep", sweepFile, channels: ["synth-kitchen"], apply: false }, out);
+ assert.equal(code, 0);
+ assert.match(lines.join("\n"), /DRY RUN/);
+ assert.match(lines.join("\n"), /i1 of "baker-sweep", a NEW article in the making/);
+ assert.match(lines.join("\n"), /its id "some-other-id" becomes "baker-sweep"/);
+ assert.equal(existsSync(path.join(paths.articlesDir, "baker-sweep")), false);
+});
+
+test("apply writes a done sweep iteration, id set, audience dropped, provenance named, never current", async () => {
+ const { out } = silent();
+ const code = await imp.importSweepMain(
+ { ...base, article: "baker-sweep", sweepFile, channels: ["synth-kitchen"], minutes: 42, model: "claude-opus (Claude Code)", apply: true, now: () => new Date("2026-10-15T12:00:00Z") },
+ out,
+ );
+ assert.equal(code, 0);
+ const it = await readIteration("baker-sweep", 1, paths);
+ assert.ok(it);
+ assert.equal(it.kind, "sweep");
+ assert.equal(it.status, "done");
+ assert.equal(it.model, "claude-opus (Claude Code)");
+ assert.equal(it.question, "What does the baker say about the bakery?");
+ assert.deepEqual(it.scope?.channels, ["synth-kitchen"]);
+ assert.equal(it.minutes, 42);
+ assert.deepEqual((it as Record<string, unknown>).imported, { from: "claude-code", at: "2026-10-15T12:00:00.000Z", report: "report.json" });
+ const report = JSON.parse((await readIterationFile("baker-sweep", 1, "report.json", paths)) ?? "{}");
+ assert.equal(report.id, "baker-sweep");
+ assert.equal(report.audience, undefined);
+ assert.equal(await readIterationFile("baker-sweep", 1, "sweep.md", paths), SWEEP);
+ // Never made current: an article in the making stays one.
+ assert.equal((await currentIteration("baker-sweep", paths)).report, null);
+ assert.equal(existsSync(path.join(paths.articlesDir, "baker-sweep", "report.json")), false);
+});
+
+test("a second import is the next iteration", async () => {
+ const { lines, out } = silent();
+ assert.equal(await imp.importSweepMain({ ...base, article: "baker-sweep", apply: true }, out), 0);
+ assert.match(lines.join("\n"), /i2 of "baker-sweep"/);
+ const it = await readIteration("baker-sweep", 2, paths);
+ assert.equal(it?.model, imp.DEFAULT_IMPORT_MODEL);
+ assert.equal(await readIterationFile("baker-sweep", 2, "sweep.md", paths), null);
+});
+
+test("an article the registry has gets an iteration; its report is untouched", async () => {
+ await writeArticle({ ...BASIC, id: "baker-live" }, { paths });
+ const before = readFileSync(path.join(paths.articlesDir, "baker-live", "report.json"), "utf8");
+ const { lines, out } = silent();
+ assert.equal(await imp.importSweepMain({ ...base, article: "baker-live", apply: true }, out), 0);
+ assert.match(lines.join("\n"), /an article the registry has \(it is NOT made current\)/);
+ assert.ok(await readIteration("baker-live", 1, paths));
+ assert.equal(readFileSync(path.join(paths.articlesDir, "baker-live", "report.json"), "utf8"), before);
+});
+
+test("refusals: a bad id, no question, a bad channel, a missing file, a report that does not parse", async () => {
+ const cases: [Partial<Parameters<typeof imp.importSweepMain>[0]>, RegExp][] = [
+ [{ article: "Not An Id" }, /is not an article id/],
+ [{ article: "new" }, /is not an article id/],
+ [{ article: "baker-x", question: " " }, /names its question/],
+ [{ article: "baker-x", channels: ["bad slug!"] }, /is not a channel slug/],
+ [{ article: "baker-x", reportFile: path.join(IN, "nope.json") }, /no such file/],
+ [{ article: "baker-x", sweepFile: path.join(IN, "nope.md") }, /no such file/],
+ ];
+ const notReport = path.join(IN, "not-a-report.json");
+ writeFileSync(notReport, JSON.stringify({ format: "archilyzer-report", version: 1, title: "x" }));
+ cases.push([{ article: "baker-x", reportFile: notReport }, /does not parse/]);
+ for (const [o, why] of cases) {
+ const { lines, out } = silent();
+ const code = await imp.importSweepMain({ ...base, apply: true, ...o } as Parameters<typeof imp.importSweepMain>[0], out);
+ assert.equal(code, 1, JSON.stringify(o));
+ assert.match(lines.join("\n"), why);
+ }
+ assert.equal(existsSync(path.join(paths.articlesDir, "baker-x")), false);
+});
+
+test("the CLI row: usage errors exit 2", async () => {
+ const err = console.error;
+ console.error = () => {};
+ try {
+ assert.equal(await imp.importSweepRow(undefined, { article: "a", question: "q" }), 2);
+ assert.equal(await imp.importSweepRow(reportFile, { question: "q" }), 2);
+ assert.equal(await imp.importSweepRow(reportFile, { article: "a", question: "q", minutes: "soon" }), 2);
+ } finally {
+ console.error = err;
+ }
+});
diff --git a/common/bin/reports-import-sweep.ts b/common/bin/reports-import-sweep.ts
@@ -0,0 +1,198 @@
+// `archilyzer reports import-sweep <report.json> --article <id> --question <q>
+// [--sweep <sweep.md>] [--channels <a,b>] [--model <m>] [--minutes <n>] [--apply]`
+// — a report made OUTSIDE the editor's report-draft jobs (a Claude Code
+// session's /sweep, a hand-run research pass) becomes the next ITERATION of its
+// article, through the iterations store (lib/report/iterations.ts), never by
+// hand. A DRY RUN unless `--apply`: it prints what it would do and writes
+// nothing.
+//
+// Why: a task routed to `code` (settings.generation) runs in Claude Code, which
+// writes its report to a file; only the editor's API and local jobs made
+// iterations. Without this the only path into the registry was the release-27
+// one-off `import-local-runs`, which labels the result as the retired
+// stopgap's. This is the general door, and it says where the iteration came
+// from: `imported: { from: "claude-code" | <--from>, at, report }`.
+//
+// The iteration is kind `sweep`, status `done`, `$0` (a Claude Code session is
+// not billed through the generation ledger), with the question, the channels
+// and the minutes given. Its report.json is the file given, its `id` set to the
+// article's and its `audience` dropped (the registry's alone); it must parse as
+// a report. It is NEVER made current: the operator chooses it in umtool
+// ("Use this iteration") or `umtool chain <id> <n>` makes it current as its
+// first step. A new article id makes an article in the making.
+//
+// Exit 0 when the plan is sound (dry run) or the iteration is written (apply);
+// 1 when it is refused; 2 for a usage error.
+
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { createIteration, iterationLabel, readIterations, updateIteration, writeIterationFile } from "../lib/report/iterations";
+import { RESERVED_ARTICLE_IDS, readArticleState } from "../lib/report/registry";
+import { isReportId } from "../lib/report/schema";
+import { parseReport } from "../lib/report/validate";
+
+type StorePaths = Pick<Paths, "articlesDir" | "exportIndexDir">;
+type Out = { log: (s: string) => void; error: (s: string) => void };
+
+export type ImportSweepOptions = {
+ reportFile: string;
+ article: string;
+ question: string;
+ sweepFile?: string;
+ channels?: string[];
+ model?: string;
+ from?: string;
+ minutes?: number;
+ apply: boolean;
+ paths: StorePaths;
+ now?: () => Date;
+};
+
+export type ImportSweepPlan =
+ | { ok: false; refused: string }
+ | {
+ ok: true;
+ article: string;
+ articleExists: boolean;
+ nextLabel: string;
+ report: Record<string, unknown>;
+ reportIdWas?: string;
+ problems: string[];
+ sweepMd?: string;
+ model: string;
+ from: string;
+ channels: string[];
+ };
+
+export const DEFAULT_IMPORT_MODEL = "claude-code";
+const CHANNEL_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
+
+const obj = (v: unknown): Record<string, unknown> => (v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
+
+export async function planImportSweep(o: ImportSweepOptions): Promise<ImportSweepPlan> {
+ const refuse = (refused: string): ImportSweepPlan => ({ ok: false, refused });
+ const article = o.article.trim();
+ if (!isReportId(article) || RESERVED_ARTICLE_IDS.includes(article)) return refuse(`"${article}" is not an article id`);
+ if (!o.question.trim()) return refuse("an imported sweep names its question (--question)");
+ const channels = (o.channels ?? []).map((c) => c.trim()).filter(Boolean);
+ const badChannel = channels.find((c) => !CHANNEL_RE.test(c));
+ if (badChannel) return refuse(`"${badChannel}" is not a channel slug`);
+
+ let raw: unknown;
+ try {
+ raw = JSON.parse(await readFile(o.reportFile, "utf8"));
+ } catch (err) {
+ return refuse(`${o.reportFile}: ${(err as NodeJS.ErrnoException).code === "ENOENT" ? "no such file" : "not JSON"}`);
+ }
+ const report = { ...obj(raw) };
+ const wasId = typeof report.id === "string" ? report.id : undefined;
+ report.id = article;
+ // An iteration's report never carries an audience: the registry's alone.
+ delete report.audience;
+ const parsed = parseReport(report, { id: article });
+ if (!parsed.ok) {
+ return refuse(`the report does not parse: ${parsed.problems.slice(0, 3).map((p) => `${p.path || "(root)"}: ${p.message}`).join("; ")}`);
+ }
+
+ let sweepMd: string | undefined;
+ if (o.sweepFile) {
+ try {
+ sweepMd = await readFile(o.sweepFile, "utf8");
+ } catch {
+ return refuse(`${o.sweepFile}: no such file`);
+ }
+ }
+
+ const its = await readIterations(article, o.paths).catch(() => null);
+ if (its?.problems.length) return refuse(`"${article}" has unsound iterations (${its.problems.map((p) => iterationLabel(p.n)).join(", ")}); fix them first`);
+ const highest = Math.max(0, ...(its?.iterations ?? []).map((i) => i.n), its?.current?.highest ?? 0);
+ const state = await readArticleState(article, o.paths);
+
+ return {
+ ok: true,
+ article,
+ articleExists: state?.exists === true,
+ nextLabel: iterationLabel(highest + 1),
+ report,
+ ...(wasId !== article ? { reportIdWas: wasId ?? "(none)" } : {}),
+ problems: parsed.problems.map((p) => `${p.path || "(root)"}: ${p.message}`),
+ ...(sweepMd !== undefined ? { sweepMd } : {}),
+ model: o.model?.trim() || DEFAULT_IMPORT_MODEL,
+ from: o.from?.trim() || "claude-code",
+ channels,
+ };
+}
+
+export function formatImportSweep(plan: ImportSweepPlan, o: { apply: boolean; reportFile: string }): string[] {
+ if (!plan.ok) return [`reports import-sweep: REFUSED — ${plan.refused}`];
+ const L = [o.apply ? "reports import-sweep: APPLY" : "reports import-sweep: DRY RUN — nothing is written (--apply writes)"];
+ L.push(
+ `${o.reportFile} → ${plan.nextLabel} of "${plan.article}", ${plan.articleExists ? "an article the registry has (it is NOT made current)" : "a NEW article in the making (not listed, not a draft, until it is made current)"}`,
+ );
+ L.push(` sweep on ${plan.model} · from ${plan.from} · $0.00${plan.channels.length ? ` · channels ${plan.channels.join(", ")}` : ""}`);
+ L.push(` files: report.json${plan.reportIdWas ? ` (its id "${plan.reportIdWas}" becomes "${plan.article}")` : ""}${plan.sweepMd !== undefined ? ", sweep.md" : ""}`);
+ if (plan.problems.length) L.push(` the report has ${plan.problems.length} problem(s), so it cannot be made current until they are fixed: ${plan.problems.slice(0, 3).join("; ")}`);
+ L.push(` make it current: umtool's Iterations tab ("Use this iteration"), or \`umtool chain ${plan.article} <n>\` (its first step)`);
+ return L;
+}
+
+export async function importSweepMain(o: ImportSweepOptions, out: Out = console): Promise<number> {
+ const plan = await planImportSweep(o);
+ for (const l of formatImportSweep(plan, { apply: o.apply, reportFile: o.reportFile })) out.log(l);
+ if (!plan.ok) return 1;
+ if (!o.apply) return 0;
+ const now = (o.now ?? (() => new Date()))();
+ const created = await createIteration(
+ plan.article,
+ { kind: "sweep", model: plan.model, question: o.question.trim(), ...(plan.channels.length ? { scope: { channels: plan.channels } } : {}), status: "running" },
+ o.paths,
+ now,
+ );
+ const n = created.n;
+ await writeIterationFile(plan.article, n, "report.json", plan.report, o.paths);
+ if (plan.sweepMd !== undefined) await writeIterationFile(plan.article, n, "sweep.md", plan.sweepMd, o.paths);
+ await updateIteration(
+ plan.article,
+ n,
+ {
+ status: "done",
+ ...(o.minutes !== undefined && Number.isFinite(o.minutes) && o.minutes >= 0 ? { minutes: o.minutes } : {}),
+ endedAt: now.toISOString(),
+ imported: { from: plan.from, at: now.toISOString(), report: path.basename(o.reportFile) },
+ } as Parameters<typeof updateIteration>[2],
+ o.paths,
+ now,
+ );
+ out.log(`wrote "${plan.article}" ${iterationLabel(n)} (done)`);
+ return 0;
+}
+
+// The CLI row.
+export async function importSweepRow(
+ reportFile: string | undefined,
+ flags: { article?: string; question?: string; sweep?: string; channels?: string; model?: string; from?: string; minutes?: string; apply?: boolean },
+): Promise<number> {
+ if (!reportFile || typeof flags.article !== "string" || typeof flags.question !== "string") {
+ console.error("reports import-sweep: give <report.json> --article <id> --question <question>");
+ return 2;
+ }
+ const minutes = typeof flags.minutes === "string" ? Number(flags.minutes) : undefined;
+ if (minutes !== undefined && !(Number.isFinite(minutes) && minutes >= 0)) {
+ console.error("reports import-sweep: --minutes is a number of minutes");
+ return 2;
+ }
+ const { getPaths } = await import("../lib/paths");
+ return importSweepMain({
+ reportFile: path.resolve(reportFile),
+ article: flags.article,
+ question: flags.question,
+ ...(typeof flags.sweep === "string" ? { sweepFile: path.resolve(flags.sweep) } : {}),
+ ...(typeof flags.channels === "string" ? { channels: flags.channels.split(",") } : {}),
+ ...(typeof flags.model === "string" ? { model: flags.model } : {}),
+ ...(typeof flags.from === "string" ? { from: flags.from } : {}),
+ ...(minutes !== undefined ? { minutes } : {}),
+ apply: flags.apply === true,
+ paths: getPaths(),
+ });
+}
diff --git a/common/controller/autoRunner.ts b/common/controller/autoRunner.ts
@@ -123,6 +123,8 @@ import {
import { transcribeOneFromQueue } from "./transcribeOneFromQueue";
import { findVideoSourceUrl } from "./undownloadedVideos";
import { downloadOneManaged } from "../ytdlp/downloadOneManaged";
+import { makeStoredUrlLaneMemo, storedUrlLaneMode, storedUrlRescue } from "./laneStoredUrl";
+import { storedUrlGapRemainingMs } from "../jobs/storedUrlPace";
import { resolveDownloadFormatPreset } from "../ytdlp/downloadFormat";
// The automatic priority-queue runners. Each kind (auto-transcribe /
@@ -1170,6 +1172,10 @@ type Picked = {
// `pick.path` is empty, so no node's active count moves for it. `run()`
// branches on this and nothing else.
scan?: { slug: string; targets: number };
+ // THE STORED-URL UNIT (release 32 R9, controller/laneStoredUrl.ts): picked
+ // past a cooling or held platform because its record stores a media URL; it
+ // downloads as `only`, `held` on a held platform.
+ storedOnly?: { held: boolean };
};
async function runLoop(
@@ -1290,6 +1296,11 @@ async function runLoop(
const platformSkip = new Set<string>();
const platformKey = (slug: string, slugToPlatform: Map<string, string>) =>
slugToPlatform.get(slug) ?? "unknown";
+ // Which pending videos store a media URL (release 32 R9), remembered for
+ // the runner's life, and this tick's videos offered past a cooling or held
+ // platform because they do.
+ const storedLane = makeStoredUrlLaneMemo();
+ let storedPickIds = new Set<string>();
// videoId -> child download job id, for the units the runner currently has on
// the registry's platform queues. Used to hard-cancel them (kill yt-dlp or
@@ -1677,6 +1688,7 @@ async function runLoop(
let anyHeld = false;
let anyPaced = false;
platformSkip.clear();
+ storedPickIds = new Set<string>();
if (kind === "download") {
// Merge in any cooldown a manual sync/import wrote to the shared state
// (read-modify-write from outside the runner) since our last persist.
@@ -1698,8 +1710,12 @@ async function runLoop(
for (const [pf, n] of platformInFlight) {
if (n >= PER_PLATFORM_CAP) platformSkip.add(pf);
}
+ // Skipped for a cooldown or a hold, and not busy: a platform whose
+ // stored-URL videos may still be taken (release 32 R9).
+ const backedOff = new Set<string>();
for (const pf of Object.keys(kindState.platformBackoff)) {
if (isCoolingDown(kindState.platformBackoff, pf, now)) {
+ if (!platformSkip.has(pf)) backedOff.add(pf);
platformSkip.add(pf);
// A platform skipped for a cooldown is a different answer to "why is
// it idle?" than one skipped for being busy, so the two are tracked
@@ -1716,12 +1732,31 @@ async function runLoop(
}
}
if (platformSkip.size > 0) {
- for (const leafId of Object.keys(pending)) {
- pending[leafId] = pending[leafId].filter((id) => {
- const slug = owner.get(id);
- return !(slug && platformSkip.has(platformKey(slug, slugToPlatform)));
- });
- }
+ // THE STORED-URL RESCUE (release 32 R9, controller/laneStoredUrl.ts):
+ // an opted-in channel's video on a cooling or held platform stays
+ // pending when its record stores a media URL and the platform's
+ // stored-URL rest has elapsed — one new file per rest. Everything else
+ // on a skipped platform is dropped, as before.
+ const rescuable = new Set(
+ [...backedOff].filter((pf) => storedUrlGapRemainingMs(pf, {}, now) === 0),
+ );
+ const metaBySlug = new Map(metaCache.map((m) => [m.slug, m]));
+ const rescue = storedUrlRescue({
+ pending,
+ owner,
+ platformSkip,
+ rescuable,
+ platformOf: (slug) => platformKey(slug, slugToPlatform),
+ optedIn: (slug) => {
+ const m = metaBySlug.get(slug);
+ return m ? storedUrlLaneMode(m.config, platformKey(slug, slugToPlatform)) !== null : false;
+ },
+ known: storedLane.known,
+ });
+ for (const leafId of Object.keys(pending)) pending[leafId] = rescue.pending[leafId] ?? [];
+ storedPickIds = rescue.storedIds;
+ // Read on this tick, offered from the next.
+ if (rescue.unknown.length > 0) await storedLane.probe(paths.channelsDir, rescue.unknown);
}
// A video rate-limited recently is skipped until its deferral lapses, so
// after a cooldown the runner moves on rather than re-picking it.
@@ -1842,6 +1877,10 @@ async function runLoop(
const unitPlatform =
kind === "download" ? platformKey(channelSlug, slugToPlatform) : null;
+ const storedOnly =
+ unitPlatform && storedPickIds.has(pick.videoId) && platformSkip.has(unitPlatform)
+ ? { held: isPlatformHeld(kindState.platformHolds, unitPlatform) }
+ : undefined;
// Reserve the slot and account active counts up the path BEFORE returning,
// so the next selection sees the reservation (and ancestor caps reflect it).
live.inFlight.set(pick.videoId, {
@@ -1864,8 +1903,13 @@ async function runLoop(
channelSlug,
});
persist();
- onLog(`Auto-${kind}: ${channelSlug}/${pick.videoId} (leaf ${pick.leafId})`);
- return { pick, channelSlug, unitPlatform };
+ onLog(
+ `Auto-${kind}: ${channelSlug}/${pick.videoId} (leaf ${pick.leafId})` +
+ (storedOnly
+ ? ` from its stored media URL — ${unitPlatform} is ${storedOnly.held ? "held" : "cooling down"}`
+ : ""),
+ );
+ return { pick, channelSlug, unitPlatform, ...(storedOnly ? { storedOnly } : {}) };
};
// ONE UNIT ON AN OPERATION LANE.
@@ -2002,6 +2046,7 @@ async function runLoop(
onLog,
signal: runSignal,
drainSignal: ctx.drainSignal,
+ ...(picked.storedOnly ? { storedOnly: picked.storedOnly } : {}),
onChildJob: (jid) => { childJobIds.set(pick.videoId, jid); const u = live.inFlight.get(pick.videoId); if (u) u.jobId = jid; },
});
} catch (err) {
@@ -2164,6 +2209,9 @@ type LaunchArgs = {
// Download only: called with the child download job's id once enqueued, so the
// runner can hard-cancel it when stopped. No-op for transcription units.
onChildJob?: (jobId: string) => void;
+ // Download only: picked past a cooling or held platform (release 32 R9) —
+ // the download is `only` from the record's stored media URL.
+ storedOnly?: { held: boolean };
};
// The outcome of one unit. `failureClass` is set only for download failures
@@ -2317,6 +2365,10 @@ async function launchUnit(args: LaunchArgs): Promise<UnitResult> {
global: settings.downloadFormat,
}),
appendArchive: true,
+ // Past a cooling or held platform: the stored URL only, no lookup.
+ ...(args.storedOnly
+ ? { storedUrl: "only" as const, ...(args.storedOnly.held ? { storedUrlHeld: true } : {}) }
+ : {}),
});
unitStatus = record.status;
unitFailureClass = record.failureClass;
@@ -2377,6 +2429,11 @@ async function launchUnit(args: LaunchArgs): Promise<UnitResult> {
? { outcome: "transcribed", failureClass: "subs_rate_limit" }
: { outcome: "transcribed" };
}
+ // A stored-URL unit asked the platform nothing: its failure (the CDN's, or
+ // no trusted URL after all) is not the platform's (jobs/unitOutcome.ts).
+ if (args.storedOnly) {
+ return { outcome: "failed", viaStoredUrl: true, ...(unitFailureClass ? { failureClass: unitFailureClass } : {}) };
+ }
// failureClass drives the runner's per-platform backoff (rate_limit/network).
return { outcome: "failed", failureClass: unitFailureClass };
}
diff --git a/common/controller/browserLookupJob.ts b/common/controller/browserLookupJob.ts
@@ -0,0 +1,175 @@
+// THE BROWSER LOOKUP AS A JOB (release 32 R9) — what the video page's "Read
+// from the page", the channel page's "List from the page" and
+// `/api/ops/browser-lookup` enqueue. The work is ytdlp/odyseeBrowserLookup.ts
+// (one video) and controller/odyseeBrowserListing.ts (the channel's page).
+//
+// THE PER-REQUEST OPT-IN: a person (or an ops body) asks for exactly this. A
+// channel's `browserLookup: true` makes the managed download do the video half
+// by itself when the lookup is refused (ytdlp/downloadOneManaged.ts).
+//
+// THE REFUSALS COME BEFORE ANY JOB: a channel whose text cannot be read; a
+// request naming nothing; an id the channel cannot resolve to a page URL, or a
+// page that is not Odysee's; a listing of a channel whose URL is not an Odysee
+// channel page or whose yt-dlp match filter cannot be applied here.
+//
+// NOT REFUSED FOR A HELD OR COOLING PLATFORM: the hold is yt-dlp's lookup's,
+// and asking the page as a browser is the way round it the operator measured.
+// Paced (one page per BROWSER_LOOKUP gap, ytdlp/odyseeBrowserLookup.ts) and on
+// the platform's download queue, so it never runs beside a download, a sync or
+// another lookup of that platform. `needsText`: it writes text files only.
+//
+// The job's log ends with `summary: {json}` — the per-video statuses and the
+// listing's counts — for the UI to read back into sentences.
+
+import path from "node:path";
+import { assertChannelTextReadable } from "../lib/channelMedia";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { detectPlatform } from "../lib/platform";
+import { downloadQueueKey, resolveQueueKey } from "../lib/queueKeys";
+import type { Paths } from "../lib/paths";
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import {
+ BROWSER_LOOKUP_PLATFORMS,
+ browserLookupVideo,
+ type BrowserLookupDeps,
+} from "../ytdlp/odyseeBrowserLookup";
+import { browserListChannel, browserListingRefusal } from "./odyseeBrowserListing";
+import { isVideoIdSegment } from "./refreshVideoMetadata";
+import { findVideoSourceUrl } from "./undownloadedVideos";
+
+export const BROWSER_LOOKUP_JOB_KIND = "browser-lookup";
+// A bound on one request: each video is a page view, a minute apart.
+export const BROWSER_LOOKUP_MAX_VIDEOS = 50;
+
+export type BrowserLookupSummary = {
+ videos: { id: string; status: string; stored: boolean; error?: string }[];
+ listing?: { status: string; seen?: number; filtered?: number; added?: number; error?: string };
+};
+
+export type BrowserLookupJobOpts = {
+ paths: Paths;
+ slug: string;
+ channelConfig: ChannelConfig;
+ videoIds?: string[];
+ listing?: boolean;
+ scrolls?: number;
+ skipLiveDownloads: boolean;
+ queueKey?: string;
+ requestedBy?: string;
+ afterRun?: () => void | Promise<void>;
+ // Test seam: the page reader and the gap.
+ deps?: BrowserLookupDeps;
+};
+
+export async function runBrowserLookupJob(opts: BrowserLookupJobOpts): Promise<StreamActionResult> {
+ const { paths, slug, channelConfig } = opts;
+ try {
+ await assertChannelTextReadable(paths, slug, channelConfig);
+ } catch (err) {
+ return { ok: false, error: (err as Error).message };
+ }
+ const ids = [...new Set(opts.videoIds ?? [])];
+ if (ids.length === 0 && !opts.listing) {
+ return { ok: false, error: "Name the videos to look up, or ask for the channel's listing." };
+ }
+ if (ids.length > BROWSER_LOOKUP_MAX_VIDEOS) {
+ return { ok: false, error: `At most ${BROWSER_LOOKUP_MAX_VIDEOS} videos per browser lookup (${ids.length} asked).` };
+ }
+ const bad = ids.filter((id) => !isVideoIdSegment(id));
+ if (bad.length) return { ok: false, error: `Not a video id: ${bad.join(", ")}.` };
+ if (opts.listing) {
+ const refusal = browserListingRefusal(channelConfig);
+ if (refusal) return { ok: false, error: refusal };
+ }
+ const targets: { id: string; url: string }[] = [];
+ const unresolved: string[] = [];
+ for (const id of ids) {
+ const url = await findVideoSourceUrl(paths, slug, id, channelConfig);
+ const platform = url ? detectPlatform(url) : null;
+ if (!url || !platform || !BROWSER_LOOKUP_PLATFORMS.includes(platform)) unresolved.push(id);
+ else targets.push({ id, url });
+ }
+ if (unresolved.length) {
+ return {
+ ok: false,
+ error:
+ `No Odysee page URL for ${unresolved.join(", ")} (no metadata.info.json, and the playlist has no ` +
+ `matching entry, or the page is not Odysee's).`,
+ };
+ }
+
+ return runManagedFunction({
+ kind: BROWSER_LOOKUP_JOB_KIND,
+ queueKey: resolveQueueKey(downloadQueueKey(channelConfig), opts.queueKey),
+ paths,
+ channelSlug: slug,
+ ...(targets.length === 1 && !opts.listing ? { videoId: targets[0].id } : {}),
+ spec: {
+ kind: BROWSER_LOOKUP_JOB_KIND,
+ slug,
+ params: {
+ ...(ids.length ? { videoIds: ids } : {}),
+ ...(opts.listing ? { listing: true } : {}),
+ ...(opts.scrolls !== undefined ? { scrolls: opts.scrolls } : {}),
+ queueKey: opts.queueKey,
+ },
+ },
+ fn: async (onLog, signal) => {
+ const summary: BrowserLookupSummary = { videos: [] };
+ if (opts.listing) {
+ const r = await browserListChannel({
+ paths,
+ slug,
+ config: channelConfig,
+ ...(opts.scrolls !== undefined ? { scrolls: opts.scrolls } : {}),
+ skipLiveDownloads: opts.skipLiveDownloads,
+ onLog,
+ signal,
+ ...(opts.deps ? { deps: opts.deps } : {}),
+ });
+ summary.listing =
+ r.status === "listed"
+ ? { status: r.status, seen: r.seen, filtered: r.filtered, added: r.added.length }
+ : { status: r.status, error: r.error };
+ if (r.status !== "listed") onLog(`Browser listing: ${r.status} — ${r.error}\n`);
+ }
+ for (const t of targets) {
+ if (signal.aborted) break;
+ const r = await browserLookupVideo({
+ videoDir: path.join(paths.channelsDir, slug, "data", t.id),
+ pageUrl: t.url,
+ onLog,
+ signal,
+ ...(opts.requestedBy ? { requestedBy: opts.requestedBy } : {}),
+ ...(opts.deps ? { deps: opts.deps } : {}),
+ });
+ if ("error" in r) {
+ onLog(`${t.id}: ${r.status} — ${r.error}\n`);
+ summary.videos.push({ id: t.id, status: r.status, stored: false, error: r.error });
+ } else {
+ summary.videos.push({ id: t.id, status: r.status, stored: r.stored !== null });
+ }
+ }
+ onLog(`summary: ${JSON.stringify(summary)}\n`);
+ await opts.afterRun?.();
+ const good =
+ summary.videos.filter((v) => v.status === "written" || v.status === "patched" || v.status === "unchanged").length +
+ (summary.listing?.status === "listed" ? 1 : 0);
+ if (good === 0 && !signal.aborted) {
+ throw new Error("The browser lookup found nothing it could write.");
+ }
+ },
+ });
+}
+
+// The job log's last `summary:` line, parsed (the UI reads it back).
+export function browserLookupSummaryOf(log: string): BrowserLookupSummary | null {
+ const lines = log.split("\n").filter((l) => l.startsWith("summary: "));
+ const last = lines.at(-1);
+ if (!last) return null;
+ try {
+ return JSON.parse(last.slice("summary: ".length)) as BrowserLookupSummary;
+ } catch {
+ return null;
+ }
+}
diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts
@@ -47,6 +47,7 @@ import {
type StoredUrlWhy,
} from "../lib/storedMediaUrl";
import { storedMediaUrl } from "../lib/storedMediaUrl-server";
+import { newStoredPageSession } from "../ytdlp/storedUrlPageOpen";
import { readChannelConfig } from "./channels";
import { findVideoSourceUrl } from "./undownloadedVideos";
@@ -101,7 +102,10 @@ import { findVideoSourceUrl } from "./undownloadedVideos";
// `notAttempted` (and the run reports the stop). The backoff is still recorded
// (the lookup IS limited); a stored-URL success never records the platform
// clean; a 429 from the stored URL itself stops the run as any 429 does. Same
-// queue, same gaps.
+// queue, same gaps — plus, since release 32 R9, the platform's stored-URL rest
+// (jobs/storedUrlPace.ts, shared with full downloads) before a cut of a NEW
+// file, and the video's player page opened before its first cut in the run
+// (fetchWindowManaged, one page state per run).
//
// A JOB OF THIS KIND SPANS CHANNELS, so runManagedFunction's per-channel text
// guard has no channel to ask. It is asked here instead, once per channel: an
@@ -435,6 +439,10 @@ export async function fetchWindows({
const interrupted = (): FetchWindowsStop | null =>
signal?.aborted ? "cancel" : drainSignal?.aborted ? "drain" : null;
+ // THE RUN'S PAGE STATE for stored-URL cuts (release 32 R9): a video's page
+ // is opened before its first cut in this run, not before every window.
+ const pageSession = newStoredPageSession();
+
// Network attempts so far (the gap is owed before every one after the
// first), and the run of consecutive network-class failures.
let networkAttempts = 0;
@@ -636,7 +644,7 @@ export async function fetchWindows({
videoDir,
videoId: dirId,
videoUrl: url,
- ...(target ? { storedMedia: target } : {}),
+ ...(target ? { storedMedia: target, storedUrlCut: { pageSession } } : {}),
cwd: path.join(paths.channelsDir, item.slug),
from: item.from,
to: item.to,
diff --git a/common/controller/fetchWindowsStoredUrl.test.ts b/common/controller/fetchWindowsStoredUrl.test.ts
@@ -26,6 +26,9 @@ const ARGS_LOG = path.join(ROOT, "argv.jsonl");
const PROBES = path.join(ROOT, "probes");
process.env.FAKE_ARGS_LOG = ARGS_LOG;
process.env.FAKE_PROBES = PROBES;
+// Release 32 R9: a stored-URL cut of a new file waits out the platform's
+// stored-URL rest (20 min); the test-only knob makes the rest it sets 0.
+process.env.E2E_CLIP_WINDOW_GAP_MS = "0";
// The target decides: an odysee.com page (the lookup) answers 429, as the live
// lbry extractor did; a CDN file named `cdn429` answers 429 too; anything else
diff --git a/common/controller/laneStoredUrl.test.ts b/common/controller/laneStoredUrl.test.ts
@@ -0,0 +1,135 @@
+// The download lane takes a cooling or held platform's stored-URL videos
+// (release 32 R9): the channel's opt-in, the filter, the per-video memo, and
+// what a failed stored-URL unit does to the platform (nothing).
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/laneStoredUrl.test.ts
+
+import { 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";
+import { makeStoredUrlLaneMemo, storedUrlLaneMode, storedUrlRescue } from "./laneStoredUrl";
+import { applyUnitOutcome, type UnitOutcomeState } from "../jobs/unitOutcome";
+import { isVideoDeferred } from "../jobs/platformBackoff";
+import type { ChannelConfig } from "../lib/channelConfig";
+
+const cfg = (over: Partial<ChannelConfig>) => ({ handling: "transcribe", ...over }) as ChannelConfig;
+
+test("the opt-in: only/fallback, transcribe handling, a stored-URL platform", () => {
+ assert.equal(storedUrlLaneMode(cfg({ storedUrlDownloads: "only" }), "odysee"), "only");
+ assert.equal(storedUrlLaneMode(cfg({ storedUrlDownloads: "fallback" }), "odysee"), "fallback");
+ assert.equal(storedUrlLaneMode(cfg({ storedUrlDownloads: "never" }), "odysee"), null);
+ assert.equal(storedUrlLaneMode(cfg({}), "odysee"), null, "absent = never");
+ assert.equal(storedUrlLaneMode(cfg({ storedUrlDownloads: "only", handling: "youtube" }), "odysee"), null);
+ assert.equal(storedUrlLaneMode(cfg({ storedUrlDownloads: "only" }), "youtube"), null);
+});
+
+test("the filter keeps a skipped platform's opted-in videos that store a URL, and lists the unread", () => {
+ const owner = new Map([
+ ["o1", "ody"],
+ ["o2", "ody"],
+ ["o3", "ody"],
+ ["n1", "ody-plain"],
+ ["y1", "yt"],
+ ]);
+ const platforms: Record<string, string> = { ody: "odysee", "ody-plain": "odysee", yt: "youtube" };
+ const known: Record<string, boolean | undefined> = { o1: true, o2: false };
+ const r = storedUrlRescue({
+ pending: { leaf: ["o1", "o2", "o3", "n1", "y1"], other: ["o3"] },
+ owner,
+ platformSkip: new Set(["odysee"]),
+ rescuable: new Set(["odysee"]),
+ platformOf: (slug) => platforms[slug],
+ optedIn: (slug) => slug === "ody",
+ known: (_slug, id) => known[id],
+ });
+ assert.deepEqual(r.pending, { leaf: ["o1", "y1"], other: [] });
+ assert.deepEqual([...r.storedIds], ["o1"]);
+ assert.deepEqual(r.unknown, [{ slug: "ody", id: "o3" }], "once, though it is in two leaves");
+});
+
+test("a skipped platform that is not rescuable (busy, or its stored-URL rest not over) keeps nothing", () => {
+ const r = storedUrlRescue({
+ pending: { leaf: ["o1", "y1"] },
+ owner: new Map([
+ ["o1", "ody"],
+ ["y1", "yt"],
+ ]),
+ platformSkip: new Set(["odysee"]),
+ rescuable: new Set(),
+ platformOf: (slug) => (slug === "ody" ? "odysee" : "youtube"),
+ optedIn: () => true,
+ known: () => true,
+ });
+ assert.deepEqual(r.pending, { leaf: ["y1"] });
+ assert.equal(r.storedIds.size, 0);
+ assert.deepEqual(r.unknown, []);
+});
+
+test("the memo reads a record once, at most the limit per call, and a trusted URL reads true", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "lanestored-"));
+ const dir = (id: string) => path.join(root, "ody", "data", id);
+ await mkdir(dir("a"), { recursive: true });
+ await writeFile(
+ path.join(dir("a"), "metadata.info.json"),
+ JSON.stringify({
+ id: "a",
+ webpage_url: "https://odysee.com/@x:1/a:1",
+ formats: [{ format_id: "original", url: "https://player.odycdn.com/v6/streams/a/sd.mp4", protocol: "https" }],
+ }),
+ );
+ await mkdir(dir("b"), { recursive: true });
+ let reads = 0;
+ const memo = makeStoredUrlLaneMemo(async (d) => {
+ reads++;
+ const { storedMediaUrl } = await import("../lib/storedMediaUrl-server");
+ return storedMediaUrl(d);
+ });
+ const ids = [
+ { slug: "ody", id: "a" },
+ { slug: "ody", id: "b" },
+ { slug: "ody", id: "c" },
+ ];
+ assert.equal(await memo.probe(root, ids, 2), 2);
+ assert.equal(memo.known("ody", "a"), true);
+ assert.equal(memo.known("ody", "b"), false);
+ assert.equal(memo.known("ody", "c"), undefined, "past the limit: next tick");
+ assert.equal(await memo.probe(root, ids, 2), 1);
+ assert.equal(reads, 3, "each record read once");
+});
+
+const empty = (): UnitOutcomeState => ({
+ platformBackoff: {},
+ videoDeferrals: {},
+ platformPace: {},
+ platformHolds: {},
+ subtitleDeferrals: {},
+});
+
+test("a failed stored-URL unit: a CDN refusal defers the video and backs nothing off", () => {
+ const s = empty();
+ const now = 1_000_000;
+ const r = applyUnitOutcome(
+ s,
+ { platform: "odysee", videoId: "v1", channelSlug: "ody", outcome: "failed", failureClass: "rate_limit", viaStoredUrl: true },
+ now,
+ );
+ assert.equal(r.markCompleted, false);
+ assert.ok(isVideoDeferred(s.videoDeferrals, "v1", now + 1));
+ assert.deepEqual(s.platformBackoff, {}, "the platform is not backed off");
+ assert.deepEqual(s.platformPace, {});
+ assert.match(r.line ?? "", /stored media URL refused it \(rate_limit\).*odysee is not backed off/);
+});
+
+test("a failed stored-URL unit for any other reason retires the video, touching nothing", () => {
+ const s = empty();
+ const r = applyUnitOutcome(
+ s,
+ { platform: "odysee", videoId: "v2", channelSlug: "ody", outcome: "failed", failureClass: "per_video", viaStoredUrl: true },
+ 1_000_000,
+ );
+ assert.equal(r.markCompleted, true);
+ assert.deepEqual(s.platformBackoff, {});
+ assert.deepEqual(s.videoDeferrals, {});
+});
diff --git a/common/controller/laneStoredUrl.ts b/common/controller/laneStoredUrl.ts
@@ -0,0 +1,108 @@
+// THE DOWNLOAD LANE PICKS HELD-PLATFORM WORK FROM STORED URLS (release 32 R9).
+//
+// The lane drops every pending video of a platform that is cooling down or
+// held (autoRunner's platformSkip): asking the platform again would only earn
+// another 429. Release 32 R7 gave a download a way round the LOOKUP — the media
+// URL the record's metadata.info.json already stores, read the way the player
+// reads it — but the lane never offered such a video, so the held Odysee
+// backlog waited for the hold to lift.
+//
+// Now a channel that opted in (`storedUrlDownloads: "only" | "fallback"`,
+// transcribe handling, a STORED_URL_PLATFORMS platform) keeps the pending
+// videos of a cooling or held platform whose record stores a trusted URL —
+// and only when the platform is not busy and the platform's stored-URL rest
+// (jobs/storedUrlPace.ts, the gap shared with clip cuts) has elapsed, so the
+// lane takes one new file per rest. Such a unit downloads as `only` (no page
+// or API request: the lookup is the limited thing), `storedUrlHeld` on a held
+// platform, and settles nothing (viaStoredUrl, jobs/unitOutcome.ts).
+//
+// "Does the record store a URL" is a file read, so it is remembered per video
+// for the runner's life (a record's stored format does not change without a
+// new lookup, which is exactly what is not happening) and at most
+// STORED_URL_LANE_PROBES_PER_TICK unknown videos are read per tick; a video is
+// offered from the tick after its read.
+
+import path from "node:path";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { isStoredUrlPlatform, type StoredMediaUrl } from "../lib/storedMediaUrl";
+import { storedMediaUrl } from "../lib/storedMediaUrl-server";
+
+export const STORED_URL_LANE_PROBES_PER_TICK = 40;
+
+// The channel's stored-URL mode when the lane may take its videos past a
+// cooling or held platform, else null.
+export function storedUrlLaneMode(
+ config: Pick<ChannelConfig, "storedUrlDownloads" | "handling">,
+ platform: string | null | undefined,
+): "only" | "fallback" | null {
+ const mode = config.storedUrlDownloads;
+ if (mode !== "only" && mode !== "fallback") return null;
+ if (config.handling !== "transcribe") return null;
+ if (!isStoredUrlPlatform(platform)) return null;
+ return mode;
+}
+
+export type StoredUrlLaneMemo = {
+ // true / false once read; undefined = not read yet.
+ known(slug: string, id: string): boolean | undefined;
+ // Read up to `limit` of `ids` (unknown ones), remembering each answer.
+ probe(channelsDir: string, ids: ReadonlyArray<{ slug: string; id: string }>, limit?: number): Promise<number>;
+};
+
+export function makeStoredUrlLaneMemo(
+ read: (videoDir: string) => Promise<StoredMediaUrl | null> = storedMediaUrl,
+): StoredUrlLaneMemo {
+ const memo = new Map<string, boolean>();
+ const key = (slug: string, id: string) => `${slug}\0${id}`;
+ return {
+ known: (slug, id) => memo.get(key(slug, id)),
+ async probe(channelsDir, ids, limit = STORED_URL_LANE_PROBES_PER_TICK) {
+ const todo = ids.filter((x) => !memo.has(key(x.slug, x.id))).slice(0, limit);
+ await Promise.all(
+ todo.map(async ({ slug, id }) => {
+ const s = await read(path.join(channelsDir, slug, "data", id)).catch(() => null);
+ memo.set(key(slug, id), s !== null);
+ }),
+ );
+ return todo.length;
+ },
+ };
+}
+
+// THE FILTER (pure): which skipped videos stay pending because they can be
+// downloaded from their stored URL. `rescuable` = the platforms skipped ONLY
+// for a cooldown or a hold (not busy) whose stored-URL rest has elapsed.
+export function storedUrlRescue(args: {
+ pending: Record<string, string[]>;
+ owner: ReadonlyMap<string, string>;
+ platformSkip: ReadonlySet<string>;
+ rescuable: ReadonlySet<string>;
+ platformOf: (slug: string) => string;
+ optedIn: (slug: string) => boolean;
+ known: (slug: string, id: string) => boolean | undefined;
+}): { pending: Record<string, string[]>; storedIds: Set<string>; unknown: { slug: string; id: string }[] } {
+ const storedIds = new Set<string>();
+ const unknown: { slug: string; id: string }[] = [];
+ const seenUnknown = new Set<string>();
+ const out: Record<string, string[]> = {};
+ for (const [leafId, ids] of Object.entries(args.pending)) {
+ out[leafId] = ids.filter((id) => {
+ const slug = args.owner.get(id);
+ if (!slug) return true;
+ const pf = args.platformOf(slug);
+ if (!args.platformSkip.has(pf)) return true;
+ if (!args.rescuable.has(pf) || !args.optedIn(slug)) return false;
+ const k = args.known(slug, id);
+ if (k === true) {
+ storedIds.add(id);
+ return true;
+ }
+ if (k === undefined && !seenUnknown.has(id)) {
+ seenUnknown.add(id);
+ unknown.push({ slug, id });
+ }
+ return false;
+ });
+ }
+ return { pending: out, storedIds, unknown };
+}
diff --git a/common/controller/odyseeBrowserListing.test.ts b/common/controller/odyseeBrowserListing.test.ts
@@ -0,0 +1,103 @@
+// A channel's listing from its page in a (fake) browser, and the browser
+// lookup job's door (release 32 R9). No browser: testing/web/fakeOdyseePage.mjs.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/odyseeBrowserListing.test.ts
+
+import { test, beforeEach } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { browserListChannel, browserListingRefusal } from "./odyseeBrowserListing";
+import { browserLookupSummaryOf, runBrowserLookupJob } from "./browserLookupJob";
+import { clearPlatformGaps } from "../jobs/platformGap";
+import {
+ channelPageRead,
+ channelUrlOf,
+ fakePageReader,
+ pageUrlOf,
+ syntheticChannel,
+ syntheticClaim,
+} from "../testing/web/fakeOdyseePage.mjs";
+import type { ChannelConfig } from "../lib/channelConfig";
+import type { Paths } from "../lib/paths";
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "browserlisting-"));
+const ch = syntheticChannel({ name: "@synthchan", title: "Synth Channel" });
+const show1 = syntheticClaim({ name: "show-1", title: "SynthShow - 1", channel: ch, releaseTime: 1700000000 });
+const show2 = syntheticClaim({ name: "show-2", title: "SynthShow - 2", channel: ch, releaseTime: 1700200000 });
+const vlog = syntheticClaim({ name: "vlog", title: "A vlog", channel: ch, releaseTime: 1700100000 });
+const stranger = syntheticClaim({ name: "theirs", title: "SynthShow - not ours", channel: syntheticChannel({ name: "@other" }) });
+const signal = new AbortController().signal;
+const noLog = () => {};
+
+let n = 0;
+async function channel(config: Partial<ChannelConfig>, playlist?: string[]) {
+ const channelsDir = path.join(ROOT, `case-${++n}`, "channels");
+ const slug = "synth";
+ await mkdir(path.join(channelsDir, slug), { recursive: true });
+ const cfg = { handling: "transcribe", platform: "odysee", url: channelUrlOf(ch), ...config } as ChannelConfig;
+ await writeFile(path.join(channelsDir, slug, "config.json"), JSON.stringify(cfg));
+ if (playlist) await writeFile(path.join(channelsDir, slug, "playlist"), playlist.join("\n") + "\n");
+ return { paths: { channelsDir } as Paths, slug, cfg, root: path.join(channelsDir, slug) };
+}
+
+beforeEach(() => clearPlatformGaps());
+
+test("the listing adds the page's own new uploads at the top of the playlist, newest first, and to the roster", async () => {
+ const c = await channel({}, [pageUrlOf(show1)]);
+ const reader = fakePageReader({ [channelUrlOf(ch)]: channelPageRead({ channel: ch, pages: [[show2, stranger], [vlog, show1]] }) });
+ const r = await browserListChannel({
+ paths: c.paths,
+ slug: c.slug,
+ config: c.cfg,
+ scrolls: 2,
+ skipLiveDownloads: true,
+ onLog: noLog,
+ signal,
+ deps: { reader, gapMs: 0 },
+ });
+ assert.equal(r.status, "listed");
+ assert.ok(r.status === "listed" && r.seen === 3 && r.added.length === 2);
+ const playlist = (await readFile(path.join(c.root, "playlist"), "utf8")).trim().split("\n");
+ assert.deepEqual(playlist, [pageUrlOf(show2), pageUrlOf(vlog), pageUrlOf(show1)], "new first, nothing removed");
+ const roster = JSON.parse(await readFile(path.join(c.root, "roster.json"), "utf8"));
+ assert.ok(JSON.stringify(roster).includes(show2.claim_id));
+ assert.equal(reader.calls[0].scrolls, 2);
+});
+
+test("the channel's title match filter decides what is listed", async () => {
+ const c = await channel({ ytdlpExtraArgs: ["--match-filters=title~='SynthShow'"] });
+ const reader = fakePageReader({ "*": channelPageRead({ channel: ch, pages: [[show2, vlog, show1]] }) });
+ const r = await browserListChannel({ paths: c.paths, slug: c.slug, config: c.cfg, skipLiveDownloads: true, onLog: noLog, signal, deps: { reader, gapMs: 0 } });
+ assert.ok(r.status === "listed" && r.filtered === 1);
+ const playlist = (await readFile(path.join(c.root, "playlist"), "utf8")).trim().split("\n");
+ assert.deepEqual(playlist, [pageUrlOf(show2), pageUrlOf(show1)]);
+});
+
+test("refused before anything opens: not Odysee, no @channel, an unreadable match filter", async () => {
+ assert.match(browserListingRefusal({ url: "https://www.youtube.com/@x" } as ChannelConfig) ?? "", /Odysee|odysee/);
+ assert.match(browserListingRefusal({ url: "https://odysee.com/some-stream:abc" } as ChannelConfig) ?? "", /@channel/);
+ assert.match(
+ browserListingRefusal({ url: channelUrlOf(ch), ytdlpExtraArgs: ["--match-filter", "duration>600"] } as ChannelConfig) ?? "",
+ /cannot be applied/,
+ );
+ assert.equal(browserListingRefusal({ url: channelUrlOf(ch) } as ChannelConfig), null);
+});
+
+test("the job's door: nothing named, too many, an id with no Odysee page", async () => {
+ const c = await channel({}, [pageUrlOf(show1)]);
+ const base = { paths: c.paths, slug: c.slug, channelConfig: c.cfg, skipLiveDownloads: true };
+ assert.equal((await runBrowserLookupJob({ ...base })).ok, false);
+ const many = await runBrowserLookupJob({ ...base, videoIds: Array.from({ length: 51 }, (_, i) => `v${i}`) });
+ assert.match((many as { error: string }).error, /At most 50/);
+ const yt = await channel({ platform: "youtube", url: "https://www.youtube.com/@synth" } as Partial<ChannelConfig>);
+ const notOdysee = await runBrowserLookupJob({ paths: yt.paths, slug: yt.slug, channelConfig: yt.cfg, skipLiveDownloads: true, videoIds: ["abcdefghijk"] });
+ assert.match((notOdysee as { error: string }).error, /No Odysee page URL for abcdefghijk/);
+});
+
+test("the summary line reads back", () => {
+ const log = `x\nsummary: {"videos":[{"id":"a","status":"written","stored":true}]}\n`;
+ assert.deepEqual(browserLookupSummaryOf(log), { videos: [{ id: "a", status: "written", stored: true }] });
+ assert.equal(browserLookupSummaryOf("nothing"), null);
+});
diff --git a/common/controller/odyseeBrowserListing.ts b/common/controller/odyseeBrowserListing.ts
@@ -0,0 +1,161 @@
+// A CHANNEL'S LISTING FROM ITS PAGE, IN A BROWSER (release 32 R9).
+//
+// yt-dlp's lbry listing (`--flat-playlist` of the channel URL) is a
+// `claim_search` through Odysee's API, and on 2026-10-16/17 it answered 429
+// where the channel page, loaded by a browser, answered 200. This opens the
+// channel page (ytdlp/odyseePageReader.ts), scrolls it a bounded number of
+// times so it lists more uploads, and reads the uploads out of the page's own
+// `claim_search` answers (lib/odyseePageApi.ts listingFromResponses) as the
+// page URLs yt-dlp's listing prints.
+//
+// ADD-ONLY. A page shows the newest uploads, not the whole channel, so this
+// never decides that something LEFT the listing: the ids join the roster as a
+// sighting (mergeRosterFile, source "listing" — the paged sync's call), and
+// the ones `playlist` does not hold yet are put at its top, newest first,
+// ahead of everything already there. Nothing is removed and nothing is
+// downloaded: the download lane and download-missing see them as undownloaded
+// as they see any listed video. Serialised with the channel's sync and
+// downloads by the job's queue (the platform's download queue).
+//
+// FILTERED AS yt-dlp's LISTING WOULD BE: a channel whose `ytdlpExtraArgs` carry
+// a `--match-filter` lists only the matching titles through yt-dlp; here the
+// readable form (`title~='<regex>'`) is applied, and an unreadable one refuses
+// the listing (ytdlp/odyseeBrowserLookup.ts browserLookupDecision). The app's
+// download filters apply too.
+
+import path from "node:path";
+import { readFile } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { detectPlatform } from "../lib/platform";
+import { extractVideoId } from "../lib/videoId";
+import { writeFileAtomic } from "../lib/jsonFile-server";
+import {
+ channelClaimFor,
+ listingFromResponses,
+ odyseeInfoFromClaim,
+ odyseePageRef,
+} from "../lib/odyseePageApi";
+import { notePlatformGap, platformGapRemainingMs, waitForPlatformGap } from "../jobs/platformGap";
+import {
+ BROWSER_LOOKUP_PLATFORMS,
+ browserLookupDecision,
+ browserLookupGapKey,
+ browserLookupGapMs,
+ type BrowserLookupDeps,
+} from "../ytdlp/odyseeBrowserLookup";
+import { readOdyseePage } from "../ytdlp/odyseePageReader";
+import { mergeRosterFile, observationsFromUrls } from "./rosterStore";
+
+export const BROWSER_LISTING_DEFAULT_SCROLLS = 5;
+
+export type BrowserListingResult =
+ | { status: "listed"; seen: number; filtered: number; added: string[] }
+ | { status: "refused" | "unreadable" | "not-found"; error: string };
+
+// Before anything is opened: the channel's URL is an Odysee channel page, and
+// its match filter (if any) is one a browser listing can apply.
+export function browserListingRefusal(config: ChannelConfig): string | null {
+ const url = config.url ?? "";
+ const platform = detectPlatform(url);
+ if (!platform || !BROWSER_LOOKUP_PLATFORMS.includes(platform)) {
+ return `A browser listing is for ${BROWSER_LOOKUP_PLATFORMS.join(", ")} channels; this channel's URL is ${url || "unset"}.`;
+ }
+ if (!odyseePageRef(url).channel) return `The channel URL (${url}) names no @channel page.`;
+ const probe = browserLookupDecision(config, { title: "" }, { skipLiveDownloads: false });
+ if (!probe.ok && !probe.skip) return `Not listed: ${probe.reason}.`;
+ return null;
+}
+
+export async function browserListChannel(opts: {
+ paths: Paths;
+ slug: string;
+ config: ChannelConfig;
+ scrolls?: number;
+ skipLiveDownloads: boolean;
+ onLog: (s: string) => void;
+ signal: AbortSignal;
+ deps?: BrowserLookupDeps;
+}): Promise<BrowserListingResult> {
+ const { paths, slug, config, onLog, signal } = opts;
+ const refusal = browserListingRefusal(config);
+ if (refusal) return { status: "refused", error: refusal };
+ const pageUrl = config.url!;
+ const platform = detectPlatform(pageUrl)!;
+ const ref = odyseePageRef(pageUrl);
+ const key = browserLookupGapKey(platform);
+ const gapMs = opts.deps?.gapMs ?? browserLookupGapMs(platform);
+ try {
+ await waitForPlatformGap({
+ label: `A browser listing (${platform})`,
+ remainingMs: () => platformGapRemainingMs(key),
+ signal,
+ onLog: (line) => onLog(`${line}\n`),
+ ...(opts.deps?.sleep ? { sleep: opts.deps.sleep } : {}),
+ });
+ } catch {
+ return { status: "unreadable", error: "cancelled while waiting for the gap between browser lookups" };
+ }
+ notePlatformGap(key, gapMs);
+ const reader = opts.deps?.reader ?? readOdyseePage;
+ let read;
+ try {
+ read = await reader({ pageUrl, signal, onLog, scrolls: opts.scrolls ?? BROWSER_LISTING_DEFAULT_SCROLLS });
+ } finally {
+ notePlatformGap(key, gapMs);
+ }
+ if (!read.ok && read.responses.length === 0) {
+ return { status: "unreadable", error: `the channel page could not be read (${read.error ?? "no API answer"})` };
+ }
+ // The channel's claim id: the page's resolve of `@name`, else the URL's own.
+ const fromUrl = (() => {
+ try {
+ const seg = decodeURIComponent(new URL(pageUrl).pathname).split("/").find((s) => s.startsWith("@")) ?? "";
+ const m = /[:#]([0-9a-f]{40})$/.exec(seg);
+ return m ? m[1] : null;
+ } catch {
+ return null;
+ }
+ })();
+ const channelClaim = ref.channel ? channelClaimFor(read.responses, ref.channel) : null;
+ const listing = listingFromResponses(read.responses, {
+ claimId: channelClaim?.claimId ?? fromUrl,
+ name: ref.channel,
+ });
+ if (listing.length === 0) {
+ return { status: "not-found", error: `the channel page's API answers (${read.responses.length}) list no uploads of ${ref.channel}` };
+ }
+ let filtered = 0;
+ const kept: string[] = [];
+ for (const { url, claim } of listing) {
+ const info = odyseeInfoFromClaim(claim, { pageUrl: url, streamingUrl: null });
+ const d = browserLookupDecision(config, info, { skipLiveDownloads: opts.skipLiveDownloads });
+ if (d.ok) kept.push(url);
+ else filtered++;
+ }
+
+ const root = path.join(paths.channelsDir, slug);
+ const playlistPath = path.join(root, "playlist");
+ const existing = (await readFile(playlistPath, "utf8").catch(() => ""))
+ .split("\n")
+ .map((s) => s.trim())
+ .filter(Boolean);
+ const have = new Set(existing.map((u) => extractVideoId(u)).filter((id): id is string => Boolean(id)));
+ const added = kept.filter((u) => {
+ const id = extractVideoId(u);
+ return id !== null && !have.has(id);
+ });
+ if (added.length > 0) {
+ const next = [...added, ...existing];
+ await writeFileAtomic(playlistPath, next.join("\n") + "\n", { mkdir: true });
+ }
+ if (kept.length > 0) {
+ await mergeRosterFile(paths, slug, observationsFromUrls(kept), new Date().toISOString(), "listing");
+ }
+ onLog(
+ `Browser listing of ${ref.channel}: ${listing.length} upload(s) on the page` +
+ (filtered ? `, ${filtered} declined by the channel's filters` : "") +
+ `, ${added.length} new to the playlist.\n`,
+ );
+ return { status: "listed", seen: listing.length, filtered, added };
+}
diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts
@@ -95,6 +95,8 @@ const ADDED_KINDS: Record<string, { label: string; drainable: boolean }> = {
"fetch-windows": { label: "Fetch windows", drainable: true },
// One video's metadata re-read: one spawn, cancelled rather than drained.
"refresh-metadata": { label: "Refresh metadata", drainable: false },
+ // An Odysee record or listing read from its page in a browser: page by page.
+ "browser-lookup": { label: "Browser lookup", drainable: false },
// One file through a local worker (pnpm ops transcribe): one engine run.
"transcribe-file": { label: "Transcribe file", drainable: false },
// One synthesis (pnpm ops tts): one engine run, or a cache hit.
@@ -167,6 +169,7 @@ const TEXT_KINDS = [
"evict-clips",
"metadata-scan",
"refresh-metadata",
+ "browser-lookup",
"download-missing-subs",
"check-availability",
"quick-availability-check",
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -681,6 +681,22 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
needsMedia: false,
needsText: true,
},
+ // An Odysee video's record (or the channel's listing) read from its page in
+ // a headless browser (release 32 R9, controller/browserLookupJob.ts), when
+ // yt-dlp's lookup is refused. On the platform download queue, so it never
+ // runs beside a download or a sync of that platform; `needsText`: it writes
+ // metadata.info.json, the playlist and the roster, no media. Not drainable
+ // (each page is ~20 s); replayable (the spec carries the ids and the listing
+ // flag).
+ "browser-lookup": {
+ kind: "browser-lookup",
+ label: "Browser lookup",
+ drainable: false,
+ replayable: true,
+ queueKeyStrategy: "platform",
+ needsMedia: false,
+ needsText: true,
+ },
// THE HUB'S AND THE HOMEPAGE'S BUILD AND DEPLOY (release 13 slice W1). They
// ran from /sites — the hub since release 7, the homepage since release 11 —
// with no entry here, so /jobs showed their raw machine kinds. The labels
diff --git a/common/jobs/storedUrlPace.ts b/common/jobs/storedUrlPace.ts
@@ -0,0 +1,63 @@
+// ONE PACING STATE FOR A PLATFORM'S STORED-URL FILES (release 32 R9).
+//
+// Odysee's CDN allows one new original file per rest (measured 2026-10-16: the
+// next file a minute later answered 429). Release 32 R7 spaced full downloads
+// from the stored media URL by STORED_URL_NEW_FILE_GAP_MS under the platformGap
+// key `stored-url:<platform>`; the clip cut kept only the clip gap
+// (`clip-window:<platform>`, 30 s), so a cut and a download minutes apart were
+// two new files inside one rest. Now both read the SAME state:
+//
+// - a full download always waits out the gap (it is a whole file);
+// - a clip cut waits it out unless the last stored-URL read on the platform
+// was the SAME file (two windows of one video are one file, already
+// unlocked by its page open) — a cut of a new file waits like a download;
+// - both note the gap at their start and their end, and remember the file.
+//
+// In memory and process-wide (on globalThis, as platformGap.ts is): a restart
+// is itself a gap.
+
+import { notePlatformGap, platformGapRemainingMs } from "./platformGap";
+import { storedUrlGapKey } from "../lib/storedMediaUrl";
+
+declare global {
+ // eslint-disable-next-line no-var
+ var __yttStoredUrlLastFile__: Map<string, string> | undefined;
+}
+
+function lastFiles(): Map<string, string> {
+ if (!globalThis.__yttStoredUrlLastFile__) globalThis.__yttStoredUrlLastFile__ = new Map();
+ return globalThis.__yttStoredUrlLastFile__;
+}
+
+// The URL of the last stored-URL file read on `platform` in this process.
+export function storedUrlLastFile(platform: string): string | null {
+ return lastFiles().get(storedUrlGapKey(platform)) ?? null;
+}
+
+// Milliseconds before a stored-URL read of `url` on `platform` may start.
+// `sameFileFree`: a read of the file read last owes no gap (the clip cut).
+export function storedUrlGapRemainingMs(
+ platform: string,
+ opts: { url?: string; sameFileFree?: boolean } = {},
+ now: number = Date.now(),
+): number {
+ if (opts.sameFileFree && opts.url && storedUrlLastFile(platform) === opts.url) return 0;
+ return platformGapRemainingMs(storedUrlGapKey(platform), now);
+}
+
+// A stored-URL read of `url` on `platform` started or ended at `now`: the next
+// new file waits `gapMs` from now (never shortened), and this is the last file.
+export function noteStoredUrlRead(
+ platform: string,
+ url: string,
+ gapMs: number,
+ now: number = Date.now(),
+): void {
+ notePlatformGap(storedUrlGapKey(platform), gapMs, now);
+ lastFiles().set(storedUrlGapKey(platform), url);
+}
+
+// Tests only.
+export function clearStoredUrlFiles(): void {
+ lastFiles().clear();
+}
diff --git a/common/jobs/unitOutcome.ts b/common/jobs/unitOutcome.ts
@@ -20,7 +20,9 @@
// - a success through the record's stored media URL (release 32 R7,
// `viaStoredUrl`) retires the video and settles nothing: the platform was
// not asked. One whose page lookup was rate-limited first comes in as a
-// `rate_limit` and backs the platform off like any other.
+// `rate_limit` and backs the platform off like any other. A stored-URL unit
+// that FAILED (release 32 R9, picked past a cooling or held platform) moves
+// nothing either: a CDN refusal defers the video, anything else retires it.
//
// Release 17, slice RL (see platformBackoff.ts, "The adaptive pace"):
// - `rate_limit` also doubles the platform's pace, and a backoff that has
@@ -94,6 +96,24 @@ export function applyUnitOutcome(
pruneSubtitleDeferrals(state.subtitleDeferrals, now);
decayPaceByTime(state.platformPace, now);
const pf = unit.platform;
+ if (pf !== null && unit.viaStoredUrl && unit.outcome === "failed") {
+ // A STORED-URL UNIT THAT FAILED (release 32 R9: the lane picked it past a
+ // cooling or held platform, `only`). The platform was not asked, so its
+ // backoff, hold and pace stay as they are. A refusal from the CDN defers
+ // the video (the stored-URL rest spaces the next file anyway); anything
+ // else retires it for the session.
+ if (unit.failureClass === "rate_limit" || unit.failureClass === "network") {
+ deferVideo(state.videoDeferrals, unit.videoId, unit.channelSlug, now);
+ return {
+ markCompleted: false,
+ line: `Auto-download: ${unit.videoId}'s stored media URL refused it (${unit.failureClass}) — deferred 6h; ${pf} is not backed off by it.`,
+ };
+ }
+ return {
+ markCompleted: true,
+ line: `Auto-download: ${unit.videoId} from its stored media URL failed (${unit.failureClass ?? "unknown"}); ${pf} is not touched.`,
+ };
+ }
if (
pf !== null &&
(unit.failureClass === "rate_limit" || unit.failureClass === "network")
diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts
@@ -152,6 +152,9 @@ export type ChannelConfig = {
// Release 32 R7: whether a full download may read the record's stored media
// URL (lib/storedMediaUrl.ts) the way the platform's player does.
storedUrlDownloads?: StoredUrlMode;
+ // Release 32 R9: when yt-dlp's lookup is refused, read a video's metadata
+ // from its page in a headless browser (ytdlp/odyseeBrowserLookup.ts).
+ browserLookup?: boolean;
recordedDate?: RecordedDateRule;
mirror?: MirrorConfig;
};
@@ -214,6 +217,8 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
"Audio-integrity checking for sources that intermittently serve corrupt audio mid-download: the managed downloader periodically validates the in-progress `.part` file and rolls back to the last known-good snapshot on corruption (transcribe handling), and a clip window gets the same final probe, fetched once more when malformed and never kept when malformed twice. ON BY DEFAULT for an Odysee video (`audioCheck: {\"enabled\": false}` turns it off); the channel's opt-in for any other platform.",
storedUrlDownloads:
'Whether a full download (transcribe handling) reads the media URL the record\'s `metadata.info.json` already stores, the way the platform\'s own player reads it — ranged requests with the page\'s Referer and Origin, no yt-dlp — through the same audio check. `"never"` (the default: the page, as always), `"fallback"` (the page first; on a rate limit, or a held platform, the stored URL) or `"only"` (the stored URL and no page request; a video without one fails, asking nothing). Odysee only (its CDN hosts). Two such downloads on one platform are at least 20 minutes apart: the CDN allows one new file per rest. A request\'s own `storedUrl` overrides it.',
+ browserLookup:
+ "`true`, with `storedUrlDownloads` `fallback` or `only`: when a video's record stores no media URL — `only`, or a `fallback` whose yt-dlp lookup was refused (a 429) — the managed download opens the video's page in a headless browser, reads the record from the page's own API answers and writes `metadata.info.json` (marked `_source: \"browser\"`), then downloads from the media URL the page named. Odysee only; one page a minute; the channel's `--match-filter title~='…'` and download filters still decide. Absent = off. The video page's **Read from the page** and the channel's **List from the page** ask for it once, whatever this says.",
recordedDate:
"For a channel that MIRRORS another's streams (a VOD archive): how to read the date a video was RECORDED from its title, since its `upload_date` is the date of the copy. The index stores the result as the record's `recordedDate` (`YYYYMMDD`), which coverage reads before the upload date. A title it does not match, a date that is not a real day, or one after the upload date gives none. Changing the rule re-derives the channel's records on the next index build. An object without a usable `titlePattern` is dropped.",
mirror:
@@ -422,6 +427,7 @@ export const CHANNEL_CONFIG_COERCIONS: {
: undefined,
audioCheck: coerceAudioCheck,
storedUrlDownloads: (v) => (isStoredUrlMode(v) ? v : undefined),
+ browserLookup: (v) => (v === true ? true : undefined),
recordedDate: coerceRecordedDateRule,
mirror: coerceMirrorConfig,
};
diff --git a/common/lib/channelConfigSchema.test.ts b/common/lib/channelConfigSchema.test.ts
@@ -39,7 +39,7 @@ test("one key list: docs = coercions = schema shape, sync-state keys inside it",
assert.deepEqual(Object.keys(CHANNEL_CONFIG_COERCIONS), [...CHANNEL_CONFIG_KEYS]);
assert.deepEqual(Object.keys(channelConfigObjectSchema.shape), [...CHANNEL_CONFIG_KEYS]);
assert.deepEqual(Object.keys(CHANNEL_CONFIG_FIELD_DOCS), [...CHANNEL_CONFIG_KEYS]);
- assert.equal(CHANNEL_CONFIG_KEYS.length, 35);
+ assert.equal(CHANNEL_CONFIG_KEYS.length, 36);
assert.equal(sameKeys, true);
assert.equal(fits, true);
for (const k of CHANNEL_SYNC_STATE_KEYS) assert.ok(CHANNEL_CONFIG_KEYS.includes(k), k);
diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts
@@ -76,6 +76,7 @@ export const channelConfigObjectSchema = z.object({
sleepBetweenDownloadsSeconds: field("sleepBetweenDownloadsSeconds"),
audioCheck: field("audioCheck"),
storedUrlDownloads: field("storedUrlDownloads"),
+ browserLookup: field("browserLookup"),
recordedDate: field("recordedDate"),
mirror: field("mirror"),
});
diff --git a/common/lib/clipWindow.ts b/common/lib/clipWindow.ts
@@ -160,6 +160,10 @@ export type ClipProvenance = {
// window fetched through the page.
source?: ClipWindowSource;
sourceHost?: string;
+ // How many times the player's page was opened for this window's cut (release
+ // 32 R9, ytdlp/storedUrlPageOpen.ts): a stored-URL cut opens it before the
+ // first cut of each video in a run. Absent when none was.
+ pageOpens?: number;
// WHICH COPY a window of a gone recording was fetched from (release 29 E2,
// publish/findCopy.ts): a Wayback Machine capture of its page, or an
// archive.org mirror's file — and its URL. Absent when the window came from
@@ -228,6 +232,8 @@ export function parseClipProvenance(raw: unknown): ClipProvenance | null {
}
const sourceHost = str(r.sourceHost);
if (sourceHost) out.sourceHost = sourceHost;
+ const pageOpens = num(r.pageOpens);
+ if (pageOpens !== undefined && pageOpens > 0) out.pageOpens = pageOpens;
const copy = coerceClipCopy(r.copy);
if (copy) out.copy = copy;
const ac = r.audioCheck as { verdict?: unknown; attempts?: unknown } | undefined;
diff --git a/common/lib/envVars.test.ts b/common/lib/envVars.test.ts
@@ -23,8 +23,10 @@ const SKIP_DIRS = new Set(["node_modules", ".next", "out", "out-private", "publi
// Playwright (TEST_WORKER_INDEX, which it sets in each worker process; the
// two-origin config reads it to stage only in the runner — and
// TEST_PARALLEL_INDEX, the worker's slot, which the editor suite reads to find
-// its own servers and data root).
-const PLATFORM = new Set(["CI", "NODE_ENV", "NEXT_RUNTIME", "LD_LIBRARY_PATH", "PATH", "HOME", "NODE_OPTIONS", "TEST_WORKER_INDEX", "TEST_PARALLEL_INDEX"]);
+// its own servers and data root), and node's test runner (NODE_TEST_CONTEXT,
+// set in each test file's process; the player-page opener never launches a
+// browser under it).
+const PLATFORM = new Set(["CI", "NODE_ENV", "NEXT_RUNTIME", "LD_LIBRARY_PATH", "PATH", "HOME", "NODE_OPTIONS", "TEST_WORKER_INDEX", "TEST_PARALLEL_INDEX", "NODE_TEST_CONTEXT"]);
function codeFiles(): string[] {
const out: string[] = [];
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -217,7 +217,8 @@ const DECLARED: EnvVarDecl[] = [
{ name: "E2E_AUDIO_CHECK_RECOVER_STEP_MS", audience: "test", default: "the real step", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "Likewise, the recovery step." },
{ name: "E2E_AUDIO_CHECK_RECOVER_AFTER", audience: "test", default: "the real count", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "Likewise, the recovery count." },
{ name: "E2E_BACKOFF_BASE_MS", audience: "test", default: "`60000` (the real base)", readBy: "common/jobs/platformBackoff.ts", doc: "The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse." },
- { name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts", doc: "The pause between two clip-window fetches in one batch. The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." },
+ { name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts", doc: "The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." },
+ { name: "E2E_ODYSEE_PAGE_FIXTURE", audience: "test", default: "unset (a headless browser)", readBy: "common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts", doc: "A JSON file of recorded Odysee page reads keyed by page URL (`\"*\"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`)." },
{ name: "E2E_BLUESKY_ORIGIN_FILE", audience: "test", default: "unset (the real Bluesky)", readBy: "common/social/blueskyEndpoints.ts", doc: "A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored." },
{ name: "E2E_AUDIO_CHECK_DEBUG_PAUSE_MS", audience: "test", default: "off", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "A debugging pause inside the audio check." },
{ name: "E2E_FAKE_YTDLP_AUDIO_CHECK_MODE", audience: "test", default: "—", readBy: "editor/e2e/fixtures/bin/fake-ytdlp.mjs", doc: "Fake yt-dlp: which audio-check scenario to act out." },
diff --git a/common/lib/metadataHistory.ts b/common/lib/metadataHistory.ts
@@ -82,6 +82,10 @@ export const METADATA_HISTORY_WRITERS = [
// controller/attachMedia.ts `createRecords`): the folder's own yt-dlp
// .info.json, or one built from its description.txt / source.txt and name.
"local-archive",
+ // An Odysee record completed from its page's own API answers in a headless
+ // browser (release 32 R9, ytdlp/odyseeBrowserLookup.ts), when yt-dlp's lookup
+ // is refused: only the keys the file lacks, and the one stored format.
+ "browser-lookup",
] as const;
export type MetadataHistoryWriter = (typeof METADATA_HISTORY_WRITERS)[number];
diff --git a/common/lib/odyseePageApi.test.ts b/common/lib/odyseePageApi.test.ts
@@ -0,0 +1,105 @@
+// Reading an Odysee record out of a page's own API answers (release 32 R9),
+// over synthetic answers in the LBRY SDK's shape (testing/web/fakeOdyseePage.mjs).
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/odyseePageApi.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ claimForPage,
+ claimsFromResponses,
+ isOdyseeApiUrl,
+ listingFromResponses,
+ odyseeInfoFromClaim,
+ odyseePageRef,
+ originalFileUrl,
+ streamingUrlFor,
+ channelClaimFor,
+} from "./odyseePageApi";
+import { storedMediaUrlFromInfo } from "./storedMediaUrl";
+import {
+ cdnUrlOf,
+ channelPageRead,
+ pageUrlOf,
+ refusedAnswer,
+ syntheticChannel,
+ syntheticClaim,
+ videoPageRead,
+} from "../testing/web/fakeOdyseePage.mjs";
+
+const ch = syntheticChannel({ name: "@synthchan", title: "Synth Channel" });
+const v1 = syntheticClaim({ name: "first-stream", title: "First Stream", channel: ch, releaseTime: 1700000000, duration: 4321 });
+const v2 = syntheticClaim({ name: "second-stream", title: "Second Stream", channel: ch, releaseTime: 1700100000 });
+const other = syntheticClaim({ name: "recommended", title: "Someone Else", channel: syntheticChannel({ name: "@other" }) });
+
+test("the API hosts, and nothing else", () => {
+ assert.ok(isOdyseeApiUrl("https://api.na-backend.odysee.com/api/v1/proxy?m=resolve"));
+ assert.ok(isOdyseeApiUrl("https://api.odysee.com/file/view_count"));
+ assert.ok(isOdyseeApiUrl("https://api.lbry.tv/api/v1/proxy"));
+ assert.ok(!isOdyseeApiUrl("https://player.odycdn.com/v6/streams/x/y.mp4"));
+ assert.ok(!isOdyseeApiUrl("https://odysee.com/@x"));
+ assert.ok(!isOdyseeApiUrl("not a url"));
+});
+
+test("claims come out of resolve, claim_search and bare answers; a refusal adds nothing", () => {
+ const read = videoPageRead({ claim: v1, related: [other, v2] });
+ const claims = claimsFromResponses([...read.responses, refusedAnswer("resolve")]);
+ assert.deepEqual([...claims.keys()].sort(), [v1.claim_id, v2.claim_id, other.claim_id].sort());
+});
+
+test("the page's claim: by the URL's claim id (full or a prefix), never 'the only one'", () => {
+ const claims = claimsFromResponses(videoPageRead({ claim: v1, related: [other] }).responses);
+ assert.equal(claimForPage(claims, pageUrlOf(v1))?.claim_id, v1.claim_id);
+ assert.equal(claimForPage(claims, `https://odysee.com/first-stream:${v1.claim_id.slice(0, 3)}`)?.claim_id, v1.claim_id);
+ assert.equal(claimForPage(claims, "https://odysee.com/first-stream")?.claim_id, v1.claim_id, "by name, one match");
+ assert.equal(claimForPage(claims, "https://odysee.com/not-here:abc")?.claim_id, undefined);
+ assert.deepEqual(odyseePageRef(`https://odysee.com/@synthchan:5/first-stream:${v1.claim_id}`), {
+ name: "first-stream",
+ claimRef: v1.claim_id,
+ channel: "@synthchan",
+ });
+});
+
+test("the file: the get answer's streaming_url, else the player's CDN request; v3 for an /api/ path", () => {
+ const read = videoPageRead({ claim: v1 });
+ assert.equal(streamingUrlFor(v1.claim_id, read.responses, read.mediaUrls), cdnUrlOf(v1));
+ const noGet = videoPageRead({ claim: v1, get: false });
+ assert.equal(streamingUrlFor(v1.claim_id, noGet.responses, noGet.mediaUrls), cdnUrlOf(v1), "the CDN request, query dropped");
+ assert.equal(streamingUrlFor(v1.claim_id, noGet.responses, []), null);
+ assert.equal(originalFileUrl("https://cdn.example/api/v4/streams/free/x/y"), "https://cdn.example/api/v3/streams/free/x/y");
+});
+
+test("the record yt-dlp would write, marked _source: browser, and the stored-URL reader trusts it", () => {
+ const info = odyseeInfoFromClaim(v1, { pageUrl: pageUrlOf(v1), streamingUrl: cdnUrlOf(v1), at: "2026-10-17T00:00:00.000Z" });
+ assert.equal(info.id, v1.claim_id);
+ assert.equal(info.title, "First Stream");
+ assert.equal(info.duration, 4321);
+ assert.equal(info.release_timestamp, 1700000000);
+ assert.equal(info.upload_date, "20231114", "from the timestamp, UTC, as yt-dlp derives it");
+ assert.equal(info.channel, "Synth Channel");
+ assert.equal(info.uploader_id, "@synthchan");
+ assert.equal(info.extractor, "lbry");
+ assert.equal(info.webpage_url, pageUrlOf(v1));
+ assert.equal(info._source, "browser");
+ assert.equal((info.formats as unknown[]).length, 1);
+ assert.equal(info.filesize, 123456789, "the SDK's string size, as a number");
+ const stored = storedMediaUrlFromInfo(info);
+ assert.equal(stored?.url, cdnUrlOf(v1));
+ assert.equal(stored?.host, "player.odycdn.com");
+ const bare = odyseeInfoFromClaim(v1, { pageUrl: pageUrlOf(v1), streamingUrl: null });
+ assert.equal(bare.formats, undefined);
+ assert.equal(storedMediaUrlFromInfo(bare), null);
+});
+
+test("a channel page's listing: its own uploads, newest first, as listing URLs", () => {
+ const read = channelPageRead({ channel: ch, pages: [[v1, other], [v2]] });
+ const claim = channelClaimFor(read.responses, "@synthchan");
+ assert.equal(claim?.claimId, ch.claim_id);
+ const listing = listingFromResponses(read.responses, { claimId: claim?.claimId, name: "@synthchan" });
+ assert.deepEqual(
+ listing.map((l) => l.url),
+ [pageUrlOf(v2), pageUrlOf(v1)],
+ );
+ assert.deepEqual(listingFromResponses(read.responses, { name: "@synthchan" }).length, 2, "by name when no id");
+ assert.deepEqual(listingFromResponses(read.responses, {}), [], "no channel, no listing");
+});
diff --git a/common/lib/odyseePageApi.ts b/common/lib/odyseePageApi.ts
@@ -0,0 +1,356 @@
+// AN ODYSEE RECORD FROM THE PAGE'S OWN API ANSWERS (release 32 R9).
+//
+// Measured live 2026-10-17: a headless browser's load of an odysee.com page
+// gets 200 from Odysee's API (`api.na-backend.odysee.com/api/v1/proxy`,
+// `api.odysee.com/*`) where yt-dlp's lbry extractor gets 429 — the page asks
+// the same LBRY SDK methods yt-dlp does (`resolve`, `claim_search`, `get`), as
+// a browser. ytdlp/odyseePageReader.ts opens the page and keeps every JSON
+// answer of those hosts (and the URLs the player asks the CDN for); this module
+// reads them into the metadata.info.json shape yt-dlp writes, so the index, the
+// stored-URL download (lib/storedMediaUrl.ts) and every reader see an ordinary
+// record — marked `_source: "browser"`.
+//
+// THE SHAPES are the LBRY SDK's JSON-RPC answers as yt-dlp's own extractor
+// reads them (yt_dlp/extractor/lbry.py: `_parse_stream`, `_fetch_page`, the
+// `get` call's `streaming_url`): a claim is `{claim_id, name, timestamp,
+// value_type, value: {title, description, thumbnail.url, release_time, tags,
+// license, stream_type, source: {name, media_type, size}, video|audio:
+// {duration, width, height}}, signing_channel: {claim_id, name, value.title}}`;
+// `resolve` answers `{result: {<lbry url>: claim}}`, `claim_search` `{result:
+// {items: [claim…]}}`, `get` `{result: {streaming_url}}`. The reader is
+// TOLERANT of where in an answer a claim sits (a result keyed by URL, a list of
+// items, a bare claim, a JSON-RPC batch) because the page's exact request mix
+// was not recorded offline: the unit tests run on synthetic answers of that
+// shape, and the live check (plans/release-32/odysee-loop.md) is what confirms
+// the page asks these and nothing else is needed.
+//
+// Pure: no I/O.
+
+export type PageApiResponse = {
+ // The request URL (the proxy's `?m=<method>` included when the page sends it).
+ url: string;
+ status: number;
+ // The request's JSON body, when it had one (a JSON-RPC call).
+ request?: unknown;
+ // The response's JSON body.
+ body: unknown;
+};
+
+// The hosts whose answers are the page's API (and the ones yt-dlp's extractor
+// asks — api.lbry.tv is its proxy).
+export const ODYSEE_API_HOSTS: readonly string[] = [
+ "api.na-backend.odysee.com",
+ "api.odysee.com",
+ "api.lbry.tv",
+ "api.lbry.com",
+];
+
+export function isOdyseeApiUrl(raw: string): boolean {
+ try {
+ const host = new URL(raw).hostname.toLowerCase();
+ return ODYSEE_API_HOSTS.includes(host) || (host.endsWith(".odysee.com") && host.startsWith("api."));
+ } catch {
+ return false;
+ }
+}
+
+export type OdyseeClaim = {
+ claim_id: string;
+ name: string;
+ value_type?: string;
+ timestamp?: number;
+ permanent_url?: string;
+ canonical_url?: string;
+ value: Record<string, unknown>;
+ signing_channel?: { claim_id?: string; name?: string; value?: Record<string, unknown> };
+};
+
+const obj = (v: unknown): Record<string, unknown> | null =>
+ v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
+const str = (v: unknown): string | undefined => (typeof v === "string" && v !== "" ? v : undefined);
+// The SDK answers many numbers as strings ("release_time": "1702586407").
+const int = (v: unknown): number | undefined => {
+ const n = typeof v === "number" ? v : typeof v === "string" && /^\d+$/.test(v) ? Number(v) : NaN;
+ return Number.isFinite(n) ? Math.trunc(n) : undefined;
+};
+
+function asClaim(v: unknown): OdyseeClaim | null {
+ const o = obj(v);
+ if (!o) return null;
+ const claimId = str(o.claim_id);
+ const name = str(o.name);
+ const value = obj(o.value);
+ if (!claimId || !/^[0-9a-f]{40}$/.test(claimId) || !name || !value) return null;
+ return o as unknown as OdyseeClaim;
+}
+
+// The JSON-RPC results in one answer (a batch is an array of envelopes).
+function resultsOf(body: unknown): unknown[] {
+ if (Array.isArray(body)) return body.flatMap(resultsOf);
+ const o = obj(body);
+ if (!o) return [];
+ if ("result" in o) return [o.result];
+ if ("data" in o) return [o.data];
+ return [o];
+}
+
+// Every claim in the answers, by claim id (the first seen wins).
+export function claimsFromResponses(responses: readonly PageApiResponse[]): Map<string, OdyseeClaim> {
+ const out = new Map<string, OdyseeClaim>();
+ const add = (c: OdyseeClaim | null) => {
+ if (c && !out.has(c.claim_id)) out.set(c.claim_id, c);
+ };
+ for (const r of responses) {
+ if (r.status < 200 || r.status >= 300) continue;
+ for (const result of resultsOf(r.body)) {
+ const direct = asClaim(result);
+ if (direct) {
+ add(direct);
+ continue;
+ }
+ const o = obj(result);
+ if (!o) continue;
+ if (Array.isArray(o.items)) for (const item of o.items) add(asClaim(item));
+ for (const v of Object.values(o)) add(asClaim(v));
+ }
+ }
+ return out;
+}
+
+const STREAM_TYPES = new Set(["video", "audio"]);
+
+export function isStreamClaim(c: OdyseeClaim): boolean {
+ return (c.value_type === undefined || c.value_type === "stream") && STREAM_TYPES.has(String(c.value.stream_type));
+}
+
+// The video's page URL → its claim id (`…/<name>:<claim id or a prefix>`) and name.
+export function odyseePageRef(pageUrl: string): { name: string | null; claimRef: string | null; channel: string | null } {
+ let u: URL;
+ try {
+ u = new URL(pageUrl);
+ } catch {
+ return { name: null, claimRef: null, channel: null };
+ }
+ const segs = decodeURIComponent(u.pathname).split("/").filter(Boolean);
+ const last = segs.at(-1) ?? "";
+ const channelSeg = segs.find((s) => s.startsWith("@")) ?? null;
+ const [name, ref] = last.startsWith("@") ? [null, null] : splitRef(last);
+ return { name, claimRef: ref, channel: channelSeg ? splitRef(channelSeg)[0] : null };
+}
+
+function splitRef(seg: string): [string | null, string | null] {
+ const i = seg.search(/[:#]/);
+ if (i < 0) return [seg || null, null];
+ const ref = seg.slice(i + 1).toLowerCase();
+ return [seg.slice(0, i) || null, /^[0-9a-f]{1,40}$/.test(ref) ? ref : null];
+}
+
+// The claim a VIDEO page is about: by claim id (a full id, or the prefix the
+// URL carries), else by name when exactly one stream claim has it. A video
+// page also resolves its recommendations, so "the one stream claim" is never
+// assumed.
+export function claimForPage(claims: ReadonlyMap<string, OdyseeClaim>, pageUrl: string): OdyseeClaim | null {
+ const { name, claimRef } = odyseePageRef(pageUrl);
+ const streams = [...claims.values()].filter(isStreamClaim);
+ if (claimRef) {
+ const hits = streams.filter((c) => c.claim_id.startsWith(claimRef) && (!name || c.name === name || claimRef.length === 40));
+ return hits.length === 1 ? hits[0] : null;
+ }
+ if (name) {
+ const hits = streams.filter((c) => c.name === name);
+ return hits.length === 1 ? hits[0] : null;
+ }
+ return null;
+}
+
+// yt-dlp's own rule: the v3 API path is the ORIGINAL file (lbry.py: "GET
+// request to v3 API returns original video/audio file if available"). A v6
+// `/streams/` URL has no /api/ segment and is kept as it is.
+export function originalFileUrl(streamingUrl: string): string {
+ return streamingUrl.replace(/\/api\/v\d+\//, "/api/v3/");
+}
+
+// The claim's file on the CDN: a `get` answer's `streaming_url` naming the
+// claim, else the first URL the player asked the CDN for under the claim's
+// `/streams/<claim id>/` (query and fragment dropped).
+export function streamingUrlFor(
+ claimId: string,
+ responses: readonly PageApiResponse[],
+ mediaUrls: readonly string[] = [],
+): string | null {
+ for (const r of responses) {
+ if (r.status < 200 || r.status >= 300) continue;
+ for (const result of resultsOf(r.body)) {
+ const s = str(obj(result)?.streaming_url);
+ if (s && s.includes(claimId)) return originalFileUrl(s);
+ }
+ }
+ for (const m of mediaUrls) {
+ try {
+ const u = new URL(m);
+ if (u.pathname.includes(`/streams/${claimId}/`)) return `${u.origin}${u.pathname}`;
+ } catch {
+ /* not a URL */
+ }
+ }
+ return null;
+}
+
+const MIME_EXT: Readonly<Record<string, string>> = {
+ "video/mp4": "mp4",
+ "video/webm": "webm",
+ "video/quicktime": "mov",
+ "video/x-matroska": "mkv",
+ "audio/mpeg": "mp3",
+ "audio/mp4": "m4a",
+ "audio/ogg": "ogg",
+};
+
+function extOf(source: Record<string, unknown> | null, url: string | null): string {
+ const fromName = str(source?.name)?.match(/\.([A-Za-z0-9]{2,5})$/)?.[1];
+ if (fromName) return fromName.toLowerCase();
+ const mime = str(source?.media_type);
+ if (mime && MIME_EXT[mime]) return MIME_EXT[mime];
+ const fromUrl = url?.match(/\.([A-Za-z0-9]{2,5})(?:$|[?#])/)?.[1];
+ return fromUrl ? fromUrl.toLowerCase() : "mp4";
+}
+
+const ymd = (epochSec: number | undefined): string | undefined => {
+ if (epochSec === undefined) return undefined;
+ const d = new Date(epochSec * 1000);
+ if (Number.isNaN(d.getTime())) return undefined;
+ return d.toISOString().slice(0, 10).replace(/-/g, "");
+};
+
+export const BROWSER_SOURCE = "browser";
+
+// The metadata.info.json a browser lookup writes: the fields yt-dlp's lbry
+// extractor sets (and the derived dates its core adds), plus ONE format —
+// `original`, the claim's file — when the page named it. `_source: "browser"`
+// says who wrote it; a later yt-dlp prefetch rewrites the file whole.
+export function odyseeInfoFromClaim(
+ claim: OdyseeClaim,
+ opts: { pageUrl: string; streamingUrl: string | null; at?: string },
+): Record<string, unknown> {
+ const v = claim.value;
+ const streamType = String(v.stream_type);
+ const media = obj(v[streamType]);
+ const source = obj(v.source);
+ const thumb = str(obj(v.thumbnail)?.url);
+ const timestamp = int(claim.timestamp);
+ const releaseTimestamp = int(v.release_time);
+ const duration = int(media?.duration);
+ const width = int(media?.width);
+ const height = int(media?.height);
+ const filesize = int(source?.size);
+ const channel = obj(claim.signing_channel);
+ const channelId = str(channel?.claim_id);
+ const uploaderId = str(channel?.name);
+ const tags = Array.isArray(v.tags) ? v.tags.filter((t): t is string => typeof t === "string" && t !== "") : undefined;
+ const url = opts.streamingUrl;
+ const ext = extOf(source, url);
+ const format = url
+ ? {
+ url,
+ format_id: "original",
+ quality: 1,
+ ext,
+ protocol: url.startsWith("http:") ? "http" : "https",
+ ...(filesize !== undefined ? { filesize } : {}),
+ ...(width !== undefined ? { width } : {}),
+ ...(height !== undefined ? { height } : {}),
+ ...(streamType === "audio" ? { vcodec: "none" } : {}),
+ http_headers: { Referer: "https://odysee.com/" },
+ }
+ : null;
+ let basename: string | undefined;
+ try {
+ basename = decodeURIComponent(new URL(opts.pageUrl).pathname).split("/").filter(Boolean).at(-1);
+ } catch {
+ basename = undefined;
+ }
+ const info: Record<string, unknown> = {
+ id: claim.claim_id,
+ title: str(v.title) ?? claim.name,
+ ...(thumb ? { thumbnail: thumb, thumbnails: [{ url: thumb, id: "0" }] } : {}),
+ ...(str(v.description) !== undefined ? { description: v.description } : {}),
+ ...(str(v.license) ? { license: v.license } : {}),
+ ...(timestamp !== undefined ? { timestamp } : {}),
+ ...(releaseTimestamp !== undefined ? { release_timestamp: releaseTimestamp } : {}),
+ ...(tags && tags.length ? { tags } : {}),
+ ...(duration !== undefined ? { duration } : {}),
+ ...(str(obj(channel?.value)?.title) ? { channel: obj(channel?.value)?.title } : {}),
+ ...(channelId ? { channel_id: channelId } : {}),
+ ...(uploaderId ? { uploader_id: uploaderId } : {}),
+ ...(uploaderId && channelId ? { channel_url: `https://odysee.com/${uploaderId}:${channelId}` } : {}),
+ ...(format ? { formats: [format] } : {}),
+ is_live: false,
+ http_headers: { Referer: "https://odysee.com/" },
+ webpage_url: opts.pageUrl,
+ ...(basename ? { webpage_url_basename: basename } : {}),
+ webpage_url_domain: "odysee.com",
+ extractor: "lbry",
+ extractor_key: "LBRY",
+ display_id: claim.claim_id,
+ fulltitle: str(v.title) ?? claim.name,
+ ...(ymd(timestamp ?? releaseTimestamp) ? { upload_date: ymd(timestamp ?? releaseTimestamp) } : {}),
+ ...(ymd(releaseTimestamp) ? { release_date: ymd(releaseTimestamp) } : {}),
+ // The selected format at the top level, as yt-dlp writes it.
+ ...(format
+ ? {
+ url: format.url,
+ format_id: format.format_id,
+ ext: format.ext,
+ protocol: format.protocol,
+ ...(filesize !== undefined ? { filesize } : {}),
+ ...(width !== undefined ? { width } : {}),
+ ...(height !== undefined ? { height } : {}),
+ }
+ : {}),
+ _type: "video",
+ _source: BROWSER_SOURCE,
+ ...(opts.at ? { _browserLookupAt: opts.at } : {}),
+ };
+ return info;
+}
+
+// A channel page's listing: its stream claims (signed by the channel, when the
+// channel is known), newest first by release time, as the page URLs yt-dlp's
+// listing prints (`https://odysee.com/<name>:<claim id>`).
+export function listingFromResponses(
+ responses: readonly PageApiResponse[],
+ channel: { claimId?: string | null; name?: string | null },
+): { url: string; claim: OdyseeClaim }[] {
+ const claims = [...claimsFromResponses(responses).values()].filter(isStreamClaim);
+ const mine = claims.filter((c) => {
+ const sc = c.signing_channel;
+ if (channel.claimId) return sc?.claim_id === channel.claimId;
+ if (channel.name) return sc?.name === channel.name;
+ return false;
+ });
+ const when = (c: OdyseeClaim) => int(c.value.release_time) ?? int(c.timestamp) ?? 0;
+ return mine
+ .sort((a, b) => when(b) - when(a))
+ .map((claim) => ({ url: `https://odysee.com/${claim.name}:${claim.claim_id}`, claim }));
+}
+
+// The channel claim a channel page resolved (`@name`), when it did.
+export function channelClaimFor(
+ responses: readonly PageApiResponse[],
+ channelName: string,
+): { claimId: string; name: string } | null {
+ for (const r of responses) {
+ if (r.status < 200 || r.status >= 300) continue;
+ for (const result of resultsOf(r.body)) {
+ const o = obj(result);
+ if (!o) continue;
+ for (const v of [o, ...Object.values(o)]) {
+ const c = obj(v);
+ if (c && c.value_type === "channel" && c.name === channelName && typeof c.claim_id === "string") {
+ return { claimId: c.claim_id, name: channelName };
+ }
+ }
+ }
+ }
+ return null;
+}
diff --git a/common/testing/web/fakeOdyseePage.d.mts b/common/testing/web/fakeOdyseePage.d.mts
@@ -0,0 +1,58 @@
+import type { PageApiResponse } from "../../lib/odyseePageApi";
+import type { PageApiRead, PageApiReader } from "../../ytdlp/odyseePageReader";
+
+export type SyntheticChannel = {
+ claim_id: string;
+ name: string;
+ value_type: "channel";
+ timestamp: number;
+ value: { title: string };
+};
+
+export type SyntheticClaim = {
+ claim_id: string;
+ name: string;
+ value_type: "stream";
+ timestamp: number;
+ canonical_url: string;
+ permanent_url: string;
+ signing_channel: { claim_id: string; name: string; value: { title: string } };
+ value: Record<string, unknown> & { title: string; source: { sd_hash: string; media_type: string; name: string; size: string } };
+};
+
+export function syntheticChannel(opts: { name: string; title?: string; claimId?: string }): SyntheticChannel;
+export function syntheticClaim(opts: {
+ name: string;
+ title: string;
+ channel: SyntheticChannel;
+ claimId?: string;
+ releaseTime?: number;
+ timestamp?: number;
+ duration?: number;
+ size?: number;
+ sdHash?: string;
+ streamType?: "video" | "audio" | "binary";
+ mediaType?: string;
+ height?: number;
+ width?: number;
+ description?: string;
+ tags?: string[];
+}): SyntheticClaim;
+export function pageUrlOf(claim: SyntheticClaim): string;
+export function channelUrlOf(channel: SyntheticChannel): string;
+export function cdnUrlOf(claim: SyntheticClaim): string;
+export function resolveAnswer(claims: ReadonlyArray<SyntheticClaim | SyntheticChannel>): PageApiResponse;
+export function claimSearchAnswer(claims: ReadonlyArray<SyntheticClaim>, page?: number): PageApiResponse;
+export function getAnswer(claim: SyntheticClaim, streamingUrl: string): PageApiResponse;
+export function refusedAnswer(method: string): PageApiResponse;
+export function videoPageRead(opts: {
+ claim: SyntheticClaim;
+ related?: SyntheticClaim[];
+ streamingUrl?: string | null;
+ mediaUrls?: string[];
+ get?: boolean;
+}): PageApiRead;
+export function channelPageRead(opts: { channel: SyntheticChannel; pages: SyntheticClaim[][] }): PageApiRead;
+export function fakePageReader(
+ reads: Record<string, PageApiRead | ((opts: { pageUrl: string; play?: boolean; scrolls?: number }) => PageApiRead)>,
+): PageApiReader & { calls: { pageUrl: string; play: boolean; scrolls: number }[] };
diff --git a/common/testing/web/fakeOdyseePage.mjs b/common/testing/web/fakeOdyseePage.mjs
@@ -0,0 +1,143 @@
+// Synthetic odysee.com page reads (release 32 R9): what a headless browser's
+// load of a video page or a channel page would keep of the page's own API
+// answers — the LBRY SDK's JSON-RPC through Odysee's proxy (`resolve`,
+// `claim_search`, `get`), in the shape yt-dlp's lbry extractor reads
+// (yt_dlp/extractor/lbry.py). Invented claims, channels and hashes: nothing
+// recorded from the real site. No browser and no network: `fakePageReader`
+// answers a PageApiReader call from these.
+//
+// const ch = syntheticChannel({ name: "@synthchan", title: "Synth Channel" });
+// const v = syntheticClaim({ name: "a-synthetic-stream", title: "…", channel: ch, releaseTime: 1700000000 });
+// const read = videoPageRead({ claim: v, related: [other], streamingUrl: cdnUrlOf(v) });
+// const reader = fakePageReader({ [pageUrlOf(v)]: read }); // reader.calls lists every call
+
+const PROXY = "https://api.na-backend.odysee.com/api/v1/proxy";
+
+function hex40(seed) {
+ let h = "";
+ let x = 0x9e3779b9 ^ [...String(seed)].reduce((a, c) => (a * 31 + c.charCodeAt(0)) >>> 0, 7);
+ while (h.length < 40) {
+ x = (x * 1103515245 + 12345) >>> 0;
+ h += (x >>> 8).toString(16).padStart(6, "0");
+ }
+ return h.slice(0, 40);
+}
+
+export function syntheticChannel({ name, title, claimId }) {
+ return {
+ claim_id: claimId ?? hex40(`channel:${name}`),
+ name,
+ value_type: "channel",
+ timestamp: 1690000000,
+ value: { title: title ?? name.slice(1) },
+ };
+}
+
+export function syntheticClaim({
+ name,
+ title,
+ channel,
+ claimId,
+ releaseTime = 1700000000,
+ timestamp,
+ duration = 3600,
+ size = 123456789,
+ sdHash,
+ streamType = "video",
+ mediaType = "video/mp4",
+ height = 720,
+ width = 1280,
+ description = "A synthetic stream.",
+ tags = ["synthetic"],
+}) {
+ const id = claimId ?? hex40(`stream:${name}`);
+ return {
+ claim_id: id,
+ name,
+ value_type: "stream",
+ timestamp: timestamp ?? releaseTime + 60,
+ canonical_url: `lbry://${channel.name}#${channel.claim_id.slice(0, 1)}/${name}#${id.slice(0, 1)}`,
+ permanent_url: `lbry://${name}#${id}`,
+ signing_channel: { claim_id: channel.claim_id, name: channel.name, value: { title: channel.value.title } },
+ value: {
+ title,
+ description,
+ license: "None",
+ // The SDK answers these as strings.
+ release_time: String(releaseTime),
+ tags,
+ stream_type: streamType,
+ source: {
+ media_type: mediaType,
+ name: `${name}.mp4`,
+ sd_hash: sdHash ?? hex40(`sd:${name}`) + hex40(`sd2:${name}`).slice(0, 56),
+ size: String(size),
+ },
+ thumbnail: { url: `https://thumbs.odycdn.com/${hex40(`th:${name}`).slice(0, 32)}.webp` },
+ [streamType]: streamType === "video" ? { duration, height, width } : { duration },
+ },
+ };
+}
+
+export const pageUrlOf = (claim) => `https://odysee.com/${claim.name}:${claim.claim_id}`;
+export const channelUrlOf = (channel) => `https://odysee.com/${channel.name}`;
+export const cdnUrlOf = (claim) =>
+ `https://player.odycdn.com/v6/streams/${claim.claim_id}/${claim.value.source.sd_hash.slice(0, 6)}.mp4`;
+
+const rpc = (method, params, result, status = 200) => ({
+ url: `${PROXY}?m=${method}`,
+ status,
+ request: { jsonrpc: "2.0", method, params, id: 1 },
+ body: status === 200 ? { jsonrpc: "2.0", result, id: 1 } : { error: { code: status, message: "Too Many Requests" } },
+});
+
+export const resolveAnswer = (claims) =>
+ rpc(
+ "resolve",
+ { urls: claims.map((c) => c.permanent_url ?? `lbry://${c.name}#${c.claim_id}`) },
+ Object.fromEntries(claims.map((c) => [c.permanent_url ?? `lbry://${c.name}#${c.claim_id}`, c])),
+ );
+
+export const claimSearchAnswer = (claims, page = 1) =>
+ rpc("claim_search", { page, page_size: claims.length, no_totals: true }, { items: claims, page, page_size: claims.length });
+
+export const getAnswer = (claim, streamingUrl) =>
+ rpc("get", { uri: claim.permanent_url, save_file: false }, { streaming_url: streamingUrl, claim_id: claim.claim_id });
+
+export const refusedAnswer = (method) => rpc(method, {}, null, 429);
+
+// A video page: its resolve (the claim plus recommendations), the related
+// claim_search, the player's get and its CDN request.
+export function videoPageRead({ claim, related = [], streamingUrl, mediaUrls, get = true }) {
+ const url = streamingUrl === undefined ? cdnUrlOf(claim) : streamingUrl;
+ return {
+ ok: true,
+ responses: [
+ resolveAnswer([claim]),
+ ...(related.length ? [claimSearchAnswer(related)] : []),
+ ...(get && url ? [getAnswer(claim, url)] : []),
+ ],
+ mediaUrls: mediaUrls ?? (url ? [`${url}?range=0`] : []),
+ };
+}
+
+// A channel page: its resolve, and one claim_search per page of uploads.
+export function channelPageRead({ channel, pages }) {
+ return {
+ ok: true,
+ responses: [resolveAnswer([channel]), ...pages.map((p, i) => claimSearchAnswer(p, i + 1))],
+ mediaUrls: [],
+ };
+}
+
+export function fakePageReader(reads) {
+ const calls = [];
+ const reader = async ({ pageUrl, play, scrolls }) => {
+ calls.push({ pageUrl, play: Boolean(play), scrolls: scrolls ?? 0 });
+ const hit = reads[pageUrl] ?? reads["*"];
+ if (!hit) return { ok: false, responses: [], mediaUrls: [], error: `no recorded read for ${pageUrl}` };
+ return typeof hit === "function" ? hit({ pageUrl, play, scrolls }) : hit;
+ };
+ reader.calls = calls;
+ return reader;
+}
diff --git a/common/ytdlp/browserLookupDownload.test.ts b/common/ytdlp/browserLookupDownload.test.ts
@@ -0,0 +1,143 @@
+// downloadOneManaged with the browser lookup (release 32 R9): a record that
+// stores no media URL is read from its page (a fake page reader — no browser)
+// and downloaded from the file the page named, from a fake CDN on loopback;
+// the channel's title match filter still decides; off, nothing changes. Real
+// ffmpeg for the audio check (skipped without it). No real network.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/browserLookupDownload.test.ts
+
+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";
+import { hasFfmpeg, makeToneFile } from "../testing/audio/corruptAudio.mjs";
+import { startFakeRangedCdn, type FakeRangedCdn } from "../testing/web/fakeRangedCdn.mjs";
+import { fakePageReader, syntheticChannel, syntheticClaim, videoPageRead } from "../testing/web/fakeOdyseePage.mjs";
+import type { ChannelConfig } from "../lib/channelConfig";
+import type { Paths } from "../lib/paths";
+import { storedUrlAttemptOf } from "../lib/downloadOutcome";
+import { clearPlatformGaps } from "../jobs/platformGap";
+import { downloadOneManaged, type ManagedDownloadOpts } from "./downloadOneManaged";
+
+const FF = hasFfmpeg();
+const CLAIM = "FAKE-TEST-VALUEFAKE-TEST-VALUEfedcba98";
+const FILE_PATH = `/v6/streams/${CLAIM}/d4e5f6.mp4`;
+const PAGE = `https://odysee.com/synthetic-stream:${CLAIM}`;
+const FAST = { intervalMs: 0, sizeGateBytes: 0, maxRollbacks: 3 };
+const ch = syntheticChannel({ name: "@synth", title: "Synth" });
+
+type Fixture = { root: string; videoDir: string; ytdlpLog: string; paths: Paths; cdn: FakeRangedCdn };
+
+async function fixture(opts: { prefetch?: "ok" | "429" } = {}): Promise<Fixture> {
+ const root = await mkdtemp(path.join(os.tmpdir(), "browser-download-"));
+ const channelsDir = path.join(root, "channels");
+ const videoDir = path.join(channelsDir, "c", "data", CLAIM);
+ await mkdir(videoDir, { recursive: true });
+ const clean = FF ? await readFile(makeToneFile(path.join(root, "src.mp4"), { duration: 30, faststart: true })) : Buffer.alloc(1);
+ const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean } });
+ const ytdlpLog = path.join(root, "ytdlp.log");
+ const bin = path.join(root, "fake-ytdlp.sh");
+ const line429 = `echo "ERROR: [lbry] ${CLAIM}: Unable to download webpage: HTTP Error 429: Too Many Requests" >&2; exit 1`;
+ await writeFile(
+ bin,
+ `#!/bin/sh\necho "$@" >> ${JSON.stringify(ytdlpLog)}\n` +
+ `case "$*" in *--skip-download*) ${opts.prefetch === "429" ? line429 : "exit 0"} ;; esac\nexit 0\n`,
+ );
+ await chmod(bin, 0o755);
+ const paths = { channelsDir, ytdlpBin: bin, ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" } as Paths;
+ return { root, videoDir, ytdlpLog, paths, cdn };
+}
+
+function claim(title = "SynthShow - 01/02/2024") {
+ return syntheticClaim({ name: "synthetic-stream", title, channel: ch, claimId: CLAIM, duration: 30 });
+}
+
+function run(f: Fixture, reader: ReturnType<typeof fakePageReader>, over: Partial<ManagedDownloadOpts> = {}, log = { s: "" }) {
+ return downloadOneManaged({
+ channelSlug: "c",
+ channelConfig: { handling: "transcribe", url: "https://odysee.com/@synth", audioFormat: "mp3", browserLookup: true } as ChannelConfig,
+ paths: f.paths,
+ videoUrl: PAGE,
+ onLog: (s) => (log.s += s),
+ signal: new AbortController().signal,
+ storedUrlDeps: { fetch: f.cdn.fetch, chunkBytes: 16 * 1024, knobs: FAST, gapMs: 0, openPage: null },
+ browserLookupDeps: { reader, gapMs: 0 },
+ ...over,
+ });
+}
+
+async function done(f: Fixture) {
+ clearPlatformGaps();
+ await f.cdn.close();
+ await rm(f.root, { recursive: true, force: true });
+}
+
+test("only, no record: the page is read, the record written, the file downloaded from the URL it named", { skip: !FF }, async () => {
+ const f = await fixture();
+ try {
+ const reader = fakePageReader({ [PAGE]: videoPageRead({ claim: claim(), streamingUrl: f.cdn.url(FILE_PATH) }) });
+ const log = { s: "" };
+ const record = await run(f, reader, { storedUrl: "only" }, log);
+ assert.equal(record.status, "ok-audio-checked", log.s);
+ assert.equal(reader.calls.length, 1);
+ assert.equal(storedUrlAttemptOf(record)?.why, "only");
+ const info = JSON.parse(await readFile(path.join(f.videoDir, "metadata.info.json"), "utf8"));
+ assert.equal(info._source, "browser");
+ assert.equal(info.formats[0].url, f.cdn.url(FILE_PATH));
+ assert.match(log.s, /stores no media URL; reading its record from the page in a browser/);
+ } finally {
+ await done(f);
+ }
+});
+
+test("fallback, the prefetch rate-limited and no record: the browser lookup, then the stored-URL download", { skip: !FF }, async () => {
+ const f = await fixture({ prefetch: "429" });
+ try {
+ const reader = fakePageReader({ "*": videoPageRead({ claim: claim(), streamingUrl: f.cdn.url(FILE_PATH) }) });
+ const log = { s: "" };
+ const record = await run(f, reader, { storedUrl: "fallback" }, log);
+ assert.equal(record.status, "ok-audio-checked", log.s);
+ assert.equal(storedUrlAttemptOf(record)?.why, "rate-limited", "the platform still backs off");
+ assert.equal(reader.calls.length, 1);
+ } finally {
+ await done(f);
+ }
+});
+
+test("the channel's title match filter declines what the page found: skipped, no CDN read", async () => {
+ const f = await fixture();
+ try {
+ const reader = fakePageReader({ "*": videoPageRead({ claim: claim("A vlog"), streamingUrl: f.cdn.url(FILE_PATH) }) });
+ const record = await run(f, reader, {
+ storedUrl: "only",
+ channelConfig: {
+ handling: "transcribe",
+ url: "https://odysee.com/@synth",
+ browserLookup: true,
+ ytdlpExtraArgs: ["--match-filters=title~='SynthShow'"],
+ } as ChannelConfig,
+ });
+ assert.equal(record.status, "skipped-filtered");
+ assert.equal(record.filter?.name, "ytdlpMatchFilter");
+ assert.equal(f.cdn.requests.length, 0);
+ } finally {
+ await done(f);
+ }
+});
+
+test("browserLookup off: no page is read, and `only` with no record fails asking nothing (as before)", async () => {
+ const f = await fixture();
+ try {
+ const reader = fakePageReader({ "*": videoPageRead({ claim: claim(), streamingUrl: f.cdn.url(FILE_PATH) }) });
+ const record = await run(f, reader, {
+ storedUrl: "only",
+ channelConfig: { handling: "transcribe", url: "https://odysee.com/@synth" } as ChannelConfig,
+ });
+ assert.equal(record.status, "failed");
+ assert.equal(record.failureClass, "per_video");
+ assert.equal(reader.calls.length, 0);
+ } finally {
+ await done(f);
+ }
+});
diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts
@@ -116,7 +116,15 @@ import {
import { storedMediaUrl } from "../lib/storedMediaUrl-server";
import { fullAudioLine, fullAudioState } from "../lib/fullAudioFirst";
import type { DownloadFailureClass } from "../lib/availability";
-import { notePlatformGap, platformGapRemainingMs, waitForPlatformGap } from "../jobs/platformGap";
+import { platformGapRemainingMs, waitForPlatformGap } from "../jobs/platformGap";
+import { noteStoredUrlRead } from "../jobs/storedUrlPace";
+import {
+ BROWSER_LOOKUP_PLATFORMS,
+ browserLookupDecision,
+ browserLookupVideo,
+ browserLookupWanted,
+ type BrowserLookupDeps,
+} from "./odyseeBrowserLookup";
import {
storedUrlDownload,
type StoredUrlDownloadDeps,
@@ -232,6 +240,14 @@ export type ManagedDownloadOpts = {
// The platform is HELD and the caller's door let this run through as
// `only` (the log and the attempt say "held" rather than "only").
storedUrlHeld?: boolean;
+ // THE BROWSER LOOKUP (release 32 R9, ytdlp/odyseeBrowserLookup.ts): with a
+ // stored-URL mode, a record that stores no media URL — `only`, or a
+ // `fallback` whose prefetch was rate-limited — is read from the video's page
+ // in a headless browser first, and downloaded from the file the page named.
+ // Absent = the channel's `browserLookup`.
+ browserLookup?: boolean;
+ // Test seam: the page reader and the gap. Production callers pass none.
+ browserLookupDeps?: BrowserLookupDeps;
// Test seam: the CDN fetch, the chunk, the audio check's knobs, and the gap
// between two stored-URL files (default STORED_URL_NEW_FILE_GAP_MS) with
// its sleep. Every production caller passes none.
@@ -845,11 +861,16 @@ async function runManagedDownload(
// platform refused writes nothing useful, and the stored URL is the record's.
const storedMode = resolveStoredUrlMode(opts.storedUrl, opts.channelConfig.storedUrlDownloads);
const storedDir = canonicalId ? path.join(channelDir, "data", canonicalId) : null;
- const stored =
+ let stored =
storedMode !== "never" && opts.channelConfig.handling === "transcribe" && storedDir
? await storedMediaUrl(storedDir)
: null;
if (storedMode === "only" && canonicalId && storedDir) {
+ if (!stored) {
+ const looked = await storedViaBrowserLookup(opts, storedDir, canonicalId, startedAt, attempts);
+ if (looked && "record" in looked) return looked.record;
+ if (looked) stored = looked.stored;
+ }
if (stored) {
return runStoredUrlDownload(opts, {
videoDir: storedDir,
@@ -975,7 +996,13 @@ async function runManagedDownload(
classifyDownloadFailure(lastFullTail, lastPrefetch.availabilityClass) ===
"rate_limit"
) {
- if (stored && storedMode === "fallback") {
+ let fallbackStored = stored;
+ if (!fallbackStored && storedMode === "fallback" && opts.channelConfig.handling === "transcribe") {
+ const looked = await storedViaBrowserLookup(opts, videoDir, canonicalId, startedAt, attempts);
+ if (looked && "record" in looked) return looked.record;
+ if (looked) fallbackStored = looked.stored;
+ }
+ if (fallbackStored && storedMode === "fallback") {
opts.onLog(
`Metadata prefetch for ${canonicalId} was rate-limited by the source; ` +
`downloading from the stored media URL instead (the platform still backs off).\n`,
@@ -985,7 +1012,7 @@ async function runManagedDownload(
videoId: canonicalId,
channelDir,
startedAt,
- stored,
+ stored: fallbackStored,
why: "rate-limited",
attempts,
lastFullTail,
@@ -2119,7 +2146,8 @@ async function runStoredUrlDownload(
failureClass: "unknown",
});
}
- notePlatformGap(key, gapMs);
+ // The one pacing state the clip cut reads too (jobs/storedUrlPace.ts).
+ noteStoredUrlRead(stored.platform, stored.url, gapMs);
let r: StoredUrlDownloadResult;
try {
r = await storedUrlDownload({
@@ -2142,7 +2170,7 @@ async function runStoredUrlDownload(
...(deps ? { deps } : {}),
});
} finally {
- notePlatformGap(key, gapMs);
+ noteStoredUrlRead(stored.platform, stored.url, gapMs);
}
if (gapMs > 0) {
opts.onLog(
@@ -2210,6 +2238,85 @@ async function runStoredUrlDownload(
});
}
+// THE BROWSER LOOKUP FOR A DOWNLOAD (release 32 R9): the record stores no
+// media URL; when the request or the channel asks for it, read the record from
+// the video's page in a headless browser. null = not asked (or it found no
+// file: the caller goes on as without it); `stored` = download from it;
+// `record` = the outcome already written (the channel's filters declined the
+// video, or its match filter cannot be applied to a lookup).
+async function storedViaBrowserLookup(
+ opts: ManagedDownloadOpts,
+ videoDir: string,
+ videoId: string,
+ startedAt: string,
+ attempts: DownloadAttempt[],
+): Promise<{ stored: StoredMediaUrl } | { record: DownloadOutcomeRecord } | null> {
+ if (!browserLookupWanted(opts.browserLookup, opts.channelConfig)) return null;
+ if (opts.channelConfig.handling !== "transcribe") return null;
+ const platform = detectPlatform(opts.videoUrl);
+ if (!platform || !BROWSER_LOOKUP_PLATFORMS.includes(platform) || opts.signal.aborted) return null;
+ opts.onLog(`${videoId} stores no media URL; reading its record from the page in a browser (browser lookup).\n`);
+ const r = await browserLookupVideo({
+ videoDir,
+ pageUrl: opts.videoUrl,
+ onLog: opts.onLog,
+ signal: opts.signal,
+ ...(opts.browserLookupDeps ? { deps: opts.browserLookupDeps } : {}),
+ });
+ if ("error" in r) {
+ opts.onLog(`Browser lookup of ${videoId}: ${r.status} — ${r.error}.\n`);
+ return null;
+ }
+ if (!r.stored) {
+ opts.onLog(`Browser lookup of ${videoId}: the page named no media file the allowlist trusts.\n`);
+ return null;
+ }
+ const d = browserLookupDecision(
+ opts.channelConfig,
+ r.info,
+ { skipLiveDownloads: opts.globalSkipLiveDownloads ?? true },
+ (line) => opts.onLog(line.endsWith("\n") ? line : `${line}\n`),
+ );
+ if (d.ok) return { stored: r.stored };
+ if (!d.skip) {
+ opts.onLog(`Not downloading ${videoId}: ${d.reason}.\n`);
+ attempts.push({
+ n: 1,
+ kind: "stored-url-ranged",
+ handling: opts.channelConfig.handling,
+ usedCookies: false,
+ ytdlpExitCode: 1,
+ error: `browser lookup: ${d.reason}`,
+ });
+ return {
+ record: await writeOutcome(opts, videoDir, {
+ videoId,
+ status: "failed",
+ startedAt,
+ attempts,
+ lastFullTail: "",
+ failureClass: "per_video",
+ }),
+ };
+ }
+ opts.onLog(`Skipping ${videoId}: ${d.reason} [filter=${d.filter}]\n`);
+ const record: DownloadOutcomeRecord = {
+ videoId,
+ webpageUrl: opts.videoUrl,
+ status: "skipped-filtered",
+ startedAt,
+ finishedAt: new Date().toISOString(),
+ attempts,
+ filter: { name: d.filter, reason: d.reason },
+ };
+ try {
+ await writeDownloadOutcome(videoDir, record);
+ } catch (err) {
+ opts.onLog(`Failed to write download-outcome.json: ${(err as Error).message}\n`);
+ }
+ return { record };
+}
+
// `only`, and the record stores no media URL the allowlist trusts (or the
// channel is not transcribe handling): nothing is asked of anyone. A per-video
// failure, so a batch goes on to the next video.
diff --git a/common/ytdlp/fetchWindowManaged.ts b/common/ytdlp/fetchWindowManaged.ts
@@ -52,10 +52,20 @@ import { FULL_LOG_PROGRESS_ARGS } from "./downloadOneManaged";
import { clipFormatSelector, copyClipFormatSelector } from "./downloadFormat";
import {
STORED_MEDIA_USER_AGENT,
+ STORED_URL_NEW_FILE_GAP_MS,
storedUrlWhyText,
type StoredMediaUrl,
type StoredUrlWhy,
} from "../lib/storedMediaUrl";
+import {
+ newStoredPageSession,
+ openPlayerPage,
+ PAGE_OPEN_PLATFORMS,
+ type PageOpener,
+ type StoredPageSession,
+} from "./storedUrlPageOpen";
+import { waitForPlatformGap } from "../jobs/platformGap";
+import { noteStoredUrlRead, storedUrlGapRemainingMs } from "../jobs/storedUrlPace";
// The source height a clip is worth fetching at. 720 is umtool's number and the
// reason is the render: the deliverable is 1080p with a clip inset, so pixels
@@ -123,6 +133,21 @@ export type FetchWindowOpts = {
// extractor, the copy path's lenient selector, the platform player's
// Referer) and no page or API request is made. `why` is for the log.
storedMedia?: StoredMediaUrl & { why: StoredUrlWhy };
+ // THE STORED-URL CUT'S PAGE AND GAP (release 32 R9). Every field optional;
+ // production callers pass at most `pageSession`.
+ storedUrlCut?: {
+ // The run's page state (storedUrlPageOpen.ts): the batch passes one per
+ // run so a video's page is opened before its FIRST cut only. Absent = a
+ // fresh one for this window.
+ pageSession?: StoredPageSession;
+ // Absent = the real opener for a platform in PAGE_OPEN_PLATFORMS; null =
+ // no page open. Tests inject a fake (never a browser).
+ openPage?: PageOpener | null;
+ // The one stored-URL gap (jobs/storedUrlPace.ts); absent =
+ // STORED_URL_NEW_FILE_GAP_MS. Tests pass 0 or a sleep.
+ gapMs?: number;
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
+ };
// Working directory for the yt-dlp process. Nothing it writes is
// cwd-relative (`-o` is absolute and `--ignore-config` stops the operator's
// own config redirecting anything), so this only decides where yt-dlp's own
@@ -223,9 +248,25 @@ export function storedMediaFfmpegArgs(
];
}
+// TEST-ONLY: E2E_CLIP_WINDOW_GAP_MS (the e2e server's and the editor route
+// tests' clip gap) also replaces the stored-URL rest a cut sets, so a test's
+// second stored-URL window does not wait 20 minutes. A full download's rest has
+// no knob (storedUrlDeps.gapMs is its seam).
+function e2eStoredUrlRestMs(): number | undefined {
+ if (process.env.E2E_CLIP_WINDOW_GAP_MS === undefined) return undefined;
+ const raw = Number(process.env.E2E_CLIP_WINDOW_GAP_MS);
+ return Number.isFinite(raw) && raw >= 0 ? raw : undefined;
+}
+
export async function fetchWindowManaged(
- opts: FetchWindowOpts,
+ given: FetchWindowOpts,
): Promise<FetchWindowResult> {
+ // One page state across this window's attempts (a corrupt re-fetch is a
+ // second cut of the same video, not a first).
+ const opts: FetchWindowOpts =
+ given.storedMedia && !given.storedUrlCut?.pageSession
+ ? { ...given, storedUrlCut: { ...given.storedUrlCut, pageSession: newStoredPageSession() } }
+ : given;
for (let attempt = 1; ; attempt++) {
try {
return await fetchWindowOnce(opts, attempt);
@@ -362,6 +403,7 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise<
];
let args: string[] = [];
+ let pageOpens = 0;
if (stored) {
// A STORED MEDIA URL IS READ THE WAY THE SITE'S OWN PLAYER READS IT (release 32): ranged GETs
// with the page's Referer and Origin and a browser's user agent — ffmpeg's input seek (-ss
@@ -369,15 +411,77 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise<
// URL with one unranged GET first, which the CDN answers like a bulk download (429 on Odysee,
// 2026-10-16) while it serves the player's ranged requests (206). No yt-dlp, no cookies.
args = storedMediaFfmpegArgs(stored, from, to, maxHeight, part);
- const outcome = await runOneYtdlp(
- { ytdlpBin: opts.paths.ffmpegBin, onLog: opts.onLog, signal: opts.signal },
- opts.cwd ?? videoDir,
- args,
- );
+ const cut = opts.storedUrlCut ?? {};
+ const session = cut.pageSession ?? newStoredPageSession();
+ const openPage: PageOpener | null =
+ cut.openPage !== undefined
+ ? cut.openPage
+ : PAGE_OPEN_PLATFORMS.includes(stored.platform)
+ ? openPlayerPage
+ : null;
+ const gapMs = cut.gapMs ?? e2eStoredUrlRestMs() ?? STORED_URL_NEW_FILE_GAP_MS;
+
+ // THE ONE GAP (release 32 R9, jobs/storedUrlPace.ts): a cut of a NEW file
+ // waits out the platform's stored-URL rest exactly as a full download
+ // does; a cut of the file read last (another window of the same video)
+ // owes nothing more than the clip gap its caller already kept.
+ try {
+ await waitForPlatformGap({
+ label: `A cut from the stored media URL (${stored.platform})`,
+ remainingMs: () => storedUrlGapRemainingMs(stored.platform, { url: stored.url, sameFileFree: true }),
+ signal: opts.signal,
+ onLog: (line) => opts.onLog(`${line}\n`),
+ ...(cut.sleep ? { sleep: cut.sleep } : {}),
+ });
+ } catch {
+ throw new FetchWindowError(
+ `cancelled while waiting for the gap between stored-URL files (${stored.platform})`,
+ "unknown",
+ "public",
+ );
+ }
+ noteStoredUrlRead(stored.platform, stored.url, gapMs);
+
+ // THE PLAYER'S PAGE FIRST (release 32 R9; R7's finding): the CDN serves a
+ // file only after a player opened the video's page. Before the first cut
+ // of each video in a run; again on a 429 that follows a cut served since
+ // the last open; never twice in a row.
+ let page = session.pages.get(opts.videoUrl);
+ const open = async (): Promise<void> => {
+ if (!openPage || opts.signal.aborted) return;
+ session.opens++;
+ pageOpens++;
+ page = { cutsSinceOpen: 0 };
+ session.pages.set(opts.videoUrl, page);
+ const r = await openPage({ pageUrl: opts.videoUrl, cdnHost: stored.host, signal: opts.signal, onLog: opts.onLog });
+ if (!r.ok) {
+ opts.onLog(`The page open did not show the player served (${r.error ?? "no media request"}); cutting anyway.\n`);
+ }
+ };
+ if (openPage && !page) await open();
+ const cutOnce = () =>
+ runOneYtdlp(
+ { ytdlpBin: opts.paths.ffmpegBin, onLog: opts.onLog, signal: opts.signal },
+ opts.cwd ?? videoDir,
+ args,
+ );
+ const refused = (tail: string) => /\b429\b|Too Many Requests/i.test(tail);
+ let outcome = await cutOnce();
+ if (outcome.exitCode !== 0 && refused(outcome.stderrTail) && openPage && page && page.cutsSinceOpen > 0 && !opts.signal.aborted) {
+ opts.onLog(
+ `HTTP Error 429 from ${stored.host} after ${page.cutsSinceOpen} cut(s) since the page was opened; ` +
+ `opening it again.\n`,
+ );
+ await rm(part, { force: true });
+ await open();
+ outcome = await cutOnce();
+ }
+ noteStoredUrlRead(stored.platform, stored.url, gapMs);
+ if (outcome.exitCode === 0 && page) page.cutsSinceOpen++;
if (outcome.exitCode !== 0) {
await rm(part, { force: true });
const tail = outcome.stderrTail.trim().split("\n").slice(-4).join(" / ");
- const failureClass: DownloadFailureClass = /\b429\b|Too Many Requests/i.test(outcome.stderrTail)
+ const failureClass: DownloadFailureClass = refused(outcome.stderrTail)
? "rate_limit"
: /\b(403|404|410)\b|Forbidden|Not Found/i.test(outcome.stderrTail)
? "per_video"
@@ -518,6 +622,7 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise<
: {}),
...(opts.provenance.copy ? { copy: opts.provenance.copy } : {}),
...(stored ? { source: "stored-media-url" as const, sourceHost: stored.host } : {}),
+ ...(pageOpens > 0 ? { pageOpens } : {}),
...(audioCheck ? { audioCheck } : {}),
bytes: st.size,
fetchedAt: new Date().toISOString(),
diff --git a/common/ytdlp/fetchWindowStoredCut.test.ts b/common/ytdlp/fetchWindowStoredCut.test.ts
@@ -0,0 +1,305 @@
+// The stored-URL clip cut opens the player's page first and shares the
+// platform's stored-URL gap with full downloads (release 32 R9).
+//
+// A fake ffmpeg (a node script: one ranged GET of its `-i` URL with the
+// `-headers` it was given, the bytes written to the output; "HTTP error 429" and
+// exit 1 on a refusal) against the fake CDN on loopback, whose `requireUnlock`
+// models 2026-10-17's finding: every read answers 429 until a player opened the
+// video's page. The opener is injected; no test launches a browser or reaches
+// the network.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/fetchWindowStoredCut.test.ts
+
+import { test, beforeEach } from "node:test";
+import assert from "node:assert/strict";
+import { chmod, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { FetchWindowError, fetchWindowManaged, type FetchWindowOpts } from "./fetchWindowManaged";
+import { newStoredPageSession, type PageOpener } from "./storedUrlPageOpen";
+import { startFakeRangedCdn, type FakeRangedCdn } from "../testing/web/fakeRangedCdn.mjs";
+import { clearPlatformGaps, platformGapRemainingMs } from "../jobs/platformGap";
+import { clearStoredUrlFiles, noteStoredUrlRead, storedUrlLastFile } from "../jobs/storedUrlPace";
+import { storedUrlGapKey, type StoredMediaUrl } from "../lib/storedMediaUrl";
+import { listClipWindows } from "../lib/clipWindow-server";
+import { fetchWindows } from "../controller/fetchWindows";
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "storedcut-"));
+const FFMPEG = path.join(ROOT, "fake-ffmpeg.mjs");
+await writeFile(
+ FFMPEG,
+ `#!/usr/bin/env node
+import { writeFileSync } from "node:fs";
+const args = process.argv.slice(2);
+const out = args[args.length - 1];
+// The audio check's probe writes to /dev/null: a clean verdict.
+if (out === "/dev/null") process.exit(0);
+const url = args[args.indexOf("-i") + 1];
+const headers = {};
+for (const line of (args[args.indexOf("-headers") + 1] ?? "").split("\\r\\n")) {
+ const m = /^([^:]+):\\s*(.*)$/.exec(line);
+ if (m) headers[m[1]] = m[2];
+}
+headers["User-Agent"] = args[args.indexOf("-user_agent") + 1];
+headers.Range = "bytes=0-1023";
+const res = await fetch(url, { headers });
+if (res.status !== 206 && res.status !== 200) {
+ process.stderr.write(\`[https @ 0x1] HTTP error \${res.status} \${res.status === 429 ? "Too Many Requests" : "Forbidden"}\\n\${url}: Server returned \${res.status}\\n\`);
+ process.exit(1);
+}
+writeFileSync(out, Buffer.from(await res.arrayBuffer()));
+`,
+);
+await chmod(FFMPEG, 0o755);
+
+const CLAIM = "FAKE-TEST-VALUEFAKE-TEST-VALUE01234567";
+const PAGE = `https://odysee.com/@synthetic:1/a-synthetic-stream:${CLAIM.slice(0, 1)}`;
+const FILE_PATH = `/v6/streams/${CLAIM}/sd0.mp4`;
+const BODY = Buffer.alloc(64 * 1024, 7);
+
+let n = 0;
+async function videoDir(): Promise<string> {
+ const d = path.join(ROOT, `case-${++n}`, "data", CLAIM);
+ await mkdir(d, { recursive: true });
+ return d;
+}
+
+function storedOf(cdn: FakeRangedCdn, p = FILE_PATH): StoredMediaUrl & { why: "only" } {
+ return { url: `${cdn.base}${p}`, host: "player.odycdn.com", platform: "odysee", referer: "https://odysee.com/", why: "only" };
+}
+
+function opts(dir: string, cdn: FakeRangedCdn, extra: Partial<FetchWindowOpts> = {}): FetchWindowOpts {
+ return {
+ channelSlug: "c",
+ channelConfig: {} as ChannelConfig,
+ paths: { ffmpegBin: FFMPEG } as unknown as Paths,
+ videoDir: dir,
+ videoId: CLAIM,
+ videoUrl: PAGE,
+ storedMedia: storedOf(cdn),
+ from: 10,
+ to: 20,
+ provenance: { requestedBy: "test" },
+ onLog: () => {},
+ signal: new AbortController().signal,
+ corruptRetryGapMs: 0,
+ ...extra,
+ };
+}
+
+// An opener that unlocks the fake CDN, as a player's page view does.
+function unlocking(cdn: FakeRangedCdn, pages: string[]): PageOpener {
+ return async ({ pageUrl }) => {
+ pages.push(pageUrl);
+ cdn.unlock();
+ return { ok: true, mediaStatuses: [206] };
+ };
+}
+
+beforeEach(() => {
+ clearPlatformGaps();
+ clearStoredUrlFiles();
+});
+
+test("the cut opens the video's page first, then cuts; the window records the open", async () => {
+ const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: BODY }, requireUnlock: true });
+ try {
+ const pages: string[] = [];
+ const dir = await videoDir();
+ const res = await fetchWindowManaged(opts(dir, cdn, { storedUrlCut: { openPage: unlocking(cdn, pages), gapMs: 0 } }));
+ assert.deepEqual(pages, [PAGE], "the PAGE url, once");
+ assert.equal(res.bytes, 1024);
+ const prov = (await listClipWindows(dir))[0]?.provenance;
+ assert.equal(prov?.source, "stored-media-url");
+ assert.equal(prov?.pageOpens, 1);
+ const read = cdn.requests.find((r) => r.status === 206);
+ assert.equal(read?.referer, "https://odysee.com/");
+ } finally {
+ await cdn.close();
+ }
+});
+
+test("a run's page state: a second window of the same video opens nothing and owes no stored-URL gap", async () => {
+ const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: BODY }, requireUnlock: true });
+ try {
+ const pages: string[] = [];
+ const waits: number[] = [];
+ const sleep = async (ms: number) => {
+ waits.push(ms);
+ clearPlatformGaps();
+ };
+ const pageSession = newStoredPageSession();
+ const cut = { pageSession, openPage: unlocking(cdn, pages), gapMs: 60_000, sleep };
+ const dir = await videoDir();
+ await fetchWindowManaged(opts(dir, cdn, { storedUrlCut: cut }));
+ const second = await fetchWindowManaged(opts(dir, cdn, { storedUrlCut: cut, from: 40, to: 50 }));
+ assert.deepEqual(pages, [PAGE], "opened before the first cut only");
+ assert.deepEqual(waits, [], "the same file read last: no stored-URL gap");
+ assert.equal(second.provenance?.pageOpens, undefined, "the second cut opened nothing");
+ assert.equal(pageSession.opens, 1);
+ } finally {
+ await cdn.close();
+ }
+});
+
+test("a 429 after a cut served since the open opens the page again and cuts once more", async () => {
+ // The unlock lapses after one cut's bytes.
+ const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: BODY }, requireUnlock: true, unlockBytes: 1024 });
+ try {
+ const pages: string[] = [];
+ const log = { s: "" };
+ const cut = { pageSession: newStoredPageSession(), openPage: unlocking(cdn, pages), gapMs: 0 };
+ const dir = await videoDir();
+ await fetchWindowManaged(opts(dir, cdn, { storedUrlCut: cut }));
+ const second = await fetchWindowManaged(
+ opts(dir, cdn, { storedUrlCut: cut, from: 40, to: 50, onLog: (s) => (log.s += s) }),
+ );
+ assert.equal(pages.length, 2);
+ assert.equal(second.provenance?.pageOpens, 1);
+ assert.match(log.s, /HTTP Error 429 from player\.odycdn\.com after 1 cut\(s\) since the page was opened; opening it again/);
+ } finally {
+ await cdn.close();
+ }
+});
+
+test("a 429 straight after an open is a rate limit: no second open, the backoff recorded", async () => {
+ const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: BODY }, requireUnlock: true });
+ try {
+ const pages: string[] = [];
+ const backoffs: string[] = [];
+ // An open that does NOT unlock (the CDN still refuses).
+ const openPage: PageOpener = async ({ pageUrl }) => {
+ pages.push(pageUrl);
+ return { ok: false, mediaStatuses: [429], error: "the player's media requests were not served" };
+ };
+ const err = await fetchWindowManaged(
+ opts(await videoDir(), cdn, {
+ storedUrlCut: { openPage, gapMs: 0 },
+ onPlatformBackoff: (c) => {
+ backoffs.push(c);
+ },
+ }),
+ ).then(
+ () => null,
+ (e: unknown) => e,
+ );
+ assert.ok(err instanceof FetchWindowError);
+ assert.equal(err.failureClass, "rate_limit");
+ assert.deepEqual(pages, [PAGE], "never twice in a row");
+ assert.deepEqual(backoffs, ["rate_limit"]);
+ } finally {
+ await cdn.close();
+ }
+});
+
+test("one gap: a cut of a new file waits out a full download's rest, and sets the rest a download waits", async () => {
+ const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: BODY } });
+ try {
+ const waits: number[] = [];
+ const log = { s: "" };
+ const sleep = async (ms: number) => {
+ waits.push(ms);
+ clearPlatformGaps();
+ };
+ // A full download of ANOTHER file on the platform just ended.
+ noteStoredUrlRead("odysee", "https://player.odycdn.com/v6/streams/other/sd.mp4", 60_000);
+ await fetchWindowManaged(
+ opts(await videoDir(), cdn, {
+ storedUrlCut: { openPage: null, gapMs: 60_000, sleep },
+ onLog: (s) => (log.s += s),
+ }),
+ );
+ assert.equal(waits.length, 1);
+ assert.ok(waits[0] > 55_000 && waits[0] <= 60_000);
+ assert.match(log.s, /A cut from the stored media URL \(odysee\) asks for a gap between videos: waiting \d+s/);
+ // …and the cut set the rest the next download reads.
+ assert.ok(platformGapRemainingMs(storedUrlGapKey("odysee")) > 55_000);
+ assert.equal(storedUrlLastFile("odysee"), storedOf(cdn).url);
+ } finally {
+ await cdn.close();
+ }
+});
+
+test("a page cut (no stored URL) opens no page and touches no stored-URL gap", async () => {
+ const ytdlp = path.join(ROOT, "fake-ytdlp.mjs");
+ await writeFile(
+ ytdlp,
+ `#!/usr/bin/env node
+import { writeFileSync } from "node:fs";
+const a = process.argv.slice(2);
+writeFileSync(a[a.indexOf("-o") + 1], "mp4");
+`,
+ );
+ await chmod(ytdlp, 0o755);
+ const pages: string[] = [];
+ const dir = await videoDir();
+ const res = await fetchWindowManaged({
+ channelSlug: "c",
+ channelConfig: { audioCheck: { enabled: false } } as ChannelConfig,
+ paths: { ytdlpBin: ytdlp, ffmpegBin: FFMPEG } as unknown as Paths,
+ videoDir: dir,
+ videoId: CLAIM,
+ videoUrl: PAGE,
+ from: 10,
+ to: 20,
+ provenance: { requestedBy: "test" },
+ onLog: () => {},
+ signal: new AbortController().signal,
+ storedUrlCut: {
+ openPage: async ({ pageUrl }) => {
+ pages.push(pageUrl);
+ return { ok: true, mediaStatuses: [] };
+ },
+ },
+ });
+ assert.deepEqual(pages, []);
+ assert.equal(platformGapRemainingMs(storedUrlGapKey("odysee")), 0);
+ assert.equal(await readFile(res.file, "utf8"), "mp4");
+});
+
+test("fetch-windows hands every stored-URL cut of one run the same page state", async () => {
+ const seen: unknown[] = [];
+ const paths = { channelsDir: path.join(ROOT, "channels") } as unknown as Paths;
+ for (const id of ["a", "b"]) await mkdir(path.join(ROOT, "channels", "ody", "data", id), { recursive: true });
+ const result = await fetchWindows({
+ paths,
+ items: [
+ { slug: "ody", id: "a", from: 1, to: 2 },
+ { slug: "ody", id: "a", from: 5, to: 6 },
+ { slug: "ody", id: "b", from: 1, to: 2 },
+ ],
+ provenance: { requestedBy: "test" },
+ gapMs: 0,
+ storedUrl: "only",
+ deps: {
+ getSettings: () => ({ sleepBetweenDownloadsSeconds: 0 }) as never,
+ readChannelConfig: async () => ({ platform: "odysee" }) as ChannelConfig,
+ assertTextReadable: async () => {},
+ savedWindowSource: async () => ({ kind: "none" }) as never,
+ findVideoSourceUrl: async (_p, _s, id) => `https://odysee.com/@x:1/${id}:1`,
+ storedMediaUrl: async (dir) => ({
+ url: `https://player.odycdn.com/v6/streams/${path.basename(dir)}/sd.mp4`,
+ host: "player.odycdn.com",
+ platform: "odysee",
+ referer: "https://odysee.com/",
+ }),
+ heldRefusal: async () => null,
+ cooldownRemainingMs: async () => 0,
+ recordBackoff: async () => {},
+ recordClean: async () => null,
+ gapRemainingMs: () => 0,
+ noteGap: () => {},
+ sleep: async () => {},
+ fetchWindow: async (o) => {
+ seen.push(o.storedUrlCut?.pageSession);
+ return { file: "x", from: o.from, to: o.to, bytes: 1, cached: false, provenance: null };
+ },
+ },
+ });
+ assert.equal(result.storedUrl.length, 3);
+ assert.equal(seen.length, 3);
+ assert.ok(seen[0], "a page state is passed");
+ assert.ok(seen.every((s) => s === seen[0]), "one page state for the run");
+});
diff --git a/common/ytdlp/odyseeBrowserLookup.test.ts b/common/ytdlp/odyseeBrowserLookup.test.ts
@@ -0,0 +1,139 @@
+// One video's metadata from its page in a (fake) browser (release 32 R9): the
+// record written whole or patched, paced, and the channel's filters applied to
+// what it finds. No browser: testing/web/fakeOdyseePage.mjs answers.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/odyseeBrowserLookup.test.ts
+
+import { test, beforeEach } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import {
+ browserLookupDecision,
+ browserLookupGapKey,
+ browserLookupVideo,
+ browserLookupWanted,
+ matchFiltersOf,
+ titleMatchFilter,
+} from "./odyseeBrowserLookup";
+import { readOdyseePage } from "./odyseePageReader";
+import { clearPlatformGaps, platformGapRemainingMs } from "../jobs/platformGap";
+import {
+ cdnUrlOf,
+ fakePageReader,
+ pageUrlOf,
+ syntheticChannel,
+ syntheticClaim,
+ videoPageRead,
+} from "../testing/web/fakeOdyseePage.mjs";
+import type { ChannelConfig } from "../lib/channelConfig";
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "browserlookup-"));
+const ch = syntheticChannel({ name: "@synthchan", title: "Synth Channel" });
+const v1 = syntheticClaim({ name: "first-stream", title: "SynthShow - 01/02/2024 - Topics", channel: ch });
+const other = syntheticClaim({ name: "recommended", title: "Someone Else", channel: syntheticChannel({ name: "@other" }) });
+let n = 0;
+const dirOf = () => path.join(ROOT, `case-${++n}`, "data", v1.claim_id);
+const noLog = () => {};
+const signal = new AbortController().signal;
+
+beforeEach(() => clearPlatformGaps());
+
+test("no record yet: the whole record is written from the page, with its stored media URL", async () => {
+ const reader = fakePageReader({ [pageUrlOf(v1)]: videoPageRead({ claim: v1, related: [other] }) });
+ const dir = dirOf();
+ const r = await browserLookupVideo({ videoDir: dir, pageUrl: pageUrlOf(v1), onLog: noLog, signal, deps: { reader, gapMs: 0 } });
+ assert.equal(r.status, "written");
+ assert.ok("stored" in r && r.stored?.url === cdnUrlOf(v1));
+ const disk = JSON.parse(await readFile(path.join(dir, "metadata.info.json"), "utf8"));
+ assert.equal(disk._source, "browser");
+ assert.equal(disk.id, v1.claim_id);
+ assert.deepEqual(reader.calls, [{ pageUrl: pageUrlOf(v1), play: true, scrolls: 0 }], "a video page is played");
+});
+
+test("a record with no stored URL is patched (the format and what it lacks), in the history as browser-lookup", async () => {
+ const dir = dirOf();
+ await mkdir(dir, { recursive: true });
+ await writeFile(
+ path.join(dir, "metadata.info.json"),
+ JSON.stringify({ id: v1.claim_id, title: "Kept Title", webpage_url: pageUrlOf(v1), extractor: "lbry" }),
+ );
+ const reader = fakePageReader({ "*": videoPageRead({ claim: v1 }) });
+ const r = await browserLookupVideo({ videoDir: dir, pageUrl: pageUrlOf(v1), onLog: noLog, signal, deps: { reader, gapMs: 0 } });
+ assert.equal(r.status, "patched");
+ const disk = JSON.parse(await readFile(path.join(dir, "metadata.info.json"), "utf8"));
+ assert.equal(disk.title, "Kept Title", "a key it has is never replaced");
+ assert.equal(disk.formats[0].url, cdnUrlOf(v1));
+ assert.equal(disk._source, undefined, "a patched yt-dlp record is not re-labelled");
+ assert.ok(disk._browserLookupAt);
+ const history = JSON.parse(await readFile(path.join(dir, "metadata.history.json"), "utf8"));
+ assert.equal(history.entries.at(-1).by, "browser-lookup");
+ const again = await browserLookupVideo({ videoDir: dir, pageUrl: pageUrlOf(v1), onLog: noLog, signal, deps: { reader, gapMs: 0 } });
+ assert.equal(again.status, "unchanged");
+});
+
+test("a page that names no such claim is not-found; one that cannot be read is unreadable; nothing written", async () => {
+ const dir = dirOf();
+ const wrong = fakePageReader({ "*": videoPageRead({ claim: other }) });
+ const r = await browserLookupVideo({ videoDir: dir, pageUrl: pageUrlOf(v1), onLog: noLog, signal, deps: { reader: wrong, gapMs: 0 } });
+ assert.equal(r.status, "not-found");
+ const dead = fakePageReader({});
+ const r2 = await browserLookupVideo({ videoDir: dir, pageUrl: pageUrlOf(v1), onLog: noLog, signal, deps: { reader: dead, gapMs: 0 } });
+ assert.equal(r2.status, "unreadable");
+ await assert.rejects(readFile(path.join(dir, "metadata.info.json")));
+});
+
+test("not an Odysee page: refused before any read", async () => {
+ const reader = fakePageReader({ "*": videoPageRead({ claim: v1 }) });
+ const r = await browserLookupVideo({ videoDir: dirOf(), pageUrl: "https://www.youtube.com/watch?v=abcdefghijk", onLog: noLog, signal, deps: { reader } });
+ assert.equal(r.status, "refused");
+ assert.equal(reader.calls.length, 0);
+});
+
+test("paced: the second lookup on the platform waits out the gap the first set", async () => {
+ const reader = fakePageReader({ "*": videoPageRead({ claim: v1 }) });
+ const waits: number[] = [];
+ const sleep = async (ms: number) => {
+ waits.push(ms);
+ clearPlatformGaps();
+ };
+ await browserLookupVideo({ videoDir: dirOf(), pageUrl: pageUrlOf(v1), onLog: noLog, signal, deps: { reader, gapMs: 60_000, sleep } });
+ assert.deepEqual(waits, []);
+ assert.ok(platformGapRemainingMs(browserLookupGapKey("odysee")) > 55_000);
+ await browserLookupVideo({ videoDir: dirOf(), pageUrl: pageUrlOf(v1), onLog: noLog, signal, deps: { reader, gapMs: 60_000, sleep } });
+ assert.equal(waits.length, 1);
+});
+
+test("the real reader never opens a browser under a test runner", async () => {
+ const log = { s: "" };
+ const r = await readOdyseePage({ pageUrl: pageUrlOf(v1), signal, onLog: (s) => (log.s += s) });
+ assert.equal(r.ok, false);
+ assert.match(r.error ?? "", /test runner/);
+});
+
+test("the opt-in: the request's word, else the channel's", () => {
+ assert.equal(browserLookupWanted(undefined, {}), false);
+ assert.equal(browserLookupWanted(undefined, { browserLookup: true }), true);
+ assert.equal(browserLookupWanted(false, { browserLookup: true }), false);
+ assert.equal(browserLookupWanted(true, {}), true);
+});
+
+test("the channel's yt-dlp title match filter is applied; one it cannot read refuses", () => {
+ assert.deepEqual(matchFiltersOf({ ytdlpExtraArgs: ["--match-filters=title~='SynthShow'", "--match-filter", "title~=\"(?i)other\""] }), [
+ "title~='SynthShow'",
+ 'title~="(?i)other"',
+ ]);
+ assert.ok(titleMatchFilter("title~='(?i)synthshow'")?.test("SYNTHSHOW live"));
+ assert.equal(titleMatchFilter("duration>600"), null);
+ assert.equal(titleMatchFilter("title~='a' & duration>600"), null);
+ const cfg = (args: string[]) => ({ handling: "transcribe", ytdlpExtraArgs: args }) as ChannelConfig;
+ const s = { skipLiveDownloads: true };
+ assert.deepEqual(browserLookupDecision(cfg(["--match-filters=title~='SynthShow'"]), { title: "SynthShow - x" }, s), { ok: true });
+ const no = browserLookupDecision(cfg(["--match-filters=title~='SynthShow'"]), { title: "A vlog" }, s);
+ assert.equal(no.ok, false);
+ assert.ok(!no.ok && no.skip && no.filter === "ytdlpMatchFilter");
+ const cannot = browserLookupDecision(cfg(["--match-filters=duration>600"]), { title: "SynthShow" }, s);
+ assert.ok(!cannot.ok && !cannot.skip);
+ assert.deepEqual(browserLookupDecision(cfg([]), { title: "anything" }, s), { ok: true });
+});
diff --git a/common/ytdlp/odyseeBrowserLookup.ts b/common/ytdlp/odyseeBrowserLookup.ts
@@ -0,0 +1,263 @@
+// ONE VIDEO'S METADATA FROM ITS PAGE, IN A BROWSER (release 32 R9).
+//
+// When yt-dlp's lbry lookup answers 429 (the prefetch, a refresh), a record
+// that was never fetched has no metadata.info.json — and so no stored media
+// URL for the stored-URL download (lib/storedMediaUrl.ts) to read. The page
+// itself answers a browser (measured 2026-10-17), so this opens the video's
+// page (ytdlp/odyseePageReader.ts), reads the claim and the file the player
+// asks for out of the page's own API answers (lib/odyseePageApi.ts), and
+// writes the record yt-dlp would have written, marked `_source: "browser"`.
+//
+// WHAT IS WRITTEN. No file yet: the whole record. A file already there: only
+// what it lacks — keys it does not have, and the one `original` format (with
+// its top-level twins) when it stores no media URL the allowlist trusts —
+// through `patchMetadataInfo` as writer `browser-lookup`, so the change is in
+// metadata.history.json. A yt-dlp prefetch later rewrites the file whole, as
+// it always has.
+//
+// PACED LIKE THE LOOKUP: one page per platform per BROWSER_LOOKUP gap (the
+// platform's import floor, 60 s on Odysee), waited out before and set at the
+// start and the end (jobs/platformGap.ts, key `browser-lookup:<platform>`).
+//
+// THE CHANNEL'S FILTERS STILL DECIDE. A lookup asks no yt-dlp, so the
+// channel's `--match-filter(s)` in `ytdlpExtraArgs` would never be applied to
+// what it finds: `browserLookupDecision` applies the one form it can read
+// (`title~='<regex>'`) and the app's download filters, and a channel whose
+// match filter it cannot read is refused rather than fetched unfiltered.
+//
+// Odysee only (BROWSER_LOOKUP_PLATFORMS); opt-in per channel
+// (`browserLookup`) or per request.
+
+import path from "node:path";
+import { mkdir, readFile } from "node:fs/promises";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { detectPlatform } from "../lib/platform";
+import { writeJsonAtomic } from "../lib/jsonFile-server";
+import { patchMetadataInfo } from "../lib/metadataHistory-server";
+import { storedMediaUrlFromInfo, type StoredMediaUrl } from "../lib/storedMediaUrl";
+import {
+ claimForPage,
+ claimsFromResponses,
+ odyseeInfoFromClaim,
+ streamingUrlFor,
+} from "../lib/odyseePageApi";
+import { evaluateDownloadFilters } from "../lib/downloadFilters";
+import { notePlatformGap, platformGapRemainingMs, waitForPlatformGap } from "../jobs/platformGap";
+import { platformImportMinGapSeconds } from "./platformArgs.mjs";
+import { readOdyseePage, type PageApiReader } from "./odyseePageReader";
+
+export const BROWSER_LOOKUP_PLATFORMS: readonly string[] = ["odysee"];
+
+export function browserLookupGapKey(platform: string): string {
+ return `browser-lookup:${platform}`;
+}
+
+export function browserLookupGapMs(platform: string): number {
+ // A recorded read (the e2e server's E2E_ODYSEE_PAGE_FIXTURE) asks no
+ // platform anything: no gap.
+ if (process.env.E2E_ODYSEE_PAGE_FIXTURE) return 0;
+ return Math.max(60, platformImportMinGapSeconds(platform)) * 1000;
+}
+
+// The request's choice, else the channel's.
+export function browserLookupWanted(
+ request: boolean | undefined,
+ config: Pick<ChannelConfig, "browserLookup">,
+): boolean {
+ return request ?? config.browserLookup === true;
+}
+
+export type BrowserLookupDeps = {
+ reader?: PageApiReader;
+ // The gap between two page reads on a platform (absent = browserLookupGapMs).
+ gapMs?: number;
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
+};
+
+export type BrowserLookupResult =
+ | {
+ status: "written" | "patched" | "unchanged";
+ info: Record<string, unknown>;
+ stored: StoredMediaUrl | null;
+ claimId: string;
+ }
+ | { status: "refused" | "unreadable" | "not-found"; error: string };
+
+const INFO_JSON = "metadata.info.json";
+
+// Keys of the one format's top-level twins: written together or not at all.
+const FORMAT_KEYS = ["formats", "url", "format_id", "ext", "protocol", "filesize", "width", "height"] as const;
+
+export async function browserLookupVideo(opts: {
+ videoDir: string;
+ pageUrl: string;
+ onLog: (s: string) => void;
+ signal: AbortSignal;
+ requestedBy?: string;
+ deps?: BrowserLookupDeps;
+}): Promise<BrowserLookupResult> {
+ const { videoDir, pageUrl, onLog, signal } = opts;
+ const platform = detectPlatform(pageUrl);
+ if (!platform || !BROWSER_LOOKUP_PLATFORMS.includes(platform)) {
+ return { status: "refused", error: `a browser lookup is for ${BROWSER_LOOKUP_PLATFORMS.join(", ")} pages, not ${pageUrl}` };
+ }
+ const key = browserLookupGapKey(platform);
+ const gapMs = opts.deps?.gapMs ?? browserLookupGapMs(platform);
+ try {
+ await waitForPlatformGap({
+ label: `A browser lookup (${platform})`,
+ remainingMs: () => platformGapRemainingMs(key),
+ signal,
+ onLog: (line) => onLog(`${line}\n`),
+ ...(opts.deps?.sleep ? { sleep: opts.deps.sleep } : {}),
+ });
+ } catch {
+ return { status: "unreadable", error: "cancelled while waiting for the gap between browser lookups" };
+ }
+ notePlatformGap(key, gapMs);
+ const reader = opts.deps?.reader ?? readOdyseePage;
+ let read;
+ try {
+ read = await reader({ pageUrl, signal, onLog, play: true });
+ } finally {
+ notePlatformGap(key, gapMs);
+ }
+ if (!read.ok && read.responses.length === 0) {
+ return { status: "unreadable", error: `the page could not be read (${read.error ?? "no API answer"})` };
+ }
+ const claims = claimsFromResponses(read.responses);
+ const claim = claimForPage(claims, pageUrl);
+ if (!claim) {
+ return {
+ status: "not-found",
+ error: `the page's API answers (${read.responses.length}) name no stream claim for ${pageUrl}`,
+ };
+ }
+ const streamingUrl = streamingUrlFor(claim.claim_id, read.responses, read.mediaUrls);
+ const at = new Date().toISOString();
+ const info = odyseeInfoFromClaim(claim, { pageUrl, streamingUrl, at });
+ onLog(
+ `The page names ${claim.claim_id} ("${String(info.title)}")` +
+ (streamingUrl ? `, its file ${new URL(streamingUrl).host}` : ", but no media file") +
+ ".\n",
+ );
+
+ const file = path.join(videoDir, INFO_JSON);
+ let current: Record<string, unknown> | null = null;
+ let exists = false;
+ try {
+ const text = await readFile(file, "utf8");
+ exists = true;
+ const parsed: unknown = JSON.parse(text);
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) current = parsed as Record<string, unknown>;
+ } catch {
+ current = null;
+ }
+ if (exists && !current) {
+ return { status: "refused", error: `${file} is not a JSON object; not overwriting it` };
+ }
+ if (!current) {
+ await mkdir(videoDir, { recursive: true });
+ await writeJsonAtomic(file, info, { indent: 0, newline: false });
+ onLog(`Wrote ${INFO_JSON} from the page (_source: browser).\n`);
+ return { status: "written", info, stored: storedMediaUrlFromInfo(info), claimId: claim.claim_id };
+ }
+ const patch: Record<string, unknown> = {};
+ const missing = (v: unknown) => v === undefined || v === null || v === "";
+ for (const [k, v] of Object.entries(info)) {
+ if ((FORMAT_KEYS as readonly string[]).includes(k) || k === "_source" || k === "_browserLookupAt") continue;
+ if (missing(current[k])) patch[k] = v;
+ }
+ if (!storedMediaUrlFromInfo(current) && Array.isArray(info.formats)) {
+ for (const k of FORMAT_KEYS) if (info[k] !== undefined) patch[k] = info[k];
+ }
+ if (Object.keys(patch).length === 0) {
+ onLog(`${INFO_JSON} already has everything the page named; nothing written.\n`);
+ return { status: "unchanged", info: current, stored: storedMediaUrlFromInfo(current), claimId: claim.claim_id };
+ }
+ patch._browserLookupAt = at;
+ await patchMetadataInfo(videoDir, patch, {
+ by: "browser-lookup",
+ ...(opts.requestedBy ? { requestedBy: opts.requestedBy } : {}),
+ onLog,
+ });
+ const next = { ...current, ...patch };
+ onLog(`Patched ${INFO_JSON} from the page: ${Object.keys(patch).filter((k) => !k.startsWith("_")).join(", ")}.\n`);
+ return { status: "patched", info: next, stored: storedMediaUrlFromInfo(next), claimId: claim.claim_id };
+}
+
+// ---- The channel's filters, applied to what a browser lookup found ----
+
+// yt-dlp's match filters in the channel's extra args, as `--match-filter(s)
+// EXPR` or `--match-filter(s)=EXPR`.
+export function matchFiltersOf(config: Pick<ChannelConfig, "ytdlpExtraArgs">): string[] {
+ const args = config.ytdlpExtraArgs ?? [];
+ const out: string[] = [];
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i];
+ const m = /^--match-filters?=(.*)$/s.exec(a);
+ if (m) out.push(m[1]);
+ else if ((a === "--match-filter" || a === "--match-filters") && i + 1 < args.length) out.push(args[++i]);
+ }
+ return out;
+}
+
+// One filter of the form yt-dlp's `title~='<regex>'` (re.search; an inline
+// `(?i)` at the start is the case-insensitive flag). Anything else — another
+// field, `&`, `!`, a comparison — is not readable here: null.
+export function titleMatchFilter(expr: string): RegExp | null {
+ const m = /^\s*title\s*~=\s*(?:'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)")\s*$/s.exec(expr);
+ if (!m) return null;
+ let src = m[1] ?? m[2] ?? "";
+ let flags = "";
+ if (src.startsWith("(?i)")) {
+ src = src.slice(4);
+ flags = "i";
+ }
+ try {
+ return new RegExp(src, flags);
+ } catch {
+ return null;
+ }
+}
+
+export type BrowserLookupDecision =
+ | { ok: true }
+ | { ok: false; skip: true; filter: string; reason: string }
+ | { ok: false; skip: false; reason: string };
+
+// Whether a record found by a browser lookup may be downloaded (or listed):
+// the channel's readable match filters (yt-dlp ORs several), then the app's
+// download filters. A match filter this cannot read refuses outright.
+export function browserLookupDecision(
+ config: ChannelConfig,
+ info: Record<string, unknown>,
+ settings: { skipLiveDownloads: boolean },
+ onLog?: (line: string) => void,
+): BrowserLookupDecision {
+ const exprs = matchFiltersOf(config);
+ if (exprs.length > 0) {
+ const res = exprs.map(titleMatchFilter);
+ if (res.some((r) => r === null)) {
+ return {
+ ok: false,
+ skip: false,
+ reason:
+ `the channel's yt-dlp match filter (${exprs.join(" | ")}) cannot be applied to a browser lookup — ` +
+ `only title~='<regex>' can`,
+ };
+ }
+ const title = typeof info.title === "string" ? info.title : "";
+ if (!res.some((r) => r!.test(title))) {
+ return { ok: false, skip: true, filter: "ytdlpMatchFilter", reason: `the title does not match ${exprs.join(" | ")}` };
+ }
+ }
+ const decision = evaluateDownloadFilters({
+ metadata: info as never,
+ channelConfig: config,
+ settings,
+ ...(onLog ? { onLog } : {}),
+ });
+ if (decision?.skip) return { ok: false, skip: true, filter: decision.filter, reason: decision.reason };
+ return { ok: true };
+}
diff --git a/common/ytdlp/odyseePageReader.ts b/common/ytdlp/odyseePageReader.ts
@@ -0,0 +1,171 @@
+// READ AN ODYSEE PAGE THE WAY A BROWSER LOADS IT (release 32 R9).
+//
+// The live finding (2026-10-17): a headless Chromium page load of odysee.com
+// gets 200 from Odysee's API where yt-dlp's lbry extractor gets 429. So when
+// the lookup is refused, the page itself is opened — a fresh context, no
+// cookies, the same headless Playwright as the player-page opener
+// (storedUrlPageOpen.ts) — and every JSON answer of the API hosts
+// (lib/odyseePageApi.ts ODYSEE_API_HOSTS) is kept with its request body, plus
+// the URLs the player asks the CDN for. lib/odyseePageApi.ts reads them.
+//
+// A VIDEO page is played for a few seconds (so the player asks `get` and the
+// CDN for the file — which is also the page open that unlocks the CDN for a
+// stored-URL read that follows). A CHANNEL page is scrolled `scrolls` times, a
+// few seconds apart, so it lists more of its uploads.
+//
+// INJECTED: callers take a `PageApiReader`; tests pass a fake built from
+// recorded answers and never launch a browser. Under a test runner
+// (NODE_TEST_CONTEXT) the real reader refuses. On the e2e server,
+// E2E_ODYSEE_PAGE_FIXTURE names a JSON file of recorded reads keyed by page URL
+// (`"*"` for any), answered instead of a browser.
+
+import { readFile } from "node:fs/promises";
+import { importPlaywright } from "../social/playwrightRuntime";
+import { isOdyseeApiUrl, type PageApiResponse } from "../lib/odyseePageApi";
+
+export type PageApiRead = {
+ ok: boolean;
+ responses: PageApiResponse[];
+ // The CDN URLs the player requested, in order.
+ mediaUrls: string[];
+ error?: string;
+};
+
+export type PageApiReader = (opts: {
+ pageUrl: string;
+ signal: AbortSignal;
+ onLog: (s: string) => void;
+ // A video page: press play and let it play (the player asks for its file).
+ play?: boolean;
+ // A channel page: scroll to the end this many times.
+ scrolls?: number;
+}) => Promise<PageApiRead>;
+
+export const PAGE_READ_SETTLE_MS = 10_000;
+export const PAGE_READ_PLAY_MS = 8_000;
+export const PAGE_READ_SCROLL_MS = 3_000;
+export const PAGE_READ_GOTO_TIMEOUT_MS = 45_000;
+// A bound on one channel read: a page that keeps loading forever is not read
+// forever.
+export const PAGE_READ_MAX_SCROLLS = 40;
+
+function wait(ms: number, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve) => {
+ if (signal.aborted) return resolve();
+ const t = setTimeout(() => {
+ signal.removeEventListener("abort", done);
+ resolve();
+ }, ms);
+ function done() {
+ clearTimeout(t);
+ resolve();
+ }
+ signal.addEventListener("abort", done, { once: true });
+ });
+}
+
+// The e2e server's recorded reads (E2E_ODYSEE_PAGE_FIXTURE): `{ "<page url>":
+// PageApiRead, "*": PageApiRead }`. Read on every call (a spec writes it).
+async function fixtureRead(file: string, pageUrl: string): Promise<PageApiRead> {
+ try {
+ const all = JSON.parse(await readFile(file, "utf8")) as Record<string, PageApiRead>;
+ const hit = all[pageUrl] ?? all["*"];
+ if (hit) return { ok: hit.ok !== false, responses: hit.responses ?? [], mediaUrls: hit.mediaUrls ?? [] };
+ return { ok: false, responses: [], mediaUrls: [], error: `no recorded read for ${pageUrl}` };
+ } catch (err) {
+ return { ok: false, responses: [], mediaUrls: [], error: (err as Error).message };
+ }
+}
+
+// The real reader. Never throws: a page that could not be read is `ok: false`
+// with the reason, and the caller decides.
+export const readOdyseePage: PageApiReader = async ({ pageUrl, signal, onLog, play, scrolls }) => {
+ const responses: PageApiResponse[] = [];
+ const mediaUrls: string[] = [];
+ const fixture = process.env.E2E_ODYSEE_PAGE_FIXTURE;
+ if (fixture) {
+ onLog(`Reading ${pageUrl} from the recorded page answers (E2E_ODYSEE_PAGE_FIXTURE).\n`);
+ return fixtureRead(fixture, pageUrl);
+ }
+ if (process.env.NODE_TEST_CONTEXT) {
+ onLog(`Not opening ${pageUrl} in a browser under a test runner.\n`);
+ return { ok: false, responses, mediaUrls, error: "not opened under a test runner" };
+ }
+ let browser: { close: () => Promise<void> } | null = null;
+ const pending: Promise<void>[] = [];
+ try {
+ const { chromium } = await importPlaywright();
+ const b = await chromium.launch({ headless: true });
+ browser = b;
+ const ctx = await b.newContext({});
+ const page = await ctx.newPage();
+ type Resp = {
+ url: () => string;
+ status: () => number;
+ headers: () => Record<string, string>;
+ json: () => Promise<unknown>;
+ request: () => { postData: () => string | null; url: () => string };
+ };
+ page.on("request", ((req: { url: () => string }) => {
+ try {
+ const u = new URL(req.url());
+ if (u.hostname.endsWith(".odycdn.com") && u.pathname.includes("/streams/")) mediaUrls.push(req.url());
+ } catch {
+ /* not a URL */
+ }
+ }) as never);
+ page.on("response", ((r: Resp) => {
+ const url = r.url();
+ if (!isOdyseeApiUrl(url)) return;
+ if (!/json/i.test(r.headers()["content-type"] ?? "")) return;
+ pending.push(
+ (async () => {
+ let body: unknown;
+ try {
+ body = await r.json();
+ } catch {
+ return;
+ }
+ let request: unknown;
+ try {
+ const raw = r.request().postData();
+ request = raw ? JSON.parse(raw) : undefined;
+ } catch {
+ request = undefined;
+ }
+ responses.push({ url, status: r.status(), ...(request !== undefined ? { request } : {}), body });
+ })(),
+ );
+ }) as never);
+ onLog(`Opening ${pageUrl} in a headless browser to read its own API answers.\n`);
+ await page.goto(pageUrl, { waitUntil: "domcontentloaded", timeout: PAGE_READ_GOTO_TIMEOUT_MS }).catch(() => {});
+ await wait(PAGE_READ_SETTLE_MS, signal);
+ if (play && !signal.aborted) {
+ await page
+ .evaluate(
+ `(() => { const b = document.querySelector(".vjs-big-play-button, [aria-label*='Play']"); if (b) { b.click(); return; } const v = document.querySelector("video"); if (v) { v.muted = true; v.play().catch(() => {}); } })()`,
+ )
+ .catch(() => {});
+ await wait(PAGE_READ_PLAY_MS, signal);
+ }
+ const n = Math.min(Math.max(0, scrolls ?? 0), PAGE_READ_MAX_SCROLLS);
+ for (let i = 0; i < n && !signal.aborted; i++) {
+ await page.evaluate("window.scrollTo(0, document.body.scrollHeight)").catch(() => {});
+ await wait(PAGE_READ_SCROLL_MS, signal);
+ }
+ await Promise.allSettled(pending);
+ onLog(
+ `Read ${pageUrl}: ${responses.length} API answer(s) ` +
+ `(${responses.filter((r) => r.status >= 200 && r.status < 300).length} ok), ` +
+ `${mediaUrls.length} media request(s).\n`,
+ );
+ return { ok: responses.some((r) => r.status >= 200 && r.status < 300), responses, mediaUrls };
+ } catch (err) {
+ const error = (err as Error).message;
+ onLog(`Could not read ${pageUrl} in a browser: ${error}\n`);
+ await Promise.allSettled(pending);
+ return { ok: false, responses, mediaUrls, error };
+ } finally {
+ await browser?.close().catch(() => {});
+ }
+};
diff --git a/common/ytdlp/storedUrlPageOpen.ts b/common/ytdlp/storedUrlPageOpen.ts
@@ -57,6 +57,20 @@ function abortableWait(ms: number, signal: AbortSignal): Promise<void> {
// regardless (the CDN may serve it anyway).
export const openPlayerPage: PageOpener = async ({ pageUrl, cdnHost, signal, onLog }) => {
const mediaStatuses: number[] = [];
+ // NEVER A BROWSER UNDER A TEST RUNNER (release 32 R9). node's runner (and
+ // tsx --test) sets NODE_TEST_CONTEXT in every test file's process: a test
+ // that reaches the real opener — an editor route test running the whole cut —
+ // gets "not opened" and reads on, instead of a headless browser on the
+ // network. Tests that exercise the open inject their own opener.
+ if (process.env.NODE_TEST_CONTEXT) {
+ onLog(`Not opening the player's page under a test runner (${pageUrl}).\n`);
+ return { ok: false, mediaStatuses, error: "not opened under a test runner" };
+ }
+ // Nor on the e2e server (which sets E2E_ODYSEE_PAGE_FIXTURE on every slot).
+ if (process.env.E2E_ODYSEE_PAGE_FIXTURE) {
+ onLog(`Not opening the player's page on the e2e server (${pageUrl}).\n`);
+ return { ok: false, mediaStatuses, error: "not opened on the e2e server" };
+ }
let browser: { close: () => Promise<void> } | null = null;
try {
const { chromium } = await importPlaywright();
@@ -96,3 +110,19 @@ export const openPlayerPage: PageOpener = async ({ pageUrl, cdnHost, signal, onL
await browser?.close().catch(() => {});
}
};
+
+// THE CLIP CUT'S PAGE STATE FOR ONE RUN (release 32 R9). A fetch-windows run
+// opens a video's page before the first cut of that video, and again only on
+// a refusal that follows a cut served since the last open (the unlock may
+// have lapsed) — never twice in a row: a refusal straight after an open means
+// the open did not unlock the file, and another will not either. Keyed by the
+// video's PAGE url. A run that passes none gets a fresh one per window (a
+// single-window job opens the page before its one cut).
+export type StoredPageSession = {
+ pages: Map<string, { cutsSinceOpen: number }>;
+ opens: number;
+};
+
+export function newStoredPageSession(): StoredPageSession {
+ return { pages: new Map(), opens: 0 };
+}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -4,6 +4,9 @@
- **Partial transcripts wait for the full audio first.** A video whose download completed with malformed audio (a corrupt full source) used to get a salvage transcript, with gaps, as soon as anyone pressed Transcribe. When the video's record stores an Odysee media URL, Transcribe and the corrupt full sources' Retry now download from that URL first, up to two times and 20 minutes apart. The salvage transcript is made only if neither download comes back clean. A clean download is transcribed in full. **Salvage** (`transcribe-one {"salvage": true}`) still makes the partial transcript at once. The channel's line shows **awaiting full audio** for the videos still waiting, and the salvaged transcripts read **salvaged — full audio attempts: n**. The video page's salvaged notice gives the same count, the video list marks a salvaged transcript amber, and the MCP's `get_transcripts` marks it partial as `get_transcript` already did.
- **find-copy no longer reports a Wayback copy that has no video.** The Wayback Machine's video index can list a video whose file it does not hold, and such a copy then failed to fetch (404). A copy now counts as found only when one of its video files answers a request for its first bytes. Otherwise the lookup says **page captured, no video**, archive.org is tried next, and the video is recorded as none found, not as a copy that failed. Looking up copies for an article's cited windows now records none found too, as the channel and site lookup already did.
- **The verdict bench shows the model what you read, and rules each part of a claim.** A claim's cited posts and pages now go to the model beside the transcript, quoted with who posted them and when. A section heading that names a verdict is no longer shown to the model. A claim that repeats an earlier one (the same words over the same clips, as in a re-cut report) is still asked each time; `--dedupe` (the body's `"dedupe": true`) asks it once instead. The model no longer picks a verdict. It lists the claim's parts and says of each whether the evidence shows it, shows it wrong, or does not show it, and the verdict follows from those answers: every part shown is CORROBORATED, some shown and some not is PARTLY, nothing shown but a part shown wrong is CONTRADICTED, nothing shown is NOT_FOUND. What each verdict means (REPORT.md, the bench page) now says this. A part the evidence does not show makes a claim PARTLY again, as your rulings do. Proposed verdicts use the same rule. umtool's `/tools/bench` shows under each claim what the model saw (its transcript lines, its posts and pages), and under each answer its parts. This is prompt version 3. Needs a restart of the editor and umtool.
+- **An Odysee record can be read from its page in a browser when Odysee refuses yt-dlp.** The video page of an Odysee channel has **Read from the page**: it opens the video's Odysee page in a headless browser (which Odysee answers when it answers yt-dlp with 429), reads the record from what the page itself loads, and writes `metadata.info.json` — or, when there is one, adds only what it lacks and the media file the page's player asked for, so a stored-URL download can then read it. The record says `_source: "browser"`, and the change is in the metadata history. The channel's Playlist stage has **List from the page** (the uploads the channel page shows, scrolled as many times as you say, added to the top of the playlist — nothing removed, nothing downloaded) and **Read records from their pages** (a list of ids). A channel's Configure form has **Browser lookup**: with **Stored media URL downloads** set, a video whose record names no media file is looked up this way first and then downloaded. The channel's `--match-filter title~='…'` and download filters still decide what is listed and downloaded. One page a minute; Odysee only. `pnpm ops browser-lookup --json '{"slug":"<channel>","ids":["<claim id>"]}'` or `'{"slug":"<channel>","listing":true}'`. Needs a restart of the editor.
+- **The download lane takes an Odysee channel's held videos from their stored media URLs.** With **Stored media URL downloads** on (fallback or only), when Odysee is cooling down or held the lane still downloads that channel's videos whose record stores the media file — one new file per 20 minutes, without asking Odysee anything and without counting as Odysee answering. A refusal from the file's server defers the video; Odysee's own backoff is not touched. Needs a restart of the editor.
+- **Clip windows cut from Odysee's stored media URL open the video's page first, and wait their turn with full downloads.** Odysee's file server serves a video only once its player has opened the page, so **Fetch windows** with the stored media URL opens each video's page in a headless browser before its first window (again if the server refuses after a window came down), and a window of a new video waits out the same 20-minute rest a full download does — a second window of the same video does not. The window's provenance counts the page opens. Needs a restart of the editor.
- **"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.
diff --git a/editor/app/api/ops/browser-lookup/route.test.ts b/editor/app/api/ops/browser-lookup/route.test.ts
@@ -0,0 +1,104 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import {
+ cdnUrlOf,
+ channelPageRead,
+ channelUrlOf,
+ pageUrlOf,
+ syntheticChannel,
+ syntheticClaim,
+ videoPageRead,
+} from "yt-dlp-transcript-common/testing/web/fakeOdyseePage.mjs";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/browser-lookup/route.test.ts"
+//
+// `/api/ops/browser-lookup` (release 32 R9) end to end: the body's checks, the
+// door, and the job over recorded page reads (E2E_ODYSEE_PAGE_FIXTURE — no
+// browser, no network): a record completed with the file its page named, and
+// a listing added to the top of the playlist.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "browser-lookup-route-"));
+const SLUG = "demo-odysee";
+const FIXTURE = path.join(ROOT, "pages.json");
+const ch = syntheticChannel({ name: "@demo", title: "Demo" });
+const v1 = syntheticClaim({ name: "stream-one", title: "Stream One", channel: ch, releaseTime: 1700000000 });
+const v2 = syntheticClaim({ name: "stream-two", title: "Stream Two", channel: ch, releaseTime: 1700300000 });
+process.env.WORKER_TOKEN = "test-token";
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+process.env.E2E_ODYSEE_PAGE_FIXTURE = FIXTURE;
+await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 }));
+await writeFile(
+ FIXTURE,
+ JSON.stringify({
+ [pageUrlOf(v1)]: videoPageRead({ claim: v1 }),
+ [channelUrlOf(ch)]: channelPageRead({ channel: ch, pages: [[v2, v1]] }),
+ }),
+);
+const CHANNEL = path.join(ROOT, "channels", SLUG);
+await mkdir(path.join(CHANNEL, "data", v1.claim_id), { recursive: true });
+await writeFile(
+ path.join(CHANNEL, "config.json"),
+ JSON.stringify({ name: "Demo", handling: "transcribe", url: channelUrlOf(ch), platform: "odysee" }),
+);
+await writeFile(path.join(CHANNEL, "playlist"), `${pageUrlOf(v1)}\n`);
+await writeFile(
+ path.join(CHANNEL, "data", v1.claim_id, "metadata.info.json"),
+ JSON.stringify({ id: v1.claim_id, title: "Stream One", webpage_url: pageUrlOf(v1), extractor: "lbry" }),
+);
+
+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/ops/browser-lookup", {
+ method: "POST",
+ headers: { authorization: "Bearer test-token", "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+}
+
+async function settle(jobId: string): Promise<string | undefined> {
+ const reg = getRegistry();
+ for (let i = 0; i < 400; 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("the body: ids or listing, scrolls bounded", async () => {
+ assert.equal((await post({ slug: SLUG })).status, 400);
+ assert.equal((await post({ slug: SLUG, listing: true, scrolls: 41 })).status, 400);
+ assert.equal((await post({ slug: SLUG, ids: [] })).status, 400);
+});
+
+test("ids: the record is completed with the file its page named", async () => {
+ const res = await post({ slug: SLUG, ids: [v1.claim_id] });
+ assert.equal(res.status, 200, await res.clone().text());
+ const { jobId } = (await res.json()) as { jobId: string };
+ assert.equal(await settle(jobId), "done");
+ assert.deepEqual(getRegistry().get(jobId)?.spec?.params?.videoIds, [v1.claim_id], "a Retry keeps the ids");
+ const info = JSON.parse(await readFile(path.join(CHANNEL, "data", v1.claim_id, "metadata.info.json"), "utf8"));
+ assert.equal(info.formats[0].url, cdnUrlOf(v1));
+ assert.equal(info.title, "Stream One");
+ const history = JSON.parse(await readFile(path.join(CHANNEL, "data", v1.claim_id, "metadata.history.json"), "utf8"));
+ assert.equal(history.entries.at(-1).by, "browser-lookup");
+});
+
+test("listing: the page's new uploads go to the top of the playlist", async () => {
+ const res = await post({ slug: SLUG, listing: true, scrolls: 2 });
+ assert.equal(res.status, 200, await res.clone().text());
+ const { jobId } = (await res.json()) as { jobId: string };
+ assert.equal(await settle(jobId), "done");
+ const playlist = (await readFile(path.join(CHANNEL, "playlist"), "utf8")).trim().split("\n");
+ assert.deepEqual(playlist, [pageUrlOf(v2), pageUrlOf(v1)]);
+});
diff --git a/editor/app/api/ops/browser-lookup/route.ts b/editor/app/api/ops/browser-lookup/route.ts
@@ -0,0 +1,48 @@
+import { browserLookupAction } from "../../../channels/[slug]/browserLookupActions";
+import {
+ OpsInputError,
+ jobResponse,
+ ops,
+ optBool,
+ optPositiveInt,
+ optString,
+ reqSlug,
+ reqStringArray,
+} from "../_lib";
+import { PAGE_READ_MAX_SCROLLS } from "yt-dlp-transcript-common/ytdlp/odyseePageReader";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, ids?: ["<videoId>", …], listing?: true, scrolls?, queueKey? }
+// -> { ok: true, jobId }
+//
+// An Odysee record read from its page in a headless browser (release 32 R9),
+// for when yt-dlp's lbry lookup is refused: each named video's page is opened
+// and played, its claim and the file the player asks for are read out of the
+// page's own API answers, and its metadata.info.json is written (none yet:
+// whole, `_source: "browser"`) or completed (only what it lacks, and the one
+// stored format; in metadata.history.json as `browser-lookup`). `listing:
+// true` opens the channel's page, scrolls it `scrolls` times (default 5, at
+// most 40) and adds the uploads its playlist lacks at the top, newest first,
+// through the channel's title match filter. One page a minute, on the
+// platform's queue; not refused for a held platform. The log ends with a
+// `summary: {…}` line. At most 50 ids.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "ids", "listing", "scrolls", "queueKey"], async (body) => {
+ const ids = body.ids === undefined ? undefined : reqStringArray(body, "ids");
+ const listing = optBool(body, "listing");
+ if (!ids && !listing) throw new OpsInputError('Send "ids" (videos to look up) or "listing": true');
+ const scrolls = optPositiveInt(body, "scrolls");
+ if (scrolls !== undefined && scrolls > PAGE_READ_MAX_SCROLLS) {
+ throw new OpsInputError(`"scrolls" must be at most ${PAGE_READ_MAX_SCROLLS}`);
+ }
+ return jobResponse(
+ await browserLookupAction(reqSlug(body, "slug"), {
+ ...(ids ? { ids } : {}),
+ ...(listing ? { listing: true } : {}),
+ ...(scrolls !== undefined ? { scrolls } : {}),
+ ...(optString(body, "queueKey") ? { queueKey: optString(body, "queueKey") } : {}),
+ }),
+ );
+ });
+}
diff --git a/editor/app/channels/[slug]/browserLookupActions.ts b/editor/app/channels/[slug]/browserLookupActions.ts
@@ -0,0 +1,41 @@
+"use server";
+
+import { safeRevalidate } from "../../lib/safeRevalidate";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
+import { runBrowserLookupJob } from "yt-dlp-transcript-common/controller/browserLookupJob";
+import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
+
+// THE BROWSER LOOKUP (release 32 R9): an Odysee video's record, or the
+// channel's listing, read from its page in a headless browser when yt-dlp's
+// lookup is refused — the `browser-lookup` job, as the video page's "Read from
+// the page", the Playlist stage's "List from the page" and `pnpm ops
+// browser-lookup` (`/api/ops/browser-lookup`) ask for it. The work and its
+// refusals are common/controller/browserLookupJob.ts.
+export async function browserLookupAction(
+ slug: string,
+ req: { ids?: string[]; listing?: boolean; scrolls?: number; queueKey?: string },
+): Promise<StreamActionResult> {
+ const paths = getPaths();
+ const channelConfig = await readChannelConfig(paths, slug);
+ if (!channelConfig) return { ok: false, error: `Channel "${slug}" not found` };
+ const ids = (req.ids ?? []).map((s) => s.trim()).filter(Boolean);
+ return runBrowserLookupJob({
+ paths,
+ slug,
+ channelConfig,
+ ...(ids.length ? { videoIds: ids } : {}),
+ ...(req.listing ? { listing: true } : {}),
+ ...(req.scrolls !== undefined ? { scrolls: req.scrolls } : {}),
+ skipLiveDownloads: getSettings().skipLiveDownloads,
+ ...(req.queueKey ? { queueKey: req.queueKey } : {}),
+ requestedBy: "editor",
+ afterRun: () => {
+ safeRevalidate([
+ `/channels/${slug}`,
+ ...ids.map((id) => `/channels/${slug}/videos/${id}`),
+ ]);
+ },
+ });
+}
diff --git a/editor/app/channels/[slug]/components/BrowserLookupSection.tsx b/editor/app/channels/[slug]/components/BrowserLookupSection.tsx
@@ -0,0 +1,77 @@
+"use client";
+
+import { useState } from "react";
+import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
+import { cancelJobAction } from "../../../jobs/actions";
+import { browserLookupAction } from "../browserLookupActions";
+
+// THE BROWSER LOOKUP ON THE PLAYLIST STAGE (release 32 R9), for an Odysee
+// channel: the listing and a list of records read from the pages in a
+// headless browser, for when yt-dlp's lookup answers 429. Both are the
+// `browser-lookup` job (common/controller/browserLookupJob.ts).
+export function BrowserLookupSection({ slug }: { slug: string }) {
+ const [scrolls, setScrolls] = useState("5");
+ const [ids, setIds] = useState("");
+ const idList = ids
+ .split(/[\s,]+/)
+ .map((s) => s.trim())
+ .filter(Boolean);
+ const scrollCount = Math.min(40, Math.max(1, Math.floor(Number(scrolls) || 5)));
+ return (
+ <>
+ <div className="flex flex-col gap-2" data-browser-listing>
+ <div>
+ <h3 className="text-base font-semibold">List from the page</h3>
+ <p className="text-sm text-muted-foreground">
+ Open the channel's Odysee page in a headless browser and add the uploads it shows to the
+ playlist, newest first — for when Store playlist and Sync are refused. Nothing is removed and
+ nothing is downloaded; the channel's title match filter applies.
+ </p>
+ </div>
+ <label className="flex items-center gap-2 text-sm">
+ <span>Scroll the page</span>
+ <input
+ type="number"
+ min={1}
+ max={40}
+ value={scrolls}
+ onChange={(e) => setScrolls(e.target.value)}
+ aria-label="page scrolls"
+ className="w-20 rounded border border-border bg-card px-2 py-1 text-sm"
+ />
+ <span className="text-muted-foreground">times</span>
+ </label>
+ <StreamActionLog
+ trigger={() => browserLookupAction(slug, { listing: true, scrolls: scrollCount })}
+ cancelAction={cancelJobAction}
+ buttonLabel="List from the page"
+ runningLabel="Reading the channel page…"
+ />
+ </div>
+ <div className="flex flex-col gap-2" data-browser-records>
+ <div>
+ <h3 className="text-base font-semibold">Read records from their pages</h3>
+ <p className="text-sm text-muted-foreground">
+ Each video's Odysee page, one a minute: its record is written (or completed) with the media
+ file the page's player asks for, which a stored-URL download then reads. Up to 50 ids.
+ </p>
+ </div>
+ <textarea
+ value={ids}
+ onChange={(e) => setIds(e.target.value)}
+ rows={3}
+ aria-label="video ids to read from their pages"
+ placeholder="one claim id per line"
+ className="rounded border border-border bg-card px-2 py-1 font-mono text-xs"
+ />
+ <StreamActionLog
+ trigger={() => browserLookupAction(slug, { ids: idList })}
+ cancelAction={cancelJobAction}
+ buttonLabel={idList.length ? `Read ${idList.length} from the pages` : "Read from the pages"}
+ runningLabel="Reading the pages…"
+ disabled={idList.length === 0 || idList.length > 50}
+ />
+ </div>
+ </>
+ );
+}
diff --git a/editor/app/channels/[slug]/components/stages/PlaylistStage.tsx b/editor/app/channels/[slug]/components/stages/PlaylistStage.tsx
@@ -12,6 +12,7 @@ import {
} from "../../pipelineActions";
import type { MetadataScanRun } from "yt-dlp-transcript-common/controller/metadataScanStore";
import type { MetadataScanView } from "../../lib/metadataScanView";
+import { BrowserLookupSection } from "../BrowserLookupSection";
type Props = {
slug: string;
@@ -19,6 +20,8 @@ type Props = {
defaultQueueKey: string;
existingQueues: string[];
metadataScan: MetadataScanView;
+ // Release 32 R9: an Odysee channel offers the browser lookup.
+ browserLookup?: boolean;
};
export function PlaylistStage({
@@ -27,6 +30,7 @@ export function PlaylistStage({
defaultQueueKey,
existingQueues,
metadataScan,
+ browserLookup,
}: Props) {
const [storeQueue, setStoreQueue] = useState(defaultQueueKey);
const [syncQueue, setSyncQueue] = useState(defaultQueueKey);
@@ -119,6 +123,7 @@ export function PlaylistStage({
}
/>
</div>
+ {browserLookup && <BrowserLookupSection slug={slug} />}
<div className="flex flex-col gap-2">
<Heading
title="Import single video"
diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx
@@ -484,6 +484,7 @@ export default async function ChannelDetailPage({
<PlaylistStage
slug={slug}
hasUrl={!!config!.url}
+ browserLookup={(config!.platform ?? detectUrlPlatform(config!.url ?? null)) === "odysee"}
defaultQueueKey={platformDefaultQueueKey}
existingQueues={existingQueues}
metadataScan={{
diff --git a/editor/app/channels/[slug]/videos/[id]/components/BrowserLookupControl.tsx b/editor/app/channels/[slug]/videos/[id]/components/BrowserLookupControl.tsx
@@ -0,0 +1,22 @@
+"use client";
+
+import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
+import { cancelJobAction } from "../../../../../jobs/actions";
+import { browserLookupAction } from "../../../browserLookupActions";
+
+// "Read from the page" (release 32 R9): an Odysee video's record read from its
+// page in a headless browser, for when yt-dlp's lookup is refused (a 429). The
+// record gains what it lacks — and the media file the page's player asked for,
+// which the stored-URL download then reads. Offered on an Odysee record only;
+// the job's log names what it wrote.
+export function BrowserLookupControl({ slug, videoId }: { slug: string; videoId: string }) {
+ return (
+ <StreamActionLog
+ trigger={() => browserLookupAction(slug, { ids: [videoId] })}
+ cancelAction={cancelJobAction}
+ buttonLabel="Read from the page"
+ runningLabel="Reading the page…"
+ label={`Read ${videoId} from its Odysee page`}
+ />
+ );
+}
diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx
@@ -58,6 +58,9 @@ import {
type AudioIntegrityRecord,
} from "yt-dlp-transcript-common/lib/audioIntegrity";
import { RefreshMetadataControl } from "./components/RefreshMetadataControl";
+import { BrowserLookupControl } from "./components/BrowserLookupControl";
+import { BROWSER_LOOKUP_PLATFORMS } from "yt-dlp-transcript-common/ytdlp/odyseeBrowserLookup";
+import { detectPlatform as detectPagePlatform } from "yt-dlp-transcript-common/lib/platform";
import { loadVideoTags } from "./lib/videoTags";
import { loadVideoOperationPanels } from "./lib/videoOperationPanels";
import { channelTextStall } from "yt-dlp-transcript-common/lib/channelMedia";
@@ -372,6 +375,11 @@ export default async function VideoDetailPage({
existingQueues={existingQueues}
/>
)}
+ {/* Release 32 R9: an Odysee channel's record read from its page in a
+ headless browser, for when yt-dlp's lookup is refused. */}
+ {BROWSER_LOOKUP_PLATFORMS.includes(config.platform ?? detectPagePlatform(config.url ?? null) ?? "") && (
+ <BrowserLookupControl slug={slug} videoId={id} />
+ )}
</header>
<RunningJobsList jobs={activeJobs} hideChannelSlug hideVideoId />
diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx
@@ -743,6 +743,28 @@ export function ChannelForm({
new file per 20 minutes on the platform.
</span>
</label>
+ <label className="flex items-start gap-2 text-sm">
+ <input
+ type="checkbox"
+ name="browserLookup"
+ aria-label="browser lookup"
+ defaultChecked={seedChecked(state, "browserLookup", c?.browserLookup === true)}
+ className="mt-1"
+ />
+ <span className="flex flex-col gap-0.5">
+ <span className="font-medium">
+ Browser lookup{" "}
+ <span className="text-muted-foreground font-normal">
+ (with stored media URL downloads, Odysee)
+ </span>
+ </span>
+ <span className="text-xs text-muted-foreground">
+ When a video's record names no media file, read it from the
+ video's page in a headless browser first, then download from
+ the file the page names. One page a minute.
+ </span>
+ </span>
+ </label>
</Section>
<Section title="Retention & persistence">
<label className="flex flex-col gap-1 text-sm">
diff --git a/editor/app/channels/components/channelConfigToForm.ts b/editor/app/channels/components/channelConfigToForm.ts
@@ -23,6 +23,7 @@ import { AUDIO_CHECK_PLATFORMS } from "yt-dlp-transcript-common/lib/audioCheckPo
// The checkbox-shaped fields (presence, not value).
export const CHANNEL_FORM_FLAGS = [
"keepSourceVideo",
+ "browserLookup",
"downloadFilterIncludeLivestreams",
"audioCheckEnabled",
"audioCheckResumeDuringProbe",
@@ -107,6 +108,7 @@ export function channelConfigToFormData(config: ChannelConfig): FormData {
put(fd, "cookiesFromBrowser", config.cookiesFromBrowser);
put(fd, "cookieMode", config.cookieMode);
put(fd, "storedUrlDownloads", config.storedUrlDownloads);
+ if (config.browserLookup) fd.set("browserLookup", "on");
put(fd, "downloadFilterInclude", config.downloadFilter?.include);
put(fd, "downloadFilterExclude", config.downloadFilter?.exclude);
if (config.downloadFilter?.includeLivestreams) {
diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts
@@ -136,3 +136,19 @@ test("the form writes storedUrlDownloads; Never clears it; the ops patch round-t
applyChannelFormPatch(back, { storedUrlDownloads: "" });
assert.equal("storedUrlDownloads" in parseChannelForm(back).config, false);
});
+
+// The browser lookup (release 32 R9): a checkbox — checked writes `true`,
+// unchecked writes nothing; the ops patch round-trips it.
+test("the form writes browserLookup from its checkbox; unchecked clears it; the ops patch round-trips", () => {
+ assert.equal(parseChannelForm(form({ browserLookup: "on" })).config.browserLookup, true);
+ assert.equal("browserLookup" in parseChannelForm(form({})).config, false);
+ assert.ok((CHANNEL_FORM_FIELDS as readonly string[]).includes("browserLookup"));
+ const fd = channelConfigToFormData({ handling: "transcribe", name: "Synth", url: ODYSEE });
+ applyChannelFormPatch(fd, { browserLookup: true });
+ const set = parseChannelForm(fd).config;
+ assert.equal(set.browserLookup, true);
+ const back = channelConfigToFormData(set);
+ assert.equal(back.get("browserLookup"), "on");
+ applyChannelFormPatch(back, { browserLookup: false });
+ assert.equal("browserLookup" in parseChannelForm(back).config, false);
+});
diff --git a/editor/app/channels/components/parseChannelForm.ts b/editor/app/channels/components/parseChannelForm.ts
@@ -62,6 +62,7 @@ export const CHANNEL_FORM_FIELDS = [
"cookieMode",
"audioCheck",
"storedUrlDownloads",
+ "browserLookup",
"downloadFilter",
"recordedDate",
"mirror",
@@ -228,6 +229,8 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm {
const storedUrlRaw = String(formData.get("storedUrlDownloads") ?? "").trim();
const storedUrlDownloads =
isStoredUrlMode(storedUrlRaw) && storedUrlRaw !== "never" ? storedUrlRaw : undefined;
+ // The browser lookup (release 32 R9): a checkbox; unchecked = omitted.
+ const browserLookup = formData.get("browserLookup") != null;
// Download filter. Both patterns are regex SOURCES compiled with "i" at
// download time, so the form is the place that refuses an unparseable one:
@@ -409,6 +412,7 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm {
if (cookieMode) config.cookieMode = cookieMode;
if (audioCheck) config.audioCheck = audioCheck;
if (storedUrlDownloads) config.storedUrlDownloads = storedUrlDownloads;
+ if (browserLookup) config.browserLookup = true;
if (downloadFilter) config.downloadFilter = downloadFilter;
if (recordedDateTitlePattern) {
config.recordedDate = { titlePattern: recordedDateTitlePattern };
diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts
@@ -60,6 +60,7 @@ import {
replayFetchWindowAction,
} from "../channels/[slug]/videos/[id]/videoActions";
import { fetchWindowsJobAction } from "../channels/[slug]/videos/fetchWindowsAction";
+import { browserLookupAction } from "../channels/[slug]/browserLookupActions";
import type { FetchWindowsItem } from "yt-dlp-transcript-common/controller/fetchWindows";
import { reportsPrepareAction } from "../sites/lib/reportsPrepareAction";
import { reportsExportAction } from "../sites/lib/reportsExportAction";
@@ -366,6 +367,18 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = {
}
return refreshVideoMetadataAction(spec.slug, videoId, queueKey);
},
+ // An Odysee record (or the listing) read from its page in a browser: the
+ // ids and the listing flag as asked; the action re-checks the door.
+ "browser-lookup": (spec) => {
+ const { p, queueKey } = params(spec);
+ const ids = Array.isArray(p.videoIds) ? p.videoIds.filter((x): x is string => typeof x === "string") : [];
+ return browserLookupAction(spec.slug, {
+ ...(ids.length ? { ids } : {}),
+ ...(p.listing === true ? { listing: true } : {}),
+ ...(num(p.scrolls) !== undefined ? { scrolls: num(p.scrolls) } : {}),
+ ...(queueKey ? { queueKey } : {}),
+ });
+ },
"check-post-availability": (spec) => {
const { p, queueKey } = params(spec);
return checkPostAvailabilityAction(
diff --git a/editor/e2e/browser-lookup.spec.ts b/editor/e2e/browser-lookup.spec.ts
@@ -0,0 +1,86 @@
+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { test, expect } from "@playwright/test";
+import { baseUrl } from "./baseUrl";
+import { channelStage, generateReport, readJson, resetData, resolvePath, testPaths } from "./helpers";
+import { odyseePageFixtureFile } from "./servers";
+import {
+ cdnUrlOf,
+ pageUrlOf,
+ syntheticChannel,
+ syntheticClaim,
+ videoPageRead,
+} from "yt-dlp-transcript-common/testing/web/fakeOdyseePage.mjs";
+
+// Release 32 R9: the browser lookup, by hand (the UI-without-AI rule). An
+// Odysee record that stores no media URL is read from its page — here from the
+// slot's recorded page reads (E2E_ODYSEE_PAGE_FIXTURE, e2e/servers.ts; no
+// browser opens on the e2e server) — and the record gains the file the page
+// named. The per-channel setting is on the Configure form; the listing's
+// button is in the Playlist stage of an Odysee channel.
+
+const CHANNEL = "test-transcribe";
+const FIXTURE = "one-transcribe-channel";
+const ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`;
+const ch = syntheticChannel({ name: "@synthchan", title: "Synth Channel" });
+const claim = syntheticClaim({ name: "a-synthetic-stream", title: "A Synthetic Stream", channel: ch });
+const CLAIM = claim.claim_id;
+
+async function invalidate() {
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+}
+
+test("configure: the browser lookup setting saves and clears", async ({ page }) => {
+ await resetData(FIXTURE);
+ await generateReport(page, CHANNEL);
+ await page.goto(channelStage(CHANNEL, "configure"));
+ const box = page.getByLabel("browser lookup", { exact: true });
+ await expect(box).not.toBeChecked();
+ await box.check();
+ await page.getByRole("button", { name: /save changes/i }).click();
+ await expect
+ .poll(async () => (await readJson<{ browserLookup?: boolean }>(`${ROOT}/config.json`)).browserLookup)
+ .toBe(true);
+ await page.reload();
+ await expect(page.getByLabel("browser lookup", { exact: true })).toBeChecked();
+ await page.getByLabel("browser lookup", { exact: true }).uncheck();
+ await page.getByRole("button", { name: /save changes/i }).click();
+ await expect
+ .poll(async () => "browserLookup" in (await readJson<Record<string, unknown>>(`${ROOT}/config.json`)))
+ .toBe(false);
+});
+
+test("video page: Read from the page completes the record with the file the page named", async ({ page }) => {
+ test.setTimeout(120_000);
+ await resetData(FIXTURE);
+ const dir = resolvePath(`${ROOT}/data/${CLAIM}`);
+ await mkdir(dir, { recursive: true });
+ await writeFile(
+ `${dir}/metadata.info.json`,
+ JSON.stringify({ id: CLAIM, extractor: "lbry", title: "A synthetic stream", webpage_url: pageUrlOf(claim) }),
+ );
+ const fixture = odyseePageFixtureFile(resolvePath(testPaths().transcriptsDir));
+ await writeFile(fixture, JSON.stringify({ [pageUrlOf(claim)]: videoPageRead({ claim }) }));
+ try {
+ await invalidate();
+ await page.goto(`/channels/${CHANNEL}/videos/${CLAIM}`);
+ await page.getByRole("button", { name: "Read from the page" }).click();
+ await expect
+ .poll(
+ async () => {
+ const info = JSON.parse(await readFile(`${dir}/metadata.info.json`, "utf8")) as { formats?: { url: string }[] };
+ return info.formats?.[0]?.url ?? null;
+ },
+ { timeout: 90_000 },
+ )
+ .toBe(cdnUrlOf(claim));
+ const info = JSON.parse(await readFile(`${dir}/metadata.info.json`, "utf8")) as Record<string, unknown>;
+ expect(info.title).toBe("A synthetic stream");
+ expect(typeof info._browserLookupAt).toBe("string");
+ // The page now offers the stored URL the lookup found (R7's control).
+ await invalidate();
+ await page.reload();
+ await expect(page.getByLabel("stored media URL", { exact: true })).toBeVisible();
+ } finally {
+ await rm(fixture, { force: true });
+ }
+});
diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts
@@ -52,6 +52,11 @@ export function blueskyOriginFile(transcriptsDir: string): string {
return join(transcriptsDir, ".fake-bluesky-origin");
}
+/** The slot's recorded Odysee page reads (browser-lookup.spec writes it). */
+export function odyseePageFixtureFile(transcriptsDir: string): string {
+ return join(transcriptsDir, ".fake-odysee-pages.json");
+}
+
/** The start-mode build directory (scripts/e2e-stamp.mjs PACKAGES.editor.distDir). */
export const E2E_DIST_DIR = ".next/e2e";
const EXPORT_SITES_DIR = join(EDITOR_ROOT, "e2e", "fixtures", "sites");
@@ -200,6 +205,10 @@ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env)
// Where a spec names its fake Bluesky's origin (capture-posts.spec): the
// slot's own test data, so two slots never share one.
editorEnv.E2E_BLUESKY_ORIGIN_FILE = blueskyOriginFile(paths.transcriptsDir);
+ // The browser lookup's recorded page reads (browser-lookup.spec): set on
+ // every slot, so the e2e server never opens a headless browser on the
+ // network — the player-page opener refuses under it too.
+ editorEnv.E2E_ODYSEE_PAGE_FIXTURE = odyseePageFixtureFile(paths.transcriptsDir);
// A start-mode server runs the stamped build (shared, read-only); a second
// `next dev` needs a dist dir of its own (Next locks `<distDir>/dev/lock`).
if (mode === "start" && !env.CI) editorEnv.E2E_NEXT_DIST_DIR = E2E_DIST_DIR;
diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts
@@ -34,6 +34,12 @@ import { currentSlot } from "./e2e/testPaths";
// writes its fake Bluesky's loopback origin into,
// which the AppView, bsky.app and the image CDN
// then are (common/social/blueskyEndpoints.ts)
+// E2E_ODYSEE_PAGE_FIXTURE set per slot (e2e/servers.ts): the file of
+// recorded Odysee page reads the browser lookup
+// answers from (browser-lookup.spec); while it is
+// set no headless browser opens a page at all
+// (common/ytdlp/odyseePageReader.ts,
+// storedUrlPageOpen.ts)
// E2E_MODE `start` (the default): the editor runs under
// `next start` from a build the stamp vouches for
// (scripts/e2e-stamp.mjs — rebuilt through the
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -10265,3 +10265,85 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
stored URL); the video list's transcript dot is amber with "salvaged transcript (partial …)" (`VideoRow.
salvagedTranscript`); MCP `get_transcripts` adds the salvage caveat to that video's block (get_transcript and
get_video_metadata already did; the export's TranscriptModal already shows "Partial transcript: …").
+
+## Release 32 lane R9: the Odysee loop — the cut's page open, one stored-URL rest, the lane, the browser lookup (verified 2026-10-17, branch `r32/odysee-loop`)
+
+- **The clip cut opens the player's page** (`ytdlp/fetchWindowManaged.ts`, the stored-URL ffmpeg branch).
+ `FetchWindowOpts.storedUrlCut?: {pageSession?, openPage?, gapMs?, sleep?}`; production passes at most `pageSession`.
+ `StoredPageSession` (`ytdlp/storedUrlPageOpen.ts` `newStoredPageSession()`: `{pages: Map<pageUrl, {cutsSinceOpen}>,
+ opens}`): `fetchWindows` makes ONE per run and hands it to every stored-URL item; absent, `fetchWindowManaged` makes
+ one per window (kept across its corrupt re-fetch). Before the first cut of a video: open (absent `openPage` = the real
+ `openPlayerPage` for PAGE_OPEN_PLATFORMS; null = none). A 429 (stderr `429`/`Too Many Requests`) after
+ `cutsSinceOpen > 0`: open again, delete the part, cut once more; a 429 with `cutsSinceOpen === 0` (straight after an
+ open) is the `rate_limit` FetchWindowError as before. Provenance `pageOpens` (count for THIS window, > 0 only;
+ `parseClipProvenance` keeps it). `openPlayerPage` returns `{ok:false}` without a browser when `NODE_TEST_CONTEXT`
+ (node's test runner) or `E2E_ODYSEE_PAGE_FIXTURE` (the e2e server) is set.
+- **One stored-URL rest** (`jobs/storedUrlPace.ts`): `storedUrlGapRemainingMs(platform, {url?, sameFileFree?})`,
+ `noteStoredUrlRead(platform, url, gapMs)` (platformGap key `stored-url:<platform>` + the last file, on globalThis
+ `__yttStoredUrlLastFile__`), `storedUrlLastFile`, `clearStoredUrlFiles` (tests). The cut waits `sameFileFree: true`
+ (a cut of the file read last owes nothing) and notes at start and end; the full download (`runStoredUrlDownload`)
+ waits without the exemption (R7's test: the same file twice still waits) and notes through `noteStoredUrlRead`.
+ The cut's rest = `storedUrlCut.gapMs` ?? `E2E_CLIP_WINDOW_GAP_MS` (when set, ≥ 0) ?? STORED_URL_NEW_FILE_GAP_MS.
+- **The lane's stored-URL rescue** (`controller/laneStoredUrl.ts`; `autoRunner.ts` next()): `backedOff` = platforms
+ added to platformSkip by the cooldown loop that were not already skipped as busy; `rescuable` = those whose
+ `storedUrlGapRemainingMs(pf) === 0`. `storedUrlRescue({pending, owner, platformSkip, rescuable, platformOf, optedIn,
+ known})` keeps a skipped platform's id when rescuable, the owner is opted in (`storedUrlLaneMode(config, platform)`:
+ `storedUrlDownloads` only|fallback, handling transcribe, STORED_URL_PLATFORMS) and `known === true`; unknown ids are
+ read after the filter (`makeStoredUrlLaneMemo().probe`, ≤ STORED_URL_LANE_PROBES_PER_TICK = 40, `storedMediaUrl` of
+ `data/<id>`, memo for the runner's life). `Picked.storedOnly = {held}` → `LaunchArgs.storedOnly` → downloadOneManaged
+ `{storedUrl: "only", storedUrlHeld?}`. A failed stored-only unit returns `{outcome: "failed", viaStoredUrl: true}`;
+ `applyUnitOutcome`'s new first branch: rate_limit/network → `deferVideo` (6 h), no escalation, `markCompleted:
+ false`; else `markCompleted: true`, nothing touched.
+- **The browser lookup.** `lib/odyseePageApi.ts` (pure): `PageApiResponse {url, status, request?, body}`,
+ `ODYSEE_API_HOSTS` (`api.na-backend.odysee.com`, `api.odysee.com`, `api.lbry.tv`, `api.lbry.com`) +
+ `isOdyseeApiUrl`; `claimsFromResponses` (2xx only; a JSON-RPC `result`/`data`, a batch array; a claim = 40-hex
+ `claim_id` + `name` + object `value`, found bare, in `items`, or as a value of a URL-keyed result);
+ `claimForPage(claims, pageUrl)` (by the URL's `:<claim id or prefix>`, name agreeing unless the id is full; else a
+ unique stream claim by name; never "the one claim"); `streamingUrlFor(claimId, responses, mediaUrls)` (a `get`
+ result's `streaming_url` containing the claim id, `/api/vN/` → `/api/v3/`; else the first CDN request under
+ `/streams/<claimId>/`, query dropped); `odyseeInfoFromClaim(claim, {pageUrl, streamingUrl, at?})` (yt-dlp's lbry
+ fields + `upload_date` from timestamp UTC, `release_date`, one format `{format_id: "original", quality 1, ext,
+ protocol, filesize, width, height, http_headers.Referer}` and its top-level twins, `_type: "video"`,
+ `_source: "browser"`, `_browserLookupAt`); `listingFromResponses(responses, {claimId?, name?})` (stream claims signed
+ by the channel, newest first by `release_time`, `https://odysee.com/<name>:<claim_id>`); `channelClaimFor`.
+- `ytdlp/odyseePageReader.ts`: `PageApiReader({pageUrl, signal, onLog, play?, scrolls?}) → {ok, responses,
+ mediaUrls, error?}`; `readOdyseePage` (headless Playwright, fresh context; JSON answers of the API hosts with the
+ request's postData; CDN `*.odycdn.com …/streams/` request URLs; settle 10 s, play 8 s, each scroll 3 s, ≤ 40).
+ `E2E_ODYSEE_PAGE_FIXTURE` = a JSON file `{<pageUrl> | "*": PageApiRead}` answered instead (read per call).
+- `ytdlp/odyseeBrowserLookup.ts`: `BROWSER_LOOKUP_PLATFORMS = ["odysee"]`; gap key `browser-lookup:<platform>`,
+ `browserLookupGapMs` = max(60, import floor) s, 0 under the e2e fixture; `browserLookupVideo({videoDir, pageUrl,
+ onLog, signal, requestedBy?, deps?: {reader?, gapMs?, sleep?}})` → `written` (no file: whole, `writeJsonAtomic`
+ compact) | `patched` (`patchMetadataInfo` by **`browser-lookup`**, new METADATA_HISTORY_WRITERS entry: absent/null/""
+ keys, the format group only when `storedMediaUrlFromInfo(current)` is null, `_browserLookupAt`; never `_source`) |
+ `unchanged` | `refused` | `unreadable` | `not-found`. `matchFiltersOf(config)` (`--match-filter(s)[=]`),
+ `titleMatchFilter(expr)` (`title~='…'`/`"…"`, leading `(?i)`; else null), `browserLookupDecision(config, info,
+ {skipLiveDownloads})` → ok | `{skip: true, filter: "ytdlpMatchFilter"|<app filter>}` | `{skip: false}` (a match
+ filter it cannot read). `browserLookupWanted(request, config)`.
+- `downloadOneManaged({browserLookup?, browserLookupDeps?})` + channel key **`browserLookup: true`** (CHANNEL.md;
+ coercion: only `true` kept): with a stored mode and no stored URL — `only` (before `noStoredUrlOutcome`) or
+ `fallback` after a rate-limited prefetch — `storedViaBrowserLookup` looks up first (transcribe handling, the PAGE url
+ on BROWSER_LOOKUP_PLATFORMS); found → the stored-URL download as before (why `only`/`held`/`rate-limited`); a filter
+ skip → a `skipped-filtered` outcome with `filter` (dir kept); an unreadable match filter → `failed`, per_video;
+ nothing found → on as without it.
+- `controller/odyseeBrowserListing.ts` `browserListChannel({paths, slug, config, scrolls?, skipLiveDownloads, onLog,
+ signal, deps?})`: `browserListingRefusal(config)` first (an Odysee `@channel` URL; a readable match filter); the
+ channel page (default 5 scrolls); listing through `browserLookupDecision`; new ids (by `extractVideoId`) PREPENDED to
+ `playlist` (`writeFileAtomic`), every kept URL to the roster (`mergeRosterFile`, "listing"). A third `playlist`
+ writer, additive only (store-playlist and the full sweep replace it).
+- `controller/browserLookupJob.ts` `runBrowserLookupJob({paths, slug, channelConfig, videoIds?, listing?, scrolls?,
+ skipLiveDownloads, queueKey?, requestedBy?, afterRun?, deps?})`: kind **`browser-lookup`** (jobKinds: platform queue,
+ needsText, replayable, not drainable; spec params `videoIds`, `listing`, `scrolls`, `queueKey`); door: text readable,
+ ids or listing, ≤ BROWSER_LOOKUP_MAX_VIDEOS (50), ids as path segments, each id's `findVideoSourceUrl` on Odysee;
+ not refused for a held/cooling platform. Log ends `summary: {"videos":[{id,status,stored,error?}],"listing"?:…}`
+ (`browserLookupSummaryOf`); the job fails when nothing was written or listed.
+- Editor: `browserLookupAction(slug, {ids?, listing?, scrolls?, queueKey?})`
+ (`app/channels/[slug]/browserLookupActions.ts`); `POST /api/ops/browser-lookup` (`ids` non-empty strings, `listing`,
+ `scrolls` 1–40); the video page's **Read from the page** (`BrowserLookupControl`, channels whose platform/url is on
+ BROWSER_LOOKUP_PLATFORMS); the Playlist stage's `BrowserLookupSection` (`data-browser-listing`: **List from the page**,
+ `aria-label "page scrolls"`; `data-browser-records`: **Read records from their pages**, `aria-label "video ids to read
+ from their pages"`), shown for an Odysee channel (`PlaylistStage browserLookup`); the Configure form's checkbox
+ `name/aria-label "browser lookup"` (CHANNEL_FORM_FIELDS + CHANNEL_FORM_FLAGS). The e2e server sets
+ `E2E_ODYSEE_PAGE_FIXTURE` per slot (`e2e/servers.ts` `odyseePageFixtureFile` = `<transcripts>/.fake-odysee-pages.json`).
+- Test kit: `testing/web/fakeOdyseePage.mjs` — `syntheticChannel`, `syntheticClaim`, `pageUrlOf`, `channelUrlOf`,
+ `cdnUrlOf` (`/v6/streams/<claim>/<sd_hash[:6]>.mp4`), `resolveAnswer`, `claimSearchAnswer`, `getAnswer`,
+ `refusedAnswer`, `videoPageRead`, `channelPageRead`, `fakePageReader` (`.calls`).
diff --git a/plans/release-32/odysee-loop.md b/plans/release-32/odysee-loop.md
@@ -0,0 +1,141 @@
+# Release 32 lane R9 — close the Odysee loop (as shipped)
+
+Proven live (the orchestrator, 2026-10-17): Odysee's CDN serves a stream's original file to this connection only after
+a player opened that video's page (headless Chromium: goto, ~10 s, play, ~8 s); cold reads 429. A browser's page load
+also gets 200 from Odysee's API (`api.na-backend.odysee.com/api/v1/proxy`, `api.odysee.com/*`) where yt-dlp's lbry
+extractor gets 429. R7 used the page open for full downloads; this lane gives it to the clip cut, makes the cut and the
+download share one pacing state, lets the lane take held-platform stored-URL work, and adds the browser-backed lookup.
+
+## What
+
+1. **The clip cut opens the page** (`ytdlp/fetchWindowManaged.ts`, the stored-URL ffmpeg cut): R7's `PageOpener`
+ (`openPlayerPage` for PAGE_OPEN_PLATFORMS; `storedUrlCut.openPage` injects one, null = none) runs before the FIRST cut
+ of each video in a run — fetch-windows passes one `StoredPageSession` per run (`storedUrlPageOpen.ts`
+ `newStoredPageSession`), a single-window job gets a fresh one. A 429 after a cut was served since the last open opens
+ the page again and cuts once more; a 429 straight after an open is the rate limit it always was (no second open). The
+ window's provenance records `pageOpens` (`lib/clipWindow.ts`, parsed tolerantly).
+2. **One gap** (`jobs/storedUrlPace.ts`): the clip cut now reads and sets R7's `stored-url:<platform>` rest (20 min) —
+ a cut of a NEW file waits it out like a full download, a cut of the file read last (another window of the same
+ video) owes only the clip gap; both note the rest at their start and end and remember the file
+ (`noteStoredUrlRead`). A full download always waits (R7's rule, unchanged). `E2E_CLIP_WINDOW_GAP_MS` (test-only)
+ also replaces the rest a cut sets.
+3. **The lane takes held-platform stored-URL work** (`controller/laneStoredUrl.ts`, wired in `autoRunner.ts`): a
+ channel with `storedUrlDownloads` `only`/`fallback` (transcribe handling, a STORED_URL_PLATFORMS platform) keeps its
+ pending videos on a cooling or held platform whose record stores a trusted media URL — only when the platform is not
+ busy and its stored-URL rest has elapsed (one new file per rest). "Stores a URL" is a file read, remembered per video
+ for the runner's life, at most 40 unknown videos read per tick (offered from the next tick). The unit downloads as
+ `only` (`storedUrlHeld` on a held platform) and settles nothing; a FAILED stored-URL unit moves no backoff either
+ (`jobs/unitOutcome.ts`: a CDN refusal defers the video 6 h, anything else retires it for the session).
+4. **The browser-backed lookup** (Odysee only):
+ - `lib/odyseePageApi.ts` (pure): the page's API answers (`resolve`, `claim_search`, `get` through the proxy) read into
+ claims, the page's own claim (by the URL's claim id or a prefix of it, else a unique name — never "the only one", a
+ video page resolves its recommendations), the file (the `get` answer's `streaming_url` naming the claim, else the
+ player's CDN request; yt-dlp's `/api/vN/` → `/api/v3/` rule), the metadata.info.json yt-dlp's lbry extractor writes
+ (+ `_source: "browser"`, one `original` format), a channel page's listing (its own uploads, newest first).
+ - `ytdlp/odyseePageReader.ts`: the injected `PageApiReader`; the real one is headless Chromium (Playwright, a fresh
+ context, no cookies) keeping every JSON answer of the API hosts with its request body and the CDN requests; a
+ video page is played (so the player asks `get` — the same view unlocks the CDN), a channel page scrolled (bounded,
+ 40). Refuses under a test runner; answers from `E2E_ODYSEE_PAGE_FIXTURE` on the e2e server (and R7's page opener
+ opens nothing there).
+ - `ytdlp/odyseeBrowserLookup.ts` `browserLookupVideo`: paced (`browser-lookup:<platform>`, 60 s), writes the whole
+ record when there is none, else patches only what it lacks and the one format when it stores no trusted URL
+ (`patchMetadataInfo`, new history writer `browser-lookup`). `browserLookupDecision`: the channel's yt-dlp
+ `--match-filter(s) title~='<regex>'` (the one form it can read; any other refuses) and the app's download filters.
+ - `controller/odyseeBrowserListing.ts` `browserListChannel`: the channel page's uploads, filtered as yt-dlp's listing
+ would be, ADD-ONLY — new ids at the top of `playlist`, every listed id into the roster (`mergeRosterFile`,
+ "listing"). Nothing removed, nothing downloaded.
+ - `controller/browserLookupJob.ts`: the `browser-lookup` job (platform download queue, `needsText`, replayable),
+ refusals before the job (text unreadable, nothing named, > 50 ids, an id with no Odysee page URL, a listing of a
+ non-Odysee or match-filter-unreadable channel); not refused for a held platform; the log ends `summary: {json}`.
+ - The managed download (`downloadOneManaged`): with a stored-URL mode and the channel's new `browserLookup: true`
+ (or `opts.browserLookup`), a record that stores no media URL (`only`, or `fallback` after a rate-limited prefetch)
+ is looked up in the browser first and downloaded from the file the page named; a filter decline writes a
+ `skipped-filtered` outcome, an unreadable match filter a `failed` (per_video) one.
+ - Editor: `POST /api/ops/browser-lookup {slug, ids?, listing?, scrolls?, queueKey?}`; the video page's **Read from
+ the page** (Odysee channels); the Playlist stage's **List from the page** (scrolls) and **Read records from their
+ pages** (ids); the Configure form's **Browser lookup** checkbox (`aria-label "browser lookup"`); Retry; ops help,
+ COMMANDS.md, CHANNEL.md, ENVIRONMENT.md.
+
+## Files
+
+Common: `jobs/storedUrlPace.ts` (new), `ytdlp/fetchWindowManaged.ts`, `ytdlp/storedUrlPageOpen.ts`,
+`controller/fetchWindows.ts`, `ytdlp/downloadOneManaged.ts`, `lib/clipWindow.ts`, `controller/laneStoredUrl.ts` (new),
+`controller/autoRunner.ts`, `jobs/unitOutcome.ts`, `lib/odyseePageApi.ts` (new), `ytdlp/odyseePageReader.ts` (new),
+`ytdlp/odyseeBrowserLookup.ts` (new), `controller/odyseeBrowserListing.ts` (new), `controller/browserLookupJob.ts` (new),
+`lib/channelConfig.ts`, `lib/channelConfigSchema.ts`, `lib/metadataHistory.ts`, `jobs/jobKinds.ts`, `lib/envVars.ts`,
+`testing/web/fakeOdyseePage.mjs` (+ `.d.mts`, new). Editor: `app/channels/[slug]/browserLookupActions.ts` (new),
+`app/api/ops/browser-lookup/route.ts` (new), `app/channels/[slug]/components/BrowserLookupSection.tsx` (new),
+`app/channels/[slug]/videos/[id]/components/BrowserLookupControl.tsx` (new), `…/stages/PlaylistStage.tsx`,
+`app/channels/[slug]/page.tsx`, `…/videos/[id]/page.tsx`, `app/channels/components/{ChannelForm.tsx,parseChannelForm.ts,channelConfigToForm.ts}`,
+`app/jobs/jobReplayRegistry.ts`, `…/videos/[id]/videoActions.ts` (the merge's duplicate import), `e2e/servers.ts`,
+`playwright.config.ts`. `scripts/archilyzer-ops.mjs`, COMMANDS.md, CHANNEL.md, ENVIRONMENT.md.
+Tests: `ytdlp/fetchWindowStoredCut.test.ts` (7), `controller/laneStoredUrl.test.ts` (6), `lib/odyseePageApi.test.ts`
+(6), `ytdlp/odyseeBrowserLookup.test.ts` (8), `ytdlp/browserLookupDownload.test.ts` (4),
+`controller/odyseeBrowserListing.test.ts` (5), `jobs/jobKinds.test.ts` (+2 rows), `lib/channelConfigSchema.test.ts`
+(count), `controller/fetchWindowsStoredUrl.test.ts` (the rest zeroed), editor `app/api/ops/browser-lookup/route.test.ts`
+(3), `parseChannelForm.test.ts` (+1), `e2e/browser-lookup.spec.ts` (2).
+
+| Commit | What |
+| --- | --- |
+| `3c3c76cc` | common: the cut opens the page (one page state per run), one stored-URL rest (`jobs/storedUrlPace.ts`), `pageOpens`; the opener's test-runner guard; the merge's duplicate import in videoActions.ts |
+| `4dd12f67` | common: the lane's stored-URL rescue (`controller/laneStoredUrl.ts`), a failed stored-only unit moves no backoff |
+| `0d9add57` | common: the browser lookup (page reader, page-API reader, per-video lookup, listing, job), `browserLookup` in the download, CHANNEL.md, ENVIRONMENT.md, the e2e fixture knob |
+| `ae5a71bb` | editor: Read from the page, List from the page, Read records from their pages, the Configure checkbox, the ops route, Retry, the e2e spec, ops help, COMMANDS.md |
+| (this commit) | this record, FACTS, CHANGELOG |
+
+## Gates
+
+All through the shared heavy lock (`r31-locked.sh` / `r31-locked6.sh`; unit suites and tsc also through `pnpm heavy`
+with an estimate), from the worktree root:
+- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean at `4dd12f67` (state of items 1–3) and at
+ `ae5a71bb`. On `main` (`eb8d9523`) the editor did NOT type-check — `videoActions.ts` imported `StoredUrlMode` twice
+ (the R6/R7 merge); fixed in `3c3c76cc`.
+- common: 4537 at the branch's start (4536 pass, 1 skipped, measured on a clean tree) → **4573 (4572 pass, 0 fail,
+ 1 skipped)** (the one failure of the first full run was the channel-config key count, 35 → 36, fixed and re-run).
+- editor unit: 342 → **346/346**.
+- test:scripts: **1053 (1049 pass + 4 skipped)**, no script test added (the ops help text only).
+- mcp: not touched, not run.
+- `docs env --check`, `docs files --check`, `docs cli --check`, `settings example --check`: clean.
+- e2e, foreground, `browser-lookup.spec.ts` + `stored-url-downloads.spec.ts` at `ae5a71bb`: **4/4 passed** (20.1 s;
+ start-mode build 55 s through the heavy slot).
+
+## Rulings followed
+
+Opt-in everywhere (the channel's `storedUrlDownloads` for the lane, `browserLookup` for the automatic lookup, the op
+for a one-off); Odysee only; one stream, real gaps (one new stored-URL file per rest across cuts and downloads, one
+browser page a minute); add-only listings; the channel's filters still decide; no model; no live network or browser
+in any test (fakes: an injected opener, the fake CDN's page-open lock, synthetic page answers). Records state rulings.
+
+## What the live check must confirm (the API shape was not knowable offline)
+
+The page-API reader was built against yt-dlp's own lbry extractor (`yt_dlp/extractor/lbry.py` in the installed
+yt-dlp-patched: `resolve` → `{result: {<url>: claim}}`, `claim_search` → `{result: {items}}`, `get` →
+`{result: {streaming_url}}`) and synthetic answers of that shape. A live run must show: (1) the video page's answers
+include a `resolve` (or `claim_search`) carrying the page's own claim — the job log's "The page names <claim> (…)";
+(2) the file comes from a `get` answer or the player's CDN request and equals the shape the corpus stores
+(`https://player.odycdn.com/v6/streams/<claim>/<6 hex>.mp4`); (3) a channel page's answers include `claim_search`
+items signed by the channel, and five scrolls list more than the first page; (4) a stored-URL cut after the page open
+lands (the R7 finding, now on the cut path).
+
+## Found and left
+
+- **A real browser may have opened during the first unit run** (before the guard existed): the editor route test
+ `app/api/media/fetch-window/route.storedUrl.test.ts` drives the whole single-window cut, which then reached the real
+ `openPlayerPage` for its synthetic page `https://odysee.com/@demo:1/stream-s1:s1` (the test timed out waiting ~10 s;
+ the run was stopped). If Playwright launched, that was one headless page view of a nonexistent Odysee URL. The
+ opener now refuses under a test runner and on the e2e server.
+- Not every R5 test of the cut exercised a second window of a different video — with the shared rest a run of
+ windows over several Odysee videos now takes 20 minutes per new video (the ruling); the tests zero the rest with
+ `E2E_CLIP_WINDOW_GAP_MS`.
+- The synchronous single-window path (`stream: true`, umtool's / the MCP's fetch_clip) can now wait up to 20 minutes
+ for the rest when a download or another video's cut just read a file; the job log says so. Unchanged otherwise.
+
+## Owed
+
+- The live check above: the page-API reader has never seen a real Odysee page (by rule).
+- The lane's rescue does not run the browser lookup for a held video whose record stores NO URL (it is not picked);
+ the op, or a batch with `browserLookup`, fills those first.
+- A per-request `browserLookup` on the download routes (`download-missing`, `transcribe-one`, `retry-bucket`) was not
+ added: the channel key and the dedicated op are the opt-ins (ManagedDownloadOpts carries it for a future caller).
+- The listing is the newest uploads only (a bounded number of scrolls); a full back catalogue still needs yt-dlp's
+ listing (Store playlist) on a day Odysee answers it.
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -41,6 +41,8 @@
// pnpm ops sync --json '{"slug":"the-quartering"}' --wait
// pnpm ops metadata-scan --json '{"slug":"the-quartering"}'
// pnpm ops refresh-metadata --json '{"slug":"the-quartering","id":"<videoId>"}' --wait
+// pnpm ops browser-lookup --json '{"slug":"demo-odysee","ids":["<claimId>"]}' --wait
+// pnpm ops browser-lookup --json '{"slug":"demo-odysee","listing":true,"scrolls":5}' --wait
// pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait
// pnpm ops import-video --json '{"slug":"demo-archive","url":"https://archive.org/details/example-item"}'
// pnpm ops import-archive-org --json '{"slug":"demo-archive","item":"example-item","match":"\\.mp4$"}' --wait
@@ -313,6 +315,10 @@ const ACTIONS = [
// ONE video's metadata.info.json re-read from its source ({slug, id}): no
// subtitles, no media; the rewrite lands in metadata.history.json.
"refresh-metadata",
+ // An Odysee record ({slug, ids: [...]}) or the channel's listing ({slug,
+ // listing: true, scrolls?}) read from its page in a headless browser, for
+ // when yt-dlp's lookup is refused; one page a minute, on the platform queue.
+ "browser-lookup",
"import-video",
// archive.org media into a channel: one item ({slug, item, files: [...] |
// match: "<regex>"}), many ({items: [...]}) or a search ({query, limit?});
@@ -1129,6 +1135,15 @@ export function usage() {
' the keys that changed. An id with no data/<id>/ is refused (a refresh',
' re-reads a video already archived), as are archive.org and Wayback records.',
"",
+ 'browser-lookup reads Odysee records from their pages in a headless browser,',
+ ' for when yt-dlp\'s lookup answers 429: {"slug", "ids": [...]} (at most 50)',
+ ' writes each record (none yet: whole, `_source: "browser"`) or completes it',
+ ' (the keys it lacks, and the one media file the page\'s player asked for);',
+ ' "listing": true (with "scrolls", default 5, at most 40) adds the uploads',
+ ' the channel page shows to the playlist, newest first, through the title',
+ ' match filter. One page a minute; not refused for a held platform. The log',
+ ' ends with a `summary: {...}` line.',
+ "",
'retry-bucket runs one bucket of a channel\'s report as one job, past any',
' lane hold: {"slug", "bucket"}. "ids": [...] runs only those videos, and',
" every one must be in the bucket (a stray id is refused, named); a job run",