vidfom commited on
Commit
0d57450
·
verified ·
1 Parent(s): 8acaa31

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/.github/workflows/publish.yml +24 -0
  2. ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/.gitignore +162 -0
  3. ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/LICENSE +21 -0
  4. ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/README.md +86 -0
  5. ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/__init__.py +25 -0
  6. ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/nodes/flux-prompt-enhance-node.py +57 -0
  7. ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/pyproject.toml +15 -0
  8. ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/requirements.txt +2 -0
  9. ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/workflow/marduk191ComfyUI-Fluxpromptenhancer.json +110 -0
  10. ComfyUI/custom_nodes/ComfyUI-Manager/.github/workflows/publish.yml +25 -0
  11. ComfyUI/custom_nodes/ComfyUI-Manager/.github/workflows/ruff.yml +23 -0
  12. ComfyUI/custom_nodes/ComfyUI-Manager/.gitignore +20 -0
  13. ComfyUI/custom_nodes/ComfyUI-Manager/LICENSE.txt +674 -0
  14. ComfyUI/custom_nodes/ComfyUI-Manager/README.md +401 -0
  15. ComfyUI/custom_nodes/ComfyUI-Manager/__init__.py +21 -0
  16. ComfyUI/custom_nodes/ComfyUI-Manager/alter-list.json +224 -0
  17. ComfyUI/custom_nodes/ComfyUI-Manager/channels.list.template +6 -0
  18. ComfyUI/custom_nodes/ComfyUI-Manager/check.bat +21 -0
  19. ComfyUI/custom_nodes/ComfyUI-Manager/check.sh +43 -0
  20. ComfyUI/custom_nodes/ComfyUI-Manager/cm-cli.py +1277 -0
  21. ComfyUI/custom_nodes/ComfyUI-Manager/cm-cli.sh +2 -0
  22. ComfyUI/custom_nodes/ComfyUI-Manager/components/.gitignore +2 -0
  23. ComfyUI/custom_nodes/ComfyUI-Manager/custom-node-list.json +0 -0
  24. ComfyUI/custom_nodes/ComfyUI-Manager/docs/en/cm-cli.md +147 -0
  25. ComfyUI/custom_nodes/ComfyUI-Manager/docs/en/use_aria2.md +40 -0
  26. ComfyUI/custom_nodes/ComfyUI-Manager/docs/ko/cm-cli.md +150 -0
  27. ComfyUI/custom_nodes/ComfyUI-Manager/extension-node-map.json +0 -0
  28. ComfyUI/custom_nodes/ComfyUI-Manager/extras.json +26 -0
  29. ComfyUI/custom_nodes/ComfyUI-Manager/git_helper.py +523 -0
  30. ComfyUI/custom_nodes/ComfyUI-Manager/github-stats.json +0 -0
  31. ComfyUI/custom_nodes/ComfyUI-Manager/glob/cm_global.py +117 -0
  32. ComfyUI/custom_nodes/ComfyUI-Manager/glob/cnr_utils.py +253 -0
  33. ComfyUI/custom_nodes/ComfyUI-Manager/glob/git_utils.py +85 -0
  34. ComfyUI/custom_nodes/ComfyUI-Manager/glob/manager_core.py +0 -0
  35. ComfyUI/custom_nodes/ComfyUI-Manager/glob/manager_downloader.py +159 -0
  36. ComfyUI/custom_nodes/ComfyUI-Manager/glob/manager_server.py +1771 -0
  37. ComfyUI/custom_nodes/ComfyUI-Manager/glob/manager_util.py +532 -0
  38. ComfyUI/custom_nodes/ComfyUI-Manager/glob/node_package.py +72 -0
  39. ComfyUI/custom_nodes/ComfyUI-Manager/glob/security_check.py +117 -0
  40. ComfyUI/custom_nodes/ComfyUI-Manager/glob/share_3rdparty.py +384 -0
  41. ComfyUI/custom_nodes/ComfyUI-Manager/js/cm-api.js +67 -0
  42. ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-manager.js +1634 -0
  43. ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-share-common.js +1102 -0
  44. ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-share-copus.js +985 -0
  45. ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-share-openart.js +746 -0
  46. ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-share-youml.js +569 -0
  47. ComfyUI/custom_nodes/ComfyUI-Manager/js/common.js +654 -0
  48. ComfyUI/custom_nodes/ComfyUI-Manager/js/components-manager.js +812 -0
  49. ComfyUI/custom_nodes/ComfyUI-Manager/js/custom-nodes-manager.css +699 -0
  50. ComfyUI/custom_nodes/ComfyUI-Manager/js/custom-nodes-manager.js +2173 -0
ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/.github/workflows/publish.yml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Publish to Comfy registry
2
+ on:
3
+ workflow_dispatch:
4
+ push:
5
+ branches:
6
+ - main
7
+ - master
8
+ paths:
9
+ - "pyproject.toml"
10
+
11
+ jobs:
12
+ publish-node:
13
+ name: Publish Custom Node to registry
14
+ runs-on: ubuntu-latest
15
+ # if this is a forked repository. Skipping the workflow.
16
+ if: github.event.repository.fork == false
17
+ steps:
18
+ - name: Check out code
19
+ uses: actions/checkout@v4
20
+ - name: Publish Custom Node
21
+ uses: Comfy-Org/publish-node-action@main
22
+ with:
23
+ ## Add your own personal access token to your Github Repository secrets and reference it here.
24
+ personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/.gitignore ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 marduk191
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/README.md ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ No longer maintained for public updates as another developer has started a version and we really don't need 2.
2
+
3
+ # Flux Prompt Enhance Node for ComfyUI
4
+
5
+ This custom node for ComfyUI integrates the Flux-Prompt-Enhance model, allowing you to enhance your prompts directly within your ComfyUI workflows.
6
+
7
+ ## Features
8
+
9
+ - Enhance short prompts into more detailed, descriptive ones
10
+ - Seamless integration with ComfyUI
11
+ - Token limited to 256 for schnell compatibility
12
+ - Easy to install and use
13
+
14
+ ## Prerequisites
15
+
16
+ - ComfyUI installed and working
17
+ - Python 3.7 or higher
18
+ - PyTorch 1.9.0 or higher
19
+ - Hugging Face Transformers library 4.18.0 or higher
20
+
21
+ ## Installation
22
+
23
+ 1. Ensure you have ComfyUI installed and working.
24
+
25
+ 2. Clone this repository into your ComfyUI custom nodes directory:
26
+
27
+ ```
28
+ cd /path/to/ComfyUI/custom_nodes
29
+ git clone https://github.com/marduk191/ComfyUI-Fluxpromptenhancer.git
30
+ ```
31
+
32
+ 3. Install the required dependencies:
33
+
34
+ ```
35
+ cd ComfyUI-Fluxpromptenhancer
36
+ pip install -r requirements.txt
37
+ ```
38
+
39
+ This will install PyTorch and the Hugging Face Transformers library, along with any other necessary dependencies.
40
+
41
+ Note: Make sure you're using the same Python environment that ComfyUI uses.
42
+
43
+ 4. The Flux-Prompt-Enhance model will be automatically downloaded when you first use the node. However, if you want to pre-download it or if you're working in an offline environment, you can manually download the model:
44
+
45
+ ```
46
+ python -c "from transformers import AutoTokenizer, AutoModelForSeq2SeqLM; AutoTokenizer.from_pretrained('gokaygokay/Flux-Prompt-Enhance'); AutoModelForSeq2SeqLM.from_pretrained('gokaygokay/Flux-Prompt-Enhance')"
47
+ ```
48
+
49
+ This command will download the model and tokenizer to the default Hugging Face cache directory (usually `~/.cache/huggingface/` on Linux or `C:\Users\YourUsername\.cache\huggingface\` on Windows).
50
+
51
+ 5. Restart ComfyUI or reload custom nodes.
52
+
53
+ ## Usage
54
+
55
+ 1. In the ComfyUI interface, you should now see a new node called "Flux Prompt Enhance" in the "marduk191/Flux_Prompt_Enhancer" category.
56
+
57
+ 2. You can type in this node, or convert the widget to input and connect a string input (your initial prompt) to this node.
58
+
59
+ 3. The node will output an enhanced version of your input prompt.
60
+
61
+ ## Example
62
+
63
+ Input: "beautiful house with text 'hello'"
64
+
65
+ Output: "a two-story house with white trim, large windows on the second floor, three chimneys on the roof, green trees and shrubs in front of the house, stone pathway leading to the front door, text on the house reads "hello" in all caps, blue sky above, shadows cast by the trees, sunlight creating contrast on the house's facade, some plants visible near the bottom right corner, overall warm and serene atmosphere."
66
+
67
+ ## Troubleshooting
68
+
69
+ - If the node doesn't appear in ComfyUI, make sure you've placed the files in the correct directory and restarted ComfyUI.
70
+ - If you encounter any "module not found" errors, ensure that all dependencies (including PyTorch and Hugging Face Transformers) are correctly installed in the same Python environment that ComfyUI is using.
71
+ - If you get an error about the model not being found, make sure you have an internet connection for the automatic download, or try the manual download step in the installation instructions.
72
+
73
+ ## Contributing
74
+
75
+ Contributions are welcome! Please feel free to submit a Pull Request.
76
+
77
+ ## License
78
+
79
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
80
+
81
+ ## Acknowledgments
82
+
83
+ - This node uses the [Flux-Prompt-Enhance](https://huggingface.co/gokaygokay/Flux-Prompt-Enhance) model by gokaygokay.
84
+ - Thanks to the ComfyUI team for creating an extensible platform.
85
+ - This project relies on the Hugging Face Transformers library for model loading and inference.
86
+
ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.util
2
+ import os
3
+ import importlib
4
+ import pkg_resources
5
+ import sys
6
+ import subprocess
7
+ import folder_paths
8
+
9
+
10
+ node_list = [
11
+ "flux-prompt-enhance-node",
12
+ ]
13
+
14
+ NODE_CLASS_MAPPINGS = {}
15
+ NODE_DISPLAY_NAME_MAPPINGS = {}
16
+
17
+ for module_name in node_list:
18
+ imported_module = importlib.import_module(f".nodes.{module_name}", __name__)
19
+
20
+ NODE_CLASS_MAPPINGS = {**NODE_CLASS_MAPPINGS, **imported_module.NODE_CLASS_MAPPINGS}
21
+ NODE_DISPLAY_NAME_MAPPINGS = {**NODE_DISPLAY_NAME_MAPPINGS, **imported_module.NODE_DISPLAY_NAME_MAPPINGS}
22
+
23
+
24
+ WEB_DIRECTORY = "./web"
25
+ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/nodes/flux-prompt-enhance-node.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
3
+
4
+ class FluxPromptEnhanceNode:
5
+ def __init__(self):
6
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
7
+ self.model_checkpoint = "/content/ComfyUI/models/LLM/Flux-Prompt-Enhance"
8
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_checkpoint)
9
+ self.model = AutoModelForSeq2SeqLM.from_pretrained(self.model_checkpoint)
10
+ self.enhancer = pipeline('text2text-generation',
11
+ model=self.model,
12
+ tokenizer=self.tokenizer,
13
+ repetition_penalty=1.2,
14
+ device=self.device)
15
+ self.max_target_length = 256
16
+ self.prefix = "enhance prompt: "
17
+
18
+ @classmethod
19
+ def INPUT_TYPES(cls):
20
+ return {
21
+ "required": {
22
+ "prompt": ("STRING", {"multiline": True}),
23
+ "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
24
+ },
25
+ }
26
+
27
+ RETURN_TYPES = ("STRING",)
28
+ FUNCTION = "enhance_prompt"
29
+ CATEGORY = "marduk191/Flux_Prompt_Enhancer"
30
+
31
+ def enhance_prompt(self, prompt, seed):
32
+ # Set the seed for reproducibility
33
+ torch.manual_seed(seed)
34
+
35
+ # Use do_sample and temperature to control randomness
36
+ do_sample = seed != 0
37
+ temperature = 0.7 if do_sample else 0.0
38
+
39
+ answer = self.enhancer(
40
+ self.prefix + prompt,
41
+ max_length=self.max_target_length,
42
+ do_sample=do_sample,
43
+ temperature=temperature,
44
+ num_return_sequences=1,
45
+ top_k=50,
46
+ top_p=0.95,
47
+ )
48
+ enhanced_prompt = answer[0]['generated_text']
49
+ return (enhanced_prompt,)
50
+
51
+ NODE_CLASS_MAPPINGS = {
52
+ "FluxPromptEnhance": FluxPromptEnhanceNode
53
+ }
54
+
55
+ NODE_DISPLAY_NAME_MAPPINGS = {
56
+ "FluxPromptEnhance": "Flux Prompt Enhance"
57
+ }
ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/pyproject.toml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "comfyui-fluxpromptenhancer"
3
+ description = "This custom node for ComfyUI integrates the Flux-Prompt-Enhance model, allowing you to enhance your prompts directly within your ComfyUI workflows."
4
+ version = "1.0.0"
5
+ license = {file = "LICENSE"}
6
+ dependencies = ["torch>=1.9.0", "transformers>=4.18.0"]
7
+
8
+ [project.urls]
9
+ Repository = "https://github.com/marduk191/ComfyUI-Fluxpromptenhancer"
10
+ # Used by Comfy Registry https://comfyregistry.org
11
+
12
+ [tool.comfy]
13
+ PublisherId = "marduk191"
14
+ DisplayName = "ComfyUI-Fluxpromptenhancer"
15
+ Icon = "https://raw.githubusercontent.com/marduk191/comfyui-marnodes/main/icon/RA.png"
ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ torch>=1.9.0
2
+ transformers>=4.18.0
ComfyUI/custom_nodes/ComfyUI-Fluxpromptenhancer/workflow/marduk191ComfyUI-Fluxpromptenhancer.json ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "last_node_id": 3,
3
+ "last_link_id": 1,
4
+ "nodes": [
5
+ {
6
+ "id": 1,
7
+ "type": "FluxPromptEnhance",
8
+ "pos": [
9
+ 480,
10
+ 190
11
+ ],
12
+ "size": {
13
+ "0": 400,
14
+ "1": 200
15
+ },
16
+ "flags": {},
17
+ "order": 0,
18
+ "mode": 0,
19
+ "outputs": [
20
+ {
21
+ "name": "STRING",
22
+ "type": "STRING",
23
+ "links": [
24
+ 1
25
+ ],
26
+ "slot_index": 0,
27
+ "shape": 3
28
+ }
29
+ ],
30
+ "properties": {
31
+ "Node name for S&R": "FluxPromptEnhance"
32
+ },
33
+ "widgets_values": [
34
+ "a girl in the forest",
35
+ true
36
+ ],
37
+ "color": "#232",
38
+ "bgcolor": "#353"
39
+ },
40
+ {
41
+ "id": 2,
42
+ "type": "ShowText|pysssss",
43
+ "pos": [
44
+ 920,
45
+ 190
46
+ ],
47
+ "size": {
48
+ "0": 510,
49
+ "1": 200
50
+ },
51
+ "flags": {},
52
+ "order": 1,
53
+ "mode": 0,
54
+ "inputs": [
55
+ {
56
+ "name": "text",
57
+ "type": "STRING",
58
+ "link": 1,
59
+ "widget": {
60
+ "name": "text"
61
+ }
62
+ }
63
+ ],
64
+ "outputs": [
65
+ {
66
+ "name": "STRING",
67
+ "type": "STRING",
68
+ "links": null,
69
+ "shape": 6
70
+ }
71
+ ],
72
+ "properties": {
73
+ "Node name for S&R": "ShowText|pysssss"
74
+ },
75
+ "widgets_values": [
76
+ "",
77
+ "a young girl with long brown hair, wearing a white sleeveless top and blue jeans, standing in the middle of a forest, her left hand resting on her hip, she is looking to her right, tall trees with green leaves surround her, sunlight filters through the tree canopy creating dappled light on her face and clothing, some branches are visible above her head, there is a sense of depth with the background slightly blurred, giving a sense of depth and focus on the girl."
78
+ ],
79
+ "color": "#232",
80
+ "bgcolor": "#353"
81
+ }
82
+ ],
83
+ "links": [
84
+ [
85
+ 1,
86
+ 1,
87
+ 0,
88
+ 2,
89
+ 0,
90
+ "STRING"
91
+ ]
92
+ ],
93
+ "groups": [],
94
+ "config": {},
95
+ "extra": {
96
+ "ds": {
97
+ "scale": 1.6105100000000008,
98
+ "offset": [
99
+ -342.648768092095,
100
+ 79.24110219744011
101
+ ]
102
+ },
103
+ "0246.VERSION": [
104
+ 0,
105
+ 0,
106
+ 4
107
+ ]
108
+ },
109
+ "version": 0.4
110
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/.github/workflows/publish.yml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Publish to Comfy registry
2
+ on:
3
+ workflow_dispatch:
4
+ push:
5
+ branches:
6
+ - main-blocked
7
+ paths:
8
+ - "pyproject.toml"
9
+
10
+ permissions:
11
+ issues: write
12
+
13
+ jobs:
14
+ publish-node:
15
+ name: Publish Custom Node to registry
16
+ runs-on: ubuntu-latest
17
+ if: ${{ github.repository_owner == 'ltdrdata' }}
18
+ steps:
19
+ - name: Check out code
20
+ uses: actions/checkout@v4
21
+ - name: Publish Custom Node
22
+ uses: Comfy-Org/publish-node-action@v1
23
+ with:
24
+ ## Add your own personal access token to your Github Repository secrets and reference it here.
25
+ personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
ComfyUI/custom_nodes/ComfyUI-Manager/.github/workflows/ruff.yml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Python Linting
2
+
3
+ on: [push, pull_request]
4
+
5
+ jobs:
6
+ ruff:
7
+ name: Run Ruff
8
+ runs-on: ubuntu-latest
9
+
10
+ steps:
11
+ - name: Checkout repository
12
+ uses: actions/checkout@v4
13
+
14
+ - name: Set up Python
15
+ uses: actions/setup-python@v2
16
+ with:
17
+ python-version: 3.x
18
+
19
+ - name: Install Ruff
20
+ run: pip install ruff
21
+
22
+ - name: Run Ruff
23
+ run: ruff check .
ComfyUI/custom_nodes/ComfyUI-Manager/.gitignore ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ .idea/
3
+ .vscode/
4
+ .history/
5
+ *.code-workspace
6
+ .tmp
7
+ .cache
8
+ config.ini
9
+ snapshots/**
10
+ startup-scripts/**
11
+ .openart_key
12
+ .youml
13
+ matrix_auth
14
+ channels.list
15
+ comfyworkflows_sharekey
16
+ github-stats-cache.json
17
+ pip_overrides.json
18
+ *.json
19
+ check2.sh
20
+ /venv/
ComfyUI/custom_nodes/ComfyUI-Manager/LICENSE.txt ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
ComfyUI/custom_nodes/ComfyUI-Manager/README.md ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ComfyUI Manager
2
+
3
+ **ComfyUI-Manager** is an extension designed to enhance the usability of [ComfyUI](https://github.com/comfyanonymous/ComfyUI). It offers management functions to **install, remove, disable, and enable** various custom nodes of ComfyUI. Furthermore, this extension provides a hub feature and convenience functions to access a wide range of information within ComfyUI.
4
+
5
+ ![menu](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/refs/heads/Main/ComfyUI-Manager/images/dialog.jpg)
6
+
7
+ ## NOTICE
8
+ * V3.16: Support for `uv` has been added. Set `use_uv` in `config.ini`.
9
+ * V3.10: `double-click feature` is removed
10
+ * This feature has been moved to https://github.com/ltdrdata/comfyui-connection-helper
11
+ * V3.3.2: Overhauled. Officially supports [https://comfyregistry.org/](https://comfyregistry.org/).
12
+ * You can see whole nodes info on [ComfyUI Nodes Info](https://ltdrdata.github.io/) page.
13
+
14
+ ## Installation
15
+
16
+ ### Installation[method1] (General installation method: ComfyUI-Manager only)
17
+
18
+ To install ComfyUI-Manager in addition to an existing installation of ComfyUI, you can follow the following steps:
19
+
20
+ 1. goto `ComfyUI/custom_nodes` dir in terminal(cmd)
21
+ 2. `git clone https://github.com/ltdrdata/ComfyUI-Manager comfyui-manager`
22
+ 3. Restart ComfyUI
23
+
24
+
25
+ ### Installation[method2] (Installation for portable ComfyUI version: ComfyUI-Manager only)
26
+ 1. install git
27
+ - https://git-scm.com/download/win
28
+ - standalone version
29
+ - select option: use windows default console window
30
+ 2. Download [scripts/install-manager-for-portable-version.bat](https://github.com/ltdrdata/ComfyUI-Manager/raw/main/scripts/install-manager-for-portable-version.bat) into installed `"ComfyUI_windows_portable"` directory
31
+ - Don't click. Right click the link and use save as...
32
+ 3. double click `install-manager-for-portable-version.bat` batch file
33
+
34
+ ![portable-install](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/portable-install.jpg)
35
+
36
+
37
+ ### Installation[method3] (Installation through comfy-cli: install ComfyUI and ComfyUI-Manager at once.)
38
+ > RECOMMENDED: comfy-cli provides various features to manage ComfyUI from the CLI.
39
+
40
+ * **prerequisite: python 3, git**
41
+
42
+ Windows:
43
+ ```commandline
44
+ python -m venv venv
45
+ venv\Scripts\activate
46
+ pip install comfy-cli
47
+ comfy install
48
+ ```
49
+
50
+ Linux/OSX:
51
+ ```commandline
52
+ python -m venv venv
53
+ . venv/bin/activate
54
+ pip install comfy-cli
55
+ comfy install
56
+ ```
57
+ * See also: https://github.com/Comfy-Org/comfy-cli
58
+
59
+
60
+ ### Installation[method4] (Installation for linux+venv: ComfyUI + ComfyUI-Manager)
61
+
62
+ To install ComfyUI with ComfyUI-Manager on Linux using a venv environment, you can follow these steps:
63
+ * **prerequisite: python-is-python3, python3-venv, git**
64
+
65
+ 1. Download [scripts/install-comfyui-venv-linux.sh](https://github.com/ltdrdata/ComfyUI-Manager/raw/main/scripts/install-comfyui-venv-linux.sh) into empty install directory
66
+ - Don't click. Right click the link and use save as...
67
+ - ComfyUI will be installed in the subdirectory of the specified directory, and the directory will contain the generated executable script.
68
+ 2. `chmod +x install-comfyui-venv-linux.sh`
69
+ 3. `./install-comfyui-venv-linux.sh`
70
+
71
+ ### Installation Precautions
72
+ * **DO**: `ComfyUI-Manager` files must be accurately located in the path `ComfyUI/custom_nodes/comfyui-manager`
73
+ * Installing in a compressed file format is not recommended.
74
+ * **DON'T**: Decompress directly into the `ComfyUI/custom_nodes` location, resulting in the Manager contents like `__init__.py` being placed directly in that directory.
75
+ * You have to remove all ComfyUI-Manager files from `ComfyUI/custom_nodes`
76
+ * **DON'T**: In a form where decompression occurs in a path such as `ComfyUI/custom_nodes/ComfyUI-Manager/ComfyUI-Manager`.
77
+ * **DON'T**: In a form where decompression occurs in a path such as `ComfyUI/custom_nodes/ComfyUI-Manager-main`.
78
+ * In such cases, `ComfyUI-Manager` may operate, but it won't be recognized within `ComfyUI-Manager`, and updates cannot be performed. It also poses the risk of duplicate installations. Remove it and install properly via `git clone` method.
79
+
80
+
81
+ You can execute ComfyUI by running either `./run_gpu.sh` or `./run_cpu.sh` depending on your system configuration.
82
+
83
+ ## Colab Notebook
84
+ This repository provides Colab notebooks that allow you to install and use ComfyUI, including ComfyUI-Manager. To use ComfyUI, [click on this link](https://colab.research.google.com/github/ltdrdata/ComfyUI-Manager/blob/main/notebooks/comfyui_colab_with_manager.ipynb).
85
+ * Support for installing ComfyUI
86
+ * Support for basic installation of ComfyUI-Manager
87
+ * Support for automatically installing dependencies of custom nodes upon restarting Colab notebooks.
88
+
89
+
90
+ ## How To Use
91
+
92
+ 1. Click "Manager" button on main menu
93
+
94
+ ![mainmenu](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/topbar.jpg)
95
+
96
+
97
+ 2. If you click on 'Install Custom Nodes' or 'Install Models', an installer dialog will open.
98
+
99
+ ![menu](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/refs/heads/Main/ComfyUI-Manager/images/dialog.jpg)
100
+
101
+ * There are three DB modes: `DB: Channel (1day cache)`, `DB: Local`, and `DB: Channel (remote)`.
102
+ * `Channel (1day cache)` utilizes Channel cache information with a validity period of one day to quickly display the list.
103
+ * This information will be updated when there is no cache, when the cache expires, or when external information is retrieved through the Channel (remote).
104
+ * Whenever you start ComfyUI anew, this mode is always set as the **default** mode.
105
+ * `Local` uses information stored locally in ComfyUI-Manager.
106
+ * This information will be updated only when you update ComfyUI-Manager.
107
+ * For custom node developers, they should use this mode when registering their nodes in `custom-node-list.json` and testing them.
108
+ * `Channel (remote)` retrieves information from the remote channel, always displaying the latest list.
109
+ * In cases where retrieval is not possible due to network errors, it will forcibly use local information.
110
+
111
+ * The ```Fetch Updates``` menu retrieves update data for custom nodes locally. Actual updates are applied by clicking the ```Update``` button in the ```Install Custom Nodes``` menu.
112
+
113
+ 3. Click 'Install' or 'Try Install' button.
114
+
115
+ ![node-install-dialog](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/custom-nodes.jpg)
116
+
117
+ ![model-install-dialog](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/models.jpg)
118
+
119
+ * Installed: This item is already installed.
120
+ * Install: Clicking this button will install the item.
121
+ * Try Install: This is a custom node of which installation information cannot be confirmed. Click the button to try installing it.
122
+
123
+ * If a red background `Channel` indicator appears at the top, it means it is not the default channel. Since the amount of information held is different from the default channel, many custom nodes may not appear in this channel state.
124
+ * Channel settings have a broad impact, affecting not only the node list but also all functions like "Update all."
125
+ * Conflicted Nodes with a yellow background show a list of nodes conflicting with other extensions in the respective extension. This issue needs to be addressed by the developer, and users should be aware that due to these conflicts, some nodes may not function correctly and may need to be installed accordingly.
126
+
127
+ 4. Share
128
+ ![menu](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/topbar.jpg) ![share](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/share.jpg)
129
+
130
+ * You can share the workflow by clicking the Share button at the bottom of the main menu or selecting Share Output from the Context Menu of the Image node.
131
+ * Currently, it supports sharing via [https://comfyworkflows.com/](https://comfyworkflows.com/),
132
+ [https://openart.ai](https://openart.ai/workflows/dev), [https://youml.com](https://youml.com)
133
+ as well as through the Matrix channel.
134
+
135
+ ![menu](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/share-setting.jpg)
136
+
137
+ * Through the Share settings in the Manager menu, you can configure the behavior of the Share button in the Main menu or Share Output button on Context Menu.
138
+ * `None`: hide from Main menu
139
+ * `All`: Show a dialog where the user can select a title for sharing.
140
+
141
+
142
+ ## Paths
143
+ In `ComfyUI-Manager` V3.0 and later, configuration files and dynamically generated files are located under `<USER_DIRECTORY>/default/ComfyUI-Manager/`.
144
+
145
+ * <USER_DIRECTORY>
146
+ * If executed without any options, the path defaults to ComfyUI/user.
147
+ * It can be set using --user-directory <USER_DIRECTORY>.
148
+
149
+ * Basic config files: `<USER_DIRECTORY>/default/ComfyUI-Manager/config.ini`
150
+ * Configurable channel lists: `<USER_DIRECTORY>/default/ComfyUI-Manager/channels.ini`
151
+ * Configurable pip overrides: `<USER_DIRECTORY>/default/ComfyUI-Manager/pip_overrides.json`
152
+ * Configurable pip blacklist: `<USER_DIRECTORY>/default/ComfyUI-Manager/pip_blacklist.list`
153
+ * Configurable pip auto fix: `<USER_DIRECTORY>/default/ComfyUI-Manager/pip_auto_fix.list`
154
+ * Saved snapshot files: `<USER_DIRECTORY>/default/ComfyUI-Manager/snapshots`
155
+ * Startup script files: `<USER_DIRECTORY>/default/ComfyUI-Manager/startup-scripts`
156
+ * Component files: `<USER_DIRECTORY>/default/ComfyUI-Manager/components`
157
+
158
+
159
+ ## `extra_model_paths.yaml` Configuration
160
+ The following settings are applied based on the section marked as `is_default`.
161
+
162
+ * `custom_nodes`: Path for installing custom nodes
163
+ * Importing does not need to adhere to the path set as `is_default`, but this is the path where custom nodes are installed by the `ComfyUI Nodes Manager`.
164
+ * `download_model_base`: Path for downloading models
165
+
166
+
167
+ ## Snapshot-Manager
168
+ * When you press `Save snapshot` or use `Update All` on `Manager Menu`, the current installation status snapshot is saved.
169
+ * Snapshot file dir: `<USER_DIRECTORY>/default/ComfyUI-Manager/snapshots`
170
+ * You can rename snapshot file.
171
+ * Press the "Restore" button to revert to the installation status of the respective snapshot.
172
+ * However, for custom nodes not managed by Git, snapshot support is incomplete.
173
+ * When you press `Restore`, it will take effect on the next ComfyUI startup.
174
+ * The selected snapshot file is saved in `<USER_DIRECTORY>/default/ComfyUI-Manager/startup-scripts/restore-snapshot.json`, and upon restarting ComfyUI, the snapshot is applied and then deleted.
175
+
176
+ ![model-install-dialog](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/snapshot.jpg)
177
+
178
+
179
+ ## cm-cli: command line tools for power user
180
+ * A tool is provided that allows you to use the features of ComfyUI-Manager without running ComfyUI.
181
+ * For more details, please refer to the [cm-cli documentation](docs/en/cm-cli.md).
182
+
183
+
184
+ ## How to register your custom node into ComfyUI-Manager
185
+
186
+ * Add an entry to `custom-node-list.json` located in the root of ComfyUI-Manager and submit a Pull Request.
187
+ * NOTE: Before submitting the PR after making changes, please check `Use local DB` and ensure that the extension list loads without any issues in the `Install custom nodes` dialog. Occasionally, missing or extra commas can lead to JSON syntax errors.
188
+ * The remaining JSON will be updated through scripts in the future, so you don't need to worry about it.
189
+
190
+
191
+ ## Custom node support guide
192
+
193
+ * **NOTICE:**
194
+ - You should no longer assume that the GitHub repository name will match the subdirectory name under `custom_nodes`. The name of the subdirectory under `custom_nodes` will now use the normalized name from the `name` field in `pyproject.toml`.
195
+ - Avoid relying on directory names for imports whenever possible.
196
+
197
+ * https://docs.comfy.org/registry/overview
198
+ * https://github.com/Comfy-Org/rfcs
199
+
200
+ **Special purpose files** (optional)
201
+ * `pyproject.toml` - Spec file for comfyregistry.
202
+ * `node_list.json` - When your custom nodes pattern of NODE_CLASS_MAPPINGS is not conventional, it is used to manually provide a list of nodes for reference. ([example](https://github.com/melMass/comfy_mtb/raw/main/node_list.json))
203
+ * `requirements.txt` - When installing, this pip requirements will be installed automatically
204
+ * `install.py` - When installing, it is automatically called
205
+ * **All scripts are executed from the root path of the corresponding custom node.**
206
+
207
+
208
+ ## Component Sharing
209
+ * **Copy & Paste**
210
+ * [Demo Page](https://ltdrdata.github.io/component-demo/)
211
+ * When pasting a component from the clipboard, it supports text in the following JSON format. (text/plain)
212
+ ```
213
+ {
214
+ "kind": "ComfyUI Components",
215
+ "timestamp": <current timestamp>,
216
+ "components":
217
+ {
218
+ <component name>: <component nodedata>
219
+ }
220
+ }
221
+ ```
222
+ * `<current timestamp>` Ensure that the timestamp is always unique.
223
+ * "components" should have the same structure as the content of the file stored in `<USER_DIRECTORY>/default/ComfyUI-Manager/components`.
224
+ * `<component name>`: The name should be in the format `<prefix>::<node name>`.
225
+ * `<compnent nodeata>`: In the nodedata of the group node.
226
+ * `<version>`: Only two formats are allowed: `major.minor.patch` or `major.minor`. (e.g. `1.0`, `2.2.1`)
227
+ * `<datetime>`: Saved time
228
+ * `<packname>`: If the packname is not empty, the category becomes packname/workflow, and it is saved in the <packname>.pack file in `<USER_DIRECTORY>/default/ComfyUI-Manager/components`.
229
+ * `<category>`: If there is neither a category nor a packname, it is saved in the components category.
230
+ ```
231
+ "version":"1.0",
232
+ "datetime": 1705390656516,
233
+ "packname": "mypack",
234
+ "category": "util/pipe",
235
+ ```
236
+ * **Drag & Drop**
237
+ * Dragging and dropping a `.pack` or `.json` file will add the corresponding components.
238
+ * Example pack: [Impact.pack](misc/Impact.pack)
239
+
240
+ * Dragging and dropping or pasting a single component will add a node. However, when adding multiple components, nodes will not be added.
241
+
242
+
243
+ ## Support of missing nodes installation
244
+
245
+ ![missing-menu](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/missing-menu.jpg)
246
+
247
+ * When you click on the ```Install Missing Custom Nodes``` button in the menu, it displays a list of extension nodes that contain nodes not currently present in the workflow.
248
+
249
+ ![missing-list](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/missing-list.jpg)
250
+
251
+
252
+ # Config
253
+ * You can modify the `config.ini` file to apply the settings for ComfyUI-Manager.
254
+ * The path to the `config.ini` used by ComfyUI-Manager is displayed in the startup log messages.
255
+ * See also: [https://github.com/ltdrdata/ComfyUI-Manager#paths]
256
+ * Configuration options:
257
+ ```
258
+ [default]
259
+ git_exe = <Manually specify the path to the git executable. If left empty, the default git executable path will be used.>
260
+ use_uv = <Use uv instead of pip for dependency installation.>
261
+ default_cache_as_channel_url = <Determines whether to retrieve the DB designated as channel_url at startup>
262
+ bypass_ssl = <Set to True if SSL errors occur to disable SSL.>
263
+ file_logging = <Configure whether to create a log file used by ComfyUI-Manager.>
264
+ windows_selector_event_loop_policy = <If an event loop error occurs on Windows, set this to True.>
265
+ model_download_by_agent = <When downloading models, use an agent instead of torchvision_download_url.>
266
+ downgrade_blacklist = <Set a list of packages to prevent downgrades. List them separated by commas.>
267
+ security_level = <Set the security level => strong|normal|normal-|weak>
268
+ always_lazy_install = <Whether to perform dependency installation on restart even in environments other than Windows.>
269
+ network_mode = <Set the network mode => public|private|offline>
270
+ ```
271
+
272
+ * network_mode:
273
+ - public: An environment that uses a typical public network.
274
+ - private: An environment that uses a closed network, where a private node DB is configured via `channel_url`. (Uses cache if available)
275
+ - offline: An environment that does not use any external connections when using an offline network. (Uses cache if available)
276
+
277
+
278
+ ## Additional Feature
279
+ * Logging to file feature
280
+ * This feature is enabled by default and can be disabled by setting `file_logging = False` in the `config.ini`.
281
+
282
+ * Fix node(recreate): When right-clicking on a node and selecting `Fix node (recreate)`, you can recreate the node. The widget's values are reset, while the connections maintain those with the same names.
283
+ * It is used to correct errors in nodes of old workflows created before, which are incompatible with the version changes of custom nodes.
284
+
285
+ * Double-Click Node Title: You can set the double click behavior of nodes in the ComfyUI-Manager menu.
286
+ * `Copy All Connections`, `Copy Input Connections`: Double-clicking a node copies the connections of the nearest node.
287
+ * This action targets the nearest node within a straight-line distance of 1000 pixels from the center of the node.
288
+ * In the case of `Copy All Connections`, it duplicates existing outputs, but since it does not allow duplicate connections, the existing output connections of the original node are disconnected.
289
+ * This feature copies only the input and output that match the names.
290
+
291
+ * `Possible Input Connections`: It connects all outputs that match the closest type within the specified range.
292
+ * This connection links to the closest outputs among the nodes located on the left side of the target node.
293
+
294
+ * `Possible(left) + Copy(right)`: When you Double-Click on the left half of the title, it operates as `Possible Input Connections`, and when you Double-Click on the right half, it operates as `Copy All Connections`.
295
+
296
+ * Prevent downgrade of specific packages
297
+ * List the package names in the `downgrade_blacklist` section of the `config.ini` file, separating them with commas.
298
+ * e.g
299
+ ```
300
+ downgrade_blacklist = diffusers, kornia
301
+ ```
302
+
303
+ * Custom pip mapping
304
+ * When you create the `pip_overrides.json` file, it changes the installation of specific pip packages to installations defined by the user.
305
+ * Please refer to the `pip_overrides.json.template` file.
306
+
307
+ * Prevent the installation of specific pip packages
308
+ * List the package names one per line in the `pip_blacklist.list` file.
309
+
310
+ * Automatically Restoring pip Installation
311
+ * If you list pip spec requirements in `pip_auto_fix.list`, similar to `requirements.txt`, it will automatically restore the specified versions when starting ComfyUI or when versions get mismatched during various custom node installations.
312
+ * `--index-url` can be used.
313
+
314
+ * Use `aria2` as downloader
315
+ * [howto](docs/en/use_aria2.md)
316
+
317
+
318
+ ## Environment Variables
319
+
320
+ The following features can be configured using environment variables:
321
+
322
+ * **COMFYUI_PATH**: The installation path of ComfyUI
323
+ * **GITHUB_ENDPOINT**: Reverse proxy configuration for environments with limited access to GitHub
324
+ * **HF_ENDPOINT**: Reverse proxy configuration for environments with limited access to Hugging Face
325
+
326
+
327
+ ### Example 1:
328
+ Redirecting `https://github.com/ltdrdata/ComfyUI-Impact-Pack` to `https://mirror.ghproxy.com/https://github.com/ltdrdata/ComfyUI-Impact-Pack`
329
+
330
+ ```
331
+ GITHUB_ENDPOINT=https://mirror.ghproxy.com/https://github.com
332
+ ```
333
+
334
+ #### Example 2:
335
+ Changing `https://huggingface.co/path/to/somewhere` to `https://some-hf-mirror.com/path/to/somewhere`
336
+
337
+ ```
338
+ HF_ENDPOINT=https://some-hf-mirror.com
339
+ ```
340
+
341
+ ## Scanner
342
+ When you run the `scan.sh` script:
343
+
344
+ * It updates the `extension-node-map.json`.
345
+ * To do this, it pulls or clones the custom nodes listed in `custom-node-list.json` into `~/.tmp/default`.
346
+ * To skip this step, add the `--skip-update` option.
347
+ * If you want to specify a different path instead of `~/.tmp/default`, run `python scanner.py [path]` directly instead of `scan.sh`.
348
+
349
+ * It updates the `github-stats.json`.
350
+ * This uses the GitHub API, so set your token with `export GITHUB_TOKEN=your_token_here` to avoid quickly reaching the rate limit and malfunctioning.
351
+ * To skip this step, add the `--skip-update-stat` option.
352
+
353
+ * The `--skip-all` option applies both `--skip-update` and `--skip-stat-update`.
354
+
355
+
356
+ ## Troubleshooting
357
+ * If your `git.exe` is installed in a specific location other than system git, please install ComfyUI-Manager and run ComfyUI. Then, specify the path including the file name in `git_exe = ` in the `<USER_DIRECTORY>/default/ComfyUI-Manager/config.ini` file that is generated.
358
+ * If updating ComfyUI-Manager itself fails, please go to the **ComfyUI-Manager** directory and execute the command `git update-ref refs/remotes/origin/main a361cc1 && git fetch --all && git pull`.
359
+ * If you encounter the error message `Overlapped Object has pending operation at deallocation on Comfyui Manager load` under Windows
360
+ * Edit `config.ini` file: add `windows_selector_event_loop_policy = True`
361
+ * if `SSL: CERTIFICATE_VERIFY_FAILED` error is occured.
362
+ * Edit `config.ini` file: add `bypass_ssl = True`
363
+
364
+
365
+ ## Security policy
366
+ * Edit `config.ini` file: add `security_level = <LEVEL>`
367
+ * `strong`
368
+ * doesn't allow `high` and `middle` level risky feature
369
+ * `normal`
370
+ * doesn't allow `high` level risky feature
371
+ * `middle` level risky feature is available
372
+ * `normal-`
373
+ * doesn't allow `high` level risky feature if `--listen` is specified and not starts with `127.`
374
+ * `middle` level risky feature is available
375
+ * `weak`
376
+ * all feature is available
377
+
378
+ * `high` level risky features
379
+ * `Install via git url`, `pip install`
380
+ * Installation of custom nodes registered not in the `default channel`.
381
+ * Fix custom nodes
382
+
383
+ * `middle` level risky features
384
+ * Uninstall/Update
385
+ * Installation of custom nodes registered in the `default channel`.
386
+ * Restore/Remove Snapshot
387
+ * Restart
388
+
389
+ * `low` level risky features
390
+ * Update ComfyUI
391
+
392
+
393
+ # Disclaimer
394
+
395
+ * This extension simply provides the convenience of installing custom nodes and does not guarantee their proper functioning.
396
+
397
+
398
+ ## Credit
399
+ ComfyUI/[ComfyUI](https://github.com/comfyanonymous/ComfyUI) - A powerful and modular stable diffusion GUI.
400
+
401
+ **And, for all ComfyUI custom node developers**
ComfyUI/custom_nodes/ComfyUI-Manager/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ cli_mode_flag = os.path.join(os.path.dirname(__file__), '.enable-cli-only-mode')
5
+
6
+ if not os.path.exists(cli_mode_flag):
7
+ sys.path.append(os.path.join(os.path.dirname(__file__), "glob"))
8
+ import manager_server # noqa: F401
9
+ import share_3rdparty # noqa: F401
10
+ import cm_global
11
+
12
+ if not cm_global.disable_front and not 'DISABLE_COMFYUI_MANAGER_FRONT' in os.environ:
13
+ WEB_DIRECTORY = "js"
14
+ else:
15
+ print("\n[ComfyUI-Manager] !! cli-only-mode is enabled !!\n")
16
+
17
+ NODE_CLASS_MAPPINGS = {}
18
+ __all__ = ['NODE_CLASS_MAPPINGS']
19
+
20
+
21
+
ComfyUI/custom_nodes/ComfyUI-Manager/alter-list.json ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "items": [
3
+ {
4
+ "id":"https://github.com/Fannovel16/comfyui_controlnet_aux",
5
+ "tags":"controlnet",
6
+ "description": "This extension provides preprocessor nodes for using controlnet."
7
+ },
8
+ {
9
+ "id":"https://github.com/comfyanonymous/ComfyUI_experiments",
10
+ "tags":"Dynamic Thresholding, DT, CFG, controlnet, reference only",
11
+ "description": "This experimental nodes contains a 'Reference Only' node and a 'ModelSamplerTonemapNoiseTest' node corresponding to the 'Dynamic Threshold'."
12
+ },
13
+ {
14
+ "id":"https://github.com/ltdrdata/ComfyUI-Impact-Pack",
15
+ "tags":"ddetailer, adetailer, ddsd, DD, loopback scaler, prompt, wildcard, dynamic prompt",
16
+ "description": "To implement the feature of automatically detecting faces and enhancing details, various detection nodes and detailers provided by the Impact Pack can be applied. Similarly to Loopback Scaler, it also provides various custom workflows that can apply Ksampler while gradually scaling up."
17
+ },
18
+ {
19
+ "id":"https://github.com/ltdrdata/ComfyUI-Inspire-Pack",
20
+ "tags":"lora block weight, effective block analyzer, lbw, variation seed",
21
+ "description": "The Inspire Pack provides the functionality of Lora Block Weight, Variation Seed."
22
+ },
23
+ {
24
+ "id":"https://github.com/biegert/ComfyUI-CLIPSeg/raw/main/custom_nodes/clipseg.py",
25
+ "tags":"ddsd",
26
+ "description": "This extension provides a feature that generates segment masks on an image using a text prompt. When used in conjunction with Impact Pack, it enables applications such as DDSD."
27
+ },
28
+ {
29
+ "id":"https://github.com/BadCafeCode/masquerade-nodes-comfyui",
30
+ "tags":"ddetailer",
31
+ "description": "This extension is a less feature-rich and well-maintained alternative to Impact Pack, but it has fewer dependencies and may be easier to install on abnormal configurations. The author recommends trying Impact Pack first."
32
+ },
33
+ {
34
+ "id":"https://github.com/BlenderNeko/ComfyUI_Cutoff",
35
+ "tags":"cutoff",
36
+ "description": "By using this extension, prompts like 'blue hair' can be prevented from interfering with other prompts by blocking the attribute 'blue' from being used in prompts other than 'hair'."
37
+ },
38
+ {
39
+ "id":"https://github.com/BlenderNeko/ComfyUI_ADV_CLIP_emb",
40
+ "tags":"prompt, weight",
41
+ "description": "There are differences in the processing methods of prompts, such as weighting and scheduling, between A1111 and ComfyUI. With this extension, various settings can be used to implement prompt processing methods similar to A1111. As this feature is also integrated into ComfyUI Cutoff, please download the Cutoff extension if you plan to use it in conjunction with Cutoff."
42
+ },
43
+ {
44
+ "id":"https://github.com/shiimizu/ComfyUI_smZNodes",
45
+ "tags":"prompt, weight",
46
+ "description": "There are differences in the processing methods of prompts, such as weighting and scheduling, between A1111 and ComfyUI. This extension helps to reproduce the same embedding as A1111."
47
+ },
48
+ {
49
+ "id":"https://github.com/BlenderNeko/ComfyUI_Noise",
50
+ "tags":"img2img alt, random",
51
+ "description": "The extension provides an unsampler that reverses the sampling process, allowing for a function similar to img2img alt to be implemented. Furthermore, ComfyUI uses CPU's Random instead of GPU's Random for better reproducibility compared to A1111. This extension provides the ability to use GPU's Random for Latent Noise. However, since GPU's Random may vary depending on the GPU model, reproducibility on different devices cannot be guaranteed."
52
+ },
53
+ {
54
+ "id":"https://github.com/BlenderNeko/ComfyUI_SeeCoder",
55
+ "tags":"seecoder, prompt-free-diffusion",
56
+ "description": "The extension provides seecoder feature."
57
+ },
58
+ {
59
+ "id":"https://github.com/lilly1987/ComfyUI_node_Lilly",
60
+ "tags":"prompt, wildcard",
61
+ "description": "This extension provides features such as a wildcard function that randomly selects prompts belonging to a category and the ability to directly load lora from prompts."
62
+ },
63
+ {
64
+ "id":"https://github.com/Davemane42/ComfyUI_Dave_CustomNode",
65
+ "tags":"latent couple",
66
+ "description": "ComfyUI already provides the ability to composite latents by default. However, this extension makes it more convenient to use by visualizing the composite area."
67
+ },
68
+ {
69
+ "id":"https://github.com/LEv145/images-grid-comfy-plugin",
70
+ "tags":"X/Y Plot",
71
+ "description": "This tool provides a viewer node that allows for checking multiple outputs in a grid, similar to the X/Y Plot extension."
72
+ },
73
+ {
74
+ "id":"https://github.com/pythongosssss/ComfyUI-WD14-Tagger",
75
+ "tags":"deepbooru, clip interrogation",
76
+ "description": "This extension generates clip text by taking an image as input and using the Deepbooru model."
77
+ },
78
+ {
79
+ "id":"https://github.com/szhublox/ambw_comfyui",
80
+ "tags":"supermerger",
81
+ "description": "This node takes two models, merges individual blocks together at various ratios, and automatically rates each merge, keeping the ratio with the highest score. "
82
+ },
83
+ {
84
+ "id":"https://github.com/ssitu/ComfyUI_UltimateSDUpscale",
85
+ "tags":"upscaler, Ultimate SD Upscale",
86
+ "description": "ComfyUI nodes for the Ultimate Stable Diffusion Upscale script by Coyote-A. Uses the same script used in the A1111 extension to hopefully replicate images generated using the A1111 webui."
87
+ },
88
+ {
89
+ "id":"https://github.com/dawangraoming/ComfyUI_ksampler_gpu/raw/main/ksampler_gpu.py",
90
+ "tags":"random, noise",
91
+ "description": "A1111 provides KSampler that uses GPU-based random noise. This extension offers KSampler utilizing GPU-based random noise."
92
+ },
93
+ {
94
+ "id":"https://github.com/space-nuko/nui-suite",
95
+ "tags":"prompt, dynamic prompt",
96
+ "description": "This extension provides nodes with the functionality of dynamic prompts."
97
+ },
98
+ {
99
+ "id":"https://github.com/melMass/comfy_mtb",
100
+ "tags":"roop",
101
+ "description": "This extension provides bunch of nodes including roop"
102
+ },
103
+ {
104
+ "id":"https://github.com/ssitu/ComfyUI_roop",
105
+ "tags":"roop",
106
+ "description": "This extension provides nodes for the roop A1111 webui script."
107
+ },
108
+ {
109
+ "id":"https://github.com/asagi4/comfyui-prompt-control",
110
+ "tags":"prompt, prompt editing",
111
+ "description": "This extension provides the ability to use prompts like \n\n**a [large::0.1] [cat|dog:0.05] [<lora:somelora:0.5:0.6>::0.5] [in a park:in space:0.4]**\n\n"
112
+ },
113
+ {
114
+ "id":"https://github.com/adieyal/comfyui-dynamicprompts",
115
+ "tags":"prompt, dynamic prompt",
116
+ "description": "This extension is a port of sd-dynamic-prompt to ComfyUI."
117
+ },
118
+ {
119
+ "id":"https://github.com/kwaroran/abg-comfyui",
120
+ "tags":"abg, background remover",
121
+ "description": "A Anime Background Remover node for comfyui, based on this hf space, works same as AGB extention in automatic1111."
122
+ },
123
+ {
124
+ "id":"https://github.com/Gourieff/comfyui-reactor-node",
125
+ "tags":"reactor, sd-webui-roop-nsfw",
126
+ "description": "This is a ported version of ComfyUI for the sd-webui-roop-nsfw extension."
127
+ },
128
+ {
129
+ "id":"https://github.com/laksjdjf/cgem156-ComfyUI",
130
+ "tags":"regional prompt, latent couple, prompt",
131
+ "description": "This custom nodes provide a functionality similar to regional prompts, offering couple features at the attention level."
132
+ },
133
+ {
134
+ "id":"https://github.com/FizzleDorf/ComfyUI_FizzNodes",
135
+ "tags":"deforum",
136
+ "description": "This custom nodes provide functionality that assists in animation creation, similar to deforum."
137
+ },
138
+ {
139
+ "id":"https://github.com/seanlynch/comfyui-optical-flow",
140
+ "tags":"deforum, vid2vid",
141
+ "description": "This custom nodes provide functionality that assists in animation creation, similar to deforum."
142
+ },
143
+ {
144
+ "id":"https://github.com/ssitu/ComfyUI_fabric",
145
+ "tags":"fabric",
146
+ "description": "Similar to sd-webui-fabric, this custom nodes provide the functionality of [a/FABRIC](https://github.com/sd-fabric/fabric)."
147
+ },
148
+ {
149
+ "id":"https://github.com/Zuellni/ComfyUI-ExLlama",
150
+ "tags":"ExLlama, prompt, language model",
151
+ "description": "Similar to text-generation-webui, this custom nodes provide the functionality of [a/exllama](https://github.com/turboderp/exllama)."
152
+ },
153
+ {
154
+ "id":"https://github.com/spinagon/ComfyUI-seamless-tiling",
155
+ "tags":"tiling",
156
+ "description": "ComfyUI node for generating seamless textures Replicates 'Tiling' option from A1111"
157
+ },
158
+ {
159
+ "id":"https://github.com/laksjdjf/cd-tuner_negpip-ComfyUI",
160
+ "tags":"cd-tuner, negpip",
161
+ "description": "This extension is a port of the [a/sd-webui-cd-tuner](https://github.com/hako-mikan/sd-webui-cd-tuner)(a.k.a. CD(color/Detail) Tuner )and [a/sd-webui-negpip](https://github.com/hako-mikan/sd-webui-negpip)(a.k.a. NegPiP) extensions of A1111 to ComfyUI."
162
+ },
163
+ {
164
+ "id":"https://github.com/mcmonkeyprojects/sd-dynamic-thresholding",
165
+ "tags":"DT, dynamic thresholding",
166
+ "description": "This custom node is a port of the Dynamic Thresholding extension from A1111 to make it available for use in ComfyUI."
167
+ },
168
+ {
169
+ "id":"https://github.com/hhhzzyang/Comfyui_Lama",
170
+ "tags":"lama, inpainting anything",
171
+ "description": "This extension provides custom nodes developed based on [a/LaMa](https://github.com/advimman/lama) and [a/Inpainting anything](https://github.com/geekyutao/Inpaint-Anything)."
172
+ },
173
+ {
174
+ "id":"https://github.com/mlinmg/ComfyUI-LaMA-Preprocessor",
175
+ "tags":"lama",
176
+ "description": "This extension provides custom nodes for [a/LaMa](https://github.com/advimman/lama) functionality."
177
+ },
178
+ {
179
+ "id":"https://github.com/Haoming02/comfyui-diffusion-cg",
180
+ "tags":"diffusion-cg",
181
+ "description": "This extension provides custom nodes for [a/SD Webui Diffusion Color Grading](https://github.com/Haoming02/sd-webui-diffusion-cg) functionality."
182
+ },
183
+ {
184
+ "id":"https://github.com/asagi4/ComfyUI-CADS",
185
+ "tags":"diffusion-cg",
186
+ "description": "This extension provides custom nodes for [a/sd-webui-cads](https://github.com/v0xie/sd-webui-cads) functionality."
187
+ },
188
+ {
189
+ "id":"https://git.mmaker.moe/mmaker/sd-webui-color-enhance",
190
+ "tags":"color-enhance",
191
+ "description": "This extension supports both A1111 and ComfyUI simultaneously."
192
+ },
193
+ {
194
+ "id":"https://github.com/shiimizu/ComfyUI-TiledDiffusion",
195
+ "tags":"multidiffusion",
196
+ "description": "This extension provides custom nodes for [a/Mixture of Diffusers](https://github.com/albarji/mixture-of-diffusers) and [a/MultiDiffusion](https://github.com/omerbt/MultiDiffusion)"
197
+ },
198
+ {
199
+ "id":"https://github.com/abyz22/image_control",
200
+ "tags":"BMAB",
201
+ "description": "This extension provides some alternative functionalities of the [a/sd-webui-bmab](https://github.com/portu-sim/sd-webui-bmab) extension."
202
+ },
203
+ {
204
+ "id":"https://github.com/blepping/ComfyUI-sonar",
205
+ "tags":"sonar",
206
+ "description": "This extension provides some alternative functionalities of the [a/stable-diffusion-webui-sonar](https://github.com/Kahsolt/stable-diffusion-webui-sonar) extension."
207
+ },
208
+ {
209
+ "id":"https://github.com/AIFSH/ComfyUI-RVC",
210
+ "tags":"sonar",
211
+ "description": "a comfyui custom node for [a/Retrieval-based-Voice-Conversion-WebUI](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI.git), you can Voice-Conversion in comfyui now!"
212
+ },
213
+ {
214
+ "id":"https://github.com/portu-sim/comfyui-bmab",
215
+ "tags":"bmab",
216
+ "description": "a comfyui custom node for [a/sd-webui-bmab](https://github.com/portu-sim/sd-webui-bmab)"
217
+ },
218
+ {
219
+ "id":"https://github.com/ThereforeGames/ComfyUI-Unprompted",
220
+ "tags":"unprompted",
221
+ "description": "This extension is a port of [a/unprompted](https://github.com/ThereforeGames/unprompted)"
222
+ }
223
+ ]
224
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/channels.list.template ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ default::https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main
2
+ recent::https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/node_db/new
3
+ legacy::https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/node_db/legacy
4
+ forked::https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/node_db/forked
5
+ dev::https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/node_db/dev
6
+ tutorial::https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/node_db/tutorial
ComfyUI/custom_nodes/ComfyUI-Manager/check.bat ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+
3
+ python json-checker.py "custom-node-list.json"
4
+ python json-checker.py "model-list.json"
5
+ python json-checker.py "alter-list.json"
6
+ python json-checker.py "extension-node-map.json"
7
+ python json-checker.py "node_db\new\custom-node-list.json"
8
+ python json-checker.py "node_db\new\model-list.json"
9
+ python json-checker.py "node_db\new\extension-node-map.json"
10
+ python json-checker.py "node_db\dev\custom-node-list.json"
11
+ python json-checker.py "node_db\dev\model-list.json"
12
+ python json-checker.py "node_db\dev\extension-node-map.json"
13
+ python json-checker.py "node_db\tutorial\custom-node-list.json"
14
+ python json-checker.py "node_db\tutorial\model-list.json"
15
+ python json-checker.py "node_db\tutorial\extension-node-map.json"
16
+ python json-checker.py "node_db\legacy\custom-node-list.json"
17
+ python json-checker.py "node_db\legacy\model-list.json"
18
+ python json-checker.py "node_db\legacy\extension-node-map.json"
19
+ python json-checker.py "node_db\forked\custom-node-list.json"
20
+ python json-checker.py "node_db\forked\model-list.json"
21
+ python json-checker.py "node_db\forked\extension-node-map.json"
ComfyUI/custom_nodes/ComfyUI-Manager/check.sh ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ echo
4
+ echo CHECK1
5
+
6
+ files=(
7
+ "custom-node-list.json"
8
+ "model-list.json"
9
+ "alter-list.json"
10
+ "extension-node-map.json"
11
+ "github-stats.json"
12
+ "extras.json"
13
+ "node_db/new/custom-node-list.json"
14
+ "node_db/new/model-list.json"
15
+ "node_db/new/extension-node-map.json"
16
+ "node_db/dev/custom-node-list.json"
17
+ "node_db/dev/model-list.json"
18
+ "node_db/dev/extension-node-map.json"
19
+ "node_db/tutorial/custom-node-list.json"
20
+ "node_db/tutorial/model-list.json"
21
+ "node_db/tutorial/extension-node-map.json"
22
+ "node_db/legacy/custom-node-list.json"
23
+ "node_db/legacy/model-list.json"
24
+ "node_db/legacy/extension-node-map.json"
25
+ "node_db/forked/custom-node-list.json"
26
+ "node_db/forked/model-list.json"
27
+ "node_db/forked/extension-node-map.json"
28
+ )
29
+
30
+ for file in "${files[@]}"; do
31
+ python json-checker.py "$file"
32
+ done
33
+
34
+ echo
35
+ echo CHECK2
36
+ find ~/.tmp/default -name "*.py" -print0 | xargs -0 grep -E "crypto|^_A="
37
+
38
+ echo
39
+ echo CHECK3
40
+ find ~/.tmp/default -name "requirements.txt" | xargs grep "^\s*https\\?:"
41
+ find ~/.tmp/default -name "requirements.txt" | xargs grep "\.whl"
42
+
43
+ echo
ComfyUI/custom_nodes/ComfyUI-Manager/cm-cli.py ADDED
@@ -0,0 +1,1277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import traceback
4
+ import json
5
+ import asyncio
6
+ import concurrent
7
+ import threading
8
+ from typing import Optional
9
+
10
+ import typer
11
+ from rich import print
12
+ from typing_extensions import List, Annotated
13
+ import re
14
+ import git
15
+ import importlib
16
+
17
+
18
+ sys.path.append(os.path.dirname(__file__))
19
+ sys.path.append(os.path.join(os.path.dirname(__file__), "glob"))
20
+
21
+ import manager_util
22
+
23
+ # read env vars
24
+ # COMFYUI_FOLDERS_BASE_PATH is not required in cm-cli.py
25
+ # `comfy_path` should be resolved before importing manager_core
26
+ comfy_path = os.environ.get('COMFYUI_PATH')
27
+ if comfy_path is None:
28
+ try:
29
+ import folder_paths
30
+ comfy_path = os.path.join(os.path.dirname(folder_paths.__file__))
31
+ except:
32
+ print("\n[bold yellow]WARN: The `COMFYUI_PATH` environment variable is not set. Assuming `custom_nodes/ComfyUI-Manager/../../` as the ComfyUI path.[/bold yellow]", file=sys.stderr)
33
+ comfy_path = os.path.abspath(os.path.join(manager_util.comfyui_manager_path, '..', '..'))
34
+
35
+ # This should be placed here
36
+ sys.path.append(comfy_path)
37
+
38
+ import utils.extra_config
39
+ import cm_global
40
+ import manager_core as core
41
+ from manager_core import unified_manager
42
+ import cnr_utils
43
+
44
+ comfyui_manager_path = os.path.abspath(os.path.dirname(__file__))
45
+
46
+ cm_global.pip_blacklist = {'torch', 'torchsde', 'torchvision'}
47
+ cm_global.pip_downgrade_blacklist = ['torch', 'torchsde', 'torchvision', 'transformers', 'safetensors', 'kornia']
48
+ cm_global.pip_overrides = {'numpy': 'numpy<2'}
49
+
50
+ if os.path.exists(os.path.join(manager_util.comfyui_manager_path, "pip_overrides.json")):
51
+ with open(os.path.join(manager_util.comfyui_manager_path, "pip_overrides.json"), 'r', encoding="UTF-8", errors="ignore") as json_file:
52
+ cm_global.pip_overrides = json.load(json_file)
53
+
54
+
55
+ if os.path.exists(os.path.join(manager_util.comfyui_manager_path, "pip_blacklist.list")):
56
+ with open(os.path.join(manager_util.comfyui_manager_path, "pip_blacklist.list"), 'r', encoding="UTF-8", errors="ignore") as f:
57
+ for x in f.readlines():
58
+ y = x.strip()
59
+ if y != '':
60
+ cm_global.pip_blacklist.add(y)
61
+
62
+
63
+ def check_comfyui_hash():
64
+ try:
65
+ repo = git.Repo(comfy_path)
66
+ core.comfy_ui_revision = len(list(repo.iter_commits('HEAD')))
67
+ core.comfy_ui_commit_datetime = repo.head.commit.committed_datetime
68
+ except:
69
+ print('[bold yellow]INFO: Frozen ComfyUI mode.[/bold yellow]')
70
+ core.comfy_ui_revision = 0
71
+ core.comfy_ui_commit_datetime = 0
72
+
73
+ cm_global.variables['comfyui.revision'] = core.comfy_ui_revision
74
+
75
+
76
+ check_comfyui_hash() # This is a preparation step for manager_core
77
+ core.check_invalid_nodes()
78
+
79
+
80
+ def read_downgrade_blacklist():
81
+ try:
82
+ import configparser
83
+ config = configparser.ConfigParser(strict=False)
84
+ config.read(core.manager_config.path)
85
+ default_conf = config['default']
86
+
87
+ if 'downgrade_blacklist' in default_conf:
88
+ items = default_conf['downgrade_blacklist'].split(',')
89
+ items = [x.strip() for x in items if x != '']
90
+ cm_global.pip_downgrade_blacklist += items
91
+ cm_global.pip_downgrade_blacklist = list(set(cm_global.pip_downgrade_blacklist))
92
+ except:
93
+ pass
94
+
95
+
96
+ read_downgrade_blacklist() # This is a preparation step for manager_core
97
+
98
+
99
+ class Ctx:
100
+ folder_paths = None
101
+
102
+ def __init__(self):
103
+ self.channel = 'default'
104
+ self.no_deps = False
105
+ self.mode = 'cache'
106
+ self.user_directory = None
107
+ self.custom_nodes_paths = [os.path.join(core.comfy_base_path, 'custom_nodes')]
108
+ self.manager_files_directory = os.path.dirname(__file__)
109
+
110
+ if Ctx.folder_paths is None:
111
+ try:
112
+ Ctx.folder_paths = importlib.import_module('folder_paths')
113
+ except ImportError:
114
+ print("Warning: Unable to import folder_paths module")
115
+
116
+ def set_channel_mode(self, channel, mode):
117
+ if mode is not None:
118
+ self.mode = mode
119
+
120
+ valid_modes = ["remote", "local", "cache"]
121
+ if mode and mode.lower() not in valid_modes:
122
+ typer.echo(
123
+ f"Invalid mode: {mode}. Allowed modes are 'remote', 'local', 'cache'.",
124
+ err=True,
125
+ )
126
+ exit(1)
127
+
128
+ if channel is not None:
129
+ self.channel = channel
130
+
131
+ asyncio.run(unified_manager.reload(cache_mode=self.mode, dont_wait=False))
132
+ asyncio.run(unified_manager.load_nightly(self.channel, self.mode))
133
+
134
+ def set_no_deps(self, no_deps):
135
+ self.no_deps = no_deps
136
+
137
+ def set_user_directory(self, user_directory):
138
+ if user_directory is None:
139
+ return
140
+
141
+ extra_model_paths_yaml = os.path.join(user_directory, 'extra_model_paths.yaml')
142
+ if os.path.exists(extra_model_paths_yaml):
143
+ utils.extra_config.load_extra_path_config(extra_model_paths_yaml)
144
+
145
+ core.update_user_directory(user_directory)
146
+
147
+ if os.path.exists(core.manager_pip_overrides_path):
148
+ with open(core.manager_pip_overrides_path, 'r', encoding="UTF-8", errors="ignore") as json_file:
149
+ cm_global.pip_overrides = json.load(json_file)
150
+ cm_global.pip_overrides = {'numpy': 'numpy<2'}
151
+
152
+ if os.path.exists(core.manager_pip_blacklist_path):
153
+ with open(core.manager_pip_blacklist_path, 'r', encoding="UTF-8", errors="ignore") as f:
154
+ for x in f.readlines():
155
+ y = x.strip()
156
+ if y != '':
157
+ cm_global.pip_blacklist.add(y)
158
+
159
+ def update_custom_nodes_dir(self, target_dir):
160
+ import folder_paths
161
+ a, b = folder_paths.folder_names_and_paths['custom_nodes']
162
+ folder_paths.folder_names_and_paths['custom_nodes'] = [os.path.abspath(target_dir)], set()
163
+
164
+ @staticmethod
165
+ def get_startup_scripts_path():
166
+ return os.path.join(core.manager_startup_script_path, "install-scripts.txt")
167
+
168
+ @staticmethod
169
+ def get_restore_snapshot_path():
170
+ return os.path.join(core.manager_startup_script_path, "restore-snapshot.json")
171
+
172
+ @staticmethod
173
+ def get_snapshot_path():
174
+ return core.manager_snapshot_path
175
+
176
+ @staticmethod
177
+ def get_custom_nodes_paths():
178
+ if Ctx.folder_paths is None:
179
+ print("Error: folder_paths module is not available")
180
+ return []
181
+ return Ctx.folder_paths.get_folder_paths('custom_nodes')
182
+
183
+
184
+ cmd_ctx = Ctx()
185
+
186
+
187
+ def install_node(node_spec_str, is_all=False, cnt_msg=''):
188
+ if core.is_valid_url(node_spec_str):
189
+ # install via urls
190
+ res = asyncio.run(core.gitclone_install(node_spec_str, no_deps=cmd_ctx.no_deps))
191
+ if not res.result:
192
+ print(res.msg)
193
+ print(f"[bold red]ERROR: An error occurred while installing '{node_spec_str}'.[/bold red]")
194
+ else:
195
+ print(f"{cnt_msg} [INSTALLED] {node_spec_str:50}")
196
+ else:
197
+ node_spec = unified_manager.resolve_node_spec(node_spec_str)
198
+
199
+ if node_spec is None:
200
+ return
201
+
202
+ node_name, version_spec, is_specified = node_spec
203
+
204
+ # NOTE: install node doesn't allow update if version is not specified
205
+ if not is_specified:
206
+ version_spec = None
207
+
208
+ res = asyncio.run(unified_manager.install_by_id(node_name, version_spec, cmd_ctx.channel, cmd_ctx.mode, instant_execution=True, no_deps=cmd_ctx.no_deps))
209
+
210
+ if res.action == 'skip':
211
+ print(f"{cnt_msg} [ SKIP ] {node_name:50} => Already installed")
212
+ elif res.action == 'enable':
213
+ print(f"{cnt_msg} [ ENABLED ] {node_name:50}")
214
+ elif res.action == 'install-git' and res.target == 'nightly':
215
+ print(f"{cnt_msg} [INSTALLED] {node_name:50}[NIGHTLY]")
216
+ elif res.action == 'install-git' and res.target == 'unknown':
217
+ print(f"{cnt_msg} [INSTALLED] {node_name:50}[UNKNOWN]")
218
+ elif res.action == 'install-cnr' and res.result:
219
+ print(f"{cnt_msg} [INSTALLED] {node_name:50}[{res.target}]")
220
+ elif res.action == 'switch-cnr' and res.result:
221
+ print(f"{cnt_msg} [INSTALLED] {node_name:50}[{res.target}]")
222
+ elif (res.action == 'switch-cnr' or res.action == 'install-cnr') and not res.result and node_name in unified_manager.cnr_map:
223
+ print(f"\nAvailable version of '{node_name}'")
224
+ show_versions(node_name)
225
+ print("")
226
+ else:
227
+ print(f"[bold red]ERROR: An error occurred while installing '{node_name}'.\n{res.msg}[/bold red]")
228
+
229
+
230
+ def reinstall_node(node_spec_str, is_all=False, cnt_msg=''):
231
+ node_spec = unified_manager.resolve_node_spec(node_spec_str)
232
+
233
+ node_name, version_spec, _ = node_spec
234
+
235
+ unified_manager.unified_uninstall(node_name, version_spec == 'unknown')
236
+ install_node(node_name, is_all=is_all, cnt_msg=cnt_msg)
237
+
238
+
239
+ def fix_node(node_spec_str, is_all=False, cnt_msg=''):
240
+ node_spec = unified_manager.resolve_node_spec(node_spec_str, guess_mode='active')
241
+
242
+ if node_spec is None:
243
+ if not is_all:
244
+ if unified_manager.resolve_node_spec(node_spec_str, guess_mode='inactive') is not None:
245
+ print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Disabled")
246
+ else:
247
+ print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Not installed")
248
+
249
+ return
250
+
251
+ node_name, version_spec, _ = node_spec
252
+
253
+ print(f"{cnt_msg} [ FIXING ]: {node_name:50}[{version_spec}]")
254
+ res = unified_manager.unified_fix(node_name, version_spec, no_deps=cmd_ctx.no_deps)
255
+
256
+ if not res.result:
257
+ print(f"[bold red]ERROR: f{res.msg}[/bold red]")
258
+
259
+
260
+ def uninstall_node(node_spec_str: str, is_all: bool = False, cnt_msg: str = ''):
261
+ spec = node_spec_str.split('@')
262
+ if len(spec) == 2 and spec[1] == 'unknown':
263
+ node_name = spec[0]
264
+ is_unknown = True
265
+ else:
266
+ node_name = spec[0]
267
+ is_unknown = False
268
+
269
+ res = unified_manager.unified_uninstall(node_name, is_unknown)
270
+ if len(spec) == 1 and res.action == 'skip' and not is_unknown:
271
+ res = unified_manager.unified_uninstall(node_name, True)
272
+
273
+ if res.action == 'skip':
274
+ print(f"{cnt_msg} [ SKIPPED ]: {node_name:50} => Not installed")
275
+
276
+ elif res.result:
277
+ print(f"{cnt_msg} [UNINSTALLED] {node_name:50}")
278
+ else:
279
+ print(f"ERROR: An error occurred while uninstalling '{node_name}'.")
280
+
281
+
282
+ def update_node(node_spec_str, is_all=False, cnt_msg=''):
283
+ node_spec = unified_manager.resolve_node_spec(node_spec_str, 'active')
284
+
285
+ if node_spec is None:
286
+ if unified_manager.resolve_node_spec(node_spec_str, 'inactive'):
287
+ print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Disabled")
288
+ else:
289
+ print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Not installed")
290
+ return None
291
+
292
+ node_name, version_spec, _ = node_spec
293
+
294
+ res = unified_manager.unified_update(node_name, version_spec, no_deps=cmd_ctx.no_deps, return_postinstall=True)
295
+
296
+ if not res.result:
297
+ print(f"ERROR: An error occurred while updating '{node_name}'.")
298
+ elif res.action == 'skip':
299
+ print(f"{cnt_msg} [ SKIPPED ]: {node_name:50} => {res.msg}")
300
+ else:
301
+ print(f"{cnt_msg} [ UPDATED ]: {node_name:50} => ({version_spec} -> {res.target})")
302
+
303
+ return res.with_target(f'{node_name}@{res.target}')
304
+
305
+
306
+ def update_parallel(nodes):
307
+ is_all = False
308
+ if 'all' in nodes:
309
+ is_all = True
310
+ nodes = []
311
+ for x in unified_manager.active_nodes.keys():
312
+ nodes.append(x)
313
+ for x in unified_manager.unknown_active_nodes.keys():
314
+ nodes.append(x+"@unknown")
315
+ else:
316
+ nodes = [x for x in nodes if x.lower() not in ['comfy', 'comfyui']]
317
+
318
+ total = len(nodes)
319
+
320
+ lock = threading.Lock()
321
+ processed = []
322
+
323
+ i = 0
324
+
325
+ def process_custom_node(x):
326
+ nonlocal i
327
+ nonlocal processed
328
+
329
+ with lock:
330
+ i += 1
331
+
332
+ try:
333
+ res = update_node(x, is_all=is_all, cnt_msg=f'{i}/{total}')
334
+ with lock:
335
+ processed.append(res)
336
+ except Exception as e:
337
+ print(f"ERROR: {e}")
338
+ traceback.print_exc()
339
+
340
+ with concurrent.futures.ThreadPoolExecutor(4) as executor:
341
+ for item in nodes:
342
+ executor.submit(process_custom_node, item)
343
+
344
+ i = 1
345
+ for res in processed:
346
+ if res is not None:
347
+ print(f"[{i}/{total}] Post update: {res.target}")
348
+ if res.postinstall is not None:
349
+ res.postinstall()
350
+ i += 1
351
+
352
+
353
+ def update_comfyui():
354
+ res = core.update_path(comfy_path, instant_execution=True)
355
+ if res == 'fail':
356
+ print("Updating ComfyUI has failed.")
357
+ elif res == 'updated':
358
+ print("ComfyUI is updated.")
359
+ else:
360
+ print("ComfyUI is already up to date.")
361
+
362
+
363
+ def enable_node(node_spec_str, is_all=False, cnt_msg=''):
364
+ if unified_manager.resolve_node_spec(node_spec_str, guess_mode='active') is not None:
365
+ print(f"{cnt_msg} [ SKIP ] {node_spec_str:50} => Already enabled")
366
+ return
367
+
368
+ node_spec = unified_manager.resolve_node_spec(node_spec_str, guess_mode='inactive')
369
+
370
+ if node_spec is None:
371
+ print(f"{cnt_msg} [ SKIP ] {node_spec_str:50} => Not found")
372
+ return
373
+
374
+ node_name, version_spec, _ = node_spec
375
+
376
+ res = unified_manager.unified_enable(node_name, version_spec)
377
+
378
+ if res.action == 'skip':
379
+ print(f"{cnt_msg} [ SKIP ] {node_name:50} => {res.msg}")
380
+ elif res.result:
381
+ print(f"{cnt_msg} [ENABLED] {node_name:50}")
382
+ else:
383
+ print(f"{cnt_msg} [ FAIL ] {node_name:50} => {res.msg}")
384
+
385
+
386
+ def disable_node(node_spec_str: str, is_all=False, cnt_msg=''):
387
+ if 'comfyui-manager' in node_spec_str.lower():
388
+ return
389
+
390
+ node_spec = unified_manager.resolve_node_spec(node_spec_str, guess_mode='active')
391
+
392
+ if node_spec is None:
393
+ if unified_manager.resolve_node_spec(node_spec_str, guess_mode='inactive') is not None:
394
+ print(f"{cnt_msg} [ SKIP ] {node_spec_str:50} => Already disabled")
395
+ else:
396
+ print(f"{cnt_msg} [ SKIP ] {node_spec_str:50} => Not found")
397
+ return
398
+
399
+ node_name, version_spec, _ = node_spec
400
+
401
+ res = unified_manager.unified_disable(node_name, version_spec == 'unknown')
402
+
403
+ if res.action == 'skip':
404
+ print(f"{cnt_msg} [ SKIP ] {node_name:50} => {res.msg}")
405
+ elif res.result:
406
+ print(f"{cnt_msg} [DISABLED] {node_name:50}")
407
+ else:
408
+ print(f"{cnt_msg} [ FAIL ] {node_name:50} => {res.msg}")
409
+
410
+
411
+ def show_list(kind, simple=False):
412
+ custom_nodes = asyncio.run(unified_manager.get_custom_nodes(channel=cmd_ctx.channel, mode=cmd_ctx.mode))
413
+
414
+ # collect not-installed unknown nodes
415
+ not_installed_unknown_nodes = []
416
+ repo_unknown = {}
417
+
418
+ for k, v in custom_nodes.items():
419
+ if 'cnr_latest' not in v:
420
+ if len(v['files']) == 1:
421
+ repo_url = v['files'][0]
422
+ node_name = repo_url.split('/')[-1]
423
+ if node_name not in unified_manager.unknown_inactive_nodes and node_name not in unified_manager.unknown_active_nodes:
424
+ not_installed_unknown_nodes.append(v)
425
+ else:
426
+ repo_unknown[node_name] = v
427
+
428
+ processed = {}
429
+ unknown_processed = []
430
+
431
+ flag = kind in ['all', 'cnr', 'installed', 'enabled']
432
+ for k, v in unified_manager.active_nodes.items():
433
+ if flag:
434
+ cnr = unified_manager.cnr_map[k]
435
+ processed[k] = "[ ENABLED ] ", cnr['name'], k, cnr['publisher']['name'], v[0]
436
+ else:
437
+ processed[k] = None
438
+
439
+ if flag and kind != 'cnr':
440
+ for k, v in unified_manager.unknown_active_nodes.items():
441
+ item = repo_unknown.get(k)
442
+
443
+ if item is None:
444
+ continue
445
+
446
+ log_item = "[ ENABLED ] ", item['title'], k, item['author']
447
+ unknown_processed.append(log_item)
448
+
449
+ flag = kind in ['all', 'cnr', 'installed', 'disabled']
450
+ for k, v in unified_manager.cnr_inactive_nodes.items():
451
+ if k in processed:
452
+ continue
453
+
454
+ if flag:
455
+ cnr = unified_manager.cnr_map[k]
456
+ processed[k] = "[ DISABLED ] ", cnr['name'], k, cnr['publisher']['name'], ", ".join(list(v.keys()))
457
+ else:
458
+ processed[k] = None
459
+
460
+ for k, v in unified_manager.nightly_inactive_nodes.items():
461
+ if k in processed:
462
+ continue
463
+
464
+ if flag:
465
+ cnr = unified_manager.cnr_map[k]
466
+ processed[k] = "[ DISABLED ] ", cnr['name'], k, cnr['publisher']['name'], 'nightly'
467
+ else:
468
+ processed[k] = None
469
+
470
+ if flag and kind != 'cnr':
471
+ for k, v in unified_manager.unknown_inactive_nodes.items():
472
+ item = repo_unknown.get(k)
473
+
474
+ if item is None:
475
+ continue
476
+
477
+ log_item = "[ DISABLED ] ", item['title'], k, item['author']
478
+ unknown_processed.append(log_item)
479
+
480
+ flag = kind in ['all', 'cnr', 'not-installed']
481
+ for k, v in unified_manager.cnr_map.items():
482
+ if k in processed:
483
+ continue
484
+
485
+ if flag:
486
+ cnr = unified_manager.cnr_map[k]
487
+ ver_spec = v['latest_version']['version'] if 'latest_version' in v else '0.0.0'
488
+ processed[k] = "[ NOT INSTALLED ] ", cnr['name'], k, cnr['publisher']['name'], ver_spec
489
+ else:
490
+ processed[k] = None
491
+
492
+ if flag and kind != 'cnr':
493
+ for x in not_installed_unknown_nodes:
494
+ if len(x['files']) == 1:
495
+ node_id = os.path.basename(x['files'][0])
496
+ log_item = "[ NOT INSTALLED ] ", x['title'], node_id, x['author']
497
+ unknown_processed.append(log_item)
498
+
499
+ for x in processed.values():
500
+ if x is None:
501
+ continue
502
+
503
+ prefix, title, short_id, author, ver_spec = x
504
+ if simple:
505
+ print(title+'@'+ver_spec)
506
+ else:
507
+ print(f"{prefix} {title:50} {short_id:30} (author: {author:20}) \\[{ver_spec}]")
508
+
509
+ for x in unknown_processed:
510
+ prefix, title, short_id, author = x
511
+ if simple:
512
+ print(title+'@unknown')
513
+ else:
514
+ print(f"{prefix} {title:50} {short_id:30} (author: {author:20}) [UNKNOWN]")
515
+
516
+
517
+ async def show_snapshot(simple_mode=False):
518
+ json_obj = await core.get_current_snapshot()
519
+
520
+ if simple_mode:
521
+ print(f"[{json_obj['comfyui']}] comfyui")
522
+ for k, v in json_obj['git_custom_nodes'].items():
523
+ print(f"[{v['hash']}] {k}")
524
+ for v in json_obj['file_custom_nodes']:
525
+ print(f"[ N/A ] {v['filename']}")
526
+
527
+ else:
528
+ formatted_json = json.dumps(json_obj, ensure_ascii=False, indent=4)
529
+ print(formatted_json)
530
+
531
+
532
+ def show_snapshot_list(simple_mode=False):
533
+ snapshot_path = cmd_ctx.get_snapshot_path()
534
+
535
+ files = os.listdir(snapshot_path)
536
+ json_files = [x for x in files if x.endswith('.json')]
537
+ for x in sorted(json_files):
538
+ print(x)
539
+
540
+
541
+ def cancel():
542
+ if os.path.exists(cmd_ctx.get_startup_scripts_path()):
543
+ os.remove(cmd_ctx.get_startup_scripts_path())
544
+
545
+ if os.path.exists(cmd_ctx.get_restore_snapshot_path()):
546
+ os.remove(cmd_ctx.get_restore_snapshot_path())
547
+
548
+
549
+ async def auto_save_snapshot():
550
+ path = await core.save_snapshot_with_postfix('cli-autosave')
551
+ print(f"Current snapshot is saved as `{path}`")
552
+
553
+
554
+ def get_all_installed_node_specs():
555
+ res = []
556
+ processed = set()
557
+ for k, v in unified_manager.active_nodes.items():
558
+ node_spec_str = f"{k}@{v[0]}"
559
+ res.append(node_spec_str)
560
+ processed.add(k)
561
+
562
+ for k in unified_manager.cnr_inactive_nodes.keys():
563
+ if k in processed:
564
+ continue
565
+
566
+ latest = unified_manager.get_from_cnr_inactive_nodes(k)
567
+ if latest is not None:
568
+ node_spec_str = f"{k}@{str(latest[0])}"
569
+ res.append(node_spec_str)
570
+
571
+ for k in unified_manager.nightly_inactive_nodes.keys():
572
+ if k in processed:
573
+ continue
574
+
575
+ node_spec_str = f"{k}@nightly"
576
+ res.append(node_spec_str)
577
+
578
+ for k in unified_manager.unknown_active_nodes.keys():
579
+ node_spec_str = f"{k}@unknown"
580
+ res.append(node_spec_str)
581
+
582
+ for k in unified_manager.unknown_inactive_nodes.keys():
583
+ node_spec_str = f"{k}@unknown"
584
+ res.append(node_spec_str)
585
+
586
+ return res
587
+
588
+
589
+ def for_each_nodes(nodes, act, allow_all=True):
590
+ is_all = False
591
+ if allow_all and 'all' in nodes:
592
+ is_all = True
593
+ nodes = get_all_installed_node_specs()
594
+ else:
595
+ nodes = [x for x in nodes if x.lower() not in ['comfy', 'comfyui', 'all']]
596
+
597
+ total = len(nodes)
598
+ i = 1
599
+ for x in nodes:
600
+ try:
601
+ act(x, is_all=is_all, cnt_msg=f'{i}/{total}')
602
+ except Exception as e:
603
+ print(f"ERROR: {e}")
604
+ traceback.print_exc()
605
+ i += 1
606
+
607
+
608
+ app = typer.Typer()
609
+
610
+
611
+ @app.command(help="Display help for commands")
612
+ def help(ctx: typer.Context):
613
+ print(ctx.find_root().get_help())
614
+ ctx.exit(0)
615
+
616
+
617
+ @app.command(help="Install custom nodes")
618
+ def install(
619
+ nodes: List[str] = typer.Argument(
620
+ ..., help="List of custom nodes to install"
621
+ ),
622
+ channel: Annotated[
623
+ str,
624
+ typer.Option(
625
+ show_default=False,
626
+ help="Specify the operation mode"
627
+ ),
628
+ ] = None,
629
+ mode: str = typer.Option(
630
+ None,
631
+ help="[remote|local|cache]"
632
+ ),
633
+ no_deps: Annotated[
634
+ Optional[bool],
635
+ typer.Option(
636
+ "--no-deps",
637
+ show_default=False,
638
+ help="Skip installing any Python dependencies",
639
+ ),
640
+ ] = False,
641
+ user_directory: str = typer.Option(
642
+ None,
643
+ help="user directory"
644
+ ),
645
+ ):
646
+ cmd_ctx.set_user_directory(user_directory)
647
+ cmd_ctx.set_channel_mode(channel, mode)
648
+ cmd_ctx.set_no_deps(no_deps)
649
+
650
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
651
+ for_each_nodes(nodes, act=install_node)
652
+ pip_fixer.fix_broken()
653
+
654
+
655
+ @app.command(help="Reinstall custom nodes")
656
+ def reinstall(
657
+ nodes: List[str] = typer.Argument(
658
+ ..., help="List of custom nodes to reinstall"
659
+ ),
660
+ channel: Annotated[
661
+ str,
662
+ typer.Option(
663
+ show_default=False,
664
+ help="Specify the operation mode"
665
+ ),
666
+ ] = None,
667
+ mode: str = typer.Option(
668
+ None,
669
+ help="[remote|local|cache]"
670
+ ),
671
+ no_deps: Annotated[
672
+ Optional[bool],
673
+ typer.Option(
674
+ "--no-deps",
675
+ show_default=False,
676
+ help="Skip installing any Python dependencies",
677
+ ),
678
+ ] = False,
679
+ user_directory: str = typer.Option(
680
+ None,
681
+ help="user directory"
682
+ ),
683
+ ):
684
+ cmd_ctx.set_user_directory(user_directory)
685
+ cmd_ctx.set_channel_mode(channel, mode)
686
+ cmd_ctx.set_no_deps(no_deps)
687
+
688
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
689
+ for_each_nodes(nodes, act=reinstall_node)
690
+ pip_fixer.fix_broken()
691
+
692
+
693
+ @app.command(help="Uninstall custom nodes")
694
+ def uninstall(
695
+ nodes: List[str] = typer.Argument(
696
+ ..., help="List of custom nodes to uninstall"
697
+ ),
698
+ channel: Annotated[
699
+ str,
700
+ typer.Option(
701
+ show_default=False,
702
+ help="Specify the operation mode"
703
+ ),
704
+ ] = None,
705
+ mode: str = typer.Option(
706
+ None,
707
+ help="[remote|local|cache]"
708
+ ),
709
+ ):
710
+ cmd_ctx.set_channel_mode(channel, mode)
711
+ for_each_nodes(nodes, act=uninstall_node)
712
+
713
+
714
+ @app.command(help="Update custom nodes")
715
+ def update(
716
+ nodes: List[str] = typer.Argument(
717
+ ...,
718
+ help="[all|List of custom nodes to update]"
719
+ ),
720
+ channel: Annotated[
721
+ str,
722
+ typer.Option(
723
+ show_default=False,
724
+ help="Specify the operation mode"
725
+ ),
726
+ ] = None,
727
+ mode: str = typer.Option(
728
+ None,
729
+ help="[remote|local|cache]"
730
+ ),
731
+ user_directory: str = typer.Option(
732
+ None,
733
+ help="user directory"
734
+ ),
735
+ ):
736
+ cmd_ctx.set_user_directory(user_directory)
737
+ cmd_ctx.set_channel_mode(channel, mode)
738
+
739
+ if 'all' in nodes:
740
+ asyncio.run(auto_save_snapshot())
741
+
742
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
743
+
744
+ for x in nodes:
745
+ if x.lower() in ['comfyui', 'comfy', 'all']:
746
+ update_comfyui()
747
+ break
748
+
749
+ update_parallel(nodes)
750
+ pip_fixer.fix_broken()
751
+
752
+
753
+ @app.command(help="Disable custom nodes")
754
+ def disable(
755
+ nodes: List[str] = typer.Argument(
756
+ ...,
757
+ help="[all|List of custom nodes to disable]"
758
+ ),
759
+ channel: Annotated[
760
+ str,
761
+ typer.Option(
762
+ show_default=False,
763
+ help="Specify the operation mode"
764
+ ),
765
+ ] = None,
766
+ mode: str = typer.Option(
767
+ None,
768
+ help="[remote|local|cache]"
769
+ ),
770
+ user_directory: str = typer.Option(
771
+ None,
772
+ help="user directory"
773
+ ),
774
+ ):
775
+ cmd_ctx.set_user_directory(user_directory)
776
+ cmd_ctx.set_channel_mode(channel, mode)
777
+
778
+ if 'all' in nodes:
779
+ asyncio.run(auto_save_snapshot())
780
+
781
+ for_each_nodes(nodes, disable_node, allow_all=True)
782
+
783
+
784
+ @app.command(help="Enable custom nodes")
785
+ def enable(
786
+ nodes: List[str] = typer.Argument(
787
+ ...,
788
+ help="[all|List of custom nodes to enable]"
789
+ ),
790
+ channel: Annotated[
791
+ str,
792
+ typer.Option(
793
+ show_default=False,
794
+ help="Specify the operation mode"
795
+ ),
796
+ ] = None,
797
+ mode: str = typer.Option(
798
+ None,
799
+ help="[remote|local|cache]"
800
+ ),
801
+ user_directory: str = typer.Option(
802
+ None,
803
+ help="user directory"
804
+ ),
805
+ ):
806
+ cmd_ctx.set_user_directory(user_directory)
807
+ cmd_ctx.set_channel_mode(channel, mode)
808
+
809
+ if 'all' in nodes:
810
+ asyncio.run(auto_save_snapshot())
811
+
812
+ for_each_nodes(nodes, enable_node, allow_all=True)
813
+
814
+
815
+ @app.command(help="Fix dependencies of custom nodes")
816
+ def fix(
817
+ nodes: List[str] = typer.Argument(
818
+ ...,
819
+ help="[all|List of custom nodes to fix]"
820
+ ),
821
+ channel: Annotated[
822
+ str,
823
+ typer.Option(
824
+ show_default=False,
825
+ help="Specify the operation mode"
826
+ ),
827
+ ] = None,
828
+ mode: str = typer.Option(
829
+ None,
830
+ help="[remote|local|cache]"
831
+ ),
832
+ user_directory: str = typer.Option(
833
+ None,
834
+ help="user directory"
835
+ ),
836
+ ):
837
+ cmd_ctx.set_user_directory(user_directory)
838
+ cmd_ctx.set_channel_mode(channel, mode)
839
+
840
+ if 'all' in nodes:
841
+ asyncio.run(auto_save_snapshot())
842
+
843
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
844
+ for_each_nodes(nodes, fix_node, allow_all=True)
845
+ pip_fixer.fix_broken()
846
+
847
+
848
+ @app.command("show-versions", help="Show all available versions of the node")
849
+ def show_versions(node_name: str):
850
+ versions = cnr_utils.all_versions_of_node(node_name)
851
+ if versions is None:
852
+ print(f"Node not found in Comfy Registry: {node_name}")
853
+
854
+ for x in versions:
855
+ print(f"[{x['createdAt'][:10]}] {x['version']} -- {x['changelog']}")
856
+
857
+
858
+ @app.command("show", help="Show node list")
859
+ def show(
860
+ arg: str = typer.Argument(
861
+ help="[installed|enabled|not-installed|disabled|all|cnr|snapshot|snapshot-list]"
862
+ ),
863
+ channel: Annotated[
864
+ str,
865
+ typer.Option(
866
+ show_default=False,
867
+ help="Specify the operation mode"
868
+ ),
869
+ ] = None,
870
+ mode: str = typer.Option(
871
+ None,
872
+ help="[remote|local|cache]"
873
+ ),
874
+ user_directory: str = typer.Option(
875
+ None,
876
+ help="user directory"
877
+ ),
878
+ ):
879
+ valid_commands = [
880
+ "installed",
881
+ "enabled",
882
+ "not-installed",
883
+ "disabled",
884
+ "all",
885
+ "cnr",
886
+ "snapshot",
887
+ "snapshot-list",
888
+ ]
889
+ if arg not in valid_commands:
890
+ typer.echo(f"Invalid command: `show {arg}`", err=True)
891
+ exit(1)
892
+
893
+ cmd_ctx.set_user_directory(user_directory)
894
+ cmd_ctx.set_channel_mode(channel, mode)
895
+ if arg == 'snapshot':
896
+ show_snapshot()
897
+ elif arg == 'snapshot-list':
898
+ show_snapshot_list()
899
+ else:
900
+ show_list(arg)
901
+
902
+
903
+ @app.command("simple-show", help="Show node list (simple mode)")
904
+ def simple_show(
905
+ arg: str = typer.Argument(
906
+ help="[installed|enabled|not-installed|disabled|all|snapshot|snapshot-list]"
907
+ ),
908
+ channel: Annotated[
909
+ str,
910
+ typer.Option(
911
+ show_default=False,
912
+ help="Specify the operation mode"
913
+ ),
914
+ ] = None,
915
+ mode: str = typer.Option(
916
+ None,
917
+ help="[remote|local|cache]"
918
+ ),
919
+ user_directory: str = typer.Option(
920
+ None,
921
+ help="user directory"
922
+ ),
923
+ ):
924
+ valid_commands = [
925
+ "installed",
926
+ "enabled",
927
+ "not-installed",
928
+ "disabled",
929
+ "all",
930
+ "snapshot",
931
+ "snapshot-list",
932
+ ]
933
+ if arg not in valid_commands:
934
+ typer.echo(f"[bold red]Invalid command: `show {arg}`[/bold red]", err=True)
935
+ exit(1)
936
+
937
+ cmd_ctx.set_user_directory(user_directory)
938
+ cmd_ctx.set_channel_mode(channel, mode)
939
+
940
+ if arg == 'snapshot':
941
+ show_snapshot(True)
942
+ elif arg == 'snapshot-list':
943
+ show_snapshot_list(True)
944
+ else:
945
+ show_list(arg, True)
946
+
947
+
948
+ @app.command('cli-only-mode', help="Set whether to use ComfyUI-Manager in CLI-only mode.")
949
+ def cli_only_mode(
950
+ mode: str = typer.Argument(
951
+ ..., help="[enable|disable]"
952
+ ),
953
+ user_directory: str = typer.Option(
954
+ None,
955
+ help="user directory"
956
+ )
957
+ ):
958
+ cmd_ctx.set_user_directory(user_directory)
959
+ cli_mode_flag = os.path.join(cmd_ctx.manager_files_directory, '.enable-cli-only-mode')
960
+
961
+ if mode.lower() == 'enable':
962
+ with open(cli_mode_flag, 'w'):
963
+ pass
964
+ print("\nINFO: `cli-only-mode` is enabled\n")
965
+ elif mode.lower() == 'disable':
966
+ if os.path.exists(cli_mode_flag):
967
+ os.remove(cli_mode_flag)
968
+ print("\nINFO: `cli-only-mode` is disabled\n")
969
+ else:
970
+ print(f"\n[bold red]Invalid value for cli-only-mode: {mode}[/bold red]\n")
971
+ exit(1)
972
+
973
+
974
+ @app.command(
975
+ "deps-in-workflow", help="Generate dependencies file from workflow (.json/.png)"
976
+ )
977
+ def deps_in_workflow(
978
+ workflow: Annotated[
979
+ str, typer.Option(show_default=False, help="Workflow file (.json/.png)")
980
+ ],
981
+ output: Annotated[
982
+ str, typer.Option(show_default=False, help="Output file (.json)")
983
+ ],
984
+ channel: Annotated[
985
+ str,
986
+ typer.Option(
987
+ show_default=False,
988
+ help="Specify the operation mode"
989
+ ),
990
+ ] = None,
991
+ mode: str = typer.Option(
992
+ None,
993
+ help="[remote|local|cache]"
994
+ ),
995
+ user_directory: str = typer.Option(
996
+ None,
997
+ help="user directory"
998
+ )
999
+ ):
1000
+ cmd_ctx.set_user_directory(user_directory)
1001
+ cmd_ctx.set_channel_mode(channel, mode)
1002
+
1003
+ input_path = workflow
1004
+ output_path = output
1005
+
1006
+ if not os.path.exists(input_path):
1007
+ print(f"[bold red]File not found: {input_path}[/bold red]")
1008
+ exit(1)
1009
+
1010
+ used_exts, unknown_nodes = asyncio.run(core.extract_nodes_from_workflow(input_path, mode=cmd_ctx.mode, channel_url=cmd_ctx.channel))
1011
+
1012
+ custom_nodes = {}
1013
+ for x in used_exts:
1014
+ custom_nodes[x] = {'state': core.simple_check_custom_node(x),
1015
+ 'hash': '-'
1016
+ }
1017
+
1018
+ res = {
1019
+ 'custom_nodes': custom_nodes,
1020
+ 'unknown_nodes': list(unknown_nodes)
1021
+ }
1022
+
1023
+ with open(output_path, "w", encoding='utf-8') as output_file:
1024
+ json.dump(res, output_file, indent=4)
1025
+
1026
+ print(f"Workflow dependencies are being saved into {output_path}.")
1027
+
1028
+
1029
+ @app.command("save-snapshot", help="Save a snapshot of the current ComfyUI environment. If output path isn't provided. Save to ComfyUI-Manager/snapshots path.")
1030
+ def save_snapshot(
1031
+ output: Annotated[
1032
+ str,
1033
+ typer.Option(
1034
+ show_default=False, help="Specify the output file path. (.json/.yaml)"
1035
+ ),
1036
+ ] = None,
1037
+ user_directory: str = typer.Option(
1038
+ None,
1039
+ help="user directory"
1040
+ ),
1041
+ full_snapshot: Annotated[
1042
+ bool,
1043
+ typer.Option(
1044
+ show_default=False, help="If the snapshot should include custom node, ComfyUI version and pip versions (default), or only custom node details"
1045
+ ),
1046
+ ] = True,
1047
+ ):
1048
+ cmd_ctx.set_user_directory(user_directory)
1049
+
1050
+ if output is not None:
1051
+ if(not output.endswith('.json') and not output.endswith('.yaml')):
1052
+ print("[bold red]ERROR: output path should be either '.json' or '.yaml' file.[/bold red]")
1053
+ raise typer.Exit(code=1)
1054
+
1055
+ dir_path = os.path.dirname(output)
1056
+
1057
+ if(dir_path != '' and not os.path.exists(dir_path)):
1058
+ print(f"[bold red]ERROR: {output} path not exists.[/bold red]")
1059
+ raise typer.Exit(code=1)
1060
+
1061
+ path = asyncio.run(core.save_snapshot_with_postfix('snapshot', output, not full_snapshot))
1062
+ print(f"Current snapshot is saved as `{path}`")
1063
+
1064
+
1065
+ @app.command("restore-snapshot", help="Restore snapshot from snapshot file")
1066
+ def restore_snapshot(
1067
+ snapshot_name: str,
1068
+ pip_non_url: Optional[bool] = typer.Option(
1069
+ default=None,
1070
+ show_default=False,
1071
+ is_flag=True,
1072
+ help="Restore for pip packages registered on PyPI.",
1073
+ ),
1074
+ pip_non_local_url: Optional[bool] = typer.Option(
1075
+ default=None,
1076
+ show_default=False,
1077
+ is_flag=True,
1078
+ help="Restore for pip packages registered at web URLs.",
1079
+ ),
1080
+ pip_local_url: Optional[bool] = typer.Option(
1081
+ default=None,
1082
+ show_default=False,
1083
+ is_flag=True,
1084
+ help="Restore for pip packages specified by local paths.",
1085
+ ),
1086
+ user_directory: str = typer.Option(
1087
+ None,
1088
+ help="user directory"
1089
+ ),
1090
+ restore_to: Optional[str] = typer.Option(
1091
+ None,
1092
+ help="Manually specify the installation path for the custom node. Ignore user directory."
1093
+ )
1094
+ ):
1095
+ cmd_ctx.set_user_directory(user_directory)
1096
+
1097
+ if restore_to:
1098
+ cmd_ctx.update_custom_nodes_dir(restore_to)
1099
+
1100
+ extras = []
1101
+ if pip_non_url:
1102
+ extras.append('--pip-non-url')
1103
+
1104
+ if pip_non_local_url:
1105
+ extras.append('--pip-non-local-url')
1106
+
1107
+ if pip_local_url:
1108
+ extras.append('--pip-local-url')
1109
+
1110
+ print(f"PIPs restore mode: {extras}")
1111
+
1112
+ if os.path.exists(snapshot_name):
1113
+ snapshot_path = os.path.abspath(snapshot_name)
1114
+ else:
1115
+ snapshot_path = os.path.join(cmd_ctx.get_snapshot_path(), snapshot_name)
1116
+ if not os.path.exists(snapshot_path):
1117
+ print(f"[bold red]ERROR: `{snapshot_path}` is not exists.[/bold red]")
1118
+ exit(1)
1119
+
1120
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
1121
+ try:
1122
+ asyncio.run(core.restore_snapshot(snapshot_path, extras))
1123
+ except Exception:
1124
+ print("[bold red]ERROR: Failed to restore snapshot.[/bold red]")
1125
+ traceback.print_exc()
1126
+ raise typer.Exit(code=1)
1127
+ pip_fixer.fix_broken()
1128
+
1129
+
1130
+ @app.command(
1131
+ "restore-dependencies", help="Restore dependencies from whole installed custom nodes."
1132
+ )
1133
+ def restore_dependencies(
1134
+ user_directory: str = typer.Option(
1135
+ None,
1136
+ help="user directory"
1137
+ )
1138
+ ):
1139
+ cmd_ctx.set_user_directory(user_directory)
1140
+
1141
+ node_paths = []
1142
+
1143
+ for base_path in cmd_ctx.get_custom_nodes_paths():
1144
+ for name in os.listdir(base_path):
1145
+ target = os.path.join(base_path, name)
1146
+ if os.path.isdir(target) and not name.endswith('.disabled'):
1147
+ node_paths.append(target)
1148
+
1149
+ total = len(node_paths)
1150
+ i = 1
1151
+
1152
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
1153
+ for x in node_paths:
1154
+ print("----------------------------------------------------------------------------------------------------")
1155
+ print(f"Restoring [{i}/{total}]: {x}")
1156
+ unified_manager.execute_install_script('', x, instant_execution=True)
1157
+ i += 1
1158
+ pip_fixer.fix_broken()
1159
+
1160
+
1161
+ @app.command(
1162
+ "post-install", help="Install dependencies and execute installation script"
1163
+ )
1164
+ def post_install(
1165
+ path: str = typer.Argument(
1166
+ help="path to custom node",
1167
+ )
1168
+ ):
1169
+ path = os.path.expanduser(path)
1170
+
1171
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
1172
+ unified_manager.execute_install_script('', path, instant_execution=True)
1173
+ pip_fixer.fix_broken()
1174
+
1175
+
1176
+ @app.command(
1177
+ "install-deps",
1178
+ help="Install dependencies from dependencies file(.json) or workflow(.png/.json)",
1179
+ )
1180
+ def install_deps(
1181
+ deps: str = typer.Argument(
1182
+ help="Dependency spec file (.json)",
1183
+ ),
1184
+ channel: Annotated[
1185
+ str,
1186
+ typer.Option(
1187
+ show_default=False,
1188
+ help="Specify the operation mode"
1189
+ ),
1190
+ ] = None,
1191
+ mode: str = typer.Option(
1192
+ None,
1193
+ help="[remote|local|cache]"
1194
+ ),
1195
+ user_directory: str = typer.Option(
1196
+ None,
1197
+ help="user directory"
1198
+ ),
1199
+ ):
1200
+ cmd_ctx.set_user_directory(user_directory)
1201
+ cmd_ctx.set_channel_mode(channel, mode)
1202
+ asyncio.run(auto_save_snapshot())
1203
+
1204
+ if not os.path.exists(deps):
1205
+ print(f"[bold red]File not found: {deps}[/bold red]")
1206
+ exit(1)
1207
+ else:
1208
+ with open(deps, 'r', encoding="UTF-8", errors="ignore") as json_file:
1209
+ try:
1210
+ json_obj = json.load(json_file)
1211
+ except:
1212
+ print(f"[bold red]Invalid json file: {deps}[/bold red]")
1213
+ exit(1)
1214
+
1215
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
1216
+ for k in json_obj['custom_nodes'].keys():
1217
+ state = core.simple_check_custom_node(k)
1218
+ if state == 'installed':
1219
+ continue
1220
+ elif state == 'not-installed':
1221
+ asyncio.run(core.gitclone_install(k, instant_execution=True))
1222
+ else: # disabled
1223
+ core.gitclone_set_active([k], False)
1224
+ pip_fixer.fix_broken()
1225
+
1226
+ print("Dependency installation and activation complete.")
1227
+
1228
+
1229
+ @app.command(help="Clear reserved startup action in ComfyUI-Manager")
1230
+ def clear():
1231
+ cancel()
1232
+
1233
+
1234
+ @app.command("export-custom-node-ids", help="Export custom node ids")
1235
+ def export_custom_node_ids(
1236
+ path: str,
1237
+ channel: Annotated[
1238
+ str,
1239
+ typer.Option(
1240
+ show_default=False,
1241
+ help="Specify the operation mode"
1242
+ ),
1243
+ ] = None,
1244
+ mode: str = typer.Option(
1245
+ None,
1246
+ help="[remote|local|cache]"
1247
+ ),
1248
+ user_directory: str = typer.Option(
1249
+ None,
1250
+ help="user directory"
1251
+ ),
1252
+ ):
1253
+ cmd_ctx.set_user_directory(user_directory)
1254
+ cmd_ctx.set_channel_mode(channel, mode)
1255
+
1256
+ with open(path, "w", encoding='utf-8') as output_file:
1257
+ for x in unified_manager.cnr_map.keys():
1258
+ print(x, file=output_file)
1259
+
1260
+ custom_nodes = asyncio.run(unified_manager.get_custom_nodes(channel=cmd_ctx.channel, mode=cmd_ctx.mode))
1261
+ for x in custom_nodes.values():
1262
+ if 'cnr_latest' not in x:
1263
+ if len(x['files']) == 1:
1264
+ repo_url = x['files'][0]
1265
+ node_id = repo_url.split('/')[-1]
1266
+ print(f"{node_id}@unknown", file=output_file)
1267
+
1268
+ if 'id' in x:
1269
+ print(f"{x['id']}@unknown", file=output_file)
1270
+
1271
+
1272
+ if __name__ == '__main__':
1273
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
1274
+ sys.exit(app())
1275
+
1276
+
1277
+ print("")
ComfyUI/custom_nodes/ComfyUI-Manager/cm-cli.sh ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ #!/bin/bash
2
+ python cm-cli.py $*
ComfyUI/custom_nodes/ComfyUI-Manager/components/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ *.json
2
+ *.pack
ComfyUI/custom_nodes/ComfyUI-Manager/custom-node-list.json ADDED
The diff for this file is too large to render. See raw diff
 
ComfyUI/custom_nodes/ComfyUI-Manager/docs/en/cm-cli.md ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `cm-cli`: ComfyUI-Manager CLI
2
+
3
+ `cm-cli` is a tool that allows you to use various functions of ComfyUI-Manager from the command line without launching ComfyUI.
4
+
5
+
6
+ ```
7
+ -= ComfyUI-Manager CLI (V2.24) =-
8
+
9
+
10
+ python cm-cli.py [OPTIONS]
11
+
12
+ OPTIONS:
13
+ [install|reinstall|uninstall|update|disable|enable|fix] node_name ... ?[--channel <channel name>] ?[--mode [remote|local|cache]]
14
+ [update|disable|enable|fix] all ?[--channel <channel name>] ?[--mode [remote|local|cache]]
15
+ [simple-show|show] [installed|enabled|not-installed|disabled|all|snapshot|snapshot-list] ?[--channel <channel name>] ?[--mode [remote|local|cache]]
16
+ save-snapshot ?[--output <snapshot .json/.yaml>]
17
+ restore-snapshot <snapshot .json/.yaml> ?[--pip-non-url] ?[--pip-non-local-url] ?[--pip-local-url]
18
+ cli-only-mode [enable|disable]
19
+ restore-dependencies
20
+ clear
21
+ ```
22
+
23
+ ## How To Use?
24
+ * You can execute it via `python cm-cli.py`.
25
+ * For example, if you want to update all custom nodes:
26
+ * In the ComfyUI-Manager directory, you can execute the command `python cm-cli.py update all`.
27
+ * If running from the ComfyUI directory, you can specify the path to cm-cli.py like this: `python custom_nodes/ComfyUI-Manager/cm-cli.py update all`.
28
+
29
+ ## Prerequisite
30
+ * It must be run in the same Python environment as the one running ComfyUI.
31
+ * If using a venv, you must run it with the venv activated.
32
+ * If using a portable version, and you are in the directory with the run_nvidia_gpu.bat file, you should execute the command as follows:
33
+ `.\python_embeded\python.exe ComfyUI\custom_nodes\ComfyUI-Manager\cm-cli.py update all`
34
+ * The path for ComfyUI can be set with the COMFYUI_PATH environment variable. If omitted, a warning message will appear, and the path will be set relative to the installed location of ComfyUI-Manager:
35
+ ```
36
+ WARN: The `COMFYUI_PATH` environment variable is not set. Assuming `custom_nodes/ComfyUI-Manager/../../` as the ComfyUI path.
37
+ ```
38
+
39
+ ## Features
40
+
41
+ ### 1. --channel, --mode
42
+ * For viewing information and managing custom nodes, you can set the information database through --channel and --mode.
43
+ * For instance, executing the command `python cm-cli.py update all --channel recent --mode remote` will operate based on the latest information from remote rather than local data embedded in the current ComfyUI-Manager repo and will only target the list in the recent channel.
44
+ * --channel, --mode are only available with the commands `simple-show, show, install, uninstall, update, disable, enable, fix`.
45
+
46
+ ### 2. Viewing Management Information
47
+
48
+ `[simple-show|show] [installed|enabled|not-installed|disabled|all|snapshot|snapshot-list] ?[--channel <channel name>] ?[--mode [remote|local|cache]]`
49
+
50
+ * `[show|simple-show]` - `show` provides detailed information, while `simple-show` displays information more simply.
51
+
52
+ Executing a command like `python cm-cli.py show installed` will display detailed information about the installed custom nodes.
53
+
54
+ ```
55
+ -= ComfyUI-Manager CLI (V2.24) =-
56
+
57
+ FETCH DATA from: https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/custom-node-list.json
58
+ [ ENABLED ] ComfyUI-Manager (author: Dr.Lt.Data)
59
+ [ ENABLED ] ComfyUI-Impact-Pack (author: Dr.Lt.Data)
60
+ [ ENABLED ] ComfyUI-Inspire-Pack (author: Dr.Lt.Data)
61
+ [ ENABLED ] ComfyUI_experiments (author: comfyanonymous)
62
+ [ ENABLED ] ComfyUI-SAI_API (author: Stability-AI)
63
+ [ ENABLED ] stability-ComfyUI-nodes (author: Stability-AI)
64
+ [ ENABLED ] comfyui_controlnet_aux (author: Fannovel16)
65
+ [ ENABLED ] ComfyUI-Frame-Interpolation (author: Fannovel16)
66
+ [ DISABLED ] ComfyUI-Loopchain (author: Fannovel16)
67
+ ```
68
+
69
+ Using a command like `python cm-cli.py simple-show installed` will simply display information about the installed custom nodes.
70
+
71
+ ```
72
+ -= ComfyUI-Manager CLI (V2.24) =-
73
+
74
+ FETCH DATA from: https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/custom-node-list.json
75
+ ComfyUI-Manager
76
+ ComfyUI-Impact-Pack
77
+ ComfyUI-Inspire-Pack
78
+ ComfyUI_experiments
79
+ ComfyUI-SAI_API
80
+ stability-ComfyUI-nodes
81
+ comfyui_controlnet_aux
82
+ ComfyUI-Frame-Interpolation
83
+ ComfyUI-Loopchain
84
+ ```
85
+
86
+ `[installed|enabled|not-installed|disabled|all|snapshot|snapshot-list]`
87
+ * `enabled`, `disabled`: Shows nodes that have been enabled or disabled among the installed custom nodes.
88
+ * `installed`: Shows all nodes that have been installed, regardless of whether they are enabled or disabled.
89
+ * `not-installed`: Shows a list of custom nodes that have not been installed.
90
+ * `all`: Shows a list of all custom nodes.
91
+ * `snapshot`: Displays snapshot information of the currently installed custom nodes. When viewed with `show`, it is displayed in JSON format, and with `simple-show`, it is displayed simply, along with the commit hash.
92
+ * `snapshot-list`: Shows a list of snapshot files stored in ComfyUI-Manager/snapshots.
93
+
94
+ ### 3. Managing Custom Nodes
95
+
96
+ `[install|reinstall|uninstall|update|disable|enable|fix] node_name ... ?[--channel <channel name>] ?[--mode [remote|local|cache]]`
97
+
98
+ * You can apply management functions by listing the names of custom nodes, such as `python cm-cli.py install ComfyUI-Impact-Pack ComfyUI-Inspire-Pack ComfyUI_experiments`.
99
+ * The names of the custom nodes are as shown by `show` and are the names of the git repositories.
100
+ (Plans are to update the use of nicknames in the future.)
101
+
102
+ `[update|disable|enable|fix] all ?[--channel <channel name>] ?[--mode [remote|local|cache]]`
103
+
104
+ * The `update, disable, enable, fix` functions can be specified for all.
105
+
106
+ * Detailed Operations
107
+ * `install`: Installs the specified custom nodes.
108
+ * `reinstall`: Removes and then reinstalls the specified custom nodes.
109
+ * `uninstall`: Uninstalls the specified custom nodes.
110
+ * `update`: Updates the specified custom nodes.
111
+ * `disable`: Disables the specified custom nodes.
112
+ * `enable`: Enables the specified custom nodes.
113
+ * `fix`: Attempts to fix dependencies for the specified custom nodes.
114
+
115
+
116
+ ### 4. Snapshot Management
117
+ * `python cm-cli.py save-snapshot [--output <snapshot .json/.yaml>]`: Saves the current snapshot.
118
+ * With `--output`, you can save a file in .yaml format to any specified path.
119
+ * `python cm-cli.py restore-snapshot <snapshot .json/.yaml>`: Restores to the specified snapshot.
120
+ * If a file exists at the snapshot path, that snapshot is loaded.
121
+ * If no file exists at the snapshot path, it is implicitly assumed to be in ComfyUI-Manager/snapshots.
122
+ * `--pip-non-url`: Restore for pip packages registered on PyPI.
123
+ * `--pip-non-local-url`: Restore for pip packages registered at web URLs.
124
+ * `--pip-local-url`: Restore for pip packages specified by local paths.
125
+ * `--user-directory`: Set the user directory.
126
+ * `--restore-to`: The path where the restored custom nodes will be installed. (When this option is applied, only the custom nodes installed in the target path are recognized as installed.)
127
+
128
+ ### 5. CLI Only Mode
129
+
130
+ You can set whether to use ComfyUI-Manager solely via CLI.
131
+
132
+ `cli-only-mode [enable|disable]`
133
+
134
+ * This mode can be used if you want to restrict the use of ComfyUI-Manager through the GUI for security or policy reasons.
135
+ * When CLI only mode is enabled, ComfyUI-Manager is loaded in a very restricted state, the internal web API is disabled, and the Manager button is not displayed in the main menu.
136
+
137
+ ### 6. Dependency Restoration
138
+
139
+ `restore-dependencies`
140
+
141
+ * This command can be used if custom nodes are installed under the `ComfyUI/custom_nodes` path but their dependencies are not installed.
142
+ * It is useful when starting a new cloud instance, like colab, where dependencies need to be reinstalled and installation scripts re-executed.
143
+ * It can also be utilized if ComfyUI is reinstalled and only the custom_nodes path has been backed up and restored.
144
+
145
+ ### 7. Clear
146
+
147
+ In the GUI, installations, updates, or snapshot restorations are scheduled to execute the next time ComfyUI is launched. The `clear` command clears this scheduled state, ensuring no pre-execution actions are applied.
ComfyUI/custom_nodes/ComfyUI-Manager/docs/en/use_aria2.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use `aria2` as downloader
2
+
3
+ Two environment variables are needed to use `aria2` as the downloader.
4
+
5
+ ```bash
6
+ export COMFYUI_MANAGER_ARIA2_SERVER=http://127.0.0.1:6800
7
+ export COMFYUI_MANAGER_ARIA2_SECRET=__YOU_MUST_CHANGE_IT__
8
+ ```
9
+
10
+ An example `docker-compose.yml`
11
+
12
+ ```yaml
13
+ services:
14
+
15
+ aria2:
16
+ container_name: aria2
17
+ image: p3terx/aria2-pro
18
+ environment:
19
+ - PUID=1000
20
+ - PGID=1000
21
+ - UMASK_SET=022
22
+ - RPC_SECRET=__YOU_MUST_CHANGE_IT__
23
+ - RPC_PORT=5080
24
+ - DISK_CACHE=64M
25
+ - IPV6_MODE=false
26
+ - UPDATE_TRACKERS=false
27
+ - CUSTOM_TRACKER_URL=
28
+ volumes:
29
+ - ./config:/config
30
+ - ./downloads:/downloads
31
+ - ~/ComfyUI/models:/models
32
+ - ~/ComfyUI/custom_nodes:/custom_nodes
33
+ ports:
34
+ - 6800:6800
35
+ restart: unless-stopped
36
+ logging:
37
+ driver: json-file
38
+ options:
39
+ max-size: 1m
40
+ ```
ComfyUI/custom_nodes/ComfyUI-Manager/docs/ko/cm-cli.md ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `cm-cli`: ComfyUI-Manager CLI
2
+
3
+ `cm-cli` 는 ComfyUI를 실행시키지 않고 command line에서 ComfyUI-Manager의 여러가지 기능을 사용할 수 있도록 도와주는 도구입니다.
4
+
5
+
6
+ ```
7
+ -= ComfyUI-Manager CLI (V2.24) =-
8
+
9
+
10
+ python cm-cli.py [OPTIONS]
11
+
12
+ OPTIONS:
13
+ [install|reinstall|uninstall|update|disable|enable|fix] node_name ... ?[--channel <channel name>] ?[--mode [remote|local|cache]]
14
+ [update|disable|enable|fix] all ?[--channel <channel name>] ?[--mode [remote|local|cache]]
15
+ [simple-show|show] [installed|enabled|not-installed|disabled|all|snapshot|snapshot-list] ?[--channel <channel name>] ?[--mode [remote|local|cache]]
16
+ save-snapshot ?[--output <snapshot .json/.yaml>]
17
+ restore-snapshot <snapshot .json/.yaml> ?[--pip-non-url] ?[--pip-non-local-url] ?[--pip-local-url]
18
+ cli-only-mode [enable|disable]
19
+ restore-dependencies
20
+ clear
21
+ ```
22
+
23
+ ## How To Use?
24
+ * `python cm-cli.py` 를 통해서 실행 시킬 수 있습니다.
25
+ * 예를 들어 custom node를 모두 업데이트 하고 싶다면
26
+ * ComfyUI-Manager경로 에서 `python cm-cli.py update all` 를 command를 실행할 수 있습니다.
27
+ * ComfyUI 경로에서 실행한다면, `python custom_nodes/ComfyUI-Manager/cm-cli.py update all` 와 같이 cm-cli.py 의 경로를 지정할 수도 있습니다.
28
+
29
+ ## Prerequisite
30
+ * ComfyUI 를 실행하는 python과 동일한 python 환경에서 실행해야 합니다.
31
+ * venv를 사용할 경우 해당 venv를 activate 한 상태에서 실행해야 합니다.
32
+ * portable 버전을 사용할 경우 run_nvidia_gpu.bat 파일이 있는 경로인 경우, 다음과 같은 방식으로 코맨드를 실행해야 합니다.
33
+ `.\python_embeded\python.exe ComfyUI\custom_nodes\ComfyUI-Manager\cm-cli.py update all`
34
+ * ComfyUI 의 경로는 COMFYUI_PATH 환경 변수로 설정할 수 있습니다. 만약 생략할 경우 다음과 같은 경고 메시지가 나타나며, ComfyUI-Manager가 설치된 경로를 기준으로 상대 경로로 설정됩니다.
35
+ ```
36
+ WARN: The `COMFYUI_PATH` environment variable is not set. Assuming `custom_nodes/ComfyUI-Manager/../../` as the ComfyUI path.
37
+ ```
38
+
39
+ ## Features
40
+
41
+ ### 1. --channel, --mode
42
+ * 정보 보기 기능과 커스텀 노드 관리 기능의 경우는 --channel과 --mode를 통해 정보 DB를 설정할 수 있습니다.
43
+ * 예들 들어 `python cm-cli.py update all --channel recent --mode remote`와 같은 command를 실행할 경우, 현재 ComfyUI-Manager repo에 내장된 로컬의 정보가 아닌 remote의 최신 정보를 기준으로 동작하며, recent channel에 있는 목록을 대상으로만 동작합니다.
44
+ * --channel, --mode 는 `simple-show, show, install, uninstall, update, disable, enable, fix` command에서만 사용 가능합니다.
45
+
46
+ ### 2. 관리 정보 보기
47
+
48
+ `[simple-show|show] [installed|enabled|not-installed|disabled|all|snapshot|snapshot-list] ?[--channel <channel name>] ?[--mode [remote|local|cache]]`
49
+
50
+
51
+ * `[show|simple-show]` - `show`는 상세하게 정보를 보여주며, `simple-show`는 간단하게 정보를 보여줍니다.
52
+
53
+
54
+ `python cm-cli.py show installed` 와 같은 코맨드를 실행하면 설치된 커스텀 노드의 정보를 상세하게 보여줍니다.
55
+ ```
56
+ -= ComfyUI-Manager CLI (V2.24) =-
57
+
58
+ FETCH DATA from: https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/custom-node-list.json
59
+ [ ENABLED ] ComfyUI-Manager (author: Dr.Lt.Data)
60
+ [ ENABLED ] ComfyUI-Impact-Pack (author: Dr.Lt.Data)
61
+ [ ENABLED ] ComfyUI-Inspire-Pack (author: Dr.Lt.Data)
62
+ [ ENABLED ] ComfyUI_experiments (author: comfyanonymous)
63
+ [ ENABLED ] ComfyUI-SAI_API (author: Stability-AI)
64
+ [ ENABLED ] stability-ComfyUI-nodes (author: Stability-AI)
65
+ [ ENABLED ] comfyui_controlnet_aux (author: Fannovel16)
66
+ [ ENABLED ] ComfyUI-Frame-Interpolation (author: Fannovel16)
67
+ [ DISABLED ] ComfyUI-Loopchain (author: Fannovel16)
68
+ ```
69
+
70
+ `python cm-cli.py simple-show installed` 와 같은 코맨드를 이용해서 설치된 커스텀 노드의 정보를 간단하게 보여줍니다.
71
+
72
+ ```
73
+ -= ComfyUI-Manager CLI (V2.24) =-
74
+
75
+ FETCH DATA from: https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/custom-node-list.json
76
+ ComfyUI-Manager
77
+ ComfyUI-Impact-Pack
78
+ ComfyUI-Inspire-Pack
79
+ ComfyUI_experiments
80
+ ComfyUI-SAI_API
81
+ stability-ComfyUI-nodes
82
+ comfyui_controlnet_aux
83
+ ComfyUI-Frame-Interpolation
84
+ ComfyUI-Loopchain
85
+ ```
86
+
87
+ * `[installed|enabled|not-installed|disabled|all|snapshot|snapshot-list]`
88
+ * `enabled`, `disabled`: 설치된 커스텀 노드들 중 enable 되었거나, disable된 노드들을 보여줍니다.
89
+ * `installed`: enable, disable 여부와 상관없이 설치된 모든 노드를 보여줍니다
90
+ * `not-installed`: 설치되지 않은 커스텀 노드의 목록을 보여줍니다.
91
+ * `all`: 모든 커스텀 노드의 목록을 보여줍니다.
92
+ * `snapshot`: 현재 설치된 커스텀 노드의 snapshot 정보를 보여줍니다. `show`롤 통해서 볼 경우는 json 출력 형태로 보여주며, `simple-show`를 통해서 볼 경우는 간단하게, 커밋 해시와 함께 보여줍니다.
93
+ * `snapshot-list`: ComfyUI-Manager/snapshots 에 저장된 snapshot 파일의 목록을 보여줍니다.
94
+
95
+ ### 3. 커스텀 노드 관리 하기
96
+
97
+ `[install|reinstall|uninstall|update|disable|enable|fix] node_name ... ?[--channel <channel name>] ?[--mode [remote|local|cache]]`
98
+
99
+ * `python cm-cli.py install ComfyUI-Impact-Pack ComfyUI-Inspire-Pack ComfyUI_experiments` 와 같이 커스텀 노드의 이름을 나열해서 관리 기능을 적용할 수 있습니다.
100
+ * 커스텀 노드의 이름은 `show`를 했을 때 보여주는 이름이며, git repository의 이름입니다.
101
+ (추후 nickname 을 사용가능하돌고 업데이트 할 예정입니다.)
102
+
103
+ `[update|disable|enable|fix] all ?[--channel <channel name>] ?[--mode [remote|local|cache]]`
104
+
105
+ * `update, disable, enable, fix` 기능은 all 로 지정 가능합니다.
106
+
107
+ * 세부 동작
108
+ * `install`: 지정된 커스텀 노드들을 설치합니다
109
+ * `reinstall`: 지정된 커스텀 노드를 삭제하고 재설치 합니다.
110
+ * `uninstall`: 지정된 커스텀 노드들을 삭제합니다.
111
+ * `update`: 지정된 커스텀 노드들을 업데이트합니다.
112
+ * `disable`: 지정된 커스텀 노드들을 비활성화합니다.
113
+ * `enable`: 지정된 커스텀 노드들을 활성화합니다.
114
+ * `fix`: 지정된 커스텀 노드의 의존성을 고치기 위한 시도를 합니다.
115
+
116
+
117
+ ### 4. 스냅샷 관리 기능
118
+ * `python cm-cli.py save-snapshot ?[--output <snapshot .json/.yaml>]`: 현재의 snapshot을 저장합니다.
119
+ * --output 으로 임의의 경로에 .yaml 파일과 format으로 저장할 수 있습니다.
120
+ * `python cm-cli.py restore-snapshot <snapshot .json/.yaml>`: 지정된 snapshot으로 복구합니다.
121
+ * snapshot 경로에 파일이 존재하는 경우 해당 snapshot을 로드합니다.
122
+ * snapshot 경로에 파일이 존재하지 않는 경우 묵시적으로, ComfyUI-Manager/snapshots 에 있다고 가정합니다.
123
+ * `--pip-non-url`: PyPI 에 등록된 pip 패키지들에 대해서 복구를 수행
124
+ * `--pip-non-local-url`: web URL에 등록된 pip 패키지들에 대해서 복구를 수행
125
+ * `--pip-local-url`: local 경로를 지정하고 있는 pip 패키지들에 대해서 복구를 수행
126
+ * `--user-directory`: 사용자 디렉토리 설정
127
+ * `--restore-to`: 복구될 커스텀 노드가 설치될 경로. (이 옵션을 적용할 경우 오직 대상 경로에 설치된 custom nodes 만 설치된 것으로 인식함.)
128
+
129
+ ### 5. CLI only mode
130
+
131
+ ComfyUI-Manager를 CLI로만 사용할 것인지를 설정할 수 있습니다.
132
+
133
+ `cli-only-mode [enable|disable]`
134
+
135
+ * security 혹은 policy 의 이유로 GUI 를 통한 ComfyUI-Manager 사용을 제한하고 싶은 경우 이 모드를 사용할 수 있습니다.
136
+ * CLI only mode를 적용할 경우 ComfyUI-Manager 가 매우 제한된 상태로 로드되어, 내부적으로 제공하는 web API가 비활성화 되며, 메인 메뉴에서도 Manager 버튼이 표시되지 않습니다.
137
+
138
+
139
+ ### 6. 의존성 설치
140
+
141
+ `restore-dependencies`
142
+
143
+ * `ComfyUI/custom_nodes` 하위 경로에 커스텀 노드들이 설치되어 있긴 하지만, 의존성이 설치되지 않은 경우 사용할 수 있습니다.
144
+ * colab 과 같이 cloud instance를 새로 시작하는 경우 의존성 재설치 및 설치 스크립트가 재실행 되어야 하는 경우 사용합니다.
145
+ * ComfyUI을 재설치할 경우, custom_nodes 경로만 백업했다가 재설치 할 경우 활용 가능합니다.
146
+
147
+
148
+ ### 7. clear
149
+
150
+ GUI에서 install, update를 하거나 snapshot 을 restore하는 경우 예약을 통해서 다음번 ComfyUI를 실행할 경우 실행되는 구조입니다. `clear` 는 이런 예약 상태를 clear해서, 아무런 사전 실행이 적용되지 않도록 합니다.
ComfyUI/custom_nodes/ComfyUI-Manager/extension-node-map.json ADDED
The diff for this file is too large to render. See raw diff
 
ComfyUI/custom_nodes/ComfyUI-Manager/extras.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "favorites": [
3
+ "comfyui_ipadapter_plus",
4
+ "comfyui-animatediff-evolved",
5
+ "comfyui_controlnet_aux",
6
+ "comfyui-impact-pack",
7
+ "comfyui-impact-subpack",
8
+ "comfyui-custom-scripts",
9
+ "comfyui-layerdiffuse",
10
+ "comfyui-liveportraitkj",
11
+ "aigodlike-comfyui-translation",
12
+ "comfyui-reactor",
13
+ "comfyui_instantid",
14
+ "sd-dynamic-thresholding",
15
+ "pr-was-node-suite-comfyui-47064894",
16
+ "comfyui-advancedliveportrait",
17
+ "comfyui_layerstyle",
18
+ "efficiency-nodes-comfyui",
19
+ "comfyui-crystools",
20
+ "comfyui-advanced-controlnet",
21
+ "comfyui-videohelpersuite",
22
+ "comfyui-kjnodes",
23
+ "comfy-mtb",
24
+ "comfyui_essentials"
25
+ ]
26
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/git_helper.py ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import sys
3
+ import os
4
+ import traceback
5
+
6
+ import git
7
+ import json
8
+ import yaml
9
+ import requests
10
+ from tqdm.auto import tqdm
11
+ from git.remote import RemoteProgress
12
+
13
+
14
+ comfy_path = os.environ.get('COMFYUI_PATH')
15
+ git_exe_path = os.environ.get('GIT_EXE_PATH')
16
+
17
+ if comfy_path is None:
18
+ print("\nWARN: The `COMFYUI_PATH` environment variable is not set. Assuming `custom_nodes/ComfyUI-Manager/../../` as the ComfyUI path.", file=sys.stderr)
19
+ comfy_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
20
+
21
+
22
+ def download_url(url, dest_folder, filename=None):
23
+ # Ensure the destination folder exists
24
+ if not os.path.exists(dest_folder):
25
+ os.makedirs(dest_folder)
26
+
27
+ # Extract filename from URL if not provided
28
+ if filename is None:
29
+ filename = os.path.basename(url)
30
+
31
+ # Full path to save the file
32
+ dest_path = os.path.join(dest_folder, filename)
33
+
34
+ # Download the file
35
+ response = requests.get(url, stream=True)
36
+ if response.status_code == 200:
37
+ with open(dest_path, 'wb') as file:
38
+ for chunk in response.iter_content(chunk_size=1024):
39
+ if chunk:
40
+ file.write(chunk)
41
+ else:
42
+ print(f"Failed to download file from {url}")
43
+
44
+
45
+ nodelist_path = os.path.join(os.path.dirname(__file__), "custom-node-list.json")
46
+ working_directory = os.getcwd()
47
+
48
+ if os.path.basename(working_directory) != 'custom_nodes':
49
+ print("WARN: This script should be executed in custom_nodes dir")
50
+ print(f"DBG: INFO {working_directory}")
51
+ print(f"DBG: INFO {sys.argv}")
52
+ # exit(-1)
53
+
54
+
55
+ class GitProgress(RemoteProgress):
56
+ def __init__(self):
57
+ super().__init__()
58
+ self.pbar = tqdm(ascii=True)
59
+
60
+ def update(self, op_code, cur_count, max_count=None, message=''):
61
+ self.pbar.total = max_count
62
+ self.pbar.n = cur_count
63
+ self.pbar.pos = 0
64
+ self.pbar.refresh()
65
+
66
+
67
+ def gitclone(custom_nodes_path, url, target_hash=None, repo_path=None):
68
+ repo_name = os.path.splitext(os.path.basename(url))[0]
69
+
70
+ if repo_path is None:
71
+ repo_path = os.path.join(custom_nodes_path, repo_name)
72
+
73
+ # Clone the repository from the remote URL
74
+ repo = git.Repo.clone_from(url, repo_path, recursive=True, progress=GitProgress())
75
+
76
+ if target_hash is not None:
77
+ print(f"CHECKOUT: {repo_name} [{target_hash}]")
78
+ repo.git.checkout(target_hash)
79
+
80
+ repo.git.clear_cache()
81
+ repo.close()
82
+
83
+
84
+ def gitcheck(path, do_fetch=False):
85
+ try:
86
+ # Fetch the latest commits from the remote repository
87
+ repo = git.Repo(path)
88
+
89
+ if repo.head.is_detached:
90
+ print("CUSTOM NODE CHECK: True")
91
+ return
92
+
93
+ current_branch = repo.active_branch
94
+ branch_name = current_branch.name
95
+
96
+ remote_name = current_branch.tracking_branch().remote_name
97
+ remote = repo.remote(name=remote_name)
98
+
99
+ if do_fetch:
100
+ remote.fetch()
101
+
102
+ # Get the current commit hash and the commit hash of the remote branch
103
+ commit_hash = repo.head.commit.hexsha
104
+
105
+ if f'{remote_name}/{branch_name}' in repo.refs:
106
+ remote_commit_hash = repo.refs[f'{remote_name}/{branch_name}'].object.hexsha
107
+ else:
108
+ print("CUSTOM NODE CHECK: True") # non default branch is treated as updatable
109
+ return
110
+
111
+ # Compare the commit hashes to determine if the local repository is behind the remote repository
112
+ if commit_hash != remote_commit_hash:
113
+ # Get the commit dates
114
+ commit_date = repo.head.commit.committed_datetime
115
+ remote_commit_date = repo.refs[f'{remote_name}/{branch_name}'].object.committed_datetime
116
+
117
+ # Compare the commit dates to determine if the local repository is behind the remote repository
118
+ if commit_date < remote_commit_date:
119
+ print("CUSTOM NODE CHECK: True")
120
+ else:
121
+ print("CUSTOM NODE CHECK: False")
122
+ except Exception as e:
123
+ print(e)
124
+ print("CUSTOM NODE CHECK: Error")
125
+
126
+
127
+ def get_remote_name(repo):
128
+ available_remotes = [remote.name for remote in repo.remotes]
129
+ if 'origin' in available_remotes:
130
+ return 'origin'
131
+ elif 'upstream' in available_remotes:
132
+ return 'upstream'
133
+ elif len(available_remotes) > 0:
134
+ return available_remotes[0]
135
+
136
+ if not available_remotes:
137
+ print(f"[ComfyUI-Manager] No remotes are configured for this repository: {repo.working_dir}")
138
+ else:
139
+ print(f"[ComfyUI-Manager] Available remotes in '{repo.working_dir}': ")
140
+ for remote in available_remotes:
141
+ print(f"- {remote}")
142
+
143
+ return None
144
+
145
+
146
+ def switch_to_default_branch(repo):
147
+ remote_name = get_remote_name(repo)
148
+
149
+ try:
150
+ if remote_name is None:
151
+ return False
152
+
153
+ default_branch = repo.git.symbolic_ref(f'refs/remotes/{remote_name}/HEAD').replace(f'refs/remotes/{remote_name}/', '')
154
+ repo.git.checkout(default_branch)
155
+ return True
156
+ except:
157
+ # try checkout master
158
+ # try checkout main if failed
159
+ try:
160
+ repo.git.checkout(repo.heads.master)
161
+ return True
162
+ except:
163
+ try:
164
+ if remote_name is not None:
165
+ repo.git.checkout('-b', 'master', f'{remote_name}/master')
166
+ return True
167
+ except:
168
+ try:
169
+ repo.git.checkout(repo.heads.main)
170
+ return True
171
+ except:
172
+ try:
173
+ if remote_name is not None:
174
+ repo.git.checkout('-b', 'main', f'{remote_name}/main')
175
+ return True
176
+ except:
177
+ pass
178
+
179
+ print("[ComfyUI Manager] Failed to switch to the default branch")
180
+ return False
181
+
182
+
183
+ def gitpull(path):
184
+ # Check if the path is a git repository
185
+ if not os.path.exists(os.path.join(path, '.git')):
186
+ raise ValueError('Not a git repository')
187
+
188
+ # Pull the latest changes from the remote repository
189
+ repo = git.Repo(path)
190
+ if repo.is_dirty():
191
+ print(f"STASH: '{path}' is dirty.")
192
+ repo.git.stash()
193
+
194
+ commit_hash = repo.head.commit.hexsha
195
+ try:
196
+ if repo.head.is_detached:
197
+ switch_to_default_branch(repo)
198
+
199
+ current_branch = repo.active_branch
200
+ branch_name = current_branch.name
201
+
202
+ remote_name = current_branch.tracking_branch().remote_name
203
+ remote = repo.remote(name=remote_name)
204
+
205
+ if f'{remote_name}/{branch_name}' not in repo.refs:
206
+ switch_to_default_branch(repo)
207
+ current_branch = repo.active_branch
208
+ branch_name = current_branch.name
209
+
210
+ remote.fetch()
211
+ if f'{remote_name}/{branch_name}' in repo.refs:
212
+ remote_commit_hash = repo.refs[f'{remote_name}/{branch_name}'].object.hexsha
213
+ else:
214
+ print("CUSTOM NODE PULL: Fail") # update fail
215
+ return
216
+
217
+ if commit_hash == remote_commit_hash:
218
+ print("CUSTOM NODE PULL: None") # there is no update
219
+ repo.close()
220
+ return
221
+
222
+ remote.pull()
223
+
224
+ repo.git.submodule('update', '--init', '--recursive')
225
+ new_commit_hash = repo.head.commit.hexsha
226
+
227
+ if commit_hash != new_commit_hash:
228
+ print("CUSTOM NODE PULL: Success") # update success
229
+ else:
230
+ print("CUSTOM NODE PULL: Fail") # update fail
231
+ except Exception as e:
232
+ print(e)
233
+ print("CUSTOM NODE PULL: Fail") # unknown git error
234
+
235
+ repo.close()
236
+
237
+
238
+ def checkout_comfyui_hash(target_hash):
239
+ repo = git.Repo(comfy_path)
240
+ commit_hash = repo.head.commit.hexsha
241
+
242
+ if commit_hash != target_hash:
243
+ try:
244
+ print(f"CHECKOUT: ComfyUI [{target_hash}]")
245
+ repo.git.checkout(target_hash)
246
+ except git.GitCommandError as e:
247
+ print(f"Error checking out the ComfyUI: {str(e)}")
248
+
249
+
250
+ def checkout_custom_node_hash(git_custom_node_infos):
251
+ repo_name_to_url = {}
252
+
253
+ for url in git_custom_node_infos.keys():
254
+ repo_name = url.split('/')[-1]
255
+
256
+ if repo_name.endswith('.git'):
257
+ repo_name = repo_name[:-4]
258
+
259
+ repo_name_to_url[repo_name] = url
260
+
261
+ for path in os.listdir(working_directory):
262
+ if path.endswith("ComfyUI-Manager"):
263
+ continue
264
+
265
+ fullpath = os.path.join(working_directory, path)
266
+
267
+ if os.path.isdir(fullpath):
268
+ is_disabled = path.endswith(".disabled")
269
+
270
+ try:
271
+ git_dir = os.path.join(fullpath, '.git')
272
+ if not os.path.exists(git_dir):
273
+ continue
274
+
275
+ need_checkout = False
276
+ repo_name = os.path.basename(fullpath)
277
+
278
+ if repo_name.endswith('.disabled'):
279
+ repo_name = repo_name[:-9]
280
+
281
+ if repo_name not in repo_name_to_url:
282
+ if not is_disabled:
283
+ # should be disabled
284
+ print(f"DISABLE: {repo_name}")
285
+ new_path = fullpath + ".disabled"
286
+ os.rename(fullpath, new_path)
287
+ need_checkout = False
288
+ else:
289
+ item = git_custom_node_infos[repo_name_to_url[repo_name]]
290
+ if item['disabled'] and is_disabled:
291
+ pass
292
+ elif item['disabled'] and not is_disabled:
293
+ # disable
294
+ print(f"DISABLE: {repo_name}")
295
+ new_path = fullpath + ".disabled"
296
+ os.rename(fullpath, new_path)
297
+
298
+ elif not item['disabled'] and is_disabled:
299
+ # enable
300
+ print(f"ENABLE: {repo_name}")
301
+ new_path = fullpath[:-9]
302
+ os.rename(fullpath, new_path)
303
+ fullpath = new_path
304
+ need_checkout = True
305
+ else:
306
+ need_checkout = True
307
+
308
+ if need_checkout:
309
+ repo = git.Repo(fullpath)
310
+ commit_hash = repo.head.commit.hexsha
311
+
312
+ if commit_hash != item['hash']:
313
+ print(f"CHECKOUT: {repo_name} [{item['hash']}]")
314
+ repo.git.checkout(item['hash'])
315
+
316
+ except Exception:
317
+ print(f"Failed to restore snapshots for the custom node '{path}'")
318
+
319
+ # clone missing
320
+ for k, v in git_custom_node_infos.items():
321
+ if 'ComfyUI-Manager' in k:
322
+ continue
323
+
324
+ if not v['disabled']:
325
+ repo_name = k.split('/')[-1]
326
+ if repo_name.endswith('.git'):
327
+ repo_name = repo_name[:-4]
328
+
329
+ path = os.path.join(working_directory, repo_name)
330
+ if not os.path.exists(path):
331
+ print(f"CLONE: {path}")
332
+ gitclone(working_directory, k, target_hash=v['hash'])
333
+
334
+
335
+ def invalidate_custom_node_file(file_custom_node_infos):
336
+ global nodelist_path
337
+
338
+ enabled_set = set()
339
+ for item in file_custom_node_infos:
340
+ if not item['disabled']:
341
+ enabled_set.add(item['filename'])
342
+
343
+ for path in os.listdir(working_directory):
344
+ fullpath = os.path.join(working_directory, path)
345
+
346
+ if not os.path.isdir(fullpath) and fullpath.endswith('.py'):
347
+ if path not in enabled_set:
348
+ print(f"DISABLE: {path}")
349
+ new_path = fullpath+'.disabled'
350
+ os.rename(fullpath, new_path)
351
+
352
+ elif not os.path.isdir(fullpath) and fullpath.endswith('.py.disabled'):
353
+ path = path[:-9]
354
+ if path in enabled_set:
355
+ print(f"ENABLE: {path}")
356
+ new_path = fullpath[:-9]
357
+ os.rename(fullpath, new_path)
358
+
359
+ # download missing: just support for 'copy' style
360
+ py_to_url = {}
361
+
362
+ with open(nodelist_path, 'r', encoding="UTF-8") as json_file:
363
+ info = json.load(json_file)
364
+ for item in info['custom_nodes']:
365
+ if item['install_type'] == 'copy':
366
+ for url in item['files']:
367
+ if url.endswith('.py'):
368
+ py = url.split('/')[-1]
369
+ py_to_url[py] = url
370
+
371
+ for item in file_custom_node_infos:
372
+ filename = item['filename']
373
+ if not item['disabled']:
374
+ target_path = os.path.join(working_directory, filename)
375
+
376
+ if not os.path.exists(target_path) and filename in py_to_url:
377
+ url = py_to_url[filename]
378
+ print(f"DOWNLOAD: {filename}")
379
+ download_url(url, working_directory)
380
+
381
+
382
+ def apply_snapshot(path):
383
+ try:
384
+ if os.path.exists(path):
385
+ if not path.endswith('.json') and not path.endswith('.yaml'):
386
+ print(f"Snapshot file not found: `{path}`")
387
+ print("APPLY SNAPSHOT: False")
388
+ return None
389
+
390
+ with open(path, 'r', encoding="UTF-8") as snapshot_file:
391
+ if path.endswith('.json'):
392
+ info = json.load(snapshot_file)
393
+ elif path.endswith('.yaml'):
394
+ info = yaml.load(snapshot_file, Loader=yaml.SafeLoader)
395
+ info = info['custom_nodes']
396
+ else:
397
+ # impossible case
398
+ print("APPLY SNAPSHOT: False")
399
+ return None
400
+
401
+ comfyui_hash = info['comfyui']
402
+ git_custom_node_infos = info['git_custom_nodes']
403
+ file_custom_node_infos = info['file_custom_nodes']
404
+
405
+ if comfyui_hash:
406
+ checkout_comfyui_hash(comfyui_hash)
407
+ checkout_custom_node_hash(git_custom_node_infos)
408
+ invalidate_custom_node_file(file_custom_node_infos)
409
+
410
+ print("APPLY SNAPSHOT: True")
411
+ if 'pips' in info and info['pips']:
412
+ return info['pips']
413
+ else:
414
+ return None
415
+
416
+ print(f"Snapshot file not found: `{path}`")
417
+ print("APPLY SNAPSHOT: False")
418
+
419
+ return None
420
+ except Exception as e:
421
+ print(e)
422
+ traceback.print_exc()
423
+ print("APPLY SNAPSHOT: False")
424
+
425
+ return None
426
+
427
+
428
+ def restore_pip_snapshot(pips, options):
429
+ non_url = []
430
+ local_url = []
431
+ non_local_url = []
432
+ for k, v in pips.items():
433
+ if v == "":
434
+ non_url.append(k)
435
+ else:
436
+ if v.startswith('file:'):
437
+ local_url.append(v)
438
+ else:
439
+ non_local_url.append(v)
440
+
441
+ failed = []
442
+ if '--pip-non-url' in options:
443
+ # try all at once
444
+ res = 1
445
+ try:
446
+ res = subprocess.check_call([sys.executable, '-m', 'pip', 'install'] + non_url)
447
+ except:
448
+ pass
449
+
450
+ # fallback
451
+ if res != 0:
452
+ for x in non_url:
453
+ res = 1
454
+ try:
455
+ res = subprocess.check_call([sys.executable, '-m', 'pip', 'install', x])
456
+ except:
457
+ pass
458
+
459
+ if res != 0:
460
+ failed.append(x)
461
+
462
+ if '--pip-non-local-url' in options:
463
+ for x in non_local_url:
464
+ res = 1
465
+ try:
466
+ res = subprocess.check_call([sys.executable, '-m', 'pip', 'install', x])
467
+ except:
468
+ pass
469
+
470
+ if res != 0:
471
+ failed.append(x)
472
+
473
+ if '--pip-local-url' in options:
474
+ for x in local_url:
475
+ res = 1
476
+ try:
477
+ res = subprocess.check_call([sys.executable, '-m', 'pip', 'install', x])
478
+ except:
479
+ pass
480
+
481
+ if res != 0:
482
+ failed.append(x)
483
+
484
+ print(f"Installation failed for pip packages: {failed}")
485
+
486
+
487
+ def setup_environment():
488
+ if git_exe_path is not None:
489
+ git.Git().update_environment(GIT_PYTHON_GIT_EXECUTABLE=git_exe_path)
490
+
491
+
492
+ setup_environment()
493
+
494
+
495
+ try:
496
+ if sys.argv[1] == "--clone":
497
+ repo_path = None
498
+ if len(sys.argv) > 4:
499
+ repo_path = sys.argv[4]
500
+
501
+ gitclone(sys.argv[2], sys.argv[3], repo_path=repo_path)
502
+ elif sys.argv[1] == "--check":
503
+ gitcheck(sys.argv[2], False)
504
+ elif sys.argv[1] == "--fetch":
505
+ gitcheck(sys.argv[2], True)
506
+ elif sys.argv[1] == "--pull":
507
+ gitpull(sys.argv[2])
508
+ elif sys.argv[1] == "--apply-snapshot":
509
+ options = set()
510
+ for x in sys.argv:
511
+ if x in ['--pip-non-url', '--pip-local-url', '--pip-non-local-url']:
512
+ options.add(x)
513
+
514
+ pips = apply_snapshot(sys.argv[2])
515
+
516
+ if pips and len(options) > 0:
517
+ restore_pip_snapshot(pips, options)
518
+ sys.exit(0)
519
+ except Exception as e:
520
+ print(e)
521
+ sys.exit(-1)
522
+
523
+
ComfyUI/custom_nodes/ComfyUI-Manager/github-stats.json ADDED
The diff for this file is too large to render. See raw diff
 
ComfyUI/custom_nodes/ComfyUI-Manager/glob/cm_global.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import traceback
2
+
3
+ #
4
+ # Global Var
5
+ #
6
+ # Usage:
7
+ # import cm_global
8
+ # cm_global.variables['comfyui.revision'] = 1832
9
+ # print(f"log mode: {cm_global.variables['logger.enabled']}")
10
+ #
11
+ variables = {}
12
+
13
+
14
+ #
15
+ # Global API
16
+ #
17
+ # Usage:
18
+ # [register API]
19
+ # import cm_global
20
+ #
21
+ # def api_hello(msg):
22
+ # print(f"hello: {msg}")
23
+ # return msg
24
+ #
25
+ # cm_global.register_api('hello', api_hello)
26
+ #
27
+ # [use API]
28
+ # import cm_global
29
+ #
30
+ # test = cm_global.try_call(api='hello', msg='an example')
31
+ # print(f"'{test}' is returned")
32
+ #
33
+
34
+ APIs = {}
35
+
36
+
37
+ def register_api(k, f):
38
+ global APIs
39
+ APIs[k] = f
40
+
41
+
42
+ def try_call(**kwargs):
43
+ if 'api' in kwargs:
44
+ api_name = kwargs['api']
45
+ try:
46
+ api = APIs.get(api_name)
47
+ if api is not None:
48
+ del kwargs['api']
49
+ return api(**kwargs)
50
+ else:
51
+ print(f"WARN: The '{kwargs['api']}' API has not been registered.")
52
+ except Exception as e:
53
+ print(f"ERROR: An exception occurred while calling the '{api_name}' API.")
54
+ raise e
55
+ else:
56
+ return None
57
+
58
+
59
+ #
60
+ # Extension Info
61
+ #
62
+ # Usage:
63
+ # import cm_global
64
+ #
65
+ # cm_global.extension_infos['my_extension'] = {'version': [0, 1], 'name': 'me', 'description': 'example extension', }
66
+ #
67
+ extension_infos = {}
68
+
69
+ on_extension_registered_handlers = {}
70
+
71
+
72
+ def register_extension(extension_name, v):
73
+ global extension_infos
74
+ global on_extension_registered_handlers
75
+ extension_infos[extension_name] = v
76
+
77
+ if extension_name in on_extension_registered_handlers:
78
+ for k, f in on_extension_registered_handlers[extension_name]:
79
+ try:
80
+ f(extension_name, v)
81
+ except Exception:
82
+ print(f"[ERROR] '{k}' on_extension_registered_handlers")
83
+ traceback.print_exc()
84
+
85
+ del on_extension_registered_handlers[extension_name]
86
+
87
+
88
+ def add_on_extension_registered(k, extension_name, f):
89
+ global on_extension_registered_handlers
90
+ if extension_name in extension_infos:
91
+ try:
92
+ v = extension_infos[extension_name]
93
+ f(extension_name, v)
94
+ except Exception:
95
+ print(f"[ERROR] '{k}' on_extension_registered_handler")
96
+ traceback.print_exc()
97
+ else:
98
+ if extension_name not in on_extension_registered_handlers:
99
+ on_extension_registered_handlers[extension_name] = []
100
+
101
+ on_extension_registered_handlers[extension_name].append((k, f))
102
+
103
+
104
+ def add_on_revision_detected(k, f):
105
+ if 'comfyui.revision' in variables:
106
+ try:
107
+ f(variables['comfyui.revision'])
108
+ except Exception:
109
+ print(f"[ERROR] '{k}' on_revision_detected_handler")
110
+ traceback.print_exc()
111
+ else:
112
+ variables['cm.on_revision_detected_handler'].append((k, f))
113
+
114
+
115
+ error_dict = {}
116
+
117
+ disable_front = False
ComfyUI/custom_nodes/ComfyUI-Manager/glob/cnr_utils.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import json
3
+ import os
4
+ import platform
5
+ import time
6
+ from dataclasses import dataclass
7
+ from typing import List
8
+
9
+ import manager_core
10
+ import manager_util
11
+ import requests
12
+ import toml
13
+
14
+ base_url = "https://api.comfy.org"
15
+
16
+
17
+ lock = asyncio.Lock()
18
+
19
+ is_cache_loading = False
20
+
21
+ async def get_cnr_data(cache_mode=True, dont_wait=True):
22
+ try:
23
+ return await _get_cnr_data(cache_mode, dont_wait)
24
+ except asyncio.TimeoutError:
25
+ print("A timeout occurred during the fetch process from ComfyRegistry.")
26
+ return await _get_cnr_data(cache_mode=True, dont_wait=True) # timeout fallback
27
+
28
+ async def _get_cnr_data(cache_mode=True, dont_wait=True):
29
+ global is_cache_loading
30
+
31
+ uri = f'{base_url}/nodes'
32
+
33
+ async def fetch_all():
34
+ remained = True
35
+ page = 1
36
+
37
+ full_nodes = {}
38
+
39
+
40
+ # Determine form factor based on environment and platform
41
+ is_desktop = bool(os.environ.get('__COMFYUI_DESKTOP_VERSION__'))
42
+ system = platform.system().lower()
43
+ is_windows = system == 'windows'
44
+ is_mac = system == 'darwin'
45
+ is_linux = system == 'linux'
46
+
47
+ # Get ComfyUI version tag
48
+ if is_desktop:
49
+ # extract version from pyproject.toml instead of git tag
50
+ comfyui_ver = manager_core.get_current_comfyui_ver() or 'unknown'
51
+ else:
52
+ comfyui_ver = manager_core.get_comfyui_tag() or 'unknown'
53
+
54
+ if is_desktop:
55
+ if is_windows:
56
+ form_factor = 'desktop-win'
57
+ elif is_mac:
58
+ form_factor = 'desktop-mac'
59
+ else:
60
+ form_factor = 'other'
61
+ else:
62
+ if is_windows:
63
+ form_factor = 'git-windows'
64
+ elif is_mac:
65
+ form_factor = 'git-mac'
66
+ elif is_linux:
67
+ form_factor = 'git-linux'
68
+ else:
69
+ form_factor = 'other'
70
+
71
+ while remained:
72
+ # Add comfyui_version and form_factor to the API request
73
+ sub_uri = f'{base_url}/nodes?page={page}&limit=30&comfyui_version={comfyui_ver}&form_factor={form_factor}'
74
+ sub_json_obj = await asyncio.wait_for(manager_util.get_data_with_cache(sub_uri, cache_mode=False, silent=True, dont_cache=True), timeout=30)
75
+ remained = page < sub_json_obj['totalPages']
76
+
77
+ for x in sub_json_obj['nodes']:
78
+ full_nodes[x['id']] = x
79
+
80
+ if page % 5 == 0:
81
+ print(f"FETCH ComfyRegistry Data: {page}/{sub_json_obj['totalPages']}")
82
+
83
+ page += 1
84
+ time.sleep(0.5)
85
+
86
+ print("FETCH ComfyRegistry Data [DONE]")
87
+
88
+ for v in full_nodes.values():
89
+ if 'latest_version' not in v:
90
+ v['latest_version'] = dict(version='nightly')
91
+
92
+ return {'nodes': list(full_nodes.values())}
93
+
94
+ if cache_mode:
95
+ is_cache_loading = True
96
+ cache_state = manager_util.get_cache_state(uri)
97
+
98
+ if dont_wait:
99
+ if cache_state == 'not-cached':
100
+ return {}
101
+ else:
102
+ print("[ComfyUI-Manager] The ComfyRegistry cache update is still in progress, so an outdated cache is being used.")
103
+ with open(manager_util.get_cache_path(uri), 'r', encoding="UTF-8", errors="ignore") as json_file:
104
+ return json.load(json_file)['nodes']
105
+
106
+ if cache_state == 'cached':
107
+ with open(manager_util.get_cache_path(uri), 'r', encoding="UTF-8", errors="ignore") as json_file:
108
+ return json.load(json_file)['nodes']
109
+
110
+ try:
111
+ json_obj = await fetch_all()
112
+ manager_util.save_to_cache(uri, json_obj)
113
+ return json_obj['nodes']
114
+ except:
115
+ res = {}
116
+ print("Cannot connect to comfyregistry.")
117
+ finally:
118
+ if cache_mode:
119
+ is_cache_loading = False
120
+
121
+ return res
122
+
123
+
124
+ @dataclass
125
+ class NodeVersion:
126
+ changelog: str
127
+ dependencies: List[str]
128
+ deprecated: bool
129
+ id: str
130
+ version: str
131
+ download_url: str
132
+
133
+
134
+ def map_node_version(api_node_version):
135
+ """
136
+ Maps node version data from API response to NodeVersion dataclass.
137
+
138
+ Args:
139
+ api_data (dict): The 'node_version' part of the API response.
140
+
141
+ Returns:
142
+ NodeVersion: An instance of NodeVersion dataclass populated with data from the API.
143
+ """
144
+ return NodeVersion(
145
+ changelog=api_node_version.get(
146
+ "changelog", ""
147
+ ), # Provide a default value if 'changelog' is missing
148
+ dependencies=api_node_version.get(
149
+ "dependencies", []
150
+ ), # Provide a default empty list if 'dependencies' is missing
151
+ deprecated=api_node_version.get(
152
+ "deprecated", False
153
+ ), # Assume False if 'deprecated' is not specified
154
+ id=api_node_version[
155
+ "id"
156
+ ], # 'id' should be mandatory; raise KeyError if missing
157
+ version=api_node_version[
158
+ "version"
159
+ ], # 'version' should be mandatory; raise KeyError if missing
160
+ download_url=api_node_version.get(
161
+ "downloadUrl", ""
162
+ ), # Provide a default value if 'downloadUrl' is missing
163
+ )
164
+
165
+
166
+ def install_node(node_id, version=None):
167
+ """
168
+ Retrieves the node version for installation.
169
+
170
+ Args:
171
+ node_id (str): The unique identifier of the node.
172
+ version (str, optional): Specific version of the node to retrieve. If omitted, the latest version is returned.
173
+
174
+ Returns:
175
+ NodeVersion: Node version data or error message.
176
+ """
177
+ if version is None:
178
+ url = f"{base_url}/nodes/{node_id}/install"
179
+ else:
180
+ url = f"{base_url}/nodes/{node_id}/install?version={version}"
181
+
182
+ response = requests.get(url)
183
+ if response.status_code == 200:
184
+ # Convert the API response to a NodeVersion object
185
+ return map_node_version(response.json())
186
+ else:
187
+ return None
188
+
189
+
190
+ def all_versions_of_node(node_id):
191
+ url = f"{base_url}/nodes/{node_id}/versions?statuses=NodeVersionStatusActive&statuses=NodeVersionStatusPending"
192
+
193
+ response = requests.get(url)
194
+ if response.status_code == 200:
195
+ return response.json()
196
+ else:
197
+ return None
198
+
199
+
200
+ def read_cnr_info(fullpath):
201
+ try:
202
+ toml_path = os.path.join(fullpath, 'pyproject.toml')
203
+ tracking_path = os.path.join(fullpath, '.tracking')
204
+
205
+ if not os.path.exists(toml_path) or not os.path.exists(tracking_path):
206
+ return None # not valid CNR node pack
207
+
208
+ with open(toml_path, "r", encoding="utf-8") as f:
209
+ data = toml.load(f)
210
+
211
+ project = data.get('project', {})
212
+ name = project.get('name').strip().lower()
213
+
214
+ # normalize version
215
+ # for example: 2.5 -> 2.5.0
216
+ version = str(manager_util.StrictVersion(project.get('version')))
217
+
218
+ urls = project.get('urls', {})
219
+ repository = urls.get('Repository')
220
+
221
+ if name and version: # repository is optional
222
+ return {
223
+ "id": name,
224
+ "version": version,
225
+ "url": repository
226
+ }
227
+
228
+ return None
229
+ except Exception:
230
+ return None # not valid CNR node pack
231
+
232
+
233
+ def generate_cnr_id(fullpath, cnr_id):
234
+ cnr_id_path = os.path.join(fullpath, '.git', '.cnr-id')
235
+ try:
236
+ if not os.path.exists(cnr_id_path):
237
+ with open(cnr_id_path, "w") as f:
238
+ return f.write(cnr_id)
239
+ except:
240
+ print(f"[ComfyUI Manager] unable to create file: {cnr_id_path}")
241
+
242
+
243
+ def read_cnr_id(fullpath):
244
+ cnr_id_path = os.path.join(fullpath, '.git', '.cnr-id')
245
+ try:
246
+ if os.path.exists(cnr_id_path):
247
+ with open(cnr_id_path) as f:
248
+ return f.read().strip()
249
+ except:
250
+ pass
251
+
252
+ return None
253
+
ComfyUI/custom_nodes/ComfyUI-Manager/glob/git_utils.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import configparser
3
+
4
+
5
+ GITHUB_ENDPOINT = os.getenv('GITHUB_ENDPOINT')
6
+
7
+
8
+ def is_git_repo(path: str) -> bool:
9
+ """ Check if the path is a git repository. """
10
+ # NOTE: Checking it through `git.Repo` must be avoided.
11
+ # It locks the file, causing issues on Windows.
12
+ return os.path.exists(os.path.join(path, '.git'))
13
+
14
+
15
+ def get_commit_hash(fullpath):
16
+ git_head = os.path.join(fullpath, '.git', 'HEAD')
17
+ if os.path.exists(git_head):
18
+ with open(git_head) as f:
19
+ line = f.readline()
20
+
21
+ if line.startswith("ref: "):
22
+ ref = os.path.join(fullpath, '.git', line[5:].strip())
23
+ if os.path.exists(ref):
24
+ with open(ref) as f2:
25
+ return f2.readline().strip()
26
+ else:
27
+ return "unknown"
28
+ else:
29
+ return line
30
+
31
+ return "unknown"
32
+
33
+
34
+ def git_url(fullpath):
35
+ """
36
+ resolve version of unclassified custom node based on remote url in .git/config
37
+ """
38
+ git_config_path = os.path.join(fullpath, '.git', 'config')
39
+
40
+ if not os.path.exists(git_config_path):
41
+ return None
42
+
43
+ # Set `strict=False` to allow duplicate `vscode-merge-base` sections, addressing <https://github.com/ltdrdata/ComfyUI-Manager/issues/1529>
44
+ config = configparser.ConfigParser(strict=False)
45
+ config.read(git_config_path)
46
+
47
+ for k, v in config.items():
48
+ if k.startswith('remote ') and 'url' in v:
49
+ return v['url']
50
+
51
+ return None
52
+
53
+
54
+ def normalize_url(url) -> str:
55
+ github_id = normalize_to_github_id(url)
56
+ if github_id is not None:
57
+ url = f"https://github.com/{github_id}"
58
+
59
+ return url
60
+
61
+
62
+ def normalize_to_github_id(url) -> str:
63
+ if 'github' in url or (GITHUB_ENDPOINT is not None and GITHUB_ENDPOINT in url):
64
+ author = os.path.basename(os.path.dirname(url))
65
+
66
+ if author.startswith('git@github.com:'):
67
+ author = author.split(':')[1]
68
+
69
+ repo_name = os.path.basename(url)
70
+ if repo_name.endswith('.git'):
71
+ repo_name = repo_name[:-4]
72
+
73
+ return f"{author}/{repo_name}"
74
+
75
+ return None
76
+
77
+
78
+ def get_url_for_clone(url):
79
+ url = normalize_url(url)
80
+
81
+ if GITHUB_ENDPOINT is not None and url.startswith('https://github.com/'):
82
+ url = GITHUB_ENDPOINT + url[18:] # url[18:] -> remove `https://github.com`
83
+
84
+ return url
85
+
ComfyUI/custom_nodes/ComfyUI-Manager/glob/manager_core.py ADDED
The diff for this file is too large to render. See raw diff
 
ComfyUI/custom_nodes/ComfyUI-Manager/glob/manager_downloader.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from urllib.parse import urlparse
3
+ import urllib
4
+ import sys
5
+ import logging
6
+ import requests
7
+ from huggingface_hub import HfApi
8
+ from tqdm.auto import tqdm
9
+
10
+
11
+ aria2 = os.getenv('COMFYUI_MANAGER_ARIA2_SERVER')
12
+ HF_ENDPOINT = os.getenv('HF_ENDPOINT')
13
+
14
+
15
+ if aria2 is not None:
16
+ secret = os.getenv('COMFYUI_MANAGER_ARIA2_SECRET')
17
+ url = urlparse(aria2)
18
+ port = url.port
19
+ host = url.scheme + '://' + url.hostname
20
+ import aria2p
21
+
22
+ aria2 = aria2p.API(aria2p.Client(host=host, port=port, secret=secret))
23
+
24
+
25
+ def basic_download_url(url, dest_folder: str, filename: str):
26
+ '''
27
+ Download file from url to dest_folder with filename
28
+ using requests library.
29
+ '''
30
+ import requests
31
+
32
+ # Ensure the destination folder exists
33
+ if not os.path.exists(dest_folder):
34
+ os.makedirs(dest_folder)
35
+
36
+ # Full path to save the file
37
+ dest_path = os.path.join(dest_folder, filename)
38
+
39
+ # Download the file
40
+ response = requests.get(url, stream=True)
41
+ if response.status_code == 200:
42
+ with open(dest_path, 'wb') as file:
43
+ for chunk in response.iter_content(chunk_size=1024):
44
+ if chunk:
45
+ file.write(chunk)
46
+ else:
47
+ raise Exception(f"Failed to download file from {url}")
48
+
49
+
50
+ def download_url(model_url: str, model_dir: str, filename: str):
51
+ if HF_ENDPOINT:
52
+ model_url = model_url.replace('https://huggingface.co', HF_ENDPOINT)
53
+ logging.info(f"model_url replaced by HF_ENDPOINT, new = {model_url}")
54
+ if aria2:
55
+ return aria2_download_url(model_url, model_dir, filename)
56
+ else:
57
+ from torchvision.datasets.utils import download_url as torchvision_download_url
58
+ return torchvision_download_url(model_url, model_dir, filename)
59
+
60
+
61
+ def aria2_find_task(dir: str, filename: str):
62
+ target = os.path.join(dir, filename)
63
+
64
+ downloads = aria2.get_downloads()
65
+
66
+ for download in downloads:
67
+ for file in download.files:
68
+ if file.is_metadata:
69
+ continue
70
+ if str(file.path) == target:
71
+ return download
72
+
73
+
74
+ def aria2_download_url(model_url: str, model_dir: str, filename: str):
75
+ import manager_core as core
76
+ import tqdm
77
+ import time
78
+
79
+ if model_dir.startswith(core.comfy_path):
80
+ model_dir = model_dir[len(core.comfy_path) :]
81
+
82
+ download_dir = model_dir if model_dir.startswith('/') else os.path.join('/models', model_dir)
83
+
84
+ download = aria2_find_task(download_dir, filename)
85
+ if download is None:
86
+ options = {'dir': download_dir, 'out': filename}
87
+ download = aria2.add(model_url, options)[0]
88
+
89
+ if download.is_active:
90
+ with tqdm.tqdm(
91
+ total=download.total_length,
92
+ bar_format='{l_bar}{bar}{r_bar}',
93
+ desc=filename,
94
+ unit='B',
95
+ unit_scale=True,
96
+ ) as progress_bar:
97
+ while download.is_active:
98
+ if progress_bar.total == 0 and download.total_length != 0:
99
+ progress_bar.reset(download.total_length)
100
+ progress_bar.update(download.completed_length - progress_bar.n)
101
+ time.sleep(1)
102
+ download.update()
103
+
104
+
105
+ def download_url_with_agent(url, save_path):
106
+ try:
107
+ headers = {
108
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
109
+
110
+ req = urllib.request.Request(url, headers=headers)
111
+ response = urllib.request.urlopen(req)
112
+ data = response.read()
113
+
114
+ if not os.path.exists(os.path.dirname(save_path)):
115
+ os.makedirs(os.path.dirname(save_path))
116
+
117
+ with open(save_path, 'wb') as f:
118
+ f.write(data)
119
+
120
+ except Exception as e:
121
+ print(f"Download error: {url} / {e}", file=sys.stderr)
122
+ return False
123
+
124
+ print("Installation was successful.")
125
+ return True
126
+
127
+ # NOTE: snapshot_download doesn't provide file size tqdm.
128
+ def download_repo_in_bytes(repo_id, local_dir):
129
+ api = HfApi()
130
+ repo_info = api.repo_info(repo_id=repo_id, files_metadata=True)
131
+
132
+ os.makedirs(local_dir, exist_ok=True)
133
+
134
+ total_size = 0
135
+ for file_info in repo_info.siblings:
136
+ if file_info.size is not None:
137
+ total_size += file_info.size
138
+
139
+ pbar = tqdm(total=total_size, unit="B", unit_scale=True, desc="Downloading")
140
+
141
+ for file_info in repo_info.siblings:
142
+ out_path = os.path.join(local_dir, file_info.rfilename)
143
+ os.makedirs(os.path.dirname(out_path), exist_ok=True)
144
+
145
+ if file_info.size is None:
146
+ continue
147
+
148
+ download_url = f"https://huggingface.co/{repo_id}/resolve/main/{file_info.rfilename}"
149
+
150
+ with requests.get(download_url, stream=True) as r, open(out_path, "wb") as f:
151
+ r.raise_for_status()
152
+ for chunk in r.iter_content(chunk_size=65536):
153
+ if chunk:
154
+ f.write(chunk)
155
+ pbar.update(len(chunk))
156
+
157
+ pbar.close()
158
+
159
+
ComfyUI/custom_nodes/ComfyUI-Manager/glob/manager_server.py ADDED
@@ -0,0 +1,1771 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import traceback
2
+
3
+ import folder_paths
4
+ import locale
5
+ import subprocess # don't remove this
6
+ import concurrent
7
+ import nodes
8
+ import os
9
+ import sys
10
+ import threading
11
+ import re
12
+ import shutil
13
+ import git
14
+ from datetime import datetime
15
+
16
+ from server import PromptServer
17
+ import manager_core as core
18
+ import manager_util
19
+ import cm_global
20
+ import logging
21
+ import asyncio
22
+ import queue
23
+
24
+ import manager_downloader
25
+
26
+
27
+ logging.info(f"### Loading: ComfyUI-Manager ({core.version_str})")
28
+ logging.info("[ComfyUI-Manager] network_mode: " + core.get_config()['network_mode'])
29
+
30
+ comfy_ui_hash = "-"
31
+ comfyui_tag = None
32
+
33
+ SECURITY_MESSAGE_MIDDLE_OR_BELOW = "ERROR: To use this action, a security_level of `middle or below` is required. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
34
+ SECURITY_MESSAGE_NORMAL_MINUS = "ERROR: To use this feature, you must either set '--listen' to a local IP and set the security level to 'normal-' or lower, or set the security level to 'middle' or 'weak'. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
35
+ SECURITY_MESSAGE_GENERAL = "ERROR: This installation is not allowed in this security_level. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
36
+ SECURITY_MESSAGE_NORMAL_MINUS_MODEL = "ERROR: Downloading models that are not in '.safetensors' format is only allowed for models registered in the 'default' channel at this security level. If you want to download this model, set the security level to 'normal-' or lower."
37
+
38
+ routes = PromptServer.instance.routes
39
+
40
+ def handle_stream(stream, prefix):
41
+ stream.reconfigure(encoding=locale.getpreferredencoding(), errors='replace')
42
+ for msg in stream:
43
+ if prefix == '[!]' and ('it/s]' in msg or 's/it]' in msg) and ('%|' in msg or 'it [' in msg):
44
+ if msg.startswith('100%'):
45
+ print('\r' + msg, end="", file=sys.stderr),
46
+ else:
47
+ print('\r' + msg[:-1], end="", file=sys.stderr),
48
+ else:
49
+ if prefix == '[!]':
50
+ print(prefix, msg, end="", file=sys.stderr)
51
+ else:
52
+ print(prefix, msg, end="")
53
+
54
+
55
+ from comfy.cli_args import args
56
+ import latent_preview
57
+
58
+ def is_loopback(address):
59
+ import ipaddress
60
+ try:
61
+ return ipaddress.ip_address(address).is_loopback
62
+ except ValueError:
63
+ return False
64
+
65
+ is_local_mode = is_loopback(args.listen)
66
+
67
+
68
+ model_dir_name_map = {
69
+ "checkpoints": "checkpoints",
70
+ "checkpoint": "checkpoints",
71
+ "unclip": "checkpoints",
72
+ "text_encoders": "text_encoders",
73
+ "clip": "text_encoders",
74
+ "vae": "vae",
75
+ "lora": "loras",
76
+ "t2i-adapter": "controlnet",
77
+ "t2i-style": "controlnet",
78
+ "controlnet": "controlnet",
79
+ "clip_vision": "clip_vision",
80
+ "gligen": "gligen",
81
+ "upscale": "upscale_models",
82
+ "embedding": "embeddings",
83
+ "embeddings": "embeddings",
84
+ "unet": "diffusion_models",
85
+ "diffusion_model": "diffusion_models",
86
+ }
87
+
88
+
89
+ def is_allowed_security_level(level):
90
+ if level == 'block':
91
+ return False
92
+ elif level == 'high':
93
+ if is_local_mode:
94
+ return core.get_config()['security_level'] in ['weak', 'normal-']
95
+ else:
96
+ return core.get_config()['security_level'] == 'weak'
97
+ elif level == 'middle':
98
+ return core.get_config()['security_level'] in ['weak', 'normal', 'normal-']
99
+ else:
100
+ return True
101
+
102
+
103
+ async def get_risky_level(files, pip_packages):
104
+ json_data1 = await core.get_data_by_mode('local', 'custom-node-list.json')
105
+ json_data2 = await core.get_data_by_mode('cache', 'custom-node-list.json', channel_url='https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main')
106
+
107
+ all_urls = set()
108
+ for x in json_data1['custom_nodes'] + json_data2['custom_nodes']:
109
+ all_urls.update(x.get('files', []))
110
+
111
+ for x in files:
112
+ if x not in all_urls:
113
+ return "high"
114
+
115
+ all_pip_packages = set()
116
+ for x in json_data1['custom_nodes'] + json_data2['custom_nodes']:
117
+ all_pip_packages.update(x.get('pip', []))
118
+
119
+ for p in pip_packages:
120
+ if p not in all_pip_packages:
121
+ return "block"
122
+
123
+ return "middle"
124
+
125
+
126
+ class ManagerFuncsInComfyUI(core.ManagerFuncs):
127
+ def get_current_preview_method(self):
128
+ if args.preview_method == latent_preview.LatentPreviewMethod.Auto:
129
+ return "auto"
130
+ elif args.preview_method == latent_preview.LatentPreviewMethod.Latent2RGB:
131
+ return "latent2rgb"
132
+ elif args.preview_method == latent_preview.LatentPreviewMethod.TAESD:
133
+ return "taesd"
134
+ else:
135
+ return "none"
136
+
137
+ def run_script(self, cmd, cwd='.'):
138
+ if len(cmd) > 0 and cmd[0].startswith("#"):
139
+ logging.error(f"[ComfyUI-Manager] Unexpected behavior: `{cmd}`")
140
+ return 0
141
+
142
+ process = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1, env=core.get_script_env())
143
+
144
+ stdout_thread = threading.Thread(target=handle_stream, args=(process.stdout, ""))
145
+ stderr_thread = threading.Thread(target=handle_stream, args=(process.stderr, "[!]"))
146
+
147
+ stdout_thread.start()
148
+ stderr_thread.start()
149
+
150
+ stdout_thread.join()
151
+ stderr_thread.join()
152
+
153
+ return process.wait()
154
+
155
+
156
+ core.manager_funcs = ManagerFuncsInComfyUI()
157
+
158
+ sys.path.append('../..')
159
+
160
+ from manager_downloader import download_url, download_url_with_agent
161
+
162
+ core.comfy_path = os.path.dirname(folder_paths.__file__)
163
+ core.js_path = os.path.join(core.comfy_path, "web", "extensions")
164
+
165
+ local_db_model = os.path.join(manager_util.comfyui_manager_path, "model-list.json")
166
+ local_db_alter = os.path.join(manager_util.comfyui_manager_path, "alter-list.json")
167
+ local_db_custom_node_list = os.path.join(manager_util.comfyui_manager_path, "custom-node-list.json")
168
+ local_db_extension_node_mappings = os.path.join(manager_util.comfyui_manager_path, "extension-node-map.json")
169
+
170
+
171
+ def set_preview_method(method):
172
+ if method == 'auto':
173
+ args.preview_method = latent_preview.LatentPreviewMethod.Auto
174
+ elif method == 'latent2rgb':
175
+ args.preview_method = latent_preview.LatentPreviewMethod.Latent2RGB
176
+ elif method == 'taesd':
177
+ args.preview_method = latent_preview.LatentPreviewMethod.TAESD
178
+ else:
179
+ args.preview_method = latent_preview.LatentPreviewMethod.NoPreviews
180
+
181
+ core.get_config()['preview_method'] = method
182
+
183
+
184
+ set_preview_method(core.get_config()['preview_method'])
185
+
186
+
187
+ def set_component_policy(mode):
188
+ core.get_config()['component_policy'] = mode
189
+
190
+ def set_update_policy(mode):
191
+ core.get_config()['update_policy'] = mode
192
+
193
+ def set_db_mode(mode):
194
+ core.get_config()['db_mode'] = mode
195
+
196
+ def print_comfyui_version():
197
+ global comfy_ui_hash
198
+ global comfyui_tag
199
+
200
+ is_detached = False
201
+ try:
202
+ repo = git.Repo(os.path.dirname(folder_paths.__file__))
203
+ core.comfy_ui_revision = len(list(repo.iter_commits('HEAD')))
204
+
205
+ comfy_ui_hash = repo.head.commit.hexsha
206
+ cm_global.variables['comfyui.revision'] = core.comfy_ui_revision
207
+
208
+ core.comfy_ui_commit_datetime = repo.head.commit.committed_datetime
209
+ cm_global.variables['comfyui.commit_datetime'] = core.comfy_ui_commit_datetime
210
+
211
+ is_detached = repo.head.is_detached
212
+ current_branch = repo.active_branch.name
213
+
214
+ comfyui_tag = core.get_comfyui_tag()
215
+
216
+ try:
217
+ if not os.environ.get('__COMFYUI_DESKTOP_VERSION__') and core.comfy_ui_commit_datetime.date() < core.comfy_ui_required_commit_datetime.date():
218
+ logging.warning(f"\n\n## [WARN] ComfyUI-Manager: Your ComfyUI version ({core.comfy_ui_revision})[{core.comfy_ui_commit_datetime.date()}] is too old. Please update to the latest version. ##\n\n")
219
+ except:
220
+ pass
221
+
222
+ # process on_revision_detected -->
223
+ if 'cm.on_revision_detected_handler' in cm_global.variables:
224
+ for k, f in cm_global.variables['cm.on_revision_detected_handler']:
225
+ try:
226
+ f(core.comfy_ui_revision)
227
+ except Exception:
228
+ logging.error(f"[ERROR] '{k}' on_revision_detected_handler")
229
+ traceback.print_exc()
230
+
231
+ del cm_global.variables['cm.on_revision_detected_handler']
232
+ else:
233
+ logging.warning("[ComfyUI-Manager] Some features are restricted due to your ComfyUI being outdated.")
234
+ # <--
235
+
236
+ if current_branch == "master":
237
+ if comfyui_tag:
238
+ logging.info(f"### ComfyUI Version: {comfyui_tag} | Released on '{core.comfy_ui_commit_datetime.date()}'")
239
+ else:
240
+ logging.info(f"### ComfyUI Revision: {core.comfy_ui_revision} [{comfy_ui_hash[:8]}] | Released on '{core.comfy_ui_commit_datetime.date()}'")
241
+ else:
242
+ if comfyui_tag:
243
+ logging.info(f"### ComfyUI Version: {comfyui_tag} on '{current_branch}' | Released on '{core.comfy_ui_commit_datetime.date()}'")
244
+ else:
245
+ logging.info(f"### ComfyUI Revision: {core.comfy_ui_revision} on '{current_branch}' [{comfy_ui_hash[:8]}] | Released on '{core.comfy_ui_commit_datetime.date()}'")
246
+ except:
247
+ if is_detached:
248
+ logging.info(f"### ComfyUI Revision: {core.comfy_ui_revision} [{comfy_ui_hash[:8]}] *DETACHED | Released on '{core.comfy_ui_commit_datetime.date()}'")
249
+ else:
250
+ logging.info("### ComfyUI Revision: UNKNOWN (The currently installed ComfyUI is not a Git repository)")
251
+
252
+
253
+ print_comfyui_version()
254
+ core.check_invalid_nodes()
255
+
256
+
257
+
258
+ def setup_environment():
259
+ git_exe = core.get_config()['git_exe']
260
+
261
+ if git_exe != '':
262
+ git.Git().update_environment(GIT_PYTHON_GIT_EXECUTABLE=git_exe)
263
+
264
+
265
+ setup_environment()
266
+
267
+ # Expand Server api
268
+
269
+ from aiohttp import web
270
+ import aiohttp
271
+ import json
272
+ import zipfile
273
+ import urllib.request
274
+
275
+
276
+ def get_model_dir(data, show_log=False):
277
+ if 'download_model_base' in folder_paths.folder_names_and_paths:
278
+ models_base = folder_paths.folder_names_and_paths['download_model_base'][0][0]
279
+ else:
280
+ models_base = folder_paths.models_dir
281
+
282
+ # NOTE: Validate to prevent path traversal.
283
+ if any(char in data['filename'] for char in {'/', '\\', ':'}):
284
+ return None
285
+
286
+ def resolve_custom_node(save_path):
287
+ save_path = save_path[13:] # remove 'custom_nodes/'
288
+
289
+ # NOTE: Validate to prevent path traversal.
290
+ if save_path.startswith(os.path.sep) or ':' in save_path:
291
+ return None
292
+
293
+ repo_name = save_path.replace('\\','/').split('/')[0] # get custom node repo name
294
+
295
+ # NOTE: The creation of files within the custom node path should be removed in the future.
296
+ repo_path = core.lookup_installed_custom_nodes_legacy(repo_name)
297
+ if repo_path is not None and repo_path[0]:
298
+ # Returns the retargeted path based on the actually installed repository
299
+ return os.path.join(os.path.dirname(repo_path[1]), save_path)
300
+ else:
301
+ return None
302
+
303
+ if data['save_path'] != 'default':
304
+ if '..' in data['save_path'] or data['save_path'].startswith('/'):
305
+ if show_log:
306
+ logging.info(f"[WARN] '{data['save_path']}' is not allowed path. So it will be saved into 'models/etc'.")
307
+ base_model = os.path.join(models_base, "etc")
308
+ else:
309
+ if data['save_path'].startswith("custom_nodes"):
310
+ base_model = resolve_custom_node(data['save_path'])
311
+ if base_model is None:
312
+ if show_log:
313
+ logging.info(f"[ComfyUI-Manager] The target custom node for model download is not installed: {data['save_path']}")
314
+ return None
315
+ else:
316
+ base_model = os.path.join(models_base, data['save_path'])
317
+ else:
318
+ model_dir_name = model_dir_name_map.get(data['type'].lower())
319
+ if model_dir_name is not None:
320
+ base_model = folder_paths.folder_names_and_paths[model_dir_name][0][0]
321
+ else:
322
+ base_model = os.path.join(models_base, "etc")
323
+
324
+ return base_model
325
+
326
+
327
+ def get_model_path(data, show_log=False):
328
+ base_model = get_model_dir(data, show_log)
329
+ if base_model is None:
330
+ return None
331
+ else:
332
+ if data['filename'] == '<huggingface>':
333
+ return os.path.join(base_model, os.path.basename(data['url']))
334
+ else:
335
+ return os.path.join(base_model, data['filename'])
336
+
337
+
338
+ def check_state_of_git_node_pack(node_packs, do_fetch=False, do_update_check=True, do_update=False):
339
+ if do_fetch:
340
+ print("Start fetching...", end="")
341
+ elif do_update:
342
+ print("Start updating...", end="")
343
+ elif do_update_check:
344
+ print("Start update check...", end="")
345
+
346
+ def process_custom_node(item):
347
+ core.check_state_of_git_node_pack_single(item, do_fetch, do_update_check, do_update)
348
+
349
+ with concurrent.futures.ThreadPoolExecutor(4) as executor:
350
+ for k, v in node_packs.items():
351
+ if v.get('active_version') in ['unknown', 'nightly']:
352
+ executor.submit(process_custom_node, v)
353
+
354
+ if do_fetch:
355
+ print("\x1b[2K\rFetching done.")
356
+ elif do_update:
357
+ update_exists = any(item.get('updatable', False) for item in node_packs.values())
358
+ if update_exists:
359
+ print("\x1b[2K\rUpdate done.")
360
+ else:
361
+ print("\x1b[2K\rAll extensions are already up-to-date.")
362
+ elif do_update_check:
363
+ print("\x1b[2K\rUpdate check done.")
364
+
365
+
366
+ def nickname_filter(json_obj):
367
+ preemptions_map = {}
368
+
369
+ for k, x in json_obj.items():
370
+ if 'preemptions' in x[1]:
371
+ for y in x[1]['preemptions']:
372
+ preemptions_map[y] = k
373
+ elif k.endswith("/ComfyUI"):
374
+ for y in x[0]:
375
+ preemptions_map[y] = k
376
+
377
+ updates = {}
378
+ for k, x in json_obj.items():
379
+ removes = set()
380
+ for y in x[0]:
381
+ k2 = preemptions_map.get(y)
382
+ if k2 is not None and k != k2:
383
+ removes.add(y)
384
+
385
+ if len(removes) > 0:
386
+ updates[k] = [y for y in x[0] if y not in removes]
387
+
388
+ for k, v in updates.items():
389
+ json_obj[k][0] = v
390
+
391
+ return json_obj
392
+
393
+
394
+ task_queue = queue.Queue()
395
+ nodepack_result = {}
396
+ model_result = {}
397
+ tasks_in_progress = set()
398
+ task_worker_lock = threading.Lock()
399
+
400
+ async def task_worker():
401
+ global task_queue
402
+ global nodepack_result
403
+ global model_result
404
+ global tasks_in_progress
405
+
406
+ async def do_install(item) -> str:
407
+ ui_id, node_spec_str, channel, mode, skip_post_install = item
408
+
409
+ try:
410
+ node_spec = core.unified_manager.resolve_node_spec(node_spec_str)
411
+ if node_spec is None:
412
+ logging.error(f"Cannot resolve install target: '{node_spec_str}'")
413
+ return f"Cannot resolve install target: '{node_spec_str}'"
414
+
415
+ node_name, version_spec, is_specified = node_spec
416
+ res = await core.unified_manager.install_by_id(node_name, version_spec, channel, mode, return_postinstall=skip_post_install)
417
+ # discard post install if skip_post_install mode
418
+
419
+ if res.action not in ['skip', 'enable', 'install-git', 'install-cnr', 'switch-cnr']:
420
+ logging.error(f"[ComfyUI-Manager] Installation failed:\n{res.msg}")
421
+ return res.msg
422
+
423
+ elif not res.result:
424
+ logging.error(f"[ComfyUI-Manager] Installation failed:\n{res.msg}")
425
+ return res.msg
426
+
427
+ return 'success'
428
+ except Exception:
429
+ traceback.print_exc()
430
+ return f"Installation failed:\n{node_spec_str}"
431
+
432
+ async def do_update(item):
433
+ ui_id, node_name, node_ver = item
434
+
435
+ try:
436
+ res = core.unified_manager.unified_update(node_name, node_ver)
437
+
438
+ if res.ver == 'unknown':
439
+ url = core.unified_manager.unknown_active_nodes[node_name][0]
440
+ title = os.path.basename(url)
441
+ else:
442
+ url = core.unified_manager.cnr_map[node_name].get('repository')
443
+ title = core.unified_manager.cnr_map[node_name]['name']
444
+
445
+ manager_util.clear_pip_cache()
446
+
447
+ if url is not None:
448
+ base_res = {'url': url, 'title': title}
449
+ else:
450
+ base_res = {'title': title}
451
+
452
+ if res.result:
453
+ if res.action == 'skip':
454
+ base_res['msg'] = 'skip'
455
+ return base_res
456
+ else:
457
+ base_res['msg'] = 'success'
458
+ return base_res
459
+
460
+ base_res['msg'] = f"An error occurred while updating '{node_name}'."
461
+ logging.error(f"\nERROR: An error occurred while updating '{node_name}'. (res.result={res.result}, res.action={res.action})")
462
+ return base_res
463
+ except Exception:
464
+ traceback.print_exc()
465
+
466
+ return {'msg':f"An error occurred while updating '{node_name}'."}
467
+
468
+ async def do_update_comfyui(is_stable) -> str:
469
+ try:
470
+ repo_path = os.path.dirname(folder_paths.__file__)
471
+ latest_tag = None
472
+ if is_stable:
473
+ res, latest_tag = core.update_to_stable_comfyui(repo_path)
474
+ else:
475
+ res = core.update_path(repo_path)
476
+
477
+ if res == "fail":
478
+ logging.error("ComfyUI update failed")
479
+ return "fail"
480
+ elif res == "updated":
481
+ if is_stable:
482
+ logging.info("ComfyUI is updated to latest stable version.")
483
+ return "success-stable-"+latest_tag
484
+ else:
485
+ logging.info("ComfyUI is updated to latest nightly version.")
486
+ return "success-nightly"
487
+ else: # skipped
488
+ logging.info("ComfyUI is up-to-date.")
489
+ return "skip"
490
+
491
+ except Exception:
492
+ traceback.print_exc()
493
+
494
+ return "An error occurred while updating 'comfyui'."
495
+
496
+ async def do_fix(item) -> str:
497
+ ui_id, node_name, node_ver = item
498
+
499
+ try:
500
+ res = core.unified_manager.unified_fix(node_name, node_ver)
501
+
502
+ if res.result:
503
+ return 'success'
504
+ else:
505
+ logging.error(res.msg)
506
+
507
+ logging.error(f"\nERROR: An error occurred while fixing '{node_name}@{node_ver}'.")
508
+ except Exception:
509
+ traceback.print_exc()
510
+
511
+ return f"An error occurred while fixing '{node_name}@{node_ver}'."
512
+
513
+ async def do_uninstall(item) -> str:
514
+ ui_id, node_name, is_unknown = item
515
+
516
+ try:
517
+ res = core.unified_manager.unified_uninstall(node_name, is_unknown)
518
+
519
+ if res.result:
520
+ return 'success'
521
+
522
+ logging.error(f"\nERROR: An error occurred while uninstalling '{node_name}'.")
523
+ except Exception:
524
+ traceback.print_exc()
525
+
526
+ return f"An error occurred while uninstalling '{node_name}'."
527
+
528
+ async def do_disable(item) -> str:
529
+ ui_id, node_name, is_unknown = item
530
+
531
+ try:
532
+ res = core.unified_manager.unified_disable(node_name, is_unknown)
533
+
534
+ if res:
535
+ return 'success'
536
+
537
+ except Exception:
538
+ traceback.print_exc()
539
+
540
+ return f"Failed to disable: '{node_name}'"
541
+
542
+ async def do_install_model(item) -> str:
543
+ ui_id, json_data = item
544
+
545
+ model_path = get_model_path(json_data)
546
+ model_url = json_data['url']
547
+
548
+ res = False
549
+
550
+ try:
551
+ if model_path is not None:
552
+ logging.info(f"Install model '{json_data['name']}' from '{model_url}' into '{model_path}'")
553
+
554
+ if json_data['filename'] == '<huggingface>':
555
+ if os.path.exists(os.path.join(model_path, os.path.dirname(json_data['url']))):
556
+ logging.error(f"[ComfyUI-Manager] the model path already exists: {model_path}")
557
+ return f"The model path already exists: {model_path}"
558
+
559
+ logging.info(f"[ComfyUI-Manager] Downloading '{model_url}' into '{model_path}'")
560
+ manager_downloader.download_repo_in_bytes(repo_id=model_url, local_dir=model_path)
561
+
562
+ return 'success'
563
+
564
+ elif not core.get_config()['model_download_by_agent'] and (
565
+ model_url.startswith('https://github.com') or model_url.startswith('https://huggingface.co') or model_url.startswith('https://heibox.uni-heidelberg.de')):
566
+ model_dir = get_model_dir(json_data, True)
567
+ download_url(model_url, model_dir, filename=json_data['filename'])
568
+ if model_path.endswith('.zip'):
569
+ res = core.unzip(model_path)
570
+ else:
571
+ res = True
572
+
573
+ if res:
574
+ return 'success'
575
+ else:
576
+ res = download_url_with_agent(model_url, model_path)
577
+ if res and model_path.endswith('.zip'):
578
+ res = core.unzip(model_path)
579
+ else:
580
+ logging.error(f"[ComfyUI-Manager] Model installation error: invalid model type - {json_data['type']}")
581
+
582
+ if res:
583
+ return 'success'
584
+
585
+ except Exception as e:
586
+ logging.error(f"[ComfyUI-Manager] ERROR: {e}", file=sys.stderr)
587
+
588
+ return f"Model installation error: {model_url}"
589
+
590
+ stats = {}
591
+
592
+ while True:
593
+ done_count = len(nodepack_result) + len(model_result)
594
+ total_count = done_count + task_queue.qsize()
595
+
596
+ if task_queue.empty():
597
+ logging.info(f"\n[ComfyUI-Manager] Queued works are completed.\n{stats}")
598
+
599
+ logging.info("\nAfter restarting ComfyUI, please refresh the browser.")
600
+ PromptServer.instance.send_sync("cm-queue-status",
601
+ {'status': 'done',
602
+ 'nodepack_result': nodepack_result, 'model_result': model_result,
603
+ 'total_count': total_count, 'done_count': done_count})
604
+ nodepack_result = {}
605
+ task_queue = queue.Queue()
606
+ return # terminate worker thread
607
+
608
+ with task_worker_lock:
609
+ kind, item = task_queue.get()
610
+ tasks_in_progress.add((kind, item[0]))
611
+
612
+ try:
613
+ if kind == 'install':
614
+ msg = await do_install(item)
615
+ elif kind == 'install-model':
616
+ msg = await do_install_model(item)
617
+ elif kind == 'update':
618
+ msg = await do_update(item)
619
+ elif kind == 'update-main':
620
+ msg = await do_update(item)
621
+ elif kind == 'update-comfyui':
622
+ msg = await do_update_comfyui(item[1])
623
+ elif kind == 'fix':
624
+ msg = await do_fix(item)
625
+ elif kind == 'uninstall':
626
+ msg = await do_uninstall(item)
627
+ elif kind == 'disable':
628
+ msg = await do_disable(item)
629
+ else:
630
+ msg = "Unexpected kind: " + kind
631
+ except Exception:
632
+ traceback.print_exc()
633
+ msg = f"Exception: {(kind, item)}"
634
+
635
+ with task_worker_lock:
636
+ tasks_in_progress.remove((kind, item[0]))
637
+
638
+ ui_id = item[0]
639
+ if kind == 'install-model':
640
+ model_result[ui_id] = msg
641
+ ui_target = "model_manager"
642
+ elif kind == 'update-main':
643
+ nodepack_result[ui_id] = msg
644
+ ui_target = "main"
645
+ elif kind == 'update-comfyui':
646
+ nodepack_result['comfyui'] = msg
647
+ ui_target = "main"
648
+ elif kind == 'update':
649
+ nodepack_result[ui_id] = msg['msg']
650
+ ui_target = "nodepack_manager"
651
+ else:
652
+ nodepack_result[ui_id] = msg
653
+ ui_target = "nodepack_manager"
654
+
655
+ stats[kind] = stats.get(kind, 0) + 1
656
+
657
+ PromptServer.instance.send_sync("cm-queue-status",
658
+ {'status': 'in_progress', 'target': item[0], 'ui_target': ui_target,
659
+ 'total_count': total_count, 'done_count': done_count})
660
+
661
+
662
+ @routes.get("/customnode/getmappings")
663
+ async def fetch_customnode_mappings(request):
664
+ """
665
+ provide unified (node -> node pack) mapping list
666
+ """
667
+ mode = request.rel_url.query["mode"]
668
+
669
+ nickname_mode = False
670
+ if mode == "nickname":
671
+ mode = "local"
672
+ nickname_mode = True
673
+
674
+ json_obj = await core.get_data_by_mode(mode, 'extension-node-map.json')
675
+ json_obj = core.map_to_unified_keys(json_obj)
676
+
677
+ if nickname_mode:
678
+ json_obj = nickname_filter(json_obj)
679
+
680
+ all_nodes = set()
681
+ patterns = []
682
+ for k, x in json_obj.items():
683
+ all_nodes.update(set(x[0]))
684
+
685
+ if 'nodename_pattern' in x[1]:
686
+ patterns.append((x[1]['nodename_pattern'], x[0]))
687
+
688
+ missing_nodes = set(nodes.NODE_CLASS_MAPPINGS.keys()) - all_nodes
689
+
690
+ for x in missing_nodes:
691
+ for pat, item in patterns:
692
+ if re.match(pat, x):
693
+ item.append(x)
694
+
695
+ return web.json_response(json_obj, content_type='application/json')
696
+
697
+
698
+ @routes.get("/customnode/fetch_updates")
699
+ async def fetch_updates(request):
700
+ try:
701
+ if request.rel_url.query["mode"] == "local":
702
+ channel = 'local'
703
+ else:
704
+ channel = core.get_config()['channel_url']
705
+
706
+ await core.unified_manager.reload(request.rel_url.query["mode"])
707
+ await core.unified_manager.get_custom_nodes(channel, request.rel_url.query["mode"])
708
+
709
+ res = core.unified_manager.fetch_or_pull_git_repo(is_pull=False)
710
+
711
+ for x in res['failed']:
712
+ logging.error(f"FETCH FAILED: {x}")
713
+
714
+ logging.info("\nDone.")
715
+
716
+ if len(res['updated']) > 0:
717
+ return web.Response(status=201)
718
+
719
+ return web.Response(status=200)
720
+ except:
721
+ traceback.print_exc()
722
+ return web.Response(status=400)
723
+
724
+
725
+ @routes.get("/manager/queue/update_all")
726
+ async def update_all(request):
727
+ if not is_allowed_security_level('middle'):
728
+ logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
729
+ return web.Response(status=403)
730
+
731
+ with task_worker_lock:
732
+ is_processing = task_worker_thread is not None and task_worker_thread.is_alive()
733
+ if is_processing:
734
+ return web.Response(status=401)
735
+
736
+ await core.save_snapshot_with_postfix('autosave')
737
+
738
+ if request.rel_url.query["mode"] == "local":
739
+ channel = 'local'
740
+ else:
741
+ channel = core.get_config()['channel_url']
742
+
743
+ await core.unified_manager.reload(request.rel_url.query["mode"])
744
+ await core.unified_manager.get_custom_nodes(channel, request.rel_url.query["mode"])
745
+
746
+ for k, v in core.unified_manager.active_nodes.items():
747
+ if k == 'comfyui-manager':
748
+ # skip updating comfyui-manager if desktop version
749
+ if os.environ.get('__COMFYUI_DESKTOP_VERSION__'):
750
+ continue
751
+
752
+ update_item = k, k, v[0]
753
+ task_queue.put(("update-main", update_item))
754
+
755
+ for k, v in core.unified_manager.unknown_active_nodes.items():
756
+ if k == 'comfyui-manager':
757
+ # skip updating comfyui-manager if desktop version
758
+ if os.environ.get('__COMFYUI_DESKTOP_VERSION__'):
759
+ continue
760
+
761
+ update_item = k, k, 'unknown'
762
+ task_queue.put(("update-main", update_item))
763
+
764
+ return web.Response(status=200)
765
+
766
+
767
+ def convert_markdown_to_html(input_text):
768
+ pattern_a = re.compile(r'\[a/([^]]+)]\(([^)]+)\)')
769
+ pattern_w = re.compile(r'\[w/([^]]+)]')
770
+ pattern_i = re.compile(r'\[i/([^]]+)]')
771
+ pattern_bold = re.compile(r'\*\*([^*]+)\*\*')
772
+ pattern_white = re.compile(r'%%([^*]+)%%')
773
+
774
+ def replace_a(match):
775
+ return f"<a href='{match.group(2)}' target='blank'>{match.group(1)}</a>"
776
+
777
+ def replace_w(match):
778
+ return f"<p class='cm-warn-note'>{match.group(1)}</p>"
779
+
780
+ def replace_i(match):
781
+ return f"<p class='cm-info-note'>{match.group(1)}</p>"
782
+
783
+ def replace_bold(match):
784
+ return f"<B>{match.group(1)}</B>"
785
+
786
+ def replace_white(match):
787
+ return f"<font color='white'>{match.group(1)}</font>"
788
+
789
+ input_text = input_text.replace('\\[', '&#91;').replace('\\]', '&#93;').replace('<', '&lt;').replace('>', '&gt;')
790
+
791
+ result_text = re.sub(pattern_a, replace_a, input_text)
792
+ result_text = re.sub(pattern_w, replace_w, result_text)
793
+ result_text = re.sub(pattern_i, replace_i, result_text)
794
+ result_text = re.sub(pattern_bold, replace_bold, result_text)
795
+ result_text = re.sub(pattern_white, replace_white, result_text)
796
+
797
+ return result_text.replace("\n", "<BR>")
798
+
799
+
800
+ def populate_markdown(x):
801
+ if 'description' in x:
802
+ x['description'] = convert_markdown_to_html(manager_util.sanitize_tag(x['description']))
803
+
804
+ if 'name' in x:
805
+ x['name'] = manager_util.sanitize_tag(x['name'])
806
+
807
+ if 'title' in x:
808
+ x['title'] = manager_util.sanitize_tag(x['title'])
809
+
810
+
811
+ # freeze imported version
812
+ startup_time_installed_node_packs = core.get_installed_node_packs()
813
+ @routes.get("/customnode/installed")
814
+ async def installed_list(request):
815
+ mode = request.query.get('mode', 'default')
816
+
817
+ if mode == 'imported':
818
+ res = startup_time_installed_node_packs
819
+ else:
820
+ res = core.get_installed_node_packs()
821
+
822
+ return web.json_response(res, content_type='application/json')
823
+
824
+
825
+ @routes.get("/customnode/getlist")
826
+ async def fetch_customnode_list(request):
827
+ """
828
+ provide unified custom node list
829
+ """
830
+ if request.rel_url.query.get("skip_update", '').lower() == "true":
831
+ skip_update = True
832
+ else:
833
+ skip_update = False
834
+
835
+ if request.rel_url.query["mode"] == "local":
836
+ channel = 'local'
837
+ else:
838
+ channel = core.get_config()['channel_url']
839
+
840
+ node_packs = await core.get_unified_total_nodes(channel, request.rel_url.query["mode"], 'cache')
841
+ json_obj_github = core.get_data_by_mode(request.rel_url.query["mode"], 'github-stats.json', 'default')
842
+ json_obj_extras = core.get_data_by_mode(request.rel_url.query["mode"], 'extras.json', 'default')
843
+
844
+ core.populate_github_stats(node_packs, await json_obj_github)
845
+ core.populate_favorites(node_packs, await json_obj_extras)
846
+
847
+ check_state_of_git_node_pack(node_packs, not skip_update, do_update_check=not skip_update)
848
+
849
+ for v in node_packs.values():
850
+ populate_markdown(v)
851
+
852
+ if channel != 'local':
853
+ found = 'custom'
854
+
855
+ for name, url in core.get_channel_dict().items():
856
+ if url == channel:
857
+ found = name
858
+ break
859
+
860
+ channel = found
861
+
862
+ result = dict(channel=channel, node_packs=node_packs)
863
+
864
+ return web.json_response(result, content_type='application/json')
865
+
866
+
867
+ @routes.get("/customnode/alternatives")
868
+ async def fetch_customnode_alternatives(request):
869
+ alter_json = await core.get_data_by_mode(request.rel_url.query["mode"], 'alter-list.json')
870
+
871
+ res = {}
872
+
873
+ for item in alter_json['items']:
874
+ populate_markdown(item)
875
+ res[item['id']] = item
876
+
877
+ res = core.map_to_unified_keys(res)
878
+
879
+ return web.json_response(res, content_type='application/json')
880
+
881
+
882
+ def check_model_installed(json_obj):
883
+ def is_exists(model_dir_name, filename, url):
884
+ if filename == '<huggingface>':
885
+ filename = os.path.basename(url)
886
+
887
+ dirs = folder_paths.get_folder_paths(model_dir_name)
888
+
889
+ for x in dirs:
890
+ if os.path.exists(os.path.join(x, filename)):
891
+ return True
892
+
893
+ return False
894
+
895
+ model_dir_names = ['checkpoints', 'loras', 'vae', 'text_encoders', 'diffusion_models', 'clip_vision', 'embeddings',
896
+ 'diffusers', 'vae_approx', 'controlnet', 'gligen', 'upscale_models', 'hypernetworks',
897
+ 'photomaker', 'classifiers']
898
+
899
+ total_models_files = set()
900
+ for x in model_dir_names:
901
+ for y in folder_paths.get_filename_list(x):
902
+ total_models_files.add(y)
903
+
904
+ def process_model_phase(item):
905
+ if 'diffusion' not in item['filename'] and 'pytorch' not in item['filename'] and 'model' not in item['filename']:
906
+ # non-general name case
907
+ if item['filename'] in total_models_files:
908
+ item['installed'] = 'True'
909
+ return
910
+
911
+ if item['save_path'] == 'default':
912
+ model_dir_name = model_dir_name_map.get(item['type'].lower())
913
+ if model_dir_name is not None:
914
+ item['installed'] = str(is_exists(model_dir_name, item['filename'], item['url']))
915
+ else:
916
+ item['installed'] = 'False'
917
+ else:
918
+ model_dir_name = item['save_path'].split('/')[0]
919
+ if model_dir_name in folder_paths.folder_names_and_paths:
920
+ if is_exists(model_dir_name, item['filename'], item['url']):
921
+ item['installed'] = 'True'
922
+
923
+ if 'installed' not in item:
924
+ if item['filename'] == '<huggingface>':
925
+ filename = os.path.basename(item['url'])
926
+ else:
927
+ filename = item['filename']
928
+
929
+ fullpath = os.path.join(folder_paths.models_dir, item['save_path'], filename)
930
+
931
+ item['installed'] = 'True' if os.path.exists(fullpath) else 'False'
932
+
933
+ with concurrent.futures.ThreadPoolExecutor(8) as executor:
934
+ for item in json_obj['models']:
935
+ executor.submit(process_model_phase, item)
936
+
937
+
938
+ @routes.get("/externalmodel/getlist")
939
+ async def fetch_externalmodel_list(request):
940
+ # The model list is only allowed in the default channel, yet.
941
+ json_obj = await core.get_data_by_mode(request.rel_url.query["mode"], 'model-list.json')
942
+
943
+ check_model_installed(json_obj)
944
+
945
+ for x in json_obj['models']:
946
+ populate_markdown(x)
947
+
948
+ return web.json_response(json_obj, content_type='application/json')
949
+
950
+
951
+ @PromptServer.instance.routes.get("/snapshot/getlist")
952
+ async def get_snapshot_list(request):
953
+ items = [f[:-5] for f in os.listdir(core.manager_snapshot_path) if f.endswith('.json')]
954
+ items.sort(reverse=True)
955
+ return web.json_response({'items': items}, content_type='application/json')
956
+
957
+
958
+ @routes.get("/snapshot/remove")
959
+ async def remove_snapshot(request):
960
+ if not is_allowed_security_level('middle'):
961
+ logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
962
+ return web.Response(status=403)
963
+
964
+ try:
965
+ target = request.rel_url.query["target"]
966
+
967
+ path = os.path.join(core.manager_snapshot_path, f"{target}.json")
968
+ if os.path.exists(path):
969
+ os.remove(path)
970
+
971
+ return web.Response(status=200)
972
+ except:
973
+ return web.Response(status=400)
974
+
975
+
976
+ @routes.get("/snapshot/restore")
977
+ async def restore_snapshot(request):
978
+ if not is_allowed_security_level('middle'):
979
+ logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
980
+ return web.Response(status=403)
981
+
982
+ try:
983
+ target = request.rel_url.query["target"]
984
+
985
+ path = os.path.join(core.manager_snapshot_path, f"{target}.json")
986
+ if os.path.exists(path):
987
+ if not os.path.exists(core.manager_startup_script_path):
988
+ os.makedirs(core.manager_startup_script_path)
989
+
990
+ target_path = os.path.join(core.manager_startup_script_path, "restore-snapshot.json")
991
+ shutil.copy(path, target_path)
992
+
993
+ logging.info(f"Snapshot restore scheduled: `{target}`")
994
+ return web.Response(status=200)
995
+
996
+ logging.error(f"Snapshot file not found: `{path}`")
997
+ return web.Response(status=400)
998
+ except:
999
+ return web.Response(status=400)
1000
+
1001
+
1002
+ @routes.get("/snapshot/get_current")
1003
+ async def get_current_snapshot_api(request):
1004
+ try:
1005
+ return web.json_response(await core.get_current_snapshot(), content_type='application/json')
1006
+ except:
1007
+ return web.Response(status=400)
1008
+
1009
+
1010
+ @routes.get("/snapshot/save")
1011
+ async def save_snapshot(request):
1012
+ try:
1013
+ await core.save_snapshot_with_postfix('snapshot')
1014
+ return web.Response(status=200)
1015
+ except:
1016
+ return web.Response(status=400)
1017
+
1018
+
1019
+ def unzip_install(files):
1020
+ temp_filename = 'manager-temp.zip'
1021
+ for url in files:
1022
+ if url.endswith("/"):
1023
+ url = url[:-1]
1024
+ try:
1025
+ headers = {
1026
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
1027
+
1028
+ req = urllib.request.Request(url, headers=headers)
1029
+ response = urllib.request.urlopen(req)
1030
+ data = response.read()
1031
+
1032
+ with open(temp_filename, 'wb') as f:
1033
+ f.write(data)
1034
+
1035
+ with zipfile.ZipFile(temp_filename, 'r') as zip_ref:
1036
+ zip_ref.extractall(core.get_default_custom_nodes_path())
1037
+
1038
+ os.remove(temp_filename)
1039
+ except Exception as e:
1040
+ logging.error(f"Install(unzip) error: {url} / {e}", file=sys.stderr)
1041
+ return False
1042
+
1043
+ logging.info("Installation was successful.")
1044
+ return True
1045
+
1046
+
1047
+ def copy_install(files, js_path_name=None):
1048
+ for url in files:
1049
+ if url.endswith("/"):
1050
+ url = url[:-1]
1051
+ try:
1052
+ filename = os.path.basename(url)
1053
+ if url.endswith(".py"):
1054
+ download_url(url, core.get_default_custom_nodes_path(), filename)
1055
+ else:
1056
+ path = os.path.join(core.js_path, js_path_name) if js_path_name is not None else core.js_path
1057
+ if not os.path.exists(path):
1058
+ os.makedirs(path)
1059
+ download_url(url, path, filename)
1060
+
1061
+ except Exception as e:
1062
+ logging.error(f"Install(copy) error: {url} / {e}", file=sys.stderr)
1063
+ return False
1064
+
1065
+ logging.info("Installation was successful.")
1066
+ return True
1067
+
1068
+
1069
+ def copy_uninstall(files, js_path_name='.'):
1070
+ for url in files:
1071
+ if url.endswith("/"):
1072
+ url = url[:-1]
1073
+ dir_name = os.path.basename(url)
1074
+ base_path = core.get_default_custom_nodes_path() if url.endswith('.py') else os.path.join(core.js_path, js_path_name)
1075
+ file_path = os.path.join(base_path, dir_name)
1076
+
1077
+ try:
1078
+ if os.path.exists(file_path):
1079
+ os.remove(file_path)
1080
+ elif os.path.exists(file_path + ".disabled"):
1081
+ os.remove(file_path + ".disabled")
1082
+ except Exception as e:
1083
+ logging.error(f"Uninstall(copy) error: {url} / {e}", file=sys.stderr)
1084
+ return False
1085
+
1086
+ logging.info("Uninstallation was successful.")
1087
+ return True
1088
+
1089
+
1090
+ def copy_set_active(files, is_disable, js_path_name='.'):
1091
+ if is_disable:
1092
+ action_name = "Disable"
1093
+ else:
1094
+ action_name = "Enable"
1095
+
1096
+ for url in files:
1097
+ if url.endswith("/"):
1098
+ url = url[:-1]
1099
+ dir_name = os.path.basename(url)
1100
+ base_path = core.get_default_custom_nodes_path() if url.endswith('.py') else os.path.join(core.js_path, js_path_name)
1101
+ file_path = os.path.join(base_path, dir_name)
1102
+
1103
+ try:
1104
+ if is_disable:
1105
+ current_name = file_path
1106
+ new_name = file_path + ".disabled"
1107
+ else:
1108
+ current_name = file_path + ".disabled"
1109
+ new_name = file_path
1110
+
1111
+ os.rename(current_name, new_name)
1112
+
1113
+ except Exception as e:
1114
+ logging.error(f"{action_name}(copy) error: {url} / {e}", file=sys.stderr)
1115
+
1116
+ return False
1117
+
1118
+ logging.info(f"{action_name} was successful.")
1119
+ return True
1120
+
1121
+
1122
+ @routes.get("/customnode/versions/{node_name}")
1123
+ async def get_cnr_versions(request):
1124
+ node_name = request.match_info.get("node_name", None)
1125
+ versions = core.cnr_utils.all_versions_of_node(node_name)
1126
+
1127
+ if versions is not None:
1128
+ return web.json_response(versions, content_type='application/json')
1129
+
1130
+ return web.Response(status=400)
1131
+
1132
+
1133
+ @routes.get("/customnode/disabled_versions/{node_name}")
1134
+ async def get_disabled_versions(request):
1135
+ node_name = request.match_info.get("node_name", None)
1136
+ versions = []
1137
+ if node_name in core.unified_manager.nightly_inactive_nodes:
1138
+ versions.append(dict(version='nightly'))
1139
+
1140
+ for v in core.unified_manager.cnr_inactive_nodes.get(node_name, {}).keys():
1141
+ versions.append(dict(version=v))
1142
+
1143
+ if versions:
1144
+ return web.json_response(versions, content_type='application/json')
1145
+
1146
+ return web.Response(status=400)
1147
+
1148
+
1149
+ @routes.post("/customnode/import_fail_info")
1150
+ async def import_fail_info(request):
1151
+ json_data = await request.json()
1152
+
1153
+ if 'cnr_id' in json_data:
1154
+ module_name = core.unified_manager.get_module_name(json_data['cnr_id'])
1155
+ else:
1156
+ module_name = core.unified_manager.get_module_name(json_data['url'])
1157
+
1158
+ if module_name is not None:
1159
+ info = cm_global.error_dict.get(module_name)
1160
+ if info is not None:
1161
+ return web.json_response(info)
1162
+
1163
+ return web.Response(status=400)
1164
+
1165
+
1166
+ @routes.post("/manager/queue/reinstall")
1167
+ async def reinstall_custom_node(request):
1168
+ await uninstall_custom_node(request)
1169
+ await install_custom_node(request)
1170
+
1171
+
1172
+ @routes.get("/manager/queue/reset")
1173
+ async def reset_queue(request):
1174
+ global task_queue
1175
+ task_queue = queue.Queue()
1176
+ return web.Response(status=200)
1177
+
1178
+
1179
+ @routes.get("/manager/queue/status")
1180
+ async def queue_count(request):
1181
+ global task_queue
1182
+
1183
+ with task_worker_lock:
1184
+ done_count = len(nodepack_result) + len(model_result)
1185
+ in_progress_count = len(tasks_in_progress)
1186
+ total_count = done_count + in_progress_count + task_queue.qsize()
1187
+ is_processing = task_worker_thread is not None and task_worker_thread.is_alive()
1188
+
1189
+ return web.json_response({
1190
+ 'total_count': total_count, 'done_count': done_count, 'in_progress_count': in_progress_count,
1191
+ 'is_processing': is_processing})
1192
+
1193
+
1194
+ @routes.post("/manager/queue/install")
1195
+ async def install_custom_node(request):
1196
+ if not is_allowed_security_level('middle'):
1197
+ logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
1198
+ return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
1199
+
1200
+ json_data = await request.json()
1201
+
1202
+ # non-nightly cnr is safe
1203
+ risky_level = None
1204
+ cnr_id = json_data.get('id')
1205
+ skip_post_install = json_data.get('skip_post_install')
1206
+
1207
+ git_url = None
1208
+
1209
+ selected_version = json_data.get('selected_version')
1210
+ if json_data['version'] != 'unknown' and selected_version != 'unknown':
1211
+ if skip_post_install:
1212
+ if cnr_id in core.unified_manager.nightly_inactive_nodes or cnr_id in core.unified_manager.cnr_inactive_nodes:
1213
+ core.unified_manager.unified_enable(cnr_id)
1214
+ return web.Response(status=200)
1215
+ elif selected_version is None:
1216
+ selected_version = 'latest'
1217
+
1218
+ if selected_version != 'nightly':
1219
+ risky_level = 'low'
1220
+ node_spec_str = f"{cnr_id}@{selected_version}"
1221
+ else:
1222
+ node_spec_str = f"{cnr_id}@nightly"
1223
+ git_url = [json_data.get('repository')]
1224
+ if git_url is None:
1225
+ logging.error(f"[ComfyUI-Manager] Following node pack doesn't provide `nightly` version: ${git_url}")
1226
+ return web.Response(status=404, text=f"Following node pack doesn't provide `nightly` version: ${git_url}")
1227
+ elif json_data['version'] != 'unknown' and selected_version == 'unknown':
1228
+ logging.error(f"[ComfyUI-Manager] Invalid installation request: {json_data}")
1229
+ return web.Response(status=400, text="Invalid installation request")
1230
+ else:
1231
+ # unknown
1232
+ unknown_name = os.path.basename(json_data['files'][0])
1233
+ node_spec_str = f"{unknown_name}@unknown"
1234
+ git_url = json_data.get('files')
1235
+
1236
+ # apply security policy if not cnr node (nightly isn't regarded as cnr node)
1237
+ if risky_level is None:
1238
+ if git_url is not None:
1239
+ risky_level = await get_risky_level(git_url, json_data.get('pip', []))
1240
+ else:
1241
+ return web.Response(status=404, text=f"Following node pack doesn't provide `nightly` version: ${git_url}")
1242
+
1243
+ if not is_allowed_security_level(risky_level):
1244
+ logging.error(SECURITY_MESSAGE_GENERAL)
1245
+ return web.Response(status=404, text="A security error has occurred. Please check the terminal logs")
1246
+
1247
+ install_item = json_data.get('ui_id'), node_spec_str, json_data['channel'], json_data['mode'], skip_post_install
1248
+ task_queue.put(("install", install_item))
1249
+
1250
+ return web.Response(status=200)
1251
+
1252
+
1253
+ task_worker_thread:threading.Thread = None
1254
+
1255
+ @routes.get("/manager/queue/start")
1256
+ async def queue_start(request):
1257
+ global nodepack_result
1258
+ global model_result
1259
+ global task_worker_thread
1260
+
1261
+ if task_worker_thread is not None and task_worker_thread.is_alive():
1262
+ return web.Response(status=201) # already in-progress
1263
+
1264
+ nodepack_result = {}
1265
+ model_result = {}
1266
+
1267
+ task_worker_thread = threading.Thread(target=lambda: asyncio.run(task_worker()))
1268
+ task_worker_thread.start()
1269
+
1270
+ return web.Response(status=200)
1271
+
1272
+
1273
+ @routes.post("/manager/queue/fix")
1274
+ async def fix_custom_node(request):
1275
+ if not is_allowed_security_level('middle'):
1276
+ logging.error(SECURITY_MESSAGE_GENERAL)
1277
+ return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
1278
+
1279
+ json_data = await request.json()
1280
+
1281
+ node_id = json_data.get('id')
1282
+ node_ver = json_data['version']
1283
+ if node_ver != 'unknown':
1284
+ node_name = node_id
1285
+ else:
1286
+ # unknown
1287
+ node_name = os.path.basename(json_data['files'][0])
1288
+
1289
+ update_item = json_data.get('ui_id'), node_name, json_data['version']
1290
+ task_queue.put(("fix", update_item))
1291
+
1292
+ return web.Response(status=200)
1293
+
1294
+
1295
+ @routes.post("/customnode/install/git_url")
1296
+ async def install_custom_node_git_url(request):
1297
+ if not is_allowed_security_level('high'):
1298
+ logging.error(SECURITY_MESSAGE_NORMAL_MINUS)
1299
+ return web.Response(status=403)
1300
+
1301
+ url = await request.text()
1302
+ res = await core.gitclone_install(url)
1303
+
1304
+ if res.action == 'skip':
1305
+ logging.info(f"\nAlready installed: '{res.target}'")
1306
+ return web.Response(status=200)
1307
+ elif res.result:
1308
+ logging.info("\nAfter restarting ComfyUI, please refresh the browser.")
1309
+ return web.Response(status=200)
1310
+
1311
+ logging.error(res.msg)
1312
+ return web.Response(status=400)
1313
+
1314
+
1315
+ @routes.post("/customnode/install/pip")
1316
+ async def install_custom_node_pip(request):
1317
+ if not is_allowed_security_level('high'):
1318
+ logging.error(SECURITY_MESSAGE_NORMAL_MINUS)
1319
+ return web.Response(status=403)
1320
+
1321
+ packages = await request.text()
1322
+ core.pip_install(packages.split(' '))
1323
+
1324
+ return web.Response(status=200)
1325
+
1326
+
1327
+ @routes.post("/manager/queue/uninstall")
1328
+ async def uninstall_custom_node(request):
1329
+ if not is_allowed_security_level('middle'):
1330
+ logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
1331
+ return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
1332
+
1333
+ json_data = await request.json()
1334
+
1335
+ node_id = json_data.get('id')
1336
+ if json_data['version'] != 'unknown':
1337
+ is_unknown = False
1338
+ node_name = node_id
1339
+ else:
1340
+ # unknown
1341
+ is_unknown = True
1342
+ node_name = os.path.basename(json_data['files'][0])
1343
+
1344
+ uninstall_item = json_data.get('ui_id'), node_name, is_unknown
1345
+ task_queue.put(("uninstall", uninstall_item))
1346
+
1347
+ return web.Response(status=200)
1348
+
1349
+
1350
+ @routes.post("/manager/queue/update")
1351
+ async def update_custom_node(request):
1352
+ if not is_allowed_security_level('middle'):
1353
+ logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
1354
+ return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
1355
+
1356
+ json_data = await request.json()
1357
+
1358
+ node_id = json_data.get('id')
1359
+ if json_data['version'] != 'unknown':
1360
+ node_name = node_id
1361
+ else:
1362
+ # unknown
1363
+ node_name = os.path.basename(json_data['files'][0])
1364
+
1365
+ update_item = json_data.get('ui_id'), node_name, json_data['version']
1366
+ task_queue.put(("update", update_item))
1367
+
1368
+ return web.Response(status=200)
1369
+
1370
+
1371
+ @routes.get("/manager/queue/update_comfyui")
1372
+ async def update_comfyui(request):
1373
+ is_stable = core.get_config()['update_policy'] != 'nightly-comfyui'
1374
+ task_queue.put(("update-comfyui", ('comfyui', is_stable)))
1375
+ return web.Response(status=200)
1376
+
1377
+
1378
+ @routes.get("/comfyui_manager/comfyui_versions")
1379
+ async def comfyui_versions(request):
1380
+ try:
1381
+ res, current, latest = core.get_comfyui_versions()
1382
+ return web.json_response({'versions': res, 'current': current}, status=200, content_type='application/json')
1383
+ except Exception as e:
1384
+ logging.error(f"ComfyUI update fail: {e}", file=sys.stderr)
1385
+
1386
+ return web.Response(status=400)
1387
+
1388
+
1389
+ @routes.get("/comfyui_manager/comfyui_switch_version")
1390
+ async def comfyui_switch_version(request):
1391
+ try:
1392
+ if "ver" in request.rel_url.query:
1393
+ core.switch_comfyui(request.rel_url.query['ver'])
1394
+
1395
+ return web.Response(status=200)
1396
+ except Exception as e:
1397
+ logging.error(f"ComfyUI update fail: {e}", file=sys.stderr)
1398
+
1399
+ return web.Response(status=400)
1400
+
1401
+
1402
+ @routes.post("/manager/queue/disable")
1403
+ async def disable_node(request):
1404
+ json_data = await request.json()
1405
+
1406
+ node_id = json_data.get('id')
1407
+ if json_data['version'] != 'unknown':
1408
+ is_unknown = False
1409
+ node_name = node_id
1410
+ else:
1411
+ # unknown
1412
+ is_unknown = True
1413
+ node_name = os.path.basename(json_data['files'][0])
1414
+
1415
+ update_item = json_data.get('ui_id'), node_name, is_unknown
1416
+ task_queue.put(("disable", update_item))
1417
+
1418
+ return web.Response(status=200)
1419
+
1420
+
1421
+ async def check_whitelist_for_model(item):
1422
+ json_obj = await core.get_data_by_mode('cache', 'model-list.json')
1423
+
1424
+ for x in json_obj.get('models', []):
1425
+ if x['save_path'] == item['save_path'] and x['base'] == item['base'] and x['filename'] == item['filename']:
1426
+ return True
1427
+
1428
+ json_obj = await core.get_data_by_mode('local', 'model-list.json')
1429
+
1430
+ for x in json_obj.get('models', []):
1431
+ if x['save_path'] == item['save_path'] and x['base'] == item['base'] and x['filename'] == item['filename']:
1432
+ return True
1433
+
1434
+ return False
1435
+
1436
+
1437
+ @routes.post("/manager/queue/install_model")
1438
+ async def install_model(request):
1439
+ json_data = await request.json()
1440
+
1441
+ if not is_allowed_security_level('middle'):
1442
+ logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
1443
+ return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
1444
+
1445
+ # validate request
1446
+ if not await check_whitelist_for_model(json_data):
1447
+ logging.error(f"[ComfyUI-Manager] Invalid model install request is detected: {json_data}")
1448
+ return web.Response(status=400, text="Invalid model install request is detected")
1449
+
1450
+ if not json_data['filename'].endswith('.safetensors') and not is_allowed_security_level('high'):
1451
+ models_json = await core.get_data_by_mode('cache', 'model-list.json', 'default')
1452
+
1453
+ is_belongs_to_whitelist = False
1454
+ for x in models_json['models']:
1455
+ if x.get('url') == json_data['url']:
1456
+ is_belongs_to_whitelist = True
1457
+ break
1458
+
1459
+ if not is_belongs_to_whitelist:
1460
+ logging.error(SECURITY_MESSAGE_NORMAL_MINUS_MODEL)
1461
+ return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
1462
+
1463
+ install_item = json_data.get('ui_id'), json_data
1464
+ task_queue.put(("install-model", install_item))
1465
+
1466
+ return web.Response(status=200)
1467
+
1468
+
1469
+ @routes.get("/manager/preview_method")
1470
+ async def preview_method(request):
1471
+ if "value" in request.rel_url.query:
1472
+ set_preview_method(request.rel_url.query['value'])
1473
+ core.write_config()
1474
+ else:
1475
+ return web.Response(text=core.manager_funcs.get_current_preview_method(), status=200)
1476
+
1477
+ return web.Response(status=200)
1478
+
1479
+
1480
+ @routes.get("/manager/db_mode")
1481
+ async def db_mode(request):
1482
+ if "value" in request.rel_url.query:
1483
+ set_db_mode(request.rel_url.query['value'])
1484
+ core.write_config()
1485
+ else:
1486
+ return web.Response(text=core.get_config()['db_mode'], status=200)
1487
+
1488
+ return web.Response(status=200)
1489
+
1490
+
1491
+
1492
+ @routes.get("/manager/policy/component")
1493
+ async def component_policy(request):
1494
+ if "value" in request.rel_url.query:
1495
+ set_component_policy(request.rel_url.query['value'])
1496
+ core.write_config()
1497
+ else:
1498
+ return web.Response(text=core.get_config()['component_policy'], status=200)
1499
+
1500
+ return web.Response(status=200)
1501
+
1502
+
1503
+ @routes.get("/manager/policy/update")
1504
+ async def update_policy(request):
1505
+ if "value" in request.rel_url.query:
1506
+ set_update_policy(request.rel_url.query['value'])
1507
+ core.write_config()
1508
+ else:
1509
+ return web.Response(text=core.get_config()['update_policy'], status=200)
1510
+
1511
+ return web.Response(status=200)
1512
+
1513
+
1514
+ @routes.get("/manager/channel_url_list")
1515
+ async def channel_url_list(request):
1516
+ channels = core.get_channel_dict()
1517
+ if "value" in request.rel_url.query:
1518
+ channel_url = channels.get(request.rel_url.query['value'])
1519
+ if channel_url is not None:
1520
+ core.get_config()['channel_url'] = channel_url
1521
+ core.write_config()
1522
+ else:
1523
+ selected = 'custom'
1524
+ selected_url = core.get_config()['channel_url']
1525
+
1526
+ for name, url in channels.items():
1527
+ if url == selected_url:
1528
+ selected = name
1529
+ break
1530
+
1531
+ res = {'selected': selected,
1532
+ 'list': core.get_channel_list()}
1533
+ return web.json_response(res, status=200)
1534
+
1535
+ return web.Response(status=200)
1536
+
1537
+
1538
+ def add_target_blank(html_text):
1539
+ pattern = r'(<a\s+href="[^"]*"\s*[^>]*)(>)'
1540
+
1541
+ def add_target(match):
1542
+ if 'target=' not in match.group(1):
1543
+ return match.group(1) + ' target="_blank"' + match.group(2)
1544
+ return match.group(0)
1545
+
1546
+ modified_html = re.sub(pattern, add_target, html_text)
1547
+
1548
+ return modified_html
1549
+
1550
+
1551
+ @routes.get("/manager/notice")
1552
+ async def get_notice(request):
1553
+ url = "github.com"
1554
+ path = "/ltdrdata/ltdrdata.github.io/wiki/News"
1555
+
1556
+ async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
1557
+ async with session.get(f"https://{url}{path}") as response:
1558
+ if response.status == 200:
1559
+ # html_content = response.read().decode('utf-8')
1560
+ html_content = await response.text()
1561
+
1562
+ pattern = re.compile(r'<div class="markdown-body">([\s\S]*?)</div>')
1563
+ match = pattern.search(html_content)
1564
+
1565
+ if match:
1566
+ markdown_content = match.group(1)
1567
+ version_tag = os.environ.get('__COMFYUI_DESKTOP_VERSION__')
1568
+ if version_tag is not None:
1569
+ markdown_content += f"<HR>ComfyUI: {version_tag} [Desktop]"
1570
+ else:
1571
+ version_tag = core.get_comfyui_tag()
1572
+ if version_tag is None:
1573
+ markdown_content += f"<HR>ComfyUI: {core.comfy_ui_revision}[{comfy_ui_hash[:6]}]({core.comfy_ui_commit_datetime.date()})"
1574
+ else:
1575
+ markdown_content += (f"<HR>ComfyUI: {version_tag}<BR>"
1576
+ f"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;({core.comfy_ui_commit_datetime.date()})")
1577
+ # markdown_content += f"<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;()"
1578
+ markdown_content += f"<BR>Manager: {core.version_str}"
1579
+
1580
+ markdown_content = add_target_blank(markdown_content)
1581
+
1582
+ try:
1583
+ if '__COMFYUI_DESKTOP_VERSION__' not in os.environ:
1584
+ if core.comfy_ui_commit_datetime == datetime(1900, 1, 1, 0, 0, 0):
1585
+ markdown_content = '<P style="text-align: center; color:red; background-color:white; font-weight:bold">Your ComfyUI isn\'t git repo.</P>' + markdown_content
1586
+ elif core.comfy_ui_required_commit_datetime.date() > core.comfy_ui_commit_datetime.date():
1587
+ markdown_content = '<P style="text-align: center; color:red; background-color:white; font-weight:bold">Your ComfyUI is too OUTDATED!!!</P>' + markdown_content
1588
+ except:
1589
+ pass
1590
+
1591
+ return web.Response(text=markdown_content, status=200)
1592
+ else:
1593
+ return web.Response(text="Unable to retrieve Notice", status=200)
1594
+ else:
1595
+ return web.Response(text="Unable to retrieve Notice", status=200)
1596
+
1597
+
1598
+ @routes.get("/manager/reboot")
1599
+ def restart(self):
1600
+ if not is_allowed_security_level('middle'):
1601
+ logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
1602
+ return web.Response(status=403)
1603
+
1604
+ try:
1605
+ sys.stdout.close_log()
1606
+ except Exception:
1607
+ pass
1608
+
1609
+ if '__COMFY_CLI_SESSION__' in os.environ:
1610
+ with open(os.path.join(os.environ['__COMFY_CLI_SESSION__'] + '.reboot'), 'w'):
1611
+ pass
1612
+
1613
+ print("\nRestarting...\n\n") # This printing should not be logging - that will be ugly
1614
+ exit(0)
1615
+
1616
+ print("\nRestarting... [Legacy Mode]\n\n") # This printing should not be logging - that will be ugly
1617
+
1618
+ sys_argv = sys.argv.copy()
1619
+ if '--windows-standalone-build' in sys_argv:
1620
+ sys_argv.remove('--windows-standalone-build')
1621
+
1622
+ if sys_argv[0].endswith("__main__.py"): # this is a python module
1623
+ module_name = os.path.basename(os.path.dirname(sys_argv[0]))
1624
+ cmds = [sys.executable, '-m', module_name] + sys_argv[1:]
1625
+ elif sys.platform.startswith('win32'):
1626
+ cmds = ['"' + sys.executable + '"', '"' + sys_argv[0] + '"'] + sys_argv[1:]
1627
+ else:
1628
+ cmds = [sys.executable] + sys_argv
1629
+
1630
+ print(f"Command: {cmds}", flush=True)
1631
+
1632
+ return os.execv(sys.executable, cmds)
1633
+
1634
+
1635
+ @routes.post("/manager/component/save")
1636
+ async def save_component(request):
1637
+ try:
1638
+ data = await request.json()
1639
+ name = data['name']
1640
+ workflow = data['workflow']
1641
+
1642
+ if not os.path.exists(core.manager_components_path):
1643
+ os.mkdir(core.manager_components_path)
1644
+
1645
+ if 'packname' in workflow and workflow['packname'] != '':
1646
+ sanitized_name = manager_util.sanitize_filename(workflow['packname']) + '.pack'
1647
+ else:
1648
+ sanitized_name = manager_util.sanitize_filename(name) + '.json'
1649
+
1650
+ filepath = os.path.join(core.manager_components_path, sanitized_name)
1651
+ components = {}
1652
+ if os.path.exists(filepath):
1653
+ with open(filepath) as f:
1654
+ components = json.load(f)
1655
+
1656
+ components[name] = workflow
1657
+
1658
+ with open(filepath, 'w') as f:
1659
+ json.dump(components, f, indent=4, sort_keys=True)
1660
+ return web.Response(text=filepath, status=200)
1661
+ except:
1662
+ return web.Response(status=400)
1663
+
1664
+
1665
+ @routes.post("/manager/component/loads")
1666
+ async def load_components(request):
1667
+ if os.path.exists(core.manager_components_path):
1668
+ try:
1669
+ json_files = [f for f in os.listdir(core.manager_components_path) if f.endswith('.json')]
1670
+ pack_files = [f for f in os.listdir(core.manager_components_path) if f.endswith('.pack')]
1671
+
1672
+ components = {}
1673
+ for json_file in json_files + pack_files:
1674
+ file_path = os.path.join(core.manager_components_path, json_file)
1675
+ with open(file_path, 'r') as file:
1676
+ try:
1677
+ # When there is a conflict between the .pack and the .json, the pack takes precedence and overrides.
1678
+ components.update(json.load(file))
1679
+ except json.JSONDecodeError as e:
1680
+ logging.error(f"[ComfyUI-Manager] Error decoding component file in file {json_file}: {e}")
1681
+
1682
+ return web.json_response(components)
1683
+ except Exception as e:
1684
+ logging.error(f"[ComfyUI-Manager] failed to load components\n{e}")
1685
+ return web.Response(status=400)
1686
+ else:
1687
+ return web.json_response({})
1688
+
1689
+
1690
+ @routes.get("/manager/version")
1691
+ async def get_version(request):
1692
+ return web.Response(text=core.version_str, status=200)
1693
+
1694
+
1695
+ async def _confirm_try_install(sender, custom_node_url, msg):
1696
+ json_obj = await core.get_data_by_mode('default', 'custom-node-list.json')
1697
+
1698
+ sender = manager_util.sanitize_tag(sender)
1699
+ msg = manager_util.sanitize_tag(msg)
1700
+ target = core.lookup_customnode_by_url(json_obj, custom_node_url)
1701
+
1702
+ if target is not None:
1703
+ PromptServer.instance.send_sync("cm-api-try-install-customnode",
1704
+ {"sender": sender, "target": target, "msg": msg})
1705
+ else:
1706
+ logging.error(f"[ComfyUI Manager API] Failed to try install - Unknown custom node url '{custom_node_url}'")
1707
+
1708
+
1709
+ def confirm_try_install(sender, custom_node_url, msg):
1710
+ asyncio.run(_confirm_try_install(sender, custom_node_url, msg))
1711
+
1712
+
1713
+ cm_global.register_api('cm.try-install-custom-node', confirm_try_install)
1714
+
1715
+
1716
+ async def default_cache_update():
1717
+ core.refresh_channel_dict()
1718
+ channel_url = core.get_config()['channel_url']
1719
+ async def get_cache(filename):
1720
+ try:
1721
+ if core.get_config()['default_cache_as_channel_url']:
1722
+ uri = f"{channel_url}/{filename}"
1723
+ else:
1724
+ uri = f"{core.DEFAULT_CHANNEL}/{filename}"
1725
+
1726
+ cache_uri = str(manager_util.simple_hash(uri)) + '_' + filename
1727
+ cache_uri = os.path.join(manager_util.cache_dir, cache_uri)
1728
+
1729
+ json_obj = await manager_util.get_data(uri, True)
1730
+
1731
+ with manager_util.cache_lock:
1732
+ with open(cache_uri, "w", encoding='utf-8') as file:
1733
+ json.dump(json_obj, file, indent=4, sort_keys=True)
1734
+ logging.info(f"[ComfyUI-Manager] default cache updated: {uri}")
1735
+ except Exception as e:
1736
+ logging.error(f"[ComfyUI-Manager] Failed to perform initial fetching '{filename}': {e}")
1737
+ traceback.print_exc()
1738
+
1739
+ if core.get_config()['network_mode'] != 'offline':
1740
+ a = get_cache("custom-node-list.json")
1741
+ b = get_cache("extension-node-map.json")
1742
+ c = get_cache("model-list.json")
1743
+ d = get_cache("alter-list.json")
1744
+ e = get_cache("github-stats.json")
1745
+
1746
+ await asyncio.gather(a, b, c, d, e)
1747
+
1748
+ if core.get_config()['network_mode'] == 'private':
1749
+ logging.info("[ComfyUI-Manager] The private comfyregistry is not yet supported in `network_mode=private`.")
1750
+ else:
1751
+ # load at least once
1752
+ await core.unified_manager.reload('remote', dont_wait=False)
1753
+ await core.unified_manager.get_custom_nodes(channel_url, 'remote')
1754
+
1755
+ logging.info("[ComfyUI-Manager] All startup tasks have been completed.")
1756
+
1757
+
1758
+ threading.Thread(target=lambda: asyncio.run(default_cache_update())).start()
1759
+
1760
+ if not os.path.exists(core.manager_config_path):
1761
+ core.get_config()
1762
+ core.write_config()
1763
+
1764
+
1765
+ cm_global.register_extension('ComfyUI-Manager',
1766
+ {'version': core.version,
1767
+ 'name': 'ComfyUI Manager',
1768
+ 'nodes': {},
1769
+ 'description': 'This extension provides the ability to manage custom nodes in ComfyUI.', })
1770
+
1771
+
ComfyUI/custom_nodes/ComfyUI-Manager/glob/manager_util.py ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ description:
3
+ `manager_util` is the lightest module shared across the prestartup_script, main code, and cm-cli of ComfyUI-Manager.
4
+ """
5
+ import traceback
6
+
7
+ import aiohttp
8
+ import json
9
+ import threading
10
+ import os
11
+ from datetime import datetime
12
+ import subprocess
13
+ import sys
14
+ import re
15
+ import logging
16
+ import platform
17
+ import shlex
18
+
19
+
20
+ cache_lock = threading.Lock()
21
+
22
+ comfyui_manager_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
23
+ cache_dir = os.path.join(comfyui_manager_path, '.cache') # This path is also updated together in **manager_core.update_user_directory**.
24
+
25
+ use_uv = False
26
+
27
+
28
+ def add_python_path_to_env():
29
+ if platform.system() != "Windows":
30
+ sep = ':'
31
+ else:
32
+ sep = ';'
33
+
34
+ os.environ['PATH'] = os.path.dirname(sys.executable)+sep+os.environ['PATH']
35
+
36
+
37
+ def make_pip_cmd(cmd):
38
+ if 'python_embeded' in sys.executable:
39
+ if use_uv:
40
+ return [sys.executable, '-s', '-m', 'uv', 'pip'] + cmd
41
+ else:
42
+ return [sys.executable, '-s', '-m', 'pip'] + cmd
43
+ else:
44
+ # FIXED: https://github.com/ltdrdata/ComfyUI-Manager/issues/1667
45
+ if use_uv:
46
+ return [sys.executable, '-m', 'uv', 'pip'] + cmd
47
+ else:
48
+ return [sys.executable, '-m', 'pip'] + cmd
49
+
50
+ # DON'T USE StrictVersion - cannot handle pre_release version
51
+ # try:
52
+ # from distutils.version import StrictVersion
53
+ # except:
54
+ # print(f"[ComfyUI-Manager] 'distutils' package not found. Activating fallback mode for compatibility.")
55
+ class StrictVersion:
56
+ def __init__(self, version_string):
57
+ self.version_string = version_string
58
+ self.major = 0
59
+ self.minor = 0
60
+ self.patch = 0
61
+ self.pre_release = None
62
+ self.parse_version_string()
63
+
64
+ def parse_version_string(self):
65
+ parts = self.version_string.split('.')
66
+ if not parts:
67
+ raise ValueError("Version string must not be empty")
68
+
69
+ self.major = int(parts[0])
70
+ self.minor = int(parts[1]) if len(parts) > 1 else 0
71
+ self.patch = int(parts[2]) if len(parts) > 2 else 0
72
+
73
+ # Handling pre-release versions if present
74
+ if len(parts) > 3:
75
+ self.pre_release = parts[3]
76
+
77
+ def __str__(self):
78
+ version = f"{self.major}.{self.minor}.{self.patch}"
79
+ if self.pre_release:
80
+ version += f"-{self.pre_release}"
81
+ return version
82
+
83
+ def __eq__(self, other):
84
+ return (self.major, self.minor, self.patch, self.pre_release) == \
85
+ (other.major, other.minor, other.patch, other.pre_release)
86
+
87
+ def __lt__(self, other):
88
+ if (self.major, self.minor, self.patch) == (other.major, other.minor, other.patch):
89
+ return self.pre_release_compare(self.pre_release, other.pre_release) < 0
90
+ return (self.major, self.minor, self.patch) < (other.major, other.minor, other.patch)
91
+
92
+ @staticmethod
93
+ def pre_release_compare(pre1, pre2):
94
+ if pre1 == pre2:
95
+ return 0
96
+ if pre1 is None:
97
+ return 1
98
+ if pre2 is None:
99
+ return -1
100
+ return -1 if pre1 < pre2 else 1
101
+
102
+ def __le__(self, other):
103
+ return self == other or self < other
104
+
105
+ def __gt__(self, other):
106
+ return not self <= other
107
+
108
+ def __ge__(self, other):
109
+ return not self < other
110
+
111
+ def __ne__(self, other):
112
+ return not self == other
113
+
114
+
115
+ def simple_hash(input_string):
116
+ hash_value = 0
117
+ for char in input_string:
118
+ hash_value = (hash_value * 31 + ord(char)) % (2**32)
119
+
120
+ return hash_value
121
+
122
+
123
+ def is_file_created_within_one_day(file_path):
124
+ if not os.path.exists(file_path):
125
+ return False
126
+
127
+ file_creation_time = os.path.getctime(file_path)
128
+ current_time = datetime.now().timestamp()
129
+ time_difference = current_time - file_creation_time
130
+
131
+ return time_difference <= 86400
132
+
133
+
134
+ async def get_data(uri, silent=False):
135
+ if not silent:
136
+ print(f"FETCH DATA from: {uri}", end="")
137
+
138
+ if uri.startswith("http"):
139
+ async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
140
+ headers = {
141
+ 'Cache-Control': 'no-cache',
142
+ 'Pragma': 'no-cache',
143
+ 'Expires': '0'
144
+ }
145
+ async with session.get(uri, headers=headers) as resp:
146
+ json_text = await resp.text()
147
+ else:
148
+ with cache_lock:
149
+ with open(uri, "r", encoding="utf-8") as f:
150
+ json_text = f.read()
151
+
152
+ try:
153
+ json_obj = json.loads(json_text)
154
+ except Exception as e:
155
+ logging.error(f"[ComfyUI-Manager] An error occurred while fetching '{uri}': {e}")
156
+
157
+ return {}
158
+
159
+ if not silent:
160
+ print(" [DONE]")
161
+
162
+ return json_obj
163
+
164
+
165
+ def get_cache_path(uri):
166
+ cache_uri = str(simple_hash(uri)) + '_' + os.path.basename(uri).replace('&', "_").replace('?', "_").replace('=', "_")
167
+ return os.path.join(cache_dir, cache_uri+'.json')
168
+
169
+
170
+ def get_cache_state(uri):
171
+ cache_uri = get_cache_path(uri)
172
+
173
+ if not os.path.exists(cache_uri):
174
+ return "not-cached"
175
+ elif is_file_created_within_one_day(cache_uri):
176
+ return "cached"
177
+
178
+ return "expired"
179
+
180
+
181
+ def save_to_cache(uri, json_obj, silent=False):
182
+ cache_uri = get_cache_path(uri)
183
+
184
+ with cache_lock:
185
+ with open(cache_uri, "w", encoding='utf-8') as file:
186
+ json.dump(json_obj, file, indent=4, sort_keys=True)
187
+ if not silent:
188
+ logging.info(f"[ComfyUI-Manager] default cache updated: {uri}")
189
+
190
+
191
+ async def get_data_with_cache(uri, silent=False, cache_mode=True, dont_wait=False, dont_cache=False):
192
+ cache_uri = get_cache_path(uri)
193
+
194
+ if cache_mode and dont_wait:
195
+ # NOTE: return the cache if possible, even if it is expired, so do not cache
196
+ if not os.path.exists(cache_uri):
197
+ logging.error(f"[ComfyUI-Manager] The network connection is unstable, so it is operating in fallback mode: {uri}")
198
+
199
+ return {}
200
+ else:
201
+ if not is_file_created_within_one_day(cache_uri):
202
+ logging.error(f"[ComfyUI-Manager] The network connection is unstable, so it is operating in outdated cache mode: {uri}")
203
+
204
+ return await get_data(cache_uri, silent=silent)
205
+
206
+ if cache_mode and is_file_created_within_one_day(cache_uri):
207
+ json_obj = await get_data(cache_uri, silent=silent)
208
+ else:
209
+ json_obj = await get_data(uri, silent=silent)
210
+ if not dont_cache:
211
+ with cache_lock:
212
+ with open(cache_uri, "w", encoding='utf-8') as file:
213
+ json.dump(json_obj, file, indent=4, sort_keys=True)
214
+ if not silent:
215
+ logging.info(f"[ComfyUI-Manager] default cache updated: {uri}")
216
+
217
+ return json_obj
218
+
219
+
220
+ def sanitize_tag(x):
221
+ return x.replace('<', '&lt;').replace('>', '&gt;')
222
+
223
+
224
+ def extract_package_as_zip(file_path, extract_path):
225
+ import zipfile
226
+ try:
227
+ with zipfile.ZipFile(file_path, "r") as zip_ref:
228
+ zip_ref.extractall(extract_path)
229
+ extracted_files = zip_ref.namelist()
230
+ logging.info(f"Extracted zip file to {extract_path}")
231
+ return extracted_files
232
+ except zipfile.BadZipFile:
233
+ logging.error(f"File '{file_path}' is not a zip or is corrupted.")
234
+ return None
235
+
236
+
237
+ pip_map = None
238
+
239
+
240
+ def get_installed_packages(renew=False):
241
+ global pip_map
242
+
243
+ if renew or pip_map is None:
244
+ try:
245
+ result = subprocess.check_output(make_pip_cmd(['list']), universal_newlines=True)
246
+
247
+ pip_map = {}
248
+ for line in result.split('\n'):
249
+ x = line.strip()
250
+ if x:
251
+ y = line.split()
252
+ if y[0] == 'Package' or y[0].startswith('-'):
253
+ continue
254
+
255
+ normalized_name = y[0].lower().replace('-', '_')
256
+ pip_map[normalized_name] = y[1]
257
+ except subprocess.CalledProcessError:
258
+ logging.error("[ComfyUI-Manager] Failed to retrieve the information of installed pip packages.")
259
+ return set()
260
+
261
+ return pip_map
262
+
263
+
264
+ def clear_pip_cache():
265
+ global pip_map
266
+ pip_map = None
267
+
268
+
269
+ def parse_requirement_line(line):
270
+ tokens = shlex.split(line)
271
+ if not tokens:
272
+ return None
273
+
274
+ package_spec = tokens[0]
275
+
276
+ pattern = re.compile(
277
+ r'^(?P<package>[A-Za-z0-9_.+-]+)'
278
+ r'(?P<operator>==|>=|<=|!=|~=|>|<)?'
279
+ r'(?P<version>[A-Za-z0-9_.+-]*)$'
280
+ )
281
+ m = pattern.match(package_spec)
282
+ if not m:
283
+ return None
284
+
285
+ package = m.group('package')
286
+ operator = m.group('operator') or None
287
+ version = m.group('version') or None
288
+
289
+ index_url = None
290
+ if '--index-url' in tokens:
291
+ idx = tokens.index('--index-url')
292
+ if idx + 1 < len(tokens):
293
+ index_url = tokens[idx + 1]
294
+
295
+ res = {'package': package}
296
+
297
+ if operator is not None:
298
+ res['operator'] = operator
299
+
300
+ if version is not None:
301
+ res['version'] = StrictVersion(version)
302
+
303
+ if index_url is not None:
304
+ res['index_url'] = index_url
305
+
306
+ return res
307
+
308
+
309
+ torch_torchvision_torchaudio_version_map = {
310
+ '2.6.0': ('0.21.0', '2.6.0'),
311
+ '2.5.1': ('0.20.0', '2.5.0'),
312
+ '2.5.0': ('0.20.0', '2.5.0'),
313
+ '2.4.1': ('0.19.1', '2.4.1'),
314
+ '2.4.0': ('0.19.0', '2.4.0'),
315
+ '2.3.1': ('0.18.1', '2.3.1'),
316
+ '2.3.0': ('0.18.0', '2.3.0'),
317
+ '2.2.2': ('0.17.2', '2.2.2'),
318
+ '2.2.1': ('0.17.1', '2.2.1'),
319
+ '2.2.0': ('0.17.0', '2.2.0'),
320
+ '2.1.2': ('0.16.2', '2.1.2'),
321
+ '2.1.1': ('0.16.1', '2.1.1'),
322
+ '2.1.0': ('0.16.0', '2.1.0'),
323
+ '2.0.1': ('0.15.2', '2.0.1'),
324
+ '2.0.0': ('0.15.1', '2.0.0'),
325
+ }
326
+
327
+
328
+
329
+ class PIPFixer:
330
+ def __init__(self, prev_pip_versions, comfyui_path, manager_files_path):
331
+ self.prev_pip_versions = { **prev_pip_versions }
332
+ self.comfyui_path = comfyui_path
333
+ self.manager_files_path = manager_files_path
334
+
335
+ def torch_rollback(self):
336
+ spec = self.prev_pip_versions['torch'].split('+')
337
+ if len(spec) > 0:
338
+ platform = spec[1]
339
+ else:
340
+ cmd = make_pip_cmd(['install', '--force', 'torch', 'torchvision', 'torchaudio'])
341
+ subprocess.check_output(cmd, universal_newlines=True)
342
+ logging.error(cmd)
343
+ return
344
+
345
+ torch_ver = StrictVersion(spec[0])
346
+ torch_ver = f"{torch_ver.major}.{torch_ver.minor}.{torch_ver.patch}"
347
+ torch_torchvision_torchaudio_ver = torch_torchvision_torchaudio_version_map.get(torch_ver)
348
+
349
+ if torch_torchvision_torchaudio_ver is None:
350
+ cmd = make_pip_cmd(['install', '--pre', 'torch', 'torchvision', 'torchaudio',
351
+ '--index-url', f"https://download.pytorch.org/whl/nightly/{platform}"])
352
+ logging.info("[ComfyUI-Manager] restore PyTorch to nightly version")
353
+ else:
354
+ torchvision_ver, torchaudio_ver = torch_torchvision_torchaudio_ver
355
+ cmd = make_pip_cmd(['install', f'torch=={torch_ver}', f'torchvision=={torchvision_ver}', f"torchaudio=={torchaudio_ver}",
356
+ '--index-url', f"https://download.pytorch.org/whl/{platform}"])
357
+ logging.info(f"[ComfyUI-Manager] restore PyTorch to {torch_ver}+{platform}")
358
+
359
+ subprocess.check_output(cmd, universal_newlines=True)
360
+
361
+ def fix_broken(self):
362
+ new_pip_versions = get_installed_packages(True)
363
+
364
+ # remove `comfy` python package
365
+ try:
366
+ if 'comfy' in new_pip_versions:
367
+ cmd = make_pip_cmd(['uninstall', 'comfy'])
368
+ subprocess.check_output(cmd, universal_newlines=True)
369
+
370
+ logging.warning("[ComfyUI-Manager] 'comfy' python package is uninstalled.\nWARN: The 'comfy' package is completely unrelated to ComfyUI and should never be installed as it causes conflicts with ComfyUI.")
371
+ except Exception as e:
372
+ logging.error("[ComfyUI-Manager] Failed to uninstall `comfy` python package")
373
+ logging.error(e)
374
+
375
+ # fix torch - reinstall torch packages if version is changed
376
+ try:
377
+ if 'torch' not in self.prev_pip_versions or 'torchvision' not in self.prev_pip_versions or 'torchaudio' not in self.prev_pip_versions:
378
+ logging.error("[ComfyUI-Manager] PyTorch is not installed")
379
+ elif self.prev_pip_versions['torch'] != new_pip_versions['torch'] \
380
+ or self.prev_pip_versions['torchvision'] != new_pip_versions['torchvision'] \
381
+ or self.prev_pip_versions['torchaudio'] != new_pip_versions['torchaudio']:
382
+ self.torch_rollback()
383
+ except Exception as e:
384
+ logging.error("[ComfyUI-Manager] Failed to restore PyTorch")
385
+ logging.error(e)
386
+
387
+ # fix opencv
388
+ try:
389
+ ocp = new_pip_versions.get('opencv-contrib-python')
390
+ ocph = new_pip_versions.get('opencv-contrib-python-headless')
391
+ op = new_pip_versions.get('opencv-python')
392
+ oph = new_pip_versions.get('opencv-python-headless')
393
+
394
+ versions = [ocp, ocph, op, oph]
395
+ versions = [StrictVersion(x) for x in versions if x is not None]
396
+ versions.sort(reverse=True)
397
+
398
+ if len(versions) > 0:
399
+ # upgrade to maximum version
400
+ targets = []
401
+ cur = versions[0]
402
+ if ocp is not None and StrictVersion(ocp) != cur:
403
+ targets.append('opencv-contrib-python')
404
+ if ocph is not None and StrictVersion(ocph) != cur:
405
+ targets.append('opencv-contrib-python-headless')
406
+ if op is not None and StrictVersion(op) != cur:
407
+ targets.append('opencv-python')
408
+ if oph is not None and StrictVersion(oph) != cur:
409
+ targets.append('opencv-python-headless')
410
+
411
+ if len(targets) > 0:
412
+ for x in targets:
413
+ cmd = make_pip_cmd(['install', f"{x}=={versions[0].version_string}", "numpy<2"])
414
+ subprocess.check_output(cmd, universal_newlines=True)
415
+
416
+ logging.info(f"[ComfyUI-Manager] 'opencv' dependencies were fixed: {targets}")
417
+ except Exception as e:
418
+ logging.error("[ComfyUI-Manager] Failed to restore opencv")
419
+ logging.error(e)
420
+
421
+ # fix numpy
422
+ try:
423
+ np = new_pip_versions.get('numpy')
424
+ if np is not None:
425
+ if StrictVersion(np) >= StrictVersion('2'):
426
+ cmd = make_pip_cmd(['install', "numpy<2"])
427
+ subprocess.check_output(cmd , universal_newlines=True)
428
+
429
+ logging.info("[ComfyUI-Manager] 'numpy' dependency were fixed")
430
+ except Exception as e:
431
+ logging.error("[ComfyUI-Manager] Failed to restore numpy")
432
+ logging.error(e)
433
+
434
+ # fix missing frontend
435
+ try:
436
+ # NOTE: package name in requirements is 'comfyui-frontend-package'
437
+ # but, package name from `pip freeze` is 'comfyui_frontend_package'
438
+ # but, package name from `uv pip freeze` is 'comfyui-frontend-package'
439
+ #
440
+ # get_installed_packages returns normalized name (i.e. comfyui_frontend_package)
441
+ if 'comfyui_frontend_package' not in new_pip_versions:
442
+ requirements_path = os.path.join(self.comfyui_path, 'requirements.txt')
443
+
444
+ with open(requirements_path, 'r') as file:
445
+ lines = file.readlines()
446
+
447
+ front_line = next((line.strip() for line in lines if line.startswith('comfyui-frontend-package')), None)
448
+ if front_line is None:
449
+ logging.info("[ComfyUI-Manager] Skipped fixing the 'comfyui-frontend-package' dependency because the ComfyUI is outdated.")
450
+ else:
451
+ cmd = make_pip_cmd(['install', front_line])
452
+ subprocess.check_output(cmd , universal_newlines=True)
453
+ logging.info("[ComfyUI-Manager] 'comfyui-frontend-package' dependency were fixed")
454
+ except Exception as e:
455
+ logging.error("[ComfyUI-Manager] Failed to restore comfyui-frontend-package")
456
+ logging.error(e)
457
+
458
+ # restore based on custom list
459
+ pip_auto_fix_path = os.path.join(self.manager_files_path, "pip_auto_fix.list")
460
+ if os.path.exists(pip_auto_fix_path):
461
+ with open(pip_auto_fix_path, 'r', encoding="UTF-8", errors="ignore") as f:
462
+ fixed_list = []
463
+
464
+ for x in f.readlines():
465
+ try:
466
+ parsed = parse_requirement_line(x)
467
+ need_to_reinstall = True
468
+
469
+ normalized_name = parsed['package'].lower().replace('-', '_')
470
+ if normalized_name in new_pip_versions:
471
+ if 'version' in parsed and 'operator' in parsed:
472
+ cur = StrictVersion(new_pip_versions[parsed['package']])
473
+ dest = parsed['version']
474
+ op = parsed['operator']
475
+ if cur == dest:
476
+ if op in ['==', '>=', '<=']:
477
+ need_to_reinstall = False
478
+ elif cur < dest:
479
+ if op in ['<=', '<', '~=', '!=']:
480
+ need_to_reinstall = False
481
+ elif cur > dest:
482
+ if op in ['>=', '>', '~=', '!=']:
483
+ need_to_reinstall = False
484
+
485
+ if need_to_reinstall:
486
+ cmd_args = ['install']
487
+ if 'version' in parsed and 'operator' in parsed:
488
+ cmd_args.append(parsed['package']+parsed['operator']+parsed['version'].version_string)
489
+
490
+ if 'index_url' in parsed:
491
+ cmd_args.append('--index-url')
492
+ cmd_args.append(parsed['index_url'])
493
+
494
+ cmd = make_pip_cmd(cmd_args)
495
+ subprocess.check_output(cmd, universal_newlines=True)
496
+
497
+ fixed_list.append(parsed['package'])
498
+ except Exception as e:
499
+ traceback.print_exc()
500
+ logging.error(f"[ComfyUI-Manager] Failed to restore '{x}'")
501
+ logging.error(e)
502
+
503
+ if len(fixed_list) > 0:
504
+ logging.info(f"[ComfyUI-Manager] dependencies in pip_auto_fix.json were fixed: {fixed_list}")
505
+
506
+ def sanitize(data):
507
+ return data.replace("<", "&lt;").replace(">", "&gt;")
508
+
509
+
510
+ def sanitize_filename(input_string):
511
+ result_string = re.sub(r'[^a-zA-Z0-9_]', '_', input_string)
512
+ return result_string
513
+
514
+
515
+ def robust_readlines(fullpath):
516
+ import chardet
517
+ try:
518
+ with open(fullpath, "r") as f:
519
+ return f.readlines()
520
+ except:
521
+ encoding = None
522
+ with open(fullpath, "rb") as f:
523
+ raw_data = f.read()
524
+ result = chardet.detect(raw_data)
525
+ encoding = result['encoding']
526
+
527
+ if encoding is not None:
528
+ with open(fullpath, "r", encoding=encoding) as f:
529
+ return f.readlines()
530
+
531
+ print(f"[ComfyUI-Manager] Failed to recognize encoding for: {fullpath}")
532
+ return []
ComfyUI/custom_nodes/ComfyUI-Manager/glob/node_package.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ import os
5
+
6
+ from git_utils import get_commit_hash
7
+
8
+
9
+ @dataclass
10
+ class InstalledNodePackage:
11
+ """Information about an installed node package."""
12
+
13
+ id: str
14
+ fullpath: str
15
+ disabled: bool
16
+ version: str
17
+
18
+ @property
19
+ def is_unknown(self) -> bool:
20
+ return self.version == "unknown"
21
+
22
+ @property
23
+ def is_nightly(self) -> bool:
24
+ return self.version == "nightly"
25
+
26
+ @property
27
+ def is_from_cnr(self) -> bool:
28
+ return not self.is_unknown and not self.is_nightly
29
+
30
+ @property
31
+ def is_enabled(self) -> bool:
32
+ return not self.disabled
33
+
34
+ @property
35
+ def is_disabled(self) -> bool:
36
+ return self.disabled
37
+
38
+ def get_commit_hash(self) -> str:
39
+ return get_commit_hash(self.fullpath)
40
+
41
+ def isValid(self) -> bool:
42
+ if self.is_from_cnr:
43
+ return os.path.exists(os.path.join(self.fullpath, '.tracking'))
44
+
45
+ return True
46
+
47
+ @staticmethod
48
+ def from_fullpath(fullpath: str, resolve_from_path) -> InstalledNodePackage:
49
+ parent_folder_name = os.path.basename(os.path.dirname(fullpath))
50
+ module_name = os.path.basename(fullpath)
51
+
52
+ if module_name.endswith(".disabled"):
53
+ node_id = module_name[:-9]
54
+ disabled = True
55
+ elif parent_folder_name == ".disabled":
56
+ # Nodes under custom_nodes/.disabled/* are disabled
57
+ node_id = module_name
58
+ disabled = True
59
+ else:
60
+ node_id = module_name
61
+ disabled = False
62
+
63
+ info = resolve_from_path(fullpath)
64
+ if info is None:
65
+ version = 'unknown'
66
+ else:
67
+ node_id = info['id'] # robust module guessing
68
+ version = info['ver']
69
+
70
+ return InstalledNodePackage(
71
+ id=node_id, fullpath=fullpath, disabled=disabled, version=version
72
+ )
ComfyUI/custom_nodes/ComfyUI-Manager/glob/security_check.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import subprocess
3
+ import os
4
+
5
+
6
+ def security_check():
7
+ print("[START] Security scan")
8
+
9
+ custom_nodes_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
10
+ comfyui_path = os.path.abspath(os.path.join(custom_nodes_path, '..'))
11
+
12
+ guide = {
13
+ "ComfyUI_LLMVISION": """
14
+ 0.Remove ComfyUI\\custom_nodes\\ComfyUI_LLMVISION.
15
+ 1.Remove pip packages: openai-1.16.3.dist-info, anthropic-0.21.4.dist-info, openai-1.30.2.dist-info, anthropic-0.21.5.dist-info, anthropic-0.26.1.dist-info, %LocalAppData%\\rundll64.exe
16
+ (For portable versions, it is recommended to reinstall. If you are using a venv, it is advised to recreate the venv.)
17
+ 2.Remove these files in your system: lib/browser/admin.py, Cadmino.py, Fadmino.py, VISION-D.exe, BeamNG.UI.exe
18
+ 3.Check your Windows registry for the key listed above and remove it.
19
+ (HKEY_CURRENT_USER\\Software\\OpenAICLI)
20
+ 4.Run a malware scanner.
21
+ 5.Change all of your passwords, everywhere.
22
+
23
+ (Reinstall OS is recommended.)
24
+ \n
25
+ Detailed information: https://old.reddit.com/r/comfyui/comments/1dbls5n/psa_if_youve_used_the_comfyui_llmvision_node_from/
26
+ """,
27
+ "lolMiner": """
28
+ 1. Remove pip packages: lolMiner*
29
+ 2. Remove files: lolMiner*, 4G_Ethash_Linux_Readme.txt, mine* in ComfyUI dir.
30
+
31
+ (Reinstall ComfyUI is recommended.)
32
+ """,
33
+ "ultralytics==8.3.41": f"""
34
+ Execute following commands:
35
+ {sys.executable} -m pip uninstall ultralytics
36
+ {sys.executable} -m pip install ultralytics==8.3.40
37
+
38
+ And kill and remove /tmp/ultralytics_runner
39
+
40
+
41
+ The version 8.3.41 to 8.3.42 of the Ultralytics package you installed is compromised. Please uninstall that version and reinstall the latest version.
42
+ https://blog.comfy.org/comfyui-statement-on-the-ultralytics-crypto-miner-situation/
43
+ """,
44
+ "ultralytics==8.3.42": f"""
45
+ Execute following commands:
46
+ {sys.executable} -m pip uninstall ultralytics
47
+ {sys.executable} -m pip install ultralytics==8.3.40
48
+
49
+ And kill and remove /tmp/ultralytics_runner
50
+
51
+
52
+ The version 8.3.41 to 8.3.42 of the Ultralytics package you installed is compromised. Please uninstall that version and reinstall the latest version.
53
+ https://blog.comfy.org/comfyui-statement-on-the-ultralytics-crypto-miner-situation/
54
+ """
55
+ }
56
+
57
+ node_blacklist = {"ComfyUI_LLMVISION": "ComfyUI_LLMVISION"}
58
+
59
+ pip_blacklist = {
60
+ "AppleBotzz": "ComfyUI_LLMVISION",
61
+ "ultralytics==8.3.41": "ultralytics==8.3.41"
62
+ }
63
+
64
+ file_blacklist = {
65
+ "ComfyUI_LLMVISION": ["%LocalAppData%\\rundll64.exe"],
66
+ "lolMiner": [os.path.join(comfyui_path, 'lolMiner')]
67
+ }
68
+
69
+ installed_pips = subprocess.check_output([sys.executable, '-m', "pip", "freeze"], text=True)
70
+
71
+ detected = set()
72
+ try:
73
+ anthropic_info = subprocess.check_output([sys.executable, '-m', "pip", "show", "anthropic"], text=True, stderr=subprocess.DEVNULL)
74
+ anthropic_reqs = [x for x in anthropic_info.split('\n') if x.startswith("Requires")][0].split(': ')[1]
75
+ if "pycrypto" in anthropic_reqs:
76
+ location = [x for x in anthropic_info.split('\n') if x.startswith("Location")][0].split(': ')[1]
77
+ for fi in os.listdir(location):
78
+ if fi.startswith("anthropic"):
79
+ guide["ComfyUI_LLMVISION"] = f"\n0.Remove {os.path.join(location, fi)}" + guide["ComfyUI_LLMVISION"]
80
+ detected.add("ComfyUI_LLMVISION")
81
+ except subprocess.CalledProcessError:
82
+ pass
83
+
84
+ for k, v in node_blacklist.items():
85
+ if os.path.exists(os.path.join(custom_nodes_path, k)):
86
+ print(f"[SECURITY ALERT] custom node '{k}' is dangerous.")
87
+ detected.add(v)
88
+
89
+ for k, v in pip_blacklist.items():
90
+ if k in installed_pips:
91
+ detected.add(v)
92
+ break
93
+
94
+ for k, v in file_blacklist.items():
95
+ for x in v:
96
+ if os.path.exists(os.path.expandvars(x)):
97
+ detected.add(k)
98
+ break
99
+
100
+ if len(detected) > 0:
101
+ for line in installed_pips.split('\n'):
102
+ for k, v in pip_blacklist.items():
103
+ if k in line:
104
+ print(f"[SECURITY ALERT] '{line}' is dangerous.")
105
+
106
+ print("\n########################################################################")
107
+ print(" Malware has been detected, forcibly terminating ComfyUI execution.")
108
+ print("########################################################################\n")
109
+
110
+ for x in detected:
111
+ print(f"\n======== TARGET: {x} =========")
112
+ print("\nTODO:")
113
+ print(guide.get(x))
114
+
115
+ exit(-1)
116
+
117
+ print("[DONE] Security scan")
ComfyUI/custom_nodes/ComfyUI-Manager/glob/share_3rdparty.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mimetypes
2
+ import manager_core as core
3
+ import os
4
+ from aiohttp import web
5
+ import aiohttp
6
+ import json
7
+ import hashlib
8
+
9
+ import folder_paths
10
+ from server import PromptServer
11
+
12
+
13
+ def extract_model_file_names(json_data):
14
+ """Extract unique file names from the input JSON data."""
15
+ file_names = set()
16
+ model_filename_extensions = {'.safetensors', '.ckpt', '.pt', '.pth', '.bin'}
17
+
18
+ # Recursively search for file names in the JSON data
19
+ def recursive_search(data):
20
+ if isinstance(data, dict):
21
+ for value in data.values():
22
+ recursive_search(value)
23
+ elif isinstance(data, list):
24
+ for item in data:
25
+ recursive_search(item)
26
+ elif isinstance(data, str) and '.' in data:
27
+ file_names.add(os.path.basename(data)) # file_names.add(data)
28
+
29
+ recursive_search(json_data)
30
+ return [f for f in list(file_names) if os.path.splitext(f)[1] in model_filename_extensions]
31
+
32
+
33
+ def find_file_paths(base_dir, file_names):
34
+ """Find the paths of the files in the base directory."""
35
+ file_paths = {}
36
+
37
+ for root, dirs, files in os.walk(base_dir):
38
+ # Exclude certain directories
39
+ dirs[:] = [d for d in dirs if d not in ['.git']]
40
+
41
+ for file in files:
42
+ if file in file_names:
43
+ file_paths[file] = os.path.join(root, file)
44
+ return file_paths
45
+
46
+
47
+ def compute_sha256_checksum(filepath):
48
+ """Compute the SHA256 checksum of a file, in chunks"""
49
+ sha256 = hashlib.sha256()
50
+ with open(filepath, 'rb') as f:
51
+ for chunk in iter(lambda: f.read(4096), b''):
52
+ sha256.update(chunk)
53
+ return sha256.hexdigest()
54
+
55
+
56
+ @PromptServer.instance.routes.get("/manager/share_option")
57
+ async def share_option(request):
58
+ if "value" in request.rel_url.query:
59
+ core.get_config()['share_option'] = request.rel_url.query['value']
60
+ core.write_config()
61
+ else:
62
+ return web.Response(text=core.get_config()['share_option'], status=200)
63
+
64
+ return web.Response(status=200)
65
+
66
+
67
+ def get_openart_auth():
68
+ if not os.path.exists(os.path.join(core.manager_files_path, ".openart_key")):
69
+ return None
70
+ try:
71
+ with open(os.path.join(core.manager_files_path, ".openart_key"), "r") as f:
72
+ openart_key = f.read().strip()
73
+ return openart_key if openart_key else None
74
+ except:
75
+ return None
76
+
77
+
78
+ def get_matrix_auth():
79
+ if not os.path.exists(os.path.join(core.manager_files_path, "matrix_auth")):
80
+ return None
81
+ try:
82
+ with open(os.path.join(core.manager_files_path, "matrix_auth"), "r") as f:
83
+ matrix_auth = f.read()
84
+ homeserver, username, password = matrix_auth.strip().split("\n")
85
+ if not homeserver or not username or not password:
86
+ return None
87
+ return {
88
+ "homeserver": homeserver,
89
+ "username": username,
90
+ "password": password,
91
+ }
92
+ except:
93
+ return None
94
+
95
+
96
+ def get_comfyworkflows_auth():
97
+ if not os.path.exists(os.path.join(core.manager_files_path, "comfyworkflows_sharekey")):
98
+ return None
99
+ try:
100
+ with open(os.path.join(core.manager_files_path, "comfyworkflows_sharekey"), "r") as f:
101
+ share_key = f.read()
102
+ if not share_key.strip():
103
+ return None
104
+ return share_key
105
+ except:
106
+ return None
107
+
108
+
109
+ def get_youml_settings():
110
+ if not os.path.exists(os.path.join(core.manager_files_path, ".youml")):
111
+ return None
112
+ try:
113
+ with open(os.path.join(core.manager_files_path, ".youml"), "r") as f:
114
+ youml_settings = f.read().strip()
115
+ return youml_settings if youml_settings else None
116
+ except:
117
+ return None
118
+
119
+
120
+ def set_youml_settings(settings):
121
+ with open(os.path.join(core.manager_files_path, ".youml"), "w") as f:
122
+ f.write(settings)
123
+
124
+
125
+ @PromptServer.instance.routes.get("/manager/get_openart_auth")
126
+ async def api_get_openart_auth(request):
127
+ # print("Getting stored Matrix credentials...")
128
+ openart_key = get_openart_auth()
129
+ if not openart_key:
130
+ return web.Response(status=404)
131
+ return web.json_response({"openart_key": openart_key})
132
+
133
+
134
+ @PromptServer.instance.routes.post("/manager/set_openart_auth")
135
+ async def api_set_openart_auth(request):
136
+ json_data = await request.json()
137
+ openart_key = json_data['openart_key']
138
+ with open(os.path.join(core.manager_files_path, ".openart_key"), "w") as f:
139
+ f.write(openart_key)
140
+ return web.Response(status=200)
141
+
142
+
143
+ @PromptServer.instance.routes.get("/manager/get_matrix_auth")
144
+ async def api_get_matrix_auth(request):
145
+ # print("Getting stored Matrix credentials...")
146
+ matrix_auth = get_matrix_auth()
147
+ if not matrix_auth:
148
+ return web.Response(status=404)
149
+ return web.json_response(matrix_auth)
150
+
151
+
152
+ @PromptServer.instance.routes.get("/manager/youml/settings")
153
+ async def api_get_youml_settings(request):
154
+ youml_settings = get_youml_settings()
155
+ if not youml_settings:
156
+ return web.Response(status=404)
157
+ return web.json_response(json.loads(youml_settings))
158
+
159
+
160
+ @PromptServer.instance.routes.post("/manager/youml/settings")
161
+ async def api_set_youml_settings(request):
162
+ json_data = await request.json()
163
+ set_youml_settings(json.dumps(json_data))
164
+ return web.Response(status=200)
165
+
166
+
167
+ @PromptServer.instance.routes.get("/manager/get_comfyworkflows_auth")
168
+ async def api_get_comfyworkflows_auth(request):
169
+ # Check if the user has provided Matrix credentials in a file called 'matrix_accesstoken'
170
+ # in the same directory as the ComfyUI base folder
171
+ # print("Getting stored Comfyworkflows.com auth...")
172
+ comfyworkflows_auth = get_comfyworkflows_auth()
173
+ if not comfyworkflows_auth:
174
+ return web.Response(status=404)
175
+ return web.json_response({"comfyworkflows_sharekey": comfyworkflows_auth})
176
+
177
+
178
+ @PromptServer.instance.routes.post("/manager/set_esheep_workflow_and_images")
179
+ async def set_esheep_workflow_and_images(request):
180
+ json_data = await request.json()
181
+ with open(os.path.join(core.manager_files_path, "esheep_share_message.json"), "w", encoding='utf-8') as file:
182
+ json.dump(json_data, file, indent=4)
183
+ return web.Response(status=200)
184
+
185
+
186
+ @PromptServer.instance.routes.get("/manager/get_esheep_workflow_and_images")
187
+ async def get_esheep_workflow_and_images(request):
188
+ with open(os.path.join(core.manager_files_path, "esheep_share_message.json"), 'r', encoding='utf-8') as file:
189
+ data = json.load(file)
190
+ return web.Response(status=200, text=json.dumps(data))
191
+
192
+
193
+ def set_matrix_auth(json_data):
194
+ homeserver = json_data['homeserver']
195
+ username = json_data['username']
196
+ password = json_data['password']
197
+ with open(os.path.join(core.manager_files_path, "matrix_auth"), "w") as f:
198
+ f.write("\n".join([homeserver, username, password]))
199
+
200
+
201
+ def set_comfyworkflows_auth(comfyworkflows_sharekey):
202
+ with open(os.path.join(core.manager_files_path, "comfyworkflows_sharekey"), "w") as f:
203
+ f.write(comfyworkflows_sharekey)
204
+
205
+
206
+ def has_provided_matrix_auth(matrix_auth):
207
+ return matrix_auth['homeserver'].strip() and matrix_auth['username'].strip() and matrix_auth['password'].strip()
208
+
209
+
210
+ def has_provided_comfyworkflows_auth(comfyworkflows_sharekey):
211
+ return comfyworkflows_sharekey.strip()
212
+
213
+
214
+ @PromptServer.instance.routes.post("/manager/share")
215
+ async def share_art(request):
216
+ # get json data
217
+ json_data = await request.json()
218
+
219
+ matrix_auth = json_data['matrix_auth']
220
+ comfyworkflows_sharekey = json_data['cw_auth']['cw_sharekey']
221
+
222
+ set_matrix_auth(matrix_auth)
223
+ set_comfyworkflows_auth(comfyworkflows_sharekey)
224
+
225
+ share_destinations = json_data['share_destinations']
226
+ credits = json_data['credits']
227
+ title = json_data['title']
228
+ description = json_data['description']
229
+ is_nsfw = json_data['is_nsfw']
230
+ prompt = json_data['prompt']
231
+ potential_outputs = json_data['potential_outputs']
232
+ selected_output_index = json_data['selected_output_index']
233
+
234
+ try:
235
+ output_to_share = potential_outputs[int(selected_output_index)]
236
+ except:
237
+ # for now, pick the first output
238
+ output_to_share = potential_outputs[0]
239
+
240
+ assert output_to_share['type'] in ('image', 'output')
241
+ output_dir = folder_paths.get_output_directory()
242
+
243
+ if output_to_share['type'] == 'image':
244
+ asset_filename = output_to_share['image']['filename']
245
+ asset_subfolder = output_to_share['image']['subfolder']
246
+
247
+ if output_to_share['image']['type'] == 'temp':
248
+ output_dir = folder_paths.get_temp_directory()
249
+ else:
250
+ asset_filename = output_to_share['output']['filename']
251
+ asset_subfolder = output_to_share['output']['subfolder']
252
+
253
+ if asset_subfolder:
254
+ asset_filepath = os.path.join(output_dir, asset_subfolder, asset_filename)
255
+ else:
256
+ asset_filepath = os.path.join(output_dir, asset_filename)
257
+
258
+ # get the mime type of the asset
259
+ assetFileType = mimetypes.guess_type(asset_filepath)[0]
260
+
261
+ share_website_host = "UNKNOWN"
262
+ if "comfyworkflows" in share_destinations:
263
+ share_website_host = "https://comfyworkflows.com"
264
+ share_endpoint = f"{share_website_host}/api"
265
+
266
+ # get presigned urls
267
+ async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
268
+ async with session.post(
269
+ f"{share_endpoint}/get_presigned_urls",
270
+ json={
271
+ "assetFileName": asset_filename,
272
+ "assetFileType": assetFileType,
273
+ "workflowJsonFileName": 'workflow.json',
274
+ "workflowJsonFileType": 'application/json',
275
+ },
276
+ ) as resp:
277
+ assert resp.status == 200
278
+ presigned_urls_json = await resp.json()
279
+ assetFilePresignedUrl = presigned_urls_json["assetFilePresignedUrl"]
280
+ assetFileKey = presigned_urls_json["assetFileKey"]
281
+ workflowJsonFilePresignedUrl = presigned_urls_json["workflowJsonFilePresignedUrl"]
282
+ workflowJsonFileKey = presigned_urls_json["workflowJsonFileKey"]
283
+
284
+ # upload asset
285
+ async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
286
+ async with session.put(assetFilePresignedUrl, data=open(asset_filepath, "rb")) as resp:
287
+ assert resp.status == 200
288
+
289
+ # upload workflow json
290
+ async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
291
+ async with session.put(workflowJsonFilePresignedUrl, data=json.dumps(prompt['workflow']).encode('utf-8')) as resp:
292
+ assert resp.status == 200
293
+
294
+ model_filenames = extract_model_file_names(prompt['workflow'])
295
+ model_file_paths = find_file_paths(folder_paths.base_path, model_filenames)
296
+
297
+ models_info = {}
298
+ for filename, filepath in model_file_paths.items():
299
+ models_info[filename] = {
300
+ "filename": filename,
301
+ "sha256_checksum": compute_sha256_checksum(filepath),
302
+ "relative_path": os.path.relpath(filepath, folder_paths.base_path),
303
+ }
304
+
305
+ # make a POST request to /api/upload_workflow with form data key values
306
+ async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
307
+ form = aiohttp.FormData()
308
+ if comfyworkflows_sharekey:
309
+ form.add_field("shareKey", comfyworkflows_sharekey)
310
+ form.add_field("source", "comfyui_manager")
311
+ form.add_field("assetFileKey", assetFileKey)
312
+ form.add_field("assetFileType", assetFileType)
313
+ form.add_field("workflowJsonFileKey", workflowJsonFileKey)
314
+ form.add_field("sharedWorkflowWorkflowJsonString", json.dumps(prompt['workflow']))
315
+ form.add_field("sharedWorkflowPromptJsonString", json.dumps(prompt['output']))
316
+ form.add_field("shareWorkflowCredits", credits)
317
+ form.add_field("shareWorkflowTitle", title)
318
+ form.add_field("shareWorkflowDescription", description)
319
+ form.add_field("shareWorkflowIsNSFW", str(is_nsfw).lower())
320
+ form.add_field("currentSnapshot", json.dumps(await core.get_current_snapshot()))
321
+ form.add_field("modelsInfo", json.dumps(models_info))
322
+
323
+ async with session.post(
324
+ f"{share_endpoint}/upload_workflow",
325
+ data=form,
326
+ ) as resp:
327
+ assert resp.status == 200
328
+ upload_workflow_json = await resp.json()
329
+ workflowId = upload_workflow_json["workflowId"]
330
+
331
+ # check if the user has provided Matrix credentials
332
+ if "matrix" in share_destinations:
333
+ comfyui_share_room_id = '!LGYSoacpJPhIfBqVfb:matrix.org'
334
+ filename = os.path.basename(asset_filepath)
335
+ content_type = assetFileType
336
+
337
+ try:
338
+ from matrix_client.api import MatrixHttpApi
339
+ from matrix_client.client import MatrixClient
340
+
341
+ homeserver = 'matrix.org'
342
+ if matrix_auth:
343
+ homeserver = matrix_auth.get('homeserver', 'matrix.org')
344
+ homeserver = homeserver.replace("http://", "https://")
345
+ if not homeserver.startswith("https://"):
346
+ homeserver = "https://" + homeserver
347
+
348
+ client = MatrixClient(homeserver)
349
+ try:
350
+ token = client.login(username=matrix_auth['username'], password=matrix_auth['password'])
351
+ if not token:
352
+ return web.json_response({"error": "Invalid Matrix credentials."}, content_type='application/json', status=400)
353
+ except:
354
+ return web.json_response({"error": "Invalid Matrix credentials."}, content_type='application/json', status=400)
355
+
356
+ matrix = MatrixHttpApi(homeserver, token=token)
357
+ with open(asset_filepath, 'rb') as f:
358
+ mxc_url = matrix.media_upload(f.read(), content_type, filename=filename)['content_uri']
359
+
360
+ workflow_json_mxc_url = matrix.media_upload(prompt['workflow'], 'application/json', filename='workflow.json')['content_uri']
361
+
362
+ text_content = ""
363
+ if title:
364
+ text_content += f"{title}\n"
365
+ if description:
366
+ text_content += f"{description}\n"
367
+ if credits:
368
+ text_content += f"\ncredits: {credits}\n"
369
+ matrix.send_message(comfyui_share_room_id, text_content)
370
+ matrix.send_content(comfyui_share_room_id, mxc_url, filename, 'm.image')
371
+ matrix.send_content(comfyui_share_room_id, workflow_json_mxc_url, 'workflow.json', 'm.file')
372
+ except:
373
+ import traceback
374
+ traceback.print_exc()
375
+ return web.json_response({"error": "An error occurred when sharing your art to Matrix."}, content_type='application/json', status=500)
376
+
377
+ return web.json_response({
378
+ "comfyworkflows": {
379
+ "url": None if "comfyworkflows" not in share_destinations else f"{share_website_host}/workflows/{workflowId}",
380
+ },
381
+ "matrix": {
382
+ "success": None if "matrix" not in share_destinations else True
383
+ }
384
+ }, content_type='application/json', status=200)
ComfyUI/custom_nodes/ComfyUI-Manager/js/cm-api.js ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { api } from "../../scripts/api.js";
2
+ import { app } from "../../scripts/app.js";
3
+ import { sleep, customConfirm, customAlert } from "./common.js";
4
+
5
+ async function tryInstallCustomNode(event) {
6
+ let msg = '-= [ComfyUI Manager] extension installation request =-\n\n';
7
+ msg += `The '${event.detail.sender}' extension requires the installation of the '${event.detail.target.title}' extension. `;
8
+
9
+ if(event.detail.target.installed == 'Disabled') {
10
+ msg += 'However, the extension is currently disabled. Would you like to enable it and reboot?'
11
+ }
12
+ else if(event.detail.target.installed == 'True') {
13
+ msg += 'However, it seems that the extension is in an import-fail state or is not compatible with the current version. Please address this issue.';
14
+ }
15
+ else {
16
+ msg += `Would you like to install it and reboot?`;
17
+ }
18
+
19
+ msg += `\n\nRequest message:\n${event.detail.msg}`;
20
+
21
+ if(event.detail.target.installed == 'True') {
22
+ customAlert(msg);
23
+ return;
24
+ }
25
+ const res = await customConfirm(msg);
26
+ if(res) {
27
+ if(event.detail.target.installed == 'Disabled') {
28
+ const response = await api.fetchApi(`/customnode/toggle_active`, {
29
+ method: 'POST',
30
+ headers: { 'Content-Type': 'application/json' },
31
+ body: JSON.stringify(event.detail.target)
32
+ });
33
+ }
34
+ else {
35
+ await sleep(300);
36
+ app.ui.dialog.show(`Installing... '${event.detail.target.title}'`);
37
+
38
+ const response = await api.fetchApi(`/customnode/install`, {
39
+ method: 'POST',
40
+ headers: { 'Content-Type': 'application/json' },
41
+ body: JSON.stringify(event.detail.target)
42
+ });
43
+
44
+ if(response.status == 403) {
45
+ show_message('This action is not allowed with this security level configuration.');
46
+ return false;
47
+ }
48
+ else if(response.status == 400) {
49
+ let msg = await res.text();
50
+ show_message(msg);
51
+ return false;
52
+ }
53
+ }
54
+
55
+ let response = await api.fetchApi("/manager/reboot");
56
+ if(response.status == 403) {
57
+ show_message('This action is not allowed with this security level configuration.');
58
+ return false;
59
+ }
60
+
61
+ await sleep(300);
62
+
63
+ app.ui.dialog.show(`Rebooting...`);
64
+ }
65
+ }
66
+
67
+ api.addEventListener("cm-api-try-install-customnode", tryInstallCustomNode);
ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-manager.js ADDED
@@ -0,0 +1,1634 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { api } from "../../scripts/api.js";
2
+ import { app } from "../../scripts/app.js";
3
+ import { $el, ComfyDialog } from "../../scripts/ui.js";
4
+ import {
5
+ SUPPORTED_OUTPUT_NODE_TYPES,
6
+ ShareDialog,
7
+ ShareDialogChooser,
8
+ getPotentialOutputsAndOutputNodes,
9
+ showOpenArtShareDialog,
10
+ showShareDialog,
11
+ showYouMLShareDialog
12
+ } from "./comfyui-share-common.js";
13
+ import { OpenArtShareDialog } from "./comfyui-share-openart.js";
14
+ import {
15
+ free_models, install_pip, install_via_git_url, manager_instance,
16
+ rebootAPI, setManagerInstance, show_message, customAlert, customPrompt,
17
+ infoToast, showTerminal, setNeedRestart
18
+ } from "./common.js";
19
+ import { ComponentBuilderDialog, getPureName, load_components, set_component_policy } from "./components-manager.js";
20
+ import { CustomNodesManager } from "./custom-nodes-manager.js";
21
+ import { ModelManager } from "./model-manager.js";
22
+ import { SnapshotManager } from "./snapshot.js";
23
+
24
+ let manager_version = await getVersion();
25
+
26
+ var docStyle = document.createElement('style');
27
+ docStyle.innerHTML = `
28
+ .comfy-toast {
29
+ position: fixed;
30
+ bottom: 20px;
31
+ left: 50%;
32
+ transform: translateX(-50%);
33
+ background-color: rgba(0, 0, 0, 0.7);
34
+ color: white;
35
+ padding: 10px 20px;
36
+ border-radius: 5px;
37
+ z-index: 1000;
38
+ transition: opacity 0.5s;
39
+ }
40
+
41
+ .comfy-toast-fadeout {
42
+ opacity: 0;
43
+ }
44
+
45
+ #cm-manager-dialog {
46
+ width: 1000px;
47
+ height: 455px;
48
+ box-sizing: content-box;
49
+ z-index: 1000;
50
+ overflow-y: auto;
51
+ }
52
+
53
+ .cb-widget {
54
+ width: 400px;
55
+ height: 25px;
56
+ box-sizing: border-box;
57
+ z-index: 1000;
58
+ margin-top: 10px;
59
+ margin-bottom: 5px;
60
+ }
61
+
62
+ .cb-widget-input {
63
+ width: 305px;
64
+ height: 25px;
65
+ box-sizing: border-box;
66
+ }
67
+ .cb-widget-input:disabled {
68
+ background-color: #444444;
69
+ color: white;
70
+ }
71
+
72
+ .cb-widget-input-label {
73
+ width: 90px;
74
+ height: 25px;
75
+ box-sizing: border-box;
76
+ color: white;
77
+ text-align: right;
78
+ display: inline-block;
79
+ margin-right: 5px;
80
+ }
81
+
82
+ .cm-menu-container {
83
+ column-gap: 20px;
84
+ display: flex;
85
+ flex-wrap: wrap;
86
+ justify-content: center;
87
+ box-sizing: content-box;
88
+ }
89
+
90
+ .cm-menu-column {
91
+ display: flex;
92
+ flex-direction: column;
93
+ flex: 1 1 auto;
94
+ width: 300px;
95
+ box-sizing: content-box;
96
+ }
97
+
98
+ .cm-title {
99
+ background-color: black;
100
+ text-align: center;
101
+ height: 40px;
102
+ width: calc(100% - 10px);
103
+ font-weight: bold;
104
+ justify-content: center;
105
+ align-content: center;
106
+ vertical-align: middle;
107
+ }
108
+
109
+ #custom-nodes-grid a {
110
+ color: #5555FF;
111
+ font-weight: bold;
112
+ text-decoration: none;
113
+ }
114
+
115
+ #custom-nodes-grid a:hover {
116
+ color: #7777FF;
117
+ text-decoration: underline;
118
+ }
119
+
120
+ #external-models-grid a {
121
+ color: #5555FF;
122
+ font-weight: bold;
123
+ text-decoration: none;
124
+ }
125
+
126
+ #external-models-grid a:hover {
127
+ color: #7777FF;
128
+ text-decoration: underline;
129
+ }
130
+
131
+ #alternatives-grid a {
132
+ color: #5555FF;
133
+ font-weight: bold;
134
+ text-decoration: none;
135
+ }
136
+
137
+ #alternatives-grid a:hover {
138
+ color: #7777FF;
139
+ text-decoration: underline;
140
+ }
141
+
142
+ .cm-notice-board {
143
+ width: 290px;
144
+ height: 230px;
145
+ overflow: auto;
146
+ color: var(--input-text);
147
+ border: 1px solid var(--descrip-text);
148
+ padding: 5px 10px;
149
+ overflow-x: hidden;
150
+ box-sizing: content-box;
151
+ }
152
+
153
+ .cm-notice-board > ul {
154
+ display: block;
155
+ list-style-type: disc;
156
+ margin-block-start: 1em;
157
+ margin-block-end: 1em;
158
+ margin-inline-start: 0px;
159
+ margin-inline-end: 0px;
160
+ padding-inline-start: 40px;
161
+ }
162
+
163
+ .cm-conflicted-nodes-text {
164
+ background-color: #CCCC55 !important;
165
+ color: #AA3333 !important;
166
+ font-size: 10px;
167
+ border-radius: 5px;
168
+ padding: 10px;
169
+ }
170
+
171
+ .cm-warn-note {
172
+ background-color: #101010 !important;
173
+ color: #FF3800 !important;
174
+ font-size: 13px;
175
+ border-radius: 5px;
176
+ padding: 10px;
177
+ overflow-x: hidden;
178
+ overflow: auto;
179
+ }
180
+
181
+ .cm-info-note {
182
+ background-color: #101010 !important;
183
+ color: #FF3800 !important;
184
+ font-size: 13px;
185
+ border-radius: 5px;
186
+ padding: 10px;
187
+ overflow-x: hidden;
188
+ overflow: auto;
189
+ }
190
+ `;
191
+
192
+ function is_legacy_front() {
193
+ let compareVersion = '1.2.49';
194
+ try {
195
+ const frontendVersion = window['__COMFYUI_FRONTEND_VERSION__'];
196
+ if (typeof frontendVersion !== 'string') {
197
+ return false;
198
+ }
199
+
200
+ function parseVersion(versionString) {
201
+ const parts = versionString.split('.').map(Number);
202
+ return parts.length === 3 && parts.every(part => !isNaN(part)) ? parts : null;
203
+ }
204
+
205
+ const currentVersion = parseVersion(frontendVersion);
206
+ const comparisonVersion = parseVersion(compareVersion);
207
+
208
+ if (!currentVersion || !comparisonVersion) {
209
+ return false;
210
+ }
211
+
212
+ for (let i = 0; i < 3; i++) {
213
+ if (currentVersion[i] > comparisonVersion[i]) {
214
+ return false;
215
+ } else if (currentVersion[i] < comparisonVersion[i]) {
216
+ return true;
217
+ }
218
+ }
219
+
220
+ return false;
221
+ } catch {
222
+ return true;
223
+ }
224
+ }
225
+
226
+ document.head.appendChild(docStyle);
227
+
228
+ var update_comfyui_button = null;
229
+ var switch_comfyui_button = null;
230
+ var update_all_button = null;
231
+ var restart_stop_button = null;
232
+ var update_policy_combo = null;
233
+
234
+ let share_option = 'all';
235
+ var is_updating = false;
236
+
237
+
238
+ // copied style from https://github.com/pythongosssss/ComfyUI-Custom-Scripts
239
+ const style = `
240
+ #workflowgallery-button {
241
+ width: 310px;
242
+ height: 27px;
243
+ padding: 0px !important;
244
+ position: relative;
245
+ overflow: hidden;
246
+ font-size: 17px !important;
247
+ }
248
+ #cm-nodeinfo-button {
249
+ width: 310px;
250
+ height: 27px;
251
+ padding: 0px !important;
252
+ position: relative;
253
+ overflow: hidden;
254
+ font-size: 17px !important;
255
+ }
256
+ #cm-manual-button {
257
+ width: 310px;
258
+ height: 27px;
259
+ position: relative;
260
+ overflow: hidden;
261
+ }
262
+
263
+ .cm-button {
264
+ width: 310px;
265
+ height: 30px;
266
+ position: relative;
267
+ overflow: hidden;
268
+ font-size: 17px !important;
269
+ }
270
+
271
+ .cm-button-red {
272
+ width: 310px;
273
+ height: 30px;
274
+ position: relative;
275
+ overflow: hidden;
276
+ font-size: 17px !important;
277
+ background-color: #500000 !important;
278
+ color: white !important;
279
+ }
280
+
281
+
282
+ .cm-button-orange {
283
+ width: 310px;
284
+ height: 30px;
285
+ position: relative;
286
+ overflow: hidden;
287
+ font-size: 17px !important;
288
+ font-weight: bold;
289
+ background-color: orange !important;
290
+ color: black !important;
291
+ }
292
+
293
+ .cm-experimental-button {
294
+ width: 290px;
295
+ height: 30px;
296
+ position: relative;
297
+ overflow: hidden;
298
+ font-size: 17px !important;
299
+ }
300
+
301
+ .cm-experimental {
302
+ width: 310px;
303
+ border: 1px solid #555;
304
+ border-radius: 5px;
305
+ padding: 10px;
306
+ align-items: center;
307
+ text-align: center;
308
+ justify-content: center;
309
+ box-sizing: border-box;
310
+ }
311
+
312
+ .cm-experimental-legend {
313
+ margin-top: -20px;
314
+ margin-left: 50%;
315
+ width:auto;
316
+ height:20px;
317
+ font-size: 13px;
318
+ font-weight: bold;
319
+ background-color: #990000;
320
+ color: #CCFFFF;
321
+ border-radius: 5px;
322
+ text-align: center;
323
+ transform: translateX(-50%);
324
+ display: block;
325
+ }
326
+
327
+ .cm-menu-combo {
328
+ cursor: pointer;
329
+ width: 310px;
330
+ box-sizing: border-box;
331
+ }
332
+
333
+ .cm-small-button {
334
+ width: 120px;
335
+ height: 30px;
336
+ position: relative;
337
+ overflow: hidden;
338
+ box-sizing: border-box;
339
+ font-size: 17px !important;
340
+ }
341
+
342
+ #cm-install-customnodes-button {
343
+ width: 200px;
344
+ height: 30px;
345
+ position: relative;
346
+ overflow: hidden;
347
+ box-sizing: border-box;
348
+ font-size: 17px !important;
349
+ }
350
+
351
+ .cm-search-filter {
352
+ width: 200px;
353
+ height: 30px !important;
354
+ position: relative;
355
+ overflow: hidden;
356
+ box-sizing: border-box;
357
+ }
358
+
359
+ .cb-node-label {
360
+ width: 400px;
361
+ height:28px;
362
+ color: black;
363
+ background-color: #777777;
364
+ font-size: 18px;
365
+ text-align: center;
366
+ font-weight: bold;
367
+ }
368
+
369
+ #cm-close-button {
370
+ width: calc(100% - 65px);
371
+ bottom: 10px;
372
+ position: absolute;
373
+ overflow: hidden;
374
+ }
375
+
376
+ #cm-save-button {
377
+ width: calc(100% - 65px);
378
+ bottom:40px;
379
+ position: absolute;
380
+ overflow: hidden;
381
+ }
382
+ #cm-save-button:disabled {
383
+ background-color: #444444;
384
+ }
385
+
386
+ .pysssss-workflow-arrow-2 {
387
+ position: absolute;
388
+ top: 0;
389
+ bottom: 0;
390
+ right: 0;
391
+ font-size: 12px;
392
+ display: flex;
393
+ align-items: center;
394
+ width: 24px;
395
+ justify-content: center;
396
+ background: rgba(255,255,255,0.1);
397
+ content: "▼";
398
+ }
399
+ .pysssss-workflow-arrow-2:after {
400
+ content: "▼";
401
+ }
402
+ .pysssss-workflow-arrow-2:hover {
403
+ filter: brightness(1.6);
404
+ background-color: var(--comfy-menu-bg);
405
+ }
406
+ .pysssss-workflow-popup-2 ~ .litecontextmenu {
407
+ transform: scale(1.3);
408
+ }
409
+ #workflowgallery-button-menu {
410
+ z-index: 10000000000 !important;
411
+ }
412
+ #cm-manual-button-menu {
413
+ z-index: 10000000000 !important;
414
+ }
415
+ `;
416
+
417
+ async function init_share_option() {
418
+ api.fetchApi('/manager/share_option')
419
+ .then(response => response.text())
420
+ .then(data => {
421
+ share_option = data || 'all';
422
+ });
423
+ }
424
+
425
+ async function init_notice(notice) {
426
+ api.fetchApi('/manager/notice')
427
+ .then(response => response.text())
428
+ .then(data => {
429
+ notice.innerHTML = data;
430
+ })
431
+ }
432
+
433
+ await init_share_option();
434
+
435
+
436
+ async function set_inprogress_mode() {
437
+ update_comfyui_button.disabled = true;
438
+ update_comfyui_button.style.backgroundColor = "gray";
439
+
440
+ update_all_button.disabled = true;
441
+ update_all_button.style.backgroundColor = "gray";
442
+
443
+ switch_comfyui_button.disabled = true;
444
+ switch_comfyui_button.style.backgroundColor = "gray";
445
+
446
+ restart_stop_button.innerText = 'Stop';
447
+ }
448
+
449
+
450
+ async function reset_action_buttons() {
451
+ const isElectron = 'electronAPI' in window;
452
+
453
+ if(isElectron) {
454
+ update_all_button.innerText = "Update All Custom Nodes";
455
+ }
456
+ else {
457
+ update_all_button.innerText = "Update All";
458
+ }
459
+
460
+ update_comfyui_button.innerText = "Update ComfyUI";
461
+ switch_comfyui_button.innerText = "Switch ComfyUI";
462
+ restart_stop_button.innerText = 'Restart';
463
+
464
+ update_comfyui_button.disabled = false;
465
+ update_all_button.disabled = false;
466
+ switch_comfyui_button.disabled = false;
467
+
468
+ update_comfyui_button.style.backgroundColor = "";
469
+ update_all_button.style.backgroundColor = "";
470
+ switch_comfyui_button.style.backgroundColor = "";
471
+ }
472
+
473
+ async function updateComfyUI() {
474
+ let prev_text = update_comfyui_button.innerText;
475
+ update_comfyui_button.innerText = "Updating ComfyUI...";
476
+
477
+ set_inprogress_mode();
478
+
479
+ const response = await api.fetchApi('/manager/queue/update_comfyui');
480
+
481
+ showTerminal();
482
+
483
+ is_updating = true;
484
+ await api.fetchApi('/manager/queue/start');
485
+ }
486
+
487
+ function showVersionSelectorDialog(versions, current, onSelect) {
488
+ const dialog = new ComfyDialog();
489
+ dialog.element.style.zIndex = 1100;
490
+ dialog.element.style.width = "300px";
491
+ dialog.element.style.padding = "0";
492
+ dialog.element.style.backgroundColor = "#2a2a2a";
493
+ dialog.element.style.border = "1px solid #3a3a3a";
494
+ dialog.element.style.borderRadius = "8px";
495
+ dialog.element.style.boxSizing = "border-box";
496
+ dialog.element.style.overflow = "hidden";
497
+
498
+ const contentStyle = {
499
+ width: "300px",
500
+ display: "flex",
501
+ flexDirection: "column",
502
+ alignItems: "center",
503
+ padding: "20px",
504
+ boxSizing: "border-box",
505
+ gap: "15px"
506
+ };
507
+
508
+ let selectedVersion = versions[0];
509
+
510
+ const versionList = $el("select", {
511
+ multiple: true,
512
+ size: Math.min(10, versions.length),
513
+ style: {
514
+ width: "260px",
515
+ height: "auto",
516
+ backgroundColor: "#383838",
517
+ color: "#ffffff",
518
+ border: "1px solid #4a4a4a",
519
+ borderRadius: "4px",
520
+ padding: "5px",
521
+ boxSizing: "border-box"
522
+ }
523
+ },
524
+ versions.map((v, index) => $el("option", {
525
+ value: v,
526
+ textContent: v,
527
+ selected: v === current
528
+ }))
529
+ );
530
+
531
+ versionList.addEventListener('change', (e) => {
532
+ selectedVersion = e.target.value;
533
+ Array.from(e.target.options).forEach(opt => {
534
+ opt.selected = opt.value === selectedVersion;
535
+ });
536
+ });
537
+
538
+ const content = $el("div", {
539
+ style: contentStyle
540
+ }, [
541
+ $el("h3", {
542
+ textContent: "Select Version",
543
+ style: {
544
+ color: "#ffffff",
545
+ backgroundColor: "#1a1a1a",
546
+ padding: "10px 15px",
547
+ margin: "0 0 10px 0",
548
+ width: "260px",
549
+ textAlign: "center",
550
+ borderRadius: "4px",
551
+ boxSizing: "border-box",
552
+ whiteSpace: "nowrap",
553
+ overflow: "hidden",
554
+ textOverflow: "ellipsis"
555
+ }
556
+ }),
557
+ versionList,
558
+ $el("div", {
559
+ style: {
560
+ display: "flex",
561
+ justifyContent: "space-between",
562
+ width: "260px",
563
+ gap: "10px"
564
+ }
565
+ }, [
566
+ $el("button", {
567
+ textContent: "Cancel",
568
+ onclick: () => dialog.close(),
569
+ style: {
570
+ flex: "1",
571
+ padding: "8px",
572
+ backgroundColor: "#4a4a4a",
573
+ color: "#ffffff",
574
+ border: "none",
575
+ borderRadius: "4px",
576
+ cursor: "pointer",
577
+ whiteSpace: "nowrap",
578
+ overflow: "hidden",
579
+ textOverflow: "ellipsis"
580
+ }
581
+ }),
582
+ $el("button", {
583
+ textContent: "Select",
584
+ onclick: () => {
585
+ if (selectedVersion) {
586
+ onSelect(selectedVersion);
587
+ dialog.close();
588
+ } else {
589
+ customAlert("Please select a version.");
590
+ }
591
+ },
592
+ style: {
593
+ flex: "1",
594
+ padding: "8px",
595
+ backgroundColor: "#4CAF50",
596
+ color: "#ffffff",
597
+ border: "none",
598
+ borderRadius: "4px",
599
+ cursor: "pointer",
600
+ whiteSpace: "nowrap",
601
+ overflow: "hidden",
602
+ textOverflow: "ellipsis"
603
+ }
604
+ }),
605
+ ])
606
+ ]);
607
+
608
+ dialog.show(content);
609
+ }
610
+
611
+ async function switchComfyUI() {
612
+ switch_comfyui_button.disabled = true;
613
+ switch_comfyui_button.style.backgroundColor = "gray";
614
+
615
+ let res = await api.fetchApi(`/comfyui_manager/comfyui_versions`, { cache: "no-store" });
616
+
617
+ switch_comfyui_button.disabled = false;
618
+ switch_comfyui_button.style.backgroundColor = "";
619
+
620
+ if(res.status == 200) {
621
+ let obj = await res.json();
622
+
623
+ let versions = [];
624
+ let default_version;
625
+
626
+ for(let v of obj.versions) {
627
+ default_version = v;
628
+ versions.push(v);
629
+ }
630
+
631
+ showVersionSelectorDialog(versions, obj.current, async (selected_version) => {
632
+ if(selected_version == 'nightly') {
633
+ update_policy_combo.value = 'nightly-comfyui';
634
+ api.fetchApi('/manager/policy/update?value=nightly-comfyui');
635
+ }
636
+ else {
637
+ update_policy_combo.value = 'stable-comfyui';
638
+ api.fetchApi('/manager/policy/update?value=stable-comfyui');
639
+ }
640
+
641
+ let response = await api.fetchApi(`/comfyui_manager/comfyui_switch_version?ver=${selected_version}`, { cache: "no-store" });
642
+ if (response.status == 200) {
643
+ infoToast(`ComfyUI version is switched to ${selected_version}`);
644
+ }
645
+ else {
646
+ customAlert('Failed to switch ComfyUI version.');
647
+ }
648
+ });
649
+ }
650
+ else {
651
+ customAlert('Failed to fetch ComfyUI versions.');
652
+ }
653
+ }
654
+
655
+ async function onQueueStatus(event) {
656
+ const isElectron = 'electronAPI' in window;
657
+
658
+ if(event.detail.status == 'in_progress') {
659
+ set_inprogress_mode();
660
+ update_all_button.innerText = `in progress.. (${event.detail.done_count}/${event.detail.total_count})`;
661
+ }
662
+ else if(event.detail.status == 'done') {
663
+ reset_action_buttons();
664
+
665
+ if(!is_updating) {
666
+ return;
667
+ }
668
+
669
+ is_updating = false;
670
+
671
+ let success_list = [];
672
+ let failed_list = [];
673
+ let comfyui_state = null;
674
+
675
+ for(let k in event.detail.nodepack_result){
676
+ let v = event.detail.nodepack_result[k];
677
+
678
+ if(k == 'comfyui') {
679
+ comfyui_state = v;
680
+ continue;
681
+ }
682
+
683
+ if(v.msg == 'success') {
684
+ success_list.push(k);
685
+ }
686
+ else if(v.msg != 'skip')
687
+ failed_list.push(k);
688
+ }
689
+
690
+ let msg = "";
691
+
692
+ if(success_list.length == 0 && comfyui_state.startsWith('skip')) {
693
+ if(failed_list.length == 0) {
694
+ msg += "You are already up to date.";
695
+ }
696
+ }
697
+ else {
698
+ msg = "To apply the updates, you need to <button class='cm-small-button' id='cm-reboot-button5'>RESTART</button> ComfyUI.<hr>";
699
+
700
+ if(comfyui_state == 'success-nightly') {
701
+ msg += "ComfyUI has been updated to latest nightly version.<BR><BR>";
702
+ infoToast("ComfyUI has been updated to the latest nightly version.");
703
+ }
704
+ else if(comfyui_state.startsWith('success-stable')) {
705
+ const ver = comfyui_state.split("-").pop();
706
+ msg += `ComfyUI has been updated to ${ver}.<BR><BR>`;
707
+ infoToast(`ComfyUI has been updated to ${ver}`);
708
+ }
709
+ else if(comfyui_state == 'skip') {
710
+ msg += "ComfyUI is already up to date.<BR><BR>"
711
+ }
712
+ else if(comfyui_state != null) {
713
+ msg += "Failed to update ComfyUI.<BR><BR>"
714
+ }
715
+
716
+ if(success_list.length > 0) {
717
+ msg += "The following custom nodes have been updated:<ul>";
718
+ for(let x in success_list) {
719
+ let k = success_list[x];
720
+ let url = event.detail.nodepack_result[k].url;
721
+ let title = event.detail.nodepack_result[k].title;
722
+ if(url) {
723
+ msg += `<li><a href='${url}' target='_blank'>${title}</a></li>`;
724
+ }
725
+ else {
726
+ msg += `<li>${k}</li>`;
727
+ }
728
+ }
729
+ msg += "</ul>";
730
+ }
731
+
732
+ setNeedRestart(true);
733
+ }
734
+
735
+ if(failed_list.length > 0) {
736
+ msg += '<br>The update for the following custom nodes has failed:<ul>';
737
+ for(let x in failed_list) {
738
+ let k = failed_list[x];
739
+ let url = event.detail.nodepack_result[k].url;
740
+ let title = event.detail.nodepack_result[k].title;
741
+ if(url) {
742
+ msg += `<li><a href='${url}' target='_blank'>${title}</a></li>`;
743
+ }
744
+ else {
745
+ msg += `<li>${k}</li>`;
746
+ }
747
+ }
748
+
749
+ msg += '</ul>'
750
+ }
751
+
752
+ show_message(msg);
753
+
754
+ const rebootButton = document.getElementById('cm-reboot-button5');
755
+ rebootButton?.addEventListener("click",
756
+ function() {
757
+ if(rebootAPI()) {
758
+ manager_dialog.close();
759
+ }
760
+ });
761
+ }
762
+ }
763
+
764
+ api.addEventListener("cm-queue-status", onQueueStatus);
765
+
766
+
767
+ async function updateAll(update_comfyui) {
768
+ update_all_button.innerText = "Updating...";
769
+
770
+ set_inprogress_mode();
771
+
772
+ var mode = manager_instance.datasrc_combo.value;
773
+
774
+ showTerminal();
775
+
776
+ if(update_comfyui) {
777
+ update_all_button.innerText = "Updating ComfyUI...";
778
+ await api.fetchApi('/manager/queue/update_comfyui');
779
+ }
780
+
781
+ const response = await api.fetchApi(`/manager/queue/update_all?mode=${mode}`);
782
+
783
+ if (response.status == 401) {
784
+ customAlert('Another task is already in progress. Please stop the ongoing task first.');
785
+ }
786
+ else if(response.status == 200) {
787
+ is_updating = true;
788
+ await api.fetchApi('/manager/queue/start');
789
+ }
790
+ }
791
+
792
+ function newDOMTokenList(initialTokens) {
793
+ const tmp = document.createElement(`div`);
794
+
795
+ const classList = tmp.classList;
796
+ if (initialTokens) {
797
+ initialTokens.forEach(token => {
798
+ classList.add(token);
799
+ });
800
+ }
801
+
802
+ return classList;
803
+ }
804
+
805
+ /**
806
+ * Check whether the node is a potential output node (img, gif or video output)
807
+ */
808
+ const isOutputNode = (node) => {
809
+ return SUPPORTED_OUTPUT_NODE_TYPES.includes(node.type);
810
+ }
811
+
812
+ function restartOrStop() {
813
+ if(restart_stop_button.innerText == 'Restart'){
814
+ rebootAPI();
815
+ }
816
+ else {
817
+ api.fetchApi('/manager/queue/reset');
818
+ infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
819
+ }
820
+ }
821
+
822
+ // -----------
823
+ class ManagerMenuDialog extends ComfyDialog {
824
+ createControlsMid() {
825
+ let self = this;
826
+ const isElectron = 'electronAPI' in window;
827
+
828
+ update_comfyui_button =
829
+ $el("button.cm-button", {
830
+ type: "button",
831
+ textContent: "Update ComfyUI",
832
+ style: {
833
+ display: isElectron ? 'none' : 'block'
834
+ },
835
+ onclick:
836
+ () => updateComfyUI()
837
+ });
838
+
839
+ switch_comfyui_button =
840
+ $el("button.cm-button", {
841
+ type: "button",
842
+ textContent: "Switch ComfyUI",
843
+ style: {
844
+ display: isElectron ? 'none' : 'block'
845
+ },
846
+ onclick:
847
+ () => switchComfyUI()
848
+ });
849
+
850
+ restart_stop_button =
851
+ $el("button.cm-button-red", {
852
+ type: "button",
853
+ textContent: "Restart",
854
+ onclick: () => restartOrStop()
855
+ });
856
+
857
+ if(isElectron) {
858
+ update_all_button =
859
+ $el("button.cm-button", {
860
+ type: "button",
861
+ textContent: "Update All Custom Nodes",
862
+ onclick:
863
+ () => updateAll(false)
864
+ });
865
+ }
866
+ else {
867
+ update_all_button =
868
+ $el("button.cm-button", {
869
+ type: "button",
870
+ textContent: "Update All",
871
+ onclick:
872
+ () => updateAll(true)
873
+ });
874
+ }
875
+
876
+ const res =
877
+ [
878
+ $el("button.cm-button", {
879
+ type: "button",
880
+ textContent: "Custom Nodes Manager",
881
+ onclick:
882
+ () => {
883
+ if(!CustomNodesManager.instance) {
884
+ CustomNodesManager.instance = new CustomNodesManager(app, self);
885
+ }
886
+ CustomNodesManager.instance.show(CustomNodesManager.ShowMode.NORMAL);
887
+ }
888
+ }),
889
+
890
+ $el("button.cm-button", {
891
+ type: "button",
892
+ textContent: "Install Missing Custom Nodes",
893
+ onclick:
894
+ () => {
895
+ if(!CustomNodesManager.instance) {
896
+ CustomNodesManager.instance = new CustomNodesManager(app, self);
897
+ }
898
+ CustomNodesManager.instance.show(CustomNodesManager.ShowMode.MISSING);
899
+ }
900
+ }),
901
+
902
+ $el("button.cm-button", {
903
+ type: "button",
904
+ textContent: "Custom Nodes In Workflow",
905
+ onclick:
906
+ () => {
907
+ if(!CustomNodesManager.instance) {
908
+ CustomNodesManager.instance = new CustomNodesManager(app, self);
909
+ }
910
+ CustomNodesManager.instance.show(CustomNodesManager.ShowMode.IN_WORKFLOW);
911
+ }
912
+ }),
913
+
914
+ $el("br", {}, []),
915
+ $el("button.cm-button", {
916
+ type: "button",
917
+ textContent: "Model Manager",
918
+ onclick:
919
+ () => {
920
+ if(!ModelManager.instance) {
921
+ ModelManager.instance = new ModelManager(app, self);
922
+ }
923
+ ModelManager.instance.show();
924
+ }
925
+ }),
926
+
927
+ $el("button.cm-button", {
928
+ type: "button",
929
+ textContent: "Install via Git URL",
930
+ onclick: async () => {
931
+ var url = await customPrompt("Please enter the URL of the Git repository to install", "");
932
+
933
+ if (url !== null) {
934
+ install_via_git_url(url, self);
935
+ }
936
+ }
937
+ }),
938
+
939
+ $el("br", {}, []),
940
+ update_all_button,
941
+ update_comfyui_button,
942
+ switch_comfyui_button,
943
+ // fetch_updates_button,
944
+
945
+ $el("br", {}, []),
946
+ restart_stop_button,
947
+ ];
948
+
949
+ return res;
950
+ }
951
+
952
+ createControlsLeft() {
953
+ const isElectron = 'electronAPI' in window;
954
+
955
+ let self = this;
956
+
957
+ // db mode
958
+ this.datasrc_combo = document.createElement("select");
959
+ this.datasrc_combo.setAttribute("title", "Configure where to retrieve node/model information. If set to 'local,' the channel is ignored, and if set to 'channel (remote),' it fetches the latest information each time the list is opened.");
960
+ this.datasrc_combo.className = "cm-menu-combo";
961
+ this.datasrc_combo.appendChild($el('option', { value: 'cache', text: 'DB: Channel (1day cache)' }, []));
962
+ this.datasrc_combo.appendChild($el('option', { value: 'local', text: 'DB: Local' }, []));
963
+ this.datasrc_combo.appendChild($el('option', { value: 'remote', text: 'DB: Channel (remote)' }, []));
964
+
965
+ api.fetchApi('/manager/db_mode')
966
+ .then(response => response.text())
967
+ .then(data => { this.datasrc_combo.value = data; });
968
+
969
+ this.datasrc_combo.addEventListener('change', function (event) {
970
+ api.fetchApi(`/manager/db_mode?value=${event.target.value}`);
971
+ });
972
+
973
+ // preview method
974
+ let preview_combo = document.createElement("select");
975
+ preview_combo.setAttribute("title", "Configure how latent variables will be decoded during preview in the sampling process.");
976
+ preview_combo.className = "cm-menu-combo";
977
+ preview_combo.appendChild($el('option', { value: 'auto', text: 'Preview method: Auto' }, []));
978
+ preview_combo.appendChild($el('option', { value: 'taesd', text: 'Preview method: TAESD (slow)' }, []));
979
+ preview_combo.appendChild($el('option', { value: 'latent2rgb', text: 'Preview method: Latent2RGB (fast)' }, []));
980
+ preview_combo.appendChild($el('option', { value: 'none', text: 'Preview method: None (very fast)' }, []));
981
+
982
+ api.fetchApi('/manager/preview_method')
983
+ .then(response => response.text())
984
+ .then(data => { preview_combo.value = data; });
985
+
986
+ preview_combo.addEventListener('change', function (event) {
987
+ api.fetchApi(`/manager/preview_method?value=${event.target.value}`);
988
+ });
989
+
990
+ // channel
991
+ let channel_combo = document.createElement("select");
992
+ channel_combo.setAttribute("title", "Configure the channel for retrieving data from the Custom Node list (including missing nodes) or the Model list.");
993
+ channel_combo.className = "cm-menu-combo";
994
+ api.fetchApi('/manager/channel_url_list')
995
+ .then(response => response.json())
996
+ .then(async data => {
997
+ try {
998
+ let urls = data.list;
999
+ for (let i in urls) {
1000
+ if (urls[i] != '') {
1001
+ let name_url = urls[i].split('::');
1002
+ channel_combo.appendChild($el('option', { value: name_url[0], text: `Channel: ${name_url[0]}` }, []));
1003
+ }
1004
+ }
1005
+
1006
+ channel_combo.addEventListener('change', function (event) {
1007
+ api.fetchApi(`/manager/channel_url_list?value=${event.target.value}`);
1008
+ });
1009
+
1010
+ channel_combo.value = data.selected;
1011
+ }
1012
+ catch (exception) {
1013
+
1014
+ }
1015
+ });
1016
+
1017
+
1018
+ // share
1019
+ let share_combo = document.createElement("select");
1020
+ share_combo.setAttribute("title", "Hide the share button in the main menu or set the default action upon clicking it. Additionally, configure the default share site when sharing via the context menu's share button.");
1021
+ share_combo.className = "cm-menu-combo";
1022
+ const share_options = [
1023
+ ['none', 'None'],
1024
+ ['openart', 'OpenArt AI'],
1025
+ ['youml', 'YouML'],
1026
+ ['matrix', 'Matrix Server'],
1027
+ ['comfyworkflows', 'ComfyWorkflows'],
1028
+ ['copus', 'Copus'],
1029
+ ['all', 'All'],
1030
+ ];
1031
+ for (const option of share_options) {
1032
+ share_combo.appendChild($el('option', { value: option[0], text: `Share: ${option[1]}` }, []));
1033
+ }
1034
+
1035
+ api.fetchApi('/manager/share_option')
1036
+ .then(response => response.text())
1037
+ .then(data => {
1038
+ share_combo.value = data || 'all';
1039
+ share_option = data || 'all';
1040
+ });
1041
+
1042
+ share_combo.addEventListener('change', function (event) {
1043
+ const value = event.target.value;
1044
+ share_option = value;
1045
+ api.fetchApi(`/manager/share_option?value=${value}`);
1046
+ const shareButton = document.getElementById("shareButton");
1047
+ if (value === 'none') {
1048
+ shareButton.style.display = "none";
1049
+ } else {
1050
+ shareButton.style.display = "inline-block";
1051
+ }
1052
+ });
1053
+
1054
+ let component_policy_combo = document.createElement("select");
1055
+ component_policy_combo.setAttribute("title", "When loading the workflow, configure which version of the component to use.");
1056
+ component_policy_combo.className = "cm-menu-combo";
1057
+ component_policy_combo.appendChild($el('option', { value: 'workflow', text: 'Component: Use workflow version' }, []));
1058
+ component_policy_combo.appendChild($el('option', { value: 'higher', text: 'Component: Use higher version' }, []));
1059
+ component_policy_combo.appendChild($el('option', { value: 'mine', text: 'Component: Use my version' }, []));
1060
+ api.fetchApi('/manager/policy/component')
1061
+ .then(response => response.text())
1062
+ .then(data => {
1063
+ component_policy_combo.value = data;
1064
+ set_component_policy(data);
1065
+ });
1066
+
1067
+ component_policy_combo.addEventListener('change', function (event) {
1068
+ api.fetchApi(`/manager/policy/component?value=${event.target.value}`);
1069
+ set_component_policy(event.target.value);
1070
+ });
1071
+
1072
+ update_policy_combo = document.createElement("select");
1073
+
1074
+ if(isElectron)
1075
+ update_policy_combo.style.display = 'none';
1076
+
1077
+ update_policy_combo.setAttribute("title", "Sets the policy to be applied when performing an update.");
1078
+ update_policy_combo.className = "cm-menu-combo";
1079
+ update_policy_combo.appendChild($el('option', { value: 'stable-comfyui', text: 'Update: ComfyUI Stable Version' }, []));
1080
+ update_policy_combo.appendChild($el('option', { value: 'nightly-comfyui', text: 'Update: ComfyUI Nightly Version' }, []));
1081
+ api.fetchApi('/manager/policy/update')
1082
+ .then(response => response.text())
1083
+ .then(data => {
1084
+ update_policy_combo.value = data;
1085
+ });
1086
+
1087
+ update_policy_combo.addEventListener('change', function (event) {
1088
+ api.fetchApi(`/manager/policy/update?value=${event.target.value}`);
1089
+ });
1090
+
1091
+ return [
1092
+ $el("br", {}, []),
1093
+ this.datasrc_combo,
1094
+ channel_combo,
1095
+ preview_combo,
1096
+ share_combo,
1097
+ component_policy_combo,
1098
+ update_policy_combo,
1099
+ $el("br", {}, []),
1100
+
1101
+ $el("br", {}, []),
1102
+ $el("filedset.cm-experimental", {}, [
1103
+ $el("legend.cm-experimental-legend", {}, ["EXPERIMENTAL"]),
1104
+ $el("button.cm-experimental-button", {
1105
+ type: "button",
1106
+ textContent: "Snapshot Manager",
1107
+ onclick:
1108
+ () => {
1109
+ if(!SnapshotManager.instance)
1110
+ SnapshotManager.instance = new SnapshotManager(app, self);
1111
+ SnapshotManager.instance.show();
1112
+ }
1113
+ }),
1114
+ $el("button.cm-experimental-button", {
1115
+ type: "button",
1116
+ textContent: "Install PIP packages",
1117
+ onclick:
1118
+ async () => {
1119
+ var url = await customPrompt("Please enumerate the pip packages to be installed.\n\nExample: insightface opencv-python-headless>=4.1.1\n", "");
1120
+
1121
+ if (url !== null) {
1122
+ install_pip(url, self);
1123
+ }
1124
+ }
1125
+ })
1126
+ ]),
1127
+ ];
1128
+ }
1129
+
1130
+ createControlsRight() {
1131
+ const elts = [
1132
+ $el("button.cm-button", {
1133
+ id: 'cm-manual-button',
1134
+ type: "button",
1135
+ textContent: "Community Manual",
1136
+ onclick: () => { window.open("https://blenderneko.github.io/ComfyUI-docs/", "comfyui-community-manual"); }
1137
+ }, [
1138
+ $el("div.pysssss-workflow-arrow-2", {
1139
+ id: `cm-manual-button-arrow`,
1140
+ onclick: (e) => {
1141
+ e.preventDefault();
1142
+ e.stopPropagation();
1143
+
1144
+ LiteGraph.closeAllContextMenus();
1145
+ const menu = new LiteGraph.ContextMenu(
1146
+ [
1147
+ {
1148
+ title: "ComfyUI Docs",
1149
+ callback: () => { window.open("https://docs.comfy.org/", "comfyui-official-manual"); },
1150
+ },
1151
+ {
1152
+ title: "Comfy Custom Node How To",
1153
+ callback: () => { window.open("https://github.com/chrisgoringe/Comfy-Custom-Node-How-To/wiki/aaa_index", "comfyui-community-manual1"); },
1154
+ },
1155
+ {
1156
+ title: "ComfyUI Guide To Making Custom Nodes",
1157
+ callback: () => { window.open("https://github.com/Suzie1/ComfyUI_Guide_To_Making_Custom_Nodes/wiki", "comfyui-community-manual2"); },
1158
+ },
1159
+ {
1160
+ title: "ComfyUI Examples",
1161
+ callback: () => { window.open("https://comfyanonymous.github.io/ComfyUI_examples", "comfyui-community-manual3"); },
1162
+ },
1163
+ {
1164
+ title: "Close",
1165
+ callback: () => {
1166
+ LiteGraph.closeAllContextMenus();
1167
+ },
1168
+ }
1169
+ ],
1170
+ {
1171
+ event: e,
1172
+ scale: 1.3,
1173
+ },
1174
+ window
1175
+ );
1176
+ // set the id so that we can override the context menu's z-index to be above the comfyui manager menu
1177
+ menu.root.id = "cm-manual-button-menu";
1178
+ menu.root.classList.add("pysssss-workflow-popup-2");
1179
+ },
1180
+ })
1181
+ ]),
1182
+
1183
+ $el("button", {
1184
+ id: 'workflowgallery-button',
1185
+ type: "button",
1186
+ style: {
1187
+ ...(localStorage.getItem("wg_last_visited") ? {height: '50px'} : {})
1188
+ },
1189
+ onclick: (e) => {
1190
+ const last_visited_site = localStorage.getItem("wg_last_visited")
1191
+ if (!!last_visited_site) {
1192
+ window.open(last_visited_site, last_visited_site);
1193
+ } else {
1194
+ this.handleWorkflowGalleryButtonClick(e)
1195
+ }
1196
+ },
1197
+ }, [
1198
+ $el("p", {
1199
+ textContent: 'Workflow Gallery',
1200
+ style: {
1201
+ 'text-align': 'center',
1202
+ 'color': 'var(--input-text)',
1203
+ 'font-size': '18px',
1204
+ 'margin': 0,
1205
+ 'padding': 0,
1206
+ }
1207
+ }, [
1208
+ $el("p", {
1209
+ id: 'workflowgallery-button-last-visited-label',
1210
+ textContent: `(${localStorage.getItem("wg_last_visited") ? localStorage.getItem("wg_last_visited").split('/')[2] : ''})`,
1211
+ style: {
1212
+ 'text-align': 'center',
1213
+ 'color': 'var(--input-text)',
1214
+ 'font-size': '12px',
1215
+ 'margin': 0,
1216
+ 'padding': 0,
1217
+ }
1218
+ })
1219
+ ]),
1220
+ $el("div.pysssss-workflow-arrow-2", {
1221
+ id: `comfyworkflows-button-arrow`,
1222
+ onclick: this.handleWorkflowGalleryButtonClick
1223
+ })
1224
+ ]),
1225
+
1226
+ $el("button.cm-button", {
1227
+ id: 'cm-nodeinfo-button',
1228
+ type: "button",
1229
+ textContent: "Nodes Info",
1230
+ onclick: () => { window.open("https://ltdrdata.github.io/", "comfyui-node-info"); }
1231
+ }),
1232
+ $el("br", {}, []),
1233
+ ];
1234
+
1235
+ var textarea = document.createElement("div");
1236
+ textarea.className = "cm-notice-board";
1237
+ elts.push(textarea);
1238
+
1239
+ init_notice(textarea);
1240
+
1241
+ return elts;
1242
+ }
1243
+
1244
+ constructor() {
1245
+ super();
1246
+
1247
+ const close_button = $el("button", { id: "cm-close-button", type: "button", textContent: "Close", onclick: () => this.close() });
1248
+
1249
+ const content =
1250
+ $el("div.comfy-modal-content",
1251
+ [
1252
+ $el("tr.cm-title", {}, [
1253
+ $el("font", {size:6, color:"white"}, [`ComfyUI Manager ${manager_version}`])]
1254
+ ),
1255
+ $el("br", {}, []),
1256
+ $el("div.cm-menu-container",
1257
+ [
1258
+ $el("div.cm-menu-column", [...this.createControlsLeft()]),
1259
+ $el("div.cm-menu-column", [...this.createControlsMid()]),
1260
+ $el("div.cm-menu-column", [...this.createControlsRight()])
1261
+ ]),
1262
+
1263
+ $el("br", {}, []),
1264
+ close_button,
1265
+ ]
1266
+ );
1267
+
1268
+ content.style.width = '100%';
1269
+ content.style.height = '100%';
1270
+
1271
+ this.element = $el("div.comfy-modal", { id:'cm-manager-dialog', parent: document.body }, [ content ]);
1272
+ }
1273
+
1274
+ get isVisible() {
1275
+ return this.element?.style?.display !== "none";
1276
+ }
1277
+
1278
+ show() {
1279
+ this.element.style.display = "block";
1280
+ }
1281
+
1282
+ toggleVisibility() {
1283
+ if (this.isVisible) {
1284
+ this.close();
1285
+ } else {
1286
+ this.show();
1287
+ }
1288
+ }
1289
+
1290
+ handleWorkflowGalleryButtonClick(e) {
1291
+ e.preventDefault();
1292
+ e.stopPropagation();
1293
+ LiteGraph.closeAllContextMenus();
1294
+
1295
+ // Modify the style of the button so that the UI can indicate the last
1296
+ // visited site right away.
1297
+ const modifyButtonStyle = (url) => {
1298
+ const workflowGalleryButton = document.getElementById('workflowgallery-button');
1299
+ workflowGalleryButton.style.height = '50px';
1300
+ const lastVisitedLabel = document.getElementById('workflowgallery-button-last-visited-label');
1301
+ lastVisitedLabel.textContent = `(${url.split('/')[2]})`;
1302
+ }
1303
+
1304
+ const menu = new LiteGraph.ContextMenu(
1305
+ [
1306
+ {
1307
+ title: "Share your art",
1308
+ callback: () => {
1309
+ if (share_option === 'openart') {
1310
+ showOpenArtShareDialog();
1311
+ return;
1312
+ } else if (share_option === 'matrix' || share_option === 'comfyworkflows') {
1313
+ showShareDialog(share_option);
1314
+ return;
1315
+ } else if (share_option === 'youml') {
1316
+ showYouMLShareDialog();
1317
+ return;
1318
+ }
1319
+
1320
+ if (!ShareDialogChooser.instance) {
1321
+ ShareDialogChooser.instance = new ShareDialogChooser();
1322
+ }
1323
+ ShareDialogChooser.instance.show();
1324
+ },
1325
+ },
1326
+ {
1327
+ title: "Open 'openart.ai'",
1328
+ callback: () => {
1329
+ const url = "https://openart.ai/workflows/dev";
1330
+ localStorage.setItem("wg_last_visited", url);
1331
+ window.open(url, url);
1332
+ modifyButtonStyle(url);
1333
+ },
1334
+ },
1335
+ {
1336
+ title: "Open 'youml.com'",
1337
+ callback: () => {
1338
+ const url = "https://youml.com/?from=comfyui-share";
1339
+ localStorage.setItem("wg_last_visited", url);
1340
+ window.open(url, url);
1341
+ modifyButtonStyle(url);
1342
+ },
1343
+ },
1344
+ {
1345
+ title: "Open 'comfyworkflows.com'",
1346
+ callback: () => {
1347
+ const url = "https://comfyworkflows.com/";
1348
+ localStorage.setItem("wg_last_visited", url);
1349
+ window.open(url, url);
1350
+ modifyButtonStyle(url);
1351
+ },
1352
+ },
1353
+ {
1354
+ title: "Open 'esheep'",
1355
+ callback: () => {
1356
+ const url = "https://www.esheep.com";
1357
+ localStorage.setItem("wg_last_visited", url);
1358
+ window.open(url, url);
1359
+ modifyButtonStyle(url);
1360
+ },
1361
+ },
1362
+ {
1363
+ title: "Open 'Copus.io'",
1364
+ callback: () => {
1365
+ const url = "https://www.copus.io";
1366
+ localStorage.setItem("wg_last_visited", url);
1367
+ window.open(url, url);
1368
+ modifyButtonStyle(url);
1369
+ },
1370
+ },
1371
+ {
1372
+ title: "Close",
1373
+ callback: () => {
1374
+ LiteGraph.closeAllContextMenus();
1375
+ },
1376
+ }
1377
+ ],
1378
+ {
1379
+ event: e,
1380
+ scale: 1.3,
1381
+ },
1382
+ window
1383
+ );
1384
+ // set the id so that we can override the context menu's z-index to be above the comfyui manager menu
1385
+ menu.root.id = "workflowgallery-button-menu";
1386
+ menu.root.classList.add("pysssss-workflow-popup-2");
1387
+ }
1388
+ }
1389
+
1390
+ async function getVersion() {
1391
+ let version = await api.fetchApi(`/manager/version`);
1392
+ return await version.text();
1393
+ }
1394
+
1395
+ app.registerExtension({
1396
+ name: "Comfy.ManagerMenu",
1397
+
1398
+ aboutPageBadges: [
1399
+ {
1400
+ label: `ComfyUI-Manager ${manager_version}`,
1401
+ url: 'https://github.com/ltdrdata/ComfyUI-Manager',
1402
+ icon: 'pi pi-th-large'
1403
+ }
1404
+ ],
1405
+
1406
+ commands: [
1407
+ {
1408
+ id: "Comfy.Manager.Menu.ToggleVisibility",
1409
+ label: "Toggle Manager Menu Visibility",
1410
+ icon: "mdi mdi-puzzle",
1411
+ function: () => {
1412
+ if (!manager_instance) {
1413
+ setManagerInstance(new ManagerMenuDialog());
1414
+ manager_instance.show();
1415
+ } else {
1416
+ manager_instance.toggleVisibility();
1417
+ }
1418
+ },
1419
+ },
1420
+ {
1421
+ id: "Comfy.Manager.CustomNodesManager.ToggleVisibility",
1422
+ label: "Toggle Custom Nodes Manager Visibility",
1423
+ icon: "pi pi-server",
1424
+ function: () => {
1425
+ if (CustomNodesManager.instance?.isVisible) {
1426
+ CustomNodesManager.instance.close();
1427
+ return;
1428
+ }
1429
+
1430
+ if (!manager_instance) {
1431
+ setManagerInstance(new ManagerMenuDialog());
1432
+ }
1433
+ if (!CustomNodesManager.instance) {
1434
+ CustomNodesManager.instance = new CustomNodesManager(app, self);
1435
+ }
1436
+ CustomNodesManager.instance.show(CustomNodesManager.ShowMode.NORMAL);
1437
+ },
1438
+ }
1439
+ ],
1440
+
1441
+ init() {
1442
+ $el("style", {
1443
+ textContent: style,
1444
+ parent: document.head,
1445
+ });
1446
+ },
1447
+ async setup() {
1448
+ let orig_clear = app.graph.clear;
1449
+ app.graph.clear = function () {
1450
+ orig_clear.call(app.graph);
1451
+ load_components();
1452
+ };
1453
+
1454
+ load_components();
1455
+
1456
+ const menu = document.querySelector(".comfy-menu");
1457
+ const separator = document.createElement("hr");
1458
+
1459
+ separator.style.margin = "20px 0";
1460
+ separator.style.width = "100%";
1461
+ menu.append(separator);
1462
+
1463
+ try {
1464
+ // new style Manager buttons
1465
+ // unload models button into new style Manager button
1466
+ let cmGroup = new (await import("../../scripts/ui/components/buttonGroup.js")).ComfyButtonGroup(
1467
+ new(await import("../../scripts/ui/components/button.js")).ComfyButton({
1468
+ icon: "puzzle",
1469
+ action: () => {
1470
+ if(!manager_instance)
1471
+ setManagerInstance(new ManagerMenuDialog());
1472
+ manager_instance.show();
1473
+ },
1474
+ tooltip: "ComfyUI Manager",
1475
+ content: "Manager",
1476
+ classList: "comfyui-button comfyui-menu-mobile-collapse primary"
1477
+ }).element,
1478
+ new(await import("../../scripts/ui/components/button.js")).ComfyButton({
1479
+ icon: "star",
1480
+ action: () => {
1481
+ if(!manager_instance)
1482
+ setManagerInstance(new ManagerMenuDialog());
1483
+
1484
+ if(!CustomNodesManager.instance) {
1485
+ CustomNodesManager.instance = new CustomNodesManager(app, self);
1486
+ }
1487
+ CustomNodesManager.instance.show(CustomNodesManager.ShowMode.FAVORITES);
1488
+ },
1489
+ tooltip: "Show favorite custom node list"
1490
+ }).element,
1491
+ new(await import("../../scripts/ui/components/button.js")).ComfyButton({
1492
+ icon: "vacuum-outline",
1493
+ action: () => {
1494
+ free_models();
1495
+ },
1496
+ tooltip: "Unload Models"
1497
+ }).element,
1498
+ new(await import("../../scripts/ui/components/button.js")).ComfyButton({
1499
+ icon: "vacuum",
1500
+ action: () => {
1501
+ free_models(true);
1502
+ },
1503
+ tooltip: "Free model and node cache"
1504
+ }).element,
1505
+ new(await import("../../scripts/ui/components/button.js")).ComfyButton({
1506
+ icon: "share",
1507
+ action: () => {
1508
+ if (share_option === 'openart') {
1509
+ showOpenArtShareDialog();
1510
+ return;
1511
+ } else if (share_option === 'matrix' || share_option === 'comfyworkflows') {
1512
+ showShareDialog(share_option);
1513
+ return;
1514
+ } else if (share_option === 'youml') {
1515
+ showYouMLShareDialog();
1516
+ return;
1517
+ }
1518
+
1519
+ if(!ShareDialogChooser.instance) {
1520
+ ShareDialogChooser.instance = new ShareDialogChooser();
1521
+ }
1522
+ ShareDialogChooser.instance.show();
1523
+ },
1524
+ tooltip: "Share"
1525
+ }).element
1526
+ );
1527
+
1528
+ app.menu?.settingsGroup.element.before(cmGroup.element);
1529
+ }
1530
+ catch(exception) {
1531
+ console.log('ComfyUI is outdated. New style menu based features are disabled.');
1532
+ }
1533
+
1534
+ // old style Manager button
1535
+ const managerButton = document.createElement("button");
1536
+ managerButton.textContent = "Manager";
1537
+ managerButton.onclick = () => {
1538
+ if(!manager_instance)
1539
+ setManagerInstance(new ManagerMenuDialog());
1540
+ manager_instance.show();
1541
+ }
1542
+ menu.append(managerButton);
1543
+
1544
+ const shareButton = document.createElement("button");
1545
+ shareButton.id = "shareButton";
1546
+ shareButton.textContent = "Share";
1547
+ shareButton.onclick = () => {
1548
+ if (share_option === 'openart') {
1549
+ showOpenArtShareDialog();
1550
+ return;
1551
+ } else if (share_option === 'matrix' || share_option === 'comfyworkflows') {
1552
+ showShareDialog(share_option);
1553
+ return;
1554
+ } else if (share_option === 'youml') {
1555
+ showYouMLShareDialog();
1556
+ return;
1557
+ }
1558
+
1559
+ if(!ShareDialogChooser.instance) {
1560
+ ShareDialogChooser.instance = new ShareDialogChooser();
1561
+ }
1562
+ ShareDialogChooser.instance.show();
1563
+ }
1564
+ // make the background color a gradient of blue to green
1565
+ shareButton.style.background = "linear-gradient(90deg, #00C9FF 0%, #92FE9D 100%)";
1566
+ shareButton.style.color = "black";
1567
+
1568
+ // Load share option from local storage to determine whether to show
1569
+ // the share button.
1570
+ const shouldShowShareButton = share_option !== 'none';
1571
+ shareButton.style.display = shouldShowShareButton ? "inline-block" : "none";
1572
+
1573
+ menu.append(shareButton);
1574
+ },
1575
+
1576
+ async beforeRegisterNodeDef(nodeType, nodeData, app) {
1577
+ this._addExtraNodeContextMenu(nodeType, app);
1578
+ },
1579
+
1580
+ _addExtraNodeContextMenu(node, app) {
1581
+ const origGetExtraMenuOptions = node.prototype.getExtraMenuOptions;
1582
+ node.prototype.cm_menu_added = true;
1583
+ node.prototype.getExtraMenuOptions = function (_, options) {
1584
+ origGetExtraMenuOptions?.apply?.(this, arguments);
1585
+
1586
+ if (node.category.startsWith('group nodes>')) {
1587
+ options.push({
1588
+ content: "Save As Component",
1589
+ callback: (obj) => {
1590
+ if (!ComponentBuilderDialog.instance) {
1591
+ ComponentBuilderDialog.instance = new ComponentBuilderDialog();
1592
+ }
1593
+ ComponentBuilderDialog.instance.target_node = node;
1594
+ ComponentBuilderDialog.instance.show();
1595
+ }
1596
+ }, null);
1597
+ }
1598
+
1599
+ if (isOutputNode(node)) {
1600
+ const { potential_outputs } = getPotentialOutputsAndOutputNodes([this]);
1601
+ const hasOutput = potential_outputs.length > 0;
1602
+
1603
+ // Check if the previous menu option is `null`. If it's not,
1604
+ // then we need to add a `null` as a separator.
1605
+ if (options[options.length - 1] !== null) {
1606
+ options.push(null);
1607
+ }
1608
+
1609
+ options.push({
1610
+ content: "🏞️ Share Output",
1611
+ disabled: !hasOutput,
1612
+ callback: (obj) => {
1613
+ if (!ShareDialog.instance) {
1614
+ ShareDialog.instance = new ShareDialog();
1615
+ }
1616
+ const shareButton = document.getElementById("shareButton");
1617
+ if (shareButton) {
1618
+ const currentNode = this;
1619
+ if (!OpenArtShareDialog.instance) {
1620
+ OpenArtShareDialog.instance = new OpenArtShareDialog();
1621
+ }
1622
+ OpenArtShareDialog.instance.selectedNodeId = currentNode.id;
1623
+ if (!ShareDialog.instance) {
1624
+ ShareDialog.instance = new ShareDialog(share_option);
1625
+ }
1626
+ ShareDialog.instance.selectedNodeId = currentNode.id;
1627
+ shareButton.click();
1628
+ }
1629
+ }
1630
+ }, null);
1631
+ }
1632
+ }
1633
+ },
1634
+ });
ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-share-common.js ADDED
@@ -0,0 +1,1102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { api } from "../../scripts/api.js";
2
+ import { app } from "../../scripts/app.js";
3
+ import { $el, ComfyDialog } from "../../scripts/ui.js";
4
+ import { CopusShareDialog } from "./comfyui-share-copus.js";
5
+ import { OpenArtShareDialog } from "./comfyui-share-openart.js";
6
+ import { YouMLShareDialog } from "./comfyui-share-youml.js";
7
+ import { customAlert } from "./common.js";
8
+
9
+ export const SUPPORTED_OUTPUT_NODE_TYPES = [
10
+ "PreviewImage",
11
+ "SaveImage",
12
+ "VHS_VideoCombine",
13
+ "ADE_AnimateDiffCombine",
14
+ "SaveAnimatedWEBP",
15
+ "CR Image Output"
16
+ ]
17
+
18
+ var docStyle = document.createElement('style');
19
+ docStyle.innerHTML = `
20
+ .cm-menu-container {
21
+ column-gap: 20px;
22
+ display: flex;
23
+ flex-wrap: wrap;
24
+ justify-content: center;
25
+ }
26
+
27
+ .cm-menu-column {
28
+ display: flex;
29
+ flex-direction: column;
30
+ }
31
+
32
+ .cm-title {
33
+ padding: 10px 10px 0 10p;
34
+ background-color: black;
35
+ text-align: center;
36
+ height: 45px;
37
+ }
38
+ `;
39
+ document.head.appendChild(docStyle);
40
+
41
+ export function getPotentialOutputsAndOutputNodes(nodes) {
42
+ const potential_outputs = [];
43
+ const potential_output_nodes = [];
44
+
45
+ // iterate over the array of nodes to find the ones that are marked as SaveImage
46
+ // TODO: Add support for AnimateDiffCombine, etc. nodes that save videos/gifs, etc.
47
+ for (let i = 0; i < nodes.length; i++) {
48
+ const node = nodes[i];
49
+ if (!SUPPORTED_OUTPUT_NODE_TYPES.includes(node.type)) {
50
+ continue;
51
+ }
52
+
53
+ if (node.type === "SaveImage" || node.type === "CR Image Output") {
54
+ // check if node has an 'images' array property
55
+ if (node.hasOwnProperty("images") && Array.isArray(node.images)) {
56
+ // iterate over the images array and add each image to the potential_outputs array
57
+ for (let j = 0; j < node.images.length; j++) {
58
+ potential_output_nodes.push(node);
59
+ potential_outputs.push({ "type": "image", "image": node.images[j], "title": node.title, "node_id": node.id });
60
+ }
61
+ }
62
+ }
63
+ else if (node.type === "PreviewImage") {
64
+ // check if node has an 'images' array property
65
+ if (node.hasOwnProperty("images") && Array.isArray(node.images)) {
66
+ // iterate over the images array and add each image to the potential_outputs array
67
+ for (let j = 0; j < node.images.length; j++) {
68
+ potential_output_nodes.push(node);
69
+ potential_outputs.push({ "type": "image", "image": node.images[j], "title": node.title, "node_id": node.id });
70
+ }
71
+ }
72
+ }
73
+ else if (node.type === "VHS_VideoCombine") {
74
+ // check if node has a 'widgets' array property, with type 'image'
75
+ if (node.hasOwnProperty("widgets") && Array.isArray(node.widgets)) {
76
+ // iterate over the widgets array and add each image to the potential_outputs array
77
+ for (let j = 0; j < node.widgets.length; j++) {
78
+ if (node.widgets[j].type === "image") {
79
+ const widgetValue = node.widgets[j].value;
80
+ const parsedURLVals = parseURLPath(widgetValue);
81
+
82
+ // ensure that the parsedURLVals have 'filename', 'subfolder', 'type', and 'format' properties
83
+ if (parsedURLVals.hasOwnProperty("filename") && parsedURLVals.hasOwnProperty("subfolder") && parsedURLVals.hasOwnProperty("type") && parsedURLVals.hasOwnProperty("format")) {
84
+ if (parsedURLVals.type !== "output") {
85
+ // TODO
86
+ }
87
+ potential_output_nodes.push(node);
88
+ potential_outputs.push({ "type": "output", 'title': node.title, "node_id": node.id , "output": { "filename": parsedURLVals.filename, "subfolder": parsedURLVals.subfolder, "value": widgetValue, "format": parsedURLVals.format } });
89
+ }
90
+ } else if (node.widgets[j].type === "preview") {
91
+ const widgetValue = node.widgets[j].value;
92
+ const parsedURLVals = widgetValue.params;
93
+
94
+ if(!parsedURLVals.format?.startsWith('image')) {
95
+ // video isn't supported format
96
+ continue;
97
+ }
98
+
99
+ // ensure that the parsedURLVals have 'filename', 'subfolder', 'type', and 'format' properties
100
+ if (parsedURLVals.hasOwnProperty("filename") && parsedURLVals.hasOwnProperty("subfolder") && parsedURLVals.hasOwnProperty("type") && parsedURLVals.hasOwnProperty("format")) {
101
+ if (parsedURLVals.type !== "output") {
102
+ // TODO
103
+ }
104
+ potential_output_nodes.push(node);
105
+ potential_outputs.push({ "type": "output", 'title': node.title, "node_id": node.id , "output": { "filename": parsedURLVals.filename, "subfolder": parsedURLVals.subfolder, "value": `/view?filename=${parsedURLVals.filename}&subfolder=${parsedURLVals.subfolder}&type=${parsedURLVals.type}&format=${parsedURLVals.format}`, "format": parsedURLVals.format } });
106
+ }
107
+ }
108
+ }
109
+ }
110
+ }
111
+ else if (node.type === "ADE_AnimateDiffCombine") {
112
+ // check if node has a 'widgets' array property, with type 'image'
113
+ if (node.hasOwnProperty("widgets") && Array.isArray(node.widgets)) {
114
+ // iterate over the widgets array and add each image to the potential_outputs array
115
+ for (let j = 0; j < node.widgets.length; j++) {
116
+ if (node.widgets[j].type === "image") {
117
+ const widgetValue = node.widgets[j].value;
118
+ const parsedURLVals = parseURLPath(widgetValue);
119
+ // ensure that the parsedURLVals have 'filename', 'subfolder', 'type', and 'format' properties
120
+ if (parsedURLVals.hasOwnProperty("filename") && parsedURLVals.hasOwnProperty("subfolder") && parsedURLVals.hasOwnProperty("type") && parsedURLVals.hasOwnProperty("format")) {
121
+ if (parsedURLVals.type !== "output") {
122
+ // TODO
123
+ continue;
124
+ }
125
+ potential_output_nodes.push(node);
126
+ potential_outputs.push({ "type": "output", 'title': node.title, "output": { "filename": parsedURLVals.filename, "subfolder": parsedURLVals.subfolder, "type": parsedURLVals.type, "value": widgetValue, "format": parsedURLVals.format } });
127
+ }
128
+ }
129
+ }
130
+ }
131
+ }
132
+ else if (node.type === "SaveAnimatedWEBP") {
133
+ // check if node has an 'images' array property
134
+ if (node.hasOwnProperty("images") && Array.isArray(node.images)) {
135
+ // iterate over the images array and add each image to the potential_outputs array
136
+ for (let j = 0; j < node.images.length; j++) {
137
+ potential_output_nodes.push(node);
138
+ potential_outputs.push({ "type": "image", "image": node.images[j], "title": node.title });
139
+ }
140
+ }
141
+ }
142
+ }
143
+
144
+ // Note: make sure that two arrays are the same length
145
+ return { potential_outputs, potential_output_nodes };
146
+ }
147
+
148
+
149
+ export function parseURLPath(urlPath) {
150
+ // Extract the query string from the URL path
151
+ var queryString = urlPath.split('?')[1];
152
+
153
+ // Use the URLSearchParams API to parse the query string
154
+ var params = new URLSearchParams(queryString);
155
+
156
+ // Create an object to store the parsed parameters
157
+ var parsedParams = {};
158
+
159
+ // Iterate over each parameter and add it to the object
160
+ for (var pair of params.entries()) {
161
+ parsedParams[pair[0]] = pair[1];
162
+ }
163
+
164
+ // Return the object with the parsed parameters
165
+ return parsedParams;
166
+ }
167
+
168
+
169
+ export const shareToEsheep= () => {
170
+ app.graphToPrompt()
171
+ .then(prompt => {
172
+ const nodes = app.graph._nodes
173
+ const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
174
+ const workflow = prompt['workflow']
175
+ api.fetchApi(`/manager/set_esheep_workflow_and_images`, {
176
+ method: 'POST',
177
+ headers: { 'Content-Type': 'application/json' },
178
+ body: JSON.stringify({
179
+ workflow: workflow,
180
+ images: potential_outputs
181
+ })
182
+ }).then(response => {
183
+ var domain = window.location.hostname;
184
+ var port = window.location.port;
185
+ port = port || (window.location.protocol === 'http:' ? '80' : window.location.protocol === 'https:' ? '443' : '');
186
+ var full_domin = domain + ':' + port
187
+ window.open('https://www.esheep.com/app/workflow_upload?from_local='+ full_domin, '_blank');
188
+ });
189
+ })
190
+ }
191
+
192
+ export const showCopusShareDialog = () => {
193
+ if (!CopusShareDialog.instance) {
194
+ CopusShareDialog.instance = new CopusShareDialog();
195
+ }
196
+
197
+ return app.graphToPrompt()
198
+ .then(prompt => {
199
+ return app.graph._nodes;
200
+ })
201
+ .then(nodes => {
202
+ const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
203
+ CopusShareDialog.instance.show({ potential_outputs, potential_output_nodes});
204
+ })
205
+ }
206
+
207
+ export const showOpenArtShareDialog = () => {
208
+ if (!OpenArtShareDialog.instance) {
209
+ OpenArtShareDialog.instance = new OpenArtShareDialog();
210
+ }
211
+
212
+ return app.graphToPrompt()
213
+ .then(prompt => {
214
+ // console.log({ prompt })
215
+ return app.graph._nodes;
216
+ })
217
+ .then(nodes => {
218
+ const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
219
+ OpenArtShareDialog.instance.show({ potential_outputs, potential_output_nodes});
220
+ })
221
+ }
222
+
223
+
224
+ export const showYouMLShareDialog = () => {
225
+ if (!YouMLShareDialog.instance) {
226
+ YouMLShareDialog.instance = new YouMLShareDialog();
227
+ }
228
+
229
+ return app.graphToPrompt()
230
+ .then(prompt => {
231
+ return app.graph._nodes;
232
+ })
233
+ .then(nodes => {
234
+ const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
235
+ YouMLShareDialog.instance.show(potential_outputs, potential_output_nodes);
236
+ })
237
+ }
238
+
239
+
240
+ export const showShareDialog = async (share_option) => {
241
+ if (!ShareDialog.instance) {
242
+ ShareDialog.instance = new ShareDialog(share_option);
243
+ }
244
+ return app.graphToPrompt()
245
+ .then(prompt => {
246
+ // console.log({ prompt })
247
+ return app.graph._nodes;
248
+ })
249
+ .then(nodes => {
250
+ // console.log({ nodes });
251
+ const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
252
+ if (potential_outputs.length === 0) {
253
+ if (potential_output_nodes.length === 0) {
254
+ // todo: add support for other output node types (animatediff combine, etc.)
255
+ const supported_nodes_string = SUPPORTED_OUTPUT_NODE_TYPES.join(", ");
256
+ customAlert(`No supported output node found (${supported_nodes_string}). To share this workflow, please add an output node to your graph and re-run your prompt.`);
257
+ } else {
258
+ customAlert("To share this, first run a prompt. Once it's done, click 'Share'.\n\nNOTE: Images of the Share target can only be selected in the PreviewImage, SaveImage, and VHS_VideoCombine nodes. In the case of VHS_VideoCombine, only the image/gif and image/webp formats are supported.");
259
+ }
260
+ return false;
261
+ }
262
+ ShareDialog.instance.show({ potential_outputs, potential_output_nodes, share_option });
263
+ return true;
264
+ });
265
+ }
266
+
267
+ export class ShareDialogChooser extends ComfyDialog {
268
+ static instance = null;
269
+ constructor() {
270
+ super();
271
+ this.element = $el("div.comfy-modal", {
272
+ parent: document.body, style: {
273
+ 'overflow-y': "auto",
274
+ }
275
+ },
276
+ [$el("div.comfy-modal-content",
277
+ {},
278
+ [...this.createButtons()]),
279
+ ]);
280
+ this.selectedNodeId = null;
281
+ }
282
+ createButtons() {
283
+ const buttons = [
284
+ {
285
+ key: "openart",
286
+ textContent: "OpenArt AI",
287
+ website: "https://openart.ai/workflows/",
288
+ description: "Share ComfyUI workflows and art on OpenArt.ai",
289
+ onclick: () => {
290
+ showOpenArtShareDialog();
291
+ this.close();
292
+ }
293
+ },
294
+ {
295
+ key: "youml",
296
+ textContent: "YouML",
297
+ website: "https://youml.com",
298
+ description: "Share your workflow or transform it into an interactive app on YouML.com",
299
+ onclick: () => {
300
+ showYouMLShareDialog();
301
+ this.close();
302
+ }
303
+ },
304
+ {
305
+ key: "matrix",
306
+ textContent: "Matrix Server",
307
+ website: "https://app.element.io/#/room/%23comfyui_space%3Amatrix.org",
308
+ description: "Share your art on the official ComfyUI matrix server",
309
+ onclick: async () => {
310
+ showShareDialog('matrix').then((suc) => {
311
+ suc && this.close();
312
+ })
313
+ }
314
+ },
315
+ {
316
+ key: "comfyworkflows",
317
+ textContent: "ComfyWorkflows",
318
+ website: "https://comfyworkflows.com",
319
+ description: "Share & browse thousands of ComfyUI workflows and art 🎨<br/><br/><a style='color:var(--input-text);' href='https://comfyworkflows.com' target='_blank'>ComfyWorkflows.com</a>",
320
+ onclick: () => {
321
+ showShareDialog('comfyworkflows').then((suc) => {
322
+ suc && this.close();
323
+ })
324
+ }
325
+ },
326
+ {
327
+ key: "esheep",
328
+ textContent: "eSheep",
329
+ website: "https://www.esheep.com",
330
+ description: "Share & download thousands of ComfyUI workflows on <a style='color:var(--input-text);' href='https://www.esheep.com' target='_blank'>esheep.com</a>",
331
+ onclick: () => {
332
+ shareToEsheep();
333
+ this.close();
334
+ }
335
+ },
336
+ {
337
+ key: "Copus",
338
+ textContent: "Copus",
339
+ website: "https://www.copus.io",
340
+ description: "🔴 Earn simple. Get paid from your ComfyUI workflows—no revenue sharing. Ever.",
341
+ onclick: () => {
342
+ showCopusShareDialog();
343
+ this.close();
344
+ }
345
+ },
346
+ ];
347
+
348
+ function createShareButtonsWithDescriptions() {
349
+ // Responsive container
350
+ const container = $el("div", {
351
+ style: {
352
+ display: "flex",
353
+ 'flex-wrap': 'wrap',
354
+ 'justify-content': 'space-around',
355
+ 'padding': '10px',
356
+ }
357
+ });
358
+
359
+ buttons.forEach(b => {
360
+ const button = $el("button",
361
+ {
362
+ type: "button",
363
+ textContent: b.textContent,
364
+ onclick: b.onclick,
365
+ style: {
366
+ 'width': '25%',
367
+ 'minWidth': '200px',
368
+ 'background-color': b.backgroundColor || '',
369
+ 'border-radius': '5px',
370
+ 'cursor': 'pointer',
371
+ 'padding': '5px 5px',
372
+ 'margin-bottom': '5px',
373
+ 'transition': 'background-color 0.3s',
374
+ 'position':'relative'
375
+ }
376
+ },
377
+ [
378
+ $el("span", { style: {
379
+ } }),
380
+ ]
381
+ );
382
+ button.addEventListener('mouseover', () => {
383
+ button.style.backgroundColor = '#007BFF'; // Change color on hover
384
+ });
385
+ button.addEventListener('mouseout', () => {
386
+ button.style.backgroundColor = b.backgroundColor || '';
387
+ });
388
+
389
+ const description = $el("p", {
390
+ innerHTML: b.description,
391
+ style: {
392
+ 'text-align': 'left',
393
+ color: 'var(--input-text)',
394
+ 'font-size': '14px',
395
+ 'margin-bottom': '0',
396
+ },
397
+ });
398
+
399
+ const copus_ui =$el("div", { style: {
400
+ 'position': 'absolute',
401
+ 'height': '100%',
402
+ 'left': '-25px',
403
+ 'top': '-26px',
404
+ 'width': '100%',
405
+ 'z-index':'-1',
406
+ 'background':'url("https://static.copus.io/images/client/202412/test/f28ac6ef8f4c6f3d5d50856a272ed02c.png")',
407
+ 'background-repeat': 'no-repeat',
408
+ } });
409
+ const copus_ui_bottom =$el("div", { style: {
410
+ 'position': 'absolute',
411
+ 'height': '100%',
412
+ 'left': '25px',
413
+ 'bottom': '-26px',
414
+ 'width': '100%',
415
+ 'transform':'scale(-1, -1)',
416
+ 'z-index':'-1',
417
+ 'background':'url("https://static.copus.io/images/client/202412/test/f28ac6ef8f4c6f3d5d50856a272ed02c.png")',
418
+ 'background-repeat': 'no-repeat',
419
+ } });
420
+
421
+ const websiteLink = $el("a", {
422
+ textContent: "🌐 Website",
423
+ href: b.website,
424
+ target: "_blank",
425
+ style: {
426
+ color: 'var(--input-text)',
427
+ 'margin-left': '10px',
428
+ 'font-size': '12px',
429
+ 'text-decoration': 'none',
430
+ 'align-self': 'center',
431
+ },
432
+ });
433
+
434
+ // Add highlight to the website link
435
+ websiteLink.addEventListener('mouseover', () => {
436
+ websiteLink.style.opacity = '0.7';
437
+ });
438
+
439
+ websiteLink.addEventListener('mouseout', () => {
440
+ websiteLink.style.opacity = '1';
441
+ });
442
+
443
+ const buttonLinkContainer = $el("div", {
444
+ style: {
445
+ display: 'flex',
446
+ 'align-items': 'center',
447
+ 'margin-bottom': '10px',
448
+ }
449
+ }, [button, websiteLink]);
450
+ const column = $el("div", {
451
+ style: {
452
+ 'flex-basis': '100%',
453
+ 'margin': '10px',
454
+ 'padding': '10px 20px',
455
+ 'border': '1px solid #ddd',
456
+ 'border-radius': '5px',
457
+ 'box-shadow': '0 2px 4px rgba(0, 0, 0, 0.1)',
458
+ 'position':'relative'
459
+ }
460
+ }, [buttonLinkContainer, description
461
+ ,
462
+ b.key ==='Copus' ?
463
+ copus_ui
464
+ :'',
465
+ b.key ==='Copus' ?
466
+ copus_ui_bottom
467
+ :'',
468
+ ]);
469
+
470
+ container.appendChild(column);
471
+ });
472
+
473
+ return container;
474
+ }
475
+
476
+ return [
477
+ $el("p", {
478
+ textContent: 'Choose a platform to share your workflow',
479
+ style: {
480
+ 'text-align': 'center',
481
+ 'color': 'var(--input-text)',
482
+ 'font-size': '18px',
483
+ 'margin-bottom': '10px',
484
+ },
485
+ }
486
+ ),
487
+
488
+ $el("div.cm-menu-container", {
489
+ id: "comfyui-share-container"
490
+ }, [
491
+ $el("div.cm-menu-column", [
492
+ createShareButtonsWithDescriptions(),
493
+ $el("br", {}, []),
494
+ ]),
495
+ ]),
496
+ $el("div.cm-menu-container", {
497
+ id: "comfyui-share-container"
498
+ }, [
499
+ $el("button", {
500
+ type: "button",
501
+ style: {
502
+ margin: "0 25px",
503
+ width: "100%",
504
+ },
505
+ textContent: "Close",
506
+ onclick: () => {
507
+ this.close()
508
+ }
509
+ }),
510
+ $el("br", {}, []),
511
+ ]),
512
+ ];
513
+ }
514
+ show() {
515
+ this.element.style.display = "block";
516
+ this.element.style.zIndex = 1099;
517
+ }
518
+ }
519
+ export class ShareDialog extends ComfyDialog {
520
+ static instance = null;
521
+ static matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
522
+ static cw_sharekey = "";
523
+
524
+ constructor(share_option) {
525
+ super();
526
+ this.share_option = share_option;
527
+ this.element = $el("div.comfy-modal", {
528
+ parent: document.body, style: {
529
+ 'overflow-y': "auto",
530
+ }
531
+ },
532
+ [$el("div.comfy-modal-content",
533
+ {},
534
+ [...this.createButtons()]),
535
+ ]);
536
+ this.selectedOutputIndex = 0;
537
+ }
538
+
539
+ createButtons() {
540
+ this.radio_buttons = $el("div", {
541
+ id: "selectOutputImages",
542
+ }, []);
543
+
544
+ this.is_nsfw_checkbox = $el("input", { type: 'checkbox', id: "is_nsfw" }, [])
545
+ const is_nsfw_checkbox_text = $el("label", {
546
+ }, [" Is this NSFW?"])
547
+ this.is_nsfw_checkbox.style.color = "var(--fg-color)";
548
+ this.is_nsfw_checkbox.checked = false;
549
+
550
+ this.matrix_destination_checkbox = $el("input", { type: 'checkbox', id: "matrix_destination" }, [])
551
+ const matrix_destination_checkbox_text = $el("label", {}, [" ComfyUI Matrix server"])
552
+ this.matrix_destination_checkbox.style.color = "var(--fg-color)";
553
+ this.matrix_destination_checkbox.checked = this.share_option === 'matrix'; //true;
554
+
555
+ this.comfyworkflows_destination_checkbox = $el("input", { type: 'checkbox', id: "comfyworkflows_destination" }, [])
556
+ const comfyworkflows_destination_checkbox_text = $el("label", {}, [" ComfyWorkflows.com"])
557
+ this.comfyworkflows_destination_checkbox.style.color = "var(--fg-color)";
558
+ this.comfyworkflows_destination_checkbox.checked = this.share_option !== 'matrix';
559
+
560
+ this.matrix_homeserver_input = $el("input", { type: 'text', id: "matrix_homeserver", placeholder: "matrix.org", value: ShareDialog.matrix_auth.homeserver || 'matrix.org' }, []);
561
+ this.matrix_username_input = $el("input", { type: 'text', placeholder: "Username", value: ShareDialog.matrix_auth.username || '' }, []);
562
+ this.matrix_password_input = $el("input", { type: 'password', placeholder: "Password", value: ShareDialog.matrix_auth.password || '' }, []);
563
+
564
+ this.cw_sharekey_input = $el("input", { type: 'text', placeholder: "Share key (found on your profile page)", value: ShareDialog.cw_sharekey || '' }, []);
565
+ this.cw_sharekey_input.style.width = "100%";
566
+
567
+ this.credits_input = $el("input", {
568
+ type: "text",
569
+ placeholder: "This will be used to give credits",
570
+ required: false,
571
+ }, []);
572
+
573
+ this.title_input = $el("input", {
574
+ type: "text",
575
+ placeholder: "ex: My awesome art",
576
+ required: false
577
+ }, []);
578
+
579
+ this.description_input = $el("textarea", {
580
+ placeholder: "ex: Trying out a new workflow... ",
581
+ required: false,
582
+ }, []);
583
+
584
+ this.share_button = $el("button", {
585
+ type: "submit",
586
+ textContent: "Share",
587
+ style: {
588
+ backgroundColor: "blue"
589
+ }
590
+ }, []);
591
+
592
+ this.final_message = $el("div", {
593
+ style: {
594
+ color: "white",
595
+ textAlign: "center",
596
+ // marginTop: "10px",
597
+ // backgroundColor: "black",
598
+ padding: "10px",
599
+ }
600
+ }, []);
601
+
602
+ this.share_finalmessage_container = $el("div.cm-menu-container", {
603
+ id: "comfyui-share-finalmessage-container",
604
+ style: {
605
+ display: "none",
606
+ }
607
+ }, [
608
+ $el("div.cm-menu-column", [
609
+ this.final_message,
610
+ $el("button", {
611
+ type: "button",
612
+ textContent: "Close",
613
+ onclick: () => {
614
+ // Reset state
615
+ this.matrix_destination_checkbox.checked = this.share_option === 'matrix';
616
+ this.comfyworkflows_destination_checkbox.checked = this.share_option !== 'matrix';
617
+ this.share_button.textContent = "Share";
618
+ this.share_button.style.display = "inline-block";
619
+ this.final_message.innerHTML = "";
620
+ this.final_message.style.color = "white";
621
+ this.credits_input.value = "";
622
+ this.title_input.value = "";
623
+ this.description_input.value = "";
624
+ this.is_nsfw_checkbox.checked = false;
625
+ this.selectedOutputIndex = 0;
626
+
627
+ // hide the final message
628
+ this.share_finalmessage_container.style.display = "none";
629
+
630
+ // show the share container
631
+ this.share_container.style.display = "flex";
632
+
633
+ this.close()
634
+ }
635
+ }),
636
+ ])
637
+ ]);
638
+ this.share_container = $el("div.cm-menu-container", {
639
+ id: "comfyui-share-container"
640
+ }, [
641
+ $el("div.cm-menu-column", [
642
+ $el("details", {
643
+ style: {
644
+ border: "1px solid #999",
645
+ padding: "5px",
646
+ borderRadius: "5px",
647
+ backgroundColor: "#222"
648
+ }
649
+ }, [
650
+ $el("summary", {
651
+ style: {
652
+ color: "white",
653
+ cursor: "pointer",
654
+ }
655
+ }, [`Matrix account`]),
656
+ $el("div", {
657
+ style: {
658
+ display: "flex",
659
+ flexDirection: "row",
660
+ }
661
+ }, [
662
+ $el("div", {
663
+ textContent: "Homeserver",
664
+ style: {
665
+ marginRight: "10px",
666
+ }
667
+ }, []),
668
+ this.matrix_homeserver_input,
669
+ ]),
670
+
671
+ $el("div", {
672
+ style: {
673
+ display: "flex",
674
+ flexDirection: "row",
675
+ }
676
+ }, [
677
+ $el("div", {
678
+ textContent: "Username",
679
+ style: {
680
+ marginRight: "10px",
681
+ }
682
+ }, []),
683
+ this.matrix_username_input,
684
+ ]),
685
+
686
+ $el("div", {
687
+ style: {
688
+ display: "flex",
689
+ flexDirection: "row",
690
+ }
691
+ }, [
692
+ $el("div", {
693
+ textContent: "Password",
694
+ style: {
695
+ marginRight: "10px",
696
+ }
697
+ }, []),
698
+ this.matrix_password_input,
699
+ ]),
700
+
701
+ ]),
702
+ $el("details", {
703
+ style: {
704
+ border: "1px solid #999",
705
+ marginTop: "10px",
706
+ padding: "5px",
707
+ borderRadius: "5px",
708
+ backgroundColor: "#222"
709
+ },
710
+ }, [
711
+ $el("summary", {
712
+ style: {
713
+ color: "white",
714
+ cursor: "pointer",
715
+ }
716
+ }, [`Comfyworkflows.com account`]),
717
+ $el("h4", {
718
+ textContent: "Share key (found on your profile page)",
719
+ }, []),
720
+ $el("p", { size: 3, color: "white" }, ["If provided, your art will be saved to your account. Otherwise, it will be shared anonymously."]),
721
+ this.cw_sharekey_input,
722
+ ]),
723
+
724
+ $el("div", {}, [
725
+ $el("p", {
726
+ size: 3, color: "white", style: {
727
+ color: 'var(--input-text)'
728
+ }
729
+ }, [`Select where to share your art:`]),
730
+ this.matrix_destination_checkbox,
731
+ matrix_destination_checkbox_text,
732
+ $el("br", {}, []),
733
+ this.comfyworkflows_destination_checkbox,
734
+ comfyworkflows_destination_checkbox_text,
735
+ ]),
736
+
737
+ $el("h4", {
738
+ textContent: "Credits (optional)",
739
+ size: 3,
740
+ color: "white",
741
+ style: {
742
+ color: 'var(--input-text)'
743
+ }
744
+ }, []),
745
+ this.credits_input,
746
+ // $el("br", {}, []),
747
+
748
+ $el("h4", {
749
+ textContent: "Title (optional)",
750
+ size: 3,
751
+ color: "white",
752
+ style: {
753
+ color: 'var(--input-text)'
754
+ }
755
+ }, []),
756
+ this.title_input,
757
+ // $el("br", {}, []),
758
+
759
+ $el("h4", {
760
+ textContent: "Description (optional)",
761
+ size: 3,
762
+ color: "white",
763
+ style: {
764
+ color: 'var(--input-text)'
765
+ }
766
+ }, []),
767
+ this.description_input,
768
+ $el("br", {}, []),
769
+
770
+ $el("div", {}, [this.is_nsfw_checkbox, is_nsfw_checkbox_text]),
771
+ // $el("br", {}, []),
772
+
773
+ // this.final_message,
774
+ // $el("br", {}, []),
775
+ ]),
776
+ $el("div.cm-menu-column", [
777
+ this.radio_buttons,
778
+ $el("br", {}, []),
779
+
780
+ this.share_button,
781
+
782
+ $el("button", {
783
+ type: "button",
784
+ textContent: "Close",
785
+ onclick: () => {
786
+ // Reset state
787
+ this.matrix_destination_checkbox.checked = this.share_option === 'matrix';
788
+ this.comfyworkflows_destination_checkbox.checked = this.share_option !== 'matrix';
789
+ this.share_button.textContent = "Share";
790
+ this.share_button.style.display = "inline-block";
791
+ this.final_message.innerHTML = "";
792
+ this.final_message.style.color = "white";
793
+ this.credits_input.value = "";
794
+ this.title_input.value = "";
795
+ this.description_input.value = "";
796
+ this.is_nsfw_checkbox.checked = false;
797
+ this.selectedOutputIndex = 0;
798
+
799
+ // hide the final message
800
+ this.share_finalmessage_container.style.display = "none";
801
+
802
+ // show the share container
803
+ this.share_container.style.display = "flex";
804
+
805
+ this.close()
806
+ }
807
+ }),
808
+ $el("br", {}, []),
809
+ ]),
810
+ ]);
811
+
812
+ // get the user's existing matrix auth and share key
813
+ ShareDialog.matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
814
+ try {
815
+ api.fetchApi(`/manager/get_matrix_auth`)
816
+ .then(response => response.json())
817
+ .then(data => {
818
+ ShareDialog.matrix_auth = data;
819
+ this.matrix_homeserver_input.value = ShareDialog.matrix_auth.homeserver;
820
+ this.matrix_username_input.value = ShareDialog.matrix_auth.username;
821
+ this.matrix_password_input.value = ShareDialog.matrix_auth.password;
822
+ })
823
+ .catch(error => {
824
+ // console.log(error);
825
+ });
826
+ } catch (error) {
827
+ // console.log(error);
828
+ }
829
+
830
+ // get the user's existing comfyworkflows share key
831
+ ShareDialog.cw_sharekey = "";
832
+ try {
833
+ // console.log("Fetching comfyworkflows share key")
834
+ api.fetchApi(`/manager/get_comfyworkflows_auth`)
835
+ .then(response => response.json())
836
+ .then(data => {
837
+ ShareDialog.cw_sharekey = data.comfyworkflows_sharekey;
838
+ this.cw_sharekey_input.value = ShareDialog.cw_sharekey;
839
+ })
840
+ .catch(error => {
841
+ // console.log(error);
842
+ });
843
+ } catch (error) {
844
+ // console.log(error);
845
+ }
846
+
847
+ this.share_button.onclick = async () => {
848
+ const prompt = await app.graphToPrompt();
849
+ const nodes = app.graph._nodes;
850
+
851
+ // console.log({ prompt, nodes });
852
+
853
+ const destinations = [];
854
+ if (this.matrix_destination_checkbox.checked) {
855
+ destinations.push("matrix");
856
+ }
857
+ if (this.comfyworkflows_destination_checkbox.checked) {
858
+ destinations.push("comfyworkflows");
859
+ }
860
+
861
+ // if destinations includes matrix, make an api call to /manager/check_matrix to ensure that the user has configured their matrix settings
862
+ if (destinations.includes("matrix")) {
863
+ let definedMatrixAuth = !!this.matrix_homeserver_input.value && !!this.matrix_username_input.value && !!this.matrix_password_input.value;
864
+ if (!definedMatrixAuth) {
865
+ customAlert("Please set your Matrix account details.");
866
+ return;
867
+ }
868
+ }
869
+
870
+ if (destinations.includes("comfyworkflows") && !this.cw_sharekey_input.value && false) { //!confirm("You have NOT set your ComfyWorkflows.com share key. Your art will NOT be connected to your account (it will be shared anonymously). Continue?")) {
871
+ return;
872
+ }
873
+
874
+ const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
875
+
876
+ // console.log({ potential_outputs, potential_output_nodes })
877
+
878
+ if (potential_outputs.length === 0) {
879
+ if (potential_output_nodes.length === 0) {
880
+ // todo: add support for other output node types (animatediff combine, etc.)
881
+ const supported_nodes_string = SUPPORTED_OUTPUT_NODE_TYPES.join(", ");
882
+ customAlert(`No supported output node found (${supported_nodes_string}). To share this workflow, please add an output node to your graph and re-run your prompt.`);
883
+ } else {
884
+ customAlert("To share this, first run a prompt. Once it's done, click 'Share'.\n\nNOTE: Images of the Share target can only be selected in the PreviewImage, SaveImage, and VHS_VideoCombine nodes. In the case of VHS_VideoCombine, only the image/gif and image/webp formats are supported.");
885
+ }
886
+ this.selectedOutputIndex = 0;
887
+ this.close();
888
+ return;
889
+ }
890
+
891
+ // Change the text of the share button to "Sharing..." to indicate that the share process has started
892
+ this.share_button.textContent = "Sharing...";
893
+
894
+ const response = await api.fetchApi(`/manager/share`, {
895
+ method: 'POST',
896
+ headers: { 'Content-Type': 'application/json' },
897
+ body: JSON.stringify({
898
+ matrix_auth: {
899
+ homeserver: this.matrix_homeserver_input.value,
900
+ username: this.matrix_username_input.value,
901
+ password: this.matrix_password_input.value,
902
+ },
903
+ cw_auth: {
904
+ cw_sharekey: this.cw_sharekey_input.value,
905
+ },
906
+ share_destinations: destinations,
907
+ credits: this.credits_input.value,
908
+ title: this.title_input.value,
909
+ description: this.description_input.value,
910
+ is_nsfw: this.is_nsfw_checkbox.checked,
911
+ prompt,
912
+ potential_outputs,
913
+ selected_output_index: this.selectedOutputIndex,
914
+ // potential_output_nodes
915
+ })
916
+ });
917
+
918
+ if (response.status != 200) {
919
+ try {
920
+ const response_json = await response.json();
921
+ if (response_json.error) {
922
+ customAlert(response_json.error);
923
+ this.close();
924
+ return;
925
+ } else {
926
+ customAlert("Failed to share your art. Please try again.");
927
+ this.close();
928
+ return;
929
+ }
930
+ } catch (e) {
931
+ customAlert("Failed to share your art. Please try again.");
932
+ this.close();
933
+ return;
934
+ }
935
+ }
936
+
937
+ const response_json = await response.json();
938
+
939
+ if (response_json.comfyworkflows.url) {
940
+ this.final_message.innerHTML = "Your art has been shared: <a href='" + response_json.comfyworkflows.url + "' target='_blank'>" + response_json.comfyworkflows.url + "</a>";
941
+ if (response_json.matrix.success) {
942
+ this.final_message.innerHTML += "<br>Your art has been shared in the ComfyUI Matrix server's #share channel!";
943
+ }
944
+ } else {
945
+ if (response_json.matrix.success) {
946
+ this.final_message.innerHTML = "Your art has been shared in the ComfyUI Matrix server's #share channel!";
947
+ }
948
+ }
949
+
950
+ this.final_message.style.color = "green";
951
+
952
+ // hide #comfyui-share-container and show #comfyui-share-finalmessage-container
953
+ this.share_container.style.display = "none";
954
+ this.share_finalmessage_container.style.display = "block";
955
+
956
+ // hide the share button
957
+ this.share_button.textContent = "Shared!";
958
+ this.share_button.style.display = "none";
959
+ // this.close();
960
+ }
961
+
962
+ const res =
963
+ [
964
+ $el("tr.td", { width: "100%" }, [
965
+ $el("font", { size: 6, color: "white" }, [`Share your art`]),
966
+ ]),
967
+ $el("br", {}, []),
968
+
969
+ this.share_finalmessage_container,
970
+ this.share_container,
971
+ ];
972
+
973
+ res[0].style.padding = "10px 10px 10px 10px";
974
+ res[0].style.backgroundColor = "black"; //"linear-gradient(90deg, #00C9FF 0%, #92FE9D 100%)";
975
+ res[0].style.textAlign = "center";
976
+ res[0].style.height = "45px";
977
+ return res;
978
+ }
979
+
980
+ show({potential_outputs, potential_output_nodes, share_option}) {
981
+ // Sort `potential_output_nodes` by node ID to make the order always
982
+ // consistent, but we should also keep `potential_outputs` in the same
983
+ // order as `potential_output_nodes`.
984
+ const potential_output_to_order = {};
985
+ potential_output_nodes.forEach((node, index) => {
986
+ if (node.id in potential_output_to_order) {
987
+ potential_output_to_order[node.id][1].push(potential_outputs[index]);
988
+ } else {
989
+ potential_output_to_order[node.id] = [node, [potential_outputs[index]]];
990
+ }
991
+ })
992
+ // Sort the object `potential_output_to_order` by key (node ID)
993
+ const sorted_potential_output_to_order = Object.fromEntries(
994
+ Object.entries(potential_output_to_order).sort((a, b) => a[0].id - b[0].id)
995
+ );
996
+ const sorted_potential_outputs = []
997
+ const sorted_potential_output_nodes = []
998
+ for (const [key, value] of Object.entries(sorted_potential_output_to_order)) {
999
+ sorted_potential_output_nodes.push(value[0]);
1000
+ sorted_potential_outputs.push(...value[1]);
1001
+ }
1002
+ potential_output_nodes = sorted_potential_output_nodes;
1003
+ potential_outputs = sorted_potential_outputs;
1004
+
1005
+ // console.log({ potential_outputs, potential_output_nodes })
1006
+ this.radio_buttons.innerHTML = ""; // clear the radio buttons
1007
+ let is_radio_button_checked = false; // only check the first radio button if multiple images from the same node
1008
+ const new_radio_buttons = $el("div", {
1009
+ id: "selectOutput-Options",
1010
+ style: {
1011
+ 'overflow-y': 'scroll',
1012
+ 'max-height': '400px',
1013
+ }
1014
+ }, potential_outputs.map((output, index) => {
1015
+ const {node_id} = output;
1016
+ const radio_button = $el("input", { type: 'radio', name: "selectOutputImages", value: index, required: index === 0 }, [])
1017
+ let radio_button_img;
1018
+ if (output.type === "image" || output.type === "temp") {
1019
+ radio_button_img = $el("img", { src: `/view?filename=${output.image.filename}&subfolder=${output.image.subfolder}&type=${output.image.type}`, style: { width: "auto", height: "100px" } }, []);
1020
+ } else if (output.type === "output") {
1021
+ radio_button_img = $el("img", { src: output.output.value, style: { width: "auto", height: "100px" } }, []);
1022
+ } else {
1023
+ // unsupported output type
1024
+ // this should never happen
1025
+ // TODO
1026
+ radio_button_img = $el("img", { src: "", style: { width: "auto", height: "100px" } }, []);
1027
+ }
1028
+ const radio_button_text = $el("label", {
1029
+ // style: {
1030
+ // color: 'var(--input-text)'
1031
+ // }
1032
+ }, [output.title])
1033
+ radio_button.style.color = "var(--fg-color)";
1034
+
1035
+ // Make the radio button checked if it's the selected node,
1036
+ // otherwise make the first radio button checked.
1037
+ if (this.selectedNodeId) {
1038
+ if (this.selectedNodeId === node_id && !is_radio_button_checked) {
1039
+ radio_button.checked = true;
1040
+ is_radio_button_checked = true;
1041
+ }
1042
+ } else {
1043
+ radio_button.checked = index === 0;
1044
+ }
1045
+
1046
+ if (radio_button.checked) {
1047
+ this.selectedOutputIndex = index;
1048
+ }
1049
+
1050
+ radio_button.onchange = () => {
1051
+ this.selectedOutputIndex = parseInt(radio_button.value);
1052
+ };
1053
+
1054
+ return $el("div", {
1055
+ style: {
1056
+ display: "flex",
1057
+ 'align-items': 'center',
1058
+ 'justify-content': 'space-between',
1059
+ 'margin-bottom': '10px',
1060
+ }
1061
+ }, [radio_button, radio_button_text, radio_button_img]);
1062
+ }));
1063
+ const header = $el("h3", {
1064
+ textContent: "Select an image to share",
1065
+ size: 3,
1066
+ color: "white",
1067
+ style: {
1068
+ 'text-align': 'center',
1069
+ color: 'var(--input-text)',
1070
+ backgroundColor: 'black',
1071
+ padding: '10px',
1072
+ 'margin-top': '0px',
1073
+ }
1074
+ }, [
1075
+ $el("p", {
1076
+ textContent: "Scroll to see all outputs",
1077
+ size: 2,
1078
+ color: "white",
1079
+ style: {
1080
+ 'text-align': 'center',
1081
+ color: 'var(--input-text)',
1082
+ 'margin-bottom': '5px',
1083
+ 'font-style': 'italic',
1084
+ 'font-size': '12px',
1085
+ },
1086
+ }, [])
1087
+ ]);
1088
+ this.radio_buttons.appendChild(header);
1089
+ // this.radio_buttons.appendChild(subheader);
1090
+ this.radio_buttons.appendChild(new_radio_buttons);
1091
+ this.element.style.display = "block";
1092
+
1093
+ share_option = share_option || this.share_option;
1094
+ if (share_option === 'comfyworkflows') {
1095
+ this.matrix_destination_checkbox.checked = false;
1096
+ this.comfyworkflows_destination_checkbox.checked = true;
1097
+ } else {
1098
+ this.matrix_destination_checkbox.checked = true;
1099
+ this.comfyworkflows_destination_checkbox.checked = false;
1100
+ }
1101
+ }
1102
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-share-copus.js ADDED
@@ -0,0 +1,985 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../scripts/app.js";
2
+ import { $el, ComfyDialog } from "../../scripts/ui.js";
3
+ import { customAlert } from "./common.js";
4
+
5
+ const env = "prod";
6
+
7
+ let DEFAULT_HOMEPAGE_URL = "https://copus.io";
8
+
9
+ let API_ENDPOINT = "https://api.client.prod.copus.io";
10
+
11
+ if (env !== "prod") {
12
+ API_ENDPOINT = "https://api.test.copus.io";
13
+ DEFAULT_HOMEPAGE_URL = "https://test.copus.io";
14
+ }
15
+
16
+ const style = `
17
+ .copus-share-dialog a {
18
+ color: #f8f8f8;
19
+ }
20
+ .copus-share-dialog a:hover {
21
+ color: #007bff;
22
+ }
23
+ .output_label {
24
+ border: 5px solid transparent;
25
+ }
26
+ .output_label:hover {
27
+ border: 5px solid #59E8C6;
28
+ }
29
+ .output_label.checked {
30
+ border: 5px solid #59E8C6;
31
+ }
32
+ `;
33
+
34
+ // Shared component styles
35
+ const sectionStyle = {
36
+ marginBottom: 0,
37
+ padding: 0,
38
+ borderRadius: "8px",
39
+ boxShadow: "0 2px 4px rgba(0, 0, 0, 0.05)",
40
+ display: "flex",
41
+ flexDirection: "column",
42
+ justifyContent: "center",
43
+ position: "relative",
44
+ };
45
+
46
+ export class CopusShareDialog extends ComfyDialog {
47
+ static instance = null;
48
+
49
+ constructor() {
50
+ super();
51
+ $el("style", {
52
+ textContent: style,
53
+ parent: document.head,
54
+ });
55
+ this.element = $el(
56
+ "div.comfy-modal.copus-share-dialog",
57
+ {
58
+ parent: document.body,
59
+ style: {
60
+ "overflow-y": "auto",
61
+ },
62
+ },
63
+ [$el("div.comfy-modal-content", {}, [...this.createButtons()])]
64
+ );
65
+ this.selectedOutputIndex = 0;
66
+ this.selectedOutput_lock = 0;
67
+ this.selectedNodeId = null;
68
+ this.uploadedImages = [];
69
+ this.allFilesImages = [];
70
+ this.selectedFile = null;
71
+ this.allFiles = [];
72
+ this.titleNum = 0;
73
+ }
74
+
75
+ createButtons() {
76
+ const inputStyle = {
77
+ display: "block",
78
+ minWidth: "500px",
79
+ width: "100%",
80
+ padding: "10px",
81
+ margin: "10px 0",
82
+ borderRadius: "4px",
83
+ border: "1px solid #ddd",
84
+ boxSizing: "border-box",
85
+ };
86
+
87
+ const textAreaStyle = {
88
+ display: "block",
89
+ minWidth: "500px",
90
+ width: "100%",
91
+ padding: "10px",
92
+ margin: "10px 0",
93
+ borderRadius: "4px",
94
+ border: "1px solid #ddd",
95
+ boxSizing: "border-box",
96
+ minHeight: "100px",
97
+ background: "#222",
98
+ resize: "vertical",
99
+ color: "#f2f2f2",
100
+ fontFamily: "Arial",
101
+ fontWeight: "400",
102
+ fontSize: "15px",
103
+ };
104
+
105
+ const hyperLinkStyle = {
106
+ display: "block",
107
+ marginBottom: "15px",
108
+ fontWeight: "bold",
109
+ fontSize: "14px",
110
+ };
111
+
112
+ const labelStyle = {
113
+ color: "#f8f8f8",
114
+ display: "block",
115
+ margin: "10px 0 0 0",
116
+ fontWeight: "bold",
117
+ textDecoration: "none",
118
+ };
119
+
120
+ const buttonStyle = {
121
+ padding: "10px 80px",
122
+ margin: "10px 5px",
123
+ borderRadius: "4px",
124
+ border: "none",
125
+ cursor: "pointer",
126
+ color: "#fff",
127
+ backgroundColor: "#007bff",
128
+ };
129
+
130
+ // upload images input
131
+ this.uploadImagesInput = $el("input", {
132
+ type: "file",
133
+ multiple: false,
134
+ style: inputStyle,
135
+ accept: "image/*",
136
+ });
137
+
138
+ this.uploadImagesInput.addEventListener("change", async (e) => {
139
+ const file = e.target.files[0];
140
+ if (!file) {
141
+ this.previewImage.src = "";
142
+ this.previewImage.style.display = "none";
143
+ return;
144
+ }
145
+ const reader = new FileReader();
146
+ reader.onload = async (e) => {
147
+ const imgData = e.target.result;
148
+ this.previewImage.src = imgData;
149
+ this.previewImage.style.display = "block";
150
+ this.selectedFile = null;
151
+ // Once user uploads an image, we uncheck all radio buttons
152
+ this.radioButtons.forEach((ele) => {
153
+ ele.checked = false;
154
+ ele.parentElement.classList.remove("checked");
155
+ });
156
+
157
+ // Add the opacity style toggle here to indicate that they only need
158
+ // to upload one image or choose one from the outputs.
159
+ this.outputsSection.style.opacity = 0.35;
160
+ this.uploadImagesInput.style.opacity = 1;
161
+ };
162
+ reader.readAsDataURL(file);
163
+ });
164
+
165
+ // preview image
166
+ this.previewImage = $el("img", {
167
+ src: "",
168
+ style: {
169
+ width: "100%",
170
+ maxHeight: "100px",
171
+ objectFit: "contain",
172
+ display: "none",
173
+ marginTop: "10px",
174
+ },
175
+ });
176
+
177
+ this.keyInput = $el("input", {
178
+ type: "password",
179
+ placeholder: "Copy & paste your API key",
180
+ style: inputStyle,
181
+ });
182
+ this.TitleInput = $el("input", {
183
+ type: "text",
184
+ placeholder: "Title (Required)",
185
+ style: inputStyle,
186
+ maxLength: "70",
187
+ oninput: () => {
188
+ const titleNum = this.TitleInput.value.length;
189
+ titleNumDom.textContent = `${titleNum}/70`;
190
+ },
191
+ });
192
+ this.SubTitleInput = $el("input", {
193
+ type: "text",
194
+ placeholder: "Subtitle (Optional)",
195
+ style: inputStyle,
196
+ maxLength: "350",
197
+ oninput: () => {
198
+ const titleNum = this.SubTitleInput.value.length;
199
+ subTitleNumDom.textContent = `${titleNum}/350`;
200
+ },
201
+ });
202
+ this.LockInput = $el("input", {
203
+ type: "text",
204
+ placeholder: "",
205
+ style: {
206
+ width: "100px",
207
+ padding: "7px",
208
+ borderRadius: "4px",
209
+ border: "1px solid #ddd",
210
+ boxSizing: "border-box",
211
+ },
212
+ oninput: (event) => {
213
+ let input = event.target.value;
214
+ // Use a regular expression to match a number with up to two decimal places
215
+ const regex = /^\d*\.?\d{0,2}$/;
216
+ if (!regex.test(input)) {
217
+ // If the input doesn't match, remove the last entered character
218
+ event.target.value = input.slice(0, -1);
219
+ }
220
+ const numericValue = parseFloat(input);
221
+ if (numericValue > 9999) {
222
+ input = "9999";
223
+ }
224
+ // Update the input field with the valid value
225
+ event.target.value = input;
226
+ },
227
+ });
228
+ this.descriptionInput = $el("textarea", {
229
+ placeholder: "Content (Optional)",
230
+ style: {
231
+ ...textAreaStyle,
232
+ minHeight: "100px",
233
+ },
234
+ });
235
+
236
+ // Header Section
237
+ const headerSection = $el("h3", {
238
+ textContent: "Share your workflow to Copus",
239
+ size: 3,
240
+ color: "white",
241
+ style: {
242
+ "text-align": "center",
243
+ color: "white",
244
+ margin: "0 0 10px 0",
245
+ },
246
+ });
247
+ this.getAPIKeyLink = $el(
248
+ "a",
249
+ {
250
+ style: {
251
+ ...hyperLinkStyle,
252
+ color: "#59E8C6",
253
+ },
254
+ href: `${DEFAULT_HOMEPAGE_URL}?fromPage=comfyUI`,
255
+ target: "_blank",
256
+ },
257
+ ["👉 Get your API key here"]
258
+ );
259
+ const linkSection = $el(
260
+ "div",
261
+ {
262
+ style: {
263
+ marginTop: "10px",
264
+ display: "flex",
265
+ flexDirection: "column",
266
+ },
267
+ },
268
+ [
269
+ // this.communityLink,
270
+ this.getAPIKeyLink,
271
+ ]
272
+ );
273
+
274
+ // Account Section
275
+ const accountSection = $el("div", { style: sectionStyle }, [
276
+ $el("label", { style: labelStyle }, ["1️⃣ Copus API Key"]),
277
+ this.keyInput,
278
+ ]);
279
+
280
+ // Output Upload Section
281
+ const outputUploadSection = $el("div", { style: sectionStyle }, [
282
+ $el(
283
+ "label",
284
+ {
285
+ style: {
286
+ ...labelStyle,
287
+ margin: "10px 0 0 0",
288
+ },
289
+ },
290
+ ["2️⃣ Image/Thumbnail (Required)"]
291
+ ),
292
+ this.previewImage,
293
+ this.uploadImagesInput,
294
+ ]);
295
+
296
+ // Outputs Section
297
+ this.outputsSection = $el(
298
+ "div",
299
+ {
300
+ id: "selectOutputs",
301
+ },
302
+ []
303
+ );
304
+
305
+ const titleNumDom = $el(
306
+ "label",
307
+ {
308
+ style: {
309
+ fontSize: "12px",
310
+ position: "absolute",
311
+ right: "10px",
312
+ bottom: "-10px",
313
+ color: "#999",
314
+ },
315
+ },
316
+ ["0/70"]
317
+ );
318
+ const subTitleNumDom = $el(
319
+ "label",
320
+ {
321
+ style: {
322
+ fontSize: "12px",
323
+ position: "absolute",
324
+ right: "10px",
325
+ bottom: "-10px",
326
+ color: "#999",
327
+ },
328
+ },
329
+ ["0/350"]
330
+ );
331
+ const descriptionNumDom = $el(
332
+ "label",
333
+ {
334
+ style: {
335
+ fontSize: "12px",
336
+ position: "absolute",
337
+ right: "10px",
338
+ bottom: "-10px",
339
+ color: "#999",
340
+ },
341
+ },
342
+ ["0/70"]
343
+ );
344
+ // Additional Inputs Section
345
+ const additionalInputsSection = $el(
346
+ "div",
347
+ { style: { ...sectionStyle, } },
348
+ [
349
+ $el("label", { style: labelStyle }, ["3️⃣ Title "]),
350
+ this.TitleInput,
351
+ titleNumDom,
352
+ ]
353
+ );
354
+ const SubtitleSection = $el("div", { style: sectionStyle }, [
355
+ $el("label", { style: labelStyle }, ["4️⃣ Subtitle "]),
356
+ this.SubTitleInput,
357
+ subTitleNumDom,
358
+ ]);
359
+ const DescriptionSection = $el("div", { style: sectionStyle }, [
360
+ $el("label", { style: labelStyle }, ["5️⃣ Description "]),
361
+ this.descriptionInput,
362
+ // descriptionNumDom,
363
+ ]);
364
+ // switch between outputs section and additional inputs section
365
+ this.radioButtons_lock = [];
366
+
367
+ this.radioButtonsCheck_lock = $el("input", {
368
+ type: "radio",
369
+ name: "output_type_lock",
370
+ value: "0",
371
+ id: "blockchain1_lock",
372
+ checked: true,
373
+ });
374
+ this.radioButtonsCheckOff_lock = $el("input", {
375
+ type: "radio",
376
+ name: "output_type_lock",
377
+ value: "1",
378
+ id: "blockchain_lock",
379
+ });
380
+
381
+ const blockChainSection_lock = $el("div", { style: sectionStyle }, [
382
+ $el("label", { style: labelStyle }, ["6️⃣ Pay to download"]),
383
+ $el(
384
+ "label",
385
+ {
386
+ style: {
387
+ marginTop: "10px",
388
+ display: "flex",
389
+ alignItems: "center",
390
+ cursor: "pointer",
391
+ },
392
+ },
393
+ [
394
+ this.radioButtonsCheck_lock,
395
+ $el("div", { style: { marginLeft: "5px" ,display:'flex',alignItems:'center'} }, [
396
+ $el("span", { style: { marginLeft: "5px" } }, ["ON"]),
397
+ $el("span", { style: { marginLeft: "20px",marginRight:'10px' ,color:'#fff'} }, ["Price US$"]),
398
+ this.LockInput
399
+ ]),
400
+ ]
401
+ ),
402
+ $el(
403
+ "label",
404
+ { style: { display: "flex", alignItems: "center", cursor: "pointer" } },
405
+ [
406
+ this.radioButtonsCheckOff_lock,
407
+ $el("span", { style: { marginLeft: "5px" } }, ["OFF"]),
408
+ ]
409
+ ),
410
+
411
+ $el(
412
+ "p",
413
+ { style: { fontSize: "16px", color: "#fff", margin: "10px 0 0 0" } },
414
+ ["Get paid from your workflow. You can change the price and withdraw your earnings on Copus."]
415
+ ),
416
+ ]);
417
+
418
+ this.radioButtons = [];
419
+
420
+ this.radioButtonsCheck = $el("input", {
421
+ type: "radio",
422
+ name: "output_type",
423
+ value: "0",
424
+ id: "blockchain1",
425
+ checked: true,
426
+ });
427
+ this.radioButtonsCheckOff = $el("input", {
428
+ type: "radio",
429
+ name: "output_type",
430
+ value: "1",
431
+ id: "blockchain",
432
+ });
433
+
434
+ const blockChainSection = $el("div", { style: sectionStyle }, [
435
+ $el("label", { style: labelStyle }, ["7️⃣ Store on blockchain "]),
436
+ $el(
437
+ "label",
438
+ {
439
+ style: {
440
+ marginTop: "10px",
441
+ display: "flex",
442
+ alignItems: "center",
443
+ cursor: "pointer",
444
+ },
445
+ },
446
+ [
447
+ this.radioButtonsCheck,
448
+ $el("span", { style: { marginLeft: "5px" } }, ["ON"]),
449
+ ]
450
+ ),
451
+ $el(
452
+ "label",
453
+ { style: { display: "flex", alignItems: "center", cursor: "pointer" } },
454
+ [
455
+ this.radioButtonsCheckOff,
456
+ $el("span", { style: { marginLeft: "5px" } }, ["OFF"]),
457
+ ]
458
+ ),
459
+ $el(
460
+ "p",
461
+ { style: { fontSize: "16px", color: "#fff", margin: "10px 0 0 0" } },
462
+ ["Secure ownership with a permanent & decentralized storage"]
463
+ ),
464
+ ]);
465
+
466
+
467
+ // Message Section
468
+ this.message = $el(
469
+ "div",
470
+ {
471
+ style: {
472
+ color: "#ff3d00",
473
+ textAlign: "center",
474
+ padding: "10px",
475
+ fontSize: "20px",
476
+ },
477
+ },
478
+ []
479
+ );
480
+
481
+ this.shareButton = $el("button", {
482
+ type: "submit",
483
+ textContent: "Share",
484
+ style: buttonStyle,
485
+ onclick: () => {
486
+ this.handleShareButtonClick();
487
+ },
488
+ });
489
+
490
+ // Share and Close Buttons
491
+ const buttonsSection = $el(
492
+ "div",
493
+ {
494
+ style: {
495
+ textAlign: "right",
496
+ marginTop: "20px",
497
+ display: "flex",
498
+ justifyContent: "space-between",
499
+ },
500
+ },
501
+ [
502
+ $el("button", {
503
+ type: "button",
504
+ textContent: "Close",
505
+ style: {
506
+ ...buttonStyle,
507
+ backgroundColor: undefined,
508
+ },
509
+ onclick: () => {
510
+ this.close();
511
+ },
512
+ }),
513
+ this.shareButton,
514
+ ]
515
+ );
516
+
517
+ // Composing the full layout
518
+ const layout = [
519
+ headerSection,
520
+ linkSection,
521
+ accountSection,
522
+ outputUploadSection,
523
+ this.outputsSection,
524
+ additionalInputsSection,
525
+ SubtitleSection,
526
+ DescriptionSection,
527
+ // contestSection,
528
+ blockChainSection_lock,
529
+ blockChainSection,
530
+ this.message,
531
+ buttonsSection,
532
+ ];
533
+
534
+ return layout;
535
+ }
536
+ /**
537
+ * api
538
+ * @param {url} path
539
+ * @param {params} options
540
+ * @param {statusText} statusText
541
+ * @returns
542
+ */
543
+ async fetchApi(path, options, statusText) {
544
+ if (statusText) {
545
+ this.message.textContent = statusText;
546
+ }
547
+ const fullPath = new URL(API_ENDPOINT + path);
548
+ const response = await fetch(fullPath, options);
549
+ if (!response.ok) {
550
+ throw new Error(response.statusText);
551
+ }
552
+ if (statusText) {
553
+ this.message.textContent = "";
554
+ }
555
+ const data = await response.json();
556
+ return {
557
+ ok: response.ok,
558
+ statusText: response.statusText,
559
+ status: response.status,
560
+ data,
561
+ };
562
+ }
563
+ /**
564
+ * @param {file} uploadFile
565
+ */
566
+ async uploadThumbnail(uploadFile, type) {
567
+ const form = new FormData();
568
+ form.append("file", uploadFile);
569
+ form.append("apiToken", this.keyInput.value);
570
+ try {
571
+ const res = await this.fetchApi(
572
+ `/client/common/opus/uploadImage`,
573
+ {
574
+ method: "POST",
575
+ body: form,
576
+ },
577
+ "Uploading thumbnail..."
578
+ );
579
+ if (res.status && res.data.status && res.data) {
580
+ const { data } = res.data;
581
+ if (type) {
582
+ this.allFilesImages.push({
583
+ url: data,
584
+ });
585
+ }
586
+ this.uploadedImages.push({
587
+ url: data,
588
+ });
589
+ } else {
590
+ throw new Error("make sure your API key is correct and try again later");
591
+ }
592
+ } catch (e) {
593
+ if (e?.response?.status === 413) {
594
+ throw new Error("File size is too large (max 20MB)");
595
+ } else {
596
+ throw new Error("Error uploading thumbnail: " + e.message);
597
+ }
598
+ }
599
+ }
600
+
601
+ async handleShareButtonClick() {
602
+ this.message.textContent = "";
603
+ try {
604
+ this.shareButton.disabled = true;
605
+ this.shareButton.textContent = "Sharing...";
606
+ await this.share();
607
+ } catch (e) {
608
+ customAlert(e.message);
609
+ }
610
+ this.shareButton.disabled = false;
611
+ this.shareButton.textContent = "Share";
612
+ }
613
+ /**
614
+ * share
615
+ * @param {string} title
616
+ * @param {string} subtitle
617
+ * @param {string} content
618
+ * @param {boolean} storeOnChain
619
+ * @param {string} coverUrl
620
+ * @param {string[]} imageUrls
621
+ * @param {string} apiToken
622
+ */
623
+ async share() {
624
+ const prompt = await app.graphToPrompt();
625
+ const workflowJSON = prompt["workflow"];
626
+ const form_values = {
627
+ title: this.TitleInput.value,
628
+ subTitle: this.SubTitleInput.value,
629
+ content: this.descriptionInput.value,
630
+ storeOnChain: this.radioButtonsCheck.checked ? true : false,
631
+ lockState:this.radioButtonsCheck_lock.checked ? 2 : 0,
632
+ unlockPrice:this.LockInput.value,
633
+ };
634
+
635
+ if (!this.keyInput.value) {
636
+ throw new Error("API key is required");
637
+ }
638
+
639
+ if (!this.uploadImagesInput.files[0] && !this.selectedFile) {
640
+ throw new Error("Thumbnail is required");
641
+ }
642
+
643
+ if (!form_values.title) {
644
+ throw new Error("Title is required");
645
+ }
646
+
647
+ if(this.radioButtonsCheck_lock.checked){
648
+ if (!this.LockInput.value){
649
+ throw new Error("Price is required");
650
+ }
651
+ }
652
+
653
+ if (!this.uploadedImages.length) {
654
+ if (this.selectedFile) {
655
+ await this.uploadThumbnail(this.selectedFile);
656
+ } else {
657
+ for (const file of this.uploadImagesInput.files) {
658
+ try {
659
+ await this.uploadThumbnail(file);
660
+ } catch (e) {
661
+ this.uploadedImages = [];
662
+ throw new Error(e.message);
663
+ }
664
+ }
665
+
666
+ if (this.uploadImagesInput.files.length === 0) {
667
+ throw new Error("No thumbnail uploaded");
668
+ }
669
+ }
670
+ }
671
+ if (this.allFiles.length > 0) {
672
+ for (const file of this.allFiles) {
673
+ try {
674
+ await this.uploadThumbnail(file, true);
675
+ } catch (e) {
676
+ this.allFilesImages = [];
677
+ throw new Error(e.message);
678
+ }
679
+ }
680
+ }
681
+ try {
682
+ const res = await this.fetchApi(
683
+ "/client/common/opus/shareFromComfyUI",
684
+ {
685
+ method: "POST",
686
+ headers: { "Content-Type": "application/json" },
687
+ body: JSON.stringify({
688
+ workflowJson: workflowJSON,
689
+ apiToken: this.keyInput.value,
690
+ coverUrl: this.uploadedImages[0].url,
691
+ imageUrls: this.allFilesImages.map((image) => image.url),
692
+ ...form_values,
693
+ }),
694
+ },
695
+ "Uploading workflow..."
696
+ );
697
+
698
+ if (res.status && res.data.status && res.data) {
699
+ localStorage.setItem("copus_token",this.keyInput.value);
700
+ const { data } = res.data;
701
+ if (data) {
702
+ const url = `${DEFAULT_HOMEPAGE_URL}/work/${data}`;
703
+ this.message.innerHTML = `Workflow has been shared successfully. <a href="${url}" target="_blank">Click here to view it.</a>`;
704
+ this.previewImage.src = "";
705
+ this.previewImage.style.display = "none";
706
+ this.uploadedImages = [];
707
+ this.allFilesImages = [];
708
+ this.allFiles = [];
709
+ this.TitleInput.value = "";
710
+ this.SubTitleInput.value = "";
711
+ this.descriptionInput.value = "";
712
+ this.selectedFile = null;
713
+ }
714
+ }
715
+ } catch (e) {
716
+ throw new Error("Error sharing workflow: " + e.message);
717
+ }
718
+ }
719
+
720
+ async fetchImageBlob(url) {
721
+ const response = await fetch(url);
722
+ const blob = await response.blob();
723
+ return blob;
724
+ }
725
+
726
+ async show({ potential_outputs, potential_output_nodes } = {}) {
727
+ // Sort `potential_output_nodes` by node ID to make the order always
728
+ // consistent, but we should also keep `potential_outputs` in the same
729
+ // order as `potential_output_nodes`.
730
+ const potential_output_to_order = {};
731
+ potential_output_nodes.forEach((node, index) => {
732
+ if (node.id in potential_output_to_order) {
733
+ potential_output_to_order[node.id][1].push(potential_outputs[index]);
734
+ } else {
735
+ potential_output_to_order[node.id] = [node, [potential_outputs[index]]];
736
+ }
737
+ });
738
+ // Sort the object `potential_output_to_order` by key (node ID)
739
+ const sorted_potential_output_to_order = Object.fromEntries(
740
+ Object.entries(potential_output_to_order).sort(
741
+ (a, b) => a[0].id - b[0].id
742
+ )
743
+ );
744
+ const sorted_potential_outputs = [];
745
+ const sorted_potential_output_nodes = [];
746
+ for (const [key, value] of Object.entries(
747
+ sorted_potential_output_to_order
748
+ )) {
749
+ sorted_potential_output_nodes.push(value[0]);
750
+ sorted_potential_outputs.push(...value[1]);
751
+ }
752
+ potential_output_nodes = sorted_potential_output_nodes;
753
+ potential_outputs = sorted_potential_outputs;
754
+ const apiToken = localStorage.getItem("copus_token");
755
+ this.message.innerHTML = "";
756
+ this.message.textContent = "";
757
+ this.element.style.display = "block";
758
+ this.previewImage.src = "";
759
+ this.previewImage.style.display = "none";
760
+ this.keyInput.value = apiToken!=null?apiToken:"";
761
+ this.uploadedImages = [];
762
+ this.allFilesImages = [];
763
+ this.allFiles = [];
764
+ // If `selectedNodeId` is provided, we will select the corresponding radio
765
+ // button for the node. In addition, we move the selected radio button to
766
+ // the top of the list.
767
+ if (this.selectedNodeId) {
768
+ const index = potential_output_nodes.findIndex(
769
+ (node) => node.id === this.selectedNodeId
770
+ );
771
+ if (index >= 0) {
772
+ this.selectedOutputIndex = index;
773
+ }
774
+ }
775
+
776
+ this.radioButtons = [];
777
+ const new_radio_buttons = $el(
778
+ "div",
779
+ {
780
+ id: "selectOutput-Options",
781
+ style: {
782
+ "overflow-y": "scroll",
783
+ "max-height": "200px",
784
+ display: "grid",
785
+ "grid-template-columns": "repeat(auto-fit, minmax(100px, 1fr))",
786
+ "grid-template-rows": "auto",
787
+ "grid-column-gap": "10px",
788
+ "grid-row-gap": "10px",
789
+ "margin-bottom": "10px",
790
+ padding: "10px",
791
+ "border-radius": "8px",
792
+ "box-shadow": "0 2px 4px rgba(0, 0, 0, 0.05)",
793
+ "background-color": "var(--bg-color)",
794
+ },
795
+ },
796
+ potential_outputs.map((output, index) => {
797
+ const { node_id } = output;
798
+ const radio_button = $el(
799
+ "input",
800
+ {
801
+ type: "radio",
802
+ name: "selectOutputImages",
803
+ value: index,
804
+ required: index === 0,
805
+ },
806
+ []
807
+ );
808
+ let radio_button_img;
809
+ let filename;
810
+ if (output.type === "image" || output.type === "temp") {
811
+ radio_button_img = $el(
812
+ "img",
813
+ {
814
+ src: `/view?filename=${output.image.filename}&subfolder=${output.image.subfolder}&type=${output.image.type}`,
815
+ style: {
816
+ width: "100px",
817
+ height: "100px",
818
+ objectFit: "cover",
819
+ borderRadius: "5px",
820
+ },
821
+ },
822
+ []
823
+ );
824
+ filename = output.image.filename;
825
+ } else if (output.type === "output") {
826
+ radio_button_img = $el(
827
+ "img",
828
+ {
829
+ src: output.output.value,
830
+ style: {
831
+ width: "auto",
832
+ height: "100px",
833
+ objectFit: "cover",
834
+ borderRadius: "5px",
835
+ },
836
+ },
837
+ []
838
+ );
839
+ filename = output.filename;
840
+ } else {
841
+ // unsupported output type
842
+ // this should never happen
843
+ radio_button_img = $el(
844
+ "img",
845
+ {
846
+ src: "",
847
+ style: { width: "auto", height: "100px" },
848
+ },
849
+ []
850
+ );
851
+ }
852
+ const radio_button_text = $el(
853
+ "span",
854
+ {
855
+ style: {
856
+ color: "gray",
857
+ display: "block",
858
+ fontSize: "12px",
859
+ overflowX: "hidden",
860
+ textOverflow: "ellipsis",
861
+ textWrap: "nowrap",
862
+ maxWidth: "100px",
863
+ },
864
+ },
865
+ [output.title]
866
+ );
867
+ const node_id_chip = $el(
868
+ "span",
869
+ {
870
+ style: {
871
+ color: "#FBFBFD",
872
+ display: "block",
873
+ backgroundColor: "rgba(0, 0, 0, 0.5)",
874
+ fontSize: "12px",
875
+ overflowX: "hidden",
876
+ padding: "2px 3px",
877
+ textOverflow: "ellipsis",
878
+ textWrap: "nowrap",
879
+ maxWidth: "100px",
880
+ position: "absolute",
881
+ top: "3px",
882
+ left: "3px",
883
+ borderRadius: "3px",
884
+ },
885
+ },
886
+ [`Node: ${node_id}`]
887
+ );
888
+ radio_button.style.color = "var(--fg-color)";
889
+ radio_button.checked = this.selectedOutputIndex === index;
890
+
891
+ radio_button.onchange = async () => {
892
+ this.selectedOutputIndex = parseInt(radio_button.value);
893
+
894
+ // Remove the "checked" class from all radio buttons
895
+ this.radioButtons.forEach((ele) => {
896
+ ele.parentElement.classList.remove("checked");
897
+ });
898
+ radio_button.parentElement.classList.add("checked");
899
+
900
+ this.fetchImageBlob(radio_button_img.src).then((blob) => {
901
+ const file = new File([blob], filename, {
902
+ type: blob.type,
903
+ });
904
+ this.previewImage.src = radio_button_img.src;
905
+ this.previewImage.style.display = "block";
906
+ this.selectedFile = file;
907
+ });
908
+
909
+ // Add the opacity style toggle here to indicate that they only need
910
+ // to upload one image or choose one from the outputs.
911
+ this.outputsSection.style.opacity = 1;
912
+ this.uploadImagesInput.style.opacity = 0.35;
913
+ };
914
+
915
+ if (radio_button.checked) {
916
+ this.fetchImageBlob(radio_button_img.src).then((blob) => {
917
+ const file = new File([blob], filename, {
918
+ type: blob.type,
919
+ });
920
+ this.previewImage.src = radio_button_img.src;
921
+ this.previewImage.style.display = "block";
922
+ this.selectedFile = file;
923
+ });
924
+ // Add the opacity style toggle here to indicate that they only need
925
+ // to upload one image or choose one from the outputs.
926
+ this.outputsSection.style.opacity = 1;
927
+ this.uploadImagesInput.style.opacity = 0.35;
928
+ }
929
+ this.radioButtons.push(radio_button);
930
+ let src = "";
931
+ if (output.type === "image" || output.type === "temp") {
932
+ filename = output.image.filename;
933
+ src = `/view?filename=${output.image.filename}&subfolder=${output.image.subfolder}&type=${output.image.type}`;
934
+ } else if (output.type === "output") {
935
+ src = output.output.value;
936
+ filename = output.filename;
937
+ }
938
+ if (src) {
939
+ this.fetchImageBlob(src).then((blob) => {
940
+ const file = new File([blob], filename, {
941
+ type: blob.type,
942
+ });
943
+ this.allFiles.push(file);
944
+ });
945
+ }
946
+ return $el(
947
+ `label.output_label${radio_button.checked ? ".checked" : ""}`,
948
+ {
949
+ style: {
950
+ display: "flex",
951
+ flexDirection: "column",
952
+ alignItems: "center",
953
+ justifyContent: "center",
954
+ marginBottom: "10px",
955
+ cursor: "pointer",
956
+ position: "relative",
957
+ },
958
+ },
959
+ [radio_button_img, radio_button_text, radio_button, node_id_chip]
960
+ );
961
+ })
962
+ );
963
+
964
+ const header = $el(
965
+ "p",
966
+ {
967
+ textContent:
968
+ this.radioButtons.length === 0
969
+ ? "Queue Prompt to see the outputs"
970
+ : "Or choose one from the outputs (scroll to see all)",
971
+ size: 2,
972
+ color: "white",
973
+ style: {
974
+ color: "white",
975
+ margin: "0 0 5px 0",
976
+ fontSize: "12px",
977
+ },
978
+ },
979
+ []
980
+ );
981
+ this.outputsSection.innerHTML = "";
982
+ this.outputsSection.appendChild(header);
983
+ this.outputsSection.appendChild(new_radio_buttons);
984
+ }
985
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-share-openart.js ADDED
@@ -0,0 +1,746 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {app} from "../../scripts/app.js";
2
+ import {api} from "../../scripts/api.js";
3
+ import {ComfyDialog, $el} from "../../scripts/ui.js";
4
+ import { customAlert } from "./common.js";
5
+
6
+ const LOCAL_STORAGE_KEY = "openart_comfy_workflow_key";
7
+ const DEFAULT_HOMEPAGE_URL = "https://openart.ai/workflows/dev?developer=true";
8
+ //const DEFAULT_HOMEPAGE_URL = "http://localhost:8080/workflows/dev?developer=true";
9
+
10
+ const API_ENDPOINT = "https://openart.ai/api";
11
+ //const API_ENDPOINT = "http://localhost:8080/api";
12
+
13
+ const style = `
14
+ .openart-share-dialog a {
15
+ color: #f8f8f8;
16
+ }
17
+ .openart-share-dialog a:hover {
18
+ color: #007bff;
19
+ }
20
+ .output_label {
21
+ border: 5px solid transparent;
22
+ }
23
+ .output_label:hover {
24
+ border: 5px solid #59E8C6;
25
+ }
26
+ .output_label.checked {
27
+ border: 5px solid #59E8C6;
28
+ }
29
+ `;
30
+
31
+ // Shared component styles
32
+ const sectionStyle = {
33
+ marginBottom: 0,
34
+ padding: 0,
35
+ borderRadius: "8px",
36
+ boxShadow: "0 2px 4px rgba(0, 0, 0, 0.05)",
37
+ display: "flex",
38
+ flexDirection: "column",
39
+ justifyContent: "center",
40
+ };
41
+
42
+ export class OpenArtShareDialog extends ComfyDialog {
43
+ static instance = null;
44
+
45
+ constructor() {
46
+ super();
47
+ $el("style", {
48
+ textContent: style,
49
+ parent: document.head,
50
+ });
51
+ this.element = $el(
52
+ "div.comfy-modal.openart-share-dialog",
53
+ {
54
+ parent: document.body,
55
+ style: {
56
+ "overflow-y": "auto",
57
+ },
58
+ },
59
+ [$el("div.comfy-modal-content", {}, [...this.createButtons()])]
60
+ );
61
+ this.selectedOutputIndex = 0;
62
+ this.selectedNodeId = null;
63
+ this.uploadedImages = [];
64
+ this.selectedFile = null;
65
+ }
66
+
67
+ async readKey() {
68
+ let key = ""
69
+ try {
70
+ key = await api.fetchApi(`/manager/get_openart_auth`)
71
+ .then(response => response.json())
72
+ .then(data => {
73
+ return data.openart_key;
74
+ })
75
+ .catch(error => {
76
+ // console.log(error);
77
+ });
78
+ } catch (error) {
79
+ // console.log(error);
80
+ }
81
+ return key || "";
82
+ }
83
+
84
+ async saveKey(value) {
85
+ await api.fetchApi(`/manager/set_openart_auth`, {
86
+ method: 'POST',
87
+ headers: {'Content-Type': 'application/json'},
88
+ body: JSON.stringify({
89
+ openart_key: value
90
+ })
91
+ });
92
+ }
93
+
94
+ createButtons() {
95
+ const inputStyle = {
96
+ display: "block",
97
+ minWidth: "500px",
98
+ width: "100%",
99
+ padding: "10px",
100
+ margin: "10px 0",
101
+ borderRadius: "4px",
102
+ border: "1px solid #ddd",
103
+ boxSizing: "border-box",
104
+ };
105
+
106
+ const hyperLinkStyle = {
107
+ display: "block",
108
+ marginBottom: "15px",
109
+ fontWeight: "bold",
110
+ fontSize: "14px",
111
+ };
112
+
113
+ const labelStyle = {
114
+ color: "#f8f8f8",
115
+ display: "block",
116
+ margin: "10px 0 0 0",
117
+ fontWeight: "bold",
118
+ textDecoration: "none",
119
+ };
120
+
121
+ const buttonStyle = {
122
+ padding: "10px 80px",
123
+ margin: "10px 5px",
124
+ borderRadius: "4px",
125
+ border: "none",
126
+ cursor: "pointer",
127
+ color: "#fff",
128
+ backgroundColor: "#007bff",
129
+ };
130
+
131
+ // upload images input
132
+ this.uploadImagesInput = $el("input", {
133
+ type: "file",
134
+ multiple: false,
135
+ style: inputStyle,
136
+ accept: "image/*",
137
+ });
138
+
139
+ this.uploadImagesInput.addEventListener("change", async (e) => {
140
+ const file = e.target.files[0];
141
+ if (!file) {
142
+ this.previewImage.src = "";
143
+ this.previewImage.style.display = "none";
144
+ return;
145
+ }
146
+ const reader = new FileReader();
147
+ reader.onload = async (e) => {
148
+ const imgData = e.target.result;
149
+ this.previewImage.src = imgData;
150
+ this.previewImage.style.display = "block";
151
+ this.selectedFile = null
152
+ // Once user uploads an image, we uncheck all radio buttons
153
+ this.radioButtons.forEach((ele) => {
154
+ ele.checked = false;
155
+ ele.parentElement.classList.remove("checked");
156
+ });
157
+
158
+ // Add the opacity style toggle here to indicate that they only need
159
+ // to upload one image or choose one from the outputs.
160
+ this.outputsSection.style.opacity = 0.35;
161
+ this.uploadImagesInput.style.opacity = 1;
162
+ };
163
+ reader.readAsDataURL(file);
164
+ });
165
+
166
+ // preview image
167
+ this.previewImage = $el("img", {
168
+ src: "",
169
+ style: {
170
+ width: "100%",
171
+ maxHeight: "100px",
172
+ objectFit: "contain",
173
+ display: "none",
174
+ marginTop: '10px',
175
+ },
176
+ });
177
+
178
+ this.keyInput = $el("input", {
179
+ type: "password",
180
+ placeholder: "Copy & paste your API key",
181
+ style: inputStyle,
182
+ });
183
+ this.NameInput = $el("input", {
184
+ type: "text",
185
+ placeholder: "Title (required)",
186
+ style: inputStyle,
187
+ });
188
+ this.descriptionInput = $el("textarea", {
189
+ placeholder: "Description (optional)",
190
+ style: {
191
+ ...inputStyle,
192
+ minHeight: "100px",
193
+ },
194
+ });
195
+
196
+ // Header Section
197
+ const headerSection = $el("h3", {
198
+ textContent: "Share your workflow to OpenArt",
199
+ size: 3,
200
+ color: "white",
201
+ style: {
202
+ 'text-align': 'center',
203
+ color: 'var(--input-text)',
204
+ margin: '0 0 10px 0',
205
+ }
206
+ });
207
+
208
+ // LinkSection
209
+ this.communityLink = $el("a", {
210
+ style: hyperLinkStyle,
211
+ href: DEFAULT_HOMEPAGE_URL,
212
+ target: "_blank"
213
+ }, ["👉 Check out thousands of workflows shared from the community"])
214
+ this.getAPIKeyLink = $el("a", {
215
+ style: {
216
+ ...hyperLinkStyle,
217
+ color: "#59E8C6"
218
+ },
219
+ href: DEFAULT_HOMEPAGE_URL,
220
+ target: "_blank"
221
+ }, ["👉 Get your API key here"])
222
+ const linkSection = $el(
223
+ "div",
224
+ {
225
+ style: {
226
+ marginTop: "10px",
227
+ display: "flex",
228
+ flexDirection: "column",
229
+ },
230
+ },
231
+ [
232
+ this.communityLink,
233
+ this.getAPIKeyLink,
234
+ ]
235
+ );
236
+
237
+ // Account Section
238
+ const accountSection = $el("div", {style: sectionStyle}, [
239
+ $el("label", {style: labelStyle}, ["1️⃣ OpenArt API Key"]),
240
+ this.keyInput,
241
+ ]);
242
+
243
+ // Output Upload Section
244
+ const outputUploadSection = $el("div", {style: sectionStyle}, [
245
+ $el("label", {
246
+ style: {
247
+ ...labelStyle,
248
+ margin: "10px 0 0 0"
249
+ }
250
+ }, ["2️⃣ Image/Thumbnail (Required)"]),
251
+ this.previewImage,
252
+ this.uploadImagesInput,
253
+ ]);
254
+
255
+ // Outputs Section
256
+ this.outputsSection = $el("div", {
257
+ id: "selectOutputs",
258
+ }, []);
259
+
260
+ // Additional Inputs Section
261
+ const additionalInputsSection = $el("div", {style: sectionStyle}, [
262
+ $el("label", {style: labelStyle}, ["3️⃣ Workflow Information"]),
263
+ this.NameInput,
264
+ this.descriptionInput,
265
+ ]);
266
+
267
+ // OpenArt Contest Section
268
+ /*
269
+ this.joinContestCheckbox = $el("input", {
270
+ type: 'checkbox',
271
+ id: "join_contest"s
272
+ }, [])
273
+ this.joinContestDescription = $el("a", {
274
+ style: {
275
+ ...hyperLinkStyle,
276
+ display: 'inline-block',
277
+ color: "#59E8C6",
278
+ fontSize: '12px',
279
+ marginLeft: '10px',
280
+ marginBottom: 0,
281
+ },
282
+ href: "https://contest.openart.ai/",
283
+ target: "_blank"
284
+ }, ["🏆 I'm participating in the OpenArt workflow contest"])
285
+ this.joinContestLabel = $el("label", {
286
+ style: {
287
+ display: 'flex',
288
+ alignItems: 'center',
289
+ cursor: 'pointer',
290
+ }
291
+ }, [this.joinContestCheckbox, this.joinContestDescription])
292
+ const contestSection = $el("div", {style: sectionStyle}, [
293
+ this.joinContestLabel,
294
+ ]);
295
+ */
296
+
297
+ // Message Section
298
+ this.message = $el(
299
+ "div",
300
+ {
301
+ style: {
302
+ color: "#ff3d00",
303
+ textAlign: "center",
304
+ padding: "10px",
305
+ fontSize: "20px",
306
+ },
307
+ },
308
+ []
309
+ );
310
+
311
+ this.shareButton = $el("button", {
312
+ type: "submit",
313
+ textContent: "Share",
314
+ style: buttonStyle,
315
+ onclick: () => {
316
+ this.handleShareButtonClick();
317
+ },
318
+ });
319
+
320
+ // Share and Close Buttons
321
+ const buttonsSection = $el(
322
+ "div",
323
+ {
324
+ style: {
325
+ textAlign: "right",
326
+ marginTop: "20px",
327
+ display: "flex",
328
+ justifyContent: "space-between",
329
+ },
330
+ },
331
+ [
332
+ $el("button", {
333
+ type: "button",
334
+ textContent: "Close",
335
+ style: {
336
+ ...buttonStyle,
337
+ backgroundColor: undefined,
338
+ },
339
+ onclick: () => {
340
+ this.close();
341
+ },
342
+ }),
343
+ this.shareButton,
344
+ ]
345
+ );
346
+
347
+ // Composing the full layout
348
+ const layout = [
349
+ headerSection,
350
+ linkSection,
351
+ accountSection,
352
+ outputUploadSection,
353
+ this.outputsSection,
354
+ additionalInputsSection,
355
+ // contestSection,
356
+ this.message,
357
+ buttonsSection,
358
+ ];
359
+
360
+ return layout;
361
+ }
362
+
363
+ async fetchApi(path, options, statusText) {
364
+ if (statusText) {
365
+ this.message.textContent = statusText;
366
+ }
367
+ const addSearchParams = (url, params = {}) =>
368
+ new URL(
369
+ `${url.origin}${url.pathname}?${new URLSearchParams([
370
+ ...Array.from(url.searchParams.entries()),
371
+ ...Object.entries(params),
372
+ ])}`
373
+ );
374
+
375
+ const fullPath = addSearchParams(new URL(API_ENDPOINT + path), {
376
+ workflow_api_key: this.keyInput.value,
377
+ });
378
+
379
+ const response = await fetch(fullPath, options);
380
+
381
+ if (!response.ok) {
382
+ throw new Error(response.statusText);
383
+ }
384
+
385
+ if (statusText) {
386
+ this.message.textContent = "";
387
+ }
388
+ const data = await response.json();
389
+ return {
390
+ ok: response.ok,
391
+ statusText: response.statusText,
392
+ status: response.status,
393
+ data,
394
+ };
395
+ }
396
+
397
+ async uploadThumbnail(uploadFile) {
398
+ const form = new FormData();
399
+ form.append("file", uploadFile);
400
+ try {
401
+ const res = await this.fetchApi(
402
+ `/workflows/upload_thumbnail`,
403
+ {
404
+ method: "POST",
405
+ body: form,
406
+ },
407
+ "Uploading thumbnail..."
408
+ );
409
+
410
+ if (res.ok && res.data) {
411
+ const {image_url, width, height} = res.data;
412
+ this.uploadedImages.push({
413
+ url: image_url,
414
+ width,
415
+ height,
416
+ });
417
+ }
418
+ } catch (e) {
419
+ if (e?.response?.status === 413) {
420
+ throw new Error("File size is too large (max 20MB)");
421
+ } else {
422
+ throw new Error("Error uploading thumbnail: " + e.message);
423
+ }
424
+ }
425
+ }
426
+
427
+ async handleShareButtonClick() {
428
+ this.message.textContent = "";
429
+ await this.saveKey(this.keyInput.value);
430
+ try {
431
+ this.shareButton.disabled = true;
432
+ this.shareButton.textContent = "Sharing...";
433
+ await this.share();
434
+ } catch (e) {
435
+ customAlert(e.message);
436
+ }
437
+ this.shareButton.disabled = false;
438
+ this.shareButton.textContent = "Share";
439
+ }
440
+
441
+ async share() {
442
+ const prompt = await app.graphToPrompt();
443
+ const workflowJSON = prompt["workflow"];
444
+ const workflowAPIJSON = prompt["output"];
445
+ const form_values = {
446
+ name: this.NameInput.value,
447
+ description: this.descriptionInput.value,
448
+ };
449
+
450
+ if (!this.keyInput.value) {
451
+ throw new Error("API key is required");
452
+ }
453
+
454
+ if (!this.uploadImagesInput.files[0] && !this.selectedFile) {
455
+ throw new Error("Thumbnail is required");
456
+ }
457
+
458
+ if (!form_values.name) {
459
+ throw new Error("Title is required");
460
+ }
461
+
462
+ const current_snapshot = await api.fetchApi(`/snapshot/get_current`)
463
+ .then(response => response.json())
464
+ .catch(error => {
465
+ // console.log(error);
466
+ });
467
+
468
+
469
+ if (!this.uploadedImages.length) {
470
+ if (this.selectedFile) {
471
+ await this.uploadThumbnail(this.selectedFile);
472
+ } else {
473
+ for (const file of this.uploadImagesInput.files) {
474
+ try {
475
+ await this.uploadThumbnail(file);
476
+ } catch (e) {
477
+ this.uploadedImages = [];
478
+ throw new Error(e.message);
479
+ }
480
+ }
481
+
482
+ if (this.uploadImagesInput.files.length === 0) {
483
+ throw new Error("No thumbnail uploaded");
484
+ }
485
+ }
486
+ }
487
+
488
+ // const join_contest = this.joinContestCheckbox.checked;
489
+
490
+ try {
491
+ const response = await this.fetchApi(
492
+ "/workflows/publish",
493
+ {
494
+ method: "POST",
495
+ headers: {"Content-Type": "application/json"},
496
+ body: JSON.stringify({
497
+ workflow_json: workflowJSON,
498
+ upload_images: this.uploadedImages,
499
+ form_values,
500
+ advanced_config: {
501
+ workflow_api_json: workflowAPIJSON,
502
+ snapshot: current_snapshot,
503
+ },
504
+ // join_contest,
505
+ }),
506
+ },
507
+ "Uploading workflow..."
508
+ );
509
+
510
+ if (response.ok) {
511
+ const {workflow_id} = response.data;
512
+ if (workflow_id) {
513
+ const url = `https://openart.ai/workflows/-/-/${workflow_id}`;
514
+ this.message.innerHTML = `Workflow has been shared successfully. <a href="${url}" target="_blank">Click here to view it.</a>`;
515
+ this.previewImage.src = "";
516
+ this.previewImage.style.display = "none";
517
+ this.uploadedImages = [];
518
+ this.NameInput.value = "";
519
+ this.descriptionInput.value = "";
520
+ this.radioButtons.forEach((ele) => {
521
+ ele.checked = false;
522
+ ele.parentElement.classList.remove("checked");
523
+ });
524
+ this.selectedOutputIndex = 0;
525
+ this.selectedNodeId = null;
526
+ this.selectedFile = null;
527
+ }
528
+ }
529
+ } catch (e) {
530
+ throw new Error("Error sharing workflow: " + e.message);
531
+ }
532
+ }
533
+
534
+ async fetchImageBlob(url) {
535
+ const response = await fetch(url);
536
+ const blob = await response.blob();
537
+ return blob;
538
+ }
539
+
540
+ async show({potential_outputs, potential_output_nodes} = {}) {
541
+ // Sort `potential_output_nodes` by node ID to make the order always
542
+ // consistent, but we should also keep `potential_outputs` in the same
543
+ // order as `potential_output_nodes`.
544
+ const potential_output_to_order = {};
545
+ potential_output_nodes.forEach((node, index) => {
546
+ if (node.id in potential_output_to_order) {
547
+ potential_output_to_order[node.id][1].push(potential_outputs[index]);
548
+ } else {
549
+ potential_output_to_order[node.id] = [node, [potential_outputs[index]]];
550
+ }
551
+ })
552
+ // Sort the object `potential_output_to_order` by key (node ID)
553
+ const sorted_potential_output_to_order = Object.fromEntries(
554
+ Object.entries(potential_output_to_order).sort((a, b) => a[0].id - b[0].id)
555
+ );
556
+ const sorted_potential_outputs = []
557
+ const sorted_potential_output_nodes = []
558
+ for (const [key, value] of Object.entries(sorted_potential_output_to_order)) {
559
+ sorted_potential_output_nodes.push(value[0]);
560
+ sorted_potential_outputs.push(...value[1]);
561
+ }
562
+ potential_output_nodes = sorted_potential_output_nodes;
563
+ potential_outputs = sorted_potential_outputs;
564
+
565
+ this.message.innerHTML = "";
566
+ this.message.textContent = "";
567
+ this.element.style.display = "block";
568
+ this.previewImage.src = "";
569
+ this.previewImage.style.display = "none";
570
+ const key = await this.readKey();
571
+ this.keyInput.value = key;
572
+ this.uploadedImages = [];
573
+
574
+ // If `selectedNodeId` is provided, we will select the corresponding radio
575
+ // button for the node. In addition, we move the selected radio button to
576
+ // the top of the list.
577
+ if (this.selectedNodeId) {
578
+ const index = potential_output_nodes.findIndex(node => node.id === this.selectedNodeId);
579
+ if (index >= 0) {
580
+ this.selectedOutputIndex = index;
581
+ }
582
+ }
583
+
584
+ this.radioButtons = [];
585
+ const new_radio_buttons = $el("div",
586
+ {
587
+ id: "selectOutput-Options",
588
+ style: {
589
+ 'overflow-y': 'scroll',
590
+ 'max-height': '200px',
591
+
592
+ 'display': 'grid',
593
+ 'grid-template-columns': 'repeat(auto-fit, minmax(100px, 1fr))',
594
+ 'grid-template-rows': 'auto',
595
+ 'grid-column-gap': '10px',
596
+ 'grid-row-gap': '10px',
597
+ 'margin-bottom': '10px',
598
+ 'padding': '10px',
599
+ 'border-radius': '8px',
600
+ 'box-shadow': '0 2px 4px rgba(0, 0, 0, 0.05)',
601
+ 'background-color': 'var(--bg-color)',
602
+ }
603
+ },
604
+ potential_outputs.map((output, index) => {
605
+ const {node_id} = output;
606
+ const radio_button = $el("input", {
607
+ type: 'radio',
608
+ name: "selectOutputImages",
609
+ value: index,
610
+ required: index === 0
611
+ }, [])
612
+ let radio_button_img;
613
+ let filename;
614
+ if (output.type === "image" || output.type === "temp") {
615
+ radio_button_img = $el("img", {
616
+ src: `/view?filename=${output.image.filename}&subfolder=${output.image.subfolder}&type=${output.image.type}`,
617
+ style: {
618
+ width: "100px",
619
+ height: "100px",
620
+ objectFit: "cover",
621
+ borderRadius: "5px"
622
+ }
623
+ }, []);
624
+ filename = output.image.filename
625
+ } else if (output.type === "output") {
626
+ radio_button_img = $el("img", {
627
+ src: output.output.value,
628
+ style: {
629
+ width: "auto",
630
+ height: "100px",
631
+ objectFit: "cover",
632
+ borderRadius: "5px"
633
+ }
634
+ }, []);
635
+ filename = output.filename
636
+ } else {
637
+ // unsupported output type
638
+ // this should never happen
639
+ // TODO
640
+ radio_button_img = $el("img", {
641
+ src: "",
642
+ style: {width: "auto", height: "100px"}
643
+ }, []);
644
+ }
645
+ const radio_button_text = $el("span", {
646
+ style: {
647
+ color: 'gray',
648
+ display: 'block',
649
+ fontSize: '12px',
650
+ overflowX: 'hidden',
651
+ textOverflow: 'ellipsis',
652
+ textWrap: 'nowrap',
653
+ maxWidth: '100px',
654
+ }
655
+ }, [output.title])
656
+ const node_id_chip = $el("span", {
657
+ style: {
658
+ color: '#FBFBFD',
659
+ display: 'block',
660
+ backgroundColor: 'rgba(0, 0, 0, 0.5)',
661
+ fontSize: '12px',
662
+ overflowX: 'hidden',
663
+ padding: '2px 3px',
664
+ textOverflow: 'ellipsis',
665
+ textWrap: 'nowrap',
666
+ maxWidth: '100px',
667
+ position: 'absolute',
668
+ top: '3px',
669
+ left: '3px',
670
+ borderRadius: '3px',
671
+ }
672
+ }, [`Node: ${node_id}`])
673
+ radio_button.style.color = "var(--fg-color)";
674
+ radio_button.checked = this.selectedOutputIndex === index;
675
+
676
+ radio_button.onchange = async () => {
677
+ this.selectedOutputIndex = parseInt(radio_button.value);
678
+
679
+ // Remove the "checked" class from all radio buttons
680
+ this.radioButtons.forEach((ele) => {
681
+ ele.parentElement.classList.remove("checked");
682
+ });
683
+ radio_button.parentElement.classList.add("checked");
684
+
685
+ this.fetchImageBlob(radio_button_img.src).then((blob) => {
686
+ const file = new File([blob], filename, {
687
+ type: blob.type,
688
+ });
689
+ this.previewImage.src = radio_button_img.src;
690
+ this.previewImage.style.display = "block";
691
+ this.selectedFile = file;
692
+ })
693
+
694
+ // Add the opacity style toggle here to indicate that they only need
695
+ // to upload one image or choose one from the outputs.
696
+ this.outputsSection.style.opacity = 1;
697
+ this.uploadImagesInput.style.opacity = 0.35;
698
+ };
699
+
700
+ if (radio_button.checked) {
701
+ this.fetchImageBlob(radio_button_img.src).then((blob) => {
702
+ const file = new File([blob], filename, {
703
+ type: blob.type,
704
+ });
705
+ this.previewImage.src = radio_button_img.src;
706
+ this.previewImage.style.display = "block";
707
+ this.selectedFile = file;
708
+ })
709
+ // Add the opacity style toggle here to indicate that they only need
710
+ // to upload one image or choose one from the outputs.
711
+ this.outputsSection.style.opacity = 1;
712
+ this.uploadImagesInput.style.opacity = 0.35;
713
+ }
714
+
715
+ this.radioButtons.push(radio_button);
716
+
717
+ return $el(`label.output_label${radio_button.checked ? '.checked' : ''}`, {
718
+ style: {
719
+ display: "flex",
720
+ flexDirection: "column",
721
+ alignItems: "center",
722
+ justifyContent: "center",
723
+ marginBottom: "10px",
724
+ cursor: "pointer",
725
+ position: 'relative',
726
+ }
727
+ }, [radio_button_img, radio_button_text, radio_button, node_id_chip]);
728
+ })
729
+ );
730
+
731
+ const header =
732
+ $el("p", {
733
+ textContent: this.radioButtons.length === 0 ? "Queue Prompt to see the outputs" : "Or choose one from the outputs (scroll to see all)",
734
+ size: 2,
735
+ color: "white",
736
+ style: {
737
+ color: 'var(--input-text)',
738
+ margin: '0 0 5px 0',
739
+ fontSize: '12px',
740
+ },
741
+ }, [])
742
+ this.outputsSection.innerHTML = "";
743
+ this.outputsSection.appendChild(header);
744
+ this.outputsSection.appendChild(new_radio_buttons);
745
+ }
746
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-share-youml.js ADDED
@@ -0,0 +1,569 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {app} from "../../scripts/app.js";
2
+ import {api} from "../../scripts/api.js";
3
+ import {ComfyDialog, $el} from "../../scripts/ui.js";
4
+ import { customAlert } from "./common.js";
5
+
6
+ const BASE_URL = "https://youml.com";
7
+ //const BASE_URL = "http://localhost:3000";
8
+ const DEFAULT_HOMEPAGE_URL = `${BASE_URL}/?from=comfyui`;
9
+ const TOKEN_PAGE_URL = `${BASE_URL}/my-token`;
10
+ const API_ENDPOINT = `${BASE_URL}/api`;
11
+
12
+ const style = `
13
+ .youml-share-dialog {
14
+ overflow-y: auto;
15
+ }
16
+ .youml-share-dialog .dialog-header {
17
+ text-align: center;
18
+ color: white;
19
+ margin: 0 0 10px 0;
20
+ }
21
+ .youml-share-dialog .dialog-section {
22
+ margin-bottom: 0;
23
+ padding: 0;
24
+ border-radius: 8px;
25
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
26
+ display: flex;
27
+ flex-direction: column;
28
+ justify-content: center;
29
+ }
30
+ .youml-share-dialog input, .youml-share-dialog textarea {
31
+ display: block;
32
+ min-width: 500px;
33
+ width: 100%;
34
+ padding: 10px;
35
+ margin: 10px 0;
36
+ border-radius: 4px;
37
+ border: 1px solid #ddd;
38
+ box-sizing: border-box;
39
+ }
40
+ .youml-share-dialog textarea {
41
+ color: var(--input-text);
42
+ background-color: var(--comfy-input-bg);
43
+ }
44
+ .youml-share-dialog .workflow-description {
45
+ min-height: 75px;
46
+ }
47
+ .youml-share-dialog label {
48
+ color: #f8f8f8;
49
+ display: block;
50
+ margin: 5px 0 0 0;
51
+ font-weight: bold;
52
+ text-decoration: none;
53
+ }
54
+ .youml-share-dialog .action-button {
55
+ padding: 10px 80px;
56
+ margin: 10px 5px;
57
+ border-radius: 4px;
58
+ border: none;
59
+ cursor: pointer;
60
+ }
61
+ .youml-share-dialog .share-button {
62
+ color: #fff;
63
+ background-color: #007bff;
64
+ }
65
+ .youml-share-dialog .close-button {
66
+ background-color: none;
67
+ }
68
+ .youml-share-dialog .action-button-panel {
69
+ text-align: right;
70
+ display: flex;
71
+ justify-content: space-between;
72
+ }
73
+ .youml-share-dialog .status-message {
74
+ color: #fd7909;
75
+ text-align: center;
76
+ padding: 5px;
77
+ font-size: 18px;
78
+ }
79
+ .youml-share-dialog .status-message a {
80
+ color: white;
81
+ }
82
+ .youml-share-dialog .output-panel {
83
+ overflow: auto;
84
+ max-height: 180px;
85
+ display: grid;
86
+ grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
87
+ grid-template-rows: auto;
88
+ grid-column-gap: 10px;
89
+ grid-row-gap: 10px;
90
+ margin-bottom: 10px;
91
+ padding: 10px;
92
+ border-radius: 8px;
93
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
94
+ background-color: var(--bg-color);
95
+ }
96
+ .youml-share-dialog .output-panel .output-image {
97
+ width: 100px;
98
+ height: 100px;
99
+ objectFit: cover;
100
+ borderRadius: 5px;
101
+ }
102
+
103
+ .youml-share-dialog .output-panel .radio-button {
104
+ color:var(--fg-color);
105
+ }
106
+ .youml-share-dialog .output-panel .radio-text {
107
+ color: gray;
108
+ display: block;
109
+ font-size: 12px;
110
+ overflow-x: hidden;
111
+ text-overflow: ellipsis;
112
+ text-wrap: nowrap;
113
+ max-width: 100px;
114
+ }
115
+ .youml-share-dialog .output-panel .node-id {
116
+ color: #FBFBFD;
117
+ display: block;
118
+ background-color: rgba(0, 0, 0, 0.5);
119
+ font-size: 12px;
120
+ overflow-x: hidden;
121
+ padding: 2px 3px;
122
+ text-overflow: ellipsis;
123
+ text-wrap: nowrap;
124
+ max-width: 100px;
125
+ position: absolute;
126
+ top: 3px;
127
+ left: 3px;
128
+ border-radius: 3px;
129
+ }
130
+ .youml-share-dialog .output-panel .output-label {
131
+ display: flex;
132
+ flex-direction: column;
133
+ align-items: center;
134
+ justify-content: center;
135
+ margin-bottom: 10px;
136
+ cursor: pointer;
137
+ position: relative;
138
+ border: 5px solid transparent;
139
+ }
140
+ .youml-share-dialog .output-panel .output-label:hover {
141
+ border: 5px solid #007bff;
142
+ }
143
+ .youml-share-dialog .output-panel .output-label.checked {
144
+ border: 5px solid #007bff;
145
+ }
146
+ .youml-share-dialog .missing-output-message{
147
+ color: #fd7909;
148
+ font-size: 16px;
149
+ margin-bottom:10px
150
+ }
151
+ .youml-share-dialog .select-output-message{
152
+ color: white;
153
+ margin-bottom:5px
154
+ }
155
+ `;
156
+
157
+ export class YouMLShareDialog extends ComfyDialog {
158
+ static instance = null;
159
+
160
+ constructor() {
161
+ super();
162
+ $el("style", {
163
+ textContent: style,
164
+ parent: document.head,
165
+ });
166
+ this.element = $el(
167
+ "div.comfy-modal.youml-share-dialog",
168
+ {
169
+ parent: document.body,
170
+ },
171
+ [$el("div.comfy-modal-content", {}, [...this.createLayout()])]
172
+ );
173
+ this.selectedOutputIndex = 0;
174
+ this.selectedNodeId = null;
175
+ this.uploadedImages = [];
176
+ this.selectedFile = null;
177
+ }
178
+
179
+ async loadToken() {
180
+ let key = ""
181
+ try {
182
+ const response = await api.fetchApi(`/manager/youml/settings`)
183
+ const settings = await response.json()
184
+ return settings.token
185
+ } catch (error) {
186
+ }
187
+ return key || "";
188
+ }
189
+
190
+ async saveToken(value) {
191
+ await api.fetchApi(`/manager/youml/settings`, {
192
+ method: 'POST',
193
+ headers: {'Content-Type': 'application/json'},
194
+ body: JSON.stringify({
195
+ token: value
196
+ })
197
+ });
198
+ }
199
+
200
+ createLayout() {
201
+ // Header Section
202
+ const headerSection = $el("h3.dialog-header", {
203
+ textContent: "Share your workflow to YouML.com",
204
+ size: 3,
205
+ });
206
+
207
+ // Workflow Info Section
208
+ this.nameInput = $el("input", {
209
+ type: "text",
210
+ placeholder: "Name (required)",
211
+ });
212
+ this.descriptionInput = $el("textarea.workflow-description", {
213
+ placeholder: "Description (optional, markdown supported)",
214
+ });
215
+ const workflowMetadata = $el("div.dialog-section", {}, [
216
+ $el("label", {}, ["Workflow info"]),
217
+ this.nameInput,
218
+ this.descriptionInput,
219
+ ]);
220
+
221
+ // Outputs Section
222
+ this.outputsSection = $el("div.dialog-section", {
223
+ id: "selectOutputs",
224
+ }, []);
225
+
226
+ const outputUploadSection = $el("div.dialog-section", {}, [
227
+ $el("label", {}, ["Thumbnail"]),
228
+ this.outputsSection,
229
+ ]);
230
+
231
+ // API Token Section
232
+ this.apiTokenInput = $el("input", {
233
+ type: "password",
234
+ placeholder: "Copy & paste your API token",
235
+ });
236
+ const getAPITokenButton = $el("button", {
237
+ href: DEFAULT_HOMEPAGE_URL,
238
+ target: "_blank",
239
+ onclick: () => window.open(TOKEN_PAGE_URL, "_blank"),
240
+ }, ["Get your API Token"])
241
+
242
+ const apiTokenSection = $el("div.dialog-section", {}, [
243
+ $el("label", {}, ["YouML API Token"]),
244
+ this.apiTokenInput,
245
+ getAPITokenButton,
246
+ ]);
247
+
248
+ // Message Section
249
+ this.message = $el("div.status-message", {}, []);
250
+
251
+ // Share and Close Buttons
252
+ this.shareButton = $el("button.action-button.share-button", {
253
+ type: "submit",
254
+ textContent: "Share",
255
+ onclick: () => {
256
+ this.handleShareButtonClick();
257
+ },
258
+ });
259
+
260
+ const buttonsSection = $el(
261
+ "div.action-button-panel",
262
+ {},
263
+ [
264
+ $el("button.action-button.close-button", {
265
+ type: "button",
266
+ textContent: "Close",
267
+ onclick: () => {
268
+ this.close();
269
+ },
270
+ }),
271
+ this.shareButton,
272
+ ]
273
+ );
274
+
275
+ // Composing the full layout
276
+ const layout = [
277
+ headerSection,
278
+ workflowMetadata,
279
+ outputUploadSection,
280
+ apiTokenSection,
281
+ this.message,
282
+ buttonsSection,
283
+ ];
284
+
285
+ return layout;
286
+ }
287
+
288
+ async fetchYoumlApi(path, options, statusText) {
289
+ if (statusText) {
290
+ this.message.textContent = statusText;
291
+ }
292
+
293
+ const fullPath = new URL(API_ENDPOINT + path)
294
+
295
+ const fetchOptions = Object.assign({}, options)
296
+
297
+ fetchOptions.headers = {
298
+ ...fetchOptions.headers,
299
+ "Authorization": `Bearer ${this.apiTokenInput.value}`,
300
+ "User-Agent": "ComfyUI-Manager-Youml/1.0.0",
301
+ }
302
+
303
+ const response = await fetch(fullPath, fetchOptions);
304
+
305
+ if (!response.ok) {
306
+ throw new Error(response.statusText + " " + (await response.text()));
307
+ }
308
+
309
+ if (statusText) {
310
+ this.message.textContent = "";
311
+ }
312
+ const data = await response.json();
313
+ return {
314
+ ok: response.ok,
315
+ statusText: response.statusText,
316
+ status: response.status,
317
+ data,
318
+ };
319
+ }
320
+
321
+ async uploadThumbnail(uploadFile, recipeId) {
322
+ const form = new FormData();
323
+ form.append("file", uploadFile, uploadFile.name);
324
+ try {
325
+ const res = await this.fetchYoumlApi(
326
+ `/v1/comfy/recipes/${recipeId}/thumbnail`,
327
+ {
328
+ method: "POST",
329
+ body: form,
330
+ },
331
+ "Uploading thumbnail..."
332
+ );
333
+
334
+ } catch (e) {
335
+ if (e?.response?.status === 413) {
336
+ throw new Error("File size is too large (max 20MB)");
337
+ } else {
338
+ throw new Error("Error uploading thumbnail: " + e.message);
339
+ }
340
+ }
341
+ }
342
+
343
+ async handleShareButtonClick() {
344
+ this.message.textContent = "";
345
+ await this.saveToken(this.apiTokenInput.value);
346
+ try {
347
+ this.shareButton.disabled = true;
348
+ this.shareButton.textContent = "Sharing...";
349
+ await this.share();
350
+ } catch (e) {
351
+ customAlert(e.message);
352
+ } finally {
353
+ this.shareButton.disabled = false;
354
+ this.shareButton.textContent = "Share";
355
+ }
356
+ }
357
+
358
+ async share() {
359
+ const prompt = await app.graphToPrompt();
360
+ const workflowJSON = prompt["workflow"];
361
+ const workflowAPIJSON = prompt["output"];
362
+ const form_values = {
363
+ name: this.nameInput.value,
364
+ description: this.descriptionInput.value,
365
+ };
366
+
367
+ if (!this.apiTokenInput.value) {
368
+ throw new Error("API token is required");
369
+ }
370
+
371
+ if (!this.selectedFile) {
372
+ throw new Error("Thumbnail is required");
373
+ }
374
+
375
+ if (!form_values.name) {
376
+ throw new Error("Title is required");
377
+ }
378
+
379
+
380
+ try {
381
+ let snapshotData = null;
382
+ try {
383
+ const snapshot = await api.fetchApi(`/snapshot/get_current`)
384
+ snapshotData = await snapshot.json()
385
+ } catch (e) {
386
+ console.error("Failed to get snapshot", e)
387
+ }
388
+
389
+ const request = {
390
+ name: this.nameInput.value,
391
+ description: this.descriptionInput.value,
392
+ workflowUiJson: JSON.stringify(workflowJSON),
393
+ workflowApiJson: JSON.stringify(workflowAPIJSON),
394
+ }
395
+
396
+ if (snapshotData) {
397
+ request.snapshotJson = JSON.stringify(snapshotData)
398
+ }
399
+
400
+ const response = await this.fetchYoumlApi(
401
+ "/v1/comfy/recipes",
402
+ {
403
+ method: "POST",
404
+ headers: {"Content-Type": "application/json"},
405
+ body: JSON.stringify(request),
406
+ },
407
+ "Uploading workflow..."
408
+ );
409
+
410
+ if (response.ok) {
411
+ const {id, recipePageUrl, editorPageUrl} = response.data;
412
+ if (id) {
413
+ let messagePrefix = "Workflow has been shared."
414
+ if (this.selectedFile) {
415
+ try {
416
+ await this.uploadThumbnail(this.selectedFile, id);
417
+ } catch (e) {
418
+ console.error("Thumbnail upload failed: ", e);
419
+ messagePrefix = "Workflow has been shared, but thumbnail upload failed. You can create a thumbnail on YouML later."
420
+ }
421
+ }
422
+ this.message.innerHTML = `${messagePrefix} To turn your workflow into an interactive app, ` +
423
+ `<a href="${recipePageUrl}" target="_blank">visit it on YouML</a>`;
424
+
425
+ this.uploadedImages = [];
426
+ this.nameInput.value = "";
427
+ this.descriptionInput.value = "";
428
+ this.radioButtons.forEach((ele) => {
429
+ ele.checked = false;
430
+ ele.parentElement.classList.remove("checked");
431
+ });
432
+ this.selectedOutputIndex = 0;
433
+ this.selectedNodeId = null;
434
+ this.selectedFile = null;
435
+ }
436
+ }
437
+ } catch (e) {
438
+ throw new Error("Error sharing workflow: " + e.message);
439
+ }
440
+ }
441
+
442
+ async fetchImageBlob(url) {
443
+ const response = await fetch(url);
444
+ const blob = await response.blob();
445
+ return blob;
446
+ }
447
+
448
+ async show(potentialOutputs, potentialOutputNodes) {
449
+ const potentialOutputsToOrder = {};
450
+ potentialOutputNodes.forEach((node, index) => {
451
+ if (node.id in potentialOutputsToOrder) {
452
+ potentialOutputsToOrder[node.id][1].push(potentialOutputs[index]);
453
+ } else {
454
+ potentialOutputsToOrder[node.id] = [node, [potentialOutputs[index]]];
455
+ }
456
+ })
457
+ const sortedPotentialOutputsToOrder = Object.fromEntries(
458
+ Object.entries(potentialOutputsToOrder).sort((a, b) => a[0].id - b[0].id)
459
+ );
460
+ const sortedPotentialOutputs = []
461
+ const sortedPotentiaOutputNodes = []
462
+ for (const [key, value] of Object.entries(sortedPotentialOutputsToOrder)) {
463
+ sortedPotentiaOutputNodes.push(value[0]);
464
+ sortedPotentialOutputs.push(...value[1]);
465
+ }
466
+ potentialOutputNodes = sortedPotentiaOutputNodes;
467
+ potentialOutputs = sortedPotentialOutputs;
468
+
469
+
470
+ // If `selectedNodeId` is provided, we will select the corresponding radio
471
+ // button for the node. In addition, we move the selected radio button to
472
+ // the top of the list.
473
+ if (this.selectedNodeId) {
474
+ const index = potentialOutputNodes.findIndex(node => node.id === this.selectedNodeId);
475
+ if (index >= 0) {
476
+ this.selectedOutputIndex = index;
477
+ }
478
+ }
479
+
480
+ this.radioButtons = [];
481
+ const newRadioButtons = $el("div.output-panel",
482
+ {
483
+ id: "selectOutput-Options",
484
+ },
485
+ potentialOutputs.map((output, index) => {
486
+ const {node_id: nodeId} = output;
487
+ const radioButton = $el("input.radio-button", {
488
+ type: "radio",
489
+ name: "selectOutputImages",
490
+ value: index,
491
+ required: index === 0
492
+ }, [])
493
+ let radioButtonImage;
494
+ let filename;
495
+ if (output.type === "image" || output.type === "temp") {
496
+ radioButtonImage = $el("img.output-image", {
497
+ src: `/view?filename=${output.image.filename}&subfolder=${output.image.subfolder}&type=${output.image.type}`,
498
+ }, []);
499
+ filename = output.image.filename
500
+ } else if (output.type === "output") {
501
+ radioButtonImage = $el("img.output-image", {
502
+ src: output.output.value,
503
+ }, []);
504
+ filename = output.output.filename
505
+ } else {
506
+ radioButtonImage = $el("img.output-image", {
507
+ src: "",
508
+ }, []);
509
+ }
510
+ const radioButtonText = $el("span.radio-text", {}, [output.title])
511
+ const nodeIdChip = $el("span.node-id", {}, [`Node: ${nodeId}`])
512
+ radioButton.checked = this.selectedOutputIndex === index;
513
+
514
+ radioButton.onchange = async () => {
515
+ this.selectedOutputIndex = parseInt(radioButton.value);
516
+
517
+ // Remove the "checked" class from all radio buttons
518
+ this.radioButtons.forEach((ele) => {
519
+ ele.parentElement.classList.remove("checked");
520
+ });
521
+ radioButton.parentElement.classList.add("checked");
522
+
523
+ this.fetchImageBlob(radioButtonImage.src).then((blob) => {
524
+ const file = new File([blob], filename, {
525
+ type: blob.type,
526
+ });
527
+ this.selectedFile = file;
528
+ })
529
+ };
530
+
531
+ if (radioButton.checked) {
532
+ this.fetchImageBlob(radioButtonImage.src).then((blob) => {
533
+ const file = new File([blob], filename, {
534
+ type: blob.type,
535
+ });
536
+ this.selectedFile = file;
537
+ })
538
+ }
539
+
540
+ this.radioButtons.push(radioButton);
541
+
542
+ return $el(`label.output-label${radioButton.checked ? '.checked' : ''}`, {},
543
+ [radioButtonImage, radioButtonText, radioButton, nodeIdChip]);
544
+ })
545
+ );
546
+
547
+ let header;
548
+ if (this.radioButtons.length === 0) {
549
+ header = $el("div.missing-output-message", {textContent: "Queue Prompt to see the outputs and select a thumbnail"}, [])
550
+ } else {
551
+ header = $el("div.select-output-message", {textContent: "Choose one from the outputs (scroll to see all)"}, [])
552
+ }
553
+
554
+ this.outputsSection.innerHTML = "";
555
+ this.outputsSection.appendChild(header);
556
+ if (this.radioButtons.length > 0) {
557
+ this.outputsSection.appendChild(newRadioButtons);
558
+ }
559
+
560
+ this.message.innerHTML = "";
561
+ this.message.textContent = "";
562
+
563
+ const token = await this.loadToken();
564
+ this.apiTokenInput.value = token;
565
+ this.uploadedImages = [];
566
+
567
+ this.element.style.display = "block";
568
+ }
569
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/js/common.js ADDED
@@ -0,0 +1,654 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../scripts/app.js";
2
+ import { api } from "../../scripts/api.js";
3
+ import { $el, ComfyDialog } from "../../scripts/ui.js";
4
+ import { getBestPosition, getPositionStyle, getRect } from './popover-helper.js';
5
+
6
+
7
+ function internalCustomConfirm(message, confirmMessage, cancelMessage) {
8
+ return new Promise((resolve) => {
9
+ // transparent bg
10
+ const modalOverlay = document.createElement('div');
11
+ modalOverlay.style.position = 'fixed';
12
+ modalOverlay.style.top = 0;
13
+ modalOverlay.style.left = 0;
14
+ modalOverlay.style.width = '100%';
15
+ modalOverlay.style.height = '100%';
16
+ modalOverlay.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
17
+ modalOverlay.style.display = 'flex';
18
+ modalOverlay.style.alignItems = 'center';
19
+ modalOverlay.style.justifyContent = 'center';
20
+ modalOverlay.style.zIndex = '1101';
21
+
22
+ // Modal window container (dark bg)
23
+ const modalDialog = document.createElement('div');
24
+ modalDialog.style.backgroundColor = '#333';
25
+ modalDialog.style.padding = '20px';
26
+ modalDialog.style.borderRadius = '4px';
27
+ modalDialog.style.maxWidth = '400px';
28
+ modalDialog.style.width = '80%';
29
+ modalDialog.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.5)';
30
+ modalDialog.style.color = '#fff';
31
+
32
+ // Display message
33
+ const modalMessage = document.createElement('p');
34
+ modalMessage.textContent = message;
35
+ modalMessage.style.margin = '0';
36
+ modalMessage.style.padding = '0 0 20px';
37
+ modalMessage.style.wordBreak = 'keep-all';
38
+
39
+ // Button container
40
+ const modalButtons = document.createElement('div');
41
+ modalButtons.style.display = 'flex';
42
+ modalButtons.style.justifyContent = 'flex-end';
43
+
44
+ // Confirm button (green)
45
+ const confirmButton = document.createElement('button');
46
+ if(confirmMessage)
47
+ confirmButton.textContent = confirmMessage;
48
+ else
49
+ confirmButton.textContent = 'Confirm';
50
+ confirmButton.style.marginLeft = '10px';
51
+ confirmButton.style.backgroundColor = '#28a745'; // green
52
+ confirmButton.style.color = '#fff';
53
+ confirmButton.style.border = 'none';
54
+ confirmButton.style.padding = '6px 12px';
55
+ confirmButton.style.borderRadius = '4px';
56
+ confirmButton.style.cursor = 'pointer';
57
+ confirmButton.style.fontWeight = 'bold';
58
+
59
+ // Cancel button (red)
60
+ const cancelButton = document.createElement('button');
61
+ if(cancelMessage)
62
+ cancelButton.textContent = cancelMessage;
63
+ else
64
+ cancelButton.textContent = 'Cancel';
65
+
66
+ cancelButton.style.marginLeft = '10px';
67
+ cancelButton.style.backgroundColor = '#dc3545'; // red
68
+ cancelButton.style.color = '#fff';
69
+ cancelButton.style.border = 'none';
70
+ cancelButton.style.padding = '6px 12px';
71
+ cancelButton.style.borderRadius = '4px';
72
+ cancelButton.style.cursor = 'pointer';
73
+ cancelButton.style.fontWeight = 'bold';
74
+
75
+ const closeModal = () => {
76
+ document.body.removeChild(modalOverlay);
77
+ };
78
+
79
+ confirmButton.addEventListener('click', () => {
80
+ closeModal();
81
+ resolve(true);
82
+ });
83
+
84
+ cancelButton.addEventListener('click', () => {
85
+ closeModal();
86
+ resolve(false);
87
+ });
88
+
89
+ modalButtons.appendChild(confirmButton);
90
+ modalButtons.appendChild(cancelButton);
91
+ modalDialog.appendChild(modalMessage);
92
+ modalDialog.appendChild(modalButtons);
93
+ modalOverlay.appendChild(modalDialog);
94
+ document.body.appendChild(modalOverlay);
95
+ });
96
+ }
97
+
98
+ export function show_message(msg) {
99
+ app.ui.dialog.show(msg);
100
+ app.ui.dialog.element.style.zIndex = 1100;
101
+ }
102
+
103
+ export async function sleep(ms) {
104
+ return new Promise(resolve => setTimeout(resolve, ms));
105
+ }
106
+
107
+ export async function customConfirm(message) {
108
+ try {
109
+ let res = await
110
+ window['app'].extensionManager.dialog
111
+ .confirm({
112
+ title: 'Confirm',
113
+ message: message
114
+ });
115
+
116
+ return res;
117
+ }
118
+ catch {
119
+ let res = await internalCustomConfirm(message);
120
+ return res;
121
+ }
122
+ }
123
+
124
+
125
+ export function customAlert(message) {
126
+ try {
127
+ window['app'].extensionManager.toast.addAlert(message);
128
+ }
129
+ catch {
130
+ alert(message);
131
+ }
132
+ }
133
+
134
+ export function infoToast(summary, message) {
135
+ try {
136
+ app.extensionManager.toast.add({
137
+ severity: 'info',
138
+ summary: summary,
139
+ detail: message,
140
+ life: 3000
141
+ })
142
+ }
143
+ catch {
144
+ // do nothing
145
+ }
146
+ }
147
+
148
+
149
+ export async function customPrompt(title, message) {
150
+ try {
151
+ let res = await
152
+ window['app'].extensionManager.dialog
153
+ .prompt({
154
+ title: title,
155
+ message: message
156
+ });
157
+
158
+ return res;
159
+ }
160
+ catch {
161
+ return prompt(title, message)
162
+ }
163
+ }
164
+
165
+
166
+ export function rebootAPI() {
167
+ if ('electronAPI' in window) {
168
+ window.electronAPI.restartApp();
169
+ return true;
170
+ }
171
+
172
+ customConfirm("Are you sure you'd like to reboot the server?").then((isConfirmed) => {
173
+ if (isConfirmed) {
174
+ try {
175
+ api.fetchApi("/manager/reboot");
176
+ }
177
+ catch(exception) {}
178
+ }
179
+ });
180
+
181
+ return false;
182
+ }
183
+
184
+
185
+ export var manager_instance = null;
186
+
187
+ export function setManagerInstance(obj) {
188
+ manager_instance = obj;
189
+ }
190
+
191
+ export function showToast(message, duration = 3000) {
192
+ const toast = $el("div.comfy-toast", {textContent: message});
193
+ document.body.appendChild(toast);
194
+ setTimeout(() => {
195
+ toast.classList.add("comfy-toast-fadeout");
196
+ setTimeout(() => toast.remove(), 500);
197
+ }, duration);
198
+ }
199
+
200
+ function isValidURL(url) {
201
+ if(url.includes('&'))
202
+ return false;
203
+
204
+ const http_pattern = /^(https?|ftp):\/\/[^\s$?#]+$/;
205
+ const ssh_pattern = /^(.+@|ssh:\/\/).+:.+$/;
206
+ return http_pattern.test(url) || ssh_pattern.test(url);
207
+ }
208
+
209
+ export async function install_pip(packages) {
210
+ if(packages.includes('&'))
211
+ app.ui.dialog.show(`Invalid PIP package enumeration: '${packages}'`);
212
+
213
+ const res = await api.fetchApi("/customnode/install/pip", {
214
+ method: "POST",
215
+ body: packages,
216
+ });
217
+
218
+ if(res.status == 403) {
219
+ show_message('This action is not allowed with this security level configuration.');
220
+ return;
221
+ }
222
+
223
+ if(res.status == 200) {
224
+ show_message(`PIP package installation is processed.<br>To apply the pip packages, please click the <button id='cm-reboot-button3'><font size='3px'>RESTART</font></button> button in ComfyUI.`);
225
+
226
+ const rebootButton = document.getElementById('cm-reboot-button3');
227
+ const self = this;
228
+
229
+ rebootButton.addEventListener("click", rebootAPI);
230
+ }
231
+ else {
232
+ show_message(`Failed to install '${packages}'<BR>See terminal log.`);
233
+ }
234
+ }
235
+
236
+ export async function install_via_git_url(url, manager_dialog) {
237
+ if(!url) {
238
+ return;
239
+ }
240
+
241
+ if(!isValidURL(url)) {
242
+ show_message(`Invalid Git url '${url}'`);
243
+ return;
244
+ }
245
+
246
+ show_message(`Wait...<BR><BR>Installing '${url}'`);
247
+
248
+ const res = await api.fetchApi("/customnode/install/git_url", {
249
+ method: "POST",
250
+ body: url,
251
+ });
252
+
253
+ if(res.status == 403) {
254
+ show_message('This action is not allowed with this security level configuration.');
255
+ return;
256
+ }
257
+
258
+ if(res.status == 200) {
259
+ show_message(`'${url}' is installed<BR>To apply the installed custom node, please <button id='cm-reboot-button4'><font size='3px'>RESTART</font></button> ComfyUI.`);
260
+
261
+ const rebootButton = document.getElementById('cm-reboot-button4');
262
+ const self = this;
263
+
264
+ rebootButton.addEventListener("click",
265
+ function() {
266
+ if(rebootAPI()) {
267
+ manager_dialog.close();
268
+ }
269
+ });
270
+ }
271
+ else {
272
+ show_message(`Failed to install '${url}'<BR>See terminal log.`);
273
+ }
274
+ }
275
+
276
+ export async function free_models(free_execution_cache) {
277
+ try {
278
+ let mode = "";
279
+ if(free_execution_cache) {
280
+ mode = '{"unload_models": true, "free_memory": true}';
281
+ }
282
+ else {
283
+ mode = '{"unload_models": true}';
284
+ }
285
+
286
+ let res = await api.fetchApi(`/free`, {
287
+ method: 'POST',
288
+ headers: { 'Content-Type': 'application/json' },
289
+ body: mode
290
+ });
291
+
292
+ if (res.status == 200) {
293
+ if(free_execution_cache) {
294
+ showToast("'Models' and 'Execution Cache' have been cleared.", 3000);
295
+ }
296
+ else {
297
+ showToast("Models' have been unloaded.", 3000);
298
+ }
299
+ } else {
300
+ showToast('Unloading of models failed. Installed ComfyUI may be an outdated version.', 5000);
301
+ }
302
+ } catch (error) {
303
+ showToast('An error occurred while trying to unload models.', 5000);
304
+ }
305
+ }
306
+
307
+ export function md5(inputString) {
308
+ const hc = '0123456789abcdef';
309
+ const rh = n => {let j,s='';for(j=0;j<=3;j++) s+=hc.charAt((n>>(j*8+4))&0x0F)+hc.charAt((n>>(j*8))&0x0F);return s;}
310
+ const ad = (x,y) => {let l=(x&0xFFFF)+(y&0xFFFF);let m=(x>>16)+(y>>16)+(l>>16);return (m<<16)|(l&0xFFFF);}
311
+ const rl = (n,c) => (n<<c)|(n>>>(32-c));
312
+ const cm = (q,a,b,x,s,t) => ad(rl(ad(ad(a,q),ad(x,t)),s),b);
313
+ const ff = (a,b,c,d,x,s,t) => cm((b&c)|((~b)&d),a,b,x,s,t);
314
+ const gg = (a,b,c,d,x,s,t) => cm((b&d)|(c&(~d)),a,b,x,s,t);
315
+ const hh = (a,b,c,d,x,s,t) => cm(b^c^d,a,b,x,s,t);
316
+ const ii = (a,b,c,d,x,s,t) => cm(c^(b|(~d)),a,b,x,s,t);
317
+ const sb = x => {
318
+ let i;const nblk=((x.length+8)>>6)+1;const blks=[];for(i=0;i<nblk*16;i++) { blks[i]=0 };
319
+ for(i=0;i<x.length;i++) {blks[i>>2]|=x.charCodeAt(i)<<((i%4)*8);}
320
+ blks[i>>2]|=0x80<<((i%4)*8);blks[nblk*16-2]=x.length*8;return blks;
321
+ }
322
+ let i,x=sb(inputString),a=1732584193,b=-271733879,c=-1732584194,d=271733878,olda,oldb,oldc,oldd;
323
+ for(i=0;i<x.length;i+=16) {olda=a;oldb=b;oldc=c;oldd=d;
324
+ a=ff(a,b,c,d,x[i+ 0], 7, -680876936);d=ff(d,a,b,c,x[i+ 1],12, -389564586);c=ff(c,d,a,b,x[i+ 2],17, 606105819);
325
+ b=ff(b,c,d,a,x[i+ 3],22,-1044525330);a=ff(a,b,c,d,x[i+ 4], 7, -176418897);d=ff(d,a,b,c,x[i+ 5],12, 1200080426);
326
+ c=ff(c,d,a,b,x[i+ 6],17,-1473231341);b=ff(b,c,d,a,x[i+ 7],22, -45705983);a=ff(a,b,c,d,x[i+ 8], 7, 1770035416);
327
+ d=ff(d,a,b,c,x[i+ 9],12,-1958414417);c=ff(c,d,a,b,x[i+10],17, -42063);b=ff(b,c,d,a,x[i+11],22,-1990404162);
328
+ a=ff(a,b,c,d,x[i+12], 7, 1804603682);d=ff(d,a,b,c,x[i+13],12, -40341101);c=ff(c,d,a,b,x[i+14],17,-1502002290);
329
+ b=ff(b,c,d,a,x[i+15],22, 1236535329);a=gg(a,b,c,d,x[i+ 1], 5, -165796510);d=gg(d,a,b,c,x[i+ 6], 9,-1069501632);
330
+ c=gg(c,d,a,b,x[i+11],14, 643717713);b=gg(b,c,d,a,x[i+ 0],20, -373897302);a=gg(a,b,c,d,x[i+ 5], 5, -701558691);
331
+ d=gg(d,a,b,c,x[i+10], 9, 38016083);c=gg(c,d,a,b,x[i+15],14, -660478335);b=gg(b,c,d,a,x[i+ 4],20, -405537848);
332
+ a=gg(a,b,c,d,x[i+ 9], 5, 568446438);d=gg(d,a,b,c,x[i+14], 9,-1019803690);c=gg(c,d,a,b,x[i+ 3],14, -187363961);
333
+ b=gg(b,c,d,a,x[i+ 8],20, 1163531501);a=gg(a,b,c,d,x[i+13], 5,-1444681467);d=gg(d,a,b,c,x[i+ 2], 9, -51403784);
334
+ c=gg(c,d,a,b,x[i+ 7],14, 1735328473);b=gg(b,c,d,a,x[i+12],20,-1926607734);a=hh(a,b,c,d,x[i+ 5], 4, -378558);
335
+ d=hh(d,a,b,c,x[i+ 8],11,-2022574463);c=hh(c,d,a,b,x[i+11],16, 1839030562);b=hh(b,c,d,a,x[i+14],23, -35309556);
336
+ a=hh(a,b,c,d,x[i+ 1], 4,-1530992060);d=hh(d,a,b,c,x[i+ 4],11, 1272893353);c=hh(c,d,a,b,x[i+ 7],16, -155497632);
337
+ b=hh(b,c,d,a,x[i+10],23,-1094730640);a=hh(a,b,c,d,x[i+13], 4, 681279174);d=hh(d,a,b,c,x[i+ 0],11, -358537222);
338
+ c=hh(c,d,a,b,x[i+ 3],16, -722521979);b=hh(b,c,d,a,x[i+ 6],23, 76029189);a=hh(a,b,c,d,x[i+ 9], 4, -640364487);
339
+ d=hh(d,a,b,c,x[i+12],11, -421815835);c=hh(c,d,a,b,x[i+15],16, 530742520);b=hh(b,c,d,a,x[i+ 2],23, -995338651);
340
+ a=ii(a,b,c,d,x[i+ 0], 6, -198630844);d=ii(d,a,b,c,x[i+ 7],10, 1126891415);c=ii(c,d,a,b,x[i+14],15,-1416354905);
341
+ b=ii(b,c,d,a,x[i+ 5],21, -57434055);a=ii(a,b,c,d,x[i+12], 6, 1700485571);d=ii(d,a,b,c,x[i+ 3],10,-1894986606);
342
+ c=ii(c,d,a,b,x[i+10],15, -1051523);b=ii(b,c,d,a,x[i+ 1],21,-2054922799);a=ii(a,b,c,d,x[i+ 8], 6, 1873313359);
343
+ d=ii(d,a,b,c,x[i+15],10, -30611744);c=ii(c,d,a,b,x[i+ 6],15,-1560198380);b=ii(b,c,d,a,x[i+13],21, 1309151649);
344
+ a=ii(a,b,c,d,x[i+ 4], 6, -145523070);d=ii(d,a,b,c,x[i+11],10,-1120210379);c=ii(c,d,a,b,x[i+ 2],15, 718787259);
345
+ b=ii(b,c,d,a,x[i+ 9],21, -343485551);a=ad(a,olda);b=ad(b,oldb);c=ad(c,oldc);d=ad(d,oldd);
346
+ }
347
+ return rh(a)+rh(b)+rh(c)+rh(d);
348
+ }
349
+
350
+ export async function fetchData(route, options) {
351
+ let err;
352
+ const res = await api.fetchApi(route, options).catch(e => {
353
+ err = e;
354
+ });
355
+
356
+ if (!res) {
357
+ return {
358
+ status: 400,
359
+ error: new Error("Unknown Error")
360
+ }
361
+ }
362
+
363
+ const { status, statusText } = res;
364
+ if (err) {
365
+ return {
366
+ status,
367
+ error: err
368
+ }
369
+ }
370
+
371
+ if (status !== 200) {
372
+ return {
373
+ status,
374
+ error: new Error(statusText || "Unknown Error")
375
+ }
376
+ }
377
+
378
+ const data = await res.json();
379
+ if (!data) {
380
+ return {
381
+ status,
382
+ error: new Error(`Failed to load data: ${route}`)
383
+ }
384
+ }
385
+ return {
386
+ status,
387
+ data
388
+ }
389
+ }
390
+
391
+ // https://cenfun.github.io/open-icons/
392
+ export const icons = {
393
+ search: '<svg viewBox="0 0 24 24" width="100%" height="100%" pointer-events="none" xmlns="http://www.w3.org/2000/svg"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m21 21-4.486-4.494M19 10.5a8.5 8.5 0 1 1-17 0 8.5 8.5 0 0 1 17 0"/></svg>',
394
+ conflicts: '<svg viewBox="0 0 400 400" width="100%" height="100%" pointer-events="none" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="m397.2 350.4.2-.2-180-320-.2.2C213.8 24.2 207.4 20 200 20s-13.8 4.2-17.2 10.4l-.2-.2-180 320 .2.2c-1.6 2.8-2.8 6-2.8 9.6 0 11 9 20 20 20h360c11 0 20-9 20-20 0-3.6-1.2-6.8-2.8-9.6M220 340h-40v-40h40zm0-60h-40V120h40z"/></svg>',
395
+ passed: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 426.667 426.667"><path fill="#6AC259" d="M213.333,0C95.518,0,0,95.514,0,213.333s95.518,213.333,213.333,213.333c117.828,0,213.333-95.514,213.333-213.333S331.157,0,213.333,0z M174.199,322.918l-93.935-93.931l31.309-31.309l62.626,62.622l140.894-140.898l31.309,31.309L174.199,322.918z"/></svg>',
396
+ download: '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" width="100%" height="100%" viewBox="0 0 32 32"><path fill="currentColor" d="M26 24v4H6v-4H4v4a2 2 0 0 0 2 2h20a2 2 0 0 0 2-2v-4zm0-10l-1.41-1.41L17 20.17V2h-2v18.17l-7.59-7.58L6 14l10 10l10-10z"></path></svg>',
397
+ close: '<svg xmlns="http://www.w3.org/2000/svg" pointer-events="none" width="100%" height="100%" viewBox="0 0 16 16"><g fill="currentColor"><path fill-rule="evenodd" clip-rule="evenodd" d="m7.116 8-4.558 4.558.884.884L8 8.884l4.558 4.558.884-.884L8.884 8l4.558-4.558-.884-.884L8 7.116 3.442 2.558l-.884.884L7.116 8z"/></g></svg>',
398
+ arrowRight: '<svg xmlns="http://www.w3.org/2000/svg" pointer-events="none" width="100%" height="100%" viewBox="0 0 20 20"><path fill="currentColor" fill-rule="evenodd" d="m2.542 2.154 7.254 7.26c.136.14.204.302.204.483a.73.73 0 0 1-.204.5l-7.575 7.398c-.383.317-.724.317-1.022 0-.299-.317-.299-.643 0-.98l7.08-6.918-6.754-6.763c-.237-.343-.215-.654.066-.935.281-.28.598-.295.951-.045Zm9 0 7.254 7.26c.136.14.204.302.204.483a.73.73 0 0 1-.204.5l-7.575 7.398c-.383.317-.724.317-1.022 0-.299-.317-.299-.643 0-.98l7.08-6.918-6.754-6.763c-.237-.343-.215-.654.066-.935.281-.28.598-.295.951-.045Z"/></svg>'
399
+ }
400
+
401
+ export function sanitizeHTML(str) {
402
+ return str
403
+ .replace(/&/g, "&amp;")
404
+ .replace(/</g, "&lt;")
405
+ .replace(/>/g, "&gt;")
406
+ .replace(/"/g, "&quot;")
407
+ .replace(/'/g, "&#039;");
408
+ }
409
+
410
+ export function showTerminal() {
411
+ try {
412
+ const panel = app.extensionManager.bottomPanel;
413
+ const isTerminalVisible = panel.bottomPanelVisible && panel.activeBottomPanelTab.id === 'logs-terminal';
414
+ if (!isTerminalVisible)
415
+ panel.toggleBottomPanelTab('logs-terminal');
416
+ }
417
+ catch(exception) {
418
+ // do nothing
419
+ }
420
+ }
421
+
422
+ let need_restart = false;
423
+
424
+ export function setNeedRestart(value) {
425
+ need_restart = value;
426
+ }
427
+
428
+ async function onReconnected(event) {
429
+ if(need_restart) {
430
+ setNeedRestart(false);
431
+
432
+ const confirmed = await customConfirm("To apply the changes to the node pack's installation status, you need to refresh the browser. Would you like to refresh?");
433
+ if (!confirmed) {
434
+ return;
435
+ }
436
+
437
+ window.location.reload(true);
438
+ }
439
+ }
440
+
441
+ api.addEventListener('reconnected', onReconnected);
442
+
443
+ const storeId = "comfyui-manager-grid";
444
+ let timeId;
445
+ export function storeColumnWidth(gridId, columnItem) {
446
+ clearTimeout(timeId);
447
+ timeId = setTimeout(() => {
448
+ let data = {};
449
+ const dataStr = localStorage.getItem(storeId);
450
+ if (dataStr) {
451
+ try {
452
+ data = JSON.parse(dataStr);
453
+ } catch (e) {}
454
+ }
455
+
456
+ if (!data[gridId]) {
457
+ data[gridId] = {};
458
+ }
459
+
460
+ data[gridId][columnItem.id] = columnItem.width;
461
+
462
+ localStorage.setItem(storeId, JSON.stringify(data));
463
+
464
+ }, 200)
465
+ }
466
+
467
+ export function restoreColumnWidth(gridId, columns) {
468
+ const dataStr = localStorage.getItem(storeId);
469
+ if (!dataStr) {
470
+ return;
471
+ }
472
+ let data;
473
+ try {
474
+ data = JSON.parse(dataStr);
475
+ } catch (e) {}
476
+ if(!data) {
477
+ return;
478
+ }
479
+ const widthMap = data[gridId];
480
+ if (!widthMap) {
481
+ return;
482
+ }
483
+
484
+ columns.forEach(columnItem => {
485
+ const w = widthMap[columnItem.id];
486
+ if (w) {
487
+ columnItem.width = w;
488
+ }
489
+ });
490
+
491
+ }
492
+
493
+ export function getTimeAgo(dateStr) {
494
+ const date = new Date(dateStr);
495
+
496
+ if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
497
+ return "";
498
+ }
499
+
500
+ const units = [
501
+ { max: 2760000, value: 60000, name: 'minute', past: 'a minute ago', future: 'in a minute' },
502
+ { max: 72000000, value: 3600000, name: 'hour', past: 'an hour ago', future: 'in an hour' },
503
+ { max: 518400000, value: 86400000, name: 'day', past: 'yesterday', future: 'tomorrow' },
504
+ { max: 2419200000, value: 604800000, name: 'week', past: 'last week', future: 'in a week' },
505
+ { max: 28512000000, value: 2592000000, name: 'month', past: 'last month', future: 'in a month' }
506
+ ];
507
+ const diff = Date.now() - date.getTime();
508
+ // less than a minute
509
+ if (Math.abs(diff) < 60000)
510
+ return 'just now';
511
+ for (let i = 0; i < units.length; i++) {
512
+ if (Math.abs(diff) < units[i].max) {
513
+ return format(diff, units[i].value, units[i].name, units[i].past, units[i].future, diff < 0);
514
+ }
515
+ }
516
+ function format(diff, divisor, unit, past, future, isInTheFuture) {
517
+ const val = Math.round(Math.abs(diff) / divisor);
518
+ if (isInTheFuture)
519
+ return val <= 1 ? future : 'in ' + val + ' ' + unit + 's';
520
+ return val <= 1 ? past : val + ' ' + unit + 's ago';
521
+ }
522
+ return format(diff, 31536000000, 'year', 'last year', 'in a year', diff < 0);
523
+ };
524
+
525
+ export const loadCss = (cssFile) => {
526
+ const cssPath = import.meta.resolve(cssFile);
527
+ //console.log(cssPath);
528
+ const $link = document.createElement("link");
529
+ $link.setAttribute("rel", 'stylesheet');
530
+ $link.setAttribute("href", cssPath);
531
+ document.head.appendChild($link);
532
+ };
533
+
534
+ export const copyText = (text) => {
535
+ return new Promise((resolve) => {
536
+ let err;
537
+ try {
538
+ navigator.clipboard.writeText(text);
539
+ } catch (e) {
540
+ err = e;
541
+ }
542
+ if (err) {
543
+ resolve(false);
544
+ } else {
545
+ resolve(true);
546
+ }
547
+ });
548
+ };
549
+
550
+ function renderPopover($elem, target, options = {}) {
551
+ // async microtask
552
+ queueMicrotask(() => {
553
+
554
+ const containerRect = getRect(window);
555
+ const targetRect = getRect(target);
556
+ const elemRect = getRect($elem);
557
+
558
+ const positionInfo = getBestPosition(
559
+ containerRect,
560
+ targetRect,
561
+ elemRect,
562
+ options.positions
563
+ );
564
+ const style = getPositionStyle(positionInfo, {
565
+ bgColor: options.bgColor,
566
+ borderColor: options.borderColor,
567
+ borderRadius: options.borderRadius
568
+ });
569
+
570
+ $elem.style.top = positionInfo.top + "px";
571
+ $elem.style.left = positionInfo.left + "px";
572
+ $elem.style.background = style.background;
573
+
574
+ });
575
+ }
576
+
577
+ let $popover;
578
+ export function hidePopover() {
579
+ if ($popover) {
580
+ $popover.remove();
581
+ $popover = null;
582
+ }
583
+ }
584
+ export function showPopover(target, text, className, options) {
585
+ hidePopover();
586
+ $popover = document.createElement("div");
587
+ $popover.className = ['cn-popover', className].filter(it => it).join(" ");
588
+ document.body.appendChild($popover);
589
+ $popover.innerHTML = text;
590
+ $popover.style.display = "block";
591
+ renderPopover($popover, target, {
592
+ borderRadius: 10,
593
+ ... options
594
+ });
595
+ }
596
+
597
+ let $tooltip;
598
+ export function hideTooltip(target) {
599
+ if ($tooltip) {
600
+ $tooltip.style.display = "none";
601
+ $tooltip.innerHTML = "";
602
+ $tooltip.style.top = "0px";
603
+ $tooltip.style.left = "0px";
604
+ }
605
+ }
606
+ export function showTooltip(target, text, className = 'cn-tooltip', styleMap = {}) {
607
+ if (!$tooltip) {
608
+ $tooltip = document.createElement("div");
609
+ $tooltip.className = className;
610
+ $tooltip.style.cssText = `
611
+ pointer-events: none;
612
+ position: fixed;
613
+ z-index: 10001;
614
+ padding: 20px;
615
+ color: #1e1e1e;
616
+ max-width: 350px;
617
+ filter: drop-shadow(1px 5px 5px rgb(0 0 0 / 30%));
618
+ ${Object.keys(styleMap).map(k=>k+":"+styleMap[k]+";").join("")}
619
+ `;
620
+ document.body.appendChild($tooltip);
621
+ }
622
+
623
+ $tooltip.innerHTML = text;
624
+ $tooltip.style.display = "block";
625
+ renderPopover($tooltip, target, {
626
+ positions: ['top', 'bottom', 'right', 'center'],
627
+ bgColor: "#ffffff",
628
+ borderColor: "#cccccc",
629
+ borderRadius: 5
630
+ });
631
+ }
632
+
633
+ function initTooltip () {
634
+ const mouseenterHandler = (e) => {
635
+ const target = e.target;
636
+ const text = target.getAttribute('tooltip');
637
+ if (text) {
638
+ showTooltip(target, text);
639
+ }
640
+ };
641
+ const mouseleaveHandler = (e) => {
642
+ const target = e.target;
643
+ const text = target.getAttribute('tooltip');
644
+ if (text) {
645
+ hideTooltip(target);
646
+ }
647
+ };
648
+ document.body.removeEventListener('mouseenter', mouseenterHandler, true);
649
+ document.body.removeEventListener('mouseleave', mouseleaveHandler, true);
650
+ document.body.addEventListener('mouseenter', mouseenterHandler, true);
651
+ document.body.addEventListener('mouseleave', mouseleaveHandler, true);
652
+ }
653
+
654
+ initTooltip();
ComfyUI/custom_nodes/ComfyUI-Manager/js/components-manager.js ADDED
@@ -0,0 +1,812 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../scripts/app.js";
2
+ import { api } from "../../scripts/api.js"
3
+ import { sleep, show_message, customConfirm, customAlert } from "./common.js";
4
+ import { GroupNodeConfig, GroupNodeHandler } from "../../extensions/core/groupNode.js";
5
+ import { ComfyDialog, $el } from "../../scripts/ui.js";
6
+
7
+ const SEPARATOR = ">"
8
+
9
+ let pack_map = {};
10
+ let rpack_map = {};
11
+
12
+ export function getPureName(node) {
13
+ // group nodes/
14
+ let category = null;
15
+ if(node.category) {
16
+ category = node.category.substring(12);
17
+ }
18
+ else {
19
+ category = node.constructor.category?.substring(12);
20
+ }
21
+ if(category) {
22
+ let purename = node.comfyClass.substring(category.length+1);
23
+ return purename;
24
+ }
25
+ else if(node.comfyClass.startsWith('workflow/') || node.comfyClass.startsWith(`workflow${SEPARATOR}`)) {
26
+ return node.comfyClass.substring(9);
27
+ }
28
+ else {
29
+ return node.comfyClass;
30
+ }
31
+ }
32
+
33
+ function isValidVersionString(version) {
34
+ const versionPattern = /^(\d+)\.(\d+)(\.(\d+))?$/;
35
+
36
+ const match = version.match(versionPattern);
37
+
38
+ return match !== null &&
39
+ parseInt(match[1], 10) >= 0 &&
40
+ parseInt(match[2], 10) >= 0 &&
41
+ (!match[3] || parseInt(match[4], 10) >= 0);
42
+ }
43
+
44
+ function register_pack_map(name, data) {
45
+ if(data.packname) {
46
+ pack_map[data.packname] = name;
47
+ rpack_map[name] = data;
48
+ }
49
+ else {
50
+ rpack_map[name] = data;
51
+ }
52
+ }
53
+
54
+ function storeGroupNode(name, data, register=true) {
55
+ let extra = app.graph.extra;
56
+ if (!extra) app.graph.extra = extra = {};
57
+ let groupNodes = extra.groupNodes;
58
+ if (!groupNodes) extra.groupNodes = groupNodes = {};
59
+ groupNodes[name] = data;
60
+
61
+ if(register) {
62
+ register_pack_map(name, data);
63
+ }
64
+ }
65
+
66
+ export async function load_components() {
67
+ let data = await api.fetchApi('/manager/component/loads', {method: "POST"});
68
+ let components = await data.json();
69
+
70
+ let start_time = Date.now();
71
+ let failed = [];
72
+ let failed2 = [];
73
+
74
+ for(let name in components) {
75
+ if(app.graph.extra?.groupNodes?.[name]) {
76
+ if(data) {
77
+ let data = components[name];
78
+
79
+ let category = data.packname;
80
+ if(data.category) {
81
+ category += SEPARATOR + data.category;
82
+ }
83
+ if(category == '') {
84
+ category = 'components';
85
+ }
86
+
87
+ const config = new GroupNodeConfig(name, data);
88
+ await config.registerType(category);
89
+
90
+ register_pack_map(name, data);
91
+ continue;
92
+ }
93
+ }
94
+
95
+ let nodeData = components[name];
96
+
97
+ storeGroupNode(name, nodeData);
98
+
99
+ const config = new GroupNodeConfig(name, nodeData);
100
+
101
+ while(true) {
102
+ try {
103
+ let category = nodeData.packname;
104
+ if(nodeData.category) {
105
+ category += SEPARATOR + nodeData.category;
106
+ }
107
+ if(category == '') {
108
+ category = 'components';
109
+ }
110
+
111
+ await config.registerType(category);
112
+ register_pack_map(name, nodeData);
113
+ break;
114
+ }
115
+ catch {
116
+ let elapsed_time = Date.now() - start_time;
117
+ if (elapsed_time > 5000) {
118
+ failed.push(name);
119
+ break;
120
+ } else {
121
+ await sleep(100);
122
+ }
123
+ }
124
+ }
125
+ }
126
+
127
+ // fallback1
128
+ for(let i in failed) {
129
+ let name = failed[i];
130
+
131
+ if(app.graph.extra?.groupNodes?.[name]) {
132
+ continue;
133
+ }
134
+
135
+ let nodeData = components[name];
136
+
137
+ storeGroupNode(name, nodeData);
138
+
139
+ const config = new GroupNodeConfig(name, nodeData);
140
+ while(true) {
141
+ try {
142
+ let category = nodeData.packname;
143
+ if(nodeData.workflow.category) {
144
+ category += SEPARATOR + nodeData.category;
145
+ }
146
+ if(category == '') {
147
+ category = 'components';
148
+ }
149
+
150
+ await config.registerType(category);
151
+ register_pack_map(name, nodeData);
152
+ break;
153
+ }
154
+ catch {
155
+ let elapsed_time = Date.now() - start_time;
156
+ if (elapsed_time > 10000) {
157
+ failed2.push(name);
158
+ break;
159
+ } else {
160
+ await sleep(100);
161
+ }
162
+ }
163
+ }
164
+ }
165
+
166
+ // fallback2
167
+ for(let name in failed2) {
168
+ let name = failed2[i];
169
+
170
+ let nodeData = components[name];
171
+
172
+ storeGroupNode(name, nodeData);
173
+
174
+ const config = new GroupNodeConfig(name, nodeData);
175
+ while(true) {
176
+ try {
177
+ let category = nodeData.workflow.packname;
178
+ if(nodeData.workflow.category) {
179
+ category += SEPARATOR + nodeData.category;
180
+ }
181
+ if(category == '') {
182
+ category = 'components';
183
+ }
184
+
185
+ await config.registerType(category);
186
+ register_pack_map(name, nodeData);
187
+ break;
188
+ }
189
+ catch {
190
+ let elapsed_time = Date.now() - start_time;
191
+ if (elapsed_time > 30000) {
192
+ failed.push(name);
193
+ break;
194
+ } else {
195
+ await sleep(100);
196
+ }
197
+ }
198
+ }
199
+ }
200
+ }
201
+
202
+ async function save_as_component(node, version, author, prefix, nodename, packname, category) {
203
+ let component_name = `${prefix}::${nodename}`;
204
+
205
+ let subgraph = app.graph.extra?.groupNodes?.[component_name];
206
+ if(!subgraph) {
207
+ subgraph = app.graph.extra?.groupNodes?.[getPureName(node)];
208
+ }
209
+
210
+ subgraph.version = version;
211
+ subgraph.author = author;
212
+ subgraph.datetime = Date.now();
213
+ subgraph.packname = packname;
214
+ subgraph.category = category;
215
+
216
+ let body =
217
+ {
218
+ name: component_name,
219
+ workflow: subgraph
220
+ };
221
+
222
+ pack_map[packname] = component_name;
223
+ rpack_map[component_name] = subgraph;
224
+
225
+ const res = await api.fetchApi('/manager/component/save', {
226
+ method: "POST",
227
+ headers: {
228
+ "Content-Type": "application/json",
229
+ },
230
+ body: JSON.stringify(body),
231
+ });
232
+
233
+ if(res.status == 200) {
234
+ storeGroupNode(component_name, subgraph);
235
+ const config = new GroupNodeConfig(component_name, subgraph);
236
+
237
+ let category = body.workflow.packname;
238
+ if(body.workflow.category) {
239
+ category += SEPARATOR + body.workflow.category;
240
+ }
241
+ if(category == '') {
242
+ category = 'components';
243
+ }
244
+
245
+ await config.registerType(category);
246
+
247
+ let path = await res.text();
248
+ show_message(`Component '${component_name}' is saved into:\n${path}`);
249
+ }
250
+ else
251
+ show_message(`Failed to save component.`);
252
+ }
253
+
254
+ async function import_component(component_name, component, mode) {
255
+ if(mode) {
256
+ let body =
257
+ {
258
+ name: component_name,
259
+ workflow: component
260
+ };
261
+
262
+ const res = await api.fetchApi('/manager/component/save', {
263
+ method: "POST",
264
+ headers: { "Content-Type": "application/json", },
265
+ body: JSON.stringify(body)
266
+ });
267
+ }
268
+
269
+ let category = component.packname;
270
+ if(component.category) {
271
+ category += SEPARATOR + component.category;
272
+ }
273
+ if(category == '') {
274
+ category = 'components';
275
+ }
276
+
277
+ storeGroupNode(component_name, component);
278
+ const config = new GroupNodeConfig(component_name, component);
279
+ await config.registerType(category);
280
+ }
281
+
282
+ function restore_to_loaded_component(component_name) {
283
+ if(rpack_map[component_name]) {
284
+ let component = rpack_map[component_name];
285
+ storeGroupNode(component_name, component, false);
286
+ const config = new GroupNodeConfig(component_name, component);
287
+ config.registerType(component.category);
288
+ }
289
+ }
290
+
291
+ // Using a timestamp prevents duplicate pastes and ensures the prevention of re-deletion of litegrapheditor_clipboard.
292
+ let last_paste_timestamp = null;
293
+
294
+ function versionCompare(v1, v2) {
295
+ let ver1;
296
+ let ver2;
297
+ if(v1 && v1 != '') {
298
+ ver1 = v1.split('.');
299
+ ver1[0] = parseInt(ver1[0]);
300
+ ver1[1] = parseInt(ver1[1]);
301
+ if(ver1.length == 2)
302
+ ver1.push(0);
303
+ else
304
+ ver1[2] = parseInt(ver2[2]);
305
+ }
306
+ else {
307
+ ver1 = [0,0,0];
308
+ }
309
+
310
+ if(v2 && v2 != '') {
311
+ ver2 = v2.split('.');
312
+ ver2[0] = parseInt(ver2[0]);
313
+ ver2[1] = parseInt(ver2[1]);
314
+ if(ver2.length == 2)
315
+ ver2.push(0);
316
+ else
317
+ ver2[2] = parseInt(ver2[2]);
318
+ }
319
+ else {
320
+ ver2 = [0,0,0];
321
+ }
322
+
323
+ if(ver1[0] > ver2[0])
324
+ return -1;
325
+ else if(ver1[0] < ver2[0])
326
+ return 1;
327
+
328
+ if(ver1[1] > ver2[1])
329
+ return -1;
330
+ else if(ver1[1] < ver2[1])
331
+ return 1;
332
+
333
+ if(ver1[2] > ver2[2])
334
+ return -1;
335
+ else if(ver1[2] < ver2[2])
336
+ return 1;
337
+
338
+ return 0;
339
+ }
340
+
341
+ function checkVersion(name, component) {
342
+ let msg = '';
343
+ if(rpack_map[name]) {
344
+ let old_version = rpack_map[name].version;
345
+ if(!old_version || old_version == '') {
346
+ msg = ` '${name}' Upgrade (V0.0 -> V${component.version})`;
347
+ }
348
+ else {
349
+ let c = versionCompare(old_version, component.version);
350
+ if(c < 0) {
351
+ msg = ` '${name}' Downgrade (V${old_version} -> V${component.version})`;
352
+ }
353
+ else if(c > 0) {
354
+ msg = ` '${name}' Upgrade (V${old_version} -> V${component.version})`;
355
+ }
356
+ else {
357
+ msg = ` '${name}' Same version (V${component.version})`;
358
+ }
359
+ }
360
+ }
361
+ else {
362
+ msg = `'${name}' NEW (V${component.version})`;
363
+ }
364
+
365
+ return msg;
366
+ }
367
+
368
+ async function handle_import_components(components) {
369
+ let msg = 'Components:\n';
370
+ let cnt = 0;
371
+ for(let name in components) {
372
+ let component = components[name];
373
+ let v = checkVersion(name, component);
374
+
375
+ if(cnt < 10) {
376
+ msg += v + '\n';
377
+ }
378
+ else if (cnt == 10) {
379
+ msg += '...\n';
380
+ }
381
+ else {
382
+ // do nothing
383
+ }
384
+
385
+ cnt++;
386
+ }
387
+
388
+ let last_name = null;
389
+ msg += '\nWill you load components?\n';
390
+ const confirmed = await customConfirm(msg);
391
+ if(confirmed) {
392
+ const mode = await customConfirm('\nWill you save components?\n(cancel=load without save)');
393
+
394
+ for(let name in components) {
395
+ let component = components[name];
396
+ import_component(name, component, mode);
397
+ last_name = name;
398
+ }
399
+
400
+ if(mode) {
401
+ show_message('Components are saved.');
402
+ }
403
+ else {
404
+ show_message('Components are loaded.');
405
+ }
406
+ }
407
+
408
+ if(cnt == 1 && last_name) {
409
+ const node = LiteGraph.createNode(`workflow${SEPARATOR}${last_name}`);
410
+ node.pos = [app.canvas.graph_mouse[0], app.canvas.graph_mouse[1]];
411
+ app.canvas.graph.add(node, false);
412
+ }
413
+ }
414
+
415
+ async function handlePaste(e) {
416
+ let data = (e.clipboardData || window.clipboardData);
417
+ const items = data.items;
418
+ for(const item of items) {
419
+ if(item.kind == 'string' && item.type == 'text/plain') {
420
+ data = data.getData("text/plain");
421
+ try {
422
+ let json_data = JSON.parse(data);
423
+ if(json_data.kind == 'ComfyUI Components' && last_paste_timestamp != json_data.timestamp) {
424
+ last_paste_timestamp = json_data.timestamp;
425
+ await handle_import_components(json_data.components);
426
+
427
+ // disable paste node
428
+ localStorage.removeItem("litegrapheditor_clipboard", null);
429
+ }
430
+ else {
431
+ console.log('This components are already pasted: ignored');
432
+ }
433
+ }
434
+ catch {
435
+ // nothing to do
436
+ }
437
+ }
438
+ }
439
+ }
440
+
441
+ document.addEventListener("paste", handlePaste);
442
+
443
+
444
+ export class ComponentBuilderDialog extends ComfyDialog {
445
+ constructor() {
446
+ super();
447
+ }
448
+
449
+ clear() {
450
+ while (this.element.children.length) {
451
+ this.element.removeChild(this.element.children[0]);
452
+ }
453
+ }
454
+
455
+ show() {
456
+ this.invalidateControl();
457
+
458
+ this.element.style.display = "block";
459
+ this.element.style.zIndex = 1099;
460
+ this.element.style.width = "500px";
461
+ this.element.style.height = "480px";
462
+ }
463
+
464
+ invalidateControl() {
465
+ this.clear();
466
+
467
+ let self = this;
468
+
469
+ const close_button = $el("button", { id: "cm-close-button", type: "button", textContent: "Close", onclick: () => self.close() });
470
+ this.save_button = $el("button",
471
+ { id: "cm-save-button", type: "button", textContent: "Save", onclick: () =>
472
+ {
473
+ save_as_component(self.target_node, self.version_string.value.trim(), self.author.value.trim(), self.node_prefix.value.trim(),
474
+ self.getNodeName(), self.getPackName(), self.category.value.trim());
475
+ }
476
+ });
477
+
478
+ let default_nodename = getPureName(this.target_node).trim();
479
+
480
+ let groupNode = app.graph.extra.groupNodes[default_nodename];
481
+ let default_packname = groupNode.packname;
482
+ if(!default_packname) {
483
+ default_packname = '';
484
+ }
485
+
486
+ let default_category = groupNode.category;
487
+ if(!default_category) {
488
+ default_category = '';
489
+ }
490
+
491
+ this.default_ver = groupNode.version;
492
+ if(!this.default_ver) {
493
+ this.default_ver = '0.0';
494
+ }
495
+
496
+ let default_author = groupNode.author;
497
+ if(!default_author) {
498
+ default_author = '';
499
+ }
500
+
501
+ let delimiterIndex = default_nodename.indexOf('::');
502
+ let default_prefix = "";
503
+ if(delimiterIndex != -1) {
504
+ default_prefix = default_nodename.substring(0, delimiterIndex);
505
+ default_nodename = default_nodename.substring(delimiterIndex + 2);
506
+ }
507
+
508
+ if(!default_prefix) {
509
+ this.save_button.disabled = true;
510
+ }
511
+
512
+ this.pack_list = this.createPackListCombo();
513
+
514
+ let version_string = this.createLabeledInput('input version (e.g. 1.0)', '*Version : ', this.default_ver);
515
+ this.version_string = version_string[1];
516
+ this.version_string.disabled = true;
517
+
518
+ let author = this.createLabeledInput('input author (e.g. Dr.Lt.Data)', 'Author : ', default_author);
519
+ this.author = author[1];
520
+
521
+ let node_prefix = this.createLabeledInput('input node prefix (e.g. mypack)', '*Prefix : ', default_prefix);
522
+ this.node_prefix = node_prefix[1];
523
+
524
+ let manual_nodename = this.createLabeledInput('input node name (e.g. MAKE_BASIC_PIPE)', 'Nodename : ', default_nodename);
525
+ this.manual_nodename = manual_nodename[1];
526
+
527
+ let manual_packname = this.createLabeledInput('input pack name (e.g. mypack)', 'Packname : ', default_packname);
528
+ this.manual_packname = manual_packname[1];
529
+
530
+ let category = this.createLabeledInput('input category (e.g. util/pipe)', 'Category : ', default_category);
531
+ this.category = category[1];
532
+
533
+ this.node_label = this.createNodeLabel();
534
+
535
+ let author_mode = this.createAuthorModeCheck();
536
+ this.author_mode = author_mode[0];
537
+
538
+ const content =
539
+ $el("div.comfy-modal-content",
540
+ [
541
+ $el("tr.cm-title", {}, [
542
+ $el("font", {size:6, color:"white"}, [`ComfyUI-Manager: Component Builder`])]
543
+ ),
544
+ $el("br", {}, []),
545
+ $el("div.cm-menu-container",
546
+ [
547
+ author_mode[0],
548
+ author_mode[1],
549
+ category[0],
550
+ author[0],
551
+ node_prefix[0],
552
+ manual_nodename[0],
553
+ manual_packname[0],
554
+ version_string[0],
555
+ this.pack_list,
556
+ $el("br", {}, []),
557
+ this.node_label
558
+ ]),
559
+
560
+ $el("br", {}, []),
561
+ this.save_button,
562
+ close_button,
563
+ ]
564
+ );
565
+
566
+ content.style.width = '100%';
567
+ content.style.height = '100%';
568
+
569
+ this.element = $el("div.comfy-modal", { id:'cm-manager-dialog', parent: document.body }, [ content ]);
570
+ }
571
+
572
+ validateInput() {
573
+ let msg = "";
574
+
575
+ if(!isValidVersionString(this.version_string.value)) {
576
+ msg += 'Invalid version string: '+event.value+"\n";
577
+ }
578
+
579
+ if(this.node_prefix.value.trim() == '') {
580
+ msg += 'Node prefix cannot be empty\n';
581
+ }
582
+
583
+ if(this.manual_nodename.value.trim() == '') {
584
+ msg += 'Node name cannot be empty\n';
585
+ }
586
+
587
+ if(msg != '') {
588
+ // alert(msg);
589
+ }
590
+
591
+ this.save_button.disabled = msg != "";
592
+ }
593
+
594
+ getPackName() {
595
+ if(this.pack_list.selectedIndex == 0) {
596
+ return this.manual_packname.value.trim();
597
+ }
598
+
599
+ return this.pack_list.value.trim();
600
+ }
601
+
602
+ getNodeName() {
603
+ if(this.manual_nodename.value.trim() != '') {
604
+ return this.manual_nodename.value.trim();
605
+ }
606
+
607
+ return getPureName(this.target_node);
608
+ }
609
+
610
+ createAuthorModeCheck() {
611
+ let check = $el("input",{type:'checkbox', id:"author-mode"},[])
612
+ const check_label = $el("label",{for:"author-mode"},["Enable author mode"]);
613
+ check_label.style.color = "var(--fg-color)";
614
+ check_label.style.cursor = "pointer";
615
+ check.checked = false;
616
+
617
+ let self = this;
618
+ check.onchange = () => {
619
+ self.version_string.disabled = !check.checked;
620
+
621
+ if(!check.checked) {
622
+ self.version_string.value = self.default_ver;
623
+ }
624
+ else {
625
+ customAlert('If you are not the author, it is not recommended to change the version, as it may cause component update issues.');
626
+ }
627
+ };
628
+
629
+ return [check, check_label];
630
+ }
631
+
632
+ createNodeLabel() {
633
+ let label = $el('p');
634
+ label.className = 'cb-node-label';
635
+ if(this.target_node.comfyClass.includes('::'))
636
+ label.textContent = getPureName(this.target_node);
637
+ else
638
+ label.textContent = " _::" + getPureName(this.target_node);
639
+ return label;
640
+ }
641
+
642
+ createLabeledInput(placeholder, label, value) {
643
+ let textbox = $el('input.cb-widget-input', {type:'text', placeholder:placeholder, value:value}, []);
644
+
645
+ let self = this;
646
+ textbox.onchange = () => {
647
+ this.validateInput.call(self);
648
+ this.node_label.textContent = this.node_prefix.value + "::" + this.manual_nodename.value;
649
+ }
650
+ let row = $el('span.cb-widget', {}, [ $el('span.cb-widget-input-label', label), textbox]);
651
+
652
+ return [row, textbox];
653
+ }
654
+
655
+ createPackListCombo() {
656
+ let combo = document.createElement("select");
657
+ combo.className = "cb-widget";
658
+ let default_packname_option = { value: '##manual', text: 'Packname: Manual' };
659
+
660
+ combo.appendChild($el('option', default_packname_option, []));
661
+ for(let name in pack_map) {
662
+ combo.appendChild($el('option', { value: name, text: 'Packname: '+ name }, []));
663
+ }
664
+
665
+ let self = this;
666
+ combo.onchange = function () {
667
+ if(combo.selectedIndex == 0) {
668
+ self.manual_packname.disabled = false;
669
+ }
670
+ else {
671
+ self.manual_packname.disabled = true;
672
+ }
673
+ };
674
+
675
+ return combo;
676
+ }
677
+ }
678
+
679
+ let orig_handleFile = app.handleFile;
680
+
681
+ async function handleFile(file) {
682
+ if (file.name?.endsWith(".json") || file.name?.endsWith(".pack")) {
683
+ const reader = new FileReader();
684
+ reader.onload = async () => {
685
+ let is_component = false;
686
+ const jsonContent = JSON.parse(reader.result);
687
+ for(let name in jsonContent) {
688
+ let cand = jsonContent[name];
689
+ is_component = cand.datetime && cand.version;
690
+ break;
691
+ }
692
+
693
+ if(is_component) {
694
+ await handle_import_components(jsonContent);
695
+ }
696
+ else {
697
+ orig_handleFile.call(app, file);
698
+ }
699
+ };
700
+ reader.readAsText(file);
701
+
702
+ return;
703
+ }
704
+
705
+ orig_handleFile.call(app, file);
706
+ }
707
+
708
+ app.handleFile = handleFile;
709
+
710
+ let current_component_policy = 'workflow';
711
+ try {
712
+ api.fetchApi('/manager/policy/component')
713
+ .then(response => response.text())
714
+ .then(data => { current_component_policy = data; });
715
+ }
716
+ catch {}
717
+
718
+ function getChangedVersion(groupNodes) {
719
+ if(!Object.keys(pack_map).length || !groupNodes)
720
+ return null;
721
+
722
+ let res = {};
723
+ for(let component_name in groupNodes) {
724
+ let data = groupNodes[component_name];
725
+
726
+ if(rpack_map[component_name]) {
727
+ let v = versionCompare(data.version, rpack_map[component_name].version);
728
+ res[component_name] = v;
729
+ }
730
+ }
731
+
732
+ return res;
733
+ }
734
+
735
+ const loadGraphData = app.loadGraphData;
736
+ app.loadGraphData = async function () {
737
+ if(arguments.length == 0)
738
+ return await loadGraphData.apply(this, arguments);
739
+
740
+ let graphData = arguments[0];
741
+ let groupNodes = graphData.extra?.groupNodes;
742
+ let res = getChangedVersion(groupNodes);
743
+
744
+ if(res) {
745
+ let target_components = null;
746
+ switch(current_component_policy) {
747
+ case 'higher':
748
+ target_components = Object.keys(res).filter(key => res[key] == 1);
749
+ break;
750
+
751
+ case 'mine':
752
+ target_components = Object.keys(res);
753
+ break;
754
+
755
+ default:
756
+ // do nothing
757
+ }
758
+
759
+ if(target_components) {
760
+ for(let i in target_components) {
761
+ let component_name = target_components[i];
762
+ let component = rpack_map[component_name];
763
+ if(component && graphData.extra?.groupNodes) {
764
+ graphData.extra.groupNodes[component_name] = component;
765
+ }
766
+ }
767
+ }
768
+ }
769
+ else {
770
+ console.log('Empty components: policy ignored');
771
+ }
772
+
773
+ arguments[0] = graphData;
774
+ return await loadGraphData.apply(this, arguments);
775
+ };
776
+
777
+ export function set_component_policy(v) {
778
+ current_component_policy = v;
779
+ }
780
+
781
+ let graphToPrompt = app.graphToPrompt;
782
+ app.graphToPrompt = async function () {
783
+ let p = await graphToPrompt.call(app);
784
+ try {
785
+ let groupNodes = p.workflow.extra?.groupNodes;
786
+ if(groupNodes) {
787
+ p.workflow.extra = { ... p.workflow.extra};
788
+
789
+ // get used group nodes
790
+ let used_group_nodes = new Set();
791
+ for(let node of p.workflow.nodes) {
792
+ if(node.type.startsWith(`workflow/`) || node.type.startsWith(`workflow${SEPARATOR}`)) {
793
+ used_group_nodes.add(node.type.substring(9));
794
+ }
795
+ }
796
+
797
+ // remove unused group nodes
798
+ let new_groupNodes = {};
799
+ for (let key in p.workflow.extra.groupNodes) {
800
+ if (used_group_nodes.has(key)) {
801
+ new_groupNodes[key] = p.workflow.extra.groupNodes[key];
802
+ }
803
+ }
804
+ p.workflow.extra.groupNodes = new_groupNodes;
805
+ }
806
+ }
807
+ catch(e) {
808
+ console.log(`Failed to filtering group nodes: ${e}`);
809
+ }
810
+
811
+ return p;
812
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/js/custom-nodes-manager.css ADDED
@@ -0,0 +1,699 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .cn-manager {
2
+ --grid-font: -apple-system, BlinkMacSystemFont, "Segue UI", "Noto Sans", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
3
+ z-index: 1099;
4
+ width: 80%;
5
+ height: 80%;
6
+ display: flex;
7
+ flex-direction: column;
8
+ gap: 10px;
9
+ color: var(--fg-color);
10
+ font-family: arial, sans-serif;
11
+ text-underline-offset: 3px;
12
+ outline: none;
13
+ }
14
+
15
+ .cn-manager .cn-flex-auto {
16
+ flex: auto;
17
+ }
18
+
19
+ .cn-manager button {
20
+ font-size: 16px;
21
+ color: var(--input-text);
22
+ background-color: var(--comfy-input-bg);
23
+ border-radius: 8px;
24
+ border-color: var(--border-color);
25
+ border-style: solid;
26
+ margin: 0;
27
+ padding: 4px 8px;
28
+ min-width: 100px;
29
+ }
30
+
31
+ .cn-manager button:disabled,
32
+ .cn-manager input:disabled,
33
+ .cn-manager select:disabled {
34
+ color: gray;
35
+ }
36
+
37
+ .cn-manager button:disabled {
38
+ background-color: var(--comfy-input-bg);
39
+ }
40
+
41
+ .cn-manager .cn-manager-restart {
42
+ display: none;
43
+ background-color: #500000;
44
+ color: white;
45
+ }
46
+
47
+ .cn-manager .cn-manager-stop {
48
+ display: none;
49
+ background-color: #500000;
50
+ color: white;
51
+ }
52
+
53
+ .cn-manager .cn-manager-back {
54
+ align-items: center;
55
+ justify-content: center;
56
+ }
57
+
58
+ .arrow-icon {
59
+ height: 1em;
60
+ width: 1em;
61
+ margin-right: 5px;
62
+ transform: translateY(2px);
63
+ }
64
+
65
+ .cn-icon {
66
+ display: block;
67
+ width: 16px;
68
+ height: 16px;
69
+ }
70
+
71
+ .cn-icon svg {
72
+ display: block;
73
+ margin: 0;
74
+ pointer-events: none;
75
+ }
76
+
77
+ .cn-manager-header {
78
+ display: flex;
79
+ flex-wrap: wrap;
80
+ gap: 5px;
81
+ align-items: center;
82
+ padding: 0 5px;
83
+ }
84
+
85
+ .cn-manager-header label {
86
+ display: flex;
87
+ gap: 5px;
88
+ align-items: center;
89
+ }
90
+
91
+ .cn-manager-filter {
92
+ height: 28px;
93
+ line-height: 28px;
94
+ }
95
+
96
+ .cn-manager-keywords {
97
+ height: 28px;
98
+ line-height: 28px;
99
+ padding: 0 5px 0 26px;
100
+ background-size: 16px;
101
+ background-position: 5px center;
102
+ background-repeat: no-repeat;
103
+ background-image: url("data:image/svg+xml;charset=utf8,%3Csvg%20viewBox%3D%220%200%2024%2024%22%20width%3D%22100%25%22%20height%3D%22100%25%22%20pointer-events%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20fill%3D%22none%22%20stroke%3D%22%23888%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%20stroke-width%3D%222%22%20d%3D%22m21%2021-4.486-4.494M19%2010.5a8.5%208.5%200%201%201-17%200%208.5%208.5%200%200%201%2017%200%22%2F%3E%3C%2Fsvg%3E");
104
+ }
105
+
106
+ .cn-manager-status {
107
+ padding-left: 10px;
108
+ }
109
+
110
+ .cn-manager-grid {
111
+ flex: auto;
112
+ border: 1px solid var(--border-color);
113
+ overflow: hidden;
114
+ position: relative;
115
+ }
116
+
117
+ .cn-manager-selection {
118
+ display: flex;
119
+ flex-wrap: wrap;
120
+ gap: 10px;
121
+ align-items: center;
122
+ }
123
+
124
+ .cn-manager-message {
125
+ position: relative;
126
+ }
127
+
128
+ .cn-manager-footer {
129
+ display: flex;
130
+ flex-wrap: wrap;
131
+ gap: 10px;
132
+ align-items: center;
133
+ }
134
+
135
+ .cn-manager-grid .tg-turbogrid {
136
+ font-family: var(--grid-font);
137
+ font-size: 15px;
138
+ background: var(--bg-color);
139
+ }
140
+
141
+ .cn-manager-grid .tg-turbogrid .tg-highlight::after {
142
+ position: absolute;
143
+ top: 0;
144
+ left: 0;
145
+ content: "";
146
+ display: block;
147
+ width: 100%;
148
+ height: 100%;
149
+ box-sizing: border-box;
150
+ background-color: #80bdff11;
151
+ pointer-events: none;
152
+ }
153
+
154
+ .cn-manager-grid .cn-pack-name a {
155
+ color: skyblue;
156
+ text-decoration: none;
157
+ word-break: break-word;
158
+ }
159
+
160
+ .cn-manager-grid .cn-pack-desc a {
161
+ color: #5555FF;
162
+ font-weight: bold;
163
+ text-decoration: none;
164
+ }
165
+
166
+ .cn-manager-grid .tg-cell a:hover {
167
+ text-decoration: underline;
168
+ }
169
+
170
+ .cn-manager-grid .cn-pack-version {
171
+ line-height: 100%;
172
+ display: flex;
173
+ flex-direction: column;
174
+ justify-content: center;
175
+ height: 100%;
176
+ gap: 5px;
177
+ }
178
+
179
+ .cn-manager-grid .cn-pack-nodes {
180
+ line-height: 100%;
181
+ display: flex;
182
+ flex-direction: column;
183
+ justify-content: center;
184
+ gap: 5px;
185
+ cursor: pointer;
186
+ height: 100%;
187
+ }
188
+
189
+ .cn-manager-grid .cn-pack-nodes:hover {
190
+ text-decoration: underline;
191
+ }
192
+
193
+ .cn-manager-grid .cn-pack-conflicts {
194
+ color: orange;
195
+ }
196
+
197
+ .cn-popover {
198
+ position: fixed;
199
+ z-index: 10000;
200
+ padding: 20px;
201
+ color: #1e1e1e;
202
+ filter: drop-shadow(1px 5px 5px rgb(0 0 0 / 30%));
203
+ overflow: hidden;
204
+ }
205
+
206
+ .cn-flyover {
207
+ position: absolute;
208
+ top: 0;
209
+ right: 0;
210
+ z-index: 1000;
211
+ display: none;
212
+ width: 50%;
213
+ height: 100%;
214
+ background-color: var(--comfy-menu-bg);
215
+ animation-duration: 0.2s;
216
+ animation-fill-mode: both;
217
+ flex-direction: column;
218
+ }
219
+
220
+ .cn-flyover::before {
221
+ position: absolute;
222
+ top: 0;
223
+ content: "";
224
+ z-index: 10;
225
+ display: block;
226
+ width: 10px;
227
+ height: 100%;
228
+ pointer-events: none;
229
+ left: -10px;
230
+ background-image: linear-gradient(to left, rgb(0 0 0 / 20%), rgb(0 0 0 / 0%));
231
+ }
232
+
233
+ .cn-flyover-header {
234
+ height: 45px;
235
+ display: flex;
236
+ align-items: center;
237
+ gap: 5px;
238
+ border-bottom: 1px solid var(--border-color);
239
+ }
240
+
241
+ .cn-flyover-close {
242
+ display: flex;
243
+ align-items: center;
244
+ padding: 0 10px;
245
+ justify-content: center;
246
+ cursor: pointer;
247
+ opacity: 0.8;
248
+ height: 100%;
249
+ }
250
+
251
+ .cn-flyover-close:hover {
252
+ opacity: 1;
253
+ }
254
+
255
+ .cn-flyover-close svg {
256
+ display: block;
257
+ margin: 0;
258
+ pointer-events: none;
259
+ width: 20px;
260
+ height: 20px;
261
+ }
262
+
263
+ .cn-flyover-title {
264
+ display: flex;
265
+ align-items: center;
266
+ font-weight: bold;
267
+ gap: 10px;
268
+ flex: auto;
269
+ }
270
+
271
+ .cn-flyover-body {
272
+ height: calc(100% - 45px);
273
+ overflow-y: auto;
274
+ position: relative;
275
+ background-color: var(--comfy-menu-secondary-bg);
276
+ }
277
+
278
+ @keyframes cn-slide-in-right {
279
+ from {
280
+ visibility: visible;
281
+ transform: translate3d(100%, 0, 0);
282
+ }
283
+
284
+ to {
285
+ transform: translate3d(0, 0, 0);
286
+ }
287
+ }
288
+
289
+ .cn-slide-in-right {
290
+ animation-name: cn-slide-in-right;
291
+ }
292
+
293
+ @keyframes cn-slide-out-right {
294
+ from {
295
+ transform: translate3d(0, 0, 0);
296
+ }
297
+
298
+ to {
299
+ visibility: hidden;
300
+ transform: translate3d(100%, 0, 0);
301
+ }
302
+ }
303
+
304
+ .cn-slide-out-right {
305
+ animation-name: cn-slide-out-right;
306
+ }
307
+
308
+ .cn-nodes-list {
309
+ width: 100%;
310
+ }
311
+
312
+ .cn-nodes-row {
313
+ display: flex;
314
+ align-items: center;
315
+ gap: 10px;
316
+ }
317
+
318
+ .cn-nodes-row:nth-child(odd) {
319
+ background-color: rgb(0 0 0 / 5%);
320
+ }
321
+
322
+ .cn-nodes-row:hover {
323
+ background-color: rgb(0 0 0 / 10%);
324
+ }
325
+
326
+ .cn-nodes-sn {
327
+ text-align: right;
328
+ min-width: 35px;
329
+ color: var(--drag-text);
330
+ flex-shrink: 0;
331
+ font-size: 12px;
332
+ padding: 8px 5px;
333
+ }
334
+
335
+ .cn-nodes-name {
336
+ cursor: pointer;
337
+ white-space: nowrap;
338
+ flex-shrink: 0;
339
+ position: relative;
340
+ padding: 8px 5px;
341
+ }
342
+
343
+ .cn-nodes-name::after {
344
+ content: attr(action);
345
+ position: absolute;
346
+ pointer-events: none;
347
+ top: 50%;
348
+ left: 100%;
349
+ transform: translate(5px, -50%);
350
+ font-size: 12px;
351
+ color: var(--drag-text);
352
+ background-color: var(--comfy-input-bg);
353
+ border-radius: 10px;
354
+ border: 1px solid var(--border-color);
355
+ padding: 3px 8px;
356
+ display: none;
357
+ }
358
+
359
+ .cn-nodes-name.action::after {
360
+ display: block;
361
+ }
362
+
363
+ .cn-nodes-name:hover {
364
+ text-decoration: underline;
365
+ }
366
+
367
+ .cn-nodes-conflict .cn-nodes-name,
368
+ .cn-nodes-conflict .cn-icon {
369
+ color: orange;
370
+ }
371
+
372
+ .cn-conflicts-list {
373
+ display: flex;
374
+ flex-wrap: wrap;
375
+ gap: 5px;
376
+ align-items: center;
377
+ padding: 5px 0;
378
+ }
379
+
380
+ .cn-conflicts-list b {
381
+ font-weight: normal;
382
+ color: var(--descrip-text);
383
+ }
384
+
385
+ .cn-nodes-pack {
386
+ cursor: pointer;
387
+ color: skyblue;
388
+ }
389
+
390
+ .cn-nodes-pack:hover {
391
+ text-decoration: underline;
392
+ }
393
+
394
+ .cn-pack-badge {
395
+ font-size: 12px;
396
+ font-weight: normal;
397
+ background-color: var(--comfy-input-bg);
398
+ border-radius: 10px;
399
+ border: 1px solid var(--border-color);
400
+ padding: 3px 8px;
401
+ color: var(--error-text);
402
+ }
403
+
404
+ .cn-preview {
405
+ min-width: 300px;
406
+ max-width: 500px;
407
+ min-height: 120px;
408
+ overflow: hidden;
409
+ font-size: 12px;
410
+ pointer-events: none;
411
+ padding: 12px;
412
+ color: var(--fg-color);
413
+ }
414
+
415
+ .cn-preview-header {
416
+ display: flex;
417
+ gap: 8px;
418
+ align-items: center;
419
+ border-bottom: 1px solid var(--comfy-input-bg);
420
+ padding: 5px 10px;
421
+ }
422
+
423
+ .cn-preview-dot {
424
+ width: 8px;
425
+ height: 8px;
426
+ border-radius: 50%;
427
+ background-color: grey;
428
+ position: relative;
429
+ filter: drop-shadow(1px 2px 3px rgb(0 0 0 / 30%));
430
+ }
431
+
432
+ .cn-preview-dot.cn-preview-optional::after {
433
+ content: "";
434
+ position: absolute;
435
+ pointer-events: none;
436
+ top: 50%;
437
+ left: 50%;
438
+ transform: translate(-50%, -50%);
439
+ background-color: var(--comfy-input-bg);
440
+ border-radius: 50%;
441
+ width: 3px;
442
+ height: 3px;
443
+ }
444
+
445
+ .cn-preview-dot.cn-preview-grid {
446
+ border-radius: 0;
447
+ }
448
+
449
+ .cn-preview-dot.cn-preview-grid::before {
450
+ content: '';
451
+ position: absolute;
452
+ border-left: 1px solid var(--comfy-input-bg);
453
+ border-right: 1px solid var(--comfy-input-bg);
454
+ width: 4px;
455
+ height: 100%;
456
+ left: 2px;
457
+ top: 0;
458
+ z-index: 1;
459
+ }
460
+
461
+ .cn-preview-dot.cn-preview-grid::after {
462
+ content: '';
463
+ position: absolute;
464
+ border-top: 1px solid var(--comfy-input-bg);
465
+ border-bottom: 1px solid var(--comfy-input-bg);
466
+ width: 100%;
467
+ height: 4px;
468
+ left: 0;
469
+ top: 2px;
470
+ z-index: 1;
471
+ }
472
+
473
+ .cn-preview-name {
474
+ flex: auto;
475
+ font-size: 14px;
476
+ }
477
+
478
+ .cn-preview-io {
479
+ display: flex;
480
+ justify-content: space-between;
481
+ padding: 10px 10px;
482
+ }
483
+
484
+ .cn-preview-column > div {
485
+ display: flex;
486
+ gap: 10px;
487
+ align-items: center;
488
+ height: 18px;
489
+ overflow: hidden;
490
+ white-space: nowrap;
491
+ text-overflow: ellipsis;
492
+ }
493
+
494
+ .cn-preview-input {
495
+ justify-content: flex-start;
496
+ }
497
+
498
+ .cn-preview-output {
499
+ justify-content: flex-end;
500
+ }
501
+
502
+ .cn-preview-list {
503
+ display: flex;
504
+ flex-direction: column;
505
+ gap: 3px;
506
+ padding: 0 10px 10px 10px;
507
+ }
508
+
509
+ .cn-preview-switch {
510
+ position: relative;
511
+ display: flex;
512
+ justify-content: space-between;
513
+ align-items: center;
514
+ background: var(--bg-color);
515
+ border: 2px solid var(--border-color);
516
+ border-radius: 10px;
517
+ text-wrap: nowrap;
518
+ padding: 2px 20px;
519
+ gap: 10px;
520
+ }
521
+
522
+ .cn-preview-switch::before,
523
+ .cn-preview-switch::after {
524
+ position: absolute;
525
+ pointer-events: none;
526
+ top: 50%;
527
+ transform: translate(0, -50%);
528
+ color: var(--fg-color);
529
+ opacity: 0.8;
530
+ }
531
+
532
+ .cn-preview-switch::before {
533
+ content: "◀";
534
+ left: 5px;
535
+ }
536
+
537
+ .cn-preview-switch::after {
538
+ content: "▶";
539
+ right: 5px;
540
+ }
541
+
542
+ .cn-preview-value {
543
+ color: var(--descrip-text);
544
+ }
545
+
546
+ .cn-preview-string {
547
+ min-height: 30px;
548
+ max-height: 300px;
549
+ background: var(--bg-color);
550
+ color: var(--descrip-text);
551
+ border-radius: 3px;
552
+ padding: 3px 5px;
553
+ overflow-y: auto;
554
+ overflow-x: hidden;
555
+ }
556
+
557
+ .cn-preview-description {
558
+ margin: 0px 10px 10px 10px;
559
+ padding: 6px;
560
+ background: var(--border-color);
561
+ color: var(--descrip-text);
562
+ border-radius: 5px;
563
+ font-style: italic;
564
+ word-break: break-word;
565
+ }
566
+
567
+ .cn-tag-list {
568
+ display: flex;
569
+ flex-wrap: wrap;
570
+ gap: 5px;
571
+ align-items: center;
572
+ margin-bottom: 5px;
573
+ }
574
+
575
+ .cn-tag-list > div {
576
+ background-color: var(--border-color);
577
+ border-radius: 5px;
578
+ padding: 0 5px;
579
+ }
580
+
581
+ .cn-install-buttons {
582
+ display: flex;
583
+ flex-direction: column;
584
+ gap: 3px;
585
+ padding: 3px;
586
+ align-items: center;
587
+ justify-content: center;
588
+ height: 100%;
589
+ }
590
+
591
+ .cn-selected-buttons {
592
+ display: flex;
593
+ gap: 5px;
594
+ align-items: center;
595
+ padding-right: 20px;
596
+ }
597
+
598
+ .cn-manager .cn-btn-enable {
599
+ background-color: #333399;
600
+ color: white;
601
+ }
602
+
603
+ .cn-manager .cn-btn-disable {
604
+ background-color: #442277;
605
+ color: white;
606
+ }
607
+
608
+ .cn-manager .cn-btn-update {
609
+ background-color: #1155AA;
610
+ color: white;
611
+ }
612
+
613
+ .cn-manager .cn-btn-try-update {
614
+ background-color: Gray;
615
+ color: white;
616
+ }
617
+
618
+ .cn-manager .cn-btn-try-fix {
619
+ background-color: #6495ED;
620
+ color: white;
621
+ }
622
+
623
+ .cn-manager .cn-btn-import-failed {
624
+ background-color: #AA1111;
625
+ font-size: 10px;
626
+ font-weight: bold;
627
+ color: white;
628
+ }
629
+
630
+ .cn-manager .cn-btn-install {
631
+ background-color: black;
632
+ color: white;
633
+ }
634
+
635
+ .cn-manager .cn-btn-try-install {
636
+ background-color: Gray;
637
+ color: white;
638
+ }
639
+
640
+ .cn-manager .cn-btn-uninstall {
641
+ background-color: #993333;
642
+ color: white;
643
+ }
644
+
645
+ .cn-manager .cn-btn-reinstall {
646
+ background-color: #993333;
647
+ color: white;
648
+ }
649
+
650
+ .cn-manager .cn-btn-switch {
651
+ background-color: #448833;
652
+ color: white;
653
+
654
+ }
655
+
656
+ @keyframes cn-btn-loading-bg {
657
+ 0% {
658
+ left: 0;
659
+ }
660
+ 100% {
661
+ left: -105px;
662
+ }
663
+ }
664
+
665
+ .cn-manager button.cn-btn-loading {
666
+ position: relative;
667
+ overflow: hidden;
668
+ border-color: rgb(0 119 207 / 80%);
669
+ background-color: var(--comfy-input-bg);
670
+ }
671
+
672
+ .cn-manager button.cn-btn-loading::after {
673
+ position: absolute;
674
+ top: 0;
675
+ left: 0;
676
+ content: "";
677
+ width: 500px;
678
+ height: 100%;
679
+ background-image: repeating-linear-gradient(
680
+ -45deg,
681
+ rgb(0 119 207 / 30%),
682
+ rgb(0 119 207 / 30%) 10px,
683
+ transparent 10px,
684
+ transparent 15px
685
+ );
686
+ animation: cn-btn-loading-bg 2s linear infinite;
687
+ }
688
+
689
+ .cn-manager-light .cn-pack-name a {
690
+ color: blue;
691
+ }
692
+
693
+ .cn-manager-light .cm-warn-note {
694
+ background-color: #ccc !important;
695
+ }
696
+
697
+ .cn-manager-light .cn-btn-install {
698
+ background-color: #333;
699
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/js/custom-nodes-manager.js ADDED
@@ -0,0 +1,2173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../scripts/app.js";
2
+ import { ComfyDialog, $el } from "../../scripts/ui.js";
3
+ import { api } from "../../scripts/api.js";
4
+
5
+ import {
6
+ manager_instance, rebootAPI, install_via_git_url,
7
+ fetchData, md5, icons, show_message, customConfirm, customAlert, customPrompt,
8
+ sanitizeHTML, infoToast, showTerminal, setNeedRestart,
9
+ storeColumnWidth, restoreColumnWidth, getTimeAgo, copyText, loadCss,
10
+ showPopover, hidePopover
11
+ } from "./common.js";
12
+
13
+ // https://cenfun.github.io/turbogrid/api.html
14
+ import TG from "./turbogrid.esm.js";
15
+
16
+ loadCss("./custom-nodes-manager.css");
17
+
18
+ const gridId = "node";
19
+
20
+ const pageHtml = `
21
+ <div class="cn-manager-header">
22
+ <label>Filter
23
+ <select class="cn-manager-filter"></select>
24
+ </label>
25
+ <input class="cn-manager-keywords" type="search" placeholder="Search" />
26
+ <div class="cn-manager-status"></div>
27
+ <div class="cn-flex-auto"></div>
28
+ <div class="cn-manager-channel"></div>
29
+ </div>
30
+ <div class="cn-manager-grid"></div>
31
+ <div class="cn-manager-selection"></div>
32
+ <div class="cn-manager-message"></div>
33
+ <div class="cn-manager-footer">
34
+ <button class="cn-manager-back">
35
+ <svg class="arrow-icon" width="14" height="14" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
36
+ <path d="M2 8H18M2 8L8 2M2 8L8 14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
37
+ </svg>
38
+ Back
39
+ </button>
40
+ <button class="cn-manager-restart">Restart</button>
41
+ <button class="cn-manager-stop">Stop</button>
42
+ <div class="cn-flex-auto"></div>
43
+ <button class="cn-manager-used-in-workflow">Used In Workflow</button>
44
+ <button class="cn-manager-check-update">Check Update</button>
45
+ <button class="cn-manager-check-missing">Check Missing</button>
46
+ <button class="cn-manager-install-url">Install via Git URL</button>
47
+ </div>
48
+ `;
49
+
50
+ const ShowMode = {
51
+ NORMAL: "Normal",
52
+ UPDATE: "Update",
53
+ MISSING: "Missing",
54
+ FAVORITES: "Favorites",
55
+ ALTERNATIVES: "Alternatives",
56
+ IN_WORKFLOW: "In Workflow",
57
+ };
58
+
59
+ export class CustomNodesManager {
60
+ static instance = null;
61
+ static ShowMode = ShowMode;
62
+
63
+ constructor(app, manager_dialog) {
64
+ this.app = app;
65
+ this.manager_dialog = manager_dialog;
66
+ this.id = "cn-manager";
67
+
68
+ app.registerExtension({
69
+ name: "Comfy.CustomNodesManager",
70
+ afterConfigureGraph: (missingNodeTypes) => {
71
+ const item = this.getFilterItem(ShowMode.MISSING);
72
+ if (item) {
73
+ item.hasData = false;
74
+ item.hashMap = null;
75
+ }
76
+ }
77
+ });
78
+
79
+ this.filter = '';
80
+ this.keywords = '';
81
+ this.restartMap = {};
82
+
83
+ this.init();
84
+
85
+ api.addEventListener("cm-queue-status", this.onQueueStatus);
86
+ api.getNodeDefs().then(objs => {
87
+ this.nodeMap = objs;
88
+ })
89
+ }
90
+
91
+ init() {
92
+ this.element = $el("div", {
93
+ parent: document.body,
94
+ className: "comfy-modal cn-manager"
95
+ });
96
+ this.element.innerHTML = pageHtml;
97
+ this.element.setAttribute("tabindex", 0);
98
+ this.element.focus();
99
+
100
+ this.initFilter();
101
+ this.bindEvents();
102
+ this.initGrid();
103
+ }
104
+
105
+ showVersionSelectorDialog(versions, onSelect) {
106
+ const dialog = new ComfyDialog();
107
+ dialog.element.style.zIndex = 1100;
108
+ dialog.element.style.width = "300px";
109
+ dialog.element.style.padding = "0";
110
+ dialog.element.style.backgroundColor = "#2a2a2a";
111
+ dialog.element.style.border = "1px solid #3a3a3a";
112
+ dialog.element.style.borderRadius = "8px";
113
+ dialog.element.style.boxSizing = "border-box";
114
+ dialog.element.style.overflow = "hidden";
115
+
116
+ const contentStyle = {
117
+ width: "300px",
118
+ display: "flex",
119
+ flexDirection: "column",
120
+ alignItems: "center",
121
+ padding: "20px",
122
+ boxSizing: "border-box",
123
+ gap: "15px"
124
+ };
125
+
126
+ let selectedVersion = versions[0];
127
+
128
+ const versionList = $el("select", {
129
+ multiple: true,
130
+ size: Math.min(10, versions.length),
131
+ style: {
132
+ width: "260px",
133
+ height: "auto",
134
+ backgroundColor: "#383838",
135
+ color: "#ffffff",
136
+ border: "1px solid #4a4a4a",
137
+ borderRadius: "4px",
138
+ padding: "5px",
139
+ boxSizing: "border-box"
140
+ }
141
+ },
142
+ versions.map((v, index) => $el("option", {
143
+ value: v,
144
+ textContent: v,
145
+ selected: index === 0
146
+ }))
147
+ );
148
+
149
+ versionList.addEventListener('change', (e) => {
150
+ selectedVersion = e.target.value;
151
+ Array.from(e.target.options).forEach(opt => {
152
+ opt.selected = opt.value === selectedVersion;
153
+ });
154
+ });
155
+
156
+ const content = $el("div", {
157
+ style: contentStyle
158
+ }, [
159
+ $el("h3", {
160
+ textContent: "Select Version",
161
+ style: {
162
+ color: "#ffffff",
163
+ backgroundColor: "#1a1a1a",
164
+ padding: "10px 15px",
165
+ margin: "0 0 10px 0",
166
+ width: "260px",
167
+ textAlign: "center",
168
+ borderRadius: "4px",
169
+ boxSizing: "border-box",
170
+ whiteSpace: "nowrap",
171
+ overflow: "hidden",
172
+ textOverflow: "ellipsis"
173
+ }
174
+ }),
175
+ versionList,
176
+ $el("div", {
177
+ style: {
178
+ display: "flex",
179
+ justifyContent: "space-between",
180
+ width: "260px",
181
+ gap: "10px"
182
+ }
183
+ }, [
184
+ $el("button", {
185
+ textContent: "Cancel",
186
+ onclick: () => dialog.close(),
187
+ style: {
188
+ flex: "1",
189
+ padding: "8px",
190
+ backgroundColor: "#4a4a4a",
191
+ color: "#ffffff",
192
+ border: "none",
193
+ borderRadius: "4px",
194
+ cursor: "pointer",
195
+ whiteSpace: "nowrap",
196
+ overflow: "hidden",
197
+ textOverflow: "ellipsis"
198
+ }
199
+ }),
200
+ $el("button", {
201
+ textContent: "Select",
202
+ onclick: () => {
203
+ if (selectedVersion) {
204
+ onSelect(selectedVersion);
205
+ dialog.close();
206
+ } else {
207
+ customAlert("Please select a version.");
208
+ }
209
+ },
210
+ style: {
211
+ flex: "1",
212
+ padding: "8px",
213
+ backgroundColor: "#4CAF50",
214
+ color: "#ffffff",
215
+ border: "none",
216
+ borderRadius: "4px",
217
+ cursor: "pointer",
218
+ whiteSpace: "nowrap",
219
+ overflow: "hidden",
220
+ textOverflow: "ellipsis"
221
+ }
222
+ }),
223
+ ])
224
+ ]);
225
+
226
+ dialog.show(content);
227
+ }
228
+
229
+ initFilter() {
230
+ const $filter = this.element.querySelector(".cn-manager-filter");
231
+ const filterList = [{
232
+ label: "All",
233
+ value: "",
234
+ hasData: true
235
+ }, {
236
+ label: "Installed",
237
+ value: "installed",
238
+ hasData: true
239
+ }, {
240
+ label: "Enabled",
241
+ value: "enabled",
242
+ hasData: true
243
+ }, {
244
+ label: "Disabled",
245
+ value: "disabled",
246
+ hasData: true
247
+ }, {
248
+ label: "Import Failed",
249
+ value: "import-fail",
250
+ hasData: true
251
+ }, {
252
+ label: "Not Installed",
253
+ value: "not-installed",
254
+ hasData: true
255
+ }, {
256
+ label: "ComfyRegistry",
257
+ value: "cnr",
258
+ hasData: true
259
+ }, {
260
+ label: "Non-ComfyRegistry",
261
+ value: "unknown",
262
+ hasData: true
263
+ }, {
264
+ label: "Update",
265
+ value: ShowMode.UPDATE,
266
+ hasData: false
267
+ }, {
268
+ label: "In Workflow",
269
+ value: ShowMode.IN_WORKFLOW,
270
+ hasData: false
271
+ }, {
272
+ label: "Missing",
273
+ value: ShowMode.MISSING,
274
+ hasData: false
275
+ }, {
276
+ label: "Favorites",
277
+ value: ShowMode.FAVORITES,
278
+ hasData: false
279
+ }, {
280
+ label: "Alternatives of A1111",
281
+ value: ShowMode.ALTERNATIVES,
282
+ hasData: false
283
+ }];
284
+ this.filterList = filterList;
285
+ $filter.innerHTML = filterList.map(item => {
286
+ return `<option value="${item.value}">${item.label}</option>`
287
+ }).join("");
288
+ }
289
+
290
+ getFilterItem(filter) {
291
+ return this.filterList.find(it => it.value === filter)
292
+ }
293
+
294
+ getActionButtons(action, rowItem, is_selected_button) {
295
+ const buttons = {
296
+ "enable": {
297
+ label: "Enable",
298
+ mode: "enable"
299
+ },
300
+ "disable": {
301
+ label: "Disable",
302
+ mode: "disable"
303
+ },
304
+
305
+ "update": {
306
+ label: "Update",
307
+ mode: "update"
308
+ },
309
+ "try-update": {
310
+ label: "Try update",
311
+ mode: "update"
312
+ },
313
+
314
+ "try-fix": {
315
+ label: "Try fix",
316
+ mode: "fix"
317
+ },
318
+
319
+ "reinstall": {
320
+ label: "Reinstall",
321
+ mode: "reinstall"
322
+ },
323
+
324
+ "install": {
325
+ label: "Install",
326
+ mode: "install"
327
+ },
328
+
329
+ "try-install": {
330
+ label: "Try install",
331
+ mode: "install"
332
+ },
333
+
334
+ "uninstall": {
335
+ label: "Uninstall",
336
+ mode: "uninstall"
337
+ },
338
+
339
+ "switch": {
340
+ label: "Switch Ver",
341
+ mode: "switch"
342
+ }
343
+ }
344
+
345
+ const installGroups = {
346
+ "disabled": ["enable", "switch", "uninstall"],
347
+ "updatable": ["update", "switch", "disable", "uninstall"],
348
+ "import-fail": ["try-fix", "switch", "disable", "uninstall"],
349
+ "enabled": ["try-update", "switch", "disable", "uninstall"],
350
+ "not-installed": ["install"],
351
+ 'unknown': ["try-install"],
352
+ "invalid-installation": ["reinstall"],
353
+ }
354
+
355
+ if (!installGroups.updatable) {
356
+ installGroups.enabled = installGroups.enabled.filter(it => it !== "try-update");
357
+ }
358
+
359
+ if (rowItem?.title === "ComfyUI-Manager") {
360
+ installGroups.enabled = installGroups.enabled.filter(it => it !== "disable" && it !== "uninstall" && it !== "switch");
361
+ }
362
+
363
+ let list = installGroups[action];
364
+
365
+ if(is_selected_button || rowItem?.version === "unknown") {
366
+ list = list.filter(it => it !== "switch");
367
+ }
368
+
369
+ if (!list) {
370
+ return "";
371
+ }
372
+
373
+ return list.map(id => {
374
+ const bt = buttons[id];
375
+ return `<button class="cn-btn-${id}" group="${action}" mode="${bt.mode}">${bt.label}</button>`;
376
+ }).join("");
377
+ }
378
+
379
+ getButton(target) {
380
+ if(!target) {
381
+ return;
382
+ }
383
+ const mode = target.getAttribute("mode");
384
+ if (!mode) {
385
+ return;
386
+ }
387
+ const group = target.getAttribute("group");
388
+ if (!group) {
389
+ return;
390
+ }
391
+ return {
392
+ group,
393
+ mode,
394
+ target,
395
+ label: target.innerText
396
+ }
397
+ }
398
+
399
+ bindEvents() {
400
+ const eventsMap = {
401
+ ".cn-manager-filter": {
402
+ change: (e) => {
403
+
404
+ if (this.grid) {
405
+ this.grid.selectAll(false);
406
+ }
407
+
408
+ const value = e.target.value
409
+ this.filter = value;
410
+ const item = this.getFilterItem(value);
411
+ if (item && (!item.hasData)) {
412
+ this.loadData(value);
413
+ return;
414
+ }
415
+ this.updateGrid();
416
+ }
417
+ },
418
+
419
+ ".cn-manager-keywords": {
420
+ input: (e) => {
421
+ const keywords = `${e.target.value}`.trim();
422
+ if (keywords !== this.keywords) {
423
+ this.keywords = keywords;
424
+ this.updateGrid();
425
+ }
426
+ },
427
+ focus: (e) => e.target.select()
428
+ },
429
+
430
+ ".cn-manager-selection": {
431
+ click: (e) => {
432
+ const btn = this.getButton(e.target);
433
+ if (btn) {
434
+ const nodes = this.selectedMap[btn.group];
435
+ if (nodes) {
436
+ this.installNodes(nodes, btn);
437
+ }
438
+ }
439
+ }
440
+ },
441
+
442
+ ".cn-manager-back": {
443
+ click: (e) => {
444
+ this.flyover.hide(true);
445
+ this.removeHighlight();
446
+ hidePopover();
447
+ this.close()
448
+ manager_instance.show();
449
+ }
450
+ },
451
+
452
+ ".cn-manager-restart": {
453
+ click: () => {
454
+ this.close();
455
+ this.manager_dialog.close();
456
+ rebootAPI();
457
+ }
458
+ },
459
+
460
+ ".cn-manager-stop": {
461
+ click: () => {
462
+ api.fetchApi('/manager/queue/reset');
463
+ infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
464
+ }
465
+ },
466
+
467
+ ".cn-manager-used-in-workflow": {
468
+ click: (e) => {
469
+ e.target.classList.add("cn-btn-loading");
470
+ this.setFilter(ShowMode.IN_WORKFLOW);
471
+ this.loadData(ShowMode.IN_WORKFLOW);
472
+ }
473
+ },
474
+
475
+ ".cn-manager-check-update": {
476
+ click: (e) => {
477
+ e.target.classList.add("cn-btn-loading");
478
+ this.setFilter(ShowMode.UPDATE);
479
+ this.loadData(ShowMode.UPDATE);
480
+ }
481
+ },
482
+
483
+ ".cn-manager-check-missing": {
484
+ click: (e) => {
485
+ e.target.classList.add("cn-btn-loading");
486
+ this.setFilter(ShowMode.MISSING);
487
+ this.loadData(ShowMode.MISSING);
488
+ }
489
+ },
490
+
491
+ ".cn-manager-install-url": {
492
+ click: async (e) => {
493
+ const url = await customPrompt("Please enter the URL of the Git repository to install", "");
494
+ if (url !== null) {
495
+ install_via_git_url(url, this.manager_dialog);
496
+ }
497
+ }
498
+ }
499
+ };
500
+ Object.keys(eventsMap).forEach(selector => {
501
+ const target = this.element.querySelector(selector);
502
+ if (target) {
503
+ const events = eventsMap[selector];
504
+ if (events) {
505
+ Object.keys(events).forEach(type => {
506
+ target.addEventListener(type, events[type]);
507
+ });
508
+ }
509
+ }
510
+ });
511
+
512
+ }
513
+
514
+ // ===========================================================================================
515
+
516
+ initGrid() {
517
+ const container = this.element.querySelector(".cn-manager-grid");
518
+ const grid = new TG.Grid(container);
519
+ this.grid = grid;
520
+
521
+ this.flyover = this.createFlyover(container);
522
+
523
+ let prevViewRowsLength = -1;
524
+ grid.bind('onUpdated', (e, d) => {
525
+ const viewRows = grid.viewRows;
526
+ prevViewRowsLength = viewRows.length;
527
+ this.showStatus(`${prevViewRowsLength.toLocaleString()} custom nodes`);
528
+ });
529
+
530
+ grid.bind('onSelectChanged', (e, changes) => {
531
+ this.renderSelected();
532
+ });
533
+
534
+ grid.bind("onColumnWidthChanged", (e, columnItem) => {
535
+ storeColumnWidth(gridId, columnItem)
536
+ });
537
+
538
+ grid.bind('onClick', (e, d) => {
539
+
540
+ this.addHighlight(d.rowItem);
541
+
542
+ if (d.columnItem.id === "nodes") {
543
+ this.showNodes(d);
544
+ return;
545
+ }
546
+
547
+ const btn = this.getButton(d.e.target);
548
+ if (btn) {
549
+ const item = this.grid.getRowItemBy("hash", d.rowItem.hash);
550
+
551
+ const { target, label, mode} = btn;
552
+ if((mode === "install" || mode === "switch" || mode == "enable") && item.originalData.version != 'unknown') {
553
+ // install after select version via dialog if item is cnr node
554
+ this.installNodeWithVersion(d.rowItem, btn, mode == 'enable');
555
+ } else {
556
+ this.installNodes([d.rowItem.hash], btn, d.rowItem.title);
557
+ }
558
+ return;
559
+ }
560
+
561
+ });
562
+
563
+ // iteration events
564
+ this.element.addEventListener("click", (e) => {
565
+ if (container === e.target || container.contains(e.target)) {
566
+ return;
567
+ }
568
+ this.removeHighlight();
569
+ });
570
+ // proxy keyboard events
571
+ this.element.addEventListener("keydown", (e) => {
572
+ if (e.target === this.element) {
573
+ grid.containerKeyDownHandler(e);
574
+ }
575
+ }, true);
576
+
577
+
578
+ grid.setOption({
579
+ theme: 'dark',
580
+ selectVisible: true,
581
+ selectMultiple: true,
582
+ selectAllVisible: true,
583
+
584
+ textSelectable: true,
585
+ scrollbarRound: true,
586
+
587
+ frozenColumn: 1,
588
+ rowNotFound: "No Results",
589
+
590
+ rowHeight: 40,
591
+ bindWindowResize: true,
592
+ bindContainerResize: true,
593
+
594
+ cellResizeObserver: (rowItem, columnItem) => {
595
+ const autoHeightColumns = ['title', 'action', 'description', "alternatives"];
596
+ return autoHeightColumns.includes(columnItem.id)
597
+ },
598
+
599
+ // updateGrid handler for filter and keywords
600
+ rowFilter: (rowItem) => {
601
+
602
+ const searchableColumns = ["title", "author", "description"];
603
+ if (this.hasAlternatives()) {
604
+ searchableColumns.push("alternatives");
605
+ }
606
+
607
+ let shouldShown = grid.highlightKeywordsFilter(rowItem, searchableColumns, this.keywords);
608
+
609
+ if (shouldShown) {
610
+ if(this.filter && rowItem.filterTypes) {
611
+ shouldShown = rowItem.filterTypes.includes(this.filter);
612
+ }
613
+ }
614
+
615
+ return shouldShown;
616
+ }
617
+ });
618
+
619
+ }
620
+
621
+ hasAlternatives() {
622
+ return this.filter === ShowMode.ALTERNATIVES
623
+ }
624
+
625
+ async handleImportFail(rowItem) {
626
+ var info;
627
+ if(rowItem.version == 'unknown'){
628
+ info = {
629
+ 'url': rowItem.originalData.files[0]
630
+ };
631
+ }
632
+ else{
633
+ info = {
634
+ 'cnr_id': rowItem.originalData.id
635
+ };
636
+ }
637
+
638
+ const response = await api.fetchApi(`/customnode/import_fail_info`, {
639
+ method: 'POST',
640
+ headers: { 'Content-Type': 'application/json' },
641
+ body: JSON.stringify(info)
642
+ });
643
+
644
+ let res = await response.json();
645
+
646
+ let title = `<FONT COLOR=GREEN><B>Error message occurred while importing the '${rowItem.title}' module.</B></FONT><BR><HR><BR>`
647
+
648
+ if(res.code == 400)
649
+ {
650
+ show_message(title+'The information is not available.')
651
+ }
652
+ else {
653
+ show_message(title+sanitizeHTML(res['msg']).replace(/ /g, '&nbsp;').replace(/\n/g, '<BR>'));
654
+ }
655
+ }
656
+
657
+ renderGrid() {
658
+
659
+ // update theme
660
+ const globalStyle = window.getComputedStyle(document.body);
661
+ this.colorVars = {
662
+ bgColor: globalStyle.getPropertyValue('--comfy-menu-bg'),
663
+ borderColor: globalStyle.getPropertyValue('--border-color')
664
+ }
665
+
666
+ const colorPalette = this.app.ui.settings.settingsValues['Comfy.ColorPalette'];
667
+ this.colorPalette = colorPalette;
668
+ Array.from(this.element.classList).forEach(cn => {
669
+ if (cn.startsWith("cn-manager-")) {
670
+ this.element.classList.remove(cn);
671
+ }
672
+ });
673
+ this.element.classList.add(`cn-manager-${colorPalette}`);
674
+
675
+ const options = {
676
+ theme: colorPalette === "light" ? "" : "dark"
677
+ };
678
+
679
+
680
+ let self = this;
681
+ const columns = [{
682
+ id: 'id',
683
+ name: 'ID',
684
+ width: 50,
685
+ align: 'center'
686
+ }, {
687
+ id: 'title',
688
+ name: 'Title',
689
+ width: 200,
690
+ minWidth: 100,
691
+ maxWidth: 500,
692
+ classMap: 'cn-pack-name',
693
+ formatter: (title, rowItem, columnItem) => {
694
+ const container = document.createElement('div');
695
+
696
+ if (rowItem.action === 'invalid-installation') {
697
+ const invalidTag = document.createElement('span');
698
+ invalidTag.style.color = 'red';
699
+ invalidTag.innerHTML = '<b>(INVALID)</b>';
700
+ container.appendChild(invalidTag);
701
+ } else if (rowItem.action === 'import-fail') {
702
+ const button = document.createElement('button');
703
+ button.className = 'cn-btn-import-failed';
704
+ button.innerText = 'IMPORT FAILED ↗';
705
+ button.onclick = () => self.handleImportFail(rowItem);
706
+ container.appendChild(button);
707
+ container.appendChild(document.createElement('br'));
708
+ }
709
+
710
+ const link = document.createElement('a');
711
+ if(rowItem.originalData.repository)
712
+ link.href = rowItem.originalData.repository;
713
+ else
714
+ link.href = rowItem.reference;
715
+ link.target = '_blank';
716
+ link.innerHTML = `<b>${title}</b>`;
717
+ container.appendChild(link);
718
+
719
+ return container;
720
+ }
721
+ }, {
722
+ id: 'version',
723
+ name: 'Version',
724
+ width: 100,
725
+ minWidth: 80,
726
+ maxWidth: 300,
727
+ classMap: 'cn-pack-version',
728
+ formatter: (version, rowItem, columnItem) => {
729
+ if(!version) {
730
+ return;
731
+ }
732
+ if(rowItem.cnr_latest && version != rowItem.cnr_latest) {
733
+ if(version == 'nightly') {
734
+ return `<div>${version}</div><div>[${rowItem.cnr_latest}]</div>`;
735
+ }
736
+ return `<div>${version}</div><div>[↑${rowItem.cnr_latest}]</div>`;
737
+ }
738
+ return version;
739
+ }
740
+ }, {
741
+ id: 'action',
742
+ name: 'Action',
743
+ width: 130,
744
+ minWidth: 110,
745
+ maxWidth: 200,
746
+ sortable: false,
747
+ align: 'center',
748
+ formatter: (action, rowItem, columnItem) => {
749
+ if (rowItem.restart) {
750
+ return `<font color="red">Restart Required</span>`;
751
+ }
752
+ const buttons = this.getActionButtons(action, rowItem);
753
+ return `<div class="cn-install-buttons">${buttons}</div>`;
754
+ }
755
+ }, {
756
+ id: "nodes",
757
+ name: "Nodes",
758
+ width: 100,
759
+ formatter: (v, rowItem, columnItem) => {
760
+ if (!rowItem.nodes) {
761
+ return '';
762
+ }
763
+ const list = [`<div class="cn-pack-nodes">`];
764
+ list.push(`<div>${rowItem.nodes} node${(rowItem.nodes>1?'s':'')}</div>`);
765
+ if (rowItem.conflicts) {
766
+ list.push(`<div class="cn-pack-conflicts">${rowItem.conflicts} conflict${(rowItem.conflicts>1?'s':'')}</div>`);
767
+ }
768
+ list.push('</div>');
769
+ return list.join("");
770
+ }
771
+ }, {
772
+ id: "alternatives",
773
+ name: "Alternatives",
774
+ width: 400,
775
+ maxWidth: 5000,
776
+ invisible: !this.hasAlternatives(),
777
+ classMap: 'cn-pack-desc'
778
+ }, {
779
+ id: 'description',
780
+ name: 'Description',
781
+ width: 400,
782
+ maxWidth: 5000,
783
+ classMap: 'cn-pack-desc'
784
+ }, {
785
+ id: 'author',
786
+ name: 'Author',
787
+ width: 120,
788
+ classMap: "cn-pack-author",
789
+ formatter: (author, rowItem, columnItem) => {
790
+ if (rowItem.trust) {
791
+ return `<span tooltip="This author has been active for more than six months in GitHub">✅ ${author}</span>`;
792
+ }
793
+ return author;
794
+ }
795
+ }, {
796
+ id: 'stars',
797
+ name: '★',
798
+ align: 'center',
799
+ classMap: "cn-pack-stars",
800
+ formatter: (stars) => {
801
+ if (stars < 0) {
802
+ return 'N/A';
803
+ }
804
+ if (typeof stars === 'number') {
805
+ return stars.toLocaleString();
806
+ }
807
+ return stars;
808
+ }
809
+ }, {
810
+ id: 'last_update',
811
+ name: 'Last Update',
812
+ align: 'center',
813
+ type: 'date',
814
+ width: 100,
815
+ classMap: "cn-pack-last-update",
816
+ formatter: (last_update) => {
817
+ if (last_update < 0) {
818
+ return 'N/A';
819
+ }
820
+ const ago = getTimeAgo(last_update);
821
+ const short = `${last_update}`.split(' ')[0];
822
+ return `<span tooltip="${ago}">${short}</span>`;
823
+ }
824
+ }];
825
+
826
+ restoreColumnWidth(gridId, columns);
827
+
828
+ const rows_values = Object.values(this.custom_nodes);
829
+ rows_values.sort((a, b) => {
830
+ if (a.version == 'unknown' && b.version != 'unknown') return 1;
831
+ if (a.version != 'unknown' && b.version == 'unknown') return -1;
832
+
833
+ if (a.stars !== b.stars) {
834
+ return b.stars - a.stars;
835
+ }
836
+
837
+ if (a.last_update !== b.last_update) {
838
+ return new Date(b.last_update) - new Date(a.last_update);
839
+ }
840
+
841
+ return 0;
842
+ });
843
+
844
+ rows_values.forEach((it, i) => {
845
+ it.id = i + 1;
846
+ });
847
+
848
+ this.grid.setData({
849
+ options: options,
850
+ rows: rows_values,
851
+ columns: columns
852
+ });
853
+
854
+ this.grid.render();
855
+ }
856
+
857
+ updateGrid() {
858
+ if (this.grid) {
859
+ this.grid.update();
860
+ if (this.hasAlternatives()) {
861
+ this.grid.showColumn("alternatives");
862
+ } else {
863
+ this.grid.hideColumn("alternatives");
864
+ }
865
+ }
866
+ }
867
+
868
+ addHighlight(rowItem) {
869
+ this.removeHighlight();
870
+ if (this.grid && rowItem) {
871
+ this.grid.setRowState(rowItem, 'highlight', true);
872
+ this.highlightRow = rowItem;
873
+ }
874
+ }
875
+
876
+ removeHighlight() {
877
+ if (this.grid && this.highlightRow) {
878
+ this.grid.setRowState(this.highlightRow, 'highlight', false);
879
+ this.highlightRow = null;
880
+ }
881
+ }
882
+
883
+ // ===========================================================================================
884
+
885
+ getWidgetType(type, inputName) {
886
+ if (type === 'COMBO') {
887
+ return 'COMBO'
888
+ }
889
+ const widgets = app.widgets;
890
+ if (`${type}:${inputName}` in widgets) {
891
+ return `${type}:${inputName}`
892
+ }
893
+ if (type in widgets) {
894
+ return type
895
+ }
896
+ }
897
+
898
+ createNodePreview(nodeItem) {
899
+ // console.log(nodeItem);
900
+ const list = [`<div class="cn-preview-header">
901
+ <div class="cn-preview-dot"></div>
902
+ <div class="cn-preview-name">${nodeItem.name}</div>
903
+ <div class="cn-pack-badge">Preview</div>
904
+ </div>`];
905
+
906
+ // Node slot I/O
907
+ const inputList = [];
908
+ nodeItem.input_order.required?.map(name => {
909
+ inputList.push({
910
+ name
911
+ });
912
+ })
913
+ nodeItem.input_order.optional?.map(name => {
914
+ inputList.push({
915
+ name,
916
+ optional: true
917
+ });
918
+ });
919
+
920
+ const slotInputList = [];
921
+ const widgetInputList = [];
922
+ const inputMap = Object.assign({}, nodeItem.input.optional, nodeItem.input.required);
923
+ inputList.forEach(it => {
924
+ const inputName = it.name;
925
+ const _inputData = inputMap[inputName];
926
+ let type = _inputData[0];
927
+ let options = _inputData[1] || {};
928
+ if (Array.isArray(type)) {
929
+ options.default = type[0];
930
+ type = 'COMBO';
931
+ }
932
+ it.type = type;
933
+ it.options = options;
934
+
935
+ // convert force/default inputs
936
+ if (options.forceInput || options.defaultInput) {
937
+ slotInputList.push(it);
938
+ return;
939
+ }
940
+
941
+ const widgetType = this.getWidgetType(type, inputName);
942
+ if (widgetType) {
943
+ it.default = options.default;
944
+ widgetInputList.push(it);
945
+ } else {
946
+ slotInputList.push(it);
947
+ }
948
+ });
949
+
950
+ const outputList = nodeItem.output.map((type, i) => {
951
+ return {
952
+ type,
953
+ name: nodeItem.output_name[i],
954
+ list: nodeItem.output_is_list[i]
955
+ }
956
+ });
957
+
958
+ // dark
959
+ const colorMap = {
960
+ "CLIP": "#FFD500",
961
+ "CLIP_VISION": "#A8DADC",
962
+ "CLIP_VISION_OUTPUT": "#ad7452",
963
+ "CONDITIONING": "#FFA931",
964
+ "CONTROL_NET": "#6EE7B7",
965
+ "IMAGE": "#64B5F6",
966
+ "LATENT": "#FF9CF9",
967
+ "MASK": "#81C784",
968
+ "MODEL": "#B39DDB",
969
+ "STYLE_MODEL": "#C2FFAE",
970
+ "VAE": "#FF6E6E",
971
+ "NOISE": "#B0B0B0",
972
+ "GUIDER": "#66FFFF",
973
+ "SAMPLER": "#ECB4B4",
974
+ "SIGMAS": "#CDFFCD",
975
+ "TAESD": "#DCC274"
976
+ }
977
+
978
+ const inputHtml = slotInputList.map(it => {
979
+ const color = colorMap[it.type] || "gray";
980
+ const optional = it.optional ? " cn-preview-optional" : ""
981
+ return `<div class="cn-preview-input">
982
+ <div class="cn-preview-dot${optional}" style="background-color:${color}"></div>
983
+ ${it.name}
984
+ </div>`;
985
+ }).join("");
986
+
987
+ const outputHtml = outputList.map(it => {
988
+ const color = colorMap[it.type] || "gray";
989
+ const grid = it.list ? " cn-preview-grid" : "";
990
+ return `<div class="cn-preview-output">
991
+ ${it.name}
992
+ <div class="cn-preview-dot${grid}" style="background-color:${color}"></div>
993
+ </div>`;
994
+ }).join("");
995
+
996
+ list.push(`<div class="cn-preview-io">
997
+ <div class="cn-preview-column">${inputHtml}</div>
998
+ <div class="cn-preview-column">${outputHtml}</div>
999
+ </div>`);
1000
+
1001
+ // Node widget inputs
1002
+ if (widgetInputList.length) {
1003
+ list.push(`<div class="cn-preview-list">`);
1004
+
1005
+ // console.log(widgetInputList);
1006
+ widgetInputList.forEach(it => {
1007
+
1008
+ let value = it.default;
1009
+ if (typeof value === "object" && value && Object.prototype.hasOwnProperty.call(value, "content")) {
1010
+ value = value.content;
1011
+ }
1012
+ if (typeof value === "undefined" || value === null) {
1013
+ value = "";
1014
+ } else {
1015
+ value = `${value}`;
1016
+ }
1017
+
1018
+ if (
1019
+ (it.type === "STRING" && (value || it.options.multiline))
1020
+ || it.type === "MARKDOWN"
1021
+ ) {
1022
+ if (value) {
1023
+ value = value.replace(/\r?\n/g, "<br>")
1024
+ }
1025
+ list.push(`<div class="cn-preview-string">${value || it.name}</div>`);
1026
+ return;
1027
+ }
1028
+
1029
+ list.push(`<div class="cn-preview-switch">
1030
+ <div>${it.name}</div>
1031
+ <div class="cn-preview-value">${value}</div>
1032
+ </div>`);
1033
+ });
1034
+ list.push(`</div>`);
1035
+ }
1036
+
1037
+ if (nodeItem.description) {
1038
+ list.push(`<div class="cn-preview-description">${nodeItem.description}</div>`)
1039
+ }
1040
+
1041
+ return list.join("");
1042
+ }
1043
+
1044
+ showNodePreview(target) {
1045
+ const nodeName = target.innerText;
1046
+ const nodeItem = this.nodeMap[nodeName];
1047
+ if (!nodeItem) {
1048
+ this.hideNodePreview();
1049
+ return;
1050
+ }
1051
+ const html = this.createNodePreview(nodeItem);
1052
+ showPopover(target, html, "cn-preview cn-preview-"+this.colorPalette, {
1053
+ positions: ['left'],
1054
+ bgColor: this.colorVars.bgColor,
1055
+ borderColor: this.colorVars.borderColor
1056
+ })
1057
+ }
1058
+
1059
+ hideNodePreview() {
1060
+ hidePopover();
1061
+ }
1062
+
1063
+ createFlyover(container) {
1064
+ const $flyover = document.createElement("div");
1065
+ $flyover.className = "cn-flyover";
1066
+ $flyover.innerHTML = `<div class="cn-flyover-header">
1067
+ <div class="cn-flyover-close">${icons.arrowRight}</div>
1068
+ <div class="cn-flyover-title"></div>
1069
+ <div class="cn-flyover-close">${icons.close}</div>
1070
+ </div>
1071
+ <div class="cn-flyover-body"></div>`
1072
+ container.appendChild($flyover);
1073
+
1074
+ const $flyoverTitle = $flyover.querySelector(".cn-flyover-title");
1075
+ const $flyoverBody = $flyover.querySelector(".cn-flyover-body");
1076
+
1077
+ let width = '50%';
1078
+ let visible = false;
1079
+
1080
+ let timeHide;
1081
+ const closeHandler = (e) => {
1082
+ if ($flyover === e.target || $flyover.contains(e.target)) {
1083
+ return;
1084
+ }
1085
+ clearTimeout(timeHide);
1086
+ timeHide = setTimeout(() => {
1087
+ flyover.hide();
1088
+ }, 100);
1089
+ }
1090
+
1091
+ const hoverHandler = (e) => {
1092
+ if(e.type === "mouseenter") {
1093
+ if(e.target.classList.contains("cn-nodes-name")) {
1094
+ this.showNodePreview(e.target);
1095
+ }
1096
+ return;
1097
+ }
1098
+ this.hideNodePreview();
1099
+ }
1100
+
1101
+ const displayHandler = () => {
1102
+ if (visible) {
1103
+ $flyover.classList.remove("cn-slide-in-right");
1104
+ } else {
1105
+ $flyover.classList.remove("cn-slide-out-right");
1106
+ $flyover.style.width = '0px';
1107
+ $flyover.style.display = "none";
1108
+ }
1109
+ }
1110
+
1111
+ const flyover = {
1112
+ show: (titleHtml, bodyHtml) => {
1113
+ clearTimeout(timeHide);
1114
+ this.element.removeEventListener("click", closeHandler);
1115
+ $flyoverTitle.innerHTML = titleHtml;
1116
+ $flyoverBody.innerHTML = bodyHtml;
1117
+ $flyover.style.display = "block";
1118
+ $flyover.style.width = width;
1119
+ if(!visible) {
1120
+ $flyover.classList.add("cn-slide-in-right");
1121
+ }
1122
+ visible = true;
1123
+ setTimeout(() => {
1124
+ this.element.addEventListener("click", closeHandler);
1125
+ }, 100);
1126
+ },
1127
+ hide: (now) => {
1128
+ visible = false;
1129
+ this.element.removeEventListener("click", closeHandler);
1130
+ if(now) {
1131
+ displayHandler();
1132
+ return;
1133
+ }
1134
+ $flyover.classList.add("cn-slide-out-right");
1135
+ }
1136
+ }
1137
+
1138
+ $flyover.addEventListener("animationend", (e) => {
1139
+ displayHandler();
1140
+ });
1141
+
1142
+ $flyover.addEventListener("mouseenter", hoverHandler, true);
1143
+ $flyover.addEventListener("mouseleave", hoverHandler, true);
1144
+
1145
+ $flyover.addEventListener("click", (e) => {
1146
+
1147
+ if(e.target.classList.contains("cn-nodes-name")) {
1148
+ const nodeName = e.target.innerText;
1149
+ const nodeItem = this.nodeMap[nodeName];
1150
+ if (!nodeItem) {
1151
+ copyText(nodeName).then((res) => {
1152
+ if (res) {
1153
+ e.target.setAttribute("action", "Copied");
1154
+ e.target.classList.add("action");
1155
+ setTimeout(() => {
1156
+ e.target.classList.remove("action");
1157
+ e.target.removeAttribute("action");
1158
+ }, 1000);
1159
+ }
1160
+ });
1161
+ return;
1162
+ }
1163
+
1164
+ const [x, y, w, h] = app.canvas.ds.visible_area;
1165
+ const dpi = Math.max(window.devicePixelRatio ?? 1, 1);
1166
+ const node = window.LiteGraph?.createNode(
1167
+ nodeItem.name,
1168
+ nodeItem.display_name,
1169
+ {
1170
+ pos: [x + (w-300) / dpi / 2, y]
1171
+ }
1172
+ );
1173
+ if (node) {
1174
+ app.graph.add(node);
1175
+ e.target.setAttribute("action", "Added to Workflow");
1176
+ e.target.classList.add("action");
1177
+ setTimeout(() => {
1178
+ e.target.classList.remove("action");
1179
+ e.target.removeAttribute("action");
1180
+ }, 1000);
1181
+ }
1182
+
1183
+ return;
1184
+ }
1185
+ if(e.target.classList.contains("cn-nodes-pack")) {
1186
+ const hash = e.target.getAttribute("hash");
1187
+ const rowItem = this.grid.getRowItemBy("hash", hash);
1188
+ //console.log(rowItem);
1189
+ this.grid.scrollToRow(rowItem);
1190
+ this.addHighlight(rowItem);
1191
+ return;
1192
+ }
1193
+ if(e.target.classList.contains("cn-flyover-close")) {
1194
+ flyover.hide();
1195
+ return;
1196
+ }
1197
+ });
1198
+
1199
+ return flyover;
1200
+ }
1201
+
1202
+ showNodes(d) {
1203
+ const nodesList = d.rowItem.nodesList;
1204
+ if (!nodesList) {
1205
+ return;
1206
+ }
1207
+
1208
+ const rowItem = d.rowItem;
1209
+ const isNotInstalled = rowItem.action == "not-installed";
1210
+
1211
+ let titleHtml = `<div class="cn-nodes-pack" hash="${rowItem.hash}">${rowItem.title}</div>`;
1212
+ if (isNotInstalled) {
1213
+ titleHtml += '<div class="cn-pack-badge">Not Installed</div>'
1214
+ }
1215
+
1216
+ const list = [];
1217
+ list.push(`<div class="cn-nodes-list">`);
1218
+
1219
+ nodesList.forEach((it, i) => {
1220
+ let rowClass = 'cn-nodes-row'
1221
+ if (it.conflicts) {
1222
+ rowClass += ' cn-nodes-conflict';
1223
+ }
1224
+
1225
+ list.push(`<div class="${rowClass}">`);
1226
+ list.push(`<div class="cn-nodes-sn">${i+1}</div>`);
1227
+ list.push(`<div class="cn-nodes-name">${it.name}</div>`);
1228
+
1229
+ if (it.conflicts) {
1230
+ list.push(`<div class="cn-conflicts-list"><div class="cn-nodes-conflict cn-icon">${icons.conflicts}</div><b>Conflict with</b>${it.conflicts.map(c => {
1231
+ return `<div class="cn-nodes-pack" hash="${c.hash}">${c.title}</div>`;
1232
+ }).join("<b>,</b>")}</div>`);
1233
+ }
1234
+ list.push(`</div>`);
1235
+ });
1236
+
1237
+ list.push("</div>");
1238
+ const bodyHtml = list.join("");
1239
+
1240
+ this.flyover.show(titleHtml, bodyHtml);
1241
+ }
1242
+
1243
+ async loadNodes(node_packs) {
1244
+ const mode = manager_instance.datasrc_combo.value;
1245
+ this.showStatus(`Loading node mappings (${mode}) ...`);
1246
+ const res = await fetchData(`/customnode/getmappings?mode=${mode}`);
1247
+ if (res.error) {
1248
+ console.log(res.error);
1249
+ return;
1250
+ }
1251
+
1252
+ const data = res.data;
1253
+
1254
+ const findNode = (k, title) => {
1255
+ let item = node_packs[k];
1256
+ if (item) {
1257
+ return item;
1258
+ }
1259
+
1260
+ // git url
1261
+ if (k.includes("/")) {
1262
+ const gitName = k.split("/").pop();
1263
+ item = node_packs[gitName];
1264
+ if (item) {
1265
+ return item;
1266
+ }
1267
+ }
1268
+
1269
+ return node_packs[title];
1270
+ }
1271
+
1272
+ const conflictsMap = {};
1273
+
1274
+ // add nodes data
1275
+ Object.keys(data).forEach(k => {
1276
+ const [nodes, metadata] = data[k];
1277
+ if (nodes?.length) {
1278
+ const title = metadata?.title_aux;
1279
+ const nodeItem = findNode(k, title);
1280
+ if (nodeItem) {
1281
+
1282
+ // deduped
1283
+ const eList = Array.from(new Set(nodes));
1284
+
1285
+ nodeItem.nodes = eList.length;
1286
+ const nodesMap = {};
1287
+ eList.forEach(extName => {
1288
+ nodesMap[extName] = {
1289
+ name: extName
1290
+ };
1291
+ let cList = conflictsMap[extName];
1292
+ if(!cList) {
1293
+ cList = [];
1294
+ conflictsMap[extName] = cList;
1295
+ }
1296
+ cList.push(nodeItem.key);
1297
+ });
1298
+ nodeItem.nodesMap = nodesMap;
1299
+ } else {
1300
+ // should be removed
1301
+ // console.log("not found", k, title, nodes)
1302
+ }
1303
+ }
1304
+ });
1305
+
1306
+ // calculate conflicts data
1307
+ Object.keys(conflictsMap).forEach(extName => {
1308
+ const cList = conflictsMap[extName];
1309
+ if(cList.length <= 1) {
1310
+ return;
1311
+ }
1312
+ cList.forEach(key => {
1313
+ const nodeItem = node_packs[key];
1314
+ const extItem = nodeItem.nodesMap[extName];
1315
+ if(!extItem.conflicts) {
1316
+ extItem.conflicts = []
1317
+ }
1318
+ const conflictsList = cList.filter(k => k !== key);
1319
+ conflictsList.forEach(k => {
1320
+ const nItem = node_packs[k];
1321
+ extItem.conflicts.push({
1322
+ key: k,
1323
+ title: nItem.title,
1324
+ hash: nItem.hash
1325
+ })
1326
+
1327
+ })
1328
+ })
1329
+ })
1330
+
1331
+ Object.values(node_packs).forEach(nodeItem => {
1332
+ if (nodeItem.nodesMap) {
1333
+ nodeItem.nodesList = Object.values(nodeItem.nodesMap);
1334
+ nodeItem.conflicts = nodeItem.nodesList.filter(it => it.conflicts).length;
1335
+ }
1336
+ })
1337
+
1338
+ }
1339
+
1340
+ // ===========================================================================================
1341
+
1342
+ renderSelected() {
1343
+ const selectedList = this.grid.getSelectedRows();
1344
+ if (!selectedList.length) {
1345
+ this.showSelection("");
1346
+ return;
1347
+ }
1348
+
1349
+ const selectedMap = {};
1350
+ selectedList.forEach(item => {
1351
+ let type = item.action;
1352
+ if (item.restart) {
1353
+ type = "Restart Required";
1354
+ }
1355
+ if (selectedMap[type]) {
1356
+ selectedMap[type].push(item.hash);
1357
+ } else {
1358
+ selectedMap[type] = [item.hash];
1359
+ }
1360
+ });
1361
+
1362
+ this.selectedMap = selectedMap;
1363
+
1364
+ const list = [];
1365
+ Object.keys(selectedMap).forEach(v => {
1366
+ const filterItem = this.getFilterItem(v);
1367
+ list.push(`<div class="cn-selected-buttons">
1368
+ <span>Selected <b>${selectedMap[v].length}</b> ${filterItem ? filterItem.label : v}</span>
1369
+ ${this.grid.hasMask ? "" : this.getActionButtons(v, null, true)}
1370
+ </div>`);
1371
+ });
1372
+
1373
+ this.showSelection(list.join(""));
1374
+ }
1375
+
1376
+ focusInstall(item, mode) {
1377
+ const cellNode = this.grid.getCellNode(item, "action");
1378
+ if (cellNode) {
1379
+ const cellBtn = cellNode.querySelector(`button[mode="${mode}"]`);
1380
+ if (cellBtn) {
1381
+ cellBtn.classList.add("cn-btn-loading");
1382
+ return true
1383
+ }
1384
+ }
1385
+ }
1386
+
1387
+ async installNodeWithVersion(rowItem, btn, is_enable) {
1388
+ let hash = rowItem.hash;
1389
+ let title = rowItem.title;
1390
+
1391
+ const item = this.grid.getRowItemBy("hash", hash);
1392
+
1393
+ let node_id = item.originalData.id;
1394
+
1395
+ this.showLoading();
1396
+ let res;
1397
+ if(is_enable) {
1398
+ res = await api.fetchApi(`/customnode/disabled_versions/${node_id}`, { cache: "no-store" });
1399
+ }
1400
+ else {
1401
+ res = await api.fetchApi(`/customnode/versions/${node_id}`, { cache: "no-store" });
1402
+ }
1403
+ this.hideLoading();
1404
+
1405
+ if(res.status == 200) {
1406
+ let obj = await res.json();
1407
+
1408
+ let versions = [];
1409
+ let default_version;
1410
+ let version_cnt = 0;
1411
+
1412
+ if(!is_enable) {
1413
+ if(rowItem.originalData.active_version != 'nightly') {
1414
+ versions.push('nightly');
1415
+ default_version = 'nightly';
1416
+ version_cnt++;
1417
+ }
1418
+
1419
+ if(rowItem.cnr_latest != rowItem.originalData.active_version && obj.length > 0) {
1420
+ versions.push('latest');
1421
+ }
1422
+ }
1423
+
1424
+ for(let v of obj) {
1425
+ if(rowItem.originalData.active_version != v.version) {
1426
+ default_version = v.version;
1427
+ versions.push(v.version);
1428
+ version_cnt++;
1429
+ }
1430
+ }
1431
+
1432
+ this.showVersionSelectorDialog(versions, (selected_version) => {
1433
+ this.installNodes([hash], btn, title, selected_version);
1434
+ });
1435
+ }
1436
+ else {
1437
+ show_message('Failed to fetch versions from ComfyRegistry.');
1438
+ }
1439
+ }
1440
+
1441
+ async installNodes(list, btn, title, selected_version) {
1442
+ let stats = await api.fetchApi('/manager/queue/status');
1443
+ stats = await stats.json();
1444
+ if(stats.is_processing) {
1445
+ customAlert(`[ComfyUI-Manager] There are already tasks in progress. Please try again after it is completed. (${stats.done_count}/${stats.total_count})`);
1446
+ return;
1447
+ }
1448
+
1449
+ const { target, label, mode} = btn;
1450
+
1451
+ if(mode === "uninstall") {
1452
+ title = title || `${list.length} custom nodes`;
1453
+
1454
+ const confirmed = await customConfirm(`Are you sure uninstall ${title}?`);
1455
+ if (!confirmed) {
1456
+ return;
1457
+ }
1458
+ }
1459
+
1460
+ if(mode === "reinstall") {
1461
+ title = title || `${list.length} custom nodes`;
1462
+
1463
+ const confirmed = await customConfirm(`Are you sure reinstall ${title}?`);
1464
+ if (!confirmed) {
1465
+ return;
1466
+ }
1467
+ }
1468
+
1469
+ target.classList.add("cn-btn-loading");
1470
+ this.showError("");
1471
+
1472
+ let needRestart = false;
1473
+ let errorMsg = "";
1474
+
1475
+ await api.fetchApi('/manager/queue/reset');
1476
+
1477
+ let target_items = [];
1478
+
1479
+ for (const hash of list) {
1480
+ const item = this.grid.getRowItemBy("hash", hash);
1481
+ target_items.push(item);
1482
+
1483
+ if (!item) {
1484
+ errorMsg = `Not found custom node: ${hash}`;
1485
+ break;
1486
+ }
1487
+
1488
+ this.grid.scrollRowIntoView(item);
1489
+
1490
+ if (!this.focusInstall(item, mode)) {
1491
+ this.grid.onNextUpdated(() => {
1492
+ this.focusInstall(item, mode);
1493
+ });
1494
+ }
1495
+
1496
+ this.showStatus(`${label} ${item.title} ...`);
1497
+
1498
+ const data = item.originalData;
1499
+ data.selected_version = selected_version;
1500
+ data.channel = this.channel;
1501
+ data.mode = this.mode;
1502
+ data.ui_id = hash;
1503
+
1504
+ let install_mode = mode;
1505
+ if(mode == 'switch') {
1506
+ install_mode = 'install';
1507
+ }
1508
+
1509
+ // don't post install if install_mode == 'enable'
1510
+ data.skip_post_install = install_mode == 'enable';
1511
+ let api_mode = install_mode;
1512
+ if(install_mode == 'enable') {
1513
+ api_mode = 'install';
1514
+ }
1515
+
1516
+ if(install_mode == 'reinstall') {
1517
+ api_mode = 'reinstall';
1518
+ }
1519
+
1520
+ const res = await api.fetchApi(`/manager/queue/${api_mode}`, {
1521
+ method: 'POST',
1522
+ body: JSON.stringify(data)
1523
+ });
1524
+
1525
+ if (res.status != 200) {
1526
+ errorMsg = `'${item.title}': `;
1527
+
1528
+ if(res.status == 403) {
1529
+ errorMsg += `This action is not allowed with this security level configuration.\n`;
1530
+ } else if(res.status == 404) {
1531
+ errorMsg += `With the current security level configuration, only custom nodes from the <B>"default channel"</B> can be installed.\n`;
1532
+ } else {
1533
+ errorMsg += await res.text() + '\n';
1534
+ }
1535
+
1536
+ break;
1537
+ }
1538
+ }
1539
+
1540
+ this.install_context = {btn: btn, targets: target_items};
1541
+
1542
+ if(errorMsg) {
1543
+ this.showError(errorMsg);
1544
+ show_message("[Installation Errors]\n"+errorMsg);
1545
+
1546
+ // reset
1547
+ for(let k in target_items) {
1548
+ const item = target_items[k];
1549
+ this.grid.updateCell(item, "action");
1550
+ }
1551
+ }
1552
+ else {
1553
+ await api.fetchApi('/manager/queue/start');
1554
+ this.showStop();
1555
+ showTerminal();
1556
+ }
1557
+ }
1558
+
1559
+ async onQueueStatus(event) {
1560
+ let self = CustomNodesManager.instance;
1561
+ if(event.detail.status == 'in_progress' && event.detail.ui_target == 'nodepack_manager') {
1562
+ const hash = event.detail.target;
1563
+
1564
+ const item = self.grid.getRowItemBy("hash", hash);
1565
+
1566
+ item.restart = true;
1567
+ self.restartMap[item.hash] = true;
1568
+ self.grid.updateCell(item, "action");
1569
+ self.grid.setRowSelected(item, false);
1570
+ }
1571
+ else if(event.detail.status == 'done') {
1572
+ self.hideStop();
1573
+ self.onQueueCompleted(event.detail);
1574
+ }
1575
+ }
1576
+
1577
+ async onQueueCompleted(info) {
1578
+ let result = info.nodepack_result;
1579
+
1580
+ if(result.length == 0) {
1581
+ return;
1582
+ }
1583
+
1584
+ let self = CustomNodesManager.instance;
1585
+
1586
+ if(!self.install_context) {
1587
+ return;
1588
+ }
1589
+
1590
+ const { target, label, mode } = self.install_context.btn;
1591
+ target.classList.remove("cn-btn-loading");
1592
+
1593
+ let errorMsg = "";
1594
+
1595
+ for(let hash in result){
1596
+ let v = result[hash];
1597
+
1598
+ if(v != 'success' && v != 'skip')
1599
+ errorMsg += v+'\n';
1600
+ }
1601
+
1602
+ for(let k in self.install_context.targets) {
1603
+ let item = self.install_context.targets[k];
1604
+ self.grid.updateCell(item, "action");
1605
+ }
1606
+
1607
+ if (errorMsg) {
1608
+ self.showError(errorMsg);
1609
+ show_message("Installation Error:\n"+errorMsg);
1610
+ } else {
1611
+ self.showStatus(`${label} ${result.length} custom node(s) successfully`);
1612
+ }
1613
+
1614
+ self.showRestart();
1615
+ self.showMessage(`To apply the installed/updated/disabled/enabled custom node, please restart ComfyUI. And refresh browser.`, "red");
1616
+
1617
+ infoToast(`[ComfyUI-Manager] All node pack tasks in the queue have been completed.\n${info.done_count}/${info.total_count}`);
1618
+ self.install_context = undefined;
1619
+ }
1620
+
1621
+ // ===========================================================================================
1622
+
1623
+ getNodesInWorkflow() {
1624
+ let usedGroupNodes = new Set();
1625
+ let allUsedNodes = {};
1626
+
1627
+ for(let k in app.graph._nodes) {
1628
+ let node = app.graph._nodes[k];
1629
+
1630
+ if(node.type.startsWith('workflow>')) {
1631
+ usedGroupNodes.add(node.type.slice(9));
1632
+ continue;
1633
+ }
1634
+
1635
+ allUsedNodes[node.type] = node;
1636
+ }
1637
+
1638
+ for(let k of usedGroupNodes) {
1639
+ let subnodes = app.graph.extra.groupNodes[k]?.nodes;
1640
+
1641
+ if(subnodes) {
1642
+ for(let k2 in subnodes) {
1643
+ let node = subnodes[k2];
1644
+ allUsedNodes[node.type] = node;
1645
+ }
1646
+ }
1647
+ }
1648
+
1649
+ return allUsedNodes;
1650
+ }
1651
+
1652
+ async getMissingNodes() {
1653
+ let unresolved_missing_nodes = new Set();
1654
+ let hashMap = {};
1655
+ let allUsedNodes = this.getNodesInWorkflow();
1656
+
1657
+ const registered_nodes = new Set();
1658
+ for (let i in LiteGraph.registered_node_types) {
1659
+ registered_nodes.add(LiteGraph.registered_node_types[i].type);
1660
+ }
1661
+
1662
+ let unresolved_aux_ids = {};
1663
+ let outdated_comfyui = false;
1664
+ let unresolved_cnr_list = [];
1665
+
1666
+ for(let k in allUsedNodes) {
1667
+ let node = allUsedNodes[k];
1668
+
1669
+ if(!registered_nodes.has(node.type)) {
1670
+ // missing node
1671
+ if(node.properties.cnr_id) {
1672
+ if(node.properties.cnr_id == 'comfy-core') {
1673
+ outdated_comfyui = true;
1674
+ }
1675
+
1676
+ let item = this.custom_nodes[node.properties.cnr_id];
1677
+ if(item) {
1678
+ hashMap[item.hash] = true;
1679
+ }
1680
+ else {
1681
+ console.log(`CM: cannot find '${node.properties.cnr_id}' from cnr list.`);
1682
+ unresolved_aux_ids[node.properties.cnr_id] = node.type;
1683
+ unresolved_cnr_list.push(node.properties.cnr_id);
1684
+ }
1685
+ }
1686
+ else if(node.properties.aux_id) {
1687
+ unresolved_aux_ids[node.properties.aux_id] = node.type;
1688
+ }
1689
+ else {
1690
+ unresolved_missing_nodes.add(node.type);
1691
+ }
1692
+ }
1693
+ }
1694
+
1695
+
1696
+ if(unresolved_cnr_list.length > 0) {
1697
+ let error_msg = "Failed to find the following ComfyRegistry list.\nThe cache may be outdated, or the nodes may have been removed from ComfyRegistry.<HR>";
1698
+ for(let i in unresolved_cnr_list) {
1699
+ error_msg += '<li>'+unresolved_cnr_list[i]+'</li>';
1700
+ }
1701
+
1702
+ show_message(error_msg);
1703
+ }
1704
+
1705
+ if(outdated_comfyui) {
1706
+ customAlert('ComfyUI is outdated, so some built-in nodes cannot be used.');
1707
+ }
1708
+
1709
+ if(Object.keys(unresolved_aux_ids).length > 0) {
1710
+ // building aux_id to nodepack map
1711
+ let aux_id_to_pack = {};
1712
+ for(let k in this.custom_nodes) {
1713
+ let nodepack = this.custom_nodes[k];
1714
+ let aux_id;
1715
+ if(nodepack.repository?.startsWith('https://github.com')) {
1716
+ aux_id = nodepack.repository.split('/').slice(-2).join('/');
1717
+ aux_id_to_pack[aux_id] = nodepack;
1718
+ }
1719
+ else if(nodepack.repository) {
1720
+ aux_id = nodepack.repository.split('/').slice(-1);
1721
+ aux_id_to_pack[aux_id] = nodepack;
1722
+ }
1723
+ }
1724
+
1725
+ // resolving aux_id
1726
+ for(let k in unresolved_aux_ids) {
1727
+ let nodepack = aux_id_to_pack[k];
1728
+ if(nodepack) {
1729
+ hashMap[nodepack.hash] = true;
1730
+ }
1731
+ else {
1732
+ unresolved_missing_nodes.add(unresolved_aux_ids[k]);
1733
+ }
1734
+ }
1735
+ }
1736
+
1737
+ if(unresolved_missing_nodes.size > 0) {
1738
+ await this.getMissingNodesLegacy(hashMap, unresolved_missing_nodes);
1739
+ }
1740
+
1741
+ return hashMap;
1742
+ }
1743
+
1744
+ async getMissingNodesLegacy(hashMap, missing_nodes) {
1745
+ const mode = manager_instance.datasrc_combo.value;
1746
+ this.showStatus(`Loading missing nodes (${mode}) ...`);
1747
+ const res = await fetchData(`/customnode/getmappings?mode=${mode}`);
1748
+ if (res.error) {
1749
+ this.showError(`Failed to get custom node mappings: ${res.error}`);
1750
+ return;
1751
+ }
1752
+
1753
+ const mappings = res.data;
1754
+
1755
+ // build regex->url map
1756
+ const regex_to_pack = [];
1757
+ for(let k in this.custom_nodes) {
1758
+ let node = this.custom_nodes[k];
1759
+
1760
+ if(node.nodename_pattern) {
1761
+ regex_to_pack.push({
1762
+ regex: new RegExp(node.nodename_pattern),
1763
+ url: node.files[0]
1764
+ });
1765
+ }
1766
+ }
1767
+
1768
+ // build name->url map
1769
+ const name_to_packs = {};
1770
+ for (const url in mappings) {
1771
+ const names = mappings[url];
1772
+
1773
+ for(const name in names[0]) {
1774
+ let v = name_to_packs[names[0][name]];
1775
+ if(v == undefined) {
1776
+ v = [];
1777
+ name_to_packs[names[0][name]] = v;
1778
+ }
1779
+ v.push(url);
1780
+ }
1781
+ }
1782
+
1783
+ let unresolved_missing_nodes = new Set();
1784
+ for (let node_type of missing_nodes) {
1785
+ const packs = name_to_packs[node_type.trim()];
1786
+ if(packs)
1787
+ packs.forEach(url => {
1788
+ unresolved_missing_nodes.add(url);
1789
+ });
1790
+ else {
1791
+ for(let j in regex_to_pack) {
1792
+ if(regex_to_pack[j].regex.test(node_type)) {
1793
+ unresolved_missing_nodes.add(regex_to_pack[j].url);
1794
+ }
1795
+ }
1796
+ }
1797
+ }
1798
+
1799
+ for(let k in this.custom_nodes) {
1800
+ let item = this.custom_nodes[k];
1801
+
1802
+ if(unresolved_missing_nodes.has(item.id)) {
1803
+ hashMap[item.hash] = true;
1804
+ }
1805
+ else if (item.files?.some(file => unresolved_missing_nodes.has(file))) {
1806
+ hashMap[item.hash] = true;
1807
+ }
1808
+ }
1809
+
1810
+ return hashMap;
1811
+ }
1812
+
1813
+ async getFavorites() {
1814
+ const hashMap = {};
1815
+ for(let k in this.custom_nodes) {
1816
+ let item = this.custom_nodes[k];
1817
+ if(item.is_favorite)
1818
+ hashMap[item.hash] = true;
1819
+ }
1820
+
1821
+ return hashMap;
1822
+ }
1823
+
1824
+ async getNodepackInWorkflow() {
1825
+ let allUsedNodes = this.getNodesInWorkflow();
1826
+
1827
+ // building aux_id to nodepack map
1828
+ let aux_id_to_pack = {};
1829
+ for(let k in this.custom_nodes) {
1830
+ let nodepack = this.custom_nodes[k];
1831
+ let aux_id;
1832
+ if(nodepack.repository?.startsWith('https://github.com')) {
1833
+ aux_id = nodepack.repository.split('/').slice(-2).join('/');
1834
+ aux_id_to_pack[aux_id] = nodepack;
1835
+ }
1836
+ else if(nodepack.repository) {
1837
+ aux_id = nodepack.repository.split('/').slice(-1);
1838
+ aux_id_to_pack[aux_id] = nodepack;
1839
+ }
1840
+ }
1841
+
1842
+ const hashMap = {};
1843
+ for(let k in allUsedNodes) {
1844
+ var item;
1845
+ if(allUsedNodes[k].properties.cnr_id) {
1846
+ item = this.custom_nodes[allUsedNodes[k].properties.cnr_id];
1847
+ }
1848
+ else if(allUsedNodes[k].properties.aux_id) {
1849
+ item = aux_id_to_pack[allUsedNodes[k].properties.aux_id];
1850
+ }
1851
+
1852
+ if(item)
1853
+ hashMap[item.hash] = true;
1854
+ }
1855
+
1856
+ return hashMap;
1857
+ }
1858
+
1859
+ async getAlternatives() {
1860
+ const mode = manager_instance.datasrc_combo.value;
1861
+ this.showStatus(`Loading alternatives (${mode}) ...`);
1862
+ const res = await fetchData(`/customnode/alternatives?mode=${mode}`);
1863
+ if (res.error) {
1864
+ this.showError(`Failed to get alternatives: ${res.error}`);
1865
+ return [];
1866
+ }
1867
+
1868
+ const hashMap = {};
1869
+ const items = res.data;
1870
+
1871
+ for(let i in items) {
1872
+ let item = items[i];
1873
+ let custom_node = this.custom_nodes[i];
1874
+
1875
+ if (!custom_node) {
1876
+ console.log(`Not found custom node: ${item.id}`);
1877
+ continue;
1878
+ }
1879
+
1880
+ const tags = `${item.tags}`.split(",").map(tag => {
1881
+ return `<div>${tag.trim()}</div>`;
1882
+ }).join("");
1883
+
1884
+ hashMap[custom_node.hash] = {
1885
+ alternatives: `<div class="cn-tag-list">${tags}</div> ${item.description}`
1886
+ }
1887
+
1888
+ }
1889
+
1890
+ return hashMap;
1891
+ }
1892
+
1893
+ async loadData(show_mode = ShowMode.NORMAL) {
1894
+ const isElectron = 'electronAPI' in window;
1895
+
1896
+ this.show_mode = show_mode;
1897
+ console.log("Show mode:", show_mode);
1898
+
1899
+ this.showLoading();
1900
+
1901
+ const mode = manager_instance.datasrc_combo.value;
1902
+ this.showStatus(`Loading custom nodes (${mode}) ...`);
1903
+
1904
+ const skip_update = this.show_mode === ShowMode.UPDATE ? "" : "&skip_update=true";
1905
+
1906
+ if(this.show_mode === ShowMode.UPDATE) {
1907
+ infoToast('Fetching updated information. This may take some time if many custom nodes are installed.');
1908
+ }
1909
+
1910
+ const res = await fetchData(`/customnode/getlist?mode=${mode}${skip_update}`);
1911
+ if (res.error) {
1912
+ this.showError("Failed to get custom node list.");
1913
+ this.hideLoading();
1914
+ return;
1915
+ }
1916
+
1917
+ const { channel, node_packs } = res.data;
1918
+
1919
+ if(isElectron) {
1920
+ delete node_packs['comfyui-manager'];
1921
+ }
1922
+
1923
+ this.channel = channel;
1924
+ this.mode = mode;
1925
+ this.custom_nodes = node_packs;
1926
+
1927
+ if(this.channel !== 'default') {
1928
+ this.element.querySelector(".cn-manager-channel").innerHTML = `Channel: ${this.channel} (Incomplete list)`;
1929
+ }
1930
+
1931
+ for (const k in node_packs) {
1932
+ let item = node_packs[k];
1933
+ item.originalData = JSON.parse(JSON.stringify(item));
1934
+ if(item.originalData.id == undefined) {
1935
+ item.originalData.id = k;
1936
+ }
1937
+ item.key = k;
1938
+ item.hash = md5(k);
1939
+ }
1940
+
1941
+ await this.loadNodes(node_packs);
1942
+
1943
+ const filterItem = this.getFilterItem(this.show_mode);
1944
+ if(filterItem) {
1945
+ let hashMap;
1946
+ if(this.show_mode == ShowMode.UPDATE) {
1947
+ hashMap = {};
1948
+ for (const k in node_packs) {
1949
+ let it = node_packs[k];
1950
+ if (it['update-state'] === "true") {
1951
+ hashMap[it.hash] = true;
1952
+ }
1953
+ }
1954
+ } else if(this.show_mode == ShowMode.MISSING) {
1955
+ hashMap = await this.getMissingNodes();
1956
+ } else if(this.show_mode == ShowMode.ALTERNATIVES) {
1957
+ hashMap = await this.getAlternatives();
1958
+ } else if(this.show_mode == ShowMode.FAVORITES) {
1959
+ hashMap = await this.getFavorites();
1960
+ } else if(this.show_mode == ShowMode.IN_WORKFLOW) {
1961
+ hashMap = await this.getNodepackInWorkflow();
1962
+ }
1963
+ filterItem.hashMap = hashMap;
1964
+
1965
+ if(this.show_mode != ShowMode.IN_WORKFLOW) {
1966
+ filterItem.hasData = true;
1967
+ }
1968
+ }
1969
+
1970
+ for(let k in node_packs) {
1971
+ let nodeItem = node_packs[k];
1972
+
1973
+ if (this.restartMap[nodeItem.hash]) {
1974
+ nodeItem.restart = true;
1975
+ }
1976
+
1977
+ if(nodeItem['update-state'] == "true") {
1978
+ nodeItem.action = 'updatable';
1979
+ }
1980
+ else if(nodeItem['import-fail']) {
1981
+ nodeItem.action = 'import-fail';
1982
+ }
1983
+ else {
1984
+ nodeItem.action = nodeItem.state;
1985
+ }
1986
+
1987
+ if(nodeItem['invalid-installation']) {
1988
+ nodeItem.action = 'invalid-installation';
1989
+ }
1990
+
1991
+ const filterTypes = new Set();
1992
+ this.filterList.forEach(filterItem => {
1993
+ const { value, hashMap } = filterItem;
1994
+ if (hashMap) {
1995
+ const hashData = hashMap[nodeItem.hash]
1996
+ if (hashData) {
1997
+ filterTypes.add(value);
1998
+ if (value === ShowMode.UPDATE) {
1999
+ nodeItem['update-state'] = "true";
2000
+ }
2001
+ if (value === ShowMode.MISSING) {
2002
+ nodeItem['missing-node'] = "true";
2003
+ }
2004
+ if (typeof hashData === "object") {
2005
+ Object.assign(nodeItem, hashData);
2006
+ }
2007
+ }
2008
+ } else {
2009
+ if (nodeItem.state === value) {
2010
+ filterTypes.add(value);
2011
+ }
2012
+
2013
+ switch(nodeItem.state) {
2014
+ case "enabled":
2015
+ filterTypes.add("enabled");
2016
+ case "disabled":
2017
+ filterTypes.add("installed");
2018
+ break;
2019
+ case "not-installed":
2020
+ filterTypes.add("not-installed");
2021
+ break;
2022
+ }
2023
+
2024
+ if(nodeItem.version != 'unknown') {
2025
+ filterTypes.add("cnr");
2026
+ }
2027
+ else {
2028
+ filterTypes.add("unknown");
2029
+ }
2030
+
2031
+ if(nodeItem['update-state'] == 'true') {
2032
+ filterTypes.add("updatable");
2033
+ }
2034
+
2035
+ if(nodeItem['import-fail']) {
2036
+ filterTypes.add("import-fail");
2037
+ }
2038
+
2039
+ if(nodeItem['invalid-installation']) {
2040
+ filterTypes.add("invalid-installation");
2041
+ }
2042
+ }
2043
+ });
2044
+
2045
+ nodeItem.filterTypes = Array.from(filterTypes);
2046
+ }
2047
+
2048
+ this.renderGrid();
2049
+
2050
+ this.hideLoading();
2051
+
2052
+ }
2053
+
2054
+ // ===========================================================================================
2055
+
2056
+ showSelection(msg) {
2057
+ this.element.querySelector(".cn-manager-selection").innerHTML = msg;
2058
+ }
2059
+
2060
+ showError(err) {
2061
+ this.showMessage(err, "red");
2062
+ }
2063
+
2064
+ showMessage(msg, color) {
2065
+ if (color) {
2066
+ msg = `<font color="${color}">${msg}</font>`;
2067
+ }
2068
+ this.element.querySelector(".cn-manager-message").innerHTML = msg;
2069
+ }
2070
+
2071
+ showStatus(msg, color) {
2072
+ if (color) {
2073
+ msg = `<font color="${color}">${msg}</font>`;
2074
+ }
2075
+ this.element.querySelector(".cn-manager-status").innerHTML = msg;
2076
+ }
2077
+
2078
+ showLoading() {
2079
+ this.setDisabled(true);
2080
+ if (this.grid) {
2081
+ this.grid.showLoading();
2082
+ this.grid.showMask({
2083
+ opacity: 0.05
2084
+ });
2085
+ }
2086
+ }
2087
+
2088
+ hideLoading() {
2089
+ this.setDisabled(false);
2090
+ if (this.grid) {
2091
+ this.grid.hideLoading();
2092
+ this.grid.hideMask();
2093
+ }
2094
+ }
2095
+
2096
+ setDisabled(disabled) {
2097
+ const $close = this.element.querySelector(".cn-manager-close");
2098
+ const $restart = this.element.querySelector(".cn-manager-restart");
2099
+ const $stop = this.element.querySelector(".cn-manager-stop");
2100
+
2101
+ const list = [
2102
+ ".cn-manager-header input",
2103
+ ".cn-manager-header select",
2104
+ ".cn-manager-footer button",
2105
+ ".cn-manager-selection button"
2106
+ ].map(s => {
2107
+ return Array.from(this.element.querySelectorAll(s));
2108
+ })
2109
+ .flat()
2110
+ .filter(it => {
2111
+ return it !== $close && it !== $restart && it !== $stop;
2112
+ });
2113
+
2114
+ list.forEach($elem => {
2115
+ if (disabled) {
2116
+ $elem.setAttribute("disabled", "disabled");
2117
+ } else {
2118
+ $elem.removeAttribute("disabled");
2119
+ }
2120
+ });
2121
+
2122
+ Array.from(this.element.querySelectorAll(".cn-btn-loading")).forEach($elem => {
2123
+ $elem.classList.remove("cn-btn-loading");
2124
+ });
2125
+
2126
+ }
2127
+
2128
+ showRestart() {
2129
+ this.element.querySelector(".cn-manager-restart").style.display = "block";
2130
+ setNeedRestart(true);
2131
+ }
2132
+
2133
+ showStop() {
2134
+ this.element.querySelector(".cn-manager-stop").style.display = "block";
2135
+ }
2136
+
2137
+ hideStop() {
2138
+ this.element.querySelector(".cn-manager-stop").style.display = "none";
2139
+ }
2140
+
2141
+ setFilter(filterValue) {
2142
+ let filter = "";
2143
+ const filterItem = this.getFilterItem(filterValue);
2144
+ if(filterItem) {
2145
+ filter = filterItem.value;
2146
+ }
2147
+ this.filter = filter;
2148
+ this.element.querySelector(".cn-manager-filter").value = filter;
2149
+ }
2150
+
2151
+ setKeywords(keywords = "") {
2152
+ this.keywords = keywords;
2153
+ this.element.querySelector(".cn-manager-keywords").value = keywords;
2154
+ }
2155
+
2156
+ show(show_mode) {
2157
+ this.element.style.display = "flex";
2158
+ this.element.focus();
2159
+ this.setFilter(show_mode);
2160
+ this.setKeywords("");
2161
+ this.showSelection("");
2162
+ this.showMessage("");
2163
+ this.loadData(show_mode);
2164
+ }
2165
+
2166
+ close() {
2167
+ this.element.style.display = "none";
2168
+ }
2169
+
2170
+ get isVisible() {
2171
+ return this.element?.style?.display !== "none";
2172
+ }
2173
+ }