Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

82.9 KB
Raw Blame
// `fuobe worker run`: the worker's loop (docs/gpu-workers.md). It beats to the studio, keeps its own ComfyUI running
// only while it may work, takes one job at a time with the same runner the browser uses, checks each graph itself,
// cleans up after each job, and pauses itself when another program uses the GPU.
//
// It also keeps jobs going through trouble: finished results stay on its disk until the studio has them (hold.mjs), so a
// stop before the upload never runs a job twice; every call to the studio follows one retry policy (retry.mjs); a job
// that stalls or runs past its run limit goes back to the line and a stuck ComfyUI is started again; a ComfyUI that ran
// out of memory is freed and the job sent once more; a job its ComfyUI stopped on twice fails, not the worker; inputs are
// read from the studio once and every clip and sound is made again by ffmpeg (media.mjs); the PC stays awake while it
// holds a job or waits for one (awake.mjs); and it looks at its model folders again every 10 minutes.
//
// Studio jobs first (turns.mjs, local-work.mjs): with a turns folder set, local ComfyUI work on the PC is told apart
// from other programs. Another program still pauses the worker as before. Local ComfyUI work instead gets a request for
// a turn, and the worker waits for the answer with its jobs kept in their place.
//
// The CPU slot (worker.json `cpuSlot: true`): beside its GPU's job it runs one CPU task at a time, claimed for itself:
// light CPU work (joins, trims, adding sound, loops, Ken Burns, filters) on a second ComfyUI of its own that runs on the
// CPU only, and finishing jobs (finish.mjs: the 3D finish, camera paths) with its own code. Every picture of an account's
// job is made again from its pixels before anything reads it (picture.mjs).
//
// The text slot (worker.json `textSlot`, text.mjs): the studio's free text helper, answered by a llama.cpp server the
// worker starts itself, on the GPU when there is room, else on the CPU. Its memory counts as the worker's own.
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { StayAwake } from "./awake.mjs";
import { allowedNodes, cleanJob, emptyFolders, graphCheck, inputRules } from "./checks.mjs";
import { folders, GuardMissing, OwnComfy, PortBusy, yamlFolders } from "./comfy.mjs";
import { ffmpegOf, PROTOCOL, protocolOf, readControl, saveConfig, savedConfig, writeControl, writeStatus } from "./config.mjs";
import { BRIEF_COOL_DOWN_MS, BRIEF_EVERY_MS, BRIEF_PAUSE_MS, GpuWatch, MID_JOB_GRACE_MS, othersOf, readGpu, readGpuGen, readGpuTotal } from "./gpu.mjs";
import { Hold } from "./hold.mjs";
import { asListed, inventoryHash, listedNames, loadedPacks, missingModelDirs, modelFiles, packFolders, packsAsSeen, readLoaded, runtimeFileList, writeLoaded } from "./inventory.mjs";
import { freeLocal, localIdle, readCounters, readListeners, readLock, splitMemory, unknownHolder } from "./local-work.mjs";
import { takeLock, workerLives } from "./lock.mjs";
import { finishers } from "./finish.mjs";
import { ffmpegVersion, fileSize, mediaKind, outputCap, reencode } from "./media.mjs";
import { modelAgain, modelFormat } from "./model-file.mjs";
import { canCleanPictures, cleanPicture, isPicture } from "./picture.mjs";
import { previewShrinker } from "./preview.mjs";
import { withPlainResults } from "./results.mjs";
import { detectsFaces, runSelfCheck } from "./self-check.mjs";
import { LogRing } from "./log-ring.mjs";
import { failure, Reach, retrying } from "./retry.mjs";
import { builtCatalogVersion, ceilingOf, ceilingWords, graphInside, laneMap, readPcAnswers, workerCatalog } from "./tickets.mjs";
import { TEXT_DRAIN_MS, TextSlot, textSlotOf, textTurn } from "./text.mjs";
import { CpuMeter, ramNow, readSensors, STATS_SEND_MS, statsOf } from "./stats.mjs";
import { RAM_REUSE_MS, ramGuardOf, ramSplit, RamWatch, readProcs } from "./ram.mjs";
import { readLocalWork, SiteTurns, writeMode, writeSite } from "./turns.mjs";
import { CodeWatch, headOf, restartDue, UPDATE_DEFER_MAX_MS } from "./update.mjs";

const here = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(here, "../../..");

export const VERSION = (() => {
  try {
    return JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).version ?? "0.0.0";
  } catch {
    return "0.0.0";
  }
})();

/** The studio's catalog, as this worker build has it. */
export function loadRequirements(file = path.join(ROOT, "workflows/comfyui/requirements.json")) {
  return JSON.parse(fs.readFileSync(file, "utf8"));
}

const HOUR = 3_600_000;
/** After a failed face self-check, the wait before the next try of a check that did not run to the end. */
export const SELF_CHECK_RETRY_MS = 5_000;
/** A face self-check that failed twice (once more after a restart of its ComfyUI): face jobs wait this long, then it checks again. */
export const SELF_CHECK_PAUSE_MS = 5 * 60_000;
/**
 * A face self-check that times out less than this long after its last GPU job ended (or while its text slot answers on
 * the GPU) only waited for a busy GPU: it is "not checked yet", never a fault of its ComfyUI.
 */
export const FACE_SETTLE_MS = 60_000;
/** How long the last counters read that worked stands in for one that failed. */
export const COUNTERS_REUSE_MS = 90_000;
/** Busy readings in a row (5 s apart) that only the GPU's total decided, before they pause the worker. */
export const TOTAL_BUSY_READINGS = 6;
/** A GPU reading (every 5 s) says how busy the GPU is for this long; after that, how busy it is is unknown (null). */
export const GPU_BUSY_FRESH_MS = 30_000;

/** The worker looks at its model folders again this often (a folder that comes back after a restart counts). */
export const RESCAN_MS = 10 * 60_000;

/**
 * It checks that every model folder is there this often. While one isn't (a drive still locked, or not connected yet
 * after a restart), it takes no new job and keeps the studio's list of its files as it was.
 */
export const MODELS_CHECK_MS = 60_000;

/**
 * A one-second wait in the worker's loop that took longer than this means the PC slept (the process was stopped). The
 * next beat says how long (`slept`), so a job the studio took back meanwhile counts against no one.
 */
export const SLEPT_MS = 60_000;

/**
 * After a claim that found no job for a slot, that slot asks again only this long after (ms): two idle slots never ask
 * more often than the studio's limit allows.
 */
export const IDLE_CLAIM_MS = 3000;

/**
 * The shortest wait after a claim that found nothing while the last beat said a person's job waits that this worker may
 * take now (ms): it asks again soon, but never once a second for as long as that word lasts (a beat comes every 10 s).
 */
export const CLAIM_GAP_MS = 1500;

/**
 * May a slot claim now: `missedAt` is when its last claim found nothing (-Infinity after a job, or before any claim). Not
 * before `idleMs` has gone by since, or CLAIM_GAP_MS while a person's job waits for it (`claimable`).
 */
export const claimDue = (t, missedAt, claimable = 0, idleMs = IDLE_CLAIM_MS) => t - missedAt >= (claimable > 0 ? Math.min(CLAIM_GAP_MS, idleMs) : idleMs);

/**
 * While the owner's own job waits for this worker and local ComfyUI work keeps the GPU's memory, the worker looks at
 * that work's /queue at most once in this long (ms).
 */
export const IDLE_LOOK_MS = 10_000;

/** After it asked idle local ComfyUI work to free its memory, the worker may take the owner's job for this long (ms). */
export const ROOM_MS = 30_000;

/** A worker token as the studio makes them. */
const NEXT_TOKEN = /^fuobe_wkr_[A-Za-z0-9_-]{43}$/;

/** Kept results that the studio hasn't taken for this long are deleted (the studio drops its jobs after a day). */
export const HOLD_MAX_AGE_MS = 24 * HOUR;

/**
 * While it may not work, it asks for the job of its kept results at most this often after the studio said it has none
 * for it (the job may still come back to it once it may work again, so the results stay).
 */
export const HELD_RETRY_MS = 60_000;

/** The port an older setup saved for every worker; a worker.json that still pins it gets a free port at each start. */
export const OLD_SETUP_PORT = 8190;

/** The settings as the worker uses them: a port that an older setup saved (8190) is no pin (the same object otherwise). */
export const withoutOldPort = (cfg) => (Number(cfg?.port) === OLD_SETUP_PORT ? { ...cfg, port: null } : cfg);

/** An address on a private network: 10.x, 172.16.x to 172.31.x, 192.168.x, or IPv6 fc00::/7. */
export function privateHost(hostname) {
  const h = String(hostname).replace(/^\[|\]$/g, "");
  const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h);
  if (m) {
    const [a, b] = [Number(m[1]), Number(m[2])];
    return m.slice(1).every((x) => Number(x) <= 255) && (a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168));
  }
  return /^f[cd][0-9a-f]{0,2}:/i.test(h);
}

/** The studio's address uses http (allowed only on this PC, or on a private network with allowHttpSite). */
export const plainHttp = (site) => {
  try {
    return new URL(String(site)).protocol === "http:";
  } catch {
    return false;
  }
};

/**
 * Why the studio's address won't do, or null: it must be https, so the token and people's files never cross the
 * network in the clear. This PC itself (127.0.0.1, localhost) may use http, for tests. An address on a private network
 * may use http only when worker.json says `allowHttpSite: true` (`o` is the settings).
 */
export function siteProblem(site, o = {}) {
  let u;
  try {
    u = new URL(String(site));
  } catch {
    return "That isn't a web address.";
  }
  if (u.protocol === "https:") return null;
  if (u.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(u.hostname)) return null;
  if (u.protocol === "http:" && privateHost(u.hostname)) {
    return o?.allowHttpSite === true ? null : "The studio's address must start with https://. For an http:// address on your own network, set allowHttpSite to true in worker.json.";
  }
  return "The studio's address must start with https://.";
}

/**
 * The worker's local pause, from its switch (`worker pause`), the GPU, its model folders (`modelsMissing`: the ones that
 * aren't there) and its ComfyUI: { paused, why, until }. A pause by hand ("here", "here-until:<ms>", "here-now") always
 * wins over the GPU's. Its RAM guard never pauses it (ram.mjs).
 */
export function localPause(control, gpu, comfyTrouble, now, modelsMissing = []) {
  if (control.paused && control.until && now >= control.until) return null; // its --for ran out: the caller clears it
  if (control.paused) return { paused: true, why: control.now ? "here-now" : control.until ? `here-until:${control.until}` : "here", until: control.until ?? null };
  if (gpu.paused) return { paused: true, why: `gpu-busy:${gpu.who ?? "another program"}`, until: null };
  if (modelsMissing.length) return { paused: true, why: "models-not-ready", until: null };
  if (comfyTrouble) return { paused: true, why: comfyTrouble, until: null };
  return { paused: false, why: null, until: null };
}

const sha256 = (data) => crypto.createHash("sha256").update(data).digest("hex");
const arrayBuffer = (buf) => buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
const count = (v) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : null);

/**
 * What the beat says for studio jobs first: { claimable, owner }. `claimable` is the beat's claimableNow (people's jobs
 * this worker may take now). It is null when the studio doesn't say, and then local ComfyUI work counts as another
 * program, as before. `owner` is the beat's ownerWaitingNow (the owner's own jobs it may take now; 0 when it doesn't
 * say): they ask for no turn, but idle local ComfyUI work is asked to free its memory for them.
 */
export function siteOf(answer) {
  return { claimable: count(answer?.claimableNow), owner: count(answer?.ownerWaitingNow) ?? 0 };
}

/**
 * Run until `signal` aborts or the studio stops it. Returns why it ended: "aborted" (Ctrl+C, the scheduled task's end),
 * "signed-out" (the studio doesn't know its token) or "disconnected". `deps`: { fetch, now, sleep, readGpu, log, home, env,
 * signal, requirements, ComputerRunner, rules, pins, runtime (the run-time files it verifies: inventory.mjs
 * runtimeFileList), allowed, ffmpegVersion, reencode, awake, rescanMs, comfy (OwnComfy's own options), readCounters,
 * readListeners, readProcs, ramNow and ramGuard (the RAM guard's numbers, ram.mjs), gpuEveryMs, gpuGraceMs (MID_JOB_GRACE_MS), gpuBriefMs (BRIEF_PAUSE_MS), readGpuGen, idleClaimMs
 * (IDLE_CLAIM_MS), canCleanPictures, and for job tickets: composer
 * (src/lib/ticket-compose.ts as built), catalogVersion, catalogDir, allLanes, codeWatch (update.mjs's CodeWatch: new
 * code on disk ends it with "update" once no person's job waits for it and its jobs are done) and updateDeferMs
 * (UPDATE_DEFER_MAX_MS) }.
 */
export async function runWorker(saved, deps) {
  // One worker at a time on a worker folder: a second one would stop the first one's ComfyUI, empty its folders and
  // take its job. It refuses to start instead (WorkerRunning), before it touches anything.
  fs.mkdirSync(saved.workDir, { recursive: true });
  const lock = await takeLock(saved.workDir, { commandLineOf: deps.comfy?.commandLineOf });
  try {
    return await work(saved, deps, lock.owner);
  } finally {
    lock.release();
  }
}

/** The worker's loop, with the worker folder's lock held (`owner`: { pid, id, script }, the lock's). */
async function work(saved, deps, owner) {
  const now = deps.now ?? Date.now;
  const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
  const say = deps.log ?? ((line) => console.log(`[${new Date().toISOString().slice(11, 19)}] ${line}`));
  // Each line also goes to the studio, masked, in the next beats (log-ring.mjs).
  const ring = deps.logRing ?? new LogRing({ now });
  const log = (line) => {
    say(line);
    ring.add(line);
  };
  const cfg = withoutOldPort(saved);
  if (cfg !== saved) log(`worker.json pins port ${OLD_SETUP_PORT}, from an older setup: its ComfyUI takes a free port at each start instead. Run fuobe worker setup again to save the new settings.`);
  const fetchFn = deps.fetch ?? fetch;
  const problem = siteProblem(cfg.site, cfg);
  if (problem) throw new Error(problem);
  if (cfg.allowHttpSite === true && plainHttp(cfg.site) && privateHost(new URL(cfg.site).hostname)) {
    log("The studio's address uses http:// (allowHttpSite): its token and people's files cross your network unencrypted.");
  }
  const index = deps.requirements ?? loadRequirements();
  const { ComputerRunner } = deps.ComputerRunner ? { ComputerRunner: deps.ComputerRunner } : await import("./dist/computer-runner.mjs");
  // What takes this PC's folders out of the words it sends the studio (the job runner does it for every job report).
  const redact = deps.redact ?? (await import("./dist/engine-error.mjs").then((m) => m.withoutLocalPaths).catch(() => undefined));
  const site = cfg.site.replace(/\/+$/, "");
  const f = folders(cfg.workDir);
  fs.mkdirSync(cfg.workDir, { recursive: true });
  /** A job's last line in the log: how it ended, and a failed one's reason in short (ComfyUI's own, when it said one). */
  const endedLine = (what, t, phase, why) => {
    const said = typeof why === "string" ? (redact ? redact(why) : why).replace(/\s+/g, " ").replace(/[\s.]+$/, "").slice(0, 600) : "";
    return `${what} ${t.id} ${phase}${said ? `: ${said}` : ""}.`;
  };
  emptyFolders(f);
  // Inputs kept by their SHA-256 while their job runs here (a job sent again reads nothing from the studio twice).
  const cacheDir = path.join(cfg.workDir, "cache");
  const emptyCache = () => fs.rmSync(cacheDir, { recursive: true, force: true });
  emptyCache();
  const hold = new Hold(path.join(cfg.workDir, "hold"));
  const allowed = deps.allowed ?? allowedNodes(cfg.allowNodesFile);
  const rules = deps.rules ?? inputRules();
  // Job tickets (tickets.mjs): the catalog version its build composes for, its own copy of the catalog, and its PC's
  // ceiling (worker.json `ceiling`), the most it ever runs. Full graphs only for the owner's own jobs, and none at all
  // when worker.json says `acceptGraphs: false`.
  const catalogVersion = deps.catalogVersion !== undefined ? deps.catalogVersion : builtCatalogVersion();
  const catalogDir = deps.catalogDir ?? path.join(ROOT, "workflows/comfyui");
  const ceiling = ceilingOf(cfg.ceiling);
  let composer = deps.composer ?? null;
  let laneOf = null;
  let gpuGen = null;
  let studioCatalog = null;
  log(`This PC runs ${ceilingWords(ceiling)}${cfg.acceptGraphs === false ? ", from job tickets only" : ""}.`);
  const comfy = new OwnComfy(cfg, { now, fetch: fetchFn, folderNames: yamlFolders(index), log, owner, workerLives: (rec) => workerLives(rec, { commandLineOf: deps.comfy?.commandLineOf }), ...deps.comfy });
  // Only its own ComfyUI, and only while the process it started is up and ready: never whatever listens on that port.
  // Its results come without what a save node writes into them unasked (results.mjs).
  const ownFetch = withPlainResults((url, init) => comfy.fetch(url, init));
  const own = (url, init) => (comfy.alive() && comfy.ready ? ownFetch(url, init) : Promise.reject(new Error("Its own ComfyUI isn't running")));
  // A ComfyUI that a stopped worker left running is stopped now, before anything else uses the GPU.
  await comfy.stopLeftover();
  // Studio jobs first: only with a turns folder set in worker.json. Without one, every program counts the same, as before.
  const turns = cfg.yieldFolder
    ? new SiteTurns({
        folder: cfg.yieldFolder,
        stateFile: path.join(deps.home ?? cfg.workDir, "turns.json"),
        maxHoursPerDay: cfg.yieldMaxHoursPerDay,
        interruptGapMin: cfg.interruptGapMin,
        neverInterrupt: !!cfg.neverInterrupt,
        graceMs: deps.turnGraceMs,
      })
    : null;
  if (turns && !turns.folderOk()) log(`The turns folder ${cfg.yieldFolder} isn't there: local ComfyUI work counts as another program until it is.`);
  const busyMb = cfg.busyVramMb ?? 1024;
  // Two busy readings in a row pause it when it tells programs apart (a reading can catch memory on its way); during
  // its own job, only busy readings that last the grace time.
  const gpu = new GpuWatch({
    autoResume: !!cfg.autoResume,
    resumeAfterMs: (cfg.resumeAfterMin ?? 10) * 60_000,
    resumeBelowC: cfg.resumeBelowC ?? 75,
    busyReadings: turns ? 2 : 1,
    graceMs: deps.gpuGraceMs ?? MID_JOB_GRACE_MS,
    briefMs: deps.gpuBriefMs ?? BRIEF_PAUSE_MS,
    briefResumeMs: BRIEF_COOL_DOWN_MS,
    briefEveryMs: BRIEF_EVERY_MS,
  });
  // The RAM guard (ram.mjs): other programs' share of the PC's memory, read every few seconds while the owner's switch
  // for this worker is on (the beat's `worker.ramGuard`; off by default). worker.json `ramGuard` gives only its numbers.
  // Above its line, claims prefer jobs that fit whole on its card, and its ComfyUI lets go of its memory before each GPU
  // job and when idle. It never pauses. (Tests give their own numbers: { othersMb, everyMs }.)
  const ramCfg = deps.ramGuard ?? ramGuardOf(cfg.ramGuard);
  if (ramCfg.problem) log(`${ramCfg.problem}: its RAM guard uses its default for it.`);
  const ramGuard = { othersMb: ramCfg.othersMb, everyMs: ramCfg.everyMs };
  const ramWatch = new RamWatch({ othersMb: ramGuard.othersMb });
  // The site's switch as the last beat said (null before the first answer), and whether its ComfyUI let go of its memory
  // since its last GPU job.
  let ramOn = null;
  let ramIdleFreed = false;
  const gbOf = (mb) => `${Math.round((mb ?? 0) / 102.4) / 10} GB`;
  let ramReadAt = -Infinity;
  // A reading under way, and the last one that came back and isn't used yet ({ split }: null when it failed).
  let ramReading = null;
  let ramRead = null;
  let ramGood = null;
  let ramGoodAt = -Infinity;
  let ramFailSaid = false;
  const awake = deps.awake ?? new StayAwake({ now, log });
  // Its GPU's generation, once (tests give their own reader: the GPU's own tool is never run there).
  gpuGen = await (deps.readGpuGen ?? (deps.readGpu ? async () => null : () => readGpuGen(cfg.nvidiaSmi)))().catch(() => null);
  // ffmpeg: worker.json's, or the PATH's when worker.json names none (an older setup's never did).
  const ffmpegBin = ffmpegOf(cfg);
  const ffmpeg = ffmpegBin ? await (deps.ffmpegVersion ?? ffmpegVersion)(ffmpegBin) : null;
  log(
    ffmpeg
      ? `ffmpeg is there${cfg.ffmpeg === undefined ? " (on the PATH)" : ""}: it takes clips and sound, and makes each one again first.`
      : ffmpegBin
        ? `No working ffmpeg at ${ffmpegBin}: it takes pictures only. Set ffmpeg in worker.json (its full path), or run fuobe worker setup again.`
        : "No ffmpeg (ffmpeg in worker.json): it takes pictures only.",
  );
  let comfyTrouble = null;
  let troubleAt = 0;
  // Its ComfyUI lists the nodes of its face detector's self-check (self-check.mjs), and how many checks it ran.
  let faceNodes = !!deps.faceNodes;
  let faceChecks = 0;
  // When a face self-check last failed twice: face jobs go back in line until SELF_CHECK_PAUSE_MS later; other jobs go on.
  let facesDownAt = null;
  // A face check it owes, done between jobs before its next claim: "check" (not checked yet: a job was in hand after a
  // start, or a check timed out on a busy GPU; once FACE_SETTLE_MS after its last GPU job) or "restart" (a check before
  // a face job failed: that job went back in line, and its ComfyUI may start again now that no job is in hand).
  let facesOwed = null;
  // When its last GPU job that reached its ComfyUI ended, and whether the job in hand passed its checks (so it runs).
  let gpuJobEndedAt = -Infinity;
  let jobVetted = false;
  let answer = null;
  let inv = { files: [], nodePacks: [], media: ffmpeg ? ["image", "video", "audio"] : ["image"] };
  let packs = [];
  let invHash = null;
  let gpuInfo = { otherApps: [], tempC: null, busyPct: null };
  // The PC's live hardware stats (stats.mjs), read with the GPU: the last reading goes in each beat.
  let hwStats = null;
  const cpuMeter = new CpuMeter(deps.cpuTimes);
  let lastGpuAt = 0;
  // When the GPU was last read: a reading older than GPU_BUSY_FRESH_MS says nothing about how busy it is now.
  let gpuReadAt = 0;
  let pause = { paused: true, why: "here", until: null };
  let busyJob = false;
  let job = Promise.resolve();
  let lastTask = null;
  let heldRetryAt = 0;
  let holdCheckedAt = -Infinity;
  // How long the PC slept since the studio last answered a beat (ms), and how much of it the beat in flight carries.
  let slept = 0;
  let sleptSent = 0;
  // Why it doesn't start the line's work now although it may (the beat's `holding`: { why, since }), or null.
  let holding = null;
  // New code on disk (update.mjs): once no person's job waits for it (at most updateDeferMs after it found the code), it
  // takes no new job, finishes the one it has, and ends to start again on the new code.
  const codeWatch = deps.codeWatch ?? new CodeWatch({ root: ROOT, dist: path.join(here, "dist"), home: deps.home });
  const updateDeferMs = deps.updateDeferMs ?? UPDATE_DEFER_MAX_MS;
  let updating = false;
  // When it found new code on disk (null: none yet).
  let updateFoundAt = null;
  // When its last GPU or CPU job ended while it waits to restart on new code (a text job in hand may still end).
  let textDrainAt = null;
  // An update asked for now (status.json `update`, which the updater on the PC reads): by the owner ("owner", the beat
  // answer's updateNow) or by a job whose graph changed in the studio's newer catalog ("graph"). Its restart keeps the
  // rules above: after the job in hand, never cutting a person's job off.
  let updateWanted = null;
  let ownerAskSeen = null;
  const wantUpdate = (why) => {
    if (updateWanted?.why === why && now() - updateWanted.at < 60_000) return;
    updateWanted = { at: now(), why };
    // New code may already be there: look at once.
    codeWatch.checkedAt = -Infinity;
  };
  // The commit its code came from (the studio shows it, "Back on <commit>").
  const startedCommit = (() => {
    try {
      return headOf(ROOT);
    } catch {
      return null;
    }
  })();
  // Its ComfyUI's start, while it goes on (beats go on meanwhile), and the signal that ends a start when the worker stops.
  let starting = null;
  const stopStarts = new AbortController();
  deps.signal?.addEventListener("abort", () => stopStarts.abort(), { once: true });
  let guardMissingAt = -Infinity;
  // Studio jobs first: the last port table, the last split of the GPU's memory, and the last turn step.
  let listing = null;
  let listedAt = -Infinity;
  // The last counters read that worked, and when: a read that fails now and then (typeperf under load) uses it for a while.
  let goodCounters = null;
  let goodCountersAt = -Infinity;
  // Busy readings in a row that only the total decided (no counters, no lock): one alone never pauses.
  let totalBusyInARow = 0;
  let split = null;
  let turn = { siteWaiting: 0, oldestWaitS: 0, interrupt: false, interruptAt: null, waitForYield: false, late: false, startsAt: null, ended: null };
  // The owner's own job and local ComfyUI work that keeps memory: when its /queue was last looked at, when it was last
  // asked to free its memory (it may take the owner's job for ROOM_MS after), and whether the log said it waits.
  let idleLookAt = -Infinity;
  let roomAt = -Infinity;
  let ownerWaitSaid = false;
  // Local ComfyUI work is asked with the plain fetch, never the one that carries the worker's token to the studio.
  const localFetch = deps.localFetch ?? globalThis.fetch;
  let siteWritten = "";
  let siteAt = 0;
  let siteFailed = false;
  // The owner's mode as last written to the turns folder and said in the log.
  let modeFailed = false;
  let modeSaid = null;
  const writeTurn = (t, body) => {
    const key = JSON.stringify([body.siteWaiting, body.interruptAt]);
    siteWritten = key;
    siteAt = t;
    try {
      writeSite(cfg.yieldFolder, { ...body, at: t });
      siteFailed = false;
    } catch (e) {
      if (!siteFailed) log(`Couldn't write to the turns folder: ${e.message}`);
      siteFailed = true;
    }
  };

  // How often its ComfyUI stopped while running each task (a task that stops it twice fails, not the worker).
  const crashFile = path.join(cfg.workDir, "crashes.json");
  const crashes = (() => {
    try {
      const c = JSON.parse(fs.readFileSync(crashFile, "utf8"));
      return c && typeof c === "object" ? c : {};
    } catch {
      return {};
    }
  })();
  const saveCrashes = () => {
    try {
      fs.writeFileSync(crashFile, JSON.stringify(crashes), { mode: 0o600 });
    } catch {}
  };
  comfy.onCrash = (code, task) => {
    log(`ComfyUI stopped (exit ${code}).`);
    if (!task) return;
    crashes[task] = (crashes[task] ?? 0) + 1;
    saveCrashes();
  };

  const api = retrying(fetchFn, { now, sleep, signal: deps.signal, log });
  // Its token: worker.json's, until the studio gives it the next one (a token with a lifetime, docs/gpu-workers.md).
  let token = cfg.token;
  // A token given in FUOBE_WORKER_TOKEN stays out of files, and the environment's token is the one every start uses: so
  // it never takes a next token (saved in worker.json, the next start would still use the old one, which stops working
  // once the new one is used). It says when its token ends instead, so it can be replaced in time.
  const envToken = !!(deps.env ?? process.env).FUOBE_WORKER_TOKEN;
  const canRotate = !!deps.home && !envToken;
  let endWarned = null;
  const call = (p, init = {}) => api(`${site}${p}`, { ...init, headers: { ...(init.headers ?? {}), Authorization: `Bearer ${token}`, "User-Agent": `FuobeWorker/${VERSION}` } });
  /** The studio's next token: saved in worker.json first, then used from the next call on (the old one stops then). */
  const takeToken = (next) => {
    if (!next || typeof next.value !== "string" || !NEXT_TOKEN.test(next.value) || next.value === token) return;
    if (!canRotate) return;
    try {
      saveConfig(deps.home, { ...savedConfig(deps.home), token: next.value });
    } catch (e) {
      log(`Couldn't save its next token in worker.json (${e.message}): it keeps the one it has, and asks again later.`);
      return;
    }
    token = next.value;
    log(`Saved its next token in worker.json${Number.isFinite(next.expiresAt) ? ` (it lasts until ${new Date(next.expiresAt).toISOString().slice(0, 10)})` : ""}.`);
  };

  // The run-time files it verifies beside the catalog's own (a look's or a motion's LoRAs), as its build lists them.
  const runtime = deps.runtime ?? runtimeFileList();
  // What its ComfyUI loaded of each pack (GET /object_info after each start), kept across restarts: a pack whose import
  // failed there doesn't count for the workflows that need its nodes, whatever its folder says.
  const loadedFile = path.join(cfg.workDir, "loaded-packs.json");
  let loaded = readLoaded(loadedFile);
  // The model names its ComfyUI lists with "\" (Windows), read with its nodes: a job's "/" names are sent as listed.
  let listed = new Map();
  async function scan() {
    packs = packFolders(cfg.comfyDir, index);
    inv = { files: await modelFiles(cfg.modelDirs ?? [], index, path.join(cfg.workDir, "hash-cache.json"), deps.pins, { comfyDir: cfg.comfyDir, fileCheck: cfg.fileCheck, runtime }), nodePacks: packsAsSeen(packs, loaded), media: inv.media };
    invHash = inventoryHash(inv);
  }
  /**
   * After its ComfyUI started: which of the catalog's node classes it lists, pack by pack. A change goes in the next
   * beat's hash, and the studio asks for the list again. Not read (an older ComfyUI, no answer): the last reading stays.
   */
  async function readLoadedNodes() {
    let info;
    try {
      const r = await comfy.fetch(`${comfy.base}/object_info`, {}, 120_000);
      if (!r.ok) return;
      info = await r.json();
    } catch {
      return;
    }
    if (!info || typeof info !== "object" || !Object.keys(info).length) return;
    listed = listedNames(info);
    faceNodes = deps.faceNodes ?? (!!info.H3FaceTrackCrop && !!info.PreviewAny);
    const fresh = loadedPacks(packs, index, info);
    for (const [name, l] of Object.entries(fresh)) {
      if (!l.missing.length || JSON.stringify(loaded[name]) === JSON.stringify(l)) continue;
      const all = (index.packs?.[name]?.classes ?? []).length === l.missing.length;
      log(`${all ? `The node pack ${name} didn't load in its ComfyUI` : `Some nodes of ${name} didn't load in its ComfyUI`} (${l.missing.join(", ")}; see comfyui.log): the studio sends it no workflow that needs ${all ? "them" : "those"}.`);
    }
    for (const [name, l] of Object.entries(fresh)) if (!l.missing.length && loaded[name]?.missing?.length) log(`The node pack ${name} loads in its ComfyUI now.`);
    if (JSON.stringify(fresh) === JSON.stringify(loaded)) return;
    loaded = fresh;
    writeLoaded(loadedFile, loaded);
    inv = { ...inv, nodePacks: packsAsSeen(packs, loaded) };
    invHash = inventoryHash(inv);
  }
  // Its GPU is busy for a face check: its last GPU job ended less than FACE_SETTLE_MS ago, or its text slot answers there.
  const faceSettleMs = deps.faceSettleMs ?? FACE_SETTLE_MS;
  const faceGpuBusy = () => now() - gpuJobEndedAt < faceSettleMs || (!!text?.busy && text.server?.device === "gpu");
  /**
   * Its face detector's self-check (self-check.mjs) on its GPU ComfyUI, while that ComfyUI has the face nodes. A failure
   * starts its ComfyUI again and checks once more; a second failure holds back face jobs only (they go back in line,
   * "self-check") for SELF_CHECK_PAUSE_MS (5 minutes), while every other job goes on. True when it passed, or when there
   * is nothing to check.
   *
   * Its ComfyUI is never started again under a GPU job in hand: after a start with a job in hand it checks once that job
   * has ended; before a face job, a failure gives that job back and its ComfyUI starts again between jobs. A check that
   * times out on a busy GPU (FACE_SETTLE_MS) is "not checked yet": checked again between jobs, never held against it.
   * `o.start`: the check after a start; `o.job`: the check before a job in hand (false: that job goes back in line).
   */
  async function checkFaces(when, o = {}) {
    if (!faceNodes || !comfy.ready) return true;
    if (facesDownAt !== null) {
      if (now() - facesDownAt < SELF_CHECK_PAUSE_MS) return false;
      facesDownAt = null;
    }
    const inHand = () => busyJob && jobUsesGpu;
    if (o.start && inHand()) {
      facesOwed ??= "check";
      log(`Its face check ${when} waits: a job is in hand, and it checks once that job has ended.`);
      return true;
    }
    const notYet = () => {
      facesOwed ??= "check";
      log(`Its face check ${when} timed out while its GPU was busy: not checked yet, and it checks again between jobs${o.job ? " (this face job goes back in line)" : ""}.`);
      return !o.job;
    };
    const passed = () => {
      facesOwed = null;
      return true;
    };
    const once = () => (deps.selfCheck ?? runSelfCheck)((url, init) => comfy.fetch(url, init), comfy.base, { n: ++faceChecks, now, sleep });
    const read = (r) => `${r.height === null ? "no face" : `${Math.round(r.height)} px`} (${r.why}${r.detail ? `: ${r.detail}` : ""})`;
    let first = await once();
    if (first.ok) return passed();
    if (first.why === "timeout" && faceGpuBusy()) return notYet();
    // A check that didn't run to the end (its graph failed, its photo didn't upload, it timed out) is often a ComfyUI
    // that has only just started: one more try after a few seconds, before it is started again.
    if (first.why !== "height" && first.why !== "no-report") {
      log(`Its face check ${when} didn't finish: ${read(first)}. Trying once more in ${Math.round(SELF_CHECK_RETRY_MS / 1000)} s.`);
      await sleep(SELF_CHECK_RETRY_MS);
      first = await once();
      if (first.ok) {
        log(`Its face check passed on the second try (${Math.round(first.height)} px).`);
        return passed();
      }
      if (first.why === "timeout" && faceGpuBusy()) return notYet();
    }
    // A job in hand (the face job this check is for): it goes back in line, and its ComfyUI starts again between jobs.
    if (inHand()) {
      facesOwed = "restart";
      log(`Its face check ${when} read ${read(first)}: this job goes back in line, and its ComfyUI starts again once no job is in hand.`);
      return false;
    }
    log(`Its face check ${when} read ${read(first)}: starting its ComfyUI again.`);
    // While it starts again, the loop starts no ComfyUI of its own (a start under way already holds `starting`).
    const mine = !starting;
    const again = (async () => {
      await comfy.stop();
      try {
        await comfy.start(
          packs.map((p) => p.folder),
          { signal: stopStarts.signal },
        );
        await readLoadedNodes();
      } catch (e) {
        log(`ComfyUI didn't start: ${e.message}`);
      }
    })();
    if (mine) starting = again;
    await again;
    if (mine && starting === again) starting = null;
    const second = comfy.ready ? await once() : { ok: false, height: null, why: "no-comfy" };
    if (second.ok) {
      log(`Its face check passed after the restart (${Math.round(second.height)} px).`);
      return passed();
    }
    facesOwed = null;
    facesDownAt = now();
    log(`Its face check failed again after the restart (${second.why}${second.detail ? `: ${second.detail}` : ""}): face jobs go back in line for ${Math.round(SELF_CHECK_PAUSE_MS / 60_000)} minutes, then it checks again first; other jobs go on.`);
    return false;
  }
  // One look at a time; the next beat carries a changed hash, and the studio then asks for the list.
  let scanning = null;
  let scannedAt = now();
  const rescan = () =>
    (scanning ??= scan()
      .catch((e) => log(`Couldn't look at its model folders: ${e.message}`))
      .finally(() => {
        scanning = null;
        scannedAt = now();
      }));
  await scan();
  // A model folder that isn't there yet: no new job, and no list of files that lacks its files, until it is.
  let modelsMissing = missingModelDirs(cfg.modelDirs);
  let modelsCheckedAt = now();
  let modelsBack = null;
  const sayMissing = (missing) =>
    log(`${missing.length === 1 ? "A model folder isn't" : `${missing.length} model folders aren't`} there yet (${missing.join(", ")}): it takes no new job until ${missing.length === 1 ? "it is" : "they are"}, and looks again every minute.`);
  if (modelsMissing.length) sayMissing(modelsMissing);

  // Pictures of an account's job are made again here: without the tool for it (pnpm install in its checkout), such a
  // job goes back to the line for another worker.
  const pictureTool = deps.canCleanPictures ?? canCleanPictures();
  if (!pictureTool) log("It can't make pictures again here (run pnpm install in its checkout): it takes only the owner's own jobs until it can.");
  /**
   * An input for its ComfyUI: read from the studio once, kept by its SHA-256 (in the slot's own `cacheDir`), a clip or
   * sound made again by ffmpeg, and a picture of an account's job ticket or of a finishing job made again from its pixels.
   */
  const takeInputIn = (cacheDir) => async (t, input, read) => {
    if (!/^[0-9a-f]{64}$/.test(String(input.sha256))) return "input-changed";
    fs.mkdirSync(cacheDir, { recursive: true });
    const kept = path.join(cacheDir, input.sha256);
    let data = null;
    if (fs.existsSync(kept)) {
      const b = fs.readFileSync(kept);
      if (sha256(b) === input.sha256) data = b;
    }
    if (!data) {
      const got = await read();
      if (typeof got === "string") return got;
      data = Buffer.from(got);
      fs.writeFileSync(kept, data, { mode: 0o600 });
    }
    // A 3D file (a finishing job's GLB is checked by its own script): real by its bytes, and a splat made again.
    const model = t.finish ? null : modelFormat(input);
    if (model) {
      const again = modelAgain(model, data, !!t.ticket);
      if (again) return arrayBuffer(again);
      log(`Job ${t.id}: one of its 3D files isn't one it takes.`);
      return "input-unreadable";
    }
    const kind = mediaKind(input, t.graph);
    if (!kind) {
      // The studio sends an account's pictures as they came: no EXIF, GPS or other metadata of them reaches its ComfyUI.
      if (!(t.ticket || t.finish) || !isPicture(input)) return arrayBuffer(data);
      if (!pictureTool) return "give-back";
      const clean = path.join(cacheDir, `${input.sha256}.png`);
      if (!fs.existsSync(clean)) {
        const part = `${clean}.part`;
        if (!(await (deps.cleanPicture ?? cleanPicture)({ src: kept, dst: part }))) {
          fs.rmSync(part, { force: true });
          log(`Job ${t.id}: one of its pictures couldn't be read.`);
          return "input-unreadable";
        }
        fs.renameSync(part, clean);
      }
      return arrayBuffer(fs.readFileSync(clean));
    }
    // Without ffmpeg it takes no clip or sound: another worker that can make them again runs the job.
    if (!ffmpeg) return "give-back";
    const made = path.join(cacheDir, `${input.sha256}.${kind}`);
    const cap = outputCap(data.length);
    if (!fs.existsSync(made)) {
      const part = `${made}.part`;
      if (!(await (deps.reencode ?? reencode)({ ffmpeg: ffmpegBin, kind, name: input.name, src: kept, dst: part, capBytes: cap }))) {
        fs.rmSync(part, { force: true });
        log(`Job ${t.id}: ffmpeg couldn't make one of its ${kind === "video" ? "clips" : "sounds"} again (unreadable, or over ${Math.round(cap / 2 ** 20)} MB).`);
        return "input-unreadable";
      }
      fs.renameSync(part, made);
    }
    // Never more than the cap into memory.
    if (fileSize(made) >= cap) {
      fs.rmSync(made, { force: true });
      return "input-unreadable";
    }
    return arrayBuffer(fs.readFileSync(made));
  };
  const takeInput = takeInputIn(cacheDir);

  /** A job ticket's graph, composed here (or why it is refused), from the facts of the ComfyUI that runs it. */
  async function composeJob(t, ownFetch = own, base = comfy.base) {
    if (!catalogVersion) return { refused: "update-worker" };
    composer ??= await import("./dist/compose/lib/ticket-compose.mjs");
    // Each workflow's lane, when its ceiling names lanes.
    if (ceiling?.lanes && !laneOf) laneOf = laneMap(index, deps.allLanes ?? (await import("./dist/lanes.mjs")).allLanes);
    const facts = composer.workerFactsFrom(await readPcAnswers(ownFetch, base));
    const r = await composer.composeTicket({ ticket: t.ticket, generationId: t.generationId, inputs: t.inputs }, { catalog: workerCatalog(catalogDir), catalogVersion, ceiling, laneOf, facts, index });
    if (r.ok) return { graph: r.graph, made: r.made };
    // A ticket for the studio's newer catalog whose graph this build makes otherwise: back in line at no cost, and the
    // update is asked for at once (the updater reads it in status.json).
    if (r.graphChanged) {
      wantUpdate("graph");
      log(`Job ${t.id} goes back in line: its graph changed in the studio's newer catalog. Asking for the update now.`);
      return { refused: r.reason };
    }
    // Why, for the PC's owner (never a setting's value: those are someone's prompt).
    log(`Refused job ${t.id}: ${r.reason === "update-worker" ? "its ticket is for another catalog (update the worker)" : r.reason === "outside-ceiling" ? "it is more than this PC runs (its ceiling in worker.json)" : "its ticket isn't one it can use"}.`);
    return { refused: r.reason };
  }

  /**
   * The worker's own checks of a job's graph before its ComfyUI sees it (checks.mjs): the reason it refuses it, or null.
   * With `o.faces` (its GPU runner), a job that detects faces first passes the face self-check, or goes back in line.
   */
  async function vetJob(t, o = {}) {
    const check = () => graphCheck(t.graph, allowed, inv.files, { rules, staged: (t.inputs ?? []).map((i) => i.name) });
    let problem = check();
    // A model file it doesn't have yet (a drive that came back after a restart): look again once before refusing.
    if (problem?.reason === "model-unverified") {
      log(`Job ${t.id} needs a model file it hasn't found: looking at its model folders again.`);
      await rescan();
      problem = check();
    }
    // Which node and input, for the PC's owner (never a value: those are someone's prompt or file).
    if (problem) {
      log(`Refused job ${t.id}: ${problem.reason} at node ${problem.node}${problem.cls ? ` (${problem.cls}${problem.input ? `.${problem.input}` : ""})` : ""}.`);
      return problem.reason;
    }
    t.graph = asListed(t.graph, listed);
    if (o.faces && detectsFaces(t.graph) && !(await checkFaces("before a face job", { job: true }))) return { giveBack: "self-check" };
    if (o.faces) jobVetted = true;
    return null;
  }

  // The CPU slot (worker.json `cpuSlot: true`): its own ComfyUI on the CPU only (its own folders, port, key and kept
  // inputs), its own kept results, and the finishing jobs this PC can run.
  const cpuOn = cfg.cpuSlot === true;
  const cpuDir = path.join(cfg.workDir, "cpu");
  const fc = folders(cpuDir);
  const cpuCacheDir = path.join(cpuDir, "cache");
  // Its kept inputs, and anything a finishing job left behind (a stop mid-job), go after each job, at start and at exit.
  const emptyCpuCache = () => {
    fs.rmSync(cpuCacheDir, { recursive: true, force: true });
    fs.rmSync(path.join(cpuDir, "finish"), { recursive: true, force: true, maxRetries: 3, retryDelay: 200 });
  };
  const cpuComfy = cpuOn
    ? new OwnComfy(
        { ...cfg, workDir: cpuDir, port: null, cpuOnly: true, ...(cfg.cpuComfyCommand && { comfyCommand: cfg.cpuComfyCommand }) },
        { now, fetch: fetchFn, folderNames: yamlFolders(index), log, owner, workerLives: (rec) => workerLives(rec, { commandLineOf: deps.comfy?.commandLineOf }), ...deps.comfy },
      )
    : null;
  const cpuHold = cpuOn ? new Hold(path.join(cfg.workDir, "hold-cpu")) : null;
  const cpuOwnFetch = withPlainResults((url, init) => cpuComfy.fetch(url, init));
  const cpuOwn = (url, init) => (cpuComfy?.alive() && cpuComfy.ready ? cpuOwnFetch(url, init) : Promise.reject(new Error("Its CPU slot's ComfyUI isn't running")));
  const finish = cpuOn ? (deps.finishers ?? finishers({ workDir: cpuDir, ffmpeg: ffmpeg ? ffmpegBin : null })) : null;
  if (cpuOn) {
    fs.mkdirSync(cpuDir, { recursive: true });
    emptyFolders(fc);
    emptyCpuCache();
    await cpuComfy.stopLeftover();
    cpuComfy.onCrash = (code, task) => {
      log(`Its CPU slot's ComfyUI stopped (exit ${code}).`);
      if (!task) return;
      crashes[task] = (crashes[task] ?? 0) + 1;
      saveCrashes();
    };
    log(`It has a CPU slot: light CPU work${finish.kinds.length ? ` and finishing jobs (${finish.kinds.join(", ")})` : ""} run beside its GPU's job.`);
  }
  // The text slot: its own claims for the studio's text jobs, beside the GPU's job and the CPU slot's.
  const textCfg = textSlotOf(cfg.textSlot);
  if (textCfg?.problem) log(`${textCfg.problem}: its text slot is off.`);
  const text = textCfg && !textCfg.problem ? (deps.textSlot ?? new TextSlot(textCfg, { call, log, workDir: cfg.workDir, home: deps.home, now, sleep, env: deps.env, redact, ...deps.text })) : null;
  const gpuTotalMb = text ? await (deps.readGpuTotal ?? (deps.readGpu ? async () => null : () => readGpuTotal(cfg.nvidiaSmi)))().catch(() => null) : null;
  let lastUsedMb = null;
  /** Where a new start of the text slot's server may run: the GPU while nothing else holds it and there is room, else the CPU. */
  const textRoom = () => {
    const held = gpu.paused || gpu.busyInARow > 0 || (!!turns && (split?.workMb ?? 0) > busyMb && turn.siteWaiting === 0);
    if (held) return "cpu";
    if (text.server?.device === "gpu") return "gpu";
    return gpuTotalMb !== null && lastUsedMb !== null && gpuTotalMb - lastUsedMb >= textCfg.gpuMinFreeMb ? "gpu" : "cpu";
  };
  let cpuRunner = null;
  let busyCpu = false;
  let cpuJob = Promise.resolve();
  let cpuStarting = null;
  let lastCpuTask = null;
  /** What a slot's runner says it works on, for the beat. */
  const runningOf = (r) =>
    r.view.jobs.filter((j) => j.phase !== "done" && j.phase !== "failed").map((j) => ({ task: j.taskId, ...(j.position !== undefined && { position: j.position }), ...(j.phase === "running" && { value: j.value, max: j.max, ...r.motion?.(j.taskId) }) }));

  const runner = new ComputerRunner(
    {
      api: call,
      local: own,
      compose: composeJob,
      factsExtra: () => (gpuGen ? { gpuGen } : {}),
      sha256: async (data) => sha256(Buffer.from(data)),
      origin: site,
      socket: typeof WebSocket === "function" ? (url) => (comfy.ready ? new WebSocket(comfy.rebase(url), { headers: comfy.headers() }) : null) : undefined,
      now,
      sleep,
      vet: (t) => vetJob(t, { faces: true }),
      ended: async (t, phase, why) => {
        log(endedLine("Job", t, phase, why));
        // Done: the studio has every result. Otherwise its kept results wait for the next claim to say whose job it is,
        // after a while (so a studio that won't take them now doesn't keep its ComfyUI from starting).
        if (phase === "done") hold.drop(t.id);
        else if (hold.has(t.id)) heldRetryAt = now() + HELD_RETRY_MS;
        delete crashes[t.id];
        saveCrashes();
        await cleanJob(f, comfy.base, own);
        emptyCache();
      },
      beatExtra: () => {
        sleptSent = slept;
        const lines = ring.take();
        return {
          // Its log lines since the last beat the studio answered; older studios ignore them.
          ...(lines.length && { log: lines }),
          // Without its picture tool, it takes no job ticket: the studio sends it the owner's own jobs only.
          protocol: protocolOf(pictureTool),
          version: VERSION,
          ...(startedCommit && { commit: startedCommit }),
          // It saves the next token a beat answer gives it (never one for a token from the environment).
          canRotateToken: canRotate,
          local: pause,
          gpu: gpuInfo,
          // The PC's live hardware stats (GPU, CPU, memory, sensors); older studios ignore them.
          // Only a recent reading: one the loop could not renew for a while never reaches the studio as new.
          ...(hwStats && now() - hwStats.at <= STATS_SEND_MS && { stats: hwStats }),
          inventoryHash: invHash,
          warmLane: null,
          // The catalog its build composes job tickets for, and what its PC may ever run.
          catalogVersion,
          ...(ceiling && { ceiling }),
          // The jobs whose results it keeps: a pause doesn't send them back in line, so they go up instead of running again.
          held: [...hold.ids(), ...(cpuHold?.ids() ?? [])].slice(0, 16),
          // The PC slept: a job taken back from it meanwhile goes on with no blame.
          ...(slept > 0 && { slept }),
          // Its CPU slot: the finishing jobs it runs, and the task it works on.
          ...(cpuOn && { cpuSlot: { finishes: finish.kinds }, cpuRunning: cpuRunner ? runningOf(cpuRunner) : [] }),
          // Why the line's work waits on it now (the owner's queue view shows it); older studios ignore it.
          ...(holding && { holding }),
          // Local work on its PC, as the helper there wrote it to the turns folder (counts and codes only).
          ...(turns && { localWork: readLocalWork(cfg.yieldFolder, now()) }),
        };
      },
      onBeat: (a) => {
        // The studio heard about the sleep.
        slept = Math.max(0, slept - sleptSent);
        sleptSent = 0;
        // The studio has the log lines that beat carried.
        ring.ack();
        // A studio that takes jobs only from a newer worker program: say so once (it sends this worker none).
        const min = Number(a?.worker?.minProtocol);
        if (min > PROTOCOL && answer?.worker?.minProtocol !== a.worker.minProtocol) log("The studio needs a newer worker program: it sends this one no jobs. Update the worker (docs/gpu-workers.md, \"Install and update\").");
        // A studio whose catalog is another than this build's: its people's runs wait for an updated worker. Said once.
        const theirs = a?.worker?.catalogVersion;
        if (typeof theirs === "string" && theirs !== catalogVersion && theirs !== studioCatalog) log("The studio's catalog is another than this worker's: it runs people's jobs whose graphs are the same in both, and waits for its update (docs/gpu-workers.md, \"Install and update\").");
        // The owner asked for an update now (once for each ask).
        const ask = Number(a?.worker?.updateNow);
        if (Number.isFinite(ask) && ask > 0 && ask !== ownerAskSeen) {
          ownerAskSeen = ask;
          wantUpdate("owner");
          log("The owner asked for an update now: it looks for new code at once and restarts after the job in hand.");
        }
        if (typeof theirs === "string") studioCatalog = theirs;
        answer = a;
        takeToken(a?.worker?.token);
        // The owner's mode (who goes first), for the helper on the PC's side: mode.json in the turns folder.
        if (turns && a?.worker?.queue && turns.folderOk()) {
          try {
            writeMode(cfg.yieldFolder, a.worker.queue, now());
            modeFailed = false;
          } catch (e) {
            if (!modeFailed) log(`Couldn't write the owner's mode to the turns folder: ${e.message}`);
            modeFailed = true;
          }
        }
        const q = a?.worker?.queue;
        if (q && typeof q.mode === "string" && q.mode !== modeSaid) {
          if (modeSaid !== null || q.mode !== "people-first") log(`The owner set who goes first: ${q.mode}${typeof q.until === "number" ? ` until ${new Date(q.until).toISOString().slice(11, 16)} UTC` : ""}.`);
          modeSaid = q.mode;
        }
        // A token from the environment with a lifetime: said once for each end date, so it is replaced there in time.
        const ends = Number(a?.worker?.tokenExpiresAt);
        if (envToken && Number.isFinite(ends) && ends > 0 && ends !== endWarned) {
          endWarned = ends;
          log(`Its token comes from FUOBE_WORKER_TOKEN, so it saves no next one: it stops working on ${new Date(ends).toISOString().slice(0, 10)}. Before then, make a new token in Settings → Workers and put it in FUOBE_WORKER_TOKEN.`);
        }
        // The owner's switch on the Workers page wins over worker.json; null leaves worker.json's.
        const s = a?.worker?.autoResume;
        gpu.o.autoResume = typeof s === "boolean" ? s : !!cfg.autoResume;
      },
      worker: {
        hold,
        input: takeInput,
        graphs: cfg.acceptGraphs !== false,
        olderStudio: () => !!answer && typeof answer.worker?.catalogVersion !== "string",
        inside: (t) => graphInside(ceiling, t),
        // The studio's stall limit comes with each job; a stallMin in worker.json wins over it on this PC.
        stallMs: 10 * 60_000,
        stallLocalMs: Number(cfg.stallMin) > 0 ? Number(cfg.stallMin) * 60_000 : null,
        free: () => comfy.free(),
        // How busy its GPU is, sent with each running job: its latest reading, or null when there is no fresh one.
        gpuBusy: () => (now() - gpuReadAt <= GPU_BUSY_FRESH_MS ? (gpuInfo.busyPct ?? null) : null),
        // A live preview that isn't a small JPEG is made again by ffmpeg (none without it).
        shrinkPreview: deps.shrinkPreview ?? previewShrinker({ ffmpeg: ffmpeg ? ffmpegBin : null, dir: path.join(cfg.workDir, "preview") }),
        crashes: (t) => crashes[t.id] ?? 0,
        stuck: async () => {
          log("Its ComfyUI didn't let go of a job: starting it again.");
          await comfy.stop();
        },
        claimed: async (t, o = {}) => {
          if (!t) {
            // No job for it now. Its kept results stay (their job may come back to it); while it may not work it asks
            // again for them only after a while. Its copies of inputs go.
            if (o.onlyHeld) heldRetryAt = now() + HELD_RETRY_MS;
            emptyCache();
            return;
          }
          // Another job, given to a worker that may work: the kept results of any other job aren't this worker's any
          // more (one job at a time).
          if (!o.onlyHeld) hold.dropAllBut(t.id);
          else if (!hold.has(t.id)) heldRetryAt = now() + HELD_RETRY_MS;
          comfy.task = t.id;
          // Another job than the one its ComfyUI last had: nothing of that one stays, in its ComfyUI or in the inputs.
          if (t.id !== lastTask) {
            await cleanJob(f, comfy.base, own);
            emptyCache();
            lastTask = t.id;
          }
          // Its RAM guard, above the line: its own ComfyUI lets go of its memory before a GPU job starts there (not for a
          // job already in it, kept results going up, or a finishing job, which runs on no ComfyUI).
          if (!o.onlyHeld && ramOn && ramWatch.over && t.finish === undefined && (!t.resume || t.resume === "sending")) {
            ramIdleFreed = true;
            await comfy.free();
          }
        },
      },
    },
    { device: "worker", port: cfg.port || 8190, clientId: crypto.randomBytes(8).toString("hex") },
  );

  // The CPU slot's runner: the same runner, on its CPU-only ComfyUI, claiming for its CPU slot. It never beats (the
  // worker's beat says what it works on), and its jobs never wait for the GPU's.
  if (cpuOn) {
    cpuRunner = new ComputerRunner(
      {
        api: call,
        local: cpuOwn,
        compose: (t) => composeJob(t, cpuOwn, cpuComfy.base),
        sha256: async (data) => sha256(Buffer.from(data)),
        origin: site,
        socket: typeof WebSocket === "function" ? (url) => (cpuComfy.ready ? new WebSocket(cpuComfy.rebase(url), { headers: cpuComfy.headers() }) : null) : undefined,
        now,
        sleep,
        vet: vetJob,
        finish: (t, inputs, o) => finish.finish(t, inputs, o),
        ended: async (t, phase, why) => {
          log(endedLine("CPU slot job", t, phase, why));
          if (phase === "done") cpuHold.drop(t.id);
          delete crashes[t.id];
          saveCrashes();
          await cleanJob(fc, cpuComfy.base, cpuOwn);
          emptyCpuCache();
        },
        worker: {
          hold: cpuHold,
          input: takeInputIn(cpuCacheDir),
          graphs: cfg.acceptGraphs !== false,
          olderStudio: () => !!answer && typeof answer.worker?.catalogVersion !== "string",
          inside: (t) => graphInside(ceiling, t),
          stallMs: 10 * 60_000,
          stallLocalMs: Number(cfg.stallMin) > 0 ? Number(cfg.stallMin) * 60_000 : null,
          free: () => cpuComfy.free(),
          crashes: (t) => crashes[t.id] ?? 0,
          stuck: async () => {
            log("Its CPU slot's ComfyUI didn't let go of a job: starting it again.");
            await cpuComfy.stop();
          },
          claimed: async (t) => {
            if (!t) return void emptyCpuCache();
            cpuHold.dropAllBut(t.id);
            cpuComfy.task = t.id;
            if (t.id !== lastCpuTask) {
              await cleanJob(fc, cpuComfy.base, cpuOwn);
              emptyCpuCache();
              lastCpuTask = t.id;
            }
          },
        },
      },
      { device: "worker-cpu", port: 8191, clientId: crypto.randomBytes(8).toString("hex"), slot: "cpu" },
    );
  }
  // When each slot's last claim found nothing (claimDue): it asks again a little later.
  const idleClaimMs = deps.idleClaimMs ?? IDLE_CLAIM_MS;
  let gpuMissedAt = -Infinity;
  let cpuMissedAt = -Infinity;
  const takeCpu = () => {
    busyCpu = true;
    cpuJob = cpuRunner
      .claimAndRun()
      .then((had) => {
        cpuMissedAt = had ? -Infinity : now();
      })
      // A claim the studio never answered (the retry policy gave up on it) had no job: none stopped.
      .catch((e) => log(cpuComfy.task ? `A CPU slot job stopped: ${failure(e)}` : `Its CPU slot can't ask the studio for a job: ${failure(e)}`))
      .finally(() => {
        busyCpu = false;
        cpuComfy.task = null;
      });
  };

  const mayWork = () => !updating && !pause.paused && answer?.worker && !answer.worker.paused && answer.worker.insideHours && !answer.worker.drain;
  const state = () =>
    updating
      ? "Finishing its job, then restarting on new code"
      : pause.why === "models-not-ready"
      ? "Waiting for its model folders"
      : pause.paused
        ? `Paused here (${pause.why})`
        : !answer
          ? "Connecting"
          : answer.worker?.paused
            ? "Paused on the website"
            : !answer.worker?.insideHours
              ? "Outside its hours"
              : answer.worker?.drain
                ? "Finishing, then pausing"
                : turn.waitForYield
                  ? "Waiting for local ComfyUI work to make room (its jobs keep their place)"
                  : comfy.ready
                    ? "Ready"
                    : "Starting ComfyUI";
  // A job that runs on its ComfyUI (not only sending kept results, which needs no GPU).
  let jobUsesGpu = false;
  const take = (o) => {
    busyJob = true;
    jobUsesGpu = !o?.onlyHeld;
    jobVetted = false;
    // Other programs use the PC's memory (its RAM guard): a claim prefers no job that streams from RAM.
    job = runner
      .claimAndRun(!o?.onlyHeld && ramOn && ramWatch.over ? { ...o, noStream: true } : o)
      .then((had) => {
        if (!o?.onlyHeld) gpuMissedAt = had ? -Infinity : now();
        // A GPU job ran: its ComfyUI may hold models again, let go of once it is idle.
        if (had && !o?.onlyHeld) ramIdleFreed = false;
      })
      .catch((e) => log(comfy.task ? `A job stopped: ${failure(e)}` : `It can't ask the studio for a job: ${failure(e)}`))
      .finally(() => {
        // A job that went to its ComfyUI: a face check just after it may still meet a busy GPU (FACE_SETTLE_MS).
        if (jobVetted) gpuJobEndedAt = now();
        jobVetted = false;
        busyJob = false;
        jobUsesGpu = false;
        comfy.task = null;
      });
  };

  /** Turns work now: the folder is there, the studio said what this worker can take, and today's hours aren't used up. */
  const turnsReady = (t) => !!turns && turns.folderOk() && !!answer && siteOf(answer).claimable !== null && turns.capLeft(t);

  /** The GPU's memory split three ways, from the counters and the port table (looked at again every 30 s, or sooner when a new process holds memory). */
  async function splitNow(t, reading, own) {
    let counters = await (deps.readCounters ?? readCounters)(cfg.gpuCounters);
    if (counters) {
      goodCounters = counters;
      goodCountersAt = t;
    } else if (goodCounters && t - goodCountersAt <= COUNTERS_REUSE_MS) counters = goodCounters;
    if (counters && (t - listedAt >= 30_000 || (listing && unknownHolder(counters, listing, own.pid, busyMb)))) {
      // A read that fails keeps the last port table (and is tried again on the next reading).
      const read = await (deps.readListeners ?? readListeners)(cfg.powershell);
      if (read) {
        listing = read;
        listedAt = t;
      }
    }
    return splitMemory({
      usedMb: reading.usedMb,
      apps: reading.apps,
      counters,
      listing,
      own,
      ports: cfg.localComfyPorts,
      excludePorts: cfg.localComfyExcludePorts,
      excludePids: cfg.localComfyExcludePids,
      baselineMb: cfg.desktopBaselineMb,
      lock: readLock(cfg.gpuLockFile),
      lockOwners: cfg.gpuLockComfyOwners,
      gpu: cfg.gpuLuid,
    });
  }

  let beatAt = 0;
  // A lone missed beat says nothing; two in a row say the studio can't be reached (retry.mjs).
  const reach = new Reach(log);
  let lastState = "";
  try {
    while (!deps.signal?.aborted) {
      const t = now();
      // New code installed: a restart never makes a person wait. While people's jobs wait that it may take (the last
      // beat's claimableNow), it goes on taking them, for at most updateDeferMs. Then it takes no new job, and once no job
      // is in hand (the GPU's and the CPU slot's), it ends, and starts again on it. The text slot takes jobs until then; a
      // text job in hand then gets up to TEXT_DRAIN_MS to end.
      if (updateFoundAt === null && codeWatch.check(t)) {
        updateFoundAt = t;
        if (!restartDue(t, updateFoundAt, siteOf(answer).claimable, updateDeferMs)) log(`New worker code is installed: restarting once no person's job waits for it (at most ${Math.round(updateDeferMs / 60_000)} min).`);
      }
      if (!updating && updateFoundAt !== null && restartDue(t, updateFoundAt, siteOf(answer).claimable, updateDeferMs)) {
        updating = true;
        log("New worker code is installed: restarting after this job.");
      }
      if (updating && !busyJob && !busyCpu) {
        textDrainAt ??= t;
        if (!text?.running || t - textDrainAt >= TEXT_DRAIN_MS) break;
      }
      // Its own switch, and --for running out.
      let control = readControl(deps.home);
      if (control.paused && control.until && t >= control.until) {
        writeControl(deps.home, { paused: false });
        control = { paused: false };
        gpu.clear();
        log("The pause ran out: back to work.");
      }
      if (control.resumedAt && control.resumedAt > (gpu.clearedAt ?? 0)) {
        gpu.clear();
        gpu.clearedAt = control.resumedAt;
      }
      // The GPU, every 5 s: nvidia-smi's total, and with a turns folder the GPU counters and the port table too.
      if (t - lastGpuAt >= (deps.gpuEveryMs ?? 5000)) {
        lastGpuAt = t;
        const reading = await (deps.readGpu ?? readGpu)(cfg.nvidiaSmi);
        // The live stats from the same reading, with the CPU, the memory and the sensors file (never fails the turn).
        try {
          hwStats = statsOf({ at: now(), gpu: reading?.stats ?? null, cpu: cpuMeter.read(), ram: (deps.ramNow ?? ramNow)(), sensors: readSensors(cfg.sensorsFile, Date.now(), deps.readSensorsFile) });
        } catch {
          hwStats = null;
        }
        if (reading) {
          const mine = text?.own() ?? { pids: [], mb: 0 };
          const own = { running: comfy.alive(), mb: await comfy.vramMb(), pid: comfy.pid, port: comfy.alive() ? comfy.port : null, job: busyJob && jobUsesGpu, extraPids: mine.pids, extraMb: mine.mb };
          lastUsedMb = reading.usedMb;
          let verdict;
          if (turns) {
            split = await splitNow(t, reading, own);
            // Local ComfyUI work is asked for a turn only while turns work (the folder, the studio's count, the caps);
            // otherwise it counts as another program, as before.
            const othersBusy = split.othersMb > busyMb;
            const workBusy = !turnsReady(t) && split.workMb > busyMb;
            const busy = othersBusy || workBusy;
            // Only the total decided (the counters failed and no lock said whose): a few such readings in a row first.
            totalBusyInARow = busy && split.source === "total" ? totalBusyInARow + 1 : 0;
            const totalUnsure = totalBusyInARow > 0 && totalBusyInARow < TOTAL_BUSY_READINGS;
            verdict = { busy, who: othersBusy ? split.who : `ComfyUI${split.work.port ? ` on port ${split.work.port}` : ""}`, othersMb: split.othersMb, cause: othersBusy ? null : "work", unsure: busy && ((own.job && !split.ownSure) || totalUnsure), job: own.job, source: split.source };
            // A pause that only local ComfyUI work caused ends once turns work again (the next day, the folder back).
            if (!verdict.busy && gpu.paused && gpu.cause === "work") {
              gpu.clear();
              log("Local ComfyUI work no longer keeps it paused: back to work.");
            }
          } else verdict = { ...othersOf(reading, own, busyMb), job: own.job };
          const was = gpu.paused;
          gpu.update(verdict, reading.tempC, t);
          gpuInfo = { otherApps: reading.apps.filter((a) => a.pid !== comfy.pid).map((a) => ({ pid: a.pid, name: a.name, vramBytes: (a.usedMb ?? 0) * 2 ** 20 })), tempC: reading.tempC, busyPct: reading.busyPct ?? null };
          gpuReadAt = t;
          if (!was && gpu.paused) log(`Another program is using the GPU (${gpu.who}): pausing (${Math.round(verdict.othersMb ?? 0)} MB not its own${verdict.source ? `, by ${verdict.source}` : ""}).`);
          if (was && !gpu.paused) log("The GPU stayed free for the whole cool-down: resuming.");
        }
      }
      // The RAM guard, while the owner's switch is on, every everyS: the PC's used memory less its own processes' (itself,
      // its ComfyUIs, its text slot's server and what they started). A failed reading keeps the last good one for
      // RAM_REUSE_MS, then counts as free. The reading runs beside the loop (a PowerShell start takes about a second,
      // longer when memory is short): the loop uses each one once it is there.
      const ramSwitch = answer?.worker?.ramGuard === true;
      if (answer && ramSwitch !== ramOn) {
        if (ramSwitch) log(`Its RAM guard is on: with other programs above ${gbOf(ramGuard.othersMb)} of this PC's memory, it prefers jobs that fit whole on its card, and its ComfyUI lets go of its memory before each job and when idle.`);
        else if (ramOn) log("Its RAM guard is off: it takes any job it can run, as before.");
        if (!ramSwitch) {
          ramWatch.clear();
          ramRead = null;
          ramGood = null;
        }
        ramOn = ramSwitch;
      }
      if (ramOn && !ramReading && t - ramReadAt >= ramGuard.everyMs) {
        ramReadAt = t;
        const roots = [process.pid, comfy.pid, cpuComfy?.pid ?? null, text?.server?.pid ?? null];
        ramReading = (deps.readProcs ?? readProcs)(cfg.powershell)
          .catch(() => null)
          .then((procs) => {
            const usedMb = (deps.ramNow ?? ramNow)().usedMb;
            ramRead = { split: procs && usedMb !== null ? ramSplit(usedMb, procs, roots) : null };
          })
          .finally(() => (ramReading = null));
      }
      if (ramOn && ramRead) {
        const { split: got } = ramRead;
        ramRead = null;
        if (got) {
          ramGood = got;
          ramGoodAt = t;
          ramFailSaid = false;
        } else if (!ramFailSaid) {
          log("Couldn't read the memory of this PC's programs: its RAM guard tries again at the next reading.");
          ramFailSaid = true;
        }
        const wasOver = ramWatch.over;
        ramWatch.update(t - ramGoodAt <= RAM_REUSE_MS ? ramGood : null);
        if (!wasOver && ramWatch.over) {
          log(`Other programs use ${gbOf(ramWatch.othersMb)} of this PC's memory${ramWatch.who ? ` (the most: ${ramWatch.who})` : ""}, above its RAM guard's line of ${gbOf(ramGuard.othersMb)}: it prefers jobs that fit whole on its card, and its ComfyUI lets go of its memory before each job and when idle.`);
          ramIdleFreed = false;
        } else if (wasOver && !ramWatch.over) log("Other programs' memory is under its RAM guard's line again: it takes any job it can run, as before.");
      }
      // Above the line with no GPU job in hand: its own ComfyUI lets go of its memory, once until its next GPU job.
      if (ramOn && ramWatch.over && !ramIdleFreed && !busyJob && comfy.ready) {
        ramIdleFreed = true;
        await comfy.free();
      }
      if (comfyTrouble === "comfy-crashes" && !comfy.crashedTooOften(t) && t - guardMissingAt >= HOUR) comfyTrouble = null;
      // A ComfyUI that stopped answering (hung) is stopped; the next turn starts it again. Every beat looks at it (its
      // /system_stats), so one that answers anything at all is never taken for hung.
      if (comfy.alive() && comfy.ready && t - comfy.answeredAt > (cfg.hungMin ?? 3) * 60_000) {
        log("Its ComfyUI stopped answering: starting it again.");
        await comfy.stop();
      }
      if (!modelsBack && t - modelsCheckedAt >= (deps.modelsCheckMs ?? MODELS_CHECK_MS)) {
        modelsCheckedAt = t;
        const missing = missingModelDirs(cfg.modelDirs);
        if (missing.length && !modelsMissing.length) {
          sayMissing(missing);
          modelsMissing = missing;
        } else if (!missing.length && modelsMissing.length) {
          // Its files are read again first, so the studio gets the whole list before it takes a job.
          log("Its model folders are all there: looking at them again.");
          modelsBack = rescan().finally(() => {
            modelsMissing = missingModelDirs(cfg.modelDirs);
            modelsBack = null;
          });
        } else modelsMissing = missing;
      }
      let next = localPause(control, gpu, comfyTrouble, t, modelsMissing) ?? { paused: false, why: null, until: null };
      // Waiting for its turn is not a pause: its jobs keep their place in the line. The helper's estimate of the start
      // goes with it.
      if (!next.paused && turn.waitForYield) next = { paused: false, why: turn.late ? "waiting-for-yield:no-answer" : "waiting-for-yield", until: turn.startsAt };
      const changed = next.paused !== pause.paused || next.why !== pause.why || next.until !== pause.until;
      pause = next;
      // A new pause, or every 5 s while busy or in a turn and 10 s otherwise: beat.
      let beaten = false;
      if (changed || t - beatAt >= (busyJob || turn.siteWaiting > 0 ? 5000 : 10_000)) {
        beatAt = t;
        beaten = true;
        try {
          const a = await runner.beat();
          reach.back();
          if (runner.view.stopped) {
            log(runner.view.stopped === "signed-out" ? "The studio doesn't know this worker's token. Run fuobe worker setup again." : "The studio stopped this worker.");
            break;
          }
          if (a?.worker?.sendInventory && !modelsMissing.length) {
            const r = await call("/api/gpu/computer/inventory", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(inv) });
            if (r.ok) {
              const body = await r.json();
              log(`Sent its files: it can run ${body.workflows?.length ?? 0} of the studio's workflows.`);
            }
          }
        } catch (e) {
          reach.miss(e);
        }
      }
      // Its model folders, again every 10 minutes (in the background: beats go on while it hashes a new file).
      if (t - scannedAt >= (deps.rescanMs ?? RESCAN_MS) && !scanning && !modelsMissing.length) void rescan();
      // Its own ComfyUI runs only while it may work; a pause (and a stop-now) frees the GPU.
      const stopNow = (pause.paused && (pause.why === "here-now" || pause.why?.startsWith("gpu-busy"))) || answer?.worker?.pauseNow;
      // Studio jobs first: the turn, from what the beat said and what holds the GPU; site.json on every beat, on a change,
      // and every 5 s (the helper counts a file older than 15 s as gone).
      let holdBack = false;
      if (turns) {
        const s = siteOf(answer);
        const workHolds = (split?.workMb ?? 0) > busyMb;
        const was = turn;
        turn = turns.step(t, {
          may: turnsReady(t) && !pause.paused && !!mayWork(),
          // A busy reading that may still turn into a pause begins no turn and ends none (no new job starts either).
          unsure: gpu.busyInARow > 0,
          claimable: s.claimable,
          busy: busyJob && jobUsesGpu && !stopNow,
          workHolds,
          workThere: !!split && (split.work.pids.length > 0 || !!split.work.lock),
          // The beat has no request to interrupt local work, and no wait of its own: the worker counts the wait itself.
          serverInterrupt: false,
        });
        if (turn.waitForYield && !was.waitForYield) log("Local ComfyUI work holds the GPU: asking it to make room for the studio's jobs.");
        if (turn.late && !was.late) log("Local ComfyUI work hasn't answered for 3 minutes: still waiting, with the jobs kept in line.");
        if (was.waitForYield && !turn.waitForYield && turn.siteWaiting > 0) log("Local ComfyUI work made room: starting.");
        if (turn.ended === "idle") {
          log("No studio job for a minute: its ComfyUI lets go of its memory for local work.");
          if (comfy.ready && !busyJob) await comfy.free();
        }
        if (turns.folderOk() && (beaten || JSON.stringify([turn.siteWaiting, turn.interruptAt]) !== siteWritten || t - siteAt >= 5000)) {
          writeTurn(t, { siteWaiting: turn.siteWaiting, oldestWaitS: turn.oldestWaitS, interrupt: turn.interrupt, interruptAt: turn.interruptAt });
        }
        // The owner's own job asks for no turn. Local ComfyUI work that runs nothing and only keeps its models loaded is
        // asked to free its memory (its /queue read first, then its /free), and the worker takes the job. Work that runs
        // a job, or that can't be asked (no port: the lock decided), is left alone, and the owner's job waits.
        const ownerOnly = turnsReady(t) && workHolds && turn.siteWaiting === 0 && !turn.waitForYield && s.owner > 0 && gpu.busyInARow === 0;
        let roomForOwner = false;
        if (ownerOnly && !busyJob && comfy.ready && mayWork() && !stopNow) {
          if (t - roomAt < ROOM_MS) roomForOwner = true;
          else if (t - idleLookAt >= IDLE_LOOK_MS) {
            idleLookAt = t;
            const ports = split?.work?.ports ?? [];
            if (ports.length && (await localIdle(localFetch, ports))) {
              log(`Local ComfyUI work on port ${ports.join(", ")} runs nothing and keeps its models loaded: asking it to free its memory for the owner's job.`);
              await freeLocal(localFetch, ports);
              // The reading from before the free is out of date: the next turn reads the GPU again, so the owner's job
              // doesn't count the freed memory as local work still holding the GPU (and ask it for room after the job).
              split = null;
              lastGpuAt = -Infinity;
              roomAt = now();
              roomForOwner = true;
              ownerWaitSaid = false;
            } else if (!ownerWaitSaid) {
              log("The owner's job waits for local ComfyUI work to finish.");
              ownerWaitSaid = true;
            }
          }
        } else if (!ownerOnly) ownerWaitSaid = false;
        // No new job while local ComfyUI work holds the GPU, unless a turn has begun and it made room, or it was idle
        // and freed its memory for the owner's job.
        holdBack = turn.waitForYield || (turnsReady(t) && workHolds && turn.siteWaiting === 0 && !roomForOwner) || gpu.busyInARow > 0;
      }
      // Kept results go up before its ComfyUI starts (they need none, and a start can take minutes), unless the studio
      // said a moment ago that their job isn't this worker's now.
      const heldFirst = hold.ids().length > 0 && t >= heldRetryAt && (!busyJob || !jobUsesGpu);
      if (mayWork()) {
        if (!comfy.alive() && !starting && !comfyTrouble && t >= comfy.restartAt && !heldFirst) {
          if (comfy.crashedTooOften(t)) {
            comfyTrouble = "comfy-crashes";
            log("ComfyUI keeps stopping: pausing for an hour.");
          } else {
            log("Starting its own ComfyUI.");
            // In the background: beats go on while it starts. The packs by their folder names on disk, which is what
            // ComfyUI matches (whatever the catalog's case).
            starting = comfy
              .start(
                packs.map((p) => p.folder),
                { signal: stopStarts.signal },
              )
              .then(() => readLoadedNodes())
              // Its face check comes before its first claim: no claim while `starting` holds.
              .then(() => checkFaces("after its start", { start: true }))
              .catch((e) => {
                if (stopStarts.signal.aborted) return;
                if (e instanceof PortBusy) {
                  comfyTrouble = "port-busy";
                  troubleAt = now();
                  log(`${e.message}: it won't start ComfyUI there, and won't connect to it.`);
                } else if (e instanceof GuardMissing) {
                  // Not again for an hour: it would only start the same ComfyUI again.
                  comfyTrouble = "comfy-crashes";
                  guardMissingAt = now();
                  log(`${e.message}: it won't use it, and pauses for an hour.`);
                } else if (mayWork()) log(`ComfyUI didn't start: ${e.message}`);
              })
              .finally(() => (starting = null));
          }
        }
        // A face check it owes, between jobs and before its next claim (it holds `starting`, so no claim meanwhile).
        if (facesOwed && facesDownAt === null && comfy.ready && !starting && !busyJob && (facesOwed === "restart" || !faceGpuBusy())) {
          starting = checkFaces("between jobs")
            .catch((e) => log(`Its face check between jobs didn't run: ${e.message}`))
            .finally(() => (starting = null));
        }
        if (comfy.ready && !starting && answer?.runner && !busyJob && !holdBack && !heldFirst && claimDue(t, gpuMissedAt, siteOf(answer).claimable ?? 0, idleClaimMs)) take();
      } else if (comfy.alive() && (stopNow || !busyJob)) {
        log("Stopping its own ComfyUI (paused).");
        await comfy.stop();
      }
      // The CPU slot: its ComfyUI runs only while the worker may work, and it takes its own work beside the GPU's job (it
      // needs no turn and no free GPU). Another program on the GPU lets its task finish; a stop-now stops it too.
      if (cpuOn) {
        if (mayWork()) {
          if (!cpuComfy.alive() && !cpuStarting && t >= cpuComfy.restartAt && !cpuComfy.crashedTooOften(t)) {
            cpuStarting = cpuComfy
              .start(
                packs.map((p) => p.folder),
                { signal: stopStarts.signal },
              )
              .catch((e) => {
                if (!stopStarts.signal.aborted && mayWork()) log(`Its CPU slot's ComfyUI didn't start: ${e.message}`);
              })
              .finally(() => (cpuStarting = null));
          }
          if (cpuComfy.ready && answer?.runner && !busyCpu && claimDue(t, cpuMissedAt, 0, idleClaimMs)) takeCpu();
        } else if (cpuComfy.alive() && (!busyCpu || pause.why === "here-now" || answer?.worker?.pauseNow)) {
          await cpuComfy.stop();
        }
      }
      // The text slot: never while paused by hand, on the website or outside its hours. While the worker waits for its
      // GPU's job to end before it restarts on new code, the text slot goes on: text jobs take seconds.
      if (text) {
        const byHand = pause.paused && /^here/.test(pause.why ?? "");
        const turn = textTurn({ updating, gpuBusy: busyJob || busyCpu, byHand, worker: answer?.worker ?? null });
        text.tick(t, { ...turn, room: textRoom() });
      }
      // Kept results the studio never took are deleted after a day.
      if (t - holdCheckedAt >= 60_000) {
        holdCheckedAt = t;
        for (const id of hold.expire(t, HOLD_MAX_AGE_MS)) log(`Deleted the kept results of job ${id}: the studio didn't take them for a day.`);
      }
      // Kept results go up first, and even while it may not work (or waits for its turn): they need no GPU and no ComfyUI.
      // Not while it ends for new code: they stay for its next start.
      if (!busyJob && answer && heldFirst && !updating) take({ onlyHeld: true });
      // Why the line's work waits on it, while the studio says work waits that it could take (the beat's `holding`, with
      // since when): a pause of its own or on the website is said by the beat already, and a job of its own runs.
      {
        const s = siteOf(answer);
        let why = null;
        if ((s.claimable ?? 0) + s.owner > 0) {
          if (updating) why = "updating";
          else if ((busyJob && jobUsesGpu) || !mayWork() || !answer?.runner) why = null;
          else if (heldFirst || busyJob) why = "sending-kept";
          else if (!comfy.ready || starting) why = "starting-comfy";
          else if (turn.waitForYield) why = "waiting-for-yield";
          else if (gpu.busyInARow > 0) why = "gpu-check";
          else if (holdBack) why = "local-work";
        }
        holding = why ? { why, since: holding?.why === why ? holding.since : now() } : null;
      }
      // Awake while it holds a job, has results to send, or waits for work.
      awake.set(!!answer?.worker && (busyJob || busyCpu || hold.ids().length > 0 || !!mayWork()));
      // A taken port is tried again (a bind test, never a connection) once a minute.
      if (comfyTrouble === "port-busy" && t - troubleAt >= 60_000) comfyTrouble = null;
      const s = state();
      if (s !== lastState) {
        lastState = s;
        log(s);
      }
      writeStatus(deps.home, { state: s, pause, at: t, comfy: comfy.alive() ? comfy.pid : null, answer: answer?.worker ?? null, ...(updateWanted && !updating && { update: { asked: updateWanted.at, why: updateWanted.why } }) });
      const before = now();
      await sleep(1000);
      // A second that took over a minute: the PC slept (the whole process stopped). The next beat says so.
      const gap = now() - before;
      if (gap >= SLEPT_MS) {
        slept += gap;
        log(`The PC slept for about ${Math.max(1, Math.round(gap / 60_000))} min: the studio hears it, so a job taken back meanwhile counts against no one.`);
      }
    }
  } finally {
    // Every way out: the job in hand stops (its kept results stay for the next start), its ComfyUI stops, the PC may
    // sleep again, and no input, result or cached file stays in its folders.
    runner.stop();
    cpuRunner?.stop();
    await Promise.race([Promise.all([job, cpuJob]), new Promise((r) => setTimeout(r, 10_000).unref?.())]);
    await text?.end(updating && !deps.signal?.aborted ? "updating" : "stopped");
    awake.set(false);
    // No turn any more: local ComfyUI work may go on at once.
    if (turns?.folderOk()) writeTurn(now(), { siteWaiting: 0, oldestWaitS: 0, interrupt: false, interruptAt: null });
    // A start under way ends first (it stops at the signal), so no ComfyUI is left behind.
    stopStarts.abort();
    await comfy.stop();
    await starting;
    await comfy.stop();
    emptyFolders(f);
    emptyCache();
    if (cpuOn) {
      await cpuComfy.stop();
      await cpuStarting;
      await cpuComfy.stop();
      emptyFolders(fc);
      emptyCpuCache();
    }
  }
  return deps.signal?.aborted ? "aborted" : (runner.view.stopped ?? (updating ? "update" : "disconnected"));
}