Archilyzer · Source

archilyzer

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

commit 44770c65030bc1c930531057255f8e33eb9f3c19
parent 194aadc762a862c5e80675b6b992ce50bed6cf43
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 17:22:52 -0500

x-sittings review 2: x-playwright refused, captures halt on any refusal, capture ceiling, the stop cleared only by the operator

- G1: the Playwright fallback fetcher cannot tell X's refusals: fetchPosts
  refuses a channel on it in every mode (inside the X job, before any walk),
  naming the switch to x-gallery-dl, and its own fetch() refuses too.
- G2: a capture asks xStopped() before every page load in its three loops;
  an avatar's or an article image's 429 and three unrendered pages in a row
  record the X stop and end the capture at once.
- G3: capture-posts takes at most social.x.maxPostsPerJob posts (the rest
  are `owed`); the trending read divides the setting over its tabs.
- G4: clearBackoff never removes a running X stop (a clean answer, Clear
  hold); "Clear the X stop" (/cookies, pnpm ops x-session clearStop) asks
  for confirmation, says what it risks, and is logged.
- G5: recordXStop tells the job before the state write.

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

Diffstat:
MCOMMANDS.md | 4++--
MOPERATING.md | 11+++++++++--
Mcommon/controller/capturePosts.ts | 22+++++++++++++++++++---
Mcommon/controller/fetchPosts.test.ts | 26++++++++++++++++++++++++++
Mcommon/controller/fetchPosts.ts | 6++++++
Mcommon/controller/readXTrending.ts | 19+++++++++++++++++--
Mcommon/jobs/downloadBackoff.ts | 35++++++++++++++++++++++++++++++++---
Mcommon/jobs/platformBackoff.ts | 17+++++++++++++++--
Mcommon/jobs/xSittings.test.ts | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xArticleCapture.test.ts | 12++++++++++++
Mcommon/social/xArticleCapture.ts | 15+++++++++++++--
Mcommon/social/xGalleryDlFetcher.ts | 3+++
Mcommon/social/xPlaywrightFetcher.ts | 21+++++++++++++++++++++
Mcommon/social/xPostCapture.test.ts | 30++++++++++++++++++++++++++++++
Mcommon/social/xPostCapture.ts | 44++++++++++++++++++++++++++++++++++++++++----
Meditor/CHANGELOG.md | 8++++++++
Meditor/app/api/ops/x-session/route.test.ts | 13+++++++++++++
Meditor/app/api/ops/x-session/route.ts | 16+++++++++++++++-
Meditor/app/cookies/CookiesBoard.tsx | 35+++++++++++++++++++++++++++++++----
Meditor/app/cookies/actions.ts | 15+++++++++++++++
Mscripts/archilyzer-ops.mjs | 6++++++
21 files changed, 383 insertions(+), 25 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -198,9 +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"}. 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"}'` | +| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x", "instagram" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /cookies) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The For "instagram" it sends Instagram NO request either and is the operator's word that its check is passed: it clears the alert, and the next Instagram job raises it again if it was not. The timer never asks Instagram. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). Asked while a recheck or another press for the service runs (a click, the dashboard's, the timer's): refused, 409 {busy: true}, never queued. dismiss-service clears a service's cookie alert by hand: {"service"}. x-session marks the X account's state by hand: {"accountState": "suspended" \| "ok", "note"?}. While it is suspended, check-post- availability and capture-posts with screenshots on X (the jobs that record a post as deleted or unavailable) are refused, because a suspended account's answers are thinned; every other X job logs it. get x-session and /cookies show it as the account's alert. Nothing is asked of X. Answers {account: {state, note?, at, by}}. {"clearStop": true, "confirm": true, "note"?} is "Clear the X stop": the one way X's 15-minute stop after a rate limit or a bot check ends early (a clean answer or clear-platform-hold never ends it). Without "confirm" it clears nothing and answers 409 with what it risks; each clear is logged in .jobs/x-stop-cleared.jsonl. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -&gt; {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` | | `dismiss-service` | — | | -| `x-session` | — | `pnpm ops x-session --json '{"accountState":"suspended","note":"read-only since the 21st"}'`<br>`pnpm ops x-session --json '{"accountState":"ok"}'` | +| `x-session` | — | `pnpm ops x-session --json '{"accountState":"suspended","note":"read-only since the 21st"}'`<br>`pnpm ops x-session --json '{"accountState":"ok"}'`<br>`pnpm ops x-session --json '{"clearStop":true,"confirm":true,"note":"checked by hand"}'` | | `rerun-service-jobs` | — | | | `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` | | `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. Only a download waits on the platform's queue: the transcription runs as a transcribe-one job on the video's own queue (transcribe-one:&lt;slug&gt;:&lt;id&gt;), at once when nothing is downloaded, else handed off by the whisper-video once the audio is down. A job; --wait follows it through the hand-off to the end of the transcription. "queueKey" names another queue. A youtube-handling video with no audio whose metadata lists English captions has those fetched instead ({"instead": "captions", "message"}, the job the caption download), one with an English caption track on disk is refused; "asr": true transcribes it anyway (no "file"). "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. "whilePaused": true runs this one transcription during a pause-all on a worker the pause alone switched off; the pause stays on (the video page's "Transcribe now (workers paused)"). A video its record says is live, scheduled or still processing its VOD (live\_status is\_live, is\_upcoming, post\_live) is refused before anything is queued — a download would read the stream at 1x and hold the platform queue: record it with record-live, or wait for the VOD (refresh-metadata re-reads the record once it has ended). With its audio on disk it transcribes. | | diff --git a/OPERATING.md b/OPERATING.md @@ -561,10 +561,17 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait then refuses every X job of any kind until it ends (`X answered a rate limit (429) a short while ago: no X job starts before …`), and **Refresh cookies and Connect X account are refused too** (they load x.com), with the time it ends. A stop file that cannot be read refuses as well. `get x-session` shows `cooldown {until}`; - `clear-platform-hold {"platform": "twitter"}` is the explicit way to end it early. + nothing ends it early — not a clean answer from another reader, not Clear hold — but the operator's + **Clear the X stop** (/cookies, or `pnpm ops x-session --json '{"clearStop":true,"confirm":true}'`), which says + what it risks first and is logged in `.jobs/x-stop-cleared.jsonl`. Inside a capture, a refusal met by any of + its readers (an avatar's or an article image's 429, three pages in a row that would not render) records the + stop and ends the loop at once. A capture takes at most `social.x.maxPostsPerJob` posts (the rest are owed, + `owed`); a trending read's posts over its tabs stay within the same setting. +- **The Playwright fallback fetcher (`postFetcher: "x-playwright"`) is refused**: it cannot tell X's refusals. + A channel on it is refused in every mode, with the sentence naming the switch to `x-gallery-dl`. - **What one X job may read.** A walk of an account's timeline (sync new, Resume backfill, `full`, `older`) or of an X search reads at most `social.x.maxPostsPerJob` posts (300; 20-400 in the code), then saves its place and - ends; the next sitting continues it. A trending read's posts over both tabs stay within 400. + ends; the next sitting continues it. - **Clear session (Forget session) forgets the login only**: the profile, the jar and its refresh stamp. The suspended mark, the sitting and X's job count stay (they describe the account); Mark ok and a new Refresh are their own acts. 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 { xJobPostLimit } from "../lib/xSitting"; import { keepVerdictsTrustedWhileSuspended } from "../social/xAccountState"; import path from "node:path"; import { isXSearchChannel } from "../lib/xSearch/config"; @@ -167,6 +168,9 @@ export type CapturePostsResult = { avatars?: XAvatarRunSummary; // X: what the run read of the posts' context, when it read any. context?: XContextRunSummary; + // X: the ids past the per-job ceiling (social.x.maxPostsPerJob), not + // captured by this job and left for a later one (review 2 G3). + owed?: string[]; }; // Why this fetcher cannot capture posts, or null when it can. Shared with the @@ -263,7 +267,8 @@ export async function capturePosts( const log = (line: string) => onLog?.(line); const fail = (error: string): CapturePostsResult => ({ ok: false, outcomes: [], error }); const channelDir = path.join(paths.channelsDir, slug); - const ids = [...new Set(opts.ids)]; + let ids = [...new Set(opts.ids)]; + let owed: string[] = []; if (nothingToCapture(opts)) return fail(NOTHING_TO_CAPTURE); if (ids.length === 0) return fail("No post ids to capture."); @@ -300,6 +305,17 @@ export async function capturePosts( if (fetcher.platform === "twitter") { const refusal = xJobContextRefusal(`A capture of ${opts.slug}'s posts`, `pnpm ops capture-posts --json '{"slug":"${opts.slug}","ids":[…]}' --wait`); if (refusal) return fail(refusal); + // WHAT ONE X JOB MAY TAKE (review 2 G3): the first posts up to the + // ceiling; the rest are owed to a later job (`owed`). + const cap = xJobPostLimit(settings?.social?.x as { maxPostsPerJob?: number } | undefined); + if (ids.length > cap) { + owed = ids.slice(cap); + ids = ids.slice(0, cap); + log( + `This X capture takes the first ${cap} of ${cap + owed.length} posts (social.x.maxPostsPerJob); ` + + `the other ${owed.length} are left for a later job, from ${owed[0]}.`, + ); + } } const avatarsOnly = opts.avatarsOnly === true; if (avatarsOnly) { @@ -511,9 +527,9 @@ export async function capturePosts( const stoppedByOperator = (opts.signal ?? controller.signal).aborted || Boolean(opts.drain?.aborted); if (result.stoppedEarly && !stoppedByOperator) { - return { ok: false, outcomes: result.outcomes, error: result.stoppedEarly, ...avatars }; + return { ok: false, outcomes: result.outcomes, error: result.stoppedEarly, ...avatars, ...(owed.length ? { owed } : {}) }; } - return { ok: true, outcomes: result.outcomes, ...avatars }; + return { ok: true, outcomes: result.outcomes, ...avatars, ...(owed.length ? { owed } : {}) }; } const waitFor = (ms: number, signal: AbortSignal) => diff --git a/common/controller/fetchPosts.test.ts b/common/controller/fetchPosts.test.ts @@ -758,3 +758,29 @@ test("R2a: an availability check of an X channel outside the editor's job is ref const inside = await asEditorJob(() => checkPostAvailability({ paths, slug: SLUG })); assert.doesNotMatch(inside.error ?? "", /asks X, and X/); }); + +// LANE X-SITTINGS, review 2 G1: the Playwright fallback cannot tell X's +// refusals, so a channel on it is refused in every mode, before anything +// opens, with the sentence naming the switch; the fetcher refuses too. +test("x-playwright is refused in every mode, naming the postFetcher to switch to; nothing is asked of X", async () => { + const slug = "fake-x-playwright"; + const root = await makeChannel(slug); + const config = JSON.parse(await readFile(path.join(root, "config.json"), "utf8")); + await writeFile(path.join(root, "config.json"), JSON.stringify({ ...config, postFetcher: "x-playwright" })); + const before = (await readFile(ARGS_LOG, "utf8").catch(() => "")).trim().split("\n").length; + for (const mode of [{}, { backfill: true }, { full: true }, { older: true }]) { + const log: string[] = []; + const { runInJobContext } = await import("../lib/jobContext"); + const ctx = { jobId: "g1", kind: "fetch-posts", queueKey: "platform:twitter", onLog: () => {}, staleServices: new Set<string>() }; + const r = await runInJobContext(ctx, async () => fetchPosts({ paths: (await import("../lib/paths")).getPaths(), slug, settings: {}, onLog: (l) => log.push(l), ...mode })); + assert.equal(r.ok, false, JSON.stringify(mode)); + // Refused by fetchPosts itself, before any walk began. + assert.ok(!log.some((l) => /^Fetching (older )?posts/.test(l)), log.join("\n")); + assert.match(r.error ?? "", /^fake-x-playwright's post fetcher is x-playwright \(the Playwright fallback\), which cannot tell when X refuses or rate-limits it, so it is refused: set the channel's postFetcher to x-gallery-dl/); + } + assert.equal((await readFile(ARGS_LOG, "utf8").catch(() => "")).trim().split("\n").length, before, "no gallery-dl run"); + const { xPlaywrightFetcher } = await import("../social/xPlaywrightFetcher"); + const direct = await xPlaywrightFetcher.fetch({ accountUrl: "https://x.com/faketester", handle: "faketester", channelSlug: slug, seenIds: new Set() } as never); + assert.equal(direct.complete, false); + assert.match(direct.error ?? "", /is refused/); +}); diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts @@ -96,6 +96,7 @@ import { instagramJobGuard } from "../jobs/instagramGuard"; import { currentJobContext } from "../lib/jobContext"; import { xJobContextRefusal } from "../lib/xJobRule"; import { xJobPostLimit } from "../lib/xSitting"; +import { X_PLAYWRIGHT_REFUSED, xPlaywrightRefused } from "../social/xPlaywrightFetcher"; import { INSTAGRAM_QUEUE_KEY, INSTAGRAM_QUEUE_REFUSAL, isInstagramPostsChannelConfig } from "../lib/instagram/channel"; import { detectPlatform } from "../lib/platform"; import { postsMediaDir } from "../social/postCapture"; @@ -415,6 +416,11 @@ export async function fetchPosts( // …and only on X's queue (added scope R2): asked where the job runs too. const queue = xJobContextRefusal(slug, X_FETCH_DOOR(slug)); if (queue) return { ok: false, written: 0, skipped: 0, complete: false, error: queue }; + // THE PLAYWRIGHT FALLBACK IS REFUSED (review 2 G1): it cannot tell X's + // refusals, so it would scroll past a 429 and call the walk complete. + if (fetcher.id === "x-playwright" && xPlaywrightRefused()) { + return { ok: false, written: 0, skipped: 0, complete: false, error: X_PLAYWRIGHT_REFUSED(slug) }; + } // WHAT ONE X JOB MAY READ (review 1 F8; lib/xSitting.ts): every mode // below — timeline, backfill, full, older, search — takes the limit. const limit = xJobPostLimit(settings?.social?.x as { maxPostsPerJob?: number } | undefined, opts.limit); diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts @@ -102,7 +102,22 @@ export const READ_X_TRENDING_RESULT_MARKER = "@@read-x-trending "; // (jobs/downloadBackoff.ts recordPlatformCooldown — the cooldown import-post // already respects), read by this job's enqueue and start. export { X_RATE_LIMIT_HOLD_MS } from "../lib/xJobRule"; -import { X_POSTS_PER_JOB_CEILING } from "../lib/xSitting"; +import { xJobPostLimit } from "../lib/xSitting"; +import { getSettings } from "../lib/settings"; + +// WHAT ONE READ MAY TAKE (review 2 G3): its posts over all its tabs stay +// within social.x.maxPostsPerJob (default 300; the code's ceiling bounds it). +export function xTrendingPostsPerTab(asked: number, tabs: number, x: { maxPostsPerJob?: number } | undefined): number { + return Math.max(1, Math.min(asked, Math.floor(xJobPostLimit(x) / Math.max(1, tabs)))); +} + +function xPostsSettingNow(): { maxPostsPerJob?: number } | undefined { + try { + return getSettings().social?.x; + } catch { + return undefined; + } +} import { X_RATE_LIMIT_HOLD_MS } from "../lib/xJobRule"; const X_PLATFORM = "twitter"; @@ -286,7 +301,7 @@ export async function planReadXTrending( ref, // WHAT ONE X JOB MAY READ (review 1 F8): the read's posts over all its // tabs stay within X's per-job ceiling (lib/xSitting.ts). - limits: { ...limits.limits, posts: Math.max(1, Math.min(limits.limits.posts, Math.floor(X_POSTS_PER_JOB_CEILING / Math.max(1, tabs.tabs.length)))) }, + limits: { ...limits.limits, posts: xTrendingPostsPerTab(limits.limits.posts, tabs.tabs.length, xPostsSettingNow()) }, ...(topic ? { topic } : {}), probe: ask.probe === true, headed: ask.headed === true, diff --git a/common/jobs/downloadBackoff.ts b/common/jobs/downloadBackoff.ts @@ -42,7 +42,7 @@ import { settlePlatformClean, } from "./platformBackoff"; import { staticSleepRequestsSeconds } from "../ytdlp/platformArgs.mjs"; -import { applyXStop, X_STOP_PLATFORM } from "./platformBackoff"; +import { applyXStop, clearXStopEntry, X_STOP_MS, X_STOP_PLATFORM } from "./platformBackoff"; import { currentJobContext } from "../lib/jobContext"; import { readFile } from "node:fs/promises"; @@ -288,13 +288,15 @@ export async function clearPlatformHold( // ends DEFERRED, saying so (jobs/streamCommand.ts). `why` names the answer // ("a rate limit (gallery-dl)"). Answers when the stop ends (ms). export async function recordXStop(why: string, paths: Paths = getPaths(), now: number = Date.now()): Promise<number> { + // The job is told FIRST (review 2 G5): a write that fails still stops it. + const job = currentJobContext(); + if (job && (!job.xStop || job.xStop.until < now + X_STOP_MS)) job.xStop = { until: now + X_STOP_MS, why, at: now }; const until = await mutateDownloadState(paths, (state) => { prunePlatformPacing(state.download, now); return applyXStop(state.download, now).until; }); - const job = currentJobContext(); if (job) { - if (!job.xStop || job.xStop.until < until) job.xStop = { until, why, at: now }; + if (job.xStop && job.xStop.until < until) job.xStop = { ...job.xStop, until }; job.onLog(`X answered ${why}: X is left alone until ${new Date(until).toISOString().slice(11, 16)} UTC (15 minutes); this job stops here.`); } return until; @@ -321,3 +323,30 @@ export async function xStopRemainingMs(paths: Paths = getPaths(), now: number = } return entry && entry.until > now ? entry.until - now : 0; } + +// "CLEAR THE X STOP" (review 2 G4): the operator's named, logged act — the +// only way X's 15-minute stop ends before its time. Without `confirm` it +// removes nothing and answers what it would risk. Each clear is logged in +// `<jobsDir>/x-stop-cleared.jsonl` ({at, until, why, by, note?}). +export const X_STOP_CLEAR_RISK = + "Clearing the X stop lets the next X job ask X at once, inside the 15 minutes X was left alone for after it " + + "answered a rate limit or a bot check — asking again then is what gets an account limited or locked."; + +export async function clearXStop( + paths: Paths, + opts: { confirm: boolean; by: string; note?: string; now?: number }, +): Promise<{ ok: true; cleared: { until: number } | null; message: string } | { ok: false; confirmNeeded: true; message: string }> { + const now = opts.now ?? Date.now(); + if (!opts.confirm) return { ok: false, confirmNeeded: true, message: `${X_STOP_CLEAR_RISK} Confirm to clear it.` }; + const removed = await mutateDownloadState(paths, (state) => clearXStopEntry(state.download, now)); + if (!removed) return { ok: true, cleared: null, message: "No X stop was running; nothing was cleared." }; + const { appendFile, mkdir } = await import("node:fs/promises"); + const line = { at: new Date(now).toISOString(), until: new Date(removed.until).toISOString(), by: opts.by, ...(opts.note ? { note: opts.note } : {}) }; + await mkdir(paths.jobsDir, { recursive: true }); + await appendFile(`${paths.jobsDir}/x-stop-cleared.jsonl`, `${JSON.stringify(line)}\n`); + return { + ok: true, + cleared: { until: removed.until }, + message: `The X stop (until ${line.until.slice(11, 16)} UTC) was cleared by ${opts.by}; X jobs may start now. Logged in .jobs/x-stop-cleared.jsonl.`, + }; +} diff --git a/common/jobs/platformBackoff.ts b/common/jobs/platformBackoff.ts @@ -95,14 +95,27 @@ export function isCoolingDown( return entry !== undefined && entry.until > now; } -// Clear a platform's backoff (called on a successful download). Mutates in place. +// Clear a platform's backoff (called on a successful download, and by Clear +// hold). Mutates in place. NEVER X'S STOP BEFORE ITS TIME (review 2 G4): a +// clean answer from any reader, or Clear hold, leaves an X stop that has not +// ended; only clearXStopEntry — the operator's "Clear the X stop" — removes it. export function clearBackoff( state: PlatformBackoffState, platform: string, + now: number = Date.now(), ): void { + if (platform === X_STOP_PLATFORM && (state[platform]?.until ?? 0) > now) return; delete state[platform]; } +// THE OPERATOR'S "CLEAR THE X STOP" (review 2 G4): the one removal of X's stop +// before its time. Answers what was removed (null: no stop was running). +export function clearXStopEntry(state: { platformBackoff: PlatformBackoffState }, now: number): PlatformBackoffEntry | null { + const entry = state.platformBackoff[X_STOP_PLATFORM]; + delete state.platformBackoff[X_STOP_PLATFORM]; + return entry && entry.until > now ? entry : null; +} + // Drop entries whose cooldown lapsed long enough ago that keeping their `fails` // count for escalation memory no longer matters. Mutates in place, keeping the // map bounded across a long-running server. We retain a lapsed entry for one @@ -451,7 +464,7 @@ export function settlePlatformClean( ): CleanEffect { const pacing = opts.pacing ?? PACING_DEFAULTS; const releasedHold = isPlatformHeld(state.platformHolds, platform); - clearBackoff(state.platformBackoff, platform); + clearBackoff(state.platformBackoff, platform, opts.now ?? Date.now()); delete state.platformHolds[platform]; const pace = state.platformPace[platform]; let decayed = false; diff --git a/common/jobs/xSittings.test.ts b/common/jobs/xSittings.test.ts @@ -629,3 +629,53 @@ test("F1: the auto-download lane's X unit that met a rate limit sets the 15-minu assert.deepEqual(state.platformHolds, {}, "no hold"); assert.match(fx.line ?? "", /X answered a rate limit — X is left alone until/); }); + +test("review 2 G3: a capture takes at most social.x.maxPostsPerJob posts (the rest owed); a trending read's tabs share the setting", async () => { + const { capturePosts } = await import("../controller/capturePosts"); + const { xTrendingPostsPerTab } = await import("../controller/readXTrending"); + const { getSettings } = await import("../lib/settings"); + await reset(); + await writeSettings({ maxPostsPerJob: 50 }); + const ids = Array.from({ length: 51 }, (_, i) => String(1000 + i)); + const log: string[] = []; + const ctx = { jobId: "g3", kind: "capture-posts", queueKey: "platform:twitter", onLog: () => {}, staleServices: new Set<string>() }; + await runInJobContext(ctx, () => capturePosts({ paths, slug: ACCOUNTS[0], settings: getSettings(), ids, onLog: (l) => log.push(l) })); + assert.ok(log.some((l) => /^This X capture takes the first 50 of 51 posts \(social\.x\.maxPostsPerJob\); the other 1 are left for a later job, from 1050\.$/.test(l)), log.join("\n")); + // The trending read: the setting over its tabs, never past what was asked. + assert.equal(xTrendingPostsPerTab(200, 2, undefined), 150); + assert.equal(xTrendingPostsPerTab(200, 2, { maxPostsPerJob: 20 }), 10); + assert.equal(xTrendingPostsPerTab(200, 1, { maxPostsPerJob: 9999 }), 200); + assert.equal(xTrendingPostsPerTab(400, 1, { maxPostsPerJob: 9999 }), 400); + await writeSettings(); +}); + +test("review 2 G4: nothing ends the X stop before its time — not a clean answer, not Clear hold — but 'Clear the X stop', confirmed and logged", async () => { + const { recordPlatformClean, clearPlatformHold, clearXStop } = await import("./downloadBackoff"); + const { settlePlatformClean } = await import("./platformBackoff"); + const left = async () => Math.round((await xStopRemainingMs(paths)) / 60_000); + await reset(); + await recordXStop("a rate limit", paths); + // A clean answer from another reader (a window fetch, a sync) and the lane page's Clear hold. + await recordPlatformClean("twitter", paths); + assert.equal(await left(), 15); + await clearPlatformHold("twitter", paths); + assert.equal(await left(), 15); + // The pure settle, too. + const st = { platformBackoff: { twitter: { until: Date.now() + 600_000, fails: 1 } }, platformHolds: {}, platformPace: {} } as never; + settlePlatformClean(st, "twitter", { baseSeconds: 1 }); + assert.ok((st as { platformBackoff: Record<string, unknown> }).platformBackoff.twitter); + // The operator's act: unconfirmed, it clears nothing and says what it risks. + const asked = await clearXStop(paths, { confirm: false, by: "test" }); + assert.equal(asked.ok, false); + assert.match(asked.message, /^Clearing the X stop lets the next X job ask X at once, inside the 15 minutes/); + assert.equal(await left(), 15); + const done = await clearXStop(paths, { confirm: true, by: "test", note: "checked" }); + assert.equal(done.ok, true); + assert.equal(await left(), 0); + const logged = (await readFile(path.join(paths.jobsDir, "x-stop-cleared.jsonl"), "utf8")).trim().split("\n").map((l) => JSON.parse(l)); + assert.deepEqual([logged.at(-1).by, logged.at(-1).note], ["test", "checked"]); + // An ended stop is pruned as before (a clean answer clears an expired entry). + const expired = { platformBackoff: { twitter: { until: Date.now() - 1, fails: 1 } }, platformHolds: {}, platformPace: {} } as never; + settlePlatformClean(expired, "twitter", { baseSeconds: 1 }); + assert.equal((expired as { platformBackoff: Record<string, unknown> }).platformBackoff.twitter, undefined); +}); diff --git a/common/social/xArticleCapture.test.ts b/common/social/xArticleCapture.test.ts @@ -470,3 +470,15 @@ test("run: an older record's article is not lost by a run that does not read it" assert.deepEqual(h.visits, []); assert.deepEqual((await readPostCapture(dir))!.article, article); }); + +// LANE X-SITTINGS, review 2 G2: an image X's host answers 429 ends the image +// loop at once and marks the article refused, so the capture records the X +// stop and loads no further page. +test("article: an image answered 429 stops the images at once and marks the article refused", async () => { + const dir = await tmpDir(); + const p = articlePage([articleSnap()], { served: { [orig(COVER)]: { status: 429 } } }); + const res = await captureXArticle(p, LINK, dir, { now: NOW }); + assert.deepEqual(p.fetched, [orig(COVER)], "nothing after the 429"); + assert.equal(res.refused, true); + assert.match(res.stop ?? "", /rate limit \(429\) to an article image/); +}); diff --git a/common/social/xArticleCapture.ts b/common/social/xArticleCapture.ts @@ -338,6 +338,9 @@ export async function captureXArticle( ...(trimmed ? { trimmed: true } : {}), ...(error ? { error } : {}), }, + // An image refused with 429: the caller records X's stop and loads no + // further page (review 2 G2). + ...(images.refused ? { refused: true as const, stop: "X answered a rate limit (429) to an article image; stopping rather than asking again." } : {}), }; } @@ -349,7 +352,7 @@ async function fetchArticleImages( blocks: ReadonlyArray<XArticleBlock>, dir: string, opts: XArticleCaptureOptions, -): Promise<{ saved: Map<string, CapturedFile>; errors: string[] }> { +): Promise<{ saved: Map<string, CapturedFile>; errors: string[]; refused?: true }> { const saved = new Map<string, CapturedFile>(); const errors: string[] = []; const srcs = [...new Set(blocks.flatMap((b) => (b.type === "image" && b.src ? [b.src] : [])))]; @@ -359,7 +362,9 @@ async function fetchArticleImages( return { saved, errors }; } let n = 0; + let refused = false; for (const src of srcs) { + if (refused) break; if (opts.signal?.aborted) { errors.push("cancelled before the rest of the images"); break; @@ -373,6 +378,12 @@ async function fetchArticleImages( const res = await page.request.get(url, { timeout: 30_000, failOnStatusCode: false }); if (!res.ok()) { last = `HTTP ${res.status()} for ${url}`; + // X's image host rate-limited it: the X stop, and no further image + // (review 2 G2). + if (res.status() === 429) { + refused = true; + break; + } continue; } const body = await res.body(); @@ -388,7 +399,7 @@ async function fetchArticleImages( if (last) errors.push(last); } if (saved.size) opts.onLog?.(`article: ${saved.size} image(s) saved.`); - return { saved, errors }; + return { saved, errors, ...(refused ? { refused: true as const } : {}) }; } // A re-capture with fewer images leaves no older numbered file behind. diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts @@ -32,6 +32,7 @@ import { execa } from "execa"; import { getPaths } from "../lib/paths"; import { noteXServiceOutcome } from "../lib/serviceCookies-server"; import { recordXStop } from "../jobs/downloadBackoff"; +import { currentJobContext } from "../lib/jobContext"; import { looksLikeXAuthFailure, xBlockKind, xBlockLine } from "./xGalleryDlSignals"; import { cookieArgs } from "../lib/cookiePolicy"; import type { Post, PostRef } from "../lib/posts"; @@ -450,6 +451,8 @@ export async function captureXPostsByIds( pause, // X refused a page: the X stop, recorded at once (review 1 F1). noteXStop: (why) => recordXStop(why, paths), + // Any reader of this job that met X's stop (an avatar's 429) halts it. + xStopped: () => Boolean(currentJobContext()?.xStop), articleImagePauseMs: () => ARTICLE_IMAGE_PAUSE_MS + Math.floor(Math.random() * ARTICLE_IMAGE_PAUSE_MS), }); } diff --git a/common/social/xPlaywrightFetcher.ts b/common/social/xPlaywrightFetcher.ts @@ -125,6 +125,23 @@ function mergeTweet( return merged; } +// REFUSED (lane x-sittings, review 2 G1, the operator's ruling): this reader +// reads no response status and no refusal or challenge page, so a 429 from X +// would be scrolled past and reported as a complete walk, with no X stop and +// no place to continue from. Until it can tell X's refusals (and keep a +// place), no X job runs it: fetchPosts refuses the channel, and fetch() below +// refuses too, for any caller that reaches it another way. +export const X_PLAYWRIGHT_REFUSED = (slug: string) => + `${slug}'s post fetcher is x-playwright (the Playwright fallback), which cannot tell when X refuses or rate-limits ` + + "it, so it is refused: set the channel's postFetcher to x-gallery-dl (the channel page → Configure → scraping " + + `method, or pnpm ops channel-config --json '{"slug":"${slug}","patch":{"postFetcher":"x-gallery-dl"}}'), then fetch again. Nothing was asked of X.`; + +// Always: no setting, environment variable or option turns the refusal off. +// Lifting it is a code change, made once this reader sees X's refusals. +export function xPlaywrightRefused(): boolean { + return true; +} + export const xPlaywrightFetcher: SocialFetcher = { id: "x-playwright", label: "X / Twitter (Playwright fallback)", @@ -155,6 +172,10 @@ export const xPlaywrightFetcher: SocialFetcher = { }, async fetch(input: PostFetchInput): Promise<PostFetchResult> { + // Refused before anything opens (review 2 G1). + if (xPlaywrightRefused()) { + return { posts: [], complete: false, error: X_PLAYWRIGHT_REFUSED(input.channelSlug || "This channel") }; + } const { accountUrl, channelSlug, since, seenIds, limit, signal, onLog } = input; const paths = getPaths(); diff --git a/common/social/xPostCapture.test.ts b/common/social/xPostCapture.test.ts @@ -15,6 +15,7 @@ import type { PageLike } from "./playwrightRuntime"; import { captureXPosts, classifyXPostSnapshot, + X_STOPPED_CAPTURE, shootXPost, type XCaptureDeps, type XPostSnapshot, @@ -514,3 +515,32 @@ test("run: a refused page records the X stop and stops the run", async () => { assert.deepEqual(res.outcomes.map((o) => o.id), ["11", "22"]); assert.equal(classifyXPostSnapshot(page("Rate limit exceeded")).refused, true); }); + +// LANE X-SITTINGS, review 2 G2: once any reader of the job met X's stop (an +// avatar's 429), the capture loads no further page; three pages in a row that +// would not render record the stop. +test("run: a stop met by another reader of the job halts the capture before its next page load", async () => { + const h = harness({ "11": [post()], "22": [post()], "33": [post()] }); + let stoppedNow = false; + const res = await captureXPosts(await input(["11", "22", "33"]), { + ...h.deps, + // The first post's media download is where "the avatar's 429" landed. + downloadMedia: async (a) => { + const r = await h.deps.downloadMedia(a); + stoppedNow = true; + return r; + }, + xStopped: () => stoppedNow, + }); + assert.equal(res.stoppedEarly, X_STOPPED_CAPTURE); + assert.deepEqual(res.outcomes.map((o) => o.id), ["11"]); + assert.deepEqual(h.downloads, ["11"], "no page or download after the stop"); +}); + +test("run: three pages in a row that would not render record the X stop", async () => { + const h = harness({ "11": [page("")], "22": [page("")], "33": [page("")], "44": [post()] }); + const stops: string[] = []; + const res = await captureXPosts(await input(["11", "22", "33", "44"]), { ...h.deps, noteXStop: async (w) => void stops.push(w) }); + assert.deepEqual(stops, ["three pages in a row it would not render, to a capture"]); + assert.match(res.stoppedEarly ?? "", /3 posts in a row failed/); +}); diff --git a/common/social/xPostCapture.ts b/common/social/xPostCapture.ts @@ -362,6 +362,11 @@ export type XCaptureDeps = { // X REFUSED a page or the media (a rate limit, a bot check): the X stop, // recorded at once (jobs/downloadBackoff.ts recordXStop in production). noteXStop?: (why: string) => Promise<unknown>; + // Has this job met X's stop (a refusal recorded by any reader inside it — + // an avatar's 429, an article image's)? Asked before every page load: a + // capture asks X nothing more once it has (review 2 G2). Production: the + // job context's xStop. + xStopped?: () => boolean; // One post's media into `dir` (gallery-dl in production). downloadMedia: (args: { id: string; @@ -381,6 +386,23 @@ export type XCaptureDeps = { // failing every post should not page through the rest of the list. const STOP_AFTER_ERRORS = 3; +export const X_STOPPED_CAPTURE = + "X refused this capture (a rate limit, a bot check or a page it would not render): the X stop is recorded and no further page is loaded in this job; the rest are left for a later sitting."; + +// The capture's halt (review 2 G2): the stop noted in this run, or met by any +// reader of this job. +function haltFor(deps: Pick<XCaptureDeps, "noteXStop" | "xStopped">) { + let noted = false; + return { + note: async (why: string) => { + noted = true; + await deps.noteXStop?.(why); + }, + halted: () => noted || (deps.xStopped?.() ?? false), + }; +} + + // The capture loop: per id, what is owed (captureWork), the shot, the media, // the record. Every post's record is written as soon as that post is done, so // a cancel or a crash loses at most the post in hand. @@ -410,6 +432,7 @@ export async function captureXPosts( let errorsInARow = 0; let browser: { page: PageLike; close: () => Promise<void> } | undefined; + const halt = haltFor(deps); const contact = async () => { if (contacts++ > 0) await deps.pause(deps.pauseMs(), signal); }; @@ -431,6 +454,7 @@ export async function captureXPosts( try { for (const [i, id] of input.ids.entries()) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); if (input.drain?.aborted) return stopped("Drained; the rest are left for a later run."); const dir = postCaptureDir(input.outDir, id); @@ -470,6 +494,7 @@ export async function captureXPosts( let stop: string | undefined; if (work.shot || threadOwed) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); await contact(); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); browser ??= await deps.openPage(); @@ -506,7 +531,7 @@ export async function captureXPosts( threadError = res.error ?? `The page showed the post as ${res.state}.`; } stop = res.stop; - if (res.refused) await deps.noteXStop?.("a refused page to a capture"); + if (res.refused) await halt.note("a refused page to a capture"); if (res.thread) { if ("thread" in res.thread) thread = res.thread.thread; else if ("none" in res.thread) threadNone = res.thread.none; @@ -523,6 +548,7 @@ export async function captureXPosts( // download: X has nothing to give for a deleted or walled one. const postIsThere = state === undefined || state === "captured"; if (work.media && postIsThere && !stop) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); await contact(); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); await mkdir(dir, { recursive: true }); @@ -556,6 +582,7 @@ export async function captureXPosts( let article: ArticleCaptureRecord | undefined = existing?.article; let articleFailed = false; if (work.article && articleLink && (state === undefined || state === "captured") && !stop) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); await contact(); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); browser ??= await deps.openPage(); @@ -572,7 +599,7 @@ export async function captureXPosts( // A run that only read the article learns of the post only that it // linked to a readable article. state ??= article.state === "captured" ? "captured" : "error"; - if (got.refused) await deps.noteXStop?.("a refused article page to a capture"); + if (got.refused) await halt.note("a refusal to an article (its page or an image) in a capture"); if (got.stop) { stop = got.stop; if (article.state === "login-wall") needsCookies = true; @@ -630,6 +657,9 @@ export async function captureXPosts( } errorsInARow = finalState === "error" || articleFailed ? errorsInARow + 1 : 0; if (errorsInARow >= STOP_AFTER_ERRORS) { + // Pages that would not render, three in a row: X's bot check as + // often as not — the X stop (review 2 G2). + await halt.note("three pages in a row it would not render, to a capture"); return stopped( `${STOP_AFTER_ERRORS} posts in a row failed; stopping rather than paging through the rest.`, ); @@ -704,8 +734,10 @@ async function captureXAvatarsOnly(input: PostCaptureInput, deps: XCaptureDeps): onLog?.(why); return done({ stoppedEarly: why, ...extra }); }; + const halt = haltFor(deps); try { for (const [i, id] of picks.entries()) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); if (input.drain?.aborted) return stopped("Drained; the rest are left for a later run."); if (contacts++ > 0) await deps.pause(deps.pauseMs(), signal); @@ -722,7 +754,7 @@ async function captureXAvatarsOnly(input: PostCaptureInput, deps: XCaptureDeps): if (res.state !== "captured") { const why = res.error ?? `the page showed the post as ${res.state}`; onLog?.(`${id}: no avatar read — ${why}.`); - if (res.refused) await deps.noteXStop?.("a refused page to a capture"); + if (res.refused) await halt.note("a refused page to a capture"); if (res.stop) { return stopped(`${res.stop} Stopped at ${id}; the rest are left for a later run.`, { needsCookies: res.state === "login-wall", @@ -730,6 +762,7 @@ async function captureXAvatarsOnly(input: PostCaptureInput, deps: XCaptureDeps): } errorsInARow = res.state === "error" ? errorsInARow + 1 : 0; if (errorsInARow >= STOP_AFTER_ERRORS) { + await halt.note("three pages in a row it would not render, to a capture"); return stopped(`${STOP_AFTER_ERRORS} pages in a row failed; stopping rather than paging through the rest.`); } continue; @@ -794,8 +827,10 @@ async function captureXContextOnly(input: PostCaptureInput, deps: XCaptureDeps): onLog?.(why); return done({ stoppedEarly: why, ...extra }); }; + const halt = haltFor(deps); try { for (const [i, { id, existing }] of picks.entries()) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); if (input.drain?.aborted) return stopped("Drained; the rest are left for a later run."); if (contacts++ > 0) await deps.pause(deps.pauseMs(), signal); @@ -814,7 +849,7 @@ async function captureXContextOnly(input: PostCaptureInput, deps: XCaptureDeps): if (res.state !== "captured") { const why = res.error ?? `the page showed the post as ${res.state}`; onLog?.(`${id}: no context read — ${why}.`); - if (res.refused) await deps.noteXStop?.("a refused page to a capture"); + if (res.refused) await halt.note("a refused page to a capture"); summary.failed.push({ id, error: why }); if (res.stop) { return stopped(`${res.stop} Stopped at ${id}; the rest are left for a later run.`, { @@ -823,6 +858,7 @@ async function captureXContextOnly(input: PostCaptureInput, deps: XCaptureDeps): } errorsInARow = res.state === "error" ? errorsInARow + 1 : 0; if (errorsInARow >= STOP_AFTER_ERRORS) { + await halt.note("three pages in a row it would not render, to a capture"); return stopped(`${STOP_AFTER_ERRORS} pages in a row failed; stopping rather than paging through the rest.`); } continue; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -36,6 +36,14 @@ - **Forget session keeps the suspended mark, the sitting and X's job count.** While the account is marked suspended, nothing is written as deleted or unavailable from X's answers, video checks and outcomes included. - The drawn gap is always at least 3 minutes wide, whatever is set. + - Nothing ends the 15-minute stop early except **Clear the X stop** on /cookies (or `pnpm ops x-session + --json '{"clearStop":true,"confirm":true}'`), which asks first and is logged. A clean answer from another + reader and Clear hold no longer end it. + - Inside a capture, a refusal from any part of it (an avatar, an article image, three pages that would not + render) records the stop and ends the capture at once. A capture takes at most 300 posts per job; the rest + are left for a later one. + - **Channels on the Playwright fallback fetcher (`x-playwright`) are refused**, because it cannot tell when X + refuses it. Switch the channel to `x-gallery-dl`. - Needs a restart of the editor. - **umtool: name a channel once for a whole cut.** - A cut made from two recordings of one channel showed two names for it, the older record's uploader name and diff --git a/editor/app/api/ops/x-session/route.test.ts b/editor/app/api/ops/x-session/route.test.ts @@ -61,3 +61,16 @@ test("POST refuses a state it does not know, a stray key and a note that is not assert.equal(r.body.ok, false); } }); + +test("POST clearStop: unconfirmed answers 409 with what it risks; confirmed clears it", async () => { + const { recordXStop, xStopRemainingMs } = await import("yt-dlp-transcript-common/jobs/downloadBackoff"); + const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); + await recordXStop("a rate limit", getPaths()); + const asked = await post({ clearStop: true }); + assert.equal(asked.status, 409); + assert.match(asked.body.error ?? "", /^Clearing the X stop lets the next X job ask X at once/); + assert.ok((await xStopRemainingMs(getPaths())) > 0); + const done = await post({ clearStop: true, confirm: true }); + assert.equal(done.status, 200); + assert.equal(await xStopRemainingMs(getPaths()), 0); +}); diff --git a/editor/app/api/ops/x-session/route.ts b/editor/app/api/ops/x-session/route.ts @@ -3,6 +3,7 @@ import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels import { xSessionReport } from "yt-dlp-transcript-common/jobs/networkGuard"; import { NextResponse } from "next/server"; import { writeXAccountState } from "yt-dlp-transcript-common/social/xAccountState"; +import { clearXStop } from "yt-dlp-transcript-common/jobs/downloadBackoff"; import { readRoute } from "../_read"; import { oneOf, ops, opsFail, optString } from "../_lib"; @@ -36,8 +37,21 @@ export async function GET(request: Request) { // "suspended" the network guard refuses the X jobs that record posts as // deleted or unavailable, and every other X job logs it. Nothing is asked of // X; nothing else is written. /cookies has the same control. +// +// POST {"clearStop": true, "confirm"?: true, "note"?} — "Clear the X stop" +// (common/jobs/downloadBackoff.ts clearXStop): the one way X's 15-minute stop +// after a rate limit or a bot check ends before its time. Without "confirm" it +// clears nothing and answers 409 with what it risks; each clear is logged. export async function POST(request: Request) { - return ops(request, ["accountState", "note"], async (body) => { + return ops(request, ["accountState", "note", "clearStop", "confirm"], async (body) => { + if (body.clearStop !== undefined) { + if (body.clearStop !== true) return opsFail('"clearStop" must be true'); + if (body.accountState !== undefined) return opsFail('"clearStop" and "accountState" are two acts: send one'); + const note = optString(body, "note"); + const r = await clearXStop(getPaths(), { confirm: body.confirm === true, by: "pnpm ops x-session", ...(note ? { note } : {}) }); + if (!r.ok) return opsFail(r.message, 409, { confirmNeeded: true }); + return NextResponse.json({ ok: true, cleared: r.cleared, message: r.message }); + } const state = oneOf(body, "accountState", ["suspended", "ok"] as const); const note = optString(body, "note"); const account = await writeXAccountState(getPaths(), state, note ? { note } : {}); diff --git a/editor/app/cookies/CookiesBoard.tsx b/editor/app/cookies/CookiesBoard.tsx @@ -16,7 +16,7 @@ import { type XSittingView, } from "yt-dlp-transcript-common/lib/cookieStatus"; import { usePolledPayload } from "../lib/usePolledPayload"; -import { cookieControlsAction, pressCookieButtonAction, setXAccountStateAction } from "./actions"; +import { clearXStopAction, cookieControlsAction, pressCookieButtonAction, setXAccountStateAction } from "./actions"; import { sectionFailed, type CookieControls } from "../lib/cookieControlsTypes"; import { XSessionSection } from "../settings/components/XSessionSection"; import { ArchiveSourcesSection } from "../settings/components/ArchiveSessionSection"; @@ -219,9 +219,36 @@ function XSittingPanel({ view, onStatus }: { view: XSittingView; onStatus: (s: C <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> + <div className="flex flex-col gap-2 sm:flex-row sm:items-center"> + <p className="text-xs text-destructive" aria-label="X cooldown"> + X answered a rate limit or a bot check: no X job starts before {hms(view.cooldownUntil)}. + </p> + <button + type="button" + aria-label="Clear the X stop" + disabled={pending} + onClick={async () => { + if ( + !window.confirm( + "Clearing the X stop lets the next X job ask X at once, inside the 15 minutes X was left alone for. " + + "Asking again then is what gets an account limited or locked. Clear it?", + ) + ) + return; + setPending(true); + try { + const r = await clearXStopAction(true); + onStatus(r.status); + setAnswer({ text: r.message, ok: r.ok }); + } finally { + setPending(false); + } + }} + className="w-full rounded-md border border-destructive/60 px-3 py-2 text-sm text-destructive hover:bg-muted disabled:opacity-50 sm:w-auto sm:py-1.5" + > + Clear the X stop + </button> + </div> )} {view.account.alert && ( <p role="alert" aria-label="X account alert" className="text-xs text-destructive break-words"> diff --git a/editor/app/cookies/actions.ts b/editor/app/cookies/actions.ts @@ -38,6 +38,7 @@ import { listForumChannels } from "../lib/forumChannels"; import { loadCookieStatus } from "../lib/cookieStatus"; import { loadCookieControls, type CookieControls } from "../lib/cookieControls"; import { writeXAccountState } from "yt-dlp-transcript-common/social/xAccountState"; +import { clearXStop } from "yt-dlp-transcript-common/jobs/downloadBackoff"; export type CookiePressResult = { ok: boolean; @@ -126,3 +127,17 @@ export async function setXAccountStateAction(state: string, note?: string): Prom } return { ...answer, message: displayText(answer.message), status: await loadCookieStatus(paths) }; } + +// "CLEAR THE X STOP" on /cookies (common/jobs/downloadBackoff.ts clearXStop): +// the page asks the operator to confirm what it risks first; logged. +export async function clearXStopAction(confirm: boolean): Promise<CookiePressResult> { + const paths = getPaths(); + let answer: Answer; + try { + const r = await clearXStop(paths, { confirm: confirm === true, by: "/cookies" }); + answer = { ok: r.ok, message: r.message }; + } catch (e) { + answer = { ok: false, message: (e as Error).message }; + } + return { ...answer, message: displayText(answer.message), status: await loadCookieStatus(paths) }; +} diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -152,6 +152,7 @@ // pnpm ops get x-session // pnpm ops x-session --json '{"accountState":"suspended","note":"read-only since the 21st"}' // pnpm ops x-session --json '{"accountState":"ok"}' +// pnpm ops x-session --json '{"clearStop":true,"confirm":true,"note":"checked by hand"}' // pnpm ops get cookies [fresh] // pnpm ops recheck-service --json '{"service":"rumble"}' // pnpm ops recheck-service --json '{"service":"x"}' @@ -1769,6 +1770,11 @@ export function usage() { " suspended account's answers are thinned; every other X job logs it.", " get x-session and /cookies show it as the account's alert. Nothing is", " asked of X. Answers {account: {state, note?, at, by}}.", + ' {"clearStop": true, "confirm": true, "note"?} is "Clear the X stop": the', + " one way X's 15-minute stop after a rate limit or a bot check ends early", + " (a clean answer or clear-platform-hold never ends it). Without", + ' "confirm" it clears nothing and answers 409 with what it risks; each', + " clear is logged in .jobs/x-stop-cleared.jsonl.", 'rerun-service-jobs retries every job a service\'s cookie alert stopped, once', ' it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them.', "",