Archilyzer · Source

archilyzer

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

commit f466d5b90060ddb640009b37e1051c702a2fef1f
parent 19ab80fe4924cc5a83c31e00e2b45a8307616a57
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 28 Oct 2026 22:43:33 -0400

Merge lane/reply-parent: an X reply's thread shot (the post it answers over it, its author blurred) and posts[].thread in report videos

- capture-posts: an X reply can also write shot-thread.png beside shot.png,
  the union from its immediate parent to the reply, shot from the window;
  the parent's avatar, name and handle blurred unless it carries an
  organisation's gold or a government's grey check (a blue check is blurred).
- umtool: a manifest post's `thread: true` draws the thread shot in place of
  its shot; the feed draws it whole (scaled to fit, never cut).
- Writers: updatePosts / normalizePostPatches / applyPostsDraft / upsertPost
  take `thread`; `umtool posts add --thread`, new `umtool posts set`; the
  On-screen Posts table's thread box.
- Docs: knobs.md, cli.md, OPERATING.md, CHANGELOG, COMMANDS.md.

Conflicts: editor/CHANGELOG.md -- both sides' Unreleased bullets kept.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MCHANNEL.md | 1+
MCOMMANDS.md | 2+-
MOPERATING.md | 13+++++++++++++
Mcommon/controller/capturePosts.test.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/capturePosts.ts | 51++++++++++++++++++++++++++++++++++++++++++++++-----
Mcommon/lib/channelConfig.ts | 4++++
Mcommon/lib/channelConfigSchema.test.ts | 2+-
Mcommon/lib/channelConfigSchema.ts | 1+
Mcommon/lib/report/draft/research/tools.ts | 7++++---
Mcommon/social/fetchers.ts | 11+++++++++++
Mcommon/social/postCapture.test.ts | 49++++++++++++++++++++++++++++++++++++++++---------
Mcommon/social/postCapture.ts | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/social/viewportShot.test.ts | 34+++++++++++++++++++++++++++++++++-
Mcommon/social/viewportShot.ts | 37++++++++++++++++++++++++++++++-------
Mcommon/social/xPostCapture.ts | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Acommon/social/xThreadShot.test.ts | 368+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/xThreadShot.ts | 357+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 2++
Meditor/app/api/ops/capture-posts/route.test.ts | 16++++++++++++++++
Meditor/app/api/ops/capture-posts/route.ts | 14++++++++++----
Meditor/app/channels/[slug]/components/SocialChannelPanel.tsx | 5++++-
Meditor/app/channels/[slug]/components/SocialPostTools.tsx | 28+++++++++++++++++++++++++---
Meditor/app/channels/[slug]/page.tsx | 2++
Meditor/app/channels/[slug]/socialActions.ts | 22+++++++++++++++++++---
Meditor/app/jobs/jobReplayRegistry.ts | 5+++++
Mscripts/archilyzer-ops.mjs | 8+++++++-
Mumtool/app/api/report/onscreen/route.ts | 14+++++++++++++-
Mumtool/app/api/report/posts/route.ts | 14++++++++------
Mumtool/bin/umtool.mjs | 10+++++++---
Mumtool/components/projects/OnscreenSection.tsx | 30++++++++++++++++++++++++++----
Mumtool/docs/cli.md | 3++-
Mumtool/docs/knobs.md | 1+
Mumtool/lib/report/manifest.mjs | 45++++++++++++++++++++++++++++-----------------
Mumtool/lib/report/manifest.test.mjs | 25++++++++++++++++++++++++-
Mumtool/lib/report/onscreen.mjs | 11++++++++++-
Mumtool/lib/report/onscreen.test.mjs | 19++++++++++++++++++-
Mumtool/lib/report/postsCli.mjs | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mumtool/lib/report/postsCli.test.mjs | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/chrome-feed.mjs | 46++++++++++++++++++++++++++++++++++++++++++----
Mumtool/report-to-video/chrome-feed.test.mjs | 47++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/report-to-video/chrome-posts.test.mjs | 35++++++++++++++++++++++++++++++++++-
Mumtool/report-to-video/compose-chrome.mjs | 34++++++++++++++++++++++++++++------
Mumtool/report-to-video/deck.mjs | 28+++++++++++++++++++++++++++-
43 files changed, 1677 insertions(+), 109 deletions(-)

diff --git a/CHANNEL.md b/CHANNEL.md @@ -19,6 +19,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `postFetcher` | config | Social channels only: which social fetcher drives ingest (e.g. `"bluesky-atproto"`, `"x-gallery-dl"`). Absent = resolve by URL detection. Trimmed. | | `socialHandle` | config | Social channels only: the bare account handle (a leading "@" is stripped). Derived from `url` at creation but stored, so a later URL-format change upstream cannot silently re-point ingest at a different account. | | `postPagePauseSeconds` | config | Social channels that are read page by page (a forum thread) only: the pause between two page loads, in seconds; each pause is jittered to 0.85–1.65× of it. Absent = the fetcher's own (12 s, so 10–20 s); floored at 5, capped at 600. | +| `postCaptureThread` | config | X channels only: `capture-posts` also shoots each reply's THREAD SHOT — the post it answers over the reply, `posts-media/<id>/shot-thread.png` beside `shot.png`, the parent's author blurred unless verified or the reply's own — unless the run says `"thread": false`. Absent = false (a run asks with `"thread": true`). | | `platform` | config | The source platform: youtube, rumble, odysee, twitch, kick, archiveorg (archive.org items — imported, never listed; see README.md, "archive.org items"), bitchute (BitChute videos and channels; see README.md, "BitChute"), twitter, bluesky, xenforo (a forum thread) or webpage (Wayback Machine captures of pages; see `wayback`). An unknown value is dropped. | | `name` | config | Display name. | | `url` | config | The channel / playlist / account URL syncs enumerate. Absent = the channel is never auto-synced. | diff --git a/COMMANDS.md b/COMMANDS.md @@ -130,7 +130,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/&lt;id&gt;/: {"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. 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/&lt;id&gt;/: {"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; {"&lt;id&gt;": false} sets it per post. 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": "&lt;branch&gt;", 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 &lt;id&gt; in &lt;dir&gt; — archilyzer publish build &lt;id&gt;". `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 @@ -369,6 +369,19 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait age in minutes, the limit, `allowed`, and the refusal an X job would get (`reason`). An agent asks it first and, when `allowed` is false, asks the operator for a refresh instead of queueing. - `capture-posts` saves a screenshot and the attached media of named posts (and a linked X Article). + **A reply with the post it answers**: `"thread": true` (X; a channel's `postCaptureThread` makes it the + default) also writes `shot-thread.png` beside `shot.png` — the immediate parent over the reply, one page + load for both, and a post shot before gets only that. The replied-to author's avatar, name and handle (and + any link to them in the reply) are blurred unless they carry an organisation's gold or a government's grey + check, or are the reply's own author; X Premium's blue check is bought, so a blue-checked person is blurred + too. `"threadRedact": false` (or `{"<id>": false}` for one post) takes it unblurred, for an author you have + judged public. `capture.json`'s `thread` records the parent, its badge and every blurred box. A report + video draws it with `umtool posts set <project> <post> thread=on` (or `posts add … --thread`): + + ```sh + pnpm ops capture-posts --json '{"slug":"example-x-replies","ids":["<postId>"],"thread":true}' --wait + umtool posts set <project> <postId> thread=on + ``` - 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 @@ -218,6 +218,69 @@ test("the articles: on by default, refused alone only when not asked for by name assert.equal(calls[0].articles, true); }); +test("the thread shots (X): off by default, the run's word or the channel's, each reply's parent id passed", async () => { + const root = path.join(channelsDir, "demo-x-replies"); + await mkdir(root, { recursive: true }); + const config = { + handling: "transcribe", + sourceKind: "social", + platform: "twitter", + postFetcher: "test-capture-x", + socialHandle: "example_user", + name: "Example (X replies)", + url: "https://x.com/example_user", + }; + await writeFile(path.join(root, "config.json"), JSON.stringify(config)); + const base = { + channelSlug: "demo-x-replies", author: "example_user", createdAt: "2026-10-25T04:34:32.000Z", uploadDate: "20261025", + platform: "twitter" as const, isRepost: false, links: [], + }; + await writePosts(root, [ + { + ...base, id: "501", slug: "demo-x-replies/501", text: "@someone Well..", url: "https://x.com/example_user/status/501", isReply: true, + replyTo: { platform: "twitter" as const, id: "500", author: "someone" }, + }, + { ...base, id: "502", slug: "demo-x-replies/502", text: "a post", url: "https://x.com/example_user/status/502", isReply: false }, + ]); + answer = { outcomes: [] }; + + calls = []; + assert.equal((await run("demo-x-replies", ["501"], { articles: false })).ok, true); + assert.equal(calls[0].thread, false); + assert.equal(calls[0].archived, undefined, "nothing read for a run with no articles and no thread"); + + calls = []; + assert.equal((await run("demo-x-replies", ["501", "502"], { thread: true, threadRedact: { "501": false } })).ok, true); + assert.equal(calls[0].thread, true); + assert.deepEqual(calls[0].threadRedact, { "501": false }); + const archived = calls[0].archived!; + assert.deepEqual(archived.get("501"), { + text: "@someone Well..", links: [], author: "example_user", isReply: true, replyTo: { id: "500", author: "someone" }, + }); + assert.equal(archived.get("502")?.isReply, false); + + // The channel's default, and the run's word over it. + await writeFile(path.join(root, "config.json"), JSON.stringify({ ...config, postCaptureThread: true })); + calls = []; + await run("demo-x-replies", ["501"]); + assert.equal(calls[0].thread, true); + calls = []; + await run("demo-x-replies", ["501"], { thread: false }); + assert.equal(calls[0].thread, false); + + // Asked for by name, the thread shots alone are a run. + calls = []; + assert.equal((await run("demo-x-replies", ["501"], { shots: false, media: false, thread: true })).ok, true); + assert.equal(calls.length, 1); +}); + +test("the thread shots are X's only: another platform's run takes none", async () => { + await makeChannel("demo-social-thread"); + calls = []; + await run("demo-social-thread", ["aaa"], { thread: true }); + assert.equal(calls[0].thread, false); +}); + test("a Wayback pages channel: its records rendered from their captures, no fetcher, nothing in the availability sidecar", async () => { const root = path.join(channelsDir, "demo-pages"); await mkdir(root, { recursive: true }); diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -67,6 +67,13 @@ export type CapturePostsOptions = { force?: boolean; // Also open and save the X Article a post links to. Defaults to true. articles?: boolean; + // X: also shoot a reply's thread shot (the post it answers over it, + // shot-thread.png). Defaults to the channel's `postCaptureThread`, else + // false. + thread?: boolean; + // 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; onLog?: (line: string) => void; signal?: AbortSignal; // The job's drain: stop between posts. @@ -95,16 +102,34 @@ export function capturePostsProblem( } 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).'; + '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 were asked for by -// name: their default alone does not make a run. +// 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. export function nothingToCapture(o: { shots?: boolean; media?: boolean; articles?: boolean; + thread?: boolean; }): boolean { - return o.shots === false && o.media === false && o.articles !== true; + return o.shots === false && o.media === false && o.articles !== true && o.thread !== true; +} + +// 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>; +export function parseThreadRedact(v: unknown): { ok: true; value: ThreadRedactKnob | undefined } | { ok: false; error: string } { + if (v === undefined || v === null) return { ok: true, value: undefined }; + if (typeof v === "boolean") return { ok: true, value: v }; + if (typeof v === "object" && !Array.isArray(v)) { + const out: Record<string, boolean> = {}; + for (const [k, b] of Object.entries(v as Record<string, unknown>)) { + if (typeof b !== "boolean") return { ok: false, error: `"threadRedact" for ${k} must be true or false` }; + out[k] = b; + } + return { ok: true, value: out }; + } + return { ok: false, error: '"threadRedact" must be true, false or { "<post id>": true | false }' }; } // The ids not in the channel's archive, or null when every one is. @@ -147,6 +172,9 @@ export async function capturePosts( // 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. + // The thread shot: X only, the run's word or the channel's default. + const thread = fetcher.platform === "twitter" ? (opts.thread ?? config.postCaptureThread ?? false) : false; + if (opts.thread && fetcher.platform !== "twitter") log(`Thread shots are X's only; ${fetcher.label} takes none.`); const handle = config.socialHandle ?? handleFromAccountUrl(accountUrl) ?? (isXSearchChannel(config) ? slug : ""); if (!handle) return fail(`Could not determine an account handle for ${slug}`); @@ -162,11 +190,13 @@ export async function capturePosts( url?: string; media?: { kind: string; url: string; name?: string }[]; author?: string; + isReply?: boolean; + replyTo?: { id: string; author?: string }; }; let archived: Map<string, Archived> | undefined; const forum = fetcher.platform === "xenforo"; const bluesky = fetcher.platform === "bluesky"; - if ((opts.articles !== false && fetcher.platform === "twitter") || forum || bluesky) { + if ((opts.articles !== false && fetcher.platform === "twitter") || thread || forum || bluesky) { const wanted = new Set(ids); archived = new Map(); for (const p of await readAllPosts(channelRoot)) { @@ -177,6 +207,14 @@ 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 } : {}), + // The thread shot tells the parent by the id the reply answers. + ...(thread + ? { + author: p.author, + isReply: p.isReply, + ...(p.replyTo ? { replyTo: { id: p.replyTo.id, ...(p.replyTo.author ? { author: p.replyTo.author } : {}) } } : {}), + } + : {}), }); } } @@ -193,6 +231,7 @@ export async function capturePosts( opts.shots === false ? "" : " screenshot", opts.media === false ? "" : " media", opts.articles === false || fetcher.platform !== "twitter" ? "" : " articles", + thread ? ` thread shots${opts.threadRedact === false ? " (no blur)" : ""}` : "", ].join("") + (opts.force ? ", again where already captured" : "") + ".", @@ -213,6 +252,8 @@ export async function capturePosts( media: opts.media, force: opts.force, articles: opts.articles, + thread, + ...(opts.threadRedact !== undefined ? { threadRedact: opts.threadRedact } : {}), archived, cookies: alwaysCookies(policy), cookieSource: xLogin?.source, diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -171,6 +171,7 @@ export type ChannelConfig = { postFetcher?: string; socialHandle?: string; postPagePauseSeconds?: number; + postCaptureThread?: boolean; platform?: Platform; name?: string; url?: string; @@ -225,6 +226,8 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { 'Social channels only: the bare account handle (a leading "@" is stripped). Derived from `url` at creation but stored, so a later URL-format change upstream cannot silently re-point ingest at a different account.', postPagePauseSeconds: "Social channels that are read page by page (a forum thread) only: the pause between two page loads, in seconds; each pause is jittered to 0.85–1.65× of it. Absent = the fetcher's own (12 s, so 10–20 s); floored at 5, capped at 600.", + postCaptureThread: + 'X channels only: `capture-posts` also shoots each reply\'s THREAD SHOT — the post it answers over the reply, `posts-media/<id>/shot-thread.png` beside `shot.png`, the parent\'s author blurred unless verified or the reply\'s own — unless the run says `"thread": false`. Absent = false (a run asks with `"thread": true`).', platform: "The source platform: youtube, rumble, odysee, twitch, kick, archiveorg (archive.org items — imported, never listed; see README.md, \"archive.org items\"), bitchute (BitChute videos and channels; see README.md, \"BitChute\"), twitter, bluesky, xenforo (a forum thread) or webpage (Wayback Machine captures of pages; see `wayback`). An unknown value is dropped.", name: "Display name.", url: "The channel / playlist / account URL syncs enumerate. Absent = the channel is never auto-synced.", @@ -448,6 +451,7 @@ export const CHANNEL_CONFIG_COERCIONS: { typeof v === "string" && v.trim() ? v.trim().replace(/^@/, "") : undefined, postPagePauseSeconds: (v) => isFiniteNumber(v) && v > 0 ? Math.min(Math.max(Math.floor(v), 5), 600) : undefined, + postCaptureThread: bool, platform: (v) => typeof v === "string" && PLATFORM_VALUES.includes(v as Platform) ? (v as Platform) diff --git a/common/lib/channelConfigSchema.test.ts b/common/lib/channelConfigSchema.test.ts @@ -39,7 +39,7 @@ test("one key list: docs = coercions = schema shape, sync-state keys inside it", assert.deepEqual(Object.keys(CHANNEL_CONFIG_COERCIONS), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(channelConfigObjectSchema.shape), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(CHANNEL_CONFIG_FIELD_DOCS), [...CHANNEL_CONFIG_KEYS]); - assert.equal(CHANNEL_CONFIG_KEYS.length, 39); // 2026-10-26: `chat` + assert.equal(CHANNEL_CONFIG_KEYS.length, 40); // 2026-10-27: `postCaptureThread` assert.equal(sameKeys, true); assert.equal(fits, true); for (const k of CHANNEL_SYNC_STATE_KEYS) assert.ok(CHANNEL_CONFIG_KEYS.includes(k), k); diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts @@ -48,6 +48,7 @@ export const channelConfigObjectSchema = z.object({ postFetcher: field("postFetcher"), socialHandle: field("socialHandle"), postPagePauseSeconds: field("postPagePauseSeconds"), + postCaptureThread: field("postCaptureThread"), platform: field("platform"), name: field("name"), url: field("url"), diff --git a/common/lib/report/draft/research/tools.ts b/common/lib/report/draft/research/tools.ts @@ -127,10 +127,11 @@ export const ACTION_SPECS: Record<AcquisitionAction, ActionSpec> = { "capture-posts": { action: "capture-posts", editorAction: "capture-posts", - description: "Capture archived posts of a social channel: a screenshot and the attached media of each id.", - properties: { slug: str, ids: strList, shots: bool, media: bool, articles: bool }, + 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 }, required: ["slug", "ids"], - body: (a) => pick(a, ["slug", "ids", "shots", "media", "articles"]), + body: (a) => pick(a, ["slug", "ids", "shots", "media", "articles", "thread"]), }, "import-post": { action: "import-post", diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts @@ -248,6 +248,13 @@ export type PostCaptureInput = Pick< // Also capture the long-form article a post links to (X Articles), where it // links to one. Defaults to true. articles?: boolean; + // X: also shoot a reply's thread shot -- the post it answers over it, + // `shot-thread.png` (xThreadShot.ts). Defaults to false. + thread?: boolean; + // The thread shot's blur of the parent's author: undefined is the rule + // (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>>; // 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. @@ -263,6 +270,10 @@ export type PostCaptureInput = Pick< // The post's author as archived (Bluesky: a repost is archived under the // original's author, which its lookup must name). author?: string; + // Whether it is a reply, and what it answers (X: the thread shot's + // parent is told by this id). + isReply?: boolean; + replyTo?: { id: string; author?: string }; } >; // A soft stop: no new post is started once it fires, and the one in hand diff --git a/common/social/postCapture.test.ts b/common/social/postCapture.test.ts @@ -23,6 +23,7 @@ import { postsMediaDir, readPostCapture, SHOT_FILENAME, + THREAD_SHOT_FILENAME, writePostCapture, type ArticleCaptureRecord, type PostCaptureRecord, @@ -106,28 +107,30 @@ test("availability: only what the page said about the post — never a verdict f test("what a capture owes: nothing for a settled post, only the missing half otherwise, everything when forced", () => { const all = { shots: true, media: true, force: false }; - assert.deepEqual(captureWork(null, all), { shot: true, media: true, article: false }); - assert.deepEqual(captureWork(null, { ...all, media: false }), { shot: true, media: false, article: false }); + assert.deepEqual(captureWork(null, all), { shot: true, media: true, article: false, thread: false }); + assert.deepEqual(captureWork(null, { ...all, media: false }), { shot: true, media: false, article: false, thread: false }); const done = record({ shot: { name: SHOT_FILENAME, bytes: 1, sha256: "x" }, mediaState: "ok" }); - assert.deepEqual(captureWork(done, all), { shot: false, media: false, article: false }); - assert.deepEqual(captureWork(record({ ...done, mediaState: "none" }), all), { shot: false, media: false, article: false }); + assert.deepEqual(captureWork(done, all), { shot: false, media: false, article: false, thread: false }); + assert.deepEqual(captureWork(record({ ...done, mediaState: "none" }), all), { shot: false, media: false, article: false, thread: false }); // The media failed (or was never asked for): only the media is owed. - assert.deepEqual(captureWork(record({ ...done, mediaState: "error" }), all), { shot: false, media: true, article: false }); - assert.deepEqual(captureWork(record({ ...done, mediaState: "skipped" }), all), { shot: false, media: true, article: false }); + assert.deepEqual(captureWork(record({ ...done, mediaState: "error" }), all), { shot: false, media: true, article: false, thread: false }); + assert.deepEqual(captureWork(record({ ...done, mediaState: "skipped" }), all), { shot: false, media: true, article: false, thread: false }); // A shot that failed is owed again. - assert.deepEqual(captureWork(record({ state: "error", mediaState: "ok" }), all), { shot: true, media: false, article: false }); + assert.deepEqual(captureWork(record({ state: "error", mediaState: "ok" }), all), { shot: true, media: false, article: false, thread: false }); // Deleted is settled: asking again is a request for the same answer. assert.deepEqual(captureWork(record({ state: "deleted", mediaState: "skipped" }), all), { shot: false, media: false, article: false, + thread: false, }); // force re-takes whatever was asked for. - assert.deepEqual(captureWork(done, { ...all, force: true }), { shot: true, media: true, article: false }); + assert.deepEqual(captureWork(done, { ...all, force: true }), { shot: true, media: true, article: false, thread: false }); assert.deepEqual(captureWork(record({ state: "deleted" }), { shots: false, media: true, force: true }), { shot: false, media: true, article: false, + thread: false, }); }); @@ -147,7 +150,7 @@ test("what a capture owes the article half: only when asked, settled once captur // Not asked for by name: the older callers' shape owes no article. assert.equal(captureWork(null, { shots: true, media: true, force: false }).article, false); // A post shot before articles were captured owes only its article. - assert.deepEqual(captureWork(done, all), { shot: false, media: false, article: true }); + assert.deepEqual(captureWork(done, all), { shot: false, media: false, article: true, thread: false }); for (const state of ["captured", "deleted", "unavailable"] as const) { assert.equal(captureWork(record({ ...done, article: article(state) }), all).article, false, state); } @@ -159,6 +162,34 @@ test("what a capture owes the article half: only when asked, settled once captur assert.equal(captureWork(record({ state: "deleted" }), all).article, false); }); +test("what a capture owes the thread shot: only when asked, settled once taken or found to be none, owed again after an error", () => { + const all = { shots: true, media: true, force: false, thread: true }; + const done = record({ shot: { name: SHOT_FILENAME, bytes: 1, sha256: "x" }, mediaState: "ok" }); + assert.equal(captureWork(null, all).thread, true); + assert.equal(captureWork(null, { ...all, thread: false }).thread, false); + // Not asked for: the older callers' shape owes none. + assert.equal(captureWork(done, { shots: true, media: true, force: false }).thread, false); + // A post shot before: only its thread shot is owed. + assert.deepEqual(captureWork(done, all), { shot: false, media: false, article: false, thread: true }); + const thread = { + name: THREAD_SHOT_FILENAME, bytes: 2, sha256: "y", parentId: "5", parentVerified: false, parentFrom: "reply-to" as const, + redaction: { applied: true, reason: "private" as const, boxes: [] }, + }; + assert.equal(captureWork(record({ ...done, thread }), all).thread, false); + assert.equal(captureWork(record({ ...done, threadNone: "not a reply" }), all).thread, false); + assert.equal(captureWork(record({ ...done, threadError: "the page moved" }), all).thread, true); + assert.equal(captureWork(record({ ...done, thread }), { ...all, force: true }).thread, true); + assert.equal(captureWork(record({ state: "deleted" }), all).thread, false); +}); + +test("the thread shot is not a medium of the post", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "thread-files-")); + await writeFile(path.join(dir, SHOT_FILENAME), "a"); + await writeFile(path.join(dir, THREAD_SHOT_FILENAME), "b"); + await writeFile(path.join(dir, "1_1.jpg"), "c"); + assert.deepEqual(await listCapturedMediaFiles(dir), ["1_1.jpg"]); +}); + test("article files are named by the layout, images numbered from 1", () => { assert.equal(articleImageFilename(1, "jpg"), "article-img-1.jpg"); assert.ok(isArticleFile("article.md")); diff --git a/common/social/postCapture.ts b/common/social/postCapture.ts @@ -2,6 +2,10 @@ // // Layout, per channel: // channels/<slug>/posts-media/<post id>/shot.png — the post, as rendered +// channels/<slug>/posts-media/<post id>/shot-thread.png — a reply with the +// post it answers above it (X, opt-in: `thread`), its author blurred +// unless verified or the reply's own (xPostCapture.ts); never in place +// of shot.png // channels/<slug>/posts-media/<post id>/<media…> — its attached media // channels/<slug>/posts-media/<post id>/capture.json — this module's record // channels/<slug>/posts-media/<post id>/article.* — the X Article the post @@ -30,6 +34,7 @@ import type { PostAvailability } from "../lib/posts"; export const POSTS_MEDIA_DIRNAME = "posts-media"; export const CAPTURE_FILENAME = "capture.json"; export const SHOT_FILENAME = "shot.png"; +export const THREAD_SHOT_FILENAME = "shot-thread.png"; export const ARTICLE_JSON_FILENAME = "article.json"; export const ARTICLE_MD_FILENAME = "article.md"; export const ARTICLE_SHOT_FILENAME = "article.png"; @@ -128,6 +133,46 @@ export type ArticleCaptureRecord = { error?: string; }; +// Why a thread shot's parent author was or was not blurred: +// private — the parent's author is neither verified nor the reply's own +// (the default's reason to blur) +// blue-check — the parent's author carries only X Premium's blue check, +// which anyone can buy: blurred like a private author +// verified — the parent's author carries an organisation's gold check or a +// government's grey one: not blurred +// self — a self-thread: the parent is the reply's own author's +// off — the capture (or its channel) turned the blur off +// forced — the capture asked for the blur whatever the author +export type ThreadRedactionReason = "private" | "blue-check" | "verified" | "self" | "off" | "forced"; + +// One blurred box of a thread shot, in the shot's own pixels (its top-left +// is 0,0), and what it covered. +export type RedactedBox = { + what: "avatar" | "name" | "user-name" | "mention"; + box: { x: number; y: number; width: number; height: number }; +}; + +// The thread shot: shot-thread.png (CapturedFile's `name`), the reply with +// its IMMEDIATE parent above it -- one parent only, a longer chain cut to it. +export type ThreadCaptureRecord = CapturedFile & { + parentId: string; + parentHandle?: string; + // The parent's display name as the page showed it. + parentAuthor?: string; + // Any check by the name (parentBadge says which). + parentVerified: boolean; + parentBadge?: "blue" | "gold" | "grey" | "other"; + // How the parent was told on the page: its status link matched the + // archive's in-reply-to id, or (the archive not saying) the post directly + // above the reply. + parentFrom: "reply-to" | "above"; + redaction: { + applied: boolean; + reason: ThreadRedactionReason; + boxes: RedactedBox[]; + }; +}; + export type PostCaptureRecord = { version: 1; id: string; @@ -150,6 +195,13 @@ export type PostCaptureRecord = { media: CapturedFile[]; // The X Article the post links to, when one was captured or tried. article?: ArticleCaptureRecord; + // The thread shot (X replies, asked for with `thread`), when one was taken. + thread?: ThreadCaptureRecord; + // Why a thread shot was asked for and none taken, settled: the post is not + // a reply, or its parent did not render above it. A failure that may pass + // is `threadError` instead, and owed again. + threadNone?: string; + threadError?: string; error?: string; }; @@ -189,6 +241,7 @@ export async function listCapturedMediaFiles(dir: string): Promise<string[]> { .filter( (n) => n !== SHOT_FILENAME && + n !== THREAD_SHOT_FILENAME && n !== CAPTURE_FILENAME && !isArticleFile(n) && !n.endsWith(".part") && @@ -222,15 +275,18 @@ export async function writePostCapture( // media download that did not finish ("error", or never attempted) is owed. // The article half is owed only if the post links to one (the caller knows); // one captured, deleted or walled is settled, one that failed is owed. +// The thread shot is owed when asked for and neither taken nor settled as +// none (not a reply, no parent shown); one that failed is owed again. export function captureWork( existing: PostCaptureRecord | null, - wanted: { shots: boolean; media: boolean; force: boolean; articles?: boolean }, -): { shot: boolean; media: boolean; article: boolean } { + wanted: { shots: boolean; media: boolean; force: boolean; articles?: boolean; thread?: boolean }, +): { shot: boolean; media: boolean; article: boolean; thread: boolean } { const articles = wanted.articles ?? false; + const thread = wanted.thread ?? false; if (wanted.force || !existing) { - return { shot: wanted.shots, media: wanted.media, article: articles }; + return { shot: wanted.shots, media: wanted.media, article: articles, thread }; } - if (existing.state === "deleted") return { shot: false, media: false, article: false }; + if (existing.state === "deleted") return { shot: false, media: false, article: false, thread: false }; return { shot: wanted.shots && !existing.shot, media: @@ -238,6 +294,7 @@ export function captureWork( existing.mediaState !== "ok" && existing.mediaState !== "none", article: articles && !articleSettled(existing.article), + thread: thread && !existing.thread && !existing.threadNone, }; } diff --git a/common/social/viewportShot.test.ts b/common/social/viewportShot.test.ts @@ -7,7 +7,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import type { PageLike } from "./playwrightRuntime"; -import { shootFromViewport, TOP_ROOM, VIEW_SCRIPT_MARKER, type ElementView } from "./viewportShot"; +import { shootFromViewport, TOP_ROOM, unionBox, VIEW_SCRIPT_MARKER, viewScript, type ElementView } from "./viewportShot"; const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47]); @@ -153,3 +153,35 @@ test("the window is put back even when the shot throws", async () => { await assert.rejects(shootFromViewport(p, { selector: SEL, settleMs: 0 }), /Target closed/); assert.deepEqual(p.sizes.at(-1), { width: 1280, height: 720 }); }); + +test("a selector list is measured as ONE box, their union, by the page's own script", () => { + const rects: Record<string, { left: number; top: number; right: number; bottom: number }> = { + "[p]": { left: 283, top: -200, right: 881, bottom: 20 }, + "[o]": { left: 283, top: 20, right: 881, bottom: 300 }, + }; + const g = globalThis as Record<string, unknown>; + const saved = { document: g.document, window: g.window }; + g.document = { + querySelector: (s: string) => + rects[s] + ? { getBoundingClientRect: () => ({ ...rects[s], width: rects[s].right - rects[s].left, height: rects[s].bottom - rects[s].top }) } + : null, + }; + g.window = { innerWidth: 1280, innerHeight: 720 }; + try { + assert.deepEqual((0, eval)(viewScript(["[p]", "[o]"])), { x: 283, y: -200, width: 598, height: 500, vw: 1280, vh: 720 }); + assert.deepEqual((0, eval)(viewScript("[o]")), { x: 283, y: 20, width: 598, height: 280, vw: 1280, vh: 720 }); + // One of them missing: nothing to shoot as the union. + assert.equal((0, eval)(viewScript(["[p]", "[gone]"])), null); + } finally { + g.document = saved.document; + g.window = saved.window; + } + assert.deepEqual( + unionBox([ + { x: 283, y: -200, width: 598, height: 220 }, + { x: 283, y: 20, width: 598, height: 280 }, + ]), + { x: 283, y: -200, width: 598, height: 500 }, + ); +}); diff --git a/common/social/viewportShot.ts b/common/social/viewportShot.ts @@ -38,8 +38,9 @@ export type ElementView = { export type ViewportShotOptions = { // The element, as a selector the page can query (a marker attribute the - // caller set). - selector: string; + // caller set) -- or several, shot as ONE box: their union (a reply's thread + // shot, its parent's article over its own). Every one must be on the page. + selector: string | ReadonlyArray<string>; // Shoot at most this much of the element's height, from its top. maxHeight?: number; // The tallest window it will grow to (default 16 384 px). @@ -65,12 +66,34 @@ const MOVED_PX = 1; export const VIEW_SCRIPT_MARKER = "__archilyzerElementView"; -export const viewScript = (selector: string) => `(() => { +// The smallest box holding every one of `boxes` (null for none): what a +// selector list is shot as. The page runs the same arithmetic (viewScript). +export function unionBox( + boxes: ReadonlyArray<{ x: number; y: number; width: number; height: number }>, +): { x: number; y: number; width: number; height: number } | null { + if (boxes.length === 0) return null; + const left = Math.min(...boxes.map((b) => b.x)); + const top = Math.min(...boxes.map((b) => b.y)); + const right = Math.max(...boxes.map((b) => b.x + b.width)); + const bottom = Math.max(...boxes.map((b) => b.y + b.height)); + return { x: left, y: top, width: right - left, height: bottom - top }; +} + +export const viewScript = (selector: string | ReadonlyArray<string>) => `(() => { const ${VIEW_SCRIPT_MARKER} = true; - const el = document.querySelector(${JSON.stringify(selector)}); - if (!el) return null; - const r = el.getBoundingClientRect(); - return { x: r.left, y: r.top, width: r.width, height: r.height, vw: window.innerWidth, vh: window.innerHeight }; + const sels = ${JSON.stringify(typeof selector === "string" ? [selector] : [...selector])}; + const rs = []; + for (const s of sels) { + const el = document.querySelector(s); + if (!el) return null; + rs.push(el.getBoundingClientRect()); + } + if (!rs.length) return null; + const left = Math.min(...rs.map((r) => r.left)); + const top = Math.min(...rs.map((r) => r.top)); + const right = Math.max(...rs.map((r) => r.right)); + const bottom = Math.max(...rs.map((r) => r.bottom)); + return { x: left, y: top, width: right - left, height: bottom - top, vw: window.innerWidth, vh: window.innerHeight }; })()`; const scrollScript = (dy: number) => `window.scrollBy(0, ${Math.round(dy)})`; diff --git a/common/social/xPostCapture.ts b/common/social/xPostCapture.ts @@ -25,6 +25,11 @@ // or on its rendered card — and the run then opens the article too, one more // paced contact (xArticleCapture.ts), unless `articles` is off. // +// With `thread` (opt-in), a reply also gets its THREAD SHOT in the same page +// load: the post it answers over the reply, `shot-thread.png`, the parent's +// author blurred unless verified or the reply's own (xThreadShot.ts). A post +// the archive says is no reply is not opened for it. +// // 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. @@ -54,6 +59,7 @@ import { import { xArticleLinkFromArchive, type XArticleLink } from "./xArticle"; import { captureXArticle, xArticleLinkFromCard } from "./xArticleCapture"; import { shootFromViewport } from "./viewportShot"; +import { shootXThread, type ThreadShotOptions, type ThreadShotResult } from "./xThreadShot"; // The post's own article, marked by the snapshot. const CAPTURE_SELECTOR = "[data-archilyzer-capture]"; @@ -201,16 +207,27 @@ export type XShotResult = XPostVerdict & { shot?: CapturedFile; // The X Article the post's card links to, when it does. articleLink?: XArticleLink; + // The thread shot, when one was asked for and the post rendered. + thread?: ThreadShotResult; +}; + +export type XShotOptions = { + // Shoot the post's own article (default true): false for a run that owes + // only the thread shot of a post shot before. + own?: boolean; + // The thread shot too (xThreadShot.ts), after the post's own. + thread?: Omit<ThreadShotOptions, "onLog" | "url"> | null; }; // One post's screenshot: load, read the page, open a sensitive cover, shoot // the post's own article. Writes `shot.png` into `dir` only for a post that -// rendered. +// rendered (and `shot-thread.png`, asked for, for a reply). export async function shootXPost( page: PageLike, id: string, dir: string, onLog?: (line: string) => void, + opts: XShotOptions = {}, ): Promise<XShotResult> { const url = xStatusUrl(id); try { @@ -244,6 +261,11 @@ export async function shootXPost( if (!rect || rect.width < 1 || rect.height < 1) { return { state: "error", error: "The post rendered with no size to shoot." }; } + const articleLink = xArticleLinkFromCard(snap.article?.articleHrefs); + if (opts.own === false) { + const thread = opts.thread ? await shootXThread(page, id, dir, { ...opts.thread, url, onLog }) : undefined; + return { ...verdict, ...(articleLink ? { articleLink } : {}), ...(thread ? { thread } : {}) }; + } let png: Uint8Array; try { // From the window, the post made to fit it: a full-page capture resizes @@ -274,8 +296,9 @@ export async function shootXPost( await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, SHOT_FILENAME), png); const shot = await describeCapturedFile(dir, SHOT_FILENAME, url); - const articleLink = xArticleLinkFromCard(snap.article?.articleHrefs); - return { ...verdict, shot, ...(articleLink ? { articleLink } : {}) }; + // 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 } : {}) }; } export type MediaDownloadResult = @@ -318,6 +341,7 @@ export async function captureXPosts( media: input.media ?? true, force: input.force ?? false, articles: input.articles ?? true, + thread: input.thread ?? false, }; const now = deps.now ?? (() => new Date()); const outcomes: PostCaptureOutcome[] = []; @@ -348,7 +372,18 @@ export async function captureXPosts( : null; const articleOwedNow = work.article && !!articleLink && (!existing || work.shot || existing.state === "captured"); - if (!work.shot && !work.media && !articleOwedNow) { + // The thread shot: not for a post the archive says is no reply (no page + // load for it), nor for one a page already said is not there. + const arch = input.archived?.get(id); + let thread = work.thread ? undefined : existing?.thread; + let threadNone = work.thread ? undefined : existing?.threadNone; + let threadError = work.thread ? undefined : existing?.threadError; + let threadOwed = work.thread && (!existing || work.shot || existing.state === "captured"); + if (threadOwed && arch && arch.isReply === false && !arch.replyTo) { + threadNone = "Not a reply (the archive says so)."; + threadOwed = false; + } + if (!work.shot && !work.media && !articleOwedNow && !threadOwed && threadNone === existing?.threadNone) { onLog?.(`${id}: already captured (${existing?.state ?? "nothing asked for"}) — skipped.`); continue; } @@ -360,16 +395,31 @@ export async function captureXPosts( let error: string | undefined; let stop: string | undefined; - if (work.shot) { + if (work.shot || threadOwed) { await contact(); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); browser ??= await deps.openPage(); - const res = await shootXPost(browser.page, id, dir, onLog); - state = res.state; - sensitive = res.sensitive; - shot = res.shot; - error = res.error; + const res = await shootXPost(browser.page, id, dir, onLog, { + own: work.shot, + thread: threadOwed + ? { replyTo: arch?.replyTo ?? null, ownHandle: arch?.author, redact: threadRedactFor(input.threadRedact, id) } + : null, + }); + if (work.shot) { + state = res.state; + sensitive = res.sensitive; + shot = res.shot; + error = res.error; + } else if (res.state !== "captured") { + // A thread-only load the page refused: the post's record stands. + threadError = res.error ?? `The page showed the post as ${res.state}.`; + } stop = res.stop; + if (res.thread) { + if ("thread" in res.thread) thread = res.thread.thread; + else if ("none" in res.thread) threadNone = res.thread.none; + else threadError = res.thread.error; + } if (wanted.articles && !articleLink && res.articleLink) articleLink = res.articleLink; } @@ -440,6 +490,9 @@ export async function captureXPosts( mediaState, media, ...(article ? { article } : {}), + ...(thread ? { thread } : {}), + ...(threadNone && !thread ? { threadNone } : {}), + ...(threadError && !thread ? { threadError } : {}), ...(error ? { error } : {}), }; await writePostCapture(dir, record); @@ -451,12 +504,16 @@ export async function captureXPosts( ...(work.shot && captureAvailability(finalState) ? { availability: captureAvailability(finalState) } : {}), - files: (shot ? 1 : 0) + media.length + (article?.files.length ?? 0), + files: (shot ? 1 : 0) + (thread ? 1 : 0) + media.length + (article?.files.length ?? 0), ...(error ? { error } : {}), }); onLog?.( `${id}: ${finalState}${sensitive ? " (behind a sensitive-media cover)" : ""}` + (shot ? ", shot" : "") + + (thread && thread !== existing?.thread + ? `, thread shot (parent ${thread.parentId}${thread.redaction.applied ? ", its author blurred" : `, not blurred: ${thread.redaction.reason}`})` + : "") + + (work.thread && !thread && (threadNone || threadError) ? `, no thread shot: ${threadNone ?? threadError}` : "") + (mediaState === "ok" ? `, ${media.length} media file(s)` : mediaState === "none" ? ", no media" : "") + (article && article !== existing?.article ? `, ${describeArticle(article)}` : "") + (error ? ` — ${error}` : ""), @@ -480,6 +537,16 @@ export async function captureXPosts( } } +// The blur knob for one post: the run's, or the post's own entry of it. +export function threadRedactFor( + knob: PostCaptureInput["threadRedact"], + id: string, +): boolean | undefined { + if (knob === undefined || typeof knob === "boolean") return knob; + const v = knob[id]; + return typeof v === "boolean" ? v : undefined; +} + function describeArticle(a: ArticleCaptureRecord): string { if (a.state !== "captured") { return `article ${a.state}` + (a.error ? ` (${a.error})` : ""); diff --git a/common/social/xThreadShot.test.ts b/common/social/xThreadShot.test.ts @@ -0,0 +1,368 @@ +// A reply's thread shot, against fakes only: the parent picked from a +// recorded page snapshot, the blur's choice, the union box, and the run that +// shoots it beside the post's own shot. No browser, no network. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xThreadShot.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, stat } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { PageLike } from "./playwrightRuntime"; +import { readPostCapture, SHOT_FILENAME, THREAD_SHOT_FILENAME, writePostCapture } from "./postCapture"; +import { unionBox, VIEW_SCRIPT_MARKER, type ElementView } from "./viewportShot"; +import { + boxInShot, + MARK_PARENT_MARKER, + pickThreadParent, + REDACT_MARKER, + REDACTED_BOXES_MARKER, + redactScript, + shootXThread, + THREAD_SNAPSHOT_MARKER, + threadRedaction, + type ThreadArticle, + type ThreadSnapshot, +} from "./xThreadShot"; +import { captureXPosts, threadRedactFor, type XCaptureDeps, type XPostSnapshot } from "./xPostCapture"; + +const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 7]); +const THREAD_PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 8, 8]); + +const art = (id: string, handle: string, top: number, bottom: number, over: Partial<ThreadArticle> = {}): ThreadArticle => ({ + id, + handle, + name: handle, + verified: false, + top, + bottom, + ...over, +}); + +// The reply 2114214000653414579's page, as its archive says: a chain +// root -> 2114113495989907691 (Toothless2210) -> the reply, and a reply under it. +const CHAIN: ThreadSnapshot = { + own: 2, + articles: [ + art("2114053463176855722", "TheQuartering", 0, 400), + art("2114113495989907691", "Toothless2210", 400, 620), + art("2114214000653414579", "TheQuartering", 620, 900), + art("2114300000000000000", "someone", 900, 1100), + ], +}; + +// --- the parent ---------------------------------------------------------------- + +test("parent: the archive's in-reply-to id picks the IMMEDIATE parent out of a chain, not its root", () => { + const pick = pickThreadParent(CHAIN, { id: "2114113495989907691" }); + assert.ok("parent" in pick); + assert.equal(pick.index, 1); + assert.equal(pick.parent.handle, "Toothless2210"); + assert.equal(pick.from, "reply-to"); +}); + +test("parent: with no archive word, the post directly above the reply; never a reply listed under it", () => { + const pick = pickThreadParent(CHAIN, null); + assert.ok("parent" in pick); + assert.equal(pick.parent.id, "2114113495989907691"); + assert.equal(pick.from, "above"); + // The reply under the post is not a parent, even named by id. + const under = pickThreadParent(CHAIN, { id: "2114300000000000000" }); + assert.ok("none" in under); +}); + +test("parent: an archive id not on the page is no parent (the post above it would be a grandparent)", () => { + const gone = pickThreadParent(CHAIN, { id: "999" }); + assert.ok("none" in gone); + assert.match(gone.none, /999.*did not render/); +}); + +test("parent: a post with nothing above it is not a reply; an unmarked page has no own article", () => { + const alone: ThreadSnapshot = { own: 0, articles: [art("1", "a", 0, 300), art("2", "b", 300, 500)] }; + const none = pickThreadParent(alone, null); + assert.ok("none" in none); + assert.match(none.none, /Not a reply/); + assert.ok("none" in pickThreadParent({ own: -1, articles: CHAIN.articles }, null)); +}); + +// --- the blur ------------------------------------------------------------------ + +test("blur: a private author is blurred; a gold- or grey-checked one or the reply's own author is not; the knob overrides", () => { + assert.deepEqual(threadRedaction({ parentHandle: "someone", parentVerified: false, ownHandle: "TheQuartering" }), { + redact: true, + reason: "private", + }); + for (const parentBadge of ["gold", "grey"] as const) { + assert.deepEqual(threadRedaction({ parentHandle: "org", parentVerified: true, parentBadge, ownHandle: "TheQuartering" }), { + redact: false, + reason: "verified", + }); + } + // X Premium's blue check is bought: the proof run's parent (a person asking "How's Huck?") carries one. + for (const parentBadge of ["blue", "other", undefined] as const) { + assert.deepEqual(threadRedaction({ parentHandle: "Toothless2210", parentVerified: true, parentBadge, ownHandle: "TheQuartering" }), { + redact: true, + reason: "blue-check", + }); + } + // A self-thread, whatever the case or the @. + assert.deepEqual(threadRedaction({ parentHandle: "thequartering", parentVerified: false, ownHandle: "@TheQuartering" }), { + redact: false, + reason: "self", + }); + assert.deepEqual(threadRedaction({ parentHandle: "x", parentVerified: false, ownHandle: "y" }, false), { redact: false, reason: "off" }); + assert.deepEqual(threadRedaction({ parentHandle: "x", parentVerified: true, parentBadge: "gold", ownHandle: "y" }, true), { redact: true, reason: "forced" }); + // No own handle known: not a self-thread. + assert.equal(threadRedaction({ parentHandle: "x", parentVerified: false }).redact, true); +}); + +test("blur: the knob per post — the run's boolean, or the post's own entry", () => { + assert.equal(threadRedactFor(undefined, "1"), undefined); + assert.equal(threadRedactFor(false, "1"), false); + assert.equal(threadRedactFor({ "1": false }, "1"), false); + assert.equal(threadRedactFor({ "1": false }, "2"), undefined); +}); + +test("blur: the page script blurs by profile link, case-insensitively, falling back to the User-Name block", () => { + const s = redactScript("@Toothless2210"); + assert.match(s, /"toothless2210"/); + assert.match(s, /Tweet-User-Avatar/); + assert.match(s, /User-Name/); + assert.match(s, /blur\(/); +}); + +test("boxes: the union of the parent's and the reply's boxes; a blurred box placed in the shot, its spread clipped", () => { + const parent = { x: 283, y: -200, width: 598, height: 220 }; + const own = { x: 283, y: 20, width: 598, height: 280 }; + assert.deepEqual(unionBox([parent, own]), { x: 283, y: -200, width: 598, height: 500 }); + assert.equal(unionBox([]), null); + const u = unionBox([parent, own])!; + // The avatar at the parent's top-left corner: its spread clipped at 0. + assert.deepEqual(boxInShot({ x: 299, y: -188, width: 40, height: 40 }, u, 36), { x: 0, y: 0, width: 92, height: 88 }); + assert.deepEqual(boxInShot({ x: 400, y: -150, width: 100, height: 20 }, u, 0), { x: 117, y: 50, width: 100, height: 20 }); +}); + +// --- the shot ------------------------------------------------------------------ + +type FakeThreadPage = PageLike & { calls: string[]; shots: unknown[] }; + +// A page holding CHAIN: the window measure answers the union of the parent's +// and the reply's boxes (viewport coordinates) when asked for both. +function threadPage(opts: { + snap?: ThreadSnapshot; + redacted?: { avatar: number; name: number; mention: number } | null; + post?: XPostSnapshot; + windowed?: boolean; +} = {}): FakeThreadPage { + const calls: string[] = []; + const shots: unknown[] = []; + const view: ElementView = { x: 283, y: 64, width: 598, height: 500, vw: 1280, vh: 900 }; + const ownView: ElementView = { x: 283, y: 284, width: 598, height: 280, vw: 1280, vh: 900 }; + return { + calls, + shots, + goto: async (url: string) => void calls.push(`goto ${url}`), + waitForSelector: async () => undefined, + waitForTimeout: async () => undefined, + on: () => {}, + ...(opts.windowed === false ? {} : { setViewportSize: async () => undefined }), + evaluate: async (script: string) => { + if (script.includes(VIEW_SCRIPT_MARKER)) { + if (opts.windowed === false) return null; + const both = script.includes("data-archilyzer-thread-parent"); + calls.push(both ? "measure-thread" : "measure-own"); + return both ? view : ownView; + } + if (script.includes(THREAD_SNAPSHOT_MARKER)) return opts.snap ?? CHAIN; + if (script.includes(MARK_PARENT_MARKER)) { + calls.push(`mark ${/\[(\d+)\]/.exec(script)?.[1]}`); + return true; + } + if (script.includes(REDACT_MARKER)) { + calls.push("redact"); + return opts.redacted === undefined ? { avatar: 1, name: 2, mention: 1 } : opts.redacted; + } + if (script.includes(REDACTED_BOXES_MARKER)) { + return { + parts: [ + { x: 283, y: 64, width: 598, height: 220 }, + { x: 283, y: 284, width: 598, height: 280 }, + ], + redacted: [ + { what: "avatar", box: { x: 299, y: 76, width: 40, height: 40 } }, + { what: "name", box: { x: 347, y: 76, width: 110, height: 20 } }, + ], + }; + } + if (script.includes("imgs.length")) return 0; + if (script.includes("b.click()")) return 0; + if (script.includes("article[data-testid")) { + calls.push("snapshot"); + return opts.post ?? { path: "/TheQuartering/status/2114214000653414579", text: "", article: { rect: { x: 283, y: 284, width: 598, height: 280 }, sensitive: false } }; + } + return undefined; + }, + screenshot: async (o?: unknown) => { + shots.push(o); + const clip = (o as { clip?: { height: number } })?.clip; + return clip && clip.height === 500 ? THREAD_PNG : PNG; + }, + }; +} + +test("shot: the union from the parent's top to the reply's bottom, the private author blurred first, the boxes recorded", async () => { + const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xthread-")), "2114214000653414579"); + const p = threadPage(); + const res = await shootXThread(p, "2114214000653414579", dir, { + replyTo: { id: "2114113495989907691", author: "Toothless2210" }, + url: "https://x.com/i/status/2114214000653414579", + }); + assert.ok("thread" in res, JSON.stringify(res)); + const t = res.thread; + assert.equal(t.name, THREAD_SHOT_FILENAME); + assert.equal(t.parentId, "2114113495989907691"); + assert.equal(t.parentHandle, "Toothless2210"); + assert.equal(t.parentVerified, false); + assert.equal(t.parentFrom, "reply-to"); + assert.equal(t.redaction.applied, true); + assert.equal(t.redaction.reason, "private"); + assert.deepEqual(t.redaction.boxes, [ + { what: "avatar", box: { x: 0, y: 0, width: 92, height: 88 } }, + { what: "name", box: { x: 28, y: 0, width: 182, height: 68 } }, + ]); + // Marked, blurred, THEN shot -- one viewport clip of the union. + assert.deepEqual(p.calls.filter((c) => c !== "measure-thread"), ["mark 1", "redact"]); + assert.deepEqual(p.shots, [{ type: "png", clip: { x: 283, y: 64, width: 598, height: 500 } }]); + assert.deepEqual(new Uint8Array(await readFile(path.join(dir, THREAD_SHOT_FILENAME))), THREAD_PNG); +}); + +test("shot: a gold-checked parent is shot unblurred; a parent whose name cannot be found to blur gets no shot", async () => { + const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xthread-")), "1"); + const verified = { ...CHAIN, articles: CHAIN.articles.map((a, i) => (i === 1 ? { ...a, verified: true, badge: "gold" as const } : a)) }; + const p = threadPage({ snap: verified }); + const res = await shootXThread(p, "1", dir, { replyTo: { id: "2114113495989907691" } }); + assert.ok("thread" in res); + assert.deepEqual(res.thread.redaction, { applied: false, reason: "verified", boxes: [] }); + assert.ok(!p.calls.includes("redact")); + + const dir2 = path.join(await mkdtemp(path.join(os.tmpdir(), "xthread-")), "1"); + const blind = threadPage({ redacted: { avatar: 1, name: 0, mention: 0 } }); + const refused = await shootXThread(blind, "1", dir2, { replyTo: { id: "2114113495989907691" } }); + assert.ok("error" in refused); + assert.match(refused.error, /could not be found to blur/); + assert.equal(blind.shots.length, 0); + await assert.rejects(stat(path.join(dir2, THREAD_SHOT_FILENAME))); +}); + +test("shot: with nothing above it there is no thread shot, and nothing is shot or blurred", async () => { + const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xthread-")), "1"); + const p = threadPage({ snap: { own: 0, articles: [art("1", "TheQuartering", 0, 300)] } }); + const res = await shootXThread(p, "1", dir, {}); + assert.ok("none" in res); + assert.equal(p.shots.length, 0); + assert.ok(!p.calls.includes("redact")); +}); + +test("shot: a page that cannot be measured in its window shoots the union from a full-page clip", async () => { + const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xthread-")), "1"); + const p = threadPage({ windowed: false }); + const inner = p.evaluate; + p.evaluate = async (s: string) => + s.includes("window.scrollX") && s.includes("data-archilyzer-thread-parent") && !s.includes(REDACTED_BOXES_MARKER) + ? [ + { x: 283, y: 1000, width: 598, height: 220 }, + { x: 283, y: 1220, width: 598, height: 280 }, + ] + : inner(s); + const res = await shootXThread(p, "1", dir, { replyTo: { id: "2114113495989907691" } }); + assert.ok("thread" in res, JSON.stringify(res)); + assert.deepEqual(p.shots, [{ type: "png", fullPage: true, clip: { x: 283, y: 1000, width: 598, height: 500 } }]); +}); + +// --- the run --------------------------------------------------------------------- + +function deps(p: PageLike, opened: { n: number }): XCaptureDeps { + return { + openPage: async () => { + opened.n++; + return { page: p, close: async () => {} }; + }, + downloadMedia: async () => ({ ok: true, files: [] }), + pauseMs: () => 5_000, + pause: async () => {}, + now: () => new Date("2026-10-27T12:00:00.000Z"), + }; +} + +test("run: thread on — the post's own shot, then the thread shot in the same load, both recorded", async () => { + const outDir = await mkdtemp(path.join(os.tmpdir(), "posts-media-")); + const p = threadPage(); + const opened = { n: 0 }; + const id = "2114214000653414579"; + const res = await captureXPosts( + { + ids: [id], + handle: "TheQuartering", + outDir, + media: false, + thread: true, + archived: new Map([[id, { text: "@Toothless2210 Well..", isReply: true, replyTo: { id: "2114113495989907691", author: "Toothless2210" }, author: "TheQuartering" }]]), + signal: new AbortController().signal, + }, + deps(p, opened), + ); + assert.deepEqual(res.outcomes, [{ id, state: "captured", availability: "available", files: 2 }]); + assert.equal(p.calls.filter((c) => c.startsWith("goto")).length, 1, "one page load for both shots"); + const rec = (await readPostCapture(path.join(outDir, id)))!; + assert.equal(rec.shot?.name, SHOT_FILENAME); + assert.equal(rec.thread?.name, THREAD_SHOT_FILENAME); + assert.equal(rec.thread?.parentId, "2114113495989907691"); + assert.equal(rec.thread?.redaction.applied, true); + // The own shot was taken before anything was blurred. + const firstShot = p.calls.indexOf("measure-own"); + assert.ok(firstShot >= 0 && firstShot < p.calls.indexOf("redact")); +}); + +test("run: a post shot before gets only its thread shot; a post the archive says is no reply gets no page load", async () => { + const outDir = await mkdtemp(path.join(os.tmpdir(), "posts-media-")); + const id = "2114214000653414579"; + const plain = "2091829122808832397"; + for (const pid of [id, plain]) { + await writePostCapture(path.join(outDir, pid), { + version: 1, id: pid, url: `https://x.com/i/status/${pid}`, capturedAt: "2026-10-20T00:00:00.000Z", state: "captured", + shot: { name: SHOT_FILENAME, bytes: 5, sha256: "old" }, mediaState: "none", media: [], + }); + } + const p = threadPage(); + const opened = { n: 0 }; + const res = await captureXPosts( + { + ids: [plain, id], + handle: "TheQuartering", + outDir, + thread: true, + archived: new Map([ + [plain, { text: "Up all night.", isReply: false }], + [id, { text: "@Toothless2210 Well..", isReply: true, replyTo: { id: "2114113495989907691" } }], + ]), + signal: new AbortController().signal, + }, + deps(p, opened), + ); + assert.deepEqual(res.outcomes.map((o) => [o.id, o.availability]), [ + [plain, undefined], + [id, undefined], + ]); + assert.equal(p.calls.filter((c) => c.startsWith("goto")).length, 1, "only the reply's page is opened"); + assert.ok(!p.calls.includes("measure-own"), "the post's own shot is not taken again"); + const r = (await readPostCapture(path.join(outDir, id)))!; + assert.equal(r.shot?.sha256, "old", "shot.png is kept"); + assert.equal(r.thread?.parentId, "2114113495989907691"); + const n = (await readPostCapture(path.join(outDir, plain)))!; + assert.match(n.threadNone ?? "", /Not a reply/); + // Settled: the next run owes neither. + const again = threadPage(); + await captureXPosts({ ids: [plain, id], handle: "TheQuartering", outDir, thread: true, signal: new AbortController().signal }, deps(again, { n: 0 })); + assert.equal(again.calls.length, 0); +}); diff --git a/common/social/xThreadShot.ts b/common/social/xThreadShot.ts @@ -0,0 +1,357 @@ +// A reply's THREAD SHOT: the post it answers, over the reply itself, as one +// picture -- `shot-thread.png` beside the post's own `shot.png`, never in its +// place (postCapture.ts has the layout; xPostCapture.ts calls this after the +// post's own shot, in the same page load). +// +// An X status page for a reply renders the conversation above the post: its +// parent, the parent's parent, up to the root, each an +// `article[data-testid="tweet"]`. The thread shot is cut to ONE of them, the +// IMMEDIATE parent -- the box from that article's top to the reply's bottom. +// Which article that is: the one whose status link is the id the archive +// says the reply answers (`replyTo.id`); with no archive word, the article +// directly above the reply. An archive id that is not on the page is no +// parent at all -- the article above it would be a grandparent (X draws a +// deleted or walled parent as a notice, not an article), and a shot that +// names the wrong post as the one replied to is worse than none. +// +// PRIVACY. The parent's author is often a private person replying to a +// public one. By default the shot blurs the parent's avatar, display name and +// @handle, and every link to their profile in the reply (the "Replying to" +// line and any @mention), unless the parent's author is verified or is the +// reply's own author (a self-thread). VERIFIED MEANS AN ORGANISATION'S GOLD +// CHECK OR A GOVERNMENT'S GREY ONE: X's blue check is X Premium's, bought by +// anyone, so a blue-checked private person is blurred like any other (the +// proof run's parent was one: a person asking "How's Huck?"); the badge is +// recorded either way, and `redact: false` lets a public blue-checked +// author through. The blur is a CSS filter set on those +// elements in the page before the shot; their boxes are measured after it +// and recorded, in the shot's own pixels, in capture.json. A parent whose +// name cannot be found to blur gets NO thread shot: the blur is not skipped +// to get a picture. +// +// `redact: false` turns the blur off (an author the operator has judged +// public); `redact: true` blurs even a gold- or grey-checked author. +// +// NOT VERIFIED AGAINST LIVE X beyond the one proof run the CHANGELOG names; +// the markers are X's as of 2026-10. + +import { mkdir, writeFile } from "node:fs/promises"; +import path from "node:path"; +import type { PageLike } from "./playwrightRuntime"; +import { + describeCapturedFile, + THREAD_SHOT_FILENAME, + type RedactedBox, + type ThreadCaptureRecord, + type ThreadRedactionReason, +} from "./postCapture"; +import { shootFromViewport, unionBox } from "./viewportShot"; + +// The post's own article (xPostCapture.ts marks it) and its parent's. +export const OWN_SELECTOR = "[data-archilyzer-capture]"; +export const PARENT_SELECTOR = "[data-archilyzer-thread-parent]"; +const REDACTED_ATTR = "data-archilyzer-redacted"; + +export const THREAD_SNAPSHOT_MARKER = "__archilyzerThreadSnapshot"; +export const MARK_PARENT_MARKER = "__archilyzerMarkParent"; +export const REDACT_MARKER = "__archilyzerRedact"; +export const REDACTED_BOXES_MARKER = "__archilyzerBlurredBoxes"; + +// One article of the page as the thread snapshot reads it, in document order. +export type ThreadArticle = { + // Its status link (the one holding its <time>): /<handle>/status/<id>. + id?: string; + handle?: string; + // The display name: User-Name's first line. + name?: string; + verified: boolean; + // Which check it carries: X Premium's blue, an organisation's gold, a + // government's grey, or one the snapshot could not tell. + badge?: XBadge; + // Its box's top and bottom, document coordinates. + top: number; + bottom: number; +}; + +export type XBadge = "blue" | "gold" | "grey" | "other"; + +export type ThreadSnapshot = { + // The post's own article among `articles`, or -1 when it is not marked. + own: number; + articles: ThreadArticle[]; +}; + +export const threadSnapshotScript = () => `(() => { + const ${THREAD_SNAPSHOT_MARKER} = true; + const all = Array.from(document.querySelectorAll('article[data-testid="tweet"]')); + const own = all.findIndex((a) => a.hasAttribute("data-archilyzer-capture")); + const articles = all.map((a) => { + let id, handle; + for (const l of a.querySelectorAll('a[href*="/status/"]')) { + const m = /^\\/([^/?#]+)\\/status\\/(\\d+)/.exec(l.getAttribute("href") || ""); + if (m && l.querySelector("time")) { handle = m[1]; id = m[2]; break; } + } + const un = a.querySelector('[data-testid="User-Name"]'); + const name = un ? ((un.innerText || "").split("\\n")[0] || "").trim() : ""; + const icon = un && un.querySelector('[data-testid="icon-verified"]'); + const verified = !!icon; + let badge; + if (icon) { + // Gold is drawn with a gradient; blue and grey are one fill, X's own colours. + const paint = [getComputedStyle(icon).color, icon.getAttribute("fill") || "", + ...Array.from(icon.querySelectorAll("[fill]")).map((e) => e.getAttribute("fill") || "")].join(" "); + badge = /linearGradient/i.test(icon.outerHTML) ? "gold" + : /29,\\s*155,\\s*240|#1d9bf0/i.test(paint) ? "blue" + : /130,\\s*154,\\s*171|#829aab/i.test(paint) ? "grey" + : "other"; + } + const r = a.getBoundingClientRect(); + return { id, handle, name: name || undefined, verified, badge, top: r.top + window.scrollY, bottom: r.bottom + window.scrollY }; + }); + return { own, articles }; +})()`; + +export type ThreadParentPick = + | { index: number; parent: ThreadArticle; from: "reply-to" | "above" } + | { none: string }; + +// Which article is the reply's immediate parent. Pure: the snapshot and the +// archive's word in, the pick out. Only articles ABOVE the reply count (in +// document order before it, and ending above its top): X lists the replies to +// a post under it, as articles too. +export function pickThreadParent( + snap: ThreadSnapshot, + replyTo?: { id?: string } | null, +): ThreadParentPick { + if (snap.own < 0 || !snap.articles[snap.own]) return { none: "The post's own article is not on the page." }; + const own = snap.articles[snap.own]; + const above = snap.articles + .map((a, index) => ({ a, index })) + .filter(({ a, index }) => index < snap.own && a.bottom <= own.top + 2); + const want = replyTo?.id; + if (want) { + const hit = above.find(({ a }) => a.id === want); + if (hit) return { index: hit.index, parent: hit.a, from: "reply-to" }; + return { + none: + `The post it answers (${want}) did not render above it` + + (above.length ? " — the post above is another one of the thread" : "") + + " (deleted or walled?).", + }; + } + const last = above[above.length - 1]; + if (!last) return { none: "Not a reply: no post above it on the page." }; + if (!last.a.id) return { none: "The post above it has no status link to name it by." }; + return { index: last.index, parent: last.a, from: "above" }; +} + +// Whether the parent's author is blurred, and why. Pure. +// Only a gold or grey check is "verified" here: the blue is bought (above). +export function threadRedaction( + p: { parentHandle?: string; parentVerified: boolean; parentBadge?: XBadge; ownHandle?: string }, + redact?: boolean, +): { redact: boolean; reason: ThreadRedactionReason } { + if (redact === false) return { redact: false, reason: "off" }; + if (redact === true) return { redact: true, reason: "forced" }; + const same = (a?: string, b?: string) => !!a && !!b && a.replace(/^@/, "").toLowerCase() === b.replace(/^@/, "").toLowerCase(); + if (same(p.parentHandle, p.ownHandle)) return { redact: false, reason: "self" }; + if (p.parentVerified && (p.parentBadge === "gold" || p.parentBadge === "grey")) return { redact: false, reason: "verified" }; + if (p.parentVerified) return { redact: true, reason: "blue-check" }; + return { redact: true, reason: "private" }; +} + +export const markParentScript = (index: number) => `(() => { + const ${MARK_PARENT_MARKER} = true; + for (const el of document.querySelectorAll("[data-archilyzer-thread-parent]")) el.removeAttribute("data-archilyzer-thread-parent"); + const a = document.querySelectorAll('article[data-testid="tweet"]')[${Math.floor(index)}]; + if (!a) return false; + a.setAttribute("data-archilyzer-thread-parent", ""); + return true; +})()`; + +// The blur: the parent's avatar, every link to its author's profile (X draws +// the display name and the @handle as two), or -- when it finds no such link +// -- the whole User-Name block; and every link to that profile in the reply. +// Returns how many of each it set. +export const redactScript = (handle: string, px = 14) => `(() => { + const ${REDACT_MARKER} = true; + const handle = ${JSON.stringify(handle.replace(/^@/, "").toLowerCase())}; + const parent = document.querySelector(${JSON.stringify(PARENT_SELECTOR)}); + const own = document.querySelector(${JSON.stringify(OWN_SELECTOR)}); + if (!parent) return null; + const blur = (el, what, amount) => { + el.setAttribute("${REDACTED_ATTR}", what); + el.style.setProperty("filter", "blur(" + amount + "px)", "important"); + }; + const toProfile = (root) => Array.from(root.querySelectorAll("a[href]")).filter((l) => { + const h = (l.getAttribute("href") || "").split(/[?#]/)[0].toLowerCase(); + return h === "/" + handle || h === "https://x.com/" + handle || h === "https://twitter.com/" + handle; + }); + const n = { avatar: 0, name: 0, mention: 0 }; + for (const el of parent.querySelectorAll('[data-testid="Tweet-User-Avatar"]')) { blur(el, "avatar", ${px + 4}); n.avatar++; } + // A profile link inside the avatar is the avatar's, already blurred. + for (const l of toProfile(parent)) { + if (l.closest('[data-testid="Tweet-User-Avatar"]')) continue; + blur(l, "name", ${px}); n.name++; + } + if (n.name === 0) { + const un = parent.querySelector('[data-testid="User-Name"]'); + if (un) { blur(un, "user-name", ${px}); n.name++; } + } + if (own) for (const l of toProfile(own)) { blur(l, "mention", ${px}); n.mention++; } + return n; +})()`; + +// The blurred boxes and the thread's union box, in viewport coordinates, read +// together so the one is placed in the other. +export const redactedBoxesScript = () => `(() => { + const ${REDACTED_BOXES_MARKER} = true; + const rect = (el) => { const r = el.getBoundingClientRect(); return { x: r.left, y: r.top, width: r.width, height: r.height }; }; + const parent = document.querySelector(${JSON.stringify(PARENT_SELECTOR)}); + const own = document.querySelector(${JSON.stringify(OWN_SELECTOR)}); + if (!parent || !own) return null; + return { + parts: [parent, own].map(rect), + redacted: Array.from(document.querySelectorAll("[${REDACTED_ATTR}]")).map((el) => ({ what: el.getAttribute("${REDACTED_ATTR}"), box: rect(el) })), + }; +})()`; + +type Box = { x: number; y: number; width: number; height: number }; + +// A blurred box in the shot's pixels: offset by the union's top-left, the +// CSS blur's spread added round it, and clipped to the shot. +export function boxInShot(box: Box, union: Box, spread = 0): Box { + const x0 = Math.max(0, Math.floor(box.x - union.x - spread)); + const y0 = Math.max(0, Math.floor(box.y - union.y - spread)); + const x1 = Math.min(Math.ceil(union.width), Math.ceil(box.x - union.x + box.width + spread)); + const y1 = Math.min(Math.ceil(union.height), Math.ceil(box.y - union.y + box.height + spread)); + return { x: x0, y: y0, width: Math.max(0, x1 - x0), height: Math.max(0, y1 - y0) }; +} + +// Let the parent's images load too, so the shot is not of grey boxes. +const PARENT_IMAGES_SCRIPT = `(() => { + const root = document.querySelector(${JSON.stringify(PARENT_SELECTOR)}) || document; + const imgs = Array.from(root.querySelectorAll("img")).filter((i) => !i.complete); + return Promise.all(imgs.map((i) => new Promise((r) => { + i.addEventListener("load", r, { once: true }); + i.addEventListener("error", r, { once: true }); + setTimeout(r, 5000); + }))).then(() => imgs.length); +})()`; + +const DOC_UNION_SCRIPT = `(() => { + const els = [${JSON.stringify(PARENT_SELECTOR)}, ${JSON.stringify(OWN_SELECTOR)}].map((s) => document.querySelector(s)); + if (els.some((e) => !e)) return null; + return els.map((e) => { const r = e.getBoundingClientRect(); return { x: r.left + window.scrollX, y: r.top + window.scrollY, width: r.width, height: r.height }; }); +})()`; + +export type ThreadShotOptions = { + // What the archive says the post answers, when it says. + replyTo?: { id?: string; author?: string } | null; + // The reply's own author (for a self-thread), when the caller knows it; + // else read off the page. + ownHandle?: string; + // undefined: the rule (blur a private author); false: off; true: always. + redact?: boolean; + url?: string; + onLog?: (line: string) => void; +}; + +export type ThreadShotResult = + | { thread: ThreadCaptureRecord } + | { none: string } + | { error: string }; + +// The CSS blur's spread beyond an element's box, as recorded (≈ 2σ of the +// strongest blur set). +const BLUR_SPREAD = 36; + +// The thread shot of the post whose own article is marked. The page is the +// one the post was just shot in; what is blurred here stays blurred until the +// page is left. +export async function shootXThread( + page: PageLike, + id: string, + dir: string, + opts: ThreadShotOptions = {}, +): Promise<ThreadShotResult> { + const { onLog } = opts; + const snap = (await page.evaluate(threadSnapshotScript()).catch(() => null)) as ThreadSnapshot | null; + if (!snap || !Array.isArray(snap.articles)) return { error: "The page could not be read for the thread." }; + const pick = pickThreadParent(snap, opts.replyTo); + if ("none" in pick) return { none: pick.none }; + const { parent } = pick; + const ownHandle = opts.ownHandle ?? snap.articles[snap.own]?.handle; + const choice = threadRedaction( + { parentHandle: parent.handle ?? opts.replyTo?.author, parentVerified: parent.verified, parentBadge: parent.badge, ownHandle }, + opts.redact, + ); + if (!(await page.evaluate(markParentScript(pick.index)).catch(() => false))) { + return { error: "The parent's article vanished before it could be marked." }; + } + if (choice.redact) { + const handle = parent.handle ?? opts.replyTo?.author; + if (!handle) return { error: "The parent's author has no handle to blur by; no thread shot." }; + const n = (await page.evaluate(redactScript(handle)).catch(() => null)) as + | { avatar: number; name: number; mention: number } + | null; + if (!n || n.name === 0) { + return { error: "The parent's name could not be found to blur; no thread shot." }; + } + onLog?.( + `${id}: blurring @${handle} (${choice.reason}): ${n.avatar} avatar, ${n.name} name, ${n.mention} mention(s).`, + ); + } else { + onLog?.(`${id}: the parent's author @${parent.handle ?? "?"} is not blurred (${choice.reason}).`); + } + await page.evaluate(PARENT_IMAGES_SCRIPT).catch(() => {}); + + let png: Uint8Array; + try { + const fromWindow = await shootFromViewport(page, { selector: [PARENT_SELECTOR, OWN_SELECTOR], onLog }); + if (fromWindow && "error" in fromWindow) return { error: `The thread could not be shot: ${fromWindow.error}` }; + if (fromWindow) png = fromWindow.png; + else { + const parts = (await page.evaluate(DOC_UNION_SCRIPT).catch(() => null)) as Box[] | null; + const u = parts ? unionBox(parts) : null; + if (!u || u.width < 1 || u.height < 1) return { error: "The thread rendered with no size to shoot." }; + onLog?.(`${id}: shooting the thread from a full-page capture.`); + png = await page.screenshot({ + type: "png", + fullPage: true, + clip: { x: Math.max(0, Math.floor(u.x)), y: Math.max(0, Math.floor(u.y)), width: Math.ceil(u.width), height: Math.ceil(u.height) }, + }); + } + } catch (err) { + return { error: `The thread's screenshot failed: ${((err as Error)?.message ?? String(err)).split("\n")[0]}` }; + } + + // Where the blur landed, in the shot's own pixels. The window shot's + // layout is the one measured now (shootFromViewport checks it held still). + let boxes: RedactedBox[] = []; + if (choice.redact) { + const read = (await page.evaluate(redactedBoxesScript()).catch(() => null)) as + | { parts: Box[]; redacted: { what: RedactedBox["what"]; box: Box }[] } + | null; + const u = read ? unionBox(read.parts) : null; + if (u) { + boxes = read!.redacted.map((r) => ({ what: r.what, box: boxInShot(r.box, u, BLUR_SPREAD) })); + } + } + + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, THREAD_SHOT_FILENAME), png); + const file = await describeCapturedFile(dir, THREAD_SHOT_FILENAME, opts.url); + return { + thread: { + ...file, + parentId: parent.id!, + ...(parent.handle ? { parentHandle: parent.handle } : {}), + ...(parent.name ? { parentAuthor: parent.name } : {}), + parentVerified: parent.verified, + ...(parent.badge ? { parentBadge: parent.badge } : {}), + parentFrom: pick.from, + redaction: { applied: choice.redact, reason: choice.reason, boxes }, + }, + }; +} diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,8 @@ # Changelog ## [Unreleased] +- **A reply can be captured with the post it answers above it.** `capture-posts` with `"thread": true` (X; or a channel's new `postCaptureThread`, or the Thread shot box under Capture posts on an X channel's page) also writes `shot-thread.png` beside the post's `shot.png`: the post it replies to over the reply, in the same page load — only the immediate parent, a longer chain cut to it. The parent is the post the archive says it answers; with no archive word, the post directly above it on the page; a post the archive says is no reply is not opened for it, and a post shot before gets only its thread shot. **The replied-to author is blurred** — avatar, name and handle, and any link to them in the reply — unless they carry an organisation's gold or a government's grey check, or are the reply's own author. X Premium's blue check is bought, so a blue-checked person is blurred like anyone else (the first live proof's parent was one). `"threadRedact": false` (or `{"<id>": false}`) takes it unblurred; a parent whose name cannot be found to blur gets no thread shot. capture.json records the parent, its badge and every blurred box. Proved on TheQuartering's reply 2114214000653414579. Needs a restart of the editor. +- **A report video can draw a reply with the post it answers.** A manifest post's `thread: true` draws its capture's `shot-thread.png` in place of its shot (its own shot while there is none) — set with `umtool posts set <project> <post> thread=on`, `umtool posts add … --thread`, or the **thread** box in the On-screen Posts table. In the feed a thread shot is drawn whole: the card under it leaves rather than the reply being squeezed, and one taller than the column is scaled to fit, never cut. A cut with no thread shot renders byte for byte as before. - **A site build can now run beside a report-video render when there is memory for both.** A render declared nothing to the machine's heavy slot, so it always ran alone: a site build started while a take rendered waited out the whole render (an hour or more for a full cut). A render now says how much memory it will need — measured on the Huck cut: about 6 GB for a whole cut (its widest step, a crossfade over 23 clips at once, peaked at 4.9 GB), about 2.4 GB for a short take of part of a cut, more with more `UMTOOL_CHROME_WORKERS` — and the encode ladder (`umtool variants`) about 1 GB. A capped site build (one run under `systemd-run … -p MemoryMax=5G`) is let in beside it while the memory left after the render's share stays at or above the 6000 MB floor, and waits for it otherwise. On this 16 GB machine that is often for a short take and rare for a whole cut. A publish stage's own build is not capped, so it still waits for the render as before. `UMTOOL_RENDER_ESTIMATE_MB` / `UMTOOL_LADDER_ESTIMATE_MB` set the share by hand, and `0` makes a render run alone again. Start a take or a build-video run as it is, not under `pnpm heavy --`, which makes it run alone. Needs a restart of umtool for takes made from the app (the `umtool take` command has it now). - **Report-video takes no longer keep their build work forever.** On 2026-10-27 /home reached 100 % (5.4 GB free of 1.5 TB), and 131 GB of it was takes' build work: each full take's chrome frames (about 12 GB for the 34-minute Huck cut, kept with `--keep-frames` so a `--from` twin can reuse them), its crossfade batches and its clip segments, swept by hand. `umtool prune <project>` (or `--all`) now lists each take's work files — segments, chrome frames, crossfade batches, encode chunks, raw clip copies, `work-from-*` — and what freeing them gives back, or why the take keeps them: a build running in it or from it (never freed), the picked take, the take the project's manifest is, a pin in `takes/prune.json`, the newest 2 of its group, anything modified in the last 3 days, and the `--from` bases of those. It is a dry run unless `--yes`. Files hard-linked between takes are counted once, and freed only when every take holding them lets them go, so the numbers are what the disk gets back, not a sum of `du`s. The renders, previews, take.json and manifests are never touched, and nothing is followed out of a take through a link. The Takes page says each take's work and why it is kept, with **Free work files** per take and for the project (the plan first, then **Free them**). A take that finishes building now prunes its project by the same rules and says what it freed in its log, and a render that starts with under 30 GB free does the same across every project, and refuses to start under 10 GB with a sentence saying so. `--keep`, `--older-than`, `takes/prune.json` and `UMTOOL_PRUNE_*` / `UMTOOL_DISK_GUARD*` change the rules or turn them off. A dry run over ~/reports on 2026-10-27, after the hand sweep: 27 GiB of work in 32 projects' takes, 4.0 GiB of it free to go (2.4 GiB in the Huck project, whose last three days of takes are all kept). Needs a restart of umtool for the Takes page and for takes made from it; the CLI has it at once. - **An X post's screenshot is of the post, not of a page in the middle of laying itself out.** On 2026-10-27 a forced capture of TheQuartering's post 2114859155022389342 came out shifted about 100 px: its left edge cut off, X's menu laid over its words and the gap beside the column showing; another post once came out as a strip of the post above it. The shot was a full-page capture, which resizes the page for the moment of the capture — in the X session profile the page saw its window go to 1×1 — and X laid itself out again for that size while it was being captured, so the shot was cut from a different layout than the one measured. A post is now shot from the window as it stands: scrolled into it, the window made taller first when the post is taller than it, so nothing is resized under the shot; and the post is measured again after the shot and shot again if it moved. An X Article's shot is taken the same way. Posts taller than the tallest window (16,384 px) are still shot from a full-page capture. 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 @@ -72,6 +72,22 @@ test("both halves off is nothing to do unless the articles are asked for by name assert.deepEqual(await readdir(path.join(ROOT, ".jobs")).catch(() => []), []); }); +test("thread: a boolean; threadRedact a boolean or { id: boolean }; the thread shots alone are a run", async () => { + const bad = await post({ slug: SLUG, ids: ["111"], thread: "yes" }); + assert.equal(bad.status, 400); + assert.match(bad.error, /"thread" must be a boolean/); + for (const threadRedact of ["no", [false], { "111": "off" }]) { + const res = await post({ slug: SLUG, ids: ["111"], thread: true, threadRedact }); + assert.equal(res.status, 400, JSON.stringify(threadRedact)); + assert.match(res.error, /"threadRedact"/); + } + // Asked for by name, past the nothing-to-do check to the next refusal. + const stray = await post({ slug: SLUG, ids: ["999"], shots: false, media: false, thread: true, threadRedact: { "999": false } }); + assert.equal(stray.status, 400); + assert.equal(stray.error, "1 id(s) not in demo-x's posts archive: 999"); + assert.deepEqual(await readdir(path.join(ROOT, ".jobs")).catch(() => []), []); +}); + // Moved from e2e/ops-api.spec.ts (release 19, A2b): nothing below reaches X — // every case is refused before a job exists. async function channel(slug: string, config: Record<string, unknown>): Promise<void> { diff --git a/editor/app/api/ops/capture-posts/route.ts b/editor/app/api/ops/capture-posts/route.ts @@ -10,15 +10,20 @@ import { export const dynamic = "force-dynamic"; -// POST { slug, ids, shots?, media?, force?, articles?, queueKey? } -> { ok: true, jobId } +// POST { slug, ids, shots?, media?, force?, articles?, thread?, threadRedact?, 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 // the channel's posts-media/<id>/. A post that links to an X Article (its // archived text, or its card) also gets the article — read into article.json, // article.md and article.png, with its images — unless `articles` is false -// (default true). Posts already captured are skipped unless `force`. The job -// runs on the platform's queue, as a post fetch does. +// (default true). An X reply also gets its thread shot -- the post it answers +// over it, shot-thread.png -- with `thread` (default: the channel's +// `postCaptureThread`); its parent's author is blurred unless verified or the +// reply's own, and `threadRedact` (false: off, true: always, or +// { "<id>": bool } per post) overrides that. Posts already captured are +// skipped unless `force`. The job runs on the platform's queue, as a post +// fetch does. // // Every refusal is the action's own sentence: both halves off (an // articles-only run names `articles: true`), a channel that @@ -27,7 +32,7 @@ export const dynamic = "force-dynamic"; export async function POST(request: Request) { return ops( request, - ["slug", "ids", "shots", "media", "force", "articles", "queueKey"], + ["slug", "ids", "shots", "media", "force", "articles", "thread", "threadRedact", "queueKey"], async (body) => { const slug = reqSlug(body, "slug"); return jobResponse( @@ -39,6 +44,7 @@ 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 }, ), ); }, diff --git a/editor/app/channels/[slug]/components/SocialChannelPanel.tsx b/editor/app/channels/[slug]/components/SocialChannelPanel.tsx @@ -47,6 +47,9 @@ export type SocialChannelState = { olderStatus: string; // The channel's platform; "xenforo" is a forum thread. platform?: string; + // X channels: the Capture posts thread-shot option's default (the + // channel's `postCaptureThread`); absent elsewhere, and the option with it. + captureThread?: boolean; // A forum thread's browser session (its host's profile), when it is one. forumSession?: ForumSessionStatus; // An X search channel (release 38): its query and where its walk stands. @@ -581,7 +584,7 @@ export function SocialChannelPanel({ </section> )} - <SocialPostTools slug={slug} /> + <SocialPostTools slug={slug} captureThread={state.captureThread} /> <p className="text-xs text-muted-foreground"> Posts are indexed into the search corpus by the normal build — there is diff --git a/editor/app/channels/[slug]/components/SocialPostTools.tsx b/editor/app/channels/[slug]/components/SocialPostTools.tsx @@ -8,13 +8,19 @@ import { importPostAction } from "../importPostAction"; // A posts channel's ops-only operations as buttons (release 32): one post // imported by its URL (`import-post`), and specific posts captured — a -// screenshot and their media (`capture-posts`). -export function SocialPostTools({ slug }: { slug: string }) { +// screenshot and their media (`capture-posts`). On an X channel +// (`captureThread` given: the channel's default), a reply's thread shot too -- +// the post it answers over it, its author blurred unless verified or the +// reply's own, or not blurred when the operator unticks the blur. +export function SocialPostTools({ slug, captureThread }: { slug: string; captureThread?: boolean }) { const [url, setUrl] = useState(""); const [ids, setIds] = useState(""); const [shots, setShots] = useState(true); const [media, setMedia] = useState(true); const [force, setForce] = useState(false); + const [thread, setThread] = useState(captureThread ?? false); + const [blur, setBlur] = useState(true); + const x = captureThread !== undefined; const idList = ids.split(/[\s,]+/).filter(Boolean); const input = "rounded border border-border bg-card px-2 py-1 text-sm font-mono"; return ( @@ -47,9 +53,25 @@ export function SocialPostTools({ slug }: { slug: string }) { <input type="checkbox" checked={force} onChange={(e) => setForce(e.target.checked)} /> Again, if captured </label> + {x && ( + <label className="flex items-center gap-2" title="A reply: the post it answers over it, as shot-thread.png beside shot.png"> + <input type="checkbox" checked={thread} onChange={(e) => setThread(e.target.checked)} /> + Thread shot (replies) + </label> + )} + {x && thread && ( + <label className="flex items-center gap-2" title="Blur the replied-to author's avatar, name and handle unless they are verified or the reply's own author"> + <input type="checkbox" checked={blur} onChange={(e) => setBlur(e.target.checked)} /> + Blur the replied-to author + </label> + )} </div> <StreamActionLog - trigger={() => capturePostsAction(slug, idList, undefined, shots, media, force)} + trigger={() => + capturePostsAction(slug, idList, undefined, shots, media, force, undefined, x + ? { thread, ...(thread && !blur ? { threadRedact: false } : {}) } + : {}) + } cancelAction={cancelJobAction} buttonLabel={`Capture ${idList.length || ""} post${idList.length === 1 ? "" : "s"}`.replace(" ", " ")} runningLabel="Capturing…" diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -274,6 +274,8 @@ export default async function ChannelDetailPage({ handle: config.socialHandle ?? slug, accountUrl: config.url, platform: config.platform, + // X only: the capture's thread-shot option, at the channel's default. + ...(config.platform === "twitter" ? { captureThread: config.postCaptureThread ?? false } : {}), ...(forumSession ? { forumSession } : {}), ...(xSearch ? { diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -47,8 +47,10 @@ import { capturePostsProblem, NOTHING_TO_CAPTURE, nothingToCapture, + parseThreadRedact, strayCaptureIds, strayIdsRefusal, + type ThreadRedactKnob, } from "yt-dlp-transcript-common/controller/capturePosts"; import { readPostFetchState, @@ -297,7 +299,10 @@ export async function fetchPostsAction( // exists: nothing asked for, no ids, a channel that is not social, a fetcher // that cannot capture, or an id that is not in the channel's posts archive // (named). Posts already captured are skipped unless `force`. A post that -// links to an X Article gets the article too unless `articles` is false. +// 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. export async function capturePostsAction( slug: string, ids: string[], @@ -306,8 +311,13 @@ export async function capturePostsAction( media?: boolean, force?: boolean, articles?: boolean, + more: { thread?: boolean; threadRedact?: ThreadRedactKnob } = {}, ): Promise<StreamActionResult> { - if (nothingToCapture({ shots, media, articles })) return { ok: false, error: NOTHING_TO_CAPTURE }; + const { thread } = 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 }; const wanted = [...new Set(ids)]; if (wanted.length === 0) return { ok: false, error: "No post ids to capture." }; const paths = getPaths(); @@ -341,7 +351,11 @@ export async function capturePostsAction( spec: { kind: "capture-posts", slug, - params: { queueKey, ids: wanted, shots, media, force, articles }, + params: { + queueKey, ids: wanted, shots, media, force, articles, + ...(thread !== undefined ? { thread } : {}), + ...(threadRedact !== undefined ? { threadRedact } : {}), + }, }, fn: async (onLog, signal, _progress, ctx) => { const result = await capturePosts({ @@ -353,6 +367,8 @@ export async function capturePostsAction( media, force, articles, + thread, + threadRedact, onLog, signal, drain: ctx.drainSignal, diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -439,6 +439,11 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { bool(p.media), bool(p.force), bool(p.articles), + { + thread: bool(p.thread), + // A boolean or { id: boolean }; the action refuses any other shape. + threadRedact: p.threadRedact as boolean | Record<string, boolean> | undefined, + }, ); }, "download-missing-subs": (spec) => { diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1449,7 +1449,13 @@ export function usage() { ' 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. Paced like a post fetch, on its queue.', + ' 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.', "", 'persist-videos saves specific videos, across channels, to the saved-video', ' store: {"items": [{"slug", "id"}, ...]}. "format": "original" |', diff --git a/umtool/app/api/report/onscreen/route.ts b/umtool/app/api/report/onscreen/route.ts @@ -1,3 +1,5 @@ +import { stat } from "node:fs/promises"; +import path from "node:path"; import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, manifestToken, updateOnscreen } from "@/lib/report/manifest.mjs"; import { postRows, scheduleForPreview } from "@/lib/report/onscreen.mjs"; @@ -50,6 +52,16 @@ export async function GET(request: Request) { const provenance = cut.provenance ?? {}; const multi = isMultiChannel(entries, provenance); const posts = postRows({ variantManifest: cut, metas, schedule }); + // Whether each post's thread shot (shot-thread.png beside its shot) is on + // disk: the Posts table's thread box draws it only then. + const withThreads = await Promise.all( + posts.posts.map(async (p: { threadShot: string | null }) => ({ + ...p, + hasThreadShot: p.threadShot + ? Boolean(await stat(path.resolve(/* turbopackIgnore: true */ r.project.dir, p.threadShot)).catch(() => null)) + : false, + })), + ); const rows = entries.map((e, i) => { const { onscreen, ...bare } = e; return { @@ -68,7 +80,7 @@ export async function GET(request: Request) { rows, maxChars: deck.title.maxChars, multiChannel: multi, - posts: posts.posts, + posts: withThreads, clips: posts.clips, postsShown: deck.posts.show, postsEstimated: schedule.estimated === true, diff --git a/umtool/app/api/report/posts/route.ts b/umtool/app/api/report/posts/route.ts @@ -5,13 +5,15 @@ import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; -// The two decisions a person makes about a post once it is in the manifest: -// which clip it rides on (`attachTo`, null for the automatic one) and whether -// it is shown (`hide`). Adding, removing or rewording posts is not here -- -// they are written into the manifest by whoever cites them. +// The decisions a person makes about a post once it is in the manifest: +// which clip it rides on (`attachTo`, null for the automatic one), whether +// it is shown (`hide`), and -- a reply -- whether it is drawn with the post it +// answers above it (`thread`: its capture's shot-thread.png, when there is +// one). Adding, removing or rewording posts is not here -- they are written +// into the manifest by whoever cites them. // // PUT is the Posts table's one save: `{ project, posts: { <id>: { attachTo?, -// hide? } }, token }`. One unknown id, one bad value, or a result the build's +// hide?, thread? } }, token }`. One unknown id, one bad value, or a result the build's // validatePosts refuses fails the WHOLE batch and nothing is written. The // client sends a project id, never a path. Read through GET // /api/report/onscreen, which carries the rows and the token. @@ -35,7 +37,7 @@ export async function PUT(request: Request) { const { result: res, editNotes } = await withEditNotes(r.project, () => updatePosts( r.project.dir, - body.posts as Record<string, { attachTo?: string | null; hide?: boolean }>, + body.posts as Record<string, { attachTo?: string | null; hide?: boolean; thread?: boolean }>, { token: body.token === undefined ? null : String(body.token) }, ), ); diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -78,7 +78,8 @@ // [--date …] [--quote …] [--cite S] | move <id> --to <index> | remove <id> | duplicate <id> | // post <json|@file> | post-remove <id> | teaser <id> <patch-json> | undo] the cut's structure // umtool scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--json] cuts + black spans, source seconds -// umtool posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag …] a post from the archive +// umtool posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag …] [--thread] a post from the archive +// set <project> <post> thread=on|off [hide=on|off] [attach=<clipId>|auto] the Posts table's writer import process from "node:process"; import { PROJECT_KINDS, @@ -819,9 +820,12 @@ function usage() { " umtool scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10] [--pad 30 | --from S --to S] [--json]", " scene cuts (scdet) and black spans (blackdetect) in the clip's fetched window, in SOURCE", " seconds — for blur.from/blur.to and trims; nothing fetched (`umtool fetch` first)", - " umtool posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--json]", + " umtool posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--json]", " a post entry from the corpus's posts archive, its screenshot copied into posts-media/;", - " refused when the post has no shot (`pnpm ops capture-posts` first)", + " refused when the post has no shot (`pnpm ops capture-posts` first); --thread: a reply drawn", + " with the post it answers above it (shot-thread.png, capture-posts \"thread\": true)", + " umtool posts set <project> <post> thread=on|off [hide=on|off] [attach=<clipId>|auto] [--json]", + " the Posts table's writer (updatePosts); <post> is x-<postId> or the bare <postId>", "", `reading ${REPORTS_ROOT} (set REPORTS_DIR to move it)`, "", diff --git a/umtool/components/projects/OnscreenSection.tsx b/umtool/components/projects/OnscreenSection.tsx @@ -113,7 +113,7 @@ export type DeckPreviewDoc = { verdictLabels?: Record<string, string>; }; /** An unsaved change to a post, as PUT /api/report/posts takes it. */ -export type PostPatch = { attachTo?: string | null; hide?: boolean }; +export type PostPatch = { attachTo?: string | null; hide?: boolean; thread?: boolean }; /** What each segment's panel should say right now, by entry id. */ export type DeckTexts = Record<string, { title: string; subtitle: string }>; export type Onscreen = { title?: string; subtitle?: string }; @@ -742,13 +742,16 @@ type PostRow = { url: string; attachTo: string | null; hide: boolean; + // Drawn with the post it answers above it (its thread shot), when there is one. + thread?: boolean; + hasThreadShot?: boolean; auto: PostWhere | null; effective: PostWhere | null; timing: { segment: string; slot: number; of: number; appear?: number; out?: [number, number]; in?: number } | null; }; type ClipOption = { id: string; label: string; day: string | null; from?: number }; /** A post's row as the form holds it: `attachTo` "" is the automatic clip. */ -type PostDraft = { attachTo: string; hide: boolean }; +type PostDraft = { attachTo: string; hide: boolean; thread: boolean }; type JobView = { id: string; state: "running" | "done" | "failed"; @@ -776,13 +779,14 @@ const claimValue = (d: Draft): Claim | null => d.claimId.trim() || d.verdict ? { id: d.claimId.trim(), verdict: d.verdict } : null; /** A row's draft as the writer takes it: the text, and the claim beside it. */ const rowValue = (d: Draft): OnscreenRow => ({ ...(onscreenValue(d) ?? {}), claim: claimValue(d) }); -const postDraftOf = (p: PostRow): PostDraft => ({ attachTo: p.attachTo ?? "", hide: p.hide }); -const samePost = (a: PostDraft, b: PostDraft) => a.attachTo === b.attachTo && a.hide === b.hide; +const postDraftOf = (p: PostRow): PostDraft => ({ attachTo: p.attachTo ?? "", hide: p.hide, thread: p.thread === true }); +const samePost = (a: PostDraft, b: PostDraft) => a.attachTo === b.attachTo && a.hide === b.hide && a.thread === b.thread; /** Only what changed, in the writer's shape. */ const postPatch = (d: PostDraft, saved: PostDraft): PostPatch => { const p: PostPatch = {}; if (d.attachTo !== saved.attachTo) p.attachTo = d.attachTo || null; if (d.hide !== saved.hide) p.hide = d.hide; + if (d.thread !== saved.thread) p.thread = d.thread; return p; }; const clipText = (id: string, label: string) => (label ? `${id} — ${label}` : id); @@ -1646,6 +1650,7 @@ export default function OnscreenSection({ <th className="px-1.5 py-0.5">words</th> <th className="w-72 px-1.5 py-0.5">rides on</th> <th className="w-12 px-1.5 py-0.5 text-center">hide</th> + <th className="w-14 px-1.5 py-0.5 text-center" title="a reply: drawn with the post it answers above it (its thread shot)">thread</th> </tr> </thead> <tbody> @@ -1749,6 +1754,23 @@ export default function OnscreenSection({ aria-label={`hide post ${p.id}`} /> </td> + <td className="px-1.5 py-1 text-center"> + {/* Only a post whose capture took a thread shot, or one already set (so it can be cleared). */} + {(p.hasThreadShot || d.thread || p.thread) && ( + <input + type="checkbox" + data-testid="onscreen-post-thread" + checked={d.thread} + onChange={(e) => set({ thread: e.target.checked })} + aria-label={`draw post ${p.id} with the post it answers`} + title={ + p.hasThreadShot + ? "draw the reply with the post it answers above it (shot-thread.png)" + : "no thread shot on disk: its own shot is drawn (pnpm ops capture-posts with \"thread\": true)" + } + /> + )} + </td> </tr> ); })} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -58,7 +58,8 @@ Inbox cannot disagree about what is wrong with one. | `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` · `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` · `clips show <project> [--json]` · `clips segments <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. `--keep-cut` proposes without touching the cut (nothing moved, removed or added; the proposals are listed). **`--scope auto`** reads the narrated video auto-scope finds in the speaker turns (`--segment sN` names one, else the longest); `segments` lists them. A chat replay beside the recording (`live_chat.cues.json`) adds chat-burst moments and the log names the chat's lag. A channel on no site gets each clip linked to its platform page (`citeUrl`). A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) | | `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `remove <id>` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) | | `scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10] [--pad 30 \| --from S --to S] [--json]` | the picture's **scene cuts** (ffmpeg `scdet`, score ≥ threshold) and **black spans** (`blackdetect`) in the clip's fetched window, in SOURCE seconds — for `blur.from`/`blur.to` and trims ([knobs.md](knobs.md#a-clips-picture-blurred)). The window is the one the build would cut from (the project's `out/clips-raw`, the editor's `channels/<slug>/data/<id>/clips/`, a saved source); the extent ± `--pad` inside it is scanned. Nothing is fetched: **exit 1** with no window on disk (`fetch` first) | -| `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run | +| `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key. Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** | +| `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run) | A project argument is an exact id, a directory, or a **unique** basename. Two projects answering to one name is reported, never resolved by picking one. diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -126,6 +126,7 @@ that mentions the seizure in question and one before it. The Marks box is on eve | `render.chrome.deck.<key>` — any of the deck's own keys (`finale`, `pip`, …), as JSON; refused in the build's words when it does not know the key or the value | On-screen settings (the ones it has a field for) | `umtool look <p> deck.finale='{…}'` | — | | `render.chrome.deck.markerLayout` — `stagger` or `truncate` when labels crowd (default: stagger only when a label would truncate) | markers, **layout** | `deck.markerLayout=truncate` | `PUT /api/report/chrome {project, token, markerLayout}` | | `render.chrome.deck.claims[]` — his explicit claims drawn against the record on the rail, at most 6: a `count` or a `goalpost` ([below](#claim-checks-on-the-rail)) | On-screen, **claim checks**: add a count / a goalpost, the clip picker, **use the playhead**, his words, the window's dates, the record's verdict, per, the claim; a goalpost's steps (**add a step**), each its from date and due durations; remove — the build's validator under each as it is typed | `umtool look <p> deck.claims='[…]'` (`deck.claims=` none) | `PUT /api/report/chrome {project, token, claims}` | +| `posts[].thread` — `true`: a reply drawn with the post it answers above it — the capture's `shot-thread.png` beside the post's `shot` (taken by `pnpm ops capture-posts --json '{"slug":…,"ids":[…],"thread":true}'`, the replied-to author's avatar, name and handle blurred unless gold- or grey-checked or the reply's own; `"threadRedact": false` takes it unblurred), the post's own shot while there is none; needs a `shot`. In the feed a thread shot is drawn whole: the card under it leaves rather than the reply being squeezed, and one taller than the column is scaled to fit, never cut; the popup posts pan through it as through any tall shot | Media, On-screen **Posts** table: **thread** (shown once a thread shot is on disk) | `umtool posts set <p> <post> thread=on` (`thread=off` clears it) · on add: `umtool posts add <p> <channel>/<postId> --thread` | `PUT /api/report/posts {project, token, posts: {<id>: {thread}}}` | | `render.blur` — `off`: every clip's picture as recorded, no caption (the uncensored variant); `on` (the default) blurs the clips that ask | Build, **Look**: **Blurred clips** | `umtool look <p> blur=off` · a take: `umtool take <p> --id uncensored --set render.blur=off` | `PUT /api/report/render {project, token, patch: {blur}}` | | `render.intro` — the brand sting the cut opens with: a style (`boot` `boot-wipe` `boot-dark` `boot-cascade` `boot-mark`) or `{style, ground?, mark?, sound?, seconds?, site?, swap?, url?, urlPlace?}`; absent is none ([report-video.md](report-video.md#the-brand-intro-renderintro)) | Build, **Look**: **Intro** | `umtool look <p> intro=boot-dark` (`intro=` none) · a take: `umtool take <p> --id intro-wipe --set render.intro=boot-wipe` | `PUT /api/report/render {project, token, patch: {intro}}` | | `render.intro.site` — on the chime, "Archi" becomes the cited site's name ("Jera"), "lyzer" stays, the colours go to its accent: `auto` (the site whose `siteUrl` is `provenance.siteOrigin`; none found, no swap), a site id, `{name, lead?, accent?, url?}`, or `none`/absent (the plain intro, byte for byte). `render.intro.swap` `swipe-down` (default) \| `roll` \| `wipe`; `render.intro.url` `both` (default: the site's, then archilyzer.pages.dev) \| `site` \| `project` \| `false`; `render.intro.urlPlace` `under` (default: one row under MEDIA) \| `replace` (MEDIA's place) | — (manifest or a take) | a take: `umtool take <p> --id intro-jera --set render.intro.style=boot-dark --set render.intro.mark=chime --set render.intro.site=auto` (`--set render.intro.swap=roll`, `--set render.intro.url=false`, `--set render.intro.urlPlace=replace`) · standalone: `node umtool/report-to-video/intro.mjs render --style boot-dark --mark chime --site auto --site-origin https://jeralyzer.pages.dev --swap wipe --out x.mp4` | `PUT /api/report/render {project, token, patch: {intro: {…, site}}}` | diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -1139,43 +1139,45 @@ export async function updateRender(dir, patch, { token = null } = {}) { } // --------------------------------------------------------------------------- -// POSTS: the two things a person decides about a post once an agent has put it -// in the manifest -- which clip it rides on, and whether it is shown at all. +// POSTS: the things a person decides about a post once an agent has put it +// in the manifest -- which clip it rides on, whether it is shown at all, and +// (a reply) whether it is drawn with the post it answers above it (`thread`: +// the capture's shot-thread.png in place of its shot, when there is one). // // Adding, removing or rewording a post is not here. A post is a quotation of // somebody else's words with a permalink; it is written by whoever cites it, // into the manifest, and this writer refuses to be a second way to do that. // --------------------------------------------------------------------------- -const POST_PATCH_KEYS = ["attachTo", "hide"]; +const POST_PATCH_KEYS = ["attachTo", "hide", "thread"]; /** * A batch of post patches, checked for shape before anything is read: post id - * → `{ attachTo?: string | null, hide?: boolean }`. `attachTo: ""` is the - * same as null (a select's "auto"). + * → `{ attachTo?: string | null, hide?: boolean, thread?: boolean }`. + * `attachTo: ""` is the same as null (a select's "auto"). * * @param {unknown} posts - * @returns {Record<string, { attachTo?: string | null, hide?: boolean }>} + * @returns {Record<string, { attachTo?: string | null, hide?: boolean, thread?: boolean }>} */ export function normalizePostPatches(posts) { if (!posts || typeof posts !== "object" || Array.isArray(posts)) { - throw new Error("posts must be an object of post id → { attachTo, hide }"); + throw new Error("posts must be an object of post id → { attachTo, hide, thread }"); } const ids = Object.keys(posts); if (!ids.length) throw new Error("nothing to change"); - /** @type {Record<string, { attachTo?: string | null, hide?: boolean }>} */ + /** @type {Record<string, { attachTo?: string | null, hide?: boolean, thread?: boolean }>} */ const out = {}; for (const id of ids) { const v = /** @type {Record<string, unknown>} */ (posts)[id]; if (!v || typeof v !== "object" || Array.isArray(v)) { - throw new Error(`${id}: a post patch must be an object with attachTo and/or hide`); + throw new Error(`${id}: a post patch must be an object with attachTo, hide and/or thread`); } for (const k of Object.keys(v)) { if (!POST_PATCH_KEYS.includes(k)) { - throw new Error(`${id}: ${k} is not something this writer changes (only attachTo and hide)`); + throw new Error(`${id}: ${k} is not something this writer changes (only attachTo, hide and thread)`); } } - /** @type {{ attachTo?: string | null, hide?: boolean }} */ + /** @type {{ attachTo?: string | null, hide?: boolean, thread?: boolean }} */ const p = {}; if ("attachTo" in v) { const a = /** @type {Record<string, unknown>} */ (v).attachTo; @@ -1188,15 +1190,20 @@ export function normalizePostPatches(posts) { if (typeof h !== "boolean") throw new Error(`${id}: hide must be true or false`); p.hide = h; } + if ("thread" in v) { + const t = /** @type {Record<string, unknown>} */ (v).thread; + if (typeof t !== "boolean") throw new Error(`${id}: thread must be true or false`); + p.thread = t; + } out[id] = p; } return out; } /** - * Patch the `attachTo` and `hide` of any number of posts, in one write. + * Patch the `attachTo`, `hide` and `thread` of any number of posts, in one write. * - * `attachTo: null` and `hide: false` DELETE the key -- the automatic clip and + * `attachTo: null`, `hide: false` and `thread: false` DELETE the key -- the automatic clip and * a shown post are what an absent key already says, and a manifest read by * humans should not carry `"hide": false` as if somebody decided it. A key the * patch does not name is left alone. @@ -1238,16 +1245,20 @@ export async function updatePosts(dir, posts, { token = null } = {}) { if (p.hide) post.hide = true; else delete post.hide; } + if ("thread" in p) { + if (p.thread) post.thread = true; + else delete post.thread; + } } const errors = validatePosts(manifest.posts, manifest.timeline ?? [], manifest.render); if (errors.length) throw new PostsRefused(errors); const nextToken = await writeManifestAtomic(dir, manifest); - /** @type {Record<string, { attachTo: string | null, hide: boolean }>} */ + /** @type {Record<string, { attachTo: string | null, hide: boolean, thread: boolean }>} */ const saved = {}; for (const id of ids) { const post = byId.get(id); - saved[id] = { attachTo: post.attachTo ?? null, hide: post.hide === true }; + saved[id] = { attachTo: post.attachTo ?? null, hide: post.hide === true, thread: post.thread === true }; } return { posts: saved, token: nextToken }; }); @@ -1768,7 +1779,7 @@ const POST_TEXT_KEYS = ["platform", "author", "handle", "date", "text", "url", " /** * Add a post, or replace the one with its id. The value is the post as it * should be stored: an empty optional string is dropped rather than written. - * `attachTo` and `hide` are kept from the stored post unless the value names + * `attachTo`, `hide` and `thread` are kept from the stored post unless the value names * them. Checked with the build's validatePosts. * * @param {string} dir @@ -1788,7 +1799,7 @@ export async function upsertPost(dir, post, { token = null } = {}) { if (v === undefined || v === null || (typeof v === "string" && !v.trim())) continue; next[k] = typeof v === "string" ? v.trim() : v; } - for (const k of ["attachTo", "hide"]) { + for (const k of ["attachTo", "hide", "thread"]) { const v = k in post ? post[k] : prev[k]; if (v === undefined || v === null || v === "" || v === false) continue; next[k] = v; diff --git a/umtool/lib/report/manifest.test.mjs b/umtool/lib/report/manifest.test.mjs @@ -21,6 +21,7 @@ import { updateClip, updateOnscreen, updatePosts, + upsertPost, } from "./manifest.mjs"; import { validateCutEdits } from "umtool-report-to-video/deck"; @@ -399,7 +400,7 @@ test("updatePosts: attachTo and hide round trip; null and false delete the key; try { const token = await manifestToken(dir); const res = await updatePosts(dir, { p1: { attachTo: "c02", hide: true }, p2: { attachTo: null, hide: false } }, { token }); - assert.deepEqual(res.posts, { p1: { attachTo: "c02", hide: true }, p2: { attachTo: null, hide: false } }); + assert.deepEqual(res.posts, { p1: { attachTo: "c02", hide: true, thread: false }, p2: { attachTo: null, hide: false, thread: false } }); assert.equal(res.token, await manifestToken(dir)); const raw = await readRaw(dir); assert.ok(raw.startsWith('{\n "slug"') && raw.endsWith("}\n"), "the CLI's formatting kept"); @@ -422,6 +423,28 @@ test("updatePosts: attachTo and hide round trip; null and false delete the key; } }); +test("updatePosts: thread round trips on a post with a shot (false deletes it); a post with no shot is refused it; upsertPost keeps it", async () => { + const m0 = withPosts(); + m0.posts[0].shot = "posts-media/acct/1/shot.png"; + const dir = await project(m0); + try { + const res = await updatePosts(dir, { p1: { thread: true } }); + assert.deepEqual(res.posts.p1, { attachTo: null, hide: false, thread: true }); + assert.equal(post(await read(dir), "p1").thread, true); + // Replaced by a writer that does not name it: kept, as attachTo is. + await upsertPost(dir, { ...m0.posts[0], text: "one, again" }); + assert.equal(post(await read(dir), "p1").thread, true); + await updatePosts(dir, { p1: { thread: false } }); + assert.ok(!("thread" in post(await read(dir), "p1")), "thread: false deletes the key"); + await assert.rejects(updatePosts(dir, { p1: { thread: "yes" } }), /thread must be true or false/); + const before = await readRaw(dir); + await assert.rejects(updatePosts(dir, { p2: { thread: true } }), /posts\[1\]\.thread draws the thread shot beside the post's shot/); + assert.equal(await readRaw(dir), before); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + test("updatePosts: an unknown post id refuses the WHOLE batch and writes nothing", async () => { const dir = await project(withPosts()); try { diff --git a/umtool/lib/report/onscreen.mjs b/umtool/lib/report/onscreen.mjs @@ -36,6 +36,7 @@ import { postWindows, resolveDeck, roundPosts, + threadShotOf, transitionOf, } from "umtool-report-to-video/deck"; import { marksOf, rawMarksOf, roundStamps, stampSchedule } from "umtool-report-to-video/factcheck"; @@ -304,6 +305,10 @@ export function applyPostsDraft(posts, draft = {}) { if (d.hide) out.hide = true; else delete out.hide; } + if ("thread" in d) { + if (d.thread) out.thread = true; + else delete out.thread; + } return out; }); } @@ -351,7 +356,7 @@ export function postRows({ variantManifest, metas, schedule = null }) { const entries = variantManifest.timeline ?? []; const posts = Array.isArray(variantManifest.posts) ? variantManifest.posts : []; const labelOf = new Map(entries.map((e, i) => [e.id, clipLabel(e, metas[i] ?? null)])); - const bare = posts.map(({ attachTo: _a, hide: _h, ...p }) => p); + const bare = posts.map(({ attachTo: _a, hide: _h, thread: _t, ...p }) => p); const auto = new Map(attachPosts({ posts: bare, entries, metas }).map((a) => [a.id, a])); const effective = new Map(attachPosts({ posts, entries, metas }).map((a) => [a.id, a])); const timing = new Map((schedule?.posts ?? []).map((p) => [p.id, p])); @@ -369,6 +374,10 @@ export function postRows({ variantManifest, metas, schedule = null }) { url: p.url, attachTo: p.attachTo ?? null, hide: p.hide === true, + // A reply drawn with the post it answers (its thread shot, when the + // capture took one -- the route says whether it is on disk). + thread: p.thread === true, + threadShot: threadShotOf(p.shot), auto: where(auto.get(p.id)), effective: p.hide ? null : where(effective.get(p.id)), // A popup post's appear and leave, or a feed post's tick-in (`in`). diff --git a/umtool/lib/report/onscreen.test.mjs b/umtool/lib/report/onscreen.test.mjs @@ -229,7 +229,7 @@ test("applyPostsDraft: the writer's rule, on a copy", () => { assert.equal(applyPostsDraft(posts, {}), posts); assert.deepEqual(normalizePostsDraft(undefined), {}); assert.deepEqual(normalizePostsDraft({}), {}); - assert.throws(() => normalizePostsDraft({ p1: { text: "x" } }), /only attachTo and hide/); + assert.throws(() => normalizePostsDraft({ p1: { text: "x" } }), /only attachTo, hide and thread/); }); test("postRows: the automatic clip, the effective one, and the slot in the schedule", () => { @@ -261,6 +261,23 @@ test("postRows: the automatic clip, the effective one, and the slot in the sched assert.deepEqual(postRows({ variantManifest: cut(), metas }).posts, []); }); +test("postRows and the draft: a reply's thread choice and where its thread shot would be", () => { + const m = withPosts(); + m.posts[0].shot = "posts-media/acct/1/shot.png"; + m.posts[0].thread = true; + const by = Object.fromEntries(postRows({ variantManifest: m, metas }).posts.map((p) => [p.id, p])); + assert.equal(by.p1.thread, true); + assert.equal(by.p1.threadShot, "posts-media/acct/1/shot-thread.png"); + assert.equal(by.p2.thread, false); + assert.equal(by.p2.threadShot, null); + // The draft's thread, by the writer's rule: false removes the key. + const out = applyPostsDraft(m.posts, { p1: { thread: false }, p2: { thread: true } }); + assert.ok(!("thread" in out[0])); + assert.equal(out[1].thread, true); + assert.deepEqual(normalizePostsDraft({ p1: { thread: true } }), { p1: { thread: true } }); + assert.throws(() => normalizePostsDraft({ p1: { thread: "on" } }), /thread must be true or false/); +}); + test("clipLabel: deck title, then the quote, then the stream's title", () => { assert.equal(clipLabel({ onscreen: { title: "T" }, quote: "q" }, { title: "m" }), "T"); assert.equal(clipLabel({ quote: " q " }, { title: "m" }), "q"); diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -3,7 +3,13 @@ // link and handle as the archive holds them, and its screenshot. // // umtool posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] -// [--author A] [--id ID] [--dry-run] [--json] +// [--author A] [--id ID] [--thread] [--dry-run] [--json] +// umtool posts set <project> <post> thread=on|off [hide=on|off] [attach=<clipId>|auto] [--json] +// +// `--thread` / `thread=on` draws a reply with the post it answers above it: +// the capture's `shot-thread.png` beside its `shot.png` (capture-posts +// `"thread": true` takes it), the post's own shot while there is none. `set` +// is updatePosts -- the writer the Posts table's Save runs. // // The row is `channels/<slug>/posts/YYYY-MM.jsonl`'s (common/lib/posts-server.ts // owns that layout; an X id names its month, so its shard is read first). The @@ -27,16 +33,20 @@ import path from "node:path"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { channelsDirFor, readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; -import { StaleToken, StructureRefused, manifestToken, upsertPost } from "./manifest.mjs"; +import { PostsRefused, StaleToken, StructureRefused, manifestToken, updatePosts, upsertPost } from "./manifest.mjs"; export const POSTS_USAGE = [ "usage: umtool posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID]", - " [--dry-run] [--json]", + " [--thread] [--dry-run] [--json]", + " umtool posts set <project> <post> thread=on|off [hide=on|off] [attach=<clipId>|auto] [--json]", " a post card from the corpus's posts archive (channels/<slug>/posts/*.jsonl): its words, date, link and handle,", " and its screenshot (channels/<slug>/posts-media/<postId>/shot.png) copied into the project's posts-media/.", " The id is x-<postId> (bsky-, post-) unless --id; --attach pins it to a clip; --author overrides the name", " (default: the name an earlier post by the same handle carries in this cut, else the archive's).", " A post with no screenshot is refused: `pnpm ops capture-posts --json '{\"slug\":…,\"ids\":[…]}'` first.", + " --thread (or `set … thread=on`): a reply drawn with the post it answers above it -- the capture's", + " shot-thread.png beside shot.png (capture-posts with \"thread\": true takes it); its own shot while there is none.", + " set: <post> is the manifest's post id (x-<postId>) or the bare <postId>; the Posts table's writer.", ].join("\n"); const VALUED = new Set(["--attach", "--flag", "--author", "--id"]); @@ -99,7 +109,7 @@ export const projectShotRel = (slug, postId) => `posts-media/${slug}/${postId}/s * name an earlier post by the same handle carries (the Huck cut's posts say * "Jeremy Hambly", the archive "TheQuartering"). */ -export function postEntryOf(row, { slug, postId, manifest = null, attach = null, flag = null, author = null, id = null }) { +export function postEntryOf(row, { slug, postId, manifest = null, attach = null, flag = null, author = null, id = null, thread = false }) { const platform = deckPlatformOf(row.platform); const handle = typeof row.author === "string" && row.author ? row.author.replace(/^@/, "") : null; const earlier = (Array.isArray(manifest?.posts) ? manifest.posts : []).find( @@ -121,10 +131,49 @@ export function postEntryOf(row, { slug, postId, manifest = null, attach = null, ...(attach ? { attachTo: attach } : {}), text: typeof row.text === "string" ? row.text : "", shot: projectShotRel(slug, postId), + ...(thread ? { thread: true } : {}), ...(flag ? { flag } : {}), }; } +const ON = new Set(["on", "true", "yes", "1"]); +const OFF = new Set(["off", "false", "no", "0"]); + +/** + * `posts set`'s words as the Posts table's patch: `thread=on|off`, + * `hide=on|off`, `attach=<clipId>|auto`. Throws on anything else. + * + * @param {string[]} pairs + * @returns {{ attachTo?: string | null, hide?: boolean, thread?: boolean }} + */ +export function postPatchOf(pairs) { + /** @type {{ attachTo?: string | null, hide?: boolean, thread?: boolean }} */ + const out = {}; + for (const pair of pairs) { + const eq = pair.indexOf("="); + const k = eq > 0 ? pair.slice(0, eq) : pair; + const v = eq > 0 ? pair.slice(eq + 1).toLowerCase() : ""; + if (k === "thread" || k === "hide") { + if (ON.has(v)) out[k] = true; + else if (OFF.has(v)) out[k] = false; + else throw new CliError(`${k}= takes on or off, not ${JSON.stringify(v)}`); + } else if (k === "attach") { + if (!v) throw new CliError("attach= takes a clip id, or auto"); + out.attachTo = v === "auto" ? null : pair.slice(eq + 1); + } else throw new CliError(`${pair}: not a post knob (thread=, hide=, attach=)`); + } + if (!Object.keys(out).length) throw new CliError("nothing to set: thread=on|off, hide=on|off or attach=<clipId>|auto"); + return out; +} + +/** The manifest's post `ref` names: its id, or an x-/bsky-/post- id with that native id. */ +export function findPostId(manifest, ref) { + const posts = Array.isArray(manifest?.posts) ? manifest.posts : []; + if (posts.some((p) => p?.id === ref)) return ref; + const hits = posts.filter((p) => typeof p?.id === "string" && ["x-", "bsky-", "post-"].some((pre) => p.id === pre + ref)); + return hits.length === 1 ? hits[0].id : null; +} + /** What of a capture's directory is copied beside the manifest: the shot, its record, the post's pictures. */ export const CAPTURE_COPY_RE = /^(?:shot\.png|capture\.json|.+\.(?:png|jpe?g|webp|gif))$/i; @@ -205,10 +254,11 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con }; try { const [verb, projectArg, ref] = words; - if (verb !== "add" || !projectArg || !ref || flags.has("--help")) { + if ((verb !== "add" && verb !== "set") || !projectArg || !ref || flags.has("--help")) { err(POSTS_USAGE); return 2; } + if (verb === "set") return await setCommand(projectArg, ref, words.slice(3), { root, json, out }); const slash = ref.indexOf("/"); const slug = slash > 0 ? ref.slice(0, slash) : ""; const postId = slash > 0 ? ref.slice(slash + 1) : ""; @@ -240,7 +290,11 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con if (attach && !(manifest.timeline ?? []).some((e) => e?.type === "clip" && e.id === attach)) { throw new CliError(`--attach ${attach}: no clip with that id in ${project.id}`); } - const post = postEntryOf(found.row, { slug, postId, manifest, attach, flag: str("--flag"), author: str("--author"), id: str("--id") }); + const thread = flags.has("--thread"); + const post = postEntryOf(found.row, { slug, postId, manifest, attach, flag: str("--flag"), author: str("--author"), id: str("--id"), thread }); + // A thread shot asked for and not taken: the card draws its own shot until a capture takes one. + const threadFrom = path.join(path.dirname(shotFrom), "shot-thread.png"); + const threadMissing = thread && !(await stat(threadFrom).catch(() => null)); const shotTo = path.join(project.dir, ...post.shot.split("/")); if (dryRun) { out(json ? JSON.stringify({ ok: true, dryRun: true, post, shard: found.shard, shotFrom, shotTo }, null, 2) : `would add ${post.id} (${found.shard}):\n${JSON.stringify(post, null, 2)}\n shot ${shotFrom} -> ${shotTo}`); @@ -259,12 +313,19 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con upsertPost(project.dir, post, { token: await manifestToken(project.dir) }), ); if (json) { - out(JSON.stringify({ ok: true, ...result, shard: found.shard, shot: { from: shotFrom, to: shotTo, via: where }, copied, editNotes }, null, 2)); + out(JSON.stringify({ ok: true, ...result, shard: found.shard, shot: { from: shotFrom, to: shotTo, via: where }, copied, ...(thread ? { threadShot: !threadMissing } : {}), editNotes }, null, 2)); return 0; } out(`${result.created ? "added" : "replaced"} post ${result.post.id}${result.post.attachTo ? ` -> ${result.post.attachTo}` : ""} ${result.post.date}`); out(` ${result.post.author ?? ""}${result.post.handle ? ` @${result.post.handle}` : ""}: ${result.post.text.split("\n")[0].slice(0, 100)}`); out(` shot ${result.post.shot}${where === "linked" ? " (posts-media links the channel's captures)" : copied.length ? ` (copied: ${copied.join(", ")})` : " (already there)"}`); + if (threadMissing) { + out( + ` thread: no shot-thread.png yet -- its own shot is drawn until one is taken:\n` + + ` pnpm ops capture-posts --json '${JSON.stringify({ slug, ids: [postId], thread: true })}'` + + (where === "linked" ? "" : `\n then umtool posts add again (it copies the new shot in)`), + ); + } else if (thread) out(" thread: drawn with the post it answers (shot-thread.png)"); if (result.snapshot?.rel && !result.snapshot.skipped) out(` undo point: ${result.snapshot.rel}`); if (editNotes) { out( @@ -275,6 +336,10 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con } return 0; } catch (e) { + if (e instanceof PostsRefused) { + err(`umtool posts: refused — the build would not take it:\n${e.errors.map((x) => ` ${x}`).join("\n")}`); + return 1; + } if (e instanceof StructureRefused) { err(`umtool posts: refused — the build would not take it:\n${e.errors.map((x) => ` ${x}`).join("\n")}`); return 1; @@ -287,3 +352,33 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con return e instanceof CliError ? 2 : 1; } } + +/** `posts set`: the Posts table's writer (updatePosts), from the CLI. */ +async function setCommand(projectArg, ref, pairs, { root, json, out }) { + const patch = postPatchOf(pairs); + const r = await resolveProject(projectArg, root); + if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${projectArg}"`); + const project = r.project; + const manifest = await readManifest(project.dir); + if (!manifest) throw new CliError(`${project.id} has no manifest`); + const id = findPostId(manifest, ref); + if (!id) throw new CliError(`no post ${ref} in ${project.id} (its id, or x-<postId>)`); + const { result, editNotes } = await withEditNotes(project, async () => + updatePosts(project.dir, { [id]: patch }, { token: await manifestToken(project.dir) }), + ); + const saved = result.posts[id]; + const post = manifest.posts.find((p) => p?.id === id); + const threadFile = saved.thread && typeof post?.shot === "string" + ? path.join(project.dir, ...post.shot.split("/").slice(0, -1), "shot-thread.png") + : null; + const threadThere = threadFile ? Boolean(await stat(threadFile).catch(() => null)) : null; + if (json) { + out(JSON.stringify({ ok: true, id, post: saved, ...(threadThere === null ? {} : { threadShot: threadThere }), token: result.token, editNotes }, null, 2)); + return 0; + } + out(`set ${id}: thread ${saved.thread ? "on" : "off"}, ${saved.hide ? "hidden" : "shown"}, rides on ${saved.attachTo ?? "auto"}`); + if (threadThere === false) out(" no shot-thread.png beside its shot yet -- its own shot is drawn (capture-posts with \"thread\": true)"); + if (editNotes) out(` edit noted for ${editNotes.generatedBy}`); + return 0; +} diff --git a/umtool/lib/report/postsCli.test.mjs b/umtool/lib/report/postsCli.test.mjs @@ -166,3 +166,62 @@ test("posts add never copies through a link out of the project: linked captures assert.deepEqual(await readdir(away), []); assert.equal(await shotHome(other, path.join(other, "posts-media", "fresh", "1"), path.join(CHANNELS, "acct-X", "posts-media")), "project"); }); + +test("posts add --thread: the entry asks for the thread shot, copied beside its shot; with none yet it says which capture takes it", async () => { + // A reply with a thread shot, and one without. + const RID = "2114214000653414579"; + const NID = "2114580970087108886"; + const posts = path.join(CHANNELS, "acct-R", "posts"); + await mkdir(posts, { recursive: true }); + const row = (id, text) => JSON.stringify({ ...ROW, id, channelSlug: "acct-R", text, url: `https://x.com/Acct/status/${id}`, createdAt: "2026-10-25T04:34:32.000Z" }); + await writeFile(path.join(posts, "2026-10.jsonl"), [row(RID, "@someone Well.."), row(NID, "@other He eats raw"), ""].join("\n")); + for (const id of [RID, NID]) { + await mkdir(path.join(CHANNELS, "acct-R", "posts-media", id), { recursive: true }); + await writeFile(path.join(CHANNELS, "acct-R", "posts-media", id, "shot.png"), "PNG"); + } + await writeFile(path.join(CHANNELS, "acct-R", "posts-media", RID, "shot-thread.png"), "THREAD"); + const dir = await project("thread"); + const { lines, run } = runner(); + assert.equal(await run("add", "thread", `acct-R/${RID}`, "--thread", "--json"), 0); + const res = JSON.parse(lines.at(-1)); + assert.equal(res.post.thread, true); + assert.equal(res.threadShot, true); + assert.ok(res.copied.includes("shot-thread.png"), "the thread shot is copied in with the shot"); + assert.equal(await readFile(path.join(dir, "posts-media", "acct-R", RID, "shot-thread.png"), "utf8"), "THREAD"); + + assert.equal(await run("add", "thread", `acct-R/${NID}`, "--thread"), 0); + assert.ok(lines.some((l) => /no shot-thread\.png yet/.test(l))); + assert.ok(lines.some((l) => l.includes(`"thread":true`) && l.includes("capture-posts"))); + const m = await read(dir); + assert.equal(m.posts.find((p) => p.id === `x-${NID}`).thread, true, "asked for: drawn once a capture takes it"); + + // Replaced without --thread: the choice is kept, as attachTo is. + assert.equal(await run("add", "thread", `acct-R/${RID}`, "--json"), 0); + assert.equal(JSON.parse(lines.at(-1)).post.thread, true); +}); + +test("posts set: the Posts table's writer -- thread on/off by the post's id or its bare id; refusals in words", async () => { + const dir = await project("set"); + const { lines, run } = runner(); + assert.equal(await run("add", "set", `acct-X/${XID}`), 0); + assert.equal(await run("set", "set", XID, "thread=on", "--json"), 0); + const on = JSON.parse(lines.at(-1)); + assert.equal(on.id, `x-${XID}`); + assert.deepEqual(on.post, { attachTo: null, hide: false, thread: true }); + assert.equal(on.threadShot, false, "no thread shot beside its shot: its own is drawn"); + assert.equal((await read(dir)).posts.find((p) => p.id === `x-${XID}`).thread, true); + assert.equal(await run("set", "set", `x-${XID}`, "thread=off", "hide=on", "attach=c01"), 0); + const off = (await read(dir)).posts.find((p) => p.id === `x-${XID}`); + assert.equal("thread" in off, false, "off removes the key"); + assert.equal(off.hide, true); + assert.equal(off.attachTo, "c01"); + assert.equal(await run("set", "set", XID, "thread=maybe"), 2); + assert.match(lines.at(-1), /thread= takes on or off/); + assert.equal(await run("set", "set", "nope", "thread=on"), 2); + assert.match(lines.at(-1), /no post nope/); + assert.equal(await run("set", "set", XID, "attach=c99"), 1); + assert.match(lines.at(-1), /refused/); + // The build's check: a post with no shot cannot ask for a thread shot. + assert.equal(await run("set", "set", "x-1", "thread=on"), 1); + assert.match(lines.at(-1), /thread draws the thread shot beside the post's shot/); +}); diff --git a/umtool/report-to-video/chrome-feed.mjs b/umtool/report-to-video/chrome-feed.mjs @@ -264,6 +264,38 @@ export function feedShotLone({ heights, shots, column, gap = 16 }) { } /** + * feedShotLone, and a `whole` picture: a reply's THREAD SHOT (the post it + * answers over the reply, posts[].thread) must be read top to bottom, so one + * that would not be drawn at its full height beside the card under it takes + * the column instead -- that card is pushed out as feedCues pushes any card + * that no longer fits -- and one taller than the column is scaled down to + * it whole (`.shot` is object-fit: contain, so the reply is never cut off). + * Without a `whole` shot it is exactly feedShotLone. PURE and SELF-CONTAINED + * (embedded like feedCues); only a page with a thread shot carries it, so a + * page without one is byte-for-byte what it was. + * + * @returns {{ imgs: Array<number|null>, heights: number[] }} + */ +export function feedShotWhole({ heights, shots, column, gap = 16 }) { + const out = heights.slice(); + const imgs = heights.map(() => null); + for (let j = 0; j < out.length; j += 1) { + const s = shots[j]; + if (!s || !(s.full > s.drawn + 1)) continue; + const chrome = (heights[j] || 0) - s.drawn; + const stays = j > 0 && (heights[j] || 0) + gap + out[j - 1] <= column; + const fitsBeside = stays && Math.floor(column - out[j - 1] - gap - chrome) >= Math.round(s.full); + const beside = stays && (!s.whole || fitsBeside) ? out[j - 1] + gap : 0; + const room = Math.floor(column - beside - chrome); + const img = Math.min(Math.round(s.full), room); + if (img <= s.drawn) continue; + imgs[j] = img; + out[j] = chrome + img; + } + return { imgs, heights: out }; +} + +/** * Who the feed is, for its header: the one author's name and platform when * every post is theirs, else "Posts" and every platform there is. */ @@ -296,6 +328,7 @@ export function feedHtml(schedule, render, opts = {}) { const fonts = opts.fonts ?? {}; const qrSrcs = opts.qrSrcs ?? {}; const shotSrcs = opts.shotSrcs ?? {}; + const threadShots = new Set(opts.threadShots ?? []); const gsapSrc = opts.gsap ?? "assets/gsap.min.js"; const total = schedule.total; const from = Number(opts.from ?? 0); @@ -311,6 +344,9 @@ export function feedHtml(schedule, render, opts = {}) { // without a picture keeps feedShotRoom's text, so its bytes -- and the // render cache keyed on them -- are what they were. const anyShot = posts.some((p) => shotSrcs[p.id]); + // A thread shot drawn whole (feedShotWhole); only such a page carries it. + const anyThread = posts.some((p) => shotSrcs[p.id] && threadShots.has(p.id)); + const roomFn = anyThread ? "feedShotWhole" : anyShot ? "feedShotLone" : "feedShotRoom"; const panel = deck.background === "panel"; // The column's ground meets the deck's top edge in the deck's own colour, @@ -325,10 +361,12 @@ export function feedHtml(schedule, render, opts = {}) { const { name, platform } = postWho(p); const src = qrSrcs[p.id]; const shot = shotSrcs[p.id]; + // A thread shot is marked, so the page gives it the column (feedShotLone `whole`). + const whole = threadShots.has(p.id) ? ` data-thread="1"` : ""; return ( `<article class="post${shot ? " has-shot" : ""}" data-post="${esc(p.id)}" data-k="c${j}">` + (shot - ? `<div class="body shot-body"><img class="shot" src="${esc(shot)}" alt=""></div>` + ? `<div class="body shot-body"><img class="shot" src="${esc(shot)}"${whole} alt=""></div>` : `<div class="body">` + `<div class="meta">` + (who.single ? "" : (platform ? `<span class="platform">${esc(platform)}</span>` : "") + @@ -481,7 +519,7 @@ export function feedHtml(schedule, render, opts = {}) { const byK = {}; for (const el of document.querySelectorAll("[data-k]")) byK[el.dataset.k] = el; ${embedFn("feedCues", feedCues)} - ${anyShot ? embedFn("feedShotLone", feedShotLone) : embedFn("feedShotRoom", feedShotRoom)} + ${anyThread ? embedFn("feedShotWhole", feedShotWhole) : anyShot ? embedFn("feedShotLone", feedShotLone) : embedFn("feedShotRoom", feedShotRoom)} const params = new URLSearchParams(location.search); // A window plays the cut's [from, from + dur]; the page is seeked in its own seconds. @@ -529,9 +567,9 @@ export function feedHtml(schedule, render, opts = {}) { const img = c.querySelector("img.shot"); if (!img || !img.naturalWidth) return null; const full = (img.parentElement.clientWidth - 2 * F.shotPad) * img.naturalHeight / img.naturalWidth; - return { drawn: img.offsetHeight, full }; + return ${anyThread ? "img.dataset.thread ? { drawn: img.offsetHeight, full, whole: true } : " : ""}{ drawn: img.offsetHeight, full }; }); - const room = ${anyShot ? "feedShotLone" : "feedShotRoom"}({ heights: cards.map((c) => c.offsetHeight), shots, column: F.column, gap: F.motion.gap }); + const room = ${roomFn}({ heights: cards.map((c) => c.offsetHeight), shots, column: F.column, gap: F.motion.gap }); room.imgs.forEach((h, j) => { if (h != null) cards[j].querySelector("img.shot").style.maxHeight = h + "px"; }); const heights = cards.map((c) => c.offsetHeight); document.documentElement.dataset.shots = room.imgs.map((h) => h ?? "").join(","); diff --git a/umtool/report-to-video/chrome-feed.test.mjs b/umtool/report-to-video/chrome-feed.test.mjs @@ -11,7 +11,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; -import { FEED_MOTION, feedCues, feedHtml, feedLayout, feedShotLone, feedShotRoom, feedWho } from "./chrome-feed.mjs"; +import { FEED_MOTION, feedCues, feedHtml, feedLayout, feedShotLone, feedShotRoom, feedShotWhole, feedWho } from "./chrome-feed.mjs"; import { deckChoreography, deckGeometry, deckSchedule, estimateSchedule, feedGeometry, feedOn, postHolds, postSchedule, postsGeometry, postWindows, validateChrome, validatePosts, @@ -515,3 +515,48 @@ test("the page: the screenshot rule rides in the page and sizes the pictures bef assert.ok(grow > 0 && plan > grow, "pictures are sized before the stack is planned from the heights"); assert.match(html, /"shotPad":10/); }); + +test("feedShotWhole: without a thread shot it is exactly feedShotLone", () => { + for (const args of [ + { heights: [200, 310], shots: [null, { drawn: 290, full: 900 }], column: 700, gap: 16 }, + { heights: [310, 310, 310], shots: [{ drawn: 290, full: 900 }, { drawn: 290, full: 900 }, { drawn: 290, full: 470 }], column: 760 }, + { heights: [600, 310], shots: [null, { drawn: 290, full: 470 }], column: 760, gap: 16 }, + { heights: [120, 310, 130, 310], shots: [null, { drawn: 290, full: 380 }, null, { drawn: 290, full: 330 }], column: 760 }, + ]) { + assert.deepEqual(feedShotWhole(args), feedShotLone(args), JSON.stringify(args)); + } +}); + +test("feedShotWhole: a thread shot is drawn whole -- the card under it leaves rather than the reply being squeezed", () => { + // Card 0 words (200); card 1 a thread shot drawn at 290 of a full 620 (chrome 20); column 760. + // Beside the card under it: 760 - 216 - 20 = 524 < 620, so feedShotLone draws it at 524; + // a whole one takes the column and is drawn at its full 620, the card under it pushed out. + const args = { heights: [200, 310], shots: [null, { drawn: 290, full: 620 }], column: 760, gap: 16 }; + assert.deepEqual(feedShotLone(args).imgs, [null, 524]); + const whole = { ...args, shots: [null, { drawn: 290, full: 620, whole: true }] }; + const r = feedShotWhole(whole); + assert.deepEqual(r.imgs, [null, 620]); + const plan = feedCues({ posts: [{ id: "a", in: 1 }, { id: "b", in: 5 }], heights: r.heights, column: 760 }); + assert.deepEqual(plan.gone, [5, null], "the card under the thread shot leaves as it lands"); + // One that fits beside the card under it keeps that card. + const fits = { heights: [200, 310], shots: [null, { drawn: 290, full: 480, whole: true }], column: 760, gap: 16 }; + assert.deepEqual(feedShotWhole(fits).imgs, [null, 480]); + assert.ok(200 + 16 + 20 + 480 <= 760); + // Taller than the column: drawn at the column's height (scaled to fit by object-fit: contain, never cut). + const tall = feedShotWhole({ heights: [200, 310], shots: [null, { drawn: 290, full: 1500, whole: true }], column: 760, gap: 16 }); + assert.deepEqual(tall.imgs, [null, 740]); + assert.deepEqual(tall.heights, [200, 760]); +}); + +test("the page: a thread shot is marked and carries feedShotWhole; the .shot rule scales it to fit, never crops", () => { + const posts = POSTS.map((p) => (p.id === "b" ? { ...p, shot: "shots/b.png", thread: true } : p)); + const { html } = page(posts, { shotSrcs: { b: "assets/shot00.png" }, threadShots: ["b"] }); + assert.ok(html.includes('<img class="shot" src="assets/shot00.png" data-thread="1" alt="">')); + assert.match(html, /const feedShotWhole = /); + assert.match(html, /const room = feedShotWhole\(\{ heights/); + assert.match(html, /img\.dataset\.thread \? \{ drawn: img\.offsetHeight, full, whole: true \}/); + assert.match(html, /\.shot \{[^}]*object-fit: contain/); + // Named but its picture is the post's own (no thread shot on disk): a plain shot page. + const plain = page(posts, { shotSrcs: { b: "assets/shot00.png" } }).html; + assert.doesNotMatch(plain, /feedShotWhole|data-thread/); +}); diff --git a/umtool/report-to-video/chrome-posts.test.mjs b/umtool/report-to-video/chrome-posts.test.mjs @@ -15,7 +15,8 @@ import { fileURLToPath } from "node:url"; import { postDate, postParagraphs, postsCues, postsHtml, postWho, snapWindow, windowPosts, } from "./chrome-posts.mjs"; -import { postSchedule, postsGeometry, postWindows, validatePosts } from "./deck.mjs"; +import { postSchedule, postsGeometry, postWindows, threadShotOf, validatePosts } from "./deck.mjs"; +import { postThreadFile } from "./compose-chrome.mjs"; import { applyChromeArgs, chromeOverlayChain, chromeRegions, postsRegions } from "./build-video.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); @@ -548,3 +549,35 @@ test("postsHtml: a screenshot sits in a viewport at the card's width, and the pa assert.doesNotMatch(html, /\.shot \{[^}]*object-fit/, "never shrunk to fit"); assert.match(html, /const pans = cards\.map/); }); + +test("thread: a reply's thread shot is asked for on a post with a shot, placed with it, and found beside the shot", async () => { + const shot = "posts-media/acct-x-replies/2114214000653414579/shot.png"; + assert.deepEqual(validatePosts([POST("a", "2026-01-01", { shot, thread: true })]), []); + assert.deepEqual(validatePosts([POST("a", "2026-01-01", { shot, thread: false })]), []); + assert.match(validatePosts([POST("a", "2026-01-01", { shot, thread: "yes" })]).join(" | "), /posts\[0\]\.thread must be true or false/); + assert.match(validatePosts([POST("a", "2026-01-01", { thread: true })]).join(" | "), /posts\[0\]\.thread draws the thread shot beside the post's shot/); + assert.equal(threadShotOf(shot), "posts-media/acct-x-replies/2114214000653414579/shot-thread.png"); + assert.equal(threadShotOf("shot.png"), "shot-thread.png"); + assert.equal(threadShotOf(undefined), null); + // Placed: the schedule carries it beside the shot; a post without one places as it always did. + const placed = postSchedule({ + posts: [POST("a", "2024-10-19", { shot, thread: true }), POST("b", "2024-10-20", { thread: true }), POST("c", "2024-10-21", { shot })], + entries: CLIPS, segments: SEGS, D: 0.5, total: 28.5, render: RENDER, + }); + const by = Object.fromEntries(placed.map((p) => [p.id, p])); + assert.equal(by.a.thread, true); + assert.ok(!("thread" in by.b) && !("thread" in by.c)); + // The composer draws the thread shot only when it is on disk; else the post's own. + const dir = mkdtempSync(path.join(tmpdir(), "thread-shot-")); + try { + const at = path.join(dir, "posts-media", "acct-x-replies", "2114214000653414579"); + mkdirSync(at, { recursive: true }); + writeFileSync(path.join(at, "shot.png"), "PNG"); + assert.equal(await postThreadFile({ shot, thread: true }, dir), null, "none taken yet: its own shot"); + writeFileSync(path.join(at, "shot-thread.png"), "PNG2"); + assert.equal(await postThreadFile({ shot, thread: true }, dir), path.join(at, "shot-thread.png")); + assert.equal(await postThreadFile({ shot }, dir), null, "not asked for"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs @@ -31,7 +31,7 @@ // and the crossfade -- so the build writes the schedule and this reads it. // Recomputing it here would be a second implementation of segmentOffsets() and // would drift the first time the transition changed. -import { copyFile, link, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { copyFile, link, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import { execFile, spawn } from "node:child_process"; import { promisify } from "node:util"; import path from "node:path"; @@ -52,7 +52,7 @@ import { threadsHtml } from "./chrome-threads.mjs"; import { flipsHtml } from "./chrome-flips.mjs"; import { statsHtml } from "./chrome-stats.mjs"; import { finaleHtml, finaleLayout } from "./chrome-finale.mjs"; -import { fxGeometry } from "./deck.mjs"; +import { fxGeometry, threadShotOf } from "./deck.mjs"; import { FRAME_KEY_REGIONS, frameKeys } from "./frame-keys.mjs"; const run = promisify(execFile); @@ -621,6 +621,23 @@ async function copyFonts(render, assetsDir, names, { strict }) { } /** + * A placed post's thread shot on disk (`thread: true`, deck.mjs threadShotOf: + * `shot-thread.png` beside its shot), or null: not asked for, or the capture + * took none (not a reply, no parent shown) -- the post's own shot is drawn + * instead, as before. + * + * @returns {Promise<string|null>} + */ +export async function postThreadFile(p, manifestDir) { + if (p?.thread !== true) return null; + const rel = threadShotOf(p.shot); + if (!rel) return null; + const file = path.resolve(manifestDir, rel); + const st = await stat(file).catch(() => null); + return st?.isFile() ? file : null; +} + +/** * The posts' screenshots (`posts[].shot`, relative to the manifest) -- or, * with `key` "logo", their logos (`posts[].logo`) -- copied * in beside the page as `shotNN<ext>` (`logoNN<ext>`), one per distinct file. Returns @@ -628,12 +645,14 @@ async function copyFonts(render, assetsDir, names, { strict }) { * the region: a card drawn without the picture its post names is not the * card the manifest asks for. */ -async function copyShots(posts, manifestDir, assetsDir, key = "shot") { +async function copyShots(posts, manifestDir, assetsDir, key = "shot", threads = null) { const out = {}; const byFile = new Map(); for (const p of posts) { if (typeof p[key] !== "string" || !p[key]) continue; - const file = path.resolve(manifestDir, p[key]); + const thread = key === "shot" ? await postThreadFile(p, manifestDir) : null; + if (thread) threads?.add(p.id); + const file = thread ?? path.resolve(manifestDir, p[key]); if (!byFile.has(file)) { const name = `${key}${String(byFile.size).padStart(2, "0")}${path.extname(file).toLowerCase()}`; try { @@ -786,8 +805,11 @@ async function regionHtml(region, { manifest, manifestDir, base, projDir, assets : await qrPngsFor(posts.map((p) => p.qrUrl), render, resolveDeck(render).posts.qrSize, assetsDir); const qrSrcs = {}; for (const p of posts) if (p.qrUrl) qrSrcs[p.id] = byUrl.get(p.qrUrl); - const shotSrcs = await copyShots(posts, manifestDir, assetsDir); - return feedHtml(schedule, render, { fonts, qrSrcs, shotSrcs, from, duration }); + // A thread shot (a reply over the post it answers) is drawn whole: the + // feed gives it the column rather than the room beside the card under it. + const threads = new Set(); + const shotSrcs = await copyShots(posts, manifestDir, assetsDir, "shot", threads); + return feedHtml(schedule, render, { fonts, qrSrcs, shotSrcs, threadShots: [...threads], from, duration }); } if (region === "stamp") { // The fact-check stamps (chrome-stamp.mjs): the deck's faces, no QR. diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -1847,13 +1847,31 @@ const POST_VARIANTS = Object.freeze(["sourced", "full"]); export const POST_LAYOUTS = Object.freeze(["popup", "feed"]); /** Where a post's QR links (`posts.links`): its page on the archive, or the platform's own link. */ export const POST_LINKS = Object.freeze(["archive", "original"]); -const POST_KEYS = ["id", "platform", "author", "handle", "date", "text", "url", "attachTo", "hide", "siteChannel", "siteUrl", "postId", "shot", "variant", "accent", "logo", "flag"]; +const POST_KEYS = ["id", "platform", "author", "handle", "date", "text", "url", "attachTo", "hide", "siteChannel", "siteUrl", "postId", "shot", "thread", "variant", "accent", "logo", "flag"]; /** A post's `flag`: at most this many characters. */ export const POST_FLAG_MAX = 60; /** The pictures a post's `shot` may be. */ export const POST_SHOT_EXTS = Object.freeze([".png", ".jpg", ".jpeg", ".webp"]); +/** A reply's thread shot (capture-posts `thread`): beside the post's own shot, under this name. */ +export const THREAD_SHOT_NAME = "shot-thread.png"; + +/** + * Where a post's thread shot would be: `shot-thread.png` in its `shot`'s + * folder (the capture's layout, common/social/postCapture.ts), or null for a + * post with no shot. Whether the file is there is the composer's to check + * (compose-chrome.mjs postShotFile): a post with `thread: true` and none + * draws its own shot, as it did. + * + * @returns {string|null} + */ +export function threadShotOf(shot) { + if (typeof shot !== "string" || !shot) return null; + const i = shot.lastIndexOf("/"); + return (i < 0 ? "" : shot.slice(0, i + 1)) + THREAD_SHOT_NAME; +} + /** * Why a post's `shot` cannot be drawn, or null: a path to a screenshot of the * post, RELATIVE to the manifest (it is checked in beside it, as an image @@ -1924,6 +1942,12 @@ export function validatePosts(posts, timeline = [], render = null) { } // A screenshot drawn instead of the text card; the text stays the post's words. if (p.shot != null && shotError(p.shot)) errors.push(`${w}.shot ${shotError(p.shot)}`); + // The reply drawn with the post it answers above it: its thread shot, when + // the capture took one beside the shot (threadShotOf). + if (p.thread !== undefined && typeof p.thread !== "boolean") errors.push(`${w}.thread must be true or false`); + else if (p.thread === true && (typeof p.shot !== "string" || !p.shot)) { + errors.push(`${w}.thread draws the thread shot beside the post's shot, and the post has no shot`); + } // The card's own marks: a colour for its rail and rim, a logo in its corner, // a short flag above its words -- so one kind of card reads apart from another. if (p.accent != null && (typeof p.accent !== "string" || !/^#[0-9a-fA-F]{6}$/.test(p.accent))) { @@ -2104,6 +2128,8 @@ function postFieldsOf(p, provenance, links) { qrUrl: postQrUrl(p, provenance, { links }), // Only with a screenshot, so a post without one places as it always did. ...(typeof p.shot === "string" && p.shot ? { shot: p.shot } : {}), + // The thread shot is asked for; the composer draws it when it is on disk. + ...(typeof p.shot === "string" && p.shot && p.thread === true ? { thread: true } : {}), ...(typeof p.accent === "string" && p.accent ? { accent: p.accent } : {}), ...(typeof p.logo === "string" && p.logo ? { logo: p.logo } : {}), ...(typeof p.flag === "string" && p.flag.trim() ? { flag: p.flag.trim() } : {}),