commit 049260b34f2f89eed7d5e64efd8c3705107069ca
parent 7afea3ba551600c014a4a3f31f17e97958e8f8bb
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 1 Nov 2026 02:00:17 -0500
Merge lane/cookie-alerts-1031: an X cookie-refresh banner like Rumble's (gallery-dl lines classified: challenge / login failure / rate limit / one account; a jar-age alert from the fresh-jar rule, its age read from disk by name) and Rumble probed on a timer (settings.serviceCookies, every 3 h jittered; never stacking, never retrying)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
31 files changed, 2088 insertions(+), 65 deletions(-)
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/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/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/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"
+ ]
}
}