@animastor/installer 0.1.1 → 0.2.9

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.
@@ -37,6 +37,9 @@ const worker = require('./worker');
37
37
  const repoBundleSource = require('../worker-bundle-source');
38
38
  const prereq = require('./prereq');
39
39
  const management = require('../management');
40
+ const comfyOwnerMod = require('./comfy-owner');
41
+ const nodeDeps = require('./node-deps');
42
+ const pydeps = require('./pydeps');
40
43
  const { createProgressReporter } = require('./progress');
41
44
  const { buildVerificationReport } = require('../verification-report');
42
45
 
@@ -323,18 +326,53 @@ async function runInstallation(args) {
323
326
  // user's own ComfyUI alone but still runs OUR worker. The flags are also
324
327
  // remembered across re-runs — a bare re-run keeps the same wiring instead
325
328
  // of silently reverting to defaults. Explicit CLI flags always win.
329
+ // ComfyUI ownership, resolved BY FACT by the caller (engine/comfy-owner.js
330
+ // reads the running processes). The recorded settings are only reused
331
+ // when they do not contradict the machine: an install-state that says
332
+ // "managed / startComfyui=true" while the PLATFORM runs its own ComfyUI
333
+ // must never make the installer start a second one on 8188.
334
+ const comfyOwner = options.comfyOwner || null;
335
+ const foreignComfy = comfyOwner && comfyOwner.owner === 'foreign' ? comfyOwner : null;
336
+ if (!dryRun && comfyOwner) {
337
+ for (const c of comfyOwner.conflicts || []) log.info(`install state corrected — ${c.message}`);
338
+ if (st.mode !== mode) {
339
+ log.info(`install state corrected: mode ${st.mode || '(unset)'} → ${mode}`);
340
+ st.mode = mode;
341
+ }
342
+ }
326
343
  if (!dryRun) {
327
344
  const saved = st.installer_options || {};
328
- for (const k of ['comfyPort', 'startComfyui', 'startWorker']) {
345
+ const requestedStartComfy = options.startComfyui;
346
+ for (const k of ['comfyPort', 'startWorker']) {
347
+ // A foreign (platform) ComfyUI dictates the port from its cmdline
348
+ // — the remembered port of a previous boot is not reused (and not
349
+ // announced as "reusing").
350
+ if (k === 'comfyPort' && foreignComfy) continue;
329
351
  if (options[k] === undefined && saved[k] !== undefined) {
330
352
  options[k] = saved[k];
331
353
  log.info(`reusing remembered setting: ${k}=${saved[k]}`);
332
354
  }
333
355
  }
334
- if (options.startComfyui === undefined) options.startComfyui = (mode === 'managed');
335
- if (options.startWorker === undefined) options.startWorker = (mode !== 'existing') && (decisions.worker_setup !== false);
356
+ // ComfyUI start: the ownership FACT beats both the flag and the
357
+ // remembered setting — a foreign instance means "never start a second
358
+ // ComfyUI", full stop.
359
+ const startDecision = comfyOwnerMod.decideStartComfy({
360
+ owner: comfyOwner ? comfyOwner.owner : 'none',
361
+ requested: requestedStartComfy,
362
+ remembered: saved.startComfyui,
363
+ mode,
364
+ });
365
+ options.startComfyui = startDecision.startComfyui;
366
+ if (startDecision.ignored_request) log.warn(`--start-comfy ignored: ${startDecision.reason}`);
367
+ else if (startDecision.reason === 'remembered setting') log.info(`reusing remembered setting: startComfyui=${!!startDecision.startComfyui}`);
368
+ // The worker is OURS in every mode (existing mode only leaves the
369
+ // user's ComfyUI alone) — an installed-but-stopped worker is exactly
370
+ // the "installed, never online" failure.
371
+ if (options.startWorker === undefined) options.startWorker = decisions.worker_setup !== false;
336
372
  // Never wire this install to a FOREIGN service on the default port.
337
- if (options.comfyPort !== undefined) {
373
+ // (Our own-port logic only: with the platform's ComfyUI the port is
374
+ // its --port, the "occupied → pick a new one" search does not apply.)
375
+ if (options.comfyPort !== undefined && !foreignComfy) {
338
376
  const ours = st.comfyui_runtime && st.comfyui_runtime.port === options.comfyPort;
339
377
  const s = await comfyPortState(io, options.comfyPort);
340
378
  if (s === 'foreign' && !ours) {
@@ -342,6 +380,16 @@ async function runInstallation(args) {
342
380
  options.comfyPort = undefined;
343
381
  }
344
382
  }
383
+ if (foreignComfy && foreignComfy.port) {
384
+ // The platform's ComfyUI IS the target: its --port (re-read from
385
+ // the cmdline on every run — it changes between boots).
386
+ options.comfyPort = foreignComfy.port;
387
+ }
388
+ if (options.comfyPort === undefined && mode !== 'managed' && options.runningComfy && options.runningComfy.port) {
389
+ // existing/shared: the user's running ComfyUI IS the target — use
390
+ // its real --port instead of assuming 8188.
391
+ options.comfyPort = options.runningComfy.port;
392
+ }
345
393
  if (options.comfyPort === undefined) {
346
394
  options.comfyPort = await autoPickComfyPort(io, { st, mode, log });
347
395
  }
@@ -350,6 +398,33 @@ async function runInstallation(args) {
350
398
  startComfyui: !!options.startComfyui,
351
399
  startWorker: !!options.startWorker,
352
400
  };
401
+ // Restart of the platform's ComfyUI after node dependencies (0.2.4):
402
+ // a recorded answer survives every run; an explicit flag replaces it.
403
+ const restartPlatform = options.restartPlatformComfy !== undefined ? options.restartPlatformComfy : saved.restartPlatformComfy;
404
+ if (restartPlatform === true || restartPlatform === false) st.installer_options.restartPlatformComfy = restartPlatform;
405
+ // Node-deps record of the dependency gate (overlay, version
406
+ // replacements, accepted conflicts — installer 0.2.6) is written by
407
+ // the CLI before the engine runs: kept, not dropped.
408
+ if (saved.nodeDeps) st.installer_options.nodeDeps = saved.nodeDeps;
409
+ // Hub version seen by this run (bootstrap env) — `animastor doctor`
410
+ // prints it instead of "hub unknown" on later runs.
411
+ // Who runs the ComfyUI, as seen by THIS run (installer 0.2.3): the
412
+ // boot path of the next run waits for a platform ComfyUI by it.
413
+ if (comfyOwner && comfyOwner.owner !== 'none') {
414
+ st.comfy_owner = {
415
+ owner: comfyOwner.owner,
416
+ pid: comfyOwner.pid ?? null,
417
+ url: comfyOwner.url || null,
418
+ seen_at: new Date(io.now()).toISOString(),
419
+ };
420
+ }
421
+ if (options.hubVersion) st.hub_version = String(options.hubVersion);
422
+ else if (process.env.ANIMASTOR_HUB_VERSION) st.hub_version = process.env.ANIMASTOR_HUB_VERSION;
423
+ }
424
+ // Installer 0.2.5: what the CLI created before the engine ran (node-deps
425
+ // overlay, prestartup custom node) is owned → removed by `uninstall`.
426
+ for (const e of options.ownedServices || []) {
427
+ if (e && e.path && !dryRun) state.addOwnedComponent(st, 'services', e);
353
428
  }
354
429
  const save = () => state.saveState(io, statePath, st, io.now);
355
430
  if (initialState) {
@@ -586,6 +661,23 @@ async function runInstallation(args) {
586
661
  const a = st.artifacts[id];
587
662
  return !!(a && a.detail && /python dependencies incomplete/.test(a.detail.reason || ''));
588
663
  });
664
+ // Type B (installer 0.2.4): the pip requirements of every required
665
+ // node on disk are checked in the Python of OUR ComfyUI (the running
666
+ // main.py, else the venv) — unsatisfied ones get the same idempotent
667
+ // pip retry, and the managed instance is restarted below.
668
+ if (!runtimeFatal && !dryRun && mode === 'managed' && !foreignComfy) {
669
+ const oursPid = comfyOwner && comfyOwner.ours ? comfyOwner.ours.pid : null;
670
+ const fromProc = oursPid ? nodeDeps.pythonOfProcess(io, oursPid).python : null;
671
+ const venvPy = platformAdapter.venvPythonBin(path.join(comfyuiRoot, 'venv'));
672
+ const depsPython = fromProc || (io.fs.existsSync(venvPy) ? venvPy : null);
673
+ if (depsPython) {
674
+ const dc = nodeDeps.checkNodeDeps(io, { python: depsPython, root: comfyuiRoot, manifests });
675
+ for (const n of dc.nodes) {
676
+ if (!retryDeps.includes(n.id)) retryDeps.push(n.id);
677
+ log.info(`custom-node dependencies missing in ${depsPython}: ${nodeDeps.describeUnsatisfied([n])}`);
678
+ }
679
+ }
680
+ }
589
681
  const nodesApproved = !runtimeFatal && nodesStep && nodesStep.action && nodesStep.decision === 'yes';
590
682
  if (!runtimeFatal && (nodesApproved || retryDeps.length > 0)) {
591
683
  const python = platformAdapter.venvPythonBin(path.join(comfyuiRoot, 'venv'));
@@ -636,6 +728,11 @@ async function runInstallation(args) {
636
728
  // /object_info registry reflects the files on disk; otherwise
637
729
  // verification below would check a stale process and fail.
638
730
  const nodesChanged = result.results.custom_nodes.some((x) => x.status === 'installed' && !x.reason);
731
+ if (nodesChanged && !options.nodeClassesDeadline) {
732
+ // Freshly installed nodes: the class check below may wait for
733
+ // the restarted ComfyUI (0.2.4).
734
+ options.nodeClassesDeadline = io.now() + Math.max(options.comfyWaitMs || 0, options.verifyTimeoutMs || 120000);
735
+ }
639
736
  if (nodesChanged && options.startComfyui !== false) {
640
737
  const port = options.comfyPort || 8188;
641
738
  const rr = await log.step('restart ComfyUI', () => withBusy('Waiting for ComfyUI to restart', () => comfyui.restartManagedComfyUI(io, {
@@ -689,10 +786,21 @@ async function runInstallation(args) {
689
786
  } else if (strategy.mechanism === 'installer_preload') {
690
787
  // D2 closed: installer pre-downloads ModelScope repos
691
788
  // Use dedicated ModelScope snapshot download (not single-file downloadArtifact)
692
- const expectedFiles = dep.expected_files || null;
789
+ // An incomplete repo downloads ONLY its missing files —
790
+ // files already on disk are never re-hashed or
791
+ // re-downloaded (a different-but-working revision must
792
+ // not trigger a multi-GB re-download) — and next to the
793
+ // found files when they live in an extra_model_paths
794
+ // folder.
795
+ const entry = report.entries.find((e) => e.id === spec.id) || {};
796
+ const expectedFiles = (entry.reason === 'incomplete' && Array.isArray(entry.missing_files) && entry.missing_files.length > 0)
797
+ ? entry.missing_files
798
+ : (dep.expected_files || null);
799
+ const loc = entry.found && entry.found.location ? entry.found.location : null;
800
+ const dlSpec = loc ? { ...spec, target_path: loc.target_dir } : spec;
693
801
  const checksums = null; // ModelScope checksums not yet in manifest; verified by size
694
- const r = await log.step(`download model ${spec.id} (ModelScope)`, async () => downloader.downloadModelScopeRepo(io, spec, {
695
- root: comfyuiRoot,
802
+ const r = await log.step(`download model ${spec.id} (ModelScope)`, async () => downloader.downloadModelScopeRepo(io, dlSpec, {
803
+ root: loc ? loc.base : comfyuiRoot,
696
804
  getHeader,
697
805
  retries: options.downloadRetries || 3,
698
806
  retryDelayMs: options.retryDelayMs || 500,
@@ -773,10 +881,76 @@ async function runInstallation(args) {
773
881
  save();
774
882
  }
775
883
 
884
+ // Node.js for the worker: the SAME binary everywhere (installer start,
885
+ // start-worker.sh, `animastor` tool) — recorded as NODE_BIN in .env.
886
+ const nodePick = options.nodeBinary !== undefined ? options.nodeBinary : probe.pickNodeBinary(io);
887
+ const nodeBin = nodePick ? nodePick.bin : process.execPath;
888
+
889
+ // 4.55 ComfyUI up + API base probe ------------------------------------------
890
+ // Managed mode starts its ComfyUI BEFORE the worker is wired, so the
891
+ // worker's COMFY_URL comes from a real probe: plain
892
+ // http://127.0.0.1:<port> first, a notebook prefix only when the plain
893
+ // URL does not answer. Existing mode never starts the user's ComfyUI.
894
+ const comfyPort = options.comfyPort || 8188;
895
+ let comfyUrl = null;
896
+ // A foreign (platform) ComfyUI is addressed EXACTLY as its cmdline says
897
+ // (--port plus --baseurl), re-verified on every run: the port and the
898
+ // prefix change between node boots, so nothing is remembered.
899
+ if (!runtimeFatal && !dryRun && foreignComfy && foreignComfy.url) {
900
+ const stats = await comfyui.systemStats(io, foreignComfy.url);
901
+ if (stats) {
902
+ comfyUrl = foreignComfy.url;
903
+ log.info(`ComfyUI API: ${comfyUrl} (started outside the installer — pid ${foreignComfy.pid}, left running)`);
904
+ } else {
905
+ log.warn(`the ComfyUI process (pid ${foreignComfy.pid}) does not answer GET /system_stats at ${foreignComfy.url} yet`);
906
+ }
907
+ }
908
+ if (!runtimeFatal && !dryRun && !comfyUrl) {
909
+ const plainUp = await comfyui.systemStats(io, `http://127.0.0.1:${comfyPort}`);
910
+ if (!plainUp && options.startComfyui && io.fs.existsSync(comfyuiRoot)) {
911
+ const started = await log.step('start ComfyUI', () => withBusy('Starting ComfyUI', async () => {
912
+ const { pid } = comfyui.startComfyUI(io, { root: comfyuiRoot, port: comfyPort, device });
913
+ const up = await comfyui.waitForApi(io, `http://127.0.0.1:${comfyPort}`, { timeoutMs: options.verifyTimeoutMs || 120000, intervalMs: options.pollIntervalMs || 2000 });
914
+ if (!up.ok) throw new Error(up.reason);
915
+ return { pid, up };
916
+ }));
917
+ if (started.ok) result.results.comfyui_started = { pid: started.value.pid, port: comfyPort };
918
+ }
919
+ const prefixes = [];
920
+ if (workerDir) prefixes.push(worker.readEnvValues(io, workerDir).NOTEBOOK_PATH);
921
+ if (options.runningComfy && options.runningComfy.baseurl) prefixes.push(options.runningComfy.baseurl);
922
+ if (foreignComfy && foreignComfy.baseurl) prefixes.push(foreignComfy.baseurl);
923
+ const pr = await probe.probeComfyUrl(io, { port: comfyPort, prefixes: prefixes.filter(Boolean) });
924
+ comfyUrl = pr.url;
925
+ result.results.comfy_url = { url: pr.url, tried: pr.tried, prefixed: !!pr.prefixed };
926
+ if (pr.url) log.info(`ComfyUI API: ${pr.url}${pr.prefixed ? ' (reverse-proxy prefix — the plain URL did not answer)' : ''}`);
927
+ else log.warn(`ComfyUI API not reachable (tried: ${pr.tried.join(', ')})`);
928
+ }
929
+
776
930
  // 4.6 Worker bundle + .env --------------------------------------------------
777
931
  const workerStep = stepById(plan, 'worker-setup');
778
- if (workerStep && workerStep.action && workerStep.decision === 'yes') {
779
- for (const w of workerStep.workers || []) {
932
+ // An installed-but-OUTDATED bundle (e.g. 2.1.1 without COMFY_URL
933
+ // support) is refreshed even when the plan has nothing to install —
934
+ // only with the user's consent to the fixes.
935
+ let bundleTargets = workerStep && workerStep.action && workerStep.decision === 'yes' ? (workerStep.workers || []) : [];
936
+ if (bundleTargets.length === 0 && decisions.apply_fixes !== false && decisions.worker_setup !== false && workerDir
937
+ && io.fs.existsSync(path.join(workerDir, 'worker.cjs'))) {
938
+ const srcDir = repoBundleSource.resolveRepoBundleDir(io.fs, repoRoot);
939
+ const have = worker.readPkgVersion(io, workerDir);
940
+ let want = srcDir ? worker.readPkgVersion(io, srcDir) : null;
941
+ if (!want && hubUrl && io.http && io.http.fetchJson) {
942
+ // no bundled copy: the hub's published bundle version decides
943
+ try {
944
+ const meta = await io.http.fetchJson(`${hubUrl.replace(/\/$/, '')}/worker-bundle/sha256`);
945
+ if (meta && meta.status === 200 && meta.json && typeof meta.json.version === 'string') want = meta.json.version;
946
+ } catch (_) { /* hub unreachable — keep the installed bundle */ }
947
+ }
948
+ if (have && want && have !== want) {
949
+ bundleTargets = [{ id: `worker:${manifests[0].profile.id}`, worker_type: (manifests[0].worker_bundle || {}).worker_type }];
950
+ }
951
+ }
952
+ if (bundleTargets.length > 0) {
953
+ for (const w of bundleTargets) {
780
954
  const manifest = manifests.find((m) => `worker:${m.profile.id}` === w.id) || manifests[0];
781
955
  const bundleRes = await log.step(`install worker bundle (${w.worker_type})`, async () => {
782
956
  // The distributed installer package may not carry the
@@ -802,6 +976,8 @@ async function runInstallation(args) {
802
976
  return withBusySync('Installing worker bundle', () => worker.installWorkerBundle(io, {
803
977
  workerDir, manifest, repoRoot, bundleDir, hubUrl,
804
978
  httpFetchText: null, log,
979
+ update: decisions.apply_fixes !== false,
980
+ nodeBin,
805
981
  }));
806
982
  } finally {
807
983
  if (bundleTmp) {
@@ -826,6 +1002,21 @@ async function runInstallation(args) {
826
1002
  }
827
1003
  }
828
1004
 
1005
+ // 4.6a node-classes.json (installer 0.2.7) — the profile's node
1006
+ // classes for the worker's readiness gate (bundle >= 2.2.2). Written
1007
+ // on every run where a bundle is installed (fresh install, update,
1008
+ // re-run); never fatal.
1009
+ if (workerDir && io.fs.existsSync(path.join(workerDir, 'worker.cjs'))) {
1010
+ const nc = worker.writeNodeClasses(io, { workerDir, manifests, log });
1011
+ result.results.worker.push({ id: 'node-classes', node_classes: nc });
1012
+ if (nc.status === 'written' && st.components.worker) {
1013
+ const owned = new Set(st.components.worker.files_installed || []);
1014
+ owned.add(worker.NODE_CLASSES_FILE);
1015
+ st.components.worker.files_installed = Array.from(owned);
1016
+ save();
1017
+ }
1018
+ }
1019
+
829
1020
  // 4.7 Worker Key + .env configuration ----------------------------------------
830
1021
  // Runs on EVERY install where the worker is wanted — even full re-runs
831
1022
  // whose plan has no worker-key step (nothing left to ask). configureEnv
@@ -836,6 +1027,7 @@ async function runInstallation(args) {
836
1027
  const workerWanted = decisions.worker_setup === true || decisions.worker_setup === 'yes'
837
1028
  || (keyStep && (keyStep.provided || decisions.worker_key_provided === true));
838
1029
  let tokenValue = null; // held in memory only; never stored on result/state
1030
+ let workerConfigChanged = false; // .env or bundle changed in THIS run → restart a running worker
839
1031
  if (workerWanted) {
840
1032
  const manifest = manifests[0];
841
1033
  const required = ((manifest.worker_bundle || {}).env || {}).required || [];
@@ -855,12 +1047,31 @@ async function runInstallation(args) {
855
1047
  values[key] = defaultEnvValue(key, { hubUrl, manifests });
856
1048
  }
857
1049
  }
858
- // Point the worker at the ComfyUI port chosen for this install
859
- // (--comfy-port). Shared hosts often run several ComfyUI
860
- // instances; the default 8188 may belong to a different one.
861
- if (options.comfyPort) values.COMFY_PORT = String(options.comfyPort);
862
- const cfg = await log.step('configure worker .env', async () => worker.configureEnv(io, { workerDir, manifest, values, log }));
1050
+ // Installer-owned wiring: worker type from the PROFILE, the node
1051
+ // binary, the probed ComfyUI API base and port (shared hosts often
1052
+ // run several ComfyUI instances; the default 8188 may belong to a
1053
+ // different one). Written for missing keys always; existing values
1054
+ // are replaced only when the user accepted the fixes
1055
+ // (decisions.apply_fixes — one "Fix?" question in the CLI).
1056
+ const desired = desiredEnvWiring({ manifests, nodeBin, comfyUrl, comfyPort: options.comfyPort, hubUrl, hubUrlExplicit: !!options.hubUrlExplicit });
1057
+ Object.assign(values, desired);
1058
+ const secretOverrides = {};
1059
+ if (options.replaceWorkerKey && secretProvider) {
1060
+ const fresh = await secretProvider('ANIMASTOR_WORKER_TOKEN');
1061
+ if (fresh) {
1062
+ log.registerSecret(fresh);
1063
+ secretOverrides.ANIMASTOR_WORKER_TOKEN = fresh;
1064
+ tokenValue = fresh;
1065
+ }
1066
+ }
1067
+ const cfg = await log.step('configure worker .env', async () => worker.configureEnv(io, {
1068
+ workerDir, manifest, values,
1069
+ overrides: decisions.apply_fixes !== false ? desired : {},
1070
+ secretOverrides,
1071
+ log,
1072
+ }));
863
1073
  result.results.worker.push({ id: 'env', config: cfg.ok ? cfg.value : { status: 'failed', reason: String(cfg.error && cfg.error.message) } });
1074
+ if (cfg.ok && (cfg.value.created || (cfg.value.changed || []).length > 0 || (cfg.value.added || []).length > 0)) workerConfigChanged = true;
864
1075
  if (cfg.ok && st.components.worker) {
865
1076
  st.components.worker.env_created = cfg.value.created === true;
866
1077
  } else if (cfg.ok) {
@@ -873,49 +1084,8 @@ async function runInstallation(args) {
873
1084
  save();
874
1085
  }
875
1086
 
876
- // 4.8 Worker start (managed-mode default / --start-worker) --------
877
- // A fatal runtime failure leaves the install unrecoverable — every
878
- // dependent step (including daemon starts) is SKIPPED, never ploughed
879
- // through behind a broken ComfyUI.
880
- let startedWorkerPid = null;
881
- if (options.startWorker && workerDir && !runtimeFatal) {
882
- const r = await log.step('start worker', async () => worker.startWorker(io, { workerDir }));
883
- const res = r.ok ? r.value : { started: false, alive: false, reason: String(r.error && r.error.message) };
884
- result.results.worker.push({ id: 'worker-process', ...res });
885
- if (res.started && res.alive) {
886
- startedWorkerPid = res.pid;
887
- if (res.already_running) log.info(`worker already running (pid ${res.pid}) — not spawning a second instance`);
888
- state.setArtifact(st, 'worker-process', 'installed', { pid: res.pid });
889
- } else {
890
- state.setArtifact(st, 'worker-process', 'failed', { reason: res.reason || null });
891
- result.warnings.push(`worker did not start: ${res.reason || 'unknown reason'}`);
892
- }
893
- save();
894
- }
895
-
896
- // 4.9 Verification --------------------------------------------------------------
897
- // A fatal runtime failure means ComfyUI cannot start — skip the live
898
- // start step entirely (it would only spawn a doomed process).
899
- const ver = await runVerification({
900
- io, manifests, roots: { comfyuiRoot, workerDir, hubUrl },
901
- options: { ...options, startComfyui: runtimeFatal ? false : options.startComfyui },
902
- log, crypto,
903
- tokenValue,
904
- device,
905
- workerPid: startedWorkerPid,
906
- onEvent: (kind, value) => { result.results[kind] = value; },
907
- });
908
- result.verification = ver;
909
- // Record the instance this installer started so future runs reuse its
910
- // port instead of auto-picking a new one (the runVerification scope
911
- // has no state — the start step reports via the comfyui_started event).
912
- const startedEv = result.results.comfyui_started;
913
- if (startedEv && startedEv.port) {
914
- st.comfyui_runtime = { port: startedEv.port, pid: startedEv.pid, started_at: io.now() };
915
- save();
916
- }
917
-
918
- // 4.10 Management tools ---------------------------------------------------
1087
+ // 4.75 Management tools (before the worker start: the final summary names
1088
+ // the `animastor` command in its fix lines) ---------------------------------------------------
919
1089
  // Optional component (install decision install_management_tools). The
920
1090
  // tools are thin wrappers around this CLI's management commands — the
921
1091
  // runtime logic is shared (management.js), never duplicated. Installing
@@ -924,13 +1094,22 @@ async function runInstallation(args) {
924
1094
  // precisely. A tools failure must never fail the installation itself.
925
1095
  if (decisions.install_management_tools === true && toolsDir && !dryRun) {
926
1096
  try {
1097
+ // The bootstrap runs this CLI from a temp dir wiped on exit —
1098
+ // the tools must point at a PERSISTENT copy of the installer
1099
+ // (<base>/installer), refreshed on every run.
927
1100
  const r = await log.step('install management tools', async () => withBusySync('Installing management tools', () => management.installManagementTools(io, {
928
1101
  toolsDir,
929
- nodePath: process.execPath,
1102
+ nodePath: nodeBin,
930
1103
  cliPath: path.join(__dirname, '..', 'cli.js'),
1104
+ // engine/ → installer/ → src/ → package root (src/, ai/, package.json)
1105
+ installerSrcRoot: options.persistInstaller === false ? null : path.resolve(__dirname, '..', '..', '..'),
1106
+ installerDestRoot: path.join(path.dirname(toolsDir), 'installer'),
1107
+ linkDir: options.linkDir !== undefined ? options.linkDir : management.defaultLinkDir({ uid: currentUid, home }),
1108
+ home,
931
1109
  statePath,
932
1110
  root: comfyuiRoot,
933
1111
  workerDir,
1112
+ hubUrl,
934
1113
  log,
935
1114
  platformAdapter,
936
1115
  })));
@@ -942,7 +1121,26 @@ async function runInstallation(args) {
942
1121
  for (const f of r.value.files) {
943
1122
  state.addOwnedComponent(st, 'services', { id: 'management-tools', path: f });
944
1123
  }
1124
+ if (r.value.link) state.addOwnedComponent(st, 'services', { id: 'animastor-command', path: r.value.link });
1125
+ if (r.value.installerDir) state.addOwnedComponent(st, 'services', { id: 'installer-copy', path: r.value.installerDir });
1126
+ if (r.value.path_hint) result.warnings.push(r.value.path_hint);
945
1127
  state.setArtifact(st, 'management-tools', 'installed', { dir: r.value.toolsDir });
1128
+ // Autostart: ~/animastor/start-worker.sh becomes a thin
1129
+ // wrapper around `animastor start` (the old script is kept
1130
+ // as .bak). Installed next to the worker, re-applied on
1131
+ // every run so a reboot that wipes the file is repaired.
1132
+ const wrap = management.ensureStartWorkerWrapper(io, {
1133
+ workerDir,
1134
+ animastorPath: r.value.link || r.value.command || null,
1135
+ });
1136
+ result.results.start_worker_wrapper = wrap;
1137
+ if (wrap.status === 'replaced') {
1138
+ log.info(`autostart: start-worker.sh replaced by the animastor wrapper${wrap.backup ? ` (old script: ${wrap.backup})` : ''}`);
1139
+ } else if (wrap.status === 'created') {
1140
+ log.info(`autostart: start-worker.sh created → ${wrap.path}`);
1141
+ } else if (wrap.status === 'failed') {
1142
+ result.warnings.push(`autostart wrapper could not be written: ${wrap.reason}`);
1143
+ }
946
1144
  } else {
947
1145
  const reason = r.error && r.error.message ? r.error.message : 'unknown failure';
948
1146
  result.warnings.push(`management tools could not be installed: ${reason}`);
@@ -956,8 +1154,143 @@ async function runInstallation(args) {
956
1154
  }
957
1155
  }
958
1156
 
1157
+ // 4.8 Worker start (default in every mode; --no-start-worker opts out) ---
1158
+ // "done" ONLY after the worker itself logged "ComfyUI ready": a
1159
+ // spawned-but-stuck process is a FAILED step, never a silent pass.
1160
+ // A fatal runtime failure leaves the install unrecoverable — every
1161
+ // dependent step (including daemon starts) is SKIPPED.
1162
+ let startedWorkerPid = null;
1163
+ let workerReady = null;
1164
+ let workerStart = null;
1165
+ if (options.startWorker && workerDir && !runtimeFatal) {
1166
+ const r = await log.step('start worker', async () => {
1167
+ const bundleChanged = !!options.bundleRefreshedEarly || result.results.worker.some((x) => x.bundle && (x.bundle.files_installed || []).length > 0);
1168
+ // Installer 0.2.8: a running worker is restarted only when its
1169
+ // configuration changed, and never in the middle of a task
1170
+ // (worker.ensureWorker: wait up to --wait-job-ms, else deferred).
1171
+ const configChanged = [];
1172
+ if (workerConfigChanged) configChanged.push('.env changed by this run');
1173
+ if (bundleChanged) configChanged.push('worker bundle updated by this run');
1174
+ const res = await worker.ensureWorker(io, {
1175
+ workerDir, nodeBin, graceMs: options.workerGraceMs || 3000,
1176
+ configChanged,
1177
+ force: !!options.forceWorkerRestart,
1178
+ boot: !!options.boot,
1179
+ waitJobMs: options.waitJobMs !== undefined ? options.waitJobMs : worker.DEFAULT_WAIT_JOB_MS,
1180
+ pollMs: options.jobPollMs || 5000,
1181
+ sleep: options.sleep || null,
1182
+ log,
1183
+ tool: options.toolCommand || toolCommandFrom(result.results.management_tools),
1184
+ });
1185
+ workerStart = res;
1186
+ if (res.deferred) throw new Error(res.reason);
1187
+ if (!res.started || !res.alive) {
1188
+ // An immediate exit is usually the fail-closed credential
1189
+ // gate — say so (the fix is a new key, not a re-run).
1190
+ if (res.logFile) {
1191
+ const scan = worker.scanWorkerLog(worker.readLogFrom(io, res.logFile, res.logOffset || 0));
1192
+ if (scan.auth_failed) {
1193
+ workerReady = { comfy_ready: false, heartbeat: false, auth_failed: true, reason: `the Worker Key was rejected (Worker authentication failed) — see ${res.logFile}` };
1194
+ throw new Error(workerReady.reason);
1195
+ }
1196
+ }
1197
+ throw new Error(res.reason || 'worker did not start');
1198
+ }
1199
+
1200
+ // The 90 s "worker → ComfyUI ready" window opens only once
1201
+ // ComfyUI itself answers (installer 0.2.3) — a ComfyUI that is
1202
+ // still loading must not eat the worker's time.
1203
+ const comfyUpUrl = comfyUrl || (foreignComfy && foreignComfy.url) || null;
1204
+ const ready = await withBusy('Waiting for the worker to reach ComfyUI', () => worker.waitForWorkerReady(io, {
1205
+ workerDir, pid: res.pid, logFile: res.logFile, logOffset: res.logOffset || 0,
1206
+ comfyUp: comfyUpUrl ? async () => !!(await comfyui.systemStats(io, comfyUpUrl)) : null,
1207
+ comfyUpTimeoutMs: options.comfyWaitMs || 0,
1208
+ comfyTimeoutMs: options.workerReadyTimeoutMs || 90000,
1209
+ pollMs: options.pollIntervalMs || 1000,
1210
+ requireHeartbeat: false,
1211
+ }));
1212
+ workerReady = ready;
1213
+ if (!ready.comfy_ready) throw new Error(ready.reason);
1214
+ return { ...res, ...ready };
1215
+ });
1216
+ const res = r.ok ? r.value : { ...(workerStart || {}), started: !!(workerStart && workerStart.started), alive: false, reason: String(r.error && r.error.message) };
1217
+ result.results.worker.push({
1218
+ id: 'worker-process', pid: res.pid || null, started: !!res.started, comfy_ready: !!(workerReady && workerReady.comfy_ready), reason: r.ok ? null : res.reason, log_file: res.logFile || null,
1219
+ action: workerStart ? workerStart.action || null : null,
1220
+ restart_reasons: workerStart ? workerStart.restart_reasons || [] : [],
1221
+ restart_pending: workerStart && workerStart.restart_pending ? workerStart.restart_pending : null,
1222
+ deferred: !!(workerStart && workerStart.deferred),
1223
+ });
1224
+ if (r.ok) {
1225
+ startedWorkerPid = res.pid;
1226
+ state.setArtifact(st, 'worker-process', 'installed', { pid: res.pid });
1227
+ } else {
1228
+ if (workerStart && workerStart.pid) startedWorkerPid = workerStart.pid;
1229
+ state.setArtifact(st, 'worker-process', 'failed', { reason: res.reason || null });
1230
+ }
1231
+ save();
1232
+ // Hub heartbeat (Animastor shows ONLINE) — only meaningful once the
1233
+ // worker reached ComfyUI (heartbeats start after that).
1234
+ if (r.ok) {
1235
+ const hb = await withBusy('Waiting for the hub to confirm the heartbeat', () => worker.waitForWorkerReady(io, {
1236
+ workerDir, pid: res.pid, logFile: res.logFile, logOffset: res.logOffset || 0,
1237
+ comfyTimeoutMs: 1000, heartbeatTimeoutMs: options.heartbeatTimeoutMs || 45000,
1238
+ pollMs: options.pollIntervalMs || 1000,
1239
+ }));
1240
+ workerReady = hb;
1241
+ }
1242
+ }
1243
+
1244
+ // "current job: none|<id>" of the doctor result (installer 0.2.8) —
1245
+ // read at the end of the step, from the running worker's own log.
1246
+ if (workerDir && !dryRun) {
1247
+ try { result.results.current_job = worker.currentJobLabel(io, { workerDir }); } catch (_) { result.results.current_job = 'unknown'; }
1248
+ }
1249
+
1250
+ // 4.9 Verification --------------------------------------------------------------
1251
+ // A fatal runtime failure means ComfyUI cannot start — skip the live
1252
+ // start step entirely (it would only spawn a doomed process).
1253
+ const ver = await runVerification({
1254
+ io, manifests, roots: { comfyuiRoot, workerDir, hubUrl },
1255
+ options: { ...options, comfyUrl, startComfyui: runtimeFatal ? false : options.startComfyui },
1256
+ log, crypto,
1257
+ tokenValue,
1258
+ device,
1259
+ workerPid: startedWorkerPid,
1260
+ onEvent: (kind, value) => { result.results[kind] = value; },
1261
+ });
1262
+ result.verification = ver;
1263
+ // Record the instance this installer started so future runs reuse its
1264
+ // port instead of auto-picking a new one (the runVerification scope
1265
+ // has no state — the start step reports via the comfyui_started event).
1266
+ const startedEv = result.results.comfyui_started;
1267
+ if (startedEv && startedEv.port) {
1268
+ st.comfyui_runtime = { port: startedEv.port, pid: startedEv.pid, started_at: io.now() };
1269
+ save();
1270
+ }
1271
+
1272
+ // 4.11 End-to-end: ComfyUI API → worker "ComfyUI ready" → hub heartbeat.
1273
+ result.results.comfy_owner = {
1274
+ owner: comfyOwner ? comfyOwner.owner : null,
1275
+ mode,
1276
+ pid: comfyOwner ? comfyOwner.pid : null,
1277
+ url: comfyUrl,
1278
+ baseurl: comfyOwner ? comfyOwner.baseurl : null,
1279
+ };
1280
+ result.e2e = await endToEndChecks(io, {
1281
+ mode, comfyUrl, comfyPort, hubUrl,
1282
+ comfyTried: (result.results.comfy_url && result.results.comfy_url.tried) || (foreignComfy && foreignComfy.url ? [foreignComfy.url] : []),
1283
+ platformComfy: !!foreignComfy,
1284
+ workerWanted: !!(options.startWorker && workerDir && !runtimeFatal),
1285
+ workerStart, workerReady,
1286
+ tool: options.toolCommand || toolCommandFrom(result.results.management_tools),
1287
+ });
1288
+
959
1289
  if (runtimeFatal) {
960
1290
  result.status = 'failed';
1291
+ } else if (result.e2e.some((c) => c.ok === false)) {
1292
+ const blockedCount = result.blocked.length + result.results.models.filter((m) => m.status === 'blocked').length;
1293
+ result.status = blockedCount > 0 ? 'blocked' : 'failed';
961
1294
  } else {
962
1295
  const blockedCount = result.blocked.length + result.results.models.filter((m) => m.status === 'blocked').length;
963
1296
  if (result.blocked.length > 0 || blockedCount > 0) result.status = 'blocked';
@@ -974,6 +1307,51 @@ async function runInstallation(args) {
974
1307
  }
975
1308
  }
976
1309
 
1310
+ /**
1311
+ * Installer 0.2.5: bring an INSTALLED worker bundle to the version this
1312
+ * installer ships (its bundled copy, else the hub's published bundle) —
1313
+ * called by the CLI BEFORE any check that can end the run early (live E2E
1314
+ * 02.11: installer 0.2.4 stopped at the node-deps gate and left bundle 2.2.0
1315
+ * behind). A missing installation is left to the regular install step.
1316
+ * @returns {Promise<{ status: 'absent'|'current'|'unknown'|'updated'|'failed', have: string|null, want: string|null, files_installed?: string[], reason?: string }>}
1317
+ */
1318
+ async function refreshInstalledWorkerBundle(io, { workerDir, manifest, repoRoot = null, hubUrl = null, log = null, nodeBin = null }) {
1319
+ if (!workerDir || !manifest || !io.fs.existsSync(path.join(workerDir, 'worker.cjs'))) return { status: 'absent', have: null, want: null };
1320
+ const srcDir = repoBundleSource.resolveRepoBundleDir(io.fs, repoRoot);
1321
+ const have = worker.readPkgVersion(io, workerDir);
1322
+ let want = srcDir ? worker.readPkgVersion(io, srcDir) : null;
1323
+ if (!want && hubUrl && io.http && io.http.fetchJson) {
1324
+ try {
1325
+ const meta = await io.http.fetchJson(`${hubUrl.replace(/\/$/, '')}/worker-bundle/sha256`);
1326
+ if (meta && meta.status === 200 && meta.json && typeof meta.json.version === 'string') want = meta.json.version;
1327
+ } catch (_) { /* hub unreachable */ }
1328
+ }
1329
+ if (!have || !want) return { status: 'unknown', have, want };
1330
+ if (have === want) return { status: 'current', have, want };
1331
+ const wbFiles = ((manifest.worker_bundle || {}).files) || [];
1332
+ const missingFromRepo = wbFiles.filter((f) => !(srcDir && io.fs.existsSync(path.join(srcDir, f))));
1333
+ let bundleDir = null;
1334
+ let bundleTmp = null;
1335
+ try {
1336
+ if (missingFromRepo.length > 0 && hubUrl) {
1337
+ const fetched = await worker.fetchHubWorkerBundle(io, { hubUrl });
1338
+ if (fetched.bundleDir) { bundleDir = fetched.bundleDir; bundleTmp = fetched.tmpDir; }
1339
+ else return { status: 'failed', have, want, reason: `worker bundle fetch failed: ${fetched.reason}` };
1340
+ }
1341
+ const r = worker.installWorkerBundle(io, { workerDir, manifest, repoRoot, bundleDir, hubUrl, httpFetchText: null, log, update: true, nodeBin });
1342
+ if (r.status !== 'installed') return { status: 'failed', have, want, reason: r.reason || r.status };
1343
+ const now = worker.readPkgVersion(io, workerDir);
1344
+ if (now !== want) return { status: 'failed', have, want, reason: `bundle is ${now} after the update, expected ${want}` };
1345
+ return { status: 'updated', have, want, files_installed: r.files_installed || [] };
1346
+ } catch (err) {
1347
+ return { status: 'failed', have, want, reason: err.message };
1348
+ } finally {
1349
+ if (bundleTmp) {
1350
+ try { io.fs.rmSync(bundleTmp, { recursive: true, force: true }); } catch (_) { /* best effort */ }
1351
+ }
1352
+ }
1353
+ }
1354
+
977
1355
  function pickUpdateTarget(manifest) {
978
1356
  const spec = (manifest.runtime_requirements || {}).comfyui || {};
979
1357
  if (spec.pin && (spec.pin.commit || spec.pin.tag)) return spec.pin;
@@ -989,6 +1367,120 @@ function findModelDep(manifests, id) {
989
1367
  return null;
990
1368
  }
991
1369
 
1370
+ /**
1371
+ * Installer-owned .env wiring for this run (non-secret): WORKER_TYPE from the
1372
+ * profile manifest (never a hard-coded default), NODE_BIN, COMFY_URL when a
1373
+ * probe proved it, COMFY_PORT, HUB_URL when the hub was given explicitly.
1374
+ */
1375
+ function desiredEnvWiring({ manifests, nodeBin = null, comfyUrl = null, comfyPort = null, hubUrl = null, hubUrlExplicit = false }) {
1376
+ const out = {};
1377
+ const type = (manifests[0] && manifests[0].worker_bundle && manifests[0].worker_bundle.worker_type) || null;
1378
+ if (type) out.WORKER_TYPE = type;
1379
+ if (nodeBin) out.NODE_BIN = nodeBin;
1380
+ if (comfyUrl) {
1381
+ out.COMFY_URL = comfyUrl;
1382
+ // NOTEBOOK_PATH follows the probe too (older workers ignore COMFY_URL
1383
+ // and build the URL from COMFY_PORT + NOTEBOOK_PATH): empty when the
1384
+ // plain URL answered, the prefix only when the probe needed it.
1385
+ const m = /^https?:\/\/[^/]+(\/.*)?$/.exec(comfyUrl);
1386
+ out.NOTEBOOK_PATH = m && m[1] ? m[1] : '';
1387
+ }
1388
+ if (comfyPort) out.COMFY_PORT = String(comfyPort);
1389
+ if (hubUrlExplicit && hubUrl) out.HUB_URL = hubUrl;
1390
+ return out;
1391
+ }
1392
+
1393
+ /**
1394
+ * End-to-end checks for type A when the platform's ComfyUI never came up:
1395
+ * one ✗ with the cause and the fix, the worker is not started at all.
1396
+ */
1397
+ function platformComfyMissingChecks({ reason, tool = 'animastor' }) {
1398
+ return [
1399
+ { id: 'comfyui', ok: false, label: 'ComfyUI API', detail: reason, fix: `run \`${tool} doctor\` after the platform's ComfyUI is up` },
1400
+ { id: 'worker', ok: null, label: 'Worker → ComfyUI', detail: 'not started — the platform\'s ComfyUI is not up (no worker against the address of a previous boot)', fix: null },
1401
+ { id: 'heartbeat', ok: null, label: 'Hub heartbeat (Online)', detail: 'not checked — worker not started', fix: null },
1402
+ ];
1403
+ }
1404
+
1405
+ /** The command users type for fixes: `animastor` when linked into PATH, else the absolute tool path. */
1406
+ function toolCommandFrom(tools) {
1407
+ if (tools && tools.command) return tools.command;
1408
+ return 'animastor';
1409
+ }
1410
+
1411
+ /**
1412
+ * The three end-to-end checks the installer result is judged by. Each ✗
1413
+ * carries ONE line of cause and ONE exact fix command — the final summary
1414
+ * prints exactly these (no "scroll up").
1415
+ * @returns {Promise<Array<{ id, ok: boolean|null, label, detail, fix }>>}
1416
+ */
1417
+ async function endToEndChecks(io, { mode, comfyUrl, comfyPort, hubUrl, workerWanted, workerStart, workerReady, tool = 'animastor', comfyTried = [], platformComfy = false }) {
1418
+ const checks = [];
1419
+ const stats = comfyUrl ? await comfyui.systemStats(io, comfyUrl) : null;
1420
+ // Addresses in the result are always FULL (with the notebook prefix):
1421
+ // every URL that was really tried, not a bare host:port.
1422
+ const tried = (comfyTried || []).filter(Boolean);
1423
+ const where = comfyUrl || (tried.length > 0 ? tried.join(', ') : `http://127.0.0.1:${comfyPort || 8188}`);
1424
+ const prefixed = tried.find((u) => /^https?:\/\/[^/]+\/./.test(u)) || null;
1425
+ checks.push(stats
1426
+ ? { id: 'comfyui', ok: true, label: 'ComfyUI API', detail: comfyUrl, fix: null }
1427
+ : {
1428
+ id: 'comfyui', ok: false, label: 'ComfyUI API',
1429
+ detail: `not reachable at ${where} (GET /system_stats)`,
1430
+ fix: mode === 'managed'
1431
+ ? `${tool} start`
1432
+ : platformComfy
1433
+ ? `ComfyUI is started by the platform — when ${comfyUrl || prefixed || where} answers, run: ${tool} doctor`
1434
+ : prefixed
1435
+ ? `start your ComfyUI so that ${prefixed} answers, then run: ${tool} doctor`
1436
+ : `start your ComfyUI on port ${comfyPort || 8188}, then run: ${tool} doctor`,
1437
+ });
1438
+ if (!workerWanted) {
1439
+ checks.push({ id: 'worker', ok: null, label: 'Worker → ComfyUI', detail: 'worker start skipped (--no-start-worker)', fix: `${tool} start` });
1440
+ checks.push({ id: 'heartbeat', ok: null, label: 'Hub heartbeat (Online)', detail: 'not checked — worker not started', fix: `${tool} start` });
1441
+ return checks;
1442
+ }
1443
+ const newKeyFix = `create a new Worker Key in Animastor → Settings → Workers, then run: ${tool} doctor --new-key`;
1444
+ if (workerStart && workerStart.deferred) {
1445
+ // Installer 0.2.8: the worker keeps running (and serving) on its old
1446
+ // configuration; the needed restart was not done — FAILED, exit ≠ 0.
1447
+ checks.push({
1448
+ id: 'worker', ok: false, label: 'Worker restart',
1449
+ detail: String(workerStart.reason || 'restart deferred').replace(/\s+/g, ' '),
1450
+ fix: workerStart.busy_job
1451
+ ? `re-run \`${tool} doctor\` when the task finishes (or \`${tool} doctor --wait-job-ms <ms>\` to wait longer); \`${tool} doctor --force\` restarts now and loses the task's result`
1452
+ : `${tool} doctor --force (restarts the worker even if it is busy)`,
1453
+ });
1454
+ checks.push({ id: 'heartbeat', ok: null, label: 'Hub heartbeat (Online)', detail: `not re-checked — the worker (pid ${workerStart.pid}) keeps running on its previous configuration`, fix: null });
1455
+ return checks;
1456
+ }
1457
+ const r = workerReady || {};
1458
+ // A running worker left as is (installer 0.2.8) is not restarted by
1459
+ // another doctor run — the fix that restarts it is reboot-worker.
1460
+ const rerun = workerStart && workerStart.action === 'left' ? `${tool} reboot-worker` : `${tool} doctor`;
1461
+ if (r.comfy_ready) {
1462
+ checks.push({ id: 'worker', ok: true, label: 'Worker → ComfyUI', detail: '"ComfyUI ready" in the worker log', fix: null });
1463
+ } else {
1464
+ const reason = (r.reason || (workerStart && workerStart.reason) || 'worker did not start').replace(/\s+/g, ' ');
1465
+ checks.push({
1466
+ id: 'worker', ok: false, label: 'Worker → ComfyUI', detail: reason,
1467
+ fix: r.auth_failed ? newKeyFix : rerun,
1468
+ });
1469
+ }
1470
+ if (r.heartbeat) {
1471
+ checks.push({ id: 'heartbeat', ok: true, label: 'Hub heartbeat (Online)', detail: hubUrl || null, fix: null });
1472
+ } else if (!r.comfy_ready) {
1473
+ checks.push({ id: 'heartbeat', ok: false, label: 'Hub heartbeat (Online)', detail: 'not reached — the worker sends heartbeats only after it reached ComfyUI', fix: r.auth_failed ? newKeyFix : rerun });
1474
+ } else {
1475
+ checks.push({
1476
+ id: 'heartbeat', ok: false, label: 'Hub heartbeat (Online)',
1477
+ detail: (r.reason || 'no heartbeat confirmed').replace(/\s+/g, ' '),
1478
+ fix: r.auth_failed ? newKeyFix : `check that this machine reaches ${hubUrl} (curl -fsS ${hubUrl}/health), then run: ${rerun}`,
1479
+ });
1480
+ }
1481
+ return checks;
1482
+ }
1483
+
992
1484
  function defaultEnvValue(key, { hubUrl, manifests }) {
993
1485
  if (key === 'HUB_URL') return hubUrl || 'https://animastor.org/gpu';
994
1486
  if (key === 'WORKER_TYPE') return (manifests[0].worker_bundle || {}).worker_type || 'image';
@@ -1008,7 +1500,7 @@ async function runVerification({ io, manifests, roots, options, log, crypto, tok
1008
1500
  // ComfyUI live check: use an already-running instance, or start one in
1009
1501
  // managed mode (files on disk are NOT sufficient verification).
1010
1502
  const port = options.comfyPort || 8188;
1011
- const baseUrl = `http://127.0.0.1:${port}`;
1503
+ const baseUrl = options.comfyUrl || `http://127.0.0.1:${port}`;
1012
1504
  const withBusy = (label, fn, o) => (options.term ? options.term.withBusy(label, fn, o) : fn());
1013
1505
  let stats = await comfyui.systemStats(io, baseUrl);
1014
1506
  if (!stats && options.startComfyui && io.fs.existsSync(comfyuiRoot)) {
@@ -1034,8 +1526,50 @@ async function runVerification({ io, manifests, roots, options, log, crypto, tok
1034
1526
  for (const cls of dep.provides_classes || []) manifestClasses.add(cls);
1035
1527
  }
1036
1528
  }
1037
- const missingClasses = Array.from(manifestClasses).filter((c) => !classes.has(c));
1038
- if (missingClasses.length > 0) live.comfyui.missing_node_classes = missingClasses;
1529
+ let missingClasses = Array.from(manifestClasses).filter((c) => !classes.has(c));
1530
+ // Installer 0.2.4: right after the node dependencies were
1531
+ // installed or when the ComfyUI is a new process, the classes are
1532
+ // re-checked until the end of the wait window — not FAILED at once.
1533
+ const deadline = Number(options.nodeClassesDeadline) || 0;
1534
+ const pause = options.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
1535
+ if (missingClasses.length > 0 && deadline > io.now()) {
1536
+ log.info(`node classes not registered yet (${missingClasses.join(', ')}) — re-checking for up to ${Math.round((deadline - io.now()) / 1000)} s`);
1537
+ while (missingClasses.length > 0 && io.now() < deadline) {
1538
+ await pause(Math.min(options.pollIntervalMs || 3000, Math.max(1, deadline - io.now())));
1539
+ const again = await comfyui.objectInfoClasses(io, baseUrl);
1540
+ if (again) missingClasses = Array.from(manifestClasses).filter((c) => !again.has(c));
1541
+ }
1542
+ if (missingClasses.length === 0) log.info('node classes registered');
1543
+ }
1544
+ if (missingClasses.length > 0) {
1545
+ live.comfyui.missing_node_classes = missingClasses;
1546
+ // Installer 0.2.5: say WHY (missing packages / IMPORT FAILED /
1547
+ // restart needed) — "run doctor" alone looped on the live node.
1548
+ try {
1549
+ const ownerInfo = options.comfyOwner || null;
1550
+ const pid = ownerInfo && ownerInfo.pid ? ownerInfo.pid : null;
1551
+ const py = pid ? nodeDeps.pythonOfProcess(io, pid).python : null;
1552
+ let extraPaths = [];
1553
+ if (py && workerDir && ownerInfo && ownerInfo.owner === 'foreign') {
1554
+ const plan = pydeps.planPersistence(io, { python: py, root: comfyuiRoot, base: pydeps.overlayBase(workerDir), create: false });
1555
+ if (plan.kind === 'overlay' && plan.sitePackages && io.fs.existsSync(plan.sitePackages)) extraPaths = [plan.sitePackages];
1556
+ }
1557
+ const logFiles = [
1558
+ workerDir ? path.join(path.dirname(path.resolve(workerDir)), 'logs', 'comfyui-restart.log') : null,
1559
+ comfyuiRoot ? path.join(comfyuiRoot, 'comfyui-installer.log') : null,
1560
+ ].filter(Boolean);
1561
+ const diag = await nodeDeps.diagnoseMissingClasses(io, {
1562
+ missingClasses, manifests, root: comfyuiRoot, url: baseUrl, pid, python: py, extraPaths, logFiles,
1563
+ });
1564
+ live.comfyui.missing_node_classes_cause = {
1565
+ kind: diag.kind, detail: diag.detail, log_source: diag.log_source,
1566
+ owner: ownerInfo && ownerInfo.owner === 'foreign' ? 'foreign' : 'managed',
1567
+ };
1568
+ log.info(`node classes missing — cause: ${diag.kind}: ${diag.detail}`);
1569
+ } catch (err) {
1570
+ log.warn(`node classes missing — cause not determined: ${err.message}`);
1571
+ }
1572
+ }
1039
1573
  }
1040
1574
  // workflow static validation (no generation) — only meaningful when
1041
1575
  // at least one OPTIONAL profile workflow copy is actually installed;
@@ -1176,5 +1710,10 @@ module.exports = {
1176
1710
  createInterruptGuard,
1177
1711
  comfyPortState,
1178
1712
  autoPickComfyPort,
1713
+ platformComfyMissingChecks,
1714
+ refreshInstalledWorkerBundle,
1715
+ writeNodeClasses: worker.writeNodeClasses,
1716
+ desiredEnvWiring,
1717
+ endToEndChecks,
1179
1718
  CPU_MODE_WARNING,
1180
1719
  };