Archilyzer · Source

archilyzer

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

commit 71b525a78d8c10e12b45e1b2e65f7ca068a8b4fa
parent 63e7a318b97f6f7616daa5c7e9d508025b440b96
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 20:07:41 -0500

x: the operator's rulings of 18 Nov -- higher trending caps, X jobs on X's queue only under an immutable cap, and a trending read that covers Latest as well as Top

R1. A trending read's defaults are 20 scrolls and 200 posts per tab (were 8 and 60); the maxima 40 and
400. Its deadline is 2 minutes plus 12 s for every scroll each tab may make: 6 minutes for one tab at
20 scrolls, 10 for both, 18 for both at the maximum.

R2. common/lib/xJobRule.ts: X jobs run on X's queue only, and at most 12 start in any rolling 60
minutes and 150 in any rolling 24 hours, per X login, over every kind of X job. The numbers are
constants: no setting, config key, environment variable, option or queue changes them.
- The network guard takes a job for X's when its queue is X's or its channel is on X, refuses any
  other queue at enqueue and at the start, refuses at enqueue when the cap is reached, and checks and
  records one start at the last guard before the work. Each channel of an X run is one start.
- Where X is about to be asked the code asks for a job of the editor's on X's queue: fetchPosts,
  capturePosts, importPost, checkPostAvailability, runXTrendingRead.
- The count is transcripts/.x-session/job-starts.json: under its lock, kept across a restart, refusing
  every X job when it cannot be read, and never freeing a start early when the clock is set back.
- The scheduler skips X channels while the cap is reached; a watch's tick is skipped as for a
  cooldown. `get x-session` shows the count.

R3. One read job scrolls the tab the page opens on, then presses the page's own Latest tab, waits for
the page's request for that tab's timeline and scrolls it under the same caps. It builds no request.
- The parser's end rule and post lists are per timeline; read.json says per tab its posts, scrolls,
  stop and whether the capture shows its end; sightings and gone marks are per tab, and a post is gone
  from the page once every tab that showed it has dropped it.
- A Latest that cannot be opened ends the read "Top read; Latest not read: <why>": a read, no strike,
  nothing retried. A 429, a 403 or a login wall on either tab stops the whole read.
- `tabs` on read-x-trending and per watch (default both); the fake profile browser has the two-tab
  page; the channel page, the MCP and umtool say the per-tab state.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MCHANNEL.md | 2+-
MCOMMANDS.md | 12+++++++++---
MOPERATING.md | 39+++++++++++++++++++++++++++++++++------
Mcommon/controller/capturePosts.test.ts | 22+++++++++++++++++++++-
Mcommon/controller/capturePosts.ts | 7+++++++
Mcommon/controller/checkPostAvailability.ts | 7+++++++
Mcommon/controller/fetchPosts.test.ts | 16++++++++++++++++
Mcommon/controller/fetchPosts.ts | 9+++++++--
Mcommon/controller/readXTrending.test.ts | 148++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mcommon/controller/readXTrending.ts | 190++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mcommon/controller/xRun.ts | 2++
Mcommon/controller/xTrendingCooldown.test.ts | 5++++-
Mcommon/controller/xTrendingWatch.test.ts | 9+++++++++
Mcommon/controller/xTrendingWatch.ts | 11+++++++++--
Mcommon/controller/xTrendingWatchJob.test.ts | 5++++-
Mcommon/jobs/instagramSchedule.test.ts | 22++++++++++++++++++++++
Mcommon/jobs/networkGuard.ts | 85++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/jobs/pacingGuard.test.ts | 110++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/jobs/streamCommand.ts | 8+++++---
Mcommon/jobs/syncScheduler.ts | 25++++++++++++++++++++++++-
Mcommon/lib/channelConfig.ts | 2+-
Acommon/lib/xJobCap-server.ts | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xJobRule.test.ts | 141+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xJobRule.ts | 132+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/xTrending/config.test.ts | 16++++++++--------
Mcommon/lib/xTrending/config.ts | 8++++----
Mcommon/lib/xTrending/store.test.ts | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/lib/xTrending/store.ts | 223++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Mcommon/lib/xTrending/watch.ts | 20+++++++++++++++++++-
Mcommon/social/__fixtures__/xTrendingCapture.ts | 44++++++++++++++++++++++++++++++++++++++------
Mcommon/social/fakeXProfileBrowser.ts | 31+++++++++++++++++++++++++++++--
Mcommon/social/importPost.test.ts | 22+++++++++++++++++++++-
Mcommon/social/importPost.ts | 6++++++
Mcommon/social/playwrightRuntime.ts | 8++++++++
Mcommon/social/xTrendingParse.test.ts | 18++++++++++++++----
Mcommon/social/xTrendingParse.ts | 60++++++++++++++++++++++++++++++++++++++++++------------------
Mcommon/social/xTrendingRead.test.ts | 97++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/social/xTrendingRead.ts | 242++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/views/schedulerStatus.ts | 3+++
Meditor/CHANGELOG.md | 19+++++++++++++++++++
Meditor/app/api/ops/_xTrendingWatch.ts | 2+-
Meditor/app/api/ops/read-x-trending/route.ts | 18++++++++++++------
Meditor/app/api/ops/watch-trending/route.ts | 7+++++--
Meditor/app/channels/[slug]/components/XTrendingPanel.tsx | 20+++++++++++++++++++-
Meditor/app/channels/[slug]/xTrendingActions.ts | 6++++++
Meditor/app/channels/components/parseChannelForm.test.ts | 6+++---
Meditor/app/scheduler/runTick.ts | 4++++
Meditor/app/scheduler/status.ts | 4+++-
Meditor/e2e/x-trending.spec.ts | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mmcp/src/xTrending.test.ts | 17+++++++++++++++++
Mmcp/src/xTrending.ts | 12+++++++++---
Mplans/x-trending.md | 67++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mscripts/archilyzer-ops.mjs | 27+++++++++++++++++++++------
Mumtool/components/tools/library/LibraryView.tsx | 16+++++++++++++---
Mumtool/e2e/fixtures/editor-stub-trending.mjs | 1+
Mumtool/e2e/fixtures/library-fixture.mjs | 2++
Mumtool/e2e/library.spec.ts | 5++++-
Mumtool/lib/library/cli.mjs | 4++--
Mumtool/lib/library/filters.mjs | 5+++++
Mumtool/lib/library/view.test.mjs | 5+++++
60 files changed, 2065 insertions(+), 245 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?, 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. | +| `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–40 scrolls, default 20; 1–400 posts, default 200; each of the page's two tabs has both); 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 @@ -218,9 +218,9 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `save-page-now-batch` | save-page-now-batch saves a LIST of pages as ONE resumable job: {"urls": \[...\]} \| {"file": &lt;abs path: a JSON list, {urls}, or a URL a line&gt;} \| {"batch": &lt;id&gt;}, "skipArchived"? (true), "sources"? (\["wayback", "archive.today"\]), "evidence"? (abs path), "dailyCap"? (150 anonymous, at most 200; 5000 with keys), "dryRun"? -&gt; {jobId, batch}. Each URL in turn: looked up (the Wayback CDX, archive.today's timemap, each paced) and archived-already when a copy shows it (a Wayback row that recorded a 200, or an archive.today copy); else saved through Save Page Now's pacer (anonymous without keys), saved or failed with the reason; a site Save Page Now refuses as a site (x.com, 5 Nov: "limitations when it comes to archiving this site") is asked once a run, its other URLs looked up only. archive.today and Ghostarchive are looked up, never asked to save. The state is &lt;transcripts&gt;/.spn-batches/&lt;batch&gt;.json, written after every URL: the same request again, {batch}, a Retry or a restart continues from the first pending URL. The evidence (JSON + CSV: url, status, reason, waybackUrl, waybackCaptureTs, waybackHttpStatus, waybackMimetype, archiveTodayUrl, archiveTodayCaptureTs, shows, savedMode, checkedAt, doneAt) is rewritten after every URL; default &lt;transcripts&gt;/.spn-batches/&lt;batch&gt;.evidence.json. Progress (done/total, ETA) in /jobs. The log ends with @@save-page-now-batch {batch, mode, counts, run, evidence, statePath, etaSeconds, stopped?}. | `pnpm ops save-page-now-batch --json '{"file":"/home/me/lists/posts.json","dryRun":true}'`<br>`pnpm ops save-page-now-batch --json '{"file":"/home/me/lists/posts.json","evidence":"/home/me/evidence/posts"}'`<br>`pnpm ops save-page-now-batch --json '{"batch":"spn-0123456789ab"}'` | | `archive-lookup` | archive-lookup answers the copies of a page each archive source holds: {"url"} (the page's own URL), "source"?: "wayback" \| "archive.today" (default both), "limit"?: 50 per source (at most 500) -&gt; {url, found, sources: \[{source, label, ok, captures: \[{source, captureTs, originalUrl, mementoUrl, status?, mimetype?}\], refusal?, error?}\]}, oldest first. Each source through its own paced client; one that refuses is its own entry's sentence (refusal "excluded": excluded from the Wayback Machine (cause unknown); "challenge"; "rate-limited"). Read only. wayback-lookup stays. | `pnpm ops archive-lookup --json '{"url":"https://blog.example/a-post.html"}'` | | `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 &lt;handle&gt;-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) -&gt; {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 -&gt; {exclude, changed}. No model, no request but the new channel's fetch. An X TRENDING LIBRARY's accounts (get trending &lt;slug&gt; --accounts) are leads too: with "slug" a library, "archive" creates &lt;handle&gt;-x for an account that wrote a post the library holds, on no site, naming nothing of the library, and ASKS X NOTHING, now or later: no first fetch is started and the channel is made with SYNC OFF (its priority tier paused, which the scheduler, Sync all and the lanes honour) -&gt; {slug, jobIds: \[\], syncOff: true, sentence}. The sentence says how to turn sync on (channel-priority, tier normal) and run the first fetch (fetch-posts). "fetch": true asks for the ordinary behaviour instead (the first fetch started, sync on). "never" and "restore" are a search channel's only. | `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"}'`<br>`pnpm ops x-search-lead --json '{"slug":"trending","handle":"example","action":"archive","dryRun":true}'` | -| `read-x-trending` | read-x-trending reads ONE X trending page into an X trending library: {"slug", "url": "https://x.com/i/trending/&lt;number&gt;"}, 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/&lt;slug&gt;/trending/reads/&lt;readId&gt;/), 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": "&lt;readId&gt;"} 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` | +| `read-x-trending` | read-x-trending reads ONE X trending page into an X trending library: {"slug", "url": "https://x.com/i/trending/&lt;number&gt;"}, 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/&lt;slug&gt;/trending/reads/&lt;readId&gt;/), 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 the page's own title). "tabs": \["top"\], \["latest"\] or both (the default): BOTH ARE READ IN THIS ONE JOB - Top to its stop, then the page's own Latest tab is pressed and read under the same caps. A Latest that cannot be opened ends the read "Top read; Latest not read: &lt;why&gt;", ok, nothing retried. "scrolls": 1-40 moves to the bottom of a tab (default: the channel's cap, else 20); "posts": stop a tab once 1-400 are seen on it (else 200); a tab also stops after two scrolls with nothing new, and the whole read 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 its deadline: 2 minutes plus 12 s for every scroll each tab may make (both tabs at 20 scrolls: 10 minutes; one tab: 6; both at 40: 18). 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": "&lt;readId&gt;"} 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" - the caller's word: an agent says "agent". 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; a post the operator judged through its thread is the operator's too. 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 trending read or capture of ANY library waits its turn: every library's ticks are one stream). 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. That limit is the watch's own, whatever the login source or the setting: a jar whose age cannot be read, a limit set to 0 and an unreadable settings file all pause it. The X alert, a rate-limit cooldown and a missing profile pause it the same way. Three reads in a row that do not end "read" (a rate limit, a 403, a page that will not load) pause it until the operator switches it on again ("by": "operator"; an agent's ask is refused). A post a page showed before and does not show at a read whose capture shows the page's end (asked for more, the page had none, no answer failed) 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 (refused on an idle boot; two asks at once are one scan). 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}'` | +| `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 trending read or capture of ANY library waits its turn: every library's ticks are one stream). 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. "tabs": the page's tabs each tick reads, as read-x-trending's (the default: both, in the one job). "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. That limit is the watch's own, whatever the login source or the setting: a jar whose age cannot be read, a limit set to 0 and an unreadable settings file all pause it. The X alert, a rate-limit cooldown and a missing profile pause it the same way. Three reads in a row that do not end "read" (a rate limit, a 403, a page that will not load) pause it until the operator switches it on again ("by": "operator"; an agent's ask is refused). A post a page showed before and does not show at a read whose capture shows the page's end (asked for more, the page had none, no answer failed) 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 (refused on an idle boot; two asks at once are one scan). 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}'` | | `purge-trending` | purge-trending removes the captures of DROPPED posts of an X trending library, in two steps. {"slug", "dryRun": true, "topic"?, "ids"?} removes nothing: it counts the dropped posts with a capture (posts, ids, files, bytes) and answers "confirm", a digest of exactly those posts. {"slug", "confirm", "by": "operator", "topic"?, "ids"?} removes them: the screenshot, the record and the media under channels/&lt;slug&gt;/trending/posts-media/&lt;id&gt;/. It is the operator's press: an agent's removal is refused (an agent may ask for the dry run), and a confirm that no longer matches (a post dropped or kept, a capture added since) is refused with nothing removed. Only posts whose judgement in force is drop BY THE OPERATOR (their own entry, or their thread's) are taken: an agent's drop is a suggestion and is never purged (agentDropped counts those left alone), nor is a post marked later, kept or undecided; an id named that is not such a post is listed in skipped. gone names the posts to be removed that are gone from the page: their capture is the only copy, and the sentence says removing it cannot be undone. The judgements, the posts and the reads stay, and so does every media file another post still uses (blobsKept). Refused while a capture of the library is queued or running (a dry run then says captureInFlight). A later keep captures the post again. | `pnpm ops purge-trending --json '{"slug":"trending","topic":"kettle-festival","dryRun":true}'`<br>`pnpm ops purge-trending --json '{"slug":"trending","topic":"kettle-festival","confirm":"<the dry run's confirm>","by":"operator"}'` | | `organise-trending` | organise-trending organises the topics of an X trending library. "by" is who asks ("agent" unless told) and is recorded. {"slug", "op": "rename", "topic", "title"} renames a topic: its id stays, so its watch, posts and judgements are untouched; a name another topic answers to is refused, and so is a rename while a read or a reparse of the library is queued or running (a read may name its topic by its name). {"slug", "op": "move", "to", "ids": \[..\] \| "thread", "create"?} moves posts (or every post of one thread, by its root post's id) into the topic "to" (an id or a name; "create": true makes a topic of that name, with no trending page, when there is none) -&gt; {to, moved, skipped}; judgements and captures are untouched, a later read never moves a post back, and it is not refused beside a read or a capture. {"slug", "op": "merge", "into", "from": \[..\], "by": "operator"} puts every post, page and read of the "from" topics into "into" and removes them -&gt; {into, merged, posts, pages, watch}. THERE IS NO UNMERGE, so a merge is the operator's (an agent's is refused), and it is refused while a read or a reparse of the library is queued or running. The merged topics' ids keep meaning "into"; judgements are untouched; ONE watch stands (the target's live watch with its own terms, else the first merged topic's moves to it), and "sentence" says which. A topic has one published channel too (published: {carried?, left}): the target's stays; with none, the first merged topic's becomes its own; any other is left as it is, never added to again, and named in the sentence. | `pnpm ops organise-trending --json '{"slug":"trending","op":"rename","topic":"kettle-festival","title":"Kettle festival 2026"}'`<br>`pnpm ops organise-trending --json '{"slug":"trending","op":"move","to":"kettle-festival","ids":["1900000000000001001"]}'`<br>`pnpm ops organise-trending --json '{"slug":"trending","op":"merge","into":"kettle-festival","from":["teapots"],"by":"operator"}'` | | `publish-trending` | publish-trending publishes a topic of an X trending library, in two steps. {"slug", "topic", "dryRun": true, "channel"?} writes nothing: it says what would be written (channel, creates, posts, ids, already, files, bytes, textOnly, noLongerKept) and what to know before the press: sites (the sites the channel is ALREADY ON: what is added goes public at their next build), movedIn (posts to publish that were moved into the topic, and by whom) and mismatched (files that no longer match the digest their capture recorded: not copied). It answers "confirm", a digest of exactly that, the sites included. Then {"slug", "topic", "confirm", "by": "operator"} publishes: the topic's posts whose judgement in force is keep BY THE OPERATOR (their own entry, or their thread's) go into an ORDINARY posts channel ("channel": a slug of the topic's name unless given, fixed at the first publish) with their captured media and screenshots, COPIED (the library keeps its own; a purge of the library and a delete of the channel do not reach each other). An agent's keep is not published. The channel is on NO site (adding it to one is a separate step: site-config, /sites), names nothing of the library (no judgement, note, read, watch or gone mark) and is never fetched. It is the operator's press: an agent's publish is refused (an agent may ask for the dry run), and a confirm that no longer matches is refused with nothing written. Re-publishing adds newly kept posts and files and removes nothing: a post published before and since dropped is listed in noLongerKept and left; textOnly lists kept posts with no capture yet (published as their words; a later publish adds the files). Refused while a read, a reparse or a capture of the library is queued or running (a dry run then says inFlight), and when a channel of that slug exists that this publish did not make (no record of it, a source of its own, a post this topic never published, or not the very directory this publish made: a channel deleted and made again by hand is refused, even empty). | `pnpm ops publish-trending --json '{"slug":"trending","topic":"kettle-festival","dryRun":true}'`<br>`pnpm ops publish-trending --json '{"slug":"trending","topic":"kettle-festival","confirm":"<the dry run's confirm>","by":"operator"}'` | @@ -360,7 +360,13 @@ get x-session [<slug>] is the X login an X job would use and whether one "browser": cookiesFromBrowser, whose age cannot be read), hasCookies, looksAuthenticated, cookiesUpdatedAt, ageMinutes, maxAgeMinutes (social.x.maxCookieAgeMinutes; 0 = off), the X cookie alert if it is up, - allowed, and reason (the refusal an X job would get). <slug> names a + allowed, and reason (the refusal an X job would get); and X's JOB CAP: + login (whose count it is), cap {lastHour, perHour: 12, lastDay, perDay: + 150, reached, nextAt?} - at most 12 X jobs start in any 60 minutes and + 150 in any 24 hours, per X login, over every kind of X job; a job past + it is refused before it starts with the time the next may start. The + numbers are constants of the code (common/lib/xJobRule.ts): no setting, + option or queue raises them. <slug> names a channel whose own cookiesFromBrowser may decide the source. Nothing is asked of X: a refresh is Refresh cookies / Connect X account on /settings. Ask it before queueing fetch-posts or capture-posts on X. diff --git a/OPERATING.md b/OPERATING.md @@ -526,6 +526,23 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait (plain, `--backfill`, `--full`, `--older`, an X search channel) and for every X fetcher, and names `pnpm ops fetch-posts`: run directly it had no queue, no gap, no fresh-jar rule, no X alert and no cooldown. It still fetches a Bluesky account, a forum thread (`--pages N`) and a web page, whose pacing is the fetcher's own. + `pnpm archilyzer posts check` on an X channel is refused the same way. The Add-channel form's **Fetch details** + on an X address reads the handle off the URL and asks X nothing. +- **X jobs run on X's queue only.** Every job that asks X as the connected account or with X's cookies — a + posts fetch in any mode, `resume-backfill`, a Sync, `create-channel` with a fetch, `capture-posts` on an X + channel or a library, `read-x-trending`, `import-post` of an X post, an availability check of an X channel, an + X run, an X lead archived with a fetch — is refused with a `queueKey` other than `platform:twitter`, when it is + queued and again where it runs. On another queue it ran beside the job on X's and outside the gap between X jobs. +- **X's job cap: 12 in any 60 minutes, 150 in any 24 hours, per X login.** Over every kind of X job together + (each channel of an X run is one). A job past it is refused before it starts, with the time the next may start; + nothing queues behind it. The scheduler skips X channels while it is reached and a trending watch waits, as for + a cooldown. `pnpm ops get x-session` shows the count (`cap`). **The two numbers are constants of the code** + (`common/lib/xJobRule.ts`): no setting, channel option, environment variable, flag or queue raises them, and + changing them is a code change. The count is kept in `transcripts/.x-session/job-starts.json`; if that file + cannot be read no X job starts until it is repaired. X's own gap (5 minutes) already means 12 jobs an hour, so + the hourly cap bites only if that gap is lowered; the daily cap bites sooner: an X run over more than 150 + channels, more than 150 X channels on a daily sync, or two topics watched at 30 minutes (a tick is a read and + usually a capture: about 96 jobs a day per topic) each reach it. - **X only on a fresh jar.** With the connected profile as the login source, a job aimed at X is refused — at enqueue and again when its queue reaches it — unless the cookies were refreshed within `social.x.maxCookieAgeMinutes` (60; 0 = off): `X cookies were last refreshed 16 days ago (limit 60 min): @@ -740,10 +757,11 @@ pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","o never served or indexed. - **What a read costs**: one page load, the page's own first requests, and at most one more page of its timeline per scroll. A scroll moves to the bottom of what has loaded, then waits 4–10 s. It stops at the scroll cap - (`"scrolls"`, 1–20, default 8), at the post cap (`"posts"`, 1–200, default 60), after two scrolls that brought + (`"scrolls"`, 1–40, default 20), at the post cap (`"posts"`, 1–400, default 200), each counted per tab, after two scrolls that brought nothing new, and at once on a 429, a 403, a 401 or X's login page. Nothing retries. - **A read cannot hang.** The page's load has 75 s; a scroll, the address and the screenshot 20 s each; closing - the browser 10 s (then it is killed); the whole read 6 minutes. Past any of them the read fails with a sentence, + the browser 10 s (then it is killed); the whole read 2 minutes plus 12 s for every scroll each tab may make (both tabs at + 20 scrolls: 10 minutes; one tab: 6; both at the maximum 40: 18). Past any of them the read fails with a sentence, the browser closed and the capture kept. The channel's own caps are `xTrendingMaxScrolls` / `xTrendingMaxPosts` (Configure, or `channel-config`). - **A read lists posts**: the post's words, author, date and its media by kind, parsed from the saved file and @@ -759,10 +777,19 @@ pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","o topic already answers to. Whatever the topic is called, the page's entry in it keeps X's title, summary and when X last updated them: the channel page, `get trending` (`sources[].title` / `summary` / `lastUpdatedAt`), `x_trending_topics`, and umtool's library page and `umtool library topics` show them as X's. -- **A read sees one tab.** A trending page has tabs (`Top`, `Latest`), each its own list of posts. A read sees - the tab the page opens on and says which: in its sentence, in `read.json` (`tabs`: a label and a count), per - post (`posts[].reads[].tab`) and per page (`sources[].lastReadTab`, with the page's `tabs`). The other tab is - not read. "Gone from the page" compares a read with earlier reads of the same tab only. +- **A read covers both tabs, in one job.** A trending page has tabs (`Top`, `Latest`), each its own list of + posts; `Latest` is where a post that is deleted quickly shows first. A read scrolls `Top` to its stop, then + presses the page's own `Latest` tab (it never builds a request: it waits for the page's request for that tab's + timeline) and scrolls it under the same caps. `"tabs": ["top"]` or `["latest"]` reads one; a watch takes the + same option. Everything stays one capture (`responses.jsonl`), with `page-latest.png` beside `page.png`. + `read.json` says per tab (`tabs`): its posts, its scrolls, why it stopped and whether the capture shows its + end. A `Latest` that cannot be opened — no such tab on the page, or pressing it brings nothing within 20 s — + ends the read `Top read; Latest not read: <why>`: still a read, no strike against a watch, nothing retried. A + 429, a 403 or a login wall on either tab stops the whole read. +- **"Gone" is said tab by tab.** A tab read to its end marks the posts it showed before and no longer shows. A + post gone from one tab while the other still shows it is `Gone from the "Latest" tab …; another tab still shows + it` (`posts[].goneTabs`); it is `gone from the page` once every tab that showed it has dropped it. Neither says + the post was deleted. - **`"probe": true`** saves the capture and a summary (the operations' names and sizes, how many posts the parser finds) and writes no post. `{"reparse": "<readId>"}` parses a saved capture again, offline, as a `reparse-x-trending` job: X is asked nothing, so it needs no fresh jar. `read.json` is written when a read diff --git a/common/controller/capturePosts.test.ts b/common/controller/capturePosts.test.ts @@ -15,7 +15,10 @@ process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); const { getPaths } = await import("../lib/paths"); const { registerSocialFetcher } = await import("../social/fetchers"); const { readPostAvailability, writePostAvailability, writePosts } = await import("../lib/posts-server"); -const { capturePosts, NOTHING_TO_CAPTURE } = await import("./capturePosts"); +// X is asked only inside a job of the editor's, on X's queue (lib/xJobRule.ts): these calls stand where one does. +const { capturePosts: capturePostsDirect, NOTHING_TO_CAPTURE } = await import("./capturePosts"); +const { insideEditorJob } = await import("../testing/jobs/asEditorJob"); +const capturePosts = insideEditorJob(capturePostsDirect); type Input = import("../social/fetchers").PostCaptureInput; type Result = import("../social/fetchers").PostCaptureResult; @@ -669,3 +672,20 @@ test("an X trending library's logged-in fallback asks, per post and at that mome assert.deepEqual(logins, ["8001"]); assert.deepEqual([results["8001"].ok, results["8002"].ok], [true, false]); }); + +// Added scope R2 (lane x-followups): where X is about to be asked, only a job on X's queue stands. +test("R2a: a capture of an X channel's posts outside the editor's job, or in a job on another queue, asks its fetcher nothing; a Bluesky channel's is not X's", async () => { + const { asEditorJob } = await import("../testing/jobs/asEditorJob"); + // The channel the thread-shot test made (an X channel, the X test fetcher). + const ask = { paths: getPaths(), slug: "demo-x-replies", settings: {}, ids: ["9001"] }; + const before = calls.length; + const outside = await capturePostsDirect(ask); + assert.equal(outside.ok, false); + assert.match(outside.error ?? "", /^A capture of demo-x-replies's posts asks X, and X is asked only by the editor's own jobs .*Queue it instead: pnpm ops capture-posts/); + const elsewhere = await asEditorJob(() => capturePostsDirect(ask), { queueKey: "manual" }); + assert.match(elsewhere.error ?? "", /X jobs run on X's queue only \(platform:twitter\): the queue "manual" is refused/); + assert.equal(calls.length, before, "the fetcher was not asked"); + // Bluesky: no such rule. + const sky = await capturePostsDirect({ paths: getPaths(), slug: "demo-social", settings: {}, ids: [] }); + assert.doesNotMatch(sky.error ?? "", /asks X/); +}); diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -32,6 +32,7 @@ // `contextOnly` loads one page per post for that alone (and the avatars it // shows), writing the context into the record and nothing about availability. +import { xJobContextRefusal } from "../lib/xJobRule"; import path from "node:path"; import { isXSearchChannel } from "../lib/xSearch/config"; import { isXTrendingChannel, xTrendingMaxVideoBytes, type XTrendingConfig } from "../lib/xTrending/config"; @@ -294,6 +295,12 @@ export async function capturePosts( : resolveSocialFetcher(config.postFetcher, accountUrl); const problem = capturePostsProblem(fetcher); if (problem || !fetcher?.captureByIds) return fail(problem ?? "This channel has no post fetcher."); + // X IS ASKED ONLY BY THE EDITOR'S JOBS, ON X'S QUEUE (lib/xJobRule.ts): a + // capture of an X channel's posts, or of a library's, asked where it runs. + if (fetcher.platform === "twitter") { + const refusal = xJobContextRefusal(`A capture of ${opts.slug}'s posts`, `pnpm ops capture-posts --json '{"slug":"${opts.slug}","ids":[…]}' --wait`); + if (refusal) return fail(refusal); + } const avatarsOnly = opts.avatarsOnly === true; if (avatarsOnly) { const nope = avatarsOnlyProblem(fetcher.platform, fetcher.label); diff --git a/common/controller/checkPostAvailability.ts b/common/controller/checkPostAvailability.ts @@ -17,6 +17,7 @@ // checked first (the default, cheap and incremental), `unchecked` only covers // posts never looked at, `all` re-checks everything. +import { xJobContextRefusal } from "../lib/xJobRule"; import path from "node:path"; import { readChannelConfig } from "./channels"; import type { Paths } from "../lib/paths"; @@ -160,6 +161,12 @@ export async function checkPostAvailability( if (fetcher.platform === "instagram") { return { ok: false, ...empty, error: INSTAGRAM_NO_AVAILABILITY_CHECK }; } + // An X channel's check runs only as the editor's job, on X's queue + // (lib/xJobRule.ts): `pnpm archilyzer posts check` on one is refused. + if (fetcher.platform === "twitter") { + const refusal = xJobContextRefusal(`An availability check of ${slug}'s posts`, `pnpm ops check-post-availability --json '{"slug":"${slug}"}' --wait`); + if (refusal) return { ok: false, ...empty, error: refusal }; + } if (!fetcher.checkAvailability) { // Better to say so than to guess. gallery-dl, for instance, has no cheap // per-post liveness probe, so its channels should switch fetcher to sweep. diff --git a/common/controller/fetchPosts.test.ts b/common/controller/fetchPosts.test.ts @@ -740,3 +740,19 @@ test("S2: a resumed backfill whose place is in the timeline phase says it may pa assert.ok(!next.log.includes(X_TIMELINE_PHASE_PLACE_NOTE)); assert.equal(next.result.complete, true); }); + +// ── added scope R2: where X is about to be asked, only a job on X's queue stands ── + +test("R2a: an availability check of an X channel outside the editor's job is refused (the `posts check` command line's path)", async () => { + const { checkPostAvailability } = await import("./checkPostAvailability"); + const paths = (await import("../lib/paths")).getPaths(); + const { asEditorJob } = await import("../testing/jobs/asEditorJob"); + const outside = await checkPostAvailability({ paths, slug: SLUG }); + assert.equal(outside.ok, false); + assert.match(outside.error ?? "", /^An availability check of fake-x's posts asks X, and X is asked only by the editor's own jobs .*Queue it instead: pnpm ops check-post-availability/); + const elsewhere = await asEditorJob(() => checkPostAvailability({ paths, slug: SLUG }), { queueKey: "manual" }); + assert.match(elsewhere.error ?? "", /X jobs run on X's queue only \(platform:twitter\): the queue "manual" is refused/); + // On X's queue it gets as far as its own answer (this fetcher has no availability check). + const inside = await asEditorJob(() => checkPostAvailability({ paths, slug: SLUG })); + assert.doesNotMatch(inside.error ?? "", /asks X, and X/); +}); diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts @@ -94,6 +94,7 @@ import { } from "../social/instagramMedia"; import { instagramJobGuard } from "../jobs/instagramGuard"; import { currentJobContext } from "../lib/jobContext"; +import { xJobContextRefusal } from "../lib/xJobRule"; import { INSTAGRAM_QUEUE_KEY, INSTAGRAM_QUEUE_REFUSAL, isInstagramPostsChannelConfig } from "../lib/instagram/channel"; import { detectPlatform } from "../lib/platform"; import { postsMediaDir } from "../social/postCapture"; @@ -204,6 +205,7 @@ export const INSTAGRAM_ONLY_AS_A_JOB = (slug: string) => // their pacing is the fetcher's own (a forum's page pause, its browser // profile), and `posts fetch --pages N` on a forum thread is a documented way // to read without an editor (README). +const X_FETCH_DOOR = (slug: string) => `pnpm ops fetch-posts --json '{"slug":"${slug}"}' --wait`; export const X_ONLY_AS_A_JOB = (slug: string) => `${slug} is an X channel, and X is asked only by the editor's own jobs (on X's queue, spaced apart, on a fresh ` + `cookie jar, stopped by the X alert and held after a rate limit): nothing was asked. ` + @@ -407,8 +409,11 @@ export async function fetchPosts( // X: only inside a job of the editor's (X_ONLY_AS_A_JOB says why). Asked // before the search, older and timeline branches, so no mode slips past. - if (fetcher.platform === "twitter" && !currentJobContext()) { - return { ok: false, written: 0, skipped: 0, complete: false, error: X_ONLY_AS_A_JOB(slug) }; + if (fetcher.platform === "twitter") { + if (!currentJobContext()) return { ok: false, written: 0, skipped: 0, complete: false, error: X_ONLY_AS_A_JOB(slug) }; + // …and only on X's queue (added scope R2): asked where the job runs too. + const queue = xJobContextRefusal(slug, X_FETCH_DOOR(slug)); + if (queue) return { ok: false, written: 0, skipped: 0, complete: false, error: queue }; } // AN X SEARCH CHANNEL (release 38): its query across accounts, walked in diff --git a/common/controller/readXTrending.test.ts b/common/controller/readXTrending.test.ts @@ -12,6 +12,10 @@ import type { Paths } from "../lib/paths"; import { listXTrending, readXTrendingPosts, readXTrendingReadRecord } from "../lib/xTrending/store"; import { fakeTrendingPage, type FakeTrendingPage } from "../social/fakeXProfileBrowser"; import { + FIXTURE_LATEST_PAGE, + fixtureLatestContinuation, + fixtureLatestFirst, + fixtureTwoTabResponses, FIXTURE_LAST_UPDATED_MS, FIXTURE_SUMMARY, FIXTURE_TIMELINE_OP, @@ -26,14 +30,19 @@ import { NO_X_PROFILE_FOR_TRENDING, planReadXTrending, reparseXTrendingRead, - runXTrendingRead, + runXTrendingRead as runXTrendingReadDirect, type ReadXTrendingAsk, type ReadXTrendingResult, } from "./readXTrending"; +import { insideEditorJob } from "../testing/jobs/asEditorJob"; + +// X is asked only inside a job of the editor's, on X's queue (lib/xJobRule.ts): these calls stand where one does. +const runXTrendingRead = insideEditorJob(runXTrendingReadDirect); const TMP = mkdtempSync(path.join(tmpdir(), "read-x-trending-")); after(() => rmSync(TMP, { recursive: true, force: true })); +const FIXTURE_FIRST_PAGE_0 = { id: "1900000000000001001", handle: "teapot_news", name: "Teapot News", text: "The kettle festival opens today.", media: ["photo", "photo"] as Array<"photo"> }; const READ_1 = "tr-01JA0000000000000000000000"; const READ_2 = "tr-01JB0000000000000000000000"; @@ -57,7 +66,8 @@ async function run( ask: Partial<ReadXTrendingAsk> = {}, over: { readId?: string; at?: string; profileBusy?: () => string | null; held?: () => Promise<string | null>; ingest?: never; openPage?: never } = {}, ): Promise<{ result: ReadXTrendingResult; notes: Array<Record<string, unknown>>; log: string[]; limited: number; cleaned: number }> { - const planned = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL, ...ask }, withProfile); + // One tab unless a test asks for both: the page's other tab is R3's tests' (at the end). + const planned = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL, tabs: ["top"], ...ask }, withProfile); assert.ok(planned.ok, planned.ok ? "" : planned.error); assert.equal(planned.plan.mode, "read"); const notes: Array<Record<string, unknown>> = []; @@ -105,8 +115,8 @@ test("every refusal before a job is a sentence", async () => { assert.match(await error(plan({})), /Give "url" .* or "reparse"/); assert.match(await error(plan({ url: FIXTURE_TREND_URL, reparse: READ_1 })), /holds no saved read/); assert.match(await error(plan({ url: "https://x.com/example/status/1" })), /not a trending page URL/); - assert.match(await error(plan({ url: FIXTURE_TREND_URL, scrolls: 21 })), /"scrolls" is a whole number, 1–20/); - assert.match(await error(plan({ url: FIXTURE_TREND_URL, posts: 201 })), /"posts" is a whole number, 1–200/); + assert.match(await error(plan({ url: FIXTURE_TREND_URL, scrolls: 41 })), /"scrolls" is a whole number, 1–40/); + assert.match(await error(plan({ url: FIXTURE_TREND_URL, posts: 401 })), /"posts" is a whole number, 1–400/); assert.match(await error(plan({ url: FIXTURE_TREND_URL, topic: " " })), /topic/); assert.equal(await error(plan({ url: FIXTURE_TREND_URL }, { hasProfile: async () => false })), NO_X_PROFILE_FOR_TRENDING); assert.match(await error(plan({ reparse: "nope" })), /not a trending read id/); @@ -196,6 +206,8 @@ test("a re-read adds the new posts, keeps the old ones, and appends the read wit summary: FIXTURE_SUMMARY, lastUpdatedAt: new Date(FIXTURE_LAST_UPDATED_MS).toISOString(), tabs: ["Top", "Latest"], + // The second capture named only a timeline id: the source's known tabs say which tab that is. + lastReadTab: "Top", reads: 2, lastReadAt: "2026-11-17T12:00:00.000Z", }, @@ -620,13 +632,13 @@ test("the real shape: a read with no topic named makes one called by the page's assert.equal(result.outcome, "read"); assert.deepEqual(result.posts, { onPage: 6, added: 6 }); assert.deepEqual(result.topic, { id: `t-${real.INVENTED_TREND_ID}`, title: real.INVENTED_TITLE, created: true }); - assert.deepEqual(result.tabs, [{ tab: "Top", posts: 6 }]); + assert.deepEqual(result.tabs, [{ tab: "Top", asked: "top", posts: 6, scrolls: 4, stop: "idle", pageEnd: false }]); assert.equal( result.sentence, `Read ${real.INVENTED_TREND_URL}: 6 posts on the page, 6 new, in topic "${real.INVENTED_TITLE}" (t-${real.INVENTED_TREND_ID}), shown by the page's "Top" tab.`, ); const record = await readXTrendingReadRecord(root(paths), READ_1); - assert.deepEqual(record?.tabs, [{ tab: "Top", posts: 6 }]); + assert.deepEqual(record?.tabs, result.tabs); // read.json: names, labels and sizes — no timeline id, no summary, no post. const recordText = readFileSync(path.join(root(paths), "trending", "reads", READ_1, "read.json"), "utf8"); for (const never of [real.INVENTED_TOP_TIMELINE, real.INVENTED_LATEST_TIMELINE, real.INVENTED_SUMMARY, "festival opens today", "teapot_news", real.realBottomCursor(1)]) { @@ -694,7 +706,8 @@ test("the real shape: a library read before titles were parsed is put right by a const members = JSON.parse(readFileSync(membersFile(paths), "utf8")).posts as Record<string, { seen: Array<{ tab?: string }> }>; assert.ok(Object.values(members).every((m) => m.seen.length === 1 && m.seen[0].tab === "Top")); const record = await readXTrendingReadRecord(root(paths), READ_1); - assert.deepEqual(record?.tabs, [{ tab: "Top", posts: 6 }]); + // The reparse keeps what the read knew of the tab (its scrolls, why it stopped) and says again what the capture holds. + assert.deepEqual(record?.tabs, [{ tab: "Top", asked: "top", posts: 6, scrolls: 2, stop: "idle", pageEnd: false }]); assert.deepEqual(record?.topic, { id: `t-${real.INVENTED_TREND_ID}`, title: real.INVENTED_TITLE }); // A second reparse renames nothing and says nothing of a rename. assert.doesNotMatch((await reparse(paths)).sentence, /until now/); @@ -749,7 +762,7 @@ test("S3: a post first seen in an answer that named no timeline does not drop th // One more answer listing a post, whose request names no timeline at all. const stray = { url: "https://x.com/i/api/graphql/q/ExampleTrendTimeline?variables=%7B%7D", status: 200, body: fixtureTimelineBody([{ id: "1900000000000003099", handle: "stray_post", text: "Listed by an answer that names no timeline." }]) }; const { result } = await run(paths, { load: [...real.realCaptureResponses({ later: [] }), stray], scrolls: [] }, { url: real.INVENTED_TREND_URL }); - assert.deepEqual(result.tabs, [{ tab: "Top", posts: 3 }, { posts: 1 }]); + assert.deepEqual(result.tabs, [{ tab: "Top", asked: "top", posts: 3, scrolls: 2, stop: "idle", pageEnd: false }, { posts: 1, pageEnd: false }]); assert.match(result.sentence, /shown by the page's "Top" tab\.$/); const topic = JSON.parse(readFileSync(path.join(root(paths), "trending", "topics.json"), "utf8")).topics[0]; assert.equal(topic.sources[0].reads[0].tab, "Top"); @@ -757,3 +770,122 @@ test("S3: a post first seen in an answer that named no timeline does not drop th assert.equal(members["1900000000000003099"].seen[0].tab, "Top"); assert.equal(members["1900000000000003001"].seen[0].tab, "Top"); }); + +// ── added scope R3: Top and Latest in one job ────────────────────────────── + +test("R3: \"tabs\" is top, latest or both (the default); anything else is refused, and a reparse takes none", async () => { + const { xTrendingTabsAsked, X_TRENDING_TABS_PROBLEM } = await import("./readXTrending"); + assert.deepEqual(xTrendingTabsAsked(undefined), { ok: true, tabs: ["top", "latest"] }); + assert.deepEqual(xTrendingTabsAsked(["latest", "top", "TOP"]), { ok: true, tabs: ["top", "latest"] }); + assert.deepEqual(xTrendingTabsAsked(["latest"]), { ok: true, tabs: ["latest"] }); + for (const bad of [[], ["media"], "top", [1], {}]) assert.deepEqual(xTrendingTabsAsked(bad), { ok: false, error: X_TRENDING_TABS_PROBLEM }); + const paths = corpus("r3-plan"); + const plan = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL }, withProfile); + assert.ok(plan.ok && plan.plan.mode === "read"); + assert.deepEqual(plan.plan.tabs, ["top", "latest"]); + const refused = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL, tabs: ["all"] }, withProfile); + assert.deepEqual(refused, { ok: false, error: X_TRENDING_TABS_PROBLEM }); +}); + +test("R3: one job reads Top, then Latest: one capture, each post's sightings per tab, read.json tab by tab", async () => { + const paths = corpus("r3-both"); + const { result, log } = await run(paths, fixtureTwoTabResponses(), { tabs: ["top", "latest"], topic: "Kettle Festival" }); + assert.equal(result.ok, true); + assert.equal(result.outcome, "read"); + // Five posts: Top's four and the one only Latest shows. + assert.deepEqual(result.posts, { onPage: 5, added: 5 }); + assert.deepEqual(result.tabs, [ + { tab: "Top", asked: "top", posts: 4, scrolls: 3, stop: "idle", pageEnd: true }, + { tab: "Latest", asked: "latest", posts: 3, scrolls: 2, stop: "idle", pageEnd: true }, + ]); + assert.equal(result.sentence, `Read ${FIXTURE_TREND_URL}: 5 posts on the page, 5 new, in topic "Kettle Festival" (kettle-festival), shown by the page's "Top" and "Latest" tabs.`); + assert.ok(log.some((l) => /Top, then Latest/.test(l))); + const record = await readXTrendingReadRecord(root(paths), READ_1); + assert.deepEqual(record?.tabs, result.tabs); + assert.equal(record?.scrolls, 5); + assert.deepEqual(readdirSync(path.join(root(paths), "trending", "reads", READ_1)).sort(), ["page-latest.png", "page.png", "read.json", "responses.jsonl"]); + const members = JSON.parse(readFileSync(path.join(root(paths), "trending", "membership.json"), "utf8")).posts; + assert.deepEqual(members["1900000000000001001"].seen.map((s: { tab: string; rank: number }) => [s.tab, s.rank]), [["Top", 1], ["Latest", 2]]); + assert.deepEqual(members["1900000000000001009"].seen.map((s: { tab: string; rank: number }) => [s.tab, s.rank]), [["Latest", 1]]); + const listing = await listXTrending(root(paths)); + assert.deepEqual(listing.topics[0].sources[0].lastReadTabs, ["Top", "Latest"]); + // A reparse of the two-tab capture says the same of each tab and adds nothing. + const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }); + assert.ok(planned.ok && planned.plan.mode === "reparse"); + const again = await reparseXTrendingRead({ plan: planned.plan as never }); + assert.deepEqual(again.posts, { onPage: 5, added: 0 }); + assert.deepEqual(again.tabs, result.tabs); + // A probe covers both tabs too, and writes no post. + const probe = await run(corpus("r3-probe"), fixtureTwoTabResponses(), { tabs: ["top", "latest"], probe: true }); + assert.equal(probe.result.outcome, "probe"); + assert.deepEqual(probe.result.tabs?.map((t) => [t.tab, t.posts, t.stop]), [["Top", 4, "idle"], ["Latest", 3, "idle"]]); +}); + +test("R3: a Latest tab that cannot be opened ends the read \"Top read; Latest not read: <why>\" — a read, not a failure, and nothing is retried", async () => { + const never = fixtureTwoTabResponses(); + never.tabs.Latest = {}; + const paths = corpus("r3-never"); + const { result, notes } = await run(paths, never, { tabs: ["top", "latest"], topic: "Kettle Festival" }); + assert.equal(result.ok, true); + assert.equal(result.outcome, "read"); + assert.deepEqual(result.posts, { onPage: 4, added: 4 }); + assert.equal( + result.sentence, + `Read ${FIXTURE_TREND_URL}: 4 posts on the page, 4 new, in topic "Kettle Festival" (kettle-festival), shown by the page's "Top" tab. ` + + `Top read; Latest not read: pressing "Latest" brought no answer for its timeline within 20 s.`, + ); + assert.deepEqual(result.tabs?.[1], { tab: "Latest", asked: "latest", posts: 0, scrolls: 0, stop: "not-read", pageEnd: false, why: 'pressing "Latest" brought no answer for its timeline within 20 s' }); + // A clean request: the X alert it could clear is cleared, none is raised. + assert.deepEqual(notes.map((n) => n.kind), [undefined]); + // Top's read stands by itself: a later read may say what Top no longer shows. + const hidden = fixtureTwoTabResponses(); + hidden.tabs.Latest.hidden = true; + hidden.load = [hidden.load[0], { ...hidden.load[1], body: fixtureTimelineBody([FIXTURE_FIRST_PAGE_0]) }]; + hidden.scrolls = [[fixtureContinuation([], 5)], []]; + const second = await run(paths, hidden, { tabs: ["top", "latest"], topic: "Kettle Festival" }, { readId: READ_2, at: "2026-11-17T12:00:00.000Z" }); + assert.equal(second.result.outcome, "read"); + assert.deepEqual([...(second.result.gone ?? [])].sort(), ["1900000000000001002", "1900000000000001004", "1900000000000001005"]); + assert.match(second.result.sentence, /Top read; Latest not read: the page shows no tab named "Latest"\./); +}); + +test("R3: a post that leaves Latest between two reads is said gone from that tab while Top still shows it; gone from the page once Top drops it too", async () => { + const paths = corpus("r3-leaves"); + await run(paths, fixtureTwoTabResponses(), { tabs: ["top", "latest"], topic: "Kettle Festival" }); + // Second read: Latest no longer lists 1001 (Top does) nor 1009 (which only Latest showed). + const latestNow = [FIXTURE_LATEST_PAGE[2]]; + const second = await run(paths, fixtureTwoTabResponses(latestNow), { tabs: ["top", "latest"] }, { readId: READ_2, at: "2026-11-17T12:00:00.000Z" }); + assert.deepEqual(second.result.gone, ["1900000000000001009"]); + assert.deepEqual(second.result.goneFromTab, [{ id: "1900000000000001001", tab: "Latest" }]); + assert.equal( + second.result.sentence, + `Read ${FIXTURE_TREND_URL}: 4 posts on the page, 0 new, in topic "Kettle Festival" (kettle-festival), shown by the page's "Top" and "Latest" tabs. ` + + `1 post this page showed before is gone from the page at 12:00 UTC. 1 post is gone from the "Latest" tab and still shown by another.`, + ); + const listing = await listXTrending(root(paths)); + assert.deepEqual(listing.posts.find((p) => p.id === "1900000000000001001")?.goneTabs, [{ tab: "Latest", at: "2026-11-17T12:00:00.000Z", read: READ_2 }]); + assert.equal(listing.posts.find((p) => p.id === "1900000000000001001")?.gone, undefined); + // A read of Latest that was CAPPED says nothing of what Latest no longer shows. + const capped = fixtureTwoTabResponses([FIXTURE_LATEST_PAGE[0]]); + capped.tabs.Latest.scrolls = [[fixtureLatestContinuation([{ id: "1900000000000001010", handle: "lid_watch", text: "One more." }])]]; + const third = await run(paths, capped, { tabs: ["top", "latest"], scrolls: 3 }, { readId: "tr-01JC0000000000000000000000", at: "2026-11-17T13:00:00.000Z" }); + assert.deepEqual(third.result.tabs?.map((t) => [t.tab, t.pageEnd]), [["Top", true], ["Latest", false]]); + assert.equal(third.result.goneFromTab, undefined); + void fixtureLatestFirst; +}); + +// Added scope R2: where X is about to be asked, only a job on X's queue stands. +test("R2a: a trending read outside the editor's job, or in a job on another queue, opens no browser", async () => { + const { asEditorJob } = await import("../testing/jobs/asEditorJob"); + const paths = corpus("r2-outside"); + const planned = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL }, withProfile); + assert.ok(planned.ok && planned.plan.mode === "read"); + let opened = 0; + const ask = { paths, plan: planned.plan as never, deps: { openPage: async () => (opened++, assert.fail("a browser was opened")), held: async () => null } }; + const outside = await runXTrendingReadDirect(ask); + assert.equal(outside.ok, false); + assert.match(outside.sentence, /^A read of https:\/\/x\.com\/i\/trending\/\d+ asks X, and X is asked only by the editor's own jobs .*Queue it instead: pnpm ops read-x-trending/); + const elsewhere = await asEditorJob(() => runXTrendingReadDirect(ask), { queueKey: "manual" }); + assert.match(elsewhere.sentence, /X jobs run on X's queue only \(platform:twitter\): the queue "manual" is refused/); + assert.equal(opened, 0); + assert.equal(existsSync(path.join(root(paths), "trending", "reads")), false); +}); diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts @@ -69,8 +69,10 @@ import { type XTrendingReadOperation, type XTrendingReadOutcome, type XTrendingReadRecord, + type XTrendingReadTab, } from "../lib/xTrending/store"; import { ulid } from "../jobs/ulid"; +import { xJobContextRefusal } from "../lib/xJobRule"; import { readXSessionStatus } from "../social/xSessionBroker"; import { xRequestPauseMs } from "../social/xGalleryDlFetcher"; import type { ChromiumLike } from "../social/playwrightRuntime"; @@ -78,8 +80,11 @@ import { parseTrendingCapture, readCaptureLines } from "../social/xTrendingParse import { openXTrendingPage, readXTrendingPage, + TRENDING_TAB_ASKS, type TrendingPageRead, type TrendingPageSession, + type TrendingTabAsk, + type TrendingTabRead, } from "../social/xTrendingRead"; import { isValidChannelSlug, readChannelConfig } from "./channels"; @@ -128,6 +133,9 @@ export type ReadXTrendingAsk = { posts?: unknown; probe?: boolean; headed?: boolean; + // The page's tabs to read: ["top"], ["latest"] or both (the default). Both + // are read in ONE job: Top, then the page's Latest tab is pressed. + tabs?: unknown; // THIS READ IS A WATCH'S TICK (controller/xTrendingWatch.ts): nobody is // there when it starts, so the watch's own jar rule is asked again at its // start (runXTrendingRead `watchRefusal`). Set by the scan only — the ops @@ -135,6 +143,18 @@ export type ReadXTrendingAsk = { watch?: boolean; }; +// The tabs a read is asked for: "top", "latest" or both; absent, both. In the +// page's order, each once. Anything else is refused with a sentence. +export const X_TRENDING_TABS_PROBLEM = `"tabs" is ["top"], ["latest"] or ["top", "latest"] (the default: both, read in one job)`; +export function xTrendingTabsAsked(v: unknown): { ok: true; tabs: TrendingTabAsk[] } | { ok: false; error: string } { + if (v === undefined || v === null) return { ok: true, tabs: [...TRENDING_TAB_ASKS] }; + if (!Array.isArray(v) || v.length === 0 || !v.every((t) => typeof t === "string" && (TRENDING_TAB_ASKS as readonly string[]).includes(t.toLowerCase()))) { + return { ok: false, error: X_TRENDING_TABS_PROBLEM }; + } + const asked = new Set(v.map((t: string) => t.toLowerCase())); + return { ok: true, tabs: TRENDING_TAB_ASKS.filter((t) => asked.has(t)) }; +} + export type ReadXTrendingPlan = | { mode: "read"; @@ -145,6 +165,7 @@ export type ReadXTrendingPlan = topic?: string; probe: boolean; headed: boolean; + tabs: TrendingTabAsk[]; watch?: boolean; } | { mode: "reparse"; slug: string; channelRoot: string; record: XTrendingReadRecord; topic?: string }; @@ -209,8 +230,8 @@ export async function planReadXTrending( } const topic = ask.topic?.trim(); if (hasReparse) { - if (ask.probe || ask.headed || ask.scrolls !== undefined || ask.posts !== undefined) { - return fail(`"probe", "headed", "scrolls" and "posts" apply to a read of a page, not to "reparse" (which asks X nothing).`); + if (ask.probe || ask.headed || ask.scrolls !== undefined || ask.posts !== undefined || ask.tabs !== undefined) { + return fail(`"probe", "headed", "scrolls", "posts" and "tabs" apply to a read of a page, not to "reparse" (which asks X nothing).`); } if (!isXTrendingReadId(ask.reparse)) return fail(`"${String(ask.reparse)}" is not a trending read id (tr-…)`); let record = await readXTrendingReadRecord(channelRoot, ask.reparse); @@ -246,6 +267,8 @@ export async function planReadXTrending( if (!ref) return fail(NOT_A_TRENDING_URL); const limits = xTrendingLimits(config.xTrending, { scrolls: ask.scrolls, posts: ask.posts }); if (!limits.ok) return fail(limits.error); + const tabs = xTrendingTabsAsked(ask.tabs); + if (!tabs.ok) return fail(tabs.error); const hasProfile = deps.hasProfile ?? (async () => (await readXSessionStatus(paths)).hasProfile); if (!(await hasProfile())) return fail(NO_X_PROFILE_FOR_TRENDING); // X cooling down after a rate limit: refused before a job exists. @@ -262,6 +285,7 @@ export async function planReadXTrending( ...(topic ? { topic } : {}), probe: ask.probe === true, headed: ask.headed === true, + tabs: tabs.tabs, ...(ask.watch === true ? { watch: true } : {}), }, }; @@ -285,9 +309,10 @@ export type ReadXTrendingResult = { operations: XTrendingReadOperation[]; posts: { onPage: number; added: number }; topic?: { id: string; title: string; created?: boolean; renamed?: { was: string } }; - // Which tab's timeline the read saw: the page's label for it and the posts - // it showed (a read sees one tab, the one the page opens on). - tabs?: Array<{ tab?: string; posts: number }>; + // The read, tab by tab (store.ts XTrendingReadTab): the posts each listed, + // its scrolls, why it stopped, whether the capture shows its end; a tab + // asked for and not opened is "not-read" with `why`. + tabs?: XTrendingReadTab[]; // A watch's tick that was NOT read, because the watch's jar rule refused it // at the job's start: no browser opened, nothing asked of X. It is neither // a read nor a failed read (the watch counts no strike for it). @@ -297,6 +322,8 @@ export type ReadXTrendingResult = { // read that reached the page's end, and never meaning deleted. newIds?: string[]; gone?: string[]; + // Posts ONE TAB read to its end no longer shows, while another still does. + goneFromTab?: Array<{ id: string; tab: string }>; // What happened, as one sentence (the refusal, when `ok` is false). sentence: string; error?: string; @@ -326,8 +353,10 @@ type Ingested = { // the page's end — the posts the page showed before and not now. newIds?: string[]; gone?: string[]; - // Which tab's timeline the capture lists (store.ts XTrendingReadRecord.tabs). - tabs?: Array<{ tab?: string; posts: number }>; + // Posts a tab read to its end no longer shows while another tab still does. + goneFromTab?: Array<{ id: string; tab: string }>; + // Tab by tab (store.ts XTrendingReadRecord.tabs). + tabs?: XTrendingReadTab[]; }; // The tab a capture's posts are the page's, when its timelines name exactly one. @@ -339,11 +368,29 @@ export function readTabOf(timelines: ReadonlyArray<{ tab?: string }>): string | // `, shown by the page's "Top" tab` — what a read saw, in a sentence; "" when the // capture does not say. function tabText(tabs: Ingested["tabs"]): string { - const named = (tabs ?? []).filter((t) => t.tab); + // The tabs that listed posts (one asked for and not read listed none). + const named = (tabs ?? []).filter((t) => t.tab && t.stop !== "not-read" && (t.posts > 0 || t.stop !== undefined)); if (named.length === 0) return ""; return `, shown by the page's ${named.map((t) => `"${t.tab}"`).join(" and ")} tab${named.length === 1 ? "" : "s"}`; } +// "Top read; Latest not read: <why>." — a tab that was asked for and could +// not be opened. Not a failure: what the other tab showed stands. +function notReadText(tabs: Ingested["tabs"]): string { + const missed = (tabs ?? []).filter((t) => t.stop === "not-read"); + if (missed.length === 0) return ""; + const read = (tabs ?? []).filter((t) => t.tab && t.stop !== "not-read" && t.stop !== "not-asked").map((t) => t.tab); + return ` ${read.length ? `${read.join(" and ")} read; ` : ""}${missed.map((t) => `${t.tab ?? (t.asked === "latest" ? "Latest" : "Top")} not read: ${t.why ?? "it could not be opened"}`).join("; ")}.`; +} + +// "2 posts are gone from the "Latest" tab and still shown by another." +function goneFromTabText(goneFromTab: Ingested["goneFromTab"]): string { + if (!goneFromTab?.length) return ""; + const by = new Map<string, number>(); + for (const g of goneFromTab) by.set(g.tab, (by.get(g.tab) ?? 0) + 1); + return [...by].map(([tab, count]) => ` ${plural(count, "post")} ${count === 1 ? "is" : "are"} gone from the "${tab}" tab and still shown by another.`).join(""); +} + // A topic that took the page's title in this pass, said once. function renamedText(topic: Ingested["topic"]): string { return topic?.renamed ? ` The topic was "${topic.renamed.was}" until now: it took the page's title.` : ""; @@ -359,24 +406,70 @@ 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; + // THE READ, TAB BY TAB (the page reader's): which tabs were scrolled and why + // each stopped. A tab is read to its end — the only read that may say a + // post is gone from it — when its scrolling went idle, no answer of the + // read failed (`clean`), and the capture itself shows that timeline's end. + // Absent for a reparse, which says nothing of what a page no longer shows. + pageTabs?: ReadonlyArray<TrendingTabRead>; + clean?: boolean; + // A reparse: the tabs the read's record already has (their scrolls and stops are kept). + recordedTabs?: ReadonlyArray<XTrendingReadTab>; }): 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 tabs = parsed.timelines.map((t) => ({ ...(t.tab ? { tab: t.tab } : {}), posts: t.posts })); + const named = parsed.timelines.filter((t) => t.timelineId); + const untagged = parsed.timelines.find((t) => !t.timelineId); + const scrolled = (timelineId: string | undefined) => o.pageTabs?.find((t) => t.timelineId !== undefined && t.timelineId === timelineId); + // What read.json says, tab by tab: the reader's tabs in the order it read + // them (with what the capture holds of each), then any timeline the capture + // lists that the reader did not name. + const tabs: XTrendingReadTab[] = []; + // The timeline each entry is of (never written: read.json holds labels). + const timelineOf = new Map<XTrendingReadTab, string>(); + const said = new Set<string>(); + for (const t of o.pageTabs ?? []) { + const listed = t.timelineId ? named.find((x) => x.timelineId === t.timelineId) : named.length === 0 ? untagged : undefined; + if (t.timelineId) said.add(t.timelineId); + const entry: XTrendingReadTab = { + ...(t.tab ?? listed?.tab ? { tab: t.tab ?? listed?.tab } : {}), + asked: t.asked, + posts: listed?.postIds.length ?? 0, + scrolls: t.scrolls, + stop: t.stop, + pageEnd: Boolean(listed?.pageEnd), + ...(t.why ? { why: t.why } : {}), + }; + if (t.timelineId) timelineOf.set(entry, t.timelineId); + tabs.push(entry); + } + const unnamedByReader = (o.pageTabs ?? []).some((t) => !t.timelineId) && named.length === 0; + for (const t of parsed.timelines) { + if (t.timelineId ? said.has(t.timelineId) : unnamedByReader) continue; + const before = o.recordedTabs?.find((r) => r.tab !== undefined && r.tab === t.tab); + const entry: XTrendingReadTab = { + ...(t.tab ? { tab: t.tab } : {}), + ...(before?.asked ? { asked: before.asked } : {}), + posts: t.postIds.length, + ...(before?.scrolls !== undefined ? { scrolls: before.scrolls } : {}), + ...(before?.stop ? { stop: before.stop } : {}), + pageEnd: t.pageEnd, + ...(before?.why ? { why: before.why } : {}), + }; + if (t.timelineId) timelineOf.set(entry, t.timelineId); + tabs.push(entry); + } + // A tab the record says was not read stays said (a reparse cannot know it otherwise). + for (const r of o.recordedTabs ?? []) { + if (r.stop === "not-read" && !tabs.some((t) => t.tab === r.tab && t.asked === r.asked)) tabs.push({ ...r, posts: 0, pageEnd: false }); + } const base = { operations: parsed.operations, responses: parsed.responses, onPage: parsed.posts.length, ...(tabs.length ? { tabs } : {}), }; - // The ONE tab this capture names (review 1 S3): a post first seen in an - // answer whose request named no timeline does not drop the read's tab — it - // inherits it (store.ts), and only when exactly one tab was named. - const tab = readTabOf(parsed.timelines); 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)); @@ -386,11 +479,26 @@ async function ingestCapture(o: { const byId = new Map((await readXTrendingPosts(o.channelRoot)).map((p) => [p.id, p])); const threads: Record<string, string> = {}; for (const p of parsed.posts) threads[p.id] = xTrendingThreadKey(byId.get(p.id) ?? p, byId); + // THE TABS' READS: each named timeline's posts in its own order, and whether + // it was read to its end. Posts an answer listed without naming a timeline + // (review 1 S3) go with the ONE named tab when there is exactly one (they + // never make it complete or incomplete), else stand by themselves. + const tabReads = named.map((t) => { + const tab = scrolled(t.timelineId); + const complete = Boolean(o.clean && t.pageEnd && tab?.stop === "idle"); + return { ...(t.tab ? { tab: t.tab } : {}), timelineId: t.timelineId!, postIds: [...t.postIds], ...(complete ? { complete: true } : {}) }; + }); + if (untagged) { + if (tabReads.length === 1) tabReads[0].postIds.push(...untagged.postIds.filter((id) => !tabReads[0].postIds.includes(id))); + else if (tabReads.length === 0) { + // No request named a timeline (a page from before tabs were read): the opening tab's, whatever it is called. + const only = (o.pageTabs ?? []).length <= 1 ? o.pageTabs?.[0] : undefined; + const complete = Boolean(o.clean && untagged.pageEnd && only?.stop === "idle"); + tabReads.push({ timelineId: "", postIds: [...untagged.postIds], ...(complete ? { complete: true } : {}) }); + } else tabReads.push({ timelineId: "", postIds: [...untagged.postIds] }); + } const recorded = await recordXTrendingRead(o.channelRoot, { threads, - // Only when the scrolling stopped at the page's end AND the capture shows - // it (review 1 S2: "idle" alone also follows a next page that failed). - ...(o.complete && parsed.pageEnd ? { complete: true } : {}), readId: o.readId, at: o.at, ref: o.ref, @@ -399,10 +507,21 @@ async function ingestCapture(o: { added: written.written, media: parsed.media, ...(parsed.page ? { page: parsed.page } : {}), - ...(tab ? { tab } : {}), - tabs: parsed.tabs, + tabReads: tabReads.map(({ timelineId, ...t }) => ({ ...t, ...(timelineId ? { timelineId } : {}) })), }); - return { ...base, added: written.written, topic: recorded.topic, newIds, gone: recorded.gone }; + // The labels the source knew for timelines the capture itself did not name. + for (const t of tabs) { + const label = recorded.tabLabels?.[timelineOf.get(t) ?? ""]; + if (!t.tab && label) t.tab = label; + } + return { + ...base, + added: written.written, + topic: recorded.topic, + newIds, + gone: recorded.gone, + ...(recorded.goneFromTab?.length ? { goneFromTab: recorded.goneFromTab } : {}), + }; } export type ReadXTrendingDeps = { @@ -456,6 +575,10 @@ export async function runXTrendingRead(o: { const none = { responses: 0, operations: [], posts: { onPage: 0, added: 0 } }; // A Connect or a Refresh holds the profile: asked again here, at the start. + // X is asked only by the editor's jobs, on X's queue (lib/xJobRule.ts): + // asked here, where the browser is about to be opened. + const outside = xJobContextRefusal(`A read of ${plan.ref.url}`, `pnpm ops read-x-trending --json '{"slug":"${plan.slug}","url":"${plan.ref.url}"}' --wait`); + if (outside) return { ...base, ...none, ok: false, outcome: "error", sentence: outside, error: outside }; const busy = deps.profileBusy?.() ?? null; if (busy) return { ...base, ...none, ok: false, outcome: "error", sentence: busy, error: busy }; if (plan.watch) { @@ -503,7 +626,8 @@ export async function runXTrendingRead(o: { await writeXTrendingReadRecord(plan.channelRoot, started); log( `Reading ${plan.ref.url} for ${plan.slug} (${plan.headed ? "in a window" : "headless"}; ` + - `at most ${plural(plan.limits.scrolls, "scroll")}, ${plural(plan.limits.posts, "post")})` + + `at most ${plural(plan.limits.scrolls, "scroll")}, ${plural(plan.limits.posts, "post")} per tab; ` + + `${plan.tabs.length === 2 ? "Top, then Latest" : plan.tabs[0] === "latest" ? "Latest only" : "Top only"})` + (plan.probe ? " — a probe: the capture is saved, no post is written." : ".") + (plan.watch ? " A watch's tick." : ""), ); @@ -520,6 +644,7 @@ export async function runXTrendingRead(o: { ...(deps.chromium ? { chromium: deps.chromium } : {}), })), limits: plan.limits, + tabs: plan.tabs, pauseMs: deps.pauseMs ?? (() => xRequestPauseMs()), ...(deps.pause ? { pause: deps.pause } : {}), signal, @@ -543,13 +668,12 @@ export async function runXTrendingRead(o: { ref: plan.ref, ...(plan.topic ? { topic: plan.topic } : {}), write: !plan.probe && !walled, - // "idle": two scrolls brought no new post — the page's end, OR a next - // page that did not load. So also: no answer that failed, none that was - // not kept; and the capture itself must show the end (ingestCapture). - complete: - page.stop === "idle" && - page.saved === page.responses && - Object.keys(page.statuses).every((status) => /^2\d\d$/.test(status)), + // A tab's "idle" is two scrolls that brought no new post: its end, OR a + // next page that did not load. So also: no answer that failed, none + // that was not kept (`clean`); and the capture itself must show that + // tab's end (ingestCapture). + pageTabs: page.tabs, + clean: page.saved === page.responses && Object.keys(page.statuses).every((status) => /^2\d\d$/.test(status)), }); } catch (err) { ingestError = ((err as Error)?.message ?? String(err)).split("\n")[0]; @@ -636,10 +760,12 @@ export async function runXTrendingRead(o: { `in topic "${ingested.topic?.title}" (${ingested.topic?.id})` + tabText(ingested.tabs) + (page.stop === "cancelled" ? "; the read was stopped early." : ".") + + notReadText(ingested.tabs) + renamedText(ingested.topic) + (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.` - : ""); + : "") + + goneFromTabText(ingested.goneFromTab); // 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); @@ -690,6 +816,7 @@ export async function runXTrendingRead(o: { ...(ingested.tabs ? { tabs: ingested.tabs } : {}), ...(ingested.newIds?.length ? { newIds: ingested.newIds } : {}), ...(ingested.gone?.length ? { gone: ingested.gone } : {}), + ...(ingested.goneFromTab?.length ? { goneFromTab: ingested.goneFromTab } : {}), sentence, ...(ok ? {} : { error: sentence }), }; @@ -742,6 +869,7 @@ export async function reparseXTrendingRead(o: { ref, ...(plan.topic ? { topic: plan.topic } : {}), write: !walled, + ...(record.tabs ? { recordedTabs: record.tabs } : {}), }); const kept = captureAt(record.id); let outcome: XTrendingReadOutcome; diff --git a/common/controller/xRun.ts b/common/controller/xRun.ts @@ -665,6 +665,8 @@ export function defaultXRunDeps(paths: Paths, jobId: string): XRunDeps { paths, channelSlug: slug, job: { id: jobId }, + // Each channel's fetch is one X job against X's job cap. + countStart: true, }); return res.ok ? { ok: true, notes: res.notes } : { ok: false, error: res.error }; }, diff --git a/common/controller/xTrendingCooldown.test.ts b/common/controller/xTrendingCooldown.test.ts @@ -47,7 +47,10 @@ test("no cooldown: a read may start; after a 429: refused until the minute it na test("N4: a clean read leaves the download lane's X backoff exactly as it was", async () => { const { mkdirSync, writeFileSync: write } = await import("node:fs"); const { recordDownloadBackoff } = await import("../jobs/downloadBackoff"); - const { planReadXTrending, runXTrendingRead } = await import("./readXTrending"); + const { planReadXTrending, runXTrendingRead: runXTrendingReadDirect } = await import("./readXTrending"); + // X is asked only inside a job of the editor's, on X's queue (lib/xJobRule.ts): these calls stand where one does. + const { insideEditorJob } = await import("../testing/jobs/asEditorJob"); + const runXTrendingRead = insideEditorJob(runXTrendingReadDirect); const { fakeTrendingPage } = await import("../social/fakeXProfileBrowser"); const { FIXTURE_TREND_URL, fixtureTrendingResponses } = await import("../social/__fixtures__/xTrendingCapture"); const paths = getPaths(); diff --git a/common/controller/xTrendingWatch.test.ts b/common/controller/xTrendingWatch.test.ts @@ -386,6 +386,8 @@ test("M1: the watch asks a jar under its limit whatever the source, the setting maxAgeMinutes: 60, ageChecked: true, alert: null, + login: "profile", + cap: { lastHour: 0, perHour: 12, lastDay: 0, perDay: 150, reached: false }, // What the guard says of a person's job: allowed, in every case below. allowed: true, reason: null, @@ -396,6 +398,13 @@ test("M1: the watch asks a jar under its limit whatever the source, the setting const old = new Date(now - 3 * 60 * MIN).toISOString(); // The control: a fresh jar ticks. assert.equal(await ask({}), null); + // Added scope R2: X's job cap is reached — a pause like a cooldown's (the tick is skipped, no strike, it goes on by itself), not the jar's. + const cap = "X's job cap is reached for this login: 12 X jobs started in the last 60 minutes (the cap is 12). The next X job may start at 13:00 UTC (in 4 min); …"; + assert.deepEqual(await ask({ allowed: false, reason: cap, cap: { lastHour: 12, perHour: 12, lastDay: 12, perDay: 150, reached: true } } as never), { reason: "cooldown", sentence: cap }); + assert.deepEqual(await ask({ allowed: false, reason: "X's job count cannot be read (f): no X job starts while it is unreadable", cap: { lastHour: 0, perHour: 12, lastDay: 0, perDay: 150, reached: true, unreadable: true } } as never), { + reason: "cooldown", + sentence: "X's job count cannot be read (f): no X job starts while it is unreadable", + }); // Exemption 1: the login comes from the browser — the guard cannot read its age and lets a job through. const browser = await ask({ source: "browser", ageChecked: false, cookiesUpdatedAt: old, ageMinutes: 180 }); assert.equal(browser?.reason, "jar"); diff --git a/common/controller/xTrendingWatch.ts b/common/controller/xTrendingWatch.ts @@ -68,7 +68,8 @@ 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 }; +// `tabs`: the one tab the watch reads, when it does not read both. +export type WatchTick = { slug: string; topic: string; url: string; trendId: string; tabs?: Array<"top" | "latest"> }; export type WatchScanDeps = { paths: Paths; @@ -169,6 +170,12 @@ export async function watchRefusal(paths: Paths, slug: string, now: number, deps sentence: `X cookies were last refreshed ${ageText(now - written)} ago (limit ${limit} min for a watch): press Refresh cookies (or Connect X account) on /cookies.`, }; } + // X'S JOB CAP IS REACHED (lib/xJobRule.ts): like a cooldown — the tick is + // skipped, the watch waits, and it goes on by itself once the cap has room. + // Not the jar's fault and not a failed read. + if (!report.allowed && report.cap.reached && report.alert === null && /^X's job (cap|count)/.test(report.reason ?? "")) { + return { reason: "cooldown", sentence: report.reason ?? "X's job cap is reached." }; + } // Whatever else the guard would refuse a person's job for. if (!report.allowed) return { reason: "jar", sentence: report.reason ?? "X's cookie jar is past its limit." }; const held = await (deps.held ?? xTrendingHeld)(paths, now); @@ -324,7 +331,7 @@ export async function scanXTrendingWatches(deps: WatchScanDeps): Promise<WatchSc 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 tick: WatchTick = { slug: pick.slug, topic: pick.topic.id, url: page.url, trendId: page.trendId, ...(pick.watch.tabs ? { tabs: pick.watch.tabs } : {}) }; 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) => { diff --git a/common/controller/xTrendingWatchJob.test.ts b/common/controller/xTrendingWatchJob.test.ts @@ -21,7 +21,10 @@ const { guardNetworkJob } = await import("../jobs/networkGuard"); const { recordXTrendingRead, readXTrendingTopics, writeXTrendingPosts } = await import("../lib/xTrending/store"); const { readXTrendingWatches, setXTrendingWatch } = await import("../lib/xTrending/watch"); const { refuseWatchJob, noteXTrendingWatchRead } = await import("./xTrendingWatch"); -const { planReadXTrending, runXTrendingRead } = await import("./readXTrending"); +const { planReadXTrending, runXTrendingRead: runXTrendingReadDirect } = await import("./readXTrending"); +// X is asked only inside a job of the editor's, on X's queue (lib/xJobRule.ts): these calls stand where one does. +const { insideEditorJob } = await import("../testing/jobs/asEditorJob"); +const runXTrendingRead = insideEditorJob(runXTrendingReadDirect); const { FIXTURE_TREND_ID, FIXTURE_TREND_URL } = await import("../social/__fixtures__/xTrendingCapture"); const paths = getPaths(); diff --git a/common/jobs/instagramSchedule.test.ts b/common/jobs/instagramSchedule.test.ts @@ -72,3 +72,25 @@ test("an Instagram channel told only by its URL (no platform in its config) is h // Its cadence is Instagram's too. assert.equal(view[0]!.intervalMinutes, 720); }); + +// Added scope R2 (lane x-followups): X's job cap is reached — the scheduler skips X's channels, like a cooldown. +test("R2b: while X's job cap is reached every X posts channel is skipped with the sentence and takes no slot; Instagram is not X's business", async () => { + const { xSyncHold } = await import("./syncScheduler"); + const CAP = "X's job cap is reached for this login: 12 X jobs started in the last 60 minutes (the cap is 12). The next X job may start at 13:00 UTC (in 4 min); …"; + const r = selectDueChannels({ ...base, xCapHeld: CAP }); + assert.ok(!r.due.includes("x-chan")); + assert.ok(r.due.includes("ig-ready")); + assert.deepEqual(r.skipped.filter((s) => s.slug === "x-chan"), [{ slug: "x-chan", reason: CAP }]); + const view = buildScheduleView({ ...base, xCapHeld: CAP }); + const x = view.find((v) => v.slug === "x-chan")!; + assert.deepEqual([x.autoSyncEligible, x.heldReason], [false, CAP]); + assert.equal(view.find((v) => v.slug === "ig-ready")!.autoSyncEligible, true); + // With room under the cap nothing is held. + assert.ok(selectDueChannels(base).due.includes("x-chan")); + // The predicate: an X posts channel by its platform or its URL; never a video channel. + assert.equal(xSyncHold({ sourceKind: "social", platform: "twitter" }, CAP), CAP); + assert.equal(xSyncHold({ sourceKind: "social", url: "https://x.com/example" }, CAP), CAP); + assert.equal(xSyncHold({ sourceKind: "social", platform: "bluesky" }, CAP), null); + assert.equal(xSyncHold({ sourceKind: "video", url: "https://x.com/example" } as never, CAP), null); + assert.equal(xSyncHold({ sourceKind: "social", platform: "twitter" }, null), null); +}); diff --git a/common/jobs/networkGuard.ts b/common/jobs/networkGuard.ts @@ -47,13 +47,21 @@ import { } from "../social/xSessionBroker"; import { resolveXCookieSource, xMaxCookieAgeMinutes, type XCookieSource } from "../social/xCookieSource"; import { jobKindLabel, kindIsNetwork } from "./jobKinds"; -import { queueGapPlatform } from "./queueGap"; +import { xLoginKey, xQueueRefusal } from "../lib/xJobRule"; +import { recordXJobStart, xJobCapStatus } from "../lib/xJobCap-server"; +import { queueGapClock, queueGapPlatform } from "./queueGap"; export type NetworkJobOpts = { kind: string; queueKey: string; paths: Paths; channelSlug?: string; + // THE LAST GUARD BEFORE THE JOB'S WORK (jobs/streamCommand.ts; an X run's + // guard before each channel): an X job that passes it is COUNTED against + // X's job cap (lib/xJobRule.ts), checked and recorded in one step. The + // guards before it — at enqueue, and at the start before the queue's gap — + // only look. + countStart?: boolean; }; // ── 1. the empty queue ───────────────────────────────────────────────────── @@ -89,6 +97,19 @@ export async function networkJobPlatform(opts: NetworkJobOpts): Promise<string | } } +// Whether a job asks X: its queue is X's, OR its channel is on X. Both are +// asked (lane x-followups, R2): a job moved to another platform's queue used +// to be taken for that platform's and met none of X's rules. +export async function jobAsksX(opts: NetworkJobOpts): Promise<boolean> { + if (queueGapPlatform(opts.queueKey) === "twitter") return true; + if (!opts.channelSlug) return false; + try { + return (await channelPlatform(opts.paths, opts.channelSlug)) === "twitter"; + } catch { + return false; + } +} + // ── 2 + 3. X ─────────────────────────────────────────────────────────────── // "16 days", "3 h", "45 min". @@ -179,9 +200,11 @@ async function channelCookieSpec(paths: Paths, slug: string | undefined, setting return resolveCookiePolicy(settings, config).cookies; } +// `login`: the X login the job would use, as X's job count names it. +// `capped`: the refusal is the job cap's (no cookie banner is raised for it). export type XGuardResult = - | { ok: true; note?: string } - | { ok: false; message: string; alert: boolean }; + | { ok: true; note?: string; login: string } + | { ok: false; message: string; alert: boolean; capped?: true }; // WHAT AN X JOB WOULD BE TOLD NOW, and why — the fresh-jar rule's inputs and // its verdict in one record, for `pnpm ops get x-session` (an agent asks it @@ -207,6 +230,11 @@ export type XSessionReport = { ageChecked: boolean; // The X cookie alert, when it is up (a challenge or a login wall). alert: { raisedAt: string; line: string } | null; + // X'S JOB CAP (lib/xJobRule.ts): the login the count is kept for, the X + // jobs started in the last 60 minutes and 24 hours, the caps (constants of + // the code), and — when the cap is reached — when the next may start. + login: string; + cap: { lastHour: number; perHour: number; lastDay: number; perDay: number; reached: boolean; nextAt?: string; unreadable?: true }; // Would an X job start now? `reason` is the refusal it would get. allowed: boolean; reason: string | null; @@ -230,7 +258,25 @@ export async function xSessionReport(opts: { const ageMinutes = status.cookiesUpdatedAt ? Math.max(0, Math.floor((now - Date.parse(status.cookiesUpdatedAt)) / 60_000)) : null; + const login = xLoginKey(resolved.source, resolved.browserSpec); + // The count's clock is the queue gap's (jobs/queueGap.ts): the two rules + // that space X jobs read one clock. + const capStatus = await xJobCapStatus(opts.paths, login, opts.now ?? queueGapClock().now()); + const cap = { + lastHour: capStatus.lastHour, + perHour: capStatus.perHour, + lastDay: capStatus.lastDay, + perDay: capStatus.perDay, + reached: !capStatus.ok, + ...(capStatus.nextAt !== undefined ? { nextAt: new Date(capStatus.nextAt).toISOString() } : {}), + ...(capStatus.unreadable ? { unreadable: true as const } : {}), + }; + // The cap refuses whatever else would let the job through. + const capped = <T extends { allowed: boolean; reason: string | null }>(r: T): T => + r.allowed && !capStatus.ok ? { ...r, allowed: false, reason: capStatus.sentence ?? "X's job cap is reached." } : r; const base = { + login, + cap, source: resolved.source, sourceChosen: resolved.chosen, ...(resolved.browserSpec ? { browserSpec: resolved.browserSpec } : {}), @@ -261,21 +307,31 @@ export async function xSessionReport(opts: { }; } // Settings unreadable: the guard has nothing to apply and lets the job run. - if (!settings) return { ...base, alert: null, allowed: true, reason: null }; + if (!settings) return capped({ ...base, alert: null, allowed: true, reason: null }); const verdict = xJarVerdict({ source: resolved.source, status, maxAgeMinutes, now }); return verdict.ok - ? { ...base, alert: null, allowed: true, reason: null, ...(verdict.note ? { note: verdict.note } : {}) } + ? capped({ ...base, alert: null, allowed: true, reason: null, ...(verdict.note ? { note: verdict.note } : {}) }) : { ...base, alert: null, allowed: false, reason: verdict.message }; } +// Why no X job starts now BECAUSE OF X'S JOB CAP (or its unreadable count), +// or null: for the scheduler, which then skips X's channels rather than +// queue syncs that would each be refused. +export async function xCapHeldReason(paths: Paths, now?: number): Promise<string | null> { + const r = await xSessionReport({ paths, ...(now !== undefined ? { now } : {}) }); + if (!r.cap.reached) return null; + return (await xJobCapStatus(paths, r.login, now ?? queueGapClock().now())).sentence ?? "X's job cap is reached."; +} + export async function xJobGuard(opts: { paths: Paths; channelSlug?: string; now?: number; }): Promise<XGuardResult> { const r = await xSessionReport(opts); - if (r.allowed) return r.note ? { ok: true, note: r.note } : { ok: true }; - return { ok: false, message: r.reason ?? "X job refused.", alert: r.alert !== null }; + if (r.allowed) return { ok: true, login: r.login, ...(r.note ? { note: r.note } : {}) }; + const capped = r.cap.reached && r.alert === null && r.reason !== null && /^X's job (cap|count)/.test(r.reason); + return { ok: false, message: r.reason ?? "X job refused.", alert: r.alert !== null, ...(capped ? { capped: true as const } : {}) }; } // ── the one entry point ──────────────────────────────────────────────────── @@ -289,8 +345,18 @@ type PlatformGuard = (opts: NetworkJobOpts & { job?: { id: string } }) => Promis // X's (rules 2 and 3 above). async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promise<NetworkGuardResult> { + // X's queue only, whatever the job and whoever named the queue. + const queue = xQueueRefusal(`${jobKindLabel(opts.kind)}${opts.channelSlug ? ` for ${opts.channelSlug}` : ""}`, opts.queueKey); + if (queue) return { ok: false, error: queue }; const x = await xJobGuard({ paths: opts.paths, channelSlug: opts.channelSlug }); if (x.ok) { + // THE START, COUNTED: checked and recorded in one step. An X run's own + // start asks X nothing: each of its channels is a start (it is guarded, + // with its slug, before each one). + if (opts.countStart && opts.job && !(opts.kind === "x-run" && !opts.channelSlug)) { + const counted = await recordXJobStart(opts.paths, x.login, queueGapClock().now()); + if (!counted.ok) return { ok: false, error: counted.sentence ?? "X's job cap is reached." }; + } // The jar passed at a job's START: a jar-age banner from an earlier // refusal clears. (Not at enqueue — the start follows, and enqueue stays // as cheap as it was.) @@ -299,7 +365,7 @@ async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promi } if (x.alert && opts.job) { await noteServiceStoppedJob(opts.paths, X_SERVICE, { id: opts.job.id, kind: opts.kind }); - } else if (!x.alert) { + } else if (!x.alert && !x.capped) { // The fresh-jar rule refused it: X's cookie banner says so on the // dashboard (kind jar-age), and a job refused at its start is offered for // "Re-run stopped jobs" once the jar is fresh. @@ -338,7 +404,8 @@ export async function guardNetworkJob( if (!kindIsNetwork(opts.kind)) return { ok: true, notes: [] }; const empty = emptyQueueRefusal(opts.kind, opts.queueKey); if (empty) return { ok: false, error: empty }; - const platform = await networkJobPlatform(opts); + // A job that asks X meets X's guard whatever queue it is on. + const platform = (await jobAsksX(opts)) ? "twitter" : await networkJobPlatform(opts); const guard = platform && Object.hasOwn(PLATFORM_GUARDS, platform) ? PLATFORM_GUARDS[platform] : undefined; return guard ? guard(opts) : { ok: true, notes: [] }; } diff --git a/common/jobs/pacingGuard.test.ts b/common/jobs/pacingGuard.test.ts @@ -82,6 +82,7 @@ const { runManagedFunction } = await import("./streamCommand"); const { fetchPosts } = await import("../controller/fetchPosts"); const { getSettings } = await import("../lib/settings"); const { setQueueGapClock, clearQueueGaps } = await import("./queueGap"); +const { xJobStartsFile } = await import("../lib/xJobCap-server"); const { readServiceCookieState, serviceCookiesFile } = await import("../lib/serviceCookies-server"); await import("../social/xGalleryDlFetcher"); @@ -126,6 +127,8 @@ async function reset(): Promise<void> { await rm(RUNS, { force: true }); await rm(serviceCookiesFile(paths), { force: true }); await rm(path.join(paths.jobsDir, "queue-gaps.json"), { force: true }); + // X's job count (lib/xJobCap-server.ts): each test starts from none. + await rm(xJobStartsFile(paths), { force: true }); } async function readLog(jobId: string): Promise<string> { @@ -322,7 +325,7 @@ test("get x-session reports what the guard would answer: source, age, limit, all assert.equal(fresh.allowed, true); assert.equal(fresh.reason, null); assert.equal(fresh.profileDir, path.join(transcripts, ".x-session", "profile")); - assert.deepEqual(await xJobGuard({ paths }), { ok: true }); + assert.deepEqual(await xJobGuard({ paths }), { ok: true, login: "profile" }); await writeJar(2 * 60 * 60_000); const stale = await xSessionReport({ paths }); @@ -345,3 +348,108 @@ test("a network job is never run unqueued: the override \"\" is refused", async assert.equal(local.ok, true); if (local.ok) assert.equal((await local.done).status, "done"); }); + +// ── added scope R2 (lane x-followups): X's queue only, and X's job cap ───── + +const { guardNetworkJob, jobAsksX, xSessionReport: xReport } = await import("./networkGuard"); +const { recordXJobStart, xJobCapStatus } = await import("../lib/xJobCap-server"); +const { xQueueRefusal } = await import("../lib/xJobRule"); +const { runInJobContext } = await import("../lib/jobContext"); + +test("R2a: a job that asks X is refused on any queue but X's — at enqueue for every kind, and where it runs", async () => { + await reset(); + await writeJar(5 * 60_000); + const before = await runCount(); + // A named queue, another platform's queue: no job is made. + for (const queueKey of ["manual", "platform:youtube", "x-second-lane"]) { + const res = await fetchJob(SLUGS[0], new Map(), queueKey); + assert.equal(res.ok, false, queueKey); + assert.equal(res.ok ? "" : res.error, xQueueRefusal(`Fetch posts for ${SLUGS[0]}`, queueKey) ?? "?"); + } + // Every kind that asks X, by its channel: the queue it was moved to no longer hides that it is X's. + for (const kind of ["fetch-posts", "capture-posts", "check-post-availability", "import-post"]) { + assert.equal(await jobAsksX({ kind, queueKey: "manual", paths, channelSlug: SLUGS[0] }), true); + const g = await guardNetworkJob({ kind, queueKey: "platform:youtube", paths, channelSlug: SLUGS[0] }); + assert.equal(g.ok, false, kind); + assert.match(g.ok ? "" : g.error, /asks X, and X jobs run on X's queue only \(platform:twitter\): the queue "platform:youtube" is refused/); + } + // …and the kinds that have no channel are X's by their queue (a trending read, an X run). + assert.equal(await jobAsksX({ kind: "read-x-trending", queueKey: "platform:twitter", paths }), true); + assert.equal(await jobAsksX({ kind: "download-missing", queueKey: "platform:youtube", paths }), false); + // WHERE IT RUNS: a job that is on another queue anyway (a context made by hand) is refused by the fetch itself. + const ran = await runInJobContext({ jobId: "by-hand", kind: "fetch-posts", queueKey: "manual", onLog: () => {}, staleServices: new Set() }, () => + fetchPosts({ paths, slug: SLUGS[0], settings: getSettings() }), + ); + assert.equal(ran.ok, false); + assert.match(ran.error ?? "", /X jobs run on X's queue only \(platform:twitter\): the queue "manual" is refused\..* Nothing was asked\.$/); + assert.equal(await runCount(), before, "gallery-dl was never started"); +}); + +test("R2b: X's job cap — the 13th X job in an hour is refused before it starts, over every kind together, and get x-session shows the count", async () => { + await reset(); + await writeJar(5 * 60_000); + const before = await runCount(); + // Eleven starts on record, of whatever kinds; then one fetch through the funnel is the twelfth. + for (let i = 0; i < 11; i++) await recordXJobStart(paths, "profile", fakeNow); + const twelfth = await fetchJob(SLUGS[0], new Map()); + assert.equal(twelfth.ok, true, twelfth.ok ? "" : twelfth.error); + if (twelfth.ok) assert.equal((await twelfth.done).status, "done"); + assert.equal((await xJobCapStatus(paths, "profile", fakeNow)).lastHour, 12); + // The thirteenth, of ANOTHER kind: refused at enqueue, no job at all, with when the next may start. + for (const [kind, slug] of [["fetch-posts", SLUGS[1]], ["capture-posts", SLUGS[1]], ["check-post-availability", SLUGS[2]], ["import-post", SLUGS[2]], ["read-x-trending", undefined], ["x-run", undefined]] as const) { + const res = await runManagedFunction({ kind, queueKey: "platform:twitter", paths, ...(slug ? { channelSlug: slug } : {}), fn: async () => assert.fail("the job ran") }); + assert.equal(res.ok, false, kind); + assert.match(res.ok ? "" : res.error, /^X's job cap is reached for this login: 12 X jobs started in the last 60 minutes \(the cap is 12\)\. The next X job may start at \d\d:\d\d UTC \(in \d+ min\); ask again then/, kind); + } + assert.equal(await runCount(), before + 1); + // The cap raises no cookie banner: it is not the jar's fault. + assert.equal((await readServiceCookieState(paths)).services.x?.raisedAt, undefined); + // get x-session: the count, the caps, and the refusal. + const report = await xReport({ paths }); + assert.equal(report.login, "profile"); + assert.equal(report.allowed, false); + assert.deepEqual({ ...report.cap, nextAt: typeof report.cap.nextAt }, { lastHour: 12, perHour: 12, lastDay: 12, perDay: 150, reached: true, nextAt: "string" }); + assert.match(report.reason ?? "", /^X's job cap is reached/); + // An hour on, the oldest starts have left the window and X jobs start again. + fakeNow += 61 * 60_000; + await writeJar(5 * 60_000); + const after = await fetchJob(SLUGS[3], new Map()); + assert.equal(after.ok, true, after.ok ? "" : after.error); + if (after.ok) assert.equal((await after.done).status, "done"); +}); + +test("R2b: the start is counted once, by the last guard before the work; a look counts nothing; a job that met the cap while it waited is refused at its start", async () => { + await reset(); + await writeJar(5 * 60_000); + const count = async () => (await xJobCapStatus(paths, "profile", fakeNow)).lastHour; + const job = { id: "job-1" }; + const opts = { kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: SLUGS[0] }; + // Enqueue, and the start's first guard: looks. + assert.equal((await guardNetworkJob(opts)).ok, true); + assert.equal((await guardNetworkJob({ ...opts, job })).ok, true); + assert.equal(await count(), 0); + // The last guard before the work: one start. + assert.equal((await guardNetworkJob({ ...opts, job, countStart: true })).ok, true); + assert.equal(await count(), 1); + // An X run's own start asks X nothing; each channel's turn in it is a start. + assert.equal((await guardNetworkJob({ kind: "x-run", queueKey: "platform:twitter", paths, job, countStart: true })).ok, true); + assert.equal(await count(), 1); + assert.equal((await guardNetworkJob({ kind: "x-run", queueKey: "platform:twitter", paths, channelSlug: SLUGS[1], job, countStart: true })).ok, true); + assert.equal(await count(), 2); + // A job that is no X job is not counted. + assert.equal((await guardNetworkJob({ kind: "reparse-x-trending", queueKey: "platform:twitter", paths, job, countStart: true })).ok, true); + assert.equal(await count(), 2); + // The cap fills while a job waits its turn: its start is refused, and the refused start is not counted. + for (let i = 0; i < 10; i++) await recordXJobStart(paths, "profile", fakeNow); + const late = await guardNetworkJob({ ...opts, job, countStart: true }); + assert.equal(late.ok, false); + assert.match(late.ok ? "" : late.error, /^X's job cap is reached/); + assert.equal(await count(), 12); + // A count that cannot be read refuses every X job, at enqueue and at the start. + await writeFile(path.join(transcripts, ".x-session", "job-starts.json"), "{broken"); + for (const g of [await guardNetworkJob(opts), await guardNetworkJob({ ...opts, job, countStart: true })]) { + assert.equal(g.ok, false); + assert.match(g.ok ? "" : g.error, /^X's job count cannot be read .*no X job starts while it is unreadable/); + } + await reset(); +}); diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts @@ -530,8 +530,8 @@ export async function runManagedFunction( // go stale during a five-minute wait. Only a job that reached its work // counts as an end for the next one's gap. const network = opts.network !== false && kindIsNetwork(opts.kind); - const guard = async () => { - const res = await guardNetworkJob({ ...opts, job: { id } }); + const guard = async (countStart = false) => { + const res = await guardNetworkJob({ ...opts, job: { id }, ...(countStart ? { countStart: true } : {}) }); if (!res.ok) throw new Error(res.error); return res.notes; }; @@ -561,7 +561,9 @@ export async function runManagedFunction( } throw err; } - for (const note of await guard()) onLog(note); + // The last guard before the work: an X job that passes it is counted + // against X's job cap (lib/xJobRule.ts). + for (const note of await guard(true)) onLog(note); reachedWork = true; } await runInJobContext(jobCtx, () => opts.fn(onLog, abort.signal, setProgress, ctx)); diff --git a/common/jobs/syncScheduler.ts b/common/jobs/syncScheduler.ts @@ -1,5 +1,6 @@ import { isInstagramPostsChannelConfig } from "../lib/instagram/channel"; import { isRemoteOnlyChannel, type ChannelConfig } from "../lib/channelConfig"; +import { detectPlatform } from "../lib/platform"; import type { SyncSchedulerSettings } from "../lib/settings"; import { type ChannelPriority, @@ -53,8 +54,22 @@ export type SelectDueInput = { // so the tick asks and hands the sentence in). Every Instagram channel is // then skipped with it, and takes no sync slot. instagramHeld?: string | null; + // WHY NO X JOB STARTS NOW, when X's job cap is reached (lib/xJobRule.ts; + // the tick asks jobs/networkGuard.ts xCapHeldReason and hands the sentence + // in). Every X posts channel is then skipped with it and takes no sync + // slot: a sync queued anyway would be refused, each tick, as a failed job. + xCapHeld?: string | null; }; +// Why an X posts channel is not synced now, or null: X's job cap is reached. +export function xSyncHold( + config: Pick<ChannelConfig, "sourceKind" | "platform"> & Partial<Pick<ChannelConfig, "url">>, + held: string | null | undefined, +): string | null { + if (!held || config.sourceKind !== "social") return null; + return (config.platform ?? detectPlatform(config.url)) === "twitter" ? held : null; +} + // WHY AN INSTAGRAM CHANNEL IS NOT SYNCED NOW, or null (review 1, S10). A // channel with no cookie source of its own would be refused by its fetch // before anything is asked; one while Instagram is held, by the guard. Either @@ -207,6 +222,12 @@ export function selectDueChannels(input: SelectDueInput): SelectDueResult { if (igHold !== INSTAGRAM_SYNC_NO_COOKIES) skipped.push({ slug, reason: igHold }); continue; } + // X's job cap is reached: its channels wait, like a cooldown. + const xHold = xSyncHold(config, input.xCapHeld); + if (xHold) { + skipped.push({ slug, reason: xHold }); + continue; + } if (activeSlugs.has(slug)) { skipped.push({ slug, reason: "already running" }); @@ -313,10 +334,12 @@ export function buildScheduleView(input: { jitter?: number; // SelectDueInput.instagramHeld: the same sentence, for the same skip. instagramHeld?: string | null; + // SelectDueInput.xCapHeld: the same. + xCapHeld?: string | null; }): ChannelScheduleView[] { const { channels, scheduler, state, now, priority } = input; return channels.map(({ slug, config }) => { - const igHold = instagramSyncHold(config, input.instagramHeld); + const igHold = instagramSyncHold(config, input.instagramHeld) ?? xSyncHold(config, input.xCapHeld); const interval = resolveIntervalMinutes(config, scheduler); const sweepInterval = resolveFullSweepIntervalMinutes(config, scheduler); const cs = state.channels[slug]; 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?, 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.', + '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–40 scrolls, default 20; 1–400 posts, default 200; each of the page\'s two tabs has both); 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/xJobCap-server.ts b/common/lib/xJobCap-server.ts @@ -0,0 +1,87 @@ +// X'S JOB COUNT, ON DISK (lane x-followups, R2): every X job's start, per X +// login, in `<transcripts>/.x-session/job-starts.json`: +// { "version": 1, "logins": { "profile": [<ms>, …], "browser:firefox": […] } } +// The rule and its numbers are lib/xJobRule.ts. Here: the file is read and +// written under its lock (one check-and-record at a time), it survives a +// restart, and it FAILS CLOSED — a file that is there and cannot be read or +// parsed refuses every X job until it is repaired; only a file that does not +// exist is an empty count (a fresh install). +// +// SERVER-ONLY (node:fs). + +import path from "node:path"; +import type { Paths } from "./paths"; +import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server"; +import { X_JOB_CAP, xCapClock, xJobCapSentence, xJobCapUnreadableSentence, xJobCapVerdict, type XJobCapVerdict } from "./xJobRule"; + +export function xJobStartsFile(paths: Paths): string { + return path.join(paths.transcriptsDir, ".x-session", "job-starts.json"); +} + +type StartsFile = { version: 1; logins: Record<string, number[]> }; + +async function readStarts(paths: Paths): Promise<{ ok: true; logins: Record<string, number[]> } | { ok: false }> { + const read = await readJsonFile(xJobStartsFile(paths)); + if (!read.ok) return read.reason === "absent" ? { ok: true, logins: {} } : { ok: false }; + const v = read.value as Partial<StartsFile> | null; + if (!v || typeof v !== "object" || v.version !== 1 || !v.logins || typeof v.logins !== "object" || Array.isArray(v.logins)) return { ok: false }; + const logins: Record<string, number[]> = {}; + for (const [login, starts] of Object.entries(v.logins)) { + if (!Array.isArray(starts) || !starts.every((t) => typeof t === "number" && Number.isFinite(t))) return { ok: false }; + logins[login] = [...starts]; + } + return { ok: true, logins }; +} + +export type XJobCapStatus = XJobCapVerdict & { + login: string; + perHour: number; + perDay: number; + // The count could not be read: `ok` is false and nothing starts. + unreadable?: true; + // The refusal, when `ok` is false. + sentence?: string; +}; + +function statusOf(login: string, starts: ReadonlyArray<number>, now: number): XJobCapStatus { + const v = xJobCapVerdict(starts, now); + return { ...v, login, perHour: X_JOB_CAP.perHour, perDay: X_JOB_CAP.perDay, ...(v.ok ? {} : { sentence: xJobCapSentence(v, now) }) }; +} + +function unreadable(paths: Paths, login: string): XJobCapStatus { + return { ok: false, lastHour: 0, lastDay: 0, login, perHour: X_JOB_CAP.perHour, perDay: X_JOB_CAP.perDay, unreadable: true, sentence: xJobCapUnreadableSentence(xJobStartsFile(paths)) }; +} + +// Would an X job of this login start now? Nothing is written. +export async function xJobCapStatus(paths: Paths, login: string, now: number = Date.now()): Promise<XJobCapStatus> { + const read = await readStarts(paths); + return read.ok ? statusOf(login, read.logins[login] ?? [], now) : unreadable(paths, login); +} + +// ONE X JOB STARTS: checked and recorded in one step, under the file's lock. +// `ok: false` — the cap is reached, or the count is unreadable — records +// nothing, and the job does not start. The time recorded is never earlier +// than the latest start on record (xCapClock). +export async function recordXJobStart(paths: Paths, login: string, now: number = Date.now()): Promise<XJobCapStatus> { + const file = xJobStartsFile(paths); + return withJsonFileLock(file, async () => { + const read = await readStarts(paths); + if (!read.ok) return unreadable(paths, login); + const starts = read.logins[login] ?? []; + const before = statusOf(login, starts, now); + if (!before.ok) return before; + const at = xCapClock(starts, now); + // Kept: what the longer window can still count. + const logins: Record<string, number[]> = {}; + for (const [key, list] of Object.entries(read.logins)) { + const clock = xCapClock(list, now); + const kept = list.filter((t) => t > clock - X_JOB_CAP.dayMs); + if (kept.length || key === login) logins[key] = kept; + } + logins[login] = [...(logins[login] ?? []), at]; + await writeJsonAtomic(file, { version: 1, logins } satisfies StartsFile, { mkdir: true }); + // This start was within the cap: said so, with the count it leaves. + const after = statusOf(login, logins[login], now); + return { ok: true, lastHour: after.lastHour, lastDay: after.lastDay, login, perHour: X_JOB_CAP.perHour, perDay: X_JOB_CAP.perDay }; + }); +} diff --git a/common/lib/xJobRule.test.ts b/common/lib/xJobRule.test.ts @@ -0,0 +1,141 @@ +// X's two rules (lib/xJobRule.ts) and the count on disk (lib/xJobCap-server.ts). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/xJobRule.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "./paths"; +import { runInJobContext } from "./jobContext"; +import { X_JOB_CAP, X_QUEUE_KEY, xJobCapSentence, xJobCapVerdict, xJobContextRefusal, xLoginKey, xQueueRefusal } from "./xJobRule"; +import { recordXJobStart, xJobCapStatus, xJobStartsFile } from "./xJobCap-server"; + +const TMP = mkdtempSync(path.join(tmpdir(), "x-job-rule-")); +after(() => rmSync(TMP, { recursive: true, force: true })); +const corpus = (name: string) => ({ transcriptsDir: path.join(TMP, name) }) as unknown as Paths; +const T0 = Date.parse("2026-11-18T12:00:00.000Z"); +const MIN = 60_000; + +test("the numbers: 12 X jobs in any 60 minutes, 150 in any 24 hours, and they are frozen", () => { + assert.deepEqual({ ...X_JOB_CAP }, { perHour: 12, hourMs: 3_600_000, perDay: 150, dayMs: 86_400_000 }); + assert.ok(Object.isFrozen(X_JOB_CAP)); + assert.equal(X_QUEUE_KEY, "platform:twitter"); + // Nothing in the rule's two modules reads a setting, an environment variable or an option. + for (const file of ["xJobRule.ts", "xJobCap-server.ts"]) { + const code = readFileSync(path.join(import.meta.dirname, file), "utf8").replace(/^\s*\/\/.*$/gm, ""); + assert.doesNotMatch(code, /process\.env|getSettings|settings\b|\bforce\b/i, file); + } +}); + +test("the hour window: the 13th start in 60 minutes is refused, and says when the next may start", () => { + const starts = Array.from({ length: 12 }, (_, i) => T0 + i * 5 * MIN); // 12:00 … 12:55 + assert.deepEqual(xJobCapVerdict(starts.slice(0, 11), T0 + 56 * MIN), { ok: true, lastHour: 11, lastDay: 11 }); + const full = xJobCapVerdict(starts, T0 + 56 * MIN); + assert.deepEqual(full, { ok: false, lastHour: 12, lastDay: 12, nextAt: T0 + 60 * MIN, window: "hour" }); + assert.equal( + xJobCapSentence(full, T0 + 56 * MIN), + "X's job cap is reached for this login: 12 X jobs started in the last 60 minutes (the cap is 12). The next X job may start at 13:00 UTC (in 4 min); " + + "ask again then — nothing queues or retries by itself. The cap is fixed in the code (common/lib/xJobRule.ts): no setting, option or queue raises it.", + ); + // Rolling: at 13:00 the 12:00 start has left the window (a start exactly 60 minutes old is out). + assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN).ok, true); + assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN - 1).ok, false); + // X's own gap (5 minutes) makes exactly 12 an hour: the cap never bites a run at the default gap. + assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN).lastHour, 11); +}); + +test("the day window: the 151st start in 24 hours is refused until the oldest of the last 150 is a day old", () => { + const starts = Array.from({ length: 150 }, (_, i) => T0 + i * 9 * MIN); // one every 9 minutes: 22.5 hours + const now = T0 + 150 * 9 * MIN; + const full = xJobCapVerdict(starts, now); + assert.equal(full.ok, false); + assert.equal(full.window, "day"); + assert.equal(full.lastDay, 150); + assert.equal(full.nextAt, T0 + 24 * 60 * MIN); + assert.match(xJobCapSentence(full, now), /150 X jobs started in the last 24 hours \(the cap is 150\)\. The next X job may start at 12:00 UTC \(in 90 min\)/); + // The day is named when it is not today's. + assert.match(xJobCapSentence(xJobCapVerdict(starts, T0 + 151 * 9 * MIN - 23 * 60 * MIN), T0 + 5 * MIN), /may start at 2026-11-19 12:00 UTC \(in about 24 h\)/); + assert.equal(xJobCapVerdict(starts, T0 + 24 * 60 * MIN).ok, true); + assert.equal(xJobCapVerdict(starts.slice(1), now).ok, true); +}); + +test("a clock set back never frees a start early", () => { + const starts = Array.from({ length: 12 }, (_, i) => T0 + i * MIN); // 12:00 … 12:11 + // The clock now reads two hours EARLIER than the latest start: every start still counts. + const back = xJobCapVerdict(starts, T0 - 120 * MIN); + assert.equal(back.ok, false); + assert.equal(back.lastHour, 12); + assert.equal(back.nextAt, T0 + 60 * MIN); + // Only once the clock has passed them again by the window do they leave it. + assert.equal(xJobCapVerdict(starts, T0 + 59 * MIN).ok, false); + assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN).ok, true); +}); + +test("the count is on disk: checked and recorded in one step, kept across a restart, per login", async () => { + const paths = corpus("disk"); + for (let i = 0; i < 12; i++) assert.equal((await recordXJobStart(paths, "profile", T0 + i * MIN)).ok, true); + const refused = await recordXJobStart(paths, "profile", T0 + 12 * MIN); + assert.equal(refused.ok, false); + assert.match(refused.sentence ?? "", /^X's job cap is reached for this login: 12 X jobs started in the last 60 minutes/); + // A refused start records nothing. + const file = JSON.parse(readFileSync(xJobStartsFile(paths), "utf8")); + assert.deepEqual(Object.keys(file.logins), ["profile"]); + assert.equal(file.logins.profile.length, 12); + // "Restart": nothing is in memory; the file is the count. + const again = await xJobCapStatus(paths, "profile", T0 + 13 * MIN); + assert.deepEqual([again.ok, again.lastHour, again.lastDay, again.nextAt], [false, 12, 12, T0 + 60 * MIN]); + // Another login has its own count. + assert.equal((await recordXJobStart(paths, xLoginKey("browser", "firefox"), T0 + 13 * MIN)).ok, true); + assert.equal(xLoginKey("browser"), "browser:default"); + assert.equal(xLoginKey("profile", "ignored"), "profile"); + // A start recorded with the clock set back is recorded no earlier than the latest on record. + const p2 = corpus("disk-back"); + await recordXJobStart(p2, "profile", T0); + await recordXJobStart(p2, "profile", T0 - 600 * MIN); + assert.deepEqual(JSON.parse(readFileSync(xJobStartsFile(p2), "utf8")).logins.profile, [T0, T0]); + // Starts older than a day are dropped when the next is recorded. + await recordXJobStart(p2, "profile", T0 + 25 * 60 * MIN); + assert.deepEqual(JSON.parse(readFileSync(xJobStartsFile(p2), "utf8")).logins.profile, [T0 + 25 * 60 * MIN]); + // Two at once: both recorded, neither lost. + const p3 = corpus("disk-race"); + await Promise.all(Array.from({ length: 12 }, (_, i) => recordXJobStart(p3, "profile", T0 + i))); + assert.equal(JSON.parse(readFileSync(xJobStartsFile(p3), "utf8")).logins.profile.length, 12); + assert.equal((await recordXJobStart(p3, "profile", T0 + 20)).ok, false); +}); + +test("a count that cannot be read fails closed: no X job starts, and nothing is written over it", async () => { + for (const [name, text] of [["garbage", "{not json"], ["shape", '{"version":1,"logins":[]}'], ["version", '{"version":2,"logins":{}}'], ["times", '{"version":1,"logins":{"profile":["soon"]}}']] as const) { + const paths = corpus(`closed-${name}`); + mkdirSync(path.dirname(xJobStartsFile(paths)), { recursive: true }); + writeFileSync(xJobStartsFile(paths), text); + const status = await xJobCapStatus(paths, "profile", T0); + assert.equal(status.ok, false, name); + assert.equal(status.unreadable, true); + assert.match(status.sentence ?? "", /^X's job count cannot be read \(.*job-starts\.json\): no X job starts while it is unreadable/); + assert.equal((await recordXJobStart(paths, "profile", T0)).ok, false); + assert.equal(readFileSync(xJobStartsFile(paths), "utf8"), text); + } + // A file that is not there is an empty count. + assert.deepEqual(await xJobCapStatus(corpus("closed-absent"), "profile", T0), { ok: true, lastHour: 0, lastDay: 0, login: "profile", perHour: 12, perDay: 150 }); +}); + +test("X jobs run on X's queue only: any other queue is refused, when queued and where the job runs", () => { + assert.equal(xQueueRefusal("fetch-posts for example-x", "platform:twitter"), null); + assert.equal( + xQueueRefusal("fetch-posts for example-x", "manual"), + 'fetch-posts for example-x asks X, and X jobs run on X\'s queue only (platform:twitter): the queue "manual" is refused. ' + + "On another queue it would run beside the job on X's, outside the gap between X jobs. Leave the queue at its default.", + ); + assert.match(xQueueRefusal("x", "platform:youtube") ?? "", /"platform:youtube" is refused/); + assert.match(xQueueRefusal("x", undefined) ?? "", /the queue it was given is refused/); + const ctx = (queueKey?: string) => ({ jobId: "j", kind: "fetch-posts", ...(queueKey ? { queueKey } : {}), onLog: () => {}, staleServices: new Set<string>() }); + // No job at all. + assert.match(xJobContextRefusal("example-x", "pnpm ops fetch-posts") ?? "", /^example-x asks X, and X is asked only by the editor's own jobs .* nothing was asked\. Queue it instead: pnpm ops fetch-posts$/); + // A job on another queue. + assert.match(runInJobContext(ctx("manual"), () => xJobContextRefusal("example-x", "d")) ?? "", /the queue "manual" is refused\..* Nothing was asked\.$/); + assert.match(runInJobContext(ctx(), () => xJobContextRefusal("example-x", "d")) ?? "", /the queue it was given is refused/); + // X's queue. + assert.equal(runInJobContext(ctx("platform:twitter"), () => xJobContextRefusal("example-x", "d")), null); +}); diff --git a/common/lib/xJobRule.ts b/common/lib/xJobRule.ts @@ -0,0 +1,132 @@ +// THE TWO RULES EVERY X JOB MEETS, AND THEIR NUMBERS (lane x-followups, R2; +// the operator, 18 Nov 2026: "X should refuse and/or have an immutable global +// per-account cap"). ONE module: the constants are here and nowhere else. +// +// 1. X JOBS RUN ON X'S QUEUE ONLY (`platform:twitter`). A job that asks X +// as the connected account or with X's cookies — a posts fetch in any +// mode, a resumed backfill, a sync, a capture, a trending read, an +// import of an X post, an availability check, a channel's turn in an X +// run — is refused on any other queue: when it is queued +// (jobs/networkGuard.ts) and again where it runs (xJobContextRefusal, +// asked by the code that is about to ask X). On another queue it would +// run beside the job on X's and outside the gap between X jobs. +// +// 2. A CAP NOBODY CAN RAISE: at most X_JOB_CAP.perHour X jobs started in any +// rolling 60 minutes and X_JOB_CAP.perDay in any rolling 24 hours, per X +// login, over every kind of X job together. A job past it is refused +// before it starts, with the time the next may start. +// +// THE CAP IS A CONSTANT OF THE CODE. It is not in settings.json, not in a +// channel's config, not an environment variable, not an option of any action +// or command, and no `force` passes it. Changing it is a code change, reviewed +// like one. Nothing in this module reads a setting. +// +// Pure but for xJobContextRefusal, which reads the running job's context +// (lib/jobContext.ts). The count's file is lib/xJobCap-server.ts. + +import { currentJobContext } from "./jobContext"; + +export const X_QUEUE_KEY = "platform:twitter"; + +export const X_JOB_CAP = Object.freeze({ + perHour: 12, + hourMs: 60 * 60_000, + perDay: 150, + dayMs: 24 * 60 * 60_000, +}); + +// ── 1. the queue ─────────────────────────────────────────────────────────── + +// Why a job that asks X may not be on `queueKey`, or null. `what` names the +// job ("fetch-posts for example-x"). +export function xQueueRefusal(what: string, queueKey: string | undefined): string | null { + if (queueKey === X_QUEUE_KEY) return null; + return ( + `${what} asks X, and X jobs run on X's queue only (${X_QUEUE_KEY}): the queue ` + + `${queueKey === undefined || queueKey === "" ? "it was given" : `"${queueKey}"`} is refused. ` + + "On another queue it would run beside the job on X's, outside the gap between X jobs. Leave the queue at its default." + ); +} + +// WHERE X IS ABOUT TO BE ASKED: only inside a job of the editor's, and only +// one on X's queue. Null when the caller stands there. `door` names the way +// in ("pnpm ops fetch-posts --json '{…}' --wait"). +export function xJobContextRefusal(what: string, door: string): string | null { + const job = currentJobContext(); + if (!job) { + return ( + `${what} asks X, and X is asked only by the editor's own jobs (on X's queue, spaced apart, on a fresh ` + + `cookie jar, under X's job cap, stopped by the X alert and held after a rate limit): nothing was asked. ` + + `Queue it instead: ${door}` + ); + } + const queue = xQueueRefusal(what, job.queueKey); + return queue ? `${queue} Nothing was asked.` : null; +} + +// ── 2. the cap ───────────────────────────────────────────────────────────── + +export type XJobCapVerdict = { + ok: boolean; + // X jobs started in the last 60 minutes and the last 24 hours. + lastHour: number; + lastDay: number; + // When the next X job may start (ms since the epoch), when `ok` is false. + nextAt?: number; + window?: "hour" | "day"; +}; + +// THE CLOCK NEVER FREES A START EARLY. The windows end at the LATER of now +// and the latest recorded start: a machine clock set back (by a person, by a +// time sync) leaves every recorded start inside its window until the clock +// has passed it again. +export function xCapClock(starts: ReadonlyArray<number>, now: number): number { + return starts.reduce((a, t) => (t > a ? t : a), now); +} + +export function xJobCapVerdict(starts: ReadonlyArray<number>, now: number): XJobCapVerdict { + const at = xCapClock(starts, now); + const recent = [...starts].filter((t) => Number.isFinite(t)).sort((a, b) => b - a); + const hour = recent.filter((t) => t > at - X_JOB_CAP.hourMs); + const day = recent.filter((t) => t > at - X_JOB_CAP.dayMs); + const out = { lastHour: hour.length, lastDay: day.length }; + // The next may start once the oldest of the newest <cap> starts has left its window. + const hourFree = hour.length >= X_JOB_CAP.perHour ? hour[X_JOB_CAP.perHour - 1] + X_JOB_CAP.hourMs : null; + const dayFree = day.length >= X_JOB_CAP.perDay ? day[X_JOB_CAP.perDay - 1] + X_JOB_CAP.dayMs : null; + if (hourFree === null && dayFree === null) return { ok: true, ...out }; + const window = dayFree !== null && (hourFree === null || dayFree >= hourFree) ? "day" : "hour"; + return { ok: false, ...out, nextAt: Math.max(hourFree ?? 0, dayFree ?? 0), window }; +} + +const hhmm = (ms: number) => new Date(ms).toISOString().slice(11, 16); +const day = (ms: number) => new Date(ms).toISOString().slice(0, 10); + +// The refusal: which cap, how full, and when the next X job may start. +export function xJobCapSentence(v: XJobCapVerdict, now: number): string { + if (v.ok || v.nextAt === undefined) return ""; + const full = + v.window === "day" + ? `${v.lastDay} X jobs started in the last 24 hours (the cap is ${X_JOB_CAP.perDay})` + : `${v.lastHour} X jobs started in the last 60 minutes (the cap is ${X_JOB_CAP.perHour})`; + const minutes = Math.max(1, Math.ceil((v.nextAt - now) / 60_000)); + const when = `${day(v.nextAt) === day(now) ? "" : `${day(v.nextAt)} `}${hhmm(v.nextAt)} UTC`; + const wait = minutes >= 120 ? `about ${Math.round(minutes / 60)} h` : `${minutes} min`; + return ( + `X's job cap is reached for this login: ${full}. The next X job may start at ${when} (in ${wait}); ` + + "ask again then — nothing queues or retries by itself. The cap is fixed in the code (common/lib/xJobRule.ts): no setting, option or queue raises it." + ); +} + +// The sentence for a count that cannot be read: nothing starts on a guess. +export function xJobCapUnreadableSentence(file: string): string { + return ( + `X's job count cannot be read (${file}): no X job starts while it is unreadable, because the cap on X jobs ` + + "is counted there. Repair the file (it is JSON: {version, logins: {<login>: [times]}}), then ask again." + ); +} + +// Which login a job uses, as the count's key: the connected profile, or the +// browser whose cookies are read (by its spec). +export function xLoginKey(source: "profile" | "browser", browserSpec?: string): string { + return source === "browser" ? `browser:${(browserSpec ?? "").trim() || "default"}` : "profile"; +} diff --git a/common/lib/xTrending/config.test.ts b/common/lib/xTrending/config.test.ts @@ -39,7 +39,7 @@ test("a trending page URL is its id; anything else is refused", () => { test("the marker is an object; its caps are kept only in range", () => { assert.deepEqual(coerceXTrendingConfig({}), {}); assert.deepEqual(coerceXTrendingConfig({ maxScrolls: 4, maxPosts: 30, other: 1 }), { maxScrolls: 4, maxPosts: 30 }); - assert.deepEqual(coerceXTrendingConfig({ maxScrolls: 21, maxPosts: 0 }), {}); + assert.deepEqual(coerceXTrendingConfig({ maxScrolls: 41, maxPosts: 0 }), {}); assert.deepEqual(coerceXTrendingConfig({ maxScrolls: 2.5, maxPosts: "9" }), {}); for (const bad of [undefined, null, true, "yes", 1, []]) assert.equal(coerceXTrendingConfig(bad), undefined); }); @@ -65,17 +65,17 @@ test("a library is a channel carrying the marker — the marker alone — and it assert.equal(isXTrendingChannel(null), false); }); -test("a read's caps: the ask, else the channel's, else 8 scrolls and 60 posts; out of range is refused", () => { - assert.deepEqual(xTrendingLimits(undefined), { ok: true, limits: { scrolls: 8, posts: 60 } }); - assert.deepEqual(xTrendingLimits({ maxScrolls: 3 }), { ok: true, limits: { scrolls: 3, posts: 60 } }); +test("a read's caps: the ask, else the channel's, else 20 scrolls and 200 posts; out of range is refused", () => { + assert.deepEqual(xTrendingLimits(undefined), { ok: true, limits: { scrolls: 20, posts: 200 } }); + assert.deepEqual(xTrendingLimits({ maxScrolls: 3 }), { ok: true, limits: { scrolls: 3, posts: 200 } }); assert.deepEqual(xTrendingLimits({ maxScrolls: 3 }, { scrolls: 20, posts: 200 }), { ok: true, limits: { scrolls: 20, posts: 200 }, }); - assert.deepEqual(xTrendingLimits({}, { scrolls: 21 }), { ok: false, error: '"scrolls" is a whole number, 1–20' }); - assert.deepEqual(xTrendingLimits({}, { posts: 201 }), { ok: false, error: '"posts" is a whole number, 1–200' }); - assert.deepEqual(xTrendingLimits({}, { posts: 0 }), { ok: false, error: '"posts" is a whole number, 1–200' }); - assert.deepEqual(xTrendingLimits({}, { scrolls: "8" }), { ok: false, error: '"scrolls" is a whole number, 1–20' }); + assert.deepEqual(xTrendingLimits({}, { scrolls: 41 }), { ok: false, error: '"scrolls" is a whole number, 1–40' }); + assert.deepEqual(xTrendingLimits({}, { posts: 401 }), { ok: false, error: '"posts" is a whole number, 1–400' }); + assert.deepEqual(xTrendingLimits({}, { posts: 0 }), { ok: false, error: '"posts" is a whole number, 1–400' }); + assert.deepEqual(xTrendingLimits({}, { scrolls: "8" }), { ok: false, error: '"scrolls" is a whole number, 1–40' }); }); test("the per-file media cap: 100 MB unless the library says otherwise, kept only in range", () => { diff --git a/common/lib/xTrending/config.ts b/common/lib/xTrending/config.ts @@ -55,10 +55,10 @@ export function xRateLimitHoldSentence(what: string, remainingMs: number, now: n ); } -export const X_TRENDING_DEFAULT_SCROLLS = 8; -export const X_TRENDING_MAX_SCROLLS = 20; -export const X_TRENDING_DEFAULT_POSTS = 60; -export const X_TRENDING_MAX_POSTS = 200; +export const X_TRENDING_DEFAULT_SCROLLS = 20; +export const X_TRENDING_MAX_SCROLLS = 40; +export const X_TRENDING_DEFAULT_POSTS = 200; +export const X_TRENDING_MAX_POSTS = 400; 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 diff --git a/common/lib/xTrending/store.test.ts b/common/lib/xTrending/store.test.ts @@ -647,9 +647,10 @@ test("gone from the page is said per tab: a post only the other tab showed is no assert.deepEqual(listing.posts.find((p) => p.id === "703")?.reads, [{ read: READ_C, trendId: REF.trendId, at: at(11), tab: "Latest" }]); assert.deepEqual(listing.posts.find((p) => p.id === "704")?.reads, [{ read: READ_A, trendId: REF.trendId, at: at(9) }]); assert.equal(listing.topics[0].sources[0].lastReadTab, "Top"); - // A complete read that cannot say its tab (no page answer in its capture) is the opening tab's: 703 is still excused only by a KNOWN difference. + // A complete read that cannot say its tab judges only sightings that name none: 703, seen on Latest, is not its to judge. const unknown = await recordXTrendingRead(dir, { readId: "tr-01JE0000000000000000000000", at: at(13), ref: REF, topic: "T", postIds: ["701"], added: 0, complete: true }); - assert.deepEqual(unknown.gone, ["703"]); + assert.deepEqual(unknown.gone, []); + assert.equal((await readXTrendingMembership(dir))["703"].gone, undefined); }); // ── review 1: S4 and the set-name field ──────────────────────────────────── @@ -742,3 +743,72 @@ test("a listing gives at most 600 characters of X's summary, cut at a word; the assert.equal(listedXTrendingSummary("Short."), "Short."); assert.equal(listedXTrendingSummary("x".repeat(700)).length, 600); }); + +// ── added scope R3: one read, two tabs ───────────────────────────────────── + +test("R3: a read of two tabs records each tab's sightings and ranks; gone is said tab by tab, and of the page once every tab that showed the post has stopped", async () => { + const dir = root("two-tabs"); + const at = (h: number) => `2026-11-17T${String(h).padStart(2, "0")}:00:00.000Z`; + const id = (n: number) => `tr-01J${String.fromCharCode(64 + n)}0000000000000000000000`; + const read = (n: number, top: string[], latest: string[], complete: { top?: boolean; latest?: boolean } = { top: true, latest: true }, page = true) => + recordXTrendingRead(dir, { + readId: id(n), + at: at(8 + n), + ref: REF, + topic: "T", + postIds: [...new Set([...top, ...latest])], + added: 0, + ...(page ? { page: PAGE } : {}), + tabReads: [ + // Named by the capture's page answer, or only by the timeline id the requests carried. + { ...(page ? { tab: "Top" } : {}), timelineId: "tl-top", postIds: top, ...(complete.top ? { complete: true } : {}) }, + { ...(page ? { tab: "Latest" } : {}), timelineId: "tl-latest", postIds: latest, ...(complete.latest ? { complete: true } : {}) }, + ], + }); + await writeXTrendingPosts(dir, ["901", "902", "903", "904"].map((p) => post(p, "a", `post ${p}`))); + // Read 1: 901 and 902 on both tabs, 903 on Top only, 904 on Latest only. + const first = await read(1, ["901", "902", "903"], ["904", "902", "901"]); + assert.deepEqual(first.tabs, ["Top", "Latest"]); + assert.deepEqual([first.placed, first.kept, first.gone], [4, 0, []]); + let members = await readXTrendingMembership(dir); + assert.deepEqual(members["902"].seen, [ + { read: id(1), trendId: REF.trendId, at: at(9), rank: 2, tab: "Top" }, + { read: id(1), trendId: REF.trendId, at: at(9), rank: 2, tab: "Latest" }, + ]); + assert.deepEqual(members["904"].seen.map((s) => [s.tab, s.rank]), [["Latest", 1]]); + assert.deepEqual((await readXTrendingTopics(dir))[0].sources[0].reads[0].tabs, ["Top", "Latest"]); + assert.deepEqual((await listXTrending(dir)).topics[0].sources[0].lastReadTabs, ["Top", "Latest"]); + + // Read 2: Latest no longer shows 902 (Top still does) nor 904 (which only Latest showed). + const second = await read(2, ["901", "902", "903"], ["901"]); + assert.deepEqual(second.gone, ["904"]); + assert.deepEqual(second.goneFromTab, [{ id: "902", tab: "Latest" }]); + members = await readXTrendingMembership(dir); + assert.equal(members["902"].gone, undefined); + assert.deepEqual(Object.keys(members["902"].goneTabs ?? {}), ["Latest"]); + assert.deepEqual(members["904"].gone, { at: at(10), read: id(2), trendId: REF.trendId }); + let listing = await listXTrending(dir); + assert.deepEqual(listing.posts.find((p) => p.id === "902")?.goneTabs, [{ tab: "Latest", at: at(10), read: id(2) }]); + assert.equal(listing.posts.find((p) => p.id === "902")?.gone, undefined); + // Gone from the page says it all: no per-tab line beside it. + assert.equal(listing.posts.find((p) => p.id === "904")?.goneTabs, undefined); + assert.ok(listing.posts.find((p) => p.id === "904")?.gone); + + // Read 3: Top was capped (not read to its end), Latest to its end again: nothing new is said of Top's posts. + const third = await read(3, ["901"], ["901"], { latest: true }); + assert.deepEqual([third.gone, third.goneFromTab], [[], undefined]); + // Read 4: Top to its end without 902: now gone from every tab that showed it — gone from the page. 903 too (Top only). + const fourth = await read(4, ["901"], ["901"]); + assert.deepEqual([...fourth.gone].sort(), ["902", "903"]); + // Read 5 names no tab in its capture (no page answer): the source's known tabs name them by timeline id. 902 is back on Latest. + const fifth = await read(5, ["901"], ["901", "902"], { top: true, latest: true }, false); + assert.deepEqual(fifth.tabs, ["Top", "Latest"]); + assert.deepEqual(fifth.back, ["902"]); + members = await readXTrendingMembership(dir); + assert.equal(members["902"].gone, undefined); + assert.deepEqual(members["902"].wasGone, [{ from: at(12), to: at(13) }]); + // Still gone from Top, shown again by Latest: said so. + listing = await listXTrending(dir); + assert.deepEqual(listing.posts.find((p) => p.id === "902")?.goneTabs?.map((g) => g.tab), ["Top"]); + assert.equal(members["902"].seen.at(-1)?.tab, "Latest"); +}); diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts @@ -57,6 +57,8 @@ export const TRENDING_DIRNAME = "trending"; export const TRENDING_READS_DIRNAME = "reads"; export const TRENDING_RESPONSES_FILENAME = "responses.jsonl"; export const TRENDING_PAGE_SHOT_FILENAME = "page.png"; +// The page after the read pressed its second tab (or tried to). +export const TRENDING_TAB_SHOT_FILENAME = "page-latest.png"; export const TRENDING_READ_FILENAME = "read.json"; export function trendingDir(channelRoot: string): string { @@ -317,6 +319,8 @@ export type XTrendingSourceRead = { // opens on. Absent for a read saved before tabs were read, until it is // parsed again, and for a capture whose page answer or timeline id is missing. tab?: string; + // A read that covered several tabs (Top, then Latest): their labels. + tabs?: string[]; }; // One tab of a trending page: its label and the timeline it lists. @@ -406,6 +410,12 @@ export type XTrendingMember = { seen: XTrendingSeen[]; media?: XTrendingMedia; gone?: XTrendingGone; + // GONE FROM ONE TAB (lane x-followups): per tab label ("" for a read that + // could not say its tab), the read of that tab that reached its end and did + // not show the post. `gone` above is set once every tab that showed the + // post has a mark here; a mark alone means "gone from that tab, still shown + // by another". + goneTabs?: Record<string, XTrendingGone>; // Earlier absences that ended: gone from `from`, shown again at `to`. wasGone?: Array<{ from: string; to: string }>; // Its last move between topics (lib/xTrending/organise.ts): the topic it @@ -430,7 +440,8 @@ function parseTopics(raw: unknown): XTrendingTopic[] { const reads: XTrendingSourceRead[] = []; for (const r of Array.isArray(s.reads) ? s.reads : []) { if (!r || typeof r !== "object" || !isXTrendingReadId(r.id) || !str(r.at)) continue; - reads.push({ id: r.id, at: r.at, posts: Number(r.posts) || 0, added: Number(r.added) || 0, ...(str(r.tab) ? { tab: r.tab } : {}) }); + const readTabs = (Array.isArray(r.tabs) ? r.tabs : []).filter((x: unknown): x is string => str(x)); + reads.push({ id: r.id, at: r.at, posts: Number(r.posts) || 0, added: Number(r.added) || 0, ...(str(r.tab) ? { tab: r.tab } : {}), ...(readTabs.length > 1 ? { tabs: readTabs } : {}) }); } const tabs: XTrendingTab[] = []; for (const tab of Array.isArray(s.tabs) ? s.tabs : []) { @@ -489,6 +500,14 @@ function parseMembership(raw: unknown): Record<string, XTrendingMember> { : undefined; 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 goneTabs: Record<string, XTrendingGone> = {}; + if (m.goneTabs && typeof m.goneTabs === "object" && !Array.isArray(m.goneTabs)) { + for (const [tab, mark] of Object.entries(m.goneTabs as Record<string, Partial<XTrendingGone> | null>)) { + if (mark && typeof mark === "object" && str(mark.at) && isXTrendingReadId(mark.read) && str(mark.trendId)) { + goneTabs[tab] = { at: mark.at, read: mark.read, trendId: mark.trendId }; + } + } + } 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), ); @@ -503,6 +522,7 @@ function parseMembership(raw: unknown): Record<string, XTrendingMember> { seen, ...(media ? { media } : {}), ...(gone ? { gone } : {}), + ...(Object.keys(goneTabs).length ? { goneTabs } : {}), ...(wasGone.length ? { wasGone: wasGone.map((w) => ({ from: w.from, to: w.to })) } : {}), ...(moved ? { moved } : {}), }; @@ -619,6 +639,12 @@ export type RecordReadInput = { // ONE; and, per post, the tab that showed it. tab?: string; tabs?: Readonly<Record<string, string>>; + // A READ OF SEVERAL TABS (lane x-followups): per timeline the capture lists, + // the posts it listed in its own order, its tab's label when the capture + // names it (else `timelineId`, which the source's known tabs may name), and + // whether that tab was read to its end. Given, it replaces `tab` and + // `complete`; `postIds` stays every post of the read, each once. + tabReads?: ReadonlyArray<{ tab?: string; timelineId?: string; postIds: ReadonlyArray<string>; complete?: boolean }>; }; export type RecordReadResult = { @@ -633,6 +659,12 @@ export type RecordReadResult = { // only), and posts that were gone and are shown again. gone: string[]; back: string[]; + // Posts a tab read to its end no longer shows while another tab still does. + goneFromTab?: Array<{ id: string; tab: string }>; + // The tabs this read listed, by label (as the source names them), and the + // label of each timeline id the read named. + tabs?: string[]; + tabLabels?: Record<string, string>; }; // A page's title as a topic's name: one line, cut to a topic name's length. @@ -713,82 +745,119 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead found.titleFrom = "page"; } } + // THE TABS THIS READ LISTED, each named: by the capture's own page answer, + // else by the tabs the source already knows for that timeline id (a + // capture with no page answer still says which tab it was). + const tabLabels: Record<string, string> = {}; + const tabReads = (input.tabReads ?? [{ postIds: [...input.postIds], ...(input.tab ? { tab: input.tab } : {}), ...(input.complete ? { complete: true } : {}) }]).map((t) => { + const tab = t.tab ?? (t.timelineId ? source!.tabs?.find((known) => known.timelineId === t.timelineId)?.label : undefined); + if (tab && t.timelineId) tabLabels[t.timelineId] = tab; + return { postIds: [...t.postIds], ...(tab ? { tab } : {}), ...(t.complete ? { complete: true } : {}) }; + }); + const tabsSeen = [...new Set(tabReads.map((t) => t.tab).filter((t): t is string => Boolean(t)))]; const read = source.reads.find((r) => r.id === input.readId); + const tabFields = { ...(tabsSeen.length === 1 ? { tab: tabsSeen[0] } : {}), ...(tabsSeen.length > 1 ? { tabs: tabsSeen } : {}) }; if (!read) { - source.reads.push({ id: input.readId, at: input.at, posts: input.postIds.length, added: input.added, ...(input.tab ? { tab: input.tab } : {}) }); + source.reads.push({ id: input.readId, at: input.at, posts: input.postIds.length, added: input.added, ...tabFields }); } else { // The same read recorded again (a reparse): what the capture is now // read to hold, and whatever this pass added on top of the last. read.posts = input.postIds.length; read.added += input.added; - if (input.tab) read.tab = input.tab; + if (tabsSeen.length) { + delete read.tab; + delete read.tabs; + Object.assign(read, tabFields); + } } await writeJsonAtomic(topicsPath(channelRoot), { version: 1, topics } satisfies TopicsFile, { mkdir: true }); - return { id: found.id, title: found.title, created, ...(renamed ? { renamed } : {}) }; + return { id: found.id, title: found.title, created, ...(renamed ? { renamed } : {}), tabReads, tabLabels }; }); const counts = await withJsonFileLock(membershipPath(channelRoot), async () => { const posts = await readXTrendingMembership(channelRoot); let placed = 0; let kept = 0; const gone: string[] = []; + const goneFromTab: Array<{ id: string; tab: string }> = []; const back: string[] = []; - input.postIds.forEach((id, i) => { - const tab = input.tabs?.[id] ?? input.tab; - const seen: XTrendingSeen = { read: input.readId, trendId: input.ref.trendId, at: input.at, rank: i + 1, ...(tab ? { tab } : {}) }; - const have = posts[id]; - if (have) { - kept++; - const sighting = have.seen.find((s) => s.read === input.readId); - if (!sighting) have.seen.push(seen); - // The same read again (a reparse): the tab it could not say before. - else if (tab && !sighting.tab) sighting.tab = tab; - if (!have.media && input.media?.[id]) have.media = input.media[id]; - if (!have.thread && input.threads?.[id]) have.thread = input.threads[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); + const counted = new Set<string>(); + for (const tabRead of topic.tabReads) { + tabRead.postIds.forEach((id, i) => { + const tab = input.tabs?.[id] ?? tabRead.tab; + const seen: XTrendingSeen = { read: input.readId, trendId: input.ref.trendId, at: input.at, rank: i + 1, ...(tab ? { tab } : {}) }; + const have = posts[id]; + if (have) { + if (!counted.has(id)) kept++; + // One sighting per read AND tab. The same read again (a reparse) + // gives the sighting the tab it could not say before. + const same = have.seen.find((s) => s.read === input.readId && s.tab === tab); + const untagged = same ? undefined : have.seen.find((s) => s.read === input.readId && s.tab === undefined); + if (!same && untagged && tab) untagged.tab = tab; + else if (!same && !untagged) have.seen.push(seen); + if (!have.media && input.media?.[id]) have.media = input.media[id]; + if (!have.thread && input.threads?.[id]) have.thread = input.threads[id]; + // Shown again on this tab, by a read later than the one that missed it. + const key = tab ?? ""; + const tabMark = have.goneTabs?.[key]; + if (tabMark && input.at > tabMark.at) { + delete have.goneTabs![key]; + if (Object.keys(have.goneTabs!).length === 0) delete have.goneTabs; + } + if (have.gone && input.at > have.gone.at) { + (have.wasGone ??= []).push({ from: have.gone.at, to: input.at }); + delete have.gone; + if (!back.includes(id)) back.push(id); + } + } else { + placed++; + posts[id] = { + topic: topic.id, + ...(input.threads?.[id] ? { thread: input.threads[id] } : {}), + seen: [seen], + ...(input.media?.[id] ? { media: input.media[id] } : {}), + }; } - } else { - placed++; - posts[id] = { - topic: topic.id, - ...(input.threads?.[id] ? { thread: input.threads[id] } : {}), - seen: [seen], - ...(input.media?.[id] ? { media: input.media[id] } : {}), - }; - } - }); - if (input.complete) { - const shown = new Set(input.postIds); + counted.add(id); + }); + } + // GONE, TAB BY TAB. A tab read to its end marks the posts THAT TAB showed + // before and does not show now (`goneTabs[<tab>]`). A post is gone from + // the PAGE (`gone`) once every tab that showed it has such a mark; until + // then it is "gone from <tab>, still shown by <the other>". + // + // WHICH SIGHTINGS A TAB'S READ JUDGES: its own tab's, and those that name + // no tab (a read from before tabs were read: the tab the page opens on). + // A read that cannot say its tab judges only sightings that name none. + for (const tabRead of topic.tabReads) { + if (!tabRead.complete) continue; + const key = tabRead.tab ?? ""; + const shown = new Set(tabRead.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 — and NOT ON - // ANOTHER TAB than this read saw: a post only the other tab showed is - // not missing from this one. Only a KNOWN difference excuses it: a - // sighting or a read that names no tab (a read from before tabs were - // read, a capture with no page answer) was of the tab the page opens - // on, the only one a read sees. - if ( - !m.seen.some( - (s) => - s.trendId === input.ref.trendId && - s.read !== input.readId && - s.at < input.at && - (s.tab === undefined || input.tab === undefined || s.tab === input.tab), - ) - ) { - continue; + if (shown.has(id) || m.gone || m.goneTabs?.[key]) continue; + const ofPage = m.seen.filter((s) => s.trendId === input.ref.trendId); + if (!ofPage.some((s) => s.read !== input.readId && s.at < input.at && (s.tab === undefined || s.tab === tabRead.tab))) continue; + const mark: XTrendingGone = { at: input.at, read: input.readId, trendId: input.ref.trendId }; + (m.goneTabs ??= {})[key] = mark; + const named = [...new Set(ofPage.map((s) => s.tab).filter((t): t is string => t !== undefined))]; + const tabsSeen = named.length ? named : [key]; + if (tabsSeen.every((t) => m.goneTabs?.[t])) { + m.gone = mark; + gone.push(id); + } else if (tabRead.tab) { + goneFromTab.push({ id, tab: tabRead.tab }); } - 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, gone, back }; + return { placed, kept, gone, back, ...(goneFromTab.length ? { goneFromTab } : {}) }; }); - return { topic, ...counts }; + const tabs = [...new Set(topic.tabReads.map((t) => t.tab).filter((t): t is string => Boolean(t)))]; + return { + topic: { id: topic.id, title: topic.title, created: topic.created, ...(topic.renamed ? { renamed: topic.renamed } : {}) }, + ...(tabs.length ? { tabs } : {}), + ...(Object.keys(topic.tabLabels).length ? { tabLabels: topic.tabLabels } : {}), + ...counts, + }; } // ── one read's record ────────────────────────────────────────────────────── @@ -819,6 +888,16 @@ export type XTrendingReadOutcome = | "gone" | "error"; +export type XTrendingReadTab = { + tab?: string; + asked?: "top" | "latest"; + posts: number; + scrolls?: number; + stop?: string; + pageEnd?: boolean; + why?: string; +}; + export type XTrendingReadRecord = { version: 1; id: string; @@ -850,7 +929,14 @@ export type XTrendingReadRecord = { // capture lists, the page's label for it (absent when the page names no // such tab, or the capture has no page answer) and the posts it showed // first. Labels and counts only. A read sees one: the tab the page opens on. - tabs?: Array<{ tab?: string; posts: number }>; + // + // TAB BY TAB (R3): a read covers "Top" and then "Latest". Per tab: what was + // asked (`asked`), how many scrolls it took, why its scrolling stopped + // (`stop`: a TrendingReadStop, "not-read" with `why` when the tab could not + // be opened, "not-asked" for the opening tab of a read asked for the other + // only) and whether the capture shows that tab's end (`pageEnd`). An entry + // with no `tab` is posts listed by a request that named no timeline. + tabs?: XTrendingReadTab[]; shot: boolean; sentence: string; // When the capture was last parsed again (`reparse`). @@ -953,6 +1039,8 @@ export type XTrendingTopicRow = { lastUpdatedAt?: string; tabs?: string[]; lastReadTab?: string; + // …or the tabs, when the last read covered several. + lastReadTabs?: string[]; reads: number; lastReadAt: string | null; }>; @@ -972,6 +1060,9 @@ export type XTrendingPostRow = { media: XTrendingMedia & { thumbnail?: string }; topic: string; reads: Array<{ read: string; trendId: string; at: string; tab?: string }>; + // Gone from these tabs while another tab of the page still shows it (a + // tab's read reached its end without it). Absent once `gone` is set. + goneTabs?: Array<{ tab: string; at: string; read: 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; @@ -1084,9 +1175,21 @@ export function listedXTrendingSummary(summary: string, max: number = X_TRENDING return `${(word > max * 0.8 ? cut.slice(0, word) : cut).trimEnd()}…`; } -// The tab the source's latest read saw, when that read says. -function lastReadTabOf(s: XTrendingSource): string | undefined { - return s.reads.reduce<XTrendingSourceRead | undefined>((a, r) => (a === undefined || r.at > a.at ? r : a), undefined)?.tab; +// The tabs the source's latest read saw, when that read says. +function lastReadTabsOf(s: XTrendingSource): string[] { + const last = s.reads.reduce<XTrendingSourceRead | undefined>((a, r) => (a === undefined || r.at > a.at ? r : a), undefined); + return last?.tabs?.length ? last.tabs : last?.tab ? [last.tab] : []; +} + +// The tabs a post is gone from WHILE THE PAGE STILL SHOWS IT on another: +// nothing once it is gone from the page (`gone` says that), and never the +// mark of a read that could not say its tab. +function goneFromTabsOf(m: XTrendingMember): Array<{ tab: string; at: string; read: string }> { + if (m.gone || !m.goneTabs) return []; + return Object.entries(m.goneTabs) + .filter(([tab]) => tab !== "") + .map(([tab, mark]) => ({ tab, at: mark.at, read: mark.read })) + .sort((a, b) => a.tab.localeCompare(b.tab)); } const lastSeen = (m: XTrendingMember) => m.seen.reduce((a, s) => (s.at > a ? s.at : a), ""); @@ -1172,6 +1275,7 @@ export async function listXTrending( topic: m.topic, reads: m.seen.map((s) => ({ read: s.read, trendId: s.trendId, at: s.at, ...(s.tab ? { tab: s.tab } : {}) })), ...(m.gone ? { gone: m.gone } : {}), + ...(goneFromTabsOf(m).length ? { goneTabs: goneFromTabsOf(m) } : {}), thread, ...(effective ? { judgement: effective } : {}), ...(opts.detail @@ -1223,7 +1327,8 @@ export async function listXTrending( ...(s.summary ? { summary: listedXTrendingSummary(s.summary) } : {}), ...(s.lastUpdatedAt ? { lastUpdatedAt: s.lastUpdatedAt } : {}), ...(s.tabs?.length ? { tabs: s.tabs.map((t) => t.label) } : {}), - ...(lastReadTabOf(s) ? { lastReadTab: lastReadTabOf(s)! } : {}), + ...(lastReadTabsOf(s).length === 1 ? { lastReadTab: lastReadTabsOf(s)[0] } : {}), + ...(lastReadTabsOf(s).length > 1 ? { lastReadTabs: lastReadTabsOf(s) } : {}), reads: s.reads.length, lastReadAt: s.reads.reduce<string | null>((a, r) => (a === null || r.at > a ? r.at : a), null), })), diff --git a/common/lib/xTrending/watch.ts b/common/lib/xTrending/watch.ts @@ -41,6 +41,15 @@ export const X_TRENDING_WATCH_PAUSE_REASONS: readonly XTrendingWatchPauseReason[ // the watch pauses ("failing") until a person switches it on again. export const X_TRENDING_WATCH_MAX_FAILURES = 3; +// A watch's tabs when it does NOT read both (both is the default and is not +// written): ["top"] or ["latest"]. Anything else reads both. +export function watchTabsOf(v: unknown): Array<"top" | "latest"> | undefined { + if (!Array.isArray(v)) return undefined; + const asked = new Set(v.filter((t): t is string => typeof t === "string").map((t) => t.toLowerCase())); + const tabs = (["top", "latest"] as const).filter((t) => asked.has(t)); + return tabs.length === 1 ? [...tabs] : undefined; +} + export type XTrendingWatch = { on: boolean; intervalMinutes: number; @@ -48,6 +57,8 @@ export type XTrendingWatch = { startedAt: string; until: string; shots: boolean; + // The ONE tab each tick reads, when not both (R3): ["top"] or ["latest"]. + tabs?: Array<"top" | "latest">; by: "agent" | "operator"; // The last tick the scan enqueued: when, its job, and when the next is due. lastTickAt?: string; @@ -87,6 +98,7 @@ function parseWatch(raw: unknown): XTrendingWatch | null { startedAt: r.startedAt, until: r.until, shots: r.shots === true, + ...(watchTabsOf(r.tabs) ? { tabs: watchTabsOf(r.tabs) } : {}), by: r.by === "operator" ? "operator" : "agent", ...(iso(r.lastTickAt) ? { lastTickAt: r.lastTickAt } : {}), ...(str(r.lastJobId) ? { lastJobId: r.lastJobId } : {}), @@ -142,6 +154,9 @@ export type SetWatchAsk = { intervalMinutes: number; hours: number; shots?: boolean; + // The page's tabs each tick reads: ["top"], ["latest"] or both. Absent: + // what the watch had, else both. + tabs?: ReadonlyArray<"top" | "latest">; by: "agent" | "operator"; maxTopics: number; now: number; @@ -211,6 +226,7 @@ export async function setXTrendingWatch(channelRoot: string, ask: SetWatchAsk): startedAt: live?.startedAt ?? at, until, shots: ask.shots ?? live?.shots ?? false, + ...(watchTabsOf(ask.tabs ?? live?.tabs) ? { tabs: watchTabsOf(ask.tabs ?? live?.tabs) } : {}), by: ask.by, ...(live?.lastTickAt ? { lastTickAt: live.lastTickAt } : {}), ...(live?.lastJobId ? { lastJobId: live.lastJobId } : {}), @@ -232,7 +248,9 @@ export async function setXTrendingWatch(channelRoot: string, ask: SetWatchAsk): 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" : ""}`; + const every = + `every ${w.intervalMinutes} min until ${hhmm(Date.parse(w.until))} UTC${w.shots ? ", screenshotting every new post" : ""}` + + (w.tabs ? `, reading the "${w.tabs[0] === "latest" ? "Latest" : "Top"}" tab only` : ""); if (w.paused?.reason === "failing") return `Watched ${every} — PAUSED since ${hhmm(Date.parse(w.paused.since))} UTC, until the operator switches it on again: ${w.paused.sentence}`; 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; diff --git a/common/social/__fixtures__/xTrendingCapture.ts b/common/social/__fixtures__/xTrendingCapture.ts @@ -121,12 +121,12 @@ function entry(t: FixtureTweet): Record<string, unknown> { } // One timeline answer holding these posts. -export function fixtureTimelineBody(tweets: FixtureTweet[]): Record<string, unknown> { +export function fixtureTimelineBody(tweets: FixtureTweet[], bottom: string = FIXTURE_BOTTOM_CURSOR): Record<string, unknown> { return { data: { timeline: { instructions: [ - { type: "TimelineAddEntries", entries: [...tweets.map(entry), { entryId: "cursor-bottom-1", content: { entryType: "TimelineTimelineCursor", cursorType: "Bottom", value: FIXTURE_BOTTOM_CURSOR } }] }, + { type: "TimelineAddEntries", entries: [...tweets.map(entry), { entryId: "cursor-bottom-1", content: { entryType: "TimelineTimelineCursor", cursorType: "Bottom", value: bottom } }] }, ], }, }, @@ -155,11 +155,11 @@ export const FIXTURE_SECOND_PAGE: FixtureTweet[] = [ // page's next request for that timeline carries. export const FIXTURE_BOTTOM_CURSOR = "fixture-cursor"; -const graphqlUrl = (op: string, n: number, cursor?: string) => +const graphqlUrl = (op: string, n: number, cursor?: string, timelineId: string = FIXTURE_TOP_TIMELINE) => `https://x.com/i/api/graphql/fixtureQueryId${n}/${op}?variables=${encodeURIComponent( JSON.stringify({ rest_id: FIXTURE_TREND_ID, - ...(op === FIXTURE_TIMELINE_OP ? { timelineId: FIXTURE_TOP_TIMELINE } : {}), + ...(op === FIXTURE_TIMELINE_OP ? { timelineId } : {}), ...(cursor ? { cursor } : {}), }), )}`; @@ -167,8 +167,40 @@ const graphqlUrl = (op: string, n: number, cursor?: string) => // The address of a request for the page's timeline (the tab the page opens // on): its `variables` name the timeline, and the cursor it continues from // when it is not the first. -export function fixtureTimelineUrl(n = 2, cursor?: string): string { - return graphqlUrl(FIXTURE_TIMELINE_OP, n, cursor); +export function fixtureTimelineUrl(n = 2, cursor?: string, timelineId: string = FIXTURE_TOP_TIMELINE): string { + return graphqlUrl(FIXTURE_TIMELINE_OP, n, cursor, timelineId); +} + +// THE PAGE'S OTHER TAB, "Latest" (lane x-followups): its own timeline and its +// own cursor. `fixtureLatestFirst` is what pressing the tab brings; +// `fixtureLatestContinuation` what a scroll then brings (no post: the tab's end). +export const FIXTURE_LATEST_CURSOR = "fixture-latest-cursor"; +export function fixtureLatestFirst(tweets: FixtureTweet[], n = 20): FixtureResponse { + return { url: graphqlUrl(FIXTURE_TIMELINE_OP, n, undefined, FIXTURE_LATEST_TIMELINE), status: 200, body: fixtureTimelineBody(tweets, FIXTURE_LATEST_CURSOR) }; +} +export function fixtureLatestContinuation(tweets: FixtureTweet[] = [], n = 21): FixtureResponse { + return { url: graphqlUrl(FIXTURE_TIMELINE_OP, n, FIXTURE_LATEST_CURSOR, FIXTURE_LATEST_TIMELINE), status: 200, body: fixtureTimelineBody(tweets, FIXTURE_LATEST_CURSOR) }; +} +// What "Latest" lists: a post only it shows, and two that "Top" shows too. +export const FIXTURE_LATEST_PAGE: FixtureTweet[] = [ + { id: "1900000000000001009", handle: "lid_watch", text: "Just now: the doors are open." }, + { id: "1900000000000001001", handle: "teapot_news", name: "Teapot News", text: "The kettle festival opens today.", media: ["photo", "photo"] }, + { id: "1900000000000001005", handle: "lid_watch", text: "A reply about the queue.", replyTo: { id: "1900000000000001001", handle: "teapot_news" }, media: ["animated_gif"] }, +]; +// The page with both tabs: "Top" as fixtureTrendingResponses plays it (read +// to its end by a continuation that brings nothing), and a "Latest" tab that +// can be pressed and is read to its end too. +export function fixtureTwoTabResponses(latest: FixtureTweet[] = FIXTURE_LATEST_PAGE): { + load: FixtureResponse[]; + scrolls: FixtureResponse[][]; + tabs: Record<string, { load?: FixtureResponse[]; scrolls?: FixtureResponse[][]; hidden?: boolean }>; +} { + const top = fixtureTrendingResponses(); + return { + load: top.load, + scrolls: [top.scrolls[0], [fixtureContinuation([], 5)], []], + tabs: { Latest: { load: [fixtureLatestFirst(latest)], scrolls: [[fixtureLatestContinuation([])], []] } }, + }; } // The page asking its timeline for MORE: the request carries the bottom cursor diff --git a/common/social/fakeXProfileBrowser.ts b/common/social/fakeXProfileBrowser.ts @@ -17,7 +17,8 @@ // exists (a spec writes it). The file holds SYNTHETIC cookies only: // { "delayMs"?: number, "closeAfterMs"?: number, "fail"?: string, // "cookies": [{ name, value, domain, path?, expires? }], -// "trending"?: { href?, load: [{url, status, body?, text?}], scrolls: [[…], …] } } +// "trending"?: { href?, load: [{url, status, body?, text?}], scrolls: [[…], …], +// tabs?: { "<label>": { load?, scrolls?, hidden? } } } } // // A TRENDING PAGE (lane x-trending): with `trending` in the file, the fake's // page answers a read of x.com/i/trending/<id> (xTrendingRead.ts) from it — @@ -40,6 +41,12 @@ export type FakeTrendingPage = { gotoError?: string; load: FakeTrendingResponse[]; scrolls?: FakeTrendingResponse[][]; + // THE PAGE'S OTHER TABS (lane x-followups), by the label the page shows: + // pressing one (getByRole("tab", {name})) plays its `load` back and makes + // its `scrolls` the ones the next scrolls bring. A tab with `hidden` is not + // on the page at all; one with no `load` is pressed and brings nothing (a + // tab that never loads). + tabs?: Record<string, { load?: FakeTrendingResponse[]; scrolls?: FakeTrendingResponse[][]; hidden?: boolean }>; }; type FixtureFile = { @@ -68,6 +75,8 @@ export function fakeTrendingPage( const handlers: Array<(res: unknown) => void> = []; let asked = ""; let scrolled = 0; + // The tab pressed last ("" = the tab the page opened on). + let active = ""; const emit = (responses: FakeTrendingResponse[] | undefined) => { for (const r of responses ?? []) { const res = { @@ -84,6 +93,7 @@ export function fakeTrendingPage( if (f.delayMs && f.delayMs > 0) await wait(Math.min(f.delayMs, 30_000)); asked = url; scrolled = 0; + active = ""; if (f.trending?.gotoError) throw new Error(f.trending.gotoError); emit(f.trending?.load); return null; @@ -94,9 +104,26 @@ export function fakeTrendingPage( const t = source().trending; if (!t) return null; if (fn === "location.href") return t.href ?? asked; - if (fn.includes("scrollTo")) emit(t.scrolls?.[scrolled++]); + if (fn.includes("scrollTo")) emit((active ? t.tabs?.[active]?.scrolls : t.scrolls)?.[scrolled++]); return null; }, + // The page's tabs, pressed as a person presses them. Only role "tab". + getByRole: (role: string, opts?: { name?: string | RegExp }) => { + const name = typeof opts?.name === "string" ? opts.name : ""; + const tab = role === "tab" ? source().trending?.tabs?.[name] : undefined; + const there = Boolean(tab && !tab.hidden); + return { + count: async () => (there ? 1 : 0), + first: () => ({ + click: async () => { + if (!there) throw new Error(`no tab named ${name}`); + active = name; + scrolled = 0; + emit(source().trending?.tabs?.[name]?.load); + }, + }), + }; + }, on: (event: string, cb: (arg: never) => void) => { if (event === "response") handlers.push(cb as (res: unknown) => void); }, diff --git a/common/social/importPost.test.ts b/common/social/importPost.test.ts @@ -45,7 +45,10 @@ channel("synth-kitchen", { name: "Synth Kitchen", handling: "youtube", url: "htt const { getPaths } = await import("../lib/paths"); const { readAllPosts } = await import("../lib/posts-server"); const { parsePostUrl } = await import("./fetchers"); -const { importPost, planImportPost, NOT_A_POST_URL } = await import("./importPost"); +// X is asked only inside a job of the editor's, on X's queue (lib/xJobRule.ts): these calls stand where one does. +const { importPost: importPostDirect, planImportPost, NOT_A_POST_URL } = await import("./importPost"); +const { insideEditorJob } = await import("../testing/jobs/asEditorJob"); +const importPost = insideEditorJob(importPostDirect); const { xGalleryDlFetcher } = await import("./xGalleryDlFetcher"); const { readFileSync } = await import("node:fs"); type Fetcher = import("./fetchers").SocialFetcher; @@ -181,3 +184,20 @@ test("X through gallery-dl: the status URL is what it reads, and the one post it const archived = await readAllPosts(path.join(ROOT, "channels", "synth-gdl")); assert.deepEqual(archived.map((p) => p.id), ["1700000000000000077"], "the quoted post is not written"); }); + +// Added scope R2 (lane x-followups): where X is about to be asked, only a job on X's queue stands. +test("R2a: importing an X post outside the editor's job, or in a job on another queue, asks the fetcher nothing; a Bluesky post is not X's", async () => { + const { asEditorJob } = await import("../testing/jobs/asEditorJob"); + const { f, asked } = fakeFetcher("twitter", (id) => post(id, "synthbaker")); + const ask = { paths, slug: "synth-social", url: "https://x.com/synthbaker/status/1700000000000000555", settings: {}, fetcherFor: () => f }; + const outside = await importPostDirect(ask); + assert.equal(outside.ok, false); + assert.match(outside.error ?? "", /^Importing https:\/\/x\.com\/synthbaker\/status\/1700000000000000555 asks X, and X is asked only by the editor's own jobs .*Queue it instead: pnpm ops import-post/); + const elsewhere = await asEditorJob(() => importPostDirect(ask), { queueKey: "platform:youtube" }); + assert.match(elsewhere.error ?? "", /X jobs run on X's queue only \(platform:twitter\): the queue "platform:youtube" is refused/); + assert.deepEqual(asked, []); + // Bluesky has no such rule: read with no job at all. + const sky = fakeFetcher("bluesky", () => null); + const r = await importPostDirect({ paths, slug: "synth-sky", url: "https://bsky.app/profile/synthbaker.bsky.social/post/3kother", settings: {}, fetcherFor: () => sky.f }); + assert.doesNotMatch(r.error ?? "", /asks X/); +}); diff --git a/common/social/importPost.ts b/common/social/importPost.ts @@ -17,6 +17,7 @@ // platform's queue, so it never runs beside a fetch of the same source. // A post already archived is not read again. +import { xJobContextRefusal } from "../lib/xJobRule"; import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "../lib/sourcelessPosts"; import path from "node:path"; import type { Paths } from "../lib/paths"; @@ -144,6 +145,11 @@ export async function importPost(opts: { log(`Post ${ref.id} is already in ${opts.slug}'s archive; nothing to read.`); return { ...base, ok: true, already: true }; } + // X is asked only by the editor's jobs, on X's queue (lib/xJobRule.ts). + if (fetcher.platform === "twitter") { + const refusal = xJobContextRefusal(`Importing ${ref.url}`, `pnpm ops import-post --json '{"slug":"${opts.slug}","url":"…"}' --wait`); + if (refusal) return { ...base, ok: false, error: refusal }; + } const policy = resolveCookiePolicy(opts.settings, config); const xLogin = fetcher.platform === "twitter" ? await resolveXCookieSourceFor(opts.paths, opts.settings, policy.cookies) : undefined; diff --git a/common/social/playwrightRuntime.ts b/common/social/playwrightRuntime.ts @@ -49,6 +49,14 @@ export type PageLike = { waitForTimeout: (ms: number) => Promise<void>; evaluate: (fn: string) => Promise<unknown>; on: (event: string, cb: (arg: never) => void) => void; + // Something the page shows, found as a person finds it — by its role and + // its name (Playwright's getByRole) — and pressed. A trending read presses + // the page's own tab with it (xTrendingRead.ts); nothing else does. + // Optional: a page without it has nothing to press. + getByRole?: ( + role: string, + opts?: { name?: string | RegExp; exact?: boolean }, + ) => { count: () => Promise<number>; first: () => { click: (opts?: { timeout?: number }) => Promise<void> } }; // The post capture's shot (xPostCapture.ts): a PNG of the page, clipped to // the post. `clip` is in document coordinates when `fullPage` is set, in // the window's otherwise. diff --git a/common/social/xTrendingParse.test.ts b/common/social/xTrendingParse.test.ts @@ -254,7 +254,7 @@ test("the real shape: a capture parses to the page's posts once each, the page, assert.equal(parsed.posts[1].quoted?.id, "1900000000000002900"); assert.equal(parsed.page?.title, real.INVENTED_TITLE); assert.equal(parsed.page?.summary, real.INVENTED_SUMMARY); - assert.deepEqual(parsed.timelines, [{ timelineId: real.INVENTED_TOP_TIMELINE, tab: "Top", posts: 6 }]); + assert.deepEqual(parsed.timelines, [{ timelineId: real.INVENTED_TOP_TIMELINE, tab: "Top", posts: 6, postIds: parsed.posts.map((p) => p.id), pageEnd: false }]); assert.deepEqual(new Set(Object.values(parsed.tabs)), new Set(["Top"])); assert.equal(Object.keys(parsed.tabs).length, 6); assert.deepEqual( @@ -269,7 +269,7 @@ test("the real shape: a capture parses to the page's posts once each, the page, // A capture with no page answer: posts all the same, no page, a timeline that is no known tab. const bare = parseTrendingCapture(linesOf([real.realFirstPage(real.INVENTED_FIRST)]), "lib"); assert.equal(bare.page, undefined); - assert.deepEqual(bare.timelines, [{ timelineId: real.INVENTED_TOP_TIMELINE, posts: 3 }]); + assert.deepEqual(bare.timelines.map((t) => [t.timelineId, t.tab, t.posts, t.pageEnd]), [[real.INVENTED_TOP_TIMELINE, undefined, 3, false]]); assert.deepEqual(bare.tabs, {}); // The old fixture names no timeline: one untagged timeline. assert.deepEqual(parseTrendingCapture(linesOf(fixtureTrendingResponses().load), "lib").timelines.map((t) => t.timelineId), [FIXTURE_TOP_TIMELINE]); @@ -336,10 +336,20 @@ test("the real shape: two tabs in one capture show no end, and each post is the ]; const parsed = parseTrendingCapture(linesOf(responses), "lib"); assert.equal(parsed.pageEnd, false); + // PER TIMELINE: each tab's own posts in its own order (a post both show is in both), and each tab's own end. assert.deepEqual(parsed.timelines, [ - { timelineId: real.INVENTED_TOP_TIMELINE, tab: "Top", posts: 3 }, - { timelineId: real.INVENTED_LATEST_TIMELINE, tab: "Latest", posts: 1 }, + { timelineId: real.INVENTED_TOP_TIMELINE, tab: "Top", posts: 3, postIds: ["1900000000000003001", "1900000000000003002", "1900000000000003003"], pageEnd: true }, + { timelineId: real.INVENTED_LATEST_TIMELINE, tab: "Latest", posts: 1, postIds: ["1900000000000003004", "1900000000000003001"], pageEnd: true }, ]); + // One tab at its end and the other capped: said of each by itself. + const capped = parseTrendingCapture(linesOf(responses.slice(0, -1)), "lib"); + assert.deepEqual(capped.timelines.map((t) => [t.tab, t.pageEnd]), [["Top", true], ["Latest", false]]); + // A continuation that brings only posts the OTHER tab showed is not this tab's end: they are new to it. + const borrowed = [...responses.slice(0, -1), real.realContinuation([real.INVENTED_FIRST[1]], { ...latest, asked: "latest-1", bottom: "latest-2" })]; + assert.deepEqual(parseTrendingCapture(linesOf(borrowed), "lib").timelines.map((t) => [t.tab, t.pageEnd]), [["Top", true], ["Latest", false]]); + // A failed answer anywhere: neither tab shows an end. + const failed = [...responses, { url: real.realStoryTopics().url, status: 500 }]; + assert.deepEqual(parseTrendingCapture(linesOf(failed), "lib").timelines.map((t) => t.pageEnd), [false, false]); assert.equal(parsed.tabs["1900000000000003001"], "Top"); assert.equal(parsed.tabs["1900000000000003004"], "Latest"); // Each tab alone, read to its end, shows it: the continuation is its own timeline's. diff --git a/common/social/xTrendingParse.ts b/common/social/xTrendingParse.ts @@ -393,10 +393,13 @@ export type ParsedTrendingCapture = { // included. Only a capture that shows the end may be read as "what this // page no longer shows". // - // ONE TIMELINE (lane x-followups): the continuation is the last answer's - // OWN timeline's (the same operation asked for the same timeline id), and a - // capture that lists two timelines — two tabs of the page — shows no end: - // what one tab no longer shows says nothing of the other. + // PER TIMELINE (lane x-followups): a trending page has tabs, each its own + // timeline, and one read may list two of them (Top, then Latest). The rule + // above is asked of EACH timeline by itself (`timelines[].pageEnd`): its own + // last answer, continuing from its own previous bottom cursor, bringing no + // post that timeline had not shown. What one tab no longer shows says + // nothing of the other. `pageEnd` here is the one timeline's when the + // capture lists exactly one, and false for a capture that lists two. pageEnd: boolean; // What the page says of itself (trendPageOf), when an answer carried it. page?: TrendingPageInfo; @@ -404,7 +407,9 @@ export type ParsedTrendingCapture = { // timeline id its requests named (absent when they named none), the tab of // the page it is (when the page names that id), and how many of the page's // posts it showed first. - timelines: Array<{ timelineId?: string; tab?: string; posts: number }>; + // `postIds`: every post that timeline listed, in its own order (a post two + // tabs show is in both); `pageEnd`: the capture shows that timeline's end. + timelines: Array<{ timelineId?: string; tab?: string; posts: number; postIds: string[]; pageEnd: boolean }>; // Post id → the label of the tab that showed it first, for the posts whose // timeline is one of the page's tabs. tabs: Record<string, string>; @@ -422,7 +427,9 @@ export function parseTrendingCapture( // Per answer of the page's own operations, in order: its operation, the // timeline it asked for, and how many posts it brought that no earlier // answer had. - const answers: Array<{ op: string; timelineId?: string; fresh: number; asked?: string; bottom?: string; instructions: boolean }> = []; + const answers: Array<{ op: string; timelineId?: string; fresh: number; freshOfTimeline: number; asked?: string; bottom?: string; instructions: boolean }> = []; + // Timeline id ("" when a request named none) → the posts it listed, in order. + const listedBy = new Map<string, string[]>(); const seenIds = new Set<string>(); // Post id → the timeline id of the answer that showed it first. const firstTimeline = new Map<string, string>(); @@ -449,9 +456,19 @@ export function parseTrendingCapture( op.tweets += found.length; const asked = requestVariablesOf(line.url); let fresh = 0; + let freshOfTimeline = 0; + const key = asked.timelineId ?? ""; for (const raw of found) { raws.push(raw); const id = xIdOf(raw); + if (id) { + const listed = listedBy.get(key) ?? []; + listedBy.set(key, listed); + if (!listed.includes(id)) { + listed.push(id); + freshOfTimeline++; + } + } if (id && !seenIds.has(id)) { seenIds.add(id); fresh++; @@ -464,6 +481,7 @@ export function parseTrendingCapture( answers.push({ op: line.op, fresh, + freshOfTimeline, instructions: shape.instructions, ...(asked.timelineId ? { timelineId: asked.timelineId } : {}), ...(asked.cursor ? { asked: asked.cursor } : {}), @@ -473,18 +491,18 @@ export function parseTrendingCapture( // The answers of the operations that ever listed posts, in order. const listing = answers.filter((a) => (ops.get(a.op)?.tweets ?? 0) > 0); if (listing.some((a) => !a.instructions)) failed = true; - const last = listing.at(-1); - // The answer before it of the same operation AND the same timeline: whose - // bottom cursor it must carry. - const before = last ? listing.slice(0, -1).filter((a) => a.op === last.op && a.timelineId === last.timelineId).at(-1) : undefined; const timelineIds = [...new Set(listing.map((a) => a.timelineId).filter((id): id is string => id !== undefined))]; - const pageEnd = - !failed && - last !== undefined && - timelineIds.length <= 1 && - before?.bottom !== undefined && - last.asked === before.bottom && - last.fresh === 0; + // One timeline's end: its own last answer continues from its own previous + // bottom cursor (the same operation) and brought nothing that timeline had + // not shown. + const endOf = (key: string): boolean => { + const own = listing.filter((a) => (a.timelineId ?? "") === key); + const last = own.at(-1); + const before = last ? own.slice(0, -1).filter((a) => a.op === last.op).at(-1) : undefined; + return !failed && last !== undefined && before?.bottom !== undefined && last.asked === before.bottom && last.freshOfTimeline === 0; + }; + const keys = [...new Set(listing.map((a) => a.timelineId ?? ""))]; + const pageEnd = keys.length === 1 && endOf(keys[0]); const posts = normalizeXTweets(raws, channelSlug); const kept: Record<string, TrendingMediaSummary> = {}; for (const p of posts) if (media[p.id]) kept[p.id] = media[p.id]; @@ -499,12 +517,18 @@ export function parseTrendingCapture( if (timelineId) shownFirst.set(timelineId, (shownFirst.get(timelineId) ?? 0) + 1); } const untagged = posts.length - [...shownFirst.values()].reduce((a, n) => a + n, 0); + const isPost = new Set(posts.map((p) => p.id)); + const listedOf = (key: string) => (listedBy.get(key) ?? []).filter((id) => isPost.has(id)); const timelines: ParsedTrendingCapture["timelines"] = timelineIds.map((timelineId) => ({ timelineId, ...(labelOf.get(timelineId) ? { tab: labelOf.get(timelineId)! } : {}), posts: shownFirst.get(timelineId) ?? 0, + postIds: listedOf(timelineId), + pageEnd: endOf(timelineId), })); - if (untagged > 0 || (timelines.length === 0 && listing.length > 0)) timelines.push({ posts: untagged }); + if (untagged > 0 || (timelines.length === 0 && listing.length > 0)) { + timelines.push({ posts: untagged, postIds: listedOf(""), pageEnd: keys.includes("") && endOf("") }); + } return { posts, media: kept, diff --git a/common/social/xTrendingRead.test.ts b/common/social/xTrendingRead.test.ts @@ -12,8 +12,13 @@ import { fakeTrendingPage, type FakeTrendingPage } from "./fakeXProfileBrowser"; import { bounded, isXLoginHref, openXTrendingPage, readXTrendingPage, type TrendingPageRead } from "./xTrendingRead"; import { readCaptureLines } from "./xTrendingParse"; import { + FIXTURE_LATEST_PAGE, + FIXTURE_LATEST_TIMELINE, FIXTURE_TIMELINE_OP, + FIXTURE_TOP_TIMELINE, FIXTURE_TREND_URL, + fixtureLatestFirst, + fixtureTwoTabResponses, fixtureTimelineBody, fixtureTrendingResponses, } from "./__fixtures__/xTrendingCapture"; @@ -26,7 +31,8 @@ after(() => rmSync(TMP, { recursive: true, force: true })); let dirs = 0; async function read( trending: FakeTrendingPage, - over: { scrolls?: number; posts?: number; signal?: AbortSignal } = {}, + // One tab unless a test asks for both: the page's other tab is R3's tests' (below). + over: { scrolls?: number; posts?: number; signal?: AbortSignal; tabs?: Array<"top" | "latest"> } = {}, ): Promise<{ result: TrendingPageRead; dir: string; closed: number; pauses: number[]; log: string[] }> { const dir = path.join(TMP, `read-${++dirs}`); const pauses: number[] = []; @@ -38,6 +44,7 @@ async function read( dir, openPage: async () => ({ page, close: async () => void closed++ }), limits: { scrolls: over.scrolls ?? 8, posts: over.posts ?? 60 }, + tabs: over.tabs ?? ["top"], pauseMs: () => 7_000, pause: async (ms) => void pauses.push(ms), signal: over.signal ?? new AbortController().signal, @@ -61,6 +68,7 @@ test("a read keeps every GraphQL answer raw and a screenshot, and stops after tw statuses: { "200": 4 }, tweets: 4, shot: true, + tabs: [{ asked: "top", tab: "Top", timelineId: FIXTURE_TOP_TIMELINE, scrolls: 3, posts: 4, stop: "idle" }], }); assert.ok(result.bytes > 0); assert.equal(closed, 1); @@ -547,3 +555,90 @@ test("kill ends the browser's own process when its pid checks out; else it says await mac.kill!(); assert.ok(log3.some((l) => /not killed \(finding the browser's process is Linux-only\); closing it again instead/.test(l))); }); + +// ── added scope R3: both tabs in one read ────────────────────────────────── + +const BOTH: Array<"top" | "latest"> = ["top", "latest"]; + +test("R3: the deadline covers what the read may do: 6 min for one tab at 20 scrolls, 10 for both, 18 at the maximum", async () => { + const { readDeadlineMs, READ_DEADLINE_MS, TAB_WAIT_MS } = await import("./xTrendingRead"); + assert.equal(readDeadlineMs({ scrolls: 20 }, 1), 6 * 60_000); + assert.equal(READ_DEADLINE_MS, 6 * 60_000); + assert.equal(readDeadlineMs({ scrolls: 20 }, 2), 10 * 60_000); + assert.equal(readDeadlineMs({ scrolls: 40 }, 2), 18 * 60_000); + assert.equal(TAB_WAIT_MS, 20_000); +}); + +test("R3: after Top is read to its stop the page's Latest tab is pressed and read under the same caps, into the one capture", async () => { + const { result, dir, pauses, log } = await read(fixtureTwoTabResponses(), { tabs: BOTH }); + assert.equal(result.stop, "idle"); + assert.deepEqual(result.tabs, [ + { asked: "top", tab: "Top", timelineId: FIXTURE_TOP_TIMELINE, scrolls: 3, posts: 4, stop: "idle" }, + { asked: "latest", tab: "Latest", timelineId: FIXTURE_LATEST_TIMELINE, scrolls: 2, posts: 3, stop: "idle" }, + ]); + assert.equal(result.scrolls, 5); + // Five distinct posts: two of Latest's three are Top's too. + assert.equal(result.tweets, 5); + assert.ok(log.includes('Pressed the page\'s "Latest" tab.')); + // One capture: Top's answers, then Latest's, each request naming its own timeline. + const lines = await readCaptureLines(path.join(dir, "responses.jsonl")); + const timelines = lines.filter((l) => l.op === FIXTURE_TIMELINE_OP).map((l) => JSON.parse(new URL(l.url).searchParams.get("variables")!).timelineId); + assert.deepEqual(timelines, [FIXTURE_TOP_TIMELINE, FIXTURE_TOP_TIMELINE, FIXTURE_TOP_TIMELINE, FIXTURE_LATEST_TIMELINE, FIXTURE_LATEST_TIMELINE]); + assert.equal(readFileSync(path.join(dir, "page-latest.png")).subarray(1, 4).toString(), "PNG"); + assert.equal(result.tabShot, true); + // Never two contacts in a row: a wait after the load, after every scroll, and after the press. + assert.ok(pauses.filter((ms) => ms === 7_000).length >= 1 + 5 + 1); +}); + +test("R3: a Latest tab the page does not show, or one whose press brings nothing, is \"not read\" with its reason — Top's read stands", async () => { + const hidden = fixtureTwoTabResponses(); + hidden.tabs.Latest.hidden = true; + const a = await read(hidden, { tabs: BOTH }); + assert.equal(a.result.stop, "idle"); + assert.deepEqual(a.result.tabs[1], { asked: "latest", tab: "Latest", timelineId: FIXTURE_LATEST_TIMELINE, scrolls: 0, posts: 0, stop: "not-read", why: 'the page shows no tab named "Latest"' }); + assert.deepEqual(a.result.tabs[0], { asked: "top", tab: "Top", timelineId: FIXTURE_TOP_TIMELINE, scrolls: 3, posts: 4, stop: "idle" }); + // Pressed, and the page asks nothing for it. + const silent = fixtureTwoTabResponses(); + silent.tabs.Latest = {}; + const b = await read(silent, { tabs: BOTH }); + assert.equal(b.result.stop, "idle"); + assert.equal(b.result.tabs[1].stop, "not-read"); + assert.equal(b.result.tabs[1].why, 'pressing "Latest" brought no answer for its timeline within 20 s'); + assert.equal(b.result.scrolls, 3, "no scroll followed a press that brought nothing"); + // The page's own answer names no tabs at all (it was not fetched). + const noPage = fixtureTwoTabResponses(); + noPage.load = noPage.load.slice(1); + const c = await read(noPage, { tabs: BOTH }); + assert.equal(c.result.tabs[1].stop, "not-read"); + assert.match(c.result.tabs[1].why ?? "", /page's own answer, which names its tabs and their timelines, was not among what it fetched/); + assert.equal(c.result.tabs[0].tab, undefined); + assert.equal(c.result.tabs[0].posts, 4); +}); + +test("R3: a 429 on Latest stops the whole read; a 429 on Top means Latest is never pressed", async () => { + const limited = fixtureTwoTabResponses(); + limited.tabs.Latest.scrolls = [[{ url: fixtureLatestFirst([]).url, status: 429, text: "" }]]; + const a = await read(limited, { tabs: BOTH }); + assert.equal(a.result.stop, "rate-limit"); + assert.equal(a.result.tabs[1].stop, "rate-limit"); + assert.equal(a.result.tabs[1].scrolls, 1); + assert.equal(a.result.tabs[0].stop, "idle"); + const onTop = fixtureTwoTabResponses(); + onTop.scrolls = [[{ url: fixtureTwoTabResponses().load[1].url, status: 429, text: "" }]]; + const b = await read(onTop, { tabs: BOTH }); + assert.equal(b.result.stop, "rate-limit"); + assert.equal(b.result.tabs.length, 1); + assert.ok(!b.log.some((l) => /Pressed/.test(l))); + assert.equal(existsSync(path.join(b.dir, "page-latest.png")), false); +}); + +test("R3: each tab has the full caps; asked for Latest alone, Top is not scrolled", async () => { + const many = fixtureTwoTabResponses(FIXTURE_LATEST_PAGE); + // Top stops at a post cap of 4 after its first scroll; Latest then has its own count of 3 and reads on. + const capped = await read(many, { tabs: BOTH, posts: 4 }); + assert.deepEqual(capped.result.tabs.map((t) => [t.asked, t.stop, t.posts]), [["top", "post-cap", 4], ["latest", "idle", 3]]); + const only = await read(fixtureTwoTabResponses(), { tabs: ["latest"] }); + assert.deepEqual(only.result.tabs.map((t) => [t.asked, t.stop, t.scrolls]), [["top", "not-asked", 0], ["latest", "idle", 2]]); + // What the page loaded of Top by itself is in the capture all the same. + assert.equal(only.result.tabs[0].posts, 3); +}); diff --git a/common/social/xTrendingRead.ts b/common/social/xTrendingRead.ts @@ -22,12 +22,24 @@ // NOTHING HERE WAITS FOREVER (review 1). Every call into the page is raced // against a deadline — the load 75 s, a scroll, a look at the address or a // screenshot 20 s each, closing the browser 10 s — and against the job's -// cancel; and the whole read against READ_DEADLINE_MS (6 minutes: twenty -// scrolls at the longest gap, twice over). A page that stops answering ends +// cancel; and the whole read against its deadline (readDeadlineMs: two +// minutes, and twelve seconds — the longest gap and a page call — for every +// scroll each tab may make). A page that stops answering ends // the read with a sentence, what was captured kept, and the browser is closed // (killed, when closing does not answer) so the profile is free again. Once // the read returns, nothing more is appended to responses.jsonl. // +// TWO TABS, ONE READ (lane x-followups, R3). A trending page has tabs — "Top", +// which it opens on, and "Latest" — each its own timeline. After the opening +// tab is read to its stop, the read PRESSES THE PAGE'S OWN TAB: the element +// with the tab's role and the label the page's own answer gave for it, found +// as a person finds it. It builds no request: it waits for the page's request +// for that tab's timeline (the timeline id the page's answer named) and then +// scrolls under the same caps. Each tab has the full scroll and post caps. +// A tab that is not found, or whose press brings no timeline answer within +// the wait, is "not read" with its reason: not a failure, and never retried. +// A 429, a 403, a 401 or a login page on either tab stops the whole read. +// // The caller (controller/readXTrending.ts) is one editor job on X's queue; // this module knows nothing of queues, alerts or the store. @@ -42,6 +54,7 @@ import { X_TRENDING_IDLE_SCROLLS, type XTrendingLimits } from "../lib/xTrending/ import { TRENDING_PAGE_SHOT_FILENAME, TRENDING_RESPONSES_FILENAME, + TRENDING_TAB_SHOT_FILENAME, } from "../lib/xTrending/store"; import { importPlaywright, type ChromiumLike, type PageLike } from "./playwrightRuntime"; import { launchHeadedContext, type HeadedDisplayLaunchDeps } from "./headedDisplay"; @@ -52,8 +65,11 @@ import { xIdOf } from "./xNormalize"; import { collectTimelineTweets, graphqlOpOf, + requestVariablesOf, + trendPageOf, X_TRENDING_IGNORED_OPS, type TrendingCaptureLine, + type TrendingPageInfo, } from "./xTrendingParse"; // One answer is kept up to this size, a read's answers up to this in all: @@ -66,7 +82,42 @@ export const TRENDING_READ_MAX_BYTES = 64 * 1024 * 1024; export const PAGE_LOAD_TIMEOUT_MS = 75_000; export const PAGE_CALL_TIMEOUT_MS = 20_000; export const PAGE_CLOSE_TIMEOUT_MS = 10_000; -export const READ_DEADLINE_MS = 6 * 60_000; +// How long the read waits, after pressing a tab, for the page's request for +// that tab's timeline. +export const TAB_WAIT_MS = 20_000; +// One whole read: two minutes for the load, the screenshots and the tab +// press, and twelve seconds (the longest gap, 10 s, and a page call) for +// every scroll each tab may make. One tab at 20 scrolls: 6 minutes (what a +// read always had). Both tabs at the default 20 scrolls: 10 minutes. Both at +// the maximum 40: 18 minutes. +export const READ_DEADLINE_BASE_MS = 2 * 60_000; +export const READ_DEADLINE_PER_SCROLL_MS = 12_000; +export function readDeadlineMs(limits: Pick<XTrendingLimits, "scrolls">, tabs: number): number { + return READ_DEADLINE_BASE_MS + Math.max(1, tabs) * limits.scrolls * READ_DEADLINE_PER_SCROLL_MS; +} +export const READ_DEADLINE_MS = readDeadlineMs({ scrolls: 20 }, 1); + +// The tabs a read may be asked for, and in the order it reads them: the tab +// the page opens on, then the other. +export type TrendingTabAsk = "top" | "latest"; +export const TRENDING_TAB_ASKS: readonly TrendingTabAsk[] = ["top", "latest"]; +export const TRENDING_TAB_LABEL: Readonly<Record<TrendingTabAsk, string>> = { top: "Top", latest: "Latest" }; + +// One tab of a read: what was asked, the page's own label and timeline for it +// (when the page's answer named one), how it went. +// stop why its scrolling stopped (TrendingReadStop), or +// "not-read": the tab was asked for and could not be opened — +// `why` says so — or "not-asked": the page loaded it (the tab it +// opens on) and the read was asked for the other only. +export type TrendingTabRead = { + asked: TrendingTabAsk; + tab?: string; + timelineId?: string; + scrolls: number; + posts: number; + stop: TrendingReadStop | "not-read" | "not-asked"; + why?: string; +}; // Why a read stopped scrolling. // idle two scrolls in a row brought no new post: the page's end @@ -106,6 +157,13 @@ export type TrendingPageRead = { // The FIRST answer that stopped the read — a 429, a 403 or a 401 — by its // operation and status, so a read's record says which request it was. stoppedBy?: { op: string; status: number }; + // Tab by tab, in the order they were read. `stop` and `scrolls` above are + // the whole read's: the stop of the last tab that was scrolled (or the + // answer that stopped everything), and every scroll. + tabs: TrendingTabRead[]; + // page-latest.png was written (the page after the second tab was pressed, + // or after the press was tried). + tabShot?: boolean; }; // `kill` ends the browser when `close` does not answer: the process itself, @@ -184,6 +242,8 @@ export async function readXTrendingPage(o: { dir: string; openPage: () => Promise<TrendingPageSession>; limits: XTrendingLimits; + // The tabs to read (default: both), read in the page's order. + tabs?: ReadonlyArray<TrendingTabAsk>; pauseMs: () => number; pause?: (ms: number, signal: AbortSignal) => Promise<void>; signal: AbortSignal; @@ -192,7 +252,7 @@ export async function readXTrendingPage(o: { // The byte caps and the deadlines, for tests (defaults: the constants above). maxResponseBytes?: number; maxReadBytes?: number; - timeouts?: { load?: number; call?: number; close?: number; read?: number }; + timeouts?: { load?: number; call?: number; close?: number; read?: number; tab?: number }; }): Promise<TrendingPageRead> { const log = o.onLog ?? (() => {}); const pause = o.pause ?? abortablePause; @@ -203,8 +263,10 @@ export async function readXTrendingPage(o: { load: o.timeouts?.load ?? PAGE_LOAD_TIMEOUT_MS, call: o.timeouts?.call ?? PAGE_CALL_TIMEOUT_MS, close: o.timeouts?.close ?? PAGE_CLOSE_TIMEOUT_MS, - read: o.timeouts?.read ?? READ_DEADLINE_MS, + read: o.timeouts?.read ?? readDeadlineMs(o.limits, (o.tabs ?? TRENDING_TAB_ASKS).length), + tab: o.timeouts?.tab ?? TAB_WAIT_MS, }; + const wanted = TRENDING_TAB_ASKS.filter((t) => (o.tabs ?? TRENDING_TAB_ASKS).includes(t)); // The read's own clock: fired at its deadline, and by the job's cancel. const clock = new AbortController(); let pastDeadline = false; @@ -229,8 +291,18 @@ export async function readXTrendingPage(o: { statuses: {}, tweets: 0, shot: false, + tabs: [], }; const seen = new Set<string>(); + // Per timeline the page asked for ("" for a request that named none): the + // posts it listed, and how many answers it has had. + const seenBy = new Map<string, Set<string>>(); + const answersBy = new Map<string, number>(); + // What the page said of itself: its tabs' labels and timelines. + let pageInfo: TrendingPageInfo | undefined; + // The first timeline the page asked for: the tab it opens on, whether or + // not the page's own answer (which names the tabs) was among what it fetched. + let firstTimeline: string | undefined; let rateLimited = false; let unauthorized = false; let forbidden = false; @@ -286,9 +358,18 @@ export async function readXTrendingPage(o: { out.saved++; keep({ ...base, bytes, body }); if (status >= 200 && status < 300 && !X_TRENDING_IGNORED_OPS.includes(op)) { - for (const raw of collectTimelineTweets(body)) { + pageInfo ??= trendPageOf(body); + const timeline = requestVariablesOf(url).timelineId ?? ""; + const found = collectTimelineTweets(body); + if (timeline || found.length) answersBy.set(timeline, (answersBy.get(timeline) ?? 0) + 1); + if (timeline && found.length) firstTimeline ??= timeline; + const own = seenBy.get(timeline) ?? new Set<string>(); + seenBy.set(timeline, own); + for (const raw of found) { const id = xIdOf(raw); - if (id) seen.add(id); + if (!id) continue; + seen.add(id); + own.add(id); } } })().catch(() => { @@ -339,28 +420,137 @@ export async function readXTrendingPage(o: { } log(`The page loaded: ${out.responses} answer(s), ${seen.size} post(s) so far.`); - let idle = 0; - let stop: TrendingReadStop | null = blocked(); - while (!stop) { - if (signal.aborted) stop = pastDeadline ? "deadline" : "cancelled"; - else if (seen.size >= o.limits.posts) stop = "post-cap"; - else if (out.scrolls >= o.limits.scrolls) stop = "scroll-cap"; - if (stop) break; - const before = seen.size; - await bounded("scrolling", page.evaluate(SCROLL_TO_BOTTOM), t.call, signal); - out.scrolls++; - await pause(o.pauseMs(), signal); - await settle(); - stop = blocked(); - if (stop) break; - if (seen.size === before) { - if (++idle >= X_TRENDING_IDLE_SCROLLS) stop = "idle"; + // THE PAGE'S TABS, as its own answer named them. The tab it opens on is + // "Top"; with no such answer the opening tab is whatever the page lists. + const tabOf = (ask: TrendingTabAsk) => + pageInfo?.tabs.find((t) => t.label.trim().toLowerCase() === TRENDING_TAB_LABEL[ask].toLowerCase()); + // The posts one tab has listed so far: its own timeline's, else (a page + // that named no tabs) every post seen. + const countOf = (timelineId: string | undefined) => (timelineId ? (seenBy.get(timelineId)?.size ?? 0) : seen.size); + + // One tab scrolled to its stop, under the read's caps. + const scrollTab = async (timelineId: string | undefined): Promise<{ stop: TrendingReadStop; scrolls: number }> => { + let idle = 0; + let scrolls = 0; + let stop: TrendingReadStop | null = blocked(); + while (!stop) { + if (signal.aborted) stop = pastDeadline ? "deadline" : "cancelled"; + else if (countOf(timelineId) >= o.limits.posts) stop = "post-cap"; + else if (scrolls >= o.limits.scrolls) stop = "scroll-cap"; + if (stop) break; + const before = countOf(timelineId); + await bounded("scrolling", page.evaluate(SCROLL_TO_BOTTOM), t.call, signal); + scrolls++; + out.scrolls++; + await pause(o.pauseMs(), signal); + await settle(); + stop = blocked(); + if (stop) break; + if (countOf(timelineId) === before) { + if (++idle >= X_TRENDING_IDLE_SCROLLS) stop = "idle"; + } else { + idle = 0; + } + log(`Scroll ${out.scrolls}: ${countOf(timelineId)} post(s) on this tab, ${out.responses} answer(s).`); + } + return { stop: stop ?? "idle", scrolls }; + }; + // A stop that ends the whole read, not one tab's scrolling. + const ends = (stop: TrendingReadStop) => stop !== "idle" && stop !== "scroll-cap" && stop !== "post-cap"; + + // THE TAB THE PAGE OPENS ON. + const named = tabOf("top"); + const top = named ?? (firstTimeline ? { label: undefined, timelineId: firstTimeline } : undefined); + const openingTab: TrendingTabRead = { + asked: "top", + ...(top?.label ? { tab: top.label } : {}), + ...(top ? { timelineId: top.timelineId } : {}), + scrolls: 0, + posts: 0, + stop: "not-asked", + }; + out.tabs.push(openingTab); + let stop: TrendingReadStop = blocked() ?? "idle"; + if (wanted.includes("top") || blocked()) { + const r = await scrollTab(top?.timelineId); + openingTab.stop = r.stop; + openingTab.scrolls = r.scrolls; + stop = r.stop; + } + openingTab.posts = countOf(top?.timelineId); + + // THE OTHER TAB: pressed, never asked for. + if (wanted.includes("latest") && !ends(stop)) { + const latest = tabOf("latest"); + const second: TrendingTabRead = { + asked: "latest", + ...(latest ? { tab: latest.label, timelineId: latest.timelineId } : {}), + scrolls: 0, + posts: 0, + stop: "not-read", + }; + out.tabs.push(second); + const label = latest?.label ?? TRENDING_TAB_LABEL.latest; + if (!latest) { + second.why = pageInfo + ? `the page's own answer names no "${label}" tab (it names: ${pageInfo.tabs.map((x) => `"${x.label}"`).join(", ") || "none"})` + : "the page's own answer, which names its tabs and their timelines, was not among what it fetched"; + } else if (!page.getByRole) { + second.why = "this page cannot be pressed"; } else { - idle = 0; + // The page's own control: a tab by role, else a link or a button of that name. + let pressed = false; + const had = answersBy.get(latest.timelineId) ?? 0; + for (const role of ["tab", "link", "button"]) { + const found = page.getByRole(role, { name: latest.label, exact: true }); + const count = await bounded(`looking for the "${label}" tab`, found.count(), t.call, signal).catch((err) => { + if (err instanceof PageDeadlineError) throw err; + return 0; + }); + if (!count) continue; + await bounded(`pressing the "${label}" tab`, found.first().click({ timeout: Math.min(t.call, 15_000) }), t.call, signal); + pressed = true; + log(`Pressed the page's "${label}" tab.`); + break; + } + if (!pressed) { + second.why = `the page shows no tab named "${label}"`; + } else { + // The page's own request for that tab's timeline: waited for, in short steps. + for (let waited = 0; waited < t.tab && (answersBy.get(latest.timelineId) ?? 0) <= had && !signal.aborted && !blocked(); waited += 500) { + await pause(500, signal); + await settle(); + } + if (blocked()) { + second.stop = blocked()!; + stop = second.stop; + } else if (signal.aborted) { + second.stop = pastDeadline ? "deadline" : "cancelled"; + stop = second.stop; + } else if ((answersBy.get(latest.timelineId) ?? 0) <= had) { + second.why = `pressing "${label}" brought no answer for its timeline within ${Math.round(t.tab / 1000)} s`; + } else { + await pause(o.pauseMs(), signal); + await settle(); + const r = await scrollTab(latest.timelineId); + second.stop = r.stop; + second.scrolls = r.scrolls; + stop = r.stop; + } + } + } + second.posts = countOf(latest?.timelineId); + // The page as it stood after the press (or the try): beside page.png. + try { + const png = await bounded("the second screenshot", page.screenshot({ type: "png" }), t.call, signal); + await writeFile(path.join(o.dir, TRENDING_TAB_SHOT_FILENAME), png); + out.tabShot = true; + } catch (err) { + if (err instanceof PageDeadlineError) throw err; } - log(`Scroll ${out.scrolls}: ${seen.size} post(s), ${out.responses} answer(s).`); + if (second.stop === "not-read") log(`The "${label}" tab was not read: ${second.why}.`); } - out.stop = stop ?? "idle"; + out.stop = stop; } catch (err) { const hung = err instanceof PageDeadlineError || pastDeadline; out.stop = blocked() ?? (hung ? "deadline" : o.signal.aborted ? "cancelled" : "error"); diff --git a/common/views/schedulerStatus.ts b/common/views/schedulerStatus.ts @@ -46,6 +46,8 @@ export type SchedulerStatusInputs = { // Why no Instagram job starts now, when none does (the shell asks the // guard: jobs/instagramGuard.ts). instagramHeld?: string | null; + // Why no X job starts now, when X's job cap is reached (jobs/networkGuard.ts xCapHeldReason). + xCapHeld?: string | null; }; export function buildSchedulerStatusPayload( @@ -60,6 +62,7 @@ export function buildSchedulerStatusPayload( priority: settings.channelPriority, jitter: settings.pacing?.jitter ?? 0, ...(inputs.instagramHeld ? { instagramHeld: inputs.instagramHeld } : {}), + ...(inputs.xCapHeld ? { xCapHeld: inputs.xCapHeld } : {}), }); return { now, diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,25 @@ # Changelog ## [Unreleased] +- **X jobs run on X's queue only, under a cap no setting can raise.** + - A job that asks X is refused on any queue but `platform:twitter`, when it is queued and where it runs: a posts + fetch in any mode, a resumed backfill, a Sync, a capture, a trending read, an import of an X post, an + availability check, an X run. A job moved to another queue used to run beside the one on X's, with no gap. + - **At most 12 X jobs start in any 60 minutes and 150 in any 24 hours, per X login**, over every kind together. + A job past the cap is refused before it starts and says when the next may start. The scheduler skips X + channels meanwhile and a trending watch waits. `pnpm ops get x-session` shows the count. + - The numbers are constants of the code (`common/lib/xJobRule.ts`). No setting, option, environment variable, + flag or queue changes them. The count survives a restart, and an unreadable count stops every X job. + - The Add-channel form's Fetch details no longer starts gallery-dl against X for an X address: it reads the + handle off the URL. `pnpm archilyzer posts check` refuses an X channel as `posts fetch` does. +- **A trending read covers Top and Latest in one job, and can reach the page's end.** + - After Top is read, the read presses the page's Latest tab and reads it under the same caps. `"tabs"` on + `read-x-trending` and on a watch picks one tab; the channel page's form has the same choice. + - A Latest tab that cannot be opened ends the read `Top read; Latest not read: <why>`. It is still a read. + - "Gone" is said per tab: gone from Latest while Top still shows it, or gone from the page. + - The caps are higher so a read can reach the end, which is what lets it say a post is gone: 20 scrolls and + 200 posts per tab by default (were 8 and 60), at most 40 and 400. A read's deadline is 2 minutes plus 12 s per + scroll per tab: 10 minutes for both tabs at the defaults. - **A trending page's topic carries X's title and summary, and a read says which tab it saw.** The first real read of a trending page named its topic `Trending <number>`: the page's own answer was never parsed. - A topic you did not name is called by the page's title. One still called `Trending <number>` takes the title at diff --git a/editor/app/api/ops/_xTrendingWatch.ts b/editor/app/api/ops/_xTrendingWatch.ts @@ -22,7 +22,7 @@ export function xTrendingWatchDeps(): WatchScanDeps { busy: () => xTrendingJobWaiting(getRegistry().list(), (slug) => isXTrendingLibrarySync(paths.channelsDir, slug)), enqueue: async (tick) => { // Marked as the watch's: its job asks the watch's jar rule at its start. - const started = await readXTrendingAction({ slug: tick.slug, url: tick.url, topic: tick.topic, watch: true }); + const started = await readXTrendingAction({ slug: tick.slug, url: tick.url, topic: tick.topic, watch: true, ...(tick.tabs ? { tabs: tick.tabs } : {}) }); if (!started.ok) return { ok: false, error: started.error }; void started.stream.cancel(); return { ok: true, jobId: started.jobId }; diff --git a/editor/app/api/ops/read-x-trending/route.ts b/editor/app/api/ops/read-x-trending/route.ts @@ -3,7 +3,7 @@ import { jobResponse, ops, optBool, optPositiveInt, optString, reqSlug } from ". export const dynamic = "force-dynamic"; -// POST { slug, url, topic?, scrolls?, posts?, probe?, headed? } -> { ok: true, jobId } +// POST { slug, url, topic?, scrolls?, posts?, tabs?, probe?, headed? } -> { ok: true, jobId } // POST { slug, reparse: "<readId>", topic? } -> { ok: true, jobId } // // ONE X trending page (https://x.com/i/trending/<number>) read into `slug`, @@ -17,10 +17,15 @@ export const dynamic = "force-dynamic"; // // topic the 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 at most this many moves to the bottom of the page (1–20; the -// channel's cap, else 8). posts: stop once this many are seen -// (1–200; else 60). A read also stops after two scrolls that -// brought nothing new, and at once on a 429 or a login wall. +// scrolls at most this many moves to the bottom of a tab (1–40; the +// channel's cap, else 20). posts: stop once this many are seen on +// a tab (1–400; else 200). A tab's read also stops after two +// scrolls that brought nothing new, and the whole read at once on +// a 429 or a login wall. +// tabs the page's tabs to read: ["top"], ["latest"] or both (the +// default). Both are read in THIS one job: Top to its stop, then +// the page's Latest tab is pressed. A Latest that cannot be +// opened ends the read "Top read; Latest not read: <why>", ok. // probe save the capture and its summary; write no post. // headed open a window on the editor's desktop instead of a headless one. // reparse a saved read's id: its capture parsed again, OFFLINE (a @@ -39,7 +44,7 @@ export const dynamic = "force-dynamic"; export async function POST(request: Request) { return ops( request, - ["slug", "url", "reparse", "topic", "scrolls", "posts", "probe", "headed"], + ["slug", "url", "reparse", "topic", "scrolls", "posts", "tabs", "probe", "headed"], async (body) => { const url = optString(body, "url"); const reparse = optString(body, "reparse"); @@ -56,6 +61,7 @@ export async function POST(request: Request) { ...(topic !== undefined ? { topic } : {}), ...(scrolls !== undefined ? { scrolls } : {}), ...(posts !== undefined ? { posts } : {}), + ...(body.tabs !== undefined ? { tabs: body.tabs } : {}), ...(probe ? { probe: true } : {}), ...(headed ? { headed: true } : {}), }), diff --git a/editor/app/api/ops/watch-trending/route.ts b/editor/app/api/ops/watch-trending/route.ts @@ -4,7 +4,7 @@ import { ops, opsFail, optBool, optString, reqSlug } from "../_lib"; export const dynamic = "force-dynamic"; -// POST { slug, topic, on, intervalMinutes?, hours?, shots?, by? } +// POST { slug, topic, on, intervalMinutes?, hours?, shots?, tabs?, by? } // -> { ok: true, slug, topic, watch, sentence } // POST { slug, settings: {maxVideoMb?, intervalMinutes?, hours?, maxTopics?} } // -> { ok: true, slug, settings, sentence } @@ -23,6 +23,8 @@ export const dynamic = "force-dynamic"; // // on true watches the topic (again: its terms change, its history // stays); false stops (the watch ends "switched off") +// tabs the page's tabs each tick reads: ["top"], ["latest"] or both +// (the default; both are read in the one job). // 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" @@ -67,7 +69,7 @@ export const dynamic = "force-dynamic"; // 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) => { + return ops(request, ["slug", "topic", "on", "intervalMinutes", "hours", "shots", "tabs", "by", "settings", "tick"], async (body) => { const topic = optString(body, "topic"); const on = optBool(body, "on"); const shots = optBool(body, "shots"); @@ -81,6 +83,7 @@ export async function POST(request: Request) { ...(body.intervalMinutes !== undefined ? { intervalMinutes: body.intervalMinutes } : {}), ...(body.hours !== undefined ? { hours: body.hours } : {}), ...(shots !== undefined ? { shots } : {}), + ...(body.tabs !== undefined ? { tabs: body.tabs } : {}), ...(body.by !== undefined ? { by: body.by } : {}), }); if (!result.ok) return opsFail(result.error); diff --git a/editor/app/channels/[slug]/components/XTrendingPanel.tsx b/editor/app/channels/[slug]/components/XTrendingPanel.tsx @@ -187,6 +187,8 @@ export function XTrendingPanel({ const [posts, setPosts] = useState(""); const [probe, setProbe] = useState(false); const [headed, setHeaded] = useState(false); + // The page's tabs one read covers: both (Top, then Latest, in the one job), or one. + const [tabs, setTabs] = useState<"both" | "top" | "latest">("both"); const [reparse, setReparse] = useState(listing.reads[0] ?? ""); const input = "rounded border border-border bg-card px-2 py-1 text-sm"; const num = (v: string) => (v.trim() ? Number(v) : undefined); @@ -248,6 +250,14 @@ export function XTrendingPanel({ className={`${input} w-20`} /> </label> + <label className="flex flex-col gap-1"> + <span className="font-medium">Tabs</span> + <select value={tabs} onChange={(e) => setTabs(e.target.value as "both" | "top" | "latest")} aria-label="tabs" className={`${input} w-40`}> + <option value="both">Top, then Latest</option> + <option value="top">Top only</option> + <option value="latest">Latest only</option> + </select> + </label> <label className="flex items-center gap-2" title="Save the page's answers and a summary; write no post"> <input type="checkbox" checked={probe} onChange={(e) => setProbe(e.target.checked)} /> Probe (save only) @@ -265,6 +275,7 @@ export function XTrendingPanel({ ...(topic.trim() ? { topic: topic.trim() } : {}), ...(num(scrolls) !== undefined ? { scrolls: num(scrolls) } : {}), ...(num(posts) !== undefined ? { posts: num(posts) } : {}), + ...(tabs === "both" ? {} : { tabs: [tabs] }), ...(probe ? { probe: true } : {}), ...(headed ? { headed: true } : {}), }) @@ -323,7 +334,9 @@ export function XTrendingPanel({ {s.url} </a>{" "} · read {s.reads}×{s.lastReadAt ? `, last ${s.lastReadAt.slice(0, 16).replace("T", " ")} UTC` : ""} - {s.lastReadTab ? ( + {s.lastReadTabs ? ( + <span data-x-trending-tab=""> · the last read saw the {s.lastReadTabs.map((tab) => `“${tab}”`).join(" and ")} tabs</span> + ) : s.lastReadTab ? ( <span data-x-trending-tab=""> {" "} · the last read saw the “{s.lastReadTab}” tab @@ -366,6 +379,11 @@ export function XTrendingPanel({ Gone from the page at {when(p.gone.at)} UTC. </span> )} + {p.goneTabs?.map((g) => ( + <span key={g.tab} data-x-trending-gone-tab={g.tab} className="text-xs text-amber-700 dark:text-amber-400"> + Gone from the “{g.tab}” tab at {when(g.at)} UTC; another tab still shows it. + </span> + ))} <span className="whitespace-pre-wrap">{p.text}</span> <PostJudge slug={slug} post={p} /> </li> diff --git a/editor/app/channels/[slug]/xTrendingActions.ts b/editor/app/channels/[slug]/xTrendingActions.ts @@ -28,6 +28,7 @@ import { reparseXTrendingRead, runXTrendingRead, X_TRENDING_QUEUE, + xTrendingTabsAsked, type ReadXTrendingAsk, type ReadXTrendingResult, } from "yt-dlp-transcript-common/controller/readXTrending"; @@ -267,6 +268,7 @@ export type WatchXTrendingAsk = { intervalMinutes?: unknown; hours?: unknown; shots?: boolean; + tabs?: unknown; by?: unknown; }; @@ -346,6 +348,9 @@ export async function watchXTrendingAction(ask: WatchXTrendingAsk): Promise<Watc 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; + // The tabs each tick reads: as a read's ("top", "latest" or both). + const tabs = ask.tabs === undefined ? undefined : xTrendingTabsAsked(ask.tabs); + if (tabs && !tabs.ok) return { ok: false, error: tabs.error }; const now = Date.now(); const set = await setXTrendingWatch(lib.channelRoot, { topics: await readXTrendingTopics(lib.channelRoot), @@ -354,6 +359,7 @@ export async function watchXTrendingAction(ask: WatchXTrendingAsk): Promise<Watc intervalMinutes: terms.terms.intervalMinutes, hours: terms.terms.hours, ...(ask.shots !== undefined ? { shots: ask.shots } : {}), + ...(tabs?.ok ? { tabs: tabs.tabs } : {}), by: ask.by === "operator" ? "operator" : "agent", maxTopics: xTrendingWatchMaxTopics(config), now, diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts @@ -457,9 +457,9 @@ test("a library refuses a URL and a cap out of range, in sentences", () => { parseChannelForm(form({ handling: "transcribe", platform: "x-trending", ...fields })); assert.throws(refused({ url: "https://x.com/i/trending/1900000000000000001" }), /An X trending library has no URL/); assert.throws(refused({ url: "https://x.com/example_user" }), /An X trending library has no URL/); - assert.throws(refused({ xTrendingMaxScrolls: "21" }), /scroll cap is a whole number, 1–20/); - assert.throws(refused({ xTrendingMaxPosts: "0" }), /post cap is a whole number, 1–200/); - assert.throws(refused({ xTrendingMaxPosts: "many" }), /post cap is a whole number, 1–200/); + assert.throws(refused({ xTrendingMaxScrolls: "41" }), /scroll cap is a whole number, 1–40/); + assert.throws(refused({ xTrendingMaxPosts: "0" }), /post cap is a whole number, 1–400/); + assert.throws(refused({ xTrendingMaxPosts: "many" }), /post cap is a whole number, 1–400/); // An ordinary X account is not a library. assert.equal(parseChannelForm(form({ handling: "transcribe", url: "https://x.com/example_user" })).config.xTrending, undefined); }); diff --git a/editor/app/scheduler/runTick.ts b/editor/app/scheduler/runTick.ts @@ -5,6 +5,7 @@ // row and two forms import from it. import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { instagramHeldReason } from "yt-dlp-transcript-common/jobs/instagramGuard"; +import { xCapHeldReason } from "yt-dlp-transcript-common/jobs/networkGuard"; import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; @@ -15,6 +16,7 @@ import { nextEligibleAfterFailure, selectDueChannels, isInstagramPostsConfig, + xSyncHold, type ChannelEntry, } from "yt-dlp-transcript-common/jobs/syncScheduler"; import { @@ -141,6 +143,8 @@ export async function runSchedulerTick(): Promise<SchedulerTickResult> { jitter: pacingJitter(), // Instagram's alert or cooldown: its channels take no slot while it is up. instagramHeld: channels.some((c) => isInstagramPostsConfig(c.config)) ? await instagramHeldReason(paths) : null, + // X's job cap (common/lib/xJobRule.ts): its channels take no slot while it is reached. + xCapHeld: channels.some((c) => xSyncHold(c.config, "x") !== null) ? await xCapHeldReason(paths) : null, focusSlugs: resolveFocusSlugs( priority, siteChannels, diff --git a/editor/app/scheduler/status.ts b/editor/app/scheduler/status.ts @@ -7,7 +7,8 @@ import { } from "yt-dlp-transcript-common/views/schedulerStatus"; import { readSchedulerState } from "yt-dlp-transcript-common/jobs/syncSchedulerState"; import { instagramHeldReason } from "yt-dlp-transcript-common/jobs/instagramGuard"; -import { isInstagramPostsConfig } from "yt-dlp-transcript-common/jobs/syncScheduler"; +import { isInstagramPostsConfig, xSyncHold } from "yt-dlp-transcript-common/jobs/syncScheduler"; +import { xCapHeldReason } from "yt-dlp-transcript-common/jobs/networkGuard"; import { resolveHeartbeatSeconds } from "./heartbeat"; // THE SHELL. The payload is `common/views/schedulerStatus.ts`; this reads the @@ -30,5 +31,6 @@ export async function buildSchedulerStatusPayload(): Promise<SchedulerStatusPayl heartbeatSeconds: resolveHeartbeatSeconds(), // Asked only when there is an Instagram channel to say it about. instagramHeld: channels.some((c) => isInstagramPostsConfig(c.config)) ? await instagramHeldReason(paths) : null, + xCapHeld: channels.some((c) => xSyncHold(c.config, "x") !== null) ? await xCapHeldReason(paths) : null, }); } diff --git a/editor/e2e/x-trending.spec.ts b/editor/e2e/x-trending.spec.ts @@ -28,6 +28,8 @@ import { fixtureTimelineBody, fixtureTimelineUrl, fixtureTrendingResponses, + fixtureTwoTabResponses, + FIXTURE_LATEST_PAGE, } from "../../common/social/__fixtures__/xTrendingCapture"; const TOKEN = "test-worker-token"; @@ -99,6 +101,8 @@ test("an X trending library: the form, one read, the library by topic, the listi // One read, into a named topic. await page.getByLabel("trending page URL").fill(`${FIXTURE_TREND_URL}?src=trend_click`); await page.getByLabel("topic", { exact: true }).fill("Kettle Festival"); + // One tab here: the page's other tab is the two-tab test's (the last one in this file). + await page.getByLabel("tabs", { exact: true }).selectOption("top"); await page.getByRole("button", { name: "Read trending page" }).click(); // Four posts: the promoted entry, the quoted post and another surface's post are not the page's. await expect.poll(archiveLines, { timeout: 60_000 }).toBe(4); @@ -117,7 +121,7 @@ test("an X trending library: the form, one read, the library by topic, the listi // read.json is written TWICE: when the read starts (stop "started", outcome "error": what a read that // died is left as) and when it ends. The posts are on disk before the second write, so the record is // read until it is the final one — never once, and never after a wait. - type ReadRecord = { outcome: string; stop: string; scrolls: number; posts: { onPage: number; added: number }; operations: { op: string }[]; tabs?: { tab?: string; posts: number }[]; sentence: string }; + type ReadRecord = { outcome: string; stop: string; scrolls: number; posts: { onPage: number; added: number }; operations: { op: string }[]; tabs?: Record<string, unknown>[]; sentence: string }; const recordFile = rel(`channels/${SLUG}/trending/reads/${readId}/read.json`); // A read between the two halves of the atomic write finds no file, or half of one: asked again. const readRecord = () => readJson<ReadRecord>(recordFile).catch(() => null); @@ -129,7 +133,7 @@ test("an X trending library: the form, one read, the library by topic, the listi expect(record.posts).toEqual({ onPage: 4, added: 4 }); expect(record.operations.map((o) => o.op)).toEqual(["ExampleTrendPage", "ExampleTrendTimeline", "HomeTimeline"]); // Which of the page's tabs the read saw: the label and a count. - expect(record.tabs).toEqual([{ tab: "Top", posts: 4 }]); + expect(record.tabs).toEqual([{ tab: "Top", asked: "top", posts: 4, scrolls: 3, stop: "idle", pageEnd: false }]); expect(record.sentence).toBe(`Read ${FIXTURE_TREND_URL}: 4 posts on the page, 4 new, in topic "Kettle Festival" (kettle-festival), shown by the page's "Top" tab.`); const recordText = await readFile(t(`channels/${SLUG}/trending/reads/${readId}/read.json`), "utf8"); expect(recordText).not.toContain("teapot_news"); @@ -560,3 +564,90 @@ test("an X trending library: rename, move, merge; a topic published into an ordi const twice = await post("x-search-lead", { slug: SLUG, handle: "saucer_fan", action: "archive" }); expect(String(twice.json.error)).toContain("@saucer_fan is already archived: saucer_fan-x."); }); + +// ADDED SCOPE R3 (lane x-followups): one job reads the page's "Top" tab and +// then presses its "Latest" tab. The fake page has both (invented data); no +// browser, no request. +test("an X trending library: one read covers Top and Latest; a Latest that never loads is said and is no failure; a post that leaves Latest is gone from that tab only", async ({ page, request }) => { + test.setTimeout(240_000); + await seed(); + const post = async (action: string, data: Record<string, unknown>) => { + const res = await request.post(`${baseUrl}/api/ops/${action}`, { headers: AUTH, data }); + return { status: res.status(), json: (await res.json()) as Record<string, unknown> }; + }; + type Tab = { tab?: string; asked?: string; posts: number; scrolls?: number; stop?: string; pageEnd?: boolean; why?: string }; + type Record_ = { stop: string; outcome: string; sentence: string; tabs?: Tab[] }; + const fake = (trending: unknown) => + writeFile(t(".fake-x-profile-cookies.json"), JSON.stringify({ cookies: [{ name: "auth_token", value: "fixture-not-a-real-token", domain: ".x.com" }], trending })); + const readsDir = t(`channels/${SLUG}/trending/reads`); + const readIds = async () => (await readdir(readsDir).catch(() => [] as string[])).filter((n) => n.startsWith("tr-")).sort(); + // The n-th read's final record (read.json is written when a read starts and again when it ends). + const finished = async (n: number): Promise<Record_> => { + await expect.poll(async () => (await readIds()).length, { timeout: 60_000 }).toBe(n); + const file = rel(`channels/${SLUG}/trending/reads/${(await readIds())[n - 1]}/read.json`); + const read = () => readJson<Record_>(file).catch(() => null); + await expect.poll(async () => (await read())?.stop ?? "started", { timeout: 90_000 }).not.toBe("started"); + return (await read())!; + }; + const idle = () => + expect.poll(async () => ((await (await request.get(`${baseUrl}/api/ops/jobs?active=1&slug=${SLUG}`, { headers: AUTH })).json()) as { jobs?: unknown[] }).jobs?.length ?? 0, { timeout: 60_000 }).toBe(0); + const listing = async () => + (await (await request.get(`${baseUrl}/api/ops/trending?slug=${SLUG}`, { headers: AUTH })).json()) as { + topics: { sources: { lastReadTab?: string; lastReadTabs?: string[] }[] }[]; + posts: { id: string; reads: { tab?: string }[]; gone?: { at: string }; goneTabs?: { tab: string }[] }[]; + }; + expect((await post("create-channel", { slug: SLUG, fields: { name: "Trending", handling: "transcribe", platform: "x-trending" } })).status).toBe(200); + + // 1. BOTH TABS, ONE JOB (the default): Top's four posts, and the one only Latest shows. + await fake(fixtureTwoTabResponses()); + expect((await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL, topic: "Kettle Festival" })).status).toBe(200); + const first = await finished(1); + expect(first.outcome).toBe("read"); + expect(first.tabs).toEqual([ + { tab: "Top", asked: "top", posts: 4, scrolls: 3, stop: "idle", pageEnd: true }, + { tab: "Latest", asked: "latest", posts: 3, scrolls: 2, stop: "idle", pageEnd: true }, + ]); + expect(first.sentence).toBe(`Read ${FIXTURE_TREND_URL}: 5 posts on the page, 5 new, in topic "Kettle Festival" (kettle-festival), shown by the page's "Top" and "Latest" tabs.`); + expect((await readdir(`${readsDir}/${(await readIds())[0]}`)).sort()).toEqual(["page-latest.png", "page.png", "read.json", "responses.jsonl"]); + await idle(); + const one = await listing(); + expect(one.topics[0].sources[0].lastReadTabs).toEqual(["Top", "Latest"]); + expect(one.posts.find((p) => p.id === "1900000000000001001")?.reads.map((r) => r.tab)).toEqual(["Top", "Latest"]); + expect(one.posts.find((p) => p.id === "1900000000000001009")?.reads.map((r) => r.tab)).toEqual(["Latest"]); + await page.goto(`${baseUrl}/channels/${SLUG}`); + await expect(page.locator("[data-x-trending-source] [data-x-trending-tab]")).toContainText("the last read saw the “Top” and “Latest” tabs"); + // "tabs" is top, latest or both: anything else is refused with a sentence, before any job. + const bad = await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL, tabs: ["media"] }); + expect(bad.status).toBe(400); + expect(String(bad.json.error)).toBe('"tabs" is ["top"], ["latest"] or ["top", "latest"] (the default: both, read in one job)'); + + // 2. A POST LEAVES LATEST between two reads: Latest now lists one post; 1001 is still on Top, 1009 was only ever on Latest. + await fake(fixtureTwoTabResponses([FIXTURE_LATEST_PAGE[2]])); + expect((await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL })).status).toBe(200); + const second = await finished(2); + expect(second.sentence).toContain('1 post this page showed before is gone from the page at'); + expect(second.sentence).toContain('1 post is gone from the "Latest" tab and still shown by another.'); + await idle(); + const two = await listing(); + expect(two.posts.find((p) => p.id === "1900000000000001001")?.goneTabs?.map((g) => g.tab)).toEqual(["Latest"]); + expect(two.posts.find((p) => p.id === "1900000000000001001")?.gone).toBeUndefined(); + expect(two.posts.find((p) => p.id === "1900000000000001009")?.gone).toBeTruthy(); + await page.reload(); + await expect(page.locator('[data-x-trending-post="1900000000000001001"] [data-x-trending-gone-tab="Latest"]')).toContainText("Gone from the “Latest” tab at"); + await expect(page.locator('[data-x-trending-post="1900000000000001001"] [data-x-trending-gone]')).toHaveCount(0); + await expect(page.locator('[data-x-trending-post="1900000000000001009"] [data-x-trending-gone]')).toContainText("Gone from the page at"); + + // 3. A LATEST TAB THAT NEVER LOADS: pressed, and the page asks nothing for it. The read waits its 20 s, says so, and is a read. + const never = fixtureTwoTabResponses(); + never.tabs.Latest = {}; + await fake(never); + expect((await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL })).status).toBe(200); + const third = await finished(3); + expect(third.outcome).toBe("read"); + expect(third.tabs?.[1]).toEqual({ tab: "Latest", asked: "latest", posts: 0, scrolls: 0, stop: "not-read", pageEnd: false, why: 'pressing "Latest" brought no answer for its timeline within 20 s' }); + expect(third.sentence).toContain('Top read; Latest not read: pressing "Latest" brought no answer for its timeline within 20 s.'); + await idle(); + // Nothing is retried: three reads were asked for, and three there are; nothing new is said of Latest's posts. + expect(await readIds()).toHaveLength(3); + expect((await listing()).posts.find((p) => p.id === "1900000000000001005")?.gone).toBeUndefined(); +}); diff --git a/mcp/src/xTrending.test.ts b/mcp/src/xTrending.test.ts @@ -229,3 +229,20 @@ test("x_trending_topics cuts a long summary of X's at 600 characters, at a word" assert.ok(said.length <= 600 && said.endsWith("…"), String(said.length)); assert.ok(summary.startsWith(said.slice(0, -1))); }); + +// Added scope R3: a read covers both tabs; a post may be gone from one tab only. +test("the tools say both tabs of a two-tab read, and a post gone from one tab while another still shows it", async () => { + const listing = { + ...LISTING, + topics: [{ ...LISTING.topics[0], sources: [{ trendId: "1900000000000000001", url: TREND, tabs: ["Top", "Latest"], lastReadTabs: ["Top", "Latest"], reads: 1, lastReadAt: "2026-11-17T12:00:00.000Z" }] }], + posts: [{ ...LISTING.posts[0], goneTabs: [{ tab: "Latest", at: "2026-11-18T10:30:00.000Z", read: READ }] }], + total: 1, + }; + const { deps } = fakeEditor(() => ({ status: 200, body: listing }), env); + const client = await connectWith(deps); + const topics = body(await client.callTool({ name: "x_trending_topics", arguments: { channel: "trending" } })); + assert.match(topics, / · read 1×, last 2026-11-17 12:00 UTC · the last read saw the "Top" and "Latest" tabs$/m); + const posts = body(await client.callTool({ name: "x_trending_posts", arguments: { channel: "trending" } })); + assert.match(posts, new RegExp(`^ gone from the "Latest" tab at 2026-11-18 10:30 UTC \\(read ${READ}\\); another tab still shows it$`, "m")); + assert.doesNotMatch(posts, /gone from the page/); +}); diff --git a/mcp/src/xTrending.ts b/mcp/src/xTrending.ts @@ -34,6 +34,7 @@ type Topic = { lastUpdatedAt?: string; tabs?: string[]; lastReadTab?: string; + lastReadTabs?: string[]; reads: number; lastReadAt: string | null; }>; @@ -55,6 +56,8 @@ type PostRow = { thread?: string; // A page that showed it before did not show it at `at` (never "deleted"). gone?: { at: string; read: string; trendId: string }; + // A tab's read reached its end without it while another tab still shows it. + goneTabs?: Array<{ tab: string; at: string; read: string }>; capture?: { at: string; state: string; shot: boolean; files: number; mediaState: string; mediaOwed?: string }; }; @@ -79,7 +82,9 @@ export function renderXTrendingTopics(slug: string, body: ListingBody): string { for (const t of topics) { lines.push(`- ${t.id} — "${t.title}": ${t.posts} post${t.posts === 1 ? "" : "s"}`); for (const s of t.sources ?? []) { - const tab = s.lastReadTab + const tab = s.lastReadTabs?.length + ? ` · the last read saw the ${s.lastReadTabs.map((t) => `"${t}"`).join(" and ")} tabs` + : s.lastReadTab ? ` · the last read saw the "${s.lastReadTab}" tab${s.tabs && s.tabs.length > 1 ? ` of ${s.tabs.map((t) => `"${t}"`).join(", ")}` : ""}` : ""; lines.push(` ${s.url} · read ${s.reads}×, last ${day(s.lastReadAt)} UTC${tab}`); @@ -111,6 +116,7 @@ export function renderXTrendingPosts(slug: string, body: ListingBody, topic?: st lines.push(` ${p.text.replace(/\s*\n\s*/g, " / ")}`); if (reads) lines.push(` shown by: ${reads}`); if (p.thread && p.thread !== p.id) lines.push(` in thread ${p.thread}`); + for (const g of p.goneTabs ?? []) lines.push(` gone from the "${g.tab}" tab at ${day(g.at)} UTC (read ${g.read}); another tab still shows it`); if (p.gone) lines.push(` gone from the page at ${day(p.gone.at)} UTC (read ${p.gone.read}; the page stopped showing it, which is not "deleted")`); if (p.capture) { const owed = p.capture.mediaOwed === "kept" ? "; more media owed once it is kept" : p.capture.mediaOwed === "next" ? "; more media owed to the next capture" : ""; @@ -237,7 +243,7 @@ export const X_TRENDING_TOOLS = [ "An X TRENDING LIBRARY's topics: the operator's topics, each with the X trending pages " + "(x.com/i/trending/<id>) read into it, how often and when, X's own title and summary of " + "the page (X's words, not the operator's), which of the page's tabs the last read saw (a " + - "read sees ONE tab, the one the page opens on), and its post count; and the " + + "read covers Top and Latest in one job unless asked for one), and its post count; and the " + "ids of the saved reads; and each topic's WATCH, when it has one — whether it is being " + "read again on an interval, until when, and why it is paused (a watch runs only while " + "X's cookie jar is fresh, so a stale jar pauses it until the operator refreshes). A library is PRIVATE — on no site, in no index, so no other " + @@ -260,7 +266,7 @@ export const X_TRENDING_TOOLS = [ "date, words, media by kind and count, the reads that showed it (and the page's tab), its topic, and — once " + "it has them — the thread it belongs to, what its capture holds (and what media it is " + "still owed), its judgement (keep / drop / later; none is undecided; its own, or its " + - "thread's), and whether a page stopped showing it (\"gone from the page at <time>\": a " + + "thread's), whether ONE TAB of the page stopped showing it while another still does, and whether a page stopped showing it (\"gone from the page at <time>\": a " + "trending page is a ranked list, so this is NOT a claim the post was deleted) — the " + "newest read's first, in the order the page showed them. For looking through what a " + "trending page held before anything is archived or published. PRIVATE material: never " + diff --git a/plans/x-trending.md b/plans/x-trending.md @@ -356,7 +356,7 @@ scrolls. What it showed, and what changed (shapes with invented data: `common/so not taken. One function decides, inside the topics file's lock (`recordXTrendingRead`). - **Tabs.** A timeline request names its timeline (`variables.timelineId`) and, after the first, its cursor. The read's tab is the page's tab with that timeline id: kept in `read.json` (`tabs`: label and count), on the - source's read and on each sighting (`seen[].tab`); a reparse fills it in. A read sees the tab the page opens on. + source's read and on each sighting (`seen[].tab`); a reparse fills it in. (R3 below: a read now covers both tabs.) - **The page's end.** The first answer of a timeline ends with cursor entries; every later one carries its cursors in `TimelineReplaceEntry` instructions. `timelineShapeOf` reads both. The continuation that shows the end is the last answer's own timeline's; a capture listing two timelines shows no end; and "gone" does not count a sighting @@ -365,13 +365,56 @@ scrolls. What it showed, and what changed (shapes with invented data: `common/so (the continuation from the previous bottom cursor brought nothing new, and nothing failed), which needs no knowledge of the end's shape; whether the real page ever sends such an answer is still unseen. -**What reading "Latest" would need** (not built). It is where a post that is deleted quickly would first show. -(1) A second read of the same page with the tab pressed: the reader clicks the tab named "Latest" in the page (it -never builds a request), waits for the timeline request whose `timelineId` is that tab's, then scrolls as now. (2) -One job per tab, or one job for both under the same caps: a ruling, since each tab costs its own page of requests -per scroll. (3) `read-x-trending {"tab": "Latest"}` and the watch's choice of tab per topic. (4) The store is -ready: sightings, reads and the gone rule are per tab, and the parser refuses an end for a capture that lists two -timelines, so a two-tab read must be parsed per timeline (the answers are already keyed by it). +**Review 1, as fixed.** M1: the Add-channel form's Fetch details started gallery-dl against X outside any job; +the gallery-dl fetcher's probe now reads the handle off the URL (Nitter's, the Playwright fallback's and +Instagram's already made no request; the gallery-dl fetcher claims every x.com URL, so the form's yt-dlp probe is +never reached for one). S1: a search-phase place `3_<N>/` is checked exactly (a first-page post above N). S2: a +timeline-phase place says it may pass through archived posts first; it is not rewritten (nothing in gallery-dl's +source proves the archive unbroken down to its oldest post). S3: the read's tab is the one named timeline's. S4: +a topic is named from what its source holds, under the source's age guard. S5: a publish dry run says when the +topic is named by X's page (`titleFrom`). A topic's `titleFrom` is its own field; a listing gives 600 characters +of X's summary; no shipped module imports `common/testing` (`common/architecture.test.ts`). + +## Rulings of 18 Nov (the operator), as built in `lane/x-followups` + +**R1. The caps are raised so a read can reach a page's end.** Defaults 20 scrolls and 200 posts PER TAB (were 8 +and 60); maxima 40 and 400. A read's deadline is `120 s + tabs × scrolls × 12 s` (`readDeadlineMs`): 6 minutes for +one tab at 20 scrolls (what a read always had), 10 for both tabs at the defaults, 18 for both at the maximum. + +**R2. X jobs run on X's queue only, under an immutable cap per login.** `common/lib/xJobRule.ts` holds the rule +and its numbers: 12 X jobs started in any rolling 60 minutes, 150 in any rolling 24 hours, per X login, over +every kind of X job. No setting, config key, environment variable, option, flag or queue changes them. +- The network guard treats a job as X's when its queue is X's OR its channel is on X (a job on another + platform's queue used to be taken for that platform's and met none of X's rules); refuses any queue but + `platform:twitter` at enqueue and at the start; refuses at enqueue when the cap is reached; and checks and + records one start in one step at the LAST guard before the job's work. An X run's own start asks X nothing: + each of its channels is one start. +- Where X is about to be asked the code asks again (`xJobContextRefusal`: a job of the editor's, on X's queue): + `fetchPosts`, `capturePosts`, `importPost`, `checkPostAvailability`, `runXTrendingRead`. +- The count is `transcripts/.x-session/job-starts.json`, per login, written under its lock, kept across a + restart; a file that cannot be read refuses every X job; a clock set back never frees a start early. Its clock + is the queue gap's. +- The scheduler skips X posts channels while the cap is reached; a watch's tick is skipped as for a cooldown. +- A job replayed at boot re-enters through its action and the same funnel, so both rules hold for it. + +**R3. A read covers "Latest" as well as "Top", in one job.** The reader scrolls the tab the page opens on to its +stop, then presses the page's own tab (by role `tab`, else `link`, else `button`, with the label the page's +answer gave), waits up to 20 s for the page's request for that tab's timeline, and scrolls it under the same +caps. It builds no request. +- One `responses.jsonl`; `page-latest.png` beside `page.png` (the page after the press, or after the try). +- The parser's end rule and post lists are per timeline. `read.json` `tabs`: per tab its label, what was asked, + posts, scrolls, stop, `pageEnd`, and `why` for a tab not read. +- Sightings are per read and tab; `goneTabs[<tab>]` marks a post a tab's complete read no longer shows; `gone` + (the page) is set once every tab that showed the post has such a mark. A read that cannot name its tab judges + only sightings that name none; a capture with no page answer is named through the tabs the source already knows + for its timeline ids. +- "Top read; Latest not read: <why>" is a read: no error, no strike, no retry. A 429, a 403 or a login wall on + either tab stops the whole read. +- `"tabs"` on `read-x-trending` and per watch; the default is both. +- NOT YET SEEN: the real Latest tab. Whether its control has the role and name assumed, and whether its timeline + answers have the shape of Top's, is confirmed by the first real two-tab read. The capture alone is enough to + put a wrong guess right: every answer the page fetched is in it, each with the timeline its request named, and + `read.json` says what the press did. **Ignored in the capture, listed.** `TrendRelevantUsers` and the first timeline answer's accounts module: the accounts X names for the trend (the library's accounts listing counts authors of posts instead). `useStoryTopicQuery`: @@ -383,8 +426,10 @@ read assert nothing about the page's end: conservative, left so. - The END of a timeline is confirmed by no capture yet (above). The parser is built so that a change is local to `common/social/xTrendingParse.ts`. -- With the default post cap (60) the first real read stopped at the cap after three scrolls: a read of a busy page - never reaches its end, so "gone from the page" is never said of it. Raising `xTrendingMaxPosts` is the - operator's choice (each scroll is one more request). +- The first real read stopped at the old post cap (60) after three scrolls. With 200 posts and 20 scrolls per + tab a read can reach a page's end; whether a busy page has one within the caps is still to be seen. +- X's daily job cap (150) is below what the app can ask for at its own defaults: two topics watched at 30 + minutes, an X run over more than 150 channels, or more than 150 X channels on a daily sync. The cap refuses the + excess; raising it is the operator's code change. - Whether a watch may keep the jar fresh by itself is the operator's to rule; until then the jar rule above stands. diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1316,7 +1316,13 @@ export function usage() { " \"browser\": cookiesFromBrowser, whose age cannot be read), hasCookies,", " looksAuthenticated, cookiesUpdatedAt, ageMinutes, maxAgeMinutes", " (social.x.maxCookieAgeMinutes; 0 = off), the X cookie alert if it is up,", - " allowed, and reason (the refusal an X job would get). <slug> names a", + " allowed, and reason (the refusal an X job would get); and X's JOB CAP:", + " login (whose count it is), cap {lastHour, perHour: 12, lastDay, perDay:", + " 150, reached, nextAt?} - at most 12 X jobs start in any 60 minutes and", + " 150 in any 24 hours, per X login, over every kind of X job; a job past", + " it is refused before it starts with the time the next may start. The", + " numbers are constants of the code (common/lib/xJobRule.ts): no setting,", + " option or queue raises them. <slug> names a", " channel whose own cookiesFromBrowser may decide the source. Nothing is", " asked of X: a refresh is Refresh cookies / Connect X account on", " /settings. Ask it before queueing fetch-posts or capture-posts on X.", @@ -1972,13 +1978,20 @@ export function usage() { " 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.", + " read into before, else a new one named for the page's own title).", + " \"tabs\": [\"top\"], [\"latest\"] or both (the default): BOTH ARE READ IN", + " THIS ONE JOB - Top to its stop, then the page's own Latest tab is", + " pressed and read under the same caps. A Latest that cannot be opened", + " ends the read \"Top read; Latest not read: <why>\", ok, nothing retried.", + " \"scrolls\": 1-40 moves to the bottom of a tab (default: the channel's", + " cap, else 20); \"posts\": stop a tab once 1-400 are seen on it (else", + " 200); a tab also stops after two scrolls with nothing new, and the whole", + " read 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.", + " the read within its deadline: 2 minutes plus 12 s for every scroll each", + " tab may make (both tabs at 20 scrolls: 10 minutes; one tab: 6; both at", + " 40: 18). 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", @@ -2104,6 +2117,8 @@ export function usage() { " 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.", + " \"tabs\": the page's tabs each tick reads, as read-x-trending's (the", + " default: both, in the one job).", ' "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,", diff --git a/umtool/components/tools/library/LibraryView.tsx b/umtool/components/tools/library/LibraryView.tsx @@ -8,7 +8,7 @@ import type { Post } from "yt-dlp-transcript-common/lib/posts"; import { Badge } from "@/components/ui/badge"; import { Button, buttonVariants } from "@/components/ui/button"; import { useHydrated } from "@/components/ui/use-hydrated"; -import { captureSentence, filterWords, goneSentence, libraryHref } from "@/lib/library/filters.mjs"; +import { captureSentence, filterWords, goneSentence, goneTabSentence, libraryHref } from "@/lib/library/filters.mjs"; import { isTyping, LIBRARY_KEYS, libraryAction, stateOfAction } from "@/lib/library/keys.mjs"; import { libraryMediaSrc } from "@/lib/library/mediaSrc.mjs"; import { pressSetOf, UNDO_SAYS, undoSetOf } from "@/lib/library/undo.mjs"; @@ -521,6 +521,11 @@ export default function LibraryView({ data: opened }: { data: Ok }) { {goneSentence(row.gone, utc)} </span> )} + {row.goneTabs?.map((g) => ( + <span key={g.tab} data-library-gone-tab={g.tab} className="text-doubt-text"> + {goneTabSentence(g, utc)} + </span> + ))} {row.capture && <span data-library-capture={row.capture.state}>{captureSentence(row.capture, utc)}</span>} {row.capture?.mediaOwed && <span>media owed: {row.capture.mediaOwed === "kept" ? "fetched once the post is kept" : "asked for again by the next capture"}</span>} {!row.capture && row.media.count > 0 && <span>{row.media.count} media, not captured</span>} @@ -763,7 +768,7 @@ function TopicPanel({ lib, topic, topics, off, run, onPurged, go }: { lib: strin {topic && topic.sources - .filter((src) => src.title || src.summary || src.lastReadTab) + .filter((src) => src.title || src.summary || src.lastReadTab || src.lastReadTabs) .map((src) => ( <div key={src.trendId} data-library-source={src.trendId} className="mt-2 text-[12.5px] text-text-2"> {src.title && ( @@ -777,10 +782,15 @@ function TopicPanel({ lib, topic, topics, off, run, onPurged, go }: { lib: strin X’s summary: {src.summary} </p> )} + {src.lastReadTabs && ( + <p className="m-0 text-muted" data-library-tab=""> + The last read saw the page’s {src.lastReadTabs.map((tab) => `“${tab}”`).join(" and ")} tabs. + </p> + )} {src.lastReadTab && ( <p className="m-0 text-muted" data-library-tab=""> The last read saw the page’s “{src.lastReadTab}” tab - {src.tabs && src.tabs.length > 1 ? ` (the page has ${src.tabs.map((tab) => `“${tab}”`).join(", ")}); a read sees one tab.` : "."} + {src.tabs && src.tabs.length > 1 ? ` (the page has ${src.tabs.map((tab) => `“${tab}”`).join(", ")}).` : "."} </p> )} </div> diff --git a/umtool/e2e/fixtures/editor-stub-trending.mjs b/umtool/e2e/fixtures/editor-stub-trending.mjs @@ -66,6 +66,7 @@ function row(p, detail) { topic: p.topic, reads: [{ read: "tr-01JA0000000000000000000000", trendId: "1900000000000000001", at: p.firstSeenAt }], ...(p.gone ? { gone: p.gone } : {}), + ...(p.goneTabs ? { goneTabs: p.goneTabs } : {}), ...(p.capture && (captured || p.capture.state !== "captured") ? { capture: { ...p.capture, shot: captured, files: captureFiles(p)?.media.length ?? 0 } } : {}), thread: p.thread, ...(judgement ? { judgement } : {}), diff --git a/umtool/e2e/fixtures/library-fixture.mjs b/umtool/e2e/fixtures/library-fixture.mjs @@ -72,6 +72,8 @@ export function libraryState() { posts: [ post(P.opening, "teapot_news", "Teapot News", "The kettle festival opens today.", "kettle-festival", READ_1, { mediaCount: 2, kinds: ["image", "video"], capture: { at: "2026-11-17T10:05:00.000Z", state: "captured", mediaState: "ok" } }), post(P.reply, "saucer_fan", "Saucer Fan", "A reply about spouts.", "kettle-festival", READ_1, { + // Gone from one tab of the page while the other still shows it (a two-tab read). + goneTabs: [{ tab: "Latest", at: READ_2, read: "tr-01JB0000000000000000000000" }], thread: P.opening, isReply: true, replyTo: { platform: "twitter", id: P.opening, author: "teapot_news" }, diff --git a/umtool/e2e/library.spec.ts b/umtool/e2e/library.spec.ts @@ -137,6 +137,9 @@ test("a post is drawn with its captured media, its thread context, and the words // Gone from the page, in those words; a capture's own state verbatim. await expect(post(page, P.gone).locator("[data-library-gone]")).toHaveText("Gone from the page at 17 Nov 2026, 11:00 UTC"); + // PER TAB: a post one tab stopped showing while the other still shows it says which tab, and is not "gone from the page". + await expect(post(page, P.reply).locator('[data-library-gone-tab="Latest"]')).toHaveText("Gone from the “Latest” tab at 17 Nov 2026, 11:00 UTC; another tab still shows it."); + await expect(post(page, P.reply).locator("[data-library-gone]")).toHaveCount(0); await expect(post(page, P.fresh).locator("[data-library-capture]")).toHaveText("capture: deleted at 17 Nov 2026, 12:05 UTC"); // No post is called deleted: the only place the word may stand is a capture's recorded state. const text = await page.locator("[data-library-posts]").innerText(); @@ -387,7 +390,7 @@ test("the watch: why it is paused, that only the operator restarts a failing one const source = page.locator('[data-library-panel="lids"] [data-library-source]'); await expect(source.locator("[data-library-x-title]")).toContainText("X’s title: Lid makers meet"); await expect(source.locator("[data-library-x-summary]")).toHaveText("X’s summary: Lid makers met to agree on one thread size."); - await expect(source.locator("[data-library-tab]")).toHaveText("The last read saw the page’s “Top” tab (the page has “Top”, “Latest”); a read sees one tab."); + await expect(source.locator("[data-library-tab]")).toHaveText("The last read saw the page’s “Top” tab (the page has “Top”, “Latest”)."); // A topic with no words from X shows none. await expect(page.locator('[data-library-panel="lids"] [data-library-source]')).toHaveCount(1); await panel.locator("[data-library-watch-shots]").check(); diff --git a/umtool/lib/library/cli.mjs b/umtool/lib/library/cli.mjs @@ -95,7 +95,7 @@ async function filterOf(flags, lib, reportsRoot) { const line = (p) => { const j = p.judgement ? `${p.judgement.state}${p.judgement.from === "thread" ? " (thread)" : ""} by ${p.judgement.by}` : "unjudged"; - const gone = p.gone ? ` · gone from the page at ${p.gone.at}` : ""; + const gone = (p.gone ? ` · gone from the page at ${p.gone.at}` : "") + (p.goneTabs ?? []).map((g) => ` · gone from the "${g.tab}" tab at ${g.at}`).join(""); const capture = p.capture ? ` · capture: ${p.capture.state} at ${p.capture.at}` : ""; return `${p.id} @${p.author} ${j}${gone}${capture}\n ${String(p.text).replace(/\s+/g, " ").slice(0, 160)}`; }; @@ -138,7 +138,7 @@ export async function libraryCommand(args, deps = {}) { .flatMap((src) => [ src.title ? ` X's title: ${src.title}` : "", src.summary ? ` X's summary: ${src.summary.length > 600 ? `${src.summary.slice(0, 599).trimEnd()}…` : src.summary}` : "", - src.lastReadTab ? ` The last read saw the "${src.lastReadTab}" tab${src.tabs?.length > 1 ? ` of ${src.tabs.map((tab) => `"${tab}"`).join(", ")}` : ""}.` : "", + src.lastReadTabs?.length ? ` The last read saw the ${src.lastReadTabs.map((tab) => `"${tab}"`).join(" and ")} tabs.` : src.lastReadTab ? ` The last read saw the "${src.lastReadTab}" tab${src.tabs?.length > 1 ? ` of ${src.tabs.map((tab) => `"${tab}"`).join(", ")}` : ""}.` : "", ]) .filter(Boolean) .map((line) => `\n${line}`) diff --git a/umtool/lib/library/filters.mjs b/umtool/lib/library/filters.mjs @@ -83,6 +83,11 @@ export function filterWords(view) { } /** "gone from the page at <time>": the one sentence for a gone mark. Never "deleted". */ +/** "Gone from the “Latest” tab at <time>; another tab still shows it." — one tab's read reached its end without the post (never "deleted"). */ +export function goneTabSentence(g, fmt = (iso) => iso) { + return `Gone from the “${g.tab}” tab at ${fmt(g.at)}; another tab still shows it.`; +} + export function goneSentence(gone, fmt = (iso) => iso) { return gone && typeof gone.at === "string" ? `Gone from the page at ${fmt(gone.at)}` : ""; } diff --git a/umtool/lib/library/view.test.mjs b/umtool/lib/library/view.test.mjs @@ -68,3 +68,8 @@ test("undo puts back each id's OWN entry, or removes the judgement it had none o // S7: an undone entry becomes the operator's, and the bar says so. assert.match(UNDO_SAYS, /written as the operator's whoever wrote them before/); }); + +test("gone from one tab is its own sentence, never \"deleted\"", async () => { + const { goneTabSentence } = await import("./filters.mjs"); + assert.equal(goneTabSentence({ tab: "Latest", at: "2026-11-17T12:00:00.000Z" }, (iso) => iso.slice(11, 16)), "Gone from the “Latest” tab at 12:00; another tab still shows it."); +});