commit c9fd8dcc0f2f7fbe05673a7d4921c4fb40a8722d
parent 39b82e85c3aeede0dfb8b5b5f316350fec90a2dc
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 1 Nov 2026 00:08:58 -0400
cookie alerts on a timer: Rumble's clearance probed before a sync fails, raised alerts rechecked, X's jar age re-read — settings.serviceCookies (every 3 h, jittered; 0 off), never stacking, never retrying, not on an idle boot
- common/controller/serviceCookieTimer.ts: one tick per interval — X's jar from disk (a jar-age banner clears once fresh; X jobs queued on an old jar raise it), every raised alert with something to ask rechecked once (as the banner's Recheck, a recheck-service-cookies job), and each probe service (default Rumble) with no alert asked once for its last clean video; a Rumble embed 403 is confirmed once on the previous, different known-good video a jittered minute later. Skipped while a job is queued or running on the platform's queues, while it cools down or is held, when it answered cleanly within the interval, or while a recheck of it runs; the next tick is armed only when one ends.
- settings.serviceCookies {recheckIntervalMinutes: 180 (0 off, 30-1440), probeServices: ["rumble"]} (SETTINGS.md, settings.json.example regenerated); settable with pnpm ops settings.
- lastGood keeps the previous, different clean URL (prev) for the confirmation; recheck takes a target.
- instrumentation arms it below the idle gate and not on the e2e test server.
- get services carries x (the jar's age, read from disk) and timer (its last tick); the X banner shows the jar line. COMMANDS.md regenerated.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
15 files changed, 946 insertions(+), 17 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/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.ts b/common/controller/recheckServiceCookies.ts
@@ -162,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 };
@@ -171,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 };
@@ -196,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));
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/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.ts b/common/lib/serviceCookies.ts
@@ -226,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;
@@ -322,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;
}
@@ -438,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;
}
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/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";
@@ -63,6 +73,14 @@ 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}
@@ -126,7 +144,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,26 @@ export async function loadCookieAlerts(
const replayable = Boolean(live?.spec ?? meta?.spec);
if (status && replayable) statuses.set(id, status);
}
- return buildServiceCookieAlerts(state, {
+ const payload = buildServiceCookieAlerts(state, {
now,
browser: configuredCookieBrowser(),
statusOf: (id) => statuses.get(id),
});
+ // 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;
+ }
+ if (settings) {
+ try {
+ payload.x = await readXJarAge(paths, settings, { maxAgeMinutes: resolvedXMaxCookieAgeMinutes(settings), now });
+ } catch {
+ /* no X login to read */
+ }
+ }
+ payload.timer = serviceCookieTimerView(settings?.serviceCookies.recheckIntervalMinutes);
+ return payload;
}
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/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"
+ ]
}
}