Archilyzer · Source

archilyzer

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

commit c470c4be8a063bdb033ba864cff3721cbca1ef82
parent 78996182e946bfe204dafbf962514b827e443c0e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 07:45:49 -0500

umtool e2e: library.spec, over a stub editor's invented library -- the stub answers GET /api/ops/trending with the judge view's asks and records judge-trending, watch-trending and purge-trending with the `by` each carried (editor-stub-trending.mjs); the spec's fixture channel holds the captured files umtool's media route serves and is removed after it. Thirteen tests: the stream's order, topics and watches, a post with its media and words, the presses and undo, the keys, every filter and Mark seen, bulk as one ask, the watch switch, the purge, the media route's refusals, the operator stamp, 360 px, and the editor down

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

Diffstat:
Aumtool/e2e/fixtures/editor-stub-trending.mjs | 231+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/editor-stub.mjs | 5+++++
Aumtool/e2e/fixtures/library-fixture.mjs | 128+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/library.spec.ts | 551+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4 files changed, 915 insertions(+), 0 deletions(-)

diff --git a/umtool/e2e/fixtures/editor-stub-trending.mjs b/umtool/e2e/fixtures/editor-stub-trending.mjs @@ -0,0 +1,231 @@ +// The editor's X trending library, stubbed for umtool's Posts library page +// (library.spec.ts; lane posts-library): GET /api/ops/trending with the judge +// view's asks, and the three presses — judge-trending, watch-trending, +// purge-trending — over an invented library held in memory +// (library-fixture.mjs libraryState). Every press is RECORDED with the `by` +// it carried, which is the part no page shows. +// +// POST /__stub/trending {reset?: true, mode?: "ok" | "unreachable" | "none"} +// "unreachable": every trending route drops the connection (the editor is down); +// "none": the editor holds no library +// GET /__stub/trending -> { mode, requests, judgements, captured, watches } +// +// Nothing here asks X, or any host, anything. +import { createHash } from "node:crypto"; +import { libraryState } from "./library-fixture.mjs"; + +let state = libraryState(); +let mode = "ok"; +let requests = []; +let jobs = 0; + +const NOW = "2026-11-18T09:00:00.000Z"; +const ROUTES = ["/api/ops/trending", "/api/ops/judge-trending", "/api/ops/watch-trending", "/api/ops/purge-trending"]; + +const effective = (p) => { + const own = state.judgements.posts[p.id]; + const thread = state.judgements.threads[p.thread]; + // The operator's entry outranks an agent's; between two of one hand, the post's own. + if (own && thread) return own.by === "agent" && thread.by === "operator" ? { ...thread, from: "thread" } : own; + return own ?? (thread ? { ...thread, from: "thread" } : undefined); +}; + +function watchSentence(w) { + if (!w) return undefined; + if (w.ended) return w.ended.sentence; + const every = `every ${w.intervalMinutes} min until 10:00 UTC${w.shots ? ", screenshotting every new post" : ""}`; + if (w.paused?.reason === "failing") return `Watched ${every} — PAUSED since 12:00 UTC, until someone switches it on again: ${w.paused.sentence}`; + if (w.paused) return `Watched ${every} — PAUSED since 12:00 UTC: ${w.paused.sentence}`; + return `Watched ${every}; ${w.ticks} ticks so far, next at the next scan.`; +} + +function captureFiles(p) { + if (!state.captured.includes(p.id)) return undefined; + const media = []; + if (p.kinds.includes("image")) media.push({ name: `${p.id}_1.jpg`, kind: "image", bytes: 68 }); + if (p.kinds.includes("video")) media.push({ name: `${p.id}_2.mp4`, kind: "video", bytes: 58 }); + return { shot: "shot.png", ...(p.context ? { threadShot: "shot-thread.png", context: p.context } : {}), media }; +} + +function row(p, detail) { + const judgement = effective(p); + const captured = state.captured.includes(p.id); + return { + id: p.id, + author: p.author, + authorName: p.authorName, + createdAt: p.createdAt, + url: p.url, + text: p.text, + media: { count: p.mediaCount, kinds: p.kinds }, + topic: p.topic, + reads: [{ read: "tr-01JA0000000000000000000000", trendId: "1900000000000000001", at: p.firstSeenAt }], + ...(p.gone ? { gone: p.gone } : {}), + ...(p.capture && (captured || p.capture.state !== "captured") ? { capture: { ...p.capture, shot: captured, files: captureFiles(p)?.media.length ?? 0 } } : {}), + thread: p.thread, + ...(judgement ? { judgement } : {}), + ...(detail + ? { + detail: { + post: { isReply: p.isReply === true, isRepost: false, ...(p.replyTo ? { replyTo: p.replyTo } : {}), links: [], ...(p.mediaCount ? { mediaCount: p.mediaCount } : {}) }, + firstSeenAt: p.firstSeenAt, + ...(state.judgements.posts[p.id] ? { ownJudgement: state.judgements.posts[p.id] } : {}), + ...(state.judgements.threads[p.thread] ? { threadJudgement: state.judgements.threads[p.thread] } : {}), + ...(captureFiles(p) ? { capture: captureFiles(p) } : {}), + }, + } + : {}), + }; +} + +function listing(sp) { + const topic = sp.get("topic"); + const detail = sp.get("detail") === "1"; + const words = (sp.get("q") ?? "").toLowerCase().split(/\s+/).filter(Boolean); + const author = sp.get("author")?.replace(/^@/, "").toLowerCase() ?? null; + const since = sp.get("since"); + const stateOf = (p) => effective(p)?.state ?? "unjudged"; + const inTopic = state.posts.filter((p) => !topic || p.topic === topic); + const rows = inTopic.filter( + (p) => + (!sp.get("state") || stateOf(p) === sp.get("state")) && + (sp.get("gone") !== "1" || p.gone) && + (sp.get("media") !== "1" || p.mediaCount > 0) && + (author === null || p.author.toLowerCase() === author) && + (!since || p.firstSeenAt > since) && + words.every((w) => `${p.text} ${p.author} ${p.authorName}`.toLowerCase().includes(w)), + ); + const offset = Number(sp.get("offset") ?? 0); + const limit = Number(sp.get("limit") ?? 100); + const authors = new Map(); + for (const p of inTopic) authors.set(p.author, (authors.get(p.author) ?? 0) + 1); + return { + ok: true, + slug: state.slug, + name: state.name, + topics: state.topics.map((t) => { + const mine = state.posts.filter((p) => p.topic === t.id); + const counts = { unjudged: 0, keep: 0, drop: 0, later: 0, gone: 0 }; + for (const p of mine) { + counts[stateOf(p)]++; + if (p.gone) counts.gone++; + } + return { id: t.id, title: t.title, posts: mine.length, ...(t.watch ? { watch: { ...t.watch, sentence: watchSentence(t.watch) } } : {}), ...(detail ? { counts } : {}), sources: [] }; + }), + posts: sp.get("ids") === "1" ? [] : rows.slice(offset, offset + limit).map((p) => row(p, detail)), + total: rows.length, + reads: [], + ...(detail ? { authors: [...authors].map(([a, n]) => ({ author: a, posts: n })).sort((a, b) => b.posts - a.posts || (a.author < b.author ? -1 : 1)) } : {}), + ...(sp.get("ids") === "1" ? { ids: rows.map((p) => p.id) } : {}), + }; +} + +function judge(body) { + const before = new Map(state.posts.map((p) => [p.id, effective(p)?.state])); + const written = []; + const skipped = []; + for (const item of body.set ?? []) { + const key = item.id ?? item.thread; + const bag = item.id !== undefined ? state.judgements.posts : state.judgements.threads; + if (!state.posts.some((p) => (item.id !== undefined ? p.id === key : p.thread === key))) { + skipped.push({ ...(item.id !== undefined ? { id: key } : { thread: key }), reason: "not a post of the library" }); + continue; + } + if (body.by === "agent" && bag[key]?.by === "operator") { + skipped.push({ ...(item.id !== undefined ? { id: key } : { thread: key }), reason: "the operator judged it" }); + continue; + } + if (item.state === "undecided") delete bag[key]; + else bag[key] = { state: item.state, ...(item.note ? { note: item.note } : {}), by: body.by, at: NOW }; + written.push({ ...(item.id !== undefined ? { id: key } : { thread: key }), state: item.state }); + } + const kept = state.posts.filter((p) => effective(p)?.state === "keep" && before.get(p.id) !== "keep").map((p) => p.id); + return { ok: true, slug: state.slug, written, skipped, kept, ...(kept.length && body.archive !== false ? { archive: { jobId: `stub-capture-${++jobs}`, ids: kept } } : {}) }; +} + +function watch(body) { + const topic = state.topics.find((t) => t.id === body.topic); + if (!topic) return { ok: false, error: `${state.slug} has no topic "${body.topic}"` }; + if (body.on && topic.watch?.paused?.reason === "failing" && body.by !== "operator") return { ok: false, error: "This watch is paused as failing: only the operator switches it on again." }; + if (!body.on) topic.watch = { ...(topic.watch ?? {}), on: false, ended: { at: NOW, reason: "off", sentence: "Switched off: not watched." } }; + else topic.watch = { on: true, intervalMinutes: body.intervalMinutes ?? 30, startedAt: NOW, until: "2026-11-20T10:00:00.000Z", shots: body.shots === true, by: body.by ?? "agent", ticks: 0, failures: 0, nextSource: 0, goneSources: [] }; + return { ok: true, slug: state.slug, topic: topic.id, watch: topic.watch, sentence: watchSentence(topic.watch) }; +} + +const digest = (ids) => createHash("sha256").update(JSON.stringify([state.slug, [...ids].sort()])).digest("hex").slice(0, 16); + +function purge(body) { + const ids = state.posts.filter((p) => (!body.topic || p.topic === body.topic) && effective(p)?.state === "drop" && state.captured.includes(p.id)).map((p) => p.id).sort(); + const files = ids.reduce((n, pid) => n + 2 + (captureFiles(state.posts.find((p) => p.id === pid))?.media.length ?? 0), 0); + const bytes = files * 68; + const confirm = digest(ids); + const what = `the capture${ids.length === 1 ? "" : "s"} of ${ids.length} dropped post${ids.length === 1 ? "" : "s"}: ${files} file${files === 1 ? "" : "s"}, ${bytes} B`; + if (body.dryRun === true) { + return { ok: true, slug: state.slug, dryRun: true, posts: ids.length, ids, files, bytes, blobsFreed: 0, blobsKept: 0, skipped: [], confirm, sentence: ids.length ? `Would remove ${what}. The judgements stay.` : "No dropped post has a capture: nothing to remove." }; + } + if (body.by !== "operator") return { ok: false, error: "Removing dropped posts' captures is the operator's press" }; + if (body.confirm !== confirm) return { ok: false, error: `The dropped posts with a capture have changed since the dry run (${ids.length} now): nothing was removed. Run the dry run again and confirm what it shows.` }; + state.captured = state.captured.filter((pid) => !ids.includes(pid)); + return { ok: true, slug: state.slug, dryRun: false, posts: ids.length, ids, files, bytes, blobsFreed: 0, blobsKept: 0, skipped: [], confirm, sentence: `Removed ${what}. The judgements stay.` }; +} + +/** The spec's door. True when answered. */ +export function trendingControl(req, res, url, { json, readBody }) { + if (url.pathname !== "/__stub/trending") return false; + if (req.method === "GET") { + req.resume(); + json(res, 200, { mode, requests, judgements: state.judgements, captured: state.captured, watches: Object.fromEntries(state.topics.map((t) => [t.id, t.watch ?? null])) }); + return true; + } + readBody(req, (body) => { + if (body?.reset === true) { + state = libraryState(); + requests = []; + jobs = 0; + mode = "ok"; + } + if (body?.mode !== undefined) { + if (!["ok", "unreachable", "none"].includes(body.mode)) return json(res, 400, { error: `mode "${body.mode}" is not one of ok, unreachable, none` }); + mode = body.mode; + } + json(res, 200, { ok: true, mode }); + }); + return true; +} + +/** The editor's trending routes (behind the bearer). True when answered. */ +export function trendingRoute(req, res, url, { json, readBody, authorization }) { + if (!ROUTES.includes(url.pathname)) return false; + if (mode === "unreachable") { + req.socket.destroy(); + return true; + } + if (req.method === "GET" && url.pathname === "/api/ops/trending") { + req.resume(); + if (!url.searchParams.has("slug")) { + const all = listing(new URLSearchParams({ detail: "1" })); + json(res, 200, { ok: true, libraries: mode === "none" ? [] : [{ slug: state.slug, name: state.name, topics: all.topics.length, posts: all.total, unjudged: all.topics.reduce((n, t) => n + t.counts.unjudged, 0) }] }); + return true; + } + if (mode === "none" || url.searchParams.get("slug") !== state.slug) { + json(res, 404, { ok: false, error: `No such channel: ${url.searchParams.get("slug")}` }); + return true; + } + const topic = url.searchParams.get("topic"); + if (topic && !state.topics.some((t) => t.id === topic)) { + json(res, 400, { ok: false, error: `${state.slug} has no topic "${topic}" (its topics: ${state.topics.map((t) => t.id).join(", ")})` }); + return true; + } + json(res, 200, listing(url.searchParams)); + return true; + } + if (req.method !== "POST") return false; + readBody(req, (body) => { + const action = url.pathname.slice("/api/ops/".length); + requests.push({ action, body, authorization }); + if (!body || body.slug !== state.slug) return json(res, 400, { ok: false, error: `${body?.slug} is not an X trending library` }); + const answer = action === "judge-trending" ? judge(body) : action === "watch-trending" ? watch(body) : purge(body); + json(res, answer.ok ? 200 : 400, answer); + }); + return true; +} diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -17,6 +17,7 @@ import { intakeControl, intakeRoute } from "./editor-stub-intake.mjs"; import { servicesControl, servicesRoute } from "./editor-stub-services.mjs"; +import { trendingControl, trendingRoute } from "./editor-stub-trending.mjs"; import http from "node:http"; import { spawn, spawnSync } from "node:child_process"; import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync, statSync } from "node:fs"; @@ -1287,6 +1288,8 @@ const server = http.createServer((req, res) => { if (intakeControl(req, res, url, { json, readBody })) return; // The cookie alerts a spec puts up (editor-stub-services.mjs, needs-you.spec.ts). if (servicesControl(req, res, url, { json, readBody })) return; + // The Posts library's invented library (editor-stub-trending.mjs, library.spec.ts). + if (trendingControl(req, res, url, { json, readBody })) return; if (req.method === "POST" && url.pathname === "/__stub/ops-jobs") { return readBody(req, (body) => { const mode = body?.mode ?? "ok"; @@ -1306,6 +1309,8 @@ const server = http.createServer((req, res) => { // The editor's cookie alerts and X's jar (editor-stub-services.mjs): the Inbox's X jar row reads them. if (servicesRoute(req, res, url, { json })) return; + // Lane posts-library: an X trending library's listing and its three presses (editor-stub-trending.mjs). + if (trendingRoute(req, res, url, { json, readBody, authorization: auth })) return; // UI notes items 13 and 16: a channel's counts, the focus, capture-posts (editor-stub-intake.mjs). if (intakeRoute(req, res, url, { channels: CHANNELS, json, readBody, push: (r) => (requests.push({ ...r, authorization: auth }), record()) })) return; // Release 38 lane C: a research case's verify, leads and evidence stages (editor-stub-case-stages.mjs). diff --git a/umtool/e2e/fixtures/library-fixture.mjs b/umtool/e2e/fixtures/library-fixture.mjs @@ -0,0 +1,128 @@ +// What library.spec.ts judges (lane posts-library; the page /tools/library): +// an invented X trending library — two topics with watches, a third with none, +// a thread, a post gone from the page, dropped posts with captures — as the +// stub editor answers it (editor-stub-trending.mjs), and the few media files +// umtool's own media route serves from the fixture's corpus. +// +// The channel directory is made by the spec and removed after it +// (makeLibraryFixture / removeLibraryFixture), not by make-fixture.mjs: no +// other spec sees one more channel. Invented ids, handles and words; no real +// trending id, and nothing here is ever asked of X. +import { linkSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +export const LIB = "trending-lib"; +export const LIB_NAME = "Trending fixture"; +export const NOT_A_LIB = "testchan"; + +const id = (n) => `19000000000000${String(n).padStart(5, "0")}`; +export const P = { + opening: id(7001), + reply: id(7002), + gone: id(7003), + dropped: id(7004), + later: id(7005), + fresh: id(7006), + cup: id(7101), + cupDropped: id(7102), +}; + +const READ_1 = "2026-11-17T10:00:00.000Z"; +const READ_2 = "2026-11-17T11:00:00.000Z"; +const READ_3 = "2026-11-17T12:00:00.000Z"; + +// A 1×1 PNG and a few bytes that stand for a video (the route serves bytes; nothing decodes them). +const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==", "base64"); +export const VIDEO_BYTES = Buffer.from("FAKE-TEST-VALUEghijklmnopqrstuvwxyz-library-fixture-video"); + +/** The captured files of each post: name → bytes. */ +export const CAPTURES = { + [P.opening]: { "shot.png": PNG, [`${P.opening}_1.jpg`]: PNG, [`${P.opening}_2.mp4`]: VIDEO_BYTES }, + [P.reply]: { "shot.png": PNG, "shot-thread.png": PNG }, + [P.dropped]: { "shot.png": PNG, [`${P.dropped}_1.jpg`]: PNG }, + [P.cupDropped]: { "shot.png": PNG }, +}; + +/** The library's state as the stub editor starts with it (a fresh copy per call). */ +export function libraryState() { + const post = (pid, author, authorName, text, topic, firstSeenAt, extra = {}) => ({ id: pid, author, authorName, createdAt: "2026-11-16T12:00:00.000Z", text, url: `https://x.com/${author}/status/${pid}`, topic, thread: pid, firstSeenAt, mediaCount: 0, kinds: [], ...extra }); + return { + slug: LIB, + name: LIB_NAME, + topics: [ + { + id: "kettle-festival", + title: "Kettle festival", + watch: { on: true, intervalMinutes: 30, startedAt: READ_1, until: "2026-11-19T10:00:00.000Z", shots: false, by: "operator", ticks: 2, failures: 0, nextSource: 0, goneSources: [], paused: { reason: "jar", since: READ_3, sentence: "X's cookie jar is 75 minutes old, past the watch's 60." } }, + }, + { + id: "cup-shortage", + title: "Cup shortage", + watch: { on: true, intervalMinutes: 60, startedAt: READ_1, until: "2026-11-19T10:00:00.000Z", shots: true, by: "agent", ticks: 5, failures: 3, nextSource: 0, goneSources: [], paused: { reason: "failing", since: READ_3, sentence: "The last read ended rate-limited." } }, + }, + { id: "lids", title: "Lids" }, + ], + posts: [ + post(P.opening, "teapot_news", "Teapot News", "The kettle festival opens today.", "kettle-festival", READ_1, { mediaCount: 2, kinds: ["image", "video"], capture: { at: "2026-11-17T10:05:00.000Z", state: "captured", mediaState: "ok" } }), + post(P.reply, "saucer_fan", "Saucer Fan", "A reply about spouts.", "kettle-festival", READ_1, { + thread: P.opening, + isReply: true, + replyTo: { platform: "twitter", id: P.opening, author: "teapot_news" }, + capture: { at: "2026-11-17T10:06:00.000Z", state: "captured", mediaState: "none" }, + context: { parent: { handle: "teapot_news", text: "The kettle festival opens today." } }, + }), + post(P.gone, "lid_watch", "Lid Watch", "A lid fell off a kettle.", "kettle-festival", READ_1, { gone: { at: READ_2, read: "tr-01JB0000000000000000000000", trendId: "1900000000000000001" } }), + post(P.dropped, "spout_co", "Spout Co", "Spouts are back in stock.", "kettle-festival", READ_1, { mediaCount: 1, kinds: ["image"], capture: { at: "2026-11-17T10:07:00.000Z", state: "captured", mediaState: "ok" } }), + post(P.later, "teapot_news", "Teapot News", "More on the kettle parade later.", "kettle-festival", READ_2), + post(P.fresh, "kettle_fan", "Kettle Fan", "Just arrived at the festival.", "kettle-festival", READ_3, { capture: { at: "2026-11-17T12:05:00.000Z", state: "deleted", mediaState: "skipped" } }), + post(P.cup, "cup_other", "Cup Other", "Cups are short this week.", "cup-shortage", READ_1), + post(P.cupDropped, "cup_other", "Cup Other", "Buy my cups.", "cup-shortage", READ_1, { capture: { at: "2026-11-17T10:08:00.000Z", state: "captured", mediaState: "none" } }), + ], + judgements: { + posts: { + [P.dropped]: { state: "drop", by: "operator", at: "2026-11-17T12:30:00.000Z" }, + [P.later]: { state: "later", note: "check the source", by: "agent", at: "2026-11-17T12:31:00.000Z" }, + [P.cupDropped]: { state: "drop", by: "agent", at: "2026-11-17T12:32:00.000Z" }, + }, + threads: {}, + }, + // Posts whose capture is still on disk (a purge takes the dropped ones). + captured: Object.keys(CAPTURES), + }; +} + +const libDir = (channels) => path.join(channels, LIB); + +/** The library's channel in the fixture corpus: its marker and its captured files (a video as a hardlink to its blob). */ +export function makeLibraryFixture({ channels }) { + removeLibraryFixture({ channels }); + const dir = libDir(channels); + mkdirSync(path.join(dir, "trending", "media-store", "ab"), { recursive: true }); + mkdirSync(path.join(dir, "trending", "reads", "tr-01JA0000000000000000000000"), { recursive: true }); + writeFileSync(path.join(dir, "config.json"), JSON.stringify({ name: LIB_NAME, handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} })); + writeFileSync(path.join(dir, "trending", "reads", "tr-01JA0000000000000000000000", "page.png"), PNG); + writeFileSync(path.join(dir, "trending", "judgements.json"), JSON.stringify({ version: 1, posts: {}, threads: {} })); + for (const [pid, files] of Object.entries(CAPTURES)) { + const cap = path.join(dir, "trending", "posts-media", pid); + mkdirSync(cap, { recursive: true }); + writeFileSync(path.join(cap, "capture.json"), JSON.stringify({ version: 1, id: pid, state: "captured" })); + for (const [name, bytes] of Object.entries(files)) { + if (name.endsWith(".mp4")) { + const blob = path.join(dir, "trending", "media-store", "ab", `${pid}.mp4`); + writeFileSync(blob, bytes); + linkSync(blob, path.join(cap, name)); + } else writeFileSync(path.join(cap, name), bytes); + } + } + // A name planted in a capture whose real path is the raw read's page: never served. + symlinkSync(path.join(dir, "trending", "reads", "tr-01JA0000000000000000000000", "page.png"), path.join(dir, "trending", "posts-media", P.opening, "planted.png")); + // A channel that is no library, with a file of the same shape. + const other = path.join(channels, NOT_A_LIB, "trending", "posts-media", P.opening); + mkdirSync(other, { recursive: true }); + writeFileSync(path.join(other, "shot.png"), PNG); +} + +export function removeLibraryFixture({ channels }) { + rmSync(libDir(channels), { recursive: true, force: true }); + rmSync(path.join(channels, NOT_A_LIB, "trending"), { recursive: true, force: true }); +} diff --git a/umtool/e2e/library.spec.ts b/umtool/e2e/library.spec.ts @@ -0,0 +1,551 @@ +import { test, expect, type APIRequestContext, type Page } from "@playwright/test"; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; +import { LIB, makeLibraryFixture, NOT_A_LIB, P, removeLibraryFixture, VIDEO_BYTES } from "./fixtures/library-fixture.mjs"; +import * as urls from "./urls"; +import { warm, WARM_TIMEOUT } from "./warm"; + +// --------------------------------------------------------------------------- +// THE POSTS LIBRARY (/tools/library; plans/x-trending.md slice 3, lane +// posts-library): a private X trending library browsed by topic and judged. +// +// The library is the STUB EDITOR's (e2e/fixtures/editor-stub-trending.mjs: an +// invented library in memory, every press recorded with the `by` it carried); +// its captured media are files in the fixture's corpus, served by umtool's own +// route. Nothing here reaches X, the live editor, or the operator's reports. +// WRITES the fixture's REPORTS_ROOT/.umtool/posts-library.json (Mark seen) and +// channels/trending-lib/ (made before, removed after). +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const CHANNELS = path.join(FIXTURE, "channels"); +const SEEN = path.join(FIXTURE, ".umtool", "posts-library.json"); +const STUB = `http://127.0.0.1:${portFor("EDITOR_STUB_PORT")}`; +const KETTLES = "kettle-festival"; +const CUPS = "cup-shortage"; + +type Recorded = { action: string; body: Record<string, any>; authorization: string }; +type StubState = { requests: Recorded[]; judgements: { posts: Record<string, any>; threads: Record<string, any> }; captured: string[]; watches: Record<string, any> }; + +const stub = async (request: APIRequestContext): Promise<StubState> => (await request.get(`${STUB}/__stub/trending`)).json(); +const reset = async (request: APIRequestContext, mode: "ok" | "unreachable" | "none" = "ok") => { + expect((await request.post(`${STUB}/__stub/trending`, { data: { reset: true, mode } })).status()).toBe(200); + rmSync(SEEN, { force: true }); +}; +const last = async (request: APIRequestContext) => (await stub(request)).requests.at(-1)!; +const lib = (view: Record<string, unknown> = {}) => urls.postsLibraryHref({ lib: LIB, ...view }); +const post = (page: Page, id: string) => page.locator(`[data-library-post="${id}"]`); +const rail = (page: Page) => page.locator('[data-library-topics="rail"]'); +const status = (page: Page) => page.locator("[data-library-status]"); +const idle = (page: Page) => expect(page.locator("[data-library]")).toHaveAttribute("data-library-busy", "false"); +const shown = (page: Page) => page.locator("[data-library-post]").evaluateAll((els) => els.map((e) => e.getAttribute("data-library-post"))); + +async function open(page: Page, view: Record<string, unknown> = {}) { + await page.goto(lib(view)); + await expect(page.locator('[data-stream-filled="library"]')).toBeVisible({ timeout: 30_000 }); + // The presses are live once the page is (a button is disabled until then). + await expect(page.locator("[data-library-scope]")).toBeEnabled(); +} + +test.describe.configure({ mode: "serial" }); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + makeLibraryFixture({ channels: CHANNELS }); + await warm(playwright, [urls.postsLibraryHref(), urls.toolsHref()]); +}); +test.afterAll(async ({ request }) => { + await reset(request); + removeLibraryFixture({ channels: CHANNELS }); +}); +test.beforeEach(async ({ request, page }) => { + await reset(request); + await page.setViewportSize({ width: 1366, height: 900 }); +}); + +test("the head is sent before the library, behind a placeholder of its shape", async ({ baseURL }) => { + const res = await fetch(baseURL + lib(), { headers: { "Accept-Encoding": "identity", Cookie: "e2e-stream-delay=1500" } }); + expect(res.status).toBe(200); + const html = await res.text(); + const filledAt = html.indexOf("data-stream-filled"); + expect(filledAt, "the library never streamed in").toBeGreaterThan(0); + const shell = html.slice(0, filledAt); + expect(shell).toContain("data-app-rail"); + expect(shell).toContain("Posts library"); + expect(shell).toContain('data-stream-skeleton="library"'); + expect(shell).not.toContain("data-library-post"); + expect(html.slice(filledAt)).toContain(`data-library-post="${P.opening}"`); +}); + +test("found from Tools; topics on the left with their counts and what each watch is doing", async ({ page }) => { + await page.goto(urls.toolsHref()); + await expect(page.locator("[data-tool-entry=library] a")).toHaveAttribute("href", urls.postsLibraryHref()); + await open(page); + + const kettles = rail(page).locator(`[data-library-topic="${KETTLES}"]`); + await expect(kettles).toContainText("Kettle festival"); + await expect(kettles.locator("[data-library-topic-posts]")).toHaveText("6"); + await expect(kettles.locator("[data-library-topic-unjudged]")).toHaveText("4"); + // A paused watch says why; a failing one is told apart. + await expect(kettles).toHaveAttribute("data-library-watch", "paused"); + await expect(kettles.locator("[data-library-topic-watch]")).toContainText("Watch paused · Watched every 30 min"); + await expect(kettles.locator("[data-library-topic-watch]")).toContainText("X's cookie jar is 75 minutes old"); + const cups = rail(page).locator(`[data-library-topic="${CUPS}"]`); + await expect(cups).toHaveAttribute("data-library-watch", "failing"); + await expect(cups.locator("[data-library-topic-watch]")).toContainText("Watch failing"); + await expect(rail(page).locator('[data-library-topic="lids"]')).toHaveAttribute("data-library-watch", "none"); + // Every topic's posts, 8 in all. + await expect(page.locator("[data-library-count]")).toHaveAttribute("data-library-count", "8"); + + await kettles.click(); + await expect(page).toHaveURL(new RegExp(`topic=${KETTLES}`)); + await expect(page.locator("[data-library-count]")).toHaveAttribute("data-library-count", "6"); + await expect(page.locator(`[data-library-panel="${KETTLES}"]`)).toContainText("6 posts · 4 unjudged · 0 kept · 1 dropped · 1 later"); + // It fits a desk without scrolling sideways. + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true); + // Nothing here offers a post to a project, a report or a site. + await expect(page.locator("[data-posts-library]").getByRole("button", { name: /add to|publish|cut|project|report/i })).toHaveCount(0); + await expect(page.locator("[data-posts-library]").getByRole("link", { name: /add to|publish/i })).toHaveCount(0); +}); + +test("a post is drawn with its captured media, its thread context, and the words for gone and for a capture's state", async ({ page }) => { + await open(page, { topic: KETTLES }); + const media = (id: string, name: string) => `/api/library/media/${LIB}/${id}/${name}`; + + // The opening post: the archive viewer's body, with the screenshot, a picture and a video from umtool's media route. + const opening = post(page, P.opening); + await expect(opening.locator(`article[data-post-id="${P.opening}"]`)).toContainText("The kettle festival opens today."); + await expect(opening.locator("[data-post-capture-shot]")).toHaveAttribute("src", media(P.opening, "shot.png")); + await expect(opening.locator('[data-post-capture-media="image"] img')).toHaveAttribute("src", media(P.opening, `${P.opening}_1.jpg`)); + await expect(opening.locator('[data-post-capture-media="video"] video')).toHaveAttribute("src", media(P.opening, `${P.opening}_2.mp4`)); + // The picture really loads. + await expect.poll(() => opening.locator("[data-post-capture-shot]").evaluate((img: HTMLImageElement) => img.complete && img.naturalWidth > 0)).toBe(true); + await expect(opening.locator("[data-library-capture]")).toHaveText("capture: captured at 17 Nov 2026, 10:05 UTC"); + + // The reply: what it answers, as its capture read it, and the thread shot. + const reply = post(page, P.reply); + await expect(reply.locator('[data-library-context="parent"]')).toHaveText("In answer to @teapot_news: The kettle festival opens today."); + await expect(reply.locator("[data-library-thread]")).toHaveText("in a thread"); + await expect(reply.locator("[data-library-thread-shot] img")).toHaveAttribute("src", media(P.reply, "shot-thread.png")); + + // Gone from the page, in those words; a capture's own state verbatim. + await expect(post(page, P.gone).locator("[data-library-gone]")).toHaveText("Gone from the page at 17 Nov 2026, 11:00 UTC"); + await expect(post(page, P.fresh).locator("[data-library-capture]")).toHaveText("capture: deleted at 17 Nov 2026, 12:05 UTC"); + // No post is called deleted: the only place the word may stand is a capture's recorded state. + const text = await page.locator("[data-library-posts]").innerText(); + expect(text.match(/deleted/gi) ?? []).toHaveLength(1); + expect(await page.locator("[data-library-gone]").allInnerTexts()).toEqual(["Gone from the page at 17 Nov 2026, 11:00 UTC"]); + + // Judgements already there: whose, and the note. + await expect(post(page, P.dropped)).toHaveAttribute("data-library-judgement", "drop"); + await expect(post(page, P.dropped).locator("[data-library-by]")).toContainText("by the operator"); + await expect(post(page, P.later).locator("[data-library-by]")).toContainText("by the agent"); + await expect(post(page, P.later).locator("[data-library-note]")).toHaveText("Note: check the source"); +}); + +test("keep, drop, later and clear are the editor's judge-trending, as the operator; a thread, a note, and undo of the last press", async ({ page, request }) => { + await open(page, { topic: KETTLES }); + + await post(page, P.opening).locator('[data-library-press="keep"]').click(); + await expect(post(page, P.opening)).toHaveAttribute("data-library-judgement", "keep"); + await expect(status(page)).toHaveText("1 judgement kept. 1 post queued for archiving (the editor's capture job stub-capture-1)."); + let r = await last(request); + expect(r.action).toBe("judge-trending"); + expect(r.body).toEqual({ slug: LIB, by: "operator", set: [{ id: P.opening, state: "keep" }] }); + expect(r.authorization).toBe("Bearer umtool-e2e-token"); + await expect(post(page, P.opening).locator("[data-library-by]")).toContainText("by the operator"); + await idle(page); + + // Undo: its own entry removed, nothing archived, and the bar says what undo does not do. + await expect(page.locator("[data-library-undo-says]")).toHaveText("Undo puts the judgements back. It does not cancel a capture already queued."); + await page.locator("[data-library-undo]").click(); + await expect(post(page, P.opening)).toHaveAttribute("data-library-judgement", "unjudged"); + r = await last(request); + expect(r.body).toEqual({ slug: LIB, by: "operator", set: [{ id: P.opening, state: "undecided" }], archive: false }); + await expect(status(page)).toContainText("Undone: 1 judgement put back."); + await expect(page.locator("[data-library-undo]")).toBeDisabled(); + await idle(page); + + // The whole thread: the reply's Drop judges the thread's root, and both posts read dropped. + await page.locator("[data-library-scope]").click(); + await expect(page.locator("[data-library-scope]")).toHaveAttribute("data-library-scope", "thread"); + await post(page, P.reply).locator('[data-library-press="drop"]').click(); + await expect(post(page, P.reply)).toHaveAttribute("data-library-judgement", "drop"); + await expect(post(page, P.opening)).toHaveAttribute("data-library-judgement", "drop"); + await expect(post(page, P.reply).locator("[data-library-by]")).toContainText("from its thread"); + r = await last(request); + expect(r.body).toEqual({ slug: LIB, by: "operator", set: [{ thread: P.opening, state: "drop" }] }); + await idle(page); + // Clear the thread's. + await post(page, P.reply).locator('[data-library-press="clear"]').click(); + await expect(post(page, P.opening)).toHaveAttribute("data-library-judgement", "unjudged"); + expect((await last(request)).body.set).toEqual([{ thread: P.opening, state: "undecided" }]); + await idle(page); + await page.locator("[data-library-scope]").click(); + + // A note goes with a judgement. + await post(page, P.gone).locator('[data-library-press="note"]').click(); + await post(page, P.gone).locator("[data-library-note-editor] textarea").fill("left the page within the hour"); + await post(page, P.gone).locator('[data-library-note-save="later"]').click(); + await expect(post(page, P.gone).locator("[data-library-note]")).toHaveText("Note: left the page within the hour"); + expect((await last(request)).body).toEqual({ slug: LIB, by: "operator", set: [{ id: P.gone, state: "later", note: "left the page within the hour" }] }); + await idle(page); + // Undo puts back what was there: nothing. + await page.locator("[data-library-undo]").click(); + await expect(post(page, P.gone)).toHaveAttribute("data-library-judgement", "unjudged"); + // Every press of this test was the operator's. + expect((await stub(request)).requests.every((x) => x.body.by === "operator")).toBe(true); +}); + +test("the keys: j and k move, a d l c judge, x selects, u undoes, ? lists them, Shift asks before a bulk press", async ({ page, request }) => { + await open(page, { topic: KETTLES }); + const focused = () => page.locator('[data-library-focus="true"]').getAttribute("data-library-post"); + const order = await shown(page); + expect(await focused()).toBe(order[0]); + await page.keyboard.press("j"); + expect(await focused()).toBe(order[1]); + await page.keyboard.press("j"); + await page.keyboard.press("k"); + expect(await focused()).toBe(order[1]); + + await page.keyboard.press("a"); + await expect(post(page, order[1]!)).toHaveAttribute("data-library-judgement", "keep"); + expect((await last(request)).body.set).toEqual([{ id: order[1], state: "keep" }]); + await idle(page); + await page.keyboard.press("d"); + await expect(post(page, order[1]!)).toHaveAttribute("data-library-judgement", "drop"); + await idle(page); + await page.keyboard.press("l"); + await expect(post(page, order[1]!)).toHaveAttribute("data-library-judgement", "later"); + await idle(page); + // u: back to what it was before the last press (drop). + await page.keyboard.press("u"); + await expect(post(page, order[1]!)).toHaveAttribute("data-library-judgement", "drop"); + expect((await last(request)).body).toMatchObject({ archive: false, by: "operator", set: [{ id: order[1], state: "drop" }] }); + await idle(page); + await page.keyboard.press("c"); + await expect(post(page, order[1]!)).toHaveAttribute("data-library-judgement", "unjudged"); + await idle(page); + + // x selects; with a selection a press judges the selected posts. + await page.keyboard.press("x"); + await page.keyboard.press("j"); + await page.keyboard.press("x"); + await expect(page.locator("[data-library-selected]")).toHaveAttribute("data-library-selected", "2"); + await page.keyboard.press("l"); + await expect(post(page, order[2]!)).toHaveAttribute("data-library-judgement", "later"); + expect((await last(request)).body.set).toEqual([{ id: order[1], state: "later" }, { id: order[2], state: "later" }]); + await idle(page); + + // t: the scope; ?: the list; typing in the search box presses nothing. + await page.keyboard.press("t"); + await expect(page.locator("[data-library-scope]")).toHaveAttribute("data-library-scope", "thread"); + await page.keyboard.press("t"); + await page.keyboard.press("?"); + await expect(page.locator("[data-library-help]")).toContainText("keep everything in the filter"); + await expect(page.locator("[data-library-help] kbd").first()).toHaveText("j"); + const before = (await stub(request)).requests.length; + await page.keyboard.press("/"); + await expect(page.locator("[data-library-search]")).toBeFocused(); + await page.keyboard.type("ad"); + expect((await stub(request)).requests.length).toBe(before); + await page.locator("[data-library-search]").fill(""); + await page.locator("[data-library-search]").blur(); + + // Shift+D asks first, with the count; Escape leaves it. + await page.keyboard.press("Shift+D"); + await expect(page.locator('[data-library-confirm="drop"] [data-library-confirm-count]')).toHaveText("6"); + await page.keyboard.press("Escape"); + await expect(page.locator("[data-library-confirm]")).toHaveCount(0); + expect((await stub(request)).requests.length).toBe(before); +}); + +test("the filters: unjudged, kept, dropped, later, gone, has media, by author, search, and new since Mark seen", async ({ page, request }) => { + await open(page, { topic: KETTLES }); + const only = async (expected: string[]) => { + await expect(page.locator("[data-library-count]")).toHaveAttribute("data-library-count", String(expected.length)); + expect((await shown(page)).sort()).toEqual([...expected].sort()); + }; + await page.locator('[data-library-state="unjudged"]').click(); + await only([P.opening, P.reply, P.gone, P.fresh]); + await page.locator('[data-library-state="drop"]').click(); + await only([P.dropped]); + await page.locator('[data-library-state="later"]').click(); + await only([P.later]); + await page.locator('[data-library-state="keep"]').click(); + await only([]); + await expect(page.locator("[data-library-count]")).toHaveText("No post kept in “Kettle festival”."); + await page.locator('[data-library-state="all"]').click(); + await only([P.opening, P.reply, P.gone, P.dropped, P.later, P.fresh]); + + await page.locator('[data-library-toggle="gone"]').click(); + await only([P.gone]); + await page.locator('[data-library-toggle="gone"]').click(); + await page.locator('[data-library-toggle="media"]').click(); + await only([P.opening, P.dropped]); + await page.locator('[data-library-toggle="media"]').click(); + await only([P.opening, P.reply, P.gone, P.dropped, P.later, P.fresh]); + + await page.locator("[data-library-author]").selectOption("teapot_news"); + await only([P.opening, P.later]); + await page.locator("[data-library-author]").selectOption(""); + await page.locator("[data-library-search]").fill("LID kettle"); + await page.locator("[data-library-search]").press("Enter"); + await only([P.gone]); + await expect(page).toHaveURL(/q=LID\+kettle/); + await expect(page).toHaveURL(new RegExp(`topic=${KETTLES}`)); + + // New: never marked, every post is new. Marked seen before the last read: the one post that read first showed. + await open(page, { topic: KETTLES }); + await expect(rail(page).locator(`[data-library-topic="${KETTLES}"] [data-library-topic-new]`)).toHaveText("6"); + mkdirSync(path.dirname(SEEN), { recursive: true }); + writeFileSync(SEEN, JSON.stringify({ format: "umtool-posts-library", version: 1, libraries: { [LIB]: { topics: { [KETTLES]: { seenAt: "2026-11-17T11:30:00.000Z" } } } } })); + await open(page, { topic: KETTLES }); + await expect(rail(page).locator(`[data-library-topic="${KETTLES}"] [data-library-topic-new]`)).toHaveText("1"); + await page.locator('[data-library-toggle="new"]').click(); + await only([P.fresh]); + await expect(page.locator("[data-library-seen-at]")).toHaveText("marked seen 17 Nov 2026, 11:30 UTC"); + + // Mark seen is the only thing that moves it: after the press nothing is new. + await page.locator("[data-library-seen]").click(); + await expect(status(page)).toContainText("“Kettle festival” marked seen"); + await only([]); + const doc = JSON.parse(readFileSync(SEEN, "utf8")); + expect(doc.libraries[LIB].topics[KETTLES].previous).toBe("2026-11-17T11:30:00.000Z"); + expect(Date.parse(doc.libraries[LIB].topics[KETTLES].seenAt)).toBeGreaterThan(Date.parse("2026-11-18T00:00:00.000Z")); + // Marking seen asked the editor for nothing but reads. + expect((await stub(request)).requests).toEqual([]); +}); + +test("bulk over the filter: the confirm states the count and that keeps archive through the paced capture job; one ask, one job; undo puts all back", async ({ page, request }) => { + await open(page, { topic: KETTLES, state: "unjudged" }); + await page.locator('[data-library-bulk="keep"]').click(); + const confirm = page.locator('[data-library-confirm="keep"]'); + await expect(confirm.locator("[data-library-confirm-count]")).toHaveText("4"); + await expect(confirm).toContainText("Keep all 4 posts (unjudged) in “Kettle festival”?"); + await expect(confirm).toContainText("Each keep archives the post's screenshot and media through the editor's paced capture job: one job per 500 posts, never one per post."); + expect((await stub(request)).requests).toEqual([]); + await confirm.locator("[data-library-confirm-yes]").click(); + await expect(status(page)).toHaveText("4 judgements kept. 4 posts queued for archiving (the editor's capture job stub-capture-1)."); + const all = (await stub(request)).requests; + // ONE judge ask for the four posts: one capture job, not four. + expect(all).toHaveLength(1); + expect(all[0].body.by).toBe("operator"); + expect(all[0].body.set.map((s: { id: string }) => s.id).sort()).toEqual([P.opening, P.reply, P.gone, P.fresh].sort()); + expect(all[0].body.set.every((s: { state: string }) => s.state === "keep")).toBe(true); + // The unjudged filter is now empty. + await expect(page.locator("[data-library-count]")).toHaveAttribute("data-library-count", "0"); + await idle(page); + + await page.locator("[data-library-undo]").click(); + await expect(page.locator("[data-library-count]")).toHaveAttribute("data-library-count", "4"); + const undo = await last(request); + expect(undo.body.archive).toBe(false); + expect(undo.body.set).toHaveLength(4); + expect(undo.body.set.every((s: { state: string }) => s.state === "undecided")).toBe(true); + expect((await stub(request)).judgements.posts[P.opening]).toBeUndefined(); +}); + +test("the watch: why it is paused, that only the operator restarts a failing one, and the switch with its terms", async ({ page, request }) => { + await open(page, { topic: KETTLES }); + const panel = page.locator("[data-library-watch-panel]"); + await expect(panel).toHaveAttribute("data-library-watch-panel", "paused"); + await expect(panel.locator("[data-library-watch-why]")).toContainText("Paused: X's cookie jar is 75 minutes old, past the watch's 60."); + await expect(panel.locator("[data-library-watch-why]")).toContainText("Refresh cookies in the editor, on /cookies"); + + await open(page, { topic: CUPS }); + await expect(panel).toHaveAttribute("data-library-watch-panel", "failing"); + await expect(panel.locator("[data-library-watch-why]")).toContainText("Only the operator restarts a failing watch: press Watch again."); + await panel.locator("[data-library-watch-interval]").fill("45"); + await panel.locator("[data-library-watch-hours]").fill("24"); + await panel.locator("[data-library-watch-on]").click(); + await expect(panel).toHaveAttribute("data-library-watch-panel", "on"); + let r = await last(request); + expect(r.action).toBe("watch-trending"); + expect(r.body).toEqual({ slug: LIB, topic: CUPS, on: true, intervalMinutes: 45, hours: 24, shots: true, by: "operator" }); + await expect(panel.locator("[data-library-watch-sentence]")).toContainText("Watched every 45 min"); + await expect(rail(page).locator(`[data-library-topic="${CUPS}"]`)).toHaveAttribute("data-library-watch", "on"); + await idle(page); + + await panel.locator("[data-library-watch-off]").click(); + await expect(panel).toHaveAttribute("data-library-watch-panel", "ended"); + r = await last(request); + expect(r.body).toEqual({ slug: LIB, topic: CUPS, on: false, by: "operator" }); + + // A topic never watched: Watch, with "screenshot everything new". + await open(page, { topic: "lids" }); + await expect(panel).toHaveAttribute("data-library-watch-panel", "none"); + await expect(panel.locator("[data-library-watch-sentence]")).toHaveText("Not watched."); + await panel.locator("[data-library-watch-shots]").check(); + await panel.locator("[data-library-watch-on]").click(); + await expect(panel).toHaveAttribute("data-library-watch-panel", "on"); + expect((await last(request)).body).toEqual({ slug: LIB, topic: "lids", on: true, shots: true, by: "operator" }); +}); + +test("purge of dropped posts' captures: two presses, the first saying what would go; the judgements stay", async ({ page, request }) => { + await open(page, { topic: KETTLES }); + await page.locator("[data-library-purge]").click(); + const plan = page.locator("[data-library-purge-plan]"); + await expect(plan.locator("[data-library-purge-sentence]")).toHaveText("Would remove the capture of 1 dropped post: 3 files, 204 B. The judgements stay."); + let r = await last(request); + expect(r.action).toBe("purge-trending"); + expect(r.body).toEqual({ slug: LIB, topic: KETTLES, dryRun: true, by: "operator" }); + // Nothing removed yet. + expect((await stub(request)).captured).toContain(P.dropped); + await idle(page); + + await plan.locator("[data-library-purge-yes]").click(); + await expect(status(page)).toHaveText("Removed the capture of 1 dropped post: 3 files, 204 B. The judgements stay."); + r = await last(request); + expect(r.body.by).toBe("operator"); + expect(r.body.topic).toBe(KETTLES); + expect(r.body.confirm).toMatch(/^[0-9a-f]{16}$/); + expect(r.body.dryRun).toBeUndefined(); + const after = await stub(request); + expect(after.captured).not.toContain(P.dropped); + // The other topic's dropped post, and the judgement itself, are untouched. + expect(after.captured).toContain(P.cupDropped); + expect(after.judgements.posts[P.dropped].state).toBe("drop"); + await expect(post(page, P.dropped)).toHaveAttribute("data-library-judgement", "drop"); + await idle(page); + + // Again: nothing to remove, and no removal is offered. + await page.locator("[data-library-purge]").click(); + await expect(plan.locator("[data-library-purge-sentence]")).toHaveText("No dropped post has a capture: nothing to remove."); + await expect(plan.locator("[data-library-purge-yes]")).toHaveCount(0); + await plan.locator("[data-library-purge-no]").click(); + // Cancel after a dry run removes nothing. + await open(page, { topic: CUPS }); + await page.locator("[data-library-purge]").click(); + await expect(plan.locator("[data-library-purge-sentence]")).toContainText("Would remove the capture of 1 dropped post"); + await plan.locator("[data-library-purge-no]").click(); + expect((await stub(request)).captured).toContain(P.cupDropped); +}); + +test("the media route serves a library's captured pictures and videos, and nothing else", async ({ request }) => { + const at = (l: string, id: string, name: string) => `/api/library/media/${l}/${id}/${name}`; + const shot = await request.get(at(LIB, P.opening, "shot.png")); + expect(shot.status()).toBe(200); + expect(shot.headers()["content-type"]).toBe("image/png"); + expect(shot.headers()["cache-control"]).toBe("private, no-store"); + expect(shot.headers()["cross-origin-resource-policy"]).toBe("same-origin"); + // A video, by byte range. + const part = await request.get(at(LIB, P.opening, `${P.opening}_2.mp4`), { headers: { range: "bytes=0-9" } }); + expect(part.status()).toBe(206); + expect(part.headers()["content-range"]).toBe(`bytes 0-9/${VIDEO_BYTES.length}`); + expect((await part.body()).toString()).toBe(VIDEO_BYTES.subarray(0, 10).toString()); + const head = await request.head(at(LIB, P.opening, "shot.png")); + expect(head.status()).toBe(200); + + // The record, a name whose real path is the raw read, a traversal, an id that is no id: never. + for (const [l, id, name] of [ + [LIB, P.opening, "capture.json"], + [LIB, P.opening, "planted.png"], + [LIB, P.opening, "missing.png"], + [LIB, "..", "judgements.json"], + [LIB, "reads", "page.png"], + [LIB, P.opening, "..%2F..%2Fjudgements.json"], + [LIB, P.opening, "%2E%2E"], + // A channel that is no library, with a file of the same shape on disk. + [NOT_A_LIB, P.opening, "shot.png"], + ["nope", P.opening, "shot.png"], + ]) { + const res = await request.get(at(l, id, name)); + expect([400, 404], `${l}/${id}/${name} answered ${res.status()}`).toContain(res.status()); + } + expect(existsSync(path.join(CHANNELS, NOT_A_LIB, "trending", "posts-media", P.opening, "shot.png"))).toBe(true); + // It lists nothing: no directory, no index. + for (const dir of [`/api/library/media/${LIB}/${P.opening}`, `/api/library/media/${LIB}`, "/api/library/media"]) { + expect((await request.get(dir)).status(), dir).toBe(404); + } + // Another site's page cannot fetch it. + expect((await request.get(at(LIB, P.opening, "shot.png"), { headers: { "sec-fetch-site": "cross-site" } })).status()).toBe(403); + expect((await request.get(at(LIB, P.opening, "shot.png"), { headers: { "sec-fetch-site": "same-origin" } })).status()).toBe(200); + // Read only. + expect([404, 405]).toContain((await request.post(at(LIB, P.opening, "shot.png"), { data: {} })).status()); +}); + +test("the press routes write as the operator whatever the body says, and send an agent elsewhere", async ({ request }) => { + // A body that claims to be an agent: not read. + const judged = await request.post("/api/library/judge", { data: { lib: LIB, by: "agent", set: [{ id: P.cup, state: "later", by: "agent" }] } }); + expect(judged.status()).toBe(200); + expect((await last(request)).body).toEqual({ slug: LIB, by: "operator", set: [{ id: P.cup, state: "later" }] }); + await request.post("/api/library/watch", { data: { lib: LIB, topic: "lids", on: true, by: "agent" } }); + expect((await last(request)).body.by).toBe("operator"); + await request.post("/api/library/purge", { data: { lib: LIB, dryRun: true, by: "agent" } }); + expect((await last(request)).body.by).toBe("operator"); + + // A caller carrying a bearer is an agent or the editor: refused, and nothing reaches the editor. + const before = (await stub(request)).requests.length; + for (const route of ["judge", "watch", "purge", "seen"]) { + const res = await request.post(`/api/library/${route}`, { headers: { authorization: "Bearer umtool-e2e-token" }, data: { lib: LIB, set: [{ id: P.cup, state: "keep" }], topic: "lids", on: true, dryRun: true, topics: ["lids"] } }); + expect(res.status(), route).toBe(403); + expect((await res.json()).error).toContain("pnpm ops judge-trending"); + } + expect((await stub(request)).requests.length).toBe(before); + expect(existsSync(SEEN)).toBe(false); + + // The page's own read, asked again after a press: the view's rows, to umtool's own pages only. + const read = await request.get(`/api/library?lib=${LIB}&topic=${KETTLES}&state=drop`); + expect(read.status()).toBe(200); + expect(read.headers()["cache-control"]).toBe("private, no-store"); + const rows = await read.json(); + expect(rows.ok).toBe(true); + expect(rows.posts.map((p: { id: string }) => p.id)).toEqual([P.dropped]); + expect((await request.get(`/api/library?lib=${LIB}`, { headers: { "sec-fetch-site": "cross-site" } })).status()).toBe(403); + + // Ill-shaped: refused here with a sentence, the editor not asked. + const bad = await request.post("/api/library/judge", { data: { lib: LIB, set: [{ id: "../x", state: "keep" }] } }); + expect(bad.status()).toBe(400); + expect((await bad.json()).error).toContain("not a post id"); + // A bulk press whose count is stale judges nothing. + const stale = await request.post("/api/library/judge", { data: { lib: LIB, bulk: { view: { topic: KETTLES, state: "unjudged" }, state: "drop" }, expect: 99 } }); + expect(stale.status()).toBe(409); + expect((await stale.json()).error).toContain("nothing was judged"); + expect((await stub(request)).requests.length).toBe(before); +}); + +test("on a phone (360 px): nothing pushes the page sideways, the topics fold, and a press works", async ({ page, request }) => { + await page.setViewportSize({ width: 360, height: 740 }); + await open(page, { topic: KETTLES }); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true); + await expect(rail(page)).toBeHidden(); + const fold = page.locator('[data-library-topics="fold"]'); + await expect(fold.locator("summary")).toHaveText("Topics · Kettle festival"); + await fold.locator("summary").click(); + await expect(fold.locator(`[data-library-topic="${CUPS}"]`)).toBeVisible(); + await fold.locator("summary").click(); + + await post(page, P.opening).locator('[data-library-press="keep"]').click(); + await expect(post(page, P.opening)).toHaveAttribute("data-library-judgement", "keep"); + expect((await last(request)).body).toEqual({ slug: LIB, by: "operator", set: [{ id: P.opening, state: "keep" }] }); + // The bar and the watch panel fit too. + await expect(page.locator("[data-library-bar]")).toBeVisible(); + for (const sel of ["[data-library-bar]", "[data-library-panel]", "[data-library-filters]", `[data-library-post="${P.opening}"]`]) { + const box = (await page.locator(sel).first().boundingBox())!; + expect(box.x, sel).toBeGreaterThanOrEqual(-1); + expect(box.x + box.width, sel).toBeLessThanOrEqual(361); + } + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true); + await page.screenshot({ path: test.info().outputPath("library-360.png"), fullPage: true }); +}); + +test("with the editor down, or holding no library, the page says so in a sentence", async ({ page, request }) => { + await reset(request, "unreachable"); + await page.goto(lib()); + const gone = page.locator("[data-library-unavailable]"); + await expect(gone).toHaveAttribute("data-library-unavailable", "unreachable", { timeout: 30_000 }); + await expect(gone).toContainText("The editor is not answering at"); + await expect(gone).toContainText("The library is read and judged through the editor: start it, then reload."); + await expect(page.locator("[data-library-post]")).toHaveCount(0); + // The shell is whole. + await expect(page.locator("[data-app-rail]")).toBeVisible(); + + await reset(request, "none"); + await page.goto(lib()); + await expect(gone).toHaveAttribute("data-library-unavailable", "no-library"); + await expect(gone).toContainText("The editor has no X trending library."); +});