commit 9d8fd941515c01c695d2e8ea6cb35a69e791c391
parent 579d45e4c4f313f4383e3a6f71e102acb3887a7a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 22:19:40 -0500
Merge lane/post-threads-avatars: capture-posts keeps X authors' avatars -- read off the post page it already loads (the parent's and quoted author's with thread on), fetched at 400x400 through the same browser context, stored in the channel's posts-media/_avatars/ with avatars.json; avatarsOnly captures one page per author
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
25 files changed, 1633 insertions(+), 31 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -146,7 +146,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. A record that stores an Odysee media URL is read from that URL (as "only") until 2 such downloads are on record, then from the page. "storedUrl": "fallback" \| "only" reads each from the media URL its record stores, as on download-missing (a held platform's retry runs as "only"). "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` |
| `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | |
| `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"}. "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). A forum thread keeps two positions: a run catches up from the last page, then continues the history where it stopped; "full": true is its full re-walk (every page, edits updated). "retryOnBlock": {"minutes": 30, "max": 12} (or true: the forum default in settings) waits out a challenge or refusal page and runs again, max tries in all. "full" and "older" together are refused. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. A drained fetch stops at its next resume point and the next run resumes. | |
-| `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/<id>/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. "thread": true (X; default the channel's postCaptureThread) also shoots each reply with the post it answers above it, as shot-thread.png beside shot.png (a post shot before gets only that); the replied-to author's avatar, name and handle are blurred unless verified or the reply's own. "threadRedact": false turns the blur off, true blurs any author; {"<id>": false} sets it per post. Paced like a post fetch, on its queue. | |
+| `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/<id>/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. "thread": true (X; default the channel's postCaptureThread) also shoots each reply with the post it answers above it, as shot-thread.png beside shot.png (a post shot before gets only that); the replied-to author's avatar, name and handle are blurred unless verified or the reply's own. "threadRedact": false turns the blur off, true blurs any author; {"<id>": false} sets it per post. X also keeps each author's avatar, read off the page the shot loads (with "thread", the replied-to and quoted authors' too), in posts-media/\_avatars/<handle>.<ext> + avatars.json; an author already stored is not fetched again unless "force". "avatars": false turns that off. "avatarsOnly": true (X) loads ONE post page per distinct archived author for the avatars alone -- no shot, media, article or thread shot, no capture record, no availability: one author's avatar is {"slug", "ids": \["<one of their post ids>"\], "avatarsOnly": true}. Paced like a post fetch, on its queue. | |
| `publish` | publish runs publish stages on the editor's publish queue, one at a time, under one run id: {"verb": …}. "index" updates the index; "build" builds "siteId"/"siteIds" (forced; the index first when stale; "runner": "docker" builds every site in containers; "allowMissingMedia": true lets a report citation with no prepared media through compose, local builds only); "deploy" ships their built bundles (production, "preview": "<branch>", or "to": "local"; "force" redeploys a bundle already shipped there); "hub" / "homepage" build them, {"deploy": true} deploys after; "now" is Publish now (the stale index, then each policy target); "stale" builds every stale site. The answer lists every job ({target, kind, jobId}) and --wait follows them all. A site never built is refused: "no build of <id> in <dir> — archilyzer publish build <id>". `get publish` is the status. | |
| `build-index`, `build-site`, `build-deploy`, `deploy-site`, `build-hub`, `deploy-hub`, `build-homepage`, `deploy-homepage` | build-index, build-site, build-deploy, deploy-site, build-hub, deploy-hub, build-homepage and deploy-homepage are publish's aliases, with their old bodies and answers ("skipData" is accepted and ignored). | `pnpm ops build-deploy --json '{"siteIds":["anilyzer","jeralyzer"]}' --wait`<br>`pnpm ops build-site --json '{"siteId":"anilyzer"}' --wait`<br>`pnpm ops deploy-site --json '{"siteId":"anilyzer","preview":"tags-exclude"}' --wait`<br>`pnpm ops build-hub --wait`<br>`pnpm ops build-hub --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-hub --wait`<br>`pnpm ops build-homepage --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-homepage --json '{"preview":"refresh"}' --wait` |
| `build-site`, `build-deploy`, `deploy-site` | build-site, build-deploy and deploy-site all take "siteId" (one) or "siteIds" (a list). | |
diff --git a/OPERATING.md b/OPERATING.md
@@ -408,6 +408,27 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait
pnpm ops capture-posts --json '{"slug":"example-x-replies","ids":["<postId>"],"thread":true}' --wait
umtool posts set <project> <postId> thread=on
```
+- **Authors' avatars (X).** A post card draws its author's face from the channel's avatar store, not an initial
+ letter. Every X capture that loads a post page reads the author's avatar off it (with `"thread": true`, the
+ replied-to and quoted authors' too) and fetches it at 400×400 through the same browser context — no extra page
+ load; once per author per run, and an author already stored is not fetched again unless `"force": true`.
+ `"avatars": false` turns that off. For the avatars alone, `"avatarsOnly": true` loads ONE post page per distinct
+ archived author (the first id of each; one already stored costs no load unless `"force"`), paced like any X
+ contact, and writes nothing else — no shot, media, article, thread shot, `capture.json` or availability. One
+ author's avatar is one page load:
+
+ ```sh
+ pnpm ops capture-posts --json '{"slug":"ObviousRises-x","ids":["<one of his post ids>"],"avatarsOnly":true}' --wait
+ ```
+
+ The store, beside the post ids (never one of them):
+
+ ```
+ channels/<slug>/posts-media/_avatars/<handle>.<ext> # jpg | png | webp | gif
+ channels/<slug>/posts-media/_avatars/avatars.json # { "<handle>": { "file", "url" (the _400x400), "capturedAt", "postId" } }
+ ```
+
+ Keys keep the handle's case as X prints it; lookups ignore case. X's default "egg" picture is not stored.
- A **forum thread** keeps two positions (`posts-state.json` `forum`): **Fetch posts** catches up from the last page
to the newest held post, then continues the history from where it stopped, down to page 1 — `"pages": N` caps
the pages that hold anything new (an all-held page is stepped past uncounted), and a capped catch-up never moves
diff --git a/common/controller/capturePosts.test.ts b/common/controller/capturePosts.test.ts
@@ -352,3 +352,64 @@ test("a Wayback pages channel: its records rendered from their captures, no fetc
"1 id(s) not in demo-pages's posts archive: nope",
);
});
+
+test("avatars (X): on by default, off by word; avatarsOnly is its own run, X's only, archived authors passed, nothing recorded", async () => {
+ const root = path.join(channelsDir, "demo-x-avatars");
+ await mkdir(root, { recursive: true });
+ await writeFile(
+ path.join(root, "config.json"),
+ JSON.stringify({
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "twitter",
+ postFetcher: "test-capture-x",
+ socialHandle: "example_user",
+ name: "Example (X avatars)",
+ url: "https://x.com/example_user",
+ }),
+ );
+ const base = {
+ channelSlug: "demo-x-avatars", createdAt: "2026-10-25T04:34:32.000Z", uploadDate: "20261025",
+ platform: "twitter" as const, isRepost: false, isReply: false, links: [],
+ };
+ await writePosts(root, [
+ { ...base, id: "601", slug: "demo-x-avatars/601", author: "ObviousRises", text: "a", url: "https://x.com/ObviousRises/status/601" },
+ { ...base, id: "602", slug: "demo-x-avatars/602", author: "someone_else", text: "b", url: "https://x.com/someone_else/status/602" },
+ ]);
+
+ // A normal run: the fetcher's default (on), or the run's word.
+ calls = [];
+ answer = { outcomes: [] };
+ await run("demo-x-avatars", ["601"], { articles: false });
+ assert.equal(calls[0].avatars, undefined);
+ assert.equal(calls[0].avatarsOnly, undefined);
+ calls = [];
+ await run("demo-x-avatars", ["601"], { articles: false, avatars: false });
+ assert.equal(calls[0].avatars, false);
+
+ // avatarsOnly: a run even with both halves off; each id's archived author
+ // goes with it; an outcome the fetcher (wrongly) returns is not recorded.
+ calls = [];
+ answer = {
+ outcomes: [{ id: "601", state: "deleted", availability: { state: "deleted", checkedAt: "x" } as never, files: 0 }],
+ avatars: { stored: ["ObviousRises"], skipped: [], failed: [], pages: 1 },
+ };
+ const res = await run("demo-x-avatars", ["601", "602"], { avatarsOnly: true, shots: false, media: false, articles: false });
+ assert.equal(res.ok, true);
+ assert.deepEqual(res.outcomes, []);
+ assert.deepEqual(res.avatars?.stored, ["ObviousRises"]);
+ assert.equal(calls[0].avatarsOnly, true);
+ assert.equal(calls[0].archived?.get("601")?.author, "ObviousRises");
+ assert.equal(calls[0].archived?.get("602")?.author, "someone_else");
+ assert.deepEqual(await readPostAvailability(root), {});
+
+ // Another platform keeps none: refused by name, before the fetcher.
+ await makeChannel("demo-social-avatars");
+ calls = [];
+ assert.equal(
+ (await run("demo-social-avatars", ["aaa"], { avatarsOnly: true })).error,
+ "Avatars are X's only; Test capture keeps none.",
+ );
+ assert.equal(calls.length, 0);
+ answer = { outcomes: [] };
+});
diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts
@@ -13,6 +13,11 @@
// of the archive, and an id from somewhere else is refused by name. Each id's
// archived text and links go to the fetcher with it, so a post that is an X
// Article's link is known as one before its page is opened.
+//
+// X also keeps the posts' AUTHORS' AVATARS, read off the page the shot loads,
+// in `posts-media/_avatars/` (social/xAvatars.ts has the store): on by
+// default (`avatars: false` turns it off), and `avatarsOnly` loads one page
+// per archived author for that alone, recording nothing about the posts.
import path from "node:path";
import { isXSearchChannel } from "../lib/xSearch/config";
@@ -39,6 +44,7 @@ import {
type SocialFetcher,
} from "../social/fetchers";
import { postsMediaDir } from "../social/postCapture";
+import type { XAvatarRunSummary } from "../social/xAvatarCapture";
import { isWaybackPagesChannel } from "../lib/waybackPages/config";
import {
captureWaybackPageRecords,
@@ -74,6 +80,11 @@ export type CapturePostsOptions = {
// The thread shot's blur of the parent's author (xThreadShot.ts): absent
// is the rule, false off, true always -- for the run or per post id.
threadRedact?: ThreadRedactKnob;
+ // X: save the authors' avatars from the pages the shots load (default
+ // true), or ONLY them -- one page per distinct archived author, no shot,
+ // media, article or thread shot, no capture record, no availability.
+ avatars?: boolean;
+ avatarsOnly?: boolean;
onLog?: (line: string) => void;
signal?: AbortSignal;
// The job's drain: stop between posts.
@@ -88,6 +99,8 @@ export type CapturePostsResult = {
outcomes: PostCaptureOutcome[];
needsCookies?: boolean;
error?: string;
+ // X: what the run did about avatars, when it did anything.
+ avatars?: XAvatarRunSummary;
};
// Why this fetcher cannot capture posts, or null when it can. Shared with the
@@ -105,16 +118,24 @@ export const NOTHING_TO_CAPTURE =
'Nothing to capture: both the screenshot and the media are turned off (to read only the articles, ask for "articles": true; only the thread shots, "thread": true).';
// Both halves off is nothing to do — unless the articles or the thread shots
-// were asked for by name: their defaults alone do not make a run.
+// were asked for by name: their defaults alone do not make a run. An
+// avatars-only run is a run of its own, whatever the halves say.
export function nothingToCapture(o: {
shots?: boolean;
media?: boolean;
articles?: boolean;
thread?: boolean;
+ avatarsOnly?: boolean;
}): boolean {
+ if (o.avatarsOnly === true) return false;
return o.shots === false && o.media === false && o.articles !== true && o.thread !== true;
}
+// The refusal for avatars asked of a platform that keeps none.
+export function avatarsOnlyProblem(platform: string | undefined, label: string): string | null {
+ return platform === "twitter" ? null : `Avatars are X's only; ${label} keeps none.`;
+}
+
// The thread shot's blur knob as a caller wrote it: a boolean for the run, or
// { "<post id>": boolean }. Returns the knob, or the sentence refusing it.
export type ThreadRedactKnob = boolean | Record<string, boolean>;
@@ -163,12 +184,20 @@ export async function capturePosts(
// A Wayback pages channel (release 37 S4): no fetcher — each record is
// rendered from its capture's replay, its images from the archive.
- if (isWaybackPagesChannel(config)) return captureChannelPageRecords(opts, channelRoot, ids);
+ if (isWaybackPagesChannel(config)) {
+ if (opts.avatarsOnly) return fail(avatarsOnlyProblem(undefined, "a Wayback pages channel")!);
+ return captureChannelPageRecords(opts, channelRoot, ids);
+ }
const accountUrl = config.url ?? "";
const fetcher = resolveSocialFetcher(config.postFetcher, accountUrl);
const problem = capturePostsProblem(fetcher);
if (problem || !fetcher?.captureByIds) return fail(problem ?? "This channel has no post fetcher.");
+ const avatarsOnly = opts.avatarsOnly === true;
+ if (avatarsOnly) {
+ const nope = avatarsOnlyProblem(fetcher.platform, fetcher.label);
+ if (nope) return fail(nope);
+ }
// An X search channel has no account (release 38): its posts are any
// author's, and the X capture opens each by its status id alone.
@@ -196,7 +225,7 @@ export async function capturePosts(
let archived: Map<string, Archived> | undefined;
const forum = fetcher.platform === "xenforo";
const bluesky = fetcher.platform === "bluesky";
- if ((opts.articles !== false && fetcher.platform === "twitter") || thread || forum || bluesky) {
+ if ((opts.articles !== false && fetcher.platform === "twitter") || thread || forum || bluesky || avatarsOnly) {
const wanted = new Set(ids);
archived = new Map();
for (const p of await readAllPosts(channelRoot)) {
@@ -207,6 +236,8 @@ export async function capturePosts(
...(forum ? { url: p.url, ...(p.media ? { media: p.media } : {}) } : {}),
// Bluesky looks each post up under its own author (a repost's is the original's).
...(bluesky ? { url: p.url, author: p.author } : {}),
+ // An avatars-only run loads one page per author.
+ ...(avatarsOnly ? { author: p.author } : {}),
// The thread shot tells the parent by the id the reply answers.
...(thread
? {
@@ -225,13 +256,21 @@ export async function capturePosts(
? await resolveXCookieSourceFor(paths, settings, policy.cookies)
: undefined;
- log(
+ if (avatarsOnly) {
+ log(
+ `Capturing the authors' avatars of ${ids.length} post(s) of ${slug} via ${fetcher.label}` +
+ (thread ? " (with the replied-to and quoted authors')" : "") +
+ (opts.force ? ", again where already stored" : "") +
+ ".",
+ );
+ } else log(
`Capturing ${ids.length} post(s) of ${slug} via ${fetcher.label} (@${handle}):` +
[
opts.shots === false ? "" : " screenshot",
opts.media === false ? "" : " media",
opts.articles === false || fetcher.platform !== "twitter" ? "" : " articles",
thread ? ` thread shots${opts.threadRedact === false ? " (no blur)" : ""}` : "",
+ fetcher.platform === "twitter" && opts.avatars !== false ? " avatars" : "",
].join("") +
(opts.force ? ", again where already captured" : "") +
".",
@@ -254,6 +293,8 @@ export async function capturePosts(
articles: opts.articles,
thread,
...(opts.threadRedact !== undefined ? { threadRedact: opts.threadRedact } : {}),
+ ...(opts.avatars !== undefined ? { avatars: opts.avatars } : {}),
+ ...(avatarsOnly ? { avatarsOnly: true } : {}),
archived,
cookies: alwaysCookies(policy),
cookieSource: xLogin?.source,
@@ -268,6 +309,17 @@ export async function capturePosts(
return fail(message);
}
+ const avatars = result.avatars ? { avatars: result.avatars } : {};
+ if (avatarsOnly) {
+ // Nothing about the posts was learned or written: no sidecar, no records.
+ if (result.needsCookies) {
+ return { ok: false, outcomes: [], needsCookies: true, error: result.stoppedEarly ?? "The capture needs an X login.", ...avatars };
+ }
+ const stoppedByOperator = (opts.signal ?? controller.signal).aborted || Boolean(opts.drain?.aborted);
+ if (result.stoppedEarly && !stoppedByOperator) return { ok: false, outcomes: [], error: result.stoppedEarly, ...avatars };
+ return { ok: true, outcomes: [], ...avatars };
+ }
+
// What the pages said about each post, folded into the sidecar.
const observations = new Map<string, PostAvailability>();
for (const o of result.outcomes) {
@@ -302,6 +354,7 @@ export async function capturePosts(
ok: false,
outcomes: result.outcomes,
needsCookies: true,
+ ...avatars,
error:
result.stoppedEarly ??
(forum ? "The capture needs the forum session (Connect)." : "The capture needs an X login."),
@@ -310,9 +363,9 @@ export async function capturePosts(
const stoppedByOperator =
(opts.signal ?? controller.signal).aborted || Boolean(opts.drain?.aborted);
if (result.stoppedEarly && !stoppedByOperator) {
- return { ok: false, outcomes: result.outcomes, error: result.stoppedEarly };
+ return { ok: false, outcomes: result.outcomes, error: result.stoppedEarly, ...avatars };
}
- return { ok: true, outcomes: result.outcomes };
+ return { ok: true, outcomes: result.outcomes, ...avatars };
}
// capture-posts on a Wayback pages channel: the records' shots from their
diff --git a/common/lib/report/draft/research/tools.ts b/common/lib/report/draft/research/tools.ts
@@ -128,10 +128,10 @@ export const ACTION_SPECS: Record<AcquisitionAction, ActionSpec> = {
action: "capture-posts",
editorAction: "capture-posts",
description:
- "Capture archived posts of a social channel: a screenshot and the attached media of each id; thread: an X reply also shot with the post it answers above it (shot-thread.png, the replied-to author blurred unless verified).",
- properties: { slug: str, ids: strList, shots: bool, media: bool, articles: bool, thread: bool },
+ "Capture archived posts of a social channel: a screenshot and the attached media of each id; thread: an X reply also shot with the post it answers above it (shot-thread.png, the replied-to author blurred unless verified); X keeps each author's avatar (posts-media/_avatars/); avatarsOnly: only the avatars, one page per author.",
+ properties: { slug: str, ids: strList, shots: bool, media: bool, articles: bool, thread: bool, avatarsOnly: bool },
required: ["slug", "ids"],
- body: (a) => pick(a, ["slug", "ids", "shots", "media", "articles", "thread"]),
+ body: (a) => pick(a, ["slug", "ids", "shots", "media", "articles", "thread", "avatarsOnly"]),
},
"import-post": {
action: "import-post",
diff --git a/common/social/__fixtures__/x-avatar-quoted_400x400.jpg b/common/social/__fixtures__/x-avatar-quoted_400x400.jpg
Binary files differ.
diff --git a/common/social/__fixtures__/x-avatar_400x400.jpg b/common/social/__fixtures__/x-avatar_400x400.jpg
Binary files differ.
diff --git a/common/social/__fixtures__/x-avatar_normal.jpg b/common/social/__fixtures__/x-avatar_normal.jpg
Binary files differ.
diff --git a/common/social/__fixtures__/x-post-avatars.html b/common/social/__fixtures__/x-post-avatars.html
@@ -0,0 +1,104 @@
+<!doctype html>
+<!-- An X status page as X draws it (2026-11), cut to what the capture reads:
+ the reply's parent above it, the post itself (its author's avatar, a
+ quoted post's card with its own avatar), and a reply under it. Every
+ picture is on {{ORIGIN}}, the test's loopback server, at X's
+ profile_images path. Recorded-style, hand-trimmed; no live X. -->
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Mr. Obvious on X</title>
+<style>
+ body { margin: 0; background: #000; color: #e7e9ea; font: 15px/20px system-ui, sans-serif; }
+ [data-testid="primaryColumn"] { width: 600px; margin: 0 auto; border-left: 1px solid #2f3336; border-right: 1px solid #2f3336; }
+ article { display: flex; gap: 12px; padding: 12px 16px; border-bottom: 1px solid #2f3336; }
+ [data-testid="Tweet-User-Avatar"] { flex: none; width: 40px; }
+ [data-testid^="UserAvatar-Container-"] { width: 40px; height: 40px; border-radius: 9999px; overflow: hidden; position: relative; }
+ [data-testid^="UserAvatar-Container-"] img { width: 100%; height: 100%; display: block; }
+ .bg { position: absolute; inset: 0; background-size: cover; }
+ .body { flex: 1; min-width: 0; }
+ [data-testid="User-Name"] a { color: inherit; text-decoration: none; }
+ .handle, time { color: #71767b; }
+ .quote { margin-top: 12px; border: 1px solid #2f3336; border-radius: 16px; padding: 12px; }
+ .quote [data-testid^="UserAvatar-Container-"] { width: 20px; height: 20px; display: inline-block; vertical-align: middle; }
+</style>
+</head>
+<body>
+<main role="main">
+<div data-testid="primaryColumn">
+ <section aria-labelledby="accessible-list-1" role="region">
+ <div aria-label="Timeline: Conversation">
+
+ <article aria-labelledby="id-p" role="article" tabindex="0" data-testid="tweet">
+ <div data-testid="Tweet-User-Avatar">
+ <div data-testid="UserAvatar-Container-parent_person">
+ <a href="/parent_person" role="link" tabindex="-1">
+ <div class="bg" style="background-image: url("{{ORIGIN}}/profile_images/777/pp_normal.jpg");"></div>
+ <img alt="" draggable="true" src="{{ORIGIN}}/profile_images/777/pp_normal.jpg">
+ </a>
+ </div>
+ </div>
+ <div class="body">
+ <div data-testid="User-Name">
+ <a href="/parent_person" role="link"><span>A Private Person</span></a>
+ <a href="/parent_person" role="link" tabindex="-1"><span class="handle">@parent_person</span></a>
+ <a href="/parent_person/status/1849999999999999990" role="link"><time datetime="2026-10-30T12:00:00.000Z">Oct 30</time></a>
+ </div>
+ <div data-testid="tweetText" lang="en"><span>So what happened next?</span></div>
+ </div>
+ </article>
+
+ <article aria-labelledby="id-o" role="article" tabindex="-1" data-testid="tweet">
+ <div data-testid="Tweet-User-Avatar">
+ <div data-testid="UserAvatar-Container-ObviousRises">
+ <a href="/ObviousRises" role="link" tabindex="-1">
+ <div class="bg" style="background-image: url("{{ORIGIN}}/profile_images/1712345678901234567/Mr_O_normal.jpg");"></div>
+ <img alt="" draggable="true" src="{{ORIGIN}}/profile_images/1712345678901234567/Mr_O_normal.jpg">
+ </a>
+ </div>
+ </div>
+ <div class="body">
+ <div data-testid="User-Name">
+ <a href="/ObviousRises" role="link"><span>Mr. Obvious</span></a>
+ <a href="/ObviousRises" role="link" tabindex="-1"><span class="handle">@ObviousRises</span></a>
+ <a href="/ObviousRises/status/1850000000000000001" role="link"><time datetime="2026-10-31T09:00:00.000Z">9:00 AM · Oct 31, 2026</time></a>
+ </div>
+ <div><span class="handle">Replying to </span><a href="/parent_person" role="link">@parent_person</a></div>
+ <div data-testid="tweetText" lang="en"><span>It is obvious, and here is the receipt.</span></div>
+ <div class="quote" role="link" tabindex="0">
+ <div data-testid="User-Name">
+ <div data-testid="UserAvatar-Container-quoted_person">
+ <div class="bg" style="background-image: url("{{ORIGIN}}/profile_images/888/qq_mini.jpg");"></div>
+ <img alt="" draggable="true" src="{{ORIGIN}}/profile_images/888/qq_mini.jpg">
+ </div>
+ <span>Quoted Person</span> <span class="handle">@quoted_person · Oct 29</span>
+ </div>
+ <div data-testid="tweetText" lang="en"><span>The receipt itself.</span></div>
+ </div>
+ <div role="group" aria-label="3 replies, 5 reposts, 40 likes"><button data-testid="reply" type="button"><span>3</span></button></div>
+ </div>
+ </article>
+
+ <article aria-labelledby="id-r" role="article" tabindex="0" data-testid="tweet">
+ <div data-testid="Tweet-User-Avatar">
+ <div data-testid="UserAvatar-Container-a_replier">
+ <a href="/a_replier" role="link" tabindex="-1">
+ <img alt="" draggable="true" src="{{ORIGIN}}/profile_images/999/rr_normal.jpg">
+ </a>
+ </div>
+ </div>
+ <div class="body">
+ <div data-testid="User-Name">
+ <a href="/a_replier" role="link"><span>Someone Replying</span></a>
+ <a href="/a_replier/status/1850000000000000009" role="link"><time datetime="2026-10-31T10:00:00.000Z">Oct 31</time></a>
+ </div>
+ <div data-testid="tweetText" lang="en"><span>A reply under the post: never read.</span></div>
+ </div>
+ </article>
+
+ </div>
+ </section>
+</div>
+</main>
+</body>
+</html>
diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts
@@ -18,6 +18,7 @@ import type { OlderBackfillPosition } from "../lib/posts-server";
import type { ForumWalkState } from "../lib/forumWalk";
import type { XCookieSource } from "./xCookieSource";
import type { PostCaptureState } from "./postCapture";
+import type { XAvatarRunSummary } from "./xAvatarCapture";
export type PostFetchInput = {
// The account's canonical URL as configured on the channel.
@@ -255,6 +256,15 @@ export type PostCaptureInput = Pick<
// (blurred unless verified or the reply's own), false off, true always --
// for the whole run, or per post id (an id not named takes the rule).
threadRedact?: boolean | Readonly<Record<string, boolean>>;
+ // X: read the post author's avatar off the page the shot loads (and, with
+ // the thread on, the parent's and the quoted post's authors'), into
+ // `<outDir>/_avatars/` (xAvatars.ts). Defaults to true; an author already
+ // stored is not fetched again unless `force`.
+ avatars?: boolean;
+ // X: ONLY the avatars — one post page per distinct archived author, no
+ // shot, no media, no article, no thread shot, and no capture record or
+ // availability observation written. Defaults to false.
+ avatarsOnly?: boolean;
// What the posts archive holds for each id — its text and expanded links —
// for the links a capture follows (an X Article's). Ids absent are read
// from the page alone.
@@ -300,6 +310,8 @@ export type PostCaptureResult = {
// Why the run stopped before its last id, when it did. The ids after it are
// left for a later run — never retried in this one.
stoppedEarly?: string;
+ // X: what the run did about avatars, when it did anything.
+ avatars?: XAvatarRunSummary;
};
// Input for importing ONE post by its URL (`SocialFetcher.fetchOne`, release
diff --git a/common/social/postCapture.ts b/common/social/postCapture.ts
@@ -30,6 +30,7 @@ import { readdir, stat } from "node:fs/promises";
import path from "node:path";
import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server";
import type { PostAvailability } from "../lib/posts";
+import { AVATARS_DIRNAME } from "./xAvatars";
export const POSTS_MEDIA_DIRNAME = "posts-media";
export const CAPTURE_FILENAME = "capture.json";
@@ -56,9 +57,10 @@ export function postsMediaDir(channelRoot: string): string {
// One post's capture directory. The id is checked here, at the one place a
// post id becomes a path: a platform-native id is digits (X) or a short
-// alphanumeric key (Bluesky), never a separator.
+// alphanumeric key (Bluesky), never a separator. `_avatars` is the authors'
+// pictures beside them (xAvatars.ts), never a post.
export function postCaptureDir(outDir: string, id: string): string {
- if (!/^[A-Za-z0-9_-]{1,64}$/.test(id)) {
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(id) || id === AVATARS_DIRNAME) {
throw new Error(`"${id}" is not a post id`);
}
return path.join(outDir, id);
diff --git a/common/social/xAvatarCapture.browser.test.ts b/common/social/xAvatarCapture.browser.test.ts
@@ -0,0 +1,237 @@
+// The avatar read and download in a REAL headless Chromium, against a
+// recorded-style X status page (__fixtures__/x-post-avatars.html) — never
+// x.com. The browser's every request to x.com is answered by the fixture
+// through the context's router, anything else not on the test's loopback
+// server is aborted, and the host resolver maps every other name to nowhere,
+// so nothing can leave the machine. The pictures are served by a loopback
+// server at X's profile_images path.
+//
+// What it proves: the read finds the author's, the quoted post's and the
+// parent's avatars in X's markup; the download is the _400x400 size, fetched
+// ONCE per author through the page's own request context (it carries the
+// context's cookie), with no second page load and the page left where it was;
+// an avatars-only run writes no capture record; a normal run shoots the post
+// and reads the avatars from the same load.
+//
+// Skips where Playwright or its Chromium is not installed. With
+// AVATAR_PROOF_DIR set, it leaves a screenshot, the store and a log there.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xAvatarCapture.browser.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { cp, mkdir, mkdtemp, readdir, readFile, writeFile } from "node:fs/promises";
+import http from "node:http";
+import type { AddressInfo } from "node:net";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { importPlaywright, type PageLike } from "./playwrightRuntime";
+import { captureXPosts, type XCaptureDeps } from "./xPostCapture";
+import { AVATARS_DIRNAME, readXAvatarIndex } from "./xAvatars";
+import { SHOT_FILENAME } from "./postCapture";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIX = path.join(HERE, "__fixtures__");
+const POST_ID = "1850000000000000001";
+const PARENT_ID = "1849999999999999990";
+
+type Served = { path: string; cookie?: string; drawnByPage?: boolean };
+
+async function fixtureServer() {
+ const normal = await readFile(path.join(FIX, "x-avatar_normal.jpg"));
+ const big = await readFile(path.join(FIX, "x-avatar_400x400.jpg"));
+ const quoted = await readFile(path.join(FIX, "x-avatar-quoted_400x400.jpg"));
+ const served: Served[] = [];
+ const server = http.createServer((req, res) => {
+ const p = (req.url ?? "").split("?")[0];
+ served.push({
+ path: p,
+ ...(req.headers.cookie ? { cookie: req.headers.cookie } : {}),
+ ...(req.headers["x-drawn-by"] ? { drawnByPage: true } : {}),
+ });
+ const m = /^\/profile_images\/\d+\/([A-Za-z0-9_-]+?)_(normal|mini|400x400)\.jpg$/.exec(p);
+ if (!m) {
+ res.writeHead(404).end();
+ return;
+ }
+ const body = m[2] !== "400x400" ? normal : m[1] === "Mr_O" ? big : quoted;
+ res.writeHead(200, { "content-type": "image/jpeg", "content-length": body.length }).end(body);
+ });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+ const html = (await readFile(path.join(FIX, "x-post-avatars.html"), "utf8")).replaceAll("{{ORIGIN}}", origin);
+ return { origin, html, served, close: () => new Promise<void>((r) => server.close(() => r())) };
+}
+
+type PwPage = PageLike & {
+ url: () => string;
+ mainFrame: () => unknown;
+ on: (event: "framenavigated", cb: (f: { url: () => string }) => void) => void;
+};
+
+test("in a real Chromium: the avatars read off a recorded-style X page and fetched through its own context", async (t) => {
+ let chromium;
+ try {
+ ({ chromium } = await importPlaywright());
+ } catch (err) {
+ t.skip(`Playwright is not installed here: ${(err as Error).message.slice(0, 80)}`);
+ return;
+ }
+ const fx = await fixtureServer();
+ let browser;
+ try {
+ browser = await chromium.launch({
+ headless: true,
+ // Nothing resolves but the loopback server: x.com is answered by the router.
+ args: ["--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1"],
+ });
+ } catch (err) {
+ await fx.close();
+ t.skip(`Chromium would not launch: ${(err as Error).message.slice(0, 80)}`);
+ return;
+ }
+ const proofDir = process.env.AVATAR_PROOF_DIR;
+ const log: string[] = [];
+ const onLog = (line: string) => log.push(line);
+ try {
+ const context = (await browser.newContext({ viewport: { width: 1000, height: 900 } })) as unknown as {
+ newPage: () => Promise<PwPage>;
+ route: (url: string, handler: (route: Route) => Promise<void>) => Promise<void>;
+ addCookies: (c: Record<string, unknown>[]) => Promise<void>;
+ close: () => Promise<void>;
+ };
+ type Route = {
+ request: () => { url: () => string; resourceType: () => string };
+ fulfill: (o: Record<string, unknown>) => Promise<void>;
+ continue: () => Promise<void>;
+ abort: () => Promise<void>;
+ };
+ const docLoads: string[] = [];
+ const blocked: string[] = [];
+ await context.route("**/*", async (route) => {
+ const u = new URL(route.request().url());
+ if (u.hostname === "x.com") {
+ docLoads.push(u.pathname);
+ await route.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fx.html });
+ } else if (u.hostname === "127.0.0.1" && u.port === new URL(fx.origin).port) {
+ // The page's own pictures. An https page's http image is mixed
+ // content Chromium upgrades to https, which the loopback server does
+ // not speak: answered from it here, so the page draws them.
+ const r = await fetch(`${fx.origin}${u.pathname}${u.search}`, { headers: { "x-drawn-by": "page" } });
+ await route.fulfill({
+ status: r.status,
+ contentType: r.headers.get("content-type") ?? "application/octet-stream",
+ body: Buffer.from(await r.arrayBuffer()),
+ });
+ } else {
+ blocked.push(u.href);
+ await route.abort();
+ }
+ });
+ // The profile's cookie, as the live context carries X's: the download
+ // must arrive with it.
+ await context.addCookies([{ name: "auth_token", value: "fixture-session", domain: "127.0.0.1", path: "/" }]);
+ const page = await context.newPage();
+ const navs: string[] = [];
+ page.on("framenavigated", (f) => {
+ if (f === page.mainFrame()) navs.push(f.url());
+ });
+
+ const out = path.join(await mkdtemp(path.join(os.tmpdir(), "xavatar-browser-")), "posts-media");
+ const deps: XCaptureDeps = {
+ openPage: async () => ({ page, close: async () => {} }),
+ downloadMedia: async () => ({ ok: true, files: [] }),
+ pauseMs: () => 0,
+ pause: async () => {},
+ };
+ const archived = new Map([
+ [POST_ID, { text: "", author: "ObviousRises", isReply: true, replyTo: { id: PARENT_ID, author: "parent_person" } }],
+ ]);
+
+ // 1. avatarsOnly, thread on: the author's, the quoted post's and the parent's.
+ const res = await captureXPosts(
+ { ids: [POST_ID], handle: "ObviousRises", outDir: out, signal: new AbortController().signal, avatarsOnly: true, thread: true, archived, onLog },
+ deps,
+ );
+ assert.deepEqual(res.outcomes, []);
+ assert.deepEqual(res.avatars?.stored, ["ObviousRises", "quoted_person", "parent_person"], log.join("\n"));
+ assert.deepEqual(res.avatars?.failed, []);
+ // One page load, and the page is where it was.
+ assert.deepEqual(docLoads, [`/i/status/${POST_ID}`]);
+ assert.deepEqual(navs, [`https://x.com/i/status/${POST_ID}`]);
+ assert.equal(page.url(), `https://x.com/i/status/${POST_ID}`);
+ assert.deepEqual(blocked, []);
+ // Each author's 400×400, once, through the context (its cookie on it).
+ const bigs = fx.served.filter((s) => s.path.endsWith("_400x400.jpg"));
+ assert.deepEqual(
+ bigs.map((s) => s.path).sort(),
+ [
+ "/profile_images/1712345678901234567/Mr_O_400x400.jpg",
+ "/profile_images/777/pp_400x400.jpg",
+ "/profile_images/888/qq_400x400.jpg",
+ ],
+ );
+ for (const s of bigs) assert.match(s.cookie ?? "", /auth_token=fixture-session/, s.path);
+ // Not one of them is a picture the page drew: those are the small sizes.
+ assert.ok(bigs.every((s) => !s.drawnByPage));
+ assert.ok(fx.served.some((s) => s.drawnByPage && s.path.endsWith("Mr_O_normal.jpg")), "the page drew the 48px one");
+ // The reply under the post is never read.
+ assert.ok(!fx.served.some((s) => s.path.includes("rr_400x400")));
+ const store = path.join(out, AVATARS_DIRNAME);
+ const index = await readXAvatarIndex(store);
+ assert.deepEqual(Object.keys(index), ["ObviousRises", "parent_person", "quoted_person"]);
+ assert.equal(index.ObviousRises.url, `${fx.origin}/profile_images/1712345678901234567/Mr_O_400x400.jpg`);
+ assert.equal(index.ObviousRises.postId, POST_ID);
+ assert.deepEqual(
+ await readFile(path.join(store, "ObviousRises.jpg")),
+ await readFile(path.join(FIX, "x-avatar_400x400.jpg")),
+ "the stored picture is the 400×400, not the 48px one the page drew",
+ );
+ // No capture record: posts-media holds the store and nothing else.
+ assert.deepEqual(await readdir(out), [AVATARS_DIRNAME]);
+
+ // 2. A normal run on the same page: the shot, and the avatar already
+ // stored is not fetched again.
+ const before = fx.served.filter((s) => s.path.endsWith("_400x400.jpg")).length;
+ const res2 = await captureXPosts(
+ { ids: [POST_ID], handle: "ObviousRises", outDir: out, signal: new AbortController().signal, media: false, articles: false, onLog },
+ deps,
+ );
+ assert.equal(res2.outcomes[0]?.state, "captured", log.join("\n"));
+ assert.deepEqual(res2.avatars?.skipped, ["ObviousRises"]);
+ assert.equal(fx.served.filter((s) => s.path.endsWith("_400x400.jpg")).length, before);
+ assert.deepEqual(docLoads, [`/i/status/${POST_ID}`, `/i/status/${POST_ID}`]);
+ const shot = await readFile(path.join(out, POST_ID, SHOT_FILENAME));
+ assert.equal(shot.readUInt32BE(0), 0x89504e47);
+
+ if (proofDir) {
+ await mkdir(proofDir, { recursive: true });
+ await writeFile(path.join(proofDir, "fixture-page.png"), await page.screenshot({ type: "png", fullPage: true }));
+ await cp(path.join(out, POST_ID, SHOT_FILENAME), path.join(proofDir, "fixture-post-shot.png"));
+ await cp(store, path.join(proofDir, "_avatars"), { recursive: true });
+ await writeFile(
+ path.join(proofDir, "fixture-proof.log"),
+ [
+ `fixture origin: ${fx.origin} (x.com answered by the context router; everything else unresolvable)`,
+ `document loads (x.com): ${JSON.stringify(docLoads)}`,
+ `main-frame navigations: ${JSON.stringify(navs)}`,
+ `page.url() after the runs: ${page.url()}`,
+ `blocked requests: ${JSON.stringify(blocked)}`,
+ "served by the loopback server (path, cookie):",
+ ...fx.served.map(
+ (s) => ` ${s.path}${s.drawnByPage ? " [drawn by the page]" : ""}${s.cookie ? ` [cookie: ${s.cookie}]` : ""}`,
+ ),
+ `avatars.json: ${JSON.stringify(index, null, 2)}`,
+ "run log:",
+ ...log.map((l) => ` ${l}`),
+ "",
+ ].join("\n"),
+ );
+ }
+ await context.close();
+ } finally {
+ await browser.close();
+ await fx.close();
+ }
+});
diff --git a/common/social/xAvatarCapture.test.ts b/common/social/xAvatarCapture.test.ts
@@ -0,0 +1,269 @@
+// The avatar half of the X capture, against fakes only: a page that answers
+// the capture's evaluates (the post's snapshot, the avatar read) and serves
+// the picture through a fake request context. No browser, no network — the
+// in-page read itself is proved in a real Chromium by
+// xAvatarCapture.browser.test.ts.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xAvatarCapture.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readdir, readFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { PageLike } from "./playwrightRuntime";
+import { captureXPosts, type XCaptureDeps, type XPostSnapshot } from "./xPostCapture";
+import { AVATARS_SCRIPT_MARKER, avatarsScript, parseAvatarCandidates, type XAvatarCandidate } from "./xAvatarCapture";
+import { AVATARS_DIRNAME, readXAvatarIndex, writeXAvatar } from "./xAvatars";
+import { VIEW_SCRIPT_MARKER } from "./viewportShot";
+import type { PostCaptureInput } from "./fetchers";
+
+const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 9, 9]);
+const JPG = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 7]);
+const RECT = { x: 10, y: 120, width: 598, height: 300 };
+const snap = (id: string): XPostSnapshot => ({ path: `/someone/status/${id}`, text: "the post", article: { rect: RECT, sensitive: false } });
+const pic = (n: string) => `https://pbs.twimg.com/profile_images/${n}/face_normal.jpg`;
+
+type Fake = PageLike & { gotos: string[]; gets: string[]; reads: string[]; shots: number };
+
+// Each status page answers with its snapshot and the avatars `byId` names.
+function fakePage(byId: Record<string, XAvatarCandidate[]>): Fake {
+ let current = "";
+ const gotos: string[] = [];
+ const gets: string[] = [];
+ const reads: string[] = [];
+ const page: Fake = {
+ gotos,
+ gets,
+ reads,
+ shots: 0,
+ goto: async (url: string) => {
+ gotos.push(url);
+ current = /status\/(\d+)/.exec(url)?.[1] ?? "";
+ },
+ waitForSelector: async () => undefined,
+ waitForTimeout: async () => undefined,
+ on: () => {},
+ evaluate: async (script: string) => {
+ if (script.includes(AVATARS_SCRIPT_MARKER)) {
+ reads.push(script);
+ return byId[current] ?? [];
+ }
+ if (script.includes(VIEW_SCRIPT_MARKER)) return null;
+ if (script.includes("imgs.length")) return 0;
+ return snap(current);
+ },
+ screenshot: async () => {
+ page.shots++;
+ return PNG;
+ },
+ request: {
+ get: async (url: string) => {
+ gets.push(url);
+ return {
+ ok: () => true,
+ status: () => 200,
+ headers: () => ({ "content-type": "image/jpeg" }),
+ body: async () => JPG,
+ };
+ },
+ },
+ };
+ return page;
+}
+
+function deps(page: Fake, over: Partial<XCaptureDeps> = {}): XCaptureDeps & { pauses: number[]; opened: number } {
+ const d = {
+ pauses: [] as number[],
+ opened: 0,
+ openPage: async () => {
+ d.opened++;
+ return { page, close: async () => {} };
+ },
+ downloadMedia: async () => ({ ok: true as const, files: [] }),
+ pauseMs: () => 4000,
+ pause: async (ms: number) => {
+ d.pauses.push(ms);
+ },
+ now: () => new Date("2026-11-02T20:00:00.000Z"),
+ ...over,
+ };
+ return d;
+}
+
+async function outDir(): Promise<string> {
+ return path.join(await mkdtemp(path.join(os.tmpdir(), "xavatar-run-")), "posts-media");
+}
+
+const input = (out: string, ids: string[], over: Partial<PostCaptureInput> = {}): PostCaptureInput => ({
+ ids,
+ handle: "ObviousRises",
+ outDir: out,
+ signal: new AbortController().signal,
+ media: false,
+ articles: false,
+ ...over,
+});
+
+test("read: the script carries its marker and the archive's parent id; its answer is kept to the shape", () => {
+ const s = avatarsScript({ parent: true, quotes: true, parentId: "500" });
+ assert.ok(s.includes(AVATARS_SCRIPT_MARKER));
+ assert.ok(s.includes('"500"'));
+ assert.deepEqual(parseAvatarCandidates({ path: "/x" }), []);
+ assert.deepEqual(
+ parseAvatarCandidates([
+ { role: "author", handle: "ObviousRises", src: pic("1") },
+ { role: "author", handle: "../x", src: pic("1") },
+ { role: "fan", handle: "a", src: pic("1") },
+ { role: "parent", handle: "b", src: "" },
+ null,
+ ]),
+ [{ role: "author", handle: "ObviousRises", src: pic("1") }],
+ );
+});
+
+test("run: a normal capture stores the author's avatar from the page it shot — one load, one fetch at 400×400", async () => {
+ const out = await outDir();
+ const page = fakePage({ "11": [{ role: "author", handle: "ObviousRises", src: pic("9") }] });
+ const d = deps(page);
+ const res = await captureXPosts(input(out, ["11"]), d);
+ assert.equal(res.outcomes[0].state, "captured");
+ assert.equal(page.gotos.length, 1);
+ assert.equal(page.shots, 1);
+ assert.deepEqual(page.gets, ["https://pbs.twimg.com/profile_images/9/face_400x400.jpg"]);
+ assert.deepEqual(res.avatars?.stored, ["ObviousRises"]);
+ const index = await readXAvatarIndex(path.join(out, AVATARS_DIRNAME));
+ assert.deepEqual(index, {
+ ObviousRises: {
+ file: "ObviousRises.jpg",
+ url: "https://pbs.twimg.com/profile_images/9/face_400x400.jpg",
+ capturedAt: "2026-11-02T20:00:00.000Z",
+ postId: "11",
+ },
+ });
+ assert.deepEqual(new Uint8Array(await readFile(path.join(out, AVATARS_DIRNAME, "ObviousRises.jpg"))), JPG);
+ // Without the thread, only the author is looked for.
+ assert.ok(page.reads[0].includes("const wantParent = false"));
+});
+
+test("run: two posts of one author fetch the picture once; an author already stored is not fetched again", async () => {
+ const out = await outDir();
+ const a = [{ role: "author" as const, handle: "ObviousRises", src: pic("9") }];
+ const page = fakePage({ "11": a, "12": a });
+ await captureXPosts(input(out, ["11", "12"]), deps(page));
+ assert.equal(page.gets.length, 1);
+ // A later run: stored (under another case, even) — read, not fetched.
+ const page2 = fakePage({ "13": [{ role: "author", handle: "obviousrises", src: pic("9") }] });
+ const res = await captureXPosts(input(out, ["13"]), deps(page2));
+ assert.equal(page2.gets.length, 0);
+ assert.deepEqual(res.avatars?.skipped, ["obviousrises"]);
+ // force fetches again, and the entry takes the case X prints now.
+ const page3 = fakePage({ "14": [{ role: "author", handle: "obviousrises", src: pic("10") }] });
+ await captureXPosts(input(out, ["14"], { force: true }), deps(page3));
+ assert.equal(page3.gets.length, 1);
+ const index = await readXAvatarIndex(path.join(out, AVATARS_DIRNAME));
+ assert.deepEqual(Object.keys(index), ["obviousrises"]);
+ assert.equal(index.obviousrises.postId, "14");
+});
+
+test("run: avatars: false reads none; X's default picture is not stored", async () => {
+ const out = await outDir();
+ const page = fakePage({ "11": [{ role: "author", handle: "ObviousRises", src: pic("9") }] });
+ const res = await captureXPosts(input(out, ["11"], { avatars: false }), deps(page));
+ assert.equal(page.reads.length, 0);
+ assert.equal(page.gets.length, 0);
+ assert.equal(res.avatars, undefined);
+
+ const egg = fakePage({
+ "12": [{ role: "author", handle: "eggy", src: "https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png" }],
+ });
+ const res2 = await captureXPosts(input(out, ["12"]), deps(egg));
+ assert.equal(egg.gets.length, 0);
+ assert.deepEqual(res2.avatars?.skipped, ["eggy"]);
+ assert.deepEqual(await readXAvatarIndex(path.join(out, AVATARS_DIRNAME)), {});
+});
+
+test("run: with the thread on, the parent's and the quoted post's authors' too, by the archive's parent id", async () => {
+ const out = await outDir();
+ const page = fakePage({
+ "21": [
+ { role: "author", handle: "ObviousRises", src: pic("1") },
+ { role: "quoted", handle: "quoted_one", src: pic("2") },
+ { role: "parent", handle: "parent_one", src: pic("3") },
+ ],
+ });
+ const archived = new Map([["21", { text: "", author: "ObviousRises", isReply: true, replyTo: { id: "20" } }]]);
+ const res = await captureXPosts(input(out, ["21"], { thread: true, shots: false, archived }), deps(page));
+ assert.ok(page.reads[0].includes("const wantParent = true"));
+ assert.ok(page.reads[0].includes('const parentId = "20"'));
+ assert.deepEqual(res.avatars?.stored, ["ObviousRises", "quoted_one", "parent_one"]);
+ assert.deepEqual(Object.keys(await readXAvatarIndex(path.join(out, AVATARS_DIRNAME))), ["ObviousRises", "parent_one", "quoted_one"]);
+});
+
+test("avatarsOnly: one page per distinct archived author, paced, no shot, no media, no capture record", async () => {
+ const out = await outDir();
+ const page = fakePage({
+ "31": [{ role: "author", handle: "ObviousRises", src: pic("1") }],
+ "33": [{ role: "author", handle: "someone_else", src: pic("2") }],
+ });
+ let downloads = 0;
+ const d = deps(page, {
+ downloadMedia: async () => {
+ downloads++;
+ return { ok: true, files: [] };
+ },
+ });
+ const archived = new Map([
+ ["31", { text: "", author: "ObviousRises" }],
+ ["32", { text: "", author: "obviousrises" }],
+ ["33", { text: "", author: "someone_else" }],
+ ]);
+ const res = await captureXPosts(input(out, ["31", "32", "33"], { avatarsOnly: true, media: true, archived }), d);
+ assert.deepEqual(page.gotos, ["https://x.com/i/status/31", "https://x.com/i/status/33"]);
+ assert.deepEqual(d.pauses, [4000], "the gap before every contact after the first");
+ assert.equal(page.shots, 0);
+ assert.equal(downloads, 0);
+ assert.deepEqual(res.outcomes, []);
+ assert.equal(res.avatars?.pages, 2);
+ assert.deepEqual(res.avatars?.stored, ["ObviousRises", "someone_else"]);
+ // Nothing but the store under posts-media/: no post directory, no capture.json.
+ assert.deepEqual(await readdir(out), [AVATARS_DIRNAME]);
+});
+
+test("avatarsOnly: an author already stored costs no page load unless force", async () => {
+ const out = await outDir();
+ await writeXAvatar(path.join(out, AVATARS_DIRNAME), {
+ handle: "ObviousRises",
+ bytes: JPG,
+ url: "https://pbs.twimg.com/profile_images/1/face_400x400.jpg",
+ postId: "1",
+ });
+ const page = fakePage({ "31": [{ role: "author", handle: "ObviousRises", src: pic("1") }] });
+ const archived = new Map([["31", { text: "", author: "obviousrises" }]]);
+ const d = deps(page);
+ const res = await captureXPosts(input(out, ["31"], { avatarsOnly: true, archived }), d);
+ assert.equal(d.opened, 0);
+ assert.deepEqual(page.gotos, []);
+ assert.deepEqual(res.avatars?.skipped, ["obviousrises"]);
+
+ const res2 = await captureXPosts(input(out, ["31"], { avatarsOnly: true, archived, force: true }), deps(page));
+ assert.deepEqual(page.gotos, ["https://x.com/i/status/31"]);
+ assert.deepEqual(page.gets, ["https://pbs.twimg.com/profile_images/1/face_400x400.jpg"]);
+ assert.deepEqual(res2.avatars?.stored, ["ObviousRises"]);
+});
+
+test("avatarsOnly: a login wall stops the run with needsCookies, the rest left", async () => {
+ const out = await outDir();
+ const page = fakePage({});
+ page.evaluate = async (script: string) =>
+ script.includes(AVATARS_SCRIPT_MARKER) ? [] : { path: "/i/flow/login", text: "", article: null };
+ const archived = new Map([
+ ["41", { text: "", author: "a" }],
+ ["42", { text: "", author: "b" }],
+ ]);
+ const res = await captureXPosts(input(out, ["41", "42"], { avatarsOnly: true, archived }), deps(page));
+ assert.equal(res.needsCookies, true);
+ assert.match(res.stoppedEarly ?? "", /Stopped at 41/);
+ assert.equal(page.gotos.length, 1);
+ assert.deepEqual(res.outcomes, []);
+});
diff --git a/common/social/xAvatarCapture.ts b/common/social/xAvatarCapture.ts
@@ -0,0 +1,238 @@
+// Reading X authors' avatars off a post page capture-posts has ALREADY loaded,
+// and saving them into the channel's avatar store (xAvatars.ts).
+//
+// NO EXTRA PAGE LOAD. The read is one evaluate over the page as it stands: the
+// post's own article (xPostCapture.ts marks it) and its author's avatar
+// container — X draws `[data-testid="Tweet-User-Avatar"]` holding
+// `[data-testid="UserAvatar-Container-<handle>"]`, a link to `/<handle>` and an
+// <img src="https://pbs.twimg.com/profile_images/<n>/<name>_normal.jpg">. With
+// the thread on, also the post it answers (the archive's replyTo id, else the
+// article directly above — the thread shot's own pick, xThreadShot.ts) and the
+// post it quotes (an avatar container inside the article's quote card,
+// `[role="link"]`).
+//
+// THE DOWNLOAD goes through the page's own request context (`page.request`, a
+// Playwright APIRequestContext that IS the browser context's: the profile's
+// cookies, no tab, no navigation) — the same route an X Article's images take
+// (xArticleCapture.ts), chosen over an in-page fetch() because pbs.twimg.com's
+// CORS answer is not ours to rely on and the bytes would have to cross the
+// evaluate boundary as base64. One GET per author per run, of the _400x400
+// size; nothing is retried. It is a request to X's image CDN for a picture the
+// page has just drawn, so it takes no post gap of its own (the page load that
+// preceded it took one).
+//
+// NOT VERIFIED AGAINST LIVE X: the markup is X's as of 2026-11, proved against
+// a recorded-style fixture page in a real Chromium (xAvatarCapture.browser
+// test); the first real run is the check.
+
+import type { PageLike } from "./playwrightRuntime";
+import {
+ isXAvatarHandle,
+ lookupXAvatar,
+ readXAvatarIndex,
+ upgradeXAvatarUrl,
+ writeXAvatar,
+} from "./xAvatars";
+
+export const AVATARS_SCRIPT_MARKER = "__archilyzerAvatars";
+
+export type XAvatarRole = "author" | "parent" | "quoted";
+
+export type XAvatarCandidate = { role: XAvatarRole; handle: string; src: string };
+
+export type XAvatarReadOptions = {
+ // The post it answers, and the quoted post: read only with the thread on.
+ parent?: boolean;
+ quotes?: boolean;
+ // The archive's word for the parent: its status id. Not on the page means
+ // no parent (the article above would be another post of the thread).
+ parentId?: string | null;
+};
+
+// The in-page read. Each article's author avatar: the container inside
+// Tweet-User-Avatar, else the first container not inside a quote card. The
+// handle from the container's test id, else its profile link; the picture from
+// its <img>, else a background-image.
+export const avatarsScript = (o: XAvatarReadOptions = {}) => `(() => {
+ const ${AVATARS_SCRIPT_MARKER} = true;
+ const wantParent = ${o.parent ? "true" : "false"};
+ const wantQuotes = ${o.quotes ? "true" : "false"};
+ const parentId = ${JSON.stringify(o.parentId ?? null)};
+ const all = Array.from(document.querySelectorAll('article[data-testid="tweet"]'));
+ const own = document.querySelector("[data-archilyzer-capture]");
+ if (!own) return [];
+ const HANDLE = /^[A-Za-z0-9_]{1,30}$/;
+ const handleOf = (c) => {
+ const t = (c.getAttribute("data-testid") || "").replace(/^UserAvatar-Container-/, "");
+ if (HANDLE.test(t)) return t;
+ for (const l of c.querySelectorAll("a[href]")) {
+ const m = /^\\/([A-Za-z0-9_]{1,30})\\/?$/.exec(l.getAttribute("href") || "");
+ if (m) return m[1];
+ }
+ return null;
+ };
+ const srcOf = (c) => {
+ const img = c.querySelector("img[src]");
+ if (img && img.src) return img.src;
+ for (const el of c.querySelectorAll("*")) {
+ const m = /url\\(["']?([^"')]+)["']?\\)/.exec(el.style && el.style.backgroundImage || "");
+ if (m) return new URL(m[1], location.href).href;
+ }
+ return null;
+ };
+ const read = (c, role) => {
+ const handle = handleOf(c);
+ const src = srcOf(c);
+ return handle && src ? { role, handle, src } : null;
+ };
+ const containers = (a) => Array.from(a.querySelectorAll('[data-testid^="UserAvatar-Container-"]'));
+ const inQuote = (c, a) => { const q = c.closest('[role="link"]'); return !!q && a.contains(q) && q !== a; };
+ const authorContainer = (a) => {
+ const box = a.querySelector('[data-testid="Tweet-User-Avatar"]');
+ const inBox = box && (box.matches('[data-testid^="UserAvatar-Container-"]') ? box : box.querySelector('[data-testid^="UserAvatar-Container-"]'));
+ return inBox || containers(a).find((c) => !inQuote(c, a)) || null;
+ };
+ const out = [];
+ const mine = authorContainer(own);
+ const author = mine && read(mine, "author");
+ if (author) out.push(author);
+ if (wantQuotes) {
+ for (const c of containers(own)) {
+ if (c === mine || !inQuote(c, own)) continue;
+ const q = read(c, "quoted");
+ if (q) out.push(q);
+ }
+ }
+ if (wantParent) {
+ const ownIdx = all.indexOf(own);
+ const top = own.getBoundingClientRect().top;
+ const idOf = (a) => {
+ for (const l of a.querySelectorAll('a[href*="/status/"]')) {
+ const m = /\\/status\\/(\\d+)/.exec(l.getAttribute("href") || "");
+ if (m && l.querySelector("time")) return m[1];
+ }
+ return null;
+ };
+ const above = all.filter((a, i) => i < ownIdx && a.getBoundingClientRect().bottom <= top + 2);
+ const parent = parentId ? above.find((a) => idOf(a) === parentId) : above[above.length - 1];
+ const pc = parent && authorContainer(parent);
+ const p = pc && read(pc, "parent");
+ if (p) out.push(p);
+ }
+ return out;
+})()`;
+
+const ROLES = new Set<XAvatarRole>(["author", "parent", "quoted"]);
+
+// What the read returned, kept to the shape (anything else is no avatar).
+export function parseAvatarCandidates(raw: unknown): XAvatarCandidate[] {
+ if (!Array.isArray(raw)) return [];
+ const out: XAvatarCandidate[] = [];
+ for (const r of raw) {
+ if (!r || typeof r !== "object") continue;
+ const { role, handle, src } = r as Record<string, unknown>;
+ if (typeof role !== "string" || !ROLES.has(role as XAvatarRole)) continue;
+ if (typeof handle !== "string" || !isXAvatarHandle(handle) || typeof src !== "string" || !src) continue;
+ out.push({ role: role as XAvatarRole, handle, src });
+ }
+ return out;
+}
+
+export async function readXAvatarCandidates(page: PageLike, o: XAvatarReadOptions = {}): Promise<XAvatarCandidate[]> {
+ try {
+ return parseAvatarCandidates(await page.evaluate(avatarsScript(o)));
+ } catch {
+ return [];
+ }
+}
+
+export type XAvatarRunSummary = {
+ // Handles stored this run, as X prints them.
+ stored: string[];
+ // Handles not fetched: already in the store, or X's default picture.
+ skipped: string[];
+ failed: { handle: string; error: string }[];
+ // Post pages loaded for the avatars alone (avatarsOnly).
+ pages: number;
+};
+
+export function emptyAvatarSummary(): XAvatarRunSummary {
+ return { stored: [], skipped: [], failed: [], pages: 0 };
+}
+
+export type SaveXAvatarsContext = {
+ // The store: `<posts-media>/_avatars`.
+ dir: string;
+ // The post page they were read from.
+ postId: string;
+ // Fetch even an author the store already has.
+ force?: boolean;
+ // Lower-cased handles already handled this run: one fetch per author.
+ seen: Set<string>;
+ summary: XAvatarRunSummary;
+ now?: () => Date;
+ onLog?: (line: string) => void;
+};
+
+// Fetch and store each candidate's picture, through the page's own request
+// context. Never throws: a failure is the summary's and the log's.
+export async function saveXAvatars(
+ page: PageLike,
+ candidates: ReadonlyArray<XAvatarCandidate>,
+ ctx: SaveXAvatarsContext,
+): Promise<void> {
+ const { summary, onLog } = ctx;
+ let index: Awaited<ReturnType<typeof readXAvatarIndex>> | undefined;
+ for (const c of candidates) {
+ const key = c.handle.toLowerCase();
+ if (ctx.seen.has(key)) continue;
+ ctx.seen.add(key);
+ index ??= await readXAvatarIndex(ctx.dir);
+ if (!ctx.force && lookupXAvatar(index, c.handle)) {
+ summary.skipped.push(c.handle);
+ continue;
+ }
+ const url = upgradeXAvatarUrl(c.src);
+ if (!url) {
+ summary.skipped.push(c.handle);
+ onLog?.(`avatar @${c.handle}: X's default picture (or not X's CDN) — not stored.`);
+ continue;
+ }
+ if (!page.request) {
+ summary.failed.push({ handle: c.handle, error: "this browser page cannot fetch (no request context)" });
+ continue;
+ }
+ try {
+ const res = await page.request.get(url, { timeout: 30_000, failOnStatusCode: false });
+ if (!res.ok()) throw new Error(`HTTP ${res.status()} for ${url}`);
+ const type = res.headers()["content-type"] ?? "";
+ if (type && !/^image\//i.test(type)) throw new Error(`${url} answered ${type.split(";")[0]}, not an image`);
+ const bytes = await res.body();
+ const { handle } = await writeXAvatar(ctx.dir, {
+ handle: c.handle,
+ bytes,
+ url,
+ contentType: type,
+ postId: ctx.postId,
+ capturedAt: (ctx.now ?? (() => new Date()))().toISOString(),
+ });
+ summary.stored.push(handle);
+ onLog?.(`avatar @${handle} saved (${c.role}${c.role === "author" ? "" : " of " + ctx.postId}).`);
+ } catch (err) {
+ const error = ((err as Error)?.message ?? String(err)).split("\n")[0];
+ summary.failed.push({ handle: c.handle, error });
+ onLog?.(`avatar @${c.handle}: ${error}`);
+ }
+ }
+}
+
+export function describeAvatarSummary(s: XAvatarRunSummary): string {
+ return (
+ `Avatars: ${s.stored.length} saved` +
+ (s.stored.length ? ` (${s.stored.map((h) => "@" + h).join(", ")})` : "") +
+ `, ${s.skipped.length} already stored or default` +
+ (s.failed.length ? `, ${s.failed.length} failed (${s.failed.map((f) => "@" + f.handle).join(", ")})` : "") +
+ (s.pages ? `; ${s.pages} page(s) loaded for them` : "") +
+ "."
+ );
+}
diff --git a/common/social/xAvatars.test.ts b/common/social/xAvatars.test.ts
@@ -0,0 +1,160 @@
+// The avatar store and the URL rule (xAvatars.ts). Temp dirs only.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xAvatars.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readdir, readFile, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import {
+ AVATARS_DIRNAME,
+ AVATARS_INDEX_FILENAME,
+ isXAvatarHandle,
+ lookupXAvatar,
+ readXAvatarIndex,
+ upgradeXAvatarUrl,
+ writeXAvatar,
+ xAvatarExtension,
+ xAvatarFile,
+ xAvatarsDir,
+} from "./xAvatars";
+import { postCaptureDir, postsMediaDir } from "./postCapture";
+
+const JPG = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]);
+const PB = "https://pbs.twimg.com/profile_images/1712345678901234567/AbC-dEf_";
+
+test("url: every size X serves maps to _400x400, the extension and query kept", () => {
+ for (const suffix of ["normal", "bigger", "mini", "reasonably_small", "x96", "200x200", "400x400"]) {
+ assert.equal(upgradeXAvatarUrl(`${PB}${suffix}.jpg`), `${PB}400x400.jpg`, suffix);
+ }
+ // No suffix: the original upload, any size — asked for at 400 too.
+ assert.equal(
+ upgradeXAvatarUrl("https://pbs.twimg.com/profile_images/123/abc.png"),
+ "https://pbs.twimg.com/profile_images/123/abc_400x400.png",
+ );
+ // A name with an underscore of its own, and no extension at all.
+ assert.equal(
+ upgradeXAvatarUrl("https://pbs.twimg.com/profile_images/123/my_pic_normal.jpeg"),
+ "https://pbs.twimg.com/profile_images/123/my_pic_400x400.jpeg",
+ );
+ assert.equal(
+ upgradeXAvatarUrl("https://pbs.twimg.com/profile_images/123/abc_normal"),
+ "https://pbs.twimg.com/profile_images/123/abc_400x400",
+ );
+ assert.equal(
+ upgradeXAvatarUrl("https://pbs.twimg.com/profile_images/123/abc_normal.webp?v=2"),
+ "https://pbs.twimg.com/profile_images/123/abc_400x400.webp?v=2",
+ );
+});
+
+test("url: X's default egg, another host, another path or no URL is no avatar", () => {
+ assert.equal(upgradeXAvatarUrl("https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png"), null);
+ assert.equal(upgradeXAvatarUrl("https://pbs.twimg.com/sticky/default_profile_images/default_profile_400x400.png"), null);
+ assert.equal(upgradeXAvatarUrl("https://evil.example/profile_images/123/abc_normal.jpg"), null);
+ assert.equal(upgradeXAvatarUrl("https://pbs.twimg.com/media/Gabc123?format=jpg&name=small"), null);
+ assert.equal(upgradeXAvatarUrl("data:image/png;base64,AAAA"), null);
+ assert.equal(upgradeXAvatarUrl("not a url"), null);
+ // Loopback is allowed: a test's fixture server.
+ assert.equal(
+ upgradeXAvatarUrl("http://127.0.0.1:4321/profile_images/123/abc_normal.jpg"),
+ "http://127.0.0.1:4321/profile_images/123/abc_400x400.jpg",
+ );
+});
+
+test("extension: the response's type, else the URL's, else jpg", () => {
+ assert.equal(xAvatarExtension(`${PB}400x400.jpg`, "image/png"), "png");
+ assert.equal(xAvatarExtension(`${PB}400x400.jpg`, "image/jpeg; charset=binary"), "jpg");
+ assert.equal(xAvatarExtension(`${PB}400x400.jpeg`), "jpg");
+ assert.equal(xAvatarExtension(`${PB}400x400.webp`, "application/octet-stream"), "webp");
+ assert.equal(xAvatarExtension(`${PB}400x400.gif`), "gif");
+ assert.equal(xAvatarExtension(`${PB}400x400`), "jpg");
+ assert.equal(xAvatarExtension(`${PB}400x400.bmp`), "jpg");
+});
+
+test("handles: X's own shape only", () => {
+ for (const h of ["ObviousRises", "a", "under_score_1", "x".repeat(30)]) assert.equal(isXAvatarHandle(h), true, h);
+ for (const h of ["", "x".repeat(31), "../etc", "a.b", "a-b", "a b", "avatars.json"]) assert.equal(isXAvatarHandle(h), false, h);
+});
+
+test("layout: posts-media/_avatars, and _avatars is never taken for a post id", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "xavatars-layout-"));
+ assert.equal(xAvatarsDir(postsMediaDir(root)), path.join(root, "posts-media", AVATARS_DIRNAME));
+ assert.throws(() => postCaptureDir(postsMediaDir(root), AVATARS_DIRNAME), /not a post id/);
+ assert.doesNotThrow(() => postCaptureDir(postsMediaDir(root), "_avatars2"));
+});
+
+test("store: the picture and its entry, in the exact shape umtool reads", async () => {
+ const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xavatars-")), AVATARS_DIRNAME);
+ const got = await writeXAvatar(dir, {
+ handle: "ObviousRises",
+ bytes: JPG,
+ url: `${PB}400x400.jpg`,
+ contentType: "image/jpeg",
+ postId: "1850000000000000001",
+ capturedAt: "2026-11-02T20:00:00.000Z",
+ });
+ assert.equal(got.handle, "ObviousRises");
+ assert.deepEqual(await readdir(dir).then((n) => n.sort()), ["ObviousRises.jpg", AVATARS_INDEX_FILENAME]);
+ assert.deepEqual(new Uint8Array(await readFile(path.join(dir, "ObviousRises.jpg"))), JPG);
+ assert.deepEqual(JSON.parse(await readFile(path.join(dir, AVATARS_INDEX_FILENAME), "utf8")), {
+ ObviousRises: {
+ file: "ObviousRises.jpg",
+ url: `${PB}400x400.jpg`,
+ capturedAt: "2026-11-02T20:00:00.000Z",
+ postId: "1850000000000000001",
+ },
+ });
+ assert.equal(await xAvatarFile(dir, "obviousrises"), path.join(dir, "ObviousRises.jpg"));
+ assert.equal(await xAvatarFile(dir, "nobody"), null);
+});
+
+test("store: merged with what is there; another case replaces the entry and its file", async () => {
+ const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xavatars-")), AVATARS_DIRNAME);
+ const w = (handle: string, ext = "jpg", postId = "1") =>
+ writeXAvatar(dir, { handle, bytes: JPG, url: `${PB}400x400.${ext}`, postId, capturedAt: "2026-11-02T20:00:00.000Z" });
+ await w("alice");
+ await w("Bob", "png");
+ // Two at once: the read-modify-writes do not drop each other.
+ await Promise.all([w("carol"), w("dave"), w("erin")]);
+ let index = await readXAvatarIndex(dir);
+ assert.deepEqual(Object.keys(index), ["alice", "Bob", "carol", "dave", "erin"]);
+
+ // A re-capture as X prints it now: one entry, the old file gone.
+ await w("BOB", "jpg", "2");
+ index = await readXAvatarIndex(dir);
+ assert.deepEqual(Object.keys(index), ["alice", "BOB", "carol", "dave", "erin"]);
+ assert.equal(index.BOB.postId, "2");
+ assert.equal(lookupXAvatar(index, "@bob")?.handle, "BOB");
+ assert.equal(lookupXAvatar(index, "nobody"), null);
+ const files = (await readdir(dir)).sort();
+ assert.ok(!files.includes("Bob.png"), files.join(","));
+ assert.ok(files.includes("BOB.jpg"));
+ assert.ok(!files.some((f) => f.includes(".tmp-")), "no temp file left");
+});
+
+test("store: a bad handle, a bad post id or no bytes is refused; an unreadable index is never overwritten", async () => {
+ const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xavatars-")), AVATARS_DIRNAME);
+ const ok = { handle: "alice", bytes: JPG, url: `${PB}400x400.jpg`, postId: "1" };
+ await assert.rejects(writeXAvatar(dir, { ...ok, handle: "../x" }), /not an X handle/);
+ await assert.rejects(writeXAvatar(dir, { ...ok, handle: "avatars.json" }), /not an X handle/);
+ await assert.rejects(writeXAvatar(dir, { ...ok, postId: "../1" }), /not a post id/);
+ await assert.rejects(writeXAvatar(dir, { ...ok, bytes: new Uint8Array() }), /empty/);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, AVATARS_INDEX_FILENAME), "{ truncated");
+ await assert.rejects(writeXAvatar(dir, ok), /unparseable; not overwriting/);
+ assert.equal(await readFile(path.join(dir, AVATARS_INDEX_FILENAME), "utf8"), "{ truncated");
+ // A reader just finds nothing.
+ assert.deepEqual(await readXAvatarIndex(dir), {});
+});
+
+test("store: entries not of the shape, or under a key that is no handle, are left out on read", async () => {
+ const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xavatars-")), AVATARS_DIRNAME);
+ await mkdir(dir, { recursive: true });
+ const good = { file: "a.jpg", url: "u", capturedAt: "t", postId: "1" };
+ await writeFile(
+ path.join(dir, AVATARS_INDEX_FILENAME),
+ JSON.stringify({ a: good, "b/c": good, d: { file: 3 }, e: null }),
+ );
+ assert.deepEqual(await readXAvatarIndex(dir), { a: good });
+});
diff --git a/common/social/xAvatars.ts b/common/social/xAvatars.ts
@@ -0,0 +1,228 @@
+// X authors' profile pictures, kept beside a channel's post captures so a post
+// card can show the author's face instead of an initial letter.
+//
+// THE STORE (umtool reads it as plain JSON; keep the shape):
+//
+// channels/<slug>/posts-media/_avatars/<handle>.<ext> ext: jpg | png | webp | gif
+// channels/<slug>/posts-media/_avatars/avatars.json
+// { "<handle>": { "file": "<handle>.<ext>",
+// "url": "<the _400x400 url it was fetched from>",
+// "capturedAt": "<ISO>",
+// "postId": "<the post page it was read from>" } }
+//
+// Keys keep the handle's case as X prints it; a lookup ignores case, and a
+// re-capture under another case REPLACES the entry (and its file), never adds a
+// second one. Handles are X's: `^[A-Za-z0-9_]{1,30}$`. Every write is atomic
+// (tmp + rename) and a read-modify-write of the index under the process's
+// per-file lock, so a write never drops another handle.
+//
+// `_avatars` sits among the post-id directories of posts-media/ and is never
+// one: postCaptureDir refuses the name (postCapture.ts), and nothing that walks
+// posts-media/ takes its children for post ids (the readers go by archived or
+// cited id).
+//
+// Capturing them is xAvatarCapture.ts (in the post page capture-posts already
+// loads); this module is the store and the URL rule only — no browser.
+//
+// SERVER-ONLY (node:fs).
+
+import { rm, stat } from "node:fs/promises";
+import path from "node:path";
+import {
+ readJsonFile,
+ withJsonFileLock,
+ writeFileAtomic,
+ writeJsonAtomic,
+} from "../lib/jsonFile-server";
+
+export const AVATARS_DIRNAME = "_avatars";
+export const AVATARS_INDEX_FILENAME = "avatars.json";
+
+export type XAvatarEntry = {
+ file: string;
+ url: string;
+ capturedAt: string;
+ postId: string;
+};
+
+export type XAvatarIndex = Record<string, XAvatarEntry>;
+
+const HANDLE_RE = /^[A-Za-z0-9_]{1,30}$/;
+const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
+
+export function isXAvatarHandle(handle: string): boolean {
+ return HANDLE_RE.test(handle);
+}
+
+// `<posts-media>/_avatars`.
+export function xAvatarsDir(postsMediaDir: string): string {
+ return path.join(postsMediaDir, AVATARS_DIRNAME);
+}
+
+// The sizes X serves a profile picture at, as the suffix before the extension.
+const SIZE_SUFFIXES = ["normal", "bigger", "mini", "reasonably_small", "x96", "200x200", "400x400"];
+const PROFILE_IMAGE_PATH = new RegExp(
+ `^(.*/profile_images/\\d+/)([^/]+?)(?:_(?:${SIZE_SUFFIXES.join("|")}))?(\\.[A-Za-z0-9]+)?$`,
+);
+
+// Hosts an avatar is fetched from: X's image CDN, and loopback (a test's
+// fixture server — never a third-party host a page could name).
+function avatarHostAllowed(host: string): boolean {
+ return host === "pbs.twimg.com" || host === "127.0.0.1" || host === "localhost" || host === "[::1]";
+}
+
+// A profile picture's URL at 400×400, the largest fixed size X serves (the
+// no-suffix original can be any size). `_normal` (48), `_bigger` (73), `_mini`
+// (24), `_reasonably_small` (128), `_x96`, `_200x200`, `_400x400` and the
+// no-suffix original all map to it; the extension and any query stay. X's
+// default "egg" (abs.twimg.com/sticky/default_profile_images/…) is no
+// picture of anyone and is not stored: null — as is anything that is not a
+// profile_images URL on X's CDN.
+export function upgradeXAvatarUrl(src: string): string | null {
+ let u: URL;
+ try {
+ u = new URL(src);
+ } catch {
+ return null;
+ }
+ if (u.protocol !== "https:" && u.protocol !== "http:") return null;
+ if (/\/default_profile_images\//.test(u.pathname)) return null;
+ if (!avatarHostAllowed(u.hostname === "::1" ? "[::1]" : u.hostname)) return null;
+ const m = PROFILE_IMAGE_PATH.exec(u.pathname);
+ if (!m) return null;
+ u.pathname = `${m[1]}${m[2]}_400x400${m[3] ?? ""}`;
+ return u.toString();
+}
+
+const TYPE_EXT: Record<string, string> = {
+ "image/jpeg": "jpg",
+ "image/jpg": "jpg",
+ "image/pjpeg": "jpg",
+ "image/png": "png",
+ "image/webp": "webp",
+ "image/gif": "gif",
+};
+
+// The stored file's extension: the response's type when it names one of the
+// four, else the URL's, else jpg (what X serves profile pictures as).
+export function xAvatarExtension(url: string, contentType?: string | null): string {
+ const t = (contentType ?? "").split(";")[0].trim().toLowerCase();
+ if (TYPE_EXT[t]) return TYPE_EXT[t];
+ let pathname = url;
+ try {
+ pathname = new URL(url).pathname;
+ } catch {
+ /* a bare path */
+ }
+ const ext = /\.([A-Za-z0-9]+)$/.exec(pathname)?.[1]?.toLowerCase();
+ if (ext === "jpeg" || ext === "jpg") return "jpg";
+ if (ext === "png" || ext === "webp" || ext === "gif") return ext;
+ return "jpg";
+}
+
+function validEntry(handle: string, v: unknown): v is XAvatarEntry {
+ if (!isXAvatarHandle(handle) || !v || typeof v !== "object") return false;
+ const e = v as Partial<XAvatarEntry>;
+ return typeof e.file === "string" && typeof e.url === "string" && typeof e.capturedAt === "string" && typeof e.postId === "string";
+}
+
+type IndexRead = { ok: true; index: XAvatarIndex } | { ok: false; reason: "unreadable" | "unparseable" };
+
+async function readIndexStrict(dir: string): Promise<IndexRead> {
+ const got = await readJsonFile(path.join(dir, AVATARS_INDEX_FILENAME));
+ if (!got.ok) return got.reason === "absent" ? { ok: true, index: {} } : { ok: false, reason: got.reason };
+ const v = got.value;
+ if (!v || typeof v !== "object" || Array.isArray(v)) return { ok: false, reason: "unparseable" };
+ const index: XAvatarIndex = {};
+ for (const [k, e] of Object.entries(v as Record<string, unknown>)) {
+ if (validEntry(k, e)) index[k] = { file: e.file, url: e.url, capturedAt: e.capturedAt, postId: e.postId };
+ }
+ return { ok: true, index };
+}
+
+// The store's index; {} when there is none (or it cannot be read — a lookup
+// then simply finds nothing). Entries that are not the shape are left out.
+export async function readXAvatarIndex(dir: string): Promise<XAvatarIndex> {
+ const got = await readIndexStrict(dir);
+ return got.ok ? got.index : {};
+}
+
+// The entry for `handle`, whatever case it was stored under.
+export function lookupXAvatar(
+ index: XAvatarIndex,
+ handle: string,
+): { handle: string; entry: XAvatarEntry } | null {
+ const want = handle.replace(/^@/, "").toLowerCase();
+ for (const [k, entry] of Object.entries(index)) {
+ if (k.toLowerCase() === want) return { handle: k, entry };
+ }
+ return null;
+}
+
+// The picture's absolute path, when the store has one for `handle` and the
+// file is there.
+export async function xAvatarFile(dir: string, handle: string): Promise<string | null> {
+ const hit = lookupXAvatar(await readXAvatarIndex(dir), handle);
+ if (!hit) return null;
+ const file = path.join(dir, path.basename(hit.entry.file));
+ return (await stat(file).catch(() => null))?.isFile() ? file : null;
+}
+
+export type WriteXAvatarInput = {
+ handle: string;
+ bytes: Uint8Array;
+ // The URL the bytes came from (the _400x400 one).
+ url: string;
+ contentType?: string | null;
+ // The post page the avatar was read from.
+ postId: string;
+ capturedAt?: string;
+};
+
+// Store one avatar: the picture as `<handle>.<ext>`, then its entry merged
+// into avatars.json (an entry for the same handle in another case, and its
+// file, replaced). Refuses a handle that is not X's, and an index it cannot
+// read (it is never overwritten from ignorance).
+export async function writeXAvatar(dir: string, a: WriteXAvatarInput): Promise<{ handle: string; entry: XAvatarEntry }> {
+ const handle = a.handle.replace(/^@/, "");
+ if (!isXAvatarHandle(handle)) throw new Error(`"${a.handle}" is not an X handle`);
+ if (!POST_ID_RE.test(a.postId)) throw new Error(`"${a.postId}" is not a post id`);
+ if (!a.bytes || a.bytes.length === 0) throw new Error(`The avatar for @${handle} is empty`);
+ const file = `${handle}.${xAvatarExtension(a.url, a.contentType)}`;
+ const entry: XAvatarEntry = {
+ file,
+ url: a.url,
+ capturedAt: a.capturedAt ?? new Date().toISOString(),
+ postId: a.postId,
+ };
+ const indexPath = path.join(dir, AVATARS_INDEX_FILENAME);
+ await withJsonFileLock(indexPath, async () => {
+ const got = await readIndexStrict(dir);
+ if (!got.ok) throw new Error(`${indexPath} is ${got.reason}; not overwriting it`);
+ await writeFileAtomic(path.join(dir, file), Buffer.from(a.bytes), { mkdir: true });
+ const index = got.index;
+ for (const [k, old] of Object.entries(index)) {
+ if (k.toLowerCase() !== handle.toLowerCase()) continue;
+ delete index[k];
+ if (old.file !== file) await removeOldFile(dir, path.basename(old.file), file);
+ }
+ index[handle] = entry;
+ const sorted: XAvatarIndex = {};
+ for (const k of Object.keys(index).sort((x, y) => x.toLowerCase().localeCompare(y.toLowerCase()) || x.localeCompare(y))) {
+ sorted[k] = index[k];
+ }
+ await writeJsonAtomic(indexPath, sorted);
+ });
+ return { handle, entry };
+}
+
+// The replaced entry's picture, unless it IS the new one (a case-insensitive
+// filesystem names `Foo.jpg` and `foo.jpg` the same file).
+async function removeOldFile(dir: string, oldName: string, newName: string): Promise<void> {
+ if (!oldName || oldName === AVATARS_INDEX_FILENAME) return;
+ const oldPath = path.join(dir, oldName);
+ const [o, n] = await Promise.all([stat(oldPath).catch(() => null), stat(path.join(dir, newName)).catch(() => null)]);
+ if (!o) return;
+ if (n && o.ino === n.ino && o.dev === n.dev) return;
+ await rm(oldPath, { force: true });
+}
diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts
@@ -372,11 +372,12 @@ export async function captureXPostsByIds(
const paths = getPaths();
// The profile shoots the posts and opens the articles. A post is known to
// link to an article before any page only by its archived text; one found
- // on a card is found by a shot, which already needs the profile.
+ // on a card is found by a shot, which already needs the profile. An
+ // avatars-only run reads the post pages through it too.
const articles =
(input.articles ?? true) &&
input.ids.some((id) => xArticleLinkFromArchive(input.archived?.get(id)) !== null);
- if ((input.shots ?? true) || articles) {
+ if (input.avatarsOnly || (input.shots ?? true) || articles) {
const status = await readXSessionStatus(paths);
if (!status.hasProfile) {
const why =
diff --git a/common/social/xPostCapture.ts b/common/social/xPostCapture.ts
@@ -30,6 +30,13 @@
// author blurred unless verified or the reply's own (xThreadShot.ts). A post
// the archive says is no reply is not opened for it.
//
+// The AUTHOR'S AVATAR is read off the same page (xAvatarCapture.ts) and saved
+// into `posts-media/_avatars/` (xAvatars.ts) — with the thread on, the
+// parent's and the quoted post's authors' too — unless `avatars` is off; an
+// author already stored is not fetched again. `avatarsOnly` loads one post
+// page per distinct archived author for that alone, and writes no capture
+// record.
+//
// NOT VERIFIED AGAINST LIVE X. The page markers below are X's as of this
// writing and are tested against recorded snapshots, never x.com; the first
// real run is the check.
@@ -60,6 +67,16 @@ import { xArticleLinkFromArchive, type XArticleLink } from "./xArticle";
import { captureXArticle, xArticleLinkFromCard } from "./xArticleCapture";
import { shootFromViewport } from "./viewportShot";
import { shootXThread, type ThreadShotOptions, type ThreadShotResult } from "./xThreadShot";
+import {
+ describeAvatarSummary,
+ emptyAvatarSummary,
+ readXAvatarCandidates,
+ saveXAvatars,
+ type XAvatarCandidate,
+ type XAvatarReadOptions,
+ type XAvatarRunSummary,
+} from "./xAvatarCapture";
+import { lookupXAvatar, readXAvatarIndex, xAvatarsDir } from "./xAvatars";
// The post's own article, marked by the snapshot.
const CAPTURE_SELECTOR = "[data-archilyzer-capture]";
@@ -209,6 +226,8 @@ export type XShotResult = XPostVerdict & {
articleLink?: XArticleLink;
// The thread shot, when one was asked for and the post rendered.
thread?: ThreadShotResult;
+ // The avatars read off the page, when asked for and the post rendered.
+ avatars?: XAvatarCandidate[];
};
export type XShotOptions = {
@@ -217,6 +236,9 @@ export type XShotOptions = {
own?: boolean;
// The thread shot too (xThreadShot.ts), after the post's own.
thread?: Omit<ThreadShotOptions, "onLog" | "url"> | null;
+ // Read the authors' avatars off the page (xAvatarCapture.ts): nothing is
+ // fetched here, the caller saves them through the same page.
+ avatars?: XAvatarReadOptions | null;
};
// One post's screenshot: load, read the page, open a sensitive cover, shoot
@@ -262,9 +284,13 @@ export async function shootXPost(
return { state: "error", error: "The post rendered with no size to shoot." };
}
const articleLink = xArticleLinkFromCard(snap.article?.articleHrefs);
+ // Before any shot: the thread shot's blur is a CSS filter, but the read
+ // should see the page as X drew it.
+ const avatars = opts.avatars ? await readXAvatarCandidates(page, opts.avatars) : undefined;
+ const found = avatars ? { avatars } : {};
if (opts.own === false) {
const thread = opts.thread ? await shootXThread(page, id, dir, { ...opts.thread, url, onLog }) : undefined;
- return { ...verdict, ...(articleLink ? { articleLink } : {}), ...(thread ? { thread } : {}) };
+ return { ...verdict, ...(articleLink ? { articleLink } : {}), ...(thread ? { thread } : {}), ...found };
}
let png: Uint8Array;
try {
@@ -298,7 +324,7 @@ export async function shootXPost(
const shot = await describeCapturedFile(dir, SHOT_FILENAME, url);
// After the post's own shot, so nothing the thread shot blurs is in it.
const thread = opts.thread ? await shootXThread(page, id, dir, { ...opts.thread, url, onLog }) : undefined;
- return { ...verdict, shot, ...(articleLink ? { articleLink } : {}), ...(thread ? { thread } : {}) };
+ return { ...verdict, shot, ...(articleLink ? { articleLink } : {}), ...(thread ? { thread } : {}), ...found };
}
export type MediaDownloadResult =
@@ -342,8 +368,13 @@ export async function captureXPosts(
force: input.force ?? false,
articles: input.articles ?? true,
thread: input.thread ?? false,
+ avatars: input.avatars ?? true,
};
+ if (input.avatarsOnly) return captureXAvatarsOnly(input, deps);
const now = deps.now ?? (() => new Date());
+ const avatarDir = xAvatarsDir(input.outDir);
+ const avatarSeen = new Set<string>();
+ const avatarSummary = emptyAvatarSummary();
const outcomes: PostCaptureOutcome[] = [];
let contacts = 0;
let errorsInARow = 0;
@@ -352,9 +383,15 @@ export async function captureXPosts(
const contact = async () => {
if (contacts++ > 0) await deps.pause(deps.pauseMs(), signal);
};
+ const withAvatars = (): Partial<PostCaptureResult> => {
+ const s = avatarSummary;
+ if (!s.stored.length && !s.skipped.length && !s.failed.length) return {};
+ onLog?.(describeAvatarSummary(s));
+ return { avatars: s };
+ };
const stopped = (why: string, extra: Partial<PostCaptureResult> = {}) => {
onLog?.(why);
- return { outcomes, stoppedEarly: why, ...extra };
+ return { outcomes, stoppedEarly: why, ...extra, ...withAvatars() };
};
try {
@@ -404,7 +441,19 @@ export async function captureXPosts(
thread: threadOwed
? { replyTo: arch?.replyTo ?? null, ownHandle: arch?.author, redact: threadRedactFor(input.threadRedact, id) }
: null,
+ avatars: wanted.avatars ? avatarReadOptions(wanted.thread, arch) : null,
});
+ if (res.avatars?.length) {
+ await saveXAvatars(browser.page, res.avatars, {
+ dir: avatarDir,
+ postId: id,
+ force: wanted.force,
+ seen: avatarSeen,
+ summary: avatarSummary,
+ now,
+ onLog,
+ });
+ }
if (work.shot) {
state = res.state;
sensitive = res.sensitive;
@@ -531,7 +580,102 @@ export async function captureXPosts(
);
}
}
- return { outcomes };
+ return { outcomes, ...withAvatars() };
+ } finally {
+ await browser?.close().catch(() => {});
+ }
+}
+
+type ArchivedForAvatars = { author?: string; isReply?: boolean; replyTo?: { id: string } } | undefined;
+
+// What the avatar read looks for on one post's page: its author's always;
+// with the thread on, the post it answers (unless the archive says it is no
+// reply) and the post it quotes.
+function avatarReadOptions(thread: boolean, arch: ArchivedForAvatars): XAvatarReadOptions {
+ if (!thread) return {};
+ const noReply = !!arch && arch.isReply === false && !arch.replyTo;
+ return { parent: !noReply, quotes: true, parentId: arch?.replyTo?.id ?? null };
+}
+
+// `avatarsOnly`: one post page per distinct archived author (the first id of
+// each; an author the store has is not loaded unless `force`), the avatars
+// read off it and saved — no shot, no media, no article, no thread shot, and
+// no capture record or availability: `outcomes` stays empty. Paced like every
+// other X contact, and stopped like one by a login wall or X refusing.
+async function captureXAvatarsOnly(input: PostCaptureInput, deps: XCaptureDeps): Promise<PostCaptureResult> {
+ const { signal, onLog } = input;
+ const force = input.force ?? false;
+ const thread = input.thread ?? false;
+ const now = deps.now ?? (() => new Date());
+ const dir = xAvatarsDir(input.outDir);
+ const summary = emptyAvatarSummary();
+ const seen = new Set<string>();
+ const store = await readXAvatarIndex(dir);
+
+ // The pages owed: the first id of each archived author not yet stored.
+ const authorKeys = new Set<string>();
+ const picks: string[] = [];
+ for (const id of input.ids) {
+ const author = input.archived?.get(id)?.author?.replace(/^@/, "");
+ const key = author ? author.toLowerCase() : `#${id}`;
+ if (authorKeys.has(key)) continue;
+ authorKeys.add(key);
+ if (author && !force && lookupXAvatar(store, author)) {
+ summary.skipped.push(author);
+ onLog?.(`@${author}: avatar already stored — skipped (no page load).`);
+ continue;
+ }
+ picks.push(id);
+ }
+ onLog?.(`Avatars only: ${picks.length} post page(s) to load, one per author.`);
+
+ let contacts = 0;
+ let errorsInARow = 0;
+ let browser: { page: PageLike; close: () => Promise<void> } | undefined;
+ const done = (extra: Partial<PostCaptureResult> = {}): PostCaptureResult => {
+ onLog?.(describeAvatarSummary(summary));
+ return { outcomes: [], avatars: summary, ...extra };
+ };
+ const stopped = (why: string, extra: Partial<PostCaptureResult> = {}) => {
+ onLog?.(why);
+ return done({ stoppedEarly: why, ...extra });
+ };
+ try {
+ for (const [i, id] of picks.entries()) {
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ if (input.drain?.aborted) return stopped("Drained; the rest are left for a later run.");
+ if (contacts++ > 0) await deps.pause(deps.pauseMs(), signal);
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ onLog?.(`[${i + 1}/${picks.length}] ${id} (for its author's avatar)`);
+ browser ??= await deps.openPage();
+ summary.pages++;
+ const arch = input.archived?.get(id);
+ const res = await shootXPost(browser.page, id, postCaptureDir(input.outDir, id), onLog, {
+ own: false,
+ thread: null,
+ avatars: avatarReadOptions(thread, arch),
+ });
+ if (res.state !== "captured") {
+ const why = res.error ?? `the page showed the post as ${res.state}`;
+ onLog?.(`${id}: no avatar read — ${why}.`);
+ if (res.stop) {
+ return stopped(`${res.stop} Stopped at ${id}; the rest are left for a later run.`, {
+ needsCookies: res.state === "login-wall",
+ });
+ }
+ errorsInARow = res.state === "error" ? errorsInARow + 1 : 0;
+ if (errorsInARow >= STOP_AFTER_ERRORS) {
+ return stopped(`${STOP_AFTER_ERRORS} pages in a row failed; stopping rather than paging through the rest.`);
+ }
+ continue;
+ }
+ errorsInARow = 0;
+ if (!res.avatars?.some((a) => a.role === "author")) onLog?.(`${id}: no author avatar found on the page.`);
+ if (res.avatars?.length) {
+ await saveXAvatars(browser.page, res.avatars, { dir, postId: id, force, seen, summary, now, onLog });
+ }
+ }
+ return done();
} finally {
await browser?.close().catch(() => {});
}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **X post captures keep the authors' avatars.** A post card showed an initial letter because the posts archive keeps no profile pictures. `capture-posts` on an X channel now reads the post author's avatar off the page it already loads for the shot (with `"thread": true`, the replied-to and quoted authors' too) and saves it at 400×400, fetched through the same browser context with no extra page load, into `posts-media/_avatars/<handle>.<ext>` and `avatars.json` — once per author, an author already stored skipped unless `"force": true`; `"avatars": false` turns it off. `"avatarsOnly": true` loads one post page per distinct archived author for the avatars alone and writes nothing else (no shot, media, record or availability): `pnpm ops capture-posts --json '{"slug":"<x-channel>","ids":["<one post id>"],"avatarsOnly":true}' --wait`. X's default picture is not stored. Needs a restart of the editor.
- **A research case can be verified, its leads decided and its evidence captured, all in umtool.** The case pipeline page gains **7 Verify**, **8 Leads** and **10 Evidence**. **Verify** shows each finding's moment in every caption track side by side — the original audio's captions beside the uploaded `en` ones, the quote's words lit where they land and "holds the quote" or "4 of 5 words" on each — and an **Audio check** that has the editor transcribe the window on a local worker (its held media, or a clip fetched through it; **Run even while transcription is paused** for a pause-all) and diffs what was heard with the quote ("Heard 9 of 9 words"). A finding is marked Verified, Corrected, Disputed, Unverified or Quarantined (one first seen on a forum says so); **Correct by hand** keeps the reader's words ("The reader wrote: …"). **Leads** lists the accounts and pages a forum or posts channel links most, counted by post, with the posts around each on demand; **Never archive** makes the lead's name one of the case's private names — stored as its hash, never as text, and withheld from then on — and **Archive** creates its channel through the editor on no site and starts its first fetch (**Older walk** after). **Evidence** takes Wayback captures of a list of pages at chosen dates (a page the Wayback Machine will not show is the row "excluded from the Wayback Machine (cause unknown)") and a forum post's attachments and screenshot, shown everywhere as "forum attachment, post #N, unverified", attached to the findings they back and listed in the exported report's Evidence section. Any quote, note or role typed by hand that holds one of the case's private names is refused by the privacy gate, with the row and a count, never the name. Needs a restart of umtool.
- **Newgrounds pages are read whole.** A Wayback capture of a 2014 Newgrounds user page used to come out as one small block of it: the page keeps its profile, stats, links and news in many small boxes the generic extractor dropped. A user page (`<user>.newgrounds.com/`) is now read box by box — "Profile", "Location: …", "Joined on: …", its links — and an art page or a movie page is one record per work (its title, author, comments, image or file, tags, credits and date) that later captures update. A channel imported before this is put right by **Re-extract** (`reextract-pages`), from the captures it already keeps; nothing is fetched. Needs a restart of the editor.
- **A Wayback scan goes on past a page the archive excludes.** A target the Wayback Machine answers 403 for stopped the whole `wayback-scan` as an error. Now that target is marked "excluded from the Wayback Machine (cause unknown)" on the Captures tab (and `refusal: "excluded"` in the scan's result), it is done for this pass, and the next target is scanned. A new pass asks again. Needs a restart of the editor.
diff --git a/editor/app/api/ops/capture-posts/route.test.ts b/editor/app/api/ops/capture-posts/route.test.ts
@@ -167,3 +167,30 @@ test("capture-posts refuses what it cannot capture, and an id not in the archive
assert.deepEqual(await readdir(path.join(ROOT, ".jobs")).catch(() => []), []);
});
+
+test("avatars and avatarsOnly: booleans; avatarsOnly is a run of its own, X's only — refused before any job", async () => {
+ for (const key of ["avatars", "avatarsOnly"]) {
+ const bad = await post({ slug: SLUG, ids: ["111"], [key]: "yes" });
+ assert.equal(bad.status, 400, key);
+ assert.match(bad.error, new RegExp(`"${key}" must be a boolean`));
+ }
+ // Both halves off is no refusal for an avatars-only run: past it, to the
+ // next one (an id not archived).
+ const stray = await post({ slug: SLUG, ids: ["999"], shots: false, media: false, avatarsOnly: true });
+ assert.equal(stray.status, 400);
+ assert.equal(stray.error, "1 id(s) not in demo-x's posts archive: 999");
+ // Another platform keeps none.
+ await channel("example-bsky-avatars", {
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "bluesky",
+ postFetcher: "bluesky-atproto",
+ socialHandle: "example.bsky.social",
+ name: "Example (Bluesky)",
+ url: "https://bsky.app/profile/example.bsky.social",
+ });
+ const bsky = await post({ slug: "example-bsky-avatars", ids: ["1"], avatarsOnly: true });
+ assert.equal(bsky.status, 400);
+ assert.match(bsky.error, /^Avatars are X's only; .* keeps none\.$/);
+ assert.deepEqual(await readdir(path.join(ROOT, ".jobs")).catch(() => []), []);
+});
diff --git a/editor/app/api/ops/capture-posts/route.ts b/editor/app/api/ops/capture-posts/route.ts
@@ -10,7 +10,7 @@ import {
export const dynamic = "force-dynamic";
-// POST { slug, ids, shots?, media?, force?, articles?, thread?, threadRedact?, queueKey? } -> { ok: true, jobId }
+// POST { slug, ids, shots?, media?, force?, articles?, thread?, threadRedact?, avatars?, avatarsOnly?, queueKey? } -> { ok: true, jobId }
//
// Capture specific archived posts of a social channel: a screenshot of each
// (`shots`, default true) and its attached media (`media`, default true), into
@@ -25,14 +25,23 @@ export const dynamic = "force-dynamic";
// skipped unless `force`. The job runs on the platform's queue, as a post
// fetch does.
//
+// X keeps each post author's AVATAR, read off the page the shot loads (with
+// `thread`, the replied-to and quoted authors' too), in
+// `posts-media/_avatars/<handle>.<ext>` + `avatars.json` -- `avatars: false`
+// turns that off. `avatarsOnly: true` loads ONE post page per distinct
+// archived author for the avatars alone: no shot, media, article or thread
+// shot, no capture record, no availability; an author already stored is
+// skipped unless `force`. One author's avatar is one page load:
+// {"slug":"ObviousRises-x","ids":["<one of his post ids>"],"avatarsOnly":true}
+//
// Every refusal is the action's own sentence: both halves off (an
// articles-only run names `articles: true`), a channel that
// is not a social one, a fetcher that cannot capture, an id not in the
-// channel's posts archive.
+// channel's posts archive, `avatarsOnly` on a channel that is not X.
export async function POST(request: Request) {
return ops(
request,
- ["slug", "ids", "shots", "media", "force", "articles", "thread", "threadRedact", "queueKey"],
+ ["slug", "ids", "shots", "media", "force", "articles", "thread", "threadRedact", "avatars", "avatarsOnly", "queueKey"],
async (body) => {
const slug = reqSlug(body, "slug");
return jobResponse(
@@ -44,7 +53,12 @@ export async function POST(request: Request) {
optBool(body, "media"),
optBool(body, "force"),
optBool(body, "articles"),
- { thread: optBool(body, "thread"), threadRedact: body.threadRedact as boolean | Record<string, boolean> | undefined },
+ {
+ thread: optBool(body, "thread"),
+ threadRedact: body.threadRedact as boolean | Record<string, boolean> | undefined,
+ avatars: optBool(body, "avatars"),
+ avatarsOnly: optBool(body, "avatarsOnly"),
+ },
),
);
},
diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts
@@ -43,6 +43,7 @@ import {
type CheckPostAvailabilityMode,
} from "yt-dlp-transcript-common/controller/checkPostAvailability";
import {
+ avatarsOnlyProblem,
capturePosts,
capturePostsProblem,
NOTHING_TO_CAPTURE,
@@ -302,7 +303,10 @@ export async function fetchPostsAction(
// links to an X Article gets the article too unless `articles` is false. An X
// reply gets its thread shot (the post it answers over it) with `thread`
// (default: the channel's `postCaptureThread`), its parent's author blurred
-// by the rule unless `threadRedact` says otherwise.
+// by the rule unless `threadRedact` says otherwise. X keeps the authors'
+// avatars from the pages it loads (`avatars: false` turns that off);
+// `avatarsOnly` loads one page per archived author for them alone (X only,
+// refused here elsewhere).
export async function capturePostsAction(
slug: string,
ids: string[],
@@ -311,13 +315,13 @@ export async function capturePostsAction(
media?: boolean,
force?: boolean,
articles?: boolean,
- more: { thread?: boolean; threadRedact?: ThreadRedactKnob } = {},
+ more: { thread?: boolean; threadRedact?: ThreadRedactKnob; avatars?: boolean; avatarsOnly?: boolean } = {},
): Promise<StreamActionResult> {
- const { thread } = more;
+ const { thread, avatars, avatarsOnly } = more;
const redact = parseThreadRedact(more.threadRedact);
if (!redact.ok) return { ok: false, error: redact.error };
const threadRedact = redact.value;
- if (nothingToCapture({ shots, media, articles, thread })) return { ok: false, error: NOTHING_TO_CAPTURE };
+ if (nothingToCapture({ shots, media, articles, thread, avatarsOnly })) return { ok: false, error: NOTHING_TO_CAPTURE };
const wanted = [...new Set(ids)];
if (wanted.length === 0) return { ok: false, error: "No post ids to capture." };
const paths = getPaths();
@@ -329,12 +333,14 @@ export async function capturePostsAction(
// A Wayback pages channel has no fetcher: its records are rendered from
// their captures, on archive.org's queue (release 37 S4).
const pages = isWaybackPagesChannel(config);
+ if (pages && avatarsOnly) return { ok: false, error: avatarsOnlyProblem(undefined, "a Wayback pages channel")! };
if (!pages) {
await registerBuiltinSocialFetchers();
- const problem = capturePostsProblem(
- resolveSocialFetcher(config.postFetcher, config.url),
- );
+ const fetcher = resolveSocialFetcher(config.postFetcher, config.url);
+ const problem = capturePostsProblem(fetcher);
if (problem) return { ok: false, error: problem };
+ const nope = avatarsOnly ? avatarsOnlyProblem(fetcher?.platform, fetcher?.label ?? "") : null;
+ if (nope) return { ok: false, error: nope };
}
const stray = strayCaptureIds(
wanted,
@@ -355,6 +361,8 @@ export async function capturePostsAction(
queueKey, ids: wanted, shots, media, force, articles,
...(thread !== undefined ? { thread } : {}),
...(threadRedact !== undefined ? { threadRedact } : {}),
+ ...(avatars !== undefined ? { avatars } : {}),
+ ...(avatarsOnly ? { avatarsOnly } : {}),
},
},
fn: async (onLog, signal, _progress, ctx) => {
@@ -369,6 +377,8 @@ export async function capturePostsAction(
articles,
thread,
threadRedact,
+ avatars,
+ avatarsOnly,
onLog,
signal,
drain: ctx.drainSignal,
diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts
@@ -443,6 +443,8 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = {
thread: bool(p.thread),
// A boolean or { id: boolean }; the action refuses any other shape.
threadRedact: p.threadRedact as boolean | Record<string, boolean> | undefined,
+ avatars: bool(p.avatars),
+ avatarsOnly: bool(p.avatarsOnly),
},
);
},
diff --git a/editor/e2e/capture-posts.spec.ts b/editor/e2e/capture-posts.spec.ts
@@ -123,6 +123,16 @@ test("capture-posts on a Bluesky channel: shots cropped to the post, its images,
`/profile/${HANDLE}/post/${withImages}`,
`/profile/${HANDLE}/post/${textOnly}`,
]);
+
+ // Avatars are X's: a Bluesky capture keeps none, and an avatars-only
+ // run here is refused by name before any job.
+ expect(await readdir(media)).not.toContain("_avatars");
+ const av = await request.post(`${baseUrl}/api/ops/capture-posts`, {
+ headers: AUTH,
+ data: { slug: SLUG, ids, avatarsOnly: true },
+ });
+ expect(av.status()).toBe(400);
+ expect(((await av.json()) as { error?: string }).error).toMatch(/^Avatars are X's only; .* keeps none\.$/);
} finally {
await rm(originFile, { force: true });
await bsky.close();
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -1535,8 +1535,16 @@ export function usage() {
' shot-thread.png beside shot.png (a post shot before gets only that);',
' the replied-to author\'s avatar, name and handle are blurred unless',
' verified or the reply\'s own. "threadRedact": false turns the blur off,',
- ' true blurs any author; {"<id>": false} sets it per post. Paced like a',
- ' post fetch, on its queue.',
+ ' true blurs any author; {"<id>": false} sets it per post. X also keeps',
+ ' each author\'s avatar, read off the page the shot loads (with "thread",',
+ ' the replied-to and quoted authors\' too), in',
+ ' posts-media/_avatars/<handle>.<ext> + avatars.json; an author already',
+ ' stored is not fetched again unless "force". "avatars": false turns that',
+ ' off. "avatarsOnly": true (X) loads ONE post page per distinct archived',
+ ' author for the avatars alone -- no shot, media, article or thread shot,',
+ ' no capture record, no availability: one author\'s avatar is',
+ ' {"slug", "ids": ["<one of their post ids>"], "avatarsOnly": true}.',
+ ' Paced like a post fetch, on its queue.',
"",
'persist-videos saves specific videos, across channels, to the saved-video',
' store: {"items": [{"slug", "id"}, ...]}. "format": "original" |',