commit d99e1bfbafe002c106c20141ce46f20c74a2d3a7
parent 5ca1161dd768df87dcf6d03bde55b1ec144076de
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 20 Oct 2026 14:18:19 -0400
wayback pages live (editor): the channel page's Originals and Save Page Now, the ops routes, e2e spec
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
10 files changed, 609 insertions(+), 3 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,8 @@
# Changelog
## [Unreleased]
+- **Is a Wayback page's original still up? The channel page says, and can ask the Wayback Machine to save one now.** A Wayback pages channel's page has **Originals**: **Check originals** asks each record's original address at its own site — never the Wayback Machine — once per address, a few seconds apart, and the page lists every original that is gone (404 or 410, or X's, Tumblr's, Google Docs' or YouTube's "does not exist" page) with "the only copy" linking its Wayback copy; a suspended account or a document no longer shared reads as unavailable, and anything else (a wall, an outage, a redirect to another site) as an error, never as gone. Gone records read as deleted wherever a deleted post does. **Save Page Now** — "Ask the Wayback Machine to capture this now" — takes any address, or a record whose original is still up (**Capture now**): archive.org captures the page, the job waits for it, and the new capture is imported into the channel. It needs your archive.org S3 keys (`ARCHIVE_ORG_S3_ACCESS` and `ARCHIVE_ORG_S3_SECRET` in the editor's environment, or in the mode-600 file `archiveOrg.s3KeyFile` names); without them the button is off and says why, and the keys are never logged. From a terminal: `pnpm ops check-post-availability`, `pnpm ops save-page-now` (`dryRun` first). Needs a restart of the editor.
+- **find-copy finds a copy of a gone page a report cites.** `pnpm ops find-copy` with `"pages": true` checks each page a report cites at its own site; for one that is gone it imports the Wayback capture nearest the citation's date into the Wayback pages channel you name (`"channel"`) or the one whose targets cover it, and its result names the record the citation should now cite. A page still up is left (save it now instead), and a cited page record whose original is gone keeps its stored capture. `"dryRun": true` asks the same questions and imports nothing. The report is not rewritten.
- **Wayback Machine captures of pages are records of their own.** A capture of a page that is not a video — an old blog post, a group's site, a channel's About page, a document taken down — goes into a **Wayback pages** channel: on the New channel form, paste a Wayback URL of such a page (`web.archive.org/web/*/example.com/blog*` scopes every capture under that path, `*.example.com` a whole domain, one capture's URL that page) or choose **Wayback pages** as the platform, and edit its targets (a URL, how it matches, optional dates). The channel page's **Import a capture** takes a capture's URL, or the page's own URL and a date for the capture nearest it, and imports it as one job at archive.org's pace: the page as captured is kept, its readable text, title, author, date, links and images become a record — searchable, in the MCP and on a built site like any post — dated by the page's own date when it gives one. A later capture of the same page is kept as a version of the first. **Re-extract** reads every kept capture again with no request. A capture of a video is still Import video's, and is refused here with a sentence saying so. An x.com or twitter.com capture is private exactly as X posts are. From a terminal: `pnpm ops import-page` (`dryRun` says what it would fetch) and `pnpm ops reextract-pages`; `pnpm archilyzer wayback pages import|reextract` run without the editor. Needs a restart of the editor.
- **Scan a Wayback pages channel, then choose what to import.** A channel whose config names `wayback.targets` (a page, a prefix, a host or a domain, with optional dates) has a **Captures** tab: **Scan now** lists what the Wayback Machine holds of them — one row per distinct version of each page, with when it was first and last seen — without fetching a single page, at archive.org's pace, at most 50,000 rows a run; **Continue scan** picks up where a run stopped, and a later scan marks what is **new**. Filter by year, path and text, then **Import selected** or **Import all in range** (asked to confirm above 50): one import job per capture, one at a time. Rows already imported are marked and skipped. The same over HTTP: `pnpm ops wayback-scan --json '{"slug":"<slug>"}'` and `pnpm ops wayback-import --json '{"slug":"<slug>","year":"2014"}'` (both take `dryRun`); offline, `pnpm archilyzer wayback scan <slug>`. With `wayback.auto: true` the download lane imports the captures later scans add, at the same pace; it is off unless a channel turns it on.
- **Wayback captures of Tumblr, Twitter, forums, Google Docs and YouTube About pages are read as their posts.** A Tumblr blog's post, index, tagged or archive page becomes one record per post (its date, tags, images and what it reblogged), and the same post seen on an index and on its own page is one record. An old Twitter profile or status page becomes one record per tweet — replies, retweets and quotes pointing at the tweets they answer, and the profile's bio, website and counts as one more — and a capture of X's later JavaScript app says it holds no posts. A captured XenForo thread page gives the same posts, with the same ids, that a forum channel of the thread holds. A Google Doc's mobilebasic or published page gives the document's text with its headings; its edit page says it holds no text and names the mobilebasic address to look for. A YouTube channel's About page gives how the channel described itself at that capture: description, links, joined date and counts. Nothing calls a model.
diff --git a/editor/app/api/ops/check-post-availability/route.ts b/editor/app/api/ops/check-post-availability/route.ts
@@ -0,0 +1,32 @@
+import { checkPostAvailabilityAction } from "../../../channels/[slug]/socialActions";
+import {
+ CHECK_POST_AVAILABILITY_MODES,
+ type CheckPostAvailabilityMode,
+} from "yt-dlp-transcript-common/controller/checkPostAvailability";
+import { OpsInputError, jobResponse, ops, optPositiveInt, optString, reqSlug } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, mode?, limit? } -> { ok: true, jobId }
+//
+// WHICH ARCHIVED POSTS ARE GONE AT THEIR SOURCE (the channel page's "Check
+// deleted posts"; release 37 S5 adds this door): a check-post-availability
+// job. A Wayback pages channel's records are checked by their ORIGINAL URL at
+// its own site (lib/waybackPages/liveness-server.ts, the web pacer — never
+// the Wayback Machine), one request per distinct URL; any other posts
+// channel through its fetcher's own check. `mode`: "stale" (default) |
+// "unchecked" | "all"; `limit` (default 200) counts posts, or URLs for a
+// pages channel. The verdicts land in posts-availability.json.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "mode", "limit"], async (body) => {
+ const slug = reqSlug(body, "slug");
+ const mode = optString(body, "mode");
+ if (mode !== undefined && !(CHECK_POST_AVAILABILITY_MODES as string[]).includes(mode)) {
+ throw new OpsInputError(`"mode" must be one of ${CHECK_POST_AVAILABILITY_MODES.join(", ")}`);
+ }
+ const limit = optPositiveInt(body, "limit");
+ return jobResponse(
+ await checkPostAvailabilityAction(slug, undefined, mode as CheckPostAvailabilityMode | undefined, limit),
+ );
+ });
+}
diff --git a/editor/app/api/ops/find-copy/route.ts b/editor/app/api/ops/find-copy/route.ts
@@ -1,6 +1,8 @@
import { findCopyAction, findWholeCopiesAction } from "../../../channels/[slug]/videos/findCopyAction";
import { FIND_COPY_MAX_LIMIT, GONE_SCOPES, type GoneScope } from "yt-dlp-transcript-common/publish/findCopy";
import { OpsInputError, jobResponse, ops, optBool, optPositiveInt, optString } from "../_lib";
+import { findPageCopiesAction } from "../../../channels/[slug]/waybackLiveActions";
+import { FIND_PAGE_COPY_MAX_LIMIT } from "yt-dlp-transcript-common/publish/findCopyPages";
export const dynamic = "force-dynamic";
@@ -36,12 +38,48 @@ export const dynamic = "force-dynamic";
// with `@@find-copy {scope, gone, dryRun, max, channels, eligible, skipped,
// looked: [{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?,
// via?, outcome}], left, items, stopped?, fetchJobId?, refused?}`.
+//
+// POST { article } | { siteId } | { articles: true }, pages: true, channel?,
+// max?, dryRun? -> { ok, jobId } — THE PAGE MODE (release 37 S5,
+// publish/findCopyPages.ts): every page the reports cite whose ORIGINAL is
+// gone at its own site gets the Wayback capture nearest the citation's date
+// imported into the Wayback pages channel named (`channel`) or the one whose
+// targets cover it; a cited page record whose original is gone has its
+// capture imported again when it is not stored. A find-copy job on the
+// archive.org queue; at most `max` (default 10, at most 100) pages looked up.
+// The log ends with `@@find-copy {host, dryRun, max, pages, posts, items:
+// [{citedBy, url, original, channel?, capture?, outcome, detail, pointTo?,
+// as?, records?}], left, stopped?}` — `pointTo`/`as` name the record a
+// citation should cite; the report is not rewritten.
export async function POST(request: Request) {
- return ops(request, ["article", "siteId", "articles", "dryRun", "retryFailed", "slug", "gone", "max"], async (body) => {
+ return ops(request, ["article", "siteId", "articles", "dryRun", "retryFailed", "slug", "gone", "max", "pages", "channel"], async (body) => {
const article = optString(body, "article")?.trim();
const siteId = optString(body, "siteId")?.trim();
const articles = optBool(body, "articles") === true;
const gone = optString(body, "gone");
+ if (optBool(body, "pages") === true) {
+ if (gone !== undefined || optString(body, "slug") !== undefined || body.retryFailed !== undefined) {
+ throw new OpsInputError('"pages" is its own mode: send "article", "articles": true or "siteId", with "channel"?, "max"?, "dryRun"? — not "gone", "slug" or "retryFailed"');
+ }
+ if ([article, siteId, articles || undefined].filter(Boolean).length !== 1) {
+ throw new OpsInputError('send one of "article" (an article id), "articles": true or "siteId"');
+ }
+ const max = optPositiveInt(body, "max");
+ if (max !== undefined && max > FIND_PAGE_COPY_MAX_LIMIT) {
+ throw new OpsInputError(`"max" must be at most ${FIND_PAGE_COPY_MAX_LIMIT}`);
+ }
+ const channel = optString(body, "channel")?.trim() || undefined;
+ return jobResponse(
+ await findPageCopiesAction({
+ ...(article ? { article } : {}),
+ ...(siteId ? { siteId } : {}),
+ ...(channel ? { channel } : {}),
+ ...(max !== undefined ? { max } : {}),
+ dryRun: optBool(body, "dryRun") === true,
+ }),
+ );
+ }
+ if (optString(body, "channel") !== undefined) throw new OpsInputError('"channel" goes with "pages": true (the page mode)');
if (gone !== undefined) {
if (!(GONE_SCOPES as readonly string[]).includes(gone)) {
throw new OpsInputError(`"gone" must be one of ${GONE_SCOPES.join(", ")}`);
diff --git a/editor/app/api/ops/save-page-now/route.ts b/editor/app/api/ops/save-page-now/route.ts
@@ -0,0 +1,31 @@
+import { NextResponse } from "next/server";
+import { savePageNowAction, savePageNowDryRunAction } from "../../../channels/[slug]/waybackLiveActions";
+import { jobResponse, ops, optBool, optString, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { url, slug?, dryRun? } -> { ok: true, jobId } | (dryRun) { ok: true, dryRun: true, wouldAsk, … }
+//
+// SAVE PAGE NOW (release 37 S5, controller/savePageNow.ts): the Wayback
+// Machine asked to capture `url` now, with archive.org's S3 keys (the
+// editor's ARCHIVE_ORG_S3_ACCESS + ARCHIVE_ORG_S3_SECRET, else the mode-600
+// file settings `archiveOrg.s3KeyFile` names) — a `save-page-now` job on the
+// archive.org queue that asks for the capture (the page alone), polls its
+// status, and, with `slug` (a Wayback pages channel), starts an import-page
+// job of the capture. The log ends with `@@save-page-now {ok, url, slug?,
+// spnJobId, captureTs, originalUrl, waybackUrl, importJobId?, importError?,
+// polls, error?}`. `dryRun` answers what it would ask and starts nothing.
+// Every refusal is the controller's sentence (no keys among them); the keys
+// are never echoed.
+export async function POST(request: Request) {
+ return ops(request, ["url", "slug", "dryRun"], async (body) => {
+ const url = reqString(body, "url");
+ const slug = optString(body, "slug")?.trim() || undefined;
+ if (optBool(body, "dryRun") === true) {
+ const r = await savePageNowDryRunAction(url, slug);
+ if (!r.ok) return NextResponse.json({ ok: false, error: r.error }, { status: 400 });
+ return NextResponse.json(r);
+ }
+ return jobResponse(await savePageNowAction(url, slug, "ops"));
+ });
+}
diff --git a/editor/app/api/ops/settings/route.ts b/editor/app/api/ops/settings/route.ts
@@ -5,6 +5,7 @@ import { OpsInputError, ops, opsFail } from "../_lib";
import { readRoute, redactSecrets } from "../_read";
import { settingsPatchProblem } from "./patch";
import { looksLikeApiKey } from "yt-dlp-transcript-common/lib/generationSettings";
+import { looksLikeS3Key } from "yt-dlp-transcript-common/lib/archiveOrgTorrent";
export const dynamic = "force-dynamic";
@@ -65,6 +66,14 @@ export async function POST(request: Request) {
"generation.apiKeyFile is the PATH of the mode-600 file that holds the key, and the value sent looks like a key itself — refused, not stored",
);
}
+ // archive.org's S3 keys are never a setting either (release 37 S5): the
+ // same refusal for archiveOrg.s3KeyFile, without the value.
+ const s3KeyFile = (patch as { archiveOrg?: { s3KeyFile?: unknown } }).archiveOrg?.s3KeyFile;
+ if (typeof s3KeyFile === "string" && looksLikeS3Key(s3KeyFile)) {
+ throw new OpsInputError(
+ "archiveOrg.s3KeyFile is the PATH of the mode-600 file that holds archive.org's S3 keys, and the value sent is not a path — refused, not stored",
+ );
+ }
const current = getSettings();
const problem = settingsPatchProblem(
patch as Record<string, unknown>,
diff --git a/editor/app/channels/[slug]/components/WaybackLivePanel.tsx b/editor/app/channels/[slug]/components/WaybackLivePanel.tsx
@@ -0,0 +1,185 @@
+"use client";
+
+// A WAYBACK PAGES channel, live (release 37 S5): whether each record's
+// ORIGINAL is still up (check-post-availability, asked at the original's own
+// site — never the Wayback Machine), the records whose original is gone (the
+// Wayback copy is then the only copy), and Save Page Now — "Ask the Wayback
+// Machine to capture this now" — for a page still up, its capture imported
+// here. Save Page Now is off without archive.org's S3 keys, and says why.
+
+import { useState, useTransition } from "react";
+import Link from "next/link";
+import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
+import { cancelJobAction } from "../../../jobs/actions";
+import { checkPostAvailabilityAction } from "../socialActions";
+import { savePageNowAction } from "../waybackLiveActions";
+
+export type WaybackLiveRow = {
+ id: string;
+ title: string;
+ originalUrl: string;
+ waybackUrl: string;
+ // posts-availability.json's verdict on the original, when checked.
+ availability?: string;
+ reason?: string;
+ checkedAt?: string;
+};
+
+export type WaybackLiveState = {
+ // Distinct original URLs, and how many were checked / are gone.
+ originals: number;
+ checked: number;
+ gone: number;
+ unavailable: number;
+ // Records whose original is gone (deleted or unavailable), newest first.
+ goneRows: WaybackLiveRow[];
+ // Records whose original answered, one per original URL (Save Page Now).
+ liveRows: WaybackLiveRow[];
+ spn: { on: true } | { on: false; reason: string };
+};
+
+function CaptureNow({ slug, url, disabled }: { slug: string; url: string; disabled: boolean }) {
+ const [pending, start] = useTransition();
+ const [job, setJob] = useState<string | null>(null);
+ const [err, setErr] = useState<string | null>(null);
+ return (
+ <span className="inline-flex items-center gap-2">
+ <button
+ type="button"
+ disabled={disabled || pending}
+ aria-label={`capture ${url} now`}
+ onClick={() =>
+ start(async () => {
+ setErr(null);
+ const res = await savePageNowAction(url, slug);
+ if (res.ok) {
+ void res.stream.cancel();
+ setJob(res.jobId);
+ } else {
+ setErr(res.error);
+ }
+ })
+ }
+ className="rounded border border-border px-2 py-0.5 text-xs hover:bg-muted disabled:opacity-50"
+ >
+ {pending ? "Asking…" : "Capture now"}
+ </button>
+ {job && (
+ <Link href={`/jobs/${job}`} className="text-xs underline underline-offset-2">
+ job
+ </Link>
+ )}
+ {err && (
+ <span role="alert" className="text-xs text-destructive">
+ {err}
+ </span>
+ )}
+ </span>
+ );
+}
+
+export function WaybackLivePanel({ slug, state }: { slug: string; state: WaybackLiveState }) {
+ const [url, setUrl] = useState("");
+ const [checkJob, setCheckJob] = useState<string | null>(null);
+ const [spnJob, setSpnJob] = useState<string | null>(null);
+ const input = "rounded border border-border bg-card px-2 py-1 text-sm font-mono";
+ const spnOff = !state.spn.on;
+ return (
+ <div className="flex flex-col gap-4">
+ <section aria-label="originals" className="flex flex-col gap-2 rounded-lg border border-border p-3">
+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
+ <h4 className="text-sm font-semibold">Originals</h4>
+ <span role="status" aria-label="originals checked" className="text-sm text-muted-foreground">
+ {state.checked} of {state.originals} original URL{state.originals === 1 ? "" : "s"} checked · {state.gone} gone
+ {state.unavailable > 0 ? ` · ${state.unavailable} unavailable` : ""}
+ </span>
+ </div>
+ <StreamActionLog
+ trigger={() => checkPostAvailabilityAction(slug)}
+ cancelAction={cancelJobAction}
+ buttonLabel="Check originals"
+ runningLabel="Checking…"
+ label={`Check the originals of ${slug}`}
+ disabled={state.originals === 0}
+ onSettled={(started, out) => setCheckJob(started ? out.jobId : null)}
+ />
+ {checkJob && (
+ <Link href={`/jobs/${checkJob}`} className="text-xs underline underline-offset-2">
+ Open the check job
+ </Link>
+ )}
+ {state.goneRows.length > 0 && (
+ <table aria-label="originals gone" className="mt-1 w-full text-sm">
+ <thead>
+ <tr className="text-left text-xs text-muted-foreground">
+ <th className="py-1 pr-2 font-medium">Page</th>
+ <th className="py-1 pr-2 font-medium">Original</th>
+ <th className="py-1 font-medium">Wayback copy</th>
+ </tr>
+ </thead>
+ <tbody>
+ {state.goneRows.map((r) => (
+ <tr key={r.id} data-original-gone={r.id} className="border-t border-border align-top">
+ <td className="py-1 pr-2">{r.title}</td>
+ <td className="py-1 pr-2 text-xs">
+ <a href={r.originalUrl} target="_blank" rel="noreferrer" className="font-mono underline underline-offset-2">
+ {r.availability === "deleted" ? "gone" : "unavailable"}
+ </a>
+ {r.reason && <span className="text-muted-foreground"> · {r.reason}</span>}
+ </td>
+ <td className="py-1 text-xs">
+ <a href={r.waybackUrl} target="_blank" rel="noreferrer" className="underline underline-offset-2">
+ the only copy
+ </a>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </section>
+ <section aria-label="save page now" className="flex flex-col gap-2 rounded-lg border border-border p-3">
+ <h4 className="text-sm font-semibold">Save Page Now</h4>
+ {spnOff && (
+ <p role="status" aria-label="save page now off" className="text-xs text-muted-foreground">
+ {state.spn.on ? "" : state.spn.reason}
+ </p>
+ )}
+ <input
+ value={url}
+ onChange={(e) => setUrl(e.target.value)}
+ aria-label="page to capture"
+ placeholder="https://…"
+ disabled={spnOff}
+ className={`${input} w-[36rem] max-w-full`}
+ />
+ <StreamActionLog
+ trigger={() => savePageNowAction(url.trim(), slug)}
+ cancelAction={cancelJobAction}
+ buttonLabel="Ask the Wayback Machine to capture this now"
+ runningLabel="Capturing…"
+ label={`Save Page Now into ${slug}`}
+ disabled={spnOff || !url.trim()}
+ onSettled={(started, out) => setSpnJob(started ? out.jobId : null)}
+ />
+ {spnJob && (
+ <Link href={`/jobs/${spnJob}`} aria-label="save page now job" className="text-xs underline underline-offset-2">
+ Open the capture job
+ </Link>
+ )}
+ {state.liveRows.length > 0 && (
+ <ul aria-label="originals still up" className="mt-1 flex flex-col gap-1 text-sm">
+ {state.liveRows.map((r) => (
+ <li key={r.id} data-original-live={r.id} className="flex flex-wrap items-center gap-2">
+ <a href={r.originalUrl} target="_blank" rel="noreferrer" className="font-mono text-xs underline underline-offset-2">
+ {r.originalUrl}
+ </a>
+ <CaptureNow slug={slug} url={r.originalUrl} disabled={spnOff} />
+ </li>
+ ))}
+ </ul>
+ )}
+ </section>
+ </div>
+ );
+}
diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx
@@ -22,6 +22,9 @@ import { readForumSessionStatus } from "yt-dlp-transcript-common/social/forumSes
import { parseXenforoThreadUrl } from "yt-dlp-transcript-common/social/xenforoParse";
import { SocialChannelPanel } from "./components/SocialChannelPanel";
import { WaybackPagesPanel } from "./components/WaybackPagesPanel";
+import { WaybackLivePanel } from "./components/WaybackLivePanel";
+import { waybackLiveState } from "./waybackLiveState";
+import { savePageNowAvailability } from "yt-dlp-transcript-common/controller/savePageNow";
import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config";
import { countStoredCaptures } from "yt-dlp-transcript-common/lib/waybackPages/store-server";
import { waybackCaptureDate } from "yt-dlp-transcript-common/lib/wayback";
@@ -186,11 +189,11 @@ export default async function ChannelDetailPage({
: undefined;
// A WAYBACK PAGES channel (release 37): its captures, its scope, Import a
// capture — no fetcher, nothing to fetch.
+ const pageRecords = isWaybackPagesChannel(config) ? (await readAllPosts(channelRoot)).filter((p) => p.page) : [];
const wayback = isWaybackPagesChannel(config)
? {
captureCount: await countStoredCaptures(channelRoot),
- recent: (await readAllPosts(channelRoot))
- .filter((p) => p.page)
+ recent: pageRecords
.sort((a, b) => b.page!.captureTs.padEnd(14, "0").localeCompare(a.page!.captureTs.padEnd(14, "0")))
.slice(0, 20)
.map((p) => ({
@@ -209,6 +212,7 @@ export default async function ChannelDetailPage({
<div className="flex flex-col gap-6">
<RunningJobsList jobs={socialRunningJobs} hideChannelSlug />
{wayback ? (
+ <>
<WaybackPagesPanel
slug={slug}
state={{
@@ -218,6 +222,12 @@ export default async function ChannelDetailPage({
recent: wayback.recent,
}}
/>
+ {/* Release 37 S5: is each original still up; Save Page Now. */}
+ <WaybackLivePanel
+ slug={slug}
+ state={waybackLiveState(pageRecords, postAvailability, savePageNowAvailability())}
+ />
+ </>
) : (
<SocialChannelPanel
slug={slug}
diff --git a/editor/app/channels/[slug]/waybackLiveActions.ts b/editor/app/channels/[slug]/waybackLiveActions.ts
@@ -0,0 +1,102 @@
+"use server";
+
+// WAYBACK PAGES, LIVE (release 37 S5): Save Page Now — "Ask the Wayback
+// Machine to capture this now" (controller/savePageNow.ts) — and find-copy's
+// page mode, a copy of every gone page a report cites (publish/findCopyPages.ts).
+// Both on the archive.org queue; the controllers' refusals in their own
+// sentences, before a job exists. The original-URL availability check is the
+// posts' own action (socialActions.ts checkPostAvailabilityAction).
+
+import { safeRevalidate } from "../../lib/safeRevalidate";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSite, isValidSiteId, listSiteIds } from "yt-dlp-transcript-common/lib/site";
+import { articlesWorkHost, siteReportHost, type ReportHost } from "yt-dlp-transcript-common/publish/reportHost";
+import { runManagedFunction, type StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
+import {
+ queueSavePageNow,
+ savePageNow,
+ savePageNowAvailability,
+ type SavePageNowAvailability,
+ type SavePageNowResult,
+} from "yt-dlp-transcript-common/controller/savePageNow";
+import { WAYBACK_PAGES_QUEUE } from "yt-dlp-transcript-common/controller/importPage";
+import { findPageCopies } from "yt-dlp-transcript-common/publish/findCopyPages";
+import { FIND_COPY_RESULT_MARKER } from "yt-dlp-transcript-common/publish/findCopy";
+import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
+import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config";
+
+export async function savePageNowAction(url: string, slug?: string, requestedBy?: string): Promise<StreamActionResult> {
+ return queueSavePageNow({
+ paths: getPaths(),
+ url: url.trim(),
+ ...(slug?.trim() ? { slug: slug.trim() } : {}),
+ ...(requestedBy ? { requestedBy } : {}),
+ onDone: () => {
+ if (slug) safeRevalidate([`/channels/${slug}`]);
+ },
+ });
+}
+
+// What a capture WOULD ask, answered now (no job, no request).
+export async function savePageNowDryRunAction(url: string, slug?: string): Promise<SavePageNowResult> {
+ return savePageNow({ paths: getPaths(), url: url.trim(), ...(slug?.trim() ? { slug: slug.trim() } : {}), dryRun: true });
+}
+
+// Whether the button is on, and why not (the keys' presence, never their
+// value).
+export async function savePageNowAvailabilityAction(): Promise<SavePageNowAvailability> {
+ return savePageNowAvailability();
+}
+
+// FIND-COPY, PAGE MODE: `{article} | {articles: true} | {siteId}`, `channel?`,
+// `max?`, `dryRun?` — one find-copy job on the archive.org queue. Its log ends
+// with `@@find-copy {host, dryRun, max, pages, posts, items, left, stopped?}`.
+export async function findPageCopiesAction(req: {
+ article?: string;
+ siteId?: string;
+ channel?: string;
+ max?: number;
+ dryRun?: boolean;
+}): Promise<StreamActionResult> {
+ const paths = getPaths();
+ let host: ReportHost;
+ try {
+ if (req.article) {
+ host = await articlesWorkHost(paths, [req.article], { only: true });
+ } else if (req.siteId) {
+ if (!isValidSiteId(req.siteId)) return { ok: false, error: `"${req.siteId}" is not a valid site id` };
+ if (!listSiteIds(paths).includes(req.siteId)) return { ok: false, error: `No site "${req.siteId}"` };
+ host = siteReportHost(paths, getSite(req.siteId, paths));
+ } else {
+ host = await articlesWorkHost(paths);
+ }
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+ if (req.channel) {
+ const config = await readChannelConfig(paths, req.channel);
+ if (!config) return { ok: false, error: `No such channel: ${req.channel}` };
+ if (!isWaybackPagesChannel(config)) return { ok: false, error: `${req.channel} is not a Wayback pages channel` };
+ }
+ return runManagedFunction({
+ kind: "find-copy",
+ queueKey: WAYBACK_PAGES_QUEUE,
+ paths,
+ ...(req.channel ? { channelSlug: req.channel } : {}),
+ fn: async (onLog, signal) => {
+ const r = await findPageCopies({
+ paths,
+ host,
+ ...(req.channel ? { channel: req.channel } : {}),
+ ...(req.max !== undefined ? { max: req.max } : {}),
+ dryRun: req.dryRun === true,
+ signal,
+ onLog,
+ });
+ onLog(`${FIND_COPY_RESULT_MARKER}${JSON.stringify(r)}`);
+ const touched = new Set(r.items.filter((i) => i.outcome === "imported" && i.channel).map((i) => `/channels/${i.channel}`));
+ if (touched.size > 0) safeRevalidate([...touched]);
+ if (signal.aborted) throw new Error("cancelled");
+ },
+ });
+}
diff --git a/editor/app/channels/[slug]/waybackLiveState.ts b/editor/app/channels/[slug]/waybackLiveState.ts
@@ -0,0 +1,51 @@
+// The Wayback pages channel's live panel's state (release 37 S5,
+// components/WaybackLivePanel.tsx), from its page records and the
+// availability sidecar: one row per original URL.
+
+import type { Post, PostAvailabilityMap } from "yt-dlp-transcript-common/lib/posts";
+import { groupByOriginalUrl } from "yt-dlp-transcript-common/lib/waybackPages/liveness";
+import type { WaybackLiveRow, WaybackLiveState } from "./components/WaybackLivePanel";
+
+const ROWS = 20;
+
+export function waybackLiveState(
+ records: ReadonlyArray<Post>,
+ availability: PostAvailabilityMap,
+ spn: WaybackLiveState["spn"],
+): WaybackLiveState {
+ const groups = groupByOriginalUrl(records);
+ const byId = new Map(records.map((r) => [r.id, r]));
+ let checked = 0;
+ let gone = 0;
+ let unavailable = 0;
+ const goneRows: WaybackLiveRow[] = [];
+ const liveRows: WaybackLiveRow[] = [];
+ for (const [url, ids] of groups) {
+ // The newest capture of the page stands for it.
+ const newest = ids
+ .map((id) => byId.get(id)!)
+ .sort((a, b) => b.page!.captureTs.padEnd(14, "0").localeCompare(a.page!.captureTs.padEnd(14, "0")))[0]!;
+ const av = ids.map((id) => availability[id]).find(Boolean);
+ const row: WaybackLiveRow = {
+ id: newest.id,
+ title: newest.page!.title || newest.text.split("\n")[0]!.slice(0, 120) || url,
+ originalUrl: url,
+ waybackUrl: newest.page!.waybackUrl,
+ ...(av ? { availability: av.availability, checkedAt: av.checkedAt, ...(av.reason ? { reason: av.reason } : {}) } : {}),
+ };
+ if (av) checked++;
+ if (av?.availability === "deleted") gone++;
+ if (av?.availability === "account_unavailable") unavailable++;
+ if (av && (av.availability === "deleted" || av.availability === "account_unavailable")) goneRows.push(row);
+ else if (av?.availability === "available") liveRows.push(row);
+ }
+ return {
+ originals: groups.size,
+ checked,
+ gone,
+ unavailable,
+ goneRows: goneRows.slice(0, ROWS),
+ liveRows: liveRows.slice(0, ROWS),
+ spn,
+ };
+}
diff --git a/editor/e2e/wayback-live.spec.ts b/editor/e2e/wayback-live.spec.ts
@@ -0,0 +1,146 @@
+// Wayback pages, live (release 37 S5), over the fake Wayback Machine
+// (common/testing/web/fakeWayback.mjs, its Save Page Now block) named to the
+// test server through E2E_WAYBACK_ORIGIN_FILE (e2e/servers.ts). Neither the
+// real web.archive.org nor any original site is contacted: the originals'
+// verdicts are written to posts-availability.json as the check would.
+//
+// A Wayback pages channel's page shows Originals (checked / gone, the gone
+// table) and Save Page Now: off with its sentence while no archive.org keys
+// are configured; with keys (a mode-600 file the settings name), "Ask the
+// Wayback Machine to capture this now" runs a save-page-now job whose capture
+// is imported into the channel. The ops door answers a dry run.
+
+import { test, expect, type APIRequestContext } from "@playwright/test";
+import { chmod, mkdir, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import {
+ startFakeWayback,
+ FAKE_SPN_ACCESS,
+ FAKE_SPN_SECRET,
+ PAGE_ARTICLE_TS,
+ PAGE_ARTICLE_URL,
+ SPN_CAPTURE_TS,
+} from "yt-dlp-transcript-common/testing/web/fakeWayback.mjs";
+import { pageRecordId } from "yt-dlp-transcript-common/lib/waybackPages/types";
+import { baseUrl } from "./baseUrl";
+import { resetData, resolvePath, testPaths, writeSettings } from "./helpers";
+import { waybackOriginFile } from "./servers";
+
+const AUTH = { authorization: "Bearer test-worker-token" };
+const SLUG = "old-blog-live";
+const LIVE = "https://blog.example/still-up.html";
+
+async function waitForJob(request: APIRequestContext, jobId: string): Promise<{ status: string; tail: string[] }> {
+ let last = { status: "", tail: [] as string[] };
+ await expect
+ .poll(
+ async () => {
+ const res = await request.get(`${baseUrl}/api/ops/job/${jobId}?tail=40`, { headers: AUTH });
+ const body = (await res.json()) as { job: { status: string }; tail?: string[] };
+ last = { status: body.job.status, tail: body.tail ?? [] };
+ return last.status;
+ },
+ { timeout: 90_000, intervals: [1_000] },
+ )
+ .toMatch(/^(done|failed|cancelled)$/);
+ return last;
+}
+
+test("Originals and Save Page Now on a Wayback pages channel: off without keys, then a capture imported", async ({ page, request }) => {
+ test.setTimeout(180_000);
+ await resetData("empty");
+ const root = resolvePath(testPaths().transcriptsDir);
+ const keyFile = path.join(root, "spn-keys.env");
+ await rm(keyFile, { force: true });
+ await writeSettings({ minFreeDiskGB: 0, archiveOrg: { s3KeyFile: keyFile } });
+ const channelRoot = path.join(root, "channels", SLUG);
+ await mkdir(channelRoot, { recursive: true });
+ await writeFile(
+ path.join(channelRoot, "config.json"),
+ JSON.stringify({
+ name: "Old blog (live)",
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "webpage",
+ socialHandle: "blog.example",
+ url: "https://web.archive.org/web/*/blog.example/*",
+ wayback: { targets: [{ url: "blog.example/", match: "prefix" }] },
+ }),
+ );
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+
+ const wb = await startFakeWayback();
+ const originFile = waybackOriginFile(root);
+ await writeFile(originFile, wb.base);
+ try {
+ // One record, imported from the fake.
+ const imp = await request.post(`${baseUrl}/api/ops/import-page`, {
+ headers: AUTH,
+ data: { slug: SLUG, url: `https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}` },
+ });
+ const impBody = (await imp.json()) as { jobId?: string; error?: string };
+ expect(imp.status(), impBody.error).toBe(200);
+ expect((await waitForJob(request, impBody.jobId!)).status).toBe("done");
+ const articleId = pageRecordId(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL);
+
+ await page.goto(`/channels/${SLUG}`);
+ const originals = page.getByRole("region", { name: "originals" });
+ await expect(originals.getByLabel("originals checked")).toHaveText("0 of 1 original URL checked · 0 gone");
+ await expect(originals.getByRole("button", { name: "Check originals" })).toBeEnabled();
+ // No keys: the button is off and says why; nothing was asked of SPN.
+ const spn = page.getByRole("region", { name: "save page now" });
+ await expect(spn.getByLabel("save page now off")).toContainText("Save Page Now needs archive.org S3 keys");
+ await expect(spn.getByRole("button", { name: "Ask the Wayback Machine to capture this now" })).toBeDisabled();
+ const refused = await request.post(`${baseUrl}/api/ops/save-page-now`, { headers: AUTH, data: { url: LIVE, slug: SLUG } });
+ expect(refused.status()).toBe(400);
+ expect(((await refused.json()) as { error: string }).error).toContain("needs archive.org S3 keys");
+ expect(wb.requests.filter((r) => r.path.startsWith("/save"))).toEqual([]);
+
+ // The original's verdict, as the check writes it: gone — the Wayback copy is the only copy.
+ await writeFile(
+ path.join(channelRoot, "posts-availability.json"),
+ JSON.stringify({ [articleId]: { availability: "deleted", checkedAt: "2026-10-20T10:00:00.000Z", status: 404, reason: "HTTP 404" } }),
+ );
+ // The keys, in a mode-600 file the settings name.
+ await writeFile(keyFile, `ARCHIVE_ORG_S3_ACCESS=${FAKE_SPN_ACCESS}\nARCHIVE_ORG_S3_SECRET=${FAKE_SPN_SECRET}\n`);
+ await chmod(keyFile, 0o600);
+ await page.reload();
+ await expect(originals.getByLabel("originals checked")).toHaveText("1 of 1 original URL checked · 1 gone");
+ const goneRow = page.locator(`[data-original-gone="${articleId}"]`);
+ await expect(goneRow.getByRole("link", { name: "the only copy" })).toHaveAttribute(
+ "href",
+ `https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}`,
+ );
+ await expect(goneRow).toContainText("HTTP 404");
+ await expect(spn.getByLabel("save page now off")).toHaveCount(0);
+
+ // A dry run over ops asks nothing.
+ const dry = await request.post(`${baseUrl}/api/ops/save-page-now`, { headers: AUTH, data: { url: LIVE, slug: SLUG, dryRun: true } });
+ const dryBody = (await dry.json()) as { ok: boolean; wouldAsk?: string };
+ expect(dryBody.ok).toBe(true);
+ expect(dryBody.wouldAsk).toContain(`then import the capture into ${SLUG}`);
+ expect(wb.requests.filter((r) => r.path.startsWith("/save"))).toEqual([]);
+
+ // Ask the Wayback Machine to capture the live page now: the capture, then its import.
+ await spn.getByLabel("page to capture").fill(LIVE);
+ await spn.getByRole("button", { name: "Ask the Wayback Machine to capture this now" }).click();
+ const log = page.getByRole("log", { name: `Save Page Now into ${SLUG} output` });
+ await expect(log).toContainText('"ok":true', { timeout: 90_000 });
+ const text = (await log.textContent()) ?? "";
+ expect(text).toContain(`"captureTs":"${SPN_CAPTURE_TS}"`);
+ expect(text).not.toContain(FAKE_SPN_SECRET);
+ const importJobId = /"importJobId":"([^"]+)"/.exec(text)?.[1];
+ expect(importJobId, text).toBeTruthy();
+ expect((await waitForJob(request, importJobId!)).status).toBe("done");
+ expect(wb.spnForms).toEqual([{ url: LIVE, capture_outlinks: "0" }]);
+
+ await page.reload();
+ await expect(page.getByRole("region", { name: "Wayback pages" }).getByLabel("pages held")).toHaveText("2 records from 2 captures");
+ await expect(page.locator(`[data-page-record="${pageRecordId(SPN_CAPTURE_TS, LIVE)}"]`)).toBeVisible();
+ await expect(originals.getByLabel("originals checked")).toHaveText("1 of 2 original URLs checked · 1 gone");
+ } finally {
+ await rm(originFile, { force: true });
+ await rm(keyFile, { force: true });
+ await wb.close();
+ }
+});