commit be485ac2e5d664c340cc1683569aed0f8c71b2d1
parent 97a9a4f684455310a830613f8ac8527664499fd5
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 1 Nov 2026 10:55:37 -0500
Merge branch 'main' into lane/play-walk-app
Diffstat:
61 files changed, 3162 insertions(+), 179 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
@@ -83,6 +83,7 @@ units, a capped scope); `HEAVY_CAP=0` turns that off. Bypasses: `HEAVY=0`,
```sh
umtool take <project> --id <take> … --priority # for that take's lifetime
umtool render-mode on [--for 90m] [--note "…"] # a window, for a chain of renders (default 2h)
+umtool render-mode on [--for 90m] -- <cmd …> # held while <cmd> runs, released when it exits (scripts)
umtool render-mode status | off
pnpm ops render-mode --json '{"on":true,"for":"90m"}' # the same with only pnpm ops; get render-mode
```
@@ -91,7 +92,10 @@ While it is on, every other heavy job (e2e suites, `next build`s, the publish st
renders) waits at the heavy slot's door — `queue-lock: held for a render (umtool take <p> --id
<t>, since 13:31) — waiting` is the gate working — while the render runs on the floor 4000 MB
and the cap 10240 MB; the editor's transcription and download lanes are held (only the ones
-not already held; only those are released). It turns itself off: at the take's end, failure
+not already held; only those are released). **A script uses `render-mode on -- <cmd …>`, never a bare `on`**: the
+command carries the token, the hold is its pid, and it ends when the command exits — a bare `on`
+in a script leaves a window behind and its later commands wait at the door (the chain trap);
+`--print-token` prints the token alone. It turns itself off: at the take's end, failure
or signal, at the window's `until`, or when its process is gone (the editor's heartbeat
releases the lanes). Then tell the operator to **close Firefox and other heavy apps**, and
put the render before any merge or ship it does not need. A job already running is not
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -158,7 +158,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| orpheus \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...; orpheus: leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). The expressive tags <laugh> <chuckle> <sigh> <cough> <sniffle> <groan> <yawn> <gasp> are performed by orpheus and stripped for the others; any other <...> is refused. Numbers, years, money and times are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro and orpheus need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU (a local llama-server the editor starts and stops) and waits while a transcription holds it. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait` |
| `settings` | settings patches settings.json through the editor's one writer: {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` |
| `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | |
-| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /settings). dismiss-service clears a service's cookie alert by hand: {"service"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'` |
+| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /settings) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). dismiss-service clears a service's cookie alert by hand: {"service"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` |
| `dismiss-service` | — | |
| `rerun-service-jobs` | — | |
| `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` |
@@ -269,9 +269,15 @@ get sites lists every site: id, title, siteUrl, Pages project, audience,
get workers, get auto-queue and get scheduler are /workers, the four lanes
of /operations, and /operations/sync — the payloads those pages poll.
get services is the dashboard's cookie refresh alerts: each service
- (rumble, youtube, odysee, archive.today, a forum host) whose cookies look
+ (rumble, youtube, odysee, archive.today, x, a forum host) whose cookies look
stale, or are OK again with the jobs the alert stopped; "pending" lists
- a first Rumble embed 403 waiting for a second video.
+ a first Rumble embed 403 waiting for a second video. X's kinds: challenge,
+ auth-failure (a login refused) and jar-age (the cookie jar past
+ social.x.maxCookieAgeMinutes while X work waits). "x" is X's jar read
+ from disk whether or not an alert is up (source, at, ageMinutes,
+ maxAgeMinutes, loggedIn, fresh, summary); "timer" is the proactive
+ recheck timer (settings.serviceCookies: intervalMinutes, armed,
+ lastTickAt, nextTickAt, last: what its last tick did per service).
get x-session [<slug>] is the X login an X job would use and whether one
would start NOW, from the same check that refuses a stale-cookie X job:
source ("profile": the exported jar under transcripts/.x-session;
diff --git a/OPERATING.md b/OPERATING.md
@@ -171,7 +171,22 @@ pnpm ops dismiss-service --json '{"service":"rumble"}'
sentence, and the refused jobs are listed for **Re-run stopped jobs**. Pass X's check by hand (Connect X
account on /settings and clear it in the window; with the browser login, open x.com in that browser),
press **Refresh cookies**, then **Recheck** — which sends X *no* request: it clears when the login on disk
- was renewed after the alert was raised.
+ was renewed after the alert was raised. A gallery-dl "AuthRequired: authenticated cookies needed" (a
+ logged-out timeline), "Could not authenticate you" or a 401 is a **login failure**; a 429 or a rate-limit
+ wait is pacing and never raises it; a protected or blocking account and a twimg.com media 403 are about
+ that one account or file (`common/social/xGalleryDlSignals.ts`).
+- **X's jar is old** (kind `jar-age`): an X job the fresh-jar rule refused (`social.x.maxCookieAgeMinutes`,
+ 60 by default) puts up "X needs fresh cookies" with the jar's age read from disk — the exported jar's
+ time, or the browser's x.com `auth_token` last-sent time, read by name. It does not itself refuse X jobs
+ (the rule does) and clears as soon as a job passes on a fresh jar; Recheck re-reads the age. A job
+ refused at its start is offered under **Re-run stopped jobs**. `get services` always carries `x`: the
+ jar's source, age, limit and `fresh`.
+- **On a timer** (`settings.serviceCookies`): every `recheckIntervalMinutes` (180; 0 = off), jittered up,
+ every raised banner is rechecked once, each `probeServices` service (default Rumble) idle that long is
+ asked once for its last clean video (a Rumble 403 confirmed once on the previous, different video), and
+ X's jar age is re-read. Never while a job is queued or running on the platform's queues, while it cools
+ down or is held, or while a recheck runs; never retried. `get services` → `timer` shows the last tick.
+ `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'` turns it off.
- The job it stopped says so in its log: `stopped: Rumble cookies look stale — open rumble.com in …, then
Recheck on the dashboard.` `archilyzer doctor` lists it under "service cookies".
- The state is `transcripts/.service-cookies.json` (`common/lib/serviceCookies.ts`); never hand-edit it.
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -56,6 +56,7 @@ A copied example PINS every default it spells — including each lane's `autoQue
| [`generation`](#generation) | object — see below |
| [`clips`](#clips) | object — see below |
| [`jobs`](#jobs) | object — see below |
+| [`serviceCookies`](#servicecookies) | object — see below |
## `adminTitle`
@@ -1286,3 +1287,25 @@ Default:
"resumeInterruptedOnBoot": true
}
```
+
+## `serviceCookies`
+
+The cookie refresh alerts' PROACTIVE timer (plans/cookie-refresh-alerts.md): how often the editor rechecks raised alerts, probes Rumble's clearance with no alert up, and re-reads X's cookie jar age, by itself — so the dashboard banner goes up before a sync or a download fails. See ServiceCookiesSettings and common/controller/serviceCookieTimer.ts.
+
+#### `serviceCookies`
+
+| Key | Default | Description |
+|---|---|---|
+| `recheckIntervalMinutes` | `180` | Every this many minutes (stretched by up to `pacing.jitter`, never shortened) the editor looks at each service's cookies by itself (common/controller/serviceCookieTimer.ts): every RAISED cookie alert that has something to ask is rechecked once, as the banner's Recheck does (so a banner clears by itself once the operator has opened the site in the browser); each of `probeServices` with no alert is probed once — one metadata request for the last video it answered cleanly — so a stale Cloudflare clearance raises the banner before a sync or a download fails on it; and X's cookie jar is re-read from disk (never a request to X). A service is skipped when a job is queued or running on its platform (that job is the probe), when it is cooling down or held, when it answered cleanly within the interval, or when a recheck of it is already running. A failed probe is never retried: the banner goes up (a Rumble embed 403 confirms on a second, different known-good video, once, a jittered minute or more later) and waits for the next tick or a manual Recheck. 0 turns the timer off; otherwise 30–1440. Default 180. Not armed on an idle boot (ARCHILYZER_IDLE_BOOT) or on the e2e test server. `pnpm ops get services` shows its last tick (`timer`). |
+| `probeServices` | list — see below | The yt-dlp services the timer probes with no alert up — any of `"rumble"`, `"youtube"`, `"odysee"`. Default `["rumble"]` (Rumble's Cloudflare clearance is the one that goes stale by itself). `[]` probes nothing; raised alerts are still rechecked. |
+
+Default:
+
+```json
+{
+ "recheckIntervalMinutes": 180,
+ "probeServices": [
+ "rumble"
+ ]
+}
+```
diff --git a/WORKTREES.md b/WORKTREES.md
@@ -351,6 +351,7 @@ transcription lane, the editor, and e2e servers and browsers beside it. **Render
```sh
umtool take <project> --id <take> … --priority # for this take's lifetime (on at start; off at end, failure, signal)
umtool render-mode on [--for 90m] [--note …] # a window for a chain of renders (default 2h)
+umtool render-mode on [--for 90m] -- <cmd …> # held while <cmd> runs (holder: its pid), off when it exits
umtool render-mode status | off [--force]
pnpm ops render-mode --json '{"on":true,"for":"90m"}' # the same from a session with only pnpm ops
pnpm ops get render-mode
@@ -366,7 +367,13 @@ While it is on:
- **the render is admitted**: it and everything under it carry the hold's token
(`RENDER_PRIORITY_TOKEN`), on the floor **4000 MB** and the cap **10240 MB** unless
`HEAVY_MIN_FREE_MB` / `HEAVY_CAP_MB` say otherwise. Every `umtool take` started inside a
- manual window joins it; another command joins with the token `on` prints.
+ manual window joins it; another command joins with the token `on` prints
+ (`--print-token` prints it alone, for `export RENDER_PRIORITY_TOKEN=$(…)`).
+- **a script wraps its chain: `umtool render-mode on -- <cmd …>`.** The command is spawned
+ with the token in its environment, the hold's holder is the command's pid, and the hold is
+ released when it exits — done, failed, or umtool signalled (the signal is passed on); the
+ exit code is the command's. A bare `on` in a script is the chain trap: the window outlives
+ the script, and a command that never got the token waits at the door behind it.
- **the editor's transcription and download lanes are held** — only the ones not already
held, and only those are released at the end (a hold someone else made stays). With no
editor to ask, render mode still holds the door and says the lanes were not held.
diff --git a/common/controller/recheckServiceCookies.test.ts b/common/controller/recheckServiceCookies.test.ts
@@ -161,3 +161,75 @@ test("Recheck (X): no request to X — stale until the login is renewed after th
await rm(paths.transcriptsDir, { recursive: true, force: true });
}
});
+
+test("Recheck (X, jar-age): the jar's age on disk, no request — stale while old, clean once fresh; a challenge is never overwritten by it", async () => {
+ const paths = await tmpPaths();
+ try {
+ const { noteXJarStale, noteXJarFresh, noteXServiceOutcome } = await import("../lib/serviceCookies-server");
+ assert.equal(await noteXJarStale(paths, { line: "X cookies were last refreshed 3 h ago (limit 60 min): …", channel: "ember-x", job: { id: "J1", kind: "fetch-posts" } }), true);
+ let x = (await readServiceCookieState(paths)).services.x;
+ assert.equal(x?.kind, "jar-age");
+ assert.deepEqual(x?.jobs, [{ id: "J1", kind: "fetch-posts" }]);
+ const asked: string[] = [];
+ let fresh = false;
+ const deps = {
+ runYtdlp: async () => {
+ asked.push("yt-dlp");
+ return { exitCode: 0, stderrTail: "", archiveLine: null };
+ },
+ xLogin: async () => {
+ asked.push("login");
+ return { source: "profile" as const, loggedIn: true };
+ },
+ xJar: async () => ({
+ source: "profile" as const,
+ at: new Date().toISOString(),
+ ageMinutes: fresh ? 1 : 180,
+ maxAgeMinutes: 60,
+ loggedIn: true,
+ fresh,
+ readAt: new Date().toISOString(),
+ summary: fresh ? "The X cookie jar was written 1 min ago (limit 60 min)." : "The X cookie jar was written 3 h ago (limit 60 min): press Refresh cookies (or Connect X account) on /settings.",
+ }),
+ };
+ const stale = await recheckServiceCookies({ paths, service: "x", deps });
+ assert.equal(stale.result, "stale");
+ assert.match(stale.message, /3 h ago .*Recheck sends X no request\.$/);
+ fresh = true;
+ const clean = await recheckServiceCookies({ paths, service: "x", deps });
+ assert.equal(clean.result, "clean");
+ x = (await readServiceCookieState(paths)).services.x;
+ assert.equal(x?.clearedBy, "recheck");
+ assert.deepEqual(asked, [], "neither yt-dlp nor the challenge path was asked");
+ // Nothing raised: fresh is a no-op.
+ assert.equal(await noteXJarFresh(paths), null);
+
+ // A challenge is up: the jar-age path records the job but never replaces it.
+ await noteXServiceOutcome(paths, { challengeLine: "[twitter][warning] Cloudflare challenge", kind: "challenge" });
+ assert.equal(await noteXJarStale(paths, { line: "old jar", job: { id: "J2" } }), true);
+ x = (await readServiceCookieState(paths)).services.x;
+ assert.equal(x?.kind, "challenge");
+ assert.equal(x?.evidence.line, "[twitter][warning] Cloudflare challenge");
+ assert.deepEqual(x?.jobs.map((j) => j.id), ["J2"]);
+ assert.equal(await noteXJarFresh(paths), null, "a fresh jar does not clear a challenge");
+ assert.equal(isAlertRaised((await readServiceCookieState(paths)).services.x), true);
+ } finally {
+ await rm(paths.transcriptsDir, { recursive: true, force: true });
+ }
+});
+
+test("X's login failure is its own kind: an auth-failure alert, worded so", async () => {
+ const paths = await tmpPaths();
+ try {
+ const { noteXServiceOutcome } = await import("../lib/serviceCookies-server");
+ await noteXServiceOutcome(paths, { challengeLine: "[twitter][error] AuthRequired: authenticated cookies needed to access this timeline", kind: "auth-failure" });
+ const x = (await readServiceCookieState(paths)).services.x;
+ assert.equal(x?.kind, "auth-failure");
+ assert.equal(isAlertRaised(x), true);
+ const { buildServiceCookieAlerts } = await import("../lib/serviceCookies");
+ const view = buildServiceCookieAlerts(await readServiceCookieState(paths), { now: Date.now() });
+ assert.match(view.alerts[0]?.detail ?? "", /^1 login failure since /);
+ } finally {
+ await rm(paths.transcriptsDir, { recursive: true, force: true });
+ }
+});
diff --git a/common/controller/recheckServiceCookies.ts b/common/controller/recheckServiceCookies.ts
@@ -22,6 +22,9 @@
// on /settings) with a login in it, or, with the
// browser source, the browser's x.com auth_token
// last sent since — read from disk only.
+// A "jar-age" alert (the fresh-jar rule's
+// banner) is clean when the jar is within
+// social.x.maxCookieAgeMinutes again.
//
// A clean answer clears the alert (clearedBy "recheck") and, for a yt-dlp
// service, settles the platform's backoff as any clean manual request does
@@ -43,8 +46,10 @@ import {
import {
noteServiceCookieClean,
noteServiceCookieSignal,
+ noteXJarFresh,
readServiceCookieState,
} from "../lib/serviceCookies-server";
+import type { XJarStatusView } from "../lib/serviceCookies";
import { recordPlatformClean } from "../jobs/downloadBackoff";
import { runOneYtdlp, type AttemptOutcome } from "../ytdlp/runOneYtdlp";
import { channelExtraArgs, configForVideoUrl, pacedPlatformArgs, withBrowserUserAgent } from "../ytdlp/channelArgs";
@@ -77,6 +82,8 @@ export type RecheckDeps = {
// X's login, read from disk (no request): the source in use, when it was
// last renewed, and whether it holds a login.
xLogin: (paths: Paths) => Promise<{ source: "browser" | "profile"; renewedAt?: string; loggedIn: boolean; browser?: string }>;
+ // X's jar age against the limit, read from disk (social/xJarAge.ts).
+ xJar: (paths: Paths) => Promise<XJarStatusView>;
};
const defaultDeps = (paths: Paths): RecheckDeps => ({
@@ -116,6 +123,12 @@ const defaultDeps = (paths: Paths): RecheckDeps => ({
...(login.browserSpec ? { browser: login.browserSpec } : {}),
};
},
+ xJar: async (p) => {
+ const { readXJarAge } = await import("../social/xJarAge");
+ const { resolvedXMaxCookieAgeMinutes } = await import("../jobs/networkGuard");
+ const settings = getSettings();
+ return readXJarAge(p, settings, { maxAgeMinutes: resolvedXMaxCookieAgeMinutes(settings), fresh: true });
+ },
});
// The probe's argv: metadata only, nothing written, the channel's own args
@@ -149,6 +162,9 @@ export async function recheckServiceCookies(opts: {
onLog?: (line: string) => void;
signal?: AbortSignal;
deps?: Partial<RecheckDeps>;
+ // Ask THIS request instead of the last clean one (the timer's second,
+ // different known-good video — controller/serviceCookieTimer.ts).
+ target?: { url: string; channel?: string };
}): Promise<RecheckOutcome> {
const { paths, service } = opts;
const deps = { ...defaultDeps(paths), ...opts.deps };
@@ -158,7 +174,8 @@ export async function recheckServiceCookies(opts: {
const state = await readServiceCookieState(paths);
const entry = state.services[service];
const good = state.lastGood[service];
- const target = good ?? (entry?.evidence.url ? { url: entry.evidence.url, channel: entry.evidence.channel } : null);
+ const target =
+ opts.target ?? good ?? (entry?.evidence.url ? { url: entry.evidence.url, channel: entry.evidence.channel } : null);
const out = (result: RecheckOutcome["result"], message: string): RecheckOutcome => {
log(message);
return { service, result, message };
@@ -183,7 +200,11 @@ export async function recheckServiceCookies(opts: {
const config = target.channel ? await deps.readChannelConfig(paths, target.channel).catch(() => null) : null;
const args = recheckYtdlpArgs(target.url, config, deps.cookieSpec(config));
const cwd = target.channel && config ? path.join(paths.channelsDir, target.channel) : paths.transcriptsDir;
- log(`Rechecking ${label}: one metadata request for ${target.url}${good ? " (its last clean request)" : " (the request that failed)"}.`);
+ log(
+ `Rechecking ${label}: one metadata request for ${target.url}` +
+ (opts.target ? " (an earlier clean request)" : good ? " (its last clean request)" : " (the request that failed)") +
+ ".",
+ );
const res = await deps.runYtdlp(cwd, args, (l) => opts.onLog?.(l), signal);
if (res.exitCode === 0) return clean(target.url);
const sig = serviceCookieSignalFromStderr(res.stderrTail, detectPlatform(target.url));
@@ -217,6 +238,20 @@ export async function recheckServiceCookies(opts: {
return out("failed", `${label} answered the page with ${block.kind} (${block.detail}); the alert stays.`);
}
case "x": {
+ if (entry?.kind === "jar-age" && !entry.clearedAt) {
+ let jar: XJarStatusView;
+ try {
+ jar = await deps.xJar(paths);
+ } catch (e) {
+ return out("failed", `Could not read X's cookie jar: ${(e as Error).message}. The alert stays.`);
+ }
+ log(`Rechecking ${label}: the cookie jar's age on disk, no request to X.`);
+ if (jar.fresh) {
+ await noteXJarFresh(paths, { by: "recheck" });
+ return out("clean", `${label}'s cookie jar is fresh (${jar.summary}) — its cookie alert is cleared; no request sent.`);
+ }
+ return out("stale", `${jar.summary} Recheck sends X no request.`);
+ }
const raisedAt = entry?.raisedAt ?? entry?.since;
let login: Awaited<ReturnType<RecheckDeps["xLogin"]>>;
try {
diff --git a/common/controller/serviceCookieTimer.test.ts b/common/controller/serviceCookieTimer.test.ts
@@ -0,0 +1,312 @@
+// The cookie recheck timer (serviceCookieTimer.ts): what one tick asks and
+// what it leaves alone (never stacking on a running job, a running recheck, a
+// cooling platform or a recent clean answer; never retrying), Rumble's
+// one-time confirmation on a second known-good video, X's jar from disk, and
+// the timer itself (off at 0, not armed on an idle boot, a tick in flight
+// skips the next). Every dependency is injected: nothing here asks a site.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/serviceCookieTimer.test.ts
+
+import { test, afterEach } from "node:test";
+import assert from "node:assert/strict";
+import {
+ OFF_POLL_MS,
+ runServiceCookieTick,
+ serviceCookieTimerView,
+ startServiceCookieTimer,
+ stopServiceCookieTimer,
+ type ServiceCookieTickDeps,
+ type TickJob,
+} from "./serviceCookieTimer";
+import {
+ applyServiceCookieSignal,
+ emptyServiceCookieState,
+ type ServiceCookieState,
+ type XJarStatusView,
+} from "../lib/serviceCookies";
+import type { RecheckOutcome } from "./recheckServiceCookies";
+
+const NOW = Date.parse("2026-11-01T04:00:00Z");
+const ago = (min: number) => new Date(NOW - min * 60_000).toISOString();
+
+function jar(fresh: boolean): XJarStatusView {
+ return {
+ source: "profile",
+ at: ago(fresh ? 5 : 300),
+ ageMinutes: fresh ? 5 : 300,
+ maxAgeMinutes: 60,
+ loggedIn: true,
+ fresh,
+ readAt: new Date(NOW).toISOString(),
+ summary: fresh ? "The X cookie jar was written 5 min ago (limit 60 min)." : "The X cookie jar was written 5 h ago (limit 60 min): press Refresh cookies (or Connect X account) on /settings.",
+ };
+}
+
+type Harness = {
+ deps: ServiceCookieTickDeps;
+ state: ServiceCookieState;
+ calls: { service: string; target?: string }[];
+ jobs: TickJob[];
+ stale: string[];
+ freshCalls: number;
+ waits: number;
+ answers: Record<string, RecheckOutcome["result"][]>;
+ cooling: Set<string>;
+ xFresh: boolean;
+};
+
+function harness(init: (s: ServiceCookieState) => void = () => {}): Harness {
+ const state = emptyServiceCookieState();
+ init(state);
+ const h: Harness = {
+ state,
+ calls: [],
+ jobs: [],
+ stale: [],
+ freshCalls: 0,
+ waits: 0,
+ answers: {},
+ cooling: new Set(),
+ xFresh: true,
+ deps: undefined as unknown as ServiceCookieTickDeps,
+ };
+ h.deps = {
+ now: () => NOW,
+ settings: () => ({ recheckIntervalMinutes: 180, probeServices: ["rumble"] }),
+ readState: async () => structuredClone(h.state),
+ jobs: () => h.jobs,
+ cooling: async (p) => h.cooling.has(p),
+ recheck: async (service, target) => {
+ h.calls.push({ service, ...(target ? { target: target.url } : {}) });
+ const result = h.answers[service]?.shift() ?? "clean";
+ // A stale Rumble answer records a pending embed 403 on the asked video.
+ if (result === "stale" && service === "rumble") {
+ const url = target?.url ?? h.state.lastGood.rumble?.url ?? "";
+ applyServiceCookieSignal(h.state, { service, kind: "embed-403", line: "403", videoId: url }, { url }, NOW);
+ }
+ return { service, result, message: result };
+ },
+ xJar: async () => jar(h.xFresh),
+ noteXJarStale: async (line) => {
+ h.stale.push(line);
+ return true;
+ },
+ noteXJarFresh: async () => {
+ h.freshCalls++;
+ return "cleared";
+ },
+ confirmWait: async () => {
+ h.waits++;
+ },
+ log: () => {},
+ };
+ return h;
+}
+
+const withGood = (min: number, prev = true) => (s: ServiceCookieState) => {
+ s.lastGood.rumble = {
+ url: "https://rumble.com/v1-a.html",
+ at: ago(min),
+ channel: "huck",
+ ...(prev ? { prev: { url: "https://rumble.com/v2-b.html", at: ago(min + 30) } } : {}),
+ };
+};
+
+test("a probe: Rumble idle past the interval is asked ONCE for its last clean video", async () => {
+ const h = harness(withGood(240));
+ const actions = await runServiceCookieTick(h.deps);
+ assert.deepEqual(h.calls, [{ service: "rumble" }]);
+ assert.equal(actions.find((a) => a.service === "rumble")?.action, "probed");
+});
+
+test("never stacking: a job on Rumble's queue, a recheck already running, a cooling platform, a recent clean answer, nothing known-good — no request", async () => {
+ for (const [label, setup] of [
+ ["a sync running", (h: Harness) => h.jobs.push({ kind: "sync", queueKey: "platform:rumble", status: "running" })],
+ ["a clip fetch queued", (h: Harness) => h.jobs.push({ kind: "fetch-windows", queueKey: "clips:rumble", status: "queued" })],
+ ["a recheck running", (h: Harness) => h.jobs.push({ kind: "recheck-service-cookies", queueKey: "service-cookies:rumble", status: "running" })],
+ ["cooling", (h: Harness) => h.cooling.add("rumble")],
+ ] as const) {
+ const h = harness(withGood(240));
+ setup(h);
+ const actions = await runServiceCookieTick(h.deps);
+ assert.deepEqual(h.calls, [], label);
+ assert.equal(actions.find((a) => a.service === "rumble")?.action, "skipped", label);
+ }
+ // A job that has ended does not hold it back.
+ const ended = harness(withGood(240));
+ ended.jobs.push({ kind: "sync", queueKey: "platform:rumble", status: "done" });
+ await runServiceCookieTick(ended.deps);
+ assert.equal(ended.calls.length, 1);
+
+ const recent = harness(withGood(30));
+ assert.match((await runServiceCookieTick(recent.deps)).find((a) => a.service === "rumble")?.message ?? "", /answered cleanly 30 min ago/);
+ assert.deepEqual(recent.calls, []);
+ const none = harness();
+ await runServiceCookieTick(none.deps);
+ assert.deepEqual(none.calls, []);
+});
+
+test("Rumble's ambiguous 403: confirmed ONCE on the previous, different known-good video after a wait; never a third request", async () => {
+ const h = harness(withGood(240));
+ h.answers.rumble = ["stale", "stale"];
+ const actions = await runServiceCookieTick(h.deps);
+ assert.deepEqual(h.calls, [{ service: "rumble" }, { service: "rumble", target: "https://rumble.com/v2-b.html" }]);
+ assert.equal(h.waits, 1);
+ assert.deepEqual(actions.filter((a) => a.service === "rumble").map((a) => a.action), ["probed", "confirmed"]);
+ // Two different videos refused: the alert is up.
+ assert.ok(h.state.services.rumble?.raisedAt);
+
+ // No earlier, different video: one request, the first 403 stays pending.
+ const solo = harness(withGood(240, false));
+ solo.answers.rumble = ["stale"];
+ await runServiceCookieTick(solo.deps);
+ assert.equal(solo.calls.length, 1);
+ assert.equal(solo.waits, 0);
+ assert.equal(solo.state.services.rumble?.raisedAt, undefined);
+
+ // A probe that failed for another reason is not retried.
+ const failed = harness(withGood(240));
+ failed.answers.rumble = ["failed"];
+ await runServiceCookieTick(failed.deps);
+ assert.equal(failed.calls.length, 1);
+});
+
+test("raised alerts are rechecked once (any service that has something to ask); a running job on the platform holds it back", async () => {
+ const h = harness((s) => {
+ withGood(240)(s);
+ applyServiceCookieSignal(s, { service: "youtube", kind: "bot-check", line: "bot" }, { url: "https://www.youtube.com/watch?v=aaaaaaaaaaa" }, NOW - 3600_000);
+ applyServiceCookieSignal(s, { service: "rumble", kind: "embed-403", line: "a", videoId: "e1" }, { url: "https://rumble.com/v1-a.html" }, NOW - 3600_000);
+ applyServiceCookieSignal(s, { service: "rumble", kind: "embed-403", line: "b", videoId: "e2" }, { url: "https://rumble.com/v2-b.html" }, NOW - 3600_000);
+ });
+ h.jobs.push({ kind: "sync", queueKey: "platform:youtube", status: "running" });
+ const actions = await runServiceCookieTick(h.deps);
+ // Rumble's banner rechecked; not probed again in the same tick. YouTube held back by its running sync.
+ assert.deepEqual(h.calls, [{ service: "rumble" }]);
+ assert.equal(actions.find((a) => a.service === "youtube")?.action, "skipped");
+ assert.equal(actions.find((a) => a.service === "rumble")?.action, "rechecked");
+});
+
+test("X from disk: queued X jobs on an old jar raise the jar-age banner; a fresh jar clears it; no X job queued, nothing is raised", async () => {
+ const idle = harness();
+ idle.xFresh = false;
+ await runServiceCookieTick(idle.deps);
+ assert.deepEqual(idle.stale, [], "no X work waiting: no banner");
+
+ const waiting = harness();
+ waiting.xFresh = false;
+ waiting.jobs.push({ kind: "fetch-posts", queueKey: "platform:twitter", status: "queued" });
+ await runServiceCookieTick(waiting.deps);
+ assert.equal(waiting.stale.length, 1);
+ assert.match(waiting.stale[0], /^1 X job is queued on an old cookie jar: The X cookie jar was written 5 h ago/);
+
+ const raised = harness((s) => {
+ applyServiceCookieSignal(s, { service: "x", kind: "jar-age", line: "old" }, {}, NOW - 3600_000);
+ });
+ raised.xFresh = true;
+ const actions = await runServiceCookieTick(raised.deps);
+ assert.equal(raised.freshCalls, 1);
+ assert.equal(actions.find((a) => a.service === "x")?.action, "cleared");
+ assert.deepEqual(raised.calls.filter((c) => c.service === "x"), [], "jar-age is re-read, not rechecked");
+});
+
+// ── the timer ──────────────────────────────────────────────────────────────
+
+afterEach(() => stopServiceCookieTimer());
+
+function fakeScheduler() {
+ const pending: { fn: () => void; ms: number; cancelled: boolean }[] = [];
+ return {
+ pending,
+ schedule: (fn: () => void, ms: number) => {
+ const p = { fn, ms, cancelled: false };
+ pending.push(p);
+ return { cancel: () => (p.cancelled = true) };
+ },
+ fire: () => {
+ const p = pending.shift();
+ assert.ok(p && !p.cancelled, "a tick was scheduled");
+ p.fn();
+ },
+ };
+}
+
+test("the timer: 0 is off (it only looks again later whether it was turned on)", async () => {
+ const sched = fakeScheduler();
+ let ticks = 0;
+ assert.equal(
+ startServiceCookieTimer({
+ env: {},
+ settings: () => ({ recheckIntervalMinutes: 0, probeServices: ["rumble"] }),
+ schedule: sched.schedule,
+ jitter: (ms) => ms,
+ deps: async () => {
+ ticks++;
+ return harness().deps;
+ },
+ log: () => {},
+ }),
+ true,
+ );
+ assert.equal(sched.pending[0].ms, OFF_POLL_MS);
+ sched.fire();
+ await new Promise((r) => setImmediate(r));
+ assert.equal(ticks, 0);
+ assert.equal(sched.pending[0].ms, OFF_POLL_MS);
+ assert.equal(serviceCookieTimerView().armed, true);
+});
+
+test("the timer: not armed on an idle boot, nor twice", () => {
+ assert.equal(startServiceCookieTimer({ env: { ARCHILYZER_IDLE_BOOT: "1" }, log: () => {} }), false);
+ assert.equal(serviceCookieTimerView().armed, false);
+ const sched = fakeScheduler();
+ const opts = {
+ env: {},
+ settings: () => ({ recheckIntervalMinutes: 180, probeServices: [] }),
+ schedule: sched.schedule,
+ jitter: (ms: number) => ms,
+ deps: async () => harness().deps,
+ log: () => {},
+ };
+ assert.equal(startServiceCookieTimer(opts), true);
+ assert.equal(startServiceCookieTimer(opts), false);
+ // The first tick comes no sooner than 15 min after boot, and no later than the interval.
+ assert.equal(sched.pending[0].ms, 15 * 60_000);
+});
+
+test("the timer: a tick still in flight when the next is due skips it; the next is scheduled after the interval, jittered up", async () => {
+ const sched = fakeScheduler();
+ let release!: () => void;
+ let ticks = 0;
+ const logs: string[] = [];
+ startServiceCookieTimer({
+ env: {},
+ settings: () => ({ recheckIntervalMinutes: 180, probeServices: [] }),
+ schedule: sched.schedule,
+ jitter: (ms) => ms * 1.1,
+ deps: async () => {
+ ticks++;
+ const h = harness();
+ return {
+ ...h.deps,
+ settings: () => ({ recheckIntervalMinutes: 180, probeServices: [] }),
+ readState: async () => {
+ await new Promise<void>((r) => (release = r));
+ return emptyServiceCookieState();
+ },
+ };
+ },
+ log: (l) => logs.push(l),
+ });
+ sched.fire(); // tick 1 starts and hangs
+ await new Promise((r) => setImmediate(r));
+ assert.equal(ticks, 1);
+ // No tick is scheduled while one is in flight: the next is armed only when
+ // this one ends, so two can never overlap.
+ assert.equal(sched.pending.length, 0);
+ release();
+ await new Promise((r) => setTimeout(r, 10));
+ assert.equal(sched.pending.length, 1);
+ assert.equal(sched.pending[0].ms, 180 * 60_000 * 1.1);
+ assert.ok(serviceCookieTimerView().lastTickAt);
+ assert.equal(logs.filter((l) => /still running/.test(l)).length, 0);
+});
diff --git a/common/controller/serviceCookieTimer.ts b/common/controller/serviceCookieTimer.ts
@@ -0,0 +1,389 @@
+// THE COOKIE RECHECK TIMER (plans/cookie-refresh-alerts.md, "Proactive"):
+// the cookie refresh alerts used to be raised only by a job that FAILED on a
+// stale cookie — a Rumble sync or a clip fetch met the embed 403 first, and
+// the banner explained the failure after it. Operator, 2026-10-31: "make
+// Rumble trigger on a timer so we can be more proactive."
+//
+// Every `settings.serviceCookies.recheckIntervalMinutes` (default 180; 0 =
+// off), stretched by up to `pacing.jitter` and never shortened, ONE tick:
+//
+// 1. X's jar, from disk (social/xJarAge.ts — never a request to X): a raised
+// jar-age banner clears once the jar is fresh; with none up, X jobs
+// queued on a jar past `social.x.maxCookieAgeMinutes` raise it before
+// their start refuses them.
+// 2. Every RAISED alert with something to ask is rechecked once, exactly as
+// the banner's Recheck (controller/recheckServiceCookies.ts, as a
+// `recheck-service-cookies` job): a banner clears by itself once the
+// operator has opened the site in the browser. X's recheck asks X
+// nothing.
+// 3. Each of `probeServices` (default Rumble) with no alert up is PROBED: one
+// metadata request for the last video it answered cleanly. Rumble's embed
+// 403 is ambiguous (a removed video 403s too), so a 403 there is
+// confirmed ONCE on the previous, different known-good video, a jittered
+// minute or more later — two different videos refused raise the banner,
+// as two in a job do. Never more than two requests per service per tick.
+//
+// NEVER STACKING, NEVER PUSHING: a service is skipped when a job is queued or
+// running on its platform's queues (that job is the probe, and its answer
+// raises or clears the alert by itself), when the platform is cooling down or
+// held (jobs/platformBackoff.ts), when it answered cleanly within the
+// interval, or when a recheck of it is already queued or running; a tick
+// still in flight when the next is due skips the next. A failed probe is NEVER
+// retried: the alert goes up and waits for the next tick or a manual Recheck.
+//
+// Not armed on an idle boot (ARCHILYZER_IDLE_BOOT, lib/idleBoot.ts) — a tick
+// is a request to a platform — nor on the e2e test server (instrumentation.ts).
+// State lives on globalThis: the instrumentation hook and a route may load
+// this module twice, and two timers would be two probes.
+
+import { isIdleBoot } from "../lib/idleBoot";
+import { getSettings } from "../lib/settings";
+import { jitterMs } from "../lib/jitter";
+import type { Paths } from "../lib/paths";
+import {
+ buildServiceCookieAlerts,
+ isAlertRaised,
+ serviceFamily,
+ serviceLabel,
+ X_SERVICE,
+ type ServiceCookieState,
+ type ServiceCookieTimerView,
+ type XJarStatusView,
+} from "../lib/serviceCookies";
+import type { ServiceCookiesSettings } from "../lib/serviceCookieSettings";
+import type { RecheckOutcome } from "./recheckServiceCookies";
+
+export const RECHECK_JOB_KIND = "recheck-service-cookies";
+export const recheckQueueKey = (service: string) => `service-cookies:${service}`;
+// When the setting is 0, how often the timer looks whether it was turned on.
+export const OFF_POLL_MS = 15 * 60_000;
+// The first tick after boot: no sooner than this (boot resumes its own work).
+export const FIRST_TICK_MAX_MS = 15 * 60_000;
+// Rumble's second known-good video is asked no sooner than this after the first.
+export const CONFIRM_GAP_MS = 60_000;
+
+export type TickJob = { kind: string; queueKey: string; status: string };
+
+export type TickAction = {
+ service: string;
+ action: "rechecked" | "probed" | "confirmed" | "skipped" | "cleared" | "raised" | "ok";
+ message: string;
+};
+
+export type ServiceCookieTickDeps = {
+ now: () => number;
+ settings: () => ServiceCookiesSettings;
+ readState: () => Promise<ServiceCookieState>;
+ // The registry's jobs (any status; only queued and running count).
+ jobs: () => TickJob[];
+ // The platform is cooling down or held.
+ cooling: (platform: string) => Promise<boolean>;
+ // One recheck, as a job; `target` asks that request instead of the last
+ // clean one.
+ recheck: (service: string, target?: { url: string; channel?: string }) => Promise<RecheckOutcome>;
+ xJar: () => Promise<XJarStatusView>;
+ noteXJarStale: (line: string) => Promise<boolean>;
+ noteXJarFresh: () => Promise<string | null>;
+ // A wait between Rumble's two known-good videos (jittered up, at least CONFIRM_GAP_MS).
+ confirmWait: () => Promise<void>;
+ log: (line: string) => void;
+};
+
+const ACTIVE = new Set(["queued", "running"]);
+
+export async function runServiceCookieTick(deps: ServiceCookieTickDeps): Promise<TickAction[]> {
+ const out: TickAction[] = [];
+ const act = (a: TickAction) => {
+ out.push(a);
+ deps.log(`[cookies] ${serviceLabel(a.service)}: ${a.action} — ${a.message}`);
+ };
+ const settings = deps.settings();
+ const intervalMs = settings.recheckIntervalMinutes * 60_000;
+ const active = () => deps.jobs().filter((j) => ACTIVE.has(j.status));
+ const rechecking = (svc: string) =>
+ active().some((j) => j.kind === RECHECK_JOB_KIND && j.queueKey === recheckQueueKey(svc));
+ const busy = (platform: string) =>
+ active().some((j) => j.queueKey === `platform:${platform}` || j.queueKey === `clips:${platform}`);
+
+ // Why a service is not asked now, or null.
+ const holdBack = async (svc: string): Promise<string | null> => {
+ if (rechecking(svc)) return "a recheck of it is already queued or running";
+ if (serviceFamily(svc) === "ytdlp") {
+ if (busy(svc)) return `a job is queued or running on its queue (its answer is the probe)`;
+ if (await deps.cooling(svc).catch(() => false)) return "the platform is cooling down or held";
+ }
+ return null;
+ };
+
+ let state = await deps.readState();
+
+ // 1. X's jar, from disk.
+ const xEntry = state.services[X_SERVICE];
+ try {
+ if (isAlertRaised(xEntry) && xEntry!.kind === "jar-age") {
+ const jar = await deps.xJar();
+ if (jar.fresh) {
+ await deps.noteXJarFresh();
+ act({ service: X_SERVICE, action: "cleared", message: `the jar is fresh (${jar.summary})` });
+ } else {
+ act({ service: X_SERVICE, action: "ok", message: `still old: ${jar.summary}` });
+ }
+ } else if (!isAlertRaised(xEntry)) {
+ const xJobs = active().filter((j) => j.queueKey === "platform:twitter").length;
+ if (xJobs > 0) {
+ const jar = await deps.xJar();
+ if (!jar.fresh && jar.maxAgeMinutes > 0) {
+ await deps.noteXJarStale(
+ `${xJobs} X job${xJobs === 1 ? " is" : "s are"} queued on an old cookie jar: ${jar.summary}`,
+ );
+ act({ service: X_SERVICE, action: "raised", message: `${xJobs} queued X job(s), ${jar.summary}` });
+ }
+ }
+ }
+ } catch (err) {
+ deps.log(`[cookies] X: could not read the jar: ${(err as Error).message}`);
+ }
+
+ // 2. Every raised (stale) alert with something to ask.
+ const view = buildServiceCookieAlerts(state, { now: deps.now() });
+ const asked = new Set<string>();
+ for (const alert of view.alerts) {
+ if (alert.state !== "stale" || !alert.canRecheck) continue;
+ if (alert.service === X_SERVICE && alert.kind === "jar-age") continue;
+ const why = await holdBack(alert.service);
+ if (why) {
+ act({ service: alert.service, action: "skipped", message: why });
+ continue;
+ }
+ asked.add(alert.service);
+ const res = await deps.recheck(alert.service).catch((err) => ({
+ service: alert.service,
+ result: "failed" as const,
+ message: (err as Error).message,
+ }));
+ act({ service: alert.service, action: "rechecked", message: `${res.result}: ${res.message}` });
+ }
+
+ // 3. The probes, with no alert up.
+ if (settings.probeServices.length) state = await deps.readState();
+ for (const svc of settings.probeServices) {
+ if (asked.has(svc)) continue;
+ const entry = state.services[svc];
+ if (isAlertRaised(entry)) continue;
+ const good = state.lastGood[svc];
+ if (!good) {
+ act({ service: svc, action: "skipped", message: "no clean request is recorded to ask again" });
+ continue;
+ }
+ const sinceGood = deps.now() - Date.parse(good.at);
+ if (intervalMs > 0 && sinceGood < intervalMs) {
+ act({ service: svc, action: "skipped", message: `answered cleanly ${Math.floor(sinceGood / 60_000)} min ago` });
+ continue;
+ }
+ const why = await holdBack(svc);
+ if (why) {
+ act({ service: svc, action: "skipped", message: why });
+ continue;
+ }
+ const res = await deps.recheck(svc).catch((err) => ({
+ service: svc,
+ result: "failed" as const,
+ message: (err as Error).message,
+ }));
+ act({ service: svc, action: "probed", message: `${res.result}: ${res.message}` });
+ if (res.result !== "stale") continue;
+ // Rumble's ambiguous 403: one first video, still pending — confirm ONCE
+ // on the previous, different known-good video.
+ const after = (await deps.readState()).services[svc];
+ const prev = good.prev;
+ if (!after || after.raisedAt || after.kind !== "embed-403" || !prev || prev.url === good.url) continue;
+ await deps.confirmWait();
+ const why2 = await holdBack(svc);
+ if (why2) {
+ act({ service: svc, action: "skipped", message: `the confirmation: ${why2}` });
+ continue;
+ }
+ const res2 = await deps.recheck(svc, { url: prev.url, ...(prev.channel ? { channel: prev.channel } : {}) }).catch(
+ (err) => ({ service: svc, result: "failed" as const, message: (err as Error).message }),
+ );
+ act({ service: svc, action: "confirmed", message: `${res2.result}: ${res2.message}` });
+ }
+ return out;
+}
+
+// ── the default deps (the live editor) ─────────────────────────────────────
+
+export async function defaultTickDeps(paths: Paths, log: (line: string) => void): Promise<ServiceCookieTickDeps> {
+ const { getRegistry } = await import("../jobs/registry");
+ const { platformCooldownRemainingMs, platformHold } = await import("../jobs/downloadBackoff");
+ const { readServiceCookieState, noteXJarStale, noteXJarFresh } = await import("../lib/serviceCookies-server");
+ const { readXJarAge } = await import("../social/xJarAge");
+ const { resolvedXMaxCookieAgeMinutes } = await import("../jobs/networkGuard");
+ return {
+ now: () => Date.now(),
+ settings: () => getSettings().serviceCookies,
+ readState: () => readServiceCookieState(paths),
+ jobs: () => getRegistry().list().map((j) => ({ kind: j.kind, queueKey: j.queueKey, status: j.status })),
+ cooling: async (platform) =>
+ (await platformCooldownRemainingMs(platform, paths)) > 0 || (await platformHold(platform, paths)) !== null,
+ recheck: (service, target) => runRecheckServiceJob(paths, service, target),
+ xJar: async () => {
+ const settings = getSettings();
+ return readXJarAge(paths, settings, { maxAgeMinutes: resolvedXMaxCookieAgeMinutes(settings), fresh: true });
+ },
+ noteXJarStale: (line) => noteXJarStale(paths, { line }),
+ noteXJarFresh: () => noteXJarFresh(paths),
+ confirmWait: () => new Promise((r) => setTimeout(r, jitterMs(CONFIRM_GAP_MS)).unref?.()),
+ log,
+ };
+}
+
+// ONE RECHECK AS A JOB (kind `recheck-service-cookies`, its own queue
+// `service-cookies:<service>`): what the banner's Recheck and the timer both
+// run, so it shows on /jobs with its log.
+export async function runRecheckServiceJob(
+ paths: Paths,
+ service: string,
+ target?: { url: string; channel?: string },
+): Promise<RecheckOutcome & { jobId?: string }> {
+ const { runManagedFunction } = await import("../jobs/streamCommand");
+ const { recheckServiceCookies } = await import("./recheckServiceCookies");
+ let outcome: RecheckOutcome | null = null;
+ const res = await runManagedFunction({
+ kind: RECHECK_JOB_KIND,
+ queueKey: recheckQueueKey(service),
+ paths,
+ fn: async (onLog, signal) => {
+ outcome = await recheckServiceCookies({ paths, service, onLog, signal, ...(target ? { target } : {}) });
+ },
+ });
+ if (!res.ok) return { service, result: "failed", message: res.error };
+ void res.stream.cancel();
+ const done = await res.done;
+ const o = outcome as RecheckOutcome | null;
+ if (done.status !== "done" || !o) {
+ return { service, result: "failed", message: `The ${serviceLabel(service)} recheck ended ${done.status}.`, jobId: res.jobId };
+ }
+ return { ...o, jobId: res.jobId };
+}
+
+// ── the timer ──────────────────────────────────────────────────────────────
+
+type TimerState = {
+ handle?: { cancel: () => void };
+ inFlight: boolean;
+ intervalMinutes: number;
+ lastTickAt?: number;
+ nextTickAt?: number;
+ last?: TickAction[];
+};
+
+const KEY = Symbol.for("archilyzer.serviceCookieTimer");
+function slot(): { state?: TimerState } {
+ const g = globalThis as unknown as Record<symbol, { state?: TimerState }>;
+ return (g[KEY] ??= {});
+}
+
+export type TimerScheduler = (fn: () => void, ms: number) => { cancel: () => void };
+
+const realScheduler: TimerScheduler = (fn, ms) => {
+ const t = setTimeout(fn, ms);
+ t.unref?.();
+ return { cancel: () => clearTimeout(t) };
+};
+
+export type StartTimerOpts = {
+ log?: (line: string) => void;
+ env?: Record<string, string | undefined>;
+ // Injected for tests; the live editor's are built from `paths`.
+ deps?: () => Promise<ServiceCookieTickDeps>;
+ settings?: () => ServiceCookiesSettings;
+ schedule?: TimerScheduler;
+ jitter?: (ms: number) => number;
+ now?: () => number;
+};
+
+// Arms the timer once per process. Answers false when it is already armed,
+// or the process booted idle.
+export function startServiceCookieTimer(opts: StartTimerOpts & { paths?: Paths } = {}): boolean {
+ const s = slot();
+ if (s.state) return false;
+ if (isIdleBoot(opts.env ?? process.env)) return false;
+ const log = opts.log ?? ((l: string) => console.log(l));
+ const schedule = opts.schedule ?? realScheduler;
+ const now = opts.now ?? Date.now;
+ const settingsOf = opts.settings ?? (() => getSettings().serviceCookies);
+ const jitter = opts.jitter ?? ((ms: number) => jitterMs(ms));
+ const depsOf =
+ opts.deps ??
+ (async () => {
+ const { getPaths } = await import("../lib/paths");
+ return defaultTickDeps(opts.paths ?? getPaths(), log);
+ });
+ const state: TimerState = { inFlight: false, intervalMinutes: 0 };
+ s.state = state;
+
+ const interval = (): number => {
+ try {
+ return settingsOf().recheckIntervalMinutes;
+ } catch {
+ return 0;
+ }
+ };
+ const arm = (ms: number) => {
+ state.nextTickAt = now() + ms;
+ state.handle = schedule(tick, ms);
+ };
+ const tick = () => {
+ const minutes = interval();
+ state.intervalMinutes = minutes;
+ if (minutes <= 0) {
+ // Off: look again later whether it was turned on.
+ state.nextTickAt = undefined;
+ state.handle = schedule(tick, OFF_POLL_MS);
+ return;
+ }
+ if (state.inFlight) {
+ log("[cookies] the previous tick is still running; this one is skipped");
+ arm(jitter(minutes * 60_000));
+ return;
+ }
+ state.inFlight = true;
+ state.lastTickAt = now();
+ void (async () => {
+ try {
+ state.last = await runServiceCookieTick(await depsOf());
+ } catch (err) {
+ log(`[cookies] tick failed: ${(err as Error).message}`);
+ } finally {
+ state.inFlight = false;
+ arm(jitter(Math.max(1, interval() || minutes) * 60_000));
+ }
+ })();
+ };
+
+ const first = interval();
+ state.intervalMinutes = first;
+ if (first <= 0) state.handle = schedule(tick, OFF_POLL_MS);
+ else arm(jitter(Math.min(first * 60_000, FIRST_TICK_MAX_MS)));
+ return true;
+}
+
+export function stopServiceCookieTimer(): void {
+ const s = slot();
+ s.state?.handle?.cancel();
+ s.state = undefined;
+}
+
+// For `pnpm ops get services` / the dashboard payload.
+export function serviceCookieTimerView(settingsMinutes?: number): ServiceCookieTimerView {
+ const st = slot().state;
+ if (!st) return { intervalMinutes: settingsMinutes ?? 0, armed: false };
+ return {
+ intervalMinutes: settingsMinutes ?? st.intervalMinutes,
+ armed: true,
+ ...(st.lastTickAt ? { lastTickAt: new Date(st.lastTickAt).toISOString() } : {}),
+ ...(st.nextTickAt ? { nextTickAt: new Date(st.nextTickAt).toISOString() } : {}),
+ ...(st.last ? { last: st.last.map(({ service, action, message }) => ({ service, action, message })) } : {}),
+ };
+}
diff --git a/common/jobs/networkGuard.ts b/common/jobs/networkGuard.ts
@@ -30,6 +30,8 @@ import { serviceFixText, X_SERVICE } from "../lib/serviceCookies";
import {
configuredCookieBrowser,
noteServiceStoppedJob,
+ noteXJarFresh,
+ noteXJarStale,
raisedServiceAlert,
} from "../lib/serviceCookies-server";
import {
@@ -150,6 +152,11 @@ function e2eDefaultMaxAge(): number | undefined {
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : undefined;
}
+// social.x.maxCookieAgeMinutes as every X reader applies it (0 = off).
+export function resolvedXMaxCookieAgeMinutes(settings: Pick<SiteSettings, "social"> | null): number {
+ return settings?.social?.x?.maxCookieAgeMinutes ?? e2eDefaultMaxAge() ?? xMaxCookieAgeMinutes(settings?.social?.x);
+}
+
function settingsNow(): SiteSettings | null {
try {
return getSettings();
@@ -214,8 +221,7 @@ export async function xSessionReport(opts: {
browserSpec: settings ? await channelCookieSpec(opts.paths, opts.channelSlug, settings) : undefined,
profileConnected: status.looksAuthenticated,
});
- const maxAgeMinutes =
- settings?.social?.x?.maxCookieAgeMinutes ?? e2eDefaultMaxAge() ?? xMaxCookieAgeMinutes(settings?.social?.x);
+ const maxAgeMinutes = resolvedXMaxCookieAgeMinutes(settings);
const ageMinutes = status.cookiesUpdatedAt
? Math.max(0, Math.floor((now - Date.parse(status.cookiesUpdatedAt)) / 60_000))
: null;
@@ -233,15 +239,19 @@ export async function xSessionReport(opts: {
maxAgeMinutes,
ageChecked: resolved.source === "profile" && maxAgeMinutes > 0,
};
+ // A raised jar-age alert does not refuse by itself: it IS the fresh-jar
+ // rule's banner, and the rule below decides (and clears it once the jar is
+ // fresh — guardNetworkJob).
const raised = await raisedServiceAlert(opts.paths, X_SERVICE);
- if (raised) {
+ if (raised && raised.kind !== "jar-age") {
const at = (raised.raisedAt ?? raised.since).slice(11, 16);
+ const what = raised.kind === "auth-failure" ? "a login failure" : "a challenge";
return {
...base,
alert: { raisedAt: raised.raisedAt ?? raised.since, line: raised.evidence.line },
allowed: false,
reason:
- `X answered with a challenge at ${at} UTC (${raised.evidence.line}) and its cookie alert is up, ` +
+ `X answered with ${what} at ${at} UTC (${raised.evidence.line}) and its cookie alert is up, ` +
`so no X job starts: ${serviceFixText(X_SERVICE, configuredCookieBrowser())}, then Recheck on the dashboard.`,
};
}
@@ -280,9 +290,24 @@ export async function guardNetworkJob(
const platform = await networkJobPlatform(opts);
if (platform !== "twitter") return { ok: true, notes: [] };
const x = await xJobGuard({ paths: opts.paths, channelSlug: opts.channelSlug });
- if (x.ok) return { ok: true, notes: x.note ? [x.note] : [] };
+ if (x.ok) {
+ // The jar passed at a job's START: a jar-age banner from an earlier
+ // refusal clears. (Not at enqueue — the start follows, and enqueue stays
+ // as cheap as it was.)
+ if (opts.job) await noteXJarFresh(opts.paths);
+ return { ok: true, notes: x.note ? [x.note] : [] };
+ }
if (x.alert && opts.job) {
await noteServiceStoppedJob(opts.paths, X_SERVICE, { id: opts.job.id, kind: opts.kind });
+ } else if (!x.alert) {
+ // The fresh-jar rule refused it: X's cookie banner says so on the
+ // dashboard (kind jar-age), and a job refused at its start is offered for
+ // "Re-run stopped jobs" once the jar is fresh.
+ await noteXJarStale(opts.paths, {
+ line: x.message,
+ ...(opts.channelSlug ? { channel: opts.channelSlug } : {}),
+ ...(opts.job ? { job: { id: opts.job.id, kind: opts.kind } } : {}),
+ });
}
return { ok: false, error: x.message };
}
diff --git a/common/jobs/pacingGuard.test.ts b/common/jobs/pacingGuard.test.ts
@@ -35,6 +35,9 @@ await writeFile(
import { appendFileSync } from "node:fs";
appendFileSync(process.env.FAKE_RUNS, process.argv.slice(2).join(" ") + "\\n");
if (process.env.FAKE_MODE === "challenge") {
+ // X answers after a moment, as it does: the loop has queued all 13 by then
+ // (on a loaded machine an instant answer raced the loop's later enqueues).
+ await new Promise((r) => setTimeout(r, 2000));
process.stderr.write("[twitter][warning] Cloudflare challenge\\n");
}
process.exit(0);
@@ -234,6 +237,77 @@ test("a stale jar is refused at enqueue, and at the start of a job queued while
assert.match(c.ok ? "" : c.error, /holds no login/);
});
+test("the fresh-jar rule raises X's jar-age banner (the job refused at its start is on it); a fresh jar clears it; a challenge escalates it", async () => {
+ await reset();
+ const { buildServiceCookieAlerts, isBlockingAlert } = await import("../lib/serviceCookies");
+ // Refused at enqueue: the banner goes up, no job to re-run.
+ await writeJar(3 * 60 * 60_000);
+ const refused = await fetchJob(SLUGS[0], new Map());
+ assert.equal(refused.ok, false);
+ let x = (await readServiceCookieState(paths)).services.x;
+ assert.ok(x?.raisedAt && !x.clearedAt, "the X banner is up");
+ assert.equal(x.kind, "jar-age");
+ assert.equal(isBlockingAlert(x), false, "jar-age does not itself refuse X jobs");
+ assert.match(x.evidence.line, /^X cookies were last refreshed 3 h ago \(limit 60 min\)/);
+ assert.equal(x.evidence.channel, SLUGS[0]);
+ assert.deepEqual(x.jobs, []);
+
+ // Queued while fresh, refused at its start: recorded on the banner.
+ await writeJar(5 * 60_000);
+ let release!: () => void;
+ const held = new Promise<void>((r) => (release = r));
+ const a = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: SLUGS[0], fn: () => held });
+ assert.ok(a.ok);
+ // The guard let job a through at its start on a fresh jar: the banner is OK again.
+ for (let i = 0; i < 100 && !(await readServiceCookieState(paths)).services.x?.clearedAt; i++) {
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ x = (await readServiceCookieState(paths)).services.x;
+ assert.equal(x?.clearedBy, "clean");
+ const b = await fetchJob(SLUGS[1], new Map());
+ assert.ok(b.ok);
+ await writeJar(2 * 60 * 60_000);
+ release();
+ await a.done;
+ const bDone = await b.done;
+ assert.equal(bDone.status, "failed");
+ x = (await readServiceCookieState(paths)).services.x;
+ assert.ok(x?.raisedAt && !x.clearedAt);
+ assert.equal(x.kind, "jar-age");
+ assert.deepEqual(x.jobs.map((j) => j.id), [bDone.jobId]);
+ // Three short lines: the age, the one action for the login source in use, the job it refused.
+ const st = await readServiceCookieState(paths);
+ const view = buildServiceCookieAlerts(st, {
+ now: Date.now(),
+ browser: "firefox",
+ xJar: { source: "profile", ageMinutes: 120, maxAgeMinutes: 60 },
+ });
+ assert.equal(view.alerts[0]?.headline, "X cookies are 2 h old (limit 60 min)");
+ assert.equal(view.alerts[0]?.fix, "Refresh cookies (or Connect X account) on /settings — then Recheck.");
+ assert.equal(view.alerts[0]?.detail, `Refused fetch-posts ${bDone.jobId} (${SLUGS[1]}).`);
+ assert.equal(view.alerts[0]?.compact, true);
+ const browserView = buildServiceCookieAlerts(st, {
+ now: Date.now(),
+ browser: "firefox",
+ xJar: { source: "browser", ageMinutes: 200, maxAgeMinutes: 60 },
+ });
+ assert.equal(browserView.alerts[0]?.headline, "X cookies are 3 h old (limit 60 min)");
+ assert.equal(browserView.alerts[0]?.fix, "Open x.com in Firefox — then Recheck.");
+
+ // A real challenge from X while the jar-age banner is up escalates it to a
+ // blocking alert, keeping the job it holds.
+ const { noteXServiceOutcome } = await import("../lib/serviceCookies-server");
+ await noteXServiceOutcome(paths, { challengeLine: "[twitter][warning] Cloudflare challenge", kind: "challenge" });
+ x = (await readServiceCookieState(paths)).services.x;
+ assert.equal(x?.kind, "challenge");
+ assert.equal(isBlockingAlert(x), true);
+ assert.deepEqual(x!.jobs.map((j) => j.id), [bDone.jobId]);
+ // And the jar-age path cannot overwrite it.
+ await writeJar(5 * 60_000);
+ await fetchJob(SLUGS[2], new Map());
+ assert.equal((await readServiceCookieState(paths)).services.x?.kind, "challenge");
+});
+
test("get x-session reports what the guard would answer: source, age, limit, allowed", async () => {
await reset();
const { xSessionReport, xJobGuard } = await import("./networkGuard");
diff --git a/common/lib/report/draft/tasks/links.ts b/common/lib/report/draft/tasks/links.ts
@@ -12,19 +12,23 @@
// the run's corpus.
import { parseCitationHref } from "../../convertShared";
+import { siteVideoId } from "../../../videoDirId.mjs";
import { extractJsonObject } from "../../../parseStdoutJson";
import type { CorpusToolsLike } from "./types";
-export function momentHref(origin: string, slug: string, id: string, seconds: number): string {
- return `${origin}/?v=${encodeURIComponent(`${slug}/${id}`)}&t=${Math.max(0, Math.floor(seconds))}`;
+// `platform`, when the caller knows it, maps a Twitch VOD's directory id `<n>`
+// to the record id `v<n>` the archive serves (siteVideoId — never keyed on the
+// id being digits). An id from a tool result is already the archive's.
+export function momentHref(origin: string, slug: string, id: string, seconds: number, platform?: string | null): string {
+ return `${origin}/?v=${encodeURIComponent(`${slug}/${siteVideoId(id, platform)}`)}&t=${Math.max(0, Math.floor(seconds))}`;
}
export function postLinkHref(origin: string, slug: string, id: string): string {
return `${origin}/?v=${encodeURIComponent(`${slug}/${id}`)}&vm=post`;
}
-export const momentBaseOf = (origin: string, slug: string, id: string) =>
- `${origin}/?v=${encodeURIComponent(`${slug}/${id}`)}&t=`;
+export const momentBaseOf = (origin: string, slug: string, id: string, platform?: string | null) =>
+ `${origin}/?v=${encodeURIComponent(`${slug}/${siteVideoId(id, platform)}`)}&t=`;
// Which channel (slug) holds a recording: read off a moment link when there is
// one, else asked of the corpus (get_video_metadata over the run's channels).
@@ -108,9 +112,11 @@ export async function rewriteMomentBases(text: string, resolver: SlugResolver, o
const MD_LINK = /\]\((https?:\/\/[^)\s]+)\)/g;
-// A platform's watch URL: `?v=<id>` (no slash in it) or youtu.be/<id>, and
-// its `t` (`t=90`, `t=90s`).
-function platformVideo(href: string): { id: string; seconds: number } | null {
+// A platform's watch URL: `?v=<id>` (no slash in it) or youtu.be/<id>, or a
+// Twitch VOD's `twitch.tv/videos/<n>` (served by the archive as `v<n>`:
+// siteVideoId, on the platform the host names), and its `t` (`t=90`, `t=90s`,
+// `t=1h2m3s`).
+export function platformVideo(href: string): { id: string; seconds: number } | null {
let u: URL;
try {
u = new URL(href);
@@ -118,14 +124,17 @@ function platformVideo(href: string): { id: string; seconds: number } | null {
return null;
}
let id: string | null = null;
+ const twitch = /^\/videos\/(\d+)\/?$/.exec(u.pathname);
if (u.hostname === "youtu.be") id = u.pathname.slice(1).split("/")[0] || null;
+ else if (/(^|\.)twitch\.tv$/.test(u.hostname)) id = twitch ? siteVideoId(twitch[1]!, "twitch") : null;
else {
const v = u.searchParams.get("v");
if (v && !v.includes("/")) id = v;
}
if (!id) return null;
- const t = /^(\d+)s?$/.exec(u.searchParams.get("t") ?? "");
- return { id, seconds: t ? Number(t[1]) : 0 };
+ const t = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?$/.exec(u.searchParams.get("t") ?? "");
+ const seconds = t ? Number(t[1] ?? 0) * 3600 + Number(t[2] ?? 0) * 60 + Number(t[3] ?? 0) : 0;
+ return { id, seconds };
}
// The backstop over finished markdown. Answers the text and how many links it
diff --git a/common/lib/report/draft/tasks/tasks.test.ts b/common/lib/report/draft/tasks/tasks.test.ts
@@ -8,7 +8,7 @@ import os from "node:os";
import path from "node:path";
import { ORIGIN, POSTS, cuesOf } from "../../../../testing/draft/corpus.mjs";
import { NARRATION_WRITING_RULES, rulesForModel, ruleForModel } from "../authoringRules";
-import { momentHref, rewriteLinks, rewriteMomentBases, slugResolver } from "./links";
+import { momentHref, platformVideo, rewriteLinks, rewriteMomentBases, slugResolver } from "./links";
import { chunksOf, lintClaim, locate, parseEnumerate, parseTranscripts, windowsOf } from "./sweep-pipeline";
import { pickCorpusBuild, siteOriginOf } from "./corpusSource";
import { checkQuotes, convertSweepText, dropFailedFindings } from "./quotes";
@@ -66,6 +66,22 @@ test("links: moment links are built on the origin; a platform URL and another or
assert.equal(asked, 2, "synth-other, then synth-kitchen — and cached for the second link");
});
+test("links: a Twitch VOD is linked as the archive's v<n> — by platform, never because the id is digits", async () => {
+ // A directory id with the platform known: the record id the archive serves.
+ assert.equal(momentHref(ORIGIN, "synth-twitch", "2468013579", 61.2, "twitch"), `${ORIGIN}/?v=synth-twitch%2Fv2468013579&t=61`);
+ assert.equal(momentHref(ORIGIN, "synth-twitch", "v2468013579", 61, "twitch"), `${ORIGIN}/?v=synth-twitch%2Fv2468013579&t=61`);
+ // An X status id is digits too: never a v.
+ assert.equal(momentHref(ORIGIN, "synth-social", "1850000000000000000", 4, "x"), `${ORIGIN}/?v=synth-social%2F1850000000000000000&t=4`);
+ assert.equal(momentHref(ORIGIN, "synth-social", "1850000000000000000", 4), `${ORIGIN}/?v=synth-social%2F1850000000000000000&t=4`);
+ // A twitch.tv/videos/<n> URL is the platform saying so; its t is h/m/s.
+ assert.deepEqual(platformVideo("https://www.twitch.tv/videos/2468013579?t=1h2m3s"), { id: "v2468013579", seconds: 3723 });
+ assert.equal(platformVideo("https://www.twitch.tv/somebody"), null);
+ const r = slugResolver(stubCorpus({ v2468013579: "synth-twitch" }), ["synth-twitch"]);
+ const out = await rewriteLinks("- [Stream @ 1:02:03](https://www.twitch.tv/videos/2468013579?t=1h2m3s)", r, ORIGIN);
+ assert.equal(out.fixed, 1);
+ assert.ok(out.md.includes(`(${ORIGIN}/?v=synth-twitch%2Fv2468013579&t=3723)`), out.md);
+});
+
test("links: get_transcripts' moment_base becomes the origin's, by the moment_base's own slug or by asking", async () => {
const text = [
"## Pie stream\n- video_id: pie-stream-02 | channel: Synth Kitchen\n- source: https://video.example/watch?v=pie-stream-02\n- moment_base: https://video.example/watch?v=pie-stream-02&t=\n[0:10|10] hello",
diff --git a/common/lib/serviceCookieSettings.ts b/common/lib/serviceCookieSettings.ts
@@ -0,0 +1,68 @@
+// settings.serviceCookies — the PROACTIVE side of the cookie refresh alerts
+// (plans/cookie-refresh-alerts.md, controller/serviceCookieTimer.ts): how often
+// the editor looks at each service's cookies by itself, so a stale Rumble
+// clearance is noticed before a sync or a download fails on it. Pure: the
+// type, its defaults, the sanitizer settingsSchema.ts runs it through and the
+// per-field docs SETTINGS.md renders.
+
+import type { FieldDocs } from "./fieldDocs";
+
+export type ServiceCookiesSettings = {
+ recheckIntervalMinutes: number;
+ probeServices: string[];
+};
+
+export const SERVICE_COOKIE_RECHECK_DEFAULT_MINUTES = 180;
+// Below half an hour a "proactive" probe is a poll; above a day it notices
+// nothing a sync would not.
+export const SERVICE_COOKIE_RECHECK_MIN_MINUTES = 30;
+export const SERVICE_COOKIE_RECHECK_MAX_MINUTES = 1440;
+// The yt-dlp services a tick may probe with no alert up.
+export const SERVICE_COOKIE_PROBE_SERVICES = ["rumble", "youtube", "odysee"] as const;
+
+export const DEFAULT_SERVICE_COOKIES_SETTINGS: ServiceCookiesSettings = {
+ recheckIntervalMinutes: SERVICE_COOKIE_RECHECK_DEFAULT_MINUTES,
+ probeServices: ["rumble"],
+};
+
+export const SERVICE_COOKIES_SETTINGS_FIELD_DOCS: FieldDocs<ServiceCookiesSettings> = {
+ recheckIntervalMinutes:
+ "Every this many minutes (stretched by up to `pacing.jitter`, never shortened) the editor looks at each " +
+ "service's cookies by itself (common/controller/serviceCookieTimer.ts): every RAISED cookie alert that has " +
+ "something to ask is rechecked once, as the banner's Recheck does (so a banner clears by itself once the " +
+ "operator has opened the site in the browser); each of `probeServices` with no alert is probed once — one " +
+ "metadata request for the last video it answered cleanly — so a stale Cloudflare clearance raises the banner " +
+ "before a sync or a download fails on it; and X's cookie jar is re-read from disk (never a request to X). A " +
+ "service is skipped when a job is queued or running on its platform (that job is the probe), when it is " +
+ "cooling down or held, when it answered cleanly within the interval, or when a recheck of it is already " +
+ "running. A failed probe is never retried: the banner goes up (a Rumble embed 403 confirms on a second, " +
+ "different known-good video, once, a jittered minute or more later) and waits for the next tick or a manual " +
+ "Recheck. 0 turns the timer off; otherwise " +
+ `${SERVICE_COOKIE_RECHECK_MIN_MINUTES}–${SERVICE_COOKIE_RECHECK_MAX_MINUTES}. Default ` +
+ `${SERVICE_COOKIE_RECHECK_DEFAULT_MINUTES}. Not armed on an idle boot (ARCHILYZER_IDLE_BOOT) or on the e2e ` +
+ "test server. `pnpm ops get services` shows its last tick (`timer`).",
+ probeServices:
+ "The yt-dlp services the timer probes with no alert up — any of " +
+ `${SERVICE_COOKIE_PROBE_SERVICES.map((s) => `\`"${s}"\``).join(", ")}. Default \`["rumble"]\` (Rumble's ` +
+ "Cloudflare clearance is the one that goes stale by itself). `[]` probes nothing; raised alerts are still " +
+ "rechecked.",
+};
+
+export function clampServiceCookieRecheckMinutes(v: unknown): number {
+ if (typeof v !== "number" || !Number.isFinite(v)) return SERVICE_COOKIE_RECHECK_DEFAULT_MINUTES;
+ const n = Math.floor(v);
+ if (n <= 0) return 0;
+ return Math.min(SERVICE_COOKIE_RECHECK_MAX_MINUTES, Math.max(SERVICE_COOKIE_RECHECK_MIN_MINUTES, n));
+}
+
+export function sanitizeServiceCookies(value: unknown): ServiceCookiesSettings {
+ const r = (value && typeof value === "object" && !Array.isArray(value) ? value : {}) as Record<string, unknown>;
+ const known = SERVICE_COOKIE_PROBE_SERVICES as readonly string[];
+ const probeServices = Array.isArray(r.probeServices)
+ ? [...new Set(r.probeServices.filter((s): s is string => typeof s === "string" && known.includes(s)))]
+ : [...DEFAULT_SERVICE_COOKIES_SETTINGS.probeServices];
+ return {
+ recheckIntervalMinutes: clampServiceCookieRecheckMinutes(r.recheckIntervalMinutes),
+ probeServices,
+ };
+}
diff --git a/common/lib/serviceCookies-server.ts b/common/lib/serviceCookies-server.ts
@@ -24,6 +24,7 @@ import {
coerceServiceCookieState,
forumServiceKey,
isAlertRaised,
+ isBlockingAlert,
isYtdlpCookieService,
noteLastGood,
pruneServiceCookieState,
@@ -115,7 +116,7 @@ export async function noteServiceCookieSignal(
);
if (res.raised && job && !job.staleServices.has(signal.service)) {
job.staleServices.add(signal.service);
- job.onLog(`${serviceStoppedLine(signal.service, opts.browser ?? configuredCookieBrowser())}\n`);
+ job.onLog(`${serviceStoppedLine(signal.service, opts.browser ?? configuredCookieBrowser(), res.entry.kind)}\n`);
} else if (!res.raised && job && signal.kind === "embed-403") {
job.onLog(
`${serviceLabel(signal.service)} refused an embed (${signal.videoId ?? "?"}) with a 403 — a removed video does ` +
@@ -312,13 +313,13 @@ export async function markServiceCookieRerun(
// throws. Answers the line for the job log when a clean request cleared it.
export async function noteXServiceOutcome(
paths: Pick<Paths, "transcriptsDir">,
- outcome: { challengeLine?: string; url?: string; channel?: string },
+ outcome: { challengeLine?: string; kind?: "challenge" | "auth-failure"; url?: string; channel?: string },
): Promise<string | null> {
try {
if (outcome.challengeLine) {
await noteServiceCookieSignal(
paths,
- { service: X_SERVICE, kind: "challenge", line: outcome.challengeLine.trim().slice(0, 300) },
+ { service: X_SERVICE, kind: outcome.kind ?? "challenge", line: outcome.challengeLine.trim().slice(0, 300) },
{
...(outcome.url ? { url: outcome.url } : {}),
...(outcome.channel ? { channel: outcome.channel } : {}),
@@ -376,3 +377,75 @@ export async function noteServiceStoppedJob(
// bookkeeping only
}
}
+
+// ── X's jar age (the fresh-jar rule as a banner) ──────────────────────────
+
+// X WORK WAS REFUSED, OR IS WAITING, ON AN OLD JAR: the fresh-jar rule refused
+// an X job (jobs/networkGuard.ts — at enqueue, or at its start: then `job` is
+// recorded for "Re-run stopped jobs"), or the recheck timer found X jobs
+// queued on a jar past its limit. Raises (or keeps) X's "jar-age" alert — one
+// is enough. A no-op while a BLOCKING X alert (a challenge, a login failure) is
+// up: that one already says more, and its sentence must not be overwritten.
+// Never throws; answers whether the alert is up after it.
+export async function noteXJarStale(
+ paths: Pick<Paths, "transcriptsDir">,
+ info: { line: string; channel?: string; job?: { id: string; kind?: string } },
+ now: number = Date.now(),
+): Promise<boolean> {
+ try {
+ return await mutate(
+ paths,
+ (state, at) => {
+ const e = state.services[X_SERVICE];
+ if (isBlockingAlert(e)) {
+ if (info.job && !e!.jobs.some((j) => j.id === info.job!.id)) {
+ e!.jobs = [...e!.jobs, { id: info.job.id, ...(info.job.kind ? { kind: info.job.kind } : {}) }].slice(-20);
+ return { changed: true, out: true };
+ }
+ return { changed: false, out: true };
+ }
+ const r = applyServiceCookieSignal(
+ state,
+ { service: X_SERVICE, kind: "jar-age", line: info.line.trim().slice(0, 300) },
+ {
+ ...(info.job ? { jobId: info.job.id, ...(info.job.kind ? { jobKind: info.job.kind } : {}) } : {}),
+ ...(info.channel ? { channel: info.channel } : {}),
+ },
+ at,
+ );
+ return { changed: true, out: isAlertRaised(r.entry) };
+ },
+ now,
+ );
+ } catch {
+ return false;
+ }
+}
+
+// X's jar is FRESH again (the guard let an X job through, the timer or a
+// Recheck re-read it): a raised jar-age alert clears — "OK again", with the
+// jobs it stopped offered for re-run. Any other X alert is left alone (only
+// Recheck, Dismiss or a clean gallery-dl run clears a challenge). A cheap
+// unlocked peek first, so the guard's every X job costs one read. Never
+// throws; answers the job-log line when it cleared one.
+export async function noteXJarFresh(
+ paths: Pick<Paths, "transcriptsDir">,
+ opts: { now?: number; by?: "clean" | "recheck" } = {},
+): Promise<string | null> {
+ try {
+ const peek = (await readServiceCookieState(paths)).services[X_SERVICE];
+ if (!isAlertRaised(peek) || peek!.kind !== "jar-age") return null;
+ return await mutate(
+ paths,
+ (state, now) => {
+ const e = state.services[X_SERVICE];
+ if (!isAlertRaised(e) || e!.kind !== "jar-age") return { changed: false, out: null };
+ applyServiceCookieClean(state, X_SERVICE, now, opts.by ?? "clean");
+ return { changed: true, out: "X's cookie jar is fresh again: its cookie alert is cleared.\n" };
+ },
+ opts.now,
+ );
+ } catch {
+ return null;
+ }
+}
diff --git a/common/lib/serviceCookies.ts b/common/lib/serviceCookies.ts
@@ -22,13 +22,21 @@
import { isBotCheck } from "./availability";
-export type ServiceCookieKind = "embed-403" | "bot-check" | "challenge" | "check-page";
+// "auth-failure": X's login refused or gone (gallery-dl's AuthRequired, a 401,
+// "Could not authenticate you" — social/xGalleryDlSignals.ts). "jar-age": X's
+// cookie jar older than `social.x.maxCookieAgeMinutes` while X work wants to
+// run (an X job refused for it, or X jobs queued) — the one kind that is NOT a
+// request's answer, raised from a clock and a file's age, and the one X kind
+// that does not itself refuse X jobs (the fresh-jar rule already does).
+export type ServiceCookieKind = "embed-403" | "bot-check" | "challenge" | "check-page" | "auth-failure" | "jar-age";
export const SERVICE_COOKIE_KINDS: readonly ServiceCookieKind[] = [
"embed-403",
"bot-check",
"challenge",
"check-page",
+ "auth-failure",
+ "jar-age",
];
// The yt-dlp services: their requests go through yt-dlp with the browser
@@ -91,8 +99,14 @@ export function serviceLabel(service: string): string {
// What the operator does about it, as one clause ("open rumble.com in
// firefox"). `browser` is the configured `cookiesFromBrowser` spec — what
// yt-dlp reads the cookies from — when there is one.
-export function serviceFixText(service: string, browser?: string): string {
+export function serviceFixText(service: string, browser?: string, kind?: ServiceCookieKind): string {
const b = browserName(browser);
+ if (service === X_SERVICE && kind === "jar-age") {
+ return (
+ "press Refresh cookies (or Connect X account) on /settings for a fresh X cookie jar — with the browser " +
+ `login, open x.com in ${b} — then Recheck; nothing is asked of X until then`
+ );
+ }
switch (service) {
case "rumble":
return `open rumble.com in ${b} (a fresh Cloudflare clearance cookie)`;
@@ -121,8 +135,8 @@ function browserName(spec: string | undefined): string {
}
// The line a job's log carries when it meets a stale service.
-export function serviceStoppedLine(service: string, browser?: string): string {
- return `stopped: ${serviceLabel(service)} cookies look stale — ${serviceFixText(service, browser)}, then Recheck on the dashboard.`;
+export function serviceStoppedLine(service: string, browser?: string, kind?: ServiceCookieKind): string {
+ return `stopped: ${serviceLabel(service)} cookies look stale — ${serviceFixText(service, browser, kind)}, then Recheck on the dashboard.`;
}
// ── the signal ────────────────────────────────────────────────────────────
@@ -212,8 +226,15 @@ export type ServiceCookieEntry = {
rerunJobIds?: string[];
};
-// The last clean request per service — what Recheck asks again.
-export type ServiceCookieLastGood = { url: string; channel?: string; at: string };
+// The last clean request per service — what Recheck asks again — and the one
+// before it for a DIFFERENT URL (`prev`): the proactive timer's second,
+// different known-good video when the first answers Rumble's ambiguous 403.
+export type ServiceCookieLastGood = {
+ url: string;
+ channel?: string;
+ at: string;
+ prev?: { url: string; channel?: string; at: string };
+};
export type ServiceCookieState = {
version: 1;
@@ -308,7 +329,18 @@ export function coerceServiceCookieState(raw: unknown): ServiceCookieState {
const at = iso(g.at);
if (!url || !at) continue;
const channel = str(g.channel, 200);
- out.lastGood[key] = { url, at, ...(channel ? { channel } : {}) };
+ const p = g.prev && typeof g.prev === "object" ? (g.prev as Record<string, unknown>) : null;
+ const prevUrl = p ? str(p.url) : undefined;
+ const prevAt = p ? iso(p.at) : undefined;
+ const prevChannel = p ? str(p.channel, 200) : undefined;
+ out.lastGood[key] = {
+ url,
+ at,
+ ...(channel ? { channel } : {}),
+ ...(prevUrl && prevAt && prevUrl !== url
+ ? { prev: { url: prevUrl, at: prevAt, ...(prevChannel ? { channel: prevChannel } : {}) } }
+ : {}),
+ };
}
return out;
}
@@ -317,6 +349,13 @@ export function isAlertRaised(e: ServiceCookieEntry | undefined): boolean {
return !!e?.raisedAt && !e.clearedAt;
}
+// A raised alert that REFUSES the service's jobs (jobs/networkGuard.ts — X
+// only): every raised kind but jar-age, whose refusal is the fresh-jar rule's
+// own and which clears the moment the jar is fresh.
+export function isBlockingAlert(e: ServiceCookieEntry | undefined): boolean {
+ return isAlertRaised(e) && e!.kind !== "jar-age";
+}
+
export type SignalContext = {
jobId?: string;
jobKind?: string;
@@ -336,9 +375,14 @@ export function applyServiceCookieSignal(
let entry = state.services[signal.service];
const stalePending =
entry && !entry.raisedAt && now - Date.parse(entry.lastSeen) > PENDING_SIGNAL_TTL_MS;
+ // A raised jar-age alert that meets a real answer from X (a challenge, a
+ // login wall) is ESCALATED to it — that kind refuses every X job, jar-age
+ // does not — keeping the jobs it already holds for "Re-run stopped jobs".
+ const escalate = !!entry?.raisedAt && !entry.clearedAt && entry.kind === "jar-age" && signal.kind !== "jar-age";
+ const carriedJobs = escalate ? entry!.jobs : [];
// A cleared alert is replaced by the new trouble; so is a pending one gone
// stale, and one of another kind that never raised.
- if (!entry || entry.clearedAt || stalePending || (!entry.raisedAt && entry.kind !== signal.kind)) {
+ if (!entry || entry.clearedAt || stalePending || escalate || (!entry.raisedAt && entry.kind !== signal.kind)) {
entry = {
service: signal.service,
kind: signal.kind,
@@ -347,7 +391,7 @@ export function applyServiceCookieSignal(
count: 0,
evidence: { line: signal.line },
videos: [],
- jobs: [],
+ jobs: [...carriedJobs],
};
state.services[signal.service] = entry;
}
@@ -412,7 +456,16 @@ export function noteLastGood(
): boolean {
const prev = state.lastGood[service];
if (prev && now - Date.parse(prev.at) < LAST_GOOD_REFRESH_MS) return false;
- state.lastGood[service] = { url: good.url, at: new Date(now).toISOString(), ...(good.channel ? { channel: good.channel } : {}) };
+ const older =
+ prev && prev.url !== good.url
+ ? { url: prev.url, at: prev.at, ...(prev.channel ? { channel: prev.channel } : {}) }
+ : prev?.prev;
+ state.lastGood[service] = {
+ url: good.url,
+ at: new Date(now).toISOString(),
+ ...(good.channel ? { channel: good.channel } : {}),
+ ...(older ? { prev: older } : {}),
+ };
return true;
}
@@ -463,18 +516,61 @@ export type ServiceCookieAlertView = {
canRecheck: boolean;
// The jobs the alert stopped (failed or cancelled), not yet re-run.
stoppedJobs: ServiceCookieJobView[];
+ // Drawn as headline + `fix` (one action line) + `detail` when it is not
+ // empty — no evidence line (X's jar-age banner).
+ compact?: boolean;
rerunAt?: string;
rerunJobIds?: string[];
};
+// X's cookie jar, read from disk (no request): the profile's exported jar's
+// mtime, or — with the browser login — when Firefox last sent its x.com
+// auth_token (social/xJarAge.ts). Served beside the alerts whether or not one
+// is up, so `pnpm ops get services` always says how fresh X's login is.
+export type XJarStatusView = {
+ source: "profile" | "browser";
+ // When the login was last renewed (ISO), when it could be read.
+ at: string | null;
+ ageMinutes: number | null;
+ // social.x.maxCookieAgeMinutes, resolved (0 = no limit).
+ maxAgeMinutes: number;
+ // An auth_token is in the source (null: the source could not be read).
+ loggedIn: boolean | null;
+ // Within the limit (or no limit) and logged in: an X job may start on it.
+ fresh: boolean;
+ readAt: string;
+ summary: string;
+};
+
+// The proactive recheck timer (controller/serviceCookieTimer.ts), when this
+// process armed it.
+export type ServiceCookieTimerView = {
+ // settings.serviceCookies.recheckIntervalMinutes (0 = off).
+ intervalMinutes: number;
+ armed: boolean;
+ lastTickAt?: string;
+ nextTickAt?: string;
+ // What the last tick did, per service it looked at.
+ last?: { service: string; action: string; message: string }[];
+};
+
export type ServiceCookieAlertsPayload = {
alerts: ServiceCookieAlertView[];
// Services with a first signal waiting for a second (not shown as a banner).
pending: { service: string; label: string; kind: ServiceCookieKind; videos: string[]; lastSeen: string }[];
+ x?: XJarStatusView;
+ timer?: ServiceCookieTimerView;
};
const STOPPED_STATUSES = new Set(["failed", "cancelled"]);
+// "45 min", "3 h", "16 days".
+function jarAgeText(min: number): string {
+ if (min < 120) return `${min} min`;
+ const h = Math.floor(min / 60);
+ return h < 48 ? `${h} h` : `${Math.floor(h / 24)} days`;
+}
+
function hhmm(isoText: string): string {
return isoText.slice(11, 16);
}
@@ -489,6 +585,10 @@ function kindPhrase(kind: ServiceCookieKind, count: number, videos: number): str
return `${count} challenge page${count === 1 ? "" : "s"}`;
case "check-page":
return `${count} check page${count === 1 ? "" : "s"}`;
+ case "auth-failure":
+ return `${count} login failure${count === 1 ? "" : "s"}`;
+ case "jar-age":
+ return "cookie jar past its age limit";
}
}
@@ -500,6 +600,9 @@ export function buildServiceCookieAlerts(
now: number;
browser?: string;
statusOf?: (jobId: string) => string | undefined;
+ // X's jar as read from disk: a jar-age banner's headline says its age, and
+ // its one action line matches the login source in use.
+ xJar?: Pick<XJarStatusView, "source" | "ageMinutes" | "maxAgeMinutes">;
},
): ServiceCookieAlertsPayload {
const alerts: ServiceCookieAlertView[] = [];
@@ -513,7 +616,7 @@ export function buildServiceCookieAlerts(
continue;
}
if (e.clearedAt && opts.now - Date.parse(e.clearedAt) > CLEARED_KEEP_MS) continue;
- const fix = serviceFixText(e.service, opts.browser);
+ const fix = serviceFixText(e.service, opts.browser, e.kind);
const jobs = e.jobs.map((j) => {
const status = opts.statusOf?.(j.id);
return { ...j, ...(status ? { status } : {}) };
@@ -530,6 +633,46 @@ export function buildServiceCookieAlerts(
(e.evidence.channel ? `, ${e.evidence.channel}` : "");
const stale = !e.clearedAt;
const n = stoppedJobs.length;
+ // X's jar-age banner is THREE SHORT LINES, no lead paragraph (operator's UI
+ // rule): how old the jar is, the one thing to do for the login source in
+ // use, and which job it refused when it refused one.
+ if (stale && e.kind === "jar-age") {
+ const jar = opts.xJar;
+ const age = jar?.ageMinutes != null ? jarAgeText(jar.ageMinutes) : null;
+ const limit = jar && jar.maxAgeMinutes > 0 ? ` (limit ${jar.maxAgeMinutes} min)` : "";
+ const action =
+ jar?.source === "browser"
+ ? `Open x.com in ${browserName(opts.browser).replace(/^[a-z]/, (c) => c.toUpperCase())} — then Recheck.`
+ : "Refresh cookies (or Connect X account) on /settings — then Recheck.";
+ const queued = /^(\d+ X jobs? (?:is|are) queued)/.exec(e.evidence.line)?.[1];
+ const refused = job
+ ? `Refused ${job.kind ? `${job.kind} ` : ""}${job.id}${e.evidence.channel ? ` (${e.evidence.channel})` : ""}.`
+ : e.evidence.channel
+ ? `Refused an X job on ${e.evidence.channel}.`
+ : queued
+ ? `${queued}.`
+ : "";
+ alerts.push({
+ service: e.service,
+ label,
+ family: serviceFamily(e.service),
+ state: "stale",
+ kind: e.kind,
+ since: e.since,
+ raisedAt: e.raisedAt,
+ lastSeen: e.lastSeen,
+ count: e.count,
+ videos: e.videos,
+ evidence: e.evidence,
+ fix: action,
+ headline: age ? `${label} cookies are ${age} old${limit}` : `${label} cookies are past their age limit${limit}`,
+ detail: refused,
+ compact: true,
+ canRecheck: true,
+ stoppedJobs,
+ });
+ continue;
+ }
alerts.push({
service: e.service,
label,
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -15,6 +15,7 @@ import {
ARCHIVES_SETTINGS_FIELD_DOCS,
CLIPS_SETTINGS_FIELD_DOCS,
JOBS_SETTINGS_FIELD_DOCS,
+ SERVICE_COOKIES_SETTINGS_FIELD_DOCS,
ARCHIVE_STORAGE_SETTINGS_FIELD_DOCS,
ATTRIBUTION_SETTINGS_FIELD_DOCS,
BACKFILL_SETTINGS_FIELD_DOCS,
@@ -342,6 +343,13 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
defaults: fromObject(d.jobs),
},
],
+ serviceCookies: [
+ {
+ path: "serviceCookies",
+ docs: SERVICE_COOKIES_SETTINGS_FIELD_DOCS,
+ defaults: fromObject(d.serviceCookies),
+ },
+ ],
};
}
diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts
@@ -35,6 +35,7 @@ import type { TtsSettings } from "./ttsSettings";
import type { ArchivesSettings } from "./archives/settings";
import type { ClipsSettings } from "./clipSettings";
import type { JobsSettings } from "./jobsSettings";
+import type { ServiceCookiesSettings } from "./serviceCookieSettings";
import type { GenerationSettings } from "./generationSettings";
import type {
AttributionSettings,
@@ -126,13 +127,15 @@ type PreSchemaSiteSettings = {
clips: ClipsSettings;
// What the job system does across a restart (2026-10-26).
jobs: JobsSettings;
+ // The cookie refresh alerts' proactive timer (2026-10-31).
+ serviceCookies: ServiceCookiesSettings;
};
// Bracketed so the conditional does not distribute (see commit 8c43231).
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true;
-test("SiteSettings keeps its 44 fields, in file order", () => {
+test("SiteSettings keeps its 45 fields, in file order", () => {
assert.equal(shapeUnchanged, true);
assert.deepEqual(Object.keys(siteSettingsSchema.shape), [
"adminTitle",
@@ -179,6 +182,7 @@ test("SiteSettings keeps its 44 fields, in file order", () => {
"generation",
"clips",
"jobs",
+ "serviceCookies",
]);
// A parsed object carries every key, in that order — writeSettings writes
// exactly this, so the order is the on-disk order.
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -83,6 +83,7 @@ import { sanitizeTts, type TtsSettings } from "./ttsSettings";
import { sanitizeArchives, type ArchivesSettings } from "./archives/settings";
import { sanitizeClips, type ClipsSettings } from "./clipSettings";
import { sanitizeJobs, type JobsSettings } from "./jobsSettings";
+import { sanitizeServiceCookies, type ServiceCookiesSettings } from "./serviceCookieSettings";
import { sanitizeGeneration, type GenerationSettings } from "./generationSettings";
export {
GENERATION_CAPS_FIELD_DOCS,
@@ -103,6 +104,7 @@ export { ORPHEUS_TTS_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, type TtsSetti
export { ARCHIVES_SETTINGS_FIELD_DOCS, type ArchivesSettings } from "./archives/settings";
export { CLIPS_SETTINGS_FIELD_DOCS, type ClipsSettings } from "./clipSettings";
export { JOBS_SETTINGS_FIELD_DOCS, type JobsSettings } from "./jobsSettings";
+export { SERVICE_COOKIES_SETTINGS_FIELD_DOCS, type ServiceCookiesSettings } from "./serviceCookieSettings";
import {
DEFAULT_COOKIE_MODE,
isCookieMode,
@@ -2000,6 +2002,9 @@ export const siteSettingsSchema = z.object({
jobs: settingsField((v): JobsSettings => sanitizeJobs(v)).describe(
"What the job system does on its own across a restart: whether the jobs the previous process left interrupted are resumed at boot (common/jobs/resumeInterrupted.ts). See JobsSettings.",
),
+ serviceCookies: settingsField((v): ServiceCookiesSettings => sanitizeServiceCookies(v)).describe(
+ "The cookie refresh alerts' PROACTIVE timer (plans/cookie-refresh-alerts.md): how often the editor rechecks raised alerts, probes Rumble's clearance with no alert up, and re-reads X's cookie jar age, by itself — so the dashboard banner goes up before a sync or a download fails. See ServiceCookiesSettings and common/controller/serviceCookieTimer.ts.",
+ ),
});
export type SiteSettings = z.infer<typeof siteSettingsSchema>;
diff --git a/common/lib/videoDirId.mjs b/common/lib/videoDirId.mjs
@@ -50,6 +50,26 @@ export function twitchVodRecordId(dirId) {
}
/**
+ * The id the ARCHIVE serves a manifest entry's recording under — what a link
+ * to its page (`?v=<channel>/<id>`) must carry. An explicit `siteVideo` wins
+ * (a Rumble clip: its local dir is the URL slug, the archive keys the embed
+ * id). Else `video`, except that a TWITCH VOD's directory id `<n>` is served
+ * as its record id `v<n>` (twitchVodRecordId) — keyed on the PLATFORM, never
+ * on the id being all digits: an X status id is digits too, and is served as
+ * it is.
+ * @param {string | { video?: unknown, siteVideo?: unknown } | null | undefined} entry
+ * an entry (`{video, siteVideo?}`) or a bare id
+ * @param {string | null | undefined} platform the recording's (or its channel's) platform
+ * @returns {string}
+ */
+export function siteVideoId(entry, platform) {
+ const e = typeof entry === "string" ? { video: entry } : (entry ?? {});
+ if (typeof e.siteVideo === "string" && e.siteVideo) return e.siteVideo;
+ const id = e.video == null ? "" : String(e.video);
+ return platform === "twitch" ? (twitchVodRecordId(id) ?? id) : id;
+}
+
+/**
* The platform a channel's config names: `platform`, else its `url`'s host
* (ytdlp/channelArgs.ts channelPlatform's rule). Null for none.
* @param {{ platform?: unknown, url?: unknown } | null | undefined} config
diff --git a/common/lib/videoDirId.test.ts b/common/lib/videoDirId.test.ts
@@ -14,6 +14,7 @@ import {
channelConfigPlatform,
extractVideoId,
pickVideoDirId,
+ siteVideoId,
twitchVodDirId,
twitchVodRecordId,
} from "./videoId";
@@ -36,6 +37,16 @@ test("twitchVodDirId drops only a v before digits; twitchVodRecordId is its reve
assert.equal(twitchVodRecordId(twitchVodDirId(META.id)!), META.id);
});
+test("siteVideoId: the archive's id — v<n> for a Twitch directory id only, siteVideo first, X digits untouched", () => {
+ assert.equal(siteVideoId({ video: N }, "twitch"), `v${N}`);
+ assert.equal(siteVideoId(`v${N}`, "twitch"), `v${N}`);
+ assert.equal(siteVideoId({ video: N }, "x"), N);
+ assert.equal(siteVideoId({ video: N }, null), N);
+ assert.equal(siteVideoId({ video: N }, undefined), N);
+ assert.equal(siteVideoId({ video: "a-url-slug", siteVideo: "v2embedid" }, "rumble"), "v2embedid");
+ assert.equal(siteVideoId(null, "twitch"), "");
+});
+
test("channelConfigPlatform: the platform key, else the url's host", () => {
assert.equal(channelConfigPlatform({ platform: "twitch" }), "twitch");
assert.equal(channelConfigPlatform({ url: "https://www.twitch.tv/example" }), "twitch");
diff --git a/common/lib/videoId.ts b/common/lib/videoId.ts
@@ -20,6 +20,7 @@ import { isJwPlayerHost, isWaybackHost, jwPlayerMediaId, parseWaybackUrl } from
export {
channelConfigPlatform,
pickVideoDirId,
+ siteVideoId,
twitchVodDirId,
twitchVodRecordId,
} from "./videoDirId.mjs";
diff --git a/common/social/__fixtures__/firefoxCookieStore.ts b/common/social/__fixtures__/firefoxCookieStore.ts
@@ -16,6 +16,8 @@ export type FixtureCookie = {
expiry?: number;
// PRTime: microseconds since the epoch.
lastAccessed?: number;
+ // PRTime; absent: lastAccessed.
+ creationTime?: number;
isSecure?: 0 | 1;
isHttpOnly?: 0 | 1;
sameSite?: number;
@@ -58,7 +60,7 @@ export function insertFixtureCookies(db: SqliteDb, cookies: ReadonlyArray<Fixtur
c.path ?? "/",
c.expiry ?? Math.floor(Date.now() / 1000) + 86_400 * 365,
c.lastAccessed ?? nowUs,
- c.lastAccessed ?? nowUs,
+ c.creationTime ?? c.lastAccessed ?? nowUs,
c.isSecure ?? 1,
c.isHttpOnly ?? 1,
c.sameSite ?? 0,
diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts
@@ -31,6 +31,7 @@ import type { Readable } from "node:stream";
import { execa } from "execa";
import { getPaths } from "../lib/paths";
import { noteXServiceOutcome } from "../lib/serviceCookies-server";
+import { looksLikeXAuthFailure, xBlockKind, xBlockLine } from "./xGalleryDlSignals";
import { cookieArgs } from "../lib/cookiePolicy";
import type { Post } from "../lib/posts";
import type { OlderBackfillPosition } from "../lib/posts-server";
@@ -70,40 +71,22 @@ import {
type OnePostFetchResult,
} from "./fetchers";
-// Substrings in gallery-dl's stderr that mean "we are not authenticated" (or no
-// longer are). Mapped to needsCookies so the channel lands in the existing
+// "Are we still logged in?" — classified line by line in xGalleryDlSignals.ts
+// (pure, unit-tested on gallery-dl's real messages): a challenge, a login
+// failure, a rate limit (pacing, never cookies) or one account's refusal
+// (protected, blocked, suspended; a media file's 403 on twimg.com). An auth
+// failure maps to needsCookies so the channel lands in the existing
// Needs-cookies bucket instead of looking like a generic crash.
-const AUTH_ERROR_PATTERNS = [
- "401",
- "403",
- "authorization",
- "unauthorized",
- "login required",
- "requires authentication",
- "no username",
- "bad credentials",
- "could not log in",
-];
-
-function looksLikeAuthFailure(text: string): boolean {
- const lower = text.toLowerCase();
- return AUTH_ERROR_PATTERNS.some((p) => lower.includes(p));
-}
-
+//
// X STOPPED ANSWERING (plans/pacing-guard.md). On 2026-10-23 gallery-dl
// printed `[twitter][warning] Cloudflare challenge`, EXITED 0, read nothing,
// and the job ended `done` — the next twelve fetches went straight on. A
-// challenge word on any stderr line, or an auth failure (AUTH_ERROR_PATTERNS)
-// on a warning or error line, now stops the run whatever the exit code: the
-// fetch fails (posts read so far kept) and the X cookie alert is raised, which
-// refuses every X job until it is cleared (jobs/networkGuard.ts).
-const X_CHALLENGE_LINE = /cloudflare|\bchallenge\b|just a moment|captcha/i;
-const LEVEL_LINE = /\]\[(warning|error)\]/i;
-
-export function xBlockLine(line: string): boolean {
- if (X_CHALLENGE_LINE.test(line)) return true;
- return LEVEL_LINE.test(line) && looksLikeAuthFailure(line);
-}
+// challenge on any stderr line, or a login failure on a warning or error line,
+// now stops the run whatever the exit code: the fetch fails (posts read so far
+// kept) and the X cookie alert is raised, which refuses every X job until it
+// is cleared (jobs/networkGuard.ts).
+const looksLikeAuthFailure = looksLikeXAuthFailure;
+export { xBlockLine };
export function xBlockedError(line: string): string {
return (
@@ -122,7 +105,7 @@ async function noteXOutcome(
): Promise<void> {
if (challengeLine) onLog?.(`[auth] ${xBlockedError(challengeLine)}`);
const cleared = await noteXServiceOutcome(getPaths(), {
- ...(challengeLine ? { challengeLine } : {}),
+ ...(challengeLine ? { challengeLine, kind: xBlockKind(challengeLine) } : {}),
...(url ? { url } : {}),
...(channel ? { channel } : {}),
});
diff --git a/common/social/xGalleryDlSignals.test.ts b/common/social/xGalleryDlSignals.test.ts
@@ -0,0 +1,76 @@
+// What a gallery-dl stderr line says about X's login (xGalleryDlSignals.ts),
+// on the messages gallery-dl 1.32's twitter extractor and job runner really
+// print (extractor/twitter.py, extractor/common.py, exception.py, job.py):
+// a challenge and a login failure raise X's cookie alert; a rate limit is
+// pacing; one account's or one media file's refusal is not the login.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xGalleryDlSignals.test.ts
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import {
+ classifyXStderrLine,
+ looksLikeXAuthFailure,
+ xBlockKind,
+ xBlockLine,
+} from "./xGalleryDlSignals";
+
+const CASES: Array<[string, ReturnType<typeof classifyXStderrLine>]> = [
+ // Challenges — any level, one is enough.
+ ["[twitter][warning] Cloudflare challenge", "challenge"],
+ ["[twitter][error] ChallengeError: Cloudflare challenge (403 Forbidden) for 'https://x.com/i/api/graphql/abc/UserTweets'", "challenge"],
+ ["[twitter][warning] Cloudflare CAPTCHA", "challenge"],
+ ["[twitter][warning] DDoS-Guard challenge", "challenge"],
+ // The login gone or refused.
+ ["[twitter][error] AuthRequired: authenticated cookies needed to access this timeline", "auth"],
+ ["[twitter][error] AuthenticationError: Invalid login credentials", "auth"],
+ ["[twitter][error] 'Could not authenticate you'", "auth"],
+ ["[twitter][error] HttpError: '401 Unauthorized' for 'https://x.com/i/api/graphql/abc/UserTweets'", "auth"],
+ ["[twitter][error] HTTP redirect to login page (401 Unauthorized)", "auth"],
+ ["[twitter][error] 403 Forbidden (Forbidden)", "auth"],
+ ["[twitter][error] AuthorizationError: Account temporarily locked", "auth"],
+ // Pacing, never cookies.
+ ["[twitter][info] Waiting for 14 minutes until 03:12:44 (rate limit)", "rate-limit"],
+ ["[twitter][info] Waiting for 60 seconds until 03:12:44 (429 Too Many Requests)", "rate-limit"],
+ ["[twitter][error] Rate limit exceeded", "rate-limit"],
+ ["[twitter][error] HttpError: '429 Too Many Requests' for 'https://x.com/i/api/graphql/403abc/UserTweets'", "rate-limit"],
+ // One account, one post, one media file: the login is fine.
+ ["[twitter][error] AuthorizationError: someone's Tweets are protected", "account"],
+ ["[twitter][error] AuthorizationError: someone blocked your account", "account"],
+ ["[twitter][error] AuthRequired: Protected Tweet", "account"],
+ ["[twitter][error] AuthRequired: NSFW Tweet", "account"],
+ ["[twitter][error] NotFoundError: Requested user could not be found", "account"],
+ ["[download][warning] HttpError: '403 Forbidden' for 'https://video.twimg.com/ext_tw_video/1/pu/vid/720x1280/a.mp4'", "account"],
+ // Nothing.
+ ["[twitter][debug] Cursor: DAABCgABG", null],
+ ["[twitter][debug] HttpError: '401 Unauthorized' (debug lines never count)", null],
+ ["[twitter][info] Requesting guest token", null],
+ ["", null],
+ // A login phrase on an untagged line counts only for a failed run's tail.
+ ["401 Unauthorized", null],
+];
+
+test("each real gallery-dl line is classified: challenge, auth, rate limit, one account, or nothing", () => {
+ for (const [line, want] of CASES) {
+ assert.equal(classifyXStderrLine(line), want, line);
+ }
+});
+
+test("xBlockLine stops a run (and raises X's alert) only on a challenge or a login failure", () => {
+ assert.equal(xBlockLine("[twitter][warning] Cloudflare challenge"), true);
+ assert.equal(xBlockLine("[twitter][error] AuthRequired: authenticated cookies needed to access this timeline"), true);
+ assert.equal(xBlockLine("[twitter][info] Waiting for 14 minutes until 03:12:44 (rate limit)"), false);
+ assert.equal(xBlockLine("[twitter][error] HttpError: '429 Too Many Requests' for 'https://x.com/i/api/x'"), false);
+ assert.equal(xBlockLine("[twitter][error] AuthorizationError: someone's Tweets are protected"), false);
+ assert.equal(xBlockLine("[download][warning] HttpError: '403 Forbidden' for 'https://pbs.twimg.com/media/a.jpg'"), false);
+ assert.equal(xBlockKind("[twitter][warning] Cloudflare challenge"), "challenge");
+ assert.equal(xBlockKind("[twitter][error] 'Could not authenticate you'"), "auth-failure");
+});
+
+test("a failed run's tail: a login failure (even untagged) is Needs-cookies; a rate limit or a protected account is not", () => {
+ assert.equal(looksLikeXAuthFailure("some progress\n401 Unauthorized"), true);
+ assert.equal(looksLikeXAuthFailure("[twitter][error] AuthRequired: authenticated cookies needed to access this timeline"), true);
+ assert.equal(looksLikeXAuthFailure("[twitter][error] Rate limit exceeded"), false);
+ assert.equal(looksLikeXAuthFailure("[twitter][error] AuthorizationError: someone's Tweets are protected"), false);
+ assert.equal(looksLikeXAuthFailure("[twitter][error] AbortExtraction: 404 Not Found (GraphQL query id rotated)"), false);
+});
diff --git a/common/social/xGalleryDlSignals.ts b/common/social/xGalleryDlSignals.ts
@@ -0,0 +1,114 @@
+// WHAT ONE gallery-dl STDERR LINE SAYS ABOUT X (plans/pacing-guard.md,
+// plans/cookie-refresh-alerts.md). Pure and client-safe: the X fetcher
+// (xGalleryDlFetcher.ts) asks it of every stderr line, and the answer decides
+// whether X's cookie alert goes up — which refuses EVERY X job until it is
+// cleared (jobs/networkGuard.ts). So the classes are drawn carefully:
+//
+// "challenge" Cloudflare's (or DDoS-Guard's) check or a captcha. One is
+// enough: the next request after it is the one that gets the
+// account locked.
+// "auth" the login itself is gone or refused: gallery-dl's
+// AuthRequired ("authenticated cookies needed to access this
+// timeline" — what X answers a logged-out timeline with),
+// AuthenticationError, "Could not authenticate you", a 401, a
+// 403 from X's API, an account X has temporarily locked. The
+// COOKIES are the fix (counted only on a warning or error line).
+// "rate-limit" a 429, "Too Many Requests", "rate limit" — PACING, never
+// cookies: gallery-dl waits it out itself, and fresh cookies
+// would not help.
+// "account" about ONE account or post, not the login: a protected
+// account, one that blocked ours, a suspended or missing one,
+// an NSFW or protected tweet, a media file's 403/404 on
+// twimg.com. Not a cookie signal — raising X's alert for it
+// would stop every other X job for nothing.
+// null anything else (progress, debug, an unrelated error).
+//
+// The order matters: a ChallengeError line carries "403" too
+// ("Cloudflare challenge (403 Forbidden) for '…'"), and a 429 line may carry
+// a URL with digits in it, so challenge is asked first, then the rate limit,
+// then the per-account phrases, and only then the login.
+
+export type XStderrClass = "challenge" | "auth" | "rate-limit" | "account";
+
+const DEBUG_LINE = /\]\[debug\]/i;
+// "[twitter][warning] …", "[twitter][error] …", "[download][error] …".
+const LEVEL_LINE = /\]\[(warning|error)\]/i;
+
+const CHALLENGE = /cloudflare|\bchallenge\b|just a moment|captcha|ddos-guard/i;
+const RATE_LIMIT = /\b429\b|too many requests|rate[- ]?limit/i;
+// One account's or one post's refusal: the login is fine.
+const ACCOUNT_SCOPED = new RegExp(
+ [
+ "tweets are protected",
+ "blocked your account",
+ "protected tweet",
+ "nsfw tweet",
+ "age-restricted",
+ "account (?:is )?suspended",
+ "user (?:is )?suspended",
+ "user not found",
+ "could not be found",
+ "notfounderror",
+ "does not exist",
+ // A media file on X's CDN: a removed video or picture, not the login.
+ "twimg\\.com",
+ ].join("|"),
+ "i",
+);
+const AUTH = new RegExp(
+ [
+ "authrequired",
+ "authenticationerror",
+ "authorizationerror",
+ "authenticated cookies needed",
+ "account credentials required",
+ "invalid login credentials",
+ "could not authenticate you",
+ "login required",
+ "requires authentication",
+ "redirect to (?:the )?login",
+ "no username",
+ "bad credentials",
+ "could not log in",
+ "unauthorized",
+ "account temporarily locked",
+ "\\b401\\b",
+ "\\b403\\b",
+ ].join("|"),
+ "i",
+);
+
+// `anyLevel`: count a login phrase on a line with no [warning]/[error] tag
+// too — for the tail of a run that already EXITED non-zero, where the failure
+// is not in doubt and only its cause is asked.
+export function classifyXStderrLine(line: string, opts: { anyLevel?: boolean } = {}): XStderrClass | null {
+ const l = line.trim();
+ if (!l || DEBUG_LINE.test(l)) return null;
+ if (CHALLENGE.test(l)) return "challenge";
+ if (RATE_LIMIT.test(l)) return "rate-limit";
+ const levelled = opts.anyLevel || LEVEL_LINE.test(l);
+ if (ACCOUNT_SCOPED.test(l)) return levelled ? "account" : null;
+ if (AUTH.test(l)) return levelled ? "auth" : null;
+ return null;
+}
+
+// The lines that stop an X run and raise its cookie alert: a challenge on any
+// line, a login failure on a warning or error line.
+export function xBlockLine(line: string): boolean {
+ const c = classifyXStderrLine(line);
+ return c === "challenge" || c === "auth";
+}
+
+// The alert's kind for a blocking line.
+export function xBlockKind(line: string): "challenge" | "auth-failure" {
+ return classifyXStderrLine(line) === "challenge" ? "challenge" : "auth-failure";
+}
+
+// A failed run's stderr tail: does it say the LOGIN failed (the Needs-cookies
+// bucket), as opposed to a rate limit, one protected account, or a crash?
+export function looksLikeXAuthFailure(text: string): boolean {
+ return text.split("\n").some((l) => {
+ const c = classifyXStderrLine(l, { anyLevel: true });
+ return c === "auth" || c === "challenge";
+ });
+}
diff --git a/common/social/xJarAge.test.ts b/common/social/xJarAge.test.ts
@@ -0,0 +1,117 @@
+// X's jar age, from disk (xJarAge.ts): the profile jar's mtime, or the
+// browser's x.com auth_token last-sent time read BY NAME from a Firefox
+// cookies.sqlite. Every store is a fixture written through node:sqlite under a
+// temp HOME (__fixtures__/firefoxCookieStore.ts) — no test reads a real
+// browser profile, and nothing asks X.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xJarAge.test.ts
+
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync } from "node:fs";
+import { mkdir, readdir, rm, utimes, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { readFirefoxXAuthTimes, readXJarAge, xJarStatusFrom } from "./xJarAge";
+import { writeFirefoxCookieStore, type FixtureCookie } from "./__fixtures__/firefoxCookieStore";
+
+const TMP = mkdtempSync(path.join(os.tmpdir(), "xjarage-"));
+after(() => rm(TMP, { recursive: true, force: true }));
+let n = 0;
+const fresh = (label: string) => path.join(TMP, `${label}-${++n}`);
+
+const NOW = Date.UTC(2026, 9, 31, 23, 0, 0);
+const us = (msAgo: number) => (NOW - msAgo) * 1000;
+const SECRET = "fixture-auth-value-never-read";
+
+function login(lastUsedMsAgo: number, extra: FixtureCookie[] = []): FixtureCookie[] {
+ return [
+ { host: ".x.com", name: "auth_token", value: SECRET, lastAccessed: us(lastUsedMsAgo), creationTime: us(30 * 86_400_000) },
+ { host: ".x.com", name: "ct0", value: "csrf" },
+ { host: "notx.com", name: "auth_token", value: "lookalike", lastAccessed: us(0) },
+ ...extra,
+ ];
+}
+
+function pathsAt(dir: string): Paths {
+ return { transcriptsDir: dir } as unknown as Paths;
+}
+
+test("the name-only read: the x.com auth_token's times, its value never selected", async () => {
+ const { file } = await writeFirefoxCookieStore(fresh("ff"), login(30 * 60_000));
+ const t = await readFirefoxXAuthTimes(file, { tmpRoot: TMP });
+ assert.equal(t.found, true);
+ assert.equal(t.lastAccessedMs, NOW - 30 * 60_000);
+ assert.equal(t.creationMs, NOW - 30 * 86_400_000);
+ assert.equal(JSON.stringify(t).includes(SECRET), false);
+ // The private copy is gone.
+ assert.deepEqual((await readdir(TMP)).filter((f) => f.startsWith("archilyzer-xjar-")), []);
+});
+
+test("a login only Firefox's write-ahead log holds counts; one in an unread container does not", async () => {
+ const { file, db } = await writeFirefoxCookieStore(fresh("wal"), login(5 * 60_000), { keepOpen: true });
+ try {
+ assert.equal((await readFirefoxXAuthTimes(file, { tmpRoot: TMP })).found, true);
+ } finally {
+ db?.close();
+ }
+ const { file: f2 } = await writeFirefoxCookieStore(fresh("container"), [
+ { host: ".x.com", name: "auth_token", value: SECRET, lastAccessed: us(60_000), originAttributes: "^userContextId=2" },
+ ]);
+ assert.equal((await readFirefoxXAuthTimes(f2, { tmpRoot: TMP })).found, false);
+ assert.equal((await readFirefoxXAuthTimes(f2, { tmpRoot: TMP, container: "all" })).found, true);
+});
+
+test("browser source: fresh within the limit, stale past it, no limit at 0; cached between reads unless asked fresh", async () => {
+ const home = fresh("home");
+ const profile = path.join(home, ".mozilla", "firefox", "abc.default-release");
+ await writeFirefoxCookieStore(profile, login(30 * 60_000));
+ const settings = { cookiesFromBrowser: "firefox", social: { x: { cookieSource: "browser" as const } } };
+ const p = pathsAt(fresh("transcripts"));
+ const ok = await readXJarAge(p, settings, { maxAgeMinutes: 60, now: NOW, home, tmpRoot: TMP, fresh: true });
+ assert.equal(ok.source, "browser");
+ assert.equal(ok.loggedIn, true);
+ assert.equal(ok.ageMinutes, 30);
+ assert.equal(ok.fresh, true);
+ assert.match(ok.summary, /last used 30 min ago \(limit 60 min\)\.$/);
+ assert.equal(JSON.stringify(ok).includes(SECRET), false);
+
+ const stale = await readXJarAge(p, settings, { maxAgeMinutes: 20, now: NOW, home, tmpRoot: TMP, fresh: true });
+ assert.equal(stale.fresh, false);
+ assert.match(stale.summary, /open x\.com in that browser/);
+ assert.equal((await readXJarAge(p, settings, { maxAgeMinutes: 0, now: NOW, home, tmpRoot: TMP, fresh: true })).fresh, true);
+
+ // The store changes (the operator opened x.com) — a cached read does not see
+ // it; a fresh read does.
+ await rm(profile, { recursive: true, force: true });
+ await writeFirefoxCookieStore(profile, login(60_000));
+ const cached = await readXJarAge(p, settings, { maxAgeMinutes: 60, now: NOW + 60_000, home, tmpRoot: TMP });
+ assert.equal(cached.ageMinutes, 31, "re-derived from the cached reading at the new time");
+ const reread = await readXJarAge(p, settings, { maxAgeMinutes: 60, now: NOW, home, tmpRoot: TMP, fresh: true });
+ assert.equal(reread.ageMinutes, 1);
+});
+
+test("profile source: the exported jar's mtime and its auth_token", async () => {
+ const dir = fresh("transcripts");
+ const jar = path.join(dir, ".x-session", "cookies.txt");
+ await mkdir(path.join(dir, ".x-session", "profile"), { recursive: true });
+ await writeFile(jar, "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tv\n");
+ const t = new Date(NOW - 3 * 3600_000);
+ await utimes(jar, t, t);
+ const settings = { social: { x: { cookieSource: "profile" as const } } };
+ const v = await readXJarAge(pathsAt(dir), settings, { maxAgeMinutes: 60, now: NOW });
+ assert.equal(v.source, "profile");
+ assert.equal(v.ageMinutes, 180);
+ assert.equal(v.fresh, false);
+ assert.match(v.summary, /^The X cookie jar was written 3 h ago \(limit 60 min\): press Refresh cookies/);
+ await utimes(jar, new Date(NOW - 60_000), new Date(NOW - 60_000));
+ assert.equal((await readXJarAge(pathsAt(dir), settings, { maxAgeMinutes: 60, now: NOW })).fresh, true);
+});
+
+test("the verdict, pure: no login is never fresh; an unreadable source says why", () => {
+ assert.equal(xJarStatusFrom({ source: "profile", at: null, loggedIn: false, maxAgeMinutes: 0, now: NOW }).fresh, false);
+ const u = xJarStatusFrom({ source: "browser", at: null, loggedIn: null, maxAgeMinutes: 60, now: NOW, unreadable: "No Firefox cookie store found." });
+ assert.equal(u.fresh, false);
+ assert.equal(u.summary, "No Firefox cookie store found.");
+});
diff --git a/common/social/xJarAge.ts b/common/social/xJarAge.ts
@@ -0,0 +1,224 @@
+// HOW FRESH IS X'S LOGIN — read from disk, never from X (plans/cookie-refresh-
+// alerts.md, "X's jar age"). The X fetchers' login comes from one of two
+// sources (social/xCookieSource.ts):
+//
+// "profile" the session broker's exported jar (`.x-session/cookies.txt`):
+// fresh = the file was written (Connect X account / Refresh
+// cookies) within `social.x.maxCookieAgeMinutes`, and it holds an
+// auth_token. A stat and a substring test.
+// "browser" the operator's Firefox, named by cookiesFromBrowser: fresh =
+// Firefox SENT its x.com auth_token (moz_cookies.lastAccessed —
+// the operator had x.com open) within the limit. Read BY NAME:
+// the query selects the cookie's host, name and times only —
+// never its value — from a private copy of the store (the store
+// and its write-ahead log, so a login Firefox has not
+// checkpointed yet counts), in a 0700 temp dir removed after.
+//
+// Nothing here asks X anything, and nothing refreshes the jar: a refresh is a
+// human click (refreshXCookies loads x.com/home — itself a request to X).
+//
+// The browser read copies a small SQLite file, so its answer is cached for a
+// few minutes (the dashboard polls); `fresh: true` reads again (the recheck
+// timer, Recheck).
+
+import { copyFile, mkdir, mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { XJarStatusView } from "../lib/serviceCookies";
+import { loadSqlite } from "./nodeSqlite";
+import { readXSessionStatus } from "./xSessionBroker";
+import {
+ X_AUTH_COOKIE,
+ findFirefoxCookieDb,
+ firefoxContainerScope,
+ inContainerScope,
+ isXComHost,
+ resolveXCookieSourceFor,
+ type XLoginSettings,
+} from "./xBrowserLogin";
+import { parseBrowserSpec, SELF_READ_BROWSERS } from "./xCookieSource";
+
+export const X_JAR_BROWSER_CACHE_MS = 5 * 60_000;
+
+export type FirefoxAuthTimes = {
+ // The newest x.com auth_token in scope: when Firefox last sent it and when
+ // it was set (ms since the epoch).
+ lastAccessedMs?: number;
+ creationMs?: number;
+ // Any x.com auth_token in scope at all.
+ found: boolean;
+};
+
+// PRTime (microseconds) → ms; a value already in ms is kept.
+function prtimeMs(v: unknown): number | undefined {
+ const n = typeof v === "bigint" ? Number(v) : typeof v === "number" ? v : NaN;
+ if (!Number.isFinite(n) || n <= 0) return undefined;
+ return Math.floor(n > 1e14 ? n / 1000 : n);
+}
+
+// THE NAME-ONLY READ: the x.com auth_token's times from a Firefox
+// cookies.sqlite, in the container scope gallery-dl reads (`container` as in
+// a cookiesFromBrowser spec: absent/"none", "all", or a name). The value column
+// is never selected.
+export async function readFirefoxXAuthTimes(
+ dbFile: string,
+ opts: { container?: string; tmpRoot?: string } = {},
+): Promise<FirefoxAuthTimes> {
+ const { DatabaseSync } = await loadSqlite();
+ const scope = await firefoxContainerScope(dbFile, opts.container);
+ const tmp = await mkdtemp(path.join(opts.tmpRoot ?? os.tmpdir(), "archilyzer-xjar-"));
+ try {
+ const copy = path.join(tmp, "store", "cookies.sqlite");
+ await mkdir(path.dirname(copy));
+ await copyFile(dbFile, copy);
+ await copyFile(`${dbFile}-wal`, `${copy}-wal`).catch((err: NodeJS.ErrnoException) => {
+ if (err.code !== "ENOENT") throw err;
+ });
+ const db = new DatabaseSync(copy);
+ try {
+ const rows = db
+ .prepare(
+ "SELECT host, name, lastAccessed, creationTime, originAttributes FROM moz_cookies WHERE name = ?",
+ )
+ .all(X_AUTH_COOKIE) as Array<Record<string, unknown>>;
+ let best: FirefoxAuthTimes = { found: false };
+ for (const r of rows) {
+ if (typeof r.host !== "string" || !isXComHost(r.host)) continue;
+ const attrs = typeof r.originAttributes === "string" ? r.originAttributes : "";
+ if (!inContainerScope(attrs, scope)) continue;
+ const last = prtimeMs(r.lastAccessed);
+ const created = prtimeMs(r.creationTime);
+ if (!best.found || (last ?? 0) > (best.lastAccessedMs ?? 0)) {
+ best = {
+ found: true,
+ ...(last ? { lastAccessedMs: last } : {}),
+ ...(created ? { creationMs: created } : {}),
+ };
+ }
+ }
+ return best;
+ } finally {
+ db.close();
+ }
+ } finally {
+ await rm(tmp, { recursive: true, force: true });
+ }
+}
+
+function ageText(min: number): string {
+ if (min < 120) return `${min} min`;
+ const h = Math.floor(min / 60);
+ return h < 48 ? `${h} h` : `${Math.floor(h / 24)} days`;
+}
+
+// The verdict from what was read, pure.
+export function xJarStatusFrom(input: {
+ source: "profile" | "browser";
+ at: string | null;
+ loggedIn: boolean | null;
+ maxAgeMinutes: number;
+ now: number;
+ // What could not be read, when nothing could (browser source).
+ unreadable?: string;
+}): XJarStatusView {
+ const readAt = new Date(input.now).toISOString();
+ const ageMinutes = input.at ? Math.max(0, Math.floor((input.now - Date.parse(input.at)) / 60_000)) : null;
+ const within = input.maxAgeMinutes <= 0 || (ageMinutes !== null && ageMinutes <= input.maxAgeMinutes);
+ const fresh = input.loggedIn === true && within;
+ const limit = input.maxAgeMinutes > 0 ? ` (limit ${input.maxAgeMinutes} min)` : " (no age limit)";
+ let summary: string;
+ if (input.unreadable) summary = input.unreadable;
+ else if (input.source === "profile") {
+ summary = !input.at
+ ? "No X cookie jar has been exported: press Connect X account on /settings."
+ : input.loggedIn !== true
+ ? "The X cookie jar holds no login (no auth_token): press Connect X account on /settings."
+ : `The X cookie jar was written ${ageText(ageMinutes!)} ago${limit}` +
+ (fresh ? "." : ": press Refresh cookies (or Connect X account) on /settings.");
+ } else {
+ summary = input.loggedIn !== true
+ ? "No X login in the browser cookiesFromBrowser names (no x.com auth_token): log in to x.com there."
+ : !input.at
+ ? "The browser holds an X login; when it was last used could not be read."
+ : `The browser's X login was last used ${ageText(ageMinutes!)} ago${limit}` +
+ (fresh ? "." : ": open x.com in that browser.");
+ }
+ return {
+ source: input.source,
+ at: input.at,
+ ageMinutes,
+ maxAgeMinutes: input.maxAgeMinutes,
+ loggedIn: input.loggedIn,
+ fresh,
+ readAt,
+ summary,
+ };
+}
+
+type Cache = { key: string; at: number; view: XJarStatusView };
+const CACHE_KEY = Symbol.for("archilyzer.xJarAge.cache");
+function cache(): { last?: Cache } {
+ const g = globalThis as unknown as Record<symbol, { last?: Cache }>;
+ return (g[CACHE_KEY] ??= {});
+}
+
+export async function readXJarAge(
+ paths: Paths,
+ settings: XLoginSettings,
+ opts: { maxAgeMinutes: number; now?: number; fresh?: boolean; home?: string; tmpRoot?: string },
+): Promise<XJarStatusView> {
+ const now = opts.now ?? Date.now();
+ const resolved = await resolveXCookieSourceFor(paths, settings);
+ if (resolved.source === "profile") {
+ const st = await readXSessionStatus(paths);
+ return xJarStatusFrom({
+ source: "profile",
+ at: st.cookiesUpdatedAt ?? null,
+ loggedIn: st.hasCookies ? st.looksAuthenticated : false,
+ maxAgeMinutes: opts.maxAgeMinutes,
+ now,
+ });
+ }
+ const spec = resolved.browserSpec?.trim() ?? "";
+ const key = `browser:${spec}`;
+ const c = cache();
+ if (!opts.fresh && c.last && c.last.key === key && now - c.last.at < X_JAR_BROWSER_CACHE_MS) {
+ // Re-derive the age at `now` from the cached reading.
+ return xJarStatusFrom({
+ source: "browser",
+ at: c.last.view.at,
+ loggedIn: c.last.view.loggedIn,
+ maxAgeMinutes: opts.maxAgeMinutes,
+ now,
+ });
+ }
+ const unreadable = (why: string) =>
+ xJarStatusFrom({ source: "browser", at: null, loggedIn: null, maxAgeMinutes: opts.maxAgeMinutes, now, unreadable: why });
+ const parsed = spec ? parseBrowserSpec(spec) : null;
+ if (!parsed) return unreadable("cookiesFromBrowser names no browser to read an X login from.");
+ if (!SELF_READ_BROWSERS.includes(parsed.browser)) {
+ return unreadable(`${parsed.browser}'s cookie store is encrypted; only Firefox's X login age can be read here.`);
+ }
+ let view: XJarStatusView;
+ try {
+ const found = await findFirefoxCookieDb(parsed, opts.home ?? os.homedir());
+ if (!found.file) return unreadable("No Firefox cookie store found.");
+ const t = await readFirefoxXAuthTimes(found.file, {
+ ...(parsed.container ? { container: parsed.container } : {}),
+ ...(opts.tmpRoot ? { tmpRoot: opts.tmpRoot } : {}),
+ });
+ const atMs = t.lastAccessedMs ?? t.creationMs;
+ view = xJarStatusFrom({
+ source: "browser",
+ at: atMs ? new Date(atMs).toISOString() : null,
+ loggedIn: t.found,
+ maxAgeMinutes: opts.maxAgeMinutes,
+ now,
+ });
+ } catch (err) {
+ return unreadable(`Could not read Firefox's cookie store: ${(err as Error).message}`);
+ }
+ c.last = { key, at: now, view };
+ return view;
+}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,8 @@
# Changelog
## [Unreleased]
+- **X has a cookie banner like Rumble's, and says how fresh its jar is.** X's banner used to go up only when X answered a fetch with a challenge, so an X fetch on an old jar was simply refused with a sentence the operator saw only in a job's error. Now the fresh-jar rule's refusal (`social.x.maxCookieAgeMinutes`, an hour by default) puts an **X needs fresh cookies** banner on the dashboard — "press Refresh cookies (or Connect X account) on /settings — with the browser login, open x.com in firefox" — with the jar's age under it, read from disk: the exported jar's time, or, with the browser login, when Firefox last sent its x.com `auth_token` (read by the cookie's name from a private copy of Firefox's cookie store; its value is never read). An X fetch refused at its start is offered under **Re-run stopped jobs** once the jar is fresh. Recheck re-reads the age and asks X nothing; the banner clears by itself as soon as an X job passes the rule on a fresh jar. This banner does not itself refuse X jobs (the rule does); a real challenge or login failure from X replaces it with the one that does. gallery-dl's own words are now read more carefully: its "AuthRequired: authenticated cookies needed to access this timeline" (what X answers a logged-out timeline with), "Could not authenticate you", a 401 and an API 403 count as a **login failure** (worded so on the banner and in the refusal), a 429 or "rate limit" is pacing and never raises the banner, and a protected or blocking account, an NSFW or protected tweet and a 403 on a twimg.com media file are about that one account or file — those used to raise X's banner and stop every X job. `pnpm ops get services` now always carries `x` (the jar's source, age, limit and whether an X job could start on it). Needs a restart of the editor.
+- **Rumble's cookies are checked on a timer, so the banner goes up before a sync fails.** Until now a stale Cloudflare clearance was noticed only when a Rumble sync or clip fetch failed on it. Every 3 hours (stretched a little at random, never shortened) the editor now looks by itself: when Rumble has been idle that long, it asks Rumble once for the last video it answered cleanly — a refusal is checked once more on the previous, different video a minute or more later, because a removed video refuses too, and two different videos refused put the banner up; every banner already up is rechecked once, as its Recheck button does, so it clears by itself after rumble.com was opened in Firefox; and X's jar age is re-read from disk (X jobs queued on an old jar put X's banner up before their start refuses them). Nothing is asked while a job is queued or running on Rumble's queues (its answer is the check), while Rumble is cooling down or held, or while a recheck runs, and a failed check is never retried — it waits for the next tick or a click. Each check is a **Recheck service cookies** job on /jobs. `settings.serviceCookies.recheckIntervalMinutes` (180; 30–1440; 0 turns it off) and `probeServices` (`["rumble"]`; YouTube and Odysee may be added), set with `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`; `pnpm ops get services` shows the timer's last tick under `timer`. Not on an idle boot. Needs a restart of the editor.
- **A channel can download only the videos you add.** The operator wanted Harmful Opinions downloaded by hand, with its title filter gone, and nothing said that: `syncIntervalMinutes: 0` stops the listing but the download lane still works the backlog it has — and dropping a filter re-decides every video it had settled, so the whole channel would come down — while a `paused` tier stops every lane, transcription too. Configure → Advanced → **Downloads**: Manual (`downloadMode: "manual"` in config.json; `pnpm ops channel-config --json '{"slug":"<slug>","patch":{"downloadMode":"manual"}}'`, `""` sets it back to Automatic). On a manual channel the download lane skips the channel (its backlog, retries, metadata scan and chat backlog); a sync reads only the newest page of the listing and a full sweep still refreshes the playlist and the maybe-missing set, and neither downloads the new uploads it finds; Download from playlist, Download videos (`download-missing`) and the bucket retries refuse with a notice. What you ask for still downloads — Import, `import-video`, the video page's download and persist buttons, `persist-videos`, clip windows, a whole-recording fetch — and the videos on disk are still transcribed. The channel's report keeps the listed videos it lacks as **Listed, not requested** (`manualNotRequestedIds`) rather than undownloaded work, so no lane, rack figure, dashboard count or group Download button counts them, and a video that leaves the listing unfetched is not raised as never fetched; the channel page says "Manual downloads — only videos you add are downloaded" at the top and the rack row carries a **manual dl** chip. An import still passes the channel's download filter, so set the mode first and then clear the filter. Needs a restart of the editor.
- **A report-video take can be walked clip by clip before it is rendered, and made the cut.** Until now the clip bench walked only a project's own cut, and a take's clips could only be watched as a render. Now a take — a tight version's 27 sub-windows, say — opens on the bench at `/projects/<project>/takes/<take>/walk` (**Walk this take** on its card, or **walk a take** on the Cut tab): its clips in walk order with their verdicts, each played from the windows already fetched, with nothing fetched again for a clip inside one. Everything the walk changes — a verdict, a trim, a note, a clip removed or moved (**← earlier**, **later →**, **Remove from take**) — goes into the take's own patch in `takes/<take>/take.json`, never the project's manifest, and **Undo take edit** takes back the newest one. **walk every clip** keeps the clips that already carry a verdict on the walk. `umtool take <project> --id <take> --patch F --draft` records a take without rendering it (the Takes page shows it as **draft — walk / render**), and `umtool take <project> --id <take> --full` or **Render full** renders it later from its walked patch. **Make this the cut** (`umtool take <project> --id <take> --promote`) puts the take over the project's manifest with one undo point, so the Cut tab's **Undo last edit** takes it back; it waits for **Make it the cut anyway** when the take's timeline would replace a cut that changed since the take was made. From a terminal: `umtool walk <project> --take <take>`, `umtool window <project> <clip> --take <take> …` and `umtool timeline <project> --take <take> move|remove|undo`. A windowed render of a take whose timeline has none of the project's clips is now timed over the take's own clips instead of being refused. Needs a restart of umtool for the pages; the CLI has it at once.
- **A live stream can be transcribed and clipped while it is still recording.** Until now a recording was transcribed only once the stream ended and the file landed, so on a long stream nothing could be found or shared until hours later. `pnpm ops record-live` takes `"preclip": true` (or `{"everyMinutes": 10, "maxChunkMinutes": 20, "overlapSeconds": 15, "scan": true, "mine": true, "project": "<slug>"}`, defaults in `settings.livePreclip`). `pnpm ops live-preclip {"slug", "id"}` starts the same thing on a recording already running, and the video page's **Live pre-clip** panel has a Start button. Every few minutes a tick transcribes only what was recorded since the last one. It reads the growing file in place and never copies it or touches the recorder, whatever the recording is: one MPEG-TS, YouTube's separate video and audio, or Kick's polled VOD. The new span is transcribed on the transcription worker, with word timings, and added to `data/<id>/live-transcript.json`, marked provisional, on the clock the landed video will have. The clip finder then grows a umtool project for the stream (`<id>-live`), so its windows can be walked in the clip editor while the stream goes on. A busy worker never piles ticks up: the next tick takes everything since, and a tick that is far behind is followed by the next one at once. A tick is skipped, and the log says why, when there is under 30 s new, when the machine is under the 6 GB memory floor (checked again every minute), or when the store's disk has under 2 GB free. A recorder that restarts or falls back (Rumble) is followed. If its audio matches, the transcript goes on; if not, it starts again on the new recording and the project's windows are flagged. When the stream lands, the landed video is checked against what was transcribed live, and the windows stay where they are when it matches (flagged when it does not). Once the final transcript is there it replaces the live one, and the project reads the corpus from then on. `"action": "stop"`, `"status"` and `"finalize"` stop it (the recording goes on), print its state, and finish that hand-over by hand. **A clip of a stream still live can be shared at once:** `pnpm ops live-clip {"slug", "id", "start", "end"}`, the panel's **Share this clip**, or the clip editor's **Share now (live)** cuts the window from what is recorded so far and makes the clip's short with the live captions. A share is at most 2:20 and 512 MiB, for X, and nothing is fetched from the network. Needs a restart of the editor and umtool.
diff --git a/editor/app/components/dashboard/CookieAlertsPanel.tsx b/editor/app/components/dashboard/CookieAlertsPanel.tsx
@@ -5,12 +5,14 @@
// firefox" — with Recheck (one request through the service's own path) and
// Dismiss; once the service answers cleanly again, "OK again" with Re-run for
// the jobs it stopped. The dashboard's top slot, like the first-run checklist.
+// X's card also says how fresh its cookie jar is, read from disk (`data.x`).
import Link from "next/link";
import { useState, useTransition } from "react";
import type {
ServiceCookieAlertView,
ServiceCookieAlertsPayload,
+ XJarStatusView,
} from "yt-dlp-transcript-common/lib/serviceCookies";
import {
dismissServiceCookiesAction,
@@ -21,7 +23,15 @@ import {
const BUTTON =
"rounded-md border border-border bg-card px-2.5 py-1 text-xs hover:bg-muted disabled:opacity-50";
-function AlertCard({ alert, onChange }: { alert: ServiceCookieAlertView; onChange: () => void }) {
+function AlertCard({
+ alert,
+ xJar,
+ onChange,
+}: {
+ alert: ServiceCookieAlertView;
+ xJar?: XJarStatusView;
+ onChange: () => void;
+}) {
const [note, setNote] = useState<{ text: string; error: boolean } | null>(null);
const [pending, start] = useTransition();
const stale = alert.state === "stale";
@@ -44,6 +54,15 @@ function AlertCard({ alert, onChange }: { alert: ServiceCookieAlertView; onChang
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="flex min-w-0 flex-col gap-1">
<p className={`text-sm font-medium ${stale ? "text-destructive" : "text-brand"}`}>{alert.headline}</p>
+ {alert.compact ? (
+ <>
+ <p className="text-xs" aria-label={`${alert.label} cookies action`}>
+ {alert.fix}
+ </p>
+ {alert.detail && <p className="text-xs text-muted-foreground break-words">{alert.detail}</p>}
+ </>
+ ) : (
+ <>
<p className="text-xs text-muted-foreground break-words">
{alert.detail}
{alert.family === "forum" && channel && (
@@ -63,11 +82,21 @@ function AlertCard({ alert, onChange }: { alert: ServiceCookieAlertView; onChang
</>
)}
</p>
+ {alert.family === "x" && xJar && (
+ <p
+ className={`text-xs ${xJar.fresh ? "text-muted-foreground" : "text-destructive/80"}`}
+ aria-label="X cookie jar"
+ >
+ {xJar.summary}
+ </p>
+ )}
{alert.evidence.line && (
<code className="block max-w-full truncate text-[11px] text-muted-foreground" title={alert.evidence.line}>
{alert.evidence.line}
</code>
)}
+ </>
+ )}
</div>
<div className="flex shrink-0 flex-wrap items-center gap-1.5">
{stale && alert.canRecheck && (
@@ -126,7 +155,7 @@ export function CookieAlertsPanel({
return (
<div className="flex flex-col gap-2" aria-label="Cookie refresh alerts">
{data.alerts.map((a) => (
- <AlertCard key={a.service} alert={a} onChange={onChange} />
+ <AlertCard key={a.service} alert={a} xJar={a.family === "x" ? data.x : undefined} onChange={onChange} />
))}
</div>
);
diff --git a/editor/app/lib/cookieAlerts.ts b/editor/app/lib/cookieAlerts.ts
@@ -1,7 +1,10 @@
// THE DASHBOARD'S COOKIE REFRESH ALERTS (plans/cookie-refresh-alerts.md): the
// state file read, each recorded job's status asked of the registry (else its
// sidecar), and the pure builder (lib/serviceCookies.ts) over both. Served as
-// the `cookieAlerts` view and SSR-seeded by app/page.tsx.
+// the `cookieAlerts` view and SSR-seeded by app/page.tsx. Beside the alerts:
+// X's jar age read from disk (`x` — always, so `pnpm ops get services` says
+// how fresh X's login is) and the proactive recheck timer's last tick
+// (`timer`, controller/serviceCookieTimer.ts).
import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths";
import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
@@ -14,6 +17,10 @@ import {
configuredCookieBrowser,
readServiceCookieState,
} from "yt-dlp-transcript-common/lib/serviceCookies-server";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { readXJarAge } from "yt-dlp-transcript-common/social/xJarAge";
+import { resolvedXMaxCookieAgeMinutes } from "yt-dlp-transcript-common/jobs/networkGuard";
+import { serviceCookieTimerView } from "yt-dlp-transcript-common/controller/serviceCookieTimer";
export async function loadCookieAlerts(
paths: Paths = getPaths(),
@@ -37,9 +44,29 @@ export async function loadCookieAlerts(
const replayable = Boolean(live?.spec ?? meta?.spec);
if (status && replayable) statuses.set(id, status);
}
- return buildServiceCookieAlerts(state, {
+ // Never a request: a stat of the profile's jar, or (browser login) a cached
+ // name-only read of Firefox's store. A read that fails leaves `x` out.
+ let settings: ReturnType<typeof getSettings> | null = null;
+ try {
+ settings = getSettings();
+ } catch {
+ settings = null;
+ }
+ let x: Awaited<ReturnType<typeof readXJarAge>> | undefined;
+ if (settings) {
+ try {
+ x = await readXJarAge(paths, settings, { maxAgeMinutes: resolvedXMaxCookieAgeMinutes(settings), now });
+ } catch {
+ /* no X login to read */
+ }
+ }
+ const payload = buildServiceCookieAlerts(state, {
now,
browser: configuredCookieBrowser(),
statusOf: (id) => statuses.get(id),
+ ...(x ? { xJar: x } : {}),
});
+ if (x) payload.x = x;
+ payload.timer = serviceCookieTimerView(settings?.serviceCookies.recheckIntervalMinutes);
+ return payload;
}
diff --git a/editor/e2e/cookie-alerts.spec.ts b/editor/e2e/cookie-alerts.spec.ts
@@ -235,3 +235,106 @@ test("X: a stale jar refuses Fetch posts; \"\" is refused; a challenge fails the
expect(ok.body.ok).toBe(true);
expect(await waitJob(request, ok.body.jobId!)).toBe("done");
});
+
+// ── X's cookie banner like Rumble's (2026-10-31) ──────────────────────────
+//
+// Operator: "add banner cookie refresh indicator for X like we have for
+// Rumble". The fresh-jar rule's refusal raises X's banner (kind jar-age) with
+// the jar's age read from disk; Recheck re-reads it (no request to X); a
+// refreshed jar makes it "OK again". A logged-out timeline (gallery-dl's
+// AuthRequired) raises a login-failure alert; the 429 wait before it does not.
+
+type ServicesBody = {
+ alerts: { service: string; state: string; kind: string; headline: string }[];
+ x?: { source: string; ageMinutes: number | null; maxAgeMinutes: number; fresh: boolean; summary: string };
+ timer?: { intervalMinutes: number; armed: boolean };
+};
+
+async function services(request: APIRequestContext): Promise<ServicesBody> {
+ return (await (await request.get(`${baseUrl}/api/ops/services`, { headers: AUTH })).json()) as ServicesBody;
+}
+
+test("X: a fetch refused for an old jar raises the X banner with the jar's age; Recheck re-reads it; a refreshed jar is OK again", async ({
+ page,
+ request,
+}, testInfo) => {
+ test.setTimeout(120_000);
+ await writeSettings({ minFreeDiskGB: 0, social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 60 } } });
+ await xChannel("x-other", "faketester");
+
+ // No alert yet: get services still says how fresh X's jar is.
+ await xJar(5 * 60_000);
+ const before = await services(request);
+ expect(before.alerts).toEqual([]);
+ expect(before.x).toMatchObject({ source: "profile", maxAgeMinutes: 60, fresh: true });
+ // The timer is not armed on the test server; its setting is reported.
+ expect(before.timer).toMatchObject({ intervalMinutes: 180, armed: false });
+
+ await xJar(3 * 60 * 60_000);
+ const refused = await fetchPosts(request, "x-other");
+ expect(refused.status).toBe(400);
+ expect(refused.body.error).toMatch(/^X cookies were last refreshed 3 h ago \(limit 60 min\)/);
+
+ const s = await services(request);
+ expect(s.alerts.map((a) => [a.service, a.state, a.kind])).toEqual([["x", "stale", "jar-age"]]);
+ expect(s.x).toMatchObject({ fresh: false, ageMinutes: 180 });
+
+ await page.goto(`${baseUrl}/`);
+ const banner = page.getByRole("alert", { name: "X cookies" });
+ // Three short lines, no lead paragraph: the age, the one action, the job it refused.
+ await expect(banner.locator("p").first()).toHaveText("X cookies are 3 h old (limit 60 min)");
+ await expect(banner.getByLabel("X cookies action")).toHaveText(
+ "Refresh cookies (or Connect X account) on /settings — then Recheck.",
+ );
+ await expect(banner).toContainText("Refused an X job on x-other.");
+ await expect(banner.locator("code")).toHaveCount(0);
+ await expect(banner).not.toContainText("X cookies were last refreshed");
+ await banner.screenshot({ path: testInfo.outputPath("x-cookie-banner.png") });
+ await page.screenshot({ path: testInfo.outputPath("x-cookie-banner-page.png"), fullPage: false });
+
+ // Recheck on the old jar: stale, and X was asked nothing.
+ await banner.getByRole("button", { name: "Recheck" }).click();
+ await expect(page.getByRole("status", { name: "X cookies result" })).toContainText("Recheck sends X no request", {
+ timeout: 30_000,
+ });
+ await expect(banner).toHaveAttribute("data-state", "stale");
+
+ // The operator refreshes the jar; Recheck: OK again, and the next fetch runs.
+ await xJar(0);
+ await banner.getByRole("button", { name: "Recheck" }).click();
+ await expect(banner).toHaveAttribute("data-state", "ok-again", { timeout: 30_000 });
+ await expect(banner).toContainText("X cookies OK again");
+ expect((await services(request)).x).toMatchObject({ fresh: true });
+ const ok = await fetchPosts(request, "x-other");
+ expect(ok.body.ok).toBe(true);
+ expect(await waitJob(request, ok.body.jobId!)).toBe("done");
+});
+
+test("X: a logged-out timeline (AuthRequired) fails the fetch and raises a login-failure alert that refuses the next X fetch; the 429 wait before it is not counted", async ({
+ page,
+ request,
+}) => {
+ test.setTimeout(120_000);
+ await writeSettings({ minFreeDiskGB: 0, social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 60 } } });
+ await xChannel("x-logged-out", "logged_out_user");
+ await xChannel("x-other", "faketester");
+ await xJar(60_000);
+
+ const res = await fetchPosts(request, "x-logged-out");
+ expect(res.body.ok).toBe(true);
+ expect(await waitJob(request, res.body.jobId!)).toBe("failed");
+ const log = await readFile(resolvePath(`${testPaths().transcriptsDir}/.jobs/${res.body.jobId}.log`), "utf8");
+ expect(log).toContain("AuthRequired: authenticated cookies needed to access this timeline");
+ expect(log).toMatch(/X answered with a challenge or a login wall \(\[twitter\]\[error\] AuthRequired/);
+
+ const s = await services(request);
+ expect(s.alerts.map((a) => [a.service, a.state, a.kind])).toEqual([["x", "stale", "auth-failure"]]);
+ const next = await fetchPosts(request, "x-other");
+ expect(next.status).toBe(400);
+ expect(next.body.error).toMatch(/^X answered with a login failure at \d\d:\d\d UTC .*no X job starts/);
+
+ await page.goto(`${baseUrl}/`);
+ const banner = page.getByRole("alert", { name: "X cookies" });
+ await expect(banner).toContainText("X needs fresh cookies: pass X's check by hand");
+ await expect(banner).toContainText("1 login failure since");
+});
diff --git a/editor/e2e/fixtures/bin/fake-gallery-dl.mjs b/editor/e2e/fixtures/bin/fake-gallery-dl.mjs
@@ -38,6 +38,16 @@ if (handle === "challenged_user") {
process.exit(0);
}
+// A LOGGED-OUT TIMELINE: what gallery-dl 1.32 prints when X answers the
+// timeline without a login (extractor/twitter.py raises AuthRequired; the job
+// exits 16) — for the account `logged_out_user` (cookie-alerts.spec). Before
+// that line follows a rate-limit wait, which is pacing and must not count.
+if (handle === "logged_out_user") {
+ process.stderr.write("[twitter][info] Waiting for 1 seconds until 03:12:44 (429 Too Many Requests)\n");
+ process.stderr.write("[twitter][error] AuthRequired: authenticated cookies needed to access this timeline\n");
+ process.exit(16);
+}
+
// Mirror the real failure the Needs-cookies bucket models: when the fixture is
// asked to simulate an expired session, exit non-zero with an auth-shaped
// message on stderr.
diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts
@@ -244,6 +244,25 @@ export async function register() {
/* a watch that fails to arm must not block server readiness */
}
+ // THE COOKIE RECHECK TIMER (plans/cookie-refresh-alerts.md, "Proactive"):
+ // every settings.serviceCookies.recheckIntervalMinutes (default 3 h, 0 =
+ // off), raised cookie alerts are rechecked, Rumble's clearance is probed
+ // when Rumble has been idle, and X's jar age is re-read from disk — so the
+ // dashboard banner goes up before a sync fails. Below the idle gate: a probe
+ // is a request to a platform. Not on the e2e test server either, whose
+ // specs drive Recheck by hand against fake binaries.
+ // See common/controller/serviceCookieTimer.ts.
+ if (process.env.E2E_TEST_ROUTES !== "1") {
+ try {
+ const { startServiceCookieTimer } = await import(
+ "yt-dlp-transcript-common/controller/serviceCookieTimer"
+ );
+ startServiceCookieTimer({ log: (line) => console.log(line) });
+ } catch {
+ /* a timer that fails to arm must not block server readiness */
+ }
+ }
+
// Start the automatic priority-queue runners — all four lanes — if their
// policies are enabled. Each is a self-managed registry job; this only
// kicks them off and returns. Best-effort — a failure here must not stop the
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -11549,6 +11549,21 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
`recheck-service`, `dismiss-service`, `rerun-service-jobs` (`{service}`). Doctor section "service cookies". The
e2e fake answers `embed403` URLs with the RumbleEmbed 403 until `fake-ytdlp.fresh-cookies` is in its cwd, and
`--skip-download --print id` is its recheck branch (`e2e/cookie-alerts.spec.ts`).
+- **X's banner and the timer (verified 2026-10-31, branch `lane/cookie-alerts-1031`):** kinds `auth-failure`
+ (gallery-dl's login refused) and `jar-age` (the fresh-jar rule's refusal) joined `challenge` for X.
+ `isBlockingAlert` = raised and not jar-age: only a blocking X alert refuses X jobs (`xSessionReport`); jar-age
+ is raised by `guardNetworkJob` on a fresh-jar refusal (`noteXJarStale`; at start the job is recorded) and
+ cleared (`noteXJarFresh`, `clearedBy: clean`) by the next job that passes, the timer or Recheck. A raised
+ jar-age that meets a challenge is ESCALATED in `applyServiceCookieSignal` (its jobs kept); `noteXJarStale` is a
+ no-op on a blocking alert. gallery-dl lines: `common/social/xGalleryDlSignals.ts` (challenge → rate-limit →
+ one-account → auth; auth only on a `[warning]`/`[error]` line except in a failed run's tail). Jar age:
+ `common/social/xJarAge.ts` (`readXJarAge`: profile = cookies.txt mtime + auth_token; browser =
+ `SELECT host, name, lastAccessed, creationTime, originAttributes FROM moz_cookies WHERE name='auth_token'` on a
+ copy of cookies.sqlite + WAL, cached 5 min unless `fresh`). `lastGood.prev` = the previous clean request with a
+ DIFFERENT url (the timer's Rumble confirmation). The timer: `common/controller/serviceCookieTimer.ts`
+ (`settings.serviceCookies`, `startServiceCookieTimer` in instrumentation below the idle gate and not with
+ `E2E_TEST_ROUTES=1`; state on globalThis `archilyzer.serviceCookieTimer`; the next tick is armed only when one
+ ends). `loadCookieAlerts` adds `x` (jar view) and `timer`.
- **`safeRevalidate` also skips `used "revalidatePath …" during render which is unsupported`** (found by this
lane's e2e): a job STARTED at once inside a server action carries that request's store; when the action (or
`retryJobAction`, which revalidates `/jobs`) triggers a re-render of the page in the same request, a revalidation
diff --git a/plans/cookie-refresh-alerts.md b/plans/cookie-refresh-alerts.md
@@ -105,3 +105,35 @@ Decisions (where the plan was refined against the code):
own `safeRevalidate` ("used revalidatePath … during render") after its work was done, and ended `failed` — the
re-run batch did. `editor/app/lib/safeRevalidate.ts` now skips that like a missing store (+ unit test); the cookie
actions do not revalidate at all.
+
+## X's banner and the timer (2026-10-31, branch `lane/cookie-alerts-1031`)
+
+Operator, 23:35: "add banner cookie refresh indicator for X like we have for Rumble and also make Rumble trigger
+on a timer so we can be more proactive."
+
+- **X like Rumble.** X was already a service (plans/pacing-guard.md), but its banner rose only on a challenge;
+ an X job refused for an old jar said so only in its own error. Now the fresh-jar refusal raises X's banner
+ (kind `jar-age`, "press Refresh cookies (or Connect X account) on /settings — with the browser login, open
+ x.com in <browser>"), with the jar's age read from disk under it; it does not itself refuse X jobs, clears when
+ a job passes on a fresh jar, and Recheck re-reads the age (no request). gallery-dl's lines are classified in
+ `social/xGalleryDlSignals.ts`: AuthRequired / AuthenticationError / "Could not authenticate you" / 401 / API 403
+ / a locked account = `auth-failure` (blocking, worded "a login failure"); 429 / rate limit = pacing, never an
+ alert; protected / blocked / suspended / NSFW / a twimg.com media 403 = one account, not the login (before,
+ "authorization" and a bare "403" substring raised the blocking alert for these).
+- **Rumble on a timer.** `controller/serviceCookieTimer.ts`, `settings.serviceCookies` (180 min, 0 off,
+ `probeServices: ["rumble"]`). One tick: X's jar re-read (X jobs queued on an old jar raise jar-age); every
+ raised alert with something to ask rechecked once; each probe service idle for the interval asked once for
+ its last clean video — a Rumble 403 confirmed once on `lastGood.prev` (a different video) ≥ 1 min (jittered)
+ later, two different videos raise it. Skipped while a job is queued or running on `platform:<p>` / `clips:<p>`,
+ while cooling or held, while a recheck runs, or when the service answered cleanly within the interval. Never
+ retried. Not on an idle boot or the e2e test server.
+
+Decisions:
+- jar-age is raised on DEMAND (a refused X job, or X jobs queued), not whenever the jar is past the limit: X
+ work is manual and the jar is refreshed only for a session, so an always-on banner would be up nearly always
+ and learned to be ignored.
+- The browser login's age (Firefox's auth_token `lastAccessed`) is SHOWN (`get services` → `x`, and the timer
+ raises jar-age on it when X jobs are queued), but the fresh-jar rule still does not refuse on it — that rule's
+ scope (profile only) is unchanged.
+- A Rumble probe that 403s on the last clean video makes a SECOND request (the previous, different clean video)
+ rather than raising on one — the two-videos rule stands; that is the most a tick asks of one service.
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -121,6 +121,7 @@
// pnpm ops get services
// pnpm ops get x-session
// pnpm ops recheck-service --json '{"service":"rumble"}'
+// pnpm ops recheck-service --json '{"service":"x"}'
// pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'
// pnpm ops amend-release --json '{"workspace":"editor","release":"0.11.1","version":"minor","commit":true}'
// pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait
@@ -1060,9 +1061,15 @@ export function usage() {
"get workers, get auto-queue and get scheduler are /workers, the four lanes",
" of /operations, and /operations/sync — the payloads those pages poll.",
"get services is the dashboard's cookie refresh alerts: each service",
- " (rumble, youtube, odysee, archive.today, a forum host) whose cookies look",
+ " (rumble, youtube, odysee, archive.today, x, a forum host) whose cookies look",
" stale, or are OK again with the jobs the alert stopped; \"pending\" lists",
- " a first Rumble embed 403 waiting for a second video.",
+ " a first Rumble embed 403 waiting for a second video. X's kinds: challenge,",
+ " auth-failure (a login refused) and jar-age (the cookie jar past",
+ " social.x.maxCookieAgeMinutes while X work waits). \"x\" is X's jar read",
+ " from disk whether or not an alert is up (source, at, ageMinutes,",
+ " maxAgeMinutes, loggedIn, fresh, summary); \"timer\" is the proactive",
+ " recheck timer (settings.serviceCookies: intervalMinutes, armed,",
+ " lastTickAt, nextTickAt, last: what its last tick did per service).",
"get x-session [<slug>] is the X login an X job would use and whether one",
" would start NOW, from the same check that refuses a stale-cookie X job:",
" source (\"profile\": the exported jar under transcripts/.x-session;",
@@ -1174,7 +1181,12 @@ export function usage() {
' Waits for it: {jobId, result: "clean" | "stale" | "failed", message};',
" \"clean\" clears the alert (and a yt-dlp service's backoff, as any clean",
' request). For "x" it sends X NO request: clean when the login on disk',
- ' was renewed after the alert (Refresh cookies on /settings).',
+ ' was renewed after the alert (Refresh cookies on /settings) — for a',
+ ' jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The',
+ ' editor also rechecks by itself on a timer',
+ ' (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off;',
+ ' `pnpm ops settings',
+ ' --json \'{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}\'`).',
'dismiss-service clears a service\'s cookie alert by hand: {"service"}.',
'rerun-service-jobs retries every job a service\'s cookie alert stopped, once',
' it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them.',
diff --git a/settings.json.example b/settings.json.example
@@ -342,5 +342,11 @@
},
"jobs": {
"resumeInterruptedOnBoot": true
+ },
+ "serviceCookies": {
+ "recheckIntervalMinutes": 180,
+ "probeServices": [
+ "rumble"
+ ]
}
}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -73,6 +73,7 @@
// | ls <project> | relabel <project> <take> <label> | supersede <project> <take> [--by T] [--clear]
// | delete <project> <take> [--dry-run] [--force] take housekeeping
// umtool render-mode on [--for 90m] [--note T] | off [--force] | status [--json] render mode: a render gets the machine
+// umtool render-mode on [--for 90m] [--print-token] -- <cmd …> held while <cmd> runs (its env carries the token)
// umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3]
// [--out NAME] [--dry-run] [--json] a trailer cut from the take's finished master
// umtool trailer-beats <project> [ls | add <clip> [<from>-<to>] | set <n> <from>-<to> | remove <n> | move <n> --to <m>
@@ -874,6 +875,9 @@ function usage() {
" umtool render-mode on [--for 90m] [--note T] | off [--force] | status [--json] render mode: a render the",
" operator waits for gets the machine (other heavy jobs wait; the editor's transcription and",
" download lanes held); `on` is a window for a chain of renders (default 2h)",
+ " on [--for D] [--print-token] -- <cmd …>: held while <cmd> runs (its env carries the token,",
+ " the hold is its pid), released when it exits -- the form for a script; --print-token prints",
+ " the token alone on stdout",
" umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] [--out NAME]",
" a trailer cut from the take's finished master: the master's own frames, so the deck shows the",
" whole timeline; beats are clip source seconds or master seconds ([--dry-run] the mapping only)",
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -52,7 +52,7 @@ Inbox cannot disagree about what is wrong with one.
| `notes …` | operator notes: list, read, reply, resolve ([notes.md](notes.md)) |
| `take <project> --id <id> --label L [--group G] [--kind similar\|different] [--summary S] [--style NAME] [--patch FILE \| --patch-json JSON \| --set path=value …] [--effect NAME] [--at S --dur S \| --full] [--quick] [--force] [--progress ndjson]` | one **take**: the manifest with a montage style's patch, then an overlay effect's (`--effect`, release 35), then the take's own, rendered into `takes/<id>/` (the Takes page's New take); `--id <id> --rebuild` makes one again from its own `take.json` ([report-video.md](report-video.md#making-takes)) |
| `take <project> --id <id> --label L [--patch F \| …] --draft` (`--no-render`) · `take <project> --id <id> [--full \| --at S --dur S]` · `take <project> --id <id> --rebuild [--full \| --at S --dur S]` · `take <project> --id <id> --promote [--anyway] [--json]` | a **draft** take: recorded with nothing rendered, to be walked first; a draft named with no patch flags is rendered from its stored (walked) patch, and `--rebuild` takes a window flag; **make it the cut**: the take's patch applied to the manifest now, one undo point (`revisions/…-auto-before-promote-take`), refused (exit 1) when its timeline would replace a cut that changed since, until `--anyway` ([report-video.md](report-video.md#walking-a-take-drafts-edits-into-the-take-and-making-it-the-cut)) |
-| `take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json]` · `render-mode off [--force] [--json]` · `render-mode status [--json]` | **render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription and download lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints. `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, "Render mode") |
+| `take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json \| --print-token]` · `render-mode on [--for 90m] [--note T] [--print-token] -- <cmd …>` · `render-mode off [--force] [--json]` · `render-mode status [--json]` | **render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription and download lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints (`--print-token`: the token alone on stdout, the rest on stderr). **`on … -- <cmd …>` is the form for a script**: the command is spawned with the token in its environment, the hold is the command's pid, and it is released when the command exits — done, failed, or umtool signalled (the signal is passed on); umtool exits with the command's code, and inside a manual window the command joins it. A bare `on` in a script leaves the window behind (the chain trap). `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, "Render mode") |
| `takes make <project> [--recipe FILE] [--only ID,ID] [--force]` · `takes make <project> --all-styles [--group G] [--at S --dur S \| --full]` | a recipe's takes, one at a time (default `takes/recipe.json`); every montage style, one take each (Make all styles); **exit 1** if any failed |
| `takes styles [--json]` · `takes effects <project> [--json]` · `takes pick <project> <take> [--anyway] [--json]` | the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway` |
| `takes ls <project> [--json]` · `takes relabel <project> <take> <label…>` · `takes supersede <project> <take> [--by <take>]` · `takes supersede <project> <take> --clear` · `takes delete <project> <take> [--dry-run] [--force]` | **take housekeeping** (the Takes page's ✎, **Mark superseded**, **Delete take**): the takes with picked / superseded / RENDERING; a label fixed in `take.json` (an undo point of the take's own); a take folded away as superseded (verdicts.json, nothing deleted); a take deleted. Relabel and delete are refused (**exit 1**) while the take renders or a live render is made from it ([knobs.md](knobs.md#takes-relabel-supersede-delete)) |
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -190,6 +190,15 @@ them; a mute mark or claim mark inside one is refused. `umtool check` reports a
bench (a span dragged on its waveform), `umtool window --gap/--gap-remove/--gaps` and `umtool set gap.add=…`; the
whole of it is in [knobs.md, "Gaps inside a clip"](knobs.md#gaps-inside-a-clip).
+**A gap-joined clip is fetched and cut per piece.** `umtool fetch` asks for each kept piece on its own, padded at its
+own edges by `render.fetchPad` (pieces under a minute apart as one span), so a clip joining two moments of a stream —
+`start` 5385, `end` 21812, one gap between — asks for its two moments, never the 4½ hours between. The build has each
+piece (on disk, else fetched: that span only), joins the pieces end to end into `segments/<id>.pieces.mp4` (one input
+per piece, the first piece's size, the render's fps) and cuts the segment from it; the cut record stays in the
+recording's seconds, the seconds between pieces a gap. A window on disk holding the whole extent is still cut from as
+before. Room (`render.room`) is not applied to a clip cut from its pieces. The bench and the project page's cache pill
+still look for one window holding the clip's extent.
+
The matcher is deliberately loose, because a quote is prose a human wrote about
speech a machine transcribed: case and punctuation are dropped, `[bracketed]`
editorial words and `[Speaker]` markers are dropped, and an **ellipsis splits
@@ -1127,6 +1136,7 @@ can ask for the machine:
```sh
umtool take <project> --id <take> … --priority # this take's lifetime
umtool render-mode on --for 90m --note "the Ember cut" # a window for a chain of renders
+umtool render-mode on -- sh render-all.sh # a script's chain: held while it runs, off when it exits
umtool render-mode status
umtool render-mode off
```
diff --git a/umtool/e2e/live-preview.spec.ts b/umtool/e2e/live-preview.spec.ts
@@ -98,17 +98,22 @@ test("the live preview: the deck over the clip, the tally and the stamp at the p
await expect(page.getByTestId("live-stamp")).toHaveAttribute("data-feed-ready", "1", { timeout: 15_000 });
await expect.poll(() => opacityIn(frameOf(page, /stamp-preview/), '.stamp[data-claim="k1"]')).toBeGreaterThan(0.9);
await expect.poll(() => opacityIn(frameOf(page, /\/sourced\/index\.html/), '[data-k="ty.CONTRADICTED.n1"]')).toBeGreaterThan(0.9);
- expect(await opacityIn(frameOf(page, /\/sourced\/index\.html/), '[data-k="ty.CONTRADICTED.n0"]')).toBeLessThan(0.1);
+ // The outgoing 0 rolls out (power2.in) over STAMP_MOTION.roll, 0.4 s from 5.0: at 5.4 the playhead
+ // may sit on the roll's last frames (it read ~0.2 there), so it is judged a tenth on.
+ await nudgePlayer(page, 0.1);
+ await expect.poll(() => opacityIn(frameOf(page, /\/sourced\/index\.html/), '[data-k="ty.CONTRADICTED.n0"]')).toBeLessThan(0.1);
- // 0.8 s more (source 6.2): the clip's second mark, its own stamp and step.
- await nudgePlayer(page, 0.8);
+ // 0.7 s more (source 6.2): the clip's second mark, its own stamp and step (its stamp is out by 6.3).
+ await nudgePlayer(page, 0.7);
await expect(page.locator("[data-live-stamp]")).toHaveAttribute("data-live-stamp", "k1b:on");
await expect(page.locator("[data-live-tally]")).toHaveAttribute("data-live-tally", "CORROBORATED:1,CONTRADICTED:1");
await expect.poll(() => opacityIn(frameOf(page, /stamp-preview/), '.stamp[data-claim="k1b"]')).toBeGreaterThan(0.9);
+ // Its 1 rolls in over 0.4 s from 6.0 (it read 0.88 at 6.2): judged once the roll is over.
+ await nudgePlayer(page, 0.2);
await expect.poll(() => opacityIn(frameOf(page, /\/sourced\/index\.html/), '[data-k="ty.CORROBORATED.n1"]')).toBeGreaterThan(0.9);
- // Back before both (source 4.6): no stamp, nothing counted -- the pages are seeked back too.
- await nudgePlayer(page, -1.6);
+ // Back before both (source 4.7): no stamp, nothing counted -- the pages are seeked back too.
+ await nudgePlayer(page, -1.7);
await expect(page.locator("[data-live-stamp]")).toHaveAttribute("data-live-stamp", "");
await expect(page.locator("[data-live-tally]")).toHaveAttribute("data-live-tally", "CORROBORATED:0,CONTRADICTED:0");
await expect.poll(() => opacityIn(frameOf(page, /stamp-preview/), '.stamp[data-claim="k1"]')).toBeLessThan(0.1);
diff --git a/umtool/e2e/onscreen.spec.ts b/umtool/e2e/onscreen.spec.ts
@@ -422,6 +422,16 @@ const readSchedule = () =>
// A build prunes the deck's frames after the final mux and records how many
// there were (report-to-video/prune-frames.mjs): the sequence must be gone,
// and its count is read from the record.
+/**
+ * Whether a renderer call wrote a layer's frames: to `<stem>-frames`, or -- a
+ * first render, which captures each distinct frame once and links every frame
+ * of the layer to it (compose-chrome.mjs reuseFrames, 61e53aea) -- to
+ * `work-capture-<stem>-frames` beside it.
+ */
+const rendersLayer = (argv: string, stem: string) =>
+ [FRAMES.replace(/deck-frames$/, `${stem}-frames`), FRAMES.replace(/deck-frames$/, `work-capture-${stem}-frames`)].some(
+ (dir) => argv.includes(`--output ${dir} `) || argv.endsWith(`--output ${dir}`),
+ );
const prunedFrames = (name = "deck-frames") => {
expect(existsSync(path.join(VARIANT_OUT, "chrome", name)), `${name} pruned after the mux`).toBe(false);
const rec = JSON.parse(readFileSync(path.join(VARIANT_OUT, "chrome", "pruned.json"), "utf8")) as {
@@ -470,7 +480,7 @@ test("re-render on-screen runs --chrome-only over a built cut, to done, rebuildi
expect(argv).toContain("render --format png-sequence");
expect(argv).toContain("--fps 15");
expect(argv).toContain("--no-browser-gpu");
- expect(argv).toContain(`--output ${FRAMES}`);
+ expect(rendersLayer(argv, "deck"), argv).toBe(true);
expect(built.events.filter((e) => e.ev === "chrome").map((e) => e.phase)).toEqual(
expect.arrayContaining(["schedule", "compose", "render", "overlay"]),
);
diff --git a/umtool/e2e/stats-overlay.spec.ts b/umtool/e2e/stats-overlay.spec.ts
@@ -70,7 +70,9 @@ test("a deck build lays the stats region over each clip, and verify-build holds
expect(chrome.some((e) => e.phase === "compose" && e.region === "stats")).toBe(true);
expect(chrome.some((e) => e.phase === "render" && e.region === "stats")).toBe(true);
const renders = readFileSync(INVOCATIONS, "utf8").split("\n").filter((l) => l.includes("stats-build-fixture"));
- expect(renders.some((l) => l.includes(path.join(VARIANT_OUT, "chrome", "stats-frames")))).toBe(true);
+ // A first render captures each distinct frame once into work-capture-stats-frames (compose-chrome.mjs reuseFrames).
+ const chromeDir = path.join(VARIANT_OUT, "chrome");
+ expect(renders.some((l) => l.includes(`${chromeDir}/stats-frames`) || l.includes(`${chromeDir}/work-capture-stats-frames`))).toBe(true);
// The schedule draws both clips, each number held from the scan's point.
const schedule = JSON.parse(readFileSync(path.join(VARIANT_OUT, "schedule.json"), "utf8")) as {
diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs
@@ -20,6 +20,7 @@ import { resolveVideoDirSync } from "yt-dlp-transcript-common/lib/videoDir-serve
import { deliverablesState, finishCommand, outDirState, leftoversOf } from "../report/storage.mjs";
import { CHANNELS_DIR, inside, resolveInRoots } from "../paths.mjs";
import { channelName, cleanTitle } from "umtool-report-to-video/attribution";
+import { archiveMomentUrl } from "umtool-report-to-video/site-links";
import { deckOn, resolveDeck, teaserTitle } from "umtool-report-to-video/deck";
import { originQrsOf } from "umtool-report-to-video/lint";
import { DRAFTS_REVIEW_FILE, NARRATION_REVIEW_FILE } from "umtool-report-to-video/drafts-review";
@@ -200,7 +201,7 @@ export const channelFor = (m, e) => e.channel ?? m?.provenance?.channelSlug ?? n
* is not the id the site serves), else the viewer moment URL is derived.
*/
export const derivedCiteUrl = (m, e) =>
- `${m?.provenance?.siteOrigin ?? ""}/?v=${encodeURIComponent(`${channelFor(m, e)}/${e.video}`)}&t=${Math.floor(e.start ?? 0)}`;
+ archiveMomentUrl({ ...e, channel: channelFor(m, e) }, m?.provenance, e.start ?? 0, { origin: m?.provenance?.siteOrigin ?? "" });
export const citeUrlFor = (m, e) => e.citeUrl ?? derivedCiteUrl(m, e);
/**
diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs
@@ -8,7 +8,10 @@
//
// `from`/`to` are the build's own fetch span (build-video.mjs `fetchSpan`:
// start − render.fetchPad … end + render.fetchPad, two decimals) — for a phrase
-// seed (fetchPad 0) exactly the clip's start and end. `pad` is provenance (the
+// seed (fetchPad 0) exactly the clip's start and end. A clip with gaps is
+// asked for PER KEPT PIECE (gaps.mjs fetchPieces, the build's `fetchSpans`):
+// each piece padded at its own edges, pieces under a minute apart as one —
+// a gap-joined clip over 5385–21812 asks for its two moments, not 4½ hours. `pad` is provenance (the
// seconds each side that are margin): the fetchPad, else 3. `reason` is
// "<title> montage" for a montage (clips carrying `montage`), else the title.
// A montage clip the rulings leave out (cut / not-him / read-aloud) is not
@@ -35,6 +38,7 @@ import { createHash } from "node:crypto";
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import path from "node:path";
import { LEFT_OUT_VERDICTS, clipMomentKey, readMontageRulings } from "umtool-report-to-video/montage-rulings";
+import { fetchPieces, renderGaps } from "umtool-report-to-video/gaps";
import { agentToken } from "../annotations/agentAuth.mjs";
export const FETCH_RUNS_FILE = "fetch-runs.json";
@@ -87,15 +91,19 @@ export function fetchWindowsBody(manifest, { manifestPath, project, rulings = nu
skipped.push({ clipId: String(e.id), why: `ruled ${ruling.verdict}` });
continue;
}
- items.push({
- slug,
- id: e.video,
- from: r2(Math.max(0, Number(e.start) - margin)),
- to: r2(Number(e.end) + margin),
- clipId: e.id,
- pad: padOf,
- reason: why.slice(0, REASON_LIMIT),
- });
+ // One item per kept piece (gaps.mjs fetchPieces, the build's fetchSpans):
+ // a gap-joined clip asks for its moments, never the hours between them.
+ for (const span of fetchPieces(Number(e.start), Number(e.end), renderGaps(e, manifest?.render ?? {}), { before: margin, after: margin })) {
+ items.push({
+ slug,
+ id: e.video,
+ from: r2(span.from),
+ to: r2(span.to),
+ clipId: e.id,
+ pad: padOf,
+ reason: why.slice(0, REASON_LIMIT),
+ });
+ }
}
return {
body: { requestedBy: `umtool:${project}`, manifest: path.resolve(manifestPath), storedUrl: "fallback", items },
@@ -122,14 +130,15 @@ export function refetchEvictions(body, skipped, { clipIds = [], videos = [] }) {
const add = (it) => {
const key = `${it.slug}/${it.id}`;
const req = byVideo.get(key) ?? { slug: it.slug, id: it.id, covering: [], clipIds: [] };
- if (req.clipIds.includes(it.clipId)) return;
+ // A clip fetched in pieces is one clip with several spans.
+ if (req.covering.some((c) => c.from === it.from && c.to === it.to)) return;
req.covering.push({ from: it.from, to: it.to });
- req.clipIds.push(it.clipId);
+ if (!req.clipIds.includes(it.clipId)) req.clipIds.push(it.clipId);
byVideo.set(key, req);
};
for (const clipId of clipIds) {
- const it = items.find((i) => i.clipId === clipId);
- if (!it) {
+ const its = items.filter((i) => i.clipId === clipId);
+ if (!its.length) {
const left = skipped.find((s) => s.clipId === clipId);
return {
ok: false,
@@ -138,7 +147,7 @@ export function refetchEvictions(body, skipped, { clipIds = [], videos = [] }) {
: `no clip "${clipId}" in the manifest's timeline`,
};
}
- add(it);
+ for (const it of its) add(it);
}
for (const v of videos) {
const at = String(v).indexOf("/");
diff --git a/umtool/lib/report/fetchWindows.test.mjs b/umtool/lib/report/fetchWindows.test.mjs
@@ -273,3 +273,29 @@ test("umtool fetch --refetch: evict-clips {slug, id, covering} first, waited for
await rm(root, { recursive: true, force: true });
}
});
+
+test("a gap-joined clip is fetched per kept piece, each padded at its own edges -- never the hours between", () => {
+ // Two moments of one stream joined by a gap: 5385–5400 and 21800–21812.
+ const joined = { type: "clip", id: "j01", channel: "synth-tw", video: "2468013579", start: 5385, end: 21812, gaps: [{ from: 5400, to: 21800 }] };
+ const short = { type: "clip", id: "j02", channel: "synth-tw", video: "2468013579", start: 100, end: 130, gaps: [{ from: 110, to: 112.5 }] };
+ const m = { title: "Pieces", render: { fetchPad: 3, transition: 0 }, timeline: [joined, short] };
+ const { body } = fetchWindowsBody(m, { manifestPath: "/r/p/video.manifest.json", project: "p" });
+ assert.deepEqual(
+ body.items.map((i) => [i.clipId, i.from, i.to]),
+ [
+ ["j01", 5382, 5403],
+ ["j01", 21797, 21815],
+ // A short gap: one span, the padded extent, as before.
+ ["j02", 97, 133],
+ ],
+ );
+ const asked = body.items.filter((i) => i.clipId === "j01").reduce((s, i) => s + (i.to - i.from), 0);
+ assert.ok(asked < 60, `the joined clip asks for ${asked}s, not ${21815 - 5382}s`);
+ // A refetch of the clip evicts both of its pieces.
+ const r = refetchEvictions(body, [], { clipIds: ["j01"] });
+ assert.ok(r.ok);
+ assert.deepEqual(r.requests, [{ slug: "synth-tw", id: "2468013579", covering: [{ from: 5382, to: 5403 }, { from: 21797, to: 21815 }], clipIds: ["j01"] }]);
+ // A montage cuts every clip to its phrase, so applies no gaps: the whole extent.
+ const montage = fetchWindowsBody({ ...m, render: { ...m.render, montage: {} }, timeline: [joined] }, { manifestPath: "/r/p/video.manifest.json", project: "p" });
+ assert.deepEqual(montage.body.items.map((i) => [i.from, i.to]), [[5382, 21815]]);
+});
diff --git a/umtool/lib/report/moments.mjs b/umtool/lib/report/moments.mjs
@@ -23,6 +23,7 @@ import { readdir, readFile, stat } from "node:fs/promises";
import path from "node:path";
import { DEFAULT_VARIANT } from "umtool-report-to-video/build-video";
import { channelFor } from "../projects/report.mjs";
+import { archiveMomentUrl } from "umtool-report-to-video/site-links";
const TAKE_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
const APPROX_TOLERANCE = 0.25;
@@ -132,7 +133,7 @@ export function resolveMoment({ schedule, manifest, variant = null, t, duration
out.video = String(e.video);
const origin = manifest?.provenance?.siteOrigin;
if (origin && channel) {
- out.url = `${origin}/?v=${encodeURIComponent(`${channel}/${e.video}`)}&t=${Math.floor(out.sourceT)}`;
+ out.url = archiveMomentUrl({ ...e, channel }, manifest?.provenance, out.sourceT, { origin });
}
}
}
diff --git a/umtool/lib/report/renderMode.mjs b/umtool/lib/report/renderMode.mjs
@@ -4,7 +4,9 @@
// umtool take <p> --id <t> … --priority on for the take's lifetime: on at
// the start, off at the end, on a
// failure and on a signal
-// umtool render-mode on [--for 90m] [--note …] [--json] a window (a chain of renders)
+// umtool render-mode on [--for 90m] [--note …] [--json | --print-token] a window (a chain of renders)
+// umtool render-mode on [--for 90m] [--note …] -- <cmd …> held while the command runs (holder: its
+// pid; its env carries the token), off when it exits
// umtool render-mode off [--force] [--json]
// umtool render-mode status [--json]
//
@@ -90,55 +92,37 @@ export function lanesLine(state) {
}
/**
- * Run `fn` (a take's make) in render mode, as `umtool take … --priority` asks.
- *
- * --priority, render mode off on for this process (holder: its pid), off
- * after `fn` — done, failed or signalled
- * a manual window on joined: the render carries its token; the
- * window stays on afterwards (with or without --priority)
- * --priority, another render run as is; its render waits at the door
- *
- * The token goes into process.env, so the render queue-lock starts inherits it.
+ * Hold render mode while `fn` runs, then let go — done, failed or signalled.
+ * The one on/off/signal path of `withTakePriority` (holder: this process) and
+ * `render-mode on -- <cmd>` (holder: the command's pid). Returns
+ * `{ran: false, held}` without calling `fn` when another hold won the claim.
*
* @template T
- * @param {{ priority: boolean, project: string, take?: string | null, cmd?: string, log: (s: string) => void,
- * env?: Record<string, string | undefined>, file?: string, lanes?: any, signals?: boolean }} o
- * @param {() => Promise<T>} fn
- * @returns {Promise<T>}
+ * @param {{ holder: import("yt-dlp-transcript-common/lib/renderPriority.mjs").RenderHolder, by: string,
+ * log: (s: string) => void, env?: Record<string, string | undefined>, file?: string, lanes?: any,
+ * signals?: boolean, token?: string, forMs?: number | null, note?: string | null,
+ * onLine?: (state: any) => void, onSignal?: (sig: NodeJS.Signals) => void }} o
+ * @param {(token: string) => Promise<T>} fn
+ * @returns {Promise<{ ran: true, value: T } | { ran: false, held: any }>}
*/
-export async function withTakePriority(o, fn) {
+export async function withRenderHold(o, fn) {
const env = o.env ?? process.env;
const file = o.file ?? renderModeFile(env);
- const status = readRenderPriority(file);
- if (status.held && status.state) {
- if (!status.state.holder) {
- env[RENDER_PRIORITY_TOKEN_ENV] = status.state.token;
- o.log(`render mode is on (${describeRenderPriority(status.state)}) — this take renders in it`);
- return fn();
- }
- if (o.priority) o.log(`render mode is held by another render (${describeRenderPriority(status.state)}) — this one waits for it`);
- return fn();
- }
- if (!o.priority) return fn();
-
const lanes = o.lanes !== undefined ? o.lanes : editorLanes(editorConfig(env));
- const cmd = o.cmd ?? `umtool take ${o.project}${o.take ? ` --id ${o.take}` : ""}`;
const on = await renderModeOn({
file,
- holder: { pid: process.pid, cmd, project: o.project, take: o.take ?? null },
- by: "umtool take --priority",
+ holder: o.holder,
+ by: o.by,
+ forMs: o.forMs ?? null,
+ note: o.note ?? null,
editor: lanes ? editorConfig(env).url : null,
lanes,
+ ...(o.token ? { token: o.token } : {}),
});
- if (!on.ok || !on.state) {
- // Another hold went on between the look and the claim: render as any job.
- o.log(`render mode is held by another render${on.held ? ` (${describeRenderPriority(on.held)})` : ""} — this one waits for it`);
- return fn();
- }
+ if (!on.ok || !on.state) return { ran: false, held: on.held ?? null };
const token = on.state.token;
env[RENDER_PRIORITY_TOKEN_ENV] = token;
- o.log(`render mode on for this take — ${lanesLine(on.state)}`);
- o.log(` ${RENDER_MODE_REMINDER}`);
+ o.onLine?.(on.state);
let ended = false;
const end = async () => {
@@ -163,6 +147,11 @@ export async function withTakePriority(o, fn) {
for (const sig of /** @type {NodeJS.Signals[]} */ (["SIGINT", "SIGTERM", "SIGHUP"])) {
const h = () => {
const code = 128 + ({ SIGINT: 2, SIGTERM: 15, SIGHUP: 1 }[sig] ?? 0);
+ try {
+ o.onSignal?.(sig);
+ } catch {
+ /* the child is gone already */
+ }
setTimeout(() => process.exit(code), 10_000).unref();
void end().finally(() => process.exit(code));
};
@@ -171,15 +160,167 @@ export async function withTakePriority(o, fn) {
}
}
try {
- return await fn();
+ return { ran: true, value: await fn(token) };
} finally {
for (const [sig, h] of handlers) process.off(sig, h);
await end();
}
}
+/**
+ * Run `fn` (a take's make) in render mode, as `umtool take … --priority` asks.
+ *
+ * --priority, render mode off on for this process (holder: its pid), off
+ * after `fn` — done, failed or signalled
+ * a manual window on joined: the render carries its token; the
+ * window stays on afterwards (with or without --priority)
+ * inside `render-mode on -- …` the chain's hold: this take carries its token already
+ * --priority, another render run as is; its render waits at the door
+ *
+ * The token goes into process.env, so the render queue-lock starts inherits it.
+ *
+ * @template T
+ * @param {{ priority: boolean, project: string, take?: string | null, cmd?: string, log: (s: string) => void,
+ * env?: Record<string, string | undefined>, file?: string, lanes?: any, signals?: boolean }} o
+ * @param {() => Promise<T>} fn
+ * @returns {Promise<T>}
+ */
+export async function withTakePriority(o, fn) {
+ const env = o.env ?? process.env;
+ const file = o.file ?? renderModeFile(env);
+ const status = readRenderPriority(file);
+ if (status.held && status.state) {
+ if (!status.state.holder) {
+ env[RENDER_PRIORITY_TOKEN_ENV] = status.state.token;
+ o.log(`render mode is on (${describeRenderPriority(status.state)}) — this take renders in it`);
+ return fn();
+ }
+ if (env[RENDER_PRIORITY_TOKEN_ENV] === status.state.token) {
+ o.log(`render mode is on (${describeRenderPriority(status.state)}) — this take is part of it`);
+ return fn();
+ }
+ if (o.priority) o.log(`render mode is held by another render (${describeRenderPriority(status.state)}) — this one waits for it`);
+ return fn();
+ }
+ if (!o.priority) return fn();
+
+ const cmd = o.cmd ?? `umtool take ${o.project}${o.take ? ` --id ${o.take}` : ""}`;
+ const r = await withRenderHold(
+ {
+ holder: { pid: process.pid, cmd, project: o.project, take: o.take ?? null },
+ by: "umtool take --priority",
+ log: o.log,
+ env,
+ file,
+ lanes: o.lanes,
+ signals: o.signals,
+ onLine: (state) => {
+ o.log(`render mode on for this take — ${lanesLine(state)}`);
+ o.log(` ${RENDER_MODE_REMINDER}`);
+ },
+ },
+ () => fn(),
+ );
+ if (r.ran) return r.value;
+ // Another hold went on between the look and the claim: render as any job.
+ o.log(`render mode is held by another render${r.held ? ` (${describeRenderPriority(r.held)})` : ""} — this one waits for it`);
+ return fn();
+}
+
+/** Quote one argv word for a log line, as a shell would read it. */
+function shellWord(w) {
+ return /^[\w@%+=:,./-]+$/.test(w) ? w : `'${String(w).replace(/'/g, "'\\''")}'`;
+}
+
+/**
+ * `umtool render-mode on [--for D] [--note T] -- <cmd…>`: the command runs in
+ * render mode and the hold ends when it does. The command is spawned with the
+ * hold's token in RENDER_PRIORITY_TOKEN (so every heavy job under it is the
+ * render), the hold's holder is the command's pid (a crash of this process
+ * leaves a hold that ends with the command), and the hold is released when the
+ * command exits — done, failed, or this process signalled (the signal is
+ * passed on to the command). Exits with the command's code.
+ *
+ * Inside a manual window it joins (the window's token; the window stays on);
+ * beside another render's hold it runs as any job and its heavy work waits.
+ *
+ * @param {string[]} cmd
+ * @param {{ forMs: number | null, note: string | null, printToken: boolean, log: (s: string) => void,
+ * err: (s: string) => void, env: Record<string, string | undefined>, file: string, lanes: any,
+ * signals?: boolean, spawnImpl?: typeof import("node:child_process").spawn }} o
+ * @returns {Promise<number>}
+ */
+async function renderModeChain(cmd, o) {
+ const { spawn } = await import("node:child_process");
+ const { randomBytes } = await import("node:crypto");
+ const spawnImpl = o.spawnImpl ?? spawn;
+ const say = o.printToken ? o.err : o.log; // --print-token: stdout carries the token alone
+ const full = cmd.map(shellWord).join(" ");
+ const line = full.length > 160 ? `${full.slice(0, 159)}…` : full;
+ /** @param {string | undefined} token */
+ const run = (token) => {
+ const childEnv = { ...o.env };
+ if (token) childEnv[RENDER_PRIORITY_TOKEN_ENV] = token;
+ else delete childEnv[RENDER_PRIORITY_TOKEN_ENV];
+ const child = spawnImpl(cmd[0], cmd.slice(1), { stdio: "inherit", env: /** @type {NodeJS.ProcessEnv} */ (childEnv) });
+ const exited = new Promise((resolve) => {
+ child.on("error", (e) => {
+ o.err(`render-mode: could not run ${cmd[0]}: ${e.message}`);
+ resolve(127);
+ });
+ child.on("exit", (code, sig) => resolve(code ?? 128 + (sig ? ({ SIGINT: 2, SIGTERM: 15, SIGHUP: 1, SIGKILL: 9 }[sig] ?? 1) : 1)));
+ });
+ return { child, exited: /** @type {Promise<number>} */ (exited) };
+ };
+
+ const status = readRenderPriority(o.file);
+ if (status.held && status.state) {
+ const joins = !status.state.holder;
+ say(
+ joins
+ ? `render mode is on (${describeRenderPriority(status.state)}) — ${line} runs in it; the window stays on`
+ : `render mode is held by another render (${describeRenderPriority(status.state)}) — ${line} runs without it; its heavy work waits`,
+ );
+ if (o.printToken && joins) o.log(status.state.token);
+ return run(joins ? status.state.token : undefined).exited;
+ }
+
+ // The token is chosen before the spawn so the command carries it from its
+ // first instruction; the hold is claimed with the command's pid as holder.
+ const token = randomBytes(8).toString("hex");
+ if (o.printToken) o.log(token);
+ const { child, exited } = run(token);
+ if (child.pid == null) return exited; // never started ("error" says why)
+ const r = await withRenderHold(
+ {
+ holder: { pid: child.pid, cmd: full.slice(0, 200) },
+ by: "umtool render-mode on --",
+ token,
+ forMs: o.forMs,
+ note: o.note,
+ log: say,
+ env: { ...o.env },
+ file: o.file,
+ lanes: o.lanes,
+ signals: o.signals,
+ onLine: (state) => {
+ say(`render mode ON for ${line} (pid ${child.pid}) — ${lanesLine(state)}`);
+ say(` ${RENDER_MODE_REMINDER}`);
+ },
+ onSignal: (sig) => {
+ child.kill(sig);
+ },
+ },
+ () => exited,
+ );
+ if (r.ran) return r.value;
+ say(`render mode was taken by another render meanwhile${r.held ? ` (${describeRenderPriority(r.held)})` : ""} — ${line} runs without it; its heavy work waits`);
+ return exited;
+}
+
const USAGE = [
- "usage: umtool render-mode on [--for 90m] [--note TEXT] [--json]",
+ "usage: umtool render-mode on [--for 90m] [--note TEXT] [--json | --print-token]",
+ " umtool render-mode on [--for 90m] [--note TEXT] [--print-token] -- <command …>",
" umtool render-mode off [--force] [--json]",
" umtool render-mode status [--json]",
"",
@@ -192,16 +333,27 @@ const USAGE = [
"--priority` turns it on for the take's lifetime instead. `off` ends it (a running take's hold",
"only with --force). A hold whose process is gone or whose window is over is no hold: its lanes",
"are released by the editor's heartbeat, /jobs, or the next `status`/`on`.",
+ "",
+ "`on -- <command …>` is the form for a script: the command runs in render mode with the token in",
+ "its environment, the hold is the command's (its pid), and it ends when the command exits — done,",
+ "failed or signalled (a signal is passed on); the exit code is the command's. No window is left",
+ "behind for a script that forgot `off`. --print-token prints the token alone on stdout (the other",
+ "lines go to stderr), for `export RENDER_PRIORITY_TOKEN=$(umtool render-mode on --print-token)`.",
"The same from the editor: pnpm ops render-mode --json '{\"on\": true, \"for\": \"90m\"}' / get render-mode.",
].join("\n");
/**
- * `umtool render-mode on|off|status`.
+ * `umtool render-mode on|off|status`, and `on -- <command …>`.
* @param {string[]} args
- * @param {{ log?: (s: string) => void, err?: (s: string) => void, env?: Record<string, string | undefined>, file?: string, lanes?: any }} [opts]
+ * @param {{ log?: (s: string) => void, err?: (s: string) => void, env?: Record<string, string | undefined>, file?: string, lanes?: any,
+ * signals?: boolean, spawnImpl?: typeof import("node:child_process").spawn }} [opts]
* @returns {Promise<number>}
*/
-export async function renderModeCommand(args, { log = console.log, err = console.error, env = process.env, file, lanes } = {}) {
+export async function renderModeCommand(allArgs, { log = console.log, err = console.error, env = process.env, file, lanes, signals, spawnImpl } = {}) {
+ // `on … -- <command …>`: everything after the first `--` is the command.
+ const dash = allArgs.indexOf("--");
+ const args = dash >= 0 ? allArgs.slice(0, dash) : allArgs;
+ const cmd = dash >= 0 ? allArgs.slice(dash + 1) : null;
const valued = new Set(["--for", "--note"]);
const sub = args.find((a, i) => !a.startsWith("--") && !valued.has(args[i - 1]));
const flag = (n) => {
@@ -217,6 +369,15 @@ export async function renderModeCommand(args, { log = console.log, err = console
err(USAGE);
return 2;
}
+ if (cmd && (sub !== "on" || !cmd.length)) {
+ err(sub === "on" ? "render-mode on --: name the command to run after --" : `render-mode ${sub} takes no command (only \`on -- <command …>\` does)`);
+ return 2;
+ }
+ const printToken = args.includes("--print-token");
+ if (printToken && json) {
+ err("--print-token and --json: one or the other");
+ return 2;
+ }
const where = file ?? renderModeFile(env);
const cfg = editorConfig(env);
const editor = lanes !== undefined ? lanes : editorLanes(cfg);
@@ -247,6 +408,7 @@ export async function renderModeCommand(args, { log = console.log, err = console
err(`--for wants a duration: 90m, 2h, 1h30m, or minutes — not "${raw}"`);
return 2;
}
+ if (cmd) return renderModeChain(cmd, { forMs, note: flag("--note") ?? null, printToken, log, err, env, file: where, lanes: editor, signals, spawnImpl });
const r = await renderModeOn({ file: where, holder: null, forMs, note: flag("--note") ?? null, by: "umtool render-mode", editor: editor ? cfg.url : null, lanes: editor });
if (!r.ok || !r.state) {
if (json) out({ ok: false, error: "render mode is already on", held: r.held });
@@ -257,6 +419,11 @@ export async function renderModeCommand(args, { log = console.log, err = console
out({ ok: true, state: r.state, file: where, reminder: RENDER_MODE_REMINDER });
return 0;
}
+ if (printToken) {
+ log(r.state.token);
+ err(`render mode ON until ${clockOf(r.state.until)} — ${lanesLine(r.state)}; end it: umtool render-mode off`);
+ return 0;
+ }
log(`render mode ON until ${clockOf(r.state.until)} — ${lanesLine(r.state)}`);
log(` ${RENDER_MODE_REMINDER}`);
log(" every `umtool take` started now renders in it; another command joins with:");
diff --git a/umtool/lib/report/renderMode.test.mjs b/umtool/lib/report/renderMode.test.mjs
@@ -253,3 +253,128 @@ test("umtool take --priority: the take is made inside render mode, and render mo
await rm(root, { recursive: true, force: true });
}
});
+
+test("render-mode on -- <cmd>: held while the command runs (its pid the holder, its env the token), released at its exit, its code returned", async () => {
+ const dir = mkdtempSync(path.join(tmpdir(), "render-mode-chain-"));
+ const file = path.join(dir, "state.json");
+ const seen = path.join(dir, "seen.json");
+ const ed = fakeLanes({ download: true });
+ const out = [];
+ const err = [];
+ // The command waits for the hold (its lanes recorded), then records what it
+ // saw — its env's token, the state file, its own pid — and exits 3.
+ const waitThen = `const fs = require("node:fs"); const t0 = Date.now();
+(function look() {
+ try {
+ const s = JSON.parse(fs.readFileSync(${JSON.stringify(file)}, "utf8"));
+ if (s.lanesHeld && s.lanesHeld.length) {
+ fs.writeFileSync(${JSON.stringify(seen)}, JSON.stringify({ token: process.env.RENDER_PRIORITY_TOKEN, state: s, pid: process.pid }));
+ process.exit(3);
+ }
+ } catch {}
+ if (Date.now() - t0 > 10000) process.exit(9);
+ setTimeout(look, 20);
+})();`;
+ const code = await renderModeCommand(["on", "--note", "the cut", "--", process.execPath, "-e", waitThen], {
+ log: (l) => out.push(l),
+ err: (l) => err.push(l),
+ env: { PATH: process.env.PATH },
+ file,
+ lanes: ed.lanes,
+ signals: false,
+ });
+ assert.equal(code, 3, "the command's exit code");
+ const s = JSON.parse(readFileSync(seen, "utf8"));
+ assert.equal(s.token, s.state.token, "the command carries the hold's token");
+ assert.equal(s.state.holder.pid, s.pid, "the hold is the command's pid");
+ assert.equal(s.state.note, "the cut");
+ assert.equal(s.state.until, null, "no window: it ends with the command");
+ assert.match(s.state.holder.cmd, /-e/);
+ assert.equal(existsSync(file), false, "released at the command's exit");
+ assert.deepEqual(ed.calls, ["hold transcription", "release transcription"], "download was held already: left alone");
+ assert.match(out.join("\n"), /render mode ON for [\s\S]* \(pid \d+\) — lanes held: transcription/);
+ assert.match(out.join("\n"), /render mode off — lanes released: transcription/);
+});
+
+test("render-mode on -- <cmd>: --print-token puts the token alone on stdout; a failing spawn returns 127 and holds nothing", async () => {
+ const file = tmpFile();
+ const ed = fakeLanes();
+ const out = [];
+ const err = [];
+ const io = { log: (l) => out.push(l), err: (l) => err.push(l), env: { PATH: process.env.PATH }, file, lanes: ed.lanes, signals: false };
+ assert.equal(await renderModeCommand(["on", "--print-token", "--", process.execPath, "-e", "process.exit(0)"], io), 0);
+ assert.equal(out.length, 1);
+ assert.match(out[0], /^[0-9a-f]{16}$/);
+ assert.ok(err.some((l) => /render mode ON for/.test(l)));
+ assert.equal(existsSync(file), false);
+ assert.equal(await renderModeCommand(["on", "--", path.join(tmpdir(), "no-such-command-render-mode")], io), 127);
+ assert.equal(existsSync(file), false);
+ assert.equal(await renderModeCommand(["on", "--"], io), 2, "no command");
+ assert.equal(await renderModeCommand(["off", "--", "true"], io), 2, "only on runs a command");
+
+ // The window form with --print-token: the token alone on stdout, and it is the window's.
+ out.length = 0;
+ assert.equal(await renderModeCommand(["on", "--for", "10m", "--print-token"], io), 0);
+ assert.deepEqual(out, [readRenderPriorityState(file).token]);
+ assert.equal(await renderModeCommand(["on", "--print-token", "--json"], io), 2);
+
+ // Inside that window a chained command joins it: the window's token, the window left on.
+ const seen = path.join(path.dirname(file), "seen.txt");
+ const code = await renderModeCommand(["on", "--", process.execPath, "-e", `require("node:fs").writeFileSync(${JSON.stringify(seen)}, process.env.RENDER_PRIORITY_TOKEN || "")`], io);
+ assert.equal(code, 0);
+ assert.equal(readFileSync(seen, "utf8"), readRenderPriorityState(file).token);
+ assert.equal(readRenderPriority(file).held, true, "the window outlives the command");
+ assert.equal(await renderModeCommand(["off"], io), 0);
+});
+
+test("render-mode on -- <cmd> signalled: the signal reaches the command and the hold ends", async () => {
+ const dir = mkdtempSync(path.join(tmpdir(), "render-mode-chain-sig-"));
+ const file = path.join(dir, "state.json");
+ const log = path.join(dir, "lanes.log");
+ const childLog = path.join(dir, "child.log");
+ const script = path.join(dir, "chain.mjs");
+ writeFileSync(
+ script,
+ `import { appendFileSync } from "node:fs";
+import { renderModeCommand } from ${JSON.stringify(path.join(HERE, "renderMode.mjs"))};
+const lanes = {
+ isHeld: async () => false,
+ hold: async (l) => appendFileSync(${JSON.stringify(log)}, "hold " + l + "\\n"),
+ release: async (l) => appendFileSync(${JSON.stringify(log)}, "release " + l + "\\n"),
+};
+const child = 'process.on("SIGTERM",()=>{require("node:fs").appendFileSync(${JSON.stringify(childLog)},"TERM\\\\n");process.exit(0)});require("node:fs").appendFileSync(${JSON.stringify(childLog)},"ready\\\\n");setInterval(()=>{},1000)';
+process.exit(await renderModeCommand(["on", "--", process.execPath, "-e", child], { log: (l) => console.log(l), err: (l) => console.error(l), env: { PATH: process.env.PATH }, file: ${JSON.stringify(file)}, lanes }));
+`,
+ );
+ const proc = spawn(process.execPath, [script], { stdio: ["ignore", "pipe", "pipe"] });
+ let out = "";
+ proc.stdout.on("data", (d) => (out += d));
+ proc.stderr.on("data", (d) => (out += d));
+ const t0 = Date.now();
+ while (!/render mode ON for/.test(out) || !existsSync(childLog)) {
+ if (Date.now() - t0 > 15_000) throw new Error(`never went on: ${out}`);
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ const held = readRenderPriority(file);
+ assert.equal(held.held, true);
+ assert.notEqual(held.state.holder.pid, proc.pid, "the holder is the command, not umtool");
+ proc.kill("SIGTERM");
+ const code = await new Promise((r) => proc.on("exit", (c) => r(c)));
+ assert.equal(code, 143);
+ assert.equal(existsSync(file), false);
+ assert.equal(readFileSync(log, "utf8"), "hold transcription\nhold download\nrelease transcription\nrelease download\n");
+ for (let i = 0; i < 100 && !readFileSync(childLog, "utf8").includes("TERM"); i += 1) await new Promise((r) => setTimeout(r, 20));
+ assert.equal(readFileSync(childLog, "utf8"), "ready\nTERM\n", "the command got the signal");
+});
+
+test("a take started under render-mode on -- … is part of that hold (no 'waits for it')", async () => {
+ const file = tmpFile();
+ writeFileSync(file, JSON.stringify({ version: 1, token: "chain", since: new Date().toISOString(), until: null, holder: { pid: process.pid, cmd: "sh render-all.sh" }, lanesHeld: [] }));
+ const lines = [];
+ const env = { RENDER_PRIORITY_TOKEN: "chain" };
+ await withTakePriority({ priority: true, project: "p", take: "t", log: (l) => lines.push(l), env, file, lanes: null, signals: false }, async () => {
+ assert.equal(env.RENDER_PRIORITY_TOKEN, "chain");
+ });
+ assert.match(lines[0], /this take is part of it/);
+ assert.equal(readRenderPriorityState(file).token, "chain");
+});
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -135,6 +135,7 @@ import {
cardWidth, contentWidth, reservedFooterHeight,
} from "./render-cards.mjs";
import { DEFAULT_CHANNELS_DIR, createCueSource, siteOriginFromManifest } from "./cues.mjs";
+import { archiveMomentUrl } from "./site-links.mjs";
import { cutArgs } from "yt-dlp-transcript-common/lib/evidenceClip.mjs";
// Where a clip's media is ALREADY on disk -- the build's raw cache, the
// editor's corpus windows, the saved source -- asked before anything fetches.
@@ -164,7 +165,7 @@ import { blurCaptionLayout, blurPictureFilters, blurProblems, blurRecordOf, blur
import { validateFinaleEntries } from "./finale.mjs";
// Seconds taken out of a clip's middle (gaps.mjs): pure; the segment's graph is built there too.
import {
- gapFilterParts, gapSeconds, gapsOnSegment, inGap, offsetIn, recordGaps, renderGaps, validateGapEntries,
+ fetchPieces, gapFilterParts, gapSeconds, gapsOnSegment, inGap, keptSpans, offsetIn, recordGaps, renderGaps, validateGapEntries,
} from "./gaps.mjs";
import { SYNC_FILE, writeSyncReport } from "./sync-report.mjs";
import { validateThreadEntries } from "./threads.mjs";
@@ -544,6 +545,10 @@ const HUMAN = {
(e.source === "audio" ? " — audio only, under a poster" : "") +
(e.source === "audio-fallback" ? " — AUDIO-FALLBACK: the picture is not on disk; a poster plays" : "")
: ` fetch ${e.id}: ${e.video} ${hms(e.from)}–${hms(e.to)} (network)`,
+ // A gap-joined clip cut from its pieces (piecedClipSource), joined into one file.
+ pieces: (e) =>
+ ` pieces ${e.id}: ${e.pieces.length} piece(s) ${e.pieces.map(([a, b]) => `${hms(a)}–${hms(b)}`).join(", ")} ` +
+ `joined in ${e.file}: ${Number(e.seconds).toFixed(1)}s of the ${hms(e.pieces[0][0])}–${hms(e.pieces[e.pieces.length - 1][1])} extent`,
snap: (e) =>
` snap ${e.id}: ${e.start ? "start✓" : "start–"} ${e.end ? "end✓" : "end–"} ` +
`(${Number(e.seconds).toFixed(1)}s)`,
@@ -848,6 +853,8 @@ export { AUDIO_ON_CLOCK };
* what was asked for. `--pad` stays the shorthand that sets both.
*/
export function fetchSpan(entry, render, opts = {}) {
+ // One piece of a clip fetched in pieces (fetchSpans): that piece's span.
+ if (opts.span) return { from: opts.span.from, to: opts.span.to };
const pad = opts.pad ?? render.fetchPad ?? 3.0;
const padBefore = opts.padBefore ?? pad;
const padAfter = opts.padAfter ?? pad;
@@ -855,6 +862,100 @@ export function fetchSpan(entry, render, opts = {}) {
}
/**
+ * The spans a clip's source is needed over, PER KEPT PIECE (gaps.mjs
+ * fetchPieces): each piece of its extent less the gaps this render applies,
+ * padded at its own edges as fetchSpan pads the extent, pieces under a minute
+ * apart as one. One span -- fetchSpan's -- for a clip without gaps, for one
+ * whose gaps are short, and in a montage (it applies no gaps). What umtool
+ * fetch asks the editor for (fetchWindows.mjs), and what a gap-joined clip
+ * spanning hours is cut from (piecedClipSource).
+ */
+export function fetchSpans(entry, render, opts = {}) {
+ if (opts.span) return [fetchSpan(entry, render, opts)];
+ const pad = opts.pad ?? render.fetchPad ?? 3.0;
+ return fetchPieces(entry.start, entry.end, renderGaps(entry, render), {
+ before: opts.padBefore ?? pad,
+ after: opts.padAfter ?? pad,
+ });
+}
+
+/**
+ * The clock of a clip cut from its pieces joined end to end (piecedClipSource):
+ * each span laid after the one before, so the seconds between them -- inside
+ * a gap, never played -- are not in the file. `toVirtual` maps a source second
+ * onto the joined file's clock (one between the spans lands on the nearest
+ * span's edge), `toReal` maps back (past either end it runs on, as a file's
+ * clock would). Pure.
+ *
+ * @param {Array<{ from: number, to: number }>} spans
+ */
+export function piecesClock(spans) {
+ const groups = [];
+ let v = 0;
+ for (const s of spans) {
+ groups.push({ from: s.from, to: s.to, v0: v, len: s.to - s.from });
+ v += s.to - s.from;
+ }
+ const total = v;
+ const toVirtual = (t) => {
+ if (!Number.isFinite(t) || !groups.length) return t;
+ let near = groups[0];
+ let dist = Infinity;
+ for (const g of groups) {
+ if (t >= g.from && t <= g.to) return g.v0 + (t - g.from);
+ const d = t < g.from ? g.from - t : t - g.to;
+ if (d < dist) {
+ dist = d;
+ near = g;
+ }
+ }
+ if (t < groups[0].from) return t - groups[0].from;
+ if (t > groups[groups.length - 1].to) return total + (t - groups[groups.length - 1].to);
+ return t < near.from ? near.v0 : near.v0 + near.len;
+ };
+ const toReal = (x) => {
+ if (!Number.isFinite(x) || !groups.length) return x;
+ if (x < 0) return groups[0].from + x;
+ for (const g of groups) if (x <= g.v0 + g.len) return g.from + (x - g.v0);
+ const last = groups[groups.length - 1];
+ return last.to + (x - total);
+ };
+ /**
+ * The source seconds a cut on this clock leaves out between its first and
+ * last: its own gaps (`gaps`, on this clock) and every second between two
+ * pieces, as gaps in the source's seconds -- what the cut record says. A
+ * gap that shrank to nothing on this clock (no pad between two pieces) is
+ * still the source's seconds between them.
+ * @param {number} a @param {number} b the cut, on this clock
+ * @param {Array<{ from: number, to: number }>} gaps on this clock
+ */
+ const realGaps = (a, b, gaps) => {
+ const kept = [];
+ for (const k of keptSpans(a, b, gaps)) {
+ for (const g of groups) {
+ const lo = Math.max(k.from, g.v0);
+ const hi = Math.min(k.to, g.v0 + g.len);
+ if (hi - lo > 1e-9) kept.push({ from: g.from + (lo - g.v0), to: g.from + (hi - g.v0) });
+ }
+ }
+ const out = [];
+ for (let i = 1; i < kept.length; i += 1) if (kept[i].from - kept[i - 1].to > 1e-6) out.push({ from: kept[i - 1].to, to: kept[i].from });
+ return out;
+ };
+ return { spans: groups.map((g) => ({ from: g.from, to: g.to })), total, toVirtual, toReal, realGaps };
+}
+
+/** A clip's source seconds on a pieces clock: what the segment's cut reads in place of the entry's own. Pure. */
+export function virtualEntry(entry, clock) {
+ const v = { ...entry };
+ for (const k of ["start", "end", "cutStart", "cutEnd", "cite"]) if (Number.isFinite(entry[k])) v[k] = clock.toVirtual(entry[k]);
+ if (Array.isArray(entry.gaps)) {
+ v.gaps = entry.gaps.map((g) => (g && Number.isFinite(g.from) && Number.isFinite(g.to) ? { ...g, from: clock.toVirtual(g.from), to: clock.toVirtual(g.to) } : g));
+ }
+ return v;
+}
+
+/**
* Where this build looks for media already on disk: the raw cache, the
* channels tree and the clip's channel. One per build; `resolve` is memoised,
* so `--no-network`'s up-front pass and the clip's own fetch probe a saved
@@ -912,6 +1013,15 @@ export async function planLocalSources(entries, timeline, render, opts, local, m
audioUse({ entry, meta, render, network: networkOn(opts), fallback: !!opts.audioFallback });
let use = ask(null);
let hit = await local.resolve(entry, span, { exact, audio: use !== null });
+ // A gap-joined clip is had when each of its pieces is (fetchSpans, piecedClipSource).
+ if (!hit) {
+ const spans = fetchSpans(entry, render, opts);
+ if (spans.length > 1) {
+ const hits = [];
+ for (const s of spans) hits.push(await local.resolve(entry, s, { exact, audio: use !== null }));
+ if (hits.every(Boolean)) hit = hits.find((h) => h.kind !== "audio") ?? hits[0];
+ }
+ }
const row = {
// By id: a variant's view may be a copy of the manifest's entry.
index: timeline.findIndex((e) => e === entry || (entry.id != null && e?.id === entry.id)),
@@ -1205,6 +1315,89 @@ async function fetchClip(entry, meta, render, local, opts) {
return { path: dest, fetchStart: from, cached: false, source: "network" };
}
+/**
+ * A gap-joined clip's source, cut from its PIECES (fetchSpans): when its
+ * gaps leave more than one span and no window on disk holds the whole extent,
+ * each span is had on its own (on disk, else fetched -- that span only) and
+ * the spans are joined end to end into `segments/<id>.pieces.mp4`: one input
+ * per piece, concatenated, every piece the first one's size and the render's
+ * fps. The segment is then cut from that file on its pieces clock
+ * (piecesClock): `entry` is the clip with its seconds on that clock, `clock`
+ * maps the cut back to the source's for the cut record. Null for every other
+ * clip -- one span, a `src`, a whole window on disk -- which is cut as ever.
+ * The joined file is made again only when its pieces change (`.pieces.mp4.json`).
+ */
+async function piecedClipSource(entry, meta, render, local, opts, outDir) {
+ if (hasLocalMedia(entry)) return null;
+ const spans = fetchSpans(entry, render, opts);
+ if (spans.length < 2) return null;
+ if (await onDiskClipSource(entry, meta, render, local, opts)) return null;
+ const parts = [];
+ for (const span of spans) parts.push({ span, ...(await fetchClipAligned(entry, meta, render, local, { ...opts, span })) });
+ const probes = await Promise.all(parts.map((p) => probeMedia(p.path)));
+ const withPicture = probes.filter((p) => p.hasVideo).length;
+ if (withPicture && withPicture < parts.length) {
+ throw new Error(
+ `${entry.id}: its pieces' sources differ -- ${parts.filter((_, k) => !probes[k].hasVideo).map((p) => path.basename(p.path)).join(", ")} ` +
+ "has only sound, the others a picture; fetch the piece again (umtool fetch --refetch)",
+ );
+ }
+ const fps = render.fps ?? 30;
+ let dims = null;
+ if (withPicture) {
+ const [w, h] = await probeDims(parts[0].path);
+ dims = [Math.max(2, 2 * Math.round(w / 2)), Math.max(2, 2 * Math.round(h / 2))];
+ }
+ const file = path.join(outDir, "segments", `${entry.id}.pieces.mp4`);
+ const keyFile = `${file}.json`;
+ const sigs = await Promise.all(parts.map((p) => stat(p.path).then((s) => ({ size: s.size, mtimeMs: Math.round(s.mtimeMs) }), () => null)));
+ const key = `${JSON.stringify({
+ version: 1, fps, dims,
+ pieces: parts.map((p, k) => ({ file: p.path, fetchStart: p.fetchStart, from: p.span.from, to: p.span.to, ...sigs[k] })),
+ }, null, 2)}\n`;
+ const had = await readFile(keyFile, "utf8").catch(() => null);
+ if (had !== key || !(await exists(file))) {
+ const inputs = [];
+ const filters = [];
+ const legs = [];
+ parts.forEach((p, k) => {
+ const len = p.span.to - p.span.from;
+ const a = p.span.from - p.fetchStart;
+ inputs.push(...cutArgs(p.path, Math.max(0, a), p.span.to - p.fetchStart));
+ const L = len.toFixed(3);
+ if (dims) {
+ const [W, H] = dims;
+ filters.push(
+ `[${k}:v]scale=${W}:${H}:force_original_aspect_ratio=decrease,pad=${W}:${H}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=${fps},format=yuv420p,` +
+ `tpad=stop_mode=clone:stop_duration=${L},trim=duration=${L},setpts=PTS-STARTPTS[pv${k}]`,
+ );
+ }
+ // A piece that starts before its media does keeps its place: silence first.
+ const lead = a < 0 ? `adelay=${Math.round(-a * 1000)}:all=1,` : "";
+ filters.push(`[${k}:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,${lead}apad=whole_dur=${L},atrim=duration=${L},asetpts=PTS-STARTPTS[pa${k}]`);
+ legs.push(`${dims ? `[pv${k}]` : ""}[pa${k}]`);
+ });
+ filters.push(`${legs.join("")}concat=n=${parts.length}:v=${dims ? 1 : 0}:a=1${dims ? "[pv]" : ""}[pa]`);
+ const tmp = `${file}.tmp.mp4`;
+ await mkdir(path.dirname(file), { recursive: true });
+ await execFileP(FFMPEG, [
+ "-nostdin", "-v", "error", "-y", ...inputs,
+ "-filter_complex", filters.join(";"),
+ ...(dims ? ["-map", "[pv]", "-c:v", "libx264", "-preset", "veryfast", "-crf", "12", "-pix_fmt", "yuv420p", "-r", String(fps)] : []),
+ "-map", "[pa]", "-c:a", "aac", "-b:a", "320k", "-ar", "48000",
+ "-movflags", "+faststart", tmp,
+ ], { maxBuffer: 1 << 24 });
+ await rename(tmp, file);
+ await writeFile(keyFile, key, "utf8");
+ }
+ const clock = piecesClock(spans);
+ EMIT("pieces", {
+ id: entry.id, file: path.basename(file), seconds: Number(clock.total.toFixed(2)),
+ pieces: spans.map((s) => [Number(s.from.toFixed(2)), Number(s.to.toFixed(2))]),
+ });
+ return { path: file, fetchStart: 0, cached: true, source: "pieces", clock, entry: virtualEntry(entry, clock) };
+}
+
// The silences of a file, in its own seconds (cut-points.mjs detectSilence,
// with this build's ffmpeg). The snap that reads them is snap.mjs's `snap`,
// re-exported above for the tests.
@@ -1240,7 +1433,13 @@ const encodeArgsVideoOnly = (render) => [
async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, provenance, framing = null) {
const outDir = dirs.dir;
- const { path: raw, fetchStart, scan } = await fetchClipAligned(entry, meta, render, dirs.local, opts);
+ // A gap-joined clip whose pieces are apart is cut from them joined
+ // (piecedClipSource): `clipE` is the clip on that file's clock, `toReal`
+ // maps a cut on it back to the source's. Every other clip: itself, as ever.
+ const pieced = await piecedClipSource(entry, meta, render, dirs.local, opts, outDir);
+ const { path: raw, fetchStart, scan } = pieced ?? (await fetchClipAligned(entry, meta, render, dirs.local, opts));
+ const clipE = pieced ? pieced.entry : entry;
+ const toReal = pieced ? pieced.clock.toReal : (t) => t;
// Every file this writes in segments/ is written through a rename (the
// segment by encodeSegmentCached, the records and texts by replaceFile), so
// a link to another take's file -- `umtool take --from` links them in -- is
@@ -1263,22 +1462,22 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
// starting exactly on the quote's first syllable sounds like a dropped
// frame.
const hasCut = Number.isFinite(entry.cutStart) && Number.isFinite(entry.cutEnd);
- const { from: playFrom, to: playTo } = playWindow(entry, render);
+ const { from: playFrom, to: playTo } = playWindow(clipE, render);
if (hasCut) {
EMIT("cut", {
id: entry.id,
extent: [entry.start, entry.end],
- cut: [playFrom, playTo],
+ cut: pieced ? [toReal(playFrom), toReal(playTo)] : [playFrom, playTo],
seconds: Number((playTo - playFrom).toFixed(2)),
});
// The header prints a second, and it has to be a second you can hear in
// the clip that plays. Kept rather than moved: a cite is a citation, and
// silently re-pointing one is worse than saying it is off.
- const at = entry.cite ?? entry.start;
+ const at = clipE.cite ?? clipE.start;
if (at < playFrom - 0.05 || at > playTo + 0.05) {
EMIT("note", {
message:
- `${entry.id}: cite ${at} is outside the cut ${playFrom.toFixed(2)}–${playTo.toFixed(2)} ` +
+ `${entry.id}: cite ${entry.cite ?? entry.start} is outside the cut ${toReal(playFrom).toFixed(2)}–${toReal(playTo).toFixed(2)} ` +
`— kept as written; move it or widen the cut`,
});
}
@@ -1304,7 +1503,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
}
// GAPS (gaps.mjs): seconds taken out of the clip's middle, so it plays as one
// segment of jump cuts. A montage cuts to its phrase: none there.
- const clipGaps = mont ? [] : renderGaps(entry, render);
+ const clipGaps = mont ? [] : renderGaps(clipE, render);
if (mont && Array.isArray(entry.gaps) && entry.gaps.length) {
EMIT("note", { message: `${entry.id}: a montage cuts to its phrase — its gaps are not applied` });
}
@@ -1312,7 +1511,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
// A locked edge snaps only outward, inside the silence it sits in (mute.mjs lockedEdges);
// and no edge snaps across a gap (a gap's edges are exact).
const snapped = mont ? null : snapCut({
- sil, wantA, wantB, render, locked: lockedEdges(entry, render),
+ sil, wantA, wantB, render, locked: lockedEdges(clipE, render),
...(clipGaps.length ? { gaps: clipGaps.map((g) => ({ from: g.from - fetchStart, to: g.to - fetchStart })) } : {}),
});
const a = mont ? mont.win.start : snapped.a;
@@ -1323,7 +1522,8 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
// Room at the edges (render.room, room.mjs): the picture widened past the
// snapped cut -- to the first silence and a join's length beyond, muted --
// the sound heard over [cutA, soundB] only. Null when off: the cut as ever.
- const room = dirs.room && !mont && !dirs.short
+ // Not for a clip cut from its pieces: room's record is in the source's seconds of one file.
+ const room = dirs.room && !mont && !dirs.short && !pieced
? await segmentRoom({ entry, raw, render, provenance, look: dirs.look, D: dirs.room.D, first: dirs.room.first === entry.id, fetchStart, cutA, cutB })
: null;
const segA = room ? room.plan.picA : cutA;
@@ -1340,9 +1540,13 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
id: entry.id, gaps: segGaps.length, cut: Number(gapTotal.toFixed(3)), seconds: Number(segSeconds.toFixed(3)),
...(segGaps.length < clipGaps.length ? { dropped: clipGaps.length - segGaps.length } : {}),
});
- const at = entry.cite ?? entry.start;
+ const at = clipE.cite ?? clipE.start;
const g = inGap(at, clipGaps);
- if (g) EMIT("note", { message: `${entry.id}: cite ${at} is inside the gap ${g.from}–${g.to}, which never plays — kept as written; move it` });
+ if (g) {
+ EMIT("note", {
+ message: `${entry.id}: cite ${entry.cite ?? entry.start} is inside the gap ${toReal(g.from)}–${toReal(g.to)}, which never plays — kept as written; move it`,
+ });
+ }
}
// Where in the SOURCE this segment really starts and ends, snapped: what a
// `muteFrom` (source seconds) is measured from at the join, long after this
@@ -1350,13 +1554,20 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
// picture's span; `room.sound` is the part that is heard.
const cutRecord = {
version: 1, id: entry.id, video: entry.video,
- start: Number((fetchStart + segA).toFixed(3)), end: Number((fetchStart + segB).toFixed(3)),
+ start: Number(toReal(fetchStart + segA).toFixed(3)), end: Number(toReal(fetchStart + segB).toFixed(3)),
snapped: { start: a.snapped, end: b.snapped },
...(room ? { room: room.record } : {}),
// Only with gaps, so a clip without them records what it always did.
- ...(segGaps.length
- ? { gaps: segGaps.map((g) => ({ from: Number((fetchStart + segA + g.from).toFixed(3)), to: Number((fetchStart + segA + g.to).toFixed(3)) })) }
- : {}),
+ // Cut from its pieces: every source second left out, the seconds between pieces too.
+ ...(pieced
+ ? {
+ gaps: pieced.clock
+ .realGaps(fetchStart + segA, fetchStart + segB, segGaps.map((g) => ({ from: fetchStart + segA + g.from, to: fetchStart + segA + g.to })))
+ .map((g) => ({ from: Number(g.from.toFixed(3)), to: Number(g.to.toFixed(3)) })),
+ }
+ : segGaps.length
+ ? { gaps: segGaps.map((g) => ({ from: Number((fetchStart + segA + g.from).toFixed(3)), to: Number((fetchStart + segA + g.to).toFixed(3)) })) }
+ : {}),
};
// Even loudness for a cut that is not a montage (render.loudness, release
// 36): the cut as it will play, measured, one gain toward the target
@@ -1452,7 +1663,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
// render.blur "off"): every chain below is the one it always was.
const blur = clipBlurOf(entry, render);
if (blur && !media.hasVideo) EMIT("note", { message: `${entry.id}: no picture to blur in ${path.basename(raw)} — the poster plays as it is` });
- const span = media.hasVideo ? blurSpan(blur, fetchStart + segA, segSeconds, cutRecord.gaps) : null;
+ const span = media.hasVideo ? blurSpan(blur, toReal(fetchStart + segA), segSeconds, cutRecord.gaps) : null;
if (blur) cutRecord.blur = blurRecordOf(blur);
/** The blur's filters for a picture fitted into `bw` × `bh` (empty: none). */
const blurPicture = async (bw, bh) => {
@@ -2271,11 +2482,7 @@ async function qrForEntry(entry, provenance, render, outDir) {
// A mirror's LOCAL slug is not the id the site serves, and a clip taken from a
// copy whose archived transcript is broken should point at the copy that reads —
// so an explicit per-clip citeUrl always wins over the derived one.
- const url =
- entry.citeUrl ??
- `${provenance.siteOrigin}/?v=${encodeURIComponent(
- `${entry.channel ?? provenance.channelSlug}/${entry.video}`,
- )}&t=${Math.floor(entry.start)}`;
+ const url = entry.citeUrl ?? archiveMomentUrl(entry, provenance, entry.start);
const png = path.join(outDir, "qr", `${entry.id}.png`);
await execFileP(QRENCODE, [
"-o", png,
diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs
@@ -15,6 +15,7 @@
// No ffmpeg, no fs, no network. If a function here needs one, it belongs in
// build-video.mjs or compose-chrome.mjs instead.
import { createHash } from "node:crypto";
+import { archiveMomentUrl } from "./site-links.mjs";
import { playEdges, soundEdges as soundEdgesOf, soundOnSegment } from "./mute.mjs";
import { gappedLength, offsetIn, recordGaps, renderGaps } from "./gaps.mjs";
import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs";
@@ -980,10 +981,7 @@ export function deckQrUrl(entry, provenance = {}, { links = DECK_DEFAULTS.qr.lin
// A clip from a file beside the manifest (`src`) has no page anywhere.
if (entry.src != null) return null;
const original = links === "original" ? originalUrlAt(meta?.webpageUrl, entry.start) : null;
- return original ??
- `${provenance.siteOrigin}/?v=${encodeURIComponent(
- `${entry.channel ?? provenance.channelSlug}/${entry.video}`,
- )}&t=${Math.floor(entry.start)}`;
+ return original ?? archiveMomentUrl(entry, provenance, entry.start);
}
if (entry.type === "image") return entry.citeUrl ?? null;
return null;
diff --git a/umtool/report-to-video/gaps-render.test.mjs b/umtool/report-to-video/gaps-render.test.mjs
@@ -20,7 +20,7 @@ import test from "node:test";
const CORPUS = mkdtempSync(path.join(os.tmpdir(), "rtv-gaps-corpus-"));
process.env.CHANNELS_DIR = CORPUS;
-const { buildVideo, probeDuration, setProgressMode } = await import("./build-video.mjs");
+const { buildVideo, fetchSpans, piecesClock, probeDuration, setProgressMode, virtualEntry } = await import("./build-video.mjs");
const { deckSchedule, estimatedDuration, muteSegmentSeconds, segmentSoundEdits } = await import("./deck.mjs");
const { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } = await import("./brand.mjs");
const { renderCut, snapCut } = await import("./snap.mjs");
@@ -149,6 +149,103 @@ test("render: a gap is taken out of ONE segment -- the kept seconds long, no bla
}
});
+// ---- a gap-joined clip cut from its pieces -----------------------------------------
+// Two moments of one recording joined by a gap: 1–5 s and 190–200 s. Only the
+// two pieces are on disk (two windows, the second WHITE with a higher tone),
+// never the 185 s between: --no-network builds it from them, one segment, the
+// kept 14 s, the record in the recording's own seconds.
+
+{
+ const dir = path.join(CORPUS, CHANNEL, "data", "vid2");
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, "transcript.cues.json"), JSON.stringify({ id: "vid2", title: "Long", duration: 300, uploadDate: "20240102", cues: [{ start: 0.2, end: 299, text: "words" }] }));
+ writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "vid2", title: "Long", duration: 300 }));
+}
+
+test("render: a gap-joined clip whose pieces are minutes apart is cut from its two pieces -- never the seconds between", { skip: !have && "needs ffmpeg" }, async () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), "rtv-pieces-"));
+ const raw = path.join(root, "out", "clips-raw");
+ mkdirSync(raw, { recursive: true });
+ const window = (name, colour, hz, d) => {
+ const r = spawnSync("ffmpeg", [
+ "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=${colour}:s=320x180:r=${FPS}:d=${d}`,
+ "-f", "lavfi", "-i", `sine=frequency=${hz}:sample_rate=48000:duration=${d}`,
+ "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", path.join(raw, name),
+ ]);
+ assert.equal(r.status, 0, String(r.stderr));
+ };
+ window("vid2_0.00-12.00.mp4", "gray", 440, 12);
+ window("vid2_185.00-205.00.mp4", "white", 880, 20);
+ const manifestPath = path.join(root, "video.manifest.json");
+ await writeFile(manifestPath, JSON.stringify({
+ slug: "pieces", title: "Pieces",
+ provenance: { channelSlug: CHANNEL, channelsDir: CORPUS },
+ render: RENDER,
+ timeline: [{ type: "clip", id: "j1", channel: CHANNEL, video: "vid2", start: 1, end: 200, cite: 1, quote: "q", gaps: [{ from: 5, to: 190 }] }],
+ }));
+ const events = [];
+ setProgressMode((e) => events.push(e));
+ try {
+ await buildVideo({ manifestPath, opts: { noNetwork: true } });
+ const pieces = events.find((e) => e.ev === "pieces");
+ assert.ok(pieces, "the clip was cut from its pieces");
+ assert.deepEqual(pieces.pieces, [[1, 5], [190, 200]]);
+ assert.deepEqual(events.filter((e) => e.ev === "fetch").map((e) => [e.from, e.to, e.reuse]), [[1, 5, "vid2_0.00-12.00.mp4"], [190, 200, "vid2_185.00-205.00.mp4"]]);
+ const seg = path.join(root, "out", "sourced", "segments", "j1.mp4");
+ near(await probeDuration(seg, FPS), 14, 1 / FPS + 1e-6, "the kept seconds: 4 + 10");
+ const rec = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8"));
+ assert.deepEqual([rec.start, rec.end], [1, 200], "the record in the recording's seconds");
+ assert.deepEqual(rec.gaps, [{ from: 5, to: 190 }]);
+ const y = lumas(seg);
+ const at = (t) => y[Math.floor(t * FPS)];
+ assert.ok(at(2) > 60 && at(2) < 200, `the first piece is the grey window (YAVG ${at(2)})`);
+ assert.ok(at(9) > 200, `the second piece is the white window (YAVG ${at(9)})`);
+ assert.ok(rms(seg, 0.2, 3.8) > 800 && rms(seg, 4.2, 13.8) > 800, "heard through both pieces");
+ // Built again with nothing changed: the joined file and the segment are reused.
+ events.length = 0;
+ const before = md5(seg);
+ await buildVideo({ manifestPath, opts: { noNetwork: true } });
+ assert.equal(md5(seg), before);
+ assert.ok(events.some((e) => e.ev === "note" && / segment unchanged /.test(e.message) && e.message.split(":")[0] === "j1"), "the segment is reused");
+ // Padded pieces (fetchPad 3): the pad between them is a gap on the joined clock; the same cut.
+ const m = JSON.parse(await readFile(manifestPath, "utf8"));
+ m.render = { ...m.render, fetchPad: 3 };
+ await writeFile(manifestPath, JSON.stringify(m));
+ events.length = 0;
+ await buildVideo({ manifestPath, opts: { noNetwork: true } });
+ assert.deepEqual(events.find((e) => e.ev === "pieces")?.pieces, [[0, 8], [187, 203]]);
+ near(await probeDuration(seg, FPS), 14, 1 / FPS + 1e-6, "padded: the kept seconds still");
+ const padded = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8"));
+ assert.deepEqual([padded.start, padded.end, padded.gaps], [1, 200, [{ from: 5, to: 190 }]]);
+ } finally {
+ quiet();
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("piecesClock / virtualEntry / fetchSpans: the pieces laid end to end, and back", () => {
+ const clip = { type: "clip", id: "j", video: "v", start: 5385, end: 21812, cite: 5390, gaps: [{ from: 5400, to: 21800 }] };
+ const spans = fetchSpans(clip, { fetchPad: 3 });
+ assert.deepEqual(spans, [{ from: 5382, to: 5403 }, { from: 21797, to: 21815 }]);
+ assert.deepEqual(fetchSpans({ ...clip, gaps: [] }, { fetchPad: 3 }), [{ from: 5382, to: 21815 }]);
+ assert.deepEqual(fetchSpans(clip, { fetchPad: 3, montage: { style: "wall" } }), [{ from: 5382, to: 21815 }], "a montage applies no gaps");
+ const c = piecesClock(spans);
+ assert.equal(c.total, 39);
+ assert.equal(c.toVirtual(5385), 3);
+ assert.equal(c.toVirtual(21800), 24);
+ assert.equal(c.toVirtual(10000), 21, "between the pieces: the nearer edge");
+ assert.equal(c.toReal(3), 5385);
+ assert.equal(c.toReal(24), 21800);
+ assert.equal(c.toReal(-1), 5381);
+ const v = virtualEntry(clip, c);
+ assert.deepEqual([v.start, v.end, v.cite, v.gaps], [3, 36, 8, [{ from: 18, to: 24 }]]);
+ assert.equal(clip.start, 5385, "the entry itself is untouched");
+ assert.deepEqual(c.realGaps(3, 36, [{ from: 18, to: 24 }]), [{ from: 5400, to: 21800 }]);
+ // No pad: the pieces touch on the joined clock, the seconds between are still a gap.
+ const bare = piecesClock([{ from: 1, to: 5 }, { from: 190, to: 200 }]);
+ assert.deepEqual(bare.realGaps(0, 14, []), [{ from: 5, to: 190 }]);
+});
+
// ---- the schedule's mappings, no ffmpeg ------------------------------------------
const CLIP = { type: "clip", id: "c1", video: "v", start: 100, end: 120, cutStart: 102, cutEnd: 118 };
diff --git a/umtool/report-to-video/gaps.mjs b/umtool/report-to-video/gaps.mjs
@@ -284,6 +284,34 @@ export function keptSpans(from, to, gaps) {
return out;
}
+/** Padded pieces closer than this are fetched as one span: a minute more of one window is cheaper than another paced fetch. */
+export const FETCH_JOIN_UNDER = 60;
+
+/**
+ * The spans a clip's source is FETCHED over: each kept piece of [from, to]
+ * (keptSpans) padded `before` / `after` at its own outer edges, and padded
+ * pieces less than `joinUnder` seconds apart joined into one. A clip without
+ * gaps -- or whose gaps are short -- is one span, its padded extent, as it
+ * always was; a gap-joined clip spanning hours (two moments of one stream)
+ * is one span per moment, never the hours between.
+ *
+ * @param {number} from
+ * @param {number} to
+ * @param {Array<{ from: number, to: number }> | null | undefined} gaps the gaps a render applies (renderGaps)
+ * @param {{ before?: number, after?: number, joinUnder?: number }} [pad]
+ * @returns {Array<{ from: number, to: number }>}
+ */
+export function fetchPieces(from, to, gaps, { before = 0, after = 0, joinUnder = FETCH_JOIN_UNDER } = {}) {
+ const out = [];
+ for (const p of keptSpans(from, to, gaps)) {
+ const span = { from: Math.max(0, p.from - before), to: p.to + after };
+ const last = out[out.length - 1];
+ if (last && span.from - last.to < joinUnder) last.to = Math.max(last.to, span.to);
+ else out.push(span);
+ }
+ return out;
+}
+
/**
* A segment's gaps on its OWN clock, for the encode: each gap's edges in
* seconds from the segment's first frame (`segStart`, source seconds), put on
diff --git a/umtool/report-to-video/gaps.test.mjs b/umtool/report-to-video/gaps.test.mjs
@@ -207,3 +207,15 @@ test("gapFilterParts on a real clip: the kept seconds, the gap's black and silen
rmSync(dir, { recursive: true, force: true });
}
});
+
+test("fetchPieces: one padded span per kept piece; pieces under a minute apart are one; no gaps is the padded extent", async () => {
+ const { fetchPieces } = await import("./gaps.mjs");
+ assert.deepEqual(fetchPieces(10, 20, [], { before: 3, after: 2 }), [{ from: 7, to: 22 }]);
+ assert.deepEqual(fetchPieces(1, 20, null, { before: 3, after: 3 }), [{ from: 0, to: 23 }], "never before 0");
+ assert.deepEqual(fetchPieces(5385, 21812, [{ from: 5400, to: 21800 }], { before: 3, after: 3 }), [{ from: 5382, to: 5403 }, { from: 21797, to: 21815 }]);
+ assert.deepEqual(fetchPieces(100, 300, [{ from: 120, to: 170 }], { before: 3, after: 3 }), [{ from: 97, to: 303 }], "47 s apart: one fetch");
+ assert.deepEqual(
+ fetchPieces(0, 1000, [{ from: 100, to: 400 }, { from: 410, to: 900 }], { before: 3, after: 3 }),
+ [{ from: 0, to: 103 }, { from: 397, to: 413 }, { from: 897, to: 1003 }],
+ );
+});
diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs
@@ -95,6 +95,7 @@ import { validateTransitionStyle } from "./transition.mjs";
import { validateLook } from "./look.mjs";
import { roomWindowWarnings } from "./room.mjs";
import { qrUrlFor } from "./render-cards.mjs";
+import { archiveMomentUrl } from "./site-links.mjs";
import { cardNarrationSeconds, hasNarration, narrationsOf, validateNarration } from "./narration.mjs";
import { validatePodcast } from "./build-podcast.mjs";
import { draftsReviewFromNarration, draftsReviewProblems, readDraftsReview } from "./drafts-review.mjs";
@@ -199,8 +200,7 @@ export function qrsOf(manifest, { only = null, metaOf = null } = {}) {
let url = null;
if (e.type === "clip") {
if (e.src != null && !e.citeUrl) continue;
- url = e.citeUrl ??
- `${provenance.siteOrigin}/?v=${encodeURIComponent(`${e.channel ?? provenance.channelSlug}/${e.video}`)}&t=${Math.floor(e.start)}`;
+ url = e.citeUrl ?? archiveMomentUrl(e, provenance, e.start);
} else if (e.type === "image" && e.citeUrl) {
url = e.citeUrl;
}
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -18,6 +18,7 @@
},
"exports": {
"./attribution": "./attribution.mjs",
+ "./site-links": "./site-links.mjs",
"./brand": "./brand.mjs",
"./brand-ids": "./brand-ids.mjs",
"./build-video": "./build-video.mjs",
diff --git a/umtool/report-to-video/render-cards.mjs b/umtool/report-to-video/render-cards.mjs
@@ -39,6 +39,7 @@ import { BRAND_CARD_STYLES, renderBrandCard } from "./brand-cards.mjs";
import { FIRA_SANS, textWidth } from "./svg-faces.mjs";
import { deckOn, resolveDeck, subtitleBoxes } from "./deck.mjs";
import { ensureWriteDir } from "../lib/report/storage.mjs";
+import { archiveMomentUrl } from "./site-links.mjs";
const execFileP = promisify(execFile);
@@ -738,12 +739,7 @@ export function qrUrlFor(entry, provenance) {
if (entry.type === "clip" && !momentless) {
// A mirror's LOCAL slug is not the id the site serves, so an explicit
// per-clip citeUrl always wins over the derived one.
- return (
- entry.citeUrl ??
- `${provenance.siteOrigin}/?v=${encodeURIComponent(
- `${entry.channel ?? provenance.channelSlug}/${entry.video}`,
- )}&t=${Math.floor(entry.cite ?? entry.start)}`
- );
+ return entry.citeUrl ?? archiveMomentUrl(entry, provenance, entry.cite ?? entry.start);
}
// A card is not a moment, so it gets the search rather than a timestamp.
//
diff --git a/umtool/report-to-video/site-links.mjs b/umtool/report-to-video/site-links.mjs
@@ -0,0 +1,98 @@
+// site-links — the ONE place a manifest entry's link to its moment on the
+// archive is built (`<origin>/?v=<channel>%2F<id>&t=<s>`): the corner QR, the
+// deck's QR, the YouTube description's sources, lint's QR check, the review
+// page's cite link, the moment lookup.
+//
+// The id is the one the ARCHIVE serves (siteVideoId, common/lib/videoDirId.mjs):
+// an entry's `siteVideo` when it pins one (a Rumble clip), else its `video` —
+// but a Twitch VOD's `video` is its directory id `<n>` while the archive keys
+// the record id `v<n>`. That mapping is decided by the recording's PLATFORM,
+// never by the id being all digits (an X status id is digits too):
+//
+// the entry's own `platform`, else its channel's (config.json `platform`,
+// else the host of its `url` — channelConfigPlatform, the rule every
+// resolveVideoDirId caller uses), read once per channel from CHANNELS_DIR.
+//
+// With no local channel config (a machine with no corpus) the platform is
+// unknown and the id goes out as written. The channel is `siteChannel`, else
+// `channel`, else the provenance's channelSlug.
+
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { channelConfigPlatform, siteVideoId } from "yt-dlp-transcript-common/lib/videoDirId.mjs";
+import { CHANNELS_DIR } from "../lib/paths.mjs";
+
+/** @type {Map<string, string | null>} */
+const PLATFORMS = new Map();
+
+/**
+ * A channel's platform from its config.json, cached per (dir, slug); null when
+ * there is no readable config.
+ * @param {string | null | undefined} slug
+ * @param {string} [channelsDir]
+ * @returns {string | null}
+ */
+export function channelPlatform(slug, channelsDir = CHANNELS_DIR) {
+ if (!slug) return null;
+ const key = `${channelsDir}\u0000${slug}`;
+ if (PLATFORMS.has(key)) return /** @type {string | null} */ (PLATFORMS.get(key));
+ let platform = null;
+ try {
+ platform = channelConfigPlatform(JSON.parse(readFileSync(path.join(/* turbopackIgnore: true */ channelsDir, slug, "config.json"), "utf8")));
+ } catch {
+ platform = null;
+ }
+ PLATFORMS.set(key, platform);
+ return platform;
+}
+
+/** Forget the cached platforms (tests). */
+export function clearChannelPlatforms() {
+ PLATFORMS.clear();
+}
+
+/**
+ * The recording's platform: the entry's own `platform`, else its LOCAL
+ * channel's (`channel`, else the provenance's slug — the directory the cues
+ * come from).
+ * @param {any} entry
+ * @param {any} [provenance]
+ * @param {{ channelsDir?: string }} [opts]
+ * @returns {string | null}
+ */
+export function entryPlatform(entry, provenance = {}, { channelsDir } = {}) {
+ if (typeof entry?.platform === "string" && entry.platform) return entry.platform;
+ return channelPlatform(entry?.channel ?? provenance?.channelSlug ?? null, channelsDir);
+}
+
+/**
+ * The `<channel>/<id>` the archive serves an entry's recording under.
+ * @param {any} entry
+ * @param {any} [provenance]
+ * @param {{ channelsDir?: string, platform?: string | null }} [opts]
+ * @returns {{ channel: string | undefined, video: string }}
+ */
+export function siteRefOf(entry, provenance = {}, opts = {}) {
+ // No channel stays `undefined`, as the builders this replaced wrote it (a
+ // schedule pinned byte-for-byte reads "undefined/…").
+ const channel = entry?.siteChannel ?? entry?.channel ?? provenance?.channelSlug;
+ const platform = opts.platform !== undefined ? opts.platform : entryPlatform(entry, provenance, opts);
+ return { channel, video: siteVideoId(entry, platform) };
+}
+
+/**
+ * An entry's moment on the archive at `seconds` (floored):
+ * `<origin>/?v=<channel>%2F<id>&t=<s>`. `origin` is the provenance's
+ * `siteOrigin` unless given; it is used as it is (a missing origin gives the
+ * "undefined/?v=…" the old builders gave — callers that care check first).
+ * @param {any} entry
+ * @param {any} provenance
+ * @param {number} seconds
+ * @param {{ origin?: string | null, channelsDir?: string, platform?: string | null }} [opts]
+ */
+export function archiveMomentUrl(entry, provenance, seconds, opts = {}) {
+ const origin = opts.origin !== undefined ? opts.origin : provenance?.siteOrigin;
+ const { channel, video } = siteRefOf(entry, provenance, opts);
+ const at = Number(seconds);
+ return `${origin}/?v=${encodeURIComponent(`${channel}/${video}`)}&t=${Math.floor(Number.isFinite(at) ? at : 0)}`;
+}
diff --git a/umtool/report-to-video/site-links.test.mjs b/umtool/report-to-video/site-links.test.mjs
@@ -0,0 +1,93 @@
+// The archive link an entry's QR, deck QR, YouTube source line, lint check,
+// review cite link and moment lookup carry (site-links.mjs): a Twitch VOD's
+// directory id `<n>` goes out as the record id `v<n>` the archive serves —
+// decided by the channel's PLATFORM, never by the id being digits (an X status
+// id is digits too and goes out as it is). A temp CHANNELS_DIR with synthetic
+// channels; never the corpus. Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+const CHANNELS = mkdtempSync(path.join(tmpdir(), "site-links-"));
+for (const [slug, config] of [
+ ["twitchchan", { platform: "twitch" }],
+ ["twitchbyurl", { url: "https://www.twitch.tv/somebody" }],
+ ["xchan", { platform: "x" }],
+ ["ytchan", { url: "https://www.youtube.com/@somebody" }],
+]) {
+ mkdirSync(path.join(CHANNELS, slug), { recursive: true });
+ writeFileSync(path.join(CHANNELS, slug, "config.json"), JSON.stringify(config));
+}
+// CHANNELS_DIR is read when umtool/lib/paths.mjs loads: set it first.
+process.env.CHANNELS_DIR = CHANNELS;
+const { archiveMomentUrl, channelPlatform, siteRefOf } = await import("./site-links.mjs");
+const { deckQrUrl } = await import("./deck.mjs");
+const { momentLinkOf } = await import("./youtube.mjs");
+const { qrUrlFor } = await import("./render-cards.mjs");
+const { qrsOf } = await import("./lint.mjs");
+const { derivedCiteUrl, citeUrlFor } = await import("../lib/projects/report.mjs");
+const { resolveMoment } = await import("../lib/report/moments.mjs");
+const { siteVideoId } = await import("yt-dlp-transcript-common/lib/videoDirId.mjs");
+
+const ORIGIN = "https://example.pages.dev";
+const N = "2468013579";
+const XID = "1850000000000000000";
+const twitchClip = { type: "clip", id: "t01", channel: "twitchchan", video: N, start: 125.4, end: 140, cite: 130 };
+const xClip = { type: "clip", id: "x01", channel: "xchan", video: XID, start: 3.2, end: 9 };
+const prov = { siteOrigin: ORIGIN, channelSlug: "ytchan" };
+const twitchUrl = (t) => `${ORIGIN}/?v=twitchchan%2Fv${N}&t=${t}`;
+const xUrl = (t) => `${ORIGIN}/?v=xchan%2F${XID}&t=${t}`;
+
+test("siteVideoId: v<n> only for Twitch; siteVideo wins; X digits and every other platform untouched", () => {
+ assert.equal(siteVideoId({ video: N }, "twitch"), `v${N}`);
+ assert.equal(siteVideoId(N, "twitch"), `v${N}`);
+ assert.equal(siteVideoId({ video: `v${N}` }, "twitch"), `v${N}`, "already the record id");
+ assert.equal(siteVideoId({ video: XID }, "x"), XID);
+ assert.equal(siteVideoId({ video: XID }, null), XID, "unknown platform: as written, never guessed from digits");
+ assert.equal(siteVideoId({ video: "a-url-slug", siteVideo: "v2embed" }, "rumble"), "v2embed");
+ assert.equal(siteVideoId({ video: "dQw4w9WgXcQ" }, "youtube"), "dQw4w9WgXcQ");
+});
+
+test("channelPlatform reads config.json (platform, else the url's host); none for an unknown channel", () => {
+ assert.equal(channelPlatform("twitchchan"), "twitch");
+ assert.equal(channelPlatform("twitchbyurl"), "twitch");
+ assert.equal(channelPlatform("xchan"), "x");
+ assert.equal(channelPlatform("ytchan"), "youtube");
+ assert.equal(channelPlatform("nochan"), null);
+ assert.deepEqual(siteRefOf({ video: N, platform: "twitch", channel: "nochan" }), { channel: "nochan", video: `v${N}` }, "an entry's own platform wins");
+ assert.deepEqual(siteRefOf({ video: N, channel: "nochan" }), { channel: "nochan", video: N }, "no config: as written");
+ assert.deepEqual(siteRefOf({ video: "slug", siteVideo: "v9", siteChannel: "site-chan", channel: "local" }), { channel: "site-chan", video: "v9" });
+ assert.equal(archiveMomentUrl({ video: N }, { siteOrigin: ORIGIN, channelSlug: "twitchbyurl" }, 7.9), `${ORIGIN}/?v=twitchbyurl%2Fv${N}&t=7`, "the provenance's channel decides");
+});
+
+test("a Twitch clip with no citeUrl: every builder links v<digits>; an X clip's digits get no v", () => {
+ // the deck's QR (a clip's start)
+ assert.equal(deckQrUrl(twitchClip, prov), twitchUrl(125));
+ assert.equal(deckQrUrl(xClip, prov), xUrl(3));
+ // the YouTube description's moment link (the cited second)
+ assert.equal(momentLinkOf(twitchClip, prov), twitchUrl(130));
+ assert.equal(momentLinkOf(xClip, prov), xUrl(3));
+ // the rail / corner QR (render-cards)
+ assert.equal(qrUrlFor(twitchClip, prov), twitchUrl(130));
+ assert.equal(qrUrlFor(xClip, prov), xUrl(3));
+ // the review page's cite link
+ const m = { provenance: prov, timeline: [twitchClip, xClip] };
+ assert.equal(derivedCiteUrl(m, twitchClip), twitchUrl(125));
+ assert.equal(citeUrlFor(m, xClip), xUrl(3));
+ // a citeUrl still wins
+ assert.equal(deckQrUrl({ ...twitchClip, citeUrl: "https://elsewhere/x" }, prov), "https://elsewhere/x");
+});
+
+test("lint measures the same link the corner QR draws", () => {
+ const qrs = qrsOf({ provenance: prov, render: {}, timeline: [twitchClip, xClip] });
+ assert.deepEqual(qrs.map((q) => q.url), [twitchUrl(125), xUrl(3)]);
+});
+
+test("a moment on the cut resolves to the archive's v<digits> page", () => {
+ const schedule = { segments: [{ id: "t01", start: 0, duration: 14.6 }], total: 14.6, transition: 0 };
+ const got = resolveMoment({ schedule, manifest: { provenance: prov, timeline: [twitchClip] }, t: 2 });
+ assert.equal(got.video, N, "the local id stays the local id");
+ assert.equal(got.url, twitchUrl(127));
+});
diff --git a/umtool/report-to-video/youtube.mjs b/umtool/report-to-video/youtube.mjs
@@ -24,6 +24,8 @@
//
// PURE: no fs. build-video.mjs writes the file.
+import { archiveMomentUrl } from "./site-links.mjs";
+
/** YouTube's rules for a description's chapters. */
export const YOUTUBE_CHAPTERS = Object.freeze({ min: 3, minSeconds: 10 });
@@ -98,7 +100,7 @@ export function momentLinkOf(entry, provenance = {}) {
const channel = entry.channel ?? provenance?.channelSlug;
if (!origin || !channel || !entry.video) return null;
const at = Number.isFinite(Number(entry.cite)) ? Number(entry.cite) : Number(entry.start);
- return `${origin}/?v=${encodeURIComponent(`${channel}/${entry.video}`)}&t=${Math.floor(Number.isFinite(at) ? at : 0)}`;
+ return archiveMomentUrl(entry, provenance, at, { origin });
}
/** The cut's moment links, in cut order, each once. */