commit f4505c97e201e6ff4ea2b8751cb3dce151b6cab5
parent f97a5e526e5ce3c8921019700cf383574ab1d930
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 27 Oct 2026 12:42:18 -0400
live pre-clip in umtool: clips mode "live", the live share, the clip editor's Share now
POST /api/report/clips {mode: "live"} grows the stream's project from the
editor's live-transcript.json, synchronously (a proposal pass; never behind a
render): the project's .shadow-channels copy of the recording (the live cues,
one speaker's turns, the record, the editor's clip cache linked), the live
words and laugh scan, a pass over [0, transcribedTo - 20 s] with ids kept.
"final" hands it to the corpus. POST /api/report/live-share cuts a clip's window
from the recording in progress through the editor's /api/media/live-window and
makes its short offline (--skip-fetch --no-network), 2:20 at most. The clip
editor shows the live banner and its flags, and Share now on a live project.
liveClip.ts refuses a short over X's 512 MiB.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
12 files changed, 856 insertions(+), 4 deletions(-)
diff --git a/common/controller/liveClip.test.ts b/common/controller/liveClip.test.ts
@@ -0,0 +1,116 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { execa } from "execa";
+import type { ChannelConfig } from "../lib/channelConfig";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/liveClip.test.ts
+//
+// A share of a stream still live (controller/liveClip.ts): the window cut now
+// from a recording in progress (a real, tiny MPEG-TS), the cache, the live
+// edge; and the ops job's conversation with umtool (a stub fetch).
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "live-clip-"));
+const CORPUS = path.join(ROOT, "transcripts");
+process.env.TRANSCRIPTS_DIR = CORPUS;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await mkdir(CORPUS, { recursive: true });
+await writeFile(process.env.SETTINGS_FILE, "{}");
+
+const { getPaths } = await import("../lib/paths");
+const { liveWindow, parseLiveClipBody, runLiveClip } = await import("./liveClip");
+const { liveRecordingSidecar } = await import("../lib/mediaImport-server");
+const paths = getPaths();
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const SLUG = "synth-live";
+const CONFIG = { handling: "transcribe", url: "https://www.youtube.com/@synth", platform: "youtube", name: "Synth" } as ChannelConfig;
+
+test("parseLiveClipBody: start/end or clip, 2:20, the project's default", () => {
+ assert.deepEqual(parseLiveClipBody({ slug: "s", id: "Ab1", start: 10, end: 70 }), { ok: true, value: { slug: "s", id: "Ab1", project: "ab1-live", start: 10, end: 70 } });
+ assert.deepEqual(parseLiveClipBody({ slug: "s", id: "Ab1", clip: "r003", project: "mine" }), { ok: true, value: { slug: "s", id: "Ab1", project: "mine", clip: "r003" } });
+ assert.match((parseLiveClipBody({ slug: "s", id: "a", start: 0, end: 200 }) as { error: string }).error, /2:20/);
+ assert.match((parseLiveClipBody({ slug: "s", id: "a", clip: "r1", start: 1, end: 2 }) as { error: string }).error, /not both/);
+ assert.match((parseLiveClipBody({ slug: "s", id: "a" }) as { error: string }).error, /"start" and "end"/);
+});
+
+test("liveWindow: cut now from the part being recorded, then the cache; past the edge says how long to wait", async (t) => {
+ const id = "win001";
+ const videoDir = path.join(CORPUS, "channels", SLUG, "data", id);
+ await mkdir(videoDir, { recursive: true });
+ const store = path.join(paths.savedVideosDir, SLUG);
+ await mkdir(store, { recursive: true });
+ const stem = `.${id}.live-2026-10-27T12-00-00-000Z.ytdlp`;
+ try {
+ await execa(paths.ffmpegBin, [
+ "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=160x90:r=10:d=40", "-f", "lavfi", "-i", "sine=f=300:d=40:r=16000",
+ "-c:v", "libx264", "-preset", "ultrafast", "-g", "20", "-c:a", "aac", "-b:a", "48k", "-f", "mpegts", path.join(store, `${stem}.ts`),
+ ]);
+ } catch {
+ return t.skip("no ffmpeg with libx264 here");
+ }
+ await liveRecordingSidecar.write(videoDir, {
+ status: "recording",
+ url: "u",
+ platform: "youtube",
+ fromStart: true,
+ startedAt: "2026-10-27T12:00:00Z",
+ parts: [{ method: "ytdlp", url: "u", fromStart: true, startedAt: "2026-10-27T12:00:00Z", stem }],
+ });
+ const a = await liveWindow({ paths, slug: SLUG, id, channelConfig: CONFIG, from: 10, to: 20 });
+ assert.ok(a.ok, JSON.stringify(a));
+ if (!a.ok) return;
+ assert.equal(a.source, "live-recording");
+ assert.equal(a.window.file, "10.00-20.00.mp4");
+ const again = await liveWindow({ paths, slug: SLUG, id, channelConfig: CONFIG, from: 12, to: 18 });
+ assert.ok(again.ok && again.source === "cache", "the tightest window already cut serves it");
+ const late = await liveWindow({ paths, slug: SLUG, id, channelConfig: CONFIG, from: 30, to: 45 });
+ assert.ok(!late.ok && late.status === 409 && /ask again in \d+ s/.test(late.error), JSON.stringify(late));
+ const none = await liveWindow({ paths, slug: SLUG, id: "nothing", channelConfig: CONFIG, from: 1, to: 5 });
+ assert.ok(!none.ok && none.status === 404);
+});
+
+function umtoolStub(o: { states: string[]; size: number }) {
+ const seen: { method: string; url: string; body?: unknown }[] = [];
+ const doFetch = (async (url: string, init?: RequestInit) => {
+ const u = String(url);
+ seen.push({ method: init?.method ?? "GET", url: u, ...(init?.body ? { body: JSON.parse(String(init.body)) } : {}) });
+ const json = (b: unknown, status = 200) => new Response(JSON.stringify(b), { status, headers: { "content-type": "application/json" } });
+ if (u.endsWith("/api/report/live-share")) return json({ ok: true, clip: "stream-3605", added: true, window: { from: 3600.5, to: 3666.5 }, windowSource: "live-recording", job: { id: "j1" } });
+ if (u.includes("?job=j1")) {
+ const state = o.states.shift() ?? "done";
+ return json({ state, log: [`state ${state}`], next: 1 });
+ }
+ if (u.includes("/api/report/shorts?project=")) return json({ shorts: [{ clip: "stream-3605", size: o.size }] });
+ return json({ error: "?" }, 404);
+ }) as typeof fetch;
+ return { seen, doFetch };
+}
+
+test("runLiveClip: asks umtool's live share, follows the short, gives its URL; over 512 MiB is refused", async () => {
+ const s = umtoolStub({ states: ["running", "done"], size: 40 * 1024 * 1024 });
+ const lines: string[] = [];
+ const r = await runLiveClip(
+ { slug: SLUG, id: "stream", project: "stream-live", start: 3605, end: 3660 },
+ { onLog: (l) => lines.push(l), signal: new AbortController().signal, deps: { fetch: s.doFetch, umtoolUrl: "http://umtool", workerToken: "tok", pollMs: 0, sleep: async () => {} } },
+ );
+ assert.equal(r.clip, "stream-3605");
+ assert.equal(r.bytes, 40 * 1024 * 1024);
+ assert.match(r.url, /shorts\?project=stream-live&clip=stream-3605&file=1/);
+ assert.deepEqual(s.seen[0]!.body, { project: "stream-live", from: `${SLUG}/stream`, start: 3605, end: 3660 });
+ assert.ok(lines.some((l) => /window 3600.5–3666.5 s cut from the live-recording/.test(l)));
+
+ const big = umtoolStub({ states: ["done"], size: 600 * 1024 * 1024 });
+ await assert.rejects(
+ runLiveClip({ slug: SLUG, id: "stream", project: "stream-live", clip: "stream-3605" }, { onLog: () => {}, signal: new AbortController().signal, deps: { fetch: big.doFetch, umtoolUrl: "http://umtool", workerToken: "tok", pollMs: 0, sleep: async () => {} } }),
+ /over X's 512 MiB/,
+ );
+ const failed = umtoolStub({ states: ["failed"], size: 1 });
+ await assert.rejects(
+ runLiveClip({ slug: SLUG, id: "stream", project: "stream-live", clip: "c" }, { onLog: () => {}, signal: new AbortController().signal, deps: { fetch: failed.doFetch, umtoolUrl: "http://umtool", workerToken: "tok", pollMs: 0, sleep: async () => {} } }),
+ /job j1 failed/,
+ );
+});
diff --git a/common/controller/liveClip.ts b/common/controller/liveClip.ts
@@ -25,7 +25,7 @@ import { liveRecordingSidecar } from "../lib/mediaImport-server";
import { savedVideoDir } from "../lib/savedVideo";
import { findContainingClipWindow, type ClipWindow } from "../lib/clipWindow-server";
import { cutSavedVideoWindow, savedWindowSource } from "../lib/savedVideoWindow-server";
-import { checkLiveWindow, liveClipTooLong, liveProjectSlug, PROJECT_SLUG_RE } from "../lib/livePreclip";
+import { checkLiveWindow, liveClipTooLong, liveProjectSlug, LIVE_SHARE_MAX_BYTES, PROJECT_SLUG_RE } from "../lib/livePreclip";
import { cutLiveWindow, findLiveSource, probeWith } from "../lib/livePreclip-server";
import { umtoolUrl as resolveUmtoolUrl } from "../lib/umtoolUrl";
import { getWorkerToken } from "../lib/workerToken";
@@ -246,6 +246,11 @@ export async function runLiveClip(req: LiveClipRequest, o: { onLog: (s: string)
bytes = null;
}
const url = `${umtool}/api/report/shorts?project=${encodeURIComponent(req.project)}&clip=${encodeURIComponent(clip)}&file=1&download=1`;
+ // X takes 512 MiB at most. A 2:20 short is far under it; one over is said,
+ // not posted.
+ if (bytes !== null && bytes > LIVE_SHARE_MAX_BYTES) {
+ throw new Error(`the short of ${clip} is ${(bytes / 1024 / 1024).toFixed(0)} MiB, over X's 512 MiB — ${url}`);
+ }
return { project: req.project, clip, short: `shorts/${clip}.mp4`, url, bytes, window };
}
diff --git a/umtool/app/api/report/clips/route.ts b/umtool/app/api/report/clips/route.ts
@@ -2,6 +2,7 @@ import { getJob, jobView, runningJob, startJob } from "@/lib/jobs";
import { invalidateProjects, projectRef } from "@/lib/projects";
import { agentToken, routeCaller } from "@/lib/annotations/agentAuth.mjs";
import { ClipsNewError, planClipsNew } from "@/lib/report/clipsNew.mjs";
+import { liveClips } from "@/lib/report/clipsLive.mjs";
import { clipEditorHref } from "@/lib/hrefs";
import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
@@ -25,6 +26,10 @@ export const dynamic = "force-dynamic";
// segment?, wordsPath? } (release 36: the editor's Find clips) → { jobId, job, project, created, segments,
// segment, scope, href, notes } — a reactions project for the same recording whose scope covers the
// chosen one is analyzed again (`created: false`), else `slug` is scaffolded (lib/report/clipsNew.mjs)
+// POST { mode: "live", slug, from: "<channel>/<id>", final?, check? } (live pre-clip, the editor's
+// live-preclip job after each tick) → { project, created, proposals, clips, minedTo, flags, notes, href }
+// — synchronous, no job: the stream's project grown from data/<id>/live-transcript.json
+// (lib/report/clipsLive.mjs); `final` hands it to the corpus
// ?cancel=<job> stop it
// A POST with no Authorization header is the app's page; `Bearer <WORKER_TOKEN>` the editor; any other: 401.
export async function GET(request: Request) {
@@ -78,6 +83,7 @@ export async function POST(request: Request) {
const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 });
if (body.mode === "new") return startNew(body);
+ if (body.mode === "live") return liveMode(body);
const project = await projectRef(String(body.project ?? ""));
if (!project) return Response.json({ error: "no such project" }, { status: 404 });
if (!kindMakesTakes(project.kind)) return Response.json({ error: "clips are found for a report video" }, { status: 400 });
@@ -101,6 +107,23 @@ export async function POST(request: Request) {
}
}
+/**
+ * `mode: "live"` (plans/live-preclip.md): the stream's project made or grown
+ * from the editor's live transcript — one proposal pass, answered here, never
+ * a job (it must not wait behind a render). `final: true` hands it to the
+ * corpus (lib/report/clipsLive.mjs).
+ */
+async function liveMode(body: Record<string, unknown>) {
+ try {
+ const r = await liveClips(body);
+ invalidateProjects();
+ return Response.json({ ok: true, ...r }, { headers: { "cache-control": "no-store" } });
+ } catch (e) {
+ const status = e instanceof ClipsNewError ? e.status : 500;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status });
+ }
+}
+
/** `mode: "new"`: the project found or scaffolded, then `clips analyze` as one job. */
async function startNew(body: Record<string, unknown>) {
const running = runningJob();
diff --git a/umtool/app/api/report/live-share/route.ts b/umtool/app/api/report/live-share/route.ts
@@ -0,0 +1,55 @@
+import { jobView, runningJob, startJob } from "@/lib/jobs";
+import { invalidateProjects, projectRef } from "@/lib/projects";
+import { agentToken, routeCaller } from "@/lib/annotations/agentAuth.mjs";
+import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
+import { LiveShareError, editorWindowAsker, prepareLiveShare } from "@/lib/report/liveShare.mjs";
+import { setShortAside, shortSteps } from "@/lib/report/shorts.mjs";
+
+export const dynamic = "force-dynamic";
+
+// A SHAREABLE CLIP OF A STREAM STILL LIVE (plans/live-preclip.md;
+// lib/report/liveShare.mjs): the clip (added at [start, end] when given by
+// seconds), its window cut NOW by the editor from the recording in progress
+// (`/api/media/live-window`), then its short (`build-video --short`, no
+// network) as ONE job on the app's runner — followed on /api/report/shorts
+// (`?job=`), listed there like any short. The clip editor's Share now; `pnpm
+// ops live-clip` asks it with the WORKER_TOKEN.
+//
+// POST { project, clip | start, end, from?: "<channel>/<id>", replace? }
+// → { ok, clip, added, window, windowSource, job }
+// → 409 { error } past what is recorded ("ask again in N s"), a job running,
+// or a short already there (needsReplace)
+const headers = { "cache-control": "no-store" };
+
+export async function POST(request: Request) {
+ const who = routeCaller(request.headers.get("authorization"), agentToken(), "/api/report/live-share");
+ if (!who.ok) return Response.json({ error: who.error }, { status: who.status, headers });
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers });
+ const project = await projectRef(String(body.project ?? ""));
+ if (!project) return Response.json({ error: `no project ${String(body.project ?? "")}` }, { status: 404, headers });
+ if (!kindMakesTakes(project.kind)) return Response.json({ error: "a share is made of a report video's clip" }, { status: 400, headers });
+ const running = runningJob();
+ if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409, headers });
+ let prepared: Awaited<ReturnType<typeof prepareLiveShare>>;
+ try {
+ prepared = await prepareLiveShare(project, body, { askWindow: editorWindowAsker() });
+ } catch (e) {
+ const status = e instanceof LiveShareError ? e.status : 500;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
+ }
+ invalidateProjects();
+ let aside: string | null = null;
+ try {
+ aside = await setShortAside(project.dir, prepared.clip, { replace: body.replace === true || prepared.added });
+ } catch (e) {
+ const needsReplace = !!(e as { needsReplace?: boolean })?.needsReplace;
+ return Response.json({ error: e instanceof Error ? e.message : String(e), needsReplace, clip: prepared.clip }, { status: 409, headers });
+ }
+ try {
+ const job = startJob(`short ${project.id} ${prepared.clip}`, shortSteps(project, prepared.clip, { offline: true }), { project: project.id });
+ return Response.json({ ok: true, ...prepared, aside, job: jobView(job) }, { headers });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e), clip: prepared.clip }, { status: 409, headers });
+ }
+}
diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx
@@ -480,6 +480,20 @@ export default function ClipEditor({
return (
<div data-clip-editor={clip.id} data-clip-editor-busy={busy ? "" : undefined} className="flex min-h-0 flex-1 flex-col lg:grid lg:grid-cols-[minmax(0,1fr)_minmax(300px,26%)]">
<main data-bench-work="" className="deck-main min-h-0 space-y-3 overflow-auto p-4">
+ {view.live && (
+ <div data-live-project={view.live.status} className="space-y-0.5 text-[12px] text-text-2">
+ <p className="m-0">
+ {view.live.status === "live"
+ ? `Live: the stream is transcribed to ${edgeClock(view.live.transcribedTo)}, mined to ${edgeClock(view.live.minedTo)} (${view.live.passes} pass${view.live.passes === 1 ? "" : "es"}) — the words are provisional; more windows come as it records.`
+ : "Was live: the project reads the final transcript now; its windows stayed where they were."}
+ </p>
+ {view.live.flags.map((f) => (
+ <p key={f.why} role="alert" className="m-0 text-reject-text">
+ {f.why}
+ </p>
+ ))}
+ </div>
+ )}
{/* ---- the clip ---------------------------------------------------- */}
<div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
<h1 className="m-0 font-mono text-[15px] font-semibold text-text" data-editor-clip-id="">
@@ -833,7 +847,7 @@ export default function ClipEditor({
{view.reactionsError && <p className="m-0 text-[12px] text-reject-text">{view.reactionsError}</p>}
{view.rulingsError && <p className="m-0 text-[12px] text-reject-text">{view.rulingsError}</p>}
- <ShortMaker project={project} clipId={clip.id} short={view.shorts?.[clip.id] ?? null} framed={!!clip.vertical} framing={framing} onFraming={setFraming} onCentre={() => setCrop(null)} onMade={() => void reload().catch(() => {})} busy={busy} />
+ <ShortMaker project={project} clipId={clip.id} short={view.shorts?.[clip.id] ?? null} framed={!!clip.vertical} framing={framing} onFraming={setFraming} onCentre={() => setCrop(null)} onMade={() => void reload().catch(() => {})} busy={busy} live={view.live?.status === "live"} />
<RenderTake project={project} render={render} takes={takes} takesHref={takesHref} />
</aside>
</div>
@@ -1537,7 +1551,7 @@ function SpeakerLabel({ speaker, busy, onSave }: { speaker: Speaker; busy: boole
}
/** Make a short: the clip at 1080x1920 from its box, a job; the one there is set aside, never overwritten. */
-function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCentre, onMade, busy }: {
+function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCentre, onMade, busy, live = false }: {
project: string;
clipId: string;
short: { mtimeMs: number; size: number; stale: boolean } | null;
@@ -1547,6 +1561,9 @@ function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCent
onCentre: () => void;
onMade: () => void;
busy: boolean;
+ // A live pre-clip project (plans/live-preclip.md): Share now cuts the window
+ // from the recording in progress first (/api/report/live-share).
+ live?: boolean;
}) {
const [job, setJob] = useState<{ id: string; state: string; error: string | null } | null>(null);
const [err, setErr] = useState<string | null>(null);
@@ -1572,6 +1589,15 @@ function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCent
if (!r.ok || !j.job) setErr(j.error ?? `HTTP ${r.status}`);
else setJob({ id: j.job.id, state: j.job.state, error: j.job.error });
};
+ // Share now (a stream still live): the window is cut from the recording
+ // first, then the same short; nothing is fetched.
+ const shareNow = async () => {
+ setErr(null);
+ const r = await fetch("/api/report/live-share", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, clip: clipId, replace: !!short }) });
+ const j = (await r.json().catch(() => ({}))) as { job?: { id: string; state: string; error: string | null }; error?: string };
+ if (!r.ok || !j.job) setErr(j.error ?? `HTTP ${r.status}`);
+ else setJob({ id: j.job.id, state: j.job.state, error: j.job.error });
+ };
const running = job?.state === "running";
return (
<section data-short-maker={clipId} data-short-made={short ? "" : undefined} className="space-y-1.5">
@@ -1592,6 +1618,11 @@ function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCent
<button type="button" data-make-short={clipId} disabled={running || busy} onClick={() => void make()} className={buttonVariants({ variant: "go", size: "sm" })}>
{running ? "Making the short…" : short ? "Make the short again" : "Make a short"}
</button>
+ {live && (
+ <button type="button" data-live-share={clipId} disabled={running || busy} onClick={() => void shareNow()} className={buttonVariants({ variant: "outline", size: "sm" })} title="cut this clip's seconds from the recording in progress, then make its short (at most 2:20)">
+ Share now (live)
+ </button>
+ )}
{short && (
<a href={`/api/report/shorts?project=${encodeURIComponent(project)}&clip=${encodeURIComponent(clipId)}&file=1&v=${short.mtimeMs}`} target="_blank" rel="noreferrer" data-short-open={clipId} className={buttonVariants({ variant: "quiet", size: "sm" })}>
Play it
diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs
@@ -45,6 +45,7 @@ import { resolveFactcheck } from "umtool-report-to-video/factcheck";
import { momentKeysOf, readRulingsState, setMontageRuling } from "./montageRulings.mjs";
import { readReactions, reproposeAvailable, REPROPOSE_UNAVAILABLE, setSpeakerLabel, setSpeakerRole, SPEAKER_ROLES } from "./clipEditorBridge.mjs";
import { readShorts } from "./shorts.mjs";
+import { readLiveProject } from "./liveProject.mjs";
import { quoteBetween, unusedProposals, wordsOf } from "./clipEditorModel.mjs";
import { WINDOW_PAD_S } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
import { clipRoom } from "umtool-report-to-video/room";
@@ -146,7 +147,18 @@ export async function clipEditorView(project) {
});
const shorts = await readShorts(project.dir, manifest);
const doc = reactions.doc;
+ const live = await readLiveProject(project.dir);
return {
+ live: live
+ ? {
+ status: live.status === "final" ? "final" : "live",
+ transcribedTo: fin(live.transcribedTo) ? live.transcribedTo : 0,
+ minedTo: fin(live.minedTo) ? live.minedTo : 0,
+ passes: fin(live.passes) ? live.passes : 0,
+ lastPass: typeof live.lastPass === "string" ? live.lastPass : null,
+ flags: Array.isArray(live.flags) ? live.flags.filter(isObj) : [],
+ }
+ : null,
clips,
token,
rulingsError: rulings.error,
diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts
@@ -82,6 +82,19 @@ export type EditorView = {
repropose: { available: boolean; why: string | null };
/** The shorts on disk, by clip id (release 36). */
shorts: Record<string, { mtimeMs: number; size: number; stale: boolean }>;
+ /**
+ * A live pre-clip project's record (lib/report/clipsLive.mjs, plans/live-preclip.md):
+ * the stream it grows from, how far it is transcribed and mined, and its flags
+ * (a restart on another clock, a landing check that did not match). Null: not live.
+ */
+ live?: {
+ status: "live" | "final";
+ transcribedTo: number;
+ minedTo: number;
+ passes: number;
+ lastPass: string | null;
+ flags: { at: string; why: string }[];
+ } | null;
/** The cut's render.room and its join's length (release 36 lane E). */
room?: { tail: boolean; head: boolean; minGap: number | null; maxS: number | null; join: number };
/** The claim knobs' defaults (video knobs). */
diff --git a/umtool/lib/report/clipsLive.mjs b/umtool/lib/report/clipsLive.mjs
@@ -0,0 +1,269 @@
+// LIVE PRE-CLIP's project (plans/live-preclip.md): `POST /api/report/clips
+// {mode: "live", slug, from: "<channel>/<id>", final?, check?}` — the editor's
+// live-preclip job asks it after each tick. SYNCHRONOUS: a proposal pass is
+// arithmetic, and it must not wait behind a render on the app's one-job runner.
+//
+// THE RECORDING IS THE PROJECT'S OWN COPY while the stream is live: a project
+// with a `.shadow-channels/` reads its recording from there
+// (report-to-video/sources.mjs channelsDirFor), and this keeps it current from
+// the editor's data/<id>/live-transcript.json:
+//
+// .shadow-channels/<ch>/data/<id>/transcript.cues.json the live cues
+// .shadow-channels/<ch>/data/<id>/diarization.json one speaker, turns from
+// the cues (the clip finder
+// needs turns; the real
+// speakers come with the
+// landing)
+// .shadow-channels/<ch>/data/<id>/metadata.info.json the record's
+// .shadow-channels/<ch>/data/<id>/clips -> <corpus>/data/<id>/clips
+// the editor's clip cache,
+// where a live share's
+// window lands
+// words.json the live words
+// scans/<ch>--<id>.audio.json the live laugh scan
+// live-preclip.json this module's record:
+// the source, the passes,
+// the flags
+//
+// Each pass proposes over [0, transcribedTo − 20 s] (the live edge waits for the
+// next tick: a proposal there would be cut mid-thought). Ids are stable across
+// passes (clips.mjs stableIds), ruled and edited clips are protected
+// (rulingsGuard), so the windows grow without re-proposing what was proposed.
+//
+// FINAL (`final: true`, the live transcript superseded by the corpus's): the
+// shadow goes — the project reads the corpus from now on, the final cues and,
+// once diarized, the speakers — and words.json becomes the corpus's words.json
+// (or goes, so the captions come from transcript.json). The windows stay where
+// they are, by source second: the recording is append-only from its start, so
+// the partial's clock is the landed video's. A landing check that was not
+// "same" flags them (live-preclip.json `flags`, the clip editor's banner).
+//
+// Plain ESM: the route calls it; its tests run with bare node.
+import { copyFile, lstat, mkdir, readFile, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { LAUGH_CLASSES } from "yt-dlp-transcript-common/lib/clips/clips.mjs";
+import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
+import { REPORTS_ROOT } from "../projects/core.mjs";
+import { GLOBAL_CHANNELS_DIR, readManifest, clipsOf } from "../projects/report.mjs";
+import { CHANNEL_SLUG_RE, SLUG_RE, scaffoldReportVideo } from "../projects/scaffold.mjs";
+import { walkProjects } from "../projects/walk.mjs";
+import { SHADOW_CHANNELS } from "umtool-report-to-video/sources";
+import { ClipsNewError } from "./clipsNew.mjs";
+import { WORDS_FILE, proposeProject } from "./reactions.mjs";
+import { LIVE_PROJECT_FILE, readLiveProject } from "./liveProject.mjs";
+
+export const LIVE_TRANSCRIPT_FILENAME = "live-transcript.json";
+export { LIVE_PROJECT_FILE, readLiveProject };
+/** The live edge a pass leaves for the next tick (lib/livePreclip.ts PRECLIP_MINE_EDGE_SECONDS). */
+export const LIVE_MINE_EDGE_S = 20;
+/** Two cues closer than this are one turn. */
+export const LIVE_TURN_GAP_S = 1.5;
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const num = (v) => typeof v === "number" && Number.isFinite(v);
+const readJson = (f) => readFile(f, "utf8").then(JSON.parse, () => null);
+
+async function writeWhole(file, doc) {
+ await mkdir(path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(tmp, `${JSON.stringify(doc)}\n`);
+ await rename(tmp, file);
+}
+
+/**
+ * The turns of a one-speaker recording from its cues: consecutive cues with
+ * gaps under `gap` are one turn, speaker 0.
+ * @param {{ start: number, end: number }[]} cues
+ */
+export function liveTurns(cues, gap = LIVE_TURN_GAP_S) {
+ const out = [];
+ for (const c of [...cues].filter((x) => num(x?.start) && num(x?.end) && x.end > x.start).sort((a, b) => a.start - b.start)) {
+ const last = out.at(-1);
+ if (last && c.start - last.end < gap) last.end = Math.max(last.end, c.end);
+ else out.push({ start: c.start, end: c.end, speaker: 0 });
+ }
+ return out.map((t) => ({ start: Math.round(t.start * 1000) / 1000, end: Math.round(t.end * 1000) / 1000, speaker: 0 }));
+}
+
+/** The request's fields, checked. */
+export function parseLiveBody(body) {
+ const b = isObj(body) ? body : {};
+ const slug = String(b.slug ?? "").trim().toLowerCase();
+ if (!SLUG_RE.test(slug)) throw new ClipsNewError(`slug "${b.slug ?? ""}": lower-case letters, digits and dashes`);
+ const m = /^([^/]+)\/([^/]+)$/.exec(String(b.from ?? ""));
+ if (!m || !CHANNEL_SLUG_RE.test(m[1]) || !CHANNEL_SLUG_RE.test(m[2])) throw new ClipsNewError(`from "${b.from ?? ""}": <channel>/<videoId>`);
+ const check = isObj(b.check) && typeof b.check.verdict === "string" ? { verdict: String(b.check.verdict), why: String(b.check.why ?? ""), ...(num(b.check.lagSeconds) ? { lagSeconds: b.check.lagSeconds } : {}) } : null;
+ return { slug, channel: m[1], video: m[2], final: b.final === true, check };
+}
+
+/** The editor's live transcript of a recording, or null. */
+export async function readLiveTranscript(channelsDir, channel, video) {
+ const doc = await readJson(path.join(channelsDir, channel, "data", video, LIVE_TRANSCRIPT_FILENAME));
+ return isObj(doc) && doc.version === 1 && Array.isArray(doc.cues) ? doc : null;
+}
+
+
+/**
+ * The project's copy of the recording, written from the live transcript.
+ * `shadowRoot` is the `.shadow-channels` dir (the project's, or a staging one).
+ */
+export async function writeShadow({ shadowRoot, channelsDir, channel, video, doc }) {
+ const dir = path.join(shadowRoot, channel, "data", video);
+ await mkdir(dir, { recursive: true });
+ const duration = num(doc.transcribedTo) ? doc.transcribedTo : 0;
+ const turns = liveTurns(doc.cues);
+ // The clip finder refuses a recording with no turns; a live one with no words yet has one silent turn.
+ if (!turns.length) turns.push({ start: 0, end: Math.max(1, duration), speaker: 0 });
+ await writeWhole(path.join(dir, "transcript.cues.json"), { version: 1, source: "live-preclip", provisional: true, duration, cues: doc.cues });
+ await writeWhole(path.join(dir, "diarization.json"), {
+ turns,
+ audioSeconds: duration,
+ generatedAt: String(doc.updatedAt ?? new Date().toISOString()),
+ engine: { engine: "live-preclip (one speaker until the landing)" },
+ });
+ const meta = await readJson(path.join(channelsDir, channel, "data", video, "metadata.info.json"));
+ if (meta) await writeWhole(path.join(dir, "metadata.info.json"), meta);
+ const clips = path.join(dir, "clips");
+ const there = await lstat(clips).catch(() => null);
+ if (!there) await symlink(path.join(channelsDir, channel, "data", video, "clips"), clips).catch(() => {});
+ return { dir, turns: turns.length, duration };
+}
+
+/** The live laugh scan as the clip finder's scan cache (reactions.mjs readScans). */
+export function liveScanDoc(doc, now = new Date()) {
+ const s = doc.scan;
+ if (!isObj(s) || !Array.isArray(s.energy)) return null;
+ return {
+ version: 1,
+ window: s.window,
+ hop: s.hop,
+ t0: 0,
+ windows: s.energy.length,
+ energy: s.energy,
+ laugh: Array.isArray(s.laugh) ? s.laugh : null,
+ model: typeof s.model === "string" ? { file: s.model, sherpaOnnx: null, classes: [...LAUGH_CLASSES] } : null,
+ classes: [...LAUGH_CLASSES],
+ source: { path: LIVE_TRANSCRIPT_FILENAME, size: s.energy.length, mtimeMs: 0 },
+ clock: 0,
+ kind: "live",
+ madeAt: now.toISOString(),
+ };
+}
+
+async function findProject(reportsRoot, slug) {
+ for (const p of await walkProjects(reportsRoot)) if (p.id === slug) return p;
+ return null;
+}
+
+const countOf = async (dir) => {
+ const [reactions, manifest] = await Promise.all([readReactions(dir), readManifest(dir)]);
+ return { proposals: reactions?.proposals?.length ?? 0, clips: manifest ? clipsOf(manifest).length : 0 };
+};
+
+/**
+ * One `mode: "live"` request: the project made or grown, or finalized.
+ * @param {unknown} body
+ * @param {{ reportsRoot?: string, channelsDir?: string, sitesDir?: string, now?: Date }} [o]
+ */
+export async function liveClips(body, { reportsRoot = REPORTS_ROOT, channelsDir = GLOBAL_CHANNELS_DIR(), sitesDir = undefined, now = new Date() } = {}) {
+ const req = parseLiveBody(body);
+ if (!channelsDir) throw new ClipsNewError("no channels directory (CHANNELS_DIR)", 500);
+ const doc = await readLiveTranscript(channelsDir, req.channel, req.video);
+ if (!doc) throw new ClipsNewError(`${req.channel}/${req.video} has no live transcript (${LIVE_TRANSCRIPT_FILENAME})`, 404);
+ const notes = [];
+ let found = await findProject(reportsRoot, req.slug);
+ let live = found ? await readLiveProject(found.dir) : null;
+ if (found && (!live || live.source?.channel !== req.channel || live.source?.video !== req.video)) {
+ throw new ClipsNewError(`project ${req.slug} exists and is not the live project of ${req.channel}/${req.video}: name another ("project")`, 409);
+ }
+ const flags = [...(Array.isArray(live?.flags) ? live.flags : [])];
+ const flag = (why) => {
+ if (!flags.some((f) => f.why === why)) flags.push({ at: now.toISOString(), why });
+ };
+ if (live && num(live.restarts) && num(doc.restarts) && doc.restarts > live.restarts) {
+ flag(`the recording restarted on another clock (${doc.restarts}×): windows proposed before ${now.toISOString().slice(11, 16)} may not sit on the landed video's seconds`);
+ }
+ if (req.check && req.check.verdict !== "same" && req.check.verdict !== "same-recording") {
+ flag(`landing check: ${req.check.verdict} — ${req.check.why}`);
+ }
+
+ // FINAL: the corpus from now on.
+ if (req.final) {
+ if (!found) throw new ClipsNewError(`no live project ${req.slug} to finalize`, 404);
+ await rm(path.join(found.dir, SHADOW_CHANNELS), { recursive: true, force: true });
+ const corpusWords = path.join(channelsDir, req.channel, "data", req.video, WORDS_FILE);
+ if (await stat(corpusWords).then((s) => s.isFile(), () => false)) {
+ await copyFile(corpusWords, path.join(found.dir, WORDS_FILE));
+ notes.push("words.json: the final word timings");
+ } else {
+ await rm(path.join(found.dir, WORDS_FILE), { force: true });
+ notes.push("words.json removed: the captions come from the final transcript");
+ }
+ await rm(path.join(found.dir, "scans", `${req.channel}--${req.video}.audio.json`), { force: true });
+ await writeWhole(path.join(found.dir, LIVE_PROJECT_FILE), { ...live, status: "final", finalAt: now.toISOString(), check: req.check ?? live?.check ?? null, flags });
+ notes.push(`the shadow recording is gone: ${req.slug} reads ${req.channel}/${req.video} from the corpus (Find clips on the landed video re-analyzes it with the speakers and the sound)`);
+ const c = await countOf(found.dir);
+ return { project: req.slug, created: false, final: true, ...c, flags, notes, href: `/projects/${encodeURIComponent(req.slug)}/clips` };
+ }
+
+ // A pass over the live transcript.
+ let created = false;
+ if (!found) {
+ const staging = path.join(reportsRoot, `.live-staging-${req.slug}-${process.pid}`);
+ await rm(staging, { recursive: true, force: true });
+ try {
+ await writeShadow({ shadowRoot: staging, channelsDir, channel: req.channel, video: req.video, doc });
+ let r;
+ try {
+ r = await scaffoldReportVideo({ root: reportsRoot, slug: req.slug, from: `${req.channel}/${req.video}`, seed: "reactions", channelsDir: staging, ...(sitesDir ? { sitesDir } : {}) });
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ throw new ClipsNewError(msg, /already exists/.test(msg) ? 409 : 400);
+ }
+ await rename(staging, path.join(r.dir, SHADOW_CHANNELS));
+ found = { id: r.id, dir: r.dir, kind: r.kind };
+ created = true;
+ notes.push(...(r.notes ?? []).filter((n) => !/umtool clips analyze|pnpm ops transcribe/.test(n)));
+ } finally {
+ await rm(staging, { recursive: true, force: true });
+ }
+ } else {
+ await writeShadow({ shadowRoot: path.join(found.dir, SHADOW_CHANNELS), channelsDir, channel: req.channel, video: req.video, doc });
+ }
+ if (Array.isArray(doc.words) && doc.words.length) await writeWhole(path.join(found.dir, WORDS_FILE), { words: doc.words, provisional: true });
+ const scan = liveScanDoc(doc, now);
+ if (scan) await writeWhole(path.join(found.dir, "scans", `${req.channel}--${req.video}.audio.json`), scan);
+ const upTo = Math.max(0, (num(doc.transcribedTo) ? doc.transcribedTo : 0) - LIVE_MINE_EDGE_S);
+ const pass = await proposeProject({
+ project: { id: found.id, dir: found.dir },
+ from: { channel: req.channel, video: req.video },
+ params: { scopeFrom: 0, scopeTo: Math.round(upTo * 1000) / 1000 },
+ now,
+ });
+ const passes = (num(live?.passes) ? live.passes : 0) + 1;
+ await writeWhole(path.join(found.dir, LIVE_PROJECT_FILE), {
+ version: 1,
+ status: "live",
+ source: { channel: req.channel, video: req.video },
+ madeAt: live?.madeAt ?? now.toISOString(),
+ passes,
+ lastPass: now.toISOString(),
+ transcribedTo: doc.transcribedTo ?? 0,
+ minedTo: upTo,
+ restarts: num(doc.restarts) ? doc.restarts : 0,
+ ...(req.check ? { check: req.check } : live?.check ? { check: live.check } : {}),
+ flags,
+ });
+ live = { passes };
+ return {
+ project: found.id,
+ created,
+ final: false,
+ proposals: pass.doc.proposals.length,
+ clips: clipsOf({ timeline: pass.timeline }).length,
+ minedTo: upTo,
+ flags,
+ notes,
+ href: `/projects/${encodeURIComponent(found.id)}/clips`,
+ };
+}
diff --git a/umtool/lib/report/clipsLive.test.mjs b/umtool/lib/report/clipsLive.test.mjs
@@ -0,0 +1,185 @@
+// Live pre-clip's project (lib/report/clipsLive.mjs): a stream's clip-finder
+// project made from the editor's live transcript, grown as the transcript
+// grows (ids kept), flagged by a landing check, then handed to the corpus.
+// Synthetic: no audio, no model, no network.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { lstat, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
+import { scaffoldReportVideo } from "../projects/scaffold.mjs";
+import { LIVE_PROJECT_FILE, liveClips, liveScanDoc, liveTurns, parseLiveBody } from "./clipsLive.mjs";
+
+const CH = "synth-live";
+const VID = "stream001";
+
+/** A host talking, a line every 4 s, laughing ("hahaha") at the seconds given. */
+function liveDoc(transcribedTo, laughsAt, restarts = 0) {
+ const cues = [];
+ const words = [];
+ for (let t = 1; t + 3 < transcribedTo; t += 4) {
+ const laugh = laughsAt.some((l) => l >= t && l < t + 4);
+ const text = laugh ? "that is the funniest thing hahaha" : "and so the thing is we keep talking";
+ cues.push({ start: t, end: t + 3, text });
+ const ws = text.split(" ");
+ ws.forEach((w, i) => words.push({ w, start: Math.round((t + (i * 3) / ws.length) * 1000) / 1000, end: Math.round((t + ((i + 0.8) * 3) / ws.length) * 1000) / 1000 }));
+ }
+ const n = Math.floor(transcribedTo / 0.5);
+ return {
+ version: 1,
+ provisional: true,
+ status: "live",
+ basis: { stem: ".stream001.live-x.ytdlp", audioFile: ".stream001.live-x.ytdlp.ts", kind: "muxed" },
+ restarts,
+ transcribedTo,
+ cues,
+ words,
+ scan: { hop: 0.5, window: 1, energy: new Array(n).fill(-30), laugh: null, model: null },
+ chunks: [],
+ fingerprint: null,
+ updatedAt: "2026-10-27T12:00:00Z",
+ };
+}
+
+async function fixture() {
+ const root = await mkdtemp(path.join(tmpdir(), "clips-live-"));
+ const channelsDir = path.join(root, "channels");
+ const reportsRoot = path.join(root, "reports");
+ const sitesDir = path.join(root, "sites");
+ const videoDir = path.join(channelsDir, CH, "data", VID);
+ await mkdir(videoDir, { recursive: true });
+ await mkdir(reportsRoot, { recursive: true });
+ await mkdir(sitesDir, { recursive: true });
+ await writeFile(path.join(channelsDir, CH, "config.json"), JSON.stringify({ name: "Synth", platform: "youtube" }));
+ await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify({ id: VID, title: "A live show", webpage_url: `https://www.youtube.com/watch?v=${VID}`, extractor_key: "Youtube", channel: "Synth", live_status: "is_live" }));
+ const put = (doc) => writeFile(path.join(videoDir, "live-transcript.json"), JSON.stringify(doc));
+ return { root, channelsDir, reportsRoot, sitesDir, videoDir, put };
+}
+
+test("liveTurns: cues joined across short gaps, one speaker", () => {
+ assert.deepEqual(
+ liveTurns([{ start: 0, end: 2 }, { start: 2.5, end: 4 }, { start: 9, end: 10 }]),
+ [{ start: 0, end: 4, speaker: 0 }, { start: 9, end: 10, speaker: 0 }],
+ );
+ assert.deepEqual(liveTurns([]), []);
+});
+
+test("parseLiveBody: slug, from, final, check", () => {
+ assert.deepEqual(parseLiveBody({ slug: "a-live", from: "ch/vid", final: true, check: { verdict: "shifted", why: "w", lagSeconds: 1.5 } }), {
+ slug: "a-live", channel: "ch", video: "vid", final: true, check: { verdict: "shifted", why: "w", lagSeconds: 1.5 },
+ });
+ assert.throws(() => parseLiveBody({ slug: "A B", from: "ch/vid" }), /slug/);
+ assert.throws(() => parseLiveBody({ slug: "ok", from: "nope" }), /from/);
+});
+
+test("liveScanDoc: the scan cache reactions.mjs reads", () => {
+ const s = liveScanDoc(liveDoc(10, []));
+ assert.equal(s.version, 1);
+ assert.equal(s.t0, 0);
+ assert.equal(s.windows, 20);
+ assert.equal(s.laugh, null);
+ assert.equal(liveScanDoc({ scan: null }), null);
+});
+
+test("a live project: made, grown with its ids kept, flagged, then handed to the corpus", async () => {
+ const f = await fixture();
+ const opts = { reportsRoot: f.reportsRoot, channelsDir: f.channelsDir, sitesDir: f.sitesDir, now: new Date("2026-10-27T12:10:00Z") };
+ try {
+ await assert.rejects(liveClips({ slug: "stream001-live", from: `${CH}/${VID}` }, opts), (e) => e.status === 404);
+ await f.put(liveDoc(600, [200, 400]));
+ const a = await liveClips({ slug: "stream001-live", from: `${CH}/${VID}` }, opts);
+ assert.equal(a.created, true);
+ assert.equal(a.minedTo, 580);
+ assert.ok(a.proposals > 0, "the laughs and the comments make proposals");
+ const dir = path.join(f.reportsRoot, "stream001-live");
+ const shadow = path.join(dir, ".shadow-channels", CH, "data", VID);
+ const diar = JSON.parse(await readFile(path.join(shadow, "diarization.json"), "utf8"));
+ assert.equal(diar.audioSeconds, 600);
+ assert.ok(diar.turns.every((t) => t.speaker === 0));
+ assert.ok((await lstat(path.join(shadow, "clips"))).isSymbolicLink(), "the editor's clip cache, linked");
+ assert.equal(JSON.parse(await readFile(path.join(dir, "words.json"), "utf8")).provisional, true);
+ let doc = await readReactions(dir);
+ assert.deepEqual(doc.params.scope, [0, 580]);
+ assert.ok(doc.proposals.every((p) => p.end <= 580));
+ const first = doc.proposals.map((p) => [p.id, p.start, p.end]);
+ assert.ok(doc.laughs.length >= 2, "laughs from the transcript's markers (no model)");
+
+ // The transcript grows: a laugh at 900 s. The earlier proposals keep their ids.
+ await f.put(liveDoc(1200, [200, 400, 900]));
+ const b = await liveClips({ slug: "stream001-live", from: `${CH}/${VID}` }, { ...opts, now: new Date("2026-10-27T12:20:00Z") });
+ assert.equal(b.created, false);
+ assert.ok(b.proposals >= a.proposals);
+ doc = await readReactions(dir);
+ assert.deepEqual(doc.params.scope, [0, 1180]);
+ for (const [id, start, end] of first) {
+ const same = doc.proposals.find((p) => p.id === id);
+ assert.ok(same && Math.abs(same.start - start) < 0.01 && Math.abs(same.end - end) < 0.01, `${id} kept`);
+ }
+ assert.ok(doc.proposals.some((p) => p.start > 800 && p.start < 960), "a window near the new span");
+ const live = JSON.parse(await readFile(path.join(dir, LIVE_PROJECT_FILE), "utf8"));
+ assert.equal(live.passes, 2);
+ assert.deepEqual(live.flags, []);
+
+ // Another project's slug is not taken over.
+ await scaffoldReportVideo({ root: f.reportsRoot, slug: "someone-else", title: "x" });
+ await assert.rejects(liveClips({ slug: "someone-else", from: `${CH}/${VID}` }, opts), (e) => e.status === 409);
+
+ // A restart on another clock, then a landing check that did not match: flagged.
+ await f.put(liveDoc(1300, [200, 400, 900], 1));
+ const c = await liveClips({ slug: "stream001-live", from: `${CH}/${VID}`, check: { verdict: "shifted", why: "1.5 s later", lagSeconds: 1.5 } }, opts);
+ assert.equal(c.flags.length, 2, JSON.stringify(c.flags));
+ assert.ok(c.flags.some((x) => /restarted on another clock/.test(x.why)));
+ assert.ok(c.flags.some((x) => /landing check: shifted/.test(x.why)));
+
+ // Final: the shadow goes, words.json becomes the corpus's, the windows stay.
+ const clipsBefore = c.clips;
+ await writeFile(path.join(f.videoDir, "words.json"), JSON.stringify({ words: [{ w: "final", start: 1, end: 1.3 }] }));
+ const d = await liveClips({ slug: "stream001-live", from: `${CH}/${VID}`, final: true }, opts);
+ assert.equal(d.final, true);
+ assert.equal(d.clips, clipsBefore, "every window kept, by source second");
+ assert.equal(await stat(path.join(dir, ".shadow-channels")).then(() => true, () => false), false);
+ assert.equal(JSON.parse(await readFile(path.join(dir, "words.json"), "utf8")).words[0].w, "final");
+ assert.equal(await stat(path.join(f.videoDir, "words.json")).then(() => true, () => false), true, "the corpus's file is untouched");
+ const fin = JSON.parse(await readFile(path.join(dir, LIVE_PROJECT_FILE), "utf8"));
+ assert.equal(fin.status, "final");
+ assert.equal(fin.flags.length, 2);
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ }
+});
+
+test("a live share: the clip added at its seconds, the build's window asked of the editor, 2:20 at most", async () => {
+ const { prepareLiveShare, shareSpan } = await import("./liveShare.mjs");
+ const f = await fixture();
+ const opts = { reportsRoot: f.reportsRoot, channelsDir: f.channelsDir, sitesDir: f.sitesDir };
+ try {
+ await f.put(liveDoc(600, [200]));
+ await liveClips({ slug: "stream001-live", from: `${CH}/${VID}` }, opts);
+ const project = { id: "stream001-live", dir: path.join(f.reportsRoot, "stream001-live") };
+ const asked = [];
+ const askWindow = async (req) => (asked.push(req), { ok: true, status: 200, body: { from: req.from, to: req.to, source: "live-recording" } });
+ const r = await prepareLiveShare(project, { start: 300, end: 345 }, { askWindow });
+ assert.equal(r.added, true);
+ assert.equal(r.windowSource, "live-recording");
+ assert.equal(asked[0].slug, CH);
+ assert.equal(asked[0].id, VID);
+ // The clip's extent (the cut ± 1.5 s) plus the build's fetch pad.
+ const m = JSON.parse(await readFile(path.join(project.dir, "video.manifest.json"), "utf8"));
+ const clip = m.timeline.find((e) => e.id === r.clip);
+ assert.deepEqual([clip.cutStart, clip.cutEnd, clip.start, clip.end], [300, 345, 298.5, 346.5]);
+ assert.deepEqual({ from: asked[0].from, to: asked[0].to }, shareSpan(clip, m.render));
+ assert.ok(asked[0].from <= 298.5 && asked[0].to >= 346.5);
+
+ // By id; the editor's "not yet recorded" passes through as a 409.
+ const late = async () => ({ ok: false, status: 409, body: { error: "the recording holds 10:00 so far; the window ends at 10:03 — ask again in 5 s" } });
+ await assert.rejects(prepareLiveShare(project, { clip: r.clip }, { askWindow: late }), (e) => e.status === 409 && /ask again in 5 s/.test(e.message));
+ await assert.rejects(prepareLiveShare(project, { start: 0, end: 200 }, { askWindow }), /2:20/);
+ await assert.rejects(prepareLiveShare(project, { clip: "nope" }, { askWindow }), (e) => e.status === 404);
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/liveProject.mjs b/umtool/lib/report/liveProject.mjs
@@ -0,0 +1,17 @@
+// A live pre-clip project's record, `<project>/live-preclip.json`
+// (lib/report/clipsLive.mjs writes it; plans/live-preclip.md). Its own small
+// module so the clip editor's view reads it without the scaffold behind it.
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+
+export const LIVE_PROJECT_FILE = "live-preclip.json";
+
+/** The project's live record, or null (not a live project). */
+export async function readLiveProject(dir) {
+ try {
+ const d = JSON.parse(await readFile(path.join(dir, LIVE_PROJECT_FILE), "utf8"));
+ return d && typeof d === "object" && !Array.isArray(d) && d.version === 1 ? d : null;
+ } catch {
+ return null;
+ }
+}
diff --git a/umtool/lib/report/liveShare.mjs b/umtool/lib/report/liveShare.mjs
@@ -0,0 +1,121 @@
+// A SHAREABLE CLIP OF A STREAM STILL LIVE (plans/live-preclip.md) — the clip
+// editor's Share now and `pnpm ops live-clip`: `POST /api/report/live-share
+// {project, clip | start, end, from?, replace?}`.
+//
+// 1. the clip: one of the project's, or a new one added at [start, end] (the
+// clip editor's `add`, with the clip finder's WINDOW_PAD_S either side);
+// at most 2:20 (X's limit);
+// 2. its source window — the build's own span (report-to-video/build-video.mjs
+// fetchSpan: the clip's extent plus render.fetchPad) — asked of the editor
+// (`POST /api/media/live-window`, WORKER_TOKEN): cut NOW from the part being
+// recorded, or from the saved video once it has landed, into the clip
+// cache the project's shadow recording links. Past the live edge the editor
+// answers 409 with how long to wait;
+// 3. its short (lib/report/shorts.mjs, `--skip-fetch --no-network`: the window
+// above is the source, the project's words.json — the live words — the
+// captions), as one job on the app's runner.
+//
+// No request leaves this machine.
+import path from "node:path";
+import { WINDOW_PAD_S } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
+import { clipsOf, readManifest } from "../projects/report.mjs";
+import { addClip } from "./manifest.mjs";
+import { readLiveProject } from "./liveProject.mjs";
+
+/** X's limit on a video's length, seconds (common/lib/livePreclip.ts LIVE_CLIP_MAX_SECONDS). */
+export const LIVE_SHARE_MAX_SECONDS = 140;
+
+export class LiveShareError extends Error {
+ /** @param {string} message @param {number} [status] */
+ constructor(message, status = 400) {
+ super(message);
+ this.status = status;
+ }
+}
+
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const r2 = (x) => Math.round(x * 100) / 100;
+
+/** The span the build reads for a clip (build-video.mjs fetchSpan, its default pad). */
+export function shareSpan(entry, render) {
+ const pad = fin(render?.fetchPad) ? render.fetchPad : 3;
+ return { from: r2(Math.max(0, entry.start - pad)), to: r2(entry.end + pad) };
+}
+
+/**
+ * Steps 1 and 2: the clip (added when given by seconds) and its window, asked
+ * of the editor through `askWindow({slug, id, from, to, clipId, manifest})`,
+ * which resolves `{ ok, status, body }`.
+ * @param {{ id: string, dir: string }} project
+ * @param {Record<string, unknown>} body
+ * @param {{ askWindow: (req: Record<string, unknown>) => Promise<{ ok: boolean, status: number, body: any }> }} o
+ */
+export async function prepareLiveShare(project, body, { askWindow }) {
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new LiveShareError("no manifest", 404);
+ const live = await readLiveProject(project.dir);
+ let entry;
+ let added = false;
+ if (typeof body.clip === "string" && body.clip) {
+ entry = clipsOf(manifest).find((e) => e.id === body.clip);
+ if (!entry) throw new LiveShareError(`no clip ${body.clip} in ${project.id}`, 404);
+ } else {
+ if (!fin(body.start) || !fin(body.end) || body.end <= body.start) throw new LiveShareError('give "clip", or "start" and "end" (seconds of the stream)');
+ const from = typeof body.from === "string" ? /^([^/]+)\/([^/]+)$/.exec(body.from) : null;
+ const channel = from?.[1] ?? live?.source?.channel ?? null;
+ const video = from?.[2] ?? live?.source?.video ?? null;
+ if (!video) throw new LiveShareError(`${project.id} is not a live project: say which recording ("from": "<channel>/<id>")`);
+ if (body.end - body.start > LIVE_SHARE_MAX_SECONDS + 1e-6) throw new LiveShareError(`a share is at most 2:20 (X's limit); this clip is ${Math.round(body.end - body.start)} s`);
+ const res = await addClip(project.dir, {
+ video,
+ ...(channel && channel !== manifest.provenance?.channelSlug ? { channel } : {}),
+ cutStart: body.start,
+ cutEnd: body.end,
+ start: Math.max(0, body.start - WINDOW_PAD_S),
+ end: body.end + WINDOW_PAD_S,
+ title: "live share",
+ });
+ entry = res.entry;
+ added = true;
+ }
+ const cutStart = fin(entry.cutStart) ? entry.cutStart : entry.start;
+ const cutEnd = fin(entry.cutEnd) ? entry.cutEnd : entry.end;
+ if (cutEnd - cutStart > LIVE_SHARE_MAX_SECONDS + 1e-6) {
+ throw new LiveShareError(`${entry.id} is ${Math.round(cutEnd - cutStart)} s: a share is at most 2:20 (X's limit) — trim it first`);
+ }
+ const slug = entry.channel ?? manifest.provenance?.channelSlug ?? live?.source?.channel ?? null;
+ if (!slug) throw new LiveShareError(`${entry.id} names no channel`);
+ const span = shareSpan(entry, manifest.render);
+ const w = await askWindow({
+ slug,
+ id: entry.video,
+ from: span.from,
+ to: span.to,
+ requestedBy: "umtool live-share",
+ manifest: path.join(project.dir, "video.manifest.json"),
+ clipId: entry.id,
+ reason: `a live share of ${entry.id}`,
+ });
+ if (!w.ok) throw new LiveShareError(`the editor did not cut the window: ${w.body?.error ?? `HTTP ${w.status}`}`, w.status === 409 ? 409 : 502);
+ return { clip: entry.id, added, window: { from: w.body.from, to: w.body.to }, windowSource: w.body.source ?? null };
+}
+
+/** The editor's live-window route (ARCHILYZER_EDITOR_URL, WORKER_TOKEN — fetch-via-editor.mjs's). */
+export function editorWindowAsker({ editorUrl = process.env.ARCHILYZER_EDITOR_URL ?? "http://localhost:3001", token = process.env.WORKER_TOKEN ?? "", doFetch = fetch } = {}) {
+ return async (req) => {
+ if (!token) return { ok: false, status: 503, body: { error: "WORKER_TOKEN is not set on umtool: the editor cannot be asked for the window" } };
+ let res;
+ try {
+ res = await doFetch(`${editorUrl.replace(/\/+$/, "")}/api/media/live-window`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
+ body: JSON.stringify(req),
+ signal: AbortSignal.timeout(10 * 60_000),
+ });
+ } catch (e) {
+ return { ok: false, status: 502, body: { error: `the editor at ${editorUrl} did not answer (${e instanceof Error ? e.message : String(e)})` } };
+ }
+ const body = await res.json().catch(() => ({}));
+ return { ok: res.ok, status: res.status, body };
+ };
+}
diff --git a/umtool/lib/report/shorts.mjs b/umtool/lib/report/shorts.mjs
@@ -29,10 +29,14 @@ export function shortFile(dir, clipId) {
* The job's one step: build-video `--short`, NDJSON progress, beside the
* build's own steps (lib/report/driver.mjs). No path or argv from a client.
*
+ * `offline` (a live share, lib/report/liveShare.mjs): `--skip-fetch
+ * --no-network` — the window is already cut, and nothing may be fetched.
+ *
* @param {{ dir: string }} project
* @param {string} clipId
+ * @param {{ offline?: boolean }} [o]
*/
-export function shortSteps(project, clipId) {
+export function shortSteps(project, clipId, { offline = false } = {}) {
if (!safeClipId(clipId)) throw new Error(`not a clip id: ${clipId}`);
return [
{
@@ -44,6 +48,7 @@ export function shortSteps(project, clipId) {
path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"),
"--out", path.join(/* turbopackIgnore: true */ project.dir, "out"),
"--short", clipId, "--progress", "ndjson",
+ ...(offline ? ["--skip-fetch", "--no-network"] : []),
],
ndjson: true,
timeoutMs: SHORT_TIMEOUT_MS,