commit e72332a6bed5402e55a3feb97e1b0c15392426e5
parent 36ed1882f470412f64e82f3b5e930088d6b0b585
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 02:27:30 -0500
umtool, scripts, common: the render queue panel -- what runs and waits at the heavy slot, "held by …", from the slot's own files -- and a take's ETA from the project's past renders (UI notes #18)
- render mode ("Give renders the machine", --priority) already existed; this adds what was missing
- scripts/queue-lock.mjs: a WAITING ticket per job waiting for the heavy slot (heavy-queue.lock.waiting/<pid>.json: what it is, since when, its stage -- render, line, slot, memory, build, exclusive, serial -- moved as it goes, dropped once admitted or at exit); waitForAdmission's onWait
- common/lib/heavyQueue.mjs: the slot as its files say -- running tickets (an e2e suite named by its queue, a next build, a render by take and project), waiting tickets, the line's head, the build slot, the e2e suites' queues, render mode, MemAvailable against the floor; a dead or reused pid is not counted, nothing is removed. renderPriority.mjs heavyLockFile
- GET /api/render-queue?project=… and RenderQueuePanel under the take panel's render-mode banner
- lib/report/takeEta.mjs: the median render seconds per second of video over the project's past renders of the same kind (made from another take, or fresh; whole cut or window), from take.json renderSeconds -- which the take maker now records, from the build's first event to its end, so a wait at the slot does not count -- else the take's files' times less the wait its log reports
- tests: queue-lock.test.mjs (the waiting ticket, onWait), heavyQueue.test.ts, takeMaker.test.mjs (renderSeconds), ui-ops.test.mjs (ETA); docs: report-video.md, WORKTREES.md
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
15 files changed, 913 insertions(+), 10 deletions(-)
diff --git a/WORKTREES.md b/WORKTREES.md
@@ -267,8 +267,11 @@ The pieces sit in the git common dir: `heavy-queue.lock` (the slot — held SHAR
admitted weighted job, EXCLUSIVELY by a job that runs alone, so an older checkout's copy of
the gate, which always takes it exclusively, still waits for every new-style job and is
never joined by one), `heavy-queue.lock.admit` (the line), `heavy-queue.lock.build` (the
-build slot) and `heavy-queue.lock.jobs/<pid>.json` (one ticket per running job — its
-estimate and what it is; a ticket whose process is gone is dropped). The kernel releases
+build slot), `heavy-queue.lock.jobs/<pid>.json` (one ticket per running job — its
+estimate and what it is; a ticket whose process is gone is dropped) and
+`heavy-queue.lock.waiting/<pid>.json` (one per job waiting for the slot, with where it waits:
+`render`, `line`, `slot`, `memory`, `build`, `exclusive`; dropped once it is admitted). umtool's
+take panel reads them all as its **Render queue** (`common/lib/heavyQueue.mjs`). The kernel releases
every lock when its holder's fd closes. A machine whose MemTotal is under the floor is told
so and runs one job at a time; with no usable `flock` the gate warns and runs on the floor
alone — it is a safety net, not a correctness lock.
diff --git a/common/lib/heavyQueue.mjs b/common/lib/heavyQueue.mjs
@@ -0,0 +1,178 @@
+// THE HEAVY SLOT, AS IT STANDS (UI notes 2026-10-30, #18: the render queue
+// panel). Read from the slot's own files beside its lock (scripts/queue-lock.mjs,
+// WORKTREES.md "The heavy slot") -- nothing here is guessed:
+//
+// heavy-queue.lock.jobs/<pid>.json one ticket per job RUNNING in the slot:
+// its estimate, whether it builds or runs
+// alone, its command, since when
+// heavy-queue.lock.waiting/<pid>.json one ticket per job WAITING: the same,
+// and its stage (render, line, slot,
+// memory, build, exclusive, serial)
+// heavy-queue.lock.admit.holder.json the job at the head of the line
+// heavy-queue.lock.build.holder.json the build slot's holder (one next build at a time)
+// heavy-queue.lock.render.json render mode (renderPriority.mjs)
+// <name>-queue.lock.holder.json each e2e suite's own queue
+//
+// A ticket whose process is gone (or whose pid was reused) is not counted;
+// this module never removes one -- queue-lock does that. Plain ESM: umtool's
+// route and the CLI read it under bare node.
+import fs from "node:fs";
+import path from "node:path";
+import { describeRenderPriority, holderAlive, readRenderPriority, renderPriorityFile } from "./renderPriority.mjs";
+
+/** What a waiting job waits for, in words. */
+export const STAGE_WORDS = Object.freeze({
+ door: "arriving",
+ render: "waiting for the render (render mode)",
+ line: "in line behind the job at the head",
+ slot: "at the head of the line, for the slot",
+ memory: "at the head of the line, for memory",
+ build: "for the build slot (one next build at a time)",
+ exclusive: "for a job that runs alone",
+ serial: "one job at a time (this machine is under the floor)",
+});
+
+/** A ticket's process is alive and is the one that wrote it. */
+const alive = (t, isAlive) => Number.isInteger(t?.pid) && isAlive({ pid: t.pid, pidStart: t.pidStart ?? null });
+
+function readDir(dir, isAlive) {
+ let names = [];
+ try {
+ names = fs.readdirSync(/* turbopackIgnore: true */ dir).filter((n) => n.endsWith(".json"));
+ } catch {
+ return [];
+ }
+ const out = [];
+ for (const n of names) {
+ try {
+ const t = JSON.parse(fs.readFileSync(/* turbopackIgnore: true */ path.join(dir, n), "utf8"));
+ if (alive(t, isAlive)) out.push(t);
+ } catch {
+ /* half-written by queue-lock: skipped this time */
+ }
+ }
+ return out;
+}
+
+function readHolder(file, isAlive) {
+ try {
+ const h = JSON.parse(fs.readFileSync(/* turbopackIgnore: true */ file, "utf8"));
+ return alive(h, isAlive) ? h : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * What a command is: a render (build-video.mjs; its project directory and take
+ * read from the manifest path it is given), an e2e suite, a next build, the
+ * encode ladder, or the command itself.
+ * @param {string} cmd
+ * @returns {{ kind: "render" | "e2e" | "build" | "ladder" | "other", label: string, projectDir?: string | null, take?: string | null }}
+ */
+export function classifyCommand(cmd) {
+ const c = String(cmd ?? "");
+ if (/build-video\.mjs/.test(c)) {
+ // A take's render: `build-video.mjs <project>/.take-<id>.render.json --out <project>/takes/<id>/out`
+ // (umtool/lib/report/takeRender.mjs); a project build: `build-video.mjs <project>/video.manifest.json`.
+ const after = c.slice(c.indexOf("build-video.mjs") + "build-video.mjs".length).trim();
+ const man = after.split(/\s+/)[0] ?? "";
+ const take = /(?:^|\/)\.take-([a-z0-9][a-z0-9-]*)\.render\.json$/.exec(man)?.[1] ?? /\/takes\/([a-z0-9][a-z0-9-]*)\/out(?:\s|$)/.exec(after)?.[1] ?? null;
+ const projectDir = man.includes("/") ? man.slice(0, man.lastIndexOf("/")) : null;
+ const name = projectDir ? projectDir.split("/").slice(-2).join("/") : null;
+ return { kind: "render", label: take ? `render of ${take}${name ? ` (${name})` : ""}` : `render${name ? ` of ${name}` : ""}`, projectDir, take };
+ }
+ if (/variants|ladder/.test(c) && /umtool/.test(c)) return { kind: "ladder", label: "the encode ladder (variants)" };
+ if (/playwright|run-sharded-e2e|\be2e\b/.test(c)) {
+ const suite = /--name (e2e-[a-z0-9-]+)/.exec(c)?.[1] ?? /--filter ([a-z0-9-]+)/.exec(c)?.[1] ?? null;
+ return { kind: "e2e", label: suite ? `e2e suite ${suite}` : "an e2e suite" };
+ }
+ if (/next build/.test(c)) {
+ const pkg = /--filter ([a-z0-9-]+)/.exec(c)?.[1] ?? null;
+ return { kind: "build", label: pkg ? `next build (${pkg})` : "a next build" };
+ }
+ return { kind: "other", label: c.length > 90 ? `${c.slice(0, 90)}…` : c };
+}
+
+const shape = (t, now) => {
+ const what = classifyCommand(t.cmd);
+ const started = Date.parse(t.since ?? t.startedAt ?? "");
+ return {
+ pid: t.pid,
+ what: what.label,
+ kind: what.kind,
+ ...(what.projectDir ? { projectDir: what.projectDir } : {}),
+ ...(what.take ? { take: what.take } : {}),
+ estimateMb: Number.isFinite(t.estimateMb) ? t.estimateMb : null,
+ build: Boolean(t.build),
+ alone: Boolean(t.exclusive),
+ worktree: t.worktree ? path.basename(String(t.worktree)) : null,
+ branch: t.branch ?? null,
+ cmd: String(t.cmd ?? ""),
+ since: Number.isFinite(started) ? new Date(started).toISOString() : null,
+ forSeconds: Number.isFinite(started) ? Math.max(0, Math.round((now - started) / 1000)) : null,
+ };
+};
+
+/**
+ * The slot now.
+ * @param {{ heavyLock: string, renderFile?: string, env?: Record<string, string | undefined>, now?: number, isAlive?: (h: { pid: number, pidStart: string | null }) => boolean, meminfo?: string }} o
+ */
+export function readHeavyQueue({ heavyLock, renderFile, env = process.env, now = Date.now(), isAlive = holderAlive, meminfo = "/proc/meminfo" }) {
+ const running = readDir(`${heavyLock}.jobs`, isAlive).map((t) => shape(t, now)).sort((a, b) => String(a.since).localeCompare(String(b.since)));
+ const waiting = readDir(`${heavyLock}.waiting`, isAlive)
+ .map((t) => ({
+ ...shape(t, now),
+ stage: String(t.stage ?? "door"),
+ stageWords: STAGE_WORDS[/** @type {keyof typeof STAGE_WORDS} */ (t.stage)] ?? String(t.stage ?? ""),
+ }))
+ // The head of the line first, then by arrival.
+ .sort((a, b) => Number(b.stage !== "line" && b.stage !== "render" && b.stage !== "door") - Number(a.stage !== "line" && a.stage !== "render" && a.stage !== "door") || String(a.since).localeCompare(String(b.since)));
+ const head = readHolder(`${heavyLock}.admit.holder.json`, isAlive);
+ const build = readHolder(`${heavyLock}.build.holder.json`, isAlive);
+ // An older copy of queue-lock writes no ticket, only the slot's holder file.
+ const holder = running.length ? null : readHolder(`${heavyLock}.holder.json`, isAlive);
+ const dir = path.dirname(heavyLock);
+ const suites = [];
+ try {
+ for (const n of fs.readdirSync(/* turbopackIgnore: true */ dir)) {
+ const m = /^(e2e(?:-[a-z0-9-]+)?)-queue\.lock\.holder\.json$/.exec(n);
+ if (!m) continue;
+ const h = readHolder(path.join(dir, n), isAlive);
+ if (h) suites.push({ suite: m[1], ...shape(h, now) });
+ }
+ } catch {
+ /* no lock dir yet */
+ }
+ // An e2e suite's slot ticket names only its command ("playwright test"): its
+ // name is the suite queue its process holds.
+ for (const r of [...running, ...waiting]) {
+ if (r.kind !== "e2e") continue;
+ const names = suites.filter((x) => x.pid === r.pid).map((x) => x.suite);
+ if (names.length) r.what = `e2e suite ${names[0]}${names.length > 1 ? ` (and ${names.slice(1).join(", ")})` : ""}`;
+ }
+ const rp = readRenderPriority(renderFile ?? renderPriorityFile(env, { heavyLock }));
+ let mem = null;
+ try {
+ const text = fs.readFileSync(/* turbopackIgnore: true */ meminfo, "utf8");
+ const kb = (k) => Number(new RegExp(`^${k}:\\s+(\\d+)`, "m").exec(text)?.[1] ?? NaN);
+ const a = kb("MemAvailable");
+ const t = kb("MemTotal");
+ if (Number.isFinite(a)) mem = { availableMb: Math.round(a / 1024), totalMb: Number.isFinite(t) ? Math.round(t / 1024) : null };
+ } catch {
+ mem = null;
+ }
+ const floor = Number(env.HEAVY_MIN_FREE_MB ?? 6000);
+ const promised = running.reduce((n, r) => n + (r.estimateMb ?? 0), 0);
+ return {
+ heavyLock,
+ running: holder && !running.length ? [shape(holder, now)] : running,
+ waiting,
+ head: head ? shape(head, now) : null,
+ build: build ? shape(build, now) : null,
+ suites: suites.sort((a, b) => a.suite.localeCompare(b.suite)),
+ render: rp.held && rp.state ? { held: true, what: describeRenderPriority(rp.state), since: rp.state.since ?? null, until: rp.state.until ?? null } : { held: false },
+ memory: mem ? { ...mem, floorMb: Number.isFinite(floor) ? floor : 6000, promisedMb: promised } : null,
+ heldBy: running.length ? running.map((r) => r.what).join("; ") : holder ? classifyCommand(holder.cmd).label : null,
+ };
+}
diff --git a/common/lib/heavyQueue.test.ts b/common/lib/heavyQueue.test.ts
@@ -0,0 +1,82 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { classifyCommand, readHeavyQueue } from "./heavyQueue.mjs";
+
+// The render queue panel's reader (UI notes 2026-10-30, #18): the heavy slot
+// as its own files say, never guessed. A live ticket is this process's pid; a
+// dead one a pid nothing runs as.
+
+function slot() {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "heavy-queue-"));
+ const lock = path.join(dir, "heavy-queue.lock");
+ const put = (file: string, doc: unknown) => {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, JSON.stringify(doc));
+ };
+ return { dir, lock, put, done: () => fs.rmSync(dir, { recursive: true, force: true }) };
+}
+
+const LIVE = process.pid;
+const DEAD = 2 ** 22 + 12345;
+const isAlive = (h: { pid: number }) => h.pid === LIVE || h.pid === LIVE + 1 || h.pid === LIVE + 2;
+
+test("classifyCommand: a take's render names its take and project; a suite, a build", () => {
+ assert.deepEqual(
+ classifyCommand("node /x/umtool/report-to-video/build-video.mjs /r/reports/ember/cut/.take-draft-3.render.json --out /r/reports/ember/cut/takes/draft-3/out --progress ndjson"),
+ { kind: "render", label: "render of draft-3 (ember/cut)", projectDir: "/r/reports/ember/cut", take: "draft-3" },
+ );
+ assert.equal(classifyCommand("node build-video.mjs /r/p/video.manifest.json").label, "render of r/p");
+ assert.equal(classifyCommand("playwright test a.spec.ts").kind, "e2e");
+ assert.equal(classifyCommand("systemd-run --user --scope -p MemoryMax=5G pnpm --filter export exec next build").label, "next build (export)");
+});
+
+test("readHeavyQueue: running and waiting tickets (the dead ones not), the head of the line, the suites, render mode, memory", () => {
+ const s = slot();
+ try {
+ const at = (min: number) => new Date(Date.parse("2026-11-02T10:00:00Z") + min * 60_000).toISOString();
+ s.put(`${s.lock}.jobs/${LIVE}.json`, { pid: LIVE, estimateMb: 1500, build: false, exclusive: false, worktree: "/w/lane-a", branch: "lane/a", cmd: "playwright test", startedAt: at(0) });
+ s.put(`${s.lock}.jobs/${DEAD}.json`, { pid: DEAD, estimateMb: 5000, cmd: "next build", startedAt: at(0) });
+ s.put(`${s.lock}.waiting/${LIVE + 1}.json`, { pid: LIVE + 1, estimateMb: 6020, cmd: "node build-video.mjs /r/reports/ember/cut/.take-draft-9.render.json --out /r/reports/ember/cut/takes/draft-9/out", since: at(2), stage: "memory" });
+ s.put(`${s.lock}.waiting/${LIVE + 2}.json`, { pid: LIVE + 2, estimateMb: 5120, build: true, cmd: "pnpm --filter editor exec next build", since: at(1), stage: "line" });
+ s.put(`${s.lock}.admit.holder.json`, { pid: LIVE + 1, cmd: "node build-video.mjs …", startedAt: at(2) });
+ s.put(path.join(s.dir, "e2e-umtool-queue.lock.holder.json"), { pid: LIVE, cmd: "playwright test", startedAt: at(-1) });
+ s.put(path.join(s.dir, "e2e-editor-queue.lock.holder.json"), { pid: DEAD, cmd: "playwright test", startedAt: at(-1) });
+ const mem = path.join(s.dir, "meminfo");
+ fs.writeFileSync(mem, "MemTotal: 16282624 kB\nMemAvailable: 8388608 kB\n");
+ const q = readHeavyQueue({ heavyLock: s.lock, renderFile: path.join(s.dir, "none.json"), env: {}, now: Date.parse(at(3)), isAlive, meminfo: mem });
+ assert.deepEqual(q.running.map((r) => [r.pid, r.what, r.estimateMb, r.worktree, r.forSeconds]), [[LIVE, "e2e suite e2e-umtool", 1500, "lane-a", 180]]);
+ // The head of the line first (it waits for memory), then the one behind it.
+ assert.deepEqual(q.waiting.map((w) => [w.pid, w.stage, w.what]), [
+ [LIVE + 1, "memory", "render of draft-9 (ember/cut)"],
+ [LIVE + 2, "line", "next build (editor)"],
+ ]);
+ assert.equal(q.waiting[0].stageWords, "at the head of the line, for memory");
+ assert.equal(q.waiting[0].take, "draft-9");
+ assert.equal(q.head?.pid, LIVE + 1);
+ assert.deepEqual(q.suites.map((x) => x.suite), ["e2e-umtool"]);
+ assert.deepEqual(q.render, { held: false });
+ assert.deepEqual(q.memory, { availableMb: 8192, totalMb: 15901, floorMb: 6000, promisedMb: 1500 });
+ assert.equal(q.heldBy, "e2e suite e2e-umtool");
+ // Nothing was removed: queue-lock owns the files.
+ assert.ok(fs.existsSync(`${s.lock}.jobs/${DEAD}.json`));
+ } finally {
+ s.done();
+ }
+});
+
+test("readHeavyQueue: an empty slot, and render mode holding the machine", () => {
+ const s = slot();
+ try {
+ const renderFile = path.join(s.dir, "heavy-queue.lock.render.json");
+ s.put(renderFile, { token: "t", since: "2026-11-02T10:00:00.000Z", until: "2099-01-01T00:00:00.000Z", by: "umtool take", holder: { pid: LIVE, cmd: "umtool take", project: "ember/cut", take: "draft-9" }, lanesHeld: [] });
+ const q = readHeavyQueue({ heavyLock: s.lock, renderFile, env: {}, isAlive, meminfo: path.join(s.dir, "no-meminfo") });
+ assert.deepEqual([q.running, q.waiting, q.head, q.build, q.suites, q.memory, q.heldBy], [[], [], null, null, [], null, null]);
+ assert.equal(q.render.held, true);
+ assert.match(String((q.render as { what?: string }).what), /^umtool take, since /);
+ } finally {
+ s.done();
+ }
+});
diff --git a/common/lib/renderPriority.mjs b/common/lib/renderPriority.mjs
@@ -100,11 +100,19 @@ function gitCommonDir(cwd) {
*/
export function renderPriorityFile(env = process.env, { heavyLock = null, root = process.cwd() } = {}) {
if (env.RENDER_PRIORITY_FILE) return env.RENDER_PRIORITY_FILE;
- const lock =
- heavyLock ??
- env.HEAVY_LOCK_FILE ??
- path.join(/* turbopackIgnore: true */ gitCommonDir(root) ?? os.tmpdir(), HEAVY_LOCK_NAME);
- return `${lock}${STATE_SUFFIX}`;
+ return `${heavyLock ?? heavyLockFile(env, { root })}${STATE_SUFFIX}`;
+}
+
+/**
+ * The heavy slot's lock, as queue-lock.mjs finds it: HEAVY_LOCK_FILE, else
+ * `heavy-queue.lock` in the git common dir of `root` (one for every
+ * worktree), a tmpdir outside a git checkout. Its running and waiting
+ * tickets sit beside it (common/lib/heavyQueue.mjs reads them).
+ * @param {Record<string, string | undefined>} [env]
+ * @param {{ root?: string }} [opts]
+ */
+export function heavyLockFile(env = process.env, { root = process.cwd() } = {}) {
+ return env.HEAVY_LOCK_FILE ?? path.join(/* turbopackIgnore: true */ gitCommonDir(root) ?? os.tmpdir(), HEAVY_LOCK_NAME);
}
/** The file's JSON, or null (missing, half-written, not ours). */
diff --git a/common/package.json b/common/package.json
@@ -49,6 +49,7 @@
"./lib/montage/voiceMatch.mjs": "./lib/montage/voiceMatch.mjs",
"./lib/ports.mjs": "./lib/ports.mjs",
"./lib/renderPriority.mjs": "./lib/renderPriority.mjs",
+ "./lib/heavyQueue.mjs": "./lib/heavyQueue.mjs",
"./lib/report/drafted.mjs": "./lib/report/drafted.mjs",
"./lib/report/look.mjs": "./lib/report/look.mjs",
"./lib/report/intro.mjs": "./lib/report/intro.mjs",
diff --git a/scripts/queue-lock.mjs b/scripts/queue-lock.mjs
@@ -869,6 +869,15 @@ function buildLockFor(heavyLock) {
function jobsDirFor(heavyLock) {
return `${heavyLock}.jobs`;
}
+// One ticket per job WAITING for the slot, `<pid>.json` (the render queue
+// panel's "waiting", UI notes #18): what it is, since when, and where it waits
+// -- `render` (at the door while render mode holds the machine), `line` (behind
+// the job at the head of the line), `slot` (at the head, for the slot's lock),
+// or the admission's own wait (`memory`, `build`, `exclusive`, `serial`).
+// Dropped once it is admitted (its running ticket replaces it) or exits.
+export function waitingDirFor(heavyLock) {
+ return `${heavyLock}.waiting`;
+}
// `systemd-run … -p MemoryMax=5G …` → 5120; none → null.
export function memoryCapMb(cmd = []) {
@@ -1108,6 +1117,63 @@ function writeTicket(dir, job, cmd) {
};
}
+/**
+ * The waiting ticket of this process: written now (stage `door`), its stage
+ * moved by `stage(name)`, removed by `drop()` (idempotent) and at exit.
+ * Informational, like the running tickets: a missing one never blocks.
+ */
+function writeWaitingTicket(dir, job, cmd) {
+ const file = path.join(dir, `${process.pid}.json`);
+ const since = new Date().toISOString();
+ let dropped = false;
+ const put = (stage) => {
+ if (dropped) return;
+ const info = {
+ pid: process.pid,
+ pidStart: pidStartTime(process.pid),
+ estimateMb: job.estimateMb,
+ build: Boolean(job.build),
+ exclusive: Boolean(job.exclusive),
+ worktree: gitOut(["rev-parse", "--show-toplevel"]) ?? process.cwd(),
+ branch: gitOut(["rev-parse", "--abbrev-ref", "HEAD"]) ?? "?",
+ cmd: cmd.join(" "),
+ since,
+ stage,
+ stageSince: new Date().toISOString(),
+ };
+ try {
+ fs.mkdirSync(dir, { recursive: true });
+ const tmp = `${file}.tmp`;
+ fs.writeFileSync(tmp, `${JSON.stringify(info, null, 2)}\n`);
+ fs.renameSync(tmp, file);
+ } catch {
+ /* informational only */
+ }
+ };
+ const drop = () => {
+ if (dropped) return;
+ dropped = true;
+ process.off("exit", drop);
+ try {
+ fs.rmSync(file, { force: true });
+ } catch {
+ /* best effort */
+ }
+ };
+ process.on("exit", drop);
+ let last = null;
+ put("door");
+ return {
+ stage: (name) => {
+ if (name !== last) {
+ last = name;
+ put(name);
+ }
+ },
+ drop,
+ };
+}
+
function describeTicket(t) {
const where = t.worktree ? path.basename(t.worktree) : "?";
const age = t.startedAt ? ` for ${humanAge(Date.parse(t.startedAt))}` : "";
@@ -1147,6 +1213,8 @@ export async function waitForAdmission({
log = (line) => process.stderr.write(line),
now = Date.now,
sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
+ // Told what the job waits for each time that changes (its waiting ticket's stage).
+ onWait = () => {},
}) {
const t0 = now();
let lastTick = t0;
@@ -1174,6 +1242,7 @@ export async function waitForAdmission({
}
if (d.wait !== lastWait) {
lastWait = d.wait;
+ onWait(d.wait);
log(waitLine(d, mem, minMb, describe));
} else if (now() - lastTick >= tickMs) {
lastTick = now();
@@ -1340,13 +1409,17 @@ export async function withHeavy(opts, fn) {
const deadline = timeoutMs > 0 ? Date.now() + timeoutMs : 0;
const remaining = () => (deadline ? Math.max(1000, deadline - Date.now()) : 0);
const releases = [];
+ // Seen by the render queue panel until it is admitted (waitingDirFor).
+ const waiting = writeWaitingTicket(waitingDirFor(heavyLock), job, cmd);
try {
let releaseLine = null;
// RENDER MODE first, outside the line: a job waiting for the render must
// not hold the line the render is admitted through. Looked at again once in
// line — a render that went on meanwhile sends this job back to wait.
for (;;) {
+ if (renderPriorityBlocks(readRender(), process.env, { urgent: opts.urgent === true })) waiting.stage("render");
await renderGateOrExit(readRender, { urgent: opts.urgent === true, timeoutMs: remaining() });
+ waiting.stage("line");
try {
releaseLine = await holdLock(admitLockFor(heavyLock), "heavy-line", cmd, remaining(), {
...HEAVY_LOCK,
@@ -1360,6 +1433,7 @@ export async function withHeavy(opts, fn) {
`heavy: the heavy slot is not held (${err?.message ?? err}) — the memory floor still applies\n`,
);
await memoryFloorOrExit(timeoutMs);
+ waiting.drop();
process.env[HEAVY_HELD_ENV] = "1";
return await fn();
}
@@ -1368,6 +1442,7 @@ export async function withHeavy(opts, fn) {
releaseLine = null;
}
try {
+ waiting.stage("slot");
const slotWait = { ...HEAVY_LOCK, describe: () => describeSlot(heavyLock) };
if (job.exclusive) {
releases.push(await holdLock(heavyLock, HEAVY_NAME, cmd, remaining(), slotWait));
@@ -1383,16 +1458,19 @@ export async function withHeavy(opts, fn) {
describe: () => describeSlot(heavyLock),
tryBuild: () =>
holdLock(buildLockFor(heavyLock), "heavy-build", cmd, 0, BUILD_LOCK, { nonblock: true }),
+ onWait: (w) => waiting.stage(w),
});
if (releaseBuild) releases.push(releaseBuild);
}
releases.push(writeTicket(jobsDirFor(heavyLock), job, cmd));
+ waiting.drop();
} finally {
await releaseLine();
}
process.env[HEAVY_HELD_ENV] = job.build ? "build" : "1";
return await fn();
} finally {
+ waiting.drop();
delete process.env[HEAVY_HELD_ENV];
for (const release of releases.reverse()) await release();
}
diff --git a/scripts/queue-lock.test.mjs b/scripts/queue-lock.test.mjs
@@ -1088,3 +1088,52 @@ test("render mode: the render (its token) is admitted at once, on the floor 4000
});
assert.match(own.stdout, /floor=1000/);
});
+
+// THE WAITING TICKETS (UI notes #18): the render queue panel reads who waits
+// at the slot, and for what, from the slot's own files.
+test("a job waiting for the slot has a waiting ticket naming its stage; admitted, it is a running ticket instead", async () => {
+ const dir = tmpDir();
+ const log = path.join(dir, "order.log");
+ const env = heavyEnv(dir);
+ const gate = path.join(dir, "gate");
+ const first = startLock(["--heavy", "--", ...gateCmd(log, "1", gate)], env);
+ await until(() => fs.existsSync(`${env.HEAVY_LOCK_FILE}.holder.json`));
+ const second = startLock(["--heavy", "--estimate", "700", "--", ...markerCmd(log, "2", 50)], env);
+ await second.waitFor(/waiting for/);
+ const waitingDir = `${env.HEAVY_LOCK_FILE}.waiting`;
+ await until(() => readTickets(waitingDir).some((t) => t.pid === second.child.pid && t.stage !== "door" && t.stage !== "line"));
+ const [w] = readTickets(waitingDir).filter((t) => t.pid === second.child.pid);
+ // Behind a job that runs alone: at the head of the line, for the slot.
+ assert.ok(["slot", "exclusive"].includes(w.stage), w.stage);
+ assert.equal(w.estimateMb, 700);
+ assert.match(w.cmd, /appendFileSync/);
+ assert.ok(Date.parse(w.since) <= Date.now());
+ // The one running: its ticket, not a waiting one.
+ assert.deepEqual(readTickets(`${env.HEAVY_LOCK_FILE}.jobs`).map((t) => t.pid), [first.child.pid]);
+ assert.equal(readTickets(waitingDir).some((t) => t.pid === first.child.pid), false);
+ openGate(gate);
+ assert.equal((await first.done).code, 0);
+ assert.equal((await second.done).code, 0);
+ assert.deepEqual(readTickets(waitingDir), []);
+});
+
+test("waitForAdmission tells onWait what the job waits for, each time it changes", async () => {
+ let clock = 0;
+ const waits = [];
+ const sets = [[{ estimateMb: 1500 }, { estimateMb: 1500 }], [{ estimateMb: 1500 }, { estimateMb: 1500 }], []];
+ await waitForAdmission({
+ minMb: 6000,
+ pollMs: 1000,
+ tickMs: 60_000,
+ log: () => {},
+ now: () => clock,
+ sleep: async (ms) => {
+ clock += ms;
+ },
+ job: { estimateMb: 1500, build: false, exclusive: false },
+ read: () => ({ availableMb: 8000, totalMb: 16_000 }),
+ tickets: () => sets.shift() ?? [],
+ onWait: (w) => waits.push(w),
+ });
+ assert.deepEqual(waits, ["memory"]);
+});
diff --git a/umtool/app/api/render-queue/route.ts b/umtool/app/api/render-queue/route.ts
@@ -0,0 +1,37 @@
+import { realpath } from "node:fs/promises";
+import { readHeavyQueue } from "yt-dlp-transcript-common/lib/heavyQueue.mjs";
+import { heavyLockFile, renderPriorityFile } from "yt-dlp-transcript-common/lib/renderPriority.mjs";
+import { REPO_ROOT } from "@/lib/paths.mjs";
+import { projectRef } from "@/lib/projects";
+import { projectEtas } from "@/lib/report/takeEta.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE RENDER QUEUE (UI notes 2026-10-30, #18), for the take panel: what runs
+// in the machine's heavy slot and what waits at it, and for what -- read from
+// the slot's own files beside its lock (common/lib/heavyQueue.mjs:
+// heavy-queue.lock.jobs/, .waiting/, the line's and the build slot's holders,
+// the e2e suites' queues, render mode), never guessed -- and, with a project,
+// how long a take of it renders, from its past renders (lib/report/takeEta.mjs).
+// Read only: render mode is turned on by "Give renders the machine" (a take's
+// --priority) or `umtool render-mode on`.
+//
+// GET ?project=<id> -> { queue, etas, mine } `mine`: the running and waiting renders of this project
+const noStore = { "cache-control": "no-store" };
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const queue = readHeavyQueue({
+ heavyLock: heavyLockFile(process.env, { root: REPO_ROOT }),
+ renderFile: renderPriorityFile(process.env, { root: REPO_ROOT }),
+ });
+ const id = url.searchParams.get("project");
+ const project = id ? await projectRef(id) : null;
+ if (!project) return Response.json({ queue, etas: null, mine: [] }, { headers: noStore });
+ const dir = await realpath(project.dir).catch(() => project.dir);
+ const same = async (d: string | undefined) => !!d && ((await realpath(d).catch(() => d)) === dir || d === project.dir);
+ const mine: { pid: number; take: string | null; state: "running" | "waiting"; forSeconds: number | null; stage?: string }[] = [];
+ for (const r of queue.running) if (r.kind === "render" && (await same(r.projectDir))) mine.push({ pid: r.pid, take: r.take ?? null, state: "running", forSeconds: r.forSeconds });
+ for (const w of queue.waiting) if (w.kind === "render" && (await same(w.projectDir))) mine.push({ pid: w.pid, take: w.take ?? null, state: "waiting", forSeconds: w.forSeconds, stage: w.stageWords });
+ return Response.json({ queue, etas: await projectEtas(project.dir), mine }, { headers: noStore });
+}
diff --git a/umtool/components/projects/NewTakePanel.tsx b/umtool/components/projects/NewTakePanel.tsx
@@ -6,6 +6,7 @@ import { buttonVariants } from "@/components/ui/button";
import { Field, Input, Select, Textarea } from "@/components/ui/field";
import { JobProgress, type JobStepState } from "@/components/ui/job-progress";
import RenderModeBanner, { renderPriorityPref } from "./RenderModeBanner";
+import RenderQueuePanel from "./RenderQueuePanel";
// New take, Make all styles -- and the job either starts (or a card's Rebuild
// starts), watched here until it ends, then the page re-reads the takes.
@@ -162,6 +163,7 @@ export default function NewTakePanel({
return (
<section data-new-take="" className="space-y-2">
<RenderModeBanner />
+ <RenderQueuePanel project={project} />
<details className="rounded border border-[var(--color-line)] bg-[var(--color-panel)]">
<summary data-action="new-take-open" className="cursor-pointer px-3 py-2 text-[12.5px] text-text">
New take
diff --git a/umtool/components/projects/RenderQueuePanel.tsx b/umtool/components/projects/RenderQueuePanel.tsx
@@ -0,0 +1,194 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+// THE RENDER QUEUE on the take panel (UI notes 2026-10-30, #18): what runs in
+// the machine's heavy slot and what waits at it -- e2e suites, next builds,
+// renders -- read from the slot's own files (GET /api/render-queue,
+// common/lib/heavyQueue.mjs), and how long a take of this project renders,
+// from its past renders (lib/report/takeEta.mjs). "Give renders the machine"
+// beside it (RenderModeBanner) is what sends the others to wait at the door.
+
+type Row = {
+ pid: number;
+ what: string;
+ kind: string;
+ estimateMb: number | null;
+ build: boolean;
+ alone: boolean;
+ worktree: string | null;
+ branch: string | null;
+ since: string | null;
+ forSeconds: number | null;
+ stage?: string;
+ stageWords?: string;
+ take?: string;
+};
+type Eta = { etaSeconds: number; rate: number; basis: { id: string; seconds: number; renderSeconds: number; how: string }[]; note: string | null };
+type View = {
+ queue: {
+ running: Row[];
+ waiting: Row[];
+ head: Row | null;
+ suites: (Row & { suite: string })[];
+ render: { held: boolean; what?: string };
+ memory: { availableMb: number; totalMb: number | null; floorMb: number; promisedMb: number } | null;
+ heldBy: string | null;
+ };
+ etas: { seconds: number | null; newest: string | null; fresh: Eta | null; reuse: Eta | null; past: unknown[] } | null;
+ mine: { pid: number; take: string | null; state: "running" | "waiting"; forSeconds: number | null; stage?: string }[];
+};
+
+const dur = (s: number | null | undefined) => {
+ if (s == null || !Number.isFinite(s)) return "—";
+ if (s < 90) return `${Math.round(s)} s`;
+ const m = Math.round(s / 60);
+ return m >= 60 ? `${Math.floor(m / 60)} h ${String(m % 60).padStart(2, "0")} min` : `${m} min`;
+};
+const gb = (mb: number) => `${(mb / 1024).toFixed(1)} GB`;
+const clock = (s: number) => `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, "0")}`;
+
+function RowLine({ r, waiting }: { r: Row; waiting?: boolean }) {
+ return (
+ <li
+ data-queue-row={r.kind}
+ data-queue-state={waiting ? "waiting" : "running"}
+ data-queue-pid={r.pid}
+ className="flex flex-wrap items-baseline gap-x-2 border-b border-seam py-1 text-[12px]"
+ >
+ <span className="text-text">{r.what}</span>
+ {r.worktree && (
+ <span className="font-mono text-[11px] text-muted">
+ {r.worktree}
+ {r.branch && r.branch !== r.worktree ? ` (${r.branch})` : ""}
+ </span>
+ )}
+ <span className="font-mono text-[11px] text-meter">
+ {r.estimateMb ? `${gb(r.estimateMb)}` : r.alone ? "alone" : "no estimate"}
+ {r.build ? " · a build" : ""}
+ </span>
+ {waiting && r.stageWords && <span className="text-[11.5px] text-doubt-text">{r.stageWords}</span>}
+ <span className="ml-auto font-mono text-[11px] text-muted">{waiting ? "waiting " : ""}{dur(r.forSeconds)}</span>
+ </li>
+ );
+}
+
+export default function RenderQueuePanel({ project }: { project: string }) {
+ const [view, setView] = useState<View | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ let alive = true;
+ const look = () =>
+ fetch(`/api/render-queue?project=${encodeURIComponent(project)}`, { cache: "no-store" })
+ .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))
+ .then((j: View) => {
+ if (!alive) return;
+ setView(j);
+ setError(null);
+ })
+ .catch((e: unknown) => alive && setError(e instanceof Error ? e.message : String(e)));
+ void look();
+ const t = setInterval(look, 5000);
+ return () => {
+ alive = false;
+ clearInterval(t);
+ };
+ }, [project]);
+
+ if (!view) {
+ return error ? (
+ <p data-render-queue-error="" className="text-[12px] text-muted">
+ The render queue could not be read: {error}
+ </p>
+ ) : null;
+ }
+ const { queue, etas, mine } = view;
+ const busy = queue.running.length > 0 || queue.waiting.length > 0;
+ return (
+ <section data-render-queue={busy ? "busy" : "idle"} className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2">
+ <div className="flex flex-wrap items-baseline gap-2">
+ <h2 className="micro">Render queue</h2>
+ <span data-render-queue-held-by="" className="text-[12px] text-text-2">
+ {queue.render.held
+ ? `held for a render: ${queue.render.what}`
+ : queue.heldBy
+ ? `held by ${queue.heldBy}`
+ : "the heavy slot is free"}
+ </span>
+ {queue.memory && (
+ <span className="ml-auto font-mono text-[11px] text-muted" title="MemAvailable, the floor a job is admitted above, and what the running jobs declared">
+ {gb(queue.memory.availableMb)} available · floor {gb(queue.memory.floorMb)}
+ {queue.memory.promisedMb ? ` · ${gb(queue.memory.promisedMb)} promised` : ""}
+ </span>
+ )}
+ </div>
+ {queue.running.length > 0 && (
+ <ul data-render-queue-running={queue.running.length} className="mt-1">
+ {queue.running.map((r) => (
+ <RowLine key={`r${r.pid}`} r={r} />
+ ))}
+ </ul>
+ )}
+ {queue.waiting.length > 0 && (
+ <ul data-render-queue-waiting={queue.waiting.length} className="mt-1">
+ {queue.waiting.map((r) => (
+ <RowLine key={`w${r.pid}`} r={r} waiting />
+ ))}
+ </ul>
+ )}
+ {queue.suites.filter((s) => !queue.running.some((r) => r.pid === s.pid) && !queue.waiting.some((r) => r.pid === s.pid)).length > 0 && (
+ <p className="mt-1 text-[11.5px] text-muted">
+ e2e queues held:{" "}
+ {queue.suites
+ .filter((s) => !queue.running.some((r) => r.pid === s.pid) && !queue.waiting.some((r) => r.pid === s.pid))
+ .map((s) => `${s.suite} (${s.worktree ?? "?"}, building or about to ask for the slot)`)
+ .join(", ")}
+ </p>
+ )}
+ {mine.length > 0 && (
+ <p data-render-queue-mine="" className="mt-1 text-[12px] text-text-2">
+ {mine
+ .map((m) => `${m.take ?? "this project's render"}: ${m.state === "running" ? `rendering for ${dur(m.forSeconds)}` : `waiting ${dur(m.forSeconds)} — ${m.stage}`}`)
+ .join(" · ")}
+ </p>
+ )}
+ <div data-take-eta={etas?.fresh || etas?.reuse ? "known" : "unknown"} className="mt-1.5 text-[12px] text-text-2">
+ {etas?.seconds && (etas.fresh || etas.reuse) ? (
+ <>
+ <span>
+ A whole-cut take ({clock(etas.seconds)} of video):{" "}
+ {etas.reuse && (
+ <span data-take-eta-reuse={etas.reuse.etaSeconds}>
+ ~{dur(etas.reuse.etaSeconds)} made from {etas.newest} (reuse)
+ </span>
+ )}
+ {etas.reuse && etas.fresh ? " · " : ""}
+ {etas.fresh && <span data-take-eta-fresh={etas.fresh.etaSeconds}>~{dur(etas.fresh.etaSeconds)} fresh</span>}
+ </span>
+ <details className="mt-0.5">
+ <summary className="cursor-pointer text-[11.5px] text-muted">
+ from {new Set([...(etas.reuse?.basis ?? []), ...(etas.fresh?.basis ?? [])].map((b) => b.id)).size} past render(s) of this project
+ </summary>
+ <ul className="mt-0.5 font-mono text-[11px] text-muted">
+ {[...(etas.reuse?.basis.map((b) => ({ ...b, k: "reuse" })) ?? []), ...(etas.fresh?.basis.map((b) => ({ ...b, k: "fresh" })) ?? [])].map((b) => (
+ <li key={`${b.k}-${b.id}`}>
+ {b.id} ({b.k}): {clock(b.seconds)} of video in {dur(b.renderSeconds)}
+ {b.how === "files" ? " (from its files' times)" : ""}
+ </li>
+ ))}
+ </ul>
+ {[etas.reuse?.note, etas.fresh?.note].filter(Boolean).map((n) => (
+ <p key={n} className="text-[11px] text-muted">
+ {n}
+ </p>
+ ))}
+ </details>
+ </>
+ ) : (
+ <span className="text-muted">No ETA yet: no past render of this project says how long it took.</span>
+ )}
+ </div>
+ </section>
+ );
+}
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -945,7 +945,8 @@ them and records the verdicts.
```
takes/<id>/take.json id (== dir, [a-z0-9-]), group, order, label,
kind reference|similar|different, preview;
- optional summary, changes[], seconds, builtAt
+ optional summary, changes[], seconds, builtAt,
+ renderSeconds (the render's own time: the next take's ETA)
takes/<id>/preview.mp4 whatever `preview` names, inside the take dir
takes/<id>/out/<slug>.mp4 the take maker's render again, a hard link of preview.mp4
(what `umtool variants --take` and Deliver encode)
@@ -1167,6 +1168,19 @@ take: done, failed, or stopped (Ctrl-C, the job's Stop). A window ends at its `u
it at once, and the editor's heartbeat releases its lanes. Close Firefox and other heavy
apps while it renders.
+**The render queue and a take's ETA.** Under the banner, **Render queue** says what the heavy
+slot is doing, read from its own files (`common/lib/heavyQueue.mjs`; `GET /api/render-queue`):
+each job running in it (an e2e suite by its queue's name, a `next build`, a render by its take
+and project) with its worktree, its declared memory and for how long; each job **waiting** at
+it and for what — the render (render mode), the line, the slot, memory, the build slot — from
+the waiting tickets queue-lock keeps (`heavy-queue.lock.waiting/<pid>.json`); "held by …";
+MemAvailable against the floor. Beside it, **the ETA of a whole-cut take** of this project,
+made from the newest take and fresh: the median seconds of render per second of video over the
+project's past renders of that kind (`lib/report/takeEta.mjs`) — the `renderSeconds` a take
+records (from the build's first event, so a wait at the slot is not counted), else the take's
+own files (its `video.manifest.json`, written as the render starts, to `builtAt`), less any
+wait its `<take>.log` reports. With no render of a kind it says it used the others.
+
### A take's work files, and pruning them
A take's build leaves behind what makes the NEXT build fast: its clip segments, the chrome
diff --git a/umtool/lib/report/takeEta.mjs b/umtool/lib/report/takeEta.mjs
@@ -0,0 +1,160 @@
+// HOW LONG WILL THIS TAKE RENDER? (UI notes 2026-10-30, #18) -- from the
+// project's own past renders, never a constant. On the Ember cut every ETA was
+// worked out by hand.
+//
+// A past render is a take (takes/<id>/take.json) whose render time is known:
+//
+// - `renderSeconds`, which the take maker records (takeMaker.mjs: from the
+// build's first event to its end, so a wait at the heavy slot's door is
+// not counted);
+// - else the take's own files: from its video.manifest.json (written just
+// before the render starts and renamed into place unchanged) to its
+// take.json `builtAt`, less any wait at the slot its log says it had (a
+// `<take>.log` beside the project or in the take, the heavy gate's
+// `admitted after …` / `the render let go after …` lines).
+//
+// The ETA is the median seconds of render per second of video, over the past
+// renders of the same kind -- made `from` another take (its segments, frames
+// and chunks reused) or fresh, the whole cut or a window -- times the take's
+// length; with none of its kind it says it used the others. Plain ESM: the CLI
+// and the route read it under bare node.
+import { readdir, readFile, stat } from "node:fs/promises";
+import path from "node:path";
+
+const TAKE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
+const num = (v) => typeof v === "number" && Number.isFinite(v);
+
+/** `35s`, `2m10s`, `1h02m` (queue-lock's humanDuration) -> seconds, else null. */
+export function parseDuration(s) {
+ const m = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(String(s ?? "").trim());
+ if (!m || (!m[1] && !m[2] && !m[3])) return null;
+ return Number(m[1] ?? 0) * 3600 + Number(m[2] ?? 0) * 60 + Number(m[3] ?? 0);
+}
+
+/** The seconds a render's log says it waited at the heavy slot (its door, its line, memory). */
+export function slotWaitOf(text) {
+ let s = 0;
+ for (const m of String(text ?? "").matchAll(/(?:heavy: .* after |queue-lock: the render let go after )(\d+h)?(\d+m)?(\d+s)?(?: — admitted| — going on)/g)) {
+ s += parseDuration(`${m[1] ?? ""}${m[2] ?? ""}${m[3] ?? ""}`) ?? 0;
+ }
+ return s;
+}
+
+/**
+ * Every past render of the project with its render time and length.
+ * @param {string} projectDir
+ * @returns {Promise<Array<{ id: string, seconds: number, renderSeconds: number, how: "recorded" | "files", window: "full" | "window", from: string | null, quick: boolean, builtAt: string | null }>>}
+ */
+export async function pastRenders(projectDir) {
+ const takesDir = path.join(projectDir, "takes");
+ const names = await readdir(takesDir).catch(() => []);
+ const out = [];
+ for (const id of names) {
+ if (!TAKE_ID.test(id)) continue;
+ const dir = path.join(takesDir, id);
+ let t;
+ try {
+ t = JSON.parse(await readFile(path.join(dir, "take.json"), "utf8"));
+ } catch {
+ continue;
+ }
+ if (t?.draft === true || !num(t?.seconds) || t.seconds <= 0) continue;
+ let renderSeconds = num(t.renderSeconds) && t.renderSeconds > 0 ? t.renderSeconds : null;
+ let how = /** @type {"recorded" | "files"} */ ("recorded");
+ if (renderSeconds === null && typeof t.builtAt === "string") {
+ const st = await stat(path.join(dir, "video.manifest.json")).catch(() => null);
+ const end = Date.parse(t.builtAt);
+ if (st && Number.isFinite(end)) {
+ let wait = 0;
+ for (const log of [path.join(projectDir, `${id}.log`), path.join(dir, `${id}.log`), path.join(dir, "take.log")]) {
+ const text = await readFile(log, "utf8").catch(() => null);
+ if (text) {
+ wait = slotWaitOf(text);
+ break;
+ }
+ }
+ const s = (end - st.mtimeMs) / 1000 - wait;
+ // A manifest older than a day before its build is a take rebuilt in
+ // place long after: its files say nothing about the render.
+ if (s > 0 && s < 86_400) {
+ renderSeconds = Math.round(s * 10) / 10;
+ how = "files";
+ }
+ }
+ }
+ if (renderSeconds === null) continue;
+ out.push({
+ id,
+ seconds: t.seconds,
+ renderSeconds,
+ how,
+ window: t.window && t.window !== "full" ? "window" : "full",
+ from: typeof t.from === "string" && t.from ? t.from : null,
+ quick: t.quick === true,
+ builtAt: typeof t.builtAt === "string" ? t.builtAt : null,
+ });
+ }
+ return out.sort((a, b) => String(a.builtAt).localeCompare(String(b.builtAt)));
+}
+
+const median = (xs) => {
+ const s = [...xs].sort((a, b) => a - b);
+ const n = s.length;
+ return n % 2 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2;
+};
+
+/**
+ * The ETA of a take of `seconds` of video. Pure over `past`.
+ * @param {Awaited<ReturnType<typeof pastRenders>>} past
+ * @param {{ seconds: number, from?: boolean, window?: "full" | "window", quick?: boolean, last?: number }} want
+ * `from`: made from another take (reuse); `last`: at most this many of the newest renders count (default 6)
+ * @returns {null | { etaSeconds: number, rate: number, basis: Array<{ id: string, seconds: number, renderSeconds: number, how: string }>, kind: string, note: string | null }}
+ */
+export function takeEta(past, { seconds, from = false, window = "full", quick = false, last = 6 }) {
+ if (!num(seconds) || seconds <= 0 || !past.length) return null;
+ const kindOf = (p) => `${p.from ? "reuse" : "fresh"}/${p.window}${p.quick ? "/quick" : ""}`;
+ const want = `${from ? "reuse" : "fresh"}/${window}${quick ? "/quick" : ""}`;
+ let pool = past.filter((p) => kindOf(p) === want);
+ let note = null;
+ if (!pool.length) {
+ pool = past.filter((p) => p.window === window);
+ if (!pool.length) pool = past;
+ note = `no past ${from ? "take made from another" : "fresh take"}${window === "window" ? " of a window" : " of the whole cut"} — from the project's other renders`;
+ }
+ pool = pool.slice(-last);
+ const rate = median(pool.map((p) => p.renderSeconds / p.seconds));
+ return {
+ etaSeconds: Math.round(rate * seconds),
+ rate: Math.round(rate * 100) / 100,
+ basis: pool.map((p) => ({ id: p.id, seconds: p.seconds, renderSeconds: p.renderSeconds, how: p.how })),
+ kind: want,
+ note,
+ };
+}
+
+/** `1 h 05 min` / `23 min` / `40 s`. */
+export function etaText(s) {
+ if (!num(s)) return "—";
+ if (s < 90) return `${Math.round(s)} s`;
+ const m = Math.round(s / 60);
+ return m >= 60 ? `${Math.floor(m / 60)} h ${String(m % 60).padStart(2, "0")} min` : `${m} min`;
+}
+
+/**
+ * The project's ETAs for the take panel: a whole-cut take fresh and made from
+ * the newest take, at the length of the newest whole-cut take.
+ * @param {string} projectDir
+ */
+export async function projectEtas(projectDir) {
+ const past = await pastRenders(projectDir);
+ const fulls = past.filter((p) => p.window === "full");
+ const newest = fulls.at(-1) ?? null;
+ const seconds = newest?.seconds ?? null;
+ return {
+ past,
+ seconds,
+ newest: newest?.id ?? null,
+ fresh: seconds ? takeEta(past, { seconds, from: false }) : null,
+ reuse: seconds ? takeEta(past, { seconds, from: true }) : null,
+ };
+}
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -478,7 +478,7 @@ export async function linkSharedOut(projectDir, takeOut) {
* @param {{ force?: boolean, render?: RenderFn, probe?: (file: string) => Promise<number | null>,
* styles?: Record<string, { label: string, summary: string, patch: Record<string, unknown> }>,
* emit?: (ev: Record<string, unknown>) => void, log?: (line: string) => void,
- * ensureOut?: (dir: string) => Promise<unknown>, now?: () => Date,
+ * ensureOut?: (dir: string) => Promise<unknown>, now?: () => Date, clock?: () => number,
* from?: string | null, keepFrames?: boolean }} [opts]
* `from`: another take whose built segments, chrome renders and crossfade
* batches are hard-linked in before the render (takeFrom.mjs), so the build
@@ -640,6 +640,17 @@ async function makeTakeLocked(projectDir, rawSpec, opts) {
const xfade = patches.some((p) => getPath(p, "render.transition") !== undefined) && transition > 0;
emit({ ev: "take", id: spec.id, phase: "render", window: spec.window, entries: covered?.ids ?? null, basis: covered?.basis ?? null });
let file;
+ // How long the render itself took (UI notes #18: a take's ETA is read from
+ // the project's past renders, lib/report/takeEta.mjs): from the build's
+ // first event -- after the heavy slot admitted it, so a wait at the slot's
+ // door is not counted -- to its end. Recorded as take.json `renderSeconds`.
+ const clock = opts.clock ?? Date.now;
+ const renderStart = clock();
+ let firstEventAt = null;
+ const timedEmit = (ev) => {
+ if (firstEventAt === null && ev?.ev !== "take") firstEventAt = clock();
+ emit(ev);
+ };
try {
const render = opts.render ?? (await import("./takeRender.mjs")).renderTake;
({ file } = await render({
@@ -649,12 +660,13 @@ async function makeTakeLocked(projectDir, rawSpec, opts) {
full: spec.window === "full",
xfade,
keepFrames: opts.keepFrames === true,
- emit,
+ emit: timedEmit,
log,
}));
} finally {
await rm(renderPath, { force: true });
}
+ const renderSeconds = Math.round((clock() - (firstEventAt ?? renderStart)) / 100) / 10;
await moveFile(file, preview);
await keepBuildName(preview, file, (line) => log(`${spec.id}: ${line}`));
@@ -686,6 +698,8 @@ async function makeTakeLocked(projectDir, rawSpec, opts) {
baseHash: hashText(baseText),
// The take it was built from: the pruner keeps a kept take's base (takePrune.mjs).
...(opts.from ? { from: opts.from } : {}),
+ // The render's own time, for the next take's ETA (takeEta.mjs).
+ renderSeconds,
};
const tmp = `${takeFile}.tmp-${process.pid}`;
await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8");
diff --git a/umtool/lib/report/takeMaker.test.mjs b/umtool/lib/report/takeMaker.test.mjs
@@ -590,3 +590,22 @@ test("makeTake refuses a cut that still holds a clip ruled incorrect, by name an
await rm(root, { recursive: true, force: true });
}
});
+
+test("makeTake records renderSeconds: from the build's first event (after any wait at the heavy slot) to its end (UI notes #18)", async () => {
+ const { root, dir } = await project();
+ let t = 0;
+ const r = stubRender();
+ const render = async (job) => {
+ t = 30_000; // 30 s waiting at the slot's door: not counted
+ job.emit({ ev: "phase", phase: "clips" });
+ t = 30_000 + 95_400;
+ return r.render(job);
+ };
+ try {
+ await makeTake(dir, { id: "timed", label: "Timed", group: "g", window: "full" }, opts(r, { render, clock: () => t }));
+ const doc = JSON.parse(await readFile(path.join(dir, "takes", "timed", "take.json"), "utf8"));
+ assert.equal(doc.renderSeconds, 95.4);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/ui-ops.test.mjs b/umtool/lib/report/ui-ops.test.mjs
@@ -244,3 +244,67 @@ test("the inserters write the policy's link; the check's clip-link-policy rows a
await p.done();
}
});
+
+// ---- #18 a take's ETA from the project's past renders --------------------
+
+const { etaText, parseDuration, pastRenders, projectEtas, slotWaitOf, takeEta } = await import("./takeEta.mjs");
+
+test("parseDuration / slotWaitOf: the heavy gate's waits, read from a render's log", () => {
+ assert.equal(parseDuration("35s"), 35);
+ assert.equal(parseDuration("2m10s"), 130);
+ assert.equal(parseDuration("1h02m"), 3720);
+ assert.equal(parseDuration("soon"), null);
+ assert.equal(slotWaitOf("heavy: waiting for memory — …\nheavy: 8879 MB available after 35s — admitted\nqueue-lock: the render let go after 2m10s — going on\n"), 165);
+ assert.equal(slotWaitOf("take x: done (1413.3 s)"), 0, "a take's done line is the video's length, not a wait");
+});
+
+test("pastRenders: recorded renderSeconds, else the take's files' times less its log's wait; a draft or a take with no length is not one", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "ui-ops-eta-"));
+ try {
+ const take = async (id, doc, { manifestAt = null, log = null } = {}) => {
+ const d = path.join(dir, "takes", id);
+ await mkdir(d, { recursive: true });
+ await writeFile(path.join(d, "take.json"), JSON.stringify({ id, group: "takes", order: 1, label: id, kind: "reference", preview: "preview.mp4", ...doc }));
+ if (manifestAt) {
+ await writeFile(path.join(d, "video.manifest.json"), "{}");
+ await utimes(path.join(d, "video.manifest.json"), new Date(manifestAt), new Date(manifestAt));
+ }
+ if (log) await writeFile(path.join(dir, `${id}.log`), log);
+ };
+ await take("d1", { seconds: 600, window: "full", builtAt: "2026-10-30T10:40:00.000Z" }, { manifestAt: "2026-10-30T10:00:00.000Z", log: "heavy: 9000 MB available after 4m00s — admitted\n" });
+ await take("d2", { seconds: 600, window: "full", builtAt: "2026-10-31T10:00:00.000Z", renderSeconds: 900, from: "d1" });
+ await take("d3", { seconds: 30, window: { at: 0, dur: 30 }, builtAt: "2026-10-31T11:00:00.000Z", renderSeconds: 90 });
+ await take("dr", { seconds: null, draft: true, builtAt: null });
+ const past = await pastRenders(dir);
+ assert.deepEqual(past.map((p) => [p.id, p.renderSeconds, p.how, p.window, p.from]), [
+ ["d1", 2160, "files", "full", null],
+ ["d2", 900, "recorded", "full", "d1"],
+ ["d3", 90, "recorded", "window", null],
+ ]);
+ const e = await projectEtas(dir);
+ assert.equal(e.seconds, 600);
+ assert.equal(e.newest, "d2");
+ assert.equal(e.fresh?.etaSeconds, 2160);
+ assert.equal(e.reuse?.etaSeconds, 900);
+ assert.equal(etaText(e.fresh?.etaSeconds), "36 min");
+ assert.equal(etaText(4000), "1 h 07 min");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("takeEta: the median rate of the same kind, times the length; none of its kind says so and uses the others", () => {
+ const past = [
+ { id: "a", seconds: 100, renderSeconds: 300, how: "recorded", window: "full", from: null, quick: false, builtAt: "1" },
+ { id: "b", seconds: 100, renderSeconds: 500, how: "recorded", window: "full", from: null, quick: false, builtAt: "2" },
+ { id: "c", seconds: 100, renderSeconds: 100, how: "recorded", window: "full", from: "b", quick: false, builtAt: "3" },
+ ];
+ const fresh = takeEta(past, { seconds: 200 });
+ assert.deepEqual([fresh?.etaSeconds, fresh?.rate, fresh?.basis.map((b) => b.id), fresh?.note], [800, 4, ["a", "b"], null]);
+ const reuse = takeEta(past, { seconds: 200, from: true });
+ assert.deepEqual([reuse?.etaSeconds, reuse?.basis.map((b) => b.id)], [200, ["c"]]);
+ const win = takeEta(past, { seconds: 60, window: "window" });
+ assert.equal(win?.etaSeconds, 180);
+ assert.match(String(win?.note), /no past fresh take of a window — from the project's other renders/);
+ assert.equal(takeEta([], { seconds: 60 }), null);
+});