commit 3284696092f8e0ed78e1b5481ca1b6fc28f56f2b
parent 5ca233a207f275c55a152d08295f4c4d4c95a630
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 24 Nov 2026 16:39:55 -0500
space-suggestions: /cleanup/space — Free up space, and the tabs and summary line on /cleanup
The disks fullest first (size, free now, the archive's share by kind, not the
archive's), and what frees space on the one picked, by kind, biggest first.
Each row says what it frees and where, what a move fills, what is lost, and
how the number was got; its button names the suggestion's key and runs the
actions the scan wrote, through the existing writers (dry run where one
answers at once, a tick where the writer wants a person's word). Held,
selector refusals, no-writer bytes and unscanned channels below. The page
reads the scan's file only.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
10 files changed, 754 insertions(+), 4 deletions(-)
diff --git a/common/controller/spaceScan.ts b/common/controller/spaceScan.ts
@@ -44,7 +44,6 @@ import { formatBytes } from "../lib/format";
import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server";
import { isDriveNotAnswering, onDrive, stalledLocation } from "../lib/storageHealth";
import { probeLocationMemo } from "../lib/storageVolumes";
-import { STORAGE_STATUS_LABEL } from "../views/storage";
import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
import {
SPACE_CLIP_AGE_DAYS,
@@ -295,8 +294,14 @@ async function defaultLocationStatus(loc: StorageLocation, paths: Paths): Promis
if (stalledLocation(loc)) return { status: "not-answering", detail: "its drive is not answering" };
const probe = await probeLocationMemo(loc, paths);
if (probe.status === "available") return { status: "ok" };
- if (probe.status === "stalled") return { status: "not-answering", detail: STORAGE_STATUS_LABEL[probe.status] };
- return { status: "not-mounted", detail: STORAGE_STATUS_LABEL[probe.status] };
+ if (probe.status === "stalled") return { status: "not-answering", detail: "its drive is not answering" };
+ const why: Record<string, string> = {
+ "mounted-elsewhere": "its disk is mounted somewhere else (re-point it on /storage)",
+ unmounted: "its disk is attached but not mounted",
+ absent: "its disk is not attached",
+ missing: "its root does not exist",
+ };
+ return { status: "not-mounted", detail: why[probe.status] ?? probe.status };
}
// --- per channel -----------------------------------------------------------------
diff --git a/editor/app/cleanup/components/CleanupTabs.tsx b/editor/app/cleanup/components/CleanupTabs.tsx
@@ -0,0 +1,24 @@
+import Link from "next/link";
+
+// The two halves of /cleanup: the audio sweeps and their holds, and Free up
+// space (every disk, every writer that frees bytes on it).
+export function CleanupTabs({ active }: { active: "audio" | "space" }) {
+ const tab = (href: string, id: "audio" | "space", label: string) => (
+ <Link
+ href={href}
+ aria-current={active === id ? "page" : undefined}
+ className={
+ "rounded-md px-3 py-1.5 text-sm " +
+ (active === id ? "bg-secondary font-medium text-foreground" : "text-muted-foreground hover:text-foreground")
+ }
+ >
+ {label}
+ </Link>
+ );
+ return (
+ <nav aria-label="cleanup tabs" className="flex flex-wrap gap-1">
+ {tab("/cleanup/space", "space", "Free up space")}
+ {tab("/cleanup", "audio", "Audio & holds")}
+ </nav>
+ );
+}
diff --git a/editor/app/cleanup/page.tsx b/editor/app/cleanup/page.tsx
@@ -17,6 +17,9 @@ import { getSettings } from "yt-dlp-transcript-common/lib/settings";
import { isGateHeld } from "yt-dlp-transcript-common/lib/pauseGates";
import { LaneActionButton } from "../components/lanes/LaneActionButton";
import { workThroughSpeakersAction } from "../jobs/actions";
+import { CleanupTabs } from "./components/CleanupTabs";
+import { loadSpace } from "./space/lib/loadSpace";
+import { spaceSummaryLine } from "yt-dlp-transcript-common/lib/spaceSuggestions";
export const dynamic = "force-dynamic";
@@ -35,6 +38,10 @@ export default async function CleanupPage() {
const settings = getSettings();
const speakersWorking =
settings.autoQueue.backfill.enabled && !isGateHeld(settings, "backfill");
+ // Free up space's one line: the last space scan's file and each disk's free
+ // space now — no walk.
+ const space = await loadSpace();
+ const spaceLine = spaceSummaryLine(space.result, space.live);
const {
rows,
includedReclaimBytes,
@@ -60,6 +67,13 @@ export default async function CleanupPage() {
<div className="flex items-center justify-between flex-wrap gap-2">
<h1 className="text-2xl font-semibold">Cleanup</h1>
</div>
+ <CleanupTabs active="audio" />
+ <p className="text-sm" aria-label="space summary">
+ {spaceLine ?? "No space scan yet."}{" "}
+ <Link href="/cleanup/space" className="underline hover:text-foreground">
+ Free up space
+ </Link>
+ </p>
{/* Hero readout — the reclamation console. */}
<section
diff --git a/editor/app/cleanup/space/actions.ts b/editor/app/cleanup/space/actions.ts
@@ -0,0 +1,26 @@
+"use server";
+
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { readSpaceSuggestions } from "yt-dlp-transcript-common/controller/spaceScan";
+import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
+import { safeRevalidate } from "../../lib/safeRevalidate";
+import { enqueueSpaceScanJob } from "./lib/spaceJob";
+import { runSpaceSuggestion, type SpaceRunOutcome } from "./lib/runSpaceAction";
+
+// /cleanup/space's two buttons. Refresh is the `space-scan` job (`pnpm ops
+// space-scan`); a suggestion's button names its KEY and runs the actions the
+// scan wrote for it, through the existing writers (lib/runSpaceAction.ts).
+
+export async function startSpaceScanAction(): Promise<StreamActionResult> {
+ return enqueueSpaceScanJob();
+}
+
+export async function runSpaceSuggestionAction(
+ key: string,
+ opts: { dryRun?: boolean; ticked?: boolean } = {},
+): Promise<SpaceRunOutcome> {
+ const result = await readSpaceSuggestions(getPaths());
+ const out = await runSpaceSuggestion({ result, key, dryRun: opts.dryRun === true, ticked: opts.ticked === true });
+ if (!out.dryRun && out.ok) safeRevalidate(["/cleanup", "/cleanup/space"]);
+ return out;
+}
diff --git a/editor/app/cleanup/space/components/SpaceRefresh.tsx b/editor/app/cleanup/space/components/SpaceRefresh.tsx
@@ -0,0 +1,31 @@
+"use client";
+
+import Link from "next/link";
+import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
+import { cancelJobAction } from "../../../jobs/actions";
+import { startSpaceScanAction } from "../actions";
+
+// Refresh: the space scan as a job (`pnpm ops space-scan`). While one is
+// queued or running the page names it instead of offering a second.
+export function SpaceRefresh({ running }: { running: { jobId: string; status: string } | null }) {
+ if (running) {
+ return (
+ <span className="text-sm text-muted-foreground" aria-label="space scan running">
+ A scan is {running.status}:{" "}
+ <Link href={`/jobs/${running.jobId}`} className="underline hover:text-foreground">
+ its job
+ </Link>
+ </span>
+ );
+ }
+ return (
+ <StreamActionLog
+ trigger={startSpaceScanAction}
+ cancelAction={cancelJobAction}
+ buttonLabel="Refresh"
+ runningLabel="Scanning…"
+ label="Space scan"
+ title="Measure every disk the archive writes to and what would free space on each (reads only)."
+ />
+ );
+}
diff --git a/editor/app/cleanup/space/components/SpaceRow.tsx b/editor/app/cleanup/space/components/SpaceRow.tsx
@@ -0,0 +1,137 @@
+"use client";
+
+import { useState, useTransition } from "react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { Button } from "yt-dlp-transcript-common/components/ui/button";
+import { formatBytes } from "yt-dlp-transcript-common/lib/format";
+import type { SpaceSuggestion } from "yt-dlp-transcript-common/lib/spaceSuggestions";
+import { runSpaceSuggestionAction } from "../actions";
+
+// Ops that answer a dry run at once (lib/runSpaceAction.ts SPACE_DRY_RUNNABLE;
+// repeated here because that module is server-only).
+const DRY_RUNNABLE = new Set(["compress-text", "compact-saved-videos", "drop-saved-alternate"]);
+
+type Outcome = { ok: boolean; lines: string[]; jobIds: string[]; dryRun: boolean };
+
+export function SpaceRow({ s, diskLabel }: { s: SpaceSuggestion; diskLabel: Record<string, string> }) {
+ const router = useRouter();
+ const [open, setOpen] = useState(false);
+ const [ticked, setTicked] = useState(false);
+ const [preview, setPreview] = useState<Outcome | null>(null);
+ const [done, setDone] = useState<Outcome | null>(null);
+ const [pending, start] = useTransition();
+ const canDry = !!s.actions?.length && s.actions.every((a) => DRY_RUNNABLE.has(a.op));
+ const label = (id: string) => diskLabel[id] ?? id;
+
+ const run = (dryRun: boolean) =>
+ start(async () => {
+ const out = await runSpaceSuggestionAction(s.key, { dryRun, ticked });
+ if (dryRun) setPreview(out);
+ else {
+ setDone(out);
+ router.refresh();
+ }
+ });
+
+ return (
+ <li className="flex flex-col gap-1.5 border-t border-border py-2.5 first:border-t-0" aria-label={s.title}>
+ <div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">
+ <span className="text-sm">{s.title}</span>
+ <span className="font-mono text-sm tabular-nums">
+ {s.frees ? (
+ <>
+ {s.basis === "estimate" ? "~" : ""}
+ {formatBytes(s.frees.bytes)} on {label(s.frees.disk)}
+ </>
+ ) : s.later ? (
+ <>
+ later ~{formatBytes(s.later.low)}–{formatBytes(s.later.high)} on {label(s.later.disk)}
+ </>
+ ) : null}
+ </span>
+ </div>
+ <div className="flex flex-col gap-0.5 text-xs text-muted-foreground">
+ {s.fills && (
+ <span>
+ Fills {label(s.fills.disk)} by {formatBytes(s.fills.bytes)}
+ {s.fills.freeAfter !== null ? ` (${formatBytes(Math.max(0, s.fills.freeAfter))} free after)` : ""} ·{" "}
+ {s.fills.fits ? "fits" : "does not fit"}
+ </span>
+ )}
+ {s.later && <span>Frees nothing now: {s.later.when}.</span>}
+ <span>{s.basisText}</span>
+ <span>Loses: {s.loss}</span>
+ {s.shared && (
+ <span>
+ Shared: {s.shared.files} file(s), {formatBytes(s.shared.bytes)} with another hard link, not counted
+ </span>
+ )}
+ {s.disabled && <span className="text-amber-600 dark:text-amber-400">{s.disabled}</span>}
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ {s.actions?.length && !s.disabled && !done?.ok ? (
+ open ? null : (
+ <Button size="xs" variant="outline" onClick={() => setOpen(true)}>
+ {s.kind === "compact" ? "Compact…" : s.kind.startsWith("move") ? "Move…" : s.kind.startsWith("compress") ? "Compress…" : s.kind === "reverify-landing" ? "Verify again…" : "Free it…"}
+ </Button>
+ )
+ ) : null}
+ {s.link && (
+ <Link href={s.link.href} className="text-xs underline hover:text-foreground">
+ {s.link.label}
+ </Link>
+ )}
+ </div>
+ {open && !done?.ok && (
+ <div className="flex flex-col gap-2 rounded-md border border-border bg-muted/40 p-3 text-xs" role="group" aria-label={`confirm ${s.title}`}>
+ <span>
+ Runs{" "}
+ {s.actions!.map((a, i) => (
+ <code key={i} className="mr-1 font-mono">
+ pnpm ops {a.op} --json '{JSON.stringify(a.body)}'
+ </code>
+ ))}
+ </span>
+ {canDry && (
+ <div className="flex flex-col gap-1">
+ <Button size="xs" variant="ghost" className="self-start" disabled={pending} onClick={() => run(true)}>
+ Dry run
+ </Button>
+ {preview && (
+ <pre className="max-h-48 overflow-auto whitespace-pre-wrap font-mono" aria-label="dry run">
+ {preview.lines.join("\n")}
+ </pre>
+ )}
+ </div>
+ )}
+ {s.tick && (
+ <label className="flex items-center gap-1.5">
+ <input type="checkbox" checked={ticked} onChange={(e) => setTicked(e.target.checked)} />
+ {s.tick}
+ </label>
+ )}
+ <div className="flex gap-2">
+ <Button size="xs" disabled={pending || (!!s.tick && !ticked)} onClick={() => run(false)}>
+ Confirm
+ </Button>
+ <Button size="xs" variant="ghost" disabled={pending} onClick={() => setOpen(false)}>
+ Cancel
+ </Button>
+ </div>
+ </div>
+ )}
+ {done && (
+ <div className={`text-xs ${done.ok ? "text-muted-foreground" : "text-destructive"}`} role="status">
+ {done.lines.join(" · ")}
+ {done.jobIds.map((id) => (
+ <Link key={id} href={`/jobs/${id}`} className="ml-2 underline">
+ job
+ </Link>
+ ))}
+ {done.ok && <span> · rescan to update</span>}
+ </div>
+ )}
+ </li>
+ );
+}
diff --git a/editor/app/cleanup/space/lib/runSpaceAction.test.ts b/editor/app/cleanup/space/lib/runSpaceAction.test.ts
@@ -0,0 +1,87 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import type { SpaceScanResult, SpaceSuggestion } from "yt-dlp-transcript-common/lib/spaceSuggestions";
+import { runSpaceSuggestion, type SpaceRunner } from "./runSpaceAction";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/cleanup/space/lib/runSpaceAction.test.ts"
+//
+// The page's button names a suggestion by its key; what runs is the body the
+// SCAN wrote for it, through the existing writer — never a body the browser
+// sends.
+
+function row(extra: Partial<SpaceSuggestion>): SpaceSuggestion {
+ return { key: "k", kind: "evict-clips", title: "", frees: { disk: "corpus", bytes: 1 }, basis: "measured", basisText: "", loss: "", ...extra };
+}
+
+function result(rows: SpaceSuggestion[]): SpaceScanResult {
+ return { suggestions: rows } as unknown as SpaceScanResult;
+}
+
+function recorder() {
+ const calls: { op: string; body: Record<string, unknown>; dryRun: boolean }[] = [];
+ const make = (op: string): SpaceRunner => async (body, o) => {
+ calls.push({ op, body, dryRun: o.dryRun });
+ return { ok: true, lines: [`${op} ran`], jobIds: o.dryRun ? [] : [`job-${op}`], dryRun: o.dryRun };
+ };
+ const runners: Record<string, SpaceRunner> = Object.fromEntries(
+ ["compress-text", "evict-clips", "drop-saved-alternate", "relocate", "delete-file"].map((op) => [op, make(op)]),
+ );
+ return { calls, runners };
+}
+
+test("the scan's own body runs, each action in turn; a dry run only where the writer has one", async () => {
+ const { calls, runners } = recorder();
+ const r = result([
+ row({ key: "a", actions: [{ op: "evict-clips", body: { slug: "s", id: "v1", olderThanDays: 30 } }, { op: "evict-clips", body: { slug: "s", id: "v2", olderThanDays: 30 } }] }),
+ row({ key: "b", kind: "compress-captions", actions: [{ op: "compress-text", body: { slugs: ["s"], kinds: ["captions"] } }] }),
+ ]);
+ const out = await runSpaceSuggestion({ result: r, key: "a", dryRun: false, runners });
+ assert.equal(out.ok, true);
+ assert.deepEqual(out.jobIds, ["job-evict-clips", "job-evict-clips"]);
+ assert.deepEqual(calls.map((c) => c.body.id), ["v1", "v2"]);
+ // evict-clips' dry run is a job of its own: not offered as a preview.
+ const pre = await runSpaceSuggestion({ result: r, key: "a", dryRun: true, runners });
+ assert.equal(pre.ok, false);
+ assert.match(pre.lines[0], /no dry run/);
+ const dry = await runSpaceSuggestion({ result: r, key: "b", dryRun: true, runners });
+ assert.equal(dry.ok, true);
+ assert.equal(calls.at(-1)!.dryRun, true);
+ assert.deepEqual(calls.at(-1)!.body, { slugs: ["s"], kinds: ["captions"] });
+});
+
+test("refusals: an unknown key, a row with only a link, a disabled row, a missing tick, an op with no runner", async () => {
+ const { calls, runners } = recorder();
+ const r = result([
+ row({ key: "link", link: { href: "/x", label: "x" } }),
+ row({ key: "off", actions: [{ op: "relocate", body: { slugs: ["s"], locationId: "p" } }], disabled: "does not fit" }),
+ row({ key: "tick", actions: [{ op: "drop-saved-alternate", body: { slug: "s", id: "v", file: "f", confirmFormerOriginal: true } }], tick: "I mean the former original" }),
+ row({ key: "odd", actions: [{ op: "rm-rf", body: {} }] }),
+ ]);
+ for (const [key, re] of [
+ ["nope", /no suggestion "nope"/],
+ ["link", /nothing to run here/],
+ ["off", /does not fit/],
+ ["tick", /I mean the former original/],
+ ["odd", /not a writer this page runs: rm-rf/],
+ ] as const) {
+ const out = await runSpaceSuggestion({ result: r, key, dryRun: false, runners });
+ assert.equal(out.ok, false, key);
+ assert.match(out.lines.join(" "), re, key);
+ }
+ assert.equal(calls.length, 0);
+ const ticked = await runSpaceSuggestion({ result: r, key: "tick", dryRun: false, ticked: true, runners });
+ assert.equal(ticked.ok, true);
+ assert.equal(calls.length, 1);
+});
+
+test("a failing action stops the rest and says so", async () => {
+ const { runners } = recorder();
+ runners["delete-file"] = async () => ({ ok: false, lines: ["refused: drive not answering"], jobIds: [], dryRun: false });
+ const r = result([
+ row({ key: "p", actions: [{ op: "delete-file", body: { slug: "s", id: "v", file: "a.part" } }, { op: "delete-file", body: { slug: "s", id: "v", file: "a.ytdl" } }] }),
+ ]);
+ const out = await runSpaceSuggestion({ result: r, key: "p", dryRun: false, runners });
+ assert.equal(out.ok, false);
+ assert.deepEqual(out.lines, ["refused: drive not answering", "1 more not run"]);
+});
diff --git a/editor/app/cleanup/space/lib/runSpaceAction.ts b/editor/app/cleanup/space/lib/runSpaceAction.ts
@@ -0,0 +1,148 @@
+import type { SpaceScanResult } from "yt-dlp-transcript-common/lib/spaceSuggestions";
+import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
+import { formatBytes } from "yt-dlp-transcript-common/lib/format";
+
+// THE PAGE'S BUTTON, ON THE SERVER. It names a suggestion by its key; what runs
+// is the `actions` the SCAN wrote for it (`pnpm ops <op> --json <body>`), each
+// through the same action its ops route calls — compress-text, the cleanup
+// sweeps, relocate, evict-clips, delete-file, compact-saved-videos,
+// drop-saved-alternate, kept-failed-encodes, live-recording-verify. Nothing
+// else: an op not in the table is refused, and no body comes from the browser.
+// The writer refuses whatever it refuses when it runs (a busy video, a drive
+// not answering, a channel mid-move), so a stale scan cannot make it act on
+// what it would not.
+//
+// NOT "use server" (every export there is an endpoint): actions.ts wraps it.
+
+export type SpaceRunOutcome = { ok: boolean; lines: string[]; jobIds: string[]; dryRun: boolean };
+export type SpaceRunner = (body: Record<string, unknown>, o: { dryRun: boolean }) => Promise<SpaceRunOutcome>;
+
+// The writers whose dry run answers at once (a job's would be a job).
+export const SPACE_DRY_RUNNABLE: ReadonlySet<string> = new Set(["compress-text", "compact-saved-videos", "drop-saved-alternate"]);
+
+const str = (v: unknown): string => (typeof v === "string" ? v : "");
+const strs = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []);
+
+function fromStream(r: StreamActionResult): SpaceRunOutcome {
+ if (!r.ok) return { ok: false, lines: [r.error], jobIds: [], dryRun: false };
+ void r.stream.cancel();
+ return { ok: true, lines: ["queued"], jobIds: [r.jobId], dryRun: false };
+}
+
+const fail = (error: string): SpaceRunOutcome => ({ ok: false, lines: [error], jobIds: [], dryRun: false });
+
+// The real table: the same calls the ops routes make. Imported lazily, so the
+// dispatcher's test (and a page that only renders) loads none of them.
+export const SPACE_RUNNERS: Record<string, SpaceRunner> = {
+ "compress-text": async (body, o) => {
+ const { compressTextAction } = await import("../../../storage/compressTextActions");
+ const kinds = strs(body.kinds) as ("live-chat" | "captions")[];
+ const r = await compressTextAction({ slugs: strs(body.slugs), ...(kinds.length ? { kinds } : {}), dryRun: o.dryRun });
+ if (!r.ok) return fail(r.error);
+ if (r.dryRun) return { ok: true, lines: r.result.lines, jobIds: [], dryRun: true };
+ return { ok: true, lines: [`${r.jobIds.length} job(s) queued`, ...r.skipped.map((s) => `${s.slug}: ${s.reason}`)], jobIds: r.jobIds, dryRun: false };
+ },
+ cleanup: async (body) => {
+ const w = await import("../../../channels/[slug]/whisperActions");
+ const slug = str(body.slug);
+ if (body.sweep === "transcribed") return fromStream(await w.cleanAudioAction(slug));
+ if (body.sweep === "extra-formats") return fromStream(await w.cleanExtraAudioFormatsAction(slug));
+ return fail(`sweep "${str(body.sweep)}" is not one this page runs`);
+ },
+ relocate: async (body) => {
+ const { bulkRelocateChannelMediaAction } = await import("../../../channels/bulkStorageActions");
+ const r = await bulkRelocateChannelMediaAction(strs(body.slugs), { kind: "location", locationId: str(body.locationId) });
+ return {
+ ok: r.queued.length > 0,
+ lines: [...r.queued.map((s) => `${s}: queued`), ...r.skipped.map((s) => `${s.slug}: ${s.reason}`)],
+ jobIds: r.jobIds,
+ dryRun: false,
+ };
+ },
+ "evict-clips": async (body) => {
+ const { evictClipWindowsAction } = await import("../../../storage/actions");
+ return fromStream(
+ await evictClipWindowsAction({
+ ...(body.slug ? { slug: str(body.slug) } : {}),
+ ...(body.id ? { id: str(body.id) } : {}),
+ ...(typeof body.olderThanDays === "number" ? { olderThanDays: body.olderThanDays } : {}),
+ }),
+ );
+ },
+ "delete-file": async (body) => {
+ const { deleteVideoFileAction } = await import("../../../channels/[slug]/videos/[id]/videoActions");
+ const r = await deleteVideoFileAction(str(body.slug), str(body.id), str(body.file));
+ return r.ok ? { ok: true, lines: [`${str(body.file)} removed${r.note ? ` (${r.note})` : ""}`], jobIds: [], dryRun: false } : fail(r.error);
+ },
+ "compact-saved-videos": async (body, o) => {
+ const { compactSavedVideosAction } = await import("../../../saved-videos/compactActions");
+ const items = (Array.isArray(body.items) ? body.items : []).map((i) => ({ slug: str((i as Record<string, unknown>).slug), id: str((i as Record<string, unknown>).id) }));
+ const r = await compactSavedVideosAction({ items, dryRun: o.dryRun });
+ if (!r.ok) return fail(r.error);
+ if (r.dryRun) return { ok: true, lines: r.plan.lines, jobIds: [], dryRun: true };
+ return { ok: true, lines: [`${r.jobIds.length} job(s) queued on the compact queue`, ...r.skipped.map((s) => `${s.slug}: ${s.reason}`)], jobIds: r.jobIds, dryRun: false };
+ },
+ "drop-saved-alternate": async (body, o) => {
+ const { dropSavedAlternateAction } = await import("../../../channels/[slug]/videos/[id]/videoActions");
+ const r = await dropSavedAlternateAction(str(body.slug), str(body.id), str(body.file), {
+ dryRun: o.dryRun,
+ confirmOriginal: body.confirmOriginal === true,
+ confirmFormerOriginal: body.confirmFormerOriginal === true,
+ });
+ if (!r.ok) return fail(r.error);
+ const verb = r.result.dryRun ? "would free" : "freed";
+ return { ok: true, lines: [`${r.result.alternate.file}: ${verb} ${formatBytes(r.result.bytes)}${r.result.existed ? "" : " (already gone: only its entry)"}`], jobIds: [], dryRun: r.result.dryRun };
+ },
+ "kept-failed-encodes": async (body) => {
+ const { keptFailedEncodesAction } = await import("../../../saved-videos/compactActions");
+ const c = (body.clear ?? {}) as Record<string, unknown>;
+ const r = await keptFailedEncodesAction({ clear: { slug: str(c.slug), id: str(c.id) } });
+ const cleared = r.cleared;
+ return cleared?.cleared ? { ok: true, lines: [cleared.why], jobIds: [], dryRun: false } : fail(cleared?.why ?? "not cleared");
+ },
+ "live-recording-verify": async (body) => {
+ const { reverifyLiveRecordingAction } = await import("../../../channels/[slug]/liveMediaActions");
+ const r = await reverifyLiveRecordingAction({ slug: str(body.slug), id: str(body.id), ...(body.startedAt ? { startedAt: str(body.startedAt) } : {}) });
+ if (!r.ok) return fail(r.error);
+ return {
+ ok: true,
+ lines: [r.verified ? `verified: ${r.removed.length} stream file(s) removed` : `not verified: ${r.why ?? "nothing removed"}`],
+ jobIds: [],
+ dryRun: false,
+ };
+ },
+};
+
+export async function runSpaceSuggestion(opts: {
+ result: Pick<SpaceScanResult, "suggestions"> | null;
+ key: string;
+ dryRun: boolean;
+ ticked?: boolean;
+ runners?: Record<string, SpaceRunner>;
+}): Promise<SpaceRunOutcome> {
+ const runners = opts.runners ?? SPACE_RUNNERS;
+ const s = opts.result?.suggestions.find((x) => x.key === opts.key);
+ if (!s) return fail(`no suggestion "${opts.key}" in the last scan: refresh the page`);
+ if (!s.actions?.length) return fail(`nothing to run here: ${s.link ? `see ${s.link.label}` : "this row is for information"}`);
+ if (s.disabled) return fail(s.disabled);
+ if (s.tick && !opts.ticked) return fail(`tick "${s.tick}" first`);
+ const unknown = s.actions.find((a) => !runners[a.op]);
+ if (unknown) return fail(`not a writer this page runs: ${unknown.op}`);
+ if (opts.dryRun && s.actions.some((a) => !SPACE_DRY_RUNNABLE.has(a.op))) {
+ return fail(`${s.actions[0].op} has no dry run that answers here: the numbers above are the scan's`);
+ }
+ const out: SpaceRunOutcome = { ok: true, lines: [], jobIds: [], dryRun: opts.dryRun };
+ for (let i = 0; i < s.actions.length; i++) {
+ const a = s.actions[i];
+ const r = await runners[a.op](a.body, { dryRun: opts.dryRun }).catch((e: Error) => fail(e.message));
+ out.lines.push(...r.lines);
+ out.jobIds.push(...r.jobIds);
+ if (!r.ok) {
+ out.ok = false;
+ const rest = s.actions.length - i - 1;
+ if (rest > 0) out.lines.push(`${rest} more not run`);
+ break;
+ }
+ }
+ return out;
+}
diff --git a/editor/app/cleanup/space/page.tsx b/editor/app/cleanup/space/page.tsx
@@ -0,0 +1,278 @@
+import type { Metadata } from "next";
+import Link from "next/link";
+import { formatBytes } from "yt-dlp-transcript-common/lib/format";
+import {
+ ageText,
+ diskNeedOrder,
+ fullestDiskId,
+ groupSuggestions,
+ suggestionsForDisk,
+ usedPercent,
+ type SpaceArchiveShare,
+ type SpaceDisk,
+} from "yt-dlp-transcript-common/lib/spaceSuggestions";
+import { CleanupTabs } from "../components/CleanupTabs";
+import { SpaceRefresh } from "./components/SpaceRefresh";
+import { SpaceRow } from "./components/SpaceRow";
+import { loadSpace } from "./lib/loadSpace";
+
+// FREE UP SPACE (lane space-suggestions): every disk the archive writes to,
+// fullest first, and what would free space on the one picked — each through
+// the writer that already exists. Everything here is the last space scan's
+// file (controller/spaceScan.ts) plus each disk's free space now; the page
+// never walks, stats the corpus or probes a container.
+export const dynamic = "force-dynamic";
+
+export const metadata: Metadata = { title: "Free up space" };
+
+const SHARE: { key: keyof SpaceArchiveShare; label: string; color: string }[] = [
+ { key: "media", label: "Media", color: "var(--chart-1)" },
+ { key: "text", label: "Text", color: "var(--chart-2)" },
+ { key: "clips", label: "Clip windows", color: "var(--chart-3)" },
+ { key: "store", label: "Saved videos", color: "var(--chart-4)" },
+ { key: "playable", label: "Playable copies", color: "var(--chart-5)" },
+ { key: "builds", label: "Site builds", color: "var(--chart-2)" },
+ { key: "reports", label: "umtool reports", color: "var(--chart-3)" },
+ { key: "other", label: "Index and other", color: "var(--chart-4)" },
+];
+
+export default async function SpacePage({ searchParams }: { searchParams: Promise<{ disk?: string }> }) {
+ const { disk: diskParam } = await searchParams;
+ const { result, live, job } = await loadSpace();
+ const disks = result ? diskNeedOrder(result.disks, result.floorBytes) : [];
+ const fullest = result ? fullestDiskId(result.disks, result.floorBytes) : null;
+ const selected = disks.find((d) => d.id === diskParam && d.status === "ok")?.id ?? fullest;
+ const diskLabel = Object.fromEntries(disks.map((d) => [d.id, d.label]));
+ const list = result && selected ? suggestionsForDisk(result, selected) : [];
+ const groups = groupSuggestions(list);
+ const overflow = result?.overflow.filter((o) => o.disk === selected) ?? [];
+
+ return (
+ <div className="flex flex-col gap-6">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h1 className="text-2xl font-semibold">Cleanup</h1>
+ </div>
+ <CleanupTabs active="space" />
+
+ <section aria-label="space scan" className="flex flex-wrap items-center justify-between gap-3">
+ <p className="text-sm text-muted-foreground">
+ {result ? (
+ <>
+ Scanned {ageText(result.computedAt)} ({Math.round(result.tookMs / 1000)} s)
+ {result.compactionAt && result.compactionAt !== result.computedAt
+ ? ` · compaction rows from ${ageText(result.compactionAt)}`
+ : ""}
+ </>
+ ) : (
+ "No scan yet."
+ )}
+ </p>
+ <SpaceRefresh running={job} />
+ </section>
+
+ {result && (
+ <>
+ <section aria-label="disks" className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
+ {disks.map((d) => (
+ <DiskCard key={d.id} d={d} free={live[d.id] ?? d.freeBytes} fullest={d.id === fullest} selected={d.id === selected} floor={result.floorBytes} />
+ ))}
+ </section>
+
+ <section aria-label="suggestions" className="flex flex-col gap-4">
+ <h2 className="text-lg font-semibold">
+ {selected ? `What frees space on ${diskLabel[selected] ?? selected}` : "No disk to free"}
+ </h2>
+ {groups.length === 0 && <p className="text-sm text-muted-foreground">Nothing the scan found frees space here.</p>}
+ {groups.map((g) => (
+ <div key={g.kind} className="rounded-xl border border-border bg-card px-4 py-3" aria-label={`group ${g.kind}`}>
+ <div className="flex flex-wrap items-baseline justify-between gap-2">
+ <h3 className="font-medium">{g.label}</h3>
+ <span className="font-mono text-sm tabular-nums">
+ {g.bytes > 0 ? formatBytes(g.bytes) : g.laterLow > 0 ? `later ~${formatBytes(g.laterLow)}–${formatBytes(g.laterHigh)}` : "—"}
+ </span>
+ </div>
+ <ul className="mt-1">
+ {g.rows.map((s) => (
+ <SpaceRow key={s.key} s={s} diskLabel={diskLabel} />
+ ))}
+ </ul>
+ {overflow
+ .filter((o) => o.kind === g.kind)
+ .map((o) => (
+ <p key={o.kind} className="mt-1 text-xs text-muted-foreground">
+ And {o.count.toLocaleString("en-US")} more ({formatBytes(o.bytes)})
+ {o.link ? (
+ <>
+ {" "}
+ — <Link href={o.link.href} className="underline">{o.link.label}</Link>
+ </>
+ ) : null}
+ </p>
+ ))}
+ </div>
+ ))}
+ </section>
+
+ {result.held.length > 0 && (
+ <details className="rounded-xl border border-border bg-card px-4 py-3" aria-label="held">
+ <summary className="cursor-pointer font-medium">Held: not offered ({result.held.length})</summary>
+ <ul className="mt-2 flex flex-col gap-1 text-sm">
+ {result.held.map((h) => (
+ <li key={h.key} className="flex flex-wrap justify-between gap-2">
+ <span>
+ {h.what}: {h.why}
+ {h.link ? (
+ <>
+ {" "}
+ — <Link href={h.link.href} className="underline">{h.link.label}</Link>
+ </>
+ ) : null}
+ </span>
+ <span className="font-mono tabular-nums text-muted-foreground">
+ {h.bytes !== null ? formatBytes(h.bytes) : "—"}
+ {h.disk ? ` · ${diskLabel[h.disk] ?? h.disk}` : ""}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </details>
+ )}
+
+ {result.refused.length > 0 && (
+ <details className="rounded-xl border border-border bg-card px-4 py-3" aria-label="refused by the compaction selector">
+ <summary className="cursor-pointer font-medium">
+ Saved videos the compaction selector does not pick ({formatBytes(result.refused.reduce((n, g) => n + g.bytes, 0))})
+ </summary>
+ <ul className="mt-2 flex flex-col gap-1 text-sm">
+ {result.refused.map((g) => (
+ <li key={g.group} className="flex flex-col gap-0.5">
+ <span className="flex flex-wrap justify-between gap-2">
+ <span>
+ {g.group}: {g.count.toLocaleString("en-US")} container(s)
+ </span>
+ <span className="font-mono tabular-nums text-muted-foreground">{formatBytes(g.bytes)}</span>
+ </span>
+ <span className="text-xs text-muted-foreground">
+ Biggest:{" "}
+ {g.examples.map((e, i) => (
+ <span key={`${e.slug}/${e.id}`}>
+ {i ? ", " : ""}
+ <Link href={`/channels/${e.slug}/videos/${e.id}`} className="underline">
+ {e.slug}/{e.id}
+ </Link>{" "}
+ {formatBytes(e.bytes)}
+ </span>
+ ))}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </details>
+ )}
+
+ {result.unmanaged.length > 0 && (
+ <details className="rounded-xl border border-border bg-card px-4 py-3" aria-label="no writer here">
+ <summary className="cursor-pointer font-medium">The archive's, with no writer here ({formatBytes(result.unmanaged.reduce((n, u) => n + u.bytes, 0))})</summary>
+ <ul className="mt-2 flex flex-col gap-1 text-sm">
+ {result.unmanaged.map((u) => (
+ <li key={u.key} className="flex flex-wrap justify-between gap-2">
+ <span>
+ {u.what}: {u.owner}
+ {u.command ? (
+ <>
+ {" "}
+ — <code className="font-mono text-xs">{u.command}</code>
+ </>
+ ) : null}
+ {u.link ? (
+ <>
+ {" "}
+ — <Link href={u.link.href} className="underline">{u.link.label}</Link>
+ </>
+ ) : null}
+ </span>
+ <span className="font-mono tabular-nums text-muted-foreground">
+ {formatBytes(u.bytes)}
+ {u.disk ? ` · ${diskLabel[u.disk] ?? u.disk}` : ""}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </details>
+ )}
+
+ {result.notScanned.length > 0 && (
+ <details className="rounded-xl border border-border bg-card px-4 py-3" aria-label="not scanned">
+ <summary className="cursor-pointer font-medium">Channels not scanned ({result.notScanned.length})</summary>
+ <ul className="mt-2 flex flex-col gap-1 text-sm">
+ {result.notScanned.map((n) => (
+ <li key={n.slug}>
+ <Link href={`/channels/${n.slug}`} className="underline">{n.slug}</Link>: {n.why}
+ </li>
+ ))}
+ </ul>
+ </details>
+ )}
+
+ <p className="text-xs text-muted-foreground">
+ Each button runs the existing writer for its kind, which refuses what it refuses when it runs.{" "}
+ <code className="font-mono">pnpm ops get space-suggestions</code> answers the same list.
+ </p>
+ </>
+ )}
+ </div>
+ );
+}
+
+function DiskCard({ d, free, fullest, selected, floor }: { d: SpaceDisk; free: number | null; fullest: boolean; selected: boolean; floor: number }) {
+ if (d.status !== "ok") {
+ return (
+ <div className="flex flex-col gap-1 rounded-xl border border-dashed border-border bg-card p-4 text-sm text-muted-foreground" aria-label={`disk ${d.id}`}>
+ <span className="font-medium text-foreground">{d.label}</span>
+ <span>{d.status === "not-mounted" ? "Not mounted" : "Not answering"}</span>
+ {d.detail && <span className="text-xs">{d.detail}</span>}
+ </div>
+ );
+ }
+ const size = d.sizeBytes ?? 0;
+ const pct = usedPercent(d, free);
+ const share = d.archive;
+ const seg = (n: number) => (size > 0 ? `${(n / size) * 100}%` : "0%");
+ const used = size > 0 && free !== null ? size - free : 0;
+ const notArchive = Math.max(0, used - (d.archiveBytes ?? 0));
+ return (
+ <Link
+ href={`/cleanup/space?disk=${encodeURIComponent(d.id)}`}
+ aria-label={`disk ${d.id}`}
+ aria-current={selected ? "true" : undefined}
+ className={`flex flex-col gap-2 rounded-xl border bg-card p-4 text-sm ${selected ? "border-foreground" : "border-border hover:border-muted-foreground"}`}
+ >
+ <div className="flex flex-wrap items-baseline justify-between gap-2">
+ <span className="font-medium">{d.label}</span>
+ {fullest && <span className="rounded bg-destructive/15 px-1.5 py-0.5 font-mono text-[11px] uppercase text-destructive">fullest</span>}
+ </div>
+ <span className="text-xs text-muted-foreground">
+ {d.mountpoint ?? "?"} · {d.roles.join(", ")}
+ </span>
+ <div className="flex h-2 w-full overflow-hidden rounded-full bg-muted" role="img" aria-label={`${d.label} usage`}>
+ {share && SHARE.map((c) => <span key={c.key} className="h-full" style={{ width: seg(share[c.key]), background: c.color }} />)}
+ <span className="h-full bg-muted-foreground/40" style={{ width: seg(notArchive) }} />
+ </div>
+ <span className="font-mono text-xs tabular-nums">
+ {free !== null ? `${formatBytes(free)} free` : "free ?"} of {size ? formatBytes(size) : "?"}
+ {pct !== null ? ` · ${pct} % used` : ""}
+ {floor > 0 && free !== null && free < floor ? " · under the floor" : ""}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ The archive's: {formatBytes(d.archiveBytes ?? 0)}
+ {share
+ ? ` (${SHARE.filter((c) => share[c.key] > 0)
+ .map((c) => `${c.label.toLowerCase()} ${formatBytes(share[c.key])}`)
+ .join(", ")})`
+ : ""}
+ {" · "}not the archive's: {formatBytes(notArchive)}
+ </span>
+ {d.detail && <span className="text-xs text-amber-600 dark:text-amber-400">{d.detail}</span>}
+ </Link>
+ );
+}
diff --git a/editor/app/lib/nav.ts b/editor/app/lib/nav.ts
@@ -119,7 +119,7 @@ export const NAV_GROUPS: NavGroup[] = [
links: [
{ href: "/jobs", label: "Jobs", icon: ListChecks, badgeKey: "jobs", keywords: "queue tasks active running live monitor stuck" },
{ href: "/workers", label: "Workers", icon: Cpu, keywords: "transcription whisper gpu" },
- { href: "/cleanup", label: "Cleanup", icon: Trash2, badgeKey: "cleanable", keywords: "clean reclaim disk space prune audio" },
+ { href: "/cleanup", label: "Cleanup", icon: Trash2, badgeKey: "cleanable", keywords: "clean reclaim disk space prune audio free up compaction compact move platter" },
{ href: "/storage", label: "Storage", icon: HardDrive, keywords: "drive disk platter mount volume media location relocate cold" },
{ href: "/saved-videos", label: "Saved videos", icon: Bookmark, keywords: "backup" },
{ href: "/cookies", label: "Cookies", icon: Cookie, keywords: "cookie refresh rumble x twitter youtube odysee archive.today forum kiwi farms cf_clearance session login jar stale recheck connect" },