@animastor/installer 0.2.4 → 0.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -103,9 +103,53 @@ function ensureWorkerDependencies(io, { workerDir, nodeBin = null }) {
103
103
  * already on disk and were kept (files_kept).
104
104
  * @returns {{ status, files, files_installed, files_kept, dir_created, updated_from?, reason? }}
105
105
  */
106
- function installWorkerBundle(io, { workerDir, manifest, repoRoot = null, bundleDir = null, hubUrl = null, httpFetchText = null, log = null, update = true, nodeBin = null }) {
106
+ // ── installer 0.2.10: the bundle source is copied WHOLE ─────────────────────
107
+ // 0.2.9 copied only manifest.worker_bundle.files; bundle 2.4.1 added
108
+ // worker-logs.cjs (required by worker.cjs) → «Cannot find module
109
+ // './worker-logs.cjs'» after an update. The source dir (hub bundle or the
110
+ // installer's bundled copy) IS the bundle: every regular file is deployed;
111
+ // the manifest list is only the minimal presence check. Never copied: .env
112
+ // and .env.* (except .env.example), node_modules/, .git/, logs/.
113
+ const BUNDLE_SKIP_DIRS = new Set(['node_modules', '.git', 'logs']);
114
+ /** Files of a bundle that are never removed as «stale» (user data / installer-written). */
115
+ const BUNDLE_PROTECTED = new Set(['.env', 'node-classes.json']);
116
+
117
+ /** io.fs.statSync returns booleans; node fs returns methods — accept both. */
118
+ function statIs(st, what) {
119
+ if (!st) return false;
120
+ const v = st[what];
121
+ return typeof v === 'function' ? v.call(st) === true : v === true;
122
+ }
123
+
124
+ function isBundleFile(relPath) {
125
+ const base = relPath.split('/').pop();
126
+ if (base === '.env' || /^\.env\..+$/.test(base)) return base === '.env.example';
127
+ return true;
128
+ }
129
+
130
+ /** Sorted relative paths of every deployable file of a bundle dir. */
131
+ function listBundleFiles(io, dir) {
132
+ const out = [];
133
+ const walk = (rel) => {
134
+ const abs = rel ? path.join(dir, rel) : dir;
135
+ let names;
136
+ try { names = io.fs.readdirSync(abs); } catch (_) { return; }
137
+ for (const name of names) {
138
+ const r = rel ? `${rel}/${name}` : name;
139
+ const p = path.join(dir, r);
140
+ let st;
141
+ try { st = io.fs.statSync(p); } catch (_) { continue; }
142
+ if (statIs(st, 'isDirectory')) { if (!BUNDLE_SKIP_DIRS.has(name)) walk(r); continue; }
143
+ if (statIs(st, 'isFile') && isBundleFile(r)) out.push(r);
144
+ }
145
+ };
146
+ walk('');
147
+ return out.sort();
148
+ }
149
+
150
+ function installWorkerBundle(io, { workerDir, manifest, repoRoot = null, bundleDir = null, hubUrl = null, httpFetchText = null, log = null, update = true, nodeBin = null, previousBundleFiles = null }) {
107
151
  const wb = manifest.worker_bundle || {};
108
- const files = wb.files || [];
152
+ const manifestFiles = wb.files || [];
109
153
  const dirCreated = !io.fs.existsSync(workerDir);
110
154
  if (dirCreated) io.fs.mkdirSync(workerDir, { recursive: true });
111
155
 
@@ -118,17 +162,22 @@ function installWorkerBundle(io, { workerDir, manifest, repoRoot = null, bundleD
118
162
  const installed = [];
119
163
  const kept = [];
120
164
  const failed = [];
165
+ const removed = [];
121
166
 
122
- for (const f of files) {
167
+ // every file of the source bundle(s), manifest-listed or not; a file only
168
+ // the hub bundle has (repo copy partial) still comes from the hub bundle
169
+ const sources = [fromRepo ? repoBundleDir : null, bundleDir].filter(Boolean);
170
+ const sourceOf = new Map();
171
+ for (const dir of sources) for (const f of listBundleFiles(io, dir)) if (!sourceOf.has(f)) sourceOf.set(f, dir);
172
+ const bundleFiles = [...new Set([...sourceOf.keys(), ...manifestFiles])].sort();
173
+
174
+ for (const f of bundleFiles) {
123
175
  const dest = path.join(workerDir, f);
124
176
  if (io.fs.existsSync(dest) && !outdated) { kept.push(f); continue; }
125
- if (fromRepo && io.fs.existsSync(path.join(repoBundleDir, f))) {
126
- io.fs.copyFileSync(path.join(repoBundleDir, f), dest);
127
- installed.push(f);
128
- continue;
129
- }
130
- if (bundleDir && io.fs.existsSync(path.join(bundleDir, f))) {
131
- io.fs.copyFileSync(path.join(bundleDir, f), dest);
177
+ const src = sourceOf.get(f);
178
+ if (src) {
179
+ io.fs.mkdirSync(path.dirname(dest), { recursive: true });
180
+ io.fs.copyFileSync(path.join(src, f), dest);
132
181
  installed.push(f);
133
182
  continue;
134
183
  }
@@ -136,10 +185,28 @@ function installWorkerBundle(io, { workerDir, manifest, repoRoot = null, bundleD
136
185
  failed.push(f);
137
186
  }
138
187
 
188
+ // minimal presence check: everything the manifest names must be on disk
189
+ const missing = manifestFiles.filter((f) => !io.fs.existsSync(path.join(workerDir, f)));
190
+ for (const f of missing) if (!failed.includes(f)) failed.push(f);
139
191
  if (failed.length > 0) {
140
192
  return { status: 'failed', files: installed, files_installed: installed, files_kept: kept, dir_created: dirCreated, reason: `could not obtain bundle files: ${failed.join(', ')} (no repo checkout, no hub bundle)` };
141
193
  }
142
194
 
195
+ // an UPDATE removes the files of the previous bundle version that the new
196
+ // one no longer ships — only files the installer itself recorded
197
+ // (install-state worker.bundle_files), never .env / node-classes.json
198
+ if (outdated && Array.isArray(previousBundleFiles) && sources.length > 0) {
199
+ const now = new Set(bundleFiles);
200
+ for (const f of previousBundleFiles) {
201
+ if (typeof f !== 'string' || !f || now.has(f) || BUNDLE_PROTECTED.has(f) || f.includes('..') || path.isAbsolute(f)) continue;
202
+ const p = path.join(workerDir, f);
203
+ try {
204
+ if (io.fs.existsSync(p) && statIs(io.fs.statSync(p), 'isFile')) { io.fs.unlinkSync(p); removed.push(f); }
205
+ } catch (_) { /* best effort */ }
206
+ }
207
+ if (removed.length && log) log.info(`worker bundle: removed ${removed.length} file(s) of ${installedVersion} not in ${sourceVersion}: ${removed.join(', ')}`);
208
+ }
209
+
143
210
  const deps = ensureWorkerDependencies(io, { workerDir, nodeBin });
144
211
  if (deps.ran && log) log.info(`worker dependencies installed (${deps.deps.join(', ')})`);
145
212
 
@@ -149,6 +216,9 @@ function installWorkerBundle(io, { workerDir, manifest, repoRoot = null, bundleD
149
216
  }
150
217
  return {
151
218
  status: 'installed', files: installed, files_installed: installed, files_kept: kept, dir_created: dirCreated,
219
+ // install-state worker.bundle_files: what the NEXT update may remove as stale
220
+ bundle_files: sources.length > 0 ? bundleFiles : (Array.isArray(previousBundleFiles) ? previousBundleFiles : bundleFiles),
221
+ files_removed: removed,
152
222
  version: readPkgVersion(io, workerDir),
153
223
  ...(outdated ? { updated_from: installedVersion } : {}),
154
224
  };
@@ -239,7 +309,11 @@ function configureEnv(io, { workerDir, manifest, values = {}, overrides = {}, se
239
309
  if (text && !text.endsWith('\n')) text += '\n';
240
310
  text += additions.join('\n') + '\n';
241
311
  }
242
- io.fs.writeFileSync(envPath, text);
312
+ // Installer 0.2.8: an unchanged .env is NOT rewritten. Its mtime is the
313
+ // "configuration changed after the worker started" marker
314
+ // (workerConfigNewer) — rewriting identical content made every doctor
315
+ // run restart a running (even busy) worker (04.11, 13:55/13:58 UTC).
316
+ if (envCreated || text !== existingText) io.fs.writeFileSync(envPath, text);
243
317
  io.fs.chmodSync(envPath, 0o600);
244
318
 
245
319
  if (log) log.info(`.env configured: ${preserved.length} key(s) preserved, ${additions.length} added, ${changed.length} updated${changed.length ? ` (${changed.join(', ')})` : ''}, ${missingAfter.length} still missing`);
@@ -327,9 +401,50 @@ async function verifyRegistration(io, { hubUrl, token, expectedType = null }) {
327
401
  * DECLARES (the canonical bundle declares none — the old hard-coded
328
402
  * node-fetch probe made every zero-dependency install "unstartable").
329
403
  */
404
+ const LOCAL_REQUIRE_RE = /require\(\s*(["'])(\.{1,2}\/[^"']+)\1\s*\)/g;
405
+
406
+ /**
407
+ * installer 0.2.10: every local `require('./…')` reachable from worker.cjs
408
+ * must exist on disk — otherwise the worker dies at start with «Cannot find
409
+ * module» (bundle 2.4.1 / worker-logs.cjs). Pure over io.fs.
410
+ * @returns {string[]} missing modules as written in the source (e.g. './worker-logs.cjs')
411
+ */
412
+ function missingLocalRequires(io, workerDir, entry = 'worker.cjs') {
413
+ const missing = [];
414
+ const seen = new Set();
415
+ const queue = [path.join(workerDir, entry)];
416
+ const resolve = (from, spec) => {
417
+ const base = path.resolve(path.dirname(from), spec);
418
+ for (const c of [base, `${base}.js`, `${base}.cjs`, `${base}.json`, path.join(base, 'index.js')]) {
419
+ try { if (io.fs.existsSync(c) && statIs(io.fs.statSync(c), 'isFile')) return c; } catch (_) { /* next */ }
420
+ }
421
+ return null;
422
+ };
423
+ while (queue.length) {
424
+ const file = queue.shift();
425
+ if (seen.has(file)) continue;
426
+ seen.add(file);
427
+ let src;
428
+ try { src = io.fs.readFileSync(file, 'utf8'); } catch (_) { continue; }
429
+ if (typeof src !== 'string') src = String(src);
430
+ LOCAL_REQUIRE_RE.lastIndex = 0;
431
+ let m;
432
+ while ((m = LOCAL_REQUIRE_RE.exec(src)) !== null) {
433
+ const hit = resolve(file, m[2]);
434
+ if (!hit) { if (!missing.includes(m[2])) missing.push(m[2]); continue; }
435
+ if (/\.(c?js)$/.test(hit) && path.resolve(hit).startsWith(path.resolve(workerDir))) queue.push(hit);
436
+ }
437
+ }
438
+ return missing;
439
+ }
440
+
330
441
  function checkWorkerCanStart(io, { workerDir, nodeBin = 'node' }) {
331
442
  const workerCjs = path.join(workerDir, 'worker.cjs');
332
443
  if (!io.fs.existsSync(workerCjs)) return { ok: false, reason: 'worker.cjs missing' };
444
+ const missing = missingLocalRequires(io, workerDir);
445
+ if (missing.length > 0) {
446
+ return { ok: false, reason: `worker bundle incomplete: ${missing.join(', ')} missing in ${workerDir} (required by worker.cjs) — re-run the installer to redeploy the bundle`, missing };
447
+ }
333
448
  const syntax = io.exec(nodeBin, ['--check', workerCjs]);
334
449
  if (syntax.code !== 0) return { ok: false, reason: `worker.cjs failed syntax check: ${String(syntax.stderr).slice(-200)}` };
335
450
  const deps = Object.keys(declaredDependencies(io, workerDir));
@@ -414,22 +529,61 @@ function findRunningWorkerPid(io, workerDir, opts = {}) {
414
529
  */
415
530
  function workerEnvIsNewer(io, { workerDir, pid, platformAdapter = null }) {
416
531
  try {
417
- const adapter = platformAdapter || adapterOf({});
418
532
  const envM = io.fs.statSync(path.join(workerDir, '.env')).mtimeMs;
419
- // Most reliable marker: logs/worker.pid written at start (by this
420
- // installer and by start-worker.sh) — its mtime IS the start time.
533
+ const procM = workerProcessStartMs(io, { workerDir, pid, platformAdapter });
534
+ if (procM == null) return false;
535
+ return envM > procM + 1000; // 1s tolerance for same-second writes
536
+ } catch (_) {
537
+ return false;
538
+ }
539
+ }
540
+
541
+ /**
542
+ * Start time of the running worker `pid` (ms) or null when unknown.
543
+ * Most reliable marker: logs/worker.pid written at start (by this installer
544
+ * and by start-worker.sh) — its mtime IS the start time; then the platform
545
+ * adapter (/proc/<pid> on Linux, the pid marker on Windows).
546
+ */
547
+ function workerProcessStartMs(io, { workerDir, pid, platformAdapter = null }) {
548
+ try {
549
+ const adapter = platformAdapter || adapterOf({});
421
550
  let procM = pidFileStartMs(io, workerDir, pid);
422
551
  if (procM == null) procM = adapter.processStartMs(io, pid);
423
552
  if (procM == null && typeof adapter.workerStartMarkerMs === 'function') {
424
553
  procM = adapter.workerStartMarkerMs(io, workerDir);
425
554
  }
426
- if (procM == null) return false;
427
- return envM > procM + 1000; // 1s tolerance for same-second writes
555
+ return procM == null ? null : procM;
428
556
  } catch (_) {
429
- return false;
557
+ return null;
430
558
  }
431
559
  }
432
560
 
561
+ /** Files whose change requires a worker restart: .env and the bundle (installer 0.2.8). */
562
+ const WORKER_CONFIG_FILES = Object.freeze(['.env', 'package.json', 'worker.cjs', 'worker-env.cjs',
563
+ 'job-protocol-v2.cjs', 'worker-cleanup.cjs', 'worker-cleanup-journal.cjs', 'worker-logs.cjs']);
564
+
565
+ /**
566
+ * Configuration files (.env, bundle files) modified AFTER the worker `pid`
567
+ * started — the running process holds the old configuration (env and code
568
+ * are fixed at process start). Persistent across runs: a restart deferred
569
+ * because the worker was busy is still required on the next run. Unknown
570
+ * start time → [] (never restart on a guess).
571
+ * @returns {string[]} changed file names
572
+ */
573
+ function workerConfigNewer(io, { workerDir, pid, platformAdapter = null, files = WORKER_CONFIG_FILES }) {
574
+ const procM = workerProcessStartMs(io, { workerDir, pid, platformAdapter });
575
+ if (procM == null) return [];
576
+ const out = [];
577
+ for (const f of files) {
578
+ try {
579
+ const p = path.join(workerDir, f);
580
+ if (!io.fs.existsSync(p)) continue;
581
+ if (io.fs.statSync(p).mtimeMs > procM + 1000) out.push(f);
582
+ } catch (_) { /* unreadable → not counted */ }
583
+ }
584
+ return out;
585
+ }
586
+
433
587
  /** Default worker log: <install base>/logs/worker.log (same file start-worker.sh uses). */
434
588
  function workerLogPath(workerDir) {
435
589
  return path.join(path.dirname(workerDir), 'logs', 'worker.log');
@@ -507,6 +661,18 @@ function startWorker(io, { workerDir, nodeBin = null, logFile = null, graceMs =
507
661
  if (existing && !forceRestart && !workerEnvIsNewer(io, { workerDir, pid: existing, platformAdapter: adapter })) {
508
662
  return { started: true, already_running: true, pid: existing, alive: true, reason: null, logFile: log, logOffset: null };
509
663
  }
664
+ if (existing && !forceRestart) {
665
+ // Installer 0.2.8: a stale-config restart never kills a task in
666
+ // progress (`animastor start` path; doctor/install decide in
667
+ // ensureWorker, which waits for the task).
668
+ const act = readWorkerActivity(io, { workerDir, pid: existing, logFile: log });
669
+ if (act.known && act.current_job_id) {
670
+ return {
671
+ started: true, already_running: true, pid: existing, alive: true, reason: null, logFile: log, logOffset: null,
672
+ restart_pending: ['.env'], busy_job: act.current_job_id,
673
+ };
674
+ }
675
+ }
510
676
  if (existing) {
511
677
  // .env changed after this worker started — it is running on the OLD
512
678
  // configuration (its env is fixed at process start). Restart it so
@@ -577,6 +743,98 @@ function scanWorkerLog(text) {
577
743
  };
578
744
  }
579
745
 
746
+ // ── Worker activity (installer 0.2.8) ─────────────────────────────────────────
747
+ // The hub's heartbeat record (current_job_id) lives in the hub's Redis and is
748
+ // not readable from the node; the worker's OWN log carries the same facts:
749
+ // "[ts] [info] Task <job_id> (type=…" — a task was taken
750
+ // "[ts] [info] Done <job_id>" — result delivered
751
+ // "[ts] [error] Failed <job_id>" — task failed (error sent)
752
+ // "[ts] [error] Rejecting incompatible task…" — the taken task was refused
753
+ // Only the output of the CURRENT process counts (after its last
754
+ // "Worker <type> started"). "Hub heartbeat accepted" is logged on the first
755
+ // accepted beacon and again after every recovery; every failed beacon logs
756
+ // "Beacon failed" — so "heartbeat fresh" = the latest beacon marker of this
757
+ // process is an accepted one.
758
+ const TASK_START_RE = /\] Task (\S+) \(type=/;
759
+ const TASK_END_RE = /\] (?:Done|Failed) (\S+)\s*$/;
760
+ const TASK_REJECT_RE = /\] Rejecting incompatible task/;
761
+ const WORKER_LOG_TAIL_BYTES = 4 * 1024 * 1024;
762
+
763
+ /**
764
+ * Pure: classify the worker log (text of one or more runs).
765
+ * @returns {{ started: boolean, current_job_id: string|null, last_job_id: string|null,
766
+ * comfy_ready: boolean, heartbeat: boolean, healthy: boolean, last_beacon_error: string|null }}
767
+ */
768
+ function parseWorkerActivity(text) {
769
+ const all = String(text || '').split('\n');
770
+ let start = -1;
771
+ all.forEach((l, i) => { if (/\] Worker \S+ started/.test(l)) start = i; });
772
+ const lines = start >= 0 ? all.slice(start) : all;
773
+ let current = null;
774
+ let last = null;
775
+ for (const l of lines) {
776
+ let m = TASK_START_RE.exec(l);
777
+ if (m) { current = m[1]; last = m[1]; continue; }
778
+ m = TASK_END_RE.exec(l);
779
+ if (m) { if (current === m[1]) current = null; continue; }
780
+ if (TASK_REJECT_RE.test(l)) current = null;
781
+ }
782
+ const scan = scanWorkerLog(lines.join('\n'));
783
+ return {
784
+ started: start >= 0,
785
+ current_job_id: current,
786
+ last_job_id: last,
787
+ comfy_ready: scan.comfy_ready,
788
+ heartbeat: scan.heartbeat,
789
+ healthy: start >= 0 && scan.comfy_ready && scan.heartbeat && !scan.crashed && !scan.auth_failed,
790
+ last_beacon_error: scan.last_beacon_error,
791
+ };
792
+ }
793
+
794
+ /**
795
+ * Activity of the running worker `pid` from its log (tail of at most
796
+ * WORKER_LOG_TAIL_BYTES). known=false when there is no log, or the log was
797
+ * last written BEFORE this process started (it is some other process's log —
798
+ * busy/idle cannot be told).
799
+ * @returns {{ known: boolean, reason: string|null, current_job_id, last_job_id, comfy_ready, heartbeat, healthy, last_beacon_error, log_file }}
800
+ */
801
+ function readWorkerActivity(io, { workerDir, pid = null, logFile = null, tailBytes = WORKER_LOG_TAIL_BYTES }) {
802
+ const log = logFile || workerLogPath(workerDir);
803
+ const unknown = (reason) => ({
804
+ known: false, reason, current_job_id: null, last_job_id: null, comfy_ready: false, heartbeat: false,
805
+ healthy: false, last_beacon_error: null, log_file: log,
806
+ });
807
+ let text;
808
+ try {
809
+ if (!io.fs.existsSync(log)) return unknown(`no worker log at ${log}`);
810
+ text = String(io.fs.readFileSync(log, 'utf8'));
811
+ } catch (err) {
812
+ return unknown(`worker log ${log} unreadable: ${err.message}`);
813
+ }
814
+ if (pid) {
815
+ // Only the pid file is a precise start marker here (/proc/<pid> mtime
816
+ // on Linux is the procfs inode time, not the start time).
817
+ const procM = pidFileStartMs(io, workerDir, pid);
818
+ let logM = null;
819
+ try { logM = io.fs.statSync(log).mtimeMs; } catch (_) { logM = null; }
820
+ if (procM != null && typeof logM === 'number' && logM + 1000 < procM) {
821
+ return unknown(`worker log ${log} was not written by the running worker (pid ${pid})`);
822
+ }
823
+ }
824
+ if (text.length > tailBytes) text = text.slice(text.length - tailBytes);
825
+ const a = parseWorkerActivity(text);
826
+ return { known: true, reason: null, ...a, log_file: log };
827
+ }
828
+
829
+ /** "none" | "<job_id>" | "unknown" for the `current job:` line of doctor/status. */
830
+ function currentJobLabel(io, { workerDir, pid = undefined, platformAdapter = null, logFile = null }) {
831
+ const p = pid === undefined ? findRunningWorkerPid(io, workerDir, { platformAdapter }) : pid;
832
+ if (!p) return 'none';
833
+ const a = readWorkerActivity(io, { workerDir, pid: p, logFile });
834
+ if (!a.known) return 'unknown';
835
+ return a.current_job_id || 'none';
836
+ }
837
+
580
838
  function readLogFrom(io, logFile, offset) {
581
839
  try {
582
840
  const text = String(io.fs.readFileSync(logFile, 'utf8'));
@@ -735,8 +993,203 @@ async function restartManagedWorker(io, { workerDir, log = null, stopTimeoutMs =
735
993
  return { restarted: true, previously_running: previouslyRunning, pid: start.pid, alive: start.alive, reason: start.reason };
736
994
  }
737
995
 
996
+ // ── ensureWorker (installer 0.2.8) ──────────────────────────────────────────
997
+ // install/doctor/boot no longer restart a running worker by default
998
+ // (04.11: doctor restarted the audio/image workers at 13:55:15 and 13:58:52,
999
+ // between tasks only by chance — a result in flight would have been lost).
1000
+ //
1001
+ // not running → start
1002
+ // running, configuration unchanged → left as is
1003
+ // running, .env/bundle changed:
1004
+ // boot (doctor --yes, no TTY) → left as is, restart pending (warn)
1005
+ // --force → restart now
1006
+ // idle → restart
1007
+ // busy (a task in progress) → wait up to waitJobMs for the task
1008
+ // to finish, then restart; still
1009
+ // busy → DEFERRED (FAILED, exit ≠ 0)
1010
+ // busy state unknown (no log of this
1011
+ // process) → DEFERRED (FAILED; --force restarts)
1012
+ const DEFAULT_WAIT_JOB_MS = 600000;
1013
+
1014
+ /**
1015
+ * Pure decision for a running worker.
1016
+ * @returns {{ action: 'start'|'leave'|'restart'|'wait'|'defer', reasons: string[] }}
1017
+ */
1018
+ function decideWorkerAction({ pid = null, reasons = [], activity = null, force = false, boot = false }) {
1019
+ if (!pid) return { action: 'start', reasons: [] };
1020
+ if (reasons.length === 0) return { action: 'leave', reasons: [] };
1021
+ if (force) return { action: 'restart', reasons };
1022
+ if (boot) return { action: 'leave', reasons };
1023
+ if (!activity || !activity.known) return { action: 'defer', reasons };
1024
+ if (activity.current_job_id) return { action: 'wait', reasons };
1025
+ return { action: 'restart', reasons };
1026
+ }
1027
+
1028
+ /**
1029
+ * Bring the worker of this installation up without ever killing a task in
1030
+ * progress (see the table above). Returns the startWorker() shape plus
1031
+ * { action, restart_reasons, current_job, busy_job, deferred, restart_pending }.
1032
+ * @param {object} o
1033
+ * @param {string[]} [o.configChanged] what THIS run changed (".env", "worker bundle 2.2.2 → 2.2.3")
1034
+ */
1035
+ async function ensureWorker(io, {
1036
+ workerDir, nodeBin = null, graceMs = 3000, platformAdapter = null, logFile = null,
1037
+ configChanged = [], force = false, boot = false, waitJobMs = DEFAULT_WAIT_JOB_MS,
1038
+ pollMs = 5000, progressMs = 30000, sleep = null, log = null, startFn = startWorker, tool = 'animastor',
1039
+ }) {
1040
+ const adapter = platformAdapter || adapterOf({});
1041
+ const lf = logFile || workerLogPath(workerDir);
1042
+ const now = () => (io.now ? io.now() : Date.now());
1043
+ const wait = sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
1044
+ const info = (m) => { if (log) log.info(m); };
1045
+ const warn = (m) => { if (log) log.warn(m); };
1046
+ const start = (forceRestart) => startFn(io, { workerDir, nodeBin, graceMs, platformAdapter: adapter, logFile: lf, forceRestart });
1047
+
1048
+ let pid = findRunningWorkerPid(io, workerDir, { platformAdapter: adapter });
1049
+ if (!pid) {
1050
+ const res = start(false);
1051
+ return { ...res, action: 'started', restart_reasons: [], current_job: 'none' };
1052
+ }
1053
+ // What this run changed explains itself; otherwise the persistent marker
1054
+ // (files newer than the process — e.g. a restart deferred by an earlier run).
1055
+ const reasons = (configChanged || []).length > 0
1056
+ ? Array.from(new Set(configChanged))
1057
+ : workerConfigNewer(io, { workerDir, pid, platformAdapter: adapter }).map((f) => `${f} changed after the worker started`);
1058
+ let activity = readWorkerActivity(io, { workerDir, pid, logFile: lf });
1059
+ const decision = decideWorkerAction({ pid, reasons, activity, force, boot });
1060
+ const jobOf = (a) => (a.known ? (a.current_job_id || 'none') : 'unknown');
1061
+ const left = (extra = {}) => ({
1062
+ started: true, already_running: true, pid, alive: true, reason: null, logFile: lf, logOffset: null,
1063
+ action: 'left', restart_reasons: reasons, current_job: jobOf(activity), ...extra,
1064
+ });
1065
+ const deferred = (why) => ({
1066
+ started: false, already_running: true, pid, alive: true, deferred: true, reason: why, logFile: lf, logOffset: null,
1067
+ action: 'deferred', restart_reasons: reasons, current_job: jobOf(activity), busy_job: activity.current_job_id || null,
1068
+ });
1069
+
1070
+ if (decision.action === 'leave' && reasons.length === 0) {
1071
+ const health = activity.known && !activity.healthy
1072
+ ? ` — ${activity.comfy_ready ? (activity.last_beacon_error ? `last beacon failed: ${activity.last_beacon_error}` : 'no heartbeat accepted yet') : 'it has not reached ComfyUI yet'}`
1073
+ : '';
1074
+ info(`worker already running (pid ${pid}), left as is${health}`);
1075
+ return left();
1076
+ }
1077
+ if (decision.action === 'leave') {
1078
+ warn(`worker already running (pid ${pid}), left as is — restart pending (${reasons.join('; ')}); the boot path never restarts a running worker: run \`${tool} doctor\``);
1079
+ return left({ restart_pending: reasons });
1080
+ }
1081
+ if (decision.action === 'defer') {
1082
+ const why = `cannot tell whether the worker (pid ${pid}) is busy (${activity.reason}) — restart for ${reasons.join('; ')} deferred; to restart anyway: ${tool} doctor --force`;
1083
+ warn(why);
1084
+ return deferred(why);
1085
+ }
1086
+ if (decision.action === 'wait') {
1087
+ const deadline = now() + Math.max(0, Number(waitJobMs) || 0);
1088
+ let nextProgress = now();
1089
+ while (activity.known && activity.current_job_id && now() < deadline) {
1090
+ if (now() >= nextProgress) {
1091
+ info(`worker is busy with ${activity.current_job_id} (pid ${pid}) — waiting up to ${Math.round((deadline - now()) / 1000)} s for the task to finish before the restart (${reasons.join('; ')})`);
1092
+ nextProgress = now() + progressMs;
1093
+ }
1094
+ await wait(Math.min(pollMs, Math.max(1, deadline - now())));
1095
+ const still = findRunningWorkerPid(io, workerDir, { platformAdapter: adapter });
1096
+ if (still !== pid) { pid = still; break; }
1097
+ activity = readWorkerActivity(io, { workerDir, pid, logFile: lf });
1098
+ }
1099
+ if (!pid) {
1100
+ info('the worker exited while waiting — starting it');
1101
+ const res = start(false);
1102
+ return { ...res, action: 'started', restart_reasons: reasons, current_job: 'none' };
1103
+ }
1104
+ if (!activity.known) {
1105
+ const why = `cannot tell whether the worker (pid ${pid}) is busy (${activity.reason}) — restart for ${reasons.join('; ')} deferred; to restart anyway: ${tool} doctor --force`;
1106
+ warn(why);
1107
+ return deferred(why);
1108
+ }
1109
+ if (activity.current_job_id) {
1110
+ const why = `worker is busy with ${activity.current_job_id} (pid ${pid}) — restart deferred (waited ${Math.round((Number(waitJobMs) || 0) / 1000)} s; needed for: ${reasons.join('; ')}); re-run \`${tool} doctor\` when the task finishes, or \`${tool} doctor --force\` to restart now (the task's result is lost)`;
1111
+ warn(why);
1112
+ return deferred(why);
1113
+ }
1114
+ info(`the worker (pid ${pid}) finished ${activity.last_job_id || 'its task'}`);
1115
+ }
1116
+ // restart: idle (or --force)
1117
+ if (force && activity.current_job_id) warn(`--force: restarting the worker (pid ${pid}) while it is busy with ${activity.current_job_id} — the task's result is lost`);
1118
+ info(`restarting the worker (pid ${pid}): ${reasons.join('; ')}`);
1119
+ const res = start(true);
1120
+ return { ...res, action: 'restarted', restarted_from: pid, restart_reasons: reasons, current_job: 'none' };
1121
+ }
1122
+
1123
+ // ── node-classes.json (installer 0.2.7, worker bundle >= 2.2.2) ─────────────
1124
+ // GPU E2E 2026-11-02: a worker took tasks from a ComfyUI without its
1125
+ // profile's nodes. Bundle 2.2.2 asks for tasks only after ComfyUI's
1126
+ // /object_info lists every class of this file; without the file it keeps the
1127
+ // old behaviour (ComfyUI API only) and logs one warning. The installer writes
1128
+ // it from the manifests' `provides_classes` (required dependencies only) on a
1129
+ // fresh install, on a bundle update and on every doctor/boot run — so a node
1130
+ // installed by an older installer gets it on its next doctor/boot.
1131
+ //
1132
+ // { "generated_by": "animastor-installer <v>",
1133
+ // "profiles": { "audio/qwen-tts": ["Qwen3TTSLoader", …] } }
1134
+ const NODE_CLASSES_FILE = 'node-classes.json';
1135
+
1136
+ /** {profileId: [classes]} of the given manifests (required deps only, sorted, unique). */
1137
+ function nodeClassesOfManifests(manifests) {
1138
+ const profiles = {};
1139
+ for (const m of manifests || []) {
1140
+ const id = m && m.profile && m.profile.id;
1141
+ if (!id) continue;
1142
+ const set = new Set(profiles[id] || []);
1143
+ for (const dep of m.dependencies || []) {
1144
+ if (dep && dep.requirement && dep.requirement !== 'required') continue;
1145
+ for (const cls of (dep && dep.provides_classes) || []) {
1146
+ if (typeof cls === 'string' && cls.trim()) set.add(cls.trim());
1147
+ }
1148
+ }
1149
+ profiles[id] = Array.from(set).sort();
1150
+ }
1151
+ return profiles;
1152
+ }
1153
+
1154
+ /**
1155
+ * Write <workerDir>/node-classes.json for the profiles of this run. Only when
1156
+ * a worker bundle is installed there (worker.cjs present). Atomic (temp +
1157
+ * rename); an identical file is left untouched.
1158
+ * @returns {{ status: 'written'|'current'|'absent'|'skipped'|'failed', path?: string, profiles?: object, reason?: string }}
1159
+ */
1160
+ function writeNodeClasses(io, { workerDir, manifests, log = null, version = null }) {
1161
+ if (!workerDir || !io.fs.existsSync(path.join(workerDir, 'worker.cjs'))) return { status: 'absent' };
1162
+ const profiles = nodeClassesOfManifests(manifests);
1163
+ if (Object.keys(profiles).length === 0) return { status: 'skipped', reason: 'no profile manifests' };
1164
+ const file = path.join(workerDir, NODE_CLASSES_FILE);
1165
+ let v = version;
1166
+ if (!v) { try { v = require('../../../package.json').version || null; } catch (_) { v = null; } }
1167
+ const doc = { generated_by: `animastor-installer${v ? ` ${v}` : ''}`, profiles };
1168
+ const text = JSON.stringify(doc, null, 2) + '\n';
1169
+ try {
1170
+ if (io.fs.existsSync(file)) {
1171
+ let current = null;
1172
+ try { current = JSON.parse(String(io.fs.readFileSync(file, 'utf8'))); } catch (_) { current = null; }
1173
+ if (current && JSON.stringify(current.profiles || null) === JSON.stringify(profiles)) {
1174
+ return { status: 'current', path: file, profiles };
1175
+ }
1176
+ }
1177
+ const tmp = `${file}.tmp-${process.pid}`;
1178
+ io.fs.writeFileSync(tmp, text);
1179
+ io.fs.renameSync(tmp, file);
1180
+ const n = Object.values(profiles).reduce((a, l) => a + l.length, 0);
1181
+ if (log) log.info(`${NODE_CLASSES_FILE} written: ${Object.keys(profiles).join(', ')} (${n} node class(es)) — the worker takes tasks only when ComfyUI lists them`);
1182
+ return { status: 'written', path: file, profiles };
1183
+ } catch (err) {
1184
+ if (log) log.warn(`${NODE_CLASSES_FILE} could not be written: ${err.message} — the worker falls back to the ComfyUI-API-only readiness`);
1185
+ return { status: 'failed', path: file, reason: err.message };
1186
+ }
1187
+ }
1188
+
738
1189
  module.exports = {
739
1190
  installWorkerBundle,
1191
+ listBundleFiles,
1192
+ missingLocalRequires,
740
1193
  ensureWorkerDependencies,
741
1194
  declaredDependencies,
742
1195
  readPkgVersion,
@@ -754,9 +1207,21 @@ module.exports = {
754
1207
  restartManagedWorker,
755
1208
  findRunningWorkerPid,
756
1209
  workerEnvIsNewer,
1210
+ workerProcessStartMs,
1211
+ workerConfigNewer,
1212
+ WORKER_CONFIG_FILES,
1213
+ parseWorkerActivity,
1214
+ readWorkerActivity,
1215
+ currentJobLabel,
1216
+ decideWorkerAction,
1217
+ ensureWorker,
1218
+ DEFAULT_WAIT_JOB_MS,
757
1219
  configureEnv,
758
1220
  apiBaseFromHubUrl,
759
1221
  verifyRegistration,
760
1222
  checkWorkerCanStart,
761
1223
  renderEnvLines,
1224
+ NODE_CLASSES_FILE,
1225
+ nodeClassesOfManifests,
1226
+ writeNodeClasses,
762
1227
  };
@@ -183,7 +183,11 @@ async function collectStatus(io, targets, opts = {}) {
183
183
  } catch (_) { /* queue is optional */ }
184
184
  }
185
185
  return {
186
- worker: { running: !!workerPid, pid: workerPid || null },
186
+ // current job (installer 0.2.8): the running worker's task, from its own log.
187
+ worker: {
188
+ running: !!workerPid, pid: workerPid || null,
189
+ current_job: workerPid && targets.workerDir ? workerMod.currentJobLabel(io, { workerDir: targets.workerDir, pid: workerPid }) : 'none',
190
+ },
187
191
  comfyui: {
188
192
  running: comfyPids.length > 0, root_present: comfyRootPresent, port, pids: comfyPids, external, url: baseUrl,
189
193
  started_by: startedBy, foreign_pid: foreign ? foreign.pid : null,
@@ -222,6 +226,7 @@ function renderStatus(snapshot) {
222
226
  } else {
223
227
  lines.push('Queue: — (API unreachable)');
224
228
  }
229
+ lines.push(`current job: ${snapshot.worker.current_job || 'none'}`);
225
230
  if (snapshot.hub) {
226
231
  lines.push(`Hub: ${snapshot.hub.heartbeat ? `${ok} ONLINE (heartbeat accepted)` : `${bad} no heartbeat${snapshot.hub.last_error ? ` — ${snapshot.hub.last_error}` : (snapshot.hub.comfy_ready ? '' : ' — worker has not reached ComfyUI')}`}`);
227
232
  }
@@ -67,6 +67,13 @@ function summarizeRuntime(entries) {
67
67
  .join(', ') || null;
68
68
  }
69
69
 
70
+ /** Headline of a missing-node-classes cause (node-deps diagnoseMissingClasses). */
71
+ const CAUSE_TITLE = {
72
+ 'deps-missing': 'Python packages missing',
73
+ 'import-failed': 'IMPORT FAILED in the ComfyUI log',
74
+ 'restart-needed': 'ComfyUI restart needed',
75
+ };
76
+
70
77
  /**
71
78
  * @param {object} args
72
79
  * @param {object} args.report - resolver report
@@ -88,9 +95,9 @@ function buildVerificationReport({ report, live = {} }) {
88
95
  let fails = 0;
89
96
  let warns = 0;
90
97
 
91
- const push = (verdict, label, detail) => {
98
+ const push = (verdict, label, detail, extra = null) => {
92
99
  lines.push(line(verdict, label, detail));
93
- checks.push({ verdict, label, detail: detail || null });
100
+ checks.push({ verdict, label, detail: detail || null, ...(extra || {}) });
94
101
  if (verdict === false) fails += 1;
95
102
  else if (verdict === null) warns += 1;
96
103
  };
@@ -134,9 +141,16 @@ function buildVerificationReport({ report, live = {} }) {
134
141
  const nodeEntriesAll = byKind('custom_node');
135
142
  const presentButUnregistered = nodeEntriesAll.length > 0
136
143
  && nodeEntriesAll.every((e) => e.status === 'installed');
137
- push(false, 'ComfyUI node classes', `missing: ${c.missing_node_classes.join(', ')}${presentButUnregistered
138
- ? ' — the node files are present, but the running ComfyUI did not register them (import failed — see <ComfyUI>/comfyui-installer.log — or the instance predates the install); restart ComfyUI and re-run verify'
139
- : ''}`);
144
+ const cause = c.missing_node_classes_cause || null;
145
+ if (cause && cause.kind && cause.kind !== 'unknown') {
146
+ // Installer 0.2.5: the cause, not a generic "re-run" (the fix
147
+ // line is chosen from cause.kind in engine/summary.js).
148
+ push(false, 'ComfyUI node classes', `missing: ${c.missing_node_classes.join(', ')} — ${CAUSE_TITLE[cause.kind] || cause.kind}: ${cause.detail}`, { cause });
149
+ } else {
150
+ push(false, 'ComfyUI node classes', `missing: ${c.missing_node_classes.join(', ')}${presentButUnregistered
151
+ ? ' — the node files are present, but the running ComfyUI did not register them (import failed — see <ComfyUI>/comfyui-installer.log — or the instance predates the install); restart ComfyUI and re-run verify'
152
+ : ''}${cause && cause.detail ? ` (${cause.detail})` : ''}`, cause ? { cause } : null);
153
+ }
140
154
  }
141
155
  } else {
142
156
  push(null, 'ComfyUI API', 'not checked (start ComfyUI and re-run verification)');