// THE X RUN (lane x-console, 9 Nov). On 8 and 9 Nov an agent ran X // `fetch-posts` jobs by hand, one channel after another, watching the cookie // jar age and deferring the rest when the jar went stale. This is that, as ONE // editor job (`x-run`, on the X queue `platform:twitter`) with a console on // /review: // // - the channels are the operator's, in the operator's order (the console // defaults to the channel priority tiers: focus, normal, low, paused, then // rank, then slug); // - each channel is ONE `fetchPosts` (controller/fetchPosts.ts — the same // fetcher a channel's Sync new runs; there is no second one), capped at // `limit` posts (X_RUN_MAX_POSTS, 200); // - between two channels the job waits X's queue gap exactly as two // fetch-posts jobs would (`pacing.jobGapSeconds.twitter`, jittered, via // jobs/queueGap.ts: the end is noted, the gap waited); // - BEFORE EACH CHANNEL the network guard is asked again (the fresh-jar rule // and the X alert, jobs/networkGuard.ts). When it refuses, the run STOPS // there and every channel not yet fetched is DEFERRED. Nothing here ever // refreshes the jar: a refresh is the operator's click on /cookies // (refreshXCookies loads x.com/home — itself a request to X); // - a deferred run is resumed by its id (the console's Resume, `pnpm ops // x-run {"resume": id}`, a Retry of the job): it starts with the deferred // channels, in the order they had. // // THE STATE is a file per run, `/.x-runs/.json`, written // at every transition, so the console reads it while the job runs and after // the editor restarts. // // AN INTERRUPTED RUN ENDS DEFERRED; IT IS NOT RESUMED ON BOOT (the kind does // not declare `resumeOnBoot`). A restart can come minutes or hours after the // run began, and an X sequence that starts by itself on boot is the // unattended pattern the fresh-jar rule exists to stop. The state file still // says `running` for a dead job; the view reads that as interrupted, its // unfinished channels as deferred, and Resume runs them when the operator // says so. import path from "node:path"; import { readdir, rm } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; import { getSettings } from "../lib/settings"; import { isValidChannelSlug, listChannelConfigs, readChannelConfig } from "./channels"; import { isSocialChannel } from "../lib/channelConfig"; import { isWaybackPagesChannel } from "../lib/waybackPages/config"; import { isXSearchChannel } from "../lib/xSearch/config"; import { isXTrendingChannel } from "../lib/xTrending/config"; import { readPostFetchState, countPosts } from "../lib/posts-server"; import { effectiveTier, rankOf, resolveFocusSlugs, tierOrder, type ChannelPriority, type ChannelTier, } from "../lib/channelPriority"; import { siteChannelIndex } from "../lib/site"; import { ulid } from "../jobs/ulid"; import { getRegistry } from "../jobs/registry"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { guardNetworkJob, xSessionReport, type XSessionReport } from "../jobs/networkGuard"; import { noteQueueJobEnd, queueGapClock, waitForQueueGap, xQueueGapRange } from "../jobs/queueGap"; import { requestChannelSnapshot } from "../jobs/snapshotScheduler"; import { fetchPosts } from "./fetchPosts"; import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "../lib/sourcelessPosts"; export const X_RUN_JOB_KIND = "x-run"; // X's platform queue: the run serialises with every other X job (a channel's // own fetch-posts, a capture) and is spaced from them by X's gap. export const X_RUN_QUEUE = "platform:twitter"; // At most this many posts per channel per run (the fetch's own `limit`, // gallery-dl's `--post-range 1-N`). export const X_RUN_MAX_POSTS = 200; export const X_RUN_MAX_CHANNELS = 500; export const X_RUN_RESULT_MARKER = "@@x-run "; // A spec needs a slug; the replay reads params.run (the state holds the list). export const X_RUN_SPEC_SLUG = "_x-run"; export type XRunChannelStatus = "queued" | "running" | "done" | "deferred" | "failed"; export type XRunChannel = { slug: string; status: XRunChannelStatus; // New posts written (done; a failed fetch that checkpointed some, too). posts?: number; error?: string; startedAt?: string; endedAt?: string; }; // queued: made, its job waiting; running; done: every channel ran; // deferred: the guard stopped it, some channels deferred; cancelled; drained; // failed: the run itself broke (not a channel's fetch — that is the channel's). export type XRunStatus = "queued" | "running" | "done" | "deferred" | "cancelled" | "drained" | "failed"; export type XRunState = { version: 1; id: string; createdAt: string; updatedAt: string; limit: number; status: XRunStatus; // Why the run stopped short (the guard's sentence, a drain, a cancel). stopped?: string; // While the job waits X's gap before the next channel: until when (ISO). waitingUntil?: string; // Every job that ran this run, oldest first (a resume adds one). jobIds: string[]; channels: XRunChannel[]; }; export function xRunDir(paths: Pick): string { return path.join(path.dirname(paths.jobsDir), ".x-runs"); } const RUN_ID = /^xr-[0-9A-Z]{26}$/; export function isXRunId(id: unknown): id is string { return typeof id === "string" && RUN_ID.test(id); } export function xRunPath(paths: Pick, id: string): string { return path.join(xRunDir(paths), `${id}.json`); } function parseRun(raw: unknown): XRunState | null { if (!raw || typeof raw !== "object") return null; const r = raw as Partial; if (r.version !== 1 || !isXRunId(r.id) || !Array.isArray(r.channels)) return null; const channels: XRunChannel[] = []; for (const c of r.channels) { if (!c || typeof c !== "object" || typeof c.slug !== "string") continue; const status = (["queued", "running", "done", "deferred", "failed"] as const).includes(c.status) ? c.status : "queued"; channels.push({ ...c, status }); } return { version: 1, id: r.id, createdAt: typeof r.createdAt === "string" ? r.createdAt : "", updatedAt: typeof r.updatedAt === "string" ? r.updatedAt : "", limit: typeof r.limit === "number" && r.limit > 0 ? Math.min(r.limit, X_RUN_MAX_POSTS) : X_RUN_MAX_POSTS, status: typeof r.status === "string" ? r.status : "queued", ...(typeof r.stopped === "string" ? { stopped: r.stopped } : {}), ...(typeof r.waitingUntil === "string" ? { waitingUntil: r.waitingUntil } : {}), jobIds: Array.isArray(r.jobIds) ? r.jobIds.filter((j): j is string => typeof j === "string") : [], channels, }; } export async function readXRun(paths: Pick, id: string): Promise { if (!isXRunId(id)) return null; const read = await readJsonFile(xRunPath(paths, id)); return read.ok ? parseRun(read.value) : null; } export async function writeXRun(paths: Pick, state: XRunState, now = Date.now()): Promise { state.updatedAt = new Date(now).toISOString(); await writeJsonAtomic(xRunPath(paths, state.id), state, { mkdir: true }); } // The runs on disk, newest first (a run id is a ULID: it sorts by time). export async function listXRunIds(paths: Pick): Promise { let names: string[]; try { names = await readdir(xRunDir(paths)); } catch { return []; } return names .filter((n) => n.endsWith(".json")) .map((n) => n.slice(0, -".json".length)) .filter(isXRunId) .sort() .reverse(); } // The run files kept: the newest X_RUN_KEEP; older ones are removed when a // new run is made (a run's file is its console row and its Resume, nothing // else reads it). export const X_RUN_KEEP = 100; export async function pruneXRuns(paths: Pick, keep = X_RUN_KEEP): Promise { const old = (await listXRunIds(paths)).slice(keep); for (const id of old) await rm(xRunPath(paths, id), { force: true }).catch(() => {}); return old; } export async function latestXRun(paths: Pick): Promise { for (const id of await listXRunIds(paths)) { const run = await readXRun(paths, id); if (run) return run; } return null; } // ── counting and saying ──────────────────────────────────────────────────── export type XRunCounts = { total: number; queued: number; running: number; done: number; deferred: number; failed: number; // New posts written across the done channels. posts: number; }; export function xRunCounts(channels: readonly XRunChannel[]): XRunCounts { const c: XRunCounts = { total: channels.length, queued: 0, running: 0, done: 0, deferred: 0, failed: 0, posts: 0 }; for (const ch of channels) { c[ch.status]++; if (ch.status === "done") c.posts += ch.posts ?? 0; } return c; } // "3 done, 2 deferred until the next refresh" (+ ", 1 failed"; + ", 4 to go"). export function xRunSummary(counts: XRunCounts): string { const parts = [`${counts.done} done`]; if (counts.deferred > 0) parts.push(`${counts.deferred} deferred until the next refresh`); if (counts.failed > 0) parts.push(`${counts.failed} failed`); const toGo = counts.queued + counts.running; if (toGo > 0) parts.push(`${toGo} to go`); return parts.join(", "); } // THE RUN AS THE CONSOLE AND `get x-run` SHOW IT. `live` is whether its last // job is queued or running in this process. A run whose file says queued or // running but whose job is not live was INTERRUPTED (a restart, a crash): its // unfinished channels are shown deferred, and Resume runs them. export type XRunView = XRunState & { live: boolean; interrupted: boolean; jobId: string | null; counts: XRunCounts; summary: string; // Channels a Resume would run (deferred, and an interrupted run's unfinished). resumable: number; }; export function xRunView(state: XRunState, liveJob: { id: string; status: string } | null): XRunView { const live = !!liveJob && (liveJob.status === "queued" || liveJob.status === "running"); const jobId = live ? liveJob!.id : (state.jobIds.at(-1) ?? null); const interrupted = !live && (state.status === "queued" || state.status === "running"); // A run that is not live has nothing running: an unfinished channel in a // file written before every stop path deferred (or by a crash) reads as // deferred, so Resume counts it. const channels = !live ? state.channels.map((c) => c.status === "queued" || c.status === "running" ? { ...c, status: "deferred" as const } : c, ) : state.channels; const counts = xRunCounts(channels); const { waitingUntil, ...rest } = state; return { ...rest, ...(live && waitingUntil ? { waitingUntil } : {}), ...(interrupted ? { status: "deferred" as const, stopped: "Interrupted: the editor stopped while the run was in progress." } : {}), channels, live, interrupted, jobId, counts, summary: xRunSummary(counts), resumable: live ? 0 : counts.deferred, }; } // The x-run jobs queued or running in this process; a job's run is its // spec's `params.run` (known before the job starts, unlike its id in the file). function liveXRunJobs(): { id: string; status: string; run: string | null }[] { return getRegistry() .list() .filter((j) => j.kind === X_RUN_JOB_KIND && (j.status === "queued" || j.status === "running")) .map((j) => { const run = j.spec?.params?.run; return { id: j.id, status: j.status, run: typeof run === "string" ? run : null }; }); } function liveJobFor(state: XRunState): { id: string; status: string } | null { return liveXRunJobs().find((j) => j.run === state.id) ?? null; } export async function readXRunView(paths: Pick, id?: string): Promise { const state = id ? await readXRun(paths, id) : await latestXRun(paths); return state ? xRunView(state, liveJobFor(state)) : null; } // ── the channels a run may take ──────────────────────────────────────────── export type XRunCandidate = { slug: string; name: string; // The base tier the default order reads ("focus" when the focus names it). tier: ChannelTier; rank: number | null; // An X search channel (its query's windows), not an account timeline. search: boolean; postCount: number; lastFetchedAt: string | null; lastFetchedCount: number | null; lastError: string | null; }; type ConfigLike = Parameters[0] & { platform?: string; name?: string; xSearch?: unknown; wayback?: unknown; }; // An X posts channel (an account's timeline or an X search): what a run takes. export function isXPostsChannel(config: ConfigLike | null | undefined): boolean { return ( !!config && isSocialChannel(config) && config.platform === "twitter" && !isWaybackPagesChannel(config as Parameters[0]) && // A trending library has nothing an X run can fetch. !isXTrendingChannel(config as Parameters[0]) && // Nor have posts published from one: no account, no search. !isSourcelessPostsChannel(config as Parameters[0]) ); } // THE DEFAULT ORDER: the order *Sync all* queues in (editor channels/actions.ts // syncAllChannelsAction) — focus, then the `sync` tier, then rank (unranked // last), then slug. export function defaultXRunOrder( slugs: readonly string[], priority: ChannelPriority, focus: ReadonlySet, ): string[] { const tierOf = (s: string): ChannelTier => (focus.has(s) ? "focus" : effectiveTier(priority, s, "sync")); const rank = (a: number | null, b: number | null) => (a === b ? 0 : a === null ? 1 : b === null ? -1 : a - b); return [...slugs].sort( (a, b) => tierOrder(tierOf(a)) - tierOrder(tierOf(b)) || rank(rankOf(priority, a), rankOf(priority, b)) || a.localeCompare(b), ); } export async function listXRunCandidates(paths: Paths): Promise { const all = await listChannelConfigs(paths); const x = all.filter((c) => isXPostsChannel(c.config)); const priority = getSettings().channelPriority; const focus = new Set(resolveFocusSlugs(priority, siteChannelIndex(paths), all.map((c) => c.slug))); const bySlug = new Map(x.map((c) => [c.slug, c.config])); const order = defaultXRunOrder(x.map((c) => c.slug), priority, focus); return Promise.all( order.map(async (slug): Promise => { const config = bySlug.get(slug)!; const root = path.join(paths.channelsDir, slug); const [state, postCount] = await Promise.all([ readPostFetchState(root).catch(() => null), countPosts(root).catch(() => 0), ]); return { slug, name: config.name ?? slug, tier: focus.has(slug) ? "focus" : effectiveTier(priority, slug, "sync"), rank: rankOf(priority, slug), search: isXSearchChannel(config), postCount, lastFetchedAt: state?.lastFetchedAt ?? null, lastFetchedCount: state?.lastFetchedCount ?? null, lastError: state?.lastError ?? null, }; }), ); } // ── planning ─────────────────────────────────────────────────────────────── export type XRunRequest = { // A new run over these channels, in this order. channels?: readonly unknown[]; // Posts per channel, at most X_RUN_MAX_POSTS (the default). limit?: number; // Resume this run: its deferred channels (and an interrupted run's // unfinished ones), in the order they had. resume?: string; }; export type XRunPlan = { ok: true; state: XRunState; resumed: boolean } | { ok: false; error: string }; export function xRunLimitProblem(limit: unknown): string | null { if (limit === undefined) return null; if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > X_RUN_MAX_POSTS) { return `"limit" is the posts per channel, a whole number from 1 to ${X_RUN_MAX_POSTS}.`; } return null; } // The run a request names, made or prepared to resume — refused, with the // sentence, before any job exists. Writes the state (a new run's file; a // resume's channels back to queued). export async function planXRun(paths: Paths, req: XRunRequest, now = Date.now()): Promise { const live = liveXRunJobs()[0]; if (live) { return { ok: false, error: `An X run is already queued or running (job ${live.id}): one at a time.` }; } if (req.resume !== undefined) { if (req.channels !== undefined) return { ok: false, error: '"resume" and "channels" are one at a time.' }; if (!isXRunId(req.resume)) return { ok: false, error: `"${String(req.resume)}" is not an X run id.` }; const state = await readXRun(paths, req.resume); if (!state) return { ok: false, error: `No X run ${req.resume}.` }; const view = xRunView(state, null); if (view.resumable === 0) { return { ok: false, error: `X run ${state.id} has nothing to resume: ${view.summary}.` }; } for (const c of state.channels) { if (c.status === "deferred" || c.status === "queued" || c.status === "running") { c.status = "queued"; delete c.error; delete c.startedAt; delete c.endedAt; } } if (req.limit !== undefined) { const problem = xRunLimitProblem(req.limit); if (problem) return { ok: false, error: problem }; state.limit = req.limit; } state.status = "queued"; delete state.stopped; delete state.waitingUntil; await writeXRun(paths, state, now); return { ok: true, state, resumed: true }; } const problem = xRunLimitProblem(req.limit); if (problem) return { ok: false, error: problem }; const raw = req.channels ?? []; if (!Array.isArray(raw) || raw.length === 0) return { ok: false, error: "Pick one or more X posts channels to run." }; if (raw.length > X_RUN_MAX_CHANNELS) return { ok: false, error: `At most ${X_RUN_MAX_CHANNELS} channels in one run.` }; const slugs: string[] = []; for (const s of raw) { if (!isValidChannelSlug(s)) return { ok: false, error: `"${String(s)}" is not a valid channel slug.` }; if (slugs.includes(s)) return { ok: false, error: `"${s}" is named twice.` }; const config = await readChannelConfig(paths, s); if (!config) return { ok: false, error: `No such channel: ${s}` }; if (isSourcelessPostsChannel(config)) return { ok: false, error: SOURCELESS_POSTS_CHANNEL(s) }; if (!isXPostsChannel(config)) return { ok: false, error: `${s} is not an X posts channel.` }; slugs.push(s); } const at = new Date(now).toISOString(); const state: XRunState = { version: 1, id: `xr-${ulid(now)}`, createdAt: at, updatedAt: at, limit: req.limit ?? X_RUN_MAX_POSTS, status: "queued", jobIds: [], channels: slugs.map((slug) => ({ slug, status: "queued" })), }; await writeXRun(paths, state, now); await pruneXRuns(paths); return { ok: true, state, resumed: false }; } // ── the run ──────────────────────────────────────────────────────────────── export type XRunFetchResult = { ok: boolean; written: number; error?: string; drained?: boolean }; export type XRunDeps = { // One channel's fetch (production: fetchPosts, sync new, capped). fetch: ( slug: string, o: { limit: number; onLog: (line: string) => void; signal: AbortSignal; drain: AbortSignal }, ) => Promise; // The network guard, asked before each channel (production: guardNetworkJob). guard: (slug: string) => Promise<{ ok: true; notes: string[] } | { ok: false; error: string }>; // A channel's fetch ended: noted as the X queue's last end. noteEnd: () => void; // X's gap before the next channel. "drained"/"aborted" when it was cut. waitGap: (o: { signal: AbortSignal; drain: AbortSignal; onLog: (line: string) => void; onWait: (until: number | null) => void; }) => Promise<"waited" | "drained" | "aborted">; // A channel's fetch ended (production: its report regenerates). channelDone?: (slug: string) => void; now?: () => number; }; export type XRunResult = { id: string; status: XRunStatus; stopped?: string; counts: XRunCounts; summary: string; }; // THE LOOP, its effects behind `deps` (tested with stubs; no X). export async function runXRun(opts: { paths: Pick; state: XRunState; deps: XRunDeps; jobId?: string; onLog: (line: string) => void; signal: AbortSignal; drain: AbortSignal; onProgress?: (p: { done: number; total: number }) => void; }): Promise { const { paths, state, deps, onLog, signal, drain } = opts; const now = deps.now ?? Date.now; const save = () => writeXRun(paths, state, now()); const iso = () => new Date(now()).toISOString(); if (opts.jobId && !state.jobIds.includes(opts.jobId)) state.jobIds.push(opts.jobId); state.status = "running"; delete state.stopped; await save(); const total = state.channels.length; const settled = () => state.channels.filter((c) => c.status !== "queued" && c.status !== "running").length; const todo = state.channels.filter((c) => c.status === "queued"); onLog( `X run ${state.id}: ${todo.length} channel(s), at most ${state.limit} posts each, ` + `X's queue gap between them; the cookie jar is checked before each.`, ); opts.onProgress?.({ done: settled(), total }); // EVERY STOP PATH ENDS HERE: what has not run (queued, and one cut while // running) is deferred — a Resume takes exactly those — and the run says why. const stop = (status: XRunStatus, reason: string) => { for (const c of state.channels) if (c.status === "queued" || c.status === "running") c.status = "deferred"; state.status = status; state.stopped = reason; }; let stoppedEarly = false; let first = true; try { for (const ch of todo) { if (signal.aborted) { stop("cancelled", "Cancelled."); stoppedEarly = true; break; } if (drain.aborted) { stop("drained", "Drained: the channels not yet fetched stay for a Resume."); stoppedEarly = true; break; } // The run's first channel follows the job's own gap (runManagedFunction // waited it); every later one waits X's gap after the one before. if (!first) { const waited = await deps.waitGap({ signal, drain, onLog, onWait: (until) => { if (until === null) delete state.waitingUntil; else state.waitingUntil = new Date(until).toISOString(); save().catch((err) => onLog(`[warn] could not save the run's wait: ${(err as Error).message}`)); }, }); delete state.waitingUntil; if (waited === "aborted") { stop("cancelled", "Cancelled while waiting for X's gap."); stoppedEarly = true; break; } if (waited === "drained") { stop("drained", "Drained while waiting for X's gap: the channels not yet fetched stay for a Resume."); stoppedEarly = true; break; } } // THE JAR, BEFORE EACH CHANNEL. A refusal stops the run: this channel and // every one after it wait for the next refresh. const g = await deps.guard(ch.slug); if (!g.ok) { onLog(`Stopped before ${ch.slug}: ${g.error}`); stop("deferred", g.error); stoppedEarly = true; break; } for (const note of g.notes) onLog(note); first = false; ch.status = "running"; ch.startedAt = iso(); delete ch.error; await save(); onLog(`── ${ch.slug} (${state.channels.indexOf(ch) + 1}/${total}) ──`); let r: XRunFetchResult; try { r = await deps.fetch(ch.slug, { limit: state.limit, onLog, signal, drain }); } catch (err) { r = { ok: false, written: 0, error: (err as Error).message }; } deps.noteEnd(); deps.channelDone?.(ch.slug); ch.endedAt = iso(); if (signal.aborted) { // Cancelled mid-fetch: what it checkpointed is on disk; the channel // runs again on a Resume. if (r.written > 0) ch.posts = r.written; stop("cancelled", "Cancelled."); stoppedEarly = true; break; } ch.posts = r.written; if (r.ok) { ch.status = "done"; onLog(`${ch.slug}: ${r.written} new post(s).`); } else { ch.status = "failed"; ch.error = r.error ?? "Post fetch failed"; onLog(`${ch.slug} failed: ${ch.error}`); } await save(); opts.onProgress?.({ done: settled(), total }); if (r.drained) { stop("drained", "Drained: the channels not yet fetched stay for a Resume."); stoppedEarly = true; break; } } } catch (err) { // The run itself broke (a state write, the guard): nothing unfinished is // lost — it is deferred, and Resume takes it. stop("failed", (err as Error).message); delete state.waitingUntil; await save().catch(() => {}); throw err; } if (!stoppedEarly) { const left = state.channels.some((c) => c.status === "deferred"); state.status = left ? "deferred" : "done"; } delete state.waitingUntil; await save(); const counts = xRunCounts(state.channels); const summary = xRunSummary(counts); onLog(`X run ${state.id}: ${summary}${state.stopped ? ` — ${state.stopped}` : ""}.`); return { id: state.id, status: state.status, ...(state.stopped ? { stopped: state.stopped } : {}), counts, summary }; } // The production deps: fetchPosts (sync new, capped), the network guard, X's // queue gap and its end, the channel's report. export function defaultXRunDeps(paths: Paths, jobId: string): XRunDeps { return { fetch: async (slug, o) => { const r = await fetchPosts({ paths, slug, settings: getSettings(), limit: o.limit, onLog: o.onLog, signal: o.signal, drain: o.drain, }); return { ok: r.ok, written: r.written, ...(r.error ? { error: r.error } : {}), ...(r.drained ? { drained: true } : {}) }; }, guard: async (slug) => { const res = await guardNetworkJob({ kind: X_RUN_JOB_KIND, queueKey: X_RUN_QUEUE, paths, channelSlug: slug, job: { id: jobId }, // Each channel's fetch is one X job against X's job cap. countStart: true, }); return res.ok ? { ok: true, notes: res.notes } : { ok: false, error: res.error }; }, noteEnd: () => void noteQueueJobEnd(paths, X_RUN_QUEUE, queueGapClock().now()), waitGap: async (o) => { try { await waitForQueueGap({ paths, queueKey: X_RUN_QUEUE, pacing: () => getSettings().pacing, signal: AbortSignal.any([o.signal, o.drain]), onLog: o.onLog, onWait: (w) => o.onWait(w ? w.until : null), clock: queueGapClock(), }); return "waited"; } catch (err) { if (o.signal.aborted) return "aborted"; if (o.drain.aborted) return "drained"; throw err; } }, channelDone: (slug) => requestChannelSnapshot(paths, slug), }; } // THE JOB: one `x-run` on X's queue, made or resumed. Refused (no job) with // the plan's sentence — or by the network guard (a stale jar, the X alert), // in which case a new run's file is marked deferred so Resume can take it // once the jar is fresh. export async function queueXRun(opts: { paths: Paths; req: XRunRequest; deps?: (jobId: string) => XRunDeps; onChannelDone?: (slug: string) => void; now?: number; }): Promise { // ONE AT A TIME, ALSO BETWEEN THE CHECK AND THE ENQUEUE: planXRun asks the // registry for a live x-run, but awaits file I/O before the job exists, so // two clicks on Resume could both pass it. A process-wide flag (globalThis: // a server action and a route are separate module graphs) closes the gap; // once runManagedFunction returns, the job is in the registry. if (globalThis.__yttXRunStarting__) { return { ok: false, error: "An X run is being queued right now: one at a time." }; } globalThis.__yttXRunStarting__ = true; try { return await queueXRunNow(opts); } finally { globalThis.__yttXRunStarting__ = false; } } declare global { // eslint-disable-next-line no-var var __yttXRunStarting__: boolean | undefined; } async function queueXRunNow(opts: Parameters[0]): Promise { const planned = await planXRun(opts.paths, opts.req, opts.now); if (!planned.ok) return { ok: false, error: planned.error }; const { state } = planned; const res = await runManagedFunction({ kind: X_RUN_JOB_KIND, queueKey: X_RUN_QUEUE, paths: opts.paths, spec: { kind: X_RUN_JOB_KIND, slug: X_RUN_SPEC_SLUG, params: { run: state.id } }, fn: async (onLog, signal, setProgress, ctx) => { // Re-read at the start: a queued job runs the state as it is then. const fresh = (await readXRun(opts.paths, state.id)) ?? state; const base = opts.deps ? opts.deps(ctx.jobId) : defaultXRunDeps(opts.paths, ctx.jobId); const deps: XRunDeps = { ...base, channelDone: (slug) => { base.channelDone?.(slug); opts.onChannelDone?.(slug); }, }; let r: XRunResult; try { r = await runXRun({ paths: opts.paths, state: fresh, deps, jobId: ctx.jobId, onLog, signal, drain: ctx.drainSignal, onProgress: (p) => setProgress({ metric: "channels", initial: 0, target: p.total, current: p.done }), }); } catch (err) { // runXRun has deferred the unfinished channels; make sure the file // says so even when the break came before it began. for (const c of fresh.channels) if (c.status === "queued" || c.status === "running") c.status = "deferred"; fresh.status = "failed"; fresh.stopped = (err as Error).message; await writeXRun(opts.paths, fresh).catch(() => {}); throw err; } onLog(`${X_RUN_RESULT_MARKER}${JSON.stringify(r)}`); if (r.status === "cancelled") throw new Error("cancelled"); }, }); if (!res.ok) { // Refused before a job existed (a stale jar at enqueue): the run's // channels wait for the next refresh, and Resume takes them. const back = await readXRun(opts.paths, state.id); if (back) { for (const c of back.channels) if (c.status === "queued") c.status = "deferred"; back.status = "deferred"; back.stopped = res.error; await writeXRun(opts.paths, back); } return { ...res, run: state.id }; } // The job id joins the file when the job starts (runXRun): a write here // would race the job's own. return { ...res, run: state.id }; } // ── the console's payload (the /review console, `pnpm ops get x-run`) ────── export type XRunJar = Pick< XSessionReport, "source" | "cookiesUpdatedAt" | "ageMinutes" | "maxAgeMinutes" | "ageChecked" | "allowed" | "reason" | "alert" > & { // When the jar passes social.x.maxCookieAgeMinutes (ISO), when the age is // checked and a jar exists: the console counts down to it. staleAt: string | null; }; export type XRunConsole = { run: XRunView | null; candidates: XRunCandidate[]; jar: XRunJar; // X's queue gap between two channels, seconds: drawn per channel from // [gapSeconds, gapMaxSeconds] (social.x.gapMinMinutes / gapMaxMinutes). gapSeconds: number; gapMaxSeconds: number; maxPosts: number; }; export function xRunJar(report: XSessionReport): XRunJar { const staleAt = report.ageChecked && report.cookiesUpdatedAt ? new Date(Date.parse(report.cookiesUpdatedAt) + report.maxAgeMinutes * 60_000).toISOString() : null; return { source: report.source, cookiesUpdatedAt: report.cookiesUpdatedAt, ageMinutes: report.ageMinutes, maxAgeMinutes: report.maxAgeMinutes, ageChecked: report.ageChecked, allowed: report.allowed, reason: report.reason, alert: report.alert, staleAt, }; } // Nothing here asks X or writes: the jar is read from disk (xSessionReport), // the runs and the channels from theirs. export async function xRunConsole(paths: Paths, runId?: string): Promise { const [run, candidates, report] = await Promise.all([ readXRunView(paths, runId), listXRunCandidates(paths), xSessionReport({ paths }), ]); let range = xQueueGapRange(undefined, undefined); try { const settings = getSettings(); range = xQueueGapRange(settings.pacing, settings.social?.x); } catch { /* the defaults */ } return { run, candidates, jar: xRunJar(report), gapSeconds: range.minSeconds, gapMaxSeconds: range.maxSeconds, maxPosts: X_RUN_MAX_POSTS }; }