Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit bbaafd2751da60d69aba73ab5c5a456c48b15aa6
parent b0e9bc93e01cf65883b297958939419764011fc7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 23:35:47 -0400

umtool: "Cut from the stored media URL" beside every window fetch — Fetch clip, the research reader, the clip and claim benches, Fetch N unfetched clips

Offered only when the span's record stores a media file address the editor can
cut from (GET /api/cited/stored, lib/clips/stored.ts — Odysee's CDN file; a
project clip's record found the way fetch-via-editor.mjs finds it). Ticked, the
fetch asks the editor with storedUrl "fallback": /api/cited/fetch and
/api/research/fetch pass it as fetch_clip's field, /api/report/fetch as
fetch-via-editor.mjs --stored-url (refused with --full or a local fetch).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/app/api/cited/fetch/route.ts | 8++++++--
Aumtool/app/api/cited/stored/route.ts | 19+++++++++++++++++++
Mumtool/app/api/report/fetch/route.ts | 18+++++++++++++++++-
Mumtool/app/api/research/fetch/route.ts | 4+++-
Mumtool/components/clips/CitedClip.tsx | 21+++++++++++++++++++--
Aumtool/components/clips/StoredUrlOption.tsx | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/ClaimBench.tsx | 18++++++++++++++++--
Mumtool/components/projects/ClipBench.tsx | 15++++++++++++++-
Mumtool/components/projects/FetchUnfetchedButton.tsx | 19+++++++++++++++++++
Mumtool/components/projects/report/CutTab.tsx | 12++++++++++++
Mumtool/components/research/Reader.tsx | 15+++++++++++++++
Mumtool/components/research/ResearchView.tsx | 7++++++-
Mumtool/lib/clips/cited.test.ts | 10++++++++++
Mumtool/lib/clips/cited.ts | 6+++++-
Aumtool/lib/clips/stored.test.ts | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/clips/stored.ts | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/driver.mjs | 8+++++++-
Mumtool/lib/research/fetch.ts | 12++++++++++--
Mumtool/report-to-video/fetch-via-editor.mjs | 18+++++++++++++++++-
Mumtool/report-to-video/fetch-via-editor.test.mjs | 17+++++++++++++++++
20 files changed, 427 insertions(+), 15 deletions(-)

diff --git a/umtool/app/api/cited/fetch/route.ts b/umtool/app/api/cited/fetch/route.ts @@ -1,10 +1,11 @@ +import { isStoredUrlMode } from "yt-dlp-transcript-common/lib/storedMediaUrl"; 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? } +// POST { channel, video, from, to, project?, clip?, reason, report?, storedUrl? } // | { job, channel?, video?, from?, to?, … } (a poll) // -> { state: "ready", cached, play } | { state: "queued", job, status } // | { state: "failed", message, detail?, job? } @@ -21,7 +22,10 @@ export async function POST(request: Request) { 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 } : {}) })); + // "Cut from the stored media URL" (release 32 R6): the editor's mode, as given. + if (b.storedUrl !== undefined && !isStoredUrlMode(b.storedUrl)) throw new SourceError('storedUrl must be "never", "fallback" or "only"'); + const storedUrl = isStoredUrlMode(b.storedUrl) && b.storedUrl !== "never" ? b.storedUrl : undefined; + return ok(await fetchCitedClip({ target, reason, ...(report ? { report } : {}), ...(storedUrl ? { storedUrl } : {}) })); } catch (e) { return fail(e); } diff --git a/umtool/app/api/cited/stored/route.ts b/umtool/app/api/cited/stored/route.ts @@ -0,0 +1,19 @@ +import { storedUrlFor } from "@/lib/clips/stored"; +import { fail, ok } from "../../research/_respond"; + +export const dynamic = "force-dynamic"; + +// GET ?project&clip | ?channel&video -> { stored, host?, platform? } +// +// Whether the span's record stores a media file address the editor can cut a +// window from (release 32 R6, lib/clips/stored.ts). Every umtool fetch surface +// asks before it offers "Cut from the stored media URL". +export async function GET(request: Request) { + try { + const u = new URL(request.url); + const g = (k: string) => u.searchParams.get(k)?.trim() || undefined; + return ok(await storedUrlFor({ project: g("project"), clip: g("clip"), channel: g("channel"), video: g("video") })); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/report/fetch/route.ts b/umtool/app/api/report/fetch/route.ts @@ -51,6 +51,22 @@ export async function POST(request: Request) { // nowhere to put a full source that anything else would find. const wantFull = body.full === true; + // CUT FROM THE STORED MEDIA URL (release 32 R6): the editor's `storedUrl`, + // for a window asked of the editor ("fallback" | "only"). The local fetch and + // a whole recording have no such thing; asking for one with them is refused + // rather than quietly ignored. + const storedUrl = + body.storedUrl === "fallback" || body.storedUrl === "only" ? body.storedUrl : null; + if (body.storedUrl !== undefined && body.storedUrl !== null && body.storedUrl !== "never" && !storedUrl) { + return Response.json({ error: 'storedUrl must be "never", "fallback" or "only"' }, { status: 400 }); + } + if (storedUrl && (wantFull || localFetch())) { + return Response.json( + { error: wantFull ? "the stored media URL cuts a window, not the whole recording" : "the stored media URL is the editor's; this umtool fetches locally" }, + { status: 400 }, + ); + } + const r = await resolveClip(projectId, clipId); if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); @@ -125,7 +141,7 @@ export async function POST(request: Request) { ? editorFullSourceSteps(r.project, clipId, { manifest: r.manifest }) : localFetch() ? fetchSteps(r.project, clipId, { padBefore, padAfter }) - : editorFetchSteps(r.project, clipId, { padBefore, padAfter }); + : editorFetchSteps(r.project, clipId, { padBefore, padAfter, storedUrl }); const job = startJob( wantFull ? `fetch whole source ${projectId}/${clipId}` diff --git a/umtool/app/api/research/fetch/route.ts b/umtool/app/api/research/fetch/route.ts @@ -4,7 +4,7 @@ import { fail, ok } from "../_respond"; export const dynamic = "force-dynamic"; -// POST { source, channel, video, start, end, reason } | { job } +// POST { source, channel, video, start, end, reason, storedUrl? } | { job } // -> { state: "ready", file, from, to, cached } | { state: "queued", job, status } // | { state: "failed", message, job? } // @@ -26,6 +26,8 @@ export async function POST(request: Request) { start, end, reason: String(b.reason ?? "").slice(0, 400), + // "Cut from the stored media URL" (release 32 R6): fetch_clip's field. + ...(b.storedUrl === "fallback" || b.storedUrl === "only" ? { storedUrl: b.storedUrl } : {}), }), ); } catch (e) { diff --git a/umtool/components/clips/CitedClip.tsx b/umtool/components/clips/CitedClip.tsx @@ -6,6 +6,8 @@ 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"; +import { STORED_URL_UI_MODE } from "yt-dlp-transcript-common/lib/storedMediaUrl"; +import StoredUrlOption from "./StoredUrlOption"; // --------------------------------------------------------------------------- // THE CITED CLIP (release 32 R1): the seconds a citation names, played so a @@ -19,7 +21,9 @@ import { cn } from "@/lib/utils"; // 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) +// a failure is said plainly (a rate limit, corrupt audio); +// beside it, "Cut from the stored media URL" when the record +// stores one (release 32 R6, StoredUrlOption) // // 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). @@ -99,6 +103,7 @@ const CitedClip = forwardRef< const [line, setLine] = useState<string | undefined>(givenLine); const [lookError, setLookError] = useState<string | null>(null); const [fetching, setFetching] = useState<CitedFetchAnswer | { state: "asking" } | null>(null); + const [fromStored, setFromStored] = useState(false); const [now, setNow] = useState(target.from); const [playing, setPlaying] = useState(false); const media = useRef<HTMLMediaElement | null>(null); @@ -181,7 +186,12 @@ const CitedClip = forwardRef< const runFetch = async () => { setFetching({ state: "asking" }); - const body = { ...target, reason: reason ?? "umtool: play the cited span", ...(report ? { report } : {}) }; + const body = { + ...target, + reason: reason ?? "umtool: play the cited span", + ...(report ? { report } : {}), + ...(fromStored ? { storedUrl: STORED_URL_UI_MODE } : {}), + }; 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 }; @@ -339,6 +349,13 @@ const CitedClip = forwardRef< > {fetching && (fetching.state === "asking" || fetching.state === "queued") ? "Fetching…" : "Fetch clip"} </button> + <StoredUrlOption + query={{ channel: target.channel, video: target.video }} + checked={fromStored} + onChange={setFromStored} + disabled={!!fetching && (fetching.state === "asking" || fetching.state === "queued")} + compact={card} + /> {status} {!card && line && ( <details className="text-[11px] text-muted"> diff --git a/umtool/components/clips/StoredUrlOption.tsx b/umtool/components/clips/StoredUrlOption.tsx @@ -0,0 +1,103 @@ +"use client"; + +import { useEffect, useId, useState } from "react"; +import { STORED_URL_HELP, STORED_URL_LABEL } from "yt-dlp-transcript-common/lib/storedMediaUrl"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// "Cut from the stored media URL" (release 32 R6), umtool's half: a checkbox +// beside a fetch button, shown only when the span's record stores a media file +// address the editor can cut from (GET /api/cited/stored — Odysee's CDN file). +// Off by default; ticked, the fetch asks the editor with STORED_URL_UI_MODE +// ("fallback": the page first, the stored file when the platform refuses). +// --------------------------------------------------------------------------- + +export type StoredUrlQuery = { project: string; clip: string } | { channel: string; video: string }; + +const answers = new Map<string, Promise<boolean>>(); + +function keyOf(q: StoredUrlQuery): string { + return "project" in q ? `p|${q.project}|${q.clip}` : `c|${q.channel}|${q.video}`; +} + +function lookup(q: StoredUrlQuery): Promise<boolean> { + const key = keyOf(q); + let p = answers.get(key); + if (!p) { + p = fetch(`/api/cited/stored?${new URLSearchParams(q)}`, { cache: "no-store" }) + .then((r) => (r.ok ? r.json() : { stored: false })) + .then((j: { stored?: boolean }) => j.stored === true) + .catch(() => false); + answers.set(key, p); + } + return p; +} + +/** Whether the option is offered for `q` (null while asking, or with no query). */ +export function useStoredUrlOffered(q: StoredUrlQuery | null): boolean { + const [offered, setOffered] = useState(false); + const key = q ? keyOf(q) : ""; + useEffect(() => { + if (!q) return; + let live = true; + void lookup(q).then((v) => live && setOffered(v)); + return () => { + live = false; + }; + // `q` is named by its key. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key]); + return offered; +} + +/** The checkbox itself, for a caller that already knows it is offered. */ +export function StoredUrlCheckbox({ + checked, + onChange, + disabled, + compact, + className, +}: { + checked: boolean; + onChange: (v: boolean) => void; + disabled?: boolean; + /** One line; the help on hover only. */ + compact?: boolean; + className?: string; +}) { + const helpId = useId(); + return ( + <label + data-stored-url-option="" + title={STORED_URL_HELP} + className={cn("flex max-w-prose cursor-pointer items-start gap-1.5 text-left text-[12px] text-text-2", className)} + > + <input + type="checkbox" + className="mt-[3px] accent-[var(--signal)]" + checked={checked} + disabled={disabled} + onChange={(e) => onChange(e.target.checked)} + aria-describedby={compact ? undefined : helpId} + /> + <span> + {STORED_URL_LABEL} + {!compact && ( + <span id={helpId} className="block text-[11px] text-muted"> + {STORED_URL_HELP} + </span> + )} + </span> + </label> + ); +} + +/** Asks whether it is offered, and renders nothing when it is not. */ +export default function StoredUrlOption({ + query, + ...rest +}: { query: StoredUrlQuery | null } & Parameters<typeof StoredUrlCheckbox>[0]) { + const offered = useStoredUrlOffered(query); + if (!offered) return null; + return <StoredUrlCheckbox {...rest} />; +} diff --git a/umtool/components/projects/ClaimBench.tsx b/umtool/components/projects/ClaimBench.tsx @@ -3,6 +3,8 @@ import Link from "next/link"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; +import { StoredUrlCheckbox, useStoredUrlOffered } from "@/components/clips/StoredUrlOption"; +import { STORED_URL_UI_MODE } from "yt-dlp-transcript-common/lib/storedMediaUrl"; import { ReaderPane } from "@/components/ui/reader-pane"; import { citationText } from "@/lib/research/facets.mjs"; import { BenchBody, VerdictBar } from "./bench/BenchShell"; @@ -249,13 +251,22 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) { setNote(gaps.length ? `saved — still missing ${gaps.join(", ")}` : "saved — adjudicated"); }, [data.project, claim.id, token, scope, confidence, population, valueKind, basis, flagText, roles]); + // "Cut from the stored media URL" (release 32 R6): offered when the claim's + // record stores one (Odysee). + const storedOffered = useStoredUrlOffered(claim.video ? { project: data.project, clip: claim.id } : null); + const [fromStored, setFromStored] = useState(false); const fetchWindow = useCallback(async () => { setFetching(true); setNote(null); const r = await fetch("/api/report/fetch", { method: "POST", headers: { "content-type": "application/json" }, - body: JSON.stringify({ project: data.project, clip: claim.id, pad: data.pad + 5 }), + body: JSON.stringify({ + project: data.project, + clip: claim.id, + pad: data.pad + 5, + ...(storedOffered && fromStored ? { storedUrl: STORED_URL_UI_MODE } : {}), + }), }); const j = (await r.json()) as Record<string, unknown>; if (!r.ok) { @@ -273,7 +284,7 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) { } setFetching(false); window.location.reload(); - }, [data.project, claim.id, data.pad]); + }, [data.project, claim.id, data.pad, storedOffered, fromStored]); // ---- the bench shell's verdict bar and reader (P4b) ------------------------ const missing = [ @@ -393,6 +404,9 @@ export default function ClaimBench({ data }: { data: ClaimBenchData }) { > {fetching ? "fetching…" : `fetch ±${data.pad}s`} </button> + {storedOffered && ( + <StoredUrlCheckbox checked={fromStored} onChange={setFromStored} disabled={fetching} compact /> + )} </div> )} diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -9,6 +9,8 @@ import { useRouter } from "next/navigation"; import Waveform, { type Peaks } from "@/components/Waveform"; import { badgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; +import { StoredUrlCheckbox, useStoredUrlOffered } from "@/components/clips/StoredUrlOption"; +import { STORED_URL_UI_MODE } from "yt-dlp-transcript-common/lib/storedMediaUrl"; import { ReaderPane, paperButtonVariants } from "@/components/ui/reader-pane"; import { citationText } from "@/lib/research/facets.mjs"; import { BenchBody, VerdictBar } from "./bench/BenchShell"; @@ -1511,6 +1513,11 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { // its pad from what is on disk RIGHT NOW and says which number it will ask // for; the route refuses a window it can already serve; and a job that ran // still has to show a wider file before this claims anything arrived. + // "Cut from the stored media URL" (release 32 R6): offered when the clip's + // record stores one (Odysee); every window fetch below asks with it when ticked. + const storedOffered = useStoredUrlOffered({ project: data.project, clip: clip.id }); + const [fromStored, setFromStored] = useState(false); + const storedAsk = storedOffered && fromStored ? { storedUrl: STORED_URL_UI_MODE } : {}; const fetchMore = useCallback( async (pads: { padBefore: number; padAfter: number }) => { const had = windows[0] ?? null; @@ -1524,6 +1531,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { clip: clip.id, padBefore: round2(pads.padBefore), padAfter: round2(pads.padAfter), + ...storedAsk, }), }); if (!r.ok) { @@ -1563,7 +1571,9 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { setBusy(null); setNote("the fetch is still running; reload to pick it up"); }, - [data.project, clip.id, refresh, windows], + // `storedAsk` is named by what it is made of. + // eslint-disable-next-line react-hooks/exhaustive-deps + [data.project, clip.id, refresh, windows, storedOffered, fromStored], ); // ---- the whole recording -------------------------------------------------- @@ -2554,6 +2564,9 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { > Fetch whole source via editor </button> + {storedOffered && ( + <StoredUrlCheckbox checked={fromStored} onChange={setFromStored} disabled={!!busy} compact /> + )} </div> )} diff --git a/umtool/components/projects/FetchUnfetchedButton.tsx b/umtool/components/projects/FetchUnfetchedButton.tsx @@ -2,6 +2,8 @@ import { useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; +import { StoredUrlCheckbox } from "@/components/clips/StoredUrlOption"; +import { STORED_URL_UI_MODE } from "yt-dlp-transcript-common/lib/storedMediaUrl"; // --------------------------------------------------------------------------- // "Fetch the clips nobody can watch yet." @@ -19,6 +21,10 @@ import { buttonVariants } from "@/components/ui/button"; // // STOP ABANDONS, IT DOES NOT KILL. The in-flight fetch is already paid for and // its bytes are worth keeping; what Stop means is "start no more". +// +// "Cut from the stored media URL" (release 32 R6) is offered when some of the +// clips' records store one (`storedUrlClips`, counted on the server); ticked, +// every fetch asks with it — a clip with none is fetched as usual. // --------------------------------------------------------------------------- type Pending = { id: string; padBefore: number; padAfter: number }; @@ -28,13 +34,17 @@ type JobView = { id: string; state: "running" | "done" | "failed"; error: string export default function FetchUnfetchedButton({ project, pending, + storedUrlClips = 0, }: { project: string; // The clips that need judgement and have nothing cached holding them, in // walk order. Computed on the server, where `fetched` already is. pending: Pending[]; + // How many of them store a media URL the editor can cut from. + storedUrlClips?: number; }) { const [running, setRunning] = useState(false); + const [fromStored, setFromStored] = useState(false); const [done, setDone] = useState(0); const [msg, setMsg] = useState<string | null>(null); const [failed, setFailed] = useState(false); @@ -88,6 +98,7 @@ export default function FetchUnfetchedButton({ clip: clip.id, padBefore: clip.padBefore, padAfter: clip.padAfter, + ...(storedUrlClips > 0 && fromStored ? { storedUrl: STORED_URL_UI_MODE } : {}), }), }); const body = (await res.json().catch(() => ({}))) as { @@ -174,6 +185,14 @@ export default function FetchUnfetchedButton({ stop </button> )} + {storedUrlClips > 0 && ( + <StoredUrlCheckbox + checked={fromStored} + onChange={setFromStored} + disabled={running} + className="basis-full" + /> + )} {msg && ( <span data-fetch-unfetched-msg="" diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -10,6 +10,7 @@ import { listTakes } from "@/lib/report/takes.mjs"; import { buttonVariants } from "@/components/ui/button"; import { clipBenchHref, mixHref as toolsMixHref, projectHref, takesHref } from "@/lib/hrefs"; import FetchUnfetchedButton from "../FetchUnfetchedButton"; +import { clipRecord, storedUrlOf } from "@/lib/clips/stored"; import { RowControls, RowNotes, TimelineList } from "../TimelineEditor"; import { Pill, TONE, hms, type ReportTabProps } from "./shared"; @@ -39,6 +40,16 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor // What the walk is waiting on: the same clips the rows below mark "not // fetched yet". const pendingFetch = unfetchedNeedingJudgement(clips) as string[]; + // How many of them store a media URL the editor can cut from (release 32 R6): + // the button offers "Cut from the stored media URL" only when some do. + const storedPending = ( + await Promise.all( + pendingFetch.map(async (id) => { + const rec = clipRecord(m, id); + return rec ? (await storedUrlOf(rec.channel, rec.video)).stored : false; + }), + ) + ).filter(Boolean).length; const walkStart = (readiness.readyIds[0] as string | undefined) ?? clips[0]?.id; const showAll = search.all === "1"; const takes = await listTakes(project.dir); @@ -140,6 +151,7 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor <FetchUnfetchedButton project={project.id} pending={pendingFetch.map((id) => ({ id, padBefore: 20, padAfter: 20 }))} + storedUrlClips={storedPending} /> </div> )} diff --git a/umtool/components/research/Reader.tsx b/umtool/components/research/Reader.tsx @@ -1,5 +1,6 @@ "use client"; +import StoredUrlOption from "@/components/clips/StoredUrlOption"; import Link from "next/link"; import { useEffect, useRef, useState } from "react"; import { VIDEO_STATE_LABELS, type VideoState } from "yt-dlp-transcript-common/lib/availability"; @@ -68,6 +69,8 @@ export default function Reader({ onCopy, fetchState, onFetch, + fromStored = false, + onFromStored, onPin, pinning, pinned, @@ -88,6 +91,9 @@ export default function Reader({ onCopy: () => void; fetchState: FetchAnswer | { state: "asking" } | null; onFetch: () => void; + /** "Cut from the stored media URL" (release 32 R6): offered when the record stores one. */ + fromStored?: boolean; + onFromStored?: (v: boolean) => void; }) { const [playing, setPlaying] = useState<LocalMedia | null>(null); const video = useRef<HTMLVideoElement>(null); @@ -191,6 +197,15 @@ export default function Reader({ {fetching ? "Fetching…" : "Fetch clip"} </button> )} + {(!file || file.kind !== "window") && onFromStored && ( + <StoredUrlOption + query={{ channel: win.channelSlug, video: win.videoId }} + checked={fromStored} + onChange={onFromStored} + disabled={!!fetching} + compact + /> + )} <span className="ml-auto inline-flex items-center gap-1"> <button type="button" aria-label="Narrower window" className={paperButtonVariants()} disabled={span <= 15} onClick={() => onSpan(Math.max(15, Math.round(span / 2)))}> − diff --git a/umtool/components/research/ResearchView.tsx b/umtool/components/research/ResearchView.tsx @@ -1,5 +1,6 @@ "use client"; +import { STORED_URL_UI_MODE } from "yt-dlp-transcript-common/lib/storedMediaUrl"; import Link from "next/link"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; @@ -115,6 +116,7 @@ export default function ResearchView({ const [winLoading, setWinLoading] = useState(false); const [copied, setCopied] = useState(false); const [fetchState, setFetchState] = useState<FetchAnswer | { state: "asking" } | null>(null); + const [fromStored, setFromStored] = useState(false); const [cases, setCases] = useState<CaseSummary[]>(initialCases); const [board, setBoard] = useState<string | null>(initialCase && initialCases.some((c) => c.id === initialCase) ? initialCase : null); const [pinAsk, setPinAsk] = useState<"pin" | "new" | null>(null); @@ -373,6 +375,7 @@ export default function ResearchView({ start, end, reason: `umtool research: "${res.query}" @ ${win.citation.text.match(/@ ([\d:]+)\]/)?.[1] ?? start}`, + ...(fromStored ? { storedUrl: STORED_URL_UI_MODE } : {}), }), }), ); @@ -395,7 +398,7 @@ export default function ResearchView({ } catch (e) { setFetchState({ state: "failed", message: (e as Error).message }); } - }, [res, litHit, win]); + }, [res, litHit, win, fromStored]); // ── pin to a board (R2) ── const pinTo = useCallback( @@ -671,6 +674,8 @@ export default function ResearchView({ onCopy={copy} fetchState={fetchState} onFetch={fetchClip} + fromStored={fromStored} + onFromStored={setFromStored} onPin={pin} pinning={pinWorking} pinned={pinned} diff --git a/umtool/lib/clips/cited.test.ts b/umtool/lib/clips/cited.test.ts @@ -71,3 +71,13 @@ test("a cooldown says the platform is rate-limiting; an audio-check failure says const f = await lib.fetchCitedClip({ job: "j2", target }, m.deps); assert.match(f.state === "failed" ? f.message : "", /corrupt audio/); }); + +test("Cut from the stored media URL rides on the fetch as fetch_clip's storedUrl (release 32 R6)", async () => { + const e = editor([() => ({ status: 202, body: { cached: false, jobId: "j3", from: 0, to: 9 } })]); + const target = { channel: "chan", video: "v1", from: 3, to: 6 }; + await lib.fetchCitedClip({ target, reason: "review", storedUrl: "fallback" }, e.deps); + assert.equal(e.calls[0].body?.storedUrl, "fallback"); + const plain = editor([() => ({ status: 202, body: { cached: false, jobId: "j4", from: 0, to: 9 } })]); + await lib.fetchCitedClip({ target, reason: "review" }, plain.deps); + assert.equal("storedUrl" in (plain.calls[0].body ?? {}), false); +}); diff --git a/umtool/lib/clips/cited.ts b/umtool/lib/clips/cited.ts @@ -114,7 +114,9 @@ const deps: FetchClipDeps = { * 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 }, + req: + | { job: string; target?: CitedTarget } + | { target: CitedTarget; reason: string; report?: string; storedUrl?: "fallback" | "only" }, d: FetchClipDeps = deps, ): Promise<CitedFetchAnswer> { const args = @@ -127,6 +129,8 @@ export async function fetchCitedClip( end: req.target.to, reason: req.reason, ...(req.report ? { report: req.report } : {}), + // Cut from the stored media URL (release 32 R6): fetch_clip's field. + ...(req.storedUrl ? { storedUrl: req.storedUrl } : {}), wait_seconds: 0, }; const v = validateFetchClipArgs(args); diff --git a/umtool/lib/clips/stored.test.ts b/umtool/lib/clips/stored.test.ts @@ -0,0 +1,56 @@ +// "Cut from the stored media URL" (release 32 R6): umtool offers it only for a +// record that stores a media file address the editor can cut from — an Odysee +// record with its one CDN format — and finds a project clip's record the way +// fetch-via-editor.mjs does. A synthetic corpus in a temp dir; no network. +// +// Run with: pnpm --filter umtool exec tsx --test lib/clips/stored.test.ts +import { before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +let lib: typeof import("./stored"); +let channels: string; + +async function record(slug: string, id: string, info: Record<string, unknown>) { + const dir = path.join(channels, slug, "data", id); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(info)); +} + +before(async () => { + channels = path.join(await mkdtemp(path.join(os.tmpdir(), "umtool-stored-")), "channels"); + process.env.CHANNELS_DIR = channels; + lib = await import("./stored"); + await record("od", "s1", { + webpage_url: "https://odysee.com/@demo:1/s1:1", + formats: [{ url: "https://player.odycdn.com/v6/streams/s1/f0.mp4", protocol: "https" }], + }); + await record("od", "n1", { webpage_url: "https://odysee.com/@demo:1/n1:1" }); + await record("yt", "y1", { + webpage_url: "https://www.youtube.com/watch?v=y1", + formats: [{ url: "https://player.odycdn.com/v6/streams/y1/f0.mp4", protocol: "https" }], + }); +}); + +test("offered only for a record on an allowlisted platform that stores its CDN file", async () => { + assert.deepEqual(await lib.storedUrlOf("od", "s1", channels), { stored: true, host: "player.odycdn.com", platform: "odysee" }); + assert.deepEqual(await lib.storedUrlOf("od", "n1", channels), { stored: false }); + assert.deepEqual(await lib.storedUrlOf("yt", "y1", channels), { stored: false }, "not an allowlisted platform"); + assert.deepEqual(await lib.storedUrlOf("od", "missing", channels), { stored: false }); + assert.deepEqual(await lib.storedUrlOf("..", "s1", channels), { stored: false }); +}); + +test("a project clip's record: the clip's channel, else the manifest's; a ledger claim's too", () => { + const m = { + provenance: { channelSlug: "od" }, + timeline: [{ id: "c1", video: "s1" }, { id: "c2", channel: "yt", video: "y1" }, { id: "t1", type: "card" }], + ledger: [{ id: "l1", video: "n1" }], + }; + assert.deepEqual(lib.clipRecord(m, "c1"), { channel: "od", video: "s1" }); + assert.deepEqual(lib.clipRecord(m, "c2"), { channel: "yt", video: "y1" }); + assert.deepEqual(lib.clipRecord(m, "l1"), { channel: "od", video: "n1" }); + assert.equal(lib.clipRecord(m, "t1"), null); + assert.equal(lib.clipRecord(m, "nope"), null); +}); diff --git a/umtool/lib/clips/stored.ts b/umtool/lib/clips/stored.ts @@ -0,0 +1,56 @@ +import path from "node:path"; +import { storedMediaUrl } from "yt-dlp-transcript-common/lib/storedMediaUrl-server"; +import { CHANNELS_DIR } from "@/lib/paths"; +import { SourceError } from "@/lib/research/sources"; +import { resolveClip } from "@/lib/report/serve.mjs"; + +// --------------------------------------------------------------------------- +// "Cut from the stored media URL" (release 32 R6): whether a span's record +// stores a media file address the editor may cut a window from +// (lib/storedMediaUrl.ts — Odysee's CDN file only). Every fetch surface asks +// this before it offers the option, so it is shown only where it can do +// something. The editor's corpus is CHANNELS_DIR: the fetch is the editor's. +// --------------------------------------------------------------------------- + +export type StoredUrlAnswer = { stored: boolean; host?: string; platform?: string }; + +const ID = /^[\w.-]+$/; +const isDir = (v: string) => ID.test(v) && v !== "." && v !== ".."; + +/** The record `channel`/`video` names, in the editor's corpus. */ +export async function storedUrlOf(channel: string, video: string, channelsDir: string = CHANNELS_DIR): Promise<StoredUrlAnswer> { + if (!isDir(channel) || !isDir(video)) return { stored: false }; + const s = await storedMediaUrl(path.join(/* turbopackIgnore: true */ channelsDir, channel, "data", video)); + return s ? { stored: true, host: s.host, platform: s.platform } : { stored: false }; +} + +/** + * The channel and video a project clip's fetch asks the editor for — the rule + * fetch-via-editor.mjs follows: a timeline clip's `channel` (else the + * manifest's provenance.channelSlug) and `video`, or a ledger claim's. + */ +export function clipRecord( + manifest: { provenance?: { channelSlug?: string }; timeline?: unknown[]; ledger?: unknown[] }, + clipId: string, +): { channel: string; video: string } | null { + type E = { id?: unknown; channel?: unknown; video?: unknown }; + const entry = + ((manifest.timeline ?? []) as E[]).find((e) => e?.id === clipId) ?? + ((manifest.ledger ?? []) as E[]).find((e) => e?.id === clipId); + if (!entry) return null; + const channel = typeof entry.channel === "string" && entry.channel ? entry.channel : manifest.provenance?.channelSlug; + const video = typeof entry.video === "string" ? entry.video : ""; + return channel && video ? { channel, video } : null; +} + +/** For a project clip (the benches) or a channel + video (the cited player). */ +export async function storedUrlFor(q: { project?: string; clip?: string; channel?: string; video?: string }): Promise<StoredUrlAnswer> { + if (q.project && q.clip) { + const r = await resolveClip(q.project, q.clip); + if ("error" in r) throw new SourceError(String(r.error), Number(r.status) || 404); + const rec = clipRecord(r.manifest, q.clip); + return rec ? storedUrlOf(rec.channel, rec.video) : { stored: false }; + } + if (q.channel && q.video) return storedUrlOf(q.channel, q.video); + throw new SourceError("project and clip, or channel and video, are required"); +} diff --git a/umtool/lib/report/driver.mjs b/umtool/lib/report/driver.mjs @@ -313,12 +313,17 @@ export function fetchSteps(project, clipId, pad) { * * @param {{ dir: string }} project * @param {string} clipId - * @param {number | { padBefore: number, padAfter: number }} pad + * @param {number | { padBefore: number, padAfter: number, storedUrl?: "fallback" | "only" | null }} pad * @returns {import("../trim").Step[]} */ export function editorFetchSteps(project, clipId, pad) { const before = typeof pad === "object" && pad ? Number(pad.padBefore) : Number(pad); const after = typeof pad === "object" && pad ? Number(pad.padAfter) : Number(pad); + // Cut from the stored media URL (release 32 R6): `--stored-url <mode>`. + const storedUrl = + typeof pad === "object" && pad && (pad.storedUrl === "fallback" || pad.storedUrl === "only") + ? pad.storedUrl + : null; return [ { cwd: PIPELINE_DIR, @@ -338,6 +343,7 @@ export function editorFetchSteps(project, clipId, pad) { String(before), "--pad-after", String(after), + ...(storedUrl ? ["--stored-url", storedUrl] : []), "--progress", "ndjson", ], diff --git a/umtool/lib/research/fetch.ts b/umtool/lib/research/fetch.ts @@ -53,13 +53,21 @@ export function answerOf(o: FetchClipOutcome): FetchAnswer { export type FetchRequest = | { job: string } - | { source: string; channel: string; video: string; start: number; end: number; reason: string }; + | { source: string; channel: string; video: string; start: number; end: number; reason: string; storedUrl?: "fallback" | "only" }; export async function fetchForReader(req: FetchRequest): Promise<FetchAnswer> { const args = "job" in req ? { job: req.job, wait_seconds: 0 } - : { channel: req.channel, video: req.video, start: req.start, end: req.end, reason: req.reason, wait_seconds: 0 }; + : { + channel: req.channel, + video: req.video, + start: req.start, + end: req.end, + reason: req.reason, + ...(req.storedUrl ? { storedUrl: req.storedUrl } : {}), + wait_seconds: 0, + }; const v = validateFetchClipArgs(args); if (!v.ok) throw new SourceError(v.error.replace(/^fetch_clip: /, "")); if (!("job" in req)) { diff --git a/umtool/report-to-video/fetch-via-editor.mjs b/umtool/report-to-video/fetch-via-editor.mjs @@ -75,7 +75,7 @@ const clipId = flag("--fetch-only") ?? flag("--clip"); // streak and the 429 stop live there, not in a shell loop here. const wantAll = argv.includes("--all"); if (!manifestPath || (!clipId && !wantAll) || (clipId && wantAll)) { - die("usage: fetch-via-editor.mjs <manifest.json> (--fetch-only <clipId> [--full] | --all) [--max-height N] [--pad N] [--pad-before N] [--pad-after N] [--progress ndjson]"); + die("usage: fetch-via-editor.mjs <manifest.json> (--fetch-only <clipId> [--full] | --all) [--max-height N] [--stored-url fallback|only] [--pad N] [--pad-before N] [--pad-after N] [--progress ndjson]"); } // THE WHOLE RECORDING INSTEAD OF A WINDOW. For a clip whose windows would tile @@ -105,6 +105,20 @@ if ( ); } +// CUT FROM THE STORED MEDIA URL (release 32 R6): the editor's `storedUrl` — +// "fallback" (the page first, the record's stored media file when the platform +// refuses the lookup) or "only" (no page request). Odysee only, and only a +// record that stores one; any other is fetched as usual. Windows only. +const STORED_URL_MODES = ["never", "fallback", "only"]; +const storedUrlArg = flag("--stored-url"); +if (storedUrlArg !== undefined && !STORED_URL_MODES.includes(storedUrlArg)) { + die(`--stored-url ${storedUrlArg} must be one of ${STORED_URL_MODES.join(", ")}`); +} +if (storedUrlArg !== undefined && storedUrlArg !== "never" && argv.includes("--full")) { + die("--stored-url cuts a window; --full is the whole recording"); +} +const storedUrl = storedUrlArg && storedUrlArg !== "never" ? { storedUrl: storedUrlArg } : {}; + const editorUrl = (process.env.ARCHILYZER_EDITOR_URL ?? DEFAULT_EDITOR).replace(/\/+$/, ""); const token = process.env.WORKER_TOKEN ?? ""; if (!token) { @@ -242,6 +256,7 @@ if (wantAll) { requestedBy: "umtool", manifest: manifestId, ...(maxHeight !== undefined ? { maxHeight } : {}), + ...storedUrl, }), }); const body = await res.json().catch(() => ({})); @@ -357,6 +372,7 @@ const res = await ask(`${editorUrl}/api/media/fetch-window`, { webpageUrl: entry.webpageUrl ?? undefined, ...(wantFull ? { full: true } : { from, to, pad: Math.max(padBefore, padAfter) }), ...(maxHeight !== undefined ? { maxHeight } : {}), + ...storedUrl, requestedBy: "umtool", manifest: manifestId, clipId: entry.id, diff --git a/umtool/report-to-video/fetch-via-editor.test.mjs b/umtool/report-to-video/fetch-via-editor.test.mjs @@ -119,6 +119,23 @@ test("no --max-height sends none; a bad one is refused before any request", asyn } }); +test("--stored-url rides on a window request; never sends none; a bad one or one with --full is refused", async () => { + const ed = await stubEditor(CACHED(720)); + try { + assert.equal((await run(ed.url, ["--stored-url", "fallback"])).code, 0); + assert.equal(ed.posts[0].storedUrl, "fallback"); + assert.equal((await run(ed.url, ["--stored-url", "never"])).code, 0); + assert.equal("storedUrl" in ed.posts[1], false); + for (const args of [["--stored-url", "always"], ["--full", "--stored-url", "only"]]) { + const { code } = await run(ed.url, args); + assert.equal(code, 1, args.join(" ")); + } + assert.equal(ed.posts.length, 2); + } finally { + await ed.close(); + } +}); + // ---- the wait ------------------------------------------------------------------ /**