// CANCEL A TAKE WHILE IT RENDERS (UI notes 2026-10-30, item 19: "a cancel // button while it renders"). // // The render belongs to whichever process holds the take's build lock // (`takes//.building.json`, takePrune.mjs): the app's take job (a `umtool // take` the job runner spawned), or a `umtool take` an agent started in a // terminal. Nothing outside that process can stop its render CLEANLY -- a // signal from here would leave its scratch behind, or reach a process group it // does not own -- so a cancel is a REQUEST the take maker answers: // // requestCancel writes `takes//.cancel.json` {at, by, pid} beside a // LIVE build lock on this machine (a take that is not // rendering, or renders on another host, is refused in words) // watchCancel the take maker polls for it while it holds the lock; seen, // it stops its render (takeRender.mjs: the render's whole // process group, TERM then KILL), removes the half-made // render manifest, and // markCancelled writes `takes//cancelled.json` {at, by, label, rebuild} // -- what the list shows: a first render cancelled is a work // dir with this and no take.json (folded away, deletable), a // rebuild cancelled keeps its last take whole and says so // // The take maker then rejects with TakeCancelled; its build lock goes in its // own `finally`, and so does render mode when this take held it // (renderMode.mjs withRenderHold's `finally`). `releaseTakeHold` is the // belt-and-braces for a process that went without letting go. // // Plain ESM: the CLI runs it under bare node. import { readdir, readFile, rename, unlink, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { BUILD_LOCK, lockIsLive, readBuildLock } from "./takePrune.mjs"; import { isTakeId, takesDirOf, TAKE_FILE } from "./takes.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const CANCEL_FILE = ".cancel.json"; export const CANCELLED_FILE = "cancelled.json"; /** How often the take maker looks for a cancel request (ms). */ export const CANCEL_POLL_MS = 400; export class TakeCancelled extends Error { /** @param {string} take @param {string} [by] */ constructor(take, by = "") { super(`take ${take} was cancelled${by ? ` (${by})` : ""} — its render stopped; nothing was written over a finished take`); this.take = take; this.cancelled = true; } } const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null); async function writeJson(file, doc) { const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); } /** * Ask the render of take `takeId` to stop. Refused unless its build lock is * live and on this machine. * * @param {string} projectDir * @param {string} takeId * @param {{ by?: string, now?: () => Date, host?: string, alive?: (pid: number) => boolean }} [opts] * @returns {Promise<{ lock: Record, file: string }>} */ export async function requestCancel(projectDir, takeId, { by = "the Takes page", now = () => new Date(), host = os.hostname(), alive } = {}) { if (!isTakeId(takeId)) throw new Error("not a take id"); const dir = path.join(takesDirOf(projectDir), takeId); const lock = await readBuildLock(path.join(dir, BUILD_LOCK)); if (!lock || !lockIsLive(lock, { host, ...(alive ? { alive } : {}) })) throw new Error(`take ${takeId} is not rendering — nothing to cancel`); if (lock.host && lock.host !== host) throw new Error(`take ${takeId} is rendering on ${lock.host}: cancel it there`); const file = path.join(dir, CANCEL_FILE); await writeJson(file, { at: now().toISOString(), by, pid: lock.pid ?? null }); return { lock, file }; } /** * Poll for a cancel request in `takeDir`; call `onCancel(request)` once when one * appears. A request older than the watch (left by a crashed run) is cleared * first. Returns stop(). * * @param {string} takeDir * @param {(req: Record) => void} onCancel * @param {{ intervalMs?: number }} [opts] */ export function watchCancel(takeDir, onCancel, { intervalMs = CANCEL_POLL_MS } = {}) { const file = path.join(takeDir, CANCEL_FILE); let done = false; let busy = false; const ready = unlink(file).catch(() => {}); const timer = setInterval(() => { if (done || busy) return; busy = true; void ready .then(() => readJson(file)) .then((req) => { if (req && !done) { done = true; clearInterval(timer); onCancel(req); } }) .finally(() => { busy = false; }); }, intervalMs); timer.unref?.(); return () => { done = true; clearInterval(timer); }; } /** * Record that take `takeId`'s render was cancelled (and clear the request). * * @param {string} projectDir * @param {string} takeId * @param {{ by?: string, label?: string | null, rebuild?: boolean, at?: string, now?: () => Date }} info */ export async function markCancelled(projectDir, takeId, { by = "", label = null, rebuild = false, at, now = () => new Date() } = {}) { const dir = path.join(takesDirOf(projectDir), takeId); const doc = { at: at ?? now().toISOString(), by, label, rebuild }; await writeJson(path.join(dir, CANCELLED_FILE), doc); await unlink(path.join(dir, CANCEL_FILE)).catch(() => {}); return doc; } /** A take's cancelled.json, or null. */ export async function readCancelled(projectDir, takeId) { if (!isTakeId(takeId)) return null; const doc = await readJson(path.join(takesDirOf(projectDir), takeId, CANCELLED_FILE)); return doc && typeof doc === "object" && typeof doc.at === "string" ? doc : null; } /** * The take directories that are not (or not yet) takes: a first render in * progress (a live build lock, no take.json), a first render cancelled * (cancelled.json, no take.json) and a first render that FAILED (its own * record, renderRecord.mjs, says failed -- or says running and its process is * gone). What the Takes page lists beside the takes: the first with Cancel, * the second folded away with Delete, the third in the open with its error. * * @param {string} projectDir * @param {{ host?: string, alive?: (pid: number) => boolean }} [opts] * @returns {Promise<{ rendering: Array<{ id: string, label: string | null, pid: number | null, startedAt: string | null, from: string | null }>, cancelled: Array<{ id: string, label: string | null, at: string, by: string }>, failed: Array<{ id: string, label: string | null, record: any }> }>} */ export async function takeWorkDirs(projectDir, opts = {}) { const root = takesDirOf(projectDir); const names = await readdir(root).catch(() => []); const rendering = []; const cancelled = []; const failed = []; const { readRenderRecord } = await import("./renderRecord.mjs"); for (const id of names.sort()) { if (!isTakeId(id)) continue; const dir = path.join(root, id); const hasTake = await readFile(path.join(dir, TAKE_FILE), "utf8").then(() => true, () => false); if (hasTake) continue; const lock = await readBuildLock(path.join(dir, BUILD_LOCK)); if (lock && lockIsLive(lock, opts.host || opts.alive ? { ...(opts.host ? { host: opts.host } : {}), ...(opts.alive ? { alive: opts.alive } : {}) } : undefined)) { rendering.push({ id, label: typeof lock.label === "string" ? lock.label : null, pid: Number(lock.pid) || null, startedAt: lock.startedAt ?? null, from: lock.from ?? null }); continue; } const c = await readCancelled(projectDir, id); if (c) { cancelled.push({ id, label: c.label ?? null, at: c.at, by: c.by ?? "" }); continue; } const rec = await readRenderRecord(dir); if (rec && rec.state === "failed") failed.push({ id, label: rec.label ?? null, record: rec }); } return { rendering, cancelled, failed }; } const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); /** * Release render mode when take `takeId` of `projectId` holds it and its * holder is gone (the take maker's own `finally` normally does this; a process * killed outright cannot). Returns the lanes released, or null when the take * held nothing. * * @param {string} projectId * @param {string} takeId * @param {{ file?: string, lanes?: any, isAlive?: (pid: number) => boolean }} [opts] */ export async function releaseTakeHold(projectId, takeId, opts = {}) { const { editorLanes, renderModeFile } = await import("./renderMode.mjs"); const { editorConfig } = await import("./fetchWindows.mjs"); const { readRenderPriorityState, renderModeOff } = await import("yt-dlp-transcript-common/lib/renderPriority.mjs"); const file = opts.file ?? renderModeFile(); const st = readRenderPriorityState(file); const h = st?.holder; if (!st || st.ended || !h || h.take !== takeId || (h.project && h.project !== projectId)) return null; const alive = opts.isAlive ?? ((pid) => { try { process.kill(pid, 0); return true; } catch { return false; } }); if (Number(h.pid) > 0 && alive(Number(h.pid))) return null; const off = await renderModeOff({ file, token: st.token, lanes: opts.lanes !== undefined ? opts.lanes : editorLanes(editorConfig(process.env)) }); return { released: off.released ?? [], failed: off.failed ?? [] }; } /** * Cancel take `takeId`'s render and wait for it to stop: the request * (requestCancel), the take maker answering it within `waitMs`, then -- when * it has not, and `fallback` can stop the process that holds the lock (the * app's job runner, for a take it spawned) -- that. Render mode is let go if * this take held it and did not let go itself. * * @param {{ id: string, dir: string }} project * @param {string} takeId * @param {{ by?: string, waitMs?: number, pollMs?: number, fallback?: (lock: Record) => boolean, isAlive?: (pid: number) => boolean, renderModeFile?: string, lanes?: any }} [opts] * @returns {Promise<{ stopped: boolean, how: "the take maker" | "the job runner" | null, cancelled: Record | null, renderMode: { released: string[], failed: unknown[] } | null, said: string }>} */ export async function cancelTake(project, takeId, { by = "the Takes page", waitMs = 15_000, pollMs = 250, fallback, isAlive, renderModeFile: rmFile, lanes } = {}) { const { lock } = await requestCancel(project.dir, takeId, { by, ...(isAlive ? { alive: isAlive } : {}) }); const lockFile = path.join(takesDirOf(project.dir), takeId, BUILD_LOCK); const gone = async () => { const l = await readBuildLock(lockFile); return !l || Number(l.pid) !== Number(lock.pid) || !lockIsLive(l, isAlive ? { alive: isAlive } : undefined); }; let how = null; const until = Date.now() + waitMs; while (Date.now() < until) { if (await gone()) { how = "the take maker"; break; } await sleep(pollMs); } if (!how && fallback && fallback(lock)) { const late = Date.now() + 10_000; while (Date.now() < late) { if (await gone()) { how = "the job runner"; break; } await sleep(pollMs); } } const renderMode = await releaseTakeHold(project.id, takeId, { ...(rmFile ? { file: rmFile } : {}), ...(lanes !== undefined ? { lanes } : {}), ...(isAlive ? { isAlive } : {}) }).catch(() => null); // A take stopped by the job runner never wrote its own mark: this one does. let cancelled = await readCancelled(project.dir, takeId); if (how === "the job runner" && !cancelled) cancelled = await markCancelled(project.dir, takeId, { by, label: lock.label ?? null }).catch(() => null); const said = how ? `take ${takeId}: its render stopped (${how})${renderMode?.released?.length ? ` — render mode off, lanes released: ${renderMode.released.join(", ")}` : renderMode ? " — render mode off" : ""}` : `take ${takeId}: asked to stop (pid ${lock.pid}); it has not yet — it stops at its next check, or cancel it where it runs`; return { stopped: !!how, how, cancelled, renderMode, said }; }