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: restart on new code once the job in hand is done
Adarsh38d4868150af
diff --git a/bin/lib/worker/index.mjs b/bin/lib/worker/index.mjsindex 25420798..5bea10c7 100644--- a/bin/lib/worker/index.mjs+++ b/bin/lib/worker/index.mjs@@ -74,7 +74,9 @@ export async function worker(args, io) {} finally {off?.();}- // Stopped by hand: done. Stopped by the studio: not 0, so the sign-in task starts it again a minute later.+ // Stopped by hand: done. Stopped by the studio: not 0, so the sign-in task starts it again a minute later. Ended for+ // new code on disk (update.mjs): UPDATE_EXIT, so whatever started it may start it again at once.+ if (why === "update") return (await import("./update.mjs")).UPDATE_EXIT;return why === "aborted" ? 0 : why === "signed-out" ? 3 : 1;}case "pause": {diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex 0ee10c4e..1d905ce8 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -38,6 +38,7 @@ import { withPlainResults } from "./results.mjs";import { retrying } from "./retry.mjs";import { builtCatalogVersion, ceilingOf, ceilingWords, graphInside, laneMap, readPcAnswers, workerCatalog } from "./tickets.mjs";import { SiteTurns, writeSite } from "./turns.mjs";+import { CodeWatch } from "./update.mjs";const here = path.dirname(fileURLToPath(import.meta.url));const ROOT = path.resolve(here, "../../..");@@ -179,7 +180,8 @@ export function siteOf(answer) {* "signed-out" (the studio doesn't know its token) or "disconnected". `deps`: { fetch, now, sleep, readGpu, log, home, env,* signal, requirements, ComputerRunner, rules, pins, allowed, ffmpegVersion, reencode, awake, rescanMs, comfy (OwnComfy's own* options), readCounters, readListeners, gpuEveryMs, readGpuGen, idleClaimMs (IDLE_CLAIM_MS), canCleanPictures, and for- * job tickets: composer (src/lib/ticket-compose.ts as built), catalogVersion, catalogDir, allLanes }.+ * job tickets: composer (src/lib/ticket-compose.ts as built), catalogVersion, catalogDir, allLanes, and codeWatch (update.mjs's+ * CodeWatch: new code on disk ends it with "update" once its jobs are done) }.*/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@@ -282,6 +284,9 @@ async function work(saved, deps, owner) {// 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;+ // New code on disk (update.mjs): 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 });+ let updating = false;// 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();@@ -693,9 +698,11 @@ async function work(saved, deps, owner) {});};- const mayWork = () => !pause.paused && answer?.worker && !answer.worker.paused && answer.worker.insideHours && !answer.worker.drain;+ const mayWork = () => !updating && !pause.paused && answer?.worker && !answer.worker.paused && answer.worker.insideHours && !answer.worker.drain;const state = () =>- pause.why === "models-not-ready"+ 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})`@@ -761,6 +768,12 @@ async function work(saved, deps, owner) {try {while (!deps.signal?.aborted) {const t = now();+ // New code installed: once no job is in hand (the GPU's and the CPU slot's), it ends, and starts again on it.+ if (!updating && codeWatch.check(t)) {+ updating = true;+ log("New worker code is installed: restarting after this job.");+ }+ if (updating && !busyJob && !busyCpu) break;// Its own switch, and --for running out.let control = readControl(deps.home);if (control.paused && control.until && t >= control.until) {@@ -949,7 +962,8 @@ async function work(saved, deps, owner) {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.- if (!busyJob && answer && heldFirst) take({ onlyHeld: true });+ // Not while it ends for new code: they stay for its next start.+ if (!busyJob && answer && heldFirst && !updating) take({ onlyHeld: true });// 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.@@ -993,5 +1007,5 @@ async function work(saved, deps, owner) {emptyCpuCache();}}- return deps.signal?.aborted ? "aborted" : (runner.view.stopped ?? "disconnected");+ return deps.signal?.aborted ? "aborted" : (runner.view.stopped ?? (updating ? "update" : "disconnected"));}diff --git a/bin/lib/worker/update.mjs b/bin/lib/worker/update.mjsnew file mode 100644index 00000000..06f924df--- /dev/null+++ b/bin/lib/worker/update.mjs@@ -0,0 +1,117 @@+// New worker code on disk (docs/gpu-workers.md, "Install and update"). The worker notes the code it started with: its+// checkout's commit, the build stamp of its shared parts, and the update-ready file in its home folder (an updater+// writes it once a new build is in place). When any of them changes and the new code is whole (its parts' stamp matches+// its checkout), the worker takes no new job, finishes the one it has, and ends with UPDATE_EXIT so that whatever+// started it starts it again at once, on the new code. A half-done update (a checkout whose build isn't there yet)+// never ends it: it keeps working until the parts match.+import fs from "node:fs";+import path from "node:path";+import { distProblem, STAMP_FILE } from "./stamp.mjs";++/** The exit code of `fuobe worker run` after it ended to start again on new code. */+export const UPDATE_EXIT = 75;++/** The file in the worker's home folder that an updater writes once new code is installed and checked. */+export const UPDATE_READY_FILE = "update-ready.json";++/** How often the worker looks at its code on disk (a few small files). */+export const CODE_CHECK_MS = 15_000;++/** While the code on disk changed but isn't whole yet, how often it checks the stamp again (it reads every source). */+export const WHOLE_CHECK_MS = 60_000;++const readText = (file) => {+ try {+ return fs.readFileSync(file, "utf8");+ } catch {+ return null;+ }+};++/** The git folder of a checkout: `.git`, or the one a `.git` file names (a worktree). */+function gitDir(root) {+ const dotGit = path.join(root, ".git");+ try {+ if (fs.statSync(dotGit).isDirectory()) return dotGit;+ } catch {+ return null;+ }+ const m = /^gitdir:\s*(.+)$/m.exec(readText(dotGit) ?? "");+ return m ? path.resolve(root, m[1].trim()) : null;+}++/** The commit a checkout is at, from its git files (no git program), or null. */+export function headOf(root) {+ const dir = gitDir(root);+ if (!dir) return null;+ const head = (readText(path.join(dir, "HEAD")) ?? "").trim();+ const ref = /^ref:\s*(\S+)$/.exec(head)?.[1];+ if (!ref) return /^[0-9a-f]{40,64}$/.test(head) ? head : null;+ // A branch: its file, in this folder or the shared one, else packed-refs.+ const common = (readText(path.join(dir, "commondir")) ?? "").trim();+ const dirs = [dir, ...(common ? [path.resolve(dir, common)] : [])];+ for (const d of dirs) {+ const sha = (readText(path.join(d, ref)) ?? "").trim();+ if (/^[0-9a-f]{40,64}$/.test(sha)) return sha;+ }+ for (const d of dirs) {+ for (const line of (readText(path.join(d, "packed-refs")) ?? "").split("\n")) {+ const [sha, name] = line.trim().split(" ");+ if (name === ref && /^[0-9a-f]{40,64}$/.test(sha)) return sha;+ }+ }+ return null;+}++/** The stamp of the parts in `dist`, or null. */+function stampOf(dist) {+ try {+ const s = JSON.parse(readText(path.join(dist, STAMP_FILE)) ?? "null")?.stamp;+ return typeof s === "string" ? s : null;+ } catch {+ return null;+ }+}++/** The code on disk now: { head, stamp, ready } (each a string, or null when it isn't there). */+export function codeOnDisk({ root, dist, home }) {+ return { head: headOf(root), stamp: stampOf(dist), ready: home ? readText(path.join(home, UPDATE_READY_FILE)) : null };+}++const same = (a, b) => a.head === b.head && a.stamp === b.stamp && a.ready === b.ready;++/**+ * Watches the code on disk against the code the worker started with. `check(t)` is true once new code is installed+ * and whole, and stays true. `o`: { root, dist, home, everyMs, wholeEveryMs, problem (distProblem) }.+ */+export class CodeWatch {+ constructor(o) {+ this.o = { everyMs: CODE_CHECK_MS, wholeEveryMs: WHOLE_CHECK_MS, problem: distProblem, ...o };+ this.started = codeOnDisk(this.o);+ this.checkedAt = -Infinity;+ this.wholeAt = -Infinity;+ this.found = false;+ }++ check(t) {+ if (this.found) return true;+ if (t - this.checkedAt < this.o.everyMs) return false;+ this.checkedAt = t;+ const now = codeOnDisk(this.o);+ if (same(now, this.started)) return false;+ // Changed: whole only when the parts were built from this checkout. Checked at once after each new change (the+ // update-ready file comes last), else not more often than wholeEveryMs.+ const moved = !this.seen || !same(now, this.seen);+ this.seen = now;+ if (!moved && t - this.wholeAt < this.o.wholeEveryMs) return false;+ this.wholeAt = t;+ let problem;+ try {+ problem = this.o.problem(this.o.root, this.o.dist);+ } catch {+ problem = "stale";+ }+ this.found = problem === null;+ return this.found;+ }+}diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex 590fe216..0c763bc1 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -163,12 +163,22 @@ offer the worker as a download. Use a git checkout at a signed release tag:it. Get the maintainer's public key from a source that you trust, and import it before step 3. Until the repositoryhas a release tag, check out a commit instead, and verify it with `git verify-commit <commit>` in step 3.-To update, stop the worker, do steps 2 to 6 with the new tag, and start the worker again. If the worker was set up by+To update, do steps 2 to 6 with the new tag. A running worker then restarts on the new code by itself (see "New code+while the worker runs"). You can also stop the worker first and start it again after step 6. If the worker was set up byan older version, run `fuobe worker setup` again after the update. That clears the fixed port that older setups saved(8190), so its ComfyUI takes a free port at each start, and it asks for ffmpeg (without ffmpeg the worker takes noclips or sound). Until then, the worker treats a saved 8190 as no fixed port, and says when no ffmpeg is set. Do notinstall the worker from a zip file, from a copy that someone sends you, or from a branch.+**New code while the worker runs.** At its start, the worker notes three things: the commit of its checkout, the build+stamp of its parts (`dist/build-stamp.json`), and the file `update-ready.json` in its home folder. It looks at them+again every 15 seconds. When one of them changes and the parts match the checkout, the worker takes no new job. It+finishes the job that it has, writes "New worker code is installed: restarting after this job." in its log, and ends+with exit code 75. Kept results that are not sent yet stay for its next start. Whatever starts the worker can start it+again at once on exit code 75. An update that is only half done (a new checkout whose build has not run yet) does not+end the worker: it works on until the parts match, and checks the stamp once a minute meanwhile. A program that+installs updates writes `update-ready.json` last, after it has checked the new build.+### The worker's own ComfyUIThe worker always starts and stops its own ComfyUI process. It never uses a ComfyUI that it did not start. Its ComfyUI:@@ -731,7 +741,8 @@ The worker keeps its jobs going by itself:worker checks its folders every minute. Once they are all there, it reads them again, sends the new list, and takesjobs again. A job already running goes on.- **When the studio stops the worker.** If the studio no longer knows the worker's token, `fuobe worker run` ends with- exit code 3; any other stop that you did not ask for ends with exit code 1. The sign-in task that+ exit code 3; after new code is installed, it ends with exit code 75 (see "Install and update"); any other stop that+ you did not ask for ends with exit code 1. The sign-in task that`fuobe worker install` adds then starts the worker again after a minute. Ctrl+C ends with 0. On Ctrl+C, and on astop from the system (SIGTERM), the worker stops its ComfyUI and empties its folders before it ends. Kept resultsstay for its next start.@@ -876,7 +887,7 @@ routes.`tests/pool-line-order.test.ts`, `tests/pool-limits.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`,- `tests/worker-turns.test.ts`, `tests/worker-turns-run.test.ts`, `tests/cpu-slot.test.ts`,+ `tests/worker-turns.test.ts`, `tests/worker-turns-run.test.ts`, `tests/worker-update.test.ts`, `tests/cpu-slot.test.ts`,`tests/worker-cpu-slot.test.ts`, `tests/fuobe-connect-nodes.test.ts`). The CPU slot tests run a CPU task while a GPU job runs, refuse a GLB that namesan outside file on the worker, bring a turntable back with its GLB, check that an account's picture reaches itsComfyUI with no EXIF, and drop a preview over 64 KB. The turn tests use a fake port table, fake GPUdiff --git a/tests/worker-recovery.test.ts b/tests/worker-recovery.test.tsindex 343dd0ca..5547b541 100644--- a/tests/worker-recovery.test.ts+++ b/tests/worker-recovery.test.ts@@ -18,6 +18,7 @@* back, and the output arrives once.* - A model folder that isn't there yet (a drive still locked after a restart): the worker waits for it, says so, and* sends no list of files meanwhile; once the folder is there, the waiting job is taken within one look.+ * - New worker code installed mid-job: it takes no new job, finishes the one it has, and ends to start again on it.*/import { spawnSync } from "node:child_process";import crypto from "node:crypto";@@ -27,6 +28,8 @@ import path from "node:path";import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { runWorker } from "../bin/lib/worker/run.mjs";import { Hold } from "../bin/lib/worker/hold.mjs";+import { STAMP_FILE } from "../bin/lib/worker/stamp.mjs";+import { CodeWatch, UPDATE_READY_FILE } from "../bin/lib/worker/update.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";@@ -169,7 +172,7 @@ function start(w: W,s: Studio,p: Pc,- o: { steps?: number; stepMs?: number; failNext?: string; stallMin?: number; hungMin?: number; ffmpeg?: string | null; rescanMs?: number; modelsCheckMs?: number; modelDirs?: string[]; requirements?: unknown; pins?: Record<string, string>; command?: string[]; readGpu?: () => Promise<unknown>; gpuEveryMs?: number; port?: number; now?: () => number; sleep?: (ms: number) => Promise<void>; env?: Record<string, string | undefined> } = {},+ o: { steps?: number; stepMs?: number; failNext?: string; stallMin?: number; hungMin?: number; ffmpeg?: string | null; rescanMs?: number; modelsCheckMs?: number; modelDirs?: string[]; requirements?: unknown; pins?: Record<string, string>; command?: string[]; readGpu?: () => Promise<unknown>; gpuEveryMs?: number; port?: number; now?: () => number; sleep?: (ms: number) => Promise<void>; env?: Record<string, string | undefined>; codeWatch?: unknown } = {},) {const ctrl = new AbortController();const cfg = {@@ -211,6 +214,7 @@ function start(...(o.rescanMs && { rescanMs: o.rescanMs }),...(o.modelsCheckMs && { modelsCheckMs: o.modelsCheckMs }),...(o.env && { env: o.env }),+ ...(o.codeWatch ? { codeWatch: o.codeWatch } : {}),});const r = { ctrl, done };running.push(r);@@ -556,6 +560,55 @@ http.createServer((q, s) => { s.writeHead(200, { "content-type": "application/js});});+describe("new worker code", () => {+ /** A watch on a checkout of its own (its parts taken as whole) and the PC's home folder, looked at every turn. */+ function watch(p: Pc) {+ const root = tempDir("fuobe-worker-update-root-");+ fs.mkdirSync(path.join(root, ".git"), { recursive: true });+ fs.writeFileSync(path.join(root, ".git/HEAD"), `${"a".repeat(40)}+`);+ const dist = tempDir("fuobe-worker-update-dist-");+ fs.writeFileSync(path.join(dist, STAMP_FILE), JSON.stringify({ stamp: "s1" }));+ return new CodeWatch({ root, dist, home: p.home, everyMs: 0, problem: () => null });+ }+ const installed = (p: Pc) => fs.writeFileSync(path.join(p.home, UPDATE_READY_FILE), JSON.stringify({ commit: "b".repeat(40) }));+ const LINE = "New worker code is installed: restarting after this job.";++ it("installed mid-job: no new job, the job in hand finishes, then the worker ends to start again", async () => {+ const w = addWorker();+ const s = studio();+ const p = pc();+ const { id } = addTask();+ const r = start(w, s, p, { steps: 20, stepMs: 150, codeWatch: watch(p) });+ await until(async () => {+ const c = comfyOf(p);+ return c && ((await fakeStats(c.port).catch(() => null))?.step ?? 0) >= 2;+ });+ const next = addTask();+ installed(p);+ expect(await r.done).toBe("update");+ // Never mid-job: the job ran to the end, once, and the next one stays in line for another start.+ expect(state(id).state).toBe("done");+ expect(prompts(p)).toBe(1);+ expect(state(next.id).state).toBe("waiting");+ expect(p.logs.filter((l) => l === LINE)).toHaveLength(1);+ expect(p.logs.indexOf(LINE)).toBeLessThan(p.logs.indexOf(`Job ${id} done.`));+ expect(JSON.parse(fs.readFileSync(path.join(p.home, "status.json"), "utf8")).state).toBe("Finishing its job, then restarting on new code");+ });++ it("installed while it waits for work: it ends at once, with its ComfyUI stopped", async () => {+ const w = addWorker();+ const s = studio();+ const p = pc();+ const r = start(w, s, p, { codeWatch: watch(p) });+ const comfy = await until(() => p.logs.includes("Ready") && comfyOf(p));+ installed(p);+ expect(await r.done).toBe("update");+ expect(p.logs).toContain(LINE);+ expect(() => process.kill(comfy.pid, 0)).toThrow();+ });+});+describe("results carry no metadata", () => {it("every clip save node goes to its ComfyUI told to write no metadata; the rest of the graph as the studio sent it", async () => {const w = addWorker();diff --git a/tests/worker-update.test.ts b/tests/worker-update.test.tsnew file mode 100644index 00000000..2789421a--- /dev/null+++ b/tests/worker-update.test.ts@@ -0,0 +1,149 @@+/**+ * New worker code on disk (bin/lib/worker/update.mjs): the worker notes its checkout's commit, its parts' stamp and the+ * update-ready file at its start, and ends to start again only once new code is installed and whole. `fuobe worker run`+ * then ends with its own exit code. The worker loop's side (no new job, the job in hand finishes first) is in+ * tests/worker-recovery.test.ts.+ */+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it, vi } from "vitest";+import { worker } from "../bin/lib/worker/index.mjs";+import { buildStamp, STAMP_FILE } from "../bin/lib/worker/stamp.mjs";+import { CodeWatch, codeOnDisk, headOf, UPDATE_EXIT, UPDATE_READY_FILE } from "../bin/lib/worker/update.mjs";+import { tempDir } from "./helpers/temp-dir";++// `fuobe worker run` with a loop that ends for new code at once (the loop itself is tested elsewhere).+vi.mock("../bin/lib/worker/run.mjs", () => ({ runWorker: async () => "update", siteProblem: () => null, withoutOldPort: (c: unknown) => c }));++const A = "a".repeat(40);+const B = "b".repeat(40);++/** A checkout's git folder at `head` (a commit, or "ref: refs/heads/x"). */+function repo(head: string) {+ const root = tempDir("fuobe-worker-update-root-");+ fs.mkdirSync(path.join(root, ".git"), { recursive: true });+ fs.writeFileSync(path.join(root, ".git/HEAD"), `${head}\n`);+ return root;+}++/** Parts stamped with `stamp`. */+function parts(stamp: string) {+ const dist = tempDir("fuobe-worker-update-dist-");+ fs.writeFileSync(path.join(dist, STAMP_FILE), JSON.stringify({ built: "scripts/build-worker.mjs", stamp }));+ return dist;+}++describe("the commit a checkout is at", () => {+ it("reads a detached HEAD, a branch's file, packed-refs and a worktree's git file", () => {+ expect(headOf(repo(A))).toBe(A);+ const branch = repo("ref: refs/heads/main");+ expect(headOf(branch)).toBeNull();+ fs.writeFileSync(path.join(branch, ".git/packed-refs"), `# pack-refs with: peeled\n${B} refs/heads/main\n`);+ expect(headOf(branch)).toBe(B);+ fs.mkdirSync(path.join(branch, ".git/refs/heads"), { recursive: true });+ fs.writeFileSync(path.join(branch, ".git/refs/heads/main"), `${A}\n`);+ expect(headOf(branch)).toBe(A);+ // A worktree: .git is a file naming its own folder, which names the shared one.+ const wt = tempDir("fuobe-worker-update-wt-");+ const own = path.join(branch, ".git/worktrees/wt");+ fs.mkdirSync(own, { recursive: true });+ fs.writeFileSync(path.join(own, "HEAD"), "ref: refs/heads/main\n");+ fs.writeFileSync(path.join(own, "commondir"), "../..\n");+ fs.writeFileSync(path.join(wt, ".git"), `gitdir: ${own}\n`);+ expect(headOf(wt)).toBe(A);+ expect(headOf(tempDir("fuobe-worker-update-none-"))).toBeNull();+ });+});++describe("new code on disk", () => {+ it("nothing changed: no restart", () => {+ const home = tempDir("fuobe-worker-update-home-");+ const w = new CodeWatch({ root: repo(A), dist: parts("s1"), home, everyMs: 0, problem: () => null });+ for (let t = 0; t < 5; t++) expect(w.check(t)).toBe(false);+ });++ it("the update-ready file, a new commit or a new stamp, with whole parts: restart, and it stays so", () => {+ for (const change of ["ready", "head", "stamp"]) {+ const root = repo(A);+ const dist = parts("s1");+ const home = tempDir("fuobe-worker-update-home-");+ // A file left by an earlier update counts as what it started with.+ fs.writeFileSync(path.join(home, UPDATE_READY_FILE), '{"commit":"old"}');+ const w = new CodeWatch({ root, dist, home, everyMs: 0, problem: () => null });+ expect(w.check(1), change).toBe(false);+ if (change === "ready") fs.writeFileSync(path.join(home, UPDATE_READY_FILE), '{"commit":"new"}');+ if (change === "head") fs.writeFileSync(path.join(root, ".git/HEAD"), `${B}\n`);+ if (change === "stamp") fs.writeFileSync(path.join(dist, STAMP_FILE), JSON.stringify({ stamp: "s2" }));+ expect(w.check(2), change).toBe(true);+ expect(w.check(3), change).toBe(true);+ }+ });++ it("a half-done update (parts not built from the checkout): no restart until they are, and the stamp is read at most once a minute", () => {+ const root = repo(A);+ const home = tempDir("fuobe-worker-update-home-");+ let problem: string | null = "stale";+ const problemOf = vi.fn(() => problem);+ const w = new CodeWatch({ root, dist: parts("s1"), home, everyMs: 15_000, wholeEveryMs: 60_000, problem: problemOf });+ fs.writeFileSync(path.join(root, ".git/HEAD"), `${B}\n`);+ // Looked at no more often than every 15 s.+ expect(w.check(0)).toBe(false);+ expect(problemOf).toHaveBeenCalledTimes(1);+ expect(w.check(10_000)).toBe(false);+ expect(w.check(30_000)).toBe(false);+ expect(problemOf).toHaveBeenCalledTimes(1);+ problem = null;+ expect(w.check(45_000)).toBe(false);+ expect(w.check(60_000)).toBe(true);+ expect(problemOf).toHaveBeenCalledTimes(2);+ // Another change on disk (the update-ready file, written last) is checked at once.+ problem = "stale";+ const w3 = new CodeWatch({ root, dist: parts("s1"), home, everyMs: 15_000, wholeEveryMs: 60_000, problem: () => problem });+ fs.writeFileSync(path.join(root, ".git/HEAD"), `${A}\n`);+ expect(w3.check(0)).toBe(false);+ problem = null;+ expect(w3.check(15_000)).toBe(false);+ fs.writeFileSync(path.join(home, UPDATE_READY_FILE), '{"commit":"new"}');+ expect(w3.check(30_000)).toBe(true);+ // A check that throws counts as not whole.+ const w2 = new CodeWatch({ root, dist: parts("s1"), home, everyMs: 0, problem: () => { throw new Error("unreadable"); } });+ fs.writeFileSync(path.join(home, UPDATE_READY_FILE), "{}");+ expect(w2.check(0)).toBe(false);+ });++ it("with the real stamp: a checkout whose parts match is whole", () => {+ const root = repo(A);+ fs.mkdirSync(path.join(root, "src/lib"), { recursive: true });+ fs.mkdirSync(path.join(root, "src/server"), { recursive: true });+ fs.mkdirSync(path.join(root, "workflows/comfyui"), { recursive: true });+ fs.writeFileSync(path.join(root, "src/lib/a.ts"), "export const a = 1;\n");+ const dist = parts(buildStamp(root));+ const home = tempDir("fuobe-worker-update-home-");+ const w = new CodeWatch({ root, dist, home, everyMs: 0, wholeEveryMs: 0 });+ expect(codeOnDisk({ root, dist, home })).toEqual({ head: A, stamp: buildStamp(root), ready: null });+ // A new commit whose build isn't there yet.+ fs.writeFileSync(path.join(root, ".git/HEAD"), `${B}\n`);+ fs.writeFileSync(path.join(root, "src/lib/a.ts"), "export const a = 2;\n");+ expect(w.check(1)).toBe(false);+ // Its build arrives.+ fs.writeFileSync(path.join(dist, STAMP_FILE), JSON.stringify({ stamp: buildStamp(root) }));+ expect(w.check(2)).toBe(true);+ });++ it("`fuobe worker run` ends with its own exit code after ending for new code", async () => {+ const root = tempDir("fuobe-worker-update-checkout-");+ for (const d of ["src/lib", "src/server", "workflows/comfyui"]) fs.mkdirSync(path.join(root, d), { recursive: true });+ const dist = tempDir("fuobe-worker-update-parts-");+ fs.mkdirSync(path.join(dist, "compose/lib"), { recursive: true });+ for (const f of ["computer-runner.mjs", "allowed-nodes.json", "input-rules.json", "file-pins.json", "catalog-version.json", "compose/lib/ticket-compose.mjs"]) fs.writeFileSync(path.join(dist, f), "{}");+ fs.writeFileSync(path.join(dist, STAMP_FILE), JSON.stringify({ stamp: buildStamp(root) }));+ const home = tempDir("fuobe-worker-update-home-");+ fs.writeFileSync(path.join(home, "worker.json"), JSON.stringify({ site: "https://studio.example", token: "t", workDir: tempDir("fuobe-worker-update-work-") }));+ let err = "";+ const io = { env: { FUOBE_WORKER_HOME: home }, home, stdout: { write: () => {} }, stderr: { write: (s: string) => void (err += s) }, distDir: dist, rootDir: root };+ expect(await worker(["run"], io)).toBe(UPDATE_EXIT);+ expect(UPDATE_EXIT).not.toBe(0);+ expect([1, 2, 3, 4]).not.toContain(UPDATE_EXIT);+ expect(err).toBe("");+ });+});