commit 77645c80fecb1eb14f0e0d8247f3477be4e049a6 parent 2416754fe4d70c8bea6492d067156e0c0639211a Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Wed, 18 Nov 2026 05:47:01 -0500 x-trending review 2 (N1, N3, N4): a watch's job asks its jar rule when it starts; still kept decides the cap too; the page's end is the bottom continuation N1: a tick is marked as the watch's (plan, read.json, the log) and its job asks the watch's own jar rule at its start, as does the capture that follows a read, before it is queued and when it starts; a refusal opens nothing, pauses the watches and is no strike. N3: one still-kept predicate, asked once per post before its media, decides both the uncapped download and the logged-in fallback. N4: pageEnd needs the last listing answer to be the continuation from the previous answer's bottom cursor, and a 200 carrying GraphQL errors or no timeline instructions is a failed answer. Co-Authored-By: Claude <noreply@anthropic.com> Diffstat:
22 files changed, 569 insertions(+), 115 deletions(-)
diff --git a/OPERATING.md b/OPERATING.md @@ -718,15 +718,19 @@ pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","o whole thread (`get trending` gives each post's `thread`); a post's own judgement comes before its thread's. Judgements are in `channels/<slug>/trending/judgements.json`, with who decided, when and the note. - **An agent's judgement is a suggestion.** An agent's write over a judgement the operator made is skipped for - that id and named in `skipped`; the rest of the ask is written. A post the operator judged through its thread - is the operator's too, so an agent's post-level write for it is skipped. The operator overturns anything. - `"by"` is the caller's word: an agent says `"agent"`. + that id and named in `skipped`; the rest of the ask is written. The operator overturns anything. `"by"` is the + caller's word: an agent says `"agent"`. +- **Which judgement is in force.** The operator's entry, for the post or for its thread, always outranks an + agent's about the same post, whatever the order in time; between two entries of the same hand, the post's own + outranks its thread's. So an agent's post-level write is skipped whenever the post's thread is the operator's, + and an operator's thread judgement overrides an agent's older entry for one of its posts (the entry stays in + the file and decides nothing). - **Keep archives the post.** The posts that became keep go into one `capture-posts` job on X's queue: a screenshot, the post's context, a reply's thread shot, and its media. `"archive": false` marks only. If the capture is refused (a stale jar, the X alert, X cooling down) the judgement is written all the same and `archive.error` says why; `capture-posts {"slug", "ids", "thread": true, "keptMedia": true}` archives them later. - A post dropped again before that job reaches it gets no logged-in download: the judgements are read again - immediately before each one. A library's capture runs on X's queue only (`"queueKey"` is refused). + A post dropped again before that job reaches it is fetched as any post is, under the library's cap and with no + logged-in download: the judgements are read again, once per post, before its media. A library's capture runs on X's queue only (`"queueKey"` is refused). - **Drop deletes nothing.** The post, its capture and its media stay, and a later keep puts it back. Nothing in this release removes a capture. - **A library's media comes from X's media CDN and is kept once.** The saved capture of the read that showed a @@ -765,10 +769,13 @@ pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","o (its age cannot be read), when `social.x.maxCookieAgeMinutes` is 0, or when settings cannot be read. A watch is not: whatever the source, it ticks only when the profile's exported jar is between 0 and the limit old (the setting when it is above 0, else 60 minutes). A jar dated in the future, or settings that cannot be read, pause - it. + it. The rule is asked when a tick is queued and again when its job starts, and likewise for the capture that + follows a read: a tick whose turn on X's queue comes after the jar passed the limit is not read (no browser + opens), the watch pauses, and it does not count as a failed read. - **Three failed reads pause a watch for good.** Three reads of a watched topic in a row that do not end "read" (a rate limit, a 403, a login wall, a page that will not load) pause its watch as `failing`. That pause does not - end by itself: press **Watch** again, or `watch-trending {"on": true}`. /review lists it. + end by itself, and only the operator ends it: press **Watch** again, or `watch-trending {"on": true, "by": + "operator"}`. An agent's ask to switch it on is refused. /review lists it. - **New posts of a watched topic get their media at once.** After a read into a watched topic, one capture job takes the read's new posts: their media only, from the CDN, with no page opened. The same job takes the topic's posts whose media an earlier capture left owed, and its posts that have media and were never captured (so @@ -777,7 +784,8 @@ pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","o - **Gone from the page.** A post a page showed before and does not show at a read that reached the page's end is recorded `gone` with that read's time, and shown as "Gone from the page at …". It is not called deleted: a trending page is a ranked list, and a post leaves it by being outranked too. The end has to be in the capture: - the page was asked for more and answered with nothing new, and no answer failed or was dropped. A read that + the page asked for more from the bottom (the request carries the previous answer's bottom cursor) and got + nothing new, and no answer failed, was dropped or carried errors. A read that stopped at a cap, was cancelled, failed, or simply stopped getting answers says nothing. A post shown again is no longer gone, and the absence is kept as history. - **A watch ends** at its end time, when it is switched off, or when X no longer has the topic's last trending page (trending pages expire); each with a sentence in `get trending` (`watch.sentence`). diff --git a/common/controller/capturePosts.test.ts b/common/controller/capturePosts.test.ts @@ -656,9 +656,8 @@ test("an X trending library's logged-in fallback asks, per post and at that mome shots: false, articles: false, context: false, libraryMedia: { fallback: "login", - maxVideoBytes: null, // 8002 was dropped after the job was queued. - mayLogin: async (id: string) => (asked.push(id), id === "8001"), + isKept: async (id: string) => (asked.push(id), id === "8001"), deps: { cooldownMs: async () => 0, pause: async () => {} }, }, }); diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -140,11 +140,14 @@ export type CapturePostsOptions = { // maxVideoBytes a file over this is owed, not kept; null = no cap (a // kept post). Default: the library's `maxVideoMb`. // deps tests and the e2e test server: the fetch and the waits. - // mayLogin asked immediately before each logged-in download: - // whether the post is STILL marked keep (review 1 M4). + // isKept whether a post is STILL marked keep, asked once per + // post before its media (review 1 M4, review 2 N3): only + // then has it no per-file cap and the logged-in fallback. + // With it, `maxVideoBytes` is the cap of a post that is + // no longer kept (the library's, by default). libraryMedia?: { fallback?: "login" | "none"; - mayLogin?: (id: string) => Promise<boolean>; + isKept?: (id: string) => Promise<boolean>; maxVideoBytes?: number | null; deps?: Partial<LibraryMediaDeps>; }; @@ -547,7 +550,7 @@ async function libraryMediaDownloader( expected, maxVideoBytes: asked?.maxVideoBytes === undefined ? xTrendingMaxVideoBytes(config) : asked.maxVideoBytes, fallback: asked?.fallback ?? "none", - ...(asked?.mayLogin ? { mayLogin: asked.mayLogin } : {}), + ...(asked?.isKept ? { isKept: asked.isKept } : {}), deps: { fetch: (url, init) => fetch(url, init) as unknown as ReturnType<MediaFetch>, pauseMs: () => libraryMediaPauseMs(), diff --git a/common/controller/readXTrending.test.ts b/common/controller/readXTrending.test.ts @@ -15,6 +15,7 @@ import { FIXTURE_TIMELINE_OP, FIXTURE_TREND_ID, FIXTURE_TREND_URL, + fixtureContinuation, fixtureTimelineBody, fixtureTrendingResponses, } from "../social/__fixtures__/xTrendingCapture"; @@ -160,7 +161,7 @@ test("a re-read adds the new posts, keeps the old ones, and appends the read wit const first = fixtureTrendingResponses(); await run(paths, { load: first.load, scrolls: [] }); // The page's end, as the capture shows it: asked for more, the timeline had none. - const nothingMore = { url: first.scrolls[0][0].url, status: 200, body: fixtureTimelineBody([]) }; + const nothingMore = fixtureContinuation(); const again = await run( paths, { load: [first.scrolls[0][0]], scrolls: [[nothingMore]] }, @@ -577,6 +578,9 @@ test("S2: a read that went idle without the capture showing the page's end marks assert.equal(silent.result.outcome, "read"); assert.equal(silent.result.gone, undefined); assert.doesNotMatch(silent.result.sentence, /gone from the page/); + // An answer with nothing new that was not asked from the bottom (review 2 N4): nothing. + const fromTop = await reread("s2-from-top", { load: [timeline], scrolls: [[{ url: first.load[1].url, status: 200, body: fixtureTimelineBody([]) }], []] }); + assert.equal(fromTop.result.gone, undefined); // The next page answered 500: the read still ends idle, and asserts nothing. const failed = await reread("s2-failed", { load: [timeline], scrolls: [[{ url: timeline.url, status: 500, text: "upstream error" }], []] }); assert.equal(failed.result.stop, "idle"); @@ -584,10 +588,10 @@ test("S2: a read that went idle without the capture showing the page's end marks // ...even when an empty page follows the failure. const after500 = await reread("s2-failed-then-empty", { load: [timeline], - scrolls: [[{ url: timeline.url, status: 500, text: "upstream error" }], [{ url: timeline.url, status: 200, body: fixtureTimelineBody([]) }]], + scrolls: [[{ url: timeline.url, status: 500, text: "upstream error" }], [fixtureContinuation()]], }); assert.equal(after500.result.gone, undefined); // Asked for more and answered "none", cleanly: the page's end. - const ended = await reread("s2-end", { load: [timeline], scrolls: [[{ url: timeline.url, status: 200, body: fixtureTimelineBody([]) }], []] }); + const ended = await reread("s2-end", { load: [timeline], scrolls: [[fixtureContinuation()], []] }); assert.deepEqual([...(ended.result.gone ?? [])].sort(), ["1900000000000001001", "1900000000000001002"]); }); diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts @@ -128,6 +128,11 @@ export type ReadXTrendingAsk = { posts?: unknown; probe?: boolean; headed?: boolean; + // THIS READ IS A WATCH'S TICK (controller/xTrendingWatch.ts): nobody is + // there when it starts, so the watch's own jar rule is asked again at its + // start (runXTrendingRead `watchRefusal`). Set by the scan only — the ops + // route does not take it. + watch?: boolean; }; export type ReadXTrendingPlan = @@ -140,6 +145,7 @@ export type ReadXTrendingPlan = topic?: string; probe: boolean; headed: boolean; + watch?: boolean; } | { mode: "reparse"; slug: string; channelRoot: string; record: XTrendingReadRecord; topic?: string }; @@ -256,6 +262,7 @@ export async function planReadXTrending( ...(topic ? { topic } : {}), probe: ask.probe === true, headed: ask.headed === true, + ...(ask.watch === true ? { watch: true } : {}), }, }; } @@ -278,6 +285,10 @@ export type ReadXTrendingResult = { operations: XTrendingReadOperation[]; posts: { onPage: number; added: number }; topic?: { id: string; title: string; created?: boolean }; + // A watch's tick that was NOT read, because the watch's jar rule refused it + // at the job's start: no browser opened, nothing asked of X. It is neither + // a read nor a failed read (the watch counts no strike for it). + watchRefused?: { reason: string; sentence: string }; // The posts this read added to the library (ids), and the posts the page // showed before and did not show now — "gone from the page", said only by a // read that reached the page's end, and never meaning deleted. @@ -375,6 +386,13 @@ export type ReadXTrendingDeps = { noteRateLimit?: () => Promise<number>; // For tests: the capture → library step (default: ingestCapture). ingest?: typeof ingestCapture; + // A WATCH'S TICK, AT ITS START (review 2 N1): why the watch may not read + // now, by its own jar rule (xTrendingWatch.ts refuseWatchJob), or null. The + // scan asked when it queued the tick; the job may start much later (X's + // gap, another X job ahead of it), and the guard a person's job meets lets + // through what a watch must not. A plan marked `watch` with no check here + // does not run. + watchRefusal?: () => Promise<{ reason: string; sentence: string } | null>; }; export async function runXTrendingRead(o: { @@ -403,6 +421,16 @@ export async function runXTrendingRead(o: { // A Connect or a Refresh holds the profile: asked again here, at the start. const busy = deps.profileBusy?.() ?? null; if (busy) return { ...base, ...none, ok: false, outcome: "error", sentence: busy, error: busy }; + if (plan.watch) { + const refused = deps.watchRefusal + ? await deps.watchRefusal() + : { reason: "refused", sentence: "This watch tick was started with no check of X's cookie jar, so it is not run." }; + if (refused) { + const sentence = `This watch tick was not read (no browser was opened, X was asked nothing): ${refused.sentence}`; + log(sentence); + return { ...base, ...none, ok: false, outcome: "error", sentence, error: sentence, watchRefused: refused }; + } + } // And X's cooldown, asked again here: a read queued before a rate limit // does not navigate X when its turn comes. const held = await (deps.held ?? (() => xTrendingHeld(paths, now())))(); @@ -421,6 +449,7 @@ export async function runXTrendingRead(o: { endedAt: startedAt, probe: plan.probe, headed: plan.headed, + ...(plan.watch ? { watch: true as const } : {}), limits: plan.limits, scrolls: 0, stop: "started", @@ -438,7 +467,8 @@ export async function runXTrendingRead(o: { log( `Reading ${plan.ref.url} for ${plan.slug} (${plan.headed ? "in a window" : "headless"}; ` + `at most ${plural(plan.limits.scrolls, "scroll")}, ${plural(plan.limits.posts, "post")})` + - (plan.probe ? " — a probe: the capture is saved, no post is written." : "."), + (plan.probe ? " — a probe: the capture is saved, no post is written." : ".") + + (plan.watch ? " A watch's tick." : ""), ); const dir = trendingReadDir(plan.channelRoot, readId); const page: TrendingPageRead = await readXTrendingPage({ @@ -588,6 +618,7 @@ export async function runXTrendingRead(o: { endedAt: new Date(now()).toISOString(), probe: plan.probe, headed: plan.headed, + ...(plan.watch ? { watch: true as const } : {}), limits: plan.limits, scrolls: page.scrolls, stop: page.stop, diff --git a/common/controller/xTrendingWatch.test.ts b/common/controller/xTrendingWatch.test.ts @@ -509,3 +509,41 @@ test("S6: two asks for a scan at once are one scan and one read", async () => { await runXTrendingWatchScan(deps); assert.equal(h.ticks.length, 2); }); + +// Review 2 N5. +test("N5: only the operator starts a failing watch again; an enqueue does not erase a failing pause set meanwhile", async () => { + const paths = await corpus({ lib: { Kettles: [1] } }); + await on(paths, "Kettles"); + const dir = root(paths); + const h = harness(paths, ["lib"]); + // While the tick is being enqueued, three reads end badly: the watch is failing. + const enqueue = h.deps.enqueue; + h.deps.enqueue = async (tick) => { + for (let i = 0; i < 3; i++) await noteXTrendingWatchRead(dir, { trendId: trend(1).trendId, outcome: "error", now: h.state.now }); + return enqueue(tick); + }; + assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.topic, "kettles"); + let w = (await readXTrendingWatches(dir)).kettles; + assert.equal(w.paused?.reason, "failing"); + assert.equal(w.ticks, 1); + // The same when the enqueue is refused: the failing pause is not overwritten. + h.deps.enqueue = async () => ({ ok: false, error: "refused for another reason" }); + await on(paths, "Kettles", { by: "operator", now: h.state.now }); + h.deps.enqueue = async () => { + for (let i = 0; i < 3; i++) await noteXTrendingWatchRead(dir, { trendId: trend(1).trendId, outcome: "error", now: h.state.now }); + return { ok: false, error: "refused for another reason" }; + }; + h.state.now = T0 + 31 * MIN; + await scanXTrendingWatches(h.deps); + assert.equal((await readXTrendingWatches(dir)).kettles.paused?.reason, "failing"); + // An agent cannot switch it on again... + const agent = await on(paths, "Kettles", { by: "agent", now: h.state.now }); + assert.equal(agent.ok, false); + assert.match(agent.ok ? "" : agent.error, /is paused because its reads kept failing .* Only the operator starts it again/); + assert.equal((await readXTrendingWatches(dir)).kettles.paused?.reason, "failing"); + // ...the operator can. + const op = await on(paths, "Kettles", { by: "operator", now: h.state.now }); + assert.equal(op.ok, true); + w = (await readXTrendingWatches(dir)).kettles; + assert.deepEqual([w.paused, w.failures], [undefined, 0]); +}); diff --git a/common/controller/xTrendingWatch.ts b/common/controller/xTrendingWatch.ts @@ -175,6 +175,37 @@ export async function watchRefusal(paths: Paths, slug: string, now: number, deps return held ? { reason: "cooldown", sentence: held } : null; } +// THE LIVE WATCHES OF A LIBRARY, PAUSED for a refusal met outside the scan (a +// watch's job at its start). A watch paused for failing keeps that pause. +// Answers how many it paused. +export async function pauseXTrendingWatches(channelRoot: string, refusal: WatchRefusal, now: number): Promise<number> { + const at = new Date(now).toISOString(); + return mutateXTrendingWatches(channelRoot, (watches) => { + let n = 0; + for (const w of Object.values(watches)) { + if (!watchIsLive(w) || w.paused?.reason === "failing" || w.paused?.reason === refusal.reason) continue; + w.paused = { reason: refusal.reason, since: at, sentence: refusal.sentence }; + n++; + } + return { write: n > 0, result: n }; + }); +} + +// A WATCH'S JOB, AT ITS START (review 2 N1) — its tick's read, and the capture +// that follows a read into a watched topic. The scan asks the watch's jar rule +// when it queues a tick, but a job starts when its turn on X's queue comes: a +// tick queued on a 58-minute jar behind another X job starts on a 78-minute +// one, and the guard every X job meets at its start lets that through when +// the cookie-age setting is 0 or the login comes from the browser. So the +// watch's own rule is asked AGAIN here, at the moment the job would touch X. +// A refusal pauses the library's watches (as the scan would have) and is +// answered; the caller then starts nothing. +export async function refuseWatchJob(paths: Paths, slug: string, now: number = Date.now(), deps: WatchRefusalDeps = {}): Promise<WatchRefusal | null> { + const refusal = await watchRefusal(paths, slug, now, deps); + if (refusal) await pauseXTrendingWatches(path.join(paths.channelsDir, slug), refusal, now).catch(() => 0); + return refusal; +} + export const WATCH_JAR_NOTE = "A watch runs only while X's cookie jar is fresh: it resumes at the first scan after Refresh cookies on /cookies."; @@ -306,11 +337,18 @@ export async function scanXTrendingWatches(deps: WatchScanDeps): Promise<WatchSc w.nextTickAt = new Date(now + interval + Math.max(0, (deps.jitter ?? ((ms) => jitterMs(ms) - ms))(interval))).toISOString(); w.ticks++; w.nextSource = (w.nextSource + 1) % 1_000_000; - delete w.paused; + // ONLY THE PAUSE THIS ENQUEUE RESOLVES (review 2 N5): a read that was + // refused before is taken now. The file is read again under the lock + // here, and a pause set meanwhile for another reason — "failing", by a + // read that ended while this one was being queued — is not this scan's + // to erase. + if (w.paused?.reason === "refused") delete w.paused; } else { // Not asked again every minute: the next try is an interval away. w.nextTickAt = new Date(now + interval).toISOString(); - w.paused = { reason: "refused", since: w.paused?.reason === "refused" ? w.paused.since : at, sentence: started.error }; + if (w.paused?.reason !== "failing") { + w.paused = { reason: "refused", since: w.paused?.reason === "refused" ? w.paused.since : at, sentence: started.error }; + } } return { write: true, result: null }; }); diff --git a/common/controller/xTrendingWatchJob.test.ts b/common/controller/xTrendingWatchJob.test.ts @@ -0,0 +1,165 @@ +// Review 2 N1: a watch's job asks the watch's own jar rule AT ITS START, over a +// real settings file and a real (made-up) exported jar — the two cases the +// guard every X job meets lets through: a cookie-age setting of 0, and the +// browser as the login source. No browser opens and nothing is asked of X. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/xTrendingWatchJob.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "x-trending-watch-job-")); +process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { guardNetworkJob } = await import("../jobs/networkGuard"); +const { recordXTrendingRead, readXTrendingTopics, writeXTrendingPosts } = await import("../lib/xTrending/store"); +const { readXTrendingWatches, setXTrendingWatch } = await import("../lib/xTrending/watch"); +const { refuseWatchJob, noteXTrendingWatchRead } = await import("./xTrendingWatch"); +const { planReadXTrending, runXTrendingRead } = await import("./readXTrending"); +const { FIXTURE_TREND_ID, FIXTURE_TREND_URL } = await import("../social/__fixtures__/xTrendingCapture"); + +const paths = getPaths(); +const SLUG = "trending"; +const root = path.join(paths.channelsDir, SLUG); +const jar = path.join(paths.transcriptsDir, ".x-session", "cookies.txt"); +const MIN = 60_000; + +mkdirSync(root, { recursive: true }); +writeFileSync(path.join(root, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", name: "Trending", xTrending: {} })); +mkdirSync(path.join(paths.transcriptsDir, ".x-session", "profile"), { recursive: true }); +writeFileSync(jar, "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tfixture-not-a-real-token\n"); +await writeXTrendingPosts(root, [ + { id: "9001", slug: `${SLUG}/9001`, channelSlug: SLUG, author: "a", createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text: "t", url: "https://x.com/a/status/9001", platform: "twitter", isReply: false, isRepost: false, links: [] }, +]); +await recordXTrendingRead(root, { readId: "tr-01JA0000000000000000000000", at: "2026-11-17T10:00:00.000Z", ref: { trendId: FIXTURE_TREND_ID, url: FIXTURE_TREND_URL }, topic: "Kettles", postIds: ["9001"], added: 1 }); + +// The two settings under which the guard's own start check lets an old jar through. +const EXEMPT: Record<string, unknown> = { + "the cookie-age setting is 0": { social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 0 } } }, + "the login comes from the browser": { social: { x: { cookieSource: "browser", maxCookieAgeMinutes: 60 } }, cookiesFromBrowser: "firefox" }, +}; + +async function watchOn(): Promise<void> { + const set = await setXTrendingWatch(root, { topics: await readXTrendingTopics(root), topic: "kettles", on: true, intervalMinutes: 30, hours: 48, by: "operator", maxTopics: 4, now: Date.now() }); + assert.equal(set.ok, true); +} + +const jarAged = (minutes: number) => { + const at = new Date(Date.now() - minutes * MIN); + utimesSync(jar, at, at); +}; + +for (const [name, settings] of Object.entries(EXEMPT)) { + test(`N1: a watch tick whose turn comes on a 78-minute jar is not read, though the guard would start it — ${name}`, async () => { + writeFileSync(paths.settingsFile, JSON.stringify(settings)); + await watchOn(); + // Queued on a 58-minute jar: the watch's rule lets it be queued. + jarAged(58); + assert.equal(await refuseWatchJob(paths, SLUG), null); + const planned = await planReadXTrending(paths, { slug: SLUG, url: FIXTURE_TREND_URL, watch: true }, { hasProfile: async () => true, held: async () => null }); + assert.equal(planned.ok, true); + if (!planned.ok || planned.plan.mode !== "read") return; + assert.equal(planned.plan.watch, true); + // Twenty minutes behind another X job: 78 minutes. The guard an X job meets at its start still says yes... + jarAged(78); + const guard = await guardNetworkJob({ kind: "read-x-trending", queueKey: "platform:twitter", paths, channelSlug: SLUG, job: { id: "j1" } }); + assert.equal(guard.ok, true, "the control: the guard alone would start this job"); + // ...and the watch's own rule, asked at the job's start, says no: no browser opens. + let opened = 0; + const log: string[] = []; + const result = await runXTrendingRead({ + paths, + plan: planned.plan, + onLog: (l) => log.push(l), + deps: { + openPage: async () => { + opened++; + throw new Error("no browser may open"); + }, + held: async () => null, + watchRefusal: () => refuseWatchJob(paths, SLUG), + }, + }); + assert.equal(opened, 0); + assert.equal(result.ok, false); + assert.equal(result.watchRefused?.reason, "jar"); + assert.match(result.sentence, /^This watch tick was not read \(no browser was opened, X was asked nothing\): X cookies were last refreshed 78 min ago \(limit 60 min for a watch\)/); + // The watch is paused for the jar, and it is no strike against it. + const w = (await readXTrendingWatches(root)).kettles; + assert.deepEqual([w.paused?.reason, w.failures], ["jar", 0]); + + // THE FOLLOW-UP CAPTURE asks the same question before it is queued and when it starts. + await watchOn(); + assert.equal((await readXTrendingWatches(root)).kettles.paused?.reason, "jar"); + const followUp = await refuseWatchJob(paths, SLUG); + assert.equal(followUp?.reason, "jar"); + assert.match(followUp?.sentence ?? "", /78 min ago \(limit 60 min for a watch\)/); + // Refreshed: both go ahead. + jarAged(1); + assert.equal(await refuseWatchJob(paths, SLUG), null); + }); +} + +test("N1: a read marked as a watch's with no check at its start does not run; a person's read is not asked the watch's rule", async () => { + writeFileSync(paths.settingsFile, JSON.stringify(EXEMPT["the cookie-age setting is 0"])); + jarAged(78); + const plan = async (watch: boolean) => { + const p = await planReadXTrending(paths, { slug: SLUG, url: FIXTURE_TREND_URL, ...(watch ? { watch: true } : {}) }, { hasProfile: async () => true, held: async () => null }); + assert.equal(p.ok, true); + return (p as { plan: Parameters<typeof runXTrendingRead>[0]["plan"] }).plan; + }; + let opened = 0; + const openPage = async () => { + opened++; + throw new Error("stop here"); + }; + const unchecked = await runXTrendingRead({ paths, plan: await plan(true), deps: { openPage, held: async () => null } }); + assert.equal(opened, 0); + assert.match(unchecked.sentence, /started with no check of X's cookie jar, so it is not run/); + // A person's read (no `watch`) goes on to open the page: the setting is the person's choice. + const person = await runXTrendingRead({ paths, plan: await plan(false), deps: { openPage, held: async () => null, noteOutcome: async () => null } }); + assert.equal(opened, 1); + assert.equal(person.watchRefused, undefined); + // (That failed read is told to the watch as any read is.) + await noteXTrendingWatchRead(root, { trendId: FIXTURE_TREND_ID, outcome: person.outcome }); +}); + +test("N1: a watch's tick on a fresh jar is read as any read, and its record and log say it was a watch's", async () => { + const { fakeTrendingPage } = await import("../social/fakeXProfileBrowser"); + const { fixtureTrendingResponses } = await import("../social/__fixtures__/xTrendingCapture"); + const { readXTrendingReadRecord } = await import("../lib/xTrending/store"); + writeFileSync(paths.settingsFile, JSON.stringify({ social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 60 } } })); + jarAged(5); + const planned = await planReadXTrending(paths, { slug: SLUG, url: FIXTURE_TREND_URL, watch: true }, { hasProfile: async () => true, held: async () => null }); + assert.equal(planned.ok, true); + if (!planned.ok || planned.plan.mode !== "read") return; + const page = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() })); + const log: string[] = []; + let asked = 0; + const READ = "tr-01JW0000000000000000000000"; + const result = await runXTrendingRead({ + paths, + plan: planned.plan, + onLog: (l) => log.push(l), + deps: { + openPage: async () => ({ page, close: async () => {} }), + held: async () => null, + pauseMs: () => 0, + pause: async () => {}, + readId: READ, + noteOutcome: async () => null, + watchRefusal: async () => (asked++, refuseWatchJob(paths, SLUG)), + }, + }); + assert.equal(asked, 1); + assert.equal(result.outcome, "read"); + assert.equal(result.watchRefused, undefined); + assert.equal((await readXTrendingReadRecord(root, READ))?.watch, true); + assert.ok(log.some((l) => / A watch's tick\.$/.test(l)), log[0]); +}); diff --git a/common/social/__fixtures__/xTrendingCapture.ts b/common/social/__fixtures__/xTrendingCapture.ts @@ -95,7 +95,7 @@ export function fixtureTimelineBody(tweets: FixtureTweet[]): Record<string, unkn data: { timeline: { instructions: [ - { type: "TimelineAddEntries", entries: [...tweets.map(entry), { entryId: "cursor-bottom-1", content: { entryType: "TimelineTimelineCursor", value: "fixture-cursor" } }] }, + { type: "TimelineAddEntries", entries: [...tweets.map(entry), { entryId: "cursor-bottom-1", content: { entryType: "TimelineTimelineCursor", cursorType: "Bottom", value: FIXTURE_BOTTOM_CURSOR } }] }, ], }, }, @@ -120,8 +120,20 @@ export const FIXTURE_SECOND_PAGE: FixtureTweet[] = [ { id: "1900000000000001005", handle: "lid_watch", text: "A reply about the queue.", replyTo: { id: "1900000000000001001", handle: "teapot_news" }, media: ["animated_gif"] }, ]; -const graphqlUrl = (op: string, n: number) => - `https://x.com/i/api/graphql/fixtureQueryId${n}/${op}?variables=%7B%22rest_id%22%3A%22${FIXTURE_TREND_ID}%22%7D`; +// The bottom cursor every fixture timeline answer ends with, and which the +// page's next request for that timeline carries. +export const FIXTURE_BOTTOM_CURSOR = "fixture-cursor"; + +const graphqlUrl = (op: string, n: number, cursor?: string) => + `https://x.com/i/api/graphql/fixtureQueryId${n}/${op}?variables=${encodeURIComponent( + JSON.stringify({ rest_id: FIXTURE_TREND_ID, ...(cursor ? { cursor } : {}) }), + )}`; + +// The page asking its timeline for MORE: the request carries the bottom cursor +// of the answer before it. With no post it is how a page's end looks. +export function fixtureContinuation(tweets: FixtureTweet[] = [], n = 9, cursor: string = FIXTURE_BOTTOM_CURSOR): FixtureResponse { + return { url: graphqlUrl(FIXTURE_TIMELINE_OP, n, cursor), status: 200, body: fixtureTimelineBody(tweets) }; +} export type FixtureResponse = { url: string; status: number; body?: unknown; text?: string }; @@ -136,6 +148,6 @@ export function fixtureTrendingResponses(): { load: FixtureResponse[]; scrolls: // Another surface's posts: saved, never read as the page's. { url: graphqlUrl("HomeTimeline", 3), status: 200, body: fixtureTimelineBody([{ id: "1900000000000007777", handle: "home_only", text: "Not on the trending page." }]) }, ], - scrolls: [[{ url: graphqlUrl(FIXTURE_TIMELINE_OP, 4), status: 200, body: fixtureTimelineBody(FIXTURE_SECOND_PAGE) }], [], []], + scrolls: [[fixtureContinuation(FIXTURE_SECOND_PAGE, 4)], [], []], }; } diff --git a/common/social/xTrendingMedia.test.ts b/common/social/xTrendingMedia.test.ts @@ -359,19 +359,21 @@ test("S9: three refusals in a row (a 403, or no answer) and the job asks the CDN assert.deepEqual((res.ok ? [] : res.files ?? []).map((f) => f.name), ["791_3.jpg", "791_7.jpg"]); }); -// Review 1 M4. -test("M4: the logged-in download is asked for only while the post is STILL kept, checked right before it", async () => { - const h = harness("still-kept", {}); - const kept = new Set(["801"]); +// Review 1 M4, review 2 N3: one predicate, once per post, before its media. +test("M4/N3: a post still kept has no cap and the logged-in download; one dropped since the job was queued has neither", async () => { + const big = "0123456789ABCDEFGHIJ"; + const h = harness("still-kept", { [vid("K").fetchUrl]: { body: big }, [vid("D").fetchUrl]: { body: big } }); + const kept = new Set(["801", "803"]); const asked: string[] = []; const log: string[] = []; const download = createLibraryMediaDownloader({ channelRoot: h.root, - sources: new Map(), - expected: new Map([["801", 1], ["802", 1]]), - maxVideoBytes: null, + // 801 and 802: a video over the library's cap. 803 and 804: media the capture names no address for. + sources: new Map([["801", [vid("K")]], ["802", [vid("D")]]]), + expected: new Map([["801", 1], ["802", 1], ["803", 1], ["804", 1]]), + maxVideoBytes: 10, fallback: "login", - mayLogin: async (id) => (asked.push(id), kept.has(id)), + isKept: async (id) => (asked.push(id), kept.has(id)), deps: h.deps, }); let logins = 0; @@ -381,16 +383,27 @@ test("M4: the logged-in download is asked for only while the post is STILL kept, writeFileSync(path.join(dir, `${id}_1.jpg`), "VIA-LOGIN"); return { ok: true, files: [{ name: `${id}_1.jpg` }] }; }; - assert.equal((await download(h.args("801"), login)).ok, true); - // 802 was kept when the job was queued and dropped since: no login for it. - const dropped = await download({ ...h.args("802"), onLog: (l) => void log.push(l) }, login); - assert.equal(logins, 1); - assert.deepEqual(asked, ["801", "802"]); + const withLog = (id: string) => ({ ...h.args(id), onLog: (l: string) => void log.push(l) }); + // Kept: the whole video, over the cap or not. + assert.equal((await download(withLog("801"), login)).ok, true); + assert.equal(readFileSync(path.join(h.dirOf("801"), "801_1.mp4"), "utf8"), big); + // Dropped since: the cap applies — the uncapped download is not its any more. + const dropped = await download(withLog("802"), login); assert.equal(dropped.ok, false); if (!dropped.ok) { assert.equal(dropped.owed, "kept"); - assert.match(dropped.error, /802: no longer marked keep: the logged-in download is not run for it/); + assert.match(dropped.error, /802_1\.mp4: it is .*over the 1 MB cap: owed until the post is kept/); } - assert.ok(log.includes("802: no longer marked keep: the logged-in download is not run for it.")); assert.deepEqual(readdirSync(h.dirOf("802")), []); + // Kept, nothing on the CDN: the logged-in download. + assert.equal((await download(withLog("803"), login)).ok, true); + assert.equal(logins, 1); + // Dropped since, nothing on the CDN: no login for it. + const noLogin = await download(withLog("804"), login); + assert.equal(logins, 1); + assert.equal(noLogin.ok, false); + if (!noLogin.ok) assert.equal(noLogin.owed, "kept"); + // Asked once per post, before its media. + assert.deepEqual(asked, ["801", "802", "803", "804"]); + assert.equal(log.filter((l) => /no longer marked keep: its media is fetched as any post's/.test(l)).length, 2); }); diff --git a/common/social/xTrendingMedia.ts b/common/social/xTrendingMedia.ts @@ -107,10 +107,15 @@ export type LibraryMediaOptions = { // A file over this is owed, not kept. null: no cap (a kept post). maxVideoBytes: number | null; fallback: "login" | "none"; - // Asked IMMEDIATELY BEFORE each logged-in download (review 1 M4): whether - // this post is still marked keep. A post dropped since the job was queued - // gets none. Absent: the fallback is as `fallback` says. - mayLogin?: (id: string) => Promise<boolean>; + // IS THIS POST STILL MARKED KEEP? — ONE predicate, asked once per post, + // before any of its media (review 1 M4, review 2 N3). A capture of kept + // posts is queued when they are kept and may start minutes later; a post + // dropped meanwhile gets NEITHER of the things keeping buys: its media is + // fetched under `maxVideoBytes` like any post's (no uncapped download), and + // no logged-in download is run for it. A post still kept has no per-file + // cap and the fallback `fallback` says. Absent: every post is fetched as + // `maxVideoBytes` and `fallback` say. + isKept?: (id: string) => Promise<boolean>; maxFiles?: number; maxBytes?: number; deps: LibraryMediaDeps; @@ -227,8 +232,10 @@ export function createLibraryMediaDownloader( const now = deps.now ?? Date.now; const maxFiles = o.maxFiles ?? LIBRARY_MEDIA_MAX_FILES; const maxBytes = o.maxBytes ?? LIBRARY_MEDIA_MAX_BYTES; - const cap = Math.min(o.maxVideoBytes ?? LIBRARY_MEDIA_HARD_MAX_BYTES, LIBRARY_MEDIA_HARD_MAX_BYTES); - const capIsHard = o.maxVideoBytes === null || o.maxVideoBytes >= LIBRARY_MEDIA_HARD_MAX_BYTES; + const capFor = (maxVideoBytes: number | null) => ({ + cap: Math.min(maxVideoBytes ?? LIBRARY_MEDIA_HARD_MAX_BYTES, LIBRARY_MEDIA_HARD_MAX_BYTES), + capIsHard: maxVideoBytes === null || maxVideoBytes >= LIBRARY_MEDIA_HARD_MAX_BYTES, + }); const budget = { files: 0, bytes: 0 }; let saidSpent = false; // Refusals in a row, across the job's posts; and whether the job has @@ -247,6 +254,11 @@ export function createLibraryMediaDownloader( const why = xRateLimitHoldSentence("media fetch", cooling, now()); return { ok: false, owed: "next", error: why, stop: why }; } + // Still kept? Asked now, once, before anything of this post is fetched. + const kept = o.isKept ? await o.isKept(id).catch(() => false) : null; + if (kept === false) log(`${id}: no longer marked keep: its media is fetched as any post's (the per-file cap applies, no logged-in download).`); + const { cap, capIsHard } = capFor(kept === true ? null : o.maxVideoBytes); + const mayLogin = o.fallback === "login" && kept !== false; const sources = o.sources.get(id) ?? []; const expected = o.expected?.get(id) ?? sources.length; const files: { name: string; url?: string }[] = []; @@ -347,20 +359,14 @@ export function createLibraryMediaDownloader( if (sources.length < expected && !stop) { problems.push( `${expected - sources.length} of its ${expected} media file(s) have no CDN address in the saved capture` + - (o.fallback === "login" ? "" : ": owed until the post is kept"), + (mayLogin ? "" : ": owed until the post is kept"), ); - if (o.fallback === "login") failed = true; + if (mayLogin) failed = true; else owedKept = true; } // A kept post the CDN could not serve whole: the fetcher's own logged-in // download, once, and what it lands is taken into the store. - if (failed && !stop && o.fallback === "login") { - // Still kept? Asked now, not when the job was queued (review 1 M4). - if (o.mayLogin && !(await o.mayLogin(id).catch(() => false))) { - const why = `${id}: no longer marked keep: the logged-in download is not run for it`; - log(`${why}.`); - return { ok: false, owed: "kept", error: [...problems, why].join("; "), files }; - } + if (failed && !stop && mayLogin) { log(`${id}: ${problems.join("; ")} — falling back to the logged-in download.`); const viaLogin = await login(args); for (const name of await listCapturedMediaFiles(dir)) { diff --git a/common/social/xTrendingParse.test.ts b/common/social/xTrendingParse.test.ts @@ -170,29 +170,50 @@ test("media sources: a picture at its original size, a video's highest-bitrate m assert.equal(mediaSourcesInCapture([line("HomeTimeline", 200), line("ExampleTrendTimeline", 500)]).size, 0); }); -// Review 1 S2. -test("S2: a capture shows the page's end only when its last timeline answer brought nothing new and no answer failed", async () => { - const { parseTrendingCapture } = await import("./xTrendingParse"); - const { fixtureTimelineBody } = await import("./__fixtures__/xTrendingCapture"); +// Review 1 S2, review 2 N4. +test("S2/N4: a capture shows the page's end only when the bottom-cursor continuation brought nothing new and no answer failed", async () => { + const { parseTrendingCapture, requestCursorOf, timelineShapeOf } = await import("./xTrendingParse"); + const { fixtureTimelineBody, FIXTURE_BOTTOM_CURSOR } = await import("./__fixtures__/xTrendingCapture"); + type Line = import("./xTrendingParse").TrendingCaptureLine; const t = (id: string) => ({ id, handle: "a", text: `post ${id}` }); let n = 0; - type Line = import("./xTrendingParse").TrendingCaptureLine; - const line = (op: string, status: number, body?: unknown): Line => ({ n: ++n, at: "x", op, status, url: "u", bytes: 1, ...(body === undefined ? {} : { body }) }); - const page = (ids: string[]) => line("ExampleTrendTimeline", 200, fixtureTimelineBody(ids.map(t))); + const url = (op: string, cursor?: string) => `https://x.com/i/api/graphql/q/${op}?variables=${encodeURIComponent(JSON.stringify({ rest_id: "1", ...(cursor ? { cursor } : {}) }))}`; + const line = (op: string, status: number, body?: unknown, cursor?: string): Line => ({ n: ++n, at: "x", op, status, url: url(op, cursor), bytes: 1, ...(body === undefined ? {} : { body }) }); + // The first page (no cursor), and a continuation from the bottom. + const first = (ids: string[]) => line("ExampleTrendTimeline", 200, fixtureTimelineBody(ids.map(t))); + const more = (ids: string[], cursor: string = FIXTURE_BOTTOM_CURSOR) => line("ExampleTrendTimeline", 200, fixtureTimelineBody(ids.map(t)), cursor); const end = (lines: Line[]) => parseTrendingCapture(lines, "lib").pageEnd; - // Posts, then an answer with none: the end. - assert.equal(end([page(["1", "2"]), page([])]), true); - // The last answer repeated posts already seen and brought no new one: the end too. - assert.equal(end([page(["1", "2"]), page(["2"])]), true); - // The last answer still brought a new post: nothing says there was no more. - assert.equal(end([page(["1", "2"]), page(["3"])]), false); - assert.equal(end([page(["1", "2"])]), false); + assert.equal(requestCursorOf(url("Op", "abc")), "abc"); + assert.equal(requestCursorOf(url("Op")), undefined); + assert.equal(requestCursorOf("not a url"), undefined); + assert.deepEqual(timelineShapeOf(fixtureTimelineBody([])), { instructions: true, bottom: FIXTURE_BOTTOM_CURSOR }); + assert.deepEqual(timelineShapeOf({ data: {} }), { instructions: false }); + + // Posts, then the continuation from the bottom with none: the end. + assert.equal(end([first(["1", "2"]), more([])]), true); + // ...or with only posts already seen. + assert.equal(end([first(["1", "2"]), more(["2"])]), true); + // The continuation still brought a new post: nothing says there was no more. + assert.equal(end([first(["1", "2"]), more(["3"])]), false); + assert.equal(end([first(["1", "2"])]), false); + // N4: an answer with nothing new that is NOT the bottom continuation says nothing about the bottom — + // a refresh from the top (no cursor), or another cursor. + assert.equal(end([first(["1", "2"]), first(["1", "2"])]), false); + assert.equal(end([first(["1", "2"]), first([])]), false); + assert.equal(end([first(["1", "2"]), more([], "some-top-cursor")]), false); + // The answer before it named no bottom cursor: the capture cannot tell. + const noCursor = line("ExampleTrendTimeline", 200, { data: { timeline: { instructions: [{ type: "TimelineAddEntries", entries: [{ entryId: "tweet-1", content: { itemContent: { tweet_results: { result: { __typename: "Tweet", rest_id: "1", legacy: { id_str: "1", full_text: "x" } } } } } }] }] } } }); + assert.equal(end([noCursor, more([])]), false); // An answer that failed, or whose body was not kept: the capture cannot tell. - assert.equal(end([page(["1"]), line("ExampleTrendTimeline", 500), page([])]), false); - assert.equal(end([page(["1"]), { ...page([]), body: undefined, skipped: "too-large" as const }]), false); - assert.equal(end([page(["1"]), page([]), line("ExampleTrendPage", 429)]), false); + assert.equal(end([first(["1"]), line("ExampleTrendTimeline", 500), more([])]), false); + assert.equal(end([first(["1"]), { ...more([]), body: undefined, skipped: "too-large" as const }]), false); + assert.equal(end([first(["1"]), more([]), line("ExampleTrendPage", 429)]), false); + // N4: a 200 that carries GraphQL errors, or no timeline instructions, is a failed answer. + assert.equal(end([first(["1"]), line("ExampleTrendTimeline", 200, { ...fixtureTimelineBody([]), errors: [{ message: "Timeout: Unspecified" }] }, FIXTURE_BOTTOM_CURSOR)]), false); + assert.equal(end([first(["1"]), line("ExampleTrendTimeline", 200, { data: {} }, FIXTURE_BOTTOM_CURSOR)]), false); + assert.equal(end([first(["1"]), more([]), line("ExampleTrendPage", 200, { data: {}, errors: [{ message: "x" }] })]), false); // Another surface's failure is not the page's. - assert.equal(end([page(["1"]), page([]), line("HomeTimeline", 500)]), true); + assert.equal(end([first(["1"]), more([]), line("HomeTimeline", 500)]), true); // No post at all: no page to have an end. assert.equal(end([line("ExampleTrendPage", 200, { data: {} })]), false); }); diff --git a/common/social/xTrendingParse.ts b/common/social/xTrendingParse.ts @@ -238,6 +238,46 @@ export function mediaSourcesInCapture(lines: ReadonlyArray<TrendingCaptureLine>) return out; } +// The cursor a request carried: `variables` of the GraphQL URL, its `cursor`. +// Undefined when the URL has none or cannot be read. +export function requestCursorOf(url: string): string | undefined { + try { + const raw = new URL(url).searchParams.get("variables"); + const cursor = raw ? (JSON.parse(raw) as { cursor?: unknown } | null)?.cursor : undefined; + return typeof cursor === "string" && cursor ? cursor : undefined; + } catch { + return undefined; + } +} + +// What an answer says of its timeline: whether it carries instructions at all, +// and the BOTTOM cursor it ends with (the last one, when it names several). +export function timelineShapeOf(payload: unknown): { instructions: boolean; bottom?: string } { + let instructions = false; + let bottom: string | undefined; + const seen = new Set<unknown>(); + const visit = (node: unknown): void => { + if (!node || typeof node !== "object" || seen.has(node)) return; + seen.add(node); + if (Array.isArray(node)) { + for (const item of node) visit(item); + return; + } + const rec = node as Record<string, unknown>; + if (Array.isArray(rec.instructions)) instructions = true; + const value = typeof rec.value === "string" && rec.value ? rec.value : undefined; + if (value && rec.cursorType === "Bottom") bottom = value; + if (typeof rec.entryId === "string" && rec.entryId.startsWith("cursor-bottom")) { + const inner = obj(rec.content); + const v = inner?.value ?? obj(inner?.itemContent)?.value; + if (typeof v === "string" && v) bottom = v; + } + for (const child of Object.values(rec)) visit(child); + }; + visit(payload); + return { instructions, ...(bottom ? { bottom } : {}) }; +} + export type TrendingOperation = { op: string; responses: number; bytes: number; statuses: number[]; tweets: number }; export type ParsedTrendingCapture = { @@ -249,14 +289,18 @@ export type ParsedTrendingCapture = { operations: TrendingOperation[]; responses: number; bytes: number; - // THE CAPTURE SHOWS THE PAGE'S END (review 1 S2): every answer of the page - // was a 2xx whose body was kept, and the LAST answer of an operation that - // lists the page's posts brought no post the capture had not already seen — - // the page was asked for more and had none. False whenever the capture - // cannot tell: an answer that failed or was not kept (the next page may - // simply not have loaded), or a last answer that still brought new posts - // (nothing shows there was no more). Only a capture that shows the end may - // be read as "what this page no longer shows". + // THE CAPTURE SHOWS THE PAGE'S END (review 1 S2, review 2 N4). All of: + // - no answer of the page failed: every one a 2xx whose body was kept, + // carrying no GraphQL `errors`, and — for an operation that lists the + // page's posts — carrying timeline instructions; + // - the LAST answer of the listing operation is the CONTINUATION FROM THE + // BOTTOM: its request carries the bottom cursor the answer before it + // ended with (a refresh from the top, or any other cursor, that brings + // nothing new says nothing about the bottom); + // - and it brought no post the capture had not already seen. + // False whenever the capture cannot tell — which cursor an answer was for + // included. Only a capture that shows the end may be read as "what this + // page no longer shows". pageEnd: boolean; }; @@ -271,7 +315,7 @@ export function parseTrendingCapture( let bytes = 0; // Per answer of the page's own operations, in order: its operation, and how // many posts it brought that no earlier answer had. - const answers: Array<{ op: string; fresh: number }> = []; + const answers: Array<{ op: string; fresh: number; asked?: string; bottom?: string; instructions: boolean }> = []; const seenIds = new Set<string>(); let failed = false; for (const line of lines) { @@ -286,6 +330,9 @@ export function parseTrendingCapture( failed = true; continue; } + // A 200 that carries GraphQL errors answered only in part, or not at all. + const errors = obj(line.body)?.errors; + if (Array.isArray(errors) && errors.length > 0) failed = true; const found = collectTimelineTweets(line.body); op.tweets += found.length; let fresh = 0; @@ -299,11 +346,22 @@ export function parseTrendingCapture( const summary = mediaSummaryOf(raw); if (id && summary && !media[id]) media[id] = summary; } - answers.push({ op: line.op, fresh }); + const shape = timelineShapeOf(line.body); + const asked = requestCursorOf(line.url); + answers.push({ op: line.op, fresh, instructions: shape.instructions, ...(asked ? { asked } : {}), ...(shape.bottom ? { bottom: shape.bottom } : {}) }); } - // The last answer of an operation that ever listed posts. - const last = answers.filter((a) => (ops.get(a.op)?.tweets ?? 0) > 0).at(-1); - const pageEnd = !failed && last !== undefined && last.fresh === 0; + // The answers of the operations that ever listed posts, in order. + const listing = answers.filter((a) => (ops.get(a.op)?.tweets ?? 0) > 0); + if (listing.some((a) => !a.instructions)) failed = true; + const last = listing.at(-1); + // The answer before it of the same operation: whose bottom cursor it must carry. + const before = last ? listing.slice(0, -1).filter((a) => a.op === last.op).at(-1) : undefined; + const pageEnd = + !failed && + last !== undefined && + before?.bottom !== undefined && + last.asked === before.bottom && + last.fresh === 0; const posts = normalizeXTweets(raws, channelSlug); const kept: Record<string, TrendingMediaSummary> = {}; for (const p of posts) if (media[p.id]) kept[p.id] = media[p.id]; diff --git a/editor/app/api/ops/_xTrendingWatch.ts b/editor/app/api/ops/_xTrendingWatch.ts @@ -21,7 +21,8 @@ export function xTrendingWatchDeps(): WatchScanDeps { // 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 }); + // Marked as the watch's: its job asks the watch's jar rule at its start. + const started = await readXTrendingAction({ slug: tick.slug, url: tick.url, topic: tick.topic, watch: true }); if (!started.ok) return { ok: false, error: started.error }; void started.stream.cancel(); return { ok: true, jobId: started.jobId }; diff --git a/editor/app/api/ops/capture-posts/route.ts b/editor/app/api/ops/capture-posts/route.ts @@ -59,9 +59,9 @@ export const dynamic = "force-dynamic"; // 429 from the CDN stops the job and leaves X alone for 15 minutes; a 403 or a // 404 marks the file; nothing retries. `keptMedia: true` is for posts marked // keep (refused for any other id): no per-file cap, and a post the CDN cannot -// serve whole is downloaded the logged-in way — asked again of the judgements -// immediately before each such download, so a post dropped since the job was -// queued gets none. `judge-trending` runs it for the posts it marks keep. A +// serve whole is downloaded the logged-in way — the judgements are read again, +// once per post, before its media, so a post dropped since the job was queued +// gets neither: it is fetched under the library's cap, with no login. `judge-trending` runs it for the posts it marks keep. A // library's capture runs on X's queue only: `queueKey` is refused for it. Three // refusals in a row from the CDN (a 403, or no answer) and the job asks it for // no more; the rest is owed. diff --git a/editor/app/api/ops/judge-trending/route.ts b/editor/app/api/ops/judge-trending/route.ts @@ -24,9 +24,15 @@ export const dynamic = "force-dynamic"; // hand is the page's buttons, and slice 3's judge view). // AN AGENT'S JUDGEMENT IS A SUGGESTION: an agent's write over a // judgement the operator made is skipped for that id and named in -// `skipped`; the rest of the ask is written. A post the operator -// judged through its THREAD is the operator's too: an agent's -// post-level write for it is skipped. +// `skipped`; the rest of the ask is written. +// +// WHICH JUDGEMENT IS IN FORCE, one rule: the operator's entry, for the post or +// for its thread, always outranks an agent's about the same post, whatever +// the order in time; between two entries of the same hand, the post's own +// outranks its thread's. So an agent's post-level write is skipped whenever +// the post's thread is the operator's, and an operator's thread judgement +// overrides an agent's older entry for one of its posts at once (that entry +// stays in the file and decides nothing). // // `kept` names the posts whose judgement BECAME keep by this ask (their own, // or their thread's). A KEEP ARCHIVES THEM: one `capture-posts` job on X's diff --git a/editor/app/api/ops/watch-trending/route.ts b/editor/app/api/ops/watch-trending/route.ts @@ -35,16 +35,22 @@ export const dynamic = "force-dynamic"; // 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 +// cannot be read. It is asked when a tick is queued AND AGAIN WHEN THE TICK'S +// JOB STARTS (and when the capture that follows it is queued and starts): a +// job waits its turn on X's queue, and a tick whose turn comes on a jar past +// the limit is not read — no browser opens, the watch pauses, and it is no +// strike against it. The X alert, X cooling down after a rate limit and a // missing profile pause it the same way. // // 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. +// by itself, and only the OPERATOR ends it: switch the watch on again with +// `"by": "operator"` (the page's Watch button); an agent's ask is refused. // // 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`) +// the page's end (the page asked for more FROM THE BOTTOM — the request carries +// the previous answer's bottom cursor — and got nothing new, and no answer +// failed or carried errors) 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 diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -25,6 +25,7 @@ import { isXSearchChannel } from "yt-dlp-transcript-common/lib/xSearch/config"; import { isXTrendingChannel, X_TRENDING_NOT_FETCHED } from "yt-dlp-transcript-common/lib/xTrending/config"; import { readXTrendingPostIds } from "yt-dlp-transcript-common/lib/xTrending/store"; import { readXTrendingKeptIds } from "yt-dlp-transcript-common/lib/xTrending/judgements"; +import { refuseWatchJob } from "yt-dlp-transcript-common/controller/xTrendingWatch"; import { fakeXMediaFetch, fakeXProfileChromium } from "yt-dlp-transcript-common/social/fakeXProfileBrowser"; import { X_SEARCH_OLDER_REFUSAL } from "yt-dlp-transcript-common/controller/fetchXSearch"; import { WAYBACK_PAGES_NOT_FETCHED } from "yt-dlp-transcript-common/controller/fetchPosts"; @@ -363,9 +364,14 @@ export async function capturePostsAction( // no per-file cap and a post the CDN cannot serve whole is downloaded the // logged-in way. Refused for an id that is not kept. keptMedia?: boolean; + // An X trending library: this capture was queued BY A WATCH (the media of + // a watched topic's new posts), not asked for by a person. Its job asks + // the watch's own jar rule when it starts (review 2 N1), and starts + // nothing when that refuses. + watch?: boolean; } = {}, ): Promise<StreamActionResult> { - const { thread, avatars, avatarsOnly, context, contextOnly, keptMedia } = more; + const { thread, avatars, avatarsOnly, context, contextOnly, keptMedia, watch } = more; const redact = parseThreadRedact(more.threadRedact); if (!redact.ok) return { ok: false, error: redact.error }; const threadRedact = redact.value; @@ -438,6 +444,7 @@ export async function capturePostsAction( ...(context !== undefined ? { context } : {}), ...(contextOnly ? { contextOnly } : {}), ...(keptMedia ? { keptMedia } : {}), + ...(watch ? { watch } : {}), }, }, fn: async (onLog, signal, _progress, ctx) => { @@ -451,6 +458,15 @@ export async function capturePostsAction( const cooling = platform === "twitter" ? await platformCooldownRemainingMs("twitter", paths).catch(() => 0) : 0; const held = xCaptureStartRefusal({ platform, shots, avatarsOnly, contextOnly }, cooling); if (held) throw new Error(held); + // A WATCH'S CAPTURE ASKS THE WATCH'S JAR RULE NOW, at its start: it may + // have waited its turn on X's queue long past the jar's limit, and the + // guard above lets through what a watch must not (a cookie-age setting + // of 0, the browser as login source). Refused: nothing is opened or + // fetched, and the library's watches pause. + if (watch && library) { + const refusal = await refuseWatchJob(paths, slug); + if (refusal) throw new Error(`This capture was queued by a watch and did not start: ${refusal.sentence}`); + } // UNDER THE E2E TEST SERVER a library's capture never reaches X or its // CDN: the fake profile browser, the played-back CDN, and no logged-in // download (social/fakeXProfileBrowser.ts). @@ -466,15 +482,16 @@ export async function capturePostsAction( ? { libraryMedia: { fallback: keptMedia && !testServer ? ("login" as const) : ("none" as const), - // KEPT WHEN QUEUED IS NOT KEPT NOW (review 1 M4): the job may - // start minutes later (X's gap, a queue), and the operator - // may have dropped a post meanwhile. The judgements are read - // again immediately before each logged-in download, and a - // post no longer kept gets none. + // KEPT WHEN QUEUED IS NOT KEPT NOW (review 1 M4, review 2 + // N3): the job may start minutes later (X's gap, a queue), + // and the operator may have dropped a post meanwhile. The + // judgements are read again, once per post, before its media: + // only a post STILL kept has no per-file cap and the + // logged-in download; one dropped since is fetched as any + // post is, under the library's cap. ...(keptMedia - ? { mayLogin: async (id: string) => (await readXTrendingKeptIds(path.join(paths.channelsDir, slug))).has(id) } + ? { isKept: async (id: string) => (await readXTrendingKeptIds(path.join(paths.channelsDir, slug))).has(id) } : {}), - ...(keptMedia ? { maxVideoBytes: null } : {}), ...(fakeFetch ? { deps: { fetch: fakeFetch, pauseMs: () => 20 } } : {}), }, } diff --git a/editor/app/channels/[slug]/xTrendingActions.ts b/editor/app/channels/[slug]/xTrendingActions.ts @@ -33,6 +33,7 @@ import { } from "yt-dlp-transcript-common/controller/readXTrending"; import { noteXTrendingWatchRead, + refuseWatchJob, runXTrendingWatchScan, xTrendingWatchFollowUp, type WatchScanResult, @@ -114,12 +115,19 @@ export async function readXTrendingAction(ask: ReadXTrendingAsk): Promise<Stream signal, deps: { profileBusy: () => xPressInFlight(), + // A watch's tick asks the watch's own jar rule again, now, at its + // start (review 2 N1): it may have waited its turn for a long time. + ...(plan.watch ? { watchRefusal: () => refuseWatchJob(paths, plan.slug) } : {}), ...(chromium ? { chromium, pauseMs: () => 50 } : {}), }, }); - await afterXTrendingRead(plan.slug, plan.channelRoot, result, onLog).catch((err) => - onLog(`The watch could not be told of this read: ${(err as Error).message}`), - ); + // A tick the watch's rule refused was not a read: the watch is paused + // (refuseWatchJob), and it is no strike against it. + if (!result.watchRefused) { + await afterXTrendingRead(plan.slug, plan.channelRoot, result, onLog).catch((err) => + onLog(`The watch could not be told of this read: ${(err as Error).message}`), + ); + } done(onLog, result); }, }); @@ -146,9 +154,18 @@ async function afterXTrendingRead( (follow.owed ? ` and ${follow.owed} owed from an earlier capture` : "") + (follow.uncaptured ? ` and ${follow.uncaptured} never captured` : "") + ` of the watched topic "${result.topic.title}"`; + // THE CAPTURE IS THE WATCH'S JOB TOO (review 2 N1): the watch's jar rule is + // asked before it is queued, and again inside the job when it starts + // (`watch: true`) — with "screenshot everything new" it opens pages on X. + const refusal = await refuseWatchJob(getPaths(), slug); + if (refusal) { + onLog(`The media of ${what} was not queued, and the watch is paused: ${refusal.sentence}`); + return; + } 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. ...(follow.shots ? {} : { avatars: false, context: false }), + watch: true, }); if (started.ok) { void started.stream.cancel(); diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -485,6 +485,8 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { context: bool(p.context), contextOnly: bool(p.contextOnly), keptMedia: bool(p.keptMedia), + // A watch's capture stays a watch's when it is re-run or resumed. + watch: bool(p.watch), }, ); }, diff --git a/editor/e2e/x-trending.spec.ts b/editor/e2e/x-trending.spec.ts @@ -22,6 +22,7 @@ import { FIXTURE_FIRST_PAGE, FIXTURE_TIMELINE_OP, FIXTURE_TREND_URL, + fixtureContinuation, fixtureTimelineBody, fixtureTrendingResponses, } from "../../common/social/__fixtures__/xTrendingCapture"; @@ -240,7 +241,7 @@ test("an X trending library: judgements, a watch tick, media kept once, gone fro }, ], // Asked for more, the timeline has none: the page's end, which is what lets a read say "gone". - scrolls: [[{ url: `https://x.com/i/api/graphql/fixtureQueryId4/${FIXTURE_TIMELINE_OP}?variables=%7B%7D`, status: 200, body: fixtureTimelineBody([]) }], []], + scrolls: [[fixtureContinuation()], []], }, // The same bytes at both addresses: one file in the library. (The opening // post's two pictures, never captured, are taken by the same job.) diff --git a/plans/x-trending.md b/plans/x-trending.md @@ -56,8 +56,10 @@ These are rulings, not reasons. A later ruling overturns an earlier one only whe be judged too: its key is its root post's id, and a post's effective judgement is its own, else its thread's. - An agent's judgement is a suggestion. An agent's write never overrides an operator's: it is skipped - for that id and reported. That holds through a thread: a post the operator judged by its thread is the - operator's. `by` is the caller's word: the ops route cannot tell who asks, so an agent is trusted to say + for that id and reported. +- WHICH JUDGEMENT IS IN FORCE is one rule, in one function (`xTrendingEffectiveJudgement`): the + operator's entry, for the post or its thread, always outranks an agent's about the same post, whatever + the order in time; between two entries of the same hand the post's own outranks its thread's. `by` is the caller's word: the ops route cannot tell who asks, so an agent is trusted to say "agent"; the operator's hand is the page's buttons and slice 3's judge view. - Drop deletes nothing and is reversible. Purging a dropped post's capture is the operator's press (slice 3). @@ -85,13 +87,19 @@ These are rulings, not reasons. A later ruling overturns an earlier one only whe refuses a scan asked for by hand). - THE WATCH'S JAR RULE IS ITS OWN. The exemptions a person's job has (the browser as login source, a cookie-age setting of 0, settings that cannot be read) do not apply to a watch: it ticks only when the - profile's exported jar is between 0 and the limit old (the setting when above 0, else 60 minutes). + profile's exported jar is between 0 and the limit old (the setting when above 0, else 60 minutes). The + rule is asked when a tick is queued AND when its job starts, and for the capture that follows a read + both before it is queued and when it starts (`refuseWatchJob`): a refusal there opens nothing, pauses + the watch and is no strike. - ALL LIBRARIES SHARE ONE STREAM OF TICKS: no tick starts while a trending read, a reparse or a capture of any library is queued or running. The cap on watched topics stays per library. -- THREE READS IN A ROW that do not end "read" pause a watch ("failing") until a person switches it on - again. -- "Gone from the page" needs the page's end IN THE CAPTURE: asked for more, the page had nothing new, and - no answer failed or was dropped. +- THREE READS IN A ROW that do not end "read" pause a watch ("failing") until the OPERATOR switches it on + again; an agent's ask is refused. +- "Gone from the page" needs the page's end IN THE CAPTURE: the last listing answer is the continuation + from the bottom (its request carries the previous answer's bottom cursor) and brought nothing new, and no + answer failed, was dropped, carried GraphQL errors or lacked timeline instructions. +- A POST IS KEPT WHEN ITS MEDIA IS FETCHED, not when the job was queued: one predicate, asked once per post + before its media, decides both the uncapped download and the logged-in fallback. **Later slices**