// One press at a time per service, and its result recorded // (cookieRefreshGuard.ts). Over a temp transcripts dir; the jobs are handed in. // // Run with: pnpm -C editor exec tsx --test app/lib/cookieRefreshGuard.test.ts import test from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import type { Paths } from "yt-dlp-transcript-common/lib/paths"; import { readServiceCookieState } from "yt-dlp-transcript-common/lib/serviceCookies-server"; import { recheckOutcome, runningCookieActions, withCookieAction } from "./cookieRefreshGuard"; const root = await mkdtemp(path.join(os.tmpdir(), "cookie-guard-")); const paths = { transcriptsDir: root } as Paths; test.after(() => rm(root, { recursive: true, force: true })); const noJobs = () => []; test("a second press while the first runs is refused with a sentence, then allowed once it ends", async () => { let release!: () => void; const gate = new Promise((r) => (release = r)); let runs = 0; const first = withCookieAction( "x", "refresh", async () => { runs++; await gate; return { ok: true as const }; }, () => ({ ok: true, message: "Cookies refreshed." }), { paths, jobs: noJobs }, ); // While it runs: shown as running, and a second press is refused, not queued. assert.equal(runningCookieActions([]).x?.action, "refresh"); const second = await withCookieAction("x", "refresh", async () => ({ ok: true as const }), () => ({ ok: true, message: "" }), { paths, jobs: noJobs, }); assert.equal(second.ok, false); assert.match((second as { error: string }).error, /^X's refresh is already running \(since \d\d:\d\d:\d\d UTC\) — wait for it to finish\.$/); assert.equal(runs, 1); // Another service is not held by X's press. const other = await withCookieAction("rumble", "recheck", async () => ({ ok: true as const }), () => ({ ok: true, message: "clean", result: "clean" }), { paths, jobs: noJobs, }); assert.equal(other.ok, true); release(); assert.deepEqual(await first, { ok: true }); assert.equal(runningCookieActions([]).x, undefined); const state = await readServiceCookieState(paths); assert.equal(state.actions?.x?.message, "Cookies refreshed."); assert.equal(state.actions?.x?.ok, true); assert.equal(state.actions?.rumble?.result, "clean"); }); test("a recheck job queued or running on the service's queue counts as in flight", async () => { const jobs = () => [ { id: "j1", kind: "recheck-service-cookies", queueKey: "service-cookies:rumble", status: "running", queuedAt: 0, startedAt: Date.parse("2026-11-16T09:31:00Z") }, { id: "j2", kind: "recheck-service-cookies", queueKey: "service-cookies:youtube", status: "done", queuedAt: 0 }, { id: "j3", kind: "download", queueKey: "service-cookies:odysee", status: "running", queuedAt: 0 }, ]; assert.deepEqual(runningCookieActions(jobs()), { rumble: { action: "recheck", since: "2026-11-16T09:31:00.000Z", jobId: "j1" }, }); let ran = false; const r = await withCookieAction("rumble", "recheck", async () => { ran = true; return { ok: true as const }; }, () => ({ ok: true, message: "" }), { paths, jobs }); assert.equal(ran, false); assert.match((r as { error: string }).error, /Rumble's recheck is already running \(since 09:31:00 UTC\)/); }); test("a press that throws is recorded as failed and the mark is released", async () => { await assert.rejects( withCookieAction("archive.today", "connect", async () => { throw new Error("no display"); }, () => ({ ok: true, message: "" }), { paths, jobs: noJobs }), /no display/, ); assert.equal(runningCookieActions([])["archive.today"], undefined); const a = (await readServiceCookieState(paths)).actions?.["archive.today"]; assert.equal(a?.ok, false); assert.equal(a?.message, "no display"); assert.equal(a?.action, "connect"); }); test("a recheck that answers stale or failed is remembered as not ok; clean is ok", async () => { assert.deepEqual(recheckOutcome({ ok: true, jobId: "j", result: "stale", message: "Rumble still refused." }), { ok: false, result: "stale", message: "Rumble still refused.", jobId: "j", }); assert.equal(recheckOutcome({ ok: true, jobId: "j", result: "failed", message: "m" }).ok, false); assert.equal(recheckOutcome({ ok: true, jobId: "j", result: "clean", message: "m" }).ok, true); assert.deepEqual(recheckOutcome({ ok: false, error: "ended failed", jobId: "k" }), { ok: false, message: "ended failed", jobId: "k" }); // Through the guard, as the action records it. await withCookieAction( "youtube", "recheck", async () => ({ ok: true as const, jobId: "j9", result: "stale" as const, message: "YouTube still refused." }), recheckOutcome, { paths, jobs: noJobs }, ); const a = (await readServiceCookieState(paths)).actions?.youtube; assert.equal(a?.ok, false); assert.equal(a?.result, "stale"); }); test("a describe that throws keeps the press's answer and releases the mark", async () => { const r = await withCookieAction( "odysee", "recheck", async () => ({ ok: true as const, n: 1 }), () => { throw new Error("describe broke"); }, { paths, jobs: noJobs }, ); assert.deepEqual(r, { ok: true, n: 1 }); assert.equal(runningCookieActions([]).odysee, undefined); }); test("a throw before the press (finding the paths) never leaves the service marked busy", async () => { const opts = { jobs: noJobs, get paths(): Paths { throw new Error("no paths"); }, }; await assert.rejects( withCookieAction("rumble", "recheck", async () => ({ ok: true }), () => ({ ok: true, message: "" }), opts), /no paths/, ); assert.equal(runningCookieActions([]).rumble, undefined); }); // --- lane x-trending: one browser on the X profile at a time --- test("X's Connect and Refresh are refused while a job holds the profile's browser; nothing else is", async () => { const { xProfileJobRunning } = await import("./cookieRefreshGuard"); const at = Date.parse("2026-11-17T10:02:11Z"); const reading = () => [{ id: "J1", kind: "read-x-trending", queueKey: "platform:twitter", status: "running", queuedAt: 0, startedAt: at }]; const capturing = () => [{ id: "J2", kind: "capture-posts", queueKey: "platform:twitter", channelSlug: "acct-x", status: "running", queuedAt: 0, startedAt: at }]; // The job's PLATFORM decides (review 2 N6), looked up by its channel. const platformOf = (slug: string | undefined) => (slug === "acct-x" ? "twitter" : slug === "acct-bsky" ? "bluesky" : null); let ran = 0; const press = (service: string, action: "connect" | "refresh" | "recheck", jobs: () => never[]) => withCookieAction(service, action, async () => { ran++; return { ok: true as const }; }, () => ({ ok: true, message: "done" }), { paths, jobs, platformOf }); const refused = await press("x", "connect", reading as never); assert.deepEqual(refused, { ok: false, busy: true, error: "X's connect opens the connected profile, and a job is using it: Read X trending page (J1, running since 10:02:11 UTC). " + "Cancel it on /jobs or wait for it to finish, then press again.", }); const refresh = await press("x", "refresh", capturing as never); assert.match((refresh as { error: string }).error, /^X's refresh opens the connected profile, and a job is using it: Capture posts \(J2,/); assert.equal(ran, 0); // The refused press left no mark: X is not shown as running. assert.equal(runningCookieActions([]).x, undefined); // A queued read holds nothing yet; a capture on another platform's queue, a // fetch on X's, a recheck of X and another service's press are not held. const idle = [ { id: "J3", kind: "read-x-trending", queueKey: "platform:twitter", status: "queued", queuedAt: 0 }, { id: "J4", kind: "capture-posts", queueKey: "platform:bluesky", channelSlug: "acct-bsky", status: "running", queuedAt: 0 }, { id: "J5", kind: "fetch-posts", queueKey: "platform:twitter", channelSlug: "acct-x", status: "running", queuedAt: 0 }, { id: "J6", kind: "read-x-trending", queueKey: "platform:twitter", status: "done", queuedAt: 0 }, // A Bluesky capture moved onto X's queue opens no X profile. { id: "J7", kind: "capture-posts", queueKey: "platform:twitter", channelSlug: "acct-bsky", status: "running", queuedAt: 0 }, // An X capture that takes no shot opens no browser. { id: "J8", kind: "capture-posts", queueKey: "platform:twitter", channelSlug: "acct-x", status: "running", queuedAt: 0, spec: { params: { shots: false } } }, ]; assert.equal(xProfileJobRunning(idle, platformOf), null); // A queue override does not hide a job that holds the profile (N6). for (const hidden of [ { id: "J9", kind: "capture-posts", queueKey: "my-own-queue", channelSlug: "acct-x", status: "running", queuedAt: 0, startedAt: at }, { id: "J10", kind: "read-x-trending", queueKey: "elsewhere", status: "running", queuedAt: 0, startedAt: at }, { id: "J11", kind: "capture-posts", queueKey: "my-own-queue", channelSlug: "acct-x", status: "running", queuedAt: 0, startedAt: at, spec: { params: { shots: false, avatarsOnly: true } } }, ]) { assert.equal(xProfileJobRunning([hidden], platformOf)?.jobId, hidden.id); const r = await press("x", "connect", (() => [hidden]) as never); assert.equal((r as { busy?: boolean }).busy, true, hidden.id); } assert.deepEqual(await press("x", "refresh", (() => idle) as never), { ok: true }); assert.deepEqual(await press("x", "recheck", reading as never), { ok: true }); assert.deepEqual(await press("rumble", "refresh", reading as never), { ok: true }); assert.equal(ran, 3); }); test("a trending read is refused while X's Connect or Refresh is in flight, and only then", async () => { const { xPressInFlight } = await import("./cookieRefreshGuard"); assert.equal(xPressInFlight(), null); let release!: () => void; const gate = new Promise((r) => (release = r)); const connecting = withCookieAction("x", "connect", async () => { await gate; return { ok: true as const }; }, () => ({ ok: true, message: "Connected." }), { paths, jobs: noJobs }); assert.match( xPressInFlight() ?? "", /^X's connect is running \(since \d\d:\d\d:\d\d UTC\) and holds the connected profile: read the trending page once it has finished\.$/, ); // The same at an X capture's start (N6: by the job's platform, whatever // its queue; a capture that takes no shot opens no browser). const { xCaptureStartRefusal } = await import("./cookieRefreshGuard"); const now = Date.parse("2026-11-17T10:00:00Z"); assert.match( xCaptureStartRefusal({ platform: "twitter" }, 0, now) ?? "", /^X's connect is running \(since \d\d:\d\d:\d\d UTC\) and holds the connected profile: capture these posts once it has finished\.$/, ); assert.match(xCaptureStartRefusal({ platform: "twitter", shots: false, contextOnly: true }, 0, now) ?? "", /^X's connect is running/); assert.equal(xCaptureStartRefusal({ platform: "twitter", shots: false }, 0, now), null); assert.equal(xCaptureStartRefusal({ platform: "bluesky" }, 0, now), null); assert.equal(xCaptureStartRefusal({ platform: "xenforo" }, 15 * 60_000, now), null); release(); await connecting; assert.equal(xPressInFlight(), null); assert.equal(xCaptureStartRefusal({ platform: "twitter" }, 0, now), null); // N5: X cooling down after a rate limit holds an X capture too, shot or no // shot (its media comes from X), and the sentence names the time. assert.equal( xCaptureStartRefusal({ platform: "twitter", shots: false }, 12 * 60_000, now), "X answered a rate limit (429) a short while ago: no X capture starts before 10:12 UTC (12 min from now). Ask again then; nothing retries by itself.", ); assert.match(xCaptureStartRefusal({ platform: "twitter" }, 1, now) ?? "", /no X capture starts before 10:00 UTC \(1 min from now\)/); // A Refresh holds it as a Connect does. let done!: () => void; const hold = new Promise((r) => (done = r)); const refreshing = withCookieAction("x", "refresh", async () => { await hold; return { ok: true as const }; }, () => ({ ok: true, message: "Cookies refreshed." }), { paths, jobs: noJobs }); assert.match(xCaptureStartRefusal({ platform: "twitter" }, 0, now) ?? "", /^X's refresh is running/); done(); await refreshing; // A recheck of X opens no profile: a read is not held by it. let free!: () => void; const wait = new Promise((r) => (free = r)); const rechecking = withCookieAction("x", "recheck", async () => { await wait; return { ok: true as const }; }, () => ({ ok: true, message: "clean" }), { paths, jobs: noJobs }); assert.equal(xPressInFlight(), null); free(); await rechecking; });