// READ ONE X TRENDING PAGE INTO A LIBRARY (lane x-trending, slice 1) — the // editor's `read-x-trending`, ONE job on X's queue (`platform:twitter`) per // page: the network guard's fresh-jar rule, X alert and X's job gap apply to // it as to every X job (jobs/networkGuard.ts), and it serialises with every // capture, fetch and X run. // // - the page is opened in the connected X profile's browser and what the // page itself fetched is saved raw (social/xTrendingRead.ts); // - the posts are then parsed FROM THE SAVED FILE (social/xTrendingParse.ts) // and written as the library's posts (month shards, deduped by id, under // the library's own trending/ — store.ts xTrendingPostsRoot says why not // where a posts channel keeps them), and the read is recorded against a topic // (lib/xTrending/store.ts). A re-read adds posts and never drops one; // - nothing else is fetched: no media, no thread, no screenshot of a post. // Archiving a post is a separate step (slice 2). // // `probe` saves the capture and its summary and writes no post — the first // real read, from which the parser learns the page's shape. A normal read is // safe to be that first read too: a capture with no post the parser knows // ends "read saved, nothing recognised", capture kept, NOT a failure and no // X alert. `reparse` parses a saved capture again, offline (its own kind, // `reparse-x-trending`: no request, so no jar is asked of it). // // EVERY FAILURE IS ONE SENTENCE AND NOTHING RETRIES: a login wall (which // raises the X alert, stopping every X job), a 429 (pacing, never cookies: no // alert — and X is left alone for X_RATE_LIMIT_HOLD_MS, 15 minutes, a // cooldown the next read's enqueue and start both refuse on), a 403 (its own // sentence, no alert), a page X no longer has, a page that did not load or // stopped answering. What was read before the failure is kept. // // read.json IS ALWAYS THERE (review 1): it is written when the read starts // (as a read that did not finish), and again when it ends, whatever the // parse did — so a capture can always be parsed again offline. import path from "node:path"; import type { Paths } from "../lib/paths"; import { stat } from "node:fs/promises"; import { noteXServiceOutcome } from "../lib/serviceCookies-server"; import { heldPlatformRefusal, platformCooldownRemainingMs, recordXStop, } from "../jobs/downloadBackoff"; import { isXTrendingChannel, NOT_A_TRENDING_URL, NOT_AN_X_TRENDING_LIBRARY, parseXTrendingUrl, xRateLimitHoldSentence, xTrendingLimits, type XTrendingLimits, type XTrendingRef, } from "../lib/xTrending/config"; import { ensureXTrendingReadsDir, isXTrendingReadId, readXTrendingPostIds, readXTrendingPosts, readXTrendingReadRecord, xTrendingThreadKey, recordXTrendingRead, topicTitleProblem, TRENDING_DIRNAME, TRENDING_READS_DIRNAME, TRENDING_RESPONSES_FILENAME, trendingReadDir, writeXTrendingPosts, writeXTrendingReadRecord, type XTrendingReadOperation, type XTrendingReadOutcome, type XTrendingReadRecord, type XTrendingReadTab, } from "../lib/xTrending/store"; import { ulid } from "../jobs/ulid"; import { xJobContextRefusal } from "../lib/xJobRule"; import { readXSessionStatus } from "../social/xSessionBroker"; import { xRequestPauseMs } from "../social/xGalleryDlFetcher"; import type { ChromiumLike } from "../social/playwrightRuntime"; import { parseTrendingCapture, readCaptureLines } from "../social/xTrendingParse"; import { openXTrendingPage, readXTrendingPage, TRENDING_PAGE_CHANGED, TRENDING_TAB_ASKS, type TrendingPageRead, type TrendingPageSession, type TrendingTabAsk, type TrendingTabRead, } from "../social/xTrendingRead"; import { isValidChannelSlug, readChannelConfig } from "./channels"; export { READ_X_TRENDING_KIND, REPARSE_X_TRENDING_KIND, X_PROFILE_BROWSER_JOB_KINDS, X_TRENDING_QUEUE, } from "../lib/xTrending/config"; export const READ_X_TRENDING_RESULT_MARKER = "@@read-x-trending "; // How long X is left alone after it answered a read with 429: X's own // rate-limit window. Written as the `twitter` platform cooldown // (jobs/downloadBackoff.ts recordPlatformCooldown — the cooldown import-post // already respects), read by this job's enqueue and start. export { X_RATE_LIMIT_HOLD_MS } from "../lib/xJobRule"; import { xJobPostLimit } from "../lib/xSitting"; import { getSettings } from "../lib/settings"; // WHAT ONE READ MAY TAKE (review 2 G3): its posts over all its tabs stay // within social.x.maxPostsPerJob (default 300; the code's ceiling bounds it). export function xTrendingPostsPerTab(asked: number, tabs: number, x: { maxPostsPerJob?: number } | undefined): number { return Math.max(1, Math.min(asked, Math.floor(xJobPostLimit(x) / Math.max(1, tabs)))); } function xPostsSettingNow(): { maxPostsPerJob?: number } | undefined { try { return getSettings().social?.x; } catch { return undefined; } } import { X_RATE_LIMIT_HOLD_MS } from "../lib/xJobRule"; const X_PLATFORM = "twitter"; const hhmm = (ms: number) => new Date(ms).toISOString().slice(11, 16); // Why no trending read may start now — X is cooling down after a rate limit, // or held — or null. export async function xTrendingHeld(paths: Paths, now: number = Date.now()): Promise { const held = await heldPlatformRefusal(X_PLATFORM, "This trending read", paths, now).catch(() => null); if (held) return held; const ms = await platformCooldownRemainingMs(X_PLATFORM, paths).catch(() => 0); if (ms <= 0) return null; return xRateLimitHoldSentence("trending read", ms, now); } export const NO_X_PROFILE_FOR_TRENDING = "Reading a trending page needs the connected X profile (the browser that stays logged in): " + "connect an X account on /cookies, then read it again."; export type ReadXTrendingAsk = { slug: string; // A trending page to read… url?: string; // …or a saved read's id, to parse its capture again (offline). reparse?: string; // The topic the posts go into: an existing topic's id or name, or a new // one's name. Absent: the topic this page was read into before, else a new // one named for the page. topic?: string; scrolls?: unknown; posts?: unknown; probe?: boolean; headed?: boolean; // The page's tabs to read: ["top"], ["latest"] or both (the default). Both // are read in ONE job: Top, then the page's Latest tab is pressed. tabs?: unknown; // THIS READ IS A WATCH'S TICK (controller/xTrendingWatch.ts): nobody is // there when it starts, so the watch's own jar rule is asked again at its // start (runXTrendingRead `watchRefusal`). Set by the scan only — the ops // route does not take it. watch?: boolean; }; // The tabs a read is asked for: "top", "latest" or both; absent, both. In the // page's order, each once. Anything else is refused with a sentence. export const X_TRENDING_TABS_PROBLEM = `"tabs" is ["top"], ["latest"] or ["top", "latest"] (the default: both, read in one job)`; export function xTrendingTabsAsked(v: unknown): { ok: true; tabs: TrendingTabAsk[] } | { ok: false; error: string } { if (v === undefined || v === null) return { ok: true, tabs: [...TRENDING_TAB_ASKS] }; if (!Array.isArray(v) || v.length === 0 || !v.every((t) => typeof t === "string" && (TRENDING_TAB_ASKS as readonly string[]).includes(t.toLowerCase()))) { return { ok: false, error: X_TRENDING_TABS_PROBLEM }; } const asked = new Set(v.map((t: string) => t.toLowerCase())); return { ok: true, tabs: TRENDING_TAB_ASKS.filter((t) => asked.has(t)) }; } export type ReadXTrendingPlan = | { mode: "read"; slug: string; channelRoot: string; ref: XTrendingRef; limits: XTrendingLimits; topic?: string; probe: boolean; headed: boolean; tabs: TrendingTabAsk[]; watch?: boolean; } | { mode: "reparse"; slug: string; channelRoot: string; record: XTrendingReadRecord; topic?: string }; // A read left with its answers and no record (a crash before any record was // written, a library from before review 1): the record a reparse starts from. function recordlessRead(readId: string, ref: XTrendingRef, at: string): XTrendingReadRecord { return { version: 1, id: readId, trendId: ref.trendId, url: ref.url, startedAt: at, endedAt: at, probe: false, headed: false, limits: { scrolls: 0, posts: 0 }, scrolls: 0, stop: "unknown", outcome: "error", responses: 0, saved: 0, bytes: 0, statuses: {}, operations: [], posts: { onPage: 0, added: 0 }, shot: false, sentence: "This read left its answers and no record.", }; } // Everything checked before a job exists: the plan, or the refusal's sentence. export async function planReadXTrending( paths: Paths, ask: ReadXTrendingAsk, deps: { hasProfile?: () => Promise; held?: () => Promise; // Whether a read-x-trending job of this library is queued or running // (the editor asks its registry): a record still marked "started" then // belongs to a read in flight, not to one that died. readInFlight?: () => Promise; } = {}, ): Promise<{ ok: true; plan: ReadXTrendingPlan } | { ok: false; error: string }> { const fail = (error: string) => ({ ok: false as const, error }); // The slug becomes a path below: checked here, whoever the caller is. if (!isValidChannelSlug(ask.slug)) { return fail(`"${String(ask.slug)}" is not a valid channel slug (letters, digits, ".", "_", "-"; must start with a letter or digit)`); } const config = await readChannelConfig(paths, ask.slug); if (!config) return fail(`No such channel: ${ask.slug}`); if (!isXTrendingChannel(config)) return fail(NOT_AN_X_TRENDING_LIBRARY(ask.slug)); const channelRoot = path.join(paths.channelsDir, ask.slug); const hasUrl = ask.url !== undefined && ask.url !== ""; const hasReparse = ask.reparse !== undefined && ask.reparse !== ""; if (!hasUrl && !hasReparse) { return fail(`Give "url" (a trending page to read) or "reparse" (a saved read's id), one of them.`); } if (ask.topic !== undefined) { const problem = topicTitleProblem(ask.topic); if (problem) return fail(problem); } const topic = ask.topic?.trim(); if (hasReparse) { if (ask.probe || ask.headed || ask.scrolls !== undefined || ask.posts !== undefined || ask.tabs !== undefined) { return fail(`"probe", "headed", "scrolls", "posts" and "tabs" apply to a read of a page, not to "reparse" (which asks X nothing).`); } if (!isXTrendingReadId(ask.reparse)) return fail(`"${String(ask.reparse)}" is not a trending read id (tr-…)`); let record = await readXTrendingReadRecord(channelRoot, ask.reparse); if (record && hasUrl) { return fail(`Give "url" (a trending page to read) or "reparse" (a saved read's id), one of them.`); } if (!record) { // Its answers without its record: parsed all the same, once the caller // says which page it was (the record is what knew). const capture = path.join(trendingReadDir(channelRoot, ask.reparse), TRENDING_RESPONSES_FILENAME); const saved = await stat(capture).catch(() => null); if (!saved?.isFile()) { return fail(`${ask.slug} holds no saved read ${ask.reparse} (pnpm ops get trending ${ask.slug} lists them).`); } const ref = hasUrl ? parseXTrendingUrl(ask.url) : null; if (!ref) { return fail( `Saved read ${ask.reparse} has its answers but no record of which page it read: ` + `give "url" (that trending page, https://x.com/i/trending/) with "reparse".`, ); } record = recordlessRead(ask.reparse, ref, saved.mtime.toISOString()); } // A read that has not ended (review 2 N7): its record is the one written // when it started, and its capture is still being written. if (record.stop === "started" && (await deps.readInFlight?.())) { return fail(`Read ${ask.reparse} is still running: parse it again once it has finished (its job is on /jobs).`); } return { ok: true, plan: { mode: "reparse", slug: ask.slug, channelRoot, record, ...(topic ? { topic } : {}) } }; } if (hasReparse) return fail(`Give "url" (a trending page to read) or "reparse" (a saved read's id), one of them.`); const ref = parseXTrendingUrl(ask.url); if (!ref) return fail(NOT_A_TRENDING_URL); const limits = xTrendingLimits(config.xTrending, { scrolls: ask.scrolls, posts: ask.posts }); if (!limits.ok) return fail(limits.error); const tabs = xTrendingTabsAsked(ask.tabs); if (!tabs.ok) return fail(tabs.error); const hasProfile = deps.hasProfile ?? (async () => (await readXSessionStatus(paths)).hasProfile); if (!(await hasProfile())) return fail(NO_X_PROFILE_FOR_TRENDING); // X cooling down after a rate limit: refused before a job exists. const held = await (deps.held ?? (() => xTrendingHeld(paths)))(); if (held) return fail(held); return { ok: true, plan: { mode: "read", slug: ask.slug, channelRoot, ref, // WHAT ONE X JOB MAY READ (review 1 F8): the read's posts over all its // tabs stay within X's per-job ceiling (lib/xSitting.ts). limits: { ...limits.limits, posts: xTrendingPostsPerTab(limits.limits.posts, tabs.tabs.length, xPostsSettingNow()) }, ...(topic ? { topic } : {}), probe: ask.probe === true, headed: ask.headed === true, tabs: tabs.tabs, ...(ask.watch === true ? { watch: true } : {}), }, }; } export type ReadXTrendingResult = { ok: boolean; slug: string; mode: "read" | "probe" | "reparse"; url: string; trendId: string; // The read's id: `channels//trending/reads//`. read: string; outcome: XTrendingReadOutcome; stop?: string; scrolls?: number; // The operation and status of the first answer that stopped the read. stoppedBy?: { op: string; status: number }; responses: number; // Operation names and sizes — never a body. operations: XTrendingReadOperation[]; posts: { onPage: number; added: number }; topic?: { id: string; title: string; created?: boolean; renamed?: { was: string } }; // The read, tab by tab (store.ts XTrendingReadTab): the posts each listed, // its scrolls, why it stopped, whether the capture shows its end; a tab // asked for and not opened is "not-read" with `why`. tabs?: XTrendingReadTab[]; // A watch's tick that was NOT read, because the watch's jar rule refused it // at the job's start: no browser opened, nothing asked of X. It is neither // a read nor a failed read (the watch counts no strike for it). watchRefused?: { reason: string; sentence: string }; // The posts this read added to the library (ids), and the posts the page // showed before and did not show now — "gone from the page", said only by a // read that reached the page's end, and never meaning deleted. newIds?: string[]; gone?: string[]; // Posts ONE TAB read to its end no longer shows, while another still does. goneFromTab?: Array<{ id: string; tab: string }>; // What happened, as one sentence (the refusal, when `ok` is false). sentence: string; error?: string; }; function opsText(ops: ReadonlyArray): string { if (ops.length === 0) return "no GraphQL answer"; return ops .map((o) => `${o.op} ×${o.responses} (${o.bytes} bytes${o.tweets ? `, ${o.tweets} post${o.tweets === 1 ? "" : "s"}` : ""})`) .join(", "); } const plural = (n: number, one: string) => `${n} ${one}${n === 1 ? "" : "s"}`; // Where a read's capture is, as a caller reads it (relative to the channel). function captureAt(readId: string): string { return `${TRENDING_DIRNAME}/${TRENDING_READS_DIRNAME}/${readId}/`; } type Ingested = { operations: XTrendingReadOperation[]; responses: number; onPage: number; added: number; topic?: { id: string; title: string; created: boolean; renamed?: { was: string } }; // The posts this pass added to the library, and — after a read that reached // the page's end — the posts the page showed before and not now. newIds?: string[]; gone?: string[]; // Posts a tab read to its end no longer shows while another tab still does. goneFromTab?: Array<{ id: string; tab: string }>; // Tab by tab (store.ts XTrendingReadRecord.tabs). tabs?: XTrendingReadTab[]; }; // The tab a capture's posts are the page's, when its timelines name exactly one. export function readTabOf(timelines: ReadonlyArray<{ tab?: string }>): string | undefined { const named = [...new Set(timelines.map((t) => t.tab).filter((t): t is string => Boolean(t)))]; return named.length === 1 ? named[0] : undefined; } // `, shown by the page's "Top" tab` — what a read saw, in a sentence; "" when the // capture does not say. function tabText(tabs: Ingested["tabs"]): string { // The tabs that listed posts (one asked for and not read listed none). const named = (tabs ?? []).filter((t) => t.tab && t.stop !== "not-read" && (t.posts > 0 || t.stop !== undefined)); if (named.length === 0) return ""; return `, shown by the page's ${named.map((t) => `"${t.tab}"`).join(" and ")} tab${named.length === 1 ? "" : "s"}`; } // "Top read; Latest not read: ." — a tab that was asked for and could // not be opened. Not a failure: what the other tab showed stands. // "Top read; Latest stopped at the deadline." — the read's deadline fell // inside the second tab (review 2 S2): what that tab had is kept, and it // says nothing of the page's end. function notReadText(tabs: Ingested["tabs"]): string { const missed = (tabs ?? []).filter((t) => t.stop === "not-read" || (t.asked === "latest" && t.stop === "deadline")); if (missed.length === 0) return ""; const read = (tabs ?? []).filter((t) => t.tab && !missed.includes(t) && t.stop !== "not-asked").map((t) => t.tab); const name = (t: XTrendingReadTab) => t.tab ?? (t.asked === "latest" ? "Latest" : "Top"); const what = (t: XTrendingReadTab) => t.stop === "deadline" ? `${name(t)} stopped at the deadline (${plural(t.posts, "post")} read)` : `${name(t)} not read: ${t.why ?? "it could not be opened"}`; return ` ${read.length ? `${read.join(" and ")} read; ` : ""}${missed.map(what).join("; ")}.`; } // "2 posts are gone from the "Latest" tab and still shown by another." function goneFromTabText(goneFromTab: Ingested["goneFromTab"]): string { if (!goneFromTab?.length) return ""; const by = new Map(); for (const g of goneFromTab) by.set(g.tab, (by.get(g.tab) ?? 0) + 1); return [...by].map(([tab, count]) => ` ${plural(count, "post")} ${count === 1 ? "is" : "are"} gone from the "${tab}" tab and still shown by another.`).join(""); } // A topic that took the page's title in this pass, said once. function renamedText(topic: Ingested["topic"]): string { return topic?.renamed ? ` The topic was "${topic.renamed.was}" until now: it took the page's title.` : ""; } // The saved capture → the library: its posts written, the read recorded. // `write: false` (a probe) parses and counts and writes nothing. async function ingestCapture(o: { channelRoot: string; slug: string; readId: string; at: string; ref: XTrendingRef; topic?: string; write: boolean; // THE READ, TAB BY TAB (the page reader's): which tabs were scrolled and why // each stopped. A tab is read to its end — the only read that may say a // post is gone from it — when its scrolling went idle, no answer of the // read failed (`clean`), and the capture itself shows that timeline's end. // Absent for a reparse, which says nothing of what a page no longer shows. pageTabs?: ReadonlyArray; clean?: boolean; // A reparse: the tabs the read's record already has (their scrolls and stops are kept). recordedTabs?: ReadonlyArray; }): Promise { const file = path.join(trendingReadDir(o.channelRoot, o.readId), TRENDING_RESPONSES_FILENAME); const lines = await readCaptureLines(file).catch(() => []); // THE PAGE CHANGED (a press took it elsewhere): only the trend answer's own // timelines are the page's (review 3 S8) — whatever the other page sent // stays in the capture, unread. Said by the reader's tabs, or by the // record's on a reparse. const pageChanged = [...(o.pageTabs ?? []), ...(o.recordedTabs ?? [])].some((t) => t.why === TRENDING_PAGE_CHANGED); const whole = parseTrendingCapture(lines, o.slug, pageChanged ? { pageTabsOnly: true } : {}); // A TAB THE READ SAYS WAS NOT READ gives the library nothing (review 2 // S1): answers for its timeline that came in before the read stopped — a // press that took the page elsewhere — stay in the capture, unread. A post // another timeline listed too is kept. const notRead = (t: { timelineId?: string; tab?: string }) => t.timelineId !== undefined && ((o.pageTabs ?? []).some((r) => r.timelineId === t.timelineId && r.stop === "not-read") || (o.recordedTabs ?? []).some((r) => r.tab !== undefined && r.tab === t.tab && r.stop === "not-read")); const parsed = (() => { const dropped = whole.timelines.filter(notRead); if (dropped.length === 0) return whole; const keptIds = new Set(whole.timelines.filter((t) => !notRead(t)).flatMap((t) => t.postIds)); const droppedIds = new Set(dropped.flatMap((t) => t.postIds).filter((id) => !keptIds.has(id))); return { ...whole, timelines: whole.timelines.filter((t) => !notRead(t)), posts: whole.posts.filter((p) => !droppedIds.has(p.id)), media: Object.fromEntries(Object.entries(whole.media).filter(([id]) => !droppedIds.has(id))), }; })(); const named = parsed.timelines.filter((t) => t.timelineId); const untagged = parsed.timelines.find((t) => !t.timelineId); const scrolled = (timelineId: string | undefined) => o.pageTabs?.find((t) => t.timelineId !== undefined && t.timelineId === timelineId); // What read.json says, tab by tab: the reader's tabs in the order it read // them (with what the capture holds of each), then any timeline the capture // lists that the reader did not name. const tabs: XTrendingReadTab[] = []; // The timeline each entry is of (never written: read.json holds labels). const timelineOf = new Map(); const said = new Set(); for (const t of o.pageTabs ?? []) { const listed = t.timelineId ? named.find((x) => x.timelineId === t.timelineId) : named.length === 0 ? untagged : undefined; if (t.timelineId) said.add(t.timelineId); const entry: XTrendingReadTab = { ...(t.tab ?? listed?.tab ? { tab: t.tab ?? listed?.tab } : {}), asked: t.asked, posts: listed?.postIds.length ?? 0, scrolls: t.scrolls, stop: t.stop, // A tab cut by the read's deadline never shows the page's end. pageEnd: Boolean(listed?.pageEnd) && t.stop !== "deadline", ...(t.why ? { why: t.why } : {}), }; if (t.timelineId) timelineOf.set(entry, t.timelineId); tabs.push(entry); } const unnamedByReader = (o.pageTabs ?? []).some((t) => !t.timelineId) && named.length === 0; for (const t of parsed.timelines) { if (t.timelineId ? said.has(t.timelineId) : unnamedByReader) continue; const before = o.recordedTabs?.find((r) => r.tab !== undefined && r.tab === t.tab); const entry: XTrendingReadTab = { ...(t.tab ? { tab: t.tab } : {}), ...(before?.asked ? { asked: before.asked } : {}), posts: t.postIds.length, ...(before?.scrolls !== undefined ? { scrolls: before.scrolls } : {}), ...(before?.stop ? { stop: before.stop } : {}), pageEnd: t.pageEnd, ...(before?.why ? { why: before.why } : {}), }; if (t.timelineId) timelineOf.set(entry, t.timelineId); tabs.push(entry); } // A tab the record says was not read stays said (a reparse cannot know it otherwise). for (const r of o.recordedTabs ?? []) { if (r.stop === "not-read" && !tabs.some((t) => t.tab === r.tab && t.asked === r.asked)) tabs.push({ ...r, posts: 0, pageEnd: false }); } const base = { operations: parsed.operations, responses: parsed.responses, onPage: parsed.posts.length, ...(tabs.length ? { tabs } : {}), }; if (!o.write || parsed.posts.length === 0) return { ...base, added: 0 }; const had = await readXTrendingPostIds(o.channelRoot); const newIds = parsed.posts.map((p) => p.id).filter((id) => !had.has(id)); const written = await writeXTrendingPosts(o.channelRoot, parsed.posts); // A THREAD'S KEY IS DECIDED ONCE, when a post is first placed, and kept in // its membership record (store.ts): it does not move as ancestors arrive. const byId = new Map((await readXTrendingPosts(o.channelRoot)).map((p) => [p.id, p])); const threads: Record = {}; for (const p of parsed.posts) threads[p.id] = xTrendingThreadKey(byId.get(p.id) ?? p, byId); // THE TABS' READS: each named timeline's posts in its own order, and whether // it was read to its end. Posts an answer listed without naming a timeline // (review 1 S3) go with the ONE named tab when there is exactly one (they // never make it complete or incomplete), else stand by themselves. const tabReads = named.map((t) => { const tab = scrolled(t.timelineId); const complete = Boolean(o.clean && t.pageEnd && tab?.stop === "idle"); return { ...(t.tab ? { tab: t.tab } : {}), timelineId: t.timelineId!, postIds: [...t.postIds], ...(complete ? { complete: true } : {}) }; }); if (untagged) { if (tabReads.length === 1) tabReads[0].postIds.push(...untagged.postIds.filter((id) => !tabReads[0].postIds.includes(id))); else if (tabReads.length === 0) { // No request named a timeline (a page from before tabs were read): the opening tab's, whatever it is called. const only = (o.pageTabs ?? []).length <= 1 ? o.pageTabs?.[0] : undefined; const complete = Boolean(o.clean && untagged.pageEnd && only?.stop === "idle"); tabReads.push({ timelineId: "", postIds: [...untagged.postIds], ...(complete ? { complete: true } : {}) }); } else tabReads.push({ timelineId: "", postIds: [...untagged.postIds] }); } const recorded = await recordXTrendingRead(o.channelRoot, { threads, readId: o.readId, at: o.at, ref: o.ref, ...(o.topic ? { topic: o.topic } : {}), postIds: parsed.posts.map((p) => p.id), added: written.written, media: parsed.media, ...(parsed.page ? { page: parsed.page } : {}), tabReads: tabReads.map(({ timelineId, ...t }) => ({ ...t, ...(timelineId ? { timelineId } : {}) })), }); // The labels the source knew for timelines the capture itself did not name. for (const t of tabs) { const label = recorded.tabLabels?.[timelineOf.get(t) ?? ""]; if (!t.tab && label) t.tab = label; } return { ...base, added: written.written, topic: recorded.topic, newIds, gone: recorded.gone, ...(recorded.goneFromTab?.length ? { goneFromTab: recorded.goneFromTab } : {}), }; } export type ReadXTrendingDeps = { // The page (default: the connected profile, xTrendingRead.ts openXTrendingPage). openPage?: () => Promise; // The e2e suite's fake browser, handed to the default opener. chromium?: ChromiumLike; pauseMs?: () => number; pause?: (ms: number, signal: AbortSignal) => Promise; now?: () => number; readId?: string; // Why the profile cannot be opened now (a Connect or Refresh in flight), or null. profileBusy?: () => string | null; noteOutcome?: typeof noteXServiceOutcome; // X's cooldown: why no read may start now; a rate limit recorded (answers // when it ends, ms since the epoch). Nothing settles it early: it runs out. held?: () => Promise; noteRateLimit?: () => Promise; // For tests: the capture → library step (default: ingestCapture). ingest?: typeof ingestCapture; // A WATCH'S TICK, AT ITS START (review 2 N1): why the watch may not read // now, by its own jar rule (xTrendingWatch.ts refuseWatchJob), or null. The // scan asked when it queued the tick; the job may start much later (X's // gap, another X job ahead of it), and the guard a person's job meets lets // through what a watch must not. A plan marked `watch` with no check here // does not run. watchRefusal?: () => Promise<{ reason: string; sentence: string } | null>; // For tests: the page reader's deadlines (xTrendingRead.ts readXTrendingPage). timeouts?: { load?: number; call?: number; close?: number; read?: number; tab?: number }; }; export async function runXTrendingRead(o: { paths: Paths; plan: Extract; onLog?: (line: string) => void; signal?: AbortSignal; deps?: ReadXTrendingDeps; }): Promise { const { plan, paths } = o; const deps = o.deps ?? {}; const log = o.onLog ?? (() => {}); const now = deps.now ?? Date.now; const signal = o.signal ?? new AbortController().signal; const note = deps.noteOutcome ?? noteXServiceOutcome; const readId = deps.readId ?? `tr-${ulid(now())}`; const base = { slug: plan.slug, mode: plan.probe ? ("probe" as const) : ("read" as const), url: plan.ref.url, trendId: plan.ref.trendId, read: readId, }; const none = { responses: 0, operations: [], posts: { onPage: 0, added: 0 } }; // A Connect or a Refresh holds the profile: asked again here, at the start. // X is asked only by the editor's jobs, on X's queue (lib/xJobRule.ts): // asked here, where the browser is about to be opened. const outside = xJobContextRefusal(`A read of ${plan.ref.url}`, `pnpm ops read-x-trending --json '{"slug":"${plan.slug}","url":"${plan.ref.url}"}' --wait`); if (outside) return { ...base, ...none, ok: false, outcome: "error", sentence: outside, error: outside }; const busy = deps.profileBusy?.() ?? null; if (busy) return { ...base, ...none, ok: false, outcome: "error", sentence: busy, error: busy }; if (plan.watch) { const refused = deps.watchRefusal ? await deps.watchRefusal() : { reason: "refused", sentence: "This watch tick was started with no check of X's cookie jar, so it is not run." }; if (refused) { const sentence = `This watch tick was not read (no browser was opened, X was asked nothing): ${refused.sentence}`; log(sentence); return { ...base, ...none, ok: false, outcome: "error", sentence, error: sentence, watchRefused: refused }; } } // And X's cooldown, asked again here: a read queued before a rate limit // does not navigate X when its turn comes. const held = await (deps.held ?? (() => xTrendingHeld(paths, now())))(); if (held) return { ...base, ...none, ok: false, outcome: "rate-limit", sentence: held, error: held }; const startedAt = new Date(now()).toISOString(); // The record exists from the first moment: a read that dies anywhere below // leaves a capture that can still be parsed again. await ensureXTrendingReadsDir(plan.channelRoot); const started: XTrendingReadRecord = { version: 1, id: readId, trendId: plan.ref.trendId, url: plan.ref.url, startedAt, endedAt: startedAt, probe: plan.probe, headed: plan.headed, ...(plan.watch ? { watch: true as const } : {}), limits: plan.limits, scrolls: 0, stop: "started", outcome: "error", responses: 0, saved: 0, bytes: 0, statuses: {}, operations: [], posts: { onPage: 0, added: 0 }, shot: false, sentence: `This read did not finish. Whatever it captured is kept (${captureAt(readId)}); read-x-trending {"reparse": "${readId}"} parses it without asking X.`, }; await writeXTrendingReadRecord(plan.channelRoot, started); log( `Reading ${plan.ref.url} for ${plan.slug} (${plan.headed ? "in a window" : "headless"}; ` + `at most ${plural(plan.limits.scrolls, "scroll")}, ${plural(plan.limits.posts, "post")} per tab; ` + `${plan.tabs.length === 2 ? "Top, then Latest" : plan.tabs[0] === "latest" ? "Latest only" : "Top only"})` + (plan.probe ? " — a probe: the capture is saved, no post is written." : ".") + (plan.watch ? " A watch's tick." : ""), ); const dir = trendingReadDir(plan.channelRoot, readId); const page: TrendingPageRead = await readXTrendingPage({ url: plan.ref.url, dir, openPage: deps.openPage ?? (() => openXTrendingPage(paths, { headed: plan.headed, onLog: log, ...(deps.chromium ? { chromium: deps.chromium } : {}), })), limits: plan.limits, tabs: plan.tabs, pauseMs: deps.pauseMs ?? (() => xRequestPauseMs()), ...(deps.pause ? { pause: deps.pause } : {}), signal, onLog: log, now, ...(deps.timeouts ? { timeouts: deps.timeouts } : {}), }); // What was read is kept whatever stopped it — except behind a login wall, // where the page shown was not the trending page. const walled = page.stop === "login-wall"; // The parse may fail (a shape it chokes on, a disk that refuses): the read's // record is written all the same, and the capture is there for a reparse. let ingested: Ingested = { operations: [], responses: page.responses, onPage: 0, added: 0 }; let ingestError: string | undefined; try { ingested = await (deps.ingest ?? ingestCapture)({ channelRoot: plan.channelRoot, slug: plan.slug, readId, at: startedAt, ref: plan.ref, ...(plan.topic ? { topic: plan.topic } : {}), write: !plan.probe && !walled, // A tab's "idle" is two scrolls that brought no new post: its end, OR a // next page that did not load. So also: no answer that failed, none // that was not kept (`clean`); and the capture itself must show that // tab's end (ingestCapture). pageTabs: page.tabs, clean: page.saved === page.responses && Object.keys(page.statuses).every((status) => /^2\d\d$/.test(status)), }); } catch (err) { ingestError = ((err as Error)?.message ?? String(err)).split("\n")[0]; } const kept = captureAt(readId); const gone = ingested.onPage === 0 && (page.statuses["404"] ?? 0) > 0; const readSoFar = ingested.added > 0 || ingested.onPage > 0 ? ` ${plural(ingested.onPage, "post")} read before it ${plan.probe ? "are in the capture" : `were kept (${ingested.added} new)`}.` : ""; // A 429 LEAVES X ALONE WHATEVER ELSE WENT WRONG (review 2 N2): the cooldown // is recorded before the outcome is decided, so a parse that also failed // cannot send the next read straight back to X. let limitedUntil: number | undefined; if (page.stop === "rate-limit") { limitedUntil = await (deps.noteRateLimit ?? (() => recordXStop("a rate limit (429) to a trending read", paths, now())))().catch( () => now() + X_RATE_LIMIT_HOLD_MS, ); } else if (page.stop === "forbidden") { // A refusal (403) is X's bot check as often as not: the same X stop // (review 1 F1). await (deps.noteRateLimit ?? (() => recordXStop("a refusal (403) to a trending read", paths, now())))().catch(() => 0); } const untilText = limitedUntil === undefined ? "" : `${hhmm(limitedUntil)} UTC (${Math.ceil((limitedUntil - now()) / 60_000)} min)`; const leftAlone = limitedUntil === undefined ? "" : ` No trending read starts before ${untilText}`; const by = page.stoppedBy ? ` (${page.stoppedBy.op})` : ""; let outcome: XTrendingReadOutcome; let sentence: string; if (walled) { outcome = "login-wall"; sentence = "X asked to log in instead of showing the trending page: the connected profile's session has ended. " + `Connect X account (or Refresh cookies) on /cookies, then read it again. No post was written; the capture is kept (${kept}).`; await note(paths, { challengeLine: "X showed its login page to a read of a trending page (read-x-trending)", kind: "auth-failure", url: plan.ref.url, channel: plan.slug, }); } else if (ingestError !== undefined) { outcome = "error"; sentence = `The page was read and saved (${plural(page.responses, "answer")}), but its posts could not be written: ${ingestError}. ` + (limitedUntil === undefined ? "" : `X also answered 429 (rate limit): no trending read starts before ${untilText}. `) + `The capture is kept (${kept}); read-x-trending {"reparse": "${readId}"} parses it again without asking X.`; } else if (page.stop === "rate-limit") { outcome = "rate-limit"; sentence = `X answered 429 (rate limit) to the page's own request${by}: the read stopped at once and asked nothing more.` + readSoFar + `${leftAlone}; nothing retries by itself. The capture is kept (${kept}).`; } else if (page.stop === "forbidden") { outcome = "forbidden"; sentence = `X answered 403 (forbidden) to the page's own request${by}: the read stopped at once and asked nothing more.` + readSoFar + " The page did not show the login wall, so this is not taken for a lost login and no alert was raised; " + `if it happens again, Check login on /cookies. The capture is kept (${kept}).`; } else if (page.stop === "deadline") { outcome = "error"; sentence = `The trending page stopped answering: ${page.error ?? "the read ran past its deadline"}. The browser was closed.` + readSoFar + ` The capture is kept (${kept}).`; } else if (page.stop === "error") { outcome = "error"; sentence = `The trending page could not be loaded: ${page.error ?? "unknown error"}.` + readSoFar + ` The capture is kept (${kept}).`; } else if (gone) { outcome = "gone"; sentence = `X no longer has this trending page (its request was answered 404): trending pages expire. The capture is kept (${kept}).`; } else if (plan.probe) { outcome = "probe"; sentence = `Probe saved (${kept}): ${plural(page.responses, "answer")} — ${opsText(ingested.operations)}. ` + `The parser finds ${plural(ingested.onPage, "post")} in it. No post was written` + (ingested.onPage > 0 ? `; read-x-trending {"reparse": "${readId}"} writes them without asking X again.` : "."); } else if (ingested.onPage === 0) { outcome = "nothing-recognised"; sentence = `Read saved, nothing recognised: ${plural(page.responses, "answer")} (${opsText(ingested.operations)}) held no post the parser knows. ` + `The capture is kept (${kept}) for the parser to be taught from; read-x-trending {"reparse": "${readId}"} parses it again without asking X.`; } else { outcome = "read"; sentence = `Read ${plan.ref.url}: ${plural(ingested.onPage, "post")} on the page, ${ingested.added} new, ` + `in topic "${ingested.topic?.title}" (${ingested.topic?.id})` + tabText(ingested.tabs) + (page.stop === "cancelled" ? "; the read was stopped early." : ".") + notReadText(ingested.tabs) + renamedText(ingested.topic) + (ingested.gone?.length ? ` ${plural(ingested.gone.length, "post")} this page showed before ${ingested.gone.length === 1 ? "is" : "are"} gone from the page at ${hhmm(Date.parse(startedAt))} UTC.` : "") + goneFromTabText(ingested.goneFromTab); // A clean request: a raised X alert it would clear is cleared. const cleared = await note(paths, { url: plan.ref.url, channel: plan.slug }); if (cleared) log(cleared); // The platform's backoff is NOT settled here (review 2 N4): that entry is // shared with the download lane's X units, whose hold and pace are theirs // to ease. A cooldown this job set ends at its `until`. } const ok = outcome === "read" || outcome === "probe" || outcome === "nothing-recognised"; const record: XTrendingReadRecord = { version: 1, id: readId, trendId: plan.ref.trendId, url: plan.ref.url, startedAt, endedAt: new Date(now()).toISOString(), probe: plan.probe, headed: plan.headed, ...(plan.watch ? { watch: true as const } : {}), limits: plan.limits, scrolls: page.scrolls, stop: page.stop, outcome, responses: page.responses, saved: page.saved, bytes: page.bytes, statuses: page.statuses, operations: ingested.operations, posts: { onPage: ingested.onPage, added: ingested.added }, ...(ingested.topic ? { topic: { id: ingested.topic.id, title: ingested.topic.title } } : {}), ...(ingested.tabs ? { tabs: ingested.tabs } : {}), shot: page.shot, ...(page.stoppedBy ? { stoppedBy: page.stoppedBy } : {}), sentence, }; await writeXTrendingReadRecord(plan.channelRoot, record); log(sentence); return { ...base, ok, outcome, stop: page.stop, scrolls: page.scrolls, ...(page.stoppedBy ? { stoppedBy: page.stoppedBy } : {}), responses: page.responses, operations: ingested.operations, posts: { onPage: ingested.onPage, added: ingested.added }, ...(ingested.topic ? { topic: ingested.topic } : {}), ...(ingested.tabs ? { tabs: ingested.tabs } : {}), ...(ingested.newIds?.length ? { newIds: ingested.newIds } : {}), ...(ingested.gone?.length ? { gone: ingested.gone } : {}), ...(ingested.goneFromTab?.length ? { goneFromTab: ingested.goneFromTab } : {}), sentence, ...(ok ? {} : { error: sentence }), }; } // A saved capture parsed again, offline: its posts written (those the library // lacks), the read recorded against its topic. Nothing is asked of X. export async function reparseXTrendingRead(o: { plan: Extract; onLog?: (line: string) => void; now?: () => number; // Whether a read of this library is queued or running NOW (the editor asks // its registry). Asked INSIDE the job too (lane x-trending-2), not only at // enqueue: a reparse moved to another queue can start beside the read whose // capture it would parse half-written. readInFlight?: () => Promise; }): Promise { const { plan } = o; const log = o.onLog ?? (() => {}); // THE RECORD AS IT IS NOW (review 2 N7), not as the plan saw it: the plan // may have been made while the read was still running, and a reparse that // wrote the plan's copy back would replace the read's final record with the // one it started with. (The plan's is used only for a read that has none.) const record = (await readXTrendingReadRecord(plan.channelRoot, plan.record.id)) ?? plan.record; const ref: XTrendingRef = { trendId: record.trendId, url: record.url }; if (record.stop === "started" && (await o.readInFlight?.())) { const sentence = `Read ${record.id} is still running: its capture is still being written. Parse it again once it has finished (its job is on /jobs). Nothing was parsed or written.`; log(sentence); return { ok: false, slug: plan.slug, mode: "reparse", url: record.url, trendId: record.trendId, read: record.id, outcome: "error", responses: 0, operations: [], posts: { onPage: 0, added: 0 }, sentence, error: sentence, }; } const walled = record.outcome === "login-wall"; const ingested = await ingestCapture({ channelRoot: plan.channelRoot, slug: plan.slug, readId: record.id, at: record.startedAt, ref, ...(plan.topic ? { topic: plan.topic } : {}), write: !walled, ...(record.tabs ? { recordedTabs: record.tabs } : {}), }); const kept = captureAt(record.id); let outcome: XTrendingReadOutcome; let sentence: string; if (walled) { outcome = "login-wall"; sentence = `Read ${record.id} met X's login page, not the trending page: there is nothing in its capture to parse (${kept}).`; } else if (ingested.onPage === 0) { outcome = "nothing-recognised"; sentence = `Parsed ${record.id} again, nothing recognised: ${plural(ingested.responses, "answer")} (${opsText(ingested.operations)}) ` + `held no post the parser knows. The capture is kept (${kept}).`; } else { outcome = "read"; sentence = `Parsed ${record.id} again (${record.url}): ${plural(ingested.onPage, "post")} in the capture, ${ingested.added} new, ` + `in topic "${ingested.topic?.title}" (${ingested.topic?.id})${tabText(ingested.tabs)}. X was asked nothing.` + renamedText(ingested.topic); } const ok = outcome !== "login-wall"; if (ok) { await writeXTrendingReadRecord(plan.channelRoot, { ...record, outcome: outcome === "read" ? "read" : record.outcome, operations: ingested.operations, posts: { onPage: ingested.onPage, added: record.posts.added + ingested.added }, ...(ingested.topic ? { topic: { id: ingested.topic.id, title: ingested.topic.title } } : {}), ...(ingested.tabs ? { tabs: ingested.tabs } : {}), reparsedAt: new Date((o.now ?? Date.now)()).toISOString(), }); } log(sentence); return { ok, slug: plan.slug, mode: "reparse", url: record.url, trendId: record.trendId, read: record.id, outcome, responses: ingested.responses, operations: ingested.operations, posts: { onPage: ingested.onPage, added: ingested.added }, ...(ingested.topic ? { topic: ingested.topic } : {}), ...(ingested.tabs ? { tabs: ingested.tabs } : {}), sentence, ...(ok ? {} : { error: sentence }), }; }