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: the pause shortcut asks for 1, 2 or 4 hours, and baseline measures the desktop's share
Adarshfdcf65289a28
diff --git a/bin/lib/worker/index.mjs b/bin/lib/worker/index.mjsindex 7f2410f5..668e1ddd 100644--- a/bin/lib/worker/index.mjs+++ b/bin/lib/worker/index.mjs@@ -1,4 +1,4 @@-// `fuobe worker <setup | run | pause | resume | status | bench | install>` (docs/gpu-workers.md).+// `fuobe worker <setup | run | pause | resume | status | bench | baseline | install>` (docs/gpu-workers.md).import fs from "node:fs";import path from "node:path";import { fileURLToPath } from "node:url";@@ -7,7 +7,7 @@ import { installScript } from "./install.mjs";const here = path.dirname(fileURLToPath(import.meta.url));-export const WORKER_USAGE = "fuobe worker <setup | run | pause [--now] [--for 2h] | resume | status | bench | install [--yes]>";+export const WORKER_USAGE = "fuobe worker <setup | run | pause [--now] [--for 2h] [--choose] | resume | status | bench | baseline | install [--yes]>";const flag = (args, name) => args.includes(`--${name}`);const value = (args, name) => {@@ -15,6 +15,26 @@ const value = (args, name) => {return i >= 0 ? args[i + 1] : undefined;};+/** The pause shortcut's question. Returns "1h", "2h", "4h", "" (until you resume) or null (not paused). */+export async function choosePause(io) {+ if (!io.ask) return "";+ const answer = String((await io.ask("Pause the worker and have the GPU to yourself. For 1, 2 or 4 hours, or 0 until you resume? [1]: ")) ?? "").trim().toLowerCase();+ if (answer === "" || answer === "1") return "1h";+ if (answer === "2" || answer === "4") return `${answer}h`;+ if (answer === "0") return "";+ return null;+}++/** worker.json as saved (no defaults, no token from the environment). */+function savedConfig(home) {+ try {+ const c = JSON.parse(fs.readFileSync(path.join(home, "worker.json"), "utf8"));+ return c && typeof c === "object" ? c : {};+ } catch {+ return {};+ }+}+/** The worker command. Returns the exit code. */export async function worker(args, io) {const [sub = "status", ...rest] = args;@@ -54,14 +74,27 @@ export async function worker(args, io) {return why === "aborted" ? 0 : why === "signed-out" ? 3 : 1;}case "pause": {- const forMs = value(rest, "for") ? parseFor(value(rest, "for")) : null;- if (value(rest, "for") && !forMs) {+ let forText = value(rest, "for");+ let now = flag(rest, "now");+ // The shortcut asks how long. The GPU is yours at once: its job goes back in line, keeping its place.+ if (flag(rest, "choose")) {+ const pick = await choosePause(io);+ if (pick === null) {+ say("Not paused.");+ return 0;+ }+ forText = pick || undefined;+ now = true;+ }+ const forMs = forText ? parseFor(forText) : null;+ if (forText && !forMs) {io.stderr.write("Say how long, like --for 2h or --for 30m.\n");return 2;}- writeControl(home, { paused: true, now: flag(rest, "now"), until: forMs ? Date.now() + forMs : null });- say(flag(rest, "now") ? "Paused now: its job goes back in line, and its ComfyUI stops." : "Paused: it finishes its job, then stops its ComfyUI.");- if (forMs) say(`It resumes by itself at ${new Date(Date.now() + forMs).toLocaleTimeString()}.`);+ const at = (io.now ?? Date.now)();+ writeControl(home, { paused: true, now, until: forMs ? at + forMs : null });+ say(now ? "Paused now: its job goes back in line, and its ComfyUI stops." : "Paused: it finishes its job, then stops its ComfyUI.");+ if (forMs) say(`It resumes by itself at ${new Date(at + forMs).toLocaleTimeString()}.`);return 0;}case "resume":@@ -86,11 +119,24 @@ export async function worker(args, io) {say(body.tasks ? `${body.tasks} bench jobs are waiting for this worker. Keep it running.` : "No bench jobs for its lanes yet. Its times come from the jobs it runs.");return 0;}+ case "baseline": {+ // The desktop's usual share of the GPU, for studio jobs first. Local ComfyUI work may stay open; it isn't counted.+ const { measureBaseline } = await import("./local-work.mjs");+ const mb = await measureBaseline(loadConfig(home, io.env), io.gpu ?? {});+ if (mb === null) {+ io.stderr.write("Couldn't read the GPU counters or the port table on this PC, so nothing changed.\n");+ return 1;+ }+ saveConfig(home, { ...savedConfig(home), desktopBaselineMb: mb });+ say(`The desktop uses about ${mb} MB of the GPU's memory. Saved as desktopBaselineMb in worker.json.`);+ say("Measure again with no game or other GPU program open if that number looks too high.");+ return 0;+ }case "install": {const script = installScript({ node: process.execPath, bin: path.resolve(here, "../../fuobe.mjs"), home });if (!flag(rest, "yes")) {say("This adds a task that starts the worker when you sign in (and again if it stops), and two desktop shortcuts:");- say('"Pause Fuobe worker" (Ctrl+Alt+P) and "Resume Fuobe worker". To do it, run: fuobe worker install --yes');+ say('"Pause Fuobe worker" (Ctrl+Alt+P: it asks for 1, 2 or 4 hours) and "Resume Fuobe worker". To do it, run: fuobe worker install --yes');say("");say(script.text);return 0;diff --git a/bin/lib/worker/install.mjs b/bin/lib/worker/install.mjsindex bb0637c0..50652d05 100644--- a/bin/lib/worker/install.mjs+++ b/bin/lib/worker/install.mjs@@ -1,6 +1,7 @@// `fuobe worker install` (Windows): a Task Scheduler task "Fuobe worker" that starts the worker when you sign in and-// starts it again if it stops, and two desktop shortcuts with hotkeys: "Pause Fuobe worker" (Ctrl+Alt+P) and "Resume-// Fuobe worker". It prints the PowerShell first; it runs it only with --yes.+// starts it again if it stops, and two desktop shortcuts with hotkeys: "Pause Fuobe worker" (Ctrl+Alt+P), which asks+// for 1, 2 or 4 hours (or until you resume) and gives you the GPU at once, and "Resume Fuobe worker". It prints the+// PowerShell first; it runs it only with --yes.const q = (s) => `'${String(s).replaceAll("'", "''")}'`;@@ -13,15 +14,16 @@ $settings = New-ScheduledTaskSettingsSet -RestartCount 999 -RestartInterval (NewRegister-ScheduledTask -TaskName "Fuobe worker" -Action $action -Trigger $trigger -Settings $settings -RunLevel Limited -Force | Out-Null$shell = New-Object -ComObject WScript.Shell$desktop = [Environment]::GetFolderPath("Desktop")-foreach ($s in @(@("Pause Fuobe worker", "worker pause", "CTRL+ALT+P"), @("Resume Fuobe worker", "worker resume", ""))) {+# Name, arguments, hotkey, window (1: a window for the question, 7: minimized).+foreach ($s in @(@("Pause Fuobe worker", "worker pause --choose", "CTRL+ALT+P", 1), @("Resume Fuobe worker", "worker resume", "", 7))) {$lnk = $shell.CreateShortcut((Join-Path $desktop ($s[0] + ".lnk")))$lnk.TargetPath = ${q(node)}$lnk.Arguments = '"${bin.replaceAll("'", "''")}" ' + $s[1]- $lnk.WindowStyle = 7+ $lnk.WindowStyle = $s[3]if ($s[2]) { $lnk.Hotkey = $s[2] }$lnk.Save()}-Write-Host "Done: the worker starts when you sign in. Ctrl+Alt+P pauses it."+Write-Host "Done: the worker starts when you sign in. Ctrl+Alt+P pauses it for 1, 2 or 4 hours."`;return { text };}diff --git a/docs/cli.md b/docs/cli.mdindex 8331f234..eecfc40e 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -290,8 +290,10 @@ node scripts/build-worker.mjs # once, in the checkout: the worker's shared pfuobe worker setup # the studio's address, the token from Settings → Workers, ComfyUI's folder, a portfuobe worker run # until Ctrl+Cfuobe worker pause # finish the job, then stop its ComfyUI; --now: stop now; --for 2h: back by itself+fuobe worker pause --choose # asks for 1, 2 or 4 hours, then stops now (the Ctrl+Alt+P shortcut)fuobe worker resumefuobe worker status+fuobe worker baseline # the desktop's usual share of the GPU, for studio jobs firstfuobe worker install # Windows: shows a sign-in task and pause/resume shortcuts; --yes adds them```diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex 30907bc4..35aebadf 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -153,6 +153,73 @@ The worker obeys any one of these pauses. One pause never ends another pause.- **Hours:** outside its hours, the worker takes nothing new. Near the end of a window, it takes only a job that itsestimate says will finish in time.+On Windows, the pause shortcut (Ctrl+Alt+P, from `fuobe worker install`) runs `fuobe worker pause --choose`. It asks+for 1, 2 or 4 hours, or until you resume, and then pauses at once: the job goes back to the queue at no cost, and its+ComfyUI stops.++### Studio jobs first++A PC can also run ComfyUI work of its own: a ComfyUI that you use by hand, or a queue of your own renders. With+**studio jobs first**, the studio's jobs go before that local ComfyUI work, in the order they were sent. Your local+ComfyUI work runs whenever no studio job waits. Any other program (a game, Blender, a video editor) still pauses the+worker, as above.++The worker never connects to your other ComfyUIs. It reads three things only:++1. **Windows' table of listening ports** (`Get-NetTCPConnection -State Listen`). Reading the table connects to+ nothing. A python process that listens on a port in `localComfyPorts` (8188 to 8199) is local ComfyUI work. The+ worker's own ComfyUI (by its process id and its port) never counts. Neither do the ports and process ids in+ `localComfyExcludePorts` and `localComfyExcludePids`. The worker reads the table every 30 seconds, and sooner when+ a process that it doesn't know holds GPU memory.+2. **Windows' GPU counters** (`\GPU Process Memory(pid_<n>_*)\Dedicated Usage`, read with `typeperf`). These are the+ numbers that Task Manager shows for each process. `nvidia-smi` gives the total only, because its per-process memory+ reads `[N/A]` on Windows.+3. **A GPU lock file** (`gpuLockFile`), only when the counters or the port table can't be read. If the first word of+ the lock names an owner in `gpuLockComfyOwners`, the GPU's memory counts as local ComfyUI work. Any other owner+ counts as another program, and so does no lock at all.++Every 5 seconds, the worker splits the GPU's used memory three ways. **Others** are the total, minus its own ComfyUI,+minus local ComfyUI work, minus the desktop's usual share (`desktopBaselineMb`). Run `fuobe worker baseline` once,+with no game open, to measure that share. Local ComfyUI work may stay open while you measure.++- If others are above `busyVramMb` in two readings in a row, the worker pauses as before ("Your GPU is busy").+- If only local ComfyUI work holds more than `busyVramMb`, the worker asks for a turn and waits. While it waits, its+ jobs keep their place in the line. This is not a pause: there is no cool-down, and the studio does not send its jobs+ back.++**The turn files.** Set `yieldFolder` in `worker.json` to a folder for two small files. The PC's setup makes the+folder. The worker never makes it, so the folder keeps the rights that the setup gave it. If the folder isn't there,+local ComfyUI work counts as another program.++- `site.json` is written by the worker on every beat, and at least every 5 seconds:+ `{ siteWaiting, oldestWaitS, interrupt, at }`. `siteWaiting` is the number of studio jobs that this worker may take+ now (from the beat's `claimableNow`), plus the job that it runs. During a turn it is at least 1. It goes to 0 when no+ studio job has come for a minute, when the worker is paused, or when a local cap is reached. When the worker stops,+ it writes 0.+- `yielded.json` is written by a helper on the PC's side: `{ state, at, startsAt }`. The state `"yielding"` can carry+ the helper's estimate of the start time (`startsAt`, in ms). The worker passes it on in its beat. The state+ `"yielded"` means that local ComfyUI work has made room. A "yielded" counts when it was written after the turn began,+ or in the last 15 seconds. The worker then starts at once.++When no studio job has come for a minute, the worker frees its own ComfyUI's memory (`/free`) and writes+`siteWaiting: 0`, so your local work can go on. If no "yielded" comes within 3 minutes, the worker says so in its log+and in its beat (`waiting-for-yield:no-answer`). It goes on waiting, with the jobs kept in line.++**Limits that only the PC sets.** The studio can never change these:++- `yieldMaxHoursPerDay` (20): the most hours of turns in one day, on the PC's clock. After that, local ComfyUI work+ counts as another program until the next day. A restart doesn't reset the count.+- `interruptGapMin` (30): the studio can ask the helper to stop your current local job instead of letting it finish+ (`interrupt: true`). The worker passes that request on at most once in this many minutes.+- `neverInterrupt` (false): when it is true, `interrupt` is always false.++**You first.** A pause by hand always wins. While the worker is paused, `siteWaiting` is 0. With a plain+`fuobe worker pause`, a job that is still finishing keeps `siteWaiting` at 1 until it ends. The shortcut's choice+(`--choose`) and `--now` give the GPU back at once.++Turns need the studio to send `claimableNow` in the beat's answer. A studio that doesn't send it gets today's+behaviour: local ComfyUI work pauses the worker like any other program. With no `yieldFolder`, nothing changes.+### The queueA job for the workers belongs to the owner. It names the pools that may take it (`pool` by default). It also keeps:@@ -286,6 +353,13 @@ token on every call, so a revoked token stops at once.- `POST /api/gpu/computer/beat`: the browser's beat plus `{ protocol, version, local: { paused, why, until }, gpu: {otherApps, tempC }, inventoryHash, warmLane }`. The answer adds `worker: { paused, pauseNow, drain, autoResume,insideHours, nextChangeAt, lanes, minProtocol, sendInventory }`.+ - While the worker waits for its turn (see "Studio jobs first"), `local` is `{ paused: false, why:+ "waiting-for-yield", until }`, where `until` is the helper's estimate of the start time, or null. After 3 minutes+ with no answer, `why` is `"waiting-for-yield:no-answer"`. The worker may still take jobs, and its jobs keep their+ place.+ - For studio jobs first, the answer may also carry `claimableNow` (the jobs that this worker may take now: its+ lanes, files, VRAM and hours), `oldestWaitS`, and `worker.yieldInterrupt` (true: the studio asks for local+ ComfyUI work to be stopped instead of finished, within the PC's own limits). Each one is optional.- `PUT /api/gpu/computer/inventory`: `{ files: [{ folder, name, size, sha256 }], nodePacks: [{ name, commit }], media }`→ `{ lanes, workflows, missing }`. `media` lists the kinds of input that the worker takes (`image`, `video`,`audio`). With no `media`, the studio counts every kind.@@ -323,7 +397,10 @@ routes.- `pnpm test` (`tests/workers-pool.test.ts`, `tests/workers-pairing.test.ts`, `tests/worker-program.test.ts`,`tests/worker-input-rules.test.ts`, `tests/worker-environment.test.ts`, `tests/worker-guard.test.ts`,- `tests/worker-runner.test.ts`, `tests/worker-recovery.test.ts`, `tests/worker-parts.test.ts`). The input-rule tests+ `tests/worker-runner.test.ts`, `tests/worker-recovery.test.ts`, `tests/worker-parts.test.ts`,+ `tests/worker-turns.test.ts`, `tests/worker-turns-run.test.ts`). The turn tests use a fake port table, fake GPU+ counters and a fake lock file. With only local ComfyUI work on the GPU, the worker writes `siteWaiting` and claims+ within 5 seconds of the answer; with a game, it pauses and asks for no turn. The input-rule testssend graphs that try to write or read files outside the worker's folders, and check that the worker refuses them.They also prepare every catalog workflow the way the studio does, and check that the worker accepts each one. Therecovery tests run the worker against the studio's routes and a stand-in ComfyUI that the worker starts: they killdiff --git a/tests/worker-pause-choice.test.ts b/tests/worker-pause-choice.test.tsnew file mode 100644index 00000000..61e3a36f--- /dev/null+++ b/tests/worker-pause-choice.test.ts@@ -0,0 +1,72 @@+/**+ * The pause shortcut's choice (1, 2 or 4 hours, or until you resume) and `fuobe worker baseline`, with fake GPU readers.+ * Nothing here runs PowerShell, typeperf or nvidia-smi.+ */+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { parseCounters } from "../bin/lib/worker/local-work.mjs";+import { choosePause, worker } from "../bin/lib/worker/index.mjs";+import { installScript } from "../bin/lib/worker/install.mjs";+import { tempDir } from "./helpers/temp-dir";++const MB = 2 ** 20;+const LISTING = { listeners: [{ port: 8188, pid: 4242 }], names: { "4242": "python", "77": "dwm" } };+const typeperf = (rows: [number, number][]) =>+ [+ `"(PDH-CSV 4.0)",${rows.map(([pid]) => `"\\\\PC\\GPU Process Memory(pid_${pid}_luid_0x00000000_0x0000D1B5_phys_0)\\Dedicated Usage"`).join(",")}`,+ `"11/04/2026 09:00:00.000",${rows.map(([, mb]) => `"${mb * MB}"`).join(",")}`,+ ].join("\r\n");++describe("me first", () => {+ const io = (answers: string[], home: string) => {+ const out: string[] = [];+ return {+ out,+ io: {+ env: { FUOBE_WORKER_HOME: home },+ home,+ now: () => 1_000_000,+ stdout: { write: (s: string) => void out.push(s) },+ stderr: { write: (s: string) => void out.push(s) },+ ask: async () => answers.shift() ?? "",+ },+ };+ };++ it("the shortcut asks for 1, 2 or 4 hours (or until you resume) and pauses now", async () => {+ expect(await choosePause({ ask: async () => "" })).toBe("1h");+ expect(await choosePause({ ask: async () => "4" })).toBe("4h");+ expect(await choosePause({ ask: async () => "0" })).toBe("");+ expect(await choosePause({ ask: async () => "nope" })).toBeNull();+ const home = tempDir("fuobe-worker-home-");+ const a = io(["2"], home);+ expect(await worker(["pause", "--choose"], a.io)).toBe(0);+ const control = JSON.parse(fs.readFileSync(path.join(home, "control.json"), "utf8"));+ expect(control).toMatchObject({ paused: true, now: true, until: 1_000_000 + 2 * 3_600_000 });+ const b = io(["x"], home);+ fs.rmSync(path.join(home, "control.json"));+ expect(await worker(["pause", "--choose"], b.io)).toBe(0);+ expect(fs.existsSync(path.join(home, "control.json"))).toBe(false);+ expect(b.out.join("")).toContain("Not paused.");+ // --for 1h, as before.+ expect(await worker(["pause", "--for", "1h"], io([], home).io)).toBe(0);+ expect(JSON.parse(fs.readFileSync(path.join(home, "control.json"), "utf8"))).toMatchObject({ paused: true, now: false, until: 1_000_000 + 3_600_000 });+ });++ it("the Ctrl+Alt+P shortcut opens the question in a window", () => {+ const { text } = installScript({ node: "C:\\node\\node.exe", bin: "C:\\fuobe\\bin\\fuobe.mjs", home: "C:\\home" });+ expect(text).toContain('@("Pause Fuobe worker", "worker pause --choose", "CTRL+ALT+P", 1)');+ expect(text).toContain('@("Resume Fuobe worker", "worker resume", "", 7)');+ });++ it("baseline saves the desktop's share in worker.json and keeps the rest of it", async () => {+ const home = tempDir("fuobe-worker-home-");+ fs.writeFileSync(path.join(home, "worker.json"), JSON.stringify({ site: "https://studio.example", workDir: "D:\\w" }));+ const a = io([], home);+ const gpu = { readGpu: async () => ({ usedMb: 9700, tempC: 40, apps: [] }), readCounters: async () => parseCounters(typeperf([[4242, 9000], [77, 650]])), readListeners: async () => LISTING };+ expect(await worker(["baseline"], { ...a.io, gpu })).toBe(0);+ expect(JSON.parse(fs.readFileSync(path.join(home, "worker.json"), "utf8"))).toEqual({ site: "https://studio.example", workDir: "D:\\w", desktopBaselineMb: 700 });+ expect(await worker(["baseline"], { ...a.io, gpu: { ...gpu, readCounters: async () => null } })).toBe(1);+ });+});