// The trending page reader over a page that plays invented answers back // (fakeXProfileBrowser.ts fakeTrendingPage): no browser, no request, no wait. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xTrendingRead.test.ts import { after, test } from "node:test"; import assert from "node:assert/strict"; import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { fakeTrendingPage, type FakeTrendingPage } from "./fakeXProfileBrowser"; import { bounded, isXLoginHref, openXTrendingPage, readXTrendingPage, type TrendingPageRead } from "./xTrendingRead"; import { readCaptureLines } from "./xTrendingParse"; import { FIXTURE_LATEST_PAGE, FIXTURE_LATEST_TIMELINE, FIXTURE_TIMELINE_OP, FIXTURE_TOP_TIMELINE, FIXTURE_TREND_URL, fixtureLatestFirst, fixtureTwoTabResponses, fixtureTimelineBody, fixtureTrendingResponses, } from "./__fixtures__/xTrendingCapture"; import type { BrowserContextLike, ChromiumLike, PageLike } from "./playwrightRuntime"; import type { Paths } from "../lib/paths"; const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-read-")); after(() => rmSync(TMP, { recursive: true, force: true })); let dirs = 0; async function read( trending: FakeTrendingPage, // One tab unless a test asks for both: the page's other tab is R3's tests' (below). over: { scrolls?: number; posts?: number; signal?: AbortSignal; tabs?: Array<"top" | "latest">; pause?: (ms: number) => Promise; now?: () => number; timeouts?: { call?: number; read?: number }; } = {}, ): Promise<{ result: TrendingPageRead; dir: string; closed: number; pauses: number[]; log: string[] }> { const dir = path.join(TMP, `read-${++dirs}`); const pauses: number[] = []; const log: string[] = []; let closed = 0; const page = fakeTrendingPage(() => ({ trending })); const result = await readXTrendingPage({ url: FIXTURE_TREND_URL, dir, openPage: async () => ({ page, close: async () => void closed++ }), limits: { scrolls: over.scrolls ?? 8, posts: over.posts ?? 60 }, tabs: over.tabs ?? ["top"], pauseMs: () => 7_000, pause: async (ms) => { pauses.push(ms); if (over.pause) await over.pause(ms); }, signal: over.signal ?? new AbortController().signal, onLog: (l) => log.push(l), now: over.now ?? (() => Date.parse("2026-11-17T10:00:00.000Z")), ...(over.timeouts ? { timeouts: over.timeouts } : {}), }); return { result, dir, closed, pauses, log }; } const timelineUrl = (n: number) => `https://x.com/i/api/graphql/q${n}/${FIXTURE_TIMELINE_OP}`; const tweet = (n: number) => ({ id: `19000000000000020${String(n).padStart(2, "0")}`, handle: `author_${n}`, text: `Post ${n}.` }); test("a read keeps every GraphQL answer raw and a screenshot, and stops after two scrolls with nothing new", async () => { const { result, dir, closed, pauses } = await read(fixtureTrendingResponses()); assert.deepEqual(result, { stop: "idle", scrolls: 3, responses: 4, saved: 4, bytes: result.bytes, statuses: { "200": 4 }, tweets: 4, shot: true, tabs: [{ asked: "top", tab: "Top", timelineId: FIXTURE_TOP_TIMELINE, scrolls: 3, posts: 4, stop: "idle" }], }); assert.ok(result.bytes > 0); assert.equal(closed, 1); // One wait after the load, one after each scroll: never two contacts in a row. assert.deepEqual(pauses, [7_000, 7_000, 7_000, 7_000]); const lines = await readCaptureLines(path.join(dir, "responses.jsonl")); assert.deepEqual(lines.map((l) => [l.n, l.op, l.status]), [ [1, "ExampleTrendPage", 200], [2, FIXTURE_TIMELINE_OP, 200], [3, "HomeTimeline", 200], [4, FIXTURE_TIMELINE_OP, 200], ]); assert.ok(lines.every((l) => l.body !== undefined && l.at === "2026-11-17T10:00:00.000Z")); // The answer that is not GraphQL was never kept. assert.ok(!readFileSync(path.join(dir, "responses.jsonl"), "utf8").includes("example.json")); assert.equal(readFileSync(path.join(dir, "page.png")).subarray(1, 4).toString(), "PNG"); }); test("the scroll cap and the post cap each stop a read", async () => { const pages = (count: number) => ({ load: [{ url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }], scrolls: Array.from({ length: count }, (_, i) => [ { url: timelineUrl(i + 1), status: 200, body: fixtureTimelineBody([tweet(i + 1)]) }, ]), }); const capped = await read(pages(10), { scrolls: 3 }); assert.equal(capped.result.stop, "scroll-cap"); assert.equal(capped.result.scrolls, 3); assert.equal(capped.result.tweets, 4); const full = await read(pages(10), { posts: 2 }); assert.equal(full.result.stop, "post-cap"); assert.equal(full.result.scrolls, 1); assert.equal(full.result.tweets, 2); }); test("a 429 stops the read at once: no scroll follows it", async () => { const first = await read({ load: [ { url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }, { url: timelineUrl(1), status: 429, text: "Rate limit exceeded" }, ], scrolls: [[{ url: timelineUrl(2), status: 200, body: fixtureTimelineBody([tweet(2)]) }]], }); assert.equal(first.result.stop, "rate-limit"); assert.equal(first.result.scrolls, 0); assert.deepEqual(first.result.statuses, { "200": 1, "429": 1 }); assert.equal(first.result.tweets, 1); assert.deepEqual(first.pauses, [7_000]); // On a scroll: that scroll is the last. const later = await read({ load: [{ url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }], scrolls: [[{ url: timelineUrl(1), status: 429, text: "" }], [{ url: timelineUrl(2), status: 200, body: {} }]], }); assert.equal(later.result.stop, "rate-limit"); assert.equal(later.result.scrolls, 1); }); test("X's login page, or a 401, is a login wall: nothing is scrolled", async () => { const walled = await read({ href: "https://x.com/i/flow/login?redirect_after_login=%2Fi%2Ftrending%2F1", load: [], scrolls: [[]] }); assert.equal(walled.result.stop, "login-wall"); assert.equal(walled.result.scrolls, 0); const refused = await read({ load: [{ url: timelineUrl(0), status: 401, body: { errors: [{ code: 32 }] } }] }); assert.equal(refused.result.stop, "login-wall"); assert.equal(isXLoginHref("https://x.com/login"), true); assert.equal(isXLoginHref("https://x.com/account/access"), true); assert.equal(isXLoginHref("https://x.com/i/trending/1"), false); assert.equal(isXLoginHref("https://x.com/login_help_desk/status/1"), false); assert.equal(isXLoginHref(null), false); }); test("a page that does not load is an error with its first line; a cancelled read stops before it scrolls", async () => { const broken = await read({ gotoError: "net::ERR_NAME_NOT_RESOLVED at https://x.com/i/trending/1\n call log…", load: [] }); assert.equal(broken.result.stop, "error"); assert.equal(broken.result.error, "net::ERR_NAME_NOT_RESOLVED at https://x.com/i/trending/1"); assert.equal(broken.closed, 1); assert.equal(existsSync(path.join(broken.dir, "responses.jsonl")), true); const ac = new AbortController(); ac.abort(); const cancelled = await read(fixtureTrendingResponses(), { signal: ac.signal }); assert.equal(cancelled.result.stop, "cancelled"); assert.equal(cancelled.result.scrolls, 0); }); test("an answer that is not JSON is counted and not kept", async () => { const { result, dir } = await read({ load: [{ url: timelineUrl(0), status: 200, text: "not json" }] }); assert.equal(result.responses, 1); assert.equal(result.saved, 0); const [line] = await readCaptureLines(path.join(dir, "responses.jsonl")); assert.equal(line.skipped, "not-json"); assert.equal(line.body, undefined); }); // --- review 1: caps, a 403, a 401 mid-scroll, deadlines, the closed file ------ async function readWith( page: PageLike, over: Partial[0]> & { close?: () => Promise; kill?: () => Promise } = {}, ) { const dir = path.join(TMP, `read-${++dirs}`); const log: string[] = []; const { close, kill, ...rest } = over; const result = await readXTrendingPage({ url: FIXTURE_TREND_URL, dir, openPage: async () => ({ page, close: close ?? (async () => {}), ...(kill ? { kill } : {}) }), limits: { scrolls: 8, posts: 60 }, pauseMs: () => 0, pause: async () => {}, signal: new AbortController().signal, onLog: (l) => log.push(l), ...rest, }); return { result, dir, log }; } test("the byte caps: an answer too large, and answers past the read's cap, are counted and not kept", async () => { const big = fixtureTimelineBody(Array.from({ length: 6 }, (_, i) => tweet(i))); const small = fixtureTimelineBody([tweet(7)]); const smallBytes = Buffer.byteLength(JSON.stringify(small)); const page = fakeTrendingPage(() => ({ trending: { load: [ { url: timelineUrl(0), status: 200, body: big }, { url: timelineUrl(1), status: 200, body: small }, { url: timelineUrl(2), status: 200, body: small }, ], scrolls: [[], []], }, })); const { result, dir } = await readWith(page, { maxResponseBytes: smallBytes + 10, maxReadBytes: smallBytes + 10 }); assert.equal(result.responses, 3); assert.equal(result.saved, 1); assert.equal(result.bytes, smallBytes); assert.equal(result.tweets, 1); const lines = await readCaptureLines(path.join(dir, "responses.jsonl")); assert.deepEqual(lines.map((l) => [l.n, l.skipped ?? "kept", l.body === undefined]), [ [1, "too-large", true], [2, "kept", false], [3, "over-cap", true], ]); assert.ok(lines[0].bytes > smallBytes + 10); }); test("a 403 stops the read at once: no scroll follows, and it is not a login wall", async () => { const first = await read({ load: [ { url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }, { url: timelineUrl(1), status: 403, body: { errors: [{ code: 200 }] } }, ], scrolls: [[{ url: timelineUrl(2), status: 200, body: fixtureTimelineBody([tweet(2)]) }]], }); assert.equal(first.result.stop, "forbidden"); assert.equal(first.result.scrolls, 0); assert.equal(first.result.tweets, 1); // On X's login page a 403 is the login wall's. const walled = await read({ href: "https://x.com/i/flow/login", load: [{ url: timelineUrl(0), status: 403, text: "" }] }); assert.equal(walled.result.stop, "login-wall"); // And a rate limit beside a 403 is the rate limit. const both = await read({ load: [{ url: timelineUrl(0), status: 403, text: "" }, { url: timelineUrl(1), status: 429, text: "" }] }); assert.equal(both.result.stop, "rate-limit"); }); test("a 401 on a scroll ends the read there, as a login wall", async () => { const { result } = await read({ load: [{ url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }], scrolls: [ [{ url: timelineUrl(1), status: 200, body: fixtureTimelineBody([tweet(1)]) }], [{ url: timelineUrl(2), status: 401, body: { errors: [{ code: 32 }] } }], [{ url: timelineUrl(3), status: 200, body: fixtureTimelineBody([tweet(3)]) }], ], }); assert.equal(result.stop, "login-wall"); assert.equal(result.scrolls, 2); assert.equal(result.tweets, 2); }); const never = () => new Promise(() => {}); test("a page that stops answering ends the read with a sentence; the browser is closed, and killed when closing hangs too", async () => { // The scroll never answers. const base = fakeTrendingPage(() => ({ trending: { load: [{ url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }], scrolls: [[]] } })); let closed = 0; const hungScroll = { ...base, evaluate: (fn: string) => (fn.includes("scrollTo") ? never() : base.evaluate(fn)) } as PageLike; const scroll = await readWith(hungScroll, { timeouts: { call: 40 }, close: async () => void closed++ }); assert.equal(scroll.result.stop, "deadline"); assert.equal(scroll.result.error, "the page did not answer within 0 s (scrolling)"); assert.equal(scroll.result.tweets, 1); assert.equal(closed, 1); assert.equal((await readCaptureLines(path.join(scroll.dir, "responses.jsonl"))).length, 1); // The load never answers. const hungLoad = { ...base, goto: () => never() } as PageLike; const load = await readWith(hungLoad, { timeouts: { load: 40 } }); assert.equal(load.result.stop, "deadline"); assert.match(load.result.error ?? "", /did not answer within 0 s \(loading the page\)/); // Closing never answers: the browser is killed, and the read still returns. let killed = 0; const stuck = await readWith(fakeTrendingPage(() => ({ trending: { load: [], scrolls: [[], []] } })), { timeouts: { close: 40 }, close: () => never(), kill: async () => void killed++, }); assert.equal(stuck.result.stop, "idle"); assert.equal(killed, 1); assert.ok(stuck.log.some((l) => /The browser did not close .*; killing it\./.test(l))); }); test("the whole read has a deadline: past it the read stops where it is, what was captured kept", async () => { const pages = { load: [{ url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }], scrolls: Array.from({ length: 20 }, (_, i) => [{ url: timelineUrl(i + 1), status: 200, body: fixtureTimelineBody([tweet(i + 1)]) }]), }; const { result, dir } = await readWith(fakeTrendingPage(() => ({ trending: pages })), { limits: { scrolls: 20, posts: 200 }, // Each wait is 30 ms of real time; the read may take 100. pauseMs: () => 30, pause: undefined, timeouts: { read: 100 }, }); assert.equal(result.stop, "deadline"); assert.ok(result.scrolls >= 1 && result.scrolls < 20, String(result.scrolls)); assert.equal((await readCaptureLines(path.join(dir, "responses.jsonl"))).length, result.responses); }); test("once the read has returned, a late answer is not appended to the capture", async () => { const handlers: Array<(res: unknown) => void> = []; const base = fakeTrendingPage(() => ({ trending: { load: [{ url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }], scrolls: [[], []] } })); const page = { ...base, on: (event: string, cb: (arg: never) => void) => { if (event === "response") handlers.push(cb as (res: unknown) => void); base.on(event, cb); }, } as PageLike; const { result, dir } = await readWith(page); const before = readFileSync(path.join(dir, "responses.jsonl"), "utf8"); for (const h of handlers) { h({ url: () => timelineUrl(9), status: () => 200, text: async () => JSON.stringify(fixtureTimelineBody([tweet(9)])) }); } await new Promise((r) => setTimeout(r, 30)); assert.equal(readFileSync(path.join(dir, "responses.jsonl"), "utf8"), before); assert.equal(result.responses, 1); }); test("an answer whose body cannot be read costs that answer, not the read", async () => { const handlers: Array<(res: unknown) => void> = []; const page = { ...fakeTrendingPage(() => ({ trending: { load: [], scrolls: [[], []] } })), on: (event: string, cb: (arg: never) => void) => void (event === "response" && handlers.push(cb as (res: unknown) => void)), goto: async () => { for (const h of handlers) { h({ url: () => timelineUrl(0), status: () => 200, text: () => Promise.reject(new Error("the body is gone")) }); h({ url: () => { throw new Error("no url"); }, status: () => 200, text: async () => "{}" }); } return null; }, } as PageLike; const { result, dir } = await readWith(page); assert.equal(result.stop, "idle"); assert.equal(result.responses, 1); assert.equal((await readCaptureLines(path.join(dir, "responses.jsonl")))[0].skipped, "unread"); }); // --- which browser opens --------------------------------------------------- function stubChromium(extra: Partial = {}) { const launches: Array<{ dir: string; opts: Record }> = []; const page = fakeTrendingPage(() => ({})); const context: BrowserContextLike = { newPage: async () => page, pages: () => [], cookies: async () => [], addCookies: async () => {}, close: async () => {}, on: () => {}, }; const chromium: ChromiumLike = { launch: async () => { throw new Error("not used"); }, launchPersistentContext: async (dir, opts) => { launches.push({ dir, opts }); return context; }, ...extra, }; return { chromium, launches }; } const paths = (name: string) => ({ transcriptsDir: path.join(TMP, name) }) as unknown as Paths; test("a read opens the connected profile headless; \"headed\" opens it in a window, through the display search", async () => { const quiet = stubChromium(); await openXTrendingPage(paths("headless"), { chromium: quiet.chromium }); assert.equal(quiet.launches.length, 1); assert.equal(quiet.launches[0].dir, path.join(TMP, "headless", ".x-session", "profile")); assert.equal(quiet.launches[0].opts.headless, true); const window = stubChromium({ opensNoWindow: true }); const log: string[] = []; await openXTrendingPage(paths("headed"), { headed: true, chromium: window.chromium, env: { PATH: "" }, onLog: (l) => log.push(l) }); assert.equal(window.launches.length, 1); assert.equal(window.launches[0].dir, path.join(TMP, "headed", ".x-session", "profile")); assert.equal(window.launches[0].opts.headless, false); // No desktop: the Connects' refusal, before any browser starts. const none = stubChromium(); await assert.rejects( openXTrendingPage(paths("nodesk"), { headed: true, chromium: none.chromium, env: { PATH: "" }, display: { run: async () => ({ stdout: "", exitCode: 1 }), fs: { readdir: () => [], isSocket: () => false, ownedByMe: () => false }, }, }), /no desktop session/, ); assert.equal(none.launches.length, 0); }); test("a context whose first page cannot be made is closed, not left holding the profile", async () => { for (const headed of [false, true]) { let closed = 0; const context: BrowserContextLike = { newPage: async () => { throw new Error("Target page, context or browser has been closed"); }, pages: () => [], cookies: async () => [], addCookies: async () => {}, close: async () => void closed++, on: () => {}, }; const chromium: ChromiumLike = { opensNoWindow: true, launch: async () => { throw new Error("not used"); }, launchPersistentContext: async () => context, }; await assert.rejects( openXTrendingPage(paths(`newpage-${headed}`), { headed, chromium, env: { PATH: "" } }), /Target page, context or browser has been closed/, ); assert.equal(closed, 1, headed ? "headed" : "headless"); } }); // --- review 2 --------------------------------------------------------------- test("N1: a browser that opens after the deadline, or after a cancel, is closed; an aborted read opens none", async () => { // The launch resolves 80 ms in; the read gave it 30. let closed = 0; let opened = 0; const slow = () => new Promise<{ page: PageLike; close: () => Promise }>((resolve) => setTimeout(() => { opened++; resolve({ page: fakeTrendingPage(() => ({})), close: async () => void closed++ }); }, 80), ); const late = await readXTrendingPage({ url: FIXTURE_TREND_URL, dir: path.join(TMP, `read-${++dirs}`), openPage: slow, limits: { scrolls: 8, posts: 60 }, pauseMs: () => 0, pause: async () => {}, signal: new AbortController().signal, timeouts: { load: 30 }, }); assert.equal(late.stop, "deadline"); assert.match(late.error ?? "", /opening the browser/); assert.equal(closed, 0, "not open yet when the read returned"); await new Promise((r) => setTimeout(r, 120)); assert.equal(opened, 1); assert.equal(closed, 1, "the browser that opened late was closed"); // Cancelled while it launches. const ac = new AbortController(); setTimeout(() => ac.abort(), 20); const cancelled = await readXTrendingPage({ url: FIXTURE_TREND_URL, dir: path.join(TMP, `read-${++dirs}`), openPage: slow, limits: { scrolls: 8, posts: 60 }, pauseMs: () => 0, pause: async () => {}, signal: ac.signal, }); assert.equal(cancelled.stop, "cancelled"); await new Promise((r) => setTimeout(r, 120)); assert.equal(opened, 2); assert.equal(closed, 2); // Already cancelled on entry: no browser is asked for at all. const gone = new AbortController(); gone.abort(); let asked = 0; const never = await readXTrendingPage({ url: FIXTURE_TREND_URL, dir: path.join(TMP, `read-${++dirs}`), openPage: async () => { asked++; return { page: fakeTrendingPage(() => ({})), close: async () => {} }; }, limits: { scrolls: 8, posts: 60 }, pauseMs: () => 0, pause: async () => {}, signal: gone.signal, }); assert.equal(never.stop, "cancelled"); assert.equal(asked, 0); }); test("N3: a call bounded on a signal already aborted leaves no unhandled rejection behind", async () => { const unhandled: unknown[] = []; const onUnhandled = (e: unknown) => void unhandled.push(e); process.on("unhandledRejection", onUnhandled); try { const ac = new AbortController(); ac.abort(); let reject!: (e: Error) => void; const orphan = new Promise((_, r) => (reject = r)); await assert.rejects(bounded("reading its address", orphan, 1_000, ac.signal), /cancelled/); // The context closes later and the orphaned call rejects. reject(new Error("Target closed")); await new Promise((r) => setTimeout(r, 30)); assert.deepEqual(unhandled, []); } finally { process.off("unhandledRejection", onUnhandled); } }); // Lane x-trending-2: a browser that will not close is killed by its checked pid. test("kill ends the browser's own process when its pid checks out; else it says why and closes again", async () => { const profileDir = path.join(TMP, "killable", ".x-session", "profile"); const stub = stubChromium(); const log: string[] = []; const sent: Array<[number, string]> = []; const session = await openXTrendingPage(paths("killable"), { chromium: stub.chromium, onLog: (l) => log.push(l), killDeps: { platform: "linux", hostname: "host", readlink: async (file) => { assert.equal(file, path.join(profileDir, "SingletonLock")); return "host-31337"; }, cmdline: async () => `chrome\0--user-data-dir=${profileDir}\0`, kill: (pid, signal) => void sent.push([pid, signal]), }, }); await session.kill!(); assert.deepEqual(sent, [[31337, "SIGKILL"]]); assert.ok(log.some((l) => l === "Killed the browser that held the X profile (pid 31337): the profile is free again."), log.join("\n")); // A lock whose process does not name this profile: never signalled; closed again, and said. let closes = 0; const other = stubChromium(); const real = other.chromium.launchPersistentContext; other.chromium.launchPersistentContext = async (dir, opts) => { const context = await real(dir, opts); return { ...context, close: async () => void closes++ }; }; const log2: string[] = []; const stale = await openXTrendingPage(paths("stale"), { chromium: other.chromium, onLog: (l) => log2.push(l), killDeps: { platform: "linux", hostname: "host", readlink: async () => "host-31337", cmdline: async () => "bash\0", kill: (pid, signal) => void sent.push([pid, signal]) }, }); await stale.kill!(); assert.equal(sent.length, 1); assert.equal(closes, 1); assert.ok(log2.some((l) => /^The browser was not killed \(process 31337 does not name this profile on its command line \(a stale lock\): it is left alone\); closing it again instead\.$/.test(l)), log2.join("\n")); // Off Linux: the same fallback. const log3: string[] = []; const mac = await openXTrendingPage(paths("mac"), { chromium: stubChromium().chromium, onLog: (l) => log3.push(l), killDeps: { platform: "darwin" } }); await mac.kill!(); assert.ok(log3.some((l) => /not killed \(finding the browser's process is Linux-only\); closing it again instead/.test(l))); }); // ── added scope R3: both tabs in one read ────────────────────────────────── const BOTH: Array<"top" | "latest"> = ["top", "latest"]; test("R3: the deadline covers what the read may do: 6 min for one tab at 20 scrolls, 10 for both, 18 at the maximum", async () => { const { readDeadlineMs, READ_DEADLINE_MS, TAB_WAIT_MS } = await import("./xTrendingRead"); assert.equal(readDeadlineMs({ scrolls: 20 }, 1), 6 * 60_000); assert.equal(READ_DEADLINE_MS, 6 * 60_000); assert.equal(readDeadlineMs({ scrolls: 20 }, 2), 10 * 60_000); assert.equal(readDeadlineMs({ scrolls: 40 }, 2), 18 * 60_000); assert.equal(TAB_WAIT_MS, 20_000); }); test("R3: after Top is read to its stop the page's Latest tab is pressed and read under the same caps, into the one capture", async () => { const { result, dir, pauses, log } = await read(fixtureTwoTabResponses(), { tabs: BOTH }); assert.equal(result.stop, "idle"); assert.deepEqual(result.tabs, [ { asked: "top", tab: "Top", timelineId: FIXTURE_TOP_TIMELINE, scrolls: 3, posts: 4, stop: "idle" }, { asked: "latest", tab: "Latest", timelineId: FIXTURE_LATEST_TIMELINE, scrolls: 2, posts: 3, stop: "idle" }, ]); assert.equal(result.scrolls, 5); // Five distinct posts: two of Latest's three are Top's too. assert.equal(result.tweets, 5); assert.ok(log.includes('Pressed the page\'s "Latest" tab.')); // One capture: Top's answers, then Latest's, each request naming its own timeline. const lines = await readCaptureLines(path.join(dir, "responses.jsonl")); const timelines = lines.filter((l) => l.op === FIXTURE_TIMELINE_OP).map((l) => JSON.parse(new URL(l.url).searchParams.get("variables")!).timelineId); assert.deepEqual(timelines, [FIXTURE_TOP_TIMELINE, FIXTURE_TOP_TIMELINE, FIXTURE_TOP_TIMELINE, FIXTURE_LATEST_TIMELINE, FIXTURE_LATEST_TIMELINE]); assert.equal(readFileSync(path.join(dir, "page-latest.png")).subarray(1, 4).toString(), "PNG"); assert.equal(result.tabShot, true); // Never two contacts in a row: a wait after the load, after every scroll, and after the press. assert.ok(pauses.filter((ms) => ms === 7_000).length >= 1 + 5 + 1); }); test("R3: a Latest tab the page does not show, or one whose press brings nothing, is \"not read\" with its reason — Top's read stands", async () => { const hidden = fixtureTwoTabResponses(); hidden.tabs.Latest.hidden = true; const a = await read(hidden, { tabs: BOTH }); assert.equal(a.result.stop, "idle"); assert.deepEqual(a.result.tabs[1], { asked: "latest", tab: "Latest", timelineId: FIXTURE_LATEST_TIMELINE, scrolls: 0, posts: 0, stop: "not-read", why: 'the page shows no tab named "Latest" in its tab list' }); assert.deepEqual(a.result.tabs[0], { asked: "top", tab: "Top", timelineId: FIXTURE_TOP_TIMELINE, scrolls: 3, posts: 4, stop: "idle" }); // Pressed, and the page asks nothing for it. const silent = fixtureTwoTabResponses(); silent.tabs.Latest = {}; const b = await read(silent, { tabs: BOTH }); assert.equal(b.result.stop, "idle"); assert.equal(b.result.tabs[1].stop, "not-read"); assert.equal(b.result.tabs[1].why, 'pressing "Latest" brought no answer for its timeline within 20 s'); assert.equal(b.result.scrolls, 3, "no scroll followed a press that brought nothing"); // The page's own answer names no tabs at all (it was not fetched). const noPage = fixtureTwoTabResponses(); noPage.load = noPage.load.slice(1); const c = await read(noPage, { tabs: BOTH }); assert.equal(c.result.tabs[1].stop, "not-read"); assert.match(c.result.tabs[1].why ?? "", /page's own answer, which names its tabs and their timelines, was not among what it fetched/); assert.equal(c.result.tabs[0].tab, undefined); assert.equal(c.result.tabs[0].posts, 4); }); test("R3: a 429 on Latest stops the whole read; a 429 on Top means Latest is never pressed", async () => { const limited = fixtureTwoTabResponses(); limited.tabs.Latest.scrolls = [[{ url: fixtureLatestFirst([]).url, status: 429, text: "" }]]; const a = await read(limited, { tabs: BOTH }); assert.equal(a.result.stop, "rate-limit"); assert.equal(a.result.tabs[1].stop, "rate-limit"); assert.equal(a.result.tabs[1].scrolls, 1); assert.equal(a.result.tabs[0].stop, "idle"); const onTop = fixtureTwoTabResponses(); onTop.scrolls = [[{ url: fixtureTwoTabResponses().load[1].url, status: 429, text: "" }]]; const b = await read(onTop, { tabs: BOTH }); assert.equal(b.result.stop, "rate-limit"); assert.equal(b.result.tabs.length, 1); assert.ok(!b.log.some((l) => /Pressed/.test(l))); assert.equal(existsSync(path.join(b.dir, "page-latest.png")), false); }); test("R3: each tab has the full caps; asked for Latest alone, Top is not scrolled", async () => { const many = fixtureTwoTabResponses(FIXTURE_LATEST_PAGE); // Top stops at a post cap of 4 after its first scroll; Latest then has its own count of 3 and reads on. const capped = await read(many, { tabs: BOTH, posts: 4 }); assert.deepEqual(capped.result.tabs.map((t) => [t.asked, t.stop, t.posts]), [["top", "post-cap", 4], ["latest", "idle", 3]]); const only = await read(fixtureTwoTabResponses(), { tabs: ["latest"] }); assert.deepEqual(only.result.tabs.map((t) => [t.asked, t.stop, t.scrolls]), [["top", "not-asked", 0], ["latest", "idle", 2]]); // What the page loaded of Top by itself is in the capture all the same. assert.equal(only.result.tabs[0].posts, 3); }); // ── review 2 (lane x-followups): S1, S2, S3 ─────────────────────────────── test("S1: Latest is pressed only as a TAB inside the page's tab list, by its exact name — never a link or a button named like it", async () => { // A link named exactly "Latest", and no tab: nothing is pressed. const linkOnly = fixtureTwoTabResponses(); linkOnly.tabs.Latest.role = "link"; const a = await read(linkOnly, { tabs: BOTH }); assert.equal(a.result.stop, "idle"); assert.deepEqual(a.result.tabs[1], { asked: "latest", tab: "Latest", timelineId: FIXTURE_LATEST_TIMELINE, scrolls: 0, posts: 0, stop: "not-read", why: 'the page shows no tab named "Latest" in its tab list' }); assert.ok(!a.log.some((l) => /Pressed/.test(l))); assert.equal(a.result.scrolls, 3, "nothing of Latest was scrolled"); // A button: the same. const button = fixtureTwoTabResponses(); button.tabs.Latest.role = "button"; assert.equal((await read(button, { tabs: BOTH })).result.tabs[1].stop, "not-read"); // A tab, but outside the page's tab list: the same. const loose = fixtureTwoTabResponses(); loose.tabs.Latest.outsideTablist = true; assert.equal((await read(loose, { tabs: BOTH })).result.tabs[1].why, 'the page shows no tab named "Latest" in its tab list'); }); test("S1: a press that leaves the trending page stops the read at once and closes the browser: Top read, Latest not read, the page changed", async () => { const away = fixtureTwoTabResponses(); away.tabs.Latest.navigatesTo = "https://x.com/search?q=example&f=live"; const r = await read(away, { tabs: BOTH }); assert.equal(r.result.stop, "idle", "Top's read stands"); assert.equal(r.result.tabs[0].stop, "idle"); assert.deepEqual([r.result.tabs[1].stop, r.result.tabs[1].why, r.result.tabs[1].scrolls], ["not-read", "the page changed", 0]); assert.equal(r.result.scrolls, 3, "no scroll after the page changed"); assert.equal(r.result.tabShot, undefined, "nothing more is done with the page"); assert.equal(r.closed, 1); }); test("S2: a press that fails — the click throws, or the page does not answer the look-up — is \"not read\" with why; Top stands", async () => { const throws = fixtureTwoTabResponses(); throws.tabs.Latest.clickError = "Element is not visible"; const a = await read(throws, { tabs: BOTH }); assert.equal(a.result.stop, "idle"); assert.equal(a.result.tabs[1].stop, "not-read"); assert.match(a.result.tabs[1].why ?? "", /^pressing "Latest" failed: Element is not visible/); assert.equal(a.result.error, undefined); // The look-up never answers: the page call's deadline, caught. const hangs = fixtureTwoTabResponses(); hangs.tabs.Latest.countHangs = true; const b = await read(hangs, { tabs: BOTH, timeouts: { call: 50 } }); assert.equal(b.result.stop, "idle"); assert.equal(b.result.tabs[1].stop, "not-read"); assert.match(b.result.tabs[1].why ?? "", /^pressing "Latest" failed: the page did not answer within 0 s \(looking for the "Latest" tab\)/); assert.equal(b.closed, 1); }); test("S2: the read's deadline during Latest keeps Top's result: Latest stopped at the deadline, with what it had", async () => { // Latest scrolls without end; the read's deadline falls in the middle of it. const endless = fixtureTwoTabResponses(); endless.tabs.Latest.scrolls = Array.from({ length: 50 }, (_, i) => [fixtureLatestFirst([{ id: `19000000000000031${String(i).padStart(2, "0")}`, handle: `l_${i}`, text: `Latest ${i}.` }])]); let clock = 0; const r = await read(endless, { tabs: BOTH, scrolls: 40, posts: 400, // Each pause is a second of the read's clock; the deadline is 20 of them. pause: async () => { clock += 1; await new Promise((res) => setTimeout(res, 5)); }, timeouts: { read: 120 }, }); assert.ok(clock > 0); assert.equal(r.result.tabs[0].stop, "idle"); assert.equal(r.result.tabs[1].stop, "deadline"); assert.ok(r.result.tabs[1].posts > 0, "what Latest had is kept"); assert.equal(r.result.stop, "idle", "the read is Top's, not a failure"); assert.equal(r.result.error, undefined); }); test("S3: the wait for Latest's answer is bounded by its own 20 s wall clock, each step's settle counted", async () => { const silent = fixtureTwoTabResponses(); silent.tabs.Latest = {}; // Every pause takes 5 s of the clock: the wait ends after four steps, not forty. let t = Date.parse("2026-11-17T10:00:00.000Z"); let steps = 0; const r = await read(silent, { tabs: BOTH, now: () => t, pause: async (ms) => { if (ms === 500) steps++; t += 5_000; }, }); assert.equal(r.result.tabs[1].stop, "not-read"); assert.equal(r.result.tabs[1].why, 'pressing "Latest" brought no answer for its timeline within 20 s'); assert.ok(steps <= 4, `waited ${steps} steps`); });