// read-x-trending end to end over a page that plays invented answers back: no // browser, no request, no wait, a temp corpus. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/readXTrending.test.ts import { after, test } from "node:test"; import assert from "node:assert/strict"; import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import { listXTrending, readXTrendingPosts, readXTrendingReadRecord } from "../lib/xTrending/store"; import { fakeTrendingPage, type FakeTrendingPage } from "../social/fakeXProfileBrowser"; import { FIXTURE_LATEST_PAGE, fixtureLatestContinuation, fixtureLatestFirst, fixtureTwoTabResponses, FIXTURE_LAST_UPDATED_MS, FIXTURE_SUMMARY, FIXTURE_TIMELINE_OP, FIXTURE_TITLE, FIXTURE_TREND_ID, FIXTURE_TREND_URL, fixtureContinuation, fixtureTimelineBody, fixtureTrendingResponses, } from "../social/__fixtures__/xTrendingCapture"; import { NO_X_PROFILE_FOR_TRENDING, planReadXTrending, reparseXTrendingRead, runXTrendingRead as runXTrendingReadDirect, type ReadXTrendingAsk, type ReadXTrendingResult, } from "./readXTrending"; import { insideEditorJob } from "../testing/jobs/asEditorJob"; // 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 runXTrendingRead = insideEditorJob(runXTrendingReadDirect); const TMP = mkdtempSync(path.join(tmpdir(), "read-x-trending-")); after(() => rmSync(TMP, { recursive: true, force: true })); const FIXTURE_FIRST_PAGE_0 = { id: "1900000000000001001", handle: "teapot_news", name: "Teapot News", text: "The kettle festival opens today.", media: ["photo", "photo"] as Array<"photo"> }; const READ_1 = "tr-01JA0000000000000000000000"; const READ_2 = "tr-01JB0000000000000000000000"; function corpus(name: string): Paths { const transcriptsDir = path.join(TMP, name); const channelsDir = path.join(transcriptsDir, "channels"); const lib = (slug: string, config: Record) => { mkdirSync(path.join(channelsDir, slug), { recursive: true }); writeFileSync(path.join(channelsDir, slug, "config.json"), JSON.stringify(config)); }; lib("trending", { handling: "transcribe", sourceKind: "social", platform: "twitter", name: "Trending", xTrending: {} }); lib("account-x", { handling: "transcribe", sourceKind: "social", platform: "twitter", url: "https://x.com/example", socialHandle: "example" }); return { transcriptsDir, channelsDir } as unknown as Paths; } const withProfile = { hasProfile: async () => true, held: async () => null }; async function run( paths: Paths, trending: FakeTrendingPage, ask: Partial = {}, over: { readId?: string; at?: string; profileBusy?: () => string | null; held?: () => Promise; ingest?: never; openPage?: never; timeouts?: { call?: number; read?: number }; } = {}, ): Promise<{ result: ReadXTrendingResult; notes: Array>; log: string[]; limited: number; cleaned: number }> { // One tab unless a test asks for both: the page's other tab is R3's tests' (at the end). const planned = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL, tabs: ["top"], ...ask }, withProfile); assert.ok(planned.ok, planned.ok ? "" : planned.error); assert.equal(planned.plan.mode, "read"); const notes: Array> = []; const log: string[] = []; let limited = 0; const cleaned = 0; const at = Date.parse(over.at ?? "2026-11-17T10:00:00.000Z"); const page = fakeTrendingPage(() => ({ trending })); const result = await runXTrendingRead({ paths, plan: planned.plan as never, onLog: (l) => log.push(l), deps: { openPage: over.openPage ?? (async () => ({ page, close: async () => {} })), held: over.held ?? (async () => null), noteRateLimit: async () => (limited++, at + 15 * 60_000), ...(over.ingest ? { ingest: over.ingest } : {}), pauseMs: () => 0, pause: async () => {}, now: () => Date.parse(over.at ?? "2026-11-17T10:00:00.000Z"), readId: over.readId ?? READ_1, ...(over.timeouts ? { timeouts: over.timeouts } : {}), ...(over.profileBusy ? { profileBusy: over.profileBusy } : {}), noteOutcome: async (_p, outcome) => { notes.push(outcome as Record); return null; }, }, }); return { result, notes, log, limited, cleaned }; } const root = (paths: Paths) => path.join(paths.channelsDir, "trending"); test("every refusal before a job is a sentence", async () => { const paths = corpus("refusals"); const plan = (ask: Partial, deps: { hasProfile: () => Promise; held?: () => Promise } = withProfile) => planReadXTrending(paths, { slug: "trending", ...ask }, deps); const error = async (p: ReturnType) => { const r = await p; assert.equal(r.ok, false); return r.ok ? "" : r.error; }; assert.equal(await error(planReadXTrending(paths, { slug: "nope", url: FIXTURE_TREND_URL }, withProfile)), "No such channel: nope"); assert.match(await error(planReadXTrending(paths, { slug: "account-x", url: FIXTURE_TREND_URL }, withProfile)), /account-x is not an X trending library/); assert.match(await error(plan({})), /Give "url" .* or "reparse"/); assert.match(await error(plan({ url: FIXTURE_TREND_URL, reparse: READ_1 })), /holds no saved read/); assert.match(await error(plan({ url: "https://x.com/example/status/1" })), /not a trending page URL/); assert.match(await error(plan({ url: FIXTURE_TREND_URL, scrolls: 41 })), /"scrolls" is a whole number, 1–40/); assert.match(await error(plan({ url: FIXTURE_TREND_URL, posts: 401 })), /"posts" is a whole number, 1–400/); assert.match(await error(plan({ url: FIXTURE_TREND_URL, topic: " " })), /topic/); assert.equal(await error(plan({ url: FIXTURE_TREND_URL }, { hasProfile: async () => false })), NO_X_PROFILE_FOR_TRENDING); assert.match(await error(plan({ reparse: "nope" })), /not a trending read id/); assert.match(await error(plan({ reparse: READ_1 })), /holds no saved read/); assert.match(await error(plan({ reparse: READ_1, probe: true })), /apply to a read of a page/); // Nothing was made by a refusal. assert.equal(existsSync(path.join(root(paths), "trending")), false); }); test("a read writes the page's posts, records the read against a topic, and says so", async () => { const paths = corpus("read"); const { result, notes } = await run(paths, fixtureTrendingResponses(), { topic: "Kettle Festival" }); assert.equal(result.ok, true); assert.equal(result.outcome, "read"); assert.equal(result.mode, "read"); assert.equal(result.trendId, FIXTURE_TREND_ID); assert.equal(result.read, READ_1); assert.deepEqual(result.posts, { onPage: 4, added: 4 }); assert.deepEqual(result.topic, { id: "kettle-festival", title: "Kettle Festival", created: true }); assert.equal( result.sentence, `Read ${FIXTURE_TREND_URL}: 4 posts on the page, 4 new, in topic "Kettle Festival" (kettle-festival), shown by the page's "Top" tab.`, ); // A clean request was noted; no alert. assert.deepEqual(notes, [{ url: FIXTURE_TREND_URL, channel: "trending" }]); const posts = await readXTrendingPosts(root(paths)); assert.deepEqual(posts.map((p) => p.id).sort(), [ "1900000000000001001", "1900000000000001002", "1900000000000001004", "1900000000000001005", ]); assert.ok(posts.every((p) => p.channelSlug === "trending" && p.platform === "twitter")); const listing = await listXTrending(root(paths)); assert.equal(listing.topics[0].posts, 4); assert.deepEqual(listing.posts.map((p) => [p.id, p.author, p.media.kinds.join("+")]), [ ["1900000000000001001", "teapot_news", "image"], ["1900000000000001002", "saucer_fan", ""], ["1900000000000001004", "spout_clips", "video"], ["1900000000000001005", "lid_watch", "gif"], ]); // The read's record: operation names and sizes, never a body. const record = await readXTrendingReadRecord(root(paths), READ_1); assert.equal(record?.outcome, "read"); assert.equal(record?.stop, "idle"); assert.deepEqual(record?.operations.map((o) => o.op), ["ExampleTrendPage", FIXTURE_TIMELINE_OP, "HomeTimeline"]); const recordText = readFileSync(path.join(root(paths), "trending", "reads", READ_1, "read.json"), "utf8"); assert.ok(!recordText.includes("kettle festival opens"), "read.json carries no post text"); assert.ok(!recordText.includes("teapot_news"), "read.json carries no handle"); assert.deepEqual(readdirSync(path.join(root(paths), "trending", "reads", READ_1)).sort(), ["page.png", "read.json", "responses.jsonl"]); }); test("a re-read adds the new posts, keeps the old ones, and appends the read with its time", async () => { const paths = corpus("reread"); const first = fixtureTrendingResponses(); await run(paths, { load: first.load, scrolls: [] }); // The page's end, as the capture shows it: asked for more, the timeline had none. const nothingMore = fixtureContinuation(); const again = await run( paths, { load: [first.scrolls[0][0]], scrolls: [[nothingMore]] }, {}, { readId: READ_2, at: "2026-11-17T12:00:00.000Z" }, ); assert.deepEqual(again.result.posts, { onPage: 2, added: 1 }); assert.equal(again.result.topic?.created, false); // Lane x-trending-2: the ids it added; and, the read having reached the // page's end, the posts the page showed before and not now — gone FROM THE // PAGE, at the read's time, never "deleted". assert.equal(again.result.stop, "idle"); assert.deepEqual(again.result.newIds, ["1900000000000001005"]); // Each post's thread is kept with its place: 1005 answers 1001. const members = JSON.parse(readFileSync(path.join(root(paths), "trending", "membership.json"), "utf8")).posts; assert.equal(members["1900000000000001005"].thread, "1900000000000001001"); assert.equal(members["1900000000000001004"].thread, "1900000000000001004"); assert.deepEqual([...(again.result.gone ?? [])].sort(), ["1900000000000001001", "1900000000000001002"]); assert.match(again.result.sentence, /2 posts this page showed before are gone from the page at 12:00 UTC\.$/); assert.doesNotMatch(again.result.sentence, /delet/i); const listing = await listXTrending(root(paths)); assert.equal(listing.total, 4); assert.deepEqual(listing.topics[0].sources, [ // X's own words and tabs, from the first read's capture; the second read's capture had no page answer. { trendId: FIXTURE_TREND_ID, url: FIXTURE_TREND_URL, title: FIXTURE_TITLE, summary: FIXTURE_SUMMARY, lastUpdatedAt: new Date(FIXTURE_LAST_UPDATED_MS).toISOString(), tabs: ["Top", "Latest"], // The second capture named only a timeline id: the source's known tabs say which tab that is. lastReadTab: "Top", reads: 2, lastReadAt: "2026-11-17T12:00:00.000Z", }, ]); const twice = listing.posts.find((p) => p.id === "1900000000000001004"); assert.deepEqual(twice?.reads.map((r) => r.read), [READ_1, READ_2]); assert.deepEqual(listing.reads, [READ_2, READ_1]); }); test("a probe saves the capture and its summary, writes no post, and a reparse writes them without a read", async () => { const paths = corpus("probe"); const { result, notes } = await run(paths, fixtureTrendingResponses(), { probe: true }); assert.equal(result.ok, true); assert.equal(result.outcome, "probe"); assert.equal(result.mode, "probe"); assert.deepEqual(result.posts, { onPage: 4, added: 0 }); assert.match(result.sentence, /^Probe saved \(trending\/reads\/tr-01JA0000000000000000000000\/\): 4 answers — /); assert.match(result.sentence, /The parser finds 4 posts in it\. No post was written/); assert.deepEqual(notes, []); assert.equal((await readXTrendingPosts(root(paths))).length, 0); assert.deepEqual((await listXTrending(root(paths))).topics, []); assert.equal(existsSync(path.join(root(paths), "trending", "reads", READ_1, "responses.jsonl")), true); const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1, topic: "Kettles" }); assert.ok(planned.ok && planned.plan.mode === "reparse"); const reparsed = await reparseXTrendingRead({ plan: planned.plan as never, now: () => Date.parse("2026-11-18T09:00:00.000Z") }); assert.equal(reparsed.ok, true); assert.equal(reparsed.mode, "reparse"); assert.deepEqual(reparsed.posts, { onPage: 4, added: 4 }); assert.match(reparsed.sentence, /X was asked nothing\.$/); assert.equal((await readXTrendingPosts(root(paths))).length, 4); const listing = await listXTrending(root(paths)); // The read keeps the time it was made, not the time it was parsed. assert.equal(listing.topics[0].sources[0].lastReadAt, "2026-11-17T10:00:00.000Z"); const record = await readXTrendingReadRecord(root(paths), READ_1); assert.equal(record?.outcome, "read"); assert.equal(record?.reparsedAt, "2026-11-18T09:00:00.000Z"); // A second reparse adds nothing. const twice = await reparseXTrendingRead({ plan: planned.plan as never }); assert.deepEqual(twice.posts, { onPage: 4, added: 0 }); }); test("a first real read whose answers the parser does not know ends \"read saved, nothing recognised\": no failure, no alert", async () => { const paths = corpus("unknown"); const { result, notes } = await run(paths, { load: [{ url: "https://x.com/i/api/graphql/q1/UnknownTrendShape", status: 200, body: { data: { story: { headline: "invented" } } } }], scrolls: [[], []], }); assert.equal(result.ok, true); assert.equal(result.outcome, "nothing-recognised"); assert.equal(result.error, undefined); assert.match(result.sentence, /^Read saved, nothing recognised: 1 answer \(UnknownTrendShape ×1 \(\d+ bytes\)\) held no post the parser knows\./); assert.match(result.sentence, /The capture is kept \(trending\/reads\//); assert.deepEqual(notes, []); assert.equal(existsSync(path.join(root(paths), "trending", "reads", READ_1, "responses.jsonl")), true); assert.equal((await readXTrendingReadRecord(root(paths), READ_1))?.outcome, "nothing-recognised"); }); test("a login wall fails with its sentence, writes no post and raises the X alert", async () => { const paths = corpus("walled"); const { result, notes } = await run(paths, { href: "https://x.com/i/flow/login", load: [{ url: `https://x.com/i/api/graphql/q/${FIXTURE_TIMELINE_OP}`, status: 200, body: fixtureTimelineBody([{ id: "1900000000000009001", handle: "login_page_promo", text: "Shown on the login page." }]) }], }); assert.equal(result.ok, false); assert.equal(result.outcome, "login-wall"); assert.match(result.sentence, /^X asked to log in instead of showing the trending page/); assert.match(result.sentence, /No post was written; the capture is kept/); assert.equal(result.error, result.sentence); assert.equal(notes.length, 1); assert.equal(notes[0].kind, "auth-failure"); assert.ok(typeof notes[0].challengeLine === "string"); assert.equal((await readXTrendingPosts(root(paths))).length, 0); }); test("a 429 fails with its sentence, keeps what was read, and raises no alert", async () => { const paths = corpus("limited"); const f = fixtureTrendingResponses(); const { result, notes, limited, cleaned } = await run(paths, { load: [f.load[1], { url: `https://x.com/i/api/graphql/q/${FIXTURE_TIMELINE_OP}`, status: 429, text: "" }], scrolls: f.scrolls, }); // X is left alone for 15 minutes, and the sentence says until when. assert.equal(limited, 1); assert.equal(cleaned, 0); assert.match(result.sentence, /No trending read starts before 10:15 UTC \(15 min\); nothing retries by itself\./); assert.equal(result.ok, false); assert.equal(result.outcome, "rate-limit"); assert.equal(result.scrolls, 0); assert.match(result.sentence, /^X answered 429 \(rate limit\)/); assert.match(result.sentence, /3 posts read before it were kept \(3 new\)\./); assert.deepEqual(notes, []); assert.equal((await readXTrendingPosts(root(paths))).length, 3); }); test("a page X no longer has, and a page that did not load, each fail with a sentence", async () => { const paths = corpus("gone"); const gone = await run(paths, { load: [{ url: "https://x.com/i/api/graphql/q/ExampleTrendPage", status: 404, body: { errors: [{ message: "invented" }] } }], scrolls: [[], []], }); assert.equal(gone.result.ok, false); assert.equal(gone.result.outcome, "gone"); assert.match(gone.result.sentence, /^X no longer has this trending page/); assert.deepEqual(gone.notes, []); const broken = await run(paths, { gotoError: "net::ERR_TIMED_OUT\nmore", load: [] }, {}, { readId: READ_2 }); assert.equal(broken.result.ok, false); assert.equal(broken.result.outcome, "error"); assert.match(broken.result.sentence, /^The trending page could not be loaded: net::ERR_TIMED_OUT\./); assert.deepEqual(broken.notes, []); }); test("a Connect or Refresh in flight refuses the read at its start: no browser opens", async () => { const paths = corpus("busy"); const { result } = await run(paths, fixtureTrendingResponses(), {}, { profileBusy: () => "X's connect is already running." }); assert.equal(result.ok, false); assert.equal(result.sentence, "X's connect is already running."); assert.equal(existsSync(path.join(root(paths), "trending")), false); }); // --- review 1 --------------------------------------------------------------- test("a slug is checked by the plan itself, before it becomes a path", async () => { const paths = corpus("slug"); for (const slug of ["../trending", "a/b", "", ".hidden"]) { const r = await planReadXTrending(paths, { slug, url: FIXTURE_TREND_URL }, withProfile); assert.equal(r.ok, false); assert.match(r.ok ? "" : r.error, /is not a valid channel slug/); } }); test("X cooling down after a rate limit refuses a read at enqueue and at its start: no browser opens", async () => { const paths = corpus("held"); const sentence = "X answered a rate limit (429) a short while ago: no trending read starts before 10:15 UTC (12 min from now). Ask again then; nothing retries by itself."; const planned = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL }, { hasProfile: async () => true, held: async () => sentence }); assert.deepEqual(planned, { ok: false, error: sentence }); // Queued before the rate limit, started after it. let opened = 0; const { result } = await run(paths, fixtureTrendingResponses(), {}, { held: async () => sentence, openPage: (async () => { opened++; throw new Error("must not open"); }) as never, }); assert.equal(result.ok, false); assert.equal(result.outcome, "rate-limit"); assert.equal(result.sentence, sentence); assert.equal(opened, 0); assert.equal(existsSync(path.join(root(paths), "trending")), false); }); test("a clean read records no rate limit; the real cooldown is 15 minutes on the twitter platform entry", async () => { const paths = corpus("clean"); const { limited } = await run(paths, fixtureTrendingResponses()); assert.equal(limited, 0); const { X_RATE_LIMIT_HOLD_MS } = await import("./readXTrending"); assert.equal(X_RATE_LIMIT_HOLD_MS, 15 * 60_000); }); test("a 403 fails with its own sentence, keeps what was read, and raises no login alert", async () => { const paths = corpus("forbidden"); const f = fixtureTrendingResponses(); const { result, notes, limited } = await run(paths, { load: [f.load[1], { url: `https://x.com/i/api/graphql/q/${FIXTURE_TIMELINE_OP}`, status: 403, body: { errors: [{ code: 200 }] } }], scrolls: f.scrolls, }); assert.equal(result.ok, false); assert.equal(result.outcome, "forbidden"); assert.equal(result.scrolls, 0); assert.match(result.sentence, /^X answered 403 \(forbidden\) to the page's own request \(ExampleTrendTimeline\): the read stopped at once/); assert.match(result.sentence, /3 posts read before it were kept \(3 new\)\./); assert.match(result.sentence, /not taken for a lost login and no alert was raised/); assert.deepEqual(notes, []); // A 403 is X's bot check as often as not: the same 15-minute X stop as a 429 (review 1 F1). assert.equal(limited, 1); assert.equal((await readXTrendingPosts(root(paths))).length, 3); }); test("a page that stops answering fails with a sentence, the capture kept", async () => { const paths = corpus("hung"); const base = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() })); const page = { ...base, evaluate: (fn: string) => (fn.includes("scrollTo") ? Promise.reject(Object.assign(new Error("the page did not answer within 20 s (scrolling)"), { name: "PageDeadlineError" })) : base.evaluate(fn)) }; const { PageDeadlineError } = await import("../social/xTrendingRead"); const hung = { ...base, evaluate: (fn: string) => (fn.includes("scrollTo") ? Promise.reject(new PageDeadlineError("scrolling", 20_000)) : base.evaluate(fn)) }; void page; const { result } = await run(paths, fixtureTrendingResponses(), {}, { openPage: (async () => ({ page: hung, close: async () => {} })) as never }); assert.equal(result.ok, false); assert.equal(result.outcome, "error"); assert.equal(result.stop, "deadline"); assert.match(result.sentence, /^The trending page stopped answering: the page did not answer within 20 s \(scrolling\)\. The browser was closed\. 3 posts read before it were kept \(3 new\)\./); }); test("the record is written when the read starts, and a parse that fails still leaves one: the capture is parsed again offline", async () => { const paths = corpus("ingest"); // While the page is being opened, read.json is already there. let early: unknown = null; const page = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() })); const failing = await run(paths, fixtureTrendingResponses(), { topic: "Kettles" }, { openPage: (async () => { early = await readXTrendingReadRecord(root(paths), READ_1); return { page, close: async () => {} }; }) as never, ingest: (async () => { throw new Error("EACCES: permission denied, open 'posts'\n at somewhere"); }) as never, }); assert.equal((early as { stop?: string } | null)?.stop, "started"); assert.equal((early as { outcome?: string } | null)?.outcome, "error"); assert.equal(failing.result.ok, false); assert.equal(failing.result.outcome, "error"); assert.match( failing.result.sentence, /^The page was read and saved \(4 answers\), but its posts could not be written: EACCES: permission denied, open 'posts'\. The capture is kept/, ); const record = await readXTrendingReadRecord(root(paths), READ_1); assert.equal(record?.outcome, "error"); assert.equal(record?.stop, "idle"); assert.equal((await readXTrendingPosts(root(paths))).length, 0); // The offline reparse finds the record and writes the posts. const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1, topic: "Kettles" }); assert.ok(planned.ok && planned.plan.mode === "reparse", planned.ok ? "" : planned.error); const reparsed = await reparseXTrendingRead({ plan: planned.plan as never }); assert.deepEqual(reparsed.posts, { onPage: 4, added: 4 }); assert.equal((await readXTrendingReadRecord(root(paths), READ_1))?.outcome, "read"); }); test("a read left with its answers and no record is parsed again once the page is named", async () => { const paths = corpus("recordless"); await run(paths, fixtureTrendingResponses(), { probe: true }); rmSync(path.join(root(paths), "trending", "reads", READ_1, "read.json")); const bare = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }); assert.equal(bare.ok, false); assert.match(bare.ok ? "" : bare.error, /has its answers but no record of which page it read: give "url"/); const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1, url: FIXTURE_TREND_URL }); assert.ok(planned.ok && planned.plan.mode === "reparse", planned.ok ? "" : planned.error); const reparsed = await reparseXTrendingRead({ plan: planned.plan as never }); assert.equal(reparsed.ok, true); assert.deepEqual(reparsed.posts, { onPage: 4, added: 4 }); assert.equal(reparsed.trendId, FIXTURE_TREND_ID); assert.equal((await readXTrendingReadRecord(root(paths), READ_1))?.outcome, "read"); // A read WITH its record takes no url beside reparse. const both = await planReadXTrending(paths, { slug: "trending", reparse: READ_1, url: FIXTURE_TREND_URL }); assert.match(both.ok ? "" : both.error, /one of them/); }); test("a reparse updates the topic's record of the read: what the capture holds, and what was added in all", async () => { const paths = corpus("recount"); await run(paths, fixtureTrendingResponses(), { probe: true }); const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }); assert.ok(planned.ok && planned.plan.mode === "reparse"); await reparseXTrendingRead({ plan: planned.plan as never }); await reparseXTrendingRead({ plan: planned.plan as never }); const { readXTrendingTopics } = await import("../lib/xTrending/store"); const [topic] = await readXTrendingTopics(root(paths)); assert.deepEqual(topic.sources[0].reads, [{ id: READ_1, at: "2026-11-17T10:00:00.000Z", posts: 4, added: 4, tab: "Top" }]); }); test("the captures are never committed: the reads directory ignores everything under it", async () => { const paths = corpus("gitignore"); await run(paths, fixtureTrendingResponses()); const ignore = readFileSync(path.join(root(paths), "trending", "reads", ".gitignore"), "utf8"); assert.match(ignore, /^\*$/m); // And it is not taken for a read. assert.deepEqual((await listXTrending(root(paths))).reads, [READ_1]); }); // --- review 2 --------------------------------------------------------------- test("N2: a 429 leaves X alone even when the posts then cannot be written", async () => { const paths = corpus("limited-and-broken"); const f = fixtureTrendingResponses(); const { result, limited } = await run( paths, { load: [f.load[1], { url: `https://x.com/i/api/graphql/q/${FIXTURE_TIMELINE_OP}`, status: 429, text: "" }], scrolls: f.scrolls }, {}, { ingest: (async () => { throw new Error("EACCES: permission denied"); }) as never }, ); assert.equal(limited, 1, "the cooldown was recorded"); assert.equal(result.ok, false); assert.equal(result.outcome, "error"); assert.match(result.sentence, /its posts could not be written: EACCES: permission denied\./); assert.match(result.sentence, /X also answered 429 \(rate limit\): no trending read starts before 10:15 UTC \(15 min\)\./); }); test("read.json names the operation and status that stopped a read", async () => { const paths = corpus("stopped-by"); const f = fixtureTrendingResponses(); const { result } = await run(paths, { load: [f.load[1], { url: "https://x.com/i/api/graphql/q9/ExamplePeripheralOp?variables=%7B%7D", status: 403, body: { errors: [] } }], scrolls: f.scrolls, }); assert.deepEqual(result.stoppedBy, { op: "ExamplePeripheralOp", status: 403 }); const record = await readXTrendingReadRecord(root(paths), READ_1); assert.deepEqual(record?.stoppedBy, { op: "ExamplePeripheralOp", status: 403 }); assert.match(result.sentence, /^X answered 403 \(forbidden\) to the page's own request \(ExamplePeripheralOp\)/); // A read nothing stopped names none. const clean = await run(paths, fixtureTrendingResponses(), {}, { readId: READ_2 }); assert.equal(clean.result.stoppedBy, undefined); assert.equal((await readXTrendingReadRecord(root(paths), READ_2))?.stoppedBy, undefined); }); test("N7: a reparse planned while the read was unfinished parses the record as it is when the job runs", async () => { const paths = corpus("stale-plan"); // The plan is made from the record a read writes when it STARTS. let planned: Awaited> | null = null; const page = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() })); await run(paths, fixtureTrendingResponses(), { probe: true }, { openPage: (async () => { planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }); return { page, close: async () => {} }; }) as never, }); assert.ok(planned && (planned as { ok: boolean }).ok); const plan = (planned as unknown as { plan: { record: { stop: string } } }).plan; assert.equal(plan.record.stop, "started"); // The read has finished since. The reparse must not put the stale record back. const reparsed = await reparseXTrendingRead({ plan: plan as never }); assert.equal(reparsed.ok, true); const record = await readXTrendingReadRecord(root(paths), READ_1); assert.equal(record?.stop, "idle"); assert.equal(record?.scrolls, 3); assert.equal(record?.responses, 4); assert.equal(record?.probe, true); assert.equal(record?.outcome, "read"); assert.equal(record?.shot, true); }); test("N7: a reparse of a read that is still running is refused; of one that died unfinished, allowed", async () => { const paths = corpus("running"); let running: Awaited> | null = null; let dead: Awaited> | null = null; const page = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() })); await run(paths, fixtureTrendingResponses(), {}, { openPage: (async () => { running = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }, { readInFlight: async () => true }); dead = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }, { readInFlight: async () => false }); return { page, close: async () => {} }; }) as never, }); assert.deepEqual(running, { ok: false, error: `Read ${READ_1} is still running: parse it again once it has finished (its job is on /jobs).`, }); assert.equal((dead as unknown as { ok: boolean }).ok, true); }); // Lane x-trending-2: the same refusal INSIDE the job. test("a reparse whose read is still running when the job starts parses nothing and leaves the read's record alone", async () => { const paths = corpus("running-in-job"); const page = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() })); let inJob: Awaited> | null = null; let recordThen: unknown = null; await run(paths, fixtureTrendingResponses(), {}, { openPage: (async () => { // Planned as though no read were in flight (the plan can be old) — and // run while the read is: the job itself refuses. const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }, { readInFlight: async () => false }); assert.equal(planned.ok, true); if (planned.ok && planned.plan.mode === "reparse") { inJob = await reparseXTrendingRead({ plan: planned.plan, readInFlight: async () => true }); recordThen = await readXTrendingReadRecord(root(paths), READ_1); } return { page, close: async () => {} }; }) as never, }); const refused = inJob as unknown as { ok: boolean; outcome: string; sentence: string; posts: { onPage: number; added: number } }; assert.equal(refused.ok, false); assert.equal(refused.outcome, "error"); assert.match(refused.sentence, new RegExp(`^Read ${READ_1} is still running: its capture is still being written\\..*Nothing was parsed or written\\.$`)); assert.deepEqual(refused.posts, { onPage: 0, added: 0 }); assert.equal((recordThen as { stop: string }).stop, "started"); // Once the read has ended, the same reparse goes through. const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }, { readInFlight: async () => false }); assert.equal(planned.ok, true); if (planned.ok && planned.plan.mode === "reparse") { const done = await reparseXTrendingRead({ plan: planned.plan, readInFlight: async () => true }); assert.equal(done.ok, true); } }); // Review 1 S2: "idle" is not the page's end. test("S2: a read that went idle without the capture showing the page's end marks nothing gone", async () => { const first = fixtureTrendingResponses(); const timeline = first.scrolls[0][0]; const reread = async (name: string, second: FakeTrendingPage) => { const paths = corpus(name); await run(paths, { load: first.load, scrolls: [] }); return run(paths, second, {}, { readId: READ_2, at: "2026-11-17T12:00:00.000Z" }); }; // The scrolls simply brought no further answer (a next page that never loaded looks the same). const silent = await reread("s2-silent", { load: [timeline], scrolls: [[], []] }); assert.equal(silent.result.stop, "idle"); assert.equal(silent.result.outcome, "read"); assert.equal(silent.result.gone, undefined); assert.doesNotMatch(silent.result.sentence, /gone from the page/); // An answer with nothing new that was not asked from the bottom (review 2 N4): nothing. const fromTop = await reread("s2-from-top", { load: [timeline], scrolls: [[{ url: first.load[1].url, status: 200, body: fixtureTimelineBody([]) }], []] }); assert.equal(fromTop.result.gone, undefined); // The next page answered 500: the read still ends idle, and asserts nothing. const failed = await reread("s2-failed", { load: [timeline], scrolls: [[{ url: timeline.url, status: 500, text: "upstream error" }], []] }); assert.equal(failed.result.stop, "idle"); assert.equal(failed.result.gone, undefined); // ...even when an empty page follows the failure. const after500 = await reread("s2-failed-then-empty", { load: [timeline], scrolls: [[{ url: timeline.url, status: 500, text: "upstream error" }], [fixtureContinuation()]], }); assert.equal(after500.result.gone, undefined); // Asked for more and answered "none", cleanly: the page's end. const ended = await reread("s2-end", { load: [timeline], scrolls: [[fixtureContinuation()], []] }); assert.deepEqual([...(ended.result.gone ?? [])].sort(), ["1900000000000001001", "1900000000000001002"]); }); // ── lane x-followups: the real page's shape ──────────────────────────────── test("the real shape: a read with no topic named makes one called by the page's title, and says which tab it saw", async () => { const real = await import("../social/__fixtures__/xTrendingRealShape"); const paths = corpus("real-read"); const all = real.realCaptureResponses(); // The real read's order: the page's answers on load, one continuation per scroll. const { result } = await run(paths, { load: all.slice(0, 6), scrolls: all.slice(6).map((r) => [r]) }, { url: real.INVENTED_TREND_URL }); assert.equal(result.outcome, "read"); assert.deepEqual(result.posts, { onPage: 6, added: 6 }); assert.deepEqual(result.topic, { id: `t-${real.INVENTED_TREND_ID}`, title: real.INVENTED_TITLE, created: true }); assert.deepEqual(result.tabs, [{ tab: "Top", asked: "top", posts: 6, scrolls: 4, stop: "idle", pageEnd: false }]); assert.equal( result.sentence, `Read ${real.INVENTED_TREND_URL}: 6 posts on the page, 6 new, in topic "${real.INVENTED_TITLE}" (t-${real.INVENTED_TREND_ID}), shown by the page's "Top" tab.`, ); const record = await readXTrendingReadRecord(root(paths), READ_1); assert.deepEqual(record?.tabs, result.tabs); // read.json: names, labels and sizes — no timeline id, no summary, no post. const recordText = readFileSync(path.join(root(paths), "trending", "reads", READ_1, "read.json"), "utf8"); for (const never of [real.INVENTED_TOP_TIMELINE, real.INVENTED_LATEST_TIMELINE, real.INVENTED_SUMMARY, "festival opens today", "teapot_news", real.realBottomCursor(1)]) { assert.ok(!recordText.includes(never), `read.json carries no "${never}"`); } const listing = await listXTrending(root(paths)); assert.deepEqual(listing.topics[0].sources, [ { trendId: real.INVENTED_TREND_ID, url: real.INVENTED_TREND_URL, title: real.INVENTED_TITLE, summary: real.INVENTED_SUMMARY, lastUpdatedAt: new Date(real.INVENTED_LAST_UPDATED_MS).toISOString(), tabs: ["Top", "Latest"], lastReadTab: "Top", reads: 1, lastReadAt: "2026-11-17T10:00:00.000Z", }, ]); assert.ok(listing.posts.every((p) => p.reads.length === 1 && p.reads[0].tab === "Top")); // The scrolls all brought new posts: the read asserts nothing about what the page no longer shows. assert.equal(result.gone, undefined); }); test("the real shape: a library read before titles were parsed is put right by a reparse — the name, X's words, the tab — and a renamed topic is left alone", async () => { const real = await import("../social/__fixtures__/xTrendingRealShape"); const { renameXTrendingTopic } = await import("../lib/xTrending/organise"); const all = real.realCaptureResponses(); const fallback = `Trending ${real.INVENTED_TREND_ID}`; const topicsFile = (paths: Paths) => path.join(root(paths), "trending", "topics.json"); const membersFile = (paths: Paths) => path.join(root(paths), "trending", "membership.json"); // What slice 1 left of such a read: the fallback name, a source with no words, sightings with no tab. const asSlice1Left = (paths: Paths) => { const topics = JSON.parse(readFileSync(topicsFile(paths), "utf8")); topics.topics[0].title = fallback; for (const key of ["title", "summary", "lastUpdatedAt", "tabs"]) delete topics.topics[0].sources[0][key]; for (const r of topics.topics[0].sources[0].reads) delete r.tab; writeFileSync(topicsFile(paths), JSON.stringify(topics)); const members = JSON.parse(readFileSync(membersFile(paths), "utf8")); for (const m of Object.values(members.posts) as Array<{ seen: Array<{ tab?: string }> }>) for (const s of m.seen) delete s.tab; writeFileSync(membersFile(paths), JSON.stringify(members)); }; const reparse = async (paths: Paths) => { const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }); assert.ok(planned.ok && planned.plan.mode === "reparse", planned.ok ? "" : planned.error); return reparseXTrendingRead({ plan: planned.plan as never, now: () => Date.parse("2026-11-18T09:00:00.000Z") }); }; const paths = corpus("real-reparse"); await run(paths, { load: all, scrolls: [] }, { url: real.INVENTED_TREND_URL }); asSlice1Left(paths); const done = await reparse(paths); assert.equal(done.ok, true); assert.deepEqual(done.posts, { onPage: 6, added: 0 }); assert.deepEqual(done.topic, { id: `t-${real.INVENTED_TREND_ID}`, title: real.INVENTED_TITLE, created: false, renamed: { was: fallback } }); assert.equal( done.sentence, `Parsed ${READ_1} again (${real.INVENTED_TREND_URL}): 6 posts in the capture, 0 new, in topic "${real.INVENTED_TITLE}" (t-${real.INVENTED_TREND_ID}), ` + `shown by the page's "Top" tab. X was asked nothing. The topic was "${fallback}" until now: it took the page's title.`, ); const topic = JSON.parse(readFileSync(topicsFile(paths), "utf8")).topics[0]; assert.equal(topic.title, real.INVENTED_TITLE); assert.equal(topic.sources[0].summary, real.INVENTED_SUMMARY); assert.equal(topic.sources[0].reads[0].tab, "Top"); const members = JSON.parse(readFileSync(membersFile(paths), "utf8")).posts as Record }>; assert.ok(Object.values(members).every((m) => m.seen.length === 1 && m.seen[0].tab === "Top")); const record = await readXTrendingReadRecord(root(paths), READ_1); // The reparse keeps what the read knew of the tab (its scrolls, why it stopped) and says again what the capture holds. assert.deepEqual(record?.tabs, [{ tab: "Top", asked: "top", posts: 6, scrolls: 2, stop: "idle", pageEnd: false }]); assert.deepEqual(record?.topic, { id: `t-${real.INVENTED_TREND_ID}`, title: real.INVENTED_TITLE }); // A second reparse renames nothing and says nothing of a rename. assert.doesNotMatch((await reparse(paths)).sentence, /until now/); // The operator (or an agent) renamed the topic first: the reparse fills X's words on the source and leaves the name. const named = corpus("real-reparse-named"); await run(named, { load: all, scrolls: [] }, { url: real.INVENTED_TREND_URL }); asSlice1Left(named); assert.equal((await renameXTrendingTopic(root(named), { topic: `t-${real.INVENTED_TREND_ID}`, title: "Kettles, my pick", by: "operator", readInFlight: () => false })).ok, true); const kept = await reparse(named); assert.equal(kept.topic?.title, "Kettles, my pick"); assert.equal(kept.topic?.renamed, undefined); const after = JSON.parse(readFileSync(topicsFile(named), "utf8")).topics[0]; assert.equal(after.title, "Kettles, my pick"); assert.equal(after.sources[0].title, real.INVENTED_TITLE); }); test("the real shape: gone from the page is said after a read whose bottom continuation (cursors in TimelineReplaceEntry) brought nothing new, and never after a capped or failed one", async () => { const real = await import("../social/__fixtures__/xTrendingRealShape"); const base = real.realCaptureResponses({ later: [] }).slice(0, -1); // First read: the three posts of the first page and the two of the second. const seed = async (name: string) => { const paths = corpus(name); await run(paths, { load: [...base, real.realContinuation(real.INVENTED_SECOND, { n: 2 })], scrolls: [] }, { url: real.INVENTED_TREND_URL }); return paths; }; const second = (paths: Paths, scrolls: FakeTrendingPage["scrolls"]) => run(paths, { load: base, scrolls }, { url: real.INVENTED_TREND_URL }, { readId: READ_2, at: "2026-11-17T12:00:00.000Z" }); // To the end: the continuation from the first answer's bottom cursor brings one post, the one after it none. const ended = await second(await seed("real-gone-end"), [[real.realContinuation([real.INVENTED_SECOND[0]], { n: 2 })], [real.realContinuation([], { n: 3 })], []]); assert.equal(ended.result.stop, "idle"); assert.deepEqual(ended.result.gone, ["1900000000000003005"]); // Capped (the scroll cap, with posts still arriving): nothing. const capped = await second(await seed("real-gone-capped"), [[real.realContinuation([real.INVENTED_SECOND[0]], { n: 2 })]]); assert.equal(capped.result.gone, undefined); // The last answer failed: nothing. const last = real.realContinuation([], { n: 3 }); const failed = await second(await seed("real-gone-failed"), [[real.realContinuation([real.INVENTED_SECOND[0]], { n: 2 })], [{ url: last.url, status: 500, text: "upstream error" }], []]); assert.equal(failed.result.stop, "idle"); assert.equal(failed.result.gone, undefined); }); // Review 1 S3. test("S3: a post first seen in an answer that named no timeline does not drop the read's tab; it inherits the one named tab", async () => { const real = await import("../social/__fixtures__/xTrendingRealShape"); const { readTabOf } = await import("./readXTrending"); assert.equal(readTabOf([{ tab: "Top" }, {}]), "Top"); assert.equal(readTabOf([{ tab: "Top" }, { tab: "Latest" }, {}]), undefined); assert.equal(readTabOf([{}]), undefined); assert.equal(readTabOf([]), undefined); const paths = corpus("s3-untagged"); // One more answer listing a post, whose request names no timeline at all. const stray = { url: "https://x.com/i/api/graphql/q/ExampleTrendTimeline?variables=%7B%7D", status: 200, body: fixtureTimelineBody([{ id: "1900000000000003099", handle: "stray_post", text: "Listed by an answer that names no timeline." }]) }; const { result } = await run(paths, { load: [...real.realCaptureResponses({ later: [] }), stray], scrolls: [] }, { url: real.INVENTED_TREND_URL }); assert.deepEqual(result.tabs, [{ tab: "Top", asked: "top", posts: 3, scrolls: 2, stop: "idle", pageEnd: false }, { posts: 1, pageEnd: false }]); assert.match(result.sentence, /shown by the page's "Top" tab\.$/); const topic = JSON.parse(readFileSync(path.join(root(paths), "trending", "topics.json"), "utf8")).topics[0]; assert.equal(topic.sources[0].reads[0].tab, "Top"); const members = JSON.parse(readFileSync(path.join(root(paths), "trending", "membership.json"), "utf8")).posts; assert.equal(members["1900000000000003099"].seen[0].tab, "Top"); assert.equal(members["1900000000000003001"].seen[0].tab, "Top"); }); // ── added scope R3: Top and Latest in one job ────────────────────────────── test("R3: \"tabs\" is top, latest or both (the default); anything else is refused, and a reparse takes none", async () => { const { xTrendingTabsAsked, X_TRENDING_TABS_PROBLEM } = await import("./readXTrending"); assert.deepEqual(xTrendingTabsAsked(undefined), { ok: true, tabs: ["top", "latest"] }); assert.deepEqual(xTrendingTabsAsked(["latest", "top", "TOP"]), { ok: true, tabs: ["top", "latest"] }); assert.deepEqual(xTrendingTabsAsked(["latest"]), { ok: true, tabs: ["latest"] }); for (const bad of [[], ["media"], "top", [1], {}]) assert.deepEqual(xTrendingTabsAsked(bad), { ok: false, error: X_TRENDING_TABS_PROBLEM }); const paths = corpus("r3-plan"); const plan = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL }, withProfile); assert.ok(plan.ok && plan.plan.mode === "read"); assert.deepEqual(plan.plan.tabs, ["top", "latest"]); const refused = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL, tabs: ["all"] }, withProfile); assert.deepEqual(refused, { ok: false, error: X_TRENDING_TABS_PROBLEM }); }); test("R3: one job reads Top, then Latest: one capture, each post's sightings per tab, read.json tab by tab", async () => { const paths = corpus("r3-both"); const { result, log } = await run(paths, fixtureTwoTabResponses(), { tabs: ["top", "latest"], topic: "Kettle Festival" }); assert.equal(result.ok, true); assert.equal(result.outcome, "read"); // Five posts: Top's four and the one only Latest shows. assert.deepEqual(result.posts, { onPage: 5, added: 5 }); assert.deepEqual(result.tabs, [ { tab: "Top", asked: "top", posts: 4, scrolls: 3, stop: "idle", pageEnd: true }, { tab: "Latest", asked: "latest", posts: 3, scrolls: 2, stop: "idle", pageEnd: true }, ]); assert.equal(result.sentence, `Read ${FIXTURE_TREND_URL}: 5 posts on the page, 5 new, in topic "Kettle Festival" (kettle-festival), shown by the page's "Top" and "Latest" tabs.`); assert.ok(log.some((l) => /Top, then Latest/.test(l))); const record = await readXTrendingReadRecord(root(paths), READ_1); assert.deepEqual(record?.tabs, result.tabs); assert.equal(record?.scrolls, 5); assert.deepEqual(readdirSync(path.join(root(paths), "trending", "reads", READ_1)).sort(), ["page-latest.png", "page.png", "read.json", "responses.jsonl"]); const members = JSON.parse(readFileSync(path.join(root(paths), "trending", "membership.json"), "utf8")).posts; assert.deepEqual(members["1900000000000001001"].seen.map((s: { tab: string; rank: number }) => [s.tab, s.rank]), [["Top", 1], ["Latest", 2]]); assert.deepEqual(members["1900000000000001009"].seen.map((s: { tab: string; rank: number }) => [s.tab, s.rank]), [["Latest", 1]]); const listing = await listXTrending(root(paths)); assert.deepEqual(listing.topics[0].sources[0].lastReadTabs, ["Top", "Latest"]); // A reparse of the two-tab capture says the same of each tab and adds nothing. const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }); assert.ok(planned.ok && planned.plan.mode === "reparse"); const again = await reparseXTrendingRead({ plan: planned.plan as never }); assert.deepEqual(again.posts, { onPage: 5, added: 0 }); assert.deepEqual(again.tabs, result.tabs); // A probe covers both tabs too, and writes no post. const probe = await run(corpus("r3-probe"), fixtureTwoTabResponses(), { tabs: ["top", "latest"], probe: true }); assert.equal(probe.result.outcome, "probe"); assert.deepEqual(probe.result.tabs?.map((t) => [t.tab, t.posts, t.stop]), [["Top", 4, "idle"], ["Latest", 3, "idle"]]); }); test("R3: a Latest tab that cannot be opened ends the read \"Top read; Latest not read: \" — a read, not a failure, and nothing is retried", async () => { const never = fixtureTwoTabResponses(); never.tabs.Latest = {}; const paths = corpus("r3-never"); const { result, notes } = await run(paths, never, { tabs: ["top", "latest"], topic: "Kettle Festival" }); assert.equal(result.ok, true); assert.equal(result.outcome, "read"); assert.deepEqual(result.posts, { onPage: 4, added: 4 }); assert.equal( result.sentence, `Read ${FIXTURE_TREND_URL}: 4 posts on the page, 4 new, in topic "Kettle Festival" (kettle-festival), shown by the page's "Top" tab. ` + `Top read; Latest not read: pressing "Latest" brought no answer for its timeline within 20 s.`, ); assert.deepEqual(result.tabs?.[1], { tab: "Latest", asked: "latest", posts: 0, scrolls: 0, stop: "not-read", pageEnd: false, why: 'pressing "Latest" brought no answer for its timeline within 20 s' }); // A clean request: the X alert it could clear is cleared, none is raised. assert.deepEqual(notes.map((n) => n.kind), [undefined]); // Top's read stands by itself: a later read may say what Top no longer shows. const hidden = fixtureTwoTabResponses(); hidden.tabs.Latest.hidden = true; hidden.load = [hidden.load[0], { ...hidden.load[1], body: fixtureTimelineBody([FIXTURE_FIRST_PAGE_0]) }]; hidden.scrolls = [[fixtureContinuation([], 5)], []]; const second = await run(paths, hidden, { tabs: ["top", "latest"], topic: "Kettle Festival" }, { readId: READ_2, at: "2026-11-17T12:00:00.000Z" }); assert.equal(second.result.outcome, "read"); assert.deepEqual([...(second.result.gone ?? [])].sort(), ["1900000000000001002", "1900000000000001004", "1900000000000001005"]); assert.match(second.result.sentence, /Top read; Latest not read: the page shows no tab named "Latest" in its tab list\./); }); test("R3: a post that leaves Latest between two reads is said gone from that tab while Top still shows it; gone from the page once Top drops it too", async () => { const paths = corpus("r3-leaves"); await run(paths, fixtureTwoTabResponses(), { tabs: ["top", "latest"], topic: "Kettle Festival" }); // Second read: Latest no longer lists 1001 (Top does) nor 1009 (which only Latest showed). const latestNow = [FIXTURE_LATEST_PAGE[2]]; const second = await run(paths, fixtureTwoTabResponses(latestNow), { tabs: ["top", "latest"] }, { readId: READ_2, at: "2026-11-17T12:00:00.000Z" }); assert.deepEqual(second.result.gone, ["1900000000000001009"]); assert.deepEqual(second.result.goneFromTab, [{ id: "1900000000000001001", tab: "Latest" }]); assert.equal( second.result.sentence, `Read ${FIXTURE_TREND_URL}: 4 posts on the page, 0 new, in topic "Kettle Festival" (kettle-festival), shown by the page's "Top" and "Latest" tabs. ` + `1 post this page showed before is gone from the page at 12:00 UTC. 1 post is gone from the "Latest" tab and still shown by another.`, ); const listing = await listXTrending(root(paths)); assert.deepEqual(listing.posts.find((p) => p.id === "1900000000000001001")?.goneTabs, [{ tab: "Latest", at: "2026-11-17T12:00:00.000Z", read: READ_2 }]); assert.equal(listing.posts.find((p) => p.id === "1900000000000001001")?.gone, undefined); // A read of Latest that was CAPPED says nothing of what Latest no longer shows. const capped = fixtureTwoTabResponses([FIXTURE_LATEST_PAGE[0]]); capped.tabs.Latest.scrolls = [[fixtureLatestContinuation([{ id: "1900000000000001010", handle: "lid_watch", text: "One more." }])]]; const third = await run(paths, capped, { tabs: ["top", "latest"], scrolls: 3 }, { readId: "tr-01JC0000000000000000000000", at: "2026-11-17T13:00:00.000Z" }); assert.deepEqual(third.result.tabs?.map((t) => [t.tab, t.pageEnd]), [["Top", true], ["Latest", false]]); assert.equal(third.result.goneFromTab, undefined); void fixtureLatestFirst; }); // Added scope R2: where X is about to be asked, only a job on X's queue stands. test("R2a: a trending read outside the editor's job, or in a job on another queue, opens no browser", async () => { const { asEditorJob } = await import("../testing/jobs/asEditorJob"); const paths = corpus("r2-outside"); const planned = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL }, withProfile); assert.ok(planned.ok && planned.plan.mode === "read"); let opened = 0; const ask = { paths, plan: planned.plan as never, deps: { openPage: async () => (opened++, assert.fail("a browser was opened")), held: async () => null } }; const outside = await runXTrendingReadDirect(ask); assert.equal(outside.ok, false); assert.match(outside.sentence, /^A read of https:\/\/x\.com\/i\/trending\/\d+ asks X, and X is asked only by the editor's own jobs .*Queue it instead: pnpm ops read-x-trending/); const elsewhere = await asEditorJob(() => runXTrendingReadDirect(ask), { queueKey: "manual" }); assert.match(elsewhere.sentence, /X jobs run on X's queue only \(platform:twitter\): the queue "manual" is refused/); assert.equal(opened, 0); assert.equal(existsSync(path.join(root(paths), "trending", "reads")), false); }); // ── review 2 (lane x-followups): S1, S2 at the read's end ────────────────── test("S1: a press that takes the page off the trending page ends \"Top read; Latest not read: the page changed\" — a read, no strike, Top ingested", async () => { const away = fixtureTwoTabResponses(); away.tabs.Latest.navigatesTo = "https://x.com/explore"; const paths = corpus("s1-changed"); const { result } = await run(paths, away, { tabs: ["top", "latest"], topic: "Kettle Festival" }); assert.equal(result.ok, true); assert.equal(result.outcome, "read"); assert.deepEqual(result.posts, { onPage: 4, added: 4 }); assert.match(result.sentence, / Top read; Latest not read: the page changed\.$/); assert.deepEqual(result.tabs?.[1], { tab: "Latest", asked: "latest", posts: 0, scrolls: 0, stop: "not-read", pageEnd: false, why: "the page changed" }); }); test("S2: a deadline during Latest keeps Top's result — \"Top read; Latest stopped at the deadline\", pageEnd false for Latest, a read and no strike", async () => { const stuck = fixtureTwoTabResponses(); stuck.tabs.Latest.scrollHangs = true; const paths = corpus("s2-deadline"); const { result } = await run(paths, stuck, { tabs: ["top", "latest"], topic: "Kettle Festival" }, { timeouts: { call: 50 } }); assert.equal(result.ok, true); assert.equal(result.outcome, "read"); assert.match(result.sentence, / Top read; Latest stopped at the deadline \(3 posts read\)\.$/); assert.deepEqual( result.tabs?.map((t) => [t.tab, t.stop, t.pageEnd]), [["Top", "idle", true], ["Latest", "deadline", false]], ); // What Latest had is in the library. assert.equal(result.posts.onPage, 5); // An ending of "read" is what the watch counts no strike for (xTrendingWatch.ts noteXTrendingWatchRead). }); // Review 3 S8: after the press took the page elsewhere, the answers the // other page sent (its own timelines) are kept in the capture and never // ingested as this topic's — on the read and on a reparse alike. test("review 3 S8: after the page changed, an answer for any other timeline is kept in the capture and not ingested", async () => { const away = fixtureTwoTabResponses(); away.tabs.Latest.navigatesTo = "https://x.com/explore"; const STRAY = "1900000000000003991"; const strayUrl = `https://x.com/i/api/graphql/q/${FIXTURE_TIMELINE_OP}?variables=${encodeURIComponent(JSON.stringify({ timelineId: "fixture-timeline-elsewhere", count: 20 }))}`; away.tabs.Latest.load = [{ url: strayUrl, status: 200, body: fixtureTimelineBody([{ id: STRAY, handle: "elsewhere", text: "A post of the page the press went to." }]) }]; const paths = corpus("s8-elsewhere"); const { result } = await run(paths, away, { tabs: ["top", "latest"], topic: "Kettle Festival" }); assert.equal(result.outcome, "read"); assert.match(result.sentence, / Top read; Latest not read: the page changed\.$/); assert.deepEqual(result.posts, { onPage: 4, added: 4 }, "Top's four, not the other page's post"); assert.ok(!(await readXTrendingPosts(root(paths))).some((p) => p.id === STRAY)); // It is in the capture all the same. const capture = readFileSync(path.join(root(paths), "trending", "reads", READ_1, "responses.jsonl"), "utf8"); assert.ok(capture.includes(STRAY)); // A reparse of the same read reads the record's tabs and does the same. const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }); assert.ok(planned.ok && planned.plan.mode === "reparse"); const reparsed = await reparseXTrendingRead({ plan: planned.plan as never }); assert.equal(reparsed.ok, true); assert.equal(reparsed.posts.onPage, 4); assert.ok(!(await readXTrendingPosts(root(paths))).some((p) => p.id === STRAY)); });