commit 3cf6b2cbbe229d592d6bdfda497b2e8e3d794858
parent 2f11fc510c8eda9e555019a930406d1d69a109a7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 01:10:08 -0500
editor, ops: one truthful answer for a live recording, and its failure said everywhere
- GET /api/ops/live-recordings and `pnpm ops get live-recordings
[<slug>[/<id>]] [--all]`: each run from its own record (status, job,
bytes, last growth, stalled, attempts, fallback, lost, needsAttention,
reason, check).
- POST /api/ops/live-recording-ack and `pnpm ops live-recording-ack`
({slug, id, startedAt?, by?}): seen; listed still, counted no more.
- record-live answers {ok, jobId, kind, check}; `pnpm ops record-live
--wait-started` returns once the run's media bytes grow (its row on
stdout) or with the reason it failed; 15 min by default.
- every reply through ops()/readRoute() carries
`x-archilyzer-attention: live-recordings=N` while N > 0 (cached 30 s),
and the client prints one stderr line for it.
- /review "Live recordings that need you", and the same rows as a banner on
/jobs, the channel page and the video page: the reason, Record again
(record-live with the run's own url and recording keys), Acknowledge.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
20 files changed, 688 insertions(+), 17 deletions(-)
diff --git a/common/controller/liveRecordings.test.ts b/common/controller/liveRecordings.test.ts
@@ -117,3 +117,10 @@ test("the default listing: recording, needing a person, or of the last week; --a
assert.ok(all.includes("exmplold001"));
assert.equal((await loadLiveRecordingRows(paths, SLUG)).length, all.length);
});
+
+test("record-live's reply names the command that answers for the recording", async () => {
+ const { recordLiveCheckCommand } = await import("./recordLive");
+ assert.equal(recordLiveCheckCommand("demo-yt", { url: "https://www.youtube.com/watch?v=exampleid01" }), "pnpm ops get live-recordings demo-yt/exampleid01");
+ assert.equal(recordLiveCheckCommand("demo-yt", { id: "exampleid02" }), "pnpm ops get live-recordings demo-yt/exampleid02");
+ assert.equal(recordLiveCheckCommand("demo-kick", { url: "https://kick.com/somechannel" }), "pnpm ops get live-recordings demo-kick", "a Kick channel's VOD is found in the job");
+});
diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts
@@ -81,6 +81,7 @@ import {
} from "../lib/liveCapture";
import { liveRecordingSidecar } from "../lib/mediaImport-server";
import { rowOfRecord, upsertLiveRecordingRow } from "../lib/liveRecordings-server";
+import { liveRecordingCheckCommand } from "./liveRecordings";
import { setDoNotClean } from "../lib/doNotClean-server";
import type { Paths } from "../lib/paths";
import { detectPlatform } from "../lib/platform";
@@ -271,6 +272,16 @@ export async function resolveRecordLivePlan(
return { ...plan, id };
}
+// The command that answers for this recording (the record-live reply's
+// `check`): its id from the body's `id`, else the URL's; a Kick channel URL
+// (its VOD is found in the job) names the channel alone.
+export function recordLiveCheckCommand(slug: string, body: { id?: unknown; url?: unknown }): string {
+ const id = typeof body.id === "string" && body.id.trim() ? body.id.trim() : null;
+ const plan = !id && typeof body.url === "string" ? planForUrl(body.url.trim()) : null;
+ const known = id ?? (plan && !("error" in plan) ? plan.id : null);
+ return known ? liveRecordingCheckCommand(slug, known) : `pnpm ops get live-recordings ${slug}`;
+}
+
export function recordLiveQueueKey(slug: string, id: string | null, kickChannel?: string): string {
return `record-live:${slug}:${id ?? `kick-${kickChannel ?? "?"}`}`;
}
@@ -713,6 +724,18 @@ type RunHooks = {
const isMustKeep = (req: RecordLiveRequest) => req.doNotClean === true || Boolean(req.note);
+// The request's recording keys, as the channel's row keeps them (what "Record
+// again" asks again).
+export function recordAgainRequest(req: RecordLiveRequest): Record<string, unknown> {
+ const out: Record<string, unknown> = {};
+ for (const k of ["fromStart", "maxHeight", "separate", "transcribe", "doNotClean", "note"] as const) {
+ if (req[k] !== undefined) out[k] = req[k];
+ }
+ return out;
+}
+
+const rowExtra = (req: RecordLiveRequest) => ({ ...(req.note ? { note: req.note } : {}), request: recordAgainRequest(req) });
+
// THE RUN, AND ITS FAILURE RECORDED. Every way a recording can end without a
// landing leaves a row in channels/<slug>/live-recordings.json that says why
// (lib/liveRecordings-server.ts): the run's own saves write it; a throw the
@@ -752,7 +775,7 @@ export async function recordLiveRun(
mustKeep: isMustKeep(opts.request),
...(opts.jobId ? { jobId: opts.jobId } : {}),
},
- opts.request.note ? { note: opts.request.note } : {},
+ rowExtra(opts.request),
),
});
}
@@ -916,7 +939,7 @@ async function recordLiveRunInner(
const save = async () => {
await liveRecordingSidecar.write(videoDir, record);
try {
- await upsertLiveRecordingRow(paths, req.slug, rowOfRecord(id, record, req.note ? { note: req.note } : {}));
+ await upsertLiveRecordingRow(paths, req.slug, rowOfRecord(id, record, rowExtra(req)));
} catch (err) {
if (!rowWarned) say(`The channel's live recordings could not be written (${(err as Error).message}).`);
rowWarned = true;
@@ -1287,8 +1310,8 @@ export async function runRecordLiveJob(
paths,
channelSlug: req.slug,
...(plan.id ? { videoId: plan.id } : {}),
- fn: async (onLog, signal) => {
- await recordLiveRun({ ...opts, plan, onLog, signal });
+ fn: async (onLog, signal, _progress, ctx) => {
+ await recordLiveRun({ ...opts, plan, onLog, signal, jobId: ctx.jobId });
await opts.afterRun?.();
},
});
diff --git a/common/lib/liveRecordings-server.ts b/common/lib/liveRecordings-server.ts
@@ -41,6 +41,9 @@ export type LiveRecordingRow = {
lost?: LostSpan;
mustKeep: boolean;
note?: string;
+ // What record-live was asked (its body's recording keys, no `id`/`dryRun`/
+ // `preclip`): what "Record again" asks again.
+ request?: Record<string, unknown>;
streamStartedAt?: string;
parts: LivePart[];
landedPart?: number;
@@ -114,7 +117,7 @@ async function mutate<T>(
export function rowOfRecord(
id: string,
rec: LiveRecordingRecord,
- extra: { note?: string } = {},
+ extra: { note?: string; request?: Record<string, unknown> } = {},
): Omit<LiveRecordingRow, "acknowledgedAt" | "acknowledgedBy" | "supersededBy"> {
return {
id,
@@ -132,6 +135,7 @@ export function rowOfRecord(
...(rec.lost ? { lost: rec.lost } : {}),
mustKeep: rec.mustKeep === true,
...(extra.note ? { note: extra.note } : {}),
+ ...(extra.request ? { request: extra.request } : {}),
...(rec.streamStartedAt ? { streamStartedAt: rec.streamStartedAt } : {}),
parts: rec.parts.map((p) => ({ ...p })),
...(rec.landedPart !== undefined ? { landedPart: rec.landedPart } : {}),
diff --git a/editor/app/api/ops/_attention.ts b/editor/app/api/ops/_attention.ts
@@ -0,0 +1,41 @@
+import type { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { countLiveRecordingsNeedingAttention } from "yt-dlp-transcript-common/controller/liveRecordings";
+
+// WHAT NEEDS A PERSON, ON EVERY REPLY OF THE OPS DOOR. An agent polling the
+// editor reads replies, not pages: a live recording that failed (or lost its
+// start, or was interrupted) is said in a header on every answer `ops()` and
+// `readRoute()` give —
+//
+// x-archilyzer-attention: live-recordings=<N>
+//
+// — only when N > 0, and `pnpm ops` prints one stderr line for it. The count
+// (controller/liveRecordings.ts) is cached 30 s: it reads each channel's
+// live-recordings.json, and a reply must not wait for that every time.
+
+export const ATTENTION_HEADER = "x-archilyzer-attention";
+const TTL_MS = 30_000;
+
+let cached: { at: number; n: number } | null = null;
+
+export async function liveRecordingsAttention(now = Date.now()): Promise<number> {
+ if (cached && now - cached.at < TTL_MS) return cached.n;
+ const n = await countLiveRecordingsNeedingAttention(getPaths()).catch(() => 0);
+ cached = { at: now, n };
+ return n;
+}
+
+// For a write that changed the answer (an acknowledgement): the next reply counts again.
+export function forgetAttention(): void {
+ cached = null;
+}
+
+export async function withAttention(res: NextResponse): Promise<NextResponse> {
+ try {
+ const n = await liveRecordingsAttention();
+ if (n > 0) res.headers.set(ATTENTION_HEADER, `live-recordings=${n}`);
+ } catch {
+ /* a reply is never refused for its header */
+ }
+ return res;
+}
diff --git a/editor/app/api/ops/_door.test.ts b/editor/app/api/ops/_door.test.ts
@@ -113,6 +113,7 @@ test("a traversing slug is refused at the door, on every route that takes one",
["find-clips", { slug: "../../escape", id: "abc123" }],
["import-media", { slug: "../../escape", path: "/tmp/ops-api-never.mp4", id: "abc123" }],
["record-live", { slug: "../../escape", url: "https://rumble.com/v1abcde-x.html" }],
+ ["live-recording-ack", { slug: "../../escape", id: "abc123" }],
["live-preclip", { slug: "../../escape", id: "abc123", action: "status" }],
["live-clip", { slug: "../../escape", id: "abc123", start: 1, end: 20 }],
["keep-videos", { slug: "../../escape", ids: ["abc123"] }],
diff --git a/editor/app/api/ops/_lib.ts b/editor/app/api/ops/_lib.ts
@@ -6,6 +6,7 @@ import { isValidSiteId, listSiteIds } from "yt-dlp-transcript-common/lib/site";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
import type { QueueOutcome } from "../../channels/lib/queueForSlugs";
+import { withAttention } from "./_attention";
// THE OPS API IS ADAPTERS, AND NOTHING ELSE.
//
@@ -74,11 +75,12 @@ export async function ops(
}`,
);
}
+ // Every answer says what needs a person (./_attention.ts).
try {
- return await run(body as OpsBody);
+ return await withAttention(await run(body as OpsBody));
} catch (e) {
- if (e instanceof OpsInputError) return opsFail(e.message);
- return opsFail((e as Error).message, 500);
+ if (e instanceof OpsInputError) return withAttention(opsFail(e.message));
+ return withAttention(opsFail((e as Error).message, 500));
}
}
diff --git a/editor/app/api/ops/_liveRecordings.test.ts b/editor/app/api/ops/_liveRecordings.test.ts
@@ -0,0 +1,73 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { TOKEN, callGet, callPost, setupOpsCorpus } from "./_testCorpus";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_liveRecordings.test.ts"
+//
+// THE LIVE RECORDINGS DOOR (lane live-recording-guard): `get live-recordings`
+// answers each run from its own row, `live-recording-ack` acknowledges, and
+// every ops reply carries the attention header while something needs a
+// person. A temp corpus; the row is written through the one writer.
+
+const corpus = await setupOpsCorpus(null);
+test.after(() => corpus.cleanup());
+
+const SLUG = "demo-live";
+await corpus.writeChannelConfig(SLUG, { platform: "youtube", url: "https://www.youtube.com/@Example" });
+const { getPaths } = await import("yt-dlp-transcript-common/lib/paths");
+const { upsertLiveRecordingRow } = await import("yt-dlp-transcript-common/lib/liveRecordings-server");
+await upsertLiveRecordingRow(getPaths(), SLUG, {
+ id: "exampleid01",
+ url: "https://www.youtube.com/watch?v=exampleid01",
+ platform: "youtube",
+ startedAt: new Date().toISOString(),
+ endedAt: new Date().toISOString(),
+ status: "failed",
+ fromStart: true,
+ error: "nothing was recorded — 6 attempts (3 from its start, 3 from the live edge): ERROR: The downloaded file is empty",
+ attempts: 6,
+ mustKeep: true,
+ parts: [],
+});
+
+const list = (await import("./live-recordings/route")).GET as unknown as Parameters<typeof callGet>[0];
+const ack = (await import("./live-recording-ack/route")).POST as unknown as Parameters<typeof callPost>[0];
+const authed = { authorization: `Bearer ${TOKEN}` };
+
+test("get live-recordings lists the failure, and the reply carries the attention header", async () => {
+ const res = await list(new Request(`http://localhost/api/ops/live-recordings?slug=${SLUG}`, { headers: authed }), { params: Promise.resolve({}) });
+ assert.equal(res.status, 200);
+ assert.equal(res.headers.get("x-archilyzer-attention"), "live-recordings=1");
+ const body = (await res.json()) as { needsAttention: number; rows: { id: string; status: string; needsAttention: boolean; check: string }[] };
+ assert.equal(body.needsAttention, 1);
+ assert.equal(body.rows[0]?.status, "failed");
+ assert.equal(body.rows[0]?.check, `pnpm ops get live-recordings ${SLUG}/exampleid01`);
+ const bad = await callGet(list, "http://localhost/api/ops/live-recordings?id=exampleid01");
+ assert.equal(bad.status, 400, "an id needs its slug");
+ const unknown = await callGet(list, "http://localhost/api/ops/live-recordings?slugs=x");
+ assert.equal(unknown.status, 400);
+});
+
+test("live-recording-ack acknowledges it: listed still, counted no more, and the header goes", async () => {
+ const refused = await callPost(ack, { slug: SLUG, id: "nosuchid001" });
+ assert.equal(refused.status, 400);
+ const traversing = await callPost(ack, { slug: "../../escape", id: "exampleid01" });
+ assert.equal(traversing.status, 400);
+ assert.match(String(traversing.body.error), /is not a valid channel slug/);
+ const res = await ack(
+ new Request("http://localhost/api/ops/live-recording-ack", {
+ method: "POST",
+ headers: { ...authed, "content-type": "application/json" },
+ body: JSON.stringify({ slug: SLUG, id: "exampleid01", by: "test" }),
+ }),
+ );
+ assert.equal(res.status, 200);
+ assert.deepEqual(await res.json(), { ok: true, acknowledged: 1 });
+ assert.equal(res.headers.get("x-archilyzer-attention"), null);
+ const after = await callGet(list, `http://localhost/api/ops/live-recordings?slug=${SLUG}`);
+ const rows = after.body.rows as { needsAttention: boolean; acknowledgedBy?: string }[];
+ assert.equal(rows.length, 1);
+ assert.equal(rows[0]?.needsAttention, false);
+ assert.equal(rows[0]?.acknowledgedBy, "test");
+});
diff --git a/editor/app/api/ops/_read.ts b/editor/app/api/ops/_read.ts
@@ -1,5 +1,6 @@
import { NextResponse } from "next/server";
import { opsAuth, opsFail } from "./_lib";
+import { withAttention } from "./_attention";
// THE READ SIDE'S DOOR (release 19, A3): `GET /api/ops/<noun>` routes that
// answer what an existing builder already builds for a page — settings, the
@@ -28,9 +29,9 @@ export async function readRoute(
}
try {
const out = await run(q);
- return out instanceof NextResponse ? out : NextResponse.json({ ok: true, ...out });
+ return withAttention(out instanceof NextResponse ? out : NextResponse.json({ ok: true, ...out }));
} catch (e) {
- return opsFail((e as Error).message, 500);
+ return withAttention(opsFail((e as Error).message, 500));
}
}
diff --git a/editor/app/api/ops/live-recording-ack/route.ts b/editor/app/api/ops/live-recording-ack/route.ts
@@ -0,0 +1,29 @@
+import { NextResponse } from "next/server";
+import { acknowledgeLiveRecordingAction } from "../../../channels/[slug]/liveMediaActions";
+import { forgetAttention } from "../_attention";
+import { ops, opsFail, reqSlug, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, id, startedAt?, by? } -> { ok: true, acknowledged }
+//
+// A PERSON HAS SEEN IT (controller/liveRecordings.ts): every run of the record
+// that needs a person — failed, interrupted, or recorded from the live edge
+// with the stream's start lost — or the one run `startedAt` names, is
+// acknowledged. The rows stay in `get live-recordings`; they no longer count
+// in /review, the banners or the attention header. /review's Acknowledge.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "id", "startedAt", "by"], async (body) => {
+ const slug = reqSlug(body, "slug");
+ const id = reqString(body, "id");
+ const r = await acknowledgeLiveRecordingAction({
+ slug,
+ id,
+ ...(typeof body.startedAt === "string" ? { startedAt: body.startedAt } : {}),
+ by: typeof body.by === "string" && body.by.trim() ? body.by.trim() : "agent:ops",
+ });
+ if (!r.ok) return opsFail(r.error);
+ forgetAttention();
+ return NextResponse.json(r);
+ });
+}
diff --git a/editor/app/api/ops/live-recordings/route.ts b/editor/app/api/ops/live-recordings/route.ts
@@ -0,0 +1,30 @@
+import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels";
+import { listLiveRecordings } from "yt-dlp-transcript-common/controller/liveRecordings";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { readRoute } from "../_read";
+import { opsFail } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// GET [?slug=<channel>[&id=<record id>]][&all=1]
+// -> { ok, needsAttention, stallMinutes, rows: [{ slug, id, url, status
+// (recording | interrupted | landed | failed | cancelled), job, bytes,
+// lastGrowthAt, stalled, streamElapsedSeconds, capturedSeconds,
+// attempts, fallback?, lost?, error?, mustKeep, needsAttention,
+// reason, check, parts, … }] }
+//
+// IS THIS STREAM BEING RECORDED, AND IS IT GROWING (controller/
+// liveRecordings.ts): each run from its own record, never from "a job for this
+// video id". Default: what is recording, what needs a person, and the last 7
+// days; `all=1` every run kept. Nothing is written.
+export async function GET(request: Request) {
+ return readRoute(request, ["slug", "id", "all"], async (q) => {
+ const slug = q.get("slug")?.trim() || undefined;
+ const id = q.get("id")?.trim() || undefined;
+ if (slug && !isValidChannelSlug(slug)) return opsFail(`"${slug}" is not a valid channel slug`);
+ if (id && !slug) return opsFail('"id" goes with "slug"');
+ if (id && !/^[\w.-]+$/.test(id)) return opsFail(`"${id}" is not a record id`);
+ const listing = await listLiveRecordings(getPaths(), { ...(slug ? { slug } : {}), ...(id ? { id } : {}), all: q.get("all") === "1" });
+ return { ...listing };
+ });
+}
diff --git a/editor/app/api/ops/record-live/route.ts b/editor/app/api/ops/record-live/route.ts
@@ -1,12 +1,18 @@
-import { RECORD_LIVE_BODY_KEYS } from "yt-dlp-transcript-common/controller/recordLive";
+import { NextResponse } from "next/server";
+import { RECORD_LIVE_BODY_KEYS, recordLiveCheckCommand } from "yt-dlp-transcript-common/controller/recordLive";
import { recordLiveAction } from "../../../channels/[slug]/liveMediaActions";
-import { jobResponse, ops, reqSlug } from "../_lib";
+import { ops, opsFail, reqSlug } from "../_lib";
export const dynamic = "force-dynamic";
// POST { slug, url? | id?, fromStart? (true), maxHeight? (720; null = tallest),
// separate? (YouTube true, else false), transcribe?, doNotClean?, note?,
-// dryRun? } -> { ok: true, jobId }
+// dryRun? } -> { ok: true, jobId, kind: "record-live", check }
+//
+// `check` is the command that answers for the recording afterwards (`pnpm ops
+// get live-recordings <slug>/<id>`): whether it records, grows, failed — from
+// its own record, never from "a job for this video id". `pnpm ops record-live
+// … --wait-started` polls it until media bytes are being written.
//
// A LIVE STREAM RECORDED UNTIL IT ENDS (controller/recordLive.ts;
// plans/live-capture.md): yt-dlp `--live-from-start` (Rumble's DVR playlist
@@ -19,7 +25,10 @@ export const dynamic = "force-dynamic";
// stops the recorders with SIGINT and lands what they have.
export async function POST(request: Request) {
return ops(request, RECORD_LIVE_BODY_KEYS, async (body) => {
- reqSlug(body, "slug");
- return jobResponse(await recordLiveAction(body));
+ const slug = reqSlug(body, "slug");
+ const result = await recordLiveAction(body);
+ if (!result.ok) return opsFail(result.error, 400, result.info ? { info: true } : undefined);
+ void result.stream.cancel();
+ return NextResponse.json({ ok: true, jobId: result.jobId, kind: "record-live", check: recordLiveCheckCommand(slug, body) });
});
}
diff --git a/editor/app/channels/[slug]/liveMediaActions.ts b/editor/app/channels/[slug]/liveMediaActions.ts
@@ -32,6 +32,8 @@ import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/
import { parseImportRequest } from "yt-dlp-transcript-common/lib/mediaImport";
import { isArchivePath, runImportMediaJob } from "yt-dlp-transcript-common/controller/importMedia";
import { parseRecordLiveRequest, runRecordLiveJob } from "yt-dlp-transcript-common/controller/recordLive";
+import { acknowledgeLiveRecording } from "yt-dlp-transcript-common/controller/liveRecordings";
+import { loadLiveRecordingRows } from "yt-dlp-transcript-common/lib/liveRecordings-server";
import {
finalizeLivePreclip,
livePreclipStatus,
@@ -120,6 +122,47 @@ export async function recordLiveAction(body: Record<string, unknown>): Promise<S
});
}
+// LIVE RECORDINGS THAT NEED A PERSON (controller/liveRecordings.ts):
+// acknowledgeLiveRecordingAction `pnpm ops live-recording-ack`, the
+// Acknowledge button on /review and the
+// banners: the rows stay listed, no longer
+// needing anyone.
+// recordLiveAgainAction the Record again button: record-live with
+// the run's own url and recording keys.
+export async function acknowledgeLiveRecordingAction(body: {
+ slug: string;
+ id: string;
+ startedAt?: string;
+ by?: string;
+}): Promise<{ ok: true; acknowledged: number } | { ok: false; error: string }> {
+ if (!isValidChannelSlug(body.slug)) return { ok: false, error: `"${body.slug}" is not a channel slug` };
+ if (!/^[\w.-]+$/.test(body.id)) return { ok: false, error: `"${body.id}" is not a record id` };
+ const r = await acknowledgeLiveRecording(getPaths(), {
+ slug: body.slug,
+ id: body.id,
+ ...(body.startedAt ? { startedAt: body.startedAt } : {}),
+ by: body.by ?? "editor",
+ });
+ if (r.ok) safeRevalidate(["/review", "/jobs", `/channels/${body.slug}`, `/channels/${body.slug}/videos/${body.id}`]);
+ return r;
+}
+
+export async function recordLiveAgainAction(body: {
+ slug: string;
+ id: string;
+ startedAt?: string;
+}): Promise<{ ok: true; jobId: string } | { ok: false; error: string; info?: boolean }> {
+ if (!isValidChannelSlug(body.slug)) return { ok: false, error: `"${body.slug}" is not a channel slug` };
+ const rows = await loadLiveRecordingRows(getPaths(), body.slug);
+ const row = [...rows].reverse().find((r) => r.id === body.id && (!body.startedAt || r.startedAt === body.startedAt));
+ if (!row || !row.url) return { ok: false, error: `${body.slug}/${body.id} has no live recording to record again` };
+ const r = await recordLiveAction({ ...(row.request ?? { fromStart: row.fromStart }), slug: body.slug, url: row.url });
+ if (!r.ok) return { ok: false, error: r.error, ...(r.info ? { info: true } : {}) };
+ void r.stream.cancel();
+ safeRevalidate(["/review", "/jobs", `/channels/${body.slug}`]);
+ return { ok: true, jobId: r.jobId };
+}
+
export type LivePreclipActionResult =
| { ok: true; action: "start"; jobId: string }
| { ok: true; action: "stop"; jobId: string }
diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx
@@ -1,4 +1,5 @@
import { displayPath, hidePrivateSites } from "yt-dlp-transcript-common/lib/privacy/privacy-server";
+import { LiveRecordingsAttention } from "../../components/LiveRecordingsAttention";
import { isPrivateSite } from "yt-dlp-transcript-common/lib/siteSchema";
import path from "node:path";
import { Suspense, type ReactNode } from "react";
@@ -993,6 +994,7 @@ export default async function ChannelDetailPage({
return (
<div className="flex flex-col gap-6">
{!existing && <NoReportYet slug={slug} />}
+ <LiveRecordingsAttention slug={slug} />
{/* MANUAL DOWNLOADS (lib/manualDownloads.ts): said at the top, so a
channel whose listing is mostly undownloaded is not read as stalled. */}
diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx
@@ -1,4 +1,5 @@
import type { Metadata } from "next";
+import { LiveRecordingsAttention } from "../../../../components/LiveRecordingsAttention";
import Link from "next/link";
import { notFound } from "next/navigation";
import path from "node:path";
@@ -342,6 +343,7 @@ export default async function VideoDetailPage({
<span>/</span>
<span className="font-mono">{id}</span>
</div>
+ <LiveRecordingsAttention slug={slug} id={id} />
<header className="flex flex-col gap-2">
{/* h2, not h1. The channel layout above this route owns the page's
diff --git a/editor/app/components/LiveRecordingActions.tsx b/editor/app/components/LiveRecordingActions.tsx
@@ -0,0 +1,66 @@
+"use client";
+
+// THE TWO ANSWERS TO A LIVE RECORDING THAT NEEDS A PERSON (LiveRecordingsAttention):
+// Record again — record-live with the run's own url and recording keys — and
+// Acknowledge — seen; the row stays in `pnpm ops get live-recordings` and no
+// longer counts. A failed press says so.
+
+import { useState, useTransition } from "react";
+import {
+ acknowledgeLiveRecordingAction,
+ recordLiveAgainAction,
+} from "../channels/[slug]/liveMediaActions";
+
+export function LiveRecordingActions({
+ slug,
+ id,
+ startedAt,
+ canRecordAgain,
+}: {
+ slug: string;
+ id: string;
+ startedAt: string;
+ canRecordAgain: boolean;
+}): React.ReactNode {
+ const [pending, startTransition] = useTransition();
+ const [said, setSaid] = useState<{ error: boolean; text: string } | null>(null);
+ const press = (fn: () => Promise<{ ok: boolean; error?: string } & Record<string, unknown>>, done: (r: Record<string, unknown>) => string) =>
+ startTransition(async () => {
+ try {
+ const r = await fn();
+ setSaid(r.ok ? { error: false, text: done(r) } : { error: true, text: r.error ?? "failed" });
+ } catch (e) {
+ setSaid({ error: true, text: (e as Error).message });
+ }
+ });
+ const btn = "rounded-md border border-border px-2 py-1 text-xs hover:bg-muted disabled:opacity-50";
+ return (
+ <span className="flex items-center gap-2 flex-wrap">
+ {canRecordAgain && (
+ <button
+ type="button"
+ aria-label={`record ${slug}/${id} again`}
+ disabled={pending}
+ className={btn}
+ onClick={() => press(() => recordLiveAgainAction({ slug, id, startedAt }), (r) => `Recording: job ${String(r.jobId)}`)}
+ >
+ Record again
+ </button>
+ )}
+ <button
+ type="button"
+ aria-label={`acknowledge ${slug}/${id}`}
+ disabled={pending}
+ className={btn}
+ onClick={() => press(() => acknowledgeLiveRecordingAction({ slug, id, startedAt }), () => "Acknowledged")}
+ >
+ Acknowledge
+ </button>
+ {said && (
+ <span role={said.error ? "alert" : "status"} className={`text-xs ${said.error ? "text-destructive" : "text-muted-foreground"}`}>
+ {said.text}
+ </span>
+ )}
+ </span>
+ );
+}
diff --git a/editor/app/components/LiveRecordingsAttention.tsx b/editor/app/components/LiveRecordingsAttention.tsx
@@ -0,0 +1,84 @@
+import Link from "next/link";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { listLiveRecordings, type LiveRecordingView } from "yt-dlp-transcript-common/controller/liveRecordings";
+import { LiveRecordingActions } from "./LiveRecordingActions";
+
+// LIVE RECORDINGS THAT NEED A PERSON (controller/liveRecordings.ts): failed,
+// interrupted, or recorded from the live edge with the stream's start lost.
+// One component for the four places it is said — /review's section, and the
+// banners on /jobs, the channel page and the video page (narrowed by `slug`,
+// `id`) — so all four say the same sentence. It stays until a person presses
+// Acknowledge or a later recording of the stream lands from its start.
+//
+// RENDERED ONLY WHEN THERE IS SOMETHING TO SAY, like /review's other sections.
+
+function when(iso: string): string {
+ return `${iso.slice(0, 16).replace("T", " ")} UTC`;
+}
+
+function Row({ r }: { r: LiveRecordingView }) {
+ return (
+ <li
+ aria-label={`live recording ${r.slug}/${r.id}`}
+ className="flex flex-col gap-1 border-t border-destructive/30 pt-2 first:border-t-0 first:pt-0"
+ >
+ <span className="flex items-center gap-2 flex-wrap">
+ <Link href={`/channels/${r.slug}/videos/${r.id}`} className="font-medium underline hover:text-foreground">
+ {r.slug}/{r.id}
+ </Link>
+ <span className="text-muted-foreground">
+ started {when(r.startedAt)} · {r.attempts} attempt{r.attempts === 1 ? "" : "s"}
+ {r.mustKeep ? " · must keep" : ""}
+ {r.job ? (
+ <>
+ {" · "}
+ <Link href={`/jobs/${r.job.id}`} className="underline hover:text-foreground">
+ job {r.job.status}
+ </Link>
+ </>
+ ) : null}
+ </span>
+ </span>
+ <span>{r.reason}</span>
+ <LiveRecordingActions slug={r.slug} id={r.id} startedAt={r.startedAt} canRecordAgain={r.status !== "recording" && Boolean(r.url)} />
+ </li>
+ );
+}
+
+export async function LiveRecordingsAttention({
+ slug,
+ id,
+ heading = false,
+}: {
+ slug?: string;
+ id?: string;
+ // /review: a section with a heading; elsewhere a banner.
+ heading?: boolean;
+}) {
+ let rows: LiveRecordingView[];
+ try {
+ rows = (await listLiveRecordings(getPaths(), { ...(slug ? { slug } : {}), ...(id ? { id } : {}) })).rows.filter((r) => r.needsAttention);
+ } catch {
+ return null;
+ }
+ if (rows.length === 0) return null;
+ const title = `Live recordings that need you (${rows.length})`;
+ return (
+ <section
+ aria-label="live recordings that need you"
+ data-live-recordings-attention=""
+ role={heading ? undefined : "alert"}
+ className="flex flex-col gap-2 rounded-md border border-destructive/30 bg-destructive-soft px-3 py-2 text-sm"
+ >
+ {heading ? <h2 className="text-lg font-semibold">{title}</h2> : <strong>{title}</strong>}
+ <ul className="flex flex-col gap-2">
+ {rows.map((r) => (
+ <Row key={`${r.slug}/${r.id}/${r.startedAt}`} r={r} />
+ ))}
+ </ul>
+ <span className="text-xs text-muted-foreground">
+ <code>pnpm ops get live-recordings</code> lists every recording; <code>pnpm ops live-recording-ack</code> is Acknowledge.
+ </span>
+ </section>
+ );
+}
diff --git a/editor/app/jobs/page.tsx b/editor/app/jobs/page.tsx
@@ -1,4 +1,5 @@
import type { Metadata } from "next";
+import { LiveRecordingsAttention } from "../components/LiveRecordingsAttention";
import { Suspense } from "react";
import Link from "next/link";
import {
@@ -82,6 +83,7 @@ export default async function JobsPage({
</div>
</div>
<RenderModeBanner />
+ <LiveRecordingsAttention />
<StreamErrorBoundary name="jobs-list" what="The job list">
<Suspense
fallback={
diff --git a/editor/app/review/page.tsx b/editor/app/review/page.tsx
@@ -1,4 +1,5 @@
import type { Metadata } from "next";
+import { LiveRecordingsAttention } from "../components/LiveRecordingsAttention";
import Link from "next/link";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import {
@@ -45,6 +46,7 @@ export default async function ReviewPage() {
return (
<div className="flex flex-col gap-6">
<h1 className="text-2xl font-semibold">Review</h1>
+ <LiveRecordingsAttention heading />
<AutoPausedSection rows={review.autoPaused} />
<PausedWatchesSection rows={review.pausedWatches} />
<XRunConsole initial={xRun} />
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -63,6 +63,9 @@
// pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'
// pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'
// pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'
+// pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","doNotClean":true}' --wait-started
+// pnpm ops get live-recordings demo-yt/<videoId>
+// pnpm ops live-recording-ack --json '{"slug":"demo-yt","id":"<videoId>"}'
// pnpm ops live-preclip --json '{"slug":"demo-yt","id":"<videoId>","action":"status"}'
// pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait
// pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'
@@ -395,6 +398,21 @@ const GETTERS = {
"generation-usage": (day) =>
day ? `/api/ops/generation-usage?day=${encodeURIComponent(day)}` : "/api/ops/generation-usage",
iterations: (article) => `/api/ops/iterations?article=${encodeURIComponent(article)}`,
+ // Every live recording, from its own record (controller/liveRecordings.ts):
+ // status (recording | interrupted | landed | failed | cancelled), bytes, last
+ // growth, stalled, attempts, a live-edge fallback and what it lost, and
+ // needsAttention. `<slug>` or `<slug>/<id>` narrows it; --all is every run kept.
+ "live-recordings": (arg, { all }) => {
+ const q = new URLSearchParams();
+ if (arg) {
+ const [slug, id] = String(arg).split("/");
+ if (slug) q.set("slug", slug);
+ if (id) q.set("id", id);
+ }
+ if (all) q.set("all", "1");
+ const s = q.toString();
+ return `/api/ops/live-recordings${s ? `?${s}` : ""}`;
+ },
};
// READS THAT ARE JOBS: the answer needs a request upstream, so the editor
@@ -436,6 +454,7 @@ const GET_ARG_OPTIONAL = new Set([
"render-mode",
"speakers",
"lookouts",
+ "live-recordings",
]);
// The flags each noun takes beyond the shared ones; any other is refused.
@@ -446,6 +465,7 @@ const GET_FLAGS = {
trending: ["topic", "limit", "accounts"],
job: ["tail"],
jobs: ["active", "failed", "kind", "slug", "limit"],
+ "live-recordings": ["all"],
};
// The row buttons of /jobs (`POST /api/ops/job`), as `job <verb> <id…>`.
@@ -542,6 +562,10 @@ const ACTIONS = [
// clip, project?, replace?}).
"live-preclip",
"live-clip",
+ // A live recording that failed, was interrupted or lost its start, seen by
+ // a person ({slug, id, startedAt?, by?}): it stays in `get live-recordings`
+ // and no longer counts as needing anyone. /review's Acknowledge.
+ "live-recording-ack",
// A channel's saved containers remuxed losslessly into browser-playable
// copies, one torrent each ({slug, ids?, trackers?, root?, dryRun?}).
"prepare-playable",
@@ -886,6 +910,9 @@ export function parseArgs(argv) {
let counts = false;
let leads = false;
let accounts = false;
+ let all = false;
+ // record-live only: return once media bytes are being written.
+ let waitStarted = false;
let tail = 0;
// `job resume-interrupted` only: list what would be re-queued.
let dryRun = false;
@@ -932,6 +959,11 @@ export function parseArgs(argv) {
} else if (arg === "--accounts") {
accounts = true;
used.add("accounts");
+ } else if (arg === "--all") {
+ all = true;
+ used.add("all");
+ } else if (arg === "--wait-started") {
+ waitStarted = true;
} else if (arg === "--active" || arg === "--failed") {
jobs[arg.slice(2)] = true;
used.add(arg.slice(2));
@@ -987,6 +1019,9 @@ export function parseArgs(argv) {
}
}
if (positional.length === 0) return { help: true };
+ if (waitStarted && positional[0] !== "record-live") {
+ return { error: "--wait-started goes with record-live" };
+ }
if (dryRun && !(positional[0] === "job" && positional[1] === "resume-interrupted")) {
return { error: '--dry-run goes with "job resume-interrupted" (elsewhere, a body\'s "dryRun": true)' };
}
@@ -1048,7 +1083,7 @@ export function parseArgs(argv) {
}
return {
method: "GET",
- path: GETTERS[noun](positional[2], { counts, leads, accounts, tail, jobs }),
+ path: GETTERS[noun](positional[2], { counts, leads, accounts, all, tail, jobs }),
wait: false,
quiet,
waitTimeout,
@@ -1133,6 +1168,7 @@ export function parseArgs(argv) {
...(action === "x-run" ? { resultMarker: X_RUN_RESULT_MARKER } : {}),
...(action === "read-x-trending" ? { resultMarker: READ_X_TRENDING_RESULT_MARKER } : {}),
...(action === "report-schedule" ? { resultMarker: REPORT_TICK_RESULT_MARKER } : {}),
+ ...(waitStarted ? { waitStarted: true } : {}),
wait,
quiet,
waitTimeout,
@@ -1161,6 +1197,89 @@ export function previewUrlsIn(payload) {
return [...new Set(urls)];
}
+// WHAT NEEDS A PERSON, said on every reply (editor/app/api/ops/_attention.ts):
+// the header `x-archilyzer-attention: live-recordings=<N>` becomes one stderr
+// line, so an agent that only ever reads replies still hears of a live
+// recording that failed, was interrupted or lost its start. Null when N is 0.
+export function attentionLine(headerValue) {
+ const m = /live-recordings=(\d+)/.exec(headerValue ?? "");
+ const n = m ? Number(m[1]) : 0;
+ return n > 0 ? `! ${n} live recording${n === 1 ? " needs" : "s need"} you: pnpm ops get live-recordings` : null;
+}
+
+// --wait-started: how often the recording is asked after, and for how long by
+// default (the attempts' schedule, 0/+60/+180 s twice over, is ~8 minutes).
+export const WAIT_STARTED_POLL_MS = 10_000;
+export const WAIT_STARTED_DEFAULT_SECONDS = 15 * 60;
+
+// One poll's verdict on the run's row: {ok: true} once media bytes are being
+// written (more than the poll before saw) or it landed; {ok: false, reason}
+// once it failed, was cancelled or interrupted; null: ask again.
+export function startedVerdict(row, prevBytes) {
+ if (!row) return null;
+ if (row.status === "failed" || row.status === "cancelled" || row.status === "interrupted") {
+ return { ok: false, reason: row.reason ?? row.status };
+ }
+ if (row.status === "landed") return { ok: true };
+ if (typeof row.bytes === "number" && row.bytes > 0 && prevBytes !== null && row.bytes > prevBytes) return { ok: true };
+ return null;
+}
+
+// RECORD-LIVE --wait-started: returns once the recording's own row (the run
+// whose jobId the reply named, in `get live-recordings`) shows media bytes
+// growing — or fails with the reason it gives. A job that ends with no row
+// at all (a refusal before the recording) fails with the job's status.
+// Answers {ok, row?, reason?}.
+export async function waitStarted(reply, slug, opts = {}) {
+ const doFetch = opts.fetch ?? fetch;
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
+ const now = opts.now ?? (() => Date.now());
+ const say = opts.say ?? ((line) => process.stderr.write(`${line}\n`));
+ const base = opts.baseUrl ?? baseUrl();
+ const headers = opts.headers ?? authHeaders();
+ const seconds = opts.timeoutSeconds > 0 ? opts.timeoutSeconds : WAIT_STARTED_DEFAULT_SECONDS;
+ const deadline = now() + seconds * 1000;
+ const id = /live-recordings \S+\/(\S+)$/.exec(reply.check ?? "")?.[1];
+ const listing = GETTERS["live-recordings"](id ? `${slug}/${id}` : slug, { all: true });
+ let prevBytes = null;
+ let lastSaid = null;
+ for (;;) {
+ let row = null;
+ try {
+ const res = await doFetch(`${base}${listing}`, { headers });
+ const payload = await res.json();
+ row = (payload.rows ?? []).find((r) => r.jobId === reply.jobId) ?? null;
+ } catch {
+ row = null;
+ }
+ const verdict = startedVerdict(row, prevBytes);
+ if (verdict) return { ...verdict, row };
+ if (!row) {
+ try {
+ const res = await doFetch(`${base}/api/ops/job/${encodeURIComponent(reply.jobId)}`, { headers });
+ const job = (await res.json())?.job;
+ if (job && ["done", "failed", "cancelled"].includes(job.status)) {
+ return job.status === "done"
+ ? { ok: true, row: null }
+ : { ok: false, row: null, reason: `job ${reply.jobId} ended ${job.status} before it recorded anything` };
+ }
+ } catch {
+ /* asked again next poll */
+ }
+ }
+ if (row) {
+ const line = `[${reply.jobId}] ${row.reason}`;
+ if (line !== lastSaid) say(line);
+ lastSaid = line;
+ prevBytes = typeof row.bytes === "number" ? row.bytes : prevBytes;
+ }
+ if (now() >= deadline) {
+ return { ok: false, row, reason: `--wait-started: no media bytes after ${seconds} s (${reply.check})` };
+ }
+ await sleep(WAIT_STARTED_POLL_MS);
+ }
+}
+
function printPreviewUrls(payload) {
for (const url of previewUrlsIn(payload)) console.error(`preview: ${url}`);
}
@@ -1231,6 +1350,8 @@ export function usage() {
" pnpm ops get transcript <videoId> [--slug <slug>]",
" pnpm ops get coverage <slug>",
" pnpm ops get generation-usage [<YYYY-MM-DD>] | iterations <article>",
+ " pnpm ops get live-recordings [<slug>[/<id>]] [--all]",
+ " pnpm ops record-live --json '<body>' --wait-started [--wait-timeout <seconds>]",
" pnpm ops list",
"",
`Actions: ${ACTIONS.join(", ")}`,
@@ -2410,6 +2531,34 @@ export function usage() {
' {"everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine",',
' "project"}, over settings.livePreclip) starts live-preclip once the first',
' part begins, and implies "transcribe".',
+ " A from-start attempt that records nothing (yt-dlp: \"The downloaded file",
+ " is empty\") is tried again at +60 and +180 s, then from the live edge at",
+ " 0, +60 and +180 s (each wait jittered); a stream that has ended, an argv",
+ " no try can fix and a Cancel are not retried. A live-edge fallback says",
+ " what it lost (the first N min of the stream) and needs a person. The",
+ ' reply is {jobId, kind, "check"}: the `get live-recordings` command that',
+ " answers for it. --wait-started returns once media bytes are being",
+ " written (the recording's row on stdout, exit 0) or with the reason it",
+ " failed (exit 1); 15 minutes by default, --wait-timeout overrides.",
+ "",
+ "get live-recordings [<slug>[/<id>]] [--all] is THE answer to \"is this",
+ " stream being recorded, and is it growing\" — never a job for the video",
+ " id (a live-chat job is one too). Per run, from its own record: status",
+ " (recording | interrupted: no job runs it | landed | failed | cancelled),",
+ " job, bytes, lastGrowthAt, stalled (not grown for",
+ " settings.liveRecording.stallMinutes, 10), streamElapsedSeconds,",
+ " capturedSeconds (once landed), attempts, fallback, lost, error, mustKeep,",
+ " needsAttention, reason, check. Default: what is recording, what needs a",
+ " person, the last 7 days; --all every run kept",
+ " (channels/<slug>/live-recordings.json, never pruned of a failure).",
+ " needsAttention (failed, interrupted, or the stream's start lost) stays",
+ " until live-recording-ack or a later recording that lands from the start;",
+ " /review, /jobs, the channel and video pages show the same rows, and",
+ " every ops reply then prints \"! N live recordings need you\" on stderr.",
+ "",
+ 'live-recording-ack {"slug", "id", "startedAt"?, "by"?} acknowledges every',
+ " run of the record that needs a person (or the one run startedAt names):",
+ " listed still, counted no more. /review's Acknowledge.",
"",
'live-preclip transcribes and mines a recording WHILE it records: {"slug",',
' "id", "action"?: "start" (default) | "stop" | "status" | "finalize"}, and',
@@ -3449,6 +3598,8 @@ async function main() {
...(parsed.method === "POST" ? { body: JSON.stringify(parsed.body) } : {}),
});
const text = await res.text();
+ const attention = attentionLine(res.headers?.get?.("x-archilyzer-attention"));
+ if (attention) console.error(attention);
let payload;
try {
payload = JSON.parse(text);
@@ -3462,8 +3613,16 @@ async function main() {
// A result-carrying action under --wait keeps stdout for the RESULT: the
// response goes to stderr with the log.
const resultMode = Boolean(parsed.wait && parsed.resultMarker);
- (resultMode ? console.error : console.log)(JSON.stringify(payload, null, 2));
+ (resultMode || parsed.waitStarted ? console.error : console.log)(JSON.stringify(payload, null, 2));
if (!res.ok || payload.ok === false) return 1;
+ if (parsed.waitStarted && payload.jobId) {
+ // stdout carries the recording's row once it is writing media.
+ const r = await waitStarted(payload, parsed.body.slug, { timeoutSeconds: parsed.waitTimeout ?? 0 });
+ if (r.row) console.log(JSON.stringify(r.row, null, 2));
+ if (!r.ok) console.error(r.reason);
+ else if (!r.row) console.error(`[${payload.jobId}] done`);
+ return r.ok ? 0 : 1;
+ }
if (!parsed.wait) {
printPreviewUrls(payload);
return 0;
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -13,6 +13,7 @@ import {
TTS_RESULT_MARKER,
VOICE_RESULT_MARKER,
X_RUN_RESULT_MARKER,
+ attentionLine,
editorEnvFiles,
followJob,
loadEditorEnv,
@@ -21,8 +22,10 @@ import {
parseArgs,
parseDotenv,
previewUrlsIn,
+ startedVerdict,
tokenHint,
usage,
+ waitStarted,
} from "./archilyzer-ops.mjs";
test("no arguments prints usage", () => {
@@ -1192,3 +1195,91 @@ test("watch-trending posts its body; its help says a watch runs only on a fresh
assert.match(usage(), /none while a trending read or capture of ANY\n\s+library waits its turn/);
assert.match(usage(), /pause it until the operator switches it on again/);
});
+
+// --- live recordings (lane live-recording-guard) --------------------------------
+
+test("get live-recordings reads the listing, narrowed by <slug>[/<id>], --all for every run", () => {
+ assert.equal(parseArgs(["get", "live-recordings"]).path, "/api/ops/live-recordings");
+ assert.equal(parseArgs(["get", "live-recordings", "demo-yt"]).path, "/api/ops/live-recordings?slug=demo-yt");
+ assert.equal(
+ parseArgs(["get", "live-recordings", "demo-yt/exampleid01", "--all"]).path,
+ "/api/ops/live-recordings?slug=demo-yt&id=exampleid01&all=1",
+ );
+ assert.match(parseArgs(["get", "channel", "x", "--all"]).error, /does not take --all/);
+ const ack = parseArgs(["live-recording-ack", "--json", '{"slug":"demo-yt","id":"exampleid01"}']);
+ assert.equal(ack.path, "/api/ops/live-recording-ack");
+ assert.match(usage(), /\nlive-recording-ack /);
+ assert.match(usage(), /\nget live-recordings /);
+});
+
+test("--wait-started goes with record-live only", () => {
+ const p = parseArgs(["record-live", "--json", '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=exampleid01"}', "--wait-started"]);
+ assert.equal(p.waitStarted, true);
+ assert.equal(p.wait, false);
+ assert.match(parseArgs(["sync", "--wait-started"]).error, /goes with record-live/);
+ assert.match(parseArgs(["get", "live-recordings", "--wait-started"]).error, /goes with record-live/);
+});
+
+test("the attention header becomes one stderr line, only when something needs a person", () => {
+ assert.equal(attentionLine(null), null);
+ assert.equal(attentionLine("live-recordings=0"), null);
+ assert.equal(attentionLine("live-recordings=1"), "! 1 live recording needs you: pnpm ops get live-recordings");
+ assert.equal(attentionLine("live-recordings=3"), "! 3 live recordings need you: pnpm ops get live-recordings");
+});
+
+test("startedVerdict: growing bytes or a landing is started; failed, cancelled, interrupted are not", () => {
+ assert.equal(startedVerdict(null, null), null);
+ assert.equal(startedVerdict({ status: "recording", bytes: 0 }, null), null);
+ assert.equal(startedVerdict({ status: "recording", bytes: 500 }, null), null, "one sight of bytes is not growth yet");
+ assert.deepEqual(startedVerdict({ status: "recording", bytes: 900 }, 500), { ok: true });
+ assert.deepEqual(startedVerdict({ status: "landed", bytes: 900 }, null), { ok: true });
+ assert.deepEqual(startedVerdict({ status: "failed", reason: "failed: nothing was recorded" }, null), { ok: false, reason: "failed: nothing was recorded" });
+ assert.equal(startedVerdict({ status: "interrupted", reason: "interrupted" }, 5).ok, false);
+});
+
+// A fake editor: the listing answers the rows given per poll, in turn.
+function fakeLiveEditor(listings, job = { status: "running" }) {
+ let n = 0;
+ const asked = [];
+ const fetch = async (url) => {
+ asked.push(url);
+ if (url.includes("/api/ops/job/")) return { json: async () => ({ ok: true, job }) };
+ const rows = listings[Math.min(n++, listings.length - 1)];
+ return { json: async () => ({ ok: true, rows }) };
+ };
+ return { fetch, asked };
+}
+const reply = { ok: true, jobId: "job-1", kind: "record-live", check: "pnpm ops get live-recordings demo-yt/exampleid01" };
+const quiet = { sleep: async () => {}, say: () => {}, baseUrl: "http://editor.test", headers: {} };
+
+test("record-live --wait-started returns once the run's bytes grow", async () => {
+ const ed = fakeLiveEditor([
+ [],
+ [{ jobId: "job-1", status: "recording", bytes: 0, reason: "recording" }],
+ [{ jobId: "job-1", status: "recording", bytes: 4096, reason: "recording" }],
+ [{ jobId: "job-1", status: "recording", bytes: 9000, reason: "recording" }],
+ ]);
+ const r = await waitStarted(reply, "demo-yt", { ...quiet, fetch: ed.fetch });
+ assert.equal(r.ok, true);
+ assert.equal(r.row.bytes, 4096, "grown from the 0 the poll before saw");
+ assert.ok(ed.asked.some((u) => u.endsWith("/api/ops/live-recordings?slug=demo-yt&id=exampleid01&all=1")));
+});
+
+test("record-live --wait-started fails with the recording's own reason", async () => {
+ const ed = fakeLiveEditor([[{ jobId: "job-0", status: "landed" }, { jobId: "job-1", status: "failed", reason: "failed: nothing was recorded — 6 attempts" }]]);
+ const r = await waitStarted(reply, "demo-yt", { ...quiet, fetch: ed.fetch });
+ assert.equal(r.ok, false);
+ assert.match(r.reason, /6 attempts/);
+});
+
+test("record-live --wait-started: a job that ends with no row fails with its status; the bound is kept", async () => {
+ const gone = fakeLiveEditor([[]], { status: "failed" });
+ const r = await waitStarted(reply, "demo-yt", { ...quiet, fetch: gone.fetch });
+ assert.equal(r.ok, false);
+ assert.match(r.reason, /ended failed before it recorded anything/);
+ let clock = 0;
+ const stuck = fakeLiveEditor([[{ jobId: "job-1", status: "recording", bytes: 0, reason: "recording" }]]);
+ const t = await waitStarted(reply, "demo-yt", { ...quiet, fetch: stuck.fetch, now: () => clock, sleep: async (ms) => void (clock += ms), timeoutSeconds: 60 });
+ assert.equal(t.ok, false);
+ assert.match(t.reason, /no media bytes after 60 s/);
+});