commit df21626b9d8dd1755513f7a28293d1fea88026f0
parent 4d1188d1d88e2f7ac4af2b2296720e9a93573a33
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 18 Nov 2026 01:54:55 -0500
x-trending: watch a topic, with the jar rule kept
watch-trending switches a per-topic watch on with an interval and an end time (30 min, 48 h, at most 4 topics a library; all three and the per-file media cap are the library's settings). A scan of its own timer, armed below the idle gate and not on the e2e server, starts at most one read-x-trending job per scan, the longest overdue, none while a job of the library waits; a topic of several pages reads one per tick. When X would refuse the read the watches pause (a stale jar raises X's jar-age alert; the X alert, a cooldown, no profile) and resume at the first scan that finds the reason gone: the jar is never refreshed here, so a watch does not cover a night nobody presses Refresh in. A read into a watched topic queues one capture for its new posts' media (from the CDN, no page; a screenshot too when the topic says so) and for what a capture left owed to a later one; a media half now says whether it is owed to the next capture or until the post is kept, and an address found over the cap is not asked for again. A post a page showed before and not at a read that reached the page's end is recorded gone from the page at that time. A page X retired is not read again and ends the watch when it was the last. The listing carries each topic's watch and each post's gone mark and capture; the channel page has the switch and keep / drop / later buttons.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
29 files changed, 1923 insertions(+), 62 deletions(-)
diff --git a/CHANNEL.md b/CHANNEL.md
@@ -61,7 +61,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f
| `mirror` | config | For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped. See [`mirror`](#mirror). |
| `wayback` | config | A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest", auto?: true}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture's original URL. Each capture imported (`pnpm ops import-page`, the channel page's **Import a capture**) becomes a page record in the channel's posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. `auto: true` lets the download lane import the captures a later scan (`pnpm ops wayback-scan`, the **Captures** tab) adds, one job each at archive.org's pace; absent, nothing is imported unasked. Release 37 lane F: a target's `sources` (`["wayback", "archive.today"]`; absent = the Wayback Machine alone) says which archives hold its copies, and an archive.today copy imported into the channel is a page record like a capture (OPERATING.md, "Archived pages: the Wayback Machine and archive.today"); the form calls the kind "Archived pages". |
| `xSearch` | config | An X SEARCH channel (platform `"twitter"`, `sourceKind` `"social"`, `url` the search page): a saved X search across accounts, its records the matching posts from ANY author. `{query, since?, until?, windowMonths?, lang?, exclude?}` — `query` as X's search box takes it (words, `"phrases"`, `OR`, `-term`, `from:`, `to:`, `@mention`, `url:`, `filter:`, `lang:` pass through; `since:`, `until:` and `max_id:` are refused — the walk adds them); `since`/`until` the days walked between (YYYY-MM-DD; `since` inclusive, `until` exclusive; absent `until` = tomorrow, and each later fetch searches what is new); `windowMonths` each search window's span (1–12, default 3); `lang` a language code added as `lang:<code>`; `exclude` the handles **Never archive** hid from the leads view (lower case). A fetch walks the windows newest first through gallery-dl's search, resumable, at the older walk's pace and with its login (OPERATING.md, "X search"). Never on a site. An object without a valid query is dropped. |
-| `xTrending` | config | An X TRENDING LIBRARY (platform `"twitter"`, `sourceKind` `"social"`, no `url`): a PRIVATE posts channel whose records are the posts X's trending pages (`x.com/i/trending/<id>`) showed, from ANY author, read one page at a time by `pnpm ops read-x-trending` and grouped into topics. Everything of it — its posts too — is kept under `channels/<slug>/trending/`, not in `channels/<slug>/posts/`, so no reader of a posts channel finds them. The marker alone makes a channel a library. `{maxScrolls?, maxPosts?, maxVideoMb?}` — the caps a read uses when the ask names none (1–20 scrolls, default 8; 1–200 posts, default 60), and the largest media file, in MB, fetched for a post nobody has kept (1–2000, default 100; a larger one is owed until the post is kept); `{}` is a library with the defaults. Never on a site (refused on create, on Configure and by every site writer), in no index build (so not in the editor's own search either), never synced. Set by creating a channel with platform `x-trending`; not a Configure field. |
+| `xTrending` | config | An X TRENDING LIBRARY (platform `"twitter"`, `sourceKind` `"social"`, no `url`): a PRIVATE posts channel whose records are the posts X's trending pages (`x.com/i/trending/<id>`) showed, from ANY author, read one page at a time by `pnpm ops read-x-trending` and grouped into topics. Everything of it — its posts too — is kept under `channels/<slug>/trending/`, not in `channels/<slug>/posts/`, so no reader of a posts channel finds them. The marker alone makes a channel a library. `{maxScrolls?, maxPosts?, maxVideoMb?, watchIntervalMinutes?, watchHours?, watchMaxTopics?}` — the caps a read uses when the ask names none (1–20 scrolls, default 8; 1–200 posts, default 60); the largest media file, in MB, fetched for a post nobody has kept (1–2000, default 100; a larger one is owed until the post is kept); and the defaults of the watch: how often a watched topic is read (15–1440 minutes, default 30), for how long (1–168 hours, default 48) and how many topics may be watched at once (1–12, default 4) — `pnpm ops watch-trending` sets these three and `maxVideoMb`; `{}` is a library with the defaults. Never on a site (refused on create, on Configure and by every site writer), in no index build (so not in the editor's own search either), never synced. Set by creating a channel with platform `x-trending`; not a Configure field. |
| `localMedia` | config | Opt-in external MP4 library: {sourceId, directory, playback?}. The sourceId is a stable lowercase identifier; directory is an absolute server/container path. Source files remain externally owned. Playback is off unless explicitly true, and this flag alone does not authorize public serving. Removing or changing configuration must never move or delete source files. Do not reuse an existing sourceId for a different library; reconcile references explicitly. Private configuration: never include source paths in public exports. |
#### `downloadFilter`
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -220,6 +220,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `x-search-lead` | x-search-lead acts on one lead of an X search channel (the accounts its posts came from — `get channel <slug> --leads [--limit <n>]` lists them, most matches first): {"slug", "handle", "action": "archive" \| "never" \| "restore"}. "archive" creates <handle>-x, an X channel on NO site, by the New channel form's path and starts its first post fetch ("fetch": false skips it; "name"? names it; "dryRun" answers the fields and creates nothing) -> {slug, jobIds}. Refused: not an X search channel, an account an X channel archives already, a slug taken. "never" hides the handle (the channel's xSearch.exclude), "restore" un-hides it -> {exclude, changed}. No model, no request but the new channel's fetch. | `pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"archive","dryRun":true}'`<br>`pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"never"}'` |
| `read-x-trending` | read-x-trending reads ONE X trending page into an X trending library: {"slug", "url": "https://x.com/i/trending/<number>"}, as one job on X's queue (the fresh-jar rule, the X alert and X's job gap apply; ask get x-session first). The page is opened in the connected X profile's browser, every GraphQL answer the page itself fetched is saved raw with a screenshot (channels/<slug>/trending/reads/<readId>/), and the posts are parsed from the saved file and written as the library's posts. A read lists posts; it archives no media and no thread. "topic": a topic's id or name, or a new one's name (absent: the topic this page was read into before, else a new one named for it). "scrolls": 1-20 moves to the bottom of the page (default: the channel's cap, else 8); "posts": stop once 1-200 are seen (else 60); a read also stops after two scrolls with nothing new, and at once on a 429, a 403 or a login wall. A 429 leaves X alone for 15 minutes (no read is queued or started before the time its sentence names); a page that stops answering ends the read within 6 minutes. Nothing retries. "probe": true saves the capture and its summary and writes no post. "headed": true opens a window on the editor's desktop. {"slug", "reparse": "<readId>"} parses a saved read again OFFLINE (X is asked nothing; a read left with no record takes "url" too). No fresh jar needed. --wait prints the log's @@read-x-trending {ok, mode, read, outcome, stop, responses, operations (names and sizes, never a body), posts: {onPage, added}, topic, sentence}; a capture with no post the parser knows ends ok, "read saved, nothing recognised". Refused before a job: not a library, not a trending page URL, a cap out of range, no connected X profile, X's Connect or Refresh in flight, a stale jar. A library is made with create-channel, "platform": "x-trending" (no "url", no "sites": it is private, never on a site, in no index build; "xTrendingMaxScrolls"?, "xTrendingMaxPosts"? set its caps). | `pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","probe":true}' --wait`<br>`pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","topic":"Kettle festival"}' --wait`<br>`pnpm ops read-x-trending --json '{"slug":"trending","reparse":"tr-01JA0000000000000000000000"}' --wait` |
| `judge-trending` | judge-trending judges posts of an X trending library: {"slug", "set": \[{"id" \| "thread", "state", "note"?}, ...\], "by"?}. "id" is a post of the library; "thread" a thread's ROOT post id (get trending gives each post's thread), judging every post of it that has no judgement of its own. "state": keep, drop, later, or undecided (the judgement is removed: no entry is undecided). "note": up to 2000 characters. "by": "agent" (the default) or "operator". An agent's judgement is a suggestion: an agent's write over a judgement the operator made is skipped for that id and named in skipped, and the rest is written. Answers {written, skipped: \[{id \| thread, reason}\], kept, archive?} - kept names the posts whose judgement BECAME keep. A keep archives them: ONE capture-posts job on X's queue (a screenshot, the context, a reply's thread shot, the media), its id in archive.jobId; "archive": false marks only. When that job is refused (a stale jar, the X alert, X cooling down) the judgements are written all the same and archive.error says why; capture-posts {slug, ids, "thread": true, "keptMedia": true} archives them later. Drop deletes nothing: the post, its capture and its media stay, and a later keep puts it back. An id the library does not hold is skipped by name, not refused. | `pnpm ops judge-trending --json '{"slug":"trending","set":[{"id":"1900000000000001001","state":"keep","note":"the opening"},{"thread":"1900000000000001002","state":"drop"}]}'` |
+| `watch-trending` | watch-trending watches a topic of an X trending library: {"slug", "topic", "on": true, "intervalMinutes"?, "hours"?, "shots"?, "by"?}. While a topic is watched its trending page is read again every intervalMinutes (15-1440; default the library's, else 30) until hours from now (1-168; else 48), each tick the SAME single read-x-trending job on X's queue, started by the editor's own scan (once a minute, at most one read per scan, none while a read or capture of the library waits its turn). A topic of several pages reads one page per tick, in turn. At most 4 topics of a library are watched at once (its maxTopics). A new post's media is fetched at once from X's media CDN, no page opened; "shots": true also screenshots every new post. "on": false stops it. A WATCH RUNS ONLY WHILE X'S COOKIE JAR IS UNDER ITS LIMIT (60 minutes): the editor never refreshes the jar by itself, so a watch pauses when the jar goes stale (X's jar-age alert goes up, /review lists the paused watches) and resumes at the first scan after Refresh cookies on /cookies. It does not cover a night nobody presses Refresh in. The X alert, a rate-limit cooldown and a missing profile pause it the same way. A post a page showed before and does not show at a read that reached the page's end is recorded gone from the page at that time (get trending: gone) - never "deleted". A page X no longer has is not read again, and ends the watch when it was the topic's last. {"slug", "settings": {"maxVideoMb"?, "intervalMinutes"?, "hours"?, "maxTopics"?}} changes the library's defaults; {"slug", "tick": true} runs one scan now. get trending shows each topic's watch and what it is doing (watch.sentence). | `pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":true,"intervalMinutes":30,"hours":48}'`<br>`pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":false}'` |
| `wayback-lookup` | wayback-lookup answers the Wayback Machine's captures of a page (its CDX API): {"url"} or a record's {"slug", "id"} (its metadata's page, else its availability check's, else the playlist's), "okOnly"?: only the captures that recorded a 200, "limit"?: 100 (at most 500) -> {url, found, captures: \[{timestamp, status, mimetype?, replayUrl}\]}, oldest first. One request through the editor's Wayback client, with archive.org's manners (one at a time, 2 s apart, 429s waited out). Read only. A URL the Wayback Machine answers 403 for is excluded: HTTP 403, "refusal": "excluded" ("excluded from the Wayback Machine (cause unknown)"). | `pnpm ops wayback-lookup --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","okOnly":true}'` |
| `find-copy` | find-copy looks for a copy of every gone recording (deleted or private) a report cites, and fetches the cited windows from it, as a find-copy job: {"article"} \| {"articles": true} \| {"siteId"}, "dryRun"?, "retryFailed"? -> {jobId}. Per YouTube recording, one at a time: the Wayback Machine when it holds the video (the check yt-dlp makes, not a capture of the page), then archive.org (a mirror of the upload: its identifier, a file name or its original URL names the id, and the file has the recording's length). A copy a fetch failed from at its source (404, 410, 403, unreachable; never our own format selector) is not picked again, unless "retryFailed": true. A copy's windows are cut with a lenient selector (a direct file of unknown height: then the best single file). Every copy's windows go to ONE fetch-windows job on the archive.org clip queue, the copy's URL as each window's page, so the clips land in the recording's own clips/ with the copy (wayback or archive.org, and its URL) in each window's provenance. A recording with no copy is left: its moments show their words only, marked "Source deleted". The log ends with @@find-copy {recordings: \[{slug, id, gone, watchUrl, youtubeId, windows, failedBefore, tried, copy?, outcome}\], items, stopped?, fetchJobId?, refused?}. dryRun looks and starts no fetch; a cancelled job starts none. The scope mode (release 31): {"slug"} \| {"siteId"}, "gone": "no-transcript" \| "all", "dryRun"?, "max"? (10, at most 200), "retryFailed"? -> {jobId}. Every gone (deleted or private) video of the channel, or of the site's channels, that holds no audio or video ("no-transcript": and no transcript; "all": the transcribed ones too, after) is looked for the same way, at most max per run; a video whose last copy attempt found none or failed in the last 30 days is left out unless "retryFailed". Each copy's WHOLE audio is fetched into the video's own record (audio.<fmt>; its metadata stays the original's, the copy is in wayback.json or archiveorg.json and copy-attempts.json) by ONE fetch-copies job on archive.org's download queue, one at a time; the transcription lane then transcribes it like any downloaded audio. A video neither source holds is recorded none-found. dryRun asks the same (paced) questions and records and fetches nothing. The log ends with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped, looked: \[{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?, via?, outcome}\], left, items, stopped?, fetchJobId?, refused?}. The page mode (release 37): {"article"} \| {"articles": true} \| {"siteId"}, "pages": true, "channel"?, "max"? (10, at most 100), "dryRun"? -> {jobId}. Every page a report cites ("page" citations) whose original is gone at its own site gets the Wayback capture nearest the citation's date (one CDX lookup) imported into the Wayback pages channel named, else the one whose targets cover the page; a cited page record whose original is gone has its capture imported again when it is not stored. A live page is left (save-page-now it). The answer names the record each citation should cite (pointTo) and the citation as a post citation of it (as); the report is not rewritten. A find-copy job on the archive.org queue; dryRun asks the same paced questions and imports nothing. The log ends with @@find-copy {host, dryRun, max, pages, posts, items: \[{citedBy, url, original, channel?, capture?, outcome, detail, pointTo?, as?, records?}\], left, stopped?}. | `pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'`<br>`pnpm ops find-copy --json '{"article":"demo-article"}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","pages":true,"dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","pages":true,"channel":"demo-pages"}' --wait` |
| `wayback-scan` | wayback-scan lists the Wayback Machine's captures of a Wayback pages channel's targets (config wayback.targets) into its wayback-scan.json, as a wayback-scan job on archive.org's queue: {"slug", "dryRun"?, "maxRows"? (50000, at most 200000), "full"?} -> {jobId}. The CDX API per target (its matchType exact \| prefix \| host \| domain, status 200, its mimes — text/html unless it names text/plain or application/json — collapse=digest, its from/to), in pages of 5,000 with a resume key; obvious assets (css, js, images, fonts) dropped unless the target's include names them. One row per distinct (URL, digest) with first/last seen. No bodies: import-page fetches a capture. A run cut short (the row cap, a refusal, a drain) keeps each target's resume key and the next continues; once every target is complete the next run is a new pass, from 30 days before the last began, and what it adds is marked new; "full" starts a new pass from each target's start. Paced as archive.org asks (one at a time, 2 s apart, 429/503 waited out; a refusal stops the job). dryRun asks nothing and writes nothing: it logs the next request per target. The log ends with @@wayback-scan {slug, dryRun, pass, newPass, targets: \[{url, match, requests, rows, added, complete, resumeKey?, next?}\], requests, rowsRead, added, totalRows, complete, stopped?, error?}. | `pnpm ops wayback-scan --json '{"slug":"demo-pages","dryRun":true}' --wait`<br>`pnpm ops wayback-scan --json '{"slug":"demo-pages"}' --wait` |
@@ -376,13 +377,19 @@ get trending <slug> [--topic <topicId>] [--limit <n>] is an X trending
index): topics [{id, title, posts, sources: [{trendId, url, reads,
lastReadAt}]}], posts [{id, author, authorName, createdAt, url, text,
media: {count, kinds, thumbnail?}, topic, reads: [{read, trendId, at}],
- judgement?}] (the newest read's first, in page order; --limit 1-500,
+ gone?, capture?, thread, judgement?}] (the newest read's first, in page order; --limit 1-500,
default 100; total is the count before it) and reads (the saved reads'
ids, newest first). thumbnail is a captured post's first picture
(trending/posts-media/<id>/<name>, relative to the channel); thread is
the root post id of the thread a post belongs to; judgement is {state:
keep | drop | later, note?, by, at, from?} once a post has one (its own,
- or its thread's: from "thread"); no judgement is undecided. Never the
+ or its thread's: from "thread"); no judgement is undecided. gone is
+ {at, read, trendId}: a page that showed the post before did not show it
+ at a read that reached the page's end (gone from the page, not
+ deleted). capture is {at, state, shot, files, mediaState, mediaOwed?}
+ (mediaOwed "next": a later capture asks again; "kept": once the post
+ is kept). A topic carries watch {on, intervalMinutes, until, shots,
+ ticks, paused?, ended?, sentence} once it has been watched. Never the
raw capture, a cookie or a token.
get x-run [<run id>] is the X run as /review's X run console shows it:
the latest run (or the one named) — each channel's status (queued,
diff --git a/common/controller/readXTrending.test.ts b/common/controller/readXTrending.test.ts
@@ -167,6 +167,14 @@ test("a re-read adds the new posts, keeps the old ones, and appends the read wit
);
assert.deepEqual(again.result.posts, { onPage: 2, added: 1 });
assert.equal(again.result.topic?.created, false);
+ // Lane x-trending-2: the ids it added; and, the read having reached the
+ // page's end, the posts the page showed before and not now — gone FROM THE
+ // PAGE, at the read's time, never "deleted".
+ assert.equal(again.result.stop, "idle");
+ assert.deepEqual(again.result.newIds, ["1900000000000001005"]);
+ assert.deepEqual([...(again.result.gone ?? [])].sort(), ["1900000000000001001", "1900000000000001002"]);
+ assert.match(again.result.sentence, /2 posts this page showed before are gone from the page at 12:00 UTC\.$/);
+ assert.doesNotMatch(again.result.sentence, /delet/i);
const listing = await listXTrending(root(paths));
assert.equal(listing.total, 4);
assert.deepEqual(listing.topics[0].sources, [
diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts
@@ -54,6 +54,7 @@ import {
import {
ensureXTrendingReadsDir,
isXTrendingReadId,
+ readXTrendingPostIds,
readXTrendingReadRecord,
recordXTrendingRead,
topicTitleProblem,
@@ -275,6 +276,11 @@ export type ReadXTrendingResult = {
operations: XTrendingReadOperation[];
posts: { onPage: number; added: number };
topic?: { id: string; title: string; created?: boolean };
+ // The posts this read added to the library (ids), and the posts the page
+ // showed before and did not show now — "gone from the page", said only by a
+ // read that reached the page's end, and never meaning deleted.
+ newIds?: string[];
+ gone?: string[];
// What happened, as one sentence (the refusal, when `ok` is false).
sentence: string;
error?: string;
@@ -300,6 +306,10 @@ type Ingested = {
onPage: number;
added: number;
topic?: { id: string; title: string; created: boolean };
+ // The posts this pass added to the library, and — after a read that reached
+ // the page's end — the posts the page showed before and not now.
+ newIds?: string[];
+ gone?: string[];
};
// The saved capture → the library: its posts written, the read recorded.
@@ -312,14 +322,20 @@ async function ingestCapture(o: {
ref: XTrendingRef;
topic?: string;
write: boolean;
+ // The read reached the page's end (store.ts: only then is a post it did
+ // not show marked gone from the page). Never set by a reparse.
+ complete?: boolean;
}): Promise<Ingested> {
const file = path.join(trendingReadDir(o.channelRoot, o.readId), TRENDING_RESPONSES_FILENAME);
const lines = await readCaptureLines(file).catch(() => []);
const parsed = parseTrendingCapture(lines, o.slug);
const base = { operations: parsed.operations, responses: parsed.responses, onPage: parsed.posts.length };
if (!o.write || parsed.posts.length === 0) return { ...base, added: 0 };
+ const had = await readXTrendingPostIds(o.channelRoot);
+ const newIds = parsed.posts.map((p) => p.id).filter((id) => !had.has(id));
const written = await writeXTrendingPosts(o.channelRoot, parsed.posts);
const recorded = await recordXTrendingRead(o.channelRoot, {
+ ...(o.complete ? { complete: true } : {}),
readId: o.readId,
at: o.at,
ref: o.ref,
@@ -328,7 +344,7 @@ async function ingestCapture(o: {
added: written.written,
media: parsed.media,
});
- return { ...base, added: written.written, topic: recorded.topic };
+ return { ...base, added: written.written, topic: recorded.topic, newIds, gone: recorded.gone };
}
export type ReadXTrendingDeps = {
@@ -450,6 +466,8 @@ export async function runXTrendingRead(o: {
ref: plan.ref,
...(plan.topic ? { topic: plan.topic } : {}),
write: !plan.probe && !walled,
+ // "idle": the scrolling stopped because the page had no more to show.
+ complete: page.stop === "idle",
});
} catch (err) {
ingestError = ((err as Error)?.message ?? String(err)).split("\n")[0];
@@ -534,7 +552,10 @@ export async function runXTrendingRead(o: {
sentence =
`Read ${plan.ref.url}: ${plural(ingested.onPage, "post")} on the page, ${ingested.added} new, ` +
`in topic "${ingested.topic?.title}" (${ingested.topic?.id})` +
- (page.stop === "cancelled" ? "; the read was stopped early." : ".");
+ (page.stop === "cancelled" ? "; the read was stopped early." : ".") +
+ (ingested.gone?.length
+ ? ` ${plural(ingested.gone.length, "post")} this page showed before ${ingested.gone.length === 1 ? "is" : "are"} gone from the page at ${hhmm(Date.parse(startedAt))} UTC.`
+ : "");
// A clean request: a raised X alert it would clear is cleared.
const cleared = await note(paths, { url: plan.ref.url, channel: plan.slug });
if (cleared) log(cleared);
@@ -580,6 +601,8 @@ export async function runXTrendingRead(o: {
operations: ingested.operations,
posts: { onPage: ingested.onPage, added: ingested.added },
...(ingested.topic ? { topic: ingested.topic } : {}),
+ ...(ingested.newIds?.length ? { newIds: ingested.newIds } : {}),
+ ...(ingested.gone?.length ? { gone: ingested.gone } : {}),
sentence,
...(ok ? {} : { error: sentence }),
};
diff --git a/common/controller/xTrendingWatch.test.ts b/common/controller/xTrendingWatch.test.ts
@@ -0,0 +1,342 @@
+// The watch scan over temp libraries and stand-in deps: nothing here opens a
+// browser, enqueues a real job or asks X anything.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/xTrendingWatch.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { recordXTrendingRead, writeXTrendingPosts } from "../lib/xTrending/store";
+import { describeXTrendingWatch, readXTrendingWatches, setXTrendingWatch } from "../lib/xTrending/watch";
+import { xTrendingWatchTerms } from "../lib/xTrending/config";
+import type { Post } from "../lib/posts";
+import {
+ armXTrendingWatch,
+ disarmXTrendingWatch,
+ isXTrendingWatchArmed,
+ noteXTrendingWatchRead,
+ scanXTrendingWatches,
+ xTrendingWatchFollowUp,
+ type WatchRefusal,
+ type WatchScanDeps,
+ type WatchTick,
+} from "./xTrendingWatch";
+
+const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-watch-"));
+after(() => rmSync(TMP, { recursive: true, force: true }));
+
+const T0 = Date.parse("2026-11-18T10:00:00.000Z");
+const MIN = 60_000;
+const trend = (n: number) => ({ trendId: `190000000000000000${n}`, url: `https://x.com/i/trending/190000000000000000${n}` });
+const readId = (n: number) => `tr-01J${String.fromCharCode(64 + n)}0000000000000000000000`;
+
+function post(id: string): Post {
+ return {
+ id,
+ slug: `lib/${id}`,
+ channelSlug: "lib",
+ author: "kettle_fan",
+ createdAt: "2026-11-16T12:00:00.000Z",
+ uploadDate: "20261116",
+ text: `post ${id}`,
+ url: `https://x.com/kettle_fan/status/${id}`,
+ platform: "twitter",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ };
+}
+
+let n = 0;
+// A corpus with libraries; each topic gets one read of one page per `pages`.
+async function corpus(libs: Record<string, Record<string, number[]>>): Promise<Paths> {
+ const dir = path.join(TMP, `c${++n}`);
+ const paths = { transcriptsDir: dir, channelsDir: path.join(dir, "channels") } as Paths;
+ let r = 0;
+ for (const [slug, topics] of Object.entries(libs)) {
+ const root = path.join(paths.channelsDir, slug);
+ mkdirSync(root, { recursive: true });
+ writeFileSync(path.join(root, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} }));
+ for (const [topic, pages] of Object.entries(topics)) {
+ for (const p of pages) {
+ const id = `9${p}0${++r}`;
+ await writeXTrendingPosts(root, [post(id)]);
+ await recordXTrendingRead(root, { readId: readId(r), at: new Date(T0 - 60 * MIN).toISOString(), ref: trend(p), topic, postIds: [id], added: 1 });
+ }
+ }
+ }
+ return paths;
+}
+
+type Harness = { deps: WatchScanDeps; ticks: WatchTick[]; state: { now: number; refusal: WatchRefusal | null; busy: Set<string>; refuse: string | null; jar: string[] } };
+
+function harness(paths: Paths, libraries: string[]): Harness {
+ const ticks: WatchTick[] = [];
+ const state: Harness["state"] = { now: T0, refusal: null, busy: new Set(), refuse: null, jar: [] };
+ return {
+ ticks,
+ state,
+ deps: {
+ paths,
+ now: () => state.now,
+ libraries: async () => libraries,
+ busy: (slug) => state.busy.has(slug),
+ refusal: async () => state.refusal,
+ enqueue: async (tick) => {
+ if (state.refuse) return { ok: false, error: state.refuse };
+ ticks.push(tick);
+ return { ok: true, jobId: `job-${ticks.length}` };
+ },
+ noteJarStale: async (line) => void state.jar.push(line),
+ jitter: () => 0,
+ },
+ };
+}
+
+const root = (paths: Paths, slug = "lib") => path.join(paths.channelsDir, slug);
+const on = (paths: Paths, topic: string, over: Partial<Parameters<typeof setXTrendingWatch>[1]> = {}, slug = "lib") =>
+ setXTrendingWatch(root(paths, slug), { topic, on: true, intervalMinutes: 30, hours: 48, by: "agent", maxTopics: 4, now: T0, ...over });
+
+test("the switch: a topic with a page is watched with an interval and an end time; at most the library's limit; off ends it", async () => {
+ const paths = await corpus({ lib: { Kettles: [1], Saucers: [2], Lids: [3] } });
+ const first = await on(paths, "Kettles");
+ assert.equal(first.ok, true);
+ if (!first.ok) return;
+ assert.equal(first.topic, "kettles");
+ assert.deepEqual(
+ { on: first.watch.on, intervalMinutes: first.watch.intervalMinutes, until: first.watch.until, shots: first.watch.shots, ticks: first.watch.ticks },
+ { on: true, intervalMinutes: 30, until: "2026-11-20T10:00:00.000Z", shots: false, ticks: 0 },
+ );
+ assert.match(describeXTrendingWatch(first.watch, T0), /^Watched every 30 min until 2026-11-20 10:00 UTC; 0 ticks so far, next at the next scan\.$/);
+ // By title too; a topic that does not exist is refused by name.
+ assert.equal((await on(paths, "saucers", { maxTopics: 2 })).ok, true);
+ const none = await on(paths, "Spouts");
+ assert.equal(none.ok, false);
+ assert.match(none.ok ? "" : none.error, /no topic "Spouts" \(its topics: kettles, saucers, lids\)/);
+ // The limit counts the OTHER live watches.
+ const third = await on(paths, "Lids", { maxTopics: 2 });
+ assert.match(third.ok ? "" : third.error, /already watches 2 topics \(at most 2\)/);
+ // Switching a live one on again changes its terms and is not a new watch.
+ const again = await on(paths, "Kettles", { intervalMinutes: 60, shots: true, maxTopics: 2, now: T0 + 5 * MIN });
+ assert.equal(again.ok && again.watch.intervalMinutes, 60);
+ assert.equal(again.ok && again.watch.shots, true);
+ assert.equal(again.ok && again.watch.startedAt, "2026-11-18T10:00:00.000Z");
+ // Off.
+ const off = await setXTrendingWatch(root(paths), { topic: "kettles", on: false, intervalMinutes: 30, hours: 48, by: "operator", maxTopics: 2, now: T0 + 6 * MIN });
+ assert.equal(off.ok && off.watch.ended?.sentence, 'The watch of "Kettles" was switched off.');
+ assert.match((await setXTrendingWatch(root(paths), { topic: "kettles", on: false, intervalMinutes: 30, hours: 48, by: "operator", maxTopics: 2, now: T0 })).ok ? "" : "not watched", /not watched/);
+ // Now there is room for the third.
+ assert.equal((await on(paths, "Lids", { maxTopics: 2 })).ok, true);
+});
+
+test("the watch's terms: the ask's, else the library's, else 30 minutes and 48 hours; out of range is refused", () => {
+ assert.deepEqual(xTrendingWatchTerms(undefined), { ok: true, terms: { intervalMinutes: 30, hours: 48 } });
+ assert.deepEqual(xTrendingWatchTerms({ watchIntervalMinutes: 45, watchHours: 12 }), { ok: true, terms: { intervalMinutes: 45, hours: 12 } });
+ assert.deepEqual(xTrendingWatchTerms({ watchIntervalMinutes: 45 }, { intervalMinutes: 20, hours: 6 }), { ok: true, terms: { intervalMinutes: 20, hours: 6 } });
+ const short = xTrendingWatchTerms(undefined, { intervalMinutes: 5 });
+ assert.match(short.ok ? "" : short.error, /"intervalMinutes" is a whole number, 15–1440/);
+ const long = xTrendingWatchTerms(undefined, { hours: 169 });
+ assert.match(long.ok ? "" : long.error, /"hours" is a whole number, 1–168/);
+});
+
+test("one scan starts at most one read — the longest overdue — and the next tick is an interval away, never sooner", async () => {
+ const paths = await corpus({ lib: { Kettles: [1], Saucers: [2] }, other: { Lids: [3] } });
+ await on(paths, "Kettles", { now: T0 - 10 * MIN });
+ await on(paths, "Saucers", { now: T0 - 20 * MIN });
+ await on(paths, "Lids", { now: T0 - 5 * MIN }, "other");
+ const h = harness(paths, ["lib", "other"]);
+ const first = await scanXTrendingWatches(h.deps);
+ assert.deepEqual(h.ticks, [{ slug: "lib", topic: "saucers", url: trend(2).url, trendId: trend(2).trendId }]);
+ assert.equal(first.enqueued?.jobId, "job-1");
+ assert.equal(first.live, 3);
+ let w = (await readXTrendingWatches(root(paths))).saucers;
+ assert.deepEqual([w.lastTickAt, w.lastJobId, w.nextTickAt, w.ticks], ["2026-11-18T10:00:00.000Z", "job-1", "2026-11-18T10:30:00.000Z", 1]);
+ // A minute later: the next longest overdue, one again.
+ h.state.now = T0 + MIN;
+ await scanXTrendingWatches(h.deps);
+ h.state.now = T0 + 2 * MIN;
+ await scanXTrendingWatches(h.deps);
+ assert.deepEqual(h.ticks.map((t) => `${t.slug}/${t.topic}`), ["lib/saucers", "lib/kettles", "other/lids"]);
+ // Nothing is due until an interval has passed.
+ h.state.now = T0 + 29 * MIN;
+ assert.equal((await scanXTrendingWatches(h.deps)).enqueued, undefined);
+ h.state.now = T0 + 30 * MIN;
+ assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.topic, "saucers");
+ // Hours missed (the editor was down): ONE catch-up tick, not several.
+ h.state.now = T0 + 6 * 60 * MIN;
+ const before = h.ticks.length;
+ await scanXTrendingWatches(h.deps);
+ assert.equal(h.ticks.length, before + 1);
+ // (Kettles was the longest overdue by then.)
+ assert.equal((await readXTrendingWatches(root(paths))).kettles.ticks, 2);
+ assert.equal((await readXTrendingWatches(root(paths))).saucers.ticks, 2);
+});
+
+test("no tick is started for a library while a read or capture of it waits its turn", async () => {
+ const paths = await corpus({ lib: { Kettles: [1] } });
+ await on(paths, "Kettles");
+ const h = harness(paths, ["lib"]);
+ h.state.busy.add("lib");
+ assert.equal((await scanXTrendingWatches(h.deps)).enqueued, undefined);
+ assert.equal((await readXTrendingWatches(root(paths))).kettles.paused, undefined);
+ h.state.busy.clear();
+ assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.topic, "kettles");
+});
+
+test("a stale jar PAUSES the watches, raises X's jar-age alert and enqueues nothing; they resume at the first scan after a Refresh", async () => {
+ const paths = await corpus({ lib: { Kettles: [1], Saucers: [2] } });
+ await on(paths, "Kettles");
+ await on(paths, "Saucers");
+ const h = harness(paths, ["lib"]);
+ h.state.refusal = { reason: "jar", sentence: "X cookies were last refreshed 61 min ago (limit 60 min): press Refresh cookies (or Connect X account) on /cookies, then fetch again." };
+ const scan = await scanXTrendingWatches(h.deps);
+ assert.deepEqual(h.ticks, []);
+ assert.deepEqual(scan.paused.map((p) => [p.topic, p.reason]).sort(), [["kettles", "jar"], ["saucers", "jar"]]);
+ assert.equal(h.state.jar.length, 1);
+ assert.match(h.state.jar[0], /2 watched topics of lib paused: X cookies were last refreshed 61 min ago.*A watch runs only while X's cookie jar is fresh: it resumes at the first scan after Refresh cookies on \/cookies\./);
+ let w = (await readXTrendingWatches(root(paths))).kettles;
+ assert.deepEqual(w.paused && [w.paused.reason, w.paused.since], ["jar", "2026-11-18T10:00:00.000Z"]);
+ assert.match(describeXTrendingWatch(w, T0), /PAUSED since 2026-11-18 10:00 UTC: X cookies were last refreshed 61 min ago/);
+ // Still stale ten minutes later: paused since the same moment, said once more to the alert, nothing enqueued.
+ h.state.now = T0 + 10 * MIN;
+ const still = await scanXTrendingWatches(h.deps);
+ assert.deepEqual(still.paused, []);
+ assert.equal((await readXTrendingWatches(root(paths))).kettles.paused?.since, "2026-11-18T10:00:00.000Z");
+ assert.deepEqual(h.ticks, []);
+ // Refreshed: resumed at this scan, and the overdue tick is taken.
+ h.state.refusal = null;
+ h.state.now = T0 + 11 * MIN;
+ const resumed = await scanXTrendingWatches(h.deps);
+ assert.deepEqual(resumed.resumed.map((r) => r.topic).sort(), ["kettles", "saucers"]);
+ assert.equal(h.ticks.length, 1);
+ w = (await readXTrendingWatches(root(paths))).kettles;
+ assert.equal(w.paused, undefined);
+});
+
+test("the X alert, a cooldown and a missing profile pause too, each by its reason; only the jar raises the jar alert", async () => {
+ const paths = await corpus({ lib: { Kettles: [1] } });
+ await on(paths, "Kettles");
+ const h = harness(paths, ["lib"]);
+ for (const reason of ["alert", "cooldown", "no-profile"] as const) {
+ h.state.refusal = { reason, sentence: `why: ${reason}` };
+ const scan = await scanXTrendingWatches(h.deps);
+ assert.deepEqual(scan.paused, [{ slug: "lib", topic: "kettles", reason }]);
+ assert.equal((await readXTrendingWatches(root(paths))).kettles.paused?.sentence, `why: ${reason}`);
+ }
+ assert.deepEqual(h.ticks, []);
+ assert.deepEqual(h.state.jar, []);
+});
+
+test("a read refused at its enqueue pauses that watch and is not asked again for an interval", async () => {
+ const paths = await corpus({ lib: { Kettles: [1] } });
+ await on(paths, "Kettles");
+ const h = harness(paths, ["lib"]);
+ h.state.refuse = "X's Refresh is running and holds the connected profile.";
+ const scan = await scanXTrendingWatches(h.deps);
+ assert.equal(scan.refused?.error, "X's Refresh is running and holds the connected profile.");
+ let w = (await readXTrendingWatches(root(paths))).kettles;
+ assert.equal(w.paused?.reason, "refused");
+ assert.equal(w.nextTickAt, "2026-11-18T10:30:00.000Z");
+ assert.equal(w.ticks, 0);
+ // A minute later nothing is asked; the pause stands.
+ h.state.refuse = null;
+ h.state.now = T0 + MIN;
+ assert.equal((await scanXTrendingWatches(h.deps)).enqueued, undefined);
+ assert.equal((await readXTrendingWatches(root(paths))).kettles.paused?.reason, "refused");
+ // An interval later it is taken, and the pause is over.
+ h.state.now = T0 + 30 * MIN;
+ assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.topic, "kettles");
+ w = (await readXTrendingWatches(root(paths))).kettles;
+ assert.equal(w.paused, undefined);
+});
+
+test("a watch ends at its end time, with a sentence, and is not ticked again", async () => {
+ const paths = await corpus({ lib: { Kettles: [1] } });
+ await on(paths, "Kettles", { hours: 1 });
+ const h = harness(paths, ["lib"]);
+ await scanXTrendingWatches(h.deps);
+ h.state.now = T0 + 60 * MIN;
+ const scan = await scanXTrendingWatches(h.deps);
+ assert.deepEqual(scan.ended, [{ slug: "lib", topic: "kettles", sentence: 'The watch of "Kettles" ended at its end time (2026-11-18 11:00 UTC), after 1 tick.' }]);
+ assert.equal(scan.live, 0);
+ assert.equal(h.ticks.length, 1);
+ h.state.now = T0 + 120 * MIN;
+ await scanXTrendingWatches(h.deps);
+ assert.equal(h.ticks.length, 1);
+});
+
+test("a topic of several pages reads one page per tick, in turn; a page X retired is skipped, and the last one gone ends the watch", async () => {
+ const paths = await corpus({ lib: { Kettles: [1, 2] } });
+ await on(paths, "Kettles");
+ const h = harness(paths, ["lib"]);
+ for (let i = 0; i < 3; i++) {
+ h.state.now = T0 + i * 30 * MIN;
+ await scanXTrendingWatches(h.deps);
+ }
+ assert.deepEqual(h.ticks.map((t) => t.trendId), [trend(1).trendId, trend(2).trendId, trend(1).trendId]);
+ // Page 1 is gone: the watch goes on with page 2 alone.
+ assert.equal(await noteXTrendingWatchRead(root(paths), { trendId: trend(1).trendId, outcome: "gone", now: h.state.now }), null);
+ assert.equal(await noteXTrendingWatchRead(root(paths), { trendId: trend(2).trendId, outcome: "read" }), null);
+ h.state.now = T0 + 90 * MIN;
+ await scanXTrendingWatches(h.deps);
+ h.state.now = T0 + 120 * MIN;
+ await scanXTrendingWatches(h.deps);
+ assert.deepEqual(h.ticks.slice(3).map((t) => t.trendId), [trend(2).trendId, trend(2).trendId]);
+ // Page 2 gone as well: the watch ends, saying so.
+ const sentence = await noteXTrendingWatchRead(root(paths), { trendId: trend(2).trendId, outcome: "gone", now: h.state.now });
+ assert.equal(sentence, 'X no longer has the trending page of "Kettles" (trending pages expire): the watch ended.');
+ const w = (await readXTrendingWatches(root(paths))).kettles;
+ assert.deepEqual([w.on, w.ended?.reason], [false, "gone"]);
+ h.state.now = T0 + 150 * MIN;
+ await scanXTrendingWatches(h.deps);
+ assert.equal(h.ticks.length, 5);
+});
+
+test("after a read into a watched topic one capture takes its new posts with media, then what a capture left owed to a later one", async () => {
+ const paths = await corpus({ lib: { Kettles: [1] } });
+ const dir = root(paths);
+ const ids = ["7001", "7002", "7003", "7004", "7005"];
+ await writeXTrendingPosts(dir, ids.map(post));
+ await recordXTrendingRead(dir, {
+ readId: readId(20),
+ at: new Date(T0).toISOString(),
+ ref: trend(1),
+ topic: "Kettles",
+ postIds: ids,
+ added: 5,
+ media: { "7001": { count: 1, kinds: ["image"] }, "7003": { count: 1, kinds: ["video"] }, "7004": { count: 2, kinds: ["image"] }, "7005": { count: 1, kinds: ["image"] } },
+ });
+ // Not watched: nothing follows a read.
+ assert.equal(await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["7001", "7002"] }), null);
+ await on(paths, "Kettles");
+ const capture = (id: string, rec: Record<string, unknown>) => {
+ mkdirSync(path.join(dir, "trending", "posts-media", id), { recursive: true });
+ writeFileSync(path.join(dir, "trending", "posts-media", id, "capture.json"), JSON.stringify({ version: 1, id, capturedAt: "2026-11-18T09:00:00.000Z", state: "captured", media: [], ...rec }));
+ };
+ capture("7003", { mediaState: "error", mediaOwed: "next" });
+ capture("7004", { mediaState: "error", mediaOwed: "kept" });
+ capture("7005", { mediaState: "error", error: "7005_1.jpg: the CDN answered 404" });
+ // 7002 has no media: not captured by a media-only watch. 7003 is owed to a
+ // later capture: taken. 7004 (owed until kept) and 7005 (failed) are not.
+ assert.deepEqual(await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["7001", "7002"] }), { ids: ["7001", "7003"], shots: false, fresh: 1, owed: 1 });
+ // "Screenshot everything new": the post without media is taken too.
+ await on(paths, "Kettles", { shots: true });
+ assert.deepEqual(await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["7001", "7002"] }), { ids: ["7001", "7002", "7003"], shots: true, fresh: 2, owed: 1 });
+ // A read into another topic's posts takes nothing of this one's new ids.
+ assert.deepEqual((await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["424242"] }))?.ids, ["7003"]);
+});
+
+test("the scan is not armed on an idle boot; armed, it is one timer, and disarms", () => {
+ const deps = { paths: {} as Paths, busy: () => false, enqueue: async () => ({ ok: false as const, error: "never" }) };
+ disarmXTrendingWatch();
+ assert.equal(armXTrendingWatch(deps, { env: { ARCHILYZER_IDLE_BOOT: "1" }, everyMs: 0 }), false);
+ assert.equal(isXTrendingWatchArmed(), false);
+ assert.equal(armXTrendingWatch(deps, { env: {}, everyMs: 0 }), true);
+ assert.equal(armXTrendingWatch(deps, { env: {}, everyMs: 0 }), true);
+ assert.equal(isXTrendingWatchArmed(), true);
+ disarmXTrendingWatch();
+ assert.equal(isXTrendingWatchArmed(), false);
+});
diff --git a/common/controller/xTrendingWatch.ts b/common/controller/xTrendingWatch.ts
@@ -0,0 +1,374 @@
+// THE WATCH OF A LIBRARY'S TOPICS (lane x-trending-2): the scan that turns a
+// watched topic (lib/xTrending/watch.ts) into reads.
+//
+// Armed by the editor's instrumentation BELOW the idle gate
+// (ARCHILYZER_IDLE_BOOT arms nothing, and armXTrendingWatch refuses an idle
+// boot itself), not on the e2e test server — a tick is a request to X. Once
+// armed, a scan runs every CHECK_MS on an unref'd timer of its own (NOT the
+// sync heartbeat, which can be switched off), and:
+//
+// - a watch past its end time ENDS, with a sentence;
+// - ONE SCAN STARTS AT MOST ONE READ, across every library: the watch
+// longest overdue. A tick is the same single `read-x-trending` job a
+// person starts, on X's queue (one job at a time, X's gap between jobs);
+// a missed window is one catch-up tick, never several;
+// - no tick is started for a library while a read or a capture of it is
+// queued or running (that job's turn comes first);
+// - WHEN X WOULD REFUSE THE READ the watches PAUSE instead of queueing jobs
+// to be refused: X's cookie jar is past its limit ("jar": X's jar-age
+// alert goes up, on the dashboard and /cookies, and /review lists the
+// paused watches), the X alert is up, X is cooling down after a rate
+// limit, or there is no connected profile. The pause ends at the first
+// scan that finds the reason gone;
+// - a topic with several trending pages reads ONE page per tick, in turn;
+// - a page X no longer has is not read again, and a topic with no page
+// left ENDS its watch with a sentence (noteXTrendingWatchRead, called at
+// the end of every read of a library).
+//
+// THE JAR IS NEVER REFRESHED HERE. A refresh is a person's press on /cookies
+// (jobs/networkGuard.ts): a watch runs only while the jar is fresh, so it
+// does not cover a night nobody presses Refresh in.
+//
+// After a read into a watched topic, its NEW posts get their media at once
+// (xTrendingWatchFollowUp says which posts one capture job takes).
+
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { isIdleBoot } from "../lib/idleBoot";
+import { jitterMs } from "../lib/jitter";
+import { noteXJarStale } from "../lib/serviceCookies-server";
+import { xSessionReport } from "../jobs/networkGuard";
+import { isXTrendingChannel } from "../lib/xTrending/config";
+import {
+ readXTrendingMembership,
+ readXTrendingTopics,
+ xTrendingCaptureSummary,
+ type XTrendingTopic,
+} from "../lib/xTrending/store";
+import {
+ mutateXTrendingWatches,
+ readXTrendingWatches,
+ watchIsLive,
+ type XTrendingWatch,
+ type XTrendingWatchPauseReason,
+} from "../lib/xTrending/watch";
+import { listChannelConfigs } from "./channels";
+import { xTrendingHeld } from "./readXTrending";
+
+export const X_TRENDING_WATCH_CHECK_MS = 60_000;
+// One capture after a tick takes at most this many posts.
+export const X_TRENDING_WATCH_CAPTURE_MAX = 80;
+
+export type WatchRefusal = { reason: XTrendingWatchPauseReason; sentence: string };
+
+export type WatchTick = { slug: string; topic: string; url: string; trendId: string };
+
+export type WatchScanDeps = {
+ paths: Paths;
+ now?: () => number;
+ log?: (line: string) => void;
+ // The libraries (default: every channel carrying the marker).
+ libraries?: () => Promise<string[]>;
+ // A read or a capture of this library is queued or running.
+ busy: (slug: string) => boolean;
+ // Why X would refuse a read now, or null (default: watchRefusal below).
+ refusal?: (slug: string) => Promise<WatchRefusal | null>;
+ // One read, enqueued (the editor's readXTrendingAction).
+ enqueue: (tick: WatchTick) => Promise<{ ok: true; jobId: string } | { ok: false; error: string }>;
+ noteJarStale?: (line: string, slug: string) => Promise<unknown>;
+ // The stretch added to an interval (never a shortening).
+ jitter?: (ms: number) => number;
+};
+
+export type WatchScanResult = {
+ libraries: number;
+ // Watches switched on and not ended, after this scan.
+ live: number;
+ enqueued?: WatchTick & { jobId: string };
+ refused?: WatchTick & { error: string };
+ paused: Array<{ slug: string; topic: string; reason: XTrendingWatchPauseReason }>;
+ resumed: Array<{ slug: string; topic: string }>;
+ ended: Array<{ slug: string; topic: string; sentence: string }>;
+};
+
+const hhmm = (ms: number) => new Date(ms).toISOString().slice(0, 16).replace("T", " ");
+
+// WHY X WOULD REFUSE A READ NOW — read from disk, never from X: the X alert,
+// the fresh-jar rule (the same computation the network guard refuses by),
+// the connected profile, X's cooldown or hold.
+export async function watchRefusal(paths: Paths, slug: string, now: number): Promise<WatchRefusal | null> {
+ const report = await xSessionReport({ paths, channelSlug: slug, now });
+ if (!report.hasProfile) {
+ return {
+ reason: "no-profile",
+ sentence: "There is no connected X profile to read a trending page with: connect an X account on /cookies.",
+ };
+ }
+ if (!report.allowed) {
+ return { reason: report.alert ? "alert" : "jar", sentence: report.reason ?? "X's cookie jar is past its limit." };
+ }
+ const held = await xTrendingHeld(paths, now);
+ return held ? { reason: "cooldown", sentence: held } : null;
+}
+
+export const WATCH_JAR_NOTE =
+ "A watch runs only while X's cookie jar is fresh: it resumes at the first scan after Refresh cookies on /cookies.";
+
+async function defaultLibraries(paths: Paths): Promise<string[]> {
+ return (await listChannelConfigs(paths)).filter((c) => isXTrendingChannel(c.config)).map((c) => c.slug);
+}
+
+type Due = { slug: string; root: string; topic: XTrendingTopic; watch: XTrendingWatch; dueAt: number };
+
+// ONE SCAN. Never throws for one library's sake: a library whose files
+// cannot be read is skipped and said.
+export async function scanXTrendingWatches(deps: WatchScanDeps): Promise<WatchScanResult> {
+ const now = (deps.now ?? Date.now)();
+ const at = new Date(now).toISOString();
+ const log = deps.log ?? (() => {});
+ const out: WatchScanResult = { libraries: 0, live: 0, paused: [], resumed: [], ended: [] };
+ const slugs = await (deps.libraries ?? (() => defaultLibraries(deps.paths)))();
+ out.libraries = slugs.length;
+ const due: Due[] = [];
+ for (const slug of slugs) {
+ const root = path.join(deps.paths.channelsDir, slug);
+ try {
+ if (!Object.values(await readXTrendingWatches(root)).some(watchIsLive)) continue;
+ const topics = new Map((await readXTrendingTopics(root)).map((t) => [t.id, t]));
+ // 1. End what is past its end time (or whose topic is no more).
+ await mutateXTrendingWatches(root, (watches) => {
+ let write = false;
+ for (const [id, w] of Object.entries(watches)) {
+ if (!watchIsLive(w)) continue;
+ const title = topics.get(id)?.title;
+ const sentence = !title
+ ? `The watch ended: this library no longer has the topic "${id}".`
+ : now >= Date.parse(w.until)
+ ? `The watch of "${title}" ended at its end time (${hhmm(Date.parse(w.until))} UTC), after ${w.ticks} tick${w.ticks === 1 ? "" : "s"}.`
+ : null;
+ if (!sentence) continue;
+ w.on = false;
+ delete w.paused;
+ w.ended = { at, reason: title ? "until" : "off", sentence };
+ out.ended.push({ slug, topic: id, sentence });
+ write = true;
+ }
+ return { write, result: null };
+ });
+ // 2. Would X refuse a read? Then the live watches pause; else they resume.
+ const refusal = await (deps.refusal ?? ((s) => watchRefusal(deps.paths, s, now)))(slug);
+ const watches = await mutateXTrendingWatches(root, (all) => {
+ let write = false;
+ for (const [id, w] of Object.entries(all)) {
+ if (!watchIsLive(w)) continue;
+ if (refusal) {
+ if (w.paused?.reason !== refusal.reason || w.paused.sentence !== refusal.sentence) {
+ if (w.paused?.reason !== refusal.reason) out.paused.push({ slug, topic: id, reason: refusal.reason });
+ w.paused = {
+ reason: refusal.reason,
+ since: w.paused?.reason === refusal.reason ? w.paused.since : at,
+ sentence: refusal.sentence,
+ };
+ write = true;
+ }
+ } else if (w.paused && w.paused.reason !== "refused") {
+ // A read that was refused at its enqueue stays paused until one is taken.
+ delete w.paused;
+ out.resumed.push({ slug, topic: id });
+ write = true;
+ }
+ }
+ return { write, result: all };
+ });
+ for (const p of out.paused.filter((p) => p.slug === slug)) {
+ log(`x-trending watch: ${slug}/${p.topic}: paused (${p.reason}): ${refusal?.sentence ?? ""}`);
+ }
+ for (const r of out.resumed.filter((r) => r.slug === slug)) log(`x-trending watch: ${slug}/${r.topic}: resumed`);
+ const live = Object.entries(watches).filter(([, w]) => watchIsLive(w));
+ out.live += live.length;
+ if (refusal) {
+ if (refusal.reason === "jar" && live.length > 0) {
+ const line = `${live.length} watched topic${live.length === 1 ? "" : "s"} of ${slug} paused: ${refusal.sentence} ${WATCH_JAR_NOTE}`;
+ await (deps.noteJarStale ?? ((l, s) => noteXJarStale(deps.paths, { line: l, channel: s }, now)))(line, slug).catch(() => {});
+ }
+ continue;
+ }
+ // 3. What is due — unless a job of this library is already waiting its turn.
+ if (deps.busy(slug)) continue;
+ for (const [id, w] of live) {
+ const topic = topics.get(id);
+ if (!topic) continue;
+ const dueAt = w.nextTickAt ? Date.parse(w.nextTickAt) : Date.parse(w.startedAt);
+ if (dueAt <= now) due.push({ slug, root, topic, watch: w, dueAt });
+ }
+ } catch (err) {
+ log(`x-trending watch: ${slug}: the scan could not read this library: ${(err as Error).message}`);
+ }
+ }
+ if (due.length === 0) return out;
+ // The longest overdue, and only it.
+ due.sort((a, b) => a.dueAt - b.dueAt || a.slug.localeCompare(b.slug) || a.topic.id.localeCompare(b.topic.id));
+ const pick = due[0];
+ const pages = pick.topic.sources.filter((s) => !pick.watch.goneSources.includes(s.trendId));
+ if (pages.length === 0) {
+ const sentence = goneSentence(pick.topic.title);
+ await mutateXTrendingWatches(pick.root, (watches) => {
+ const w = watches[pick.topic.id];
+ if (!watchIsLive(w)) return { write: false, result: null };
+ w.on = false;
+ delete w.paused;
+ w.ended = { at, reason: "gone", sentence };
+ return { write: true, result: null };
+ });
+ out.ended.push({ slug: pick.slug, topic: pick.topic.id, sentence });
+ out.live--;
+ return out;
+ }
+ const page = pages[pick.watch.nextSource % pages.length];
+ const tick: WatchTick = { slug: pick.slug, topic: pick.topic.id, url: page.url, trendId: page.trendId };
+ const interval = pick.watch.intervalMinutes * 60_000;
+ const started = await deps.enqueue(tick).catch((err) => ({ ok: false as const, error: (err as Error).message }));
+ await mutateXTrendingWatches(pick.root, (watches) => {
+ const w = watches[pick.topic.id];
+ if (!watchIsLive(w)) return { write: false, result: null };
+ if (started.ok) {
+ w.lastTickAt = at;
+ w.lastJobId = started.jobId;
+ // Stretched, never shortened.
+ w.nextTickAt = new Date(now + interval + Math.max(0, (deps.jitter ?? ((ms) => jitterMs(ms) - ms))(interval))).toISOString();
+ w.ticks++;
+ w.nextSource = (w.nextSource + 1) % 1_000_000;
+ delete w.paused;
+ } else {
+ // Not asked again every minute: the next try is an interval away.
+ w.nextTickAt = new Date(now + interval).toISOString();
+ w.paused = { reason: "refused", since: w.paused?.reason === "refused" ? w.paused.since : at, sentence: started.error };
+ }
+ return { write: true, result: null };
+ });
+ if (started.ok) {
+ out.enqueued = { ...tick, jobId: started.jobId };
+ log(`x-trending watch: ${tick.slug}/${tick.topic}: tick → job ${started.jobId} (${tick.url})`);
+ } else {
+ out.refused = { ...tick, error: started.error };
+ out.paused.push({ slug: tick.slug, topic: tick.topic, reason: "refused" });
+ log(`x-trending watch: ${tick.slug}/${tick.topic}: not ticked: ${started.error}`);
+ }
+ return out;
+}
+
+const goneSentence = (title: string) =>
+ `X no longer has the trending page of "${title}" (trending pages expire): the watch ended.`;
+
+// THE END OF A READ, told to the watch (every read of a library, a person's
+// too). A page X answered "gone" for is not read again; when the topic has no
+// page left, its watch ends with a sentence. Answers that sentence, or null.
+export async function noteXTrendingWatchRead(
+ channelRoot: string,
+ read: { trendId: string; outcome: string; now?: number },
+): Promise<string | null> {
+ if (read.outcome !== "gone") return null;
+ const topics = await readXTrendingTopics(channelRoot);
+ const at = new Date(read.now ?? Date.now()).toISOString();
+ return mutateXTrendingWatches(channelRoot, (watches) => {
+ let write = false;
+ let sentence: string | null = null;
+ for (const topic of topics) {
+ const w = watches[topic.id];
+ if (!watchIsLive(w) || !topic.sources.some((s) => s.trendId === read.trendId)) continue;
+ if (!w.goneSources.includes(read.trendId)) w.goneSources.push(read.trendId);
+ write = true;
+ if (topic.sources.every((s) => w.goneSources.includes(s.trendId))) {
+ sentence = goneSentence(topic.title);
+ w.on = false;
+ delete w.paused;
+ w.ended = { at, reason: "gone", sentence };
+ }
+ }
+ return { write, result: sentence };
+ });
+}
+
+export type WatchFollowUp = { ids: string[]; shots: boolean; fresh: number; owed: number };
+
+// WHAT ONE CAPTURE TAKES AFTER A READ INTO A WATCHED TOPIC: the read's new
+// posts (their media at once; a screenshot too when the topic says so), then
+// the topic's posts a capture left OWED to a later one (the job's budget, X's
+// cooldown) — never one that failed, and never one owed until it is kept.
+// Null when the topic is not watched or there is nothing to take.
+export async function xTrendingWatchFollowUp(
+ channelRoot: string,
+ o: { topic: string; newIds: ReadonlyArray<string> },
+): Promise<WatchFollowUp | null> {
+ const watch = (await readXTrendingWatches(channelRoot))[o.topic];
+ if (!watchIsLive(watch)) return null;
+ const membership = await readXTrendingMembership(channelRoot);
+ // Media only: a post with none is not captured (nothing to fetch, no page).
+ const fresh = o.newIds.filter((id) => membership[id]?.topic === o.topic && (watch.shots || (membership[id]?.media?.count ?? 0) > 0));
+ const ids = fresh.slice(0, X_TRENDING_WATCH_CAPTURE_MAX);
+ let owed = 0;
+ const taken = new Set(ids);
+ for (const [id, m] of Object.entries(membership)) {
+ if (ids.length >= X_TRENDING_WATCH_CAPTURE_MAX) break;
+ if (m.topic !== o.topic || taken.has(id)) continue;
+ if ((await xTrendingCaptureSummary(channelRoot, id))?.mediaOwed !== "next") continue;
+ ids.push(id);
+ owed++;
+ }
+ return ids.length > 0 ? { ids, shots: watch.shots, fresh: ids.length - owed, owed } : null;
+}
+
+// ─── arming (the editor's instrumentation, below the idle gate) ───
+
+type Armed = { deps: WatchScanDeps; timer: ReturnType<typeof setInterval> | null; scanning: Promise<WatchScanResult> | null };
+
+declare global {
+ // eslint-disable-next-line no-var
+ var __yttXTrendingWatch__: Armed | undefined;
+}
+
+// One scan at a time: a second caller shares the one going. Null when unarmed.
+export function xTrendingWatchTick(): Promise<WatchScanResult> | null {
+ const a = globalThis.__yttXTrendingWatch__;
+ if (!a) return null;
+ if (!a.scanning) {
+ a.scanning = scanXTrendingWatches(a.deps).finally(() => {
+ a.scanning = null;
+ });
+ }
+ return a.scanning;
+}
+
+// Arm the scan: every `everyMs` (default CHECK_MS). Refused (false) on an idle
+// boot. Idempotent: a second call only replaces the deps.
+export function armXTrendingWatch(
+ deps: WatchScanDeps,
+ opts: { env?: Record<string, string | undefined>; everyMs?: number } = {},
+): boolean {
+ if (isIdleBoot(opts.env ?? process.env)) return false;
+ const armed = globalThis.__yttXTrendingWatch__;
+ if (armed) {
+ armed.deps = deps;
+ return true;
+ }
+ const state: Armed = { deps, timer: null, scanning: null };
+ globalThis.__yttXTrendingWatch__ = state;
+ const every = opts.everyMs ?? X_TRENDING_WATCH_CHECK_MS;
+ if (every > 0) {
+ state.timer = setInterval(() => {
+ void xTrendingWatchTick()?.catch((e) => state.deps.log?.(`x-trending watch: the scan failed: ${(e as Error).message}`));
+ }, every);
+ state.timer.unref?.();
+ }
+ return true;
+}
+
+export function disarmXTrendingWatch(): void {
+ const a = globalThis.__yttXTrendingWatch__;
+ if (a?.timer) clearInterval(a.timer);
+ globalThis.__yttXTrendingWatch__ = undefined;
+}
+
+export function isXTrendingWatchArmed(): boolean {
+ return globalThis.__yttXTrendingWatch__ !== undefined;
+}
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -689,8 +689,11 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
// on the profile beside it. Network; not drainable (a read is a minute or
// two; a Cancel stops it between scrolls and what it read is kept); NOT
// replayable and not resumed on boot — a read is a request to X, and nothing
- // repeats one unasked; started only by a person (or an agent's ask), never
- // by a boot.
+ // repeats one unasked; started by a person (or an agent's ask), or by the
+ // watch's scan for a topic someone switched a watch on for
+ // (controller/xTrendingWatch.ts) — never by a boot: a tick left queued
+ // across a restart is cancelled, and the scan re-derives it, which it does
+ // only while X's cookie jar is fresh.
"read-x-trending": {
kind: "read-x-trending",
label: "Read X trending page",
diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts
@@ -402,7 +402,7 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
xSearch:
'An X SEARCH channel (platform `"twitter"`, `sourceKind` `"social"`, `url` the search page): a saved X search across accounts, its records the matching posts from ANY author. `{query, since?, until?, windowMonths?, lang?, exclude?}` — `query` as X\'s search box takes it (words, `"phrases"`, `OR`, `-term`, `from:`, `to:`, `@mention`, `url:`, `filter:`, `lang:` pass through; `since:`, `until:` and `max_id:` are refused — the walk adds them); `since`/`until` the days walked between (YYYY-MM-DD; `since` inclusive, `until` exclusive; absent `until` = tomorrow, and each later fetch searches what is new); `windowMonths` each search window\'s span (1–12, default 3); `lang` a language code added as `lang:<code>`; `exclude` the handles **Never archive** hid from the leads view (lower case). A fetch walks the windows newest first through gallery-dl\'s search, resumable, at the older walk\'s pace and with its login (OPERATING.md, "X search"). Never on a site. An object without a valid query is dropped.',
xTrending:
- 'An X TRENDING LIBRARY (platform `"twitter"`, `sourceKind` `"social"`, no `url`): a PRIVATE posts channel whose records are the posts X\'s trending pages (`x.com/i/trending/<id>`) showed, from ANY author, read one page at a time by `pnpm ops read-x-trending` and grouped into topics. Everything of it — its posts too — is kept under `channels/<slug>/trending/`, not in `channels/<slug>/posts/`, so no reader of a posts channel finds them. The marker alone makes a channel a library. `{maxScrolls?, maxPosts?, maxVideoMb?}` — the caps a read uses when the ask names none (1–20 scrolls, default 8; 1–200 posts, default 60), and the largest media file, in MB, fetched for a post nobody has kept (1–2000, default 100; a larger one is owed until the post is kept); `{}` is a library with the defaults. Never on a site (refused on create, on Configure and by every site writer), in no index build (so not in the editor\'s own search either), never synced. Set by creating a channel with platform `x-trending`; not a Configure field.',
+ 'An X TRENDING LIBRARY (platform `"twitter"`, `sourceKind` `"social"`, no `url`): a PRIVATE posts channel whose records are the posts X\'s trending pages (`x.com/i/trending/<id>`) showed, from ANY author, read one page at a time by `pnpm ops read-x-trending` and grouped into topics. Everything of it — its posts too — is kept under `channels/<slug>/trending/`, not in `channels/<slug>/posts/`, so no reader of a posts channel finds them. The marker alone makes a channel a library. `{maxScrolls?, maxPosts?, maxVideoMb?, watchIntervalMinutes?, watchHours?, watchMaxTopics?}` — the caps a read uses when the ask names none (1–20 scrolls, default 8; 1–200 posts, default 60); the largest media file, in MB, fetched for a post nobody has kept (1–2000, default 100; a larger one is owed until the post is kept); and the defaults of the watch: how often a watched topic is read (15–1440 minutes, default 30), for how long (1–168 hours, default 48) and how many topics may be watched at once (1–12, default 4) — `pnpm ops watch-trending` sets these three and `maxVideoMb`; `{}` is a library with the defaults. Never on a site (refused on create, on Configure and by every site writer), in no index build (so not in the editor\'s own search either), never synced. Set by creating a channel with platform `x-trending`; not a Configure field.',
localMedia:
"Opt-in external MP4 library: {sourceId, directory, playback?}. The sourceId is a stable lowercase identifier; directory is an absolute server/container path. Source files remain externally owned. Playback is off unless explicitly true, and this flag alone does not authorize public serving. Removing or changing configuration must never move or delete source files. Do not reuse an existing sourceId for a different library; reconcile references explicitly. Private configuration: never include source paths in public exports.",
};
diff --git a/common/lib/xTrending/config.ts b/common/lib/xTrending/config.ts
@@ -25,6 +25,12 @@ export type XTrendingConfig = {
// has kept (a watched topic's new posts): it is owed until the post is
// kept. Absent: X_TRENDING_DEFAULT_VIDEO_MB.
maxVideoMb?: number;
+ // THE WATCH's defaults for this library (lib/xTrending/watch.ts): how often
+ // a watched topic is read (minutes), for how long (hours), and how many
+ // topics may be watched at once. Absent: 30, 48 and 4.
+ watchIntervalMinutes?: number;
+ watchHours?: number;
+ watchMaxTopics?: number;
};
// The two job kinds, and X's platform queue they run on: one browser on the
@@ -55,6 +61,15 @@ export const X_TRENDING_DEFAULT_POSTS = 60;
export const X_TRENDING_MAX_POSTS = 200;
export const X_TRENDING_DEFAULT_VIDEO_MB = 100;
export const X_TRENDING_MAX_VIDEO_MB = 2000;
+// The watch: X's gap between two jobs is 5 minutes and a tick is a read and
+// then a capture, so nothing shorter than 15 minutes is a real interval.
+export const X_TRENDING_WATCH_DEFAULT_INTERVAL_MINUTES = 30;
+export const X_TRENDING_WATCH_MIN_INTERVAL_MINUTES = 15;
+export const X_TRENDING_WATCH_MAX_INTERVAL_MINUTES = 24 * 60;
+export const X_TRENDING_WATCH_DEFAULT_HOURS = 48;
+export const X_TRENDING_WATCH_MAX_HOURS = 7 * 24;
+export const X_TRENDING_WATCH_DEFAULT_TOPICS = 4;
+export const X_TRENDING_WATCH_MAX_TOPICS = 12;
// A read ends after this many scrolls in a row that brought no new post.
export const X_TRENDING_IDLE_SCROLLS = 2;
@@ -74,6 +89,12 @@ export function coerceXTrendingConfig(v: unknown): XTrendingConfig | undefined {
if (posts !== undefined) out.maxPosts = posts;
const videoMb = capOf(r.maxVideoMb, X_TRENDING_MAX_VIDEO_MB);
if (videoMb !== undefined) out.maxVideoMb = videoMb;
+ const interval = capOf(r.watchIntervalMinutes, X_TRENDING_WATCH_MAX_INTERVAL_MINUTES);
+ if (interval !== undefined && interval >= X_TRENDING_WATCH_MIN_INTERVAL_MINUTES) out.watchIntervalMinutes = interval;
+ const hours = capOf(r.watchHours, X_TRENDING_WATCH_MAX_HOURS);
+ if (hours !== undefined) out.watchHours = hours;
+ const topics = capOf(r.watchMaxTopics, X_TRENDING_WATCH_MAX_TOPICS);
+ if (topics !== undefined) out.watchMaxTopics = topics;
return out;
}
@@ -151,3 +172,37 @@ export function xTrendingLimits(
export function xTrendingMaxVideoBytes(config: XTrendingConfig | undefined): number {
return (config?.maxVideoMb ?? X_TRENDING_DEFAULT_VIDEO_MB) * 1024 * 1024;
}
+
+export type XTrendingWatchTerms = { intervalMinutes: number; hours: number };
+
+// One watch's interval and length: the ask's, else the library's, else the
+// defaults. A value out of range is refused with a sentence, never clamped.
+export function xTrendingWatchTerms(
+ config: XTrendingConfig | undefined,
+ ask: { intervalMinutes?: unknown; hours?: unknown } = {},
+): { ok: true; terms: XTrendingWatchTerms } | { ok: false; error: string } {
+ let intervalMinutes = config?.watchIntervalMinutes ?? X_TRENDING_WATCH_DEFAULT_INTERVAL_MINUTES;
+ if (ask.intervalMinutes !== undefined && ask.intervalMinutes !== null) {
+ const n = capOf(ask.intervalMinutes, X_TRENDING_WATCH_MAX_INTERVAL_MINUTES);
+ if (n === undefined || n < X_TRENDING_WATCH_MIN_INTERVAL_MINUTES) {
+ return {
+ ok: false,
+ error:
+ `"intervalMinutes" is a whole number, ${X_TRENDING_WATCH_MIN_INTERVAL_MINUTES}–${X_TRENDING_WATCH_MAX_INTERVAL_MINUTES} ` +
+ `(X's jobs are 5 minutes apart, and a tick is a read and then a capture)`,
+ };
+ }
+ intervalMinutes = n;
+ }
+ let hours = config?.watchHours ?? X_TRENDING_WATCH_DEFAULT_HOURS;
+ if (ask.hours !== undefined && ask.hours !== null) {
+ const n = capOf(ask.hours, X_TRENDING_WATCH_MAX_HOURS);
+ if (n === undefined) return { ok: false, error: `"hours" is a whole number, 1–${X_TRENDING_WATCH_MAX_HOURS}` };
+ hours = n;
+ }
+ return { ok: true, terms: { intervalMinutes, hours } };
+}
+
+export function xTrendingWatchMaxTopics(config: XTrendingConfig | undefined): number {
+ return config?.watchMaxTopics ?? X_TRENDING_WATCH_DEFAULT_TOPICS;
+}
diff --git a/common/lib/xTrending/mediaStore.ts b/common/lib/xTrending/mediaStore.ts
@@ -77,7 +77,14 @@ export type XTrendingMediaBlob = {
posts: Record<string, string[]>;
};
-export type XTrendingMediaIndex = { version: 1; blobs: Record<string, XTrendingMediaBlob> };
+export type XTrendingMediaIndex = {
+ version: 1;
+ blobs: Record<string, XTrendingMediaBlob>;
+ // Addresses whose file was found larger than a cap, and how large (the
+ // cap + 1 when it was cut off mid-stream): not asked for again while the
+ // cap stands, so a watch does not start the same big download every tick.
+ oversize: Record<string, { bytes: number; at: string }>;
+};
const SHA = /^[0-9a-f]{64}$/;
const POST_ID = /^\d{1,25}$/;
@@ -86,7 +93,14 @@ const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/;
function parseIndex(raw: unknown): XTrendingMediaIndex {
const blobs = (raw as { blobs?: unknown } | null)?.blobs;
- const out: XTrendingMediaIndex = { version: 1, blobs: {} };
+ const out: XTrendingMediaIndex = { version: 1, blobs: {}, oversize: {} };
+ const oversize = (raw as { oversize?: unknown } | null)?.oversize;
+ if (oversize && typeof oversize === "object" && !Array.isArray(oversize)) {
+ for (const [url, o] of Object.entries(oversize as Record<string, { bytes?: unknown; at?: unknown } | null>)) {
+ if (!o || typeof o !== "object" || !(Number(o.bytes) > 0)) continue;
+ out.oversize[url] = { bytes: Number(o.bytes), at: typeof o.at === "string" ? o.at : "" };
+ }
+ }
if (!blobs || typeof blobs !== "object" || Array.isArray(blobs)) return out;
for (const [sha, b] of Object.entries(blobs as Record<string, Partial<XTrendingMediaBlob> | null>)) {
if (!SHA.test(sha) || !b || typeof b !== "object") continue;
@@ -109,7 +123,7 @@ function parseIndex(raw: unknown): XTrendingMediaIndex {
export async function readXTrendingMediaIndex(channelRoot: string): Promise<XTrendingMediaIndex> {
const read = await readJsonFile(xTrendingMediaIndexPath(channelRoot));
- return read.ok ? parseIndex(read.value) : { version: 1, blobs: {} };
+ return read.ok ? parseIndex(read.value) : { version: 1, blobs: {}, oversize: {} };
}
// The blob that came from this address, or undefined.
@@ -156,6 +170,18 @@ function note(blob: XTrendingMediaBlob, postId: string, name: string, url?: stri
if (url && !blob.urls.includes(url)) blob.urls.push(url);
}
+// An address whose file is larger than a cap, remembered with its size.
+export async function noteXTrendingOversize(
+ channelRoot: string,
+ o: { url: string; bytes: number; now?: () => number },
+): Promise<void> {
+ await withJsonFileLock(xTrendingMediaIndexPath(channelRoot), async () => {
+ const index = await readXTrendingMediaIndex(channelRoot);
+ index.oversize[o.url] = { bytes: o.bytes, at: new Date((o.now ?? Date.now)()).toISOString() };
+ await writeJsonAtomic(xTrendingMediaIndexPath(channelRoot), index, { mkdir: true });
+ });
+}
+
export type AdoptedMedia = {
sha256: string;
bytes: number;
@@ -204,6 +230,7 @@ export async function adoptXTrendingMedia(
posts: {},
});
note(entry, o.postId, o.name, o.url);
+ if (o.url) delete index.oversize[o.url];
await writeJsonAtomic(xTrendingMediaIndexPath(channelRoot), index, { mkdir: true });
return { sha256, bytes, deduped, linked };
});
diff --git a/common/lib/xTrending/store.test.ts b/common/lib/xTrending/store.test.ts
@@ -77,6 +77,8 @@ test("the first read of a page makes a topic named for it; a re-read adds posts,
topic: { id: `t-${REF.trendId}`, title: `Trending ${REF.trendId}`, created: true },
placed: 2,
kept: 0,
+ gone: [],
+ back: [],
});
await writeXTrendingPosts(dir, [post("103", "lid_watch", "three")]);
const second = await recordXTrendingRead(dir, {
@@ -90,6 +92,9 @@ test("the first read of a page makes a topic named for it; a re-read adds posts,
topic: { id: `t-${REF.trendId}`, title: `Trending ${REF.trendId}`, created: false },
placed: 1,
kept: 1,
+ // 102 was not shown, but this read did not say it reached the page's end.
+ gone: [],
+ back: [],
});
const topics = await readXTrendingTopics(dir);
assert.equal(topics.length, 1);
@@ -148,7 +153,7 @@ test("a named topic is found by id or title, else made; a second page merges int
postIds: ["201", "203"],
added: 1,
});
- assert.deepEqual(other, { topic: { id: "saucers", title: "Saucers", created: true }, placed: 1, kept: 1 });
+ assert.deepEqual(other, { topic: { id: "saucers", title: "Saucers", created: true }, placed: 1, kept: 1, gone: [], back: [] });
const members = await readXTrendingMembership(dir);
assert.equal(members["201"].topic, "kettle-festival");
assert.equal(members["203"].topic, "saucers");
@@ -288,3 +293,51 @@ test("no module of the lane reaches the channel's own posts-media: a library's m
const { xTrendingPostsMediaDir } = await import("./store");
assert.equal(xTrendingPostsMediaDir("/c/lib"), "/c/lib/trending/posts-media");
});
+
+// Lane x-trending-2.
+test("gone from the page: only a read that reached the page's end says so, only of posts that page showed, and a post shown again is back", async () => {
+ const dir = root("gone");
+ await writeXTrendingPosts(dir, [post("801", "a", "one"), post("802", "b", "two"), post("803", "c", "three"), post("804", "d", "four")]);
+ await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: ["801", "802"], added: 2, complete: true });
+ // Another page of the same topic showed 803; it is never judged by REF's reads.
+ await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T10:30:00.000Z", ref: REF_2, topic: "T", postIds: ["803"], added: 1, complete: true });
+ // A read that stopped at its cap asserts nothing.
+ const capped = await recordXTrendingRead(dir, { readId: READ_C, at: "2026-11-17T11:00:00.000Z", ref: REF, topic: "T", postIds: ["801"], added: 0 });
+ assert.deepEqual(capped.gone, []);
+ assert.equal((await readXTrendingMembership(dir))["802"].gone, undefined);
+ // A complete one does: 802 is gone from the page; 803 (the other page's) and 804 (new) are not.
+ const READ_D = "tr-01JD0000000000000000000000";
+ const done = await recordXTrendingRead(dir, { readId: READ_D, at: "2026-11-17T11:30:00.000Z", ref: REF, topic: "T", postIds: ["801", "804"], added: 1, complete: true });
+ assert.deepEqual(done.gone, ["802"]);
+ let members = await readXTrendingMembership(dir);
+ assert.deepEqual(members["802"].gone, { at: "2026-11-17T11:30:00.000Z", read: READ_D, trendId: REF.trendId });
+ assert.equal(members["803"].gone, undefined);
+ assert.equal(members["804"].gone, undefined);
+ const row = (await listXTrending(dir)).posts.find((p) => p.id === "802");
+ assert.deepEqual(row?.gone, { at: "2026-11-17T11:30:00.000Z", read: READ_D, trendId: REF.trendId });
+ // Recorded once: a later complete read without it does not move the time.
+ const READ_E = "tr-01JE0000000000000000000000";
+ assert.deepEqual((await recordXTrendingRead(dir, { readId: READ_E, at: "2026-11-17T12:00:00.000Z", ref: REF, topic: "T", postIds: ["801"], added: 0, complete: true })).gone, ["804"]);
+ assert.equal((await readXTrendingMembership(dir))["802"].gone?.at, "2026-11-17T11:30:00.000Z");
+ // Shown again: back, with the absence kept as history.
+ const READ_F = "tr-01JF0000000000000000000000";
+ const back = await recordXTrendingRead(dir, { readId: READ_F, at: "2026-11-17T12:30:00.000Z", ref: REF, topic: "T", postIds: ["802", "801"], added: 0, complete: true });
+ assert.deepEqual(back.back, ["802"]);
+ members = await readXTrendingMembership(dir);
+ assert.equal(members["802"].gone, undefined);
+ assert.deepEqual(members["802"].wasGone, [{ from: "2026-11-17T11:30:00.000Z", to: "2026-11-17T12:30:00.000Z" }]);
+});
+
+test("a captured post's row says what its capture holds and what it is owed", async () => {
+ const dir = root("capture-summary");
+ await writeXTrendingPosts(dir, [post("811", "a", "one"), post("812", "b", "two")]);
+ await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: ["811", "812"], added: 2 });
+ mkdirSync(path.join(dir, "trending", "posts-media", "811"), { recursive: true });
+ writeFileSync(
+ path.join(dir, "trending", "posts-media", "811", "capture.json"),
+ JSON.stringify({ version: 1, id: "811", capturedAt: "2026-11-17T10:05:00.000Z", state: "captured", mediaState: "error", mediaOwed: "kept", media: [{ name: "811_1.jpg" }] }),
+ );
+ const rows = Object.fromEntries((await listXTrending(dir)).posts.map((p) => [p.id, p]));
+ assert.deepEqual(rows["811"].capture, { at: "2026-11-17T10:05:00.000Z", state: "captured", shot: false, files: 1, mediaState: "error", mediaOwed: "kept" });
+ assert.equal(rows["812"].capture, undefined);
+});
diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts
@@ -48,6 +48,9 @@ import { readJsonFile, withJsonFileLock, writeFileAtomic, writeJsonAtomic } from
import { readAllPosts, readSeenPostIds, writePosts, type WritePostsResult } from "../posts-server";
import type { Post } from "../posts";
import type { XTrendingRef } from "./config";
+// (./watch imports this module for its paths; each uses the other only inside
+// functions, so the cycle is one of names, not of load order.)
+import { describeXTrendingWatch, readXTrendingWatches, type XTrendingWatch } from "./watch";
export const TRENDING_DIRNAME = "trending";
export const TRENDING_READS_DIRNAME = "reads";
@@ -230,6 +233,36 @@ export async function firstCapturedThumbnail(channelRoot: string, id: string): P
return pick ? `${TRENDING_DIRNAME}/${LIBRARY_MEDIA_DIRNAME}/${id}/${pick}` : undefined;
}
+// A captured post, as the listing says it: whether it was shot, how many media
+// files it holds, how its media half stands ("ok", "none", "skipped",
+// "error") and what it is owed ("next": a later capture asks again; "kept":
+// once the post is marked keep).
+export type XTrendingCaptureSummary = {
+ at: string;
+ state: string;
+ shot: boolean;
+ files: number;
+ mediaState: string;
+ mediaOwed?: "next" | "kept";
+};
+
+// capture.json of a library post, read as plain JSON (its writer is
+// social/postCapture.ts; this module imports nothing of social/).
+export async function xTrendingCaptureSummary(channelRoot: string, id: string): Promise<XTrendingCaptureSummary | undefined> {
+ if (!/^\d+$/.test(id)) return undefined;
+ const read = await readJsonFile(path.join(xTrendingPostsMediaDir(channelRoot), id, "capture.json"));
+ const r = read.ok ? (read.value as Record<string, unknown> | null) : null;
+ if (!r || typeof r !== "object" || typeof r.capturedAt !== "string" || typeof r.state !== "string") return undefined;
+ return {
+ at: r.capturedAt,
+ state: r.state,
+ shot: !!r.shot,
+ files: Array.isArray(r.media) ? r.media.length : 0,
+ mediaState: typeof r.mediaState === "string" ? r.mediaState : "skipped",
+ ...(r.mediaOwed === "next" || r.mediaOwed === "kept" ? { mediaOwed: r.mediaOwed } : {}),
+ };
+}
+
export type XTrendingSourceRead = {
// The read's id (`reads/<id>/`), when it ran, the posts it showed and how
// many of them were new to the library.
@@ -259,10 +292,20 @@ export type XTrendingTopic = {
export type XTrendingSeen = { read: string; trendId: string; at: string; rank: number };
+// GONE FROM THE PAGE (lane x-trending-2): a post a page showed before, absent
+// from a later read of that page that reached the page's end. It says what
+// the page showed and NOTHING about the post — a trending page is a ranked
+// list, and a post leaves it by being outranked as well as by being deleted.
+// A read that stopped at a cap, was cancelled or failed asserts nothing.
+export type XTrendingGone = { at: string; read: string; trendId: string };
+
export type XTrendingMember = {
topic: string;
seen: XTrendingSeen[];
media?: XTrendingMedia;
+ gone?: XTrendingGone;
+ // Earlier absences that ended: gone from `from`, shown again at `to`.
+ wasGone?: Array<{ from: string; to: string }>;
};
type TopicsFile = { version: 1; topics: XTrendingTopic[] };
@@ -319,7 +362,18 @@ function parseMembership(raw: unknown): Record<string, XTrendingMember> {
),
}
: undefined;
- out[id] = { topic: m.topic, seen, ...(media ? { media } : {}) };
+ const g = m.gone as Partial<XTrendingGone> | undefined;
+ const gone = g && typeof g === "object" && str(g.at) && isXTrendingReadId(g.read) && str(g.trendId) ? { at: g.at, read: g.read, trendId: g.trendId } : undefined;
+ const wasGone = (Array.isArray(m.wasGone) ? m.wasGone : []).filter(
+ (w): w is { from: string; to: string } => !!w && typeof w === "object" && str(w.from) && str(w.to),
+ );
+ out[id] = {
+ topic: m.topic,
+ seen,
+ ...(media ? { media } : {}),
+ ...(gone ? { gone } : {}),
+ ...(wasGone.length ? { wasGone: wasGone.map((w) => ({ from: w.from, to: w.to })) } : {}),
+ };
}
return out;
}
@@ -370,6 +424,9 @@ export type RecordReadInput = {
// How many of them the library did not hold before this read.
added: number;
media?: Readonly<Record<string, XTrendingMedia>>;
+ // The read reached the page's end (it stopped because the page had no more
+ // to show): only then is a post it did not show marked gone from the page.
+ complete?: boolean;
};
export type RecordReadResult = {
@@ -378,6 +435,10 @@ export type RecordReadResult = {
placed: number;
// Posts the library already had, left in the topic they were in.
kept: number;
+ // Posts this page showed before and did not show now (a complete read
+ // only), and posts that were gone and are shown again.
+ gone: string[];
+ back: string[];
};
// One read, recorded: its topic found or made, the page added to the topic's
@@ -427,6 +488,8 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead
const posts = await readXTrendingMembership(channelRoot);
let placed = 0;
let kept = 0;
+ const gone: string[] = [];
+ const back: string[] = [];
input.postIds.forEach((id, i) => {
const seen: XTrendingSeen = { read: input.readId, trendId: input.ref.trendId, at: input.at, rank: i + 1 };
const have = posts[id];
@@ -434,13 +497,29 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead
kept++;
if (!have.seen.some((s) => s.read === input.readId)) have.seen.push(seen);
if (!have.media && input.media?.[id]) have.media = input.media[id];
+ // Shown again, by a read later than the one that missed it.
+ if (have.gone && input.at > have.gone.at) {
+ (have.wasGone ??= []).push({ from: have.gone.at, to: input.at });
+ delete have.gone;
+ back.push(id);
+ }
} else {
placed++;
posts[id] = { topic: topic.id, seen: [seen], ...(input.media?.[id] ? { media: input.media[id] } : {}) };
}
});
+ if (input.complete) {
+ const shown = new Set(input.postIds);
+ for (const [id, m] of Object.entries(posts)) {
+ if (shown.has(id) || m.gone) continue;
+ // Only a post THIS page showed, in a read before this one.
+ if (!m.seen.some((s) => s.trendId === input.ref.trendId && s.read !== input.readId && s.at < input.at)) continue;
+ m.gone = { at: input.at, read: input.readId, trendId: input.ref.trendId };
+ gone.push(id);
+ }
+ }
await writeJsonAtomic(membershipPath(channelRoot), { version: 1, posts } satisfies MembershipFile, { mkdir: true });
- return { placed, kept };
+ return { placed, kept, gone, back };
});
return { topic, ...counts };
}
@@ -531,6 +610,9 @@ export type XTrendingTopicRow = {
id: string;
title: string;
posts: number;
+ // Its watch, once it has been watched (lib/xTrending/watch.ts), with what it
+ // is doing as one sentence.
+ watch?: XTrendingWatch & { sentence: string };
sources: Array<{
trendId: string;
url: string;
@@ -555,6 +637,11 @@ export type XTrendingPostRow = {
media: XTrendingMedia & { thumbnail?: string };
topic: string;
reads: Array<{ read: string; trendId: string; at: string }>;
+ // Gone from the page: a page that showed it before did not show it at
+ // `at` (a read that reached the page's end). Never "deleted".
+ gone?: XTrendingGone;
+ // What its capture holds: the files beside its record, and what is owed.
+ capture?: XTrendingCaptureSummary;
// The thread it belongs to: its root post's id (xTrendingThreadKey).
thread: string;
// Its own judgement, else its thread's (`from: "thread"`). Absent: undecided.
@@ -588,8 +675,10 @@ const lastSeen = (m: XTrendingMember) => m.seen.reduce((a, s) => (s.at > a ? s.a
// id); `limit` caps them (the newest read's first, in page order).
export async function listXTrending(
channelRoot: string,
- opts: { topic?: string; limit?: number; posts?: ReadonlyArray<Post> } = {},
+ opts: { topic?: string; limit?: number; posts?: ReadonlyArray<Post>; now?: number } = {},
): Promise<XTrendingListing> {
+ const now = opts.now ?? Date.now();
+ const watches = await readXTrendingWatches(channelRoot);
const [topics, membership, reads, judgements] = await Promise.all([
readXTrendingTopics(channelRoot),
readXTrendingMembership(channelRoot),
@@ -617,6 +706,7 @@ export async function listXTrending(
media: m.media ?? { count: post.mediaCount ?? 0, kinds: [] },
topic: m.topic,
reads: m.seen.map((s) => ({ read: s.read, trendId: s.trendId, at: s.at })),
+ ...(m.gone ? { gone: m.gone } : {}),
thread,
...(judgements.posts[id]
? { judgement: judgements.posts[id] }
@@ -641,6 +731,7 @@ export async function listXTrending(
id: t.id,
title: t.title,
posts: count.get(t.id) ?? 0,
+ ...(watches[t.id] ? { watch: { ...watches[t.id], sentence: describeXTrendingWatch(watches[t.id], now) } } : {}),
sources: t.sources.map((s) => ({
trendId: s.trendId,
url: s.url,
@@ -653,8 +744,15 @@ export async function listXTrending(
// The thumbnail is looked up for the rows returned only (one readdir each).
posts: await Promise.all(
rows.slice(0, limit).map(async (row) => {
- const thumbnail = await firstCapturedThumbnail(channelRoot, row.id);
- return thumbnail ? { ...row, media: { ...row.media, thumbnail } } : row;
+ const [thumbnail, capture] = await Promise.all([
+ firstCapturedThumbnail(channelRoot, row.id),
+ xTrendingCaptureSummary(channelRoot, row.id),
+ ]);
+ return {
+ ...row,
+ ...(thumbnail ? { media: { ...row.media, thumbnail } } : {}),
+ ...(capture ? { capture } : {}),
+ };
}),
),
total: rows.length,
diff --git a/common/lib/xTrending/watch.ts b/common/lib/xTrending/watch.ts
@@ -0,0 +1,206 @@
+// A LIBRARY'S WATCHED TOPICS (lane x-trending-2): `trending/watch.json`.
+//
+// A watch is a per-topic switch: while it is on, the topic's trending page is
+// read again every `intervalMinutes` until `until`, by the same single
+// `read-x-trending` job a person starts (controller/xTrendingWatch.ts is the
+// scan that enqueues it; this module is the state and its ONE writer).
+//
+// on the switch
+// shots also screenshot every new post (default: only their media)
+// paused the scan could not start a tick, and why — X's cookie jar is
+// older than the limit ("jar"), the X alert is up ("alert"), X is
+// cooling down after a rate limit ("cooldown"), there is no
+// connected profile ("no-profile"), or the read was refused
+// ("refused"). A PAUSE ENDS BY ITSELF at the first scan that finds
+// the reason gone: a watch resumes after a Refresh on /cookies.
+// ended the watch is over, with a sentence: its end time came, X no
+// longer has its page(s), or it was switched off
+//
+// A WATCH RUNS ONLY WHILE X'S COOKIE JAR IS FRESH (the fresh-jar rule,
+// jobs/networkGuard.ts): the editor never refreshes the jar by itself, so a
+// watch does not cover a night nobody presses Refresh in.
+//
+// SERVER-ONLY (node:fs).
+
+import path from "node:path";
+import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../jsonFile-server";
+import { readXTrendingTopics, trendingDir } from "./store";
+
+export type XTrendingWatchPauseReason = "jar" | "alert" | "cooldown" | "no-profile" | "refused";
+export const X_TRENDING_WATCH_PAUSE_REASONS: readonly XTrendingWatchPauseReason[] = ["jar", "alert", "cooldown", "no-profile", "refused"];
+
+export type XTrendingWatch = {
+ on: boolean;
+ intervalMinutes: number;
+ // When the watch began and when it ends (ISO).
+ startedAt: string;
+ until: string;
+ shots: boolean;
+ by: "agent" | "operator";
+ // The last tick the scan enqueued: when, its job, and when the next is due.
+ lastTickAt?: string;
+ lastJobId?: string;
+ nextTickAt?: string;
+ ticks: number;
+ // Which of the topic's pages the next tick reads (round-robin).
+ nextSource: number;
+ // Pages X answered "gone" for: not read again.
+ goneSources: string[];
+ paused?: { reason: XTrendingWatchPauseReason; since: string; sentence: string };
+ ended?: { at: string; reason: "until" | "gone" | "off"; sentence: string };
+};
+
+type WatchFile = { version: 1; topics: Record<string, XTrendingWatch> };
+
+export function xTrendingWatchPath(channelRoot: string): string {
+ return path.join(trendingDir(channelRoot), "watch.json");
+}
+
+const str = (v: unknown): v is string => typeof v === "string" && v !== "";
+const iso = (v: unknown): v is string => str(v) && Number.isFinite(Date.parse(v));
+
+function parseWatch(raw: unknown): XTrendingWatch | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const r = raw as Record<string, unknown>;
+ if (typeof r.on !== "boolean" || !iso(r.startedAt) || !iso(r.until)) return null;
+ const interval = Number(r.intervalMinutes);
+ if (!Number.isInteger(interval) || interval < 1) return null;
+ const paused = r.paused as XTrendingWatch["paused"] | undefined;
+ const ended = r.ended as XTrendingWatch["ended"] | undefined;
+ return {
+ on: r.on,
+ intervalMinutes: interval,
+ startedAt: r.startedAt,
+ until: r.until,
+ shots: r.shots === true,
+ by: r.by === "operator" ? "operator" : "agent",
+ ...(iso(r.lastTickAt) ? { lastTickAt: r.lastTickAt } : {}),
+ ...(str(r.lastJobId) ? { lastJobId: r.lastJobId } : {}),
+ ...(iso(r.nextTickAt) ? { nextTickAt: r.nextTickAt } : {}),
+ ticks: Number.isInteger(r.ticks) && (r.ticks as number) > 0 ? (r.ticks as number) : 0,
+ nextSource: Number.isInteger(r.nextSource) && (r.nextSource as number) > 0 ? (r.nextSource as number) : 0,
+ goneSources: Array.isArray(r.goneSources) ? r.goneSources.filter((t): t is string => typeof t === "string" && /^\d+$/.test(t)) : [],
+ ...(paused && typeof paused === "object" && X_TRENDING_WATCH_PAUSE_REASONS.includes(paused.reason) && iso(paused.since) && str(paused.sentence)
+ ? { paused: { reason: paused.reason, since: paused.since, sentence: paused.sentence } }
+ : {}),
+ ...(ended && typeof ended === "object" && iso(ended.at) && str(ended.sentence) && (ended.reason === "until" || ended.reason === "gone" || ended.reason === "off")
+ ? { ended: { at: ended.at, reason: ended.reason, sentence: ended.sentence } }
+ : {}),
+ };
+}
+
+// The watches by topic id ({} while there is no file). Ill-shaped entries are dropped.
+export async function readXTrendingWatches(channelRoot: string): Promise<Record<string, XTrendingWatch>> {
+ const read = await readJsonFile(xTrendingWatchPath(channelRoot));
+ const topics = read.ok ? (read.value as { topics?: unknown } | null)?.topics : null;
+ const out: Record<string, XTrendingWatch> = {};
+ if (!topics || typeof topics !== "object" || Array.isArray(topics)) return out;
+ for (const [id, raw] of Object.entries(topics as Record<string, unknown>)) {
+ const w = parseWatch(raw);
+ if (w && id) out[id] = w;
+ }
+ return out;
+}
+
+// A watch the scan still ticks: switched on and not ended.
+export const watchIsLive = (w: XTrendingWatch | undefined): w is XTrendingWatch => !!w && w.on && !w.ended;
+
+// Every write of watch.json: the file read under its lock, changed, written.
+// `change` answers false to write nothing.
+export async function mutateXTrendingWatches<T>(
+ channelRoot: string,
+ change: (topics: Record<string, XTrendingWatch>) => { write: boolean; result: T },
+): Promise<T> {
+ return withJsonFileLock(xTrendingWatchPath(channelRoot), async () => {
+ const topics = await readXTrendingWatches(channelRoot);
+ const { write, result } = change(topics);
+ if (write) await writeJsonAtomic(xTrendingWatchPath(channelRoot), { version: 1, topics } satisfies WatchFile, { mkdir: true });
+ return result;
+ });
+}
+
+export type SetWatchAsk = {
+ topic: string;
+ on: boolean;
+ intervalMinutes: number;
+ hours: number;
+ shots?: boolean;
+ by: "agent" | "operator";
+ maxTopics: number;
+ now: number;
+};
+
+export type SetWatchResult = { ok: true; topic: string; watch: XTrendingWatch } | { ok: false; error: string };
+
+const hhmm = (ms: number) => new Date(ms).toISOString().slice(0, 16).replace("T", " ");
+
+// The switch. ON: the topic must exist and hold at least one trending page,
+// and the library may not already watch `maxTopics` others; switching a live
+// watch on again changes its interval, end time and shots and keeps its
+// history. OFF: the watch ends ("switched off"); a watch that is not on is
+// left as it is.
+export async function setXTrendingWatch(channelRoot: string, ask: SetWatchAsk): Promise<SetWatchResult> {
+ const topics = await readXTrendingTopics(channelRoot);
+ const topic = topics.find((t) => t.id === ask.topic) ?? topics.find((t) => t.title.toLowerCase() === ask.topic.trim().toLowerCase());
+ if (!topic) {
+ return { ok: false, error: `This library has no topic "${ask.topic}" (its topics: ${topics.map((t) => t.id).join(", ") || "none yet"}).` };
+ }
+ const at = new Date(ask.now).toISOString();
+ return mutateXTrendingWatches<SetWatchResult>(channelRoot, (watches) => {
+ const have = watches[topic.id];
+ if (!ask.on) {
+ if (!watchIsLive(have)) {
+ return { write: false, result: { ok: false, error: `Topic "${topic.title}" is not being watched.` } };
+ }
+ have.on = false;
+ delete have.paused;
+ have.ended = { at, reason: "off", sentence: `The watch of "${topic.title}" was switched off.` };
+ return { write: true, result: { ok: true, topic: topic.id, watch: have } };
+ }
+ if (topic.sources.length === 0) {
+ return { write: false, result: { ok: false, error: `Topic "${topic.title}" holds no trending page to watch: read one into it first.` } };
+ }
+ const others = Object.entries(watches).filter(([id, w]) => id !== topic.id && watchIsLive(w)).length;
+ if (!watchIsLive(have) && others >= ask.maxTopics) {
+ return {
+ write: false,
+ result: {
+ ok: false,
+ error:
+ `This library already watches ${others} topic${others === 1 ? "" : "s"} (at most ${ask.maxTopics}): ` +
+ `switch one off first, or raise the limit (watch-trending {"settings": {"maxTopics": …}}).`,
+ },
+ };
+ }
+ const until = new Date(ask.now + ask.hours * 3_600_000).toISOString();
+ const live = watchIsLive(have) ? have : undefined;
+ const watch: XTrendingWatch = {
+ on: true,
+ intervalMinutes: ask.intervalMinutes,
+ startedAt: live?.startedAt ?? at,
+ until,
+ shots: ask.shots ?? live?.shots ?? false,
+ by: ask.by,
+ ...(live?.lastTickAt ? { lastTickAt: live.lastTickAt } : {}),
+ ...(live?.lastJobId ? { lastJobId: live.lastJobId } : {}),
+ // A changed interval counts from the last tick; a new watch ticks at the next scan.
+ ...(live?.lastTickAt ? { nextTickAt: new Date(Date.parse(live.lastTickAt) + ask.intervalMinutes * 60_000).toISOString() } : {}),
+ ticks: live?.ticks ?? 0,
+ nextSource: live?.nextSource ?? 0,
+ goneSources: live?.goneSources ?? [],
+ ...(live?.paused ? { paused: live.paused } : {}),
+ };
+ watches[topic.id] = watch;
+ return { write: true, result: { ok: true, topic: topic.id, watch } };
+ });
+}
+
+// What a watch is doing, in one sentence (the panel, `get trending`, the MCP).
+export function describeXTrendingWatch(w: XTrendingWatch, now: number): string {
+ if (w.ended) return w.ended.sentence;
+ if (!w.on) return "Not watched.";
+ const every = `every ${w.intervalMinutes} min until ${hhmm(Date.parse(w.until))} UTC${w.shots ? ", screenshotting every new post" : ""}`;
+ if (w.paused) return `Watched ${every} — PAUSED since ${hhmm(Date.parse(w.paused.since))} UTC: ${w.paused.sentence}`;
+ const next = w.nextTickAt ? Date.parse(w.nextTickAt) : now;
+ return `Watched ${every}; ${w.ticks} tick${w.ticks === 1 ? "" : "s"} so far, next ${next <= now ? "at the next scan" : `at ${hhmm(next)} UTC`}.`;
+}
diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts
@@ -237,9 +237,11 @@ export type PostAvailabilityInput = {
// channel's `posts-media/`, one directory per post id beneath it
// (postCapture.ts owns the layout).
// How one post's media download went (X). A failure may still name the files
-// it did land (`files`), say the post is merely OWED the rest (`owed`: over a
-// cap, past the job's budget — not an error of the post), and may stop the
-// whole run with a sentence (`stop`: a rate limit, a spent budget).
+// it did land (`files`), say the post is merely OWED the rest — not an error
+// of the post — and until when (`owed`: "next" = a later capture asks again,
+// the job's budget or X's cooldown having stopped this one; "kept" = only once
+// the post is marked keep, a file being over the cap), and may stop the whole
+// run with a sentence (`stop`: a rate limit).
export type PostMediaDownload =
| { ok: true; files: { name: string; url?: string }[] }
| {
@@ -247,7 +249,7 @@ export type PostMediaDownload =
error: string;
needsCookies?: boolean;
files?: { name: string; url?: string }[];
- owed?: boolean;
+ owed?: "next" | "kept";
stop?: string;
};
diff --git a/common/social/postCapture.ts b/common/social/postCapture.ts
@@ -229,6 +229,10 @@ export type PostCaptureRecord = {
trimmed?: boolean;
mediaState: CaptureMediaState;
media: CapturedFile[];
+ // The media half is not settled because the post is OWED the rest, not
+ // because it failed (an X trending library): "next" = a later capture asks
+ // again; "kept" = only once the post is marked keep.
+ mediaOwed?: "next" | "kept";
// 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.
diff --git a/common/social/xPostCapture.test.ts b/common/social/xPostCapture.test.ts
@@ -420,9 +420,9 @@ test("run: a post owed the rest of its media is not a failure, keeps the files t
const h = harness({});
h.deps.downloadMedia = async ({ id, dir }) => {
h.downloads.push(id);
- if (id === "4") return { ok: false, owed: true, error: "X's media CDN answered 429", stop: "X's media CDN answered 429 (rate limit)." };
+ if (id === "4") return { ok: false, owed: "next", error: "X's media CDN answered 429", stop: "X's media CDN answered 429 (rate limit)." };
await writeFile(path.join(dir, `${id}_1.jpg`), `media of ${id}`);
- return { ok: false, owed: true, error: `${id}_2.mp4: over the cap: owed until the post is kept`, files: [{ name: `${id}_1.jpg` }] };
+ return { ok: false, owed: "kept", error: `${id}_2.mp4: over the cap: owed until the post is kept`, files: [{ name: `${id}_1.jpg` }] };
};
const inp = await input(["1", "2", "3", "4", "5"], { shots: false });
const res = await captureXPosts(inp, h.deps);
@@ -432,6 +432,8 @@ test("run: a post owed the rest of its media is not a failure, keeps the files t
assert.deepEqual(h.downloads, ["1", "2", "3", "4"]);
const record = await readPostCapture(path.join(inp.outDir, "1"));
assert.equal(record?.mediaState, "error");
+ assert.equal(record?.mediaOwed, "kept");
+ assert.equal((await readPostCapture(path.join(inp.outDir, "4")))?.mediaOwed, "next");
assert.deepEqual(record?.media.map((m) => m.name), ["1_1.jpg"]);
assert.match(record?.error ?? "", /owed until the post is kept/);
// Owed again by the next run.
diff --git a/common/social/xPostCapture.ts b/common/social/xPostCapture.ts
@@ -510,6 +510,7 @@ export async function captureXPosts(
let mediaState: CaptureMediaState = work.media ? "skipped" : (existing?.mediaState ?? "skipped");
let media: CapturedFile[] = work.media ? [] : (existing?.media ?? []);
let needsCookies = false;
+ let mediaOwed: PostCaptureRecord["mediaOwed"] = work.media ? undefined : existing?.mediaOwed;
// Only a post that rendered (or was not shot this run) is worth a
// download: X has nothing to give for a deleted or walled one.
const postIsThere = state === undefined || state === "captured";
@@ -532,6 +533,7 @@ export async function captureXPosts(
// A post merely owed the rest of its media (a cap, the job's
// budget) did not fail.
state ??= got.owed ? "captured" : "error";
+ mediaOwed = got.owed;
if (got.stop) stop = got.stop;
if (got.needsCookies) {
needsCookies = true;
@@ -579,6 +581,7 @@ export async function captureXPosts(
...(shot ? { shot } : {}),
mediaState,
media,
+ ...(mediaOwed && mediaState === "error" ? { mediaOwed } : {}),
...(article ? { article } : {}),
...(thread ? { thread } : {}),
...(threadNone && !thread ? { threadNone } : {}),
diff --git a/common/social/xTrendingMedia.test.ts b/common/social/xTrendingMedia.test.ts
@@ -168,7 +168,7 @@ test("X's cooldown holds the media: nothing is asked while it runs", async () =>
assert.equal(res.ok, false);
if (res.ok) return;
assert.match(res.stop ?? "", /no media fetch starts before 10:09 UTC \(9 min from now\)/);
- assert.equal(res.owed, true);
+ assert.equal(res.owed, "next");
assert.deepEqual(h.asked, []);
});
@@ -184,15 +184,22 @@ test("a file over the cap is owed, by its declared size or mid-stream; a kept po
const res = await watch(h.args("731"), h.noLogin);
assert.equal(res.ok, false);
if (res.ok) return;
- assert.equal(res.owed, true);
+ assert.equal(res.owed, "kept");
assert.match(res.error, /731_1\.mp4: it is .*over the 1 MB cap: owed until the post is kept; 731_2\.mp4: it is over the 1 MB cap: owed until the post is kept/);
assert.deepEqual(res.files, [{ name: "731_3.jpg", url: img("Small").url }]);
assert.deepEqual(readdirSync(h.dirOf("731")), ["731_3.jpg"]);
+ // Found over the cap once: the next capture under the same cap does not ask for them again.
+ h.asked.length = 0;
+ const next = await watch(h.args("731"), h.noLogin);
+ assert.equal(next.ok, false);
+ assert.deepEqual(h.asked, []);
+ assert.equal(Object.keys((await readXTrendingMediaIndex(h.root)).oversize).length, 2);
// Kept: no cap, so the same files come down.
const kept = createLibraryMediaDownloader({ channelRoot: h.root, sources, maxVideoBytes: null, fallback: "login", deps: h.deps });
const again = await kept(h.args("731"), h.noLogin);
assert.equal(again.ok, true);
assert.equal(readFileSync(path.join(h.dirOf("731"), "731_2.mp4"), "utf8"), "0123456789ABCDEF");
+ assert.deepEqual((await readXTrendingMediaIndex(h.root)).oversize, {});
});
test("a job's budget: past it the rest is owed and nothing more is asked", async () => {
@@ -213,7 +220,7 @@ test("a job's budget: past it the rest is owed and nothing more is asked", async
const res = await download(h.args("742"), h.noLogin);
assert.equal(res.ok, false);
if (res.ok) return;
- assert.equal(res.owed, true);
+ assert.equal(res.owed, "next");
assert.equal(res.stop, undefined);
assert.match(res.error, /742_1\.jpg: owed \(this job's media budget of 2 files/);
// What the library already holds is still linked, budget or not.
@@ -230,7 +237,7 @@ test("the logged-in download is the fallback for a kept post only, and what it l
const owed = await watch(h.args("751"), h.noLogin);
assert.equal(owed.ok, false);
if (owed.ok) return;
- assert.equal(owed.owed, true);
+ assert.equal(owed.owed, "kept");
assert.match(owed.error, /1 of its 2 media file\(s\) have no CDN address in the saved capture: owed until the post is kept/);
// Kept: the fetcher's own download runs once, and its file joins the store.
let logins = 0;
diff --git a/common/social/xTrendingMedia.ts b/common/social/xTrendingMedia.ts
@@ -45,6 +45,7 @@ import path from "node:path";
import { once } from "node:events";
import {
adoptXTrendingMedia,
+ noteXTrendingOversize,
linkXTrendingMedia,
readXTrendingMediaIndex,
xTrendingBlobByUrl,
@@ -107,7 +108,10 @@ export type LibraryMediaOptions = {
const mb = (bytes: number) => `${Math.max(1, Math.round(bytes / (1024 * 1024)))} MB`;
const firstLine = (err: unknown) => ((err as Error)?.message ?? String(err)).split("\n")[0];
-type Fetched = { ok: true; bytes: number } | { ok: false; why: string; owed?: boolean; rateLimited?: boolean };
+const overCapWhy = (bytes: number, cap: number) =>
+ `it is ${bytes > cap + 1 ? `${mb(bytes)}, ` : ""}over the ${mb(cap)} cap: owed until the post is kept`;
+
+type Fetched = { ok: true; bytes: number } | { ok: false; why: string; oversize?: number; rateLimited?: boolean };
// One file, streamed to `<name>.part` and renamed when whole.
async function fetchOne(o: {
@@ -122,7 +126,7 @@ async function fetchOne(o: {
const over = (bytes: number): Fetched =>
o.capIsHard
? { ok: false, why: `it is larger than ${mb(o.cap)}, more than is ever kept` }
- : { ok: false, owed: true, why: `it is ${bytes > 0 ? `${mb(bytes)}, ` : ""}over the ${mb(o.cap)} cap: owed until the post is kept` };
+ : { ok: false, oversize: bytes > 0 ? bytes : o.cap + 1, why: overCapWhy(bytes, o.cap) };
const deadline = AbortSignal.any([o.signal, AbortSignal.timeout(LIBRARY_MEDIA_FILE_TIMEOUT_MS)]);
let res: Awaited<ReturnType<MediaFetch>>;
try {
@@ -193,13 +197,16 @@ export function createLibraryMediaDownloader(
const cooling = await deps.cooldownMs().catch(() => 0);
if (cooling > 0) {
const why = xRateLimitHoldSentence("media fetch", cooling, now());
- return { ok: false, owed: true, error: why, stop: why };
+ return { ok: false, owed: "next", error: why, stop: why };
}
const sources = o.sources.get(id) ?? [];
const expected = o.expected?.get(id) ?? sources.length;
const files: { name: string; url?: string }[] = [];
const problems: string[] = [];
- let owed = false;
+ // Owed to a later capture (the budget, the cooldown), or until the post
+ // is kept (a file over the cap, a file the capture names no address for).
+ let owedNext = false;
+ let owedKept = false;
let failed = false;
let stop: string | undefined;
await mkdir(dir, { recursive: true });
@@ -224,14 +231,22 @@ export function createLibraryMediaDownloader(
continue;
}
// An address the library has seen: linked from the store, nothing asked.
- const known = xTrendingBlobByUrl(await readXTrendingMediaIndex(o.channelRoot), source.url);
+ const index = await readXTrendingMediaIndex(o.channelRoot);
+ const known = xTrendingBlobByUrl(index, source.url);
if (known && (await linkXTrendingMedia(o.channelRoot, { postId: id, name, sha256: known, url: source.url }))) {
log(`${id}: ${name} is already in the library (same address): linked, not fetched.`);
files.push({ name, url: source.url });
continue;
}
+ // Found over the cap before: not asked for again while the cap stands.
+ const big = index.oversize[source.url];
+ if (!capIsHard && big && big.bytes > cap) {
+ owedKept = true;
+ problems.push(`${name}: ${overCapWhy(big.bytes, cap)}`);
+ continue;
+ }
if (budget.files >= maxFiles || budget.bytes >= maxBytes) {
- owed = true;
+ owedNext = true;
problems.push(`${name}: owed (this job's media budget of ${maxFiles} files / ${mb(maxBytes)} is used)`);
if (!saidSpent) {
saidSpent = true;
@@ -255,15 +270,17 @@ export function createLibraryMediaDownloader(
`X's media CDN answered 429 (rate limit) for ${name}: the capture stopped at once and asked nothing more. ` +
`Nothing X starts before ${new Date(until).toISOString().slice(11, 16)} UTC; nothing retries by itself.`;
problems.push(`${name}: ${got.why}`);
- owed = true;
+ owedNext = true;
break;
}
problems.push(`${name}: ${got.why}`);
- if (got.owed) owed = true;
- else failed = true;
+ if (got.oversize) {
+ owedKept = true;
+ await noteXTrendingOversize(o.channelRoot, { url: source.url, bytes: got.oversize, now });
+ } else failed = true;
}
if (signal.aborted && !stop) {
- return { ok: false, owed: true, error: "cancelled", files };
+ return { ok: false, owed: "next", error: "cancelled", files };
}
if (sources.length < expected && !stop) {
problems.push(
@@ -271,7 +288,7 @@ export function createLibraryMediaDownloader(
(o.fallback === "login" ? "" : ": owed until the post is kept"),
);
if (o.fallback === "login") failed = true;
- else owed = true;
+ else owedKept = true;
}
// A kept post the CDN could not serve whole: the fetcher's own logged-in
// download, once, and what it lands is taken into the store.
@@ -289,7 +306,7 @@ export function createLibraryMediaDownloader(
ok: false,
error: problems.join("; "),
files,
- ...(owed && !failed ? { owed: true } : {}),
+ ...(failed ? {} : owedNext ? { owed: "next" as const } : owedKept ? { owed: "kept" as const } : {}),
...(stop ? { stop } : {}),
};
};
diff --git a/editor/app/api/ops/_xTrendingWatch.ts b/editor/app/api/ops/_xTrendingWatch.ts
@@ -0,0 +1,39 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import { READ_X_TRENDING_KIND, REPARSE_X_TRENDING_KIND } from "yt-dlp-transcript-common/lib/xTrending/config";
+import { armXTrendingWatch, type WatchScanDeps } from "yt-dlp-transcript-common/controller/xTrendingWatch";
+import { readXTrendingAction } from "../../channels/[slug]/xTrendingActions";
+
+// THE WATCH'S EDITOR SIDE (lane x-trending-2): what the scan
+// (common/controller/xTrendingWatch.ts) runs on in this editor — its job
+// registry and its own read action, so a tick is exactly the job a person
+// starts — shared by `watch-trending {"tick": true}` and the timer
+// instrumentation.ts arms.
+export function xTrendingWatchDeps(): WatchScanDeps {
+ return {
+ paths: getPaths(),
+ log: (line) => console.log(line),
+ // A read or a capture of the library waiting its turn, or running.
+ busy: (slug) =>
+ getRegistry()
+ .list()
+ .some(
+ (j) =>
+ j.channelSlug === slug &&
+ (j.kind === READ_X_TRENDING_KIND || j.kind === REPARSE_X_TRENDING_KIND || j.kind === "capture-posts") &&
+ (j.status === "queued" || j.status === "running"),
+ ),
+ enqueue: async (tick) => {
+ const started = await readXTrendingAction({ slug: tick.slug, url: tick.url, topic: tick.topic });
+ if (!started.ok) return { ok: false, error: started.error };
+ void started.stream.cancel();
+ return { ok: true, jobId: started.jobId };
+ },
+ };
+}
+
+// Armed once per process, below the idle gate (armXTrendingWatch refuses an
+// idle boot itself too).
+export function armXTrendingWatchLane(): boolean {
+ return armXTrendingWatch(xTrendingWatchDeps());
+}
diff --git a/editor/app/api/ops/read-x-trending/route.test.ts b/editor/app/api/ops/read-x-trending/route.test.ts
@@ -145,6 +145,7 @@ test("get trending lists topics and posts — words, author, media, reads, topic
media: { count: 2, kinds: ["image"] },
topic: "kettles",
reads: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z" }],
+ thread: "1900000000000001001",
});
assert.equal(all.json.total, 2);
assert.deepEqual(all.json.reads, [READ]);
diff --git a/editor/app/api/ops/trending/route.ts b/editor/app/api/ops/trending/route.ts
@@ -10,10 +10,11 @@ export const dynamic = "force-dynamic";
// GET /api/ops/trending?slug=<library>[&topic=<topicId>][&limit=<n>]
// -> { ok, slug, name, topics: [{id, title, posts, sources: [{trendId, url,
-// title?, summary?, reads, lastReadAt}]}],
+// title?, summary?, reads, lastReadAt}], watch?}],
// posts: [{id, author, authorName?, createdAt, url, text,
// media: {count, kinds, thumbnail?}, topic,
-// reads: [{read, trendId, at}], thread, judgement?}],
+// reads: [{read, trendId, at}], gone?, capture?, thread,
+// judgement?}],
// total, reads: [<readId>, …] }
//
// An X trending library's topics and posts (lane x-trending) — `pnpm ops get
@@ -30,7 +31,15 @@ export const dynamic = "force-dynamic";
// the root post id of the thread it belongs to; `judgement` ({state: keep |
// drop | later, note?, by: agent | operator, at, from?}) is its own, else its
// thread's (`from: "thread"`), written by `judge-trending`; a post with none
-// is undecided. NEVER the raw capture, a cookie or a token.
+// is undecided. `gone` ({at, read, trendId}) says a page that showed the post
+// before did not show it at `at`, a read that reached the page's end: gone
+// FROM THE PAGE, which is not deleted. `capture` ({at, state, shot, files,
+// mediaState, mediaOwed?}) is what its capture holds; `mediaOwed` "next" is
+// asked for again by a later capture, "kept" once the post is marked keep.
+// A topic's `watch` ({on, intervalMinutes, until, shots, lastTickAt?,
+// nextTickAt?, ticks, paused?: {reason, since, sentence}, ended?, sentence}) is
+// there once it has been watched (`watch-trending`); `sentence` says what it
+// is doing. NEVER the raw capture, a cookie or a token.
export async function GET(request: Request) {
const denied = opsAuth(request);
if (denied) return denied;
diff --git a/editor/app/api/ops/watch-trending/route.test.ts b/editor/app/api/ops/watch-trending/route.test.ts
@@ -0,0 +1,117 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/watch-trending/route.test.ts"
+//
+// watch-trending over ops (lane x-trending-2), against a temp corpus with no
+// connected X profile: the switch, the library's settings, the listing's
+// watch, and ONE SCAN that — there being no profile — pauses the watch
+// instead of starting a read. No browser opens and nothing is asked of X.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-trending-watch-route-"));
+process.env.WORKER_TOKEN = "test-token";
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+
+const READ = "tr-01JA0000000000000000000000";
+const TREND = "https://x.com/i/trending/1900000000000000001";
+
+async function channel(slug: string, config: Record<string, unknown>): Promise<string> {
+ const dir = path.join(ROOT, "channels", slug);
+ await mkdir(path.join(dir, "trending", "posts"), { recursive: true });
+ await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config }));
+ return dir;
+}
+
+const lib = await channel("trending", { sourceKind: "social", platform: "twitter", xTrending: { maxPosts: 30 } });
+await channel("account-x", { sourceKind: "social", platform: "twitter", postFetcher: "x-gallery-dl", socialHandle: "example", url: "https://x.com/example" });
+await writeFile(
+ path.join(lib, "trending", "topics.json"),
+ JSON.stringify({
+ version: 1,
+ topics: [
+ { id: "kettles", title: "Kettles", createdAt: "2026-11-17T10:00:00.000Z", sources: [{ trendId: "1900000000000000001", url: TREND, reads: [{ id: READ, at: "2026-11-17T10:00:00.000Z", posts: 2, added: 2 }] }] },
+ { id: "empty", title: "Empty", createdAt: "2026-11-17T10:00:00.000Z", sources: [] },
+ ],
+ }),
+);
+
+const watch = (await import("./route")).POST;
+const listing = (await import("../trending/route")).GET;
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+async function call(body: Record<string, unknown>) {
+ const res = await watch(
+ new Request("http://localhost/api/ops/watch-trending", {
+ method: "POST",
+ headers: { authorization: "Bearer test-token", "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+ return { status: res.status, json: (await res.json()) as Record<string, unknown> };
+}
+
+const topics = async () => {
+ const res = await listing(new Request("http://localhost/api/ops/trending?slug=trending", { headers: { authorization: "Bearer test-token" } }));
+ return ((await res.json()) as { topics: Array<{ id: string; watch?: Record<string, unknown> }> }).topics;
+};
+
+test("watch-trending refuses with a sentence", async () => {
+ for (const [body, re] of [
+ [{ slug: "nope", topic: "kettles", on: true }, /No such channel: nope/],
+ [{ slug: "account-x", topic: "kettles", on: true }, /not an X trending library/],
+ [{ slug: "trending" }, /Give "topic" with "on".*one of them/],
+ [{ slug: "trending", topic: "kettles", on: true, tick: true }, /one of them/],
+ [{ slug: "trending", topic: "kettles" }, /"on" is true \(watch the topic\) or false/],
+ [{ slug: "trending", topic: "spouts", on: true }, /no topic "spouts" \(its topics: kettles, empty\)/],
+ [{ slug: "trending", topic: "empty", on: true }, /holds no trending page to watch/],
+ [{ slug: "trending", topic: "kettles", on: true, intervalMinutes: 5 }, /"intervalMinutes" is a whole number, 15–1440/],
+ [{ slug: "trending", topic: "kettles", on: true, hours: 1000 }, /"hours" is a whole number, 1–168/],
+ [{ slug: "trending", topic: "kettles", on: false }, /is not being watched/],
+ [{ slug: "trending", settings: { maxVideoMb: 0 } }, /"maxVideoMb" is a whole number, 1–2000/],
+ [{ slug: "trending", settings: { colour: 1 } }, /unknown setting\(s\): colour/],
+ [{ slug: "trending", settings: {} }, /names nothing to change/],
+ [{ slug: "trending", topic: "kettles", on: true, force: true }, /unknown key\(s\): force/],
+ ] as const) {
+ const r = await call(body);
+ assert.equal(r.status, 400, JSON.stringify(body));
+ assert.match(String(r.json.error), re, JSON.stringify(body));
+ }
+});
+
+test("the library's settings are written into config.xTrending, the marker and its other keys kept", async () => {
+ const r = await call({ slug: "trending", settings: { maxVideoMb: 50, intervalMinutes: 20, hours: 6, maxTopics: 1 } });
+ assert.equal(r.status, 200);
+ const config = JSON.parse(await readFile(path.join(lib, "config.json"), "utf8"));
+ assert.deepEqual(config.xTrending, { maxPosts: 30, maxVideoMb: 50, watchIntervalMinutes: 20, watchHours: 6, watchMaxTopics: 1 });
+ assert.equal(config.platform, "twitter");
+});
+
+test("a topic is watched on the library's terms; the listing shows it; a scan with no connected profile pauses it and starts nothing", async () => {
+ const on = await call({ slug: "trending", topic: "Kettles", on: true, shots: true });
+ assert.equal(on.status, 200, JSON.stringify(on.json));
+ assert.equal(on.json.topic, "kettles");
+ const w = on.json.watch as { on: boolean; intervalMinutes: number; shots: boolean; until: string; startedAt: string };
+ assert.deepEqual([w.on, w.intervalMinutes, w.shots], [true, 20, true]);
+ assert.equal(Date.parse(w.until) - Date.parse(w.startedAt), 6 * 3_600_000);
+ assert.match(String(on.json.sentence), /^Watched every 20 min until .* UTC, screenshotting every new post; 0 ticks so far/);
+ assert.equal((await topics()).find((t) => t.id === "kettles")?.watch?.on, true);
+ assert.equal((await topics()).find((t) => t.id === "empty")?.watch, undefined);
+
+ const tick = await call({ slug: "trending", tick: true });
+ assert.equal(tick.status, 200, JSON.stringify(tick.json));
+ const scan = tick.json.scan as { live: number; enqueued?: unknown; paused: Array<{ topic: string; reason: string }> };
+ assert.equal(scan.enqueued, undefined);
+ assert.deepEqual(scan.paused, [{ slug: "trending", topic: "kettles", reason: "no-profile" }]);
+ const paused = (await topics()).find((t) => t.id === "kettles")?.watch as { paused?: { reason: string }; sentence: string };
+ assert.equal(paused.paused?.reason, "no-profile");
+ assert.match(paused.sentence, /PAUSED since .* UTC: There is no connected X profile/);
+
+ const off = await call({ slug: "trending", topic: "kettles", on: false, by: "operator" });
+ assert.equal(off.status, 200);
+ assert.equal(off.json.sentence, 'The watch of "Kettles" was switched off.');
+});
diff --git a/editor/app/api/ops/watch-trending/route.ts b/editor/app/api/ops/watch-trending/route.ts
@@ -0,0 +1,71 @@
+import { NextResponse } from "next/server";
+import { watchXTrendingAction, type WatchSettingsAsk } from "../../../channels/[slug]/xTrendingActions";
+import { ops, opsFail, optBool, optString, reqSlug } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, topic, on, intervalMinutes?, hours?, shots?, by? }
+// -> { ok: true, slug, topic, watch, sentence }
+// POST { slug, settings: {maxVideoMb?, intervalMinutes?, hours?, maxTopics?} }
+// -> { ok: true, slug, settings, sentence }
+// POST { slug, tick: true }
+// -> { ok: true, slug, scan, sentence }
+//
+// WATCH A TOPIC OF AN X TRENDING LIBRARY (lane x-trending-2). While a topic
+// is watched, its trending page is read again every `intervalMinutes`
+// (15–1440; default the library's, else 30) until `hours` from now (1–168;
+// else 48), each tick the SAME single `read-x-trending` job on X's queue,
+// started by the editor's own scan (once a minute; at most one read per scan;
+// none while a read or capture of the library waits its turn). A topic of
+// several trending pages reads one page per tick, in turn. At most
+// `maxTopics` topics of a library are watched at once (default 4).
+//
+// on true watches the topic (again: its terms change, its history
+// stays); false stops (the watch ends "switched off")
+// shots also screenshot every new post. Default: a new post's MEDIA only,
+// fetched at once from X's media CDN with no page opened
+// by "agent" (default) or "operator"
+//
+// A WATCH RUNS ONLY WHILE X'S COOKIE JAR IS UNDER ITS LIMIT (60 minutes). The
+// editor never refreshes the jar by itself, so a watch PAUSES when the jar
+// goes stale — X's jar-age alert goes up and /review lists the paused watches
+// — and resumes at the first scan after Refresh cookies on /cookies. It does
+// not cover a night nobody presses Refresh in. The X alert, X cooling down
+// after a rate limit and a missing profile pause it the same way.
+//
+// A post a page showed before and does not show at a read that reached the
+// page's end is recorded "gone from the page at <time>" (`get trending`:
+// `gone`) — never "deleted": a trending page is a ranked list. A trending
+// page X no longer has is not read again, and the watch ends with a sentence
+// when it was the topic's last.
+//
+// `settings` changes the library's own defaults (config.xTrending):
+// maxVideoMb (1–2000; the largest media file fetched for a post nobody has
+// kept), intervalMinutes, hours, maxTopics (1–12). `tick: true` runs one scan
+// now, as the timer does.
+//
+// Refused with a sentence: no such channel, not a library, not exactly one of
+// topic / settings / tick, no such topic, a topic with no trending page, the
+// library's limit, an interval or length out of range, a topic not watched
+// (off).
+export async function POST(request: Request) {
+ return ops(request, ["slug", "topic", "on", "intervalMinutes", "hours", "shots", "by", "settings", "tick"], async (body) => {
+ const topic = optString(body, "topic");
+ const on = optBool(body, "on");
+ const shots = optBool(body, "shots");
+ const tick = optBool(body, "tick");
+ const result = await watchXTrendingAction({
+ slug: reqSlug(body, "slug"),
+ ...(tick ? { tick: true } : {}),
+ ...(body.settings !== undefined ? { settings: body.settings as WatchSettingsAsk } : {}),
+ ...(topic !== undefined ? { topic } : {}),
+ ...(on !== undefined ? { on } : {}),
+ ...(body.intervalMinutes !== undefined ? { intervalMinutes: body.intervalMinutes } : {}),
+ ...(body.hours !== undefined ? { hours: body.hours } : {}),
+ ...(shots !== undefined ? { shots } : {}),
+ ...(body.by !== undefined ? { by: body.by } : {}),
+ });
+ if (!result.ok) return opsFail(result.error);
+ return NextResponse.json(result);
+ });
+}
diff --git a/editor/app/channels/[slug]/components/XTrendingPanel.tsx b/editor/app/channels/[slug]/components/XTrendingPanel.tsx
@@ -1,20 +1,177 @@
"use client";
-import { useState } from "react";
+import { useState, useTransition } from "react";
+import { useRouter } from "next/navigation";
import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
import {
X_TRENDING_MAX_POSTS,
X_TRENDING_MAX_SCROLLS,
} from "yt-dlp-transcript-common/lib/xTrending/config";
-import type { XTrendingListing } from "yt-dlp-transcript-common/lib/xTrending/store";
+import {
+ X_TRENDING_WATCH_MAX_HOURS,
+ X_TRENDING_WATCH_MAX_INTERVAL_MINUTES,
+ X_TRENDING_WATCH_MIN_INTERVAL_MINUTES,
+} from "yt-dlp-transcript-common/lib/xTrending/config";
+import type {
+ XTrendingListing,
+ XTrendingPostRow,
+ XTrendingTopicRow,
+} from "yt-dlp-transcript-common/lib/xTrending/store";
import { cancelJobAction } from "../../../jobs/actions";
-import { readXTrendingAction } from "../xTrendingActions";
+import { judgeXTrendingAction, readXTrendingAction, watchXTrendingAction } from "../xTrendingActions";
+
+const when = (iso: string) => iso.slice(0, 16).replace("T", " ");
+
+// THE WATCH OF ONE TOPIC (lane x-trending-2): the switch, its interval and
+// length, and "screenshot everything new" — `pnpm ops watch-trending`.
+// A field left empty takes the library's default (30 min, 48 h unless its
+// settings say otherwise).
+function TopicWatch({ slug, topic }: { slug: string; topic: XTrendingTopicRow }) {
+ const router = useRouter();
+ const [pending, start] = useTransition();
+ const live = !!topic.watch && topic.watch.on && !topic.watch.ended;
+ const [every, setEvery] = useState(live && topic.watch ? String(topic.watch.intervalMinutes) : "");
+ const [hours, setHours] = useState("");
+ const [shots, setShots] = useState(topic.watch?.shots ?? false);
+ const [said, setSaid] = useState<string | null>(null);
+ const input = "rounded border border-border bg-card px-2 py-1 text-xs";
+ const set = (on: boolean) =>
+ start(async () => {
+ const r = await watchXTrendingAction({
+ slug,
+ topic: topic.id,
+ on,
+ by: "operator",
+ ...(on
+ ? {
+ ...(every.trim() ? { intervalMinutes: Number(every) } : {}),
+ ...(hours.trim() ? { hours: Number(hours) } : {}),
+ shots,
+ }
+ : {}),
+ });
+ setSaid(r.ok ? r.sentence : r.error);
+ router.refresh();
+ });
+ return (
+ <div data-x-trending-watch={topic.id} className="flex flex-col gap-1 text-xs">
+ <div className="flex flex-wrap items-end gap-2">
+ <label className="flex flex-col gap-0.5">
+ <span className="font-medium">Every (min)</span>
+ <input
+ type="number"
+ min={X_TRENDING_WATCH_MIN_INTERVAL_MINUTES}
+ max={X_TRENDING_WATCH_MAX_INTERVAL_MINUTES}
+ value={every}
+ placeholder="30"
+ onChange={(e) => setEvery(e.target.value)}
+ aria-label={`watch interval of ${topic.title}`}
+ className={`${input} w-20`}
+ />
+ </label>
+ <label className="flex flex-col gap-0.5">
+ <span className="font-medium">For (hours)</span>
+ <input
+ type="number"
+ min={1}
+ max={X_TRENDING_WATCH_MAX_HOURS}
+ value={hours}
+ placeholder="48"
+ onChange={(e) => setHours(e.target.value)}
+ aria-label={`watch length of ${topic.title}`}
+ className={`${input} w-20`}
+ />
+ </label>
+ <label className="flex items-center gap-1" title="Also take a screenshot of every new post (a page load each); otherwise only their media is fetched">
+ <input type="checkbox" checked={shots} onChange={(e) => setShots(e.target.checked)} aria-label={`screenshot everything new in ${topic.title}`} />
+ Screenshot everything new
+ </label>
+ <button type="button" disabled={pending} onClick={() => set(true)} className="rounded border border-border px-2 py-1 font-medium disabled:opacity-50">
+ {live ? "Change watch" : "Watch"}
+ </button>
+ {live && (
+ <button type="button" disabled={pending} onClick={() => set(false)} className="rounded border border-border px-2 py-1 disabled:opacity-50">
+ Stop watching
+ </button>
+ )}
+ </div>
+ <span data-x-trending-watch-state="" className={topic.watch?.paused ? "text-amber-700 dark:text-amber-400" : "text-muted-foreground"}>
+ {said ?? topic.watch?.sentence ?? "Not watched."}
+ </span>
+ <span className="text-muted-foreground">
+ A watch runs only while X's cookie jar is under its limit (60 min): it pauses when the jar goes stale and resumes after Refresh cookies on /cookies, so it does not cover a night nobody refreshes in.
+ </span>
+ </div>
+ );
+}
+
+const STATES = [
+ ["keep", "Keep"],
+ ["drop", "Drop"],
+ ["later", "Later"],
+] as const;
+
+// ONE POST'S JUDGEMENT (lane x-trending-2): keep / drop / later, or cleared —
+// `pnpm ops judge-trending`, by the operator. Keep archives the post.
+function PostJudge({ slug, post }: { slug: string; post: XTrendingPostRow }) {
+ const router = useRouter();
+ const [pending, start] = useTransition();
+ const [said, setSaid] = useState<string | null>(null);
+ const own = post.judgement && !post.judgement.from ? post.judgement.state : undefined;
+ const judge = (state: "keep" | "drop" | "later" | "undecided") =>
+ start(async () => {
+ const r = await judgeXTrendingAction({ slug, by: "operator", set: [{ id: post.id, state }] });
+ setSaid(
+ !r.ok
+ ? r.error
+ : r.archive && "error" in r.archive
+ ? `Kept. Not archived yet: ${r.archive.error}`
+ : r.archive
+ ? `Kept; archiving as job ${r.archive.jobId}.`
+ : null,
+ );
+ router.refresh();
+ });
+ return (
+ <span className="flex flex-wrap items-center gap-1 text-xs">
+ {STATES.map(([state, label]) => (
+ <button
+ key={state}
+ type="button"
+ disabled={pending}
+ aria-pressed={own === state}
+ aria-label={`${label} ${post.id}`}
+ onClick={() => judge(state)}
+ className={`rounded border px-2 py-0.5 disabled:opacity-50 ${own === state ? "border-foreground font-semibold" : "border-border"}`}
+ >
+ {label}
+ </button>
+ ))}
+ {own && (
+ <button type="button" disabled={pending} aria-label={`Clear ${post.id}`} onClick={() => judge("undecided")} className="rounded border border-border px-2 py-0.5 disabled:opacity-50">
+ Clear
+ </button>
+ )}
+ {post.judgement && (
+ <span data-x-trending-judgement={post.judgement.state} className="text-muted-foreground">
+ {post.judgement.state} by {post.judgement.by}
+ {post.judgement.from ? " (its thread)" : ""}
+ {post.judgement.note ? `: ${post.judgement.note}` : ""}
+ </span>
+ )}
+ {said && <span className="text-muted-foreground">{said}</span>}
+ </span>
+ );
+}
// An X trending library's page (lane x-trending, slice 1): read a trending
// page into it (`read-x-trending`, one job on X's queue), parse a saved read
// again, and the library by topic — each post's author, words, media by kind
// and when it was read. Listing only: archiving a post and judging it are
// later slices. Everything here is `pnpm ops read-x-trending` / `get trending`.
+// Lane x-trending-2 adds, per topic, its watch (`watch-trending`), and per
+// post its judgement (`judge-trending`), what its capture holds and whether a
+// page stopped showing it.
export function XTrendingPanel({
slug,
listing,
@@ -168,6 +325,7 @@ export function XTrendingPanel({
</li>
))}
</ul>
+ {t.sources.length > 0 && <TopicWatch slug={slug} topic={t} />}
<ol className="flex flex-col divide-y divide-border">
{byTopic(t.id).map((p) => (
<li key={p.id} data-x-trending-post={p.id} className="flex flex-col gap-1 py-2 text-sm">
@@ -180,8 +338,18 @@ export function XTrendingPanel({
? ` · ${p.media.count} media${p.media.kinds.length ? ` (${p.media.kinds.join(", ")})` : ""}`
: ""}
{p.reads.length > 1 ? ` · on ${p.reads.length} reads` : ""}
+ {p.capture
+ ? ` · captured${p.capture.shot ? " (shot)" : ""}, ${p.capture.files} file${p.capture.files === 1 ? "" : "s"}` +
+ (p.capture.mediaOwed === "kept" ? ", more owed once kept" : p.capture.mediaOwed === "next" ? ", more owed to the next capture" : "")
+ : ""}
</span>
+ {p.gone && (
+ <span data-x-trending-gone="" className="text-xs text-amber-700 dark:text-amber-400">
+ Gone from the page at {when(p.gone.at)} UTC.
+ </span>
+ )}
<span className="whitespace-pre-wrap">{p.text}</span>
+ <PostJudge slug={slug} post={p} />
</li>
))}
</ol>
diff --git a/editor/app/channels/[slug]/xTrendingActions.ts b/editor/app/channels/[slug]/xTrendingActions.ts
@@ -29,10 +29,34 @@ import {
runXTrendingRead,
X_TRENDING_QUEUE,
type ReadXTrendingAsk,
+ type ReadXTrendingResult,
} from "yt-dlp-transcript-common/controller/readXTrending";
+import {
+ noteXTrendingWatchRead,
+ scanXTrendingWatches,
+ xTrendingWatchFollowUp,
+ xTrendingWatchTick,
+ type WatchScanResult,
+} from "yt-dlp-transcript-common/controller/xTrendingWatch";
+import {
+ describeXTrendingWatch,
+ setXTrendingWatch,
+ type XTrendingWatch,
+} from "yt-dlp-transcript-common/lib/xTrending/watch";
+import {
+ X_TRENDING_MAX_VIDEO_MB,
+ X_TRENDING_WATCH_MAX_HOURS,
+ X_TRENDING_WATCH_MAX_INTERVAL_MINUTES,
+ X_TRENDING_WATCH_MAX_TOPICS,
+ X_TRENDING_WATCH_MIN_INTERVAL_MINUTES,
+ xTrendingWatchMaxTopics,
+ xTrendingWatchTerms,
+ type XTrendingConfig,
+} from "yt-dlp-transcript-common/lib/xTrending/config";
+
import { fakeXProfileChromium } from "yt-dlp-transcript-common/social/fakeXProfileBrowser";
import path from "node:path";
-import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
+import { isValidChannelSlug, patchChannelConfig, readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
import { isXTrendingChannel, NOT_AN_X_TRENDING_LIBRARY } from "yt-dlp-transcript-common/lib/xTrending/config";
import {
judgeXTrending,
@@ -80,21 +104,55 @@ export async function readXTrendingAction(ask: ReadXTrendingAsk): Promise<Stream
queueKey: X_TRENDING_QUEUE,
paths,
channelSlug: plan.slug,
- fn: async (onLog, signal) =>
- done(
+ fn: async (onLog, signal) => {
+ const result = await runXTrendingRead({
+ paths,
+ plan,
onLog,
- await runXTrendingRead({
- paths,
- plan,
- onLog,
- signal,
- deps: {
- profileBusy: () => xPressInFlight(),
- ...(chromium ? { chromium, pauseMs: () => 50 } : {}),
- },
- }),
- ),
+ signal,
+ deps: {
+ profileBusy: () => xPressInFlight(),
+ ...(chromium ? { chromium, pauseMs: () => 50 } : {}),
+ },
+ });
+ await afterXTrendingRead(plan.slug, plan.channelRoot, result, onLog).catch((err) =>
+ onLog(`The watch could not be told of this read: ${(err as Error).message}`),
+ );
+ done(onLog, result);
+ },
+ });
+}
+
+// THE END OF A READ, FOR THE WATCH (controller/xTrendingWatch.ts): a page X
+// retired is not read again, and ends its topic's watch when it was the last;
+// and a read into a WATCHED topic queues ONE capture for its new posts —
+// their media at once, from the CDN (no page is opened), and a screenshot
+// too when the topic says so — and for what an earlier capture left owed.
+async function afterXTrendingRead(
+ slug: string,
+ channelRoot: string,
+ result: ReadXTrendingResult,
+ onLog: (line: string) => void,
+): Promise<void> {
+ const ended = await noteXTrendingWatchRead(channelRoot, { trendId: result.trendId, outcome: result.outcome });
+ if (ended) onLog(ended);
+ if (result.outcome !== "read" || !result.topic) return;
+ const follow = await xTrendingWatchFollowUp(channelRoot, { topic: result.topic.id, newIds: result.newIds ?? [] });
+ if (!follow) return;
+ const what =
+ `${follow.fresh} new post${follow.fresh === 1 ? "" : "s"}` +
+ (follow.owed ? ` and ${follow.owed} owed from an earlier capture` : "") +
+ ` of the watched topic "${result.topic.title}"`;
+ const started = await capturePostsAction(slug, follow.ids, undefined, follow.shots, true, false, false, {
+ // Media only: no page is opened for the avatars or the context either.
+ ...(follow.shots ? {} : { avatars: false, context: false }),
});
+ if (started.ok) {
+ void started.stream.cancel();
+ onLog(`Queued capture ${started.jobId} for ${what}: their media${follow.shots ? " and a screenshot of each" : ""}.`);
+ } else {
+ onLog(`The media of ${what} was not queued: ${started.error}`);
+ }
}
// A library's root on disk, or the refusal's sentence.
@@ -160,3 +218,108 @@ export async function judgeXTrendingAction(ask: JudgeXTrendingAsk): Promise<Judg
}
return { ok: true, slug: ask.slug, ...result, ...(archive ? { archive } : {}) };
}
+
+// ── the watch ──────────────────────────────────────────────────────────────
+
+export type WatchSettingsAsk = { maxVideoMb?: unknown; intervalMinutes?: unknown; hours?: unknown; maxTopics?: unknown };
+
+export type WatchXTrendingAsk = {
+ slug: string;
+ // One scan now (what the timer does every minute).
+ tick?: boolean;
+ // The library's defaults, changed.
+ settings?: WatchSettingsAsk;
+ // The switch of one topic.
+ topic?: string;
+ on?: boolean;
+ intervalMinutes?: unknown;
+ hours?: unknown;
+ shots?: boolean;
+ by?: unknown;
+};
+
+export type WatchXTrendingResult =
+ | { ok: true; slug: string; topic?: string; watch?: XTrendingWatch; sentence: string; scan?: WatchScanResult; settings?: XTrendingConfig }
+ | { ok: false; error: string };
+
+const WATCH_ONE_OF = `Give "topic" with "on" (the switch of one topic), "settings" (the library's defaults) or "tick": true (one scan now), one of them.`;
+
+function settingsPatch(ask: WatchSettingsAsk): { ok: true; patch: Partial<XTrendingConfig> } | { ok: false; error: string } {
+ const patch: Partial<XTrendingConfig> = {};
+ const int = (v: unknown, min: number, max: number, what: string): number | string =>
+ typeof v === "number" && Number.isInteger(v) && v >= min && v <= max ? v : `"${what}" is a whole number, ${min}–${max}`;
+ const unknown = Object.keys(ask).filter((k) => !["maxVideoMb", "intervalMinutes", "hours", "maxTopics"].includes(k));
+ if (unknown.length) return { ok: false, error: `unknown setting(s): ${unknown.join(", ")} (maxVideoMb, intervalMinutes, hours, maxTopics)` };
+ for (const [key, to, min, max] of [
+ ["maxVideoMb", "maxVideoMb", 1, X_TRENDING_MAX_VIDEO_MB],
+ ["intervalMinutes", "watchIntervalMinutes", X_TRENDING_WATCH_MIN_INTERVAL_MINUTES, X_TRENDING_WATCH_MAX_INTERVAL_MINUTES],
+ ["hours", "watchHours", 1, X_TRENDING_WATCH_MAX_HOURS],
+ ["maxTopics", "watchMaxTopics", 1, X_TRENDING_WATCH_MAX_TOPICS],
+ ] as const) {
+ const v = ask[key];
+ if (v === undefined) continue;
+ const n = int(v, min, max, key);
+ if (typeof n === "string") return { ok: false, error: n };
+ patch[to] = n;
+ }
+ if (Object.keys(patch).length === 0) return { ok: false, error: `"settings" names nothing to change (maxVideoMb, intervalMinutes, hours, maxTopics)` };
+ return { ok: true, patch };
+}
+
+// WATCH A TOPIC (lane x-trending-2): the channel page's switch and `pnpm ops
+// watch-trending`. While a topic is watched its trending page is read again
+// every `intervalMinutes` until `hours` from now — each tick the same single
+// read-x-trending job, started by the scan (controller/xTrendingWatch.ts).
+// A WATCH RUNS ONLY WHILE X'S COOKIE JAR IS FRESH: it pauses when the jar
+// passes its limit and resumes at the first scan after Refresh cookies.
+export async function watchXTrendingAction(ask: WatchXTrendingAsk): Promise<WatchXTrendingResult> {
+ const lib = await libraryRoot(ask.slug);
+ if (!lib.ok) return lib;
+ const paths = getPaths();
+ const asked = [ask.tick === true, ask.settings !== undefined, ask.topic !== undefined].filter(Boolean).length;
+ if (asked !== 1) return { ok: false, error: WATCH_ONE_OF };
+ if (ask.tick) {
+ // The armed scan when there is one (one scan at a time); else one of its own.
+ const { xTrendingWatchDeps } = await import("../../api/ops/_xTrendingWatch");
+ const scan = await (xTrendingWatchTick() ?? scanXTrendingWatches(xTrendingWatchDeps()));
+ safeRevalidate([`/channels/${ask.slug}`, "/review"]);
+ const sentence = scan.enqueued
+ ? `Scanned: a tick of "${scan.enqueued.topic}" (${scan.enqueued.slug}) was started, job ${scan.enqueued.jobId}.`
+ : scan.refused
+ ? `Scanned: the tick of "${scan.refused.topic}" was refused: ${scan.refused.error}`
+ : `Scanned: ${scan.live} live watch${scan.live === 1 ? "" : "es"}, no tick started` +
+ (scan.paused.length ? ` (${scan.paused.length} paused)` : "") +
+ ".";
+ return { ok: true, slug: ask.slug, scan, sentence };
+ }
+ if (ask.settings !== undefined) {
+ if (!ask.settings || typeof ask.settings !== "object" || Array.isArray(ask.settings)) {
+ return { ok: false, error: `"settings" is an object: {maxVideoMb?, intervalMinutes?, hours?, maxTopics?}` };
+ }
+ const parsed = settingsPatch(ask.settings);
+ if (!parsed.ok) return parsed;
+ const next = await patchChannelConfig(paths, ask.slug, {}, { derive: (current) => ({ xTrending: { ...current.xTrending, ...parsed.patch } }) });
+ safeRevalidate([`/channels/${ask.slug}`]);
+ const settings = next?.xTrending ?? {};
+ return { ok: true, slug: ask.slug, settings, sentence: `Saved: ${JSON.stringify(parsed.patch)}.` };
+ }
+ if (typeof ask.on !== "boolean") return { ok: false, error: `"on" is true (watch the topic) or false (stop watching it)` };
+ if (ask.by !== undefined && ask.by !== "agent" && ask.by !== "operator") return { ok: false, error: `"by" is "agent" or "operator"` };
+ const config = (await readChannelConfig(paths, ask.slug))?.xTrending;
+ const terms = xTrendingWatchTerms(config, ask.on ? { intervalMinutes: ask.intervalMinutes, hours: ask.hours } : {});
+ if (!terms.ok) return terms;
+ const now = Date.now();
+ const set = await setXTrendingWatch(lib.channelRoot, {
+ topic: String(ask.topic),
+ on: ask.on,
+ intervalMinutes: terms.terms.intervalMinutes,
+ hours: terms.terms.hours,
+ ...(ask.shots !== undefined ? { shots: ask.shots } : {}),
+ by: ask.by === "operator" ? "operator" : "agent",
+ maxTopics: xTrendingWatchMaxTopics(config),
+ now,
+ });
+ if (!set.ok) return set;
+ safeRevalidate([`/channels/${ask.slug}`, "/review"]);
+ return { ok: true, slug: ask.slug, topic: set.topic, watch: set.watch, sentence: describeXTrendingWatch(set.watch, now) };
+}
diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts
@@ -336,6 +336,21 @@ export async function register() {
/* auto-continue that fails to arm must not block server readiness */
}
+ // THE WATCH OF X TRENDING LIBRARIES (lane x-trending-2): a scan every
+ // minute, at most ONE read-x-trending job per scan, for the topics someone
+ // switched a watch on for. Below the idle gate — a tick is a request to X —
+ // and not on the e2e test server, whose spec drives a scan by hand
+ // (`watch-trending {"tick": true}`). It never refreshes X's cookie jar: on a
+ // stale jar the watches pause. See common/controller/xTrendingWatch.ts.
+ if (process.env.E2E_TEST_ROUTES !== "1") {
+ try {
+ const { armXTrendingWatchLane } = await import("./app/api/ops/_xTrendingWatch");
+ armXTrendingWatchLane();
+ } catch {
+ /* a watch that fails to arm must not block server readiness */
+ }
+ }
+
// THE RECURRING REPORTS (umtool R5): the report-schedule lane — a scan now
// and every minute, ONE report-tick job per due schedule, held by its pause
// gate. Below the idle gate: a tick is generation work.
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -178,6 +178,8 @@
// pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","topic":"Kettle festival"}' --wait
// pnpm ops read-x-trending --json '{"slug":"trending","reparse":"tr-01JA0000000000000000000000"}' --wait
// pnpm ops get trending trending --topic kettle-festival --limit 50
+// pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":true,"intervalMinutes":30,"hours":48}'
+// pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":false}'
// pnpm ops judge-trending --json '{"slug":"trending","set":[{"id":"1900000000000001001","state":"keep","note":"the opening"},{"thread":"1900000000000001002","state":"drop"}]}'
// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://web.archive.org/web/20140305120000/https://blog.example/a-post.html","dryRun":true}'
// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20140301"}' --wait
@@ -709,6 +711,10 @@ const ACTIONS = [
// per post or per thread ({slug, set: [{id | thread, state, note?}], by?,
// archive?}); a keep archives the post through capture-posts.
"judge-trending",
+ // A topic watched: read again every interval until an end time ({slug,
+ // topic, on, intervalMinutes?, hours?, shots?}); the library's defaults
+ // ({slug, settings}); one scan now ({slug, tick: true}).
+ "watch-trending",
// EVIDENCE GAPS (release 29 E2): the Wayback Machine's captures of a page
// ({url} or a record's {slug, id}), read only and paced; and find-copy — a
// copy of every gone recording a report cites (Wayback, then archive.org),
@@ -1301,13 +1307,19 @@ export function usage() {
" index): topics [{id, title, posts, sources: [{trendId, url, reads,",
" lastReadAt}]}], posts [{id, author, authorName, createdAt, url, text,",
" media: {count, kinds, thumbnail?}, topic, reads: [{read, trendId, at}],",
- " judgement?}] (the newest read's first, in page order; --limit 1-500,",
+ " gone?, capture?, thread, judgement?}] (the newest read's first, in page order; --limit 1-500,",
" default 100; total is the count before it) and reads (the saved reads'",
" ids, newest first). thumbnail is a captured post's first picture",
" (trending/posts-media/<id>/<name>, relative to the channel); thread is",
" the root post id of the thread a post belongs to; judgement is {state:",
" keep | drop | later, note?, by, at, from?} once a post has one (its own,",
- " or its thread's: from \"thread\"); no judgement is undecided. Never the",
+ " or its thread's: from \"thread\"); no judgement is undecided. gone is",
+ " {at, read, trendId}: a page that showed the post before did not show it",
+ " at a read that reached the page's end (gone from the page, not",
+ " deleted). capture is {at, state, shot, files, mediaState, mediaOwed?}",
+ " (mediaOwed \"next\": a later capture asks again; \"kept\": once the post",
+ " is kept). A topic carries watch {on, intervalMinutes, until, shots,",
+ " ticks, paused?, ended?, sentence} once it has been watched. Never the",
" raw capture, a cookie or a token.",
"get x-run [<run id>] is the X run as /review's X run console shows it:",
" the latest run (or the one named) — each channel's status (queued,",
@@ -1937,6 +1949,32 @@ export function usage() {
" post, its capture and its media stay, and a later keep puts it back. An",
" id the library does not hold is skipped by name, not refused.",
"",
+ 'watch-trending watches a topic of an X trending library: {"slug",',
+ ' "topic", "on": true, "intervalMinutes"?, "hours"?, "shots"?, "by"?}.',
+ " While a topic is watched its trending page is read again every",
+ " intervalMinutes (15-1440; default the library's, else 30) until hours",
+ " from now (1-168; else 48), each tick the SAME single read-x-trending",
+ " job on X's queue, started by the editor's own scan (once a minute, at",
+ " most one read per scan, none while a read or capture of the library",
+ " waits its turn). A topic of several pages reads one page per tick, in",
+ " turn. At most 4 topics of a library are watched at once (its",
+ " maxTopics). A new post's media is fetched at once from X's media CDN,",
+ " no page opened; \"shots\": true also screenshots every new post.",
+ ' "on": false stops it. A WATCH RUNS ONLY WHILE X\'S COOKIE JAR IS UNDER',
+ " ITS LIMIT (60 minutes): the editor never refreshes the jar by itself,",
+ " so a watch pauses when the jar goes stale (X's jar-age alert goes up,",
+ " /review lists the paused watches) and resumes at the first scan after",
+ " Refresh cookies on /cookies. It does not cover a night nobody presses",
+ " Refresh in. The X alert, a rate-limit cooldown and a missing profile",
+ " pause it the same way. A post a page showed before and does not show",
+ " at a read that reached the page's end is recorded gone from the page",
+ " at that time (get trending: gone) - never \"deleted\". A page X no",
+ " longer has is not read again, and ends the watch when it was the",
+ ' topic\'s last. {"slug", "settings": {"maxVideoMb"?, "intervalMinutes"?,',
+ ' "hours"?, "maxTopics"?}} changes the library\'s defaults; {"slug",',
+ ' "tick": true} runs one scan now. get trending shows each topic\'s',
+ " watch and what it is doing (watch.sentence).",
+ "",
'x-run fetches several X posts channels IN SEQUENCE as ONE job on X\'s',
' queue: {"channels": [slug, ...]} in that order, each a fetch-posts sync',
' new of at most 200 posts ("limit": N, 1-200, caps it lower), X\'s queue',
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -1148,7 +1148,7 @@ test("read-x-trending is a POST with a result marker; get trending reads the lib
assert.match(parseArgs(["get", "channel", "s", "--topic", "x"]).error, /get channel does not take --topic/);
assert.match(usage(), /pnpm ops get trending <slug> \[--topic <topicId>\] \[--limit <n>\]/);
assert.match(usage(), /read-x-trending reads ONE X trending page into an X trending library/);
- assert.match(usage(), /Actions:.*x-search-lead, read-x-trending, judge-trending/);
+ assert.match(usage(), /Actions:.*x-search-lead, read-x-trending, judge-trending, watch-trending/);
});
test("judge-trending posts its body; its help says an agent never replaces the operator", () => {
@@ -1159,3 +1159,12 @@ test("judge-trending posts its body; its help says an agent never replaces the o
assert.match(usage(), /judge-trending judges posts of an X trending library/);
assert.match(usage(), /an agent's write over a judgement the operator made is\n\s+skipped/);
});
+
+test("watch-trending posts its body; its help says a watch runs only on a fresh jar", () => {
+ const p = parseArgs(["watch-trending", "--json", '{"slug":"lib","topic":"kettles","on":true,"intervalMinutes":30}']);
+ assert.equal(p.method, "POST");
+ assert.equal(p.path, "/api/ops/watch-trending");
+ assert.deepEqual(p.body, { slug: "lib", topic: "kettles", on: true, intervalMinutes: 30 });
+ assert.match(usage(), /A WATCH RUNS ONLY WHILE X'S COOKIE JAR IS UNDER\n\s+ITS LIMIT/);
+ assert.match(usage(), /It does not cover a night nobody presses\n\s+Refresh in/);
+});