// AN X TRENDING LIBRARY end to end (lane x-trending, slice 1): the platform // choice "X trending library" in the New channel form makes a private library // (no URL, the Sites section replaced by "never on a site"); Read a trending // page on its channel page runs ONE read-x-trending job on X's queue, which // saves the page's answers raw and writes the posts it parses from the saved // file; the page then shows the library by topic; `get trending` answers the // same; a stale cookie jar refuses a second read before any job. // // X is NEVER contacted and no browser starts: the test server's fake browser // (E2E_FAKE_X_PROFILE_COOKIES_FILE, common/social/fakeXProfileBrowser.ts) // plays back the INVENTED trending page of // common/social/__fixtures__/xTrendingCapture.ts. The "connected profile" is // an empty directory and a cookie jar with a made-up login. import { test, expect } from "@playwright/test"; import { mkdir, readFile, readdir, stat, utimes, writeFile } from "node:fs/promises"; import { generateReport, pathExists, readJson, resetData, resolvePath, testPaths, writeSettings, writeSite } from "./helpers"; import { baseUrl } from "./baseUrl"; // By relative path: a runtime import of the package specifier does not resolve // under playwright's loader (digest.spec.ts says why). import { FIXTURE_FIRST_PAGE, FIXTURE_SUMMARY, FIXTURE_TITLE, FIXTURE_TOP_TIMELINE, FIXTURE_TREND_URL, fixtureContinuation, fixtureTimelineBody, fixtureTimelineUrl, fixtureTrendingResponses, fixtureTwoTabResponses, FIXTURE_LATEST_PAGE, } from "../../common/social/__fixtures__/xTrendingCapture"; const TOKEN = "test-worker-token"; const AUTH = { authorization: `Bearer ${TOKEN}` }; const SLUG = "trending"; const t = (p: string) => resolvePath(`${testPaths().transcriptsDir}/${p}`); const rel = (p: string) => `${testPaths().transcriptsDir}/${p}`; type Config = { platform?: string; sourceKind?: string; url?: string; socialHandle?: string; postFetcher?: string; xTrending?: Record }; const archiveLines = async (): Promise => { // A library keeps its posts under trending/, not where a posts channel does. const file = rel(`channels/${SLUG}/trending/posts-archive`); return (await pathExists(file)) ? (await readFile(resolvePath(file), "utf8")).split("\n").filter(Boolean).length : 0; }; async function seed() { await resetData("empty"); // The cookie-age limit is off on the test server unless a spec sets it (e2e/servers.ts). await writeSettings({ minFreeDiskGB: 0, social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 60 } } }); await writeSite("demo-site", { siteTitle: "Demo" }); // A connected X profile whose jar, written now, holds a (made-up) login. await mkdir(t(".x-session/profile"), { recursive: true }); await writeFile( t(".x-session/cookies.txt"), "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tfixture-not-a-real-token\n", ); // The fake browser's page: the invented trending page. await writeFile( t(".fake-x-profile-cookies.json"), JSON.stringify({ cookies: [{ name: "auth_token", value: "fixture-not-a-real-token", domain: ".x.com" }], trending: fixtureTrendingResponses(), }), ); } test("an X trending library: the form, one read, the library by topic, the listing, a stale jar", async ({ page, request }) => { test.setTimeout(120_000); await seed(); await generateReport(page, "new"); await page.goto("/channels/new"); await page.locator('select[name="platform"]').selectOption("x-trending"); await expect(page.locator("[data-x-trending-no-site]")).toHaveText("An X trending library is private: it is never put on a site."); await expect(page.locator("[data-x-trending-fields]")).toBeVisible(); await expect(page.locator('input[name="socialHandle"]')).toHaveCount(0); await expect(page.locator('input[name="fetchPostsNow"]')).toHaveCount(0); await page.locator('input[name="name"]').fill("Trending"); await page.locator('input[name="slug"]').fill(SLUG); await page.getByRole("button", { name: /create|add channel|save/i }).first().click(); const configPath = rel(`channels/${SLUG}/config.json`); await expect .poll(async () => ((await pathExists(configPath)) ? await readJson(configPath) : null), { timeout: 15_000 }) .toMatchObject({ platform: "twitter", sourceKind: "social", xTrending: {} }); const config = await readJson(configPath); expect(config.url).toBeUndefined(); expect(config.socialHandle).toBeUndefined(); expect(config.postFetcher).toBeUndefined(); // The library's page: nothing yet, and it says it is private. await generateReport(page, SLUG); await page.goto(`/channels/${SLUG}`); await expect(page.locator("[data-x-trending-private]")).toHaveText("Private: on no site, in no build, not in search."); await expect(page.getByLabel("trending topics")).toContainText("No topic yet."); await expect(page.getByRole("button", { name: /fetch posts|sync new/i })).toHaveCount(0); // One read, into a named topic. await page.getByLabel("trending page URL").fill(`${FIXTURE_TREND_URL}?src=trend_click`); await page.getByLabel("topic", { exact: true }).fill("Kettle Festival"); // One tab here: the page's other tab is the two-tab test's (the last one in this file). await page.getByLabel("tabs", { exact: true }).selectOption("top"); await page.getByRole("button", { name: "Read trending page" }).click(); // Four posts: the promoted entry, the quoted post and another surface's post are not the page's. await expect.poll(archiveLines, { timeout: 60_000 }).toBe(4); // What the read left: the raw answers, a screenshot, a record with names and sizes only. const readsDir = t(`channels/${SLUG}/trending/reads`); const reads = async () => (await readdir(readsDir).catch(() => [] as string[])).filter((n) => n.startsWith("tr-")); await expect.poll(async () => (await reads()).length, { timeout: 15_000 }).toBe(1); const [readId] = await reads(); // The captures are never committed: the reads directory ignores everything under it. expect(await readFile(`${readsDir}/.gitignore`, "utf8")).toMatch(/^\*$/m); expect(readId).toMatch(/^tr-[0-9A-Z]{26}$/); await expect .poll(async () => (await readdir(`${readsDir}/${readId}`)).sort(), { timeout: 15_000 }) .toEqual(["page.png", "read.json", "responses.jsonl"]); // 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?: Record[]; 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(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"]); // Which of the page's tabs the read saw: the label and a count. expect(record.tabs).toEqual([{ tab: "Top", asked: "top", posts: 4, scrolls: 3, stop: "idle", pageEnd: false }]); 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)"); await expect(first).toContainText("2 media (image)"); await expect(first).toContainText("The kettle festival opens today."); await expect(topic.locator('[data-x-trending-post="1900000000000001004"]')).toContainText("1 media (video)"); await expect(page.getByLabel("saved read")).toHaveValue(readId); await expect(page.locator("body")).not.toContainText("Buy our kettles."); await expect(page.locator("body")).not.toContainText("Not on the trending page."); // The same over ops: what an agent reads. Never the raw capture. 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; 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, 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); expect(body.reads).toEqual([readId]); expect(JSON.stringify(body)).not.toContain("fixtureQueryId"); // On no site, and a site cannot take it. const site = await readJson<{ channels: { slug: string }[] }>(rel("sites/demo-site/site.json")); expect(site.channels).toEqual([]); const onSite = await request.post(`${baseUrl}/api/ops/channel-config`, { headers: AUTH, data: { slug: SLUG, sites: [{ siteId: "demo-site", groupId: "default" }] }, }); expect(onSite.status()).toBe(400); expect(((await onSite.json()) as { error: string }).error).toBe("trending is an X trending library: it is private, and never put on a site."); // A cookie jar past the limit: the next read is refused before any job, with the guard's sentence. const old = new Date(Date.now() - 2 * 60 * 60_000); await utimes(t(".x-session/cookies.txt"), old, old); const stale = await request.post(`${baseUrl}/api/ops/read-x-trending`, { headers: AUTH, data: { slug: SLUG, url: FIXTURE_TREND_URL }, }); expect(stale.status()).toBe(400); expect(((await stale.json()) as { error: string }).error).toMatch(/^X cookies were last refreshed 2 h ago \(limit 60 min\)/); expect((await reads()).length).toBe(1); expect(await archiveLines()).toBe(4); // Where every other reader of a posts channel looks, the library has nothing. expect(await pathExists(rel(`channels/${SLUG}/posts`))).toBe(false); expect(await pathExists(rel(`channels/${SLUG}/posts-archive`))).toBe(false); }); // LANE x-trending-2: judge, watch, media kept once, gone from the page, and // the jar rule pausing the watch. Still no browser and no request to X or to // its media CDN: the fake page and the played-back CDN // (common/social/fakeXProfileBrowser.ts fakeXMediaFetch) answer everything. test("an X trending library: judgements, a watch tick, media kept once, gone from the page, a stale jar pauses the watch", async ({ page, request }) => { test.setTimeout(180_000); await seed(); const post = async (action: string, data: Record) => { const res = await request.post(`${baseUrl}/api/ops/${action}`, { headers: AUTH, data }); return { status: res.status(), json: (await res.json()) as Record }; }; const listing = async () => (await (await request.get(`${baseUrl}/api/ops/trending?slug=${SLUG}`, { headers: AUTH })).json()) as { topics: { id: string; watch?: { on: boolean; ticks: number; paused?: { reason: string }; sentence: string } }[]; posts: { id: string; gone?: { at: string }; capture?: { files: number; mediaState: string }; judgement?: { state: string; by: string } }[]; }; const made = await post("create-channel", { slug: SLUG, fields: { name: "Trending", handling: "transcribe", platform: "x-trending" } }); expect(made.status, JSON.stringify(made.json)).toBe(200); expect((await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL, topic: "Kettle Festival" })).status).toBe(200); await expect.poll(archiveLines, { timeout: 60_000 }).toBe(4); // JUDGE. An agent keeps one (marking only); the operator drops another on the page. const A = "1900000000000001001"; const B = "1900000000000001002"; const kept = await post("judge-trending", { slug: SLUG, archive: false, set: [{ id: A, state: "keep", note: "the opening" }] }); expect(kept.json).toMatchObject({ ok: true, written: [{ id: A, state: "keep" }], skipped: [], kept: [A] }); await generateReport(page, SLUG); await page.goto(`/channels/${SLUG}`); const topic = page.locator('[data-x-trending-topic="kettle-festival"]'); await expect(topic.locator(`[data-x-trending-post="${A}"] [data-x-trending-judgement="keep"]`)).toContainText("keep by agent: the opening"); await page.getByRole("button", { name: `Drop ${B}`, exact: true }).click(); // (The page re-renders after the action: allow it more than the default wait.) await expect(topic.locator(`[data-x-trending-post="${B}"] [data-x-trending-judgement="drop"]`)).toContainText("drop by operator", { timeout: 30_000 }); // An agent's judgement never replaces the operator's. const over = await post("judge-trending", { slug: SLUG, archive: false, set: [{ id: B, state: "keep" }] }); expect(over.json).toMatchObject({ written: [], skipped: [{ id: B, reason: "judged by the operator: an agent's judgement does not replace it" }] }); expect((await readJson<{ posts: Record }>(rel(`channels/${SLUG}/trending/judgements.json`))).posts[B]).toMatchObject({ state: "drop", by: "operator" }); // WATCH the topic, from the page. await topic.getByRole("button", { name: "Watch", exact: true }).click(); await expect(topic.locator("[data-x-trending-watch-state]")).toContainText("Watched every 30 min until", { timeout: 30_000 }); await expect(topic).toContainText("it does not cover a night nobody refreshes in"); expect((await listing()).topics[0].watch).toMatchObject({ on: true, ticks: 0 }); // The page has changed: the opening post and a NEW one with two pictures; the rest are no longer shown. const NEW = "1900000000000001006"; const picture = (i: number) => `https://pbs.twimg.com/media/Fixture1006${i}?format=jpg&name=orig`; await writeFile( t(".fake-x-profile-cookies.json"), JSON.stringify({ cookies: [{ name: "auth_token", value: "fixture-not-a-real-token", domain: ".x.com" }], trending: { load: [ { // The timeline's first request, as the page sends it: it names the timeline and carries no cursor. url: fixtureTimelineUrl(), status: 200, body: fixtureTimelineBody([FIXTURE_FIRST_PAGE[0], { id: NEW, handle: "spout_clips", text: "Two pictures of the queue.", media: ["photo", "photo"] }]), }, ], // Asked for more, the timeline has none: the page's end, which is what lets a read say "gone". scrolls: [[fixtureContinuation()], []], }, // The same bytes at both addresses: one file in the library. (The opening // post's two pictures, never captured, are taken by the same job.) media: { [picture(0)]: { text: "FIXTURE PICTURE BYTES" }, [picture(1)]: { text: "FIXTURE PICTURE BYTES" }, "https://pbs.twimg.com/media/Fixture10010?format=jpg&name=orig": { text: "OPENING PICTURE ONE" }, "https://pbs.twimg.com/media/Fixture10011?format=jpg&name=orig": { text: "OPENING PICTURE TWO" }, }, }), ); // ONE SCAN (what the timer does once a minute; not armed on the test server): one read is started. const tick = await post("watch-trending", { slug: SLUG, tick: true }); expect(tick.status, JSON.stringify(tick.json)).toBe(200); expect(tick.json.scan).toMatchObject({ live: 1, enqueued: { slug: SLUG, topic: "kettle-festival", url: FIXTURE_TREND_URL }, paused: [] }); await expect.poll(archiveLines, { timeout: 60_000 }).toBe(5); // A second scan at once starts nothing: the next tick is an interval away. expect(((await post("watch-trending", { slug: SLUG, tick: true })).json.scan as { enqueued?: unknown }).enqueued).toBeUndefined(); // The new post's MEDIA came at once, from the (played-back) CDN, and is kept once. const dir = t(`channels/${SLUG}/trending/posts-media/${NEW}`); await expect.poll(async () => (await readdir(dir).catch(() => [] as string[])).sort(), { timeout: 60_000 }).toEqual([`${NEW}_1.jpg`, `${NEW}_2.jpg`, "capture.json"]); expect(await readFile(`${dir}/${NEW}_1.jpg`, "utf8")).toBe("FIXTURE PICTURE BYTES"); expect((await stat(`${dir}/${NEW}_1.jpg`)).ino).toBe((await stat(`${dir}/${NEW}_2.jpg`)).ino); const index = await readJson<{ blobs: Record; urls: string[] }> }>(rel(`channels/${SLUG}/trending/media-index.json`)); const blobOfNew = Object.values(index.blobs).filter((b) => b.posts[NEW]); expect(blobOfNew).toHaveLength(1); expect(blobOfNew[0].posts).toEqual({ [NEW]: [`${NEW}_1.jpg`, `${NEW}_2.jpg`] }); // A post of the watched topic that has media and was never captured is taken by the same job. await expect.poll(async () => (await readdir(t(`channels/${SLUG}/trending/posts-media/${A}`)).catch(() => [] as string[])).sort(), { timeout: 60_000 }).toEqual([`${A}_1.jpg`, `${A}_2.jpg`, "capture.json"]); // Never committed, and never where a posts channel keeps its captures. expect(await readFile(t(`channels/${SLUG}/trending/.gitignore`), "utf8")).toMatch(/^posts-media\/$/m); expect(await pathExists(rel(`channels/${SLUG}/posts-media`))).toBe(false); // GONE FROM THE PAGE: the three posts the page stopped showing, said so, never "deleted". const after = await listing(); expect(after.posts.filter((p) => p.gone).map((p) => p.id).sort()).toEqual([B, "1900000000000001004", "1900000000000001005"]); expect(after.posts.find((p) => p.id === NEW)?.capture).toMatchObject({ files: 2, mediaState: "ok" }); expect(after.topics[0].watch).toMatchObject({ on: true, ticks: 1 }); await page.reload(); await expect(topic.locator(`[data-x-trending-post="${B}"] [data-x-trending-gone]`)).toContainText("Gone from the page at"); await expect(topic.locator(`[data-x-trending-post="${A}"] [data-x-trending-gone]`)).toHaveCount(0); await expect(page.locator("body")).not.toContainText(/deleted/i); // THE JAR RULE: past its limit the watch PAUSES (nothing is enqueued, nothing refreshes the jar), and /review says so. const old = new Date(Date.now() - 2 * 60 * 60_000); await utimes(t(".x-session/cookies.txt"), old, old); const paused = await post("watch-trending", { slug: SLUG, tick: true }); expect(paused.json.scan).toMatchObject({ paused: [{ slug: SLUG, topic: "kettle-festival", reason: "jar" }] }); expect((paused.json.scan as { enqueued?: unknown }).enqueued).toBeUndefined(); expect((await listing()).topics[0].watch?.sentence).toMatch(/PAUSED since .* UTC: X cookies were last refreshed 2 h ago \(limit 60 min for a watch\)/); expect((await stat(t(".x-session/cookies.txt"))).mtimeMs).toBeLessThan(Date.now() - 60 * 60_000); await page.goto("/review"); const section = page.getByRole("region", { name: "paused watches" }); await expect(section).toContainText("Paused watches (1)"); await expect(section).toContainText("Kettle Festival"); await expect(section).toContainText("It resumes by itself at the first scan after Refresh cookies on /cookies."); // "Refreshed" (the jar written now): the first scan after it resumes the watch. const now = new Date(); await utimes(t(".x-session/cookies.txt"), now, now); const resumed = await post("watch-trending", { slug: SLUG, tick: true }); expect(resumed.json.scan).toMatchObject({ resumed: [{ slug: SLUG, topic: "kettle-festival" }], paused: [] }); await page.reload(); await expect(page.getByRole("region", { name: "paused watches" })).toHaveCount(0); // Stop watching. const off = await post("watch-trending", { slug: SLUG, topic: "kettle-festival", on: false, by: "operator" }); expect(off.json.sentence).toBe('The watch of "Kettle Festival" was switched off.'); // PURGE (lane posts-library): the captures of DROPPED posts, in two steps, the second the operator's. // The watch's new post is dropped; its capture goes, the kept post's stays, and so does every judgement. expect((await post("judge-trending", { slug: SLUG, by: "operator", archive: false, set: [{ id: NEW, state: "drop" }] })).json).toMatchObject({ written: [{ id: NEW, state: "drop" }] }); type Plan = { ok?: boolean; error?: string; posts?: number; ids?: string[]; files?: number; bytes?: number; confirm?: string; captureInFlight?: boolean; sentence?: string }; // (A tick resumed above may still be reading or capturing: a dry run says so, and the removal waits for it.) let plan: Plan = {}; await expect .poll( async () => { plan = (await post("purge-trending", { slug: SLUG, dryRun: true })).json as Plan; return plan.ok === true && plan.captureInFlight !== true && (plan.ids ?? []).includes(NEW); }, { timeout: 90_000 }, ) .toBe(true); expect(plan.ids).toEqual([NEW]); const had = (await readdir(dir)).sort(); expect(had).toEqual(expect.arrayContaining([`${NEW}_1.jpg`, `${NEW}_2.jpg`, "capture.json"])); expect(plan.files).toBe(had.length); expect(plan.sentence).toContain(`Would remove the capture of 1 dropped post: ${had.length} files, `); // Nothing went, and an agent may not remove. expect((await readdir(dir)).sort()).toEqual(had); const agent = await post("purge-trending", { slug: SLUG, confirm: plan.confirm }); expect(agent.status).toBe(400); expect(String(agent.json.error)).toContain("the operator's press"); const stale = await post("purge-trending", { slug: SLUG, confirm: "0000000000000000", by: "operator" }); expect(String(stale.json.error)).toContain("have changed since the dry run"); expect(await pathExists(rel(`channels/${SLUG}/trending/posts-media/${NEW}`))).toBe(true); const removed = await post("purge-trending", { slug: SLUG, confirm: plan.confirm, by: "operator" }); expect(removed.status, JSON.stringify(removed.json)).toBe(200); expect(removed.json).toMatchObject({ ok: true, dryRun: false, posts: 1, ids: [NEW], files: had.length }); expect(await pathExists(rel(`channels/${SLUG}/trending/posts-media/${NEW}`))).toBe(false); // The kept post's capture and the judgements are whole; the post is still listed, still dropped. expect((await readdir(t(`channels/${SLUG}/trending/posts-media/${A}`))).sort()).toContain("capture.json"); const purged = await listing(); expect(purged.posts.find((p) => p.id === NEW)).toMatchObject({ judgement: { state: "drop", by: "operator" } }); expect(purged.posts.find((p) => p.id === NEW)?.capture).toBeUndefined(); expect(purged.posts.find((p) => p.id === B)).toMatchObject({ judgement: { state: "drop", by: "operator" } }); }); // SLICE 4 (lane x-trending-publish): the library's topics organised, a topic // PUBLISHED into an ordinary channel on no site, and an account broken out. // Over ops (umtool's Posts library page is the operator's form of the same // actions: umtool/e2e/library.spec.ts). X is never contacted: the one read is // the fake browser's, the capture is planted, and archiving an account from a // library starts no fetch. test("an X trending library: rename, move, merge; a topic published into an ordinary channel that names nothing of the library; an account archived with nothing asked of X", async ({ page, request }) => { test.setTimeout(240_000); await seed(); const post = async (action: string, data: Record) => { const res = await request.post(`${baseUrl}/api/ops/${action}`, { headers: AUTH, data }); return { status: res.status(), json: (await res.json()) as Record }; }; const get = async (query: string) => (await (await request.get(`${baseUrl}/api/ops/trending?${query}`, { headers: AUTH })).json()) as Record; const A = "1900000000000001001"; const B = "1900000000000001002"; const D = "1900000000000001004"; const made = await post("create-channel", { slug: SLUG, fields: { name: "Trending", handling: "transcribe", platform: "x-trending" } }); expect(made.status, JSON.stringify(made.json)).toBe(200); expect((await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL, topic: "Kettle Festival" })).status).toBe(200); await expect.poll(archiveLines, { timeout: 60_000 }).toBe(4); // (The read's job has ended before anything below asks whether one is in flight.) await expect.poll(async () => ((await (await request.get(`${baseUrl}/api/ops/jobs?active=1&slug=${SLUG}`, { headers: AUTH })).json()) as { jobs?: unknown[] }).jobs?.length ?? 0, { timeout: 60_000 }).toBe(0); // RENAME (an agent may): the name changes, the id stays. const renamed = await post("organise-trending", { slug: SLUG, op: "rename", topic: "kettle-festival", title: "Kettles 2026" }); expect(renamed.json).toMatchObject({ ok: true, topic: "kettle-festival", title: "Kettles 2026", was: "Kettle Festival", changed: true }); expect((await get(`slug=${SLUG}`)).topics.map((t: any) => [t.id, t.title])).toEqual([["kettle-festival", "Kettles 2026"]]); // MOVE a post into a new topic, then try to merge it back. const moved = await post("organise-trending", { slug: SLUG, op: "move", to: "Spoons", ids: [B], create: true }); expect(moved.json).toMatchObject({ ok: true, to: { id: "spoons", title: "Spoons", created: true }, moved: [B], skipped: [] }); expect((await get(`slug=${SLUG}&topic=spoons`)).total).toBe(1); // A merge is the operator's: an agent's is refused, and nothing changes. const agentMerge = await post("organise-trending", { slug: SLUG, op: "merge", into: "kettle-festival", from: ["spoons"] }); expect(agentMerge.status).toBe(400); expect(String(agentMerge.json.error)).toContain("Merging topics is the operator's press"); // …and it waits for a read: one is started (the same page, read again), and the merge is refused while it is queued or running. expect((await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL })).status).toBe(200); // S9: a rename waits for it too (a read may name its topic by its name)… const renameWaits = await post("organise-trending", { slug: SLUG, op: "rename", topic: "spoons", title: "Spoons and forks", by: "operator" }); expect(renameWaits.status).toBe(400); expect(String(renameWaits.json.error)).toContain("A read of this library is queued or running: rename its topic once it has finished"); const waiting = await post("organise-trending", { slug: SLUG, op: "merge", into: "kettle-festival", from: ["spoons"], by: "operator" }); expect(waiting.status).toBe(400); expect(String(waiting.json.error)).toContain("A read of this library is queued or running: merge its topics once it has finished"); expect((await get(`slug=${SLUG}`)).topics).toHaveLength(2); let merged: Record = {}; await expect .poll( async () => { merged = (await post("organise-trending", { slug: SLUG, op: "merge", into: "kettle-festival", from: ["spoons"], by: "operator" })).json; return merged.ok === true; }, { timeout: 90_000 }, ) .toBe(true); expect(merged).toMatchObject({ into: { id: "kettle-festival", title: "Kettles 2026" }, merged: [{ id: "spoons", title: "Spoons", posts: 1, pages: 0 }], posts: 1 }); expect(String(merged.sentence)).toContain("This cannot be undone."); const one = await get(`slug=${SLUG}&topic=spoons`); expect(one.topics.map((t: any) => [t.id, t.posts, t.aliases])).toEqual([["kettle-festival", 4, ["spoons"]]]); expect(one.total).toBe(4); // KEEP: the operator keeps A (its capture planted, as a capture job leaves one), an agent keeps D. expect((await post("judge-trending", { slug: SLUG, by: "operator", archive: false, set: [{ id: A, state: "keep", note: "a private note" }] })).json).toMatchObject({ kept: [A] }); expect((await post("judge-trending", { slug: SLUG, archive: false, set: [{ id: D, state: "keep" }] })).json).toMatchObject({ kept: [D] }); const libCapture = t(`channels/${SLUG}/trending/posts-media/${A}`); await mkdir(libCapture, { recursive: true }); await writeFile(`${libCapture}/shot.png`, "FIXTURE SHOT BYTES"); await writeFile( `${libCapture}/capture.json`, JSON.stringify({ version: 1, id: A, url: `https://x.com/i/status/${A}`, capturedAt: "2026-11-18T10:00:00.000Z", state: "captured", shot: { name: "shot.png", bytes: 18, sha256: "6d61761833abb83a81e789df143b2b3d569aeb136516ee31791ec30c60d26c2a" }, mediaState: "skipped", mediaOwed: "kept", media: [] }), ); // PUBLISH, step one: what would be written. Nothing is. const dry = await post("publish-trending", { slug: SLUG, topic: "kettle-festival", dryRun: true }); expect(dry.status, JSON.stringify(dry.json)).toBe(200); expect(dry.json).toMatchObject({ dryRun: true, channel: "kettles-2026", creates: true, sites: [], kept: 1, posts: 1, ids: [A], already: 0, movedIn: [], files: 1, bytes: 18, mismatched: [], textOnly: [], noLongerKept: [] }); expect(String(dry.json.sentence)).toContain('would make the channel "kettles-2026", on no site, writing 1 post and 1 file (18 B)'); expect(await pathExists(rel("channels/kettles-2026"))).toBe(false); // An agent may not publish; a confirm that is not this dry run's is refused. const agent = await post("publish-trending", { slug: SLUG, topic: "kettle-festival", confirm: dry.json.confirm }); expect(agent.status).toBe(400); expect(String(agent.json.error)).toContain("Publishing a topic is the operator's press"); expect(String((await post("publish-trending", { slug: SLUG, topic: "kettle-festival", confirm: "0".repeat(24), by: "operator" })).json.error)).toContain("has changed since it was counted"); expect(await pathExists(rel("channels/kettles-2026"))).toBe(false); // Step two, the operator's: an ordinary channel, on no site. const done = await post("publish-trending", { slug: SLUG, topic: "kettle-festival", confirm: dry.json.confirm, by: "operator" }); expect(done.status, JSON.stringify(done.json)).toBe(200); expect(done.json).toMatchObject({ dryRun: false, channel: "kettles-2026", creates: true, posts: 1, files: 1 }); expect(await readJson(rel("channels/kettles-2026/config.json"))).toEqual({ name: "Kettles 2026", handling: "transcribe", sourceKind: "social", platform: "twitter" }); const lines = (await readFile(t("channels/kettles-2026/posts/2026-11.jsonl"), "utf8").catch(async () => { const dir = t("channels/kettles-2026/posts"); return readFile(`${dir}/${(await readdir(dir))[0]}`, "utf8"); })).trim().split("\n").map((l) => JSON.parse(l) as { id: string; slug: string; channelSlug: string; author: string }); expect(lines.map((p) => [p.id, p.slug, p.channelSlug, p.author])).toEqual([[A, `kettles-2026/${A}`, "kettles-2026", "teapot_news"]]); // The shot is a COPY: its own inode, one name. const copy = await stat(t(`channels/kettles-2026/posts-media/${A}/shot.png`)); expect(await readFile(t(`channels/kettles-2026/posts-media/${A}/shot.png`), "utf8")).toBe("FIXTURE SHOT BYTES"); expect(copy.ino).not.toBe((await stat(`${libCapture}/shot.png`)).ino); expect(copy.nlink).toBe(1); // NOTHING OF THE LIBRARY in the channel: not its slug, a judgement, the note, a read, what was owed. const walk = async (dir: string): Promise => (await Promise.all((await readdir(dir, { withFileTypes: true })).map((e) => (e.isDirectory() ? walk(`${dir}/${e.name}`) : [`${dir}/${e.name}`])))).flat(); for (const file of await walk(t("channels/kettles-2026"))) { const text = await readFile(file, "utf8"); for (const word of [`${SLUG}/`, `"${SLUG}"`, "xTrending", "a private note", "judg", "operator", "agent", "mediaOwed", "tr-01", "gone"]) { expect(text.includes(word), `${file} carries ${word}`).toBe(false); } } // On no site; the agent's keep and the undecided posts stayed in the library. expect(JSON.stringify(await readJson>(rel("sites/demo-site/site.json")))).not.toContain("kettles-2026"); expect((await readJson<{ topics: Record }> }>(rel(`channels/${SLUG}/trending/published.json`))).topics["kettle-festival"]).toMatchObject({ slug: "kettles-2026" }); // THE PUBLISHED CHANNEL MAKES NO REQUEST: a direct ask is refused with one sentence, and no job is made. const SAYS = "kettles-2026 holds posts published from a private library: it has no account to fetch from"; for (const [action, data] of [ ["fetch-posts", { slug: "kettles-2026" }], ["capture-posts", { slug: "kettles-2026", ids: [A] }], ["check-post-availability", { slug: "kettles-2026" }], ["x-run", { channels: ["kettles-2026"] }], // Configure cannot give it a source (a url, a handle). ["channel-config", { slug: "kettles-2026", patch: { url: "https://x.com/teapot_news" } }], ["channel-config", { slug: "kettles-2026", patch: { socialHandle: "teapot_news" } }], ] as const) { const refused = await post(action, data); expect(refused.status, `${action}: ${JSON.stringify(refused.json)}`).toBeGreaterThanOrEqual(400); expect(String(refused.json.error), action).toContain(SAYS); } expect((((await (await request.get(`${baseUrl}/api/ops/jobs?slug=kettles-2026`, { headers: AUTH })).json()) as { jobs?: unknown[] }).jobs ?? []).length).toBe(0); // It is a channel like any other on the editor's pages. await page.goto("/channels/kettles-2026"); await expect(page.locator("body")).toContainText("Kettles 2026"); // RE-PUBLISH adds and removes nothing: A is dropped, B is kept. await post("judge-trending", { slug: SLUG, by: "operator", archive: false, set: [{ id: A, state: "drop" }, { id: B, state: "keep" }] }); const again = await post("publish-trending", { slug: SLUG, topic: "spoons", dryRun: true }); expect(again.json).toMatchObject({ channel: "kettles-2026", creates: false, sites: [], kept: 1, posts: 1, ids: [B], already: 0, files: 0, textOnly: [B], noLongerKept: [A] }); // S5: B was moved (by an agent, into "spoons", which the operator's merge then brought here): the last hand is the merge's. expect(again.json.movedIn).toEqual([{ id: B, by: "operator", from: "spoons" }]); expect(String(again.json.sentence)).toContain("1 post to publish was moved into this topic: 0 by an agent, 1 by the operator."); // S4: THE OPERATOR PUTS THE CHANNEL ON A SITE between the count and the press: the confirm no longer holds, and // the next dry run names the site and says the post goes public. // Configure sets a published channel's name and its sites, and nothing else (channel-config is its ops twin). const onSite = await post("channel-config", { slug: "kettles-2026", patch: { name: "Kettles, 2026" }, sites: [{ siteId: "demo-site" }] }); expect(onSite.status, JSON.stringify(onSite.json)).toBe(200); expect(await readJson(rel("channels/kettles-2026/config.json"))).toEqual({ name: "Kettles, 2026", handling: "transcribe", sourceKind: "social", platform: "twitter" }); expect(JSON.stringify((await readJson<{ channels: unknown }>(rel("sites/demo-site/site.json"))).channels)).toContain("kettles-2026"); const stale2 = await post("publish-trending", { slug: SLUG, topic: "kettle-festival", confirm: again.json.confirm, by: "operator" }); expect(String(stale2.json.error)).toContain("has changed since it was counted"); const named = await post("publish-trending", { slug: SLUG, topic: "kettle-festival", dryRun: true }); expect(named.json.sites).toEqual(["demo-site"]); expect(String(named.json.sentence)).toContain("THIS CHANNEL IS ON THE SITE demo-site: this post goes public at its next build."); again.json.confirm = named.json.confirm; const second = await post("publish-trending", { slug: SLUG, topic: "kettle-festival", confirm: again.json.confirm, by: "operator" }); expect(second.status, JSON.stringify(second.json)).toBe(200); expect(String(second.json.sentence)).toContain("1 post published before is no longer kept: it stays in the channel (a publish removes nothing)."); expect((await readFile(t("channels/kettles-2026/posts-archive"), "utf8")).split("\n").filter(Boolean).sort()).toEqual([`twitter ${A}`, `twitter ${B}`]); expect(await pathExists(rel(`channels/kettles-2026/posts-media/${A}/shot.png`))).toBe(true); // A channel of the slug that this publish did not make is never appended to. const taken = await post("publish-trending", { slug: SLUG, topic: "kettle-festival", dryRun: true, channel: "elsewhere" }); expect(String(taken.json.error)).toContain('published into the channel "kettles-2026": a topic has one channel'); // THE ACCOUNTS, and one broken out: -x on no site, and X is asked nothing. const accounts = await get(`slug=${SLUG}&accounts=1`); expect(accounts.accounts.map((a: any) => a.handle).sort()).toEqual(expect.arrayContaining(["saucer_fan", "spout_clips", "teapot_news"])); expect(accounts.accounts.find((a: any) => a.handle === "saucer_fan")).toMatchObject({ posts: 1, kept: 1, keptByOperator: 1, topics: ["kettle-festival"] }); const plan = await post("x-search-lead", { slug: SLUG, handle: "saucer_fan", action: "archive", dryRun: true }); expect(plan.json).toMatchObject({ ok: true, dryRun: true, slug: "saucer_fan-x" }); expect(await pathExists(rel("channels/saucer_fan-x"))).toBe(false); const archived = await post("x-search-lead", { slug: SLUG, handle: "saucer_fan", action: "archive" }); expect(archived.status, JSON.stringify(archived.json)).toBe(200); expect(archived.json).toMatchObject({ ok: true, slug: "saucer_fan-x", jobIds: [], syncOff: true }); // M1: MADE WITH SYNC OFF. A never-synced channel with a URL is the most overdue one the scheduler knows, so // without this its next tick would fetch it. The sentence says so and how to turn it on. expect(String(archived.json.sentence)).toBe( `Made the channel "saucer_fan-x" for @saucer_fan, on no site, with sync off (its priority is paused): nothing was asked of X, and nothing will be until you say so. To turn sync on, set its priority to normal on /channels (pnpm ops channel-priority --json '{"slugs":["saucer_fan-x"],"tier":"normal"}'). Its first fetch is Fetch posts on its page (pnpm ops fetch-posts --json '{"slug":"saucer_fan-x"}').`, ); const settings = await readJson<{ channelPriority?: { channels?: Record } }>(testPaths().settingsFile); expect(settings.channelPriority?.channels?.["saucer_fan-x"]).toMatchObject({ tier: "paused" }); // (That a paused tier keeps it out of the scheduler, Sync all and the lanes: common/jobs/xLeadSyncOff.test.ts.) const account = await readJson(rel("channels/saucer_fan-x/config.json")); expect(account).toMatchObject({ platform: "twitter", sourceKind: "social", url: "https://x.com/saucer_fan", socialHandle: "saucer_fan" }); expect(JSON.stringify(account)).not.toContain(SLUG); expect((((await (await request.get(`${baseUrl}/api/ops/jobs?slug=saucer_fan-x`, { headers: AUTH })).json()) as { jobs?: unknown[] }).jobs ?? []).length).toBe(0); expect(JSON.stringify(await readJson>(rel("sites/demo-site/site.json")))).not.toContain("saucer_fan-x"); expect((await get(`slug=${SLUG}&accounts=1`)).accounts.find((a: any) => a.handle === "saucer_fan").archivedAs).toEqual(["saucer_fan-x"]); const twice = await post("x-search-lead", { slug: SLUG, handle: "saucer_fan", action: "archive" }); expect(String(twice.json.error)).toContain("@saucer_fan is already archived: saucer_fan-x."); }); // ADDED SCOPE R3 (lane x-followups): one job reads the page's "Top" tab and // then presses its "Latest" tab. The fake page has both (invented data); no // browser, no request. test("an X trending library: one read covers Top and Latest; a Latest that never loads is said and is no failure; a post that leaves Latest is gone from that tab only", async ({ page, request }) => { test.setTimeout(240_000); await seed(); const post = async (action: string, data: Record) => { const res = await request.post(`${baseUrl}/api/ops/${action}`, { headers: AUTH, data }); return { status: res.status(), json: (await res.json()) as Record }; }; type Tab = { tab?: string; asked?: string; posts: number; scrolls?: number; stop?: string; pageEnd?: boolean; why?: string }; type Record_ = { stop: string; outcome: string; sentence: string; tabs?: Tab[] }; const fake = (trending: unknown) => writeFile(t(".fake-x-profile-cookies.json"), JSON.stringify({ cookies: [{ name: "auth_token", value: "fixture-not-a-real-token", domain: ".x.com" }], trending })); const readsDir = t(`channels/${SLUG}/trending/reads`); const readIds = async () => (await readdir(readsDir).catch(() => [] as string[])).filter((n) => n.startsWith("tr-")).sort(); // The n-th read's final record (read.json is written when a read starts and again when it ends). const finished = async (n: number): Promise => { await expect.poll(async () => (await readIds()).length, { timeout: 60_000 }).toBe(n); const file = rel(`channels/${SLUG}/trending/reads/${(await readIds())[n - 1]}/read.json`); const read = () => readJson(file).catch(() => null); await expect.poll(async () => (await read())?.stop ?? "started", { timeout: 90_000 }).not.toBe("started"); return (await read())!; }; const idle = () => expect.poll(async () => ((await (await request.get(`${baseUrl}/api/ops/jobs?active=1&slug=${SLUG}`, { headers: AUTH })).json()) as { jobs?: unknown[] }).jobs?.length ?? 0, { timeout: 60_000 }).toBe(0); const listing = async () => (await (await request.get(`${baseUrl}/api/ops/trending?slug=${SLUG}`, { headers: AUTH })).json()) as { topics: { sources: { lastReadTab?: string; lastReadTabs?: string[] }[] }[]; posts: { id: string; reads: { tab?: string }[]; gone?: { at: string }; goneTabs?: { tab: string }[] }[]; }; expect((await post("create-channel", { slug: SLUG, fields: { name: "Trending", handling: "transcribe", platform: "x-trending" } })).status).toBe(200); // 1. BOTH TABS, ONE JOB (the default): Top's four posts, and the one only Latest shows. await fake(fixtureTwoTabResponses()); expect((await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL, topic: "Kettle Festival" })).status).toBe(200); const first = await finished(1); expect(first.outcome).toBe("read"); expect(first.tabs).toEqual([ { tab: "Top", asked: "top", posts: 4, scrolls: 3, stop: "idle", pageEnd: true }, { tab: "Latest", asked: "latest", posts: 3, scrolls: 2, stop: "idle", pageEnd: true }, ]); expect(first.sentence).toBe(`Read ${FIXTURE_TREND_URL}: 5 posts on the page, 5 new, in topic "Kettle Festival" (kettle-festival), shown by the page's "Top" and "Latest" tabs.`); expect((await readdir(`${readsDir}/${(await readIds())[0]}`)).sort()).toEqual(["page-latest.png", "page.png", "read.json", "responses.jsonl"]); await idle(); const one = await listing(); expect(one.topics[0].sources[0].lastReadTabs).toEqual(["Top", "Latest"]); expect(one.posts.find((p) => p.id === "1900000000000001001")?.reads.map((r) => r.tab)).toEqual(["Top", "Latest"]); expect(one.posts.find((p) => p.id === "1900000000000001009")?.reads.map((r) => r.tab)).toEqual(["Latest"]); await page.goto(`${baseUrl}/channels/${SLUG}`); await expect(page.locator("[data-x-trending-source] [data-x-trending-tab]")).toContainText("the last read saw the “Top” and “Latest” tabs"); // "tabs" is top, latest or both: anything else is refused with a sentence, before any job. const bad = await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL, tabs: ["media"] }); expect(bad.status).toBe(400); expect(String(bad.json.error)).toBe('"tabs" is ["top"], ["latest"] or ["top", "latest"] (the default: both, read in one job)'); // 2. A POST LEAVES LATEST between two reads: Latest now lists one post; 1001 is still on Top, 1009 was only ever on Latest. await fake(fixtureTwoTabResponses([FIXTURE_LATEST_PAGE[2]])); expect((await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL })).status).toBe(200); const second = await finished(2); expect(second.sentence).toContain('1 post this page showed before is gone from the page at'); expect(second.sentence).toContain('1 post is gone from the "Latest" tab and still shown by another.'); await idle(); const two = await listing(); expect(two.posts.find((p) => p.id === "1900000000000001001")?.goneTabs?.map((g) => g.tab)).toEqual(["Latest"]); expect(two.posts.find((p) => p.id === "1900000000000001001")?.gone).toBeUndefined(); expect(two.posts.find((p) => p.id === "1900000000000001009")?.gone).toBeTruthy(); await page.reload(); await expect(page.locator('[data-x-trending-post="1900000000000001001"] [data-x-trending-gone-tab="Latest"]')).toContainText("Gone from the “Latest” tab at"); await expect(page.locator('[data-x-trending-post="1900000000000001001"] [data-x-trending-gone]')).toHaveCount(0); await expect(page.locator('[data-x-trending-post="1900000000000001009"] [data-x-trending-gone]')).toContainText("Gone from the page at"); // 3. A LATEST TAB THAT NEVER LOADS: pressed, and the page asks nothing for it. The read waits its 20 s, says so, and is a read. const never = fixtureTwoTabResponses(); never.tabs.Latest = {}; await fake(never); expect((await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL })).status).toBe(200); const third = await finished(3); expect(third.outcome).toBe("read"); expect(third.tabs?.[1]).toEqual({ tab: "Latest", asked: "latest", posts: 0, scrolls: 0, stop: "not-read", pageEnd: false, why: 'pressing "Latest" brought no answer for its timeline within 20 s' }); expect(third.sentence).toContain('Top read; Latest not read: pressing "Latest" brought no answer for its timeline within 20 s.'); await idle(); // Nothing is retried: three reads were asked for, and three there are; nothing new is said of Latest's posts. expect(await readIds()).toHaveLength(3); expect((await listing()).posts.find((p) => p.id === "1900000000000001005")?.gone).toBeUndefined(); });