commit cf477274857a3f9904584144851dee56174f0c6c
parent 2a32bd0a66321a05af66cff618bbcb04dee8dac8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 30 Oct 2026 14:09:48 -0400
Render mode: a render the operator waits for gets the machine (umtool take --priority, umtool render-mode, pnpm ops render-mode)
A machine-global render-priority state beside the heavy slot's lock
(<git common dir>/heavy-queue.lock.render.json, common/lib/renderPriority.mjs):
{token, since, until, by, note, holder: {pid, pidStart, cmd, project, take},
lanesHeld, lanesSkipped, editor}. A holder pid that is gone (or reused) or an
until in the past is no hold.
- queue-lock: while it is held, every other heavy job (e2e suites, next builds,
the publish stages, other renders) waits before the line with
`queue-lock: held for a render (umtool take <p> --id <t>, since 13:31) — waiting`;
a job carrying RENDER_PRIORITY_TOKEN is the render, admitted on the floor
4000 MB and the cap 10240 MB unless HEAVY_MIN_FREE_MB / HEAVY_CAP_MB say.
RENDER_PRIORITY=0 bypasses; --urgent (a live stream's sniff) never waits.
- umtool take/takes make --priority: on for the take's lifetime, off at its
end, failure or signal; umtool render-mode on [--for 90m] [--note] | off
[--force] | status. The editor's transcription and download lanes are held
through its ops (lane), only those not held already, and only those released.
- editor: pnpm ops render-mode {"on": true, "for"?, "note"?} | {"on": false},
get render-mode; a /jobs banner (End for a manual window); the heartbeat
releases a stale hold's lanes (only its own editor's).
- umtool Takes panel: "Give renders the machine" (renders started there get
--priority) and a banner while held, with the close-heavy-apps reminder.
- Docs: AGENTS.md "Render mode", WORKTREES.md, umtool cli.md and
report-video.md; COMMANDS.md and ENVIRONMENT.md regenerated.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
36 files changed, 2306 insertions(+), 62 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
@@ -76,8 +76,31 @@ MemorySwapMax 2G) unless it carries its own cap or its caller already sits under
units, a capped scope); `HEAVY_CAP=0` turns that off. Bypasses: `HEAVY=0`,
`HEAVY_MIN_FREE_MB=<MB>`, `HEAVY_TIMEOUT=<seconds>`.
-See [WORKTREES.md](WORKTREES.md) for the port scheme, the queue, the heavy slot, and the
-shared-data caveat.
+# Render mode
+
+**When the operator is waiting for a render, give it the machine — from any session:**
+
+```sh
+umtool take <project> --id <take> … --priority # for that take's lifetime
+umtool render-mode on [--for 90m] [--note "…"] # a window, for a chain of renders (default 2h)
+umtool render-mode status | off
+pnpm ops render-mode --json '{"on":true,"for":"90m"}' # the same with only pnpm ops; get render-mode
+```
+
+While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other
+renders) waits at the heavy slot's door — `queue-lock: held for a render (umtool take <p> --id
+<t>, since 13:31) — waiting` is the gate working — while the render runs on the floor 4000 MB
+and the cap 10240 MB; the editor's transcription and download lanes are held (only the ones
+not already held; only those are released). It turns itself off: at the take's end, failure
+or signal, at the window's `until`, or when its process is gone (the editor's heartbeat
+releases the lanes). Then tell the operator to **close Firefox and other heavy apps**, and
+put the render before any merge or ship it does not need. A job already running is not
+stopped — do not start e2e or builds yourself meanwhile. The umtool take panel's **Give
+renders the machine** toggle is the same `--priority`; `/jobs` and the take panel show a
+banner. `RENDER_PRIORITY=0` runs a job anyway. Details: WORKTREES.md, "Render mode".
+
+See [WORKTREES.md](WORKTREES.md) for the port scheme, the queue, the heavy slot, render mode,
+and the shared-data caveat.
# Working this repo with no local corpus
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -146,6 +146,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `reports-prepare` | reports-prepare cuts every clip and copies every post capture a site's published reports cite into its report-media cache, before its build: {"siteId"}. The job fails, naming each one, when a citation lacks media. When nothing is missing it then exports the reports, as reports-export. {"articles": true} does it for the published articles (transcripts/ reports/, the homepage's); {"article": "<id>"} adds that one (a draft). | `pnpm ops reports-prepare --json '{"siteId":"demo-site"}' --wait`<br>`pnpm ops reports-prepare --json '{"articles":true}' --wait` |
| `reports-export` | reports-export writes each published report as report.html, report.pdf, report.md, slides.html, slides.pdf and evidence-pack.zip for the site's build to publish: {"siteId", "reportId"?, "formats"?: \["html","pdf","md", "slides","slides-pdf","zip"\]}; {"articles": true, "reportId"?, …} the articles' (reportId: one article, published or a draft). | `pnpm ops reports-export --json '{"siteId":"demo-site","formats":["html","md"]}' --wait` |
| `lane` | lane takes {"lane": "transcription"\|"download"\|"digest"\|"backfill"\| "publish", "enabled"?, "held"?, "action"?: "start"\|"stop"\|"drain"}, or {"lane": "report-schedule", "held"}: the recurring reports' gate, its only key. | `pnpm ops lane --json '{"lane":"download","held":true}'`<br>`pnpm ops lane --json '{"lane":"publish","action":"drain"}'` |
+| `render-mode` | render-mode gives a render the operator is waiting for the machine: {"on": true, "for"?: "90m" \| <minutes>, "note"?} opens a window (default 2h) in which every other heavy job — e2e suites, next builds, the publish stages, other renders — waits at the heavy slot's door, and holds the transcription and download lanes (only the ones not already held; only those are released). The answer's "join" (RENDER\_PRIORITY\_TOKEN=…) lets a render in, on the floor 4000 MB and the cap 10240 MB; every `umtool take` joins by itself. {"on": false} ends it ("force": true ends a running take's hold, which otherwise ends with the take). `umtool take … --priority` is the same for one take. `get render-mode` says whether it is on, for what, since when, which lanes it holds. Close Firefox and other heavy apps while it renders. | `pnpm ops render-mode --json '{"on":true,"for":"90m","note":"the Ember cut"}'`<br>`pnpm ops render-mode --json '{"on":false}'` |
| `tags` | tags edits the curated-tag vocabulary through its one writer: {"op": "define", "tag": {...}} (the WHOLE definition: id, label, rules and "sites", the sites it exists on, absent = every site) or {"op": "remove", "tag": "<id>"}. `get tags [<id>]` reads it. | `pnpm ops tags --json '{"op":"define","tag":{"id":"eva-collab","label":"Collab"}}'` |
| `tag-videos` | tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos in ONE write: {"tag", "op": "add" \| "remove" \| "suppress" \| "unsuppress", "videos": \[{"slug", "id"}, ...\]}. "remove" unpins only — a rule's hit survives; "suppress" rejects it. The write records who asked (ARCHILYZER\_AGENT); a big list goes in --file. | `pnpm ops tag-videos --file ids.json` |
| `keep-videos` | keep-videos sets the "Do not clean" marker on every held video of a channel whose title or description matches a download-filter pattern: {"slug", "match", "fields"?: \["title" \| "description"\], "note"?, "dryRun"?}. A match not held is reported in "notDownloaded", never created; a fresh channel wants metadata-scan first. Or by id: {"slug", "ids": \[...\], "note"?, "dryRun"?} — a held video is marked now, one not held yet (a live stream, a VOD not fetched) is PENDING and marked when its record is first written (a download, an import, a recording); "pendingAll" lists the channel's pending ids. | `pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'` |
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -133,6 +133,9 @@ Tokens, credentials and knobs a running process reads. Most configuration is not
| `HEAVY_CAP` | on | An admitted `pnpm heavy` / `queue-lock --heavy` command runs in a memory-capped systemd user scope of its own (`systemd-run --user --scope`, MemoryMax + MemorySwapMax, never MemoryHigh), so a runaway dies in its scope instead of taking the session down. Not wrapped when the command carries its own `MemoryMax=`, when the caller already sits under a finite memory.max (the live units, a capped scope, a container), or with no `systemd-run`. `0` turns it off. | scripts/queue-lock.mjs |
| `HEAVY_CAP_MB` | `8192` | The heavy cap's MemoryMax in MB; a larger `--estimate` raises it to the estimate. The cap never changes admission: an undeclared job still runs alone. | scripts/queue-lock.mjs |
| `HEAVY_CAP_SWAP_MB` | `2048` | The heavy cap's MemorySwapMax in MB. | scripts/queue-lock.mjs |
+| `RENDER_PRIORITY` | on | `0` runs a heavy job without waiting for render mode: while a render the operator waits for holds the machine (`umtool take … --priority`, `umtool render-mode on`, `pnpm ops render-mode`), every other heavy job — e2e suites, `next build`s, the publish stages, other renders — waits at the heavy slot's door. For an emergency; `HEAVY=0` skips the wait too. AGENTS.md "Render mode". | scripts/queue-lock.mjs (common/lib/renderPriority.mjs) |
+| `RENDER_PRIORITY_TOKEN` | — | The render-mode hold a heavy job belongs to: a job carrying the hold's token is the render (admitted while the others wait, on the floor 4000 MB and the cap 10240 MB unless `HEAVY_MIN_FREE_MB` / `HEAVY_CAP_MB` say). `umtool take` sets it for its render; `umtool render-mode on` and `pnpm ops render-mode` print it for another command to join. | scripts/queue-lock.mjs (common/lib/renderPriority.mjs) |
+| `RENDER_PRIORITY_FILE` | `<heavy lock>.render.json` | Render mode's state file — by default beside the heavy slot's lock (`HEAVY_LOCK_FILE`, else `<git common dir>/heavy-queue.lock`), so one per machine. The e2e servers and the tests point it at their own. | common/lib/renderPriority.mjs |
| `HEAVY_TIMEOUT` | wait forever | Seconds a `pnpm heavy` run waits for the slot, and then for the floor, before giving up (exit 3). An e2e run uses `E2E_QUEUE_TIMEOUT` for both. | scripts/queue-lock.mjs |
## Ports
diff --git a/WORKTREES.md b/WORKTREES.md
@@ -278,6 +278,7 @@ alone — it is a safety net, not a correctness lock.
| `HEAVY=0` | Skip the heavy slot AND the memory floor |
| `HEAVY_MIN_FREE_MB=<MB>` | Move the floor (`0` turns it off; the build rule still holds) |
| `HEAVY_TIMEOUT=<seconds>` | Give up waiting (line, slot, memory) after N seconds; an e2e run uses `E2E_QUEUE_TIMEOUT` |
+| `RENDER_PRIORITY=0` | Do not wait for a render in render mode (below) |
| `HEAVY_CAP=0` | Run a `--heavy` command without the default memory cap |
| `HEAVY_CAP_MB=<MB>` / `HEAVY_CAP_SWAP_MB=<MB>` | Size the cap (8192 / 2048) |
| `UMTOOL_RENDER_ESTIMATE_MB=<MB>` | What a render declares (`0`: nothing — it runs alone) |
@@ -339,21 +340,46 @@ counts the browser (it measured the whole process tree); the cap cannot.
render to finish as before. A build that declares (`systemd-run … -p MemoryMax=5G … next
build`, or `--build`) is the one that runs beside a render.
-### A render and the transcription lane
+### Render mode: a render the operator waits for gets the machine
-A render competes with the transcription lane for memory and CPU, and the lane is not a heavy
-slot holder.
-Hold the lane for the render's duration, and release it whatever the render's outcome:
+The slot admits by memory. A render someone is watching is slowed by **CPU** instead —
+measured 2026-10-30, the render peaked under 1 GB in its scope while cutting and about 200 MB
+per Chromium worker while capturing, and what dragged it was parakeet ASR from the
+transcription lane, the editor, and e2e servers and browsers beside it. **Render mode**
+(`common/lib/renderPriority.mjs`) gives that render the machine:
```sh
-pnpm ops lane --json '{"lane":"transcription","held":true}'
-node umtool/report-to-video/build-video.mjs <manifest> … ; \
- pnpm ops lane --json '{"lane":"transcription","held":false}'
+umtool take <project> --id <take> … --priority # for this take's lifetime (on at start; off at end, failure, signal)
+umtool render-mode on [--for 90m] [--note …] # a window for a chain of renders (default 2h)
+umtool render-mode status | off [--force]
+pnpm ops render-mode --json '{"on":true,"for":"90m"}' # the same from a session with only pnpm ops
+pnpm ops get render-mode
```
-A hold stops new dispatches, not a transcription already running; and the release
-resumes the lane even if someone else held it for another reason — check `/operations`
-first.
+While it is on:
+
+- **every other heavy job waits at the door** — e2e suites, `next build`s, the publish
+ stages, other renders: `queue-lock: held for a render (umtool take <p> --id <t>, since
+ 13:31) — waiting`. It waits *before* the line, so it never holds the line the render is
+ admitted through. A job already admitted is not stopped; a nested one (`HEAVY_HELD`)
+ passes as before; a live stream's sniff (`--urgent`) never waits.
+- **the render is admitted**: it and everything under it carry the hold's token
+ (`RENDER_PRIORITY_TOKEN`), on the floor **4000 MB** and the cap **10240 MB** unless
+ `HEAVY_MIN_FREE_MB` / `HEAVY_CAP_MB` say otherwise. Every `umtool take` started inside a
+ manual window joins it; another command joins with the token `on` prints.
+- **the editor's transcription and download lanes are held** — only the ones not already
+ held, and only those are released at the end (a hold someone else made stays). With no
+ editor to ask, render mode still holds the door and says the lanes were not held.
+- the umtool take panel and the editor's `/jobs` show a banner; **close Firefox and other
+ heavy apps** while it renders.
+
+The state is one file beside the slot's lock, `<git common dir>/heavy-queue.lock.render.json`
+(`{token, since, until, by, note, holder: {pid, cmd, project, take}, lanesHeld,
+lanesSkipped, editor}`). **A crash leaves no hold:** a holder pid that is gone (or reused),
+or an `until` in the past, is not held — the gate ignores it at once — and its lanes are
+released by the editor's heartbeat, `/jobs`'s End button, or the next `umtool render-mode
+status`/`on`. `RENDER_PRIORITY=0` runs a job anyway (an emergency); `HEAVY=0` skips the
+wait with everything else.
## Data directories
diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts
@@ -470,7 +470,9 @@ export const sniffLivePlaylist: LiveSniffer = async ({ paths, pageUrl, onLog, si
if (!xvfb) onLog("xvfb-run is not installed: the page is opened headless, which Rumble's Cloudflare refuses.\n");
const gate = path.join(paths.monorepoRoot, "scripts", "queue-lock.mjs");
const gated = await stat(gate).then((s) => s.isFile(), () => false);
- const [bin, ...args] = gated ? [process.execPath, gate, "--heavy", "--estimate", "1000", "--", ...inner] : inner;
+ // --urgent: a stream does not wait for a render in render mode — a few
+ // seconds of browser now, or the recording misses its start.
+ const [bin, ...args] = gated ? [process.execPath, gate, "--heavy", "--estimate", "1000", "--urgent", "--", ...inner] : inner;
onLog(`Opening ${pageUrl} in a browser for its playlist${gated ? " (the heavy slot)" : ""}.\n`);
const r = await execa(bin!, args, { reject: false, cancelSignal: signal, cwd: paths.monorepoRoot });
const line = String(r.stdout).trim().split("\n").filter((l) => l.startsWith("{")).pop();
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -169,6 +169,9 @@ const DECLARED: EnvVarDecl[] = [
{ name: "HEAVY_CAP", audience: "runtime", default: "on", readBy: "scripts/queue-lock.mjs", doc: "An admitted `pnpm heavy` / `queue-lock --heavy` command runs in a memory-capped systemd user scope of its own (`systemd-run --user --scope`, MemoryMax + MemorySwapMax, never MemoryHigh), so a runaway dies in its scope instead of taking the session down. Not wrapped when the command carries its own `MemoryMax=`, when the caller already sits under a finite memory.max (the live units, a capped scope, a container), or with no `systemd-run`. `0` turns it off." },
{ name: "HEAVY_CAP_MB", audience: "runtime", default: "`8192`", readBy: "scripts/queue-lock.mjs", doc: "The heavy cap's MemoryMax in MB; a larger `--estimate` raises it to the estimate. The cap never changes admission: an undeclared job still runs alone." },
{ name: "HEAVY_CAP_SWAP_MB", audience: "runtime", default: "`2048`", readBy: "scripts/queue-lock.mjs", doc: "The heavy cap's MemorySwapMax in MB." },
+ { name: "RENDER_PRIORITY", audience: "runtime", default: "on", readBy: "scripts/queue-lock.mjs (common/lib/renderPriority.mjs)", doc: "`0` runs a heavy job without waiting for render mode: while a render the operator waits for holds the machine (`umtool take … --priority`, `umtool render-mode on`, `pnpm ops render-mode`), every other heavy job — e2e suites, `next build`s, the publish stages, other renders — waits at the heavy slot's door. For an emergency; `HEAVY=0` skips the wait too. AGENTS.md \"Render mode\"." },
+ { name: "RENDER_PRIORITY_TOKEN", audience: "runtime", default: "—", readBy: "scripts/queue-lock.mjs (common/lib/renderPriority.mjs)", doc: "The render-mode hold a heavy job belongs to: a job carrying the hold's token is the render (admitted while the others wait, on the floor 4000 MB and the cap 10240 MB unless `HEAVY_MIN_FREE_MB` / `HEAVY_CAP_MB` say). `umtool take` sets it for its render; `umtool render-mode on` and `pnpm ops render-mode` print it for another command to join." },
+ { name: "RENDER_PRIORITY_FILE", audience: "runtime", default: "`<heavy lock>.render.json`", readBy: "common/lib/renderPriority.mjs", doc: "Render mode's state file — by default beside the heavy slot's lock (`HEAVY_LOCK_FILE`, else `<git common dir>/heavy-queue.lock`), so one per machine. The e2e servers and the tests point it at their own." },
{ name: "HEAVY_TIMEOUT", audience: "runtime", default: "wait forever", readBy: "scripts/queue-lock.mjs", doc: "Seconds a `pnpm heavy` run waits for the slot, and then for the floor, before giving up (exit 3). An e2e run uses `E2E_QUEUE_TIMEOUT` for both." },
// ── internal: the pipeline sets these for a process it spawns ──────────
diff --git a/common/lib/renderPriority.mjs b/common/lib/renderPriority.mjs
@@ -0,0 +1,452 @@
+// RENDER MODE — a render the operator is waiting for gets the machine.
+//
+// The heavy slot (scripts/queue-lock.mjs) admits by MEMORY. A render the
+// operator is watching is slowed by CPU, not memory: measured 2026-10-30, the
+// render peaked under 1 GB in its scope while cutting and ~200 MB per Chromium
+// worker while capturing, and what dragged it was parakeet ASR from the
+// transcription lane, the editor, and e2e servers and browsers beside it. So
+// render mode is a machine-global flag, one small JSON file, that:
+//
+// - makes every OTHER heavy job wait at the slot's door (queue-lock.mjs
+// withHeavy: e2e suites, `next build`s, the publish stages, other renders)
+// with `queue-lock: held for a render (umtool take <p> --id <t>, since
+// 13:31) — waiting`; a job carrying the hold's token (the render and its
+// subprocesses: RENDER_PRIORITY_TOKEN) is admitted, with the floor 4000 MB
+// and the cap 10240 MB unless HEAVY_MIN_FREE_MB / HEAVY_CAP_MB say
+// otherwise;
+// - holds the editor's transcription and download lanes, remembering which
+// ones IT held (`lanesHeld`), so ending it releases only those — a lane
+// someone else held before stays held.
+//
+// Turned on by `umtool take … --priority` (for the take's lifetime),
+// `umtool render-mode on [--for 90m]` (a window, e.g. a chain of renders) or
+// `pnpm ops render-mode {"on": true}`; AGENTS.md "Render mode".
+//
+// THE FILE sits beside the heavy slot's lock: `<heavy lock>.render.json`, i.e.
+// `<git common dir>/heavy-queue.lock.render.json` on this machine (one for
+// every worktree), beside a HEAVY_LOCK_FILE when one is set (so the gate's
+// tests have their own), or wherever RENDER_PRIORITY_FILE says. Its shape:
+//
+// { version: 1, token, since, until | null, by, note | null,
+// holder: { pid, pidStart, cmd, project, take } | null,
+// lanesHeld: ["transcription", …], lanesSkipped: [...], editor | null }
+//
+// LIVENESS, so a crash never leaves a hold: a holder whose pid is gone (or
+// reused: pidStart), or an `until` in the past, is NOT held — queue-lock
+// ignores it at once. Its lanes are released by whoever next looks with an
+// editor in hand (`reapRenderMode`: the editor's heartbeat, /jobs, `render-mode
+// status`, the next `on`). A manual window always carries an `until` (2 h by
+// default), so a forgotten one ends by itself.
+//
+// Plain JS with JSDoc, no dependencies: queue-lock.mjs runs it under bare node,
+// umtool's CLI and app and the editor import it as it is.
+
+import { execFileSync } from "node:child_process";
+import { randomBytes } from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+/** The memory floor a render in render mode is admitted on, absent HEAVY_MIN_FREE_MB. */
+export const RENDER_PRIORITY_FLOOR_MB = 4000;
+/** The render's heavy cap (MemoryMax) in render mode, absent HEAVY_CAP_MB. */
+export const RENDER_PRIORITY_CAP_MB = 10240;
+/** The editor lanes render mode holds. */
+export const RENDER_MODE_LANES = Object.freeze(["transcription", "download"]);
+/** A manual window with no --for ends after this. */
+export const DEFAULT_RENDER_MODE_WINDOW_MS = 2 * 60 * 60 * 1000;
+/** The env var a render (and everything under it) carries the hold's token in. */
+export const RENDER_PRIORITY_TOKEN_ENV = "RENDER_PRIORITY_TOKEN";
+/** The one line said to the operator when render mode goes on. */
+export const RENDER_MODE_REMINDER = "close Firefox and other heavy apps while this renders";
+
+const HEAVY_LOCK_NAME = "heavy-queue.lock";
+const STATE_SUFFIX = ".render.json";
+
+/**
+ * @typedef {{ pid: number, pidStart?: string | null, cmd?: string | null, project?: string | null, take?: string | null }} RenderHolder
+ * @typedef {{
+ * version: 1, token: string, since: string, until: string | null, by: string | null, note: string | null,
+ * holder: RenderHolder | null, lanesHeld: string[], lanesSkipped?: string[], lanesError?: string | null,
+ * editor?: string | null, ended?: boolean,
+ * }} RenderPriorityState
+ * @typedef {{ held: boolean, state: RenderPriorityState | null, stale: null | "expired" | "holder-gone" | "no-end" }} RenderPriorityStatus
+ * @typedef {{ isHeld: (lane: string) => Promise<boolean>, hold: (lane: string) => Promise<void>, release: (lane: string) => Promise<void> }} RenderModeLanes
+ */
+
+// ---------------------------------------------------------------- the file
+
+/** The git common dir of `cwd` (one for every worktree), or null. */
+function gitCommonDir(cwd) {
+ try {
+ const out = execFileSync("git", ["-C", cwd, "rev-parse", "--path-format=absolute", "--git-common-dir"], {
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ }).trim();
+ return out || null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Where render mode's state lives: RENDER_PRIORITY_FILE; else beside the heavy
+ * slot's lock — `heavyLock` (queue-lock hands its own), HEAVY_LOCK_FILE, or the
+ * one in the git common dir of `root` (default: the cwd; a CLI run from a
+ * report workspace passes its checkout) — as queue-lock.mjs finds it, a tmpdir
+ * outside a git checkout (a container).
+ * @param {Record<string, string | undefined>} [env]
+ * @param {{ heavyLock?: string | null, root?: string }} [opts]
+ */
+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}`;
+}
+
+/** The file's JSON, or null (missing, half-written, not ours). */
+export function readRenderPriorityState(file) {
+ try {
+ const s = JSON.parse(fs.readFileSync(/* turbopackIgnore: true */ file, "utf8"));
+ return s && typeof s === "object" && typeof s.token === "string" ? /** @type {RenderPriorityState} */ (s) : null;
+ } catch {
+ return null;
+ }
+}
+
+/** tmp + rename, so a reader never sees half a file. */
+function writeState(file, state) {
+ fs.mkdirSync(/* turbopackIgnore: true */ path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.${randomBytes(3).toString("hex")}.tmp`;
+ fs.writeFileSync(/* turbopackIgnore: true */ tmp, `${JSON.stringify(state, null, 2)}\n`);
+ fs.renameSync(tmp, file);
+}
+
+/**
+ * Create the file only if there is none: a hard link of a written temp file
+ * fails with EEXIST when another hold got there first, so two `on`s at once
+ * cannot both win. True when created.
+ */
+function createState(file, state) {
+ fs.mkdirSync(/* turbopackIgnore: true */ path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.${randomBytes(3).toString("hex")}.tmp`;
+ fs.writeFileSync(/* turbopackIgnore: true */ tmp, `${JSON.stringify(state, null, 2)}\n`);
+ try {
+ fs.linkSync(tmp, file);
+ return true;
+ } catch (err) {
+ if (/** @type {NodeJS.ErrnoException} */ (err).code === "EEXIST") return false;
+ throw err;
+ } finally {
+ fs.rmSync(/* turbopackIgnore: true */ tmp, { force: true });
+ }
+}
+
+/** Remove the file only while it is still the hold `token` names. */
+function removeIfToken(file, token) {
+ const cur = readRenderPriorityState(file);
+ if (cur && cur.token !== token) return false;
+ fs.rmSync(/* turbopackIgnore: true */ file, { force: true });
+ return true;
+}
+
+// ---------------------------------------------------------------- liveness
+
+/** /proc/<pid>/stat's start time (field 22), so a reused pid is not the holder. Null off Linux. */
+export function pidStartTime(pid) {
+ try {
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
+ return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19] ?? null;
+ } catch {
+ return null;
+ }
+}
+
+/** Whether the holder's process is still the one that took the hold. */
+export function holderAlive(holder) {
+ if (!holder || !Number.isInteger(holder.pid)) return false;
+ try {
+ process.kill(holder.pid, 0);
+ } catch (err) {
+ if (/** @type {NodeJS.ErrnoException} */ (err).code !== "EPERM") return false;
+ }
+ return holder.pidStart == null || pidStartTime(holder.pid) === holder.pidStart;
+}
+
+/**
+ * Whether a state is a hold now, pure but for `isAlive`. A holder pid that is
+ * gone, an `until` in the past, or a state with neither (a hold nothing would
+ * ever end) is not held — `stale` says which.
+ * @param {RenderPriorityState | null} state
+ * @param {{ now?: number, isAlive?: (h: RenderHolder) => boolean }} [opts]
+ * @returns {RenderPriorityStatus}
+ */
+export function renderPriorityStatus(state, { now = Date.now(), isAlive = holderAlive } = {}) {
+ if (!state) return { held: false, state: null, stale: null };
+ const untilMs = state.until ? Date.parse(state.until) : NaN;
+ if (Number.isFinite(untilMs) && untilMs <= now) return { held: false, state, stale: "expired" };
+ if (state.holder && state.holder.pid != null) {
+ if (!isAlive(state.holder)) return { held: false, state, stale: "holder-gone" };
+ } else if (!Number.isFinite(untilMs)) {
+ return { held: false, state, stale: "no-end" };
+ }
+ return { held: true, state, stale: null };
+}
+
+/**
+ * Render mode as it stands: `{held, state, stale}`.
+ * @param {string} file
+ * @param {{ now?: number, isAlive?: (h: RenderHolder) => boolean }} [opts]
+ */
+export function readRenderPriority(file, opts = {}) {
+ return renderPriorityStatus(readRenderPriorityState(file), opts);
+}
+
+// ------------------------------------------------------- what the gate asks
+
+/**
+ * Whether render mode makes a heavy job wait: it is held, the job does not
+ * carry its token, and nobody said RENDER_PRIORITY=0. `urgent` (a live
+ * stream's few seconds of browser) never waits.
+ * @param {RenderPriorityStatus} status
+ * @param {Record<string, string | undefined>} [env]
+ * @param {{ urgent?: boolean }} [opts]
+ */
+export function renderPriorityBlocks(status, env = process.env, { urgent = false } = {}) {
+ if (!status?.held || !status.state || urgent || env.RENDER_PRIORITY === "0") return false;
+ return env[RENDER_PRIORITY_TOKEN_ENV] !== status.state.token;
+}
+
+/** Whether `env` carries the token of the hold `status` names (the render itself). */
+export function carriesRenderPriority(status, env = process.env) {
+ return Boolean(status?.held && status.state && env[RENDER_PRIORITY_TOKEN_ENV] === status.state.token);
+}
+
+/**
+ * The render's own defaults, into `env` where it leaves them unset: the floor
+ * 4000 MB, the cap 10240 MB. Returns the names it set.
+ * @param {Record<string, string | undefined>} env
+ */
+export function applyRenderPriorityDefaults(env) {
+ const set = [];
+ if (env.HEAVY_MIN_FREE_MB == null || env.HEAVY_MIN_FREE_MB === "") {
+ env.HEAVY_MIN_FREE_MB = String(RENDER_PRIORITY_FLOOR_MB);
+ set.push("HEAVY_MIN_FREE_MB");
+ }
+ if (env.HEAVY_CAP_MB == null || env.HEAVY_CAP_MB === "") {
+ env.HEAVY_CAP_MB = String(RENDER_PRIORITY_CAP_MB);
+ set.push("HEAVY_CAP_MB");
+ }
+ return set;
+}
+
+/** "13:31", local time, or "?". */
+export function clockOf(iso) {
+ const ms = Date.parse(String(iso ?? ""));
+ if (!Number.isFinite(ms)) return "?";
+ const d = new Date(ms);
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
+}
+
+/**
+ * What the hold is, in a waiter's words: "umtool take <p> --id <t>, since
+ * 13:31" or "render mode on (by umtool) — a chain, since 13:31, until 15:31".
+ * @param {RenderPriorityState} state
+ */
+export function describeRenderPriority(state) {
+ const h = state.holder;
+ const what = h?.cmd
+ ? String(h.cmd).slice(0, 100)
+ : h?.project
+ ? `umtool take ${h.project}${h.take ? ` --id ${h.take}` : ""}`
+ : h
+ ? `pid ${h.pid}`
+ : `render mode on${state.by ? ` (by ${state.by})` : ""}`;
+ const note = state.note ? ` — ${state.note}` : "";
+ const until = state.until ? `, until ${clockOf(state.until)}` : "";
+ return `${what}${note}, since ${clockOf(state.since)}${until}`;
+}
+
+// ------------------------------------------------------------ on and off
+
+/**
+ * "90m", "2h", "1h30m", "45s", or a number of minutes -> ms; null when it is
+ * none of those.
+ * @param {unknown} v
+ */
+export function parseDurationMs(v) {
+ if (typeof v === "number") return Number.isFinite(v) && v > 0 ? Math.round(v * 60_000) : null;
+ const s = String(v ?? "").trim().toLowerCase();
+ if (/^\d+(\.\d+)?$/.test(s)) return parseDurationMs(Number(s));
+ const m = /^(?:(\d+(?:\.\d+)?)h)?(?:(\d+(?:\.\d+)?)m)?(?:(\d+(?:\.\d+)?)s)?$/.exec(s);
+ if (!s || !m || (!m[1] && !m[2] && !m[3])) return null;
+ const ms = (Number(m[1] ?? 0) * 3600 + Number(m[2] ?? 0) * 60 + Number(m[3] ?? 0)) * 1000;
+ return ms > 0 ? Math.round(ms) : null;
+}
+
+/**
+ * Release each of `lanes` through the editor; the ones that would not be.
+ * @param {string[]} names
+ * @param {RenderModeLanes | null} lanes
+ */
+async function releaseLanes(names, lanes) {
+ const released = [];
+ const failed = [];
+ for (const lane of names ?? []) {
+ if (!lanes) {
+ failed.push({ lane, error: "no editor to release it through" });
+ continue;
+ }
+ try {
+ await lanes.release(lane);
+ released.push(lane);
+ } catch (err) {
+ failed.push({ lane, error: err instanceof Error ? err.message : String(err) });
+ }
+ }
+ return { released, failed };
+}
+
+/**
+ * Turn render mode on. `holder` is the render's process (`umtool take
+ * --priority`: the hold ends with it); null is a manual window, which ends at
+ * `forMs` (default 2 h). A hold already on is NOT taken over: `{ok: false,
+ * held}`. A stale one is ended first (its lanes released). Then each of
+ * RENDER_MODE_LANES the editor does not already hold is held, and recorded as
+ * ours — the record is written after each, so a crash never forgets one.
+ *
+ * @param {{ file: string, holder?: RenderHolder | null, forMs?: number | null, note?: string | null,
+ * by?: string | null, editor?: string | null, lanes?: RenderModeLanes | null, now?: () => number,
+ * isAlive?: (h: RenderHolder) => boolean, token?: string }} o
+ */
+export async function renderModeOn({
+ file,
+ holder = null,
+ forMs = null,
+ note = null,
+ by = null,
+ editor = null,
+ lanes = null,
+ now = Date.now,
+ isAlive = holderAlive,
+ token = randomBytes(8).toString("hex"),
+}) {
+ let reaped = null;
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ const cur = readRenderPriority(file, { now: now(), isAlive });
+ if (cur.held && cur.state) return { ok: false, held: cur.state, reaped };
+ // A stale hold is ended first. A lane it could not release (no editor
+ // answering) is still render mode's: this hold inherits it, to release at
+ // its own end, rather than leave a record nothing will ever clear.
+ let inherited = [];
+ if (cur.state) {
+ reaped = await renderModeOff({ file, token: cur.state.token, lanes });
+ inherited = reaped.failed.map((f) => f.lane);
+ if (inherited.length) removeIfToken(file, cur.state.token);
+ }
+ const t = now();
+ const ms = forMs ?? (holder ? null : DEFAULT_RENDER_MODE_WINDOW_MS);
+ /** @type {RenderPriorityState} */
+ const state = {
+ version: 1,
+ token,
+ since: new Date(t).toISOString(),
+ until: ms ? new Date(t + ms).toISOString() : null,
+ by,
+ note: note ? String(note).slice(0, 200) : null,
+ holder: holder ? { pidStart: pidStartTime(holder.pid), ...holder } : null,
+ lanesHeld: [...inherited],
+ lanesSkipped: [],
+ editor,
+ };
+ if (!createState(file, state)) continue; // another `on` won the race: look again
+ const failed = [];
+ for (const lane of lanes ? RENDER_MODE_LANES : []) {
+ if (state.lanesHeld.includes(lane)) continue; // inherited: ours already
+ try {
+ if (await /** @type {RenderModeLanes} */ (lanes).isHeld(lane)) {
+ state.lanesSkipped?.push(lane); // someone else's hold: never ours to release
+ } else {
+ await /** @type {RenderModeLanes} */ (lanes).hold(lane);
+ state.lanesHeld.push(lane);
+ }
+ } catch (err) {
+ failed.push(`${lane}: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ writeState(file, state);
+ }
+ if (!lanes) state.lanesError = "no editor: the lanes were not held";
+ else if (failed.length) state.lanesError = failed.join("; ");
+ writeState(file, state);
+ return { ok: true, state, reaped };
+ }
+ const cur = readRenderPriority(file, { now: now(), isAlive });
+ return { ok: false, held: cur.state, reaped };
+}
+
+/**
+ * Turn render mode off: release the lanes IT held (only those), then remove
+ * the file. `token` names the hold being ended — a different one is left alone
+ * (`{ok: false, notOurs}`) unless `force`. A lane the editor would not release
+ * keeps the record, ended (`until` now, no holder): not a hold any more, and
+ * the next reaper with an editor releases it.
+ *
+ * @param {{ file: string, token?: string | null, lanes?: RenderModeLanes | null, force?: boolean, now?: () => number }} o
+ */
+export async function renderModeOff({ file, token = null, lanes = null, force = false, now = Date.now }) {
+ const state = readRenderPriorityState(file);
+ if (!state) return { ok: true, was: null, released: [], failed: [] };
+ if (token && state.token !== token && !force) return { ok: false, notOurs: state, released: [], failed: [] };
+ const { released, failed } = await releaseLanes(state.lanesHeld, lanes);
+ if (failed.length) {
+ const cur = readRenderPriorityState(file);
+ if (!cur || cur.token === state.token) {
+ writeState(file, {
+ ...state,
+ holder: null,
+ until: new Date(now()).toISOString(),
+ ended: true,
+ lanesHeld: failed.map((f) => f.lane),
+ lanesError: failed.map((f) => `${f.lane}: ${f.error}`).join("; "),
+ });
+ }
+ } else {
+ removeIfToken(file, state.token);
+ }
+ return { ok: true, was: state, released, failed };
+}
+
+/**
+ * End a hold that is no longer one (its holder gone, its window over): its
+ * lanes released, its file removed. Null when there is nothing stale. Called
+ * by whoever has an editor to release through. `owns(state)`, when given, says
+ * whether the lanes it records are that editor's (its `editor`): another
+ * editor's stale hold is left for that one.
+ * @param {{ file: string, lanes: RenderModeLanes | null, now?: () => number, isAlive?: (h: RenderHolder) => boolean, owns?: (s: RenderPriorityState) => boolean }} o
+ */
+export async function reapRenderMode({ file, lanes, now = Date.now, isAlive = holderAlive, owns }) {
+ const s = readRenderPriority(file, { now: now(), isAlive });
+ if (!s.state || s.held) return null;
+ if (owns && s.state.lanesHeld?.length && !owns(s.state)) return null;
+ return renderModeOff({ file, token: s.state.token, lanes, now });
+}
+
+/**
+ * Whether an `editor` a hold records (the URL its lanes were held through) is
+ * the editor listening on `port` here: a loopback host and that port.
+ * @param {string | null | undefined} editor
+ * @param {string | number} port
+ */
+export function isLocalEditor(editor, port) {
+ try {
+ const u = new URL(String(editor ?? ""));
+ const host = u.hostname.replace(/^\[|\]$/g, "");
+ const p = u.port || (u.protocol === "https:" ? "443" : "80");
+ return ["localhost", "127.0.0.1", "::1", "0.0.0.0"].includes(host) && p === String(port);
+ } catch {
+ return false;
+ }
+}
diff --git a/common/lib/renderPriority.test.ts b/common/lib/renderPriority.test.ts
@@ -0,0 +1,240 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import {
+ DEFAULT_RENDER_MODE_WINDOW_MS,
+ RENDER_PRIORITY_TOKEN_ENV,
+ applyRenderPriorityDefaults,
+ carriesRenderPriority,
+ describeRenderPriority,
+ holderAlive,
+ isLocalEditor,
+ parseDurationMs,
+ readRenderPriority,
+ readRenderPriorityState,
+ reapRenderMode,
+ renderModeOff,
+ renderModeOn,
+ renderPriorityBlocks,
+ renderPriorityFile,
+ renderPriorityStatus,
+ type RenderModeLanes,
+ type RenderPriorityState,
+} from "./renderPriority.mjs";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common test
+//
+// Render mode's state file and its lanes, all against temp files and a fake
+// editor — nothing here touches the machine's state or a live editor's lanes.
+
+function tmpFile() {
+ return path.join(mkdtempSync(path.join(os.tmpdir(), "render-priority-")), "heavy.lock.render.json");
+}
+
+/** A fake editor's lanes: `held` is what it holds; `calls` what was asked. */
+function fakeLanes(held: Record<string, boolean> = {}, { failRelease = false } = {}) {
+ const calls: string[] = [];
+ const lanes: RenderModeLanes = {
+ async isHeld(lane) {
+ return held[lane] === true;
+ },
+ async hold(lane) {
+ calls.push(`hold ${lane}`);
+ held[lane] = true;
+ },
+ async release(lane) {
+ calls.push(`release ${lane}`);
+ if (failRelease) throw new Error("editor gone");
+ held[lane] = false;
+ },
+ };
+ return { lanes, held, calls };
+}
+
+function state(over: Partial<RenderPriorityState> = {}): RenderPriorityState {
+ return {
+ version: 1,
+ token: "tok",
+ since: new Date(0).toISOString(),
+ until: null,
+ by: null,
+ note: null,
+ holder: null,
+ lanesHeld: [],
+ ...over,
+ };
+}
+
+test("renderPriorityFile: RENDER_PRIORITY_FILE, else beside the heavy slot's lock", () => {
+ assert.equal(renderPriorityFile({ RENDER_PRIORITY_FILE: "/x/state.json", HEAVY_LOCK_FILE: "/y/heavy.lock" }), "/x/state.json");
+ assert.equal(renderPriorityFile({ HEAVY_LOCK_FILE: "/y/heavy.lock" }), "/y/heavy.lock.render.json");
+ assert.equal(renderPriorityFile({}, { heavyLock: "/z/heavy-queue.lock" }), "/z/heavy-queue.lock.render.json");
+ // A git checkout: its common dir, the heavy lock's own place.
+ assert.match(renderPriorityFile({}, { root: process.cwd() }), /heavy-queue\.lock\.render\.json$/);
+});
+
+test("liveness: a gone holder, a past until, or no end at all is not a hold", () => {
+ const now = Date.parse("2026-10-30T12:00:00Z");
+ const alive = () => true;
+ const dead = () => false;
+ assert.deepEqual(renderPriorityStatus(null), { held: false, state: null, stale: null });
+ const take = state({ holder: { pid: 123 } });
+ assert.equal(renderPriorityStatus(take, { now, isAlive: alive }).held, true);
+ assert.equal(renderPriorityStatus(take, { now, isAlive: dead }).stale, "holder-gone");
+ const window = state({ until: "2026-10-30T13:00:00Z" });
+ assert.equal(renderPriorityStatus(window, { now, isAlive: dead }).held, true);
+ assert.equal(renderPriorityStatus(window, { now: Date.parse("2026-10-30T13:00:01Z") }).stale, "expired");
+ // A take's hold with an until past it is over too, holder or not.
+ assert.equal(renderPriorityStatus(state({ holder: { pid: 1 }, until: "2026-10-30T11:00:00Z" }), { now, isAlive: alive }).stale, "expired");
+ assert.equal(renderPriorityStatus(state(), { now }).stale, "no-end");
+});
+
+test("holderAlive: this process is; a dead pid, or a live pid that started at another time, is not", async () => {
+ assert.equal(holderAlive({ pid: process.pid }), true);
+ assert.equal(holderAlive({ pid: process.pid, pidStart: "not-its-start" }), os.platform() !== "linux");
+ const child = spawn(process.execPath, ["-e", ""]);
+ const pid = child.pid as number;
+ await new Promise((r) => child.on("exit", r));
+ assert.equal(holderAlive({ pid }), false);
+});
+
+test("the gate's question: held, the token not carried, no bypass", () => {
+ const held = { held: true, state: state(), stale: null } as const;
+ assert.equal(renderPriorityBlocks(held, {}), true);
+ assert.equal(renderPriorityBlocks(held, { [RENDER_PRIORITY_TOKEN_ENV]: "tok" }), false);
+ assert.equal(renderPriorityBlocks(held, { [RENDER_PRIORITY_TOKEN_ENV]: "other" }), true);
+ assert.equal(renderPriorityBlocks(held, { RENDER_PRIORITY: "0" }), false);
+ assert.equal(renderPriorityBlocks(held, {}, { urgent: true }), false);
+ assert.equal(renderPriorityBlocks({ held: false, state: state(), stale: "expired" }, {}), false);
+ assert.equal(carriesRenderPriority(held, { [RENDER_PRIORITY_TOKEN_ENV]: "tok" }), true);
+ assert.equal(carriesRenderPriority(held, {}), false);
+});
+
+test("the render's own defaults fill only what the environment leaves unset", () => {
+ const env: Record<string, string | undefined> = { HEAVY_CAP_MB: "9000" };
+ assert.deepEqual(applyRenderPriorityDefaults(env), ["HEAVY_MIN_FREE_MB"]);
+ assert.equal(env.HEAVY_MIN_FREE_MB, "4000");
+ assert.equal(env.HEAVY_CAP_MB, "9000");
+ const bare: Record<string, string | undefined> = {};
+ applyRenderPriorityDefaults(bare);
+ assert.deepEqual(bare, { HEAVY_MIN_FREE_MB: "4000", HEAVY_CAP_MB: "10240" });
+});
+
+test("describeRenderPriority and parseDurationMs", () => {
+ assert.match(describeRenderPriority(state({ holder: { pid: 1, cmd: "umtool take ember --id t1" } })), /^umtool take ember --id t1, since \d\d:\d\d$/);
+ assert.match(describeRenderPriority(state({ by: "umtool render-mode", note: "a chain", until: new Date(0).toISOString() })), /^render mode on \(by umtool render-mode\) — a chain, since \d\d:\d\d, until \d\d:\d\d$/);
+ assert.equal(parseDurationMs("90m"), 90 * 60_000);
+ assert.equal(parseDurationMs("2h"), 2 * 3_600_000);
+ assert.equal(parseDurationMs("1h30m"), 90 * 60_000);
+ assert.equal(parseDurationMs("45"), 45 * 60_000);
+ assert.equal(parseDurationMs(10), 10 * 60_000);
+ assert.equal(parseDurationMs("soon"), null);
+ assert.equal(parseDurationMs("0m"), null);
+ assert.equal(parseDurationMs(""), null);
+});
+
+test("on holds only the lanes not held already, and off releases only those", async () => {
+ const file = tmpFile();
+ const ed = fakeLanes({ download: true }); // someone else's hold
+ const on = await renderModeOn({ file, holder: { pid: process.pid, cmd: "umtool take p --id t", project: "p", take: "t" }, lanes: ed.lanes, editor: "http://localhost:3001" });
+ assert.equal(on.ok, true);
+ assert.deepEqual(on.state?.lanesHeld, ["transcription"]);
+ assert.deepEqual(on.state?.lanesSkipped, ["download"]);
+ assert.equal(on.state?.until, null); // a take's hold ends with its process
+ assert.deepEqual(ed.calls, ["hold transcription"]);
+ const onDisk = readRenderPriorityState(file);
+ assert.equal(onDisk?.token, on.state?.token);
+ assert.equal(readRenderPriority(file).held, true);
+
+ // A second `on` does not take it over.
+ const again = await renderModeOn({ file, lanes: ed.lanes });
+ assert.equal(again.ok, false);
+ assert.equal(again.held?.token, on.state?.token);
+
+ // Another hold's token is not ours to end.
+ const notOurs = await renderModeOff({ file, token: "someone-else", lanes: ed.lanes });
+ assert.equal(notOurs.ok, false);
+ assert.equal(existsSync(file), true);
+
+ const off = await renderModeOff({ file, token: on.state?.token, lanes: ed.lanes });
+ assert.deepEqual(off.released, ["transcription"]);
+ assert.deepEqual(ed.calls, ["hold transcription", "release transcription"]);
+ assert.equal(ed.held.download, true, "the hold it found stays");
+ assert.equal(existsSync(file), false);
+});
+
+test("a manual window has an until (2 h by default, or --for); with no editor it still holds the door", async () => {
+ const file = tmpFile();
+ const t0 = Date.parse("2026-10-30T13:31:00Z");
+ const on = await renderModeOn({ file, now: () => t0, note: "a chain" });
+ assert.equal(on.ok, true);
+ assert.equal(Date.parse(on.state!.until!) - t0, DEFAULT_RENDER_MODE_WINDOW_MS);
+ assert.deepEqual(on.state!.lanesHeld, []);
+ assert.match(on.state!.lanesError ?? "", /no editor/);
+ assert.equal(readRenderPriority(file, { now: t0 + 60_000 }).held, true);
+ assert.equal(readRenderPriority(file, { now: t0 + DEFAULT_RENDER_MODE_WINDOW_MS + 1 }).held, false);
+ await renderModeOff({ file });
+ const sized = await renderModeOn({ file, now: () => t0, forMs: 90 * 60_000 });
+ assert.equal(Date.parse(sized.state!.until!) - t0, 90 * 60_000);
+});
+
+test("a stale hold (its render killed) is reaped: its lanes released, its file gone; a live one is left", async () => {
+ const file = tmpFile();
+ const ed = fakeLanes();
+ writeFileSync(file, JSON.stringify(state({ holder: { pid: 999_999_999 }, lanesHeld: ["transcription", "download"], editor: "http://localhost:3001" })));
+ assert.equal(readRenderPriority(file).stale, "holder-gone");
+ // Another editor's stale hold is left for that editor.
+ assert.equal(await reapRenderMode({ file, lanes: ed.lanes, owns: (s) => isLocalEditor(s.editor, 3101) }), null);
+ assert.deepEqual(ed.calls, []);
+ const r = await reapRenderMode({ file, lanes: ed.lanes, owns: (s) => isLocalEditor(s.editor, 3001) });
+ assert.deepEqual(r?.released, ["transcription", "download"]);
+ assert.equal(existsSync(file), false);
+
+ await renderModeOn({ file, holder: { pid: process.pid }, lanes: ed.lanes });
+ assert.equal(await reapRenderMode({ file, lanes: ed.lanes }), null);
+ assert.equal(existsSync(file), true);
+});
+
+test("a lane the editor would not release stays recorded, ended — and the next hold inherits it", async () => {
+ const file = tmpFile();
+ const broken = fakeLanes({}, { failRelease: true });
+ const on = await renderModeOn({ file, holder: { pid: process.pid }, lanes: broken.lanes });
+ const off = await renderModeOff({ file, token: on.state!.token, lanes: broken.lanes });
+ assert.equal(off.failed.length, 2);
+ const ended = readRenderPriorityState(file)!;
+ assert.equal(ended.ended, true);
+ assert.deepEqual(ended.lanesHeld, ["transcription", "download"]);
+ assert.equal(readRenderPriority(file).held, false, "not a hold any more: the gate ignores it");
+
+ // Still no editor: the next `on` takes the lanes over rather than strand them.
+ const next = await renderModeOn({ file, holder: { pid: process.pid }, lanes: broken.lanes });
+ assert.equal(next.ok, true);
+ assert.deepEqual(next.state!.lanesHeld, ["transcription", "download"]);
+ // The editor is back: the next off releases them.
+ const fixed = fakeLanes({ transcription: true, download: true });
+ const done = await renderModeOff({ file, token: next.state!.token, lanes: fixed.lanes });
+ assert.deepEqual(done.released, ["transcription", "download"]);
+ assert.equal(existsSync(file), false);
+});
+
+test("isLocalEditor: a loopback host on that port", () => {
+ assert.equal(isLocalEditor("http://localhost:3001", 3001), true);
+ assert.equal(isLocalEditor("http://127.0.0.1:3001/", "3001"), true);
+ assert.equal(isLocalEditor("http://localhost:3101", 3001), false);
+ assert.equal(isLocalEditor("https://editor.example:3001", 3001), false);
+ assert.equal(isLocalEditor(null, 3001), false);
+});
+
+test("two `on`s at once: one wins, the other is told", async () => {
+ const file = tmpFile();
+ const [a, b] = await Promise.all([
+ renderModeOn({ file, holder: { pid: process.pid } }),
+ renderModeOn({ file, holder: { pid: process.pid } }),
+ ]);
+ assert.equal([a.ok, b.ok].filter(Boolean).length, 1);
+ assert.equal(JSON.parse(readFileSync(file, "utf8")).token, (a.ok ? a : b).state!.token);
+});
diff --git a/common/package.json b/common/package.json
@@ -48,6 +48,7 @@
"./lib/montage/phraseSource.mjs": "./lib/montage/phraseSource.mjs",
"./lib/montage/voiceMatch.mjs": "./lib/montage/voiceMatch.mjs",
"./lib/ports.mjs": "./lib/ports.mjs",
+ "./lib/renderPriority.mjs": "./lib/renderPriority.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/editor/app/api/ops/_renderMode.test.ts b/editor/app/api/ops/_renderMode.test.ts
@@ -0,0 +1,87 @@
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_renderMode.test.ts"
+//
+// `pnpm ops render-mode` / `get render-mode` against the route handlers, over a
+// temp corpus and a temp state file (RENDER_PRIORITY_FILE) — never the
+// machine's render mode, never the live editor's lanes.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { callGet, callPost, setupOpsCorpus } from "./_testCorpus";
+
+const corpus = await setupOpsCorpus(null);
+const STATE = path.join(corpus.root, "render-priority.json");
+process.env.RENDER_PRIORITY_FILE = STATE;
+const { GET, POST } = await import("./render-mode/route");
+const { getSettings } = await import("yt-dlp-transcript-common/lib/settings");
+const { getWorkerPool } = await import("yt-dlp-transcript-common/jobs/workerPool");
+const { renderModeReapTick } = await import("../../operations/renderMode");
+test.after(() => corpus.cleanup());
+
+const held = (lane: "transcription" | "download") => getSettings().autoQueue[lane].held === true;
+
+test("on holds the lanes not already held (and says so), off releases only those", async () => {
+ await corpus.writeSettings({ minFreeDiskGB: 0, autoQueue: { ...getSettings().autoQueue, download: { ...getSettings().autoQueue.download, held: true } } });
+ assert.equal(held("download"), true);
+ assert.equal(held("transcription"), false);
+
+ const on = await callPost(POST!, { on: true, for: "90m", note: "the Ember cut" });
+ assert.equal(on.status, 200, JSON.stringify(on.body));
+ const state = on.body.state as { token: string; lanesHeld: string[]; lanesSkipped: string[]; until: string; editor: string };
+ assert.deepEqual(state.lanesHeld, ["transcription"]);
+ assert.deepEqual(state.lanesSkipped, ["download"]);
+ assert.match(String(on.body.join), /^RENDER_PRIORITY_TOKEN=[0-9a-f]{16}$/);
+ assert.match(state.editor, /^http:\/\/localhost:\d+$/);
+ assert.equal(held("transcription"), true);
+ assert.equal(getWorkerPool().isPaused(), true, "the transcription pool's live hold too");
+ assert.equal(JSON.parse(readFileSync(STATE, "utf8")).token, state.token);
+
+ const again = await callPost(POST!, { on: true });
+ assert.equal(again.status, 409);
+ assert.match(String(again.body.error), /already on: render mode on \(by pnpm ops render-mode\) — the Ember cut/);
+
+ const got = await callGet(GET!, "http://localhost/api/ops/render-mode");
+ assert.equal(got.status, 200);
+ assert.equal(got.body.held, true);
+ assert.equal(got.body.token, undefined, "the read side carries no token");
+ assert.deepEqual(got.body.lanesHeld, ["transcription"]);
+
+ const off = await callPost(POST!, { on: false });
+ assert.equal(off.status, 200, JSON.stringify(off.body));
+ assert.deepEqual(off.body.released, ["transcription"]);
+ assert.equal(held("transcription"), false);
+ assert.equal(getWorkerPool().isPaused(), false);
+ assert.equal(held("download"), true, "someone else's hold stays");
+ assert.equal(existsSync(STATE), false);
+});
+
+test("a running take's hold is not ended without force; bad bodies are 400s", async () => {
+ writeFileSync(STATE, JSON.stringify({ version: 1, token: "take", since: new Date().toISOString(), until: null, holder: { pid: process.pid, cmd: "umtool take p --id t" }, lanesHeld: [] }));
+ const off = await callPost(POST!, { on: false });
+ assert.equal(off.status, 409);
+ assert.match(String(off.body.error), /held by a running render \(umtool take p --id t/);
+ assert.equal((await callPost(POST!, { on: false, force: true })).status, 200);
+ assert.equal(existsSync(STATE), false);
+ assert.equal((await callPost(POST!, {})).status, 400);
+ assert.equal((await callPost(POST!, { on: true, for: "soon" })).status, 400);
+ assert.equal((await callPost(POST!, { on: false, note: "x" })).status, 400);
+ assert.equal((await callPost(POST!, { on: true, lanes: ["x"] })).status, 400);
+});
+
+test("the heartbeat ends a stale hold this editor made: its lanes released; another editor's is left", async () => {
+ const port = process.env.EDITOR_PORT || process.env.PORT || "3001";
+ await callPost(POST!, { on: true });
+ assert.equal(held("transcription"), true);
+ // Its window over (a killed session's): stale.
+ const s = JSON.parse(readFileSync(STATE, "utf8"));
+ writeFileSync(STATE, JSON.stringify({ ...s, until: new Date(Date.now() - 1000).toISOString() }));
+ await renderModeReapTick();
+ assert.equal(held("transcription"), false);
+ assert.equal(existsSync(STATE), false);
+
+ // Another worktree's editor's stale hold: not this one's lanes to release.
+ writeFileSync(STATE, JSON.stringify({ ...s, until: new Date(Date.now() - 1000).toISOString(), editor: `http://localhost:${Number(port) + 100}`, lanesHeld: ["download"] }));
+ await renderModeReapTick();
+ assert.equal(existsSync(STATE), true);
+});
diff --git a/editor/app/api/ops/render-mode/route.ts b/editor/app/api/ops/render-mode/route.ts
@@ -0,0 +1,85 @@
+import { NextResponse } from "next/server";
+import {
+ RENDER_MODE_REMINDER,
+ RENDER_PRIORITY_TOKEN_ENV,
+ describeRenderPriority,
+ parseDurationMs,
+ type RenderPriorityState,
+} from "yt-dlp-transcript-common/lib/renderPriority.mjs";
+import { renderModeNow, renderModeOffHere, renderModeOnHere } from "../../../operations/renderMode";
+import { OpsInputError, ops, opsFail, optBool, optString } from "../_lib";
+import { readRoute } from "../_read";
+
+export const dynamic = "force-dynamic";
+
+// RENDER MODE (common/lib/renderPriority.mjs; AGENTS.md "Render mode"): a
+// render the operator is waiting for gets the machine — every other heavy job
+// waits at the heavy slot's door, and this editor's transcription and download
+// lanes are held (only the ones not held already; only those are released).
+// The same switch as `umtool render-mode`, for a session that has only `pnpm ops`.
+//
+// GET /api/ops/render-mode
+// -> { ok, held, what?, since, until, holder, lanesHeld, lanesSkipped,
+// lanesError, note, stale, reaped? } (no token)
+// POST { on: true, for?: "90m" | <minutes>, note? }
+// -> { ok, state: {…, token}, reminder, join } a window (default 2 h);
+// a hold already on is a 409 naming it
+// POST { on: false, force? }
+// -> { ok, was, released, failed } a running take's hold only with force
+
+function view(state: RenderPriorityState | null) {
+ if (!state) return null;
+ const rest: Partial<RenderPriorityState> = { ...state };
+ delete rest.token;
+ return { ...rest, what: describeRenderPriority(state) };
+}
+
+export async function GET(request: Request) {
+ return readRoute(request, [], async () => {
+ const now = await renderModeNow();
+ return {
+ held: now.held,
+ ...(view(now.held ? now.state : null) ?? {}),
+ stale: now.stale,
+ last: now.held ? null : view(now.state),
+ reaped: now.reaped ? { released: now.reaped.released, failed: now.reaped.failed } : null,
+ reminder: RENDER_MODE_REMINDER,
+ };
+ });
+}
+
+export async function POST(request: Request) {
+ return ops(request, ["on", "for", "note", "force"], async (body) => {
+ const on = optBool(body, "on");
+ if (on === undefined) throw new OpsInputError('"on" is required: true or false');
+ if (on) {
+ if (body.force !== undefined) throw new OpsInputError('"force" is for {"on": false}');
+ let forMs: number | null = null;
+ if (body.for !== undefined) {
+ forMs = parseDurationMs(body.for);
+ if (!forMs) throw new OpsInputError('"for" is a duration: "90m", "2h", "1h30m", or a number of minutes');
+ }
+ const r = await renderModeOnHere({ forMs, note: optString(body, "note") ?? null, by: "pnpm ops render-mode" });
+ if (!r.ok || !r.state) {
+ return opsFail(`render mode is already on: ${r.held ? describeRenderPriority(r.held) : "?"}`, 409, { held: view(r.held ?? null) });
+ }
+ return NextResponse.json({
+ ok: true,
+ state: r.state,
+ reminder: RENDER_MODE_REMINDER,
+ join: `${RENDER_PRIORITY_TOKEN_ENV}=${r.state.token}`,
+ });
+ }
+ if (body.for !== undefined || body.note !== undefined) throw new OpsInputError('"for" and "note" are for {"on": true}');
+ const force = optBool(body, "force") === true;
+ const now = await renderModeNow();
+ if (now.held && now.state?.holder && !force) {
+ return opsFail(
+ `render mode is held by a running render (${describeRenderPriority(now.state)}) — it ends with it; "force": true ends it now`,
+ 409,
+ );
+ }
+ const r = await renderModeOffHere();
+ return NextResponse.json({ ok: true, was: view(r.was ?? null), released: r.released, failed: r.failed });
+ });
+}
diff --git a/editor/app/jobs/actions.ts b/editor/app/jobs/actions.ts
@@ -316,3 +316,19 @@ export async function clearFinishedLogsAction(
revalidatePath("/jobs");
return { deleted };
}
+
+// The /jobs render-mode banner's End button: a manual window ended, its lanes
+// released (operations/renderMode.ts). A running render's hold ends with the
+// render, so the banner offers no button for it.
+export async function endRenderModeAction(): Promise<{ ok: boolean; error?: string }> {
+ const { renderModeNow, renderModeOffHere } = await import("../operations/renderMode");
+ const now = await renderModeNow();
+ if (now.held && now.state?.holder) {
+ return { ok: false, error: "a running render holds it — it ends with the render" };
+ }
+ const r = await renderModeOffHere();
+ revalidatePath("/jobs");
+ return r.failed.length
+ ? { ok: false, error: `not released: ${r.failed.map((f) => `${f.lane} (${f.error})`).join(", ")}` }
+ : { ok: true };
+}
diff --git a/editor/app/jobs/components/EndRenderModeButton.tsx b/editor/app/jobs/components/EndRenderModeButton.tsx
@@ -0,0 +1,38 @@
+"use client";
+
+import { useState } from "react";
+import { useRouter } from "next/navigation";
+import { endRenderModeAction } from "../actions";
+
+// Ends a manual render-mode window (`umtool render-mode on`, `pnpm ops
+// render-mode`) before its time: the lanes it held are released.
+export function EndRenderModeButton({ until }: { until: string | null }) {
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const router = useRouter();
+ return (
+ <span className="flex items-center gap-2">
+ {until && <span className="text-xs text-muted-foreground">until {until}</span>}
+ <button
+ type="button"
+ data-action="end-render-mode"
+ disabled={busy}
+ onClick={async () => {
+ setBusy(true);
+ setError(null);
+ try {
+ const r = await endRenderModeAction();
+ if (!r.ok) setError(r.error ?? "could not end it");
+ router.refresh();
+ } finally {
+ setBusy(false);
+ }
+ }}
+ className="px-2 py-1 rounded-md border border-warning/30 text-xs font-medium text-warning hover:bg-warning-soft disabled:opacity-50"
+ >
+ {busy ? "Ending…" : "End render mode"}
+ </button>
+ {error && <span className="text-xs text-destructive">{error}</span>}
+ </span>
+ );
+}
diff --git a/editor/app/jobs/components/RenderModeBanner.tsx b/editor/app/jobs/components/RenderModeBanner.tsx
@@ -0,0 +1,39 @@
+import {
+ RENDER_MODE_REMINDER,
+ clockOf,
+ describeRenderPriority,
+ readRenderPriority,
+} from "yt-dlp-transcript-common/lib/renderPriority.mjs";
+import { renderModeFile } from "../../operations/renderMode";
+import { EndRenderModeButton } from "./EndRenderModeButton";
+
+// RENDER MODE on /jobs (common/lib/renderPriority.mjs; AGENTS.md "Render
+// mode"): while a render the operator waits for holds the machine, say so —
+// which lanes it holds and for what — since the lanes' quiet and every heavy
+// job waiting at the door would otherwise look like a stall. Read only: the
+// heartbeat ends a hold whose render is gone.
+export function RenderModeBanner() {
+ const s = readRenderPriority(renderModeFile());
+ if (!s.held || !s.state) return null;
+ const st = s.state;
+ const lanes = st.lanesHeld.length ? `${st.lanesHeld.join(" and ")} lane${st.lanesHeld.length > 1 ? "s" : ""} held` : "Heavy jobs held";
+ return (
+ <div
+ data-render-mode-banner=""
+ role="status"
+ className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-warning/30 bg-warning-soft px-3 py-2 text-sm"
+ >
+ <span>
+ <strong>Render mode:</strong> {lanes} for {describeRenderPriority(st)}.
+ {st.lanesSkipped?.length ? ` ${st.lanesSkipped.join(", ")} already held — left alone.` : ""}
+ {st.lanesError ? ` (${st.lanesError})` : ""} Other heavy jobs (e2e, builds) wait for it;{" "}
+ {RENDER_MODE_REMINDER}.
+ </span>
+ {st.holder ? (
+ <span className="text-xs text-muted-foreground">ends with the render</span>
+ ) : (
+ <EndRenderModeButton until={st.until ? clockOf(st.until) : null} />
+ )}
+ </div>
+ );
+}
diff --git a/editor/app/jobs/page.tsx b/editor/app/jobs/page.tsx
@@ -11,6 +11,7 @@ import {
import { ClearLogsMenu } from "./components/ClearLogsMenu";
import { DrainAllButton } from "./components/DrainAllButton";
import { JobsTable } from "./components/JobsTable";
+import { RenderModeBanner } from "./components/RenderModeBanner";
import { RetryAllFailedButton } from "./components/RetryAllFailedButton";
import { PauseLaneButton } from "../components/lanes/pauseControl";
@@ -63,6 +64,7 @@ export default async function JobsPage({
<DrainAllButton />
</div>
</div>
+ <RenderModeBanner />
<JobsTable initial={initial} history={rows} total={total} />
{hasMore && (
<div className="flex items-center justify-center gap-3 text-sm">
diff --git a/editor/app/operations/renderMode.ts b/editor/app/operations/renderMode.ts
@@ -0,0 +1,105 @@
+import { revalidatePath } from "next/cache";
+import { getWorkerPool } from "yt-dlp-transcript-common/jobs/workerPool";
+import { isGateHeld, withGateHeld } from "yt-dlp-transcript-common/lib/pauseGates";
+import {
+ isLocalEditor,
+ readRenderPriority,
+ reapRenderMode,
+ renderModeOff,
+ renderModeOn,
+ renderPriorityFile,
+ type RenderModeLanes,
+ type RenderPriorityState,
+} from "yt-dlp-transcript-common/lib/renderPriority.mjs";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { saveSettings } from "../settings/saveSettings";
+
+// RENDER MODE, the editor's side (common/lib/renderPriority.mjs; AGENTS.md
+// "Render mode"). `pnpm ops render-mode` turns it on and off here, /jobs shows
+// it, and the heartbeat ends a hold that is no longer one — the render's
+// process gone, its window over — by releasing the lanes IT held.
+//
+// The lanes are held in-process, the way the lane buttons hold them
+// (operations/actions.ts setLaneHeld): the transcription pool first (its live
+// hold), then the stored gate. Not through that server action itself: the
+// heartbeat is no request, and its revalidatePath has none to revalidate.
+//
+// The state file is the one queue-lock reads: beside the heavy slot's lock in
+// this checkout's git common dir (the editor runs from editor/), or
+// RENDER_PRIORITY_FILE — the e2e servers set their own.
+
+type RenderLane = "transcription" | "download";
+
+export function renderModeFile(): string {
+ return renderPriorityFile(process.env, { root: process.cwd() });
+}
+
+// WHICH EDITOR'S LANES. A hold records the editor its lanes were held through:
+// umtool its ARCHILYZER_EDITOR_URL, this editor its own loopback URL. Another
+// worktree's dev editor shares the state file (one common dir for every
+// worktree) but not the lanes, so it reaps only a hold that names its own
+// port — never the live editor's. A hold made through a URL that is not a
+// loopback one is reaped by `umtool render-mode status|on`, not by a heartbeat.
+const ownPort = () => process.env.EDITOR_PORT || process.env.PORT || "3001";
+const selfUrl = () => `http://localhost:${ownPort()}`;
+const owns = (s: RenderPriorityState) => isLocalEditor(s.editor, ownPort());
+
+async function setHeld(lane: RenderLane, held: boolean): Promise<void> {
+ if (lane === "transcription") {
+ if (held) getWorkerPool().pauseAll();
+ else getWorkerPool().resumeAll();
+ }
+ const cur = getSettings();
+ if (isGateHeld(cur, lane) !== held) {
+ await saveSettings({ autoQueue: withGateHeld(cur, lane, held).autoQueue });
+ }
+ try {
+ revalidatePath("/jobs");
+ revalidatePath("/workers");
+ revalidatePath("/operations/[id]", "page");
+ } catch {
+ /* outside a request (the heartbeat): nothing to revalidate */
+ }
+}
+
+/** The editor's own lanes, for renderModeOn / renderModeOff. */
+export function editorRenderLanes(): RenderModeLanes {
+ return {
+ async isHeld(lane) {
+ const l = lane as RenderLane;
+ return isGateHeld(getSettings(), l) || (l === "transcription" && getWorkerPool().isPaused());
+ },
+ hold: (lane) => setHeld(lane as RenderLane, true),
+ release: (lane) => setHeld(lane as RenderLane, false),
+ };
+}
+
+/** Render mode as it stands; a stale hold is ended first (its lanes released). */
+export async function renderModeNow() {
+ const file = renderModeFile();
+ const reaped = await reapRenderMode({ file, lanes: editorRenderLanes(), owns }).catch(() => null);
+ return { ...readRenderPriority(file), reaped: reaped?.was ? reaped : null, file };
+}
+
+/** On, as a manual window: `pnpm ops render-mode {"on": true, "for"?, "note"?}`. */
+export async function renderModeOnHere(o: { forMs: number | null; note: string | null; by: string }) {
+ const file = renderModeFile();
+ return renderModeOn({ file, holder: null, forMs: o.forMs, note: o.note, by: o.by, editor: selfUrl(), lanes: editorRenderLanes() });
+}
+
+/** Off, whoever turned it on (the caller checked a running take's hold). */
+export async function renderModeOffHere() {
+ return renderModeOff({ file: renderModeFile(), lanes: editorRenderLanes() });
+}
+
+/**
+ * The heartbeat's look: a stale hold's lanes released, its file removed. Never
+ * throws. A live hold is left alone.
+ */
+export async function renderModeReapTick(): Promise<void> {
+ try {
+ await reapRenderMode({ file: renderModeFile(), lanes: editorRenderLanes(), owns });
+ } catch {
+ /* the next beat looks again */
+ }
+}
diff --git a/editor/app/scheduler/heartbeat.ts b/editor/app/scheduler/heartbeat.ts
@@ -85,6 +85,15 @@ async function fire(generation: number): Promise<void> {
// the scan records its own outcomes on the runs it reads
}
+ // Render mode whose render is gone (killed, crashed) or whose window is over
+ // is no hold: the lanes it held here are released (operations/renderMode.ts).
+ try {
+ const { renderModeReapTick } = await import("../operations/renderMode");
+ await renderModeReapTick();
+ } catch {
+ // the next beat looks again
+ }
+
// Re-read the cadence each fire so a live settings change is honored without a
// restart. If it has been turned off (0), the loop simply stops here.
if (generation !== state.generation) return;
diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts
@@ -248,6 +248,9 @@ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env)
// every slot, so the e2e server never opens a headless browser on the
// network — the player-page opener refuses under it too.
editorEnv.E2E_ODYSEE_PAGE_FIXTURE = odyseePageFixtureFile(paths.transcriptsDir);
+ // Render mode's state (common/lib/renderPriority.mjs): the slot's own, so
+ // its heartbeat never ends — and its /jobs never shows — the machine's.
+ editorEnv.RENDER_PRIORITY_FILE = join(paths.transcriptsDir, ".render-priority.json");
// A start-mode server runs the stamped build (shared, read-only); a second
// `next dev` needs a dist dir of its own (Next locks `<distDir>/dev/lock`).
if (mode === "start" && !env.CI) editorEnv.E2E_NEXT_DIST_DIR = E2E_DIST_DIR;
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -84,6 +84,9 @@
// pnpm ops channel-priority --json '{"slugs":["x"],"operation":"download","tier":"paused"}'
// pnpm ops channel-priority --json '{"focus":{"kind":"site","siteId":"x"}}'
// pnpm ops lane --json '{"lane":"download","held":true}'
+// pnpm ops render-mode --json '{"on":true,"for":"90m","note":"the Ember cut"}'
+// pnpm ops render-mode --json '{"on":false}'
+// pnpm ops get render-mode
// pnpm ops refresh-report --json '{"all":true}'
// pnpm ops relocate --json '{"slugs":["x"],"locationId":"platter"}'
// pnpm ops relocate --json '{"slugs":["x"],"locationId":"platter","dryRun":true}'
@@ -269,6 +272,9 @@ const GETTERS = {
// The dashboard's cookie refresh alerts: each service whose cookies look
// stale (or are OK again, with the jobs the alert stopped).
services: () => "/api/ops/services",
+ // Render mode (AGENTS.md "Render mode"): whether a render holds the machine,
+ // for what, since when, and which lanes it held. No token.
+ "render-mode": () => "/api/ops/render-mode",
// The X login an X job would use and whether one would start now: the
// source, the exported jar's age, social.x.maxCookieAgeMinutes and the
// network guard's verdict (common/jobs/networkGuard.ts xSessionReport).
@@ -325,6 +331,7 @@ const GET_ARG_OPTIONAL = new Set([
"services",
"x-session",
"generation-usage",
+ "render-mode",
]);
// The flags each noun takes beyond the shared ones; any other is refused.
@@ -461,6 +468,9 @@ const ACTIONS = [
// an evidence pack ({siteId, reportId?, formats?}).
"reports-export",
"lane",
+ // RENDER MODE (AGENTS.md "Render mode"): a render the operator waits for
+ // gets the machine — {on: true, for?, note?} | {on: false, force?}.
+ "render-mode",
// The curated-tag writers. `tags` edits the vocabulary (define/remove);
// `tag-videos` pins, unpins, suppresses or unsuppresses one tag over a batch
// of videos in ONE write.
@@ -1142,6 +1152,19 @@ export function usage() {
' "publish", "enabled"?, "held"?, "action"?: "start"|"stop"|"drain"}, or',
' {"lane": "report-schedule", "held"}: the recurring reports\' gate, its only key.',
"",
+ 'render-mode gives a render the operator is waiting for the machine:',
+ ' {"on": true, "for"?: "90m" | <minutes>, "note"?} opens a window (default',
+ ' 2h) in which every other heavy job — e2e suites, next builds, the publish',
+ ' stages, other renders — waits at the heavy slot\'s door, and holds the',
+ ' transcription and download lanes (only the ones not already held; only',
+ ' those are released). The answer\'s "join" (RENDER_PRIORITY_TOKEN=…) lets a',
+ ' render in, on the floor 4000 MB and the cap 10240 MB; every `umtool take`',
+ ' joins by itself. {"on": false} ends it ("force": true ends a running',
+ ' take\'s hold, which otherwise ends with the take). `umtool take …',
+ ' --priority` is the same for one take. `get render-mode` says whether it',
+ ' is on, for what, since when, which lanes it holds. Close Firefox and',
+ ' other heavy apps while it renders.',
+ "",
'clear-platform-hold clears a platform\'s rate-limit hold, backoff and raised',
' pace, as the lane strip\'s Clear hold: {"platform"}. Answers the sentence.',
"",
diff --git a/scripts/queue-lock.mjs b/scripts/queue-lock.mjs
@@ -17,7 +17,7 @@
//
// node scripts/queue-lock.mjs [--name e2e-<pkg>] [--estimate <MB>] [--prebuild <pkg>]
// [--ports PORT:3011,...] -- <cmd...>
-// node scripts/queue-lock.mjs --heavy [--estimate <MB>] [--build] -- <cmd...>
+// node scripts/queue-lock.mjs --heavy [--estimate <MB>] [--build] [--urgent] -- <cmd...>
// (`pnpm heavy -- <cmd>`)
//
// THE HEAVY SLOT. Two OOMs on this machine (2026-10-08) took Xwayland and dbus
@@ -53,8 +53,20 @@
// still runs alone. HEAVY_CAP=0 turns it off; HEAVY_CAP_MB / HEAVY_CAP_SWAP_MB
// size it (a larger --estimate raises it to the estimate).
//
-// Bypasses: HEAVY=0 (no slot, no floor), HEAVY_MIN_FREE_MB=0 (no floor),
-// HEAVY_TIMEOUT=<seconds>. E2E_QUEUE=0 skips the slot as it skips the queue;
+// RENDER MODE (common/lib/renderPriority.mjs; AGENTS.md "Render mode"). While
+// a render the operator is waiting for holds it (`umtool take … --priority`,
+// `umtool render-mode on`, `pnpm ops render-mode`), every OTHER heavy job waits
+// at the door — before the line, so it never holds the line the render needs:
+// `queue-lock: held for a render (umtool take <p> --id <t>, since 13:31) —
+// waiting`. The render and everything under it carry the hold's token
+// (RENDER_PRIORITY_TOKEN) and are admitted, on the floor 4000 MB and the cap
+// 10240 MB unless HEAVY_MIN_FREE_MB / HEAVY_CAP_MB say otherwise. A job already
+// admitted is not stopped; a nested one (HEAVY_HELD) passes as before; an
+// `--urgent` one (a live stream's sniff) never waits. RENDER_PRIORITY=0 runs
+// anyway. The state is `<heavy lock>.render.json`, beside the lock.
+//
+// Bypasses: HEAVY=0 (no slot, no floor, no render wait), HEAVY_MIN_FREE_MB=0 (no floor),
+// RENDER_PRIORITY=0 (no render wait), HEAVY_TIMEOUT=<seconds>. E2E_QUEUE=0 skips the slot as it skips the queue;
// the floor still applies. A machine whose MemTotal is under the floor is not
// made to wait forever: it is told, and runs one job at a time. The slot is a
// safety net, not a correctness lock: with no usable `flock` it warns and runs
@@ -89,6 +101,14 @@ import net from "node:net";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
+import {
+ applyRenderPriorityDefaults,
+ carriesRenderPriority,
+ describeRenderPriority,
+ readRenderPriority,
+ renderPriorityBlocks,
+ renderPriorityFile,
+} from "../common/lib/renderPriority.mjs";
const SELF = fileURLToPath(import.meta.url);
@@ -124,6 +144,8 @@ function parseArgv(argv) {
portSpec: null,
hold: false,
heavy: false,
+ // `--urgent`: a job that cannot wait for a render (a live stream's sniff).
+ urgent: false,
// The heavy slot's admission (S4): a job's memory estimate in MB, whether
// it is a `next build`, and the package whose e2e build to ensure first.
// Unset means "infer from the command" (resolveJob).
@@ -145,6 +167,7 @@ function parseArgv(argv) {
const f = flags[i];
if (f === "--hold") opts.hold = true;
else if (f === "--heavy") opts.heavy = true;
+ else if (f === "--urgent") opts.urgent = true;
else if (f === "--name") opts.name = flags[++i];
else if (f === "--ports") opts.portSpec = flags[++i];
else if (f === "--timeout") opts.timeoutMs = Number(flags[++i]) * 1000;
@@ -1200,6 +1223,75 @@ async function admitOrExit(opts) {
}
}
+// ------------------------------------------------------------- render mode
+
+/**
+ * Wait while render mode holds the machine for a render this job is not
+ * (renderPriorityBlocks). Every input is injectable for the unit tests; `read`
+ * returns readRenderPriority's `{held, state}`. Resolves `{waitedMs}`; throws
+ * `{timeout: true}` past `timeoutMs` (0 = never).
+ */
+export async function waitForRenderPriority({
+ read,
+ env = process.env,
+ urgent = false,
+ pollMs = memPollMs(),
+ tickMs = TICK_MS,
+ timeoutMs = 0,
+ log = (line) => process.stderr.write(line),
+ now = Date.now,
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
+}) {
+ let s = read();
+ if (!renderPriorityBlocks(s, env, { urgent })) return { waitedMs: 0 };
+ const t0 = now();
+ let lastTick = t0;
+ log(
+ `queue-lock: held for a render (${describeRenderPriority(s.state)}) — waiting\n` +
+ " (render mode: `umtool render-mode off` ends it; RENDER_PRIORITY=0 to run anyway)\n",
+ );
+ for (;;) {
+ await sleep(pollMs);
+ s = read();
+ const waited = now() - t0;
+ if (!renderPriorityBlocks(s, env, { urgent })) {
+ log(`queue-lock: the render let go after ${humanDuration(waited)} — going on\n`);
+ return { waitedMs: waited };
+ }
+ if (timeoutMs > 0 && waited >= timeoutMs) {
+ throw Object.assign(new Error(`queue-lock: gave up after ${humanDuration(waited)} waiting for the render`), {
+ timeout: true,
+ });
+ }
+ if (now() - lastTick >= tickMs) {
+ lastTick = now();
+ log(`queue-lock: still waiting for the render (${humanDuration(waited)}; ${describeRenderPriority(s.state)})\n`);
+ }
+ }
+}
+
+async function renderGateOrExit(read, { urgent = false, timeoutMs = 0 } = {}) {
+ try {
+ return await waitForRenderPriority({ read, urgent, timeoutMs });
+ } catch (err) {
+ if (!err.timeout) throw err;
+ process.stderr.write(`\n${err.message}\n Raise or unset the timeout, or set RENDER_PRIORITY=0.\n`);
+ process.exit(EXIT_TIMEOUT);
+ }
+}
+
+// The render itself (it carries the hold's token): its floor and cap, unless
+// the environment names them — set in process.env, so its command inherits them.
+function renderOwnDefaults(read) {
+ if (!carriesRenderPriority(read())) return;
+ const set = applyRenderPriorityDefaults(process.env);
+ if (set.length) {
+ process.stderr.write(
+ `heavy: render mode — this render runs on the floor ${process.env.HEAVY_MIN_FREE_MB} MB, capped at ${process.env.HEAVY_CAP_MB} MB\n`,
+ );
+ }
+}
+
// ------------------------------------------------------------ the entry points
/**
@@ -1211,9 +1303,13 @@ async function admitOrExit(opts) {
export async function withHeavy(opts, fn) {
if (process.env.HEAVY === "0") return fn();
const cmd = opts.cmd ?? [HEAVY_NAME];
- const job = resolveJob(opts, cmd);
const heavyLock = lockFileFor(HEAVY_NAME);
const timeoutMs = opts.timeoutMs ?? defaultTimeoutMs("HEAVY_TIMEOUT");
+ const renderFile = renderPriorityFile(process.env, { heavyLock });
+ const readRender = () => readRenderPriority(renderFile);
+ // Before the job is resolved: the render's cap is an estimate's floor.
+ if (!process.env[HEAVY_HELD_ENV]) renderOwnDefaults(readRender);
+ const job = resolveJob(opts, cmd);
// Inside an admitted run: pass through — except a build, which still waits
// for the build slot (one build at a time is hard), and says so.
@@ -1246,21 +1342,30 @@ export async function withHeavy(opts, fn) {
const releases = [];
try {
let releaseLine = null;
- try {
- releaseLine = await holdLock(admitLockFor(heavyLock), "heavy-line", cmd, timeoutMs, {
- ...HEAVY_LOCK,
- describe: () =>
- `${describeSlot(heavyLock)}; next in line: ${describeHolder(admitLockFor(heavyLock), true)}`,
- });
- } catch (err) {
- // No usable flock (a container image without util-linux): the slot is a
- // safety net, so run on the floor alone rather than not at all.
- process.stderr.write(
- `heavy: the heavy slot is not held (${err?.message ?? err}) — the memory floor still applies\n`,
- );
- await memoryFloorOrExit(timeoutMs);
- process.env[HEAVY_HELD_ENV] = "1";
- return await fn();
+ // 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 (;;) {
+ await renderGateOrExit(readRender, { urgent: opts.urgent === true, timeoutMs: remaining() });
+ try {
+ releaseLine = await holdLock(admitLockFor(heavyLock), "heavy-line", cmd, remaining(), {
+ ...HEAVY_LOCK,
+ describe: () =>
+ `${describeSlot(heavyLock)}; next in line: ${describeHolder(admitLockFor(heavyLock), true)}`,
+ });
+ } catch (err) {
+ // No usable flock (a container image without util-linux): the slot is a
+ // safety net, so run on the floor alone rather than not at all.
+ process.stderr.write(
+ `heavy: the heavy slot is not held (${err?.message ?? err}) — the memory floor still applies\n`,
+ );
+ await memoryFloorOrExit(timeoutMs);
+ process.env[HEAVY_HELD_ENV] = "1";
+ return await fn();
+ }
+ if (!renderPriorityBlocks(readRender(), process.env, { urgent: opts.urgent === true })) break;
+ await releaseLine();
+ releaseLine = null;
}
try {
const slotWait = { ...HEAVY_LOCK, describe: () => describeSlot(heavyLock) };
@@ -1342,6 +1447,8 @@ export async function withQueue(opts, fn) {
if (process.env.E2E_QUEUE === "0") {
await preflight(ports, graceMs);
if (process.env.HEAVY !== "0" && !process.env[HEAVY_HELD_ENV]) {
+ const renderFile = renderPriorityFile(process.env, { heavyLock: lockFileFor(HEAVY_NAME) });
+ await renderGateOrExit(() => readRenderPriority(renderFile), { timeoutMs });
await memoryFloorOrExit(timeoutMs);
}
return fn();
@@ -1425,12 +1532,12 @@ async function main() {
if (cmd.length === 0) {
process.stderr.write(
"usage: queue-lock.mjs [--name e2e-<pkg>] [--estimate <MB>] [--prebuild <pkg>] [--ports PORT:3011,...] -- <cmd...>\n" +
- " queue-lock.mjs --heavy [--estimate <MB>] [--build] [--timeout <s>] -- <cmd...>\n",
+ " queue-lock.mjs --heavy [--estimate <MB>] [--build] [--urgent] [--timeout <s>] -- <cmd...>\n",
);
process.exit(2);
}
const code = opts.heavy
- ? await withHeavy({ timeoutMs: opts.timeoutMs, cmd, estimateMb: opts.estimateMb, build: opts.build }, () =>
+ ? await withHeavy({ timeoutMs: opts.timeoutMs, cmd, estimateMb: opts.estimateMb, build: opts.build, urgent: opts.urgent }, () =>
runCommand(capHeavy(cmd, resolveJob(opts, cmd)), null, { forwardTerm: true }),
)
: await withQueue({ ...opts, cmd }, () => runCommand(cmd, opts.name));
diff --git a/scripts/queue-lock.test.mjs b/scripts/queue-lock.test.mjs
@@ -26,6 +26,7 @@ import {
workerScale,
waitForAdmission,
waitForMemory,
+ waitForRenderPriority,
} from "./queue-lock.mjs";
const SCRIPT = fileURLToPath(new URL("./queue-lock.mjs", import.meta.url));
@@ -41,7 +42,7 @@ function tmpDir() {
// `pnpm heavy -- pnpm test:scripts`) is dropped unless the test sets it.
function lockEnv(env) {
const out = { E2E_PORT_CHECK: "0", HEAVY: "0", HEAVY_CAP: "0", ...process.env, ...env };
- for (const k of ["HEAVY_HELD", "QUEUE_LOCK_HELD", "E2E_QUEUE"]) {
+ for (const k of ["HEAVY_HELD", "QUEUE_LOCK_HELD", "E2E_QUEUE", "RENDER_PRIORITY", "RENDER_PRIORITY_TOKEN", "RENDER_PRIORITY_FILE"]) {
if (!(k in env)) delete out[k];
}
return out;
@@ -944,3 +945,146 @@ test("an admitted --heavy command runs under systemd-run's cap by default; HEAVY
assert.match(bare.stdout, /ran/);
assert.equal(fs.existsSync(log), false, "no systemd-run at all with the cap off");
});
+
+// ------------------------------------------------------------- render mode
+
+// A render-mode hold (common/lib/renderPriority.mjs) beside the test's heavy
+// lock, held by `pid` (a live process unless the test says otherwise).
+function renderHold(env, { pid, token = "render-tok", cmd = "umtool take ember --id t1", until = null } = {}) {
+ const file = `${env.HEAVY_LOCK_FILE}.render.json`;
+ fs.writeFileSync(
+ file,
+ JSON.stringify({
+ version: 1, token, since: new Date().toISOString(), until, by: "test", note: null,
+ holder: pid == null ? null : { pid, cmd }, lanesHeld: [],
+ }),
+ );
+ return file;
+}
+
+// A process that lives until killed: a render's stand-in holder.
+function sleeper() {
+ const child = spawn(process.execPath, ["-e", "setInterval(()=>{},1000)"], { stdio: "ignore" });
+ return child;
+}
+
+test("waitForRenderPriority waits while a render holds the machine, then goes on; the token, an urgent job and RENDER_PRIORITY=0 never wait", async () => {
+ const held = { held: true, state: { token: "tok", since: new Date().toISOString(), holder: { pid: 1, cmd: "umtool take p --id t" } }, stale: null };
+ const free = { held: false, state: null, stale: null };
+ const reads = [held, held, free];
+ const lines = [];
+ let t = 0;
+ const r = await waitForRenderPriority({
+ read: () => reads.shift() ?? free,
+ env: {},
+ pollMs: 10,
+ log: (l) => lines.push(l),
+ now: () => t,
+ sleep: async (ms) => {
+ t += ms;
+ },
+ });
+ assert.equal(r.waitedMs, 20);
+ assert.match(lines[0], /^queue-lock: held for a render \(umtool take p --id t, since \d\d:\d\d\) — waiting/);
+ assert.match(lines.at(-1), /the render let go after/);
+ for (const opts of [{ env: { RENDER_PRIORITY_TOKEN: "tok" } }, { env: { RENDER_PRIORITY: "0" } }, { env: {}, urgent: true }]) {
+ const quiet = [];
+ assert.deepEqual(await waitForRenderPriority({ read: () => held, log: (l) => quiet.push(l), ...opts }), { waitedMs: 0 });
+ assert.deepEqual(quiet, []);
+ }
+ await assert.rejects(
+ waitForRenderPriority({ read: () => held, env: {}, pollMs: 10, timeoutMs: 15, log: () => {}, now: () => t, sleep: async (ms) => { t += ms; } }),
+ (err) => err.timeout === true,
+ );
+});
+
+test("render mode: a heavy job waits for the render, named, and starts when it lets go; a stale hold is no hold", async (t) => {
+ const dir = tmpDir();
+ const env = heavyEnv(dir);
+ const holder = sleeper();
+ t.after(() => holder.kill("SIGKILL"));
+ const file = renderHold(env, { pid: holder.pid });
+ const run = startLock(["--heavy", "--", process.execPath, "-e", 'console.log("ran")'], env);
+ await run.waitFor(/queue-lock: held for a render \(umtool take ember --id t1, since \d\d:\d\d\) — waiting/);
+ await delay(150);
+ fs.rmSync(file);
+ const res = await run.done;
+ assert.equal(res.code, 0, res.stderr);
+ assert.match(res.stdout, /ran/);
+ assert.match(res.stderr, /the render let go after/);
+
+ // The holder gone (a killed take): not a hold — nothing waits.
+ renderHold(env, { pid: 999_999_999 });
+ const stale = await runLock(["--heavy", "--", "true"], env);
+ assert.equal(stale.code, 0, stale.stderr);
+ assert.doesNotMatch(stale.stderr, /held for a render/);
+ // A window whose until is past: the same.
+ renderHold(env, { pid: null, until: new Date(Date.now() - 1000).toISOString() });
+ const over = await runLock(["--heavy", "--", "true"], env);
+ assert.doesNotMatch(over.stderr, /held for a render/);
+});
+
+test("render mode: an e2e suite and a build wait too; RENDER_PRIORITY=0 and HEAVY=0 run anyway; a nested job passes", async (t) => {
+ const dir = tmpDir();
+ const env = heavyEnv(dir, { E2E_QUEUE_LOCK_FILE: path.join(dir, "q.lock") });
+ const holder = sleeper();
+ t.after(() => holder.kill("SIGKILL"));
+ const file = renderHold(env, { pid: holder.pid });
+ const suite = startLock(["--name", "e2e-umtool", "--estimate", "1500", "--", "true"], env);
+ await suite.waitFor(/held for a render/);
+ const build = startLock(["--heavy", "--build", "--", "true"], env);
+ await build.waitFor(/held for a render/);
+ // E2E_QUEUE=0 skips the queue and the slot, not the render.
+ const unqueued = startLock(["--name", "e2e-editor", "--", "true"], { ...env, E2E_QUEUE: "0" });
+ await unqueued.waitFor(/held for a render/);
+
+ const bypass = await runLock(["--heavy", "--", "true"], { ...env, RENDER_PRIORITY: "0" });
+ assert.equal(bypass.code, 0);
+ assert.doesNotMatch(bypass.stderr, /held for a render/);
+ const off = await runLock(["--heavy", "--", "true"], { ...env, HEAVY: "0" });
+ assert.equal(off.code, 0);
+ assert.equal(off.stderr, "");
+ const nested = await runLock(["--heavy", "--", "true"], { ...env, HEAVY_HELD: "1" });
+ assert.equal(nested.code, 0);
+ assert.doesNotMatch(nested.stderr, /held for a render/);
+ const urgent = await runLock(["--heavy", "--urgent", "--", "true"], env);
+ assert.equal(urgent.code, 0);
+ assert.doesNotMatch(urgent.stderr, /held for a render/);
+
+ fs.rmSync(file);
+ for (const w of [suite, build, unqueued]) assert.equal((await w.done).code, 0);
+});
+
+test("render mode: the render (its token) is admitted at once, on the floor 4000 MB and capped at 10240 MB", async (t) => {
+ const dir = tmpDir();
+ const bin = path.join(dir, "bin");
+ fs.mkdirSync(bin);
+ const log = path.join(dir, "systemd-run.log");
+ fs.writeFileSync(
+ path.join(bin, "systemd-run"),
+ `#!/bin/sh\nprintf '%s\\n' "$*" >> '${log}'\nwhile [ "$1" != "--" ] && [ $# -gt 0 ]; do shift; done\n[ "$1" = "--" ] && shift\n[ $# -gt 0 ] && exec "$@"\nexit 0\n`,
+ { mode: 0o755 },
+ );
+ const cgroup = path.join(dir, "cgroup");
+ fs.writeFileSync(cgroup, "0::/queue-lock-test-not-a-cgroup.scope\n");
+ const env = heavyEnv(dir, { HEAVY_CAP: undefined, HEAVY_PROC_CGROUP: cgroup, PATH: `${bin}:${process.env.PATH}` });
+ meminfo(env.HEAVY_MEMINFO_FILE, 4500); // under the usual 6000 floor, over the render's 4000
+ const holder = sleeper();
+ t.after(() => holder.kill("SIGKILL"));
+ renderHold(env, { pid: holder.pid, token: "render-tok" });
+ const render = await runLock(
+ ["--heavy", "--estimate", "2000", "--", "sh", "-c", 'echo "floor=$HEAVY_MIN_FREE_MB cap=$HEAVY_CAP_MB"'],
+ { ...env, RENDER_PRIORITY_TOKEN: "render-tok" },
+ );
+ assert.equal(render.code, 0, render.stderr);
+ assert.doesNotMatch(render.stderr, /held for a render|waiting for memory/);
+ assert.match(render.stderr, /render mode — this render runs on the floor 4000 MB, capped at 10240 MB/);
+ // Its command (and so its subprocesses) inherits them.
+ assert.match(render.stdout, /floor=4000 cap=10240/);
+ assert.match(fs.readFileSync(log, "utf8"), /-p MemoryMax=10240M/);
+ // The environment's own numbers win.
+ const own = await runLock(["--heavy", "--", "sh", "-c", 'echo "floor=$HEAVY_MIN_FREE_MB"'], {
+ ...env, RENDER_PRIORITY_TOKEN: "render-tok", HEAVY_MIN_FREE_MB: "1000",
+ });
+ assert.match(own.stdout, /floor=1000/);
+});
diff --git a/umtool/app/api/render-mode/route.ts b/umtool/app/api/render-mode/route.ts
@@ -0,0 +1,37 @@
+import {
+ RENDER_MODE_REMINDER,
+ clockOf,
+ describeRenderPriority,
+ readRenderPriority,
+ renderPriorityFile,
+} from "yt-dlp-transcript-common/lib/renderPriority.mjs";
+import { REPO_ROOT } from "@/lib/paths.mjs";
+
+export const dynamic = "force-dynamic";
+
+// RENDER MODE as it stands (common/lib/renderPriority.mjs; AGENTS.md "Render
+// mode"), for the take panel's banner. Read only: it is turned on by a take
+// started with "Give renders the machine" (`umtool take … --priority`), by
+// `umtool render-mode on`, or by `pnpm ops render-mode`. The token is not
+// answered — a page has no use for it.
+//
+// GET -> { held, what, since, until, take, lanesHeld, lanesSkipped, lanesError, note, reminder }
+export async function GET() {
+ const s = readRenderPriority(renderPriorityFile(process.env, { root: REPO_ROOT }));
+ const st = s.held ? s.state : null;
+ return Response.json(
+ {
+ held: Boolean(st),
+ what: st ? describeRenderPriority(st) : null,
+ since: st ? clockOf(st.since) : null,
+ until: st?.until ? clockOf(st.until) : null,
+ take: st?.holder ? { project: st.holder.project ?? null, take: st.holder.take ?? null } : null,
+ lanesHeld: st?.lanesHeld ?? [],
+ lanesSkipped: st?.lanesSkipped ?? [],
+ lanesError: st?.lanesError ?? null,
+ note: st?.note ?? null,
+ reminder: RENDER_MODE_REMINDER,
+ },
+ { headers: { "cache-control": "no-store" } },
+ );
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -63,7 +63,9 @@
// umtool take <project> --id <id> --label L [--group G] [--style S] [--patch F | --set p=v …]
// [--at S --dur S | --full] [--force] [--from TAKE] [--keep-frames] | --id <id> --rebuild make one take
// [--draft] record it without rendering (walk it first) · --id <id> --promote [--anyway] make it the cut
+// [--priority] render mode for the take's lifetime: the machine is the render's (AGENTS.md "Render mode")
// umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]
+// umtool render-mode on [--for 90m] [--note T] | off [--force] | status [--json] render mode: a render gets the machine
// umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3]
// [--out NAME] [--dry-run] [--json] a trailer cut from the take's finished master
// umtool rulings <project> [import [--dry-run] | set <clip> <verdict> [--reason R] [--match M] | clear <clip>]
@@ -799,9 +801,14 @@ function usage() {
" --from TAKE reuses that take's segments, chrome and batches; --keep-frames keeps the chrome)",
" --draft (--no-render): record the take, render nothing -- walk it, edit it, render it later",
" (`umtool take <p> --id <id> --full` renders a draft from its stored patch)",
+ " --priority: render mode for the take's lifetime -- every other heavy job waits for it, the",
+ " editor's transcription and download lanes are held; all let go at its end, failure or signal",
" umtool take <project> --id <id> --promote [--anyway] make this the cut: the take's patch applied to the",
" manifest, one undo point (revisions/…-auto-before-promote-take)",
" umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]",
+ " umtool render-mode on [--for 90m] [--note T] | off [--force] | status [--json] render mode: a render the",
+ " operator waits for gets the machine (other heavy jobs wait; the editor's transcription and",
+ " download lanes held); `on` is a window for a chain of renders (default 2h)",
" umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] [--out NAME]",
" a trailer cut from the take's finished master: the master's own frames, so the deck shows the",
" whole timeline; beats are clip source seconds or master seconds ([--dry-run] the mapping only)",
@@ -905,6 +912,8 @@ const COMMANDS = {
// The take maker (release 33): lib/report/takeCli.mjs.
take: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takeCommand(argv.slice(argv.indexOf("take") + 1))),
takes: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takesCommand(argv.slice(argv.indexOf("takes") + 1))),
+ // Render mode (2026-10-30): lib/report/renderMode.mjs.
+ "render-mode": async () => process.exit(await (await import("../lib/report/renderMode.mjs")).renderModeCommand(argv.slice(argv.indexOf("render-mode") + 1))),
trailer: async () => process.exit(await (await import("../lib/report/trailerCli.mjs")).trailerCommand(argv.slice(argv.indexOf("trailer") + 1))),
// The clip deck's rulings (release 34): lib/report/rulingsCli.mjs.
rulings: async () => process.exit(await (await import("../lib/report/rulingsCli.mjs")).rulingsCommand(argv.slice(argv.indexOf("rulings") + 1))),
diff --git a/umtool/components/projects/NewTakePanel.tsx b/umtool/components/projects/NewTakePanel.tsx
@@ -5,6 +5,7 @@ import { useRouter } from "next/navigation";
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";
// 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.
@@ -38,12 +39,15 @@ export function announceTakeJob(job: unknown) {
window.dispatchEvent(new CustomEvent(TAKE_JOB_EVENT, { detail: job }));
}
-/** POST /api/report/takes/make; the job, or the error in words. */
+/**
+ * POST /api/report/takes/make; the job, or the error in words. "Give renders
+ * the machine" (RenderModeBanner) adds `priority` unless the body says.
+ */
export async function startTakeJob(body: Record<string, unknown>): Promise<{ job?: JobView; error?: string }> {
const r = await fetch("/api/report/takes/make", {
method: "POST",
headers: { "content-type": "application/json" },
- body: JSON.stringify(body),
+ body: JSON.stringify(body.priority === undefined && renderPriorityPref() ? { ...body, priority: true } : body),
cache: "no-store",
});
const j = (await r.json().catch(() => ({}))) as { job?: JobView; error?: string };
@@ -157,6 +161,7 @@ export default function NewTakePanel({
return (
<section data-new-take="" className="space-y-2">
+ <RenderModeBanner />
<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/RenderModeBanner.tsx b/umtool/components/projects/RenderModeBanner.tsx
@@ -0,0 +1,107 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+// RENDER MODE on the take panel (common/lib/renderPriority.mjs; AGENTS.md
+// "Render mode"): the "Give renders the machine" toggle, and a banner while a
+// render holds the machine.
+//
+// The toggle is this browser's: a take this page starts (New take, Make all
+// styles, a card's Rebuild / Render) carries `priority`, which runs it as
+// `umtool take … --priority` — every other heavy job waits for its render, the
+// editor's transcription and download lanes are held, both let go at its end.
+// The banner reads /api/render-mode (the state file), whoever turned it on.
+
+const PREF_KEY = "umtool:render-priority";
+
+/** Whether this browser gives its renders the machine. Off when storage cannot be read. */
+export function renderPriorityPref(): boolean {
+ try {
+ return localStorage.getItem(PREF_KEY) === "on";
+ } catch {
+ return false;
+ }
+}
+
+function setRenderPriorityPref(on: boolean) {
+ try {
+ if (on) localStorage.setItem(PREF_KEY, "on");
+ else localStorage.removeItem(PREF_KEY);
+ } catch {
+ /* a private window: the toggle lasts this page only */
+ }
+}
+
+type RenderModeView = {
+ held: boolean;
+ what: string | null;
+ since: string | null;
+ until: string | null;
+ lanesHeld: string[];
+ lanesSkipped: string[];
+ lanesError: string | null;
+ reminder: string;
+};
+
+export default function RenderModeBanner() {
+ const [ready, setReady] = useState(false);
+ const [on, setOn] = useState(false);
+ const [mode, setMode] = useState<RenderModeView | null>(null);
+
+ // Read storage after hydration: reading it during render would differ from the server's.
+ useEffect(() => {
+ setOn(renderPriorityPref());
+ setReady(true);
+ }, []);
+
+ useEffect(() => {
+ let alive = true;
+ const look = () =>
+ fetch("/api/render-mode", { cache: "no-store" })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((j: RenderModeView | null) => alive && setMode(j))
+ .catch(() => {});
+ void look();
+ const t = setInterval(look, 4000);
+ return () => {
+ alive = false;
+ clearInterval(t);
+ };
+ }, []);
+
+ return (
+ <div className="space-y-1.5">
+ <label
+ className="flex items-center gap-1.5 text-[12px] text-text-2"
+ title="Renders started here run as `umtool take … --priority`: other heavy jobs (e2e, builds, other renders) wait for them, and the editor's transcription and download lanes are held until they end."
+ >
+ <input
+ type="checkbox"
+ data-render-priority=""
+ checked={on}
+ disabled={!ready}
+ onChange={(e) => {
+ setOn(e.target.checked);
+ setRenderPriorityPref(e.target.checked);
+ }}
+ />
+ Give renders the machine
+ </label>
+ {mode?.held ? (
+ <p
+ data-render-mode-banner=""
+ role="status"
+ className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2 text-[12px] text-text"
+ >
+ <strong>Render mode:</strong>{" "}
+ {mode.lanesHeld.length ? `${mode.lanesHeld.join(" and ")} lane${mode.lanesHeld.length > 1 ? "s" : ""} held` : "the machine held"} for {mode.what}
+ {mode.lanesError ? <span className="text-text-2"> ({mode.lanesError})</span> : null}. {capitalize(mode.reminder)}.
+ </p>
+ ) : null}
+ </div>
+ );
+}
+
+function capitalize(s: string) {
+ return s ? s[0].toUpperCase() + s.slice(1) : s;
+}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -48,6 +48,7 @@ Inbox cannot disagree about what is wrong with one.
| `notes …` | operator notes: list, read, reply, resolve ([notes.md](notes.md)) |
| `take <project> --id <id> --label L [--group G] [--kind similar\|different] [--summary S] [--style NAME] [--patch FILE \| --patch-json JSON \| --set path=value …] [--effect NAME] [--at S --dur S \| --full] [--quick] [--force] [--progress ndjson]` | one **take**: the manifest with a montage style's patch, then an overlay effect's (`--effect`, release 35), then the take's own, rendered into `takes/<id>/` (the Takes page's New take); `--id <id> --rebuild` makes one again from its own `take.json` ([report-video.md](report-video.md#making-takes)) |
| `take <project> --id <id> --label L [--patch F \| …] --draft` (`--no-render`) · `take <project> --id <id> [--full \| --at S --dur S]` · `take <project> --id <id> --rebuild [--full \| --at S --dur S]` · `take <project> --id <id> --promote [--anyway] [--json]` | a **draft** take: recorded with nothing rendered, to be walked first; a draft named with no patch flags is rendered from its stored (walked) patch, and `--rebuild` takes a window flag; **make it the cut**: the take's patch applied to the manifest now, one undo point (`revisions/…-auto-before-promote-take`), refused (exit 1) when its timeline would replace a cut that changed since, until `--anyway` ([report-video.md](report-video.md#walking-a-take-drafts-edits-into-the-take-and-making-it-the-cut)) |
+| `take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json]` · `render-mode off [--force] [--json]` · `render-mode status [--json]` | **render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription and download lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints. `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, "Render mode") |
| `takes make <project> [--recipe FILE] [--only ID,ID] [--force]` · `takes make <project> --all-styles [--group G] [--at S --dur S \| --full]` | a recipe's takes, one at a time (default `takes/recipe.json`); every montage style, one take each (Make all styles); **exit 1** if any failed |
| `takes styles [--json]` · `takes effects <project> [--json]` · `takes pick <project> <take> [--anyway] [--json]` | the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway` |
| `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) |
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -1063,6 +1063,34 @@ the one the take was made from (its `baseHash`), the card says **The project cha
take was made** and the pick waits for **Use anyway**. A take that does not record its base asks
the same.
+
+### Render mode: giving a render the machine
+
+A render you are waiting for is slowed by what else the machine does — the transcription
+lane's ASR, the editor, e2e servers and browsers — more than by memory (measured 2026-10-30:
+under 1 GB in its scope while cutting, ~200 MB per Chromium worker while capturing). So a take
+can ask for the machine:
+
+```sh
+umtool take <project> --id <take> … --priority # this take's lifetime
+umtool render-mode on --for 90m --note "the Ember cut" # a window for a chain of renders
+umtool render-mode status
+umtool render-mode off
+```
+
+On the Takes page, **Give renders the machine** (this browser's toggle) starts every take —
+New take, Make all styles, a card's Render — with `--priority`, and a banner says while a
+render holds the machine.
+
+While render mode is on, every other heavy job waits at the heavy slot's door (e2e suites,
+`next build`s, the publish stages, other renders); the render is admitted on the floor
+4000 MB and the cap 10240 MB; the editor's transcription and download lanes are held — only
+the ones that were not held already, and only those are let go. A take's hold ends with the
+take: done, failed, or stopped (Ctrl-C, the job's Stop). A window ends at its `until`
+(2 h unless `--for`), or with `off`. A hold whose process died is no hold: the gate ignores
+it at once, and the editor's heartbeat releases its lanes. Close Firefox and other heavy
+apps while it renders.
+
### 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/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs
@@ -928,7 +928,26 @@ function readBody(req, then) {
});
}
+// The lanes' gates, as render mode (lib/report/renderMode.mjs) reads and holds
+// them: `GET /api/ops/settings?key=autoQueue` and `POST /api/ops/lane`.
+// download starts held, so a spec sees render mode leave someone else's hold alone.
+const lanes = { transcription: { held: false }, download: { held: true }, digest: { held: false }, backfill: { held: false } };
+
function generationRoute(req, res, url, auth) {
+ if (req.method === "GET" && url.pathname === "/api/ops/settings" && url.searchParams.get("key") === "autoQueue") {
+ req.resume();
+ return json(res, 200, { ok: true, key: "autoQueue", value: lanes });
+ }
+ if (req.method === "POST" && url.pathname === "/api/ops/lane") {
+ return readBody(req, (body) => {
+ requests.push({ route: "lane", ...(body ?? {}), authorization: auth });
+ record();
+ const lane = lanes[body?.lane];
+ if (!lane || typeof body?.held !== "boolean") return json(res, 400, { ok: false, error: '"lane" and "held"' });
+ lane.held = body.held;
+ return json(res, 200, { ok: true, lane: body.lane });
+ });
+ }
if (req.method === "GET" && url.pathname === "/api/ops/settings") {
req.resume();
const value = { ...generation, apiKeyFile: "<redacted>" };
diff --git a/umtool/e2e/takes.spec.ts b/umtool/e2e/takes.spec.ts
@@ -1,5 +1,5 @@
import { test, expect } from "@playwright/test";
-import { readFileSync, writeFileSync } from "node:fs";
+import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import * as urls from "./urls";
@@ -240,6 +240,59 @@ test("the take maker: New take with a style, the take appears, Use this take mak
await expect(page.locator("[data-take='soft'] [data-take-picked]")).toBeVisible();
});
+test("Give renders the machine: the take runs with --priority, holds the lane it found free, lets it go, and the banner says so", async ({ page, request }) => {
+ test.setTimeout(240_000);
+ const SONG = path.join(HERE, "..", ".e2e-song");
+ const STATE = path.join(SONG, "render-priority.json");
+ const laneAsks = () =>
+ (JSON.parse(readFileSync(path.join(SONG, "editor-stub.requests.json"), "utf8")) as Array<{ route: string; lane?: string; held?: boolean }>)
+ .filter((x) => x.route === "lane")
+ .map((x) => `${x.lane}:${x.held}`);
+ const before = laneAsks().length;
+
+ // The toggle is this browser's: every take the page starts carries priority.
+ await page.goto(MAKE_PAGE);
+ const toggle = page.locator("[data-render-priority]");
+ await expect(toggle).toBeEnabled();
+ await toggle.check();
+ expect(await page.evaluate(() => localStorage.getItem("umtool:render-priority"))).toBe("on");
+ await page.reload();
+ await expect(page.locator("[data-render-priority]")).toBeChecked();
+
+ // The route the form posts: priority makes it `umtool take … --priority`.
+ const r = await request.post("/api/report/takes/make", {
+ data: { project: "reports/takes-make-fixture", take: { label: "Prio", window: "full" }, priority: true },
+ });
+ expect(r.status()).toBe(200);
+ const { job } = (await r.json()) as { job: { id: string; steps: Array<{ argv: string[] }> } };
+ expect(job.steps[0].argv).toContain("--priority");
+ await expect
+ .poll(async () => ((await (await request.get(`/api/report/takes/make?job=${job.id}`)).json()) as { state: string }).state, { timeout: 180_000 })
+ .toBe("done");
+ // The stub's download lane was held already: left alone, never released.
+ expect(laneAsks().slice(before)).toEqual(["transcription:true", "transcription:false"]);
+ expect(existsSync(STATE)).toBe(false);
+
+ // While a render holds it, the panel says so (this process is the holder: alive).
+ writeFileSync(
+ STATE,
+ JSON.stringify({
+ version: 1, token: "e2e", since: new Date().toISOString(), until: null, by: "e2e", note: null,
+ holder: { pid: process.pid, cmd: "umtool take takes-make-fixture --id prio" },
+ lanesHeld: ["transcription"], lanesSkipped: ["download"],
+ }),
+ );
+ try {
+ await page.reload();
+ const banner = page.locator("[data-render-mode-banner]");
+ await expect(banner).toContainText("transcription lane held for umtool take takes-make-fixture --id prio");
+ await expect(banner).toContainText("Close Firefox and other heavy apps");
+ } finally {
+ rmSync(STATE, { force: true });
+ }
+ await expect(page.locator("[data-render-mode-banner]")).toHaveCount(0, { timeout: 10_000 });
+});
+
test("the Takes page with the New take form open fits a phone", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.goto(MAKE_PAGE);
diff --git a/umtool/lib/report/renderMode.mjs b/umtool/lib/report/renderMode.mjs
@@ -0,0 +1,288 @@
+// RENDER MODE from umtool (common/lib/renderPriority.mjs; AGENTS.md "Render
+// mode"): a render the operator is waiting for gets the machine.
+//
+// umtool take <p> --id <t> … --priority on for the take's lifetime: on at
+// the start, off at the end, on a
+// failure and on a signal
+// umtool render-mode on [--for 90m] [--note …] [--json] a window (a chain of renders)
+// umtool render-mode off [--force] [--json]
+// umtool render-mode status [--json]
+//
+// On: the state file (beside the heavy slot's lock), then the editor's
+// transcription and download lanes held through its ops — the `lane` action
+// `pnpm ops lane` posts — each only if it was not held already, and recorded,
+// so off releases only those. The editor is ARCHILYZER_EDITOR_URL with
+// WORKER_TOKEN, read as `pnpm ops` reads them (fetchWindows.mjs editorConfig).
+// With no editor to ask, render mode still holds the heavy slot's door; it
+// says the lanes were not held.
+//
+// A take inside a manual window joins it (its render carries the window's
+// token); a take with --priority while another render holds it renders
+// without it, and its render waits at the door like any other heavy job.
+
+import {
+ RENDER_MODE_LANES,
+ RENDER_MODE_REMINDER,
+ RENDER_PRIORITY_TOKEN_ENV,
+ clockOf,
+ describeRenderPriority,
+ parseDurationMs,
+ readRenderPriority,
+ reapRenderMode,
+ renderModeOff,
+ renderModeOn,
+ renderPriorityFile,
+} from "yt-dlp-transcript-common/lib/renderPriority.mjs";
+import { REPO_ROOT } from "../paths.mjs";
+import { editorConfig } from "./fetchWindows.mjs";
+
+/** The state file, as the checkout's queue-lock finds it (not the cwd's: a CLI may run in a workspace). */
+export function renderModeFile(env = process.env) {
+ return renderPriorityFile(env, { root: REPO_ROOT });
+}
+
+/**
+ * The editor's lanes over its ops: read through `GET /api/ops/settings?key=autoQueue`,
+ * held and released through `POST /api/ops/lane`. Null with no token to ask with.
+ * @param {{ url: string, token: string, fetch?: typeof fetch }} cfg
+ * @returns {import("yt-dlp-transcript-common/lib/renderPriority.mjs").RenderModeLanes | null}
+ */
+export function editorLanes(cfg) {
+ if (!cfg?.token) return null;
+ const ask = async (route, body) => {
+ const f = cfg.fetch ?? fetch;
+ let res;
+ try {
+ res = await f(`${cfg.url}${route}`, {
+ method: body ? "POST" : "GET",
+ headers: { authorization: `Bearer ${cfg.token}`, ...(body ? { "content-type": "application/json" } : {}) },
+ ...(body ? { body: JSON.stringify(body) } : {}),
+ cache: "no-store",
+ signal: AbortSignal.timeout(15_000),
+ });
+ } catch (e) {
+ throw new Error(`could not reach the editor at ${cfg.url}: ${e instanceof Error ? e.message : String(e)}`);
+ }
+ const j = await res.json().catch(() => ({}));
+ if (!res.ok || j?.ok === false) throw new Error(`the editor refused (HTTP ${res.status}): ${j?.error ?? "no reason given"}`);
+ return j;
+ };
+ return {
+ async isHeld(lane) {
+ const j = await ask("/api/ops/settings?key=autoQueue");
+ return j?.value?.[lane]?.held === true;
+ },
+ async hold(lane) {
+ await ask("/api/ops/lane", { lane, held: true });
+ },
+ async release(lane) {
+ await ask("/api/ops/lane", { lane, held: false });
+ },
+ };
+}
+
+/** The lanes line of a hold: "lanes held: transcription, download (… already held: left alone)". */
+export function lanesLine(state) {
+ const held = state.lanesHeld?.length ? `lanes held: ${state.lanesHeld.join(", ")}` : "no lanes held";
+ const skipped = state.lanesSkipped?.length ? ` (${state.lanesSkipped.join(", ")} already held — left alone)` : "";
+ const error = state.lanesError ? ` — ${state.lanesError}` : "";
+ return `${held}${skipped}${error}`;
+}
+
+/**
+ * Run `fn` (a take's make) in render mode, as `umtool take … --priority` asks.
+ *
+ * --priority, render mode off on for this process (holder: its pid), off
+ * after `fn` — done, failed or signalled
+ * a manual window on joined: the render carries its token; the
+ * window stays on afterwards (with or without --priority)
+ * --priority, another render run as is; its render waits at the door
+ *
+ * The token goes into process.env, so the render queue-lock starts inherits it.
+ *
+ * @template T
+ * @param {{ priority: boolean, project: string, take?: string | null, cmd?: string, log: (s: string) => void,
+ * env?: Record<string, string | undefined>, file?: string, lanes?: any, signals?: boolean }} o
+ * @param {() => Promise<T>} fn
+ * @returns {Promise<T>}
+ */
+export async function withTakePriority(o, fn) {
+ const env = o.env ?? process.env;
+ const file = o.file ?? renderModeFile(env);
+ const status = readRenderPriority(file);
+ if (status.held && status.state) {
+ if (!status.state.holder) {
+ env[RENDER_PRIORITY_TOKEN_ENV] = status.state.token;
+ o.log(`render mode is on (${describeRenderPriority(status.state)}) — this take renders in it`);
+ return fn();
+ }
+ if (o.priority) o.log(`render mode is held by another render (${describeRenderPriority(status.state)}) — this one waits for it`);
+ return fn();
+ }
+ if (!o.priority) return fn();
+
+ const lanes = o.lanes !== undefined ? o.lanes : editorLanes(editorConfig(env));
+ const cmd = o.cmd ?? `umtool take ${o.project}${o.take ? ` --id ${o.take}` : ""}`;
+ const on = await renderModeOn({
+ file,
+ holder: { pid: process.pid, cmd, project: o.project, take: o.take ?? null },
+ by: "umtool take --priority",
+ editor: lanes ? editorConfig(env).url : null,
+ lanes,
+ });
+ if (!on.ok || !on.state) {
+ // Another hold went on between the look and the claim: render as any job.
+ o.log(`render mode is held by another render${on.held ? ` (${describeRenderPriority(on.held)})` : ""} — this one waits for it`);
+ return fn();
+ }
+ const token = on.state.token;
+ env[RENDER_PRIORITY_TOKEN_ENV] = token;
+ o.log(`render mode on for this take — ${lanesLine(on.state)}`);
+ o.log(` ${RENDER_MODE_REMINDER}`);
+
+ let ended = false;
+ const end = async () => {
+ if (ended) return;
+ ended = true;
+ if (env[RENDER_PRIORITY_TOKEN_ENV] === token) delete env[RENDER_PRIORITY_TOKEN_ENV];
+ try {
+ const off = await renderModeOff({ file, token, lanes });
+ o.log(
+ `render mode off${off.released.length ? ` — lanes released: ${off.released.join(", ")}` : ""}` +
+ (off.failed.length ? `; NOT released: ${off.failed.map((f) => `${f.lane} (${f.error})`).join(", ")} — the editor releases them when it next looks` : ""),
+ );
+ } catch (e) {
+ o.log(`render mode: could not end it (${e instanceof Error ? e.message : String(e)}) — it ends by itself, this process being gone`);
+ }
+ };
+ // A signal ends the hold before this process goes (the job runner's Cancel
+ // signals the group; Ctrl-C the same). Then exit as the signal would.
+ /** @type {Array<[NodeJS.Signals, () => void]>} */
+ const handlers = [];
+ if (o.signals !== false) {
+ for (const sig of /** @type {NodeJS.Signals[]} */ (["SIGINT", "SIGTERM", "SIGHUP"])) {
+ const h = () => {
+ const code = 128 + ({ SIGINT: 2, SIGTERM: 15, SIGHUP: 1 }[sig] ?? 0);
+ setTimeout(() => process.exit(code), 10_000).unref();
+ void end().finally(() => process.exit(code));
+ };
+ handlers.push([sig, h]);
+ process.on(sig, h);
+ }
+ }
+ try {
+ return await fn();
+ } finally {
+ for (const [sig, h] of handlers) process.off(sig, h);
+ await end();
+ }
+}
+
+const USAGE = [
+ "usage: umtool render-mode on [--for 90m] [--note TEXT] [--json]",
+ " umtool render-mode off [--force] [--json]",
+ " umtool render-mode status [--json]",
+ "",
+ "Render mode gives a render the operator is waiting for the machine: every other heavy job",
+ "(e2e suites, next builds, the publish stages, other renders) waits at the heavy slot's door",
+ `while it is on, and the editor's ${RENDER_MODE_LANES.join(" and ")} lanes are held — only the`,
+ "ones not held already, and only those are released at off. `on` is a window (default 2h; --for",
+ "90m, 1h30m, 45 = minutes) for a chain of renders: every `umtool take` started in it renders in it;",
+ "another command joins with the RENDER_PRIORITY_TOKEN it prints. For one take, `umtool take …",
+ "--priority` turns it on for the take's lifetime instead. `off` ends it (a running take's hold",
+ "only with --force). A hold whose process is gone or whose window is over is no hold: its lanes",
+ "are released by the editor's heartbeat, /jobs, or the next `status`/`on`.",
+ "The same from the editor: pnpm ops render-mode --json '{\"on\": true, \"for\": \"90m\"}' / get render-mode.",
+].join("\n");
+
+/**
+ * `umtool render-mode on|off|status`.
+ * @param {string[]} args
+ * @param {{ log?: (s: string) => void, err?: (s: string) => void, env?: Record<string, string | undefined>, file?: string, lanes?: any }} [opts]
+ * @returns {Promise<number>}
+ */
+export async function renderModeCommand(args, { log = console.log, err = console.error, env = process.env, file, lanes } = {}) {
+ const valued = new Set(["--for", "--note"]);
+ const sub = args.find((a, i) => !a.startsWith("--") && !valued.has(args[i - 1]));
+ const flag = (n) => {
+ const i = args.indexOf(n);
+ return i >= 0 ? args[i + 1] : undefined;
+ };
+ const json = args.includes("--json");
+ if (args.includes("--help")) {
+ log(USAGE);
+ return 0;
+ }
+ if (!sub || !["on", "off", "status"].includes(sub)) {
+ err(USAGE);
+ return 2;
+ }
+ const where = file ?? renderModeFile(env);
+ const cfg = editorConfig(env);
+ const editor = lanes !== undefined ? lanes : editorLanes(cfg);
+ const out = (v) => log(JSON.stringify(v, null, 2));
+
+ if (sub === "status") {
+ const reaped = editor ? await reapRenderMode({ file: where, lanes: editor }).catch(() => null) : null;
+ const s = readRenderPriority(where);
+ if (json) {
+ out({ ok: true, held: s.held, state: s.state, stale: s.stale, reaped: reaped?.was ? reaped : null, file: where });
+ return 0;
+ }
+ if (reaped?.was) log(`a stale render mode was ended${reaped.released.length ? ` — lanes released: ${reaped.released.join(", ")}` : ""}`);
+ if (!s.held || !s.state) {
+ log(s.state ? `render mode is off (the last hold is stale: ${s.stale}; ${lanesLine(s.state)})` : "render mode is off");
+ return 0;
+ }
+ log(`render mode is ON: ${describeRenderPriority(s.state)}`);
+ log(` ${lanesLine(s.state)}`);
+ log(` ${RENDER_MODE_REMINDER}`);
+ return 0;
+ }
+
+ if (sub === "on") {
+ const raw = flag("--for");
+ const forMs = raw === undefined ? null : parseDurationMs(raw);
+ if (raw !== undefined && !forMs) {
+ err(`--for wants a duration: 90m, 2h, 1h30m, or minutes — not "${raw}"`);
+ return 2;
+ }
+ const r = await renderModeOn({ file: where, holder: null, forMs, note: flag("--note") ?? null, by: "umtool render-mode", editor: editor ? cfg.url : null, lanes: editor });
+ if (!r.ok || !r.state) {
+ if (json) out({ ok: false, error: "render mode is already on", held: r.held });
+ else err(`render mode is already on: ${r.held ? describeRenderPriority(r.held) : "?"}`);
+ return 1;
+ }
+ if (json) {
+ out({ ok: true, state: r.state, file: where, reminder: RENDER_MODE_REMINDER });
+ return 0;
+ }
+ log(`render mode ON until ${clockOf(r.state.until)} — ${lanesLine(r.state)}`);
+ log(` ${RENDER_MODE_REMINDER}`);
+ log(" every `umtool take` started now renders in it; another command joins with:");
+ log(` export ${RENDER_PRIORITY_TOKEN_ENV}=${r.state.token}`);
+ log(" end it: umtool render-mode off");
+ return 0;
+ }
+
+ // off
+ const s = readRenderPriority(where);
+ if (s.held && s.state?.holder && !args.includes("--force")) {
+ const msg = `render mode is held by a running render (${describeRenderPriority(s.state)}) — it ends with it; --force ends it now`;
+ if (json) out({ ok: false, error: msg });
+ else err(msg);
+ return 1;
+ }
+ const r = await renderModeOff({ file: where, lanes: editor });
+ if (json) {
+ out({ ok: true, was: r.was, released: r.released, failed: r.failed });
+ return r.failed.length ? 1 : 0;
+ }
+ if (!r.was) log("render mode was off");
+ else log(`render mode off${r.released.length ? ` — lanes released: ${r.released.join(", ")}` : ""}`);
+ if (r.failed.length) {
+ err(`NOT released: ${r.failed.map((f) => `${f.lane} (${f.error})`).join(", ")} — the editor releases them when it next looks`);
+ return 1;
+ }
+ return 0;
+}
diff --git a/umtool/lib/report/renderMode.test.mjs b/umtool/lib/report/renderMode.test.mjs
@@ -0,0 +1,255 @@
+// Render mode from umtool (renderMode.mjs): `umtool take … --priority`'s
+// lifetime hold, `umtool render-mode on|off|status`, and the editor lanes over
+// ops. Every test uses a temp state file and a fake editor — never the
+// machine's render mode or a live editor's lanes. Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+import { readRenderPriority, readRenderPriorityState } from "yt-dlp-transcript-common/lib/renderPriority.mjs";
+import { editorLanes, renderModeCommand, withTakePriority } from "./renderMode.mjs";
+import { takeCommand } from "./takeCli.mjs";
+import { takeSteps } from "./takeMaker.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+
+function tmpFile() {
+ return path.join(mkdtempSync(path.join(tmpdir(), "render-mode-")), "heavy.lock.render.json");
+}
+
+/** A fake editor's lanes: `held` what it holds, `calls` what was asked. */
+function fakeLanes(held = {}) {
+ const calls = [];
+ return {
+ held,
+ calls,
+ lanes: {
+ isHeld: async (lane) => held[lane] === true,
+ hold: async (lane) => {
+ calls.push(`hold ${lane}`);
+ held[lane] = true;
+ },
+ release: async (lane) => {
+ calls.push(`release ${lane}`);
+ held[lane] = false;
+ },
+ },
+ };
+}
+
+test("take --priority: on for the take (its lanes held, its token in the env), off at its end", async () => {
+ const file = tmpFile();
+ const ed = fakeLanes({ download: true });
+ const env = {};
+ const lines = [];
+ let during = null;
+ const r = await withTakePriority({ priority: true, project: "ember", take: "t1", log: (l) => lines.push(l), env, file, lanes: ed.lanes, signals: false }, async () => {
+ during = { status: readRenderPriority(file), token: env.RENDER_PRIORITY_TOKEN };
+ return "made";
+ });
+ assert.equal(r, "made");
+ assert.equal(during.status.held, true);
+ assert.equal(during.status.state.holder.pid, process.pid);
+ assert.equal(during.status.state.holder.cmd, "umtool take ember --id t1");
+ assert.equal(during.token, during.status.state.token, "the render inherits the token");
+ assert.deepEqual(ed.calls, ["hold transcription", "release transcription"], "download was held already: left alone");
+ assert.equal(ed.held.download, true);
+ assert.equal(existsSync(file), false);
+ assert.equal(env.RENDER_PRIORITY_TOKEN, undefined);
+ assert.ok(lines.some((l) => /close Firefox and other heavy apps/.test(l)));
+ assert.ok(lines.some((l) => /render mode off — lanes released: transcription/.test(l)));
+});
+
+test("take --priority: a failed take lets go too", async () => {
+ const file = tmpFile();
+ const ed = fakeLanes();
+ await assert.rejects(
+ withTakePriority({ priority: true, project: "ember", take: "t1", log: () => {}, env: {}, file, lanes: ed.lanes, signals: false }, async () => {
+ throw new Error("build-video exited 1");
+ }),
+ /build-video exited 1/,
+ );
+ assert.deepEqual(ed.calls, ["hold transcription", "hold download", "release transcription", "release download"]);
+ assert.equal(existsSync(file), false);
+});
+
+test("take --priority killed by a signal: the hold ends before the process does", async () => {
+ const dir = mkdtempSync(path.join(tmpdir(), "render-mode-sig-"));
+ const file = path.join(dir, "state.json");
+ const log = path.join(dir, "lanes.log");
+ const script = path.join(dir, "take.mjs");
+ writeFileSync(
+ script,
+ `import { appendFileSync } from "node:fs";
+import { withTakePriority } from ${JSON.stringify(path.join(HERE, "renderMode.mjs"))};
+const lanes = {
+ isHeld: async () => false,
+ hold: async (l) => appendFileSync(${JSON.stringify(log)}, "hold " + l + "\\n"),
+ release: async (l) => appendFileSync(${JSON.stringify(log)}, "release " + l + "\\n"),
+};
+await withTakePriority({ priority: true, project: "p", take: "t", log: (l) => console.log(l), env: {}, file: ${JSON.stringify(file)}, lanes }, () => new Promise(() => setInterval(() => {}, 1000)));
+`,
+ );
+ const child = spawn(process.execPath, [script], { stdio: ["ignore", "pipe", "pipe"] });
+ let out = "";
+ child.stdout.on("data", (d) => (out += d));
+ child.stderr.on("data", (d) => (out += d));
+ const t0 = Date.now();
+ while (!/render mode on for this take/.test(out)) {
+ if (Date.now() - t0 > 15_000) throw new Error(`never went on: ${out}`);
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ assert.equal(readRenderPriority(file).held, true);
+ child.kill("SIGTERM");
+ const code = await new Promise((r) => child.on("exit", (c) => r(c)));
+ assert.equal(code, 143);
+ assert.equal(existsSync(file), false);
+ assert.equal(readFileSync(log, "utf8"), "hold transcription\nhold download\nrelease transcription\nrelease download\n");
+});
+
+test("a take inside a manual window joins it (flag or not) and leaves it on; beside another render it takes nothing", async () => {
+ const file = tmpFile();
+ const ed = fakeLanes();
+ assert.equal(await renderModeCommand(["on", "--for", "30m", "--note", "a chain"], { log: () => {}, err: () => {}, env: {}, file, lanes: ed.lanes }), 0);
+ const window = readRenderPriorityState(file);
+ for (const priority of [false, true]) {
+ const env = {};
+ const lines = [];
+ await withTakePriority({ priority, project: "p", take: "t", log: (l) => lines.push(l), env, file, lanes: ed.lanes, signals: false }, async () => {
+ assert.equal(env.RENDER_PRIORITY_TOKEN, window.token);
+ });
+ assert.match(lines[0], /render mode is on \(render mode on \(by umtool render-mode\) — a chain, since/);
+ }
+ assert.equal(readRenderPriority(file).held, true, "the window outlives the takes");
+ assert.deepEqual(ed.calls, ["hold transcription", "hold download"]);
+
+ // A different render's hold: a --priority take renders without a token; nothing changes.
+ const other = tmpFile();
+ writeFileSync(other, JSON.stringify({ version: 1, token: "theirs", since: new Date().toISOString(), until: null, holder: { pid: process.pid, cmd: "umtool take x --id y" }, lanesHeld: [] }));
+ const env = {};
+ const lines = [];
+ await withTakePriority({ priority: true, project: "p", take: "t", log: (l) => lines.push(l), env, file: other, lanes: ed.lanes, signals: false }, async () => {
+ assert.equal(env.RENDER_PRIORITY_TOKEN, undefined);
+ });
+ assert.match(lines[0], /held by another render \(umtool take x --id y/);
+ assert.equal(readRenderPriorityState(other).token, "theirs");
+});
+
+test("without --priority and no window, a take is untouched", async () => {
+ const file = tmpFile();
+ const ed = fakeLanes();
+ const env = {};
+ await withTakePriority({ priority: false, project: "p", take: "t", log: () => {}, env, file, lanes: ed.lanes, signals: false }, async () => {});
+ assert.deepEqual(ed.calls, []);
+ assert.equal(existsSync(file), false);
+ assert.equal(env.RENDER_PRIORITY_TOKEN, undefined);
+});
+
+test("umtool render-mode on | status | off, with --json; off of a running take's hold needs --force", async () => {
+ const file = tmpFile();
+ const ed = fakeLanes({ download: true });
+ const out = [];
+ const err = [];
+ const io = { log: (l) => out.push(l), err: (l) => err.push(l), env: {}, file, lanes: ed.lanes };
+ assert.equal(await renderModeCommand(["status"], io), 0);
+ assert.equal(out.at(-1), "render mode is off");
+ assert.equal(await renderModeCommand(["on", "--for", "soon"], io), 2);
+ assert.equal(await renderModeCommand(["on", "--for", "90m"], io), 0);
+ assert.match(out.join("\n"), /render mode ON until \d\d:\d\d — lanes held: transcription \(download already held — left alone\)/);
+ assert.match(out.join("\n"), /export RENDER_PRIORITY_TOKEN=[0-9a-f]{16}/);
+ assert.equal(await renderModeCommand(["on"], io), 1, "already on");
+ out.length = 0;
+ assert.equal(await renderModeCommand(["status", "--json"], io), 0);
+ const st = JSON.parse(out.join("\n"));
+ assert.equal(st.held, true);
+ assert.deepEqual(st.state.lanesHeld, ["transcription"]);
+ assert.equal(await renderModeCommand(["off"], io), 0);
+ assert.deepEqual(ed.calls, ["hold transcription", "release transcription"]);
+ assert.equal(ed.held.download, true);
+ assert.equal(existsSync(file), false);
+
+ // A running take's hold (this process) ends with the take, unless --force.
+ writeFileSync(file, JSON.stringify({ version: 1, token: "take", since: new Date().toISOString(), until: null, holder: { pid: process.pid, cmd: "umtool take p --id t" }, lanesHeld: [] }));
+ assert.equal(await renderModeCommand(["off"], io), 1);
+ assert.match(err.at(-1), /held by a running render .* --force ends it now/);
+ assert.equal(await renderModeCommand(["off", "--force"], io), 0);
+ assert.equal(existsSync(file), false);
+
+ // A stale hold's lanes are released by the next status.
+ writeFileSync(file, JSON.stringify({ version: 1, token: "dead", since: new Date().toISOString(), until: null, holder: { pid: 999999999 }, lanesHeld: ["transcription"] }));
+ ed.held.transcription = true;
+ out.length = 0;
+ assert.equal(await renderModeCommand(["status"], io), 0);
+ assert.match(out[0], /a stale render mode was ended — lanes released: transcription/);
+ assert.equal(ed.held.transcription, false);
+ assert.equal(await renderModeCommand(["bogus"], io), 2);
+});
+
+test("editorLanes asks the editor's ops: settings?key=autoQueue to read, lane to hold and release; none without a token", async () => {
+ assert.equal(editorLanes({ url: "http://e", token: "" }), null);
+ const asked = [];
+ const fetch = async (url, init) => {
+ asked.push(`${init.method} ${url} ${init.body ?? ""} ${init.headers.authorization}`);
+ if (String(url).includes("settings")) return new Response(JSON.stringify({ ok: true, key: "autoQueue", value: { download: { held: true }, transcription: { held: false } } }));
+ return new Response(JSON.stringify({ ok: true }));
+ };
+ const lanes = editorLanes({ url: "http://e", token: "tok", fetch });
+ assert.equal(await lanes.isHeld("download"), true);
+ assert.equal(await lanes.isHeld("transcription"), false);
+ await lanes.hold("transcription");
+ await lanes.release("transcription");
+ assert.deepEqual(asked, [
+ "GET http://e/api/ops/settings?key=autoQueue Bearer tok",
+ "GET http://e/api/ops/settings?key=autoQueue Bearer tok",
+ 'POST http://e/api/ops/lane {"lane":"transcription","held":true} Bearer tok',
+ 'POST http://e/api/ops/lane {"lane":"transcription","held":false} Bearer tok',
+ ]);
+ const refusing = editorLanes({ url: "http://e", token: "tok", fetch: async () => new Response(JSON.stringify({ ok: false, error: "nope" }), { status: 400 }) });
+ await assert.rejects(refusing.hold("download"), /the editor refused \(HTTP 400\): nope/);
+});
+
+test("takeSteps: priority runs every kind of take job with --priority", () => {
+ const proj = { id: "reports/proj" };
+ const ctx = { styles: { flash: { label: "Flash" } }, existing: [{ id: "flash", window: "full" }], clipCount: 3 };
+ assert.ok(takeSteps(proj, { take: { label: "P" }, priority: true }, ctx).steps[0].argv.includes("--priority"));
+ assert.ok(!takeSteps(proj, { take: { label: "P" } }, ctx).steps[0].argv.includes("--priority"));
+ assert.ok(takeSteps(proj, { rebuild: "flash", priority: true }, ctx).steps[0].argv.includes("--priority"));
+ assert.ok(takeSteps(proj, { allStyles: { group: "m" }, priority: true }, ctx).steps[0].argv.includes("--priority"));
+});
+
+test("umtool take --priority: the take is made inside render mode, and render mode ends with it — done or failed", async () => {
+ const root = mkdtempSync(path.join(tmpdir(), "render-mode-take-"));
+ const dir = path.join(root, "reports", "proj");
+ await mkdir(path.join(dir, "out", "clips-raw"), { recursive: true });
+ await writeFile(
+ path.join(dir, "video.manifest.json"),
+ JSON.stringify({ slug: "proj", render: { crf: 30 }, timeline: [{ id: "s01", type: "clip", channel: "c", video: "v", start: 0, end: 13 }] }, null, 2) + "\n",
+ );
+ const file = path.join(root, "state.json");
+ const ed = fakeLanes();
+ let heldDuring = null;
+ const render = async (job) => {
+ heldDuring = readRenderPriority(file).held;
+ const out = path.join(job.outDir, `${job.slug}.mp4`);
+ await writeFile(out, "render");
+ return { file: out };
+ };
+ const io = { reportsRoot: path.join(root, "reports"), log: () => {}, err: () => {}, deps: { render, styles: {}, probe: async () => 1 }, renderMode: { file, lanes: ed.lanes, signals: false } };
+ try {
+ assert.equal(await takeCommand(["proj", "--id", "p1", "--label", "P", "--set", "render.crf=31", "--full", "--priority"], io), 0);
+ assert.equal(heldDuring, true);
+ assert.equal(existsSync(file), false);
+ assert.deepEqual(ed.calls, ["hold transcription", "hold download", "release transcription", "release download"]);
+ const failing = { ...io, deps: { ...io.deps, render: async () => { throw new Error("cut failed"); } } };
+ assert.equal(await takeCommand(["proj", "--id", "p2", "--label", "P2", "--set", "render.crf=32", "--full", "--priority"], failing), 1);
+ assert.equal(existsSync(file), false);
+ assert.equal(ed.calls.length, 8);
+ assert.ok(JSON.parse(await readFile(path.join(dir, "takes", "p1", "take.json"), "utf8")));
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs
@@ -5,8 +5,11 @@
// umtool take <project> --id <id> --label "<l>" [--group G] [--kind K] [--summary S]
// [--style NAME] [--patch FILE | --patch-json JSON | --set path=value …]
// [--effect NAME] [--at S --dur S | --full] [--quick] [--force] [--progress ndjson]
-// [--from TAKE] [--keep-frames]
+// [--from TAKE] [--keep-frames] [--priority]
// umtool take <project> --id <id> --rebuild made again from its own take.json
+// --priority: render mode for the take's lifetime (renderMode.mjs) — every
+// other heavy job waits for this render, the editor's transcription and
+// download lanes are held, and both are let go at its end, failure or signal.
// umtool takes effects <project> [--json] the effect presets this cut offers (report-to-video/fx.mjs)
// umtool takes make <project> [--recipe FILE] [--only ID,ID] [--force] [--progress ndjson]
// umtool takes make <project> --all-styles [--group G] [--at S --dur S | --full] [--force]
@@ -32,14 +35,15 @@ import {
} from "./takeMaker.mjs";
import { TAKE_FILE, takesDirOf } from "./takes.mjs";
import { fxPresetsFor } from "umtool-report-to-video/fx";
+import { withTakePriority } from "./renderMode.mjs";
import { mergePatch } from "umtool-report-to-video/montage-styles";
export const TAKE_USAGE = [
"usage: umtool take <project> --id <id> --label \"<label>\" [--group G] [--kind similar|different]",
" [--summary S] [--style NAME] [--patch FILE | --patch-json JSON | --set path=value …]",
" [--effect NAME] [--at S --dur S | --full] [--quick] [--force] [--progress ndjson]",
- " [--from TAKE] [--keep-frames]",
- " umtool take <project> --id <id> --rebuild [--at S --dur S | --full] [--from TAKE] [--keep-frames]",
+ " [--from TAKE] [--keep-frames] [--priority]",
+ " umtool take <project> --id <id> --rebuild [--at S --dur S | --full] [--from TAKE] [--keep-frames] [--priority]",
" made again from its own take.json (its stored patch, walked edits included); a window",
" flag renders it over that window instead of its own",
" umtool take <project> --id <id> --label L [--patch F | …] --draft (or --no-render) the take RECORDED,",
@@ -62,6 +66,11 @@ export const TAKE_USAGE = [
"them, and marks the take (out/.keep-frames/asked.json): a later build of it without the flag sets its",
"frames aside in out/.keep-frames/ instead of pruning them. Without it they are pruned, and a --from twin",
"captures the chrome again.",
+ "--priority gives this render the machine (render mode, `umtool render-mode`): every other heavy job",
+ "(e2e suites, next builds, the publish stages, other renders) waits for it, the editor's transcription",
+ "and download lanes are held (only the ones not held already), and both end with the take — done,",
+ "failed or stopped. Close Firefox and other heavy apps while it renders. A take started inside a",
+ "`umtool render-mode on` window renders in that window, flag or not.",
].join("\n");
export const TAKES_USAGE = [
@@ -69,6 +78,7 @@ export const TAKES_USAGE = [
` the recipe's takes, one at a time (default: takes/${RECIPE_FILE}); a take that`,
" exists is skipped unless --force",
" umtool takes make <project> --all-styles [--group G] [--at S --dur S | --full] [--quick] [--force]",
+ " [--priority] (either form: render mode for the whole batch, as `umtool take --priority`)",
` one take per montage style (writes takes/${ALL_STYLES_RECIPE})`,
" umtool takes styles [--json] the montage styles: name, label, summary",
" umtool takes pick <project> <take> [--anyway] use this take: its manifest over the project's",
@@ -195,7 +205,7 @@ async function realDeps() {
* @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, deps?: Record<string, unknown> }} [opts]
* @returns {Promise<number>}
*/
-export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, deps } = {}) {
+export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, deps, renderMode } = {}) {
try {
const p = parse(args);
if (p.has("--help") || !p.positional.length) {
@@ -254,14 +264,19 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
out.log(`render it: umtool take ${project.id} --id ${id} --full`);
return 0;
}
- const r = await makeTake(project.dir, spec, {
- force: p.has("--force") || fromStored,
- from: p.one("--from") ?? null,
- keepFrames: p.has("--keep-frames"),
- emit: out.emit,
- log: out.log,
- ...(deps ?? (await realDeps())),
- });
+ const make = async () =>
+ makeTake(project.dir, spec, {
+ force: p.has("--force") || fromStored,
+ from: p.one("--from") ?? null,
+ keepFrames: p.has("--keep-frames"),
+ emit: out.emit,
+ log: out.log,
+ ...(deps ?? (await realDeps())),
+ });
+ const r = await withTakePriority(
+ { priority: p.has("--priority"), project: project.id, take: id, log: out.log, ...(renderMode ?? {}) },
+ make,
+ );
if (r.skipped) out.log(`take ${id} exists — pass --force to make it again`);
return 0;
} catch (e) {
@@ -302,7 +317,7 @@ async function promote(project, id, p, log, err) {
* @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, deps?: Record<string, unknown> }} [opts]
* @returns {Promise<number>}
*/
-export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, deps } = {}) {
+export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, deps, renderMode } = {}) {
try {
const p = parse(args);
const [sub, ...rest] = p.positional;
@@ -369,13 +384,17 @@ export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = con
}
}
const only = p.one("--only")?.split(",").map((s) => s.trim()).filter(Boolean) ?? null;
- const results = await makeTakes(project.dir, recipe, {
- force: p.has("--force"),
- only,
- emit: out.emit,
- log: out.log,
- ...(deps ?? (await realDeps())),
- });
+ const results = await withTakePriority(
+ { priority: p.has("--priority"), project: project.id, take: null, cmd: `umtool takes make ${project.id}`, log: out.log, ...(renderMode ?? {}) },
+ async () =>
+ makeTakes(project.dir, recipe, {
+ force: p.has("--force"),
+ only,
+ emit: out.emit,
+ log: out.log,
+ ...(deps ?? (await realDeps())),
+ }),
+ );
const failed = results.filter((r) => r.status === "failed");
const made = results.filter((r) => r.status === "made").length;
const skipped = results.filter((r) => r.status === "skipped").length;
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -994,6 +994,7 @@ const windowArgs = (w) => (w === "full" ? ["--full"] : ["--at", String(w.at), "-
* { take: { id?, label, group?, style?, patch?, window?, summary?, kind?, quick? }, force? } New take
* { allStyles: { group?, window?, quick? }, force? } Make all styles
* { rebuild: "<take id>" } Rebuild
+ * any of them with `priority: true`: --priority, render mode for the render (renderMode.mjs)
*
* @param {{ id: string }} project
* @param {Record<string, any>} req
@@ -1005,6 +1006,9 @@ export function takeSteps(project, req, { styles, existing, clipCount, seconds =
const base = { cwd: UMTOOL_DIR, env: {}, ndjson: /** @type {const} */ (true) };
const cli = ["node", umtoolCli()];
const force = req.force === true ? ["--force"] : [];
+ // "Give renders the machine" (the take panel's toggle): render mode for the
+ // job's render (renderMode.mjs; `umtool take … --priority`).
+ const priority = req.priority === true ? ["--priority"] : [];
if (typeof req.rebuild === "string") {
const t = existing.find((x) => x.id === req.rebuild);
if (!t) throw new Error(`no take ${req.rebuild}`);
@@ -1018,7 +1022,7 @@ export function takeSteps(project, req, { styles, existing, clipCount, seconds =
steps: [{
...base,
label: `${/** @type {any} */ (t).draft ? "render" : "rebuild"} take ${t.id}`,
- argv: [...cli, "take", project.id, "--id", t.id, "--rebuild", ...(win ? windowArgs(win) : []), "--progress", "ndjson"],
+ argv: [...cli, "take", project.id, "--id", t.id, "--rebuild", ...(win ? windowArgs(win) : []), ...priority, "--progress", "ndjson"],
timeoutMs: takeTimeoutMs(full, clipCount, seconds),
}],
};
@@ -1036,7 +1040,7 @@ export function takeSteps(project, req, { styles, existing, clipCount, seconds =
steps: [{
...base,
label: `make ${recipe.takes.length} take(s), one per style`,
- argv: [...cli, "takes", "make", project.id, "--all-styles", ...group, ...windowArgs(recipe.window), ...(recipe.quick ? ["--quick"] : []), ...force, "--progress", "ndjson"],
+ argv: [...cli, "takes", "make", project.id, "--all-styles", ...group, ...windowArgs(recipe.window), ...(recipe.quick ? ["--quick"] : []), ...force, ...priority, "--progress", "ndjson"],
timeoutMs: recipe.takes.length * takeTimeoutMs(recipe.window === "full", clipCount, seconds),
}],
};
@@ -1053,7 +1057,7 @@ export function takeSteps(project, req, { styles, existing, clipCount, seconds =
...(spec.summary ? ["--summary", spec.summary] : []),
...(spec.style ? ["--style", spec.style] : []),
...(spec.patch ? ["--patch-json", JSON.stringify(spec.patch)] : []),
- ...windowArgs(spec.window), ...(spec.quick ? ["--quick"] : []), ...force, "--progress", "ndjson",
+ ...windowArgs(spec.window), ...(spec.quick ? ["--quick"] : []), ...force, ...priority, "--progress", "ndjson",
];
return {
kind: `take ${project.id} ${spec.id}`,
diff --git a/umtool/lib/report/takeRender.mjs b/umtool/lib/report/takeRender.mjs
@@ -20,7 +20,10 @@
// build may run beside it while MemAvailable allows; an override of 0 declares
// none, and it runs alone.
// Inside a slot already held (HEAVY_HELD: an e2e run) it passes straight
-// through. A copy of umtool without the checkout's scripts/ runs
+// through. In render mode (`umtool take … --priority`, renderMode.mjs) the
+// take's process carries the hold's RENDER_PRIORITY_TOKEN, and the render
+// inherits it with the rest of the environment: admitted while every other
+// heavy job waits, on the render's floor and cap. A copy of umtool without the checkout's scripts/ runs
// build-video directly, which takes the slot itself (heavy-gate.mjs).
import { execFile, spawn } from "node:child_process";
import { existsSync } from "node:fs";
diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts
@@ -206,6 +206,10 @@ export default defineConfig({
// with. Set here rather than in a step's env: jobView() echoes a step's
// env back to the browser, and this is a token.
`ARCHILYZER_EDITOR_URL=http://127.0.0.1:${STUB_PORT} WORKER_TOKEN=umtool-e2e-token ` +
+ // Render mode's state (common/lib/renderPriority.mjs): the fixture's own,
+ // so a take made here never joins — and the banner never shows — the
+ // machine's render mode, and a --priority take holds the stub's lanes.
+ `RENDER_PRIORITY_FILE=${FIXTURE}/render-priority.json ` +
// Two seconds of pacing per CUT, so the deliver spec can press Stop in
// the middle of a job and prove that cancelling abandons the rest while
// the next run resumes. Read only by bin/cut-from-cache.mjs.
diff --git a/umtool/report-to-video/heavy-gate.test.mjs b/umtool/report-to-video/heavy-gate.test.mjs
@@ -119,6 +119,9 @@ test("with no HEAVY_LOCK_FILE the lock is pinned to the checkout's git common di
execFileSync("git", ["init", "-q", repo]);
mkdirSync(path.join(repo, "scripts"));
copyFileSync(path.join(checkoutRoot(), "scripts", "queue-lock.mjs"), path.join(repo, "scripts", "queue-lock.mjs"));
+ // ...and render mode's state module, which the gate imports.
+ mkdirSync(path.join(repo, "common", "lib"), { recursive: true });
+ copyFileSync(path.join(checkoutRoot(), "common", "lib", "renderPriority.mjs"), path.join(repo, "common", "lib", "renderPriority.mjs"));
const lock = path.join(repo, ".git", "heavy-queue.lock");
const seen = await withEnv(
{ HEAVY: undefined, HEAVY_HELD: undefined, HEAVY_LOCK_FILE: undefined, HEAVY_MIN_FREE_MB: "0" },