commit 772085506b06929e347b1bf7ddc6ec58f8f141fc
parent 31635550b52746ca7c60e31f93d438edd440f090
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 23 Oct 2026 11:09:30 -0400
pacing guard: e2e -- the X refusals, challenge and banner (cookie-alerts.spec), the job gap on /jobs (pacing.spec), no unqueued Sync (queues.spec); built-ins off on the test server; SETTINGS/ENVIRONMENT regenerated
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
14 files changed, 216 insertions(+), 45 deletions(-)
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -236,6 +236,8 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one
| `E2E_AUDIO_CHECK_RECOVER_AFTER` | the real count | Likewise, the recovery count. | common/ytdlp/audioCheckedDownload.ts |
| `E2E_BACKOFF_BASE_MS` | `60000` (the real base) | The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse. | common/jobs/platformBackoff.ts |
| `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts |
+| `E2E_JOB_GAP_SECONDS` | the built-in gaps (20 s; X 300, forums and Bluesky 60) | Replaces every BUILT-IN `pacing.jobGapSeconds` gap (plans/pacing-guard.md); a gap set in settings.json still applies. The editor's e2e server sets 0, so two fake fetches on one platform queue do not wait; pacing.spec sets its own. | common/jobs/queueGap.ts |
+| `E2E_X_MAX_COOKIE_AGE_MINUTES` | the built-in 60 | Replaces the BUILT-IN `social.x.maxCookieAgeMinutes` (the fresh-jar rule for X jobs); a limit set in settings.json still applies. The editor's e2e server sets 0, so a fake X fetch needs no jar; x-session.spec sets its own. | common/jobs/networkGuard.ts |
| `E2E_ODYSEE_PAGE_FIXTURE` | unset (a headless browser) | A JSON file of recorded Odysee page reads keyed by page URL (`"*"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`). | common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts |
| `E2E_UMTOOL_ORIGIN_FILE` | unset (UMTOOL_URL) | A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored. | common/lib/umtoolUrl.ts |
| `E2E_WAYBACK_ORIGIN_FILE` | unset (the real Wayback Machine) | A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index, Save Page Now) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored. | common/lib/waybackClient.ts |
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -169,7 +169,7 @@ Default: `"when-required"`
## `social`
-Per-platform settings of the social posts: X's two, both chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`) and where X posts may appear (`social.x.visibility`) — 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 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.
#### `social`
@@ -184,6 +184,7 @@ Per-platform settings of the social posts: X's two, both chosen in the X account
|---|---|---|
| `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 /settings, 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. |
#### `social.xenforo`
@@ -219,6 +220,7 @@ How the download pace adapts to rate limits, per platform (release 17). Every yt
| `decayAfterCleanUnits` | `5` | How many clean auto-download units on a platform halve its pace one step back toward the fixed value. Clamped 1–1000; default 5. |
| `holdAfterFailsAtCap` | `3` | How many consecutive failures AT the 30-minute cooldown cap put a platform in a hold: the lane then runs one probe unit per holdProbeMinutes instead of one per cooldown, and a manual Sync or download on it is refused with the next probe's time. A clean probe clears the hold and the backoff. Clamped 1–100; default 3. |
| `holdProbeMinutes` | `60` | Minutes between probes while a platform is held. Clamped 1–1440; default 60. |
+| `jobGapSeconds` | `{}` | THE GAP BETWEEN TWO JOBS ON ONE PLATFORM QUEUE, in seconds, keyed by platform (the `<p>` of a `platform:<p>` queue — `twitter`, `youtube`, `megaphone.fm` …) or `default`. A job that sends requests to a platform (a kind declaring `network` in common/jobs/jobKinds.ts) does not start until this long after the previous such job on its queue ended; while it waits its log and its /jobs row say so ("waiting 4m12s: X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)"). The last end per queue survives a restart (`.jobs/queue-gaps.json`). Built in, for a key not set here: default 20, twitter 300, xenforo 60, bluesky 60 — only the keys set here are stored. 0 for a key: no gap on that platform. At most 86400. Set on /settings beside the download sleep. common/jobs/queueGap.ts. |
Default:
@@ -227,7 +229,8 @@ Default:
"sleepRequestsCapSeconds": 16,
"decayAfterCleanUnits": 5,
"holdAfterFailsAtCap": 3,
- "holdProbeMinutes": 60
+ "holdProbeMinutes": 60,
+ "jobGapSeconds": {}
}
```
diff --git a/common/jobs/networkGuard.ts b/common/jobs/networkGuard.ts
@@ -135,6 +135,16 @@ export function xJarVerdict(input: {
return { ok: true };
}
+// TEST-ONLY: E2E_X_MAX_COOKIE_AGE_MINUTES replaces the BUILT-IN limit (the e2e
+// server sets 0, so its fake X fetches need no jar); a limit a spec writes into
+// settings.json still applies. Unset everywhere but the e2e test server.
+function e2eDefaultMaxAge(): number | undefined {
+ const raw = process.env.E2E_X_MAX_COOKIE_AGE_MINUTES;
+ if (raw === undefined || raw === "") return undefined;
+ const n = Number(raw);
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : undefined;
+}
+
function settingsNow(): SiteSettings | null {
try {
return getSettings();
@@ -184,7 +194,7 @@ export async function xJobGuard(opts: {
const verdict = xJarVerdict({
source: resolved.source,
status,
- maxAgeMinutes: xMaxCookieAgeMinutes(settings.social?.x),
+ maxAgeMinutes: settings.social?.x?.maxCookieAgeMinutes ?? e2eDefaultMaxAge() ?? xMaxCookieAgeMinutes(settings.social?.x),
now,
});
return verdict.ok ? verdict : { ok: false, message: verdict.message, alert: false };
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -233,6 +233,8 @@ const DECLARED: EnvVarDecl[] = [
{ name: "E2E_AUDIO_CHECK_RECOVER_AFTER", audience: "test", default: "the real count", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "Likewise, the recovery count." },
{ name: "E2E_BACKOFF_BASE_MS", audience: "test", default: "`60000` (the real base)", readBy: "common/jobs/platformBackoff.ts", doc: "The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse." },
{ name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts", doc: "The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." },
+ { name: "E2E_JOB_GAP_SECONDS", audience: "test", default: "the built-in gaps (20 s; X 300, forums and Bluesky 60)", readBy: "common/jobs/queueGap.ts", doc: "Replaces every BUILT-IN `pacing.jobGapSeconds` gap (plans/pacing-guard.md); a gap set in settings.json still applies. The editor's e2e server sets 0, so two fake fetches on one platform queue do not wait; pacing.spec sets its own." },
+ { name: "E2E_X_MAX_COOKIE_AGE_MINUTES", audience: "test", default: "the built-in 60", readBy: "common/jobs/networkGuard.ts", doc: "Replaces the BUILT-IN `social.x.maxCookieAgeMinutes` (the fresh-jar rule for X jobs); a limit set in settings.json still applies. The editor's e2e server sets 0, so a fake X fetch needs no jar; x-session.spec sets its own." },
{ name: "E2E_ODYSEE_PAGE_FIXTURE", audience: "test", default: "unset (a headless browser)", readBy: "common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts", doc: "A JSON file of recorded Odysee page reads keyed by page URL (`\"*\"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`)." },
{ name: "E2E_UMTOOL_ORIGIN_FILE", audience: "test", default: "unset (UMTOOL_URL)", readBy: "common/lib/umtoolUrl.ts", doc: "A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored." },
{ name: "E2E_WAYBACK_ORIGIN_FILE", audience: "test", default: "unset (the real Wayback Machine)", readBy: "common/lib/waybackClient.ts", doc: "A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index, Save Page Now) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored." },
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -1818,7 +1818,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 two, both chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`) and where X posts may appear (`social.x.visibility`) — 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 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.",
),
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/editor/app/api/test/invalidate-cache/route.ts b/editor/app/api/test/invalidate-cache/route.ts
@@ -133,6 +133,12 @@ function invalidate() {
// object.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).__yttAutoQueueStatusMemo__ = undefined;
+ // And the platform queues' last-end memory (jobs/queueGap.ts): a spec that
+ // sets a job gap must not make the next spec's first job on that queue wait
+ // for the previous spec's last one. Dropped through its global, like the
+ // memo above.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (globalThis as any).__yttQueueGaps__ = undefined;
revalidatePath("/", "layout");
return NextResponse.json({ ok: true });
}
diff --git a/editor/app/jobs/components/JobRow.tsx b/editor/app/jobs/components/JobRow.tsx
@@ -131,6 +131,23 @@ function cancelReasonOf(job: JobRowView): string | undefined {
return job.status === "cancelled" ? job.cancelReason : undefined;
}
+// A network job waiting out its platform queue's gap (jobs/queueGap.ts):
+// "waiting 4m12s: X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)".
+// Counted from the poll's payload.
+function PacedLine({ job, compact }: { job: JobRowView; compact?: boolean }) {
+ if (!job.paced) return null;
+ return (
+ <span
+ data-testid="job-paced"
+ className={compact ? "min-w-0 truncate text-xs text-muted-foreground" : "self-start text-xs text-muted-foreground"}
+ title={job.paced.reason}
+ suppressHydrationWarning
+ >
+ waiting {waitText(job.paced.until - Date.now())}: {job.paced.reason}
+ </span>
+ );
+}
+
function CancelReason({ job, inline }: { job: JobRowView; inline?: boolean }) {
const reason = cancelReasonOf(job);
if (!reason) return null;
@@ -304,18 +321,7 @@ function JobRowHeading({
{job.background && " · waiting behind a manual job"}
</span>
)}
- {job.paced && (
- // A network job waiting out its platform queue's gap
- // (jobs/queueGap.ts). Counted from the poll's payload.
- <span
- data-testid="job-paced"
- className={compact ? "min-w-0 truncate text-xs text-muted-foreground" : "text-xs text-muted-foreground"}
- title={job.paced.reason}
- suppressHydrationWarning
- >
- waiting {waitText(job.paced.until - Date.now())}: {job.paced.reason}
- </span>
- )}
+ <PacedLine job={job} compact={compact} />
{/* Its counterpart for a cancelled job: why. Compact rows carry it as
the pill's title instead — they are one line, always. */}
{!compact && <CancelReason job={job} inline />}
@@ -555,6 +561,7 @@ function TableRow({
{j.status}
</span>
<CancelReason job={j} />
+ <PacedLine job={j} />
{j.stuck && (
<span
data-stuck={j.stuck.reason}
diff --git a/editor/e2e/cookie-alerts.spec.ts b/editor/e2e/cookie-alerts.spec.ts
@@ -10,7 +10,7 @@
//
// Same token as /api/ops/* (WORKER_TOKEN=test-worker-token on the test server).
-import { readFile, writeFile } from "node:fs/promises";
+import { mkdir, readFile, utimes, writeFile } from "node:fs/promises";
import { test, expect, type APIRequestContext } from "@playwright/test";
import { resetData, resolvePath, testPaths, writeSettings } from "./helpers";
import { baseUrl } from "./baseUrl";
@@ -134,3 +134,102 @@ test("ops: get services is behind the token; recheck-service refuses a name that
});
expect(await dismiss.json()).toMatchObject({ ok: true, message: "YouTube had no cookie alert to dismiss." });
});
+
+// ── X (plans/pacing-guard.md) ─────────────────────────────────────────────
+//
+// The 2026-10-23 case: fetch-posts for 13 X accounts in one loop, a 16-day-old
+// cookie jar, X answering with a Cloudflare challenge that gallery-dl printed
+// as a WARNING and exited 0 on. Now the jar's age refuses the fetch, the
+// challenge fails the job and raises the X alert, and every X job is refused
+// while it is up. The fake gallery-dl answers `challenged_user` with the
+// challenge; the jar is written by hand (no X, no browser). The test server
+// turns the built-in age limit off (E2E_X_MAX_COOKIE_AGE_MINUTES=0), so this
+// spec sets its own.
+
+async function xChannel(slug: string, handle: string): Promise<void> {
+ const dir = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`);
+ await mkdir(dir, { recursive: true });
+ await writeFile(
+ `${dir}/config.json`,
+ JSON.stringify({
+ name: `${handle} (X)`,
+ handling: "transcribe",
+ sourceKind: "social",
+ postFetcher: "x-gallery-dl",
+ platform: "twitter",
+ socialHandle: handle,
+ url: `https://x.com/${handle}`,
+ }),
+ );
+}
+
+async function xJar(ageMs: number): Promise<void> {
+ const dir = resolvePath(`${testPaths().transcriptsDir}/.x-session`);
+ await mkdir(`${dir}/profile`, { recursive: true });
+ await writeFile(`${dir}/cookies.txt`, "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tfake\n");
+ const t = new Date(Date.now() - ageMs);
+ await utimes(`${dir}/cookies.txt`, t, t);
+}
+
+async function fetchPosts(request: APIRequestContext, slug: string, extra: Record<string, unknown> = {}) {
+ const res = await request.post(`${baseUrl}/api/ops/fetch-posts`, { headers: AUTH, data: { slug, ...extra } });
+ return { status: res.status(), body: (await res.json()) as { ok: boolean; jobId?: string; error?: string } };
+}
+
+test("X: a stale jar refuses Fetch posts; \"\" is refused; a challenge fails the job, raises the X banner and refuses the next fetch; Recheck asks X nothing", async ({
+ page,
+ request,
+}) => {
+ test.setTimeout(120_000);
+ await writeSettings({ minFreeDiskGB: 0, social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 60 } } });
+ await xChannel("x-challenged", "challenged_user");
+ await xChannel("x-other", "faketester");
+
+ // A 16-day-old jar: refused before any job exists.
+ await xJar(16 * 24 * 60 * 60_000);
+ const stale = await fetchPosts(request, "x-other");
+ expect(stale.status).toBe(400);
+ expect(stale.body.error).toBe(
+ "X cookies were last refreshed 16 days ago (limit 60 min): press Refresh cookies (or Connect X account) on /settings, then fetch again.",
+ );
+
+ // A fresh jar; an unqueued fetch is still refused.
+ await xJar(60_000);
+ const unqueued = await fetchPosts(request, "x-other", { queueKey: "" });
+ expect(unqueued.status).toBe(400);
+ expect(unqueued.body.error).toMatch(/never runs unqueued: the queue override "" \(immediate\) is refused/);
+
+ // X answers with a challenge (a warning, exit 0): the job FAILS.
+ const challenged = await fetchPosts(request, "x-challenged");
+ expect(challenged.body.ok).toBe(true);
+ expect(await waitJob(request, challenged.body.jobId!)).toBe("failed");
+ const log = await readFile(resolvePath(`${testPaths().transcriptsDir}/.jobs/${challenged.body.jobId}.log`), "utf8");
+ expect(log).toContain("[twitter][warning] Cloudflare challenge");
+ expect(log).toMatch(/X answered with a challenge or a login wall/);
+
+ // The next X fetch is refused with the alert's sentence.
+ const after = await fetchPosts(request, "x-other");
+ expect(after.status).toBe(400);
+ expect(after.body.error).toMatch(/^X answered with a challenge at \d\d:\d\d UTC .*its cookie alert is up, so no X job starts/);
+
+ // The banner.
+ await page.goto(`${baseUrl}/`);
+ const banner = page.getByRole("alert", { name: "X cookies" });
+ await expect(banner).toContainText("X needs fresh cookies: pass X's check by hand");
+ await expect(banner).toHaveAttribute("data-state", "stale");
+
+ // Recheck before the jar is refreshed: stale, and no request was made.
+ await banner.getByRole("button", { name: "Recheck" }).click();
+ await expect(page.getByRole("status", { name: "X cookies result" })).toContainText("Recheck sends X no request", {
+ timeout: 30_000,
+ });
+ await expect(banner).toHaveAttribute("data-state", "stale");
+
+ // The operator refreshes the jar (Refresh cookies on /settings); Recheck clears it.
+ await xJar(0);
+ await banner.getByRole("button", { name: "Recheck" }).click();
+ await expect(banner).toHaveAttribute("data-state", "ok-again", { timeout: 30_000 });
+ const ok = await fetchPosts(request, "x-other");
+ expect(ok.body.ok).toBe(true);
+ expect(await waitJob(request, ok.body.jobId!)).toBe("done");
+});
diff --git a/editor/e2e/fixtures/bin/fake-gallery-dl.mjs b/editor/e2e/fixtures/bin/fake-gallery-dl.mjs
@@ -30,6 +30,14 @@ if (rangeIdx >= 0 && args[rangeIdx + 1]) {
if (m) limit = Number(m[1]);
}
+// X'S ANSWER ON 2026-10-23 (plans/pacing-guard.md): a Cloudflare challenge
+// as a WARNING, exit 0, nothing read — for the account `challenged_user`, so a
+// spec picks it by the channel's URL (cookie-alerts.spec).
+if (handle === "challenged_user") {
+ process.stderr.write("[twitter][warning] Cloudflare challenge\n");
+ process.exit(0);
+}
+
// Mirror the real failure the Needs-cookies bucket models: when the fixture is
// asked to simulate an expired session, exit non-zero with an auth-shaped
// message on stderr.
diff --git a/editor/e2e/pacing.spec.ts b/editor/e2e/pacing.spec.ts
@@ -1,4 +1,4 @@
-import { mkdir, writeFile } from "node:fs/promises";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
import { test, expect } from "@playwright/test";
import { readJson, resetData, resolvePath, writeSettings, testPaths } from "./helpers";
import { baseUrl } from "./baseUrl";
@@ -231,3 +231,37 @@ test("a live 429 backs youtube off, defers the video, and the next pick is the n
.toContain("a2");
expect(pickOrder(await getStatus(request))).toEqual(["wp429vid1", "a2"]);
});
+
+// THE GAP BETWEEN TWO JOBS ON ONE PLATFORM QUEUE (plans/pacing-guard.md). The
+// test server turns the built-in gaps off (E2E_JOB_GAP_SECONDS=0); this spec
+// sets YouTube's to 6 s. Two download-missing jobs on platform:youtube: the
+// second waits, its /jobs row says so while it does, and its log keeps the line.
+test("a second job on platform:youtube waits pacing.jobGapSeconds after the first ended, and says so", async ({
+ page,
+ request,
+}) => {
+ test.setTimeout(60_000);
+ await resetData("empty");
+ await writeSettings({ minFreeDiskGB: 0, sleepBetweenDownloadsSeconds: 0, pacing: { jobGapSeconds: { youtube: 6 } } });
+ await makeDownloadChannel("gap-chan", []);
+ const AUTH = { authorization: "Bearer test-worker-token" };
+ const start = async () => {
+ const res = await request.post(`${baseUrl}/api/ops/download-missing`, { headers: AUTH, data: { slug: "gap-chan" } });
+ expect(res.status()).toBe(200);
+ return ((await res.json()) as { jobId: string }).jobId;
+ };
+ const status = async (id: string) =>
+ ((await (await request.get(`${baseUrl}/api/ops/job/${id}`, { headers: AUTH })).json()) as { job?: { status?: string } })
+ .job?.status ?? "";
+ const first = await start();
+ await expect.poll(() => status(first), { timeout: 20_000 }).toBe("done");
+ const second = await start();
+ await page.goto(`${baseUrl}/jobs`);
+ await expect(page.getByTestId("job-paced").first()).toContainText(
+ "YouTube jobs are spaced 6 s apart (pacing.jobGapSeconds.youtube)",
+ { timeout: 10_000 },
+ );
+ await expect.poll(() => status(second), { timeout: 30_000 }).toBe("done");
+ const log = await readFile(resolvePath(`${testPaths().transcriptsDir}/.jobs/${second}.log`), "utf8");
+ expect(log).toMatch(/waiting \ds: YouTube jobs are spaced 6 s apart \(pacing\.jobGapSeconds\.youtube\)/);
+});
diff --git a/editor/e2e/queues.spec.ts b/editor/e2e/queues.spec.ts
@@ -205,37 +205,25 @@ test("cancels a queued job without disturbing the one running ahead of it", asyn
await expect(slowARow.getByText("running", { exact: true })).toBeVisible();
});
-test("empty queue runs immediately even when another job is queued in the same name", async ({
+// A NETWORK JOB IS NEVER RUN UNQUEUED (plans/pacing-guard.md, 2026-10-23).
+// "(immediate)" — queue "" — used to run a Sync at once beside everything,
+// outside its platform's queue and gap; it is no longer offered on an action
+// whose default is a platform queue, and typed by hand it is refused before
+// any job exists.
+test("a Sync is never run unqueued: no (immediate) option, and an empty custom queue is refused", async ({
page,
}) => {
await resetData("two-slow-channels");
-
- // Park slow-a's Sync into qShared and start it.
- await generateReport(page, "slow-a");
- await page.goto(channelStage("slow-a", "playlist"));
- await setQueueViaCustom(page, "Sync", "qShared");
- await page.getByRole("button", { name: "Sync" }).click();
- await expect(page.getByLabel("Sync output")).toContainText("test-slow", {
- timeout: 15_000,
- });
-
- // slow-b sets queue to immediate (the default empty option) and starts;
- // it should bypass qShared and run right away.
await generateReport(page, "slow-b");
await page.goto(channelStage("slow-b", "playlist"));
- await page
- .getByLabel("queue for Sync", { exact: true })
- .selectOption({ label: "(immediate)" });
+ const picker = page.getByLabel("queue for Sync", { exact: true });
+ await expect(picker.locator("option", { hasText: "(immediate)" })).toHaveCount(0);
+ await setQueueViaCustom(page, "Sync", "");
await page.getByRole("button", { name: "Sync" }).click();
- // No "queued" banner: it goes straight to running and produces output.
- await expect(page.getByLabel("Sync output")).toContainText("test-slow", {
- timeout: 15_000,
- });
-
+ await expect(page.getByLabel("Sync error")).toContainText(
+ 'never runs unqueued: the queue override "" (immediate) is refused',
+ { timeout: 10_000 },
+ );
await page.goto("/jobs");
- const slowARow = page.getByRole("row").filter({ hasText: "slow-a" }).first();
- const slowBRow = page.getByRole("row").filter({ hasText: "slow-b" }).first();
- await expect(slowARow.getByText("running", { exact: true })).toBeVisible();
- await expect(slowBRow.getByText("running", { exact: true })).toBeVisible();
- await expect(slowBRow).toContainText("(immediate)");
+ await expect(page.getByRole("row").filter({ hasText: "slow-b" })).toHaveCount(0);
});
diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts
@@ -40,6 +40,13 @@ export const E2E_SERVER_ENV: Record<string, string> = {
E2E_AUDIO_CHECK_RECOVER_AFTER: "2",
E2E_BACKOFF_BASE_MS: "20000",
E2E_CLIP_WINDOW_GAP_MS: "2000",
+ // The pacing guard's BUILT-IN defaults (plans/pacing-guard.md) are off on
+ // the test server — a spec's two fake X fetches would otherwise sit five
+ // minutes apart, and every fake X fetch would need a fresh jar. A spec that
+ // sets pacing.jobGapSeconds or social.x.maxCookieAgeMinutes in settings.json
+ // gets exactly that (pacing.spec, x-session.spec).
+ E2E_JOB_GAP_SECONDS: "0",
+ E2E_X_MAX_COOKIE_AGE_MINUTES: "0",
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
@@ -30,6 +30,10 @@ import { currentSlot } from "./e2e/testPaths";
// batch (30–45 s in production; 2 s here), so
// fetch-window.spec sees the one it owes
// (common/controller/fetchWindows.ts)
+// E2E_JOB_GAP_SECONDS, 0: the pacing guard's BUILT-IN job gap and X
+// 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
// 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/settings.json.example b/settings.json.example
@@ -13,7 +13,8 @@
"sleepRequestsCapSeconds": 16,
"decayAfterCleanUnits": 5,
"holdAfterFailsAtCap": 3,
- "holdProbeMinutes": 60
+ "holdProbeMinutes": 60,
+ "jobGapSeconds": {}
},
"downloadFormat": "auto",
"sourceVideoQuality": "original",