// The X run (lane x-console): the plan's refusals, the loop (X's gap between // channels, the guard before each, a stale jar deferring the rest, a failed // channel not stopping the run, cancel and drain), Resume, the interrupted // view, the default order — and one whole job through runManagedFunction with // the REAL network guard over a cookie jar on disk that goes stale mid-run. // Every fetch is a stub: nothing reaches X. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/xRun.test.ts import test, { after } 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-run-")); after(() => rmSync(ROOT, { recursive: true, force: true })); // Before getPaths / getSettings are first imported (both cache). process.env.TRANSCRIPTS_DIR = ROOT; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); writeFileSync( process.env.SETTINGS_FILE, JSON.stringify({ social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 60 } }, pacing: { jobGapSeconds: { twitter: 0 } }, }), ); const { getPaths } = await import("../lib/paths"); const xr = await import("./xRun"); // X's gap is drawn in 5-12 min and has no off switch now (lane x-sittings: // jobGapSeconds.twitter 0 no longer turns it off): a fake clock waits it out. const { setQueueGapClock } = await import("../jobs/queueGap"); let skew = 0; setQueueGapClock({ now: () => Date.now() + skew, sleep: async (ms) => void (skew += ms) }); const { defaultChannelPriority } = await import("../lib/channelPriority"); const paths = getPaths(); function channel(slug: string, config: Record) { const dir = path.join(paths.channelsDir, slug); mkdirSync(dir, { recursive: true }); writeFileSync(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", ...config })); } const xChannel = (slug: string) => channel(slug, { sourceKind: "social", platform: "twitter", postFetcher: "x-gallery-dl", socialHandle: slug, url: `https://x.com/${slug}`, }); xChannel("xa"); xChannel("xb"); xChannel("xc"); channel("bsky", { sourceKind: "social", platform: "bluesky", url: "https://bsky.app/profile/a.bsky.social" }); channel("yt", { platform: "youtube", url: "https://www.youtube.com/@someone" }); function jar(ageMs: number) { const dir = path.join(ROOT, ".x-session"); mkdirSync(path.join(dir, "profile"), { recursive: true }); const file = path.join(dir, "cookies.txt"); writeFileSync(file, "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tfake\n"); const t = new Date(Date.now() - ageMs); utimesSync(file, t, t); } type Call = string; function stubDeps(o: { calls: Call[]; stale?: (slug: string) => boolean; fail?: Set; onFetch?: (slug: string) => void; }): import("./xRun").XRunDeps { return { fetch: async (slug, f) => { o.calls.push(`fetch ${slug} limit=${f.limit}`); o.onFetch?.(slug); if (o.fail?.has(slug)) return { ok: false, written: 0, error: "No post fetcher" }; return { ok: true, written: 3 }; }, guard: async (slug) => { o.calls.push(`guard ${slug}`); return o.stale?.(slug) ? { ok: false, error: "X cookies were last refreshed 2 h ago (limit 60 min): press Refresh cookies" } : { ok: true, notes: [] }; }, noteEnd: () => o.calls.push("end"), waitGap: async () => { o.calls.push("gap"); return "waited"; }, }; } const never = () => new AbortController().signal; test("the plan refuses before any job: nothing picked, a stranger, a non-X channel, twice, a limit over 200", async () => { const refuse = async (req: Parameters[1]) => { const r = await xr.planXRun(paths, req); assert.equal(r.ok, false); return (r as { error: string }).error; }; assert.equal(await refuse({ channels: [] }), "Pick one or more X posts channels to run."); assert.equal(await refuse({ channels: ["nope"] }), "No such channel: nope"); assert.equal(await refuse({ channels: ["bsky"] }), "bsky is not an X posts channel."); assert.equal(await refuse({ channels: ["yt"] }), "yt is not an X posts channel."); assert.equal(await refuse({ channels: ["xa", "xa"] }), '"xa" is named twice.'); assert.equal(await refuse({ channels: ["../x"] }), '"../x" is not a valid channel slug.'); assert.match(await refuse({ channels: ["xa"], limit: 201 }), /from 1 to 200/); assert.match(await refuse({ resume: "xr-nope" }), /is not an X run id/); }); test("the loop: X's gap between channels (not before the first), the guard before each, 200 posts each; a stale jar defers the rest", async () => { const plan = await xr.planXRun(paths, { channels: ["xa", "xb", "xc"] }); assert.ok(plan.ok); const calls: Call[] = []; const lines: string[] = []; const r = await xr.runXRun({ paths, state: plan.state, deps: stubDeps({ calls, stale: (s) => s === "xc" }), jobId: "JOB1", onLog: (l) => lines.push(l), signal: never(), drain: never(), }); assert.deepEqual(calls, [ "guard xa", "fetch xa limit=200", "end", "gap", "guard xb", "fetch xb limit=200", "end", "gap", "guard xc", ]); assert.equal(r.status, "deferred"); assert.equal(r.summary, "2 done, 1 deferred until the next refresh"); assert.match(r.stopped!, /^X cookies were last refreshed 2 h ago/); const disk = (await xr.readXRun(paths, plan.state.id))!; assert.deepEqual( disk.channels.map((c) => [c.slug, c.status, c.posts]), [["xa", "done", 3], ["xb", "done", 3], ["xc", "deferred", undefined]], ); assert.deepEqual(disk.jobIds, ["JOB1"]); assert.ok(lines.some((l) => l.startsWith("Stopped before xc: X cookies"))); // RESUME starts with the deferred channel, and only it. const again = await xr.planXRun(paths, { resume: plan.state.id }); assert.ok(again.ok && again.resumed); const calls2: Call[] = []; const r2 = await xr.runXRun({ paths, state: again.state, deps: stubDeps({ calls: calls2 }), jobId: "JOB2", onLog: () => {}, signal: never(), drain: never() }); assert.deepEqual(calls2, ["guard xc", "fetch xc limit=200", "end"]); assert.equal(r2.status, "done"); assert.equal(r2.summary, "3 done"); assert.deepEqual((await xr.readXRun(paths, plan.state.id))!.jobIds, ["JOB1", "JOB2"]); // Nothing left: a second resume is refused with the summary. const none = await xr.planXRun(paths, { resume: plan.state.id }); assert.equal(none.ok, false); assert.match((none as { error: string }).error, /has nothing to resume: 3 done\.$/); }); test("a failed channel is the channel's: the run goes on; a custom limit reaches the fetch", async () => { const plan = await xr.planXRun(paths, { channels: ["xa", "xb"], limit: 50 }); assert.ok(plan.ok); const calls: Call[] = []; const r = await xr.runXRun({ paths, state: plan.state, deps: stubDeps({ calls, fail: new Set(["xa"]) }), onLog: () => {}, signal: never(), drain: never() }); assert.equal(r.status, "done"); assert.equal(r.summary, "1 done, 1 failed"); assert.ok(calls.includes("fetch xb limit=50")); const disk = (await xr.readXRun(paths, plan.state.id))!; assert.equal(disk.channels[0].error, "No post fetcher"); }); test("cancel mid-fetch: the channel and the rest wait for a Resume; drain stops between channels", async () => { const plan = await xr.planXRun(paths, { channels: ["xa", "xb"] }); assert.ok(plan.ok); const abort = new AbortController(); const r = await xr.runXRun({ paths, state: plan.state, deps: stubDeps({ calls: [], onFetch: () => abort.abort() }), onLog: () => {}, signal: abort.signal, drain: never(), }); assert.equal(r.status, "cancelled"); assert.deepEqual(r.counts, { total: 2, queued: 0, running: 0, done: 0, deferred: 2, failed: 0, posts: 0 }); const plan2 = await xr.planXRun(paths, { channels: ["xa", "xb"] }); assert.ok(plan2.ok); const drain = new AbortController(); const r2 = await xr.runXRun({ paths, state: plan2.state, deps: stubDeps({ calls: [], onFetch: () => drain.abort() }), onLog: () => {}, signal: never(), drain: drain.signal, }); assert.equal(r2.status, "drained"); assert.equal(r2.summary, "1 done, 1 deferred until the next refresh"); }); test("the view: a run whose file says running with no live job was interrupted — its unfinished channels deferred and resumable", () => { const state: import("./xRun").XRunState = { version: 1, id: "xr-01JZZZZZZZZZZZZZZZZZZZZZZZ", createdAt: "", updatedAt: "", limit: 200, status: "running", waitingUntil: "2026-11-09T12:00:00.000Z", jobIds: ["J"], channels: [ { slug: "a", status: "done", posts: 4 }, { slug: "b", status: "running" }, { slug: "c", status: "queued" }, ], }; const dead = xr.xRunView(state, null); assert.equal(dead.interrupted, true); assert.equal(dead.status, "deferred"); assert.equal(dead.summary, "1 done, 2 deferred until the next refresh"); assert.equal(dead.resumable, 2); assert.equal(dead.waitingUntil, undefined); const live = xr.xRunView(state, { id: "J", status: "running" }); assert.equal(live.interrupted, false); assert.equal(live.resumable, 0); assert.equal(live.summary, "1 done, 2 to go"); assert.equal(live.waitingUntil, "2026-11-09T12:00:00.000Z"); }); test("the default order is Sync all's: focus, then the sync tier, then rank (unranked last), then slug", () => { const p = defaultChannelPriority(); p.channels = { low1: { tier: "low" }, norm2: { tier: "normal", rank: 2 }, norm1: { tier: "normal", rank: 1 }, paused: { tier: "paused" }, syncLow: { tier: "normal", overrides: { sync: "low" } }, } as typeof p.channels; const order = xr.defaultXRunOrder(["paused", "low1", "zeta", "norm2", "syncLow", "norm1", "focused"], p, new Set(["focused"])); assert.deepEqual(order, ["focused", "norm1", "norm2", "zeta", "low1", "syncLow", "paused"]); }); test("one whole job, the REAL guard: the jar goes stale during the second channel, so the third is deferred; then a refreshed jar and Resume", async () => { jar(60_000); const fetched: string[] = []; const deps = (jobId: string) => ({ ...xr.defaultXRunDeps(paths, jobId), fetch: async (slug: string) => { fetched.push(slug); // Time passes: the jar is two hours old once xb's fetch ends. if (slug === "xb") jar(2 * 60 * 60_000); return { ok: true, written: 1 }; }, }); const res = await xr.queueXRun({ paths, req: { channels: ["xa", "xb", "xc"] }, deps }); assert.ok(res.ok, (res as { error?: string }).error); assert.equal((await res.done).status, "done"); assert.deepEqual(fetched, ["xa", "xb"]); const view = (await xr.readXRunView(paths, res.run))!; assert.equal(view.status, "deferred"); assert.equal(view.summary, "2 done, 1 deferred until the next refresh"); assert.match(view.stopped!, /^X cookies were last refreshed 2 h ago \(limit 60 min\)/); assert.equal(view.resumable, 1); assert.equal(view.live, false); // A stale jar refuses the Resume before any job (the guard at enqueue), and // the run stays deferred. const refused = await xr.queueXRun({ paths, req: { resume: res.run }, deps }); assert.equal(refused.ok, false); assert.match((refused as { error: string }).error, /^X cookies were last refreshed/); assert.equal((await xr.readXRunView(paths, res.run))!.resumable, 1); // The operator refreshes the jar; Resume runs the deferred channel. jar(0); const resumed = await xr.queueXRun({ paths, req: { resume: res.run }, deps }); assert.ok(resumed.ok, (resumed as { error?: string }).error); assert.equal((await resumed.done).status, "done"); assert.deepEqual(fetched, ["xa", "xb", "xc"]); const end = (await xr.readXRunView(paths, res.run))!; assert.equal(end.status, "done"); assert.equal(end.summary, "3 done"); assert.equal(end.jobIds.length, 2); // The latest run is this one. assert.equal((await xr.readXRunView(paths))!.id, res.run); }); test("a stale jar at the start refuses the new run before a job; its file is deferred for a Resume", async () => { jar(16 * 24 * 60 * 60_000); const res = await xr.queueXRun({ paths, req: { channels: ["xa"] } }); assert.equal(res.ok, false); assert.match((res as { error: string }).error, /16 days ago/); const view = (await xr.readXRunView(paths, res.run))!; assert.equal(view.status, "deferred"); assert.equal(view.summary, "0 done, 1 deferred until the next refresh"); }); test("every stop path defers what has not run, and Resume takes it: cancel before a channel, cancel or drain in X's gap, a thrown error", async () => { const resumable = async (id: string) => (await xr.readXRunView(paths, id))!.resumable; const run = async (deps: import("./xRun").XRunDeps, signal = never(), drain = never()) => { const plan = await xr.planXRun(paths, { channels: ["xa", "xb", "xc"] }); assert.ok(plan.ok); let threw: Error | null = null; const r = await xr .runXRun({ paths, state: plan.state, deps, onLog: () => {}, signal, drain }) .catch((e: Error) => ((threw = e), null)); const disk = (await xr.readXRun(paths, plan.state.id))!; return { id: plan.state.id, r, threw: threw as Error | null, disk }; }; const statuses = (d: import("./xRun").XRunState) => d.channels.map((c) => c.status); // Cancelled before the first channel. const pre = new AbortController(); pre.abort(); const a = await run(stubDeps({ calls: [] }), pre.signal); assert.equal(a.disk.status, "cancelled"); assert.deepEqual(statuses(a.disk), ["deferred", "deferred", "deferred"]); assert.equal(await resumable(a.id), 3); // Cancelled while waiting X's gap after the first channel. const b = await run({ ...stubDeps({ calls: [] }), waitGap: async () => "aborted" }); assert.equal(b.disk.status, "cancelled"); assert.deepEqual(statuses(b.disk), ["done", "deferred", "deferred"]); assert.equal(await resumable(b.id), 2); // Drained while waiting X's gap. const c = await run({ ...stubDeps({ calls: [] }), waitGap: async () => "drained" }); assert.equal(c.disk.status, "drained"); assert.deepEqual(statuses(c.disk), ["done", "deferred", "deferred"]); // The guard throws on the second channel: the run fails, nothing is lost. let n = 0; const d = await run({ ...stubDeps({ calls: [] }), guard: async () => { if (++n === 2) throw new Error("settings unreadable"); return { ok: true, notes: [] }; }, }); assert.equal(d.threw?.message, "settings unreadable"); assert.equal(d.disk.status, "failed"); assert.equal(d.disk.stopped, "settings unreadable"); assert.deepEqual(statuses(d.disk), ["done", "deferred", "deferred"]); assert.equal(await resumable(d.id), 2); const again = await xr.planXRun(paths, { resume: d.id }); assert.ok(again.ok); assert.deepEqual(again.state.channels.map((ch) => ch.status), ["done", "queued", "queued"]); // A file left with queued/running channels by a stopped run (a crash, an // older build) still reads them as resumable. const e = await xr.planXRun(paths, { channels: ["xa", "xb"] }); assert.ok(e.ok); e.state.status = "cancelled"; e.state.channels[0].status = "running"; await xr.writeXRun(paths, e.state); assert.equal(await resumable(e.state.id), 2); }); test("two clicks at once queue one run: the second is refused while the first is being queued", async () => { jar(0); const gate: { open?: () => void } = {}; const opened = new Promise((r) => (gate.open = r)); const deps = (jobId: string) => ({ ...xr.defaultXRunDeps(paths, jobId), fetch: async () => { await opened; return { ok: true, written: 0 }; }, }); const [one, two] = await Promise.all([ xr.queueXRun({ paths, req: { channels: ["xa"] }, deps }), xr.queueXRun({ paths, req: { channels: ["xb"] }, deps }), ]); const oks = [one, two].filter((r) => r.ok); assert.equal(oks.length, 1); const refused = [one, two].find((r) => !r.ok) as { error: string }; assert.match(refused.error, /one at a time/); // And while the first runs, a third is refused by the registry check. const three = await xr.queueXRun({ paths, req: { channels: ["xc"] }, deps }); assert.equal(three.ok, false); assert.match((three as { error: string }).error, /already queued or running/); gate.open!(); assert.equal((await (oks[0] as { done: Promise<{ status: string }> }).done).status, "done"); }); test("runs are pruned to the newest X_RUN_KEEP when a new one is made", async () => { const before = await xr.listXRunIds(paths); const removed = await xr.pruneXRuns(paths, 2); assert.equal(removed.length, Math.max(0, before.length - 2)); assert.deepEqual(await xr.listXRunIds(paths), before.slice(0, 2)); assert.equal(xr.X_RUN_KEEP, 100); });