// A reply's thread shot, against fakes only: the parent picked from a // recorded page snapshot, the blur's choice, the union box, and the run that // shoots it beside the post's own shot. No browser, no network. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xThreadShot.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, readFile, stat } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import type { PageLike } from "./playwrightRuntime"; import { readPostCapture, SHOT_FILENAME, THREAD_SHOT_FILENAME, writePostCapture } from "./postCapture"; import { unionBox, VIEW_SCRIPT_MARKER, type ElementView } from "./viewportShot"; import { boxInShot, MARK_PARENT_MARKER, pickThreadParent, REDACT_MARKER, REDACTED_BOXES_MARKER, redactScript, shootXThread, THREAD_SNAPSHOT_MARKER, threadRedaction, type ThreadArticle, type ThreadSnapshot, } from "./xThreadShot"; import { captureXPosts, threadRedactFor, type XCaptureDeps, type XPostSnapshot } from "./xPostCapture"; const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 7]); const THREAD_PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 8, 8]); const art = (id: string, handle: string, top: number, bottom: number, over: Partial = {}): ThreadArticle => ({ id, handle, name: handle, verified: false, top, bottom, ...over, }); // The reply 2114214000653414579's page, as its archive says: a chain // root -> 2114113495989907691 (Toothless2210) -> the reply, and a reply under it. const CHAIN: ThreadSnapshot = { own: 2, articles: [ art("2114053463176855722", "TheQuartering", 0, 400), art("2114113495989907691", "Toothless2210", 400, 620), art("2114214000653414579", "TheQuartering", 620, 900), art("2114300000000000000", "someone", 900, 1100), ], }; // --- the parent ---------------------------------------------------------------- test("parent: the archive's in-reply-to id picks the IMMEDIATE parent out of a chain, not its root", () => { const pick = pickThreadParent(CHAIN, { id: "2114113495989907691" }); assert.ok("parent" in pick); assert.equal(pick.index, 1); assert.equal(pick.parent.handle, "Toothless2210"); assert.equal(pick.from, "reply-to"); }); test("parent: with no archive word, the post directly above the reply; never a reply listed under it", () => { const pick = pickThreadParent(CHAIN, null); assert.ok("parent" in pick); assert.equal(pick.parent.id, "2114113495989907691"); assert.equal(pick.from, "above"); // The reply under the post is not a parent, even named by id. const under = pickThreadParent(CHAIN, { id: "2114300000000000000" }); assert.ok("none" in under); }); test("parent: an archive id not on the page is no parent (the post above it would be a grandparent)", () => { const gone = pickThreadParent(CHAIN, { id: "999" }); assert.ok("none" in gone); assert.match(gone.none, /999.*did not render/); }); test("parent: a post with nothing above it is not a reply; an unmarked page has no own article", () => { const alone: ThreadSnapshot = { own: 0, articles: [art("1", "a", 0, 300), art("2", "b", 300, 500)] }; const none = pickThreadParent(alone, null); assert.ok("none" in none); assert.match(none.none, /Not a reply/); assert.ok("none" in pickThreadParent({ own: -1, articles: CHAIN.articles }, null)); }); // --- the blur ------------------------------------------------------------------ test("blur: a private author is blurred; a gold- or grey-checked one or the reply's own author is not; the knob overrides", () => { assert.deepEqual(threadRedaction({ parentHandle: "someone", parentVerified: false, ownHandle: "TheQuartering" }), { redact: true, reason: "private", }); for (const parentBadge of ["gold", "grey"] as const) { assert.deepEqual(threadRedaction({ parentHandle: "org", parentVerified: true, parentBadge, ownHandle: "TheQuartering" }), { redact: false, reason: "verified", }); } // X Premium's blue check is bought: the proof run's parent (a person asking "How's Huck?") carries one. for (const parentBadge of ["blue", "other", undefined] as const) { assert.deepEqual(threadRedaction({ parentHandle: "Toothless2210", parentVerified: true, parentBadge, ownHandle: "TheQuartering" }), { redact: true, reason: "blue-check", }); } // A self-thread, whatever the case or the @. assert.deepEqual(threadRedaction({ parentHandle: "thequartering", parentVerified: false, ownHandle: "@TheQuartering" }), { redact: false, reason: "self", }); assert.deepEqual(threadRedaction({ parentHandle: "x", parentVerified: false, ownHandle: "y" }, false), { redact: false, reason: "off" }); assert.deepEqual(threadRedaction({ parentHandle: "x", parentVerified: true, parentBadge: "gold", ownHandle: "y" }, true), { redact: true, reason: "forced" }); // No own handle known: not a self-thread. assert.equal(threadRedaction({ parentHandle: "x", parentVerified: false }).redact, true); }); test("blur: the knob per post — the run's boolean, or the post's own entry", () => { assert.equal(threadRedactFor(undefined, "1"), undefined); assert.equal(threadRedactFor(false, "1"), false); assert.equal(threadRedactFor({ "1": false }, "1"), false); assert.equal(threadRedactFor({ "1": false }, "2"), undefined); }); test("blur: the page script blurs by profile link, case-insensitively, falling back to the User-Name block", () => { const s = redactScript("@Toothless2210"); assert.match(s, /"toothless2210"/); assert.match(s, /Tweet-User-Avatar/); assert.match(s, /User-Name/); assert.match(s, /blur\(/); }); test("boxes: the union of the parent's and the reply's boxes; a blurred box placed in the shot, its spread clipped", () => { const parent = { x: 283, y: -200, width: 598, height: 220 }; const own = { x: 283, y: 20, width: 598, height: 280 }; assert.deepEqual(unionBox([parent, own]), { x: 283, y: -200, width: 598, height: 500 }); assert.equal(unionBox([]), null); const u = unionBox([parent, own])!; // The avatar at the parent's top-left corner: its spread clipped at 0. assert.deepEqual(boxInShot({ x: 299, y: -188, width: 40, height: 40 }, u, 36), { x: 0, y: 0, width: 92, height: 88 }); assert.deepEqual(boxInShot({ x: 400, y: -150, width: 100, height: 20 }, u, 0), { x: 117, y: 50, width: 100, height: 20 }); }); // --- the shot ------------------------------------------------------------------ type FakeThreadPage = PageLike & { calls: string[]; shots: unknown[] }; // A page holding CHAIN: the window measure answers the union of the parent's // and the reply's boxes (viewport coordinates) when asked for both. function threadPage(opts: { snap?: ThreadSnapshot; redacted?: { avatar: number; name: number; mention: number } | null; post?: XPostSnapshot; windowed?: boolean; } = {}): FakeThreadPage { const calls: string[] = []; const shots: unknown[] = []; const view: ElementView = { x: 283, y: 64, width: 598, height: 500, vw: 1280, vh: 900 }; const ownView: ElementView = { x: 283, y: 284, width: 598, height: 280, vw: 1280, vh: 900 }; return { calls, shots, goto: async (url: string) => void calls.push(`goto ${url}`), waitForSelector: async () => undefined, waitForTimeout: async () => undefined, on: () => {}, ...(opts.windowed === false ? {} : { setViewportSize: async () => undefined }), evaluate: async (script: string) => { if (script.includes(VIEW_SCRIPT_MARKER)) { if (opts.windowed === false) return null; const both = script.includes("data-archilyzer-thread-parent"); calls.push(both ? "measure-thread" : "measure-own"); return both ? view : ownView; } if (script.includes(THREAD_SNAPSHOT_MARKER)) return opts.snap ?? CHAIN; if (script.includes(MARK_PARENT_MARKER)) { calls.push(`mark ${/\[(\d+)\]/.exec(script)?.[1]}`); return true; } if (script.includes(REDACT_MARKER)) { calls.push("redact"); return opts.redacted === undefined ? { avatar: 1, name: 2, mention: 1 } : opts.redacted; } if (script.includes(REDACTED_BOXES_MARKER)) { return { parts: [ { x: 283, y: 64, width: 598, height: 220 }, { x: 283, y: 284, width: 598, height: 280 }, ], redacted: [ { what: "avatar", box: { x: 299, y: 76, width: 40, height: 40 } }, { what: "name", box: { x: 347, y: 76, width: 110, height: 20 } }, ], }; } if (script.includes("imgs.length")) return 0; if (script.includes("b.click()")) return 0; if (script.includes("article[data-testid")) { calls.push("snapshot"); return opts.post ?? { path: "/TheQuartering/status/2114214000653414579", text: "", article: { rect: { x: 283, y: 284, width: 598, height: 280 }, sensitive: false } }; } return undefined; }, screenshot: async (o?: unknown) => { shots.push(o); const clip = (o as { clip?: { height: number } })?.clip; return clip && clip.height === 500 ? THREAD_PNG : PNG; }, }; } test("shot: the union from the parent's top to the reply's bottom, the private author blurred first, the boxes recorded", async () => { const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xthread-")), "2114214000653414579"); const p = threadPage(); const res = await shootXThread(p, "2114214000653414579", dir, { replyTo: { id: "2114113495989907691", author: "Toothless2210" }, url: "https://x.com/i/status/2114214000653414579", }); assert.ok("thread" in res, JSON.stringify(res)); const t = res.thread; assert.equal(t.name, THREAD_SHOT_FILENAME); assert.equal(t.parentId, "2114113495989907691"); assert.equal(t.parentHandle, "Toothless2210"); assert.equal(t.parentVerified, false); assert.equal(t.parentFrom, "reply-to"); assert.equal(t.redaction.applied, true); assert.equal(t.redaction.reason, "private"); assert.deepEqual(t.redaction.boxes, [ { what: "avatar", box: { x: 0, y: 0, width: 92, height: 88 } }, { what: "name", box: { x: 28, y: 0, width: 182, height: 68 } }, ]); // Marked, blurred, THEN shot -- one viewport clip of the union. assert.deepEqual(p.calls.filter((c) => c !== "measure-thread"), ["mark 1", "redact"]); assert.deepEqual(p.shots, [{ type: "png", clip: { x: 283, y: 64, width: 598, height: 500 } }]); assert.deepEqual(new Uint8Array(await readFile(path.join(dir, THREAD_SHOT_FILENAME))), THREAD_PNG); }); test("shot: a gold-checked parent is shot unblurred; a parent whose name cannot be found to blur gets no shot", async () => { const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xthread-")), "1"); const verified = { ...CHAIN, articles: CHAIN.articles.map((a, i) => (i === 1 ? { ...a, verified: true, badge: "gold" as const } : a)) }; const p = threadPage({ snap: verified }); const res = await shootXThread(p, "1", dir, { replyTo: { id: "2114113495989907691" } }); assert.ok("thread" in res); assert.deepEqual(res.thread.redaction, { applied: false, reason: "verified", boxes: [] }); assert.ok(!p.calls.includes("redact")); const dir2 = path.join(await mkdtemp(path.join(os.tmpdir(), "xthread-")), "1"); const blind = threadPage({ redacted: { avatar: 1, name: 0, mention: 0 } }); const refused = await shootXThread(blind, "1", dir2, { replyTo: { id: "2114113495989907691" } }); assert.ok("error" in refused); assert.match(refused.error, /could not be found to blur/); assert.equal(blind.shots.length, 0); await assert.rejects(stat(path.join(dir2, THREAD_SHOT_FILENAME))); }); test("shot: with nothing above it there is no thread shot, and nothing is shot or blurred", async () => { const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xthread-")), "1"); const p = threadPage({ snap: { own: 0, articles: [art("1", "TheQuartering", 0, 300)] } }); const res = await shootXThread(p, "1", dir, {}); assert.ok("none" in res); assert.equal(p.shots.length, 0); assert.ok(!p.calls.includes("redact")); }); test("shot: a page that cannot be measured in its window shoots the union from a full-page clip", async () => { const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xthread-")), "1"); const p = threadPage({ windowed: false }); const inner = p.evaluate; p.evaluate = async (s: string) => s.includes("window.scrollX") && s.includes("data-archilyzer-thread-parent") && !s.includes(REDACTED_BOXES_MARKER) ? [ { x: 283, y: 1000, width: 598, height: 220 }, { x: 283, y: 1220, width: 598, height: 280 }, ] : inner(s); const res = await shootXThread(p, "1", dir, { replyTo: { id: "2114113495989907691" } }); assert.ok("thread" in res, JSON.stringify(res)); assert.deepEqual(p.shots, [{ type: "png", fullPage: true, clip: { x: 283, y: 1000, width: 598, height: 500 } }]); }); // --- the run --------------------------------------------------------------------- function deps(p: PageLike, opened: { n: number }): XCaptureDeps { return { openPage: async () => { opened.n++; return { page: p, close: async () => {} }; }, downloadMedia: async () => ({ ok: true, files: [] }), pauseMs: () => 5_000, pause: async () => {}, now: () => new Date("2026-10-27T12:00:00.000Z"), }; } test("run: thread on — the post's own shot, then the thread shot in the same load, both recorded", async () => { const outDir = await mkdtemp(path.join(os.tmpdir(), "posts-media-")); const p = threadPage(); const opened = { n: 0 }; const id = "2114214000653414579"; const res = await captureXPosts( { ids: [id], handle: "TheQuartering", outDir, media: false, thread: true, archived: new Map([[id, { text: "@Toothless2210 Well..", isReply: true, replyTo: { id: "2114113495989907691", author: "Toothless2210" }, author: "TheQuartering" }]]), signal: new AbortController().signal, }, deps(p, opened), ); assert.deepEqual(res.outcomes, [{ id, state: "captured", availability: "available", files: 2 }]); assert.equal(p.calls.filter((c) => c.startsWith("goto")).length, 1, "one page load for both shots"); const rec = (await readPostCapture(path.join(outDir, id)))!; assert.equal(rec.shot?.name, SHOT_FILENAME); assert.equal(rec.thread?.name, THREAD_SHOT_FILENAME); assert.equal(rec.thread?.parentId, "2114113495989907691"); assert.equal(rec.thread?.redaction.applied, true); // The own shot was taken before anything was blurred. const firstShot = p.calls.indexOf("measure-own"); assert.ok(firstShot >= 0 && firstShot < p.calls.indexOf("redact")); }); test("run: a post shot before gets only its thread shot; a post the archive says is no reply gets no page load", async () => { const outDir = await mkdtemp(path.join(os.tmpdir(), "posts-media-")); const id = "2114214000653414579"; const plain = "2091829122808832397"; for (const pid of [id, plain]) { await writePostCapture(path.join(outDir, pid), { version: 1, id: pid, url: `https://x.com/i/status/${pid}`, capturedAt: "2026-10-20T00:00:00.000Z", state: "captured", shot: { name: SHOT_FILENAME, bytes: 5, sha256: "old" }, mediaState: "none", media: [], }); } const p = threadPage(); const opened = { n: 0 }; const res = await captureXPosts( { ids: [plain, id], handle: "TheQuartering", outDir, thread: true, archived: new Map([ [plain, { text: "Up all night.", isReply: false }], [id, { text: "@Toothless2210 Well..", isReply: true, replyTo: { id: "2114113495989907691" } }], ]), signal: new AbortController().signal, }, deps(p, opened), ); assert.deepEqual(res.outcomes.map((o) => [o.id, o.availability]), [ [plain, undefined], [id, undefined], ]); assert.equal(p.calls.filter((c) => c.startsWith("goto")).length, 1, "only the reply's page is opened"); assert.ok(!p.calls.includes("measure-own"), "the post's own shot is not taken again"); const r = (await readPostCapture(path.join(outDir, id)))!; assert.equal(r.shot?.sha256, "old", "shot.png is kept"); assert.equal(r.thread?.parentId, "2114113495989907691"); const n = (await readPostCapture(path.join(outDir, plain)))!; assert.match(n.threadNone ?? "", /Not a reply/); // Settled: the next run owes neither. const again = threadPage(); await captureXPosts({ ids: [plain, id], handle: "TheQuartering", outDir, thread: true, signal: new AbortController().signal }, deps(again, { n: 0 })); assert.equal(again.calls.length, 0); });