@animastor/installer 0.1.1 → 0.2.4

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,8 @@ 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');
40
42
  const { createProgressReporter } = require('./progress');
41
43
  const { buildVerificationReport } = require('../verification-report');
42
44
 
@@ -323,18 +325,53 @@ async function runInstallation(args) {
323
325
  // user's own ComfyUI alone but still runs OUR worker. The flags are also
324
326
  // remembered across re-runs — a bare re-run keeps the same wiring instead
325
327
  // of silently reverting to defaults. Explicit CLI flags always win.
328
+ // ComfyUI ownership, resolved BY FACT by the caller (engine/comfy-owner.js
329
+ // reads the running processes). The recorded settings are only reused
330
+ // when they do not contradict the machine: an install-state that says
331
+ // "managed / startComfyui=true" while the PLATFORM runs its own ComfyUI
332
+ // must never make the installer start a second one on 8188.
333
+ const comfyOwner = options.comfyOwner || null;
334
+ const foreignComfy = comfyOwner && comfyOwner.owner === 'foreign' ? comfyOwner : null;
335
+ if (!dryRun && comfyOwner) {
336
+ for (const c of comfyOwner.conflicts || []) log.info(`install state corrected — ${c.message}`);
337
+ if (st.mode !== mode) {
338
+ log.info(`install state corrected: mode ${st.mode || '(unset)'} → ${mode}`);
339
+ st.mode = mode;
340
+ }
341
+ }
326
342
  if (!dryRun) {
327
343
  const saved = st.installer_options || {};
328
- for (const k of ['comfyPort', 'startComfyui', 'startWorker']) {
344
+ const requestedStartComfy = options.startComfyui;
345
+ for (const k of ['comfyPort', 'startWorker']) {
346
+ // A foreign (platform) ComfyUI dictates the port from its cmdline
347
+ // — the remembered port of a previous boot is not reused (and not
348
+ // announced as "reusing").
349
+ if (k === 'comfyPort' && foreignComfy) continue;
329
350
  if (options[k] === undefined && saved[k] !== undefined) {
330
351
  options[k] = saved[k];
331
352
  log.info(`reusing remembered setting: ${k}=${saved[k]}`);
332
353
  }
333
354
  }
334
- if (options.startComfyui === undefined) options.startComfyui = (mode === 'managed');
335
- if (options.startWorker === undefined) options.startWorker = (mode !== 'existing') && (decisions.worker_setup !== false);
355
+ // ComfyUI start: the ownership FACT beats both the flag and the
356
+ // remembered setting — a foreign instance means "never start a second
357
+ // ComfyUI", full stop.
358
+ const startDecision = comfyOwnerMod.decideStartComfy({
359
+ owner: comfyOwner ? comfyOwner.owner : 'none',
360
+ requested: requestedStartComfy,
361
+ remembered: saved.startComfyui,
362
+ mode,
363
+ });
364
+ options.startComfyui = startDecision.startComfyui;
365
+ if (startDecision.ignored_request) log.warn(`--start-comfy ignored: ${startDecision.reason}`);
366
+ else if (startDecision.reason === 'remembered setting') log.info(`reusing remembered setting: startComfyui=${!!startDecision.startComfyui}`);
367
+ // The worker is OURS in every mode (existing mode only leaves the
368
+ // user's ComfyUI alone) — an installed-but-stopped worker is exactly
369
+ // the "installed, never online" failure.
370
+ if (options.startWorker === undefined) options.startWorker = decisions.worker_setup !== false;
336
371
  // Never wire this install to a FOREIGN service on the default port.
337
- if (options.comfyPort !== undefined) {
372
+ // (Our own-port logic only: with the platform's ComfyUI the port is
373
+ // its --port, the "occupied → pick a new one" search does not apply.)
374
+ if (options.comfyPort !== undefined && !foreignComfy) {
338
375
  const ours = st.comfyui_runtime && st.comfyui_runtime.port === options.comfyPort;
339
376
  const s = await comfyPortState(io, options.comfyPort);
340
377
  if (s === 'foreign' && !ours) {
@@ -342,6 +379,16 @@ async function runInstallation(args) {
342
379
  options.comfyPort = undefined;
343
380
  }
344
381
  }
382
+ if (foreignComfy && foreignComfy.port) {
383
+ // The platform's ComfyUI IS the target: its --port (re-read from
384
+ // the cmdline on every run — it changes between boots).
385
+ options.comfyPort = foreignComfy.port;
386
+ }
387
+ if (options.comfyPort === undefined && mode !== 'managed' && options.runningComfy && options.runningComfy.port) {
388
+ // existing/shared: the user's running ComfyUI IS the target — use
389
+ // its real --port instead of assuming 8188.
390
+ options.comfyPort = options.runningComfy.port;
391
+ }
345
392
  if (options.comfyPort === undefined) {
346
393
  options.comfyPort = await autoPickComfyPort(io, { st, mode, log });
347
394
  }
@@ -350,6 +397,24 @@ async function runInstallation(args) {
350
397
  startComfyui: !!options.startComfyui,
351
398
  startWorker: !!options.startWorker,
352
399
  };
400
+ // Restart of the platform's ComfyUI after node dependencies (0.2.4):
401
+ // a recorded answer survives every run; an explicit flag replaces it.
402
+ const restartPlatform = options.restartPlatformComfy !== undefined ? options.restartPlatformComfy : saved.restartPlatformComfy;
403
+ if (restartPlatform === true || restartPlatform === false) st.installer_options.restartPlatformComfy = restartPlatform;
404
+ // Hub version seen by this run (bootstrap env) — `animastor doctor`
405
+ // prints it instead of "hub unknown" on later runs.
406
+ // Who runs the ComfyUI, as seen by THIS run (installer 0.2.3): the
407
+ // boot path of the next run waits for a platform ComfyUI by it.
408
+ if (comfyOwner && comfyOwner.owner !== 'none') {
409
+ st.comfy_owner = {
410
+ owner: comfyOwner.owner,
411
+ pid: comfyOwner.pid ?? null,
412
+ url: comfyOwner.url || null,
413
+ seen_at: new Date(io.now()).toISOString(),
414
+ };
415
+ }
416
+ if (options.hubVersion) st.hub_version = String(options.hubVersion);
417
+ else if (process.env.ANIMASTOR_HUB_VERSION) st.hub_version = process.env.ANIMASTOR_HUB_VERSION;
353
418
  }
354
419
  const save = () => state.saveState(io, statePath, st, io.now);
355
420
  if (initialState) {
@@ -586,6 +651,23 @@ async function runInstallation(args) {
586
651
  const a = st.artifacts[id];
587
652
  return !!(a && a.detail && /python dependencies incomplete/.test(a.detail.reason || ''));
588
653
  });
654
+ // Type B (installer 0.2.4): the pip requirements of every required
655
+ // node on disk are checked in the Python of OUR ComfyUI (the running
656
+ // main.py, else the venv) — unsatisfied ones get the same idempotent
657
+ // pip retry, and the managed instance is restarted below.
658
+ if (!runtimeFatal && !dryRun && mode === 'managed' && !foreignComfy) {
659
+ const oursPid = comfyOwner && comfyOwner.ours ? comfyOwner.ours.pid : null;
660
+ const fromProc = oursPid ? nodeDeps.pythonOfProcess(io, oursPid).python : null;
661
+ const venvPy = platformAdapter.venvPythonBin(path.join(comfyuiRoot, 'venv'));
662
+ const depsPython = fromProc || (io.fs.existsSync(venvPy) ? venvPy : null);
663
+ if (depsPython) {
664
+ const dc = nodeDeps.checkNodeDeps(io, { python: depsPython, root: comfyuiRoot, manifests });
665
+ for (const n of dc.nodes) {
666
+ if (!retryDeps.includes(n.id)) retryDeps.push(n.id);
667
+ log.info(`custom-node dependencies missing in ${depsPython}: ${nodeDeps.describeUnsatisfied([n])}`);
668
+ }
669
+ }
670
+ }
589
671
  const nodesApproved = !runtimeFatal && nodesStep && nodesStep.action && nodesStep.decision === 'yes';
590
672
  if (!runtimeFatal && (nodesApproved || retryDeps.length > 0)) {
591
673
  const python = platformAdapter.venvPythonBin(path.join(comfyuiRoot, 'venv'));
@@ -636,6 +718,11 @@ async function runInstallation(args) {
636
718
  // /object_info registry reflects the files on disk; otherwise
637
719
  // verification below would check a stale process and fail.
638
720
  const nodesChanged = result.results.custom_nodes.some((x) => x.status === 'installed' && !x.reason);
721
+ if (nodesChanged && !options.nodeClassesDeadline) {
722
+ // Freshly installed nodes: the class check below may wait for
723
+ // the restarted ComfyUI (0.2.4).
724
+ options.nodeClassesDeadline = io.now() + Math.max(options.comfyWaitMs || 0, options.verifyTimeoutMs || 120000);
725
+ }
639
726
  if (nodesChanged && options.startComfyui !== false) {
640
727
  const port = options.comfyPort || 8188;
641
728
  const rr = await log.step('restart ComfyUI', () => withBusy('Waiting for ComfyUI to restart', () => comfyui.restartManagedComfyUI(io, {
@@ -689,10 +776,21 @@ async function runInstallation(args) {
689
776
  } else if (strategy.mechanism === 'installer_preload') {
690
777
  // D2 closed: installer pre-downloads ModelScope repos
691
778
  // Use dedicated ModelScope snapshot download (not single-file downloadArtifact)
692
- const expectedFiles = dep.expected_files || null;
779
+ // An incomplete repo downloads ONLY its missing files —
780
+ // files already on disk are never re-hashed or
781
+ // re-downloaded (a different-but-working revision must
782
+ // not trigger a multi-GB re-download) — and next to the
783
+ // found files when they live in an extra_model_paths
784
+ // folder.
785
+ const entry = report.entries.find((e) => e.id === spec.id) || {};
786
+ const expectedFiles = (entry.reason === 'incomplete' && Array.isArray(entry.missing_files) && entry.missing_files.length > 0)
787
+ ? entry.missing_files
788
+ : (dep.expected_files || null);
789
+ const loc = entry.found && entry.found.location ? entry.found.location : null;
790
+ const dlSpec = loc ? { ...spec, target_path: loc.target_dir } : spec;
693
791
  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,
792
+ const r = await log.step(`download model ${spec.id} (ModelScope)`, async () => downloader.downloadModelScopeRepo(io, dlSpec, {
793
+ root: loc ? loc.base : comfyuiRoot,
696
794
  getHeader,
697
795
  retries: options.downloadRetries || 3,
698
796
  retryDelayMs: options.retryDelayMs || 500,
@@ -773,10 +871,76 @@ async function runInstallation(args) {
773
871
  save();
774
872
  }
775
873
 
874
+ // Node.js for the worker: the SAME binary everywhere (installer start,
875
+ // start-worker.sh, `animastor` tool) — recorded as NODE_BIN in .env.
876
+ const nodePick = options.nodeBinary !== undefined ? options.nodeBinary : probe.pickNodeBinary(io);
877
+ const nodeBin = nodePick ? nodePick.bin : process.execPath;
878
+
879
+ // 4.55 ComfyUI up + API base probe ------------------------------------------
880
+ // Managed mode starts its ComfyUI BEFORE the worker is wired, so the
881
+ // worker's COMFY_URL comes from a real probe: plain
882
+ // http://127.0.0.1:<port> first, a notebook prefix only when the plain
883
+ // URL does not answer. Existing mode never starts the user's ComfyUI.
884
+ const comfyPort = options.comfyPort || 8188;
885
+ let comfyUrl = null;
886
+ // A foreign (platform) ComfyUI is addressed EXACTLY as its cmdline says
887
+ // (--port plus --baseurl), re-verified on every run: the port and the
888
+ // prefix change between node boots, so nothing is remembered.
889
+ if (!runtimeFatal && !dryRun && foreignComfy && foreignComfy.url) {
890
+ const stats = await comfyui.systemStats(io, foreignComfy.url);
891
+ if (stats) {
892
+ comfyUrl = foreignComfy.url;
893
+ log.info(`ComfyUI API: ${comfyUrl} (started outside the installer — pid ${foreignComfy.pid}, left running)`);
894
+ } else {
895
+ log.warn(`the ComfyUI process (pid ${foreignComfy.pid}) does not answer GET /system_stats at ${foreignComfy.url} yet`);
896
+ }
897
+ }
898
+ if (!runtimeFatal && !dryRun && !comfyUrl) {
899
+ const plainUp = await comfyui.systemStats(io, `http://127.0.0.1:${comfyPort}`);
900
+ if (!plainUp && options.startComfyui && io.fs.existsSync(comfyuiRoot)) {
901
+ const started = await log.step('start ComfyUI', () => withBusy('Starting ComfyUI', async () => {
902
+ const { pid } = comfyui.startComfyUI(io, { root: comfyuiRoot, port: comfyPort, device });
903
+ const up = await comfyui.waitForApi(io, `http://127.0.0.1:${comfyPort}`, { timeoutMs: options.verifyTimeoutMs || 120000, intervalMs: options.pollIntervalMs || 2000 });
904
+ if (!up.ok) throw new Error(up.reason);
905
+ return { pid, up };
906
+ }));
907
+ if (started.ok) result.results.comfyui_started = { pid: started.value.pid, port: comfyPort };
908
+ }
909
+ const prefixes = [];
910
+ if (workerDir) prefixes.push(worker.readEnvValues(io, workerDir).NOTEBOOK_PATH);
911
+ if (options.runningComfy && options.runningComfy.baseurl) prefixes.push(options.runningComfy.baseurl);
912
+ if (foreignComfy && foreignComfy.baseurl) prefixes.push(foreignComfy.baseurl);
913
+ const pr = await probe.probeComfyUrl(io, { port: comfyPort, prefixes: prefixes.filter(Boolean) });
914
+ comfyUrl = pr.url;
915
+ result.results.comfy_url = { url: pr.url, tried: pr.tried, prefixed: !!pr.prefixed };
916
+ if (pr.url) log.info(`ComfyUI API: ${pr.url}${pr.prefixed ? ' (reverse-proxy prefix — the plain URL did not answer)' : ''}`);
917
+ else log.warn(`ComfyUI API not reachable (tried: ${pr.tried.join(', ')})`);
918
+ }
919
+
776
920
  // 4.6 Worker bundle + .env --------------------------------------------------
777
921
  const workerStep = stepById(plan, 'worker-setup');
778
- if (workerStep && workerStep.action && workerStep.decision === 'yes') {
779
- for (const w of workerStep.workers || []) {
922
+ // An installed-but-OUTDATED bundle (e.g. 2.1.1 without COMFY_URL
923
+ // support) is refreshed even when the plan has nothing to install —
924
+ // only with the user's consent to the fixes.
925
+ let bundleTargets = workerStep && workerStep.action && workerStep.decision === 'yes' ? (workerStep.workers || []) : [];
926
+ if (bundleTargets.length === 0 && decisions.apply_fixes !== false && decisions.worker_setup !== false && workerDir
927
+ && io.fs.existsSync(path.join(workerDir, 'worker.cjs'))) {
928
+ const srcDir = repoBundleSource.resolveRepoBundleDir(io.fs, repoRoot);
929
+ const have = worker.readPkgVersion(io, workerDir);
930
+ let want = srcDir ? worker.readPkgVersion(io, srcDir) : null;
931
+ if (!want && hubUrl && io.http && io.http.fetchJson) {
932
+ // no bundled copy: the hub's published bundle version decides
933
+ try {
934
+ const meta = await io.http.fetchJson(`${hubUrl.replace(/\/$/, '')}/worker-bundle/sha256`);
935
+ if (meta && meta.status === 200 && meta.json && typeof meta.json.version === 'string') want = meta.json.version;
936
+ } catch (_) { /* hub unreachable — keep the installed bundle */ }
937
+ }
938
+ if (have && want && have !== want) {
939
+ bundleTargets = [{ id: `worker:${manifests[0].profile.id}`, worker_type: (manifests[0].worker_bundle || {}).worker_type }];
940
+ }
941
+ }
942
+ if (bundleTargets.length > 0) {
943
+ for (const w of bundleTargets) {
780
944
  const manifest = manifests.find((m) => `worker:${m.profile.id}` === w.id) || manifests[0];
781
945
  const bundleRes = await log.step(`install worker bundle (${w.worker_type})`, async () => {
782
946
  // The distributed installer package may not carry the
@@ -802,6 +966,8 @@ async function runInstallation(args) {
802
966
  return withBusySync('Installing worker bundle', () => worker.installWorkerBundle(io, {
803
967
  workerDir, manifest, repoRoot, bundleDir, hubUrl,
804
968
  httpFetchText: null, log,
969
+ update: decisions.apply_fixes !== false,
970
+ nodeBin,
805
971
  }));
806
972
  } finally {
807
973
  if (bundleTmp) {
@@ -836,6 +1002,7 @@ async function runInstallation(args) {
836
1002
  const workerWanted = decisions.worker_setup === true || decisions.worker_setup === 'yes'
837
1003
  || (keyStep && (keyStep.provided || decisions.worker_key_provided === true));
838
1004
  let tokenValue = null; // held in memory only; never stored on result/state
1005
+ let workerConfigChanged = false; // .env or bundle changed in THIS run → restart a running worker
839
1006
  if (workerWanted) {
840
1007
  const manifest = manifests[0];
841
1008
  const required = ((manifest.worker_bundle || {}).env || {}).required || [];
@@ -855,12 +1022,31 @@ async function runInstallation(args) {
855
1022
  values[key] = defaultEnvValue(key, { hubUrl, manifests });
856
1023
  }
857
1024
  }
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 }));
1025
+ // Installer-owned wiring: worker type from the PROFILE, the node
1026
+ // binary, the probed ComfyUI API base and port (shared hosts often
1027
+ // run several ComfyUI instances; the default 8188 may belong to a
1028
+ // different one). Written for missing keys always; existing values
1029
+ // are replaced only when the user accepted the fixes
1030
+ // (decisions.apply_fixes — one "Fix?" question in the CLI).
1031
+ const desired = desiredEnvWiring({ manifests, nodeBin, comfyUrl, comfyPort: options.comfyPort, hubUrl, hubUrlExplicit: !!options.hubUrlExplicit });
1032
+ Object.assign(values, desired);
1033
+ const secretOverrides = {};
1034
+ if (options.replaceWorkerKey && secretProvider) {
1035
+ const fresh = await secretProvider('ANIMASTOR_WORKER_TOKEN');
1036
+ if (fresh) {
1037
+ log.registerSecret(fresh);
1038
+ secretOverrides.ANIMASTOR_WORKER_TOKEN = fresh;
1039
+ tokenValue = fresh;
1040
+ }
1041
+ }
1042
+ const cfg = await log.step('configure worker .env', async () => worker.configureEnv(io, {
1043
+ workerDir, manifest, values,
1044
+ overrides: decisions.apply_fixes !== false ? desired : {},
1045
+ secretOverrides,
1046
+ log,
1047
+ }));
863
1048
  result.results.worker.push({ id: 'env', config: cfg.ok ? cfg.value : { status: 'failed', reason: String(cfg.error && cfg.error.message) } });
1049
+ if (cfg.ok && (cfg.value.created || (cfg.value.changed || []).length > 0 || (cfg.value.added || []).length > 0)) workerConfigChanged = true;
864
1050
  if (cfg.ok && st.components.worker) {
865
1051
  st.components.worker.env_created = cfg.value.created === true;
866
1052
  } else if (cfg.ok) {
@@ -873,49 +1059,8 @@ async function runInstallation(args) {
873
1059
  save();
874
1060
  }
875
1061
 
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 ---------------------------------------------------
1062
+ // 4.75 Management tools (before the worker start: the final summary names
1063
+ // the `animastor` command in its fix lines) ---------------------------------------------------
919
1064
  // Optional component (install decision install_management_tools). The
920
1065
  // tools are thin wrappers around this CLI's management commands — the
921
1066
  // runtime logic is shared (management.js), never duplicated. Installing
@@ -924,13 +1069,22 @@ async function runInstallation(args) {
924
1069
  // precisely. A tools failure must never fail the installation itself.
925
1070
  if (decisions.install_management_tools === true && toolsDir && !dryRun) {
926
1071
  try {
1072
+ // The bootstrap runs this CLI from a temp dir wiped on exit —
1073
+ // the tools must point at a PERSISTENT copy of the installer
1074
+ // (<base>/installer), refreshed on every run.
927
1075
  const r = await log.step('install management tools', async () => withBusySync('Installing management tools', () => management.installManagementTools(io, {
928
1076
  toolsDir,
929
- nodePath: process.execPath,
1077
+ nodePath: nodeBin,
930
1078
  cliPath: path.join(__dirname, '..', 'cli.js'),
1079
+ // engine/ → installer/ → src/ → package root (src/, ai/, package.json)
1080
+ installerSrcRoot: options.persistInstaller === false ? null : path.resolve(__dirname, '..', '..', '..'),
1081
+ installerDestRoot: path.join(path.dirname(toolsDir), 'installer'),
1082
+ linkDir: options.linkDir !== undefined ? options.linkDir : management.defaultLinkDir({ uid: currentUid, home }),
1083
+ home,
931
1084
  statePath,
932
1085
  root: comfyuiRoot,
933
1086
  workerDir,
1087
+ hubUrl,
934
1088
  log,
935
1089
  platformAdapter,
936
1090
  })));
@@ -942,7 +1096,26 @@ async function runInstallation(args) {
942
1096
  for (const f of r.value.files) {
943
1097
  state.addOwnedComponent(st, 'services', { id: 'management-tools', path: f });
944
1098
  }
1099
+ if (r.value.link) state.addOwnedComponent(st, 'services', { id: 'animastor-command', path: r.value.link });
1100
+ if (r.value.installerDir) state.addOwnedComponent(st, 'services', { id: 'installer-copy', path: r.value.installerDir });
1101
+ if (r.value.path_hint) result.warnings.push(r.value.path_hint);
945
1102
  state.setArtifact(st, 'management-tools', 'installed', { dir: r.value.toolsDir });
1103
+ // Autostart: ~/animastor/start-worker.sh becomes a thin
1104
+ // wrapper around `animastor start` (the old script is kept
1105
+ // as .bak). Installed next to the worker, re-applied on
1106
+ // every run so a reboot that wipes the file is repaired.
1107
+ const wrap = management.ensureStartWorkerWrapper(io, {
1108
+ workerDir,
1109
+ animastorPath: r.value.link || r.value.command || null,
1110
+ });
1111
+ result.results.start_worker_wrapper = wrap;
1112
+ if (wrap.status === 'replaced') {
1113
+ log.info(`autostart: start-worker.sh replaced by the animastor wrapper${wrap.backup ? ` (old script: ${wrap.backup})` : ''}`);
1114
+ } else if (wrap.status === 'created') {
1115
+ log.info(`autostart: start-worker.sh created → ${wrap.path}`);
1116
+ } else if (wrap.status === 'failed') {
1117
+ result.warnings.push(`autostart wrapper could not be written: ${wrap.reason}`);
1118
+ }
946
1119
  } else {
947
1120
  const reason = r.error && r.error.message ? r.error.message : 'unknown failure';
948
1121
  result.warnings.push(`management tools could not be installed: ${reason}`);
@@ -956,8 +1129,114 @@ async function runInstallation(args) {
956
1129
  }
957
1130
  }
958
1131
 
1132
+ // 4.8 Worker start (default in every mode; --no-start-worker opts out) ---
1133
+ // "done" ONLY after the worker itself logged "ComfyUI ready": a
1134
+ // spawned-but-stuck process is a FAILED step, never a silent pass.
1135
+ // A fatal runtime failure leaves the install unrecoverable — every
1136
+ // dependent step (including daemon starts) is SKIPPED.
1137
+ let startedWorkerPid = null;
1138
+ let workerReady = null;
1139
+ let workerStart = null;
1140
+ if (options.startWorker && workerDir && !runtimeFatal) {
1141
+ const r = await log.step('start worker', async () => {
1142
+ const bundleChanged = result.results.worker.some((x) => x.bundle && (x.bundle.files_installed || []).length > 0);
1143
+ const res = worker.startWorker(io, { workerDir, nodeBin, graceMs: options.workerGraceMs || 3000, forceRestart: workerConfigChanged || bundleChanged });
1144
+ workerStart = res;
1145
+ if (!res.started || !res.alive) {
1146
+ // An immediate exit is usually the fail-closed credential
1147
+ // gate — say so (the fix is a new key, not a re-run).
1148
+ if (res.logFile) {
1149
+ const scan = worker.scanWorkerLog(worker.readLogFrom(io, res.logFile, res.logOffset || 0));
1150
+ if (scan.auth_failed) {
1151
+ workerReady = { comfy_ready: false, heartbeat: false, auth_failed: true, reason: `the Worker Key was rejected (Worker authentication failed) — see ${res.logFile}` };
1152
+ throw new Error(workerReady.reason);
1153
+ }
1154
+ }
1155
+ throw new Error(res.reason || 'worker did not start');
1156
+ }
1157
+ if (res.already_running) log.info(`worker already running (pid ${res.pid}) — not spawning a second instance`);
1158
+ // The 90 s "worker → ComfyUI ready" window opens only once
1159
+ // ComfyUI itself answers (installer 0.2.3) — a ComfyUI that is
1160
+ // still loading must not eat the worker's time.
1161
+ const comfyUpUrl = comfyUrl || (foreignComfy && foreignComfy.url) || null;
1162
+ const ready = await withBusy('Waiting for the worker to reach ComfyUI', () => worker.waitForWorkerReady(io, {
1163
+ workerDir, pid: res.pid, logFile: res.logFile, logOffset: res.logOffset || 0,
1164
+ comfyUp: comfyUpUrl ? async () => !!(await comfyui.systemStats(io, comfyUpUrl)) : null,
1165
+ comfyUpTimeoutMs: options.comfyWaitMs || 0,
1166
+ comfyTimeoutMs: options.workerReadyTimeoutMs || 90000,
1167
+ pollMs: options.pollIntervalMs || 1000,
1168
+ requireHeartbeat: false,
1169
+ }));
1170
+ workerReady = ready;
1171
+ if (!ready.comfy_ready) throw new Error(ready.reason);
1172
+ return { ...res, ...ready };
1173
+ });
1174
+ const res = r.ok ? r.value : { ...(workerStart || {}), started: !!(workerStart && workerStart.started), alive: false, reason: String(r.error && r.error.message) };
1175
+ result.results.worker.push({ 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 });
1176
+ if (r.ok) {
1177
+ startedWorkerPid = res.pid;
1178
+ state.setArtifact(st, 'worker-process', 'installed', { pid: res.pid });
1179
+ } else {
1180
+ if (workerStart && workerStart.pid) startedWorkerPid = workerStart.pid;
1181
+ state.setArtifact(st, 'worker-process', 'failed', { reason: res.reason || null });
1182
+ }
1183
+ save();
1184
+ // Hub heartbeat (Animastor shows ONLINE) — only meaningful once the
1185
+ // worker reached ComfyUI (heartbeats start after that).
1186
+ if (r.ok) {
1187
+ const hb = await withBusy('Waiting for the hub to confirm the heartbeat', () => worker.waitForWorkerReady(io, {
1188
+ workerDir, pid: res.pid, logFile: res.logFile, logOffset: res.logOffset || 0,
1189
+ comfyTimeoutMs: 1000, heartbeatTimeoutMs: options.heartbeatTimeoutMs || 45000,
1190
+ pollMs: options.pollIntervalMs || 1000,
1191
+ }));
1192
+ workerReady = hb;
1193
+ }
1194
+ }
1195
+
1196
+ // 4.9 Verification --------------------------------------------------------------
1197
+ // A fatal runtime failure means ComfyUI cannot start — skip the live
1198
+ // start step entirely (it would only spawn a doomed process).
1199
+ const ver = await runVerification({
1200
+ io, manifests, roots: { comfyuiRoot, workerDir, hubUrl },
1201
+ options: { ...options, comfyUrl, startComfyui: runtimeFatal ? false : options.startComfyui },
1202
+ log, crypto,
1203
+ tokenValue,
1204
+ device,
1205
+ workerPid: startedWorkerPid,
1206
+ onEvent: (kind, value) => { result.results[kind] = value; },
1207
+ });
1208
+ result.verification = ver;
1209
+ // Record the instance this installer started so future runs reuse its
1210
+ // port instead of auto-picking a new one (the runVerification scope
1211
+ // has no state — the start step reports via the comfyui_started event).
1212
+ const startedEv = result.results.comfyui_started;
1213
+ if (startedEv && startedEv.port) {
1214
+ st.comfyui_runtime = { port: startedEv.port, pid: startedEv.pid, started_at: io.now() };
1215
+ save();
1216
+ }
1217
+
1218
+ // 4.11 End-to-end: ComfyUI API → worker "ComfyUI ready" → hub heartbeat.
1219
+ result.results.comfy_owner = {
1220
+ owner: comfyOwner ? comfyOwner.owner : null,
1221
+ mode,
1222
+ pid: comfyOwner ? comfyOwner.pid : null,
1223
+ url: comfyUrl,
1224
+ baseurl: comfyOwner ? comfyOwner.baseurl : null,
1225
+ };
1226
+ result.e2e = await endToEndChecks(io, {
1227
+ mode, comfyUrl, comfyPort, hubUrl,
1228
+ comfyTried: (result.results.comfy_url && result.results.comfy_url.tried) || (foreignComfy && foreignComfy.url ? [foreignComfy.url] : []),
1229
+ platformComfy: !!foreignComfy,
1230
+ workerWanted: !!(options.startWorker && workerDir && !runtimeFatal),
1231
+ workerStart, workerReady,
1232
+ tool: options.toolCommand || toolCommandFrom(result.results.management_tools),
1233
+ });
1234
+
959
1235
  if (runtimeFatal) {
960
1236
  result.status = 'failed';
1237
+ } else if (result.e2e.some((c) => c.ok === false)) {
1238
+ const blockedCount = result.blocked.length + result.results.models.filter((m) => m.status === 'blocked').length;
1239
+ result.status = blockedCount > 0 ? 'blocked' : 'failed';
961
1240
  } else {
962
1241
  const blockedCount = result.blocked.length + result.results.models.filter((m) => m.status === 'blocked').length;
963
1242
  if (result.blocked.length > 0 || blockedCount > 0) result.status = 'blocked';
@@ -989,6 +1268,104 @@ function findModelDep(manifests, id) {
989
1268
  return null;
990
1269
  }
991
1270
 
1271
+ /**
1272
+ * Installer-owned .env wiring for this run (non-secret): WORKER_TYPE from the
1273
+ * profile manifest (never a hard-coded default), NODE_BIN, COMFY_URL when a
1274
+ * probe proved it, COMFY_PORT, HUB_URL when the hub was given explicitly.
1275
+ */
1276
+ function desiredEnvWiring({ manifests, nodeBin = null, comfyUrl = null, comfyPort = null, hubUrl = null, hubUrlExplicit = false }) {
1277
+ const out = {};
1278
+ const type = (manifests[0] && manifests[0].worker_bundle && manifests[0].worker_bundle.worker_type) || null;
1279
+ if (type) out.WORKER_TYPE = type;
1280
+ if (nodeBin) out.NODE_BIN = nodeBin;
1281
+ if (comfyUrl) {
1282
+ out.COMFY_URL = comfyUrl;
1283
+ // NOTEBOOK_PATH follows the probe too (older workers ignore COMFY_URL
1284
+ // and build the URL from COMFY_PORT + NOTEBOOK_PATH): empty when the
1285
+ // plain URL answered, the prefix only when the probe needed it.
1286
+ const m = /^https?:\/\/[^/]+(\/.*)?$/.exec(comfyUrl);
1287
+ out.NOTEBOOK_PATH = m && m[1] ? m[1] : '';
1288
+ }
1289
+ if (comfyPort) out.COMFY_PORT = String(comfyPort);
1290
+ if (hubUrlExplicit && hubUrl) out.HUB_URL = hubUrl;
1291
+ return out;
1292
+ }
1293
+
1294
+ /**
1295
+ * End-to-end checks for type A when the platform's ComfyUI never came up:
1296
+ * one ✗ with the cause and the fix, the worker is not started at all.
1297
+ */
1298
+ function platformComfyMissingChecks({ reason, tool = 'animastor' }) {
1299
+ return [
1300
+ { id: 'comfyui', ok: false, label: 'ComfyUI API', detail: reason, fix: `run \`${tool} doctor\` after the platform's ComfyUI is up` },
1301
+ { 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 },
1302
+ { id: 'heartbeat', ok: null, label: 'Hub heartbeat (Online)', detail: 'not checked — worker not started', fix: null },
1303
+ ];
1304
+ }
1305
+
1306
+ /** The command users type for fixes: `animastor` when linked into PATH, else the absolute tool path. */
1307
+ function toolCommandFrom(tools) {
1308
+ if (tools && tools.command) return tools.command;
1309
+ return 'animastor';
1310
+ }
1311
+
1312
+ /**
1313
+ * The three end-to-end checks the installer result is judged by. Each ✗
1314
+ * carries ONE line of cause and ONE exact fix command — the final summary
1315
+ * prints exactly these (no "scroll up").
1316
+ * @returns {Promise<Array<{ id, ok: boolean|null, label, detail, fix }>>}
1317
+ */
1318
+ async function endToEndChecks(io, { mode, comfyUrl, comfyPort, hubUrl, workerWanted, workerStart, workerReady, tool = 'animastor', comfyTried = [], platformComfy = false }) {
1319
+ const checks = [];
1320
+ const stats = comfyUrl ? await comfyui.systemStats(io, comfyUrl) : null;
1321
+ // Addresses in the result are always FULL (with the notebook prefix):
1322
+ // every URL that was really tried, not a bare host:port.
1323
+ const tried = (comfyTried || []).filter(Boolean);
1324
+ const where = comfyUrl || (tried.length > 0 ? tried.join(', ') : `http://127.0.0.1:${comfyPort || 8188}`);
1325
+ const prefixed = tried.find((u) => /^https?:\/\/[^/]+\/./.test(u)) || null;
1326
+ checks.push(stats
1327
+ ? { id: 'comfyui', ok: true, label: 'ComfyUI API', detail: comfyUrl, fix: null }
1328
+ : {
1329
+ id: 'comfyui', ok: false, label: 'ComfyUI API',
1330
+ detail: `not reachable at ${where} (GET /system_stats)`,
1331
+ fix: mode === 'managed'
1332
+ ? `${tool} start`
1333
+ : platformComfy
1334
+ ? `ComfyUI is started by the platform — when ${comfyUrl || prefixed || where} answers, run: ${tool} doctor`
1335
+ : prefixed
1336
+ ? `start your ComfyUI so that ${prefixed} answers, then run: ${tool} doctor`
1337
+ : `start your ComfyUI on port ${comfyPort || 8188}, then run: ${tool} doctor`,
1338
+ });
1339
+ if (!workerWanted) {
1340
+ checks.push({ id: 'worker', ok: null, label: 'Worker → ComfyUI', detail: 'worker start skipped (--no-start-worker)', fix: `${tool} start` });
1341
+ checks.push({ id: 'heartbeat', ok: null, label: 'Hub heartbeat (Online)', detail: 'not checked — worker not started', fix: `${tool} start` });
1342
+ return checks;
1343
+ }
1344
+ const newKeyFix = `create a new Worker Key in Animastor → Settings → Workers, then run: ${tool} doctor --new-key`;
1345
+ const r = workerReady || {};
1346
+ if (r.comfy_ready) {
1347
+ checks.push({ id: 'worker', ok: true, label: 'Worker → ComfyUI', detail: '"ComfyUI ready" in the worker log', fix: null });
1348
+ } else {
1349
+ const reason = (r.reason || (workerStart && workerStart.reason) || 'worker did not start').replace(/\s+/g, ' ');
1350
+ checks.push({
1351
+ id: 'worker', ok: false, label: 'Worker → ComfyUI', detail: reason,
1352
+ fix: r.auth_failed ? newKeyFix : `${tool} doctor`,
1353
+ });
1354
+ }
1355
+ if (r.heartbeat) {
1356
+ checks.push({ id: 'heartbeat', ok: true, label: 'Hub heartbeat (Online)', detail: hubUrl || null, fix: null });
1357
+ } else if (!r.comfy_ready) {
1358
+ 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 : `${tool} doctor` });
1359
+ } else {
1360
+ checks.push({
1361
+ id: 'heartbeat', ok: false, label: 'Hub heartbeat (Online)',
1362
+ detail: (r.reason || 'no heartbeat confirmed').replace(/\s+/g, ' '),
1363
+ fix: r.auth_failed ? newKeyFix : `check that this machine reaches ${hubUrl} (curl -fsS ${hubUrl}/health), then run: ${tool} doctor`,
1364
+ });
1365
+ }
1366
+ return checks;
1367
+ }
1368
+
992
1369
  function defaultEnvValue(key, { hubUrl, manifests }) {
993
1370
  if (key === 'HUB_URL') return hubUrl || 'https://animastor.org/gpu';
994
1371
  if (key === 'WORKER_TYPE') return (manifests[0].worker_bundle || {}).worker_type || 'image';
@@ -1008,7 +1385,7 @@ async function runVerification({ io, manifests, roots, options, log, crypto, tok
1008
1385
  // ComfyUI live check: use an already-running instance, or start one in
1009
1386
  // managed mode (files on disk are NOT sufficient verification).
1010
1387
  const port = options.comfyPort || 8188;
1011
- const baseUrl = `http://127.0.0.1:${port}`;
1388
+ const baseUrl = options.comfyUrl || `http://127.0.0.1:${port}`;
1012
1389
  const withBusy = (label, fn, o) => (options.term ? options.term.withBusy(label, fn, o) : fn());
1013
1390
  let stats = await comfyui.systemStats(io, baseUrl);
1014
1391
  if (!stats && options.startComfyui && io.fs.existsSync(comfyuiRoot)) {
@@ -1034,7 +1411,21 @@ async function runVerification({ io, manifests, roots, options, log, crypto, tok
1034
1411
  for (const cls of dep.provides_classes || []) manifestClasses.add(cls);
1035
1412
  }
1036
1413
  }
1037
- const missingClasses = Array.from(manifestClasses).filter((c) => !classes.has(c));
1414
+ let missingClasses = Array.from(manifestClasses).filter((c) => !classes.has(c));
1415
+ // Installer 0.2.4: right after the node dependencies were
1416
+ // installed or when the ComfyUI is a new process, the classes are
1417
+ // re-checked until the end of the wait window — not FAILED at once.
1418
+ const deadline = Number(options.nodeClassesDeadline) || 0;
1419
+ const pause = options.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
1420
+ if (missingClasses.length > 0 && deadline > io.now()) {
1421
+ log.info(`node classes not registered yet (${missingClasses.join(', ')}) — re-checking for up to ${Math.round((deadline - io.now()) / 1000)} s`);
1422
+ while (missingClasses.length > 0 && io.now() < deadline) {
1423
+ await pause(Math.min(options.pollIntervalMs || 3000, Math.max(1, deadline - io.now())));
1424
+ const again = await comfyui.objectInfoClasses(io, baseUrl);
1425
+ if (again) missingClasses = Array.from(manifestClasses).filter((c) => !again.has(c));
1426
+ }
1427
+ if (missingClasses.length === 0) log.info('node classes registered');
1428
+ }
1038
1429
  if (missingClasses.length > 0) live.comfyui.missing_node_classes = missingClasses;
1039
1430
  }
1040
1431
  // workflow static validation (no generation) — only meaningful when
@@ -1176,5 +1567,8 @@ module.exports = {
1176
1567
  createInterruptGuard,
1177
1568
  comfyPortState,
1178
1569
  autoPickComfyPort,
1570
+ platformComfyMissingChecks,
1571
+ desiredEnvWiring,
1572
+ endToEndChecks,
1179
1573
  CPU_MODE_WARNING,
1180
1574
  };