Archilyzer · Source

archilyzer

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

commit 31635550b52746ca7c60e31f93d438edd440f090
parent 9a947558e14bcb5f54d949445fad6aaccfb6aebc
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 23 Oct 2026 11:03:15 -0400

pacing guard: a probe is a request -- a declined video whose prefetch ran waits the gap; a podcast feed's titles settle filtered episodes before any probe

download-missing on a feed channel (megaphone.fm, 2026-10-23) probed ~1,150
episodes back to back: release 9 B2 let a video declined after only its
metadata prefetch skip the between-downloads gap. Now only an outcome that
asked nothing skips it. To keep the cost down, a channel with a download
filter whose playlist is a feed's enclosures reads its feed once and writes
each episode's title into the metadata-scan store, so the settled set
declines a filtered episode with no request (controller/feedTitlePrefilter.ts).

The /settings form edits pacing.jobGapSeconds (default, X, forums, Bluesky);
the X account section edits social.x.maxCookieAgeMinutes. QueueControl no
longer offers (immediate) on an action whose default is a platform queue.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Acommon/controller/feedTitlePrefilter.test.ts | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/feedTitlePrefilter.ts | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/queueGap.ts | 7++-----
Acommon/lib/jobGap.ts | 43+++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/settingsSchema.ts | 40++--------------------------------------
Mcommon/ytdlp/managedDownloadsSleep.test.ts | 15+++++++++++----
Mcommon/ytdlp/runYtdlp.ts | 38+++++++++++++++++++++++++++++++-------
Meditor/app/components/QueueControl.tsx | 10++++++++--
Meditor/app/settings/actions.ts | 38++++++++++++++++++++++++++++++++++++++
Meditor/app/settings/components/SettingsForm.tsx | 37+++++++++++++++++++++++++++++++++++++
Meditor/app/settings/components/XSessionSection.tsx | 47+++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/settings/page.tsx | 2++
Meditor/app/settings/xSessionActions.ts | 27+++++++++++++++++++++++++++
13 files changed, 403 insertions(+), 56 deletions(-)

diff --git a/common/controller/feedTitlePrefilter.test.ts b/common/controller/feedTitlePrefilter.test.ts @@ -0,0 +1,66 @@ +// A podcast feed channel's titles before any probe (plans/pacing-guard.md). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/feedTitlePrefilter.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, mkdir } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { looksLikeFeedChannel, seedFeedTitles } from "./feedTitlePrefilter"; +import { loadMetadataScan, settledByTitleFilterIds } from "./metadataScanStore"; +import { extractVideoId } from "../lib/videoId"; + +const FEED = `<?xml version="1.0"?><rss><channel><title>Show</title> +<item><title>Episode 1: the topic</title><pubDate>Tue, 21 Oct 2026 10:00:00 GMT</pubDate> +<enclosure url="https://cdn.example.fm/ep1.mp3" type="audio/mpeg"/></item> +<item><title>Episode 2: something else</title><pubDate>Wed, 22 Oct 2026 10:00:00 GMT</pubDate> +<enclosure url="https://cdn.example.fm/ep2.mp3" type="audio/mpeg"/></item> +</channel></rss>`; + +const CONFIG = { + url: "https://feeds.example.fm/show", + downloadFilter: { include: "topic" }, +} as const; +const URLS = ["https://cdn.example.fm/ep1.mp3", "https://cdn.example.fm/ep2.mp3"]; + +test("which channels are read as a feed", () => { + assert.equal(looksLikeFeedChannel(CONFIG as never, URLS), true); + assert.equal(looksLikeFeedChannel({ url: CONFIG.url } as never, URLS), false, "no filter: nothing to settle"); + assert.equal( + looksLikeFeedChannel({ ...CONFIG, url: "https://www.youtube.com/@x" } as never, URLS), + false, + "a known platform is not a feed", + ); + assert.equal(looksLikeFeedChannel(CONFIG as never, ["https://example.fm/page/1", "https://example.fm/page/2"]), false); +}); + +test("one feed read titles the unscanned episodes; the filter then settles the unwanted one with no probe", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "feed-titles-")); + const paths = { channelsDir: path.join(root, "channels") } as Paths; + await mkdir(path.join(paths.channelsDir, "show"), { recursive: true }); + let reads = 0; + const lines: string[] = []; + const n = await seedFeedTitles({ + paths, + slug: "show", + config: CONFIG as never, + playlistUrls: URLS, + onLog: (l) => lines.push(l), + fetchFeed: async () => { + reads++; + return FEED; + }, + }); + assert.equal(reads, 1); + assert.equal(n, 2); + const scan = await loadMetadataScan(paths, "show"); + const ep2 = extractVideoId(URLS[1])!; + assert.equal(scan.entries[ep2]?.title, "Episode 2: something else"); + const settled = await settledByTitleFilterIds(paths, "show", CONFIG as never); + assert.deepEqual([...settled], [ep2]); + // Everything known: no second read. + await seedFeedTitles({ paths, slug: "show", config: CONFIG as never, playlistUrls: URLS, onLog: () => {}, fetchFeed: async () => { reads++; return FEED; } }); + assert.equal(reads, 1); +}); diff --git a/common/controller/feedTitlePrefilter.ts b/common/controller/feedTitlePrefilter.ts @@ -0,0 +1,89 @@ +// A PODCAST FEED CHANNEL'S TITLES, BEFORE ANY PROBE (plans/pacing-guard.md). +// +// A download-missing on a feed channel with a title filter (megaphone.fm, +// 2026-10-23) probed every listed episode with yt-dlp, ~1,150 of them back to +// back, only to learn each one's title and decline it. The feed already says +// every title. So, once per run and only where it can pay: ONE request for the +// channel's feed, each item's title, description and date written into the +// channel's metadata-scan store under the id its enclosure URL gives +// (`extractVideoId`, as the playlist's URLs are read) — and the batch's +// `settledByTitleFilterIds` then settles every filtered episode with no request +// at all. +// +// WHEN. The channel has a download filter, its platform is not one this app +// knows (a known platform's listing is not a feed), and the playlist's URLs +// are mostly direct media files (an RSS feed's enclosures). An item already in +// the store is left as it is: a probe's answer beats the feed's. +// +// Best effort: a feed that does not answer, or is not RSS, costs the run +// nothing but its log line. + +import { detectPlatform } from "../lib/platform"; +import { extractVideoId } from "../lib/videoId"; +import { compileDownloadFilter } from "../lib/downloadFilters"; +import { feedDateToUploadDate, parseRssFeed } from "../lib/rssFeed"; +import type { ChannelConfig } from "../lib/channelConfig"; +import type { Paths } from "../lib/paths"; +import { loadMetadataScan, upsertMetadataScan, type MetadataScanEntry } from "./metadataScanStore"; +import type { FetchFeed } from "./feedMetadataBackfill"; + +const MEDIA_FILE = /\.(mp3|m4a|m4b|aac|ogg|oga|opus|wav|flac|mp4|m4v)(?:$|[?#])/i; + +// Does this channel look like a podcast feed whose titles are worth one read? +export function looksLikeFeedChannel( + config: Pick<ChannelConfig, "url" | "platform" | "downloadFilter">, + playlistUrls: readonly string[], +): boolean { + if (!compileDownloadFilter(config.downloadFilter)) return false; + if (!config.url || !/^https?:\/\//i.test(config.url)) return false; + if (config.platform || detectPlatform(config.url)) return false; + if (playlistUrls.length === 0) return false; + const media = playlistUrls.filter((u) => MEDIA_FILE.test(u)).length; + return media * 2 >= playlistUrls.length; +} + +export async function seedFeedTitles(opts: { + paths: Paths; + slug: string; + config: Pick<ChannelConfig, "url" | "platform" | "downloadFilter">; + playlistUrls: readonly string[]; + onLog: (line: string) => void; + signal?: AbortSignal; + fetchFeed?: FetchFeed; + now?: string; +}): Promise<number> { + if (!looksLikeFeedChannel(opts.config, opts.playlistUrls)) return 0; + const wanted = new Set(opts.playlistUrls.map((u) => extractVideoId(u)).filter((id): id is string => Boolean(id))); + const scan = await loadMetadataScan(opts.paths, opts.slug); + const missing = [...wanted].filter((id) => !scan.entries[id]); + if (missing.length === 0) return 0; + let xml: string; + try { + opts.onLog(`Feed titles: reading the channel's feed once (${opts.config.url}) so filtered episodes cost no probe.\n`); + const fetchFeed = opts.fetchFeed ?? (await import("./feedMetadataBackfill")).fetchFeedText; + xml = await fetchFeed(opts.config.url!, opts.signal); + } catch (err) { + opts.onLog(`Feed titles: the feed could not be read (${(err as Error).message}); each episode is probed instead.\n`); + return 0; + } + const feed = parseRssFeed(xml); + const scannedAt = opts.now ?? new Date().toISOString(); + const entries: Record<string, MetadataScanEntry> = {}; + const missingSet = new Set(missing); + for (const item of feed.items) { + if (!item.enclosureUrl || !item.title) continue; + const id = extractVideoId(item.enclosureUrl); + if (!id || !missingSet.has(id) || entries[id]) continue; + entries[id] = { + title: item.title, + description: item.description ?? "", + uploadDate: feedDateToUploadDate(item.pubDate) ?? "", + ...(item.durationSeconds ? { duration: item.durationSeconds } : {}), + scannedAt, + }; + } + const n = Object.keys(entries).length; + if (n > 0) await upsertMetadataScan(opts.paths, opts.slug, { entries }, scannedAt); + opts.onLog(`Feed titles: ${n} of ${missing.length} unscanned episode(s) titled from the feed (${feed.items.length} item(s)).\n`); + return n; +} diff --git a/common/jobs/queueGap.ts b/common/jobs/queueGap.ts @@ -28,11 +28,8 @@ import path from "node:path"; import type { Paths } from "../lib/paths"; import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; import { spanText, waitText } from "./queueGapText"; -import { - JOB_GAP_DEFAULT_SECONDS, - jobGapSecondsFor, - type PacingSettingsBlock, -} from "../lib/settingsSchema"; +import { JOB_GAP_DEFAULT_SECONDS, jobGapSecondsFor } from "../lib/jobGap"; +import type { PacingSettingsBlock } from "../lib/settingsSchema"; export { spanText, waitText }; diff --git a/common/lib/jobGap.ts b/common/lib/jobGap.ts @@ -0,0 +1,43 @@ +// THE GAP BETWEEN TWO JOBS ON ONE PLATFORM QUEUE — `pacing.jobGapSeconds` +// (plans/pacing-guard.md). Pure and client-safe: the settings schema +// sanitizes with it, the job funnel (jobs/queueGap.ts) waits by it, and the +// /settings form shows the gaps in force. + +// The built-in gaps: every platform queue waits `default` seconds after the +// previous network job on it ended; X five minutes, a forum and Bluesky one. +export const JOB_GAP_DEFAULT_SECONDS: Readonly<Record<string, number>> = Object.freeze({ + default: 20, + twitter: 300, + xenforo: 60, + bluesky: 60, +}); +export const JOB_GAP_MAX_SECONDS = 24 * 60 * 60; + +export function sanitizeJobGapSeconds(v: unknown): Partial<Record<string, number>> { + const out: Partial<Record<string, number>> = {}; + if (!v || typeof v !== "object" || Array.isArray(v)) return out; + for (const [k, raw] of Object.entries(v as Record<string, unknown>)) { + if (!/^[a-z0-9][a-z0-9.-]{0,99}$/.test(k)) continue; + if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0) continue; + out[k] = Math.min(JOB_GAP_MAX_SECONDS, Math.floor(raw)); + } + return out; +} + +// The gap (seconds) a job on `platform`'s queue waits after the previous one +// ended: the operator's value for the platform, else the built-in one for it, +// else the operator's `default`, else the built-in default. `builtIn` lets the +// e2e server shrink the BUILT-IN values (E2E_JOB_GAP_SECONDS) while a value a +// spec sets explicitly still applies. +export function jobGapSecondsFor( + pacing: { jobGapSeconds?: Partial<Record<string, number>> } | undefined, + platform: string, + builtIn: Readonly<Record<string, number>> = JOB_GAP_DEFAULT_SECONDS, +): { seconds: number; key: string } { + const set = pacing?.jobGapSeconds ?? {}; + if (set[platform] !== undefined) return { seconds: set[platform]!, key: platform }; + if (builtIn[platform] !== undefined) return { seconds: builtIn[platform]!, key: platform }; + if (set.default !== undefined) return { seconds: set.default, key: "default" }; + return { seconds: builtIn.default ?? JOB_GAP_DEFAULT_SECONDS.default, key: "default" }; +} + diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -129,6 +129,8 @@ import { export type { Worker } from "./workers"; export type { SocialSettings, XSocialSettings, XenforoSocialSettings } from "../social/xCookieSource"; +import { sanitizeJobGapSeconds } from "./jobGap"; +export { JOB_GAP_DEFAULT_SECONDS, JOB_GAP_MAX_SECONDS, jobGapSecondsFor } from "./jobGap"; // The `social` block (release 16 slice XL). The types and the coercion live // with the source they choose, in social/xCookieSource.ts (pure, client-safe); @@ -777,44 +779,6 @@ export type PacingSettingsBlock = { jobGapSeconds: Partial<Record<string, number>>; }; -// The built-in gaps: every platform queue waits `default` seconds after the -// previous network job on it ended; X five minutes, a forum and Bluesky one. -export const JOB_GAP_DEFAULT_SECONDS: Readonly<Record<string, number>> = Object.freeze({ - default: 20, - twitter: 300, - xenforo: 60, - bluesky: 60, -}); -export const JOB_GAP_MAX_SECONDS = 24 * 60 * 60; - -function sanitizeJobGapSeconds(v: unknown): Partial<Record<string, number>> { - const out: Partial<Record<string, number>> = {}; - if (!v || typeof v !== "object" || Array.isArray(v)) return out; - for (const [k, raw] of Object.entries(v as Record<string, unknown>)) { - if (!/^[a-z0-9][a-z0-9.-]{0,99}$/.test(k)) continue; - if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0) continue; - out[k] = Math.min(JOB_GAP_MAX_SECONDS, Math.floor(raw)); - } - return out; -} - -// The gap (seconds) a job on `platform`'s queue waits after the previous one -// ended: the operator's value for the platform, else the built-in one for it, -// else the operator's `default`, else the built-in default. `builtIn` lets the -// e2e server shrink the BUILT-IN values (E2E_JOB_GAP_SECONDS) while a value a -// spec sets explicitly still applies. -export function jobGapSecondsFor( - pacing: Pick<PacingSettingsBlock, "jobGapSeconds"> | undefined, - platform: string, - builtIn: Readonly<Record<string, number>> = JOB_GAP_DEFAULT_SECONDS, -): { seconds: number; key: string } { - const set = pacing?.jobGapSeconds ?? {}; - if (set[platform] !== undefined) return { seconds: set[platform]!, key: platform }; - if (builtIn[platform] !== undefined) return { seconds: builtIn[platform]!, key: platform }; - if (set.default !== undefined) return { seconds: set.default, key: "default" }; - return { seconds: builtIn.default ?? JOB_GAP_DEFAULT_SECONDS.default, key: "default" }; -} - export const PACING_SETTINGS_FIELD_DOCS: FieldDocs<PacingSettingsBlock> = { sleepRequestsCapSeconds: "Ceiling (seconds) on a platform's adaptive `--sleep-requests`. The pace " + diff --git a/common/ytdlp/managedDownloadsSleep.test.ts b/common/ytdlp/managedDownloadsSleep.test.ts @@ -109,9 +109,15 @@ test("a fetched video sleeps before the next one", async () => { assert.equal(await sleepsFor([FETCHED, FETCHED]), 1); }); -test("a video the download filter declined does not sleep", async () => { - assert.equal(await sleepsFor([FILTERED, FETCHED]), 0); - assert.equal(await sleepsFor([FILTERED, FILTERED, FILTERED]), 0); +// A PROBE IS A REQUEST (plans/pacing-guard.md, 2026-10-23): release 9 B2 let +// a declined video skip the gap, and a podcast feed's download-missing probed +// ~1,150 episodes back to back. A declined video whose prefetch ran now waits; +// one that asked nothing (declined from what was already known) does not. +test("a video the download filter declined after a probe sleeps; one that asked nothing does not", async () => { + assert.equal(await sleepsFor([FILTERED, FETCHED]), 1); + assert.equal(await sleepsFor([FILTERED, FILTERED, FILTERED]), 2); + const ASKED_NOTHING = outcome("skipped-filtered", []); + assert.equal(await sleepsFor([ASKED_NOTHING, ASKED_NOTHING, FETCHED]), 0); }); // Release 9 review: a per-video failure KEEPS the pace, even one that never @@ -207,7 +213,8 @@ test("a soft block backs the platform off and stops the batch; a deleted video d test("the last video never sleeps, whatever it was", async () => { assert.equal(await sleepsFor([FETCHED]), 0); - assert.equal(await sleepsFor([FILTERED, FETCHED]), 0); + assert.equal(await sleepsFor([FETCHED, FILTERED]), 1); + assert.equal(await sleepsFor([FILTERED]), 0); }); test("a real fetch that failed still sleeps, per-video or not", async () => { diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts @@ -46,6 +46,7 @@ import { } from "../lib/cookiePolicy"; import { resolveEffectiveAvailability } from "../lib/availability-server"; import { withMetadataHistory } from "../lib/metadataHistory-server"; +import { seedFeedTitles } from "../controller/feedTitlePrefilter"; import { settledByTitleFilterIds, upsertMetadataScan, @@ -878,6 +879,17 @@ async function downloadPlaylistManaged( // (and re-failing) on every batch. A forceCookies run resolves to mode // "always" and so bypasses the defer exclusion. const runCookiePolicy = resolveRunCookiePolicy(opts, effectiveChannelConfig); + // A PODCAST FEED'S TITLES FIRST (plans/pacing-guard.md): one read of the + // feed titles every unscanned episode in the metadata-scan store, so the + // settled set below declines a filtered episode without probing it. + await seedFeedTitles({ + paths: opts.paths, + slug: opts.channelSlug, + config: effectiveChannelConfig, + playlistUrls: tofetch, + onLog: opts.onLog, + signal: opts.signal, + }).catch(() => 0); // ONE read of the channel-level metadata-scan store for the whole batch. const settledByFilter = await settledByTitleFilterIds( opts.paths, @@ -1051,6 +1063,15 @@ export type ManagedDownloadsDeps = { // ("This content isn't available, try again later") reading as `deleted` → // per_video — is gone since release 10: it is `rate_limit` now (isSoftBlock), // backs the platform off and stops the batch. The pace stays anyway. +// A video that asked NOTHING (plans/pacing-guard.md): no attempt at all — the +// filter declined it from what was already known. Only that one skips the gap; +// a declined video whose metadata prefetch ran (a probe) asked the platform and +// waits like any other (2026-10-23: a feed channel's ~1,150 probes ran back to +// back under the release 9 B2 rule below). +export function madeNoRequest(outcome: DownloadOutcomeRecord): boolean { + return outcome.attempts.length === 0; +} + export function declinedWithoutMediaFetch( outcome: DownloadOutcomeRecord, ): boolean { @@ -1271,12 +1292,15 @@ export async function runManagedDownloads( processedCount++; const isLast = processedCount >= urls.length; const willAbortLoop = firstFailure !== null && abortOnError; - // A VIDEO THE FILTER DECLINED DOES NOT PAY FOR A FETCH IT NEVER MADE - // (release 9, B2). On 2026-09-25 paramount-tactical's download-missing - // slept 193 times for 14 archives: every video the download filter - // declined slept 30 s after nothing but its metadata prefetch. Every - // other outcome still sleeps — a real fetch, success or failure, and - // every failure, per-video ones included (see declinedWithoutMediaFetch). + // A PROBE IS A REQUEST (plans/pacing-guard.md, 2026-10-23). Release 9 + // B2 let a video the download filter declined after only its metadata + // prefetch skip the gap (paramount-tactical slept 193 times for 14 + // archives) — and a podcast feed's download-missing then probed ~1,150 + // episodes back to back. Every outcome that asked anything now waits + // the gap; only one that asked nothing (madeNoRequest) does not. The + // cost B2 removed is paid down instead by asking less: the metadata + // scan's settled set and a feed's titles (seedFeedTitles) decline a + // filtered video before any probe. const gapMs = downloadGapMs(sleepSeconds, paceNow(), basePace, { minSeconds: minGap, }); @@ -1285,7 +1309,7 @@ export async function runManagedDownloads( !isLast && !willAbortLoop && !opts.signal.aborted && - !declinedWithoutMediaFetch(outcome) + !madeNoRequest(outcome) ) { opts.onLog(`Sleeping ${gapMs / 1000}s before next download...\n`); await sleep(gapMs, opts.signal); diff --git a/editor/app/components/QueueControl.tsx b/editor/app/components/QueueControl.tsx @@ -10,6 +10,10 @@ type Props = { defaultQueueKey: string; existingQueues: string[]; actionLabel: string; + // Whether "(immediate)" — queue "" — is offered. Absent: not for an action + // whose default is a platform queue, because a job that asks a platform is + // refused unqueued (common/jobs/networkGuard.ts, plans/pacing-guard.md). + allowImmediate?: boolean; }; export function QueueControl({ @@ -18,7 +22,9 @@ export function QueueControl({ defaultQueueKey, existingQueues, actionLabel, + allowImmediate, }: Props) { + const immediate = allowImmediate ?? !defaultQueueKey.startsWith("platform:"); const [editing, setEditing] = useState(false); const [draft, setDraft] = useState(value); @@ -31,7 +37,7 @@ export function QueueControl({ onChange={(e) => setDraft(e.target.value)} aria-label={`custom queue for ${actionLabel}`} autoFocus - placeholder="leave empty for immediate" + placeholder={immediate ? "leave empty for immediate" : "queue name"} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); @@ -95,7 +101,7 @@ export function QueueControl({ }} className="font-mono px-2 py-1 rounded border border-border bg-card text-foreground" > - <option value="">(immediate)</option> + {(immediate || value === "") && <option value="">(immediate)</option>} {named.map((opt) => ( <option key={opt} value={opt}> {opt} diff --git a/editor/app/settings/actions.ts b/editor/app/settings/actions.ts @@ -30,6 +30,38 @@ import { isSourceVideoQuality, } from "yt-dlp-transcript-common/ytdlp/downloadFormat"; import { formValues, type FormState } from "../lib/formState"; +import { + JOB_GAP_DEFAULT_SECONDS, + JOB_GAP_MAX_SECONDS, +} from "yt-dlp-transcript-common/lib/jobGap"; + +// The job-gap fields (SettingsForm's JOB_GAP_FIELDS): a value equal to the +// built-in is NOT stored, so a later change to a built-in reaches this +// install; every other key already set is kept. +const JOB_GAP_FORM_KEYS = ["default", "twitter", "xenforo", "bluesky"] as const; + +function parseJobGaps( + formData: FormData, + current: Partial<Record<string, number>>, +): { ok: true; gaps: Partial<Record<string, number>> } | { ok: false; error: string } { + const gaps: Partial<Record<string, number>> = { ...current }; + for (const key of JOB_GAP_FORM_KEYS) { + const raw = formData.get(`jobGap.${key}`); + if (raw === null) continue; + const text = String(raw).trim(); + if (text === "") { + delete gaps[key]; + continue; + } + const n = Number(text); + if (!Number.isInteger(n) || n < 0 || n > JOB_GAP_MAX_SECONDS) { + return { ok: false, error: `The ${key} job gap must be a whole number of seconds, 0–${JOB_GAP_MAX_SECONDS}.` }; + } + if (n === JOB_GAP_DEFAULT_SECONDS[key]) delete gaps[key]; + else gaps[key] = n; + } + return { ok: true, gaps }; +} // THE SHARED SAVE RESULT of /settings and the four operation-settings forms. A // failure carries what was submitted, so the form keeps what was typed @@ -129,6 +161,10 @@ export async function saveSettingsAction( }; } + const currentSettings = getSettings(); + const jobGaps = parseJobGaps(formData, currentSettings.pacing.jobGapSeconds); + if (!jobGaps.ok) return { ok: false, error: jobGaps.error, values }; + // 0 disables passive refresh; any other value must land in the allowed window. const autoRefreshParsed = Number.parseInt(autoRefreshRaw, 10); if (!Number.isFinite(autoRefreshParsed)) { @@ -238,6 +274,8 @@ export async function saveSettingsAction( cookiesFromBrowser, cookieMode, sleepBetweenDownloadsSeconds: sleepParsed, + // The whole pacing block as it is, with only the job gaps this form edits. + pacing: { ...currentSettings.pacing, jobGapSeconds: jobGaps.gaps }, downloadFormat, sourceVideoQuality, minFreeDiskGB: minFreeDiskParsed, diff --git a/editor/app/settings/components/SettingsForm.tsx b/editor/app/settings/components/SettingsForm.tsx @@ -20,6 +20,17 @@ import { SeededSelect, } from "../../components/forms/Field"; import { seedChecked } from "../../lib/formState"; +import { jobGapSecondsFor } from "yt-dlp-transcript-common/lib/jobGap"; + +// The gaps this form edits (pacing.jobGapSeconds, plans/pacing-guard.md): the +// default and the three platforms with a built-in of their own. Any other +// platform's key is set by hand in settings.json. +const JOB_GAP_FIELDS = [ + { key: "default", label: "Every platform" }, + { key: "twitter", label: "X" }, + { key: "xenforo", label: "Forums" }, + { key: "bluesky", label: "Bluesky" }, +] as const; import { SocialLinksField, toSocialRow, @@ -118,6 +129,32 @@ export function SettingsForm({ initial }: Props) { type="number" hint="Pause inserted between per-video yt-dlp invocations in managed batch downloads (download-from-playlist, download-missing). 0 disables. Default 10s. Each channel can override this in its Advanced settings." /> + <fieldset aria-label="job gaps" className="flex flex-col gap-1 text-sm"> + <legend className="font-medium">Gap between jobs on one platform (seconds)</legend> + <div className="grid grid-cols-2 gap-2 sm:grid-cols-4"> + {JOB_GAP_FIELDS.map(({ key, label }) => ( + <label key={key} className="flex flex-col gap-1 text-xs"> + <span>{label}</span> + <SeededInput + state={state} + name={`jobGap.${key}`} + initial={String(jobGapSecondsFor(initial.pacing, key).seconds)} + type="number" + min={0} + aria-label={`job gap ${key}`} + className="rounded border border-border bg-card px-2 py-1 text-sm" + /> + </label> + ))} + </div> + <span className="text-xs text-muted-foreground"> + A job that asks a platform (a sync, a download, Fetch posts…) starts + 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. + </span> + </fieldset> <label className="flex flex-col gap-1 text-sm"> <span className="font-medium">Default download format</span> <SeededSelect diff --git a/editor/app/settings/components/XSessionSection.tsx b/editor/app/settings/components/XSessionSection.tsx @@ -18,6 +18,7 @@ import { connectXAccountAction, refreshXCookiesAction, setXCookieSourceAction, + setXMaxCookieAgeAction, type XSessionActionResult, } from "../xSessionActions"; import type { XSessionStatus } from "yt-dlp-transcript-common/social/xSessionBroker"; @@ -34,12 +35,16 @@ export function XSessionSection({ initial, initialSource, initialVisibility, + initialMaxCookieAge, }: { initial: XSessionStatus; initialSource: XCookieSourceView; // `social.x.visibility`, resolved (absent = "public"); release 17 slice XP. initialVisibility: XPostsVisibility; + // `social.x.maxCookieAgeMinutes`, resolved (absent = 60; 0 = off). + initialMaxCookieAge: number; }) { + const [maxAge, setMaxAge] = useState(String(initialMaxCookieAge)); const [status, setStatus] = useState<XSessionStatus>(initial); const [source, setSource] = useState<XCookieSourceView>(initialSource); const [login, setLogin] = useState<XLoginStatus | null>(null); @@ -200,6 +205,48 @@ export function XSessionSection({ </p> )} + <div className="flex flex-wrap items-center gap-2"> + <label htmlFor="x-max-cookie-age" className="text-sm"> + Fetch only with cookies refreshed in the last + </label> + <input + id="x-max-cookie-age" + aria-label="x max cookie age minutes" + type="number" + min={0} + value={maxAge} + onChange={(e) => setMaxAge(e.target.value)} + className="w-20 rounded-md border border-border bg-background px-2 py-1 text-sm" + /> + <span className="text-sm">min</span> + <button + type="button" + aria-label="save x max cookie age" + disabled={checking} + onClick={() => + startChecking(async () => { + setError(null); + setNote(null); + const res = await setXMaxCookieAgeAction(Number(maxAge)); + if (res.ok) setNote(res.minutes === 0 ? "Cookie age check off." : `X jobs now need cookies refreshed within ${res.minutes} min.`); + else setError(res.error); + }) + } + 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"> + With the connected profile, a job that asks X (Fetch posts, an X search, + Capture posts, Import one post, the scheduler&apos;s fetches) is refused + 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. + </p> + <div className="flex flex-wrap gap-2"> <button type="button" diff --git a/editor/app/settings/page.tsx b/editor/app/settings/page.tsx @@ -8,6 +8,7 @@ import { xCookieSourceView } from "yt-dlp-transcript-common/social/xCookieSource import { xPostsVisibility } from "yt-dlp-transcript-common/lib/postsVisibility"; import { SettingsForm } from "./components/SettingsForm"; import { XSessionSection } from "./components/XSessionSection"; +import { xMaxCookieAgeMinutes } from "yt-dlp-transcript-common/social/xCookieSource"; import { ArchiveSourcesSection } from "./components/ArchiveSessionSection"; import { readArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession"; @@ -100,6 +101,7 @@ export default async function SettingsPage() { initial={xSession} initialSource={xSource} initialVisibility={xPostsVisibility(settings)} + initialMaxCookieAge={xMaxCookieAgeMinutes(settings.social.x)} /> </section> diff --git a/editor/app/settings/xSessionActions.ts b/editor/app/settings/xSessionActions.ts @@ -35,6 +35,8 @@ import { type XCookieSourceView, type XPostsVisibility, type XSocialSettings, + X_DEFAULT_MAX_COOKIE_AGE_MINUTES, + X_MAX_COOKIE_AGE_MINUTES_CAP, } from "yt-dlp-transcript-common/social/xCookieSource"; import { xPostsVisibility } from "yt-dlp-transcript-common/lib/postsVisibility"; import { saveSettings } from "./saveSettings"; @@ -177,3 +179,28 @@ export async function setXPostsVisibilityAction( revalidatePath("/settings"); return { ok: true, visibility: xPostsVisibility(getSettings()) }; } + +// THE FRESH-JAR RULE'S LIMIT — `social.x.maxCookieAgeMinutes` +// (plans/pacing-guard.md): a job aimed at X starts only when the profile's +// jar was exported within this many minutes. The default (60) is written as +// no key; 0 turns the rule off. +export type XMaxCookieAgeResult = + | { ok: true; minutes: number } + | { ok: false; error: string }; + +export async function setXMaxCookieAgeAction(minutes: number): Promise<XMaxCookieAgeResult> { + if (!Number.isInteger(minutes) || minutes < 0 || minutes > X_MAX_COOKIE_AGE_MINUTES_CAP) { + return { ok: false, error: `The X cookie age limit must be a whole number of minutes, 0–${X_MAX_COOKIE_AGE_MINUTES_CAP}.` }; + } + try { + await saveSettings( + socialXPatch(({ maxCookieAgeMinutes: _was, ...rest }) => + minutes === X_DEFAULT_MAX_COOKIE_AGE_MINUTES ? rest : { ...rest, maxCookieAgeMinutes: minutes }, + ), + ); + } catch (e) { + return { ok: false, error: (e as Error).message }; + } + revalidatePath("/settings"); + return { ok: true, minutes }; +}