Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit dc22616c792a585eb03ede7168a9e022721fa28b
parent 519cd561663e329fd729ed37988b6b726ae5afc8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 18:09:03 -0500

x-trending: the parser reads the real page -- X's title and summary, the tabs, the cursors of later answers

The first real read of a trending page named its topic "Trending <number>": slice 1 never parsed the
page's own answer (the source's title and summary were reserved for it).

- The page's answer is found by its shape (data.<key>.result.page): article title and text, when X
  last updated them, and the tabs, each a label and the timeline it lists (trendPageOf).
- A topic nobody named is born with the page's title; a topic still carrying the fallback name for
  that page takes the title on a read and on a reparse; a topic made with a name asked for, or
  renamed since by the operator or an agent, is never renamed by a read. A title another topic
  answers to is not taken. The source keeps X's title, summary, last update and tabs.
- Which tab's timeline a read saw: the timeline id in the request's variables, matched to the
  page's tabs; kept in read.json (label and count), on the source's read and on each sighting; a
  reparse fills it in. The listing, the editor's panel, the MCP tools, umtool's page and
  `umtool library topics` say X's title, summary and the tab.
- The page's end: the bottom cursor is read from a cursor entry (a timeline's first answer) and from
  TimelineReplaceEntry (every later one); the continuation is the last answer's own timeline's; two
  timelines in one capture show no end; "gone from the page" does not count a sighting known to be
  another tab's.
- common/social/__fixtures__/xTrendingRealShape.ts: the real shape with invented data. The end of a
  timeline was not in the capture and is not guessed.
- e2e: x-trending.spec.ts reads read.json until it is the read's final record (it is written when
  the read starts and again when it ends).

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mcommon/controller/readXTrending.test.ts | 147+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/controller/readXTrending.ts | 44++++++++++++++++++++++++++++++++++++++++----
Mcommon/lib/xTrending/store.test.ts | 138+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/xTrending/store.ts | 146+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mcommon/social/__fixtures__/xTrendingCapture.ts | 43+++++++++++++++++++++++++++++++++++++++----
Acommon/social/__fixtures__/xTrendingRealShape.ts | 276+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xTrendingParse.test.ts | 131+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xTrendingParse.ts | 175+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Meditor/app/api/ops/trending/route.ts | 5+++--
Meditor/app/channels/[slug]/components/XTrendingPanel.tsx | 28+++++++++++++++++++++++-----
Meditor/e2e/x-trending.spec.ts | 29+++++++++++++++++++++++------
Mmcp/src/xTrending.test.ts | 24+++++++++++++++++++-----
Mmcp/src/xTrending.ts | 29+++++++++++++++++++++++------
Mumtool/components/tools/library/LibraryView.tsx | 30+++++++++++++++++++++++++++++-
Mumtool/e2e/fixtures/editor-stub-trending.mjs | 2+-
Mumtool/e2e/fixtures/library-fixture.mjs | 7++++++-
Mumtool/e2e/library.spec.ts | 7+++++++
Mumtool/lib/library/cli.mjs | 13++++++++++++-
Mumtool/lib/library/cli.test.mjs | 24+++++++++++++++++++++++-
19 files changed, 1228 insertions(+), 70 deletions(-)

diff --git a/common/controller/readXTrending.test.ts b/common/controller/readXTrending.test.ts @@ -12,7 +12,10 @@ import type { Paths } from "../lib/paths"; import { listXTrending, readXTrendingPosts, readXTrendingReadRecord } from "../lib/xTrending/store"; import { fakeTrendingPage, type FakeTrendingPage } from "../social/fakeXProfileBrowser"; import { + FIXTURE_LAST_UPDATED_MS, + FIXTURE_SUMMARY, FIXTURE_TIMELINE_OP, + FIXTURE_TITLE, FIXTURE_TREND_ID, FIXTURE_TREND_URL, fixtureContinuation, @@ -125,7 +128,7 @@ test("a read writes the page's posts, records the read against a topic, and says 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).`, + `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" }]); @@ -185,7 +188,17 @@ test("a re-read adds the new posts, keeps the old ones, and appends the read wit const listing = await listXTrending(root(paths)); assert.equal(listing.total, 4); assert.deepEqual(listing.topics[0].sources, [ - { trendId: FIXTURE_TREND_ID, url: FIXTURE_TREND_URL, reads: 2, lastReadAt: "2026-11-17T12:00:00.000Z" }, + // 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"], + 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]); @@ -437,7 +450,7 @@ test("a reparse updates the topic's record of the read: what the capture holds, 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 }]); + 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 () => { @@ -595,3 +608,131 @@ test("S2: a read that went idle without the capture showing the page's end marks 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.REAL_TREND_URL }); + assert.equal(result.outcome, "read"); + assert.deepEqual(result.posts, { onPage: 6, added: 6 }); + assert.deepEqual(result.topic, { id: `t-${real.REAL_TREND_ID}`, title: real.REAL_TITLE, created: true }); + assert.deepEqual(result.tabs, [{ tab: "Top", posts: 6 }]); + assert.equal( + result.sentence, + `Read ${real.REAL_TREND_URL}: 6 posts on the page, 6 new, in topic "${real.REAL_TITLE}" (t-${real.REAL_TREND_ID}), shown by the page's "Top" tab.`, + ); + const record = await readXTrendingReadRecord(root(paths), READ_1); + assert.deepEqual(record?.tabs, [{ tab: "Top", posts: 6 }]); + // 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.REAL_TOP_TIMELINE, real.REAL_LATEST_TIMELINE, real.REAL_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.REAL_TREND_ID, + url: real.REAL_TREND_URL, + title: real.REAL_TITLE, + summary: real.REAL_SUMMARY, + lastUpdatedAt: new Date(real.REAL_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.REAL_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.REAL_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.REAL_TREND_ID}`, title: real.REAL_TITLE, created: false, renamed: { was: fallback } }); + assert.equal( + done.sentence, + `Parsed ${READ_1} again (${real.REAL_TREND_URL}): 6 posts in the capture, 0 new, in topic "${real.REAL_TITLE}" (t-${real.REAL_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.REAL_TITLE); + assert.equal(topic.sources[0].summary, real.REAL_SUMMARY); + assert.equal(topic.sources[0].reads[0].tab, "Top"); + const members = JSON.parse(readFileSync(membersFile(paths), "utf8")).posts as Record<string, { seen: Array<{ tab?: string }> }>; + assert.ok(Object.values(members).every((m) => m.seen.length === 1 && m.seen[0].tab === "Top")); + const record = await readXTrendingReadRecord(root(paths), READ_1); + assert.deepEqual(record?.tabs, [{ tab: "Top", posts: 6 }]); + assert.deepEqual(record?.topic, { id: `t-${real.REAL_TREND_ID}`, title: real.REAL_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.REAL_TREND_URL }); + asSlice1Left(named); + assert.equal((await renameXTrendingTopic(root(named), { topic: `t-${real.REAL_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.REAL_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.REAL_SECOND, { n: 2 })], scrolls: [] }, { url: real.REAL_TREND_URL }); + return paths; + }; + const second = (paths: Paths, scrolls: FakeTrendingPage["scrolls"]) => + run(paths, { load: base, scrolls }, { url: real.REAL_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.REAL_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.REAL_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.REAL_SECOND[0]], { n: 2 })], [{ url: last.url, status: 500, text: "upstream error" }], []]); + assert.equal(failed.result.stop, "idle"); + assert.equal(failed.result.gone, undefined); +}); diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts @@ -284,7 +284,10 @@ export type ReadXTrendingResult = { // Operation names and sizes — never a body. operations: XTrendingReadOperation[]; posts: { onPage: number; added: number }; - topic?: { id: string; title: string; created?: boolean }; + topic?: { id: string; title: string; created?: boolean; renamed?: { was: string } }; + // Which tab's timeline the read saw: the page's label for it and the posts + // it showed (a read sees one tab, the one the page opens on). + tabs?: Array<{ tab?: string; posts: number }>; // A watch's tick that was NOT read, because the watch's jar rule refused it // at the job's start: no browser opened, nothing asked of X. It is neither // a read nor a failed read (the watch counts no strike for it). @@ -318,13 +321,28 @@ type Ingested = { responses: number; onPage: number; added: number; - topic?: { id: string; title: string; created: boolean }; + topic?: { id: string; title: string; created: boolean; renamed?: { was: string } }; // The posts this pass added to the library, and — after a read that reached // the page's end — the posts the page showed before and not now. newIds?: string[]; gone?: string[]; + // Which tab's timeline the capture lists (store.ts XTrendingReadRecord.tabs). + tabs?: Array<{ tab?: string; posts: number }>; }; +// `, shown by the page's "Top" tab` — what a read saw, in a sentence; "" when the +// capture does not say. +function tabText(tabs: Ingested["tabs"]): string { + const named = (tabs ?? []).filter((t) => t.tab); + if (named.length === 0) return ""; + return `, shown by the page's ${named.map((t) => `"${t.tab}"`).join(" and ")} tab${named.length === 1 ? "" : "s"}`; +} + +// A topic that took the page's title in this pass, said once. +function renamedText(topic: Ingested["topic"]): string { + return topic?.renamed ? ` The topic was "${topic.renamed.was}" until now: it took the page's title.` : ""; +} + // The saved capture → the library: its posts written, the read recorded. // `write: false` (a probe) parses and counts and writes nothing. async function ingestCapture(o: { @@ -342,7 +360,15 @@ async function ingestCapture(o: { 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 base = { operations: parsed.operations, responses: parsed.responses, onPage: parsed.posts.length }; + const tabs = parsed.timelines.map((t) => ({ ...(t.tab ? { tab: t.tab } : {}), posts: t.posts })); + const base = { + operations: parsed.operations, + responses: parsed.responses, + onPage: parsed.posts.length, + ...(tabs.length ? { tabs } : {}), + }; + // The ONE tab this capture lists, when it lists one and the page names it. + const tab = parsed.timelines.length === 1 ? parsed.timelines[0].tab : undefined; if (!o.write || parsed.posts.length === 0) return { ...base, added: 0 }; const had = await readXTrendingPostIds(o.channelRoot); const newIds = parsed.posts.map((p) => p.id).filter((id) => !had.has(id)); @@ -364,6 +390,9 @@ async function ingestCapture(o: { postIds: parsed.posts.map((p) => p.id), added: written.written, media: parsed.media, + ...(parsed.page ? { page: parsed.page } : {}), + ...(tab ? { tab } : {}), + tabs: parsed.tabs, }); return { ...base, added: written.written, topic: recorded.topic, newIds, gone: recorded.gone }; } @@ -597,7 +626,9 @@ export async function runXTrendingRead(o: { sentence = `Read ${plan.ref.url}: ${plural(ingested.onPage, "post")} on the page, ${ingested.added} new, ` + `in topic "${ingested.topic?.title}" (${ingested.topic?.id})` + + tabText(ingested.tabs) + (page.stop === "cancelled" ? "; the read was stopped early." : ".") + + renamedText(ingested.topic) + (ingested.gone?.length ? ` ${plural(ingested.gone.length, "post")} this page showed before ${ingested.gone.length === 1 ? "is" : "are"} gone from the page at ${hhmm(Date.parse(startedAt))} UTC.` : ""); @@ -630,6 +661,7 @@ export async function runXTrendingRead(o: { operations: ingested.operations, posts: { onPage: ingested.onPage, added: ingested.added }, ...(ingested.topic ? { topic: { id: ingested.topic.id, title: ingested.topic.title } } : {}), + ...(ingested.tabs ? { tabs: ingested.tabs } : {}), shot: page.shot, ...(page.stoppedBy ? { stoppedBy: page.stoppedBy } : {}), sentence, @@ -647,6 +679,7 @@ export async function runXTrendingRead(o: { operations: ingested.operations, posts: { onPage: ingested.onPage, added: ingested.added }, ...(ingested.topic ? { topic: ingested.topic } : {}), + ...(ingested.tabs ? { tabs: ingested.tabs } : {}), ...(ingested.newIds?.length ? { newIds: ingested.newIds } : {}), ...(ingested.gone?.length ? { gone: ingested.gone } : {}), sentence, @@ -717,7 +750,8 @@ export async function reparseXTrendingRead(o: { outcome = "read"; sentence = `Parsed ${record.id} again (${record.url}): ${plural(ingested.onPage, "post")} in the capture, ${ingested.added} new, ` + - `in topic "${ingested.topic?.title}" (${ingested.topic?.id}). X was asked nothing.`; + `in topic "${ingested.topic?.title}" (${ingested.topic?.id})${tabText(ingested.tabs)}. X was asked nothing.` + + renamedText(ingested.topic); } const ok = outcome !== "login-wall"; if (ok) { @@ -727,6 +761,7 @@ export async function reparseXTrendingRead(o: { operations: ingested.operations, posts: { onPage: ingested.onPage, added: record.posts.added + ingested.added }, ...(ingested.topic ? { topic: { id: ingested.topic.id, title: ingested.topic.title } } : {}), + ...(ingested.tabs ? { tabs: ingested.tabs } : {}), reparsedAt: new Date((o.now ?? Date.now)()).toISOString(), }); } @@ -743,6 +778,7 @@ export async function reparseXTrendingRead(o: { operations: ingested.operations, posts: { onPage: ingested.onPage, added: ingested.added }, ...(ingested.topic ? { topic: ingested.topic } : {}), + ...(ingested.tabs ? { tabs: ingested.tabs } : {}), sentence, ...(ok ? {} : { error: sentence }), }; diff --git a/common/lib/xTrending/store.test.ts b/common/lib/xTrending/store.test.ts @@ -513,3 +513,141 @@ test("a library in one line: its topics, its posts and how many are undecided", assert.deepEqual(await summarizeXTrending(await judgeLibrary("judge-summary")), { topics: 2, posts: 5, unjudged: 1 }); assert.deepEqual(await summarizeXTrending(root("judge-summary-empty")), { topics: 0, posts: 0, unjudged: 0 }); }); + +// ── lane x-followups: the page's own words, the topic's name, the tab ────── + +const PAGE = { + title: "Kettle festival opens", + summary: "The annual kettle festival opened this morning.", + lastUpdatedAt: "2026-11-16T11:30:00.000Z", + tabs: [ + { label: "Top", timelineId: "tl-top" }, + { label: "Latest", timelineId: "tl-latest" }, + ], +}; + +test("a topic nobody named is born with the page's title; the source keeps X's title, summary, last update and tabs; the listing says them", async () => { + const dir = root("page-born"); + const made = await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1, page: PAGE, tab: "Top", tabs: { "101": "Top" } }); + // The id stays the page's: a name can change, an id cannot. + assert.deepEqual(made.topic, { id: `t-${REF.trendId}`, title: "Kettle festival opens", created: true }); + const [topic] = await readXTrendingTopics(dir); + assert.deepEqual(topic.sources, [ + { trendId: REF.trendId, url: REF.url, ...PAGE, reads: [{ id: READ_A, at: "2026-11-17T10:00:00.000Z", posts: 1, added: 1, tab: "Top" }] }, + ]); + assert.deepEqual((await readXTrendingMembership(dir))["101"].seen, [{ read: READ_A, trendId: REF.trendId, at: "2026-11-17T10:00:00.000Z", rank: 1, tab: "Top" }]); + const listing = await listXTrending(dir); + assert.deepEqual(listing.topics[0].sources, [ + { trendId: REF.trendId, url: REF.url, title: PAGE.title, summary: PAGE.summary, lastUpdatedAt: PAGE.lastUpdatedAt, tabs: ["Top", "Latest"], lastReadTab: "Top", reads: 1, lastReadAt: "2026-11-17T10:00:00.000Z" }, + ]); + // No page in the capture: the fallback name, as before, and nothing invented on the source. + const bare = root("page-none"); + assert.equal((await recordXTrendingRead(bare, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1 })).topic.title, `Trending ${REF.trendId}`); + assert.deepEqual((await readXTrendingTopics(bare))[0].sources[0], { trendId: REF.trendId, url: REF.url, reads: [{ id: READ_A, at: "2026-11-17T10:00:00.000Z", posts: 1, added: 1 }] }); + // A title of several lines, or longer than a topic's name may be, is one line and cut; the source keeps X's whole title. + const long = root("page-long"); + const title = `Kettle\n festival ${"x".repeat(200)}`; + const cut = await recordXTrendingRead(long, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1, page: { title } }); + assert.equal(cut.topic.title.length, 120); + assert.match(cut.topic.title, /^Kettle festival x+…$/); + assert.equal(topicTitleProblem(cut.topic.title), null); + assert.equal((await readXTrendingTopics(long))[0].sources[0].title, `Kettle festival ${"x".repeat(200)}`); +}); + +test("a topic still carrying the fallback name takes the page's title on a later pass; a topic somebody named never does", async () => { + const { renameXTrendingTopic } = await import("./organise"); + const IDLE = () => false; + const first = { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1 }; + const later = { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF, postIds: ["101"], added: 0, page: PAGE, tab: "Top" }; + const fallback = `Trending ${REF.trendId}`; + + // Made before titles were read: the next read names it — and the SAME read parsed again (a reparse) does too. + const dir = root("name-fallback"); + await recordXTrendingRead(dir, first); + const read = await recordXTrendingRead(dir, later); + assert.deepEqual(read.topic, { id: `t-${REF.trendId}`, title: PAGE.title, created: false, renamed: { was: fallback } }); + // Once named so, a later pass renames nothing (and says nothing). + assert.equal((await recordXTrendingRead(dir, { ...later, readId: READ_C, at: "2026-11-17T12:00:00.000Z", page: { ...PAGE, title: "Another headline" } })).topic.renamed, undefined); + assert.equal((await readXTrendingTopics(dir))[0].title, PAGE.title); + // …while the SOURCE follows X's words. + assert.equal((await readXTrendingTopics(dir))[0].sources[0].title, "Another headline"); + const reparsed = root("name-reparse"); + await recordXTrendingRead(reparsed, first); + const again = await recordXTrendingRead(reparsed, { ...first, added: 0, page: PAGE, tab: "Top", tabs: { "101": "Top" } }); + assert.deepEqual(again.topic.renamed, { was: fallback }); + assert.equal((await readXTrendingTopics(reparsed))[0].sources[0].reads[0].tab, "Top"); + // The reparse fills the tab its sighting could not say before, and adds no second sighting. + assert.deepEqual((await readXTrendingMembership(reparsed))["101"].seen, [{ read: READ_A, trendId: REF.trendId, at: first.at, rank: 1, tab: "Top" }]); + + // A name asked for at the read stays. + const asked = root("name-asked"); + await recordXTrendingRead(asked, { ...first, topic: "Kettles" }); + assert.equal((await recordXTrendingRead(asked, later)).topic.title, "Kettles"); + + // Renamed by an agent or by the operator: never renamed by a read — even renamed back to the fallback's own words. + for (const by of ["agent", "operator"] as const) { + const named = root(`name-renamed-${by}`); + await recordXTrendingRead(named, first); + assert.equal((await renameXTrendingTopic(named, { topic: `t-${REF.trendId}`, title: "My kettles", by, readInFlight: IDLE })).ok, true); + assert.equal((await recordXTrendingRead(named, later)).topic.title, "My kettles"); + assert.equal((await renameXTrendingTopic(named, { topic: `t-${REF.trendId}`, title: fallback, by, readInFlight: IDLE })).ok, true); + const kept = await recordXTrendingRead(named, { ...later, readId: READ_C, at: "2026-11-17T12:00:00.000Z" }); + assert.equal(kept.topic.title, fallback); + assert.equal(kept.topic.renamed, undefined); + // X's title is on the source all the same. + assert.equal((await readXTrendingTopics(named))[0].sources[0].title, PAGE.title); + } + + // The fallback of ANOTHER page is somebody's choice of words here: a second page read into the topic does not rename it. + const other = root("name-other-page"); + await recordXTrendingRead(other, first); + assert.equal((await recordXTrendingRead(other, { ...later, ref: REF_2, topic: `t-${REF.trendId}` })).topic.title, fallback); + + // A title another topic already answers to is not taken: a topic's name is its own. + const taken = root("name-taken"); + await recordXTrendingRead(taken, { ...first, ref: REF_2, topic: "kettle FESTIVAL opens" }); + await recordXTrendingRead(taken, { ...first, readId: READ_B }); + const refused = await recordXTrendingRead(taken, { ...later, readId: READ_C, at: "2026-11-17T12:00:00.000Z" }); + assert.equal(refused.topic.title, fallback); + assert.equal(refused.topic.renamed, undefined); + assert.equal((await readXTrendingTopics(taken)).find((t) => t.id === `t-${REF.trendId}`)?.sources[0].title, PAGE.title); + // …and a NEW topic is not born with a name another answers to either. + const born = root("name-born-taken"); + await recordXTrendingRead(born, { ...first, ref: REF_2, topic: PAGE.title }); + assert.equal((await recordXTrendingRead(born, { ...later })).topic.title, fallback); +}); + +test("an older read parsed again does not put its words over a newer read's", async () => { + const dir = root("page-order"); + await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: ["101"], added: 1, page: { title: "Morning headline", summary: "Morning." } }); + await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T12:00:00.000Z", ref: REF, topic: "T", postIds: ["101"], added: 0, page: { title: "Noon headline", summary: "Noon." } }); + await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: ["101"], added: 0, page: { title: "Morning headline", summary: "Morning." }, tab: "Top" }); + const source = (await readXTrendingTopics(dir))[0].sources[0]; + assert.equal(source.title, "Noon headline"); + assert.equal(source.summary, "Noon."); + // The read's own tab is the read's, whenever it is learned. + assert.equal(source.reads[0].tab, "Top"); +}); + +test("gone from the page is said per tab: a post only the other tab showed is not missing from this one", async () => { + const dir = root("gone-tabs"); + const at = (h: number) => `2026-11-17T${String(h).padStart(2, "0")}:00:00.000Z`; + // 701 and 702 on Top; 703 on Latest only; 704 by a read from before tabs were read. + await recordXTrendingRead(dir, { readId: READ_A, at: at(9), ref: REF, topic: "T", postIds: ["704"], added: 1 }); + await recordXTrendingRead(dir, { readId: READ_B, at: at(10), ref: REF, topic: "T", postIds: ["701", "702"], added: 2, tab: "Top" }); + await recordXTrendingRead(dir, { readId: READ_C, at: at(11), ref: REF, topic: "T", postIds: ["703"], added: 1, tab: "Latest" }); + // A complete read of Top that shows 701 only: 702 is gone (Top showed it), 704 too (untagged: the opening tab's), 703 is not. + const top = await recordXTrendingRead(dir, { readId: "tr-01JD0000000000000000000000", at: at(12), ref: REF, topic: "T", postIds: ["701"], added: 0, tab: "Top", complete: true }); + assert.deepEqual([...top.gone].sort(), ["702", "704"]); + const members = await readXTrendingMembership(dir); + assert.equal(members["703"].gone, undefined); + // The listing says which tab showed a post. + await writeXTrendingPosts(dir, ["701", "702", "703", "704"].map((id) => post(id, "a", `post ${id}`))); + const listing = await listXTrending(dir); + assert.deepEqual(listing.posts.find((p) => p.id === "703")?.reads, [{ read: READ_C, trendId: REF.trendId, at: at(11), tab: "Latest" }]); + assert.deepEqual(listing.posts.find((p) => p.id === "704")?.reads, [{ read: READ_A, trendId: REF.trendId, at: at(9) }]); + assert.equal(listing.topics[0].sources[0].lastReadTab, "Top"); + // A complete read that cannot say its tab (no page answer in its capture) is the opening tab's: 703 is still excused only by a KNOWN difference. + const unknown = await recordXTrendingRead(dir, { readId: "tr-01JE0000000000000000000000", at: at(13), ref: REF, topic: "T", postIds: ["701"], added: 0, complete: true }); + assert.deepEqual(unknown.gone, ["703"]); +}); diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts @@ -312,18 +312,38 @@ export type XTrendingSourceRead = { at: string; posts: number; added: number; + // The tab of the page whose timeline the read saw (its label, as X shows + // it), when the capture says which. A read sees ONE tab: the one the page + // opens on. Absent for a read saved before tabs were read, until it is + // parsed again, and for a capture whose page answer or timeline id is missing. + tab?: string; }; +// One tab of a trending page: its label and the timeline it lists. +export type XTrendingTab = { label: string; timelineId: string }; + // One trending page read into a topic. `title` and `summary` are X's own -// words for the page, filled once the parser knows where the page keeps them. +// words for the page, `lastUpdatedAt` when X last rewrote them and `tabs` the +// page's tabs (lane x-followups): all as the LATEST read or reparse that +// carried the page's own answer found them, and kept when a later capture +// lacks it. export type XTrendingSource = { trendId: string; url: string; title?: string; summary?: string; + lastUpdatedAt?: string; + tabs?: XTrendingTab[]; reads: XTrendingSourceRead[]; }; +// THE NAME A TOPIC IS BORN WITH when nobody named it and its page gave no +// title: "Trending <the page's number>". A topic still carrying it takes the +// page's title at the next read or reparse that finds one (recordXTrendingRead). +export function xTrendingFallbackTitle(trendId: string): string { + return `Trending ${trendId}`; +} + // Who organised (renamed, merged, moved) and when: the caller's word, as a // judgement's `by` is (lib/xTrending/organise.ts). export type XTrendingOrganiseBy = "agent" | "operator"; @@ -343,7 +363,9 @@ export type XTrendingTopic = { organised?: XTrendingOrganised; }; -export type XTrendingSeen = { read: string; trendId: string; at: string; rank: number }; +// One sighting: the read, the page, when, its rank on the page, and the tab +// of the page that showed it (as XTrendingSourceRead.tab). +export type XTrendingSeen = { read: string; trendId: string; at: string; rank: number; tab?: string }; // GONE FROM THE PAGE (lane x-trending-2): a post a page showed before, absent // from a later read of that page that reached the page's end. It says what @@ -383,13 +405,19 @@ function parseTopics(raw: unknown): XTrendingTopic[] { const reads: XTrendingSourceRead[] = []; for (const r of Array.isArray(s.reads) ? s.reads : []) { if (!r || typeof r !== "object" || !isXTrendingReadId(r.id) || !str(r.at)) continue; - reads.push({ id: r.id, at: r.at, posts: Number(r.posts) || 0, added: Number(r.added) || 0 }); + reads.push({ id: r.id, at: r.at, posts: Number(r.posts) || 0, added: Number(r.added) || 0, ...(str(r.tab) ? { tab: r.tab } : {}) }); + } + const tabs: XTrendingTab[] = []; + for (const tab of Array.isArray(s.tabs) ? s.tabs : []) { + if (tab && typeof tab === "object" && str(tab.label) && str(tab.timelineId)) tabs.push({ label: tab.label, timelineId: tab.timelineId }); } sources.push({ trendId: s.trendId, url: s.url, ...(str(s.title) ? { title: s.title } : {}), ...(str(s.summary) ? { summary: s.summary } : {}), + ...(str(s.lastUpdatedAt) ? { lastUpdatedAt: s.lastUpdatedAt } : {}), + ...(tabs.length ? { tabs } : {}), reads, }); } @@ -422,7 +450,7 @@ function parseMembership(raw: unknown): Record<string, XTrendingMember> { const seen: XTrendingSeen[] = []; for (const s of Array.isArray(m.seen) ? m.seen : []) { if (!s || typeof s !== "object" || !isXTrendingReadId(s.read) || !str(s.trendId) || !str(s.at)) continue; - seen.push({ read: s.read, trendId: s.trendId, at: s.at, rank: Number(s.rank) || 0 }); + seen.push({ read: s.read, trendId: s.trendId, at: s.at, rank: Number(s.rank) || 0, ...(str(s.tab) ? { tab: s.tab } : {}) }); } const media = m.media && typeof m.media === "object" && Number(m.media.count) > 0 @@ -557,10 +585,20 @@ export type RecordReadInput = { // The read reached the page's end (it stopped because the page had no more // to show): only then is a post it did not show marked gone from the page. complete?: boolean; + // What the page said of itself in this capture (xTrendingParse.ts + // trendPageOf): written onto the topic's source, and the name of a topic + // nobody named. + page?: { title?: string; summary?: string; lastUpdatedAt?: string; tabs?: ReadonlyArray<XTrendingTab> }; + // The tab whose timeline this read saw (its label), when the capture shows + // ONE; and, per post, the tab that showed it. + tab?: string; + tabs?: Readonly<Record<string, string>>; }; export type RecordReadResult = { - topic: { id: string; title: string; created: boolean }; + // `renamed`: the topic carried the name it was born with ("Trending + // <number>") and took the page's title in this pass; `was` is that name. + topic: { id: string; title: string; created: boolean; renamed?: { was: string } }; // Posts this read placed in the topic (new to the library's membership). placed: number; // Posts the library already had, left in the topic they were in. @@ -571,9 +609,26 @@ export type RecordReadResult = { back: string[]; }; +// A page's title as a topic's name: one line, cut to a topic name's length. +function pageTitleAsName(title: string | undefined): string | undefined { + const text = title?.replace(/\s+/g, " ").trim(); + if (!text) return undefined; + return text.length > X_TRENDING_TOPIC_TITLE_MAX ? text.slice(0, X_TRENDING_TOPIC_TITLE_MAX - 1).trimEnd() + "…" : text; +} + // One read, recorded: its topic found or made, the page added to the topic's // sources, the read appended, and every post it showed given a place (a post // already placed keeps its topic and gains the read). +// +// THE TOPIC'S NAME (lane x-followups). A topic made by a read that named none +// is called by the page's title when the capture carries one, else "Trending +// <number>". A topic STILL CARRYING THAT FALLBACK for this page takes the +// page's title in any later pass that finds one — a read or a reparse. A +// topic somebody named is never renamed by a read: one made with a name +// asked for, and one renamed since (`organised.what === "rename"`, by the +// operator or an agent — even back to the fallback's words). A title another +// topic already answers to is not taken (a topic's name is its own): the +// fallback stays, and the source carries X's title all the same. export async function recordXTrendingRead(channelRoot: string, input: RecordReadInput): Promise<RecordReadResult> { if (!isXTrendingReadId(input.readId)) throw new Error(`"${input.readId}" is not a trending read id`); const topic = await withJsonFileLock(topicsPath(channelRoot), async () => { @@ -586,8 +641,14 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead found = topics.find((t) => t.sources.some((s) => s.trendId === input.ref.trendId)); } let created = false; + let renamed: { was: string } | undefined; + const fallback = xTrendingFallbackTitle(input.ref.trendId); + const pageName = pageTitleAsName(input.page?.title); + // The page's title as a name, unless another topic answers to it. + const freeName = (self?: XTrendingTopic) => + pageName && !resolveXTrendingTopic(topics.filter((t) => t !== self), pageName) ? pageName : undefined; if (!found) { - const title = asked || `Trending ${input.ref.trendId}`; + const title = asked || freeName() || fallback; const base = (asked && topicIdFromTitle(asked)) || `t-${input.ref.trendId}`; let id = base; // Never the id of a topic merged away: that id means the topic it went into. @@ -596,22 +657,42 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead topics.push(found); created = true; } + else if (found.title === fallback && found.organised?.what !== "rename") { + const name = freeName(found); + if (name && name !== found.title) { + renamed = { was: found.title }; + found.title = name; + } + } let source = found.sources.find((s) => s.trendId === input.ref.trendId); if (!source) { source = { trendId: input.ref.trendId, url: input.ref.url, reads: [] }; found.sources.push(source); } + // X's own words for the page and its tabs, as THIS capture has them — only + // from a pass no older than the source's latest read (a reparse of an old + // read does not put old words over newer ones). + const newest = source.reads.reduce((a, r) => (r.at > a ? r.at : a), ""); + if (input.page && input.at >= newest) { + const title = input.page.title?.replace(/\s+/g, " ").trim(); + const summary = input.page.summary?.replace(/\s+/g, " ").trim(); + if (title) source.title = title; + if (summary) source.summary = summary; + if (input.page.lastUpdatedAt) source.lastUpdatedAt = input.page.lastUpdatedAt; + if (input.page.tabs?.length) source.tabs = input.page.tabs.map((t) => ({ label: t.label, timelineId: t.timelineId })); + } const read = source.reads.find((r) => r.id === input.readId); if (!read) { - source.reads.push({ id: input.readId, at: input.at, posts: input.postIds.length, added: input.added }); + source.reads.push({ id: input.readId, at: input.at, posts: input.postIds.length, added: input.added, ...(input.tab ? { tab: input.tab } : {}) }); } else { // The same read recorded again (a reparse): what the capture is now // read to hold, and whatever this pass added on top of the last. read.posts = input.postIds.length; read.added += input.added; + if (input.tab) read.tab = input.tab; } await writeJsonAtomic(topicsPath(channelRoot), { version: 1, topics } satisfies TopicsFile, { mkdir: true }); - return { id: found.id, title: found.title, created }; + return { id: found.id, title: found.title, created, ...(renamed ? { renamed } : {}) }; }); const counts = await withJsonFileLock(membershipPath(channelRoot), async () => { const posts = await readXTrendingMembership(channelRoot); @@ -620,11 +701,15 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead const gone: string[] = []; const back: string[] = []; input.postIds.forEach((id, i) => { - const seen: XTrendingSeen = { read: input.readId, trendId: input.ref.trendId, at: input.at, rank: i + 1 }; + const tab = input.tabs?.[id] ?? input.tab; + const seen: XTrendingSeen = { read: input.readId, trendId: input.ref.trendId, at: input.at, rank: i + 1, ...(tab ? { tab } : {}) }; const have = posts[id]; if (have) { kept++; - if (!have.seen.some((s) => s.read === input.readId)) have.seen.push(seen); + const sighting = have.seen.find((s) => s.read === input.readId); + if (!sighting) have.seen.push(seen); + // The same read again (a reparse): the tab it could not say before. + else if (tab && !sighting.tab) sighting.tab = tab; if (!have.media && input.media?.[id]) have.media = input.media[id]; if (!have.thread && input.threads?.[id]) have.thread = input.threads[id]; // Shown again, by a read later than the one that missed it. @@ -647,8 +732,23 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead const shown = new Set(input.postIds); for (const [id, m] of Object.entries(posts)) { if (shown.has(id) || m.gone) continue; - // Only a post THIS page showed, in a read before this one. - if (!m.seen.some((s) => s.trendId === input.ref.trendId && s.read !== input.readId && s.at < input.at)) continue; + // Only a post THIS page showed, in a read before this one — and NOT ON + // ANOTHER TAB than this read saw: a post only the other tab showed is + // not missing from this one. Only a KNOWN difference excuses it: a + // sighting or a read that names no tab (a read from before tabs were + // read, a capture with no page answer) was of the tab the page opens + // on, the only one a read sees. + if ( + !m.seen.some( + (s) => + s.trendId === input.ref.trendId && + s.read !== input.readId && + s.at < input.at && + (s.tab === undefined || input.tab === undefined || s.tab === input.tab), + ) + ) { + continue; + } m.gone = { at: input.at, read: input.readId, trendId: input.ref.trendId }; gone.push(id); } @@ -714,6 +814,11 @@ export type XTrendingReadRecord = { // Posts the parser finds in the capture, and how many the library lacked. posts: { onPage: number; added: number }; topic?: { id: string; title: string }; + // WHICH TAB'S TIMELINE THE READ SAW (lane x-followups): per timeline the + // capture lists, the page's label for it (absent when the page names no + // such tab, or the capture has no page answer) and the posts it showed + // first. Labels and counts only. A read sees one: the tab the page opens on. + tabs?: Array<{ tab?: string; posts: number }>; shot: boolean; sentence: string; // When the capture was last parsed again (`reparse`). @@ -811,6 +916,11 @@ export type XTrendingTopicRow = { url: string; title?: string; summary?: string; + // When X last rewrote its title and summary, the page's tabs by label, + // and the tab the LAST read saw (the only one a read sees). + lastUpdatedAt?: string; + tabs?: string[]; + lastReadTab?: string; reads: number; lastReadAt: string | null; }>; @@ -829,7 +939,7 @@ export type XTrendingPostRow = { text: string; media: XTrendingMedia & { thumbnail?: string }; topic: string; - reads: Array<{ read: string; trendId: string; at: string }>; + reads: Array<{ read: string; trendId: string; at: string; tab?: string }>; // Gone from the page: a page that showed it before did not show it at // `at` (a read that reached the page's end). Never "deleted". gone?: XTrendingGone; @@ -930,6 +1040,11 @@ export async function listXTrendingReadIds(channelRoot: string): Promise<string[ } } +// The tab the source's latest read saw, when that read says. +function lastReadTabOf(s: XTrendingSource): string | undefined { + return s.reads.reduce<XTrendingSourceRead | undefined>((a, r) => (a === undefined || r.at > a.at ? r : a), undefined)?.tab; +} + const lastSeen = (m: XTrendingMember) => m.seen.reduce((a, s) => (s.at > a ? s.at : a), ""); // The library's topics and posts. `topic` narrows the posts to one topic (its @@ -1011,7 +1126,7 @@ export async function listXTrending( text: post.text, media, topic: m.topic, - reads: m.seen.map((s) => ({ read: s.read, trendId: s.trendId, at: s.at })), + reads: m.seen.map((s) => ({ read: s.read, trendId: s.trendId, at: s.at, ...(s.tab ? { tab: s.tab } : {}) })), ...(m.gone ? { gone: m.gone } : {}), thread, ...(effective ? { judgement: effective } : {}), @@ -1062,6 +1177,9 @@ export async function listXTrending( url: s.url, ...(s.title ? { title: s.title } : {}), ...(s.summary ? { summary: s.summary } : {}), + ...(s.lastUpdatedAt ? { lastUpdatedAt: s.lastUpdatedAt } : {}), + ...(s.tabs?.length ? { tabs: s.tabs.map((t) => t.label) } : {}), + ...(lastReadTabOf(s) ? { lastReadTab: lastReadTabOf(s)! } : {}), reads: s.reads.length, lastReadAt: s.reads.reduce<string | null>((a, r) => (a === null || r.at > a ? r.at : a), null), })), diff --git a/common/social/__fixtures__/xTrendingCapture.ts b/common/social/__fixtures__/xTrendingCapture.ts @@ -3,13 +3,44 @@ // made up; the SHAPES are X's public GraphQL tweet-result shapes as this repo // already reads them (xPlaywrightFetcher.ts): `{__typename: "Tweet", rest_id, // core.user_results.result, legacy}`, a TweetWithVisibilityResults wrapper, a -// quoted result, a promoted entry. The operation names are invented too — the -// real ones are learned from the first real read (the probe). +// quoted result, a promoted entry. The operation names are invented too. The +// page's own answer (title, summary, tabs) and the timeline id its requests +// name are in the shape the first real read showed (lane x-followups); the +// whole real shape, instruction by instruction, is xTrendingRealShape.ts. export const FIXTURE_TREND_ID = "1900000000000000001"; export const FIXTURE_TREND_URL = `https://x.com/i/trending/${FIXTURE_TREND_ID}`; export const FIXTURE_TREND_OP = "ExampleTrendPage"; export const FIXTURE_TIMELINE_OP = "ExampleTrendTimeline"; +// X's own words for the page (invented), and the page's two tabs: the +// timeline the fixture's requests name is the first. +export const FIXTURE_TITLE = "Kettle festival opens"; +export const FIXTURE_SUMMARY = "The annual kettle festival opened this morning to a long queue."; +export const FIXTURE_LAST_UPDATED_MS = Date.UTC(2026, 10, 16, 11, 30, 0); +export const FIXTURE_TOP_TIMELINE = "fixture-timeline-top"; +export const FIXTURE_LATEST_TIMELINE = "fixture-timeline-latest"; + +// The page's own answer, as the real page shapes it. +export function fixtureTrendPageBody(): Record<string, unknown> { + return { + data: { + ai_trend_by_rest_id: { + rest_id: FIXTURE_TREND_ID, + result: { + page: { + article: { article_text: { entities: [], text: FIXTURE_SUMMARY }, title: FIXTURE_TITLE }, + last_updated_at_ms: FIXTURE_LAST_UPDATED_MS, + post_timelines: [ + { label: "Top", post_timeline: { id: FIXTURE_TOP_TIMELINE } }, + { label: "Latest", post_timeline: { id: FIXTURE_LATEST_TIMELINE } }, + ], + }, + rest_id: FIXTURE_TREND_ID, + }, + }, + }, + }; +} export type FixtureTweet = { id: string; @@ -126,7 +157,11 @@ export const FIXTURE_BOTTOM_CURSOR = "fixture-cursor"; const graphqlUrl = (op: string, n: number, cursor?: string) => `https://x.com/i/api/graphql/fixtureQueryId${n}/${op}?variables=${encodeURIComponent( - JSON.stringify({ rest_id: FIXTURE_TREND_ID, ...(cursor ? { cursor } : {}) }), + JSON.stringify({ + rest_id: FIXTURE_TREND_ID, + ...(op === FIXTURE_TIMELINE_OP ? { timelineId: FIXTURE_TOP_TIMELINE } : {}), + ...(cursor ? { cursor } : {}), + }), )}`; // The page asking its timeline for MORE: the request carries the bottom cursor @@ -141,7 +176,7 @@ export type FixtureResponse = { url: string; status: number; body?: unknown; tex export function fixtureTrendingResponses(): { load: FixtureResponse[]; scrolls: FixtureResponse[][] } { return { load: [ - { url: graphqlUrl(FIXTURE_TREND_OP, 1), status: 200, body: { data: { example_trend: { rest_id: FIXTURE_TREND_ID } } } }, + { url: graphqlUrl(FIXTURE_TREND_OP, 1), status: 200, body: fixtureTrendPageBody() }, { url: graphqlUrl(FIXTURE_TIMELINE_OP, 2), status: 200, body: fixtureTimelineBody(FIXTURE_FIRST_PAGE) }, // Not GraphQL: never saved. { url: "https://x.com/i/api/1.1/example.json", status: 200, body: { ok: true } }, diff --git a/common/social/__fixtures__/xTrendingRealShape.ts b/common/social/__fixtures__/xTrendingRealShape.ts @@ -0,0 +1,276 @@ +// A TRENDING PAGE'S ANSWERS IN THE SHAPE THE REAL PAGE GIVES THEM (lane +// x-followups), with INVENTED data: every id, handle, name, word, cursor and +// timeline id here is made up. The shapes are what the first real read of a +// trending page saved (18 Nov 2026), reduced to the keys the parser reads and +// the ones that could mislead it: +// +// AiTrendByRestId the page itself: data.ai_trend_by_rest_id.result +// .page — article {title, article_text.text}, +// last_updated_at_ms, disclaimer, post_timelines +// [{label, post_timeline.id}] (two tabs) — and +// result.contexts.topics. +// GenericTimelineById a tab's posts. Its request's `variables` name the +// timeline (`timelineId`), `count`, and from the +// second request on the `cursor` it continues from. +// FIRST answer: TimelineClearCache, TimelineTerminate +// Timeline (direction Top), TimelineAddEntries with +// tweet entries, one MODULE of accounts, a cursor-top +// and a cursor-bottom entry. LATER answers: +// TimelineAddEntries with tweet entries and NO cursor +// entry, then two TimelineReplaceEntry instructions +// carrying the new top and bottom cursors. +// TrendRelevantUsers accounts, under the page's own `data` key, in a +// timeline with instructions and no post. +// useStoryTopicQuery other trends of the same story (names, counts). +// small ones DataSaverMode, ViewerBadgeCounts: no post. +// +// THE END OF A TIMELINE IS NOT HERE. The read these shapes come from stopped +// at its post cap after three scrolls; no saved capture shows what the page +// fetches when a tab has no more posts. Its shape is NOT guessed: there is no +// builder for it, and `realContinuation` with no post (or only posts already +// shown) is the parser's own rule for an end acted out in the LATER-answer +// shape, not something X was seen to send. Until a read reaches a real end +// and saves it, `pageEnd` is true only for a capture that looks like that. + +import { fixtureTweetResult, type FixtureResponse, type FixtureTweet } from "./xTrendingCapture"; + +export const REAL_TREND_ID = "1900000000000000002"; +export const REAL_TREND_URL = `https://x.com/i/trending/${REAL_TREND_ID}`; +export const REAL_PAGE_OP = "AiTrendByRestId"; +export const REAL_TIMELINE_OP = "GenericTimelineById"; +export const REAL_TITLE = "Kettle festival opens with a record queue"; +export const REAL_SUMMARY = + "The annual kettle festival opened this morning. Visitors queued from dawn, and the organisers added a second hall for the afternoon demonstrations."; +export const REAL_LAST_UPDATED_MS = Date.UTC(2026, 10, 16, 11, 30, 0); +export const REAL_TOP_TIMELINE = "VGltZWxpbmU6Zml4dHVyZS10b3A="; +export const REAL_LATEST_TIMELINE = "VGltZWxpbmU6Zml4dHVyZS1sYXRlc3Q="; + +const url = (op: string, variables: Record<string, unknown>) => + `https://x.com/i/api/graphql/fixtureQueryId/${op}?variables=${encodeURIComponent(JSON.stringify(variables))}&features=${encodeURIComponent("{}")}`; + +export type RealPage = { + trendId?: string; + title?: string; + summary?: string; + lastUpdatedAtMs?: number; + tabs?: Array<{ label: string; timelineId: string }>; +}; + +// The page's own answer. +export function realPageBody(o: RealPage = {}): Record<string, unknown> { + const trendId = o.trendId ?? REAL_TREND_ID; + const tabs = o.tabs ?? [ + { label: "Top", timelineId: REAL_TOP_TIMELINE }, + { label: "Latest", timelineId: REAL_LATEST_TIMELINE }, + ]; + return { + data: { + ai_trend_by_rest_id: { + rest_id: trendId, + result: { + contexts: { topics: ["Food and drink"] }, + page: { + article: { + article_text: { entities: [], text: o.summary ?? REAL_SUMMARY }, + title: o.title ?? REAL_TITLE, + }, + available_actions: [], + disclaimer: "This story is a summary of posts and may evolve over time.", + last_updated_at_ms: o.lastUpdatedAtMs ?? REAL_LAST_UPDATED_MS, + post_timelines: tabs.map((t) => ({ label: t.label, post_timeline: { id: t.timelineId } })), + }, + rest_id: trendId, + }, + }, + }, + }; +} + +export function realPageAnswer(o: RealPage = {}): FixtureResponse { + return { + url: url(REAL_PAGE_OP, { trendId: o.trendId ?? REAL_TREND_ID, includePromotedContent: false, withBirdwatchNotes: true, withVoice: true, withCommunity: true }), + status: 200, + body: realPageBody(o), + }; +} + +function tweetEntry(t: FixtureTweet, sort: number): Record<string, unknown> { + return { + content: { + __typename: "TimelineTimelineItem", + clientEventInfo: { component: "trends_tweets", element: "tweet" }, + entryType: "TimelineTimelineItem", + itemContent: { + __typename: "TimelineTweet", + itemType: "TimelineTweet", + tweetDisplayType: "Tweet", + tweet_results: { result: fixtureTweetResult(t) }, + }, + }, + entryId: `tweet-${t.id}`, + sortIndex: String(sort), + }; +} + +function cursorEntry(kind: "Top" | "Bottom", value: string, n: number): Record<string, unknown> { + return { + content: { __typename: "TimelineTimelineCursor", cursorType: kind, entryType: "TimelineTimelineCursor", value }, + entryId: `cursor-${kind.toLowerCase()}-${n}`, + sortIndex: String(n), + }; +} + +// The accounts module the first answer carries among its entries: users, no post. +function accountsModule(): Record<string, unknown> { + const user = (handle: string, i: number) => ({ + entryId: `trends-accounts-7-user-${i}`, + item: { + clientEventInfo: { component: "trends_accounts", element: "user" }, + itemContent: { + __typename: "TimelineUser", + itemType: "TimelineUser", + userDisplayType: "User", + user_results: { result: { __typename: "User", rest_id: `80000${i}`, core: { screen_name: handle, name: handle }, legacy: { description: "An invented account." } } }, + }, + }, + }); + return { + content: { + __typename: "TimelineTimelineModule", + clientEventInfo: { component: "trends_accounts" }, + displayType: "Vertical", + entryType: "TimelineTimelineModule", + header: { displayType: "Classic", sticky: false, text: "Relevant people" }, + items: [user("kettle_org", 1), user("teapot_news", 2), user("spout_clips", 3)], + }, + entryId: "trends-accounts-7", + sortIndex: "7", + }; +} + +const timelineBody = (instructions: unknown[]) => ({ + data: { timeline: { timeline: { instructions, metadata: { scribeConfig: { page: "trends" } } } } }, +}); + +export const realBottomCursor = (n: number) => `fixture-bottom-cursor-${n}`; +export const realTopCursor = (n: number) => `fixture-top-cursor-${n}`; + +// A tab's FIRST answer: no cursor in the request; the cursors are entries. +export function realFirstPage(tweets: FixtureTweet[], o: { timelineId?: string; bottom?: string } = {}): FixtureResponse { + return { + url: url(REAL_TIMELINE_OP, { timelineId: o.timelineId ?? REAL_TOP_TIMELINE, count: 20, withQuickPromoteEligibilityTweetFields: true }), + status: 200, + body: timelineBody([ + { type: "TimelineClearCache" }, + { direction: "Top", type: "TimelineTerminateTimeline" }, + { + type: "TimelineAddEntries", + entries: [ + ...tweets.slice(0, 2).map((t, i) => tweetEntry(t, 100 - i)), + accountsModule(), + ...tweets.slice(2).map((t, i) => tweetEntry(t, 90 - i)), + cursorEntry("Top", realTopCursor(1), 999), + cursorEntry("Bottom", o.bottom ?? realBottomCursor(1), 1), + ], + }, + ]), + }; +} + +// A LATER answer of a tab: the request carries the cursor it continues from; +// the answer lists no cursor entry and REPLACES the two it had. +export function realContinuation( + tweets: FixtureTweet[], + o: { timelineId?: string; asked?: string; bottom?: string; n?: number } = {}, +): FixtureResponse { + const n = o.n ?? 2; + return { + url: url(REAL_TIMELINE_OP, { + timelineId: o.timelineId ?? REAL_TOP_TIMELINE, + count: 20, + cursor: o.asked ?? realBottomCursor(n - 1), + withQuickPromoteEligibilityTweetFields: true, + }), + status: 200, + body: timelineBody([ + { type: "TimelineAddEntries", entries: tweets.map((t, i) => tweetEntry(t, 80 - i)) }, + { entry: cursorEntry("Top", realTopCursor(n), 999), entry_id_to_replace: "cursor-top-999", type: "TimelineReplaceEntry" }, + { entry: cursorEntry("Bottom", o.bottom ?? realBottomCursor(n), 1), entry_id_to_replace: "cursor-bottom-1", type: "TimelineReplaceEntry" }, + ]), + }; +} + +// The accounts the page names, under the page's own `data` key: a timeline +// with instructions and no post. +export function realRelevantUsers(trendId: string = REAL_TREND_ID): FixtureResponse { + return { + url: url("TrendRelevantUsers", { trendId }), + status: 200, + body: { + data: { + ai_trend_by_rest_id: { + rest_id: trendId, + result: { trend_relevant_users: { timeline: { instructions: [{ type: "TimelineAddEntries", entries: [accountsModule()] }] } } }, + }, + }, + }, + }; +} + +// Other trends of the same story. +export function realStoryTopics(): FixtureResponse { + const trend = (id: string, name: string) => ({ + trend_results: { + id: `trend-${id}`, + result: { + __typename: "Trend", + core: { category: "Food and drink", created_at_ms: REAL_LAST_UPDATED_MS, hook: "An invented hook.", name }, + id: `trend-${id}`, + post_count: "1.2K", + rest_id: id, + social_proof: [], + }, + }, + }); + return { + url: url("useStoryTopicQuery", { rest_id: "story-fixture", limit: 3 }), + status: 200, + body: { data: { story_topic: { id: "story-fixture", stories: { items: [trend("1900000000000000003", "Teapot prices"), trend("1900000000000000004", "Saucer shortage")] } } } }, + }; +} + +const small = (op: string, body: unknown): FixtureResponse => ({ url: url(op, {}), status: 200, body }); + +export const REAL_FIRST: FixtureTweet[] = [ + { id: "1900000000000003001", handle: "teapot_news", name: "Teapot News", text: "The kettle festival opens today.", media: ["photo"] }, + { + id: "1900000000000003002", + handle: "saucer_fan", + text: "Quoting the festival post.", + quoted: { id: "1900000000000002900", handle: "kettle_org", text: "Festival programme attached.", media: ["photo"] }, + }, + { id: "1900000000000003003", handle: "spout_clips", name: "Spout Clips", text: "Video from the opening.", media: ["video"], namesInCore: true }, +]; +export const REAL_SECOND: FixtureTweet[] = [ + { id: "1900000000000003004", handle: "lid_watch", text: "The queue at noon.", media: ["animated_gif"] }, + { id: "1900000000000003005", handle: "kettle_org", text: "A second hall is open." }, +]; +export const REAL_THIRD: FixtureTweet[] = [ + { id: "1900000000000003006", handle: "teapot_news", name: "Teapot News", text: "Afternoon demonstrations begin." }, +]; + +// What the page fetched, in the order the real read saved it: small answers, +// the page, its accounts, its story, the first page of the default tab, then +// one continuation per scroll (`later`: the posts each brought). +export function realCaptureResponses(o: { page?: RealPage; first?: FixtureTweet[]; later?: FixtureTweet[][] } = {}): FixtureResponse[] { + const later = o.later ?? [REAL_SECOND, REAL_THIRD]; + return [ + small("DataSaverMode", { data: { viewer: { data_saver_mode: false } } }), + realPageAnswer(o.page), + realRelevantUsers(o.page?.trendId), + realStoryTopics(), + realFirstPage(o.first ?? REAL_FIRST), + small("ViewerBadgeCounts", { data: { viewer_v2: { badge_counts: { ntab_unread_count: 0 } } } }), + ...later.map((tweets, i) => realContinuation(tweets, { n: i + 2 })), + ]; +} diff --git a/common/social/xTrendingParse.test.ts b/common/social/xTrendingParse.test.ts @@ -10,6 +10,7 @@ import { import { FIXTURE_FIRST_PAGE, FIXTURE_TIMELINE_OP, + FIXTURE_TOP_TIMELINE, FIXTURE_TREND_OP, fixtureTimelineBody, fixtureTrendingResponses, @@ -217,3 +218,133 @@ test("S2/N4: a capture shows the page's end only when the bottom-cursor continua // No post at all: no page to have an end. assert.equal(end([line("ExampleTrendPage", 200, { data: {} })]), false); }); + +// ── the real page's shape (lane x-followups) ─────────────────────────────── + +test("the real shape: the page's title, summary, last update and tabs are read from the page's own answer", async () => { + const { trendPageOf } = await import("./xTrendingParse"); + const real = await import("./__fixtures__/xTrendingRealShape"); + assert.deepEqual(trendPageOf(real.realPageBody()), { + title: real.REAL_TITLE, + summary: real.REAL_SUMMARY, + lastUpdatedAt: new Date(real.REAL_LAST_UPDATED_MS).toISOString(), + tabs: [ + { label: "Top", timelineId: real.REAL_TOP_TIMELINE }, + { label: "Latest", timelineId: real.REAL_LATEST_TIMELINE }, + ], + }); + // The accounts answer shares the page's `data` key and carries no page. + assert.equal(trendPageOf(real.realRelevantUsers().body), undefined); + assert.equal(trendPageOf(real.realStoryTopics().body), undefined); + assert.equal(trendPageOf(real.realFirstPage(real.REAL_FIRST).body), undefined); + assert.equal(trendPageOf({ data: null }), undefined); + assert.equal(trendPageOf("no"), undefined); + // Words are one line; a title that is not text, a tab with no id and a date that is no number are left out. + assert.deepEqual( + trendPageOf({ data: { any_key: { result: { page: { article: { title: " Two\n lines ", article_text: { text: 7 } }, last_updated_at_ms: "soon", post_timelines: [{ label: "Top" }, { label: "Latest", post_timeline: { id: "t2" } }, { label: "Again", post_timeline: { id: "t2" } }] } } } } }), + { title: "Two lines", tabs: [{ label: "Latest", timelineId: "t2" }] }, + ); +}); + +test("the real shape: a capture parses to the page's posts once each, the page, and which tab showed them", async () => { + const real = await import("./__fixtures__/xTrendingRealShape"); + const parsed = parseTrendingCapture(linesOf(real.realCaptureResponses()), "lib"); + // Six posts: the quoted post rides on the post quoting it, the accounts of the module are no posts. + assert.deepEqual(parsed.posts.map((p) => p.id), ["1900000000000003001", "1900000000000003002", "1900000000000003003", "1900000000000003004", "1900000000000003005", "1900000000000003006"]); + assert.equal(parsed.posts[1].quoted?.id, "1900000000000002900"); + assert.equal(parsed.page?.title, real.REAL_TITLE); + assert.equal(parsed.page?.summary, real.REAL_SUMMARY); + assert.deepEqual(parsed.timelines, [{ timelineId: real.REAL_TOP_TIMELINE, tab: "Top", posts: 6 }]); + assert.deepEqual(new Set(Object.values(parsed.tabs)), new Set(["Top"])); + assert.equal(Object.keys(parsed.tabs).length, 6); + assert.deepEqual( + parsed.operations.map((o) => [o.op, o.responses, o.tweets]), + [["AiTrendByRestId", 1, 0], ["DataSaverMode", 1, 0], ["GenericTimelineById", 3, 6], ["TrendRelevantUsers", 1, 0], ["useStoryTopicQuery", 1, 0], ["ViewerBadgeCounts", 1, 0]], + ); + assert.deepEqual(parsed.media, { + "1900000000000003001": { count: 1, kinds: ["image"] }, + "1900000000000003003": { count: 1, kinds: ["video"] }, + "1900000000000003004": { count: 1, kinds: ["gif"] }, + }); + // A capture with no page answer: posts all the same, no page, a timeline that is no known tab. + const bare = parseTrendingCapture(linesOf([real.realFirstPage(real.REAL_FIRST)]), "lib"); + assert.equal(bare.page, undefined); + assert.deepEqual(bare.timelines, [{ timelineId: real.REAL_TOP_TIMELINE, posts: 3 }]); + assert.deepEqual(bare.tabs, {}); + // The old fixture names no timeline: one untagged timeline. + assert.deepEqual(parseTrendingCapture(linesOf(fixtureTrendingResponses().load), "lib").timelines.map((t) => t.timelineId), [FIXTURE_TOP_TIMELINE]); +}); + +test("the real shape: the bottom cursor is read from a cursor entry AND from TimelineReplaceEntry", async () => { + const { timelineShapeOf, requestVariablesOf } = await import("./xTrendingParse"); + const real = await import("./__fixtures__/xTrendingRealShape"); + // The first answer: a cursor entry (the top cursor beside it is not the bottom's). + assert.deepEqual(timelineShapeOf(real.realFirstPage(real.REAL_FIRST).body), { instructions: true, bottom: real.realBottomCursor(1) }); + // A later answer: no cursor entry, two replacements. + const later = real.realContinuation(real.REAL_SECOND, { n: 2 }); + assert.deepEqual(timelineShapeOf(later.body), { instructions: true, bottom: real.realBottomCursor(2) }); + assert.deepEqual(requestVariablesOf(later.url), { cursor: real.realBottomCursor(1), timelineId: real.REAL_TOP_TIMELINE }); + assert.deepEqual(requestVariablesOf(real.realFirstPage([]).url), { timelineId: real.REAL_TOP_TIMELINE }); + // A replacement named only by the entry it replaces (no cursorType on the new entry) is still the bottom's. + assert.deepEqual( + timelineShapeOf({ instructions: [{ type: "TimelineReplaceEntry", entry_id_to_replace: "cursor-bottom-1", entry: { entryId: "x", content: { value: "next" } } }] }), + { instructions: true, bottom: "next" }, + ); + // A replacement of the TOP cursor alone names no bottom. + assert.deepEqual( + timelineShapeOf({ instructions: [{ type: "TimelineReplaceEntry", entry_id_to_replace: "cursor-top-9", entry: { entryId: "cursor-top-9", content: { cursorType: "Top", value: "up" } } }] }), + { instructions: true }, + ); + // The accounts answer has instructions and no cursor. + assert.deepEqual(timelineShapeOf(real.realRelevantUsers().body), { instructions: true }); +}); + +test("the real shape: a capped read asserts nothing; the bottom continuation that brings nothing new is the end; a failed last answer asserts nothing", async () => { + const real = await import("./__fixtures__/xTrendingRealShape"); + const end = (responses: Array<{ url: string; status: number; body?: unknown }>) => parseTrendingCapture(linesOf(responses), "lib").pageEnd; + // A CAPPED READ (what the first real read was: it stopped at its post cap): every continuation brought new posts. + assert.equal(end(real.realCaptureResponses()), false); + assert.equal(end(real.realCaptureResponses({ later: [] })), false); + // The continuation from the last bottom cursor (carried by a TimelineReplaceEntry) brings no post… + assert.equal(end([...real.realCaptureResponses(), real.realContinuation([], { n: 4 })]), true); + // …or only posts already shown. + assert.equal(end([...real.realCaptureResponses(), real.realContinuation(real.REAL_THIRD, { n: 4 })]), true); + // It must continue from the bottom cursor of the answer BEFORE it: the first answer's (an entry) is stale by then. + assert.equal(end([...real.realCaptureResponses(), real.realContinuation([], { n: 4, asked: real.realBottomCursor(1) })]), false); + assert.equal(end([...real.realCaptureResponses(), real.realContinuation([], { n: 4, asked: real.realTopCursor(3) })]), false); + // A FAILED LAST ANSWER: a 429, a body not kept, GraphQL errors, no instructions. + const last = real.realContinuation([], { n: 4 }); + assert.equal(end([...real.realCaptureResponses(), { ...last, status: 429 }]), false); + assert.equal(end([...real.realCaptureResponses(), { url: last.url, status: 200 }]), false); + assert.equal(end([...real.realCaptureResponses(), { ...last, body: { ...(last.body as object), errors: [{ message: "Timeout" }] } }]), false); + assert.equal(end([...real.realCaptureResponses(), { ...last, body: { data: { timeline: {} } } }]), false); + // A failed answer BEFORE the end, then a clean end: the capture still cannot tell. + assert.equal(end([...real.realCaptureResponses(), { ...last, status: 500 }, last]), false); + // One of the page's small answers failing is the page's failure too. + assert.equal(end([...real.realCaptureResponses(), last, { url: real.realStoryTopics().url, status: 500 }]), false); +}); + +test("the real shape: two tabs in one capture show no end, and each post is the tab's that showed it first", async () => { + const real = await import("./__fixtures__/xTrendingRealShape"); + const latest = { timelineId: real.REAL_LATEST_TIMELINE }; + const responses = [ + ...real.realCaptureResponses({ later: [] }), + real.realContinuation([], { n: 2 }), + // The other tab: a post of its own and one the first tab showed. + real.realFirstPage([real.REAL_SECOND[0], real.REAL_FIRST[0]], { ...latest, bottom: "latest-1" }), + real.realContinuation([], { ...latest, asked: "latest-1", bottom: "latest-2" }), + ]; + const parsed = parseTrendingCapture(linesOf(responses), "lib"); + assert.equal(parsed.pageEnd, false); + assert.deepEqual(parsed.timelines, [ + { timelineId: real.REAL_TOP_TIMELINE, tab: "Top", posts: 3 }, + { timelineId: real.REAL_LATEST_TIMELINE, tab: "Latest", posts: 1 }, + ]); + assert.equal(parsed.tabs["1900000000000003001"], "Top"); + assert.equal(parsed.tabs["1900000000000003004"], "Latest"); + // Each tab alone, read to its end, shows it: the continuation is its own timeline's. + assert.equal(parseTrendingCapture(linesOf(responses.slice(0, -2)), "lib").pageEnd, true); + // A continuation carrying ANOTHER timeline's bottom cursor is not this one's. + const crossed = [real.realFirstPage(real.REAL_FIRST), real.realContinuation([], { ...latest, asked: real.realBottomCursor(1) })]; + assert.equal(parseTrendingCapture(linesOf(crossed), "lib").pageEnd, false); +}); diff --git a/common/social/xTrendingParse.ts b/common/social/xTrendingParse.ts @@ -15,6 +15,17 @@ // context, not another post of the page; and it skips promoted entries. A few // operations known to belong to other surfaces of the app are ignored by name. // +// WHAT THE FIRST REAL READ SHOWED (lane x-followups; the shapes are in +// __fixtures__/xTrendingRealShape.ts, with invented data): one answer carries +// the page itself — X's title and summary for the trend, when X last updated +// them, and the page's TABS, each a label and the id of the timeline it +// lists (trendPageOf) — and the posts come from a timeline operation whose +// request names that timeline id and, after the first, the cursor it +// continues from. The first timeline answer ends with cursor ENTRIES; every +// later one carries its new cursors in TimelineReplaceEntry instructions +// (timelineShapeOf reads both). The page is found by its SHAPE, the timeline +// by the posts it lists: no operation is matched by name here either. +// // Pure but for readCaptureLines (node:fs). import { readFile } from "node:fs/promises"; @@ -238,24 +249,100 @@ export function mediaSourcesInCapture(lines: ReadonlyArray<TrendingCaptureLine>) return out; } -// The cursor a request carried: `variables` of the GraphQL URL, its `cursor`. -// Undefined when the URL has none or cannot be read. -export function requestCursorOf(url: string): string | undefined { +// What a request asked for: the `variables` of the GraphQL URL. `cursor` is the +// cursor it continues from, `timelineId` the timeline it lists (a trending +// page's tab). Empty when the URL has none or cannot be read. +export function requestVariablesOf(url: string): { cursor?: string; timelineId?: string } { try { const raw = new URL(url).searchParams.get("variables"); - const cursor = raw ? (JSON.parse(raw) as { cursor?: unknown } | null)?.cursor : undefined; - return typeof cursor === "string" && cursor ? cursor : undefined; + const v = raw ? (JSON.parse(raw) as { cursor?: unknown; timelineId?: unknown } | null) : null; + const text = (x: unknown) => (typeof x === "string" && x ? x : undefined); + const cursor = text(v?.cursor); + const timelineId = text(v?.timelineId); + return { ...(cursor ? { cursor } : {}), ...(timelineId ? { timelineId } : {}) }; } catch { - return undefined; + return {}; + } +} + +// The cursor a request carried. Undefined when the URL has none or cannot be read. +export function requestCursorOf(url: string): string | undefined { + return requestVariablesOf(url).cursor; +} + +// ONE TAB OF A TRENDING PAGE: its label as X shows it and the timeline it lists. +export type TrendingPageTab = { label: string; timelineId: string }; + +// WHAT THE PAGE SAYS OF ITSELF: X's title and summary for the trend (X's own +// words, written by X), when X last updated them, and the page's tabs. +export type TrendingPageInfo = { + title?: string; + summary?: string; + lastUpdatedAt?: string; + tabs: TrendingPageTab[]; +}; + +const oneLine = (v: unknown): string | undefined => { + if (typeof v !== "string") return undefined; + const text = v.replace(/\s+/g, " ").trim(); + return text || undefined; +}; + +// The page, from one answer's body: `data.<any>.result.page` holding an +// `article` (title, article_text.text) and/or `post_timelines` (label, +// post_timeline.id). Undefined for an answer that is not the page — the +// answers that share its `data` key but carry no `page` included. +export function trendPageOf(body: unknown): TrendingPageInfo | undefined { + const data = obj(obj(body)?.data); + if (!data) return undefined; + for (const value of Object.values(data)) { + const page = obj(obj(obj(value)?.result)?.page); + if (!page) continue; + const article = obj(page.article); + const title = oneLine(article?.title); + const summary = oneLine(obj(article?.article_text)?.text); + const tabs: TrendingPageTab[] = []; + for (const item of Array.isArray(page.post_timelines) ? page.post_timelines : []) { + const label = oneLine(obj(item)?.label); + const timelineId = obj(obj(item)?.post_timeline)?.id; + if (!label || typeof timelineId !== "string" || !timelineId) continue; + if (!tabs.some((t) => t.timelineId === timelineId)) tabs.push({ label, timelineId }); + } + if (!title && !summary && tabs.length === 0) continue; + const ms = page.last_updated_at_ms; + const at = typeof ms === "number" && Number.isFinite(ms) && ms > 0 ? new Date(ms) : undefined; + return { + ...(title ? { title } : {}), + ...(summary ? { summary } : {}), + ...(at && !Number.isNaN(at.getTime()) ? { lastUpdatedAt: at.toISOString() } : {}), + tabs, + }; } + return undefined; } // What an answer says of its timeline: whether it carries instructions at all, // and the BOTTOM cursor it ends with (the last one, when it names several). +// +// A cursor is read wherever the answer keeps one, in the two places the real +// page uses and any other: +// - a cursor ENTRY among a TimelineAddEntries' entries (the first answer of +// a timeline): `{entryId: "cursor-bottom-…", content: {cursorType: +// "Bottom", value}}`; +// - a TimelineReplaceEntry instruction (every later answer, which lists no +// cursor entry): `{type: "TimelineReplaceEntry", entry_id_to_replace: +// "cursor-bottom-…", entry: {entryId, content: {cursorType: "Bottom", +// value}}}` — beside one for the top cursor, which is not the bottom's. +// A cursor of a MODULE inside the timeline (a "show more" of a carousel) is +// not the timeline's: only `cursorType: "Bottom"`, or a `cursor-bottom` id, is. export function timelineShapeOf(payload: unknown): { instructions: boolean; bottom?: string } { let instructions = false; let bottom: string | undefined; const seen = new Set<unknown>(); + const cursorOf = (content: Record<string, unknown> | undefined): string | undefined => { + const v = content?.value ?? obj(content?.itemContent)?.value; + return typeof v === "string" && v ? v : undefined; + }; const visit = (node: unknown): void => { if (!node || typeof node !== "object" || seen.has(node)) return; seen.add(node); @@ -268,9 +355,13 @@ export function timelineShapeOf(payload: unknown): { instructions: boolean; bott const value = typeof rec.value === "string" && rec.value ? rec.value : undefined; if (value && rec.cursorType === "Bottom") bottom = value; if (typeof rec.entryId === "string" && rec.entryId.startsWith("cursor-bottom")) { - const inner = obj(rec.content); - const v = inner?.value ?? obj(inner?.itemContent)?.value; - if (typeof v === "string" && v) bottom = v; + const v = cursorOf(obj(rec.content)); + if (v) bottom = v; + } + // The replacement of the bottom cursor's entry, named by the entry it replaces. + if (rec.type === "TimelineReplaceEntry" && typeof rec.entry_id_to_replace === "string" && rec.entry_id_to_replace.startsWith("cursor-bottom")) { + const v = cursorOf(obj(obj(rec.entry)?.content)); + if (v) bottom = v; } for (const child of Object.values(rec)) visit(child); }; @@ -301,7 +392,22 @@ export type ParsedTrendingCapture = { // False whenever the capture cannot tell — which cursor an answer was for // included. Only a capture that shows the end may be read as "what this // page no longer shows". + // + // ONE TIMELINE (lane x-followups): the continuation is the last answer's + // OWN timeline's (the same operation asked for the same timeline id), and a + // capture that lists two timelines — two tabs of the page — shows no end: + // what one tab no longer shows says nothing of the other. pageEnd: boolean; + // What the page says of itself (trendPageOf), when an answer carried it. + page?: TrendingPageInfo; + // The timelines whose posts the capture lists, first listed first: the + // timeline id its requests named (absent when they named none), the tab of + // the page it is (when the page names that id), and how many of the page's + // posts it showed first. + timelines: Array<{ timelineId?: string; tab?: string; posts: number }>; + // Post id → the label of the tab that showed it first, for the posts whose + // timeline is one of the page's tabs. + tabs: Record<string, string>; }; // The capture, parsed. `channelSlug` is the library's (a Post names its channel). @@ -313,10 +419,14 @@ export function parseTrendingCapture( const media: Record<string, TrendingMediaSummary> = {}; const ops = new Map<string, TrendingOperation>(); let bytes = 0; - // Per answer of the page's own operations, in order: its operation, and how - // many posts it brought that no earlier answer had. - const answers: Array<{ op: string; fresh: number; asked?: string; bottom?: string; instructions: boolean }> = []; + // Per answer of the page's own operations, in order: its operation, the + // timeline it asked for, and how many posts it brought that no earlier + // answer had. + const answers: Array<{ op: string; timelineId?: string; fresh: number; asked?: string; bottom?: string; instructions: boolean }> = []; const seenIds = new Set<string>(); + // Post id → the timeline id of the answer that showed it first. + const firstTimeline = new Map<string, string>(); + let page: TrendingPageInfo | undefined; let failed = false; for (const line of lines) { const op = ops.get(line.op) ?? { op: line.op, responses: 0, bytes: 0, statuses: [], tweets: 0 }; @@ -333,8 +443,11 @@ export function parseTrendingCapture( // A 200 that carries GraphQL errors answered only in part, or not at all. const errors = obj(line.body)?.errors; if (Array.isArray(errors) && errors.length > 0) failed = true; + // The page itself: the first answer that carries it. + page ??= trendPageOf(line.body); const found = collectTimelineTweets(line.body); op.tweets += found.length; + const asked = requestVariablesOf(line.url); let fresh = 0; for (const raw of found) { raws.push(raw); @@ -342,29 +455,56 @@ export function parseTrendingCapture( if (id && !seenIds.has(id)) { seenIds.add(id); fresh++; + if (asked.timelineId) firstTimeline.set(id, asked.timelineId); } const summary = mediaSummaryOf(raw); if (id && summary && !media[id]) media[id] = summary; } const shape = timelineShapeOf(line.body); - const asked = requestCursorOf(line.url); - answers.push({ op: line.op, fresh, instructions: shape.instructions, ...(asked ? { asked } : {}), ...(shape.bottom ? { bottom: shape.bottom } : {}) }); + answers.push({ + op: line.op, + fresh, + instructions: shape.instructions, + ...(asked.timelineId ? { timelineId: asked.timelineId } : {}), + ...(asked.cursor ? { asked: asked.cursor } : {}), + ...(shape.bottom ? { bottom: shape.bottom } : {}), + }); } // The answers of the operations that ever listed posts, in order. const listing = answers.filter((a) => (ops.get(a.op)?.tweets ?? 0) > 0); if (listing.some((a) => !a.instructions)) failed = true; const last = listing.at(-1); - // The answer before it of the same operation: whose bottom cursor it must carry. - const before = last ? listing.slice(0, -1).filter((a) => a.op === last.op).at(-1) : undefined; + // The answer before it of the same operation AND the same timeline: whose + // bottom cursor it must carry. + const before = last ? listing.slice(0, -1).filter((a) => a.op === last.op && a.timelineId === last.timelineId).at(-1) : undefined; + const timelineIds = [...new Set(listing.map((a) => a.timelineId).filter((id): id is string => id !== undefined))]; const pageEnd = !failed && last !== undefined && + timelineIds.length <= 1 && before?.bottom !== undefined && last.asked === before.bottom && last.fresh === 0; const posts = normalizeXTweets(raws, channelSlug); const kept: Record<string, TrendingMediaSummary> = {}; for (const p of posts) if (media[p.id]) kept[p.id] = media[p.id]; + // Which tab showed what: the page's tabs by the timeline id they list. + const labelOf = new Map((page?.tabs ?? []).map((t) => [t.timelineId, t.label])); + const tabs: Record<string, string> = {}; + const shownFirst = new Map<string, number>(); + for (const p of posts) { + const timelineId = firstTimeline.get(p.id); + const label = timelineId ? labelOf.get(timelineId) : undefined; + if (label) tabs[p.id] = label; + if (timelineId) shownFirst.set(timelineId, (shownFirst.get(timelineId) ?? 0) + 1); + } + const untagged = posts.length - [...shownFirst.values()].reduce((a, n) => a + n, 0); + const timelines: ParsedTrendingCapture["timelines"] = timelineIds.map((timelineId) => ({ + timelineId, + ...(labelOf.get(timelineId) ? { tab: labelOf.get(timelineId)! } : {}), + posts: shownFirst.get(timelineId) ?? 0, + })); + if (untagged > 0 || (timelines.length === 0 && listing.length > 0)) timelines.push({ posts: untagged }); return { posts, media: kept, @@ -372,6 +512,9 @@ export function parseTrendingCapture( responses: lines.length, bytes, pageEnd, + ...(page ? { page } : {}), + timelines, + tabs, }; } diff --git a/editor/app/api/ops/trending/route.ts b/editor/app/api/ops/trending/route.ts @@ -20,10 +20,11 @@ export const dynamic = "force-dynamic"; // GET /api/ops/trending?slug=<library>[&topic=<topicId>][&limit=<n>] // -> { ok, slug, name, topics: [{id, title, posts, sources: [{trendId, url, -// title?, summary?, reads, lastReadAt}], watch?}], +// title?, summary?, lastUpdatedAt?, tabs?, lastReadTab?, reads, +// lastReadAt}], watch?}], // posts: [{id, author, authorName?, createdAt, url, text, // media: {count, kinds, thumbnail?}, topic, -// reads: [{read, trendId, at}], gone?, capture?, thread, +// reads: [{read, trendId, at, tab?}], gone?, capture?, thread, // judgement?}], // total, reads: [<readId>, …] } // diff --git a/editor/app/channels/[slug]/components/XTrendingPanel.tsx b/editor/app/channels/[slug]/components/XTrendingPanel.tsx @@ -317,11 +317,29 @@ export function XTrendingPanel({ </h4> <ul className="flex flex-col gap-0.5 text-xs text-muted-foreground"> {t.sources.map((s) => ( - <li key={s.trendId}> - <a href={s.url} target="_blank" rel="noreferrer" className="font-mono underline"> - {s.url} - </a>{" "} - · read {s.reads}×{s.lastReadAt ? `, last ${s.lastReadAt.slice(0, 16).replace("T", " ")} UTC` : ""} + <li key={s.trendId} data-x-trending-source={s.trendId} className="flex flex-col gap-0.5"> + <span> + <a href={s.url} target="_blank" rel="noreferrer" className="font-mono underline"> + {s.url} + </a>{" "} + · read {s.reads}×{s.lastReadAt ? `, last ${s.lastReadAt.slice(0, 16).replace("T", " ")} UTC` : ""} + {s.lastReadTab ? ( + <span data-x-trending-tab=""> + {" "} + · the last read saw the “{s.lastReadTab}” tab + {s.tabs && s.tabs.length > 1 ? ` of ${s.tabs.map((tab) => `“${tab}”`).join(", ")}` : ""} + </span> + ) : null} + </span> + {s.title ? ( + <span data-x-trending-x-title="" className="text-foreground"> + X’s title: {s.title} + {s.lastUpdatedAt ? ( + <span className="text-muted-foreground"> · X updated it {s.lastUpdatedAt.slice(0, 16).replace("T", " ")} UTC</span> + ) : null} + </span> + ) : null} + {s.summary ? <span data-x-trending-x-summary="">X’s summary: {s.summary}</span> : null} </li> ))} </ul> diff --git a/editor/e2e/x-trending.spec.ts b/editor/e2e/x-trending.spec.ts @@ -20,7 +20,10 @@ import { baseUrl } from "./baseUrl"; // under playwright's loader (digest.spec.ts says why). import { FIXTURE_FIRST_PAGE, + FIXTURE_SUMMARY, FIXTURE_TIMELINE_OP, + FIXTURE_TITLE, + FIXTURE_TOP_TIMELINE, FIXTURE_TREND_URL, fixtureContinuation, fixtureTimelineBody, @@ -111,24 +114,38 @@ test("an X trending library: the form, one read, the library by topic, the listi await expect .poll(async () => (await readdir(`${readsDir}/${readId}`)).sort(), { timeout: 15_000 }) .toEqual(["page.png", "read.json", "responses.jsonl"]); - const record = await readJson<{ outcome: string; stop: string; scrolls: number; posts: { onPage: number; added: number }; operations: { op: string }[]; sentence: string }>( - rel(`channels/${SLUG}/trending/reads/${readId}/read.json`), - ); + // read.json is written TWICE: when the read starts (stop "started", outcome "error": what a read that + // died is left as) and when it ends. The posts are on disk before the second write, so the record is + // read until it is the final one — never once, and never after a wait. + type ReadRecord = { outcome: string; stop: string; scrolls: number; posts: { onPage: number; added: number }; operations: { op: string }[]; tabs?: { tab?: string; posts: number }[]; sentence: string }; + const recordFile = rel(`channels/${SLUG}/trending/reads/${readId}/read.json`); + // A read between the two halves of the atomic write finds no file, or half of one: asked again. + const readRecord = () => readJson<ReadRecord>(recordFile).catch(() => null); + await expect.poll(async () => (await readRecord())?.stop ?? "started", { timeout: 30_000 }).not.toBe("started"); + const record = (await readRecord())!; expect(record.outcome).toBe("read"); expect(record.stop).toBe("idle"); expect(record.scrolls).toBe(3); expect(record.posts).toEqual({ onPage: 4, added: 4 }); expect(record.operations.map((o) => o.op)).toEqual(["ExampleTrendPage", "ExampleTrendTimeline", "HomeTimeline"]); - expect(record.sentence).toBe(`Read ${FIXTURE_TREND_URL}: 4 posts on the page, 4 new, in topic "Kettle Festival" (kettle-festival).`); + // Which of the page's tabs the read saw: the label and a count. + expect(record.tabs).toEqual([{ tab: "Top", posts: 4 }]); + expect(record.sentence).toBe(`Read ${FIXTURE_TREND_URL}: 4 posts on the page, 4 new, in topic "Kettle Festival" (kettle-festival), shown by the page's "Top" tab.`); const recordText = await readFile(t(`channels/${SLUG}/trending/reads/${readId}/read.json`), "utf8"); expect(recordText).not.toContain("teapot_news"); expect(recordText).not.toContain("festival opens"); + expect(recordText).not.toContain(FIXTURE_TOP_TIMELINE); // The library by topic. await page.reload(); const topic = page.locator('[data-x-trending-topic="kettle-festival"]'); await expect(topic).toContainText("Kettle Festival · 4 posts"); await expect(topic).toContainText(FIXTURE_TREND_URL); + // X's own words for the page, beside the operator's name for the topic; and the tab the read saw. + const source = topic.locator("[data-x-trending-source]"); + await expect(source.locator("[data-x-trending-x-title]")).toContainText(`X’s title: ${FIXTURE_TITLE}`); + await expect(source.locator("[data-x-trending-x-summary]")).toHaveText(`X’s summary: ${FIXTURE_SUMMARY}`); + await expect(source.locator("[data-x-trending-tab]")).toContainText("the last read saw the “Top” tab of “Top”, “Latest”"); await expect(topic.locator("[data-x-trending-post]")).toHaveCount(4); const first = topic.locator('[data-x-trending-post="1900000000000001001"]'); await expect(first).toContainText("@teapot_news (Teapot News)"); @@ -143,12 +160,12 @@ test("an X trending library: the form, one read, the library by topic, the listi const listed = await request.get(`${baseUrl}/api/ops/trending?slug=${SLUG}&topic=kettle-festival`, { headers: AUTH }); expect(listed.status()).toBe(200); const body = (await listed.json()) as { - topics: { id: string; title: string; posts: number; sources: { url: string; reads: number }[] }[]; + topics: { id: string; title: string; posts: number; sources: { url: string; reads: number; title?: string; summary?: string; tabs?: string[]; lastReadTab?: string }[] }[]; posts: { id: string; author: string; text: string; media: { count: number; kinds: string[] }; topic: string; reads: { read: string }[] }[]; total: number; reads: string[]; }; - expect(body.topics).toMatchObject([{ id: "kettle-festival", title: "Kettle Festival", posts: 4, sources: [{ url: FIXTURE_TREND_URL, reads: 1 }] }]); + expect(body.topics).toMatchObject([{ id: "kettle-festival", title: "Kettle Festival", posts: 4, sources: [{ url: FIXTURE_TREND_URL, reads: 1, title: FIXTURE_TITLE, summary: FIXTURE_SUMMARY, tabs: ["Top", "Latest"], lastReadTab: "Top" }] }]); expect(body.posts.map((p) => p.id)).toEqual(["1900000000000001001", "1900000000000001002", "1900000000000001004", "1900000000000001005"]); expect(body.posts[3]).toMatchObject({ author: "lid_watch", media: { count: 1, kinds: ["gif"] }, topic: "kettle-festival", reads: [{ read: readId }] }); expect(body.total).toBe(4); diff --git a/mcp/src/xTrending.test.ts b/mcp/src/xTrending.test.ts @@ -20,7 +20,19 @@ const LISTING = { id: "kettle-festival", title: "Kettle Festival", posts: 2, - sources: [{ trendId: "1900000000000000001", url: TREND, reads: 2, lastReadAt: "2026-11-17T12:00:00.000Z" }], + sources: [ + { + trendId: "1900000000000000001", + url: TREND, + title: "Kettle festival opens", + summary: "The annual kettle festival opened this morning.", + lastUpdatedAt: "2026-11-16T11:30:00.000Z", + tabs: ["Top", "Latest"], + lastReadTab: "Top", + reads: 2, + lastReadAt: "2026-11-17T12:00:00.000Z", + }, + ], }, ], posts: [ @@ -33,7 +45,7 @@ const LISTING = { text: "The kettle festival\nopens today.", media: { count: 2, kinds: ["image"] }, topic: "kettle-festival", - reads: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z" }], + reads: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z", tab: "Top" }], }, { id: "1900000000000001002", @@ -69,7 +81,9 @@ test("x_trending_topics: the library's topics, their pages and reads", async () [ "X trending library trending: 1 topic, 5 posts (private: on no site, in no index)", '- kettle-festival — "Kettle Festival": 2 posts', - ` ${TREND} · read 2×, last 2026-11-17 12:00 UTC`, + ` ${TREND} · read 2×, last 2026-11-17 12:00 UTC · the last read saw the "Top" tab of "Top", "Latest"`, + " X's title: Kettle festival opens (X updated it 2026-11-16 11:30 UTC)", + " X's summary: The annual kettle festival opened this morning.", `Saved reads (newest first): ${READ}`, ].join("\n"), ); @@ -90,7 +104,7 @@ test("x_trending_posts: each post's id, author, words, media, reads and topic", "1. 1900000000000001001 @teapot_news (Teapot News) · 2026-11-16 12:00 UTC · 2 media (image) · topic kettle-festival", " https://x.com/teapot_news/status/1900000000000001001", " The kettle festival / opens today.", - ` shown by: ${READ} (2026-11-17 10:00 UTC)`, + ` shown by: ${READ} (2026-11-17 10:00 UTC, the "Top" tab)`, "2. 1900000000000001002 @saucer_fan · 2026-11-16 13:00 UTC · no media · topic kettle-festival", " https://x.com/saucer_fan/status/1900000000000001002", " Second.", @@ -156,7 +170,7 @@ test("the tools say a topic's watch, and a post's thread, capture, gone-from-the assert.match(topics, /^ {4}watch: Watched every 30 min until 2026-11-20 10:00 UTC — PAUSED since 2026-11-18 11:00 UTC: X cookies were last refreshed 61 min ago/m); const posts = body(await client.callTool({ name: "x_trending_posts", arguments: { channel: "trending" } })); assert.deepEqual(posts.split("\n").slice(4), [ - ` shown by: ${READ} (2026-11-17 10:00 UTC)`, + ` shown by: ${READ} (2026-11-17 10:00 UTC, the "Top" tab)`, " in thread 1900000000000000999", ` gone from the page at 2026-11-18 10:30 UTC (read ${READ}; the page stopped showing it, which is not "deleted")`, " captured 2026-11-18 10:05 UTC: captured, 1 media file; more media owed once it is kept", diff --git a/mcp/src/xTrending.ts b/mcp/src/xTrending.ts @@ -25,7 +25,18 @@ type Topic = { id: string; title: string; posts: number; - sources?: Array<{ trendId: string; url: string; title?: string; summary?: string; reads: number; lastReadAt: string | null }>; + sources?: Array<{ + trendId: string; + url: string; + title?: string; + summary?: string; + // When X last rewrote its title and summary; the page's tabs by label; the tab the last read saw. + lastUpdatedAt?: string; + tabs?: string[]; + lastReadTab?: string; + reads: number; + lastReadAt: string | null; + }>; // The topic's watch, once it has been watched; `sentence` says what it is doing. watch?: { on: boolean; sentence: string; paused?: { reason: string }; ended?: { reason: string } }; }; @@ -39,7 +50,7 @@ type PostRow = { text: string; media?: { count: number; kinds?: string[]; thumbnail?: string }; topic: string; - reads?: Array<{ read: string; trendId: string; at: string }>; + reads?: Array<{ read: string; trendId: string; at: string; tab?: string }>; judgement?: { state: string; note?: string; by: string; at: string; from?: string }; thread?: string; // A page that showed it before did not show it at `at` (never "deleted"). @@ -58,7 +69,11 @@ export function renderXTrendingTopics(slug: string, body: ListingBody): string { for (const t of topics) { lines.push(`- ${t.id} — "${t.title}": ${t.posts} post${t.posts === 1 ? "" : "s"}`); for (const s of t.sources ?? []) { - lines.push(` ${s.url}${s.title ? ` "${s.title}"` : ""} · read ${s.reads}×, last ${day(s.lastReadAt)} UTC`); + const tab = s.lastReadTab + ? ` · the last read saw the "${s.lastReadTab}" tab${s.tabs && s.tabs.length > 1 ? ` of ${s.tabs.map((t) => `"${t}"`).join(", ")}` : ""}` + : ""; + lines.push(` ${s.url} · read ${s.reads}×, last ${day(s.lastReadAt)} UTC${tab}`); + if (s.title) lines.push(` X's title: ${s.title}${s.lastUpdatedAt ? ` (X updated it ${day(s.lastUpdatedAt)} UTC)` : ""}`); if (s.summary) lines.push(` X's summary: ${s.summary}`); } if (t.watch) lines.push(` watch: ${t.watch.sentence}`); @@ -78,7 +93,7 @@ export function renderXTrendingPosts(slug: string, body: ListingBody, topic?: st const lines = [`X trending library ${slug}${topic ? `, topic ${topic}` : ""}: ${posts.length} of ${total} post${total === 1 ? "" : "s"}`]; if (posts.length === 0) lines.push("No post."); for (const [i, p] of posts.entries()) { - const reads = (p.reads ?? []).map((r) => `${r.read} (${day(r.at)} UTC)`).join(", "); + const reads = (p.reads ?? []).map((r) => `${r.read} (${day(r.at)} UTC${r.tab ? `, the "${r.tab}" tab` : ""})`).join(", "); lines.push( `${i + 1}. ${p.id} @${p.author}${p.authorName ? ` (${p.authorName})` : ""} · ${day(p.createdAt)} UTC · ${mediaText(p.media)} · topic ${p.topic}`, ); @@ -210,7 +225,9 @@ export const X_TRENDING_TOOLS = [ name: "x_trending_topics", description: "An X TRENDING LIBRARY's topics: the operator's topics, each with the X trending pages " + - "(x.com/i/trending/<id>) read into it, how often and when, and its post count; and the " + + "(x.com/i/trending/<id>) read into it, how often and when, X's own title and summary of " + + "the page (X's words, not the operator's), which of the page's tabs the last read saw (a " + + "read sees ONE tab, the one the page opens on), and its post count; and the " + "ids of the saved reads; and each topic's WATCH, when it has one — whether it is being " + "read again on an interval, until when, and why it is paused (a watch runs only while " + "X's cookie jar is fresh, so a stale jar pauses it until the operator refreshes). A library is PRIVATE — on no site, in no index, so no other " + @@ -230,7 +247,7 @@ export const X_TRENDING_TOOLS = [ name: "x_trending_posts", description: "The posts of an X TRENDING LIBRARY (or of one of its topics): each post's id, author, " + - "date, words, media by kind and count, the reads that showed it, its topic, and — once " + + "date, words, media by kind and count, the reads that showed it (and the page's tab), its topic, and — once " + "it has them — the thread it belongs to, what its capture holds (and what media it is " + "still owed), its judgement (keep / drop / later; none is undecided; its own, or its " + "thread's), and whether a page stopped showing it (\"gone from the page at <time>\": a " + diff --git a/umtool/components/tools/library/LibraryView.tsx b/umtool/components/tools/library/LibraryView.tsx @@ -524,7 +524,10 @@ export default function LibraryView({ data: opened }: { data: Ok }) { {row.capture && <span data-library-capture={row.capture.state}>{captureSentence(row.capture, utc)}</span>} {row.capture?.mediaOwed && <span>media owed: {row.capture.mediaOwed === "kept" ? "fetched once the post is kept" : "asked for again by the next capture"}</span>} {!row.capture && row.media.count > 0 && <span>{row.media.count} media, not captured</span>} - <span>first shown {utc(row.detail?.firstSeenAt ?? row.reads[0]?.at ?? row.createdAt)}</span> + <span> + first shown {utc(row.detail?.firstSeenAt ?? row.reads[0]?.at ?? row.createdAt)} + {row.reads[0]?.tab ? ` on the “${row.reads[0].tab}” tab` : ""} + </span> </div> <div className="mt-2 flex flex-wrap items-center gap-1.5" data-library-actions=""> @@ -758,6 +761,31 @@ function TopicPanel({ lib, topic, topics, off, run, onPurged, go }: { lib: strin )} </div> + {topic && + topic.sources + .filter((src) => src.title || src.summary || src.lastReadTab) + .map((src) => ( + <div key={src.trendId} data-library-source={src.trendId} className="mt-2 text-[12.5px] text-text-2"> + {src.title && ( + <p className="m-0 break-words" data-library-x-title=""> + X’s title: <span className="text-text">{src.title}</span> + {src.lastUpdatedAt ? <span className="text-muted"> · X updated it {utc(src.lastUpdatedAt)}</span> : null} + </p> + )} + {src.summary && ( + <p className="m-0 break-words" data-library-x-summary=""> + X’s summary: {src.summary} + </p> + )} + {src.lastReadTab && ( + <p className="m-0 text-muted" data-library-tab=""> + The last read saw the page’s “{src.lastReadTab}” tab + {src.tabs && src.tabs.length > 1 ? ` (the page has ${src.tabs.map((tab) => `“${tab}”`).join(", ")}); a read sees one tab.` : "."} + </p> + )} + </div> + ))} + {topic && ( <div className="mt-2" data-library-watch-panel={!w ? "none" : w.ended ? "ended" : failing ? "failing" : w.paused ? "paused" : w.on ? "on" : "off"}> <p className="m-0 text-[12.5px] text-text-2" data-library-watch-sentence=""> diff --git a/umtool/e2e/fixtures/editor-stub-trending.mjs b/umtool/e2e/fixtures/editor-stub-trending.mjs @@ -118,7 +118,7 @@ function listing(sp) { } const fresh = seen ? mine.filter((p) => !seen[t.id] || p.firstSeenAt > seen[t.id]).length : null; const pub = detail ? state.published?.[t.id] : undefined; - return { id: t.id, title: t.title, posts: mine.length, ...(t.aliases?.length ? { aliases: t.aliases } : {}), ...(pub ? { published: { channel: pub.channel, firstAt: NOW, lastAt: NOW, posts: pub.posts.length } } : {}), ...(t.watch ? { watch: { ...t.watch, sentence: watchSentence(t.watch) } } : {}), ...(detail ? { counts } : {}), ...(fresh !== null ? { fresh } : {}), sources: [] }; + return { id: t.id, title: t.title, posts: mine.length, ...(t.aliases?.length ? { aliases: t.aliases } : {}), ...(pub ? { published: { channel: pub.channel, firstAt: NOW, lastAt: NOW, posts: pub.posts.length } } : {}), ...(t.watch ? { watch: { ...t.watch, sentence: watchSentence(t.watch) } } : {}), ...(detail ? { counts } : {}), ...(fresh !== null ? { fresh } : {}), sources: t.sources ?? [] }; }), posts: sp.get("ids") === "1" ? [] : rows.slice(offset, offset + limit).map((p) => row(p, detail)), total: rows.length, diff --git a/umtool/e2e/fixtures/library-fixture.mjs b/umtool/e2e/fixtures/library-fixture.mjs @@ -62,7 +62,12 @@ export function libraryState() { title: "Cup shortage", watch: { on: true, intervalMinutes: 60, startedAt: READ_1, until: "2026-11-19T10:00:00.000Z", shots: true, by: "agent", ticks: 5, failures: 3, nextSource: 0, goneSources: [], paused: { reason: "failing", since: READ_3, sentence: "The last read ended rate-limited." } }, }, - { id: "lids", title: "Lids" }, + // A topic whose page X described: its own title and summary, and the tab the last read saw (as the editor's listing gives them). + { + id: "lids", + title: "Lids", + sources: [{ trendId: "1900000000000000009", url: "https://x.com/i/trending/1900000000000000009", title: "Lid makers meet", summary: "Lid makers met to agree on one thread size.", lastUpdatedAt: "2026-11-17T09:30:00.000Z", tabs: ["Top", "Latest"], lastReadTab: "Top", reads: 1, lastReadAt: READ_1 }], + }, ], posts: [ post(P.opening, "teapot_news", "Teapot News", "The kettle festival opens today.", "kettle-festival", READ_1, { mediaCount: 2, kinds: ["image", "video"], capture: { at: "2026-11-17T10:05:00.000Z", state: "captured", mediaState: "ok" } }), diff --git a/umtool/e2e/library.spec.ts b/umtool/e2e/library.spec.ts @@ -383,6 +383,13 @@ test("the watch: why it is paused, that only the operator restarts a failing one await open(page, { topic: "lids" }); await expect(panel).toHaveAttribute("data-library-watch-panel", "none"); await expect(panel.locator("[data-library-watch-sentence]")).toHaveText("Not watched."); + // X's own title and summary of the page read into the topic, beside the operator's name for it, and the tab the last read saw. + const source = page.locator('[data-library-panel="lids"] [data-library-source]'); + await expect(source.locator("[data-library-x-title]")).toContainText("X’s title: Lid makers meet"); + await expect(source.locator("[data-library-x-summary]")).toHaveText("X’s summary: Lid makers met to agree on one thread size."); + await expect(source.locator("[data-library-tab]")).toHaveText("The last read saw the page’s “Top” tab (the page has “Top”, “Latest”); a read sees one tab."); + // A topic with no words from X shows none. + await expect(page.locator('[data-library-panel="lids"] [data-library-source]')).toHaveCount(1); await panel.locator("[data-library-watch-shots]").check(); await panel.locator("[data-library-watch-on]").click(); await expect(panel).toHaveAttribute("data-library-watch-panel", "on"); diff --git a/umtool/lib/library/cli.mjs b/umtool/lib/library/cli.mjs @@ -132,7 +132,18 @@ export async function libraryCommand(args, deps = {}) { const seen = await seenOf(reportsRoot, need(lib)); const listing = await listLibrary(ask, { slug: lib, detail: true, limit: 1, seen }); const topics = listing.topics.map((t) => ({ ...t, seenAt: seen[t.id] ?? null, fresh: t.fresh ?? t.posts })); - say({ slug: lib, topics }, topics.length ? topics.map((t) => `${t.id} ${t.title} ${t.posts} posts · ${t.counts?.unjudged ?? 0} unjudged · ${t.fresh} new\n ${t.watch ? t.watch.sentence : "Not watched."}`).join("\n") : `${lib} has no topic yet.`); + // X's own words for each page read into the topic, and the tab its last read saw. + const pages = (t) => + (t.sources ?? []) + .flatMap((src) => [ + src.title ? ` X's title: ${src.title}` : "", + src.summary ? ` X's summary: ${src.summary}` : "", + src.lastReadTab ? ` The last read saw the "${src.lastReadTab}" tab${src.tabs?.length > 1 ? ` of ${src.tabs.map((tab) => `"${tab}"`).join(", ")}` : ""}.` : "", + ]) + .filter(Boolean) + .map((line) => `\n${line}`) + .join(""); + say({ slug: lib, topics }, topics.length ? topics.map((t) => `${t.id} ${t.title} ${t.posts} posts · ${t.counts?.unjudged ?? 0} unjudged · ${t.fresh} new${pages(t)}\n ${t.watch ? t.watch.sentence : "Not watched."}`).join("\n") : `${lib} has no topic yet.`); return 0; } if (sub === "posts") { diff --git a/umtool/lib/library/cli.test.mjs b/umtool/lib/library/cli.test.mjs @@ -22,7 +22,7 @@ function harness(answers = {}) { return { ok: true, total: 1, - topics: [{ id: "kettles", title: "Kettles", posts: 3, counts: { unjudged: 2, keep: 0, drop: 1, later: 0, gone: 1 }, ...(sp.get("seen") ? { fresh: Object.keys(JSON.parse(sp.get("seen"))).length ? 2 : 3 } : {}), watch: { on: true, sentence: "Watched every 30 min." }, sources: [] }], + topics: [{ id: "kettles", title: "Kettles", posts: 3, counts: { unjudged: 2, keep: 0, drop: 1, later: 0, gone: 1 }, ...(sp.get("seen") ? { fresh: Object.keys(JSON.parse(sp.get("seen"))).length ? 2 : 3 } : {}), watch: { on: true, sentence: "Watched every 30 min." }, sources: answers.sources ?? [] }], posts: [{ id: "11", author: "teapot_news", text: "The kettle\nfestival opens.", thread: "11", gone: { at: "2026-11-17T11:00:00.000Z" }, capture: { state: "captured", at: "2026-11-17T10:05:00.000Z" } }], }; } @@ -126,6 +126,28 @@ test("watch and purge: the switch with its terms; the editor's refusal is exit 1 }); }); +test("topics says X's own title and summary of each page, and the tab the last read saw", async () => { + await withRoot(async (root) => { + const h = harness({ + sources: [ + { trendId: "1", url: "https://x.com/i/trending/1", title: "Kettle festival opens", summary: "The festival opened this morning.", tabs: ["Top", "Latest"], lastReadTab: "Top", reads: 1, lastReadAt: "2026-11-17T10:00:00.000Z" }, + { trendId: "2", url: "https://x.com/i/trending/2", reads: 1, lastReadAt: "2026-11-17T10:00:00.000Z" }, + ], + }); + assert.equal(await libraryCommand(["topics", "lib"], { ...h.deps, reportsRoot: root }), 0); + assert.equal( + h.lines[0], + [ + "kettles Kettles 3 posts · 2 unjudged · 3 new", + " X's title: Kettle festival opens", + " X's summary: The festival opened this morning.", + ' The last read saw the "Top" tab of "Top", "Latest".', + " Watched every 30 min.", + ].join("\n"), + ); + }); +}); + test("seen marks topics in umtool's own state, and --new counts from it", async () => { await withRoot(async (root) => { const h = harness();