Archilyzer · Source

archilyzer

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

commit beb91321f334118c90f7397a499c1dba7be51466
parent 805d3c01770466a363532a5aaef69e873a323b05
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 17:33:39 -0500

Merge lane/x-sittings: X fetching in small, uneven sittings, with one stop for every reader

At most four X job starts per cookie refresh, a drawn 5-12 minute gap, one kind per sitting, six starts
an hour. Any rate limit or bot check from X, seen by any reader, records one 15-minute stop that every X
job kind honours; a job reads at most 300 posts and keeps its place. A hand-set suspended state stops
anything recording a post as gone from an X answer. The browser-driven fallback fetcher is refused.

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

Diffstat:
MCOMMANDS.md | 25+++++++++++++++++++------
MENVIRONMENT.md | 5+++--
MOPERATING.md | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
MSETTINGS.md | 6+++++-
Mcommon/controller/capturePosts.ts | 34++++++++++++++++++++++++++--------
Mcommon/controller/checkPostAvailability.ts | 3+++
Mcommon/controller/fetchOlderPosts.test.ts | 5++---
Mcommon/controller/fetchPosts.test.ts | 34+++++++++++++++++++++++++++++++---
Mcommon/controller/fetchPosts.ts | 12++++++++++++
Mcommon/controller/readXTrending.test.ts | 3++-
Mcommon/controller/readXTrending.ts | 31+++++++++++++++++++++++++++----
Mcommon/controller/xRun.test.ts | 5+++++
Mcommon/controller/xRun.ts | 15+++++++++------
Mcommon/controller/xTrendingWatch.ts | 16+++++++++++++++-
Mcommon/jobs/downloadBackoff.ts | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobMeta.ts | 15+++++++++++++++
Mcommon/jobs/networkGuard.ts | 272++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/jobs/pacingGuard.test.ts | 177++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------
Mcommon/jobs/platformBackoff.ts | 34++++++++++++++++++++++++++++++++--
Mcommon/jobs/queueGap.test.ts | 30+++++++++++++++++++++++-------
Mcommon/jobs/queueGap.ts | 151++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/registry.ts | 6++++++
Mcommon/jobs/streamCommand.ts | 30++++++++++++++++++++++++++++++
Mcommon/jobs/unitOutcome.ts | 12++++++++++++
Mcommon/jobs/xJobCap.test.ts | 34+++++++++++++++++-----------------
Mcommon/jobs/xJobCap.ts | 7+++++++
Acommon/jobs/xSitting.ts | 252+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/jobs/xSittings.test.ts | 681+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/availability-server.ts | 4++++
Mcommon/lib/cookieStatus.ts | 17++++++++++++++++-
Mcommon/lib/downloadOutcome-server.ts | 20+++++++++++++++++++-
Mcommon/lib/envVars.ts | 5+++--
Mcommon/lib/jobContext.ts | 23+++++++++++++++++++++++
Mcommon/lib/settingsSchema.ts | 24+++++++++++++++++++++++-
Mcommon/lib/xJobRule.test.ts | 79++++++++++++++++++++++++++++++-------------------------------------------------
Mcommon/lib/xJobRule.ts | 43++++++++++++++++++-------------------------
Acommon/lib/xSitting.ts | 255+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/fakeXProfileBrowser.test.ts | 4++--
Mcommon/social/fetchers.ts | 5+++++
Mcommon/social/headedDisplay.test.ts | 2+-
Mcommon/social/postCapture.ts | 12++++++++++++
Acommon/social/xAccountState.ts | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xArticleCapture.test.ts | 12++++++++++++
Mcommon/social/xArticleCapture.ts | 19+++++++++++++++++--
Mcommon/social/xAvatarCapture.ts | 10++++++++++
Mcommon/social/xCookieSource.ts | 17+++++++++++++++++
Mcommon/social/xGalleryDlFetcher.test.ts | 19+++++++++++++++----
Mcommon/social/xGalleryDlFetcher.ts | 96++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mcommon/social/xPlaywrightFetcher.ts | 21+++++++++++++++++++++
Mcommon/social/xPostCapture.test.ts | 43+++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xPostCapture.ts | 47+++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xSessionBroker.test.ts | 43+++++++++++++++++++++++++++++++++++++++++--
Mcommon/social/xSessionBroker.ts | 66+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Meditor/CHANGELOG.md | 44++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/x-session/route.test.ts | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/x-session/route.ts | 37+++++++++++++++++++++++++++++++++++--
Meditor/app/cookies/CookiesBoard.tsx | 119++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Meditor/app/cookies/actions.ts | 36++++++++++++++++++++++++++++++++++++
Meditor/app/lib/cookieControls.ts | 2++
Meditor/app/lib/cookieControlsTypes.ts | 2++
Meditor/app/lib/cookieStatus.ts | 15++++++++++++++-
Aeditor/app/lib/xPacing.ts | 18++++++++++++++++++
Meditor/app/review/components/XRunConsole.tsx | 12+++++++-----
Meditor/app/settings/components/SettingsForm.tsx | 6++++--
Meditor/app/settings/components/XSessionSection.tsx | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Meditor/app/settings/page.tsx | 2++
Meditor/app/settings/xSessionActions.ts | 47+++++++++++++++++++++++++++++++++++++++++++++++
Meditor/e2e/servers.ts | 5+++++
Meditor/playwright.config.ts | 5+++++
Mscripts/archilyzer-ops.mjs | 41++++++++++++++++++++++++++++++++++++-----
Mscripts/archilyzer-ops.test.mjs | 12++++++++++++
71 files changed, 3319 insertions(+), 292 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -198,8 +198,9 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `voice-convert` | voice-convert keeps a recording's performance (timing, pitch contour) and swaps its timbre for a STOCK synthetic voice, as voice-enhance's job: the same body plus "voice" — "&lt;tts engine&gt;:&lt;stock voice&gt;" (orpheus:zac, orpheus:leah, kokoro:am\_michael, ...; settings.voice.convert.target); a file, a path or a recording is REFUSED as a target (no real person's voice) — and "engine" (openvoice \| seed-vc, each installed by `archilyzer voice setup --engine <id>`). "pitch" is where the result's pitch comes from (settings.voice.convert.pitch): "target" — the stock voice's own, the read's intonation flattened to it; "source" — the pitch the take was read at (raise your voice and it rises); "contour" — the read's rises and falls, moved as a whole to the stock voice's register. "semitones" (-12 to 12) then moves a followed pitch; left out, a followed pitch takes settings.voice.convert.semitones (0 unless set). source and contour are seed-vc's, on its optional f0 model (`archilyzer voice setup --engine seed-vc --with f0`; slower, 44.1 kHz); openvoice refuses them. The target's reference is synthesized once through the tts op and kept. The result adds target, voice, pitch (semitones and f0 — the medians heard and the move applied — when followed), synthetic: true and the disclosure line. | | | `settings` | settings patches settings.json through the editor's one writer: {"patch": {"&lt;top-level key&gt;": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"diarization":{"cleanAfterCapture":true}}}'`<br>`pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` | | `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | | -| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x", "instagram" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /cookies) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The For "instagram" it sends Instagram NO request either and is the operator's word that its check is passed: it clears the alert, and the next Instagram job raises it again if it was not. The timer never asks Instagram. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). Asked while a recheck or another press for the service runs (a click, the dashboard's, the timer's): refused, 409 {busy: true}, never queued. dismiss-service clears a service's cookie alert by hand: {"service"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -&gt; {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` | +| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x", "instagram" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /cookies) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The For "instagram" it sends Instagram NO request either and is the operator's word that its check is passed: it clears the alert, and the next Instagram job raises it again if it was not. The timer never asks Instagram. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). Asked while a recheck or another press for the service runs (a click, the dashboard's, the timer's): refused, 409 {busy: true}, never queued. dismiss-service clears a service's cookie alert by hand: {"service"}. x-session marks the X account's state by hand: {"accountState": "suspended" \| "ok", "note"?}. While it is suspended, check-post- availability and capture-posts with screenshots on X (the jobs that record a post as deleted or unavailable) are refused, because a suspended account's answers are thinned; every other X job logs it. get x-session and /cookies show it as the account's alert. Nothing is asked of X. Answers {account: {state, note?, at, by}}. {"clearStop": true, "confirm": true, "note"?} is "Clear the X stop": the one way X's 15-minute stop after a rate limit or a bot check ends early (a clean answer or clear-platform-hold never ends it). Without "confirm" it clears nothing and answers 409 with what it risks; each clear is logged in .jobs/x-stop-cleared.jsonl. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -&gt; {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` | | `dismiss-service` | — | | +| `x-session` | — | `pnpm ops x-session --json '{"accountState":"suspended","note":"read-only since the 21st"}'`<br>`pnpm ops x-session --json '{"accountState":"ok"}'`<br>`pnpm ops x-session --json '{"clearStop":true,"confirm":true,"note":"checked by hand"}'` | | `rerun-service-jobs` | — | | | `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` | | `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. Only a download waits on the platform's queue: the transcription runs as a transcribe-one job on the video's own queue (transcribe-one:&lt;slug&gt;:&lt;id&gt;), at once when nothing is downloaded, else handed off by the whisper-video once the audio is down. A job; --wait follows it through the hand-off to the end of the transcription. "queueKey" names another queue. A youtube-handling video with no audio whose metadata lists English captions has those fetched instead ({"instead": "captions", "message"}, the job the caption download), one with an English caption track on disk is refused; "asr": true transcribes it anyway (no "file"). "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. "whilePaused": true runs this one transcription during a pause-all on a worker the pause alone switched off; the pause stays on (the video page's "Transcribe now (workers paused)"). A video its record says is live, scheduled or still processing its VOD (live\_status is\_live, is\_upcoming, post\_live) is refused before anything is queued — a download would read the stream at 1x and hold the platform queue: record it with record-live, or wait for the VOD (refresh-metadata re-reads the record once it has ended). With its audio on disk it transcribes. | | @@ -376,15 +377,27 @@ 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); and X's JOB CAP: - 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 ON + allowed, reason (the refusal an X job would get) and refusedBy (alert, + jar, cap, sitting, cooldown or suspended); X's JOB CAP: + cap {lastHour, perHour: 6, lastDay, perDay: 150, reached, nextAt?} - + at most 6 X jobs start in any 60 minutes and 150 in any 24 hours ON THIS MACHINE: one count over every kind of X job, whatever the login source, cookie spec or channel. A job past it is refused when queued, with the time the next may start; one that meets it when its queue - starts it ends done, deferred (not failed). A library's media-only - capture is not counted. The numbers are constants of the code + starts it ends done, deferred (not failed). Every X job counts, a + library's media-only capture too. The numbers are constants of the code (common/lib/xJobRule.ts): no setting, option or queue raises them. + X's SITTING: sitting {began, kind, used, left, limit} - a cookie + refresh begins a sitting of at most social.x.sittingJobs X job starts + (default 4, 1-6 in the code), of ONE kind fixed by its first job: + timelines (account fetches, captures, availability checks, an import) + or browse (trending reads, X search walks, a library's captures). A + start past it, or of the other kind, is refused (at its start: done, + deferred); a new Refresh on /cookies starts the next. account {state, + since?, note?, alert?} is the operator's mark (x-session, below); + cooldown {until} is X's 15-minute stop after a rate limit or a bot check + met by any reader (gallery-dl, yt-dlp, the profile's pages), which + refuses every X job and Refresh/Connect. <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 diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -261,8 +261,9 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one | `E2E_AVAILABILITY_PROBE_GAP_MS` | the real gap (3 s, stretched by `pacing.jitter`) | The pause after each per-video availability probe. The editor's e2e server and the availability unit tests set 0: their stub yt-dlp answers at once. | common/controller/checkAvailability.ts | | `E2E_PACING_JITTER` | `pacing.jitter` from settings.json (0.25) | Replaces the operator's jitter share (0–1) for every request-pacing wait. The unit tests that assert an exact gap set 0; the jitter itself is tested with its share passed in (lib/jitter.test.ts). | common/lib/jitter.ts | | `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts | -| `E2E_JOB_GAP_SECONDS` | the built-in gaps (20 s; X 300, forums and Bluesky 60) | Replaces every BUILT-IN `pacing.jobGapSeconds` gap (plans/pacing-guard.md); a gap set in settings.json still applies. The editor's e2e server sets 0, so two fake fetches on one platform queue do not wait; pacing.spec sets its own. | common/jobs/queueGap.ts | -| `E2E_X_MAX_COOKIE_AGE_MINUTES` | the built-in 60 | Replaces the BUILT-IN `social.x.maxCookieAgeMinutes` (the fresh-jar rule for X jobs); a limit set in settings.json still applies. The editor's e2e server sets 0, so a fake X fetch needs no jar; x-session.spec sets its own. | common/jobs/networkGuard.ts | +| `E2E_JOB_GAP_SECONDS` | the built-in gaps (20 s; X 300, forums and Bluesky 60) | Replaces every BUILT-IN `pacing.jobGapSeconds` gap (plans/pacing-guard.md); a gap set in settings.json still applies — but X's gap, drawn per job from `social.x.gapMinMinutes`-`gapMaxMinutes`, is collapsed to this value whatever is set. Honoured only beside `E2E_TEST_ROUTES=1`. The editor's e2e server sets 0, so two fake fetches on one platform queue do not wait; pacing.spec sets its own. | common/jobs/queueGap.ts | +| `E2E_X_SITTINGS` | unset (X's sittings apply) | `off` leaves X jobs out of X's SITTINGS (at most `social.x.sittingJobs` X job starts per cookie refresh, of one kind each; common/lib/xSitting.ts) — inert unless `E2E_TEST_ROUTES=1`. The editor's e2e server sets it: its fake X jobs run many to one corpus with no refresh between them. X's job cap is not touched. | common/jobs/networkGuard.ts | +| `E2E_X_MAX_COOKIE_AGE_MINUTES` | the built-in 60 | Replaces the BUILT-IN `social.x.maxCookieAgeMinutes` (the fresh-jar rule for X jobs); a limit set in settings.json still applies. Honoured only beside `E2E_TEST_ROUTES=1`. The editor's e2e server sets 0, so a fake X fetch needs no jar; x-session.spec sets its own. | common/jobs/networkGuard.ts | | `E2E_ODYSEE_PAGE_FIXTURE` | unset (a headless browser) | A JSON file of recorded Odysee page reads keyed by page URL (`"*"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`). | common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts | | `E2E_UMTOOL_ORIGIN_FILE` | unset (UMTOOL_URL) | A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored. | common/lib/umtoolUrl.ts | | `E2E_WAYBACK_ORIGIN_FILE` | unset (the real Wayback Machine) | A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index, Save Page Now) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored. | common/lib/waybackClient.ts | diff --git a/OPERATING.md b/OPERATING.md @@ -517,11 +517,64 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait did not continue from its place: it stops at once with a sentence and keeps the place. If a place is lost, `fetch-posts {"older": true}` walks down from the oldest archived post. - **Pacing is enforced, not advised** (plans/pacing-guard.md). Every job that asks a platform waits its - platform queue's gap after the previous one there ended — `pacing.jobGapSeconds`: Instagram 600 s, X 300 s, - forums and Bluesky 60 s, everything else 20 s (set on /settings) — and its /jobs row and log say so (`waiting 4m12s: X - jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)`). Thirteen fetches queued in one loop run five - minutes apart and stop at the first challenge. A queue override of `""` (immediate) is refused for any - such job. + platform queue's gap after the previous one there ended — `pacing.jobGapSeconds`: Instagram 600 s, forums + and Bluesky 60 s, everything else 20 s (set on /settings) — and its /jobs row and log say so. **X's gap is + drawn per job**, uniform in `social.x.gapMinMinutes`-`gapMaxMinutes` (5-12 min; never below 5, an explicit + `pacing.jobGapSeconds.twitter` above 5 min raises the minimum, and the range is always at least 3 minutes wide, + so no setting makes it a fixed beat): `waiting 8m41s (a 9m02s gap drawn from 5-12 + min): X jobs are spaced 5-12 min apart, drawn per job`. A queue override of `""` (immediate) is refused for + any such job. +- **X in small, uneven sittings** (21 Nov 2026, after the account's suspension: one sitting of a trending read + and 12 timeline fetches, each 5-6 minutes after the last). A **sitting** begins at a cookie refresh (Refresh + cookies or Connect X account on /cookies) and admits at most `social.x.sittingJobs` X job starts — 4 by + default, bounded 1-6 in the code — counted as X's job cap counts them (each channel of an X run is one; a + library's media-only capture too). A sitting is **one kind**, fixed by its first job: **timelines** + (account post fetches in any mode, an X run's channels, Sync, captures of an account's posts, availability + checks, an import of one X post, X video windows) or **browse** (trending reads, an X search channel's walk, a + trending library's captures). A job past the sitting, or of the other kind, is refused when it is queued + (`This X sitting is used up: 4 of 4 X jobs started since the cookies were refreshed at 14:02 UTC …`), or ends + `done`, deferred, when its queue reaches it; nothing retries it. **A new Refresh starts the next sitting** — + and only a refresh does: the jar's refresh time is the broker's own stamp (`.x-session/refreshed.json`), not + the jar file's time, which gallery-dl used to rewrite after every run (gallery-dl now runs with + `cookies-update` off). The sitting is kept in `.x-session/sitting.json` (a restart keeps it; deleted, it is + counted again from the job records and X's job count; unreadable, no X job starts). `pnpm ops get x-session` + shows `sitting {began, kind, used, left, limit}`, and /cookies shows it on X's row with the jobs left. An X run + stops at the sitting's end like at a stale jar, and Resume after a Refresh takes the rest; the scheduler + queues no more X syncs than the sitting has left; a trending watch waits for the next Refresh. +- **The X account's state, marked by hand.** `pnpm ops x-session --json '{"accountState":"suspended","note":"…"}'` + (or **Mark suspended** on /cookies) records that the account X answers as is suspended (read-only). While it + is: `check-post-availability`, the video checks (`check-availability`, `quick-availability-check`, + `check-maybe-missing`, `check-kept-deleted`) on X, and `capture-posts` unless both its screenshots and its + articles are off are refused; and inside every X job nothing is written as gone from X's answer — a capture + record's "deleted"/"unavailable" becomes an error owed again, a video download's "deleted"/"private" class is + dropped from its outcome and its availability history, the post availability sidecar keeps only "available" — + even if the mark is made while the job runs. Every other X job's log says the account is marked suspended. + `{"accountState":"ok"}` (Mark ok) lifts it. Nothing detects a suspension by itself: neither the fetchers nor + gallery-dl see an explicit signal of OUR account's suspension in X's answers. +- **A rate limit or a bot check from X stops every X job for 15 minutes — one rule, one place** + (`recordXStop`, common/jobs/downloadBackoff.ts). Whoever met it records the same stop at once: gallery-dl on a + timeline, a search walk or a post's media (its rate-limit or challenge line), yt-dlp on an X address (never X's + old 60-second backoff), the profile's pages (a trending read's 429 or 403, a capture's "Something went wrong" / + "rate limit exceeded"), the media CDN, the auto-download lane. gallery-dl no longer waits a 429 out: it runs + with `ratelimit=abort`, so the run ends at its last page, keeps what it read and its place, and **the job ends + `done`, deferred** ("X answered a rate limit (gallery-dl) at 14:02 UTC: this job stopped there …"). The guard + then refuses every X job of any kind until it ends (`X answered a rate limit (429) a short while ago: no X job + starts before …`), and **Refresh cookies and Connect X account are refused too** (they load x.com), with the + time it ends. A stop file that cannot be read refuses as well. `get x-session` shows `cooldown {until}`; + nothing ends it early — not a clean answer from another reader, not Clear hold — but the operator's + **Clear the X stop** (/cookies, or `pnpm ops x-session --json '{"clearStop":true,"confirm":true}'`), which says + what it risks first and is logged in `.jobs/x-stop-cleared.jsonl`. Inside a capture, a refusal met by any of + its readers (an avatar's or an article image's 429, three pages in a row that would not render) records the + stop and ends the loop at once. A capture takes at most `social.x.maxPostsPerJob` posts (the rest are owed, + `owed`); a trending read's posts over its tabs stay within the same setting. +- **The Playwright fallback fetcher (`postFetcher: "x-playwright"`) is refused**: it cannot tell X's refusals. + A channel on it is refused in every mode, with the sentence naming the switch to `x-gallery-dl`. +- **What one X job may read.** A walk of an account's timeline (sync new, Resume backfill, `full`, `older`) or of + an X search reads at most `social.x.maxPostsPerJob` posts (300; 20-400 in the code), then saves its place and + ends; the next sitting continues it. +- **Clear session (Forget session) forgets the login only**: the profile, the jar and its refresh stamp. The + suspended mark, the sitting and X's job count stay (they describe the account); Mark ok and a new Refresh are + their own acts. - **Only the editor's jobs ask X.** `pnpm archilyzer posts fetch --slug <x-channel>` is refused, in every mode (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 @@ -543,16 +596,14 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait by the time it runs fails ("the saved copy no longer covers this window; ask again and it runs on X's queue") and asks X nothing. `fetch-copies` refuses a copy whose address is X's. A `t.co` short link is X's. `record-live` of an X channel is refused (a recording would hold X's queue for hours), and so is `redownload-incomplete-bucket` on one (the transcription queue). -- **X's job cap: 12 in any 60 minutes, 150 in any 24 hours, on this machine.** ONE count over every kind of X +- **X's job cap: 6 in any 60 minutes, 150 in any 24 hours, on this machine.** ONE count over every kind of X job together (each channel of an X run is one), whatever the login source, cookie spec or channel. A job past it is refused when it is queued, with the time the next may start; nothing queues behind it. **A job that meets it when its queue starts it ends `done`, deferred** (`[deferred] …` in its log, `deferred` on the job): it did not run, it is not a failed sync, and nothing queues it again before that time. 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`). **What counts:** a job that can ask x.com with the login or X's cookies — every X job but a trending - library's media-only capture (screenshots, articles, avatars and context off, not a keep capture), which takes - files from X's media hosts with no cookie and no page: it runs on X's queue under X's gap, cooldown and the - watch's jar rule, and the cap neither counts nor holds it. **The two numbers are constants of the code** + (`cap`). **What counts:** every X job, a trending library's media-only capture included (it asks X's media + hosts; 21 Nov 2026 ruling): it is in the cap, the sitting and the gap like any other. **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. If it is gone, the last 24 hours are counted again from @@ -562,10 +613,9 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait say since when in `.jobs/x-records-kept.json`; until that is a day old, a lost count is refused, at most for a day (a date in that file after now is no proof: said again at now). A start stamped in the future (a clock set back) counts until the clock has passed it by the window. The scheduler queues no more X syncs than the cap has - starts left (less the X jobs already waiting); the others wait for a later tick. 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. + starts left (less the X jobs already waiting); the others wait for a later tick. At 6 an hour the hourly cap + bites at X's floor gap (5 minutes) and implies the daily one (6 × 24 = 144 < 150), which stays as a second, + independent bound. In practice the sitting (4 per refresh) is reached first. - **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): @@ -772,8 +822,8 @@ pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","o store, the transcript archives read `data/`, and the source mirror publishes this code repo, not the corpus. Nothing in Archilyzer commits or pushes the corpus repo; a backup you run yourself over `transcripts/` is yours to point away from `trending/reads/`. -- **One page is one job on X's queue** (`read-x-trending`): the fresh-jar rule, the X alert and X's 5-minute job - gap apply as to every X job. The page is opened in the connected X profile's browser (headless; `"headed": true` +- **One page is one job on X's queue** (`read-x-trending`): the fresh-jar rule, the X alert, X's drawn 5-12 minute job + gap and X's sitting (a read is a browse job) apply as to every X job. The page is opened in the connected X profile's browser (headless; `"headed": true` opens a window on the editor's desktop), and what the page itself fetches is kept: every GraphQL JSON answer, raw, in `channels/<slug>/trending/reads/<readId>/responses.jsonl`, a screenshot (`page.png`) and the read's record (`read.json`: operation names and sizes only). No request is built and no header is stored. That directory is diff --git a/SETTINGS.md b/SETTINGS.md @@ -180,7 +180,7 @@ Default: `"when-required"` ## `social` -Per-platform settings of the social posts: X's three, all chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`), where X posts may appear (`social.x.visibility`) and how fresh its cookies must be for an X job to start (`social.x.maxCookieAgeMinutes`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts. +Per-platform settings of the social posts: X's, all chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`), where X posts may appear (`social.x.visibility`), how fresh its cookies must be for an X job to start (`social.x.maxCookieAgeMinutes`), how many X jobs one cookie refresh admits (`social.x.sittingJobs`) and the range X's gap is drawn from (`social.x.gapMinMinutes`, `social.x.gapMaxMinutes`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts. #### `social` @@ -197,6 +197,10 @@ Per-platform settings of the social posts: X's three, all chosen in the X accoun | `cookieSource` | absent | Where the X fetchers' login comes from. `"browser"`: the operator's everyday browser, named by `cookiesFromBrowser` — gallery-dl is handed `--cookies-from-browser <spec>` and reads it on every run, and the Playwright fallback reads the same store (Firefox only; common/social/xBrowserLogin.ts), so the login lasts as long as the browser's. `"profile"`: the session broker's persistent profile ("Connect X account" on /settings) and the cookie jar it exports. ABSENT (the default) is resolved at read time, never stored: `"browser"` when `cookiesFromBrowser` is set and no profile is connected (no exported jar carrying an auth_token), else `"profile"`. The source, not `cookieMode`, governs the X fetchers. | | `visibility` | absent | Where X posts may appear. `"public"` (the default; absent): an X channel's posts are built into every site that has the channel. `"private"`: every X channel's posts (a channel with `sourceKind: "social"` and `platform: "twitter"`) are left out of every PUBLIC site build — the channel with them, since posts are all an X channel holds — and built only into PRIVATE sites (`site.json` `audience`). Nothing on disk changes and fetching does not; a site already published changes on its next build and deploy, and flipping back is a rebuild. Chosen in the X account session section of /settings; the rule is common/lib/postsVisibility.ts. | | `maxCookieAgeMinutes` | absent | THE FRESH-JAR RULE: with the `"profile"` login source, a job that sends requests to X (Fetch posts, the older walk, an X search, Capture posts, Import one post, Check deleted posts — and the scheduler's fetches) is refused when it STARTS unless the profile's exported cookie jar was written within this many minutes and carries a login (an auth_token). The refusal says what to do: press Refresh cookies (or Connect X account) on /cookies, then fetch again. A refresh is a human click — it loads x.com/home, itself a request to X — so the editor never refreshes the jar to satisfy this. With the `"browser"` source the age cannot be read: the job logs that and proceeds. ABSENT: 60. 0 turns the rule off; at most 10080 (a week). Set in the X account session section of /settings. common/jobs/networkGuard.ts. | +| `sittingJobs` | absent | X IN SITTINGS: a sitting begins at a cookie refresh (Refresh cookies or Connect X account on /cookies) and admits at most this many X job starts — every kind that asks X, counted as X's job cap counts them (each channel of an X run is one). A start beyond it is refused (at enqueue, or `done`, deferred, at its start: never a failure that retries): a new Refresh starts the next sitting. A sitting is also ONE KIND, fixed by its first job: `timelines` (account post fetches, captures, availability checks, one post's import) or `browse` (trending reads, X search channels' walks, a trending library's captures); a job of the other kind waits for the next Refresh. The sitting is kept in `.x-session/sitting.json` (rebuilt from the job records if it is lost) and shown by `pnpm ops get x-session` and on /cookies. ABSENT: 4. Bounded 1-6 in the code (common/lib/xSitting.ts): no value raises it past 6. common/jobs/xSitting.ts. | +| `gapMinMinutes` | absent | THE SHORTEST GAP BEFORE AN X JOB, in minutes: X's queue gap is drawn per job, uniform between this and `gapMaxMinutes`, after the previous X job ended, and logged ("waiting 8m41s (a 9m02s gap drawn from 5-12 min)"). Never below 5 (the floor is in the code); an explicit `pacing.jobGapSeconds.twitter` above it raises it. ABSENT: 5. At most 120. common/jobs/queueGap.ts. | +| `gapMaxMinutes` | absent | THE LONGEST GAP BEFORE AN X JOB, in minutes (see `gapMinMinutes`). Never less than the minimum plus 3 (a range of one value is a fixed beat; the spread is in the code). ABSENT: 12. At most 120. | +| `maxPostsPerJob` | absent | WHAT ONE X JOB MAY READ: a walk of an account's timeline (sync new, Resume backfill, a full or older walk) or of an X search reads at most this many posts, then saves its place and ends; the next sitting continues it. A lower `limit` on the job still applies. ABSENT: 300. Bounded 20-400 in the code (common/lib/xSitting.ts). | #### `social.xenforo` diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -33,6 +33,8 @@ // shows), writing the context into the record and nothing about availability. import { xJobContextRefusal } from "../lib/xJobRule"; +import { xJobPostLimit } from "../lib/xSitting"; +import { keepVerdictsTrustedWhileSuspended } from "../social/xAccountState"; import path from "node:path"; import { isXSearchChannel } from "../lib/xSearch/config"; import { isXTrendingChannel, xTrendingMaxVideoBytes, type XTrendingConfig } from "../lib/xTrending/config"; @@ -44,7 +46,7 @@ import { xTrendingPostsRoot, } from "../lib/xTrending/store"; import { ensureXTrendingMediaIgnore } from "../lib/xTrending/mediaStore"; -import { platformCooldownRemainingMs, recordPlatformCooldown } from "../jobs/downloadBackoff"; +import { platformCooldownRemainingMs, recordXStop } from "../jobs/downloadBackoff"; import type { ChromiumLike } from "../social/playwrightRuntime"; import { createLibraryMediaDownloader, @@ -53,7 +55,6 @@ import { type MediaFetch, } from "../social/xTrendingMedia"; import { mediaSourcesInCapture, readCaptureLines, type TrendingMediaSource } from "../social/xTrendingParse"; -import { X_RATE_LIMIT_HOLD_MS } from "./readXTrending"; import { readChannelConfig } from "./channels"; import type { Paths } from "../lib/paths"; import type { Post, PostAvailability } from "../lib/posts"; @@ -167,6 +168,9 @@ export type CapturePostsResult = { avatars?: XAvatarRunSummary; // X: what the run read of the posts' context, when it read any. context?: XContextRunSummary; + // X: the ids past the per-job ceiling (social.x.maxPostsPerJob), not + // captured by this job and left for a later one (review 2 G3). + owed?: string[]; }; // Why this fetcher cannot capture posts, or null when it can. Shared with the @@ -263,7 +267,8 @@ export async function capturePosts( const log = (line: string) => onLog?.(line); const fail = (error: string): CapturePostsResult => ({ ok: false, outcomes: [], error }); const channelDir = path.join(paths.channelsDir, slug); - const ids = [...new Set(opts.ids)]; + let ids = [...new Set(opts.ids)]; + let owed: string[] = []; if (nothingToCapture(opts)) return fail(NOTHING_TO_CAPTURE); if (ids.length === 0) return fail("No post ids to capture."); @@ -300,6 +305,17 @@ export async function capturePosts( 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); + // WHAT ONE X JOB MAY TAKE (review 2 G3): the first posts up to the + // ceiling; the rest are owed to a later job (`owed`). + const cap = xJobPostLimit(settings?.social?.x as { maxPostsPerJob?: number } | undefined); + if (ids.length > cap) { + owed = ids.slice(cap); + ids = ids.slice(0, cap); + log( + `This X capture takes the first ${cap} of ${cap + owed.length} posts (social.x.maxPostsPerJob); ` + + `the other ${owed.length} are left for a later job, from ${owed[0]}.`, + ); + } } const avatarsOnly = opts.avatarsOnly === true; if (avatarsOnly) { @@ -466,11 +482,13 @@ export async function capturePosts( return { ok: true, outcomes: [], ...avatars }; } - // What the pages said about each post, folded into the sidecar. - const observations = new Map<string, PostAvailability>(); + // What the pages said about each post, folded into the sidecar — never a + // suspended X account's "deleted" (social/xAccountState.ts). + let observations = new Map<string, PostAvailability>(); for (const o of result.outcomes) { if (o.availability) observations.set(o.id, o.availability); } + if (fetcher.platform === "twitter") observations = await keepVerdictsTrustedWhileSuspended(paths, observations, log); if (observations.size > 0) { const { map, newlyDeleted, changed } = mergePostAvailability( await readPostAvailability(channelRoot), @@ -509,9 +527,9 @@ export async function capturePosts( const stoppedByOperator = (opts.signal ?? controller.signal).aborted || Boolean(opts.drain?.aborted); if (result.stoppedEarly && !stoppedByOperator) { - return { ok: false, outcomes: result.outcomes, error: result.stoppedEarly, ...avatars }; + return { ok: false, outcomes: result.outcomes, error: result.stoppedEarly, ...avatars, ...(owed.length ? { owed } : {}) }; } - return { ok: true, outcomes: result.outcomes, ...avatars }; + return { ok: true, outcomes: result.outcomes, ...avatars, ...(owed.length ? { owed } : {}) }; } const waitFor = (ms: number, signal: AbortSignal) => @@ -577,7 +595,7 @@ async function libraryMediaDownloader( pauseMs: () => libraryMediaPauseMs(), pause: waitFor, cooldownMs: () => platformCooldownRemainingMs(X, paths), - noteRateLimit: () => recordPlatformCooldown(X, X_RATE_LIMIT_HOLD_MS, paths), + noteRateLimit: () => recordXStop("a rate limit (429) from its media CDN", paths), ...asked?.deps, }, }); diff --git a/common/controller/checkPostAvailability.ts b/common/controller/checkPostAvailability.ts @@ -18,6 +18,7 @@ // posts never looked at, `all` re-checks everything. import { xJobContextRefusal } from "../lib/xJobRule"; +import { keepVerdictsTrustedWhileSuspended } from "../social/xAccountState"; import path from "node:path"; import { readChannelConfig } from "./channels"; import type { Paths } from "../lib/paths"; @@ -217,6 +218,8 @@ export async function checkPostAvailability( return { ok: false, ...empty, error: message }; } + // A suspended X account's "deleted" is not believed (social/xAccountState.ts). + if (fetcher.platform === "twitter") observations = await keepVerdictsTrustedWhileSuspended(paths, observations, log); const checkedAt = new Date().toISOString(); const { map, newlyDeleted, changed } = mergePostAvailability( availability, diff --git a/common/controller/fetchOlderPosts.test.ts b/common/controller/fetchOlderPosts.test.ts @@ -502,7 +502,7 @@ test("with nothing archived but posts found this run, the year-of-empties rule s assert.match(older?.completeReason ?? "", /^4 windows of 3 months in a row held no posts, back to [\d-]+$/); }); -test("a drain mid-window stops the search at once and keeps the resume point inside the window", async () => { +test("X's rate limit mid-window stops the search at once (review 1 F2) and keeps the resume point inside the window", async () => { const slug = "older-drain-window"; const channelRoot = await makeChannel(slug); await seed(channelRoot, slug); @@ -528,15 +528,14 @@ test("a drain mid-window stops the search at once and keeps the resume point ins delete process.env.FAKE_MODE; } assert.equal(result.ok, true, log.join("\n")); - assert.equal(result.drained, true); assert.equal(result.complete, false); + assert.ok(log.some((l) => /X answered this search with a rate limit: the walk stops at/.test(l)), log.join("\n")); assert.ok(Date.now() - started < 15_000, `took ${Date.now() - started} ms`); const older = (await readPostFetchState(channelRoot))?.older; assert.deepEqual( { since: older?.since, until: older?.until, maxId: older?.maxId, lastError: older?.lastError }, { since: "2020-12-11", until: "2021-03-11", maxId: idOf(POST_DATES[0]), lastError: undefined }, ); - assert.ok(log.some((l) => /Drained; the next run resumes at 2020-12-11 – 2021-03-11 below/.test(l)), log.join("\n")); }); test("a drain during the pause between windows ends it at once, at the next window, before another search", async () => { diff --git a/common/controller/fetchPosts.test.ts b/common/controller/fetchPosts.test.ts @@ -167,7 +167,8 @@ test("a cancelled first walk keeps what it read, and where it stopped as the BAC assert.equal(state?.backfill?.cursor, "1/AFTER-P2"); assert.equal(state?.cursor, undefined); assert.equal(state?.sync, undefined); - assert.ok(log.some((l) => /Cancelled; the next run resumes/.test(l)), log.join("\n")); + // X's rate limit ends the run itself now (review 1 F2: ratelimit=abort), before any cancel. + assert.ok(log.some((l) => /X answered this run with a rate limit: gallery-dl stopped at its last page/.test(l)), log.join("\n")); assert.ok(log.some((l) => /sync new — nothing archived yet, so this is the first full-history walk/.test(l)), log.join("\n")); const argv = await lastArgv(); assert.ok(argv.includes("output.jsonl=true")); @@ -422,7 +423,7 @@ test("a drain mid-page waits for the page's cursor, stops there and keeps it; th assert.ok((await lastArgv()).includes("extractor.twitter.cursor=1/PAGES-P1")); }); -test("a drain while gallery-dl waits out a rate limit stops it at once, keeping the last page's cursor", async () => { +test("X's rate limit stops gallery-dl at once (review 1 F2: never waited out), keeping the last page's cursor", async () => { const slug = "fake-x-drain-wait"; const root = await makeChannel(slug); const drain = new AbortController(); @@ -439,7 +440,8 @@ test("a drain while gallery-dl waits out a rate limit stops it at once, keeping }, }); assert.equal(result.ok, true, log.join("\n")); - assert.equal(result.drained, true); + assert.equal(result.complete, false); + assert.ok(log.some((l) => /X answered this run with a rate limit: gallery-dl stopped at its last page/.test(l)), log.join("\n")); assert.equal(result.written, 6); // Not left asleep for its 60 s. assert.ok(Date.now() - started < 15_000, `took ${Date.now() - started} ms`); @@ -756,3 +758,29 @@ test("R2a: an availability check of an X channel outside the editor's job is ref const inside = await asEditorJob(() => checkPostAvailability({ paths, slug: SLUG })); assert.doesNotMatch(inside.error ?? "", /asks X, and X/); }); + +// LANE X-SITTINGS, review 2 G1: the Playwright fallback cannot tell X's +// refusals, so a channel on it is refused in every mode, before anything +// opens, with the sentence naming the switch; the fetcher refuses too. +test("x-playwright is refused in every mode, naming the postFetcher to switch to; nothing is asked of X", async () => { + const slug = "fake-x-playwright"; + const root = await makeChannel(slug); + const config = JSON.parse(await readFile(path.join(root, "config.json"), "utf8")); + await writeFile(path.join(root, "config.json"), JSON.stringify({ ...config, postFetcher: "x-playwright" })); + const before = (await readFile(ARGS_LOG, "utf8").catch(() => "")).trim().split("\n").length; + for (const mode of [{}, { backfill: true }, { full: true }, { older: true }]) { + const log: string[] = []; + const { runInJobContext } = await import("../lib/jobContext"); + const ctx = { jobId: "g1", kind: "fetch-posts", queueKey: "platform:twitter", onLog: () => {}, staleServices: new Set<string>() }; + const r = await runInJobContext(ctx, async () => fetchPosts({ paths: (await import("../lib/paths")).getPaths(), slug, settings: {}, onLog: (l) => log.push(l), ...mode })); + assert.equal(r.ok, false, JSON.stringify(mode)); + // Refused by fetchPosts itself, before any walk began. + assert.ok(!log.some((l) => /^Fetching (older )?posts/.test(l)), log.join("\n")); + assert.match(r.error ?? "", /^fake-x-playwright's post fetcher is x-playwright \(the Playwright fallback\), which cannot tell when X refuses or rate-limits it, so it is refused: set the channel's postFetcher to x-gallery-dl/); + } + assert.equal((await readFile(ARGS_LOG, "utf8").catch(() => "")).trim().split("\n").length, before, "no gallery-dl run"); + const { xPlaywrightFetcher } = await import("../social/xPlaywrightFetcher"); + const direct = await xPlaywrightFetcher.fetch({ accountUrl: "https://x.com/faketester", handle: "faketester", channelSlug: slug, seenIds: new Set() } as never); + assert.equal(direct.complete, false); + assert.match(direct.error ?? "", /is refused/); +}); diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts @@ -95,6 +95,8 @@ import { import { instagramJobGuard } from "../jobs/instagramGuard"; import { currentJobContext } from "../lib/jobContext"; import { xJobContextRefusal } from "../lib/xJobRule"; +import { xJobPostLimit } from "../lib/xSitting"; +import { X_PLAYWRIGHT_REFUSED, xPlaywrightRefused } from "../social/xPlaywrightFetcher"; import { INSTAGRAM_QUEUE_KEY, INSTAGRAM_QUEUE_REFUSAL, isInstagramPostsChannelConfig } from "../lib/instagram/channel"; import { detectPlatform } from "../lib/platform"; import { postsMediaDir } from "../social/postCapture"; @@ -414,6 +416,16 @@ export async function fetchPosts( // …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 }; + // THE PLAYWRIGHT FALLBACK IS REFUSED (review 2 G1): it cannot tell X's + // refusals, so it would scroll past a 429 and call the walk complete. + if (fetcher.id === "x-playwright" && xPlaywrightRefused()) { + return { ok: false, written: 0, skipped: 0, complete: false, error: X_PLAYWRIGHT_REFUSED(slug) }; + } + // WHAT ONE X JOB MAY READ (review 1 F8; lib/xSitting.ts): every mode + // below — timeline, backfill, full, older, search — takes the limit. + const limit = xJobPostLimit(settings?.social?.x as { maxPostsPerJob?: number } | undefined, opts.limit); + if (limit !== opts.limit) log(`This X job reads at most ${limit} posts (social.x.maxPostsPerJob); then it saves its place and ends.`); + opts = { ...opts, limit }; } // 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 @@ -391,7 +391,8 @@ test("a 403 fails with its own sentence, keeps what was read, and raises no logi assert.match(result.sentence, /3 posts read before it were kept \(3 new\)\./); assert.match(result.sentence, /not taken for a lost login and no alert was raised/); assert.deepEqual(notes, []); - assert.equal(limited, 0); + // A 403 is X's bot check as often as not: the same 15-minute X stop as a 429 (review 1 F1). + assert.equal(limited, 1); assert.equal((await readXTrendingPosts(root(paths))).length, 3); }); diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts @@ -39,7 +39,7 @@ import { noteXServiceOutcome } from "../lib/serviceCookies-server"; import { heldPlatformRefusal, platformCooldownRemainingMs, - recordPlatformCooldown, + recordXStop, } from "../jobs/downloadBackoff"; import { isXTrendingChannel, @@ -101,7 +101,24 @@ export const READ_X_TRENDING_RESULT_MARKER = "@@read-x-trending "; // rate-limit window. Written as the `twitter` platform cooldown // (jobs/downloadBackoff.ts recordPlatformCooldown — the cooldown import-post // already respects), read by this job's enqueue and start. -export const X_RATE_LIMIT_HOLD_MS = 15 * 60_000; +export { X_RATE_LIMIT_HOLD_MS } from "../lib/xJobRule"; +import { xJobPostLimit } from "../lib/xSitting"; +import { getSettings } from "../lib/settings"; + +// WHAT ONE READ MAY TAKE (review 2 G3): its posts over all its tabs stay +// within social.x.maxPostsPerJob (default 300; the code's ceiling bounds it). +export function xTrendingPostsPerTab(asked: number, tabs: number, x: { maxPostsPerJob?: number } | undefined): number { + return Math.max(1, Math.min(asked, Math.floor(xJobPostLimit(x) / Math.max(1, tabs)))); +} + +function xPostsSettingNow(): { maxPostsPerJob?: number } | undefined { + try { + return getSettings().social?.x; + } catch { + return undefined; + } +} +import { X_RATE_LIMIT_HOLD_MS } from "../lib/xJobRule"; const X_PLATFORM = "twitter"; const hhmm = (ms: number) => new Date(ms).toISOString().slice(11, 16); @@ -282,7 +299,9 @@ export async function planReadXTrending( slug: ask.slug, channelRoot, ref, - limits: limits.limits, + // WHAT ONE X JOB MAY READ (review 1 F8): the read's posts over all its + // tabs stay within X's per-job ceiling (lib/xSitting.ts). + limits: { ...limits.limits, posts: xTrendingPostsPerTab(limits.limits.posts, tabs.tabs.length, xPostsSettingNow()) }, ...(topic ? { topic } : {}), probe: ask.probe === true, headed: ask.headed === true, @@ -727,9 +746,13 @@ export async function runXTrendingRead(o: { // cannot send the next read straight back to X. let limitedUntil: number | undefined; if (page.stop === "rate-limit") { - limitedUntil = await (deps.noteRateLimit ?? (() => recordPlatformCooldown(X_PLATFORM, X_RATE_LIMIT_HOLD_MS, paths, now())))().catch( + limitedUntil = await (deps.noteRateLimit ?? (() => recordXStop("a rate limit (429) to a trending read", paths, now())))().catch( () => now() + X_RATE_LIMIT_HOLD_MS, ); + } else if (page.stop === "forbidden") { + // A refusal (403) is X's bot check as often as not: the same X stop + // (review 1 F1). + await (deps.noteRateLimit ?? (() => recordXStop("a refusal (403) to a trending read", paths, now())))().catch(() => 0); } const untilText = limitedUntil === undefined ? "" : `${hhmm(limitedUntil)} UTC (${Math.ceil((limitedUntil - now()) / 60_000)} min)`; diff --git a/common/controller/xRun.test.ts b/common/controller/xRun.test.ts @@ -28,6 +28,11 @@ writeFileSync( const { getPaths } = await import("../lib/paths"); const xr = await import("./xRun"); +// X's gap is drawn in 5-12 min and has no off switch now (lane x-sittings: +// jobGapSeconds.twitter 0 no longer turns it off): a fake clock waits it out. +const { setQueueGapClock } = await import("../jobs/queueGap"); +let skew = 0; +setQueueGapClock({ now: () => Date.now() + skew, sleep: async (ms) => void (skew += ms) }); const { defaultChannelPriority } = await import("../lib/channelPriority"); const paths = getPaths(); diff --git a/common/controller/xRun.ts b/common/controller/xRun.ts @@ -58,7 +58,7 @@ import { ulid } from "../jobs/ulid"; import { getRegistry } from "../jobs/registry"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { guardNetworkJob, xSessionReport, type XSessionReport } from "../jobs/networkGuard"; -import { noteQueueJobEnd, queueGapClock, queueGapFor, waitForQueueGap } from "../jobs/queueGap"; +import { noteQueueJobEnd, queueGapClock, waitForQueueGap, xQueueGapRange } from "../jobs/queueGap"; import { requestChannelSnapshot } from "../jobs/snapshotScheduler"; import { fetchPosts } from "./fetchPosts"; import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "../lib/sourcelessPosts"; @@ -802,8 +802,10 @@ export type XRunConsole = { run: XRunView | null; candidates: XRunCandidate[]; jar: XRunJar; - // X's queue gap between two channels (pacing.jobGapSeconds.twitter), seconds. + // X's queue gap between two channels, seconds: drawn per channel from + // [gapSeconds, gapMaxSeconds] (social.x.gapMinMinutes / gapMaxMinutes). gapSeconds: number; + gapMaxSeconds: number; maxPosts: number; }; @@ -833,11 +835,12 @@ export async function xRunConsole(paths: Paths, runId?: string): Promise<XRunCon listXRunCandidates(paths), xSessionReport({ paths }), ]); - let gapSeconds = 0; + let range = xQueueGapRange(undefined, undefined); try { - gapSeconds = queueGapFor(getSettings().pacing, "twitter").seconds; + const settings = getSettings(); + range = xQueueGapRange(settings.pacing, settings.social?.x); } catch { - gapSeconds = queueGapFor(undefined, "twitter").seconds; + /* the defaults */ } - return { run, candidates, jar: xRunJar(report), gapSeconds, maxPosts: X_RUN_MAX_POSTS }; + return { run, candidates, jar: xRunJar(report), gapSeconds: range.minSeconds, gapMaxSeconds: range.maxSeconds, maxPosts: X_RUN_MAX_POSTS }; } diff --git a/common/controller/xTrendingWatch.ts b/common/controller/xTrendingWatch.ts @@ -142,7 +142,14 @@ function settingsCanBeRead(): boolean { // 60 minutes) — an age that cannot be read, or is negative (a clock set // back), refuses — and never when settings cannot be read. export async function watchRefusal(paths: Paths, slug: string, now: number, deps: WatchRefusalDeps = {}): Promise<WatchRefusal | null> { - const report = await (deps.report ?? xSessionReport)({ paths, channelSlug: slug, now, ...(deps.counts === false ? { counts: false } : {}) }); + // A watch's job is a read or a library's capture: a browse job of X's sitting. + const report = await (deps.report ?? xSessionReport)({ + paths, + channelSlug: slug, + now, + sittingKind: "browse", + ...(deps.counts === false ? { counts: false } : {}), + }); if (!report.hasProfile) { return { reason: "no-profile", @@ -180,6 +187,13 @@ export async function watchRefusal(paths: Paths, slug: string, now: number, deps if (deps.counts !== false && !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." }; } + // X'S SITTING (lib/xSitting.ts) used up or of the other kind, X cooling down + // after a 429, or the account marked suspended: the tick is skipped and the + // watch waits — the sitting's ends at the next Refresh, the cooldown's at + // its time. Not the jar's fault. + if (!report.allowed && (report.refusedBy === "sitting" || report.refusedBy === "cooldown" || report.refusedBy === "suspended")) { + return { reason: "cooldown", sentence: report.reason ?? "X is held." }; + } // 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); diff --git a/common/jobs/downloadBackoff.ts b/common/jobs/downloadBackoff.ts @@ -42,6 +42,9 @@ import { settlePlatformClean, } from "./platformBackoff"; import { staticSleepRequestsSeconds } from "../ytdlp/platformArgs.mjs"; +import { applyXStop, clearXStopEntry, X_STOP_MS, X_STOP_PLATFORM } from "./platformBackoff"; +import { currentJobContext } from "../lib/jobContext"; +import { readFile } from "node:fs/promises"; // Milliseconds remaining in the platform's current cooldown window, or 0 if it // is not cooling down. Prefers the live shared object; else reads the file. @@ -106,6 +109,12 @@ export async function recordDownloadBackoff( failureClass: "rate_limit" | "network" = "rate_limit", pacing: PacingSettings | undefined = pacingSettings(), ): Promise<void> { + // X's rate limit (yt-dlp on an X address, any caller): the X stop, never + // the generic backoff (review 1 F1). + if (platform === X_STOP_PLATFORM && failureClass === "rate_limit") { + await recordXStop("a rate limit (yt-dlp)", paths); + return; + } await mutateDownloadState(paths, (state) => { const now = Date.now(); prunePlatformPacing(state.download, now); @@ -129,6 +138,8 @@ export async function recordPlatformCooldown( paths: Paths = getPaths(), now: number = Date.now(), ): Promise<number> { + // X's is the X stop, whatever length was asked for. + if (platform === X_STOP_PLATFORM) return recordXStop("a rate limit", paths, now); return mutateDownloadState(paths, (state) => { prunePlatformPacing(state.download, now); const prev = state.download.platformBackoff[platform]; @@ -269,3 +280,73 @@ export async function clearPlatformHold( return `Cleared by hand for ${platform}: ${parts.join(", ")}. The next failure starts from the bottom of the backoff.\n`; }); } + +// THE X STOP, RECORDED (lane x-sittings, review 1 F1/F2): every reader that +// meets X's rate limit or a bot check calls this, AT ONCE (not when its run +// ends). The guard then refuses every X job until it ends +// (jobs/networkGuard.ts); the job that met it is told through its context and +// ends DEFERRED, saying so (jobs/streamCommand.ts). `why` names the answer +// ("a rate limit (gallery-dl)"). Answers when the stop ends (ms). +export async function recordXStop(why: string, paths: Paths = getPaths(), now: number = Date.now()): Promise<number> { + // The job is told FIRST (review 2 G5): a write that fails still stops it. + const job = currentJobContext(); + if (job && (!job.xStop || job.xStop.until < now + X_STOP_MS)) job.xStop = { until: now + X_STOP_MS, why, at: now }; + const until = await mutateDownloadState(paths, (state) => { + prunePlatformPacing(state.download, now); + return applyXStop(state.download, now).until; + }); + if (job) { + if (job.xStop && job.xStop.until < until) job.xStop = { ...job.xStop, until }; + job.onLog(`X answered ${why}: X is left alone until ${new Date(until).toISOString().slice(11, 16)} UTC (15 minutes); this job stops here.`); + } + return until; +} + +// What is left of the X stop (ms), READ STRICTLY (review 1 F7): a state file +// that is there and cannot be parsed throws — the guard then refuses — where +// the lane's own reader takes it as empty. +export async function xStopRemainingMs(paths: Paths = getPaths(), now: number = Date.now()): Promise<number> { + const live = await liveAutoQueueState(paths); + let entry = live?.download.platformBackoff[X_STOP_PLATFORM]; + let text: string | null = null; + try { + text = await readFile(paths.autoQueueStateFile, "utf8"); + } catch (err) { + if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") throw err; + } + if (text !== null) { + const raw = JSON.parse(text) as { download?: { platformBackoff?: Record<string, { until?: unknown }> } }; + const onDisk = raw?.download?.platformBackoff?.[X_STOP_PLATFORM]?.until; + if (typeof onDisk === "number" && Number.isFinite(onDisk) && (!entry || onDisk > entry.until)) { + entry = { until: onDisk, fails: entry?.fails ?? 0 }; + } + } + return entry && entry.until > now ? entry.until - now : 0; +} + +// "CLEAR THE X STOP" (review 2 G4): the operator's named, logged act — the +// only way X's 15-minute stop ends before its time. Without `confirm` it +// removes nothing and answers what it would risk. Each clear is logged in +// `<jobsDir>/x-stop-cleared.jsonl` ({at, until, why, by, note?}). +export const X_STOP_CLEAR_RISK = + "Clearing the X stop lets the next X job ask X at once, inside the 15 minutes X was left alone for after it " + + "answered a rate limit or a bot check — asking again then is what gets an account limited or locked."; + +export async function clearXStop( + paths: Paths, + opts: { confirm: boolean; by: string; note?: string; now?: number }, +): Promise<{ ok: true; cleared: { until: number } | null; message: string } | { ok: false; confirmNeeded: true; message: string }> { + const now = opts.now ?? Date.now(); + if (!opts.confirm) return { ok: false, confirmNeeded: true, message: `${X_STOP_CLEAR_RISK} Confirm to clear it.` }; + const removed = await mutateDownloadState(paths, (state) => clearXStopEntry(state.download, now)); + if (!removed) return { ok: true, cleared: null, message: "No X stop was running; nothing was cleared." }; + const { appendFile, mkdir } = await import("node:fs/promises"); + const line = { at: new Date(now).toISOString(), until: new Date(removed.until).toISOString(), by: opts.by, ...(opts.note ? { note: opts.note } : {}) }; + await mkdir(paths.jobsDir, { recursive: true }); + await appendFile(`${paths.jobsDir}/x-stop-cleared.jsonl`, `${JSON.stringify(line)}\n`); + return { + ok: true, + cleared: { until: removed.until }, + message: `The X stop (until ${line.until.slice(11, 16)} UTC) was cleared by ${opts.by}; X jobs may start now. Logged in .jobs/x-stop-cleared.jsonl.`, + }; +} diff --git a/common/jobs/jobMeta.ts b/common/jobs/jobMeta.ts @@ -50,6 +50,8 @@ export type JobMeta = { // can be rebuilt from the records (jobs/xJobCap.ts). Absent on metas from // before it. xStarts?: number[]; + // The X sittings those starts were counted in (JobRecord.xSittings). + xSittings?: Array<{ began: string | null; kind: "timelines" | "browse"; at: number }>; // The job ended deferred by X's job cap (JobRecord.deferred). deferred?: { until: number; sentence: string }; }; @@ -83,6 +85,7 @@ export async function writeJobMeta( ...(record.resumedFrom ? { resumedFrom: record.resumedFrom } : {}), ...(record.resumeCount ? { resumeCount: record.resumeCount } : {}), ...(record.queueKey === X_QUEUE_KEY ? { xStarts: [...(record.xStarts ?? [])] } : {}), + ...(record.xSittings?.length ? { xSittings: record.xSittings.map((x) => ({ ...x })) } : {}), ...(record.deferred ? { deferred: { ...record.deferred } } : {}), }; await writeFile(metaPath(paths, record.id), JSON.stringify(meta), "utf8"); @@ -116,6 +119,18 @@ export async function readJobMeta( if (m.resumedFrom !== undefined && typeof m.resumedFrom !== "string") delete meta.resumedFrom; if (m.resumedAs !== undefined && typeof m.resumedAs !== "string") delete meta.resumedAs; if (m.xStarts !== undefined && !(Array.isArray(m.xStarts) && m.xStarts.every((t) => typeof t === "number" && Number.isFinite(t)))) delete meta.xStarts; + if ( + m.xSittings !== undefined && + !( + Array.isArray(m.xSittings) && + m.xSittings.every((x) => { + const r = x as { began?: unknown; kind?: unknown; at?: unknown } | null; + return !!r && (r.began === null || typeof r.began === "string") && (r.kind === "timelines" || r.kind === "browse") && typeof r.at === "number" && Number.isFinite(r.at); + }) + ) + ) { + delete meta.xSittings; + } const d = m.deferred as { until?: unknown; sentence?: unknown } | undefined; if (d !== undefined && !(d && typeof d === "object" && typeof d.until === "number" && typeof d.sentence === "string")) delete meta.deferred; if ( diff --git a/common/jobs/networkGuard.ts b/common/jobs/networkGuard.ts @@ -19,6 +19,14 @@ // the "browser" source the age cannot be read: the job logs that and // proceeds. // +// 4. X IN SITTINGS (lane x-sittings, lib/xSitting.ts, jobs/xSitting.ts): a +// cookie refresh admits at most `social.x.sittingJobs` X job starts (4; +// 1-6 in the code), of ONE kind (timelines or browse, fixed by the +// first); X cooling down after a 429 refuses every X job; and an +// account the operator marked suspended refuses the jobs that record +// posts as deleted (social/xAccountState.ts). All in xSessionReport, the +// one computation behind the refusal and `get x-session`. +// // Operator, 2026-10-23: "only start X downloads with a recent cookie refresh", // "be very careful not to do that thing on any sort of site", "This should be // enforced in Archilyzer, not just an AI standing rule". @@ -50,6 +58,17 @@ import { jobKindLabel, kindIsNetwork } from "./jobKinds"; import { xJobAsksX, xJobCounts, xQueueRefusal, type XJobPlan } from "../lib/xJobRule"; import { isXTrendingChannel } from "../lib/xTrending/config"; import { recordXJobStart, xJobCapStatus } from "./xJobCap"; +import { recordXSittingStart, xSittingLook } from "./xSitting"; +import { + xSittingJobs, + xSittingKindOf, + xSuspendedRefuses, + xSuspendedSentence, + type XSittingKind, +} from "../lib/xSitting"; +import { readXAccountState, xAccountAlertLine } from "../social/xAccountState"; +import { heldPlatformRefusal, xStopRemainingMs } from "./downloadBackoff"; +import { xRateLimitHoldSentence } from "../lib/xTrending/config"; import { writeJobMeta } from "./jobMeta"; import type { JobSpec } from "./jobSpec"; import { getRegistry } from "./registry"; @@ -214,6 +233,8 @@ export function xJarVerdict(input: { // server sets 0, so its fake X fetches need no jar); a limit a spec writes into // settings.json still applies. Unset everywhere but the e2e test server. function e2eDefaultMaxAge(): number | undefined { + // Only on the test server (review 1 F6: jobs/queueGap.ts e2eHooksOn). + if (process.env.E2E_TEST_ROUTES !== "1") return undefined; const raw = process.env.E2E_X_MAX_COOKIE_AGE_MINUTES; if (raw === undefined || raw === "") return undefined; const n = Number(raw); @@ -245,8 +266,8 @@ async function channelCookieSpec(paths: Paths, slug: string | undefined, setting // `capped`: the refusal is the job cap's (no cookie banner is raised for it), // with `nextAt`, when the next X job may start. export type XGuardResult = - | { ok: true; note?: string } - | { ok: false; message: string; alert: boolean; capped?: true; nextAt?: number }; + | { ok: true; note?: string; accountAlert?: string } + | { ok: false; message: string; alert: boolean; refusedBy?: XSessionReport["refusedBy"]; capped?: true; nextAt?: number }; // 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 @@ -277,9 +298,32 @@ export type XSessionReport = { // cookie spec or channel (review 2 M1) — the caps (constants of the code), // and, when the cap is reached, when the next may start. 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. + // X'S SITTING (lib/xSitting.ts, jobs/xSitting.ts): when it began (the + // jar's refresh; null: none on record), its kind (null: no job yet; + // "unknown": its record was lost), the starts it admitted and has left, + // and the limit (social.x.sittingJobs, 1-6). `unreadable`: the file cannot + // be read and no X job starts. + sitting: { + began: string | null; + kind: XSittingKind | "unknown" | null; + used: number; + left: number; + limit: number; + // The kind of the job asked about, when one was. + asked?: XSittingKind; + unreadable?: true; + }; + // THE ACCOUNT'S STATE as the operator marked it (social/xAccountState.ts): + // "suspended" refuses the jobs that record deleted posts; `alert` is the + // line /cookies shows. + account: { state: "ok" | "suspended"; since?: string; note?: string; alert?: string }; + // X cooling down after a rate limit (429: 15 minutes), when it is: until when. + cooldown: { until: string } | null; + // Would an X job start now? `reason` is the refusal it would get, and + // `refusedBy` which rule gave it. allowed: boolean; reason: string | null; + refusedBy?: "alert" | "jar" | "cap" | "sitting" | "cooldown" | "suspended"; note?: string; }; @@ -288,9 +332,15 @@ export async function xSessionReport(opts: { channelSlug?: string; now?: number; // False: the job asked about does not count against X's job cap (ruling - // R-a: xJobCounts), so the cap does not refuse it. The count is reported - // all the same. + // R-a: xJobCounts), so the cap does not refuse it — nor does its sitting. + // The counts are reported all the same. counts?: boolean; + // The job asked about: its sitting kind (absent: only a used-up sitting + // refuses), and whether it records posts as deleted or unavailable (a + // suspended account refuses it). + sittingKind?: XSittingKind; + recordsAvailability?: boolean; + what?: string; }): Promise<XSessionReport> { const now = opts.now ?? Date.now(); const status = await readXSessionStatus(opts.paths); @@ -316,10 +366,74 @@ export async function xSessionReport(opts: { ...(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 && opts.counts !== false ? { ...r, allowed: false, reason: capStatus.sentence ?? "X's job cap is reached." } : r; + // X'S SITTING: the jar's refresh begins it; the limit is the setting, + // bounded 1-6 in the code. + const limit = xSittingJobs(settings?.social?.x); + const refreshedAt = status.cookiesUpdatedAt ?? null; + const sittingOff = e2eSittingsOff(); + const look = await xSittingLook(opts.paths, { refreshedAt, kind: opts.sittingKind ?? "timelines", limit }); + const sitting: XSessionReport["sitting"] = { + began: look.status.state.began, + kind: look.status.state.kind, + used: look.status.used, + left: look.status.left, + limit, + ...(opts.sittingKind ? { asked: opts.sittingKind } : {}), + ...(!look.status.readable ? { unreadable: true as const } : {}), + }; + // Without a kind asked, only a used-up (or unreadable) sitting refuses. + const sittingRefusal = + sittingOff || opts.counts === false || look.verdict.ok + ? null + : opts.sittingKind || look.verdict.why === "used-up" || !look.status.readable + ? look.verdict.sentence + : null; + // The account's state, as marked. + const acct = await readXAccountState(opts.paths); + const account: XSessionReport["account"] = acct + ? { + state: acct.state, + since: acct.at, + ...(acct.note ? { note: acct.note } : {}), + ...(acct.state === "suspended" ? { alert: xAccountAlertLine(acct) } : {}), + } + : { state: "ok" }; + const suspendedRefusal = + acct?.state === "suspended" && opts.recordsAvailability === true + ? xSuspendedSentence(opts.what ?? "This job", acct.at, acct.note) + : null; + // X'S COOLDOWN AFTER A 429 (15 minutes) and its hold refuse EVERY X job, + // whatever its kind (rule 6 of lane x-sittings: it used to be asked only by + // the trending read, its media and the capture). + const wallNow = opts.now ?? Date.now(); + // READ STRICTLY (review 1 F7): a stop that cannot be read refuses. + let coolingMs = 0; + let held: string | null = null; + let unreadableStop: string | null = null; + try { + coolingMs = await xStopRemainingMs(opts.paths, wallNow); + held = await heldPlatformRefusal("twitter", opts.what ?? "This X job", opts.paths, wallNow); + } catch (err) { + unreadableStop = + `X's rate-limit stop cannot be read (${opts.paths.autoQueueStateFile}: ${(err as Error).message}): no X job starts ` + + "while it cannot be told whether X answered a rate limit in the last 15 minutes. Repair or remove the file, then ask again."; + } + const cooldown = coolingMs > 0 ? { until: new Date(wallNow + coolingMs).toISOString() } : null; + const coolRefusal = unreadableStop ?? held ?? (coolingMs > 0 ? xRateLimitHoldSentence("X job", coolingMs, wallNow) : null); + // The cap, the sitting, the cooldown and the account refuse whatever else + // would let the job through. + const capped = <T extends { allowed: boolean; reason: string | null }>(r: T): T & { refusedBy?: XSessionReport["refusedBy"] } => { + if (!r.allowed) return r; + if (coolRefusal) return { ...r, allowed: false, reason: coolRefusal, refusedBy: "cooldown" }; + if (suspendedRefusal) return { ...r, allowed: false, reason: suspendedRefusal, refusedBy: "suspended" }; + if (!capStatus.ok && opts.counts !== false) return { ...r, allowed: false, reason: capStatus.sentence ?? "X's job cap is reached.", refusedBy: "cap" }; + if (sittingRefusal) return { ...r, allowed: false, reason: sittingRefusal, refusedBy: "sitting" }; + return r; + }; const base = { + sitting, + account, + cooldown, cap, source: resolved.source, sourceChosen: resolved.chosen, @@ -345,6 +459,7 @@ export async function xSessionReport(opts: { ...base, alert: { raisedAt: raised.raisedAt ?? raised.since, line: raised.evidence.line }, allowed: false, + refusedBy: "alert", reason: `X answered with ${what} at ${at} UTC (${raised.evidence.line}) and its cookie alert is up, ` + `so no X job starts: ${serviceFixText(X_SERVICE, configuredCookieBrowser())}, then Recheck on the dashboard.`, @@ -355,24 +470,55 @@ export async function xSessionReport(opts: { const verdict = xJarVerdict({ source: resolved.source, status, maxAgeMinutes, now }); return verdict.ok ? capped({ ...base, alert: null, allowed: true, reason: null, ...(verdict.note ? { note: verdict.note } : {}) }) - : { ...base, alert: null, allowed: false, reason: verdict.message }; + : { ...base, alert: null, allowed: false, reason: verdict.message, refusedBy: "jar" }; +} + +// TEST-ONLY: E2E_X_SITTINGS=off on the e2e test server (with +// E2E_TEST_ROUTES=1, as it always runs) leaves its fake X jobs out of the +// sitting rule — they run many to a test corpus with no jar refresh between. +// Unset everywhere but the e2e test server; it does not touch X's job cap. +function e2eSittingsOff(): boolean { + return process.env.E2E_X_SITTINGS === "off" && process.env.E2E_TEST_ROUTES === "1"; } // 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: Pick<Paths, "transcriptsDir" | "jobsDir">, now?: number): Promise<string | null> { +export async function xCapHeldReason(paths: Paths, now?: number): Promise<string | null> { const status = await xJobCapStatus(paths, now ?? queueGapClock().now()); - return status.ok ? null : (status.sentence ?? "X's job cap is reached."); + if (!status.ok) return status.sentence ?? "X's job cap is reached."; + // X's sitting, used up (or unreadable), holds them the same way. + const sitting = await xSittingHeld(paths); + return sitting?.sentence ?? null; +} + +// X's sitting as the scheduler reads it: what it has left, and its refusal +// when it has none (a look: nothing counted). +async function xSittingHeld(paths: Paths): Promise<{ left: number; sentence?: string } | null> { + if (e2eSittingsOff()) return null; + try { + const status = await readXSessionStatus(paths); + const limit = xSittingJobs(settingsNow()?.social?.x); + const look = await xSittingLook(paths, { refreshedAt: status.cookiesUpdatedAt ?? null, kind: "timelines", limit }); + // The scheduler queues syncs (timelines jobs): a browse sitting, or one + // used up or unreadable, has no room for them. + if (look.verdict.ok) return { left: look.status.left }; + return { left: 0, sentence: look.verdict.sentence }; + } catch { + return null; + } } // HOW MANY X JOBS MAY START NOW under X's job cap (0 when it is reached or // its count cannot be read): for the scheduler, which queues no more X syncs // than that (review 3 N9). A look: nothing is counted. -export async function xCapRoom(paths: Pick<Paths, "transcriptsDir" | "jobsDir">, now?: number): Promise<number> { +export async function xCapRoom(paths: Paths, now?: number): Promise<number> { const status = await xJobCapStatus(paths, now ?? queueGapClock().now()); if (!status.ok) return 0; - return Math.max(0, Math.min(status.perHour - status.lastHour, status.perDay - status.lastDay)); + const cap = Math.max(0, Math.min(status.perHour - status.lastHour, status.perDay - status.lastDay)); + // No more than X's sitting has left, either. + const sitting = await xSittingHeld(paths); + return sitting ? Math.min(cap, sitting.left) : cap; } export async function xJobGuard(opts: { @@ -380,15 +526,25 @@ export async function xJobGuard(opts: { channelSlug?: string; now?: number; counts?: boolean; + sittingKind?: XSittingKind; + recordsAvailability?: boolean; + what?: string; }): Promise<XGuardResult> { const r = await xSessionReport(opts); - if (r.allowed) return { ok: true, ...(r.note ? { note: r.note } : {}) }; - const capped = r.cap.reached && r.alert === null && r.reason !== null && /^X's job (cap|count)/.test(r.reason); - const nextAt = capped && r.cap.nextAt ? Date.parse(r.cap.nextAt) : undefined; + if (r.allowed) { + return { + ok: true, + ...(r.note ? { note: r.note } : {}), + ...(r.account.state === "suspended" ? { accountAlert: r.account.alert ?? "The X account is marked suspended." } : {}), + }; + } + const capped = r.refusedBy === "cap"; + const nextAt = capped && r.cap.nextAt ? Date.parse(r.cap.nextAt) : r.refusedBy === "cooldown" && r.cooldown ? Date.parse(r.cooldown.until) : undefined; return { ok: false, message: r.reason ?? "X job refused.", alert: r.alert !== null, + ...(r.refusedBy ? { refusedBy: r.refusedBy } : {}), ...(capped ? { capped: true as const } : {}), ...(nextAt !== undefined && Number.isFinite(nextAt) ? { nextAt } : {}), }; @@ -397,13 +553,22 @@ export async function xJobGuard(opts: { // THE JOB'S PLAN, for X's job cap (lib/xJobRule.ts xJobCounts): its kind, its // spec's params, and whether its channel is a trending library (read here, // never taken from the caller). -async function xJobPlanOf(opts: NetworkJobOpts): Promise<XJobPlan> { +type XGuardPlan = XJobPlan & { channel?: XJobPlan["channel"] & { search?: boolean } }; + +async function xJobPlanOf(opts: NetworkJobOpts): Promise<XGuardPlan> { const params = planParams(opts); - let channel: XJobPlan["channel"]; + let channel: XGuardPlan["channel"]; if (opts.channelSlug) { const read = await readJsonFile(path.join(opts.paths.channelsDir, opts.channelSlug, "config.json")).catch(() => null); const config = read?.ok ? channelConfigSchema.parse(read.value) : null; - if (config) channel = { library: isXTrendingChannel(config), ...(config.postCaptureThread === true ? { postCaptureThread: true } : {}) }; + if (config) { + channel = { + library: isXTrendingChannel(config), + ...(config.postCaptureThread === true ? { postCaptureThread: true } : {}), + // An X search channel: its fetch is the search walk (browse). + ...(config.xSearch ? { search: true } : {}), + }; + } } return { kind: opts.kind, ...(params ? { params } : {}), ...(channel ? { channel } : {}) }; } @@ -428,14 +593,30 @@ async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promi // WHAT COUNTS (ruling R-a): decided from the job's own plan. A job that // does not count is not refused by the cap either; everything else of X's // guard holds for it. - const counts = xJobCounts(await xJobPlanOf(opts)); - const x = await xJobGuard({ paths: opts.paths, channelSlug: opts.channelSlug, counts }); + const plan = await xJobPlanOf(opts); + const counts = xJobCounts(plan); + // ITS SITTING KIND (lib/xSitting.ts): from its plan — its kind and its + // channel's config — never from a flag. An X run's own start (no channel) + // is no job of either kind: each channel is guarded with its slug. + const runStart = opts.kind === "x-run" && !opts.channelSlug; + const sittingKind = runStart ? undefined : xSittingKindOf(plan); + const what = `${jobKindLabel(opts.kind)}${opts.channelSlug ? ` for ${opts.channelSlug}` : ""}`; + const x = await xJobGuard({ + paths: opts.paths, + channelSlug: opts.channelSlug, + counts, + ...(sittingKind ? { sittingKind } : {}), + recordsAvailability: xSuspendedRefuses(plan), + what, + }); if (x.ok) { + const notes: string[] = x.note ? [x.note] : []; // 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 (counts && opts.countStart && opts.job && !(opts.kind === "x-run" && !opts.channelSlug)) { - const counted = await recordXJobStart(opts.paths, queueGapClock().now()); + if (counts && opts.countStart && opts.job && !runStart) { + const at = queueGapClock().now(); + const counted = await recordXJobStart(opts.paths, at); if (!counted.ok) { return { ok: false, @@ -443,23 +624,54 @@ async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promi ...(!counted.unreadable && counted.nextAt !== undefined ? { deferUntil: counted.nextAt } : {}), }; } - // The start on the job's own record (and its sidecar), so a lost count - // is rebuilt from the records (jobs/xJobCap.ts). + // THE SITTING, COUNTED (lib/xSitting.ts): checked and recorded in one + // step under its own lock. Refused here only on a race (the look above + // passed): the cap's start stays counted — more rather than fewer. const record = getRegistry().get(opts.job.id); + let sat: { began: string | null; kind: XSittingKind } | null = null; + if (sittingKind && !e2eSittingsOff()) { + const refreshedAt = (await readXSessionStatus(opts.paths)).cookiesUpdatedAt ?? null; + const r = await recordXSittingStart(opts.paths, { + refreshedAt, + kind: sittingKind, + limit: xSittingJobs(settingsNow()?.social?.x), + jobKind: opts.kind, + at: counted.at ?? at, + jobId: opts.job.id, + ...(opts.channelSlug ? { channel: opts.channelSlug } : {}), + }); + if (!r.verdict.ok) { + if (record && counted.at !== undefined) { + (record.xStarts ??= []).push(counted.at); + await writeJobMeta(opts.paths, record); + } + return { ok: false, error: r.verdict.sentence, deferUntil: 0 }; + } + sat = { began: r.began, kind: sittingKind }; + notes.push( + `X sitting: ${r.verdict.used} of ${r.verdict.limit} started (${sittingKind}, ` + + `${r.began ? `since the refresh at ${r.began.slice(11, 16)} UTC` : "no refresh on record"}); ${r.verdict.left} left.`, + ); + } + // The start on the job's own record (and its sidecar), so a lost count + // — and a lost sitting — is rebuilt from the records. if (record && counted.at !== undefined) { (record.xStarts ??= []).push(counted.at); + if (sat) (record.xSittings ??= []).push({ ...sat, at: counted.at }); await writeJobMeta(opts.paths, record); } } + // A suspended account (marked by hand): every X job's log says so. + if (x.accountAlert) notes.push(`${x.accountAlert} What X answers it may be thinned.`); // 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.) if (opts.job) await noteXJarFresh(opts.paths); - return { ok: true, notes: x.note ? [x.note] : [] }; + return { ok: true, notes }; } if (x.alert && opts.job) { await noteServiceStoppedJob(opts.paths, X_SERVICE, { id: opts.job.id, kind: opts.kind }); - } else if (!x.alert && !x.capped) { + } else if (!x.alert && x.refusedBy === "jar") { // 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. @@ -469,7 +681,11 @@ async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promi ...(opts.job ? { job: { id: opts.job.id, kind: opts.kind } } : {}), }); } - return { ok: false, error: x.message, ...(x.capped && x.nextAt !== undefined ? { deferUntil: x.nextAt } : {}) }; + // A cap, a cooldown or a sitting met AT A START ends the job deferred, not + // failed: nothing retries it (a sitting's until 0: until a Refresh). + const deferUntil = + (x.refusedBy === "cap" || x.refusedBy === "cooldown") && x.nextAt !== undefined ? x.nextAt : x.refusedBy === "sitting" ? 0 : undefined; + return { ok: false, error: x.message, ...(deferUntil !== undefined ? { deferUntil } : {}) }; } // Instagram's: its alert, then its cooldown (jobs/instagramGuard.ts). diff --git a/common/jobs/pacingGuard.test.ts b/common/jobs/pacingGuard.test.ts @@ -34,6 +34,11 @@ await writeFile( `#!/usr/bin/env node import { appendFileSync } from "node:fs"; appendFileSync(process.env.FAKE_RUNS, process.argv.slice(2).join(" ") + "\\n"); +if (process.env.FAKE_MODE === "ratelimit") { + // X's API answered 429: gallery-dl, told ratelimit=abort, stops at once. + process.stderr.write("[twitter][error] Rate limit exceeded\\n"); + process.exit(1); +} if (process.env.FAKE_MODE === "challenge") { // X answers after a moment, as it does: the loop has queued all 13 by then // (on a loaded machine an instant answer raced the loop's later enqueues). @@ -83,6 +88,7 @@ const { fetchPosts } = await import("../controller/fetchPosts"); const { getSettings } = await import("../lib/settings"); const { setQueueGapClock, clearQueueGaps } = await import("./queueGap"); const { xJobStartsFile } = await import("./xJobCap"); +const { xSittingFile } = await import("./xSitting"); const { readServiceCookieState, serviceCookiesFile } = await import("../lib/serviceCookies-server"); await import("../social/xGalleryDlFetcher"); @@ -126,11 +132,24 @@ async function reset(): Promise<void> { clearQueueGaps(); await rm(RUNS, { force: true }); await rm(serviceCookiesFile(paths), { force: true }); - await rm(path.join(paths.jobsDir, "queue-gaps.json"), { force: true }); + // X's queue gap: a known end long ago (a lost file is answered from the + // job records — review 1 F7 — whose clock is the wall's, not this test's). + await mkdir(paths.jobsDir, { recursive: true }); + await writeFile(path.join(paths.jobsDir, "queue-gaps.json"), JSON.stringify({ version: 1, ends: { "platform:twitter": 1 } })); // X's job count (jobs/xJobCap.ts): each test starts from none. (Deleting // the file would not: it is rebuilt from the earlier tests' job records.) await mkdir(path.dirname(xJobStartsFile(paths)), { recursive: true }); await writeFile(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [] })); + // X's stop after a 429 or a bot check (jobs/downloadBackoff.ts): none. + { + const { readAutoQueueState, writeAutoQueueState } = await import("./autoQueueState"); + const st = await readAutoQueueState(paths); + st.download.platformBackoff = {}; + st.download.platformHolds = {}; + await writeAutoQueueState(paths, st); + } + // X's sitting (jobs/xSitting.ts): each test starts a fresh one. + await writeFile(xSittingFile(paths), JSON.stringify({ version: 1, began: null, kind: null, starts: [] })); } async function readLog(jobId: string): Promise<string> { @@ -152,7 +171,9 @@ test("13 X fetches, job 1 meets a Cloudflare challenge: job 1 fails, the X alert const ends = await Promise.all(started.map((r) => (r.ok ? r.done : null))); assert.deepEqual( ends.map((e) => e?.status), - ["failed", ...Array(12).fill("failed")], + // Job 1 met X's bot check: it records the X stop and ends deferred + // (review 1 F1/F2); jobs 2–13 are refused by the alert. + ["done", ...Array(12).fill("failed")], ); // gallery-dl ran ONCE: only job 1 asked X. assert.equal(await runCount(), 1); @@ -160,6 +181,7 @@ test("13 X fetches, job 1 meets a Cloudflare challenge: job 1 fails, the X alert const first = await readLog(ends[0]!.jobId); assert.match(first, /Cloudflare challenge/); assert.match(first, /challenge or a login wall/); + assert.match(first, /^\[deferred\] X answered a bot check \(gallery-dl\) at \d\d:\d\d UTC/m); const second = await readLog(ends[1]!.jobId); assert.match(second, /X answered with a challenge at \d\d:\d\d UTC .*its cookie alert is up, so no X job starts/); const state = await readServiceCookieState(paths); @@ -177,7 +199,7 @@ test("13 X fetches, job 1 meets a Cloudflare challenge: job 1 fails, the X alert } }); -test("13 X fetches with no challenge start at least pacing.jobGapSeconds.twitter (300 s) apart", async () => { +test("13 X fetches queued in one loop: the sitting's 4 start 5-12 min apart (drawn), the other 9 end deferred unasked", async () => { await reset(); await writeJar(5 * 60_000); const starts = new Map<string, number>(); @@ -189,15 +211,21 @@ test("13 X fetches with no challenge start at least pacing.jobGapSeconds.twitter } const ends = await Promise.all(started.map((r) => (r.ok ? r.done : null))); assert.deepEqual(ends.map((e) => e?.status), Array(13).fill("done")); - assert.equal(await runCount(), 13); - const at = SLUGS.map((s) => starts.get(s)!); + // Only the sitting's four asked anything (lib/xSitting.ts: 4 per cookie refresh). + assert.equal(await runCount(), 4); + assert.deepEqual([...starts.keys()], SLUGS.slice(0, 4)); + for (const e of ends.slice(4)) { + assert.match(await readLog(e!.jobId), /\[deferred\] This X sitting is used up: 4 of 4 X jobs started/); + } + const at = SLUGS.slice(0, 4).map((s) => starts.get(s)!); for (let i = 1; i < at.length; i++) { - assert.ok(at[i] - at[i - 1] >= 300_000, `job ${i + 1} started ${(at[i] - at[i - 1]) / 1000}s after job ${i}`); + // The gap runs from the previous job's end (3 s after its start) and is drawn in 5-12 min. + const gap = at[i] - at[i - 1] - 3_000; + assert.ok(gap >= 300_000 && gap <= 720_000, `job ${i + 1} started ${gap / 1000}s after job ${i} ended`); } - // The waiting job's log says why it waited. + // The waiting job's log says why it waited, and what was drawn. const log2 = await readLog(ends[1]!.jobId); - // 5 min at least, stretched by up to pacing.jitter (lib/jitter.mjs). - assert.match(log2, /waiting [56]m\d\ds: X jobs are spaced 5 min apart \(pacing\.jobGapSeconds\.twitter\)/); + assert.match(log2, /waiting \d+m\d\ds \(a \d+m\d\ds gap drawn from 5-12 min\): X jobs are spaced 5-12 min apart, drawn per job/); // The end survives a restart: the file names the queue. const file = JSON.parse(await readFile(path.join(paths.jobsDir, "queue-gaps.json"), "utf8")); assert.equal(typeof file.ends["platform:twitter"], "number"); @@ -387,21 +415,21 @@ test("R2a: a job that asks X is refused on any queue but X's — at enqueue for 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 () => { +test("R2b: X's job cap — the 7th 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, 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, fakeNow)).lastHour, 12); - // The thirteenth, of ANOTHER kind: refused at enqueue, no job at all, with when the next may start. + // Five starts on record, of whatever kinds; then one fetch through the funnel is the sixth. + for (let i = 0; i < 5; i++) await recordXJobStart(paths, fakeNow); + const sixth = await fetchJob(SLUGS[0], new Map()); + assert.equal(sixth.ok, true, sixth.ok ? "" : sixth.error); + if (sixth.ok) assert.equal((await sixth.done).status, "done"); + assert.equal((await xJobCapStatus(paths, fakeNow)).lastHour, 6); + // The seventh, 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 on this machine: 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.match(res.ok ? "" : res.error, /^X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes \(the cap is 6\)\. 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. @@ -409,7 +437,7 @@ test("R2b: X's job cap — the 13th X job in an hour is refused before it starts // get x-session: the count, the caps, and the refusal. const report = await xReport({ paths }); 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.deepEqual({ ...report.cap, nextAt: typeof report.cap.nextAt }, { lastHour: 6, perHour: 6, lastDay: 6, 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; @@ -441,11 +469,11 @@ test("R2b: the start is counted once, by the last guard before the work; a look 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, fakeNow); + for (let i = 0; i < 4; i++) await recordXJobStart(paths, 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); + assert.equal(await count(), 6); // 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 })]) { @@ -476,43 +504,46 @@ test("M1: ONE count for the machine — a flipped login source, a respelled cook await writeJar(5 * 60_000); const count = async () => (await xJobCapStatus(paths, fakeNow)).lastHour; const start = (kind: string, slug: string) => guardNetworkJob({ kind, queueKey: "platform:twitter", paths, channelSlug: slug, job: { id: `m1-${kind}-${slug}` }, countStart: true }); + // One sitting of six (the most there is), so the cap is what fills here. + const SIX = { sittingJobs: 6 }; try { - // Three starts on the connected profile. - for (let i = 0; i < 3; i++) assert.equal((await start("fetch-posts", SLUGS[0])).ok, true); - assert.equal(await count(), 3); + await writeSettings({ cookieSource: "profile", ...SIX }); + // Two starts on the connected profile. + for (let i = 0; i < 2; i++) assert.equal((await start("fetch-posts", SLUGS[0])).ok, true); + assert.equal(await count(), 2); // The login source flipped to the browser: the same count, not a fresh one. - await writeSettings({ cookieSource: "browser" }, { cookiesFromBrowser: "firefox" }); - assert.equal((await xReport({ paths })).cap.lastHour, 3); - for (let i = 0; i < 3; i++) assert.equal((await start("fetch-posts", SLUGS[0])).ok, true); - assert.equal(await count(), 6); + await writeSettings({ cookieSource: "browser", ...SIX }, { cookiesFromBrowser: "firefox" }); + assert.equal((await xReport({ paths })).cap.lastHour, 2); + assert.equal((await start("fetch-posts", SLUGS[0])).ok, true); + assert.equal(await count(), 3); // The same browser spelled another way: still the same count. - await writeSettings({ cookieSource: "browser" }, { cookiesFromBrowser: " firefox:default " }); - assert.equal((await xReport({ paths })).cap.lastHour, 6); + await writeSettings({ cookieSource: "browser", ...SIX }, { cookiesFromBrowser: " firefox:default " }); + assert.equal((await xReport({ paths })).cap.lastHour, 3); assert.equal((await start("capture-posts", SLUGS[1])).ok, true); // A channel with a cookie spec of its own: the same count. await channelSpec(SLUGS[2], "chromium"); - assert.equal((await xReport({ paths, channelSlug: SLUGS[2] })).cap.lastHour, 7); + assert.equal((await xReport({ paths, channelSlug: SLUGS[2] })).cap.lastHour, 4); assert.equal((await start("check-post-availability", SLUGS[2])).ok, true); - // An X run over channels of different specs: each channel one start, in the one count. + // An X run over a channel of another spec: each channel one start, in the one count. await channelSpec(SLUGS[3], "brave"); await channelSpec(SLUGS[4], "chromium:Profile 2"); - for (const slug of [SLUGS[3], SLUGS[4], SLUGS[5], SLUGS[6]]) assert.equal((await start("x-run", slug)).ok, true); - assert.equal(await count(), 12); - // The thirteenth is refused whatever it uses. + assert.equal((await start("x-run", SLUGS[3])).ok, true); + assert.equal(await count(), 6); + // The seventh is refused whatever it uses. for (const [x, top, slug] of [ - [{ cookieSource: "profile" }, {}, SLUGS[7]], - [{ cookieSource: "browser" }, { cookiesFromBrowser: "firefox" }, SLUGS[7]], - [{ cookieSource: "browser" }, { cookiesFromBrowser: "safari" }, SLUGS[3]], + [{ cookieSource: "profile", ...SIX }, {}, SLUGS[7]], + [{ cookieSource: "browser", ...SIX }, { cookiesFromBrowser: "firefox" }, SLUGS[7]], + [{ cookieSource: "browser", ...SIX }, { cookiesFromBrowser: "safari" }, SLUGS[4]], ] as const) { await writeSettings(x, top); const refused = await start("fetch-posts", slug); assert.equal(refused.ok, false); - assert.match(refused.ok ? "" : refused.error, /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes/); + assert.match(refused.ok ? "" : refused.error, /^X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes/); } // get x-session names no login: the count is the machine's. const report = await xReport({ paths }); assert.equal("login" in report, false); - assert.deepEqual([report.cap.lastHour, report.cap.reached], [12, true]); + assert.deepEqual([report.cap.lastHour, report.cap.reached], [6, true]); } finally { await writeSettings({ cookieSource: "profile" }); for (const slug of [SLUGS[2], SLUGS[3], SLUGS[4]]) await channelSpec(slug, undefined); @@ -520,7 +551,7 @@ test("M1: ONE count for the machine — a flipped login source, a respelled cook } }); -test("R-a: a trending library's media-only capture is not counted and not refused by the cap; its keep capture and a capture with shots are", async () => { +test("review 1 F8 (R-a reversed): a trending library's media-only capture IS an X job — counted, and refused by the cap like any other", async () => { await reset(); await writeJar(5 * 60_000); const lib = "x-trending-lib"; @@ -534,26 +565,14 @@ test("R-a: a trending library's media-only capture is not counted and not refuse guardNetworkJob({ kind: "capture-posts", queueKey: "platform:twitter", paths, channelSlug: lib, spec: { kind: "capture-posts", slug: lib, params }, job: { id: "ra" }, ...(countStart ? { countStart: true } : {}) }); const count = async () => (await xJobCapStatus(paths, fakeNow)).lastHour; assert.equal((await capture(mediaOnly)).ok, true); - assert.equal(await count(), 0, "the media-only capture is not a start"); - assert.equal((await capture({ ...mediaOnly, keptMedia: true })).ok, true); - assert.equal((await capture({ ...mediaOnly, shots: true })).ok, true); - assert.equal(await count(), 2, "the keep capture and the capture with shots are"); - // The cap reached: the media-only capture still starts (it asks x.com nothing); the others are refused. - for (let i = 0; i < 10; i++) await recordXJobStart(paths, fakeNow); - assert.equal((await capture(mediaOnly, false)).ok, true); - assert.equal((await capture(mediaOnly)).ok, true); - for (const params of [{ ...mediaOnly, keptMedia: true }, { ...mediaOnly, shots: true }, { ...mediaOnly, articles: undefined }]) { + assert.equal(await count(), 1, "the media-only capture is a start"); + // The cap reached: it is refused like the others. + for (let i = 0; i < 5; i++) await recordXJobStart(paths, fakeNow); + for (const params of [mediaOnly, { ...mediaOnly, shots: true }]) { const refused = await capture(params, false); assert.equal(refused.ok, false); assert.match(refused.ok ? "" : refused.error, /^X's job cap is reached/); } - // It still meets the rest of X's guard: the queue, and the jar. - const moved = await guardNetworkJob({ kind: "capture-posts", queueKey: "manual", paths, channelSlug: lib, spec: { kind: "capture-posts", slug: lib, params: mediaOnly } }); - assert.equal(moved.ok, false); - await writeJar(5 * 60 * 60_000); - const stale = await capture(mediaOnly, false); - assert.equal(stale.ok, false); - assert.doesNotMatch(stale.ok ? "" : stale.error, /job cap/); await rm(path.join(transcripts, "channels", lib), { recursive: true, force: true }); await reset(); }); @@ -568,8 +587,8 @@ test("R-b: a job that meets the cap AT ITS START ends deferred — done, not fai const blocker = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: SLUGS[0], fn: async () => gate }); assert.equal(blocker.ok, true); for (let i = 0; i < 100 && (await xJobCapStatus(paths, fakeNow)).lastHour < 1; i++) await new Promise((r) => setTimeout(r, 20)); - // Ten more: eleven. The next passes its enqueue (a slot is left)… - for (let i = 0; i < 10; i++) await recordXJobStart(paths, fakeNow); + // Four more: five. The next passes its enqueue (a slot is left)… + for (let i = 0; i < 4; i++) await recordXJobStart(paths, fakeNow); const late = await fetchJob(SLUGS[1], new Map()); assert.equal(late.ok, true, late.ok ? "" : late.error); // …and the cap fills while it waits behind the first. @@ -581,7 +600,7 @@ test("R-b: a job that meets the cap AT ITS START ends deferred — done, not fai assert.equal(end.status, "done"); const record = getRegistry().get(late.jobId)!; assert.ok(record.deferred, "the record says it was deferred"); - assert.match(record.deferred!.sentence, /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes/); + assert.match(record.deferred!.sentence, /^X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes/); assert.equal(record.deferred!.until, (await xJobCapStatus(paths, fakeNow)).nextAt); assert.match(await readLog(late.jobId), /^\[deferred\] X's job cap is reached/m); assert.doesNotMatch(await readLog(late.jobId), /^\[error\]/m); @@ -589,7 +608,7 @@ test("R-b: a job that meets the cap AT ITS START ends deferred — done, not fai assert.deepEqual([meta?.status, meta?.deferred?.until, meta?.xStarts], ["done", record.deferred!.until, []]); // Nothing was asked, no start was counted, and no cookie banner was raised. assert.equal(await runCount(), before); - assert.equal((await xJobCapStatus(paths, fakeNow)).lastHour, 12); + assert.equal((await xJobCapStatus(paths, fakeNow)).lastHour, 6); assert.equal((await readServiceCookieState(paths)).services.x?.raisedAt, undefined); // The first job's own record carries its start (the count can be rebuilt from it). assert.equal((await readJobMeta(paths, blocker.jobId))?.xStarts?.length, 1); @@ -690,3 +709,39 @@ test("review 3 M2/S5: a window job is X's by its URLs on any channel; a URL-less } await reset(); }); + +test("rule 6 / review 1 F2: on X's rate limit gallery-dl STOPS (abort); the stop is recorded the moment it is seen; the job ends deferred; every X job of any kind is then refused", async () => { + await reset(); + await writeJar(5 * 60_000); + process.env.FAKE_MODE = "ratelimit"; + let jobId = ""; + try { + const res = await fetchJob(SLUGS[0], new Map()); + assert.equal(res.ok, true, res.ok ? "" : res.error); + if (!res.ok) return; + jobId = res.jobId; + assert.equal((await res.done).status, "done"); + } finally { + delete process.env.FAKE_MODE; + } + const log = await readLog(jobId); + // Recorded at once: the stop line comes before the run's summary. + const stopAt = log.indexOf("X answered a rate limit (gallery-dl): X is left alone until"); + assert.ok(stopAt >= 0, log); + assert.ok(stopAt < log.indexOf("gallery-dl read "), "the stop is recorded when the line is seen, before the run ends"); + assert.match(log, /^\[deferred\] X answered a rate limit \(gallery-dl\) at \d\d:\d\d UTC: this job stopped there and kept what it read/m); + const record = getRegistry().get(jobId)!; + assert.ok(record.deferred && record.deferred.until > Date.now() + 14 * 60_000); + // gallery-dl was told to abort on a rate limit, to read at most 300 posts, and not to write the jar back. + const argv = (await readFile(RUNS, "utf8")).trim().split("\n").at(-1) ?? ""; + assert.match(argv, /extractor\.twitter\.ratelimit=abort/); + assert.doesNotMatch(argv, /ratelimit=wait/); + assert.match(argv, /--post-range 1-300/); + assert.match(argv, /--cookies \S+cookies\.txt -o cookies-update=false/); + for (const [kind, slug] of [["fetch-posts", SLUGS[1]], ["capture-posts", SLUGS[2]], ["check-post-availability", SLUGS[3]], ["read-x-trending", undefined]] as const) { + const r = await runManagedFunction({ kind, queueKey: "platform:twitter", paths, ...(slug ? { channelSlug: slug } : {}), fn: async () => assert.fail("the job ran") }); + assert.equal(r.ok, false, kind); + assert.match(r.ok ? "" : r.error, /^X answered a rate limit \(429\) a short while ago: no X job starts before/, kind); + } + await reset(); +}); diff --git a/common/jobs/platformBackoff.ts b/common/jobs/platformBackoff.ts @@ -12,6 +12,7 @@ import { jitterUp } from "../lib/jitter.mjs"; import { pacingJitter } from "../lib/jitter"; +import { X_RATE_LIMIT_HOLD_MS } from "../lib/xJobRule"; export type PlatformBackoffEntry = { // Epoch ms: downloads for this platform are paused until this instant. @@ -68,6 +69,22 @@ export function mergeBackoffEntry( return { until: Math.max(a.until, b.until), fails: Math.max(a.fails, b.fails) }; } +// THE X STOP (lane x-sittings, review 1 F1): ONE rule for every answer from +// X that is a rate limit or a bot check, whoever met it — gallery-dl, yt-dlp, +// the profile's pages, the CDN. X is left alone for X_RATE_LIMIT_HOLD_MS (15 +// minutes) from `now`; `until` only ever moves later. Never X's exponential +// backoff (60 s first), never a hold. Pure: the live runner's state and the +// file (jobs/downloadBackoff.ts recordXStop) are both changed through it. +export const X_STOP_PLATFORM = "twitter"; +export const X_STOP_MS = X_RATE_LIMIT_HOLD_MS; + +export function applyXStop(state: { platformBackoff: PlatformBackoffState }, now: number): PlatformBackoffEntry { + const prev = state.platformBackoff[X_STOP_PLATFORM]; + const next = mergeBackoffEntry(prev, { until: now + X_STOP_MS, fails: (prev?.fails ?? 0) + 1 }); + state.platformBackoff[X_STOP_PLATFORM] = next; + return next; +} + // True when the platform is currently in a cooldown window. export function isCoolingDown( state: PlatformBackoffState, @@ -78,14 +95,27 @@ export function isCoolingDown( return entry !== undefined && entry.until > now; } -// Clear a platform's backoff (called on a successful download). Mutates in place. +// Clear a platform's backoff (called on a successful download, and by Clear +// hold). Mutates in place. NEVER X'S STOP BEFORE ITS TIME (review 2 G4): a +// clean answer from any reader, or Clear hold, leaves an X stop that has not +// ended; only clearXStopEntry — the operator's "Clear the X stop" — removes it. export function clearBackoff( state: PlatformBackoffState, platform: string, + now: number = Date.now(), ): void { + if (platform === X_STOP_PLATFORM && (state[platform]?.until ?? 0) > now) return; delete state[platform]; } +// THE OPERATOR'S "CLEAR THE X STOP" (review 2 G4): the one removal of X's stop +// before its time. Answers what was removed (null: no stop was running). +export function clearXStopEntry(state: { platformBackoff: PlatformBackoffState }, now: number): PlatformBackoffEntry | null { + const entry = state.platformBackoff[X_STOP_PLATFORM]; + delete state.platformBackoff[X_STOP_PLATFORM]; + return entry && entry.until > now ? entry : null; +} + // Drop entries whose cooldown lapsed long enough ago that keeping their `fails` // count for escalation memory no longer matters. Mutates in place, keeping the // map bounded across a long-running server. We retain a lapsed entry for one @@ -434,7 +464,7 @@ export function settlePlatformClean( ): CleanEffect { const pacing = opts.pacing ?? PACING_DEFAULTS; const releasedHold = isPlatformHeld(state.platformHolds, platform); - clearBackoff(state.platformBackoff, platform); + clearBackoff(state.platformBackoff, platform, opts.now ?? Date.now()); delete state.platformHolds[platform]; const pace = state.platformPace[platform]; let decayed = false; diff --git a/common/jobs/queueGap.test.ts b/common/jobs/queueGap.test.ts @@ -18,6 +18,7 @@ import { queueGapWait, waitForQueueGap, waitText, + setXGapRandom, } from "./queueGap"; import { jobGapSecondsFor, sanitizePacing } from "../lib/settingsSchema"; @@ -49,13 +50,18 @@ test("the gap: the operator's per platform, else the built-in per platform, else assert.deepEqual(sanitizePacing({ jobGapSeconds: { twitter: 10 ** 9 } }).jobGapSeconds, { twitter: 86400 }); }); -test("E2E_JOB_GAP_SECONDS replaces the built-ins only; a set value still applies", () => { +test("E2E_JOB_GAP_SECONDS replaces the built-ins only, and only on the test server (E2E_TEST_ROUTES=1); a set value still applies", () => { process.env.E2E_JOB_GAP_SECONDS = "0"; try { + // An editor started normally ignores it (review 1 F6). + delete process.env.E2E_TEST_ROUTES; + assert.equal(queueGapFor(undefined, "twitter").seconds, 300); + process.env.E2E_TEST_ROUTES = "1"; assert.equal(queueGapFor(undefined, "twitter").seconds, 0); assert.equal(queueGapFor({ jobGapSeconds: { twitter: 3 } }, "twitter").seconds, 3); } finally { delete process.env.E2E_JOB_GAP_SECONDS; + delete process.env.E2E_TEST_ROUTES; } }); @@ -76,13 +82,23 @@ test("no end yet: no wait; an end: wait out the rest; the end is persisted and r delete process.env.E2E_JOB_GAP_SECONDS; const paths = await jobsDir(); const q = "platform:twitter"; - // jitter 0: the exact gap (the jittered one has its own test below). + // X's gap is drawn from a range, never one value (jobs/xSittings.test.ts): + // a 5-5 setting is widened to 5-8 min, and a seeded draw makes it exact here. const exact = { jobGapSeconds: {}, jitter: 0 }; - assert.equal(await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_000_000 }), null); - await noteQueueJobEnd(paths, q, 1_000_000); - const w = await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_048_000 }); - assert.equal(w?.remainingMs, 252_000); - assert.equal(await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_300_000 }), null); + const xGap = { gapMinMinutes: 5, gapMaxMinutes: 5 }; + setXGapRandom(0); + try { + assert.equal(await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_000_000, xGap }), null); + await noteQueueJobEnd(paths, q, 1_000_000); + const w = await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_048_000, xGap }); + assert.ok(w && w.drawn); + assert.deepEqual(w!.drawn!.range, { minSeconds: 300, maxSeconds: 480 }); + assert.equal(w!.remainingMs, w!.drawn!.seconds * 1000 - 48_000); + assert.match(queueGapLine(w!), /^waiting \d+m\d\ds \(a \d+m\d\ds gap drawn from 5-8 min\): X jobs are spaced 5-8 min apart, drawn per job/); + assert.equal(await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_000_000 + 480_001, xGap }), null); + } finally { + setXGapRandom(null); + } const file = JSON.parse(await readFile(path.join(paths.jobsDir, "queue-gaps.json"), "utf8")); assert.equal(file.ends[q], 1_000_000); clearQueueGaps(); // the restart diff --git a/common/jobs/queueGap.ts b/common/jobs/queueGap.ts @@ -15,6 +15,14 @@ // end: a job refused at its start (a stale X jar, a raised alert) asked // nothing, so the next one is not made to wait for it. // +// X'S GAP IS DRAWN, NOT FIXED (lane x-sittings, lib/xSitting.ts): a job on +// `platform:twitter` waits a gap drawn per job, uniform in +// `social.x.gapMinMinutes`-`gapMaxMinutes` (default 5-12 min, never below 5; +// an explicit `pacing.jobGapSeconds.twitter` above the minimum raises it), and +// says what was drawn ("waiting 8m41s (a 9m02s gap drawn from 5-12 min): …"). +// 12 fetches each 5-6 minutes after the last preceded the account's +// suspension; a fixed beat is what a script looks like. +// // The last end per queue is kept in memory and in `<jobsDir>/queue-gaps.json`, // so an editor restart is not a free pass (the scheduler's first tick after a // boot would otherwise ask X at once). @@ -25,6 +33,7 @@ // (sleepBetweenDownloadsSeconds + pace) and this one. import path from "node:path"; +import { readdir } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; import { spanText, waitText } from "./queueGapText"; @@ -32,6 +41,9 @@ import { JOB_GAP_DEFAULT_SECONDS, jobGapSecondsFor } from "../lib/jobGap"; import type { PacingSettingsBlock } from "../lib/settingsSchema"; import { jitterUpStable } from "../lib/jitter.mjs"; import { pacingJitter } from "../lib/jitter"; +import { randomInt } from "node:crypto"; +import { drawXGapSeconds, xGapRange, xGapRangeText, type XGapRange } from "../lib/xSitting"; +import { getSettings } from "../lib/settings"; export { spanText, waitText }; @@ -51,7 +63,15 @@ export function queueGapPlatform(queueKey: string): string | null { // sets 0, so its specs do not wait five minutes between two fake X fetches). // A gap a spec writes into settings.json still applies. Unset everywhere but // the e2e test server. +// THE TEST SERVER'S GATE (review 1 F6): every E2E_ hook here is honoured only +// beside E2E_TEST_ROUTES=1, as the e2e server always runs — never in an +// editor started normally, whatever else its environment carries. +export function e2eHooksOn(): boolean { + return process.env.E2E_TEST_ROUTES === "1"; +} + function builtInGaps(): Readonly<Record<string, number>> { + if (!e2eHooksOn()) return JOB_GAP_DEFAULT_SECONDS; const raw = process.env.E2E_JOB_GAP_SECONDS; if (raw === undefined || raw === "") return JOB_GAP_DEFAULT_SECONDS; const n = Number(raw); @@ -61,6 +81,86 @@ function builtInGaps(): Readonly<Record<string, number>> { export type QueueGap = { seconds: number; key: string }; +// TEST-ONLY, as above: the e2e server's E2E_JOB_GAP_SECONDS, which collapses +// X's drawn range to that one value too (0: no gap), else undefined. +function e2eGapSeconds(): number | undefined { + if (!e2eHooksOn()) return undefined; + const raw = process.env.E2E_JOB_GAP_SECONDS; + if (raw === undefined || raw === "") return undefined; + const n = Number(raw); + return Number.isFinite(n) && n >= 0 ? Math.floor(n) : undefined; +} + +// ── X's gap: drawn per job (lane x-sittings, lib/xSitting.ts) ────────────── + +export type XGapSettings = { gapMinMinutes?: number; gapMaxMinutes?: number }; + +// The range X's gap is drawn from: `social.x.gapMinMinutes`-`gapMaxMinutes` +// (default 5-12 min, never below 5), an explicit pacing.jobGapSeconds.twitter +// raising the minimum. The e2e server's E2E_JOB_GAP_SECONDS collapses it. +export function xQueueGapRange( + pacing: Pick<PacingSettingsBlock, "jobGapSeconds"> | undefined, + x: XGapSettings | undefined, +): XGapRange { + const e2e = e2eGapSeconds(); + if (e2e !== undefined) return { minSeconds: e2e, maxSeconds: e2e }; + return xGapRange(x, pacing?.jobGapSeconds?.twitter); +} + +// THE DRAW: uniform in the range, from the system's random source — or, in a +// test, a seeded one (setXGapRandom). Drawn ONCE per wait: a wait is re-read +// after every sleep, and a fresh draw per read would end it at the shortest. +declare global { + // eslint-disable-next-line no-var + var __yttXGapRandom__: (() => number) | undefined; + // eslint-disable-next-line no-var + var __yttXGapDraws__: Map<string, number> | undefined; +} + +// TEST-ONLY: a seeded generator (mulberry32) for the draw; null restores the +// system's random source. +export function setXGapRandom(seed: number | null): void { + if (seed === null) { + globalThis.__yttXGapRandom__ = undefined; + return; + } + let a = seed >>> 0; + globalThis.__yttXGapRandom__ = () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function xGapRandom(): number { + return globalThis.__yttXGapRandom__ ? globalThis.__yttXGapRandom__() : randomInt(0, 2 ** 32) / 2 ** 32; +} + +// The gap drawn for the wait after the end at `last` on `queueKey` (memoised: +// the same wait, re-read, keeps its draw; a range changed while it waits is +// drawn again, within the new range). +export function drawnXGapSeconds(queueKey: string, last: number, range: XGapRange): number { + const draws = (globalThis.__yttXGapDraws__ ??= new Map()); + const key = `${queueKey}@${last}@${range.minSeconds}-${range.maxSeconds}`; + let seconds = draws.get(key); + if (seconds === undefined) { + seconds = drawXGapSeconds(range, xGapRandom()); + if (draws.size > 256) draws.clear(); + draws.set(key, seconds); + } + return seconds; +} + +function xGapSettingsNow(): XGapSettings | undefined { + try { + return getSettings().social?.x; + } catch { + return undefined; + } +} + export function queueGapFor( pacing: Pick<PacingSettingsBlock, "jobGapSeconds"> | undefined, platform: string, @@ -169,6 +269,7 @@ export function noteQueueJobEnd( export function clearQueueGaps(): void { globalThis.__yttQueueGaps__?.clear(); + globalThis.__yttXGapDraws__?.clear(); } // ── the wait ─────────────────────────────────────────────────────────────── @@ -185,6 +286,8 @@ export type QueueGapWait = { until: number; remainingMs: number; reason: string; + // X's gap: the seconds drawn for this wait, and the range drawn from. + drawn?: { seconds: number; range: XGapRange }; }; // How long a network job on `queueKey` must still wait, or null for none. @@ -199,9 +302,31 @@ export async function queueGapWait(opts: { queueKey: string; pacing: (Pick<PacingSettingsBlock, "jobGapSeconds"> & { jitter?: number }) | undefined; now: number; + // X's range settings (`social.x`); absent: read from settings. + xGap?: XGapSettings; }): Promise<QueueGapWait | null> { const platform = queueGapPlatform(opts.queueKey); if (!platform) return null; + // X'S GAP IS DRAWN PER JOB from its range (lane x-sittings), not stretched + // from a fixed beat: the draw is the unevenness, so no jitter is added. + if (platform === "twitter") { + const range = xQueueGapRange(opts.pacing, opts.xGap ?? xGapSettingsNow()); + if (range.maxSeconds <= 0) return null; + // NO END ON RECORD IS NOT "NO X JOB EVER RAN" (review 1 F7): a lost + // queue-gaps.json is answered from the job records — the latest start or + // end of a job on X's queue. Only a corpus with none waits nothing. + const last = (await lastQueueEnd(opts.paths, opts.queueKey)) ?? (await lastXJobFromRecords(opts.paths, opts.queueKey)); + if (last === undefined) return null; + const seconds = drawnXGapSeconds(opts.queueKey, last, range); + const until = last + seconds * 1000; + if (until <= opts.now) return null; + return { + until, + remainingMs: until - opts.now, + reason: `X jobs are spaced ${xGapRangeText(range)} apart, drawn per job (social.x.gapMinMinutes, social.x.gapMaxMinutes)`, + drawn: { seconds, range }, + }; + } const gap = queueGapFor(opts.pacing, platform); if (gap.seconds <= 0) return null; const last = await lastQueueEnd(opts.paths, opts.queueKey); @@ -221,7 +346,11 @@ export async function queueGapWait(opts: { // The line a waiting job's log carries: // "waiting 4m12s: X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)". +// X's: "waiting 8m41s (a 9m02s gap drawn from 5-12 min): X jobs are spaced …". export function queueGapLine(w: QueueGapWait): string { + if (w.drawn) { + return `waiting ${waitText(w.remainingMs)} (a ${waitText(w.drawn.seconds * 1000)} gap drawn from ${xGapRangeText(w.drawn.range)}): ${w.reason}`; + } return `waiting ${waitText(w.remainingMs)}: ${w.reason}`; } @@ -296,3 +425,25 @@ function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> { signal?.addEventListener("abort", onAbort, { once: true }); }); } + +// The latest start or end of an ENDED job on `queueKey` in the job records, if any. +async function lastXJobFromRecords(paths: Pick<Paths, "jobsDir">, queueKey: string): Promise<number | undefined> { + let names: string[]; + try { + names = await readdir(paths.jobsDir); + } catch { + return undefined; + } + let latest: number | undefined; + for (const name of names) { + if (!name.endsWith(".meta.json")) continue; + const read = await readJsonFile(path.join(paths.jobsDir, name)); + const m = read.ok ? (read.value as Record<string, unknown> | null) : null; + // An ended job's (not the one now starting, which is running). + if (!m || m.queueKey !== queueKey || m.status === "running" || m.status === "queued") continue; + for (const t of [m.startedAt, m.endedAt]) { + if (typeof t === "number" && Number.isFinite(t) && (latest === undefined || t > latest)) latest = t; + } + } + return latest; +} diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts @@ -185,12 +185,18 @@ export type JobRecord = { // counted for (one for a job; one per channel for an X run). Kept on its // sidecar, so a count file that is lost is rebuilt from the records. xStarts?: number[]; + // The X sittings those starts were counted in (jobs/xSitting.ts): each + // start's sitting (the jar's refresh time; null: none on record) and kind, + // so a lost sitting file is rebuilt from the records. + xSittings?: Array<{ began: string | null; kind: "timelines" | "browse"; at: number }>; // A JOB THAT ENDED DEFERRED (review 2, ruling R-b): X's job cap was reached // when its queue started it, so it did not run — not a failure. It ends // `done` with this: the sentence, and when the next X job may start. // Nothing re-queues it by itself. ALSO (lane clean-unverified): a checked // Clean audio the source rate-limited — it deleted nothing it could not // verify and queued its own retry for `until` (controller/cleanAudioJob.ts). + // AND (lane x-sittings): an X job its sitting refused (used up, or of the + // other kind, jobs/xSitting.ts): `until` is 0 — until a person's Refresh. deferred?: { until: number; sentence: string }; }; diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts @@ -25,6 +25,8 @@ import type { JobSpec } from "./jobSpec"; import { kindIsNetwork, kindNeedsMedia, kindNeedsText } from "./jobKinds"; import { guardNetworkJob } from "./networkGuard"; import { noteQueueJobEnd, queueGapClock, waitForQueueGap } from "./queueGap"; +import { X_CLIPS_QUEUE_KEY, X_QUEUE_KEY } from "../lib/xJobRule"; +import { readXAccountState } from "../social/xAccountState"; import { getSettings } from "../lib/settings"; import { assertChannelMediaReachable, @@ -537,6 +539,11 @@ export async function runManagedFunction( queueKey: opts.queueKey, onLog, staleServices: new Set<string>(), + // An X job (on X's queues): its account mark, read at each write + // (review 1 F5; lib/jobContext.ts xAnswersUntrusted). + ...(opts.queueKey === X_QUEUE_KEY || opts.queueKey === X_CLIPS_QUEUE_KEY + ? { xSuspended: async () => (await readXAccountState(opts.paths))?.state === "suspended" } + : {}), }; // A NETWORK JOB (jobs/jobKinds.ts `network`) is guarded again at its // start — an X job queued behind a challenge is refused here, not run — @@ -589,6 +596,24 @@ export async function runManagedFunction( const noteEnd = () => { if (reachedWork) void noteQueueJobEnd(opts.paths, opts.queueKey, queueGapClock().now()); }; + // X'S STOP MET BY THIS JOB (jobs/downloadBackoff.ts recordXStop, review + // 1 F2): it stopped where X answered a rate limit or a bot check, kept + // what it read, and ends DEFERRED — not done, not failed — saying when X + // may be asked again. Nothing re-queues it. + const endedByXStop = (): boolean => { + const stop = jobCtx.xStop; + if (!stop) return false; + const hhmm = (ms: number) => new Date(ms).toISOString().slice(11, 16); + record.deferred = { + until: stop.until, + sentence: + `X answered ${stop.why} at ${hhmm(stop.at)} UTC: this job stopped there and kept what it read; ` + + `no X job starts before ${hhmm(stop.until)} UTC, and a later sitting continues it.`, + }; + onLog(`[deferred] ${record.deferred.sentence}`); + registry.finalize(id, "done"); + return true; + }; run() .then(() => { noteEnd(); @@ -596,6 +621,7 @@ export async function runManagedFunction( registry.finalize(id, "cancelled"); return; } + if (endedByXStop()) return; registry.finalize(id, "done"); }) .catch((err) => { @@ -604,6 +630,10 @@ export async function runManagedFunction( registry.finalize(id, "cancelled"); return; } + if (!(err instanceof JobDeferredError) && endedByXStop()) { + onLog(`(it ended with: ${(err as Error).message})`); + return; + } // X'S JOB CAP, MET AT THE START (review 2, ruling R-b): the job did // not run and did not fail. It ends `done`, DEFERRED, with the // sentence and when the next X job may start; nothing re-queues it. diff --git a/common/jobs/unitOutcome.ts b/common/jobs/unitOutcome.ts @@ -54,6 +54,8 @@ import { pruneDeferred, pruneSubtitleDeferrals, settlePlatformClean, + applyXStop, + X_STOP_PLATFORM, } from "./platformBackoff"; import { staticSleepRequestsSeconds } from "../ytdlp/platformArgs.mjs"; @@ -114,6 +116,16 @@ export function applyUnitOutcome( line: `Auto-download: ${unit.videoId} from its stored media URL failed (${unit.failureClass ?? "unknown"}); ${pf} is not touched.`, }; } + // X's rate limit: the X stop (15 minutes), never the generic backoff + // (review 1 F1; jobs/platformBackoff.ts applyXStop). + if (pf === X_STOP_PLATFORM && unit.failureClass === "rate_limit") { + const entry = applyXStop(state, now); + deferVideo(state.videoDeferrals, unit.videoId, unit.channelSlug, now); + return { + markCompleted: false, + line: `Auto-download: X answered a rate limit — X is left alone until ${new Date(entry.until).toISOString().slice(11, 16)} UTC (15 minutes); ${unit.videoId} deferred 6h.`, + }; + } if ( pf !== null && (unit.failureClass === "rate_limit" || unit.failureClass === "network") diff --git a/common/jobs/xJobCap.test.ts b/common/jobs/xJobCap.test.ts @@ -37,17 +37,17 @@ const keptSince = (paths: ReturnType<typeof corpus>, since: number) => { test("M1: ONE count for the machine — checked and recorded in one step, kept across a restart", async () => { const paths = corpus("disk"); - for (let i = 0; i < 12; i++) assert.equal((await recordXJobStart(paths, T0 + i * MIN)).ok, true); - const refused = await recordXJobStart(paths, T0 + 12 * MIN); + for (let i = 0; i < 6; i++) assert.equal((await recordXJobStart(paths, T0 + i * MIN)).ok, true); + const refused = await recordXJobStart(paths, T0 + 6 * MIN); assert.equal(refused.ok, false); - assert.match(refused.sentence ?? "", /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes/); + assert.match(refused.sentence ?? "", /^X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes/); // A refused start records nothing; the file is one list, with no login in it. assert.deepEqual(Object.keys(fileOf(paths)).sort(), ["starts", "version"]); assert.equal(fileOf(paths).version, 2); - assert.equal(fileOf(paths).starts.length, 12); + assert.equal(fileOf(paths).starts.length, 6); // "Restart": nothing is in memory; the file is the count. const again = await xJobCapStatus(paths, T0 + 13 * MIN); - assert.deepEqual([again.ok, again.lastHour, again.lastDay, again.nextAt], [false, 12, 12, T0 + 60 * MIN]); + assert.deepEqual([again.ok, again.lastHour, again.lastDay, again.nextAt], [false, 6, 6, T0 + 60 * MIN]); // A start recorded with the clock set back is recorded at the clock's time // (review 3 S4); the later start on record still counts, and is kept. const p2 = corpus("disk-back"); @@ -59,24 +59,24 @@ test("M1: ONE count for the machine — checked and recorded in one step, kept a assert.deepEqual(fileOf(p2).starts, [T0 + 25 * HOUR]); // Two at once: both recorded, neither lost. const p3 = corpus("disk-race"); - await Promise.all(Array.from({ length: 12 }, (_, i) => recordXJobStart(p3, T0 + i))); - assert.equal(fileOf(p3).starts.length, 12); + await Promise.all(Array.from({ length: 6 }, (_, i) => recordXJobStart(p3, T0 + i))); + assert.equal(fileOf(p3).starts.length, 6); assert.equal((await recordXJobStart(p3, T0 + 20)).ok, false); }); test("M1: a count of the first shape (one list per login key) is the SUM of its lists, and is rewritten as one", async () => { const paths = corpus("migrate"); mkdirSync(path.dirname(xJobStartsFile(paths)), { recursive: true }); - // 7 starts under the profile, 5 under a browser spec: the same machine's twelve. + // 4 starts under the profile, 2 under a browser spec: the same machine's six. const logins = { - profile: Array.from({ length: 7 }, (_, i) => T0 + i * MIN), - "browser:firefox": Array.from({ length: 5 }, (_, i) => T0 + (10 + i) * MIN), + profile: Array.from({ length: 4 }, (_, i) => T0 + i * MIN), + "browser:firefox": Array.from({ length: 2 }, (_, i) => T0 + (10 + i) * MIN), }; writeFileSync(xJobStartsFile(paths), JSON.stringify({ version: 1, logins })); const status = await xJobCapStatus(paths, T0 + 20 * MIN); - assert.deepEqual([status.ok, status.lastHour], [false, 12]); + assert.deepEqual([status.ok, status.lastHour], [false, 6]); assert.equal(fileOf(paths).version, 2); - assert.equal(fileOf(paths).starts.length, 12); + assert.equal(fileOf(paths).starts.length, 6); assert.equal((await recordXJobStart(paths, T0 + 21 * MIN)).ok, false); }); @@ -102,7 +102,7 @@ test("a count that cannot be read fails closed: no X job starts, and nothing is test("R-c: a fresh corpus where no X job ever ran starts at zero", async () => { const paths = corpus("fresh"); - assert.deepEqual(await xJobCapStatus(paths, T0), { ok: true, lastHour: 0, lastDay: 0, perHour: 12, perDay: 150 }); + assert.deepEqual(await xJobCapStatus(paths, T0), { ok: true, lastHour: 0, lastDay: 0, perHour: 6, perDay: 150 }); // Records of other queues only: still zero. const p2 = corpus("fresh-other-queues"); meta(p2, { kind: "download-missing", queueKey: "platform:youtube", startedAt: T0 - MIN }); @@ -200,15 +200,15 @@ test("review 3 S4: a start in the future counts in both windows and never prunes const paths = corpus("future"); mkdirSync(path.dirname(xJobStartsFile(paths)), { recursive: true }); // Ten real starts and one stamped a year ahead (a clock that jumped forward, then back). - const real = Array.from({ length: 10 }, (_, i) => T0 + i * MIN); + const real = Array.from({ length: 4 }, (_, i) => T0 + i * MIN); writeFileSync(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [...real, T0 + 365 * 24 * HOUR] })); const status = await xJobCapStatus(paths, T0 + 10 * MIN); - assert.deepEqual([status.ok, status.lastHour, status.lastDay], [true, 11, 11]); + assert.deepEqual([status.ok, status.lastHour, status.lastDay], [true, 5, 5]); const r = await recordXJobStart(paths, T0 + 10 * MIN); - assert.deepEqual([r.ok, r.at, r.lastHour], [true, T0 + 10 * MIN, 12]); + assert.deepEqual([r.ok, r.at, r.lastHour], [true, T0 + 10 * MIN, 6]); // The real starts are kept beside the future one. assert.deepEqual(fileOf(paths).starts, [...real, T0 + 365 * 24 * HOUR, T0 + 10 * MIN]); - assert.equal((await recordXJobStart(paths, T0 + 11 * MIN)).ok, false, "the hour holds twelve"); + assert.equal((await recordXJobStart(paths, T0 + 11 * MIN)).ok, false, "the hour holds six"); }); test("review 3 M3: a rebuild that cannot show its records cover the last day refuses, writes nothing, and ends by itself", async () => { diff --git a/common/jobs/xJobCap.ts b/common/jobs/xJobCap.ts @@ -73,6 +73,13 @@ async function readStartsFile(paths: CapPaths): Promise<{ state: "absent" } | { return { state: "bad" }; } +// The counted starts on disk, for X's sitting rebuild (jobs/xSitting.ts): +// null when the file is absent or cannot be read. A look: nothing written. +export async function readXJobStarts(paths: CapPaths): Promise<number[] | null> { + const file = await readStartsFile(paths); + return file.state === "ok" ? file.starts : null; +} + // ── the records are kept (review 3 M3) ───────────────────────────────────── // RETENTION NEVER DELETES THE RECORD OF AN X JOB THAT MAY STILL COUNT diff --git a/common/jobs/xSitting.ts b/common/jobs/xSitting.ts @@ -0,0 +1,252 @@ +// X'S SITTING, ON DISK (lane x-sittings; the rule and its numbers are +// lib/xSitting.ts). `<transcripts>/.x-session/sitting.json`: +// { "version": 1, "began": <iso> | null, "kind": "timelines" | "browse" | "unknown" | null, +// "starts": [{ "at": <ms>, "jobKind": "fetch-posts", "kind": "timelines", "jobId"?, "channel"? }, …] } +// +// - read and written under its lock (one check-and-record at a time), and +// it survives a restart; +// - A NEW SITTING BEGINS ONLY AT A LATER REFRESH: when the jar's refresh +// time (social/xSessionBroker.ts readXSessionStatus: the broker's own +// stamp, written by Connect and Refresh) is later than `began`. Nothing +// else resets it — not a restart, not a jar restored from a backup, not a +// clock set back; +// - it FAILS CLOSED: a file that is there and cannot be read or parsed +// refuses every counted X job until it is repaired; +// - A FILE THAT IS NOT THERE IS NOT A FRESH SITTING: it is rebuilt from what +// else counted the same starts — X's job count (jobs/xJobCap.ts: its +// starts since `began`) and the job records (`xSittings`: each start's +// sitting and kind). A sitting with starts and no recorded kind is +// "unknown", and refuses both kinds until the next Refresh. +// +// SERVER-ONLY (node:fs). + +import path from "node:path"; +import { readdir, readFile } from "node:fs/promises"; +import type { Paths } from "../lib/paths"; +import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server"; +import { + isLaterRefresh, + xSittingVerdict, + type XSittingKind, + type XSittingState, + type XSittingVerdict, +} from "../lib/xSitting"; +import { readXJobStarts } from "./xJobCap"; + +type SittingPaths = Pick<Paths, "transcriptsDir" | "jobsDir">; + +export function xSittingFile(paths: Pick<Paths, "transcriptsDir">): string { + return path.join(paths.transcriptsDir, ".x-session", "sitting.json"); +} + +export type XSittingStart = { at: number; jobKind: string; kind: XSittingKind; jobId?: string; channel?: string }; + +type SittingFile = { + version: 1; + began: string | null; + kind: XSittingKind | "unknown" | null; + starts: XSittingStart[]; +}; + +const finite = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v); +const isKind = (v: unknown): v is XSittingKind => v === "timelines" || v === "browse"; + +function parseStart(v: unknown): XSittingStart | null { + const r = v as Record<string, unknown> | null; + if (!r || typeof r !== "object" || !finite(r.at) || typeof r.jobKind !== "string" || !isKind(r.kind)) return null; + return { + at: r.at, + jobKind: r.jobKind, + kind: r.kind, + ...(typeof r.jobId === "string" ? { jobId: r.jobId } : {}), + ...(typeof r.channel === "string" ? { channel: r.channel } : {}), + }; +} + +async function readSittingFile(paths: SittingPaths): Promise<{ state: "absent" } | { state: "bad" } | { state: "ok"; file: SittingFile }> { + const read = await readJsonFile(xSittingFile(paths)); + if (!read.ok) return read.reason === "absent" ? { state: "absent" } : { state: "bad" }; + const v = read.value as Record<string, unknown> | null; + if (!v || typeof v !== "object" || v.version !== 1) return { state: "bad" }; + if (!(v.began === null || (typeof v.began === "string" && Number.isFinite(Date.parse(v.began))))) return { state: "bad" }; + if (!(v.kind === null || v.kind === "unknown" || isKind(v.kind))) return { state: "bad" }; + if (!Array.isArray(v.starts)) return { state: "bad" }; + const starts: XSittingStart[] = []; + for (const raw of v.starts) { + const s = parseStart(raw); + if (!s) return { state: "bad" }; + starts.push(s); + } + return { state: "ok", file: { version: 1, began: v.began as string | null, kind: v.kind as SittingFile["kind"], starts } }; +} + +async function writeSittingFile(paths: SittingPaths, file: SittingFile): Promise<void> { + await writeJsonAtomic(xSittingFile(paths), file, { mkdir: true }); +} + +function stateOf(file: SittingFile): XSittingState { + const first = file.starts[0]; + return { + began: file.began, + kind: file.kind, + used: file.starts.length, + ...(first ? { first: { jobKind: first.jobKind, at: first.at } } : {}), + }; +} + +// ── the rebuild ──────────────────────────────────────────────────────────── + +// The sitting that began at `began`, from the job records and X's job count. +// The larger of the two counts is taken (more rather than fewer); the kind is +// the records' (the first start's), else "unknown" when anything started. +export async function rebuildXSitting(paths: SittingPaths, began: string | null): Promise<SittingFile> { + const since = began === null ? -Infinity : Date.parse(began); + const recorded: XSittingStart[] = []; + let names: string[] = []; + try { + names = await readdir(paths.jobsDir); + } catch { + names = []; + } + for (const name of names) { + if (!name.endsWith(".meta.json")) continue; + let m: Record<string, unknown> | null = null; + try { + const parsed = JSON.parse(await readFile(path.join(paths.jobsDir, name), "utf8")) as unknown; + m = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null; + } catch { + m = null; + } + if (!m || !Array.isArray(m.xSittings)) continue; + for (const raw of m.xSittings) { + const r = raw as { began?: unknown; kind?: unknown; at?: unknown } | null; + if (!r || !isKind(r.kind) || !finite(r.at) || (r.began ?? null) !== began) continue; + recorded.push({ + at: r.at, + jobKind: typeof m.kind === "string" ? m.kind : "?", + kind: r.kind, + ...(typeof m.id === "string" ? { jobId: m.id } : {}), + ...(typeof m.channelSlug === "string" ? { channel: m.channelSlug } : {}), + }); + } + } + recorded.sort((a, b) => a.at - b.at); + // X's job count holds every counted start of the last day: those since the + // refresh are this sitting's whether or not a record says so. + const capStarts = ((await readXJobStarts(paths)) ?? []).filter((t) => t >= since); + const starts = [...recorded]; + for (let i = recorded.length; i < capStarts.length; i++) { + // A start with no record of its kind: counted, of no known kind. + starts.push({ at: capStarts[i], jobKind: "?", kind: recorded[0]?.kind ?? "timelines" }); + } + const kind: SittingFile["kind"] = recorded[0]?.kind ?? (starts.length > 0 ? "unknown" : null); + return { version: 1, began, kind, starts }; +} + +// The sitting in force for a jar refreshed at `refreshedAt`, HOLDING THE +// LOCK: the one on disk, a new one when the jar was refreshed since, or the +// rebuilt one; written when it changed. `bad`: the file cannot be read. +async function loadLocked(paths: SittingPaths, refreshedAt: string | null): Promise<{ ok: true; file: SittingFile } | { ok: false }> { + const read = await readSittingFile(paths); + if (read.state === "bad") return { ok: false }; + if (read.state === "ok") { + if (isLaterRefresh(refreshedAt, read.file.began)) { + const fresh: SittingFile = { version: 1, began: refreshedAt, kind: null, starts: [] }; + await writeSittingFile(paths, fresh); + return { ok: true, file: fresh }; + } + return { ok: true, file: read.file }; + } + const rebuilt = await rebuildXSitting(paths, refreshedAt); + await writeSittingFile(paths, rebuilt); + return { ok: true, file: rebuilt }; +} + +export function xSittingUnreadableSentence(file: string): string { + return ( + `X's sitting cannot be read (${file}): no X job starts while it is unreadable, because the jobs a cookie refresh ` + + "admits are counted there. Repair the file (JSON: {version: 1, began, kind, starts: []}) or delete it (it is then " + + "counted again from the job records), then ask again." + ); +} + +export type XSittingStatus = { + // The file could be read (or rebuilt). + readable: boolean; + state: XSittingState; + limit: number; + used: number; + left: number; + // The refusal, when the file cannot be read. + sentence?: string; +}; + +function statusOf(file: SittingFile, limit: number): XSittingStatus { + const state = stateOf(file); + return { readable: true, state, limit, used: state.used, left: Math.max(0, limit - state.used) }; +} + +function closed(paths: SittingPaths, limit: number, began: string | null): XSittingStatus { + return { + readable: false, + state: { began, kind: "unknown", used: limit }, + limit, + used: limit, + left: 0, + sentence: xSittingUnreadableSentence(xSittingFile(paths)), + }; +} + +// The sitting as it stands for a jar refreshed at `refreshedAt` (a look: +// nothing is counted; a new sitting or a rebuild is written, under the lock). +export async function xSittingStatus(paths: SittingPaths, refreshedAt: string | null, limit: number): Promise<XSittingStatus> { + const read = await readSittingFile(paths); + if (read.state === "bad") return closed(paths, limit, refreshedAt); + if (read.state === "ok" && !isLaterRefresh(refreshedAt, read.file.began)) return statusOf(read.file, limit); + const loaded = await withJsonFileLock(xSittingFile(paths), () => loadLocked(paths, refreshedAt)); + return loaded.ok ? statusOf(loaded.file, limit) : closed(paths, limit, refreshedAt); +} + +// Would a job of `kind` start in the sitting now? (A look.) +export async function xSittingLook( + paths: SittingPaths, + opts: { refreshedAt: string | null; kind: XSittingKind; limit: number }, +): Promise<{ status: XSittingStatus; verdict: XSittingVerdict }> { + const status = await xSittingStatus(paths, opts.refreshedAt, opts.limit); + if (!status.readable) { + return { status, verdict: { ok: false, why: "unknown", used: status.used, left: 0, limit: opts.limit, sentence: status.sentence ?? "" } }; + } + return { status, verdict: xSittingVerdict(status.state, opts.kind, opts.limit) }; +} + +// ONE X JOB STARTS IN THE SITTING: checked and recorded in one step, under +// the file's lock. A refusal records nothing. The first start fixes the +// sitting's kind. +export async function recordXSittingStart( + paths: SittingPaths, + opts: { refreshedAt: string | null; kind: XSittingKind; limit: number; jobKind: string; at: number; jobId?: string; channel?: string }, +): Promise<{ verdict: XSittingVerdict; began: string | null }> { + return withJsonFileLock(xSittingFile(paths), async () => { + const loaded = await loadLocked(paths, opts.refreshedAt); + if (!loaded.ok) { + return { + began: opts.refreshedAt, + verdict: { ok: false, why: "unknown", used: opts.limit, left: 0, limit: opts.limit, sentence: xSittingUnreadableSentence(xSittingFile(paths)) }, + }; + } + const file = loaded.file; + const before = xSittingVerdict(stateOf(file), opts.kind, opts.limit); + if (!before.ok) return { verdict: before, began: file.began }; + const start: XSittingStart = { + at: opts.at, + jobKind: opts.jobKind, + kind: opts.kind, + ...(opts.jobId ? { jobId: opts.jobId } : {}), + ...(opts.channel ? { channel: opts.channel } : {}), + }; + const next: SittingFile = { ...file, kind: file.kind ?? opts.kind, starts: [...file.starts, start] }; + await writeSittingFile(paths, next); + const used = next.starts.length; + return { began: file.began, verdict: { ok: true, used, left: Math.max(0, opts.limit - used), limit: opts.limit } }; + }); +} diff --git a/common/jobs/xSittings.test.ts b/common/jobs/xSittings.test.ts @@ -0,0 +1,681 @@ +// X IN SMALL, UNEVEN SITTINGS (lane x-sittings; lib/xSitting.ts, jobs/xSitting.ts): +// the sitting's count over every kind of X job, through the real job funnel +// (runManagedFunction → the network guard), across an "editor restart", and +// reset by nothing but a later cookie refresh; the one-kind rule; the drawn +// gap; the account marked suspended; the 429 cooldown over every X kind. +// Temp dirs only; no job here asks anything of any site (each job's work is a +// stub that only records that it ran). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/xSittings.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-sittings-")); +process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +delete process.env.E2E_JOB_GAP_SECONDS; +delete process.env.E2E_X_SITTINGS; +delete process.env.E2E_X_MAX_COOKIE_AGE_MINUTES; +delete process.env.E2E_TEST_ROUTES; +// A fake gallery-dl (it asks nothing of anyone): FAKE_GDL=ratelimit prints the +// line gallery-dl prints when it aborts at X's rate limit, and exits 1. +const FAKE_GDL = path.join(ROOT, "fake-gallery-dl.mjs"); +await writeFile( + FAKE_GDL, + `#!/usr/bin/env node +if (process.env.FAKE_GDL === "ratelimit") { process.stderr.write("[twitter][error] Rate limit exceeded\\n"); process.exit(1); } +process.exit(0); +`, +); +const { chmod } = await import("node:fs/promises"); +await chmod(FAKE_GDL, 0o755); +process.env.GALLERY_DL_BIN = FAKE_GDL; + +async function writeSettings(x: Record<string, unknown> = {}): Promise<void> { + await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ social: { x: { cookieSource: "profile", ...x } } })); +} +await writeSettings(); + +const transcripts = path.join(ROOT, "transcripts"); +async function channel(slug: string, extra: Record<string, unknown> = {}): Promise<void> { + const dir = path.join(transcripts, "channels", slug); + await mkdir(dir, { recursive: true }); + await writeFile( + path.join(dir, "config.json"), + JSON.stringify({ handling: "transcribe", sourceKind: "social", postFetcher: "x-gallery-dl", platform: "twitter", name: slug, socialHandle: slug.replace(/-/g, ""), url: `https://x.com/${slug.replace(/-/g, "")}`, ...extra }), + ); +} +const ACCOUNTS = ["acct-one", "acct-two", "acct-three", "acct-four", "acct-five", "acct-six", "acct-seven"]; +for (const s of ACCOUNTS) await channel(s); +await channel("demo-library", { xTrending: {}, url: undefined, postFetcher: undefined }); +await channel("demo-search", { xSearch: { query: "kettles" } }); + +const SESSION = path.join(transcripts, ".x-session"); +const JAR = path.join(SESSION, "cookies.txt"); +// A jar written `ageMs` ago, as an old jar is: its mtime is its time (no +// broker stamp). `refresh` also writes the broker's stamp, as a Refresh does. +async function writeJar(ageMs: number, opts: { refresh?: boolean } = {}): Promise<string> { + await mkdir(path.join(SESSION, "profile"), { recursive: true }); + await writeFile(JAR, "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tv\n"); + const t = new Date(Date.now() - ageMs); + await utimes(JAR, t, t); + if (opts.refresh) await writeFile(path.join(SESSION, "refreshed.json"), JSON.stringify({ version: 1, at: t.toISOString() })); + return t.toISOString(); +} + +const { getPaths } = await import("../lib/paths"); +const { runManagedFunction } = await import("./streamCommand"); +const { setQueueGapClock, clearQueueGaps, noteQueueJobEnd, queueGapWait, queueGapLine, setXGapRandom, xQueueGapRange } = await import("./queueGap"); +const { xJobStartsFile } = await import("./xJobCap"); +const { xSittingFile } = await import("./xSitting"); +const { xSessionReport, guardNetworkJob, xCapRoom, xCapHeldReason } = await import("./networkGuard"); +const { recordPlatformCooldown } = await import("./downloadBackoff"); +const { writeAutoQueueState, readAutoQueueState } = await import("./autoQueueState"); +const { writeXAccountState, xAccountStateFile, keepVerdictsTrustedWhileSuspended } = await import("../social/xAccountState"); +const { readXSessionStatus } = await import("../social/xSessionBroker"); +const { getRegistry } = await import("./registry"); +const { parseXSittingJobs, xSittingJobs, X_SITTING_MAX_JOBS, drawXGapSeconds, xGapRange } = await import("../lib/xSitting"); +const { sanitizeSocial } = await import("../social/xCookieSource"); + +const paths = getPaths(); + +let fakeNow = Date.now(); +setQueueGapClock({ now: () => fakeNow, sleep: async (ms) => { fakeNow += ms; } }); + +async function reset(): Promise<void> { + clearQueueGaps(); + // X's queue gap: a known end long ago (a lost file is answered from the + // job records — review 1 F7 — whose clock is the wall's, not this test's). + await mkdir(paths.jobsDir, { recursive: true }); + await writeFile(path.join(paths.jobsDir, "queue-gaps.json"), JSON.stringify({ version: 1, ends: { "platform:twitter": 1 } })); + await mkdir(path.dirname(xJobStartsFile(paths)), { recursive: true }); + await writeFile(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [] })); + await rm(xSittingFile(paths), { force: true }); + await rm(xAccountStateFile(paths), { force: true }); + await rm(path.join(SESSION, "refreshed.json"), { force: true }); + // No cooldown on record. + const st = await readAutoQueueState(paths); + st.download.platformBackoff = {}; + st.download.platformHolds = {}; + await writeAutoQueueState(paths, st); + await writeSettings(); +} + +// One X job through the funnel, its work a stub. Answers how it ended. +async function xJob(kind: string, slug: string | undefined, params?: Record<string, unknown>): Promise<{ queued: boolean; error?: string; status?: string; deferred?: { until: number; sentence: string }; ran: boolean; log?: string }> { + let ran = false; + const res = await runManagedFunction({ + kind, + queueKey: "platform:twitter", + paths, + ...(slug ? { channelSlug: slug } : {}), + ...(params ? { spec: { kind, slug: slug ?? "x", params } } : {}), + fn: async () => { + ran = true; + fakeNow += 2_000; + }, + } as Parameters<typeof runManagedFunction>[0]); + if (!res.ok) return { queued: false, error: res.error, ran }; + const status = (await res.done).status; + const rec = getRegistry().get(res.jobId); + const log = await readFile(path.join(paths.jobsDir, `${res.jobId}.log`), "utf8").catch(() => ""); + return { queued: true, status, ran, log, ...(rec?.deferred ? { deferred: rec.deferred } : {}) }; +} + +test("N: a sitting admits 4 X job starts by default; the setting is bounded 1-6 in the code", () => { + assert.equal(xSittingJobs(undefined), 4); + assert.equal(xSittingJobs({ sittingJobs: 2 }), 2); + assert.equal(xSittingJobs({ sittingJobs: 60 }), X_SITTING_MAX_JOBS); + assert.equal(xSittingJobs({ sittingJobs: 0 }), 1); + assert.equal(parseXSittingJobs("4"), undefined); + assert.equal(parseXSittingJobs(9.7), 6); + assert.deepEqual(sanitizeSocial({ x: { sittingJobs: 99, gapMinMinutes: 1, gapMaxMinutes: 600 } }).x, { sittingJobs: 6, gapMinMinutes: 5, gapMaxMinutes: 120 }); + assert.deepEqual(sanitizeSocial({ x: { sittingJobs: "lots" } }).x, {}); +}); + +test("the 5th X start after a refresh is refused — over every kind of timelines job together — and ends deferred, not failed", async () => { + await reset(); + await writeJar(2 * 60_000, { refresh: true }); + const ends = [ + await xJob("fetch-posts", ACCOUNTS[0]), + await xJob("capture-posts", ACCOUNTS[1], { ids: ["1"], shots: true }), + await xJob("check-post-availability", ACCOUNTS[2]), + await xJob("import-post", ACCOUNTS[3]), + ]; + for (const e of ends) { + assert.equal(e.queued, true, e.error); + assert.equal(e.status, "done"); + assert.equal(e.ran, true); + } + // Each job's log says where the sitting stands. + assert.match(ends[0].log ?? "", /X sitting: 1 of 4 started \(timelines, since the refresh at \d\d:\d\d UTC\); 3 left\./); + assert.match(ends[3].log ?? "", /X sitting: 4 of 4 started .*; 0 left\./); + // The 5th: refused at enqueue (no job), with the sentence. + const fifth = await xJob("fetch-posts", ACCOUNTS[4]); + assert.equal(fifth.queued, false); + assert.equal(fifth.ran, false); + assert.match(fifth.error ?? "", /^This X sitting is used up: 4 of 4 X jobs started since the cookies were refreshed at \d\d:\d\d UTC \(social\.x\.sittingJobs, at most 6\)\. A new Refresh cookies on \/cookies starts the next sitting; nothing queues or retries by itself\.$/); + // get x-session shows it: used, left, kind, when it began. + const report = await xSessionReport({ paths }); + assert.equal(report.allowed, false); + assert.equal(report.refusedBy, "sitting"); + assert.deepEqual({ ...report.sitting, began: typeof report.sitting.began }, { began: "string", kind: "timelines", used: 4, left: 0, limit: 4 }); + // A job queued while there was room, started after it is gone: done, DEFERRED (until a Refresh), never run. + await writeFile(xSittingFile(paths), JSON.stringify({ ...JSON.parse(await readFile(xSittingFile(paths), "utf8")), starts: JSON.parse(await readFile(xSittingFile(paths), "utf8")).starts.slice(0, 3) })); + let ran = false; + let release!: () => void; + const blocker = new Promise<void>((r) => (release = r)); + // Hold X's queue with one job so the next one queues while the sitting has room. + const hold = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: ACCOUNTS[4], fn: async () => { await blocker; } }); + assert.equal(hold.ok, true); + const late = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: ACCOUNTS[5], fn: async () => { ran = true; } }); + assert.equal(late.ok, true, late.ok ? "" : late.error); + release(); + if (hold.ok) await hold.done; + if (late.ok) { + assert.equal((await late.done).status, "done"); + const rec = getRegistry().get(late.jobId); + assert.equal(rec?.deferred?.until, 0); + assert.match(rec?.deferred?.sentence ?? "", /^This X sitting is used up: 4 of 4/); + } + assert.equal(ran, false); +}); + +test("ONE KIND PER SITTING: the first job fixes it; a job of the other kind is refused until the next refresh", async () => { + await reset(); + await writeJar(60_000, { refresh: true }); + const read = await xJob("read-x-trending", "demo-library"); + assert.equal(read.status, "done", read.error); + // A search channel's walk and a library's capture are browse too. + assert.equal((await xJob("fetch-posts", "demo-search")).status, "done"); + assert.equal((await xJob("capture-posts", "demo-library", { ids: ["9"], shots: true })).status, "done"); + // A timeline fetch: refused, saying why. + const timeline = await xJob("fetch-posts", ACCOUNTS[0]); + assert.equal(timeline.queued, false); + assert.match(timeline.error ?? "", /^This X sitting is a browse sitting \(its first job, read-x-trending at \d\d:\d\d UTC, fixed it\): a timelines job does not start in it/); + assert.equal((await xSessionReport({ paths })).sitting.kind, "browse"); + // A later refresh begins a new sitting, of either kind. + await writeJar(0, { refresh: true }); + const after = await xJob("fetch-posts", ACCOUNTS[0]); + assert.equal(after.status, "done", after.error); + const r = await xSessionReport({ paths }); + assert.deepEqual([r.sitting.kind, r.sitting.used], ["timelines", 1]); +}); + +test("the sitting survives an editor restart and is reset by nothing but a LATER refresh", async () => { + await reset(); + const refreshed = await writeJar(5 * 60_000, { refresh: true }); + for (const s of ACCOUNTS.slice(0, 3)) assert.equal((await xJob("fetch-posts", s)).status, "done"); + // A restart: every in-memory store is gone; the file is not. + clearQueueGaps(); + assert.equal((await xSessionReport({ paths })).sitting.used, 3); + // gallery-dl (or anything) rewriting the jar moves its mtime, not the refresh. + const t = new Date(); + await utimes(JAR, t, t); + assert.equal((await readXSessionStatus(paths)).cookiesUpdatedAt, refreshed); + assert.equal((await xSessionReport({ paths })).sitting.used, 3); + // A jar restored from an older refresh continues the sitting on record. + await writeFile(path.join(SESSION, "refreshed.json"), JSON.stringify({ version: 1, at: new Date(Date.parse(refreshed) - 3600_000).toISOString() })); + assert.equal((await xSessionReport({ paths })).sitting.used, 3); + await writeFile(path.join(SESSION, "refreshed.json"), JSON.stringify({ version: 1, at: refreshed })); + // The sitting file deleted: rebuilt from the records and X's job count, kind and all. + await rm(xSittingFile(paths)); + const rebuilt = await xSessionReport({ paths }); + assert.deepEqual([rebuilt.sitting.used, rebuilt.sitting.kind], [3, "timelines"]); + // Deleted, with the records' kinds gone too: counted from X's job count, kind unknown — both kinds refused. + await rm(xSittingFile(paths)); + for (const id of getRegistry().list().map((r) => r.id)) { + const meta = path.join(paths.jobsDir, `${id}.meta.json`); + const m = JSON.parse(await readFile(meta, "utf8").catch(() => "{}")); + if (m.xSittings) { + delete m.xSittings; + await writeFile(meta, JSON.stringify(m)); + } + } + const unknown = await xSessionReport({ paths, sittingKind: "timelines" }); + assert.equal(unknown.sitting.kind, "unknown"); + assert.equal(unknown.allowed, false); + assert.match(unknown.reason ?? "", /^This X sitting's kind cannot be told/); + // An unreadable file: every counted X job is refused. + await writeFile(xSittingFile(paths), "{ not json"); + const bad = await xJob("fetch-posts", ACCOUNTS[3]); + assert.equal(bad.queued, false); + assert.match(bad.error ?? "", /^X's sitting cannot be read/); + // Only a later refresh begins a new one (stamped on the jobs' clock, which ran ahead of the wall's here). + await writeFile(xSittingFile(paths), JSON.stringify({ version: 1, began: refreshed, kind: "timelines", starts: [] })); + await writeFile(path.join(SESSION, "refreshed.json"), JSON.stringify({ version: 1, at: new Date(fakeNow + 1000).toISOString() })); + const fresh = await xSessionReport({ paths }); + assert.deepEqual([fresh.sitting.used, fresh.sitting.kind], [0, null]); +}); + +test("N is the setting, bounded: sittingJobs 2 refuses the 3rd; 50 admits 6 and refuses the 7th", async () => { + await reset(); + await writeSettings({ sittingJobs: 2 }); + await writeJar(60_000, { refresh: true }); + assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); + assert.equal((await xJob("fetch-posts", ACCOUNTS[1])).status, "done"); + assert.match((await xJob("fetch-posts", ACCOUNTS[2])).error ?? "", /used up: 2 of 2/); + await writeSettings({ sittingJobs: 50 }); + await writeJar(0, { refresh: true }); + // Out of the hourly cap's way: the first part's starts are forgotten. + await writeFile(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [] })); + for (const s of ACCOUNTS.slice(0, 6)) { + const e = await xJob("fetch-posts", s); + assert.equal(e.status, "done", e.error); + fakeNow += 11 * 60_000; // out of the hourly cap's way + } + assert.match((await xJob("fetch-posts", ACCOUNTS[6])).error ?? "", /used up: 6 of 6/); +}); + +test("UNEVEN GAPS: X's gap is drawn per job within 5-12 min, never below 5, logged with its draw; seeded only in a test", async () => { + // The pure draw: the bounds, always. + const range = xGapRange(undefined); + assert.deepEqual(range, { minSeconds: 300, maxSeconds: 720 }); + assert.equal(drawXGapSeconds(range, 0), 300); + assert.equal(drawXGapSeconds(range, 0.999999), 720); + for (let i = 0; i < 200; i++) { + const s = drawXGapSeconds(range, Math.random()); + assert.ok(s >= 300 && s <= 720, String(s)); + } + // The floor holds against any setting; an explicit jobGapSeconds.twitter above it raises the minimum, never lowers it. + // …and the range is never one value (review 1 F4): at least 3 minutes wide, whatever is set. + assert.deepEqual(xGapRange({ gapMinMinutes: 1, gapMaxMinutes: 2 }), { minSeconds: 300, maxSeconds: 480 }); + assert.deepEqual(xGapRange({ gapMinMinutes: 6, gapMaxMinutes: 9 }), { minSeconds: 360, maxSeconds: 540 }); + assert.deepEqual(xGapRange({ gapMinMinutes: 8, gapMaxMinutes: 8 }), { minSeconds: 480, maxSeconds: 660 }); + assert.deepEqual(xGapRange(undefined, 900), { minSeconds: 900, maxSeconds: 1080 }); + assert.deepEqual(xGapRange(undefined, 0), { minSeconds: 300, maxSeconds: 720 }); + assert.deepEqual(xQueueGapRange({ jobGapSeconds: { twitter: 30 } }, undefined), { minSeconds: 300, maxSeconds: 720 }); + + // The wait: drawn once per end, kept across re-reads, seeded draws repeat. + clearQueueGaps(); + setXGapRandom(42); + const end = fakeNow; + await noteQueueJobEnd(paths, "platform:twitter", end); + const w1 = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: end + 1000, xGap: {} }); + const w2 = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: end + 60_000, xGap: {} }); + assert.ok(w1 && w2); + assert.equal(w1!.until, w2!.until, "a re-read keeps the draw"); + assert.ok(w1!.drawn!.seconds >= 300 && w1!.drawn!.seconds <= 720); + assert.match(queueGapLine(w1!), /^waiting \d+m\d\ds \(a \d+m\d\ds gap drawn from 5-12 min\): X jobs are spaced 5-12 min apart, drawn per job/); + clearQueueGaps(); + setXGapRandom(42); + await noteQueueJobEnd(paths, "platform:twitter", end); + const again = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: end + 1000, xGap: {} }); + assert.equal(again!.drawn!.seconds, w1!.drawn!.seconds, "the same seed, the same draw"); + // Different ends draw differently (not one fixed beat): over 30 ends, more than one value. + const draws = new Set<number>(); + for (let i = 0; i < 30; i++) { + await noteQueueJobEnd(paths, "platform:twitter", end + (i + 1) * 3_600_000); + const w = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: end + (i + 1) * 3_600_000 + 1, xGap: {} }); + draws.add(w!.drawn!.seconds); + } + assert.ok(draws.size > 5, `${draws.size} distinct draws`); + setXGapRandom(null); + clearQueueGaps(); + + // Through the funnel: two X jobs, the second starts 5-12 min after the first ended, and its log says the draw. + await reset(); + await writeJar(60_000, { refresh: true }); + const first = await xJob("fetch-posts", ACCOUNTS[0]); + const t1 = fakeNow; + const second = await xJob("fetch-posts", ACCOUNTS[1]); + assert.equal(second.status, "done", second.error); + assert.match(second.log ?? "", /waiting \d+m\d\ds \(a \d+m\d\ds gap drawn from 5-12 min\)/); + const waited = fakeNow - 2_000 - t1; + assert.ok(waited >= 300_000 && waited <= 720_000, `${waited} ms`); + assert.equal(first.status, "done"); +}); + +test("SUSPENDED: marked by hand, it refuses availability checks and captures that record deleted posts; other X jobs log it", async () => { + await reset(); + await writeJar(60_000, { refresh: true }); + await writeXAccountState(paths, "suspended", { note: "read-only since the 21st" }); + const report = await xSessionReport({ paths }); + assert.equal(report.account.state, "suspended"); + assert.match(report.account.alert ?? "", /^The X account is marked suspended \(since .* UTC: read-only since the 21st\)/); + for (const [kind, params] of [ + ["check-post-availability", undefined], + ["capture-posts", { ids: ["1"] }], + ["capture-posts", { ids: ["1"], shots: true }], + ] as const) { + const e = await xJob(kind, ACCOUNTS[0], params); + assert.equal(e.queued, false, kind); + assert.match(e.error ?? "", /^The X account is marked suspended .*is refused, because a suspended account's answers are thinned/, kind); + } + // A capture with its screenshots AND its articles off reads no page's verdict: it runs (review 1 F5). + assert.equal((await xJob("capture-posts", ACCOUNTS[0], { ids: ["1"], shots: false, articles: false })).status, "done"); + // A fetch runs, and its log says the account is suspended. + const fetch = await xJob("fetch-posts", ACCOUNTS[1]); + assert.equal(fetch.status, "done"); + assert.match(fetch.log ?? "", /The X account is marked suspended .* What X answers it may be thinned\./); + // The last line before a verdict is written (a mark made while a job ran): only "available" is kept. + const lines: string[] = []; + const kept = await keepVerdictsTrustedWhileSuspended(paths, new Map([["1", "deleted"], ["2", "available"], ["3", "account_unavailable"]]), (l) => lines.push(l)); + assert.deepEqual([...kept], [["2", "available"]]); + assert.match(lines.join("\n"), /2 "deleted" or "unavailable" verdict\(s\) from its answers were NOT recorded/); + // Marked ok: the check runs again. + await writeXAccountState(paths, "ok"); + assert.equal((await xJob("check-post-availability", ACCOUNTS[2])).status, "done"); + const all = new Map([["1", "deleted"]]); + assert.equal(await keepVerdictsTrustedWhileSuspended(paths, all, () => {}), all); + // An unreadable state file is taken as suspended. + await writeFile(xAccountStateFile(paths), "nope"); + assert.match((await xJob("check-post-availability", ACCOUNTS[3])).error ?? "", /marked suspended/); +}); + +test("A 429 STOPS EVERY X JOB FOR 15 MINUTES: fetch, capture, availability check, import, X run channel, trending read, search walk", async () => { + await reset(); + await writeJar(60_000, { refresh: true }); + await recordPlatformCooldown("twitter", 15 * 60_000, paths); + for (const [kind, slug] of [ + ["fetch-posts", ACCOUNTS[0]], + ["sync", ACCOUNTS[0]], + ["capture-posts", ACCOUNTS[1]], + ["check-post-availability", ACCOUNTS[2]], + ["import-post", ACCOUNTS[3]], + ["read-x-trending", "demo-library"], + ["fetch-posts", "demo-search"], + ] as const) { + const e = await xJob(kind, slug); + assert.equal(e.queued, false, kind); + assert.match(e.error ?? "", /^X answered a rate limit \(429\) a short while ago: no X job starts before \d\d:\d\d UTC \(1[45] min from now\)/, kind); + } + // Each channel of an X run is guarded the same way. + const runGuard = await guardNetworkJob({ kind: "x-run", queueKey: "platform:twitter", paths, channelSlug: ACCOUNTS[4], job: { id: "01JXRUN0000000000000000000" }, countStart: true }); + assert.equal(runGuard.ok, false); + // Nothing was counted against the sitting or the cap. + const r = await xSessionReport({ paths }); + assert.equal(r.sitting.used, 0); + assert.equal(r.cap.lastHour, 0); + assert.equal(r.refusedBy, "cooldown"); + assert.ok(r.cooldown && Date.parse(r.cooldown.until) > Date.now() + 14 * 60_000); + // Once it has passed, X jobs start again. + const st = await readAutoQueueState(paths); + st.download.platformBackoff = {}; + await writeAutoQueueState(paths, st); + assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); +}); + +test("the scheduler queues no more X syncs than the sitting has left, and none into a browse sitting", async () => { + await reset(); + await writeJar(60_000, { refresh: true }); + assert.equal(await xCapRoom(paths, fakeNow), 4); + assert.equal(await xCapHeldReason(paths, fakeNow), null); + assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); + assert.equal(await xCapRoom(paths, fakeNow), 3); + // A browse sitting has no room for a timeline sync. + await writeJar(0, { refresh: true }); + assert.equal((await xJob("read-x-trending", "demo-library")).status, "done"); + assert.equal(await xCapRoom(paths, fakeNow), 0); + assert.match((await xCapHeldReason(paths, fakeNow)) ?? "", /^This X sitting is a browse sitting/); + // Used up: the sentence says so. + await writeFile(xSittingFile(paths), JSON.stringify({ version: 1, began: JSON.parse(await readFile(xSittingFile(paths), "utf8")).began, kind: "timelines", starts: [1, 2, 3, 4].map((i) => ({ at: fakeNow - i, jobKind: "fetch-posts", kind: "timelines" })) })); + assert.equal(await xCapRoom(paths, fakeNow), 0); + assert.match((await xCapHeldReason(paths, fakeNow)) ?? "", /^This X sitting is used up: 4 of 4/); +}); + +// ── review 1 ─────────────────────────────────────────────────────────────── + +const { applyXStop, X_STOP_MS } = await import("./platformBackoff"); +const { recordDownloadBackoff, recordXStop, xStopRemainingMs } = await import("./downloadBackoff"); +const { downloadXPostMedia } = await import("../social/xGalleryDlFetcher"); +const { clearXSession } = await import("../social/xSessionBroker"); +const { runInJobContext } = await import("../lib/jobContext"); +const { writePostCapture, readPostCapture } = await import("../social/postCapture"); +const { writeDownloadOutcome, loadDownloadOutcome } = await import("../lib/downloadOutcome-server"); +const { recordAvailability } = await import("../lib/availability-server"); +const { xSuspendedRefuses } = await import("../lib/xSitting"); +const { X_RATE_LIMIT_HOLD_MS } = await import("../lib/xJobRule"); + +test("F1: a 429 from ANY X reader is the same 15-minute X stop — yt-dlp on an X address, a named cooldown, a post's media download — never the 60 s backoff", async () => { + assert.equal(X_STOP_MS, X_RATE_LIMIT_HOLD_MS); + assert.equal(X_STOP_MS, 15 * 60_000); + const left = async () => Math.round((await xStopRemainingMs(paths)) / 60_000); + // yt-dlp on an X window / import / download (recordDownloadBackoff is what they call). + await reset(); + await recordDownloadBackoff("twitter", paths, "rate_limit"); + assert.equal(await left(), 15); + // Any caller that names its own length for X gets the X stop. + await reset(); + const { recordPlatformCooldown } = await import("./downloadBackoff"); + await recordPlatformCooldown("twitter", 60_000, paths); + assert.equal(await left(), 15); + // The auto-download lane's unit (pure, on the live state): the X stop too. + const st = { platformBackoff: {} as Record<string, { until: number; fails: number }> }; + const e = applyXStop(st, 1_000); + assert.equal(e.until, 1_000 + 15 * 60_000); + // gallery-dl's media download of one post: its rate-limit line is the X stop, and the capture is told to stop. + await reset(); + process.env.FAKE_GDL = "ratelimit"; + try { + const dir = path.join(ROOT, "media-1"); + await mkdir(dir, { recursive: true }); + const got = await downloadXPostMedia({ id: "123", dir, login: {}, signal: new AbortController().signal }); + assert.equal(got.ok, false); + assert.match(got.ok ? "" : (got.stop ?? ""), /rate limit/); + } finally { + delete process.env.FAKE_GDL; + } + assert.equal(await left(), 15); + // And then every X job is refused. + await writeJar(60_000, { refresh: true }); + assert.match((await xJob("fetch-posts", ACCOUNTS[0])).error ?? "", /^X answered a rate limit \(429\)/); + // A generic platform keeps its own backoff. + await reset(); + await recordDownloadBackoff("odysee", paths, "rate_limit"); + const od = (await readAutoQueueState(paths)).download.platformBackoff.odysee; + assert.ok(od && od.until - Date.now() < 5 * 60_000, "odysee's first step is short"); +}); + +test("F2: a job that meets the X stop ends DEFERRED at once, saying so, with what it read kept", async () => { + await reset(); + await writeJar(60_000, { refresh: true }); + const e = await (async () => { + let ran = false; + const res = await runManagedFunction({ + kind: "fetch-posts", + queueKey: "platform:twitter", + paths, + channelSlug: ACCOUNTS[0], + fn: async () => { + ran = true; + await recordXStop("a rate limit (gallery-dl)", paths); + throw new Error("gallery-dl exited 1"); + }, + }); + assert.ok(res.ok); + const done = await res.done; + return { ran, done, rec: getRegistry().get(res.jobId), log: await readFile(path.join(paths.jobsDir, `${res.jobId}.log`), "utf8") }; + })(); + assert.equal(e.ran, true); + assert.equal(e.done.status, "done"); + assert.ok(e.rec?.deferred); + assert.match(e.rec!.deferred!.sentence, /^X answered a rate limit \(gallery-dl\) at \d\d:\d\d UTC: this job stopped there and kept what it read; no X job starts before/); + assert.ok(e.rec!.deferred!.until > Date.now() + 14 * 60_000); + assert.match(e.log, /X answered a rate limit \(gallery-dl\): X is left alone until \d\d:\d\d UTC \(15 minutes\); this job stops here\./); + assert.doesNotMatch(e.log, /^\[error\]/m); +}); + +test("F3: Clear session forgets the login only — the suspended mark, the sitting, X's count and the 429 stop stay", async () => { + await reset(); + await writeJar(60_000, { refresh: true }); + assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); + await writeXAccountState(paths, "suspended", { note: "kept across a clear" }); + await recordXStop("a rate limit", paths); + await clearXSession(paths); + const { existsSync } = await import("node:fs"); + assert.equal(existsSync(JAR), false); + assert.equal(existsSync(path.join(SESSION, "profile")), false); + assert.equal(existsSync(path.join(SESSION, "refreshed.json")), false); + assert.equal(existsSync(xAccountStateFile(paths)), true); + assert.equal(existsSync(xSittingFile(paths)), true); + assert.equal(existsSync(xJobStartsFile(paths)), true); + const r = await xSessionReport({ paths }); + assert.equal(r.account.state, "suspended"); + assert.equal(r.sitting.used, 1); + assert.ok(r.cooldown); +}); + +test("F4: an explicit pacing.jobGapSeconds.twitter of 900 still draws unevenly — never one fixed beat", async () => { + const range = xQueueGapRange({ jobGapSeconds: { twitter: 900 } }, { gapMinMinutes: 5, gapMaxMinutes: 5 }); + assert.deepEqual(range, { minSeconds: 900, maxSeconds: 1080 }); + const draws = new Set<number>(); + for (let i = 0; i < 50; i++) draws.add(drawXGapSeconds(range, i / 50)); + assert.ok(draws.size > 20, `${draws.size} distinct gaps`); + for (const d of draws) assert.ok(d >= 900 && d <= 1080); +}); + +test("F5: while suspended nothing records a post or a video as gone from X's answer — captures with articles, video checks, outcomes, availability, capture records", async () => { + // The guard: a capture with its shots off but its articles on, and the video checks. + assert.equal(xSuspendedRefuses({ kind: "capture-posts", params: { shots: false, articles: true } }), true); + assert.equal(xSuspendedRefuses({ kind: "capture-posts", params: { shots: false } }), true); + assert.equal(xSuspendedRefuses({ kind: "capture-posts", params: { shots: false, articles: false } }), false); + for (const kind of ["check-availability", "quick-availability-check", "check-maybe-missing", "check-kept-deleted"]) { + assert.equal(xSuspendedRefuses({ kind }), true, kind); + } + await reset(); + await writeJar(60_000, { refresh: true }); + await writeXAccountState(paths, "suspended"); + assert.match((await xJob("capture-posts", ACCOUNTS[0], { ids: ["1"], shots: false, articles: true })).error ?? "", /marked suspended/); + assert.match((await xJob("check-availability", ACCOUNTS[0])).error ?? "", /marked suspended/); + // The writers, inside an X job (its context carries the mark). + const ctx = { jobId: "j", kind: "fetch-window", queueKey: "platform:twitter", onLog: () => {}, staleServices: new Set<string>(), xSuspended: async () => true }; + const dir = path.join(ROOT, "writers"); + await mkdir(dir, { recursive: true }); + await runInJobContext(ctx, async () => { + await writePostCapture(dir, { version: 1, id: "9", url: "https://x.com/i/status/9", capturedAt: "2026-11-21T00:00:00.000Z", state: "deleted", mediaState: "skipped", media: [] } as never); + await writeDownloadOutcome(dir, { status: "failed", videoId: "v", startedAt: "a", finishedAt: "b", attempts: [{ n: 1, kind: "full", handling: "transcribe", usedCookies: false, ytdlpExitCode: 1, availabilityClass: "deleted" }] } as never); + await recordAvailability(dir, { availability: "deleted", observedAt: "2026-11-21T00:00:00.000Z", source: "download" }); + }); + assert.equal((await readPostCapture(dir))!.state, "error"); + assert.equal((await loadDownloadOutcome(dir))!.attempts[0].availabilityClass, undefined); + const { existsSync } = await import("node:fs"); + assert.equal(existsSync(path.join(dir, "availability.json")), false, "no availability recorded"); + // Not suspended: written as said. + await runInJobContext({ ...ctx, xSuspended: async () => false }, () => + writePostCapture(dir, { version: 1, id: "9", url: "u", capturedAt: "c", state: "deleted", mediaState: "skipped", media: [] } as never), + ); + assert.equal((await readPostCapture(dir))!.state, "deleted"); +}); + +test("F6: in a production-shaped environment the e2e hooks are ignored — the gap, the sittings and the jar rule all hold", async () => { + await reset(); + process.env.E2E_JOB_GAP_SECONDS = "0"; + process.env.E2E_X_SITTINGS = "off"; + process.env.E2E_X_MAX_COOKIE_AGE_MINUTES = "0"; + delete process.env.E2E_TEST_ROUTES; + try { + assert.deepEqual(xQueueGapRange(undefined, undefined), { minSeconds: 300, maxSeconds: 720 }); + await writeJar(3 * 3600_000, { refresh: true }); + assert.match((await xSessionReport({ paths })).reason ?? "", /^X cookies were last refreshed 3 h ago/); + await writeSettings({ sittingJobs: 1 }); + await writeJar(60_000, { refresh: true }); + assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); + assert.match((await xJob("fetch-posts", ACCOUNTS[1])).error ?? "", /used up: 1 of 1/); + // The test server's gate opens them. + process.env.E2E_TEST_ROUTES = "1"; + assert.deepEqual(xQueueGapRange(undefined, undefined), { minSeconds: 0, maxSeconds: 0 }); + assert.equal((await xSessionReport({ paths })).allowed, true); + } finally { + delete process.env.E2E_JOB_GAP_SECONDS; + delete process.env.E2E_X_SITTINGS; + delete process.env.E2E_X_MAX_COOKIE_AGE_MINUTES; + delete process.env.E2E_TEST_ROUTES; + } +}); + +test("F7a: the three reads fail closed — an unreadable stop file, an unreadable refresh stamp, a lost queue-gaps.json", async () => { + await reset(); + await writeJar(60_000, { refresh: true }); + // 1. The stop cannot be read: every X job is refused. + const { writeFile: wf } = await import("node:fs/promises"); + await wf(paths.autoQueueStateFile, "{ broken"); + assert.match((await xJob("fetch-posts", ACCOUNTS[0])).error ?? "", /^X's rate-limit stop cannot be read/); + await reset(); + // 2. A stamp that is there and unreadable: the jar reads as never refreshed. + await writeJar(60_000, { refresh: true }); + await wf(path.join(SESSION, "refreshed.json"), "nope"); + assert.equal((await readXSessionStatus(paths)).cookiesUpdatedAt, new Date(0).toISOString()); + assert.equal((await xSessionReport({ paths })).allowed, false); + // 3. queue-gaps.json lost after X jobs ran: the next waits a gap from the records. + await reset(); + await writeJar(60_000, { refresh: true }); + assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); + clearQueueGaps(); + await rm(path.join(paths.jobsDir, "queue-gaps.json"), { force: true }); + const w = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: Date.now(), xGap: {} }); + assert.ok(w && w.remainingMs > 200_000, "a gap is waited from the last X job on record"); +}); + +test("F8: one X walk reads at most social.x.maxPostsPerJob posts (300; 20-400 in code)", async () => { + const { xJobPostLimit, X_POSTS_PER_JOB_CEILING } = await import("../lib/xSitting"); + assert.equal(xJobPostLimit(undefined), 300); + assert.equal(xJobPostLimit(undefined, 200), 200); + assert.equal(xJobPostLimit(undefined, 900), 300); + assert.equal(xJobPostLimit({ maxPostsPerJob: 5000 }), X_POSTS_PER_JOB_CEILING); + assert.equal(xJobPostLimit({ maxPostsPerJob: 1 }), 20); + assert.deepEqual(sanitizeSocial({ x: { maxPostsPerJob: 9999 } }).x, { maxPostsPerJob: 400 }); +}); + +test("F1: the auto-download lane's X unit that met a rate limit sets the 15-minute X stop, not the backoff's first step", async () => { + const { applyUnitOutcome } = await import("./unitOutcome"); + const state = { platformBackoff: {}, videoDeferrals: {}, platformPace: {}, platformHolds: {}, subtitleDeferrals: {} } as Parameters<typeof applyUnitOutcome>[0]; + const fx = applyUnitOutcome(state, { platform: "twitter", videoId: "v1", channelSlug: ACCOUNTS[0], outcome: "failed", failureClass: "rate_limit" }, 10_000); + assert.equal(state.platformBackoff.twitter.until, 10_000 + 15 * 60_000); + assert.deepEqual(state.platformHolds, {}, "no hold"); + assert.match(fx.line ?? "", /X answered a rate limit — X is left alone until/); +}); + +test("review 2 G3: a capture takes at most social.x.maxPostsPerJob posts (the rest owed); a trending read's tabs share the setting", async () => { + const { capturePosts } = await import("../controller/capturePosts"); + const { xTrendingPostsPerTab } = await import("../controller/readXTrending"); + const { getSettings } = await import("../lib/settings"); + await reset(); + await writeSettings({ maxPostsPerJob: 50 }); + const ids = Array.from({ length: 51 }, (_, i) => String(1000 + i)); + const log: string[] = []; + const ctx = { jobId: "g3", kind: "capture-posts", queueKey: "platform:twitter", onLog: () => {}, staleServices: new Set<string>() }; + await runInJobContext(ctx, () => capturePosts({ paths, slug: ACCOUNTS[0], settings: getSettings(), ids, onLog: (l) => log.push(l) })); + assert.ok(log.some((l) => /^This X capture takes the first 50 of 51 posts \(social\.x\.maxPostsPerJob\); the other 1 are left for a later job, from 1050\.$/.test(l)), log.join("\n")); + // The trending read: the setting over its tabs, never past what was asked. + assert.equal(xTrendingPostsPerTab(200, 2, undefined), 150); + assert.equal(xTrendingPostsPerTab(200, 2, { maxPostsPerJob: 20 }), 10); + assert.equal(xTrendingPostsPerTab(200, 1, { maxPostsPerJob: 9999 }), 200); + assert.equal(xTrendingPostsPerTab(400, 1, { maxPostsPerJob: 9999 }), 400); + await writeSettings(); +}); + +test("review 2 G4: nothing ends the X stop before its time — not a clean answer, not Clear hold — but 'Clear the X stop', confirmed and logged", async () => { + const { recordPlatformClean, clearPlatformHold, clearXStop } = await import("./downloadBackoff"); + const { settlePlatformClean } = await import("./platformBackoff"); + const left = async () => Math.round((await xStopRemainingMs(paths)) / 60_000); + await reset(); + await recordXStop("a rate limit", paths); + // A clean answer from another reader (a window fetch, a sync) and the lane page's Clear hold. + await recordPlatformClean("twitter", paths); + assert.equal(await left(), 15); + await clearPlatformHold("twitter", paths); + assert.equal(await left(), 15); + // The pure settle, too. + const st = { platformBackoff: { twitter: { until: Date.now() + 600_000, fails: 1 } }, platformHolds: {}, platformPace: {} } as never; + settlePlatformClean(st, "twitter", { baseSeconds: 1 }); + assert.ok((st as { platformBackoff: Record<string, unknown> }).platformBackoff.twitter); + // The operator's act: unconfirmed, it clears nothing and says what it risks. + const asked = await clearXStop(paths, { confirm: false, by: "test" }); + assert.equal(asked.ok, false); + assert.match(asked.message, /^Clearing the X stop lets the next X job ask X at once, inside the 15 minutes/); + assert.equal(await left(), 15); + const done = await clearXStop(paths, { confirm: true, by: "test", note: "checked" }); + assert.equal(done.ok, true); + assert.equal(await left(), 0); + const logged = (await readFile(path.join(paths.jobsDir, "x-stop-cleared.jsonl"), "utf8")).trim().split("\n").map((l) => JSON.parse(l)); + assert.deepEqual([logged.at(-1).by, logged.at(-1).note], ["test", "checked"]); + // An ended stop is pruned as before (a clean answer clears an expired entry). + const expired = { platformBackoff: { twitter: { until: Date.now() - 1, fails: 1 } }, platformHolds: {}, platformPace: {} } as never; + settlePlatformClean(expired, "twitter", { baseSeconds: 1 }); + assert.equal((expired as { platformBackoff: Record<string, unknown> }).platformBackoff.twitter, undefined); +}); diff --git a/common/lib/availability-server.ts b/common/lib/availability-server.ts @@ -1,3 +1,4 @@ +import { xAnswersUntrusted } from "./jobContext"; import { AVAILABILITY_FILENAME, AVAILABILITY_VALUES, @@ -54,6 +55,9 @@ export async function recordAvailability( }, opts?: { updateTopLevel?: boolean }, ): Promise<void> { + // Inside an X job whose account is marked suspended, no "gone" verdict from + // X's answer is recorded (review 1 F5). + if (obs.availability !== "public" && obs.availability !== "unlisted" && (await xAnswersUntrusted())) return; const updateTopLevel = opts?.updateTopLevel !== false; const existing = await loadAvailability(videoDir); diff --git a/common/lib/cookieStatus.ts b/common/lib/cookieStatus.ts @@ -63,7 +63,22 @@ export type CookieRow = { export type CookieRunning = { action: CookieRowButton["action"]; since: string; jobId?: string }; -export type CookieStatusPayload = { readAt: string; rows: CookieRow[] }; +// X'S SITTING AND ACCOUNT (lane x-sittings), for the X row's panel: the +// sitting since the last refresh (jobs/xSitting.ts) and the account's state +// as the operator marked it (social/xAccountState.ts). +export type XSittingView = { + began: string | null; + kind: "timelines" | "browse" | "unknown" | null; + used: number; + left: number; + limit: number; + unreadable?: true; + account: { state: "ok" | "suspended"; since?: string; note?: string; alert?: string }; + // X's 15 minutes after a 429, when it is cooling down. + cooldownUntil?: string; +}; + +export type CookieStatusPayload = { readAt: string; rows: CookieRow[]; xSitting?: XSittingView }; export type Displayers = { path: (p: string) => string; text: (s: string) => string }; diff --git a/common/lib/downloadOutcome-server.ts b/common/lib/downloadOutcome-server.ts @@ -5,6 +5,7 @@ import { type DownloadOutcomeStatus, } from "./downloadOutcome"; import { sidecar, sidecarField } from "./sidecar-server"; +import { xAnswersUntrusted } from "./jobContext"; export function coerceDownloadOutcome( value: unknown, @@ -32,8 +33,25 @@ export const downloadOutcomeSidecar = sidecar( export const { path: downloadOutcomePath, load: loadDownloadOutcome, - write: writeDownloadOutcome, } = downloadOutcomeSidecar; +// The outcome, written — but inside an X job whose account is marked +// suspended (lib/jobContext.ts xAnswersUntrusted, review 1 F5) no attempt +// keeps a "gone" class (deleted, private, members-only, needs-auth) from what +// X answered. +export async function writeDownloadOutcome(videoDir: string, record: DownloadOutcomeRecord): Promise<void> { + if (await xAnswersUntrusted()) { + record = { + ...record, + attempts: record.attempts.map((a) => { + if (a.availabilityClass === undefined || a.availabilityClass === "public" || a.availabilityClass === "unlisted") return a; + const { availabilityClass: _dropped, ...rest } = a; + return rest; + }), + }; + } + return downloadOutcomeSidecar.write(videoDir, record); +} + // Narrow re-export so callers don't have to import from both modules. export type { DownloadOutcomeStatus }; diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -258,8 +258,9 @@ const DECLARED: EnvVarDecl[] = [ { name: "E2E_AVAILABILITY_PROBE_GAP_MS", audience: "test", default: "the real gap (3 s, stretched by `pacing.jitter`)", readBy: "common/controller/checkAvailability.ts", doc: "The pause after each per-video availability probe. The editor's e2e server and the availability unit tests set 0: their stub yt-dlp answers at once." }, { name: "E2E_PACING_JITTER", audience: "test", default: "`pacing.jitter` from settings.json (0.25)", readBy: "common/lib/jitter.ts", doc: "Replaces the operator's jitter share (0–1) for every request-pacing wait. The unit tests that assert an exact gap set 0; the jitter itself is tested with its share passed in (lib/jitter.test.ts)." }, { name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts", doc: "The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." }, - { name: "E2E_JOB_GAP_SECONDS", audience: "test", default: "the built-in gaps (20 s; X 300, forums and Bluesky 60)", readBy: "common/jobs/queueGap.ts", doc: "Replaces every BUILT-IN `pacing.jobGapSeconds` gap (plans/pacing-guard.md); a gap set in settings.json still applies. The editor's e2e server sets 0, so two fake fetches on one platform queue do not wait; pacing.spec sets its own." }, - { name: "E2E_X_MAX_COOKIE_AGE_MINUTES", audience: "test", default: "the built-in 60", readBy: "common/jobs/networkGuard.ts", doc: "Replaces the BUILT-IN `social.x.maxCookieAgeMinutes` (the fresh-jar rule for X jobs); a limit set in settings.json still applies. The editor's e2e server sets 0, so a fake X fetch needs no jar; x-session.spec sets its own." }, + { name: "E2E_JOB_GAP_SECONDS", audience: "test", default: "the built-in gaps (20 s; X 300, forums and Bluesky 60)", readBy: "common/jobs/queueGap.ts", doc: "Replaces every BUILT-IN `pacing.jobGapSeconds` gap (plans/pacing-guard.md); a gap set in settings.json still applies — but X's gap, drawn per job from `social.x.gapMinMinutes`-`gapMaxMinutes`, is collapsed to this value whatever is set. Honoured only beside `E2E_TEST_ROUTES=1`. The editor's e2e server sets 0, so two fake fetches on one platform queue do not wait; pacing.spec sets its own." }, + { name: "E2E_X_SITTINGS", audience: "test", default: "unset (X's sittings apply)", readBy: "common/jobs/networkGuard.ts", doc: "`off` leaves X jobs out of X's SITTINGS (at most `social.x.sittingJobs` X job starts per cookie refresh, of one kind each; common/lib/xSitting.ts) — inert unless `E2E_TEST_ROUTES=1`. The editor's e2e server sets it: its fake X jobs run many to one corpus with no refresh between them. X's job cap is not touched." }, + { name: "E2E_X_MAX_COOKIE_AGE_MINUTES", audience: "test", default: "the built-in 60", readBy: "common/jobs/networkGuard.ts", doc: "Replaces the BUILT-IN `social.x.maxCookieAgeMinutes` (the fresh-jar rule for X jobs); a limit set in settings.json still applies. Honoured only beside `E2E_TEST_ROUTES=1`. The editor's e2e server sets 0, so a fake X fetch needs no jar; x-session.spec sets its own." }, { name: "E2E_ODYSEE_PAGE_FIXTURE", audience: "test", default: "unset (a headless browser)", readBy: "common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts", doc: "A JSON file of recorded Odysee page reads keyed by page URL (`\"*\"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`)." }, { name: "E2E_UMTOOL_ORIGIN_FILE", audience: "test", default: "unset (UMTOOL_URL)", readBy: "common/lib/umtoolUrl.ts", doc: "A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored." }, { name: "E2E_WAYBACK_ORIGIN_FILE", audience: "test", default: "unset (the real Wayback Machine)", readBy: "common/lib/waybackClient.ts", doc: "A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index, Save Page Now) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored." }, diff --git a/common/lib/jobContext.ts b/common/lib/jobContext.ts @@ -25,6 +25,15 @@ export type JobContext = { onLog: (line: string) => void; // Services whose cookie alert this job met while it ran (serviceCookies). staleServices: Set<string>; + // X'S STOP met by this job (jobs/downloadBackoff.ts recordXStop): a rate + // limit or a bot check from X. The job ends deferred, saying so. + xStop?: { until: number; why: string; at: number }; + // AN X JOB'S ACCOUNT MARK (review 1 F5): set on every job of X's queues + // (jobs/streamCommand.ts). True while the operator has marked the X account + // suspended — then no writer records a post or a video as gone from what X + // answered (xAnswersUntrusted below). Read at each write, so a mark made + // while the job runs counts. + xSuspended?: () => Promise<boolean>; }; const KEY = Symbol.for("archilyzer.jobContext"); @@ -41,3 +50,17 @@ export function runInJobContext<T>(ctx: JobContext, fn: () => T): T { export function currentJobContext(): JobContext | undefined { return storage().getStore(); } + +// Is this write inside an X job whose account is marked suspended? Then what X +// answered is thinned, and nothing may be recorded deleted, unavailable or +// private from it (review 1 F5). False outside a job. A read that throws is +// taken as suspended (fail closed). +export async function xAnswersUntrusted(): Promise<boolean> { + const ask = currentJobContext()?.xSuspended; + if (!ask) return false; + try { + return await ask(); + } catch { + return true; + } +} diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -217,6 +217,28 @@ export const X_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<XSocialSettings> = { "cannot be read: the job logs that and proceeds. ABSENT: 60. 0 turns the rule off; at most " + "10080 (a week). Set in the X account session section of /settings. " + "common/jobs/networkGuard.ts.", + sittingJobs: + "X IN SITTINGS: a sitting begins at a cookie refresh (Refresh cookies or Connect X account on /cookies) and " + + "admits at most this many X job starts — every kind that asks X, counted as X's job cap counts them (each " + + "channel of an X run is one). A start beyond it is refused (at enqueue, or `done`, deferred, at its start: " + + "never a failure that retries): a new Refresh starts the next sitting. A sitting is also ONE KIND, fixed by its " + + "first job: `timelines` (account post fetches, captures, availability checks, one post's import) or `browse` " + + "(trending reads, X search channels' walks, a trending library's captures); a job of the other kind waits for " + + "the next Refresh. The sitting is kept in `.x-session/sitting.json` (rebuilt from the job records if it is " + + "lost) and shown by `pnpm ops get x-session` and on /cookies. ABSENT: 4. Bounded 1-6 in the code " + + "(common/lib/xSitting.ts): no value raises it past 6. common/jobs/xSitting.ts.", + gapMinMinutes: + "THE SHORTEST GAP BEFORE AN X JOB, in minutes: X's queue gap is drawn per job, uniform between this and " + + "`gapMaxMinutes`, after the previous X job ended, and logged (\"waiting 8m41s (a 9m02s gap drawn from 5-12 " + + "min)\"). Never below 5 (the floor is in the code); an explicit `pacing.jobGapSeconds.twitter` above it raises " + + "it. ABSENT: 5. At most 120. common/jobs/queueGap.ts.", + gapMaxMinutes: + "THE LONGEST GAP BEFORE AN X JOB, in minutes (see `gapMinMinutes`). Never less than the minimum plus 3 (a " + + "range of one value is a fixed beat; the spread is in the code). ABSENT: 12. At most 120.", + maxPostsPerJob: + "WHAT ONE X JOB MAY READ: a walk of an account's timeline (sync new, Resume backfill, a full or older walk) or " + + "of an X search reads at most this many posts, then saves its place and ends; the next sitting continues it. " + + "A lower `limit` on the job still applies. ABSENT: 300. Bounded 20-400 in the code (common/lib/xSitting.ts).", }; export type { AutoQueueSettings } from "./autoQueueTypes"; export type { ChannelPriority } from "./channelPriority"; @@ -1986,7 +2008,7 @@ export const siteSettingsSchema = z.object({ "How yt-dlp invocations use the configured cookies (see common/lib/cookiePolicy.ts): \"always\" passes them on every invocation, \"when-required\" (default; the historical behavior) only to retry an auth/age failure, \"defer\" never in normal runs — auth-gated videos are excluded from batches and collected into the per-channel \"Needs cookies\" bucket for a manual cookie run. Per-channel override available (ChannelConfig.cookieMode).", ), social: settingsField((v): SocialSettings => sanitizeSocial(v)).describe( - "Per-platform settings of the social posts: X's three, all chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`), where X posts may appear (`social.x.visibility`) and how fresh its cookies must be for an X job to start (`social.x.maxCookieAgeMinutes`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts.", + "Per-platform settings of the social posts: X's, all chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`), where X posts may appear (`social.x.visibility`), how fresh its cookies must be for an X job to start (`social.x.maxCookieAgeMinutes`), how many X jobs one cookie refresh admits (`social.x.sittingJobs`) and the range X's gap is drawn from (`social.x.gapMinMinutes`, `social.x.gapMaxMinutes`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts.", ), sleepBetweenDownloadsSeconds: settingsField((v): number => clampSleepBetweenDownloadsSeconds(v)).describe( "Pause (seconds) inserted between per-video yt-dlp invocations in managed batch downloads, and between two auto-download units on one platform (release 17; the lane ignored it before). yt-dlp's own `-t sleep` only paces requests within one invocation, so without this the managed loop hammers the source IP back-to-back. The adaptive pace above its base (see `pacing`) is added to it. 0 disables. Per-channel override available for batch downloads.", diff --git a/common/lib/xJobRule.test.ts b/common/lib/xJobRule.test.ts @@ -12,8 +12,8 @@ import { X_JOB_CAP, X_QUEUE_KEY, isXUrl, xJobCapSentence, xJobCapVerdict, xJobAs 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 }); +test("the numbers: 6 X jobs in any 60 minutes, 150 in any 24 hours, and they are frozen", () => { + assert.deepEqual({ ...X_JOB_CAP }, { perHour: 6, 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. @@ -23,44 +23,49 @@ test("the numbers: 12 X jobs in any 60 minutes, 150 in any 24 hours, and they ar } }); -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 }); +test("the hour window: the 7th start in 60 minutes is refused, and says when the next may start", () => { + const starts = Array.from({ length: 6 }, (_, i) => T0 + i * 10 * MIN); // 12:00 … 12:50 + assert.deepEqual(xJobCapVerdict(starts.slice(0, 5), T0 + 56 * MIN), { ok: true, lastHour: 5, lastDay: 5 }); const full = xJobCapVerdict(starts, T0 + 56 * MIN); - assert.deepEqual(full, { ok: false, lastHour: 12, lastDay: 12, nextAt: T0 + 60 * MIN, window: "hour" }); + assert.deepEqual(full, { ok: false, lastHour: 6, lastDay: 6, nextAt: T0 + 60 * MIN, window: "hour" }); assert.equal( xJobCapSentence(full, T0 + 56 * MIN), - "X's job cap is reached on this machine: 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); " + + "X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes (the cap is 6). 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); + assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN).lastHour, 5); + // At X's floor gap (5 minutes) six jobs take 25 minutes: the hourly cap bites a run at the floor. + const atFloor = Array.from({ length: 6 }, (_, i) => T0 + i * 5 * MIN); + assert.equal(xJobCapVerdict(atFloor, T0 + 30 * MIN).ok, false); }); 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; + // 150 starts in 20 hours (one every 8 minutes — more than the hourly cap lets through, but the verdict + // judges each window as it is at `now`, and the last hour here is empty). + const starts = Array.from({ length: 150 }, (_, i) => T0 + i * 8 * MIN); + const now = T0 + 1300 * MIN; const full = xJobCapVerdict(starts, now); assert.equal(full.ok, false); assert.equal(full.window, "day"); + assert.equal(full.lastHour, 0); 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\)/); + 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 about 2 h\)/); // 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.match(xJobCapSentence(full, 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 + const starts = Array.from({ length: 6 }, (_, i) => T0 + i * MIN); // 12:00 … 12:05 // 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.lastHour, 6); 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); @@ -86,37 +91,13 @@ test("X jobs run on X's queue only: any other queue is refused, when queued and assert.equal(runInJobContext(ctx("platform:twitter"), () => xJobContextRefusal("example-x", "d")), null); }); -test("ruling R-a: what counts is decided from the job's own plan — only a library's media-only capture, with no way to the login, does not", () => { - // The watch's follow-up capture with shots off, as the editor queues it (xTrendingActions.ts afterXTrendingRead). - const mediaOnly = { queueKey: undefined, ids: ["1"], shots: false, media: true, force: false, articles: false, avatars: false, context: false, watch: true }; - const library = { library: true }; - assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly, channel: library }), false); - // Each way to a page or to the login makes it count. - for (const [what, params] of [ - ["shots on", { ...mediaOnly, shots: true }], - ["shots by default", { ...mediaOnly, shots: undefined }], - ["articles by default", { ...mediaOnly, articles: undefined }], - ["avatars by default", { ...mediaOnly, avatars: undefined }], - ["context by default", { ...mediaOnly, context: undefined }], - ["a thread shot", { ...mediaOnly, thread: true }], - ["avatars only", { ...mediaOnly, avatarsOnly: true }], - ["context only", { ...mediaOnly, contextOnly: true }], - ["the keep capture (login fallback)", { ...mediaOnly, keptMedia: true }], - ] as const) { - assert.equal(xJobCounts({ kind: "capture-posts", params, channel: library }), true, what); - } - // The channel's thread default counts when the plan does not say no. - assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly, channel: { library: true, postCaptureThread: true } }), true); - assert.equal(xJobCounts({ kind: "capture-posts", params: { ...mediaOnly, thread: false }, channel: { library: true, postCaptureThread: true } }), false); - // Not a library: an X channel's media comes through gallery-dl with X's cookies. - assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly, channel: { library: false } }), true); - assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly }), true); - // No plan to read: it counts. - assert.equal(xJobCounts({ kind: "capture-posts", channel: library }), true); - // Every other kind of X job counts, whatever its params say. - for (const kind of ["fetch-posts", "x-run", "read-x-trending", "import-post", "check-post-availability", "sync", "download-missing"]) { - assert.equal(xJobCounts({ kind, params: mediaOnly, channel: library }), true, kind); +test("review 1 F8: every X job counts — a library's media-only capture too; only the transcription worker does not", () => { + const mediaOnly = { ids: ["1"], shots: false, media: true, force: false, articles: false, avatars: false, context: false, watch: true }; + assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly, channel: { library: true } }), true); + for (const kind of ["fetch-posts", "x-run", "read-x-trending", "import-post", "check-post-availability", "sync", "download-missing", "capture-posts"]) { + assert.equal(xJobCounts({ kind }), true, kind); } + assert.equal(xJobCounts({ kind: "transcribe-one" }), false); }); test("S5: which network jobs ask x.com — by X's queue, X's clip queue, an import's URL, or an X channel's job that is not local", () => { @@ -268,11 +249,11 @@ test("review 4 B: an import of a file by its page is X's by that page's address, }); test("review 3 S4: a start in the future counts in both windows, and never moves the windows off the real starts", () => { - const real = Array.from({ length: 11 }, (_, i) => T0 + i * MIN); + const real = Array.from({ length: 5 }, (_, i) => T0 + i * MIN); const future = T0 + 365 * 24 * 60 * MIN; - const v = xJobCapVerdict([...real, future], T0 + 11 * MIN); - assert.deepEqual([v.ok, v.lastHour, v.lastDay], [false, 12, 12]); - // The next may start when the oldest of the newest twelve has left: the real 12:00 start, at 13:00. + const v = xJobCapVerdict([...real, future], T0 + 5 * MIN); + assert.deepEqual([v.ok, v.lastHour, v.lastDay], [false, 6, 6]); + // The next may start when the oldest of the newest six has left: the real 12:00 start, at 13:00. assert.equal(v.nextAt, T0 + 60 * MIN); // The future start alone keeps counting until the clock has passed it by the window. assert.deepEqual([xJobCapVerdict([future], T0).lastHour, xJobCapVerdict([future], T0).lastDay], [1, 1]); diff --git a/common/lib/xJobRule.ts b/common/lib/xJobRule.ts @@ -36,13 +36,24 @@ import { currentJobContext } from "./jobContext"; export const X_QUEUE_KEY = "platform:twitter"; +// THE HOURLY CAP IS 6 (the operator, 21 Nov 2026: one sitting of 12 timeline +// fetches back to back, at the old cap of 12, preceded the account's +// suspension). At 6 an hour the daily 150 is implied (6 × 24 = 144): it stays +// as a second, independent bound. export const X_JOB_CAP = Object.freeze({ - perHour: 12, + perHour: 6, hourMs: 60 * 60_000, perDay: 150, dayMs: 24 * 60 * 60_000, }); +// HOW LONG X IS LEFT ALONE AFTER IT ANSWERED 429: X's own rate-limit window. +// Written as the `twitter` platform cooldown (jobs/downloadBackoff.ts +// recordPlatformCooldown) by every X reader that meets one — a trending read, +// its media, a capture, a gallery-dl run — and read by the network guard, +// which refuses EVERY X job while it lasts (jobs/networkGuard.ts). +export const X_RATE_LIMIT_HOLD_MS = 15 * 60_000; + // ── 1. the queue ─────────────────────────────────────────────────────────── // Why a job that asks X may not be on `queueKey`, or null. `what` names the @@ -154,31 +165,13 @@ export type XJobPlan = { }; // DOES THIS X JOB COUNT AGAINST THE CAP? Every X job does — a read, a fetch in -// any mode, an X run's channel, an import, an availability check, a capture -// with its shots — EXCEPT the one job that cannot ask x.com: a trending -// library's capture of MEDIA ONLY, which takes files from X's two media CDN -// hosts by the addresses already in the saved captures, with no cookie, no -// page and no logged-in fallback. Every half that would open a page must be -// off BY NAME in the plan (shots, articles, avatars, context; no thread shot, -// by the plan or the channel's default; no avatars-only or context-only run), -// and it is not a keep capture (`keptMedia`: a post the CDN cannot serve whole -// is then downloaded the logged-in way). A capture that COULD fall back to -// the login counts. A plan that cannot be read counts. -// -// It still runs on X's queue, spaced from the others by X's gap, under X's -// cooldown and the watch's jar rule: only the count is not asked. +// any mode, an X run's channel, an import, an availability check, and a +// capture of any kind, a trending library's media-only capture included +// (review 1 F8 of lane x-sittings, the operator's ruling: it asks X's media +// hosts, so it is an X job — in the sitting, the cap and the gap). Only the +// transcription worker, which reads a file on disk, does not. export function xJobCounts(plan: XJobPlan): boolean { - // The transcription worker reads a file on disk (review 2 S5). - if (plan.kind === "transcribe-one") return false; - if (plan.kind !== "capture-posts" || plan.channel?.library !== true) return true; - const p = plan.params; - if (!p || typeof p !== "object") return true; - const off = (k: string) => p[k] === false; - if (!(off("shots") && off("articles") && off("avatars") && off("context"))) return true; - if (p.thread === true || (p.thread !== false && plan.channel.postCaptureThread === true)) return true; - if (p.avatarsOnly === true || p.contextOnly === true) return true; - if (p.keptMedia === true) return true; - return p.media === false; + return plan.kind !== "transcribe-one"; } // ── 4. which jobs ask x.com (review 2 S5, review 3 M2/S5/S6) ─────────────── diff --git a/common/lib/xSitting.ts b/common/lib/xSitting.ts @@ -0,0 +1,255 @@ +// X IN SITTINGS (lane x-sittings; the operator, 21 Nov 2026: "Implement all +// your suggestions"). The archive's X account was suspended after one sitting +// of a trending read and 12 timeline fetches back to back, each 5-6 minutes +// after the last. So X is now asked in SMALL, UNEVEN SITTINGS: +// +// 1. A SITTING begins at a cookie refresh (the jar's refresh time, +// social/xSessionBroker.ts) and admits at most `social.x.sittingJobs` X +// job starts (default 4, bounded 1-6 HERE, in code). A start beyond it is +// refused: a new Refresh on /cookies starts the next sitting. +// 2. ONE KIND PER SITTING: "timelines" (account post fetches, captures, +// checks) or "browse" (trending reads, search walks). The first job fixes +// it; a job of the other kind is refused until the next Refresh. +// 3. THE GAP BEFORE AN X JOB IS DRAWN per job, uniform in a range (default +// 5-12 min; the floor 5 min is in code), not a fixed beat. +// +// Pure and client-safe: the settings coercion, the guard (jobs/networkGuard.ts), +// the count on disk (jobs/xSitting.ts), the queue gap (jobs/queueGap.ts) and +// /cookies all read it. What counts is X's job cap's rule (lib/xJobRule.ts +// xJobCounts): the same starts, counted at the same moment. + +export type XSittingKind = "timelines" | "browse"; + +export const X_SITTING_DEFAULT_JOBS = 4; +export const X_SITTING_MIN_JOBS = 1; +export const X_SITTING_MAX_JOBS = 6; + +// `social.x.sittingJobs` as stored: a whole number 1-6, else absent. +export function parseXSittingJobs(v: unknown): number | undefined { + if (typeof v !== "number" || !Number.isFinite(v)) return undefined; + return Math.min(X_SITTING_MAX_JOBS, Math.max(X_SITTING_MIN_JOBS, Math.floor(v))); +} + +// The limit in force: the setting, bounded again (a hand-edited file never +// passes 6), else the default. +export function xSittingJobs(x: { sittingJobs?: number } | undefined): number { + return parseXSittingJobs(x?.sittingJobs) ?? X_SITTING_DEFAULT_JOBS; +} + +// ── the kind of an X job ─────────────────────────────────────────────────── + +// The job as it will run: its kind, and what its channel is (read by the +// guard from the channel's config, never from the caller). +export type XSittingPlan = { + kind: string; + channel?: { library?: boolean; search?: boolean }; +}; + +// "browse": reading what X shows — a trending page, a search walk, and the +// capture of what a trending read found (a library's posts). "timelines": +// everything else — an account's posts in any mode, an X run's channel, a +// capture of an account's posts, an availability check, an import of one +// post, an X video window. +export function xSittingKindOf(plan: XSittingPlan): XSittingKind { + if (plan.kind === "read-x-trending") return "browse"; + if (plan.channel?.search === true) return "browse"; + if (plan.channel?.library === true) return "browse"; + return "timelines"; +} + +export const X_SITTING_KIND_TEXT: Readonly<Record<XSittingKind, string>> = Object.freeze({ + timelines: "timelines (account post fetches, captures, checks)", + browse: "browse (trending reads, search walks)", +}); + +// ── the verdict ──────────────────────────────────────────────────────────── + +// The sitting as it stands: when it began (the jar's refresh time; null: no +// refresh on record), its kind (null: no job yet; "unknown": its record was +// lost and its kind cannot be told), the jobs it started, and its first job. +export type XSittingState = { + began: string | null; + kind: XSittingKind | "unknown" | null; + used: number; + first?: { jobKind: string; at: number }; +}; + +export type XSittingVerdict = + | { ok: true; used: number; left: number; limit: number } + | { ok: false; why: "used-up" | "kind" | "unknown"; used: number; left: number; limit: number; sentence: string }; + +const hhmm = (iso: string | number) => new Date(iso).toISOString().slice(11, 16); + +function beganText(began: string | null): string { + return began ? `since the cookies were refreshed at ${hhmm(began)} UTC` : "with no cookie refresh on record"; +} + +const NEXT = "A new Refresh cookies on /cookies starts the next sitting; nothing queues or retries by itself."; + +// May a job of `kind` start in this sitting? +export function xSittingVerdict(state: XSittingState, kind: XSittingKind, limit: number): XSittingVerdict { + const used = state.used; + const left = Math.max(0, limit - used); + const base = { used, left, limit }; + if (used >= limit) { + return { + ok: false, + why: "used-up", + ...base, + sentence: + `This X sitting is used up: ${used} of ${limit} X job${limit === 1 ? "" : "s"} started ${beganText(state.began)} ` + + `(social.x.sittingJobs, at most ${X_SITTING_MAX_JOBS}). ${NEXT}`, + }; + } + if (state.kind === "unknown") { + return { + ok: false, + why: "unknown", + ...base, + sentence: + `This X sitting's kind cannot be told: its record is gone and the ${used} X job${used === 1 ? "" : "s"} it started left none. ` + + `No X job starts in it. ${NEXT}`, + }; + } + if (state.kind !== null && state.kind !== kind) { + const first = state.first ? ` (its first job, ${state.first.jobKind} at ${hhmm(state.first.at)} UTC, fixed it)` : ""; + return { + ok: false, + why: "kind", + ...base, + sentence: + `This X sitting is a ${state.kind} sitting${first}: a ${kind} job does not start in it — ` + + `one sitting is ${X_SITTING_KIND_TEXT.timelines} or ${X_SITTING_KIND_TEXT.browse}, never both. ${NEXT}`, + }; + } + return { ok: true, ...base }; +} + +// Is `next` a LATER refresh than `began`, so a new sitting begins? An equal or +// earlier time (a jar restored from a backup, a clock set back) continues the +// sitting on record: only a real refresh resets it. +export function isLaterRefresh(next: string | null | undefined, began: string | null): boolean { + if (!next) return false; + const n = Date.parse(next); + if (!Number.isFinite(n)) return false; + if (began === null) return true; + const b = Date.parse(began); + return !Number.isFinite(b) || n > b; +} + +// ── the gap before an X job ──────────────────────────────────────────────── + +// The floor of X's gap: never below the fixed five minutes it replaced. +export const X_GAP_FLOOR_MINUTES = 5; +export const X_GAP_DEFAULT_MIN_MINUTES = 5; +export const X_GAP_DEFAULT_MAX_MINUTES = 12; +export const X_GAP_CEILING_MINUTES = 120; +// THE RANGE IS NEVER ONE VALUE (review 1 F4): the longest gap is at least +// this much above the shortest, whatever is set — a range of one value is a +// fixed beat again. +export const X_GAP_MIN_SPREAD_MINUTES = 3; + +// `social.x.gapMinMinutes` / `gapMaxMinutes` as stored: whole minutes from +// the floor to the ceiling, else absent. +export function parseXGapMinutes(v: unknown): number | undefined { + if (typeof v !== "number" || !Number.isFinite(v)) return undefined; + return Math.min(X_GAP_CEILING_MINUTES, Math.max(X_GAP_FLOOR_MINUTES, Math.floor(v))); +} + +export type XGapRange = { minSeconds: number; maxSeconds: number }; + +// The range in force, in seconds. The minimum is the setting (else 5 min), +// never below the floor, and raised — never lowered — by an explicit +// `pacing.jobGapSeconds.twitter` above it; the maximum is the setting (else +// 12 min), never less than the minimum plus X_GAP_MIN_SPREAD_MINUTES. +export function xGapRange( + x: { gapMinMinutes?: number; gapMaxMinutes?: number } | undefined, + explicitTwitterSeconds?: number, +): XGapRange { + const minMinutes = parseXGapMinutes(x?.gapMinMinutes) ?? X_GAP_DEFAULT_MIN_MINUTES; + let minSeconds = minMinutes * 60; + if (typeof explicitTwitterSeconds === "number" && Number.isFinite(explicitTwitterSeconds) && explicitTwitterSeconds > minSeconds) { + minSeconds = Math.floor(explicitTwitterSeconds); + } + const maxMinutes = parseXGapMinutes(x?.gapMaxMinutes) ?? X_GAP_DEFAULT_MAX_MINUTES; + const maxSeconds = Math.max(minSeconds + X_GAP_MIN_SPREAD_MINUTES * 60, maxMinutes * 60); + return { minSeconds, maxSeconds }; +} + +// One draw from the range, uniform: `rand` in [0, 1). +export function drawXGapSeconds(range: XGapRange, rand: number): number { + const r = Number.isFinite(rand) ? Math.min(Math.max(rand, 0), 1) : 0; + const s = range.minSeconds + Math.floor(r * (range.maxSeconds - range.minSeconds + 1)); + return Math.min(range.maxSeconds, Math.max(range.minSeconds, s)); +} + +// "5-12 min" (whole minutes), else "300-720 s". +export function xGapRangeText(range: XGapRange): string { + const whole = range.minSeconds % 60 === 0 && range.maxSeconds % 60 === 0; + return whole ? `${range.minSeconds / 60}-${range.maxSeconds / 60} min` : `${range.minSeconds}-${range.maxSeconds} s`; +} + +// ── the account's state (suspension) ────────────────────────────────────── + +// The operator's word on the account X answers as: "suspended" (read-only: +// its answers are thinned, so a post it cannot see is NOT a deleted post) or +// "ok". Marked by hand (`pnpm ops x-session`, /cookies). +export type XAccountState = "ok" | "suspended"; + +export function isXAccountState(v: unknown): v is XAccountState { + return v === "ok" || v === "suspended"; +} + +// The kinds a suspended account refuses: they RECORD posts as deleted or +// unavailable from what X answers. A capture with its screenshots off records +// no availability (social/xPostCapture.ts records it with the shot only). +// (review 1 F5) A capture refuses unless both halves that read a page's +// verdict — the post's shot and its article — are off by name; the video +// checks (check-availability and its kin) on an X channel refuse as the +// post check does. Every other writer is covered at the write +// (lib/jobContext.ts xAnswersUntrusted). +const SUSPENDED_REFUSED_KINDS: ReadonlySet<string> = new Set([ + "check-post-availability", + "check-availability", + "quick-availability-check", + "check-maybe-missing", + "check-kept-deleted", +]); + +export function xSuspendedRefuses(plan: { kind: string; params?: Readonly<Record<string, unknown>> }): boolean { + if (SUSPENDED_REFUSED_KINDS.has(plan.kind)) return true; + if (plan.kind !== "capture-posts") return false; + const p = plan.params; + if (p?.avatarsOnly === true || p?.contextOnly === true) return false; + return p?.shots !== false || p?.articles !== false; +} + +export function xSuspendedSentence(what: string, since: string, note?: string): string { + return ( + `The X account is marked suspended (since ${since.slice(0, 16).replace("T", " ")} UTC${note ? `: ${note}` : ""}): ` + + `${what} is refused, because a suspended account's answers are thinned and a post it cannot see would be recorded ` + + `deleted or unavailable when it is not. Mark it ok (pnpm ops x-session --json '{"accountState":"ok"}', or /cookies) once it is restored.` + ); +} + +// ── what ONE X job may read (review 1 F8) ───────────────────────────────── + +// A walk of an account's timeline (sync new, backfill, full, older) or of an +// X search reads at most `social.x.maxPostsPerJob` posts (default 300), and +// never more than the ceiling in the code; then it saves its place and ends, +// to be continued in a later sitting. One job read 634 on 20 Nov 2026. +export const X_POSTS_PER_JOB_DEFAULT = 300; +export const X_POSTS_PER_JOB_MIN = 20; +export const X_POSTS_PER_JOB_CEILING = 400; + +export function parseXPostsPerJob(v: unknown): number | undefined { + if (typeof v !== "number" || !Number.isFinite(v)) return undefined; + return Math.min(X_POSTS_PER_JOB_CEILING, Math.max(X_POSTS_PER_JOB_MIN, Math.floor(v))); +} + +// The posts this job may read: the caller's limit when lower, else the +// setting, never above the ceiling. +export function xJobPostLimit(x: { maxPostsPerJob?: number } | undefined, asked?: number): number { + const cap = parseXPostsPerJob(x?.maxPostsPerJob) ?? X_POSTS_PER_JOB_DEFAULT; + return typeof asked === "number" && Number.isFinite(asked) && asked > 0 ? Math.min(Math.floor(asked), cap) : cap; +} diff --git a/common/social/fakeXProfileBrowser.test.ts b/common/social/fakeXProfileBrowser.test.ts @@ -46,7 +46,7 @@ test("the gate: test server, inside transcriptsDir, the file exists", async () = test("refreshXCookies on the fake writes the jar from the fixture's cookies", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "fake-x-")); try { - const paths = { transcriptsDir: root } as Parameters<typeof refreshXCookies>[0]; + const paths = { transcriptsDir: root, autoQueueStateFile: path.join(root, ".auto-queue", "state.json") } as Parameters<typeof refreshXCookies>[0]; await mkdir(path.join(root, ".x-session", "profile"), { recursive: true }); const file = path.join(root, ".fake-x-profile-cookies.json"); await writeFile( @@ -70,7 +70,7 @@ test("refreshXCookies on the fake writes the jar from the fixture's cookies", as test("connectXAccount on the fake: the window closes by itself, the login is exported; clearXSession forgets it", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "fake-x-")); try { - const paths = { transcriptsDir: root } as Parameters<typeof connectXAccount>[0]; + const paths = { transcriptsDir: root, autoQueueStateFile: path.join(root, ".auto-queue", "state.json") } as Parameters<typeof connectXAccount>[0]; const file = path.join(root, ".fake-x-profile-cookies.json"); await writeFile( file, diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts @@ -112,6 +112,9 @@ export type PostFetchResult = { error?: string; // The run stopped on `drain` at a resume point (`cursor`). Not a failure. drained?: boolean; + // X answered a rate limit or a bot check: the run stopped at its resume + // point (`cursor` / `position`) and the X stop is recorded (review 1 F2). + rateLimited?: boolean; // A forum thread's walk positions after the run (with every checkpoint's). forumWalk?: ForumWalkState; // What stopped the run, when the source refused or challenged it — the @@ -188,6 +191,8 @@ export type OlderPostFetchResult = { error?: string; // The walk stopped on `drain`; `position` is where the next run resumes. drained?: boolean; + // X answered a rate limit: the walk stopped at `position` (review 1 F2). + rateLimited?: boolean; }; // Input for an X SEARCH channel's walk (`SocialFetcher.fetchSearch`, release diff --git a/common/social/headedDisplay.test.ts b/common/social/headedDisplay.test.ts @@ -437,7 +437,7 @@ test("a browser that opens no window (the e2e fake) needs no display", async () // --- each Connect passes the env ------------------------------------------------------------------ -const paths = (name: string) => ({ transcriptsDir: path.join(TMP, name) }) as unknown as Paths; +const paths = (name: string) => ({ transcriptsDir: path.join(TMP, name), autoQueueStateFile: path.join(TMP, name, ".auto-queue", "state.json") }) as unknown as Paths; test("Connect X account: the window gets the display, and the result says which", async () => { const { chromium, launches } = stubChromium(); diff --git a/common/social/postCapture.ts b/common/social/postCapture.ts @@ -24,6 +24,7 @@ // // SERVER-ONLY (node:fs). +import { xAnswersUntrusted } from "../lib/jobContext"; import { createHash } from "node:crypto"; import { createReadStream } from "node:fs"; import { readdir, stat } from "node:fs/promises"; @@ -308,6 +309,17 @@ export async function writePostCapture( dir: string, record: PostCaptureRecord, ): Promise<void> { + // Inside an X job whose account is marked suspended (review 1 F5): a post + // or an article X showed as deleted or unavailable is recorded as an error, + // owed again — never as settled. + if (await xAnswersUntrusted()) { + const gone = (st: string) => st === "deleted" || st === "unavailable"; + const note = "not recorded as gone: the X account is marked suspended"; + if (gone(record.state)) record = { ...record, state: "error", error: record.error ? `${record.error}; ${note}` : note }; + if (record.article && gone(record.article.state)) { + record = { ...record, article: { ...record.article, state: "error", error: record.article.error ? `${record.article.error}; ${note}` : note } }; + } + } await writeJsonAtomic(path.join(dir, CAPTURE_FILENAME), record, { mkdir: true }); } diff --git a/common/social/xAccountState.ts b/common/social/xAccountState.ts @@ -0,0 +1,107 @@ +// THE X ACCOUNT'S STATE, AS THE OPERATOR MARKED IT (lane x-sittings): whether +// the account X answers as is suspended (read-only). `<transcripts>/.x-session/account.json`: +// { "version": 1, "state": "suspended" | "ok", "note"?: "…", "at": <iso>, "by": "operator" } +// +// Marked BY HAND only (`pnpm ops x-session --json '{"accountState":…}'`, the +// control on /cookies). The fetchers were searched for an explicit signal of +// OUR account's suspension in X's own answers and carry none (gallery-dl's +// "account suspended" is about the account being read, not ours — +// social/xGalleryDlSignals.ts), so nothing here guesses one. +// +// While it is "suspended" the network guard refuses the X jobs that record +// posts as deleted or unavailable (lib/xSitting.ts xSuspendedRefuses), and +// every other X job's log says the account is suspended. +// +// A file that cannot be read is taken as SUSPENDED (fail closed: the jobs it +// refuses are the ones that could write a false "deleted"). +// +// SERVER-ONLY (node:fs). + +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; +import { isXAccountState, type XAccountState } from "../lib/xSitting"; + +export function xAccountStateFile(paths: Pick<Paths, "transcriptsDir">): string { + return path.join(paths.transcriptsDir, ".x-session", "account.json"); +} + +export type XAccountRecord = { + state: XAccountState; + note?: string; + at: string; + by: "operator"; + // The file is there and could not be read: taken as suspended. + unreadable?: true; +}; + +export const X_ACCOUNT_NOTE_MAX = 300; + +// The state on record; absent means "ok" (nothing marked). +export async function readXAccountState(paths: Pick<Paths, "transcriptsDir">): Promise<XAccountRecord | null> { + const read = await readJsonFile(xAccountStateFile(paths)); + if (!read.ok) { + if (read.reason === "absent") return null; + return { state: "suspended", at: new Date(0).toISOString(), by: "operator", unreadable: true, note: "account.json cannot be read" }; + } + const v = read.value as Record<string, unknown> | null; + if (!v || typeof v !== "object" || !isXAccountState(v.state) || typeof v.at !== "string") { + return { state: "suspended", at: new Date(0).toISOString(), by: "operator", unreadable: true, note: "account.json cannot be read" }; + } + return { + state: v.state, + at: v.at, + by: "operator", + ...(typeof v.note === "string" && v.note.trim() ? { note: v.note.trim().slice(0, X_ACCOUNT_NOTE_MAX) } : {}), + }; +} + +// The operator marks the account. Answers what is now on record. +export async function writeXAccountState( + paths: Pick<Paths, "transcriptsDir">, + state: XAccountState, + opts: { note?: string; now?: number } = {}, +): Promise<XAccountRecord> { + const note = opts.note?.trim().slice(0, X_ACCOUNT_NOTE_MAX); + const record: XAccountRecord = { + state, + at: new Date(opts.now ?? Date.now()).toISOString(), + by: "operator", + ...(note ? { note } : {}), + }; + await writeJsonAtomic(xAccountStateFile(paths), { version: 1, ...record }, { mkdir: true }); + return record; +} + +// The alert line /cookies and `get x-session` show while it is suspended. +export function xAccountAlertLine(r: XAccountRecord): string { + if (r.unreadable) return "The X account's state cannot be read (.x-session/account.json): taken as suspended until it is marked again."; + return `The X account is marked suspended (since ${r.at.slice(0, 16).replace("T", " ")} UTC${r.note ? `: ${r.note}` : ""}). Availability checks and captures that record deleted posts are refused.`; +} + +// THE LAST LINE BEFORE A VERDICT IS WRITTEN (an X capture, an X availability +// check): while the account is marked suspended — marked during the run, the +// guard having let the job start — no post is recorded deleted or +// unavailable from what it answered. Only "available" is kept. Answers the +// observations to write (the same map when nothing is dropped). +export async function keepVerdictsTrustedWhileSuspended<V extends string>( + paths: Pick<Paths, "transcriptsDir">, + observations: Map<string, V>, + log: (line: string) => void, +): Promise<Map<string, V>> { + const acct = await readXAccountState(paths).catch(() => null); + if (acct?.state !== "suspended") return observations; + const kept = new Map<string, V>(); + let dropped = 0; + for (const [id, v] of observations) { + if (v === "available") kept.set(id, v); + else dropped++; + } + if (dropped > 0) { + log( + `The X account is marked suspended: ${dropped} "deleted" or "unavailable" verdict(s) from its answers were NOT recorded ` + + "(a suspended account's answers are thinned).", + ); + } + return kept; +} diff --git a/common/social/xArticleCapture.test.ts b/common/social/xArticleCapture.test.ts @@ -470,3 +470,15 @@ test("run: an older record's article is not lost by a run that does not read it" assert.deepEqual(h.visits, []); assert.deepEqual((await readPostCapture(dir))!.article, article); }); + +// LANE X-SITTINGS, review 2 G2: an image X's host answers 429 ends the image +// loop at once and marks the article refused, so the capture records the X +// stop and loads no further page. +test("article: an image answered 429 stops the images at once and marks the article refused", async () => { + const dir = await tmpDir(); + const p = articlePage([articleSnap()], { served: { [orig(COVER)]: { status: 429 } } }); + const res = await captureXArticle(p, LINK, dir, { now: NOW }); + assert.deepEqual(p.fetched, [orig(COVER)], "nothing after the 429"); + assert.equal(res.refused, true); + assert.match(res.stop ?? "", /rate limit \(429\) to an article image/); +}); diff --git a/common/social/xArticleCapture.ts b/common/social/xArticleCapture.ts @@ -190,6 +190,9 @@ export type XArticleCaptureResult = { record: ArticleCaptureRecord; // Set when the run must stop here (a login wall, X refusing pages). stop?: string; + // X refused the page ("Something went wrong", "rate limit exceeded"): the + // X stop (review 1 F1). + refused?: true; }; export type XArticleCaptureOptions = { @@ -220,6 +223,7 @@ export async function captureXArticle( ...(verdict.error ? { error: verdict.error } : {}), }, ...(verdict.stop ? { stop: verdict.stop } : {}), + ...(verdict.refused ? { refused: true as const } : {}), }); try { @@ -334,6 +338,9 @@ export async function captureXArticle( ...(trimmed ? { trimmed: true } : {}), ...(error ? { error } : {}), }, + // An image refused with 429: the caller records X's stop and loads no + // further page (review 2 G2). + ...(images.refused ? { refused: true as const, stop: "X answered a rate limit (429) to an article image; stopping rather than asking again." } : {}), }; } @@ -345,7 +352,7 @@ async function fetchArticleImages( blocks: ReadonlyArray<XArticleBlock>, dir: string, opts: XArticleCaptureOptions, -): Promise<{ saved: Map<string, CapturedFile>; errors: string[] }> { +): Promise<{ saved: Map<string, CapturedFile>; errors: string[]; refused?: true }> { const saved = new Map<string, CapturedFile>(); const errors: string[] = []; const srcs = [...new Set(blocks.flatMap((b) => (b.type === "image" && b.src ? [b.src] : [])))]; @@ -355,7 +362,9 @@ async function fetchArticleImages( return { saved, errors }; } let n = 0; + let refused = false; for (const src of srcs) { + if (refused) break; if (opts.signal?.aborted) { errors.push("cancelled before the rest of the images"); break; @@ -369,6 +378,12 @@ async function fetchArticleImages( const res = await page.request.get(url, { timeout: 30_000, failOnStatusCode: false }); if (!res.ok()) { last = `HTTP ${res.status()} for ${url}`; + // X's image host rate-limited it: the X stop, and no further image + // (review 2 G2). + if (res.status() === 429) { + refused = true; + break; + } continue; } const body = await res.body(); @@ -384,7 +399,7 @@ async function fetchArticleImages( if (last) errors.push(last); } if (saved.size) opts.onLog?.(`article: ${saved.size} image(s) saved.`); - return { saved, errors }; + return { saved, errors, ...(refused ? { refused: true as const } : {}) }; } // A re-capture with fewer images leaves no older numbered file behind. diff --git a/common/social/xAvatarCapture.ts b/common/social/xAvatarCapture.ts @@ -204,6 +204,16 @@ export async function saveXAvatars( } try { const res = await page.request.get(url, { timeout: 30_000, failOnStatusCode: false }); + // X's media host rate-limited the avatar: the one X stop (review 1 F1), + // and no further avatar is asked in this run. + if (res.status() === 429) { + const { recordXStop } = await import("../jobs/downloadBackoff"); + const { getPaths } = await import("../lib/paths"); + await recordXStop("a rate limit (429) to an avatar", getPaths()).catch(() => 0); + summary.failed.push({ handle: c.handle, error: `HTTP 429 for ${url}` }); + onLog?.(`avatar @${c.handle}: X answered 429 (rate limit); no further avatar is asked.`); + break; + } if (!res.ok()) throw new Error(`HTTP ${res.status()} for ${url}`); const type = res.headers()["content-type"] ?? ""; if (type && !/^image\//i.test(type)) throw new Error(`${url} answered ${type.split(";")[0]}, not an image`); diff --git a/common/social/xCookieSource.ts b/common/social/xCookieSource.ts @@ -20,6 +20,7 @@ // controller and the editor's Settings section all read it. import { parseRetryOnBlock, type RetryOnBlock } from "../lib/forumWalk"; +import { parseXGapMinutes, parseXPostsPerJob, parseXSittingJobs } from "../lib/xSitting"; export type XCookieSource = "browser" | "profile"; @@ -56,6 +57,14 @@ export type XSocialSettings = { // many minutes and carries a login. 0 turns the rule off. Absent = // X_DEFAULT_MAX_COOKIE_AGE_MINUTES. common/jobs/networkGuard.ts. maxCookieAgeMinutes?: number; + // X IN SITTINGS (lib/xSitting.ts): the X job starts one cookie refresh + // admits (1-6; absent = 4), and the range X's queue gap is drawn from + // (minutes, never below 5; absent = 5 and 12). + sittingJobs?: number; + gapMinMinutes?: number; + gapMaxMinutes?: number; + // The posts one X walk may read (20-400; absent = 300). + maxPostsPerJob?: number; }; // Absent `social.x.maxCookieAgeMinutes`: an hour. A refresh is a human click @@ -127,11 +136,19 @@ export function sanitizeSocial(value: unknown): SocialSettings { }; const retryOnBlock = parseRetryOnBlock(xf.retryOnBlock); const maxCookieAgeMinutes = parseXMaxCookieAgeMinutes(x.maxCookieAgeMinutes); + const sittingJobs = parseXSittingJobs(x.sittingJobs); + const gapMinMinutes = parseXGapMinutes(x.gapMinMinutes); + const gapMaxMinutes = parseXGapMinutes(x.gapMaxMinutes); + const maxPostsPerJob = parseXPostsPerJob(x.maxPostsPerJob); return { x: { ...(isXCookieSource(x.cookieSource) ? { cookieSource: x.cookieSource } : {}), ...(isXPostsVisibility(x.visibility) ? { visibility: x.visibility } : {}), ...(maxCookieAgeMinutes !== undefined ? { maxCookieAgeMinutes } : {}), + ...(sittingJobs !== undefined ? { sittingJobs } : {}), + ...(gapMinMinutes !== undefined ? { gapMinMinutes } : {}), + ...(gapMaxMinutes !== undefined ? { gapMaxMinutes } : {}), + ...(maxPostsPerJob !== undefined ? { maxPostsPerJob } : {}), }, ...(retryOnBlock ? { xenforo: { retryOnBlock } } : {}), ...(Object.keys(instagram).length > 0 ? { instagram } : {}), diff --git a/common/social/xGalleryDlFetcher.test.ts b/common/social/xGalleryDlFetcher.test.ts @@ -305,7 +305,7 @@ test("search argv: the timeline's flags and login, latest-first max_id paging, n "extractor.twitter.search-results=latest", "extractor.twitter.search-pagination=max_id", "extractor.twitter.sleep-request=4.0-10.0", - "extractor.twitter.ratelimit=wait", + "extractor.twitter.ratelimit=abort", ]) { assert.ok(argv.includes(opt), opt); } @@ -334,13 +334,13 @@ test("stream: tracks the oldest post id read (any post, archived or not) and the assert.equal(s.pendingCount(), 0); }); -test("every X read paces itself: a random 4–10 s before each request, rate limits waited out", () => { +test("every X read paces itself: a random 4–10 s before each request, a rate limit stops the run (abort, review 1 F2)", () => { for (const argv of [ buildGalleryDlArgs({ accountUrl: "https://x.com/example_user" }), buildGalleryDlSearchArgs({ handle: "example_user", position: { since: "2020-12-11", until: "2021-03-11" } }), ]) { assert.ok(argv.includes(`extractor.twitter.sleep-request=${X_SLEEP_REQUEST}`)); - assert.ok(argv.includes("extractor.twitter.ratelimit=wait")); + assert.ok(argv.includes("extractor.twitter.ratelimit=abort")); } const [lo, hi] = X_SLEEP_REQUEST.split("-").map(Number); assert.ok(lo >= 4 && hi > lo, "a range, not a fixed gap"); @@ -377,7 +377,7 @@ test("capture argv: paced and logged in exactly as the reads are", () => { const capture = buildGalleryDlCaptureArgs({ id: "42", dir: "/d", cookieFile: JAR }); for (const flag of [ `extractor.twitter.sleep-request=${X_SLEEP_REQUEST}`, - "extractor.twitter.ratelimit=wait", + "extractor.twitter.ratelimit=abort", ]) { assert.ok(read.includes(flag) && capture.includes(flag), flag); } @@ -617,3 +617,14 @@ test("stream: after a search-phase place `3_<N>/`, a first-page post above N mea assert.equal(after([299, 350]), true); assert.equal(after([...Array.from({ length: TOP_RESTART_WINDOW }, (_, i) => 300 - i), 301]), false); }); + +// LANE X-SITTINGS: gallery-dl reads a cookie FILE and never writes it back +// (its `cookies-update` is on by default and rewrote the broker's jar after +// every run — the jar's mtime then said "refreshed" after every fetch). +import { galleryDlLoginArgs } from "./xGalleryDlFetcher"; +test("a cookie file is passed with cookies-update off; a browser's store is passed as it was", () => { + assert.deepEqual(galleryDlLoginArgs({ cookieFile: "/c/.x-session/cookies.txt" }), ["--cookies", "/c/.x-session/cookies.txt", "-o", "cookies-update=false"]); + assert.deepEqual(galleryDlLoginArgs({ cookies: "file:/c/other.txt" }), ["--cookies", "/c/other.txt", "-o", "cookies-update=false"]); + assert.deepEqual(galleryDlLoginArgs({ cookies: "firefox" }), ["--cookies-from-browser", "firefox"]); + assert.deepEqual(galleryDlLoginArgs({}), []); +}); diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts @@ -31,6 +31,8 @@ import type { Readable } from "node:stream"; import { execa } from "execa"; import { getPaths } from "../lib/paths"; import { noteXServiceOutcome } from "../lib/serviceCookies-server"; +import { recordXStop } from "../jobs/downloadBackoff"; +import { currentJobContext } from "../lib/jobContext"; import { looksLikeXAuthFailure, xBlockKind, xBlockLine } from "./xGalleryDlSignals"; import { cookieArgs } from "../lib/cookiePolicy"; import type { Post, PostRef } from "../lib/posts"; @@ -233,15 +235,18 @@ function galleryDlCommonArgs(opts: GalleryDlLoginAndCap): string[] { // account-history walk is hundreds of requests, so every read waits a RANDOM // 4–10 s before each one (gallery-dl's own "a-b" range, a uniform draw per // request): no fixed rhythm, and well under the rate a person scrolling would -// make. Running into the limit anyway is waited out, never pushed through -// ("wait" is gallery-dl's default; stated so it stays). Every gallery-dl run +// make. Running into the limit anyway STOPS THE RUN AT ONCE ("abort"; the +// operator, 21 Nov 2026, review 1 F2 of lane x-sittings): it used to be waited +// out in-process ("wait") and the same job paged on after X's reset. Now the +// run ends at its last page, the 15-minute X stop is recorded the moment the +// line is seen (recordXStop), and the job ends deferred. Every gallery-dl run // against X carries these — the reads and the post capture alike. function galleryDlPacingArgs(): string[] { return [ "-o", `extractor.twitter.sleep-request=${X_SLEEP_REQUEST}`, "-o", - "extractor.twitter.ratelimit=wait", + "extractor.twitter.ratelimit=abort", ]; } @@ -251,11 +256,17 @@ function galleryDlPacingArgs(): string[] { // session, though — gallery-dl will block for minutes on "Waiting for N // minutes (rate limit)" — so credentials remain the path for a deep backfill. // When none are configured we simply run as a guest rather than failing. -function galleryDlLoginArgs(opts: GalleryDlLoginAndCap): string[] { - if (opts.cookieFile) return ["--cookies", opts.cookieFile]; +// +// A COOKIE FILE IS READ, NEVER WRITTEN BACK (lane x-sittings): gallery-dl's +// `cookies-update` is on by default and rewrites a `--cookies` file with the +// session's cookies after every run (gallery-dl 1.32.9 Extractor.cookies_store). +// On the broker's jar that rewrite made every fetch look like a refresh (the +// jar's mtime), so it is passed off. +export function galleryDlLoginArgs(opts: Pick<GalleryDlLoginAndCap, "cookieFile" | "cookies">): string[] { // Same browser-cookie spec yt-dlp uses (cookiePolicy.ts), same syntax — // `file:<path>` included, which is `--cookies <path>`. - return cookieArgs(opts.cookies); + const args = opts.cookieFile ? ["--cookies", opts.cookieFile] : cookieArgs(opts.cookies); + return args.includes("--cookies") ? [...args, "-o", "cookies-update=false"] : args; } // The random gap a post capture waits before each contact with X after its @@ -354,7 +365,14 @@ export async function downloadXPostMedia(args: { for (const line of stderr.split("\n")) { if (line.trim()) args.onLog?.(`gallery-dl: ${line.trim()}`); } + // X's rate limit or bot check on a post's media (review 1 F1): the X stop, + // and the capture run stops here. + const stopWhy = stderr.split("\n").map(xStopLine).find((w) => w !== null) ?? null; + if (stopWhy) await noteXRateLimit(args.onLog, stopWhy.replace("(gallery-dl)", "(gallery-dl, a post's media)")); const blocked = stderr.split("\n").find((l) => !/\]\[debug\]/.test(l) && xBlockLine(l)); + if (stopWhy && !blocked) { + return { ok: false, error: `X answered ${stopWhy} to the media download.`, stop: "X answered a rate limit; stopping rather than asking again." }; + } if (blocked && !res.isCanceled) { await noteXOutcome(blocked, `https://x.com/i/status/${args.id}`, "", args.onLog); return { ok: false, needsCookies: true, error: xBlockedError(blocked) }; @@ -431,6 +449,10 @@ export async function captureXPostsByIds( downloadMedia: input.downloadMedia ? (args) => input.downloadMedia!(args, loginDownload) : loginDownload, pauseMs: () => xRequestPauseMs(), pause, + // X refused a page: the X stop, recorded at once (review 1 F1). + noteXStop: (why) => recordXStop(why, paths), + // Any reader of this job that met X's stop (an avatar's 429) halts it. + xStopped: () => Boolean(currentJobContext()?.xStop), articleImagePauseMs: () => ARTICLE_IMAGE_PAUSE_MS + Math.floor(Math.random() * ARTICLE_IMAGE_PAUSE_MS), }); } @@ -682,7 +704,18 @@ const CHECKPOINT_EVERY_MS = 60_000; const CURSOR_LINE = /\]\[debug\]\s+Cursor:\s+(\S+)\s*$/; const DEBUG_LINE = /\]\[debug\]/; -const RATE_LIMIT_LINE = /Waiting for .*rate limit|429 Too Many Requests/i; +// gallery-dl's rate-limit lines: its wait ("Waiting for … (rate limit)", an +// older run's), its abort ("[twitter][error] Rate limit exceeded") and a bare 429. +const RATE_LIMIT_LINE = /Waiting for .*rate limit|429 Too Many Requests|rate limit exceeded/i; + +// Does this stderr line say X answered a rate limit, or a bot check (a +// challenge)? Either is the X stop (review 1 F1). +export function xStopLine(line: string): "a rate limit (gallery-dl)" | "a bot check (gallery-dl)" | null { + if (DEBUG_LINE.test(line)) return null; + if (RATE_LIMIT_LINE.test(line)) return "a rate limit (gallery-dl)"; + if (xBlockLine(line) && xBlockKind(line) === "challenge") return "a bot check (gallery-dl)"; + return null; +} const STDERR_TAIL_LINES = 20; export type GalleryDlCheckpoint = { posts: Post[]; cursor: string }; @@ -1055,6 +1088,19 @@ async function galleryDlLoginFor( return { cookies: choice.cookies, cookieFile: choice.cookieFile }; } +// X ANSWERED THIS RUN 429 (gallery-dl waited it out between pages): X is left +// alone for 15 minutes after it — the cooldown the network guard refuses +// every X job with (lane x-sittings, rule 6). Best effort: a failed write is +// logged, never thrown. +async function noteXRateLimit(onLog?: (line: string) => void, why = "a rate limit (gallery-dl)"): Promise<void> { + try { + const until = await recordXStop(why, getPaths()); + onLog?.(`X is left alone until ${new Date(until).toISOString().slice(11, 16)} UTC (15 minutes after its rate limit): no X job starts before then.`); + } catch (err) { + onLog?.(`X's rate-limit cooldown could not be recorded: ${(err as Error).message}`); + } +} + // Feed a pipe to `onLine` a line at a time; resolves once it has closed. function readLines( input: Readable | null | undefined, @@ -1290,12 +1336,21 @@ async function walkSearchWindows( stream.pushStdout(line); maybeCheckpoint(); }); + // X'S STOP, THE MOMENT ITS LINE IS SEEN (review 1 F1/F2): recorded at + // once and the run ended — never waited out and paged on. + let xStopped: Promise<void> | null = null; const stderrDone = readLines(subprocess.stderr, (line) => { stream.pushStderr(line); + const why = xStopLine(line); + if (why && !xStopped) { + xStopped = noteXRateLimit(onLog, why); + subprocess.kill("SIGTERM"); + } maybeCheckpoint(); }); const res = await subprocess; drain?.removeEventListener("abort", onDrain); + if (xStopped) await xStopped; await Promise.all([stdoutDone, stderrDone]); await checkpoints; @@ -1314,7 +1369,9 @@ async function walkSearchWindows( maxId: stream.oldestId ?? windowStart.maxId, }; if (stream.rateLimited) { - onLog?.("[rate-limit] X throttled this search — gallery-dl paused between pages."); + onLog?.(`[rate-limit] X answered this search with a rate limit: the walk stops at ${here.since} – ${here.until}; a later sitting resumes there.`); + if (!xStopped) await noteXRateLimit(onLog); + return stopped(here, { rateLimited: true }); } onLog?.( `${windowStart.since} – ${windowStart.until}: read ${stream.distinct} post(s), ${stream.newPosts} new` + @@ -1565,11 +1622,19 @@ export const xGalleryDlFetcher: SocialFetcher = { subprocess.kill(); } }); + // X'S STOP, THE MOMENT ITS LINE IS SEEN (review 1 F1/F2): recorded at + // once and the run ended at its last page. + let xStopped: Promise<void> | null = null; const stderrDone = readLines(subprocess.stderr, (line) => { if (stream.pushStderr(line)) { betweenPages = true; if (input.drain?.aborted) stopForDrain(); } + const why = xStopLine(line); + if (why && !xStopped) { + xStopped = noteXRateLimit(onLog, why); + subprocess.kill("SIGTERM"); + } maybeCheckpoint(); }); @@ -1577,6 +1642,7 @@ export const xGalleryDlFetcher: SocialFetcher = { input.drain?.removeEventListener("abort", onDrain); await Promise.all([stdoutDone, stderrDone]); await checkpoints; + if (xStopped) await xStopped; const spawnError = `${res.code ?? ""} ${res.message ?? ""}`; if (res.failed && /ENOENT/.test(spawnError) && stream.distinct === 0) { @@ -1586,13 +1652,13 @@ export const xGalleryDlFetcher: SocialFetcher = { } const posts = stream.finish(); - if (stream.rateLimited) { + const rateLimitedHere = stream.rateLimited; + if (rateLimitedHere) { onLog?.( - "[rate-limit] X throttled this run — gallery-dl paused between pages. " + - (cookieFile || cookies - ? "Consider a longer sync interval." - : "This is a guest (no-credential) run; guest quota is much smaller."), + "[rate-limit] X answered this run with a rate limit: gallery-dl stopped at its last page. " + + (cookieFile || cookies ? "" : "This is a guest (no-credential) run; guest quota is much smaller."), ); + if (!xStopped) await noteXRateLimit(onLog); } onLog?.( `gallery-dl read ${stream.distinct} post(s): ${stream.newPosts} new` + @@ -1638,6 +1704,10 @@ export const xGalleryDlFetcher: SocialFetcher = { }; } + // Stopped at X's rate limit: what was read is kept, and the walk resumes + // from its last page in a later sitting. + if (rateLimitedHere) return { posts, complete: false, cursor: resumeAt, rateLimited: true }; + if (stoppedAtKnown) return { posts, complete: true, caughtUp: true }; if (res.isCanceled || signal.aborted || res.timedOut) { diff --git a/common/social/xPlaywrightFetcher.ts b/common/social/xPlaywrightFetcher.ts @@ -125,6 +125,23 @@ function mergeTweet( return merged; } +// REFUSED (lane x-sittings, review 2 G1, the operator's ruling): this reader +// reads no response status and no refusal or challenge page, so a 429 from X +// would be scrolled past and reported as a complete walk, with no X stop and +// no place to continue from. Until it can tell X's refusals (and keep a +// place), no X job runs it: fetchPosts refuses the channel, and fetch() below +// refuses too, for any caller that reaches it another way. +export const X_PLAYWRIGHT_REFUSED = (slug: string) => + `${slug}'s post fetcher is x-playwright (the Playwright fallback), which cannot tell when X refuses or rate-limits ` + + "it, so it is refused: set the channel's postFetcher to x-gallery-dl (the channel page → Configure → scraping " + + `method, or pnpm ops channel-config --json '{"slug":"${slug}","patch":{"postFetcher":"x-gallery-dl"}}'), then fetch again. Nothing was asked of X.`; + +// Always: no setting, environment variable or option turns the refusal off. +// Lifting it is a code change, made once this reader sees X's refusals. +export function xPlaywrightRefused(): boolean { + return true; +} + export const xPlaywrightFetcher: SocialFetcher = { id: "x-playwright", label: "X / Twitter (Playwright fallback)", @@ -155,6 +172,10 @@ export const xPlaywrightFetcher: SocialFetcher = { }, async fetch(input: PostFetchInput): Promise<PostFetchResult> { + // Refused before anything opens (review 2 G1). + if (xPlaywrightRefused()) { + return { posts: [], complete: false, error: X_PLAYWRIGHT_REFUSED(input.channelSlug || "This channel") }; + } const { accountUrl, channelSlug, since, seenIds, limit, signal, onLog } = input; const paths = getPaths(); diff --git a/common/social/xPostCapture.test.ts b/common/social/xPostCapture.test.ts @@ -15,6 +15,7 @@ import type { PageLike } from "./playwrightRuntime"; import { captureXPosts, classifyXPostSnapshot, + X_STOPPED_CAPTURE, shootXPost, type XCaptureDeps, type XPostSnapshot, @@ -501,3 +502,45 @@ process.stdout.write(tag + "\\thttps://pbs.example/77.jpg\\t" + file + "\\n"); delete process.env.FAKE_MODE; } }); + +// LANE X-SITTINGS, review 1 F1: a page X refused ("Something went wrong", +// "rate limit exceeded") is a refusal like a 429 — the run records the X stop +// through its deps, at once, and stops there. +test("run: a refused page records the X stop and stops the run", async () => { + const h = harness({ "11": [post()], "22": [page("Something went wrong. Try reloading. Retry")], "33": [post()] }); + const stops: string[] = []; + const res = await captureXPosts(await input(["11", "22", "33"]), { ...h.deps, noteXStop: async (why) => void stops.push(why) }); + assert.deepEqual(stops, ["a refused page to a capture"]); + assert.match(res.stoppedEarly ?? "", /Stopped at 22/); + assert.deepEqual(res.outcomes.map((o) => o.id), ["11", "22"]); + assert.equal(classifyXPostSnapshot(page("Rate limit exceeded")).refused, true); +}); + +// LANE X-SITTINGS, review 2 G2: once any reader of the job met X's stop (an +// avatar's 429), the capture loads no further page; three pages in a row that +// would not render record the stop. +test("run: a stop met by another reader of the job halts the capture before its next page load", async () => { + const h = harness({ "11": [post()], "22": [post()], "33": [post()] }); + let stoppedNow = false; + const res = await captureXPosts(await input(["11", "22", "33"]), { + ...h.deps, + // The first post's media download is where "the avatar's 429" landed. + downloadMedia: async (a) => { + const r = await h.deps.downloadMedia(a); + stoppedNow = true; + return r; + }, + xStopped: () => stoppedNow, + }); + assert.equal(res.stoppedEarly, X_STOPPED_CAPTURE); + assert.deepEqual(res.outcomes.map((o) => o.id), ["11"]); + assert.deepEqual(h.downloads, ["11"], "no page or download after the stop"); +}); + +test("run: three pages in a row that would not render record the X stop", async () => { + const h = harness({ "11": [page("")], "22": [page("")], "33": [page("")], "44": [post()] }); + const stops: string[] = []; + const res = await captureXPosts(await input(["11", "22", "33", "44"]), { ...h.deps, noteXStop: async (w) => void stops.push(w) }); + assert.deepEqual(stops, ["three pages in a row it would not render, to a capture"]); + assert.match(res.stoppedEarly ?? "", /3 posts in a row failed/); +}); diff --git a/common/social/xPostCapture.ts b/common/social/xPostCapture.ts @@ -194,6 +194,9 @@ export type XPostVerdict = { // Set when the run must stop here: the next post would meet the same page. stop?: string; error?: string; + // X REFUSED THE PAGE ("Something went wrong", "rate limit exceeded"): a + // refusal like a 429 — the X stop is recorded (review 1 F1). + refused?: true; }; // What a snapshot means. Pure, so every marker is testable without a browser. @@ -217,6 +220,7 @@ export function classifyXPostSnapshot( state: "error", error: `X answered “Something went wrong” instead of the ${noun}.`, stop: "X is refusing pages right now; stopping rather than asking again.", + refused: true, }; } if (DELETED_TEXT.some((re) => re.test(s.text))) return { state: "deleted" }; @@ -355,6 +359,14 @@ export type XCaptureDeps = { // A page in the logged-in profile. Opened on the first shot, closed at the // end of the run. openPage: () => Promise<{ page: PageLike; close: () => Promise<void> }>; + // X REFUSED a page or the media (a rate limit, a bot check): the X stop, + // recorded at once (jobs/downloadBackoff.ts recordXStop in production). + noteXStop?: (why: string) => Promise<unknown>; + // Has this job met X's stop (a refusal recorded by any reader inside it — + // an avatar's 429, an article image's)? Asked before every page load: a + // capture asks X nothing more once it has (review 2 G2). Production: the + // job context's xStop. + xStopped?: () => boolean; // One post's media into `dir` (gallery-dl in production). downloadMedia: (args: { id: string; @@ -374,6 +386,23 @@ export type XCaptureDeps = { // failing every post should not page through the rest of the list. const STOP_AFTER_ERRORS = 3; +export const X_STOPPED_CAPTURE = + "X refused this capture (a rate limit, a bot check or a page it would not render): the X stop is recorded and no further page is loaded in this job; the rest are left for a later sitting."; + +// The capture's halt (review 2 G2): the stop noted in this run, or met by any +// reader of this job. +function haltFor(deps: Pick<XCaptureDeps, "noteXStop" | "xStopped">) { + let noted = false; + return { + note: async (why: string) => { + noted = true; + await deps.noteXStop?.(why); + }, + halted: () => noted || (deps.xStopped?.() ?? false), + }; +} + + // The capture loop: per id, what is owed (captureWork), the shot, the media, // the record. Every post's record is written as soon as that post is done, so // a cancel or a crash loses at most the post in hand. @@ -403,6 +432,7 @@ export async function captureXPosts( let errorsInARow = 0; let browser: { page: PageLike; close: () => Promise<void> } | undefined; + const halt = haltFor(deps); const contact = async () => { if (contacts++ > 0) await deps.pause(deps.pauseMs(), signal); }; @@ -424,6 +454,7 @@ export async function captureXPosts( try { for (const [i, id] of input.ids.entries()) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); if (input.drain?.aborted) return stopped("Drained; the rest are left for a later run."); const dir = postCaptureDir(input.outDir, id); @@ -463,6 +494,7 @@ export async function captureXPosts( let stop: string | undefined; if (work.shot || threadOwed) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); await contact(); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); browser ??= await deps.openPage(); @@ -499,6 +531,7 @@ export async function captureXPosts( threadError = res.error ?? `The page showed the post as ${res.state}.`; } stop = res.stop; + if (res.refused) await halt.note("a refused page to a capture"); if (res.thread) { if ("thread" in res.thread) thread = res.thread.thread; else if ("none" in res.thread) threadNone = res.thread.none; @@ -515,6 +548,7 @@ export async function captureXPosts( // download: X has nothing to give for a deleted or walled one. const postIsThere = state === undefined || state === "captured"; if (work.media && postIsThere && !stop) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); await contact(); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); await mkdir(dir, { recursive: true }); @@ -548,6 +582,7 @@ export async function captureXPosts( let article: ArticleCaptureRecord | undefined = existing?.article; let articleFailed = false; if (work.article && articleLink && (state === undefined || state === "captured") && !stop) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); await contact(); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); browser ??= await deps.openPage(); @@ -564,6 +599,7 @@ export async function captureXPosts( // A run that only read the article learns of the post only that it // linked to a readable article. state ??= article.state === "captured" ? "captured" : "error"; + if (got.refused) await halt.note("a refusal to an article (its page or an image) in a capture"); if (got.stop) { stop = got.stop; if (article.state === "login-wall") needsCookies = true; @@ -621,6 +657,9 @@ export async function captureXPosts( } errorsInARow = finalState === "error" || articleFailed ? errorsInARow + 1 : 0; if (errorsInARow >= STOP_AFTER_ERRORS) { + // Pages that would not render, three in a row: X's bot check as + // often as not — the X stop (review 2 G2). + await halt.note("three pages in a row it would not render, to a capture"); return stopped( `${STOP_AFTER_ERRORS} posts in a row failed; stopping rather than paging through the rest.`, ); @@ -695,8 +734,10 @@ async function captureXAvatarsOnly(input: PostCaptureInput, deps: XCaptureDeps): onLog?.(why); return done({ stoppedEarly: why, ...extra }); }; + const halt = haltFor(deps); try { for (const [i, id] of picks.entries()) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); if (input.drain?.aborted) return stopped("Drained; the rest are left for a later run."); if (contacts++ > 0) await deps.pause(deps.pauseMs(), signal); @@ -713,6 +754,7 @@ async function captureXAvatarsOnly(input: PostCaptureInput, deps: XCaptureDeps): if (res.state !== "captured") { const why = res.error ?? `the page showed the post as ${res.state}`; onLog?.(`${id}: no avatar read — ${why}.`); + if (res.refused) await halt.note("a refused page to a capture"); if (res.stop) { return stopped(`${res.stop} Stopped at ${id}; the rest are left for a later run.`, { needsCookies: res.state === "login-wall", @@ -720,6 +762,7 @@ async function captureXAvatarsOnly(input: PostCaptureInput, deps: XCaptureDeps): } errorsInARow = res.state === "error" ? errorsInARow + 1 : 0; if (errorsInARow >= STOP_AFTER_ERRORS) { + await halt.note("three pages in a row it would not render, to a capture"); return stopped(`${STOP_AFTER_ERRORS} pages in a row failed; stopping rather than paging through the rest.`); } continue; @@ -784,8 +827,10 @@ async function captureXContextOnly(input: PostCaptureInput, deps: XCaptureDeps): onLog?.(why); return done({ stoppedEarly: why, ...extra }); }; + const halt = haltFor(deps); try { for (const [i, { id, existing }] of picks.entries()) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); if (input.drain?.aborted) return stopped("Drained; the rest are left for a later run."); if (contacts++ > 0) await deps.pause(deps.pauseMs(), signal); @@ -804,6 +849,7 @@ async function captureXContextOnly(input: PostCaptureInput, deps: XCaptureDeps): if (res.state !== "captured") { const why = res.error ?? `the page showed the post as ${res.state}`; onLog?.(`${id}: no context read — ${why}.`); + if (res.refused) await halt.note("a refused page to a capture"); summary.failed.push({ id, error: why }); if (res.stop) { return stopped(`${res.stop} Stopped at ${id}; the rest are left for a later run.`, { @@ -812,6 +858,7 @@ async function captureXContextOnly(input: PostCaptureInput, deps: XCaptureDeps): } errorsInARow = res.state === "error" ? errorsInARow + 1 : 0; if (errorsInARow >= STOP_AFTER_ERRORS) { + await halt.note("three pages in a row it would not render, to a capture"); return stopped(`${STOP_AFTER_ERRORS} pages in a row failed; stopping rather than paging through the rest.`); } continue; diff --git a/common/social/xSessionBroker.test.ts b/common/social/xSessionBroker.test.ts @@ -13,7 +13,7 @@ import path from "node:path"; import type { Paths } from "../lib/paths"; import type { ChromiumLike } from "./playwrightRuntime"; import { writeXBrowserRecord } from "./xBrowser"; -import { refreshXCookies, xCookieFile, xProfileDir } from "./xSessionBroker"; +import { connectXAccount, readXSessionStatus, refreshXCookies, xCookieFile, xJarRefreshedFile, xProfileDir } from "./xSessionBroker"; const TMP = mkdtempSync(path.join(os.tmpdir(), "xl-broker-")); after(() => rm(TMP, { recursive: true, force: true })); @@ -70,7 +70,8 @@ function fakeChromium(answers: Record<string, Cookie[] | Error>) { let n = 0; async function corpus(opts: { jar?: "logged-in" | "logged-out"; recorded?: boolean }) { - const paths = { transcriptsDir: path.join(TMP, `corpus-${++n}`) } as Paths; + const root = path.join(TMP, `corpus-${++n}`); + const paths = { transcriptsDir: root, autoQueueStateFile: path.join(root, ".auto-queue", "state.json") } as Paths; await mkdir(xProfileDir(paths), { recursive: true }); if (opts.recorded) { await writeXBrowserRecord( @@ -155,3 +156,41 @@ test("the bundled build cannot open the profile: the recorded browser reads it", assert.deepEqual(launches, ["bundled", SYSTEM_EXE]); assert.match(await jarText(paths), /auth_token\tVIA-RECORD/); }); + +test("lane x-sittings: a refresh is STAMPED, and the jar's refresh time is the stamp, not the jar's mtime (gallery-dl rewrote the jar after every run)", async () => { + const paths = await corpus({ jar: "logged-in", recorded: true }); + // A jar from before the stamp: its time is its mtime. + const old = new Date(Date.now() - 3 * 3600_000); + const { utimes } = await import("node:fs/promises"); + await utimes(xCookieFile(paths), old, old); + assert.equal((await readXSessionStatus(paths)).cookiesUpdatedAt, old.toISOString()); + // A Refresh writes the stamp beside the jar. + const { chromium } = fakeChromium({ bundled: [cookie("auth_token", "FRESH")] }); + const before = Date.now(); + const status = await refreshXCookies(paths, { chromium }); + const stamp = JSON.parse(await readFile(xJarRefreshedFile(paths), "utf8")); + assert.equal(stamp.version, 1); + assert.ok(Date.parse(stamp.at) >= before - 1000); + assert.equal(status.cookiesUpdatedAt, new Date(Date.parse(stamp.at)).toISOString()); + // Anything else rewriting the jar (gallery-dl's cookies-update, a copy, touch) moves its mtime, not its refresh. + const later = new Date(Date.now() + 3600_000); + await utimes(xCookieFile(paths), later, later); + assert.equal((await readXSessionStatus(paths)).cookiesUpdatedAt, status.cookiesUpdatedAt); +}); + +test("review 1 F9: Connect and Refresh ask X, so they are refused during X's 15-minute stop — with when it ends — and when the stop cannot be read", async () => { + const { recordXStop } = await import("../jobs/downloadBackoff"); + const { writeFile: wf, mkdir: md } = await import("node:fs/promises"); + const paths = await corpus({ jar: "logged-in", recorded: true }); + const { chromium, launches } = fakeChromium({ bundled: [cookie("auth_token", "FRESH")] }); + await recordXStop("a rate limit", paths); + await assert.rejects(refreshXCookies(paths, { chromium }), /^Error: Refresh cookies is refused until \d\d:\d\d UTC \(1[45] min\): X answered a rate limit or a bot check/); + await assert.rejects(connectXAccount(paths, { chromium }), /^Error: Connect X account is refused until/); + assert.deepEqual(launches, [], "no browser was opened"); + assert.match(await jarText(paths), /OLD-LOGIN/, "the jar is untouched"); + // A stop that cannot be read refuses too. + const p2 = await corpus({ jar: "logged-in", recorded: true }); + await md(path.dirname(p2.autoQueueStateFile), { recursive: true }); + await wf(p2.autoQueueStateFile, "{ broken"); + await assert.rejects(refreshXCookies(p2, { chromium }), /cannot be read/); +}); diff --git a/common/social/xSessionBroker.ts b/common/social/xSessionBroker.ts @@ -27,8 +27,9 @@ import path from "node:path"; import { readFile, rm, stat } from "node:fs/promises"; import { execa } from "execa"; -import { writeFileAtomic } from "../lib/jsonFile-server"; +import { readJsonFile, writeFileAtomic, writeJsonAtomic } from "../lib/jsonFile-server"; import type { Paths } from "../lib/paths"; +import { xStopRemainingMs } from "../jobs/downloadBackoff"; import { importPlaywright, type BrowserContextLike, @@ -57,12 +58,37 @@ export function xCookieFile(paths: Paths): string { return path.join(paths.transcriptsDir, ".x-session", "cookies.txt"); } +// WHEN THE JAR WAS LAST REFRESHED (lane x-sittings): the broker's own stamp, +// written beside the jar by Connect and Refresh (writeCookieJar, the jar's one +// writer), `{version: 1, at: <iso>}`. Not the jar's mtime: gallery-dl rewrote +// the jar after every run (its `cookies-update`, on by default — now passed +// off, xGalleryDlFetcher.ts), so the mtime said "refreshed" after every fetch, +// the fresh-jar rule never bit inside a chain of fetches, and a sitting keyed +// to it would never end (jobs/xSitting.ts). +export function xJarRefreshedFile(paths: Paths): string { + return path.join(paths.transcriptsDir, ".x-session", "refreshed.json"); +} + +// ABSENT: undefined (a jar from before the stamp: its mtime is its time). +// THERE BUT UNREADABLE: the epoch (review 1 F7) — fail closed: the jar reads +// as never refreshed (the fresh-jar rule refuses) and no new sitting begins. +const UNREADABLE_STAMP = new Date(0).toISOString(); + +async function readRefreshedAt(paths: Paths): Promise<string | undefined> { + const read = await readJsonFile(xJarRefreshedFile(paths)).catch(() => ({ ok: false as const, reason: "unreadable" as const })); + if (!read.ok) return read.reason === "absent" ? undefined : UNREADABLE_STAMP; + const at = (read.value as { at?: unknown } | null)?.at; + return typeof at === "string" && Number.isFinite(Date.parse(at)) ? new Date(Date.parse(at)).toISOString() : UNREADABLE_STAMP; +} + export type XSessionStatus = { // A profile directory exists on disk. hasProfile: boolean; // A cookie jar has been exported. hasCookies: boolean; - // When the cookie jar was last written. + // When the cookie jar was last REFRESHED (Connect / Refresh): the broker's + // stamp (xJarRefreshedFile); for a jar written before the stamp existed, + // the jar's mtime. cookiesUpdatedAt?: string; // True when the exported jar carries the session cookie X actually // authenticates with. A jar without it is present-but-useless. @@ -83,7 +109,7 @@ export async function readXSessionStatus(paths: Paths): Promise<XSessionStatus> try { const st = await stat(cookieFile); hasCookies = true; - cookiesUpdatedAt = new Date(st.mtimeMs).toISOString(); + cookiesUpdatedAt = (await readRefreshedAt(paths)) ?? new Date(st.mtimeMs).toISOString(); const text = await readFile(cookieFile, "utf8"); looksAuthenticated = text.includes(AUTH_COOKIE); } catch { @@ -179,6 +205,24 @@ function firstLine(err: unknown): string { // Playwright is imported dynamically: this module must stay importable on a // host with no browsers installed (the Docker build image), where only the // status/read helpers above are ever called. +// A CONNECT OR A REFRESH ASKS X (it loads x.com): refused while X's +// 15-minute stop after a rate limit or a bot check lasts (review 1 F9), with +// when it ends — and while that stop cannot be read. +export async function xStopRefusalForSession(paths: Paths, what: string, now: number = Date.now()): Promise<string | null> { + let ms: number; + try { + ms = await xStopRemainingMs(paths, now); + } catch (err) { + return `${what} is refused: X's rate-limit stop cannot be read (${(err as Error).message}), and ${what.toLowerCase()} loads x.com.`; + } + if (ms <= 0) return null; + const until = new Date(now + ms).toISOString().slice(11, 16); + return ( + `${what} is refused until ${until} UTC (${Math.ceil(ms / 60_000)} min): X answered a rate limit or a bot check, ` + + `and ${what.toLowerCase()} loads x.com. Press it again after ${until} UTC.` + ); +} + export async function connectXAccount( paths: Paths, opts: { @@ -192,6 +236,8 @@ export async function connectXAccount( display?: HeadedDisplayLaunchDeps; } = {}, ): Promise<XSessionStatus & { browser: string; display: string }> { + const stopped = await xStopRefusalForSession(paths, "Connect X account"); + if (stopped) throw new Error(stopped); const log = opts.onLog ?? (() => {}); const profileDir = xProfileDir(paths); // The profile directory is made by launchHeadedContext, once a display is found. @@ -321,6 +367,8 @@ export async function refreshXCookies( paths: Paths, opts: ProfileLaunchOpts = {}, ): Promise<XSessionStatus> { + const stopped = await xStopRefusalForSession(paths, "Refresh cookies"); + if (stopped) throw new Error(stopped); const log = opts.onLog ?? (() => {}); const profileDir = xProfileDir(paths); if (!(await exists(profileDir))) { @@ -378,6 +426,8 @@ async function writeCookieJar( mkdir: true, mode: 0o600, }); + // The refresh, stamped: what the fresh-jar rule and X's sitting read. + await writeJsonAtomic(xJarRefreshedFile(paths), { version: 1, at: new Date().toISOString() }, { mkdir: true }); const authed = cookies.some((c) => c.name === AUTH_COOKIE); log( `Exported ${cookies.length} X cookie(s) to ${file}` + @@ -385,8 +435,14 @@ async function writeCookieJar( ); } -// Forget the stored session entirely (profile + exported jar). +// Forget the stored LOGIN: the profile, the exported jar and its refresh +// stamp. NOT what describes the ACCOUNT and its use (review 1 F3): the +// operator's suspended mark (account.json), the sitting (sitting.json) and X's +// job count (job-starts.json) stay; X's 15-minute stop is not here at all. +// Clearing those is its own act (Mark ok; a new sitting at the next Refresh). export async function clearXSession(paths: Paths): Promise<void> { - await rm(path.dirname(xCookieFile(paths)), { recursive: true, force: true }); + await rm(xProfileDir(paths), { recursive: true, force: true }); + await rm(xCookieFile(paths), { force: true }); + await rm(xJarRefreshedFile(paths), { force: true }); } diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -60,6 +60,50 @@ - `fetch-windows` lists the window under `atRecordingEnd`. `umtool fetch --dry-run` says "saved-video, clamped at the recording's end", and `umtool window` / `timeline insert` say so when the clip is written. - The render holds the clip's end at the recording's last second, never padding with black or silence. +- **X is asked in small, uneven sittings.** The archive's X account was suspended after one sitting of a trending + read and 12 timeline fetches back to back, each 5-6 minutes after the last. + - A cookie refresh (Refresh cookies or Connect X account on /cookies) now admits at most **4 X job starts** + (`social.x.sittingJobs`, 1-6; it cannot be set higher). The 5th is refused when it is queued, or ends + **deferred** when its turn comes: "This X sitting is used up: 4 of 4 X jobs started since the cookies were + refreshed at 14:02 UTC … A new Refresh cookies on /cookies starts the next sitting." Nothing retries it. + - A sitting is **one kind**, set by its first job: timelines (account fetches, captures, availability checks, + an import) or browse (trending reads, X searches, a library's captures). A job of the other kind waits for + the next Refresh, saying why. + - **The gap before an X job is drawn anew each time**, 5-12 minutes by default (set in the X account session; + never below 5). The job's log says what was drawn: "waiting 8m41s (a 9m02s gap drawn from 5-12 min)". + - **At most 6 X jobs start in any hour** (was 12). The daily 150 is unchanged. + - A refresh is now the only thing that resets the cookies' age. gallery-dl rewrote the cookie file after every + fetch, so the file's time said "refreshed" after each one, and a chain of fetches could stay inside the + 60-minute limit. gallery-dl no longer writes the file, and the refresh time is recorded on its own. + - **A 429 from X stops every kind of X job for 15 minutes**: fetches, syncs, X runs, captures and checks too, + where before only trending reads and captures waited. A fetch that X rate-limited now records the 15 minutes + as well. + - **Mark suspended** on /cookies (or `pnpm ops x-session --json '{"accountState":"suspended"}'`) records that + the X account is suspended. While it is marked, deleted-post checks and captures with screenshots are refused, + because a suspended account may not see posts that still exist. Every other X job's log says so. **Mark ok** + lifts it. + - /cookies shows the sitting on X's row ("Sitting: 2 of 4 used, 2 left · timelines · began 14:02 UTC"), the + 15-minute wait after a 429 and the account's state. `pnpm ops get x-session` reports `sitting`, `account`, + `cooldown` and `refusedBy`. + - **One 15-minute stop for any rate limit or bot check from X**, whoever met it: gallery-dl, yt-dlp on an X + address (it used to get a 1-minute backoff), a capture whose pages X refused, a post's media download. + gallery-dl now stops at X's rate limit instead of waiting it out inside the same job; the job keeps what it + read and ends **deferred**, saying so. Refresh cookies and Connect X account are refused until the stop ends. + - **One X job reads at most 300 posts** (`social.x.maxPostsPerJob`, 20-400): a sync, a backfill or a search + then saves its place, and the next sitting continues it. + - A library's media-only capture is now an X job like the others: in the sitting, the cap and the gap. + - **Forget session keeps the suspended mark, the sitting and X's job count.** While the account is marked + suspended, nothing is written as deleted or unavailable from X's answers, video checks and outcomes included. + - The drawn gap is always at least 3 minutes wide, whatever is set. + - Nothing ends the 15-minute stop early except **Clear the X stop** on /cookies (or `pnpm ops x-session + --json '{"clearStop":true,"confirm":true}'`), which asks first and is logged. A clean answer from another + reader and Clear hold no longer end it. + - Inside a capture, a refusal from any part of it (an avatar, an article image, three pages that would not + render) records the stop and ends the capture at once. A capture takes at most 300 posts per job; the rest + are left for a later one. + - **Channels on the Playwright fallback fetcher (`x-playwright`) are refused**, because it cannot tell when X + refuses it. Switch the channel to `x-gallery-dl`. + - Needs a restart of the editor. - **umtool: name a channel once for a whole cut.** - A cut made from two recordings of one channel showed two names for it, the older record's uploader name and the current one. Before, the only fix was to hand-edit `channelTitle` on every clip. diff --git a/editor/app/api/ops/x-session/route.test.ts b/editor/app/api/ops/x-session/route.test.ts @@ -0,0 +1,76 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/x-session/route.test.ts" +// +// Lane x-sittings: the operator marks the X account suspended (or ok) through +// POST /api/ops/x-session, and GET reports it with X's sitting. Temp dirs +// only; nothing reaches X. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-session-route-")); +process.env.WORKER_TOKEN = "test-token"; +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ social: { x: { cookieSource: "profile" } } })); + +const { POST, GET } = await import("./route"); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const AUTH = { authorization: "Bearer test-token" }; + +async function post(body: Record<string, unknown>) { + const res = await POST( + new Request("http://localhost/api/ops/x-session", { + method: "POST", + headers: { ...AUTH, "content-type": "application/json" }, + body: JSON.stringify(body), + }), + ); + return { status: res.status, body: (await res.json()) as { ok: boolean; error?: string; account?: { state: string; note?: string } } }; +} + +async function get() { + const res = await GET(new Request("http://localhost/api/ops/x-session", { headers: AUTH })); + return (await res.json()) as { account: { state: string; alert?: string }; sitting: { used: number; limit: number; left: number } }; +} + +test("POST marks the account suspended with a note, GET shows it as the account's alert, and ok lifts it", async () => { + assert.equal((await get()).account.state, "ok"); + const marked = await post({ accountState: "suspended", note: "read-only since the 21st" }); + assert.equal(marked.status, 200, marked.body.error); + assert.deepEqual([marked.body.account?.state, marked.body.account?.note], ["suspended", "read-only since the 21st"]); + const file = JSON.parse(await readFile(path.join(ROOT, ".x-session", "account.json"), "utf8")); + assert.equal(file.state, "suspended"); + const after = await get(); + assert.equal(after.account.state, "suspended"); + assert.match(after.account.alert ?? "", /^The X account is marked suspended .*read-only since the 21st/); + // The sitting is reported beside it: the default four, none used. + assert.deepEqual([after.sitting.used, after.sitting.limit, after.sitting.left], [0, 4, 4]); + assert.equal((await post({ accountState: "ok" })).status, 200); + assert.equal((await get()).account.state, "ok"); +}); + +test("POST refuses a state it does not know, a stray key and a note that is not a string", async () => { + for (const body of [{ accountState: "banned" }, {}, { accountState: "ok", when: "now" }, { accountState: "ok", note: 3 }]) { + const r = await post(body); + assert.equal(r.status, 400, JSON.stringify(body)); + assert.equal(r.body.ok, false); + } +}); + +test("POST clearStop: unconfirmed answers 409 with what it risks; confirmed clears it", async () => { + const { recordXStop, xStopRemainingMs } = await import("yt-dlp-transcript-common/jobs/downloadBackoff"); + const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); + await recordXStop("a rate limit", getPaths()); + const asked = await post({ clearStop: true }); + assert.equal(asked.status, 409); + assert.match(asked.body.error ?? "", /^Clearing the X stop lets the next X job ask X at once/); + assert.ok((await xStopRemainingMs(getPaths())) > 0); + const done = await post({ clearStop: true, confirm: true }); + assert.equal(done.status, 200); + assert.equal(await xStopRemainingMs(getPaths()), 0); +}); diff --git a/editor/app/api/ops/x-session/route.ts b/editor/app/api/ops/x-session/route.ts @@ -1,15 +1,19 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels"; import { xSessionReport } from "yt-dlp-transcript-common/jobs/networkGuard"; +import { NextResponse } from "next/server"; +import { writeXAccountState } from "yt-dlp-transcript-common/social/xAccountState"; +import { clearXStop } from "yt-dlp-transcript-common/jobs/downloadBackoff"; import { readRoute } from "../_read"; -import { opsFail } from "../_lib"; +import { oneOf, ops, opsFail, optString } from "../_lib"; export const dynamic = "force-dynamic"; // GET /api/ops/x-session[?slug=<channel>] // -> { ok, source, sourceChosen, browserSpec?, profileDir, cookieFile, // hasProfile, hasCookies, looksAuthenticated, cookiesUpdatedAt, -// ageMinutes, maxAgeMinutes, ageChecked, alert, allowed, reason, note? } +// ageMinutes, maxAgeMinutes, ageChecked, alert, cap, sitting, account, +// cooldown, allowed, reason, refusedBy?, note? } // // The X login an X job would use and whether one would start NOW: the // fresh-jar rule's inputs (the source, the exported jar's age, the limit @@ -25,3 +29,32 @@ export async function GET(request: Request) { return { ...(await xSessionReport({ paths: getPaths(), channelSlug: slug })) }; }); } + +// POST /api/ops/x-session {"accountState": "suspended" | "ok", "note"?} +// -> { ok, account: {state, note?, at, by} } +// +// The operator's word on the X account (social/xAccountState.ts): while it is +// "suspended" the network guard refuses the X jobs that record posts as +// deleted or unavailable, and every other X job logs it. Nothing is asked of +// X; nothing else is written. /cookies has the same control. +// +// POST {"clearStop": true, "confirm"?: true, "note"?} — "Clear the X stop" +// (common/jobs/downloadBackoff.ts clearXStop): the one way X's 15-minute stop +// after a rate limit or a bot check ends before its time. Without "confirm" it +// clears nothing and answers 409 with what it risks; each clear is logged. +export async function POST(request: Request) { + return ops(request, ["accountState", "note", "clearStop", "confirm"], async (body) => { + if (body.clearStop !== undefined) { + if (body.clearStop !== true) return opsFail('"clearStop" must be true'); + if (body.accountState !== undefined) return opsFail('"clearStop" and "accountState" are two acts: send one'); + const note = optString(body, "note"); + const r = await clearXStop(getPaths(), { confirm: body.confirm === true, by: "pnpm ops x-session", ...(note ? { note } : {}) }); + if (!r.ok) return opsFail(r.message, 409, { confirmNeeded: true }); + return NextResponse.json({ ok: true, cleared: r.cleared, message: r.message }); + } + const state = oneOf(body, "accountState", ["suspended", "ok"] as const); + const note = optString(body, "note"); + const account = await writeXAccountState(getPaths(), state, note ? { note } : {}); + return NextResponse.json({ ok: true, account }); + }); +} diff --git a/editor/app/cookies/CookiesBoard.tsx b/editor/app/cookies/CookiesBoard.tsx @@ -13,9 +13,10 @@ import { ageSentence, type CookieRow, type CookieStatusPayload, + type XSittingView, } from "yt-dlp-transcript-common/lib/cookieStatus"; import { usePolledPayload } from "../lib/usePolledPayload"; -import { cookieControlsAction, pressCookieButtonAction } from "./actions"; +import { clearXStopAction, cookieControlsAction, pressCookieButtonAction, setXAccountStateAction } from "./actions"; import { sectionFailed, type CookieControls } from "../lib/cookieControlsTypes"; import { XSessionSection } from "../settings/components/XSessionSection"; import { ArchiveSourcesSection } from "../settings/components/ArchiveSessionSection"; @@ -175,6 +176,116 @@ function Row({ ); } + +// X'S SITTING AND ACCOUNT (lane x-sittings): how many X job starts the last +// Refresh admitted and has left, its kind, when it began; X's cooldown after +// a 429; and the account's state with its one control (Mark suspended / Mark +// ok — `pnpm ops x-session` is the same write). +function XSittingPanel({ view, onStatus }: { view: XSittingView; onStatus: (s: CookieStatusPayload) => void }) { + const [note, setNote] = useState(""); + const [pending, setPending] = useState(false); + const [answer, setAnswer] = useState<{ text: string; ok: boolean } | null>(null); + const suspended = view.account.state === "suspended"; + const mark = async () => { + if (pending) return; + setPending(true); + setAnswer(null); + try { + const r = await setXAccountStateAction(suspended ? "ok" : "suspended", suspended ? undefined : note); + onStatus(r.status); + setAnswer({ text: r.message, ok: r.ok }); + if (r.ok) setNote(""); + } catch (e) { + setAnswer({ text: (e as Error).message || "The mark failed.", ok: false }); + } finally { + setPending(false); + } + }; + const began = view.began ? `began ${hms(view.began)}` : "no refresh on record"; + const kind = view.kind === null ? "no job yet" : view.kind; + return ( + <section aria-label="X sitting" className="flex flex-col gap-2 border-t border-border pt-2"> + <p className="text-sm" aria-label="X sitting count"> + {view.unreadable ? ( + <span className="text-destructive">Sitting unreadable: no X job starts until .x-session/sitting.json is repaired.</span> + ) : ( + <> + Sitting: {view.used} of {view.limit} used, {view.left} left + <span className="text-muted-foreground"> · {kind} · {began}</span> + </> + )} + </p> + {view.left === 0 && !view.unreadable && ( + <p className="text-xs text-muted-foreground">Used up: Refresh starts the next sitting.</p> + )} + {view.cooldownUntil && ( + <div className="flex flex-col gap-2 sm:flex-row sm:items-center"> + <p className="text-xs text-destructive" aria-label="X cooldown"> + X answered a rate limit or a bot check: no X job starts before {hms(view.cooldownUntil)}. + </p> + <button + type="button" + aria-label="Clear the X stop" + disabled={pending} + onClick={async () => { + if ( + !window.confirm( + "Clearing the X stop lets the next X job ask X at once, inside the 15 minutes X was left alone for. " + + "Asking again then is what gets an account limited or locked. Clear it?", + ) + ) + return; + setPending(true); + try { + const r = await clearXStopAction(true); + onStatus(r.status); + setAnswer({ text: r.message, ok: r.ok }); + } finally { + setPending(false); + } + }} + className="w-full rounded-md border border-destructive/60 px-3 py-2 text-sm text-destructive hover:bg-muted disabled:opacity-50 sm:w-auto sm:py-1.5" + > + Clear the X stop + </button> + </div> + )} + {view.account.alert && ( + <p role="alert" aria-label="X account alert" className="text-xs text-destructive break-words"> + {view.account.alert} + </p> + )} + <div className="flex flex-col gap-2 sm:flex-row sm:items-center"> + {!suspended && ( + <input + type="text" + value={note} + onChange={(e) => setNote(e.target.value)} + placeholder="Note (optional)" + aria-label="X account note" + maxLength={300} + className="w-full rounded-md border border-border bg-background px-2 py-1.5 text-sm sm:w-64" + /> + )} + <button + type="button" + onClick={mark} + disabled={pending} + aria-label={suspended ? "Mark X account ok" : "Mark X account suspended"} + className="w-full rounded-md border border-border px-3 py-2 text-sm hover:bg-muted disabled:opacity-50 sm:w-auto sm:py-1.5" + > + {pending ? "Saving…" : suspended ? "Mark ok" : "Mark suspended"} + </button> + </div> + {answer && ( + <p role="status" aria-label="X account mark result" className={`text-xs ${answer.ok ? "text-success" : "text-destructive"}`}> + {answer.text} + </p> + )} + </section> + ); +} + const DISCLOSURE = "border-t border-border pt-2"; const SUMMARY = "cursor-pointer text-sm font-medium"; @@ -296,6 +407,7 @@ export function CookiesBoard({ initial, controls }: { initial: CookieStatusPaylo controls={ctl} gen={gens[row.service] ?? 0} refetch={() => void refetch()} + {...(row.service === "x" && status.xSitting ? { xSitting: status.xSitting, onXStatus: take } : {})} /> ))} </ul> @@ -310,16 +422,21 @@ function ItemsFor({ controls, gen, refetch, + xSitting, + onXStatus, }: { row: CookieRow; take: (s: CookieStatusPayload) => void; controls?: CookieControls; gen: number; refetch: () => void; + xSitting?: XSittingView; + onXStatus?: (s: CookieStatusPayload) => void; }) { return ( <> <Row row={row} onStatus={take}> + {xSitting ? <XSittingPanel view={xSitting} onStatus={onXStatus ?? take} /> : null} {controls ? <Controls row={row} controls={controls} gen={gen} refetch={refetch} /> : null} </Row> {controls && row.service === "odysee" && ( diff --git a/editor/app/cookies/actions.ts b/editor/app/cookies/actions.ts @@ -37,6 +37,8 @@ import { connectForumAt } from "../lib/connectForum"; import { listForumChannels } from "../lib/forumChannels"; import { loadCookieStatus } from "../lib/cookieStatus"; import { loadCookieControls, type CookieControls } from "../lib/cookieControls"; +import { writeXAccountState } from "yt-dlp-transcript-common/social/xAccountState"; +import { clearXStop } from "yt-dlp-transcript-common/jobs/downloadBackoff"; export type CookiePressResult = { ok: boolean; @@ -105,3 +107,37 @@ export async function pressCookieButtonAction(service: string, action: string): // An error may carry a path: drawn as the page draws one. return { ...answer, message: displayText(answer.message), status: await loadCookieStatus(getPaths(), { fresh: action === "recheck" }) }; } + +// THE X ACCOUNT'S STATE, MARKED BY HAND (lane x-sittings): "suspended" refuses +// the X jobs that record posts as deleted or unavailable; "ok" lifts that. The +// same write as `pnpm ops x-session --json '{"accountState":…}'`. Nothing is +// asked of X. Answers the screen's rows read again. +export async function setXAccountStateAction(state: string, note?: string): Promise<CookiePressResult> { + const paths = getPaths(); + let answer: Answer; + if (state !== "suspended" && state !== "ok") { + answer = { ok: false, message: `Not an account state: ${String(state)}` }; + } else { + try { + const r = await writeXAccountState(paths, state, typeof note === "string" && note.trim() ? { note } : {}); + answer = { ok: true, message: r.state === "suspended" ? "Marked suspended." : "Marked ok." }; + } catch (e) { + answer = { ok: false, message: (e as Error).message }; + } + } + return { ...answer, message: displayText(answer.message), status: await loadCookieStatus(paths) }; +} + +// "CLEAR THE X STOP" on /cookies (common/jobs/downloadBackoff.ts clearXStop): +// the page asks the operator to confirm what it risks first; logged. +export async function clearXStopAction(confirm: boolean): Promise<CookiePressResult> { + const paths = getPaths(); + let answer: Answer; + try { + const r = await clearXStop(paths, { confirm: confirm === true, by: "/cookies" }); + answer = { ok: r.ok, message: r.message }; + } catch (e) { + answer = { ok: false, message: (e as Error).message }; + } + return { ...answer, message: displayText(answer.message), status: await loadCookieStatus(paths) }; +} diff --git a/editor/app/lib/cookieControls.ts b/editor/app/lib/cookieControls.ts @@ -7,6 +7,7 @@ // cookieMode), and each forum host's session status. Never the whole settings // object, never a corpus walk. The rows themselves are lib/cookieStatus.ts. +import { xPacingOf } from "./xPacing"; import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths"; import { getSettings, type SiteSettings } from "yt-dlp-transcript-common/lib/settings"; import { displayText } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; @@ -61,6 +62,7 @@ export async function loadCookieControls( initialSource: xSourceForDisplay(xCookieSourceView(resolved)), initialVisibility: xPostsVisibility(st), initialMaxCookieAge: xMaxCookieAgeMinutes(st.social.x), + initialPacing: xPacingOf(st.social.x), }; }), ), diff --git a/editor/app/lib/cookieControlsTypes.ts b/editor/app/lib/cookieControlsTypes.ts @@ -20,6 +20,8 @@ export type XControls = { initialSource: XCookieSourceView; initialVisibility: XPostsVisibility; initialMaxCookieAge: number; + // X in sittings (lib/xSitting.ts): jobs per refresh, the gap's range (min). + initialPacing?: { sittingJobs: number; gapMinMinutes: number; gapMaxMinutes: number }; }; export type ArchiveControls = { initial: ArchivesSettings; session: ArchiveSessionStatus }; export type YtdlpControls = { cookiesFromBrowser: string; cookieMode: string }; diff --git a/editor/app/lib/cookieStatus.ts b/editor/app/lib/cookieStatus.ts @@ -37,6 +37,8 @@ import { forumSessionDir, readForumSessionStatus } from "yt-dlp-transcript-commo import { loadCookieAlerts } from "./cookieAlerts"; import { listForumChannels } from "./forumChannels"; import { runningCookieActions } from "./cookieRefreshGuard"; +import { xSessionReport } from "yt-dlp-transcript-common/jobs/networkGuard"; +import type { XSittingView } from "yt-dlp-transcript-common/lib/cookieStatus"; async function safe<T>(fn: () => Promise<T>, fallback: T): Promise<T> { try { @@ -123,7 +125,17 @@ export async function loadCookieStatus( const forumChannels = await safe(() => listForumChannels(paths, { fresh: opts.fresh === true }), []); - return buildCookieStatus({ + // X's sitting and account (lane x-sittings), read from disk: nothing asks X. + const report = await safe(() => xSessionReport({ paths, now }), null); + const xSitting: XSittingView | undefined = report + ? { + ...report.sitting, + account: report.account, + ...(report.cooldown ? { cooldownUntil: report.cooldown.until } : {}), + } + : undefined; + + const payload = buildCookieStatus({ now, alerts, state, @@ -135,4 +147,5 @@ export async function loadCookieStatus( running: runningCookieActions(), display: { path: displayPath, text: displayText }, }); + return xSitting ? { ...payload, xSitting } : payload; } diff --git a/editor/app/lib/xPacing.ts b/editor/app/lib/xPacing.ts @@ -0,0 +1,18 @@ +// X's sitting and gap settings as the X session controls draw them +// (common/lib/xSitting.ts): each resolved, the default where none is set. +import { + X_GAP_MIN_SPREAD_MINUTES, + X_GAP_DEFAULT_MAX_MINUTES, + X_GAP_DEFAULT_MIN_MINUTES, + parseXGapMinutes, + xSittingJobs, +} from "yt-dlp-transcript-common/lib/xSitting"; + +export function xPacingOf(x: { sittingJobs?: number; gapMinMinutes?: number; gapMaxMinutes?: number } | undefined) { + const gapMinMinutes = parseXGapMinutes(x?.gapMinMinutes) ?? X_GAP_DEFAULT_MIN_MINUTES; + return { + sittingJobs: xSittingJobs(x), + gapMinMinutes, + gapMaxMinutes: Math.max(gapMinMinutes + X_GAP_MIN_SPREAD_MINUTES, parseXGapMinutes(x?.gapMaxMinutes) ?? X_GAP_DEFAULT_MAX_MINUTES), + }; +} diff --git a/editor/app/review/components/XRunConsole.tsx b/editor/app/review/components/XRunConsole.tsx @@ -38,10 +38,12 @@ function age(ms: number): string { } // X's queue gap, as the run waits it between two channels. -function gapText(seconds: number): string { - if (seconds <= 0) return "no gap between channels"; - if (seconds < 120) return `${seconds} s between channels`; - return `${Math.round(seconds / 60)} min between channels`; +function gapText(seconds: number, maxSeconds = seconds): string { + if (maxSeconds <= 0) return "no gap between channels"; + if (maxSeconds < 120) return seconds === maxSeconds ? `${seconds} s between channels` : `${seconds}-${maxSeconds} s between channels`; + const lo = Math.round(seconds / 60); + const hi = Math.round(maxSeconds / 60); + return lo === hi ? `${lo} min between channels` : `${lo}-${hi} min between channels, drawn per channel`; } function when(iso: string | null): string { @@ -338,7 +340,7 @@ export function XRunConsole({ initial }: { initial: XRunConsolePayload }) { Start X run ({chosen.length}) </button> <span className="text-xs text-muted-foreground"> - ≤ {view.maxPosts} posts each · {gapText(view.gapSeconds)} + ≤ {view.maxPosts} posts each · {gapText(view.gapSeconds, view.gapMaxSeconds ?? view.gapSeconds)} </span> </div> {note && ( diff --git a/editor/app/settings/components/SettingsForm.tsx b/editor/app/settings/components/SettingsForm.tsx @@ -28,7 +28,7 @@ import { jobGapSecondsFor } from "yt-dlp-transcript-common/lib/jobGap"; // platform's key is set by hand in settings.json. const JOB_GAP_FIELDS = [ { key: "default", label: "Every platform" }, - { key: "twitter", label: "X" }, + { key: "twitter", label: "X (minimum)" }, { key: "xenforo", label: "Forums" }, { key: "bluesky", label: "Bluesky" }, { key: "instagram", label: "Instagram" }, @@ -125,7 +125,9 @@ export function SettingsForm({ initial }: Props) { only this long after the previous one on the same platform ended; its row on /jobs says how long it still waits. Built in: 20 s everywhere, 300 s for X, 60 s for forums and Bluesky. 0 turns a - gap off. + gap off — except X&apos;s: its gap is drawn anew for each job in + 5–12 min (set in the X account session), and a value here above + 300 s only raises its minimum. </span> </fieldset> <Field diff --git a/editor/app/settings/components/XSessionSection.tsx b/editor/app/settings/components/XSessionSection.tsx @@ -20,6 +20,7 @@ import { refreshXCookiesAction, setXCookieSourceAction, setXMaxCookieAgeAction, + setXPacingAction, type XSessionActionResult, } from "../xSessionActions"; import type { XSessionStatus } from "yt-dlp-transcript-common/social/xSessionBroker"; @@ -37,6 +38,7 @@ export function XSessionSection({ initialSource, initialVisibility, initialMaxCookieAge, + initialPacing = { sittingJobs: 4, gapMinMinutes: 5, gapMaxMinutes: 12 }, onChange, cookiesLink = true, }: { @@ -48,12 +50,17 @@ export function XSessionSection({ initialVisibility: XPostsVisibility; // `social.x.maxCookieAgeMinutes`, resolved (absent = 60; 0 = off). initialMaxCookieAge: number; + // X in sittings: jobs per cookie refresh (1-6) and the gap's range (min). + initialPacing?: { sittingJobs: number; gapMinMinutes: number; gapMaxMinutes: number }; // Told after every action here ends (the /cookies screen re-reads its row). onChange?: () => void; // The one-line link to /cookies (left out when drawn ON /cookies). cookiesLink?: boolean; }) { const [maxAge, setMaxAge] = useState(String(initialMaxCookieAge)); + const [sittingJobs, setSittingJobs] = useState(String(initialPacing.sittingJobs)); + const [gapMin, setGapMin] = useState(String(initialPacing.gapMinMinutes)); + const [gapMax, setGapMax] = useState(String(initialPacing.gapMaxMinutes)); const [status, setStatus] = useState<XSessionStatus>(initial); const [source, setSource] = useState<XCookieSourceView>(initialSource); const [login, setLogin] = useState<XLoginStatus | null>(null); @@ -264,8 +271,78 @@ export function XSessionSection({ unless the cookies were refreshed this recently — press Refresh cookies first. The editor never refreshes them itself: a refresh loads x.com. With the browser login the age cannot be read and is not checked. 0 - turns the check off. X jobs are also spaced 5 minutes apart, and none - starts while X&apos;s cookie alert is up on the dashboard. + turns the check off. None starts while X&apos;s cookie alert is up on + the dashboard, or for 15 minutes after X answers a rate limit. + </p> + + <div className="flex flex-wrap items-center gap-2"> + <label htmlFor="x-sitting-jobs" className="text-sm"> + At most + </label> + <input + id="x-sitting-jobs" + aria-label="x jobs per sitting" + type="number" + min={1} + max={6} + value={sittingJobs} + onChange={(e) => setSittingJobs(e.target.value)} + className="w-16 rounded-md border border-border bg-background px-2 py-1 text-sm" + /> + <span className="text-sm">X jobs per cookie refresh, spaced</span> + <input + aria-label="x gap min minutes" + type="number" + min={5} + max={120} + value={gapMin} + onChange={(e) => setGapMin(e.target.value)} + className="w-16 rounded-md border border-border bg-background px-2 py-1 text-sm" + /> + <span className="text-sm">to</span> + <input + aria-label="x gap max minutes" + type="number" + min={5} + max={120} + value={gapMax} + onChange={(e) => setGapMax(e.target.value)} + className="w-16 rounded-md border border-border bg-background px-2 py-1 text-sm" + /> + <span className="text-sm">min apart</span> + <button + type="button" + aria-label="save x sittings" + disabled={checking} + onClick={() => + startChecking(async () => { + setError(null); + setNote(null); + const res = await setXPacingAction({ + sittingJobs: Number(sittingJobs), + gapMinMinutes: Number(gapMin), + gapMaxMinutes: Number(gapMax), + }); + if (res.ok) { + setNote( + `A refresh now admits ${res.pacing.sittingJobs} X job${res.pacing.sittingJobs === 1 ? "" : "s"}, ` + + `${res.pacing.gapMinMinutes}–${res.pacing.gapMaxMinutes} min apart.`, + ); + } else setError(res.error); + onChange?.(); + }) + } + className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50" + > + Save + </button> + </div> + <p className="text-xs text-muted-foreground"> + One refresh, one sitting: its first job makes it timelines (account + fetches, captures, checks) or browse (trending reads, X searches), and + a job of the other kind waits for the next Refresh. The gap is drawn + anew for each job. At most 6 per sitting and 5 min apart, whatever is + set here. </p> <div className="flex flex-wrap gap-2"> diff --git a/editor/app/settings/page.tsx b/editor/app/settings/page.tsx @@ -14,6 +14,7 @@ import { StreamErrorBoundary } from "../components/StreamErrorBoundary"; import { e2eStreamDelay } from "../lib/streamDelay"; import { xSourceForDisplay } from "../lib/xSourceDisplay"; import { XSessionSection } from "./components/XSessionSection"; +import { xPacingOf } from "../lib/xPacing"; import { xMaxCookieAgeMinutes } from "yt-dlp-transcript-common/social/xCookieSource"; import { ArchiveSourcesSection } from "./components/ArchiveSessionSection"; import { readArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession"; @@ -185,6 +186,7 @@ async function XSection({ settings }: { settings: SiteSettings }) { initialSource={xSource} initialVisibility={xPostsVisibility(settings)} initialMaxCookieAge={xMaxCookieAgeMinutes(settings.social.x)} + initialPacing={xPacingOf(settings.social.x)} /> </StreamFilled> ); diff --git a/editor/app/settings/xSessionActions.ts b/editor/app/settings/xSessionActions.ts @@ -17,6 +17,16 @@ import { revalidatePath } from "next/cache"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { + X_GAP_CEILING_MINUTES, + X_GAP_DEFAULT_MAX_MINUTES, + X_GAP_DEFAULT_MIN_MINUTES, + X_GAP_FLOOR_MINUTES, + X_GAP_MIN_SPREAD_MINUTES, + X_SITTING_DEFAULT_JOBS, + X_SITTING_MAX_JOBS, + X_SITTING_MIN_JOBS, +} from "yt-dlp-transcript-common/lib/xSitting"; +import { clearXSession, connectXAccount, readXSessionStatus, @@ -238,3 +248,40 @@ export async function setXMaxCookieAgeAction(minutes: number): Promise<XMaxCooki revalidatePath("/settings"); return { ok: true, minutes }; } + +// X IN SITTINGS (common/lib/xSitting.ts): the X job starts one cookie refresh +// admits (`social.x.sittingJobs`, 1-6) and the range X's gap is drawn from +// (`gapMinMinutes`-`gapMaxMinutes`, never below 5). A default is written as no +// key. The same keys `pnpm ops settings` writes. +export type XPacingInput = { sittingJobs: number; gapMinMinutes: number; gapMaxMinutes: number }; +export type XPacingResult = { ok: true; pacing: XPacingInput } | { ok: false; error: string }; + +export async function setXPacingAction(input: XPacingInput): Promise<XPacingResult> { + const { sittingJobs, gapMinMinutes, gapMaxMinutes } = input ?? ({} as XPacingInput); + if (!Number.isInteger(sittingJobs) || sittingJobs < X_SITTING_MIN_JOBS || sittingJobs > X_SITTING_MAX_JOBS) { + return { ok: false, error: `Jobs per sitting must be a whole number, ${X_SITTING_MIN_JOBS}–${X_SITTING_MAX_JOBS}.` }; + } + if (!Number.isInteger(gapMinMinutes) || gapMinMinutes < X_GAP_FLOOR_MINUTES || gapMinMinutes > X_GAP_CEILING_MINUTES) { + return { ok: false, error: `The shortest gap must be a whole number of minutes, ${X_GAP_FLOOR_MINUTES}–${X_GAP_CEILING_MINUTES}.` }; + } + if (!Number.isInteger(gapMaxMinutes) || gapMaxMinutes < gapMinMinutes + X_GAP_MIN_SPREAD_MINUTES || gapMaxMinutes > X_GAP_CEILING_MINUTES) { + return { + ok: false, + error: `The longest gap must be a whole number of minutes, at least ${X_GAP_MIN_SPREAD_MINUTES} above the shortest and at most ${X_GAP_CEILING_MINUTES}: a range of one value is a fixed beat.`, + }; + } + try { + await saveSettings( + socialXPatch(({ sittingJobs: _s, gapMinMinutes: _a, gapMaxMinutes: _b, ...rest }) => ({ + ...rest, + ...(sittingJobs !== X_SITTING_DEFAULT_JOBS ? { sittingJobs } : {}), + ...(gapMinMinutes !== X_GAP_DEFAULT_MIN_MINUTES ? { gapMinMinutes } : {}), + ...(gapMaxMinutes !== X_GAP_DEFAULT_MAX_MINUTES ? { gapMaxMinutes } : {}), + })), + ); + } catch (e) { + return { ok: false, error: (e as Error).message }; + } + revalidatePath("/settings"); + return { ok: true, pacing: { sittingJobs, gapMinMinutes, gapMaxMinutes } }; +} diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts @@ -51,6 +51,11 @@ export const E2E_SERVER_ENV: Record<string, string> = { // gets exactly that (pacing.spec, x-session.spec). E2E_JOB_GAP_SECONDS: "0", E2E_X_MAX_COOKIE_AGE_MINUTES: "0", + // X's SITTINGS (common/lib/xSitting.ts) are off on the test server: its fake + // X jobs run many to one corpus with no cookie refresh between them, and of + // both kinds. X's job cap (6 an hour) is NOT off. Honoured only beside + // E2E_TEST_ROUTES=1 (common/jobs/networkGuard.ts e2eSittingsOff). + E2E_X_SITTINGS: "off", E2E_LIVE_CHECK: "skip", WRANGLER_BIN: join(EDITOR_ROOT, "e2e", "fixtures", "bin", "fake-wrangler.mjs"), ARCHILYZER_BRANCH: "main", diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts @@ -41,6 +41,11 @@ import { currentSlot } from "./e2e/testPaths"; // E2E_X_MAX_COOKIE_AGE_MINUTES cookie-age limit are off on the test server // (common/jobs/queueGap.ts, networkGuard.ts); a // value a spec writes into settings.json applies +// (X's drawn gap excepted: E2E_JOB_GAP_SECONDS +// collapses its range) +// E2E_X_SITTINGS off: X's sittings (jobs per cookie refresh, one +// kind each) are off on the test server, beside +// E2E_TEST_ROUTES=1 only (networkGuard.ts) // E2E_BLUESKY_ORIGIN_FILE set per slot (e2e/servers.ts): the file a spec // writes its fake Bluesky's loopback origin into, // which the AppView, bsky.app and the image CDN diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -152,6 +152,9 @@ // pnpm ops get tags eva-collab // pnpm ops get services // pnpm ops get x-session +// pnpm ops x-session --json '{"accountState":"suspended","note":"read-only since the 21st"}' +// pnpm ops x-session --json '{"accountState":"ok"}' +// pnpm ops x-session --json '{"clearStop":true,"confirm":true,"note":"checked by hand"}' // pnpm ops get cookies [fresh] // pnpm ops recheck-service --json '{"service":"rumble"}' // pnpm ops recheck-service --json '{"service":"x"}' @@ -706,6 +709,10 @@ const ACTIONS = [ // stopped re-run once it is OK again ({service}). "recheck-service", "dismiss-service", + // The X account's state as the operator marks it ({accountState: + // "suspended" | "ok", note?}): suspended refuses the X jobs that record + // deleted posts (common/social/xAccountState.ts). `get x-session` reads it. + "x-session", "rerun-service-jobs", "workers", "transcribe-one", @@ -1514,15 +1521,27 @@ 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); and X's JOB CAP:", - " 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 ON", + " allowed, reason (the refusal an X job would get) and refusedBy (alert,", + " jar, cap, sitting, cooldown or suspended); X's JOB CAP:", + " cap {lastHour, perHour: 6, lastDay, perDay: 150, reached, nextAt?} -", + " at most 6 X jobs start in any 60 minutes and 150 in any 24 hours ON", " THIS MACHINE: one count over every kind of X job, whatever the login", " source, cookie spec or channel. A job past it is refused when queued,", " with the time the next may start; one that meets it when its queue", - " starts it ends done, deferred (not failed). A library's media-only", - " capture is not counted. The numbers are constants of the code", + " starts it ends done, deferred (not failed). Every X job counts, a", + " library's media-only capture too. The numbers are constants of the code", " (common/lib/xJobRule.ts): no setting, option or queue raises them.", + " X's SITTING: sitting {began, kind, used, left, limit} - a cookie", + " refresh begins a sitting of at most social.x.sittingJobs X job starts", + " (default 4, 1-6 in the code), of ONE kind fixed by its first job:", + " timelines (account fetches, captures, availability checks, an import)", + " or browse (trending reads, X search walks, a library's captures). A", + " start past it, or of the other kind, is refused (at its start: done,", + " deferred); a new Refresh on /cookies starts the next. account {state,", + " since?, note?, alert?} is the operator's mark (x-session, below);", + " cooldown {until} is X's 15-minute stop after a rate limit or a bot check", + " met by any reader (gallery-dl, yt-dlp, the profile's pages), which", + " refuses every X job and Refresh/Connect.", " <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", @@ -1758,6 +1777,18 @@ export function usage() { ' Asked while a recheck or another press for the service runs (a click,', ' the dashboard\'s, the timer\'s): refused, 409 {busy: true}, never queued.', 'dismiss-service clears a service\'s cookie alert by hand: {"service"}.', + 'x-session marks the X account\'s state by hand: {"accountState":', + ' "suspended" | "ok", "note"?}. While it is suspended, check-post-', + " availability and capture-posts with screenshots on X (the jobs that", + " record a post as deleted or unavailable) are refused, because a", + " suspended account's answers are thinned; every other X job logs it.", + " get x-session and /cookies show it as the account's alert. Nothing is", + " asked of X. Answers {account: {state, note?, at, by}}.", + ' {"clearStop": true, "confirm": true, "note"?} is "Clear the X stop": the', + " one way X's 15-minute stop after a rate limit or a bot check ends early", + " (a clean answer or clear-platform-hold never ends it). Without", + ' "confirm" it clears nothing and answers 409 with what it risks; each', + " clear is logged in .jobs/x-stop-cleared.jsonl.", 'rerun-service-jobs retries every job a service\'s cookie alert stopped, once', ' it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them.', "", diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -988,6 +988,18 @@ test("get x-session is a GET on its route, with an optional channel", () => { assert.equal(parseArgs(["get", "x-session", "some-x"]).path, "/api/ops/x-session?slug=some-x"); assert.match(usage(), /pnpm ops get x-session \[<slug>\]/); assert.match(usage(), /maxAgeMinutes/); + assert.match(usage(), /perHour: 6/); + assert.match(usage(), /sitting \{began, kind, used, left, limit\}/); +}); + +// LANE X-SITTINGS: the operator marks the X account suspended (or ok) by hand. +test("x-session (no get) is a POST that marks the X account's state", () => { + const p = parseArgs(["x-session", "--json", '{"accountState":"suspended","note":"read-only"}']); + assert.equal(p.method, "POST"); + assert.equal(p.path, "/api/ops/x-session"); + assert.deepEqual(p.body, { accountState: "suspended", note: "read-only" }); + assert.equal(parseArgs(["get", "x-session"]).method, "GET"); + assert.match(usage(), /x-session marks the X account's state by hand/); }); // RELEASE 36 LANE A: the clip finder's chain and one video's chat replay.