commit 6bdfe3294eac7ded24ad63bae89609b79975cbf2
parent ac25c2ddf8025f5fe64311c6a02477913f29dc34
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 16 Oct 2026 16:53:18 -0400
editor: buttons for find-copy's scope mode, the audio audit, and the video's media operations
- "Find copies of gone videos" on the channel's Download stage and on the
site page: which gone videos, at most N lookups, try failed copies again;
Preview (a dry run: the candidate list with the copy each would use), then
"Find and fetch copies" armed by a preview of the same settings, the
find-copy and fetch-copies jobs linked.
- "Audit audio" on the Download stage: scope, at most N files, decode again;
the report's tally of the verdicts (clean, damaged, undecodable, out of
date) and when it was last checked.
- The video page: the audit's verdict on the held audio (decoded seconds,
gaps, out of date when the file changed); "Media tools": attach this
video's file from a local archive (preview, then attach), make a playable
copy, and the channel's Wayback / archive.org records refreshed (preview,
then refresh; a Wayback record's title and date with it).
- StreamActionLog's onSettled also hands the run's log and job id over, so a
caller can read a dry run's result marker (app/lib/resultMarker.ts).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
11 files changed, 752 insertions(+), 4 deletions(-)
diff --git a/common/components/StreamActionLog.tsx b/common/components/StreamActionLog.tsx
@@ -36,7 +36,11 @@ type Props = {
* flag there lets an operator press Preview and then Evict before a single
* count has appeared — which is the whole thing the gate exists to stop.
*/
- onSettled?: (started: boolean) => void;
+ //
+ // `out` (release 32) is what the run left: its whole log and its job id — so
+ // a caller can read a result marker off the log's last line (a dry run's
+ // candidate list) and link the job.
+ onSettled?: (started: boolean, out: { log: string; jobId: string | null }) => void;
};
type StatusPoll = {
@@ -147,6 +151,8 @@ export function StreamActionLog({
stickToBottomRef.current = true;
setRunning(true);
let started = false;
+ let full = "";
+ let startedJob: string | null = null;
try {
const result = await trigger();
if (!result.ok) {
@@ -155,18 +161,22 @@ export function StreamActionLog({
return;
}
started = true;
+ startedJob = result.jobId;
setJobId(result.jobId);
const reader = result.stream.getReader();
while (true) {
const { value, done } = await reader.read();
if (done) break;
- if (value) setLog((prev) => prev + value);
+ if (value) {
+ full += value;
+ setLog((prev) => prev + value);
+ }
}
} catch (e) {
setError((e as Error).message);
} finally {
setRunning(false);
- onSettled?.(started);
+ onSettled?.(started, { log: full, jobId: startedJob });
// A run that actually started (success, mid-stream error, or cancel)
// may have mutated server-derived data: a saved shard config, channel
// counts, bucket lists, failed-transcription lists. Re-fetch the server
diff --git a/editor/app/channels/[slug]/audioAuditActions.ts b/editor/app/channels/[slug]/audioAuditActions.ts
@@ -0,0 +1,30 @@
+"use server";
+
+// "Audit audio" on the channel's Download stage (release 32): the
+// `audio-audit` job for this channel, through the same door as
+// `pnpm ops audio-audit` (controller/audioAudit.ts). Its refusals — a bad
+// body, the channel's media unreachable — come back as the button's error.
+//
+// NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use server" file).
+
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { enqueueAudioAudit } from "yt-dlp-transcript-common/controller/audioAudit";
+import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
+
+export async function audioAuditAction(
+ slug: string,
+ opts: { scope: "untranscribed" | "all"; max?: number; force?: boolean },
+): Promise<StreamActionResult> {
+ let out;
+ try {
+ out = await enqueueAudioAudit(
+ { slug, scope: opts.scope, ...(opts.max !== undefined ? { max: opts.max } : {}), ...(opts.force ? { force: true } : {}) },
+ { paths: getPaths() },
+ );
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+ const started = out.started[0];
+ if (started) return started.result;
+ return { ok: false, error: out.refused.map((r) => r.error).join("; ") || "No audit started" };
+}
diff --git a/editor/app/channels/[slug]/components/stages/DownloadStage.tsx b/editor/app/channels/[slug]/components/stages/DownloadStage.tsx
@@ -2,7 +2,9 @@
import { useState } from "react";
import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
-import type { ExcludedFromDownload } from "yt-dlp-transcript-common/controller/channelSnapshot";
+import type { AudioIntegrityTally, ExcludedFromDownload } from "yt-dlp-transcript-common/controller/channelSnapshot";
+import { FindCopiesControl } from "../../../../components/FindCopiesControl";
+import { audioAuditAction } from "../../audioAuditActions";
import { QueueControl } from "../../../../components/QueueControl";
import {
ShardControl,
@@ -33,6 +35,9 @@ type Props = {
corruptFullSourceIds: string[];
// Release 31 lane A: held audio the audio audit found damaged.
corruptHeldAudioIds: string[];
+ // Release 32: the audio audit's verdicts over the channel (the snapshot's
+ // tally), or null when the report predates it.
+ audioIntegrity: AudioIntegrityTally | null;
missingShard: ShardConfigSummary | null;
};
@@ -48,6 +53,7 @@ export function DownloadStage({
needsCookiesIds,
corruptFullSourceIds,
corruptHeldAudioIds,
+ audioIntegrity,
missingShard,
}: Props) {
const [downloadQueue, setDownloadQueue] = useState(defaultQueueKey);
@@ -78,6 +84,7 @@ export function DownloadStage({
slug={slug}
excluded={excludedFromDownload}
/>
+ <FindCopiesControl slug={slug} />
<div className="flex flex-col gap-2">
<Heading
title="Download from playlist"
@@ -247,6 +254,80 @@ export function DownloadStage({
defaultQueueKey={defaultQueueKey}
existingQueues={existingQueues}
/>
+ <AudioAuditControl slug={slug} tally={audioIntegrity} />
+ </div>
+ );
+}
+
+// "Audit audio" (release 32; the audit is release 31 lane A's): decode the
+// audio the channel holds and write each file's verdict beside it in
+// audio-integrity.json; damaged files land in "Damaged held audio" above.
+// The line is the report's tally of those verdicts.
+function AudioAuditControl({
+ slug,
+ tally,
+}: {
+ slug: string;
+ tally: AudioIntegrityTally | null;
+}) {
+ const [scope, setScope] = useState<"untranscribed" | "all">("untranscribed");
+ const [maxText, setMaxText] = useState("");
+ const [force, setForce] = useState(false);
+ const max = Number.parseInt(maxText, 10);
+ const audited = tally ? tally.clean + tally.damaged + tally.undecodable + tally.stale : 0;
+ return (
+ <div aria-label="audit audio" className="flex flex-col gap-2 rounded border border-border p-3">
+ <h4 className="text-sm font-semibold">Audit audio</h4>
+ <p aria-label="audio audit tally" className="text-xs text-muted-foreground">
+ {audited === 0 || !tally
+ ? "Not audited."
+ : `${tally.clean} clean, ${tally.damaged} damaged, ${tally.undecodable} undecodable` +
+ (tally.stale ? `, ${tally.stale} out of date (the file changed)` : "") +
+ (tally.lastCheckedAt ? ` · last checked ${tally.lastCheckedAt.slice(0, 16).replace("T", " ")}` : "")}
+ </p>
+ <div className="flex flex-wrap items-center gap-3 text-sm">
+ <label className="flex items-center gap-2">
+ <span className="text-muted-foreground">Files</span>
+ <select
+ value={scope}
+ onChange={(e) => setScope(e.target.value as "untranscribed" | "all")}
+ aria-label="audit scope"
+ className="rounded border border-border bg-card px-2 py-1 text-sm"
+ >
+ <option value="untranscribed">videos with no transcript</option>
+ <option value="all">every video holding audio</option>
+ </select>
+ </label>
+ <label className="flex items-center gap-2">
+ <span className="text-muted-foreground">At most</span>
+ <input
+ type="number"
+ min={1}
+ value={maxText}
+ onChange={(e) => setMaxText(e.target.value)}
+ placeholder="all"
+ aria-label="audit at most files"
+ className="rounded border border-border bg-card px-2 py-1 text-sm w-20"
+ />
+ </label>
+ <label className="flex items-center gap-2">
+ <input type="checkbox" checked={force} onChange={(e) => setForce(e.target.checked)} aria-label="decode again files already audited" />
+ Decode again files already audited
+ </label>
+ </div>
+ <StreamActionLog
+ trigger={() =>
+ audioAuditAction(slug, {
+ scope,
+ ...(Number.isInteger(max) && max > 0 ? { max } : {}),
+ ...(force ? { force: true } : {}),
+ })
+ }
+ cancelAction={cancelJobAction}
+ buttonLabel="Audit audio"
+ runningLabel="Auditing…"
+ label={`Audit audio of ${slug}`}
+ />
</div>
);
}
diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx
@@ -514,6 +514,7 @@ export default async function ChannelDetailPage({
needsCookiesIds={buckets.needsCookies}
corruptFullSourceIds={buckets.corruptFullSource}
corruptHeldAudioIds={buckets.corruptHeldAudio}
+ audioIntegrity={snapshot.audioIntegrity ?? null}
missingShard={await shard("download-missing")}
/>
);
diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoMediaTools.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoMediaTools.tsx
@@ -0,0 +1,207 @@
+"use client";
+
+import Link from "next/link";
+import { useEffect, useState, useTransition } from "react";
+import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
+import { Button } from "yt-dlp-transcript-common/components/ui/button";
+import { cancelJobAction } from "../../../../../jobs/actions";
+import {
+ archiveOrgRefreshAction,
+ attachVideoMediaAction,
+ playableVideoAction,
+ waybackRefreshAction,
+ type RecordsRefreshResult,
+} from "../mediaToolsActions";
+
+// "Media tools" (release 32): the video-level operations that were CLI- or
+// ops-only — attach this video's file from a local archive, make a playable
+// copy of its saved container, and bring the channel's Wayback or archive.org
+// records up to their rules. Every one previews first where it writes.
+
+const input = "rounded border border-border bg-card px-2 py-1 text-sm";
+
+export function VideoMediaTools({
+ slug,
+ videoId,
+ saved,
+ wayback,
+ archiveOrg,
+}: {
+ slug: string;
+ videoId: string;
+ // A source container is in the saved-video store.
+ saved: boolean;
+ // A Wayback Machine copy (wayback.json, or a web.archive.org page URL).
+ wayback: boolean;
+ // An archive.org file record.
+ archiveOrg: boolean;
+}) {
+ return (
+ <details aria-label="media tools" className="rounded-lg border border-border bg-card p-3">
+ <summary className="cursor-pointer text-sm font-semibold">Media tools</summary>
+ <div className="mt-3 flex flex-col gap-4">
+ <AttachFromArchive slug={slug} videoId={videoId} saved={saved} />
+ {saved && (
+ <div className="flex flex-col gap-2">
+ <h4 className="text-sm font-semibold">Playable copy</h4>
+ <StreamActionLog
+ trigger={() => playableVideoAction(slug, videoId)}
+ cancelAction={cancelJobAction}
+ buttonLabel="Make playable copy"
+ runningLabel="Remuxing…"
+ label={`Make playable copy of ${videoId}`}
+ />
+ </div>
+ )}
+ {wayback && (
+ <RecordsRefresh
+ title="Wayback records"
+ what="Wayback"
+ slug={slug}
+ videoId={videoId}
+ withTitle
+ run={(dryRun, title) => waybackRefreshAction(slug, { dryRun, ...(title ? { title } : {}) })}
+ />
+ )}
+ {archiveOrg && (
+ <RecordsRefresh
+ title="archive.org records"
+ what="archive.org"
+ slug={slug}
+ videoId={videoId}
+ run={(dryRun) => archiveOrgRefreshAction(slug, { dryRun })}
+ />
+ )}
+ </div>
+ </details>
+ );
+}
+
+function AttachFromArchive({ slug, videoId, saved }: { slug: string; videoId: string; saved: boolean }) {
+ const [source, setSource] = useState("");
+ const [file, setFile] = useState("");
+ const [replace, setReplace] = useState(false);
+ const key = `${source}\u0000${file}\u0000${replace}`;
+ const [previewed, setPreviewed] = useState<string | null>(null);
+ const opts = { source, ...(file.trim() ? { file } : {}), ...(replace ? { replace: true } : {}) };
+ return (
+ <div className="flex flex-col gap-2">
+ <h4 className="text-sm font-semibold">Attach from a local archive</h4>
+ <div className="flex flex-wrap gap-3 text-sm">
+ <label className="flex flex-col gap-0.5">
+ <span className="text-xs text-muted-foreground">Archive (a directory, .zip or .7z, absolute path)</span>
+ <input value={source} onChange={(e) => setSource(e.target.value)} aria-label="archive path" className={`${input} w-96 max-w-full font-mono`} />
+ </label>
+ <label className="flex flex-col gap-0.5">
+ <span className="text-xs text-muted-foreground">File inside it (optional: else found by the id)</span>
+ <input value={file} onChange={(e) => setFile(e.target.value)} aria-label="file inside the archive" className={`${input} w-72 max-w-full font-mono`} />
+ </label>
+ {saved && (
+ <label className="flex items-center gap-2 self-end">
+ <input type="checkbox" checked={replace} onChange={(e) => setReplace(e.target.checked)} aria-label="replace the saved container" />
+ Replace the saved container
+ </label>
+ )}
+ </div>
+ <StreamActionLog
+ trigger={() => attachVideoMediaAction(slug, videoId, { ...opts, dryRun: true })}
+ cancelAction={cancelJobAction}
+ buttonLabel="Preview attach"
+ runningLabel="Reading the archive…"
+ label={`Preview attach of ${videoId}`}
+ disabled={!source.trim()}
+ onSettled={(started) => setPreviewed(started ? key : null)}
+ />
+ <StreamActionLog
+ trigger={() => attachVideoMediaAction(slug, videoId, opts)}
+ cancelAction={cancelJobAction}
+ buttonLabel="Attach"
+ runningLabel="Attaching…"
+ label={`Attach media to ${videoId}`}
+ disabled={previewed !== key}
+ />
+ </div>
+ );
+}
+
+function RecordsRefresh({
+ title,
+ what,
+ slug,
+ videoId,
+ withTitle = false,
+ run,
+}: {
+ title: string;
+ what: string;
+ slug: string;
+ videoId: string;
+ withTitle?: boolean;
+ run: (dryRun: boolean, title?: { id: string; title?: string; upload_date?: string }) => Promise<RecordsRefreshResult>;
+}) {
+ const [hydrated, setHydrated] = useState(false);
+ useEffect(() => setHydrated(true), []);
+ const [recTitle, setRecTitle] = useState("");
+ const [recDate, setRecDate] = useState("");
+ const key = `${recTitle}\u0000${recDate}`;
+ const [previewed, setPreviewed] = useState<string | null>(null);
+ const [result, setResult] = useState<RecordsRefreshResult | null>(null);
+ const [pending, start] = useTransition();
+ const go = (dryRun: boolean) =>
+ start(async () => {
+ const t = withTitle && (recTitle.trim() || recDate.trim()) ? { id: videoId, title: recTitle, upload_date: recDate } : undefined;
+ const res = await run(dryRun, t);
+ setResult(res);
+ if (dryRun && res.ok) setPreviewed(key);
+ });
+ const label = `${what} refresh`;
+ return (
+ <div className="flex flex-col gap-2">
+ <h4 className="text-sm font-semibold">{title}</h4>
+ {withTitle && (
+ <div className="flex flex-wrap gap-3 text-sm">
+ <label className="flex flex-col gap-0.5">
+ <span className="text-xs text-muted-foreground">This record's title (optional)</span>
+ <input value={recTitle} onChange={(e) => setRecTitle(e.target.value)} aria-label="record title" className={`${input} w-72 max-w-full`} />
+ </label>
+ <label className="flex flex-col gap-0.5">
+ <span className="text-xs text-muted-foreground">Its date (optional)</span>
+ <input type="date" value={recDate} onChange={(e) => setRecDate(e.target.value)} aria-label="record date" className={input} />
+ </label>
+ </div>
+ )}
+ <div className="flex flex-wrap gap-2">
+ <Button type="button" size="sm" variant="outline" disabled={!hydrated || pending} onClick={() => go(true)}>
+ Preview {what} refresh
+ </Button>
+ <Button type="button" size="sm" disabled={!hydrated || pending || previewed !== key} onClick={() => go(false)}>
+ Refresh {what} records
+ </Button>
+ </div>
+ {result && !result.ok && (
+ <p role="alert" aria-label={`${label} error`} className="text-xs text-destructive">
+ {result.error}
+ </p>
+ )}
+ {result?.ok && (
+ <div className="flex flex-col gap-1" aria-label={`${label} result`}>
+ <p role="status" className="text-sm">
+ {result.summary}
+ </p>
+ {result.renamed.length > 0 && (
+ <ul className="text-xs">
+ {result.renamed.map((r) => (
+ <li key={r.from}>
+ {r.from} → {result.dryRun ? r.to : <Link href={`/channels/${slug}/videos/${r.to}`} className="underline font-mono">{r.to}</Link>}
+ </li>
+ ))}
+ </ul>
+ )}
+ {result.log.length > 0 && (
+ <pre className="text-xs font-mono bg-muted border border-border rounded-md p-2 max-h-60 overflow-auto whitespace-pre-wrap">{result.log.join("\n")}</pre>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/editor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts b/editor/app/channels/[slug]/videos/[id]/mediaToolsActions.ts
@@ -0,0 +1,117 @@
+"use server";
+
+// The video page's "Media tools" (release 32, lane R3): operations that were
+// CLI- or ops-only, each a button where its object lives.
+//
+// attach `archilyzer media attach` / `pnpm ops attach-media` for THIS
+// video: its file out of a local archive (a directory, a .zip,
+// a .7z) into the saved-video store — the `attach-media` job,
+// narrowed to the file named, else to the id
+// playable `archilyzer media playable` / `prepare-playable` for this
+// video's saved container — the `prepare-playable` job
+// wayback `archilyzer wayback refresh <slug>` — the channel's Wayback
+// copies brought up to the rules (offline), a title and date for
+// this record with it; answered in the request
+// archiveOrg `archilyzer archive-org refresh <slug>` — the channel's
+// archive.org file records (offline); answered in the request
+//
+// NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use server" file).
+
+import path from "node:path";
+import { revalidatePath } from "next/cache";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { refreshWaybackRecords } from "yt-dlp-transcript-common/controller/waybackRefresh";
+import { refreshArchiveOrgRecords } from "yt-dlp-transcript-common/controller/archiveOrgRefresh";
+import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels";
+import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
+import { attachMediaAction } from "../../attachMediaActions";
+import { preparePlayableAction } from "../../playableActions";
+
+const escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+
+export async function attachVideoMediaAction(
+ slug: string,
+ videoId: string,
+ opts: { source: string; file?: string; replace?: boolean; dryRun?: boolean },
+): Promise<StreamActionResult> {
+ const file = opts.file?.trim();
+ if (file && (path.isAbsolute(file) || file.split(/[\\/]/).includes(".."))) {
+ return { ok: false, error: "The file is a path INSIDE the archive (relative, no ..)" };
+ }
+ return attachMediaAction(slug, {
+ source: opts.source,
+ ...(file ? { items: [{ id: videoId, path: file }] } : { match: escapeRegex(videoId) }),
+ ...(opts.replace ? { replace: true } : {}),
+ ...(opts.dryRun ? { dryRun: true } : {}),
+ });
+}
+
+export async function playableVideoAction(slug: string, videoId: string, dryRun = false): Promise<StreamActionResult> {
+ return preparePlayableAction(slug, { ids: [videoId], ...(dryRun ? { dryRun: true } : {}) });
+}
+
+export type RecordsRefreshResult =
+ | { ok: true; dryRun: boolean; summary: string; log: string[]; renamed: { from: string; to: string }[] }
+ | { ok: false; error: string };
+
+export async function waybackRefreshAction(
+ slug: string,
+ opts: { dryRun: boolean; title?: { id: string; title?: string; upload_date?: string } },
+): Promise<RecordsRefreshResult> {
+ if (!isValidChannelSlug(slug)) return { ok: false, error: `"${slug}" is not a channel slug` };
+ const t = opts.title;
+ const title = t?.title?.trim();
+ const date = t?.upload_date?.trim().replace(/-/g, "");
+ if (date && !/^\d{8}$/.test(date)) return { ok: false, error: "The date is YYYY-MM-DD" };
+ const titles = t && (title || date) ? { [t.id]: { ...(title ? { title } : {}), ...(date ? { upload_date: date } : {}) } } : undefined;
+ const log: string[] = [];
+ try {
+ const r = await refreshWaybackRecords({
+ slug,
+ paths: getPaths(),
+ dryRun: opts.dryRun,
+ ...(titles ? { titles } : {}),
+ onLog: (line) => log.push(line.replace(/\n$/, "")),
+ });
+ const would = opts.dryRun ? "would be " : "";
+ const renamed = r.records.filter((x) => x.rename === "renamed" || x.rename === "merged");
+ const held = r.records.filter((x) => x.rename === "held" || x.rename === "conflict").length;
+ for (const id of r.unmatchedTitles) log.push(`title: no Wayback record "${id}"`);
+ for (const f of r.failed) log.push(`${f.id}: failed — ${f.error}`);
+ const summary =
+ `${opts.dryRun ? "Preview: " : ""}${r.records.length} Wayback record(s), ${renamed.length} ${would}renamed, ` +
+ `${r.records.filter((x) => x.sidecar).length} wayback.json ${would}written, ` +
+ `${r.records.filter((x) => Object.keys(x.changes).length > 0).length} ${would}retitled` +
+ (held ? `, ${held} not renamed` : "") +
+ (r.failed.length ? `, ${r.failed.length} failed` : "") +
+ ".";
+ if (!opts.dryRun) revalidatePath(`/channels/${slug}`, "layout");
+ return { ok: true, dryRun: opts.dryRun, summary, log, renamed: renamed.map((x) => ({ from: x.from, to: x.to })) };
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+}
+
+export async function archiveOrgRefreshAction(slug: string, opts: { dryRun: boolean }): Promise<RecordsRefreshResult> {
+ if (!isValidChannelSlug(slug)) return { ok: false, error: `"${slug}" is not a channel slug` };
+ const log: string[] = [];
+ try {
+ const r = await refreshArchiveOrgRecords({
+ slug,
+ paths: getPaths(),
+ dryRun: opts.dryRun,
+ onLog: (line) => log.push(line.replace(/\n$/, "")),
+ });
+ const would = opts.dryRun ? "would be " : "";
+ for (const f of r.failed) log.push(`${f.id}: failed — ${f.error}`);
+ const summary =
+ `${opts.dryRun ? "Preview: " : ""}${r.fileRecords} archive.org file record(s), ${r.changed.length} ${would}refreshed, ` +
+ `${r.sidecars} provenance sidecar(s) ${would}updated` +
+ (r.failed.length ? `, ${r.failed.length} failed` : "") +
+ ".";
+ if (!opts.dryRun) revalidatePath(`/channels/${slug}`, "layout");
+ return { ok: true, dryRun: opts.dryRun, summary, log, renamed: [] };
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+}
diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx
@@ -48,6 +48,14 @@ import { FrameScanPanel } from "./components/FrameScanPanel";
import { frameScanView } from "./lib/frameScanView";
import { loadFrameScans } from "yt-dlp-transcript-common/lib/frameScan-server";
import { MetadataHistoryDetails } from "./components/MetadataHistoryDetails";
+import { VideoMediaTools } from "./components/VideoMediaTools";
+import { loadAudioIntegrity } from "yt-dlp-transcript-common/lib/audioIntegrity-server";
+import {
+ describeIntegrity,
+ integrityMatches,
+ integrityVerdict,
+ type AudioIntegrityRecord,
+} from "yt-dlp-transcript-common/lib/audioIntegrity";
import { RefreshMetadataControl } from "./components/RefreshMetadataControl";
import { loadVideoTags } from "./lib/videoTags";
import { loadVideoOperationPanels } from "./lib/videoOperationPanels";
@@ -160,6 +168,9 @@ export default async function VideoDetailPage({
// A gone video whose audio came from a copy (release 31, find-copy's
// scope mode): the newest `fetched` attempt in copy-attempts.json.
const audioCopy = latestFetchedCopy(await loadCopyAttempts(videoDir));
+ // The audio audit's verdict on this video's held audio (release 31 lane
+ // A's audio-integrity.json; shown since release 32).
+ const audioIntegrity = await loadAudioIntegrity(videoDir);
// The windows another tool asked this editor to fetch. One readdir of
// data/<id>/clips/ plus a stat per file — and no per-CHANNEL count anywhere,
// because that would be a walk of every video dir to draw one number.
@@ -219,6 +230,7 @@ export default async function VideoDetailPage({
archiveOrg,
wayback,
audioCopy,
+ audioIntegrity,
clipWindows,
vttProvenance,
coverage,
@@ -251,6 +263,7 @@ export default async function VideoDetailPage({
archiveOrg,
wayback,
audioCopy,
+ audioIntegrity,
clipWindows,
vttProvenance,
coverage,
@@ -327,6 +340,7 @@ export default async function VideoDetailPage({
{wayback && <WaybackProvenanceLine prov={wayback} />}
</>
)}
+ {audioIntegrity && <AudioIntegrityLine record={audioIntegrity} files={dirData.files} />}
{meta.description && (
<details className="text-sm">
<summary className="cursor-pointer text-muted-foreground hover:text-foreground">
@@ -391,6 +405,15 @@ export default async function VideoDetailPage({
<TagsPanel view={tagsView} />
+ {/* CLI-only operations on this video's media, as buttons (release 32). */}
+ <VideoMediaTools
+ slug={slug}
+ videoId={id}
+ saved={!!savedVideo}
+ wayback={!!wayback || hostOf(meta.webpageUrl) === "web.archive.org"}
+ archiveOrg={!!archiveOrg || hostOf(meta.webpageUrl) === "archive.org"}
+ />
+
{/* A frame scan's timeline, and its Scan button when the source
container is saved (the scan reads the saved video). */}
<FrameScanPanel
@@ -495,6 +518,34 @@ function AudioCopyLine({ copy }: { copy: CopyAttempt }) {
);
}
+// "Audio check: damaged: 38:55 of 1:40:00 decodes (38.9%), 3 gaps" and the
+// gaps — the audit's record for the held file, or that it is out of date.
+function AudioIntegrityLine({ record, files }: { record: AudioIntegrityRecord; files: { name: string; size: number | null }[] }) {
+ const file = files.find((f) => f.name === record.file);
+ const current = !!file && integrityMatches(record, { name: record.file, ...(file.size !== null ? { size: file.size } : {}) });
+ const verdict = integrityVerdict(record);
+ const gaps = record.gaps.slice(0, 6).map(([a, b]) => `${formatDuration(a)}–${formatDuration(b)}`);
+ return (
+ <div aria-label="audio integrity" className="text-sm text-muted-foreground">
+ Audio check ({record.file}):{" "}
+ <span className={verdict === "clean" ? "" : "text-warning"}>{describeIntegrity({ ...record, verdict })}</span>
+ {gaps.length > 0 && ` — gaps ${gaps.join(", ")}${record.gaps.length > gaps.length ? ", …" : ""}`}
+ {" · "}
+ {record.checkedAt.slice(0, 10)}
+ {!current && " · out of date: the file changed or is gone"}
+ </div>
+ );
+}
+
+function hostOf(url: string | null | undefined): string | null {
+ if (!url) return null;
+ try {
+ return new URL(url).hostname.replace(/^www\./, "");
+ } catch {
+ return null;
+ }
+}
+
function formatUploadDate(s: string): string {
// yt-dlp emits YYYYMMDD. Render as YYYY-MM-DD; pass through anything else.
if (/^\d{8}$/.test(s)) {
diff --git a/editor/app/components/FindCopiesControl.tsx b/editor/app/components/FindCopiesControl.tsx
@@ -0,0 +1,168 @@
+"use client";
+
+import Link from "next/link";
+import { useState } from "react";
+import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
+import { cancelJobAction } from "../jobs/actions";
+import { findWholeCopiesAction } from "../channels/[slug]/videos/findCopyAction";
+import {
+ FIND_COPY_MARKER,
+ FIND_COPY_OUTCOME_TEXT,
+ readResultMarker,
+ type FindCopiesResultView,
+} from "../lib/resultMarker";
+
+// "Find copies of gone videos" (release 32; find-copy's scope mode, release
+// 31 lane C): for a channel — or every channel of a site — the gone videos
+// holding no media are looked up on the Wayback Machine and archive.org.
+// Preview is a dry run (the same paced lookups, nothing recorded or fetched)
+// listing each candidate and the copy it would use; Run is armed by a preview
+// of the same settings, looks again, records what has no copy and sends every
+// copy found to ONE fetch-copies job, linked here.
+
+type Gone = "no-transcript" | "all";
+type Params = { gone: Gone; max: number; retryFailed: boolean };
+
+const sameParams = (a: Params, b: Params) => a.gone === b.gone && a.max === b.max && a.retryFailed === b.retryFailed;
+
+export function FindCopiesControl(scope: { slug: string } | { siteId: string }) {
+ const name = "slug" in scope ? scope.slug : scope.siteId;
+ const [gone, setGone] = useState<Gone>("no-transcript");
+ const [maxText, setMaxText] = useState("10");
+ const [retryFailed, setRetryFailed] = useState(false);
+ const max = Math.min(200, Math.max(1, Math.floor(Number(maxText) || 10)));
+ const params: Params = { gone, max, retryFailed };
+ const [preview, setPreview] = useState<{ params: Params; result: FindCopiesResultView | null } | null>(null);
+ const [run, setRun] = useState<{ jobId: string | null; result: FindCopiesResultView | null } | null>(null);
+ const armed = preview !== null && preview.result !== null && sameParams(preview.params, params);
+ const body = (dryRun: boolean) => ({ ...("slug" in scope ? { slug: scope.slug } : { siteId: scope.siteId }), gone, max, retryFailed, dryRun });
+
+ return (
+ <section aria-label="find copies of gone videos" className="flex flex-col gap-2 rounded border border-border p-3">
+ <h4 className="text-sm font-semibold">Find copies of gone videos</h4>
+ <div className="flex flex-wrap items-center gap-3 text-sm">
+ <label className="flex items-center gap-2">
+ <span className="text-muted-foreground">Videos</span>
+ <select
+ value={gone}
+ onChange={(e) => setGone(e.target.value as Gone)}
+ aria-label="gone videos to look for"
+ className="rounded border border-border bg-card px-2 py-1 text-sm"
+ >
+ <option value="no-transcript">gone, no transcript</option>
+ <option value="all">every gone video with no media</option>
+ </select>
+ </label>
+ <label className="flex items-center gap-2">
+ <span className="text-muted-foreground">At most</span>
+ <input
+ type="number"
+ min={1}
+ max={200}
+ value={maxText}
+ onChange={(e) => setMaxText(e.target.value)}
+ aria-label="lookups at most"
+ className="rounded border border-border bg-card px-2 py-1 text-sm w-20"
+ />
+ <span className="text-xs text-muted-foreground">lookups</span>
+ </label>
+ <label className="flex items-center gap-2">
+ <input type="checkbox" checked={retryFailed} onChange={(e) => setRetryFailed(e.target.checked)} aria-label="try failed copies again" />
+ Try failed copies again
+ </label>
+ </div>
+ <StreamActionLog
+ trigger={() => findWholeCopiesAction(body(true))}
+ cancelAction={cancelJobAction}
+ buttonLabel="Preview"
+ runningLabel="Looking…"
+ label={`Preview copies for ${name}`}
+ onSettled={(started, out) => {
+ if (!started) return;
+ setPreview({ params, result: readResultMarker<FindCopiesResultView>(out.log, FIND_COPY_MARKER) });
+ }}
+ />
+ {preview?.result && <FindCopiesResult result={preview.result} label="find copies preview" />}
+ <StreamActionLog
+ trigger={() => findWholeCopiesAction(body(false))}
+ cancelAction={cancelJobAction}
+ buttonLabel="Find and fetch copies"
+ runningLabel="Finding copies…"
+ label={`Find copies for ${name}`}
+ disabled={!armed}
+ onSettled={(started, out) => {
+ if (!started) return;
+ setRun({ jobId: out.jobId, result: readResultMarker<FindCopiesResultView>(out.log, FIND_COPY_MARKER) });
+ }}
+ />
+ {!armed && <p className="text-xs text-muted-foreground">Preview these settings first.</p>}
+ {run && (
+ <p role="status" aria-label="find copies run" className="text-sm">
+ {run.jobId && (
+ <>
+ <Link href={`/jobs/${run.jobId}`} className="underline font-mono">
+ find-copy job {run.jobId}
+ </Link>
+ {": "}
+ </>
+ )}
+ {run.result
+ ? `${run.result.looked.filter((l) => l.outcome === "fetch").length} cop${run.result.looked.filter((l) => l.outcome === "fetch").length === 1 ? "y" : "ies"} found`
+ : "finished"}
+ {run.result?.fetchJobId && (
+ <>
+ {" · "}
+ <Link href={`/jobs/${run.result.fetchJobId}`} className="underline font-mono">
+ fetch-copies job {run.result.fetchJobId}
+ </Link>
+ </>
+ )}
+ {run.result?.refused && <span className="text-destructive"> · fetch refused: {run.result.refused}</span>}
+ </p>
+ )}
+ </section>
+ );
+}
+
+function FindCopiesResult({ result, label }: { result: FindCopiesResultView; label: string }) {
+ const s = result.skipped;
+ return (
+ <div className="flex flex-col gap-1 text-sm" aria-label={label}>
+ <p className="text-xs text-muted-foreground" aria-label={`${label} counts`}>
+ {result.eligible} gone video{result.eligible === 1 ? "" : "s"} with no media in {result.channels.length} channel
+ {result.channels.length === 1 ? "" : "s"}; {result.looked.length} looked up
+ {result.left > 0 && `, ${result.left} left for a later run`}
+ {s.recent.length > 0 && `; ${s.recent.length} left out (a recent attempt found none)`}
+ {s.unreadable.length > 0 && `; ${s.unreadable.length} channel(s) unreadable`}
+ {result.stopped && ` · stopped: ${result.stopped}`}
+ </p>
+ {result.looked.length > 0 && (
+ <table className="text-xs">
+ <thead className="text-left text-muted-foreground">
+ <tr>
+ <th className="pr-3 font-medium">Video</th>
+ <th className="pr-3 font-medium">Gone</th>
+ <th className="pr-3 font-medium">Outcome</th>
+ <th className="font-medium">Copy</th>
+ </tr>
+ </thead>
+ <tbody>
+ {result.looked.map((l) => (
+ <tr key={`${l.slug}/${l.id}`} data-testid="find-copy-candidate">
+ <td className="pr-3 font-mono">
+ <Link href={`/channels/${l.slug}/videos/${l.id}`} className="underline">
+ {l.slug}/{l.id}
+ </Link>
+ {!l.noTranscript && <span className="text-muted-foreground"> (transcribed)</span>}
+ </td>
+ <td className="pr-3">{l.gone}</td>
+ <td className="pr-3">{FIND_COPY_OUTCOME_TEXT[l.outcome] ?? l.outcome}</td>
+ <td className="break-all">{l.via ?? "—"}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ );
+}
diff --git a/editor/app/lib/resultMarker.test.ts b/editor/app/lib/resultMarker.test.ts
@@ -0,0 +1,18 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { FIND_COPY_RESULT_MARKER } from "yt-dlp-transcript-common/publish/findCopy";
+import { AUDIO_AUDIT_RESULT_MARKER } from "yt-dlp-transcript-common/controller/audioAudit";
+import { AUDIO_AUDIT_MARKER, FIND_COPY_MARKER, readResultMarker } from "./resultMarker";
+
+test("the client's marker strings are the controllers'", () => {
+ assert.equal(FIND_COPY_MARKER, FIND_COPY_RESULT_MARKER);
+ assert.equal(AUDIO_AUDIT_MARKER, AUDIO_AUDIT_RESULT_MARKER);
+});
+
+test("readResultMarker: the last marker line's JSON; null for none or for a line that is not JSON", () => {
+ const log = `find-copy channel x: 2 gone video(s)\n@@find-copy {"eligible":1}\n x/a: …\n@@find-copy {"eligible":2,"looked":[]}\n`;
+ assert.deepEqual(readResultMarker(log, FIND_COPY_MARKER), { eligible: 2, looked: [] });
+ assert.equal(readResultMarker("nothing here", FIND_COPY_MARKER), null);
+ assert.equal(readResultMarker("@@find-copy {broken", FIND_COPY_MARKER), null);
+ assert.deepEqual(readResultMarker('@@audio-audit {"clean":3}', AUDIO_AUDIT_MARKER), { clean: 3 });
+});
diff --git a/editor/app/lib/resultMarker.ts b/editor/app/lib/resultMarker.ts
@@ -0,0 +1,61 @@
+// A job's RESULT MARKER read off its log (release 32): several jobs end their
+// log with one `@@<kind> {json}` line (find-copy, audio-audit, frame-scan…).
+// A button that ran one — a dry run whose answer is a candidate list — reads
+// the LAST such line. Client-safe: no server module is imported, so the
+// marker strings are written here and pinned to the controllers' constants by
+// resultMarker.test.ts.
+
+export const FIND_COPY_MARKER = "@@find-copy ";
+export const AUDIO_AUDIT_MARKER = "@@audio-audit ";
+
+/** The JSON after the last line starting with `marker`, or null (none, or not JSON). */
+export function readResultMarker<T = unknown>(log: string, marker: string): T | null {
+ const lines = log.split("\n");
+ for (let i = lines.length - 1; i >= 0; i--) {
+ const line = lines[i]!.trim();
+ if (!line.startsWith(marker.trim())) continue;
+ try {
+ return JSON.parse(line.slice(marker.trim().length).trim()) as T;
+ } catch {
+ return null;
+ }
+ }
+ return null;
+}
+
+// What the find-copy scope mode's log ends with (publish/findCopy.ts
+// FindWholeCopiesResult, plus the job's fetchJobId / refused).
+export type FindCopiesResultView = {
+ gone: "no-transcript" | "all";
+ dryRun: boolean;
+ max: number;
+ channels: string[];
+ eligible: number;
+ skipped: {
+ media: number;
+ transcript: number;
+ recent: { slug: string; id: string; at: string; outcome: string }[];
+ unreadable: { slug: string; error: string }[];
+ };
+ looked: {
+ slug: string;
+ id: string;
+ gone: string;
+ noTranscript: boolean;
+ watchUrl: string | null;
+ outcome: "fetch" | "none-found" | "not-youtube" | "error";
+ via?: string;
+ }[];
+ left: number;
+ items: unknown[];
+ stopped?: string;
+ fetchJobId?: string;
+ refused?: string;
+};
+
+export const FIND_COPY_OUTCOME_TEXT: Record<FindCopiesResultView["looked"][number]["outcome"], string> = {
+ fetch: "copy found",
+ "none-found": "no copy found",
+ "not-youtube": "not looked for (not YouTube)",
+ error: "lookup failed, try later",
+};
diff --git a/editor/app/sites/[siteId]/page.tsx b/editor/app/sites/[siteId]/page.tsx
@@ -8,6 +8,7 @@ import {
type SiteOption,
} from "../components/SiteForm";
import { getSiteCached } from "./lib/siteCache";
+import { FindCopiesControl } from "../../components/FindCopiesControl";
export const dynamic = "force-dynamic";
@@ -35,6 +36,9 @@ export default async function EditSitePage({
allSites={allSites}
isNew={false}
/>
+ {/* Every channel of the site at once (release 32): find-copy's scope
+ mode, as each channel's Download stage offers it for one. */}
+ <FindCopiesControl siteId={siteId} />
</div>
);
}