commit 116ee814d5d5ca5cd876d6a030773f59255415b3
parent 9543fab0995a30f743abe1bb9b8fe3e274540691
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 9 Nov 2026 14:32:30 -0500
review: the X run console -- pick and order X channels, one run, a cookie countdown, Resume
/review's new X run section: the X posts channels in the default order
(focus, tier, rank, slug; paused ones unpicked), checkboxes and up/down
buttons, Start X run; the run's channels (queued / running / done N posts
/ deferred / failed), "N done, M deferred until the next refresh", the
jar's age counted down to social.x.maxCookieAgeMinutes, X's gap before the
next channel, and Resume once deferred. Polled through a new `xRun` view
(2 s while live, 10 s otherwise). The e2e's fake gallery-dl ages the jar
for `jar_ages_user`, so the spec sees a run go stale mid-way.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
7 files changed, 571 insertions(+), 2 deletions(-)
diff --git a/common/views/names.ts b/common/views/names.ts
@@ -27,6 +27,9 @@ export const VIEW_NAMES = [
"widgetActionable",
"cleanable",
"cookieAlerts",
+ // /review's X run console (common/controller/xRun.ts xRunConsole): the
+ // latest run, the X posts channels, the jar's age. Reads disk only.
+ "xRun",
] as const;
export type ViewName = (typeof VIEW_NAMES)[number];
@@ -54,4 +57,5 @@ export const VIEW_CONTRACT: Record<ViewName, "observe" | "construct"> = {
widgetActionable: "construct",
cleanable: "construct",
cookieAlerts: "construct",
+ xRun: "construct",
};
diff --git a/editor/app/api/view/[name]/route.test.ts b/editor/app/api/view/[name]/route.test.ts
@@ -55,7 +55,7 @@ const PAIRS: Array<[string, string]> = [
// Views born after the consolidation: there is no old path to rewrite, so
// they are served only at /api/view/<name>.
-const NEW_VIEWS = ["cookieAlerts"];
+const NEW_VIEWS = ["cookieAlerts", "xRun"];
async function view(name: string): Promise<number> {
const res = await GET(new Request(`http://localhost/api/view/${name}`), {
diff --git a/editor/app/api/view/views.ts b/editor/app/api/view/views.ts
@@ -12,6 +12,7 @@ import { buildSchedulerStatusPayload } from "../../scheduler/status";
import { widgetSyncInputs } from "../../widget/lib/syncInputs";
import { cleanableChannels } from "../../cleanup/lib/loadCleanup";
import { loadCookieAlerts } from "../../lib/cookieAlerts";
+import { xRunConsole } from "yt-dlp-transcript-common/controller/xRun";
import {
loadActionableSummary,
widgetActionableRows,
@@ -81,4 +82,9 @@ export const VIEWS: Record<ViewName, (req: Request) => Promise<Response>> = {
// (or are OK again, with the jobs it stopped). One small file and each
// recorded job's status.
cookieAlerts: async () => NextResponse.json(await loadCookieAlerts(getPaths())),
+
+ // /review's X run console: the latest run (each channel's state, the
+ // summary), the X posts channels in the default order and the jar's age
+ // against social.x.maxCookieAgeMinutes. Disk reads only; nothing asks X.
+ xRun: async () => NextResponse.json(await xRunConsole(getPaths())),
};
diff --git a/editor/app/review/components/XRunConsole.tsx b/editor/app/review/components/XRunConsole.tsx
@@ -0,0 +1,364 @@
+"use client";
+
+// THE X RUN CONSOLE (/review, lane x-console). Pick X posts channels, order
+// them, start ONE `x-run` job: fetch-posts for each in sequence, X's queue gap
+// between two, at most 200 posts each, the cookie jar checked before each
+// channel. When the jar passes social.x.maxCookieAgeMinutes the run stops and
+// the rest are deferred; after the operator refreshes the jar (/settings),
+// Resume runs them. Nothing here refreshes cookies or asks X anything — the
+// console reads disk (the run's state file, the jar's mtime) through the
+// `xRun` view.
+
+import Link from "next/link";
+import { useEffect, useMemo, useState, useTransition } from "react";
+import type {
+ XRunCandidate,
+ XRunChannelStatus,
+ XRunConsole as XRunConsolePayload,
+ XRunView,
+} from "yt-dlp-transcript-common/controller/xRun";
+import { useNow, usePolledPayload } from "../../lib/usePolledPayload";
+import { resumeXRunAction, startXRunAction } from "../xRunActions";
+
+// "4:05", "1:02:03".
+function clock(ms: number): string {
+ const s = Math.max(0, Math.floor(ms / 1000));
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const sec = String(s % 60).padStart(2, "0");
+ return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${sec}` : `${m}:${sec}`;
+}
+
+// "45 min", "3 h", "16 days".
+function age(ms: number): string {
+ const min = Math.max(0, Math.floor(ms / 60_000));
+ if (min < 120) return `${min} min`;
+ const h = Math.floor(min / 60);
+ return h < 48 ? `${h} h` : `${Math.floor(h / 24)} days`;
+}
+
+// X's queue gap, as the run waits it between two channels.
+function gapText(seconds: number): string {
+ if (seconds <= 0) return "no gap between channels";
+ if (seconds < 120) return `${seconds} s between channels`;
+ return `${Math.round(seconds / 60)} min between channels`;
+}
+
+function when(iso: string | null): string {
+ if (!iso) return "never";
+ return `${iso.slice(0, 10)} ${iso.slice(11, 16)}`;
+}
+
+const STATUS_TONE: Record<XRunChannelStatus, string> = {
+ queued: "bg-muted text-muted-foreground",
+ running: "bg-info-soft text-info",
+ done: "bg-success-soft text-success",
+ deferred: "bg-warning-soft text-warning",
+ failed: "bg-destructive-soft text-destructive",
+};
+
+const TIER_TONE: Record<string, string> = {
+ focus: "bg-brand-soft text-brand-ink",
+ normal: "bg-muted text-muted-foreground",
+ low: "bg-muted text-faint",
+ paused: "bg-warning-soft text-warning",
+};
+
+// THE JAR, COUNTED DOWN. Ticks every second from the jar's mtime and the
+// limit; the poll refreshes both (a refresh on /settings rewrites the jar).
+function JarCountdown({ jar, now }: { jar: XRunConsolePayload["jar"]; now: number | null }) {
+ const href = "/settings";
+ if (jar.alert) {
+ return (
+ <p role="status" aria-label="x cookie jar" data-jar="alert" className="text-sm text-destructive">
+ The X cookie alert is up ({jar.alert.line}): no X job starts until it is cleared on the dashboard.
+ </p>
+ );
+ }
+ if (!jar.ageChecked) {
+ return (
+ <p role="status" aria-label="x cookie jar" data-jar="unchecked" className="text-sm text-muted-foreground">
+ {jar.source === "browser"
+ ? "X login: the browser's cookies — their age cannot be read, so the limit is not checked."
+ : "The cookie age limit is off (social.x.maxCookieAgeMinutes = 0)."}
+ </p>
+ );
+ }
+ if (!jar.cookiesUpdatedAt || !jar.staleAt) {
+ return (
+ <p role="status" aria-label="x cookie jar" data-jar="none" className="text-sm text-destructive">
+ No X cookie jar: <Link href={href} className="underline">Connect X account on /settings</Link>.
+ </p>
+ );
+ }
+ const at = now ?? Date.parse(jar.cookiesUpdatedAt);
+ const left = Date.parse(jar.staleAt) - at;
+ const old = at - Date.parse(jar.cookiesUpdatedAt);
+ if (left <= 0) {
+ return (
+ <p role="status" aria-label="x cookie jar" data-jar="stale" className="text-sm text-warning">
+ Cookie jar {age(old)} old, past the {jar.maxAgeMinutes} min limit —{" "}
+ <Link href={href} className="underline">Refresh cookies on /settings</Link>, then Resume.
+ </p>
+ );
+ }
+ return (
+ <p role="status" aria-label="x cookie jar" data-jar="fresh" className="text-sm">
+ Cookie jar {age(old)} old ·{" "}
+ <span className="font-mono tabular-nums" aria-label="cookie time left">
+ {clock(left)}
+ </span>{" "}
+ left of {jar.maxAgeMinutes} min
+ </p>
+ );
+}
+
+function RunPanel({
+ run,
+ now,
+ onResume,
+ pending,
+}: {
+ run: XRunView;
+ now: number | null;
+ onResume: () => void;
+ pending: boolean;
+}) {
+ const waitLeft = run.waitingUntil && now ? Date.parse(run.waitingUntil) - now : null;
+ return (
+ <div aria-label="x run" data-run-status={run.status} className="flex flex-col gap-2 min-w-0">
+ <div className="flex items-center gap-2 flex-wrap text-sm">
+ <span className="font-medium">Run {run.id.slice(-6).toLowerCase()}</span>
+ <span className="rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">{run.status}</span>
+ {run.jobId && (
+ <Link href={`/jobs/${run.jobId}`} className="text-xs underline text-muted-foreground">
+ job log
+ </Link>
+ )}
+ <span className="text-xs text-muted-foreground">≤ {run.limit} posts each</span>
+ </div>
+ <p aria-label="x run summary" className="text-sm font-medium">
+ {run.summary}
+ </p>
+ {waitLeft !== null && waitLeft > 0 && (
+ <p className="text-xs text-muted-foreground">
+ Next channel in <span className="font-mono tabular-nums">{clock(waitLeft)}</span> (X's queue gap).
+ </p>
+ )}
+ {run.stopped && (
+ <p aria-label="x run stopped" className="text-xs text-muted-foreground">
+ {run.stopped}
+ </p>
+ )}
+ <ol className="flex flex-col divide-y divide-border rounded-md border border-border max-h-72 overflow-y-auto">
+ {run.channels.map((c) => (
+ <li
+ key={c.slug}
+ aria-label={`x run channel ${c.slug}`}
+ data-status={c.status}
+ className="flex items-center gap-2 px-2 py-1 text-sm"
+ >
+ <Link href={`/channels/${c.slug}`} className="truncate underline-offset-2 hover:underline">
+ {c.slug}
+ </Link>
+ <span className={`ml-auto shrink-0 rounded-full px-2 py-0.5 text-xs ${STATUS_TONE[c.status]}`}>
+ {c.status === "done" ? `done · ${c.posts ?? 0} posts` : c.status}
+ </span>
+ {c.error && (
+ <span className="basis-full text-xs text-destructive truncate" title={c.error}>
+ {c.error}
+ </span>
+ )}
+ </li>
+ ))}
+ </ol>
+ {run.resumable > 0 && (
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={onResume}
+ disabled={pending}
+ className="px-3 py-1.5 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 disabled:opacity-50"
+ >
+ Resume ({run.resumable} deferred)
+ </button>
+ <span className="text-xs text-muted-foreground">after a cookie refresh; starts with the deferred channels</span>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function Picker({
+ candidates,
+ order,
+ setOrder,
+ picked,
+ setPicked,
+}: {
+ candidates: XRunCandidate[];
+ order: string[];
+ setOrder: (o: string[]) => void;
+ picked: Set<string>;
+ setPicked: (p: Set<string>) => void;
+}) {
+ const bySlug = useMemo(() => new Map(candidates.map((c) => [c.slug, c])), [candidates]);
+ const move = (i: number, d: -1 | 1) => {
+ const j = i + d;
+ if (j < 0 || j >= order.length) return;
+ const next = [...order];
+ [next[i], next[j]] = [next[j], next[i]];
+ setOrder(next);
+ };
+ const toggle = (slug: string) => {
+ const next = new Set(picked);
+ if (next.has(slug)) next.delete(slug);
+ else next.add(slug);
+ setPicked(next);
+ };
+ return (
+ <ol aria-label="x run channels" className="flex flex-col divide-y divide-border rounded-md border border-border max-h-80 overflow-y-auto">
+ {order.map((slug, i) => {
+ const c = bySlug.get(slug);
+ if (!c) return null;
+ return (
+ <li key={slug} aria-label={`pick ${slug}`} className="flex items-center gap-2 px-2 py-1 text-sm">
+ <input
+ type="checkbox"
+ aria-label={`run ${slug}`}
+ checked={picked.has(slug)}
+ onChange={() => toggle(slug)}
+ />
+ <span className="w-5 text-right text-xs tabular-nums text-faint">{i + 1}</span>
+ <span className="min-w-0 truncate" title={c.name}>
+ {slug}
+ </span>
+ <span className={`shrink-0 rounded-full px-1.5 py-0.5 text-[11px] ${TIER_TONE[c.tier] ?? TIER_TONE.normal}`}>
+ {c.tier}
+ </span>
+ {c.search && <span className="shrink-0 text-[11px] text-muted-foreground">search</span>}
+ <span
+ className="ml-auto shrink-0 text-xs text-muted-foreground tabular-nums"
+ title={c.lastError ?? undefined}
+ >
+ {c.postCount} · {when(c.lastFetchedAt)}
+ </span>
+ <span className="flex shrink-0">
+ <button
+ type="button"
+ aria-label={`move ${slug} up`}
+ onClick={() => move(i, -1)}
+ disabled={i === 0}
+ className="px-1 text-muted-foreground hover:text-foreground disabled:opacity-30"
+ >
+ ↑
+ </button>
+ <button
+ type="button"
+ aria-label={`move ${slug} down`}
+ onClick={() => move(i, 1)}
+ disabled={i === order.length - 1}
+ className="px-1 text-muted-foreground hover:text-foreground disabled:opacity-30"
+ >
+ ↓
+ </button>
+ </span>
+ </li>
+ );
+ })}
+ </ol>
+ );
+}
+
+export function XRunConsole({ initial }: { initial: XRunConsolePayload }) {
+ const [pending, startTransition] = useTransition();
+ const [fast, setFast] = useState(initial.run?.live ?? false);
+ const { data, refetch } = usePolledPayload<XRunConsolePayload>("/api/view/xRun", true, fast ? 2000 : 10_000, initial, {
+ immediate: false,
+ });
+ const view = data ?? initial;
+ const live = view.run?.live ?? false;
+ // Polled every 2 s while a run is live, every 10 s otherwise.
+ useEffect(() => setFast(live), [live]);
+ const now = useNow();
+ // The default order is the candidates' (focus, tier, rank, slug); paused
+ // channels start unpicked.
+ const [order, setOrder] = useState<string[]>(() => initial.candidates.map((c) => c.slug));
+ const [picked, setPicked] = useState<Set<string>>(
+ () => new Set(initial.candidates.filter((c) => c.tier !== "paused").map((c) => c.slug)),
+ );
+ // A channel added since the page loaded joins the end of the order.
+ const known = new Set(order);
+ const extra = view.candidates.filter((c) => !known.has(c.slug)).map((c) => c.slug);
+ const fullOrder = extra.length ? [...order, ...extra] : order;
+ const chosen = fullOrder.filter((s) => picked.has(s) && view.candidates.some((c) => c.slug === s));
+ const [note, setNote] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ const after = (res: Awaited<ReturnType<typeof startXRunAction>>, ok: string) => {
+ if (res.ok) {
+ setNote(ok);
+ setError(null);
+ setFast(true);
+ } else {
+ setNote(null);
+ setError(res.error);
+ }
+ void refetch();
+ };
+ const start = () =>
+ startTransition(async () => {
+ after(await startXRunAction(chosen), `X run queued: ${chosen.length} channel(s).`);
+ });
+ const resume = () =>
+ startTransition(async () => {
+ if (!view.run) return;
+ after(await resumeXRunAction(view.run.id), "Resume queued: the deferred channels run first.");
+ });
+
+ return (
+ <section aria-label="x run console" className="flex flex-col gap-3">
+ <div className="flex items-center justify-between flex-wrap gap-2">
+ <h2 className="text-lg font-semibold">X run</h2>
+ <JarCountdown jar={view.jar} now={now} />
+ </div>
+ {view.candidates.length === 0 ? (
+ <p className="text-sm text-muted-foreground">No X posts channels.</p>
+ ) : (
+ <div className="grid gap-4 lg:grid-cols-2">
+ <div className="flex flex-col gap-2 min-w-0">
+ <Picker candidates={view.candidates} order={fullOrder} setOrder={setOrder} picked={picked} setPicked={setPicked} />
+ <div className="flex items-center gap-2 flex-wrap">
+ <button
+ type="button"
+ onClick={start}
+ disabled={pending || live || chosen.length === 0}
+ className="px-3 py-1.5 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 disabled:opacity-50"
+ >
+ Start X run ({chosen.length})
+ </button>
+ <span className="text-xs text-muted-foreground">
+ ≤ {view.maxPosts} posts each · {gapText(view.gapSeconds)}
+ </span>
+ </div>
+ {note && (
+ <p role="status" aria-label="x run note" className="text-xs text-muted-foreground">
+ {note}
+ </p>
+ )}
+ {error && (
+ <p role="alert" aria-label="x run error" className="text-xs text-destructive">
+ {error}
+ </p>
+ )}
+ </div>
+ {view.run ? (
+ <RunPanel run={view.run} now={now} onResume={resume} pending={pending} />
+ ) : (
+ <p className="text-sm text-muted-foreground">No X run yet.</p>
+ )}
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/editor/app/review/page.tsx b/editor/app/review/page.tsx
@@ -20,6 +20,8 @@ import { RunDuplicateDetectionButton } from "./components/RunDuplicateDetectionB
import { RunMediaScanButton } from "./components/RunMediaScanButton";
import { MediaScanFindingRow } from "./components/MediaScanFindingRow";
import { DuplicateClusterReview } from "./components/DuplicateClusterReview";
+import { XRunConsole } from "./components/XRunConsole";
+import { xRunConsole } from "yt-dlp-transcript-common/controller/xRun";
export const dynamic = "force-dynamic";
@@ -29,12 +31,22 @@ export const metadata: Metadata = { title: "Review" };
// and media-integrity findings are both flag-only, both carry a reviewed state,
// and neither is an operation or a pile of reclaimable bytes — which is why
// they are here rather than on an operation page or on /cleanup.
+//
+// THE X RUN CONSOLE (lane x-console) is here for the same reason: an X run is
+// a pass a person starts and whose outcome needs a person — the cookie jar
+// goes stale mid-run, the rest are deferred, and only the operator's refresh
+// on /settings lets Resume take them. It is the X work that waits on a human
+// (the dashboard's X banner says the jar is stale; this says what waits on
+// it), not a lane the machine dispatches, and /channels is a dense rack whose
+// rows are channels, not a sequence across them.
export default async function ReviewPage() {
- const review = await loadReviewSummary(getPaths());
+ const paths = getPaths();
+ const [review, xRun] = await Promise.all([loadReviewSummary(paths), xRunConsole(paths)]);
return (
<div className="flex flex-col gap-6">
<h1 className="text-2xl font-semibold">Review</h1>
<AutoPausedSection rows={review.autoPaused} />
+ <XRunConsole initial={xRun} />
<DuplicatesSection
report={review.duplicates}
overrides={review.duplicateOverrides}
diff --git a/editor/e2e/fixtures/bin/fake-gallery-dl.mjs b/editor/e2e/fixtures/bin/fake-gallery-dl.mjs
@@ -134,3 +134,21 @@ const TWEETS = [
for (const tweet of TWEETS.slice(0, limit)) {
process.stdout.write(JSON.stringify(tweet) + "\n");
}
+
+// TIME PASSES DURING A FETCH (x-run-console.spec): for the account
+// `jar_ages_user`, the cookie jar it was handed (`--cookies <file>`) is two
+// hours old once the fetch ends — what an X run meets when the jar passes
+// social.x.maxCookieAgeMinutes between two channels. Only the file's mtime
+// changes; nothing is fetched.
+if (handle === "jar_ages_user") {
+ const at = args.indexOf("--cookies");
+ if (at >= 0 && args[at + 1]) {
+ const { utimesSync } = await import("node:fs");
+ const t = new Date(Date.now() - 2 * 60 * 60 * 1000);
+ try {
+ utimesSync(args[at + 1], t, t);
+ } catch {
+ // no jar handed over: nothing to age
+ }
+ }
+}
diff --git a/editor/e2e/x-run-console.spec.ts b/editor/e2e/x-run-console.spec.ts
@@ -0,0 +1,165 @@
+// THE X RUN CONSOLE (/review, lane x-console), end to end.
+//
+// The 8–9 Nov case in miniature: X fetch-posts for several channels, one after
+// another, until the cookie jar passes social.x.maxCookieAgeMinutes — then the
+// rest wait for a refresh. One x-run job does it: the console picks and orders
+// the channels, the run fetches each in turn (the fake gallery-dl: X is NEVER
+// contacted), the jar is read before each channel, and once it is stale the
+// remaining channel is deferred. The operator refreshes the jar (written by
+// hand here — no X, no browser) and Resume runs the deferred channel.
+//
+// The fake gallery-dl ages the jar it is handed for the account
+// `jar_ages_user` (two hours old once its fetch ends): time passing mid-run,
+// deterministically. The test server turns the built-in gap and age limit off
+// (E2E_JOB_GAP_SECONDS=0, E2E_X_MAX_COOKIE_AGE_MINUTES=0); this spec sets the
+// age limit itself.
+
+import { mkdir, utimes, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { test, expect, type Page } from "@playwright/test";
+import { pathExists, resetData, resolvePath, testPaths, writeSettings } from "./helpers";
+import { baseUrl } from "./baseUrl";
+
+const AUTH = { authorization: "Bearer test-worker-token" };
+
+async function xChannel(slug: string, handle: string): Promise<void> {
+ const dir = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`);
+ await mkdir(dir, { recursive: true });
+ await writeFile(
+ `${dir}/config.json`,
+ JSON.stringify({
+ name: `${handle} (X)`,
+ handling: "transcribe",
+ sourceKind: "social",
+ postFetcher: "x-gallery-dl",
+ platform: "twitter",
+ socialHandle: handle,
+ url: `https://x.com/${handle}`,
+ }),
+ );
+}
+
+async function xJar(ageMs: number): Promise<void> {
+ const dir = resolvePath(`${testPaths().transcriptsDir}/.x-session`);
+ await mkdir(`${dir}/profile`, { recursive: true });
+ await writeFile(`${dir}/cookies.txt`, "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tfake\n");
+ const t = new Date(Date.now() - ageMs);
+ await utimes(`${dir}/cookies.txt`, t, t);
+}
+
+const SHOTS = process.env.E2E_UI_OPS_SHOTS ?? "";
+async function shot(page: Page, name: string) {
+ if (!SHOTS) return;
+ await mkdir(SHOTS, { recursive: true });
+ await page.screenshot({ path: path.join(SHOTS, `${name}.png`), fullPage: false });
+}
+
+const posts = (slug: string) => `${testPaths().transcriptsDir}/channels/${slug}/posts-archive`;
+
+test.beforeEach(async () => {
+ await resetData("empty");
+ await writeSettings({
+ minFreeDiskGB: 0,
+ social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 60 } },
+ channelPriority: { focus: { kind: "none" }, channels: { "x-low": { tier: "low" }, "x-paused": { tier: "paused" } } },
+ });
+ await xChannel("x-alpha", "alpha_user");
+ await xChannel("x-beta", "jar_ages_user");
+ await xChannel("x-gamma", "gamma_user");
+ await xChannel("x-low", "low_user");
+ await xChannel("x-paused", "paused_user");
+});
+
+test("an X run: picked and ordered, the jar goes stale mid-run, the rest deferred; a refreshed jar and Resume finish it", async ({
+ page,
+ request,
+}) => {
+ test.setTimeout(120_000);
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await xJar(60_000);
+ await page.goto("/review");
+ const consoleEl = page.getByRole("region", { name: "x run console" });
+ await expect(consoleEl.getByRole("heading", { name: "X run" })).toBeVisible();
+
+ // The default order is the priority tiers': normal (by slug), low, paused;
+ // a paused channel starts unpicked.
+ const picker = consoleEl.getByRole("list", { name: "x run channels" });
+ await expect(picker.getByRole("listitem")).toHaveText([/x-alpha/, /x-beta/, /x-gamma/, /x-low/, /x-paused/]);
+ await expect(picker.getByRole("checkbox", { name: "run x-paused" })).not.toBeChecked();
+ await expect(picker.getByRole("checkbox", { name: "run x-alpha" })).toBeChecked();
+ // Reorder: x-low up above x-gamma, then back down.
+ await picker.getByRole("button", { name: "move x-low up" }).click();
+ await expect(picker.getByRole("listitem")).toHaveText([/x-alpha/, /x-beta/, /x-low/, /x-gamma/, /x-paused/]);
+ await picker.getByRole("button", { name: "move x-low down" }).click();
+ await expect(picker.getByRole("listitem")).toHaveText([/x-alpha/, /x-beta/, /x-gamma/, /x-low/, /x-paused/]);
+ await picker.getByRole("checkbox", { name: "run x-low" }).uncheck();
+
+ // The jar, counted down against the limit.
+ const jar = consoleEl.getByRole("status", { name: "x cookie jar" });
+ await expect(jar).toHaveAttribute("data-jar", "fresh");
+ await expect(jar).toContainText(/Cookie jar 1 min old · 5\d:\d\d left of 60 min/);
+ await shot(page, "x-run-console-picker");
+
+ await consoleEl.getByRole("button", { name: "Start X run (3)" }).click();
+ const run = consoleEl.getByLabel("x run", { exact: true });
+ await expect(run).toHaveAttribute("data-run-status", "deferred", { timeout: 60_000 });
+ await expect(consoleEl.getByLabel("x run summary")).toHaveText("2 done, 1 deferred until the next refresh");
+ await expect(run.getByLabel("x run channel x-alpha")).toHaveAttribute("data-status", "done");
+ await expect(run.getByLabel("x run channel x-alpha")).toContainText("done · 3 posts");
+ await expect(run.getByLabel("x run channel x-beta")).toHaveAttribute("data-status", "done");
+ await expect(run.getByLabel("x run channel x-gamma")).toHaveAttribute("data-status", "deferred");
+ await expect(consoleEl.getByLabel("x run stopped")).toContainText(
+ /X cookies were last refreshed (120 min|2 h) ago \(limit 60 min\)/,
+ );
+ // The jar the fetch aged is stale now: the countdown says so.
+ await expect(jar).toHaveAttribute("data-jar", "stale");
+ expect(await pathExists(posts("x-alpha"))).toBe(true);
+ expect(await pathExists(posts("x-gamma"))).toBe(false);
+ await shot(page, "x-run-console-deferred");
+
+ // The ops twin reads the same run.
+ const got = await request.get(`${baseUrl}/api/ops/x-run`, { headers: AUTH });
+ const body = (await got.json()) as { run: { id: string; summary: string; resumable: number; jobIds: string[] } };
+ expect(body.run.summary).toBe("2 done, 1 deferred until the next refresh");
+ expect(body.run.resumable).toBe(1);
+ expect(body.run.jobIds).toHaveLength(1);
+
+ // The operator refreshes the jar; Resume runs the deferred channel.
+ await xJar(0);
+ await expect(jar).toHaveAttribute("data-jar", "fresh", { timeout: 20_000 });
+ await consoleEl.getByRole("button", { name: "Resume (1 deferred)" }).click();
+ await expect(run).toHaveAttribute("data-run-status", "done", { timeout: 60_000 });
+ await expect(consoleEl.getByLabel("x run summary")).toHaveText("3 done");
+ await expect(run.getByLabel("x run channel x-gamma")).toHaveAttribute("data-status", "done");
+ expect(await pathExists(posts("x-gamma"))).toBe(true);
+ // x-low was not picked: never fetched.
+ expect(await pathExists(posts("x-low"))).toBe(false);
+ const after = (await (await request.get(`${baseUrl}/api/ops/x-run?run=${body.run.id}`, { headers: AUTH })).json()) as {
+ run: { jobIds: string[] };
+ };
+ expect(after.run.jobIds).toHaveLength(2);
+ await shot(page, "x-run-console-done");
+});
+
+test("the ops twin: a stale jar refuses a new run before any job, and the console offers its Resume", async ({
+ page,
+ request,
+}) => {
+ await xJar(16 * 24 * 60 * 60_000);
+ const res = await request.post(`${baseUrl}/api/ops/x-run`, {
+ headers: AUTH,
+ data: { channels: ["x-alpha", "x-gamma"] },
+ });
+ expect(res.status()).toBe(400);
+ const body = (await res.json()) as { error: string; run: string };
+ expect(body.error).toMatch(/^X cookies were last refreshed 16 days ago \(limit 60 min\)/);
+ expect(body.run).toMatch(/^xr-/);
+
+ await page.goto("/review");
+ const consoleEl = page.getByRole("region", { name: "x run console" });
+ await expect(consoleEl.getByLabel("x run summary")).toHaveText("0 done, 2 deferred until the next refresh");
+ await expect(consoleEl.getByRole("status", { name: "x cookie jar" })).toHaveAttribute("data-jar", "stale");
+ // Resume on the same stale jar is refused with the guard's sentence.
+ await consoleEl.getByRole("button", { name: "Resume (2 deferred)" }).click();
+ await expect(consoleEl.getByRole("alert", { name: "x run error" })).toContainText("X cookies were last refreshed 16 days ago");
+});