commit 07b88ae910e4f646ea2c710b6f1c7cce9408734f
parent c5037e3791e6ddfa58b8d698681045540afc3a97
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 18 Nov 2026 21:53:49 -0500
x-trending: review 2 S1-S3 -- the Latest press is the page's own tab and nothing else, a failed press or a deadline inside Latest keeps Top's read, and the wait has its own clock
- S1: Latest is pressed only as role "tab" inside the page's tab list, by
the exact name the page's answer gave: never a link or a button named like
it. After the press the read checks the page is still the trending page
(host and path); if not, it stops at once, closes the browser and ends
"Top read; Latest not read: the page changed" -- no strike. A tab the read
says was not read gives the library nothing (its answers stay in the
capture).
- S2: a press that throws, is not actionable or meets a look-up deadline is
"Top read; Latest not read: pressing "Latest" failed: <why>" -- a read,
Top ingested. The read's deadline (or a page call that stops answering)
inside Latest stops Latest only: "Top read; Latest stopped at the deadline
(<n> posts read)", what Latest had kept, pageEnd false for it.
- S3: the wait for Latest's answer is bounded by its own 20 s wall clock,
each step's settle counted.
- The fake page gains a tab list, links and buttons by role, a click that
throws, a look-up or scroll that never answers, and a press that leaves.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
7 files changed, 370 insertions(+), 70 deletions(-)
diff --git a/common/controller/readXTrending.test.ts b/common/controller/readXTrending.test.ts
@@ -64,7 +64,15 @@ async function run(
paths: Paths,
trending: FakeTrendingPage,
ask: Partial<ReadXTrendingAsk> = {},
- over: { readId?: string; at?: string; profileBusy?: () => string | null; held?: () => Promise<string | null>; ingest?: never; openPage?: never } = {},
+ over: {
+ readId?: string;
+ at?: string;
+ profileBusy?: () => string | null;
+ held?: () => Promise<string | null>;
+ ingest?: never;
+ openPage?: never;
+ timeouts?: { call?: number; read?: number };
+ } = {},
): Promise<{ result: ReadXTrendingResult; notes: Array<Record<string, unknown>>; 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);
@@ -89,6 +97,7 @@ async function run(
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<string, unknown>);
@@ -845,7 +854,7 @@ test("R3: a Latest tab that cannot be opened ends the read \"Top read; Latest no
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"\./);
+ 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 () => {
@@ -889,3 +898,34 @@ test("R2a: a trending read outside the editor's job, or in a job on another queu
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).
+});
diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts
@@ -376,11 +376,19 @@ function tabText(tabs: Ingested["tabs"]): string {
// "Top read; Latest not read: <why>." — 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");
+ 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 && t.stop !== "not-read" && t.stop !== "not-asked").map((t) => t.tab);
- return ` ${read.length ? `${read.join(" and ")} read; ` : ""}${missed.map((t) => `${t.tab ?? (t.asked === "latest" ? "Latest" : "Top")} not read: ${t.why ?? "it could not be opened"}`).join("; ")}.`;
+ 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."
@@ -418,7 +426,27 @@ async function ingestCapture(o: {
}): Promise<Ingested> {
const file = path.join(trendingReadDir(o.channelRoot, o.readId), TRENDING_RESPONSES_FILENAME);
const lines = await readCaptureLines(file).catch(() => []);
- const parsed = parseTrendingCapture(lines, o.slug);
+ const whole = parseTrendingCapture(lines, o.slug);
+ // 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);
@@ -438,7 +466,8 @@ async function ingestCapture(o: {
posts: listed?.postIds.length ?? 0,
scrolls: t.scrolls,
stop: t.stop,
- pageEnd: Boolean(listed?.pageEnd),
+ // 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);
@@ -549,6 +578,8 @@ export type ReadXTrendingDeps = {
// 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: {
@@ -650,6 +681,7 @@ export async function runXTrendingRead(o: {
signal,
onLog: log,
now,
+ ...(deps.timeouts ? { timeouts: deps.timeouts } : {}),
});
// What was read is kept whatever stopped it — except behind a login wall,
diff --git a/common/social/__fixtures__/xTrendingCapture.ts b/common/social/__fixtures__/xTrendingCapture.ts
@@ -193,7 +193,21 @@ export const FIXTURE_LATEST_PAGE: FixtureTweet[] = [
export function fixtureTwoTabResponses(latest: FixtureTweet[] = FIXTURE_LATEST_PAGE): {
load: FixtureResponse[];
scrolls: FixtureResponse[][];
- tabs: Record<string, { load?: FixtureResponse[]; scrolls?: FixtureResponse[][]; hidden?: boolean }>;
+ tabs: Record<
+ string,
+ {
+ load?: FixtureResponse[];
+ scrolls?: FixtureResponse[][];
+ hidden?: boolean;
+ // The fake page's other ways a "Latest" may be (social/fakeXProfileBrowser.ts FakeTrendingTab).
+ role?: "tab" | "link" | "button";
+ outsideTablist?: boolean;
+ clickError?: string;
+ countHangs?: boolean;
+ navigatesTo?: string;
+ scrollHangs?: boolean;
+ }
+ >;
} {
const top = fixtureTrendingResponses();
return {
diff --git a/common/social/fakeXProfileBrowser.ts b/common/social/fakeXProfileBrowser.ts
@@ -42,11 +42,28 @@ export type FakeTrendingPage = {
load: FakeTrendingResponse[];
scrolls?: FakeTrendingResponse[][];
// THE PAGE'S OTHER TABS (lane x-followups), by the label the page shows:
- // pressing one (getByRole("tab", {name})) plays its `load` back and makes
- // its `scrolls` the ones the next scrolls bring. A tab with `hidden` is not
- // on the page at all; one with no `load` is pressed and brings nothing (a
- // tab that never loads).
- tabs?: Record<string, { load?: FakeTrendingResponse[]; scrolls?: FakeTrendingResponse[][]; hidden?: boolean }>;
+ // pressing one (getByRole("tablist").getByRole("tab", {name})) plays its
+ // `load` back and makes its `scrolls` the ones the next scrolls bring. A tab
+ // with `hidden` is not on the page at all; one with no `load` is pressed and
+ // brings nothing (a tab that never loads). Review 2: `role` makes it a link
+ // or a button of that name instead (never pressed); `outsideTablist` puts
+ // it outside the tab list; `clickError` makes its click throw; `countHangs`
+ // makes its look-up never answer; `navigatesTo` is where the page is after
+ // it is pressed (another page).
+ tabs?: Record<string, FakeTrendingTab>;
+};
+
+export type FakeTrendingTab = {
+ load?: FakeTrendingResponse[];
+ scrolls?: FakeTrendingResponse[][];
+ hidden?: boolean;
+ role?: "tab" | "link" | "button";
+ outsideTablist?: boolean;
+ clickError?: string;
+ countHangs?: boolean;
+ navigatesTo?: string;
+ // Its scrolls never answer (a page that stops answering inside the tab).
+ scrollHangs?: boolean;
};
type FixtureFile = {
@@ -77,6 +94,8 @@ export function fakeTrendingPage(
let scrolled = 0;
// The tab pressed last ("" = the tab the page opened on).
let active = "";
+ // Where a press took the page (FakeTrendingTab.navigatesTo).
+ let movedTo: string | undefined;
const emit = (responses: FakeTrendingResponse[] | undefined) => {
for (const r of responses ?? []) {
const res = {
@@ -94,6 +113,7 @@ export function fakeTrendingPage(
asked = url;
scrolled = 0;
active = "";
+ movedTo = undefined;
if (f.trending?.gotoError) throw new Error(f.trending.gotoError);
emit(f.trending?.load);
return null;
@@ -103,26 +123,37 @@ export function fakeTrendingPage(
evaluate: async (fn: string) => {
const t = source().trending;
if (!t) return null;
- if (fn === "location.href") return t.href ?? asked;
+ if (fn === "location.href") return movedTo ?? t.href ?? asked;
+ if (fn.includes("scrollTo") && active && t.tabs?.[active]?.scrollHangs) return new Promise(() => {});
if (fn.includes("scrollTo")) emit((active ? t.tabs?.[active]?.scrolls : t.scrolls)?.[scrolled++]);
return null;
},
- // The page's tabs, pressed as a person presses them. Only role "tab".
+ // The page's controls by role and name, as Playwright finds them: a tab
+ // list (holding the tabs that are in it), and tabs, links and buttons.
getByRole: (role: string, opts?: { name?: string | RegExp }) => {
- const name = typeof opts?.name === "string" ? opts.name : "";
- const tab = role === "tab" ? source().trending?.tabs?.[name] : undefined;
- const there = Boolean(tab && !tab.hidden);
- return {
- count: async () => (there ? 1 : 0),
- first: () => ({
- click: async () => {
- if (!there) throw new Error(`no tab named ${name}`);
- active = name;
- scrolled = 0;
- emit(source().trending?.tabs?.[name]?.load);
- },
- }),
+ const tabs = () => Object.entries(source().trending?.tabs ?? {}).filter(([, t]) => !t.hidden);
+ const control = (inList: boolean) => (r: string, o?: { name?: string | RegExp }) => {
+ const name = typeof o?.name === "string" ? o.name : "";
+ const tab = tabs().find(([label, t]) => label === name && (t.role ?? "tab") === r && (inList ? !t.outsideTablist : true))?.[1];
+ return {
+ count: () => (tab?.countHangs ? new Promise<number>(() => {}) : Promise.resolve(tab ? 1 : 0)),
+ first: () => ({
+ click: async () => {
+ if (!tab) throw new Error(`no ${r} named ${name}`);
+ if (tab.clickError) throw new Error(tab.clickError);
+ active = name;
+ scrolled = 0;
+ if (tab.navigatesTo) movedTo = tab.navigatesTo;
+ emit(tab.load);
+ },
+ }),
+ };
};
+ if (role === "tablist") {
+ const any = tabs().some(([, t]) => (t.role ?? "tab") === "tab" && !t.outsideTablist) || tabs().some(([, t]) => t.countHangs);
+ return { count: async () => (any ? 1 : 0), first: () => ({ click: async () => {} }), getByRole: control(true) };
+ }
+ return control(false)(role, opts);
},
on: (event: string, cb: (arg: never) => void) => {
if (event === "response") handlers.push(cb as (res: unknown) => void);
diff --git a/common/social/playwrightRuntime.ts b/common/social/playwrightRuntime.ts
@@ -43,6 +43,14 @@ export type BrowserLike = {
close: () => Promise<void>;
};
+// What a role look-up finds (Playwright's Locator, the part used): how many,
+// the first pressed, and a look-up INSIDE it (a tab within a tab list).
+export type LocatorLike = {
+ count: () => Promise<number>;
+ first: () => { click: (opts?: { timeout?: number }) => Promise<void> };
+ getByRole?: (role: string, opts?: { name?: string | RegExp; exact?: boolean }) => LocatorLike;
+};
+
export type PageLike = {
goto: (url: string, opts?: unknown) => Promise<unknown>;
waitForSelector: (sel: string, opts?: unknown) => Promise<unknown>;
@@ -53,10 +61,7 @@ export type PageLike = {
// its name (Playwright's getByRole) — and pressed. A trending read presses
// the page's own tab with it (xTrendingRead.ts); nothing else does.
// Optional: a page without it has nothing to press.
- getByRole?: (
- role: string,
- opts?: { name?: string | RegExp; exact?: boolean },
- ) => { count: () => Promise<number>; first: () => { click: (opts?: { timeout?: number }) => Promise<void> } };
+ getByRole?: (role: string, opts?: { name?: string | RegExp; exact?: boolean }) => LocatorLike;
// The post capture's shot (xPostCapture.ts): a PNG of the page, clipped to
// the post. `clip` is in document coordinates when `fullPage` is set, in
// the window's otherwise.
diff --git a/common/social/xTrendingRead.test.ts b/common/social/xTrendingRead.test.ts
@@ -32,7 +32,15 @@ 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"> } = {},
+ over: {
+ scrolls?: number;
+ posts?: number;
+ signal?: AbortSignal;
+ tabs?: Array<"top" | "latest">;
+ pause?: (ms: number) => Promise<void>;
+ 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[] = [];
@@ -46,10 +54,14 @@ async function read(
limits: { scrolls: over.scrolls ?? 8, posts: over.posts ?? 60 },
tabs: over.tabs ?? ["top"],
pauseMs: () => 7_000,
- pause: async (ms) => void pauses.push(ms),
+ 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: () => Date.parse("2026-11-17T10:00:00.000Z"),
+ now: over.now ?? (() => Date.parse("2026-11-17T10:00:00.000Z")),
+ ...(over.timeouts ? { timeouts: over.timeouts } : {}),
});
return { result, dir, closed, pauses, log };
}
@@ -595,7 +607,7 @@ test("R3: a Latest tab the page does not show, or one whose press brings nothing
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"' });
+ 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();
@@ -642,3 +654,97 @@ test("R3: each tab has the full caps; asked for Latest alone, Top is not scrolle
// 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`);
+});
diff --git a/common/social/xTrendingRead.ts b/common/social/xTrendingRead.ts
@@ -236,6 +236,28 @@ export function abortablePause(ms: number, signal: AbortSignal): Promise<void> {
const SCROLL_TO_BOTTOM = "window.scrollTo(0, document.documentElement.scrollHeight)";
+// Whether the page is still the trending page the read opened (review 2 S1):
+// the same host and path. Its query may change (a tab may say itself there).
+export function sameTrendingPage(href: unknown, opened: string): boolean {
+ if (typeof href !== "string") return false;
+ try {
+ const a = new URL(href);
+ const b = new URL(opened);
+ return a.hostname.replace(/^www\./, "") === b.hostname.replace(/^www\./, "") && a.pathname.replace(/\/+$/, "") === b.pathname.replace(/\/+$/, "");
+ } catch {
+ return false;
+ }
+}
+
+// A page's path, for a log line: never its query (it may carry a search).
+function safePath(href: string): string {
+ try {
+ return new URL(href).pathname;
+ } catch {
+ return "an address that cannot be read";
+ }
+}
+
export async function readXTrendingPage(o: {
url: string;
// The read's directory (`trending/reads/<readId>`), made here.
@@ -304,6 +326,8 @@ export async function readXTrendingPage(o: {
// not the page's own answer (which names the tabs) was among what it fetched.
let firstTimeline: string | undefined;
let rateLimited = false;
+ // The read's deadline fell inside the second tab (review 2 S2).
+ let latestCut = false;
let unauthorized = false;
let forbidden = false;
let n = 0;
@@ -479,7 +503,13 @@ export async function readXTrendingPage(o: {
}
openingTab.posts = countOf(top?.timelineId);
- // THE OTHER TAB: pressed, never asked for.
+ // THE OTHER TAB: pressed, never asked for. WHATEVER HAPPENS HERE, THE
+ // OPENING TAB'S READ STANDS (review 2 S2): a press that fails is "not
+ // read", and the read's deadline falling inside it stops this tab only.
+ // `abandoned`: the page left the trending page — nothing more is done
+ // with it (S1); `hung`: a page call did not answer (no screenshot).
+ let abandoned = false;
+ let hung = false;
if (wanted.includes("latest") && !ends(stop)) {
const latest = tabOf("latest");
const second: TrendingTabRead = {
@@ -491,6 +521,14 @@ export async function readXTrendingPage(o: {
};
out.tabs.push(second);
const label = latest?.label ?? TRENDING_TAB_LABEL.latest;
+ // The read's own deadline (or a page that stopped answering) inside
+ // this tab: it stops here, with what it had; the read is the opening
+ // tab's. A cancel is the whole read's.
+ const cutHere = (err: unknown): boolean => {
+ if (err instanceof PageDeadlineError) hung = true;
+ if (o.signal.aborted) return false;
+ return pastDeadline || err instanceof PageDeadlineError;
+ };
if (!latest) {
second.why = pageInfo
? `the page's own answer names no "${label}" tab (it names: ${pageInfo.tabs.map((x) => `"${x.label}"`).join(", ") || "none"})`
@@ -498,26 +536,44 @@ export async function readXTrendingPage(o: {
} else if (!page.getByRole) {
second.why = "this page cannot be pressed";
} else {
- // The page's own control: a tab by role, else a link or a button of that name.
- let pressed = false;
+ // THE PAGE'S OWN TAB (S1): a control of role "tab", INSIDE the page's
+ // tab list, with exactly the name the page's own answer gave. Never a
+ // link or a button of that name: those go elsewhere.
const had = answersBy.get(latest.timelineId) ?? 0;
- for (const role of ["tab", "link", "button"]) {
- const found = page.getByRole(role, { name: latest.label, exact: true });
- const count = await bounded(`looking for the "${label}" tab`, found.count(), t.call, signal).catch((err) => {
- if (err instanceof PageDeadlineError) throw err;
- return 0;
- });
- if (!count) continue;
- await bounded(`pressing the "${label}" tab`, found.first().click({ timeout: Math.min(t.call, 15_000) }), t.call, signal);
- pressed = true;
- log(`Pressed the page's "${label}" tab.`);
- break;
+ let pressed = false;
+ try {
+ const list = page.getByRole("tablist");
+ const found = list.getByRole?.("tab", { name: latest.label, exact: true });
+ const count = found ? await bounded(`looking for the "${label}" tab`, found.count(), t.call, signal) : 0;
+ if (!found || !count) {
+ second.why = `the page shows no tab named "${label}" in its tab list`;
+ } else {
+ await bounded(`pressing the "${label}" tab`, found.first().click({ timeout: Math.min(t.call, 15_000) }), t.call, signal);
+ pressed = true;
+ log(`Pressed the page's "${label}" tab.`);
+ }
+ } catch (err) {
+ if (o.signal.aborted) throw err;
+ second.why = `pressing "${label}" failed: ${firstLine(err)}`;
+ if (err instanceof PageDeadlineError) hung = true;
}
- if (!pressed) {
- second.why = `the page shows no tab named "${label}"`;
- } else {
- // The page's own request for that tab's timeline: waited for, in short steps.
- for (let waited = 0; waited < t.tab && (answersBy.get(latest.timelineId) ?? 0) <= had && !signal.aborted && !blocked(); waited += 500) {
+ // STILL THE SAME PAGE (S1): a press that took the page anywhere else
+ // stops the read at once — nothing more is read, pressed or shot.
+ if (pressed) {
+ const href = await bounded("reading its address", page.evaluate("location.href"), t.call, signal).catch(() => null);
+ if (!sameTrendingPage(href, o.url)) {
+ second.why = "the page changed";
+ abandoned = true;
+ pressed = false;
+ log(`After pressing "${label}" the page is no longer the trending page${typeof href === "string" ? ` (${safePath(href)})` : ""}: the read stops here.`);
+ }
+ }
+ if (pressed) {
+ // The page's own request for that tab's timeline: waited for, in
+ // short steps, on ITS OWN 20 s WALL CLOCK (S3) — each step's settle
+ // counted, not only the steps.
+ const waitFrom = now();
+ for (let waited = 0; waited < t.tab && now() - waitFrom < t.tab && (answersBy.get(latest.timelineId) ?? 0) <= had && !signal.aborted && !blocked(); waited += 500) {
await pause(500, signal);
await settle();
}
@@ -525,31 +581,47 @@ export async function readXTrendingPage(o: {
second.stop = blocked()!;
stop = second.stop;
} else if (signal.aborted) {
- second.stop = pastDeadline ? "deadline" : "cancelled";
- stop = second.stop;
+ if (o.signal.aborted) {
+ second.stop = "cancelled";
+ stop = "cancelled";
+ } else {
+ second.stop = "deadline";
+ }
} else if ((answersBy.get(latest.timelineId) ?? 0) <= had) {
second.why = `pressing "${label}" brought no answer for its timeline within ${Math.round(t.tab / 1000)} s`;
} else {
- await pause(o.pauseMs(), signal);
- await settle();
- const r = await scrollTab(latest.timelineId);
- second.stop = r.stop;
- second.scrolls = r.scrolls;
- stop = r.stop;
+ const scrollsBefore = out.scrolls;
+ try {
+ await pause(o.pauseMs(), signal);
+ await settle();
+ const r = await scrollTab(latest.timelineId);
+ second.stop = r.stop;
+ // The deadline inside Latest is Latest's stop, not the read's.
+ if (r.stop !== "deadline") stop = r.stop;
+ } catch (err) {
+ if (!cutHere(err)) throw err;
+ second.stop = "deadline";
+ }
+ second.scrolls = out.scrolls - scrollsBefore;
}
}
}
second.posts = countOf(latest?.timelineId);
+ if (second.stop === "deadline") log(`The "${label}" tab stopped at the read's deadline, with ${second.posts} post(s).`);
// The page as it stood after the press (or the try): beside page.png.
- try {
- const png = await bounded("the second screenshot", page.screenshot({ type: "png" }), t.call, signal);
- await writeFile(path.join(o.dir, TRENDING_TAB_SHOT_FILENAME), png);
- out.tabShot = true;
- } catch (err) {
- if (err instanceof PageDeadlineError) throw err;
+ if (!abandoned && !hung && !signal.aborted) {
+ try {
+ const png = await bounded("the second screenshot", page.screenshot({ type: "png" }), t.call, signal);
+ await writeFile(path.join(o.dir, TRENDING_TAB_SHOT_FILENAME), png);
+ out.tabShot = true;
+ } catch {
+ /* the screenshot is a courtesy: its failure costs nothing */
+ }
}
if (second.stop === "not-read") log(`The "${label}" tab was not read: ${second.why}.`);
}
+ // The deadline fell inside the second tab: the read is the first's.
+ if (out.tabs[1]?.stop === "deadline") latestCut = true;
out.stop = stop;
} catch (err) {
const hung = err instanceof PageDeadlineError || pastDeadline;
@@ -582,7 +654,7 @@ export async function readXTrendingPage(o: {
});
}
}
- if (out.stop === "idle" && pastDeadline) out.stop = "deadline";
+ if (out.stop === "idle" && pastDeadline && !latestCut) out.stop = "deadline";
out.tweets = seen.size;
return out;
}