commit 1cf84ae3cc8434ae443b31bf5f53d815f030051b
parent 05348da09cf3062fe9d66e749c4fef9dc90ca003
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 16 Oct 2026 16:37:49 -0400
umtool: the cited clip — video first, Play span, and Fetch clip through the editor (lib/clips/cited.ts, /api/cited/{play,fetch}, components/clips/CitedClip.tsx); the evidence panel plays through it; common: reports check's findings as data (checkReports), checkMain prints them
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
13 files changed, 952 insertions(+), 137 deletions(-)
diff --git a/common/bin/reports-check.test.ts b/common/bin/reports-check.test.ts
@@ -27,7 +27,7 @@ Object.assign(process.env, {
after(() => rmSync(ROOT, { recursive: true, force: true }));
const { getPaths } = await import("../lib/paths");
-const { checkMain, verifyQuotesMain } = await import("./reports-check");
+const { checkMain, checkReports, verifyQuotesMain } = await import("./reports-check");
const { attachVideoMain } = await import("./reports-attach-video");
const { encodePlan, encodeArgs } = await import("../publish/reportVideo");
const { CHANNELS } = await import("../testing/draft/corpus.mjs");
@@ -160,6 +160,19 @@ test("check --reports checks a draft not in site.json: a drifted quote fails it"
assert.match(c.text(), /quote-drift: draft1#c1: the quote matches \d+% of what the record says there/);
});
+test("checkReports: the same findings as data, for a page (umtool's Check report)", async () => {
+ const failed = await checkReports({ siteId: "demo", paths, reports: ["draft1"], allowMissingMedia: true });
+ assert.equal(failed.status, "fail");
+ const p = failed.status === "fail" ? failed.problems.find((x) => x.kind === "quote-drift") : undefined;
+ assert.equal(p?.where, "draft1#c1");
+ assert.equal(p?.citation, "draft1#c1");
+ assert.match(p?.line ?? "", /^quote-drift: draft1#c1: /);
+ const passed = await checkReports({ siteId: "demo", paths, allowMissingMedia: true });
+ assert.equal(passed.status, "pass");
+ assert.deepEqual(passed.status === "pass" ? passed.reports.find((r) => r.id === "pub1") : null, { id: "pub1", quotes: 1, lowest: 1 });
+ assert.equal((await checkReports({ siteId: "nope", paths })).status, "usage");
+});
+
test("check: an unknown site is a usage error", async () => {
const c = capture();
assert.equal(await checkMain({ siteId: "nope", paths }, c.out), 2);
diff --git a/common/bin/reports-check.ts b/common/bin/reports-check.ts
@@ -59,6 +59,7 @@ import {
import { fragmentOf, fullSentenceFor, type FragmentFinding } from "../lib/citations/fragment";
import {
ComposeReportsError,
+ type ComposeReportsProblem,
checkSpanQuote,
formatComposeReportsProblems,
quoteDriftMessage,
@@ -72,18 +73,59 @@ type Out = { log: (s: string) => void; error: (s: string) => void };
// ─── reports check ───
-export async function checkMain(
- opts: {
- // The site, or `article` — one article id.
- siteId?: string;
- article?: string;
- reports?: string[];
- allowMissingMedia?: boolean;
- paths?: Paths;
- settings?: { social?: { x?: { visibility?: unknown } } };
- },
- out: Out = console,
-): Promise<number> {
+// One compose problem, for a page that lists them (umtool's Check report):
+// where it is and what it says, and the CLI's own line.
+export type ReportsCheckProblem = {
+ kind: string;
+ where: string;
+ message: string;
+ report?: string;
+ citation?: string;
+ line: string;
+};
+
+// What `reports check` found, before it is printed: the CLI prints it
+// (checkMain), umtool's article page draws it (release 32 R1).
+export type ReportsCheckResult =
+ // An unknown site or article: exit 2.
+ | { status: "usage"; who: string; error: string }
+ // Nothing published to check: exit 0.
+ | { status: "empty"; who: string }
+ | {
+ status: "pass";
+ who: string;
+ // Media problems let through by --allow-missing-media.
+ allowed: string[];
+ // A gone source's moment: its words only.
+ warnings: string[];
+ reports: { id: string; quotes: number; lowest: number | null }[];
+ moments: number;
+ }
+ | { status: "fail"; who: string; problems: ReportsCheckProblem[] }
+ // Anything else that stopped the check: exit 1.
+ | { status: "error"; who: string; error: string };
+
+const problemOf = (p: ComposeReportsProblem): ReportsCheckProblem => {
+ const line = formatComposeReportsProblems([p])[0];
+ return {
+ kind: p.kind,
+ where: p.citation ?? p.moment ?? `${p.report ?? "?"}${p.path ? ` at ${p.path}` : ""}`,
+ message: p.message,
+ ...(p.report ? { report: p.report } : {}),
+ ...(p.citation ? { citation: p.citation } : {}),
+ line,
+ };
+};
+
+export async function checkReports(opts: {
+ // The site, or `article` — one article id.
+ siteId?: string;
+ article?: string;
+ reports?: string[];
+ allowMissingMedia?: boolean;
+ paths?: Paths;
+ settings?: { social?: { x?: { visibility?: unknown } } };
+}): Promise<ReportsCheckResult> {
const paths = opts.paths ?? getPaths();
const who = opts.article ? `--article ${opts.article}` : String(opts.siteId);
let host: ReportHost;
@@ -91,22 +133,17 @@ export async function checkMain(
try {
host = await articlesWorkHost(paths, [opts.article]);
} catch (err) {
- out.error(`reports check: ${(err as Error).message}`);
- return 2;
+ return { status: "usage", who, error: (err as Error).message };
}
host = { ...host, published: [opts.article] };
} else {
if (!opts.siteId || !listSiteIds(paths).includes(opts.siteId)) {
- out.error(`reports check: no site "${opts.siteId}" (sites/${opts.siteId}/site.json)`);
- return 2;
+ return { status: "usage", who, error: `no site "${opts.siteId}" (sites/${opts.siteId}/site.json)` };
}
const site = getSite(opts.siteId, paths);
host = siteReportHost(paths, { ...site, pages: opts.reports ?? site.pages ?? [] });
}
- if (host.published.length === 0) {
- out.log(`reports check ${who}: the site publishes no reports — nothing to check.`);
- return 0;
- }
+ if (host.published.length === 0) return { status: "empty", who };
try {
const resolved = await resolveReports({
paths,
@@ -114,34 +151,54 @@ export async function checkMain(
allowMissingMedia: opts.allowMissingMedia === true,
...(opts.settings ? { settings: opts.settings } : {}),
});
- for (const line of formatComposeReportsProblems(resolved.allowed)) {
- out.log(` allowed (--allow-missing-media): ${line}`);
- }
- // A gone source's moment with no media is a warning: its words only.
- for (const g of resolved.sourceGone) {
- out.log(` warning: ${g.moment}: ${SOURCE_GONE_LABELS[g.state].toLowerCase()} — its words only (cited by ${g.citations.join(", ")})`);
- }
- for (const r of resolved.reports) {
- const scores = Object.values(r.citations ?? {})
- .map((c) => (c.kind === "video" || c.kind === "audio" || c.kind === "post" ? c.verification?.quoteScore : undefined))
- .filter((s): s is number => typeof s === "number");
- const low = scores.length ? Math.min(...scores) : null;
- out.log(
- ` ${r.id}: ${scores.length} quote(s) checked` + (low === null ? "" : `, lowest ${low.toFixed(2)}`),
- );
- }
- out.log(
- `reports check ${who}: ${resolved.reports.length} report(s), ${resolved.moments.length} moment(s) — compose would pass.`,
- );
- return 0;
+ return {
+ status: "pass",
+ who,
+ allowed: formatComposeReportsProblems(resolved.allowed),
+ warnings: resolved.sourceGone.map(
+ (g) => `${g.moment}: ${SOURCE_GONE_LABELS[g.state].toLowerCase()} — its words only (cited by ${g.citations.join(", ")})`,
+ ),
+ reports: resolved.reports.map((r) => {
+ const scores = Object.values(r.citations ?? {})
+ .map((c) => (c.kind === "video" || c.kind === "audio" || c.kind === "post" ? c.verification?.quoteScore : undefined))
+ .filter((s): s is number => typeof s === "number");
+ return { id: r.id, quotes: scores.length, lowest: scores.length ? Math.min(...scores) : null };
+ }),
+ moments: resolved.moments.length,
+ };
} catch (err) {
- if (!(err instanceof ComposeReportsError)) {
- out.error(`reports check ${who}: ${(err as Error).message}`);
+ if (!(err instanceof ComposeReportsError)) return { status: "error", who, error: (err as Error).message };
+ return { status: "fail", who, problems: err.problems.map(problemOf) };
+ }
+}
+
+export async function checkMain(
+ opts: Parameters<typeof checkReports>[0],
+ out: Out = console,
+): Promise<number> {
+ const r = await checkReports(opts);
+ switch (r.status) {
+ case "usage":
+ out.error(`reports check: ${r.error}`);
+ return 2;
+ case "empty":
+ out.log(`reports check ${r.who}: the site publishes no reports — nothing to check.`);
+ return 0;
+ case "error":
+ out.error(`reports check ${r.who}: ${r.error}`);
return 1;
- }
- out.error(`reports check ${who}: ${err.problems.length} problem(s) — compose would fail:`);
- for (const line of formatComposeReportsProblems(err.problems)) out.error(` ${line}`);
- return 1;
+ case "fail":
+ out.error(`reports check ${r.who}: ${r.problems.length} problem(s) — compose would fail:`);
+ for (const p of r.problems) out.error(` ${p.line}`);
+ return 1;
+ case "pass":
+ for (const line of r.allowed) out.log(` allowed (--allow-missing-media): ${line}`);
+ for (const w of r.warnings) out.log(` warning: ${w}`);
+ for (const rep of r.reports) {
+ out.log(` ${rep.id}: ${rep.quotes} quote(s) checked` + (rep.lowest === null ? "" : `, lowest ${rep.lowest.toFixed(2)}`));
+ }
+ out.log(`reports check ${r.who}: ${r.reports.length} report(s), ${r.moments} moment(s) — compose would pass.`);
+ return 0;
}
}
diff --git a/umtool/app/api/cited/fetch/route.ts b/umtool/app/api/cited/fetch/route.ts
@@ -0,0 +1,28 @@
+import { fetchCitedClip, targetOf } from "@/lib/clips/cited";
+import { SourceError } from "@/lib/research/sources";
+import { fail, ok } from "../../research/_respond";
+
+export const dynamic = "force-dynamic";
+
+// POST { channel, video, from, to, project?, clip?, reason, report? }
+// | { job, channel?, video?, from?, to?, … } (a poll)
+// -> { state: "ready", cached, play } | { state: "queued", job, status }
+// | { state: "failed", message, detail?, job? }
+//
+// Fetch clip, from the player (lib/clips/cited.ts): the editor's fetch-window
+// route exactly as fetch_clip asks for it, never yt-dlp, never waiting. A poll
+// that names its span answers ready with what plays now.
+export async function POST(request: Request) {
+ try {
+ const b = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!b) throw new SourceError("expected a JSON body");
+ const target = typeof b.channel === "string" && b.channel ? targetOf((k) => b[k]) : undefined;
+ if (typeof b.job === "string" && b.job.trim()) return ok(await fetchCitedClip({ job: b.job.trim(), ...(target ? { target } : {}) }));
+ if (!target) throw new SourceError("channel, video, from and to are required");
+ const reason = String(b.reason ?? "").trim().slice(0, 400) || "umtool: play the cited span";
+ const report = typeof b.report === "string" && b.report.trim() ? b.report.trim() : undefined;
+ return ok(await fetchCitedClip({ target, reason, ...(report ? { report } : {}) }));
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/app/api/cited/play/route.ts b/umtool/app/api/cited/play/route.ts
@@ -0,0 +1,21 @@
+import { fetchClipLine } from "@/lib/articles/evidence";
+import { findCitedPlay, targetOf } from "@/lib/clips/cited";
+import { fail, ok } from "../../research/_respond";
+
+export const dynamic = "force-dynamic";
+
+// GET ?channel&video&from&to[&project&clip][&audio=1]
+// -> { play: CitedPlay | null, fetchLine }
+//
+// What plays a cited span now (lib/clips/cited.ts): a project's cached
+// window, a corpus clip window, a saved video, or audio -- found, never
+// fetched. `fetchLine` is the MCP line for the same seconds.
+export async function GET(request: Request) {
+ try {
+ const url = new URL(request.url);
+ const t = targetOf((k) => url.searchParams.get(k));
+ return ok({ play: await findCitedPlay(t), fetchLine: fetchClipLine({ channel: t.channel, id: t.video, start: t.from, end: t.to }, url.searchParams.get("reason") || "umtool review") });
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/components/articles/EvidencePanel.tsx b/umtool/components/articles/EvidencePanel.tsx
@@ -1,14 +1,15 @@
"use client";
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";
-import CopyButton from "@/components/CopyButton";
+import CitedClip, { type CitedClipHandle } from "@/components/clips/CitedClip";
import type { Evidence } from "@/lib/articles/evidence";
import AddToVideo, { type VideoProjectLink } from "./AddToVideo";
// One citation's evidence: what it quotes, who and when, the transcript around
// it with the cited cues marked, and the media that plays it -- the prepared
-// clip, a fetched window or a saved file, seeked to the cited second -- or,
-// when there is none on disk, the MCP line that fetches it through the editor.
+// clip, a fetched window or a saved file, video first, seeked to the cited
+// second, with Play span -- or, when there is none on disk, Fetch clip (and
+// the MCP line for the same seconds): components/clips/CitedClip.tsx.
export type EvidenceHandle = { togglePlay: () => void };
@@ -45,29 +46,14 @@ const EvidencePanel = forwardRef<
{ ev: Evidence | null; error: string | null; number?: number; autoPlay?: boolean; projects?: VideoProjectLink[] }
>(
function EvidencePanel({ ev, error, number, autoPlay = false, projects = [] }, ref) {
- const media = useRef<HTMLMediaElement | null>(null);
- useImperativeHandle(ref, () => ({
- togglePlay: () => {
- const m = media.current;
- if (!m) return;
- if (m.paused) void m.play().catch(() => {});
- else m.pause();
- },
- }));
+ const clip = useRef<CitedClipHandle | null>(null);
+ const [playable, setPlayable] = useState(!!ev?.play);
+ useImperativeHandle(ref, () => ({ togglePlay: () => clip.current?.togglePlay() }));
if (error) return <p className="text-[12px] text-[var(--color-bad)]">{error}</p>;
if (!ev) return <p className="text-[12px] text-[var(--color-dim)]">loading…</p>;
- const play = ev.play;
- // File time of a record second: the cited span starts `offset` into the file.
- const fileT = (t: number) => (play && ev.start !== undefined ? Math.max(0, t - ev.start + play.offset) : 0);
- const startAt = play ? (play.kind === "prepared" ? 0 : Math.max(0, play.offset - 3)) : 0;
- const seek = (t: number) => {
- if (media.current) {
- media.current.currentTime = fileT(t);
- void media.current.play().catch(() => {});
- }
- };
+ const seek = (t: number) => clip.current?.seek(t);
return (
<div data-evidence={ev.cite} className="space-y-2 text-[12px]">
@@ -91,44 +77,18 @@ const EvidencePanel = forwardRef<
</a>
)}
- {play ? (
- <div data-play={play.kind}>
- {play.audio ? (
- <audio
- ref={(el) => {
- media.current = el;
- }}
- controls
- src={play.url}
- autoPlay={autoPlay}
- onLoadedMetadata={(e) => {
- e.currentTarget.currentTime = startAt;
- }}
- className="w-full"
- />
- ) : (
- <video
- ref={(el) => {
- media.current = el;
- }}
- controls
- src={play.url}
- autoPlay={autoPlay}
- onLoadedMetadata={(e) => {
- e.currentTarget.currentTime = startAt;
- }}
- className="aspect-video w-full rounded bg-black"
- />
- )}
- <div className="micro mt-0.5">{play.label}</div>
- </div>
- ) : ev.fetchLine ? (
- <div data-play="none" className="space-y-1 rounded border border-[var(--color-line)] bg-[var(--color-panel-2)] p-2">
- <div className="text-[var(--color-dim)]">not on disk — fetch it through the editor:</div>
- <code className="block break-all font-mono text-[11px] text-[var(--color-text)]">{ev.fetchLine}</code>
- <CopyButton text={ev.fetchLine} label="copy fetch_clip" />
- </div>
- ) : null}
+ {ev.record && ev.start !== undefined && ev.end !== undefined && (ev.kind === "video" || ev.kind === "audio") && (
+ <CitedClip
+ key={ev.cite}
+ ref={clip}
+ target={{ channel: ev.record.channel, video: ev.record.id, from: ev.start, to: ev.end, ...(ev.kind === "audio" ? { audio: true } : {}) }}
+ initial={ev.play}
+ fetchLine={ev.fetchLine}
+ reason={`umtool evidence ${ev.cite}`}
+ autoPlay={autoPlay}
+ onPlayable={setPlayable}
+ />
+ )}
{ev.post && (
<div data-post className="reader space-y-1 rounded-[2px] px-3.5 py-2.5">
@@ -148,7 +108,7 @@ const EvidencePanel = forwardRef<
<button
type="button"
onClick={() => seek(c.start)}
- disabled={!play}
+ disabled={!playable}
className={`flex w-full items-baseline gap-3 border-l-[3px] px-2.5 py-px text-left ${c.cited ? "border-reader-signal bg-[color-mix(in_srgb,var(--reader-signal)_9%,transparent)] text-reader-ink" : "border-transparent text-reader-2"} enabled:hover:text-reader-ink`}
>
<span className={`num shrink-0 font-mono text-[10.5px] ${c.cited ? "font-semibold text-reader-signal" : "text-reader-dim"}`}>{fmt(c.start)}</span>
diff --git a/umtool/components/clips/CitedClip.tsx b/umtool/components/clips/CitedClip.tsx
@@ -0,0 +1,361 @@
+"use client";
+
+import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react";
+import CopyButton from "@/components/CopyButton";
+import { buttonVariants } from "@/components/ui/button";
+import { citedKey, type CitedFetchAnswer, type CitedPlay, type CitedTarget } from "@/lib/clips/types";
+import { spanClock } from "@/lib/clips/words";
+import { cn } from "@/lib/utils";
+
+// ---------------------------------------------------------------------------
+// THE CITED CLIP (release 32 R1): the seconds a citation names, played so a
+// person can hear -- and see -- that the words are there. The one place a
+// human has to verify, and it needs no model.
+//
+// video first a clip window or saved video covering the span, seeked to
+// the cited second; "Play span" plays from the span's start
+// and stops at its end; replay is the same press
+// audio when only audio holds it, with an "audio only" label
+// Fetch clip when nothing on disk does: one press asks the editor
+// (/api/cited/fetch -> the editor's fetch-window, as the MCP's
+// fetch_clip asks), shows its progress, plays when it lands;
+// a failure is said plainly (a rate limit, corrupt audio)
+//
+// Two faces: `panel` (native controls, the evidence panel and the reader) and
+// `card` (the audition deck's: no chrome, tap replays, a span-only scrubber).
+// Its buttons never take focus, and the media gives it back, so a page's own
+// keys (approve, reject, j/k) keep working after a play.
+// ---------------------------------------------------------------------------
+
+export type CitedClipHandle = {
+ /** Play the span from its start; pause when playing. */
+ togglePlay: () => void;
+ /** Play the span from its start, always. */
+ playSpan: () => void;
+ /** Seek to a source second and play from there. */
+ seek: (t: number) => void;
+};
+
+type Looked = { play: CitedPlay | null; fetchLine?: string };
+const lookups = new Map<string, Promise<Looked>>();
+
+function lookup(t: CitedTarget, fresh = false): Promise<Looked> {
+ const key = citedKey(t);
+ if (fresh) lookups.delete(key);
+ let p = lookups.get(key);
+ if (!p) {
+ const q = new URLSearchParams({ channel: t.channel, video: t.video, from: String(t.from), to: String(t.to) });
+ if (t.project && t.clip) {
+ q.set("project", t.project);
+ q.set("clip", t.clip);
+ }
+ if (t.audio) q.set("audio", "1");
+ p = fetch(`/api/cited/play?${q}`, { cache: "no-store" }).then(async (r) => {
+ const j = await r.json();
+ if (!r.ok) throw new Error(j.error ?? r.statusText);
+ return j as Looked;
+ });
+ p.catch(() => lookups.delete(key));
+ lookups.set(key, p);
+ }
+ return p;
+}
+
+/** Ask what plays a span before it is shown (the card after the next). */
+export function warmCited(t: CitedTarget): void {
+ void lookup(t).catch(() => {});
+}
+
+const stopTyping = "input, textarea, select, button, a[href], [contenteditable=''], [contenteditable='true']";
+
+const CitedClip = forwardRef<
+ CitedClipHandle,
+ {
+ target: CitedTarget;
+ /** Known already (the evidence route found it): undefined looks it up, null is a known miss. */
+ initial?: CitedPlay | null;
+ fetchLine?: string;
+ /** Why these seconds are wanted: stored beside the window. */
+ reason?: string;
+ report?: string;
+ face?: "panel" | "card";
+ /** Play the span as soon as it can. */
+ autoPlay?: boolean;
+ /** Load the media now (the card underneath). */
+ preload?: boolean;
+ /** Space plays the span (from anywhere that is not a control). */
+ keys?: boolean;
+ /** The source second, as it plays (the lit line follows it). */
+ onTime?: (t: number) => void;
+ /** Whether something can play now. */
+ onPlayable?: (playable: boolean) => void;
+ className?: string;
+ }
+>(function CitedClip(
+ { target, initial, fetchLine: givenLine, reason, report, face = "panel", autoPlay = false, preload = false, keys = false, onTime, onPlayable, className },
+ ref,
+) {
+ const [play, setPlay] = useState<CitedPlay | null | undefined>(initial);
+ const [line, setLine] = useState<string | undefined>(givenLine);
+ const [lookError, setLookError] = useState<string | null>(null);
+ const [fetching, setFetching] = useState<CitedFetchAnswer | { state: "asking" } | null>(null);
+ const [now, setNow] = useState(target.from);
+ const [playing, setPlaying] = useState(false);
+ const media = useRef<HTMLMediaElement | null>(null);
+ const spanning = useRef(false);
+ const wantPlay = useRef(autoPlay);
+ const key = citedKey(target);
+
+ useEffect(() => {
+ if (initial !== undefined) return;
+ let live = true;
+ lookup(target)
+ .then((l) => {
+ if (!live) return;
+ setPlay(l.play);
+ if (l.fetchLine && !givenLine) setLine(l.fetchLine);
+ })
+ .catch((e) => live && setLookError(e instanceof Error ? e.message : String(e)));
+ return () => {
+ live = false;
+ };
+ // `target` is named by its key.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [key, initial]);
+
+ useEffect(() => onPlayable?.(!!play), [play, onPlayable]);
+ useEffect(() => {
+ wantPlay.current = autoPlay;
+ if (autoPlay && media.current && media.current.readyState >= 1) playSpanNow();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [autoPlay]);
+
+ // File time of a source second: the span starts `offset` into the file.
+ const fileT = useCallback((t: number) => (play ? Math.max(0, t - target.from + play.offset) : 0), [play, target.from]);
+ const sourceT = useCallback((ft: number) => (play ? ft - play.offset + target.from : target.from), [play, target.from]);
+
+ const giveBackFocus = () => {
+ const a = document.activeElement as HTMLElement | null;
+ if (a && media.current && (a === media.current || media.current.contains(a))) a.blur();
+ };
+
+ const playSpanNow = useCallback(() => {
+ const m = media.current;
+ if (!m) return;
+ m.currentTime = fileT(target.from);
+ spanning.current = true;
+ void m.play().catch(() => {});
+ }, [fileT, target.from]);
+
+ const api: CitedClipHandle = {
+ playSpan: playSpanNow,
+ togglePlay: () => {
+ const m = media.current;
+ if (!m) return;
+ if (m.paused) playSpanNow();
+ else m.pause();
+ },
+ seek: (t: number) => {
+ const m = media.current;
+ if (!m) return;
+ m.currentTime = fileT(t);
+ spanning.current = t < target.to;
+ void m.play().catch(() => {});
+ },
+ };
+ useImperativeHandle(ref, () => api);
+
+ useEffect(() => {
+ if (!keys) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key !== " " || e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return;
+ const t = e.target as HTMLElement | null;
+ if (t?.closest?.(stopTyping) || t?.closest?.("dialog[open]")) return;
+ if (!media.current) return;
+ e.preventDefault();
+ api.togglePlay();
+ };
+ document.addEventListener("keydown", onKey);
+ return () => document.removeEventListener("keydown", onKey);
+ });
+
+ const runFetch = async () => {
+ setFetching({ state: "asking" });
+ const body = { ...target, reason: reason ?? "umtool: play the cited span", ...(report ? { report } : {}) };
+ try {
+ let r = await fetch("/api/cited/fetch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
+ let a = (await r.json()) as CitedFetchAnswer & { error?: string };
+ for (let polls = 0; r.ok && a.state === "queued" && polls < 600; polls++) {
+ setFetching(a);
+ await new Promise((res) => setTimeout(res, 1000));
+ r = await fetch("/api/cited/fetch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ ...target, job: a.job }) });
+ a = (await r.json()) as CitedFetchAnswer & { error?: string };
+ }
+ if (!r.ok) {
+ setFetching({ state: "failed", message: a.error ?? `HTTP ${r.status}` });
+ return;
+ }
+ setFetching(a);
+ if (a.state === "ready") {
+ const found = a.play ?? (await lookup(target, true)).play;
+ lookups.set(key, Promise.resolve({ play: found, ...(line ? { fetchLine: line } : {}) }));
+ wantPlay.current = true;
+ setPlay(found);
+ if (!found) setFetching({ state: "failed", message: "the editor fetched it, but nothing on this disk plays the span" });
+ }
+ } catch (e) {
+ setFetching({ state: "failed", message: e instanceof Error ? e.message : String(e) });
+ }
+ };
+
+ const span = Math.max(0.001, target.to - target.from);
+ const rel = Math.min(span, Math.max(0, now - target.from));
+ const card = face === "card";
+
+ const status =
+ fetching && fetching.state !== "asking" ? (
+ <span
+ data-fetch-state={fetching.state}
+ role={fetching.state === "failed" ? "alert" : "status"}
+ className={cn("block text-[12px]", fetching.state === "failed" ? "text-reject-text" : "text-muted")}
+ title={fetching.state === "failed" ? fetching.detail : undefined}
+ >
+ {fetching.state === "ready"
+ ? `Clip ${fetching.cached ? "already held" : "fetched"}`
+ : fetching.state === "queued"
+ ? `The editor is fetching it (${fetching.status})…`
+ : fetching.message}
+ </span>
+ ) : null;
+
+ const mediaProps = {
+ ref: (el: HTMLMediaElement | null) => {
+ media.current = el;
+ },
+ src: play?.url,
+ preload: preload || autoPlay ? "auto" : "metadata",
+ "data-player": "",
+ tabIndex: -1,
+ onLoadedMetadata: (e: React.SyntheticEvent<HTMLMediaElement>) => {
+ e.currentTarget.currentTime = play ? (card ? play.offset : Math.max(0, play.offset - (play.kind === "prepared" ? play.offset : 3))) : 0;
+ if (wantPlay.current) playSpanNow();
+ },
+ onTimeUpdate: (e: React.SyntheticEvent<HTMLMediaElement>) => {
+ const t = sourceT(e.currentTarget.currentTime);
+ setNow(t);
+ onTime?.(t);
+ if (spanning.current && t >= target.to) {
+ spanning.current = false;
+ e.currentTarget.pause();
+ }
+ },
+ onPlay: () => {
+ setPlaying(true);
+ giveBackFocus();
+ },
+ onPause: () => {
+ setPlaying(false);
+ giveBackFocus();
+ },
+ onSeeked: giveBackFocus,
+ };
+
+ const noFocus = (e: React.MouseEvent) => e.preventDefault();
+
+ return (
+ <div
+ data-cited-clip={key}
+ data-play={play === undefined ? (lookError ? "error" : "looking") : play ? play.kind : "none"}
+ data-playing={playing ? "" : undefined}
+ className={cn("space-y-1.5", className)}
+ >
+ {play ? (
+ <>
+ {play.audio ? (
+ <div className={cn(card && "flex aspect-video w-full items-center justify-center rounded-[3px] bg-panel-2")}>
+ {card && (
+ <button type="button" onMouseDown={noFocus} onClick={() => api.playSpan()} className="font-mono text-[12px] text-muted" aria-label="Replay the span">
+ {playing ? "playing…" : "▶ replay"}
+ </button>
+ )}
+ <audio {...mediaProps} controls={!card} className={card ? "hidden" : "w-full"} />
+ </div>
+ ) : (
+ <video
+ {...mediaProps}
+ controls={!card}
+ playsInline
+ onClick={card ? () => api.playSpan() : undefined}
+ className={cn("aspect-video w-full rounded-[3px] bg-black", card && "cursor-pointer")}
+ />
+ )}
+ <div className="flex flex-wrap items-center gap-2">
+ {card ? (
+ <input
+ type="range"
+ aria-label="Position in the span"
+ data-span-scrubber=""
+ min={0}
+ max={span}
+ step={0.05}
+ value={rel}
+ onChange={(e) => api.seek(target.from + Number(e.target.value))}
+ onPointerUp={(e) => e.currentTarget.blur()}
+ className="min-w-0 flex-1 accent-[var(--signal)]"
+ />
+ ) : (
+ <>
+ <button type="button" data-play-span="" onMouseDown={noFocus} onClick={() => api.playSpan()} className={buttonVariants({ variant: "outline", size: "sm" })}>
+ {playing ? "Replay span" : "Play span"}
+ </button>
+ {playing && (
+ <button type="button" onMouseDown={noFocus} onClick={() => media.current?.pause()} className={buttonVariants({ variant: "ghost", size: "sm" })}>
+ Pause
+ </button>
+ )}
+ </>
+ )}
+ <span className="num font-mono text-[11px] text-muted" data-span-clock="">
+ {spanClock(rel)} / {spanClock(span)}
+ </span>
+ {play.audio && (
+ <span data-audio-only="" className="rounded-[3px] border border-seam-2 px-1.5 py-px text-[11px] text-text-2">
+ audio only
+ </span>
+ )}
+ {!card && <span className="micro">{play.label}</span>}
+ </div>
+ </>
+ ) : play === null ? (
+ <div className={cn("space-y-1.5 rounded-[3px] border border-seam bg-panel-2 p-2.5", card && "flex aspect-video w-full flex-col items-center justify-center text-center")}>
+ <div className="text-[12.5px] text-text-2">Not on disk</div>
+ <button
+ type="button"
+ data-fetch-clip=""
+ onMouseDown={noFocus}
+ disabled={!!fetching && (fetching.state === "asking" || fetching.state === "queued")}
+ onClick={() => void runFetch()}
+ className={buttonVariants({ variant: "go", size: "md" })}
+ >
+ {fetching && (fetching.state === "asking" || fetching.state === "queued") ? "Fetching…" : "Fetch clip"}
+ </button>
+ {status}
+ {!card && line && (
+ <details className="text-[11px] text-muted">
+ <summary className="cursor-pointer">or with the MCP</summary>
+ <code className="block break-all font-mono text-[11px] text-text-2">{line}</code>
+ <CopyButton text={line} label="copy fetch_clip" />
+ </details>
+ )}
+ </div>
+ ) : (
+ <div className={cn("text-[12px] text-muted", card && "flex aspect-video w-full items-center justify-center rounded-[3px] bg-panel-2")}>
+ {lookError ? <span className="text-reject-text">{lookError}</span> : "looking for the clip…"}
+ </div>
+ )}
+ {play && status}
+ </div>
+ );
+});
+
+export default CitedClip;
diff --git a/umtool/lib/articles/evidence.ts b/umtool/lib/articles/evidence.ts
@@ -2,10 +2,11 @@ import { readFile } from "node:fs/promises";
import path from "node:path";
import type { Report } from "yt-dlp-transcript-common/lib/report/schema";
import { momentKeyOf } from "yt-dlp-transcript-common/lib/citations/moments";
-import { evidenceSpan, resolveEvidenceSource } from "yt-dlp-transcript-common/lib/evidenceClip-server";
+import { evidenceSpan } from "yt-dlp-transcript-common/lib/evidenceClip-server";
import { storeMediaDir, storeMediaIndexFile } from "yt-dlp-transcript-common/publish/reportMedia";
import { readCues } from "@/lib/projects/report.mjs";
-import { CHANNELS_DIR } from "@/lib/paths";
+import { corpusPlay } from "@/lib/clips/cited";
+import type { CitedPlay } from "@/lib/clips/types";
import { channelPosts, corpusMediaUrl, postShotFile, recordDir, recordMeta } from "./article";
import { storeFor } from "./sites";
@@ -18,23 +19,16 @@ import { storeFor } from "./sites";
// 2. window a clip window the editor fetched into data/<id>/clips/;
// 3. saved a saved video or audio file in data/<id>/ (through its media
// tier link -- read, never written);
-// 4. otherwise nothing to play, and the line that fetches it through the
-// editor: the MCP `fetch_clip` tool. umtool's own fetch client
-// (api/report/fetch) is a manifest's, so it cannot ask for a
-// window no project names. Never yt-dlp.
+// 4. otherwise nothing to play: the panel's player (components/clips/
+// CitedClip.tsx) offers Fetch clip -- the editor's fetch-window
+// through /api/cited/fetch, as the MCP's fetch_clip asks (release
+// 32 R1) -- and the MCP line for the same seconds. Never yt-dlp.
export const CONTEXT_CUES = 6;
export type EvidenceCue = { start: number; end: number; text: string; cited: boolean };
-export type EvidencePlay = {
- kind: "prepared" | "window" | "saved" | "audio";
- url: string;
- /** Seconds into the file where the cited span starts. */
- offset: number;
- audio: boolean;
- label: string;
-};
+export type EvidencePlay = CitedPlay;
export type Evidence = {
cite: string;
@@ -107,22 +101,11 @@ async function preparedClip(siteId: string, c: Cite): Promise<EvidencePlay | nul
}
}
+// The corpus's own media for the span (lib/clips/cited.ts, shared with the
+// review deck's player).
async function corpusClip(c: Cite): Promise<EvidencePlay | null> {
if (c.kind !== "video" && c.kind !== "audio") return null;
- const span = { from: c.start, to: c.end };
- for (const audio of c.kind === "audio" ? [true] : [false, true]) {
- const hit = await resolveEvidenceSource({ channelsDir: CHANNELS_DIR, slug: c.channel, id: c.id, span, audio }).catch(() => null);
- if (!hit) continue;
- const kind = hit.kind === "corpus-window" ? "window" : hit.kind === "saved-video" ? "saved" : "audio";
- return {
- kind,
- url: corpusMediaUrl(hit.path),
- offset: Math.max(0, c.start - hit.windowStart),
- audio: hit.kind === "audio",
- label: kind === "window" ? `clip window ${hit.name}` : kind === "saved" ? `saved ${hit.name}` : `audio ${hit.name}`,
- };
- }
- return null;
+ return corpusPlay({ channel: c.channel, video: c.id, from: c.start, to: c.end, ...(c.kind === "audio" ? { audio: true } : {}) });
}
/** The MCP line that fetches this span through the editor. */
diff --git a/umtool/lib/clips/cited.test.ts b/umtool/lib/clips/cited.test.ts
@@ -0,0 +1,73 @@
+// The cited clip's server half (release 32 R1): a span's target parsed, a
+// fetch asked of a fake editor exactly as fetch_clip asks, queued then polled
+// to ready, and a refusal said in plain words. No network: the editor is a
+// function.
+//
+// Run with: pnpm --filter umtool exec tsx --test lib/clips/cited.test.ts
+import { before, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+let lib: typeof import("./cited");
+
+before(async () => {
+ process.env.CHANNELS_DIR = path.join(await mkdtemp(path.join(os.tmpdir(), "umtool-cited-")), "channels");
+ lib = await import("./cited");
+});
+
+type Call = { url: string; body: Record<string, unknown> | null };
+function editor(answers: ((c: Call) => { status: number; body: unknown })[]) {
+ const calls: Call[] = [];
+ let i = 0;
+ return {
+ calls,
+ deps: {
+ env: { ARCHILYZER_EDITOR_URL: "http://editor.invalid", WORKER_TOKEN: "t" } as unknown as NodeJS.ProcessEnv,
+ fetch: async (url: string, init?: { body?: string }) => {
+ const call = { url, body: init?.body ? JSON.parse(init.body) : null };
+ calls.push(call);
+ const a = answers[Math.min(i++, answers.length - 1)](call);
+ return { status: a.status, json: async () => a.body };
+ },
+ sleep: async () => {},
+ now: () => 0,
+ },
+ };
+}
+
+test("a target: corpus directories and a span, the project's clip only as a pair", () => {
+ const t = lib.targetOf((k) => ({ channel: "chan", video: "v1", from: "3", to: "6.5", project: "reports/p" })[k as "channel"]);
+ assert.deepEqual(t, { channel: "chan", video: "v1", from: 3, to: 6.5 });
+ assert.throws(() => lib.targetOf((k) => ({ channel: "..", video: "v1", from: 1, to: 2 })[k as "channel"]), /channel/);
+ assert.throws(() => lib.targetOf((k) => ({ channel: "c", video: "v", from: 5, to: 2 })[k as "channel"]), /from < to/);
+});
+
+test("fetch asks the editor as fetch_clip does (umtool, padded window), then a poll is ready", async () => {
+ const e = editor([() => ({ status: 202, body: { cached: false, jobId: "j1", from: 0, to: 9 } })]);
+ const target = { channel: "chan", video: "v1", from: 3, to: 6 };
+ const q = await lib.fetchCitedClip({ target, reason: "review" }, e.deps);
+ assert.deepEqual(q, { state: "queued", job: "j1", status: "queued" });
+ assert.equal(e.calls[0].url, "http://editor.invalid/api/media/fetch-window");
+ assert.deepEqual(
+ { ...e.calls[0].body },
+ { channelSlug: "chan", videoId: "v1", from: 0, to: 9, pad: 3, requestedBy: "umtool", reason: "review" },
+ );
+ const p = editor([() => ({ status: 200, body: { status: "done", file: "/x/clips/0.00-9.00.mp4", from: 0, to: 9 } })]);
+ const ready = await lib.fetchCitedClip({ job: "j1", target }, p.deps);
+ assert.equal(p.calls[0].url, "http://editor.invalid/api/media/fetch-window/j1");
+ // Nothing in this empty corpus to play: ready, and the player says so.
+ assert.deepEqual(ready, { state: "ready", cached: false, from: 0, to: 9, play: null });
+});
+
+test("a cooldown says the platform is rate-limiting; an audio-check failure says corrupt audio", async () => {
+ const target = { channel: "chan", video: "v1", from: 3, to: 6 };
+ const c = editor([() => ({ status: 409, body: { error: "youtube is in a rate-limit cooldown (42s remaining).", cooldownMs: 42000, platform: "youtube" } })]);
+ const r = await lib.fetchCitedClip({ target, reason: "review" }, c.deps);
+ assert.equal(r.state, "failed");
+ assert.equal(r.state === "failed" && r.message, "youtube is rate-limiting fetches: try again later.");
+ const m = editor([() => ({ status: 200, body: { status: "failed", error: "The audio check found the window 0.00–9.00 of v1 malformed" } })]);
+ const f = await lib.fetchCitedClip({ job: "j2", target }, m.deps);
+ assert.match(f.state === "failed" ? f.message : "", /corrupt audio/);
+});
diff --git a/umtool/lib/clips/cited.ts b/umtool/lib/clips/cited.ts
@@ -0,0 +1,148 @@
+import {
+ fetchClip,
+ validateFetchClipArgs,
+ type FetchClipDeps,
+} from "yt-dlp-transcript-mcp/research";
+import { resolveEvidenceSource } from "yt-dlp-transcript-common/lib/evidenceClip-server";
+import { CHANNELS_DIR } from "@/lib/paths";
+import { answerOf } from "@/lib/research/fetch";
+import { SourceError } from "@/lib/research/sources";
+import { projectCache, resolveClip, windowsFor } from "@/lib/report/serve.mjs";
+import { corpusMediaUrl } from "@/lib/articles/article";
+import type { CitedFetchAnswer, CitedPlay, CitedTarget } from "./types";
+import { fetchFailureSentence } from "./words";
+
+// ---------------------------------------------------------------------------
+// THE CITED CLIP, server side (release 32 R1): what plays a cited span, and
+// the one button that fetches it when nothing does.
+//
+// Playback, best first -- found, never fetched:
+// 1. a project's own cached window (out/clips-raw, or a corpus window the
+// project's cache counts), when the span is a project's clip: served by
+// /api/report/raw, which the clip bench plays too;
+// 2. a clip window the editor fetched into data/<id>/clips/;
+// 3. a saved video in data/<id>/ (through its media-tier link);
+// 4. audio, labelled "audio only".
+// The prepared evidence clip of a site (lib/articles/evidence.ts) comes before
+// all of these on the article pages; it is that module's.
+//
+// FETCH asks the editor's fetch-window route exactly as the MCP's fetch_clip
+// asks (requestedBy "umtool"), never yt-dlp. The corpus's channel and video
+// directories ARE the editor's, so no source lookup stands between: the
+// editor resolves the page URL from the record. The route never waits: a
+// queued fetch is polled by job id.
+// ---------------------------------------------------------------------------
+
+const WIN_EPS = 0.02;
+
+/** The corpus's own media for a span: a window, a saved video, or audio. */
+export async function corpusPlay(t: CitedTarget, channelsDir: string = CHANNELS_DIR): Promise<CitedPlay | null> {
+ const span = { from: t.from, to: t.to };
+ for (const audio of t.audio ? [true] : [false, true]) {
+ const hit = await resolveEvidenceSource({ channelsDir, slug: t.channel, id: t.video, span, audio }).catch(() => null);
+ if (!hit) continue;
+ const kind = hit.kind === "corpus-window" ? "window" : hit.kind === "saved-video" ? "saved" : "audio";
+ return {
+ kind,
+ url: corpusMediaUrl(hit.path),
+ offset: Math.max(0, t.from - hit.windowStart),
+ audio: hit.kind === "audio",
+ label: kind === "window" ? `clip window ${hit.name}` : kind === "saved" ? `saved ${hit.name}` : `audio ${hit.name}`,
+ };
+ }
+ return null;
+}
+
+/** A project clip's own cached window holding the span, served through /api/report/raw. */
+async function projectPlay(t: CitedTarget): Promise<CitedPlay | null> {
+ if (!t.project || !t.clip || t.audio) return null;
+ const r = await resolveClip(t.project, t.clip).catch(() => null);
+ if (!r || "error" in r) return null;
+ const cache = await projectCache(r.project, r.manifest);
+ const windows = (await windowsFor(r.project, { ...r.clip, start: t.from, end: t.to }, cache)) as { name: string; from: number; to: number }[];
+ const win = windows.find((w) => w.from <= t.from + WIN_EPS && w.to >= t.to - WIN_EPS);
+ if (!win) return null;
+ return {
+ kind: "window",
+ url: `/api/report/raw?${new URLSearchParams({ project: t.project, clip: t.clip, file: win.name })}`,
+ offset: Math.max(0, t.from - win.from),
+ audio: false,
+ label: `clip window ${win.name}`,
+ };
+}
+
+/** What plays the span now, or null (nothing on disk: offer Fetch clip). */
+export async function findCitedPlay(t: CitedTarget): Promise<CitedPlay | null> {
+ return (await projectPlay(t)) ?? (await corpusPlay(t));
+}
+
+/** Parse a target from a query string or a JSON body; throws a 400 in words. */
+export function targetOf(get: (k: string) => unknown): CitedTarget {
+ const s = (k: string) => {
+ const v = get(k);
+ return typeof v === "string" ? v.trim() : typeof v === "number" ? String(v) : "";
+ };
+ const channel = s("channel");
+ const video = s("video");
+ const from = Number(s("from"));
+ const to = Number(s("to"));
+ const id = /^[\w.-]+$/;
+ if (!id.test(channel) || channel === "." || channel === "..") throw new SourceError("channel must be a channel directory");
+ if (!id.test(video) || video === "." || video === "..") throw new SourceError("video must be a video directory");
+ if (!Number.isFinite(from) || !Number.isFinite(to) || from < 0 || !(from < to)) throw new SourceError("from and to must be seconds, from < to");
+ const project = s("project");
+ const clip = s("clip");
+ return {
+ channel,
+ video,
+ from,
+ to,
+ ...(project && clip ? { project, clip } : {}),
+ ...(s("audio") === "1" || get("audio") === true ? { audio: true } : {}),
+ };
+}
+
+const deps: FetchClipDeps = {
+ env: process.env,
+ fetch: (url, init) => globalThis.fetch(url, init),
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
+ now: () => Date.now(),
+};
+
+/**
+ * Fetch the span through the editor (or poll a fetch already asked for). A
+ * ready answer carries what plays now; a failure its plain sentence.
+ */
+export async function fetchCitedClip(
+ req: { job: string; target?: CitedTarget } | { target: CitedTarget; reason: string; report?: string },
+ d: FetchClipDeps = deps,
+): Promise<CitedFetchAnswer> {
+ const args =
+ "job" in req
+ ? { job: req.job, wait_seconds: 0 }
+ : {
+ channel: req.target.channel,
+ video: req.target.video,
+ start: req.target.from,
+ end: req.target.to,
+ reason: req.reason,
+ ...(req.report ? { report: req.report } : {}),
+ wait_seconds: 0,
+ };
+ const v = validateFetchClipArgs(args);
+ if (!v.ok) throw new SourceError(v.error.replace(/^fetch_clip: /, ""));
+ const a = answerOf(await fetchClip(v.request, d, { requestedBy: "umtool" }));
+ if (a.state === "failed") {
+ const plain = fetchFailureSentence(a.message);
+ return { state: "failed", message: plain.message, ...(plain.detail ? { detail: plain.detail } : {}), ...(a.job ? { job: a.job } : {}) };
+ }
+ if (a.state === "queued") return a;
+ const target = req.target;
+ return {
+ state: "ready",
+ cached: a.cached,
+ ...(a.from !== undefined ? { from: a.from } : {}),
+ ...(a.to !== undefined ? { to: a.to } : {}),
+ play: target ? await findCitedPlay(target) : null,
+ };
+}
diff --git a/umtool/lib/clips/types.ts b/umtool/lib/clips/types.ts
@@ -0,0 +1,36 @@
+// The cited clip's shapes, shared by the server (lib/clips/cited.ts, the
+// /api/cited routes) and the player (components/clips/CitedClip.tsx).
+
+/** What can play a cited span, best first: prepared, a clip window, a saved video, audio. */
+export type CitedPlay = {
+ kind: "prepared" | "window" | "saved" | "audio";
+ url: string;
+ /** Seconds into the file where the cited span starts. */
+ offset: number;
+ audio: boolean;
+ label: string;
+};
+
+/**
+ * The span a citation names. `channel`/`video` are the corpus's directories
+ * (a Rumble entry's local dir is `video`, never its `siteVideo`). With
+ * `project`+`clip` the project's own cached windows are asked first.
+ */
+export type CitedTarget = {
+ channel: string;
+ video: string;
+ from: number;
+ to: number;
+ project?: string;
+ clip?: string;
+ /** An audio citation: never look for a picture. */
+ audio?: boolean;
+};
+
+/** One answer of the fetch route: ready (and what plays now), still going, or why not, in plain words. */
+export type CitedFetchAnswer =
+ | { state: "ready"; cached: boolean; from?: number; to?: number; play: CitedPlay | null }
+ | { state: "queued"; job: string; status: string }
+ | { state: "failed"; message: string; detail?: string; job?: string };
+
+export const citedKey = (t: CitedTarget) => [t.channel, t.video, t.from, t.to, t.project ?? "", t.clip ?? "", t.audio ? "a" : ""].join("|");
diff --git a/umtool/lib/clips/words.test.ts b/umtool/lib/clips/words.test.ts
@@ -0,0 +1,41 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { fetchFailureSentence, litCount, spokenWords } from "./words";
+
+test("a rate limit says the platform is rate-limiting", () => {
+ const r = fetchFailureSentence("youtube is cooling down after a 429 (2 min): HTTP Error 429: Too Many Requests");
+ assert.equal(r.message, "youtube is rate-limiting fetches: try again later.");
+ assert.match(r.detail ?? "", /429/);
+ assert.equal(fetchFailureSentence("the editor refused it (409): rumble is in a rate-limit cooldown").message, "rumble is rate-limiting fetches: try again later.");
+});
+
+test("an audio-check failure says the source served corrupt audio", () => {
+ const r = fetchFailureSentence("the editor's job failed: The audio check found the window 1.00–9.00 of abc malformed");
+ assert.match(r.message, /corrupt audio/);
+});
+
+test("anything else is passed through", () => {
+ assert.deepEqual(fetchFailureSentence("the editor's job failed: no formats"), { message: "the editor's job failed: no formats" });
+});
+
+test("spoken words follow the cues, word by word", () => {
+ const cues = [
+ { start: 0, end: 4, text: "one two three four" },
+ { start: 4, end: 8, text: "five six seven eight" },
+ ];
+ const w = spokenWords("three four five", cues, 0, 8);
+ assert.deepEqual(w.map((x) => x.t), [2, 3, 4]);
+ assert.equal(litCount(w, 3.5), 2);
+ assert.equal(litCount(w, 1), 0);
+});
+
+test("a misheard word keeps the time before it", () => {
+ const cues = [{ start: 10, end: 14, text: "I bought a cakeup machine" }];
+ const w = spokenWords("I bought a K-Cup machine", cues, 10, 14);
+ assert.deepEqual(w.map((x) => x.t), [10, 10.8, 11.6, 11.6, 13.2]);
+});
+
+test("no cues, or a quote mostly not in them: spread evenly over the span", () => {
+ assert.deepEqual(spokenWords("a b", [], 0, 2).map((x) => x.t), [0, 1]);
+ assert.deepEqual(spokenWords("x y z w", [{ start: 0, end: 4, text: "nothing alike here" }], 0, 4).map((x) => x.t), [0, 1, 2, 3]);
+});
diff --git a/umtool/lib/clips/words.ts b/umtool/lib/clips/words.ts
@@ -0,0 +1,94 @@
+// Pure helpers of the cited-clip player and the audition deck (release 32 R1):
+// a fetch failure in plain words, and the LIT LINE -- each word of a quote with
+// the second it is spoken, so the line lights as playback reaches it.
+
+/**
+ * A fetch failure as the person reading it needs it: a rate limit says the
+ * platform is rate-limiting, an audio-check refusal says the source served
+ * corrupt audio. `detail` keeps the editor's own words.
+ */
+export function fetchFailureSentence(message: string): { message: string; detail?: string } {
+ const m = String(message ?? "").trim();
+ if (/\b429\b|rate[- ]?limit|too many requests|cooling down/i.test(m)) {
+ const platform = /^(\w+) is cooling down/i.exec(m)?.[1] ?? /\b(youtube|rumble|odysee|twitch|kick)\b/i.exec(m)?.[1] ?? "the platform";
+ return { message: `${platform} is rate-limiting fetches: try again later.`, detail: m };
+ }
+ if (/audio check found .* malformed|malformed/i.test(m)) {
+ return { message: "The source served corrupt audio for these seconds (the audio check refused it twice); nothing was kept.", detail: m };
+ }
+ if (/did not answer|ECONNREFUSED|no editor|ARCHILYZER_EDITOR_URL/i.test(m)) {
+ return { message: "The editor is not answering, so nothing can be fetched right now.", detail: m };
+ }
+ return { message: m || "the fetch failed" };
+}
+
+export type SpokenWord = { text: string; t: number };
+
+const norm = (w: string) => w.toLowerCase().replace(/[^\p{L}\p{N}']+/gu, "").replace(/'/g, "");
+
+/**
+ * Each word of `quote` with the second it is spoken: the cues in [from, to]
+ * spread their words evenly across their own span, and the quote's words are
+ * found in that sequence in order; a word not found takes the time of the one
+ * before it (or the span's start). With no cues, or fewer than half the words
+ * found, the quote spreads evenly across the span. Word-level offsets are
+ * not read: no transcript shape in the corpus carries them.
+ */
+export function spokenWords(
+ quote: string,
+ cues: readonly { start: number; end?: number; text: string }[],
+ from: number,
+ to: number,
+): SpokenWord[] {
+ const words = String(quote ?? "").split(/\s+/).filter(Boolean);
+ if (!words.length) return [];
+ const span = Math.max(0.001, to - from);
+ const timed: { n: string; t: number }[] = [];
+ const sorted = [...cues].sort((a, b) => a.start - b.start);
+ sorted.forEach((c, i) => {
+ const end = c.end ?? sorted[i + 1]?.start ?? c.start + 3;
+ if (end < from - 0.05 || c.start > to + 0.05) return;
+ const ws = String(c.text ?? "").split(/\s+/).filter(Boolean);
+ const step = ws.length ? Math.max(0, end - c.start) / ws.length : 0;
+ ws.forEach((w, j) => timed.push({ n: norm(w), t: c.start + j * step }));
+ });
+ const even = () => words.map((w, i) => ({ text: w, t: from + (i * span) / words.length }));
+ if (!timed.length) return even();
+ const out: SpokenWord[] = [];
+ let at = 0;
+ let last = from;
+ let hits = 0;
+ for (const w of words) {
+ const n = norm(w);
+ let hit = -1;
+ // Look ahead a little: a respelled or misheard word is skipped, not a derailment.
+ for (let k = at; k < Math.min(timed.length, at + 8); k++) {
+ if (n && timed[k].n === n) {
+ hit = k;
+ break;
+ }
+ }
+ if (hit >= 0) {
+ hits += 1;
+ last = Math.max(last, timed[hit].t);
+ at = hit + 1;
+ }
+ out.push({ text: w, t: last });
+ }
+ // Mostly not found (another track's words, a paraphrase): spread it instead.
+ return hits * 2 < words.length ? even() : out;
+}
+
+/** How many words are lit at `now` (the spoken ones). */
+export function litCount(words: readonly SpokenWord[], now: number): number {
+ let n = 0;
+ for (const w of words) if (w.t <= now + 0.05) n += 1;
+ return n;
+}
+
+export const spanClock = (s: number) => {
+ const v = Math.max(0, s);
+ const m = Math.floor(v / 60);
+ const r = Math.floor(v % 60);
+ return `${m}:${String(r).padStart(2, "0")}`;
+};
diff --git a/umtool/package.json b/umtool/package.json
@@ -8,7 +8,7 @@
"build": "next build",
"start": "next start --port ${UMTOOL_PORT:-3050}",
"typecheck": "tsc --noEmit",
- "test": "tsx --test lib/research/*.test.ts lib/inbox/*.test.ts",
+ "test": "tsx --test lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts",
"e2e": "node ../scripts/worktree.mjs run -- node ../scripts/queue-lock.mjs --name e2e-umtool --estimate 1500 --prebuild umtool --ports UMTOOL_E2E_PORT:3051,EDITOR_STUB_PORT:3052 -- playwright test"
},
"dependencies": {