-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauto_setup.py
More file actions
1405 lines (1232 loc) · 54.6 KB
/
Copy pathauto_setup.py
File metadata and controls
1405 lines (1232 loc) · 54.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Auto-setup: install missing custom nodes + download missing models for a workflow.
Resolution sources:
- Custom nodes: ``api.comfy.org/nodes/<cnr_id>`` first (using ``cnr_id`` + ``ver``
carried on each node's ``properties``), then ComfyUI Manager's
``custom-node-list.json`` as a fuzzy fallback by class_type.
- Models: the URL already carried on the workflow's ``properties.models`` (the
resolver in ``nodes.py`` populates this), with Manager's ``model-list.json``
as a filename-keyed fallback.
Cross-platform: Python tooling is always invoked as ``sys.executable -m pip``
/ ``sys.executable install.py`` (never a bare ``pip``/``python``, which aren't
on PATH for ComfyUI Desktop / uv-managed / portable installs). ``git`` is
located via :func:`_resolve_git` (PATH + common per-OS install dirs); when it's
genuinely absent we fall back to downloading a GitHub source tarball.
"""
from __future__ import annotations
import asyncio
import functools
import hashlib
import io
import logging
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import urllib.error
import urllib.request
import uuid
from pathlib import Path
from typing import Any, Awaitable, Callable, Iterable
import aiohttp
import folder_paths
from .nodes import RunflowDeploy, _iter_all_nodes, resolve_workflow_models
logger = logging.getLogger(__name__)
REGISTRY_NODE_URL = "https://api.comfy.org/nodes/{cnr_id}"
REGISTRY_COMFY_NODE_URL = "https://api.comfy.org/comfy-nodes/{class_type}/node"
MANAGER_CUSTOM_NODES_URL = (
"https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/custom-node-list.json"
)
MANAGER_MODELS_URL = (
"https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/model-list.json"
)
MANAGER_EXT_NODE_MAP_URL = (
"https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/extension-node-map.json"
)
HUGGINGFACE_SEARCH_URL = "https://huggingface.co/api/models"
HUGGINGFACE_TREE_URL = "https://huggingface.co/api/models/{repo}/tree/main"
def _comfy_core_class_types() -> set[str]:
"""Class types that come from ComfyUI itself (and any already-installed
custom nodes). Anything in this set is already runnable on this install.
"""
try:
import nodes as comfy_nodes # ComfyUI's own module
return set(comfy_nodes.NODE_CLASS_MAPPINGS.keys())
except Exception:
return set()
# Stock frontend/editor pseudo-nodes that have no Python class in
# NODE_CLASS_MAPPINGS — they're rendered by the editor and rewired by the
# executor at run time. Without this set the resolver treats them as missing
# custom nodes and dumps them into ``unresolved``.
_STOCK_FRONTEND_NODES: frozenset[str] = frozenset(
{
"Reroute",
"PrimitiveNode",
"Note",
"MarkdownNote",
}
)
# Module-top-level `from comfy_env import ... install ...` is the contract
# opt-in for nodes that delegate their setup to the `comfy_env` package
# (Pozzetti 3D-pipeline family: SAM3DObjects, GeometryPack, MoGe2, TRELLIS2,
# HYPano2, Pixal3D, Hunyuan3D-Part, plus the comfyui-sharp pack). Matching
# on the import (not on install.py existence alone) keeps us from running
# legacy install.py scripts that do arbitrary work in nodes that happen to
# ship one for unrelated reasons.
#
# Mirrors the deploy worker's identical guard at
# `bg-brain/workers/comfyui-deploy-worker/installer.py:_is_comfy_env_install`.
_COMFY_ENV_INSTALL_RE = re.compile(
r"^\s*from\s+comfy_env\s+import\b[^\n#]*\binstall\b",
re.MULTILINE,
)
def _is_comfy_env_install(install_py: Path) -> bool:
"""True iff ``install.py`` exists in the cloned node directory and its source
imports ``install`` from ``comfy_env`` at module top level. Read errors → False."""
if not install_py.is_file():
return False
try:
text = install_py.read_text(encoding="utf-8", errors="replace")
except OSError:
return False
return _COMFY_ENV_INSTALL_RE.search(text) is not None
def _aux_id_to_origin(aux_id: str) -> str | None:
"""Convert a ComfyUI Manager-style ``aux_id`` to an HTTPS clone origin.
`properties.aux_id` is what ComfyUI's frontend stamps onto nodes installed
via Manager's git-URL flow (vs. Comfy Registry / cnr_id). Most often it's
a plain ``"owner/repo"`` string, occasionally a full ``https://github.com/...``
URL. Returns ``None`` for unrecognized shapes so the caller can fall through
to the next resolution path.
"""
s = aux_id.strip()
if not s:
return None
if s.startswith(("http://", "https://")):
return s.rstrip("/")
# Plain `owner/repo` — be strict (exactly one slash, no shell metacharacters)
# so we don't build a malformed URL from corrupted properties.
if s.count("/") == 1 and all(c not in s for c in " \t?#&"):
owner, repo = s.split("/")
if owner and repo:
return f"https://github.com/{owner}/{repo}"
return None
# ---------------------------------------------------------------------------
# Registry client (session-scoped, in-memory)
# ---------------------------------------------------------------------------
class RegistryClient:
"""Looks up custom-node provenance and model URLs from public registries.
All caches are per-instance — callers re-use a single client for the
duration of a setup job so the two checkboxes don't re-fetch the same
JSON twice.
"""
def __init__(self) -> None:
self._node_cache: dict[str, dict | None] = {}
self._class_type_cache: dict[str, dict | None] = {}
self._manager_nodes: list[dict] | None = None
self._manager_models: list[dict] | None = None
self._ext_node_map: dict[str, list[str]] | None = None
self._hf_cache: dict[str, dict | None] = {}
self._lock = asyncio.Lock()
async def _get_json(self, session: aiohttp.ClientSession, url: str) -> Any:
async with session.get(url, timeout=aiohttp.ClientTimeout(total=20)) as resp:
resp.raise_for_status()
return await resp.json(content_type=None)
async def resolve_by_cnr_id(self, cnr_id: str) -> dict | None:
"""Return the Comfy registry record for ``cnr_id``, or None on miss/error.
The shape of interest is ``{"repository": "https://github.com/..."}``.
"""
if not cnr_id or cnr_id == "comfy-core":
return None
if cnr_id in self._node_cache:
return self._node_cache[cnr_id]
try:
async with aiohttp.ClientSession() as session:
data = await self._get_json(session, REGISTRY_NODE_URL.format(cnr_id=cnr_id))
except Exception as err:
logger.info("comfy registry lookup failed for %s: %s", cnr_id, err)
self._node_cache[cnr_id] = None
return None
self._node_cache[cnr_id] = data if isinstance(data, dict) else None
return self._node_cache[cnr_id]
async def _load_manager_nodes(self) -> list[dict]:
async with self._lock:
if self._manager_nodes is not None:
return self._manager_nodes
try:
async with aiohttp.ClientSession() as session:
data = await self._get_json(session, MANAGER_CUSTOM_NODES_URL)
self._manager_nodes = data.get("custom_nodes") or []
except Exception as err:
logger.info("manager custom-node-list fetch failed: %s", err)
self._manager_nodes = []
return self._manager_nodes
async def _load_ext_node_map(self) -> dict[str, list[str]]:
async with self._lock:
if self._ext_node_map is not None:
return self._ext_node_map
try:
async with aiohttp.ClientSession() as session:
data = await self._get_json(session, MANAGER_EXT_NODE_MAP_URL)
# Shape: {repo_url: [[class_type, ...], {...metadata...}]}
norm: dict[str, list[str]] = {}
for repo_url, value in (data or {}).items():
if isinstance(value, list) and value and isinstance(value[0], list):
norm[repo_url] = [str(x) for x in value[0]]
self._ext_node_map = norm
except Exception as err:
logger.info("manager extension-node-map fetch failed: %s", err)
self._ext_node_map = {}
return self._ext_node_map
async def resolve_by_class_type_registry(self, class_type: str) -> dict | None:
"""Reverse-lookup a class_type against the Comfy registry.
Endpoint: ``api.comfy.org/comfy-nodes/<class_type>/node`` returns the
canonical custom-node record for whichever node provides this class.
Built-in ComfyUI types 404 here — that's also the right signal: callers
check ``loaded_class_types`` first, so reaching this path for a built-in
means it wasn't loaded, and "not in registry" is a useful answer.
"""
if not class_type:
return None
if class_type in self._class_type_cache:
return self._class_type_cache[class_type]
try:
async with aiohttp.ClientSession() as session:
async with session.get(
REGISTRY_COMFY_NODE_URL.format(class_type=class_type),
timeout=aiohttp.ClientTimeout(total=15),
) as resp:
if resp.status == 404:
self._class_type_cache[class_type] = None
return None
resp.raise_for_status()
data = await resp.json(content_type=None)
except Exception as err:
logger.info("comfy registry class-type lookup failed for %s: %s", class_type, err)
self._class_type_cache[class_type] = None
return None
if not isinstance(data, dict) or not data.get("repository"):
self._class_type_cache[class_type] = None
return None
self._class_type_cache[class_type] = data
return data
@staticmethod
def _camel_split(s: str) -> list[str]:
"""Split a CamelCase class name into lowercase tokens.
Keeps runs of uppercase letters together (acronyms): ``UnetLoaderGGUF``
→ ``["unet", "loader", "gguf"]``, ``XMLHttpRequest`` →
``["xml", "http", "request"]``.
"""
import re
# Insert a boundary between lower→upper and between upper-run→upper+lower
s = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", s)
s = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1 \2", s)
return [t.lower() for t in re.split(r"[^A-Za-z0-9]+", s) if t]
_BOILERPLATE_TOKENS = frozenset({
"loader", "encoder", "decoder", "advanced", "simple", "load", "save",
"node", "nodes", "model", "models", "comfyui", "comfy",
})
async def resolve_by_class_type_manager(self, class_type: str) -> dict | None:
"""Fallback: find a Manager extension-node-map entry providing ``class_type``.
Multiple repos can declare the same class (forks, re-exports). Rank
candidates by:
1. How many class-type tokens (CamelCase split, minus generic words)
appear in the repo name. ``UnetLoaderGGUF`` → ["unet","gguf"], so
``ComfyUI-GGUF`` scores higher than ``ComfyUI-Zlycoris``.
2. Fewer total class types in the entry = more focused = more likely
the canonical source rather than an aggregator/fork.
3. Lexicographic repo URL for stability.
"""
if not class_type:
return None
ext_map = await self._load_ext_node_map()
matches: list[tuple[str, int]] = [
(repo_url, len(class_types))
for repo_url, class_types in ext_map.items()
if class_type in class_types
]
if not matches:
return None
tokens = [t for t in self._camel_split(class_type) if t not in self._BOILERPLATE_TOKENS]
def _score(item: tuple[str, int]) -> tuple[int, int, str]:
repo_url, class_count = item
repo_name = repo_url.rsplit("/", 1)[-1].lower()
name_matches = sum(1 for tok in tokens if tok in repo_name)
# Lower score wins; negate name_matches so more matches sort first.
return (-name_matches, class_count, repo_url)
matches.sort(key=_score)
return {"repository": matches[0][0]}
async def resolve_by_class_type(self, class_type: str) -> dict | None:
"""Resolve a class_type to ``{"repository": "..."}``.
Tries the comfy registry's reverse-lookup first (canonical), then
Manager's extension-node-map with smart ranking as a fallback.
"""
if not class_type:
return None
record = await self.resolve_by_class_type_registry(class_type)
if record and record.get("repository"):
return record
return await self.resolve_by_class_type_manager(class_type)
async def _load_manager_models(self) -> list[dict]:
async with self._lock:
if self._manager_models is not None:
return self._manager_models
try:
async with aiohttp.ClientSession() as session:
data = await self._get_json(session, MANAGER_MODELS_URL)
self._manager_models = data.get("models") or []
except Exception as err:
logger.info("manager model-list fetch failed: %s", err)
self._manager_models = []
return self._manager_models
async def resolve_model_by_filename(self, filename: str) -> dict | None:
"""Find a Manager model entry matching ``filename`` (basename match).
Returns ``{"url": "...", "save_path": "...", "filename": "..."}`` or None.
"""
if not filename:
return None
models = await self._load_manager_models()
for entry in models:
if entry.get("filename") == filename:
return entry
return None
async def resolve_by_huggingface_search(self, filename: str) -> dict | None:
"""Find a Hugging Face repo containing a file with exact basename ``filename``.
Strategy: search the HF Models API (with and without the extension —
relevance is usually better without), walk the top candidates, fetch
each candidate's recursive file tree (lighter than the full model
record), and return the URL of the first sibling whose basename
matches. ``main`` branch is assumed; HF refers to the default branch
by name in resolve URLs.
Returns ``{"url", "repo", "path"}`` or None. No auth — gated repos
will return 401/403 and we fall through. Results cached per filename
for the duration of the registry client's lifetime.
"""
if not filename:
return None
if filename in self._hf_cache:
return self._hf_cache[filename]
base = filename
for ext in _MODEL_EXTENSIONS:
if base.lower().endswith(ext):
base = base[: -len(ext)]
break
queries: list[str] = []
if base:
queries.append(base)
if filename and filename not in queries:
queries.append(filename)
seen_repos: set[str] = set()
timeout = aiohttp.ClientTimeout(total=15)
try:
async with aiohttp.ClientSession(timeout=timeout) as session:
for query in queries:
try:
async with session.get(
HUGGINGFACE_SEARCH_URL,
params={"search": query, "limit": 15},
) as resp:
if resp.status != 200:
continue
results = await resp.json(content_type=None)
except Exception:
continue
if not isinstance(results, list):
continue
for repo_data in results:
model_id = repo_data.get("modelId") or repo_data.get("id")
if not model_id or model_id in seen_repos:
continue
seen_repos.add(model_id)
try:
async with session.get(
HUGGINGFACE_TREE_URL.format(repo=model_id),
params={"recursive": "true"},
) as r:
if r.status != 200:
continue
tree = await r.json(content_type=None)
except Exception:
continue
if not isinstance(tree, list):
continue
for item in tree:
if not isinstance(item, dict) or item.get("type") != "file":
continue
path = item.get("path") or ""
if os.path.basename(path) == filename:
url = f"https://huggingface.co/{model_id}/resolve/main/{path}"
result = {"url": url, "repo": model_id, "path": path}
self._hf_cache[filename] = result
return result
except Exception as err:
logger.info("HF search failed for %s: %s", filename, err)
self._hf_cache[filename] = None
return None
# ---------------------------------------------------------------------------
# Plan: diff workflow requirements against what's locally installed
# ---------------------------------------------------------------------------
def _normalize_origin(url: str | None) -> str:
"""Normalize a git origin URL for equality comparison.
Strips ``.git`` and trailing slash, lowercases the host, drops scheme
differences (https/git+https/ssh) by reducing to ``host/path``.
"""
if not url:
return ""
s = url.strip().lower()
if s.startswith("git+"):
s = s[4:]
if s.startswith("git@"):
# git@github.com:owner/repo.git -> github.com/owner/repo.git
s = s.replace(":", "/", 1)[4:]
for scheme in ("https://", "http://", "ssh://"):
if s.startswith(scheme):
s = s[len(scheme):]
if s.endswith(".git"):
s = s[:-4]
return s.rstrip("/")
def _repo_name_from_origin(origin: str) -> str:
"""``https://github.com/owner/foo`` -> ``foo``."""
norm = _normalize_origin(origin)
if not norm:
return ""
return norm.rsplit("/", 1)[-1]
_NON_MODEL_FOLDER_TYPES = frozenset({
"input", "output", "temp", "user", "custom_nodes", "configs",
})
_MODEL_EXTENSIONS = (
".safetensors", ".sft", ".ckpt", ".pt", ".pth", ".bin",
".gguf", ".onnx", ".pb", ".engine",
)
def _detect_missing_widget_models(graph: dict) -> list[dict]:
"""Find widget values that look like model filenames but aren't installed
in any model folder.
Mirrors ComfyUI's own "missing model" detection. ComfyUI flags a COMBO
widget red when its current value isn't in the option list — and for
model-name widgets that option list comes from ``folder_paths``. We
reproduce that signal here:
1. Enumerate every file in every model folder_type into a set (both
relative path and basename, since dropdowns can carry either shape).
2. For each widget value in every node, if it has a model-ish extension
and doesn't appear in that set, flag it.
Returns ``[{"value": ..., "filename": ..., "node_type": ...}, ...]``.
The caller resolves the URL + save_path via Manager's model-list.
"""
installed: set[str] = set()
for ft in folder_paths.folder_names_and_paths:
if ft in _NON_MODEL_FOLDER_TYPES:
continue
try:
files = folder_paths.get_filename_list(ft) or []
except Exception:
continue
for f in files:
installed.add(f)
installed.add(os.path.basename(f))
seen: set[str] = set()
out: list[dict] = []
for node in _iter_all_nodes(graph or {}):
widgets_values = node.get("widgets_values")
if not isinstance(widgets_values, list):
continue
for value in widgets_values:
if not isinstance(value, str) or not value:
continue
if not value.lower().endswith(_MODEL_EXTENSIONS):
continue
if value in installed or os.path.basename(value) in installed:
continue
if value in seen:
continue
seen.add(value)
out.append({
"value": value,
"filename": os.path.basename(value),
"node_type": node.get("type") or "",
"node": node,
})
return out
def _url_to_filename(url: str) -> str | None:
"""Best-effort filename extraction from a download URL."""
if not url:
return None
# Strip query string, take the last path segment.
base = url.split("?", 1)[0].split("#", 1)[0].rstrip("/")
if not base:
return None
name = base.rsplit("/", 1)[-1]
return name or None
# Last-ditch fallback: when INPUT_TYPES introspection can't reveal a node's
# model folder_type (empty option lists on a fresh install, custom loaders
# without standard schemas), fall back to this map. Covers ~all common
# built-in + popular custom loaders.
_LOADER_FOLDER_HINTS: dict[str, str] = {
"VAELoader": "vae",
"CheckpointLoaderSimple": "checkpoints",
"CheckpointLoader": "checkpoints",
"unCLIPCheckpointLoader": "checkpoints",
"LoraLoader": "loras",
"LoraLoaderModelOnly": "loras",
"ControlNetLoader": "controlnet",
"ControlNetLoaderAdvanced": "controlnet",
"DiffControlNetLoader": "controlnet",
"UNETLoader": "unet",
"UnetLoaderGGUF": "unet",
"UnetLoaderGGUFAdvanced": "unet",
"CLIPLoader": "clip",
"CLIPLoaderGGUF": "clip",
"DualCLIPLoader": "clip",
"DualCLIPLoaderGGUF": "clip",
"TripleCLIPLoader": "clip",
"QuadrupleCLIPLoaderGGUF": "clip",
"CLIPVisionLoader": "clip_vision",
"UpscaleModelLoader": "upscale_models",
"StyleModelLoader": "style_models",
"GLIGENLoader": "gligen",
"HypernetworkLoader": "hypernetworks",
"DiffusersLoader": "diffusers",
"PhotoMakerLoader": "photomaker",
"IPAdapterModelLoader": "ipadapter",
}
def _guess_folder_type_for_node(node: dict) -> str | None:
"""Identify the model folder_type a node loads from.
Tries INPUT_TYPES introspection first — finds the first COMBO input whose
option list equals a model folder's file list. If introspection fails or
the option list is empty (fresh install with no files yet), falls back to
the explicit ``_LOADER_FOLDER_HINTS`` map keyed by class_type.
"""
class_type = node.get("type") or ""
try:
import nodes as comfy_nodes
except Exception:
comfy_nodes = None # type: ignore
if comfy_nodes is not None:
cls = comfy_nodes.NODE_CLASS_MAPPINGS.get(class_type)
if cls is not None:
try:
input_types = cls.INPUT_TYPES()
except Exception:
input_types = None
if isinstance(input_types, dict):
folder_sets: dict[str, frozenset[str]] = {}
for ft in folder_paths.folder_names_and_paths:
if ft in _NON_MODEL_FOLDER_TYPES:
continue
try:
folder_sets[ft] = frozenset(folder_paths.get_filename_list(ft) or [])
except Exception:
continue
for section in ("required", "optional"):
for input_spec in (input_types.get(section) or {}).values():
if not isinstance(input_spec, (list, tuple)) or not input_spec:
continue
first = input_spec[0]
if not isinstance(first, list) or not first:
continue
opt_set = frozenset(first)
for ft, files in folder_sets.items():
if files and opt_set == files:
return ft
return _LOADER_FOLDER_HINTS.get(class_type)
async def plan_setup(graph: dict) -> dict:
"""Compute the diff between what the workflow needs and what's installed.
Returns ``{"missing_models": [...], "missing_custom_nodes": [...], "unresolved": [...]}``.
Each missing_model is ``{rel_path, filename, url, sha256?, total_bytes?}``.
Each missing_custom_node is ``{name, origin, commit?, source}``.
Unresolved entries are class_types / filenames we couldn't map to a source.
"""
registry = RegistryClient()
loaded_class_types = _comfy_core_class_types()
# ---- Custom nodes ------------------------------------------------------
missing_nodes: dict[str, dict] = {} # keyed by normalized origin to dedupe
unresolved: list[dict] = []
seen_class_types: set[str] = set()
for node in _iter_all_nodes(graph or {}):
class_type = node.get("type") or ""
if class_type in seen_class_types:
continue
seen_class_types.add(class_type)
props = node.get("properties") or {}
cnr_id = props.get("cnr_id")
aux_id = props.get("aux_id")
ver = props.get("ver")
# Already runnable in this install? Skip.
if class_type in loaded_class_types:
continue
if cnr_id == "comfy-core":
continue
# Stock frontend pseudo-nodes (Reroute, Note, etc.) have no Python
# class registered, so the loaded-class check above doesn't catch
# them. Treat them as already-runnable so they don't surface as
# unresolved custom nodes.
if class_type in _STOCK_FRONTEND_NODES:
continue
origin: str | None = None
commit: str | None = None
source = ""
name = ""
if cnr_id:
record = await registry.resolve_by_cnr_id(cnr_id)
if record and record.get("repository"):
origin = record["repository"]
commit = ver or None
source = "comfy_registry"
name = cnr_id
# `aux_id` carries the canonical `owner/repo` for nodes installed via
# Manager's git-URL flow. Try it before the class-type fallback because
# `ver` gives us an exact commit pin — the Manager list path can't.
# Real-world hit: personal-account packs (PozzettiAndrea/* family) that
# aren't in the Comfy Registry and aren't in Manager's curated list.
if not origin and isinstance(aux_id, str):
aux_origin = _aux_id_to_origin(aux_id)
if aux_origin:
origin = aux_origin
commit = ver or None
source = "aux_id"
name = _repo_name_from_origin(origin)
if not origin and class_type:
record = await registry.resolve_by_class_type(class_type)
if record and record.get("repository"):
origin = record["repository"]
source = "manager"
name = _repo_name_from_origin(origin)
if not origin:
if class_type:
unresolved.append({"kind": "custom_node", "class_type": class_type})
continue
# NOTE: no "directory exists locally → skip" guard here. The functional
# signal of "this node already works" is class_type ∈ loaded_class_types,
# which we already check above. If we got past that, the class didn't
# register — re-clone is the right action, even if the directory exists.
# install_custom_node_sync rmtree's the target before moving the fresh
# clone in, so re-install is safe.
norm = _normalize_origin(origin)
if norm in missing_nodes:
# Prefer the entry with a commit pin if a later node carries one.
if commit and not missing_nodes[norm].get("commit"):
missing_nodes[norm]["commit"] = commit
continue
missing_nodes[norm] = {
"name": name or _repo_name_from_origin(origin),
"origin": origin,
"commit": commit,
"source": source,
}
logger.info(
"Runflow auto-setup: planning install of %s (commit=%s, source=%s, class_type=%s)",
origin, (commit or "HEAD"), source, class_type,
)
# ---- Models ------------------------------------------------------------
models = resolve_workflow_models(graph or {})
missing_models: list[dict] = []
models_root = Path(folder_paths.models_dir)
planned_filenames: set[str] = set()
for rel_path, info in models.items():
target = (models_root / rel_path).resolve()
try:
target.relative_to(models_root.resolve())
except ValueError:
continue
if target.is_file():
continue
url = info.get("url")
filename = Path(rel_path).name
if not url:
entry = await registry.resolve_model_by_filename(filename)
if entry and entry.get("url"):
url = entry["url"]
if not url:
unresolved.append({"kind": "model", "rel_path": rel_path, "filename": filename})
continue
missing_models.append({
"rel_path": rel_path,
"filename": filename,
"url": url,
"sha256": info.get("sha256"),
})
planned_filenames.add(filename)
# Second pass: widget values that look like model filenames but aren't
# installed and weren't covered above. resolve_workflow_models() silently
# skips widget values for which it can find neither a local file nor a
# URL in the same node's properties.models — the case ComfyUI itself flags
# as "Missing Models" with the red node outline. We pick those up here
# and look up the URL + save_path via two registries:
#
# 1. Manager's model-list — curated, carries an explicit save_path.
# 2. Hugging Face search — long-tail fallback, no curated save_path so
# we infer it from the node's INPUT_TYPES / a small hint map.
#
# _detect_missing_widget_models() carries the originating node dict so
# the folder_type can be inferred per-node without re-walking the graph.
for entry in _detect_missing_widget_models(graph or {}):
filename = entry["filename"]
if filename in planned_filenames:
continue
url: str | None = None
save_path = ""
source = ""
manager_entry = await registry.resolve_model_by_filename(filename)
if manager_entry and manager_entry.get("url"):
url = manager_entry["url"]
save_path = (manager_entry.get("save_path") or "").strip("/")
source = "manager"
else:
hf_entry = await registry.resolve_by_huggingface_search(filename)
if hf_entry and hf_entry.get("url"):
url = hf_entry["url"]
# No save_path from HF — infer from the node that referenced it.
save_path = (_guess_folder_type_for_node(entry["node"]) or "").strip("/")
source = "huggingface"
if not url:
unresolved.append({
"kind": "model",
"filename": filename,
"value": entry["value"],
})
continue
# If the widget value carries a subdir (``loras/foo/x.safetensors``),
# honor it — that's where ComfyUI is looking. Otherwise compose from
# the inferred save_path.
if "/" in entry["value"] or "\\" in entry["value"]:
rel_path = entry["value"].replace("\\", "/")
else:
rel_path = f"{save_path}/{filename}" if save_path else filename
missing_models.append({
"rel_path": rel_path,
"filename": filename,
"url": url,
"sha256": None,
"source": source,
})
planned_filenames.add(filename)
return {
"missing_models": missing_models,
"missing_custom_nodes": list(missing_nodes.values()),
"unresolved": unresolved,
}
# ---------------------------------------------------------------------------
# Workers: download models, install custom nodes
# ---------------------------------------------------------------------------
class CancelledByUser(Exception):
"""Raised from inside a worker when the job's cancel flag is set."""
ProgressCb = Callable[[dict], Awaitable[None]]
async def download_model(
url: str,
target_path: Path,
expected_sha256: str | None,
progress_cb: ProgressCb,
is_cancelled: Callable[[], bool],
) -> None:
"""Stream-download ``url`` into ``target_path`` with sha256 verification.
Writes to ``<target>.part`` and atomically renames on success. Verifies
sha256 if provided; mismatched files are deleted before raising.
"""
target_path.parent.mkdir(parents=True, exist_ok=True)
part_path = target_path.with_name(target_path.name + ".part")
timeout = aiohttp.ClientTimeout(total=None, sock_read=60, sock_connect=30)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(url, allow_redirects=True) as resp:
resp.raise_for_status()
total_header = resp.headers.get("Content-Length")
total_bytes = int(total_header) if total_header and total_header.isdigit() else 0
downloaded = 0
hasher = hashlib.sha256() if expected_sha256 else None
last_emit = 0
with open(part_path, "wb") as f:
async for chunk in resp.content.iter_chunked(1024 * 1024):
if is_cancelled():
raise CancelledByUser()
f.write(chunk)
if hasher is not None:
hasher.update(chunk)
downloaded += len(chunk)
# Throttle progress events to ~10/s worth of bytes
if downloaded - last_emit >= 256 * 1024:
await progress_cb({
"type": "model_progress",
"bytes": downloaded,
"total_bytes": total_bytes,
})
last_emit = downloaded
if hasher is not None and expected_sha256:
actual = hasher.hexdigest()
if actual.lower() != expected_sha256.lower():
try:
part_path.unlink()
except OSError:
pass
raise ValueError(f"sha256 mismatch (got {actual[:12]}…, expected {expected_sha256[:12]}…)")
# Atomic rename across the same filesystem; if target exists (race), replace.
part_path.replace(target_path)
await progress_cb({
"type": "model_progress",
"bytes": downloaded,
"total_bytes": total_bytes or downloaded,
})
def _run_subprocess(
argv: list[str],
cwd: Path | None,
log_cb: Callable[[str], None],
timeout: float | None = None,
) -> int:
"""Run a subprocess streaming combined stdout/stderr line-by-line to log_cb.
Returns the exit code. Raises ``subprocess.TimeoutExpired`` if ``timeout``
elapses. No ``shell=True`` — argv is explicit.
"""
proc = subprocess.Popen(
argv,
cwd=str(cwd) if cwd else None,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
encoding="utf-8",
errors="replace",
)
assert proc.stdout is not None
try:
for line in proc.stdout:
line = line.rstrip()
if line:
log_cb(line)
proc.wait(timeout=timeout)
except Exception:
proc.kill()
raise
return proc.returncode
@functools.lru_cache(maxsize=1)
def _resolve_git() -> str | None:
"""Locate a working ``git`` executable, or return ``None`` if absent.
ComfyUI Desktop (Mac/Windows) and the Windows portable build don't put git
on PATH, so :func:`shutil.which` alone misses it. We additionally probe the
common per-OS install locations, then *verify* the candidate actually runs
(``git --version``): on macOS ``/usr/bin/git`` is a stub that exists even
with no developer tools installed and only errors when invoked, so file
existence isn't enough. Result is cached for the process.
"""
candidates: list[str] = []
on_path = shutil.which("git")
if on_path:
candidates.append(on_path)
if sys.platform == "win32":
candidates += [
os.path.expandvars(r"%PROGRAMFILES%\Git\cmd\git.exe"),
os.path.expandvars(r"%PROGRAMFILES(X86)%\Git\cmd\git.exe"),
os.path.expandvars(r"%LOCALAPPDATA%\Programs\Git\cmd\git.exe"),
]
elif sys.platform == "darwin":
candidates += [
"/opt/homebrew/bin/git", # Apple-silicon Homebrew
"/usr/local/bin/git", # Intel Homebrew / git-scm installer
"/usr/bin/git", # Xcode CLT (may be a no-toolchain stub)
"/Library/Developer/CommandLineTools/usr/bin/git",
]
else:
candidates += ["/usr/bin/git", "/usr/local/bin/git", "/bin/git"]
seen: set[str] = set()
for cand in candidates:
if not cand or cand in seen:
continue
seen.add(cand)
# which() results are already known-present; probe paths must exist.
if cand != on_path and not Path(cand).is_file():
continue
try:
probe = subprocess.run(
[cand, "--version"],
capture_output=True, text=True, timeout=10,
)
except (OSError, subprocess.SubprocessError):
continue
if probe.returncode == 0:
return cand
return None
def _github_slug(origin: str) -> tuple[str, str] | None:
"""Return ``(owner, repo)`` for a github.com origin, else ``None``."""
norm = _normalize_origin(origin) # -> host/path, lowercased, no .git
prefix = "github.com/"
if not norm.startswith(prefix):
return None
parts = [p for p in norm[len(prefix):].split("/") if p]
if len(parts) < 2:
return None
return parts[0], parts[1]
def _safe_extract_tar(tf: tarfile.TarFile, dest: Path) -> None:
"""Extract ``tf`` into ``dest``, rejecting members that escape ``dest``."""
dest = dest.resolve()
base = str(dest) + os.sep
for member in tf.getmembers():
target = (dest / member.name).resolve()
if target != dest and not str(target).startswith(base):
raise RuntimeError(f"unsafe path in tarball: {member.name!r}")
try:
tf.extractall(dest, filter="data") # type: ignore[call-arg] # py3.12+
except TypeError:
tf.extractall(dest)
def _fetch_node_via_git(
git: str,
origin: str,
commit: str | None,
target: Path,
log_cb: Callable[[str], None],