commit 6489ec1e98a2e66a203cc2bec37d150e0e3aec6d
parent 077ce80951cae49c713ecf0c664047d6a025e545
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 9 Nov 2026 21:51:51 -0500
storage: /storage, the dashboard and ops get storage say how each drive is
Every /storage location row carries its drive's health view (drive:
ok | slow | stalled | unmounted, since, lastOkAt, latencyMs, detector,
cause, text), which is what `pnpm ops get storage` now reports per
location. The page shows it as a Drive line ("answering — 12 ms (a read in
the editor), last at 11:42", "slow at 11:42 — …", "not answering since
11:35 — …", "not mounted") and a "slow" chip beside an Available status.
The dashboard gets a drive banner (new polled view `driveHealth`,
storage/lib/driveHealth.ts): one card per location whose drive is not
answering (an alert), slow (a status), or not mounted with channels on it,
each saying what it means and linking /storage and the location's channels.
Nothing asks a drive in-process: the health record is memory and the mount
half is /storage's 10 s probe memo; channel configs are read only when a
drive is in trouble.
E2e seam: POST /api/test/drive-health records a stall or a slow sighting
for a configured location (no hung mount); e2e/drive-health.spec.ts.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
13 files changed, 549 insertions(+), 1 deletion(-)
diff --git a/common/controller/storageWatch.test.ts b/common/controller/storageWatch.test.ts
@@ -24,6 +24,7 @@ import {
import { inspectChannelMedia } from "../lib/channelMedia";
import {
applyHealthTimings,
+ driveHealthView,
healthTimings,
locationHealth,
resetStorageHealth,
@@ -708,3 +709,48 @@ test("the pass writes under the settings lock: a writer holding it is not interl
assert.equal(tierOf(h, "gone"), "paused");
});
});
+
+// THE PROBE'S STATE MACHINE WITH A FAKE PROBER (lane drive-stall): the
+// verdicts a detector gives, pass by pass, and the view every surface reports
+// from them — ok, slow (an answer at half the budget or more), stalled (no
+// answer: the gate refuses), ok again after two clean passes. No drive, no
+// subprocess: the probe is a script.
+test("a fake prober walks the drive ok -> slow -> stalled -> ok, and the gate follows only the stall", async () => {
+ await withTmp(async (h) => {
+ await seedRelocated(h, "on-cold", { targetExists: true });
+ const verdicts = [
+ { answer: "ok" as const, detector: "stat" as const, latencyMs: 4 },
+ { answer: "ok" as const, detector: "stat" as const, latencyMs: 2_200 },
+ { answer: "stalled" as const, detector: "stat" as const, cause: "a stat of its root did not answer within 3 s" },
+ { answer: "ok" as const, detector: "stat" as const, latencyMs: 6 },
+ { answer: "ok" as const, detector: "stat" as const, latencyMs: 5 },
+ ];
+ let i = 0;
+ const probe = async () => verdicts[Math.min(i++, verdicts.length - 1)];
+ const loc = { id: "cold", label: "Cold" };
+ const view = () => driveHealthView(loc, locationHealth("cold"));
+ const pass = () => runStorageHealthPass({ io: h.io, probe });
+
+ await pass();
+ assert.equal(view().state, "ok");
+ assert.equal(view().latencyMs, 4);
+ assert.equal(typeof view().lastOkAt, "number");
+
+ await pass();
+ assert.equal(view().state, "slow");
+ assert.match(String(view().cause), /^a stat of its root took 2.2 s$/);
+ // Slow is shown, never acted on: the channel's media still answers ok.
+ assert.equal((await inspectChannelMedia(h.paths, "on-cold", undefined, { fresh: true })).status, "ok");
+
+ await pass();
+ assert.equal(view().state, "stalled");
+ assert.equal((await inspectChannelMedia(h.paths, "on-cold", undefined, { fresh: true })).status, "stalled");
+
+ await pass(); // one clean answer: still stalled
+ assert.equal(view().state, "stalled");
+ await pass(); // two in a row: answering again, and not slow
+ assert.equal(view().state, "ok");
+ assert.equal(view().latencyMs, 5);
+ assert.equal((await inspectChannelMedia(h.paths, "on-cold", undefined, { fresh: true })).status, "ok");
+ });
+});
diff --git a/common/views/names.ts b/common/views/names.ts
@@ -30,6 +30,10 @@ export const VIEW_NAMES = [
// /review's X run console (common/controller/xRun.ts xRunConsole): the
// latest run, the X posts channels, the jar's age. Reads disk only.
"xRun",
+ // The dashboard's drive banner (editor/app/storage/lib/driveHealth.ts):
+ // every storage location whose drive is slow, not answering or not mounted.
+ // The health record is memory; the mount half is /storage's 10 s probe memo.
+ "driveHealth",
] as const;
export type ViewName = (typeof VIEW_NAMES)[number];
@@ -58,4 +62,5 @@ export const VIEW_CONTRACT: Record<ViewName, "observe" | "construct"> = {
cleanable: "construct",
cookieAlerts: "construct",
xRun: "construct",
+ driveHealth: "construct",
};
diff --git a/common/views/storage.test.ts b/common/views/storage.test.ts
@@ -507,3 +507,59 @@ test("a location whose drive is not answering reads so, and says since when", ()
}).rows[0];
assert.equal(quiet.notAnswering, undefined);
});
+
+// THE DRIVE'S HEALTH ON EACH ROW (lane drive-stall) — what `pnpm ops get
+// storage` reports: the shell's view, carried as it is; the internal row has
+// none. `probeMounted` is the mount half of it.
+test("each location row carries its drive's health view; the internal row none", async () => {
+ const { driveHealthView, recordLocationHealth, registerLocationHealth, noteDriveAnswer, locationHealth, resetStorageHealth } =
+ await import("../lib/storageHealth");
+ const { probeMounted } = await import("./storage");
+ resetStorageHealth();
+ const cold = loc("cold", "/mnt/cold");
+ const warm = loc("warm", "/mnt/warm");
+ const gone = loc("gone", "/mnt/gone");
+ registerLocationHealth([cold, warm, gone], NOW);
+ recordLocationHealth(cold, "stalled", { now: NOW, cause: "its disk (sdz) had 1 request(s) in flight and completed none in 15 s" });
+ noteDriveAnswer("warm", 2_400, "call", NOW);
+ const probes = {
+ cold: { status: "stalled" as const, identity: { known: false as const }, probedAt: NOW },
+ warm: { status: "available" as const, identity: { known: false as const }, probedAt: NOW },
+ gone: { status: "unmounted" as const, identity: { known: false as const }, probedAt: NOW },
+ };
+ const drives = Object.fromEntries(
+ [cold, warm, gone].map((l) => [
+ l.id,
+ driveHealthView(l, locationHealth(l.id), { now: NOW, mounted: probeMounted(probes[l.id as keyof typeof probes].status) }),
+ ]),
+ );
+ const { rows } = buildStorageRows({
+ locations: [cold, warm, gone],
+ defaultLocationId: "",
+ probes,
+ drives,
+ rollups: {},
+ internal: { root: "/corpus/channels" },
+ registry: NO_JOBS,
+ now: NOW,
+ });
+ const by = Object.fromEntries(rows.map((r) => [r.id, r]));
+ assert.equal(by.internal.drive, undefined);
+ assert.equal(by.cold.drive?.state, "stalled");
+ assert.equal(by.cold.drive?.since, NOW);
+ assert.match(String(by.cold.drive?.text), /^not answering since \d\d:\d\d — its disk \(sdz\)/);
+ assert.equal(by.warm.drive?.state, "slow");
+ assert.equal(by.warm.drive?.latencyMs, 2_400);
+ assert.equal(by.warm.drive?.lastOkAt, NOW);
+ assert.match(String(by.warm.drive?.text), /^slow at \d\d:\d\d — a read in the editor took 2.4 s$/);
+ assert.equal(by.gone.drive?.state, "unmounted");
+ assert.equal(by.gone.drive?.text, "not mounted");
+ // The mount half: available is mounted, stalled did not ask, the rest are not.
+ assert.equal(probeMounted("available"), true);
+ assert.equal(probeMounted("stalled"), undefined);
+ assert.equal(probeMounted(undefined), undefined);
+ for (const st of ["unmounted", "absent", "missing", "mounted-elsewhere"] as const) {
+ assert.equal(probeMounted(st), false);
+ }
+ resetStorageHealth();
+});
diff --git a/common/views/storage.ts b/common/views/storage.ts
@@ -9,6 +9,7 @@ import type {
} from "../controller/storageLocations";
import type { SavedVideosStoreStatus } from "../controller/relocateSavedVideos";
import type { RegistryReader } from "./inputs";
+import type { DriveHealthView } from "../lib/storageHealth";
// THE /storage PAYLOAD — one row per storage location, and for each row the
// list of things the operator may do to it and why the rest are withheld.
@@ -115,6 +116,12 @@ export type StorageRow = {
// "not answering since 11:35 — …", while the health probe finds this
// location's drive not answering (lib/storageHealth.ts). Absent otherwise.
notAnswering?: string;
+ // THE DRIVE'S HEALTH (lane drive-stall): answering, slow, not answering or
+ // not mounted, with when it last answered and how fast
+ // (lib/storageHealth.ts `driveHealthView`). What `pnpm ops get storage`
+ // reports per location. Absent on the internal row, and when the shell
+ // passed none.
+ drive?: DriveHealthView;
warning?: string;
candidateRoot?: string;
// Why every action on this row is withheld, or null. One re-point runs at a
@@ -235,6 +242,9 @@ export type StorageRowsInputs = {
// Worded by the shell (lib/storageHealth.ts's `notAnsweringText`), because
// this module takes types only from lib/.
notAnswering?: Record<string, string | undefined>;
+ // By location id: the drive's health view, built by the shell from the
+ // health record and this probe (`driveHealthView`).
+ drives?: Record<string, DriveHealthView | undefined>;
rollups: Record<string, LocationRollup | undefined>;
registry: RegistryReader;
udisksctlAvailable?: boolean;
@@ -254,6 +264,14 @@ export const STORAGE_STATUS_LABEL: Record<StorageLocationStatus, string> = {
stalled: "Not answering",
};
+// WHETHER A PROBE STATUS MEANS THE DRIVE IS MOUNTED, for the drive's health
+// view: `available` is, `stalled` did not ask (the health record decides), and
+// every other status is a root that is not there. Undefined for no probe.
+export function probeMounted(status: StorageLocationStatus | undefined): boolean | undefined {
+ if (status === undefined || status === "stalled") return undefined;
+ return status === "available";
+}
+
export const REPOINT_JOB_KIND = "repoint-storage-location";
export const SAVED_VIDEOS_JOB_KIND = "relocate-saved-videos";
@@ -453,6 +471,7 @@ export function buildStorageRows(i: StorageRowsInputs): StorageRowsPayload {
...(i.notAnswering?.[loc.id]
? { notAnswering: i.notAnswering[loc.id] }
: {}),
+ ...(i.drives?.[loc.id] ? { drive: i.drives[loc.id] } : {}),
...(probe?.warning ? { warning: probe.warning } : {}),
...(candidateRoot ? { candidateRoot } : {}),
busy,
diff --git a/editor/app/api/test/drive-health/route.ts b/editor/app/api/test/drive-health/route.ts
@@ -0,0 +1,53 @@
+import { NextResponse } from "next/server";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import {
+ noteDriveSlow,
+ recordLocationHealth,
+ registerLocationHealth,
+} from "yt-dlp-transcript-common/lib/storageHealth";
+import { forgetChannelMedia } from "yt-dlp-transcript-common/lib/channelMedia";
+import { resetStorageProbeMemo } from "yt-dlp-transcript-common/controller/storageLocations";
+import { testRouteDenied } from "../_guard";
+
+export const dynamic = "force-dynamic";
+
+// E2E test harness only (guarded by `E2E_TEST_ROUTES`, see _guard.ts).
+//
+// A STALLED DRIVE WITHOUT A HUNG MOUNT. No fixture can make a real drive stop
+// answering, and none should: this records what a detector would have said
+// about a configured location — `stalled` (one answer marks it, as the
+// counters or the watchdog would) or `slow` (the watchdog's slow refusal) —
+// into the process's health record, which every gate, page and poll reads.
+// The health pass then sees the fixture's drive answering and clears a stall
+// after `clearAfterCleanPasses` passes (30 s at the defaults), so a spec
+// asserts within that window. `/api/test/invalidate-cache` forgets it all.
+//
+// POST {"id": "<location id>", "state": "stalled" | "slow", "cause"?: "…"}
+export async function POST(req: Request) {
+ const denied = testRouteDenied();
+ if (denied) return denied;
+ const body = (await req.json().catch(() => ({}))) as {
+ id?: string;
+ state?: string;
+ cause?: string;
+ };
+ const loc = getSettings().storage.locations.find((l) => l.id === body.id);
+ if (!loc) {
+ return NextResponse.json({ error: `no storage location "${body.id}"` }, { status: 404 });
+ }
+ registerLocationHealth([loc]);
+ if (body.state === "stalled") {
+ recordLocationHealth(loc, "stalled", {
+ cause: body.cause ?? "a read in the editor did not answer within 3 s",
+ });
+ } else if (body.state === "slow") {
+ noteDriveSlow(loc.id, body.cause ?? "a read in the editor took 2.4 s");
+ } else {
+ return NextResponse.json({ error: `state must be "stalled" or "slow"` }, { status: 400 });
+ }
+ // The channels' five-second answers and the ten-second probes, so the next
+ // page sees the drive as it is now.
+ forgetChannelMedia();
+ resetStorageProbeMemo();
+ return NextResponse.json({ ok: true });
+}
diff --git a/editor/app/api/view/views.ts b/editor/app/api/view/views.ts
@@ -12,6 +12,7 @@ import { buildSchedulerStatusPayload } from "../../scheduler/status";
import { widgetSyncInputs } from "../../widget/lib/syncInputs";
import { cleanableChannels } from "../../cleanup/lib/loadCleanup";
import { loadCookieAlerts } from "../../lib/cookieAlerts";
+import { buildDriveHealthPayload } from "../../storage/lib/driveHealth";
import { xRunConsole } from "yt-dlp-transcript-common/controller/xRun";
import {
loadActionableSummary,
@@ -83,6 +84,11 @@ export const VIEWS: Record<ViewName, (req: Request) => Promise<Response>> = {
// recorded job's status.
cookieAlerts: async () => NextResponse.json(await loadCookieAlerts(getPaths())),
+ // The dashboard's drive banner: the storage locations whose drive is slow,
+ // not answering or not mounted. Polled slow; the health record is memory and
+ // the mount probe is memoised 10 s (no drive is asked in-process).
+ driveHealth: async () => NextResponse.json(await buildDriveHealthPayload()),
+
// /review's X run console: the latest run (each channel's state, the
// summary), the X posts channels in the default order and the jar's age
// against social.x.maxCookieAgeMinutes. Disk reads only; nothing asks X.
diff --git a/editor/app/components/dashboard/DashboardCockpit.tsx b/editor/app/components/dashboard/DashboardCockpit.tsx
@@ -10,6 +10,8 @@ import { NeedsWorkPanel } from "./NeedsWorkPanel";
import { QuickAddPanel } from "./QuickAddPanel";
import { FirstRunPanel, type FirstRunState } from "./FirstRunPanel";
import { CookieAlertsPanel } from "./CookieAlertsPanel";
+import { DriveHealthBanner } from "./DriveHealthBanner";
+import type { DriveHealthPayload } from "../../storage/lib/driveHealth";
import type { ServiceCookieAlertsPayload } from "yt-dlp-transcript-common/lib/serviceCookies";
import type { ChannelRowView } from "yt-dlp-transcript-common/views/channelRow";
import { ChannelsTable } from "../../channels/components/ChannelsTable";
@@ -40,9 +42,12 @@ export type DashboardCockpitInitial = {
firstRun?: FirstRunState | null;
// The cookie refresh alerts (lib/cookieAlerts.ts), polled SLOW after this.
cookieAlerts?: ServiceCookieAlertsPayload;
+ // The drive banner (storage/lib/driveHealth.ts), polled SLOW after this.
+ driveHealth?: DriveHealthPayload;
};
const EMPTY_COOKIE_ALERTS: ServiceCookieAlertsPayload = { alerts: [], pending: [] };
+const NO_DRIVE_TROUBLE: DriveHealthPayload = { drives: [] };
// The mission-control cockpit. A server component (app/page.tsx) SSRs the
// initial payloads for a flicker-free first paint; this client shell then polls
@@ -87,9 +92,17 @@ export function DashboardCockpit({
initial.cookieAlerts ?? EMPTY_COOKIE_ALERTS,
);
+ const { data: driveHealth } = usePolledPayload<DriveHealthPayload>(
+ "/api/view/driveHealth",
+ true,
+ SLOW_MS,
+ initial.driveHealth ?? NO_DRIVE_TROUBLE,
+ );
+
return (
<div className="flex flex-col gap-6">
<h1 className="sr-only">Dashboard</h1>
+ <DriveHealthBanner data={driveHealth ?? NO_DRIVE_TROUBLE} />
<CookieAlertsPanel
data={cookieAlerts ?? EMPTY_COOKIE_ALERTS}
onChange={() => void refetchCookieAlerts()}
diff --git a/editor/app/components/dashboard/DriveHealthBanner.tsx b/editor/app/components/dashboard/DriveHealthBanner.tsx
@@ -0,0 +1,84 @@
+"use client";
+
+// THE DRIVE BANNER (lane drive-stall): one card per storage location whose
+// drive is not answering, slow, or not mounted with channels on it — the
+// dashboard's top slot, beside the cookie banners. Not answering and not
+// mounted are different troubles with different fixes, so they read
+// differently: a drive that is here and stalled (a USB enclosure resetting)
+// is waited out, or unplugged and replugged; a drive that is not mounted is
+// mounted. The words come from the server (lib/storageHealth.ts
+// `driveHealthView`), so /storage and this banner cannot disagree.
+
+import Link from "next/link";
+import type {
+ DriveHealthBannerRow,
+ DriveHealthPayload,
+} from "../../storage/lib/driveHealth";
+
+const HEADLINE: Record<Exclude<DriveHealthBannerRow["state"], "ok">, string> = {
+ stalled: "is not answering",
+ slow: "is answering slowly",
+ unmounted: "is not mounted",
+};
+
+const WHAT_HAPPENS: Record<Exclude<DriveHealthBannerRow["state"], "ok">, string> = {
+ stalled:
+ "Pages and polls skip it and its channels' jobs are held until it answers again; nothing else in the editor waits on it.",
+ slow: "Everything still runs; reads on it take longer than they should.",
+ unmounted: "Its channels' jobs are held until it is back.",
+};
+
+function DriveCard({ drive }: { drive: DriveHealthBannerRow }) {
+ if (drive.state === "ok") return null;
+ const severe = drive.state !== "slow";
+ return (
+ <section
+ role={severe ? "alert" : "status"}
+ aria-label={`drive ${drive.id}`}
+ data-state={drive.state}
+ className={`rounded-md border bg-card px-4 py-3 ${
+ severe ? "border-destructive/50" : "border-amber-500/50"
+ }`}
+ >
+ <p
+ className={`text-sm font-medium ${
+ severe ? "text-destructive" : "text-amber-700 dark:text-amber-300"
+ }`}
+ >
+ The media drive {drive.label} {HEADLINE[drive.state]}
+ </p>
+ <p className="text-xs" aria-label={`drive ${drive.id} health`}>
+ {drive.text}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {WHAT_HAPPENS[drive.state]}
+ {" · "}
+ <Link href="/storage" className="underline underline-offset-2 hover:text-foreground">
+ Storage
+ </Link>
+ {drive.channels > 0 && (
+ <>
+ {" · "}
+ <Link
+ href={drive.channelsHref}
+ className="underline underline-offset-2 hover:text-foreground"
+ >
+ {drive.channels} channel(s) on it
+ </Link>
+ </>
+ )}
+ </p>
+ </section>
+ );
+}
+
+export function DriveHealthBanner({ data }: { data: DriveHealthPayload }) {
+ if (data.drives.length === 0) return null;
+ return (
+ <div aria-label="drive health" className="flex flex-col gap-2">
+ {data.drives.map((d) => (
+ <DriveCard key={d.id} drive={d} />
+ ))}
+ </div>
+ );
+}
diff --git a/editor/app/page.tsx b/editor/app/page.tsx
@@ -20,6 +20,7 @@ import { buildWidgetSyncPayload } from "yt-dlp-transcript-common/views/widgetSyn
import { widgetSyncInputs } from "./widget/lib/syncInputs";
import { DashboardCockpit } from "./components/dashboard/DashboardCockpit";
import { loadCookieAlerts } from "./lib/cookieAlerts";
+import { buildDriveHealthPayload } from "./storage/lib/driveHealth";
import {
buildChannelRowView,
channelVolumeOf,
@@ -134,10 +135,11 @@ export default async function Dashboard({
// active site for the SSR seed.
const actionable = buildWidgetActionablePayload(widgetActionableRows(rows));
- const [jobs, sync, cookieAlerts] = await Promise.all([
+ const [jobs, sync, cookieAlerts, driveHealth] = await Promise.all([
buildActiveJobsPayload(),
widgetSyncInputs().then(buildWidgetSyncPayload),
loadCookieAlerts(paths),
+ buildDriveHealthPayload(),
]);
const workers = buildWorkersPayload();
const changelogSource = loadChangelog();
@@ -153,6 +155,7 @@ export default async function Dashboard({
changelogSource,
firstRun: summary.rows.length === 0 ? firstRunState(paths) : null,
cookieAlerts,
+ driveHealth,
}}
/>
);
diff --git a/editor/app/storage/buildStorage.ts b/editor/app/storage/buildStorage.ts
@@ -4,11 +4,14 @@ import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
import { getFreeBytes } from "yt-dlp-transcript-common/lib/diskSpace";
import { udisksctlAvailable } from "yt-dlp-transcript-common/lib/storageVolumes";
import {
+ driveHealthView,
healthTimings,
isDriveNotAnswering,
+ locationHealth,
notAnsweringText,
onDrive,
stalledLocation,
+ type DriveHealthView,
} from "yt-dlp-transcript-common/lib/storageHealth";
import { clearRuleText } from "yt-dlp-transcript-common/lib/storageHealthTimings";
import { listChannelBriefs } from "yt-dlp-transcript-common/controller/channels";
@@ -24,6 +27,7 @@ import {
import { pathExists } from "yt-dlp-transcript-common/controller/relocateDir";
import {
buildStorageRows,
+ probeMounted,
type StorageRowsPayload,
} from "yt-dlp-transcript-common/views/storage";
@@ -136,6 +140,18 @@ export async function buildStorage(): Promise<StorageRowsPayload> {
`Pages and polls skip this drive until it answers ${clears}.${watched}`;
}
}
+ // EACH DRIVE'S HEALTH, from memory and this render's probe: answering, slow,
+ // not answering or not mounted (lib/storageHealth.ts `driveHealthView`). A
+ // record for another root under the same id (a re-point the pass has not
+ // seen yet) is not this drive's.
+ const drives: Record<string, DriveHealthView> = {};
+ for (const loc of locations) {
+ const h = locationHealth(loc.id);
+ drives[loc.id] = driveHealthView(loc, h && h.root === loc.root ? h : undefined, {
+ now,
+ mounted: probeMounted(probes[loc.id]?.status),
+ });
+ }
const store = await inspectSavedVideosStore(paths, settings);
// A store on a location walks that location's drive: through the watchdog,
// so a drive that stops answering mid-walk leaves the size at 0 (the store's
@@ -173,6 +189,7 @@ export async function buildStorage(): Promise<StorageRowsPayload> {
defaultLocationId: settings.storage.defaultLocationId,
probes,
notAnswering,
+ drives,
rollups,
registry: getRegistry(),
udisksctlAvailable: udisksctl,
diff --git a/editor/app/storage/components/StorageLocationsTable.tsx b/editor/app/storage/components/StorageLocationsTable.tsx
@@ -173,6 +173,17 @@ function LocationCard({
>
{row.statusLabel}
</span>
+ {/* SLOW IS NOT A STATUS: the drive is there and answering, a beat
+ late (lib/storageHealth.ts `driveHealthView`). A chip beside the
+ status, so "Available" stays true and the slowness is still seen. */}
+ {row.drive?.state === "slow" && (
+ <span
+ aria-label="location slow"
+ className="rounded-full border border-amber-500/50 bg-amber-500/10 px-2 py-0.5 text-xs font-medium text-amber-700 dark:text-amber-300"
+ >
+ slow
+ </span>
+ )}
{row.isDefault && (
<span className="rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground">
default
@@ -264,6 +275,16 @@ function LocationCard({
</dd>
<dt className="text-muted-foreground">Last probe</dt>
<dd aria-label="location last probe">{formatAge(row.lastProbeAgeMs)}</dd>
+ {/* THE DRIVE'S HEALTH in one line: answering (how fast, when last),
+ slow, not answering since, or not mounted. */}
+ {row.drive && (
+ <>
+ <dt className="text-muted-foreground">Drive</dt>
+ <dd aria-label="location drive" className="text-xs">
+ {row.drive.text}
+ </dd>
+ </>
+ )}
</dl>
{row.notAnswering && (
diff --git a/editor/app/storage/lib/driveHealth.ts b/editor/app/storage/lib/driveHealth.ts
@@ -0,0 +1,71 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { locationOfDataDir } from "yt-dlp-transcript-common/lib/storageLocations";
+import {
+ driveHealthView,
+ locationHealth,
+ type DriveHealthView,
+} from "yt-dlp-transcript-common/lib/storageHealth";
+import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels";
+import { probeAllLocations } from "yt-dlp-transcript-common/controller/storageLocations";
+import {
+ channelsHrefForLocation,
+ probeMounted,
+} from "yt-dlp-transcript-common/views/storage";
+
+// THE DASHBOARD'S DRIVE BANNER — every storage location whose drive is slow,
+// not answering or not mounted, and how many channels have their media there.
+//
+// NOTHING HERE ASKS A DRIVE IN-PROCESS. The health record is memory (the
+// health pass and the watchdog write it, lib/storageHealth.ts), and the mount
+// half is the same probe /storage renders from: memoised 10 s, a stalled
+// location answered without a call. The channel configs are read only when
+// some drive is in trouble — the corpus disk, one small file per channel —
+// because a drive nobody's media is on is not worth a banner when it is merely
+// unplugged.
+//
+// SERVER ONLY (it reaches the controller, which imports execa).
+
+export type DriveHealthBannerRow = DriveHealthView & {
+ // Channels whose media is on this location (by `mediaDir`, or a legacy
+ // channel's retired `dataDir`).
+ channels: number;
+ // `/channels?location=<id>`: the list of them.
+ channelsHref: string;
+};
+
+export type DriveHealthPayload = { drives: DriveHealthBannerRow[] };
+
+export async function buildDriveHealthPayload(): Promise<DriveHealthPayload> {
+ const paths = getPaths();
+ const locations = getSettings().storage.locations;
+ if (locations.length === 0) return { drives: [] };
+ const probes = await probeAllLocations(locations, paths);
+ const now = Date.now();
+ const troubled = locations
+ .map((loc) => {
+ const h = locationHealth(loc.id);
+ return driveHealthView(loc, h && h.root === loc.root ? h : undefined, {
+ now,
+ mounted: probeMounted(probes[loc.id]?.status),
+ });
+ })
+ .filter((v) => v.state !== "ok");
+ if (troubled.length === 0) return { drives: [] };
+ const counts = new Map<string, number>();
+ for (const { config } of await listChannelConfigs(paths)) {
+ const dir = config.mediaDir?.trim() || config.dataDir?.trim();
+ const loc = dir ? locationOfDataDir(dir, locations) : null;
+ if (loc) counts.set(loc.id, (counts.get(loc.id) ?? 0) + 1);
+ }
+ return {
+ drives: troubled
+ .map((v) => ({
+ ...v,
+ channels: counts.get(v.id) ?? 0,
+ channelsHref: channelsHrefForLocation(v.id),
+ }))
+ // An unplugged drive with nobody's media on it is not news.
+ .filter((v) => v.state !== "unmounted" || v.channels > 0),
+ };
+}
diff --git a/editor/e2e/drive-health.spec.ts b/editor/e2e/drive-health.spec.ts
@@ -0,0 +1,154 @@
+import { mkdir, rm, symlink, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { test, expect, type Page } from "@playwright/test";
+import { baseUrl } from "./baseUrl";
+import { readJson, resetData, resolvePath, testPaths, writeSettings } from "./helpers";
+
+// A DRIVE THAT IS NOT ANSWERING, ONE THAT IS SLOW, ONE THAT IS NOT MOUNTED —
+// and that /storage and the dashboard tell them apart (lane drive-stall).
+//
+// NO FIXTURE HANGS A MOUNT. `/api/test/drive-health` records what a detector
+// would have said about a configured location (a stall, or the watchdog's
+// slow refusal) into the editor's health record, which every gate, page and
+// poll reads; the health pass then sees the fixture's drive answering and
+// clears a stall after two clean passes (15–30 s), so each step marks the
+// drive again just before it looks. "Not mounted" is real: the location's
+// root is removed. The detectors and the state machine are unit-tested
+// (common/lib/storageHealth.test.ts, controller/storageWatch.test.ts).
+
+const AUTH = { authorization: "Bearer test-worker-token" };
+const SLUG = "test-youtube";
+const VIDEO = "20240101_test1234567";
+
+const channelDir = () => resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}`);
+
+// The fixture channel's media tier on `root`, as a finished move leaves it
+// (storage-locations.spec.ts builds it the same way).
+async function relocateOnDisk(root: string): Promise<void> {
+ const target = join(root, SLUG, "media");
+ await mkdir(join(target, VIDEO), { recursive: true });
+ await writeFile(join(target, VIDEO, "audio.mp3"), "ID3audio");
+ await symlink(
+ join("..", "..", "media", VIDEO, "audio.mp3"),
+ join(channelDir(), "data", VIDEO, "audio.mp3"),
+ );
+ await symlink(target, join(channelDir(), "media"));
+ const config = await readJson<Record<string, unknown>>(
+ `${testPaths().transcriptsDir}/channels/${SLUG}/config.json`,
+ );
+ await writeFile(
+ join(channelDir(), "config.json"),
+ JSON.stringify({ ...config, mediaDir: target }, null, 2) + "\n",
+ );
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+}
+
+async function mark(id: string, state: "stalled" | "slow"): Promise<void> {
+ const res = await fetch(`${baseUrl}/api/test/drive-health`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ id, state }),
+ });
+ expect(res.ok, await res.clone().text()).toBe(true);
+}
+
+async function setUp(root: string): Promise<void> {
+ await resetData("one-youtube-channel-with-data");
+ await mkdir(root, { recursive: true });
+ await relocateOnDisk(root);
+ await writeSettings({
+ adminTitle: "Test Admin",
+ minFreeDiskGB: 0,
+ storage: {
+ locations: [{ id: "cold", label: "Cold", root, autoRepoint: false }],
+ defaultLocationId: "cold",
+ },
+ });
+}
+
+function row(page: Page, id: string) {
+ return page.getByLabel(`storage location: ${id}`);
+}
+
+test("a stalled drive reads 'not answering' on /storage and the dashboard; an unmounted one 'not mounted'", async ({
+ page,
+}, testInfo) => {
+ test.setTimeout(120_000);
+ const root = testInfo.outputPath("platter");
+ await setUp(root);
+
+ // --- not answering ------------------------------------------------------
+ await mark("cold", "stalled");
+ await page.goto("/storage");
+ const cold = row(page, "cold");
+ await expect(cold.getByLabel("location status")).toHaveText("Not answering");
+ await expect(cold.getByLabel("location drive")).toHaveText(/^not answering since \d\d:\d\d — /);
+ await expect(cold.getByLabel("location slow")).toHaveCount(0);
+
+ await mark("cold", "stalled");
+ await page.goto("/");
+ const card = page.getByLabel("drive cold", { exact: true });
+ await expect(card).toBeVisible();
+ await expect(card).toHaveAttribute("data-state", "stalled");
+ await expect(card).toHaveAttribute("role", "alert");
+ await expect(card).toContainText("The media drive Cold is not answering");
+ await expect(page.getByLabel("drive cold health")).toHaveText(/^not answering since \d\d:\d\d/);
+ await expect(card.getByRole("link", { name: "1 channel(s) on it" })).toHaveAttribute(
+ "href",
+ "/channels?location=cold",
+ );
+
+ // --- the drive answers again: no banner -----------------------------------
+ await fetch(`${baseUrl}/api/test/invalidate-cache`);
+ await page.goto("/");
+ await expect(page.getByRole("heading", { name: "Dashboard" })).toBeAttached();
+ await expect(page.getByLabel("drive health")).toHaveCount(0);
+
+ // --- not mounted (the root is gone; its channel's media was on it) --------
+ await rm(root, { recursive: true, force: true });
+ await fetch(`${baseUrl}/api/test/invalidate-cache`);
+ await page.goto("/");
+ const gone = page.getByLabel("drive cold", { exact: true });
+ await expect(gone).toHaveAttribute("data-state", "unmounted");
+ await expect(gone).toContainText("The media drive Cold is not mounted");
+ await expect(page.getByLabel("drive cold health")).toHaveText("not mounted");
+ await page.goto("/storage");
+ await expect(row(page, "cold").getByLabel("location status")).not.toHaveText("Not answering");
+ await expect(row(page, "cold").getByLabel("location drive")).toHaveText("not mounted");
+});
+
+test("a slow drive stays Available with a slow chip, and its dashboard card is a status, not an alert", async ({
+ page,
+}, testInfo) => {
+ test.setTimeout(120_000);
+ const root = testInfo.outputPath("platter");
+ await setUp(root);
+
+ await mark("cold", "slow");
+ await page.goto("/storage");
+ const cold = row(page, "cold");
+ await expect(cold.getByLabel("location status")).toHaveText("Available");
+ await expect(cold.getByLabel("location slow")).toHaveText("slow");
+ await expect(cold.getByLabel("location drive")).toHaveText(
+ /^slow at \d\d:\d\d — a read in the editor took 2.4 s$/,
+ );
+
+ await mark("cold", "slow");
+ await page.goto("/");
+ const card = page.getByLabel("drive cold", { exact: true });
+ await expect(card).toHaveAttribute("data-state", "slow");
+ await expect(card).toHaveAttribute("role", "status");
+ await expect(card).toContainText("The media drive Cold is answering slowly");
+
+ // `pnpm ops get storage` reports the same view per location.
+ await mark("cold", "slow");
+ const res = await page.request.get(`${baseUrl}/api/ops/storage`, { headers: AUTH });
+ expect(res.ok(), await res.text()).toBe(true);
+ const body = (await res.json()) as {
+ storage: { rows: Array<{ id: string; drive?: { state: string; text: string; lastOkAt?: number } }> };
+ };
+ const drive = body.storage.rows.find((r) => r.id === "cold")?.drive;
+ expect(drive?.state).toBe("slow");
+ expect(drive?.text).toMatch(/^slow at /);
+ expect(body.storage.rows.find((r) => r.id === "internal")?.drive).toBeUndefined();
+});