commit 3c3fad02c41aa3978e7a6a7384fe4b1d5718cdf2 parent af3b84c24f11e996a77b81b8150842cc984d2082 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Sat, 21 Nov 2026 15:53:05 -0500 x-sittings review 1: one 15-minute X stop for every reader, gallery-dl aborts, suspended covers every writer - F1: recordXStop (jobs/downloadBackoff.ts) over applyXStop is the one X stop for any rate limit or bot check: yt-dlp on X (recordDownloadBackoff), any named twitter cooldown, the auto-download unit, gallery-dl timeline/search/ media lines, a trending read's 429 and 403, a capture's refused page or article, the media CDN, an avatar 429. Never X's 60 s exponential backoff. - F2: gallery-dl runs with ratelimit=abort; the stop is recorded the moment its line is seen, the run ends at its last page with its place kept, and the job ends done/deferred, saying so (job context xStop). - F3: Clear session removes the profile, the jar and its stamp only. - F4: the drawn range is always at least 3 minutes wide. - F5: while suspended, captures refuse unless shots and articles are off, the video checks refuse, and inside X jobs writeDownloadOutcome, recordAvailability and writePostCapture keep no "gone" verdict. - F6: E2E_JOB_GAP_SECONDS and E2E_X_MAX_COOKIE_AGE_MINUTES only beside E2E_TEST_ROUTES=1. - F7: the stop file, the refresh stamp and a lost queue-gaps.json fail closed. - F8: social.x.maxPostsPerJob (300, 20-400) for every X walk; a trending read's posts stay within 400; a library's media-only capture counts. - F9: Refresh and Connect are refused during the stop. Co-Authored-By: Claude <noreply@anthropic.com> Diffstat:
42 files changed, 841 insertions(+), 183 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md @@ -377,8 +377,8 @@ get x-session [<slug>] is the X login an X job would use and whether one 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 @@ -388,8 +388,9 @@ get x-session [<slug>] is the X login an X job would use and whether one 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 minutes after a 429, which refuses every X - job. + 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,9 +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 — but X's gap, drawn per job from `social.x.gapMinMinutes`-`gapMaxMinutes`, is collapsed to this value whatever is set. 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_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. 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_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 @@ -519,15 +519,16 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait - **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, 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, and an explicit - `pacing.jobGapSeconds.twitter` above 5 min raises the minimum): `waiting 8m41s (a 9m02s gap drawn from 5-12 + 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 is not). A sitting is **one kind**, fixed by its first job: **timelines** + 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 @@ -542,15 +543,31 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait 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` on X and `capture-posts` with screenshots (the jobs that record a post as deleted - or unavailable) are refused, the capture and the check also drop any "deleted"/"unavailable" verdict if the - mark is made while they run, and every other X job's log says the account is marked suspended. + 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 429 from X stops every X job for 15 minutes.** A trending read, its media, a capture and a gallery-dl - fetch that met X's rate limit record X's cooldown, and the guard 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 …`); `get x-session` shows - `cooldown {until}`. +- **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}`; + `clear-platform-hold {"platform": "twitter"}` is the explicit way to end it early. +- **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. A trending read's posts over both tabs stay within 400. +- **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 @@ -578,10 +595,8 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait 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 diff --git a/SETTINGS.md b/SETTINGS.md @@ -199,7 +199,8 @@ Per-platform settings of the social posts: X's, all chosen in the X account sess | `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 below the minimum. ABSENT: 12. At most 120. | +| `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 @@ -45,7 +45,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, @@ -54,7 +54,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"; @@ -580,7 +579,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/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`); diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts @@ -95,6 +95,7 @@ import { import { instagramJobGuard } from "../jobs/instagramGuard"; import { currentJobContext } from "../lib/jobContext"; import { xJobContextRefusal } from "../lib/xJobRule"; +import { xJobPostLimit } from "../lib/xSitting"; import { INSTAGRAM_QUEUE_KEY, INSTAGRAM_QUEUE_REFUSAL, isInstagramPostsChannelConfig } from "../lib/instagram/channel"; import { detectPlatform } from "../lib/platform"; import { postsMediaDir } from "../social/postCapture"; @@ -414,6 +415,11 @@ 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 }; + // 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, @@ -102,6 +102,7 @@ export const READ_X_TRENDING_RESULT_MARKER = "@@read-x-trending "; // (jobs/downloadBackoff.ts recordPlatformCooldown — the cooldown import-post // already respects), read by this job's enqueue and start. export { X_RATE_LIMIT_HOLD_MS } from "../lib/xJobRule"; +import { X_POSTS_PER_JOB_CEILING } from "../lib/xSitting"; import { X_RATE_LIMIT_HOLD_MS } from "../lib/xJobRule"; const X_PLATFORM = "twitter"; @@ -283,7 +284,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: Math.max(1, Math.min(limits.limits.posts, Math.floor(X_POSTS_PER_JOB_CEILING / Math.max(1, tabs.tabs.length)))) }, ...(topic ? { topic } : {}), probe: ask.probe === true, headed: ask.headed === true, @@ -728,9 +731,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/jobs/downloadBackoff.ts b/common/jobs/downloadBackoff.ts @@ -42,6 +42,9 @@ import { settlePlatformClean, } from "./platformBackoff"; import { staticSleepRequestsSeconds } from "../ytdlp/platformArgs.mjs"; +import { applyXStop, 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,44 @@ 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> { + const until = await mutateDownloadState(paths, (state) => { + prunePlatformPacing(state.download, now); + return applyXStop(state.download, now).until; + }); + const job = currentJobContext(); + if (job) { + if (!job.xStop || job.xStop.until < until) job.xStop = { until, why, at: now }; + 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; +} diff --git a/common/jobs/networkGuard.ts b/common/jobs/networkGuard.ts @@ -67,7 +67,7 @@ import { type XSittingKind, } from "../lib/xSitting"; import { readXAccountState, xAccountAlertLine } from "../social/xAccountState"; -import { heldPlatformRefusal, platformCooldownRemainingMs } from "./downloadBackoff"; +import { heldPlatformRefusal, xStopRemainingMs } from "./downloadBackoff"; import { xRateLimitHoldSentence } from "../lib/xTrending/config"; import { writeJobMeta } from "./jobMeta"; import type { JobSpec } from "./jobSpec"; @@ -233,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); @@ -404,10 +406,20 @@ export async function xSessionReport(opts: { // 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(); - const coolingMs = await platformCooldownRemainingMs("twitter", opts.paths).catch(() => 0); - const held = await heldPlatformRefusal("twitter", opts.what ?? "This X job", opts.paths, wallNow).catch(() => null); + // 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 = held ?? (coolingMs > 0 ? xRateLimitHoldSentence("X job", coolingMs, wallNow) : 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"] } => { diff --git a/common/jobs/pacingGuard.test.ts b/common/jobs/pacingGuard.test.ts @@ -35,8 +35,9 @@ await writeFile( 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 waits it out between pages (ratelimit=wait). - process.stderr.write("[twitter][info] Waiting for 14 minutes until 15:11:22 (rate limit)\\n"); + // 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 @@ -131,11 +132,22 @@ 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: [] })); } @@ -159,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); @@ -167,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); @@ -536,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"; @@ -550,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 < 4; 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(); }); @@ -707,34 +710,38 @@ 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: a 429 a gallery-dl fetch waited out leaves X alone for 15 minutes — the next X job of any kind is refused; the run's argv never lets gallery-dl rewrite the jar", async () => { +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); - const { readAutoQueueState, writeAutoQueueState } = await import("./autoQueueState"); - const clear = async () => { - const st = await readAutoQueueState(paths); - st.download.platformBackoff = {}; - await writeAutoQueueState(paths, st); - }; - await clear(); 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"); - assert.match(await readLog(res.jobId), /X is left alone until \d\d:\d\d UTC \(15 minutes after its rate limit\)/); } finally { delete process.env.FAKE_MODE; } - // gallery-dl was given the jar, and told not to write it back. + 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 clear(); 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, 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,16 +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"; - // X's gap is drawn from a range (jobs/xSittings.test.ts); a range of one - // value (5-5 min) makes it exact here. + // 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 }; const xGap = { gapMinMinutes: 5, gapMaxMinutes: 5 }; - 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.equal(w?.remainingMs, 252_000); - assert.equal(w && queueGapLine(w), "waiting 4m12s (a 5m00s gap drawn from 5-5 min): X jobs are spaced 5-5 min apart, drawn per job (social.x.gapMinMinutes, social.x.gapMaxMinutes)"); - assert.equal(await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_300_000, xGap }), null); + 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 @@ -33,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"; @@ -62,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); @@ -75,6 +84,7 @@ 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); @@ -302,7 +312,10 @@ export async function queueGapWait(opts: { if (platform === "twitter") { const range = xQueueGapRange(opts.pacing, opts.xGap ?? xGapSettingsNow()); if (range.maxSeconds <= 0) return null; - const last = await lastQueueEnd(opts.paths, opts.queueKey); + // 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; @@ -412,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/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/xSittings.test.ts b/common/jobs/xSittings.test.ts @@ -20,6 +20,20 @@ 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 } } })); @@ -74,7 +88,10 @@ setQueueGapClock({ now: () => fakeNow, sleep: async (ms) => { fakeNow += ms; } } async function reset(): Promise<void> { clearQueueGaps(); - 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 } })); await mkdir(path.dirname(xJobStartsFile(paths)), { recursive: true }); await writeFile(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [] })); await rm(xSittingFile(paths), { force: true }); @@ -265,9 +282,11 @@ test("UNEVEN GAPS: X's gap is drawn per job within 5-12 min, never below 5, logg 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. - assert.deepEqual(xGapRange({ gapMinMinutes: 1, gapMaxMinutes: 2 }), { minSeconds: 300, maxSeconds: 300 }); + // …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(undefined, 900), { minSeconds: 900, maxSeconds: 900 }); + 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 }); @@ -327,8 +346,8 @@ test("SUSPENDED: marked by hand, it refuses availability checks and captures tha 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 off records no availability: it runs. - assert.equal((await xJob("capture-posts", ACCOUNTS[0], { ids: ["1"], shots: false })).status, "done"); + // 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"); @@ -398,3 +417,215 @@ test("the scheduler queues no more X syncs than the sitting has left, and none i 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/); +}); 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/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,9 +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 — but X's gap, drawn per job from `social.x.gapMinMinutes`-`gapMaxMinutes`, is collapsed to this value whatever is set. 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_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. The editor's e2e server sets 0, so a fake X fetch needs no jar; x-session.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. 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 @@ -233,8 +233,12 @@ export const X_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<XSocialSettings> = { "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 below the minimum. ABSENT: 12. At " + - "most 120.", + "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"; diff --git a/common/lib/xJobRule.test.ts b/common/lib/xJobRule.test.ts @@ -91,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", () => { diff --git a/common/lib/xJobRule.ts b/common/lib/xJobRule.ts @@ -165,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 @@ -144,6 +144,10 @@ 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. @@ -157,7 +161,7 @@ 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 below the minimum. +// 12 min), never less than the minimum plus X_GAP_MIN_SPREAD_MINUTES. export function xGapRange( x: { gapMinMinutes?: number; gapMaxMinutes?: number } | undefined, explicitTwitterSeconds?: number, @@ -168,7 +172,7 @@ export function xGapRange( minSeconds = Math.floor(explicitTwitterSeconds); } const maxMinutes = parseXGapMinutes(x?.gapMaxMinutes) ?? X_GAP_DEFAULT_MAX_MINUTES; - const maxSeconds = Math.max(minSeconds, maxMinutes * 60); + const maxSeconds = Math.max(minSeconds + X_GAP_MIN_SPREAD_MINUTES * 60, maxMinutes * 60); return { minSeconds, maxSeconds }; } @@ -199,12 +203,25 @@ export function isXAccountState(v: unknown): v is XAccountState { // 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 (plan.kind === "check-post-availability") return true; + 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; + return p?.shots !== false || p?.articles !== false; } export function xSuspendedSentence(what: string, since: string, note?: string): string { @@ -214,3 +231,25 @@ export function xSuspendedSentence(what: string, since: string, note?: string): `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/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/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/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 { 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,7 +20,7 @@ // controller and the editor's Settings section all read it. import { parseRetryOnBlock, type RetryOnBlock } from "../lib/forumWalk"; -import { parseXGapMinutes, parseXSittingJobs } from "../lib/xSitting"; +import { parseXGapMinutes, parseXPostsPerJob, parseXSittingJobs } from "../lib/xSitting"; export type XCookieSource = "browser" | "profile"; @@ -63,6 +63,8 @@ export type XSocialSettings = { 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 @@ -137,6 +139,7 @@ export function sanitizeSocial(value: unknown): SocialSettings { 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 } : {}), @@ -145,6 +148,7 @@ export function sanitizeSocial(value: unknown): SocialSettings { ...(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); } diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts @@ -31,8 +31,7 @@ import type { Readable } from "node:stream"; import { execa } from "execa"; import { getPaths } from "../lib/paths"; import { noteXServiceOutcome } from "../lib/serviceCookies-server"; -import { recordPlatformCooldown } from "../jobs/downloadBackoff"; -import { X_RATE_LIMIT_HOLD_MS } from "../lib/xJobRule"; +import { recordXStop } from "../jobs/downloadBackoff"; import { looksLikeXAuthFailure, xBlockKind, xBlockLine } from "./xGalleryDlSignals"; import { cookieArgs } from "../lib/cookiePolicy"; import type { Post, PostRef } from "../lib/posts"; @@ -235,15 +234,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", ]; } @@ -362,7 +364,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) }; @@ -439,6 +448,8 @@ 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), articleImagePauseMs: () => ARTICLE_IMAGE_PAUSE_MS + Math.floor(Math.random() * ARTICLE_IMAGE_PAUSE_MS), }); } @@ -690,7 +701,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 }; @@ -1067,9 +1089,9 @@ async function galleryDlLoginFor( // 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): Promise<void> { +async function noteXRateLimit(onLog?: (line: string) => void, why = "a rate limit (gallery-dl)"): Promise<void> { try { - const until = await recordPlatformCooldown("twitter", X_RATE_LIMIT_HOLD_MS, getPaths()); + 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}`); @@ -1311,12 +1333,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; @@ -1335,8 +1366,9 @@ async function walkSearchWindows( maxId: stream.oldestId ?? windowStart.maxId, }; if (stream.rateLimited) { - onLog?.("[rate-limit] X throttled this search — gallery-dl paused between pages."); - await noteXRateLimit(onLog); + 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` + @@ -1587,11 +1619,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(); }); @@ -1599,6 +1639,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) { @@ -1608,14 +1649,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."), ); - await noteXRateLimit(onLog); + if (!xStopped) await noteXRateLimit(onLog); } onLog?.( `gallery-dl read ${stream.distinct} post(s): ${stream.newPosts} new` + @@ -1661,6 +1701,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/xPostCapture.test.ts b/common/social/xPostCapture.test.ts @@ -501,3 +501,16 @@ 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); +}); 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,9 @@ 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>; // One post's media into `dir` (gallery-dl in production). downloadMedia: (args: { id: string; @@ -499,6 +506,7 @@ export async function captureXPosts( threadError = res.error ?? `The page showed the post as ${res.state}.`; } stop = res.stop; + if (res.refused) await deps.noteXStop?.("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; @@ -564,6 +572,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 deps.noteXStop?.("a refused article page to a capture"); if (got.stop) { stop = got.stop; if (article.state === "login-wall") needsCookies = true; @@ -713,6 +722,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 deps.noteXStop?.("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", @@ -804,6 +814,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 deps.noteXStop?.("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.`, { 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 { readXSessionStatus, refreshXCookies, xCookieFile, xJarRefreshedFile, 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( @@ -176,3 +177,20 @@ test("lane x-sittings: a refresh is STAMPED, and the jar's refresh time is the s 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 @@ -29,6 +29,7 @@ import { readFile, rm, stat } from "node:fs/promises"; import { execa } from "execa"; import { readJsonFile, writeFileAtomic, writeJsonAtomic } from "../lib/jsonFile-server"; import type { Paths } from "../lib/paths"; +import { xStopRemainingMs } from "../jobs/downloadBackoff"; import { importPlaywright, type BrowserContextLike, @@ -68,10 +69,16 @@ 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(() => null); - const at = read?.ok ? (read.value as { at?: unknown } | null)?.at : undefined; - return typeof at === "string" && Number.isFinite(Date.parse(at)) ? new Date(Date.parse(at)).toISOString() : 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 = { @@ -198,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: { @@ -211,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. @@ -340,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))) { @@ -406,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 @@ -26,6 +26,16 @@ - /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. - 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 diff --git a/editor/app/lib/xPacing.ts b/editor/app/lib/xPacing.ts @@ -1,6 +1,7 @@ // 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, @@ -12,6 +13,6 @@ export function xPacingOf(x: { sittingJobs?: number; gapMinMinutes?: number; gap return { sittingJobs: xSittingJobs(x), gapMinMinutes, - gapMaxMinutes: Math.max(gapMinMinutes, parseXGapMinutes(x?.gapMaxMinutes) ?? X_GAP_DEFAULT_MAX_MINUTES), + gapMaxMinutes: Math.max(gapMinMinutes + X_GAP_MIN_SPREAD_MINUTES, parseXGapMinutes(x?.gapMaxMinutes) ?? X_GAP_DEFAULT_MAX_MINUTES), }; } diff --git a/editor/app/settings/xSessionActions.ts b/editor/app/settings/xSessionActions.ts @@ -21,6 +21,7 @@ import { 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, @@ -263,8 +264,11 @@ export async function setXPacingAction(input: XPacingInput): Promise<XPacingResu 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 || gapMaxMinutes > X_GAP_CEILING_MINUTES) { - return { ok: false, error: `The longest gap must be a whole number of minutes, from the shortest to ${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( diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1513,8 +1513,8 @@ export function usage() { " 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", @@ -1524,8 +1524,9 @@ export function usage() { " 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 minutes after a 429, which refuses every X", - " job.", + " 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",