commit a7c20abf8e606abafe1927fd175a15f0b60ca8d3
parent a4b2b173ccc1f9c4dca0af6f10f7720ff6ecbadc
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 01:36:35 -0500
umtool: Export ▾ from the clip editor -- as cut, with N s of context, raw / full exchange (UI notes item 12)
The bench's reader and Play the cut gain Export ▾ beside Export clip and raw:
"As cut (no chrome)", "With context" (what the cut plays and N s either side,
1-120, as recorded) and "Raw / full exchange" (a from-to span of source
seconds, starting at the clip's extent +-30 s). Names stay the clip id and its
date, with the kind in them (-ctx<N>, -raw, -raw-<from>-<to>) so the kinds
never overwrite each other.
Every export from the app is now ONE umtool job on the app's runner (POST
/api/report/clip-export answers 202 and the job; GET ?job= is polled for its
`export` event): `umtool export ... --progress ndjson`, which takes the
machine's heavy slot itself (heavy-gate.mjs, a declared 600 MB, so it runs
beside others while memory allows). A context or raw export whose span no
cached window holds is refused unless asked with `fetch`, which the menu
always sends: the same job then asks the editor first through the bench's own
fetch-window path (fetch-via-editor.mjs --fetch-only with the pads it needs).
`umtool export` gains --context N, --raw --from S --to S and --fetch. A cut
still fetches nothing ("fetch it first", unchanged).
No "send to phone": nothing in the repo sends a file to a phone; Download is
the phone's way, and the docs say so.
Also: the bench's snap group reads "snap edge to nearest pause".
Fixture export-fixture and a new clip-export.spec test (context, the
not-on-disk refusal, the full exchange fetched through the editor stub);
clipExport.test.mjs covers the new kinds, names, spans and job steps; docs in
knobs.md, clip-bench.md, cli.md.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
13 files changed, 674 insertions(+), 107 deletions(-)
diff --git a/umtool/app/api/report/clip-export/route.ts b/umtool/app/api/report/clip-export/route.ts
@@ -1,23 +1,29 @@
+import { getJob, jobView, runningJob, startJob } from "@/lib/jobs";
import { projectRef } from "@/lib/projects";
import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
import { refuseCaller } from "@/lib/report/caller";
-import { EXPORT_KINDS, ExportRefused, exportClip } from "@/lib/report/clipExport.mjs";
+import { EXPORT_KINDS, ExportRefused, contextSeconds, exportNeeds, exportSteps, spanOf } from "@/lib/report/clipExport.mjs";
import { cannotOpen, localRequest } from "@/lib/report/openFolder.mjs";
export const dynamic = "force-dynamic";
// EXPORT ONE CLIP (umtool/docs/knobs.md, "Export one clip"): a clean mp4 of a
-// clip -- the cut's edges, its gaps out as jump cuts, its mute -- or its whole
-// fetched window (`raw`), with no deck chrome, into <project>/exports/.
+// clip, no deck chrome, into <project>/exports/ -- as the cut plays it (`cut`:
+// its edges, its gaps out as jump cuts, its mute), with N s either side
+// (`context`), or a stretch as recorded (`raw`: the fetched window, or a
+// `span` -- the full exchange).
//
-// POST { project, clip, take?, kind?: "cut" | "raw" }
-// -> { ok, name, rel, size, seconds, summary, notes, download, canOpen, openWhy? }
+// POST { project, clip, take?, kind?: "cut" | "context" | "raw", context?: N, span?: {from, to}, fetch?: true }
+// -> 202 { job } ONE umtool job on the app's runner (lib/jobs.ts: one at a
+// time, a log, Stop): `fetch: true` asks the editor first for what a
+// context or raw export needs that is not on disk (the bench's own
+// fetch-window path), then `umtool export … --progress ndjson`, which
+// runs in the machine's heavy slot. 409 when a cut's window is not on
+// disk ("fetch it first"), when a context/raw export needs a fetch and
+// `fetch` was not asked, or when another job is running.
+// GET ?job=<id> -> { job, done?: { name, rel, size, seconds, summary, notes, download, canOpen, openWhy? }, error? }
//
-// Answered when the file is written: one short clip, re-encoded once on this
-// machine (seconds, not minutes), outside the job runner and the heavy slot,
-// so it never waits behind a build. A second ask for the same file waits for
-// the first. Nothing is fetched: a clip whose window is not on disk is a 409
-// saying so. Names, never paths: a project of the scan, a clip of its cut.
+// Names, never paths: a project of the scan, a clip of its cut.
const headers = { "cache-control": "no-store" };
export async function POST(request: Request) {
@@ -31,36 +37,79 @@ export async function POST(request: Request) {
const clip = String(body.clip ?? "");
if (!clip) return Response.json({ error: "which clip?" }, { status: 400, headers });
const take = typeof body.take === "string" && body.take ? body.take : null;
- const kind = body.kind === undefined || body.kind === null || body.kind === "" ? "cut" : String(body.kind);
+ const kind = (body.kind === undefined || body.kind === null || body.kind === "" ? "cut" : String(body.kind)) as "cut" | "context" | "raw";
if (!(EXPORT_KINDS as readonly string[]).includes(kind)) {
return Response.json({ error: `kind is one of ${EXPORT_KINDS.join(", ")}` }, { status: 400, headers });
}
try {
- const r = await exportClip(project, clip, { take, kind: kind as "cut" | "raw" });
+ const context = kind === "context" ? contextSeconds(body.context) : undefined;
+ const span = kind === "raw" ? spanOf(body.span) : null;
+ const need = await exportNeeds(project, clip, { take, kind, ...(context !== undefined ? { context } : {}), span });
+ if (kind === "cut" && !need.held) {
+ throw new ExportRefused(`${clip}: its window is not on disk — fetch it first (the Cut tab's Fetch, or \`umtool fetch ${project.id}\`)`, 409);
+ }
+ if (!need.held && body.fetch !== true) {
+ throw new ExportRefused(
+ `${clip}: what this export needs is not on disk (−${need.padBefore} s / +${need.padAfter} s around the clip) — ask again with fetch, which asks the editor first`,
+ 409,
+ );
+ }
+ const running = runningJob();
+ if (running) return Response.json({ error: `a job is already running (${running.kind}) — export when it is done`, running: jobView(running) }, { status: 409, headers });
+ let manifestPath: string | null = null;
+ if (take && !need.held) {
+ const { writePlayManifest } = await import("@/lib/report/takeManifest.mjs");
+ const { readManifest } = await import("@/lib/projects/report.mjs");
+ manifestPath = await writePlayManifest(project.dir, take, await readManifest(project.dir));
+ }
+ const steps = await exportSteps(project, clip, {
+ take,
+ kind,
+ ...(context !== undefined ? { context } : {}),
+ span,
+ fetch: need.held ? null : { padBefore: need.padBefore, padAfter: need.padAfter },
+ manifestPath,
+ });
+ const job = startJob(`export ${project.id}/${clip}`, steps, { project: project.id });
+ return Response.json({ ok: true, fetching: !need.held, job: jobView(job) }, { status: 202, headers });
+ } catch (e) {
+ const status = e instanceof ExportRefused ? e.status : 500;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
+ }
+}
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const id = url.searchParams.get("job");
+ const job = id ? getJob(id) : null;
+ if (!job) return Response.json({ error: "no such job" }, { status: 404, headers });
+ const view = jobView(job, Math.max(0, job.log.length - 12));
+ const ev = [...job.events].reverse().find((e) => e.ev === "export" || e.ev === "export-failed") as Record<string, unknown> | undefined;
+ if (ev?.ev === "export" && typeof ev.name === "string" && job.project) {
const no = cannotOpen();
const local = localRequest(request.headers);
const openWhy = no ?? (local.ok ? null : `Open folder works on the machine umtool runs on: ${local.why}`);
return Response.json(
{
- ok: true,
- clip: r.clip,
- take: r.take,
- kind: r.kind,
- name: r.name,
- rel: r.rel,
- size: r.size,
- mtimeMs: r.mtimeMs,
- seconds: r.seconds,
- summary: r.summary,
- notes: r.notes,
- download: `/api/report/exports?${new URLSearchParams({ project: project.id, name: r.name, v: String(r.mtimeMs) }).toString()}`,
- canOpen: !openWhy,
- ...(openWhy ? { openWhy } : {}),
+ job: view,
+ done: {
+ clip: ev.clip,
+ kind: ev.kind,
+ name: ev.name,
+ rel: ev.rel,
+ size: ev.size,
+ mtimeMs: ev.mtimeMs,
+ seconds: ev.seconds,
+ summary: ev.summary,
+ notes: ev.notes ?? [],
+ download: `/api/report/exports?${new URLSearchParams({ project: job.project, name: ev.name, v: String(ev.mtimeMs ?? "") }).toString()}`,
+ canOpen: !openWhy,
+ ...(openWhy ? { openWhy } : {}),
+ },
},
{ headers },
);
- } catch (e) {
- const status = e instanceof ExportRefused ? e.status : 500;
- return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
}
+ const error = ev?.ev === "export-failed" ? String(ev.error ?? "the export failed") : job.state === "failed" ? (job.error ?? "the export failed") : null;
+ return Response.json({ job: view, ...(error ? { error } : {}) }, { headers });
}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -55,8 +55,10 @@
// umtool snapshot <project> [--label L] copy the manifest into revisions/
// umtool diff <project> <snapshot> what changed since that snapshot
// umtool export <project> --format toc-bbcode|toc-markdown|description|chapters [--variant V] [--first TITLE]
-// umtool export <project> <clip> [--raw] [--take T] [--open] [--json] one clip, clean, into
-// <project>/exports/: the cut's edges, gaps out, mute (--raw: the whole fetched window)
+// umtool export <project> <clip> [--context N | --raw [--from S --to S]] [--fetch] [--take T] [--open] [--json]
+// one clip, clean, into <project>/exports/: the cut's edges, gaps out, mute (--context: what
+// the cut plays ± N s, as recorded; --raw: the fetched window, or a span, as recorded; --fetch:
+// ask the editor first for what is not on disk), in the heavy slot
// umtool check-sources [<project>…] prints the re-check chain
// umtool notes [<site>/<report> | <project> | --all] [--open|--resolved|--all-status] [--json]
// umtool notes reply <id> "<text>" [--resolve] | resolve | wontfix | reopen <id>
@@ -714,14 +716,49 @@ async function cmdExport() {
}
// One clip, clean (umtool/docs/knobs.md, "Export one clip"): the cut's edges,
-// its gaps out, its mute -- or `--raw`, the whole fetched window -- with no
-// deck chrome. Runs here, with this machine's ffmpeg; nothing is fetched.
+// its gaps out, its mute -- `--context N`, what the cut plays with N s either
+// side, as recorded -- `--raw [--from S --to S]`, a stretch as recorded (the
+// full exchange) -- with no deck chrome. Runs here, with this machine's
+// ffmpeg, in the heavy slot (a small declared estimate: it runs beside others
+// when memory allows). `--fetch` asks the editor first for what a context or
+// raw export needs that is not on disk (fetch-via-editor.mjs, the bench's own
+// path); otherwise nothing is fetched. `--progress ndjson`: one `export` event
+// on stdout at the end (the app's export job reads it).
async function cmdExportClip(p, clipId) {
- const { exportClip } = await import("../lib/report/clipExport.mjs");
+ const { EXPORT_ESTIMATE_MB, exportClip, exportNeeds } = await import("../lib/report/clipExport.mjs");
+ const ndjson = val("--progress") === "ndjson";
+ const kind = has("--raw") ? "raw" : val("--context") !== undefined ? "context" : "cut";
+ const context = val("--context");
+ const from = val("--from");
+ const to = val("--to");
+ if (kind !== "raw" && (from !== undefined || to !== undefined)) die("--from/--to are a raw export's span: add --raw");
+ if ((from === undefined) !== (to === undefined)) die("a raw span is --from S --to S, both");
+ const span = from !== undefined ? { from: Number(from), to: Number(to) } : null;
+ const take = val("--take") ?? null;
+ const say = (line) => (ndjson || json ? console.error(line) : console.log(line));
+ if (has("--fetch") && kind !== "cut") {
+ let need;
+ try {
+ need = await exportNeeds(p, clipId, { take, kind, context: context === undefined ? undefined : Number(context), span });
+ } catch (e) {
+ die(e?.message ?? String(e), 1);
+ }
+ if (!need.held) {
+ say(`fetching −${need.padBefore} s / +${need.padAfter} s around ${clipId} through the editor first`);
+ const code = await runFetchViaEditor(p, clipId, need, { take });
+ if (code !== 0) die(`the fetch did not finish (exit ${code}) — nothing exported`, 1);
+ }
+ }
+ const { withRenderSlot } = await import("../report-to-video/heavy-gate.mjs");
let r;
try {
- r = await exportClip(p, clipId, { take: val("--take") ?? null, kind: has("--raw") ? "raw" : "cut" });
+ r = await withRenderSlot(
+ ["umtool", "export", p.id, clipId, kind],
+ () => exportClip(p, clipId, { take, kind, ...(context !== undefined ? { context: Number(context) } : {}), span }),
+ { estimateMb: EXPORT_ESTIMATE_MB, say },
+ );
} catch (e) {
+ if (ndjson) console.log(JSON.stringify({ ev: "export-failed", clip: clipId, kind, error: e?.message ?? String(e) }));
die(e?.message ?? String(e), 1);
}
let opened = null;
@@ -730,13 +767,32 @@ async function cmdExportClip(p, clipId) {
opened = await openFolder({ dir: path.dirname(r.abs), file: r.abs });
}
const { plan: _plan, ...view } = r;
+ if (ndjson) return console.log(JSON.stringify({ ev: "export", ...view, abs: undefined }));
if (json) return out({ ...view, ...(opened ? { opened } : {}) });
console.log(r.abs);
- console.log(` ${r.kind === "raw" ? "raw window" : "the cut's clip"}: ${r.summary} · ${(r.size / 1e6).toFixed(1)} MB`);
+ console.log(` ${r.kind === "raw" ? "raw" : r.kind === "context" ? "with context" : "the cut's clip"}: ${r.summary} · ${(r.size / 1e6).toFixed(1)} MB`);
for (const n of r.notes) console.log(` NOTE ${n}`);
if (opened) console.log(opened.ok ? ` opened ${path.dirname(r.abs)} (${opened.how})` : ` could not open the folder: ${opened.error}`);
}
+/** The bench's own fetch (driver.mjs editorFetchSteps: fetch-via-editor.mjs --fetch-only), run here with its output on stderr. */
+async function runFetchViaEditor(p, clipId, need, { take = null } = {}) {
+ const { editorFetchSteps } = await import("../lib/report/driver.mjs");
+ let manifestPath = null;
+ if (take) {
+ const { writePlayManifest } = await import("../lib/report/takeManifest.mjs");
+ manifestPath = await writePlayManifest(p.dir, take, await readManifest(p.dir));
+ }
+ const [step] = editorFetchSteps(p, clipId, { padBefore: need.padBefore, padAfter: need.padAfter }, { manifestPath });
+ const { spawn } = await import("node:child_process");
+ return new Promise((resolve) => {
+ const argvF = step.argv.filter((a, i, all) => !(a === "--progress" || all[i - 1] === "--progress"));
+ const child = spawn(process.execPath, argvF.slice(1), { cwd: step.cwd, stdio: ["ignore", "inherit", "inherit"] });
+ child.on("error", () => resolve(127));
+ child.on("close", (code) => resolve(code ?? 1));
+ });
+}
+
async function cmdCheckSources() {
// Print, never run -- the same posture as `build`. With no arguments, the
// projects the dashboard would re-check: never checked, or older than 30 d.
@@ -859,8 +915,10 @@ function usage() {
" umtool snapshot <project> [--label L] copy the manifest into revisions/",
" umtool diff <project> <snapshot> what changed since that snapshot",
" umtool export <project> --format toc-bbcode|toc-markdown|description|chapters [--variant V] [--first TITLE]",
- " umtool export <project> <clip> [--raw] [--take T] [--open] one clip, clean, into <project>/exports/:",
- " the cut's edges, its gaps out, its mute; --raw the whole fetched window; --open shows it",
+ " umtool export <project> <clip> [--context N | --raw [--from S --to S]] [--fetch] [--take T] [--open] one clip,",
+ " clean, into <project>/exports/: the cut's edges, its gaps out, its mute; --context N what the cut",
+ " plays ± N s; --raw the whole fetched window, or a span (the full exchange), as recorded; --fetch",
+ " asks the editor first for what that needs; in the heavy slot; --open shows it",
" umtool check-sources [<project>…] prints the re-check chain (never-checked/old when no args)",
" umtool notes [<site>/<report>|<project>|--all] the operator's notes, as markdown (open ones)",
" umtool notes reply <id> \"<text>\" [--resolve] answer one; resolve | wontfix | reopen <id>",
diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx
@@ -552,6 +552,8 @@ export default function ClipBench({
// Export clip (ClipExport.tsx): this clip, clean, into the project's exports/ -- the take's clip on a take's walk.
const clipExport = useClipExport(data.project, takeId);
const [clip, setClip] = useState<Clip>(data.clip);
+ // Export ▾'s full exchange starts from the clip's saved extent.
+ const clipAround = useMemo(() => ({ start: clip.start, end: clip.end }), [clip.start, clip.end]);
const [windows, setWindows] = useState<Win[]>(data.windows);
const [cues, setCues] = useState<Cue[]>(data.cues);
const [proposed, setProposed] = useState(data.proposed);
@@ -2793,7 +2795,7 @@ export default function ClipBench({
>
Play clip
</button>
- <ClipExportButtons exp={clipExport} clip={clip.id} surface="paper" why={cached ? null : "its window is not fetched — fetch it first"} unsaved={unsaved} />
+ <ClipExportButtons exp={clipExport} clip={clip.id} surface="paper" why={cached ? null : "its window is not fetched — fetch it first"} unsaved={unsaved} around={clipAround} />
<ClipExportStatus exp={clipExport} surface="paper" />
</>
}
diff --git a/umtool/components/projects/ClipExport.tsx b/umtool/components/projects/ClipExport.tsx
@@ -19,9 +19,16 @@ import { cn } from "@/lib/utils";
// the server says when it cannot, and why). The bench's reader footer and
// Play the cut both use it; Play exports the clip at the playhead, or the one
// a note points at, through one `useClipExport`.
+//
+// EXPORT ▾ (UI notes 2026-10-30, item 12): as cut (no chrome), with N s of
+// context, raw / full exchange (a span, fetched through the editor first when
+// it is not on disk). Every export is a umtool job (POST answers 202 and the
+// job; this polls it), in the machine's heavy slot. No "send to phone": no
+// share path exists in umtool -- Download is the phone's way.
// ---------------------------------------------------------------------------
-export type ClipExportKind = "cut" | "raw";
+export type ClipExportKind = "cut" | "context" | "raw";
+export type ClipExportOpts = { context?: number; span?: { from: number; to: number } | null; fetch?: boolean };
type Done = {
clip: string;
@@ -39,14 +46,14 @@ type Done = {
export type ClipExportState =
| { k: "idle" }
- | { k: "exporting"; clip: string; kind: ClipExportKind; since: number }
+ | { k: "exporting"; clip: string; kind: ClipExportKind; since: number; fetching?: boolean; line?: string | null }
| { k: "ready"; done: Done; open: { k: "idle" } | { k: "opening" } | { k: "opened"; how: string } | { k: "failed"; error: string } }
| { k: "failed"; clip: string; kind: ClipExportKind; error: string };
export type ClipExportHandle = {
state: ClipExportState;
busy: boolean;
- run: (clip: string, kind?: ClipExportKind) => Promise<void>;
+ run: (clip: string, kind?: ClipExportKind, opts?: ClipExportOpts) => Promise<void>;
openFolder: () => Promise<void>;
dismiss: () => void;
};
@@ -59,21 +66,51 @@ export function useClipExport(project: string, take: string | null = null): Clip
const seq = useRef(0);
const busy = state.k === "exporting";
const run = useCallback(
- async (clip: string, kind: ClipExportKind = "cut") => {
+ async (clip: string, kind: ClipExportKind = "cut", opts: ClipExportOpts = {}) => {
const mine = ++seq.current;
- setState({ k: "exporting", clip, kind, since: Date.now() });
+ const since = Date.now();
+ setState({ k: "exporting", clip, kind, since });
+ const fail = (error: string) => {
+ if (mine === seq.current) setState({ k: "failed", clip, kind, error });
+ };
try {
const r = await fetch("/api/report/clip-export", {
method: "POST",
headers: { "content-type": "application/json" },
- body: JSON.stringify({ project, clip, kind, ...(take ? { take } : {}) }),
+ body: JSON.stringify({
+ project,
+ clip,
+ kind,
+ ...(take ? { take } : {}),
+ ...(kind === "context" && opts.context != null ? { context: opts.context } : {}),
+ ...(kind === "raw" && opts.span ? { span: opts.span } : {}),
+ ...(opts.fetch ? { fetch: true } : {}),
+ }),
});
- const j = (await r.json().catch(() => ({}))) as Partial<Done> & { error?: string };
+ const j = (await r.json().catch(() => ({}))) as { error?: string; fetching?: boolean; job?: { id: string } };
if (mine !== seq.current) return;
- if (!r.ok || !j.name) setState({ k: "failed", clip, kind, error: String(j.error ?? `HTTP ${r.status}`) });
- else setState({ k: "ready", done: { ...(j as Done), clip, kind }, open: { k: "idle" } });
+ if (!r.ok || !j.job?.id) return fail(String(j.error ?? `HTTP ${r.status}`));
+ const job = j.job.id;
+ setState({ k: "exporting", clip, kind, since, fetching: !!j.fetching });
+ // The job: polled until its export event (or its failure) is in.
+ for (;;) {
+ await new Promise((res) => setTimeout(res, 700));
+ if (mine !== seq.current) return;
+ const g = await fetch(`/api/report/clip-export?job=${encodeURIComponent(job)}`, { cache: "no-store" });
+ const v = (await g.json().catch(() => ({}))) as { done?: Done; error?: string; job?: { state: string; stepIndex: number; steps: unknown[]; log: string[] } };
+ if (mine !== seq.current) return;
+ if (v.done) {
+ setState({ k: "ready", done: { ...v.done, clip, kind }, open: { k: "idle" } });
+ return;
+ }
+ if (v.error || !g.ok) return fail(String(v.error ?? `HTTP ${g.status}`));
+ if (v.job && v.job.state !== "running") return fail(v.job.state === "done" ? "the job ended without an export" : `the job ${v.job.state}`);
+ const fetching = !!j.fetching && (v.job?.stepIndex ?? 0) < (v.job?.steps.length ?? 1) - 1;
+ const line = v.job?.log.filter((l) => !l.startsWith("$ ") && !l.startsWith("---")).at(-1) ?? null;
+ setState({ k: "exporting", clip, kind, since, fetching, line });
+ }
} catch (e) {
- if (mine === seq.current) setState({ k: "failed", clip, kind, error: e instanceof Error ? e.message : String(e) });
+ fail(e instanceof Error ? e.message : String(e));
}
},
[project, take],
@@ -111,27 +148,31 @@ const btn = (surface: Surface, quiet = false) =>
? paperButtonVariants()
: buttonVariants({ variant: quiet ? "quiet" : "outline", size: "sm" });
-/** Export clip, and its raw choice, for `clip` (null: nothing to export here, `why` says so). */
+/** Export clip, its raw choice, and Export ▾, for `clip` (null: nothing to export here, `why` says so). */
export function ClipExportButtons({
exp,
clip,
surface = "panel",
why = null,
unsaved = false,
+ around = null,
}: {
exp: ClipExportHandle;
clip: string | null;
surface?: Surface;
- /** Why there is nothing to export (a card, a window not fetched): the buttons are off and say so. */
+ /** Why there is nothing to export (a card, a window not fetched): the cut and raw buttons are off and say so. */
why?: string | null;
/** The bench has an edit not saved yet: the export is of the SAVED clip. */
unsaved?: boolean;
+ /** The clip's extent (source seconds): the full exchange's span starts from it. */
+ around?: { start: number; end: number } | null;
}) {
const hydrated = useHydrated();
const off = !hydrated || !clip || !!why || exp.busy;
const saved = unsaved ? " — of the SAVED window: save first to export your edit" : "";
return (
<>
+ <ExportMenu exp={exp} clip={clip} surface={surface} around={around} saved={saved} disabled={!hydrated || !clip || exp.busy} />
<button
type="button"
data-clip-export-go={clip ?? ""}
@@ -156,6 +197,122 @@ export function ClipExportButtons({
);
}
+const CONTEXT_DEFAULT = 5;
+const r1 = (n: number) => Math.round(n * 10) / 10;
+
+/**
+ * Export ▾: the three kinds (UI notes item 12) in one place -- as cut (no
+ * chrome), with N s of context, raw / full exchange over a span. Context and
+ * the full exchange are fetched through the editor first when what they need
+ * is not on disk (`fetch: true`; the job says so while it fetches).
+ */
+function ExportMenu({
+ exp,
+ clip,
+ surface,
+ around,
+ saved,
+ disabled,
+}: {
+ exp: ClipExportHandle;
+ clip: string | null;
+ surface: Surface;
+ around: { start: number; end: number } | null;
+ saved: string;
+ disabled: boolean;
+}) {
+ const [open, setOpen] = useState(false);
+ const [ctx, setCtx] = useState(String(CONTEXT_DEFAULT));
+ const [from, setFrom] = useState("");
+ const [to, setTo] = useState("");
+ const box = useRef<HTMLDivElement | null>(null);
+ // A new clip: the span starts from its extent again.
+ useEffect(() => {
+ setFrom(around ? String(r1(Math.max(0, around.start - 30))) : "");
+ setTo(around ? String(r1(around.end + 30)) : "");
+ }, [clip, around?.start, around?.end]); // eslint-disable-line react-hooks/exhaustive-deps
+ useEffect(() => {
+ if (!open) return;
+ const away = (e: PointerEvent) => {
+ if (box.current && !box.current.contains(e.target as Node)) setOpen(false);
+ };
+ const esc = (e: KeyboardEvent) => {
+ if (e.key === "Escape") setOpen(false);
+ };
+ window.addEventListener("pointerdown", away);
+ window.addEventListener("keydown", esc);
+ return () => {
+ window.removeEventListener("pointerdown", away);
+ window.removeEventListener("keydown", esc);
+ };
+ }, [open]);
+ const n = Number(ctx);
+ const ctxOk = Number.isFinite(n) && n >= 1 && n <= 120;
+ const a = Number(from);
+ const b = Number(to);
+ const spanOk = from.trim() !== "" && to.trim() !== "" && Number.isFinite(a) && Number.isFinite(b) && a >= 0 && b - a >= 0.5;
+ const go = (kind: ClipExportKind, opts: ClipExportOpts = {}) => {
+ if (!clip) return;
+ setOpen(false);
+ void exp.run(clip, kind, opts);
+ };
+ const input = "w-16 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 font-mono text-[11px] text-[var(--color-text)]";
+ const item = buttonVariants({ variant: "outline", size: "sm" });
+ return (
+ <div ref={box} className="relative inline-flex" data-clip-export-menu-box="">
+ <button
+ type="button"
+ data-clip-export-menu={clip ?? ""}
+ aria-haspopup="menu"
+ aria-expanded={open}
+ className={btn(surface)}
+ disabled={disabled}
+ title="Export ▾: as cut (no chrome), with N s of context, raw / full exchange — each a job in the heavy slot, into exports/"
+ onClick={() => setOpen((v) => !v)}
+ >
+ Export ▾
+ </button>
+ {open && (
+ <div
+ role="menu"
+ aria-label={`export ${clip ?? ""}`}
+ data-clip-export-options=""
+ className="absolute bottom-full left-0 z-30 mb-1 flex w-[19rem] max-w-[calc(100vw-2rem)] flex-col gap-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-2 text-[12px] text-[var(--color-text)] shadow-lg"
+ >
+ <div className="flex flex-col gap-0.5">
+ <button type="button" role="menuitem" data-clip-export-kind="cut" className={item} onClick={() => go("cut")} title={`the clip as the cut plays it: its edges, gaps out, its mute; no deck${saved}`}>
+ As cut (no chrome)
+ </button>
+ <span className="text-[10.5px] text-[var(--color-dim)]">its edges, gaps out as jump cuts, its mute — no rail, subtitles, QR or cards</span>
+ </div>
+ <div className="flex flex-col gap-0.5">
+ <span className="flex flex-wrap items-center gap-1.5">
+ <button type="button" role="menuitem" data-clip-export-kind="context" className={item} disabled={!ctxOk} onClick={() => go("context", { context: n, fetch: true })}>
+ With context
+ </button>
+ <input aria-label="seconds of context either side" data-clip-export-context="" className={input} inputMode="decimal" value={ctx} onChange={(e) => setCtx(e.target.value)} />
+ <span className="text-[11px] text-[var(--color-dim)]">s either side</span>
+ </span>
+ <span className="text-[10.5px] text-[var(--color-dim)]">what the cut plays and {ctxOk ? n : "N"} s around it, as recorded (1–120; fetched first if not on disk)</span>
+ </div>
+ <div className="flex flex-col gap-0.5">
+ <span className="flex flex-wrap items-center gap-1.5">
+ <button type="button" role="menuitem" data-clip-export-kind="raw" className={item} disabled={!spanOk} onClick={() => go("raw", { span: { from: r1(a), to: r1(b) }, fetch: true })}>
+ Raw / full exchange
+ </button>
+ <input aria-label="from (source seconds)" data-clip-export-from="" className={input} inputMode="decimal" value={from} onChange={(e) => setFrom(e.target.value)} />
+ <span aria-hidden>–</span>
+ <input aria-label="to (source seconds)" data-clip-export-to="" className={input} inputMode="decimal" value={to} onChange={(e) => setTo(e.target.value)} />
+ </span>
+ <span className="text-[10.5px] text-[var(--color-dim)]">source seconds, as recorded (no gaps, no mute) — what is not on disk is fetched through the editor first</span>
+ </div>
+ <span className="text-[10.5px] text-[var(--color-dim)]">named <clip>-<kind>-<date>-<words>.mp4 in the project’s exports/ · Download for a phone</span>
+ </div>
+ )}
+ </div>
+ );
+}
+
/** Exporting… / the file, Download, Open folder / failed, with the reason. */
export function ClipExportStatus({ exp, surface = "panel", className }: { exp: ClipExportHandle; surface?: Surface; className?: string }) {
const s = exp.state;
@@ -172,8 +329,10 @@ export function ClipExportStatus({ exp, surface = "panel", className }: { exp: C
if (s.k === "exporting") {
return (
<p role="status" className={cn(base, "m-0")} data-clip-export-state="exporting">
- Exporting {s.clip}
- {s.kind === "raw" ? " (raw window)" : ""}… <span className={cn("font-mono", muted)}>{Math.max(0, Math.round((Date.now() - s.since) / 1000))} s</span>
+ {s.fetching ? "Fetching what it needs through the editor, then exporting " : "Exporting "}
+ {s.clip}
+ {s.kind === "raw" ? " (raw)" : s.kind === "context" ? " (with context)" : ""}… <span className={cn("font-mono", muted)}>{Math.max(0, Math.round((Date.now() - s.since) / 1000))} s</span>
+ {s.line ? <span className={cn("ml-1 font-mono", muted)}>{s.line.slice(0, 120)}</span> : null}
</p>
);
}
diff --git a/umtool/components/projects/bench/TightenTools.tsx b/umtool/components/projects/bench/TightenTools.tsx
@@ -211,7 +211,7 @@ export function TightenButtons({ tools, busy }: { tools: ReturnType<typeof useEd
>
{tools.working === "tighten" ? "Tightening…" : "Tighten to this sentence"}
</button>
- <span className="micro">snap to nearest pause</span>
+ <span className="micro">snap edge to nearest pause</span>
<button type="button" data-snap-edge="start" className={btn} disabled={off} title="the start into the middle of the nearest pause (a silence, or between two words) — at most a second" onClick={() => void tools.snap("start")}>
← start
</button>
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -1055,6 +1055,7 @@ export default function PlayCut({
exp={clipExport}
clip={item?.clip ? item.id : null}
why={!item?.clip ? "a card is not a clip: nothing to export" : !entry?.media ? "its window is not fetched — fetch it first" : null}
+ around={item?.clip && typeof entry?.start === "number" && typeof entry?.end === "number" ? { start: entry.start, end: entry.end } : null}
/>
<ClipExportStatus exp={clipExport} />
</div>
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -46,6 +46,7 @@ Inbox cannot disagree about what is wrong with one.
| `snapshot <project> [--label L]` | copy the manifest into `revisions/` |
| `diff <project> <snapshot>` | added / removed / moved / window / retyped, by entry id |
| `export <project> --format toc-bbcode\|toc-markdown\|description\|chapters [--variant V] [--first TITLE]` | the posting artifacts, from the build's chapter offsets. A deck with markers: `chapters` are its top-level sections (subsections left out) at the second each section's first segment starts, YouTube's rules kept (0:00 first, each ≥ 10 s, at least three; what was merged is said on stderr); the opening is titled `deck.sectionTitle.first`, or `--first TITLE`, else the first section takes 0:00 |
+| `export <project> <clip> [--take T] [--open] [--json]` · `--context N` · `--raw [--from S --to S]` · `--fetch` · `--progress ndjson` | **one clip, clean** (no deck) into `<project>/exports/` as `<clip>[-ctx<N>\|-raw[-<from>-<to>]]-<date>-<words>.mp4`: as the cut plays it (its edges, gaps out, its mute); `--context N` what the cut plays ± N s (1–120), as recorded; `--raw` the fetched window, or `--from/--to` a span (the full exchange), as recorded. In the heavy slot (a 600 MB estimate). `--fetch` asks the editor first (fetch-via-editor, the bench's path) for what a context or raw export needs that is not on disk; without it nothing is fetched. `--progress ndjson`: one `export` event (the app's export job reads it) ([knobs.md](knobs.md#export-one-clip)) |
| `check-sources [<project>…]` | **prints** the re-check chain; with no args, the never-checked and >30 d projects |
| `corrections <project>` | what the report got wrong (the clip bench's sixth field) and the walk's coverage, as markdown for the next pass |
| `chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]]` | an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything) |
diff --git a/umtool/docs/clip-bench.md b/umtool/docs/clip-bench.md
@@ -250,6 +250,15 @@ mtime is in the URL: a request whose `v` matches is immutable for an hour, and o
whose `v` does not is served `no-store` rather than handing back the cut from
before the edit.
+## Export ▾ — the clip as a file
+
+The reader's footer has **Export clip** (the clip as the cut plays it), **raw** (the fetched window) and **Export ▾**:
+**As cut (no chrome)**, **With context** (N s either side of what the cut plays, as recorded) and **Raw / full
+exchange** (a from–to span of source seconds, starting at the clip's extent ± 30 s). Each is a umtool job in the heavy
+slot, named from the clip id and its date into the project's `exports/`; what context or a full exchange needs that is
+not on disk is fetched through the editor first, in the same job, and the line under the buttons says so while it
+does. Then Download (a phone's way) and Open folder ([knobs.md](knobs.md#export-one-clip)).
+
## Walking the cut
`p` and `n` (and the links in the header line) move to the previous and next
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -534,16 +534,19 @@ Then the cut: the Build tab's **final** preset (a full build, about an hour for
## Export one clip
-A clean mp4 of ONE clip, to post or hand on: the clip's footage as the cut plays it, with none of the deck — no rail,
-subtitles, QR, cards or stamps — written to the project's **`exports/`** (beside the hand-made ones) as
-`<clip>-<YYYY-MM-DD>-<slug>.mp4` (`<clip>-raw-…` for raw): the clip's date (its `date`, else the on-screen date, else
-the upload date; today with none) and the first words of its quote (else its title, else the video id). The same name
-again is written over.
+A clean mp4 of ONE clip, to post or hand on, with none of the deck — no rail, subtitles, QR, cards or stamps — written
+to the project's **`exports/`** (beside the hand-made ones) as `<clip>[-<kind>]-<YYYY-MM-DD>-<slug>.mp4`: the clip's
+date (its `date`, else the on-screen date, else the upload date; today with none) and the first words of its quote
+(else its title, else the video id). The kind is in the name — `-ctx<N>` with context, `-raw` for the fetched window,
+`-raw-<from>-<to>` for a span (the full exchange) — so the kinds never overwrite each other; the same export again is
+written over. Three kinds (UI notes 2026-10-30, item 12), the bench's and Play's **Export ▾**:
| | In umtool | From a terminal | Route |
|---|---|---|---|
-| the clip as the cut plays it | the clip bench's reader, **Export clip** (on a phone too); Play the cut, **Export clip** under the transport (the clip at the playhead) or a note's **Export <clip>** | `umtool export <p> <clip> [--take <t>] [--json]` | `POST /api/report/clip-export {project, clip, take?, kind?: "cut"}` |
-| the whole fetched window, as recorded | **raw** beside it | `umtool export <p> <clip> --raw` | `… {kind: "raw"}` |
+| **as cut (no chrome)**: the clip as the cut plays it | **Export clip**, or Export ▾ → **As cut (no chrome)** — the clip bench's reader (on a phone too); Play the cut under the transport (the clip at the playhead) or a note's **Export <clip>** | `umtool export <p> <clip> [--take <t>] [--json]` | `POST /api/report/clip-export {project, clip, take?, kind?: "cut"}` |
+| **with N s of context**: what the cut plays and N s either side (1–120, default 5), as recorded | Export ▾ → **With context**, the seconds beside it | `umtool export <p> <clip> --context N [--fetch]` | `… {kind: "context", context: N, fetch?: true}` |
+| **raw / full exchange**: a stretch of the recording as recorded — the clip and the fetch pad (**raw**), or a span of source seconds | **raw** beside Export clip; Export ▾ → **Raw / full exchange**, from–to (starting at the clip's extent ± 30 s) | `umtool export <p> <clip> --raw [--from S --to S] [--fetch]` | `… {kind: "raw", span?: {from, to}, fetch?: true}` |
+| the export's job | the status line under the buttons (*Fetching what it needs through the editor, then exporting…*, the job's last line), then the file | — | `GET /api/report/clip-export?job=<id>` → `{job, done?, error?}` |
| the file | **Download** (an attachment; the phone's way) | the path it prints | `GET /api/report/exports?project=<p>&name=<file>` (`GET …?project=<p>` lists them) |
| `exports/` in this machine's file manager, the file selected | **Open folder** | `--open` | `POST /api/report/exports {project, name?}` |
@@ -553,19 +556,30 @@ again is written over.
its **`gaps`** out as jump cuts on the frame grid with the build's 25 ms join fades, its sound **silenced** where the
cut silences it (`muteFrom`, a locked edge: `mute.mjs` soundOnSegment), its `audio` knobs (offset, gain, fades) and
the cut's loudness gain. Not applied: a blur (the export is unblurred, and says so), a montage's phrase cut.
-- **Raw**: the clip and the build's fetch pad either side (`render.fetchPad`, 3 s), clamped to the cached file — no
- gaps, no mute, no knobs.
+- **With context, and raw**: as recorded — no gaps, no mute, no knobs — from the tightest cached window of the
+ recording that **holds** the span (a wider fetch than the build's own source, often); where none does, clamped to
+ what is there and said (*the cached window ends 8.00 s before what was asked*).
+- **A umtool job, in the heavy slot.** Every export from the app is ONE job on the app's runner (`lib/jobs.ts`: one at
+ a time — a second job is a 409 naming the first — with a log and Stop): `umtool export … --progress ndjson`, which
+ takes the machine's heavy slot itself (`report-to-video/heavy-gate.mjs`) declaring a small estimate (600 MB), so it
+ runs beside others while memory allows and waits at the door in render mode. A terminal's `umtool export` takes the
+ same slot.
+- **Fetched if needed, through the editor.** A context or raw export whose span no cached window holds is refused —
+ *not on disk (−2 s / +14 s around the clip)* — unless asked with `fetch` (Export ▾ always asks, `--fetch` from a
+ terminal): then the same job first asks the editor for the window (`fetch-via-editor.mjs --fetch-only` with those
+ pads, the bench's own path: `POST /api/media/fetch-window`, paced, cookie-aware, provenanced; `UMTOOL_LOCAL_FETCH=1`
+ the pipeline's own), and cuts from what lands. A pad is at most 120 s either side of the clip's extent. **As cut**
+ fetches nothing: a clip whose window is not on disk is refused — "fetch it first" (the Cut tab's Fetch, `umtool
+ fetch <p>`); the buttons say so before you press them. On the bench the export is of the SAVED clip: save an edge
+ you moved first.
- **The encode**: cut on the input and re-encoded, so every cut is frame-exact — libx264 crf 18, yuv420p, AAC 192k,
- `+faststart`, no metadata or chapters. A few seconds for a short clip (≈10 s for 30 s of 720p); it does not take
- the heavy slot or the job runner, so it never waits behind a build. A second ask for the same file waits for the
- first.
-- **Nothing is fetched.** A clip whose window is not on disk is refused — "fetch it first" (the Cut tab's Fetch,
- `umtool fetch <p>`); the buttons say so before you press them. On the bench the export is of the SAVED clip: save an
- edge you moved first.
+ `+faststart`, no metadata or chapters. A few seconds for a short clip (≈10 s for 30 s of 720p).
- **Open folder** asks the desktop: `org.freedesktop.FileManager1.ShowItems` over the session bus (the file
selected), else `xdg-open <exports/>` on Linux; `open -R` on macOS. Refused, with the reason, inside a container,
on another OS, and from any device but the machine umtool runs on (by the request's Host, Origin and
X-Forwarded-For) — use **Download** there.
+- **No "send to phone".** Nothing in the repo sends a file to a phone (no share path, no pairing); **Download** from the
+ phone's browser is the way, and the option was left out rather than invented.
## The trailer's beats
diff --git a/umtool/e2e/clip-export.spec.ts b/umtool/e2e/clip-export.spec.ts
@@ -21,6 +21,9 @@ const HERE = path.dirname(fileURLToPath(import.meta.url));
const FIXTURE = path.join(HERE, "..", ".e2e-song");
const PLAY = "reports/play-cut-fixture";
const WALK = "reports/phone-walk-fixture";
+const EXPORT = "reports/export-fixture";
+const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
+const SHOTS = process.env.U3_SHOTS ?? null;
const exportsOf = (project: string) => path.join(FIXTURE, ...project.split("/"), "exports");
const OPEN_LOG = path.join(FIXTURE, "open-folder.jsonl");
@@ -29,7 +32,7 @@ test.beforeEach(() => {
});
test.afterAll(() => {
- for (const p of [PLAY, WALK]) rmSync(exportsOf(p), { recursive: true, force: true });
+ for (const p of [PLAY, WALK, EXPORT]) rmSync(exportsOf(p), { recursive: true, force: true });
});
const ready = async (page: Page) => {
@@ -107,3 +110,49 @@ test("the bench on a phone: Export clip in the reader, then Download", async ({
expect(await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth)).toBeLessThanOrEqual(0);
await page.screenshot({ path: test.info().outputPath("bench-export-390.png") });
});
+
+test("Export ▾ on the bench: with N s of context, and the full exchange fetched through the editor first", async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ await page.goto(urls.clipBenchHref(EXPORT, "x01"));
+ await expect(page.locator('[data-bench="x01"]')).toHaveCount(1);
+ const menu = page.locator('[data-clip-export-menu="x01"]');
+ await menu.scrollIntoViewIfNeeded();
+ await expect(menu).toBeEnabled();
+ await menu.click();
+ const options = page.locator("[data-clip-export-options]");
+ await expect(options).toBeVisible();
+ await expect(options.locator('[data-clip-export-kind="cut"]')).toHaveText("As cut (no chrome)");
+ // The full exchange starts from the clip's extent ± 30 s (the recording starts at 0).
+ await expect(options.locator("[data-clip-export-from]")).toHaveValue("0");
+ await expect(options.locator("[data-clip-export-to]")).toHaveValue("36");
+ await page.screenshot({ path: test.info().outputPath("bench-export-menu.png") });
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "u3-3-export-menu.png") });
+
+ // With 2 s of context: the cached 0–9 window holds it, nothing is fetched.
+ await options.locator("[data-clip-export-context]").fill("2");
+ await options.locator('[data-clip-export-kind="context"]').click();
+ const state = page.locator("[data-clip-export-state]");
+ await expect(state).toHaveAttribute("data-clip-export-state", "ready", { timeout: 60_000 });
+ await expect(state).toHaveAttribute("data-clip-export-name", "x01-ctx2-2026-07-22-the-full-exchange.mp4");
+ await expect(state).toContainText("the cut with 2 s either side, as recorded");
+ expect(existsSync(path.join(exportsOf(EXPORT), "x01-ctx2-2026-07-22-the-full-exchange.mp4"))).toBe(true);
+
+ // A context the cache does not hold, asked without `fetch`: refused, with what it needs.
+ const no = await page.request.post("/api/report/clip-export", { data: { project: EXPORT, clip: "x01", kind: "context", context: 20 } });
+ expect(no.status()).toBe(409);
+ expect(((await no.json()) as { error: string }).error).toContain("not on disk");
+
+ // The full exchange, 0–20 s: past the cached 9 s, so the job asks the editor first (fetch-window), then cuts it.
+ await menu.click();
+ await options.locator("[data-clip-export-from]").fill("0");
+ await options.locator("[data-clip-export-to]").fill("20");
+ await options.locator('[data-clip-export-kind="raw"]').click();
+ await expect(state).toHaveAttribute("data-clip-export-name", "x01-raw-0-20-2026-07-22-the-full-exchange.mp4", { timeout: 90_000 });
+ await expect(state).toContainText("the span asked for, as recorded");
+ const asked = JSON.parse(readFileSync(STUB_LOG, "utf8")) as { videoId?: string; clipId?: string; from?: number; to?: number }[];
+ const fetchAsk = asked.filter((r) => r.videoId === "exportvid").at(-1);
+ expect(fetchAsk?.clipId).toBe("x01");
+ expect(fetchAsk?.from).toBe(0);
+ expect(fetchAsk?.to).toBe(20);
+ expect(existsSync(path.join(exportsOf(EXPORT), "x01-raw-0-20-2026-07-22-the-full-exchange.mp4"))).toBe(true);
+});
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -803,6 +803,9 @@ CUES.walk1 = CUES.vid1.map((r) => [...r]);
// pause snap reads (report-to-video clip-words.mjs) -- laid on the tone window's silences
// (2.9-3.1, 5.9-6.1).
CUES.tightvid = CUES.vid1.map((r) => [...r]);
+// The clip-export spec's Export ▾ source (clip-export.spec.ts): a recording nothing else fetches, so
+// its full-exchange fetch (through the editor stub) moves no other spec's cache.
+CUES.exportvid = CUES.vid1.map((r) => [...r]);
for (const [vid, rows] of Object.entries(CUES)) {
const dir = path.join(CHANNELS, "testchan", "data", vid);
mkdirSync(dir, { recursive: true });
@@ -1920,6 +1923,18 @@ makeCutEditingFixture({ reports, manifest, deckManifest, cachedWindow: path.join
].map(([w, start, end]) => ({ w, start, end }));
writeFileSync(path.join(CHANNELS, "testchan", "data", "tightvid", "words.json"), JSON.stringify({ words }, null, 1));
}
+// Export ▾ (clip-export.spec.ts, UI notes item 12): with context and the full exchange, which WRITES
+// exports/ and -- through the editor stub's fetch-window -- a wider window of exportvid in the corpus.
+// x01 exportvid 2.0-6.0, the tone window cached as exportvid_0.00-9.00.mp4
+{
+ const g = manifest("export-fixture", "The Export Fixture", { siteOrigin: "https://archive.example" }, [
+ { type: "clip", id: "x01", video: "exportvid", start: 2.0, end: 6.0, cite: 2, section: 0, date: "2026-07-22", quote: "the full exchange" },
+ ]);
+ g.render.fetchPad = 0;
+ const dir = writeProject("export-fixture", g);
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "exportvid_0.00-9.00.mp4"));
+}
// A clip fetched PER KEPT PIECE (pieced.spec.ts, fetch-per-piece): no window holds its extent, the
// pieces do. READ-ONLY (the spec writes nothing), so one project serves it.
// pc01 pcvid 1-98, gap 8-91 (83 s out): both pieces on disk -- raw windows 0-9 and 90-99
diff --git a/umtool/lib/report/clipExport.mjs b/umtool/lib/report/clipExport.mjs
@@ -4,7 +4,8 @@
// `exports/`, where the operator keeps the hand-made ones
// (`exports/tr3-2026-08-12-deal-with-it-autogynephiliac.mp4`).
//
-// TWO KINDS.
+// THREE KINDS (UI notes 2026-10-30, item 12: "as cut (no chrome)", "with N s
+// context", "raw / full exchange (fetch if needed)").
//
// cut the clip as the cut plays it: the render's edges (cutPoints.mjs --
// the build's own source, snap and room; the muted room at an edge is
@@ -15,14 +16,26 @@
// its `audio` knobs (offset, gain, fades) and the cut's loudness gain.
// When the edges cannot be measured, the manifest's play window
// (noted). A blur, a montage's phrase cut and the deck are not applied.
-// raw the whole fetched window -- the clip and the build's fetch pad
-// either side, clamped to the file -- as recorded: no gaps, no mute,
-// no knobs.
+// context what the cut plays (its play window: the lead-in, the cut) with
+// N seconds either side (`context`, 1-120, default 5), as recorded: no
+// gaps, no mute, no knobs -- "what was said around it".
+// raw a stretch of the recording as recorded: `span` {from, to} in
+// source seconds (the full exchange), else the clip and the build's
+// fetch pad either side. No gaps, no mute, no knobs.
+//
+// Each cuts from a cached window that HOLDS what it asks for (the build's own
+// source for a cut; for context and raw the tightest window of the recording
+// holding the span), clamped to the file and said when none does.
+// `exportNeeds` says what a context or raw export needs that is not on disk,
+// as the pads the editor's fetch-window takes (POST /api/report/clip-export
+// with `fetch: true` runs that fetch first, in the same job).
//
// Re-encoded, never stream-copied, so every cut is on the asked-for frame:
-// libx264 crf 18, AAC 192k, +faststart. Light work (one short clip), so it
-// does not take the heavy slot. Nothing is fetched: a clip with no window on
-// disk is refused with "fetch it first".
+// libx264 crf 18, AAC 192k, +faststart. Run as a umtool job (the route) or
+// from a terminal (`umtool export`), and either way through the machine's
+// heavy slot (the CLI takes it: report-to-video/heavy-gate.mjs, a small
+// declared estimate, so it runs beside others when memory allows). Nothing is
+// fetched here: a cut with no window on disk is refused with "fetch it first".
//
// The pure half (names, the plan's ffmpeg arguments) is tested in
// clipExport.test.mjs; `exportClip` runs it.
@@ -36,8 +49,12 @@ import { AUDIO_ON_CLOCK, clipAudioFilters, clipAudioOf, offsetWindow } from "umt
/** The folder under a project that exports go into. */
export const EXPORTS_DIR = "exports";
-/** The two kinds of export. */
-export const EXPORT_KINDS = Object.freeze(["cut", "raw"]);
+/** The kinds of export. */
+export const EXPORT_KINDS = Object.freeze(["cut", "context", "raw"]);
+/** Seconds of context either side (the `context` kind): the default, and the bounds (the editor's fetch pad cap). */
+export const EXPORT_CONTEXT = Object.freeze({ default: 5, min: 1, max: 120 });
+/** What an export declares to the heavy slot (MB): one short re-encode. */
+export const EXPORT_ESTIMATE_MB = 600;
/** What a name under exports/ may be: one plain file name, an mp4. */
export const EXPORT_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,180}\.mp4$/;
@@ -94,26 +111,79 @@ export function exportDate(entry) {
}
/**
- * The export's file name: `<clipId>[-raw]-<YYYY-MM-DD>-<slug>.mp4`, the
- * shape of the hand-made ones (`ss1-raw-2026-07-22-side-scrollers-full-exchange.mp4`).
+ * The export's file name: `<clipId>[-ctx<N> | -raw[-<from>-<to>]]-<YYYY-MM-DD>-<slug>.mp4`,
+ * the shape of the hand-made ones (`ss1-raw-2026-07-22-side-scrollers-full-exchange.mp4`).
* The slug is the quote's first words, else the title's, else the video id;
- * the date the clip's, else `today` (YYYY-MM-DD).
+ * the date the clip's, else `today` (YYYY-MM-DD). A raw export of a span of
+ * its own (the full exchange) carries the span's whole seconds, so two
+ * exchanges of one clip are two files.
*
* @param {Record<string, any>} entry
- * @param {{ kind?: "cut" | "raw", today?: string }} [opts]
+ * @param {{ kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null, today?: string }} [opts]
*/
-export function exportName(entry, { kind = "cut", today = new Date().toISOString().slice(0, 10) } = {}) {
+export function exportName(entry, { kind = "cut", context = EXPORT_CONTEXT.default, span = null, today = new Date().toISOString().slice(0, 10) } = {}) {
const id = exportSlug(String(entry?.id ?? "clip"), { words: 8, max: 40 }) || "clip";
const date = exportDate(entry) ?? today;
const slug = exportSlug(entry?.quote) || exportSlug(entry?.onscreen?.title) || exportSlug(entry?.title) || exportSlug(entry?.video);
- return `${[id, kind === "raw" ? "raw" : null, date, slug || null].filter(Boolean).join("-")}.mp4`;
+ const tag =
+ kind === "raw"
+ ? span && fin(span.from) && fin(span.to)
+ ? `raw-${Math.floor(span.from)}-${Math.ceil(span.to)}`
+ : "raw"
+ : kind === "context"
+ ? `ctx${Math.round(context)}`
+ : null;
+ return `${[id, tag, date, slug || null].filter(Boolean).join("-")}.mp4`;
+}
+
+/** `context` as seconds inside EXPORT_CONTEXT's bounds, or an error naming them. */
+export function contextSeconds(v) {
+ if (v === undefined || v === null || v === "") return EXPORT_CONTEXT.default;
+ const n = Number(v);
+ if (!Number.isFinite(n) || n < EXPORT_CONTEXT.min || n > EXPORT_CONTEXT.max) {
+ throw new ExportRefused(`context is ${EXPORT_CONTEXT.min}–${EXPORT_CONTEXT.max} seconds either side (got ${String(v)})`, 400);
+ }
+ return Math.round(n * 10) / 10;
+}
+
+/** A raw export's span `{from, to}` (source seconds), checked; null when none is asked for. */
+export function spanOf(v) {
+ if (v === undefined || v === null) return null;
+ const from = Number(v?.from);
+ const to = Number(v?.to);
+ if (!Number.isFinite(from) || !Number.isFinite(to) || from < 0 || to - from < 0.5) {
+ throw new ExportRefused("a raw span is {from, to}: source seconds, from ≥ 0, at least half a second", 400);
+ }
+ if (to - from > 1800) throw new ExportRefused("a raw span is at most 30 minutes", 400);
+ return { from: Math.round(from * 100) / 100, to: Math.round(to * 100) / 100 };
+}
+
+/**
+ * The SOURCE seconds an export asks for, before the file clamps it: a cut's
+ * is its play window (the render may snap it a second either way), a context
+ * export's that ± N, a raw one's its span or the clip ± the fetch pad.
+ *
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} render
+ * @param {{ kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null }} opts
+ */
+export function exportSpan(entry, render, { kind = "cut", context = EXPORT_CONTEXT.default, span = null } = {}) {
+ if (kind === "raw") {
+ if (span) return { from: span.from, to: span.to };
+ const pad = fin(render?.fetchPad) ? render.fetchPad : 3;
+ return { from: Math.max(0, entry.start - pad), to: entry.end + pad };
+ }
+ const pw = playEdges(entry, render ?? {});
+ if (kind === "context") return { from: Math.max(0, pw.from - context), to: pw.to + context };
+ return { from: pw.from, to: pw.to };
}
/**
* What one export cuts, in SOURCE seconds -- the arithmetic, no I/O.
*
* @typedef {{
- * kind: "cut" | "raw",
+ * kind: "cut" | "context" | "raw",
+ * context?: number, span?: { from: number, to: number },
* file: string, fetchStart: number, duration?: number | null, hasVideo?: boolean,
* from: number, to: number,
* gaps: Array<{ from: number, to: number }>,
@@ -133,10 +203,11 @@ export function exportName(entry, { kind = "cut", today = new Date().toISOString
* (cutPoints.mjs; null or an errored row falls back to the manifest's edges).
*
* @param {{ entry: Record<string, any>, render?: Record<string, any>, source: { path: string, fetchStart: number },
- * media?: { duration?: number | null, hasVideo?: boolean }, row?: Record<string, any> | null, kind?: "cut" | "raw" }} o
+ * media?: { duration?: number | null, hasVideo?: boolean }, row?: Record<string, any> | null, kind?: "cut" | "context" | "raw",
+ * context?: number, span?: { from: number, to: number } | null }} o
* @returns {ExportPlan}
*/
-export function planExport({ entry, render = {}, source, media = {}, row = null, kind = "cut" }) {
+export function planExport({ entry, render = {}, source, media = {}, row = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null }) {
const fps = fin(render.fps) && render.fps > 0 ? render.fps : 30;
const fileFrom = source.fetchStart;
const fileTo = fin(media.duration) ? source.fetchStart + /** @type {number} */ (media.duration) : Infinity;
@@ -145,11 +216,23 @@ export function planExport({ entry, render = {}, source, media = {}, row = null,
kind, file: source.path, fetchStart: source.fetchStart, duration: media.duration ?? null,
hasVideo: media.hasVideo !== false, fps, notes,
};
- if (kind === "raw") {
- const pad = fin(render.fetchPad) ? render.fetchPad : 3;
- const from = Math.max(fileFrom, Math.max(0, entry.start - pad));
- const to = Math.min(fileTo, entry.end + pad);
- return { ...base, from, to, gaps: [], mute: null, soundFrom: null, audio: null, gainDb: null, edges: "window" };
+ if (kind === "raw" || kind === "context") {
+ // As recorded: the span asked for (raw: the full exchange, else the clip
+ // and the fetch pad; context: what the cut plays ± N -- the render's
+ // edges when measured), clamped to the file and said.
+ let want = exportSpan(entry, render, { kind, context, span });
+ if (kind === "context" && row && !row.missing && !row.error && fin(row.cutStart) && fin(row.cutEnd)) {
+ want = { from: Math.max(0, row.cutStart - context), to: row.cutEnd + context };
+ }
+ let from = Math.max(fileFrom, want.from);
+ let to = Math.min(fileTo, want.to);
+ if (want.from < fileFrom - 0.05) notes.push(`the cached window starts ${(fileFrom - want.from).toFixed(2)} s after what was asked: from its first frame`);
+ if (want.to > fileTo + 0.05) notes.push(`the cached window ends ${(want.to - fileTo).toFixed(2)} s before what was asked: to its last frame`);
+ if (to < from) to = from;
+ return {
+ ...base, from, to, gaps: [], mute: null, soundFrom: null, audio: null, gainDb: null, edges: "window",
+ ...(kind === "context" ? { context } : {}), ...(kind === "raw" && span ? { span } : {}),
+ };
}
let from;
let to;
@@ -249,7 +332,15 @@ export function planSummary(plan) {
if (plan.mute != null) parts.push(`muted from ${n3(plan.mute)} s`);
if (plan.soundFrom != null) parts.push(`sound from ${n3(plan.soundFrom)} s`);
parts.push(`${n3(planSeconds(plan))} s`);
- parts.push(plan.kind === "raw" ? "the whole window" : plan.edges === "render" ? "the render's edges" : "the manifest's edges");
+ parts.push(
+ plan.kind === "raw"
+ ? plan.span ? "the span asked for, as recorded" : "the whole window"
+ : plan.kind === "context"
+ ? `the cut with ${plan.context ?? EXPORT_CONTEXT.default} s either side, as recorded`
+ : plan.edges === "render"
+ ? "the render's edges"
+ : "the manifest's edges",
+ );
return parts.join(" · ");
}
@@ -285,29 +376,72 @@ export class ExportRefused extends Error {
const inflight = new Map();
/**
+ * What a context or raw export of this clip asks for, and whether a cached
+ * window holds it: `{ entry, want, held, padBefore, padAfter }`, the pads as
+ * the editor's fetch-window takes them (from the clip's extent, whole
+ * seconds, at most EXPORT_CONTEXT.max). A cut asks for what its own source
+ * holds (`held` is whether there is one).
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {string} clipId
+ * @param {{ take?: string | null, kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null }} [opts]
+ */
+export async function exportNeeds(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null } = {}) {
+ const { clipSourceOf } = await import("./cutPoints.mjs");
+ const got = await clipSourceOf(project, clipId, { take });
+ if (!got.entry) throw new ExportRefused(`no clip ${clipId} in ${take ? `take ${take} of ` : ""}${project.id}`, 404);
+ const e = got.entry;
+ if (kind === "cut") return { entry: e, want: null, held: !!got.source, padBefore: 0, padAfter: 0 };
+ const want = exportSpan(e, got.render, { kind, context, span });
+ const held = !!(await heldWindow(project, e, want));
+ const pad = (v) => Math.min(EXPORT_CONTEXT.max, Math.max(0, Math.ceil(v)));
+ return { entry: e, want, held, padBefore: pad(e.start - want.from), padAfter: pad(want.to - e.end) };
+}
+
+/** The tightest cached window of the clip's recording holding [want.from, want.to] (projectCache: out/clips-raw and the corpus's windows). */
+async function heldWindow(project, entry, want) {
+ const { projectCache } = await import("./serve.mjs");
+ const cache = await projectCache(project);
+ return cache.containing(entry.video, want.from + 0.02, want.to - 0.02) ?? null;
+}
+
+/**
* Export one clip of a project's cut (or of a take) into `<project>/exports/`.
*
* @param {{ id: string, dir: string }} project
* @param {string} clipId
- * @param {{ take?: string | null, kind?: "cut" | "raw", ffmpeg?: string, today?: string }} [opts]
- * @returns {Promise<{ project: string, clip: string, take: string | null, kind: "cut" | "raw", name: string, rel: string,
+ * @param {{ take?: string | null, kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null,
+ * ffmpeg?: string, today?: string }} [opts]
+ * @returns {Promise<{ project: string, clip: string, take: string | null, kind: "cut" | "context" | "raw", name: string, rel: string,
* abs: string, size: number, mtimeMs: number, seconds: number, summary: string, notes: string[], plan: ExportPlan }>}
*/
-export async function exportClip(project, clipId, { take = null, kind = "cut", ffmpeg, today } = {}) {
+export async function exportClip(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null, ffmpeg, today } = {}) {
if (!EXPORT_KINDS.includes(kind)) throw new ExportRefused(`an export is one of ${EXPORT_KINDS.join(", ")}`, 400);
+ const ctx = kind === "context" ? contextSeconds(context) : EXPORT_CONTEXT.default;
+ const sp = kind === "raw" ? spanOf(span) : null;
const { clipSourceOf, cutPointsFor } = await import("./cutPoints.mjs");
- const { FFMPEG_BIN, probeMedia } = await import("umtool-report-to-video/build-video");
+ const { FFMPEG_BIN, alignedClipSource, probeMedia } = await import("umtool-report-to-video/build-video");
const got = await clipSourceOf(project, clipId, { take });
if (!got.entry) throw new ExportRefused(`no clip ${clipId} in ${take ? `take ${take} of ` : ""}${project.id}`, 404);
- if (!got.source) {
+ // A context or raw export is cut from the window that holds what it asks for -- a wider fetch
+ // than the build's own source, often (the full exchange) -- when there is one.
+ /** @type {{ path: string, fetchStart: number, pieced?: { entry: Record<string, any> } } | null} */
+ let source = got.source;
+ if (kind !== "cut") {
+ const want = exportSpan(got.entry, got.render, { kind, context: ctx, span: sp });
+ const win = await heldWindow(project, got.entry, want);
+ if (win) source = await alignedClipSource({ path: win.path, fetchStart: win.from }).then((x) => ({ path: x.path, fetchStart: x.fetchStart }), () => ({ path: win.path, fetchStart: win.from }));
+ }
+ if (!source) {
throw new ExportRefused(
- `${clipId}: its window is not on disk — fetch it first (the Cut tab's Fetch, or \`umtool fetch ${project.id}\`)`,
+ `${clipId}: its window is not on disk — fetch it first (the Cut tab's Fetch, or \`umtool fetch ${project.id}\`)` +
+ (kind === "cut" ? "" : `; \`umtool export ${project.id} ${clipId} … --fetch\` asks the editor for what this export needs`),
409,
);
}
- const media = await probeMedia(got.source.path).catch(() => ({ hasVideo: true, duration: null }));
+ const media = await probeMedia(source.path).catch(() => ({ hasVideo: true, duration: null }));
let row = null;
- if (kind === "cut") {
+ if (kind === "cut" || kind === "context") {
try {
row = (await cutPointsFor(project, { take, clips: [clipId] })).clips?.[0] ?? null;
} catch (e) {
@@ -316,13 +450,13 @@ export async function exportClip(project, clipId, { take = null, kind = "cut", f
}
// A clip cut from its pieces (cutPoints.mjs piecedDiskSourceOf) is a file on its own clock:
// the plan is made on that clock -- the clip and the cut's numbers as the build sees them.
- const pieced = got.source.pieced ?? null;
+ const pieced = source.pieced ?? null;
const planRow = pieced && row && !row.error && !row.missing && row.pieced
? { ...row, cutStart: row.pieced.cutStart, cutEnd: row.pieced.cutEnd, gaps: row.pieced.gaps }
: row;
- const plan = planExport({ entry: pieced ? pieced.entry : got.entry, render: got.render, source: got.source, media, row: planRow, kind });
+ const plan = planExport({ entry: pieced ? pieced.entry : got.entry, render: got.render, source, media, row: planRow, kind, context: ctx, span: sp });
if (!(planSeconds(plan) > 0.05)) throw new ExportRefused(`${clipId}: nothing to export (${planSummary(plan)})`, 422);
- const name = exportName(got.entry, { kind, ...(today ? { today } : {}) });
+ const name = exportName(got.entry, { kind, context: ctx, span: sp, ...(today ? { today } : {}) });
const dir = path.join(/* turbopackIgnore: true */ project.dir, EXPORTS_DIR);
const abs = path.join(/* turbopackIgnore: true */ dir, name);
const run = inflight.get(abs) ?? (async () => {
@@ -350,6 +484,37 @@ export async function exportClip(project, clipId, { take = null, kind = "cut", f
}
/**
+ * The job that makes an export (the route's): the editor's fetch first when
+ * `fetch` names the pads a context or raw export still needs (driver.mjs
+ * editorFetchSteps, the bench's own; fetchSteps under UMTOOL_LOCAL_FETCH=1),
+ * then `umtool export … --progress ndjson`, which takes the heavy slot itself
+ * and ends with one `export` event.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {string} clipId
+ * @param {{ take?: string | null, kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null,
+ * fetch?: { padBefore: number, padAfter: number } | null, manifestPath?: string | null }} o
+ */
+export async function exportSteps(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null, fetch = null, manifestPath = null } = {}) {
+ const { UMTOOL_DIR, editorFetchSteps, fetchSteps, localFetch } = await import("./driver.mjs");
+ const steps = [];
+ if (fetch) {
+ const pads = { padBefore: fetch.padBefore, padAfter: fetch.padAfter };
+ steps.push(...(localFetch() ? fetchSteps(project, clipId, pads, { manifestPath }) : editorFetchSteps(project, clipId, pads, { manifestPath })));
+ }
+ const kindArgs = kind === "context" ? ["--context", String(context)] : kind === "raw" ? ["--raw", ...(span ? ["--from", String(span.from), "--to", String(span.to)] : [])] : [];
+ steps.push({
+ cwd: UMTOOL_DIR,
+ env: {},
+ label: `export ${clipId}${kind === "context" ? ` with ${context} s either side` : kind === "raw" ? (span ? ` ${span.from}–${span.to} s, as recorded` : " raw") : ""}`,
+ argv: [process.execPath, path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"), "export", project.id, clipId, ...kindArgs, ...(take ? ["--take", take] : []), "--progress", "ndjson"],
+ ndjson: true,
+ timeoutMs: 15 * 60_000,
+ });
+ return steps;
+}
+
+/**
* The exports a project holds, newest first: `{name, size, mtimeMs}`.
*
* @param {string} projectDir
diff --git a/umtool/lib/report/clipExport.test.mjs b/umtool/lib/report/clipExport.test.mjs
@@ -19,7 +19,8 @@ process.env.CHANNELS_DIR = CORPUS;
process.env.UMTOOL_CACHE_DIR = CACHE;
const {
- exportArgs, exportClip, exportDate, exportFileOf, exportName, exportSlug, listExports, planExport, planSeconds, planSummary,
+ EXPORT_CONTEXT, contextSeconds, exportArgs, exportClip, exportDate, exportFileOf, exportName, exportNeeds, exportSlug, exportSpan, exportSteps,
+ listExports, planExport, planSeconds, planSummary, spanOf,
} = await import("./clipExport.mjs");
const { cannotOpen, hostName, isLoopbackHost, localRequest, openFolder, openersFor } = await import("./openFolder.mjs");
@@ -203,8 +204,23 @@ test("export a clip: the kept seconds land in exports/ under the clip's name; ra
const rawExp = await exportClip(project, "c1", { kind: "raw" });
assert.equal(rawExp.name, "c1-raw-2026-08-12-deal-with-it.mp4");
near(probeDuration(rawExp.abs), 9, "1 s pad either side of 2–9 s, no gap", 0.12);
+ // With context: what the cut plays (2–9) and 1 s either side, as recorded -- no gap taken out.
+ const ctx = await exportClip(project, "c1", { kind: "context", context: 1 });
+ assert.equal(ctx.name, "c1-ctx1-2026-08-12-deal-with-it.mp4");
+ near(probeDuration(ctx.abs), 9, "1 s either side of 2–9 s, as recorded", 0.15);
+ // The full exchange: a span of its own, its seconds in the name; one past the file is clamped and said.
+ const full = await exportClip(project, "c1", { kind: "raw", span: { from: 0.5, to: 11.5 } });
+ assert.equal(full.name, "c1-raw-0-12-2026-08-12-deal-with-it.mp4");
+ near(probeDuration(full.abs), 11, "0.5–11.5 s", 0.15);
+ const past = await exportClip(project, "c1", { kind: "raw", span: { from: 6, to: 20 } });
+ assert.match(past.notes.join(" "), /ends 8\.00 s before what was asked/);
+ // What a context export needs that is not on disk: 30 s either side is past the 0–12 window.
+ const need = await exportNeeds(project, "c1", { kind: "context", context: 30 });
+ assert.equal(need.held, false);
+ // The pads are from the clip's extent (2–9), as the editor's fetch-window takes them; the recording starts at 0.
+ assert.deepEqual([need.padBefore, need.padAfter], [2, 30]);
const listed = await listExports(root);
- assert.deepEqual(listed.map((x) => x.name).sort(), [cut.name, rawExp.name].sort());
+ assert.deepEqual(listed.map((x) => x.name).sort(), [cut.name, rawExp.name, ctx.name, full.name, past.name].sort());
assert.deepEqual(readdirSync(path.join(root, "exports")).filter((n) => n.startsWith(".")), [], "no part file left");
await assert.rejects(exportClip(project, "nope"), /no clip nope/);
});
@@ -219,6 +235,35 @@ test("export a clip whose window is not on disk: refused, fetch it first", async
await assert.rejects(exportClip({ id: "exp2", dir: root }, "c9"), (e) => e.status === 409 && /fetch it first/.test(e.message));
});
+test("context and a raw span: their bounds, the span they ask for, and the job that makes them", async () => {
+ assert.equal(contextSeconds(undefined), EXPORT_CONTEXT.default);
+ assert.equal(contextSeconds("12"), 12);
+ for (const bad of [0, 121, "x", -1]) assert.throws(() => contextSeconds(bad), (e) => e.status === 400);
+ assert.equal(spanOf(undefined), null);
+ assert.deepEqual(spanOf({ from: 1.234, to: 9 }), { from: 1.23, to: 9 });
+ for (const bad of [{ from: 5, to: 5.2 }, { from: -1, to: 4 }, { from: 0, to: 4000 }, {}]) assert.throws(() => spanOf(bad), (e) => e.status === 400);
+ const e = { id: "c1", start: 103, end: 137, cutStart: 110, cutEnd: 130 };
+ assert.deepEqual(exportSpan(e, { leadIn: 0.4 }, { kind: "cut" }), { from: 109.6, to: 130 });
+ assert.deepEqual(exportSpan(e, { leadIn: 0.4 }, { kind: "context", context: 10 }), { from: 99.6, to: 140 });
+ assert.deepEqual(exportSpan(e, { fetchPad: 3 }, { kind: "raw" }), { from: 100, to: 140 });
+ assert.deepEqual(exportSpan(e, {}, { kind: "raw", span: { from: 50, to: 200 } }), { from: 50, to: 200 });
+ // Names: the kind in the name, so the three never overwrite each other.
+ const named = { id: "ss1", date: "2026-07-22", quote: "side scrollers full exchange" };
+ assert.equal(exportName(named, { kind: "context", context: 10 }), "ss1-ctx10-2026-07-22-side-scrollers-full-exchange.mp4");
+ assert.equal(exportName(named, { kind: "raw", span: { from: 1832.4, to: 1910.2 } }), "ss1-raw-1832-1911-2026-07-22-side-scrollers-full-exchange.mp4");
+ // The job: the editor's fetch first when asked (its pads), then `umtool export … --progress ndjson`.
+ const steps = await exportSteps({ id: "reports/x", dir: "/r/x" }, "c1", { kind: "context", context: 10, fetch: { padBefore: 14, padAfter: 9 } });
+ assert.equal(steps.length, 2);
+ assert.ok(steps[0].argv.some((a) => String(a).endsWith("fetch-via-editor.mjs")), "the editor's fetch-window path");
+ assert.deepEqual(steps[0].argv.slice(-6), ["--pad-before", "14", "--pad-after", "9", "--progress", "ndjson"]);
+ assert.deepEqual(steps[1].argv.slice(2), ["export", "reports/x", "c1", "--context", "10", "--progress", "ndjson"]);
+ assert.equal(steps[1].ndjson, true);
+ const raw = await exportSteps({ id: "reports/x", dir: "/r/x" }, "c1", { kind: "raw", span: { from: 5, to: 50 }, take: "t1" });
+ assert.equal(raw.length, 1, "nothing to fetch: the export alone");
+ assert.deepEqual(raw[0].argv.slice(2), ["export", "reports/x", "c1", "--raw", "--from", "5", "--to", "50", "--take", "t1", "--progress", "ndjson"]);
+ assert.match(planSummary({ kind: "context", context: 10, from: 0, to: 30, gaps: [], mute: null, soundFrom: null, edges: "window" }), /the cut with 10 s either side, as recorded/);
+});
+
// ---- open folder ----------------------------------------------------------------
test("who may ask to open a folder: this machine, by the headers a browser sends", () => {