commit e0d3ceb9af18cd4365c43d11eb9a0b789cfb681f
parent cfcadd5041b93d8673af35f4491c736d7086a72a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 18 Nov 2026 03:59:29 -0500
x-trending review 1 (M1, M3, S1, S4, S6, S7): the watch's own jar rule, one stream of ticks, three strikes
M1: a watch ticks only when the profile's exported jar is between 0 and the limit old (the setting when above 0, else 60 minutes), whatever the login source, and never when settings cannot be read. M3: no tick starts while a trending read, a reparse or a capture of ANY library is queued or running. S1: three reads in a row that do not end read pause the watch as failing until a person switches it on again. S4: a pause is compared by its reason only and the jar alert is raised on the transition only. S6: a scan asked for by hand shares the one in-flight scan and is refused on an idle boot. S7: the follow-up capture also takes the topic's posts with media that were never captured. watch.ts imports only types of store.ts.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
9 files changed, 451 insertions(+), 84 deletions(-)
diff --git a/common/controller/xTrendingWatch.test.ts b/common/controller/xTrendingWatch.test.ts
@@ -5,12 +5,12 @@
import { after, test } from "node:test";
import assert from "node:assert/strict";
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import type { Paths } from "../lib/paths";
-import { recordXTrendingRead, writeXTrendingPosts } from "../lib/xTrending/store";
-import { describeXTrendingWatch, readXTrendingWatches, setXTrendingWatch } from "../lib/xTrending/watch";
+import { readXTrendingTopics, recordXTrendingRead, TRENDING_DIRNAME, writeXTrendingPosts } from "../lib/xTrending/store";
+import { describeXTrendingWatch, readXTrendingWatches, setXTrendingWatch, xTrendingWatchPath } from "../lib/xTrending/watch";
import { xTrendingWatchTerms } from "../lib/xTrending/config";
import type { Post } from "../lib/posts";
import {
@@ -19,7 +19,9 @@ import {
isXTrendingWatchArmed,
noteXTrendingWatchRead,
pausedXTrendingWatches,
+ runXTrendingWatchScan,
scanXTrendingWatches,
+ watchRefusal,
xTrendingWatchFollowUp,
type WatchRefusal,
type WatchScanDeps,
@@ -84,7 +86,7 @@ function harness(paths: Paths, libraries: string[]): Harness {
paths,
now: () => state.now,
libraries: async () => libraries,
- busy: (slug) => state.busy.has(slug),
+ busy: () => state.busy.size > 0,
refusal: async () => state.refusal,
enqueue: async (tick) => {
if (state.refuse) return { ok: false, error: state.refuse };
@@ -98,8 +100,8 @@ function harness(paths: Paths, libraries: string[]): Harness {
}
const root = (paths: Paths, slug = "lib") => path.join(paths.channelsDir, slug);
-const on = (paths: Paths, topic: string, over: Partial<Parameters<typeof setXTrendingWatch>[1]> = {}, slug = "lib") =>
- setXTrendingWatch(root(paths, slug), { topic, on: true, intervalMinutes: 30, hours: 48, by: "agent", maxTopics: 4, now: T0, ...over });
+const on = async (paths: Paths, topic: string, over: Partial<Parameters<typeof setXTrendingWatch>[1]> = {}, slug = "lib") =>
+ setXTrendingWatch(root(paths, slug), { topics: await readXTrendingTopics(root(paths, slug)), topic, on: true, intervalMinutes: 30, hours: 48, by: "agent", maxTopics: 4, now: T0, ...over });
test("the switch: a topic with a page is watched with an interval and an end time; at most the library's limit; off ends it", async () => {
const paths = await corpus({ lib: { Kettles: [1], Saucers: [2], Lids: [3] } });
@@ -126,9 +128,9 @@ test("the switch: a topic with a page is watched with an interval and an end tim
assert.equal(again.ok && again.watch.shots, true);
assert.equal(again.ok && again.watch.startedAt, "2026-11-18T10:00:00.000Z");
// Off.
- const off = await setXTrendingWatch(root(paths), { topic: "kettles", on: false, intervalMinutes: 30, hours: 48, by: "operator", maxTopics: 2, now: T0 + 6 * MIN });
+ const off = await setXTrendingWatch(root(paths), { topics: await readXTrendingTopics(root(paths)), topic: "kettles", on: false, intervalMinutes: 30, hours: 48, by: "operator", maxTopics: 2, now: T0 + 6 * MIN });
assert.equal(off.ok && off.watch.ended?.sentence, 'The watch of "Kettles" was switched off.');
- assert.match((await setXTrendingWatch(root(paths), { topic: "kettles", on: false, intervalMinutes: 30, hours: 48, by: "operator", maxTopics: 2, now: T0 })).ok ? "" : "not watched", /not watched/);
+ assert.match((await setXTrendingWatch(root(paths), { topics: await readXTrendingTopics(root(paths)), topic: "kettles", on: false, intervalMinutes: 30, hours: 48, by: "operator", maxTopics: 2, now: T0 })).ok ? "" : "not watched", /not watched/);
// Now there is room for the third.
assert.equal((await on(paths, "Lids", { maxTopics: 2 })).ok, true);
});
@@ -215,9 +217,18 @@ test("a stale jar PAUSES the watches, raises X's jar-age alert and enqueues noth
assert.deepEqual(still.paused, []);
assert.equal((await readXTrendingWatches(root(paths))).kettles.paused?.since, "2026-11-18T10:00:00.000Z");
assert.deepEqual(h.ticks, []);
+ // Review 1 S4: the same reason with another age in its sentence changes
+ // nothing — watch.json is not rewritten, and the alert is not raised again
+ // (a banner the operator dismissed stays dismissed).
+ const before = readFileSync(xTrendingWatchPath(root(paths)), "utf8");
+ h.state.refusal = { reason: "jar", sentence: "X cookies were last refreshed 72 min ago (limit 60 min for a watch): press Refresh cookies." };
+ h.state.now = T0 + 11 * MIN;
+ await scanXTrendingWatches(h.deps);
+ assert.equal(readFileSync(xTrendingWatchPath(root(paths)), "utf8"), before);
+ assert.equal(h.state.jar.length, 1);
// Refreshed: resumed at this scan, and the overdue tick is taken.
h.state.refusal = null;
- h.state.now = T0 + 11 * MIN;
+ h.state.now = T0 + 12 * MIN;
const resumed = await scanXTrendingWatches(h.deps);
assert.deepEqual(resumed.resumed.map((r) => r.topic).sort(), ["kettles", "saucers"]);
assert.equal(h.ticks.length, 1);
@@ -331,12 +342,18 @@ test("after a read into a watched topic one capture takes its new posts with med
capture("7005", { mediaState: "error", error: "7005_1.jpg: the CDN answered 404" });
// 7002 has no media: not captured by a media-only watch. 7003 is owed to a
// later capture: taken. 7004 (owed until kept) and 7005 (failed) are not.
- assert.deepEqual(await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["7001", "7002"] }), { ids: ["7001", "7003"], shots: false, fresh: 1, owed: 1 });
+ // (The topic's first post, read before the watch and never captured, carries no media: not taken.)
+ assert.deepEqual(await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["7001", "7002"] }), { ids: ["7001", "7003"], shots: false, fresh: 1, owed: 1, uncaptured: 0 });
// "Screenshot everything new": the post without media is taken too.
await on(paths, "Kettles", { shots: true });
- assert.deepEqual(await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["7001", "7002"] }), { ids: ["7001", "7002", "7003"], shots: true, fresh: 2, owed: 1 });
+ assert.deepEqual(await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["7001", "7002"] }), { ids: ["7001", "7002", "7003"], shots: true, fresh: 2, owed: 1, uncaptured: 0 });
// A read into another topic's posts takes nothing of this one's new ids.
- assert.deepEqual((await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["424242"] }))?.ids, ["7003"]);
+ // ...but (review 1 S7) 7001, which has media and was never captured — the
+ // new post of an earlier tick whose capture was refused — is asked for again.
+ assert.deepEqual(await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["424242"] }), { ids: ["7003", "7001"], shots: true, fresh: 0, owed: 1, uncaptured: 1 });
+ // Once it has a record, whatever the record says, it is not "never captured".
+ capture("7001", { mediaState: "none" });
+ assert.deepEqual((await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: [] }))?.ids, ["7003"]);
});
test("the scan is not armed on an idle boot; armed, it is one timer, and disarms", () => {
@@ -350,3 +367,145 @@ test("the scan is not armed on an idle boot; armed, it is one timer, and disarms
disarmXTrendingWatch();
assert.equal(isXTrendingWatchArmed(), false);
});
+
+// Review 1 M1: the watch's own jar rule, whatever the guard would let a person's job do.
+test("M1: the watch asks a jar under its limit whatever the source, the setting or the settings file say", async () => {
+ const now = T0;
+ type Report = Awaited<ReturnType<typeof import("../jobs/networkGuard").xSessionReport>>;
+ const report = (over: Partial<Report>): (() => Promise<Report>) => async () =>
+ ({
+ source: "profile",
+ sourceChosen: true,
+ profileDir: "p",
+ cookieFile: "c",
+ hasProfile: true,
+ hasCookies: true,
+ looksAuthenticated: true,
+ cookiesUpdatedAt: new Date(now - 10 * MIN).toISOString(),
+ ageMinutes: 10,
+ maxAgeMinutes: 60,
+ ageChecked: true,
+ alert: null,
+ // What the guard says of a person's job: allowed, in every case below.
+ allowed: true,
+ reason: null,
+ ...over,
+ }) as Report;
+ const ask = (over: Partial<Report>, settingsReadable = true) =>
+ watchRefusal({} as Paths, "lib", now, { report: report(over) as never, settingsReadable: () => settingsReadable, held: async () => null });
+ const old = new Date(now - 3 * 60 * MIN).toISOString();
+ // The control: a fresh jar ticks.
+ assert.equal(await ask({}), null);
+ // Exemption 1: the login comes from the browser — the guard cannot read its age and lets a job through.
+ const browser = await ask({ source: "browser", ageChecked: false, cookiesUpdatedAt: old, ageMinutes: 180 });
+ assert.equal(browser?.reason, "jar");
+ assert.match(browser?.sentence ?? "", /last refreshed 3 h ago \(limit 60 min for a watch\)/);
+ // ...and with no exported jar at all.
+ assert.equal((await ask({ source: "browser", ageChecked: false, cookiesUpdatedAt: null, ageMinutes: null, hasCookies: false }))?.reason, "jar");
+ // Exemption 2: the setting is 0 (the rule off for a person's jobs): a watch still asks 60 minutes.
+ const off = await ask({ maxAgeMinutes: 0, ageChecked: false, cookiesUpdatedAt: old, ageMinutes: 180 });
+ assert.match(off?.sentence ?? "", /limit 60 min for a watch/);
+ assert.equal(await ask({ maxAgeMinutes: 0, ageChecked: false }), null);
+ // A stricter setting is kept.
+ assert.match((await ask({ maxAgeMinutes: 5 }))?.sentence ?? "", /10 min ago \(limit 5 min for a watch\)/);
+ // Exemption 3: settings cannot be read.
+ const unreadable = await ask({}, false);
+ assert.equal(unreadable?.reason, "jar");
+ assert.match(unreadable?.sentence ?? "", /settings\.json cannot be read/);
+ // A clock set back: the jar is dated after now.
+ const future = await ask({ cookiesUpdatedAt: new Date(now + 5 * MIN).toISOString(), ageMinutes: 0 });
+ assert.match(future?.sentence ?? "", /dated in the future/);
+ // A jar with no login.
+ assert.equal((await ask({ looksAuthenticated: false }))?.reason, "jar");
+ // The alert and the profile, as before.
+ assert.equal((await ask({ alert: { raisedAt: "x", line: "l" }, allowed: false, reason: "alert up" }))?.reason, "alert");
+ assert.equal((await ask({ hasProfile: false }))?.reason, "no-profile");
+});
+
+test("the watch's file sits where the library's other files do", () => {
+ assert.equal(xTrendingWatchPath("/x"), path.join("/x", TRENDING_DIRNAME, "watch.json"));
+});
+
+// Review 1 M3: the libraries share ONE stream of ticks.
+test("M3: a trending job of any library waiting its turn stops every library's tick; two libraries never stack two reads", async () => {
+ const paths = await corpus({ lib: { Kettles: [1] }, other: { Lids: [3] } });
+ await on(paths, "Kettles");
+ await on(paths, "Lids", {}, "other");
+ const h = harness(paths, ["lib", "other"]);
+ // As the editor's registry answers: busy once a read has been enqueued.
+ h.deps.busy = () => h.ticks.length > 0 || h.state.busy.size > 0;
+ await scanXTrendingWatches(h.deps);
+ assert.deepEqual(h.ticks.map((t) => t.slug), ["lib"]);
+ // The other library is due, and its tick waits: the first read is still queued.
+ h.state.now = T0 + MIN;
+ const second = await scanXTrendingWatches(h.deps);
+ assert.equal(second.enqueued, undefined);
+ assert.equal(h.ticks.length, 1);
+ assert.equal((await readXTrendingWatches(root(paths, "other"))).lids.ticks, 0);
+ // Not a pause: nothing is wrong, it is only not its turn.
+ assert.equal((await readXTrendingWatches(root(paths, "other"))).lids.paused, undefined);
+ // The first read (and its capture) done: now the other library's turn.
+ h.deps.busy = () => false;
+ h.state.now = T0 + 2 * MIN;
+ assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.slug, "other");
+});
+
+// Review 1 S1.
+test("S1: three reads in a row that do not end \"read\" pause the watch until a person switches it on again", async () => {
+ const paths = await corpus({ lib: { Kettles: [1] } });
+ await on(paths, "Kettles");
+ const h = harness(paths, ["lib"]);
+ const dir = root(paths);
+ const fail = (outcome: string) => noteXTrendingWatchRead(dir, { trendId: trend(1).trendId, outcome, now: h.state.now, sentence: "X answered 429 (rate limit)." });
+ assert.equal(await fail("rate-limit"), null);
+ assert.equal(await fail("error"), null);
+ // A clean read between failures starts the count again.
+ assert.equal(await noteXTrendingWatchRead(dir, { trendId: trend(1).trendId, outcome: "read" }), null);
+ assert.equal((await readXTrendingWatches(dir)).kettles.failures, 0);
+ assert.equal(await fail("forbidden"), null);
+ assert.equal(await fail("rate-limit"), null);
+ // A probe is nobody's failure.
+ assert.equal(await noteXTrendingWatchRead(dir, { trendId: trend(1).trendId, outcome: "probe" }), null);
+ const third = await fail("rate-limit");
+ assert.match(third ?? "", /^The last 3 reads of "Kettles" failed \(the last: rate-limit — X answered 429 \(rate limit\)\.\): its watch is paused until someone switches it on again/);
+ let w = (await readXTrendingWatches(dir)).kettles;
+ assert.deepEqual([w.on, w.paused?.reason, w.failures], [true, "failing", 3]);
+ assert.match(describeXTrendingWatch(w, T0), /PAUSED since .* UTC, until someone switches it on again: The last 3 reads/);
+ // No scan resumes it — not with X fine, not an interval later — and none ticks it.
+ for (const at of [T0 + MIN, T0 + 31 * MIN, T0 + 5 * 60 * MIN]) {
+ h.state.now = at;
+ const scan = await scanXTrendingWatches(h.deps);
+ assert.deepEqual([scan.enqueued, scan.resumed], [undefined, []]);
+ }
+ // Nor does a refusal overwrite the reason.
+ h.state.refusal = { reason: "jar", sentence: "stale" };
+ await scanXTrendingWatches(h.deps);
+ assert.equal((await readXTrendingWatches(dir)).kettles.paused?.reason, "failing");
+ h.state.refusal = null;
+ assert.deepEqual(h.ticks, []);
+ // /review lists it.
+ assert.deepEqual((await pausedXTrendingWatches(paths)).map((r) => [r.topic, r.reason]), [["kettles", "failing"]]);
+ // A person switches it on again: the count starts over and it ticks.
+ await on(paths, "Kettles", { now: h.state.now, by: "operator" });
+ w = (await readXTrendingWatches(dir)).kettles;
+ assert.deepEqual([w.paused, w.failures], [undefined, 0]);
+ assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.topic, "kettles");
+});
+
+// Review 1 S6.
+test("S6: two asks for a scan at once are one scan and one read", async () => {
+ const paths = await corpus({ lib: { Kettles: [1], Saucers: [2] } });
+ await on(paths, "Kettles");
+ await on(paths, "Saucers");
+ const h = harness(paths, ["lib"]);
+ let built = 0;
+ const deps = () => (built++, h.deps);
+ const [a, b] = await Promise.all([runXTrendingWatchScan(deps), runXTrendingWatchScan(deps)]);
+ assert.equal(a, b);
+ assert.equal(built, 1);
+ assert.equal(h.ticks.length, 1);
+ // A later ask is a scan of its own.
+ h.state.now = T0 + MIN;
+ await runXTrendingWatchScan(deps);
+ assert.equal(h.ticks.length, 2);
+});
diff --git a/common/controller/xTrendingWatch.ts b/common/controller/xTrendingWatch.ts
@@ -12,8 +12,11 @@
// longest overdue. A tick is the same single `read-x-trending` job a
// person starts, on X's queue (one job at a time, X's gap between jobs);
// a missed window is one catch-up tick, never several;
-// - no tick is started for a library while a read or a capture of it is
-// queued or running (that job's turn comes first);
+// - no tick is started while a trending read, a reparse or a capture of
+// ANY library is queued or running: the libraries share one stream of
+// ticks (the cap on watched topics is per library);
+// - three reads of a watched topic in a row that did not end "read" PAUSE
+// its watch ("failing") until a person switches it on again;
// - WHEN X WOULD REFUSE THE READ the watches PAUSE instead of queueing jobs
// to be refused: X's cookie jar is past its limit ("jar": X's jar-age
// alert goes up, on the dashboard and /cookies, and /review lists the
@@ -37,7 +40,8 @@ import type { Paths } from "../lib/paths";
import { isIdleBoot } from "../lib/idleBoot";
import { jitterMs } from "../lib/jitter";
import { noteXJarStale } from "../lib/serviceCookies-server";
-import { xSessionReport } from "../jobs/networkGuard";
+import { ageText, xSessionReport } from "../jobs/networkGuard";
+import { getSettings } from "../lib/settings";
import { isXTrendingChannel } from "../lib/xTrending/config";
import {
readXTrendingMembership,
@@ -47,6 +51,7 @@ import {
} from "../lib/xTrending/store";
import {
mutateXTrendingWatches,
+ X_TRENDING_WATCH_MAX_FAILURES,
pausedWatchRows,
readXTrendingWatches,
watchIsLive,
@@ -71,8 +76,10 @@ export type WatchScanDeps = {
log?: (line: string) => void;
// The libraries (default: every channel carrying the marker).
libraries?: () => Promise<string[]>;
- // A read or a capture of this library is queued or running.
- busy: (slug: string) => boolean;
+ // A trending read, a reparse or a capture of ANY library is queued or
+ // running (review 1 M3): the libraries share one stream of ticks, so two
+ // libraries never have two reads waiting on X's queue behind each other.
+ busy: () => boolean;
// Why X would refuse a read now, or null (default: watchRefusal below).
refusal?: (slug: string) => Promise<WatchRefusal | null>;
// One read, enqueued (the editor's readXTrendingAction).
@@ -95,21 +102,76 @@ export type WatchScanResult = {
const hhmm = (ms: number) => new Date(ms).toISOString().slice(0, 16).replace("T", " ");
+// The age a watch asks of X's exported jar when the setting says nothing
+// usable (0 turns the fresh-jar rule off for a person's jobs — never for a
+// watch).
+export const WATCH_MAX_JAR_AGE_MINUTES = 60;
+
+export type WatchRefusalDeps = {
+ report?: typeof xSessionReport;
+ // Whether settings.json can be read at all.
+ settingsReadable?: () => boolean;
+ held?: (paths: Paths, now: number) => Promise<string | null>;
+};
+
+function settingsCanBeRead(): boolean {
+ try {
+ getSettings();
+ return true;
+ } catch {
+ return false;
+ }
+}
+
// WHY X WOULD REFUSE A READ NOW — read from disk, never from X: the X alert,
-// the fresh-jar rule (the same computation the network guard refuses by),
-// the connected profile, X's cooldown or hold.
-export async function watchRefusal(paths: Paths, slug: string, now: number): Promise<WatchRefusal | null> {
- const report = await xSessionReport({ paths, channelSlug: slug, now });
+// the connected profile, the jar's age, X's cooldown or hold.
+//
+// THE WATCH HAS ITS OWN JAR RULE, STRICTER THAN THE GUARD'S (review 1 M1). The
+// fresh-jar rule a person's job meets (jobs/networkGuard.ts) lets a job
+// through when the login comes from the browser (its age cannot be read),
+// when `social.x.maxCookieAgeMinutes` is 0, and when settings cannot be read.
+// Those are a person's choices about a job a person started. A watch starts
+// jobs with nobody there, so none of them applies to it: WHATEVER THE SOURCE
+// AND THE SETTING, a watch ticks only when the profile's exported jar was
+// written between 0 and the limit ago (the setting when it is above 0, else
+// 60 minutes) — an age that cannot be read, or is negative (a clock set
+// back), refuses — and never when settings cannot be read.
+export async function watchRefusal(paths: Paths, slug: string, now: number, deps: WatchRefusalDeps = {}): Promise<WatchRefusal | null> {
+ const report = await (deps.report ?? xSessionReport)({ paths, channelSlug: slug, now });
if (!report.hasProfile) {
return {
reason: "no-profile",
sentence: "There is no connected X profile to read a trending page with: connect an X account on /cookies.",
};
}
- if (!report.allowed) {
- return { reason: report.alert ? "alert" : "jar", sentence: report.reason ?? "X's cookie jar is past its limit." };
+ if (report.alert) {
+ return { reason: "alert", sentence: report.reason ?? "X's cookie alert is up." };
+ }
+ if (!(deps.settingsReadable ?? settingsCanBeRead)()) {
+ return { reason: "jar", sentence: "settings.json cannot be read, so the limit on X's cookie age is not known: a watch does not tick without it." };
}
- const held = await xTrendingHeld(paths, now);
+ const limit = report.maxAgeMinutes > 0 ? report.maxAgeMinutes : WATCH_MAX_JAR_AGE_MINUTES;
+ const written = report.cookiesUpdatedAt ? Date.parse(report.cookiesUpdatedAt) : NaN;
+ // Not the report's `ageMinutes`: that one never goes below zero.
+ const ageMinutes = Number.isFinite(written) ? (now - written) / 60_000 : null;
+ if (ageMinutes === null || !report.hasCookies) {
+ return { reason: "jar", sentence: "No X cookie jar has been exported from the connected profile: press Refresh cookies (or Connect X account) on /cookies." };
+ }
+ if (!report.looksAuthenticated) {
+ return { reason: "jar", sentence: "The X cookie jar holds no login (no auth_token): press Connect X account on /cookies." };
+ }
+ if (ageMinutes < 0) {
+ return { reason: "jar", sentence: "X's cookie jar is dated in the future (the clock was set back?): press Refresh cookies on /cookies." };
+ }
+ if (ageMinutes > limit) {
+ return {
+ reason: "jar",
+ sentence: `X cookies were last refreshed ${ageText(now - written)} ago (limit ${limit} min for a watch): press Refresh cookies (or Connect X account) on /cookies.`,
+ };
+ }
+ // Whatever else the guard would refuse a person's job for.
+ if (!report.allowed) return { reason: "jar", sentence: report.reason ?? "X's cookie jar is past its limit." };
+ const held = await (deps.held ?? xTrendingHeld)(paths, now);
return held ? { reason: "cooldown", sentence: held } : null;
}
@@ -163,14 +225,15 @@ export async function scanXTrendingWatches(deps: WatchScanDeps): Promise<WatchSc
let write = false;
for (const [id, w] of Object.entries(all)) {
if (!watchIsLive(w)) continue;
+ // Paused for failing: only a person ends that (review 1 S1).
+ if (w.paused?.reason === "failing") continue;
if (refusal) {
- if (w.paused?.reason !== refusal.reason || w.paused.sentence !== refusal.sentence) {
- if (w.paused?.reason !== refusal.reason) out.paused.push({ slug, topic: id, reason: refusal.reason });
- w.paused = {
- reason: refusal.reason,
- since: w.paused?.reason === refusal.reason ? w.paused.since : at,
- sentence: refusal.sentence,
- };
+ // BY THE REASON ONLY (review 1 S4): the sentence carries the
+ // jar's age in minutes, and a watch.json rewritten every scan for
+ // it is churn. The sentence is the one the pause began with.
+ if (w.paused?.reason !== refusal.reason) {
+ out.paused.push({ slug, topic: id, reason: refusal.reason });
+ w.paused = { reason: refusal.reason, since: at, sentence: refusal.sentence };
write = true;
}
} else if (w.paused && w.paused.reason !== "refused") {
@@ -189,17 +252,19 @@ export async function scanXTrendingWatches(deps: WatchScanDeps): Promise<WatchSc
const live = Object.entries(watches).filter(([, w]) => watchIsLive(w));
out.live += live.length;
if (refusal) {
- if (refusal.reason === "jar" && live.length > 0) {
+ // The alert is raised when the watches GO stale, not at every scan
+ // after (review 1 S4): a banner the operator dismissed stays dismissed.
+ const went = out.paused.filter((p) => p.slug === slug && p.reason === "jar").length;
+ if (refusal.reason === "jar" && went > 0) {
const line = `${live.length} watched topic${live.length === 1 ? "" : "s"} of ${slug} paused: ${refusal.sentence} ${WATCH_JAR_NOTE}`;
await (deps.noteJarStale ?? ((l, s) => noteXJarStale(deps.paths, { line: l, channel: s }, now)))(line, slug).catch(() => {});
}
continue;
}
- // 3. What is due — unless a job of this library is already waiting its turn.
- if (deps.busy(slug)) continue;
+ // 3. What is due.
for (const [id, w] of live) {
const topic = topics.get(id);
- if (!topic) continue;
+ if (!topic || w.paused?.reason === "failing") continue;
const dueAt = w.nextTickAt ? Date.parse(w.nextTickAt) : Date.parse(w.startedAt);
if (dueAt <= now) due.push({ slug, root, topic, watch: w, dueAt });
}
@@ -207,7 +272,8 @@ export async function scanXTrendingWatches(deps: WatchScanDeps): Promise<WatchSc
log(`x-trending watch: ${slug}: the scan could not read this library: ${(err as Error).message}`);
}
}
- if (due.length === 0) return out;
+ // Nothing is started while a trending job of any library waits its turn.
+ if (due.length === 0 || deps.busy()) return out;
// The longest overdue, and only it.
due.sort((a, b) => a.dueAt - b.dueAt || a.slug.localeCompare(b.slug) || a.topic.id.localeCompare(b.topic.id));
const pick = due[0];
@@ -263,13 +329,20 @@ const goneSentence = (title: string) =>
`X no longer has the trending page of "${title}" (trending pages expire): the watch ended.`;
// THE END OF A READ, told to the watch (every read of a library, a person's
-// too). A page X answered "gone" for is not read again; when the topic has no
-// page left, its watch ends with a sentence. Answers that sentence, or null.
+// too):
+// - a page X answered "gone" for is not read again; when the topic has no
+// page left, its watch ends with a sentence;
+// - a read that ended "read" clears the count of failures;
+// - any other end (a rate limit, a 403, a login wall, a page that would not
+// load, nothing recognised) is a failure, and the third in a row PAUSES
+// the watch, "failing", until a person switches it on again (review 1
+// S1). A 429's 15-minute cooldown is recorded by the read as before.
+// Answers the sentence of what it did to a watch, or null.
export async function noteXTrendingWatchRead(
channelRoot: string,
- read: { trendId: string; outcome: string; now?: number },
+ read: { trendId: string; outcome: string; now?: number; sentence?: string },
): Promise<string | null> {
- if (read.outcome !== "gone") return null;
+ if (read.outcome === "probe") return null;
const topics = await readXTrendingTopics(channelRoot);
const at = new Date(read.now ?? Date.now()).toISOString();
return mutateXTrendingWatches(channelRoot, (watches) => {
@@ -278,25 +351,45 @@ export async function noteXTrendingWatchRead(
for (const topic of topics) {
const w = watches[topic.id];
if (!watchIsLive(w) || !topic.sources.some((s) => s.trendId === read.trendId)) continue;
- if (!w.goneSources.includes(read.trendId)) w.goneSources.push(read.trendId);
+ if (read.outcome === "read") {
+ if (w.failures !== 0) {
+ w.failures = 0;
+ write = true;
+ }
+ continue;
+ }
+ if (read.outcome === "gone") {
+ if (!w.goneSources.includes(read.trendId)) w.goneSources.push(read.trendId);
+ write = true;
+ if (topic.sources.every((s) => w.goneSources.includes(s.trendId))) {
+ sentence = goneSentence(topic.title);
+ w.on = false;
+ delete w.paused;
+ w.ended = { at, reason: "gone", sentence };
+ }
+ continue;
+ }
+ w.failures++;
write = true;
- if (topic.sources.every((s) => w.goneSources.includes(s.trendId))) {
- sentence = goneSentence(topic.title);
- w.on = false;
- delete w.paused;
- w.ended = { at, reason: "gone", sentence };
+ if (w.failures >= X_TRENDING_WATCH_MAX_FAILURES && w.paused?.reason !== "failing") {
+ sentence =
+ `The last ${w.failures} reads of "${topic.title}" failed (the last: ${read.outcome}` +
+ `${read.sentence ? ` — ${read.sentence}` : ""}): its watch is paused until someone switches it on again ` +
+ `(Watch on its page, or watch-trending {"topic": "${topic.id}", "on": true}).`;
+ w.paused = { reason: "failing", since: at, sentence };
}
}
return { write, result: sentence };
});
}
-export type WatchFollowUp = { ids: string[]; shots: boolean; fresh: number; owed: number };
+export type WatchFollowUp = { ids: string[]; shots: boolean; fresh: number; owed: number; uncaptured: number };
// WHAT ONE CAPTURE TAKES AFTER A READ INTO A WATCHED TOPIC: the read's new
// posts (their media at once; a screenshot too when the topic says so), then
// the topic's posts a capture left OWED to a later one (the job's budget, X's
-// cooldown) — never one that failed, and never one owed until it is kept.
+// cooldown), then its posts with media that were never captured at all —
+// never one whose capture failed, and never one owed until it is kept.
// Null when the topic is not watched or there is nothing to take.
export async function xTrendingWatchFollowUp(
channelRoot: string,
@@ -310,14 +403,28 @@ export async function xTrendingWatchFollowUp(
const ids = fresh.slice(0, X_TRENDING_WATCH_CAPTURE_MAX);
let owed = 0;
const taken = new Set(ids);
+ // Then what is owed to a later capture; then (review 1 S7) the topic's
+ // posts with media that have NO capture record at all — the new posts of an
+ // earlier tick whose capture was refused before it was a job (a stale jar,
+ // the cooldown), which nothing would otherwise ask for again.
+ const never: string[] = [];
for (const [id, m] of Object.entries(membership)) {
- if (ids.length >= X_TRENDING_WATCH_CAPTURE_MAX) break;
if (m.topic !== o.topic || taken.has(id)) continue;
- if ((await xTrendingCaptureSummary(channelRoot, id))?.mediaOwed !== "next") continue;
+ const capture = await xTrendingCaptureSummary(channelRoot, id);
+ if (capture?.mediaOwed === "next") {
+ if (ids.length < X_TRENDING_WATCH_CAPTURE_MAX) {
+ ids.push(id);
+ owed++;
+ }
+ } else if (!capture && (m.media?.count ?? 0) > 0) never.push(id);
+ }
+ let uncaptured = 0;
+ for (const id of never) {
+ if (ids.length >= X_TRENDING_WATCH_CAPTURE_MAX) break;
ids.push(id);
- owed++;
+ uncaptured++;
}
- return ids.length > 0 ? { ids, shots: watch.shots, fresh: ids.length - owed, owed } : null;
+ return ids.length > 0 ? { ids, shots: watch.shots, fresh: ids.length - owed - uncaptured, owed, uncaptured } : null;
}
// The watches that are paused now, across every library — /review's section.
@@ -353,6 +460,26 @@ export function xTrendingWatchTick(): Promise<WatchScanResult> | null {
return a.scanning;
}
+// ONE SCAN AT A TIME, ARMED OR NOT (review 1 S6): `watch-trending {"tick":
+// true}` goes through the armed scan's own in-flight promise when the timer
+// is armed, and through this one when it is not (the e2e test server) — two
+// asks at once are one scan, never two reads.
+declare global {
+ // eslint-disable-next-line no-var
+ var __yttXTrendingWatchScan__: Promise<WatchScanResult> | null | undefined;
+}
+
+export function runXTrendingWatchScan(deps: () => WatchScanDeps): Promise<WatchScanResult> {
+ const armed = xTrendingWatchTick();
+ if (armed) return armed;
+ if (!globalThis.__yttXTrendingWatchScan__) {
+ globalThis.__yttXTrendingWatchScan__ = scanXTrendingWatches(deps()).finally(() => {
+ globalThis.__yttXTrendingWatchScan__ = null;
+ });
+ }
+ return globalThis.__yttXTrendingWatchScan__;
+}
+
// Arm the scan: every `everyMs` (default CHECK_MS). Refused (false) on an idle
// boot. Idempotent: a second call only replaces the deps.
export function armXTrendingWatch(
diff --git a/common/lib/xTrending/__fixtures__/slice2Library.ts b/common/lib/xTrending/__fixtures__/slice2Library.ts
@@ -10,7 +10,7 @@ import path from "node:path";
import { writePostAvailability } from "../../posts-server";
import { judgeXTrending } from "../judgements";
import { adoptXTrendingMedia, ensureXTrendingMediaIgnore } from "../mediaStore";
-import { trendingDir, xTrendingPostsMediaDir } from "../store";
+import { readXTrendingTopics, trendingDir, xTrendingPostsMediaDir } from "../store";
import { setXTrendingWatch } from "../watch";
export const SLICE2_MARKS = {
@@ -41,7 +41,7 @@ export const SLICE2_FILE_NAMES: readonly string[] = [
// `postId` must be a post of the library, in a topic `topicId` that holds a page.
export async function plantSlice2Library(libRoot: string, o: { postId: string; topicId: string }): Promise<void> {
await judgeXTrending(libRoot, { by: "operator", set: [{ id: o.postId, state: "keep", note: `kept ${SLICE2_MARKS.note}` }] });
- await setXTrendingWatch(libRoot, { topic: o.topicId, on: true, intervalMinutes: 30, hours: 48, by: "operator", maxTopics: 4, now: Date.parse("2026-11-18T10:00:00.000Z") });
+ await setXTrendingWatch(libRoot, { topics: await readXTrendingTopics(libRoot), topic: o.topicId, on: true, intervalMinutes: 30, hours: 48, by: "operator", maxTopics: 4, now: Date.parse("2026-11-18T10:00:00.000Z") });
const dir = path.join(xTrendingPostsMediaDir(libRoot), o.postId);
mkdirSync(dir, { recursive: true });
writeFileSync(path.join(dir, `${o.postId}_1.jpg`), `picture ${SLICE2_MARKS.media}`);
diff --git a/common/lib/xTrending/watch.ts b/common/lib/xTrending/watch.ts
@@ -13,6 +13,10 @@
// connected profile ("no-profile"), or the read was refused
// ("refused"). A PAUSE ENDS BY ITSELF at the first scan that finds
// the reason gone: a watch resumes after a Refresh on /cookies.
+// EXCEPT "failing" (review 1 S1): three reads in a row that did
+// not end "read" (a rate limit, a 403, a page that will not
+// load). A watch does not read into failure for two days: it
+// stays paused until a PERSON switches it on again.
// ended the watch is over, with a sentence: its end time came, X no
// longer has its page(s), or it was switched off
//
@@ -24,10 +28,18 @@
import path from "node:path";
import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../jsonFile-server";
-import { readXTrendingTopics, trendingDir } from "./store";
+// TYPES ONLY from store.ts (which reads the watches for its listing): this
+// module imports nothing of it at run time, so the two do not form a cycle.
+import type { XTrendingTopic } from "./store";
-export type XTrendingWatchPauseReason = "jar" | "alert" | "cooldown" | "no-profile" | "refused";
-export const X_TRENDING_WATCH_PAUSE_REASONS: readonly XTrendingWatchPauseReason[] = ["jar", "alert", "cooldown", "no-profile", "refused"];
+// store.ts TRENDING_DIRNAME (watch.test.ts holds the two together).
+const TRENDING_DIRNAME = "trending";
+
+export type XTrendingWatchPauseReason = "jar" | "alert" | "cooldown" | "no-profile" | "refused" | "failing";
+export const X_TRENDING_WATCH_PAUSE_REASONS: readonly XTrendingWatchPauseReason[] = ["jar", "alert", "cooldown", "no-profile", "refused", "failing"];
+// This many reads of a watched topic in a row that did not end "read", and
+// the watch pauses ("failing") until a person switches it on again.
+export const X_TRENDING_WATCH_MAX_FAILURES = 3;
export type XTrendingWatch = {
on: boolean;
@@ -42,6 +54,8 @@ export type XTrendingWatch = {
lastJobId?: string;
nextTickAt?: string;
ticks: number;
+ // Reads of its pages in a row that did not end "read".
+ failures: number;
// Which of the topic's pages the next tick reads (round-robin).
nextSource: number;
// Pages X answered "gone" for: not read again.
@@ -53,7 +67,7 @@ export type XTrendingWatch = {
type WatchFile = { version: 1; topics: Record<string, XTrendingWatch> };
export function xTrendingWatchPath(channelRoot: string): string {
- return path.join(trendingDir(channelRoot), "watch.json");
+ return path.join(channelRoot, TRENDING_DIRNAME, "watch.json");
}
const str = (v: unknown): v is string => typeof v === "string" && v !== "";
@@ -78,6 +92,7 @@ function parseWatch(raw: unknown): XTrendingWatch | null {
...(str(r.lastJobId) ? { lastJobId: r.lastJobId } : {}),
...(iso(r.nextTickAt) ? { nextTickAt: r.nextTickAt } : {}),
ticks: Number.isInteger(r.ticks) && (r.ticks as number) > 0 ? (r.ticks as number) : 0,
+ failures: Number.isInteger(r.failures) && (r.failures as number) > 0 ? (r.failures as number) : 0,
nextSource: Number.isInteger(r.nextSource) && (r.nextSource as number) > 0 ? (r.nextSource as number) : 0,
goneSources: Array.isArray(r.goneSources) ? r.goneSources.filter((t): t is string => typeof t === "string" && /^\d+$/.test(t)) : [],
...(paused && typeof paused === "object" && X_TRENDING_WATCH_PAUSE_REASONS.includes(paused.reason) && iso(paused.since) && str(paused.sentence)
@@ -120,6 +135,8 @@ export async function mutateXTrendingWatches<T>(
}
export type SetWatchAsk = {
+ // The library's topics (store.ts readXTrendingTopics), read by the caller.
+ topics: ReadonlyArray<XTrendingTopic>;
topic: string;
on: boolean;
intervalMinutes: number;
@@ -140,7 +157,7 @@ const hhmm = (ms: number) => new Date(ms).toISOString().slice(0, 16).replace("T"
// history. OFF: the watch ends ("switched off"); a watch that is not on is
// left as it is.
export async function setXTrendingWatch(channelRoot: string, ask: SetWatchAsk): Promise<SetWatchResult> {
- const topics = await readXTrendingTopics(channelRoot);
+ const topics = ask.topics;
const topic = topics.find((t) => t.id === ask.topic) ?? topics.find((t) => t.title.toLowerCase() === ask.topic.trim().toLowerCase());
if (!topic) {
return { ok: false, error: `This library has no topic "${ask.topic}" (its topics: ${topics.map((t) => t.id).join(", ") || "none yet"}).` };
@@ -186,9 +203,11 @@ export async function setXTrendingWatch(channelRoot: string, ask: SetWatchAsk):
// A changed interval counts from the last tick; a new watch ticks at the next scan.
...(live?.lastTickAt ? { nextTickAt: new Date(Date.parse(live.lastTickAt) + ask.intervalMinutes * 60_000).toISOString() } : {}),
ticks: live?.ticks ?? 0,
+ // Switched on by a person: a watch paused for failing starts again.
+ failures: 0,
nextSource: live?.nextSource ?? 0,
goneSources: live?.goneSources ?? [],
- ...(live?.paused ? { paused: live.paused } : {}),
+ ...(live?.paused && live.paused.reason !== "failing" ? { paused: live.paused } : {}),
};
watches[topic.id] = watch;
return { write: true, result: { ok: true, topic: topic.id, watch } };
@@ -200,6 +219,7 @@ export function describeXTrendingWatch(w: XTrendingWatch, now: number): string {
if (w.ended) return w.ended.sentence;
if (!w.on) return "Not watched.";
const every = `every ${w.intervalMinutes} min until ${hhmm(Date.parse(w.until))} UTC${w.shots ? ", screenshotting every new post" : ""}`;
+ if (w.paused?.reason === "failing") return `Watched ${every} — PAUSED since ${hhmm(Date.parse(w.paused.since))} UTC, until someone switches it on again: ${w.paused.sentence}`;
if (w.paused) return `Watched ${every} — PAUSED since ${hhmm(Date.parse(w.paused.since))} UTC: ${w.paused.sentence}`;
const next = w.nextTickAt ? Date.parse(w.nextTickAt) : now;
return `Watched ${every}; ${w.ticks} tick${w.ticks === 1 ? "" : "s"} so far, next ${next <= now ? "at the next scan" : `at ${hhmm(next)} UTC`}.`;
diff --git a/editor/app/api/ops/_xTrendingWatch.ts b/editor/app/api/ops/_xTrendingWatch.ts
@@ -1,6 +1,7 @@
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
import { READ_X_TRENDING_KIND, REPARSE_X_TRENDING_KIND } from "yt-dlp-transcript-common/lib/xTrending/config";
+import { isXTrendingLibrarySync } from "yt-dlp-transcript-common/lib/xTrending/library-server";
import { armXTrendingWatch, type WatchScanDeps } from "yt-dlp-transcript-common/controller/xTrendingWatch";
import { readXTrendingAction } from "../../channels/[slug]/xTrendingActions";
@@ -10,19 +11,15 @@ import { readXTrendingAction } from "../../channels/[slug]/xTrendingActions";
// starts — shared by `watch-trending {"tick": true}` and the timer
// instrumentation.ts arms.
export function xTrendingWatchDeps(): WatchScanDeps {
+ const paths = getPaths();
return {
- paths: getPaths(),
+ paths,
log: (line) => console.log(line),
- // A read or a capture of the library waiting its turn, or running.
- busy: (slug) =>
- getRegistry()
- .list()
- .some(
- (j) =>
- j.channelSlug === slug &&
- (j.kind === READ_X_TRENDING_KIND || j.kind === REPARSE_X_TRENDING_KIND || j.kind === "capture-posts") &&
- (j.status === "queued" || j.status === "running"),
- ),
+ // A trending read, a reparse, or a capture of a LIBRARY, waiting its turn
+ // or running — whatever the library (review 1 M3): every library's ticks
+ // are one stream, so the scan never stacks one read per library on X's
+ // queue.
+ busy: () => xTrendingJobWaiting(getRegistry().list(), (slug) => isXTrendingLibrarySync(paths.channelsDir, slug)),
enqueue: async (tick) => {
const started = await readXTrendingAction({ slug: tick.slug, url: tick.url, topic: tick.topic });
if (!started.ok) return { ok: false, error: started.error };
@@ -32,6 +29,19 @@ export function xTrendingWatchDeps(): WatchScanDeps {
};
}
+type JobLike = { kind: string; status: string; channelSlug?: string };
+
+// A trending job of ANY library that is queued or running.
+export function xTrendingJobWaiting(jobs: ReadonlyArray<JobLike>, isLibrary: (slug: string) => boolean): boolean {
+ return jobs.some(
+ (j) =>
+ (j.status === "queued" || j.status === "running") &&
+ (j.kind === READ_X_TRENDING_KIND ||
+ j.kind === REPARSE_X_TRENDING_KIND ||
+ (j.kind === "capture-posts" && !!j.channelSlug && isLibrary(j.channelSlug))),
+ );
+}
+
// Armed once per process, below the idle gate (armXTrendingWatch refuses an
// idle boot itself too).
export function armXTrendingWatchLane(): boolean {
diff --git a/editor/app/api/ops/watch-trending/route.test.ts b/editor/app/api/ops/watch-trending/route.test.ts
@@ -115,3 +115,31 @@ test("a topic is watched on the library's terms; the listing shows it; a scan wi
assert.equal(off.status, 200);
assert.equal(off.json.sentence, 'The watch of "Kettles" was switched off.');
});
+
+// Review 1 S6.
+test("S6: a scan asked for by hand is refused on an idle boot; a settings change and the switch are not", async () => {
+ process.env.ARCHILYZER_IDLE_BOOT = "1";
+ try {
+ const tick = await call({ slug: "trending", tick: true });
+ assert.equal(tick.status, 400);
+ assert.match(String(tick.json.error), /booted idle \(ARCHILYZER_IDLE_BOOT\): it starts no work, so no watch scan runs/);
+ assert.equal((await call({ slug: "trending", settings: { maxTopics: 2 } })).status, 200);
+ } finally {
+ delete process.env.ARCHILYZER_IDLE_BOOT;
+ }
+});
+
+// Review 1 M3.
+test("M3: the scan counts a trending job of ANY library as waiting — and no other channel's capture", async () => {
+ const { xTrendingJobWaiting } = await import("../_xTrendingWatch");
+ const isLibrary = (slug: string) => slug === "trending" || slug === "other-library";
+ const job = (kind: string, status: string, channelSlug?: string) => ({ kind, status, ...(channelSlug ? { channelSlug } : {}) });
+ assert.equal(xTrendingJobWaiting([], isLibrary), false);
+ assert.equal(xTrendingJobWaiting([job("read-x-trending", "queued", "other-library")], isLibrary), true);
+ assert.equal(xTrendingJobWaiting([job("read-x-trending", "running", "trending")], isLibrary), true);
+ assert.equal(xTrendingJobWaiting([job("reparse-x-trending", "queued", "other-library")], isLibrary), true);
+ assert.equal(xTrendingJobWaiting([job("capture-posts", "queued", "other-library")], isLibrary), true);
+ // An ordinary X channel's capture is not the watch's business; nor is a finished job.
+ assert.equal(xTrendingJobWaiting([job("capture-posts", "running", "account-x")], isLibrary), false);
+ assert.equal(xTrendingJobWaiting([job("read-x-trending", "done", "trending"), job("capture-posts", "failed", "trending")], isLibrary), false);
+});
diff --git a/editor/app/api/ops/watch-trending/route.ts b/editor/app/api/ops/watch-trending/route.ts
@@ -16,7 +16,8 @@ export const dynamic = "force-dynamic";
// (15–1440; default the library's, else 30) until `hours` from now (1–168;
// else 48), each tick the SAME single `read-x-trending` job on X's queue,
// started by the editor's own scan (once a minute; at most one read per scan;
-// none while a read or capture of the library waits its turn). A topic of
+// none while a trending read, a reparse or a capture of ANY library waits its
+// turn: every library's ticks are one stream). A topic of
// several trending pages reads one page per tick, in turn. At most
// `maxTopics` topics of a library are watched at once (default 4).
//
@@ -30,19 +31,30 @@ export const dynamic = "force-dynamic";
// editor never refreshes the jar by itself, so a watch PAUSES when the jar
// goes stale — X's jar-age alert goes up and /review lists the paused watches
// — and resumes at the first scan after Refresh cookies on /cookies. It does
-// not cover a night nobody presses Refresh in. The X alert, X cooling down
-// after a rate limit and a missing profile pause it the same way.
+// not cover a night nobody presses Refresh in. THE LIMIT IS THE WATCH'S OWN,
+// stricter than the one a person's job meets: whatever the login source, a
+// watch asks the profile's exported jar to be between 0 and the limit old (the
+// setting when above 0, else 60 minutes), and never ticks when settings
+// cannot be read. The X alert, X cooling down after a rate limit and a
+// missing profile pause it the same way.
//
-// A post a page showed before and does not show at a read that reached the
-// page's end is recorded "gone from the page at <time>" (`get trending`:
-// `gone`) — never "deleted": a trending page is a ranked list. A trending
+// THREE READS IN A ROW THAT DO NOT END "read" (a rate limit, a 403, a page
+// that will not load) pause the watch as "failing". That pause does not end
+// by itself: switch the watch on again.
+//
+// A post a page showed before and does not show at a read whose capture shows
+// the page's end (the page was asked for more and had none, and no answer
+// failed) is recorded "gone from the page at <time>" (`get trending`: `gone`)
+// — never "deleted": a trending page is a ranked list. A read that merely went
+// quiet says nothing. A trending
// page X no longer has is not read again, and the watch ends with a sentence
// when it was the topic's last.
//
// `settings` changes the library's own defaults (config.xTrending):
// maxVideoMb (1–2000; the largest media file fetched for a post nobody has
// kept), intervalMinutes, hours, maxTopics (1–12). `tick: true` runs one scan
-// now, as the timer does.
+// now, as the timer does: through the same single scan (two asks at once are
+// one), and refused on an idle boot (ARCHILYZER_IDLE_BOOT).
//
// Refused with a sentence: no such channel, not a library, not exactly one of
// topic / settings / tick, no such topic, a topic with no trending page, the
diff --git a/editor/app/channels/[slug]/xTrendingActions.ts b/editor/app/channels/[slug]/xTrendingActions.ts
@@ -33,9 +33,8 @@ import {
} from "yt-dlp-transcript-common/controller/readXTrending";
import {
noteXTrendingWatchRead,
- scanXTrendingWatches,
+ runXTrendingWatchScan,
xTrendingWatchFollowUp,
- xTrendingWatchTick,
type WatchScanResult,
} from "yt-dlp-transcript-common/controller/xTrendingWatch";
import {
@@ -64,6 +63,8 @@ import {
type XTrendingJudgeItem,
type XTrendingJudgeResult,
} from "yt-dlp-transcript-common/lib/xTrending/judgements";
+import { isIdleBoot } from "yt-dlp-transcript-common/lib/idleBoot";
+import { readXTrendingTopics } from "yt-dlp-transcript-common/lib/xTrending/store";
import { safeRevalidate } from "../../lib/safeRevalidate";
import { capturePostsAction } from "./socialActions";
import { xPressInFlight } from "../../lib/cookieRefreshGuard";
@@ -135,14 +136,15 @@ async function afterXTrendingRead(
result: ReadXTrendingResult,
onLog: (line: string) => void,
): Promise<void> {
- const ended = await noteXTrendingWatchRead(channelRoot, { trendId: result.trendId, outcome: result.outcome });
- if (ended) onLog(ended);
+ const told = await noteXTrendingWatchRead(channelRoot, { trendId: result.trendId, outcome: result.outcome, sentence: result.sentence });
+ if (told) onLog(told);
if (result.outcome !== "read" || !result.topic) return;
const follow = await xTrendingWatchFollowUp(channelRoot, { topic: result.topic.id, newIds: result.newIds ?? [] });
if (!follow) return;
const what =
`${follow.fresh} new post${follow.fresh === 1 ? "" : "s"}` +
(follow.owed ? ` and ${follow.owed} owed from an earlier capture` : "") +
+ (follow.uncaptured ? ` and ${follow.uncaptured} never captured` : "") +
` of the watched topic "${result.topic.title}"`;
const started = await capturePostsAction(slug, follow.ids, undefined, follow.shots, true, false, false, {
// Media only: no page is opened for the avatars or the context either.
@@ -281,8 +283,14 @@ export async function watchXTrendingAction(ask: WatchXTrendingAsk): Promise<Watc
if (asked !== 1) return { ok: false, error: WATCH_ONE_OF };
if (ask.tick) {
// The armed scan when there is one (one scan at a time); else one of its own.
+ // AN IDLE BOOT STARTS NO WORK (review 1 S6): the scan is not armed
+ // there, and asking for one by hand is refused too.
+ if (isIdleBoot()) {
+ return { ok: false, error: "This editor booted idle (ARCHILYZER_IDLE_BOOT): it starts no work, so no watch scan runs. Restart it without the switch to watch topics." };
+ }
+ // One scan at a time, the armed timer's included: two asks are one scan.
const { xTrendingWatchDeps } = await import("../../api/ops/_xTrendingWatch");
- const scan = await (xTrendingWatchTick() ?? scanXTrendingWatches(xTrendingWatchDeps()));
+ const scan = await runXTrendingWatchScan(xTrendingWatchDeps);
safeRevalidate([`/channels/${ask.slug}`, "/review"]);
const sentence = scan.enqueued
? `Scanned: a tick of "${scan.enqueued.topic}" (${scan.enqueued.slug}) was started, job ${scan.enqueued.jobId}.`
@@ -311,6 +319,7 @@ export async function watchXTrendingAction(ask: WatchXTrendingAsk): Promise<Watc
if (!terms.ok) return terms;
const now = Date.now();
const set = await setXTrendingWatch(lib.channelRoot, {
+ topics: await readXTrendingTopics(lib.channelRoot),
topic: String(ask.topic),
on: ask.on,
intervalMinutes: terms.terms.intervalMinutes,
diff --git a/editor/app/review/page.tsx b/editor/app/review/page.tsx
@@ -101,7 +101,9 @@ function PausedWatchesSection({ rows }: { rows: PausedWatchRow[] }) {
<span className="text-xs text-muted-foreground">
{row.reason === "jar"
? "It resumes by itself at the first scan after Refresh cookies on /cookies. Nothing is read while it is paused."
- : "It resumes by itself at the first scan that finds this gone. Nothing is read while it is paused."}
+ : row.reason === "failing"
+ ? "It does not resume by itself: press Watch on the topic again once the reads can succeed. Nothing is read while it is paused."
+ : "It resumes by itself at the first scan that finds this gone. Nothing is read while it is paused."}
</span>
</li>
))}