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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Workers: studio jobs go before local ComfyUI work on the same PC
Adarshe4f404857b25
diff --git a/bin/lib/worker/config.mjs b/bin/lib/worker/config.mjsindex 2eaa9926..1ea04abd 100644--- a/bin/lib/worker/config.mjs+++ b/bin/lib/worker/config.mjs@@ -30,6 +30,25 @@ export const DEFAULTS = {resumeAfterMin: 10,resumeBelowC: 75,nvidiaSmi: "nvidia-smi",+ /**+ * Studio jobs first: a folder for the two turn files (site.json, yielded.json). None: every program that uses the GPU+ * pauses the worker, as before. The PC's setup makes the folder; the worker never makes it.+ */+ yieldFolder: null,+ /** Local ComfyUI work: python processes that listen on a port in this range, [low, high]. */+ localComfyPorts: [8188, 8199],+ /** Ports and process ids in that range that never count as local ComfyUI work. */+ localComfyExcludePorts: [],+ localComfyExcludePids: [],+ /** The desktop's usual share of the GPU's memory, measured at setup (`fuobe worker baseline`). */+ desktopBaselineMb: 0,+ /** Only when the GPU counters can't be read: a lock file, and the owners it may name that count as ComfyUI work. */+ gpuLockFile: null,+ gpuLockComfyOwners: [],+ /** Local caps the studio can't change: hours of turns a day, minutes between two interrupts, and never interrupt. */+ yieldMaxHoursPerDay: 20,+ interruptGapMin: 30,+ neverInterrupt: false,};const file = (home, name) => path.join(home, name);diff --git a/bin/lib/worker/gpu.mjs b/bin/lib/worker/gpu.mjsindex bf3c02bc..360eb07b 100644--- a/bin/lib/worker/gpu.mjs+++ b/bin/lib/worker/gpu.mjs@@ -72,9 +72,9 @@ export function othersOf(reading, own, busyVramMb) {/*** The automatic pause and resume. `update` takes each reading's verdict; `paused` says whether the GPU keeps the worker- * paused now. Busy pauses at once; with `autoResume`, it resumes once the GPU stayed free for `resumeAfterMs` in a row- * and is cooler than `resumeBelowC`. Any busy reading starts the cool-down again. Without autoResume, only `clear()` (a- * resume by hand) ends it.+ * paused now. Busy pauses after `busyReadings` busy readings in a row (1, the default: at once); with `autoResume`, it+ * resumes once the GPU stayed free for `resumeAfterMs` in a row and is cooler than `resumeBelowC`. Any busy reading+ * starts the cool-down again. Without autoResume, only `clear()` (a resume by hand) ends it.*/export class GpuWatch {constructor(o) {@@ -82,15 +82,23 @@ export class GpuWatch {this.paused = false;this.who = null;this.freeSince = null;+ this.busyInARow = 0;+ /** What the last busy reading saw: "work" for local ComfyUI work only (studio jobs first), else null. */+ this.cause = null;}update(verdict, tempC, now) {if (verdict.busy) {- this.paused = true;- this.who = verdict.who;+ this.busyInARow++;this.freeSince = null;+ if (this.paused || this.busyInARow >= (this.o.busyReadings ?? 1)) {+ this.paused = true;+ this.who = verdict.who;+ this.cause = verdict.cause ?? null;+ }return;}+ this.busyInARow = 0;this.freeSince ??= now;if (this.paused && this.o.autoResume && now - this.freeSince >= this.o.resumeAfterMs && (tempC === null || tempC === undefined || tempC < this.o.resumeBelowC)) {this.paused = false;@@ -102,5 +110,7 @@ export class GpuWatch {clear() {this.paused = false;this.who = null;+ this.busyInARow = 0;+ this.cause = null;}}diff --git a/bin/lib/worker/local-work.mjs b/bin/lib/worker/local-work.mjsnew file mode 100644index 00000000..72e0661c--- /dev/null+++ b/bin/lib/worker/local-work.mjs@@ -0,0 +1,208 @@+// Telling local ComfyUI work apart from other programs (docs/gpu-workers.md, "Studio jobs first"). The worker never+// connects to another ComfyUI. It reads three things only:+//+// - Windows' table of listening ports (Get-NetTCPConnection -State Listen). Reading the table never connects to a port.+// A python process that listens on a port in the local range (worker.json) is local ComfyUI work. The worker's own+// ComfyUI (by its pid and its port) and the ports and pids worker.json excludes never count.+// - Windows' GPU counters, per process (\GPU Process Memory(pid_<n>_*)\Dedicated Usage), the same numbers Task Manager+// shows. nvidia-smi reads [N/A] per process on Windows, so it gives the total only.+// - A GPU lock file, only when the counters can't be read: an owner it names as ComfyUI work counts as ComfyUI work,+// and anything else as another program.+//+// Others = the GPU's total used memory, minus the worker's own ComfyUI, minus local ComfyUI work, minus the desktop's+// usual share (measured at setup).+import { execFile } from "node:child_process";+import fs from "node:fs";+import { CONTEXT_ALLOWANCE_MB } from "./gpu.mjs";++/** ComfyUI's own default port and the next few: where local ComfyUIs listen unless worker.json says otherwise. */+export const DEFAULT_PORTS = [8188, 8199];++/** The listening ports and their processes, and every process's name, as one JSON line. */+export const LISTEN_SCRIPT = [+ "$ErrorActionPreference = 'Stop'",+ "$l = @(Get-NetTCPConnection -State Listen | ForEach-Object { @{ port = [int]$_.LocalPort; pid = [int]$_.OwningProcess } })",+ "$n = @{}",+ "foreach ($p in Get-Process -ErrorAction SilentlyContinue) { $n[[string]$p.Id] = $p.ProcessName }",+ "@{ listeners = $l; names = $n } | ConvertTo-Json -Compress -Depth 4",+].join("; ");++/** typeperf, one sample of every process's dedicated GPU memory (bytes). */+export const COUNTERS_COMMAND = ["typeperf", "\\GPU Process Memory(*)\\Dedicated Usage", "-sc", "1"];++const MB = 2 ** 20;+const int = (v) => (Number.isInteger(Number(v)) && Number(v) > 0 ? Number(v) : null);++const run = (cmd, args, timeout) =>+ new Promise((resolve) => {+ execFile(cmd, args, { timeout, windowsHide: true, maxBuffer: 8 * MB }, (err, stdout) => resolve(err ? null : String(stdout)));+ });++const command = (cmd, fallback) => {+ const list = Array.isArray(cmd) ? cmd : cmd ? [cmd] : fallback;+ return [String(list[0]), list.slice(1).map(String)];+};++/** The port table's JSON → { listeners: [{ port, pid }], names: { pid: name } }, or null when it isn't one. */+export function parseListeners(text) {+ let o;+ try {+ o = JSON.parse(String(text ?? "").trim());+ } catch {+ return null;+ }+ if (!o || typeof o !== "object") return null;+ // ConvertTo-Json writes one listener as an object, not a list.+ const list = Array.isArray(o.listeners) ? o.listeners : o.listeners && typeof o.listeners === "object" ? [o.listeners] : [];+ const listeners = list.flatMap((l) => {+ const port = int(l?.port);+ const pid = int(l?.pid);+ return port && pid ? [{ port, pid }] : [];+ });+ const names = {};+ if (o.names && typeof o.names === "object") for (const [pid, name] of Object.entries(o.names)) if (int(pid) && typeof name === "string") names[pid] = name.slice(0, 64);+ return { listeners, names };+}++/** One look at the port table, or null when it can't be read (not Windows, or PowerShell refused). */+export async function readListeners(powershell = "powershell") {+ if (process.platform !== "win32" && !Array.isArray(powershell)) return null;+ const [bin, pre] = command(powershell, ["powershell"]);+ return parseListeners(await run(bin, [...pre, "-NoProfile", "-NonInteractive", "-Command", LISTEN_SCRIPT], 10_000));+}++const INSTANCE = /\(pid_(\d+)_luid_(0x[0-9a-f]+_0x[0-9a-f]+)_phys_(\d+)\)/i;+const cells = (line) => [...line.matchAll(/"((?:[^"]|"")*)"/g)].map((m) => m[1].replaceAll('""', '"'));++/** typeperf's CSV → [{ pid, gpu, mb }] (gpu: the adapter's luid and phys), or null when it holds no sample. */+export function parseCounters(text) {+ const lines = String(text ?? "").split(/\r?\n/);+ const at = lines.findIndex((l) => l.startsWith('"(PDH-CSV'));+ if (at < 0) return null;+ const head = cells(lines[at]);+ const row = lines.slice(at + 1).find((l) => l.startsWith('"'));+ if (!row) return null;+ const values = cells(row);+ const out = [];+ head.forEach((h, i) => {+ const m = INSTANCE.exec(h);+ const v = Number(values[i]);+ if (m && values[i]?.trim() && Number.isFinite(v) && v >= 0) out.push({ pid: Number(m[1]), gpu: `${m[2].toLowerCase()}_${m[3]}`, mb: v / MB });+ });+ return out;+}++/** One reading of the GPU counters, or null when they can't be read. */+export async function readCounters(cmd) {+ if (process.platform !== "win32" && !cmd) return null;+ const [bin, args] = command(cmd, COUNTERS_COMMAND);+ return parseCounters(await run(bin, args, 15_000));+}++/** The lock file's first word: who holds the GPU now ("" for a lock with no name), or null when there is no lock. */+export function readLock(file) {+ if (!file) return null;+ try {+ const p = fs.statSync(file).isDirectory() ? `${file.replace(/[\\/]+$/, "")}/owner.txt` : file;+ const fd = fs.openSync(p, "r");+ try {+ const buf = Buffer.alloc(512);+ const n = fs.readSync(fd, buf, 0, buf.length, 0);+ return buf.subarray(0, n).toString("utf8").trim().split(/\s+/)[0] ?? "";+ } finally {+ fs.closeSync(fd);+ }+ } catch (e) {+ // A lock folder whose owner file isn't written yet still holds the GPU.+ return e?.code === "ENOENT" && fs.existsSync(file) ? "" : null;+ }+}++const isPython = (name) => /^python(w|3(\.\d+)?)?(\.exe)?$/i.test(String(name ?? ""));++/**+ * The pids of local ComfyUI work: python processes that listen on a port in `ports` ([low, high]), not the worker's own+ * ComfyUI (its pid, or its port) and not an excluded port or pid. Also the worker's own pids, and the first work port.+ */+export function workPids(listing, o) {+ const [lo, hi] = Array.isArray(o.ports) && o.ports.length === 2 ? o.ports.map(Number) : DEFAULT_PORTS;+ const own = new Set([o.ownPid].filter(Boolean));+ for (const l of listing?.listeners ?? []) if (o.ownPort && l.port === o.ownPort) own.add(l.pid);+ const excludePorts = new Set((o.excludePorts ?? []).map(Number));+ const excludePids = new Set((o.excludePids ?? []).map(Number));+ const work = new Map();+ for (const l of listing?.listeners ?? []) {+ if (l.port < lo || l.port > hi || own.has(l.pid) || excludePorts.has(l.port) || excludePids.has(l.pid)) continue;+ if (!isPython(listing.names?.[l.pid])) continue;+ if (!work.has(l.pid)) work.set(l.pid, l.port);+ }+ return { own, work };+}++/** The adapter the counters are read for: the one worker.json names, else the one whose processes hold the most. */+export function pickGpu(counters, prefer) {+ const sums = new Map();+ for (const c of counters) sums.set(c.gpu, (sums.get(c.gpu) ?? 0) + c.mb);+ if (prefer && sums.has(String(prefer).toLowerCase())) return String(prefer).toLowerCase();+ let best = null;+ for (const [gpu, mb] of sums) if (best === null || mb > sums.get(best)) best = gpu;+ return best;+}++/** Does the reading show a process holding real memory that the last port table doesn't know? (Then look again.) */+export function unknownHolder(counters, listing, ownPid, minMb) {+ if (!counters) return false;+ if (!listing) return true;+ const known = new Set(listing.listeners.map((l) => l.pid));+ return counters.some((c) => c.mb > minMb && c.pid !== ownPid && !known.has(c.pid) && isPython(listing.names?.[c.pid] ?? "python"));+}++/**+ * Split the GPU's used memory: { ownMb, workMb, othersMb, who, work: { pids, port }, source }.+ * `who` names the biggest other program (for the busy pause). `source`: "counters", "lock" (the counters failed, the+ * lock decided) or "total" (neither: everything that isn't the worker's own counts as another program, which fails+ * safe). `o`: { usedMb, apps (nvidia-smi's, for names), counters, listing, own: { pid, port, running, mb }, ports,+ * excludePorts, excludePids, baselineMb, lock (readLock's), lockOwners, gpu }.+ */+export function splitMemory(o) {+ const base = Math.max(0, Number(o.baselineMb) || 0);+ const torchOwn = o.own.running ? (o.own.mb ?? 0) + CONTEXT_ALLOWANCE_MB : 0;+ if (o.counters && o.listing) {+ const { own, work } = workPids(o.listing, { ports: o.ports, ownPid: o.own.pid, ownPort: o.own.port, excludePorts: o.excludePorts, excludePids: o.excludePids });+ const gpu = pickGpu(o.counters, o.gpu);+ const mine = o.counters.filter((c) => c.gpu === gpu);+ const sum = (pids) => mine.filter((c) => pids.has(c.pid)).reduce((n, c) => n + c.mb, 0);+ const counted = sum(own);+ // Its own ComfyUI before the counters list it: what torch says, as before.+ const ownMb = counted > 0 ? counted : torchOwn;+ const workMb = sum(new Set(work.keys()));+ const othersMb = Math.max(0, o.usedMb - ownMb - workMb - base);+ const others = mine.filter((c) => !own.has(c.pid) && !work.has(c.pid) && c.mb > 0).sort((a, b) => b.mb - a.mb);+ const top = others[0];+ const who = top ? (o.listing.names?.[top.pid] ?? o.apps?.find((a) => a.pid === top.pid)?.name ?? "another program") : "another program";+ const firstPort = [...work.values()][0] ?? null;+ return { ownMb, workMb, othersMb, who, work: { pids: [...work.keys()], port: firstPort }, source: "counters" };+ }+ const rest = Math.max(0, o.usedMb - torchOwn - base);+ const owners = (o.lockOwners ?? []).map((s) => String(s).toLowerCase()).filter(Boolean);+ if (o.lock !== null && o.lock !== undefined && owners.some((w) => String(o.lock).toLowerCase().startsWith(w))) {+ return { ownMb: torchOwn, workMb: rest, othersMb: 0, who: null, work: { pids: [], port: null, lock: true }, source: "lock" };+ }+ const named = o.apps?.find((a) => a.pid !== o.own.pid && (a.usedMb === null || a.usedMb > 0))?.name;+ return { ownMb: torchOwn, workMb: 0, othersMb: rest, who: o.lock !== null && o.lock !== undefined ? "another program" : (named ?? "another program"), work: { pids: [], port: null }, source: o.lock !== null && o.lock !== undefined ? "lock" : "total" };+}++/**+ * The desktop's usual share of the GPU, measured once at setup with no game or other GPU program open: the used memory+ * minus local ComfyUI work, from the counters. Null when the counters or the port table can't be read.+ */+export async function measureBaseline(cfg, deps = {}) {+ const { readGpu } = await import("./gpu.mjs");+ const reading = await (deps.readGpu ?? readGpu)(cfg.nvidiaSmi);+ if (!reading) return null;+ const counters = await (deps.readCounters ?? readCounters)(cfg.gpuCounters);+ const listing = counters ? await (deps.readListeners ?? readListeners)(cfg.powershell) : null;+ if (!counters || !listing) return null;+ const split = splitMemory({ usedMb: reading.usedMb, apps: reading.apps, counters, listing, own: { pid: null, port: null, running: false, mb: null }, ports: cfg.localComfyPorts, excludePorts: cfg.localComfyExcludePorts, excludePids: cfg.localComfyExcludePids, baselineMb: 0, gpu: cfg.gpuLuid });+ return Math.round(split.othersMb);+}diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex fc18d096..9d4fa854 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -8,6 +8,10 @@// 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.import crypto from "node:crypto";import fs from "node:fs";import path from "node:path";@@ -19,8 +23,10 @@ import { PROTOCOL, readControl, writeControl, writeStatus } from "./config.mjs";import { GpuWatch, othersOf, readGpu } from "./gpu.mjs";import { Hold } from "./hold.mjs";import { inventoryHash, modelFiles, packFolders } from "./inventory.mjs";+import { readCounters, readListeners, readLock, splitMemory, unknownHolder } from "./local-work.mjs";import { ffmpegVersion, mediaKind, reencode } from "./media.mjs";import { retrying } from "./retry.mjs";+import { SiteTurns, writeSite } from "./turns.mjs";const here = path.dirname(fileURLToPath(import.meta.url));const ROOT = path.resolve(here, "../../..");@@ -73,12 +79,26 @@ export function localPause(control, gpu, comfyTrouble, now) {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 (the studio's jobs this worker may take now; null when the studio+ * doesn't say, and then local ComfyUI work counts as another program, as before), oldestWaitS, interrupt }.+ */+export function siteOf(answer) {+ const w = answer?.worker ?? {};+ return {+ claimable: count(answer?.claimableNow) ?? count(w.claimableNow),+ oldestWaitS: count(answer?.oldestWaitS) ?? count(w.oldestWaitS),+ interrupt: w.yieldInterrupt === true || answer?.yieldInterrupt === true,+ };+}/*** 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,* signal, requirements, ComputerRunner, rules, pins, allowed, ffmpegVersion, reencode, awake, rescanMs, comfy (OwnComfy's own- * options) }.+ * options), readCounters, readListeners, gpuEveryMs }.*/export async function runWorker(cfg, deps) {const now = deps.now ?? Date.now;@@ -103,7 +123,21 @@ export async function runWorker(cfg, deps) {const comfy = new OwnComfy(cfg, { now, fetch: fetchFn, folderNames: index.folders ?? [], log, ...deps.comfy });// A ComfyUI that a stopped worker left running is stopped now, before anything else uses the GPU.await comfy.stopLeftover();- const gpu = new GpuWatch({ autoResume: !!cfg.autoResume, resumeAfterMs: (cfg.resumeAfterMin ?? 10) * 60_000, resumeBelowC: cfg.resumeBelowC ?? 75 });+ // 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).+ const gpu = new GpuWatch({ autoResume: !!cfg.autoResume, resumeAfterMs: (cfg.resumeAfterMin ?? 10) * 60_000, resumeBelowC: cfg.resumeBelowC ?? 75, busyReadings: turns ? 2 : 1 });const awake = deps.awake ?? new StayAwake({ now, log });const ffmpeg = await (deps.ffmpegVersion ?? ffmpegVersion)(cfg.ffmpeg);log(ffmpeg ? "ffmpeg is there: it takes clips and sound, and makes each one again first." : "No ffmpeg set (ffmpeg in worker.json): it takes pictures only.");@@ -120,6 +154,26 @@ export async function runWorker(cfg, deps) {let job = Promise.resolve();let lastTask = null;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;+ let split = null;+ let turn = { siteWaiting: 0, oldestWaitS: 0, interrupt: false, waitForYield: false, late: false, startsAt: null, ended: null };+ let siteWritten = "";+ let siteAt = 0;+ let siteFailed = false;+ const writeTurn = (t, body) => {+ const key = JSON.stringify([body.siteWaiting, body.interrupt]);+ 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");@@ -269,18 +323,63 @@ export async function runWorker(cfg, deps) {);const mayWork = () => !pause.paused && answer?.worker && !answer.worker.paused && answer.worker.insideHours && !answer.worker.drain;- const state = () => (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" : comfy.ready ? "Ready" : "Starting ComfyUI");+ const state = () =>+ 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;job = runner.claimAndRun(o).catch((e) => log(`A job stopped: ${e.message}`)).finally(() => {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) {+ const counters = await (deps.readCounters ?? readCounters)(cfg.gpuCounters);+ if (counters && (t - listedAt >= 30_000 || (listing && unknownHolder(counters, listing, own.pid, busyMb)))) {+ listing = await (deps.readListeners ?? readListeners)(cfg.powershell);+ 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;let lastState = "";try {@@ -298,12 +397,26 @@ export async function runWorker(cfg, deps) {gpu.clear();gpu.clearedAt = control.resumedAt;}- // The GPU, every 5 s, from nvidia-smi only.- if (t - lastGpuAt >= 5000) {+ // 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);if (reading) {- const verdict = othersOf(reading, { running: comfy.alive(), mb: await comfy.vramMb(), pid: comfy.pid }, cfg.busyVramMb ?? 1024);+ const own = { running: comfy.alive(), mb: await comfy.vramMb(), pid: comfy.pid, port: comfy.alive() ? comfy.port : null };+ 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;+ verdict = { busy: othersBusy || workBusy, who: othersBusy ? split.who : `ComfyUI${split.work.port ? ` on port ${split.work.port}` : ""}`, othersMb: split.othersMb, cause: othersBusy ? null : "work" };+ // 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);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 };@@ -318,12 +431,17 @@ export async function runWorker(cfg, deps) {log("Its ComfyUI stopped answering: starting it again.");await comfy.stop();}- const next = localPause(control, gpu, comfyTrouble, t) ?? { paused: false, why: null, until: null };- const changed = next.paused !== pause.paused || next.why !== pause.why;+ let next = localPause(control, gpu, comfyTrouble, t) ?? { 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 and 10 s otherwise: beat.- if (changed || t - beatAt >= (busyJob ? 5000 : 10_000)) {+ // 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();if (runner.view.stopped) {@@ -345,6 +463,36 @@ export async function runWorker(cfg, deps) {if (t - scannedAt >= (deps.rescanMs ?? RESCAN_MS) && !scanning) 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, {+ // A busy reading that may still turn into a pause asks for nothing.+ may: turnsReady(t) && !pause.paused && !!mayWork() && gpu.busyInARow === 0,+ claimable: s.claimable,+ busy: busyJob && jobUsesGpu && !stopNow,+ workHolds,+ workThere: !!split && (split.work.pids.length > 0 || !!split.work.lock),+ serverInterrupt: s.interrupt,+ oldestWaitS: s.oldestWaitS,+ });+ 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 made room after 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.interrupt]) !== siteWritten || t - siteAt >= 5000)) {+ writeTurn(t, { siteWaiting: turn.siteWaiting, oldestWaitS: turn.oldestWaitS, interrupt: turn.interrupt });+ }+ // No new job while local ComfyUI work holds the GPU, unless a turn has begun and it made room.+ holdBack = turn.waitForYield || (turnsReady(t) && workHolds && turn.siteWaiting === 0) || gpu.busyInARow > 0;+ }if (mayWork()) {if (!comfy.alive() && !comfyTrouble && t >= comfy.restartAt) {if (comfy.crashedTooOften(t)) {@@ -369,13 +517,13 @@ export async function runWorker(cfg, deps) {}}}- if (comfy.ready && answer?.runner && !busyJob) take();+ if (comfy.ready && answer?.runner && !busyJob && !holdBack) take();} else if (comfy.alive() && (stopNow || !busyJob)) {log("Stopping its own ComfyUI (paused).");await comfy.stop();}- // Kept results go up even while it may not work: they need no GPU and no ComfyUI.- if (!busyJob && answer && hold.ids().length && !(mayWork() && comfy.ready)) take({ onlyHeld: true });+ // Kept results go up even while it may not work (or waits for its turn): they need no GPU and no ComfyUI.+ if (!busyJob && answer && hold.ids().length && !(mayWork() && comfy.ready && !holdBack)) take({ onlyHeld: true });// Awake while it holds a job, has results to send, or waits for work.awake.set(!!answer?.worker && (busyJob || hold.ids().length > 0 || !!mayWork()));// A taken port is tried again (a bind test, never a connection) once a minute.@@ -394,6 +542,8 @@ export async function runWorker(cfg, deps) {runner.stop();await Promise.race([job, new Promise((r) => setTimeout(r, 10_000).unref?.())]);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 });await comfy.stop();emptyFolders(f);emptyCache();diff --git a/bin/lib/worker/turns.mjs b/bin/lib/worker/turns.mjsnew file mode 100644index 00000000..e3c4ea29--- /dev/null+++ b/bin/lib/worker/turns.mjs@@ -0,0 +1,190 @@+// Studio jobs first (docs/gpu-workers.md): while local ComfyUI work holds the GPU, the worker asks for a turn through two+// small files in a folder that worker.json names, and a helper on the PC's side answers.+//+// - site.json, which the worker writes on every beat: { siteWaiting, oldestWaitS, interrupt, at }. siteWaiting counts+// the studio's jobs this worker may take now (the beat's claimableNow) plus the one it runs. While a turn lasts it is+// at least 1, and it goes to 0 when the studio has had no job for it for a minute (the worker then frees its own+// ComfyUI's memory), when it is paused, or when a local cap is reached.+// - yielded.json, which the helper writes: { state: "yielding" | "yielded", at, startsAt? }. A fresh "yielded" lets the+// worker start at once. "yielding" may carry the helper's estimate of the start (startsAt), which the beat passes on.+//+// The studio can't change the caps here: at most `maxHoursPerDay` hours of turns a day, at most one interrupt per+// `interruptGapMin` minutes, and `neverInterrupt`, which always wins. The worker only writes numbers; the helper+// decides what to do with them.+import fs from "node:fs";+import path from "node:path";++const HOUR = 3_600_000;++export const TURNS = {+ /** No job for this long ends a turn. */+ graceMs: 60_000,+ /** A "yielded" written this recently counts, whenever the turn began. */+ freshMs: 15_000,+ /** No answer for this long: the worker says so in its beat and its log. */+ lateMs: 3 * 60_000,+ /** A tick counts towards the day's hours for at most this long (a PC that slept doesn't use up the day). */+ maxTickMs: 10_000,+};++const finite = (v) => typeof v === "number" && Number.isFinite(v);++/** The helper's answer, or null when there is none or it isn't one. */+export function readYielded(folder) {+ try {+ const p = path.join(folder, "yielded.json");+ if (fs.statSync(p).size > 4096) return null;+ const o = JSON.parse(fs.readFileSync(p, "utf8"));+ if (!o || typeof o !== "object" || !["yielding", "yielded"].includes(o.state) || !finite(o.at)) return null;+ return { state: o.state, at: o.at, startsAt: finite(o.startsAt) ? o.startsAt : null };+ } catch {+ return null;+ }+}++/** site.json, written whole (a reader never sees half of it). */+export function writeSite(folder, body) {+ const p = path.join(folder, "site.json");+ const tmp = `${p}.${process.pid}.tmp`;+ fs.writeFileSync(tmp, `${JSON.stringify(body)}\n`);+ fs.renameSync(tmp, p);+}++/** The local day (a cap counts per day on this PC's clock). */+const dayOf = (t) => {+ const d = new Date(t);+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;+};++/**+ * The turns on this PC. `step(t, facts)` runs once a loop and says what to write and whether to wait:+ * { siteWaiting, oldestWaitS, interrupt, waitForYield, late, startsAt, ended } — `ended` is "idle" when a turn ended+ * because no job came for a minute (free its own ComfyUI's memory), "stopped" when it ended for any other reason.+ */+export class SiteTurns {+ /** `o`: { folder, stateFile, maxHoursPerDay, interruptGapMin, neverInterrupt, graceMs }. */+ constructor(o) {+ this.o = o;+ this.active = false;+ this.startAt = 0;+ this.lastWantAt = 0;+ this.lastTickAt = null;+ this.neededYield = false;+ this.interrupt = false;+ this.waitSince = null;+ this.waitingSince = null;+ this.savedAt = 0;+ this.saved = this.load();+ }++ load() {+ try {+ const s = JSON.parse(fs.readFileSync(this.o.stateFile, "utf8"));+ return { day: typeof s.day === "string" ? s.day : "", usedMs: finite(s.usedMs) ? s.usedMs : 0, lastInterruptAt: finite(s.lastInterruptAt) ? s.lastInterruptAt : -Infinity };+ } catch {+ return { day: "", usedMs: 0, lastInterruptAt: -Infinity };+ }+ }++ save(t) {+ this.savedAt = t;+ try {+ fs.mkdirSync(path.dirname(this.o.stateFile), { recursive: true });+ fs.writeFileSync(this.o.stateFile, JSON.stringify({ ...this.saved, lastInterruptAt: finite(this.saved.lastInterruptAt) ? this.saved.lastInterruptAt : null }), { mode: 0o600 });+ } catch {}+ }++ /** The folder is there (the PC's setup makes it, with its rights; the worker never makes it). */+ folderOk() {+ try {+ return !!this.o.folder && fs.statSync(this.o.folder).isDirectory();+ } catch {+ return false;+ }+ }++ /** Hours of turns left today. */+ capLeft(t) {+ const max = Number(this.o.maxHoursPerDay ?? 20);+ if (!(max > 0)) return false;+ const used = this.saved.day === dayOf(t) ? this.saved.usedMs : 0;+ return used < max * HOUR;+ }++ /** The helper's answer counts for this turn. */+ yielded(t) {+ const y = readYielded(this.o.folder);+ if (!y || y.state !== "yielded" || y.at > t + 60_000) return false;+ return y.at >= this.startAt - 1000 || t - y.at <= TURNS.freshMs;+ }++ /**+ * `f`: { may (the worker may ask for a turn now: the folder is there, the studio says what it can take, nothing pauses+ * it), claimable (the beat's claimableNow), busy (a studio job runs here), workHolds (local ComfyUI work holds more+ * than busyVramMb), workThere (local ComfyUI work listens at all), serverInterrupt, oldestWaitS (the studio's, when+ * it says) }.+ */+ step(t, f) {+ const day = dayOf(t);+ if (this.saved.day !== day) this.saved = { ...this.saved, day, usedMs: 0 };+ if (this.active && this.lastTickAt !== null) this.saved.usedMs += Math.min(Math.max(0, t - this.lastTickAt), TURNS.maxTickMs);+ this.lastTickAt = t;+ const may = !!f.may && this.capLeft(t);+ const claimable = Math.max(0, Math.floor(Number(f.claimable) || 0));+ const want = (may && claimable > 0) || !!f.busy;+ let ended = null;+ if (want) {+ if (!this.active) {+ this.active = true;+ this.startAt = t;+ this.neededYield = false;+ this.interrupt = false;+ this.waitingSince = null;+ }+ this.lastWantAt = t;+ } else if (this.active && (!may || t - this.lastWantAt >= (this.o.graceMs ?? TURNS.graceMs))) {+ // Paused, a cap reached, or the studio stopped asking: at once. The line simply empty: after a minute.+ ended = may ? "idle" : "stopped";+ this.active = false;+ this.interrupt = false;+ this.waitingSince = null;+ this.save(t);+ }+ if (!this.active) {+ this.waitSince = null;+ return { siteWaiting: 0, oldestWaitS: 0, interrupt: false, waitForYield: false, late: false, startsAt: null, ended };+ }+ if (f.workHolds) this.neededYield = true;+ // The local ComfyUI work closed: nothing to wait for any more.+ if (!f.workThere && !f.workHolds) this.neededYield = false;+ const yielded = this.yielded(t);+ const waitForYield = !f.busy && this.neededYield && !yielded;+ if (waitForYield) {+ this.waitingSince ??= t;+ const gap = Number(this.o.interruptGapMin ?? 30) * 60_000;+ if (!this.interrupt && f.serverInterrupt === true && !this.o.neverInterrupt && t - this.saved.lastInterruptAt >= gap) {+ this.interrupt = true;+ this.saved.lastInterruptAt = t;+ this.save(t);+ }+ } else {+ this.waitingSince = null;+ if (yielded) this.interrupt = false;+ }+ if (this.o.neverInterrupt || f.serverInterrupt !== true) this.interrupt = false;+ if (t - this.savedAt >= 30_000) this.save(t);+ this.waitSince = claimable > 0 ? (this.waitSince ?? t) : null;+ const oldestWaitS = finite(f.oldestWaitS) ? Math.max(0, Math.round(f.oldestWaitS)) : this.waitSince === null ? 0 : Math.round((t - this.waitSince) / 1000);+ const y = waitForYield ? readYielded(this.o.folder) : null;+ return {+ // Jobs it may not take now (paused, with one still finishing) don't count.+ siteWaiting: Math.max(1, (may ? claimable : 0) + (f.busy ? 1 : 0)),+ oldestWaitS,+ interrupt: this.interrupt,+ waitForYield,+ late: waitForYield && t - this.waitingSince >= TURNS.lateMs,+ startsAt: y?.state === "yielding" && y.at >= this.startAt - 1000 ? y.startsAt : null,+ ended,+ };+ }+}diff --git a/tests/worker-turns-run.test.ts b/tests/worker-turns-run.test.tsnew file mode 100644index 00000000..9d4127a5--- /dev/null+++ b/tests/worker-turns-run.test.ts@@ -0,0 +1,315 @@+/**+ * Studio jobs first, end to end (bin/lib/worker/run.mjs): the worker against the studio's real routes, its own+ * stand-in ComfyUI (tests/helpers/fake-local-comfy.ts, a process it starts behind its guard), a fake port table, fake+ * GPU counters and a fake lock file. Never a real ComfyUI, PowerShell, typeperf or nvidia-smi.+ *+ * - Only local ComfyUI work holds the GPU: the worker writes siteWaiting, keeps the job in line (not a pause), and+ * claims within 5 s of the answer; a minute after the last job it lets go and writes 0.+ * - A game holds the GPU: the busy pause, and no turn is asked for.+ * - The studio doesn't say what the worker can take: local ComfyUI work pauses it, as before.+ * - The counters fail: a lock that names ComfyUI work leads to a turn.+ */+import fs from "node:fs";+import path from "node:path";+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { runWorker } from "../bin/lib/worker/run.mjs";+import { inputRules, readCatalog } from "../scripts/lib/worker-catalog.mjs";+import { FAKE_PNG } from "./helpers/fake-local-comfy";+import { apiAs, loadRoutes, type ComputerRoutes } from "./helpers/computer-tab";+import { tempDir } from "./helpers/temp-dir";++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+vi.setConfig({ testTimeout: 120_000 });++const dir = tempDir("fuobe-worker-turns-run-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";+delete process.env.FUOBE_PASSWORD;+globalThis.__fuobeTestDiskFree = 1e13;++const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { setSetting } = await import("@/server/settings");+const tasks = await import("@/server/computer/tasks");+const pool = await import("@/server/computer/pool");+const { ComputerRunner } = await import("@/lib/computer-runner");++const ROOT = path.resolve(__dirname, "..");+const FAKE = path.join(ROOT, "tests/helpers/fake-local-comfy.ts");+const SITE = "http://127.0.0.1:9";+const RULES = inputRules(readCatalog(ROOT));+const ALLOWED = new Set(["LoadImage", "KSampler", "SaveImage"]);+const realFetch = globalThis.fetch;+const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));++let routes: ComputerRoutes;+beforeAll(async () => {+ routes = await loadRoutes();+ setSetting("comfyWhere", "workers");+});+beforeEach(() => {+ resetRates();+ db().prepare("DELETE FROM relay_workers").run();+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();+});++type W = { id: string; token: string };+const task = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;+const workerRow = (w: W) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as { local_why: string | null; paused_local: number; local_until: number | null };++function addWorker(): W {+ const w = pool.addWorker(`pc-${Math.random().toString(36).slice(2, 8)}`);+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: { small: { delayMs: 0 } } });+ db().prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?").run(JSON.stringify({ lanes: ["small"], workflows: ["wf-test"] }), JSON.stringify({ vramBytes: 24 * 2 ** 30 }), w.id);+ return w;+}++let gens = 0;+function addTask(): string {+ const gid = `turns-gen-${++gens}`;+ const now = Date.now();+ db()+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', '{}', '[]', ?, ?)")+ .run(gid, now, now);+ const input = tasks.stageInput("owner", FAKE_PNG, "image/png", "in.png");+ return tasks.createTask({+ principal: "owner",+ generationId: gid,+ graph: { "1": { class_type: "LoadImage", inputs: { image: input } }, "3": { class_type: "KSampler", inputs: { seed: 1, steps: 4 } }, "9": { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "fuobe/worker-test" } } },+ pool: { pools: ["pool"], rankAt: now, lane: "small", needs: { workflowId: "wf-test", files: [], packs: [], minVramBytes: 0 } },+ }).id;+}++/**+ * fetch for the worker: the studio's routes for SITE, its own ComfyUI for the rest. With `claimable`, the beat's answer+ * carries claimableNow (the jobs waiting for this worker's pool), as a studio that supports turns sends it.+ */+function router(w: W, o: { claimable: boolean }) {+ // The test may switch the count on later (the same object).+ const api = apiAs(routes, null);+ return async (url: string, init: RequestInit = {}) => {+ if (!String(url).startsWith(SITE)) return realFetch(url, init);+ const u = new URL(url);+ const p = u.pathname + u.search;+ if (p === "/api/gpu/computer/inventory") return Response.json({ ok: true, lanes: ["small"], workflows: ["wf-test"], missing: [] });+ expect(new Headers(init.headers).get("authorization")).toBe(`Bearer ${w.token}`);+ const res = await api(p, init);+ if (p !== "/api/gpu/computer/beat" || !o.claimable || !res.ok) return res;+ const body = await res.json();+ const n = (db().prepare("SELECT COUNT(*) AS n FROM relay_tasks WHERE state = 'waiting' AND INSTR(',' || pools || ',', ',pool,') > 0").get() as { n: number }).n;+ return Response.json({ ...body, claimableNow: n });+ };+}++interface Pc {+ home: string;+ workDir: string;+ comfyDir: string;+ turns: string;+ lock: string;+ logs: string[];+}++function pc(): Pc {+ const base = tempDir("fuobe-worker-pc-");+ const p = { home: path.join(base, "home"), workDir: path.join(base, "work"), comfyDir: path.join(base, "comfy"), turns: path.join(base, "turns"), lock: path.join(base, "gpu.lock"), logs: [] };+ for (const d of [p.home, p.workDir, p.comfyDir, p.turns]) fs.mkdirSync(d, { recursive: true });+ return p;+}++/** Its own ComfyUI now: the pid and port the worker wrote down for this start. */+const comfyOf = (p: Pc) => {+ try {+ return JSON.parse(fs.readFileSync(path.join(p.workDir, "comfyui.pid"), "utf8")) as { pid: number; port: number };+ } catch {+ return null;+ }+};++const MB = 2 ** 20;+const LUID = "luid_0x00000000_0x0000D1B5_phys_0";+const WORK_PID = 4242;+const GAME_PID = 5555;++/**+ * The PC's GPU as the fakes show it: local ComfyUI work on 8188 holding `workMb`, a game holding `gameMb`, the desktop+ * 500 MB (the baseline says 600), and the worker's own ComfyUI 1000 MB once it runs. `counters: false`: they can't be read.+ */+function fakeGpu(p: Pc, o: { workMb?: number; gameMb?: number; counters?: boolean }) {+ const own = () => comfyOf(p);+ const procs = () => [+ { pid: WORK_PID, mb: o.workMb ?? 0 },+ { pid: GAME_PID, mb: o.gameMb ?? 0 },+ { pid: 77, mb: 500 },+ ...(own() ? [{ pid: own()!.pid, mb: 1000 }] : []),+ ];+ return {+ readGpu: async () => ({ usedMb: procs().reduce((n, c) => n + c.mb, 0), tempC: 50, apps: [] }),+ readCounters: async () => {+ if (o.counters === false) return null;+ const rows = procs();+ const text = [+ `"(PDH-CSV 4.0)",${rows.map((r) => `"\\\\PC\\GPU Process Memory(pid_${r.pid}_${LUID})\\Dedicated Usage"`).join(",")}`,+ `"11/04/2026 09:00:00.000",${rows.map((r) => `"${r.mb * MB}"`).join(",")}`,+ ].join("\r\n");+ const { parseCounters } = await import("../bin/lib/worker/local-work.mjs");+ return parseCounters(text);+ },+ readListeners: async () => ({+ listeners: [{ port: 8188, pid: WORK_PID }, ...(own() ? [{ port: own()!.port, pid: own()!.pid }] : [])],+ names: { [WORK_PID]: "python", [GAME_PID]: "game", "77": "dwm", ...(own() ? { [own()!.pid]: "node" } : {}) },+ }),+ };+}++const running: { ctrl: AbortController; done: Promise<unknown> }[] = [];+afterEach(async () => {+ for (const r of running.splice(0)) {+ r.ctrl.abort();+ await r.done.catch(() => {});+ }+});++function start(w: W, p: Pc, gpu: ReturnType<typeof fakeGpu>, o: { claimable?: boolean; lockOwners?: string[]; studio?: { claimable: boolean } } = {}) {+ const ctrl = new AbortController();+ const cfg = {+ site: SITE,+ token: w.token,+ comfyDir: p.comfyDir,+ workDir: p.workDir,+ modelDirs: [],+ comfyCommand: [process.execPath, "--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", FAKE, "--port", "{port}", "--cors", "off", "--steps", "4", "--step-ms", "40", "--worker-guard", "1"],+ comfyGuard: true,+ ffmpeg: null,+ yieldFolder: p.turns,+ desktopBaselineMb: 600,+ gpuLockFile: p.lock,+ gpuLockComfyOwners: o.lockOwners ?? [],+ };+ const done = runWorker(cfg, {+ fetch: router(w, o.studio ?? { claimable: o.claimable ?? true }),+ home: p.home,+ signal: ctrl.signal,+ requirements: { folders: [], files: {}, packs: {}, workflows: {} },+ ComputerRunner,+ rules: RULES,+ pins: {},+ allowed: ALLOWED,+ ffmpegVersion: async () => null,+ awake: { set: () => {} },+ sleep: (ms: number) => sleep(Math.min(ms, 50)),+ log: (line: string) => void p.logs.push(line),+ gpuEveryMs: 200,+ turnGraceMs: 1500,+ ...gpu,+ });+ const r = { ctrl, done };+ running.push(r);+ return r;+}++async function until<T>(fn: () => T | Promise<T>, ms = 60_000, every = 50): Promise<Exclude<T, false | null | undefined | 0 | "">> {+ const end = Date.now() + ms;+ for (;;) {+ const v = await fn();+ if (v) return v as Exclude<T, false | null | undefined | 0 | "">;+ if (Date.now() > end) throw new Error(`Timed out after ${ms} ms`);+ await sleep(every);+ }+}++const site = (p: Pc) => {+ try {+ return JSON.parse(fs.readFileSync(path.join(p.turns, "site.json"), "utf8")) as { siteWaiting: number; oldestWaitS: number; interrupt: boolean; at: number };+ } catch {+ return null;+ }+};+const comfyAnswers = async (p: Pc) => {+ const c = comfyOf(p);+ return !!c && (await realFetch(`http://127.0.0.1:${c.port}/__fake/stats`).then((r) => r.ok).catch(() => false));+};++describe("studio jobs first", () => {+ it("only local ComfyUI work holds the GPU: it asks for a turn, keeps the job in line, and claims within 5 s of the answer", async () => {+ const w = addWorker();+ const p = pc();+ const id = addTask();+ start(w, p, fakeGpu(p, { workMb: 9000 }));+ const asked = await until(() => (site(p)?.siteWaiting ?? 0) >= 1 && site(p));+ expect(asked).toMatchObject({ siteWaiting: 1, interrupt: false });+ expect(Math.abs(asked.at - Date.now())).toBeLessThan(10_000);+ // Waiting for its turn is not a pause: the studio keeps the job in its place.+ await until(() => workerRow(w).local_why === "waiting-for-yield");+ expect(workerRow(w).paused_local).toBe(0);+ await until(() => comfyAnswers(p));+ await sleep(1500);+ expect(task(id).state).toBe("waiting");+ expect(task(id).worker_id).toBeNull();+ expect(p.logs.some((l) => /Another program/.test(l))).toBe(false);+ // The answer: it claims at once, with no cool-down.+ const at = Date.now();+ fs.writeFileSync(path.join(p.turns, "yielded.json"), JSON.stringify({ state: "yielded", at }));+ await until(() => task(id).state !== "waiting", 5000);+ expect(Date.now() - at).toBeLessThan(5000);+ expect((await until(() => ["done", "failed"].includes(task(id).state) && task(id), 60_000)).state).toBe("done");+ // No job for the grace time (shortened here): it lets go of its memory and writes 0.+ await until(() => site(p)?.siteWaiting === 0, 20_000);+ expect(p.logs.some((l) => /lets go of its memory/.test(l))).toBe(true);+ expect(workerRow(w).local_why).toBeNull();+ });++ it("a game holds the GPU: the busy pause, and no turn is asked for", async () => {+ const w = addWorker();+ const p = pc();+ const id = addTask();+ start(w, p, fakeGpu(p, { workMb: 9000, gameMb: 6000 }));+ let most = 0;+ await until(() => {+ most = Math.max(most, site(p)?.siteWaiting ?? 0);+ return workerRow(w).local_why?.startsWith("gpu-busy");+ });+ expect(workerRow(w).local_why).toBe("gpu-busy:game");+ expect(workerRow(w).paused_local).toBe(1);+ for (let i = 0; i < 20; i++) {+ most = Math.max(most, site(p)?.siteWaiting ?? 0);+ await sleep(50);+ }+ expect(most).toBe(0);+ expect(site(p)?.siteWaiting).toBe(0);+ expect(task(id).state).toBe("waiting");+ expect(p.logs.some((l) => /make room/.test(l))).toBe(false);+ expect(p.logs.some((l) => /Another program is using the GPU \(game\)/.test(l))).toBe(true);+ });++ it("the studio doesn't say what it can take: local ComfyUI work pauses it, as before, until the studio says", async () => {+ const w = addWorker();+ const p = pc();+ addTask();+ const studio = { claimable: false };+ start(w, p, fakeGpu(p, { workMb: 9000 }), { studio });+ await until(() => workerRow(w).local_why?.startsWith("gpu-busy"));+ expect(workerRow(w).local_why).toBe("gpu-busy:ComfyUI on port 8188");+ expect(site(p)?.siteWaiting ?? 0).toBe(0);+ // The studio starts to send the count: the pause ends with no cool-down, and a turn is asked for.+ studio.claimable = true;+ await until(() => workerRow(w).local_why === "waiting-for-yield");+ expect(site(p)?.siteWaiting).toBe(1);+ expect(p.logs.some((l) => /no longer keeps it paused/.test(l))).toBe(true);+ });++ it("the counters fail: a lock that names ComfyUI work leads to a turn, any other owner to the busy pause", async () => {+ const w = addWorker();+ const p = pc();+ addTask();+ fs.mkdirSync(p.lock);+ fs.writeFileSync(path.join(p.lock, "owner.txt"), "render-queue batch-7 2026-11-04T09:00:00Z pid 4242\n");+ start(w, p, fakeGpu(p, { workMb: 9000, counters: false }), { lockOwners: ["render-queue"] });+ await until(() => workerRow(w).local_why === "waiting-for-yield");+ expect(site(p)?.siteWaiting).toBe(1);+ // Someone else takes the lock: another program.+ fs.writeFileSync(path.join(p.lock, "owner.txt"), "someone-else 2026-11-04T09:00:00Z\n");+ await until(() => workerRow(w).local_why?.startsWith("gpu-busy"));+ await until(() => site(p)?.siteWaiting === 0);+ });+});diff --git a/tests/worker-turns.test.ts b/tests/worker-turns.test.tsnew file mode 100644index 00000000..e44f8875--- /dev/null+++ b/tests/worker-turns.test.ts@@ -0,0 +1,276 @@+/**+ * Studio jobs first (bin/lib/worker/local-work.mjs, turns.mjs): telling local ComfyUI work apart from other programs+ * from a fake port table, fake GPU counters and a fake lock file, the turn files, and the local caps. Nothing here runs+ * PowerShell, typeperf or nvidia-smi, and nothing connects to any ComfyUI.+ */+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { GpuWatch } from "../bin/lib/worker/gpu.mjs";+import { measureBaseline, parseCounters, parseListeners, pickGpu, readLock, splitMemory, unknownHolder, workPids } from "../bin/lib/worker/local-work.mjs";+import { readYielded, SiteTurns, TURNS, writeSite } from "../bin/lib/worker/turns.mjs";+import { siteOf } from "../bin/lib/worker/run.mjs";+import { tempDir } from "./helpers/temp-dir";++const MB = 2 ** 20;+const head = (pid: number, luid = "0x00000000_0x0000D1B5") => `"\\\\PC\\GPU Process Memory(pid_${pid}_luid_${luid}_phys_0)\\Dedicated Usage"`;++/** typeperf's answer for these processes: [pid, MB, luid?]. */+function typeperf(rows: [number, number, string?][]): string {+ return [+ "",+ `"(PDH-CSV 4.0)",${rows.map(([pid, , luid]) => head(pid, luid)).join(",")}`,+ `"11/04/2026 09:00:00.000",${rows.map(([, mb]) => `"${(mb * MB).toFixed(6)}"`).join(",")}`,+ "Exiting, please wait...",+ "The command completed successfully.",+ ].join("\r\n");+}++/** The port table: local ComfyUI work on 8188 (pid 4242), a web server on 8195, the worker's own ComfyUI on 31337 (pid 900). */+const LISTING = {+ listeners: [+ { port: 8188, pid: 4242 },+ { port: 8195, pid: 4300 },+ { port: 8191, pid: 4400 },+ { port: 31337, pid: 900 },+ { port: 445, pid: 4 },+ ],+ names: { "4242": "python", "4300": "nginx", "4400": "python", "900": "python", "4": "System", "5555": "game", "77": "dwm" },+};++describe("the port table and the GPU counters", () => {+ it("reads the port table's JSON, one listener or many", () => {+ const one = parseListeners(JSON.stringify({ listeners: { port: 8188, pid: 4242 }, names: { "4242": "python" } }));+ expect(one).toEqual({ listeners: [{ port: 8188, pid: 4242 }], names: { "4242": "python" } });+ const many = parseListeners(JSON.stringify({ listeners: [{ port: 8188, pid: 4242 }, { port: "x", pid: 1 }, { port: 80, pid: 0 }], names: { "4242": "python", nope: "x" } }));+ expect(many?.listeners).toEqual([{ port: 8188, pid: 4242 }]);+ expect(many?.names).toEqual({ "4242": "python" });+ expect(parseListeners("Get-NetTCPConnection : Access is denied")).toBeNull();+ });++ it("reads typeperf's per-process dedicated memory, in MB, for each adapter", () => {+ const c = parseCounters(typeperf([[4242, 9000], [5555, 0], [77, 300, "0x00000000_0x0000AAAA"]]));+ expect(c).toEqual([+ { pid: 4242, gpu: "0x00000000_0x0000d1b5_0", mb: 9000 },+ { pid: 5555, gpu: "0x00000000_0x0000d1b5_0", mb: 0 },+ { pid: 77, gpu: "0x00000000_0x0000aaaa_0", mb: 300 },+ ]);+ expect(pickGpu(c!, null)).toBe("0x00000000_0x0000d1b5_0");+ expect(pickGpu(c!, "0x00000000_0x0000AAAA_0")).toBe("0x00000000_0x0000aaaa_0");+ expect(parseCounters("Error: No valid counters.")).toBeNull();+ });++ it("local ComfyUI work: python on a port in the range, never its own ComfyUI (by pid or port), never an excluded port", () => {+ const { own, work } = workPids(LISTING, { ports: [8188, 8199], ownPid: 900, ownPort: 31337 });+ expect([...work.keys()]).toEqual([4242, 4400]);+ expect(own.has(900)).toBe(true);+ // Its own ComfyUI started through a launcher: the process on its port is its own, whatever its pid.+ expect(workPids({ ...LISTING, listeners: [...LISTING.listeners, { port: 8190, pid: 901 }] }, { ports: [8188, 8199], ownPid: 900, ownPort: 8190 }).own.has(901)).toBe(true);+ expect([...workPids(LISTING, { ports: [8188, 8199], ownPid: 900, excludePorts: [8191] }).work.keys()]).toEqual([4242]);+ expect([...workPids(LISTING, { ports: [8188, 8199], ownPid: 900, excludePids: [4242] }).work.keys()]).toEqual([4400]);+ // A range that leaves 8191 out.+ expect([...workPids(LISTING, { ports: [8188, 8190], ownPid: 900 }).work.keys()]).toEqual([4242]);+ });++ it("only ComfyUI work holds memory: others stay under the busy line", () => {+ const counters = parseCounters(typeperf([[4242, 9000], [900, 2000], [77, 500]]));+ const s = splitMemory({ usedMb: 11_600, counters, listing: LISTING, own: { pid: 900, port: 31337, running: true, mb: 100 }, ports: [8188, 8199], baselineMb: 600 });+ expect(s.source).toBe("counters");+ expect(s.ownMb).toBe(2000);+ expect(s.workMb).toBe(9000);+ expect(s.othersMb).toBe(0);+ expect(s.work).toEqual({ pids: [4242, 4400], port: 8188 });+ });++ it("a game holds memory: others above the busy line, and the game is named", () => {+ const counters = parseCounters(typeperf([[5555, 6000], [77, 500]]));+ const s = splitMemory({ usedMb: 6500, counters, listing: LISTING, own: { pid: null, port: null, running: false, mb: null }, ports: [8188, 8199], baselineMb: 600 });+ expect(s.workMb).toBe(0);+ expect(s.othersMb).toBe(5900);+ expect(s.who).toBe("game");+ });++ it("its own ComfyUI before the counters list it: torch's number, as before", () => {+ const s = splitMemory({ usedMb: 3000, counters: [], listing: LISTING, own: { pid: 900, port: 31337, running: true, mb: 1400 }, ports: [8188, 8199], baselineMb: 0 });+ expect(s.ownMb).toBe(2000);+ expect(s.othersMb).toBe(1000);+ });++ it("the counters fail: the lock decides; an owner named as ComfyUI work is work, anyone else another program", () => {+ const dir = tempDir("fuobe-worker-lock-");+ const lock = path.join(dir, "gpu.lock");+ fs.mkdirSync(lock);+ expect(readLock(lock)).toBe("");+ fs.writeFileSync(path.join(lock, "owner.txt"), "render-queue night-batch 2026-11-04T09:00:00Z pid 77\n");+ expect(readLock(lock)).toBe("render-queue");+ expect(readLock(path.join(lock, "owner.txt"))).toBe("render-queue");+ expect(readLock(path.join(dir, "none"))).toBeNull();+ const base = { usedMb: 9600, counters: null, listing: LISTING, own: { pid: null, port: null, running: false, mb: null }, ports: [8188, 8199], baselineMb: 600, lockOwners: ["render-queue"] };+ expect(splitMemory({ ...base, lock: "render-queue" })).toMatchObject({ source: "lock", workMb: 9000, othersMb: 0 });+ expect(splitMemory({ ...base, lock: "someone-else" })).toMatchObject({ source: "lock", workMb: 0, othersMb: 9000, who: "another program" });+ expect(splitMemory({ ...base, lock: "" })).toMatchObject({ source: "lock", othersMb: 9000 });+ // No lock and no counters: everything that isn't its own counts as another program (it fails safe).+ expect(splitMemory({ ...base, lock: null, apps: [{ pid: 5, name: "blender.exe", usedMb: null }] })).toMatchObject({ source: "total", workMb: 0, othersMb: 9000, who: "blender.exe" });+ // The port table failed while the counters worked: the lock decides too.+ expect(splitMemory({ ...base, counters: parseCounters(typeperf([[4242, 9000]])), listing: null, lock: "render-queue" }).source).toBe("lock");+ });++ it("looks at the port table again when a process it doesn't know holds memory", () => {+ const counters = parseCounters(typeperf([[4242, 9000]]))!;+ expect(unknownHolder(counters, LISTING, 900, 1024)).toBe(false);+ expect(unknownHolder(parseCounters(typeperf([[6000, 4000]]))!, LISTING, 900, 1024)).toBe(true);+ // A known program that listens nowhere (a game) needs no new look.+ expect(unknownHolder(parseCounters(typeperf([[5555, 4000]]))!, LISTING, 900, 1024)).toBe(false);+ });++ it("measures the desktop's share at setup, without local ComfyUI work", async () => {+ const mb = await measureBaseline({ localComfyPorts: [8188, 8199] }, { readGpu: async () => ({ usedMb: 9700, tempC: 40, apps: [] }), readCounters: async () => parseCounters(typeperf([[4242, 9000], [77, 650]])), readListeners: async () => LISTING });+ expect(mb).toBe(700);+ expect(await measureBaseline({}, { readGpu: async () => ({ usedMb: 1, tempC: 1, apps: [] }), readCounters: async () => null })).toBeNull();+ });+});++describe("the busy pause after two readings", () => {+ it("one busy reading doesn't pause; two in a row do; a free reading between starts the count again", () => {+ const g = new GpuWatch({ autoResume: false, resumeAfterMs: 0, resumeBelowC: 75, busyReadings: 2 });+ g.update({ busy: true, who: "game" }, 50, 0);+ expect(g.paused).toBe(false);+ g.update({ busy: false, who: null }, 50, 5000);+ g.update({ busy: true, who: "game" }, 50, 10_000);+ expect(g.paused).toBe(false);+ g.update({ busy: true, who: "game" }, 50, 15_000);+ expect(g.paused).toBe(true);+ expect(g.who).toBe("game");+ // Without the option: at once, as before.+ const once = new GpuWatch({ autoResume: false, resumeAfterMs: 0, resumeBelowC: 75 });+ once.update({ busy: true, who: "x" }, 50, 0);+ expect(once.paused).toBe(true);+ });+});++describe("turns", () => {+ const T0 = new Date(2026, 10, 4, 9, 0, 0).getTime();+ const setup = (o: Record<string, unknown> = {}) => {+ const dir = tempDir("fuobe-worker-turns-");+ const folder = path.join(dir, "turns");+ fs.mkdirSync(folder);+ return { folder, turns: new SiteTurns({ folder, stateFile: path.join(dir, "home", "turns.json"), ...o }), stateFile: path.join(dir, "home", "turns.json") };+ };+ const answer = (folder: string, body: unknown) => fs.writeFileSync(path.join(folder, "yielded.json"), JSON.stringify(body));+ const facts = { may: true, claimable: 2, busy: false, workHolds: true, workThere: true, serverInterrupt: false };++ it("asks while studio jobs wait and local work holds the GPU; starts on a fresh answer; ends a minute after the last job", () => {+ const { folder, turns } = setup();+ expect(turns.folderOk()).toBe(true);+ let s = turns.step(T0, facts);+ expect(s).toMatchObject({ siteWaiting: 2, waitForYield: true, interrupt: false, ended: null });+ // An answer from before this turn doesn't count once it is old.+ answer(folder, { state: "yielded", at: T0 - 60_000 });+ expect(turns.step(T0 + 1000, facts).waitForYield).toBe(true);+ // "yielding" carries the helper's estimate of the start.+ answer(folder, { state: "yielding", at: T0 + 1500, startsAt: T0 + 90_000 });+ expect(turns.step(T0 + 2000, facts)).toMatchObject({ waitForYield: true, startsAt: T0 + 90_000 });+ answer(folder, { state: "yielded", at: T0 + 2500 });+ s = turns.step(T0 + 3000, facts);+ expect(s.waitForYield).toBe(false);+ // Running a job: siteWaiting counts it too.+ expect(turns.step(T0 + 4000, { ...facts, claimable: 1, busy: true }).siteWaiting).toBe(2);+ // The line empties: still asking for a minute, so the next job starts at once.+ expect(turns.step(T0 + 5000, { ...facts, claimable: 0 })).toMatchObject({ siteWaiting: 1, ended: null });+ expect(turns.step(T0 + 4000 + TURNS.graceMs - 1, { ...facts, claimable: 0 }).siteWaiting).toBe(1);+ expect(turns.step(T0 + 4000 + TURNS.graceMs, { ...facts, claimable: 0 })).toMatchObject({ siteWaiting: 0, ended: "idle" });+ });++ it("the GPU free of local work: no waiting, and siteWaiting still says the studio wants it", () => {+ const { turns } = setup();+ expect(turns.step(T0, { ...facts, workHolds: false, workThere: true })).toMatchObject({ siteWaiting: 2, waitForYield: false });+ // Local work loads models during the turn: from then on, a fresh answer first.+ expect(turns.step(T0 + 1000, { ...facts, workHolds: true }).waitForYield).toBe(true);+ // Its process closes: nothing left to wait for.+ expect(turns.step(T0 + 2000, { ...facts, workHolds: false, workThere: false }).waitForYield).toBe(false);+ });++ it("a pause by hand (me first), a busy GPU or the studio's pause end the turn at once; a job that finishes keeps it until it ends", () => {+ const { turns } = setup();+ turns.step(T0, facts);+ expect(turns.step(T0 + 1000, { ...facts, may: false, busy: true })).toMatchObject({ siteWaiting: 1, ended: null });+ expect(turns.step(T0 + 2000, { ...facts, may: false, busy: false })).toMatchObject({ siteWaiting: 0, ended: "stopped" });+ expect(turns.step(T0 + 3000, { ...facts, may: false })).toMatchObject({ siteWaiting: 0, waitForYield: false });+ });++ it("asks for an interrupt only when the studio does, at most once per gap, and never when the PC says never", () => {+ const a = setup({ interruptGapMin: 30 });+ expect(a.turns.step(T0, { ...facts, serverInterrupt: true }).interrupt).toBe(true);+ // The answer came: no more interrupt.+ answer(a.folder, { state: "yielded", at: T0 + 500 });+ expect(a.turns.step(T0 + 1000, { ...facts, serverInterrupt: true }).interrupt).toBe(false);+ // The next turn, 10 minutes later: inside the gap, so it waits for the job to finish.+ a.turns.step(T0 + 2000, { ...facts, may: false });+ expect(a.turns.step(T0 + 10 * 60_000, { ...facts, serverInterrupt: true })).toMatchObject({ waitForYield: true, interrupt: false });+ a.turns.step(T0 + 10 * 60_000 + 1, { ...facts, may: false });+ // 31 minutes after the first: allowed again. A new worker start remembers the last one.+ const again = new SiteTurns({ folder: a.folder, stateFile: a.stateFile, interruptGapMin: 30 });+ expect(again.step(T0 + 20 * 60_000, { ...facts, serverInterrupt: true }).interrupt).toBe(false);+ again.step(T0 + 20 * 60_000 + 1, { ...facts, may: false });+ expect(again.step(T0 + 31 * 60_000, { ...facts, serverInterrupt: true }).interrupt).toBe(true);+ // The studio didn't ask: none.+ expect(setup().turns.step(T0, facts).interrupt).toBe(false);+ // Never interrupt wins.+ expect(setup({ neverInterrupt: true }).turns.step(T0, { ...facts, serverInterrupt: true }).interrupt).toBe(false);+ });++ it("stops asking once today's hours are used up, and starts again the next day", () => {+ const { turns, folder, stateFile } = setup({ maxHoursPerDay: 1 });+ let t = T0;+ for (; t <= T0 + 3_610_000; t += 10_000) turns.step(t, facts);+ expect(turns.capLeft(t)).toBe(false);+ expect(turns.step(t, facts)).toMatchObject({ siteWaiting: 0, waitForYield: false });+ // A restart doesn't reset the day.+ expect(new SiteTurns({ folder, stateFile, maxHoursPerDay: 1 }).capLeft(t + 1000)).toBe(false);+ const tomorrow = new Date(2026, 10, 5, 0, 0, 1).getTime();+ expect(turns.capLeft(tomorrow)).toBe(true);+ expect(turns.step(tomorrow, facts).siteWaiting).toBe(2);+ // 0 hours: no turns at all.+ expect(setup({ maxHoursPerDay: 0 }).turns.step(T0, facts).siteWaiting).toBe(0);+ });++ it("a PC that slept doesn't use up the day in one tick", () => {+ const { turns } = setup({ maxHoursPerDay: 1 });+ turns.step(T0, facts);+ turns.step(T0 + 5 * 3_600_000, facts);+ expect(turns.capLeft(T0 + 5 * 3_600_000)).toBe(true);+ });++ it("writes site.json whole, and reads only a real answer", () => {+ const { folder } = setup();+ writeSite(folder, { siteWaiting: 3, oldestWaitS: 12, interrupt: false, at: T0 });+ expect(JSON.parse(fs.readFileSync(path.join(folder, "site.json"), "utf8"))).toEqual({ siteWaiting: 3, oldestWaitS: 12, interrupt: false, at: T0 });+ expect(fs.readdirSync(folder)).toEqual(["site.json"]);+ answer(folder, { state: "run-this", at: T0 });+ expect(readYielded(folder)).toBeNull();+ answer(folder, { state: "yielded", at: "now" });+ expect(readYielded(folder)).toBeNull();+ fs.writeFileSync(path.join(folder, "yielded.json"), "x".repeat(5000));+ expect(readYielded(folder)).toBeNull();+ expect(readYielded(path.join(folder, "none"))).toBeNull();+ });++ it("a folder that isn't there: no turns (the worker never makes it)", () => {+ const t = new SiteTurns({ folder: path.join(tempDir("fuobe-worker-turns-"), "missing"), stateFile: path.join(tempDir("fuobe-worker-turns-"), "s.json") });+ expect(t.folderOk()).toBe(false);+ });++ it("reads the beat's count, the oldest wait and the interrupt switch; absent means it doesn't say", () => {+ expect(siteOf({ claimableNow: 2, oldestWaitS: 40, worker: { yieldInterrupt: true } })).toEqual({ claimable: 2, oldestWaitS: 40, interrupt: true });+ expect(siteOf({ worker: { claimableNow: 1 } })).toEqual({ claimable: 1, oldestWaitS: null, interrupt: false });+ expect(siteOf({ waiting: 9, worker: {} })).toEqual({ claimable: null, oldestWaitS: null, interrupt: false });+ expect(siteOf(null).claimable).toBeNull();+ });++ it("the oldest wait: the studio's when it says, else how long this worker has seen jobs waiting", () => {+ const { turns } = setup();+ expect(turns.step(T0, { ...facts, workHolds: false }).oldestWaitS).toBe(0);+ expect(turns.step(T0 + 30_000, { ...facts, workHolds: false }).oldestWaitS).toBe(30);+ expect(turns.step(T0 + 31_000, { ...facts, workHolds: false, oldestWaitS: 95 }).oldestWaitS).toBe(95);+ });+});