commit f3b337aab4180301802fd040374bfbe178f2cdc7
parent 70e85ecd80886114c1b7be24deb28814e6d72905
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 31 Oct 2026 23:46:52 -0400
umtool: render-mode on -- <cmd> holds render mode while a command runs -- the command gets the token in its env, the hold is its pid, released when it exits (done, failed or signalled; the signal passed on), its exit code returned; --print-token prints the token alone; a take inside the chain says it is part of it
The chain trap: a bare `render-mode on` in a script left a window behind and
commands that never got the token waited at the door. withTakePriority's
on/off/signal path is now withRenderHold, shared by both.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
7 files changed, 353 insertions(+), 45 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
@@ -83,6 +83,7 @@ units, a capped scope); `HEAVY_CAP=0` turns that off. Bypasses: `HEAVY=0`,
```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 on [--for 90m] -- <cmd …> # held while <cmd> runs, released when it exits (scripts)
umtool render-mode status | off
pnpm ops render-mode --json '{"on":true,"for":"90m"}' # the same with only pnpm ops; get render-mode
```
@@ -91,7 +92,10 @@ While it is on, every other heavy job (e2e suites, `next build`s, the publish st
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
+not already held; only those are released). **A script uses `render-mode on -- <cmd …>`, never a bare `on`**: the
+command carries the token, the hold is its pid, and it ends when the command exits — a bare `on`
+in a script leaves a window behind and its later commands wait at the door (the chain trap);
+`--print-token` prints the token alone. 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
diff --git a/WORKTREES.md b/WORKTREES.md
@@ -351,6 +351,7 @@ transcription lane, the editor, and e2e servers and browsers beside it. **Render
```sh
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 on [--for 90m] -- <cmd …> # held while <cmd> runs (holder: its pid), off when it exits
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
@@ -366,7 +367,13 @@ While it is on:
- **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.
+ manual window joins it; another command joins with the token `on` prints
+ (`--print-token` prints it alone, for `export RENDER_PRIORITY_TOKEN=$(…)`).
+- **a script wraps its chain: `umtool render-mode on -- <cmd …>`.** The command is spawned
+ with the token in its environment, the hold's holder is the command's pid, and the hold is
+ released when it exits — done, failed, or umtool signalled (the signal is passed on); the
+ exit code is the command's. A bare `on` in a script is the chain trap: the window outlives
+ the script, and a command that never got the token waits at the door behind it.
- **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.
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -70,6 +70,7 @@
// [--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 render-mode on [--for 90m] [--print-token] -- <cmd …> held while <cmd> runs (its env carries the token)
// 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>]
@@ -855,6 +856,9 @@ function usage() {
" 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)",
+ " on [--for D] [--print-token] -- <cmd …>: held while <cmd> runs (its env carries the token,",
+ " the hold is its pid), released when it exits -- the form for a script; --print-token prints",
+ " the token alone on stdout",
" 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)",
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -49,7 +49,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") |
+| `take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json \| --print-token]` · `render-mode on [--for 90m] [--note T] [--print-token] -- <cmd …>` · `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 (`--print-token`: the token alone on stdout, the rest on stderr). **`on … -- <cmd …>` is the form for a script**: the command is spawned with the token in its environment, the hold is the command's pid, and it is released when the command exits — done, failed, or umtool signalled (the signal is passed on); umtool exits with the command's code, and inside a manual window the command joins it. A bare `on` in a script leaves the window behind (the chain trap). `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
@@ -1113,6 +1113,7 @@ 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 on -- sh render-all.sh # a script's chain: held while it runs, off when it exits
umtool render-mode status
umtool render-mode off
```
diff --git a/umtool/lib/report/renderMode.mjs b/umtool/lib/report/renderMode.mjs
@@ -4,7 +4,9 @@
// 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 on [--for 90m] [--note …] [--json | --print-token] a window (a chain of renders)
+// umtool render-mode on [--for 90m] [--note …] -- <cmd …> held while the command runs (holder: its
+// pid; its env carries the token), off when it exits
// umtool render-mode off [--force] [--json]
// umtool render-mode status [--json]
//
@@ -90,55 +92,37 @@ export function lanesLine(state) {
}
/**
- * 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.
+ * Hold render mode while `fn` runs, then let go — done, failed or signalled.
+ * The one on/off/signal path of `withTakePriority` (holder: this process) and
+ * `render-mode on -- <cmd>` (holder: the command's pid). Returns
+ * `{ran: false, held}` without calling `fn` when another hold won the claim.
*
* @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>}
+ * @param {{ holder: import("yt-dlp-transcript-common/lib/renderPriority.mjs").RenderHolder, by: string,
+ * log: (s: string) => void, env?: Record<string, string | undefined>, file?: string, lanes?: any,
+ * signals?: boolean, token?: string, forMs?: number | null, note?: string | null,
+ * onLine?: (state: any) => void, onSignal?: (sig: NodeJS.Signals) => void }} o
+ * @param {(token: string) => Promise<T>} fn
+ * @returns {Promise<{ ran: true, value: T } | { ran: false, held: any }>}
*/
-export async function withTakePriority(o, fn) {
+export async function withRenderHold(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",
+ holder: o.holder,
+ by: o.by,
+ forMs: o.forMs ?? null,
+ note: o.note ?? null,
editor: lanes ? editorConfig(env).url : null,
lanes,
+ ...(o.token ? { token: o.token } : {}),
});
- 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();
- }
+ if (!on.ok || !on.state) return { ran: false, held: on.held ?? null };
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}`);
+ o.onLine?.(on.state);
let ended = false;
const end = async () => {
@@ -163,6 +147,11 @@ export async function withTakePriority(o, fn) {
for (const sig of /** @type {NodeJS.Signals[]} */ (["SIGINT", "SIGTERM", "SIGHUP"])) {
const h = () => {
const code = 128 + ({ SIGINT: 2, SIGTERM: 15, SIGHUP: 1 }[sig] ?? 0);
+ try {
+ o.onSignal?.(sig);
+ } catch {
+ /* the child is gone already */
+ }
setTimeout(() => process.exit(code), 10_000).unref();
void end().finally(() => process.exit(code));
};
@@ -171,15 +160,167 @@ export async function withTakePriority(o, fn) {
}
}
try {
- return await fn();
+ return { ran: true, value: await fn(token) };
} finally {
for (const [sig, h] of handlers) process.off(sig, h);
await end();
}
}
+/**
+ * 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)
+ * inside `render-mode on -- …` the chain's hold: this take carries its token already
+ * --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 (env[RENDER_PRIORITY_TOKEN_ENV] === status.state.token) {
+ o.log(`render mode is on (${describeRenderPriority(status.state)}) — this take is part of 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 cmd = o.cmd ?? `umtool take ${o.project}${o.take ? ` --id ${o.take}` : ""}`;
+ const r = await withRenderHold(
+ {
+ holder: { pid: process.pid, cmd, project: o.project, take: o.take ?? null },
+ by: "umtool take --priority",
+ log: o.log,
+ env,
+ file,
+ lanes: o.lanes,
+ signals: o.signals,
+ onLine: (state) => {
+ o.log(`render mode on for this take — ${lanesLine(state)}`);
+ o.log(` ${RENDER_MODE_REMINDER}`);
+ },
+ },
+ () => fn(),
+ );
+ if (r.ran) return r.value;
+ // Another hold went on between the look and the claim: render as any job.
+ o.log(`render mode is held by another render${r.held ? ` (${describeRenderPriority(r.held)})` : ""} — this one waits for it`);
+ return fn();
+}
+
+/** Quote one argv word for a log line, as a shell would read it. */
+function shellWord(w) {
+ return /^[\w@%+=:,./-]+$/.test(w) ? w : `'${String(w).replace(/'/g, "'\\''")}'`;
+}
+
+/**
+ * `umtool render-mode on [--for D] [--note T] -- <cmd…>`: the command runs in
+ * render mode and the hold ends when it does. The command is spawned with the
+ * hold's token in RENDER_PRIORITY_TOKEN (so every heavy job under it is the
+ * render), the hold's holder is the command's pid (a crash of this process
+ * leaves a hold that ends with the command), and the hold is released when the
+ * command exits — done, failed, or this process signalled (the signal is
+ * passed on to the command). Exits with the command's code.
+ *
+ * Inside a manual window it joins (the window's token; the window stays on);
+ * beside another render's hold it runs as any job and its heavy work waits.
+ *
+ * @param {string[]} cmd
+ * @param {{ forMs: number | null, note: string | null, printToken: boolean, log: (s: string) => void,
+ * err: (s: string) => void, env: Record<string, string | undefined>, file: string, lanes: any,
+ * signals?: boolean, spawnImpl?: typeof import("node:child_process").spawn }} o
+ * @returns {Promise<number>}
+ */
+async function renderModeChain(cmd, o) {
+ const { spawn } = await import("node:child_process");
+ const { randomBytes } = await import("node:crypto");
+ const spawnImpl = o.spawnImpl ?? spawn;
+ const say = o.printToken ? o.err : o.log; // --print-token: stdout carries the token alone
+ const full = cmd.map(shellWord).join(" ");
+ const line = full.length > 160 ? `${full.slice(0, 159)}…` : full;
+ /** @param {string | undefined} token */
+ const run = (token) => {
+ const childEnv = { ...o.env };
+ if (token) childEnv[RENDER_PRIORITY_TOKEN_ENV] = token;
+ else delete childEnv[RENDER_PRIORITY_TOKEN_ENV];
+ const child = spawnImpl(cmd[0], cmd.slice(1), { stdio: "inherit", env: /** @type {NodeJS.ProcessEnv} */ (childEnv) });
+ const exited = new Promise((resolve) => {
+ child.on("error", (e) => {
+ o.err(`render-mode: could not run ${cmd[0]}: ${e.message}`);
+ resolve(127);
+ });
+ child.on("exit", (code, sig) => resolve(code ?? 128 + (sig ? ({ SIGINT: 2, SIGTERM: 15, SIGHUP: 1, SIGKILL: 9 }[sig] ?? 1) : 1)));
+ });
+ return { child, exited: /** @type {Promise<number>} */ (exited) };
+ };
+
+ const status = readRenderPriority(o.file);
+ if (status.held && status.state) {
+ const joins = !status.state.holder;
+ say(
+ joins
+ ? `render mode is on (${describeRenderPriority(status.state)}) — ${line} runs in it; the window stays on`
+ : `render mode is held by another render (${describeRenderPriority(status.state)}) — ${line} runs without it; its heavy work waits`,
+ );
+ if (o.printToken && joins) o.log(status.state.token);
+ return run(joins ? status.state.token : undefined).exited;
+ }
+
+ // The token is chosen before the spawn so the command carries it from its
+ // first instruction; the hold is claimed with the command's pid as holder.
+ const token = randomBytes(8).toString("hex");
+ if (o.printToken) o.log(token);
+ const { child, exited } = run(token);
+ if (child.pid == null) return exited; // never started ("error" says why)
+ const r = await withRenderHold(
+ {
+ holder: { pid: child.pid, cmd: full.slice(0, 200) },
+ by: "umtool render-mode on --",
+ token,
+ forMs: o.forMs,
+ note: o.note,
+ log: say,
+ env: { ...o.env },
+ file: o.file,
+ lanes: o.lanes,
+ signals: o.signals,
+ onLine: (state) => {
+ say(`render mode ON for ${line} (pid ${child.pid}) — ${lanesLine(state)}`);
+ say(` ${RENDER_MODE_REMINDER}`);
+ },
+ onSignal: (sig) => {
+ child.kill(sig);
+ },
+ },
+ () => exited,
+ );
+ if (r.ran) return r.value;
+ say(`render mode was taken by another render meanwhile${r.held ? ` (${describeRenderPriority(r.held)})` : ""} — ${line} runs without it; its heavy work waits`);
+ return exited;
+}
+
const USAGE = [
- "usage: umtool render-mode on [--for 90m] [--note TEXT] [--json]",
+ "usage: umtool render-mode on [--for 90m] [--note TEXT] [--json | --print-token]",
+ " umtool render-mode on [--for 90m] [--note TEXT] [--print-token] -- <command …>",
" umtool render-mode off [--force] [--json]",
" umtool render-mode status [--json]",
"",
@@ -192,16 +333,27 @@ const USAGE = [
"--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`.",
+ "",
+ "`on -- <command …>` is the form for a script: the command runs in render mode with the token in",
+ "its environment, the hold is the command's (its pid), and it ends when the command exits — done,",
+ "failed or signalled (a signal is passed on); the exit code is the command's. No window is left",
+ "behind for a script that forgot `off`. --print-token prints the token alone on stdout (the other",
+ "lines go to stderr), for `export RENDER_PRIORITY_TOKEN=$(umtool render-mode on --print-token)`.",
"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`.
+ * `umtool render-mode on|off|status`, and `on -- <command …>`.
* @param {string[]} args
- * @param {{ log?: (s: string) => void, err?: (s: string) => void, env?: Record<string, string | undefined>, file?: string, lanes?: any }} [opts]
+ * @param {{ log?: (s: string) => void, err?: (s: string) => void, env?: Record<string, string | undefined>, file?: string, lanes?: any,
+ * signals?: boolean, spawnImpl?: typeof import("node:child_process").spawn }} [opts]
* @returns {Promise<number>}
*/
-export async function renderModeCommand(args, { log = console.log, err = console.error, env = process.env, file, lanes } = {}) {
+export async function renderModeCommand(allArgs, { log = console.log, err = console.error, env = process.env, file, lanes, signals, spawnImpl } = {}) {
+ // `on … -- <command …>`: everything after the first `--` is the command.
+ const dash = allArgs.indexOf("--");
+ const args = dash >= 0 ? allArgs.slice(0, dash) : allArgs;
+ const cmd = dash >= 0 ? allArgs.slice(dash + 1) : null;
const valued = new Set(["--for", "--note"]);
const sub = args.find((a, i) => !a.startsWith("--") && !valued.has(args[i - 1]));
const flag = (n) => {
@@ -217,6 +369,15 @@ export async function renderModeCommand(args, { log = console.log, err = console
err(USAGE);
return 2;
}
+ if (cmd && (sub !== "on" || !cmd.length)) {
+ err(sub === "on" ? "render-mode on --: name the command to run after --" : `render-mode ${sub} takes no command (only \`on -- <command …>\` does)`);
+ return 2;
+ }
+ const printToken = args.includes("--print-token");
+ if (printToken && json) {
+ err("--print-token and --json: one or the other");
+ return 2;
+ }
const where = file ?? renderModeFile(env);
const cfg = editorConfig(env);
const editor = lanes !== undefined ? lanes : editorLanes(cfg);
@@ -247,6 +408,7 @@ export async function renderModeCommand(args, { log = console.log, err = console
err(`--for wants a duration: 90m, 2h, 1h30m, or minutes — not "${raw}"`);
return 2;
}
+ if (cmd) return renderModeChain(cmd, { forMs, note: flag("--note") ?? null, printToken, log, err, env, file: where, lanes: editor, signals, spawnImpl });
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 });
@@ -257,6 +419,11 @@ export async function renderModeCommand(args, { log = console.log, err = console
out({ ok: true, state: r.state, file: where, reminder: RENDER_MODE_REMINDER });
return 0;
}
+ if (printToken) {
+ log(r.state.token);
+ err(`render mode ON until ${clockOf(r.state.until)} — ${lanesLine(r.state)}; end it: umtool render-mode off`);
+ 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:");
diff --git a/umtool/lib/report/renderMode.test.mjs b/umtool/lib/report/renderMode.test.mjs
@@ -253,3 +253,128 @@ test("umtool take --priority: the take is made inside render mode, and render mo
await rm(root, { recursive: true, force: true });
}
});
+
+test("render-mode on -- <cmd>: held while the command runs (its pid the holder, its env the token), released at its exit, its code returned", async () => {
+ const dir = mkdtempSync(path.join(tmpdir(), "render-mode-chain-"));
+ const file = path.join(dir, "state.json");
+ const seen = path.join(dir, "seen.json");
+ const ed = fakeLanes({ download: true });
+ const out = [];
+ const err = [];
+ // The command waits for the hold (its lanes recorded), then records what it
+ // saw — its env's token, the state file, its own pid — and exits 3.
+ const waitThen = `const fs = require("node:fs"); const t0 = Date.now();
+(function look() {
+ try {
+ const s = JSON.parse(fs.readFileSync(${JSON.stringify(file)}, "utf8"));
+ if (s.lanesHeld && s.lanesHeld.length) {
+ fs.writeFileSync(${JSON.stringify(seen)}, JSON.stringify({ token: process.env.RENDER_PRIORITY_TOKEN, state: s, pid: process.pid }));
+ process.exit(3);
+ }
+ } catch {}
+ if (Date.now() - t0 > 10000) process.exit(9);
+ setTimeout(look, 20);
+})();`;
+ const code = await renderModeCommand(["on", "--note", "the cut", "--", process.execPath, "-e", waitThen], {
+ log: (l) => out.push(l),
+ err: (l) => err.push(l),
+ env: { PATH: process.env.PATH },
+ file,
+ lanes: ed.lanes,
+ signals: false,
+ });
+ assert.equal(code, 3, "the command's exit code");
+ const s = JSON.parse(readFileSync(seen, "utf8"));
+ assert.equal(s.token, s.state.token, "the command carries the hold's token");
+ assert.equal(s.state.holder.pid, s.pid, "the hold is the command's pid");
+ assert.equal(s.state.note, "the cut");
+ assert.equal(s.state.until, null, "no window: it ends with the command");
+ assert.match(s.state.holder.cmd, /-e/);
+ assert.equal(existsSync(file), false, "released at the command's exit");
+ assert.deepEqual(ed.calls, ["hold transcription", "release transcription"], "download was held already: left alone");
+ assert.match(out.join("\n"), /render mode ON for [\s\S]* \(pid \d+\) — lanes held: transcription/);
+ assert.match(out.join("\n"), /render mode off — lanes released: transcription/);
+});
+
+test("render-mode on -- <cmd>: --print-token puts the token alone on stdout; a failing spawn returns 127 and holds nothing", async () => {
+ const file = tmpFile();
+ const ed = fakeLanes();
+ const out = [];
+ const err = [];
+ const io = { log: (l) => out.push(l), err: (l) => err.push(l), env: { PATH: process.env.PATH }, file, lanes: ed.lanes, signals: false };
+ assert.equal(await renderModeCommand(["on", "--print-token", "--", process.execPath, "-e", "process.exit(0)"], io), 0);
+ assert.equal(out.length, 1);
+ assert.match(out[0], /^[0-9a-f]{16}$/);
+ assert.ok(err.some((l) => /render mode ON for/.test(l)));
+ assert.equal(existsSync(file), false);
+ assert.equal(await renderModeCommand(["on", "--", path.join(tmpdir(), "no-such-command-render-mode")], io), 127);
+ assert.equal(existsSync(file), false);
+ assert.equal(await renderModeCommand(["on", "--"], io), 2, "no command");
+ assert.equal(await renderModeCommand(["off", "--", "true"], io), 2, "only on runs a command");
+
+ // The window form with --print-token: the token alone on stdout, and it is the window's.
+ out.length = 0;
+ assert.equal(await renderModeCommand(["on", "--for", "10m", "--print-token"], io), 0);
+ assert.deepEqual(out, [readRenderPriorityState(file).token]);
+ assert.equal(await renderModeCommand(["on", "--print-token", "--json"], io), 2);
+
+ // Inside that window a chained command joins it: the window's token, the window left on.
+ const seen = path.join(path.dirname(file), "seen.txt");
+ const code = await renderModeCommand(["on", "--", process.execPath, "-e", `require("node:fs").writeFileSync(${JSON.stringify(seen)}, process.env.RENDER_PRIORITY_TOKEN || "")`], io);
+ assert.equal(code, 0);
+ assert.equal(readFileSync(seen, "utf8"), readRenderPriorityState(file).token);
+ assert.equal(readRenderPriority(file).held, true, "the window outlives the command");
+ assert.equal(await renderModeCommand(["off"], io), 0);
+});
+
+test("render-mode on -- <cmd> signalled: the signal reaches the command and the hold ends", async () => {
+ const dir = mkdtempSync(path.join(tmpdir(), "render-mode-chain-sig-"));
+ const file = path.join(dir, "state.json");
+ const log = path.join(dir, "lanes.log");
+ const childLog = path.join(dir, "child.log");
+ const script = path.join(dir, "chain.mjs");
+ writeFileSync(
+ script,
+ `import { appendFileSync } from "node:fs";
+import { renderModeCommand } 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"),
+};
+const child = 'process.on("SIGTERM",()=>{require("node:fs").appendFileSync(${JSON.stringify(childLog)},"TERM\\\\n");process.exit(0)});require("node:fs").appendFileSync(${JSON.stringify(childLog)},"ready\\\\n");setInterval(()=>{},1000)';
+process.exit(await renderModeCommand(["on", "--", process.execPath, "-e", child], { log: (l) => console.log(l), err: (l) => console.error(l), env: { PATH: process.env.PATH }, file: ${JSON.stringify(file)}, lanes }));
+`,
+ );
+ const proc = spawn(process.execPath, [script], { stdio: ["ignore", "pipe", "pipe"] });
+ let out = "";
+ proc.stdout.on("data", (d) => (out += d));
+ proc.stderr.on("data", (d) => (out += d));
+ const t0 = Date.now();
+ while (!/render mode ON for/.test(out) || !existsSync(childLog)) {
+ if (Date.now() - t0 > 15_000) throw new Error(`never went on: ${out}`);
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ const held = readRenderPriority(file);
+ assert.equal(held.held, true);
+ assert.notEqual(held.state.holder.pid, proc.pid, "the holder is the command, not umtool");
+ proc.kill("SIGTERM");
+ const code = await new Promise((r) => proc.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");
+ for (let i = 0; i < 100 && !readFileSync(childLog, "utf8").includes("TERM"); i += 1) await new Promise((r) => setTimeout(r, 20));
+ assert.equal(readFileSync(childLog, "utf8"), "ready\nTERM\n", "the command got the signal");
+});
+
+test("a take started under render-mode on -- … is part of that hold (no 'waits for it')", async () => {
+ const file = tmpFile();
+ writeFileSync(file, JSON.stringify({ version: 1, token: "chain", since: new Date().toISOString(), until: null, holder: { pid: process.pid, cmd: "sh render-all.sh" }, lanesHeld: [] }));
+ const lines = [];
+ const env = { RENDER_PRIORITY_TOKEN: "chain" };
+ await withTakePriority({ priority: true, project: "p", take: "t", log: (l) => lines.push(l), env, file, lanes: null, signals: false }, async () => {
+ assert.equal(env.RENDER_PRIORITY_TOKEN, "chain");
+ });
+ assert.match(lines[0], /this take is part of it/);
+ assert.equal(readRenderPriorityState(file).token, "chain");
+});