Archilyzer · Source

archilyzer

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

commit af6737d913c6c1f2ef3ee5cc23235d0aa180d145
parent f73bd4f827a70f565d8bc81dd9c5cd6d68a9e286
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 17 Nov 2026 19:09:02 -0500

x-trending S1: the editor's action, ops routes, channel form, page and CLI

pnpm ops read-x-trending {slug, url, topic?, scrolls?, posts?, probe?, headed?} (or
{slug, reparse}) runs the read as one job on X's queue; pnpm ops get trending <slug>
[--topic] [--limit] lists the library's topics and posts from its own files. Both
have a UI: the library's channel page reads a page, parses a saved read again and
shows the library by topic.

create-channel "platform": "x-trending" makes a library (New channel form: "X
trending library (private)"): a URL and site memberships are refused, the caps are
xTrendingMaxScrolls / xTrendingMaxPosts, and a Configure save can neither make a
library nor unmake one.

One browser on the X profile at a time: X's Connect and Refresh are refused while a
read-x-trending or capture-posts job is running on X's queue, and the read is
refused (at enqueue and at its start) while a Connect or Refresh is in flight.
Connect and Refresh are otherwise unchanged.

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

Diffstat:
Mcommon/controller/readXTrending.ts | 15++++++---------
Mcommon/controller/xTrendingGuards.test.ts | 4++--
Mcommon/jobs/jobKinds.ts | 11++++++-----
Mcommon/lib/xTrending/config.ts | 11+++++++++++
Aeditor/app/api/ops/read-x-trending/route.test.ts | 187+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/read-x-trending/route.ts | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/trending/route.ts | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/components/XTrendingPanel.tsx | 198+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/page.tsx | 22+++++++++++++++++++---
Meditor/app/channels/[slug]/socialActions.ts | 3+++
Aeditor/app/channels/[slug]/xTrendingActions.ts | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/actions.ts | 20++++++++++++++++++++
Meditor/app/channels/components/ChannelForm.tsx | 29+++++++++++++++++++++++------
Aeditor/app/channels/components/XTrendingFields.tsx | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/components/channelConfigToForm.ts | 9++++++++-
Meditor/app/channels/components/parseChannelForm.test.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/components/parseChannelForm.ts | 50++++++++++++++++++++++++++++++++++++++++++++++----
Meditor/app/lib/cookieRefreshGuard.test.ts | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/lib/cookieRefreshGuard.ts | 48++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mscripts/archilyzer-ops.test.mjs | 19+++++++++++++++++++
21 files changed, 1018 insertions(+), 32 deletions(-)

diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts @@ -65,17 +65,14 @@ import { } from "../social/xTrendingRead"; import { readChannelConfig } from "./channels"; -export const READ_X_TRENDING_KIND = "read-x-trending"; -export const REPARSE_X_TRENDING_KIND = "reparse-x-trending"; -// X's platform queue: one browser on the profile at a time, X's gap between jobs. -export const X_TRENDING_QUEUE = "platform:twitter"; +export { + READ_X_TRENDING_KIND, + REPARSE_X_TRENDING_KIND, + X_PROFILE_BROWSER_JOB_KINDS, + X_TRENDING_QUEUE, +} from "../lib/xTrending/config"; export const READ_X_TRENDING_RESULT_MARKER = "@@read-x-trending "; -// The job kinds that open the connected X profile in a browser while they -// run on X's queue: a Connect or a Refresh (which open the same profile) is -// refused while one of them is running (editor/app/lib/cookieRefreshGuard.ts). -export const X_PROFILE_BROWSER_JOB_KINDS: readonly string[] = [READ_X_TRENDING_KIND, "capture-posts"]; - export const NO_X_PROFILE_FOR_TRENDING = "Reading a trending page needs the connected X profile (the browser that stays logged in): " + "connect an X account on /cookies, then read it again."; diff --git a/common/controller/xTrendingGuards.test.ts b/common/controller/xTrendingGuards.test.ts @@ -41,13 +41,13 @@ test("the X run never lists a library among the X posts channels", () => { assert.equal(isXPostsChannel({ handling: "transcribe", sourceKind: "social", platform: "twitter" } as never), true); }); -test("read-x-trending: a network, drainable kind on X's queue that nothing replays or resumes; reparse asks nothing", () => { +test("read-x-trending: a network kind on X's queue that nothing replays or resumes; reparse asks nothing", () => { const read = getJobKind(READ_X_TRENDING_KIND); assert.ok(read, "registered"); assert.equal(jobKindLabel(READ_X_TRENDING_KIND), "Read X trending page"); assert.equal(read.queueKeyStrategy, "platform"); assert.equal(kindIsNetwork(READ_X_TRENDING_KIND), true); - assert.equal(isDrainableKind(READ_X_TRENDING_KIND), true); + assert.equal(isDrainableKind(READ_X_TRENDING_KIND), false); assert.equal(read.replayable, false); assert.equal(read.resumeOnBoot, undefined); assert.equal(read.startedByPerson, true); diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -686,14 +686,15 @@ const JOB_KINDS: Record<string, JobKindMeta> = { // browser, what the page itself fetched saved raw, its posts parsed from the // saved file. One page is one job on X's queue (`platform:twitter`), so the // fresh-jar rule, the X alert and X's job gap apply and no other browser is - // on the profile beside it. Network; drainable (it stops between scrolls and - // keeps what it read); NOT replayable and not resumed on boot — a read is a - // request to X, and nothing repeats one unasked; started only by a person - // (or an agent's ask), never by a boot. + // on the profile beside it. Network; not drainable (a read is a minute or + // two; a Cancel stops it between scrolls and what it read is kept); NOT + // replayable and not resumed on boot — a read is a request to X, and nothing + // repeats one unasked; started only by a person (or an agent's ask), never + // by a boot. "read-x-trending": { kind: "read-x-trending", label: "Read X trending page", - drainable: true, + drainable: false, replayable: false, queueKeyStrategy: "platform", network: true, diff --git a/common/lib/xTrending/config.ts b/common/lib/xTrending/config.ts @@ -23,6 +23,17 @@ export type XTrendingConfig = { maxPosts?: number; }; +// The two job kinds, and X's platform queue they run on: one browser on the +// profile at a time, X's gap between jobs. +export const READ_X_TRENDING_KIND = "read-x-trending"; +export const REPARSE_X_TRENDING_KIND = "reparse-x-trending"; +export const X_TRENDING_QUEUE = "platform:twitter"; + +// The job kinds that open the connected X profile in a browser while they +// run on X's queue: a Connect or a Refresh (which open the same profile) is +// refused while one of them is running (editor/app/lib/cookieRefreshGuard.ts). +export const X_PROFILE_BROWSER_JOB_KINDS: readonly string[] = [READ_X_TRENDING_KIND, "capture-posts"]; + export const X_TRENDING_DEFAULT_SCROLLS = 8; export const X_TRENDING_MAX_SCROLLS = 20; export const X_TRENDING_DEFAULT_POSTS = 60; diff --git a/editor/app/api/ops/read-x-trending/route.test.ts b/editor/app/api/ops/read-x-trending/route.test.ts @@ -0,0 +1,187 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { access, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/read-x-trending/route.test.ts" +// +// An X trending library over ops (lane x-trending), against a temp corpus: +// every refusal of read-x-trending BEFORE a job exists (so no browser opens +// and nothing is asked of X — the corpus has no connected profile, which is +// itself the last refusal), the listing (`GET /api/ops/trending`), and the +// channel form's refusals: a library on a site, a library with a URL, a +// library turned into an ordinary channel. A read itself is driven in +// e2e/x-trending.spec.ts over the fake browser. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-trending-route-")); +process.env.WORKER_TOKEN = "test-token"; +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); + +const READ = "tr-01JA0000000000000000000000"; +const TREND = "https://x.com/i/trending/1900000000000000001"; + +async function channel(slug: string, config: Record<string, unknown>): Promise<string> { + const dir = path.join(ROOT, "channels", slug); + await mkdir(path.join(dir, "posts"), { recursive: true }); + await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config })); + return dir; +} + +const lib = await channel("trending", { sourceKind: "social", platform: "twitter", xTrending: {} }); +await channel("account-x", { sourceKind: "social", platform: "twitter", postFetcher: "x-gallery-dl", socialHandle: "example", url: "https://x.com/example" }); +await writeFile( + path.join(lib, "posts", "2026-11.jsonl"), + ["1900000000000001001", "1900000000000001002"] + .map((id, i) => + JSON.stringify({ + id, + slug: `trending/${id}`, + channelSlug: "trending", + author: i ? "saucer_fan" : "teapot_news", + createdAt: "2026-11-16T12:00:00.000Z", + uploadDate: "20261116", + text: i ? "Second." : "The kettle festival opens today.", + url: `https://x.com/${i ? "saucer_fan" : "teapot_news"}/status/${id}`, + platform: "twitter", + isReply: false, + isRepost: false, + links: [], + }), + ) + .join("\n") + "\n", +); +await writeFile(path.join(lib, "posts-archive"), "twitter 1900000000000001001\ntwitter 1900000000000001002\n"); +await mkdir(path.join(lib, "trending", "reads", READ), { recursive: true }); +await writeFile(path.join(lib, "trending", "reads", READ, "responses.jsonl"), JSON.stringify({ n: 1, op: "Op", status: 200, bytes: 9, url: "u", at: "x", body: { secret: "rawcapturemarker" } }) + "\n"); +await writeFile( + path.join(lib, "trending", "topics.json"), + JSON.stringify({ + version: 1, + topics: [ + { + id: "kettles", + title: "Kettles", + createdAt: "2026-11-17T10:00:00.000Z", + sources: [{ trendId: "1900000000000000001", url: TREND, reads: [{ id: READ, at: "2026-11-17T10:00:00.000Z", posts: 2, added: 2 }] }], + }, + ], + }), +); +await writeFile( + path.join(lib, "trending", "membership.json"), + JSON.stringify({ + version: 1, + posts: { + "1900000000000001001": { topic: "kettles", seen: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z", rank: 1 }], media: { count: 2, kinds: ["image"] } }, + "1900000000000001002": { topic: "kettles", seen: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z", rank: 2 }] }, + }, + }), +); +await mkdir(path.join(ROOT, "sites", "demo-site"), { recursive: true }); +await writeFile(path.join(ROOT, "sites", "demo-site", "site.json"), JSON.stringify({ siteId: "demo-site", siteTitle: "Demo", channels: [] })); + +const readTrending = (await import("./route")).POST; +const listing = (await import("../trending/route")).GET; +const create = (await import("../create-channel/route")).POST; +const configure = (await import("../channel-config/route")).POST; +test.after(() => rm(ROOT, { recursive: true, force: true })); + +async function call(handler: (r: Request) => Promise<Response>, body: Record<string, unknown>) { + const res = await handler( + new Request("http://localhost/api/ops/x", { + method: "POST", + headers: { authorization: "Bearer test-token", "content-type": "application/json" }, + body: JSON.stringify(body), + }), + ); + return { status: res.status, json: (await res.json()) as Record<string, unknown> }; +} + +async function get(query: string, token = "test-token") { + const res = await listing(new Request(`http://localhost/api/ops/trending${query}`, { headers: { authorization: `Bearer ${token}` } })); + return { status: res.status, json: (await res.json()) as Record<string, unknown> }; +} + +const exists = (p: string) => access(p).then(() => true, () => false); + +test("read-x-trending refuses, before any job, with a sentence", async () => { + const refused = async (body: Record<string, unknown>) => { + const r = await call(readTrending, body); + assert.equal(r.status, 400, JSON.stringify(r.json)); + assert.equal(r.json.ok, false); + return String(r.json.error); + }; + assert.match(await refused({ url: TREND }), /"slug" is required/); + assert.equal(await refused({ slug: "nope", url: TREND }), "No such channel: nope"); + assert.match(await refused({ slug: "account-x", url: TREND }), /account-x is not an X trending library/); + assert.match(await refused({ slug: "trending" }), /Give "url" .* or "reparse"/); + assert.match(await refused({ slug: "trending", url: "https://x.com/example/status/1" }), /not a trending page URL/); + assert.match(await refused({ slug: "trending", url: TREND, scrolls: 21 }), /"scrolls" is a whole number, 1–20/); + assert.match(await refused({ slug: "trending", url: TREND, posts: 0 }), /"posts" must be a whole number above zero/); + assert.match(await refused({ slug: "trending", url: TREND, probe: "yes" }), /"probe" must be a boolean/); + assert.match(await refused({ slug: "trending", url: TREND, pages: 3 }), /pages/); + assert.match(await refused({ slug: "trending", reparse: "tr-01JZ0000000000000000000000" }), /holds no saved read/); + // No connected X profile in this corpus: the read is refused, and no browser was asked for. + assert.match(await refused({ slug: "trending", url: TREND }), /needs the connected X profile/); + assert.equal(await exists(path.join(ROOT, ".jobs")), false, "no job was made"); +}); + +test("get trending lists topics and posts — words, author, media, reads, topic — and never the raw capture", async () => { + const all = await get("?slug=trending"); + assert.equal(all.status, 200); + assert.deepEqual(all.json.topics, [ + { id: "kettles", title: "Kettles", posts: 2, sources: [{ trendId: "1900000000000000001", url: TREND, reads: 1, lastReadAt: "2026-11-17T10:00:00.000Z" }] }, + ]); + const posts = all.json.posts as Array<Record<string, unknown>>; + assert.deepEqual(posts[0], { + id: "1900000000000001001", + author: "teapot_news", + createdAt: "2026-11-16T12:00:00.000Z", + url: "https://x.com/teapot_news/status/1900000000000001001", + text: "The kettle festival opens today.", + media: { count: 2, kinds: ["image"] }, + topic: "kettles", + reads: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z" }], + }); + assert.equal(all.json.total, 2); + assert.deepEqual(all.json.reads, [READ]); + assert.ok(!JSON.stringify(all.json).includes("rawcapturemarker")); + assert.equal(((await get("?slug=trending&limit=1")).json.posts as unknown[]).length, 1); + assert.equal(((await get("?slug=trending&topic=kettles")).json.posts as unknown[]).length, 2); + // Refusals. + assert.match(String((await get("?slug=trending&topic=nope")).json.error), /has no topic "nope" \(its topics: kettles\)/); + assert.match(String((await get("?slug=account-x")).json.error), /not an X trending library/); + assert.equal((await get("?slug=nope")).status, 404); + assert.match(String((await get("?slug=trending&limit=501")).json.error), /1–500/); + assert.match(String((await get("?slug=trending&raw=1")).json.error), /unknown parameter "raw"/); + assert.match(String((await get("?slug=..%2Fx")).json.error), /not a valid channel slug/); + assert.equal((await get("?slug=trending", "wrong")).status, 401); +}); + +test("create-channel refuses a library on a site and a library with a URL; nothing is made", async () => { + const fields = { name: "Made trending", handling: "transcribe", platform: "x-trending" }; + const onSite = await call(create, { fields, sites: [{ siteId: "demo-site", groupId: "default" }] }); + assert.equal(onSite.status, 400); + assert.equal(onSite.json.error, "made-trending is an X trending library: it is private, and never put on a site."); + const withUrl = await call(create, { fields: { ...fields, url: TREND } }); + assert.equal(withUrl.status, 400); + assert.match(String(withUrl.json.error), /^An X trending library has no URL/); + const badCap = await call(create, { fields: { ...fields, xTrendingMaxPosts: 500 } }); + assert.match(String(badCap.json.error), /post cap is a whole number, 1–200/); + assert.equal(await exists(path.join(ROOT, "channels", "made-trending")), false); +}); + +test("Configure cannot turn a library into an ordinary channel, an account into a library, or put a library on a site", async () => { + const unmade = await call(configure, { slug: "trending", patch: { platform: "twitter", socialHandle: "example" } }); + assert.equal(unmade.status, 400); + assert.match(String(unmade.json.error), /trending is an X trending library and stays one/); + const made = await call(configure, { slug: "account-x", patch: { platform: "x-trending", url: "" } }); + assert.equal(made.status, 400); + assert.match(String(made.json.error), /Configure cannot make it one/); + const onSite = await call(configure, { slug: "trending", sites: [{ siteId: "demo-site", groupId: "default" }] }); + assert.equal(onSite.status, 400); + assert.equal(onSite.json.error, "trending is an X trending library: it is private, and never put on a site."); +}); diff --git a/editor/app/api/ops/read-x-trending/route.ts b/editor/app/api/ops/read-x-trending/route.ts @@ -0,0 +1,65 @@ +import { readXTrendingAction } from "../../../channels/[slug]/xTrendingActions"; +import { jobResponse, ops, optBool, optPositiveInt, optString, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, url, topic?, scrolls?, posts?, probe?, headed? } -> { ok: true, jobId } +// POST { slug, reparse: "<readId>", topic? } -> { ok: true, jobId } +// +// ONE X trending page (https://x.com/i/trending/<number>) read into `slug`, +// an X trending library (a private posts channel made with platform +// "x-trending"), as ONE `read-x-trending` job on X's queue: the page is +// opened in the connected X profile's browser, every GraphQL answer the page +// itself fetched is saved raw with a screenshot +// (channels/<slug>/trending/reads/<readId>/), and the posts are parsed from +// the saved file and written as the library's posts under a topic. A read +// lists posts; it archives no media and no thread. +// +// topic the topic's id or name, or a new one's name. Absent: the topic +// this page was read into before, else a new one named for it. +// scrolls at most this many moves to the bottom of the page (1–20; the +// channel's cap, else 8). posts: stop once this many are seen +// (1–200; else 60). A read also stops after two scrolls that +// brought nothing new, and at once on a 429 or a login wall. +// probe save the capture and its summary; write no post. +// headed open a window on the editor's desktop instead of a headless one. +// reparse a saved read's id: its capture parsed again, OFFLINE (a +// `reparse-x-trending` job; X is asked nothing, so no fresh jar). +// +// The log ends with `@@read-x-trending {ok, slug, mode, url, trendId, read, +// outcome, stop?, scrolls?, responses, operations, posts: {onPage, added}, +// topic?, sentence, error?}` — operation NAMES and SIZES, never a body. A +// capture with no post the parser knows ends ok, "read saved, nothing +// recognised". +// +// Every refusal is the action's own sentence: no such channel, not a +// library, not a trending page URL, a cap out of range, no connected X +// profile, a Connect or Refresh of X in flight, a stale cookie jar or a +// raised X alert (the network guard), a saved read that is not there. +export async function POST(request: Request) { + return ops( + request, + ["slug", "url", "reparse", "topic", "scrolls", "posts", "probe", "headed"], + async (body) => { + const url = optString(body, "url"); + const reparse = optString(body, "reparse"); + const topic = optString(body, "topic"); + const scrolls = optPositiveInt(body, "scrolls"); + const posts = optPositiveInt(body, "posts"); + const probe = optBool(body, "probe"); + const headed = optBool(body, "headed"); + return jobResponse( + await readXTrendingAction({ + slug: reqSlug(body, "slug"), + ...(url !== undefined ? { url } : {}), + ...(reparse !== undefined ? { reparse } : {}), + ...(topic !== undefined ? { topic } : {}), + ...(scrolls !== undefined ? { scrolls } : {}), + ...(posts !== undefined ? { posts } : {}), + ...(probe ? { probe: true } : {}), + ...(headed ? { headed: true } : {}), + }), + ); + }, + ); +} diff --git a/editor/app/api/ops/trending/route.ts b/editor/app/api/ops/trending/route.ts @@ -0,0 +1,56 @@ +import path from "node:path"; +import { NextResponse } from "next/server"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; +import { isXTrendingChannel, NOT_AN_X_TRENDING_LIBRARY } from "yt-dlp-transcript-common/lib/xTrending/config"; +import { listXTrending, X_TRENDING_LIST_MAX } from "yt-dlp-transcript-common/lib/xTrending/store"; +import { opsAuth, opsFail } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// GET /api/ops/trending?slug=<library>[&topic=<topicId>][&limit=<n>] +// -> { ok, slug, name, topics: [{id, title, posts, sources: [{trendId, url, +// title?, summary?, reads, lastReadAt}]}], +// posts: [{id, author, authorName?, createdAt, url, text, +// media: {count, kinds}, topic, reads: [{read, trendId, at}]}], +// total, reads: [<readId>, …] } +// +// An X trending library's topics and posts (lane x-trending) — `pnpm ops get +// trending <slug>` and the MCP's x_trending_topics / x_trending_posts. Read +// from the library's own files and its posts shards (lib/xTrending/store.ts): +// a library is in no index build, so nothing here needs one. `topic` narrows +// the posts to one topic; `limit` (default 100, at most 500) caps them, the +// newest read's first, in page order; `total` is the count before the cap. +// +// NEVER the raw capture, a cookie or a token: a post is its id, author, words, +// media by kind, the reads that showed it and its topic. +export async function GET(request: Request) { + const denied = opsAuth(request); + if (denied) return denied; + const sp = new URL(request.url).searchParams; + for (const key of sp.keys()) { + if (!["slug", "topic", "limit"].includes(key)) return opsFail(`unknown parameter "${key}" (slug, topic, limit)`); + } + const slug = sp.get("slug") ?? ""; + if (!isValidChannelSlug(slug)) return opsFail(`"${slug}" is not a valid channel slug`); + const topic = sp.get("topic") ?? undefined; + let limit: number | undefined; + if (sp.get("limit") !== null) { + limit = Number(sp.get("limit")); + if (!Number.isInteger(limit) || limit < 1 || limit > X_TRENDING_LIST_MAX) { + return opsFail(`"limit" is a whole number, 1–${X_TRENDING_LIST_MAX}`); + } + } + const paths = getPaths(); + const config = await readChannelConfig(paths, slug); + if (!config) return opsFail(`No such channel: ${slug}`, 404); + if (!isXTrendingChannel(config)) return opsFail(NOT_AN_X_TRENDING_LIBRARY(slug)); + const listing = await listXTrending(path.join(paths.channelsDir, slug), { + ...(topic ? { topic } : {}), + ...(limit !== undefined ? { limit } : {}), + }); + if (topic && !listing.topics.some((t) => t.id === topic)) { + return opsFail(`${slug} has no topic "${topic}" (its topics: ${listing.topics.map((t) => t.id).join(", ") || "none yet"})`); + } + return NextResponse.json({ ok: true, slug, name: config.name ?? slug, ...listing }); +} diff --git a/editor/app/channels/[slug]/components/XTrendingPanel.tsx b/editor/app/channels/[slug]/components/XTrendingPanel.tsx @@ -0,0 +1,198 @@ +"use client"; + +import { useState } from "react"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import { + X_TRENDING_MAX_POSTS, + X_TRENDING_MAX_SCROLLS, +} from "yt-dlp-transcript-common/lib/xTrending/config"; +import type { XTrendingListing } from "yt-dlp-transcript-common/lib/xTrending/store"; +import { cancelJobAction } from "../../../jobs/actions"; +import { readXTrendingAction } from "../xTrendingActions"; + +// An X trending library's page (lane x-trending, slice 1): read a trending +// page into it (`read-x-trending`, one job on X's queue), parse a saved read +// again, and the library by topic — each post's author, words, media by kind +// and when it was read. Listing only: archiving a post and judging it are +// later slices. Everything here is `pnpm ops read-x-trending` / `get trending`. +export function XTrendingPanel({ + slug, + listing, + limits, +}: { + slug: string; + listing: XTrendingListing; + limits: { scrolls: number; posts: number }; +}) { + const [url, setUrl] = useState(""); + const [topic, setTopic] = useState(""); + const [scrolls, setScrolls] = useState(""); + const [posts, setPosts] = useState(""); + const [probe, setProbe] = useState(false); + const [headed, setHeaded] = useState(false); + const [reparse, setReparse] = useState(listing.reads[0] ?? ""); + const input = "rounded border border-border bg-card px-2 py-1 text-sm"; + const num = (v: string) => (v.trim() ? Number(v) : undefined); + const byTopic = (id: string) => listing.posts.filter((p) => p.topic === id); + return ( + <div className="flex flex-col gap-6"> + <section aria-label="read a trending page" className="flex flex-col gap-3 rounded-lg border border-border p-3"> + <h3 className="text-sm font-semibold">Read a trending page</h3> + <span data-x-trending-private="" className="text-xs text-muted-foreground"> + Private: on no site, in no build, not in search. + </span> + <input + value={url} + onChange={(e) => setUrl(e.target.value)} + aria-label="trending page URL" + placeholder="https://x.com/i/trending/…" + className={`${input} w-[32rem] max-w-full font-mono`} + /> + <div className="flex flex-wrap items-end gap-3 text-sm"> + <label className="flex flex-col gap-1"> + <span className="font-medium">Topic</span> + <input + value={topic} + onChange={(e) => setTopic(e.target.value)} + aria-label="topic" + list="x-trending-topics" + placeholder="its own, or a new name" + className={`${input} w-64`} + /> + <datalist id="x-trending-topics"> + {listing.topics.map((t) => ( + <option key={t.id} value={t.title} /> + ))} + </datalist> + </label> + <label className="flex flex-col gap-1"> + <span className="font-medium">Scrolls</span> + <input + type="number" + min={1} + max={X_TRENDING_MAX_SCROLLS} + value={scrolls} + onChange={(e) => setScrolls(e.target.value)} + aria-label="scrolls" + placeholder={String(limits.scrolls)} + className={`${input} w-20`} + /> + </label> + <label className="flex flex-col gap-1"> + <span className="font-medium">Posts</span> + <input + type="number" + min={1} + max={X_TRENDING_MAX_POSTS} + value={posts} + onChange={(e) => setPosts(e.target.value)} + aria-label="posts" + placeholder={String(limits.posts)} + className={`${input} w-20`} + /> + </label> + <label className="flex items-center gap-2" title="Save the page's answers and a summary; write no post"> + <input type="checkbox" checked={probe} onChange={(e) => setProbe(e.target.checked)} /> + Probe (save only) + </label> + <label className="flex items-center gap-2" title="Open a browser window on the editor's machine instead of a headless one"> + <input type="checkbox" checked={headed} onChange={(e) => setHeaded(e.target.checked)} /> + In a window + </label> + </div> + <StreamActionLog + trigger={() => + readXTrendingAction({ + slug, + url: url.trim(), + ...(topic.trim() ? { topic: topic.trim() } : {}), + ...(num(scrolls) !== undefined ? { scrolls: num(scrolls) } : {}), + ...(num(posts) !== undefined ? { posts: num(posts) } : {}), + ...(probe ? { probe: true } : {}), + ...(headed ? { headed: true } : {}), + }) + } + cancelAction={cancelJobAction} + buttonLabel="Read trending page" + runningLabel="Reading…" + label={`Read a trending page into ${slug}`} + disabled={!url.trim()} + /> + {listing.reads.length > 0 && ( + <div className="flex flex-col gap-2 border-t border-border pt-3"> + <h4 className="text-sm font-semibold">Parse a saved read again</h4> + <select + value={reparse} + onChange={(e) => setReparse(e.target.value)} + aria-label="saved read" + className={`${input} w-80 font-mono`} + > + {listing.reads.map((id) => ( + <option key={id} value={id}> + {id} + </option> + ))} + </select> + <StreamActionLog + trigger={() => + readXTrendingAction({ slug, reparse, ...(topic.trim() ? { topic: topic.trim() } : {}) }) + } + cancelAction={cancelJobAction} + buttonLabel="Parse again (asks X nothing)" + runningLabel="Parsing…" + label={`Parse a saved read of ${slug} again`} + disabled={!reparse} + /> + </div> + )} + </section> + <section aria-label="trending topics" className="flex flex-col gap-4"> + <h3 className="text-sm font-semibold"> + Topics <span className="font-normal text-muted-foreground">· {listing.total} posts</span> + </h3> + {listing.topics.length === 0 && ( + <span className="text-sm text-muted-foreground">No topic yet.</span> + )} + {listing.topics.map((t) => ( + <article key={t.id} data-x-trending-topic={t.id} className="flex flex-col gap-2 rounded-lg border border-border p-3"> + <h4 className="text-sm font-semibold"> + {t.title} <span className="font-normal text-muted-foreground">· {t.posts} posts</span> + </h4> + <ul className="flex flex-col gap-0.5 text-xs text-muted-foreground"> + {t.sources.map((s) => ( + <li key={s.trendId}> + <a href={s.url} target="_blank" rel="noreferrer" className="font-mono underline"> + {s.url} + </a>{" "} + · read {s.reads}×{s.lastReadAt ? `, last ${s.lastReadAt.slice(0, 16).replace("T", " ")} UTC` : ""} + </li> + ))} + </ul> + <ol className="flex flex-col divide-y divide-border"> + {byTopic(t.id).map((p) => ( + <li key={p.id} data-x-trending-post={p.id} className="flex flex-col gap-1 py-2 text-sm"> + <span className="text-xs text-muted-foreground"> + <a href={p.url} target="_blank" rel="noreferrer" className="font-medium text-foreground underline"> + @{p.author} + </a> + {p.authorName ? ` (${p.authorName})` : ""} · {p.createdAt.slice(0, 16).replace("T", " ")} UTC + {p.media.count > 0 + ? ` · ${p.media.count} media${p.media.kinds.length ? ` (${p.media.kinds.join(", ")})` : ""}` + : ""} + {p.reads.length > 1 ? ` · on ${p.reads.length} reads` : ""} + </span> + <span className="whitespace-pre-wrap">{p.text}</span> + </li> + ))} + </ol> + </article> + ))} + {listing.total > listing.posts.length && ( + <span className="text-xs text-muted-foreground"> + {listing.posts.length} of {listing.total} posts shown. + </span> + )} + </section> + </div> + ); +} diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -42,6 +42,9 @@ import { waybackLiveState } from "./waybackLiveState"; import { savePageNowAvailability } from "yt-dlp-transcript-common/controller/savePageNow"; import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config"; import { isXSearchChannel } from "yt-dlp-transcript-common/lib/xSearch/config"; +import { isXTrendingChannel, xTrendingLimits } from "yt-dlp-transcript-common/lib/xTrending/config"; +import { listXTrending, X_TRENDING_LIST_MAX } from "yt-dlp-transcript-common/lib/xTrending/store"; +import { XTrendingPanel } from "./components/XTrendingPanel"; import { describeXSearchWalk } from "yt-dlp-transcript-common/lib/xSearch/walk"; import { readXSearchLeads } from "yt-dlp-transcript-common/controller/xSearchLeads"; import { XSearchLeadsPanel } from "./components/XSearchLeadsPanel"; @@ -243,21 +246,34 @@ export default async function ChannelDetailPage({ // An X SEARCH channel (release 38): its query, its walk and its leads. const xSearch = isXSearchChannel(config) && config.xSearch ? config.xSearch : null; const leads = xSearch ? await readXSearchLeads(paths, slug) : null; + // AN X TRENDING LIBRARY (lane x-trending): its topics and posts, read from + // its own files (it is in no index), and the caps a read would use. + const trending = isXTrendingChannel(config) + ? { + listing: await listXTrending(channelRoot, { limit: X_TRENDING_LIST_MAX }), + limits: (() => { + const l = xTrendingLimits(config.xTrending); + return l.ok ? l.limits : { scrolls: 8, posts: 60 }; + })(), + } + : null; // A TIMELINE's two walks (X, Bluesky; lib/timelineWalk.ts): Sync new and, // when the full-history walk is part-way, Resume backfill — never a forum // thread's (its own two walks) or an X search's (one walk). - const timeline = !forumThread && !xSearch ? timelineWalks(fetchState) : null; + const timeline = !forumThread && !xSearch && !trending ? timelineWalks(fetchState) : null; // ACCOUNT ACTIVITY (lane x-console): posts per day and the long silences, // from the stored posts — every posts channel but a Wayback pages one // (its records are captures) and an X search (its posts are many // accounts' answers to a query, not one account's activity). Streamed // behind its own Suspense boundary, read through the cached light reader // (lib/postTimes-server.ts), so the page never waits on the posts. - const showActivity = !isWaybackPagesChannel(config) && !xSearch && postCount >= 2; + const showActivity = !isWaybackPagesChannel(config) && !xSearch && !trending && postCount >= 2; return ( <div className="flex flex-col gap-6"> <RunningJobsList jobs={socialRunningJobs} hideChannelSlug /> - {wayback ? ( + {trending ? ( + <XTrendingPanel slug={slug} listing={trending.listing} limits={trending.limits} /> + ) : wayback ? ( <> <WaybackPagesPanel slug={slug} diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -22,6 +22,7 @@ import { import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig"; import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config"; 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 { X_SEARCH_OLDER_REFUSAL } from "yt-dlp-transcript-common/controller/fetchXSearch"; import { WAYBACK_PAGES_NOT_FETCHED } from "yt-dlp-transcript-common/controller/fetchPosts"; import { WAYBACK_PAGES_QUEUE } from "yt-dlp-transcript-common/controller/importPage"; @@ -236,6 +237,8 @@ export async function fetchPostsAction( // A Wayback pages channel is never fetched: its captures are imported one // by one (import-page), as chosen — no unattended crawling (release 37). if (isWaybackPagesChannel(config)) return { ok: false, info: true, error: WAYBACK_PAGES_NOT_FETCHED }; + // An X trending library has no timeline: its pages are read one at a time. + if (isXTrendingChannel(config)) return { ok: false, info: true, error: X_TRENDING_NOT_FETCHED(slug) }; // An X search channel's one walk is its search windows (release 38). if (older && isXSearchChannel(config)) return { ok: false, error: X_SEARCH_OLDER_REFUSAL }; if (backfill) { diff --git a/editor/app/channels/[slug]/xTrendingActions.ts b/editor/app/channels/[slug]/xTrendingActions.ts @@ -0,0 +1,81 @@ +"use server"; + +// READ A TRENDING PAGE INTO AN X TRENDING LIBRARY (lane x-trending, slice 1): +// the channel page's "Read a trending page" and `pnpm ops read-x-trending`, +// one body (common/controller/readXTrending.ts). +// +// Refused HERE, before a job exists, with the controller's sentences: no such +// channel, not a library, a URL that is not a trending page, a cap out of +// range, no connected X profile, a saved read that is not there — and a +// Connect or Refresh of X in flight, which holds the profile's browser +// (lib/cookieRefreshGuard.ts). runManagedFunction then asks the network guard +// (the fresh-jar rule, the X alert) at enqueue and at the job's start, and X's +// queue spaces it from every other X job. +// +// A read is a `read-x-trending` job on X's queue; `reparse` (a saved capture +// parsed again, nothing asked of X) a `reparse-x-trending` job on the same +// queue, so neither writes the library's posts beside the other. The log ends +// with `@@read-x-trending {…}`. + +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { runManagedFunction, type StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; +import { + planReadXTrending, + READ_X_TRENDING_KIND, + READ_X_TRENDING_RESULT_MARKER, + REPARSE_X_TRENDING_KIND, + reparseXTrendingRead, + runXTrendingRead, + X_TRENDING_QUEUE, + type ReadXTrendingAsk, +} from "yt-dlp-transcript-common/controller/readXTrending"; +import { fakeXProfileChromium } from "yt-dlp-transcript-common/social/fakeXProfileBrowser"; +import { safeRevalidate } from "../../lib/safeRevalidate"; +import { xPressInFlight } from "../../lib/cookieRefreshGuard"; + +export async function readXTrendingAction(ask: ReadXTrendingAsk): Promise<StreamActionResult> { + const paths = getPaths(); + const planned = await planReadXTrending(paths, ask); + if (!planned.ok) return { ok: false, error: planned.error }; + const plan = planned.plan; + const done = (onLog: (line: string) => void, result: { ok: boolean; error?: string }) => { + onLog(`${READ_X_TRENDING_RESULT_MARKER}${JSON.stringify(result)}`); + safeRevalidate([`/channels/${plan.slug}`]); + if (!result.ok) throw new Error(result.error ?? "The trending page was not read"); + }; + if (plan.mode === "reparse") { + return runManagedFunction({ + kind: REPARSE_X_TRENDING_KIND, + queueKey: X_TRENDING_QUEUE, + paths, + channelSlug: plan.slug, + fn: async (onLog) => done(onLog, await reparseXTrendingRead({ plan, onLog })), + }); + } + const busy = xPressInFlight(); + if (busy) return { ok: false, error: busy }; + // Under the e2e test server only, the fake browser (fakeXProfileBrowser.ts + // says how it is gated) and its short waits; everywhere else the real + // profile and X's request gap. + const chromium = fakeXProfileChromium(paths.transcriptsDir); + return runManagedFunction({ + kind: READ_X_TRENDING_KIND, + queueKey: X_TRENDING_QUEUE, + paths, + channelSlug: plan.slug, + fn: async (onLog, signal) => + done( + onLog, + await runXTrendingRead({ + paths, + plan, + onLog, + signal, + deps: { + profileBusy: xPressInFlight, + ...(chromium ? { chromium, pauseMs: () => 50 } : {}), + }, + }), + ), + }); +} diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts @@ -42,6 +42,7 @@ import { import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { X_SEARCH_NOT_ON_A_SITE } from "yt-dlp-transcript-common/lib/site"; import { xSearchFromUrl, xSearchQueryOfUrl } from "yt-dlp-transcript-common/lib/xSearch/config"; +import { X_TRENDING_NOT_ON_A_SITE } from "yt-dlp-transcript-common/lib/xTrending/config"; import { saveSettings, saveSettingsHeld, withSettingsLock } from "../settings/saveSettings"; import { LANES, @@ -288,6 +289,10 @@ export async function createChannelFromForm( if (config.xSearch && requests && requests.length > 0) { return fail(X_SEARCH_NOT_ON_A_SITE(slug)); } + // Nor an X trending library (lane x-trending): private. + if (config.xTrending && requests && requests.length > 0) { + return fail(X_TRENDING_NOT_ON_A_SITE(slug)); + } if (requests) { siteWrites = planSiteMembershipWrites(paths, slug, requests); } @@ -380,6 +385,18 @@ export async function updateChannelAction( } catch (e) { return { error: (e as Error).message, values }; } + // A library is made one when it is created and stays one (lane x-trending): + // a Configure save that would turn a private library into an ordinary + // channel (which a site may hold), or an account's channel into a library, + // is refused before anything is written. + if (Boolean(existing.xTrending) !== Boolean(parsed.config.xTrending)) { + return { + error: existing.xTrending + ? `${slug} is an X trending library and stays one: its platform cannot be changed. Delete the channel to be rid of it.` + : `${slug} is not an X trending library, and Configure cannot make it one: create a new channel with platform "X trending library".`, + values, + }; + } // A stored value today's checks refuse, saved unchanged: the save stands. // The form has no place for a warning, so the server log says it. for (const w of parsed.warnings) console.warn(`Channel ${slug} saved with a warning: ${w}`); @@ -394,6 +411,9 @@ export async function updateChannelAction( if (parsed.config.xSearch && requests && requests.length > 0) { return { error: X_SEARCH_NOT_ON_A_SITE(slug), values }; } + if (parsed.config.xTrending && requests && requests.length > 0) { + return { error: X_TRENDING_NOT_ON_A_SITE(slug), values }; + } if (requests) { siteWrites = planSiteMembershipWrites(paths, slug, requests); } diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx @@ -45,6 +45,7 @@ import { waybackTargetFromUrl, waybackTargetHost } from "yt-dlp-transcript-commo import { WaybackTargetsField } from "./WaybackTargetsField"; import { XSearchFields } from "./XSearchFields"; import { isXSearchUrl, xSearchFromUrl } from "yt-dlp-transcript-common/lib/xSearch/config"; +import { XTrendingFields } from "./XTrendingFields"; import { MANUAL_DOWNLOADS_TEXT } from "yt-dlp-transcript-common/lib/manualDownloads"; import { SKIP_SHORTS_TEXT } from "yt-dlp-transcript-common/lib/skipShorts"; import { probeChannelUrlAction } from "../actions"; @@ -213,7 +214,7 @@ export function ChannelForm({ c?.handling === "transcribe" ? "transcribe" : "youtube", ); const [handlingTouched, setHandlingTouched] = useState(false); - const [platform, setPlatform] = useState<string>(c?.xSearch ? "x-search" : (c?.platform ?? "")); + const [platform, setPlatform] = useState<string>(c?.xTrending ? "x-trending" : c?.xSearch ? "x-search" : (c?.platform ?? "")); const [platformTouched, setPlatformTouched] = useState(false); // Social sources are ingested into the posts corpus, not the video pipeline, // so every video-only control below is hidden for them. In edit mode this is @@ -227,9 +228,12 @@ export function ChannelForm({ : isSocialPlatform(platform as Platform) || isSocialPlatform(detectPlatform(url)) || isWaybackPagesUrl(url) || - platform === "x-search"; + platform === "x-search" || + platform === "x-trending"; // An X search channel (release 38): a query across accounts, never on a site. const isXSearch = isEdit ? Boolean(c?.xSearch) : !creatingLocal && platform === "x-search"; + // An X trending library (lane x-trending): private, no URL, never on a site. + const isXTrending = isEdit ? Boolean(c?.xTrending) : !creatingLocal && platform === "x-trending"; // A Wayback pages channel (release 37): captures of pages, no fetcher; its // scope is its targets. const isWaybackPages = isEdit ? c?.platform === "webpage" : platform === "webpage"; @@ -376,7 +380,11 @@ export function ChannelForm({ )} </Section> <Section title="Sites"> - {isXSearch ? ( + {isXTrending ? ( + <span data-x-trending-no-site="" className="text-xs text-muted-foreground"> + An X trending library is private: it is never put on a site. + </span> + ) : isXSearch ? ( <span data-x-search-no-site="" className="text-xs text-muted-foreground"> An X search channel is never put on a site. </span> @@ -456,7 +464,7 @@ export function ChannelForm({ <SeededSelect state={state} name="platform" - initial={c?.xSearch ? "x-search" : (c?.platform ?? "")} + initial={c?.xTrending ? "x-trending" : c?.xSearch ? "x-search" : (c?.platform ?? "")} className="rounded border border-border bg-card px-2 py-1 text-sm" > <option value="">Auto (detect from URL)</option> @@ -469,6 +477,7 @@ export function ChannelForm({ <option value="bitchute">BitChute</option> <option value="twitter">X / Twitter (posts)</option> <option value="x-search">X search (posts from any account)</option> + <option value="x-trending">X trending library (private)</option> <option value="bluesky">Bluesky (posts)</option> <option value="xenforo">Forum thread — XenForo (posts)</option> <option value="webpage">Archived pages (Wayback Machine, archive.today)</option> @@ -593,6 +602,7 @@ export function ChannelForm({ <option value="bitchute">BitChute</option> <option value="twitter">X / Twitter (posts)</option> <option value="x-search">X search (posts from any account)</option> + <option value="x-trending">X trending library (private)</option> <option value="bluesky">Bluesky (posts)</option> <option value="xenforo">Forum thread — XenForo (posts)</option> <option value="webpage">Archived pages (Wayback Machine, archive.today)</option> @@ -607,7 +617,11 @@ export function ChannelForm({ <legend className="px-1 text-xs font-medium uppercase tracking-wide text-muted-foreground"> On create </legend> - {isWaybackPages ? ( + {isXTrending ? ( + <span className="text-xs text-muted-foreground"> + Nothing is fetched on create: read a trending page from the channel page. + </span> + ) : isWaybackPages ? ( <span className="text-xs text-muted-foreground"> Nothing is fetched on create: import captures from the channel page. </span> @@ -688,7 +702,10 @@ export function ChannelForm({ {isSocial && isXSearch && ( <XSearchFields {...(isEdit ? (c?.xSearch ? { initial: c.xSearch } : {}) : { derivedFrom: url })} /> )} - {isSocial && !isWaybackPages && !isXSearch && ( + {isSocial && isXTrending && ( + <XTrendingFields {...(isEdit && c?.xTrending ? { initial: c.xTrending } : {})} /> + )} + {isSocial && !isWaybackPages && !isXSearch && !isXTrending && ( <> {/* A social source is ingested into the posts corpus, so it carries its fetcher + handle instead of any of the video controls. */} diff --git a/editor/app/channels/components/XTrendingFields.tsx b/editor/app/channels/components/XTrendingFields.tsx @@ -0,0 +1,53 @@ +// An X trending library's fields on the channel form (lane x-trending): the +// caps a read of a trending page uses when the read names none. Posted as +// xTrendingMaxScrolls / xTrendingMaxPosts; parseChannelForm refuses a value +// out of range with a sentence. Blank is the default. + +import { + X_TRENDING_DEFAULT_POSTS, + X_TRENDING_DEFAULT_SCROLLS, + X_TRENDING_MAX_POSTS, + X_TRENDING_MAX_SCROLLS, + type XTrendingConfig, +} from "yt-dlp-transcript-common/lib/xTrending/config"; + +export function XTrendingFields({ initial }: { initial?: XTrendingConfig }) { + const input = "w-28 rounded border border-border bg-card px-2 py-1 text-sm"; + return ( + <fieldset data-x-trending-fields="" className="flex flex-col gap-3 rounded-md border border-border px-3 py-2"> + <legend className="px-1 text-xs font-medium uppercase tracking-wide text-muted-foreground"> + X trending library + </legend> + <input type="hidden" name="sourceKind" value="social" /> + <span className="text-xs text-muted-foreground"> + Private. Each trending page is read on the channel page, one job at a time on X&apos;s queue. + </span> + <div className="flex flex-wrap gap-4"> + <label className="flex flex-col gap-1 text-sm"> + <span className="font-medium">Scrolls per read</span> + <input + type="number" + name="xTrendingMaxScrolls" + min={1} + max={X_TRENDING_MAX_SCROLLS} + defaultValue={initial?.maxScrolls ?? ""} + placeholder={String(X_TRENDING_DEFAULT_SCROLLS)} + className={input} + /> + </label> + <label className="flex flex-col gap-1 text-sm"> + <span className="font-medium">Posts per read</span> + <input + type="number" + name="xTrendingMaxPosts" + min={1} + max={X_TRENDING_MAX_POSTS} + defaultValue={initial?.maxPosts ?? ""} + placeholder={String(X_TRENDING_DEFAULT_POSTS)} + className={input} + /> + </label> + </div> + </fieldset> + ); +} diff --git a/editor/app/channels/components/channelConfigToForm.ts b/editor/app/channels/components/channelConfigToForm.ts @@ -79,6 +79,9 @@ export const CHANNEL_FORM_VALUES = [ "xSearchWindowMonths", "xSearchLang", "xSearchExclude", + // An X trending library's caps (lane x-trending): whole numbers, "" clears. + "xTrendingMaxScrolls", + "xTrendingMaxPosts", ] as const; export type ChannelFormFlag = (typeof CHANNEL_FORM_FLAGS)[number]; @@ -108,7 +111,9 @@ export function channelConfigToFormData(config: ChannelConfig): FormData { fd.set("name", config.name ?? ""); fd.set("handling", config.handling ?? "transcribe"); put(fd, "url", config.url); - put(fd, "platform", config.platform); + // A trending library is the platform CHOICE "x-trending" on the form (its + // stored platform is "twitter"): parseChannelForm keeps it a library by it. + put(fd, "platform", config.xTrending ? "x-trending" : config.platform); put(fd, "sourceKind", config.sourceKind); put(fd, "postFetcher", config.postFetcher); put(fd, "socialHandle", config.socialHandle); @@ -156,6 +161,8 @@ export function channelConfigToFormData(config: ChannelConfig): FormData { putNum(fd, "xSearchWindowMonths", config.xSearch?.windowMonths); put(fd, "xSearchLang", config.xSearch?.lang); if (config.xSearch?.exclude?.length) fd.set("xSearchExclude", JSON.stringify(config.xSearch.exclude)); + putNum(fd, "xTrendingMaxScrolls", config.xTrending?.maxScrolls); + putNum(fd, "xTrendingMaxPosts", config.xTrending?.maxPosts); // Ticked when the check is on: said so, or the platform's default (an // Odysee channel with no `audioCheck`; lib/audioCheckPolicy.ts) — so a patch // that does not name it keeps what the channel has. diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts @@ -434,3 +434,49 @@ test("a Rumble URL parses to platform rumble, and the create defaults fill what assert.equal(none.cookiesFromBrowser, undefined); assert.equal(none.ytdlpExtraArgs, undefined); }); + +// --- lane x-trending: the "X trending library" platform choice --- + +test("the X trending choice makes a library: X, social, no URL, no handle, no fetcher", () => { + const { config } = parseChannelForm(form({ handling: "transcribe", platform: "x-trending" })); + assert.equal(config.platform, "twitter"); + assert.equal(config.sourceKind, "social"); + assert.equal(config.url, undefined); + assert.equal(config.socialHandle, undefined); + assert.equal(config.postFetcher, undefined); + assert.deepEqual(config.xTrending, {}); + assert.ok((CHANNEL_FORM_FIELDS as readonly string[]).includes("xTrending")); + const capped = parseChannelForm( + form({ handling: "transcribe", platform: "x-trending", xTrendingMaxScrolls: "4", xTrendingMaxPosts: "200" }), + ).config; + assert.deepEqual(capped.xTrending, { maxScrolls: 4, maxPosts: 200 }); +}); + +test("a library refuses a URL and a cap out of range, in sentences", () => { + const refused = (fields: Record<string, string>) => () => + parseChannelForm(form({ handling: "transcribe", platform: "x-trending", ...fields })); + assert.throws(refused({ url: "https://x.com/i/trending/1900000000000000001" }), /An X trending library has no URL/); + assert.throws(refused({ url: "https://x.com/example_user" }), /An X trending library has no URL/); + assert.throws(refused({ xTrendingMaxScrolls: "21" }), /scroll cap is a whole number, 1–20/); + assert.throws(refused({ xTrendingMaxPosts: "0" }), /post cap is a whole number, 1–200/); + assert.throws(refused({ xTrendingMaxPosts: "many" }), /post cap is a whole number, 1–200/); + // An ordinary X account is not a library. + assert.equal(parseChannelForm(form({ handling: "transcribe", url: "https://x.com/example_user" })).config.xTrending, undefined); +}); + +test("a stored library round-trips through the Configure form, and a patch sets its caps", () => { + const stored = { + handling: "transcribe" as const, + name: "Trending", + sourceKind: "social" as const, + platform: "twitter" as const, + xTrending: { maxPosts: 40 }, + }; + const fd = channelConfigToFormData(stored); + assert.equal(fd.get("platform"), "x-trending"); + assert.deepEqual(parseChannelForm(fd).config.xTrending, { maxPosts: 40 }); + assert.equal(parseChannelForm(fd).config.platform, "twitter"); + validateChannelFormPatch({ xTrendingMaxScrolls: 5, xTrendingMaxPosts: "" }); + applyChannelFormPatch(fd, { xTrendingMaxScrolls: 5, xTrendingMaxPosts: "" }); + assert.deepEqual(parseChannelForm(fd).config.xTrending, { maxScrolls: 5 }); +}); diff --git a/editor/app/channels/components/parseChannelForm.ts b/editor/app/channels/components/parseChannelForm.ts @@ -40,6 +40,12 @@ import { xSearchUrl, type XSearchConfig, } from "yt-dlp-transcript-common/lib/xSearch/config"; +import { + X_TRENDING_HAS_NO_URL, + X_TRENDING_MAX_POSTS, + X_TRENDING_MAX_SCROLLS, + type XTrendingConfig, +} from "yt-dlp-transcript-common/lib/xTrending/config"; import { isCookieMode } from "yt-dlp-transcript-common/lib/cookiePolicy"; import { isDownloadFormatPreset, @@ -112,6 +118,9 @@ export const CHANNEL_FORM_FIELDS = [ "mirror", "wayback", "xSearch", + // Lane x-trending: the library's caps. The marker itself is set at creation + // and a Configure save can neither add nor remove it (channels/actions.ts). + "xTrending", ] as const satisfies ReadonlyArray<keyof ChannelConfig>; // Maps FormData -> ChannelConfig. Throws on invalid input so the server @@ -142,8 +151,12 @@ export function parseChannelForm( (isXSearchUrl(typedUrl) || (platformRaw === "twitter" && stringOrUndef(formData, "xSearchQuery") !== undefined))) ? parseXSearchFields(formData, typedUrl) : undefined; + // AN X TRENDING LIBRARY (lane x-trending): the platform choice "X trending + // library". No URL (its pages are read one at a time), no account, no + // fetcher; private, never on a site. + const xTrending = platformRaw === X_TRENDING_PLATFORM_CHOICE ? parseXTrendingFields(formData, typedUrl) : undefined; const url = xSearch ? xSearchUrl(xSearch.query) : typedUrl; - const platform: Platform | undefined = xSearch + const platform: Platform | undefined = xSearch || xTrending ? "twitter" : PLATFORM_VALUES.includes(platformRaw as Platform) ? (platformRaw as Platform) @@ -166,22 +179,24 @@ export function parseChannelForm( // A search channel is walked by the one fetcher that can (gallery-dl). const postFetcher = xSearch ? "x-gallery-dl" + : xTrending + ? undefined : sourceKind === "social" ? stringOrUndef(formData, "postFetcher") : undefined; const socialHandleRaw = - sourceKind === "social" && !xSearch ? stringOrUndef(formData, "socialHandle") : undefined; + sourceKind === "social" && !xSearch && !xTrending ? stringOrUndef(formData, "socialHandle") : undefined; // A Wayback pages channel's scope: the form's target rows (one hidden JSON // field), else one target derived from the URL. const wayback = platform === "webpage" ? parseWaybackTargets(formData, url) : undefined; const socialHandle = socialHandleRaw?.replace(/^@/, "") || (wayback ? waybackTargetHost(wayback.targets[0]) : undefined) || - (sourceKind === "social" && url && !xSearch + (sourceKind === "social" && url && !xSearch && !xTrending ? (handleFromAccountUrl(url) ?? undefined) : undefined); // A search channel has no account: its query is what it archives. - if (sourceKind === "social" && !socialHandle && !xSearch) { + if (sourceKind === "social" && !socialHandle && !xSearch && !xTrending) { throw new Error( "A social source needs an account handle (could not derive one from the URL)", ); @@ -529,10 +544,37 @@ export function parseChannelForm( if (mirrorOf.length > 0) config.mirror = { of: mirrorOf }; if (wayback) config.wayback = wayback; if (xSearch) config.xSearch = xSearch; + if (xTrending) config.xTrending = xTrending; return { name, slug, config, warnings }; } +// The platform select's value for an X trending library: not a platform (the +// channel's platform is "twitter"), a kind of X channel. +export const X_TRENDING_PLATFORM_CHOICE = "x-trending"; + +// An X trending library's marker and caps: the form's xTrendingMaxScrolls and +// xTrendingMaxPosts (blank: the defaults). A URL is refused — the library has +// none — and a cap out of range is refused, never clamped. +function parseXTrendingFields(formData: FormData, url: string | undefined): XTrendingConfig { + if (url) throw new Error(X_TRENDING_HAS_NO_URL); + const cap = (key: string, max: number, what: string): number | undefined => { + const raw = stringOrUndef(formData, key); + if (raw === undefined) return undefined; + const n = Number(raw); + if (!Number.isInteger(n) || n < 1 || n > max) { + throw new Error(`An X trending library's ${what} is a whole number, 1–${max}`); + } + return n; + }; + const maxScrolls = cap("xTrendingMaxScrolls", X_TRENDING_MAX_SCROLLS, "scroll cap"); + const maxPosts = cap("xTrendingMaxPosts", X_TRENDING_MAX_POSTS, "post cap"); + return { + ...(maxScrolls !== undefined ? { maxScrolls } : {}), + ...(maxPosts !== undefined ? { maxPosts } : {}), + }; +} + // The platform select's value for an X search channel: not a platform (the // channel's platform is "twitter"), a kind of X channel. export const X_SEARCH_PLATFORM_CHOICE = "x-search"; diff --git a/editor/app/lib/cookieRefreshGuard.test.ts b/editor/app/lib/cookieRefreshGuard.test.ts @@ -138,3 +138,63 @@ test("a throw before the press (finding the paths) never leaves the service mark ); assert.equal(runningCookieActions([]).rumble, undefined); }); + +// --- lane x-trending: one browser on the X profile at a time --- + +test("X's Connect and Refresh are refused while a job holds the profile's browser; nothing else is", async () => { + const { xProfileJobRunning } = await import("./cookieRefreshGuard"); + const at = Date.parse("2026-11-17T10:02:11Z"); + const reading = () => [{ id: "J1", kind: "read-x-trending", queueKey: "platform:twitter", status: "running", queuedAt: 0, startedAt: at }]; + const capturing = () => [{ id: "J2", kind: "capture-posts", queueKey: "platform:twitter", status: "running", queuedAt: 0, startedAt: at }]; + let ran = 0; + const press = (service: string, action: "connect" | "refresh" | "recheck", jobs: () => never[]) => + withCookieAction(service, action, async () => { ran++; return { ok: true as const }; }, () => ({ ok: true, message: "done" }), { paths, jobs }); + const refused = await press("x", "connect", reading as never); + assert.deepEqual(refused, { + ok: false, + busy: true, + error: + "X's connect opens the connected profile, and a job is using it: Read X trending page (J1, running since 10:02:11 UTC). " + + "Wait for it to finish, then press again.", + }); + const refresh = await press("x", "refresh", capturing as never); + assert.match((refresh as { error: string }).error, /^X's refresh opens the connected profile, and a job is using it: Capture posts \(J2,/); + assert.equal(ran, 0); + // The refused press left no mark: X is not shown as running. + assert.equal(runningCookieActions([]).x, undefined); + // A queued read holds nothing yet; a capture on another platform's queue, a + // fetch on X's, a recheck of X and another service's press are not held. + const idle = [ + { id: "J3", kind: "read-x-trending", queueKey: "platform:twitter", status: "queued", queuedAt: 0 }, + { id: "J4", kind: "capture-posts", queueKey: "platform:bluesky", status: "running", queuedAt: 0 }, + { id: "J5", kind: "fetch-posts", queueKey: "platform:twitter", status: "running", queuedAt: 0 }, + { id: "J6", kind: "read-x-trending", queueKey: "platform:twitter", status: "done", queuedAt: 0 }, + ]; + assert.equal(xProfileJobRunning(idle), null); + assert.deepEqual(await press("x", "refresh", (() => idle) as never), { ok: true }); + assert.deepEqual(await press("x", "recheck", reading as never), { ok: true }); + assert.deepEqual(await press("rumble", "refresh", reading as never), { ok: true }); + assert.equal(ran, 3); +}); + +test("a trending read is refused while X's Connect or Refresh is in flight, and only then", async () => { + const { xPressInFlight } = await import("./cookieRefreshGuard"); + assert.equal(xPressInFlight(), null); + let release!: () => void; + const gate = new Promise<void>((r) => (release = r)); + const connecting = withCookieAction("x", "connect", async () => { await gate; return { ok: true as const }; }, () => ({ ok: true, message: "Connected." }), { paths, jobs: noJobs }); + assert.match( + xPressInFlight() ?? "", + /^X's connect is running \(since \d\d:\d\d:\d\d UTC\) and holds the connected profile: read the trending page once it has finished\.$/, + ); + release(); + await connecting; + assert.equal(xPressInFlight(), null); + // A recheck of X opens no profile: a read is not held by it. + let free!: () => void; + const wait = new Promise<void>((r) => (free = r)); + const rechecking = withCookieAction("x", "recheck", async () => { await wait; return { ok: true as const }; }, () => ({ ok: true, message: "clean" }), { paths, jobs: noJobs }); + assert.equal(xPressInFlight(), null); + free(); + await rechecking; +}); diff --git a/editor/app/lib/cookieRefreshGuard.ts b/editor/app/lib/cookieRefreshGuard.ts @@ -12,6 +12,17 @@ // (noteServiceCookieAction, `.service-cookies.json` `actions`), which the // screen shows as "last result". // +// +// THE X PROFILE HAS ONE BROWSER AT A TIME (lane x-trending). X's Connect and +// Refresh open the connected profile; so do the jobs that read X through it +// (a trending-page read, a post capture: X_PROFILE_BROWSER_JOB_KINDS), which +// X's queue already keeps one at a time among themselves. Two browsers on one +// profile is a launch that fails with Chromium's own error, so each side is +// refused with a sentence instead: a Connect or Refresh while such a job is +// RUNNING (`xProfileJobRunning`), and the trending read while a Connect or +// Refresh is in flight (`xPressInFlight`, asked at enqueue and at its start). +// Nothing else about Connect or Refresh changes. +// // The mark lives on globalThis (one per server process, like the registry). import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths"; @@ -20,6 +31,8 @@ import { noteServiceCookieAction } from "yt-dlp-transcript-common/lib/serviceCoo import { serviceLabel, type ServiceCookieActionKind } from "yt-dlp-transcript-common/lib/serviceCookies"; import type { CookieRunning } from "yt-dlp-transcript-common/lib/cookieStatus"; import { RECHECK_JOB_KIND } from "yt-dlp-transcript-common/controller/serviceCookieTimer"; +import { X_PROFILE_BROWSER_JOB_KINDS, X_TRENDING_QUEUE } from "yt-dlp-transcript-common/lib/xTrending/config"; +import { jobKindLabel } from "yt-dlp-transcript-common/jobs/jobKinds"; const QUEUE_PREFIX = "service-cookies:"; const KEY = Symbol.for("archilyzer.cookieRefresh.inflight"); @@ -51,6 +64,37 @@ export function runningCookieActions( return out; } +// A job that holds the connected X profile's browser now: one of the kinds +// that open it, RUNNING on X's queue (a queued one holds nothing yet). +export function xProfileJobRunning( + jobs: readonly JobLike[] = getRegistry().list(), +): { kind: string; since: string; jobId: string } | null { + for (const j of jobs) { + if (j.status !== "running" || j.queueKey !== X_TRENDING_QUEUE) continue; + if (!X_PROFILE_BROWSER_JOB_KINDS.includes(j.kind)) continue; + return { kind: j.kind, since: new Date(j.startedAt ?? j.queuedAt ?? Date.now()).toISOString(), jobId: j.id }; + } + return null; +} + +export function xProfileJobSentence(action: string, job: { kind: string; since: string; jobId: string }): string { + return ( + `X's ${action} opens the connected profile, and a job is using it: ${jobKindLabel(job.kind)} ` + + `(${job.jobId}, running since ${job.since.slice(11, 19)} UTC). Wait for it to finish, then press again.` + ); +} + +// Why a job may not open the X profile now — a Connect or a Refresh of X is +// in flight — or null. (A recheck opens no profile.) +export function xPressInFlight(): string | null { + const r = inflight().get("x"); + if (!r || (r.action !== "connect" && r.action !== "refresh")) return null; + return ( + `X's ${r.action} is running (since ${r.since.slice(11, 19)} UTC) and holds the connected profile: ` + + `read the trending page once it has finished.` + ); +} + export function busySentence(service: string, r: CookieRunning): string { return `${serviceLabel(service)}'s ${r.action} is already running (since ${r.since.slice(11, 19)} UTC) — wait for it to finish.`; } @@ -86,6 +130,10 @@ export async function withCookieAction<T>( ): Promise<T | { ok: false; error: string; busy: true }> { const running = runningCookieActions(opts.jobs ? opts.jobs() : undefined)[service]; if (running) return { ok: false, error: busySentence(service, running), busy: true }; + if (service === "x" && (action === "connect" || action === "refresh")) { + const job = xProfileJobRunning(opts.jobs ? opts.jobs() : undefined); + if (job) return { ok: false, error: xProfileJobSentence(action, job), busy: true }; + } const map = inflight(); map.set(service, { action, since: new Date().toISOString() }); // Everything after the mark is inside the try: whatever throws, the finally diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -11,6 +11,7 @@ // pnpm ops <action> [--json '<body>' | --file <path>] [--wait] // [--wait-timeout <seconds>] [--quiet] // pnpm ops get channel <slug> [--counts] [--leads [--limit <n>]] +// pnpm ops get trending <slug> [--topic <topicId>] [--limit <n>] // pnpm ops get channels // pnpm ops get tags [<tagId>] // pnpm ops get job <id> [--tail [<lines>]] @@ -172,6 +173,11 @@ // pnpm ops get channel demo-search --leads --limit 20 // pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"archive","dryRun":true}' // pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"never"}' +// pnpm ops create-channel --json '{"fields":{"name":"Trending","handling":"transcribe","platform":"x-trending"}}' +// pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","probe":true}' --wait +// pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","topic":"Kettle festival"}' --wait +// pnpm ops read-x-trending --json '{"slug":"trending","reparse":"tr-01JA0000000000000000000000"}' --wait +// pnpm ops get trending trending --topic kettle-festival --limit 50 // pnpm ops import-page --json '{"slug":"demo-pages","url":"https://web.archive.org/web/20140305120000/https://blog.example/a-post.html","dryRun":true}' // pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20140301"}' --wait // pnpm ops reextract-pages --json '{"slug":"demo-pages","dryRun":true}' --wait @@ -335,6 +341,14 @@ const GETTERS = { // until the next refresh" — the X posts channels in the default order, and // the jar's age against social.x.maxCookieAgeMinutes. "x-run": (run) => (run ? `/api/ops/x-run?run=${encodeURIComponent(run)}` : "/api/ops/x-run"), + // An X trending library's topics and posts (lane x-trending), from its own + // files: --topic narrows the posts to one topic, --limit caps them. + trending: (slug, { jobs }) => { + const q = new URLSearchParams({ slug }); + if (jobs.topic) q.set("topic", jobs.topic); + if (jobs.limit) q.set("limit", String(jobs.limit)); + return `/api/ops/trending?${q.toString()}`; + }, // One channel's cleanup row: what each sweep would reclaim, what holds the rest. cleanup: (slug) => `/api/ops/cleanup/${encodeURIComponent(slug)}`, // The speakers readout: waiting, freed this run, rate, days left, per channel. @@ -414,6 +428,7 @@ const GET_FLAGS = { transcript: ["slug"], "lookout-run": ["run"], channel: ["counts", "leads", "limit"], + trending: ["topic", "limit"], job: ["tail"], jobs: ["active", "failed", "kind", "slug", "limit"], }; @@ -685,6 +700,10 @@ const ACTIONS = [ // account as its own X channel on no site, or never archive it (hidden), // or restore it ({slug, handle, action, name?, fetch?, dryRun?}). "x-search-lead", + // X TRENDING (lane x-trending): one trending page read into a private + // library, as one job on X's queue ({slug, url, topic?, scrolls?, posts?, + // probe?, headed?}), or a saved read parsed again offline ({slug, reparse}). + "read-x-trending", // EVIDENCE GAPS (release 29 E2): the Wayback Machine's captures of a page // ({url} or a record's {slug, id}), read only and paced; and find-copy — a // copy of every gone recording a report cites (Wayback, then archive.org), @@ -809,6 +828,9 @@ export const FIND_CLIPS_RESULT_MARKER = "@@find-clips "; export const LIVE_CLIP_RESULT_MARKER = "@@live-clip "; // The same for an X run (X_RUN_RESULT_MARKER in common/controller/xRun.ts). export const X_RUN_RESULT_MARKER = "@@x-run "; +// The same string is READ_X_TRENDING_RESULT_MARKER in +// common/controller/readXTrending.ts. +export const READ_X_TRENDING_RESULT_MARKER = "@@read-x-trending "; // The same for a lookout run (LOOKOUT_RUN_RESULT_MARKER in // common/controller/lookoutRun.ts). export const LOOKOUT_RUN_RESULT_MARKER = "@@lookout-run "; @@ -872,8 +894,8 @@ export function parseArgs(argv) { } else if (arg === "--active" || arg === "--failed") { jobs[arg.slice(2)] = true; used.add(arg.slice(2)); - } else if (/^--(kind|slug|limit|run)(=|$)/.test(arg)) { - const [, key, eq] = /^--(kind|slug|limit|run)(=?)/.exec(arg); + } else if (/^--(kind|slug|limit|run|topic)(=|$)/.test(arg)) { + const [, key, eq] = /^--(kind|slug|limit|run|topic)(=?)/.exec(arg); const raw = eq ? arg.slice(key.length + 3) : argv[++i]; if (raw === undefined || raw === "") { return { error: `--${key} needs a value` }; @@ -1068,6 +1090,7 @@ export function parseArgs(argv) { ...(action === "find-clips" ? { resultMarker: FIND_CLIPS_RESULT_MARKER } : {}), ...(action === "live-clip" ? { resultMarker: LIVE_CLIP_RESULT_MARKER } : {}), ...(action === "x-run" ? { resultMarker: X_RUN_RESULT_MARKER } : {}), + ...(action === "read-x-trending" ? { resultMarker: READ_X_TRENDING_RESULT_MARKER } : {}), ...(action === "report-schedule" ? { resultMarker: REPORT_TICK_RESULT_MARKER } : {}), wait, quiet, @@ -1158,6 +1181,7 @@ export function usage() { " pnpm ops get x-session [<slug>]", " pnpm ops get cookies [fresh]", " pnpm ops get x-run [<run id>]", + " pnpm ops get trending <slug> [--topic <topicId>] [--limit <n>]", " pnpm ops get cleanup <slug>", " pnpm ops get speakers", " pnpm ops get lookouts [<id>]", @@ -1267,6 +1291,14 @@ export function usage() { " browser's cookie store (names and times only, never a value) instead of", " the 5-minute cache. Check again is recheck-service; Refresh cookies and", " the Connects are clicks on /cookies.", + "get trending <slug> [--topic <topicId>] [--limit <n>] is an X trending", + " library's topics and posts, read from its own files (a library is in no", + " index): topics [{id, title, posts, sources: [{trendId, url, reads,", + " lastReadAt}]}], posts [{id, author, createdAt, url, text, media: {count,", + " kinds}, topic, reads: [{read, trendId, at}]}] (the newest read's first,", + " in page order; --limit 1-500, default 100; total is the count before", + " it) and reads (the saved reads' ids, newest first). Never the raw", + " capture, a cookie or a token.", "get x-run [<run id>] is the X run as /review's X run console shows it:", " the latest run (or the one named) — each channel's status (queued,", " running, done with its new posts, deferred, failed), \"summary\" (\"N", @@ -1844,6 +1876,33 @@ export function usage() { " drained fetch stops at its next resume point and the next run of the", " same walk resumes there.", "", + 'read-x-trending reads ONE X trending page into an X trending library:', + ' {"slug", "url": "https://x.com/i/trending/<number>"}, as one job on X\'s', + " queue (the fresh-jar rule, the X alert and X's job gap apply; ask get", + " x-session first). The page is opened in the connected X profile's", + " browser, every GraphQL answer the page itself fetched is saved raw with", + " a screenshot (channels/<slug>/trending/reads/<readId>/), and the posts", + " are parsed from the saved file and written as the library's posts. A", + " read lists posts; it archives no media and no thread. \"topic\": a", + " topic's id or name, or a new one's name (absent: the topic this page was", + " read into before, else a new one named for it). \"scrolls\": 1-20 moves", + " to the bottom of the page (default: the channel's cap, else 8);", + " \"posts\": stop once 1-200 are seen (else 60); a read also stops after two", + " scrolls with nothing new, and at once on a 429 or a login wall — nothing", + " retries. \"probe\": true saves the capture and its summary and writes no", + " post. \"headed\": true opens a window on the editor's desktop. {\"slug\",", + " \"reparse\": \"<readId>\"} parses a saved read again OFFLINE (X is asked", + " nothing; no fresh jar needed). --wait prints the log's @@read-x-trending", + " {ok, mode, read, outcome, stop, responses, operations (names and sizes,", + " never a body), posts: {onPage, added}, topic, sentence}; a capture with", + " no post the parser knows ends ok, \"read saved, nothing recognised\".", + " Refused before a job: not a library, not a trending page URL, a cap out", + " of range, no connected X profile, X's Connect or Refresh in flight, a", + " stale jar. A library is made with create-channel, \"platform\":", + " \"x-trending\" (no \"url\", no \"sites\": it is private, never on a site,", + " in no index build; \"xTrendingMaxScrolls\"?, \"xTrendingMaxPosts\"? set", + " its caps).", + "", 'x-run fetches several X posts channels IN SEQUENCE as ONE job on X\'s', ' queue: {"channels": [slug, ...]} in that order, each a fetch-posts sync', ' new of at most 200 posts ("limit": N, 1-200, caps it lower), X\'s queue', diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -1131,3 +1131,22 @@ test("the local-media actions are POSTs to their routes, named in the usage", () assert.equal(parseArgs(["local-media-import", "--json", '{"slug":"demo-local","allNew":true}', "--wait"]).wait, true); assert.match(usage(), /Actions:.*record-live, local-media-configure, local-media-preview, local-media-prepare, local-media-import, local-media-link/); }); + +// Lane x-trending: one trending page read into a private library, and the +// library's listing. +test("read-x-trending is a POST with a result marker; get trending reads the library's listing", () => { + const p = parseArgs(["read-x-trending", "--json", '{"slug":"lib","url":"https://x.com/i/trending/1900000000000000001","probe":true}', "--wait"]); + assert.equal(p.method, "POST"); + assert.equal(p.path, "/api/ops/read-x-trending"); + assert.deepEqual(p.body, { slug: "lib", url: "https://x.com/i/trending/1900000000000000001", probe: true }); + assert.equal(p.resultMarker, "@@read-x-trending "); + assert.equal(parseArgs(["get", "trending", "lib"]).path, "/api/ops/trending?slug=lib"); + assert.equal(parseArgs(["get", "trending", "lib", "--topic", "kettle-festival", "--limit", "50"]).path, "/api/ops/trending?slug=lib&topic=kettle-festival&limit=50"); + assert.equal(parseArgs(["get", "trending", "lib", "--topic=a b"]).path, "/api/ops/trending?slug=lib&topic=a+b"); + assert.match(parseArgs(["get", "trending"]).error, /trending/); + assert.match(parseArgs(["get", "trending", "lib", "--leads"]).error, /get trending does not take --leads/); + assert.match(parseArgs(["get", "channel", "s", "--topic", "x"]).error, /get channel does not take --topic/); + assert.match(usage(), /pnpm ops get trending <slug> \[--topic <topicId>\] \[--limit <n>\]/); + assert.match(usage(), /read-x-trending reads ONE X trending page into an X trending library/); + assert.match(usage(), /Actions:.*x-search-lead, read-x-trending/); +});