Archilyzer · Source

archilyzer

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

commit 1a9d99df916eb481426bc14a6ac6d6c64cd65114
parent 25156ab10ca6c9fd32d7e8a54b00776a7bacd9cb
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 13:06:14 -0500

X in small, uneven sittings: a refresh admits 4 jobs of one kind, a drawn 5-12 min gap, 6 an hour

The archive's X account was suspended after one sitting of a trending read and
12 timeline fetches back to back, each 5-6 minutes after the last, at the old
hourly cap of 12. Every rule below is in the network guard every X job passes
(xSessionReport / guardXJob), so no caller skips it.

- Sittings (lib/xSitting.ts, jobs/xSitting.ts): a cookie refresh begins a
  sitting of at most social.x.sittingJobs X job starts (default 4, bounded
  1-6 in code), counted where X's cap counts, kept in .x-session/sitting.json
  under its lock, rebuilt from the job records (xSittings) and X's job count
  when lost, unreadable = closed. A start past it is refused at enqueue, or
  ends done/deferred at its start (never a failure that retries).
- One kind per sitting: timelines or browse, fixed by the first job.
- The jar's refresh time is now the broker's own stamp (.x-session/
  refreshed.json, written by Connect/Refresh): gallery-dl's cookies-update
  rewrote the jar after every run, so its mtime said "refreshed" after every
  fetch. gallery-dl is now given -o cookies-update=false with a cookie file.
- X's queue gap is drawn per job from social.x.gapMinMinutes-gapMaxMinutes
  (5-12, never below 5), logged with its draw; seeded only by a test hook.
- X_JOB_CAP.perHour 12 -> 6.
- A 429 (X's cooldown or hold) now refuses every X job kind in the guard, and
  a gallery-dl rate-limit wait records the 15-minute cooldown.
- The operator marks the account suspended/ok (pnpm ops x-session, /cookies):
  suspended refuses check-post-availability and captures with shots, and the
  two controllers drop deleted/unavailable verdicts while it is marked.
- get x-session and /cookies show the sitting, the account and the cooldown.

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

Diffstat:
MCOMMANDS.md | 20++++++++++++++++----
MENVIRONMENT.md | 3++-
MSETTINGS.md | 5++++-
Mcommon/controller/capturePosts.ts | 7+++++--
Mcommon/controller/checkPostAvailability.ts | 3+++
Mcommon/controller/readXTrending.ts | 3++-
Mcommon/controller/xRun.test.ts | 5+++++
Mcommon/controller/xRun.ts | 15+++++++++------
Mcommon/controller/xTrendingWatch.ts | 16+++++++++++++++-
Mcommon/jobs/jobMeta.ts | 15+++++++++++++++
Mcommon/jobs/networkGuard.ts | 259++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/jobs/pacingGuard.test.ts | 134+++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------------
Mcommon/jobs/queueGap.test.ts | 11+++++++----
Mcommon/jobs/queueGap.ts | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/registry.ts | 6++++++
Mcommon/jobs/xJobCap.test.ts | 34+++++++++++++++++-----------------
Mcommon/jobs/xJobCap.ts | 7+++++++
Acommon/jobs/xSitting.ts | 252+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/jobs/xSittings.test.ts | 382+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/cookieStatus.ts | 17++++++++++++++++-
Mcommon/lib/envVars.ts | 3++-
Mcommon/lib/settingsSchema.ts | 20+++++++++++++++++++-
Mcommon/lib/xJobRule.test.ts | 43++++++++++++++++++++++++-------------------
Mcommon/lib/xJobRule.ts | 13++++++++++++-
Acommon/lib/xSitting.ts | 216+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/xAccountState.ts | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xCookieSource.ts | 13+++++++++++++
Mcommon/social/xGalleryDlFetcher.test.ts | 11+++++++++++
Mcommon/social/xGalleryDlFetcher.ts | 29++++++++++++++++++++++++++---
Mcommon/social/xSessionBroker.test.ts | 23++++++++++++++++++++++-
Mcommon/social/xSessionBroker.ts | 27++++++++++++++++++++++++---
Meditor/app/api/ops/x-session/route.ts | 23+++++++++++++++++++++--
Meditor/app/cookies/CookiesBoard.tsx | 92++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Meditor/app/cookies/actions.ts | 21+++++++++++++++++++++
Meditor/app/lib/cookieControls.ts | 2++
Meditor/app/lib/cookieControlsTypes.ts | 2++
Meditor/app/lib/cookieStatus.ts | 15++++++++++++++-
Aeditor/app/lib/xPacing.ts | 17+++++++++++++++++
Meditor/app/review/components/XRunConsole.tsx | 12+++++++-----
Meditor/app/settings/components/SettingsForm.tsx | 6++++--
Meditor/app/settings/components/XSessionSection.tsx | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Meditor/app/settings/page.tsx | 2++
Meditor/app/settings/xSessionActions.ts | 43+++++++++++++++++++++++++++++++++++++++++++
Meditor/e2e/servers.ts | 5+++++
Meditor/playwright.config.ts | 5+++++
Mscripts/archilyzer-ops.mjs | 30+++++++++++++++++++++++++++---
Mscripts/archilyzer-ops.test.mjs | 12++++++++++++
47 files changed, 2029 insertions(+), 154 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -198,8 +198,9 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `voice-convert` | voice-convert keeps a recording's performance (timing, pitch contour) and swaps its timbre for a STOCK synthetic voice, as voice-enhance's job: the same body plus "voice" — "&lt;tts engine&gt;:&lt;stock voice&gt;" (orpheus:zac, orpheus:leah, kokoro:am\_michael, ...; settings.voice.convert.target); a file, a path or a recording is REFUSED as a target (no real person's voice) — and "engine" (openvoice \| seed-vc, each installed by `archilyzer voice setup --engine <id>`). "pitch" is where the result's pitch comes from (settings.voice.convert.pitch): "target" — the stock voice's own, the read's intonation flattened to it; "source" — the pitch the take was read at (raise your voice and it rises); "contour" — the read's rises and falls, moved as a whole to the stock voice's register. "semitones" (-12 to 12) then moves a followed pitch; left out, a followed pitch takes settings.voice.convert.semitones (0 unless set). source and contour are seed-vc's, on its optional f0 model (`archilyzer voice setup --engine seed-vc --with f0`; slower, 44.1 kHz); openvoice refuses them. The target's reference is synthesized once through the tts op and kept. The result adds target, voice, pitch (semitones and f0 — the medians heard and the move applied — when followed), synthetic: true and the disclosure line. | | | `settings` | settings patches settings.json through the editor's one writer: {"patch": {"&lt;top-level key&gt;": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"diarization":{"cleanAfterCapture":true}}}'`<br>`pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` | | `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | | -| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x", "instagram" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /cookies) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The For "instagram" it sends Instagram NO request either and is the operator's word that its check is passed: it clears the alert, and the next Instagram job raises it again if it was not. The timer never asks Instagram. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). Asked while a recheck or another press for the service runs (a click, the dashboard's, the timer's): refused, 409 {busy: true}, never queued. dismiss-service clears a service's cookie alert by hand: {"service"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -&gt; {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` | +| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x", "instagram" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /cookies) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The For "instagram" it sends Instagram NO request either and is the operator's word that its check is passed: it clears the alert, and the next Instagram job raises it again if it was not. The timer never asks Instagram. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). Asked while a recheck or another press for the service runs (a click, the dashboard's, the timer's): refused, 409 {busy: true}, never queued. dismiss-service clears a service's cookie alert by hand: {"service"}. x-session marks the X account's state by hand: {"accountState": "suspended" \| "ok", "note"?}. While it is suspended, check-post- availability and capture-posts with screenshots on X (the jobs that record a post as deleted or unavailable) are refused, because a suspended account's answers are thinned; every other X job logs it. get x-session and /cookies show it as the account's alert. Nothing is asked of X. Answers {account: {state, note?, at, by}}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -&gt; {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` | | `dismiss-service` | — | | +| `x-session` | — | `pnpm ops x-session --json '{"accountState":"suspended","note":"read-only since the 21st"}'`<br>`pnpm ops x-session --json '{"accountState":"ok"}'` | | `rerun-service-jobs` | — | | | `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` | | `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. Only a download waits on the platform's queue: the transcription runs as a transcribe-one job on the video's own queue (transcribe-one:&lt;slug&gt;:&lt;id&gt;), at once when nothing is downloaded, else handed off by the whisper-video once the audio is down. A job; --wait follows it through the hand-off to the end of the transcription. "queueKey" names another queue. A youtube-handling video with no audio whose metadata lists English captions has those fetched instead ({"instead": "captions", "message"}, the job the caption download), one with an English caption track on disk is refused; "asr": true transcribes it anyway (no "file"). "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. "whilePaused": true runs this one transcription during a pause-all on a worker the pause alone switched off; the pause stays on (the video page's "Transcribe now (workers paused)"). A video its record says is live, scheduled or still processing its VOD (live\_status is\_live, is\_upcoming, post\_live) is refused before anything is queued — a download would read the stream at 1x and hold the platform queue: record it with record-live, or wait for the VOD (refresh-metadata re-reads the record once it has ended). With its audio on disk it transcribes. | | @@ -369,15 +370,26 @@ get x-session [<slug>] is the X login an X job would use and whether one "browser": cookiesFromBrowser, whose age cannot be read), hasCookies, looksAuthenticated, cookiesUpdatedAt, ageMinutes, maxAgeMinutes (social.x.maxCookieAgeMinutes; 0 = off), the X cookie alert if it is up, - allowed, and reason (the refusal an X job would get); and X's JOB CAP: - cap {lastHour, perHour: 12, lastDay, perDay: 150, reached, nextAt?} - - at most 12 X jobs start in any 60 minutes and 150 in any 24 hours ON + allowed, reason (the refusal an X job would get) and refusedBy (alert, + jar, cap, sitting, cooldown or suspended); X's JOB CAP: + cap {lastHour, perHour: 6, lastDay, perDay: 150, reached, nextAt?} - + at most 6 X jobs start in any 60 minutes and 150 in any 24 hours ON THIS MACHINE: one count over every kind of X job, whatever the login source, cookie spec or channel. A job past it is refused when queued, with the time the next may start; one that meets it when its queue starts it ends done, deferred (not failed). A library's media-only capture is not counted. The numbers are constants of the code (common/lib/xJobRule.ts): no setting, option or queue raises them. + X's SITTING: sitting {began, kind, used, left, limit} - a cookie + refresh begins a sitting of at most social.x.sittingJobs X job starts + (default 4, 1-6 in the code), of ONE kind fixed by its first job: + timelines (account fetches, captures, availability checks, an import) + or browse (trending reads, X search walks, a library's captures). A + start past it, or of the other kind, is refused (at its start: done, + deferred); a new Refresh on /cookies starts the next. account {state, + since?, note?, alert?} is the operator's mark (x-session, below); + cooldown {until} is X's 15 minutes after a 429, which refuses every X + job. <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,7 +261,8 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one | `E2E_AVAILABILITY_PROBE_GAP_MS` | the real gap (3 s, stretched by `pacing.jitter`) | The pause after each per-video availability probe. The editor's e2e server and the availability unit tests set 0: their stub yt-dlp answers at once. | common/controller/checkAvailability.ts | | `E2E_PACING_JITTER` | `pacing.jitter` from settings.json (0.25) | Replaces the operator's jitter share (0–1) for every request-pacing wait. The unit tests that assert an exact gap set 0; the jitter itself is tested with its share passed in (lib/jitter.test.ts). | common/lib/jitter.ts | | `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts | -| `E2E_JOB_GAP_SECONDS` | the built-in gaps (20 s; X 300, forums and Bluesky 60) | Replaces every BUILT-IN `pacing.jobGapSeconds` gap (plans/pacing-guard.md); a gap set in settings.json still applies. The editor's e2e server sets 0, so two fake fetches on one platform queue do not wait; pacing.spec sets its own. | common/jobs/queueGap.ts | +| `E2E_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_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_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 | diff --git a/SETTINGS.md b/SETTINGS.md @@ -180,7 +180,7 @@ Default: `"when-required"` ## `social` -Per-platform settings of the social posts: X's three, all chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`), where X posts may appear (`social.x.visibility`) and how fresh its cookies must be for an X job to start (`social.x.maxCookieAgeMinutes`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts. +Per-platform settings of the social posts: X's, all chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`), where X posts may appear (`social.x.visibility`), how fresh its cookies must be for an X job to start (`social.x.maxCookieAgeMinutes`), how many X jobs one cookie refresh admits (`social.x.sittingJobs`) and the range X's gap is drawn from (`social.x.gapMinMinutes`, `social.x.gapMaxMinutes`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts. #### `social` @@ -197,6 +197,9 @@ Per-platform settings of the social posts: X's three, all chosen in the X accoun | `cookieSource` | absent | Where the X fetchers' login comes from. `"browser"`: the operator's everyday browser, named by `cookiesFromBrowser` — gallery-dl is handed `--cookies-from-browser <spec>` and reads it on every run, and the Playwright fallback reads the same store (Firefox only; common/social/xBrowserLogin.ts), so the login lasts as long as the browser's. `"profile"`: the session broker's persistent profile ("Connect X account" on /settings) and the cookie jar it exports. ABSENT (the default) is resolved at read time, never stored: `"browser"` when `cookiesFromBrowser` is set and no profile is connected (no exported jar carrying an auth_token), else `"profile"`. The source, not `cookieMode`, governs the X fetchers. | | `visibility` | absent | Where X posts may appear. `"public"` (the default; absent): an X channel's posts are built into every site that has the channel. `"private"`: every X channel's posts (a channel with `sourceKind: "social"` and `platform: "twitter"`) are left out of every PUBLIC site build — the channel with them, since posts are all an X channel holds — and built only into PRIVATE sites (`site.json` `audience`). Nothing on disk changes and fetching does not; a site already published changes on its next build and deploy, and flipping back is a rebuild. Chosen in the X account session section of /settings; the rule is common/lib/postsVisibility.ts. | | `maxCookieAgeMinutes` | absent | THE FRESH-JAR RULE: with the `"profile"` login source, a job that sends requests to X (Fetch posts, the older walk, an X search, Capture posts, Import one post, Check deleted posts — and the scheduler's fetches) is refused when it STARTS unless the profile's exported cookie jar was written within this many minutes and carries a login (an auth_token). The refusal says what to do: press Refresh cookies (or Connect X account) on /cookies, then fetch again. A refresh is a human click — it loads x.com/home, itself a request to X — so the editor never refreshes the jar to satisfy this. With the `"browser"` source the age cannot be read: the job logs that and proceeds. ABSENT: 60. 0 turns the rule off; at most 10080 (a week). Set in the X account session section of /settings. common/jobs/networkGuard.ts. | +| `sittingJobs` | absent | X IN SITTINGS: a sitting begins at a cookie refresh (Refresh cookies or Connect X account on /cookies) and admits at most this many X job starts — every kind that asks X, counted as X's job cap counts them (each channel of an X run is one). A start beyond it is refused (at enqueue, or `done`, deferred, at its start: never a failure that retries): a new Refresh starts the next sitting. A sitting is also ONE KIND, fixed by its first job: `timelines` (account post fetches, captures, availability checks, one post's import) or `browse` (trending reads, X search channels' walks, a trending library's captures); a job of the other kind waits for the next Refresh. The sitting is kept in `.x-session/sitting.json` (rebuilt from the job records if it is lost) and shown by `pnpm ops get x-session` and on /cookies. ABSENT: 4. Bounded 1-6 in the code (common/lib/xSitting.ts): no value raises it past 6. common/jobs/xSitting.ts. | +| `gapMinMinutes` | absent | THE SHORTEST GAP BEFORE AN X JOB, in minutes: X's queue gap is drawn per job, uniform between this and `gapMaxMinutes`, after the previous X job ended, and logged ("waiting 8m41s (a 9m02s gap drawn from 5-12 min)"). Never below 5 (the floor is in the code); an explicit `pacing.jobGapSeconds.twitter` above it raises it. ABSENT: 5. At most 120. common/jobs/queueGap.ts. | +| `gapMaxMinutes` | absent | THE LONGEST GAP BEFORE AN X JOB, in minutes (see `gapMinMinutes`). Never below the minimum. ABSENT: 12. At most 120. | #### `social.xenforo` diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -33,6 +33,7 @@ // shows), writing the context into the record and nothing about availability. import { xJobContextRefusal } from "../lib/xJobRule"; +import { keepVerdictsTrustedWhileSuspended } from "../social/xAccountState"; import path from "node:path"; import { isXSearchChannel } from "../lib/xSearch/config"; import { isXTrendingChannel, xTrendingMaxVideoBytes, type XTrendingConfig } from "../lib/xTrending/config"; @@ -466,11 +467,13 @@ export async function capturePosts( return { ok: true, outcomes: [], ...avatars }; } - // What the pages said about each post, folded into the sidecar. - const observations = new Map<string, PostAvailability>(); + // What the pages said about each post, folded into the sidecar — never a + // suspended X account's "deleted" (social/xAccountState.ts). + let observations = new Map<string, PostAvailability>(); for (const o of result.outcomes) { if (o.availability) observations.set(o.id, o.availability); } + if (fetcher.platform === "twitter") observations = await keepVerdictsTrustedWhileSuspended(paths, observations, log); if (observations.size > 0) { const { map, newlyDeleted, changed } = mergePostAvailability( await readPostAvailability(channelRoot), diff --git a/common/controller/checkPostAvailability.ts b/common/controller/checkPostAvailability.ts @@ -18,6 +18,7 @@ // posts never looked at, `all` re-checks everything. import { xJobContextRefusal } from "../lib/xJobRule"; +import { keepVerdictsTrustedWhileSuspended } from "../social/xAccountState"; import path from "node:path"; import { readChannelConfig } from "./channels"; import type { Paths } from "../lib/paths"; @@ -217,6 +218,8 @@ export async function checkPostAvailability( return { ok: false, ...empty, error: message }; } + // A suspended X account's "deleted" is not believed (social/xAccountState.ts). + if (fetcher.platform === "twitter") observations = await keepVerdictsTrustedWhileSuspended(paths, observations, log); const checkedAt = new Date().toISOString(); const { map, newlyDeleted, changed } = mergePostAvailability( availability, diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts @@ -101,7 +101,8 @@ export const READ_X_TRENDING_RESULT_MARKER = "@@read-x-trending "; // rate-limit window. Written as the `twitter` platform cooldown // (jobs/downloadBackoff.ts recordPlatformCooldown — the cooldown import-post // already respects), read by this job's enqueue and start. -export const X_RATE_LIMIT_HOLD_MS = 15 * 60_000; +export { X_RATE_LIMIT_HOLD_MS } from "../lib/xJobRule"; +import { X_RATE_LIMIT_HOLD_MS } from "../lib/xJobRule"; const X_PLATFORM = "twitter"; const hhmm = (ms: number) => new Date(ms).toISOString().slice(11, 16); diff --git a/common/controller/xRun.test.ts b/common/controller/xRun.test.ts @@ -28,6 +28,11 @@ writeFileSync( const { getPaths } = await import("../lib/paths"); const xr = await import("./xRun"); +// X's gap is drawn in 5-12 min and has no off switch now (lane x-sittings: +// jobGapSeconds.twitter 0 no longer turns it off): a fake clock waits it out. +const { setQueueGapClock } = await import("../jobs/queueGap"); +let skew = 0; +setQueueGapClock({ now: () => Date.now() + skew, sleep: async (ms) => void (skew += ms) }); const { defaultChannelPriority } = await import("../lib/channelPriority"); const paths = getPaths(); diff --git a/common/controller/xRun.ts b/common/controller/xRun.ts @@ -58,7 +58,7 @@ import { ulid } from "../jobs/ulid"; import { getRegistry } from "../jobs/registry"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { guardNetworkJob, xSessionReport, type XSessionReport } from "../jobs/networkGuard"; -import { noteQueueJobEnd, queueGapClock, queueGapFor, waitForQueueGap } from "../jobs/queueGap"; +import { noteQueueJobEnd, queueGapClock, waitForQueueGap, xQueueGapRange } from "../jobs/queueGap"; import { requestChannelSnapshot } from "../jobs/snapshotScheduler"; import { fetchPosts } from "./fetchPosts"; import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "../lib/sourcelessPosts"; @@ -802,8 +802,10 @@ export type XRunConsole = { run: XRunView | null; candidates: XRunCandidate[]; jar: XRunJar; - // X's queue gap between two channels (pacing.jobGapSeconds.twitter), seconds. + // X's queue gap between two channels, seconds: drawn per channel from + // [gapSeconds, gapMaxSeconds] (social.x.gapMinMinutes / gapMaxMinutes). gapSeconds: number; + gapMaxSeconds: number; maxPosts: number; }; @@ -833,11 +835,12 @@ export async function xRunConsole(paths: Paths, runId?: string): Promise<XRunCon listXRunCandidates(paths), xSessionReport({ paths }), ]); - let gapSeconds = 0; + let range = xQueueGapRange(undefined, undefined); try { - gapSeconds = queueGapFor(getSettings().pacing, "twitter").seconds; + const settings = getSettings(); + range = xQueueGapRange(settings.pacing, settings.social?.x); } catch { - gapSeconds = queueGapFor(undefined, "twitter").seconds; + /* the defaults */ } - return { run, candidates, jar: xRunJar(report), gapSeconds, maxPosts: X_RUN_MAX_POSTS }; + return { run, candidates, jar: xRunJar(report), gapSeconds: range.minSeconds, gapMaxSeconds: range.maxSeconds, maxPosts: X_RUN_MAX_POSTS }; } diff --git a/common/controller/xTrendingWatch.ts b/common/controller/xTrendingWatch.ts @@ -142,7 +142,14 @@ function settingsCanBeRead(): boolean { // 60 minutes) — an age that cannot be read, or is negative (a clock set // back), refuses — and never when settings cannot be read. export async function watchRefusal(paths: Paths, slug: string, now: number, deps: WatchRefusalDeps = {}): Promise<WatchRefusal | null> { - const report = await (deps.report ?? xSessionReport)({ paths, channelSlug: slug, now, ...(deps.counts === false ? { counts: false } : {}) }); + // A watch's job is a read or a library's capture: a browse job of X's sitting. + const report = await (deps.report ?? xSessionReport)({ + paths, + channelSlug: slug, + now, + sittingKind: "browse", + ...(deps.counts === false ? { counts: false } : {}), + }); if (!report.hasProfile) { return { reason: "no-profile", @@ -180,6 +187,13 @@ export async function watchRefusal(paths: Paths, slug: string, now: number, deps if (deps.counts !== false && !report.allowed && report.cap.reached && report.alert === null && /^X's job (cap|count)/.test(report.reason ?? "")) { return { reason: "cooldown", sentence: report.reason ?? "X's job cap is reached." }; } + // X'S SITTING (lib/xSitting.ts) used up or of the other kind, X cooling down + // after a 429, or the account marked suspended: the tick is skipped and the + // watch waits — the sitting's ends at the next Refresh, the cooldown's at + // its time. Not the jar's fault. + if (!report.allowed && (report.refusedBy === "sitting" || report.refusedBy === "cooldown" || report.refusedBy === "suspended")) { + return { reason: "cooldown", sentence: report.reason ?? "X is held." }; + } // Whatever else the guard would refuse a person's job for. if (!report.allowed) return { reason: "jar", sentence: report.reason ?? "X's cookie jar is past its limit." }; const held = await (deps.held ?? xTrendingHeld)(paths, now); diff --git a/common/jobs/jobMeta.ts b/common/jobs/jobMeta.ts @@ -50,6 +50,8 @@ export type JobMeta = { // can be rebuilt from the records (jobs/xJobCap.ts). Absent on metas from // before it. xStarts?: number[]; + // The X sittings those starts were counted in (JobRecord.xSittings). + xSittings?: Array<{ began: string | null; kind: "timelines" | "browse"; at: number }>; // The job ended deferred by X's job cap (JobRecord.deferred). deferred?: { until: number; sentence: string }; }; @@ -83,6 +85,7 @@ export async function writeJobMeta( ...(record.resumedFrom ? { resumedFrom: record.resumedFrom } : {}), ...(record.resumeCount ? { resumeCount: record.resumeCount } : {}), ...(record.queueKey === X_QUEUE_KEY ? { xStarts: [...(record.xStarts ?? [])] } : {}), + ...(record.xSittings?.length ? { xSittings: record.xSittings.map((x) => ({ ...x })) } : {}), ...(record.deferred ? { deferred: { ...record.deferred } } : {}), }; await writeFile(metaPath(paths, record.id), JSON.stringify(meta), "utf8"); @@ -116,6 +119,18 @@ export async function readJobMeta( if (m.resumedFrom !== undefined && typeof m.resumedFrom !== "string") delete meta.resumedFrom; if (m.resumedAs !== undefined && typeof m.resumedAs !== "string") delete meta.resumedAs; if (m.xStarts !== undefined && !(Array.isArray(m.xStarts) && m.xStarts.every((t) => typeof t === "number" && Number.isFinite(t)))) delete meta.xStarts; + if ( + m.xSittings !== undefined && + !( + Array.isArray(m.xSittings) && + m.xSittings.every((x) => { + const r = x as { began?: unknown; kind?: unknown; at?: unknown } | null; + return !!r && (r.began === null || typeof r.began === "string") && (r.kind === "timelines" || r.kind === "browse") && typeof r.at === "number" && Number.isFinite(r.at); + }) + ) + ) { + delete meta.xSittings; + } const d = m.deferred as { until?: unknown; sentence?: unknown } | undefined; if (d !== undefined && !(d && typeof d === "object" && typeof d.until === "number" && typeof d.sentence === "string")) delete meta.deferred; if ( diff --git a/common/jobs/networkGuard.ts b/common/jobs/networkGuard.ts @@ -19,6 +19,14 @@ // the "browser" source the age cannot be read: the job logs that and // proceeds. // +// 4. X IN SITTINGS (lane x-sittings, lib/xSitting.ts, jobs/xSitting.ts): a +// cookie refresh admits at most `social.x.sittingJobs` X job starts (4; +// 1-6 in the code), of ONE kind (timelines or browse, fixed by the +// first); X cooling down after a 429 refuses every X job; and an +// account the operator marked suspended refuses the jobs that record +// posts as deleted (social/xAccountState.ts). All in xSessionReport, the +// one computation behind the refusal and `get x-session`. +// // Operator, 2026-10-23: "only start X downloads with a recent cookie refresh", // "be very careful not to do that thing on any sort of site", "This should be // enforced in Archilyzer, not just an AI standing rule". @@ -50,6 +58,17 @@ import { jobKindLabel, kindIsNetwork } from "./jobKinds"; import { xJobAsksX, xJobCounts, xQueueRefusal, type XJobPlan } from "../lib/xJobRule"; import { isXTrendingChannel } from "../lib/xTrending/config"; import { recordXJobStart, xJobCapStatus } from "./xJobCap"; +import { recordXSittingStart, xSittingLook } from "./xSitting"; +import { + xSittingJobs, + xSittingKindOf, + xSuspendedRefuses, + xSuspendedSentence, + type XSittingKind, +} from "../lib/xSitting"; +import { readXAccountState, xAccountAlertLine } from "../social/xAccountState"; +import { heldPlatformRefusal, platformCooldownRemainingMs } from "./downloadBackoff"; +import { xRateLimitHoldSentence } from "../lib/xTrending/config"; import { writeJobMeta } from "./jobMeta"; import type { JobSpec } from "./jobSpec"; import { getRegistry } from "./registry"; @@ -245,8 +264,8 @@ async function channelCookieSpec(paths: Paths, slug: string | undefined, setting // `capped`: the refusal is the job cap's (no cookie banner is raised for it), // with `nextAt`, when the next X job may start. export type XGuardResult = - | { ok: true; note?: string } - | { ok: false; message: string; alert: boolean; capped?: true; nextAt?: number }; + | { ok: true; note?: string; accountAlert?: string } + | { ok: false; message: string; alert: boolean; refusedBy?: XSessionReport["refusedBy"]; capped?: true; nextAt?: number }; // WHAT AN X JOB WOULD BE TOLD NOW, and why — the fresh-jar rule's inputs and // its verdict in one record, for `pnpm ops get x-session` (an agent asks it @@ -277,9 +296,32 @@ export type XSessionReport = { // cookie spec or channel (review 2 M1) — the caps (constants of the code), // and, when the cap is reached, when the next may start. cap: { lastHour: number; perHour: number; lastDay: number; perDay: number; reached: boolean; nextAt?: string; unreadable?: true }; - // Would an X job start now? `reason` is the refusal it would get. + // X'S SITTING (lib/xSitting.ts, jobs/xSitting.ts): when it began (the + // jar's refresh; null: none on record), its kind (null: no job yet; + // "unknown": its record was lost), the starts it admitted and has left, + // and the limit (social.x.sittingJobs, 1-6). `unreadable`: the file cannot + // be read and no X job starts. + sitting: { + began: string | null; + kind: XSittingKind | "unknown" | null; + used: number; + left: number; + limit: number; + // The kind of the job asked about, when one was. + asked?: XSittingKind; + unreadable?: true; + }; + // THE ACCOUNT'S STATE as the operator marked it (social/xAccountState.ts): + // "suspended" refuses the jobs that record deleted posts; `alert` is the + // line /cookies shows. + account: { state: "ok" | "suspended"; since?: string; note?: string; alert?: string }; + // X cooling down after a rate limit (429: 15 minutes), when it is: until when. + cooldown: { until: string } | null; + // Would an X job start now? `reason` is the refusal it would get, and + // `refusedBy` which rule gave it. allowed: boolean; reason: string | null; + refusedBy?: "alert" | "jar" | "cap" | "sitting" | "cooldown" | "suspended"; note?: string; }; @@ -288,9 +330,15 @@ export async function xSessionReport(opts: { channelSlug?: string; now?: number; // False: the job asked about does not count against X's job cap (ruling - // R-a: xJobCounts), so the cap does not refuse it. The count is reported - // all the same. + // R-a: xJobCounts), so the cap does not refuse it — nor does its sitting. + // The counts are reported all the same. counts?: boolean; + // The job asked about: its sitting kind (absent: only a used-up sitting + // refuses), and whether it records posts as deleted or unavailable (a + // suspended account refuses it). + sittingKind?: XSittingKind; + recordsAvailability?: boolean; + what?: string; }): Promise<XSessionReport> { const now = opts.now ?? Date.now(); const status = await readXSessionStatus(opts.paths); @@ -316,10 +364,64 @@ export async function xSessionReport(opts: { ...(capStatus.nextAt !== undefined ? { nextAt: new Date(capStatus.nextAt).toISOString() } : {}), ...(capStatus.unreadable ? { unreadable: true as const } : {}), }; - // The cap refuses whatever else would let the job through. - const capped = <T extends { allowed: boolean; reason: string | null }>(r: T): T => - r.allowed && !capStatus.ok && opts.counts !== false ? { ...r, allowed: false, reason: capStatus.sentence ?? "X's job cap is reached." } : r; + // X'S SITTING: the jar's refresh begins it; the limit is the setting, + // bounded 1-6 in the code. + const limit = xSittingJobs(settings?.social?.x); + const refreshedAt = status.cookiesUpdatedAt ?? null; + const sittingOff = e2eSittingsOff(); + const look = await xSittingLook(opts.paths, { refreshedAt, kind: opts.sittingKind ?? "timelines", limit }); + const sitting: XSessionReport["sitting"] = { + began: look.status.state.began, + kind: look.status.state.kind, + used: look.status.used, + left: look.status.left, + limit, + ...(opts.sittingKind ? { asked: opts.sittingKind } : {}), + ...(!look.status.readable ? { unreadable: true as const } : {}), + }; + // Without a kind asked, only a used-up (or unreadable) sitting refuses. + const sittingRefusal = + sittingOff || opts.counts === false || look.verdict.ok + ? null + : opts.sittingKind || look.verdict.why === "used-up" || !look.status.readable + ? look.verdict.sentence + : null; + // The account's state, as marked. + const acct = await readXAccountState(opts.paths); + const account: XSessionReport["account"] = acct + ? { + state: acct.state, + since: acct.at, + ...(acct.note ? { note: acct.note } : {}), + ...(acct.state === "suspended" ? { alert: xAccountAlertLine(acct) } : {}), + } + : { state: "ok" }; + const suspendedRefusal = + acct?.state === "suspended" && opts.recordsAvailability === true + ? xSuspendedSentence(opts.what ?? "This job", acct.at, acct.note) + : null; + // X'S COOLDOWN AFTER A 429 (15 minutes) and its hold refuse EVERY X job, + // whatever its kind (rule 6 of lane x-sittings: it used to be asked only by + // the trending read, its media and the capture). + const wallNow = opts.now ?? Date.now(); + const coolingMs = await platformCooldownRemainingMs("twitter", opts.paths).catch(() => 0); + const held = await heldPlatformRefusal("twitter", opts.what ?? "This X job", opts.paths, wallNow).catch(() => null); + const cooldown = coolingMs > 0 ? { until: new Date(wallNow + coolingMs).toISOString() } : null; + const coolRefusal = held ?? (coolingMs > 0 ? xRateLimitHoldSentence("X job", coolingMs, wallNow) : null); + // The cap, the sitting, the cooldown and the account refuse whatever else + // would let the job through. + const capped = <T extends { allowed: boolean; reason: string | null }>(r: T): T & { refusedBy?: XSessionReport["refusedBy"] } => { + if (!r.allowed) return r; + if (coolRefusal) return { ...r, allowed: false, reason: coolRefusal, refusedBy: "cooldown" }; + if (suspendedRefusal) return { ...r, allowed: false, reason: suspendedRefusal, refusedBy: "suspended" }; + if (!capStatus.ok && opts.counts !== false) return { ...r, allowed: false, reason: capStatus.sentence ?? "X's job cap is reached.", refusedBy: "cap" }; + if (sittingRefusal) return { ...r, allowed: false, reason: sittingRefusal, refusedBy: "sitting" }; + return r; + }; const base = { + sitting, + account, + cooldown, cap, source: resolved.source, sourceChosen: resolved.chosen, @@ -345,6 +447,7 @@ export async function xSessionReport(opts: { ...base, alert: { raisedAt: raised.raisedAt ?? raised.since, line: raised.evidence.line }, allowed: false, + refusedBy: "alert", reason: `X answered with ${what} at ${at} UTC (${raised.evidence.line}) and its cookie alert is up, ` + `so no X job starts: ${serviceFixText(X_SERVICE, configuredCookieBrowser())}, then Recheck on the dashboard.`, @@ -355,24 +458,54 @@ export async function xSessionReport(opts: { const verdict = xJarVerdict({ source: resolved.source, status, maxAgeMinutes, now }); return verdict.ok ? capped({ ...base, alert: null, allowed: true, reason: null, ...(verdict.note ? { note: verdict.note } : {}) }) - : { ...base, alert: null, allowed: false, reason: verdict.message }; + : { ...base, alert: null, allowed: false, reason: verdict.message, refusedBy: "jar" }; +} + +// TEST-ONLY: E2E_X_SITTINGS=off on the e2e test server (with +// E2E_TEST_ROUTES=1, as it always runs) leaves its fake X jobs out of the +// sitting rule — they run many to a test corpus with no jar refresh between. +// Unset everywhere but the e2e test server; it does not touch X's job cap. +function e2eSittingsOff(): boolean { + return process.env.E2E_X_SITTINGS === "off" && process.env.E2E_TEST_ROUTES === "1"; } // Why no X job starts now BECAUSE OF X'S JOB CAP (or its unreadable count), // or null: for the scheduler, which then skips X's channels rather than // queue syncs that would each be refused. -export async function xCapHeldReason(paths: Pick<Paths, "transcriptsDir" | "jobsDir">, now?: number): Promise<string | null> { +export async function xCapHeldReason(paths: Paths, now?: number): Promise<string | null> { const status = await xJobCapStatus(paths, now ?? queueGapClock().now()); - return status.ok ? null : (status.sentence ?? "X's job cap is reached."); + if (!status.ok) return status.sentence ?? "X's job cap is reached."; + // X's sitting, used up (or unreadable), holds them the same way. + const sitting = await xSittingHeld(paths); + return sitting?.sentence ?? null; +} + +// X's sitting as the scheduler reads it: what it has left, and its refusal +// when it has none (a look: nothing counted). +async function xSittingHeld(paths: Paths): Promise<{ left: number; sentence?: string } | null> { + if (e2eSittingsOff()) return null; + try { + const status = await readXSessionStatus(paths); + const limit = xSittingJobs(settingsNow()?.social?.x); + const look = await xSittingLook(paths, { refreshedAt: status.cookiesUpdatedAt ?? null, kind: "timelines", limit }); + if (!look.status.readable) return { left: 0, sentence: look.verdict.ok ? undefined : look.verdict.sentence }; + if (look.status.left > 0) return { left: look.status.left }; + return { left: 0, ...(look.verdict.ok ? {} : { sentence: look.verdict.sentence }) }; + } catch { + return null; + } } // HOW MANY X JOBS MAY START NOW under X's job cap (0 when it is reached or // its count cannot be read): for the scheduler, which queues no more X syncs // than that (review 3 N9). A look: nothing is counted. -export async function xCapRoom(paths: Pick<Paths, "transcriptsDir" | "jobsDir">, now?: number): Promise<number> { +export async function xCapRoom(paths: Paths, now?: number): Promise<number> { const status = await xJobCapStatus(paths, now ?? queueGapClock().now()); if (!status.ok) return 0; - return Math.max(0, Math.min(status.perHour - status.lastHour, status.perDay - status.lastDay)); + const cap = Math.max(0, Math.min(status.perHour - status.lastHour, status.perDay - status.lastDay)); + // No more than X's sitting has left, either. + const sitting = await xSittingHeld(paths); + return sitting ? Math.min(cap, sitting.left) : cap; } export async function xJobGuard(opts: { @@ -380,15 +513,25 @@ export async function xJobGuard(opts: { channelSlug?: string; now?: number; counts?: boolean; + sittingKind?: XSittingKind; + recordsAvailability?: boolean; + what?: string; }): Promise<XGuardResult> { const r = await xSessionReport(opts); - if (r.allowed) return { ok: true, ...(r.note ? { note: r.note } : {}) }; - const capped = r.cap.reached && r.alert === null && r.reason !== null && /^X's job (cap|count)/.test(r.reason); - const nextAt = capped && r.cap.nextAt ? Date.parse(r.cap.nextAt) : undefined; + if (r.allowed) { + return { + ok: true, + ...(r.note ? { note: r.note } : {}), + ...(r.account.state === "suspended" ? { accountAlert: r.account.alert ?? "The X account is marked suspended." } : {}), + }; + } + const capped = r.refusedBy === "cap"; + const nextAt = capped && r.cap.nextAt ? Date.parse(r.cap.nextAt) : r.refusedBy === "cooldown" && r.cooldown ? Date.parse(r.cooldown.until) : undefined; return { ok: false, message: r.reason ?? "X job refused.", alert: r.alert !== null, + ...(r.refusedBy ? { refusedBy: r.refusedBy } : {}), ...(capped ? { capped: true as const } : {}), ...(nextAt !== undefined && Number.isFinite(nextAt) ? { nextAt } : {}), }; @@ -397,13 +540,22 @@ export async function xJobGuard(opts: { // THE JOB'S PLAN, for X's job cap (lib/xJobRule.ts xJobCounts): its kind, its // spec's params, and whether its channel is a trending library (read here, // never taken from the caller). -async function xJobPlanOf(opts: NetworkJobOpts): Promise<XJobPlan> { +type XGuardPlan = XJobPlan & { channel?: XJobPlan["channel"] & { search?: boolean } }; + +async function xJobPlanOf(opts: NetworkJobOpts): Promise<XGuardPlan> { const params = planParams(opts); - let channel: XJobPlan["channel"]; + let channel: XGuardPlan["channel"]; if (opts.channelSlug) { const read = await readJsonFile(path.join(opts.paths.channelsDir, opts.channelSlug, "config.json")).catch(() => null); const config = read?.ok ? channelConfigSchema.parse(read.value) : null; - if (config) channel = { library: isXTrendingChannel(config), ...(config.postCaptureThread === true ? { postCaptureThread: true } : {}) }; + if (config) { + channel = { + library: isXTrendingChannel(config), + ...(config.postCaptureThread === true ? { postCaptureThread: true } : {}), + // An X search channel: its fetch is the search walk (browse). + ...(config.xSearch ? { search: true } : {}), + }; + } } return { kind: opts.kind, ...(params ? { params } : {}), ...(channel ? { channel } : {}) }; } @@ -428,14 +580,30 @@ async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promi // WHAT COUNTS (ruling R-a): decided from the job's own plan. A job that // does not count is not refused by the cap either; everything else of X's // guard holds for it. - const counts = xJobCounts(await xJobPlanOf(opts)); - const x = await xJobGuard({ paths: opts.paths, channelSlug: opts.channelSlug, counts }); + const plan = await xJobPlanOf(opts); + const counts = xJobCounts(plan); + // ITS SITTING KIND (lib/xSitting.ts): from its plan — its kind and its + // channel's config — never from a flag. An X run's own start (no channel) + // is no job of either kind: each channel is guarded with its slug. + const runStart = opts.kind === "x-run" && !opts.channelSlug; + const sittingKind = runStart ? undefined : xSittingKindOf(plan); + const what = `${jobKindLabel(opts.kind)}${opts.channelSlug ? ` for ${opts.channelSlug}` : ""}`; + const x = await xJobGuard({ + paths: opts.paths, + channelSlug: opts.channelSlug, + counts, + ...(sittingKind ? { sittingKind } : {}), + recordsAvailability: xSuspendedRefuses(plan), + what, + }); if (x.ok) { + const notes: string[] = x.note ? [x.note] : []; // THE START, COUNTED: checked and recorded in one step. An X run's own // start asks X nothing: each of its channels is a start (it is guarded, // with its slug, before each one). - if (counts && opts.countStart && opts.job && !(opts.kind === "x-run" && !opts.channelSlug)) { - const counted = await recordXJobStart(opts.paths, queueGapClock().now()); + if (counts && opts.countStart && opts.job && !runStart) { + const at = queueGapClock().now(); + const counted = await recordXJobStart(opts.paths, at); if (!counted.ok) { return { ok: false, @@ -443,23 +611,54 @@ async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promi ...(!counted.unreadable && counted.nextAt !== undefined ? { deferUntil: counted.nextAt } : {}), }; } - // The start on the job's own record (and its sidecar), so a lost count - // is rebuilt from the records (jobs/xJobCap.ts). + // THE SITTING, COUNTED (lib/xSitting.ts): checked and recorded in one + // step under its own lock. Refused here only on a race (the look above + // passed): the cap's start stays counted — more rather than fewer. const record = getRegistry().get(opts.job.id); + let sat: { began: string | null; kind: XSittingKind } | null = null; + if (sittingKind && !e2eSittingsOff()) { + const refreshedAt = (await readXSessionStatus(opts.paths)).cookiesUpdatedAt ?? null; + const r = await recordXSittingStart(opts.paths, { + refreshedAt, + kind: sittingKind, + limit: xSittingJobs(settingsNow()?.social?.x), + jobKind: opts.kind, + at: counted.at ?? at, + jobId: opts.job.id, + ...(opts.channelSlug ? { channel: opts.channelSlug } : {}), + }); + if (!r.verdict.ok) { + if (record && counted.at !== undefined) { + (record.xStarts ??= []).push(counted.at); + await writeJobMeta(opts.paths, record); + } + return { ok: false, error: r.verdict.sentence, deferUntil: 0 }; + } + sat = { began: r.began, kind: sittingKind }; + notes.push( + `X sitting: ${r.verdict.used} of ${r.verdict.limit} started (${sittingKind}, ` + + `${r.began ? `since the refresh at ${r.began.slice(11, 16)} UTC` : "no refresh on record"}); ${r.verdict.left} left.`, + ); + } + // The start on the job's own record (and its sidecar), so a lost count + // — and a lost sitting — is rebuilt from the records. if (record && counted.at !== undefined) { (record.xStarts ??= []).push(counted.at); + if (sat) (record.xSittings ??= []).push({ ...sat, at: counted.at }); await writeJobMeta(opts.paths, record); } } + // A suspended account (marked by hand): every X job's log says so. + if (x.accountAlert) notes.push(`${x.accountAlert} What X answers it may be thinned.`); // The jar passed at a job's START: a jar-age banner from an earlier // refusal clears. (Not at enqueue — the start follows, and enqueue stays // as cheap as it was.) if (opts.job) await noteXJarFresh(opts.paths); - return { ok: true, notes: x.note ? [x.note] : [] }; + return { ok: true, notes }; } if (x.alert && opts.job) { await noteServiceStoppedJob(opts.paths, X_SERVICE, { id: opts.job.id, kind: opts.kind }); - } else if (!x.alert && !x.capped) { + } else if (!x.alert && x.refusedBy === "jar") { // The fresh-jar rule refused it: X's cookie banner says so on the // dashboard (kind jar-age), and a job refused at its start is offered for // "Re-run stopped jobs" once the jar is fresh. @@ -469,7 +668,11 @@ async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promi ...(opts.job ? { job: { id: opts.job.id, kind: opts.kind } } : {}), }); } - return { ok: false, error: x.message, ...(x.capped && x.nextAt !== undefined ? { deferUntil: x.nextAt } : {}) }; + // A cap, a cooldown or a sitting met AT A START ends the job deferred, not + // failed: nothing retries it (a sitting's until 0: until a Refresh). + const deferUntil = + (x.refusedBy === "cap" || x.refusedBy === "cooldown") && x.nextAt !== undefined ? x.nextAt : x.refusedBy === "sitting" ? 0 : undefined; + return { ok: false, error: x.message, ...(deferUntil !== undefined ? { deferUntil } : {}) }; } // Instagram's: its alert, then its cooldown (jobs/instagramGuard.ts). diff --git a/common/jobs/pacingGuard.test.ts b/common/jobs/pacingGuard.test.ts @@ -34,6 +34,10 @@ await writeFile( `#!/usr/bin/env node import { appendFileSync } from "node:fs"; appendFileSync(process.env.FAKE_RUNS, process.argv.slice(2).join(" ") + "\\n"); +if (process.env.FAKE_MODE === "ratelimit") { + // X's API answered 429: gallery-dl waits it out between pages (ratelimit=wait). + process.stderr.write("[twitter][info] Waiting for 14 minutes until 15:11:22 (rate limit)\\n"); +} if (process.env.FAKE_MODE === "challenge") { // X answers after a moment, as it does: the loop has queued all 13 by then // (on a loaded machine an instant answer raced the loop's later enqueues). @@ -83,6 +87,7 @@ const { fetchPosts } = await import("../controller/fetchPosts"); const { getSettings } = await import("../lib/settings"); const { setQueueGapClock, clearQueueGaps } = await import("./queueGap"); const { xJobStartsFile } = await import("./xJobCap"); +const { xSittingFile } = await import("./xSitting"); const { readServiceCookieState, serviceCookiesFile } = await import("../lib/serviceCookies-server"); await import("../social/xGalleryDlFetcher"); @@ -131,6 +136,8 @@ async function reset(): Promise<void> { // 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 sitting (jobs/xSitting.ts): each test starts a fresh one. + await writeFile(xSittingFile(paths), JSON.stringify({ version: 1, began: null, kind: null, starts: [] })); } async function readLog(jobId: string): Promise<string> { @@ -177,7 +184,7 @@ test("13 X fetches, job 1 meets a Cloudflare challenge: job 1 fails, the X alert } }); -test("13 X fetches with no challenge start at least pacing.jobGapSeconds.twitter (300 s) apart", async () => { +test("13 X fetches queued in one loop: the sitting's 4 start 5-12 min apart (drawn), the other 9 end deferred unasked", async () => { await reset(); await writeJar(5 * 60_000); const starts = new Map<string, number>(); @@ -189,15 +196,21 @@ test("13 X fetches with no challenge start at least pacing.jobGapSeconds.twitter } const ends = await Promise.all(started.map((r) => (r.ok ? r.done : null))); assert.deepEqual(ends.map((e) => e?.status), Array(13).fill("done")); - assert.equal(await runCount(), 13); - const at = SLUGS.map((s) => starts.get(s)!); + // Only the sitting's four asked anything (lib/xSitting.ts: 4 per cookie refresh). + assert.equal(await runCount(), 4); + assert.deepEqual([...starts.keys()], SLUGS.slice(0, 4)); + for (const e of ends.slice(4)) { + assert.match(await readLog(e!.jobId), /\[deferred\] This X sitting is used up: 4 of 4 X jobs started/); + } + const at = SLUGS.slice(0, 4).map((s) => starts.get(s)!); for (let i = 1; i < at.length; i++) { - assert.ok(at[i] - at[i - 1] >= 300_000, `job ${i + 1} started ${(at[i] - at[i - 1]) / 1000}s after job ${i}`); + // The gap runs from the previous job's end (3 s after its start) and is drawn in 5-12 min. + const gap = at[i] - at[i - 1] - 3_000; + assert.ok(gap >= 300_000 && gap <= 720_000, `job ${i + 1} started ${gap / 1000}s after job ${i} ended`); } - // The waiting job's log says why it waited. + // The waiting job's log says why it waited, and what was drawn. const log2 = await readLog(ends[1]!.jobId); - // 5 min at least, stretched by up to pacing.jitter (lib/jitter.mjs). - assert.match(log2, /waiting [56]m\d\ds: X jobs are spaced 5 min apart \(pacing\.jobGapSeconds\.twitter\)/); + assert.match(log2, /waiting \d+m\d\ds \(a \d+m\d\ds gap drawn from 5-12 min\): X jobs are spaced 5-12 min apart, drawn per job/); // The end survives a restart: the file names the queue. const file = JSON.parse(await readFile(path.join(paths.jobsDir, "queue-gaps.json"), "utf8")); assert.equal(typeof file.ends["platform:twitter"], "number"); @@ -387,21 +400,21 @@ test("R2a: a job that asks X is refused on any queue but X's — at enqueue for assert.equal(await runCount(), before, "gallery-dl was never started"); }); -test("R2b: X's job cap — the 13th X job in an hour is refused before it starts, over every kind together, and get x-session shows the count", async () => { +test("R2b: X's job cap — the 7th X job in an hour is refused before it starts, over every kind together, and get x-session shows the count", async () => { await reset(); await writeJar(5 * 60_000); const before = await runCount(); - // Eleven starts on record, of whatever kinds; then one fetch through the funnel is the twelfth. - for (let i = 0; i < 11; i++) await recordXJobStart(paths, fakeNow); - const twelfth = await fetchJob(SLUGS[0], new Map()); - assert.equal(twelfth.ok, true, twelfth.ok ? "" : twelfth.error); - if (twelfth.ok) assert.equal((await twelfth.done).status, "done"); - assert.equal((await xJobCapStatus(paths, fakeNow)).lastHour, 12); - // The thirteenth, of ANOTHER kind: refused at enqueue, no job at all, with when the next may start. + // Five starts on record, of whatever kinds; then one fetch through the funnel is the sixth. + for (let i = 0; i < 5; i++) await recordXJobStart(paths, fakeNow); + const sixth = await fetchJob(SLUGS[0], new Map()); + assert.equal(sixth.ok, true, sixth.ok ? "" : sixth.error); + if (sixth.ok) assert.equal((await sixth.done).status, "done"); + assert.equal((await xJobCapStatus(paths, fakeNow)).lastHour, 6); + // The seventh, of ANOTHER kind: refused at enqueue, no job at all, with when the next may start. for (const [kind, slug] of [["fetch-posts", SLUGS[1]], ["capture-posts", SLUGS[1]], ["check-post-availability", SLUGS[2]], ["import-post", SLUGS[2]], ["read-x-trending", undefined], ["x-run", undefined]] as const) { const res = await runManagedFunction({ kind, queueKey: "platform:twitter", paths, ...(slug ? { channelSlug: slug } : {}), fn: async () => assert.fail("the job ran") }); assert.equal(res.ok, false, kind); - assert.match(res.ok ? "" : res.error, /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes \(the cap is 12\)\. The next X job may start at \d\d:\d\d UTC \(in \d+ min\); ask again then/, kind); + assert.match(res.ok ? "" : res.error, /^X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes \(the cap is 6\)\. The next X job may start at \d\d:\d\d UTC \(in \d+ min\); ask again then/, kind); } assert.equal(await runCount(), before + 1); // The cap raises no cookie banner: it is not the jar's fault. @@ -409,7 +422,7 @@ test("R2b: X's job cap — the 13th X job in an hour is refused before it starts // get x-session: the count, the caps, and the refusal. const report = await xReport({ paths }); assert.equal(report.allowed, false); - assert.deepEqual({ ...report.cap, nextAt: typeof report.cap.nextAt }, { lastHour: 12, perHour: 12, lastDay: 12, perDay: 150, reached: true, nextAt: "string" }); + assert.deepEqual({ ...report.cap, nextAt: typeof report.cap.nextAt }, { lastHour: 6, perHour: 6, lastDay: 6, perDay: 150, reached: true, nextAt: "string" }); assert.match(report.reason ?? "", /^X's job cap is reached/); // An hour on, the oldest starts have left the window and X jobs start again. fakeNow += 61 * 60_000; @@ -441,11 +454,11 @@ test("R2b: the start is counted once, by the last guard before the work; a look assert.equal((await guardNetworkJob({ kind: "reparse-x-trending", queueKey: "platform:twitter", paths, job, countStart: true })).ok, true); assert.equal(await count(), 2); // The cap fills while a job waits its turn: its start is refused, and the refused start is not counted. - for (let i = 0; i < 10; i++) await recordXJobStart(paths, fakeNow); + for (let i = 0; i < 4; i++) await recordXJobStart(paths, fakeNow); const late = await guardNetworkJob({ ...opts, job, countStart: true }); assert.equal(late.ok, false); assert.match(late.ok ? "" : late.error, /^X's job cap is reached/); - assert.equal(await count(), 12); + assert.equal(await count(), 6); // A count that cannot be read refuses every X job, at enqueue and at the start. await writeFile(path.join(transcripts, ".x-session", "job-starts.json"), "{broken"); for (const g of [await guardNetworkJob(opts), await guardNetworkJob({ ...opts, job, countStart: true })]) { @@ -476,43 +489,46 @@ test("M1: ONE count for the machine — a flipped login source, a respelled cook await writeJar(5 * 60_000); const count = async () => (await xJobCapStatus(paths, fakeNow)).lastHour; const start = (kind: string, slug: string) => guardNetworkJob({ kind, queueKey: "platform:twitter", paths, channelSlug: slug, job: { id: `m1-${kind}-${slug}` }, countStart: true }); + // One sitting of six (the most there is), so the cap is what fills here. + const SIX = { sittingJobs: 6 }; try { - // Three starts on the connected profile. - for (let i = 0; i < 3; i++) assert.equal((await start("fetch-posts", SLUGS[0])).ok, true); - assert.equal(await count(), 3); + await writeSettings({ cookieSource: "profile", ...SIX }); + // Two starts on the connected profile. + for (let i = 0; i < 2; i++) assert.equal((await start("fetch-posts", SLUGS[0])).ok, true); + assert.equal(await count(), 2); // The login source flipped to the browser: the same count, not a fresh one. - await writeSettings({ cookieSource: "browser" }, { cookiesFromBrowser: "firefox" }); - assert.equal((await xReport({ paths })).cap.lastHour, 3); - for (let i = 0; i < 3; i++) assert.equal((await start("fetch-posts", SLUGS[0])).ok, true); - assert.equal(await count(), 6); + await writeSettings({ cookieSource: "browser", ...SIX }, { cookiesFromBrowser: "firefox" }); + assert.equal((await xReport({ paths })).cap.lastHour, 2); + assert.equal((await start("fetch-posts", SLUGS[0])).ok, true); + assert.equal(await count(), 3); // The same browser spelled another way: still the same count. - await writeSettings({ cookieSource: "browser" }, { cookiesFromBrowser: " firefox:default " }); - assert.equal((await xReport({ paths })).cap.lastHour, 6); + await writeSettings({ cookieSource: "browser", ...SIX }, { cookiesFromBrowser: " firefox:default " }); + assert.equal((await xReport({ paths })).cap.lastHour, 3); assert.equal((await start("capture-posts", SLUGS[1])).ok, true); // A channel with a cookie spec of its own: the same count. await channelSpec(SLUGS[2], "chromium"); - assert.equal((await xReport({ paths, channelSlug: SLUGS[2] })).cap.lastHour, 7); + assert.equal((await xReport({ paths, channelSlug: SLUGS[2] })).cap.lastHour, 4); assert.equal((await start("check-post-availability", SLUGS[2])).ok, true); - // An X run over channels of different specs: each channel one start, in the one count. + // An X run over a channel of another spec: each channel one start, in the one count. await channelSpec(SLUGS[3], "brave"); await channelSpec(SLUGS[4], "chromium:Profile 2"); - for (const slug of [SLUGS[3], SLUGS[4], SLUGS[5], SLUGS[6]]) assert.equal((await start("x-run", slug)).ok, true); - assert.equal(await count(), 12); - // The thirteenth is refused whatever it uses. + assert.equal((await start("x-run", SLUGS[3])).ok, true); + assert.equal(await count(), 6); + // The seventh is refused whatever it uses. for (const [x, top, slug] of [ - [{ cookieSource: "profile" }, {}, SLUGS[7]], - [{ cookieSource: "browser" }, { cookiesFromBrowser: "firefox" }, SLUGS[7]], - [{ cookieSource: "browser" }, { cookiesFromBrowser: "safari" }, SLUGS[3]], + [{ cookieSource: "profile", ...SIX }, {}, SLUGS[7]], + [{ cookieSource: "browser", ...SIX }, { cookiesFromBrowser: "firefox" }, SLUGS[7]], + [{ cookieSource: "browser", ...SIX }, { cookiesFromBrowser: "safari" }, SLUGS[4]], ] as const) { await writeSettings(x, top); const refused = await start("fetch-posts", slug); assert.equal(refused.ok, false); - assert.match(refused.ok ? "" : refused.error, /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes/); + assert.match(refused.ok ? "" : refused.error, /^X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes/); } // get x-session names no login: the count is the machine's. const report = await xReport({ paths }); assert.equal("login" in report, false); - assert.deepEqual([report.cap.lastHour, report.cap.reached], [12, true]); + assert.deepEqual([report.cap.lastHour, report.cap.reached], [6, true]); } finally { await writeSettings({ cookieSource: "profile" }); for (const slug of [SLUGS[2], SLUGS[3], SLUGS[4]]) await channelSpec(slug, undefined); @@ -539,7 +555,7 @@ test("R-a: a trending library's media-only capture is not counted and not refuse assert.equal((await capture({ ...mediaOnly, shots: true })).ok, true); assert.equal(await count(), 2, "the keep capture and the capture with shots are"); // The cap reached: the media-only capture still starts (it asks x.com nothing); the others are refused. - for (let i = 0; i < 10; i++) await recordXJobStart(paths, fakeNow); + 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 }]) { @@ -568,8 +584,8 @@ test("R-b: a job that meets the cap AT ITS START ends deferred — done, not fai const blocker = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: SLUGS[0], fn: async () => gate }); assert.equal(blocker.ok, true); for (let i = 0; i < 100 && (await xJobCapStatus(paths, fakeNow)).lastHour < 1; i++) await new Promise((r) => setTimeout(r, 20)); - // Ten more: eleven. The next passes its enqueue (a slot is left)… - for (let i = 0; i < 10; i++) await recordXJobStart(paths, fakeNow); + // Four more: five. The next passes its enqueue (a slot is left)… + for (let i = 0; i < 4; i++) await recordXJobStart(paths, fakeNow); const late = await fetchJob(SLUGS[1], new Map()); assert.equal(late.ok, true, late.ok ? "" : late.error); // …and the cap fills while it waits behind the first. @@ -581,7 +597,7 @@ test("R-b: a job that meets the cap AT ITS START ends deferred — done, not fai assert.equal(end.status, "done"); const record = getRegistry().get(late.jobId)!; assert.ok(record.deferred, "the record says it was deferred"); - assert.match(record.deferred!.sentence, /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes/); + assert.match(record.deferred!.sentence, /^X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes/); assert.equal(record.deferred!.until, (await xJobCapStatus(paths, fakeNow)).nextAt); assert.match(await readLog(late.jobId), /^\[deferred\] X's job cap is reached/m); assert.doesNotMatch(await readLog(late.jobId), /^\[error\]/m); @@ -589,7 +605,7 @@ test("R-b: a job that meets the cap AT ITS START ends deferred — done, not fai assert.deepEqual([meta?.status, meta?.deferred?.until, meta?.xStarts], ["done", record.deferred!.until, []]); // Nothing was asked, no start was counted, and no cookie banner was raised. assert.equal(await runCount(), before); - assert.equal((await xJobCapStatus(paths, fakeNow)).lastHour, 12); + assert.equal((await xJobCapStatus(paths, fakeNow)).lastHour, 6); assert.equal((await readServiceCookieState(paths)).services.x?.raisedAt, undefined); // The first job's own record carries its start (the count can be rebuilt from it). assert.equal((await readJobMeta(paths, blocker.jobId))?.xStarts?.length, 1); @@ -690,3 +706,35 @@ 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 () => { + 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"; + try { + const res = await fetchJob(SLUGS[0], new Map()); + assert.equal(res.ok, true, res.ok ? "" : res.error); + if (!res.ok) return; + 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 argv = (await readFile(RUNS, "utf8")).trim().split("\n").at(-1) ?? ""; + 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/queueGap.test.ts b/common/jobs/queueGap.test.ts @@ -76,13 +76,16 @@ test("no end yet: no wait; an end: wait out the rest; the end is persisted and r delete process.env.E2E_JOB_GAP_SECONDS; const paths = await jobsDir(); const q = "platform:twitter"; - // jitter 0: the exact gap (the jittered one has its own test below). + // X's gap is drawn from a range (jobs/xSittings.test.ts); a range of one + // value (5-5 min) makes it exact here. const exact = { jobGapSeconds: {}, jitter: 0 }; - assert.equal(await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_000_000 }), null); + 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 }); + const w = await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_048_000, xGap }); assert.equal(w?.remainingMs, 252_000); - assert.equal(await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_300_000 }), null); + 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); const file = JSON.parse(await readFile(path.join(paths.jobsDir, "queue-gaps.json"), "utf8")); assert.equal(file.ends[q], 1_000_000); clearQueueGaps(); // the restart diff --git a/common/jobs/queueGap.ts b/common/jobs/queueGap.ts @@ -15,6 +15,14 @@ // end: a job refused at its start (a stale X jar, a raised alert) asked // nothing, so the next one is not made to wait for it. // +// X'S GAP IS DRAWN, NOT FIXED (lane x-sittings, lib/xSitting.ts): a job on +// `platform:twitter` waits a gap drawn per job, uniform in +// `social.x.gapMinMinutes`-`gapMaxMinutes` (default 5-12 min, never below 5; +// an explicit `pacing.jobGapSeconds.twitter` above the minimum raises it), and +// says what was drawn ("waiting 8m41s (a 9m02s gap drawn from 5-12 min): …"). +// 12 fetches each 5-6 minutes after the last preceded the account's +// suspension; a fixed beat is what a script looks like. +// // The last end per queue is kept in memory and in `<jobsDir>/queue-gaps.json`, // so an editor restart is not a free pass (the scheduler's first tick after a // boot would otherwise ask X at once). @@ -32,6 +40,9 @@ import { JOB_GAP_DEFAULT_SECONDS, jobGapSecondsFor } from "../lib/jobGap"; import type { PacingSettingsBlock } from "../lib/settingsSchema"; import { jitterUpStable } from "../lib/jitter.mjs"; import { pacingJitter } from "../lib/jitter"; +import { randomInt } from "node:crypto"; +import { drawXGapSeconds, xGapRange, xGapRangeText, type XGapRange } from "../lib/xSitting"; +import { getSettings } from "../lib/settings"; export { spanText, waitText }; @@ -61,6 +72,85 @@ function builtInGaps(): Readonly<Record<string, number>> { export type QueueGap = { seconds: number; key: string }; +// TEST-ONLY, as above: the e2e server's E2E_JOB_GAP_SECONDS, which collapses +// X's drawn range to that one value too (0: no gap), else undefined. +function e2eGapSeconds(): number | undefined { + const raw = process.env.E2E_JOB_GAP_SECONDS; + if (raw === undefined || raw === "") return undefined; + const n = Number(raw); + return Number.isFinite(n) && n >= 0 ? Math.floor(n) : undefined; +} + +// ── X's gap: drawn per job (lane x-sittings, lib/xSitting.ts) ────────────── + +export type XGapSettings = { gapMinMinutes?: number; gapMaxMinutes?: number }; + +// The range X's gap is drawn from: `social.x.gapMinMinutes`-`gapMaxMinutes` +// (default 5-12 min, never below 5), an explicit pacing.jobGapSeconds.twitter +// raising the minimum. The e2e server's E2E_JOB_GAP_SECONDS collapses it. +export function xQueueGapRange( + pacing: Pick<PacingSettingsBlock, "jobGapSeconds"> | undefined, + x: XGapSettings | undefined, +): XGapRange { + const e2e = e2eGapSeconds(); + if (e2e !== undefined) return { minSeconds: e2e, maxSeconds: e2e }; + return xGapRange(x, pacing?.jobGapSeconds?.twitter); +} + +// THE DRAW: uniform in the range, from the system's random source — or, in a +// test, a seeded one (setXGapRandom). Drawn ONCE per wait: a wait is re-read +// after every sleep, and a fresh draw per read would end it at the shortest. +declare global { + // eslint-disable-next-line no-var + var __yttXGapRandom__: (() => number) | undefined; + // eslint-disable-next-line no-var + var __yttXGapDraws__: Map<string, number> | undefined; +} + +// TEST-ONLY: a seeded generator (mulberry32) for the draw; null restores the +// system's random source. +export function setXGapRandom(seed: number | null): void { + if (seed === null) { + globalThis.__yttXGapRandom__ = undefined; + return; + } + let a = seed >>> 0; + globalThis.__yttXGapRandom__ = () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function xGapRandom(): number { + return globalThis.__yttXGapRandom__ ? globalThis.__yttXGapRandom__() : randomInt(0, 2 ** 32) / 2 ** 32; +} + +// The gap drawn for the wait after the end at `last` on `queueKey` (memoised: +// the same wait, re-read, keeps its draw; a range changed while it waits is +// drawn again, within the new range). +export function drawnXGapSeconds(queueKey: string, last: number, range: XGapRange): number { + const draws = (globalThis.__yttXGapDraws__ ??= new Map()); + const key = `${queueKey}@${last}@${range.minSeconds}-${range.maxSeconds}`; + let seconds = draws.get(key); + if (seconds === undefined) { + seconds = drawXGapSeconds(range, xGapRandom()); + if (draws.size > 256) draws.clear(); + draws.set(key, seconds); + } + return seconds; +} + +function xGapSettingsNow(): XGapSettings | undefined { + try { + return getSettings().social?.x; + } catch { + return undefined; + } +} + export function queueGapFor( pacing: Pick<PacingSettingsBlock, "jobGapSeconds"> | undefined, platform: string, @@ -169,6 +259,7 @@ export function noteQueueJobEnd( export function clearQueueGaps(): void { globalThis.__yttQueueGaps__?.clear(); + globalThis.__yttXGapDraws__?.clear(); } // ── the wait ─────────────────────────────────────────────────────────────── @@ -185,6 +276,8 @@ export type QueueGapWait = { until: number; remainingMs: number; reason: string; + // X's gap: the seconds drawn for this wait, and the range drawn from. + drawn?: { seconds: number; range: XGapRange }; }; // How long a network job on `queueKey` must still wait, or null for none. @@ -199,9 +292,28 @@ export async function queueGapWait(opts: { queueKey: string; pacing: (Pick<PacingSettingsBlock, "jobGapSeconds"> & { jitter?: number }) | undefined; now: number; + // X's range settings (`social.x`); absent: read from settings. + xGap?: XGapSettings; }): Promise<QueueGapWait | null> { const platform = queueGapPlatform(opts.queueKey); if (!platform) return null; + // X'S GAP IS DRAWN PER JOB from its range (lane x-sittings), not stretched + // from a fixed beat: the draw is the unevenness, so no jitter is added. + if (platform === "twitter") { + const range = xQueueGapRange(opts.pacing, opts.xGap ?? xGapSettingsNow()); + if (range.maxSeconds <= 0) return null; + const last = await lastQueueEnd(opts.paths, opts.queueKey); + if (last === undefined) return null; + const seconds = drawnXGapSeconds(opts.queueKey, last, range); + const until = last + seconds * 1000; + if (until <= opts.now) return null; + return { + until, + remainingMs: until - opts.now, + reason: `X jobs are spaced ${xGapRangeText(range)} apart, drawn per job (social.x.gapMinMinutes, social.x.gapMaxMinutes)`, + drawn: { seconds, range }, + }; + } const gap = queueGapFor(opts.pacing, platform); if (gap.seconds <= 0) return null; const last = await lastQueueEnd(opts.paths, opts.queueKey); @@ -221,7 +333,11 @@ export async function queueGapWait(opts: { // The line a waiting job's log carries: // "waiting 4m12s: X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)". +// X's: "waiting 8m41s (a 9m02s gap drawn from 5-12 min): X jobs are spaced …". export function queueGapLine(w: QueueGapWait): string { + if (w.drawn) { + return `waiting ${waitText(w.remainingMs)} (a ${waitText(w.drawn.seconds * 1000)} gap drawn from ${xGapRangeText(w.drawn.range)}): ${w.reason}`; + } return `waiting ${waitText(w.remainingMs)}: ${w.reason}`; } diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts @@ -185,12 +185,18 @@ export type JobRecord = { // counted for (one for a job; one per channel for an X run). Kept on its // sidecar, so a count file that is lost is rebuilt from the records. xStarts?: number[]; + // The X sittings those starts were counted in (jobs/xSitting.ts): each + // start's sitting (the jar's refresh time; null: none on record) and kind, + // so a lost sitting file is rebuilt from the records. + xSittings?: Array<{ began: string | null; kind: "timelines" | "browse"; at: number }>; // A JOB THAT ENDED DEFERRED (review 2, ruling R-b): X's job cap was reached // when its queue started it, so it did not run — not a failure. It ends // `done` with this: the sentence, and when the next X job may start. // Nothing re-queues it by itself. ALSO (lane clean-unverified): a checked // Clean audio the source rate-limited — it deleted nothing it could not // verify and queued its own retry for `until` (controller/cleanAudioJob.ts). + // AND (lane x-sittings): an X job its sitting refused (used up, or of the + // other kind, jobs/xSitting.ts): `until` is 0 — until a person's Refresh. deferred?: { until: number; sentence: string }; }; diff --git a/common/jobs/xJobCap.test.ts b/common/jobs/xJobCap.test.ts @@ -37,17 +37,17 @@ const keptSince = (paths: ReturnType<typeof corpus>, since: number) => { test("M1: ONE count for the machine — checked and recorded in one step, kept across a restart", async () => { const paths = corpus("disk"); - for (let i = 0; i < 12; i++) assert.equal((await recordXJobStart(paths, T0 + i * MIN)).ok, true); - const refused = await recordXJobStart(paths, T0 + 12 * MIN); + for (let i = 0; i < 6; i++) assert.equal((await recordXJobStart(paths, T0 + i * MIN)).ok, true); + const refused = await recordXJobStart(paths, T0 + 6 * MIN); assert.equal(refused.ok, false); - assert.match(refused.sentence ?? "", /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes/); + assert.match(refused.sentence ?? "", /^X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes/); // A refused start records nothing; the file is one list, with no login in it. assert.deepEqual(Object.keys(fileOf(paths)).sort(), ["starts", "version"]); assert.equal(fileOf(paths).version, 2); - assert.equal(fileOf(paths).starts.length, 12); + assert.equal(fileOf(paths).starts.length, 6); // "Restart": nothing is in memory; the file is the count. const again = await xJobCapStatus(paths, T0 + 13 * MIN); - assert.deepEqual([again.ok, again.lastHour, again.lastDay, again.nextAt], [false, 12, 12, T0 + 60 * MIN]); + assert.deepEqual([again.ok, again.lastHour, again.lastDay, again.nextAt], [false, 6, 6, T0 + 60 * MIN]); // A start recorded with the clock set back is recorded at the clock's time // (review 3 S4); the later start on record still counts, and is kept. const p2 = corpus("disk-back"); @@ -59,24 +59,24 @@ test("M1: ONE count for the machine — checked and recorded in one step, kept a assert.deepEqual(fileOf(p2).starts, [T0 + 25 * HOUR]); // Two at once: both recorded, neither lost. const p3 = corpus("disk-race"); - await Promise.all(Array.from({ length: 12 }, (_, i) => recordXJobStart(p3, T0 + i))); - assert.equal(fileOf(p3).starts.length, 12); + await Promise.all(Array.from({ length: 6 }, (_, i) => recordXJobStart(p3, T0 + i))); + assert.equal(fileOf(p3).starts.length, 6); assert.equal((await recordXJobStart(p3, T0 + 20)).ok, false); }); test("M1: a count of the first shape (one list per login key) is the SUM of its lists, and is rewritten as one", async () => { const paths = corpus("migrate"); mkdirSync(path.dirname(xJobStartsFile(paths)), { recursive: true }); - // 7 starts under the profile, 5 under a browser spec: the same machine's twelve. + // 4 starts under the profile, 2 under a browser spec: the same machine's six. const logins = { - profile: Array.from({ length: 7 }, (_, i) => T0 + i * MIN), - "browser:firefox": Array.from({ length: 5 }, (_, i) => T0 + (10 + i) * MIN), + profile: Array.from({ length: 4 }, (_, i) => T0 + i * MIN), + "browser:firefox": Array.from({ length: 2 }, (_, i) => T0 + (10 + i) * MIN), }; writeFileSync(xJobStartsFile(paths), JSON.stringify({ version: 1, logins })); const status = await xJobCapStatus(paths, T0 + 20 * MIN); - assert.deepEqual([status.ok, status.lastHour], [false, 12]); + assert.deepEqual([status.ok, status.lastHour], [false, 6]); assert.equal(fileOf(paths).version, 2); - assert.equal(fileOf(paths).starts.length, 12); + assert.equal(fileOf(paths).starts.length, 6); assert.equal((await recordXJobStart(paths, T0 + 21 * MIN)).ok, false); }); @@ -102,7 +102,7 @@ test("a count that cannot be read fails closed: no X job starts, and nothing is test("R-c: a fresh corpus where no X job ever ran starts at zero", async () => { const paths = corpus("fresh"); - assert.deepEqual(await xJobCapStatus(paths, T0), { ok: true, lastHour: 0, lastDay: 0, perHour: 12, perDay: 150 }); + assert.deepEqual(await xJobCapStatus(paths, T0), { ok: true, lastHour: 0, lastDay: 0, perHour: 6, perDay: 150 }); // Records of other queues only: still zero. const p2 = corpus("fresh-other-queues"); meta(p2, { kind: "download-missing", queueKey: "platform:youtube", startedAt: T0 - MIN }); @@ -200,15 +200,15 @@ test("review 3 S4: a start in the future counts in both windows and never prunes const paths = corpus("future"); mkdirSync(path.dirname(xJobStartsFile(paths)), { recursive: true }); // Ten real starts and one stamped a year ahead (a clock that jumped forward, then back). - const real = Array.from({ length: 10 }, (_, i) => T0 + i * MIN); + const real = Array.from({ length: 4 }, (_, i) => T0 + i * MIN); writeFileSync(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [...real, T0 + 365 * 24 * HOUR] })); const status = await xJobCapStatus(paths, T0 + 10 * MIN); - assert.deepEqual([status.ok, status.lastHour, status.lastDay], [true, 11, 11]); + assert.deepEqual([status.ok, status.lastHour, status.lastDay], [true, 5, 5]); const r = await recordXJobStart(paths, T0 + 10 * MIN); - assert.deepEqual([r.ok, r.at, r.lastHour], [true, T0 + 10 * MIN, 12]); + assert.deepEqual([r.ok, r.at, r.lastHour], [true, T0 + 10 * MIN, 6]); // The real starts are kept beside the future one. assert.deepEqual(fileOf(paths).starts, [...real, T0 + 365 * 24 * HOUR, T0 + 10 * MIN]); - assert.equal((await recordXJobStart(paths, T0 + 11 * MIN)).ok, false, "the hour holds twelve"); + assert.equal((await recordXJobStart(paths, T0 + 11 * MIN)).ok, false, "the hour holds six"); }); test("review 3 M3: a rebuild that cannot show its records cover the last day refuses, writes nothing, and ends by itself", async () => { diff --git a/common/jobs/xJobCap.ts b/common/jobs/xJobCap.ts @@ -73,6 +73,13 @@ async function readStartsFile(paths: CapPaths): Promise<{ state: "absent" } | { return { state: "bad" }; } +// The counted starts on disk, for X's sitting rebuild (jobs/xSitting.ts): +// null when the file is absent or cannot be read. A look: nothing written. +export async function readXJobStarts(paths: CapPaths): Promise<number[] | null> { + const file = await readStartsFile(paths); + return file.state === "ok" ? file.starts : null; +} + // ── the records are kept (review 3 M3) ───────────────────────────────────── // RETENTION NEVER DELETES THE RECORD OF AN X JOB THAT MAY STILL COUNT diff --git a/common/jobs/xSitting.ts b/common/jobs/xSitting.ts @@ -0,0 +1,252 @@ +// X'S SITTING, ON DISK (lane x-sittings; the rule and its numbers are +// lib/xSitting.ts). `<transcripts>/.x-session/sitting.json`: +// { "version": 1, "began": <iso> | null, "kind": "timelines" | "browse" | "unknown" | null, +// "starts": [{ "at": <ms>, "jobKind": "fetch-posts", "kind": "timelines", "jobId"?, "channel"? }, …] } +// +// - read and written under its lock (one check-and-record at a time), and +// it survives a restart; +// - A NEW SITTING BEGINS ONLY AT A LATER REFRESH: when the jar's refresh +// time (social/xSessionBroker.ts readXSessionStatus: the broker's own +// stamp, written by Connect and Refresh) is later than `began`. Nothing +// else resets it — not a restart, not a jar restored from a backup, not a +// clock set back; +// - it FAILS CLOSED: a file that is there and cannot be read or parsed +// refuses every counted X job until it is repaired; +// - A FILE THAT IS NOT THERE IS NOT A FRESH SITTING: it is rebuilt from what +// else counted the same starts — X's job count (jobs/xJobCap.ts: its +// starts since `began`) and the job records (`xSittings`: each start's +// sitting and kind). A sitting with starts and no recorded kind is +// "unknown", and refuses both kinds until the next Refresh. +// +// SERVER-ONLY (node:fs). + +import path from "node:path"; +import { readdir, readFile } from "node:fs/promises"; +import type { Paths } from "../lib/paths"; +import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server"; +import { + isLaterRefresh, + xSittingVerdict, + type XSittingKind, + type XSittingState, + type XSittingVerdict, +} from "../lib/xSitting"; +import { readXJobStarts } from "./xJobCap"; + +type SittingPaths = Pick<Paths, "transcriptsDir" | "jobsDir">; + +export function xSittingFile(paths: Pick<Paths, "transcriptsDir">): string { + return path.join(paths.transcriptsDir, ".x-session", "sitting.json"); +} + +export type XSittingStart = { at: number; jobKind: string; kind: XSittingKind; jobId?: string; channel?: string }; + +type SittingFile = { + version: 1; + began: string | null; + kind: XSittingKind | "unknown" | null; + starts: XSittingStart[]; +}; + +const finite = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v); +const isKind = (v: unknown): v is XSittingKind => v === "timelines" || v === "browse"; + +function parseStart(v: unknown): XSittingStart | null { + const r = v as Record<string, unknown> | null; + if (!r || typeof r !== "object" || !finite(r.at) || typeof r.jobKind !== "string" || !isKind(r.kind)) return null; + return { + at: r.at, + jobKind: r.jobKind, + kind: r.kind, + ...(typeof r.jobId === "string" ? { jobId: r.jobId } : {}), + ...(typeof r.channel === "string" ? { channel: r.channel } : {}), + }; +} + +async function readSittingFile(paths: SittingPaths): Promise<{ state: "absent" } | { state: "bad" } | { state: "ok"; file: SittingFile }> { + const read = await readJsonFile(xSittingFile(paths)); + if (!read.ok) return read.reason === "absent" ? { state: "absent" } : { state: "bad" }; + const v = read.value as Record<string, unknown> | null; + if (!v || typeof v !== "object" || v.version !== 1) return { state: "bad" }; + if (!(v.began === null || (typeof v.began === "string" && Number.isFinite(Date.parse(v.began))))) return { state: "bad" }; + if (!(v.kind === null || v.kind === "unknown" || isKind(v.kind))) return { state: "bad" }; + if (!Array.isArray(v.starts)) return { state: "bad" }; + const starts: XSittingStart[] = []; + for (const raw of v.starts) { + const s = parseStart(raw); + if (!s) return { state: "bad" }; + starts.push(s); + } + return { state: "ok", file: { version: 1, began: v.began as string | null, kind: v.kind as SittingFile["kind"], starts } }; +} + +async function writeSittingFile(paths: SittingPaths, file: SittingFile): Promise<void> { + await writeJsonAtomic(xSittingFile(paths), file, { mkdir: true }); +} + +function stateOf(file: SittingFile): XSittingState { + const first = file.starts[0]; + return { + began: file.began, + kind: file.kind, + used: file.starts.length, + ...(first ? { first: { jobKind: first.jobKind, at: first.at } } : {}), + }; +} + +// ── the rebuild ──────────────────────────────────────────────────────────── + +// The sitting that began at `began`, from the job records and X's job count. +// The larger of the two counts is taken (more rather than fewer); the kind is +// the records' (the first start's), else "unknown" when anything started. +export async function rebuildXSitting(paths: SittingPaths, began: string | null): Promise<SittingFile> { + const since = began === null ? -Infinity : Date.parse(began); + const recorded: XSittingStart[] = []; + let names: string[] = []; + try { + names = await readdir(paths.jobsDir); + } catch { + names = []; + } + for (const name of names) { + if (!name.endsWith(".meta.json")) continue; + let m: Record<string, unknown> | null = null; + try { + const parsed = JSON.parse(await readFile(path.join(paths.jobsDir, name), "utf8")) as unknown; + m = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null; + } catch { + m = null; + } + if (!m || !Array.isArray(m.xSittings)) continue; + for (const raw of m.xSittings) { + const r = raw as { began?: unknown; kind?: unknown; at?: unknown } | null; + if (!r || !isKind(r.kind) || !finite(r.at) || (r.began ?? null) !== began) continue; + recorded.push({ + at: r.at, + jobKind: typeof m.kind === "string" ? m.kind : "?", + kind: r.kind, + ...(typeof m.id === "string" ? { jobId: m.id } : {}), + ...(typeof m.channelSlug === "string" ? { channel: m.channelSlug } : {}), + }); + } + } + recorded.sort((a, b) => a.at - b.at); + // X's job count holds every counted start of the last day: those since the + // refresh are this sitting's whether or not a record says so. + const capStarts = ((await readXJobStarts(paths)) ?? []).filter((t) => t >= since); + const starts = [...recorded]; + for (let i = recorded.length; i < capStarts.length; i++) { + // A start with no record of its kind: counted, of no known kind. + starts.push({ at: capStarts[i], jobKind: "?", kind: recorded[0]?.kind ?? "timelines" }); + } + const kind: SittingFile["kind"] = recorded[0]?.kind ?? (starts.length > 0 ? "unknown" : null); + return { version: 1, began, kind, starts }; +} + +// The sitting in force for a jar refreshed at `refreshedAt`, HOLDING THE +// LOCK: the one on disk, a new one when the jar was refreshed since, or the +// rebuilt one; written when it changed. `bad`: the file cannot be read. +async function loadLocked(paths: SittingPaths, refreshedAt: string | null): Promise<{ ok: true; file: SittingFile } | { ok: false }> { + const read = await readSittingFile(paths); + if (read.state === "bad") return { ok: false }; + if (read.state === "ok") { + if (isLaterRefresh(refreshedAt, read.file.began)) { + const fresh: SittingFile = { version: 1, began: refreshedAt, kind: null, starts: [] }; + await writeSittingFile(paths, fresh); + return { ok: true, file: fresh }; + } + return { ok: true, file: read.file }; + } + const rebuilt = await rebuildXSitting(paths, refreshedAt); + await writeSittingFile(paths, rebuilt); + return { ok: true, file: rebuilt }; +} + +export function xSittingUnreadableSentence(file: string): string { + return ( + `X's sitting cannot be read (${file}): no X job starts while it is unreadable, because the jobs a cookie refresh ` + + "admits are counted there. Repair the file (JSON: {version: 1, began, kind, starts: []}) or delete it (it is then " + + "counted again from the job records), then ask again." + ); +} + +export type XSittingStatus = { + // The file could be read (or rebuilt). + readable: boolean; + state: XSittingState; + limit: number; + used: number; + left: number; + // The refusal, when the file cannot be read. + sentence?: string; +}; + +function statusOf(file: SittingFile, limit: number): XSittingStatus { + const state = stateOf(file); + return { readable: true, state, limit, used: state.used, left: Math.max(0, limit - state.used) }; +} + +function closed(paths: SittingPaths, limit: number, began: string | null): XSittingStatus { + return { + readable: false, + state: { began, kind: "unknown", used: limit }, + limit, + used: limit, + left: 0, + sentence: xSittingUnreadableSentence(xSittingFile(paths)), + }; +} + +// The sitting as it stands for a jar refreshed at `refreshedAt` (a look: +// nothing is counted; a new sitting or a rebuild is written, under the lock). +export async function xSittingStatus(paths: SittingPaths, refreshedAt: string | null, limit: number): Promise<XSittingStatus> { + const read = await readSittingFile(paths); + if (read.state === "bad") return closed(paths, limit, refreshedAt); + if (read.state === "ok" && !isLaterRefresh(refreshedAt, read.file.began)) return statusOf(read.file, limit); + const loaded = await withJsonFileLock(xSittingFile(paths), () => loadLocked(paths, refreshedAt)); + return loaded.ok ? statusOf(loaded.file, limit) : closed(paths, limit, refreshedAt); +} + +// Would a job of `kind` start in the sitting now? (A look.) +export async function xSittingLook( + paths: SittingPaths, + opts: { refreshedAt: string | null; kind: XSittingKind; limit: number }, +): Promise<{ status: XSittingStatus; verdict: XSittingVerdict }> { + const status = await xSittingStatus(paths, opts.refreshedAt, opts.limit); + if (!status.readable) { + return { status, verdict: { ok: false, why: "unknown", used: status.used, left: 0, limit: opts.limit, sentence: status.sentence ?? "" } }; + } + return { status, verdict: xSittingVerdict(status.state, opts.kind, opts.limit) }; +} + +// ONE X JOB STARTS IN THE SITTING: checked and recorded in one step, under +// the file's lock. A refusal records nothing. The first start fixes the +// sitting's kind. +export async function recordXSittingStart( + paths: SittingPaths, + opts: { refreshedAt: string | null; kind: XSittingKind; limit: number; jobKind: string; at: number; jobId?: string; channel?: string }, +): Promise<{ verdict: XSittingVerdict; began: string | null }> { + return withJsonFileLock(xSittingFile(paths), async () => { + const loaded = await loadLocked(paths, opts.refreshedAt); + if (!loaded.ok) { + return { + began: opts.refreshedAt, + verdict: { ok: false, why: "unknown", used: opts.limit, left: 0, limit: opts.limit, sentence: xSittingUnreadableSentence(xSittingFile(paths)) }, + }; + } + const file = loaded.file; + const before = xSittingVerdict(stateOf(file), opts.kind, opts.limit); + if (!before.ok) return { verdict: before, began: file.began }; + const start: XSittingStart = { + at: opts.at, + jobKind: opts.jobKind, + kind: opts.kind, + ...(opts.jobId ? { jobId: opts.jobId } : {}), + ...(opts.channel ? { channel: opts.channel } : {}), + }; + const next: SittingFile = { ...file, kind: file.kind ?? opts.kind, starts: [...file.starts, start] }; + await writeSittingFile(paths, next); + const used = next.starts.length; + return { began: file.began, verdict: { ok: true, used, left: Math.max(0, opts.limit - used), limit: opts.limit } }; + }); +} diff --git a/common/jobs/xSittings.test.ts b/common/jobs/xSittings.test.ts @@ -0,0 +1,382 @@ +// X IN SMALL, UNEVEN SITTINGS (lane x-sittings; lib/xSitting.ts, jobs/xSitting.ts): +// the sitting's count over every kind of X job, through the real job funnel +// (runManagedFunction → the network guard), across an "editor restart", and +// reset by nothing but a later cookie refresh; the one-kind rule; the drawn +// gap; the account marked suspended; the 429 cooldown over every X kind. +// Temp dirs only; no job here asks anything of any site (each job's work is a +// stub that only records that it ran). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/xSittings.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-sittings-")); +process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +delete process.env.E2E_JOB_GAP_SECONDS; +delete process.env.E2E_X_SITTINGS; +delete process.env.E2E_X_MAX_COOKIE_AGE_MINUTES; + +async function writeSettings(x: Record<string, unknown> = {}): Promise<void> { + await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ social: { x: { cookieSource: "profile", ...x } } })); +} +await writeSettings(); + +const transcripts = path.join(ROOT, "transcripts"); +async function channel(slug: string, extra: Record<string, unknown> = {}): Promise<void> { + const dir = path.join(transcripts, "channels", slug); + await mkdir(dir, { recursive: true }); + await writeFile( + path.join(dir, "config.json"), + JSON.stringify({ handling: "transcribe", sourceKind: "social", postFetcher: "x-gallery-dl", platform: "twitter", name: slug, socialHandle: slug.replace(/-/g, ""), url: `https://x.com/${slug.replace(/-/g, "")}`, ...extra }), + ); +} +const ACCOUNTS = ["acct-one", "acct-two", "acct-three", "acct-four", "acct-five", "acct-six", "acct-seven"]; +for (const s of ACCOUNTS) await channel(s); +await channel("demo-library", { xTrending: {}, url: undefined, postFetcher: undefined }); +await channel("demo-search", { xSearch: { query: "kettles" } }); + +const SESSION = path.join(transcripts, ".x-session"); +const JAR = path.join(SESSION, "cookies.txt"); +// A jar written `ageMs` ago, as an old jar is: its mtime is its time (no +// broker stamp). `refresh` also writes the broker's stamp, as a Refresh does. +async function writeJar(ageMs: number, opts: { refresh?: boolean } = {}): Promise<string> { + await mkdir(path.join(SESSION, "profile"), { recursive: true }); + await writeFile(JAR, "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tv\n"); + const t = new Date(Date.now() - ageMs); + await utimes(JAR, t, t); + if (opts.refresh) await writeFile(path.join(SESSION, "refreshed.json"), JSON.stringify({ version: 1, at: t.toISOString() })); + return t.toISOString(); +} + +const { getPaths } = await import("../lib/paths"); +const { runManagedFunction } = await import("./streamCommand"); +const { setQueueGapClock, clearQueueGaps, noteQueueJobEnd, queueGapWait, queueGapLine, setXGapRandom, xQueueGapRange } = await import("./queueGap"); +const { xJobStartsFile } = await import("./xJobCap"); +const { xSittingFile } = await import("./xSitting"); +const { xSessionReport, guardNetworkJob } = await import("./networkGuard"); +const { recordPlatformCooldown } = await import("./downloadBackoff"); +const { writeAutoQueueState, readAutoQueueState } = await import("./autoQueueState"); +const { writeXAccountState, xAccountStateFile, keepVerdictsTrustedWhileSuspended } = await import("../social/xAccountState"); +const { readXSessionStatus } = await import("../social/xSessionBroker"); +const { getRegistry } = await import("./registry"); +const { parseXSittingJobs, xSittingJobs, X_SITTING_MAX_JOBS, drawXGapSeconds, xGapRange } = await import("../lib/xSitting"); +const { sanitizeSocial } = await import("../social/xCookieSource"); + +const paths = getPaths(); + +let fakeNow = Date.now(); +setQueueGapClock({ now: () => fakeNow, sleep: async (ms) => { fakeNow += ms; } }); + +async function reset(): Promise<void> { + clearQueueGaps(); + await rm(path.join(paths.jobsDir, "queue-gaps.json"), { force: true }); + await mkdir(path.dirname(xJobStartsFile(paths)), { recursive: true }); + await writeFile(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [] })); + await rm(xSittingFile(paths), { force: true }); + await rm(xAccountStateFile(paths), { force: true }); + await rm(path.join(SESSION, "refreshed.json"), { force: true }); + // No cooldown on record. + const st = await readAutoQueueState(paths); + st.download.platformBackoff = {}; + st.download.platformHolds = {}; + await writeAutoQueueState(paths, st); + await writeSettings(); +} + +// One X job through the funnel, its work a stub. Answers how it ended. +async function xJob(kind: string, slug: string | undefined, params?: Record<string, unknown>): Promise<{ queued: boolean; error?: string; status?: string; deferred?: { until: number; sentence: string }; ran: boolean; log?: string }> { + let ran = false; + const res = await runManagedFunction({ + kind, + queueKey: "platform:twitter", + paths, + ...(slug ? { channelSlug: slug } : {}), + ...(params ? { spec: { kind, slug: slug ?? "x", params } } : {}), + fn: async () => { + ran = true; + fakeNow += 2_000; + }, + } as Parameters<typeof runManagedFunction>[0]); + if (!res.ok) return { queued: false, error: res.error, ran }; + const status = (await res.done).status; + const rec = getRegistry().get(res.jobId); + const log = await readFile(path.join(paths.jobsDir, `${res.jobId}.log`), "utf8").catch(() => ""); + return { queued: true, status, ran, log, ...(rec?.deferred ? { deferred: rec.deferred } : {}) }; +} + +test("N: a sitting admits 4 X job starts by default; the setting is bounded 1-6 in the code", () => { + assert.equal(xSittingJobs(undefined), 4); + assert.equal(xSittingJobs({ sittingJobs: 2 }), 2); + assert.equal(xSittingJobs({ sittingJobs: 60 }), X_SITTING_MAX_JOBS); + assert.equal(xSittingJobs({ sittingJobs: 0 }), 1); + assert.equal(parseXSittingJobs("4"), undefined); + assert.equal(parseXSittingJobs(9.7), 6); + assert.deepEqual(sanitizeSocial({ x: { sittingJobs: 99, gapMinMinutes: 1, gapMaxMinutes: 600 } }).x, { sittingJobs: 6, gapMinMinutes: 5, gapMaxMinutes: 120 }); + assert.deepEqual(sanitizeSocial({ x: { sittingJobs: "lots" } }).x, {}); +}); + +test("the 5th X start after a refresh is refused — over every kind of timelines job together — and ends deferred, not failed", async () => { + await reset(); + await writeJar(2 * 60_000, { refresh: true }); + const ends = [ + await xJob("fetch-posts", ACCOUNTS[0]), + await xJob("capture-posts", ACCOUNTS[1], { ids: ["1"], shots: true }), + await xJob("check-post-availability", ACCOUNTS[2]), + await xJob("import-post", ACCOUNTS[3]), + ]; + for (const e of ends) { + assert.equal(e.queued, true, e.error); + assert.equal(e.status, "done"); + assert.equal(e.ran, true); + } + // Each job's log says where the sitting stands. + assert.match(ends[0].log ?? "", /X sitting: 1 of 4 started \(timelines, since the refresh at \d\d:\d\d UTC\); 3 left\./); + assert.match(ends[3].log ?? "", /X sitting: 4 of 4 started .*; 0 left\./); + // The 5th: refused at enqueue (no job), with the sentence. + const fifth = await xJob("fetch-posts", ACCOUNTS[4]); + assert.equal(fifth.queued, false); + assert.equal(fifth.ran, false); + assert.match(fifth.error ?? "", /^This X sitting is used up: 4 of 4 X jobs started since the cookies were refreshed at \d\d:\d\d UTC \(social\.x\.sittingJobs, at most 6\)\. A new Refresh cookies on \/cookies starts the next sitting; nothing queues or retries by itself\.$/); + // get x-session shows it: used, left, kind, when it began. + const report = await xSessionReport({ paths }); + assert.equal(report.allowed, false); + assert.equal(report.refusedBy, "sitting"); + assert.deepEqual({ ...report.sitting, began: typeof report.sitting.began }, { began: "string", kind: "timelines", used: 4, left: 0, limit: 4 }); + // A job queued while there was room, started after it is gone: done, DEFERRED (until a Refresh), never run. + await writeFile(xSittingFile(paths), JSON.stringify({ ...JSON.parse(await readFile(xSittingFile(paths), "utf8")), starts: JSON.parse(await readFile(xSittingFile(paths), "utf8")).starts.slice(0, 3) })); + let ran = false; + let release!: () => void; + const blocker = new Promise<void>((r) => (release = r)); + // Hold X's queue with one job so the next one queues while the sitting has room. + const hold = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: ACCOUNTS[4], fn: async () => { await blocker; } }); + assert.equal(hold.ok, true); + const late = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: ACCOUNTS[5], fn: async () => { ran = true; } }); + assert.equal(late.ok, true, late.ok ? "" : late.error); + release(); + if (hold.ok) await hold.done; + if (late.ok) { + assert.equal((await late.done).status, "done"); + const rec = getRegistry().get(late.jobId); + assert.equal(rec?.deferred?.until, 0); + assert.match(rec?.deferred?.sentence ?? "", /^This X sitting is used up: 4 of 4/); + } + assert.equal(ran, false); +}); + +test("ONE KIND PER SITTING: the first job fixes it; a job of the other kind is refused until the next refresh", async () => { + await reset(); + await writeJar(60_000, { refresh: true }); + const read = await xJob("read-x-trending", "demo-library"); + assert.equal(read.status, "done", read.error); + // A search channel's walk and a library's capture are browse too. + assert.equal((await xJob("fetch-posts", "demo-search")).status, "done"); + assert.equal((await xJob("capture-posts", "demo-library", { ids: ["9"], shots: true })).status, "done"); + // A timeline fetch: refused, saying why. + const timeline = await xJob("fetch-posts", ACCOUNTS[0]); + assert.equal(timeline.queued, false); + assert.match(timeline.error ?? "", /^This X sitting is a browse sitting \(its first job, read-x-trending at \d\d:\d\d UTC, fixed it\): a timelines job does not start in it/); + assert.equal((await xSessionReport({ paths })).sitting.kind, "browse"); + // A later refresh begins a new sitting, of either kind. + await writeJar(0, { refresh: true }); + const after = await xJob("fetch-posts", ACCOUNTS[0]); + assert.equal(after.status, "done", after.error); + const r = await xSessionReport({ paths }); + assert.deepEqual([r.sitting.kind, r.sitting.used], ["timelines", 1]); +}); + +test("the sitting survives an editor restart and is reset by nothing but a LATER refresh", async () => { + await reset(); + const refreshed = await writeJar(5 * 60_000, { refresh: true }); + for (const s of ACCOUNTS.slice(0, 3)) assert.equal((await xJob("fetch-posts", s)).status, "done"); + // A restart: every in-memory store is gone; the file is not. + clearQueueGaps(); + assert.equal((await xSessionReport({ paths })).sitting.used, 3); + // gallery-dl (or anything) rewriting the jar moves its mtime, not the refresh. + const t = new Date(); + await utimes(JAR, t, t); + assert.equal((await readXSessionStatus(paths)).cookiesUpdatedAt, refreshed); + assert.equal((await xSessionReport({ paths })).sitting.used, 3); + // A jar restored from an older refresh continues the sitting on record. + await writeFile(path.join(SESSION, "refreshed.json"), JSON.stringify({ version: 1, at: new Date(Date.parse(refreshed) - 3600_000).toISOString() })); + assert.equal((await xSessionReport({ paths })).sitting.used, 3); + await writeFile(path.join(SESSION, "refreshed.json"), JSON.stringify({ version: 1, at: refreshed })); + // The sitting file deleted: rebuilt from the records and X's job count, kind and all. + await rm(xSittingFile(paths)); + const rebuilt = await xSessionReport({ paths }); + assert.deepEqual([rebuilt.sitting.used, rebuilt.sitting.kind], [3, "timelines"]); + // Deleted, with the records' kinds gone too: counted from X's job count, kind unknown — both kinds refused. + await rm(xSittingFile(paths)); + for (const id of getRegistry().list().map((r) => r.id)) { + const meta = path.join(paths.jobsDir, `${id}.meta.json`); + const m = JSON.parse(await readFile(meta, "utf8").catch(() => "{}")); + if (m.xSittings) { + delete m.xSittings; + await writeFile(meta, JSON.stringify(m)); + } + } + const unknown = await xSessionReport({ paths, sittingKind: "timelines" }); + assert.equal(unknown.sitting.kind, "unknown"); + assert.equal(unknown.allowed, false); + assert.match(unknown.reason ?? "", /^This X sitting's kind cannot be told/); + // An unreadable file: every counted X job is refused. + await writeFile(xSittingFile(paths), "{ not json"); + const bad = await xJob("fetch-posts", ACCOUNTS[3]); + assert.equal(bad.queued, false); + assert.match(bad.error ?? "", /^X's sitting cannot be read/); + // Only a later refresh begins a new one (stamped on the jobs' clock, which ran ahead of the wall's here). + await writeFile(xSittingFile(paths), JSON.stringify({ version: 1, began: refreshed, kind: "timelines", starts: [] })); + await writeFile(path.join(SESSION, "refreshed.json"), JSON.stringify({ version: 1, at: new Date(fakeNow + 1000).toISOString() })); + const fresh = await xSessionReport({ paths }); + assert.deepEqual([fresh.sitting.used, fresh.sitting.kind], [0, null]); +}); + +test("N is the setting, bounded: sittingJobs 2 refuses the 3rd; 50 admits 6 and refuses the 7th", async () => { + await reset(); + await writeSettings({ sittingJobs: 2 }); + await writeJar(60_000, { refresh: true }); + assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); + assert.equal((await xJob("fetch-posts", ACCOUNTS[1])).status, "done"); + assert.match((await xJob("fetch-posts", ACCOUNTS[2])).error ?? "", /used up: 2 of 2/); + await writeSettings({ sittingJobs: 50 }); + await writeJar(0, { refresh: true }); + // Out of the hourly cap's way: the first part's starts are forgotten. + await writeFile(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [] })); + for (const s of ACCOUNTS.slice(0, 6)) { + const e = await xJob("fetch-posts", s); + assert.equal(e.status, "done", e.error); + fakeNow += 11 * 60_000; // out of the hourly cap's way + } + assert.match((await xJob("fetch-posts", ACCOUNTS[6])).error ?? "", /used up: 6 of 6/); +}); + +test("UNEVEN GAPS: X's gap is drawn per job within 5-12 min, never below 5, logged with its draw; seeded only in a test", async () => { + // The pure draw: the bounds, always. + const range = xGapRange(undefined); + assert.deepEqual(range, { minSeconds: 300, maxSeconds: 720 }); + assert.equal(drawXGapSeconds(range, 0), 300); + assert.equal(drawXGapSeconds(range, 0.999999), 720); + for (let i = 0; i < 200; i++) { + const s = drawXGapSeconds(range, Math.random()); + assert.ok(s >= 300 && s <= 720, String(s)); + } + // The floor holds against any setting; an explicit jobGapSeconds.twitter above it raises the minimum, never lowers it. + assert.deepEqual(xGapRange({ gapMinMinutes: 1, gapMaxMinutes: 2 }), { minSeconds: 300, maxSeconds: 300 }); + assert.deepEqual(xGapRange({ gapMinMinutes: 6, gapMaxMinutes: 9 }), { minSeconds: 360, maxSeconds: 540 }); + assert.deepEqual(xGapRange(undefined, 900), { minSeconds: 900, maxSeconds: 900 }); + assert.deepEqual(xGapRange(undefined, 0), { minSeconds: 300, maxSeconds: 720 }); + assert.deepEqual(xQueueGapRange({ jobGapSeconds: { twitter: 30 } }, undefined), { minSeconds: 300, maxSeconds: 720 }); + + // The wait: drawn once per end, kept across re-reads, seeded draws repeat. + clearQueueGaps(); + setXGapRandom(42); + const end = fakeNow; + await noteQueueJobEnd(paths, "platform:twitter", end); + const w1 = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: end + 1000, xGap: {} }); + const w2 = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: end + 60_000, xGap: {} }); + assert.ok(w1 && w2); + assert.equal(w1!.until, w2!.until, "a re-read keeps the draw"); + assert.ok(w1!.drawn!.seconds >= 300 && w1!.drawn!.seconds <= 720); + assert.match(queueGapLine(w1!), /^waiting \d+m\d\ds \(a \d+m\d\ds gap drawn from 5-12 min\): X jobs are spaced 5-12 min apart, drawn per job/); + clearQueueGaps(); + setXGapRandom(42); + await noteQueueJobEnd(paths, "platform:twitter", end); + const again = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: end + 1000, xGap: {} }); + assert.equal(again!.drawn!.seconds, w1!.drawn!.seconds, "the same seed, the same draw"); + // Different ends draw differently (not one fixed beat): over 30 ends, more than one value. + const draws = new Set<number>(); + for (let i = 0; i < 30; i++) { + await noteQueueJobEnd(paths, "platform:twitter", end + (i + 1) * 3_600_000); + const w = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: end + (i + 1) * 3_600_000 + 1, xGap: {} }); + draws.add(w!.drawn!.seconds); + } + assert.ok(draws.size > 5, `${draws.size} distinct draws`); + setXGapRandom(null); + clearQueueGaps(); + + // Through the funnel: two X jobs, the second starts 5-12 min after the first ended, and its log says the draw. + await reset(); + await writeJar(60_000, { refresh: true }); + const first = await xJob("fetch-posts", ACCOUNTS[0]); + const t1 = fakeNow; + const second = await xJob("fetch-posts", ACCOUNTS[1]); + assert.equal(second.status, "done", second.error); + assert.match(second.log ?? "", /waiting \d+m\d\ds \(a \d+m\d\ds gap drawn from 5-12 min\)/); + const waited = fakeNow - 2_000 - t1; + assert.ok(waited >= 300_000 && waited <= 720_000, `${waited} ms`); + assert.equal(first.status, "done"); +}); + +test("SUSPENDED: marked by hand, it refuses availability checks and captures that record deleted posts; other X jobs log it", async () => { + await reset(); + await writeJar(60_000, { refresh: true }); + await writeXAccountState(paths, "suspended", { note: "read-only since the 21st" }); + const report = await xSessionReport({ paths }); + assert.equal(report.account.state, "suspended"); + assert.match(report.account.alert ?? "", /^The X account is marked suspended \(since .* UTC: read-only since the 21st\)/); + for (const [kind, params] of [ + ["check-post-availability", undefined], + ["capture-posts", { ids: ["1"] }], + ["capture-posts", { ids: ["1"], shots: true }], + ] as const) { + const e = await xJob(kind, ACCOUNTS[0], params); + assert.equal(e.queued, false, kind); + assert.match(e.error ?? "", /^The X account is marked suspended .*is refused, because a suspended account's answers are thinned/, kind); + } + // A capture with its screenshots off records no availability: it runs. + assert.equal((await xJob("capture-posts", ACCOUNTS[0], { ids: ["1"], shots: false })).status, "done"); + // A fetch runs, and its log says the account is suspended. + const fetch = await xJob("fetch-posts", ACCOUNTS[1]); + assert.equal(fetch.status, "done"); + assert.match(fetch.log ?? "", /The X account is marked suspended .* What X answers it may be thinned\./); + // The last line before a verdict is written (a mark made while a job ran): only "available" is kept. + const lines: string[] = []; + const kept = await keepVerdictsTrustedWhileSuspended(paths, new Map([["1", "deleted"], ["2", "available"], ["3", "account_unavailable"]]), (l) => lines.push(l)); + assert.deepEqual([...kept], [["2", "available"]]); + assert.match(lines.join("\n"), /2 "deleted" or "unavailable" verdict\(s\) from its answers were NOT recorded/); + // Marked ok: the check runs again. + await writeXAccountState(paths, "ok"); + assert.equal((await xJob("check-post-availability", ACCOUNTS[2])).status, "done"); + const all = new Map([["1", "deleted"]]); + assert.equal(await keepVerdictsTrustedWhileSuspended(paths, all, () => {}), all); + // An unreadable state file is taken as suspended. + await writeFile(xAccountStateFile(paths), "nope"); + assert.match((await xJob("check-post-availability", ACCOUNTS[3])).error ?? "", /marked suspended/); +}); + +test("A 429 STOPS EVERY X JOB FOR 15 MINUTES: fetch, capture, availability check, import, X run channel, trending read, search walk", async () => { + await reset(); + await writeJar(60_000, { refresh: true }); + await recordPlatformCooldown("twitter", 15 * 60_000, paths); + for (const [kind, slug] of [ + ["fetch-posts", ACCOUNTS[0]], + ["sync", ACCOUNTS[0]], + ["capture-posts", ACCOUNTS[1]], + ["check-post-availability", ACCOUNTS[2]], + ["import-post", ACCOUNTS[3]], + ["read-x-trending", "demo-library"], + ["fetch-posts", "demo-search"], + ] as const) { + const e = await xJob(kind, slug); + assert.equal(e.queued, false, kind); + assert.match(e.error ?? "", /^X answered a rate limit \(429\) a short while ago: no X job starts before \d\d:\d\d UTC \(1[45] min from now\)/, kind); + } + // Each channel of an X run is guarded the same way. + const runGuard = await guardNetworkJob({ kind: "x-run", queueKey: "platform:twitter", paths, channelSlug: ACCOUNTS[4], job: { id: "01JXRUN0000000000000000000" }, countStart: true }); + assert.equal(runGuard.ok, false); + // Nothing was counted against the sitting or the cap. + const r = await xSessionReport({ paths }); + assert.equal(r.sitting.used, 0); + assert.equal(r.cap.lastHour, 0); + assert.equal(r.refusedBy, "cooldown"); + assert.ok(r.cooldown && Date.parse(r.cooldown.until) > Date.now() + 14 * 60_000); + // Once it has passed, X jobs start again. + const st = await readAutoQueueState(paths); + st.download.platformBackoff = {}; + await writeAutoQueueState(paths, st); + assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); +}); diff --git a/common/lib/cookieStatus.ts b/common/lib/cookieStatus.ts @@ -63,7 +63,22 @@ export type CookieRow = { export type CookieRunning = { action: CookieRowButton["action"]; since: string; jobId?: string }; -export type CookieStatusPayload = { readAt: string; rows: CookieRow[] }; +// X'S SITTING AND ACCOUNT (lane x-sittings), for the X row's panel: the +// sitting since the last refresh (jobs/xSitting.ts) and the account's state +// as the operator marked it (social/xAccountState.ts). +export type XSittingView = { + began: string | null; + kind: "timelines" | "browse" | "unknown" | null; + used: number; + left: number; + limit: number; + unreadable?: true; + account: { state: "ok" | "suspended"; since?: string; note?: string; alert?: string }; + // X's 15 minutes after a 429, when it is cooling down. + cooldownUntil?: string; +}; + +export type CookieStatusPayload = { readAt: string; rows: CookieRow[]; xSitting?: XSittingView }; export type Displayers = { path: (p: string) => string; text: (s: string) => string }; diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -258,7 +258,8 @@ const DECLARED: EnvVarDecl[] = [ { name: "E2E_AVAILABILITY_PROBE_GAP_MS", audience: "test", default: "the real gap (3 s, stretched by `pacing.jitter`)", readBy: "common/controller/checkAvailability.ts", doc: "The pause after each per-video availability probe. The editor's e2e server and the availability unit tests set 0: their stub yt-dlp answers at once." }, { name: "E2E_PACING_JITTER", audience: "test", default: "`pacing.jitter` from settings.json (0.25)", readBy: "common/lib/jitter.ts", doc: "Replaces the operator's jitter share (0–1) for every request-pacing wait. The unit tests that assert an exact gap set 0; the jitter itself is tested with its share passed in (lib/jitter.test.ts)." }, { name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts", doc: "The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." }, - { name: "E2E_JOB_GAP_SECONDS", audience: "test", default: "the built-in gaps (20 s; X 300, forums and Bluesky 60)", readBy: "common/jobs/queueGap.ts", doc: "Replaces every BUILT-IN `pacing.jobGapSeconds` gap (plans/pacing-guard.md); a gap set in settings.json still applies. The editor's e2e server sets 0, so two fake fetches on one platform queue do not wait; pacing.spec sets its own." }, + { name: "E2E_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_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_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." }, diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -217,6 +217,24 @@ export const X_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<XSocialSettings> = { "cannot be read: the job logs that and proceeds. ABSENT: 60. 0 turns the rule off; at most " + "10080 (a week). Set in the X account session section of /settings. " + "common/jobs/networkGuard.ts.", + sittingJobs: + "X IN SITTINGS: a sitting begins at a cookie refresh (Refresh cookies or Connect X account on /cookies) and " + + "admits at most this many X job starts — every kind that asks X, counted as X's job cap counts them (each " + + "channel of an X run is one). A start beyond it is refused (at enqueue, or `done`, deferred, at its start: " + + "never a failure that retries): a new Refresh starts the next sitting. A sitting is also ONE KIND, fixed by its " + + "first job: `timelines` (account post fetches, captures, availability checks, one post's import) or `browse` " + + "(trending reads, X search channels' walks, a trending library's captures); a job of the other kind waits for " + + "the next Refresh. The sitting is kept in `.x-session/sitting.json` (rebuilt from the job records if it is " + + "lost) and shown by `pnpm ops get x-session` and on /cookies. ABSENT: 4. Bounded 1-6 in the code " + + "(common/lib/xSitting.ts): no value raises it past 6. common/jobs/xSitting.ts.", + gapMinMinutes: + "THE SHORTEST GAP BEFORE AN X JOB, in minutes: X's queue gap is drawn per job, uniform between this and " + + "`gapMaxMinutes`, after the previous X job ended, and logged (\"waiting 8m41s (a 9m02s gap drawn from 5-12 " + + "min)\"). Never below 5 (the floor is in the code); an explicit `pacing.jobGapSeconds.twitter` above it raises " + + "it. ABSENT: 5. At most 120. common/jobs/queueGap.ts.", + gapMaxMinutes: + "THE LONGEST GAP BEFORE AN X JOB, in minutes (see `gapMinMinutes`). Never below the minimum. ABSENT: 12. At " + + "most 120.", }; export type { AutoQueueSettings } from "./autoQueueTypes"; export type { ChannelPriority } from "./channelPriority"; @@ -1986,7 +2004,7 @@ export const siteSettingsSchema = z.object({ "How yt-dlp invocations use the configured cookies (see common/lib/cookiePolicy.ts): \"always\" passes them on every invocation, \"when-required\" (default; the historical behavior) only to retry an auth/age failure, \"defer\" never in normal runs — auth-gated videos are excluded from batches and collected into the per-channel \"Needs cookies\" bucket for a manual cookie run. Per-channel override available (ChannelConfig.cookieMode).", ), social: settingsField((v): SocialSettings => sanitizeSocial(v)).describe( - "Per-platform settings of the social posts: X's three, all chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`), where X posts may appear (`social.x.visibility`) and how fresh its cookies must be for an X job to start (`social.x.maxCookieAgeMinutes`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts.", + "Per-platform settings of the social posts: X's, all chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`), where X posts may appear (`social.x.visibility`), how fresh its cookies must be for an X job to start (`social.x.maxCookieAgeMinutes`), how many X jobs one cookie refresh admits (`social.x.sittingJobs`) and the range X's gap is drawn from (`social.x.gapMinMinutes`, `social.x.gapMaxMinutes`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts.", ), sleepBetweenDownloadsSeconds: settingsField((v): number => clampSleepBetweenDownloadsSeconds(v)).describe( "Pause (seconds) inserted between per-video yt-dlp invocations in managed batch downloads, and between two auto-download units on one platform (release 17; the lane ignored it before). yt-dlp's own `-t sleep` only paces requests within one invocation, so without this the managed loop hammers the source IP back-to-back. The adaptive pace above its base (see `pacing`) is added to it. 0 disables. Per-channel override available for batch downloads.", diff --git a/common/lib/xJobRule.test.ts b/common/lib/xJobRule.test.ts @@ -12,8 +12,8 @@ import { X_JOB_CAP, X_QUEUE_KEY, isXUrl, xJobCapSentence, xJobCapVerdict, xJobAs const T0 = Date.parse("2026-11-18T12:00:00.000Z"); const MIN = 60_000; -test("the numbers: 12 X jobs in any 60 minutes, 150 in any 24 hours, and they are frozen", () => { - assert.deepEqual({ ...X_JOB_CAP }, { perHour: 12, hourMs: 3_600_000, perDay: 150, dayMs: 86_400_000 }); +test("the numbers: 6 X jobs in any 60 minutes, 150 in any 24 hours, and they are frozen", () => { + assert.deepEqual({ ...X_JOB_CAP }, { perHour: 6, hourMs: 3_600_000, perDay: 150, dayMs: 86_400_000 }); assert.ok(Object.isFrozen(X_JOB_CAP)); assert.equal(X_QUEUE_KEY, "platform:twitter"); // Nothing in the rule's two modules reads a setting, an environment variable or an option. @@ -23,44 +23,49 @@ test("the numbers: 12 X jobs in any 60 minutes, 150 in any 24 hours, and they ar } }); -test("the hour window: the 13th start in 60 minutes is refused, and says when the next may start", () => { - const starts = Array.from({ length: 12 }, (_, i) => T0 + i * 5 * MIN); // 12:00 … 12:55 - assert.deepEqual(xJobCapVerdict(starts.slice(0, 11), T0 + 56 * MIN), { ok: true, lastHour: 11, lastDay: 11 }); +test("the hour window: the 7th start in 60 minutes is refused, and says when the next may start", () => { + const starts = Array.from({ length: 6 }, (_, i) => T0 + i * 10 * MIN); // 12:00 … 12:50 + assert.deepEqual(xJobCapVerdict(starts.slice(0, 5), T0 + 56 * MIN), { ok: true, lastHour: 5, lastDay: 5 }); const full = xJobCapVerdict(starts, T0 + 56 * MIN); - assert.deepEqual(full, { ok: false, lastHour: 12, lastDay: 12, nextAt: T0 + 60 * MIN, window: "hour" }); + assert.deepEqual(full, { ok: false, lastHour: 6, lastDay: 6, nextAt: T0 + 60 * MIN, window: "hour" }); assert.equal( xJobCapSentence(full, T0 + 56 * MIN), - "X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes (the cap is 12). The next X job may start at 13:00 UTC (in 4 min); " + + "X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes (the cap is 6). The next X job may start at 13:00 UTC (in 4 min); " + "ask again then — nothing queues or retries by itself. The cap is fixed in the code (common/lib/xJobRule.ts): no setting, option or queue raises it.", ); // Rolling: at 13:00 the 12:00 start has left the window (a start exactly 60 minutes old is out). assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN).ok, true); assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN - 1).ok, false); - // X's own gap (5 minutes) makes exactly 12 an hour: the cap never bites a run at the default gap. - assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN).lastHour, 11); + assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN).lastHour, 5); + // At X's floor gap (5 minutes) six jobs take 25 minutes: the hourly cap bites a run at the floor. + const atFloor = Array.from({ length: 6 }, (_, i) => T0 + i * 5 * MIN); + assert.equal(xJobCapVerdict(atFloor, T0 + 30 * MIN).ok, false); }); test("the day window: the 151st start in 24 hours is refused until the oldest of the last 150 is a day old", () => { - const starts = Array.from({ length: 150 }, (_, i) => T0 + i * 9 * MIN); // one every 9 minutes: 22.5 hours - const now = T0 + 150 * 9 * MIN; + // 150 starts in 20 hours (one every 8 minutes — more than the hourly cap lets through, but the verdict + // judges each window as it is at `now`, and the last hour here is empty). + const starts = Array.from({ length: 150 }, (_, i) => T0 + i * 8 * MIN); + const now = T0 + 1300 * MIN; const full = xJobCapVerdict(starts, now); assert.equal(full.ok, false); assert.equal(full.window, "day"); + assert.equal(full.lastHour, 0); assert.equal(full.lastDay, 150); assert.equal(full.nextAt, T0 + 24 * 60 * MIN); - assert.match(xJobCapSentence(full, now), /150 X jobs started in the last 24 hours \(the cap is 150\)\. The next X job may start at 12:00 UTC \(in 90 min\)/); + assert.match(xJobCapSentence(full, now), /150 X jobs started in the last 24 hours \(the cap is 150\)\. The next X job may start at 12:00 UTC \(in about 2 h\)/); // The day is named when it is not today's. - assert.match(xJobCapSentence(xJobCapVerdict(starts, T0 + 151 * 9 * MIN - 23 * 60 * MIN), T0 + 5 * MIN), /may start at 2026-11-19 12:00 UTC \(in about 24 h\)/); + assert.match(xJobCapSentence(full, T0 + 5 * MIN), /may start at 2026-11-19 12:00 UTC \(in about 24 h\)/); assert.equal(xJobCapVerdict(starts, T0 + 24 * 60 * MIN).ok, true); assert.equal(xJobCapVerdict(starts.slice(1), now).ok, true); }); test("a clock set back never frees a start early", () => { - const starts = Array.from({ length: 12 }, (_, i) => T0 + i * MIN); // 12:00 … 12:11 + const starts = Array.from({ length: 6 }, (_, i) => T0 + i * MIN); // 12:00 … 12:05 // The clock now reads two hours EARLIER than the latest start: every start still counts. const back = xJobCapVerdict(starts, T0 - 120 * MIN); assert.equal(back.ok, false); - assert.equal(back.lastHour, 12); + assert.equal(back.lastHour, 6); assert.equal(back.nextAt, T0 + 60 * MIN); // Only once the clock has passed them again by the window do they leave it. assert.equal(xJobCapVerdict(starts, T0 + 59 * MIN).ok, false); @@ -268,11 +273,11 @@ test("review 4 B: an import of a file by its page is X's by that page's address, }); test("review 3 S4: a start in the future counts in both windows, and never moves the windows off the real starts", () => { - const real = Array.from({ length: 11 }, (_, i) => T0 + i * MIN); + const real = Array.from({ length: 5 }, (_, i) => T0 + i * MIN); const future = T0 + 365 * 24 * 60 * MIN; - const v = xJobCapVerdict([...real, future], T0 + 11 * MIN); - assert.deepEqual([v.ok, v.lastHour, v.lastDay], [false, 12, 12]); - // The next may start when the oldest of the newest twelve has left: the real 12:00 start, at 13:00. + const v = xJobCapVerdict([...real, future], T0 + 5 * MIN); + assert.deepEqual([v.ok, v.lastHour, v.lastDay], [false, 6, 6]); + // The next may start when the oldest of the newest six has left: the real 12:00 start, at 13:00. assert.equal(v.nextAt, T0 + 60 * MIN); // The future start alone keeps counting until the clock has passed it by the window. assert.deepEqual([xJobCapVerdict([future], T0).lastHour, xJobCapVerdict([future], T0).lastDay], [1, 1]); diff --git a/common/lib/xJobRule.ts b/common/lib/xJobRule.ts @@ -36,13 +36,24 @@ import { currentJobContext } from "./jobContext"; export const X_QUEUE_KEY = "platform:twitter"; +// THE HOURLY CAP IS 6 (the operator, 21 Nov 2026: one sitting of 12 timeline +// fetches back to back, at the old cap of 12, preceded the account's +// suspension). At 6 an hour the daily 150 is implied (6 × 24 = 144): it stays +// as a second, independent bound. export const X_JOB_CAP = Object.freeze({ - perHour: 12, + perHour: 6, hourMs: 60 * 60_000, perDay: 150, dayMs: 24 * 60 * 60_000, }); +// HOW LONG X IS LEFT ALONE AFTER IT ANSWERED 429: X's own rate-limit window. +// Written as the `twitter` platform cooldown (jobs/downloadBackoff.ts +// recordPlatformCooldown) by every X reader that meets one — a trending read, +// its media, a capture, a gallery-dl run — and read by the network guard, +// which refuses EVERY X job while it lasts (jobs/networkGuard.ts). +export const X_RATE_LIMIT_HOLD_MS = 15 * 60_000; + // ── 1. the queue ─────────────────────────────────────────────────────────── // Why a job that asks X may not be on `queueKey`, or null. `what` names the diff --git a/common/lib/xSitting.ts b/common/lib/xSitting.ts @@ -0,0 +1,216 @@ +// X IN SITTINGS (lane x-sittings; the operator, 21 Nov 2026: "Implement all +// your suggestions"). The archive's X account was suspended after one sitting +// of a trending read and 12 timeline fetches back to back, each 5-6 minutes +// after the last. So X is now asked in SMALL, UNEVEN SITTINGS: +// +// 1. A SITTING begins at a cookie refresh (the jar's refresh time, +// social/xSessionBroker.ts) and admits at most `social.x.sittingJobs` X +// job starts (default 4, bounded 1-6 HERE, in code). A start beyond it is +// refused: a new Refresh on /cookies starts the next sitting. +// 2. ONE KIND PER SITTING: "timelines" (account post fetches, captures, +// checks) or "browse" (trending reads, search walks). The first job fixes +// it; a job of the other kind is refused until the next Refresh. +// 3. THE GAP BEFORE AN X JOB IS DRAWN per job, uniform in a range (default +// 5-12 min; the floor 5 min is in code), not a fixed beat. +// +// Pure and client-safe: the settings coercion, the guard (jobs/networkGuard.ts), +// the count on disk (jobs/xSitting.ts), the queue gap (jobs/queueGap.ts) and +// /cookies all read it. What counts is X's job cap's rule (lib/xJobRule.ts +// xJobCounts): the same starts, counted at the same moment. + +export type XSittingKind = "timelines" | "browse"; + +export const X_SITTING_DEFAULT_JOBS = 4; +export const X_SITTING_MIN_JOBS = 1; +export const X_SITTING_MAX_JOBS = 6; + +// `social.x.sittingJobs` as stored: a whole number 1-6, else absent. +export function parseXSittingJobs(v: unknown): number | undefined { + if (typeof v !== "number" || !Number.isFinite(v)) return undefined; + return Math.min(X_SITTING_MAX_JOBS, Math.max(X_SITTING_MIN_JOBS, Math.floor(v))); +} + +// The limit in force: the setting, bounded again (a hand-edited file never +// passes 6), else the default. +export function xSittingJobs(x: { sittingJobs?: number } | undefined): number { + return parseXSittingJobs(x?.sittingJobs) ?? X_SITTING_DEFAULT_JOBS; +} + +// ── the kind of an X job ─────────────────────────────────────────────────── + +// The job as it will run: its kind, and what its channel is (read by the +// guard from the channel's config, never from the caller). +export type XSittingPlan = { + kind: string; + channel?: { library?: boolean; search?: boolean }; +}; + +// "browse": reading what X shows — a trending page, a search walk, and the +// capture of what a trending read found (a library's posts). "timelines": +// everything else — an account's posts in any mode, an X run's channel, a +// capture of an account's posts, an availability check, an import of one +// post, an X video window. +export function xSittingKindOf(plan: XSittingPlan): XSittingKind { + if (plan.kind === "read-x-trending") return "browse"; + if (plan.channel?.search === true) return "browse"; + if (plan.channel?.library === true) return "browse"; + return "timelines"; +} + +export const X_SITTING_KIND_TEXT: Readonly<Record<XSittingKind, string>> = Object.freeze({ + timelines: "timelines (account post fetches, captures, checks)", + browse: "browse (trending reads, search walks)", +}); + +// ── the verdict ──────────────────────────────────────────────────────────── + +// The sitting as it stands: when it began (the jar's refresh time; null: no +// refresh on record), its kind (null: no job yet; "unknown": its record was +// lost and its kind cannot be told), the jobs it started, and its first job. +export type XSittingState = { + began: string | null; + kind: XSittingKind | "unknown" | null; + used: number; + first?: { jobKind: string; at: number }; +}; + +export type XSittingVerdict = + | { ok: true; used: number; left: number; limit: number } + | { ok: false; why: "used-up" | "kind" | "unknown"; used: number; left: number; limit: number; sentence: string }; + +const hhmm = (iso: string | number) => new Date(iso).toISOString().slice(11, 16); + +function beganText(began: string | null): string { + return began ? `since the cookies were refreshed at ${hhmm(began)} UTC` : "with no cookie refresh on record"; +} + +const NEXT = "A new Refresh cookies on /cookies starts the next sitting; nothing queues or retries by itself."; + +// May a job of `kind` start in this sitting? +export function xSittingVerdict(state: XSittingState, kind: XSittingKind, limit: number): XSittingVerdict { + const used = state.used; + const left = Math.max(0, limit - used); + const base = { used, left, limit }; + if (used >= limit) { + return { + ok: false, + why: "used-up", + ...base, + sentence: + `This X sitting is used up: ${used} of ${limit} X job${limit === 1 ? "" : "s"} started ${beganText(state.began)} ` + + `(social.x.sittingJobs, at most ${X_SITTING_MAX_JOBS}). ${NEXT}`, + }; + } + if (state.kind === "unknown") { + return { + ok: false, + why: "unknown", + ...base, + sentence: + `This X sitting's kind cannot be told: its record is gone and the ${used} X job${used === 1 ? "" : "s"} it started left none. ` + + `No X job starts in it. ${NEXT}`, + }; + } + if (state.kind !== null && state.kind !== kind) { + const first = state.first ? ` (its first job, ${state.first.jobKind} at ${hhmm(state.first.at)} UTC, fixed it)` : ""; + return { + ok: false, + why: "kind", + ...base, + sentence: + `This X sitting is a ${state.kind} sitting${first}: a ${kind} job does not start in it — ` + + `one sitting is ${X_SITTING_KIND_TEXT.timelines} or ${X_SITTING_KIND_TEXT.browse}, never both. ${NEXT}`, + }; + } + return { ok: true, ...base }; +} + +// Is `next` a LATER refresh than `began`, so a new sitting begins? An equal or +// earlier time (a jar restored from a backup, a clock set back) continues the +// sitting on record: only a real refresh resets it. +export function isLaterRefresh(next: string | null | undefined, began: string | null): boolean { + if (!next) return false; + const n = Date.parse(next); + if (!Number.isFinite(n)) return false; + if (began === null) return true; + const b = Date.parse(began); + return !Number.isFinite(b) || n > b; +} + +// ── the gap before an X job ──────────────────────────────────────────────── + +// The floor of X's gap: never below the fixed five minutes it replaced. +export const X_GAP_FLOOR_MINUTES = 5; +export const X_GAP_DEFAULT_MIN_MINUTES = 5; +export const X_GAP_DEFAULT_MAX_MINUTES = 12; +export const X_GAP_CEILING_MINUTES = 120; + +// `social.x.gapMinMinutes` / `gapMaxMinutes` as stored: whole minutes from +// the floor to the ceiling, else absent. +export function parseXGapMinutes(v: unknown): number | undefined { + if (typeof v !== "number" || !Number.isFinite(v)) return undefined; + return Math.min(X_GAP_CEILING_MINUTES, Math.max(X_GAP_FLOOR_MINUTES, Math.floor(v))); +} + +export type XGapRange = { minSeconds: number; maxSeconds: number }; + +// The range in force, in seconds. The minimum is the setting (else 5 min), +// never below the floor, and raised — never lowered — by an explicit +// `pacing.jobGapSeconds.twitter` above it; the maximum is the setting (else +// 12 min), never below the minimum. +export function xGapRange( + x: { gapMinMinutes?: number; gapMaxMinutes?: number } | undefined, + explicitTwitterSeconds?: number, +): XGapRange { + const minMinutes = parseXGapMinutes(x?.gapMinMinutes) ?? X_GAP_DEFAULT_MIN_MINUTES; + let minSeconds = minMinutes * 60; + if (typeof explicitTwitterSeconds === "number" && Number.isFinite(explicitTwitterSeconds) && explicitTwitterSeconds > minSeconds) { + minSeconds = Math.floor(explicitTwitterSeconds); + } + const maxMinutes = parseXGapMinutes(x?.gapMaxMinutes) ?? X_GAP_DEFAULT_MAX_MINUTES; + const maxSeconds = Math.max(minSeconds, maxMinutes * 60); + return { minSeconds, maxSeconds }; +} + +// One draw from the range, uniform: `rand` in [0, 1). +export function drawXGapSeconds(range: XGapRange, rand: number): number { + const r = Number.isFinite(rand) ? Math.min(Math.max(rand, 0), 1) : 0; + const s = range.minSeconds + Math.floor(r * (range.maxSeconds - range.minSeconds + 1)); + return Math.min(range.maxSeconds, Math.max(range.minSeconds, s)); +} + +// "5-12 min" (whole minutes), else "300-720 s". +export function xGapRangeText(range: XGapRange): string { + const whole = range.minSeconds % 60 === 0 && range.maxSeconds % 60 === 0; + return whole ? `${range.minSeconds / 60}-${range.maxSeconds / 60} min` : `${range.minSeconds}-${range.maxSeconds} s`; +} + +// ── the account's state (suspension) ────────────────────────────────────── + +// The operator's word on the account X answers as: "suspended" (read-only: +// its answers are thinned, so a post it cannot see is NOT a deleted post) or +// "ok". Marked by hand (`pnpm ops x-session`, /cookies). +export type XAccountState = "ok" | "suspended"; + +export function isXAccountState(v: unknown): v is XAccountState { + return v === "ok" || v === "suspended"; +} + +// The kinds a suspended account refuses: they RECORD posts as deleted or +// unavailable from what X answers. A capture with its screenshots off records +// no availability (social/xPostCapture.ts records it with the shot only). +export function xSuspendedRefuses(plan: { kind: string; params?: Readonly<Record<string, unknown>> }): boolean { + if (plan.kind === "check-post-availability") 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; +} + +export function xSuspendedSentence(what: string, since: string, note?: string): string { + return ( + `The X account is marked suspended (since ${since.slice(0, 16).replace("T", " ")} UTC${note ? `: ${note}` : ""}): ` + + `${what} is refused, because a suspended account's answers are thinned and a post it cannot see would be recorded ` + + `deleted or unavailable when it is not. Mark it ok (pnpm ops x-session --json '{"accountState":"ok"}', or /cookies) once it is restored.` + ); +} diff --git a/common/social/xAccountState.ts b/common/social/xAccountState.ts @@ -0,0 +1,107 @@ +// THE X ACCOUNT'S STATE, AS THE OPERATOR MARKED IT (lane x-sittings): whether +// the account X answers as is suspended (read-only). `<transcripts>/.x-session/account.json`: +// { "version": 1, "state": "suspended" | "ok", "note"?: "…", "at": <iso>, "by": "operator" } +// +// Marked BY HAND only (`pnpm ops x-session --json '{"accountState":…}'`, the +// control on /cookies). The fetchers were searched for an explicit signal of +// OUR account's suspension in X's own answers and carry none (gallery-dl's +// "account suspended" is about the account being read, not ours — +// social/xGalleryDlSignals.ts), so nothing here guesses one. +// +// While it is "suspended" the network guard refuses the X jobs that record +// posts as deleted or unavailable (lib/xSitting.ts xSuspendedRefuses), and +// every other X job's log says the account is suspended. +// +// A file that cannot be read is taken as SUSPENDED (fail closed: the jobs it +// refuses are the ones that could write a false "deleted"). +// +// SERVER-ONLY (node:fs). + +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; +import { isXAccountState, type XAccountState } from "../lib/xSitting"; + +export function xAccountStateFile(paths: Pick<Paths, "transcriptsDir">): string { + return path.join(paths.transcriptsDir, ".x-session", "account.json"); +} + +export type XAccountRecord = { + state: XAccountState; + note?: string; + at: string; + by: "operator"; + // The file is there and could not be read: taken as suspended. + unreadable?: true; +}; + +export const X_ACCOUNT_NOTE_MAX = 300; + +// The state on record; absent means "ok" (nothing marked). +export async function readXAccountState(paths: Pick<Paths, "transcriptsDir">): Promise<XAccountRecord | null> { + const read = await readJsonFile(xAccountStateFile(paths)); + if (!read.ok) { + if (read.reason === "absent") return null; + return { state: "suspended", at: new Date(0).toISOString(), by: "operator", unreadable: true, note: "account.json cannot be read" }; + } + const v = read.value as Record<string, unknown> | null; + if (!v || typeof v !== "object" || !isXAccountState(v.state) || typeof v.at !== "string") { + return { state: "suspended", at: new Date(0).toISOString(), by: "operator", unreadable: true, note: "account.json cannot be read" }; + } + return { + state: v.state, + at: v.at, + by: "operator", + ...(typeof v.note === "string" && v.note.trim() ? { note: v.note.trim().slice(0, X_ACCOUNT_NOTE_MAX) } : {}), + }; +} + +// The operator marks the account. Answers what is now on record. +export async function writeXAccountState( + paths: Pick<Paths, "transcriptsDir">, + state: XAccountState, + opts: { note?: string; now?: number } = {}, +): Promise<XAccountRecord> { + const note = opts.note?.trim().slice(0, X_ACCOUNT_NOTE_MAX); + const record: XAccountRecord = { + state, + at: new Date(opts.now ?? Date.now()).toISOString(), + by: "operator", + ...(note ? { note } : {}), + }; + await writeJsonAtomic(xAccountStateFile(paths), { version: 1, ...record }, { mkdir: true }); + return record; +} + +// The alert line /cookies and `get x-session` show while it is suspended. +export function xAccountAlertLine(r: XAccountRecord): string { + if (r.unreadable) return "The X account's state cannot be read (.x-session/account.json): taken as suspended until it is marked again."; + return `The X account is marked suspended (since ${r.at.slice(0, 16).replace("T", " ")} UTC${r.note ? `: ${r.note}` : ""}). Availability checks and captures that record deleted posts are refused.`; +} + +// THE LAST LINE BEFORE A VERDICT IS WRITTEN (an X capture, an X availability +// check): while the account is marked suspended — marked during the run, the +// guard having let the job start — no post is recorded deleted or +// unavailable from what it answered. Only "available" is kept. Answers the +// observations to write (the same map when nothing is dropped). +export async function keepVerdictsTrustedWhileSuspended<V extends string>( + paths: Pick<Paths, "transcriptsDir">, + observations: Map<string, V>, + log: (line: string) => void, +): Promise<Map<string, V>> { + const acct = await readXAccountState(paths).catch(() => null); + if (acct?.state !== "suspended") return observations; + const kept = new Map<string, V>(); + let dropped = 0; + for (const [id, v] of observations) { + if (v === "available") kept.set(id, v); + else dropped++; + } + if (dropped > 0) { + log( + `The X account is marked suspended: ${dropped} "deleted" or "unavailable" verdict(s) from its answers were NOT recorded ` + + "(a suspended account's answers are thinned).", + ); + } + return kept; +} diff --git a/common/social/xCookieSource.ts b/common/social/xCookieSource.ts @@ -20,6 +20,7 @@ // controller and the editor's Settings section all read it. import { parseRetryOnBlock, type RetryOnBlock } from "../lib/forumWalk"; +import { parseXGapMinutes, parseXSittingJobs } from "../lib/xSitting"; export type XCookieSource = "browser" | "profile"; @@ -56,6 +57,12 @@ export type XSocialSettings = { // many minutes and carries a login. 0 turns the rule off. Absent = // X_DEFAULT_MAX_COOKIE_AGE_MINUTES. common/jobs/networkGuard.ts. maxCookieAgeMinutes?: number; + // X IN SITTINGS (lib/xSitting.ts): the X job starts one cookie refresh + // admits (1-6; absent = 4), and the range X's queue gap is drawn from + // (minutes, never below 5; absent = 5 and 12). + sittingJobs?: number; + gapMinMinutes?: number; + gapMaxMinutes?: number; }; // Absent `social.x.maxCookieAgeMinutes`: an hour. A refresh is a human click @@ -127,11 +134,17 @@ export function sanitizeSocial(value: unknown): SocialSettings { }; const retryOnBlock = parseRetryOnBlock(xf.retryOnBlock); const maxCookieAgeMinutes = parseXMaxCookieAgeMinutes(x.maxCookieAgeMinutes); + const sittingJobs = parseXSittingJobs(x.sittingJobs); + const gapMinMinutes = parseXGapMinutes(x.gapMinMinutes); + const gapMaxMinutes = parseXGapMinutes(x.gapMaxMinutes); return { x: { ...(isXCookieSource(x.cookieSource) ? { cookieSource: x.cookieSource } : {}), ...(isXPostsVisibility(x.visibility) ? { visibility: x.visibility } : {}), ...(maxCookieAgeMinutes !== undefined ? { maxCookieAgeMinutes } : {}), + ...(sittingJobs !== undefined ? { sittingJobs } : {}), + ...(gapMinMinutes !== undefined ? { gapMinMinutes } : {}), + ...(gapMaxMinutes !== undefined ? { gapMaxMinutes } : {}), }, ...(retryOnBlock ? { xenforo: { retryOnBlock } } : {}), ...(Object.keys(instagram).length > 0 ? { instagram } : {}), diff --git a/common/social/xGalleryDlFetcher.test.ts b/common/social/xGalleryDlFetcher.test.ts @@ -617,3 +617,14 @@ test("stream: after a search-phase place `3_<N>/`, a first-page post above N mea assert.equal(after([299, 350]), true); assert.equal(after([...Array.from({ length: TOP_RESTART_WINDOW }, (_, i) => 300 - i), 301]), false); }); + +// LANE X-SITTINGS: gallery-dl reads a cookie FILE and never writes it back +// (its `cookies-update` is on by default and rewrote the broker's jar after +// every run — the jar's mtime then said "refreshed" after every fetch). +import { galleryDlLoginArgs } from "./xGalleryDlFetcher"; +test("a cookie file is passed with cookies-update off; a browser's store is passed as it was", () => { + assert.deepEqual(galleryDlLoginArgs({ cookieFile: "/c/.x-session/cookies.txt" }), ["--cookies", "/c/.x-session/cookies.txt", "-o", "cookies-update=false"]); + assert.deepEqual(galleryDlLoginArgs({ cookies: "file:/c/other.txt" }), ["--cookies", "/c/other.txt", "-o", "cookies-update=false"]); + assert.deepEqual(galleryDlLoginArgs({ cookies: "firefox" }), ["--cookies-from-browser", "firefox"]); + assert.deepEqual(galleryDlLoginArgs({}), []); +}); diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts @@ -31,6 +31,8 @@ import type { Readable } from "node:stream"; import { execa } from "execa"; import { getPaths } from "../lib/paths"; import { noteXServiceOutcome } from "../lib/serviceCookies-server"; +import { recordPlatformCooldown } from "../jobs/downloadBackoff"; +import { X_RATE_LIMIT_HOLD_MS } from "../lib/xJobRule"; import { looksLikeXAuthFailure, xBlockKind, xBlockLine } from "./xGalleryDlSignals"; import { cookieArgs } from "../lib/cookiePolicy"; import type { Post, PostRef } from "../lib/posts"; @@ -251,11 +253,17 @@ function galleryDlPacingArgs(): string[] { // session, though — gallery-dl will block for minutes on "Waiting for N // minutes (rate limit)" — so credentials remain the path for a deep backfill. // When none are configured we simply run as a guest rather than failing. -function galleryDlLoginArgs(opts: GalleryDlLoginAndCap): string[] { - if (opts.cookieFile) return ["--cookies", opts.cookieFile]; +// +// A COOKIE FILE IS READ, NEVER WRITTEN BACK (lane x-sittings): gallery-dl's +// `cookies-update` is on by default and rewrites a `--cookies` file with the +// session's cookies after every run (gallery-dl 1.32.9 Extractor.cookies_store). +// On the broker's jar that rewrite made every fetch look like a refresh (the +// jar's mtime), so it is passed off. +export function galleryDlLoginArgs(opts: Pick<GalleryDlLoginAndCap, "cookieFile" | "cookies">): string[] { // Same browser-cookie spec yt-dlp uses (cookiePolicy.ts), same syntax — // `file:<path>` included, which is `--cookies <path>`. - return cookieArgs(opts.cookies); + const args = opts.cookieFile ? ["--cookies", opts.cookieFile] : cookieArgs(opts.cookies); + return args.includes("--cookies") ? [...args, "-o", "cookies-update=false"] : args; } // The random gap a post capture waits before each contact with X after its @@ -1055,6 +1063,19 @@ async function galleryDlLoginFor( return { cookies: choice.cookies, cookieFile: choice.cookieFile }; } +// X ANSWERED THIS RUN 429 (gallery-dl waited it out between pages): X is left +// alone for 15 minutes after it — the cooldown the network guard refuses +// every X job with (lane x-sittings, rule 6). Best effort: a failed write is +// logged, never thrown. +async function noteXRateLimit(onLog?: (line: string) => void): Promise<void> { + try { + const until = await recordPlatformCooldown("twitter", X_RATE_LIMIT_HOLD_MS, getPaths()); + onLog?.(`X is left alone until ${new Date(until).toISOString().slice(11, 16)} UTC (15 minutes after its rate limit): no X job starts before then.`); + } catch (err) { + onLog?.(`X's rate-limit cooldown could not be recorded: ${(err as Error).message}`); + } +} + // Feed a pipe to `onLine` a line at a time; resolves once it has closed. function readLines( input: Readable | null | undefined, @@ -1315,6 +1336,7 @@ async function walkSearchWindows( }; if (stream.rateLimited) { onLog?.("[rate-limit] X throttled this search — gallery-dl paused between pages."); + await noteXRateLimit(onLog); } onLog?.( `${windowStart.since} – ${windowStart.until}: read ${stream.distinct} post(s), ${stream.newPosts} new` + @@ -1593,6 +1615,7 @@ export const xGalleryDlFetcher: SocialFetcher = { ? "Consider a longer sync interval." : "This is a guest (no-credential) run; guest quota is much smaller."), ); + await noteXRateLimit(onLog); } onLog?.( `gallery-dl read ${stream.distinct} post(s): ${stream.newPosts} new` + diff --git a/common/social/xSessionBroker.test.ts b/common/social/xSessionBroker.test.ts @@ -13,7 +13,7 @@ import path from "node:path"; import type { Paths } from "../lib/paths"; import type { ChromiumLike } from "./playwrightRuntime"; import { writeXBrowserRecord } from "./xBrowser"; -import { refreshXCookies, xCookieFile, xProfileDir } from "./xSessionBroker"; +import { readXSessionStatus, refreshXCookies, xCookieFile, xJarRefreshedFile, xProfileDir } from "./xSessionBroker"; const TMP = mkdtempSync(path.join(os.tmpdir(), "xl-broker-")); after(() => rm(TMP, { recursive: true, force: true })); @@ -155,3 +155,24 @@ test("the bundled build cannot open the profile: the recorded browser reads it", assert.deepEqual(launches, ["bundled", SYSTEM_EXE]); assert.match(await jarText(paths), /auth_token\tVIA-RECORD/); }); + +test("lane x-sittings: a refresh is STAMPED, and the jar's refresh time is the stamp, not the jar's mtime (gallery-dl rewrote the jar after every run)", async () => { + const paths = await corpus({ jar: "logged-in", recorded: true }); + // A jar from before the stamp: its time is its mtime. + const old = new Date(Date.now() - 3 * 3600_000); + const { utimes } = await import("node:fs/promises"); + await utimes(xCookieFile(paths), old, old); + assert.equal((await readXSessionStatus(paths)).cookiesUpdatedAt, old.toISOString()); + // A Refresh writes the stamp beside the jar. + const { chromium } = fakeChromium({ bundled: [cookie("auth_token", "FRESH")] }); + const before = Date.now(); + const status = await refreshXCookies(paths, { chromium }); + const stamp = JSON.parse(await readFile(xJarRefreshedFile(paths), "utf8")); + assert.equal(stamp.version, 1); + assert.ok(Date.parse(stamp.at) >= before - 1000); + assert.equal(status.cookiesUpdatedAt, new Date(Date.parse(stamp.at)).toISOString()); + // Anything else rewriting the jar (gallery-dl's cookies-update, a copy, touch) moves its mtime, not its refresh. + const later = new Date(Date.now() + 3600_000); + await utimes(xCookieFile(paths), later, later); + assert.equal((await readXSessionStatus(paths)).cookiesUpdatedAt, status.cookiesUpdatedAt); +}); diff --git a/common/social/xSessionBroker.ts b/common/social/xSessionBroker.ts @@ -27,7 +27,7 @@ import path from "node:path"; import { readFile, rm, stat } from "node:fs/promises"; import { execa } from "execa"; -import { writeFileAtomic } from "../lib/jsonFile-server"; +import { readJsonFile, writeFileAtomic, writeJsonAtomic } from "../lib/jsonFile-server"; import type { Paths } from "../lib/paths"; import { importPlaywright, @@ -57,12 +57,31 @@ export function xCookieFile(paths: Paths): string { return path.join(paths.transcriptsDir, ".x-session", "cookies.txt"); } +// WHEN THE JAR WAS LAST REFRESHED (lane x-sittings): the broker's own stamp, +// written beside the jar by Connect and Refresh (writeCookieJar, the jar's one +// writer), `{version: 1, at: <iso>}`. Not the jar's mtime: gallery-dl rewrote +// the jar after every run (its `cookies-update`, on by default — now passed +// off, xGalleryDlFetcher.ts), so the mtime said "refreshed" after every fetch, +// the fresh-jar rule never bit inside a chain of fetches, and a sitting keyed +// to it would never end (jobs/xSitting.ts). +export function xJarRefreshedFile(paths: Paths): string { + return path.join(paths.transcriptsDir, ".x-session", "refreshed.json"); +} + +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; +} + export type XSessionStatus = { // A profile directory exists on disk. hasProfile: boolean; // A cookie jar has been exported. hasCookies: boolean; - // When the cookie jar was last written. + // When the cookie jar was last REFRESHED (Connect / Refresh): the broker's + // stamp (xJarRefreshedFile); for a jar written before the stamp existed, + // the jar's mtime. cookiesUpdatedAt?: string; // True when the exported jar carries the session cookie X actually // authenticates with. A jar without it is present-but-useless. @@ -83,7 +102,7 @@ export async function readXSessionStatus(paths: Paths): Promise<XSessionStatus> try { const st = await stat(cookieFile); hasCookies = true; - cookiesUpdatedAt = new Date(st.mtimeMs).toISOString(); + cookiesUpdatedAt = (await readRefreshedAt(paths)) ?? new Date(st.mtimeMs).toISOString(); const text = await readFile(cookieFile, "utf8"); looksAuthenticated = text.includes(AUTH_COOKIE); } catch { @@ -378,6 +397,8 @@ async function writeCookieJar( mkdir: true, mode: 0o600, }); + // The refresh, stamped: what the fresh-jar rule and X's sitting read. + await writeJsonAtomic(xJarRefreshedFile(paths), { version: 1, at: new Date().toISOString() }, { mkdir: true }); const authed = cookies.some((c) => c.name === AUTH_COOKIE); log( `Exported ${cookies.length} X cookie(s) to ${file}` + diff --git a/editor/app/api/ops/x-session/route.ts b/editor/app/api/ops/x-session/route.ts @@ -1,15 +1,18 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels"; import { xSessionReport } from "yt-dlp-transcript-common/jobs/networkGuard"; +import { NextResponse } from "next/server"; +import { writeXAccountState } from "yt-dlp-transcript-common/social/xAccountState"; import { readRoute } from "../_read"; -import { opsFail } from "../_lib"; +import { oneOf, ops, opsFail, optString } from "../_lib"; export const dynamic = "force-dynamic"; // GET /api/ops/x-session[?slug=<channel>] // -> { ok, source, sourceChosen, browserSpec?, profileDir, cookieFile, // hasProfile, hasCookies, looksAuthenticated, cookiesUpdatedAt, -// ageMinutes, maxAgeMinutes, ageChecked, alert, allowed, reason, note? } +// ageMinutes, maxAgeMinutes, ageChecked, alert, cap, sitting, account, +// cooldown, allowed, reason, refusedBy?, note? } // // The X login an X job would use and whether one would start NOW: the // fresh-jar rule's inputs (the source, the exported jar's age, the limit @@ -25,3 +28,19 @@ export async function GET(request: Request) { return { ...(await xSessionReport({ paths: getPaths(), channelSlug: slug })) }; }); } + +// POST /api/ops/x-session {"accountState": "suspended" | "ok", "note"?} +// -> { ok, account: {state, note?, at, by} } +// +// The operator's word on the X account (social/xAccountState.ts): while it is +// "suspended" the network guard refuses the X jobs that record posts as +// deleted or unavailable, and every other X job logs it. Nothing is asked of +// X; nothing else is written. /cookies has the same control. +export async function POST(request: Request) { + return ops(request, ["accountState", "note"], async (body) => { + const state = oneOf(body, "accountState", ["suspended", "ok"] as const); + const note = optString(body, "note"); + const account = await writeXAccountState(getPaths(), state, note ? { note } : {}); + return NextResponse.json({ ok: true, account }); + }); +} diff --git a/editor/app/cookies/CookiesBoard.tsx b/editor/app/cookies/CookiesBoard.tsx @@ -13,9 +13,10 @@ import { ageSentence, type CookieRow, type CookieStatusPayload, + type XSittingView, } from "yt-dlp-transcript-common/lib/cookieStatus"; import { usePolledPayload } from "../lib/usePolledPayload"; -import { cookieControlsAction, pressCookieButtonAction } from "./actions"; +import { cookieControlsAction, pressCookieButtonAction, setXAccountStateAction } from "./actions"; import { sectionFailed, type CookieControls } from "../lib/cookieControlsTypes"; import { XSessionSection } from "../settings/components/XSessionSection"; import { ArchiveSourcesSection } from "../settings/components/ArchiveSessionSection"; @@ -175,6 +176,89 @@ function Row({ ); } + +// X'S SITTING AND ACCOUNT (lane x-sittings): how many X job starts the last +// Refresh admitted and has left, its kind, when it began; X's cooldown after +// a 429; and the account's state with its one control (Mark suspended / Mark +// ok — `pnpm ops x-session` is the same write). +function XSittingPanel({ view, onStatus }: { view: XSittingView; onStatus: (s: CookieStatusPayload) => void }) { + const [note, setNote] = useState(""); + const [pending, setPending] = useState(false); + const [answer, setAnswer] = useState<{ text: string; ok: boolean } | null>(null); + const suspended = view.account.state === "suspended"; + const mark = async () => { + if (pending) return; + setPending(true); + setAnswer(null); + try { + const r = await setXAccountStateAction(suspended ? "ok" : "suspended", suspended ? undefined : note); + onStatus(r.status); + setAnswer({ text: r.message, ok: r.ok }); + if (r.ok) setNote(""); + } catch (e) { + setAnswer({ text: (e as Error).message || "The mark failed.", ok: false }); + } finally { + setPending(false); + } + }; + const began = view.began ? `began ${hms(view.began)}` : "no refresh on record"; + const kind = view.kind === null ? "no job yet" : view.kind; + return ( + <section aria-label="X sitting" className="flex flex-col gap-2 border-t border-border pt-2"> + <p className="text-sm" aria-label="X sitting count"> + {view.unreadable ? ( + <span className="text-destructive">Sitting unreadable: no X job starts until .x-session/sitting.json is repaired.</span> + ) : ( + <> + Sitting: {view.used} of {view.limit} used, {view.left} left + <span className="text-muted-foreground"> · {kind} · {began}</span> + </> + )} + </p> + {view.left === 0 && !view.unreadable && ( + <p className="text-xs text-muted-foreground">Used up: Refresh starts the next sitting.</p> + )} + {view.cooldownUntil && ( + <p className="text-xs text-destructive" aria-label="X cooldown"> + X answered a rate limit: no X job starts before {hms(view.cooldownUntil)}. + </p> + )} + {view.account.alert && ( + <p role="alert" aria-label="X account alert" className="text-xs text-destructive break-words"> + {view.account.alert} + </p> + )} + <div className="flex flex-col gap-2 sm:flex-row sm:items-center"> + {!suspended && ( + <input + type="text" + value={note} + onChange={(e) => setNote(e.target.value)} + placeholder="Note (optional)" + aria-label="X account note" + maxLength={300} + className="w-full rounded-md border border-border bg-background px-2 py-1.5 text-sm sm:w-64" + /> + )} + <button + type="button" + onClick={mark} + disabled={pending} + aria-label={suspended ? "Mark X account ok" : "Mark X account suspended"} + className="w-full rounded-md border border-border px-3 py-2 text-sm hover:bg-muted disabled:opacity-50 sm:w-auto sm:py-1.5" + > + {pending ? "Saving…" : suspended ? "Mark ok" : "Mark suspended"} + </button> + </div> + {answer && ( + <p role="status" aria-label="X account mark result" className={`text-xs ${answer.ok ? "text-success" : "text-destructive"}`}> + {answer.text} + </p> + )} + </section> + ); +} + const DISCLOSURE = "border-t border-border pt-2"; const SUMMARY = "cursor-pointer text-sm font-medium"; @@ -296,6 +380,7 @@ export function CookiesBoard({ initial, controls }: { initial: CookieStatusPaylo controls={ctl} gen={gens[row.service] ?? 0} refetch={() => void refetch()} + {...(row.service === "x" && status.xSitting ? { xSitting: status.xSitting, onXStatus: take } : {})} /> ))} </ul> @@ -310,16 +395,21 @@ function ItemsFor({ controls, gen, refetch, + xSitting, + onXStatus, }: { row: CookieRow; take: (s: CookieStatusPayload) => void; controls?: CookieControls; gen: number; refetch: () => void; + xSitting?: XSittingView; + onXStatus?: (s: CookieStatusPayload) => void; }) { return ( <> <Row row={row} onStatus={take}> + {xSitting ? <XSittingPanel view={xSitting} onStatus={onXStatus ?? take} /> : null} {controls ? <Controls row={row} controls={controls} gen={gen} refetch={refetch} /> : null} </Row> {controls && row.service === "odysee" && ( diff --git a/editor/app/cookies/actions.ts b/editor/app/cookies/actions.ts @@ -37,6 +37,7 @@ import { connectForumAt } from "../lib/connectForum"; import { listForumChannels } from "../lib/forumChannels"; import { loadCookieStatus } from "../lib/cookieStatus"; import { loadCookieControls, type CookieControls } from "../lib/cookieControls"; +import { writeXAccountState } from "yt-dlp-transcript-common/social/xAccountState"; export type CookiePressResult = { ok: boolean; @@ -105,3 +106,23 @@ export async function pressCookieButtonAction(service: string, action: string): // An error may carry a path: drawn as the page draws one. return { ...answer, message: displayText(answer.message), status: await loadCookieStatus(getPaths(), { fresh: action === "recheck" }) }; } + +// THE X ACCOUNT'S STATE, MARKED BY HAND (lane x-sittings): "suspended" refuses +// the X jobs that record posts as deleted or unavailable; "ok" lifts that. The +// same write as `pnpm ops x-session --json '{"accountState":…}'`. Nothing is +// asked of X. Answers the screen's rows read again. +export async function setXAccountStateAction(state: string, note?: string): Promise<CookiePressResult> { + const paths = getPaths(); + let answer: Answer; + if (state !== "suspended" && state !== "ok") { + answer = { ok: false, message: `Not an account state: ${String(state)}` }; + } else { + try { + const r = await writeXAccountState(paths, state, typeof note === "string" && note.trim() ? { note } : {}); + answer = { ok: true, message: r.state === "suspended" ? "Marked suspended." : "Marked ok." }; + } catch (e) { + answer = { ok: false, message: (e as Error).message }; + } + } + return { ...answer, message: displayText(answer.message), status: await loadCookieStatus(paths) }; +} diff --git a/editor/app/lib/cookieControls.ts b/editor/app/lib/cookieControls.ts @@ -7,6 +7,7 @@ // cookieMode), and each forum host's session status. Never the whole settings // object, never a corpus walk. The rows themselves are lib/cookieStatus.ts. +import { xPacingOf } from "./xPacing"; import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths"; import { getSettings, type SiteSettings } from "yt-dlp-transcript-common/lib/settings"; import { displayText } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; @@ -61,6 +62,7 @@ export async function loadCookieControls( initialSource: xSourceForDisplay(xCookieSourceView(resolved)), initialVisibility: xPostsVisibility(st), initialMaxCookieAge: xMaxCookieAgeMinutes(st.social.x), + initialPacing: xPacingOf(st.social.x), }; }), ), diff --git a/editor/app/lib/cookieControlsTypes.ts b/editor/app/lib/cookieControlsTypes.ts @@ -20,6 +20,8 @@ export type XControls = { initialSource: XCookieSourceView; initialVisibility: XPostsVisibility; initialMaxCookieAge: number; + // X in sittings (lib/xSitting.ts): jobs per refresh, the gap's range (min). + initialPacing?: { sittingJobs: number; gapMinMinutes: number; gapMaxMinutes: number }; }; export type ArchiveControls = { initial: ArchivesSettings; session: ArchiveSessionStatus }; export type YtdlpControls = { cookiesFromBrowser: string; cookieMode: string }; diff --git a/editor/app/lib/cookieStatus.ts b/editor/app/lib/cookieStatus.ts @@ -37,6 +37,8 @@ import { forumSessionDir, readForumSessionStatus } from "yt-dlp-transcript-commo import { loadCookieAlerts } from "./cookieAlerts"; import { listForumChannels } from "./forumChannels"; import { runningCookieActions } from "./cookieRefreshGuard"; +import { xSessionReport } from "yt-dlp-transcript-common/jobs/networkGuard"; +import type { XSittingView } from "yt-dlp-transcript-common/lib/cookieStatus"; async function safe<T>(fn: () => Promise<T>, fallback: T): Promise<T> { try { @@ -123,7 +125,17 @@ export async function loadCookieStatus( const forumChannels = await safe(() => listForumChannels(paths, { fresh: opts.fresh === true }), []); - return buildCookieStatus({ + // X's sitting and account (lane x-sittings), read from disk: nothing asks X. + const report = await safe(() => xSessionReport({ paths, now }), null); + const xSitting: XSittingView | undefined = report + ? { + ...report.sitting, + account: report.account, + ...(report.cooldown ? { cooldownUntil: report.cooldown.until } : {}), + } + : undefined; + + const payload = buildCookieStatus({ now, alerts, state, @@ -135,4 +147,5 @@ export async function loadCookieStatus( running: runningCookieActions(), display: { path: displayPath, text: displayText }, }); + return xSitting ? { ...payload, xSitting } : payload; } diff --git a/editor/app/lib/xPacing.ts b/editor/app/lib/xPacing.ts @@ -0,0 +1,17 @@ +// 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_DEFAULT_MAX_MINUTES, + X_GAP_DEFAULT_MIN_MINUTES, + parseXGapMinutes, + xSittingJobs, +} from "yt-dlp-transcript-common/lib/xSitting"; + +export function xPacingOf(x: { sittingJobs?: number; gapMinMinutes?: number; gapMaxMinutes?: number } | undefined) { + const gapMinMinutes = parseXGapMinutes(x?.gapMinMinutes) ?? X_GAP_DEFAULT_MIN_MINUTES; + return { + sittingJobs: xSittingJobs(x), + gapMinMinutes, + gapMaxMinutes: Math.max(gapMinMinutes, parseXGapMinutes(x?.gapMaxMinutes) ?? X_GAP_DEFAULT_MAX_MINUTES), + }; +} diff --git a/editor/app/review/components/XRunConsole.tsx b/editor/app/review/components/XRunConsole.tsx @@ -38,10 +38,12 @@ function age(ms: number): string { } // X's queue gap, as the run waits it between two channels. -function gapText(seconds: number): string { - if (seconds <= 0) return "no gap between channels"; - if (seconds < 120) return `${seconds} s between channels`; - return `${Math.round(seconds / 60)} min between channels`; +function gapText(seconds: number, maxSeconds = seconds): string { + if (maxSeconds <= 0) return "no gap between channels"; + if (maxSeconds < 120) return seconds === maxSeconds ? `${seconds} s between channels` : `${seconds}-${maxSeconds} s between channels`; + const lo = Math.round(seconds / 60); + const hi = Math.round(maxSeconds / 60); + return lo === hi ? `${lo} min between channels` : `${lo}-${hi} min between channels, drawn per channel`; } function when(iso: string | null): string { @@ -338,7 +340,7 @@ export function XRunConsole({ initial }: { initial: XRunConsolePayload }) { Start X run ({chosen.length}) </button> <span className="text-xs text-muted-foreground"> - ≤ {view.maxPosts} posts each · {gapText(view.gapSeconds)} + ≤ {view.maxPosts} posts each · {gapText(view.gapSeconds, view.gapMaxSeconds ?? view.gapSeconds)} </span> </div> {note && ( diff --git a/editor/app/settings/components/SettingsForm.tsx b/editor/app/settings/components/SettingsForm.tsx @@ -28,7 +28,7 @@ import { jobGapSecondsFor } from "yt-dlp-transcript-common/lib/jobGap"; // platform's key is set by hand in settings.json. const JOB_GAP_FIELDS = [ { key: "default", label: "Every platform" }, - { key: "twitter", label: "X" }, + { key: "twitter", label: "X (minimum)" }, { key: "xenforo", label: "Forums" }, { key: "bluesky", label: "Bluesky" }, { key: "instagram", label: "Instagram" }, @@ -125,7 +125,9 @@ export function SettingsForm({ initial }: Props) { only this long after the previous one on the same platform ended; its row on /jobs says how long it still waits. Built in: 20 s everywhere, 300 s for X, 60 s for forums and Bluesky. 0 turns a - gap off. + gap off — except X&apos;s: its gap is drawn anew for each job in + 5–12 min (set in the X account session), and a value here above + 300 s only raises its minimum. </span> </fieldset> <Field diff --git a/editor/app/settings/components/XSessionSection.tsx b/editor/app/settings/components/XSessionSection.tsx @@ -20,6 +20,7 @@ import { refreshXCookiesAction, setXCookieSourceAction, setXMaxCookieAgeAction, + setXPacingAction, type XSessionActionResult, } from "../xSessionActions"; import type { XSessionStatus } from "yt-dlp-transcript-common/social/xSessionBroker"; @@ -37,6 +38,7 @@ export function XSessionSection({ initialSource, initialVisibility, initialMaxCookieAge, + initialPacing = { sittingJobs: 4, gapMinMinutes: 5, gapMaxMinutes: 12 }, onChange, cookiesLink = true, }: { @@ -48,12 +50,17 @@ export function XSessionSection({ initialVisibility: XPostsVisibility; // `social.x.maxCookieAgeMinutes`, resolved (absent = 60; 0 = off). initialMaxCookieAge: number; + // X in sittings: jobs per cookie refresh (1-6) and the gap's range (min). + initialPacing?: { sittingJobs: number; gapMinMinutes: number; gapMaxMinutes: number }; // Told after every action here ends (the /cookies screen re-reads its row). onChange?: () => void; // The one-line link to /cookies (left out when drawn ON /cookies). cookiesLink?: boolean; }) { const [maxAge, setMaxAge] = useState(String(initialMaxCookieAge)); + const [sittingJobs, setSittingJobs] = useState(String(initialPacing.sittingJobs)); + const [gapMin, setGapMin] = useState(String(initialPacing.gapMinMinutes)); + const [gapMax, setGapMax] = useState(String(initialPacing.gapMaxMinutes)); const [status, setStatus] = useState<XSessionStatus>(initial); const [source, setSource] = useState<XCookieSourceView>(initialSource); const [login, setLogin] = useState<XLoginStatus | null>(null); @@ -264,8 +271,78 @@ export function XSessionSection({ unless the cookies were refreshed this recently — press Refresh cookies first. The editor never refreshes them itself: a refresh loads x.com. With the browser login the age cannot be read and is not checked. 0 - turns the check off. X jobs are also spaced 5 minutes apart, and none - starts while X&apos;s cookie alert is up on the dashboard. + turns the check off. None starts while X&apos;s cookie alert is up on + the dashboard, or for 15 minutes after X answers a rate limit. + </p> + + <div className="flex flex-wrap items-center gap-2"> + <label htmlFor="x-sitting-jobs" className="text-sm"> + At most + </label> + <input + id="x-sitting-jobs" + aria-label="x jobs per sitting" + type="number" + min={1} + max={6} + value={sittingJobs} + onChange={(e) => setSittingJobs(e.target.value)} + className="w-16 rounded-md border border-border bg-background px-2 py-1 text-sm" + /> + <span className="text-sm">X jobs per cookie refresh, spaced</span> + <input + aria-label="x gap min minutes" + type="number" + min={5} + max={120} + value={gapMin} + onChange={(e) => setGapMin(e.target.value)} + className="w-16 rounded-md border border-border bg-background px-2 py-1 text-sm" + /> + <span className="text-sm">to</span> + <input + aria-label="x gap max minutes" + type="number" + min={5} + max={120} + value={gapMax} + onChange={(e) => setGapMax(e.target.value)} + className="w-16 rounded-md border border-border bg-background px-2 py-1 text-sm" + /> + <span className="text-sm">min apart</span> + <button + type="button" + aria-label="save x sittings" + disabled={checking} + onClick={() => + startChecking(async () => { + setError(null); + setNote(null); + const res = await setXPacingAction({ + sittingJobs: Number(sittingJobs), + gapMinMinutes: Number(gapMin), + gapMaxMinutes: Number(gapMax), + }); + if (res.ok) { + setNote( + `A refresh now admits ${res.pacing.sittingJobs} X job${res.pacing.sittingJobs === 1 ? "" : "s"}, ` + + `${res.pacing.gapMinMinutes}–${res.pacing.gapMaxMinutes} min apart.`, + ); + } else setError(res.error); + onChange?.(); + }) + } + className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50" + > + Save + </button> + </div> + <p className="text-xs text-muted-foreground"> + One refresh, one sitting: its first job makes it timelines (account + fetches, captures, checks) or browse (trending reads, X searches), and + a job of the other kind waits for the next Refresh. The gap is drawn + anew for each job. At most 6 per sitting and 5 min apart, whatever is + set here. </p> <div className="flex flex-wrap gap-2"> diff --git a/editor/app/settings/page.tsx b/editor/app/settings/page.tsx @@ -14,6 +14,7 @@ import { StreamErrorBoundary } from "../components/StreamErrorBoundary"; import { e2eStreamDelay } from "../lib/streamDelay"; import { xSourceForDisplay } from "../lib/xSourceDisplay"; import { XSessionSection } from "./components/XSessionSection"; +import { xPacingOf } from "../lib/xPacing"; import { xMaxCookieAgeMinutes } from "yt-dlp-transcript-common/social/xCookieSource"; import { ArchiveSourcesSection } from "./components/ArchiveSessionSection"; import { readArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession"; @@ -185,6 +186,7 @@ async function XSection({ settings }: { settings: SiteSettings }) { initialSource={xSource} initialVisibility={xPostsVisibility(settings)} initialMaxCookieAge={xMaxCookieAgeMinutes(settings.social.x)} + initialPacing={xPacingOf(settings.social.x)} /> </StreamFilled> ); diff --git a/editor/app/settings/xSessionActions.ts b/editor/app/settings/xSessionActions.ts @@ -17,6 +17,15 @@ import { revalidatePath } from "next/cache"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { + X_GAP_CEILING_MINUTES, + X_GAP_DEFAULT_MAX_MINUTES, + X_GAP_DEFAULT_MIN_MINUTES, + X_GAP_FLOOR_MINUTES, + X_SITTING_DEFAULT_JOBS, + X_SITTING_MAX_JOBS, + X_SITTING_MIN_JOBS, +} from "yt-dlp-transcript-common/lib/xSitting"; +import { clearXSession, connectXAccount, readXSessionStatus, @@ -238,3 +247,37 @@ export async function setXMaxCookieAgeAction(minutes: number): Promise<XMaxCooki revalidatePath("/settings"); return { ok: true, minutes }; } + +// X IN SITTINGS (common/lib/xSitting.ts): the X job starts one cookie refresh +// admits (`social.x.sittingJobs`, 1-6) and the range X's gap is drawn from +// (`gapMinMinutes`-`gapMaxMinutes`, never below 5). A default is written as no +// key. The same keys `pnpm ops settings` writes. +export type XPacingInput = { sittingJobs: number; gapMinMinutes: number; gapMaxMinutes: number }; +export type XPacingResult = { ok: true; pacing: XPacingInput } | { ok: false; error: string }; + +export async function setXPacingAction(input: XPacingInput): Promise<XPacingResult> { + const { sittingJobs, gapMinMinutes, gapMaxMinutes } = input ?? ({} as XPacingInput); + if (!Number.isInteger(sittingJobs) || sittingJobs < X_SITTING_MIN_JOBS || sittingJobs > X_SITTING_MAX_JOBS) { + return { ok: false, error: `Jobs per sitting must be a whole number, ${X_SITTING_MIN_JOBS}–${X_SITTING_MAX_JOBS}.` }; + } + if (!Number.isInteger(gapMinMinutes) || gapMinMinutes < X_GAP_FLOOR_MINUTES || gapMinMinutes > X_GAP_CEILING_MINUTES) { + return { ok: false, error: `The shortest gap must be a whole number of minutes, ${X_GAP_FLOOR_MINUTES}–${X_GAP_CEILING_MINUTES}.` }; + } + if (!Number.isInteger(gapMaxMinutes) || gapMaxMinutes < gapMinMinutes || 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}.` }; + } + try { + await saveSettings( + socialXPatch(({ sittingJobs: _s, gapMinMinutes: _a, gapMaxMinutes: _b, ...rest }) => ({ + ...rest, + ...(sittingJobs !== X_SITTING_DEFAULT_JOBS ? { sittingJobs } : {}), + ...(gapMinMinutes !== X_GAP_DEFAULT_MIN_MINUTES ? { gapMinMinutes } : {}), + ...(gapMaxMinutes !== X_GAP_DEFAULT_MAX_MINUTES ? { gapMaxMinutes } : {}), + })), + ); + } catch (e) { + return { ok: false, error: (e as Error).message }; + } + revalidatePath("/settings"); + return { ok: true, pacing: { sittingJobs, gapMinMinutes, gapMaxMinutes } }; +} diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts @@ -51,6 +51,11 @@ export const E2E_SERVER_ENV: Record<string, string> = { // gets exactly that (pacing.spec, x-session.spec). E2E_JOB_GAP_SECONDS: "0", E2E_X_MAX_COOKIE_AGE_MINUTES: "0", + // X's SITTINGS (common/lib/xSitting.ts) are off on the test server: its fake + // X jobs run many to one corpus with no cookie refresh between them, and of + // both kinds. X's job cap (6 an hour) is NOT off. Honoured only beside + // E2E_TEST_ROUTES=1 (common/jobs/networkGuard.ts e2eSittingsOff). + E2E_X_SITTINGS: "off", E2E_LIVE_CHECK: "skip", WRANGLER_BIN: join(EDITOR_ROOT, "e2e", "fixtures", "bin", "fake-wrangler.mjs"), ARCHILYZER_BRANCH: "main", diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts @@ -41,6 +41,11 @@ import { currentSlot } from "./e2e/testPaths"; // E2E_X_MAX_COOKIE_AGE_MINUTES cookie-age limit are off on the test server // (common/jobs/queueGap.ts, networkGuard.ts); a // value a spec writes into settings.json applies +// (X's drawn gap excepted: E2E_JOB_GAP_SECONDS +// collapses its range) +// E2E_X_SITTINGS off: X's sittings (jobs per cookie refresh, one +// kind each) are off on the test server, beside +// E2E_TEST_ROUTES=1 only (networkGuard.ts) // E2E_BLUESKY_ORIGIN_FILE set per slot (e2e/servers.ts): the file a spec // writes its fake Bluesky's loopback origin into, // which the AppView, bsky.app and the image CDN diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -150,6 +150,8 @@ // pnpm ops get tags eva-collab // pnpm ops get services // pnpm ops get x-session +// pnpm ops x-session --json '{"accountState":"suspended","note":"read-only since the 21st"}' +// pnpm ops x-session --json '{"accountState":"ok"}' // pnpm ops get cookies [fresh] // pnpm ops recheck-service --json '{"service":"rumble"}' // pnpm ops recheck-service --json '{"service":"x"}' @@ -702,6 +704,10 @@ const ACTIONS = [ // stopped re-run once it is OK again ({service}). "recheck-service", "dismiss-service", + // The X account's state as the operator marks it ({accountState: + // "suspended" | "ok", note?}): suspended refuses the X jobs that record + // deleted posts (common/social/xAccountState.ts). `get x-session` reads it. + "x-session", "rerun-service-jobs", "workers", "transcribe-one", @@ -1500,15 +1506,26 @@ export function usage() { " \"browser\": cookiesFromBrowser, whose age cannot be read), hasCookies,", " looksAuthenticated, cookiesUpdatedAt, ageMinutes, maxAgeMinutes", " (social.x.maxCookieAgeMinutes; 0 = off), the X cookie alert if it is up,", - " allowed, and reason (the refusal an X job would get); and X's JOB CAP:", - " cap {lastHour, perHour: 12, lastDay, perDay: 150, reached, nextAt?} -", - " at most 12 X jobs start in any 60 minutes and 150 in any 24 hours ON", + " allowed, reason (the refusal an X job would get) and refusedBy (alert,", + " jar, cap, sitting, cooldown or suspended); X's JOB CAP:", + " cap {lastHour, perHour: 6, lastDay, perDay: 150, reached, nextAt?} -", + " at most 6 X jobs start in any 60 minutes and 150 in any 24 hours ON", " THIS MACHINE: one count over every kind of X job, whatever the login", " source, cookie spec or channel. A job past it is refused when queued,", " with the time the next may start; one that meets it when its queue", " starts it ends done, deferred (not failed). A library's media-only", " capture is not counted. The numbers are constants of the code", " (common/lib/xJobRule.ts): no setting, option or queue raises them.", + " X's SITTING: sitting {began, kind, used, left, limit} - a cookie", + " refresh begins a sitting of at most social.x.sittingJobs X job starts", + " (default 4, 1-6 in the code), of ONE kind fixed by its first job:", + " timelines (account fetches, captures, availability checks, an import)", + " or browse (trending reads, X search walks, a library's captures). A", + " start past it, or of the other kind, is refused (at its start: done,", + " deferred); a new Refresh on /cookies starts the next. account {state,", + " since?, note?, alert?} is the operator's mark (x-session, below);", + " cooldown {until} is X's 15 minutes after a 429, which refuses every X", + " job.", " <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", @@ -1744,6 +1761,13 @@ export function usage() { ' Asked while a recheck or another press for the service runs (a click,', ' the dashboard\'s, the timer\'s): refused, 409 {busy: true}, never queued.', 'dismiss-service clears a service\'s cookie alert by hand: {"service"}.', + 'x-session marks the X account\'s state by hand: {"accountState":', + ' "suspended" | "ok", "note"?}. While it is suspended, check-post-', + " availability and capture-posts with screenshots on X (the jobs that", + " record a post as deleted or unavailable) are refused, because a", + " suspended account's answers are thinned; every other X job logs it.", + " get x-session and /cookies show it as the account's alert. Nothing is", + " asked of X. Answers {account: {state, note?, at, by}}.", 'rerun-service-jobs retries every job a service\'s cookie alert stopped, once', ' it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them.', "", diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -984,6 +984,18 @@ test("get x-session is a GET on its route, with an optional channel", () => { assert.equal(parseArgs(["get", "x-session", "some-x"]).path, "/api/ops/x-session?slug=some-x"); assert.match(usage(), /pnpm ops get x-session \[<slug>\]/); assert.match(usage(), /maxAgeMinutes/); + assert.match(usage(), /perHour: 6/); + assert.match(usage(), /sitting \{began, kind, used, left, limit\}/); +}); + +// LANE X-SITTINGS: the operator marks the X account suspended (or ok) by hand. +test("x-session (no get) is a POST that marks the X account's state", () => { + const p = parseArgs(["x-session", "--json", '{"accountState":"suspended","note":"read-only"}']); + assert.equal(p.method, "POST"); + assert.equal(p.path, "/api/ops/x-session"); + assert.deepEqual(p.body, { accountState: "suspended", note: "read-only" }); + assert.equal(parseArgs(["get", "x-session"]).method, "GET"); + assert.match(usage(), /x-session marks the X account's state by hand/); }); // RELEASE 36 LANE A: the clip finder's chain and one video's chat replay.