// Review 2 N1: a watch's job asks the watch's own jar rule AT ITS START, over a // real settings file and a real (made-up) exported jar — the two cases the // guard every X job meets lets through: a cookie-age setting of 0, and the // browser as the login source. No browser opens and nothing is asked of X. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/xTrendingWatchJob.test.ts import { after, test } from "node:test"; import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; const ROOT = mkdtempSync(path.join(tmpdir(), "x-trending-watch-job-")); process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); after(() => rmSync(ROOT, { recursive: true, force: true })); const { getPaths } = await import("../lib/paths"); const { guardNetworkJob } = await import("../jobs/networkGuard"); const { recordXTrendingRead, readXTrendingTopics, writeXTrendingPosts } = await import("../lib/xTrending/store"); const { readXTrendingWatches, setXTrendingWatch } = await import("../lib/xTrending/watch"); const { refuseWatchJob, noteXTrendingWatchRead } = await import("./xTrendingWatch"); const { planReadXTrending, runXTrendingRead: runXTrendingReadDirect } = await import("./readXTrending"); // X is asked only inside a job of the editor's, on X's queue (lib/xJobRule.ts): these calls stand where one does. const { insideEditorJob } = await import("../testing/jobs/asEditorJob"); const runXTrendingRead = insideEditorJob(runXTrendingReadDirect); const { FIXTURE_TREND_ID, FIXTURE_TREND_URL } = await import("../social/__fixtures__/xTrendingCapture"); const paths = getPaths(); const SLUG = "trending"; const root = path.join(paths.channelsDir, SLUG); const jar = path.join(paths.transcriptsDir, ".x-session", "cookies.txt"); const MIN = 60_000; mkdirSync(root, { recursive: true }); writeFileSync(path.join(root, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", name: "Trending", xTrending: {} })); mkdirSync(path.join(paths.transcriptsDir, ".x-session", "profile"), { recursive: true }); writeFileSync(jar, "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tfixture-not-a-real-token\n"); await writeXTrendingPosts(root, [ { id: "9001", slug: `${SLUG}/9001`, channelSlug: SLUG, author: "a", createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text: "t", url: "https://x.com/a/status/9001", platform: "twitter", isReply: false, isRepost: false, links: [] }, ]); await recordXTrendingRead(root, { readId: "tr-01JA0000000000000000000000", at: "2026-11-17T10:00:00.000Z", ref: { trendId: FIXTURE_TREND_ID, url: FIXTURE_TREND_URL }, topic: "Kettles", postIds: ["9001"], added: 1 }); // The two settings under which the guard's own start check lets an old jar through. const EXEMPT: Record = { "the cookie-age setting is 0": { social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 0 } } }, "the login comes from the browser": { social: { x: { cookieSource: "browser", maxCookieAgeMinutes: 60 } }, cookiesFromBrowser: "firefox" }, }; async function watchOn(): Promise { const set = await setXTrendingWatch(root, { topics: await readXTrendingTopics(root), topic: "kettles", on: true, intervalMinutes: 30, hours: 48, by: "operator", maxTopics: 4, now: Date.now() }); assert.equal(set.ok, true); } const jarAged = (minutes: number) => { const at = new Date(Date.now() - minutes * MIN); utimesSync(jar, at, at); }; for (const [name, settings] of Object.entries(EXEMPT)) { test(`N1: a watch tick whose turn comes on a 78-minute jar is not read, though the guard would start it — ${name}`, async () => { writeFileSync(paths.settingsFile, JSON.stringify(settings)); await watchOn(); // Queued on a 58-minute jar: the watch's rule lets it be queued. jarAged(58); assert.equal(await refuseWatchJob(paths, SLUG), null); const planned = await planReadXTrending(paths, { slug: SLUG, url: FIXTURE_TREND_URL, watch: true }, { hasProfile: async () => true, held: async () => null }); assert.equal(planned.ok, true); if (!planned.ok || planned.plan.mode !== "read") return; assert.equal(planned.plan.watch, true); // Twenty minutes behind another X job: 78 minutes. The guard an X job meets at its start still says yes... jarAged(78); const guard = await guardNetworkJob({ kind: "read-x-trending", queueKey: "platform:twitter", paths, channelSlug: SLUG, job: { id: "j1" } }); assert.equal(guard.ok, true, "the control: the guard alone would start this job"); // ...and the watch's own rule, asked at the job's start, says no: no browser opens. let opened = 0; const log: string[] = []; const result = await runXTrendingRead({ paths, plan: planned.plan, onLog: (l) => log.push(l), deps: { openPage: async () => { opened++; throw new Error("no browser may open"); }, held: async () => null, watchRefusal: () => refuseWatchJob(paths, SLUG), }, }); assert.equal(opened, 0); assert.equal(result.ok, false); assert.equal(result.watchRefused?.reason, "jar"); assert.match(result.sentence, /^This watch tick was not read \(no browser was opened, X was asked nothing\): X cookies were last refreshed 78 min ago \(limit 60 min for a watch\)/); // The watch is paused for the jar, and it is no strike against it. const w = (await readXTrendingWatches(root)).kettles; assert.deepEqual([w.paused?.reason, w.failures], ["jar", 0]); // THE FOLLOW-UP CAPTURE asks the same question before it is queued and when it starts. await watchOn(); assert.equal((await readXTrendingWatches(root)).kettles.paused?.reason, "jar"); const followUp = await refuseWatchJob(paths, SLUG); assert.equal(followUp?.reason, "jar"); assert.match(followUp?.sentence ?? "", /78 min ago \(limit 60 min for a watch\)/); // Refreshed: both go ahead. jarAged(1); assert.equal(await refuseWatchJob(paths, SLUG), null); }); } test("N1: a read marked as a watch's with no check at its start does not run; a person's read is not asked the watch's rule", async () => { writeFileSync(paths.settingsFile, JSON.stringify(EXEMPT["the cookie-age setting is 0"])); jarAged(78); const plan = async (watch: boolean) => { const p = await planReadXTrending(paths, { slug: SLUG, url: FIXTURE_TREND_URL, ...(watch ? { watch: true } : {}) }, { hasProfile: async () => true, held: async () => null }); assert.equal(p.ok, true); return (p as { plan: Parameters[0]["plan"] }).plan; }; let opened = 0; const openPage = async () => { opened++; throw new Error("stop here"); }; const unchecked = await runXTrendingRead({ paths, plan: await plan(true), deps: { openPage, held: async () => null } }); assert.equal(opened, 0); assert.match(unchecked.sentence, /started with no check of X's cookie jar, so it is not run/); // A person's read (no `watch`) goes on to open the page: the setting is the person's choice. const person = await runXTrendingRead({ paths, plan: await plan(false), deps: { openPage, held: async () => null, noteOutcome: async () => null } }); assert.equal(opened, 1); assert.equal(person.watchRefused, undefined); // (That failed read is told to the watch as any read is.) await noteXTrendingWatchRead(root, { trendId: FIXTURE_TREND_ID, outcome: person.outcome }); }); test("N1: a watch's tick on a fresh jar is read as any read, and its record and log say it was a watch's", async () => { const { fakeTrendingPage } = await import("../social/fakeXProfileBrowser"); const { fixtureTrendingResponses } = await import("../social/__fixtures__/xTrendingCapture"); const { readXTrendingReadRecord } = await import("../lib/xTrending/store"); writeFileSync(paths.settingsFile, JSON.stringify({ social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 60 } } })); jarAged(5); const planned = await planReadXTrending(paths, { slug: SLUG, url: FIXTURE_TREND_URL, watch: true }, { hasProfile: async () => true, held: async () => null }); assert.equal(planned.ok, true); if (!planned.ok || planned.plan.mode !== "read") return; const page = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() })); const log: string[] = []; let asked = 0; const READ = "tr-01JW0000000000000000000000"; const result = await runXTrendingRead({ paths, plan: planned.plan, onLog: (l) => log.push(l), deps: { openPage: async () => ({ page, close: async () => {} }), held: async () => null, pauseMs: () => 0, pause: async () => {}, readId: READ, noteOutcome: async () => null, watchRefusal: async () => (asked++, refuseWatchJob(paths, SLUG)), }, }); assert.equal(asked, 1); assert.equal(result.outcome, "read"); assert.equal(result.watchRefused, undefined); assert.equal((await readXTrendingReadRecord(root, READ))?.watch, true); assert.ok(log.some((l) => / A watch's tick\.$/.test(l)), log[0]); });