hungho77 commited on
Commit
6ccdab4
·
verified ·
1 Parent(s): 80c57a6

Upload 88 files

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-Manager/.cache/.cache_directory +0 -0
  2. ComfyUI/custom_nodes/ComfyUI-Manager/.github/workflows/publish.yml +21 -0
  3. ComfyUI/custom_nodes/ComfyUI-Manager/.gitignore +17 -0
  4. ComfyUI/custom_nodes/ComfyUI-Manager/LICENSE.txt +674 -0
  5. ComfyUI/custom_nodes/ComfyUI-Manager/README.md +421 -0
  6. ComfyUI/custom_nodes/ComfyUI-Manager/__init__.py +18 -0
  7. ComfyUI/custom_nodes/ComfyUI-Manager/alter-list.json +224 -0
  8. ComfyUI/custom_nodes/ComfyUI-Manager/channels.list.template +6 -0
  9. ComfyUI/custom_nodes/ComfyUI-Manager/check.bat +21 -0
  10. ComfyUI/custom_nodes/ComfyUI-Manager/check.sh +42 -0
  11. ComfyUI/custom_nodes/ComfyUI-Manager/cm-cli.py +1031 -0
  12. ComfyUI/custom_nodes/ComfyUI-Manager/components/.gitignore +2 -0
  13. ComfyUI/custom_nodes/ComfyUI-Manager/custom-node-list.json +0 -0
  14. ComfyUI/custom_nodes/ComfyUI-Manager/docs/en/cm-cli.md +146 -0
  15. ComfyUI/custom_nodes/ComfyUI-Manager/docs/en/use_aria2.md +40 -0
  16. ComfyUI/custom_nodes/ComfyUI-Manager/docs/ko/cm-cli.md +149 -0
  17. ComfyUI/custom_nodes/ComfyUI-Manager/extension-node-map.json +0 -0
  18. ComfyUI/custom_nodes/ComfyUI-Manager/git_helper.py +450 -0
  19. ComfyUI/custom_nodes/ComfyUI-Manager/github-stats.json +0 -0
  20. ComfyUI/custom_nodes/ComfyUI-Manager/glob/cm_global.py +112 -0
  21. ComfyUI/custom_nodes/ComfyUI-Manager/glob/manager_core.py +1313 -0
  22. ComfyUI/custom_nodes/ComfyUI-Manager/glob/manager_downloader.py +70 -0
  23. ComfyUI/custom_nodes/ComfyUI-Manager/glob/manager_server.py +1392 -0
  24. ComfyUI/custom_nodes/ComfyUI-Manager/glob/manager_util.py +214 -0
  25. ComfyUI/custom_nodes/ComfyUI-Manager/glob/security_check.py +117 -0
  26. ComfyUI/custom_nodes/ComfyUI-Manager/glob/share_3rdparty.py +386 -0
  27. ComfyUI/custom_nodes/ComfyUI-Manager/js/cm-api.js +63 -0
  28. ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-manager.js +1550 -0
  29. ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-share-common.js +1064 -0
  30. ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-share-copus.js +892 -0
  31. ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-share-openart.js +745 -0
  32. ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-share-youml.js +568 -0
  33. ComfyUI/custom_nodes/ComfyUI-Manager/js/common.js +244 -0
  34. ComfyUI/custom_nodes/ComfyUI-Manager/js/components-manager.js +811 -0
  35. ComfyUI/custom_nodes/ComfyUI-Manager/js/custom-nodes-manager.js +1381 -0
  36. ComfyUI/custom_nodes/ComfyUI-Manager/js/model-manager.js +891 -0
  37. ComfyUI/custom_nodes/ComfyUI-Manager/js/node_fixer.js +226 -0
  38. ComfyUI/custom_nodes/ComfyUI-Manager/js/snapshot.js +300 -0
  39. ComfyUI/custom_nodes/ComfyUI-Manager/js/turbogrid.esm.js +0 -0
  40. ComfyUI/custom_nodes/ComfyUI-Manager/json-checker.py +25 -0
  41. ComfyUI/custom_nodes/ComfyUI-Manager/misc/Impact.pack +444 -0
  42. ComfyUI/custom_nodes/ComfyUI-Manager/misc/custom-nodes.jpg +0 -0
  43. ComfyUI/custom_nodes/ComfyUI-Manager/misc/main.jpg +0 -0
  44. ComfyUI/custom_nodes/ComfyUI-Manager/misc/menu.jpg +0 -0
  45. ComfyUI/custom_nodes/ComfyUI-Manager/misc/missing-list.jpg +0 -0
  46. ComfyUI/custom_nodes/ComfyUI-Manager/misc/missing-menu.jpg +0 -0
  47. ComfyUI/custom_nodes/ComfyUI-Manager/misc/models.png +0 -0
  48. ComfyUI/custom_nodes/ComfyUI-Manager/misc/nickname.jpg +0 -0
  49. ComfyUI/custom_nodes/ComfyUI-Manager/misc/portable-install.png +0 -0
  50. ComfyUI/custom_nodes/ComfyUI-Manager/misc/share-setting.jpg +0 -0
ComfyUI/custom_nodes/ComfyUI-Manager/.cache/.cache_directory ADDED
File without changes
ComfyUI/custom_nodes/ComfyUI-Manager/.github/workflows/publish.yml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ jobs:
11
+ publish-node:
12
+ name: Publish Custom Node to registry
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - name: Check out code
16
+ uses: actions/checkout@v4
17
+ - name: Publish Custom Node
18
+ uses: Comfy-Org/publish-node-action@main
19
+ with:
20
+ ## Add your own personal access token to your Github Repository secrets and reference it here.
21
+ personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
ComfyUI/custom_nodes/ComfyUI-Manager/.gitignore ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ .idea/
3
+ .vscode/
4
+ .tmp
5
+ .cache
6
+ config.ini
7
+ snapshots/**
8
+ startup-scripts/**
9
+ .openart_key
10
+ .youml
11
+ matrix_auth
12
+ channels.list
13
+ comfyworkflows_sharekey
14
+ github-stats-cache.json
15
+ pip_overrides.json
16
+ *.json
17
+ check2.sh
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,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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](misc/menu.jpg)
6
+
7
+ ## NOTICE
8
+ * V2.48.1: Security policy has been changed. Downloads of models in the list are allowed under the 'normal' security level.
9
+ * V2.47: Security policy has been changed. The former 'normal' is now 'normal-', and 'normal' no longer allows high-risk features, even if your ComfyUI is local.
10
+ * V2.37 Show a ✅ mark to accounts that have been active on GitHub for more than six months.
11
+ * V2.33 Security policy is applied.
12
+ * V2.21 [cm-cli](docs/en/cm-cli.md) tool is added.
13
+ * V2.18 to V2.18.3 is not functioning due to a severe bug. Users on these versions are advised to promptly update to V2.18.4. Please navigate to the `ComfyUI/custom_nodes/ComfyUI-Manager` directory and execute `git pull` to update.
14
+ * You can see whole nodes info on [ComfyUI Nodes Info](https://ltdrdata.github.io/) page.
15
+
16
+ ## Installation
17
+
18
+ ### Installation[method1] (General installation method: ComfyUI-Manager only)
19
+
20
+ To install ComfyUI-Manager in addition to an existing installation of ComfyUI, you can follow the following steps:
21
+
22
+ 1. goto `ComfyUI/custom_nodes` dir in terminal(cmd)
23
+ 2. `git clone https://github.com/ltdrdata/ComfyUI-Manager.git`
24
+ 3. Restart ComfyUI
25
+
26
+
27
+ ### Installation[method2] (Installation for portable ComfyUI version: ComfyUI-Manager only)
28
+ 1. install git
29
+ - https://git-scm.com/download/win
30
+ - standalone version
31
+ - select option: use windows default console window
32
+ 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
33
+ 3. double click `install-manager-for-portable-version.bat` batch file
34
+
35
+ ![portable-install](misc/portable-install.png)
36
+
37
+
38
+ ### Installation[method3] (Installation through comfy-cli: install ComfyUI and ComfyUI-Manager at once.)
39
+ > RECOMMENDED: comfy-cli provides various features to manage ComfyUI from the CLI.
40
+
41
+ * **prerequisite: python 3, git**
42
+
43
+ Windows:
44
+ ```commandline
45
+ python -m venv venv
46
+ venv\Scripts\activate
47
+ pip install comfy-cli
48
+ comfy install
49
+ ```
50
+
51
+ Linux/OSX:
52
+ ```commandline
53
+ python -m venv venv
54
+ . venv/bin/activate
55
+ pip install comfy-cli
56
+ comfy install
57
+ ```
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
+ - ComfyUI will be installed in the subdirectory of the specified directory, and the directory will contain the generated executable script.
67
+ 2. `chmod +x install-comfyui-venv-linux.sh`
68
+ 3. `./install-comfyui-venv-linux.sh`
69
+
70
+ ### Installation Precautions
71
+ * **DO**: `ComfyUI-Manager` files must be accurately located in the path `ComfyUI/custom_nodes/ComfyUI-Manager`
72
+ * Installing in a compressed file format is not recommended.
73
+ * **DON'T**: Decompress directly into the `ComfyUI/custom_nodes` location, resulting in the Manager contents like `__init__.py` being placed directly in that directory.
74
+ * You have to remove all ComfyUI-Manager files from `ComfyUI/custom_nodes`
75
+ * **DON'T**: In a form where decompression occurs in a path such as `ComfyUI/custom_nodes/ComfyUI-Manager/ComfyUI-Manager`.
76
+ * You have to move `ComfyUI/custom_nodes/ComfyUI-Manager/ComfyUI-Manager` to `ComfyUI/custom_nodes/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.
79
+ * You have to rename `ComfyUI/custom_nodes/ComfyUI-Manager-main` to `ComfyUI/custom_nodes/ComfyUI-Manager`
80
+
81
+
82
+ You can execute ComfyUI by running either `./run_gpu.sh` or `./run_cpu.sh` depending on your system configuration.
83
+
84
+ ## Colab Notebook
85
+ 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).
86
+ * Support for installing ComfyUI
87
+ * Support for basic installation of ComfyUI-Manager
88
+ * Support for automatically installing dependencies of custom nodes upon restarting Colab notebooks.
89
+
90
+ ## Changes
91
+ * **2.38** `Install Custom Nodes` menu is changed to `Custom Nodes Manager`.
92
+ * **2.21** [cm-cli](docs/en/cm-cli.md) tool is added.
93
+ * **2.4** Copy the connections of the nearest node by double-clicking.
94
+ * **2.2.3** Support Components System
95
+ * **0.29** Add `Update all` feature
96
+ * **0.25** support db channel
97
+ * You can directly modify the db channel settings in the `config.ini` file.
98
+ * If you want to maintain a new DB channel, please modify the `channels.list` and submit a PR.
99
+ * **0.23** support multiple selection
100
+ * **0.18.1** `skip update check` feature added.
101
+ * A feature that allows quickly opening windows in environments where update checks take a long time.
102
+ * **0.17.1** Bug fix for the issue where enable/disable of the web extension was not working. Compatibility patch for StableSwarmUI.
103
+ * Requires latest version of ComfyUI (Revision: 1240)
104
+ * **0.17** Support preview method setting feature.
105
+ * **0.14** Support robust update.
106
+ * **0.13** Support additional 'pip' section for install spec.
107
+ * **0.12** Better installation support for Windows.
108
+ * **0.9** Support keyword search in installer menu.
109
+ * **V0.7.1** Bug fix for the issue where updates were not being applied on Windows.
110
+ * **For those who have been using versions 0.6, please perform a manual git pull in the custom_nodes/ComfyUI-Manager directory.**
111
+ * **V0.7** To address the issue of a slow list refresh, separate the fetch update and update check processes.
112
+ * **V0.6** Support extension installation for missing nodes.
113
+ * **V0.5** Removed external git program dependencies.
114
+
115
+
116
+ ## How To Use
117
+
118
+ 1. Click "Manager" button on main menu
119
+
120
+ ![mainmenu](misc/main.jpg)
121
+
122
+
123
+ 2. If you click on 'Install Custom Nodes' or 'Install Models', an installer dialog will open.
124
+
125
+ ![menu](misc/menu.jpg)
126
+
127
+ * There are three DB modes: `DB: Channel (1day cache)`, `DB: Local`, and `DB: Channel (remote)`.
128
+ * `Channel (1day cache)` utilizes Channel cache information with a validity period of one day to quickly display the list.
129
+ * This information will be updated when there is no cache, when the cache expires, or when external information is retrieved through the Channel (remote).
130
+ * Whenever you start ComfyUI anew, this mode is always set as the **default** mode.
131
+ * `Local` uses information stored locally in ComfyUI-Manager.
132
+ * This information will be updated only when you update ComfyUI-Manager.
133
+ * For custom node developers, they should use this mode when registering their nodes in `custom-node-list.json` and testing them.
134
+ * `Channel (remote)` retrieves information from the remote channel, always displaying the latest list.
135
+ * In cases where retrieval is not possible due to network errors, it will forcibly use local information.
136
+
137
+ * 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.
138
+
139
+ 3. Click 'Install' or 'Try Install' button.
140
+
141
+ ![node-install-dialog](misc/custom-nodes.jpg)
142
+
143
+ ![model-install-dialog](misc/models.png)
144
+
145
+ * Installed: This item is already installed.
146
+ * Install: Clicking this button will install the item.
147
+ * Try Install: This is a custom node of which installation information cannot be confirmed. Click the button to try installing it.
148
+
149
+ * 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.
150
+ * Channel settings have a broad impact, affecting not only the node list but also all functions like "Update all."
151
+ * 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.
152
+
153
+ 4. If you set the `Badge:` item in the menu as `Badge: Nickname`, `Badge: Nickname (hide built-in)`, `Badge: #ID Nickname`, `Badge: #ID Nickname (hide built-in)` the information badge will be displayed on the node.
154
+ * When selecting (hide built-in), it hides the 🦊 icon, which signifies built-in nodes.
155
+ * Nodes without any indication on the badge are custom nodes that Manager cannot recognize.
156
+ * `Badge: Nickname` displays the nickname of custom nodes, while `Badge: #ID Nickname` also includes the internal ID of the node.
157
+
158
+ ![model-install-dialog](misc/nickname.jpg)
159
+
160
+
161
+ 5. Share
162
+ ![menu](misc/main.jpg) ![share](misc/share.jpg)
163
+
164
+ * 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.
165
+ * Currently, it supports sharing via [https://comfyworkflows.com/](https://comfyworkflows.com/),
166
+ [https://openart.ai](https://openart.ai/workflows/dev), [https://youml.com](https://youml.com)
167
+ as well as through the Matrix channel.
168
+
169
+ ![menu](misc/share-setting.jpg)
170
+
171
+ * Through the Share settings in the Manager menu, you can configure the behavior of the Share button in the Main menu or Share Ouput button on Context Menu.
172
+ * `None`: hide from Main menu
173
+ * `All`: Show a dialog where the user can select a title for sharing.
174
+
175
+
176
+ ## Snapshot-Manager
177
+ * When you press `Save snapshot` or use `Update All` on `Manager Menu`, the current installation status snapshot is saved.
178
+ * Snapshot file dir: `ComfyUI-Manager/snapshots`
179
+ * You can rename snapshot file.
180
+ * Press the "Restore" button to revert to the installation status of the respective snapshot.
181
+ * However, for custom nodes not managed by Git, snapshot support is incomplete.
182
+ * When you press `Restore`, it will take effect on the next ComfyUI startup.
183
+ * The selected snapshot file is saved in `ComfyUI-Manager/startup-scripts/restore-snapshot.json`, and upon restarting ComfyUI, the snapshot is applied and then deleted.
184
+
185
+ ![model-install-dialog](misc/snapshot.jpg)
186
+
187
+
188
+ ## cm-cli: command line tools for power user
189
+ * A tool is provided that allows you to use the features of ComfyUI-Manager without running ComfyUI.
190
+ * For more details, please refer to the [cm-cli documentation](docs/en/cm-cli.md).
191
+
192
+
193
+ ## How to register your custom node into ComfyUI-Manager
194
+
195
+ * Add an entry to `custom-node-list.json` located in the root of ComfyUI-Manager and submit a Pull Request.
196
+ * 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.
197
+ * The remaining JSON will be updated through scripts in the future, so you don't need to worry about it.
198
+
199
+
200
+ ## Custom node support guide
201
+
202
+ * Currently, the system operates by cloning the git repository and sequentially installing the dependencies listed in requirements.txt using pip, followed by invoking the install.py script. In the future, we plan to discuss and determine the specifications for supporting custom nodes.
203
+
204
+ * Please submit a pull request to update either the custom-node-list.json or model-list.json file.
205
+
206
+ * The scanner currently provides a detection function for missing nodes, which is capable of detecting nodes described by the following two patterns.
207
+
208
+ ```
209
+ NODE_CLASS_MAPPINGS = {
210
+ "ExecutionSwitch": ExecutionSwitch,
211
+ "ExecutionBlocker": ExecutionBlocker,
212
+ ...
213
+ }
214
+
215
+ NODE_CLASS_MAPPINGS.update({
216
+ "UniFormer-SemSegPreprocessor": Uniformer_SemSegPreprocessor,
217
+ "SemSegPreprocessor": Uniformer_SemSegPreprocessor,
218
+ })
219
+ ```
220
+ * Or you can provide manually `node_list.json` file.
221
+
222
+ * When you write a docstring in the header of the .py file for the Node as follows, it will be used for managing the database in the Manager.
223
+ * Currently, only the `nickname` is being used, but other parts will also be utilized in the future.
224
+ * The `nickname` will be the name displayed on the badge of the node.
225
+ * If there is no `nickname`, it will be truncated to 20 characters from the arbitrarily written title and used.
226
+ ```
227
+ """
228
+ @author: Dr.Lt.Data
229
+ @title: Impact Pack
230
+ @nickname: Impact Pack
231
+ @description: This extension offers various detector nodes and detailer nodes that allow you to configure a workflow that automatically enhances facial details. And provide iterative upscaler.
232
+ """
233
+ ```
234
+
235
+
236
+ * **Special purpose files** (optional)
237
+ * `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))
238
+ * `requirements.txt` - When installing, this pip requirements will be installed automatically
239
+ * `install.py` - When installing, it is automatically called
240
+ * `uninstall.py` - When uninstalling, it is automatically called
241
+ * `disable.py` - When disabled, it is automatically called
242
+ * When installing a custom node setup `.js` file, it is recommended to write this script for disabling.
243
+ * `enable.py` - When enabled, it is automatically called
244
+ * **All scripts are executed from the root path of the corresponding custom node.**
245
+
246
+
247
+ ## Component Sharing
248
+ * **Copy & Paste**
249
+ * [Demo Page](https://ltdrdata.github.io/component-demo/)
250
+ * When pasting a component from the clipboard, it supports text in the following JSON format. (text/plain)
251
+ ```
252
+ {
253
+ "kind": "ComfyUI Components",
254
+ "timestamp": <current timestamp>,
255
+ "components":
256
+ {
257
+ <component name>: <component nodedata>
258
+ }
259
+ }
260
+ ```
261
+ * `<current timestamp>` Ensure that the timestamp is always unique.
262
+ * "components" should have the same structure as the content of the file stored in ComfyUI-Manager/components.
263
+ * `<component name>`: The name should be in the format `<prefix>::<node name>`.
264
+ * `<compnent nodeata>`: In the nodedata of the group node.
265
+ * `<version>`: Only two formats are allowed: `major.minor.patch` or `major.minor`. (e.g. `1.0`, `2.2.1`)
266
+ * `<datetime>`: Saved time
267
+ * `<packname>`: If the packname is not empty, the category becomes packname/workflow, and it is saved in the <packname>.pack file in ComfyUI-Manager/components.
268
+ * `<category>`: If there is neither a category nor a packname, it is saved in the components category.
269
+ ```
270
+ "version":"1.0",
271
+ "datetime": 1705390656516,
272
+ "packname": "mypack",
273
+ "category": "util/pipe",
274
+ ```
275
+ * **Drag & Drop**
276
+ * Dragging and dropping a `.pack` or `.json` file will add the corresponding components.
277
+ * Example pack: [Impact.pack](misc/Impact.pack)
278
+
279
+ * Dragging and dropping or pasting a single component will add a node. However, when adding multiple components, nodes will not be added.
280
+
281
+
282
+ ## Support of missing nodes installation
283
+
284
+ ![missing-menu](misc/missing-menu.jpg)
285
+
286
+ * 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.
287
+
288
+ ![missing-list](misc/missing-list.jpg)
289
+
290
+
291
+ ## Additional Feature
292
+ * Logging to file feature
293
+ * This feature is enabled by default and can be disabled by setting `file_logging = False` in the `config.ini`.
294
+
295
+ * 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.
296
+ * It is used to correct errors in nodes of old workflows created before, which are incompatible with the version changes of custom nodes.
297
+
298
+ * Double-Click Node Title: You can set the double click behavior of nodes in the ComfyUI-Manager menu.
299
+ * `Copy All Connections`, `Copy Input Connections`: Double-clicking a node copies the connections of the nearest node.
300
+ * This action targets the nearest node within a straight-line distance of 1000 pixels from the center of the node.
301
+ * 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.
302
+ * This feature copies only the input and output that match the names.
303
+
304
+ * `Possible Input Connections`: It connects all outputs that match the closest type within the specified range.
305
+ * This connection links to the closest outputs among the nodes located on the left side of the target node.
306
+
307
+ * `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`.
308
+
309
+ * Prevent downgrade of specific packages
310
+ * List the package names in the `downgrade_blacklist` section of the `config.ini` file, separating them with commas.
311
+ * e.g
312
+ ```
313
+ downgrade_blacklist = diffusers, kornia
314
+ ```
315
+
316
+ * Custom pip mapping
317
+ * When you create the `pip_overrides.json` file, it changes the installation of specific pip packages to installations defined by the user.
318
+ * Please refer to the `pip_overrides.json.template` file.
319
+
320
+ * Use `aria2` as downloader
321
+ * [howto](docs/en/use_aria2.md)
322
+
323
+ ## Scanner
324
+ When you run the `scan.sh` script:
325
+
326
+ * It updates the `extension-node-map.json`.
327
+ * To do this, it pulls or clones the custom nodes listed in `custom-node-list.json` into `~/.tmp/default`.
328
+ * To skip this step, add the `--skip-update` option.
329
+ * If you want to specify a different path instead of `~/.tmp/default`, run `python scanner.py [path]` directly instead of `scan.sh`.
330
+
331
+ * It updates the `github-stats.json`.
332
+ * 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.
333
+ * To skip this step, add the `--skip-update-stat` option.
334
+
335
+ * The `--skip-all` option applies both `--skip-update` and `--skip-stat-update`.
336
+
337
+
338
+ ## Troubleshooting
339
+ * 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 ComfyUI-Manager/config.ini file that is generated.
340
+ * 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`.
341
+ * Alternatively, download the update-fix.py script from [update-fix.py](https://github.com/ltdrdata/ComfyUI-Manager/raw/main/scripts/update-fix.py) and place it in the ComfyUI-Manager directory. Then, run it using your Python command.
342
+ For the portable version, use `..\..\..\python_embeded\python.exe update-fix.py`.
343
+ * For cases where nodes like `PreviewTextNode` from `ComfyUI_Custom_Nodes_AlekPet` are only supported as front-end nodes, we currently do not provide missing nodes for them.
344
+ * Currently, `vid2vid` is not being updated, causing compatibility issues.
345
+ * If you encounter the error message `Overlapped Object has pending operation at deallocation on Comfyui Manager load` under Windows
346
+ * Edit `config.ini` file: add `windows_selector_event_loop_policy = True`
347
+ * if `SSL: CERTIFICATE_VERIFY_FAILED` error is occured.
348
+ * Edit `config.ini` file: add `bypass_ssl = True`
349
+
350
+ ## Security policy
351
+ * Edit `config.ini` file: add `security_level = <LEVEL>`
352
+ * `strong`
353
+ * doesn't allow `high` and `middle` level risky feature
354
+ * `normal`
355
+ * doesn't allow `high` level risky feature
356
+ * `middle` level risky feature is available
357
+ * `normal-`
358
+ * doesn't allow `high` level risky feature if `--listen` is specified and not starts with `127.`
359
+ * `middle` level risky feature is available
360
+ * `weak`
361
+ * all feature is available
362
+
363
+ * `high` level risky features
364
+ * `Install via git url`, `pip install`
365
+ * Installation of custom nodes registered not in the `default channel`.
366
+ * Fix custom nodes
367
+
368
+ * `middle` level risky features
369
+ * Uninstall/Update
370
+ * Installation of custom nodes registered in the `default channel`.
371
+ * Restore/Remove Snapshot
372
+ * Restart
373
+
374
+ * `low` level risky features
375
+ * Update ComfyUI
376
+
377
+
378
+ ## TODO: Unconventional form of custom node list
379
+
380
+ * https://github.com/diontimmer/Sample-Diffusion-ComfyUI-Extension
381
+ * https://github.com/senshilabs/NINJA-plugin
382
+ * https://github.com/MockbaTheBorg/Nodes
383
+ * https://github.com/StartHua/Comfyui_GPT_Story
384
+ * https://github.com/NielsGercama/comfyui_customsampling
385
+ * https://github.com/wrightdaniel2017/ComfyUI-VideoLipSync
386
+ * https://github.com/bxdsjs/ComfyUI-Image-preprocessing
387
+ * https://github.com/SMUELDigital/ComfyUI-ONSET
388
+ * https://github.com/SimithWang/comfyui-renameImages
389
+ * https://github.com/icefairy64/comfyui-model-tilt
390
+ * https://github.com/andrewharp/ComfyUI-EasyNodes
391
+ * https://github.com/SimithWang/comfyui-renameImages
392
+ * https://github.com/Tcheko243/ComfyUI-Photographer-Alpha7-Nodes
393
+ * https://github.com/Limbicnation/ComfyUINodeToolbox
394
+ * https://github.com/APZmedia/ComfyUI-APZmedia-srtTools
395
+
396
+ ## Roadmap
397
+
398
+ - [x] System displaying information about failed custom nodes import.
399
+ - [x] Guide for missing nodes in ComfyUI vanilla nodes.
400
+ - [x] Collision checking system for nodes with the same ID across extensions.
401
+ - [x] Template sharing system. (-> Component system based on Group Nodes)
402
+ - [x] 3rd party API system.
403
+ - [ ] Auto migration for custom nodes with changed structures.
404
+ - [ ] Version control feature for nodes.
405
+ - [ ] List of currently used custom nodes.
406
+ - [x] Download support multiple model download.
407
+ - [x] Model download via url.
408
+ - [x] List sorting (custom nodes).
409
+ - [x] List sorting (model).
410
+ - [ ] Provides description of node.
411
+
412
+
413
+ # Disclaimer
414
+
415
+ * This extension simply provides the convenience of installing custom nodes and does not guarantee their proper functioning.
416
+
417
+
418
+ ## Credit
419
+ ComfyUI/[ComfyUI](https://github.com/comfyanonymous/ComfyUI) - A powerful and modular stable diffusion GUI.
420
+
421
+ **And, for all ComfyUI custom node developers**
ComfyUI/custom_nodes/ComfyUI-Manager/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
9
+ import share_3rdparty
10
+ WEB_DIRECTORY = "js"
11
+ else:
12
+ print(f"\n[ComfyUI-Manager] !! cli-only-mode is enabled !!\n")
13
+
14
+ NODE_CLASS_MAPPINGS = {}
15
+ __all__ = ['NODE_CLASS_MAPPINGS']
16
+
17
+
18
+
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,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "node_db/new/custom-node-list.json"
13
+ "node_db/new/model-list.json"
14
+ "node_db/new/extension-node-map.json"
15
+ "node_db/dev/custom-node-list.json"
16
+ "node_db/dev/model-list.json"
17
+ "node_db/dev/extension-node-map.json"
18
+ "node_db/tutorial/custom-node-list.json"
19
+ "node_db/tutorial/model-list.json"
20
+ "node_db/tutorial/extension-node-map.json"
21
+ "node_db/legacy/custom-node-list.json"
22
+ "node_db/legacy/model-list.json"
23
+ "node_db/legacy/extension-node-map.json"
24
+ "node_db/forked/custom-node-list.json"
25
+ "node_db/forked/model-list.json"
26
+ "node_db/forked/extension-node-map.json"
27
+ )
28
+
29
+ for file in "${files[@]}"; do
30
+ python json-checker.py "$file"
31
+ done
32
+
33
+ echo
34
+ echo CHECK2
35
+ find ~/.tmp/default -name "*.py" -print0 | xargs -0 grep -E "crypto|^_A="
36
+
37
+ echo
38
+ echo CHECK3
39
+ find ~/.tmp/default -name "requirements.txt" | xargs grep "^\s*https\\?:"
40
+ find ~/.tmp/default -name "requirements.txt" | xargs grep "\.whl"
41
+
42
+ echo
ComfyUI/custom_nodes/ComfyUI-Manager/cm-cli.py ADDED
@@ -0,0 +1,1031 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import traceback
4
+ import json
5
+ import asyncio
6
+ import subprocess
7
+ import shutil
8
+ import concurrent
9
+ import threading
10
+ from typing import Optional
11
+
12
+ import typer
13
+ from rich import print
14
+ from typing_extensions import List, Annotated
15
+ import re
16
+ import git
17
+
18
+ sys.path.append(os.path.dirname(__file__))
19
+ sys.path.append(os.path.join(os.path.dirname(__file__), "glob"))
20
+ import manager_core as core
21
+ import cm_global
22
+
23
+ comfyui_manager_path = os.path.dirname(__file__)
24
+ comfy_path = os.environ.get('COMFYUI_PATH')
25
+
26
+ if comfy_path is None:
27
+ print(f"\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)
28
+ comfy_path = os.path.abspath(os.path.join(comfyui_manager_path, '..', '..'))
29
+
30
+ startup_script_path = os.path.join(comfyui_manager_path, "startup-scripts")
31
+ custom_nodes_path = os.path.join(comfy_path, 'custom_nodes')
32
+
33
+ script_path = os.path.join(startup_script_path, "install-scripts.txt")
34
+ restore_snapshot_path = os.path.join(startup_script_path, "restore-snapshot.json")
35
+ pip_overrides_path = os.path.join(comfyui_manager_path, "pip_overrides.json")
36
+ git_script_path = os.path.join(comfyui_manager_path, "git_helper.py")
37
+
38
+ cm_global.pip_blacklist = ['torch', 'torchsde', 'torchvision']
39
+ cm_global.pip_downgrade_blacklist = ['torch', 'torchsde', 'torchvision', 'transformers', 'safetensors', 'kornia']
40
+ cm_global.pip_overrides = {}
41
+ if os.path.exists(pip_overrides_path):
42
+ with open(pip_overrides_path, 'r', encoding="UTF-8", errors="ignore") as json_file:
43
+ cm_global.pip_overrides = json.load(json_file)
44
+ cm_global.pip_overrides['numpy'] = 'numpy<2'
45
+
46
+
47
+ def check_comfyui_hash():
48
+ repo = git.Repo(comfy_path)
49
+ core.comfy_ui_revision = len(list(repo.iter_commits('HEAD')))
50
+
51
+ comfy_ui_hash = repo.head.commit.hexsha
52
+ cm_global.variables['comfyui.revision'] = core.comfy_ui_revision
53
+
54
+ core.comfy_ui_commit_datetime = repo.head.commit.committed_datetime
55
+
56
+
57
+ check_comfyui_hash() # This is a preparation step for manager_core
58
+
59
+
60
+ def read_downgrade_blacklist():
61
+ try:
62
+ import configparser
63
+ config_path = os.path.join(os.path.dirname(__file__), "config.ini")
64
+ config = configparser.ConfigParser()
65
+ config.read(config_path)
66
+ default_conf = config['default']
67
+
68
+ if 'downgrade_blacklist' in default_conf:
69
+ items = default_conf['downgrade_blacklist'].split(',')
70
+ items = [x.strip() for x in items if x != '']
71
+ cm_global.pip_downgrade_blacklist += items
72
+ cm_global.pip_downgrade_blacklist = list(set(cm_global.pip_downgrade_blacklist))
73
+ except:
74
+ pass
75
+
76
+
77
+ read_downgrade_blacklist() # This is a preparation step for manager_core
78
+
79
+
80
+ class Ctx:
81
+ def __init__(self):
82
+ self.channel = 'default'
83
+ self.mode = 'remote'
84
+ self.processed_install = set()
85
+ self.custom_node_map_cache = None
86
+
87
+ def set_channel_mode(self, channel, mode):
88
+ if mode is not None:
89
+ self.mode = mode
90
+
91
+ valid_modes = ["remote", "local", "cache"]
92
+ if mode and mode.lower() not in valid_modes:
93
+ typer.echo(
94
+ f"Invalid mode: {mode}. Allowed modes are 'remote', 'local', 'cache'.",
95
+ err=True,
96
+ )
97
+ exit(1)
98
+
99
+ if channel is not None:
100
+ self.channel = channel
101
+
102
+ def post_install(self, url):
103
+ try:
104
+ repository_name = url.split("/")[-1].strip()
105
+ repo_path = os.path.join(custom_nodes_path, repository_name)
106
+ repo_path = os.path.abspath(repo_path)
107
+
108
+ requirements_path = os.path.join(repo_path, 'requirements.txt')
109
+ install_script_path = os.path.join(repo_path, 'install.py')
110
+
111
+ if os.path.exists(requirements_path):
112
+ with open(requirements_path, 'r', encoding="UTF-8", errors="ignore") as file:
113
+ for line in file:
114
+ package_name = core.remap_pip_package(line.strip())
115
+ if package_name and not core.is_installed(package_name):
116
+ install_cmd = [sys.executable, "-m", "pip", "install", package_name]
117
+ output = subprocess.check_output(install_cmd, cwd=repo_path, text=True)
118
+ for msg_line in output.split('\n'):
119
+ if 'Requirement already satisfied:' in msg_line:
120
+ print('.', end='')
121
+ else:
122
+ print(msg_line)
123
+
124
+ if os.path.exists(install_script_path) and f'{repo_path}/install.py' not in self.processed_install:
125
+ self.processed_install.add(f'{repo_path}/install.py')
126
+ install_cmd = [sys.executable, install_script_path]
127
+ output = subprocess.check_output(install_cmd, cwd=repo_path, text=True)
128
+ for msg_line in output.split('\n'):
129
+ if 'Requirement already satisfied:' in msg_line:
130
+ print('.', end='')
131
+ else:
132
+ print(msg_line)
133
+
134
+ except Exception:
135
+ print(f"ERROR: Restoring '{url}' is failed.")
136
+
137
+ def restore_dependencies(self):
138
+ node_paths = [os.path.join(custom_nodes_path, name) for name in os.listdir(custom_nodes_path)
139
+ if os.path.isdir(os.path.join(custom_nodes_path, name)) and not name.endswith('.disabled')]
140
+
141
+ total = len(node_paths)
142
+ i = 1
143
+ for x in node_paths:
144
+ print(f"----------------------------------------------------------------------------------------------------")
145
+ print(f"Restoring [{i}/{total}]: {x}")
146
+ self.post_install(x)
147
+ i += 1
148
+
149
+ def load_custom_nodes(self):
150
+ channel_dict = core.get_channel_dict()
151
+ if self.channel not in channel_dict:
152
+ print(f"[bold red]ERROR: Invalid channel is specified `--channel {self.channel}`[/bold red]", file=sys.stderr)
153
+ exit(1)
154
+
155
+ if self.mode not in ['remote', 'local', 'cache']:
156
+ print(f"[bold red]ERROR: Invalid mode is specified `--mode {self.mode}`[/bold red]", file=sys.stderr)
157
+ exit(1)
158
+
159
+ channel_url = channel_dict[self.channel]
160
+
161
+ res = {}
162
+ json_obj = asyncio.run(core.get_data_by_mode(self.mode, 'custom-node-list.json', channel_url=channel_url))
163
+ for x in json_obj['custom_nodes']:
164
+ for y in x['files']:
165
+ if 'github.com' in y and not (y.endswith('.py') or y.endswith('.js')):
166
+ repo_name = y.split('/')[-1]
167
+ res[repo_name] = (x, False)
168
+
169
+ if 'id' in x:
170
+ if x['id'] not in res:
171
+ res[x['id']] = (x, True)
172
+
173
+ return res
174
+
175
+ def get_custom_node_map(self):
176
+ if self.custom_node_map_cache is not None:
177
+ return self.custom_node_map_cache
178
+
179
+ self.custom_node_map_cache = self.load_custom_nodes()
180
+
181
+ return self.custom_node_map_cache
182
+
183
+ def lookup_node_path(self, node_name, robust=False):
184
+ if '..' in node_name:
185
+ print(f"\n[bold red]ERROR: Invalid node name '{node_name}'[/bold red]\n")
186
+ exit(2)
187
+
188
+ custom_node_map = self.get_custom_node_map()
189
+ if node_name in custom_node_map:
190
+ node_url = custom_node_map[node_name][0]['files'][0]
191
+ repo_name = node_url.split('/')[-1]
192
+ node_path = os.path.join(custom_nodes_path, repo_name)
193
+ return node_path, custom_node_map[node_name][0]
194
+ elif robust:
195
+ node_path = os.path.join(custom_nodes_path, node_name)
196
+ return node_path, None
197
+
198
+ print(f"\n[bold red]ERROR: Invalid node name '{node_name}'[/bold red]\n")
199
+ exit(2)
200
+
201
+
202
+ cm_ctx = Ctx()
203
+
204
+
205
+ def install_node(node_name, is_all=False, cnt_msg=''):
206
+ if core.is_valid_url(node_name):
207
+ # install via urls
208
+ res = core.gitclone_install([node_name])
209
+ if not res:
210
+ print(f"[bold red]ERROR: An error occurred while installing '{node_name}'.[/bold red]")
211
+ else:
212
+ print(f"{cnt_msg} [INSTALLED] {node_name:50}")
213
+ else:
214
+ node_path, node_item = cm_ctx.lookup_node_path(node_name)
215
+
216
+ if os.path.exists(node_path):
217
+ if not is_all:
218
+ print(f"{cnt_msg} [ SKIPPED ] {node_name:50} => Already installed")
219
+ elif os.path.exists(node_path + '.disabled'):
220
+ enable_node(node_name)
221
+ else:
222
+ res = core.gitclone_install(node_item['files'], instant_execution=True, msg_prefix=f"[{cnt_msg}] ")
223
+ if not res:
224
+ print(f"[bold red]ERROR: An error occurred while installing '{node_name}'.[/bold red]")
225
+ else:
226
+ print(f"{cnt_msg} [INSTALLED] {node_name:50}")
227
+
228
+
229
+ def reinstall_node(node_name, is_all=False, cnt_msg=''):
230
+ node_path, node_item = cm_ctx.lookup_node_path(node_name)
231
+
232
+ if os.path.exists(node_path):
233
+ shutil.rmtree(node_path)
234
+ if os.path.exists(node_path + '.disabled'):
235
+ shutil.rmtree(node_path + '.disabled')
236
+
237
+ install_node(node_name, is_all=is_all, cnt_msg=cnt_msg)
238
+
239
+
240
+ def fix_node(node_name, is_all=False, cnt_msg=''):
241
+ node_path, node_item = cm_ctx.lookup_node_path(node_name, robust=True)
242
+
243
+ files = node_item['files'] if node_item is not None else [node_path]
244
+
245
+ if os.path.exists(node_path):
246
+ print(f"{cnt_msg} [ FIXING ]: {node_name:50} => Disabled")
247
+ res = core.gitclone_fix(files, instant_execution=True)
248
+ if not res:
249
+ print(f"ERROR: An error occurred while fixing '{node_name}'.")
250
+ elif not is_all and os.path.exists(node_path + '.disabled'):
251
+ print(f"{cnt_msg} [ SKIPPED ]: {node_name:50} => Disabled")
252
+ elif not is_all:
253
+ print(f"{cnt_msg} [ SKIPPED ]: {node_name:50} => Not installed")
254
+
255
+
256
+ def uninstall_node(node_name, is_all=False, cnt_msg=''):
257
+ node_path, node_item = cm_ctx.lookup_node_path(node_name, robust=True)
258
+
259
+ files = node_item['files'] if node_item is not None else [node_path]
260
+
261
+ if os.path.exists(node_path) or os.path.exists(node_path + '.disabled'):
262
+ res = core.gitclone_uninstall(files)
263
+ if not res:
264
+ print(f"ERROR: An error occurred while uninstalling '{node_name}'.")
265
+ else:
266
+ print(f"{cnt_msg} [UNINSTALLED] {node_name:50}")
267
+ else:
268
+ print(f"{cnt_msg} [ SKIPPED ]: {node_name:50} => Not installed")
269
+
270
+
271
+ def update_node(node_name, is_all=False, cnt_msg=''):
272
+ node_path, node_item = cm_ctx.lookup_node_path(node_name, robust=True)
273
+
274
+ files = node_item['files'] if node_item is not None else [node_path]
275
+
276
+ res = core.gitclone_update(files, skip_script=True, msg_prefix=f"[{cnt_msg}] ")
277
+
278
+ if not res:
279
+ print(f"ERROR: An error occurred while updating '{node_name}'.")
280
+ return None
281
+
282
+ return node_path
283
+
284
+
285
+ def update_parallel(nodes):
286
+ is_all = False
287
+ if 'all' in nodes:
288
+ is_all = True
289
+ nodes = [x for x in cm_ctx.get_custom_node_map().keys() if os.path.exists(os.path.join(custom_nodes_path, x)) or os.path.exists(os.path.join(custom_nodes_path, x) + '.disabled')]
290
+
291
+ nodes = [x for x in nodes if x.lower() not in ['comfy', 'comfyui', 'all']]
292
+
293
+ total = len(nodes)
294
+
295
+ lock = threading.Lock()
296
+ processed = []
297
+
298
+ i = 0
299
+
300
+ def process_custom_node(x):
301
+ nonlocal i
302
+ nonlocal processed
303
+
304
+ with lock:
305
+ i += 1
306
+
307
+ try:
308
+ node_path = update_node(x, is_all=is_all, cnt_msg=f'{i}/{total}')
309
+ with lock:
310
+ processed.append(node_path)
311
+ except Exception as e:
312
+ print(f"ERROR: {e}")
313
+ traceback.print_exc()
314
+
315
+ with concurrent.futures.ThreadPoolExecutor(4) as executor:
316
+ for item in nodes:
317
+ executor.submit(process_custom_node, item)
318
+
319
+ i = 1
320
+ for node_path in processed:
321
+ if node_path is None:
322
+ print(f"[{i}/{total}] Post update: ERROR")
323
+ else:
324
+ print(f"[{i}/{total}] Post update: {node_path}")
325
+ cm_ctx.post_install(node_path)
326
+ i += 1
327
+
328
+
329
+ def update_comfyui():
330
+ res = core.update_path(comfy_path, instant_execution=True)
331
+ if res == 'fail':
332
+ print("Updating ComfyUI has failed.")
333
+ elif res == 'updated':
334
+ print("ComfyUI is updated.")
335
+ else:
336
+ print("ComfyUI is already up to date.")
337
+
338
+
339
+ def enable_node(node_name, is_all=False, cnt_msg=''):
340
+ if node_name == 'ComfyUI-Manager':
341
+ return
342
+
343
+ node_path, node_item = cm_ctx.lookup_node_path(node_name, robust=True)
344
+
345
+ if os.path.exists(node_path + '.disabled'):
346
+ current_name = node_path + '.disabled'
347
+ os.rename(current_name, node_path)
348
+ print(f"{cnt_msg} [ENABLED] {node_name:50}")
349
+ elif os.path.exists(node_path):
350
+ print(f"{cnt_msg} [SKIPPED] {node_name:50} => Already enabled")
351
+ elif not is_all:
352
+ print(f"{cnt_msg} [SKIPPED] {node_name:50} => Not installed")
353
+
354
+
355
+ def disable_node(node_name, is_all=False, cnt_msg=''):
356
+ if node_name == 'ComfyUI-Manager':
357
+ return
358
+
359
+ node_path, node_item = cm_ctx.lookup_node_path(node_name, robust=True)
360
+
361
+ if os.path.exists(node_path):
362
+ current_name = node_path
363
+ new_name = node_path + '.disabled'
364
+ os.rename(current_name, new_name)
365
+ print(f"{cnt_msg} [DISABLED] {node_name:50}")
366
+ elif os.path.exists(node_path + '.disabled'):
367
+ print(f"{cnt_msg} [ SKIPPED] {node_name:50} => Already disabled")
368
+ elif not is_all:
369
+ print(f"{cnt_msg} [ SKIPPED] {node_name:50} => Not installed")
370
+
371
+
372
+ def show_list(kind, simple=False):
373
+ for k, v in cm_ctx.get_custom_node_map().items():
374
+ if v[1]:
375
+ continue
376
+
377
+ node_path = os.path.join(custom_nodes_path, k)
378
+
379
+ states = set()
380
+ if os.path.exists(node_path):
381
+ prefix = '[ ENABLED ] '
382
+ states.add('installed')
383
+ states.add('enabled')
384
+ states.add('all')
385
+ elif os.path.exists(node_path + '.disabled'):
386
+ prefix = '[ DISABLED ] '
387
+ states.add('installed')
388
+ states.add('disabled')
389
+ states.add('all')
390
+ else:
391
+ prefix = '[ NOT INSTALLED ] '
392
+ states.add('not-installed')
393
+ states.add('all')
394
+
395
+ if kind in states:
396
+ if simple:
397
+ print(f"{k:50}")
398
+ else:
399
+ short_id = v[0].get('id', "")
400
+ print(f"{prefix} {k:50} {short_id:20} (author: {v[0]['author']})")
401
+
402
+ # unregistered nodes
403
+ candidates = os.listdir(os.path.realpath(custom_nodes_path))
404
+
405
+ for k in candidates:
406
+ fullpath = os.path.join(custom_nodes_path, k)
407
+
408
+ if os.path.isfile(fullpath):
409
+ continue
410
+
411
+ if k in ['__pycache__']:
412
+ continue
413
+
414
+ states = set()
415
+ if k.endswith('.disabled'):
416
+ prefix = '[ DISABLED ] '
417
+ states.add('installed')
418
+ states.add('disabled')
419
+ states.add('all')
420
+ k = k[:-9]
421
+ else:
422
+ prefix = '[ ENABLED ] '
423
+ states.add('installed')
424
+ states.add('enabled')
425
+ states.add('all')
426
+
427
+ if k not in cm_ctx.get_custom_node_map():
428
+ if kind in states:
429
+ if simple:
430
+ print(f"{k:50}")
431
+ else:
432
+ print(f"{prefix} {k:50} {'':20} (author: N/A)")
433
+
434
+
435
+ def show_snapshot(simple_mode=False):
436
+ json_obj = core.get_current_snapshot()
437
+
438
+ if simple_mode:
439
+ print(f"[{json_obj['comfyui']}] comfyui")
440
+ for k, v in json_obj['git_custom_nodes'].items():
441
+ print(f"[{v['hash']}] {k}")
442
+ for v in json_obj['file_custom_nodes']:
443
+ print(f"[ N/A ] {v['filename']}")
444
+
445
+ else:
446
+ formatted_json = json.dumps(json_obj, ensure_ascii=False, indent=4)
447
+ print(formatted_json)
448
+
449
+
450
+ def show_snapshot_list(simple_mode=False):
451
+ snapshot_path = os.path.join(comfyui_manager_path, 'snapshots')
452
+
453
+ files = os.listdir(snapshot_path)
454
+ json_files = [x for x in files if x.endswith('.json')]
455
+ for x in sorted(json_files):
456
+ print(x)
457
+
458
+
459
+ def cancel():
460
+ if os.path.exists(script_path):
461
+ os.remove(script_path)
462
+
463
+ if os.path.exists(restore_snapshot_path):
464
+ os.remove(restore_snapshot_path)
465
+
466
+
467
+ def auto_save_snapshot():
468
+ path = core.save_snapshot_with_postfix('cli-autosave')
469
+ print(f"Current snapshot is saved as `{path}`")
470
+
471
+
472
+ def for_each_nodes(nodes, act, allow_all=True):
473
+ is_all = False
474
+ if allow_all and 'all' in nodes:
475
+ is_all = True
476
+ nodes = [x for x in cm_ctx.get_custom_node_map().keys() if os.path.exists(os.path.join(custom_nodes_path, x)) or os.path.exists(os.path.join(custom_nodes_path, x) + '.disabled')]
477
+
478
+ nodes = [x for x in nodes if x.lower() not in ['comfy', 'comfyui', 'all']]
479
+
480
+ total = len(nodes)
481
+ i = 1
482
+ for x in nodes:
483
+ try:
484
+ act(x, is_all=is_all, cnt_msg=f'{i}/{total}')
485
+ except Exception as e:
486
+ print(f"ERROR: {e}")
487
+ traceback.print_exc()
488
+ i += 1
489
+
490
+
491
+ app = typer.Typer()
492
+
493
+
494
+ @app.command(help="Display help for commands")
495
+ def help(ctx: typer.Context):
496
+ print(ctx.find_root().get_help())
497
+ ctx.exit(0)
498
+
499
+
500
+ @app.command(help="Install custom nodes")
501
+ def install(
502
+ nodes: List[str] = typer.Argument(
503
+ ..., help="List of custom nodes to install"
504
+ ),
505
+ channel: Annotated[
506
+ str,
507
+ typer.Option(
508
+ show_default=False,
509
+ help="Specify the operation mode"
510
+ ),
511
+ ] = None,
512
+ mode: str = typer.Option(
513
+ None,
514
+ help="[remote|local|cache]"
515
+ ),
516
+ ):
517
+ cm_ctx.set_channel_mode(channel, mode)
518
+ for_each_nodes(nodes, act=install_node)
519
+
520
+
521
+ @app.command(help="Reinstall custom nodes")
522
+ def reinstall(
523
+ nodes: List[str] = typer.Argument(
524
+ ..., help="List of custom nodes to reinstall"
525
+ ),
526
+ channel: Annotated[
527
+ str,
528
+ typer.Option(
529
+ show_default=False,
530
+ help="Specify the operation mode"
531
+ ),
532
+ ] = None,
533
+ mode: str = typer.Option(
534
+ None,
535
+ help="[remote|local|cache]"
536
+ ),
537
+ ):
538
+ cm_ctx.set_channel_mode(channel, mode)
539
+ for_each_nodes(nodes, act=reinstall_node)
540
+
541
+
542
+ @app.command(help="Uninstall custom nodes")
543
+ def uninstall(
544
+ nodes: List[str] = typer.Argument(
545
+ ..., help="List of custom nodes to uninstall"
546
+ ),
547
+ channel: Annotated[
548
+ str,
549
+ typer.Option(
550
+ show_default=False,
551
+ help="Specify the operation mode"
552
+ ),
553
+ ] = None,
554
+ mode: str = typer.Option(
555
+ None,
556
+ help="[remote|local|cache]"
557
+ ),
558
+ ):
559
+ cm_ctx.set_channel_mode(channel, mode)
560
+ for_each_nodes(nodes, act=uninstall_node)
561
+
562
+
563
+ @app.command(help="Disable custom nodes")
564
+ def update(
565
+ nodes: List[str] = typer.Argument(
566
+ ...,
567
+ help="[all|List of custom nodes to update]"
568
+ ),
569
+ channel: Annotated[
570
+ str,
571
+ typer.Option(
572
+ show_default=False,
573
+ help="Specify the operation mode"
574
+ ),
575
+ ] = None,
576
+ mode: str = typer.Option(
577
+ None,
578
+ help="[remote|local|cache]"
579
+ ),
580
+ ):
581
+ cm_ctx.set_channel_mode(channel, mode)
582
+
583
+ if 'all' in nodes:
584
+ auto_save_snapshot()
585
+
586
+ for x in nodes:
587
+ if x.lower() in ['comfyui', 'comfy', 'all']:
588
+ update_comfyui()
589
+ break
590
+
591
+ update_parallel(nodes)
592
+
593
+
594
+ @app.command(help="Disable custom nodes")
595
+ def disable(
596
+ nodes: List[str] = typer.Argument(
597
+ ...,
598
+ help="[all|List of custom nodes to disable]"
599
+ ),
600
+ channel: Annotated[
601
+ str,
602
+ typer.Option(
603
+ show_default=False,
604
+ help="Specify the operation mode"
605
+ ),
606
+ ] = None,
607
+ mode: str = typer.Option(
608
+ None,
609
+ help="[remote|local|cache]"
610
+ ),
611
+ ):
612
+ cm_ctx.set_channel_mode(channel, mode)
613
+
614
+ if 'all' in nodes:
615
+ auto_save_snapshot()
616
+
617
+ for_each_nodes(nodes, disable_node, allow_all=True)
618
+
619
+
620
+ @app.command(help="Enable custom nodes")
621
+ def enable(
622
+ nodes: List[str] = typer.Argument(
623
+ ...,
624
+ help="[all|List of custom nodes to enable]"
625
+ ),
626
+ channel: Annotated[
627
+ str,
628
+ typer.Option(
629
+ show_default=False,
630
+ help="Specify the operation mode"
631
+ ),
632
+ ] = None,
633
+ mode: str = typer.Option(
634
+ None,
635
+ help="[remote|local|cache]"
636
+ ),
637
+ ):
638
+ cm_ctx.set_channel_mode(channel, mode)
639
+
640
+ if 'all' in nodes:
641
+ auto_save_snapshot()
642
+
643
+ for_each_nodes(nodes, enable_node, allow_all=True)
644
+
645
+
646
+ @app.command(help="Fix dependencies of custom nodes")
647
+ def fix(
648
+ nodes: List[str] = typer.Argument(
649
+ ...,
650
+ help="[all|List of custom nodes to fix]"
651
+ ),
652
+ channel: Annotated[
653
+ str,
654
+ typer.Option(
655
+ show_default=False,
656
+ help="Specify the operation mode"
657
+ ),
658
+ ] = None,
659
+ mode: str = typer.Option(
660
+ None,
661
+ help="[remote|local|cache]"
662
+ ),
663
+ ):
664
+ cm_ctx.set_channel_mode(channel, mode)
665
+
666
+ if 'all' in nodes:
667
+ auto_save_snapshot()
668
+
669
+ for_each_nodes(nodes, fix_node, allow_all=True)
670
+
671
+
672
+ @app.command("show", help="Show node list (simple mode)")
673
+ def show(
674
+ arg: str = typer.Argument(
675
+ help="[installed|enabled|not-installed|disabled|all|snapshot|snapshot-list]"
676
+ ),
677
+ channel: Annotated[
678
+ str,
679
+ typer.Option(
680
+ show_default=False,
681
+ help="Specify the operation mode"
682
+ ),
683
+ ] = None,
684
+ mode: str = typer.Option(
685
+ None,
686
+ help="[remote|local|cache]"
687
+ ),
688
+ ):
689
+ valid_commands = [
690
+ "installed",
691
+ "enabled",
692
+ "not-installed",
693
+ "disabled",
694
+ "all",
695
+ "snapshot",
696
+ "snapshot-list",
697
+ ]
698
+ if arg not in valid_commands:
699
+ typer.echo(f"Invalid command: `show {arg}`", err=True)
700
+ exit(1)
701
+
702
+ cm_ctx.set_channel_mode(channel, mode)
703
+ if arg == 'snapshot':
704
+ show_snapshot()
705
+ elif arg == 'snapshot-list':
706
+ show_snapshot_list()
707
+ else:
708
+ show_list(arg)
709
+
710
+
711
+ @app.command("simple-show", help="Show node list (simple mode)")
712
+ def simple_show(
713
+ arg: str = typer.Argument(
714
+ help="[installed|enabled|not-installed|disabled|all|snapshot|snapshot-list]"
715
+ ),
716
+ channel: Annotated[
717
+ str,
718
+ typer.Option(
719
+ show_default=False,
720
+ help="Specify the operation mode"
721
+ ),
722
+ ] = None,
723
+ mode: str = typer.Option(
724
+ None,
725
+ help="[remote|local|cache]"
726
+ ),
727
+ ):
728
+ valid_commands = [
729
+ "installed",
730
+ "enabled",
731
+ "not-installed",
732
+ "disabled",
733
+ "all",
734
+ "snapshot",
735
+ "snapshot-list",
736
+ ]
737
+ if arg not in valid_commands:
738
+ typer.echo(f"[bold red]Invalid command: `show {arg}`[/bold red]", err=True)
739
+ exit(1)
740
+
741
+ cm_ctx.set_channel_mode(channel, mode)
742
+ if arg == 'snapshot':
743
+ show_snapshot(True)
744
+ elif arg == 'snapshot-list':
745
+ show_snapshot_list(True)
746
+ else:
747
+ show_list(arg, True)
748
+
749
+
750
+ @app.command('cli-only-mode', help="Set whether to use ComfyUI-Manager in CLI-only mode.")
751
+ def cli_only_mode(
752
+ mode: str = typer.Argument(
753
+ ..., help="[enable|disable]"
754
+ )):
755
+ cli_mode_flag = os.path.join(os.path.dirname(__file__), '.enable-cli-only-mode')
756
+ if mode.lower() == 'enable':
757
+ with open(cli_mode_flag, 'w') as file:
758
+ pass
759
+ print(f"\nINFO: `cli-only-mode` is enabled\n")
760
+ elif mode.lower() == 'disable':
761
+ if os.path.exists(cli_mode_flag):
762
+ os.remove(cli_mode_flag)
763
+ print(f"\nINFO: `cli-only-mode` is disabled\n")
764
+ else:
765
+ print(f"\n[bold red]Invalid value for cli-only-mode: {mode}[/bold red]\n")
766
+ exit(1)
767
+
768
+
769
+ @app.command(
770
+ "deps-in-workflow", help="Generate dependencies file from workflow (.json/.png)"
771
+ )
772
+ def deps_in_workflow(
773
+ workflow: Annotated[
774
+ str, typer.Option(show_default=False, help="Workflow file (.json/.png)")
775
+ ],
776
+ output: Annotated[
777
+ str, typer.Option(show_default=False, help="Output file (.json)")
778
+ ],
779
+ channel: Annotated[
780
+ str,
781
+ typer.Option(
782
+ show_default=False,
783
+ help="Specify the operation mode"
784
+ ),
785
+ ] = None,
786
+ mode: str = typer.Option(
787
+ None,
788
+ help="[remote|local|cache]"
789
+ ),
790
+ ):
791
+ cm_ctx.set_channel_mode(channel, mode)
792
+
793
+ input_path = workflow
794
+ output_path = output
795
+
796
+ if not os.path.exists(input_path):
797
+ print(f"[bold red]File not found: {input_path}[/bold red]")
798
+ exit(1)
799
+
800
+ used_exts, unknown_nodes = asyncio.run(core.extract_nodes_from_workflow(input_path, mode=cm_ctx.mode, channel_url=cm_ctx.channel))
801
+
802
+ custom_nodes = {}
803
+ for x in used_exts:
804
+ custom_nodes[x] = {'state': core.simple_check_custom_node(x),
805
+ 'hash': '-'
806
+ }
807
+
808
+ res = {
809
+ 'custom_nodes': custom_nodes,
810
+ 'unknown_nodes': list(unknown_nodes)
811
+ }
812
+
813
+ with open(output_path, "w", encoding='utf-8') as output_file:
814
+ json.dump(res, output_file, indent=4)
815
+
816
+ print(f"Workflow dependencies are being saved into {output_path}.")
817
+
818
+
819
+ @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.")
820
+ def save_snapshot(
821
+ output: Annotated[
822
+ str,
823
+ typer.Option(
824
+ show_default=False, help="Specify the output file path. (.json/.yaml)"
825
+ ),
826
+ ] = None,
827
+ ):
828
+ path = core.save_snapshot_with_postfix('snapshot', output)
829
+ print(f"Current snapshot is saved as `{path}`")
830
+
831
+
832
+ @app.command("restore-snapshot", help="Restore snapshot from snapshot file")
833
+ def restore_snapshot(
834
+ snapshot_name: str,
835
+ pip_non_url: Optional[bool] = typer.Option(
836
+ default=None,
837
+ show_default=False,
838
+ is_flag=True,
839
+ help="Restore for pip packages registered on PyPI.",
840
+ ),
841
+ pip_non_local_url: Optional[bool] = typer.Option(
842
+ default=None,
843
+ show_default=False,
844
+ is_flag=True,
845
+ help="Restore for pip packages registered at web URLs.",
846
+ ),
847
+ pip_local_url: Optional[bool] = typer.Option(
848
+ default=None,
849
+ show_default=False,
850
+ is_flag=True,
851
+ help="Restore for pip packages specified by local paths.",
852
+ ),
853
+ ):
854
+ extras = []
855
+ if pip_non_url:
856
+ extras.append('--pip-non-url')
857
+
858
+ if pip_non_local_url:
859
+ extras.append('--pip-non-local-url')
860
+
861
+ if pip_local_url:
862
+ extras.append('--pip-local-url')
863
+
864
+ print(f"PIPs restore mode: {extras}")
865
+
866
+ if os.path.exists(snapshot_name):
867
+ snapshot_path = os.path.abspath(snapshot_name)
868
+ else:
869
+ snapshot_path = os.path.join(core.comfyui_manager_path, 'snapshots', snapshot_name)
870
+ if not os.path.exists(snapshot_path):
871
+ print(f"[bold red]ERROR: `{snapshot_path}` is not exists.[/bold red]")
872
+ exit(1)
873
+
874
+ try:
875
+ cloned_repos = []
876
+ checkout_repos = []
877
+ skipped_repos = []
878
+ enabled_repos = []
879
+ disabled_repos = []
880
+ is_failed = False
881
+
882
+ def extract_infos(msg):
883
+ nonlocal is_failed
884
+
885
+ for x in msg:
886
+ if x.startswith("CLONE: "):
887
+ cloned_repos.append(x[7:])
888
+ elif x.startswith("CHECKOUT: "):
889
+ checkout_repos.append(x[10:])
890
+ elif x.startswith("SKIPPED: "):
891
+ skipped_repos.append(x[9:])
892
+ elif x.startswith("ENABLE: "):
893
+ enabled_repos.append(x[8:])
894
+ elif x.startswith("DISABLE: "):
895
+ disabled_repos.append(x[9:])
896
+ elif 'APPLY SNAPSHOT: False' in x:
897
+ is_failed = True
898
+
899
+ print(f"Restore snapshot.")
900
+ cmd_str = [sys.executable, git_script_path, '--apply-snapshot', snapshot_path] + extras
901
+ output = subprocess.check_output(cmd_str, cwd=custom_nodes_path, text=True)
902
+ msg_lines = output.split('\n')
903
+ extract_infos(msg_lines)
904
+
905
+ for url in cloned_repos:
906
+ cm_ctx.post_install(url)
907
+
908
+ # print summary
909
+ for x in cloned_repos:
910
+ print(f"[ INSTALLED ] {x}")
911
+ for x in checkout_repos:
912
+ print(f"[ CHECKOUT ] {x}")
913
+ for x in enabled_repos:
914
+ print(f"[ ENABLED ] {x}")
915
+ for x in disabled_repos:
916
+ print(f"[ DISABLED ] {x}")
917
+
918
+ if is_failed:
919
+ print(output)
920
+ print("[bold red]ERROR: Failed to restore snapshot.[/bold red]")
921
+
922
+ except Exception:
923
+ print("[bold red]ERROR: Failed to restore snapshot.[/bold red]")
924
+ traceback.print_exc()
925
+ raise typer.Exit(code=1)
926
+
927
+
928
+ @app.command(
929
+ "restore-dependencies", help="Restore dependencies from whole installed custom nodes."
930
+ )
931
+ def restore_dependencies():
932
+ node_paths = [os.path.join(custom_nodes_path, name) for name in os.listdir(custom_nodes_path)
933
+ if os.path.isdir(os.path.join(custom_nodes_path, name)) and not name.endswith('.disabled')]
934
+
935
+ total = len(node_paths)
936
+ i = 1
937
+ for x in node_paths:
938
+ print(f"----------------------------------------------------------------------------------------------------")
939
+ print(f"Restoring [{i}/{total}]: {x}")
940
+ cm_ctx.post_install(x)
941
+ i += 1
942
+
943
+
944
+ @app.command(
945
+ "post-install", help="Install dependencies and execute installation script"
946
+ )
947
+ def post_install(
948
+ path: str = typer.Argument(
949
+ help="path to custom node",
950
+ )):
951
+ path = os.path.expanduser(path)
952
+ cm_ctx.post_install(path)
953
+
954
+
955
+ @app.command(
956
+ "install-deps",
957
+ help="Install dependencies from dependencies file(.json) or workflow(.png/.json)",
958
+ )
959
+ def install_deps(
960
+ deps: str = typer.Argument(
961
+ help="Dependency spec file (.json)",
962
+ ),
963
+ channel: Annotated[
964
+ str,
965
+ typer.Option(
966
+ show_default=False,
967
+ help="Specify the operation mode"
968
+ ),
969
+ ] = None,
970
+ mode: str = typer.Option(
971
+ None,
972
+ help="[remote|local|cache]"
973
+ ),
974
+ ):
975
+ cm_ctx.set_channel_mode(channel, mode)
976
+ auto_save_snapshot()
977
+
978
+ if not os.path.exists(deps):
979
+ print(f"[bold red]File not found: {deps}[/bold red]")
980
+ exit(1)
981
+ else:
982
+ with open(deps, 'r', encoding="UTF-8", errors="ignore") as json_file:
983
+ try:
984
+ json_obj = json.load(json_file)
985
+ except:
986
+ print(f"[bold red]Invalid json file: {deps}[/bold red]")
987
+ exit(1)
988
+
989
+ for k in json_obj['custom_nodes'].keys():
990
+ state = core.simple_check_custom_node(k)
991
+ if state == 'installed':
992
+ continue
993
+ elif state == 'not-installed':
994
+ core.gitclone_install([k], instant_execution=True)
995
+ else: # disabled
996
+ core.gitclone_set_active([k], False)
997
+
998
+ print("Dependency installation and activation complete.")
999
+
1000
+
1001
+ @app.command(help="Clear reserved startup action in ComfyUI-Manager")
1002
+ def clear():
1003
+ cancel()
1004
+
1005
+
1006
+ @app.command("export-custom-node-ids", help="Export custom node ids")
1007
+ def export_custom_node_ids(
1008
+ path: str,
1009
+ channel: Annotated[
1010
+ str,
1011
+ typer.Option(
1012
+ show_default=False,
1013
+ help="Specify the operation mode"
1014
+ ),
1015
+ ] = None,
1016
+ mode: str = typer.Option(
1017
+ None,
1018
+ help="[remote|local|cache]"
1019
+ )):
1020
+ cm_ctx.set_channel_mode(channel, mode)
1021
+
1022
+ with open(path, "w", encoding='utf-8') as output_file:
1023
+ for x in cm_ctx.get_custom_node_map().keys():
1024
+ print(x, file=output_file)
1025
+
1026
+
1027
+ if __name__ == '__main__':
1028
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
1029
+ sys.exit(app())
1030
+
1031
+ print(f"")
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,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
126
+
127
+ ### 5. CLI Only Mode
128
+
129
+ You can set whether to use ComfyUI-Manager solely via CLI.
130
+
131
+ `cli-only-mode [enable|disable]`
132
+
133
+ * This mode can be used if you want to restrict the use of ComfyUI-Manager through the GUI for security or policy reasons.
134
+ * 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.
135
+
136
+ ### 6. Dependency Restoration
137
+
138
+ `restore-dependencies`
139
+
140
+ * This command can be used if custom nodes are installed under the `ComfyUI/custom_nodes` path but their dependencies are not installed.
141
+ * It is useful when starting a new cloud instance, like colab, where dependencies need to be reinstalled and installation scripts re-executed.
142
+ * It can also be utilized if ComfyUI is reinstalled and only the custom_nodes path has been backed up and restored.
143
+
144
+ ### 7. Clear
145
+
146
+ 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,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
127
+
128
+ ### 5. CLI only mode
129
+
130
+ ComfyUI-Manager를 CLI로만 사용할 것인지를 설정할 수 있습니다.
131
+
132
+ `cli-only-mode [enable|disable]`
133
+
134
+ * security 혹은 policy 의 이유로 GUI 를 통한 ComfyUI-Manager 사용을 제한하고 싶은 경우 이 모드를 사용할 수 있습니다.
135
+ * CLI only mode를 적용할 경우 ComfyUI-Manager 가 매우 제한된 상태로 로드되어, 내부적으로 제공하는 web API가 비활성화 되며, 메인 메뉴에서도 Manager 버튼이 표시되지 않습니다.
136
+
137
+
138
+ ### 6. 의존성 설치
139
+
140
+ `restore-dependencies`
141
+
142
+ * `ComfyUI/custom_nodes` 하위 경로에 커스텀 노드들이 설치되어 있긴 하지만, 의존성이 설치되지 않은 경우 사용할 수 있습니다.
143
+ * colab 과 같이 cloud instance를 새로 시작하는 경우 의존성 재설치 및 설치 스크립트가 재실행 되어야 하는 경우 사용합니다.
144
+ * ComfyUI을 재설치할 경우, custom_nodes 경로만 백업했다가 재설치 할 경우 활용 가능합니다.
145
+
146
+
147
+ ### 7. clear
148
+
149
+ 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/git_helper.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import sys
3
+ import os
4
+ import traceback
5
+
6
+ import git
7
+ import configparser
8
+ import re
9
+ import json
10
+ import yaml
11
+ import requests
12
+ from tqdm.auto import tqdm
13
+ from git.remote import RemoteProgress
14
+
15
+
16
+ def download_url(url, dest_folder, filename=None):
17
+ # Ensure the destination folder exists
18
+ if not os.path.exists(dest_folder):
19
+ os.makedirs(dest_folder)
20
+
21
+ # Extract filename from URL if not provided
22
+ if filename is None:
23
+ filename = os.path.basename(url)
24
+
25
+ # Full path to save the file
26
+ dest_path = os.path.join(dest_folder, filename)
27
+
28
+ # Download the file
29
+ response = requests.get(url, stream=True)
30
+ if response.status_code == 200:
31
+ with open(dest_path, 'wb') as file:
32
+ for chunk in response.iter_content(chunk_size=1024):
33
+ if chunk:
34
+ file.write(chunk)
35
+ else:
36
+ print(f"Failed to download file from {url}")
37
+
38
+
39
+ config_path = os.path.join(os.path.dirname(__file__), "config.ini")
40
+ nodelist_path = os.path.join(os.path.dirname(__file__), "custom-node-list.json")
41
+ working_directory = os.getcwd()
42
+
43
+ if os.path.basename(working_directory) != 'custom_nodes':
44
+ print(f"WARN: This script should be executed in custom_nodes dir")
45
+ print(f"DBG: INFO {working_directory}")
46
+ print(f"DBG: INFO {sys.argv}")
47
+ # exit(-1)
48
+
49
+
50
+ class GitProgress(RemoteProgress):
51
+ def __init__(self):
52
+ super().__init__()
53
+ self.pbar = tqdm(ascii=True)
54
+
55
+ def update(self, op_code, cur_count, max_count=None, message=''):
56
+ self.pbar.total = max_count
57
+ self.pbar.n = cur_count
58
+ self.pbar.pos = 0
59
+ self.pbar.refresh()
60
+
61
+
62
+ def gitclone(custom_nodes_path, url, target_hash=None):
63
+ repo_name = os.path.splitext(os.path.basename(url))[0]
64
+ repo_path = os.path.join(custom_nodes_path, repo_name)
65
+
66
+ # Clone the repository from the remote URL
67
+ repo = git.Repo.clone_from(url, repo_path, recursive=True, progress=GitProgress())
68
+
69
+ if target_hash is not None:
70
+ print(f"CHECKOUT: {repo_name} [{target_hash}]")
71
+ repo.git.checkout(target_hash)
72
+
73
+ repo.git.clear_cache()
74
+ repo.close()
75
+
76
+
77
+ def gitcheck(path, do_fetch=False):
78
+ try:
79
+ # Fetch the latest commits from the remote repository
80
+ repo = git.Repo(path)
81
+
82
+ if repo.head.is_detached:
83
+ print("CUSTOM NODE CHECK: True")
84
+ return
85
+
86
+ current_branch = repo.active_branch
87
+ branch_name = current_branch.name
88
+
89
+ remote_name = current_branch.tracking_branch().remote_name
90
+ remote = repo.remote(name=remote_name)
91
+
92
+ if do_fetch:
93
+ remote.fetch()
94
+
95
+ # Get the current commit hash and the commit hash of the remote branch
96
+ commit_hash = repo.head.commit.hexsha
97
+ remote_commit_hash = repo.refs[f'{remote_name}/{branch_name}'].object.hexsha
98
+
99
+ # Compare the commit hashes to determine if the local repository is behind the remote repository
100
+ if commit_hash != remote_commit_hash:
101
+ # Get the commit dates
102
+ commit_date = repo.head.commit.committed_datetime
103
+ remote_commit_date = repo.refs[f'{remote_name}/{branch_name}'].object.committed_datetime
104
+
105
+ # Compare the commit dates to determine if the local repository is behind the remote repository
106
+ if commit_date < remote_commit_date:
107
+ print("CUSTOM NODE CHECK: True")
108
+ else:
109
+ print("CUSTOM NODE CHECK: False")
110
+ except Exception as e:
111
+ print(e)
112
+ print("CUSTOM NODE CHECK: Error")
113
+
114
+
115
+ def switch_to_default_branch(repo):
116
+ show_result = repo.git.remote("show", "origin")
117
+ matches = re.search(r"\s*HEAD branch:\s*(.*)", show_result)
118
+ if matches:
119
+ default_branch = matches.group(1)
120
+ repo.git.checkout(default_branch)
121
+
122
+
123
+ def gitpull(path):
124
+ # Check if the path is a git repository
125
+ if not os.path.exists(os.path.join(path, '.git')):
126
+ raise ValueError('Not a git repository')
127
+
128
+ # Pull the latest changes from the remote repository
129
+ repo = git.Repo(path)
130
+ if repo.is_dirty():
131
+ repo.git.stash()
132
+
133
+ commit_hash = repo.head.commit.hexsha
134
+ try:
135
+ if repo.head.is_detached:
136
+ switch_to_default_branch(repo)
137
+
138
+ current_branch = repo.active_branch
139
+ branch_name = current_branch.name
140
+
141
+ remote_name = current_branch.tracking_branch().remote_name
142
+ remote = repo.remote(name=remote_name)
143
+
144
+ remote.fetch()
145
+ remote_commit_hash = repo.refs[f'{remote_name}/{branch_name}'].object.hexsha
146
+
147
+ if commit_hash == remote_commit_hash:
148
+ print("CUSTOM NODE PULL: None") # there is no update
149
+ repo.close()
150
+ return
151
+
152
+ remote.pull()
153
+
154
+ repo.git.submodule('update', '--init', '--recursive')
155
+ new_commit_hash = repo.head.commit.hexsha
156
+
157
+ if commit_hash != new_commit_hash:
158
+ print("CUSTOM NODE PULL: Success") # update success
159
+ else:
160
+ print("CUSTOM NODE PULL: Fail") # update fail
161
+ except Exception as e:
162
+ print(e)
163
+ print("CUSTOM NODE PULL: Fail") # unknown git error
164
+
165
+ repo.close()
166
+
167
+
168
+ def checkout_comfyui_hash(target_hash):
169
+ repo_path = os.path.abspath(os.path.join(working_directory, '..')) # ComfyUI dir
170
+
171
+ repo = git.Repo(repo_path)
172
+ commit_hash = repo.head.commit.hexsha
173
+
174
+ if commit_hash != target_hash:
175
+ try:
176
+ print(f"CHECKOUT: ComfyUI [{target_hash}]")
177
+ repo.git.checkout(target_hash)
178
+ except git.GitCommandError as e:
179
+ print(f"Error checking out the ComfyUI: {str(e)}")
180
+
181
+
182
+ def checkout_custom_node_hash(git_custom_node_infos):
183
+ repo_name_to_url = {}
184
+
185
+ for url in git_custom_node_infos.keys():
186
+ repo_name = url.split('/')[-1]
187
+
188
+ if repo_name.endswith('.git'):
189
+ repo_name = repo_name[:-4]
190
+
191
+ repo_name_to_url[repo_name] = url
192
+
193
+ for path in os.listdir(working_directory):
194
+ if path.endswith("ComfyUI-Manager"):
195
+ continue
196
+
197
+ fullpath = os.path.join(working_directory, path)
198
+
199
+ if os.path.isdir(fullpath):
200
+ is_disabled = path.endswith(".disabled")
201
+
202
+ try:
203
+ git_dir = os.path.join(fullpath, '.git')
204
+ if not os.path.exists(git_dir):
205
+ continue
206
+
207
+ need_checkout = False
208
+ repo_name = os.path.basename(fullpath)
209
+
210
+ if repo_name.endswith('.disabled'):
211
+ repo_name = repo_name[:-9]
212
+
213
+ if repo_name not in repo_name_to_url:
214
+ if not is_disabled:
215
+ # should be disabled
216
+ print(f"DISABLE: {repo_name}")
217
+ new_path = fullpath + ".disabled"
218
+ os.rename(fullpath, new_path)
219
+ need_checkout = False
220
+ else:
221
+ item = git_custom_node_infos[repo_name_to_url[repo_name]]
222
+ if item['disabled'] and is_disabled:
223
+ pass
224
+ elif item['disabled'] and not is_disabled:
225
+ # disable
226
+ print(f"DISABLE: {repo_name}")
227
+ new_path = fullpath + ".disabled"
228
+ os.rename(fullpath, new_path)
229
+
230
+ elif not item['disabled'] and is_disabled:
231
+ # enable
232
+ print(f"ENABLE: {repo_name}")
233
+ new_path = fullpath[:-9]
234
+ os.rename(fullpath, new_path)
235
+ fullpath = new_path
236
+ need_checkout = True
237
+ else:
238
+ need_checkout = True
239
+
240
+ if need_checkout:
241
+ repo = git.Repo(fullpath)
242
+ commit_hash = repo.head.commit.hexsha
243
+
244
+ if commit_hash != item['hash']:
245
+ print(f"CHECKOUT: {repo_name} [{item['hash']}]")
246
+ repo.git.checkout(item['hash'])
247
+
248
+ except Exception:
249
+ print(f"Failed to restore snapshots for the custom node '{path}'")
250
+
251
+ # clone missing
252
+ for k, v in git_custom_node_infos.items():
253
+ if not v['disabled']:
254
+ repo_name = k.split('/')[-1]
255
+ if repo_name.endswith('.git'):
256
+ repo_name = repo_name[:-4]
257
+
258
+ path = os.path.join(working_directory, repo_name)
259
+ if not os.path.exists(path):
260
+ print(f"CLONE: {path}")
261
+ gitclone(working_directory, k, v['hash'])
262
+
263
+
264
+ def invalidate_custom_node_file(file_custom_node_infos):
265
+ global nodelist_path
266
+
267
+ enabled_set = set()
268
+ for item in file_custom_node_infos:
269
+ if not item['disabled']:
270
+ enabled_set.add(item['filename'])
271
+
272
+ for path in os.listdir(working_directory):
273
+ fullpath = os.path.join(working_directory, path)
274
+
275
+ if not os.path.isdir(fullpath) and fullpath.endswith('.py'):
276
+ if path not in enabled_set:
277
+ print(f"DISABLE: {path}")
278
+ new_path = fullpath+'.disabled'
279
+ os.rename(fullpath, new_path)
280
+
281
+ elif not os.path.isdir(fullpath) and fullpath.endswith('.py.disabled'):
282
+ path = path[:-9]
283
+ if path in enabled_set:
284
+ print(f"ENABLE: {path}")
285
+ new_path = fullpath[:-9]
286
+ os.rename(fullpath, new_path)
287
+
288
+ # download missing: just support for 'copy' style
289
+ py_to_url = {}
290
+
291
+ with open(nodelist_path, 'r', encoding="UTF-8") as json_file:
292
+ info = json.load(json_file)
293
+ for item in info['custom_nodes']:
294
+ if item['install_type'] == 'copy':
295
+ for url in item['files']:
296
+ if url.endswith('.py'):
297
+ py = url.split('/')[-1]
298
+ py_to_url[py] = url
299
+
300
+ for item in file_custom_node_infos:
301
+ filename = item['filename']
302
+ if not item['disabled']:
303
+ target_path = os.path.join(working_directory, filename)
304
+
305
+ if not os.path.exists(target_path) and filename in py_to_url:
306
+ url = py_to_url[filename]
307
+ print(f"DOWNLOAD: {filename}")
308
+ download_url(url, working_directory)
309
+
310
+
311
+ def apply_snapshot(target):
312
+ try:
313
+ path = os.path.join(os.path.dirname(__file__), 'snapshots', f"{target}")
314
+ if os.path.exists(path):
315
+ if not target.endswith('.json') and not target.endswith('.yaml'):
316
+ print(f"Snapshot file not found: `{path}`")
317
+ print("APPLY SNAPSHOT: False")
318
+ return None
319
+
320
+ with open(path, 'r', encoding="UTF-8") as snapshot_file:
321
+ if target.endswith('.json'):
322
+ info = json.load(snapshot_file)
323
+ elif target.endswith('.yaml'):
324
+ info = yaml.load(snapshot_file, Loader=yaml.SafeLoader)
325
+ info = info['custom_nodes']
326
+ else:
327
+ # impossible case
328
+ print("APPLY SNAPSHOT: False")
329
+ return None
330
+
331
+ comfyui_hash = info['comfyui']
332
+ git_custom_node_infos = info['git_custom_nodes']
333
+ file_custom_node_infos = info['file_custom_nodes']
334
+
335
+ checkout_comfyui_hash(comfyui_hash)
336
+ checkout_custom_node_hash(git_custom_node_infos)
337
+ invalidate_custom_node_file(file_custom_node_infos)
338
+
339
+ print("APPLY SNAPSHOT: True")
340
+ if 'pips' in info:
341
+ return info['pips']
342
+ else:
343
+ return None
344
+
345
+ print(f"Snapshot file not found: `{path}`")
346
+ print("APPLY SNAPSHOT: False")
347
+
348
+ return None
349
+ except Exception as e:
350
+ print(e)
351
+ traceback.print_exc()
352
+ print("APPLY SNAPSHOT: False")
353
+
354
+ return None
355
+
356
+
357
+ def restore_pip_snapshot(pips, options):
358
+ non_url = []
359
+ local_url = []
360
+ non_local_url = []
361
+ for k, v in pips.items():
362
+ if v == "":
363
+ non_url.append(k)
364
+ else:
365
+ if v.startswith('file:'):
366
+ local_url.append(v)
367
+ else:
368
+ non_local_url.append(v)
369
+
370
+ failed = []
371
+ if '--pip-non-url' in options:
372
+ # try all at once
373
+ res = 1
374
+ try:
375
+ res = subprocess.check_call([sys.executable, '-m', 'pip', 'install'] + non_url)
376
+ except:
377
+ pass
378
+
379
+ # fallback
380
+ if res != 0:
381
+ for x in non_url:
382
+ res = 1
383
+ try:
384
+ res = subprocess.check_call([sys.executable, '-m', 'pip', 'install', x])
385
+ except:
386
+ pass
387
+
388
+ if res != 0:
389
+ failed.append(x)
390
+
391
+ if '--pip-non-local-url' in options:
392
+ for x in non_local_url:
393
+ res = 1
394
+ try:
395
+ res = subprocess.check_call([sys.executable, '-m', 'pip', 'install', x])
396
+ except:
397
+ pass
398
+
399
+ if res != 0:
400
+ failed.append(x)
401
+
402
+ if '--pip-local-url' in options:
403
+ for x in local_url:
404
+ res = 1
405
+ try:
406
+ res = subprocess.check_call([sys.executable, '-m', 'pip', 'install', x])
407
+ except:
408
+ pass
409
+
410
+ if res != 0:
411
+ failed.append(x)
412
+
413
+ print(f"Installation failed for pip packages: {failed}")
414
+
415
+
416
+ def setup_environment():
417
+ config = configparser.ConfigParser()
418
+ config.read(config_path)
419
+ if 'default' in config and 'git_exe' in config['default'] and config['default']['git_exe'] != '':
420
+ git.Git().update_environment(GIT_PYTHON_GIT_EXECUTABLE=config['default']['git_exe'])
421
+
422
+
423
+ setup_environment()
424
+
425
+
426
+ try:
427
+ if sys.argv[1] == "--clone":
428
+ gitclone(sys.argv[2], sys.argv[3])
429
+ elif sys.argv[1] == "--check":
430
+ gitcheck(sys.argv[2], False)
431
+ elif sys.argv[1] == "--fetch":
432
+ gitcheck(sys.argv[2], True)
433
+ elif sys.argv[1] == "--pull":
434
+ gitpull(sys.argv[2])
435
+ elif sys.argv[1] == "--apply-snapshot":
436
+ options = set()
437
+ for x in sys.argv:
438
+ if x in ['--pip-non-url', '--pip-local-url', '--pip-non-local-url']:
439
+ options.add(x)
440
+
441
+ pips = apply_snapshot(sys.argv[2])
442
+
443
+ if pips and len(options) > 0:
444
+ restore_pip_snapshot(pips, options)
445
+ sys.exit(0)
446
+ except Exception as e:
447
+ print(e)
448
+ sys.exit(-1)
449
+
450
+
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,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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))
ComfyUI/custom_nodes/ComfyUI-Manager/glob/manager_core.py ADDED
@@ -0,0 +1,1313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import subprocess
4
+ import re
5
+ import shutil
6
+ import configparser
7
+ import platform
8
+ from datetime import datetime
9
+ import git
10
+ from git.remote import RemoteProgress
11
+ from urllib.parse import urlparse
12
+ from tqdm.auto import tqdm
13
+ import aiohttp
14
+ import threading
15
+ import json
16
+ import time
17
+ import yaml
18
+ import zipfile
19
+
20
+ glob_path = os.path.join(os.path.dirname(__file__)) # ComfyUI-Manager/glob
21
+ sys.path.append(glob_path)
22
+
23
+ import cm_global
24
+ from manager_util import *
25
+
26
+ version = [2, 55, 4]
27
+ version_str = f"V{version[0]}.{version[1]}" + (f'.{version[2]}' if len(version) > 2 else '')
28
+
29
+
30
+ comfyui_manager_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
31
+ custom_nodes_path = os.path.abspath(os.path.join(comfyui_manager_path, '..'))
32
+
33
+ default_custom_nodes_path = None
34
+
35
+ def get_default_custom_nodes_path():
36
+ global default_custom_nodes_path
37
+ if default_custom_nodes_path is None:
38
+ try:
39
+ import folder_paths
40
+ default_custom_nodes_path = folder_paths.get_folder_paths("custom_nodes")[0]
41
+ except:
42
+ default_custom_nodes_path = custom_nodes_path
43
+
44
+ return default_custom_nodes_path
45
+
46
+
47
+ def get_custom_nodes_paths():
48
+ try:
49
+ import folder_paths
50
+ return folder_paths.get_folder_paths("custom_nodes")
51
+ except:
52
+ return [custom_nodes_path]
53
+
54
+
55
+ def get_comfyui_tag():
56
+ repo = git.Repo(comfy_path)
57
+ try:
58
+ return repo.git.describe('--tags')
59
+ except:
60
+ return None
61
+
62
+
63
+ comfy_path = os.environ.get('COMFYUI_PATH')
64
+ if comfy_path is None:
65
+ try:
66
+ import folder_paths
67
+ comfy_path = os.path.join(os.path.dirname(folder_paths.__file__))
68
+ except:
69
+ comfy_path = os.path.abspath(os.path.join(custom_nodes_path, '..'))
70
+
71
+ channel_list_path = os.path.join(comfyui_manager_path, 'channels.list')
72
+ config_path = os.path.join(comfyui_manager_path, "config.ini")
73
+ startup_script_path = os.path.join(comfyui_manager_path, "startup-scripts")
74
+ git_script_path = os.path.join(comfyui_manager_path, "git_helper.py")
75
+ cache_dir = os.path.join(comfyui_manager_path, '.cache')
76
+ cached_config = None
77
+ js_path = None
78
+
79
+ comfy_ui_required_revision = 1930
80
+ comfy_ui_required_commit_datetime = datetime(2024, 1, 24, 0, 0, 0)
81
+
82
+ comfy_ui_revision = "Unknown"
83
+ comfy_ui_commit_datetime = datetime(1900, 1, 1, 0, 0, 0)
84
+
85
+
86
+ cache_lock = threading.Lock()
87
+
88
+
89
+ channel_dict = None
90
+ channel_list = None
91
+ pip_map = None
92
+
93
+
94
+ def remap_pip_package(pkg):
95
+ if pkg in cm_global.pip_overrides:
96
+ res = cm_global.pip_overrides[pkg]
97
+ print(f"[ComfyUI-Manager] '{pkg}' is remapped to '{res}'")
98
+ return res
99
+ else:
100
+ return pkg
101
+
102
+
103
+ def get_installed_packages():
104
+ global pip_map
105
+
106
+ if pip_map is None:
107
+ try:
108
+ result = subprocess.check_output([sys.executable, '-m', 'pip', 'list'], universal_newlines=True)
109
+
110
+ pip_map = {}
111
+ for line in result.split('\n'):
112
+ x = line.strip()
113
+ if x:
114
+ y = line.split()
115
+ if y[0] == 'Package' or y[0].startswith('-'):
116
+ continue
117
+
118
+ pip_map[y[0]] = y[1]
119
+ except subprocess.CalledProcessError as e:
120
+ print(f"[ComfyUI-Manager] Failed to retrieve the information of installed pip packages.")
121
+ return set()
122
+
123
+ return pip_map
124
+
125
+
126
+ def clear_pip_cache():
127
+ global pip_map
128
+ pip_map = None
129
+
130
+
131
+ def is_blacklisted(name):
132
+ name = name.strip()
133
+
134
+ pattern = r'([^<>!=]+)([<>!=]=?)([^ ]*)'
135
+ match = re.search(pattern, name)
136
+
137
+ if match:
138
+ name = match.group(1)
139
+
140
+ if name in cm_global.pip_blacklist:
141
+ return True
142
+
143
+ if name in cm_global.pip_downgrade_blacklist:
144
+ pips = get_installed_packages()
145
+
146
+ if match is None:
147
+ if name in pips:
148
+ return True
149
+ elif match.group(2) in ['<=', '==', '<']:
150
+ if name in pips:
151
+ if StrictVersion(pips[name]) >= StrictVersion(match.group(3)):
152
+ return True
153
+
154
+ return False
155
+
156
+
157
+ def is_installed(name):
158
+ name = name.strip()
159
+
160
+ if name.startswith('#'):
161
+ return True
162
+
163
+ pattern = r'([^<>!=]+)([<>!=]=?)([0-9.a-zA-Z]*)'
164
+ match = re.search(pattern, name)
165
+
166
+ if match:
167
+ name = match.group(1)
168
+
169
+ if name in cm_global.pip_blacklist:
170
+ return True
171
+
172
+ if name in cm_global.pip_downgrade_blacklist:
173
+ pips = get_installed_packages()
174
+
175
+ if match is None:
176
+ if name in pips:
177
+ return True
178
+ elif match.group(2) in ['<=', '==', '<']:
179
+ if name in pips:
180
+ if StrictVersion(pips[name]) >= StrictVersion(match.group(3)):
181
+ print(f"[ComfyUI-Manager] skip black listed pip installation: '{name}'")
182
+ return True
183
+
184
+ return name.lower() in get_installed_packages()
185
+
186
+
187
+ def get_channel_dict():
188
+ global channel_dict
189
+
190
+ if channel_dict is None:
191
+ channel_dict = {}
192
+
193
+ if not os.path.exists(channel_list_path):
194
+ shutil.copy(channel_list_path+'.template', channel_list_path)
195
+
196
+ with open(os.path.join(comfyui_manager_path, 'channels.list'), 'r') as file:
197
+ channels = file.read()
198
+ for x in channels.split('\n'):
199
+ channel_info = x.split("::")
200
+ if len(channel_info) == 2:
201
+ channel_dict[channel_info[0]] = channel_info[1]
202
+
203
+ return channel_dict
204
+
205
+
206
+ def get_channel_list():
207
+ global channel_list
208
+
209
+ if channel_list is None:
210
+ channel_list = []
211
+ for k, v in get_channel_dict().items():
212
+ channel_list.append(f"{k}::{v}")
213
+
214
+ return channel_list
215
+
216
+
217
+ class ManagerFuncs:
218
+ def __init__(self):
219
+ pass
220
+
221
+ def get_current_preview_method(self):
222
+ return "none"
223
+
224
+ def run_script(self, cmd, cwd='.'):
225
+ if len(cmd) > 0 and cmd[0].startswith("#"):
226
+ print(f"[ComfyUI-Manager] Unexpected behavior: `{cmd}`")
227
+ return 0
228
+
229
+ new_env = os.environ.copy()
230
+ new_env["COMFYUI_PATH"] = comfy_path
231
+ subprocess.check_call(cmd, cwd=cwd, env=new_env)
232
+
233
+ return 0
234
+
235
+
236
+ manager_funcs = ManagerFuncs()
237
+
238
+
239
+ def write_config():
240
+ config = configparser.ConfigParser()
241
+ config['default'] = {
242
+ 'preview_method': manager_funcs.get_current_preview_method(),
243
+ 'badge_mode': get_config()['badge_mode'],
244
+ 'git_exe': get_config()['git_exe'],
245
+ 'channel_url': get_config()['channel_url'],
246
+ 'share_option': get_config()['share_option'],
247
+ 'bypass_ssl': get_config()['bypass_ssl'],
248
+ "file_logging": get_config()['file_logging'],
249
+ 'default_ui': get_config()['default_ui'],
250
+ 'component_policy': get_config()['component_policy'],
251
+ 'double_click_policy': get_config()['double_click_policy'],
252
+ 'windows_selector_event_loop_policy': get_config()['windows_selector_event_loop_policy'],
253
+ 'model_download_by_agent': get_config()['model_download_by_agent'],
254
+ 'downgrade_blacklist': get_config()['downgrade_blacklist'],
255
+ 'security_level': get_config()['security_level'],
256
+ }
257
+ with open(config_path, 'w') as configfile:
258
+ config.write(configfile)
259
+
260
+
261
+ def read_config():
262
+ try:
263
+ config = configparser.ConfigParser()
264
+ config.read(config_path)
265
+ default_conf = config['default']
266
+
267
+ # policy migration: disable_unsecure_features -> security_level
268
+ if 'disable_unsecure_features' in default_conf:
269
+ if default_conf['disable_unsecure_features'].lower() == 'true':
270
+ security_level = 'strong'
271
+ else:
272
+ security_level = 'normal'
273
+ else:
274
+ security_level = default_conf['security_level'] if 'security_level' in default_conf else 'normal'
275
+
276
+ return {
277
+ 'preview_method': default_conf['preview_method'] if 'preview_method' in default_conf else manager_funcs.get_current_preview_method(),
278
+ 'badge_mode': default_conf['badge_mode'] if 'badge_mode' in default_conf else 'none',
279
+ 'git_exe': default_conf['git_exe'] if 'git_exe' in default_conf else '',
280
+ 'channel_url': default_conf['channel_url'] if 'channel_url' in default_conf else 'https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main',
281
+ 'share_option': default_conf['share_option'] if 'share_option' in default_conf else 'all',
282
+ 'bypass_ssl': default_conf['bypass_ssl'].lower() == 'true' if 'bypass_ssl' in default_conf else False,
283
+ 'file_logging': default_conf['file_logging'].lower() == 'true' if 'file_logging' in default_conf else True,
284
+ 'default_ui': default_conf['default_ui'] if 'default_ui' in default_conf else 'none',
285
+ 'component_policy': default_conf['component_policy'] if 'component_policy' in default_conf else 'workflow',
286
+ 'double_click_policy': default_conf['double_click_policy'] if 'double_click_policy' in default_conf else 'copy-all',
287
+ 'windows_selector_event_loop_policy': default_conf['windows_selector_event_loop_policy'].lower() == 'true' if 'windows_selector_event_loop_policy' in default_conf else False,
288
+ 'model_download_by_agent': default_conf['model_download_by_agent'].lower() == 'true' if 'model_download_by_agent' in default_conf else False,
289
+ 'downgrade_blacklist': default_conf['downgrade_blacklist'] if 'downgrade_blacklist' in default_conf else '',
290
+ 'security_level': security_level
291
+ }
292
+
293
+ except Exception:
294
+ return {
295
+ 'preview_method': manager_funcs.get_current_preview_method(),
296
+ 'badge_mode': 'none',
297
+ 'git_exe': '',
298
+ 'channel_url': 'https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main',
299
+ 'share_option': 'all',
300
+ 'bypass_ssl': False,
301
+ 'file_logging': True,
302
+ 'default_ui': 'none',
303
+ 'component_policy': 'workflow',
304
+ 'double_click_policy': 'copy-all',
305
+ 'windows_selector_event_loop_policy': False,
306
+ 'model_download_by_agent': False,
307
+ 'downgrade_blacklist': '',
308
+ 'security_level': 'normal',
309
+ }
310
+
311
+
312
+ def get_config():
313
+ global cached_config
314
+
315
+ if cached_config is None:
316
+ cached_config = read_config()
317
+
318
+ return cached_config
319
+
320
+
321
+ def switch_to_default_branch(repo):
322
+ show_result = repo.git.remote("show", "origin")
323
+ matches = re.search(r"\s*HEAD branch:\s*(.*)", show_result)
324
+ if matches:
325
+ default_branch = matches.group(1)
326
+ repo.git.checkout(default_branch)
327
+
328
+
329
+ def try_install_script(url, repo_path, install_cmd, instant_execution=False):
330
+ if not instant_execution and ((len(install_cmd) > 0 and install_cmd[0].startswith('#')) or (platform.system() == "Windows" and comfy_ui_commit_datetime.date() >= comfy_ui_required_commit_datetime.date())):
331
+ if not os.path.exists(startup_script_path):
332
+ os.makedirs(startup_script_path)
333
+
334
+ script_path = os.path.join(startup_script_path, "install-scripts.txt")
335
+ with open(script_path, "a") as file:
336
+ obj = [repo_path] + install_cmd
337
+ file.write(f"{obj}\n")
338
+
339
+ return True
340
+ else:
341
+ if len(install_cmd) == 5 and install_cmd[2:4] == ['pip', 'install']:
342
+ if is_blacklisted(install_cmd[4]):
343
+ print(f"[ComfyUI-Manager] skip black listed pip installation: '{install_cmd[4]}'")
344
+ return True
345
+
346
+ print(f"\n## ComfyUI-Manager: EXECUTE => {install_cmd}")
347
+ code = manager_funcs.run_script(install_cmd, cwd=repo_path)
348
+
349
+ if platform.system() != "Windows":
350
+ try:
351
+ if comfy_ui_commit_datetime.date() < comfy_ui_required_commit_datetime.date():
352
+ print("\n\n###################################################################")
353
+ print(f"[WARN] ComfyUI-Manager: Your ComfyUI version ({comfy_ui_revision})[{comfy_ui_commit_datetime.date()}] is too old. Please update to the latest version.")
354
+ print(f"[WARN] The extension installation feature may not work properly in the current installed ComfyUI version on Windows environment.")
355
+ print("###################################################################\n\n")
356
+ except:
357
+ pass
358
+
359
+ if code != 0:
360
+ if url is None:
361
+ url = os.path.dirname(repo_path)
362
+ print(f"install script failed: {url}")
363
+ return False
364
+
365
+
366
+ # use subprocess to avoid file system lock by git (Windows)
367
+ def __win_check_git_update(path, do_fetch=False, do_update=False):
368
+ if do_fetch:
369
+ command = [sys.executable, git_script_path, "--fetch", path]
370
+ elif do_update:
371
+ command = [sys.executable, git_script_path, "--pull", path]
372
+ else:
373
+ command = [sys.executable, git_script_path, "--check", path]
374
+
375
+ new_env = os.environ.copy()
376
+ new_env["COMFYUI_PATH"] = comfy_path
377
+ process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=get_default_custom_nodes_path())
378
+ output, _ = process.communicate()
379
+ output = output.decode('utf-8').strip()
380
+
381
+ if 'detected dubious' in output:
382
+ # fix and try again
383
+ safedir_path = path.replace('\\', '/')
384
+ try:
385
+ print(f"[ComfyUI-Manager] Try fixing 'dubious repository' error on '{safedir_path}' repo")
386
+ process = subprocess.Popen(['git', 'config', '--global', '--add', 'safe.directory', safedir_path], env=new_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
387
+ output, _ = process.communicate()
388
+
389
+ process = subprocess.Popen(command, env=new_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
390
+ output, _ = process.communicate()
391
+ output = output.decode('utf-8').strip()
392
+ except Exception:
393
+ print(f'[ComfyUI-Manager] failed to fixing')
394
+
395
+ if 'detected dubious' in output:
396
+ print(f'\n[ComfyUI-Manager] Failed to fixing repository setup. Please execute this command on cmd: \n'
397
+ f'-----------------------------------------------------------------------------------------\n'
398
+ f'git config --global --add safe.directory "{safedir_path}"\n'
399
+ f'-----------------------------------------------------------------------------------------\n')
400
+
401
+ if do_update:
402
+ if "CUSTOM NODE PULL: Success" in output:
403
+ process.wait()
404
+ print(f"\x1b[2K\rUpdated: {path}")
405
+ return True, True # updated
406
+ elif "CUSTOM NODE PULL: None" in output:
407
+ process.wait()
408
+ return False, True # there is no update
409
+ else:
410
+ print(f"\x1b[2K\rUpdate error: {path}")
411
+ process.wait()
412
+ return False, False # update failed
413
+ else:
414
+ if "CUSTOM NODE CHECK: True" in output:
415
+ process.wait()
416
+ return True, True
417
+ elif "CUSTOM NODE CHECK: False" in output:
418
+ process.wait()
419
+ return False, True
420
+ else:
421
+ print(f"\x1b[2K\rFetch error: {path}")
422
+ print(f"\n{output}\n")
423
+ process.wait()
424
+ return False, True
425
+
426
+
427
+ def __win_check_git_pull(path):
428
+ new_env = os.environ.copy()
429
+ new_env["COMFYUI_PATH"] = comfy_path
430
+ command = [sys.executable, git_script_path, "--pull", path]
431
+ process = subprocess.Popen(command, env=new_env, cwd=get_default_custom_nodes_path())
432
+ process.wait()
433
+
434
+
435
+ def execute_install_script(url, repo_path, lazy_mode=False, instant_execution=False):
436
+ install_script_path = os.path.join(repo_path, "install.py")
437
+ requirements_path = os.path.join(repo_path, "requirements.txt")
438
+
439
+ if lazy_mode:
440
+ install_cmd = ["#LAZY-INSTALL-SCRIPT", sys.executable]
441
+ try_install_script(url, repo_path, install_cmd)
442
+ else:
443
+ if os.path.exists(requirements_path):
444
+ print("Install: pip packages")
445
+ pip_fixer = PIPFixer(get_installed_packages())
446
+ with open(requirements_path, "r") as requirements_file:
447
+ for line in requirements_file:
448
+ #handle comments
449
+ if '#' in line:
450
+ if line.strip()[0] == '#':
451
+ print("Line is comment...skipping")
452
+ continue
453
+ else:
454
+ line = line.split('#')[0].strip()
455
+
456
+ package_name = remap_pip_package(line.strip())
457
+
458
+ if package_name and not package_name.startswith('#'):
459
+ if '--index-url' in package_name:
460
+ s = package_name.split('--index-url')
461
+ install_cmd = [sys.executable, "-m", "pip", "install", s[0].strip(), '--index-url', s[1].strip()]
462
+ else:
463
+ install_cmd = [sys.executable, "-m", "pip", "install", package_name]
464
+
465
+ if package_name.strip() != "" and not package_name.startswith('#'):
466
+ try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
467
+
468
+ pip_fixer.fix_broken()
469
+
470
+ if os.path.exists(install_script_path):
471
+ print(f"Install: install script")
472
+ install_cmd = [sys.executable, "install.py"]
473
+ try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
474
+
475
+ return True
476
+
477
+
478
+ def git_repo_has_updates(path, do_fetch=False, do_update=False):
479
+ if do_fetch:
480
+ print(f"\x1b[2K\rFetching: {path}", end='')
481
+ elif do_update:
482
+ print(f"\x1b[2K\rUpdating: {path}", end='')
483
+
484
+ # Check if the path is a git repository
485
+ if not os.path.exists(os.path.join(path, '.git')):
486
+ raise ValueError('Not a git repository')
487
+
488
+ if platform.system() == "Windows":
489
+ updated, success = __win_check_git_update(path, do_fetch, do_update)
490
+ if updated and success:
491
+ execute_install_script(None, path, lazy_mode=True)
492
+ return updated, success
493
+ else:
494
+ # Fetch the latest commits from the remote repository
495
+ repo = git.Repo(path)
496
+
497
+ current_branch = repo.active_branch
498
+ branch_name = current_branch.name
499
+
500
+ remote_name = 'origin'
501
+ remote = repo.remote(name=remote_name)
502
+
503
+ # Get the current commit hash
504
+ commit_hash = repo.head.commit.hexsha
505
+
506
+ if do_fetch or do_update:
507
+ remote.fetch()
508
+
509
+ if do_update:
510
+ if repo.head.is_detached:
511
+ switch_to_default_branch(repo)
512
+
513
+ remote_commit_hash = repo.refs[f'{remote_name}/{branch_name}'].object.hexsha
514
+
515
+ if commit_hash == remote_commit_hash:
516
+ repo.close()
517
+ return False, True
518
+
519
+ try:
520
+ remote.pull()
521
+ repo.git.submodule('update', '--init', '--recursive')
522
+ new_commit_hash = repo.head.commit.hexsha
523
+
524
+ if commit_hash != new_commit_hash:
525
+ execute_install_script(None, path)
526
+ print(f"\x1b[2K\rUpdated: {path}")
527
+ return True, True
528
+ else:
529
+ return False, False
530
+
531
+ except Exception as e:
532
+ print(f"\nUpdating failed: {path}\n{e}", file=sys.stderr)
533
+ return False, False
534
+
535
+ if repo.head.is_detached:
536
+ repo.close()
537
+ return True, True
538
+
539
+ # Get commit hash of the remote branch
540
+ current_branch = repo.active_branch
541
+ branch_name = current_branch.name
542
+
543
+ remote_commit_hash = repo.refs[f'{remote_name}/{branch_name}'].object.hexsha
544
+
545
+ # Compare the commit hashes to determine if the local repository is behind the remote repository
546
+ if commit_hash != remote_commit_hash:
547
+ # Get the commit dates
548
+ commit_date = repo.head.commit.committed_datetime
549
+ remote_commit_date = repo.refs[f'{remote_name}/{branch_name}'].object.committed_datetime
550
+
551
+ # Compare the commit dates to determine if the local repository is behind the remote repository
552
+ if commit_date < remote_commit_date:
553
+ repo.close()
554
+ return True, True
555
+
556
+ repo.close()
557
+
558
+ return False, True
559
+
560
+
561
+ class GitProgress(RemoteProgress):
562
+ def __init__(self):
563
+ super().__init__()
564
+ self.pbar = tqdm()
565
+
566
+ def update(self, op_code, cur_count, max_count=None, message=''):
567
+ self.pbar.total = max_count
568
+ self.pbar.n = cur_count
569
+ self.pbar.pos = 0
570
+ self.pbar.refresh()
571
+
572
+
573
+ def is_valid_url(url):
574
+ try:
575
+ # Check for HTTP/HTTPS URL format
576
+ result = urlparse(url)
577
+ if all([result.scheme, result.netloc]):
578
+ return True
579
+ finally:
580
+ # Check for SSH git URL format
581
+ pattern = re.compile(r"^(.+@|ssh:\/\/).+:.+$")
582
+ if pattern.match(url):
583
+ return True
584
+ return False
585
+
586
+
587
+ def gitclone_install(files, instant_execution=False, msg_prefix=''):
588
+ print(f"{msg_prefix}Install: {files}")
589
+ for url in files:
590
+ if not is_valid_url(url):
591
+ print(f"Invalid git url: '{url}'")
592
+ return False
593
+
594
+ if url.endswith("/"):
595
+ url = url[:-1]
596
+ try:
597
+ print(f"Download: git clone '{url}'")
598
+ repo_name = os.path.splitext(os.path.basename(url))[0]
599
+ repo_path = os.path.join(get_default_custom_nodes_path(), repo_name)
600
+
601
+ # Clone the repository from the remote URL
602
+ if not instant_execution and platform.system() == 'Windows':
603
+ res = manager_funcs.run_script([sys.executable, git_script_path, "--clone", get_default_custom_nodes_path(), url], cwd=get_default_custom_nodes_path())
604
+ if res != 0:
605
+ return False
606
+ else:
607
+ repo = git.Repo.clone_from(url, repo_path, recursive=True, progress=GitProgress())
608
+ repo.git.clear_cache()
609
+ repo.close()
610
+
611
+ if not execute_install_script(url, repo_path, instant_execution=instant_execution):
612
+ return False
613
+
614
+ except Exception as e:
615
+ print(f"Install(git-clone) error: {url} / {e}", file=sys.stderr)
616
+ return False
617
+
618
+ print("Installation was successful.")
619
+ return True
620
+
621
+
622
+ def git_pull(path):
623
+ # Check if the path is a git repository
624
+ if not os.path.exists(os.path.join(path, '.git')):
625
+ raise ValueError('Not a git repository')
626
+
627
+ # Pull the latest changes from the remote repository
628
+ if platform.system() == "Windows":
629
+ return __win_check_git_pull(path)
630
+ else:
631
+ repo = git.Repo(path)
632
+
633
+ if repo.is_dirty():
634
+ repo.git.stash()
635
+
636
+ if repo.head.is_detached:
637
+ switch_to_default_branch(repo)
638
+
639
+ current_branch = repo.active_branch
640
+ remote_name = current_branch.tracking_branch().remote_name
641
+ remote = repo.remote(name=remote_name)
642
+
643
+ remote.pull()
644
+ repo.git.submodule('update', '--init', '--recursive')
645
+
646
+ repo.close()
647
+
648
+ return True
649
+
650
+
651
+ async def get_data(uri, silent=False):
652
+ if not silent:
653
+ print(f"FETCH DATA from: {uri}", end="")
654
+
655
+ if uri.startswith("http"):
656
+ async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
657
+ async with session.get(uri) as resp:
658
+ json_text = await resp.text()
659
+ else:
660
+ with cache_lock:
661
+ with open(uri, "r", encoding="utf-8") as f:
662
+ json_text = f.read()
663
+
664
+ json_obj = json.loads(json_text)
665
+ if not silent:
666
+ print(f" [DONE]")
667
+ return json_obj
668
+
669
+
670
+ def simple_hash(input_string):
671
+ hash_value = 0
672
+ for char in input_string:
673
+ hash_value = (hash_value * 31 + ord(char)) % (2**32)
674
+
675
+ return hash_value
676
+
677
+
678
+ def is_file_created_within_one_day(file_path):
679
+ if not os.path.exists(file_path):
680
+ return False
681
+
682
+ file_creation_time = os.path.getctime(file_path)
683
+ current_time = datetime.now().timestamp()
684
+ time_difference = current_time - file_creation_time
685
+
686
+ return time_difference <= 86400
687
+
688
+
689
+ async def get_data_by_mode(mode, filename, channel_url=None):
690
+ if channel_url in get_channel_dict():
691
+ channel_url = get_channel_dict()[channel_url]
692
+
693
+ try:
694
+ if mode == "local":
695
+ uri = os.path.join(comfyui_manager_path, filename)
696
+ json_obj = await get_data(uri)
697
+ else:
698
+ if channel_url is None:
699
+ uri = get_config()['channel_url'] + '/' + filename
700
+ else:
701
+ uri = channel_url + '/' + filename
702
+
703
+ cache_uri = str(simple_hash(uri))+'_'+filename
704
+ cache_uri = os.path.join(cache_dir, cache_uri)
705
+
706
+ if mode == "cache":
707
+ if is_file_created_within_one_day(cache_uri):
708
+ json_obj = await get_data(cache_uri)
709
+ else:
710
+ json_obj = await get_data(uri)
711
+ with cache_lock:
712
+ with open(cache_uri, "w", encoding='utf-8') as file:
713
+ json.dump(json_obj, file, indent=4, sort_keys=True)
714
+ else:
715
+ json_obj = await get_data(uri)
716
+ with cache_lock:
717
+ with open(cache_uri, "w", encoding='utf-8') as file:
718
+ json.dump(json_obj, file, indent=4, sort_keys=True)
719
+ except Exception as e:
720
+ print(f"[ComfyUI-Manager] Due to a network error, switching to local mode.\n=> {filename}\n=> {e}")
721
+ uri = os.path.join(comfyui_manager_path, filename)
722
+ json_obj = await get_data(uri)
723
+
724
+ return json_obj
725
+
726
+
727
+ def lookup_installed_custom_nodes(repo_name):
728
+ try:
729
+ import folder_paths
730
+ base_paths = folder_paths.get_folder_paths("custom_nodes")
731
+ except:
732
+ base_paths = [custom_nodes_path]
733
+
734
+ for base_path in base_paths:
735
+ repo_path = os.path.join(base_path, repo_name)
736
+ if os.path.exists(repo_path):
737
+ return True, repo_path
738
+ elif os.path.exists(repo_path+'.disabled'):
739
+ return False, repo_path
740
+
741
+ return None
742
+
743
+ def gitclone_fix(files, instant_execution=False):
744
+ print(f"Try fixing: {files}")
745
+ for url in files:
746
+ if not is_valid_url(url):
747
+ print(f"Invalid git url: '{url}'")
748
+ return False
749
+
750
+ if url.endswith("/"):
751
+ url = url[:-1]
752
+ try:
753
+ repo_name = os.path.splitext(os.path.basename(url))[0]
754
+ repo_path = lookup_installed_custom_nodes(repo_name)
755
+
756
+ if repo_path is not None:
757
+ repo_path = repo_path[1]
758
+
759
+ if not execute_install_script(url, repo_path, instant_execution=instant_execution):
760
+ return False
761
+ else:
762
+ print(f"Custom node not found: {repo_name}")
763
+
764
+ except Exception as e:
765
+ print(f"Install(git-clone) error: {url} / {e}", file=sys.stderr)
766
+ return False
767
+
768
+ print(f"Attempt to fixing '{files}' is done.")
769
+ return True
770
+
771
+
772
+ def pip_install(packages):
773
+ install_cmd = ['#FORCE', sys.executable, "-m", "pip", "install", '-U'] + packages
774
+ try_install_script('pip install via manager', '..', install_cmd)
775
+
776
+
777
+ def rmtree(path):
778
+ retry_count = 3
779
+
780
+ while True:
781
+ try:
782
+ retry_count -= 1
783
+
784
+ if platform.system() == "Windows":
785
+ manager_funcs.run_script(['attrib', '-R', path + '\\*', '/S'])
786
+ shutil.rmtree(path)
787
+
788
+ return True
789
+
790
+ except Exception as ex:
791
+ print(f"ex: {ex}")
792
+ time.sleep(3)
793
+
794
+ if retry_count < 0:
795
+ raise ex
796
+
797
+ print(f"Uninstall retry({retry_count})")
798
+
799
+
800
+ def gitclone_uninstall(files):
801
+ import os
802
+
803
+ print(f"Uninstall: {files}")
804
+ for url in files:
805
+ if url.endswith("/"):
806
+ url = url[:-1]
807
+ try:
808
+ dir_name = os.path.splitext(os.path.basename(url))[0].replace(".git", "")
809
+ repo_path = lookup_installed_custom_nodes(dir_name)
810
+
811
+ if repo_path is None:
812
+ continue
813
+
814
+ dir_path = repo_path[1]
815
+
816
+ install_script_path = os.path.join(dir_path, "uninstall.py")
817
+ disable_script_path = os.path.join(dir_path, "disable.py")
818
+ if os.path.exists(install_script_path):
819
+ uninstall_cmd = [sys.executable, "uninstall.py"]
820
+ code = manager_funcs.run_script(uninstall_cmd, cwd=dir_path)
821
+
822
+ if code != 0:
823
+ print(f"An error occurred during the execution of the uninstall.py script. Only the '{dir_path}' will be deleted.")
824
+ elif os.path.exists(disable_script_path):
825
+ disable_script = [sys.executable, "disable.py"]
826
+ code = manager_funcs.run_script(disable_script, cwd=dir_path)
827
+ if code != 0:
828
+ print(f"An error occurred during the execution of the disable.py script. Only the '{dir_path}' will be deleted.")
829
+
830
+ rmtree(dir_path)
831
+ except Exception as e:
832
+ print(f"Uninstall(git-clone) error: {url} / {e}", file=sys.stderr)
833
+ return False
834
+
835
+ print("Uninstallation was successful.")
836
+ return True
837
+
838
+
839
+ def gitclone_set_active(files, is_disable):
840
+ import os
841
+
842
+ if is_disable:
843
+ action_name = "Disable"
844
+ else:
845
+ action_name = "Enable"
846
+
847
+ print(f"{action_name}: {files}")
848
+ for url in files:
849
+ if url.endswith("/"):
850
+ url = url[:-1]
851
+ try:
852
+ dir_name = os.path.splitext(os.path.basename(url))[0].replace(".git", "")
853
+ repo_path = lookup_installed_custom_nodes(dir_name)
854
+
855
+ if repo_path is None:
856
+ continue
857
+
858
+ dir_path = repo_path[1]
859
+
860
+ if is_disable:
861
+ current_path = dir_path
862
+ new_path = dir_path + ".disabled"
863
+ else:
864
+ current_path = dir_path + ".disabled"
865
+ new_path = dir_path
866
+
867
+ os.rename(current_path, new_path)
868
+
869
+ if is_disable:
870
+ if os.path.exists(os.path.join(new_path, "disable.py")):
871
+ disable_script = [sys.executable, "disable.py"]
872
+ try_install_script(url, new_path, disable_script)
873
+ else:
874
+ if os.path.exists(os.path.join(new_path, "enable.py")):
875
+ enable_script = [sys.executable, "enable.py"]
876
+ try_install_script(url, new_path, enable_script)
877
+
878
+ except Exception as e:
879
+ print(f"{action_name}(git-clone) error: {url} / {e}", file=sys.stderr)
880
+ return False
881
+
882
+ print(f"{action_name} was successful.")
883
+ return True
884
+
885
+
886
+ def gitclone_update(files, instant_execution=False, skip_script=False, msg_prefix=""):
887
+ import os
888
+
889
+ print(f"{msg_prefix}Update: {files}")
890
+ for url in files:
891
+ if url.endswith("/"):
892
+ url = url[:-1]
893
+ try:
894
+ repo_name = os.path.splitext(os.path.basename(url))[0].replace(".git", "")
895
+ repo_path = lookup_installed_custom_nodes(repo_name)
896
+
897
+ if repo_path is None:
898
+ continue
899
+
900
+ repo_path = repo_path[1]
901
+
902
+ git_pull(repo_path)
903
+
904
+ if not skip_script:
905
+ if instant_execution:
906
+ if not execute_install_script(url, repo_path, lazy_mode=False, instant_execution=True):
907
+ return False
908
+ else:
909
+ if not execute_install_script(url, repo_path, lazy_mode=True):
910
+ return False
911
+
912
+ except Exception as e:
913
+ print(f"Update(git-clone) error: {url} / {e}", file=sys.stderr)
914
+ return False
915
+
916
+ if not skip_script:
917
+ print("Update was successful.")
918
+ return True
919
+
920
+
921
+ def update_path(repo_path, instant_execution=False):
922
+ if not os.path.exists(os.path.join(repo_path, '.git')):
923
+ return "fail"
924
+
925
+ # version check
926
+ repo = git.Repo(repo_path)
927
+
928
+ if repo.head.is_detached:
929
+ switch_to_default_branch(repo)
930
+
931
+ current_branch = repo.active_branch
932
+ branch_name = current_branch.name
933
+
934
+ if current_branch.tracking_branch() is None:
935
+ print(f"[ComfyUI-Manager] There is no tracking branch ({current_branch})")
936
+ remote_name = 'origin'
937
+ else:
938
+ remote_name = current_branch.tracking_branch().remote_name
939
+ remote = repo.remote(name=remote_name)
940
+
941
+ try:
942
+ remote.fetch()
943
+ except Exception as e:
944
+ if 'detected dubious' in str(e):
945
+ print(f"[ComfyUI-Manager] Try fixing 'dubious repository' error on 'ComfyUI' repository")
946
+ safedir_path = comfy_path.replace('\\', '/')
947
+ subprocess.run(['git', 'config', '--global', '--add', 'safe.directory', safedir_path])
948
+ try:
949
+ remote.fetch()
950
+ except Exception:
951
+ print(f"\n[ComfyUI-Manager] Failed to fixing repository setup. Please execute this command on cmd: \n"
952
+ f"-----------------------------------------------------------------------------------------\n"
953
+ f'git config --global --add safe.directory "{safedir_path}"\n'
954
+ f"-----------------------------------------------------------------------------------------\n")
955
+
956
+ commit_hash = repo.head.commit.hexsha
957
+ remote_commit_hash = repo.refs[f'{remote_name}/{branch_name}'].object.hexsha
958
+
959
+ if commit_hash != remote_commit_hash:
960
+ git_pull(repo_path)
961
+ execute_install_script("ComfyUI", repo_path, instant_execution=instant_execution)
962
+ return "updated"
963
+ else:
964
+ return "skipped"
965
+
966
+
967
+ def lookup_customnode_by_url(data, target):
968
+ for x in data['custom_nodes']:
969
+ if target in x['files']:
970
+ dir_name = os.path.splitext(os.path.basename(target))[0].replace(".git", "")
971
+ repo_path = lookup_installed_custom_nodes(dir_name)
972
+
973
+ if repo_path is None:
974
+ continue
975
+
976
+ if repo_path[0]:
977
+ x['installed'] = 'True'
978
+ else:
979
+ x['installed'] = 'Disabled'
980
+ return x
981
+
982
+ return None
983
+
984
+
985
+ def simple_check_custom_node(url):
986
+ dir_name = os.path.splitext(os.path.basename(url))[0].replace(".git", "")
987
+ repo_path = lookup_installed_custom_nodes(dir_name)
988
+
989
+ if repo_path is None:
990
+ return 'not-installed'
991
+
992
+ if repo_path[0]:
993
+ return 'installed'
994
+ else:
995
+ return 'disabled'
996
+
997
+
998
+ def check_a_custom_node_installed(item, do_fetch=False, do_update_check=True, do_update=False):
999
+ item['installed'] = 'None'
1000
+
1001
+ if item['install_type'] == 'git-clone' and len(item['files']) == 1:
1002
+ url = item['files'][0]
1003
+
1004
+ if url.endswith("/"):
1005
+ url = url[:-1]
1006
+
1007
+ dir_name = os.path.splitext(os.path.basename(url))[0].replace(".git", "")
1008
+ repo_path = lookup_installed_custom_nodes(dir_name)
1009
+
1010
+ if repo_path is None:
1011
+ item['installed'] = 'False'
1012
+ elif repo_path[0]:
1013
+ dir_path = repo_path[1]
1014
+ try:
1015
+ item['installed'] = 'True' # default
1016
+
1017
+ if cm_global.try_call(api="cm.is_import_failed_extension", name=dir_name):
1018
+ item['installed'] = 'Fail'
1019
+
1020
+ if do_update_check:
1021
+ update_state, success = git_repo_has_updates(dir_path, do_fetch, do_update)
1022
+ if (do_update_check or do_update) and update_state:
1023
+ item['installed'] = 'Update'
1024
+ elif do_update and not success:
1025
+ item['installed'] = 'Fail'
1026
+ except:
1027
+ if cm_global.try_call(api="cm.is_import_failed_extension", name=dir_name):
1028
+ item['installed'] = 'Fail'
1029
+ else:
1030
+ item['installed'] = 'True'
1031
+
1032
+ else:
1033
+ item['installed'] = 'Disabled'
1034
+
1035
+ elif item['install_type'] == 'copy' and len(item['files']) == 1:
1036
+ dir_name = os.path.basename(item['files'][0])
1037
+
1038
+ if item['files'][0].endswith('.py'):
1039
+ base_path = lookup_installed_custom_nodes(item['files'][0])
1040
+ if base_path is None:
1041
+ item['installed'] = 'False'
1042
+ return
1043
+ elif base_path[0]:
1044
+ item['installed'] = 'True'
1045
+ else:
1046
+ item['installed'] = 'Disabled'
1047
+
1048
+ return
1049
+ elif 'js_path' in item:
1050
+ base_path = os.path.join(js_path, item['js_path'])
1051
+ else:
1052
+ base_path = js_path
1053
+
1054
+ file_path = os.path.join(base_path, dir_name)
1055
+ if os.path.exists(file_path):
1056
+ if cm_global.try_call(api="cm.is_import_failed_extension", name=dir_name):
1057
+ item['installed'] = 'Fail'
1058
+ else:
1059
+ item['installed'] = 'True'
1060
+ else:
1061
+ item['installed'] = 'False'
1062
+
1063
+
1064
+ def get_installed_pip_packages():
1065
+ # extract pip package infos
1066
+ pips = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'], text=True).split('\n')
1067
+
1068
+ res = {}
1069
+ for x in pips:
1070
+ if x.strip() == "":
1071
+ continue
1072
+
1073
+ if ' @ ' in x:
1074
+ spec_url = x.split(' @ ')
1075
+ res[spec_url[0]] = spec_url[1]
1076
+ else:
1077
+ res[x] = ""
1078
+
1079
+ return res
1080
+
1081
+
1082
+ def get_current_snapshot():
1083
+ # Get ComfyUI hash
1084
+ repo_path = comfy_path
1085
+
1086
+ if not os.path.exists(os.path.join(repo_path, '.git')):
1087
+ print(f"ComfyUI update fail: The installed ComfyUI does not have a Git repository.")
1088
+ return {}
1089
+
1090
+ repo = git.Repo(repo_path)
1091
+ comfyui_commit_hash = repo.head.commit.hexsha
1092
+
1093
+ git_custom_nodes = {}
1094
+ file_custom_nodes = []
1095
+
1096
+ try:
1097
+ import folder_paths
1098
+ base_paths = folder_paths.get_folder_paths("custom_nodes")
1099
+ except:
1100
+ base_paths = [custom_nodes_path]
1101
+
1102
+ # Get custom nodes hash
1103
+ for base_path in base_paths:
1104
+ for path in os.listdir(base_path):
1105
+ fullpath = os.path.join(base_path, path)
1106
+
1107
+ if os.path.isdir(fullpath):
1108
+ is_disabled = path.endswith(".disabled")
1109
+
1110
+ try:
1111
+ git_dir = os.path.join(fullpath, '.git')
1112
+
1113
+ if not os.path.exists(git_dir):
1114
+ continue
1115
+
1116
+ repo = git.Repo(fullpath)
1117
+ commit_hash = repo.head.commit.hexsha
1118
+ url = repo.remotes.origin.url
1119
+ git_custom_nodes[url] = {
1120
+ 'hash': commit_hash,
1121
+ 'disabled': is_disabled
1122
+ }
1123
+
1124
+ except:
1125
+ print(f"Failed to extract snapshots for the custom node '{path}'.")
1126
+
1127
+ elif path.endswith('.py'):
1128
+ is_disabled = path.endswith(".py.disabled")
1129
+ filename = os.path.basename(path)
1130
+ item = {
1131
+ 'filename': filename,
1132
+ 'disabled': is_disabled
1133
+ }
1134
+
1135
+ file_custom_nodes.append(item)
1136
+
1137
+ pip_packages = get_installed_pip_packages()
1138
+
1139
+ return {
1140
+ 'comfyui': comfyui_commit_hash,
1141
+ 'git_custom_nodes': git_custom_nodes,
1142
+ 'file_custom_nodes': file_custom_nodes,
1143
+ 'pips': pip_packages,
1144
+ }
1145
+
1146
+
1147
+ def save_snapshot_with_postfix(postfix, path=None):
1148
+ if path is None:
1149
+ now = datetime.now()
1150
+
1151
+ date_time_format = now.strftime("%Y-%m-%d_%H-%M-%S")
1152
+ file_name = f"{date_time_format}_{postfix}"
1153
+
1154
+ path = os.path.join(comfyui_manager_path, 'snapshots', f"{file_name}.json")
1155
+ else:
1156
+ file_name = path.replace('\\', '/').split('/')[-1]
1157
+ file_name = file_name.split('.')[-2]
1158
+
1159
+ snapshot = get_current_snapshot()
1160
+ if path.endswith('.json'):
1161
+ with open(path, "w") as json_file:
1162
+ json.dump(snapshot, json_file, indent=4)
1163
+
1164
+ return file_name + '.json'
1165
+
1166
+ elif path.endswith('.yaml'):
1167
+ with open(path, "w") as yaml_file:
1168
+ snapshot = {'custom_nodes': snapshot}
1169
+ yaml.dump(snapshot, yaml_file, allow_unicode=True)
1170
+
1171
+ return path
1172
+
1173
+
1174
+ async def extract_nodes_from_workflow(filepath, mode='local', channel_url='default'):
1175
+ # prepare json data
1176
+ workflow = None
1177
+ if filepath.endswith('.json'):
1178
+ with open(filepath, "r", encoding="UTF-8", errors="ignore") as json_file:
1179
+ try:
1180
+ workflow = json.load(json_file)
1181
+ except:
1182
+ print(f"Invalid workflow file: {filepath}")
1183
+ exit(-1)
1184
+
1185
+ elif filepath.endswith('.png'):
1186
+ from PIL import Image
1187
+ with Image.open(filepath) as img:
1188
+ if 'workflow' not in img.info:
1189
+ print(f"The specified .png file doesn't have a workflow: {filepath}")
1190
+ exit(-1)
1191
+ else:
1192
+ try:
1193
+ workflow = json.loads(img.info['workflow'])
1194
+ except:
1195
+ print(f"This is not a valid .png file containing a ComfyUI workflow: {filepath}")
1196
+ exit(-1)
1197
+
1198
+ if workflow is None:
1199
+ print(f"Invalid workflow file: {filepath}")
1200
+ exit(-1)
1201
+
1202
+ # extract nodes
1203
+ used_nodes = set()
1204
+
1205
+ def extract_nodes(sub_workflow):
1206
+ for x in sub_workflow['nodes']:
1207
+ node_name = x.get('type')
1208
+
1209
+ # skip virtual nodes
1210
+ if node_name in ['Reroute', 'Note']:
1211
+ continue
1212
+
1213
+ if node_name is not None and not (node_name.startswith('workflow/') or node_name.startswith('workflow>')):
1214
+ used_nodes.add(node_name)
1215
+
1216
+ if 'nodes' in workflow:
1217
+ extract_nodes(workflow)
1218
+
1219
+ if 'extra' in workflow:
1220
+ if 'groupNodes' in workflow['extra']:
1221
+ for x in workflow['extra']['groupNodes'].values():
1222
+ extract_nodes(x)
1223
+
1224
+ # lookup dependent custom nodes
1225
+ ext_map = await get_data_by_mode(mode, 'extension-node-map.json', channel_url)
1226
+
1227
+ rext_map = {}
1228
+ preemption_map = {}
1229
+ patterns = []
1230
+ for k, v in ext_map.items():
1231
+ if k == 'https://github.com/comfyanonymous/ComfyUI':
1232
+ for x in v[0]:
1233
+ if x not in preemption_map:
1234
+ preemption_map[x] = []
1235
+
1236
+ preemption_map[x] = k
1237
+ continue
1238
+
1239
+ for x in v[0]:
1240
+ if x not in rext_map:
1241
+ rext_map[x] = []
1242
+
1243
+ rext_map[x].append(k)
1244
+
1245
+ if 'preemptions' in v[1]:
1246
+ for x in v[1]['preemptions']:
1247
+ if x not in preemption_map:
1248
+ preemption_map[x] = []
1249
+
1250
+ preemption_map[x] = k
1251
+
1252
+ if 'nodename_pattern' in v[1]:
1253
+ patterns.append((v[1]['nodename_pattern'], k))
1254
+
1255
+ # identify used extensions
1256
+ used_exts = set()
1257
+ unknown_nodes = set()
1258
+
1259
+ for node_name in used_nodes:
1260
+ ext = preemption_map.get(node_name)
1261
+
1262
+ if ext is None:
1263
+ ext = rext_map.get(node_name)
1264
+ if ext is not None:
1265
+ ext = ext[0]
1266
+
1267
+ if ext is None:
1268
+ for pat_ext in patterns:
1269
+ if re.search(pat_ext[0], node_name):
1270
+ ext = pat_ext[1]
1271
+ break
1272
+
1273
+ if ext == 'https://github.com/comfyanonymous/ComfyUI':
1274
+ pass
1275
+ elif ext is not None:
1276
+ if 'Fooocus' in ext:
1277
+ print(f">> {node_name}")
1278
+
1279
+ used_exts.add(ext)
1280
+ else:
1281
+ unknown_nodes.add(node_name)
1282
+
1283
+ return used_exts, unknown_nodes
1284
+
1285
+
1286
+ def unzip(model_path):
1287
+ if not os.path.exists(model_path):
1288
+ print(f"[ComfyUI-Manager] unzip: File not found: {model_path}")
1289
+ return False
1290
+
1291
+ base_dir = os.path.dirname(model_path)
1292
+ filename = os.path.basename(model_path)
1293
+ target_dir = os.path.join(base_dir, filename[:-4])
1294
+
1295
+ os.makedirs(target_dir, exist_ok=True)
1296
+
1297
+ with zipfile.ZipFile(model_path, 'r') as zip_ref:
1298
+ zip_ref.extractall(target_dir)
1299
+
1300
+ # Check if there's only one directory inside the target directory
1301
+ contents = os.listdir(target_dir)
1302
+ if len(contents) == 1 and os.path.isdir(os.path.join(target_dir, contents[0])):
1303
+ nested_dir = os.path.join(target_dir, contents[0])
1304
+ # Move each file and sub-directory in the nested directory up to the target directory
1305
+ for item in os.listdir(nested_dir):
1306
+ shutil.move(os.path.join(nested_dir, item), os.path.join(target_dir, item))
1307
+ # Remove the now empty nested directory
1308
+ os.rmdir(nested_dir)
1309
+
1310
+ os.remove(model_path)
1311
+ return True
1312
+
1313
+
ComfyUI/custom_nodes/ComfyUI-Manager/glob/manager_downloader.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from urllib.parse import urlparse
3
+
4
+ aria2 = os.getenv('COMFYUI_MANAGER_ARIA2_SERVER')
5
+ HF_ENDPOINT = os.getenv('HF_ENDPOINT')
6
+
7
+ if aria2 is not None:
8
+ secret = os.getenv('COMFYUI_MANAGER_ARIA2_SECRET')
9
+ url = urlparse(aria2)
10
+ port = url.port
11
+ host = url.scheme + '://' + url.hostname
12
+ import aria2p
13
+
14
+ aria2 = aria2p.API(aria2p.Client(host=host, port=port, secret=secret))
15
+
16
+
17
+ def download_url(model_url: str, model_dir: str, filename: str):
18
+ if aria2:
19
+ return aria2_download_url(model_url, model_dir, filename)
20
+ else:
21
+ from torchvision.datasets.utils import download_url as torchvision_download_url
22
+
23
+ return torchvision_download_url(model_url, model_dir, filename)
24
+
25
+
26
+ def aria2_find_task(dir: str, filename: str):
27
+ target = os.path.join(dir, filename)
28
+
29
+ downloads = aria2.get_downloads()
30
+
31
+ for download in downloads:
32
+ for file in download.files:
33
+ if file.is_metadata:
34
+ continue
35
+ if str(file.path) == target:
36
+ return download
37
+
38
+
39
+ def aria2_download_url(model_url: str, model_dir: str, filename: str):
40
+ import manager_core as core
41
+ import tqdm
42
+ import time
43
+
44
+ if model_dir.startswith(core.comfy_path):
45
+ model_dir = model_dir[len(core.comfy_path) :]
46
+
47
+ if HF_ENDPOINT:
48
+ model_url = model_url.replace('https://huggingface.co', HF_ENDPOINT)
49
+
50
+ download_dir = model_dir if model_dir.startswith('/') else os.path.join('/models', model_dir)
51
+
52
+ download = aria2_find_task(download_dir, filename)
53
+ if download is None:
54
+ options = {'dir': download_dir, 'out': filename}
55
+ download = aria2.add(model_url, options)[0]
56
+
57
+ if download.is_active:
58
+ with tqdm.tqdm(
59
+ total=download.total_length,
60
+ bar_format='{l_bar}{bar}{r_bar}',
61
+ desc=filename,
62
+ unit='B',
63
+ unit_scale=True,
64
+ ) as progress_bar:
65
+ while download.is_active:
66
+ if progress_bar.total == 0 and download.total_length != 0:
67
+ progress_bar.reset(download.total_length)
68
+ progress_bar.update(download.completed_length - progress_bar.n)
69
+ time.sleep(1)
70
+ download.update()
ComfyUI/custom_nodes/ComfyUI-Manager/glob/manager_server.py ADDED
@@ -0,0 +1,1392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ from server import PromptServer
16
+ import manager_core as core
17
+ import cm_global
18
+
19
+ print(f"### Loading: ComfyUI-Manager ({core.version_str})")
20
+
21
+ comfy_ui_hash = "-"
22
+
23
+ SECURITY_MESSAGE_MIDDLE_OR_BELOW = f"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"
24
+ SECURITY_MESSAGE_NORMAL_MINUS = f"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"
25
+ SECURITY_MESSAGE_GENERAL = f"ERROR: This installation is not allowed in this security_level. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
26
+
27
+ def handle_stream(stream, prefix):
28
+ stream.reconfigure(encoding=locale.getpreferredencoding(), errors='replace')
29
+ for msg in stream:
30
+ if prefix == '[!]' and ('it/s]' in msg or 's/it]' in msg) and ('%|' in msg or 'it [' in msg):
31
+ if msg.startswith('100%'):
32
+ print('\r' + msg, end="", file=sys.stderr),
33
+ else:
34
+ print('\r' + msg[:-1], end="", file=sys.stderr),
35
+ else:
36
+ if prefix == '[!]':
37
+ print(prefix, msg, end="", file=sys.stderr)
38
+ else:
39
+ print(prefix, msg, end="")
40
+
41
+
42
+ from comfy.cli_args import args
43
+ import latent_preview
44
+
45
+
46
+ is_local_mode = args.listen.startswith('127.') or args.listen.startswith('local.')
47
+
48
+
49
+ def is_allowed_security_level(level):
50
+ if level == 'block':
51
+ return False
52
+ elif level == 'high':
53
+ if is_local_mode:
54
+ return core.get_config()['security_level'].lower() in ['weak', 'normal-']
55
+ else:
56
+ return core.get_config()['security_level'].lower() == 'weak'
57
+ elif level == 'middle':
58
+ return core.get_config()['security_level'].lower() in ['weak', 'normal', 'normal-']
59
+ else:
60
+ return True
61
+
62
+
63
+ async def get_risky_level(files, pip_packages):
64
+ json_data1 = await core.get_data_by_mode('local', 'custom-node-list.json')
65
+ json_data2 = await core.get_data_by_mode('cache', 'custom-node-list.json', channel_url='https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main')
66
+
67
+ all_urls = set()
68
+ for x in json_data1['custom_nodes'] + json_data2['custom_nodes']:
69
+ all_urls.update(x['files'])
70
+
71
+ for x in files:
72
+ if x not in all_urls:
73
+ return "high"
74
+
75
+ all_pip_packages = set()
76
+ for x in json_data1['custom_nodes'] + json_data2['custom_nodes']:
77
+ if "pip" in x:
78
+ all_pip_packages.update(x['pip'])
79
+
80
+ for p in pip_packages:
81
+ if p not in all_pip_packages:
82
+ return "block"
83
+
84
+ return "middle"
85
+
86
+
87
+ class ManagerFuncsInComfyUI(core.ManagerFuncs):
88
+ def get_current_preview_method(self):
89
+ if args.preview_method == latent_preview.LatentPreviewMethod.Auto:
90
+ return "auto"
91
+ elif args.preview_method == latent_preview.LatentPreviewMethod.Latent2RGB:
92
+ return "latent2rgb"
93
+ elif args.preview_method == latent_preview.LatentPreviewMethod.TAESD:
94
+ return "taesd"
95
+ else:
96
+ return "none"
97
+
98
+ def run_script(self, cmd, cwd='.'):
99
+ if len(cmd) > 0 and cmd[0].startswith("#"):
100
+ print(f"[ComfyUI-Manager] Unexpected behavior: `{cmd}`")
101
+ return 0
102
+
103
+ process = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1)
104
+
105
+ stdout_thread = threading.Thread(target=handle_stream, args=(process.stdout, ""))
106
+ stderr_thread = threading.Thread(target=handle_stream, args=(process.stderr, "[!]"))
107
+
108
+ stdout_thread.start()
109
+ stderr_thread.start()
110
+
111
+ stdout_thread.join()
112
+ stderr_thread.join()
113
+
114
+ return process.wait()
115
+
116
+
117
+ core.manager_funcs = ManagerFuncsInComfyUI()
118
+
119
+ sys.path.append('../..')
120
+
121
+ from manager_downloader import download_url
122
+
123
+ core.comfy_path = os.path.dirname(folder_paths.__file__)
124
+ core.js_path = os.path.join(core.comfy_path, "web", "extensions")
125
+
126
+ local_db_model = os.path.join(core.comfyui_manager_path, "model-list.json")
127
+ local_db_alter = os.path.join(core.comfyui_manager_path, "alter-list.json")
128
+ local_db_custom_node_list = os.path.join(core.comfyui_manager_path, "custom-node-list.json")
129
+ local_db_extension_node_mappings = os.path.join(core.comfyui_manager_path, "extension-node-map.json")
130
+ components_path = os.path.join(core.comfyui_manager_path, 'components')
131
+
132
+
133
+ def set_preview_method(method):
134
+ if method == 'auto':
135
+ args.preview_method = latent_preview.LatentPreviewMethod.Auto
136
+ elif method == 'latent2rgb':
137
+ args.preview_method = latent_preview.LatentPreviewMethod.Latent2RGB
138
+ elif method == 'taesd':
139
+ args.preview_method = latent_preview.LatentPreviewMethod.TAESD
140
+ else:
141
+ args.preview_method = latent_preview.LatentPreviewMethod.NoPreviews
142
+
143
+ core.get_config()['preview_method'] = args.preview_method
144
+
145
+
146
+ set_preview_method(core.get_config()['preview_method'])
147
+
148
+
149
+ def set_badge_mode(mode):
150
+ core.get_config()['badge_mode'] = mode
151
+
152
+
153
+ def set_default_ui_mode(mode):
154
+ core.get_config()['default_ui'] = mode
155
+
156
+
157
+ def set_component_policy(mode):
158
+ core.get_config()['component_policy'] = mode
159
+
160
+
161
+ def set_double_click_policy(mode):
162
+ core.get_config()['double_click_policy'] = mode
163
+
164
+
165
+ def print_comfyui_version():
166
+ global comfy_ui_hash
167
+
168
+ is_detached = False
169
+ try:
170
+ repo = git.Repo(os.path.dirname(folder_paths.__file__))
171
+ core.comfy_ui_revision = len(list(repo.iter_commits('HEAD')))
172
+
173
+ comfy_ui_hash = repo.head.commit.hexsha
174
+ cm_global.variables['comfyui.revision'] = core.comfy_ui_revision
175
+
176
+ core.comfy_ui_commit_datetime = repo.head.commit.committed_datetime
177
+ cm_global.variables['comfyui.commit_datetime'] = core.comfy_ui_commit_datetime
178
+
179
+ is_detached = repo.head.is_detached
180
+ current_branch = repo.active_branch.name
181
+
182
+ try:
183
+ if core.comfy_ui_commit_datetime.date() < core.comfy_ui_required_commit_datetime.date():
184
+ print(f"\n\n## [WARN] ComfyUI-Manager: Your ComfyUI version ({core.get_comfyui_tag()})[{core.comfy_ui_commit_datetime.date()}] is too old. Please update to the latest version. ##\n\n")
185
+ except:
186
+ pass
187
+
188
+ # process on_revision_detected -->
189
+ if 'cm.on_revision_detected_handler' in cm_global.variables:
190
+ for k, f in cm_global.variables['cm.on_revision_detected_handler']:
191
+ try:
192
+ f(core.comfy_ui_revision)
193
+ except Exception:
194
+ print(f"[ERROR] '{k}' on_revision_detected_handler")
195
+ traceback.print_exc()
196
+
197
+ del cm_global.variables['cm.on_revision_detected_handler']
198
+ else:
199
+ print(f"[ComfyUI-Manager] Some features are restricted due to your ComfyUI being outdated.")
200
+ # <--
201
+
202
+ if current_branch == "master":
203
+ version_tag = core.get_comfyui_tag()
204
+ if version_tag is None:
205
+ print(f"### ComfyUI Revision: {core.comfy_ui_revision} [{comfy_ui_hash[:8]}] | Released on '{core.comfy_ui_commit_datetime.date()}'")
206
+ else:
207
+ print(f"### ComfyUI Version: {core.get_comfyui_tag()} | Released on '{core.comfy_ui_commit_datetime.date()}'")
208
+ else:
209
+ print(f"### ComfyUI Revision: {core.comfy_ui_revision} on '{current_branch}' [{comfy_ui_hash[:8]}] | Released on '{core.comfy_ui_commit_datetime.date()}'")
210
+ except:
211
+ if is_detached:
212
+ print(f"### ComfyUI Revision: {core.comfy_ui_revision} [{comfy_ui_hash[:8]}] *DETACHED | Released on '{core.comfy_ui_commit_datetime.date()}'")
213
+ else:
214
+ print("### ComfyUI Revision: UNKNOWN (The currently installed ComfyUI is not a Git repository)")
215
+
216
+
217
+ print_comfyui_version()
218
+
219
+
220
+ async def populate_github_stats(json_obj, json_obj_github):
221
+ if 'custom_nodes' in json_obj:
222
+ for i, node in enumerate(json_obj['custom_nodes']):
223
+ url = node['reference']
224
+ if url in json_obj_github:
225
+ json_obj['custom_nodes'][i]['stars'] = json_obj_github[url]['stars']
226
+ json_obj['custom_nodes'][i]['last_update'] = json_obj_github[url]['last_update']
227
+ json_obj['custom_nodes'][i]['trust'] = json_obj_github[url]['author_account_age_days'] > 180
228
+ else:
229
+ json_obj['custom_nodes'][i]['stars'] = -1
230
+ json_obj['custom_nodes'][i]['last_update'] = -1
231
+ json_obj['custom_nodes'][i]['trust'] = False
232
+ return json_obj
233
+
234
+
235
+ def setup_environment():
236
+ git_exe = core.get_config()['git_exe']
237
+
238
+ if git_exe != '':
239
+ git.Git().update_environment(GIT_PYTHON_GIT_EXECUTABLE=git_exe)
240
+
241
+
242
+ setup_environment()
243
+
244
+ # Expand Server api
245
+
246
+ import server
247
+ from aiohttp import web
248
+ import aiohttp
249
+ import json
250
+ import zipfile
251
+ import urllib.request
252
+
253
+
254
+ def get_model_dir(data):
255
+ if 'download_model_base' in folder_paths.folder_names_and_paths:
256
+ models_base = folder_paths.folder_names_and_paths['download_model_base'][0][0]
257
+ else:
258
+ models_base = folder_paths.models_dir
259
+
260
+ def resolve_custom_node(save_path):
261
+ save_path = save_path[13:] # remove 'custom_nodes/'
262
+ repo_name = save_path.replace('\\','/').split('/')[0] # get custom node repo name
263
+ repo_path = core.lookup_installed_custom_nodes(repo_name)
264
+ if repo_path is not None and repo_path[0]:
265
+ # Returns the retargeted path based on the actually installed repository
266
+ return os.path.join(os.path.dirname(repo_path[1]), save_path)
267
+ else:
268
+ return None
269
+
270
+ if data['save_path'] != 'default':
271
+ if '..' in data['save_path'] or data['save_path'].startswith('/'):
272
+ print(f"[WARN] '{data['save_path']}' is not allowed path. So it will be saved into 'models/etc'.")
273
+ base_model = os.path.join(models_base, "etc")
274
+ else:
275
+ if data['save_path'].startswith("custom_nodes"):
276
+ base_model = resolve_custom_node(data['save_path'])
277
+ if base_model is None:
278
+ print(f"[ComfyUI-Manager] The target custom node for model download is not installed: {data['save_path']}")
279
+ return None
280
+ else:
281
+ base_model = os.path.join(models_base, data['save_path'])
282
+ else:
283
+ model_type = data['type']
284
+ if model_type == "checkpoints" or model_type == "checkpoint":
285
+ base_model = folder_paths.folder_names_and_paths["checkpoints"][0][0]
286
+ elif model_type == "unclip":
287
+ base_model = folder_paths.folder_names_and_paths["checkpoints"][0][0]
288
+ elif model_type == "clip" or model_type == "text_encoders":
289
+ if folder_paths.folder_names_and_paths.get("text_encoders"):
290
+ base_model = folder_paths.folder_names_and_paths["text_encoders"][0][0]
291
+ else:
292
+ print(f"[ComfyUI-Manager] Your ComfyUI is outdated version.")
293
+ base_model = folder_paths.folder_names_and_paths["clip"][0][0] # outdated version
294
+ elif model_type == "VAE":
295
+ base_model = folder_paths.folder_names_and_paths["vae"][0][0]
296
+ elif model_type == "lora":
297
+ base_model = folder_paths.folder_names_and_paths["loras"][0][0]
298
+ elif model_type == "T2I-Adapter":
299
+ base_model = folder_paths.folder_names_and_paths["controlnet"][0][0]
300
+ elif model_type == "T2I-Style":
301
+ base_model = folder_paths.folder_names_and_paths["controlnet"][0][0]
302
+ elif model_type == "controlnet":
303
+ base_model = folder_paths.folder_names_and_paths["controlnet"][0][0]
304
+ elif model_type == "clip_vision":
305
+ base_model = folder_paths.folder_names_and_paths["clip_vision"][0][0]
306
+ elif model_type == "gligen":
307
+ base_model = folder_paths.folder_names_and_paths["gligen"][0][0]
308
+ elif model_type == "upscale":
309
+ base_model = folder_paths.folder_names_and_paths["upscale_models"][0][0]
310
+ elif model_type == "embeddings":
311
+ base_model = folder_paths.folder_names_and_paths["embeddings"][0][0]
312
+ elif model_type == "unet" or model_type == "diffusion_model":
313
+ if folder_paths.folder_names_and_paths.get("diffusion_models"):
314
+ base_model = folder_paths.folder_names_and_paths["diffusion_models"][0][1]
315
+ else:
316
+ print(f"[ComfyUI-Manager] Your ComfyUI is outdated version.")
317
+ base_model = folder_paths.folder_names_and_paths["unet"][0][0] # outdated version
318
+ else:
319
+ base_model = os.path.join(models_base, "etc")
320
+
321
+ return base_model
322
+
323
+
324
+ def get_model_path(data):
325
+ base_model = get_model_dir(data)
326
+ if base_model is None:
327
+ return None
328
+ else:
329
+ return os.path.join(base_model, data['filename'])
330
+
331
+
332
+ def check_custom_nodes_installed(json_obj, do_fetch=False, do_update_check=True, do_update=False):
333
+ if do_fetch:
334
+ print("Start fetching...", end="")
335
+ elif do_update:
336
+ print("Start updating...", end="")
337
+ elif do_update_check:
338
+ print("Start update check...", end="")
339
+
340
+ def process_custom_node(item):
341
+ core.check_a_custom_node_installed(item, do_fetch, do_update_check, do_update)
342
+
343
+ with concurrent.futures.ThreadPoolExecutor(4) as executor:
344
+ for item in json_obj['custom_nodes']:
345
+ executor.submit(process_custom_node, item)
346
+
347
+ if do_fetch:
348
+ print(f"\x1b[2K\rFetching done.")
349
+ elif do_update:
350
+ update_exists = any(item['installed'] == 'Update' for item in json_obj['custom_nodes'])
351
+ if update_exists:
352
+ print(f"\x1b[2K\rUpdate done.")
353
+ else:
354
+ print(f"\x1b[2K\rAll extensions are already up-to-date.")
355
+ elif do_update_check:
356
+ print(f"\x1b[2K\rUpdate check done.")
357
+
358
+
359
+ def nickname_filter(json_obj):
360
+ preemptions_map = {}
361
+
362
+ for k, x in json_obj.items():
363
+ if 'preemptions' in x[1]:
364
+ for y in x[1]['preemptions']:
365
+ preemptions_map[y] = k
366
+ elif k.endswith("/ComfyUI"):
367
+ for y in x[0]:
368
+ preemptions_map[y] = k
369
+
370
+ updates = {}
371
+ for k, x in json_obj.items():
372
+ removes = set()
373
+ for y in x[0]:
374
+ k2 = preemptions_map.get(y)
375
+ if k2 is not None and k != k2:
376
+ removes.add(y)
377
+
378
+ if len(removes) > 0:
379
+ updates[k] = [y for y in x[0] if y not in removes]
380
+
381
+ for k, v in updates.items():
382
+ json_obj[k][0] = v
383
+
384
+ return json_obj
385
+
386
+
387
+ @PromptServer.instance.routes.get("/customnode/getmappings")
388
+ async def fetch_customnode_mappings(request):
389
+ mode = request.rel_url.query["mode"]
390
+
391
+ nickname_mode = False
392
+ if mode == "nickname":
393
+ mode = "local"
394
+ nickname_mode = True
395
+
396
+ json_obj = await core.get_data_by_mode(mode, 'extension-node-map.json')
397
+
398
+ if nickname_mode:
399
+ json_obj = nickname_filter(json_obj)
400
+
401
+ all_nodes = set()
402
+ patterns = []
403
+ for k, x in json_obj.items():
404
+ all_nodes.update(set(x[0]))
405
+
406
+ if 'nodename_pattern' in x[1]:
407
+ patterns.append((x[1]['nodename_pattern'], x[0]))
408
+
409
+ missing_nodes = set(nodes.NODE_CLASS_MAPPINGS.keys()) - all_nodes
410
+
411
+ for x in missing_nodes:
412
+ for pat, item in patterns:
413
+ if re.match(pat, x):
414
+ item.append(x)
415
+
416
+ return web.json_response(json_obj, content_type='application/json')
417
+
418
+
419
+ @PromptServer.instance.routes.get("/customnode/fetch_updates")
420
+ async def fetch_updates(request):
421
+ try:
422
+ json_obj = await core.get_data_by_mode(request.rel_url.query["mode"], 'custom-node-list.json')
423
+
424
+ check_custom_nodes_installed(json_obj, True)
425
+
426
+ update_exists = any('custom_nodes' in json_obj and 'installed' in node and node['installed'] == 'Update' for node in
427
+ json_obj['custom_nodes'])
428
+
429
+ if update_exists:
430
+ return web.Response(status=201)
431
+
432
+ return web.Response(status=200)
433
+ except:
434
+ return web.Response(status=400)
435
+
436
+
437
+ @PromptServer.instance.routes.get("/customnode/update_all")
438
+ async def update_all(request):
439
+ if not is_allowed_security_level('middle'):
440
+ print(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
441
+ return web.Response(status=403)
442
+
443
+ try:
444
+ core.save_snapshot_with_postfix('autosave')
445
+
446
+ json_obj = await core.get_data_by_mode(request.rel_url.query["mode"], 'custom-node-list.json')
447
+
448
+ check_custom_nodes_installed(json_obj, do_update=True)
449
+
450
+ updated = [item['title'] for item in json_obj['custom_nodes'] if item['installed'] == 'Update']
451
+ failed = [item['title'] for item in json_obj['custom_nodes'] if item['installed'] == 'Fail']
452
+
453
+ res = {'updated': updated, 'failed': failed}
454
+
455
+ if len(updated) == 0 and len(failed) == 0:
456
+ status = 200
457
+ else:
458
+ status = 201
459
+
460
+ return web.json_response(res, status=status, content_type='application/json')
461
+ except:
462
+ return web.Response(status=400)
463
+ finally:
464
+ core.clear_pip_cache()
465
+
466
+
467
+ def convert_markdown_to_html(input_text):
468
+ pattern_a = re.compile(r'\[a/([^]]+)\]\(([^)]+)\)')
469
+ pattern_w = re.compile(r'\[w/([^]]+)\]')
470
+ pattern_i = re.compile(r'\[i/([^]]+)\]')
471
+ pattern_bold = re.compile(r'\*\*([^*]+)\*\*')
472
+ pattern_white = re.compile(r'%%([^*]+)%%')
473
+
474
+ def replace_a(match):
475
+ return f"<a href='{match.group(2)}' target='blank'>{match.group(1)}</a>"
476
+
477
+ def replace_w(match):
478
+ return f"<p class='cm-warn-note'>{match.group(1)}</p>"
479
+
480
+ def replace_i(match):
481
+ return f"<p class='cm-info-note'>{match.group(1)}</p>"
482
+
483
+ def replace_bold(match):
484
+ return f"<B>{match.group(1)}</B>"
485
+
486
+ def replace_white(match):
487
+ return f"<font color='white'>{match.group(1)}</font>"
488
+
489
+ input_text = input_text.replace('\\[', '&#91;').replace('\\]', '&#93;').replace('<', '&lt;').replace('>', '&gt;')
490
+
491
+ result_text = re.sub(pattern_a, replace_a, input_text)
492
+ result_text = re.sub(pattern_w, replace_w, result_text)
493
+ result_text = re.sub(pattern_i, replace_i, result_text)
494
+ result_text = re.sub(pattern_bold, replace_bold, result_text)
495
+ result_text = re.sub(pattern_white, replace_white, result_text)
496
+
497
+ return result_text.replace("\n", "<BR>")
498
+
499
+
500
+ def populate_markdown(x):
501
+ if 'description' in x:
502
+ x['description'] = convert_markdown_to_html(x['description'])
503
+
504
+ if 'name' in x:
505
+ x['name'] = x['name'].replace('<', '&lt;').replace('>', '&gt;')
506
+
507
+ if 'title' in x:
508
+ x['title'] = x['title'].replace('<', '&lt;').replace('>', '&gt;')
509
+
510
+
511
+ @PromptServer.instance.routes.get("/customnode/getlist")
512
+ async def fetch_customnode_list(request):
513
+ if "skip_update" in request.rel_url.query and request.rel_url.query["skip_update"] == "true":
514
+ skip_update = True
515
+ else:
516
+ skip_update = False
517
+
518
+ if request.rel_url.query["mode"] == "local":
519
+ channel = 'local'
520
+ else:
521
+ channel = core.get_config()['channel_url']
522
+
523
+ json_obj = await core.get_data_by_mode(request.rel_url.query["mode"], 'custom-node-list.json')
524
+ json_obj_github = await core.get_data_by_mode(request.rel_url.query["mode"], 'github-stats.json', 'default')
525
+ json_obj = await populate_github_stats(json_obj, json_obj_github)
526
+
527
+ def is_ignored_notice(code):
528
+ if code is not None and code.startswith('#NOTICE_'):
529
+ try:
530
+ notice_version = [int(x) for x in code[8:].split('.')]
531
+ return notice_version[0] < core.version[0] or (notice_version[0] == core.version[0] and notice_version[1] <= core.version[1])
532
+ except Exception:
533
+ return False
534
+ else:
535
+ return False
536
+
537
+ json_obj['custom_nodes'] = [record for record in json_obj['custom_nodes'] if not is_ignored_notice(record.get('author'))]
538
+
539
+ check_custom_nodes_installed(json_obj, False, not skip_update)
540
+
541
+ for x in json_obj['custom_nodes']:
542
+ populate_markdown(x)
543
+
544
+ if channel != 'local':
545
+ found = 'custom'
546
+
547
+ for name, url in core.get_channel_dict().items():
548
+ if url == channel:
549
+ found = name
550
+ break
551
+
552
+ channel = found
553
+
554
+ json_obj['channel'] = channel
555
+
556
+ return web.json_response(json_obj, content_type='application/json')
557
+
558
+
559
+ @PromptServer.instance.routes.get("/customnode/alternatives")
560
+ async def fetch_customnode_alternatives(request):
561
+ alter_json = await core.get_data_by_mode(request.rel_url.query["mode"], 'alter-list.json')
562
+
563
+ for item in alter_json['items']:
564
+ populate_markdown(item)
565
+
566
+ return web.json_response(alter_json, content_type='application/json')
567
+
568
+
569
+ @PromptServer.instance.routes.get("/alternatives/getlist")
570
+ async def fetch_alternatives_list(request):
571
+ if "skip_update" in request.rel_url.query and request.rel_url.query["skip_update"] == "true":
572
+ skip_update = True
573
+ else:
574
+ skip_update = False
575
+
576
+ alter_json = await core.get_data_by_mode(request.rel_url.query["mode"], 'alter-list.json')
577
+ custom_node_json = await core.get_data_by_mode(request.rel_url.query["mode"], 'custom-node-list.json')
578
+
579
+ fileurl_to_custom_node = {}
580
+
581
+ for item in custom_node_json['custom_nodes']:
582
+ for fileurl in item['files']:
583
+ fileurl_to_custom_node[fileurl] = item
584
+
585
+ for item in alter_json['items']:
586
+ fileurl = item['id']
587
+ if fileurl in fileurl_to_custom_node:
588
+ custom_node = fileurl_to_custom_node[fileurl]
589
+ core.check_a_custom_node_installed(custom_node, not skip_update)
590
+
591
+ populate_markdown(item)
592
+ populate_markdown(custom_node)
593
+ item['custom_node'] = custom_node
594
+
595
+ return web.json_response(alter_json, content_type='application/json')
596
+
597
+
598
+ def check_model_installed(json_obj):
599
+ def process_model(item):
600
+ model_path = get_model_path(item)
601
+ item['installed'] = 'None'
602
+
603
+ if model_path is not None:
604
+ if model_path.endswith('.zip'):
605
+ if os.path.exists(model_path[:-4]):
606
+ item['installed'] = 'True'
607
+ else:
608
+ item['installed'] = 'False'
609
+ elif os.path.exists(model_path):
610
+ item['installed'] = 'True'
611
+ else:
612
+ item['installed'] = 'False'
613
+
614
+ with concurrent.futures.ThreadPoolExecutor(8) as executor:
615
+ for item in json_obj['models']:
616
+ executor.submit(process_model, item)
617
+
618
+
619
+ @PromptServer.instance.routes.get("/externalmodel/getlist")
620
+ async def fetch_externalmodel_list(request):
621
+ json_obj = await core.get_data_by_mode(request.rel_url.query["mode"], 'model-list.json')
622
+
623
+ check_model_installed(json_obj)
624
+
625
+ for x in json_obj['models']:
626
+ populate_markdown(x)
627
+
628
+ return web.json_response(json_obj, content_type='application/json')
629
+
630
+
631
+ @PromptServer.instance.routes.get("/snapshot/getlist")
632
+ async def get_snapshot_list(request):
633
+ snapshots_directory = os.path.join(core.comfyui_manager_path, 'snapshots')
634
+ items = [f[:-5] for f in os.listdir(snapshots_directory) if f.endswith('.json')]
635
+ items.sort(reverse=True)
636
+ return web.json_response({'items': items}, content_type='application/json')
637
+
638
+
639
+ @PromptServer.instance.routes.get("/snapshot/remove")
640
+ async def remove_snapshot(request):
641
+ if not is_allowed_security_level('middle'):
642
+ print(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
643
+ return web.Response(status=403)
644
+
645
+ try:
646
+ target = request.rel_url.query["target"]
647
+
648
+ path = os.path.join(core.comfyui_manager_path, 'snapshots', f"{target}.json")
649
+ if os.path.exists(path):
650
+ os.remove(path)
651
+
652
+ return web.Response(status=200)
653
+ except:
654
+ return web.Response(status=400)
655
+
656
+
657
+ @PromptServer.instance.routes.get("/snapshot/restore")
658
+ async def remove_snapshot(request):
659
+ if not is_allowed_security_level('middle'):
660
+ print(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
661
+ return web.Response(status=403)
662
+
663
+ try:
664
+ target = request.rel_url.query["target"]
665
+
666
+ path = os.path.join(core.comfyui_manager_path, 'snapshots', f"{target}.json")
667
+ if os.path.exists(path):
668
+ if not os.path.exists(core.startup_script_path):
669
+ os.makedirs(core.startup_script_path)
670
+
671
+ target_path = os.path.join(core.startup_script_path, "restore-snapshot.json")
672
+ shutil.copy(path, target_path)
673
+
674
+ print(f"Snapshot restore scheduled: `{target}`")
675
+ return web.Response(status=200)
676
+
677
+ print(f"Snapshot file not found: `{path}`")
678
+ return web.Response(status=400)
679
+ except:
680
+ return web.Response(status=400)
681
+
682
+
683
+ @PromptServer.instance.routes.get("/snapshot/get_current")
684
+ async def get_current_snapshot_api(request):
685
+ try:
686
+ return web.json_response(core.get_current_snapshot(), content_type='application/json')
687
+ except:
688
+ return web.Response(status=400)
689
+
690
+
691
+ @PromptServer.instance.routes.get("/snapshot/save")
692
+ async def save_snapshot(request):
693
+ try:
694
+ core.save_snapshot_with_postfix('snapshot')
695
+ return web.Response(status=200)
696
+ except:
697
+ return web.Response(status=400)
698
+
699
+
700
+ def unzip_install(files):
701
+ temp_filename = 'manager-temp.zip'
702
+ for url in files:
703
+ if url.endswith("/"):
704
+ url = url[:-1]
705
+ try:
706
+ headers = {
707
+ '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'}
708
+
709
+ req = urllib.request.Request(url, headers=headers)
710
+ response = urllib.request.urlopen(req)
711
+ data = response.read()
712
+
713
+ with open(temp_filename, 'wb') as f:
714
+ f.write(data)
715
+
716
+ with zipfile.ZipFile(temp_filename, 'r') as zip_ref:
717
+ zip_ref.extractall(core.custom_nodes_path)
718
+
719
+ os.remove(temp_filename)
720
+ except Exception as e:
721
+ print(f"Install(unzip) error: {url} / {e}", file=sys.stderr)
722
+ return False
723
+
724
+ print("Installation was successful.")
725
+ return True
726
+
727
+
728
+ def download_url_with_agent(url, save_path):
729
+ try:
730
+ headers = {
731
+ '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'}
732
+
733
+ req = urllib.request.Request(url, headers=headers)
734
+ response = urllib.request.urlopen(req)
735
+ data = response.read()
736
+
737
+ if not os.path.exists(os.path.dirname(save_path)):
738
+ os.makedirs(os.path.dirname(save_path))
739
+
740
+ with open(save_path, 'wb') as f:
741
+ f.write(data)
742
+
743
+ except Exception as e:
744
+ print(f"Download error: {url} / {e}", file=sys.stderr)
745
+ return False
746
+
747
+ print("Installation was successful.")
748
+ return True
749
+
750
+
751
+ def copy_install(files, js_path_name=None):
752
+ for url in files:
753
+ if url.endswith("/"):
754
+ url = url[:-1]
755
+ try:
756
+ filename = os.path.basename(url)
757
+ if url.endswith(".py"):
758
+ download_url(url, core.custom_nodes_path, filename)
759
+ else:
760
+ path = os.path.join(core.js_path, js_path_name) if js_path_name is not None else core.js_path
761
+ if not os.path.exists(path):
762
+ os.makedirs(path)
763
+ download_url(url, path, filename)
764
+
765
+ except Exception as e:
766
+ print(f"Install(copy) error: {url} / {e}", file=sys.stderr)
767
+ return False
768
+
769
+ print("Installation was successful.")
770
+ return True
771
+
772
+
773
+ def copy_uninstall(files, js_path_name='.'):
774
+ for url in files:
775
+ if url.endswith("/"):
776
+ url = url[:-1]
777
+ dir_name = os.path.basename(url)
778
+ base_path = core.custom_nodes_path if url.endswith('.py') else os.path.join(core.js_path, js_path_name)
779
+ file_path = os.path.join(base_path, dir_name)
780
+
781
+ try:
782
+ if os.path.exists(file_path):
783
+ os.remove(file_path)
784
+ elif os.path.exists(file_path + ".disabled"):
785
+ os.remove(file_path + ".disabled")
786
+ except Exception as e:
787
+ print(f"Uninstall(copy) error: {url} / {e}", file=sys.stderr)
788
+ return False
789
+
790
+ print("Uninstallation was successful.")
791
+ return True
792
+
793
+
794
+ def copy_set_active(files, is_disable, js_path_name='.'):
795
+ if is_disable:
796
+ action_name = "Disable"
797
+ else:
798
+ action_name = "Enable"
799
+
800
+ for url in files:
801
+ if url.endswith("/"):
802
+ url = url[:-1]
803
+ dir_name = os.path.basename(url)
804
+ base_path = core.custom_nodes_path if url.endswith('.py') else os.path.join(core.js_path, js_path_name)
805
+ file_path = os.path.join(base_path, dir_name)
806
+
807
+ try:
808
+ if is_disable:
809
+ current_name = file_path
810
+ new_name = file_path + ".disabled"
811
+ else:
812
+ current_name = file_path + ".disabled"
813
+ new_name = file_path
814
+
815
+ os.rename(current_name, new_name)
816
+
817
+ except Exception as e:
818
+ print(f"{action_name}(copy) error: {url} / {e}", file=sys.stderr)
819
+
820
+ return False
821
+
822
+ print(f"{action_name} was successful.")
823
+ return True
824
+
825
+
826
+ @PromptServer.instance.routes.post("/customnode/install")
827
+ async def install_custom_node(request):
828
+ if not is_allowed_security_level('middle'):
829
+ print(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
830
+ return web.Response(status=403)
831
+
832
+ json_data = await request.json()
833
+
834
+ risky_level = await get_risky_level(json_data['files'], json_data.get('pip', []))
835
+ if not is_allowed_security_level(risky_level):
836
+ print(SECURITY_MESSAGE_GENERAL)
837
+ return web.Response(status=404)
838
+
839
+ install_type = json_data['install_type']
840
+
841
+ print(f"Install custom node '{json_data['title']}'")
842
+
843
+ res = False
844
+
845
+ if len(json_data['files']) == 0:
846
+ return web.Response(status=400)
847
+
848
+ if install_type == "unzip":
849
+ res = unzip_install(json_data['files'])
850
+
851
+ if install_type == "copy":
852
+ if 'js_path' in json_data:
853
+ if '.' in json_data['js_path'] or ':' in json_data['js_path'] or json_data['js_path'].startswith('/'):
854
+ print(f"[ComfyUI Manager] An abnormal JS path has been transmitted. This could be the result of a security attack.\n{json_data['js_path']}")
855
+ return web.Response(status=400)
856
+ else:
857
+ js_path_name = json_data['js_path']
858
+ else:
859
+ js_path_name = '.'
860
+ res = copy_install(json_data['files'], js_path_name)
861
+
862
+ elif install_type == "git-clone":
863
+ res = core.gitclone_install(json_data['files'])
864
+
865
+ if 'pip' in json_data:
866
+ for pname in json_data['pip']:
867
+ pkg = core.remap_pip_package(pname)
868
+ install_cmd = [sys.executable, "-m", "pip", "install", pkg]
869
+ core.try_install_script(json_data['files'][0], ".", install_cmd)
870
+
871
+ core.clear_pip_cache()
872
+
873
+ if res:
874
+ print(f"After restarting ComfyUI, please refresh the browser.")
875
+ return web.json_response({}, content_type='application/json')
876
+
877
+ return web.Response(status=400)
878
+
879
+
880
+ @PromptServer.instance.routes.post("/customnode/fix")
881
+ async def fix_custom_node(request):
882
+ if not is_allowed_security_level('middle'):
883
+ print(SECURITY_MESSAGE_GENERAL)
884
+ return web.Response(status=403)
885
+
886
+ json_data = await request.json()
887
+
888
+ install_type = json_data['install_type']
889
+
890
+ print(f"Install custom node '{json_data['title']}'")
891
+
892
+ res = False
893
+
894
+ if len(json_data['files']) == 0:
895
+ return web.Response(status=400)
896
+
897
+ if install_type == "git-clone":
898
+ res = core.gitclone_fix(json_data['files'])
899
+ else:
900
+ return web.Response(status=400)
901
+
902
+ if 'pip' in json_data:
903
+ if not is_allowed_security_level('high'):
904
+ print(SECURITY_MESSAGE_GENERAL)
905
+ return web.Response(status=403)
906
+
907
+ for pname in json_data['pip']:
908
+ install_cmd = [sys.executable, "-m", "pip", "install", '-U', pname]
909
+ core.try_install_script(json_data['files'][0], ".", install_cmd)
910
+
911
+ # HOTFIX: force downgrade to numpy<2
912
+ install_cmd = [sys.executable, "-m", "pip", "install", "numpy<2"]
913
+ core.try_install_script(json_data['files'][0], ".", install_cmd)
914
+
915
+ if res:
916
+ print(f"After restarting ComfyUI, please refresh the browser.")
917
+ return web.json_response({}, content_type='application/json')
918
+
919
+ return web.Response(status=400)
920
+
921
+
922
+ @PromptServer.instance.routes.post("/customnode/install/git_url")
923
+ async def install_custom_node_git_url(request):
924
+ if not is_allowed_security_level('high'):
925
+ print(SECURITY_MESSAGE_NORMAL_MINUS)
926
+ return web.Response(status=403)
927
+
928
+ url = await request.text()
929
+ res = core.gitclone_install([url])
930
+
931
+ if res:
932
+ print(f"After restarting ComfyUI, please refresh the browser.")
933
+ return web.Response(status=200)
934
+
935
+ return web.Response(status=400)
936
+
937
+
938
+ @PromptServer.instance.routes.post("/customnode/install/pip")
939
+ async def install_custom_node_git_url(request):
940
+ if not is_allowed_security_level('high'):
941
+ print(SECURITY_MESSAGE_NORMAL_MINUS)
942
+ return web.Response(status=403)
943
+
944
+ packages = await request.text()
945
+ core.pip_install(packages.split(' '))
946
+
947
+ return web.Response(status=200)
948
+
949
+
950
+ @PromptServer.instance.routes.post("/customnode/uninstall")
951
+ async def uninstall_custom_node(request):
952
+ if not is_allowed_security_level('middle'):
953
+ print(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
954
+ return web.Response(status=403)
955
+
956
+ json_data = await request.json()
957
+
958
+ install_type = json_data['install_type']
959
+
960
+ print(f"Uninstall custom node '{json_data['title']}'")
961
+
962
+ res = False
963
+
964
+ if install_type == "copy":
965
+ js_path_name = json_data['js_path'] if 'js_path' in json_data else '.'
966
+ res = copy_uninstall(json_data['files'], js_path_name)
967
+
968
+ elif install_type == "git-clone":
969
+ res = core.gitclone_uninstall(json_data['files'])
970
+
971
+ if res:
972
+ print(f"After restarting ComfyUI, please refresh the browser.")
973
+ return web.json_response({}, content_type='application/json')
974
+
975
+ return web.Response(status=400)
976
+
977
+
978
+ @PromptServer.instance.routes.post("/customnode/update")
979
+ async def update_custom_node(request):
980
+ if not is_allowed_security_level('middle'):
981
+ print(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
982
+ return web.Response(status=403)
983
+
984
+ json_data = await request.json()
985
+
986
+ install_type = json_data['install_type']
987
+
988
+ print(f"Update custom node '{json_data['title']}'")
989
+
990
+ res = False
991
+
992
+ if install_type == "git-clone":
993
+ res = core.gitclone_update(json_data['files'])
994
+
995
+ core.clear_pip_cache()
996
+
997
+ if res:
998
+ print(f"After restarting ComfyUI, please refresh the browser.")
999
+ return web.json_response({}, content_type='application/json')
1000
+
1001
+ return web.Response(status=400)
1002
+
1003
+
1004
+ @PromptServer.instance.routes.get("/comfyui_manager/update_comfyui")
1005
+ async def update_comfyui(request):
1006
+ print(f"Update ComfyUI")
1007
+
1008
+ try:
1009
+ repo_path = os.path.dirname(folder_paths.__file__)
1010
+ res = core.update_path(repo_path)
1011
+ if res == "fail":
1012
+ print(f"ComfyUI update fail: The installed ComfyUI does not have a Git repository.")
1013
+ return web.Response(status=400)
1014
+ elif res == "updated":
1015
+ return web.Response(status=201)
1016
+ else: # skipped
1017
+ return web.Response(status=200)
1018
+ except Exception as e:
1019
+ print(f"ComfyUI update fail: {e}", file=sys.stderr)
1020
+
1021
+ return web.Response(status=400)
1022
+
1023
+
1024
+ @PromptServer.instance.routes.post("/customnode/toggle_active")
1025
+ async def toggle_active(request):
1026
+ json_data = await request.json()
1027
+
1028
+ install_type = json_data['install_type']
1029
+ is_disabled = json_data['installed'] == "Disabled"
1030
+
1031
+ print(f"Update custom node '{json_data['title']}'")
1032
+
1033
+ res = False
1034
+
1035
+ if install_type == "git-clone":
1036
+ res = core.gitclone_set_active(json_data['files'], not is_disabled)
1037
+ elif install_type == "copy":
1038
+ res = copy_set_active(json_data['files'], not is_disabled, json_data.get('js_path', None))
1039
+
1040
+ if res:
1041
+ return web.json_response({}, content_type='application/json')
1042
+
1043
+ return web.Response(status=400)
1044
+
1045
+
1046
+ @PromptServer.instance.routes.post("/model/install")
1047
+ async def install_model(request):
1048
+ json_data = await request.json()
1049
+
1050
+ model_path = get_model_path(json_data)
1051
+
1052
+ if not is_allowed_security_level('middle'):
1053
+ print(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
1054
+ return web.Response(status=403)
1055
+
1056
+ if not json_data['filename'].endswith('.safetensors') and not is_allowed_security_level('high'):
1057
+ models_json = await core.get_data_by_mode('cache', 'model-list.json')
1058
+
1059
+ is_belongs_to_whitelist = False
1060
+ for x in models_json['models']:
1061
+ if x.get('url') == json_data['url']:
1062
+ is_belongs_to_whitelist = True
1063
+ break
1064
+
1065
+ if not is_belongs_to_whitelist:
1066
+ print(SECURITY_MESSAGE_NORMAL_MINUS)
1067
+ return web.Response(status=403)
1068
+
1069
+ res = False
1070
+
1071
+ try:
1072
+ if model_path is not None:
1073
+ print(f"Install model '{json_data['name']}' into '{model_path}'")
1074
+
1075
+ model_url = json_data['url']
1076
+ if not core.get_config()['model_download_by_agent'] and (
1077
+ model_url.startswith('https://github.com') or model_url.startswith('https://huggingface.co') or model_url.startswith('https://heibox.uni-heidelberg.de')):
1078
+ model_dir = get_model_dir(json_data)
1079
+ download_url(model_url, model_dir, filename=json_data['filename'])
1080
+ if model_path.endswith('.zip'):
1081
+ res = core.unzip(model_path)
1082
+ else:
1083
+ res = True
1084
+
1085
+ if res:
1086
+ return web.json_response({}, content_type='application/json')
1087
+ else:
1088
+ res = download_url_with_agent(model_url, model_path)
1089
+ if res and model_path.endswith('.zip'):
1090
+ res = core.unzip(model_path)
1091
+ else:
1092
+ print(f"Model installation error: invalid model type - {json_data['type']}")
1093
+
1094
+ if res:
1095
+ return web.json_response({}, content_type='application/json')
1096
+ except Exception as e:
1097
+ print(f"[ERROR] {e}", file=sys.stderr)
1098
+
1099
+ return web.Response(status=400)
1100
+
1101
+
1102
+ @PromptServer.instance.routes.get("/manager/preview_method")
1103
+ async def preview_method(request):
1104
+ if "value" in request.rel_url.query:
1105
+ set_preview_method(request.rel_url.query['value'])
1106
+ core.write_config()
1107
+ else:
1108
+ return web.Response(text=core.manager_funcs.get_current_preview_method(), status=200)
1109
+
1110
+ return web.Response(status=200)
1111
+
1112
+
1113
+ @PromptServer.instance.routes.get("/manager/badge_mode")
1114
+ async def badge_mode(request):
1115
+ if "value" in request.rel_url.query:
1116
+ set_badge_mode(request.rel_url.query['value'])
1117
+ core.write_config()
1118
+ else:
1119
+ return web.Response(text=core.get_config()['badge_mode'], status=200)
1120
+
1121
+ return web.Response(status=200)
1122
+
1123
+
1124
+ @PromptServer.instance.routes.get("/manager/default_ui")
1125
+ async def default_ui_mode(request):
1126
+ if "value" in request.rel_url.query:
1127
+ set_default_ui_mode(request.rel_url.query['value'])
1128
+ core.write_config()
1129
+ else:
1130
+ return web.Response(text=core.get_config()['default_ui'], status=200)
1131
+
1132
+ return web.Response(status=200)
1133
+
1134
+
1135
+ @PromptServer.instance.routes.get("/manager/component/policy")
1136
+ async def component_policy(request):
1137
+ if "value" in request.rel_url.query:
1138
+ set_component_policy(request.rel_url.query['value'])
1139
+ core.write_config()
1140
+ else:
1141
+ return web.Response(text=core.get_config()['component_policy'], status=200)
1142
+
1143
+ return web.Response(status=200)
1144
+
1145
+
1146
+ @PromptServer.instance.routes.get("/manager/dbl_click/policy")
1147
+ async def dbl_click_policy(request):
1148
+ if "value" in request.rel_url.query:
1149
+ set_double_click_policy(request.rel_url.query['value'])
1150
+ core.write_config()
1151
+ else:
1152
+ return web.Response(text=core.get_config()['double_click_policy'], status=200)
1153
+
1154
+ return web.Response(status=200)
1155
+
1156
+
1157
+ @PromptServer.instance.routes.get("/manager/channel_url_list")
1158
+ async def channel_url_list(request):
1159
+ channels = core.get_channel_dict()
1160
+ if "value" in request.rel_url.query:
1161
+ channel_url = channels.get(request.rel_url.query['value'])
1162
+ if channel_url is not None:
1163
+ core.get_config()['channel_url'] = channel_url
1164
+ core.write_config()
1165
+ else:
1166
+ selected = 'custom'
1167
+ selected_url = core.get_config()['channel_url']
1168
+
1169
+ for name, url in channels.items():
1170
+ if url == selected_url:
1171
+ selected = name
1172
+ break
1173
+
1174
+ res = {'selected': selected,
1175
+ 'list': core.get_channel_list()}
1176
+ return web.json_response(res, status=200)
1177
+
1178
+ return web.Response(status=200)
1179
+
1180
+
1181
+ def add_target_blank(html_text):
1182
+ pattern = r'(<a\s+href="[^"]*"\s*[^>]*)(>)'
1183
+
1184
+ def add_target(match):
1185
+ if 'target=' not in match.group(1):
1186
+ return match.group(1) + ' target="_blank"' + match.group(2)
1187
+ return match.group(0)
1188
+
1189
+ modified_html = re.sub(pattern, add_target, html_text)
1190
+
1191
+ return modified_html
1192
+
1193
+
1194
+ @PromptServer.instance.routes.get("/manager/notice")
1195
+ async def get_notice(request):
1196
+ url = "github.com"
1197
+ path = "/ltdrdata/ltdrdata.github.io/wiki/News"
1198
+
1199
+ async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
1200
+ async with session.get(f"https://{url}{path}") as response:
1201
+ if response.status == 200:
1202
+ # html_content = response.read().decode('utf-8')
1203
+ html_content = await response.text()
1204
+
1205
+ pattern = re.compile(r'<div class="markdown-body">([\s\S]*?)</div>')
1206
+ match = pattern.search(html_content)
1207
+
1208
+ if match:
1209
+ markdown_content = match.group(1)
1210
+ version_tag = core.get_comfyui_tag()
1211
+ if version_tag is None:
1212
+ markdown_content += f"<HR>ComfyUI: {core.comfy_ui_revision}[{comfy_ui_hash[:6]}]({core.comfy_ui_commit_datetime.date()})"
1213
+ else:
1214
+ markdown_content += (f"<HR>ComfyUI: {version_tag}<BR>"
1215
+ f"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;({core.comfy_ui_commit_datetime.date()})")
1216
+ # markdown_content += f"<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;()"
1217
+ markdown_content += f"<BR>Manager: {core.version_str}"
1218
+
1219
+ markdown_content = add_target_blank(markdown_content)
1220
+
1221
+ try:
1222
+ if core.comfy_ui_commit_datetime == datetime(1900, 1, 1, 0, 0, 0):
1223
+ markdown_content = f'<P style="text-align: center; color:red; background-color:white; font-weight:bold">Your ComfyUI isn\'t git repo.</P>' + markdown_content
1224
+ elif core.comfy_ui_required_commit_datetime.date() > core.comfy_ui_commit_datetime.date():
1225
+ markdown_content = f'<P style="text-align: center; color:red; background-color:white; font-weight:bold">Your ComfyUI is too OUTDATED!!!</P>' + markdown_content
1226
+ except:
1227
+ pass
1228
+
1229
+ return web.Response(text=markdown_content, status=200)
1230
+ else:
1231
+ return web.Response(text="Unable to retrieve Notice", status=200)
1232
+ else:
1233
+ return web.Response(text="Unable to retrieve Notice", status=200)
1234
+
1235
+
1236
+ @PromptServer.instance.routes.get("/manager/reboot")
1237
+ def restart(self):
1238
+ if not is_allowed_security_level('middle'):
1239
+ print(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
1240
+ return web.Response(status=403)
1241
+
1242
+ try:
1243
+ sys.stdout.close_log()
1244
+ except Exception as e:
1245
+ pass
1246
+
1247
+ if '__COMFY_CLI_SESSION__' in os.environ:
1248
+ with open(os.path.join(os.environ['__COMFY_CLI_SESSION__'] + '.reboot'), 'w') as file:
1249
+ pass
1250
+
1251
+ print(f"\nRestarting...\n\n")
1252
+ exit(0)
1253
+
1254
+ print(f"\nRestarting... [Legacy Mode]\n\n")
1255
+
1256
+ sys_argv = sys.argv.copy()
1257
+ if '--windows-standalone-build' in sys_argv:
1258
+ sys_argv.remove('--windows-standalone-build')
1259
+
1260
+ if sys.platform.startswith('win32'):
1261
+ return os.execv(sys.executable, ['"' + sys.executable + '"', '"' + sys.argv[0] + '"'] + sys.argv[1:])
1262
+ else:
1263
+ return os.execv(sys.executable, [sys.executable] + sys.argv)
1264
+
1265
+
1266
+ def sanitize_filename(input_string):
1267
+ # 알파벳, 숫자, 및 밑줄 이외의 문자를 밑줄로 대체
1268
+ result_string = re.sub(r'[^a-zA-Z0-9_]', '_', input_string)
1269
+ return result_string
1270
+
1271
+
1272
+ @PromptServer.instance.routes.post("/manager/component/save")
1273
+ async def save_component(request):
1274
+ try:
1275
+ data = await request.json()
1276
+ name = data['name']
1277
+ workflow = data['workflow']
1278
+
1279
+ if not os.path.exists(components_path):
1280
+ os.mkdir(components_path)
1281
+
1282
+ if 'packname' in workflow and workflow['packname'] != '':
1283
+ sanitized_name = sanitize_filename(workflow['packname']) + '.pack'
1284
+ else:
1285
+ sanitized_name = sanitize_filename(name) + '.json'
1286
+
1287
+ filepath = os.path.join(components_path, sanitized_name)
1288
+ components = {}
1289
+ if os.path.exists(filepath):
1290
+ with open(filepath) as f:
1291
+ components = json.load(f)
1292
+
1293
+ components[name] = workflow
1294
+
1295
+ with open(filepath, 'w') as f:
1296
+ json.dump(components, f, indent=4, sort_keys=True)
1297
+ return web.Response(text=filepath, status=200)
1298
+ except:
1299
+ return web.Response(status=400)
1300
+
1301
+
1302
+ @PromptServer.instance.routes.post("/manager/component/loads")
1303
+ async def load_components(request):
1304
+ try:
1305
+ json_files = [f for f in os.listdir(components_path) if f.endswith('.json')]
1306
+ pack_files = [f for f in os.listdir(components_path) if f.endswith('.pack')]
1307
+
1308
+ components = {}
1309
+ for json_file in json_files + pack_files:
1310
+ file_path = os.path.join(components_path, json_file)
1311
+ with open(file_path, 'r') as file:
1312
+ try:
1313
+ # When there is a conflict between the .pack and the .json, the pack takes precedence and overrides.
1314
+ components.update(json.load(file))
1315
+ except json.JSONDecodeError as e:
1316
+ print(f"[ComfyUI-Manager] Error decoding component file in file {json_file}: {e}")
1317
+
1318
+ return web.json_response(components)
1319
+ except Exception as e:
1320
+ print(f"[ComfyUI-Manager] failed to load components\n{e}")
1321
+ return web.Response(status=400)
1322
+
1323
+
1324
+ args.enable_cors_header = "*"
1325
+ if hasattr(PromptServer.instance, "app"):
1326
+ app = PromptServer.instance.app
1327
+ cors_middleware = server.create_cors_middleware(args.enable_cors_header)
1328
+ app.middlewares.append(cors_middleware)
1329
+
1330
+
1331
+ def sanitize(data):
1332
+ return data.replace("<", "&lt;").replace(">", "&gt;")
1333
+
1334
+
1335
+ async def _confirm_try_install(sender, custom_node_url, msg):
1336
+ json_obj = await core.get_data_by_mode('default', 'custom-node-list.json')
1337
+
1338
+ sender = sanitize(sender)
1339
+ msg = sanitize(msg)
1340
+ target = core.lookup_customnode_by_url(json_obj, custom_node_url)
1341
+
1342
+ if target is not None:
1343
+ PromptServer.instance.send_sync("cm-api-try-install-customnode",
1344
+ {"sender": sender, "target": target, "msg": msg})
1345
+ else:
1346
+ print(f"[ComfyUI Manager API] Failed to try install - Unknown custom node url '{custom_node_url}'")
1347
+
1348
+
1349
+ def confirm_try_install(sender, custom_node_url, msg):
1350
+ asyncio.run(_confirm_try_install(sender, custom_node_url, msg))
1351
+
1352
+
1353
+ cm_global.register_api('cm.try-install-custom-node', confirm_try_install)
1354
+
1355
+ import asyncio
1356
+
1357
+
1358
+ async def default_cache_update():
1359
+ async def get_cache(filename):
1360
+ uri = 'https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/' + filename
1361
+ cache_uri = str(core.simple_hash(uri)) + '_' + filename
1362
+ cache_uri = os.path.join(core.cache_dir, cache_uri)
1363
+
1364
+ json_obj = await core.get_data(uri, True)
1365
+
1366
+ with core.cache_lock:
1367
+ with open(cache_uri, "w", encoding='utf-8') as file:
1368
+ json.dump(json_obj, file, indent=4, sort_keys=True)
1369
+ print(f"[ComfyUI-Manager] default cache updated: {uri}")
1370
+
1371
+ a = get_cache("custom-node-list.json")
1372
+ b = get_cache("extension-node-map.json")
1373
+ c = get_cache("model-list.json")
1374
+ d = get_cache("alter-list.json")
1375
+ e = get_cache("github-stats.json")
1376
+
1377
+ await asyncio.gather(a, b, c, d, e)
1378
+
1379
+
1380
+ threading.Thread(target=lambda: asyncio.run(default_cache_update())).start()
1381
+
1382
+ if not os.path.exists(core.config_path):
1383
+ core.get_config()
1384
+ core.write_config()
1385
+
1386
+
1387
+ cm_global.register_extension('ComfyUI-Manager',
1388
+ {'version': core.version,
1389
+ 'name': 'ComfyUI Manager',
1390
+ 'nodes': {},
1391
+ 'description': 'It provides the ability to manage custom nodes in ComfyUI.', })
1392
+
ComfyUI/custom_nodes/ComfyUI-Manager/glob/manager_util.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import sys
3
+
4
+ # DON'T USE StrictVersion - cannot handle pre_release version
5
+ # try:
6
+ # from distutils.version import StrictVersion
7
+ # except:
8
+ # print(f"[ComfyUI-Manager] 'distutils' package not found. Activating fallback mode for compatibility.")
9
+ class StrictVersion:
10
+ def __init__(self, version_string):
11
+ self.version_string = version_string
12
+ self.major = 0
13
+ self.minor = 0
14
+ self.patch = 0
15
+ self.pre_release = None
16
+ self.parse_version_string()
17
+
18
+ def parse_version_string(self):
19
+ parts = self.version_string.split('.')
20
+ if not parts:
21
+ raise ValueError("Version string must not be empty")
22
+
23
+ self.major = int(parts[0])
24
+ self.minor = int(parts[1]) if len(parts) > 1 else 0
25
+ self.patch = int(parts[2]) if len(parts) > 2 else 0
26
+
27
+ # Handling pre-release versions if present
28
+ if len(parts) > 3:
29
+ self.pre_release = parts[3]
30
+
31
+ def __str__(self):
32
+ version = f"{self.major}.{self.minor}.{self.patch}"
33
+ if self.pre_release:
34
+ version += f"-{self.pre_release}"
35
+ return version
36
+
37
+ def __eq__(self, other):
38
+ return (self.major, self.minor, self.patch, self.pre_release) == \
39
+ (other.major, other.minor, other.patch, other.pre_release)
40
+
41
+ def __lt__(self, other):
42
+ if (self.major, self.minor, self.patch) == (other.major, other.minor, other.patch):
43
+ return self.pre_release_compare(self.pre_release, other.pre_release) < 0
44
+ return (self.major, self.minor, self.patch) < (other.major, other.minor, other.patch)
45
+
46
+ @staticmethod
47
+ def pre_release_compare(pre1, pre2):
48
+ if pre1 == pre2:
49
+ return 0
50
+ if pre1 is None:
51
+ return 1
52
+ if pre2 is None:
53
+ return -1
54
+ return -1 if pre1 < pre2 else 1
55
+
56
+ def __le__(self, other):
57
+ return self == other or self < other
58
+
59
+ def __gt__(self, other):
60
+ return not self <= other
61
+
62
+ def __ge__(self, other):
63
+ return not self < other
64
+
65
+ def __ne__(self, other):
66
+ return not self == other
67
+
68
+
69
+ pip_map = None
70
+
71
+ def get_installed_packages(renew=False):
72
+ global pip_map
73
+
74
+ if renew or pip_map is None:
75
+ try:
76
+ result = subprocess.check_output([sys.executable, '-m', 'pip', 'list'], universal_newlines=True)
77
+
78
+ pip_map = {}
79
+ for line in result.split('\n'):
80
+ x = line.strip()
81
+ if x:
82
+ y = line.split()
83
+ if y[0] == 'Package' or y[0].startswith('-'):
84
+ continue
85
+
86
+ pip_map[y[0]] = y[1]
87
+ except subprocess.CalledProcessError as e:
88
+ print(f"[ComfyUI-Manager] Failed to retrieve the information of installed pip packages.")
89
+ return set()
90
+
91
+ return pip_map
92
+
93
+
94
+ def clear_pip_cache():
95
+ global pip_map
96
+ pip_map = None
97
+
98
+
99
+ torch_torchvision_version_map = {
100
+ '2.5.1': '0.20.1',
101
+ '2.5.0': '0.20.0',
102
+ '2.4.1': '0.19.1',
103
+ '2.4.0': '0.19.0',
104
+ '2.3.1': '0.18.1',
105
+ '2.3.0': '0.18.0',
106
+ '2.2.2': '0.17.2',
107
+ '2.2.1': '0.17.1',
108
+ '2.2.0': '0.17.0',
109
+ '2.1.2': '0.16.2',
110
+ '2.1.1': '0.16.1',
111
+ '2.1.0': '0.16.0',
112
+ '2.0.1': '0.15.2',
113
+ '2.0.0': '0.15.1',
114
+ }
115
+
116
+
117
+ class PIPFixer:
118
+ def __init__(self, prev_pip_versions):
119
+ self.prev_pip_versions = { **prev_pip_versions }
120
+
121
+ def torch_rollback(self):
122
+ spec = self.prev_pip_versions['torch'].split('+')
123
+ if len(spec) > 0:
124
+ platform = spec[1]
125
+ else:
126
+ cmd = [sys.executable, '-m', 'pip', 'install', '--force', 'torch', 'torchvision', 'torchaudio']
127
+ subprocess.check_output(cmd, universal_newlines=True)
128
+ print(cmd)
129
+ return
130
+
131
+ torch_ver = StrictVersion(spec[0])
132
+ torch_ver = f"{torch_ver.major}.{torch_ver.minor}.{torch_ver.patch}"
133
+ torchvision_ver = torch_torchvision_version_map.get(torch_ver)
134
+
135
+ if torchvision_ver is None:
136
+ cmd = [sys.executable, '-m', 'pip', 'install', '--pre',
137
+ 'torch', 'torchvision', 'torchaudio',
138
+ '--index-url', f"https://download.pytorch.org/whl/nightly/{platform}"]
139
+ print("[manager-core] restore PyTorch to nightly version")
140
+ else:
141
+ cmd = [sys.executable, '-m', 'pip', 'install',
142
+ f'torch=={torch_ver}', f'torchvision=={torchvision_ver}', f"torchaudio=={torch_ver}",
143
+ '--index-url', f"https://download.pytorch.org/whl/{platform}"]
144
+ print(f"[manager-core] restore PyTorch to {torch_ver}+{platform}")
145
+
146
+ subprocess.check_output(cmd, universal_newlines=True)
147
+
148
+ def fix_broken(self):
149
+ new_pip_versions = get_installed_packages(True)
150
+
151
+ # remove `comfy` python package
152
+ try:
153
+ if 'comfy' in new_pip_versions:
154
+ cmd = [sys.executable, '-m', 'pip', 'uninstall', 'comfy']
155
+ subprocess.check_output(cmd, universal_newlines=True)
156
+
157
+ print(f"[manager-core] '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.")
158
+ except Exception as e:
159
+ print(f"[manager-core] Failed to uninstall `comfy` python package")
160
+ print(e)
161
+
162
+ # fix torch - reinstall torch packages if version is changed
163
+ try:
164
+ if self.prev_pip_versions['torch'] != new_pip_versions['torch'] \
165
+ or self.prev_pip_versions['torchvision'] != new_pip_versions['torchvision'] \
166
+ or self.prev_pip_versions['torchaudio'] != new_pip_versions['torchaudio']:
167
+ self.torch_rollback()
168
+ except Exception as e:
169
+ print(f"[manager-core] Failed to restore PyTorch")
170
+ print(e)
171
+
172
+ # fix opencv
173
+ try:
174
+ ocp = new_pip_versions.get('opencv-contrib-python')
175
+ ocph = new_pip_versions.get('opencv-contrib-python-headless')
176
+ op = new_pip_versions.get('opencv-python')
177
+ oph = new_pip_versions.get('opencv-python-headless')
178
+
179
+ versions = [ocp, ocph, op, oph]
180
+ versions = [StrictVersion(x) for x in versions if x is not None]
181
+ versions.sort(reverse=True)
182
+
183
+ if len(versions) > 0:
184
+ # upgrade to maximum version
185
+ targets = []
186
+ cur = versions[0]
187
+ if ocp is not None and StrictVersion(ocp) != cur:
188
+ targets.append('opencv-contrib-python')
189
+ if ocph is not None and StrictVersion(ocph) != cur:
190
+ targets.append('opencv-contrib-python-headless')
191
+ if op is not None and StrictVersion(op) != cur:
192
+ targets.append('opencv-python')
193
+ if oph is not None and StrictVersion(oph) != cur:
194
+ targets.append('opencv-python-headless')
195
+
196
+ if len(targets) > 0:
197
+ for x in targets:
198
+ cmd = [sys.executable, '-m', 'pip', 'install', f"{x}=={versions[0].version_string}"]
199
+ subprocess.check_output(cmd, universal_newlines=True)
200
+
201
+ print(f"[manager-core] 'opencv' dependencies were fixed: {targets}")
202
+ except Exception as e:
203
+ print(f"[manager-core] Failed to restore opencv")
204
+ print(e)
205
+
206
+ # fix numpy
207
+ try:
208
+ np = new_pip_versions.get('numpy')
209
+ if np is not None:
210
+ if StrictVersion(np) >= StrictVersion('2'):
211
+ subprocess.check_output([sys.executable, '-m', 'pip', 'install', f"numpy<2"], universal_newlines=True)
212
+ except Exception as e:
213
+ print(f"[manager-core] Failed to restore numpy")
214
+ print(e)
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(f"\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,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.comfyui_manager_path, ".openart_key")):
69
+ return None
70
+ try:
71
+ with open(os.path.join(core.comfyui_manager_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.comfyui_manager_path, "matrix_auth")):
80
+ return None
81
+ try:
82
+ with open(os.path.join(core.comfyui_manager_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.comfyui_manager_path, "comfyworkflows_sharekey")):
98
+ return None
99
+ try:
100
+ with open(os.path.join(core.comfyui_manager_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.comfyui_manager_path, ".youml")):
111
+ return None
112
+ try:
113
+ with open(os.path.join(core.comfyui_manager_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.comfyui_manager_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.comfyui_manager_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
+ current_workflow = json_data['workflow']
182
+ images = json_data['images']
183
+ with open(os.path.join(core.comfyui_manager_path, "esheep_share_message.json"), "w", encoding='utf-8') as file:
184
+ json.dump(json_data, file, indent=4)
185
+ return web.Response(status=200)
186
+
187
+
188
+ @PromptServer.instance.routes.get("/manager/get_esheep_workflow_and_images")
189
+ async def get_esheep_workflow_and_images(request):
190
+ with open(os.path.join(core.comfyui_manager_path, "esheep_share_message.json"), 'r', encoding='utf-8') as file:
191
+ data = json.load(file)
192
+ return web.Response(status=200, text=json.dumps(data))
193
+
194
+
195
+ def set_matrix_auth(json_data):
196
+ homeserver = json_data['homeserver']
197
+ username = json_data['username']
198
+ password = json_data['password']
199
+ with open(os.path.join(core.comfyui_manager_path, "matrix_auth"), "w") as f:
200
+ f.write("\n".join([homeserver, username, password]))
201
+
202
+
203
+ def set_comfyworkflows_auth(comfyworkflows_sharekey):
204
+ with open(os.path.join(core.comfyui_manager_path, "comfyworkflows_sharekey"), "w") as f:
205
+ f.write(comfyworkflows_sharekey)
206
+
207
+
208
+ def has_provided_matrix_auth(matrix_auth):
209
+ return matrix_auth['homeserver'].strip() and matrix_auth['username'].strip() and matrix_auth['password'].strip()
210
+
211
+
212
+ def has_provided_comfyworkflows_auth(comfyworkflows_sharekey):
213
+ return comfyworkflows_sharekey.strip()
214
+
215
+
216
+ @PromptServer.instance.routes.post("/manager/share")
217
+ async def share_art(request):
218
+ # get json data
219
+ json_data = await request.json()
220
+
221
+ matrix_auth = json_data['matrix_auth']
222
+ comfyworkflows_sharekey = json_data['cw_auth']['cw_sharekey']
223
+
224
+ set_matrix_auth(matrix_auth)
225
+ set_comfyworkflows_auth(comfyworkflows_sharekey)
226
+
227
+ share_destinations = json_data['share_destinations']
228
+ credits = json_data['credits']
229
+ title = json_data['title']
230
+ description = json_data['description']
231
+ is_nsfw = json_data['is_nsfw']
232
+ prompt = json_data['prompt']
233
+ potential_outputs = json_data['potential_outputs']
234
+ selected_output_index = json_data['selected_output_index']
235
+
236
+ try:
237
+ output_to_share = potential_outputs[int(selected_output_index)]
238
+ except:
239
+ # for now, pick the first output
240
+ output_to_share = potential_outputs[0]
241
+
242
+ assert output_to_share['type'] in ('image', 'output')
243
+ output_dir = folder_paths.get_output_directory()
244
+
245
+ if output_to_share['type'] == 'image':
246
+ asset_filename = output_to_share['image']['filename']
247
+ asset_subfolder = output_to_share['image']['subfolder']
248
+
249
+ if output_to_share['image']['type'] == 'temp':
250
+ output_dir = folder_paths.get_temp_directory()
251
+ else:
252
+ asset_filename = output_to_share['output']['filename']
253
+ asset_subfolder = output_to_share['output']['subfolder']
254
+
255
+ if asset_subfolder:
256
+ asset_filepath = os.path.join(output_dir, asset_subfolder, asset_filename)
257
+ else:
258
+ asset_filepath = os.path.join(output_dir, asset_filename)
259
+
260
+ # get the mime type of the asset
261
+ assetFileType = mimetypes.guess_type(asset_filepath)[0]
262
+
263
+ share_website_host = "UNKNOWN"
264
+ if "comfyworkflows" in share_destinations:
265
+ share_website_host = "https://comfyworkflows.com"
266
+ share_endpoint = f"{share_website_host}/api"
267
+
268
+ # get presigned urls
269
+ async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
270
+ async with session.post(
271
+ f"{share_endpoint}/get_presigned_urls",
272
+ json={
273
+ "assetFileName": asset_filename,
274
+ "assetFileType": assetFileType,
275
+ "workflowJsonFileName": 'workflow.json',
276
+ "workflowJsonFileType": 'application/json',
277
+ },
278
+ ) as resp:
279
+ assert resp.status == 200
280
+ presigned_urls_json = await resp.json()
281
+ assetFilePresignedUrl = presigned_urls_json["assetFilePresignedUrl"]
282
+ assetFileKey = presigned_urls_json["assetFileKey"]
283
+ workflowJsonFilePresignedUrl = presigned_urls_json["workflowJsonFilePresignedUrl"]
284
+ workflowJsonFileKey = presigned_urls_json["workflowJsonFileKey"]
285
+
286
+ # upload asset
287
+ async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
288
+ async with session.put(assetFilePresignedUrl, data=open(asset_filepath, "rb")) as resp:
289
+ assert resp.status == 200
290
+
291
+ # upload workflow json
292
+ async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
293
+ async with session.put(workflowJsonFilePresignedUrl, data=json.dumps(prompt['workflow']).encode('utf-8')) as resp:
294
+ assert resp.status == 200
295
+
296
+ model_filenames = extract_model_file_names(prompt['workflow'])
297
+ model_file_paths = find_file_paths(folder_paths.base_path, model_filenames)
298
+
299
+ models_info = {}
300
+ for filename, filepath in model_file_paths.items():
301
+ models_info[filename] = {
302
+ "filename": filename,
303
+ "sha256_checksum": compute_sha256_checksum(filepath),
304
+ "relative_path": os.path.relpath(filepath, folder_paths.base_path),
305
+ }
306
+
307
+ # make a POST request to /api/upload_workflow with form data key values
308
+ async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
309
+ form = aiohttp.FormData()
310
+ if comfyworkflows_sharekey:
311
+ form.add_field("shareKey", comfyworkflows_sharekey)
312
+ form.add_field("source", "comfyui_manager")
313
+ form.add_field("assetFileKey", assetFileKey)
314
+ form.add_field("assetFileType", assetFileType)
315
+ form.add_field("workflowJsonFileKey", workflowJsonFileKey)
316
+ form.add_field("sharedWorkflowWorkflowJsonString", json.dumps(prompt['workflow']))
317
+ form.add_field("sharedWorkflowPromptJsonString", json.dumps(prompt['output']))
318
+ form.add_field("shareWorkflowCredits", credits)
319
+ form.add_field("shareWorkflowTitle", title)
320
+ form.add_field("shareWorkflowDescription", description)
321
+ form.add_field("shareWorkflowIsNSFW", str(is_nsfw).lower())
322
+ form.add_field("currentSnapshot", json.dumps(core.get_current_snapshot()))
323
+ form.add_field("modelsInfo", json.dumps(models_info))
324
+
325
+ async with session.post(
326
+ f"{share_endpoint}/upload_workflow",
327
+ data=form,
328
+ ) as resp:
329
+ assert resp.status == 200
330
+ upload_workflow_json = await resp.json()
331
+ workflowId = upload_workflow_json["workflowId"]
332
+
333
+ # check if the user has provided Matrix credentials
334
+ if "matrix" in share_destinations:
335
+ comfyui_share_room_id = '!LGYSoacpJPhIfBqVfb:matrix.org'
336
+ filename = os.path.basename(asset_filepath)
337
+ content_type = assetFileType
338
+
339
+ try:
340
+ from matrix_client.api import MatrixHttpApi
341
+ from matrix_client.client import MatrixClient
342
+
343
+ homeserver = 'matrix.org'
344
+ if matrix_auth:
345
+ homeserver = matrix_auth.get('homeserver', 'matrix.org')
346
+ homeserver = homeserver.replace("http://", "https://")
347
+ if not homeserver.startswith("https://"):
348
+ homeserver = "https://" + homeserver
349
+
350
+ client = MatrixClient(homeserver)
351
+ try:
352
+ token = client.login(username=matrix_auth['username'], password=matrix_auth['password'])
353
+ if not token:
354
+ return web.json_response({"error": "Invalid Matrix credentials."}, content_type='application/json', status=400)
355
+ except:
356
+ return web.json_response({"error": "Invalid Matrix credentials."}, content_type='application/json', status=400)
357
+
358
+ matrix = MatrixHttpApi(homeserver, token=token)
359
+ with open(asset_filepath, 'rb') as f:
360
+ mxc_url = matrix.media_upload(f.read(), content_type, filename=filename)['content_uri']
361
+
362
+ workflow_json_mxc_url = matrix.media_upload(prompt['workflow'], 'application/json', filename='workflow.json')['content_uri']
363
+
364
+ text_content = ""
365
+ if title:
366
+ text_content += f"{title}\n"
367
+ if description:
368
+ text_content += f"{description}\n"
369
+ if credits:
370
+ text_content += f"\ncredits: {credits}\n"
371
+ response = matrix.send_message(comfyui_share_room_id, text_content)
372
+ response = matrix.send_content(comfyui_share_room_id, mxc_url, filename, 'm.image')
373
+ response = matrix.send_content(comfyui_share_room_id, workflow_json_mxc_url, 'workflow.json', 'm.file')
374
+ except:
375
+ import traceback
376
+ traceback.print_exc()
377
+ return web.json_response({"error": "An error occurred when sharing your art to Matrix."}, content_type='application/json', status=500)
378
+
379
+ return web.json_response({
380
+ "comfyworkflows": {
381
+ "url": None if "comfyworkflows" not in share_destinations else f"{share_website_host}/workflows/{workflowId}",
382
+ },
383
+ "matrix": {
384
+ "success": None if "matrix" not in share_destinations else True
385
+ }
386
+ }, content_type='application/json', status=200)
ComfyUI/custom_nodes/ComfyUI-Manager/js/cm-api.js ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { api } from "../../scripts/api.js";
2
+ import { app } from "../../scripts/app.js";
3
+ import { sleep } 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
+ alert(msg);
23
+ return;
24
+ }
25
+
26
+ let res = confirm(msg);
27
+ if(res) {
28
+ if(event.detail.target.installed == 'Disabled') {
29
+ const response = await api.fetchApi(`/customnode/toggle_active`, {
30
+ method: 'POST',
31
+ headers: { 'Content-Type': 'application/json' },
32
+ body: JSON.stringify(event.detail.target)
33
+ });
34
+ }
35
+ else {
36
+ await sleep(300);
37
+ app.ui.dialog.show(`Installing... '${event.detail.target.title}'`);
38
+
39
+ const response = await api.fetchApi(`/customnode/install`, {
40
+ method: 'POST',
41
+ headers: { 'Content-Type': 'application/json' },
42
+ body: JSON.stringify(event.detail.target)
43
+ });
44
+
45
+ if(response.status == 403) {
46
+ show_message('This action is not allowed with this security level configuration.');
47
+ return false;
48
+ }
49
+ }
50
+
51
+ let response = await api.fetchApi("/manager/reboot");
52
+ if(response.status == 403) {
53
+ show_message('This action is not allowed with this security level configuration.');
54
+ return false;
55
+ }
56
+
57
+ await sleep(300);
58
+
59
+ app.ui.dialog.show(`Rebooting...`);
60
+ }
61
+ }
62
+
63
+ api.addEventListener("cm-api-try-install-customnode", tryInstallCustomNode);
ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-manager.js ADDED
@@ -0,0 +1,1550 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { free_models, install_pip, install_via_git_url, manager_instance, rebootAPI, setManagerInstance, show_message } from "./common.js";
15
+ import { ComponentBuilderDialog, getPureName, load_components, set_component_policy } from "./components-manager.js";
16
+ import { CustomNodesManager } from "./custom-nodes-manager.js";
17
+ import { ModelManager } from "./model-manager.js";
18
+ import { set_double_click_policy } from "./node_fixer.js";
19
+ import { SnapshotManager } from "./snapshot.js";
20
+
21
+ var docStyle = document.createElement('style');
22
+ docStyle.innerHTML = `
23
+ .comfy-toast {
24
+ position: fixed;
25
+ bottom: 20px;
26
+ left: 50%;
27
+ transform: translateX(-50%);
28
+ background-color: rgba(0, 0, 0, 0.7);
29
+ color: white;
30
+ padding: 10px 20px;
31
+ border-radius: 5px;
32
+ z-index: 1000;
33
+ transition: opacity 0.5s;
34
+ }
35
+
36
+ .comfy-toast-fadeout {
37
+ opacity: 0;
38
+ }
39
+
40
+ #cm-manager-dialog {
41
+ width: 1000px;
42
+ height: 520px;
43
+ box-sizing: content-box;
44
+ z-index: 10000;
45
+ overflow-y: auto;
46
+ }
47
+
48
+ .cb-widget {
49
+ width: 400px;
50
+ height: 25px;
51
+ box-sizing: border-box;
52
+ z-index: 10000;
53
+ margin-top: 10px;
54
+ margin-bottom: 5px;
55
+ }
56
+
57
+ .cb-widget-input {
58
+ width: 305px;
59
+ height: 25px;
60
+ box-sizing: border-box;
61
+ }
62
+ .cb-widget-input:disabled {
63
+ background-color: #444444;
64
+ color: white;
65
+ }
66
+
67
+ .cb-widget-input-label {
68
+ width: 90px;
69
+ height: 25px;
70
+ box-sizing: border-box;
71
+ color: white;
72
+ text-align: right;
73
+ display: inline-block;
74
+ margin-right: 5px;
75
+ }
76
+
77
+ .cm-menu-container {
78
+ column-gap: 20px;
79
+ display: flex;
80
+ flex-wrap: wrap;
81
+ justify-content: center;
82
+ box-sizing: content-box;
83
+ }
84
+
85
+ .cm-menu-column {
86
+ display: flex;
87
+ flex-direction: column;
88
+ flex: 1 1 auto;
89
+ width: 300px;
90
+ box-sizing: content-box;
91
+ }
92
+
93
+ .cm-title {
94
+ background-color: black;
95
+ text-align: center;
96
+ height: 40px;
97
+ width: calc(100% - 10px);
98
+ font-weight: bold;
99
+ justify-content: center;
100
+ align-content: center;
101
+ vertical-align: middle;
102
+ }
103
+
104
+ #cm-channel-badge {
105
+ color: white;
106
+ background-color: #AA0000;
107
+ width: 220px;
108
+ height: 23px;
109
+ font-size: 13px;
110
+ border-radius: 5px;
111
+ left: 5px;
112
+ top: 5px;
113
+ align-content: center;
114
+ justify-content: center;
115
+ text-align: center;
116
+ font-weight: bold;
117
+ float: left;
118
+ vertical-align: middle;
119
+ position: relative;
120
+ }
121
+
122
+ #custom-nodes-grid a {
123
+ color: #5555FF;
124
+ font-weight: bold;
125
+ text-decoration: none;
126
+ }
127
+
128
+ #custom-nodes-grid a:hover {
129
+ color: #7777FF;
130
+ text-decoration: underline;
131
+ }
132
+
133
+ #external-models-grid a {
134
+ color: #5555FF;
135
+ font-weight: bold;
136
+ text-decoration: none;
137
+ }
138
+
139
+ #external-models-grid a:hover {
140
+ color: #7777FF;
141
+ text-decoration: underline;
142
+ }
143
+
144
+ #alternatives-grid a {
145
+ color: #5555FF;
146
+ font-weight: bold;
147
+ text-decoration: none;
148
+ }
149
+
150
+ #alternatives-grid a:hover {
151
+ color: #7777FF;
152
+ text-decoration: underline;
153
+ }
154
+
155
+ .cm-notice-board {
156
+ width: 290px;
157
+ height: 270px;
158
+ overflow: auto;
159
+ color: var(--input-text);
160
+ border: 1px solid var(--descrip-text);
161
+ padding: 5px 10px;
162
+ overflow-x: hidden;
163
+ box-sizing: content-box;
164
+ }
165
+
166
+ .cm-notice-board > ul {
167
+ display: block;
168
+ list-style-type: disc;
169
+ margin-block-start: 1em;
170
+ margin-block-end: 1em;
171
+ margin-inline-start: 0px;
172
+ margin-inline-end: 0px;
173
+ padding-inline-start: 40px;
174
+ }
175
+
176
+ .cm-conflicted-nodes-text {
177
+ background-color: #CCCC55 !important;
178
+ color: #AA3333 !important;
179
+ font-size: 10px;
180
+ border-radius: 5px;
181
+ padding: 10px;
182
+ }
183
+
184
+ .cm-warn-note {
185
+ background-color: #101010 !important;
186
+ color: #FF3800 !important;
187
+ font-size: 13px;
188
+ border-radius: 5px;
189
+ padding: 10px;
190
+ overflow-x: hidden;
191
+ overflow: auto;
192
+ }
193
+
194
+ .cm-info-note {
195
+ background-color: #101010 !important;
196
+ color: #FF3800 !important;
197
+ font-size: 13px;
198
+ border-radius: 5px;
199
+ padding: 10px;
200
+ overflow-x: hidden;
201
+ overflow: auto;
202
+ }
203
+ `;
204
+
205
+ function is_legacy_front() {
206
+ let compareVersion = '1.2.49';
207
+ try {
208
+ const frontendVersion = window['__COMFYUI_FRONTEND_VERSION__'];
209
+ if (typeof frontendVersion !== 'string') {
210
+ return false;
211
+ }
212
+
213
+ function parseVersion(versionString) {
214
+ const parts = versionString.split('.').map(Number);
215
+ return parts.length === 3 && parts.every(part => !isNaN(part)) ? parts : null;
216
+ }
217
+
218
+ const currentVersion = parseVersion(frontendVersion);
219
+ const comparisonVersion = parseVersion(compareVersion);
220
+
221
+ if (!currentVersion || !comparisonVersion) {
222
+ return false;
223
+ }
224
+
225
+ for (let i = 0; i < 3; i++) {
226
+ if (currentVersion[i] > comparisonVersion[i]) {
227
+ return false;
228
+ } else if (currentVersion[i] < comparisonVersion[i]) {
229
+ return true;
230
+ }
231
+ }
232
+
233
+ return false;
234
+ } catch {
235
+ return true;
236
+ }
237
+ }
238
+
239
+ document.head.appendChild(docStyle);
240
+
241
+ var update_comfyui_button = null;
242
+ var fetch_updates_button = null;
243
+ var update_all_button = null;
244
+ var badge_mode = "none";
245
+ let share_option = 'all';
246
+
247
+ // copied style from https://github.com/pythongosssss/ComfyUI-Custom-Scripts
248
+ const style = `
249
+ #workflowgallery-button {
250
+ width: 310px;
251
+ height: 27px;
252
+ padding: 0px !important;
253
+ position: relative;
254
+ overflow: hidden;
255
+ font-size: 17px !important;
256
+ }
257
+ #cm-nodeinfo-button {
258
+ width: 310px;
259
+ height: 27px;
260
+ padding: 0px !important;
261
+ position: relative;
262
+ overflow: hidden;
263
+ font-size: 17px !important;
264
+ }
265
+ #cm-manual-button {
266
+ width: 310px;
267
+ height: 27px;
268
+ position: relative;
269
+ overflow: hidden;
270
+ }
271
+
272
+ .cm-button {
273
+ width: 310px;
274
+ height: 30px;
275
+ position: relative;
276
+ overflow: hidden;
277
+ font-size: 17px !important;
278
+ }
279
+
280
+ .cm-button-red {
281
+ width: 310px;
282
+ height: 30px;
283
+ position: relative;
284
+ overflow: hidden;
285
+ font-size: 17px !important;
286
+ background-color: #500000 !important;
287
+ color: white !important;
288
+ }
289
+
290
+ .cm-experimental-button {
291
+ width: 290px;
292
+ height: 30px;
293
+ position: relative;
294
+ overflow: hidden;
295
+ font-size: 17px !important;
296
+ }
297
+
298
+ .cm-experimental {
299
+ width: 310px;
300
+ border: 1px solid #555;
301
+ border-radius: 5px;
302
+ padding: 10px;
303
+ align-items: center;
304
+ text-align: center;
305
+ justify-content: center;
306
+ box-sizing: border-box;
307
+ }
308
+
309
+ .cm-experimental-legend {
310
+ margin-top: -20px;
311
+ margin-left: 50%;
312
+ width:auto;
313
+ height:20px;
314
+ font-size: 13px;
315
+ font-weight: bold;
316
+ background-color: #990000;
317
+ color: #CCFFFF;
318
+ border-radius: 5px;
319
+ text-align: center;
320
+ transform: translateX(-50%);
321
+ display: block;
322
+ }
323
+
324
+ .cm-menu-combo {
325
+ cursor: pointer;
326
+ width: 310px;
327
+ box-sizing: border-box;
328
+ }
329
+
330
+ .cm-small-button {
331
+ width: 120px;
332
+ height: 30px;
333
+ position: relative;
334
+ overflow: hidden;
335
+ box-sizing: border-box;
336
+ font-size: 17px !important;
337
+ }
338
+
339
+ #cm-install-customnodes-button {
340
+ width: 200px;
341
+ height: 30px;
342
+ position: relative;
343
+ overflow: hidden;
344
+ box-sizing: border-box;
345
+ font-size: 17px !important;
346
+ }
347
+
348
+ .cm-search-filter {
349
+ width: 200px;
350
+ height: 30px !important;
351
+ position: relative;
352
+ overflow: hidden;
353
+ box-sizing: border-box;
354
+ }
355
+
356
+ .cb-node-label {
357
+ width: 400px;
358
+ height:28px;
359
+ color: black;
360
+ background-color: #777777;
361
+ font-size: 18px;
362
+ text-align: center;
363
+ font-weight: bold;
364
+ }
365
+
366
+ #cm-close-button {
367
+ width: calc(100% - 65px);
368
+ bottom: 10px;
369
+ position: absolute;
370
+ overflow: hidden;
371
+ }
372
+
373
+ #cm-save-button {
374
+ width: calc(100% - 65px);
375
+ bottom:40px;
376
+ position: absolute;
377
+ overflow: hidden;
378
+ }
379
+ #cm-save-button:disabled {
380
+ background-color: #444444;
381
+ }
382
+
383
+ .pysssss-workflow-arrow-2 {
384
+ position: absolute;
385
+ top: 0;
386
+ bottom: 0;
387
+ right: 0;
388
+ font-size: 12px;
389
+ display: flex;
390
+ align-items: center;
391
+ width: 24px;
392
+ justify-content: center;
393
+ background: rgba(255,255,255,0.1);
394
+ content: "▼";
395
+ }
396
+ .pysssss-workflow-arrow-2:after {
397
+ content: "▼";
398
+ }
399
+ .pysssss-workflow-arrow-2:hover {
400
+ filter: brightness(1.6);
401
+ background-color: var(--comfy-menu-bg);
402
+ }
403
+ .pysssss-workflow-popup-2 ~ .litecontextmenu {
404
+ transform: scale(1.3);
405
+ }
406
+ #workflowgallery-button-menu {
407
+ z-index: 10000000000 !important;
408
+ }
409
+ #cm-manual-button-menu {
410
+ z-index: 10000000000 !important;
411
+ }
412
+ `;
413
+
414
+
415
+
416
+ async function init_badge_mode() {
417
+ api.fetchApi('/manager/badge_mode')
418
+ .then(response => response.text())
419
+ .then(data => { badge_mode = data; })
420
+ }
421
+
422
+ async function init_share_option() {
423
+ api.fetchApi('/manager/share_option')
424
+ .then(response => response.text())
425
+ .then(data => {
426
+ share_option = data || 'all';
427
+ });
428
+ }
429
+
430
+ async function init_notice(notice) {
431
+ api.fetchApi('/manager/notice')
432
+ .then(response => response.text())
433
+ .then(data => {
434
+ notice.innerHTML = data;
435
+ })
436
+ }
437
+
438
+ await init_badge_mode();
439
+ await init_share_option();
440
+
441
+ async function fetchNicknames() {
442
+ const response1 = await api.fetchApi(`/customnode/getmappings?mode=nickname`);
443
+ const mappings = await response1.json();
444
+
445
+ let result = {};
446
+ let nickname_patterns = [];
447
+
448
+ for (let i in mappings) {
449
+ let item = mappings[i];
450
+ var nickname;
451
+ if (item[1].nickname) {
452
+ nickname = item[1].nickname;
453
+ }
454
+ else if (item[1].title) {
455
+ nickname = item[1].title;
456
+ }
457
+ else {
458
+ nickname = item[1].title_aux;
459
+ }
460
+
461
+ for (let j in item[0]) {
462
+ result[item[0][j]] = nickname;
463
+ }
464
+
465
+ if(item[1].nodename_pattern) {
466
+ nickname_patterns.push([item[1].nodename_pattern, nickname]);
467
+ }
468
+ }
469
+
470
+ return [result, nickname_patterns];
471
+ }
472
+
473
+ const [nicknames, nickname_patterns] = await fetchNicknames();
474
+
475
+ function getNickname(node, nodename) {
476
+ if(node.nickname) {
477
+ return node.nickname;
478
+ }
479
+ else {
480
+ if (nicknames[nodename]) {
481
+ node.nickname = nicknames[nodename];
482
+ }
483
+ else if(node.getInnerNodes) {
484
+ let pure_name = getPureName(node);
485
+ let groupNode = app.graph.extra?.groupNodes?.[pure_name];
486
+ if(groupNode) {
487
+ let packname = groupNode.packname;
488
+ node.nickname = packname;
489
+ }
490
+ return node.nickname;
491
+ }
492
+ else {
493
+ for(let i in nickname_patterns) {
494
+ let item = nickname_patterns[i];
495
+ if(nodename.match(item[0])) {
496
+ node.nickname = item[1];
497
+ }
498
+ }
499
+ }
500
+
501
+ return node.nickname;
502
+ }
503
+ }
504
+
505
+ function drawBadge(node, orig, restArgs) {
506
+ let ctx = restArgs[0];
507
+ const r = orig?.apply?.(node, restArgs);
508
+
509
+ if (!node.flags.collapsed && badge_mode != 'none' && node.constructor.title_mode != LiteGraph.NO_TITLE) {
510
+ let text = "";
511
+ if (badge_mode.startsWith('id_nick'))
512
+ text = `#${node.id} `;
513
+
514
+ let nick = node.getNickname();
515
+ if (nick) {
516
+ if (nick == 'ComfyUI') {
517
+ if(badge_mode.endsWith('hide')) {
518
+ nick = "";
519
+ }
520
+ else {
521
+ nick = "🦊"
522
+ }
523
+ }
524
+
525
+ if (nick.length > 25) {
526
+ text += nick.substring(0, 23) + "..";
527
+ }
528
+ else {
529
+ text += nick;
530
+ }
531
+ }
532
+
533
+ if (text != "") {
534
+ let fgColor = "white";
535
+ let bgColor = "#0F1F0F";
536
+ let visible = true;
537
+
538
+ ctx.save();
539
+ ctx.font = "12px sans-serif";
540
+ const sz = ctx.measureText(text);
541
+ ctx.fillStyle = bgColor;
542
+ ctx.beginPath();
543
+ ctx.roundRect(node.size[0] - sz.width - 12, -LiteGraph.NODE_TITLE_HEIGHT - 20, sz.width + 12, 20, 5);
544
+ ctx.fill();
545
+
546
+ ctx.fillStyle = fgColor;
547
+ ctx.fillText(text, node.size[0] - sz.width - 6, -LiteGraph.NODE_TITLE_HEIGHT - 6);
548
+ ctx.restore();
549
+
550
+ if (node.has_errors) {
551
+ ctx.save();
552
+ ctx.font = "bold 14px sans-serif";
553
+ const sz2 = ctx.measureText(node.type);
554
+ ctx.fillStyle = 'white';
555
+ ctx.fillText(node.type, node.size[0] / 2 - sz2.width / 2, node.size[1] / 2);
556
+ ctx.restore();
557
+ }
558
+ }
559
+ }
560
+ return r;
561
+ }
562
+
563
+
564
+ async function updateComfyUI() {
565
+ let prev_text = update_comfyui_button.innerText;
566
+ update_comfyui_button.innerText = "Updating ComfyUI...";
567
+ update_comfyui_button.disabled = true;
568
+ update_comfyui_button.style.backgroundColor = "gray";
569
+
570
+ try {
571
+ const response = await api.fetchApi('/comfyui_manager/update_comfyui');
572
+
573
+ if (response.status == 400) {
574
+ show_message('Failed to update ComfyUI.');
575
+ return false;
576
+ }
577
+
578
+ if (response.status == 201) {
579
+ show_message('ComfyUI has been successfully updated.');
580
+ }
581
+ else {
582
+ show_message('ComfyUI is already up to date with the latest version.');
583
+ }
584
+
585
+ return true;
586
+ }
587
+ catch (exception) {
588
+ show_message(`Failed to update ComfyUI / ${exception}`);
589
+ return false;
590
+ }
591
+ finally {
592
+ update_comfyui_button.disabled = false;
593
+ update_comfyui_button.innerText = prev_text;
594
+ update_comfyui_button.style.backgroundColor = "";
595
+ }
596
+ }
597
+
598
+ async function fetchUpdates(update_check_checkbox) {
599
+ let prev_text = fetch_updates_button.innerText;
600
+ fetch_updates_button.innerText = "Fetching updates...";
601
+ fetch_updates_button.disabled = true;
602
+ fetch_updates_button.style.backgroundColor = "gray";
603
+
604
+ try {
605
+ var mode = manager_instance.datasrc_combo.value;
606
+
607
+ const response = await api.fetchApi(`/customnode/fetch_updates?mode=${mode}`);
608
+
609
+ if (response.status != 200 && response.status != 201) {
610
+ show_message('Failed to fetch updates.');
611
+ return false;
612
+ }
613
+
614
+ if (response.status == 201) {
615
+ show_message("There is an updated extension available.<BR><BR><P><B>NOTE:<BR>Fetch Updates is not an update.<BR>Please update from <button id='cm-install-customnodes-button'>Install Custom Nodes</button> </B></P>");
616
+
617
+ const button = document.getElementById('cm-install-customnodes-button');
618
+ button.addEventListener("click",
619
+ async function() {
620
+ app.ui.dialog.close();
621
+
622
+ if(!CustomNodesManager.instance) {
623
+ CustomNodesManager.instance = new CustomNodesManager(app, self);
624
+ }
625
+ await CustomNodesManager.instance.show(CustomNodesManager.ShowMode.UPDATE);
626
+ }
627
+ );
628
+
629
+ update_check_checkbox.checked = false;
630
+ }
631
+ else {
632
+ show_message('All extensions are already up-to-date with the latest versions.');
633
+ }
634
+
635
+ return true;
636
+ }
637
+ catch (exception) {
638
+ show_message(`Failed to update custom nodes / ${exception}`);
639
+ return false;
640
+ }
641
+ finally {
642
+ fetch_updates_button.disabled = false;
643
+ fetch_updates_button.innerText = prev_text;
644
+ fetch_updates_button.style.backgroundColor = "";
645
+ }
646
+ }
647
+
648
+ async function updateAll(update_check_checkbox, manager_dialog) {
649
+ let prev_text = update_all_button.innerText;
650
+ update_all_button.innerText = "Updating all...(ComfyUI)";
651
+ update_all_button.disabled = true;
652
+ update_all_button.style.backgroundColor = "gray";
653
+
654
+ try {
655
+ var mode = manager_instance.datasrc_combo.value;
656
+
657
+ update_all_button.innerText = "Updating all...";
658
+ const response1 = await api.fetchApi('/comfyui_manager/update_comfyui');
659
+ const response2 = await api.fetchApi(`/customnode/update_all?mode=${mode}`);
660
+
661
+ if (response2.status == 403) {
662
+ show_message('This action is not allowed with this security level configuration.');
663
+ return false;
664
+ }
665
+
666
+ if (response1.status == 400 || response2.status == 400) {
667
+ show_message('Failed to update ComfyUI or several extensions.<BR><BR>See terminal log.<BR>');
668
+ return false;
669
+ }
670
+
671
+ if(response1.status == 201 || response2.status == 201) {
672
+ const update_info = await response2.json();
673
+
674
+ let failed_list = "";
675
+ if(update_info.failed.length > 0) {
676
+ failed_list = "<BR>FAILED: "+update_info.failed.join(", ");
677
+ }
678
+
679
+ let updated_list = "";
680
+ if(update_info.updated.length > 0) {
681
+ updated_list = "<BR>UPDATED: "+update_info.updated.join(", ");
682
+ }
683
+
684
+ show_message(
685
+ "ComfyUI and all extensions have been updated to the latest version.<BR>To apply the updated custom node, please <button class='cm-small-button' id='cm-reboot-button5'>RESTART</button> ComfyUI. And refresh browser.<BR>"
686
+ +failed_list
687
+ +updated_list
688
+ );
689
+
690
+ const rebootButton = document.getElementById('cm-reboot-button5');
691
+ rebootButton.addEventListener("click",
692
+ function() {
693
+ if(rebootAPI()) {
694
+ manager_dialog.close();
695
+ }
696
+ });
697
+ }
698
+ else {
699
+ show_message('ComfyUI and all extensions are already up-to-date with the latest versions.');
700
+ }
701
+
702
+ return true;
703
+ }
704
+ catch (exception) {
705
+ show_message(`Failed to update ComfyUI or several extensions / ${exception}`);
706
+ return false;
707
+ }
708
+ finally {
709
+ update_all_button.disabled = false;
710
+ update_all_button.innerText = prev_text;
711
+ update_all_button.style.backgroundColor = "";
712
+ }
713
+ }
714
+
715
+ function newDOMTokenList(initialTokens) {
716
+ const tmp = document.createElement(`div`);
717
+
718
+ const classList = tmp.classList;
719
+ if (initialTokens) {
720
+ initialTokens.forEach(token => {
721
+ classList.add(token);
722
+ });
723
+ }
724
+
725
+ return classList;
726
+ }
727
+
728
+ /**
729
+ * Check whether the node is a potential output node (img, gif or video output)
730
+ */
731
+ const isOutputNode = (node) => {
732
+ return SUPPORTED_OUTPUT_NODE_TYPES.includes(node.type);
733
+ }
734
+
735
+ // -----------
736
+ class ManagerMenuDialog extends ComfyDialog {
737
+ createControlsMid() {
738
+ let self = this;
739
+
740
+ update_comfyui_button =
741
+ $el("button.cm-button", {
742
+ type: "button",
743
+ textContent: "Update ComfyUI",
744
+ onclick:
745
+ () => updateComfyUI()
746
+ });
747
+
748
+ fetch_updates_button =
749
+ $el("button.cm-button", {
750
+ type: "button",
751
+ textContent: "Fetch Updates",
752
+ onclick:
753
+ () => fetchUpdates(this.update_check_checkbox)
754
+ });
755
+
756
+ update_all_button =
757
+ $el("button.cm-button", {
758
+ type: "button",
759
+ textContent: "Update All",
760
+ onclick:
761
+ () => updateAll(this.update_check_checkbox, self)
762
+ });
763
+
764
+ const res =
765
+ [
766
+ $el("button.cm-button", {
767
+ type: "button",
768
+ textContent: "Custom Nodes Manager",
769
+ onclick:
770
+ () => {
771
+ if(!CustomNodesManager.instance) {
772
+ CustomNodesManager.instance = new CustomNodesManager(app, self);
773
+ }
774
+ CustomNodesManager.instance.show(CustomNodesManager.ShowMode.NORMAL);
775
+ }
776
+ }),
777
+
778
+ $el("button.cm-button", {
779
+ type: "button",
780
+ textContent: "Install Missing Custom Nodes",
781
+ onclick:
782
+ () => {
783
+ if(!CustomNodesManager.instance) {
784
+ CustomNodesManager.instance = new CustomNodesManager(app, self);
785
+ }
786
+ CustomNodesManager.instance.show(CustomNodesManager.ShowMode.MISSING);
787
+ }
788
+ }),
789
+
790
+
791
+ $el("button.cm-button", {
792
+ type: "button",
793
+ textContent: "Model Manager",
794
+ onclick:
795
+ () => {
796
+ if(!ModelManager.instance) {
797
+ ModelManager.instance = new ModelManager(app, self);
798
+ }
799
+ ModelManager.instance.show();
800
+ }
801
+ }),
802
+
803
+ $el("button.cm-button", {
804
+ type: "button",
805
+ textContent: "Install via Git URL",
806
+ onclick: () => {
807
+ var url = prompt("Please enter the URL of the Git repository to install", "");
808
+
809
+ if (url !== null) {
810
+ install_via_git_url(url, self);
811
+ }
812
+ }
813
+ }),
814
+
815
+ $el("br", {}, []),
816
+ update_all_button,
817
+ update_comfyui_button,
818
+ fetch_updates_button,
819
+
820
+ $el("br", {}, []),
821
+ $el("button.cm-button", {
822
+ type: "button",
823
+ textContent: "Alternatives of A1111",
824
+ onclick:
825
+ () => {
826
+ if(!CustomNodesManager.instance) {
827
+ CustomNodesManager.instance = new CustomNodesManager(app, self);
828
+ }
829
+ CustomNodesManager.instance.show(CustomNodesManager.ShowMode.ALTERNATIVES);
830
+ }
831
+ }),
832
+
833
+ $el("br", {}, []),
834
+ $el("button.cm-button-red", {
835
+ type: "button",
836
+ textContent: "Restart",
837
+ onclick: () => rebootAPI()
838
+ }),
839
+ ];
840
+
841
+ return res;
842
+ }
843
+
844
+ createControlsLeft() {
845
+ let self = this;
846
+
847
+ this.update_check_checkbox = $el("input",{type:'checkbox', id:"skip_update_check"},[])
848
+ const uc_checkbox_text = $el("label",{for:"skip_update_check"},[" Skip update check"])
849
+ uc_checkbox_text.style.color = "var(--fg-color)";
850
+ uc_checkbox_text.style.cursor = "pointer";
851
+ this.update_check_checkbox.checked = true;
852
+
853
+ // db mode
854
+ this.datasrc_combo = document.createElement("select");
855
+ 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.");
856
+ this.datasrc_combo.className = "cm-menu-combo";
857
+ this.datasrc_combo.appendChild($el('option', { value: 'cache', text: 'DB: Channel (1day cache)' }, []));
858
+ this.datasrc_combo.appendChild($el('option', { value: 'local', text: 'DB: Local' }, []));
859
+ this.datasrc_combo.appendChild($el('option', { value: 'url', text: 'DB: Channel (remote)' }, []));
860
+
861
+ // preview method
862
+ let preview_combo = document.createElement("select");
863
+ preview_combo.setAttribute("title", "Configure how latent variables will be decoded during preview in the sampling process.");
864
+ preview_combo.className = "cm-menu-combo";
865
+ preview_combo.appendChild($el('option', { value: 'auto', text: 'Preview method: Auto' }, []));
866
+ preview_combo.appendChild($el('option', { value: 'taesd', text: 'Preview method: TAESD (slow)' }, []));
867
+ preview_combo.appendChild($el('option', { value: 'latent2rgb', text: 'Preview method: Latent2RGB (fast)' }, []));
868
+ preview_combo.appendChild($el('option', { value: 'none', text: 'Preview method: None (very fast)' }, []));
869
+
870
+ api.fetchApi('/manager/preview_method')
871
+ .then(response => response.text())
872
+ .then(data => { preview_combo.value = data; });
873
+
874
+ preview_combo.addEventListener('change', function (event) {
875
+ api.fetchApi(`/manager/preview_method?value=${event.target.value}`);
876
+ });
877
+
878
+ // nickname
879
+ let badge_combo = "";
880
+ if(is_legacy_front()) {
881
+ badge_combo = document.createElement("select");
882
+ badge_combo.setAttribute("title", "Configure the content to be displayed on the badge at the top right corner of the node. The ID is the identifier of the node. If 'hide built-in' is selected, both unknown nodes and built-in nodes will be omitted, making them indistinguishable");
883
+ badge_combo.className = "cm-menu-combo";
884
+ badge_combo.appendChild($el('option', { value: 'none', text: 'Badge: None' }, []));
885
+ badge_combo.appendChild($el('option', { value: 'nick', text: 'Badge: Nickname' }, []));
886
+ badge_combo.appendChild($el('option', { value: 'nick_hide', text: 'Badge: Nickname (hide built-in)' }, []));
887
+ badge_combo.appendChild($el('option', { value: 'id_nick', text: 'Badge: #ID Nickname' }, []));
888
+ badge_combo.appendChild($el('option', { value: 'id_nick_hide', text: 'Badge: #ID Nickname (hide built-in)' }, []));
889
+
890
+ api.fetchApi('/manager/badge_mode')
891
+ .then(response => response.text())
892
+ .then(data => { badge_combo.value = data; badge_mode = data; });
893
+
894
+ badge_combo.addEventListener('change', function (event) {
895
+ api.fetchApi(`/manager/badge_mode?value=${event.target.value}`);
896
+ badge_mode = event.target.value;
897
+ app.graph.setDirtyCanvas(true);
898
+ });
899
+ }
900
+
901
+ // channel
902
+ let channel_combo = document.createElement("select");
903
+ channel_combo.setAttribute("title", "Configure the channel for retrieving data from the Custom Node list (including missing nodes) or the Model list. Note that the badge utilizes local information.");
904
+ channel_combo.className = "cm-menu-combo";
905
+ api.fetchApi('/manager/channel_url_list')
906
+ .then(response => response.json())
907
+ .then(async data => {
908
+ try {
909
+ let urls = data.list;
910
+ for (let i in urls) {
911
+ if (urls[i] != '') {
912
+ let name_url = urls[i].split('::');
913
+ channel_combo.appendChild($el('option', { value: name_url[0], text: `Channel: ${name_url[0]}` }, []));
914
+ }
915
+ }
916
+
917
+ channel_combo.addEventListener('change', function (event) {
918
+ api.fetchApi(`/manager/channel_url_list?value=${event.target.value}`);
919
+ });
920
+
921
+ channel_combo.value = data.selected;
922
+ }
923
+ catch (exception) {
924
+
925
+ }
926
+ });
927
+
928
+ // default ui state
929
+ let default_ui_combo = document.createElement("select");
930
+ default_ui_combo.setAttribute("title", "Set the default state to be displayed in the main menu when the browser starts.");
931
+ default_ui_combo.className = "cm-menu-combo";
932
+ default_ui_combo.appendChild($el('option', { value: 'none', text: 'Default UI: None' }, []));
933
+ default_ui_combo.appendChild($el('option', { value: 'history', text: 'Default UI: History' }, []));
934
+ default_ui_combo.appendChild($el('option', { value: 'queue', text: 'Default UI: Queue' }, []));
935
+ api.fetchApi('/manager/default_ui')
936
+ .then(response => response.text())
937
+ .then(data => { default_ui_combo.value = data; });
938
+
939
+ default_ui_combo.addEventListener('change', function (event) {
940
+ api.fetchApi(`/manager/default_ui?value=${event.target.value}`);
941
+ });
942
+
943
+
944
+ // share
945
+ let share_combo = document.createElement("select");
946
+ 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.");
947
+ share_combo.className = "cm-menu-combo";
948
+ const share_options = [
949
+ ['none', 'None'],
950
+ ['openart', 'OpenArt AI'],
951
+ ['youml', 'YouML'],
952
+ ['matrix', 'Matrix Server'],
953
+ ['comfyworkflows', 'ComfyWorkflows'],
954
+ ['copus', 'Copus'],
955
+ ['all', 'All'],
956
+ ];
957
+ for (const option of share_options) {
958
+ share_combo.appendChild($el('option', { value: option[0], text: `Share: ${option[1]}` }, []));
959
+ }
960
+
961
+ // default ui state
962
+ let component_policy_combo = document.createElement("select");
963
+ component_policy_combo.setAttribute("title", "When loading the workflow, configure which version of the component to use.");
964
+ component_policy_combo.className = "cm-menu-combo";
965
+ component_policy_combo.appendChild($el('option', { value: 'workflow', text: 'Component: Use workflow version' }, []));
966
+ component_policy_combo.appendChild($el('option', { value: 'higher', text: 'Component: Use higher version' }, []));
967
+ component_policy_combo.appendChild($el('option', { value: 'mine', text: 'Component: Use my version' }, []));
968
+ api.fetchApi('/manager/component/policy')
969
+ .then(response => response.text())
970
+ .then(data => {
971
+ component_policy_combo.value = data;
972
+ set_component_policy(data);
973
+ });
974
+
975
+ component_policy_combo.addEventListener('change', function (event) {
976
+ api.fetchApi(`/manager/component/policy?value=${event.target.value}`);
977
+ set_component_policy(event.target.value);
978
+ });
979
+
980
+ let dbl_click_policy_combo = document.createElement("select");
981
+ dbl_click_policy_combo.setAttribute("title", "Sets the behavior when you double-click the title area of a node.");
982
+ dbl_click_policy_combo.className = "cm-menu-combo";
983
+ dbl_click_policy_combo.appendChild($el('option', { value: 'none', text: 'Double-Click: None' }, []));
984
+ dbl_click_policy_combo.appendChild($el('option', { value: 'copy-all', text: 'Double-Click: Copy All Connections' }, []));
985
+ dbl_click_policy_combo.appendChild($el('option', { value: 'copy-full', text: 'Double-Click: Copy All Connections and shape' }, []));
986
+ dbl_click_policy_combo.appendChild($el('option', { value: 'copy-input', text: 'Double-Click: Copy Input Connections' }, []));
987
+ dbl_click_policy_combo.appendChild($el('option', { value: 'possible-input', text: 'Double-Click: Possible Input Connections' }, []));
988
+ dbl_click_policy_combo.appendChild($el('option', { value: 'dual', text: 'Double-Click: Possible(left) + Copy(right)' }, []));
989
+
990
+ api.fetchApi('/manager/dbl_click/policy')
991
+ .then(response => response.text())
992
+ .then(data => {
993
+ dbl_click_policy_combo.value = data;
994
+ set_double_click_policy(data);
995
+ });
996
+
997
+ dbl_click_policy_combo.addEventListener('change', function (event) {
998
+ api.fetchApi(`/manager/dbl_click/policy?value=${event.target.value}`);
999
+ set_double_click_policy(event.target.value);
1000
+ });
1001
+
1002
+ api.fetchApi('/manager/share_option')
1003
+ .then(response => response.text())
1004
+ .then(data => {
1005
+ share_combo.value = data || 'all';
1006
+ share_option = data || 'all';
1007
+ });
1008
+
1009
+ share_combo.addEventListener('change', function (event) {
1010
+ const value = event.target.value;
1011
+ share_option = value;
1012
+ api.fetchApi(`/manager/share_option?value=${value}`);
1013
+ const shareButton = document.getElementById("shareButton");
1014
+ if (value === 'none') {
1015
+ shareButton.style.display = "none";
1016
+ } else {
1017
+ shareButton.style.display = "inline-block";
1018
+ }
1019
+ });
1020
+
1021
+ return [
1022
+ $el("div", {}, [this.update_check_checkbox, uc_checkbox_text]),
1023
+ $el("br", {}, []),
1024
+ this.datasrc_combo,
1025
+ channel_combo,
1026
+ preview_combo,
1027
+ badge_combo,
1028
+ default_ui_combo,
1029
+ share_combo,
1030
+ component_policy_combo,
1031
+ dbl_click_policy_combo,
1032
+ $el("br", {}, []),
1033
+
1034
+ $el("br", {}, []),
1035
+ $el("filedset.cm-experimental", {}, [
1036
+ $el("legend.cm-experimental-legend", {}, ["EXPERIMENTAL"]),
1037
+ $el("button.cm-experimental-button", {
1038
+ type: "button",
1039
+ textContent: "Snapshot Manager",
1040
+ onclick:
1041
+ () => {
1042
+ if(!SnapshotManager.instance)
1043
+ SnapshotManager.instance = new SnapshotManager(app, self);
1044
+ SnapshotManager.instance.show();
1045
+ }
1046
+ }),
1047
+ $el("button.cm-experimental-button", {
1048
+ type: "button",
1049
+ textContent: "Install PIP packages",
1050
+ onclick:
1051
+ () => {
1052
+ var url = prompt("Please enumerate the pip packages to be installed.\n\nExample: insightface opencv-python-headless>=4.1.1\n", "");
1053
+
1054
+ if (url !== null) {
1055
+ install_pip(url, self);
1056
+ }
1057
+ }
1058
+ }),
1059
+ $el("button.cm-experimental-button", {
1060
+ type: "button",
1061
+ textContent: "Unload models",
1062
+ onclick: () => { free_models(); }
1063
+ })
1064
+ ]),
1065
+ ];
1066
+ }
1067
+
1068
+ createControlsRight() {
1069
+ const elts = [
1070
+ $el("button.cm-button", {
1071
+ id: 'cm-manual-button',
1072
+ type: "button",
1073
+ textContent: "Community Manual",
1074
+ onclick: () => { window.open("https://blenderneko.github.io/ComfyUI-docs/", "comfyui-community-manual"); }
1075
+ }, [
1076
+ $el("div.pysssss-workflow-arrow-2", {
1077
+ id: `cm-manual-button-arrow`,
1078
+ onclick: (e) => {
1079
+ e.preventDefault();
1080
+ e.stopPropagation();
1081
+
1082
+ LiteGraph.closeAllContextMenus();
1083
+ const menu = new LiteGraph.ContextMenu(
1084
+ [
1085
+ {
1086
+ title: "ComfyUI Docs",
1087
+ callback: () => { window.open("https://docs.comfy.org/", "comfyui-official-manual"); },
1088
+ },
1089
+ {
1090
+ title: "Comfy Custom Node How To",
1091
+ callback: () => { window.open("https://github.com/chrisgoringe/Comfy-Custom-Node-How-To/wiki/aaa_index", "comfyui-community-manual1"); },
1092
+ },
1093
+ {
1094
+ title: "ComfyUI Guide To Making Custom Nodes",
1095
+ callback: () => { window.open("https://github.com/Suzie1/ComfyUI_Guide_To_Making_Custom_Nodes/wiki", "comfyui-community-manual2"); },
1096
+ },
1097
+ {
1098
+ title: "ComfyUI Examples",
1099
+ callback: () => { window.open("https://comfyanonymous.github.io/ComfyUI_examples", "comfyui-community-manual3"); },
1100
+ },
1101
+ {
1102
+ title: "Close",
1103
+ callback: () => {
1104
+ LiteGraph.closeAllContextMenus();
1105
+ },
1106
+ }
1107
+ ],
1108
+ {
1109
+ event: e,
1110
+ scale: 1.3,
1111
+ },
1112
+ window
1113
+ );
1114
+ // set the id so that we can override the context menu's z-index to be above the comfyui manager menu
1115
+ menu.root.id = "cm-manual-button-menu";
1116
+ menu.root.classList.add("pysssss-workflow-popup-2");
1117
+ },
1118
+ })
1119
+ ]),
1120
+
1121
+ $el("button", {
1122
+ id: 'workflowgallery-button',
1123
+ type: "button",
1124
+ style: {
1125
+ ...(localStorage.getItem("wg_last_visited") ? {height: '50px'} : {})
1126
+ },
1127
+ onclick: (e) => {
1128
+ const last_visited_site = localStorage.getItem("wg_last_visited")
1129
+ if (!!last_visited_site) {
1130
+ window.open(last_visited_site, last_visited_site);
1131
+ } else {
1132
+ this.handleWorkflowGalleryButtonClick(e)
1133
+ }
1134
+ },
1135
+ }, [
1136
+ $el("p", {
1137
+ textContent: 'Workflow Gallery',
1138
+ style: {
1139
+ 'text-align': 'center',
1140
+ 'color': 'var(--input-text)',
1141
+ 'font-size': '18px',
1142
+ 'margin': 0,
1143
+ 'padding': 0,
1144
+ }
1145
+ }, [
1146
+ $el("p", {
1147
+ id: 'workflowgallery-button-last-visited-label',
1148
+ textContent: `(${localStorage.getItem("wg_last_visited") ? localStorage.getItem("wg_last_visited").split('/')[2] : ''})`,
1149
+ style: {
1150
+ 'text-align': 'center',
1151
+ 'color': 'var(--input-text)',
1152
+ 'font-size': '12px',
1153
+ 'margin': 0,
1154
+ 'padding': 0,
1155
+ }
1156
+ })
1157
+ ]),
1158
+ $el("div.pysssss-workflow-arrow-2", {
1159
+ id: `comfyworkflows-button-arrow`,
1160
+ onclick: this.handleWorkflowGalleryButtonClick
1161
+ })
1162
+ ]),
1163
+
1164
+ $el("button.cm-button", {
1165
+ id: 'cm-nodeinfo-button',
1166
+ type: "button",
1167
+ textContent: "Nodes Info",
1168
+ onclick: () => { window.open("https://ltdrdata.github.io/", "comfyui-node-info"); }
1169
+ }),
1170
+ $el("br", {}, []),
1171
+ ];
1172
+
1173
+ var textarea = document.createElement("div");
1174
+ textarea.className = "cm-notice-board";
1175
+ elts.push(textarea);
1176
+
1177
+ init_notice(textarea);
1178
+
1179
+ return elts;
1180
+ }
1181
+
1182
+ constructor() {
1183
+ super();
1184
+
1185
+ const close_button = $el("button", { id: "cm-close-button", type: "button", textContent: "Close", onclick: () => this.close() });
1186
+
1187
+ const content =
1188
+ $el("div.comfy-modal-content",
1189
+ [
1190
+ $el("tr.cm-title", {}, [
1191
+ $el("font", {size:6, color:"white"}, [`ComfyUI Manager Menu`])]
1192
+ ),
1193
+ $el("br", {}, []),
1194
+ $el("div.cm-menu-container",
1195
+ [
1196
+ $el("div.cm-menu-column", [...this.createControlsLeft()]),
1197
+ $el("div.cm-menu-column", [...this.createControlsMid()]),
1198
+ $el("div.cm-menu-column", [...this.createControlsRight()])
1199
+ ]),
1200
+
1201
+ $el("br", {}, []),
1202
+ close_button,
1203
+ ]
1204
+ );
1205
+
1206
+ content.style.width = '100%';
1207
+ content.style.height = '100%';
1208
+
1209
+ this.element = $el("div.comfy-modal", { id:'cm-manager-dialog', parent: document.body }, [ content ]);
1210
+ }
1211
+
1212
+ show() {
1213
+ this.element.style.display = "block";
1214
+ }
1215
+
1216
+ handleWorkflowGalleryButtonClick(e) {
1217
+ e.preventDefault();
1218
+ e.stopPropagation();
1219
+ LiteGraph.closeAllContextMenus();
1220
+
1221
+ // Modify the style of the button so that the UI can indicate the last
1222
+ // visited site right away.
1223
+ const modifyButtonStyle = (url) => {
1224
+ const workflowGalleryButton = document.getElementById('workflowgallery-button');
1225
+ workflowGalleryButton.style.height = '50px';
1226
+ const lastVisitedLabel = document.getElementById('workflowgallery-button-last-visited-label');
1227
+ lastVisitedLabel.textContent = `(${url.split('/')[2]})`;
1228
+ }
1229
+
1230
+ const menu = new LiteGraph.ContextMenu(
1231
+ [
1232
+ {
1233
+ title: "Share your art",
1234
+ callback: () => {
1235
+ if (share_option === 'openart') {
1236
+ showOpenArtShareDialog();
1237
+ return;
1238
+ } else if (share_option === 'matrix' || share_option === 'comfyworkflows') {
1239
+ showShareDialog(share_option);
1240
+ return;
1241
+ } else if (share_option === 'youml') {
1242
+ showYouMLShareDialog();
1243
+ return;
1244
+ }
1245
+
1246
+ if (!ShareDialogChooser.instance) {
1247
+ ShareDialogChooser.instance = new ShareDialogChooser();
1248
+ }
1249
+ ShareDialogChooser.instance.show();
1250
+ },
1251
+ },
1252
+ {
1253
+ title: "Open 'openart.ai'",
1254
+ callback: () => {
1255
+ const url = "https://openart.ai/workflows/dev";
1256
+ localStorage.setItem("wg_last_visited", url);
1257
+ window.open(url, url);
1258
+ modifyButtonStyle(url);
1259
+ },
1260
+ },
1261
+ {
1262
+ title: "Open 'youml.com'",
1263
+ callback: () => {
1264
+ const url = "https://youml.com/?from=comfyui-share";
1265
+ localStorage.setItem("wg_last_visited", url);
1266
+ window.open(url, url);
1267
+ modifyButtonStyle(url);
1268
+ },
1269
+ },
1270
+ {
1271
+ title: "Open 'comfyworkflows.com'",
1272
+ callback: () => {
1273
+ const url = "https://comfyworkflows.com/";
1274
+ localStorage.setItem("wg_last_visited", url);
1275
+ window.open(url, url);
1276
+ modifyButtonStyle(url);
1277
+ },
1278
+ },
1279
+ {
1280
+ title: "Open 'esheep'",
1281
+ callback: () => {
1282
+ const url = "https://www.esheep.com";
1283
+ localStorage.setItem("wg_last_visited", url);
1284
+ window.open(url, url);
1285
+ modifyButtonStyle(url);
1286
+ },
1287
+ },
1288
+ {
1289
+ title: "Open 'Copus.io'",
1290
+ callback: () => {
1291
+ const url = "https://www.copus.io";
1292
+ localStorage.setItem("wg_last_visited", url);
1293
+ window.open(url, url);
1294
+ modifyButtonStyle(url);
1295
+ },
1296
+ },
1297
+ {
1298
+ title: "Close",
1299
+ callback: () => {
1300
+ LiteGraph.closeAllContextMenus();
1301
+ },
1302
+ }
1303
+ ],
1304
+ {
1305
+ event: e,
1306
+ scale: 1.3,
1307
+ },
1308
+ window
1309
+ );
1310
+ // set the id so that we can override the context menu's z-index to be above the comfyui manager menu
1311
+ menu.root.id = "workflowgallery-button-menu";
1312
+ menu.root.classList.add("pysssss-workflow-popup-2");
1313
+ }
1314
+ }
1315
+
1316
+
1317
+ app.registerExtension({
1318
+ name: "Comfy.ManagerMenu",
1319
+ init() {
1320
+ $el("style", {
1321
+ textContent: style,
1322
+ parent: document.head,
1323
+ });
1324
+ },
1325
+ async setup() {
1326
+ let orig_clear = app.graph.clear;
1327
+ app.graph.clear = function () {
1328
+ orig_clear.call(app.graph);
1329
+ load_components();
1330
+ };
1331
+
1332
+ load_components();
1333
+
1334
+ const menu = document.querySelector(".comfy-menu");
1335
+ const separator = document.createElement("hr");
1336
+
1337
+ separator.style.margin = "20px 0";
1338
+ separator.style.width = "100%";
1339
+ menu.append(separator);
1340
+
1341
+ try {
1342
+ // new style Manager buttons
1343
+
1344
+ // unload models button into new style Manager button
1345
+ let cmGroup = new (await import("../../scripts/ui/components/buttonGroup.js")).ComfyButtonGroup(
1346
+ new(await import("../../scripts/ui/components/button.js")).ComfyButton({
1347
+ icon: "puzzle",
1348
+ action: () => {
1349
+ if(!manager_instance)
1350
+ setManagerInstance(new ManagerMenuDialog());
1351
+ manager_instance.show();
1352
+ },
1353
+ tooltip: "ComfyUI Manager",
1354
+ content: "Manager",
1355
+ classList: "comfyui-button comfyui-menu-mobile-collapse primary"
1356
+ }).element,
1357
+ new(await import("../../scripts/ui/components/button.js")).ComfyButton({
1358
+ icon: "vacuum-outline",
1359
+ action: () => {
1360
+ free_models();
1361
+ },
1362
+ tooltip: "Unload Models"
1363
+ }).element,
1364
+ new(await import("../../scripts/ui/components/button.js")).ComfyButton({
1365
+ icon: "vacuum",
1366
+ action: () => {
1367
+ free_models(true);
1368
+ },
1369
+ tooltip: "Free model and node cache"
1370
+ }).element,
1371
+ new(await import("../../scripts/ui/components/button.js")).ComfyButton({
1372
+ icon: "share",
1373
+ action: () => {
1374
+ if (share_option === 'openart') {
1375
+ showOpenArtShareDialog();
1376
+ return;
1377
+ } else if (share_option === 'matrix' || share_option === 'comfyworkflows') {
1378
+ showShareDialog(share_option);
1379
+ return;
1380
+ } else if (share_option === 'youml') {
1381
+ showYouMLShareDialog();
1382
+ return;
1383
+ }
1384
+
1385
+ if(!ShareDialogChooser.instance) {
1386
+ ShareDialogChooser.instance = new ShareDialogChooser();
1387
+ }
1388
+ ShareDialogChooser.instance.show();
1389
+ },
1390
+ tooltip: "Share"
1391
+ }).element
1392
+ );
1393
+
1394
+ app.menu?.settingsGroup.element.before(cmGroup.element);
1395
+ }
1396
+ catch(exception) {
1397
+ console.log('ComfyUI is outdated. New style menu based features are disabled.');
1398
+ }
1399
+
1400
+ // old style Manager button
1401
+ const managerButton = document.createElement("button");
1402
+ managerButton.textContent = "Manager";
1403
+ managerButton.onclick = () => {
1404
+ if(!manager_instance)
1405
+ setManagerInstance(new ManagerMenuDialog());
1406
+ manager_instance.show();
1407
+ }
1408
+ menu.append(managerButton);
1409
+
1410
+ const shareButton = document.createElement("button");
1411
+ shareButton.id = "shareButton";
1412
+ shareButton.textContent = "Share";
1413
+ shareButton.onclick = () => {
1414
+ if (share_option === 'openart') {
1415
+ showOpenArtShareDialog();
1416
+ return;
1417
+ } else if (share_option === 'matrix' || share_option === 'comfyworkflows') {
1418
+ showShareDialog(share_option);
1419
+ return;
1420
+ } else if (share_option === 'youml') {
1421
+ showYouMLShareDialog();
1422
+ return;
1423
+ }
1424
+
1425
+ if(!ShareDialogChooser.instance) {
1426
+ ShareDialogChooser.instance = new ShareDialogChooser();
1427
+ }
1428
+ ShareDialogChooser.instance.show();
1429
+ }
1430
+ // make the background color a gradient of blue to green
1431
+ shareButton.style.background = "linear-gradient(90deg, #00C9FF 0%, #92FE9D 100%)";
1432
+ shareButton.style.color = "black";
1433
+
1434
+ // Load share option from local storage to determine whether to show
1435
+ // the share button.
1436
+ const shouldShowShareButton = share_option !== 'none';
1437
+ shareButton.style.display = shouldShowShareButton ? "inline-block" : "none";
1438
+
1439
+ menu.append(shareButton);
1440
+ },
1441
+
1442
+ async beforeRegisterNodeDef(nodeType, nodeData, app) {
1443
+ this._addExtraNodeContextMenu(nodeType, app);
1444
+ },
1445
+
1446
+ async nodeCreated(node, app) {
1447
+ if(is_legacy_front()) {
1448
+ if(!node.badge_enabled) {
1449
+ node.getNickname = function () { return getNickname(node, node.comfyClass.trim()) };
1450
+ let orig = node.onDrawForeground;
1451
+ if(!orig)
1452
+ orig = node.__proto__.onDrawForeground;
1453
+
1454
+ node.onDrawForeground = function (ctx) {
1455
+ drawBadge(node, orig, arguments)
1456
+ };
1457
+ node.badge_enabled = true;
1458
+ }
1459
+ }
1460
+ },
1461
+
1462
+ async loadedGraphNode(node, app) {
1463
+ if(is_legacy_front()) {
1464
+ if(!node.badge_enabled) {
1465
+ const orig = node.onDrawForeground;
1466
+ node.getNickname = function () { return getNickname(node, node.type.trim()) };
1467
+ node.onDrawForeground = function (ctx) { drawBadge(node, orig, arguments) };
1468
+ }
1469
+ }
1470
+ },
1471
+
1472
+ _addExtraNodeContextMenu(node, app) {
1473
+ const origGetExtraMenuOptions = node.prototype.getExtraMenuOptions;
1474
+ node.prototype.cm_menu_added = true;
1475
+ node.prototype.getExtraMenuOptions = function (_, options) {
1476
+ origGetExtraMenuOptions?.apply?.(this, arguments);
1477
+
1478
+ if (node.category.startsWith('group nodes>')) {
1479
+ options.push({
1480
+ content: "Save As Component",
1481
+ callback: (obj) => {
1482
+ if (!ComponentBuilderDialog.instance) {
1483
+ ComponentBuilderDialog.instance = new ComponentBuilderDialog();
1484
+ }
1485
+ ComponentBuilderDialog.instance.target_node = node;
1486
+ ComponentBuilderDialog.instance.show();
1487
+ }
1488
+ }, null);
1489
+ }
1490
+
1491
+ if (isOutputNode(node)) {
1492
+ const { potential_outputs } = getPotentialOutputsAndOutputNodes([this]);
1493
+ const hasOutput = potential_outputs.length > 0;
1494
+
1495
+ // Check if the previous menu option is `null`. If it's not,
1496
+ // then we need to add a `null` as a separator.
1497
+ if (options[options.length - 1] !== null) {
1498
+ options.push(null);
1499
+ }
1500
+
1501
+ options.push({
1502
+ content: "🏞️ Share Output",
1503
+ disabled: !hasOutput,
1504
+ callback: (obj) => {
1505
+ if (!ShareDialog.instance) {
1506
+ ShareDialog.instance = new ShareDialog();
1507
+ }
1508
+ const shareButton = document.getElementById("shareButton");
1509
+ if (shareButton) {
1510
+ const currentNode = this;
1511
+ if (!OpenArtShareDialog.instance) {
1512
+ OpenArtShareDialog.instance = new OpenArtShareDialog();
1513
+ }
1514
+ OpenArtShareDialog.instance.selectedNodeId = currentNode.id;
1515
+ if (!ShareDialog.instance) {
1516
+ ShareDialog.instance = new ShareDialog(share_option);
1517
+ }
1518
+ ShareDialog.instance.selectedNodeId = currentNode.id;
1519
+ shareButton.click();
1520
+ }
1521
+ }
1522
+ }, null);
1523
+ }
1524
+ }
1525
+ },
1526
+ });
1527
+
1528
+
1529
+ async function set_default_ui()
1530
+ {
1531
+ let res = await api.fetchApi('/manager/default_ui');
1532
+ if(res.status == 200) {
1533
+ let mode = await res.text();
1534
+ switch(mode) {
1535
+ case 'history':
1536
+ app.ui.queue.hide();
1537
+ app.ui.history.show();
1538
+ break;
1539
+ case 'queue':
1540
+ app.ui.queue.show();
1541
+ app.ui.history.hide();
1542
+ break;
1543
+ default:
1544
+ // do nothing
1545
+ break;
1546
+ }
1547
+ }
1548
+ }
1549
+
1550
+ set_default_ui();
ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-share-common.js ADDED
@@ -0,0 +1,1064 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
8
+ export const SUPPORTED_OUTPUT_NODE_TYPES = [
9
+ "PreviewImage",
10
+ "SaveImage",
11
+ "VHS_VideoCombine",
12
+ "ADE_AnimateDiffCombine",
13
+ "SaveAnimatedWEBP",
14
+ "CR Image Output"
15
+ ]
16
+
17
+ var docStyle = document.createElement('style');
18
+ docStyle.innerHTML = `
19
+ .cm-menu-container {
20
+ column-gap: 20px;
21
+ display: flex;
22
+ flex-wrap: wrap;
23
+ justify-content: center;
24
+ }
25
+
26
+ .cm-menu-column {
27
+ display: flex;
28
+ flex-direction: column;
29
+ }
30
+
31
+ .cm-title {
32
+ padding: 10px 10px 0 10p;
33
+ background-color: black;
34
+ text-align: center;
35
+ height: 45px;
36
+ }
37
+ `;
38
+ document.head.appendChild(docStyle);
39
+
40
+ export function getPotentialOutputsAndOutputNodes(nodes) {
41
+ const potential_outputs = [];
42
+ const potential_output_nodes = [];
43
+
44
+ // iterate over the array of nodes to find the ones that are marked as SaveImage
45
+ // TODO: Add support for AnimateDiffCombine, etc. nodes that save videos/gifs, etc.
46
+ for (let i = 0; i < nodes.length; i++) {
47
+ const node = nodes[i];
48
+ if (!SUPPORTED_OUTPUT_NODE_TYPES.includes(node.type)) {
49
+ continue;
50
+ }
51
+
52
+ if (node.type === "SaveImage" || node.type === "CR Image Output") {
53
+ // check if node has an 'images' array property
54
+ if (node.hasOwnProperty("images") && Array.isArray(node.images)) {
55
+ // iterate over the images array and add each image to the potential_outputs array
56
+ for (let j = 0; j < node.images.length; j++) {
57
+ potential_output_nodes.push(node);
58
+ potential_outputs.push({ "type": "image", "image": node.images[j], "title": node.title, "node_id": node.id });
59
+ }
60
+ }
61
+ }
62
+ else if (node.type === "PreviewImage") {
63
+ // check if node has an 'images' array property
64
+ if (node.hasOwnProperty("images") && Array.isArray(node.images)) {
65
+ // iterate over the images array and add each image to the potential_outputs array
66
+ for (let j = 0; j < node.images.length; j++) {
67
+ potential_output_nodes.push(node);
68
+ potential_outputs.push({ "type": "image", "image": node.images[j], "title": node.title, "node_id": node.id });
69
+ }
70
+ }
71
+ }
72
+ else if (node.type === "VHS_VideoCombine") {
73
+ // check if node has a 'widgets' array property, with type 'image'
74
+ if (node.hasOwnProperty("widgets") && Array.isArray(node.widgets)) {
75
+ // iterate over the widgets array and add each image to the potential_outputs array
76
+ for (let j = 0; j < node.widgets.length; j++) {
77
+ if (node.widgets[j].type === "image") {
78
+ const widgetValue = node.widgets[j].value;
79
+ const parsedURLVals = parseURLPath(widgetValue);
80
+
81
+ // ensure that the parsedURLVals have 'filename', 'subfolder', 'type', and 'format' properties
82
+ if (parsedURLVals.hasOwnProperty("filename") && parsedURLVals.hasOwnProperty("subfolder") && parsedURLVals.hasOwnProperty("type") && parsedURLVals.hasOwnProperty("format")) {
83
+ if (parsedURLVals.type !== "output") {
84
+ // TODO
85
+ }
86
+ potential_output_nodes.push(node);
87
+ potential_outputs.push({ "type": "output", 'title': node.title, "node_id": node.id , "output": { "filename": parsedURLVals.filename, "subfolder": parsedURLVals.subfolder, "value": widgetValue, "format": parsedURLVals.format } });
88
+ }
89
+ } else if (node.widgets[j].type === "preview") {
90
+ const widgetValue = node.widgets[j].value;
91
+ const parsedURLVals = widgetValue.params;
92
+
93
+ if(!parsedURLVals.format?.startsWith('image')) {
94
+ // video isn't supported format
95
+ continue;
96
+ }
97
+
98
+ // ensure that the parsedURLVals have 'filename', 'subfolder', 'type', and 'format' properties
99
+ if (parsedURLVals.hasOwnProperty("filename") && parsedURLVals.hasOwnProperty("subfolder") && parsedURLVals.hasOwnProperty("type") && parsedURLVals.hasOwnProperty("format")) {
100
+ if (parsedURLVals.type !== "output") {
101
+ // TODO
102
+ }
103
+ potential_output_nodes.push(node);
104
+ 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 } });
105
+ }
106
+ }
107
+ }
108
+ }
109
+ }
110
+ else if (node.type === "ADE_AnimateDiffCombine") {
111
+ // check if node has a 'widgets' array property, with type 'image'
112
+ if (node.hasOwnProperty("widgets") && Array.isArray(node.widgets)) {
113
+ // iterate over the widgets array and add each image to the potential_outputs array
114
+ for (let j = 0; j < node.widgets.length; j++) {
115
+ if (node.widgets[j].type === "image") {
116
+ const widgetValue = node.widgets[j].value;
117
+ const parsedURLVals = parseURLPath(widgetValue);
118
+ // ensure that the parsedURLVals have 'filename', 'subfolder', 'type', and 'format' properties
119
+ if (parsedURLVals.hasOwnProperty("filename") && parsedURLVals.hasOwnProperty("subfolder") && parsedURLVals.hasOwnProperty("type") && parsedURLVals.hasOwnProperty("format")) {
120
+ if (parsedURLVals.type !== "output") {
121
+ // TODO
122
+ continue;
123
+ }
124
+ potential_output_nodes.push(node);
125
+ potential_outputs.push({ "type": "output", 'title': node.title, "output": { "filename": parsedURLVals.filename, "subfolder": parsedURLVals.subfolder, "type": parsedURLVals.type, "value": widgetValue, "format": parsedURLVals.format } });
126
+ }
127
+ }
128
+ }
129
+ }
130
+ }
131
+ else if (node.type === "SaveAnimatedWEBP") {
132
+ // check if node has an 'images' array property
133
+ if (node.hasOwnProperty("images") && Array.isArray(node.images)) {
134
+ // iterate over the images array and add each image to the potential_outputs array
135
+ for (let j = 0; j < node.images.length; j++) {
136
+ potential_output_nodes.push(node);
137
+ potential_outputs.push({ "type": "image", "image": node.images[j], "title": node.title });
138
+ }
139
+ }
140
+ }
141
+ }
142
+
143
+ // Note: make sure that two arrays are the same length
144
+ return { potential_outputs, potential_output_nodes };
145
+ }
146
+
147
+
148
+ export function parseURLPath(urlPath) {
149
+ // Extract the query string from the URL path
150
+ var queryString = urlPath.split('?')[1];
151
+
152
+ // Use the URLSearchParams API to parse the query string
153
+ var params = new URLSearchParams(queryString);
154
+
155
+ // Create an object to store the parsed parameters
156
+ var parsedParams = {};
157
+
158
+ // Iterate over each parameter and add it to the object
159
+ for (var pair of params.entries()) {
160
+ parsedParams[pair[0]] = pair[1];
161
+ }
162
+
163
+ // Return the object with the parsed parameters
164
+ return parsedParams;
165
+ }
166
+
167
+
168
+ export const shareToEsheep= () => {
169
+ app.graphToPrompt()
170
+ .then(prompt => {
171
+ const nodes = app.graph._nodes
172
+ const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
173
+ const workflow = prompt['workflow']
174
+ api.fetchApi(`/manager/set_esheep_workflow_and_images`, {
175
+ method: 'POST',
176
+ headers: { 'Content-Type': 'application/json' },
177
+ body: JSON.stringify({
178
+ workflow: workflow,
179
+ images: potential_outputs
180
+ })
181
+ }).then(response => {
182
+ var domain = window.location.hostname;
183
+ var port = window.location.port;
184
+ port = port || (window.location.protocol === 'http:' ? '80' : window.location.protocol === 'https:' ? '443' : '');
185
+ var full_domin = domain + ':' + port
186
+ window.open('https://www.esheep.com/app/workflow_upload?from_local='+ full_domin, '_blank');
187
+ });
188
+ })
189
+ }
190
+
191
+ export const showCopusShareDialog = () => {
192
+ if (!CopusShareDialog.instance) {
193
+ CopusShareDialog.instance = new CopusShareDialog();
194
+ }
195
+
196
+ return app.graphToPrompt()
197
+ .then(prompt => {
198
+ return app.graph._nodes;
199
+ })
200
+ .then(nodes => {
201
+ const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
202
+ CopusShareDialog.instance.show({ potential_outputs, potential_output_nodes});
203
+ })
204
+ }
205
+
206
+ export const showOpenArtShareDialog = () => {
207
+ if (!OpenArtShareDialog.instance) {
208
+ OpenArtShareDialog.instance = new OpenArtShareDialog();
209
+ }
210
+
211
+ return app.graphToPrompt()
212
+ .then(prompt => {
213
+ // console.log({ prompt })
214
+ return app.graph._nodes;
215
+ })
216
+ .then(nodes => {
217
+ const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
218
+ OpenArtShareDialog.instance.show({ potential_outputs, potential_output_nodes});
219
+ })
220
+ }
221
+
222
+
223
+ export const showYouMLShareDialog = () => {
224
+ if (!YouMLShareDialog.instance) {
225
+ YouMLShareDialog.instance = new YouMLShareDialog();
226
+ }
227
+
228
+ return app.graphToPrompt()
229
+ .then(prompt => {
230
+ return app.graph._nodes;
231
+ })
232
+ .then(nodes => {
233
+ const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
234
+ YouMLShareDialog.instance.show(potential_outputs, potential_output_nodes);
235
+ })
236
+ }
237
+
238
+
239
+ export const showShareDialog = async (share_option) => {
240
+ if (!ShareDialog.instance) {
241
+ ShareDialog.instance = new ShareDialog(share_option);
242
+ }
243
+ return app.graphToPrompt()
244
+ .then(prompt => {
245
+ // console.log({ prompt })
246
+ return app.graph._nodes;
247
+ })
248
+ .then(nodes => {
249
+ // console.log({ nodes });
250
+ const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
251
+ if (potential_outputs.length === 0) {
252
+ if (potential_output_nodes.length === 0) {
253
+ // todo: add support for other output node types (animatediff combine, etc.)
254
+ const supported_nodes_string = SUPPORTED_OUTPUT_NODE_TYPES.join(", ");
255
+ alert(`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.`);
256
+ } else {
257
+ alert("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.");
258
+ }
259
+ return false;
260
+ }
261
+ ShareDialog.instance.show({ potential_outputs, potential_output_nodes, share_option });
262
+ return true;
263
+ });
264
+ }
265
+
266
+ export class ShareDialogChooser extends ComfyDialog {
267
+ static instance = null;
268
+ constructor() {
269
+ super();
270
+ this.element = $el("div.comfy-modal", {
271
+ parent: document.body, style: {
272
+ 'overflow-y': "auto",
273
+ }
274
+ },
275
+ [$el("div.comfy-modal-content",
276
+ {},
277
+ [...this.createButtons()]),
278
+ ]);
279
+ this.selectedNodeId = null;
280
+ }
281
+ createButtons() {
282
+ const buttons = [
283
+ {
284
+ key: "openart",
285
+ textContent: "OpenArt AI",
286
+ website: "https://openart.ai/workflows/",
287
+ description: "Share ComfyUI workflows and art on OpenArt.ai",
288
+ onclick: () => {
289
+ showOpenArtShareDialog();
290
+ this.close();
291
+ }
292
+ },
293
+ {
294
+ key: "youml",
295
+ textContent: "YouML",
296
+ website: "https://youml.com",
297
+ description: "Share your workflow or transform it into an interactive app on YouML.com",
298
+ onclick: () => {
299
+ showYouMLShareDialog();
300
+ this.close();
301
+ }
302
+ },
303
+ {
304
+ key: "matrix",
305
+ textContent: "Matrix Server",
306
+ website: "https://app.element.io/#/room/%23comfyui_space%3Amatrix.org",
307
+ description: "Share your art on the official ComfyUI matrix server",
308
+ onclick: async () => {
309
+ showShareDialog('matrix').then((suc) => {
310
+ suc && this.close();
311
+ })
312
+ }
313
+ },
314
+ {
315
+ key: "comfyworkflows",
316
+ textContent: "ComfyWorkflows",
317
+ website: "https://comfyworkflows.com",
318
+ 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>",
319
+ onclick: () => {
320
+ showShareDialog('comfyworkflows').then((suc) => {
321
+ suc && this.close();
322
+ })
323
+ }
324
+ },
325
+ {
326
+ key: "esheep",
327
+ textContent: "eSheep",
328
+ website: "https://www.esheep.com",
329
+ description: "Share & download thousands of ComfyUI workflows on <a style='color:var(--input-text);' href='https://www.esheep.com' target='_blank'>esheep.com</a>",
330
+ onclick: () => {
331
+ shareToEsheep();
332
+ this.close();
333
+ }
334
+ },
335
+ {
336
+ key: "Copus",
337
+ textContent: "Copus",
338
+ website: "https://www.copus.io",
339
+ description: "🔴 Permanently store and secure ownership of your workflow on the open-source platform: <a style='color:var(--input-text);' href='https://copus.io' target='_blank'>Copus.io</a>",
340
+ onclick: () => {
341
+ showCopusShareDialog();
342
+ this.close();
343
+ }
344
+ },
345
+ ];
346
+
347
+ function createShareButtonsWithDescriptions() {
348
+ // Responsive container
349
+ const container = $el("div", {
350
+ style: {
351
+ display: "flex",
352
+ 'flex-wrap': 'wrap',
353
+ 'justify-content': 'space-around',
354
+ 'padding': '10px',
355
+ }
356
+ });
357
+
358
+ buttons.forEach(b => {
359
+ const button = $el("button", {
360
+ type: "button",
361
+ textContent: b.textContent,
362
+ onclick: b.onclick,
363
+ style: {
364
+ 'width': '25%',
365
+ 'minWidth': '200px',
366
+ 'background-color': b.backgroundColor || '',
367
+ 'border-radius': '5px',
368
+ 'cursor': 'pointer',
369
+ 'padding': '5px 5px',
370
+ 'margin-bottom': '5px',
371
+ 'transition': 'background-color 0.3s',
372
+ }
373
+ });
374
+ button.addEventListener('mouseover', () => {
375
+ button.style.backgroundColor = '#007BFF'; // Change color on hover
376
+ });
377
+ button.addEventListener('mouseout', () => {
378
+ button.style.backgroundColor = b.backgroundColor || '';
379
+ });
380
+
381
+ const description = $el("p", {
382
+ innerHTML: b.description,
383
+ style: {
384
+ 'text-align': 'left',
385
+ color: 'var(--input-text)',
386
+ 'font-size': '14px',
387
+ 'margin-bottom': '0',
388
+ },
389
+ });
390
+
391
+ const websiteLink = $el("a", {
392
+ textContent: "🌐 Website",
393
+ href: b.website,
394
+ target: "_blank",
395
+ style: {
396
+ color: 'var(--input-text)',
397
+ 'margin-left': '10px',
398
+ 'font-size': '12px',
399
+ 'text-decoration': 'none',
400
+ 'align-self': 'center',
401
+ },
402
+ });
403
+
404
+ // Add highlight to the website link
405
+ websiteLink.addEventListener('mouseover', () => {
406
+ websiteLink.style.opacity = '0.7';
407
+ });
408
+
409
+ websiteLink.addEventListener('mouseout', () => {
410
+ websiteLink.style.opacity = '1';
411
+ });
412
+
413
+ const buttonLinkContainer = $el("div", {
414
+ style: {
415
+ display: 'flex',
416
+ 'align-items': 'center',
417
+ 'margin-bottom': '10px',
418
+ }
419
+ }, [button, websiteLink]);
420
+
421
+ const column = $el("div", {
422
+ style: {
423
+ 'flex-basis': '100%',
424
+ 'margin': '10px',
425
+ 'padding': '10px 20px',
426
+ 'border': '1px solid #ddd',
427
+ 'border-radius': '5px',
428
+ 'box-shadow': '0 2px 4px rgba(0, 0, 0, 0.1)',
429
+ }
430
+ }, [buttonLinkContainer, description]);
431
+
432
+ container.appendChild(column);
433
+ });
434
+
435
+ return container;
436
+ }
437
+
438
+ return [
439
+ $el("p", {
440
+ textContent: 'Choose a platform to share your workflow',
441
+ style: {
442
+ 'text-align': 'center',
443
+ 'color': 'var(--input-text)',
444
+ 'font-size': '18px',
445
+ 'margin-bottom': '10px',
446
+ },
447
+ }
448
+ ),
449
+
450
+ $el("div.cm-menu-container", {
451
+ id: "comfyui-share-container"
452
+ }, [
453
+ $el("div.cm-menu-column", [
454
+ createShareButtonsWithDescriptions(),
455
+ $el("br", {}, []),
456
+ ]),
457
+ ]),
458
+ $el("div.cm-menu-container", {
459
+ id: "comfyui-share-container"
460
+ }, [
461
+ $el("button", {
462
+ type: "button",
463
+ style: {
464
+ margin: "0 25px",
465
+ width: "100%",
466
+ },
467
+ textContent: "Close",
468
+ onclick: () => {
469
+ this.close()
470
+ }
471
+ }),
472
+ $el("br", {}, []),
473
+ ]),
474
+ ];
475
+ }
476
+ show() {
477
+ this.element.style.display = "block";
478
+ this.element.style.zIndex = 10001;
479
+ }
480
+ }
481
+ export class ShareDialog extends ComfyDialog {
482
+ static instance = null;
483
+ static matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
484
+ static cw_sharekey = "";
485
+
486
+ constructor(share_option) {
487
+ super();
488
+ this.share_option = share_option;
489
+ this.element = $el("div.comfy-modal", {
490
+ parent: document.body, style: {
491
+ 'overflow-y': "auto",
492
+ }
493
+ },
494
+ [$el("div.comfy-modal-content",
495
+ {},
496
+ [...this.createButtons()]),
497
+ ]);
498
+ this.selectedOutputIndex = 0;
499
+ }
500
+
501
+ createButtons() {
502
+ this.radio_buttons = $el("div", {
503
+ id: "selectOutputImages",
504
+ }, []);
505
+
506
+ this.is_nsfw_checkbox = $el("input", { type: 'checkbox', id: "is_nsfw" }, [])
507
+ const is_nsfw_checkbox_text = $el("label", {
508
+ }, [" Is this NSFW?"])
509
+ this.is_nsfw_checkbox.style.color = "var(--fg-color)";
510
+ this.is_nsfw_checkbox.checked = false;
511
+
512
+ this.matrix_destination_checkbox = $el("input", { type: 'checkbox', id: "matrix_destination" }, [])
513
+ const matrix_destination_checkbox_text = $el("label", {}, [" ComfyUI Matrix server"])
514
+ this.matrix_destination_checkbox.style.color = "var(--fg-color)";
515
+ this.matrix_destination_checkbox.checked = this.share_option === 'matrix'; //true;
516
+
517
+ this.comfyworkflows_destination_checkbox = $el("input", { type: 'checkbox', id: "comfyworkflows_destination" }, [])
518
+ const comfyworkflows_destination_checkbox_text = $el("label", {}, [" ComfyWorkflows.com"])
519
+ this.comfyworkflows_destination_checkbox.style.color = "var(--fg-color)";
520
+ this.comfyworkflows_destination_checkbox.checked = this.share_option !== 'matrix';
521
+
522
+ this.matrix_homeserver_input = $el("input", { type: 'text', id: "matrix_homeserver", placeholder: "matrix.org", value: ShareDialog.matrix_auth.homeserver || 'matrix.org' }, []);
523
+ this.matrix_username_input = $el("input", { type: 'text', placeholder: "Username", value: ShareDialog.matrix_auth.username || '' }, []);
524
+ this.matrix_password_input = $el("input", { type: 'password', placeholder: "Password", value: ShareDialog.matrix_auth.password || '' }, []);
525
+
526
+ this.cw_sharekey_input = $el("input", { type: 'text', placeholder: "Share key (found on your profile page)", value: ShareDialog.cw_sharekey || '' }, []);
527
+ this.cw_sharekey_input.style.width = "100%";
528
+
529
+ this.credits_input = $el("input", {
530
+ type: "text",
531
+ placeholder: "This will be used to give credits",
532
+ required: false,
533
+ }, []);
534
+
535
+ this.title_input = $el("input", {
536
+ type: "text",
537
+ placeholder: "ex: My awesome art",
538
+ required: false
539
+ }, []);
540
+
541
+ this.description_input = $el("textarea", {
542
+ placeholder: "ex: Trying out a new workflow... ",
543
+ required: false,
544
+ }, []);
545
+
546
+ this.share_button = $el("button", {
547
+ type: "submit",
548
+ textContent: "Share",
549
+ style: {
550
+ backgroundColor: "blue"
551
+ }
552
+ }, []);
553
+
554
+ this.final_message = $el("div", {
555
+ style: {
556
+ color: "white",
557
+ textAlign: "center",
558
+ // marginTop: "10px",
559
+ // backgroundColor: "black",
560
+ padding: "10px",
561
+ }
562
+ }, []);
563
+
564
+ this.share_finalmessage_container = $el("div.cm-menu-container", {
565
+ id: "comfyui-share-finalmessage-container",
566
+ style: {
567
+ display: "none",
568
+ }
569
+ }, [
570
+ $el("div.cm-menu-column", [
571
+ this.final_message,
572
+ $el("button", {
573
+ type: "button",
574
+ textContent: "Close",
575
+ onclick: () => {
576
+ // Reset state
577
+ this.matrix_destination_checkbox.checked = this.share_option === 'matrix';
578
+ this.comfyworkflows_destination_checkbox.checked = this.share_option !== 'matrix';
579
+ this.share_button.textContent = "Share";
580
+ this.share_button.style.display = "inline-block";
581
+ this.final_message.innerHTML = "";
582
+ this.final_message.style.color = "white";
583
+ this.credits_input.value = "";
584
+ this.title_input.value = "";
585
+ this.description_input.value = "";
586
+ this.is_nsfw_checkbox.checked = false;
587
+ this.selectedOutputIndex = 0;
588
+
589
+ // hide the final message
590
+ this.share_finalmessage_container.style.display = "none";
591
+
592
+ // show the share container
593
+ this.share_container.style.display = "flex";
594
+
595
+ this.close()
596
+ }
597
+ }),
598
+ ])
599
+ ]);
600
+ this.share_container = $el("div.cm-menu-container", {
601
+ id: "comfyui-share-container"
602
+ }, [
603
+ $el("div.cm-menu-column", [
604
+ $el("details", {
605
+ style: {
606
+ border: "1px solid #999",
607
+ padding: "5px",
608
+ borderRadius: "5px",
609
+ backgroundColor: "#222"
610
+ }
611
+ }, [
612
+ $el("summary", {
613
+ style: {
614
+ color: "white",
615
+ cursor: "pointer",
616
+ }
617
+ }, [`Matrix account`]),
618
+ $el("div", {
619
+ style: {
620
+ display: "flex",
621
+ flexDirection: "row",
622
+ }
623
+ }, [
624
+ $el("div", {
625
+ textContent: "Homeserver",
626
+ style: {
627
+ marginRight: "10px",
628
+ }
629
+ }, []),
630
+ this.matrix_homeserver_input,
631
+ ]),
632
+
633
+ $el("div", {
634
+ style: {
635
+ display: "flex",
636
+ flexDirection: "row",
637
+ }
638
+ }, [
639
+ $el("div", {
640
+ textContent: "Username",
641
+ style: {
642
+ marginRight: "10px",
643
+ }
644
+ }, []),
645
+ this.matrix_username_input,
646
+ ]),
647
+
648
+ $el("div", {
649
+ style: {
650
+ display: "flex",
651
+ flexDirection: "row",
652
+ }
653
+ }, [
654
+ $el("div", {
655
+ textContent: "Password",
656
+ style: {
657
+ marginRight: "10px",
658
+ }
659
+ }, []),
660
+ this.matrix_password_input,
661
+ ]),
662
+
663
+ ]),
664
+ $el("details", {
665
+ style: {
666
+ border: "1px solid #999",
667
+ marginTop: "10px",
668
+ padding: "5px",
669
+ borderRadius: "5px",
670
+ backgroundColor: "#222"
671
+ },
672
+ }, [
673
+ $el("summary", {
674
+ style: {
675
+ color: "white",
676
+ cursor: "pointer",
677
+ }
678
+ }, [`Comfyworkflows.com account`]),
679
+ $el("h4", {
680
+ textContent: "Share key (found on your profile page)",
681
+ }, []),
682
+ $el("p", { size: 3, color: "white" }, ["If provided, your art will be saved to your account. Otherwise, it will be shared anonymously."]),
683
+ this.cw_sharekey_input,
684
+ ]),
685
+
686
+ $el("div", {}, [
687
+ $el("p", {
688
+ size: 3, color: "white", style: {
689
+ color: 'var(--input-text)'
690
+ }
691
+ }, [`Select where to share your art:`]),
692
+ this.matrix_destination_checkbox,
693
+ matrix_destination_checkbox_text,
694
+ $el("br", {}, []),
695
+ this.comfyworkflows_destination_checkbox,
696
+ comfyworkflows_destination_checkbox_text,
697
+ ]),
698
+
699
+ $el("h4", {
700
+ textContent: "Credits (optional)",
701
+ size: 3,
702
+ color: "white",
703
+ style: {
704
+ color: 'var(--input-text)'
705
+ }
706
+ }, []),
707
+ this.credits_input,
708
+ // $el("br", {}, []),
709
+
710
+ $el("h4", {
711
+ textContent: "Title (optional)",
712
+ size: 3,
713
+ color: "white",
714
+ style: {
715
+ color: 'var(--input-text)'
716
+ }
717
+ }, []),
718
+ this.title_input,
719
+ // $el("br", {}, []),
720
+
721
+ $el("h4", {
722
+ textContent: "Description (optional)",
723
+ size: 3,
724
+ color: "white",
725
+ style: {
726
+ color: 'var(--input-text)'
727
+ }
728
+ }, []),
729
+ this.description_input,
730
+ $el("br", {}, []),
731
+
732
+ $el("div", {}, [this.is_nsfw_checkbox, is_nsfw_checkbox_text]),
733
+ // $el("br", {}, []),
734
+
735
+ // this.final_message,
736
+ // $el("br", {}, []),
737
+ ]),
738
+ $el("div.cm-menu-column", [
739
+ this.radio_buttons,
740
+ $el("br", {}, []),
741
+
742
+ this.share_button,
743
+
744
+ $el("button", {
745
+ type: "button",
746
+ textContent: "Close",
747
+ onclick: () => {
748
+ // Reset state
749
+ this.matrix_destination_checkbox.checked = this.share_option === 'matrix';
750
+ this.comfyworkflows_destination_checkbox.checked = this.share_option !== 'matrix';
751
+ this.share_button.textContent = "Share";
752
+ this.share_button.style.display = "inline-block";
753
+ this.final_message.innerHTML = "";
754
+ this.final_message.style.color = "white";
755
+ this.credits_input.value = "";
756
+ this.title_input.value = "";
757
+ this.description_input.value = "";
758
+ this.is_nsfw_checkbox.checked = false;
759
+ this.selectedOutputIndex = 0;
760
+
761
+ // hide the final message
762
+ this.share_finalmessage_container.style.display = "none";
763
+
764
+ // show the share container
765
+ this.share_container.style.display = "flex";
766
+
767
+ this.close()
768
+ }
769
+ }),
770
+ $el("br", {}, []),
771
+ ]),
772
+ ]);
773
+
774
+ // get the user's existing matrix auth and share key
775
+ ShareDialog.matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
776
+ try {
777
+ api.fetchApi(`/manager/get_matrix_auth`)
778
+ .then(response => response.json())
779
+ .then(data => {
780
+ ShareDialog.matrix_auth = data;
781
+ this.matrix_homeserver_input.value = ShareDialog.matrix_auth.homeserver;
782
+ this.matrix_username_input.value = ShareDialog.matrix_auth.username;
783
+ this.matrix_password_input.value = ShareDialog.matrix_auth.password;
784
+ })
785
+ .catch(error => {
786
+ // console.log(error);
787
+ });
788
+ } catch (error) {
789
+ // console.log(error);
790
+ }
791
+
792
+ // get the user's existing comfyworkflows share key
793
+ ShareDialog.cw_sharekey = "";
794
+ try {
795
+ // console.log("Fetching comfyworkflows share key")
796
+ api.fetchApi(`/manager/get_comfyworkflows_auth`)
797
+ .then(response => response.json())
798
+ .then(data => {
799
+ ShareDialog.cw_sharekey = data.comfyworkflows_sharekey;
800
+ this.cw_sharekey_input.value = ShareDialog.cw_sharekey;
801
+ })
802
+ .catch(error => {
803
+ // console.log(error);
804
+ });
805
+ } catch (error) {
806
+ // console.log(error);
807
+ }
808
+
809
+ this.share_button.onclick = async () => {
810
+ const prompt = await app.graphToPrompt();
811
+ const nodes = app.graph._nodes;
812
+
813
+ // console.log({ prompt, nodes });
814
+
815
+ const destinations = [];
816
+ if (this.matrix_destination_checkbox.checked) {
817
+ destinations.push("matrix");
818
+ }
819
+ if (this.comfyworkflows_destination_checkbox.checked) {
820
+ destinations.push("comfyworkflows");
821
+ }
822
+
823
+ // if destinations includes matrix, make an api call to /manager/check_matrix to ensure that the user has configured their matrix settings
824
+ if (destinations.includes("matrix")) {
825
+ let definedMatrixAuth = !!this.matrix_homeserver_input.value && !!this.matrix_username_input.value && !!this.matrix_password_input.value;
826
+ if (!definedMatrixAuth) {
827
+ alert("Please set your Matrix account details.");
828
+ return;
829
+ }
830
+ }
831
+
832
+ 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?")) {
833
+ return;
834
+ }
835
+
836
+ const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
837
+
838
+ // console.log({ potential_outputs, potential_output_nodes })
839
+
840
+ if (potential_outputs.length === 0) {
841
+ if (potential_output_nodes.length === 0) {
842
+ // todo: add support for other output node types (animatediff combine, etc.)
843
+ const supported_nodes_string = SUPPORTED_OUTPUT_NODE_TYPES.join(", ");
844
+ alert(`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.`);
845
+ } else {
846
+ alert("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.");
847
+ }
848
+ this.selectedOutputIndex = 0;
849
+ this.close();
850
+ return;
851
+ }
852
+
853
+ // Change the text of the share button to "Sharing..." to indicate that the share process has started
854
+ this.share_button.textContent = "Sharing...";
855
+
856
+ const response = await api.fetchApi(`/manager/share`, {
857
+ method: 'POST',
858
+ headers: { 'Content-Type': 'application/json' },
859
+ body: JSON.stringify({
860
+ matrix_auth: {
861
+ homeserver: this.matrix_homeserver_input.value,
862
+ username: this.matrix_username_input.value,
863
+ password: this.matrix_password_input.value,
864
+ },
865
+ cw_auth: {
866
+ cw_sharekey: this.cw_sharekey_input.value,
867
+ },
868
+ share_destinations: destinations,
869
+ credits: this.credits_input.value,
870
+ title: this.title_input.value,
871
+ description: this.description_input.value,
872
+ is_nsfw: this.is_nsfw_checkbox.checked,
873
+ prompt,
874
+ potential_outputs,
875
+ selected_output_index: this.selectedOutputIndex,
876
+ // potential_output_nodes
877
+ })
878
+ });
879
+
880
+ if (response.status != 200) {
881
+ try {
882
+ const response_json = await response.json();
883
+ if (response_json.error) {
884
+ alert(response_json.error);
885
+ this.close();
886
+ return;
887
+ } else {
888
+ alert("Failed to share your art. Please try again.");
889
+ this.close();
890
+ return;
891
+ }
892
+ } catch (e) {
893
+ alert("Failed to share your art. Please try again.");
894
+ this.close();
895
+ return;
896
+ }
897
+ }
898
+
899
+ const response_json = await response.json();
900
+
901
+ if (response_json.comfyworkflows.url) {
902
+ this.final_message.innerHTML = "Your art has been shared: <a href='" + response_json.comfyworkflows.url + "' target='_blank'>" + response_json.comfyworkflows.url + "</a>";
903
+ if (response_json.matrix.success) {
904
+ this.final_message.innerHTML += "<br>Your art has been shared in the ComfyUI Matrix server's #share channel!";
905
+ }
906
+ } else {
907
+ if (response_json.matrix.success) {
908
+ this.final_message.innerHTML = "Your art has been shared in the ComfyUI Matrix server's #share channel!";
909
+ }
910
+ }
911
+
912
+ this.final_message.style.color = "green";
913
+
914
+ // hide #comfyui-share-container and show #comfyui-share-finalmessage-container
915
+ this.share_container.style.display = "none";
916
+ this.share_finalmessage_container.style.display = "block";
917
+
918
+ // hide the share button
919
+ this.share_button.textContent = "Shared!";
920
+ this.share_button.style.display = "none";
921
+ // this.close();
922
+ }
923
+
924
+ const res =
925
+ [
926
+ $el("tr.td", { width: "100%" }, [
927
+ $el("font", { size: 6, color: "white" }, [`Share your art`]),
928
+ ]),
929
+ $el("br", {}, []),
930
+
931
+ this.share_finalmessage_container,
932
+ this.share_container,
933
+ ];
934
+
935
+ res[0].style.padding = "10px 10px 10px 10px";
936
+ res[0].style.backgroundColor = "black"; //"linear-gradient(90deg, #00C9FF 0%, #92FE9D 100%)";
937
+ res[0].style.textAlign = "center";
938
+ res[0].style.height = "45px";
939
+ return res;
940
+ }
941
+
942
+ show({potential_outputs, potential_output_nodes, share_option}) {
943
+ // Sort `potential_output_nodes` by node ID to make the order always
944
+ // consistent, but we should also keep `potential_outputs` in the same
945
+ // order as `potential_output_nodes`.
946
+ const potential_output_to_order = {};
947
+ potential_output_nodes.forEach((node, index) => {
948
+ if (node.id in potential_output_to_order) {
949
+ potential_output_to_order[node.id][1].push(potential_outputs[index]);
950
+ } else {
951
+ potential_output_to_order[node.id] = [node, [potential_outputs[index]]];
952
+ }
953
+ })
954
+ // Sort the object `potential_output_to_order` by key (node ID)
955
+ const sorted_potential_output_to_order = Object.fromEntries(
956
+ Object.entries(potential_output_to_order).sort((a, b) => a[0].id - b[0].id)
957
+ );
958
+ const sorted_potential_outputs = []
959
+ const sorted_potential_output_nodes = []
960
+ for (const [key, value] of Object.entries(sorted_potential_output_to_order)) {
961
+ sorted_potential_output_nodes.push(value[0]);
962
+ sorted_potential_outputs.push(...value[1]);
963
+ }
964
+ potential_output_nodes = sorted_potential_output_nodes;
965
+ potential_outputs = sorted_potential_outputs;
966
+
967
+ // console.log({ potential_outputs, potential_output_nodes })
968
+ this.radio_buttons.innerHTML = ""; // clear the radio buttons
969
+ let is_radio_button_checked = false; // only check the first radio button if multiple images from the same node
970
+ const new_radio_buttons = $el("div", {
971
+ id: "selectOutput-Options",
972
+ style: {
973
+ 'overflow-y': 'scroll',
974
+ 'max-height': '400px',
975
+ }
976
+ }, potential_outputs.map((output, index) => {
977
+ const {node_id} = output;
978
+ const radio_button = $el("input", { type: 'radio', name: "selectOutputImages", value: index, required: index === 0 }, [])
979
+ let radio_button_img;
980
+ if (output.type === "image" || output.type === "temp") {
981
+ radio_button_img = $el("img", { src: `/view?filename=${output.image.filename}&subfolder=${output.image.subfolder}&type=${output.image.type}`, style: { width: "auto", height: "100px" } }, []);
982
+ } else if (output.type === "output") {
983
+ radio_button_img = $el("img", { src: output.output.value, style: { width: "auto", height: "100px" } }, []);
984
+ } else {
985
+ // unsupported output type
986
+ // this should never happen
987
+ // TODO
988
+ radio_button_img = $el("img", { src: "", style: { width: "auto", height: "100px" } }, []);
989
+ }
990
+ const radio_button_text = $el("label", {
991
+ // style: {
992
+ // color: 'var(--input-text)'
993
+ // }
994
+ }, [output.title])
995
+ radio_button.style.color = "var(--fg-color)";
996
+
997
+ // Make the radio button checked if it's the selected node,
998
+ // otherwise make the first radio button checked.
999
+ if (this.selectedNodeId) {
1000
+ if (this.selectedNodeId === node_id && !is_radio_button_checked) {
1001
+ radio_button.checked = true;
1002
+ is_radio_button_checked = true;
1003
+ }
1004
+ } else {
1005
+ radio_button.checked = index === 0;
1006
+ }
1007
+
1008
+ if (radio_button.checked) {
1009
+ this.selectedOutputIndex = index;
1010
+ }
1011
+
1012
+ radio_button.onchange = () => {
1013
+ this.selectedOutputIndex = parseInt(radio_button.value);
1014
+ };
1015
+
1016
+ return $el("div", {
1017
+ style: {
1018
+ display: "flex",
1019
+ 'align-items': 'center',
1020
+ 'justify-content': 'space-between',
1021
+ 'margin-bottom': '10px',
1022
+ }
1023
+ }, [radio_button, radio_button_text, radio_button_img]);
1024
+ }));
1025
+ const header = $el("h3", {
1026
+ textContent: "Select an image to share",
1027
+ size: 3,
1028
+ color: "white",
1029
+ style: {
1030
+ 'text-align': 'center',
1031
+ color: 'var(--input-text)',
1032
+ backgroundColor: 'black',
1033
+ padding: '10px',
1034
+ 'margin-top': '0px',
1035
+ }
1036
+ }, [
1037
+ $el("p", {
1038
+ textContent: "Scroll to see all outputs",
1039
+ size: 2,
1040
+ color: "white",
1041
+ style: {
1042
+ 'text-align': 'center',
1043
+ color: 'var(--input-text)',
1044
+ 'margin-bottom': '5px',
1045
+ 'font-style': 'italic',
1046
+ 'font-size': '12px',
1047
+ },
1048
+ }, [])
1049
+ ]);
1050
+ this.radio_buttons.appendChild(header);
1051
+ // this.radio_buttons.appendChild(subheader);
1052
+ this.radio_buttons.appendChild(new_radio_buttons);
1053
+ this.element.style.display = "block";
1054
+
1055
+ share_option = share_option || this.share_option;
1056
+ if (share_option === 'comfyworkflows') {
1057
+ this.matrix_destination_checkbox.checked = false;
1058
+ this.comfyworkflows_destination_checkbox.checked = true;
1059
+ } else {
1060
+ this.matrix_destination_checkbox.checked = true;
1061
+ this.comfyworkflows_destination_checkbox.checked = false;
1062
+ }
1063
+ }
1064
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-share-copus.js ADDED
@@ -0,0 +1,892 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../scripts/app.js";
2
+ import { $el, ComfyDialog } from "../../scripts/ui.js";
3
+ const env = "prod";
4
+
5
+ let DEFAULT_HOMEPAGE_URL = "https://copus.io";
6
+
7
+ let API_ENDPOINT = "https://api.client.prod.copus.io/copus-client";
8
+
9
+ if (env !== "prod") {
10
+ API_ENDPOINT = "https://api.dev.copus.io/copus-client";
11
+ DEFAULT_HOMEPAGE_URL = "https://test.copus.io";
12
+ }
13
+
14
+ const style = `
15
+ .copus-share-dialog a {
16
+ color: #f8f8f8;
17
+ }
18
+ .copus-share-dialog a:hover {
19
+ color: #007bff;
20
+ }
21
+ .output_label {
22
+ border: 5px solid transparent;
23
+ }
24
+ .output_label:hover {
25
+ border: 5px solid #59E8C6;
26
+ }
27
+ .output_label.checked {
28
+ border: 5px solid #59E8C6;
29
+ }
30
+ `;
31
+
32
+ // Shared component styles
33
+ const sectionStyle = {
34
+ marginBottom: 0,
35
+ padding: 0,
36
+ borderRadius: "8px",
37
+ boxShadow: "0 2px 4px rgba(0, 0, 0, 0.05)",
38
+ display: "flex",
39
+ flexDirection: "column",
40
+ justifyContent: "center",
41
+ position: "relative",
42
+ };
43
+
44
+ export class CopusShareDialog extends ComfyDialog {
45
+ static instance = null;
46
+
47
+ constructor() {
48
+ super();
49
+ $el("style", {
50
+ textContent: style,
51
+ parent: document.head,
52
+ });
53
+ this.element = $el(
54
+ "div.comfy-modal.copus-share-dialog",
55
+ {
56
+ parent: document.body,
57
+ style: {
58
+ "overflow-y": "auto",
59
+ },
60
+ },
61
+ [$el("div.comfy-modal-content", {}, [...this.createButtons()])]
62
+ );
63
+ this.selectedOutputIndex = 0;
64
+ this.selectedNodeId = null;
65
+ this.uploadedImages = [];
66
+ this.allFilesImages = [];
67
+ this.selectedFile = null;
68
+ this.allFiles = [];
69
+ this.titleNum = 0;
70
+ }
71
+
72
+ createButtons() {
73
+ const inputStyle = {
74
+ display: "block",
75
+ minWidth: "500px",
76
+ width: "100%",
77
+ padding: "10px",
78
+ margin: "10px 0",
79
+ borderRadius: "4px",
80
+ border: "1px solid #ddd",
81
+ boxSizing: "border-box",
82
+ };
83
+
84
+ const textAreaStyle = {
85
+ display: "block",
86
+ minWidth: "500px",
87
+ width: "100%",
88
+ padding: "10px",
89
+ margin: "10px 0",
90
+ borderRadius: "4px",
91
+ border: "1px solid #ddd",
92
+ boxSizing: "border-box",
93
+ minHeight: "100px",
94
+ background: "#222",
95
+ resize: "vertical",
96
+ color: "#f2f2f2",
97
+ fontFamily: "Arial",
98
+ fontWeight: "400",
99
+ fontSize: "15px",
100
+ };
101
+
102
+ const hyperLinkStyle = {
103
+ display: "block",
104
+ marginBottom: "15px",
105
+ fontWeight: "bold",
106
+ fontSize: "14px",
107
+ };
108
+
109
+ const labelStyle = {
110
+ color: "#f8f8f8",
111
+ display: "block",
112
+ margin: "10px 0 0 0",
113
+ fontWeight: "bold",
114
+ textDecoration: "none",
115
+ };
116
+
117
+ const buttonStyle = {
118
+ padding: "10px 80px",
119
+ margin: "10px 5px",
120
+ borderRadius: "4px",
121
+ border: "none",
122
+ cursor: "pointer",
123
+ color: "#fff",
124
+ backgroundColor: "#007bff",
125
+ };
126
+
127
+ // upload images input
128
+ this.uploadImagesInput = $el("input", {
129
+ type: "file",
130
+ multiple: false,
131
+ style: inputStyle,
132
+ accept: "image/*",
133
+ });
134
+
135
+ this.uploadImagesInput.addEventListener("change", async (e) => {
136
+ const file = e.target.files[0];
137
+ if (!file) {
138
+ this.previewImage.src = "";
139
+ this.previewImage.style.display = "none";
140
+ return;
141
+ }
142
+ const reader = new FileReader();
143
+ reader.onload = async (e) => {
144
+ const imgData = e.target.result;
145
+ this.previewImage.src = imgData;
146
+ this.previewImage.style.display = "block";
147
+ this.selectedFile = null;
148
+ // Once user uploads an image, we uncheck all radio buttons
149
+ this.radioButtons.forEach((ele) => {
150
+ ele.checked = false;
151
+ ele.parentElement.classList.remove("checked");
152
+ });
153
+
154
+ // Add the opacity style toggle here to indicate that they only need
155
+ // to upload one image or choose one from the outputs.
156
+ this.outputsSection.style.opacity = 0.35;
157
+ this.uploadImagesInput.style.opacity = 1;
158
+ };
159
+ reader.readAsDataURL(file);
160
+ });
161
+
162
+ // preview image
163
+ this.previewImage = $el("img", {
164
+ src: "",
165
+ style: {
166
+ width: "100%",
167
+ maxHeight: "100px",
168
+ objectFit: "contain",
169
+ display: "none",
170
+ marginTop: "10px",
171
+ },
172
+ });
173
+
174
+ this.keyInput = $el("input", {
175
+ type: "password",
176
+ placeholder: "Copy & paste your API key",
177
+ style: inputStyle,
178
+ });
179
+ this.TitleInput = $el("input", {
180
+ type: "text",
181
+ placeholder: "Title (Required)",
182
+ style: inputStyle,
183
+ maxLength: "70",
184
+ oninput: () => {
185
+ const titleNum = this.TitleInput.value.length;
186
+ titleNumDom.textContent = `${titleNum}/70`;
187
+ },
188
+ });
189
+ this.SubTitleInput = $el("input", {
190
+ type: "text",
191
+ placeholder: "Subtitle (Optional)",
192
+ style: inputStyle,
193
+ maxLength: "70",
194
+ oninput: () => {
195
+ const titleNum = this.SubTitleInput.value.length;
196
+ subTitleNumDom.textContent = `${titleNum}/70`;
197
+ },
198
+ });
199
+ this.descriptionInput = $el("textarea", {
200
+ placeholder: "Content (Optional)",
201
+ style: {
202
+ ...textAreaStyle,
203
+ minHeight: "100px",
204
+ },
205
+ });
206
+
207
+ // Header Section
208
+ const headerSection = $el("h3", {
209
+ textContent: "Share your workflow to Copus",
210
+ size: 3,
211
+ color: "white",
212
+ style: {
213
+ "text-align": "center",
214
+ color: "white",
215
+ margin: "0 0 10px 0",
216
+ },
217
+ });
218
+ this.getAPIKeyLink = $el(
219
+ "a",
220
+ {
221
+ style: {
222
+ ...hyperLinkStyle,
223
+ color: "#59E8C6",
224
+ },
225
+ href: `${DEFAULT_HOMEPAGE_URL}?fromPage=comfyUI`,
226
+ target: "_blank",
227
+ },
228
+ ["👉 Get your API key here"]
229
+ );
230
+ const linkSection = $el(
231
+ "div",
232
+ {
233
+ style: {
234
+ marginTop: "10px",
235
+ display: "flex",
236
+ flexDirection: "column",
237
+ },
238
+ },
239
+ [
240
+ // this.communityLink,
241
+ this.getAPIKeyLink,
242
+ ]
243
+ );
244
+
245
+ // Account Section
246
+ const accountSection = $el("div", { style: sectionStyle }, [
247
+ $el("label", { style: labelStyle }, ["1️⃣ Copus API Key"]),
248
+ this.keyInput,
249
+ ]);
250
+
251
+ // Output Upload Section
252
+ const outputUploadSection = $el("div", { style: sectionStyle }, [
253
+ $el(
254
+ "label",
255
+ {
256
+ style: {
257
+ ...labelStyle,
258
+ margin: "10px 0 0 0",
259
+ },
260
+ },
261
+ ["2️⃣ Image/Thumbnail (Required)"]
262
+ ),
263
+ this.previewImage,
264
+ this.uploadImagesInput,
265
+ ]);
266
+
267
+ // Outputs Section
268
+ this.outputsSection = $el(
269
+ "div",
270
+ {
271
+ id: "selectOutputs",
272
+ },
273
+ []
274
+ );
275
+
276
+ const titleNumDom = $el(
277
+ "label",
278
+ {
279
+ style: {
280
+ fontSize: "12px",
281
+ position: "absolute",
282
+ right: "10px",
283
+ bottom: "-10px",
284
+ color: "#999",
285
+ },
286
+ },
287
+ ["0/70"]
288
+ );
289
+ const subTitleNumDom = $el(
290
+ "label",
291
+ {
292
+ style: {
293
+ fontSize: "12px",
294
+ position: "absolute",
295
+ right: "10px",
296
+ bottom: "-10px",
297
+ color: "#999",
298
+ },
299
+ },
300
+ ["0/70"]
301
+ );
302
+ const descriptionNumDom = $el(
303
+ "label",
304
+ {
305
+ style: {
306
+ fontSize: "12px",
307
+ position: "absolute",
308
+ right: "10px",
309
+ bottom: "-10px",
310
+ color: "#999",
311
+ },
312
+ },
313
+ ["0/70"]
314
+ );
315
+ // Additional Inputs Section
316
+ const additionalInputsSection = $el(
317
+ "div",
318
+ { style: { ...sectionStyle, } },
319
+ [
320
+ $el("label", { style: labelStyle }, ["3️⃣ Title "]),
321
+ this.TitleInput,
322
+ titleNumDom,
323
+ ]
324
+ );
325
+ const SubtitleSection = $el("div", { style: sectionStyle }, [
326
+ $el("label", { style: labelStyle }, ["4️⃣ Subtitle "]),
327
+ this.SubTitleInput,
328
+ subTitleNumDom,
329
+ ]);
330
+ const DescriptionSection = $el("div", { style: sectionStyle }, [
331
+ $el("label", { style: labelStyle }, ["5️⃣ Description "]),
332
+ this.descriptionInput,
333
+ // descriptionNumDom,
334
+ ]);
335
+ // switch between outputs section and additional inputs section
336
+ this.radioButtons = [];
337
+
338
+ this.radioButtonsCheck = $el("input", {
339
+ type: "radio",
340
+ name: "output_type",
341
+ value: "0",
342
+ id: "blockchain1",
343
+ checked: true,
344
+ });
345
+ this.radioButtonsCheckOff = $el("input", {
346
+ type: "radio",
347
+ name: "output_type",
348
+ value: "1",
349
+ id: "blockchain",
350
+ });
351
+
352
+ const blockChainSection = $el("div", { style: sectionStyle }, [
353
+ $el("label", { style: labelStyle }, ["6️⃣ Store on blockchain "]),
354
+ $el(
355
+ "label",
356
+ {
357
+ style: {
358
+ marginTop: "10px",
359
+ display: "flex",
360
+ alignItems: "center",
361
+ cursor: "pointer",
362
+ },
363
+ },
364
+ [
365
+ this.radioButtonsCheck,
366
+ $el("span", { style: { marginLeft: "5px" } }, ["ON"]),
367
+ ]
368
+ ),
369
+ $el(
370
+ "label",
371
+ { style: { display: "flex", alignItems: "center", cursor: "pointer" } },
372
+ [
373
+ this.radioButtonsCheckOff,
374
+ $el("span", { style: { marginLeft: "5px" } }, ["OFF"]),
375
+ ]
376
+ ),
377
+ $el(
378
+ "p",
379
+ { style: { fontSize: "16px", color: "#fff", margin: "10px 0 0 0" } },
380
+ ["Secure ownership with a permanent & decentralized storage"]
381
+ ),
382
+ ]);
383
+ // Message Section
384
+ this.message = $el(
385
+ "div",
386
+ {
387
+ style: {
388
+ color: "#ff3d00",
389
+ textAlign: "center",
390
+ padding: "10px",
391
+ fontSize: "20px",
392
+ },
393
+ },
394
+ []
395
+ );
396
+
397
+ this.shareButton = $el("button", {
398
+ type: "submit",
399
+ textContent: "Share",
400
+ style: buttonStyle,
401
+ onclick: () => {
402
+ this.handleShareButtonClick();
403
+ },
404
+ });
405
+
406
+ // Share and Close Buttons
407
+ const buttonsSection = $el(
408
+ "div",
409
+ {
410
+ style: {
411
+ textAlign: "right",
412
+ marginTop: "20px",
413
+ display: "flex",
414
+ justifyContent: "space-between",
415
+ },
416
+ },
417
+ [
418
+ $el("button", {
419
+ type: "button",
420
+ textContent: "Close",
421
+ style: {
422
+ ...buttonStyle,
423
+ backgroundColor: undefined,
424
+ },
425
+ onclick: () => {
426
+ this.close();
427
+ },
428
+ }),
429
+ this.shareButton,
430
+ ]
431
+ );
432
+
433
+ // Composing the full layout
434
+ const layout = [
435
+ headerSection,
436
+ linkSection,
437
+ accountSection,
438
+ outputUploadSection,
439
+ this.outputsSection,
440
+ additionalInputsSection,
441
+ SubtitleSection,
442
+ DescriptionSection,
443
+ // contestSection,
444
+ blockChainSection,
445
+ this.message,
446
+ buttonsSection,
447
+ ];
448
+
449
+ return layout;
450
+ }
451
+ /**
452
+ * api
453
+ * @param {url} path
454
+ * @param {params} options
455
+ * @param {statusText} statusText
456
+ * @returns
457
+ */
458
+ async fetchApi(path, options, statusText) {
459
+ if (statusText) {
460
+ this.message.textContent = statusText;
461
+ }
462
+ const fullPath = new URL(API_ENDPOINT + path);
463
+ const response = await fetch(fullPath, options);
464
+ if (!response.ok) {
465
+ throw new Error(response.statusText);
466
+ }
467
+ if (statusText) {
468
+ this.message.textContent = "";
469
+ }
470
+ const data = await response.json();
471
+ return {
472
+ ok: response.ok,
473
+ statusText: response.statusText,
474
+ status: response.status,
475
+ data,
476
+ };
477
+ }
478
+ /**
479
+ * @param {file} uploadFile
480
+ */
481
+ async uploadThumbnail(uploadFile, type) {
482
+ const form = new FormData();
483
+ form.append("file", uploadFile);
484
+ form.append("apiToken", this.keyInput.value);
485
+ try {
486
+ const res = await this.fetchApi(
487
+ `/client/common/opus/uploadImage`,
488
+ {
489
+ method: "POST",
490
+ body: form,
491
+ },
492
+ "Uploading thumbnail..."
493
+ );
494
+ if (res.status && res.data.status && res.data) {
495
+ const { data } = res.data;
496
+ if (type) {
497
+ this.allFilesImages.push({
498
+ url: data,
499
+ });
500
+ }
501
+ this.uploadedImages.push({
502
+ url: data,
503
+ });
504
+ } else {
505
+ throw new Error("make sure your API key is correct and try again later");
506
+ }
507
+ } catch (e) {
508
+ if (e?.response?.status === 413) {
509
+ throw new Error("File size is too large (max 20MB)");
510
+ } else {
511
+ throw new Error("Error uploading thumbnail: " + e.message);
512
+ }
513
+ }
514
+ }
515
+
516
+ async handleShareButtonClick() {
517
+ this.message.textContent = "";
518
+ try {
519
+ this.shareButton.disabled = true;
520
+ this.shareButton.textContent = "Sharing...";
521
+ await this.share();
522
+ } catch (e) {
523
+ alert(e.message);
524
+ }
525
+ this.shareButton.disabled = false;
526
+ this.shareButton.textContent = "Share";
527
+ }
528
+ /**
529
+ * share
530
+ * @param {string} title
531
+ * @param {string} subtitle
532
+ * @param {string} content
533
+ * @param {boolean} storeOnChain
534
+ * @param {string} coverUrl
535
+ * @param {string[]} imageUrls
536
+ * @param {string} apiToken
537
+ */
538
+ async share() {
539
+ const prompt = await app.graphToPrompt();
540
+ const workflowJSON = prompt["workflow"];
541
+ const form_values = {
542
+ title: this.TitleInput.value,
543
+ subTitle: this.SubTitleInput.value,
544
+ content: this.descriptionInput.value,
545
+ storeOnChain: this.radioButtonsCheck.checked ? true : false,
546
+ };
547
+
548
+ if (!this.keyInput.value) {
549
+ throw new Error("API key is required");
550
+ }
551
+
552
+ if (!this.uploadImagesInput.files[0] && !this.selectedFile) {
553
+ throw new Error("Thumbnail is required");
554
+ }
555
+
556
+ if (!form_values.title) {
557
+ throw new Error("Title is required");
558
+ }
559
+
560
+ if (!this.uploadedImages.length) {
561
+ if (this.selectedFile) {
562
+ await this.uploadThumbnail(this.selectedFile);
563
+ } else {
564
+ for (const file of this.uploadImagesInput.files) {
565
+ try {
566
+ await this.uploadThumbnail(file);
567
+ } catch (e) {
568
+ this.uploadedImages = [];
569
+ throw new Error(e.message);
570
+ }
571
+ }
572
+
573
+ if (this.uploadImagesInput.files.length === 0) {
574
+ throw new Error("No thumbnail uploaded");
575
+ }
576
+ }
577
+ }
578
+ if (this.allFiles.length > 0) {
579
+ for (const file of this.allFiles) {
580
+ try {
581
+ await this.uploadThumbnail(file, true);
582
+ } catch (e) {
583
+ this.allFilesImages = [];
584
+ throw new Error(e.message);
585
+ }
586
+ }
587
+ }
588
+ try {
589
+ const res = await this.fetchApi(
590
+ "/client/common/opus/shareFromComfyUI",
591
+ {
592
+ method: "POST",
593
+ headers: { "Content-Type": "application/json" },
594
+ body: JSON.stringify({
595
+ workflowJson: workflowJSON,
596
+ apiToken: this.keyInput.value,
597
+ coverUrl: this.uploadedImages[0].url,
598
+ imageUrls: this.allFilesImages.map((image) => image.url),
599
+ ...form_values,
600
+ }),
601
+ },
602
+ "Uploading workflow..."
603
+ );
604
+
605
+ if (res.status && res.data.status && res.data) {
606
+ localStorage.setItem("copus_token",this.keyInput.value);
607
+ const { data } = res.data;
608
+ if (data) {
609
+ const url = `${DEFAULT_HOMEPAGE_URL}/work/${data}`;
610
+ this.message.innerHTML = `Workflow has been shared successfully. <a href="${url}" target="_blank">Click here to view it.</a>`;
611
+ this.previewImage.src = "";
612
+ this.previewImage.style.display = "none";
613
+ this.uploadedImages = [];
614
+ this.allFilesImages = [];
615
+ this.allFiles = [];
616
+ this.TitleInput.value = "";
617
+ this.SubTitleInput.value = "";
618
+ this.descriptionInput.value = "";
619
+ this.selectedFile = null;
620
+ }
621
+ }
622
+ } catch (e) {
623
+ throw new Error("Error sharing workflow: " + e.message);
624
+ }
625
+ }
626
+
627
+ async fetchImageBlob(url) {
628
+ const response = await fetch(url);
629
+ const blob = await response.blob();
630
+ return blob;
631
+ }
632
+
633
+ async show({ potential_outputs, potential_output_nodes } = {}) {
634
+ // Sort `potential_output_nodes` by node ID to make the order always
635
+ // consistent, but we should also keep `potential_outputs` in the same
636
+ // order as `potential_output_nodes`.
637
+ const potential_output_to_order = {};
638
+ potential_output_nodes.forEach((node, index) => {
639
+ if (node.id in potential_output_to_order) {
640
+ potential_output_to_order[node.id][1].push(potential_outputs[index]);
641
+ } else {
642
+ potential_output_to_order[node.id] = [node, [potential_outputs[index]]];
643
+ }
644
+ });
645
+ // Sort the object `potential_output_to_order` by key (node ID)
646
+ const sorted_potential_output_to_order = Object.fromEntries(
647
+ Object.entries(potential_output_to_order).sort(
648
+ (a, b) => a[0].id - b[0].id
649
+ )
650
+ );
651
+ const sorted_potential_outputs = [];
652
+ const sorted_potential_output_nodes = [];
653
+ for (const [key, value] of Object.entries(
654
+ sorted_potential_output_to_order
655
+ )) {
656
+ sorted_potential_output_nodes.push(value[0]);
657
+ sorted_potential_outputs.push(...value[1]);
658
+ }
659
+ potential_output_nodes = sorted_potential_output_nodes;
660
+ potential_outputs = sorted_potential_outputs;
661
+ const apiToken = localStorage.getItem("copus_token");
662
+ this.message.innerHTML = "";
663
+ this.message.textContent = "";
664
+ this.element.style.display = "block";
665
+ this.previewImage.src = "";
666
+ this.previewImage.style.display = "none";
667
+ this.keyInput.value = apiToken!=null?apiToken:"";
668
+ this.uploadedImages = [];
669
+ this.allFilesImages = [];
670
+ this.allFiles = [];
671
+ // If `selectedNodeId` is provided, we will select the corresponding radio
672
+ // button for the node. In addition, we move the selected radio button to
673
+ // the top of the list.
674
+ if (this.selectedNodeId) {
675
+ const index = potential_output_nodes.findIndex(
676
+ (node) => node.id === this.selectedNodeId
677
+ );
678
+ if (index >= 0) {
679
+ this.selectedOutputIndex = index;
680
+ }
681
+ }
682
+
683
+ this.radioButtons = [];
684
+ const new_radio_buttons = $el(
685
+ "div",
686
+ {
687
+ id: "selectOutput-Options",
688
+ style: {
689
+ "overflow-y": "scroll",
690
+ "max-height": "200px",
691
+ display: "grid",
692
+ "grid-template-columns": "repeat(auto-fit, minmax(100px, 1fr))",
693
+ "grid-template-rows": "auto",
694
+ "grid-column-gap": "10px",
695
+ "grid-row-gap": "10px",
696
+ "margin-bottom": "10px",
697
+ padding: "10px",
698
+ "border-radius": "8px",
699
+ "box-shadow": "0 2px 4px rgba(0, 0, 0, 0.05)",
700
+ "background-color": "var(--bg-color)",
701
+ },
702
+ },
703
+ potential_outputs.map((output, index) => {
704
+ const { node_id } = output;
705
+ const radio_button = $el(
706
+ "input",
707
+ {
708
+ type: "radio",
709
+ name: "selectOutputImages",
710
+ value: index,
711
+ required: index === 0,
712
+ },
713
+ []
714
+ );
715
+ let radio_button_img;
716
+ let filename;
717
+ if (output.type === "image" || output.type === "temp") {
718
+ radio_button_img = $el(
719
+ "img",
720
+ {
721
+ src: `/view?filename=${output.image.filename}&subfolder=${output.image.subfolder}&type=${output.image.type}`,
722
+ style: {
723
+ width: "100px",
724
+ height: "100px",
725
+ objectFit: "cover",
726
+ borderRadius: "5px",
727
+ },
728
+ },
729
+ []
730
+ );
731
+ filename = output.image.filename;
732
+ } else if (output.type === "output") {
733
+ radio_button_img = $el(
734
+ "img",
735
+ {
736
+ src: output.output.value,
737
+ style: {
738
+ width: "auto",
739
+ height: "100px",
740
+ objectFit: "cover",
741
+ borderRadius: "5px",
742
+ },
743
+ },
744
+ []
745
+ );
746
+ filename = output.filename;
747
+ } else {
748
+ // unsupported output type
749
+ // this should never happen
750
+ radio_button_img = $el(
751
+ "img",
752
+ {
753
+ src: "",
754
+ style: { width: "auto", height: "100px" },
755
+ },
756
+ []
757
+ );
758
+ }
759
+ const radio_button_text = $el(
760
+ "span",
761
+ {
762
+ style: {
763
+ color: "gray",
764
+ display: "block",
765
+ fontSize: "12px",
766
+ overflowX: "hidden",
767
+ textOverflow: "ellipsis",
768
+ textWrap: "nowrap",
769
+ maxWidth: "100px",
770
+ },
771
+ },
772
+ [output.title]
773
+ );
774
+ const node_id_chip = $el(
775
+ "span",
776
+ {
777
+ style: {
778
+ color: "#FBFBFD",
779
+ display: "block",
780
+ backgroundColor: "rgba(0, 0, 0, 0.5)",
781
+ fontSize: "12px",
782
+ overflowX: "hidden",
783
+ padding: "2px 3px",
784
+ textOverflow: "ellipsis",
785
+ textWrap: "nowrap",
786
+ maxWidth: "100px",
787
+ position: "absolute",
788
+ top: "3px",
789
+ left: "3px",
790
+ borderRadius: "3px",
791
+ },
792
+ },
793
+ [`Node: ${node_id}`]
794
+ );
795
+ radio_button.style.color = "var(--fg-color)";
796
+ radio_button.checked = this.selectedOutputIndex === index;
797
+
798
+ radio_button.onchange = async () => {
799
+ this.selectedOutputIndex = parseInt(radio_button.value);
800
+
801
+ // Remove the "checked" class from all radio buttons
802
+ this.radioButtons.forEach((ele) => {
803
+ ele.parentElement.classList.remove("checked");
804
+ });
805
+ radio_button.parentElement.classList.add("checked");
806
+
807
+ this.fetchImageBlob(radio_button_img.src).then((blob) => {
808
+ const file = new File([blob], filename, {
809
+ type: blob.type,
810
+ });
811
+ this.previewImage.src = radio_button_img.src;
812
+ this.previewImage.style.display = "block";
813
+ this.selectedFile = file;
814
+ });
815
+
816
+ // Add the opacity style toggle here to indicate that they only need
817
+ // to upload one image or choose one from the outputs.
818
+ this.outputsSection.style.opacity = 1;
819
+ this.uploadImagesInput.style.opacity = 0.35;
820
+ };
821
+
822
+ if (radio_button.checked) {
823
+ this.fetchImageBlob(radio_button_img.src).then((blob) => {
824
+ const file = new File([blob], filename, {
825
+ type: blob.type,
826
+ });
827
+ this.previewImage.src = radio_button_img.src;
828
+ this.previewImage.style.display = "block";
829
+ this.selectedFile = file;
830
+ });
831
+ // Add the opacity style toggle here to indicate that they only need
832
+ // to upload one image or choose one from the outputs.
833
+ this.outputsSection.style.opacity = 1;
834
+ this.uploadImagesInput.style.opacity = 0.35;
835
+ }
836
+ this.radioButtons.push(radio_button);
837
+ let src = "";
838
+ if (output.type === "image" || output.type === "temp") {
839
+ filename = output.image.filename;
840
+ src = `/view?filename=${output.image.filename}&subfolder=${output.image.subfolder}&type=${output.image.type}`;
841
+ } else if (output.type === "output") {
842
+ src = output.output.value;
843
+ filename = output.filename;
844
+ }
845
+ if (src) {
846
+ this.fetchImageBlob(src).then((blob) => {
847
+ const file = new File([blob], filename, {
848
+ type: blob.type,
849
+ });
850
+ this.allFiles.push(file);
851
+ });
852
+ }
853
+ return $el(
854
+ `label.output_label${radio_button.checked ? ".checked" : ""}`,
855
+ {
856
+ style: {
857
+ display: "flex",
858
+ flexDirection: "column",
859
+ alignItems: "center",
860
+ justifyContent: "center",
861
+ marginBottom: "10px",
862
+ cursor: "pointer",
863
+ position: "relative",
864
+ },
865
+ },
866
+ [radio_button_img, radio_button_text, radio_button, node_id_chip]
867
+ );
868
+ })
869
+ );
870
+
871
+ const header = $el(
872
+ "p",
873
+ {
874
+ textContent:
875
+ this.radioButtons.length === 0
876
+ ? "Queue Prompt to see the outputs"
877
+ : "Or choose one from the outputs (scroll to see all)",
878
+ size: 2,
879
+ color: "white",
880
+ style: {
881
+ color: "white",
882
+ margin: "0 0 5px 0",
883
+ fontSize: "12px",
884
+ },
885
+ },
886
+ []
887
+ );
888
+ this.outputsSection.innerHTML = "";
889
+ this.outputsSection.appendChild(header);
890
+ this.outputsSection.appendChild(new_radio_buttons);
891
+ }
892
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-share-openart.js ADDED
@@ -0,0 +1,745 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {app} from "../../scripts/app.js";
2
+ import {api} from "../../scripts/api.js";
3
+ import {ComfyDialog, $el} from "../../scripts/ui.js";
4
+
5
+ const LOCAL_STORAGE_KEY = "openart_comfy_workflow_key";
6
+ const DEFAULT_HOMEPAGE_URL = "https://openart.ai/workflows/dev?developer=true";
7
+ //const DEFAULT_HOMEPAGE_URL = "http://localhost:8080/workflows/dev?developer=true";
8
+
9
+ const API_ENDPOINT = "https://openart.ai/api";
10
+ //const API_ENDPOINT = "http://localhost:8080/api";
11
+
12
+ const style = `
13
+ .openart-share-dialog a {
14
+ color: #f8f8f8;
15
+ }
16
+ .openart-share-dialog a:hover {
17
+ color: #007bff;
18
+ }
19
+ .output_label {
20
+ border: 5px solid transparent;
21
+ }
22
+ .output_label:hover {
23
+ border: 5px solid #59E8C6;
24
+ }
25
+ .output_label.checked {
26
+ border: 5px solid #59E8C6;
27
+ }
28
+ `;
29
+
30
+ // Shared component styles
31
+ const sectionStyle = {
32
+ marginBottom: 0,
33
+ padding: 0,
34
+ borderRadius: "8px",
35
+ boxShadow: "0 2px 4px rgba(0, 0, 0, 0.05)",
36
+ display: "flex",
37
+ flexDirection: "column",
38
+ justifyContent: "center",
39
+ };
40
+
41
+ export class OpenArtShareDialog extends ComfyDialog {
42
+ static instance = null;
43
+
44
+ constructor() {
45
+ super();
46
+ $el("style", {
47
+ textContent: style,
48
+ parent: document.head,
49
+ });
50
+ this.element = $el(
51
+ "div.comfy-modal.openart-share-dialog",
52
+ {
53
+ parent: document.body,
54
+ style: {
55
+ "overflow-y": "auto",
56
+ },
57
+ },
58
+ [$el("div.comfy-modal-content", {}, [...this.createButtons()])]
59
+ );
60
+ this.selectedOutputIndex = 0;
61
+ this.selectedNodeId = null;
62
+ this.uploadedImages = [];
63
+ this.selectedFile = null;
64
+ }
65
+
66
+ async readKey() {
67
+ let key = ""
68
+ try {
69
+ key = await api.fetchApi(`/manager/get_openart_auth`)
70
+ .then(response => response.json())
71
+ .then(data => {
72
+ return data.openart_key;
73
+ })
74
+ .catch(error => {
75
+ // console.log(error);
76
+ });
77
+ } catch (error) {
78
+ // console.log(error);
79
+ }
80
+ return key || "";
81
+ }
82
+
83
+ async saveKey(value) {
84
+ await api.fetchApi(`/manager/set_openart_auth`, {
85
+ method: 'POST',
86
+ headers: {'Content-Type': 'application/json'},
87
+ body: JSON.stringify({
88
+ openart_key: value
89
+ })
90
+ });
91
+ }
92
+
93
+ createButtons() {
94
+ const inputStyle = {
95
+ display: "block",
96
+ minWidth: "500px",
97
+ width: "100%",
98
+ padding: "10px",
99
+ margin: "10px 0",
100
+ borderRadius: "4px",
101
+ border: "1px solid #ddd",
102
+ boxSizing: "border-box",
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.NameInput = $el("input", {
183
+ type: "text",
184
+ placeholder: "Title (required)",
185
+ style: inputStyle,
186
+ });
187
+ this.descriptionInput = $el("textarea", {
188
+ placeholder: "Description (optional)",
189
+ style: {
190
+ ...inputStyle,
191
+ minHeight: "100px",
192
+ },
193
+ });
194
+
195
+ // Header Section
196
+ const headerSection = $el("h3", {
197
+ textContent: "Share your workflow to OpenArt",
198
+ size: 3,
199
+ color: "white",
200
+ style: {
201
+ 'text-align': 'center',
202
+ color: 'var(--input-text)',
203
+ margin: '0 0 10px 0',
204
+ }
205
+ });
206
+
207
+ // LinkSection
208
+ this.communityLink = $el("a", {
209
+ style: hyperLinkStyle,
210
+ href: DEFAULT_HOMEPAGE_URL,
211
+ target: "_blank"
212
+ }, ["👉 Check out thousands of workflows shared from the community"])
213
+ this.getAPIKeyLink = $el("a", {
214
+ style: {
215
+ ...hyperLinkStyle,
216
+ color: "#59E8C6"
217
+ },
218
+ href: DEFAULT_HOMEPAGE_URL,
219
+ target: "_blank"
220
+ }, ["👉 Get your API key here"])
221
+ const linkSection = $el(
222
+ "div",
223
+ {
224
+ style: {
225
+ marginTop: "10px",
226
+ display: "flex",
227
+ flexDirection: "column",
228
+ },
229
+ },
230
+ [
231
+ this.communityLink,
232
+ this.getAPIKeyLink,
233
+ ]
234
+ );
235
+
236
+ // Account Section
237
+ const accountSection = $el("div", {style: sectionStyle}, [
238
+ $el("label", {style: labelStyle}, ["1️⃣ OpenArt API Key"]),
239
+ this.keyInput,
240
+ ]);
241
+
242
+ // Output Upload Section
243
+ const outputUploadSection = $el("div", {style: sectionStyle}, [
244
+ $el("label", {
245
+ style: {
246
+ ...labelStyle,
247
+ margin: "10px 0 0 0"
248
+ }
249
+ }, ["2️⃣ Image/Thumbnail (Required)"]),
250
+ this.previewImage,
251
+ this.uploadImagesInput,
252
+ ]);
253
+
254
+ // Outputs Section
255
+ this.outputsSection = $el("div", {
256
+ id: "selectOutputs",
257
+ }, []);
258
+
259
+ // Additional Inputs Section
260
+ const additionalInputsSection = $el("div", {style: sectionStyle}, [
261
+ $el("label", {style: labelStyle}, ["3️⃣ Workflow Information"]),
262
+ this.NameInput,
263
+ this.descriptionInput,
264
+ ]);
265
+
266
+ // OpenArt Contest Section
267
+ /*
268
+ this.joinContestCheckbox = $el("input", {
269
+ type: 'checkbox',
270
+ id: "join_contest"s
271
+ }, [])
272
+ this.joinContestDescription = $el("a", {
273
+ style: {
274
+ ...hyperLinkStyle,
275
+ display: 'inline-block',
276
+ color: "#59E8C6",
277
+ fontSize: '12px',
278
+ marginLeft: '10px',
279
+ marginBottom: 0,
280
+ },
281
+ href: "https://contest.openart.ai/",
282
+ target: "_blank"
283
+ }, ["🏆 I'm participating in the OpenArt workflow contest"])
284
+ this.joinContestLabel = $el("label", {
285
+ style: {
286
+ display: 'flex',
287
+ alignItems: 'center',
288
+ cursor: 'pointer',
289
+ }
290
+ }, [this.joinContestCheckbox, this.joinContestDescription])
291
+ const contestSection = $el("div", {style: sectionStyle}, [
292
+ this.joinContestLabel,
293
+ ]);
294
+ */
295
+
296
+ // Message Section
297
+ this.message = $el(
298
+ "div",
299
+ {
300
+ style: {
301
+ color: "#ff3d00",
302
+ textAlign: "center",
303
+ padding: "10px",
304
+ fontSize: "20px",
305
+ },
306
+ },
307
+ []
308
+ );
309
+
310
+ this.shareButton = $el("button", {
311
+ type: "submit",
312
+ textContent: "Share",
313
+ style: buttonStyle,
314
+ onclick: () => {
315
+ this.handleShareButtonClick();
316
+ },
317
+ });
318
+
319
+ // Share and Close Buttons
320
+ const buttonsSection = $el(
321
+ "div",
322
+ {
323
+ style: {
324
+ textAlign: "right",
325
+ marginTop: "20px",
326
+ display: "flex",
327
+ justifyContent: "space-between",
328
+ },
329
+ },
330
+ [
331
+ $el("button", {
332
+ type: "button",
333
+ textContent: "Close",
334
+ style: {
335
+ ...buttonStyle,
336
+ backgroundColor: undefined,
337
+ },
338
+ onclick: () => {
339
+ this.close();
340
+ },
341
+ }),
342
+ this.shareButton,
343
+ ]
344
+ );
345
+
346
+ // Composing the full layout
347
+ const layout = [
348
+ headerSection,
349
+ linkSection,
350
+ accountSection,
351
+ outputUploadSection,
352
+ this.outputsSection,
353
+ additionalInputsSection,
354
+ // contestSection,
355
+ this.message,
356
+ buttonsSection,
357
+ ];
358
+
359
+ return layout;
360
+ }
361
+
362
+ async fetchApi(path, options, statusText) {
363
+ if (statusText) {
364
+ this.message.textContent = statusText;
365
+ }
366
+ const addSearchParams = (url, params = {}) =>
367
+ new URL(
368
+ `${url.origin}${url.pathname}?${new URLSearchParams([
369
+ ...Array.from(url.searchParams.entries()),
370
+ ...Object.entries(params),
371
+ ])}`
372
+ );
373
+
374
+ const fullPath = addSearchParams(new URL(API_ENDPOINT + path), {
375
+ workflow_api_key: this.keyInput.value,
376
+ });
377
+
378
+ const response = await fetch(fullPath, options);
379
+
380
+ if (!response.ok) {
381
+ throw new Error(response.statusText);
382
+ }
383
+
384
+ if (statusText) {
385
+ this.message.textContent = "";
386
+ }
387
+ const data = await response.json();
388
+ return {
389
+ ok: response.ok,
390
+ statusText: response.statusText,
391
+ status: response.status,
392
+ data,
393
+ };
394
+ }
395
+
396
+ async uploadThumbnail(uploadFile) {
397
+ const form = new FormData();
398
+ form.append("file", uploadFile);
399
+ try {
400
+ const res = await this.fetchApi(
401
+ `/workflows/upload_thumbnail`,
402
+ {
403
+ method: "POST",
404
+ body: form,
405
+ },
406
+ "Uploading thumbnail..."
407
+ );
408
+
409
+ if (res.ok && res.data) {
410
+ const {image_url, width, height} = res.data;
411
+ this.uploadedImages.push({
412
+ url: image_url,
413
+ width,
414
+ height,
415
+ });
416
+ }
417
+ } catch (e) {
418
+ if (e?.response?.status === 413) {
419
+ throw new Error("File size is too large (max 20MB)");
420
+ } else {
421
+ throw new Error("Error uploading thumbnail: " + e.message);
422
+ }
423
+ }
424
+ }
425
+
426
+ async handleShareButtonClick() {
427
+ this.message.textContent = "";
428
+ await this.saveKey(this.keyInput.value);
429
+ try {
430
+ this.shareButton.disabled = true;
431
+ this.shareButton.textContent = "Sharing...";
432
+ await this.share();
433
+ } catch (e) {
434
+ alert(e.message);
435
+ }
436
+ this.shareButton.disabled = false;
437
+ this.shareButton.textContent = "Share";
438
+ }
439
+
440
+ async share() {
441
+ const prompt = await app.graphToPrompt();
442
+ const workflowJSON = prompt["workflow"];
443
+ const workflowAPIJSON = prompt["output"];
444
+ const form_values = {
445
+ name: this.NameInput.value,
446
+ description: this.descriptionInput.value,
447
+ };
448
+
449
+ if (!this.keyInput.value) {
450
+ throw new Error("API key is required");
451
+ }
452
+
453
+ if (!this.uploadImagesInput.files[0] && !this.selectedFile) {
454
+ throw new Error("Thumbnail is required");
455
+ }
456
+
457
+ if (!form_values.name) {
458
+ throw new Error("Title is required");
459
+ }
460
+
461
+ const current_snapshot = await api.fetchApi(`/snapshot/get_current`)
462
+ .then(response => response.json())
463
+ .catch(error => {
464
+ // console.log(error);
465
+ });
466
+
467
+
468
+ if (!this.uploadedImages.length) {
469
+ if (this.selectedFile) {
470
+ await this.uploadThumbnail(this.selectedFile);
471
+ } else {
472
+ for (const file of this.uploadImagesInput.files) {
473
+ try {
474
+ await this.uploadThumbnail(file);
475
+ } catch (e) {
476
+ this.uploadedImages = [];
477
+ throw new Error(e.message);
478
+ }
479
+ }
480
+
481
+ if (this.uploadImagesInput.files.length === 0) {
482
+ throw new Error("No thumbnail uploaded");
483
+ }
484
+ }
485
+ }
486
+
487
+ // const join_contest = this.joinContestCheckbox.checked;
488
+
489
+ try {
490
+ const response = await this.fetchApi(
491
+ "/workflows/publish",
492
+ {
493
+ method: "POST",
494
+ headers: {"Content-Type": "application/json"},
495
+ body: JSON.stringify({
496
+ workflow_json: workflowJSON,
497
+ upload_images: this.uploadedImages,
498
+ form_values,
499
+ advanced_config: {
500
+ workflow_api_json: workflowAPIJSON,
501
+ snapshot: current_snapshot,
502
+ },
503
+ // join_contest,
504
+ }),
505
+ },
506
+ "Uploading workflow..."
507
+ );
508
+
509
+ if (response.ok) {
510
+ const {workflow_id} = response.data;
511
+ if (workflow_id) {
512
+ const url = `https://openart.ai/workflows/-/-/${workflow_id}`;
513
+ this.message.innerHTML = `Workflow has been shared successfully. <a href="${url}" target="_blank">Click here to view it.</a>`;
514
+ this.previewImage.src = "";
515
+ this.previewImage.style.display = "none";
516
+ this.uploadedImages = [];
517
+ this.NameInput.value = "";
518
+ this.descriptionInput.value = "";
519
+ this.radioButtons.forEach((ele) => {
520
+ ele.checked = false;
521
+ ele.parentElement.classList.remove("checked");
522
+ });
523
+ this.selectedOutputIndex = 0;
524
+ this.selectedNodeId = null;
525
+ this.selectedFile = null;
526
+ }
527
+ }
528
+ } catch (e) {
529
+ throw new Error("Error sharing workflow: " + e.message);
530
+ }
531
+ }
532
+
533
+ async fetchImageBlob(url) {
534
+ const response = await fetch(url);
535
+ const blob = await response.blob();
536
+ return blob;
537
+ }
538
+
539
+ async show({potential_outputs, potential_output_nodes} = {}) {
540
+ // Sort `potential_output_nodes` by node ID to make the order always
541
+ // consistent, but we should also keep `potential_outputs` in the same
542
+ // order as `potential_output_nodes`.
543
+ const potential_output_to_order = {};
544
+ potential_output_nodes.forEach((node, index) => {
545
+ if (node.id in potential_output_to_order) {
546
+ potential_output_to_order[node.id][1].push(potential_outputs[index]);
547
+ } else {
548
+ potential_output_to_order[node.id] = [node, [potential_outputs[index]]];
549
+ }
550
+ })
551
+ // Sort the object `potential_output_to_order` by key (node ID)
552
+ const sorted_potential_output_to_order = Object.fromEntries(
553
+ Object.entries(potential_output_to_order).sort((a, b) => a[0].id - b[0].id)
554
+ );
555
+ const sorted_potential_outputs = []
556
+ const sorted_potential_output_nodes = []
557
+ for (const [key, value] of Object.entries(sorted_potential_output_to_order)) {
558
+ sorted_potential_output_nodes.push(value[0]);
559
+ sorted_potential_outputs.push(...value[1]);
560
+ }
561
+ potential_output_nodes = sorted_potential_output_nodes;
562
+ potential_outputs = sorted_potential_outputs;
563
+
564
+ this.message.innerHTML = "";
565
+ this.message.textContent = "";
566
+ this.element.style.display = "block";
567
+ this.previewImage.src = "";
568
+ this.previewImage.style.display = "none";
569
+ const key = await this.readKey();
570
+ this.keyInput.value = key;
571
+ this.uploadedImages = [];
572
+
573
+ // If `selectedNodeId` is provided, we will select the corresponding radio
574
+ // button for the node. In addition, we move the selected radio button to
575
+ // the top of the list.
576
+ if (this.selectedNodeId) {
577
+ const index = potential_output_nodes.findIndex(node => node.id === this.selectedNodeId);
578
+ if (index >= 0) {
579
+ this.selectedOutputIndex = index;
580
+ }
581
+ }
582
+
583
+ this.radioButtons = [];
584
+ const new_radio_buttons = $el("div",
585
+ {
586
+ id: "selectOutput-Options",
587
+ style: {
588
+ 'overflow-y': 'scroll',
589
+ 'max-height': '200px',
590
+
591
+ 'display': 'grid',
592
+ 'grid-template-columns': 'repeat(auto-fit, minmax(100px, 1fr))',
593
+ 'grid-template-rows': 'auto',
594
+ 'grid-column-gap': '10px',
595
+ 'grid-row-gap': '10px',
596
+ 'margin-bottom': '10px',
597
+ 'padding': '10px',
598
+ 'border-radius': '8px',
599
+ 'box-shadow': '0 2px 4px rgba(0, 0, 0, 0.05)',
600
+ 'background-color': 'var(--bg-color)',
601
+ }
602
+ },
603
+ potential_outputs.map((output, index) => {
604
+ const {node_id} = output;
605
+ const radio_button = $el("input", {
606
+ type: 'radio',
607
+ name: "selectOutputImages",
608
+ value: index,
609
+ required: index === 0
610
+ }, [])
611
+ let radio_button_img;
612
+ let filename;
613
+ if (output.type === "image" || output.type === "temp") {
614
+ radio_button_img = $el("img", {
615
+ src: `/view?filename=${output.image.filename}&subfolder=${output.image.subfolder}&type=${output.image.type}`,
616
+ style: {
617
+ width: "100px",
618
+ height: "100px",
619
+ objectFit: "cover",
620
+ borderRadius: "5px"
621
+ }
622
+ }, []);
623
+ filename = output.image.filename
624
+ } else if (output.type === "output") {
625
+ radio_button_img = $el("img", {
626
+ src: output.output.value,
627
+ style: {
628
+ width: "auto",
629
+ height: "100px",
630
+ objectFit: "cover",
631
+ borderRadius: "5px"
632
+ }
633
+ }, []);
634
+ filename = output.filename
635
+ } else {
636
+ // unsupported output type
637
+ // this should never happen
638
+ // TODO
639
+ radio_button_img = $el("img", {
640
+ src: "",
641
+ style: {width: "auto", height: "100px"}
642
+ }, []);
643
+ }
644
+ const radio_button_text = $el("span", {
645
+ style: {
646
+ color: 'gray',
647
+ display: 'block',
648
+ fontSize: '12px',
649
+ overflowX: 'hidden',
650
+ textOverflow: 'ellipsis',
651
+ textWrap: 'nowrap',
652
+ maxWidth: '100px',
653
+ }
654
+ }, [output.title])
655
+ const node_id_chip = $el("span", {
656
+ style: {
657
+ color: '#FBFBFD',
658
+ display: 'block',
659
+ backgroundColor: 'rgba(0, 0, 0, 0.5)',
660
+ fontSize: '12px',
661
+ overflowX: 'hidden',
662
+ padding: '2px 3px',
663
+ textOverflow: 'ellipsis',
664
+ textWrap: 'nowrap',
665
+ maxWidth: '100px',
666
+ position: 'absolute',
667
+ top: '3px',
668
+ left: '3px',
669
+ borderRadius: '3px',
670
+ }
671
+ }, [`Node: ${node_id}`])
672
+ radio_button.style.color = "var(--fg-color)";
673
+ radio_button.checked = this.selectedOutputIndex === index;
674
+
675
+ radio_button.onchange = async () => {
676
+ this.selectedOutputIndex = parseInt(radio_button.value);
677
+
678
+ // Remove the "checked" class from all radio buttons
679
+ this.radioButtons.forEach((ele) => {
680
+ ele.parentElement.classList.remove("checked");
681
+ });
682
+ radio_button.parentElement.classList.add("checked");
683
+
684
+ this.fetchImageBlob(radio_button_img.src).then((blob) => {
685
+ const file = new File([blob], filename, {
686
+ type: blob.type,
687
+ });
688
+ this.previewImage.src = radio_button_img.src;
689
+ this.previewImage.style.display = "block";
690
+ this.selectedFile = file;
691
+ })
692
+
693
+ // Add the opacity style toggle here to indicate that they only need
694
+ // to upload one image or choose one from the outputs.
695
+ this.outputsSection.style.opacity = 1;
696
+ this.uploadImagesInput.style.opacity = 0.35;
697
+ };
698
+
699
+ if (radio_button.checked) {
700
+ this.fetchImageBlob(radio_button_img.src).then((blob) => {
701
+ const file = new File([blob], filename, {
702
+ type: blob.type,
703
+ });
704
+ this.previewImage.src = radio_button_img.src;
705
+ this.previewImage.style.display = "block";
706
+ this.selectedFile = file;
707
+ })
708
+ // Add the opacity style toggle here to indicate that they only need
709
+ // to upload one image or choose one from the outputs.
710
+ this.outputsSection.style.opacity = 1;
711
+ this.uploadImagesInput.style.opacity = 0.35;
712
+ }
713
+
714
+ this.radioButtons.push(radio_button);
715
+
716
+ return $el(`label.output_label${radio_button.checked ? '.checked' : ''}`, {
717
+ style: {
718
+ display: "flex",
719
+ flexDirection: "column",
720
+ alignItems: "center",
721
+ justifyContent: "center",
722
+ marginBottom: "10px",
723
+ cursor: "pointer",
724
+ position: 'relative',
725
+ }
726
+ }, [radio_button_img, radio_button_text, radio_button, node_id_chip]);
727
+ })
728
+ );
729
+
730
+ const header =
731
+ $el("p", {
732
+ textContent: this.radioButtons.length === 0 ? "Queue Prompt to see the outputs" : "Or choose one from the outputs (scroll to see all)",
733
+ size: 2,
734
+ color: "white",
735
+ style: {
736
+ color: 'var(--input-text)',
737
+ margin: '0 0 5px 0',
738
+ fontSize: '12px',
739
+ },
740
+ }, [])
741
+ this.outputsSection.innerHTML = "";
742
+ this.outputsSection.appendChild(header);
743
+ this.outputsSection.appendChild(new_radio_buttons);
744
+ }
745
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/js/comfyui-share-youml.js ADDED
@@ -0,0 +1,568 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {app} from "../../scripts/app.js";
2
+ import {api} from "../../scripts/api.js";
3
+ import {ComfyDialog, $el} from "../../scripts/ui.js";
4
+
5
+ const BASE_URL = "https://youml.com";
6
+ //const BASE_URL = "http://localhost:3000";
7
+ const DEFAULT_HOMEPAGE_URL = `${BASE_URL}/?from=comfyui`;
8
+ const TOKEN_PAGE_URL = `${BASE_URL}/my-token`;
9
+ const API_ENDPOINT = `${BASE_URL}/api`;
10
+
11
+ const style = `
12
+ .youml-share-dialog {
13
+ overflow-y: auto;
14
+ }
15
+ .youml-share-dialog .dialog-header {
16
+ text-align: center;
17
+ color: white;
18
+ margin: 0 0 10px 0;
19
+ }
20
+ .youml-share-dialog .dialog-section {
21
+ margin-bottom: 0;
22
+ padding: 0;
23
+ border-radius: 8px;
24
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
25
+ display: flex;
26
+ flex-direction: column;
27
+ justify-content: center;
28
+ }
29
+ .youml-share-dialog input, .youml-share-dialog textarea {
30
+ display: block;
31
+ min-width: 500px;
32
+ width: 100%;
33
+ padding: 10px;
34
+ margin: 10px 0;
35
+ border-radius: 4px;
36
+ border: 1px solid #ddd;
37
+ box-sizing: border-box;
38
+ }
39
+ .youml-share-dialog textarea {
40
+ color: var(--input-text);
41
+ background-color: var(--comfy-input-bg);
42
+ }
43
+ .youml-share-dialog .workflow-description {
44
+ min-height: 75px;
45
+ }
46
+ .youml-share-dialog label {
47
+ color: #f8f8f8;
48
+ display: block;
49
+ margin: 5px 0 0 0;
50
+ font-weight: bold;
51
+ text-decoration: none;
52
+ }
53
+ .youml-share-dialog .action-button {
54
+ padding: 10px 80px;
55
+ margin: 10px 5px;
56
+ border-radius: 4px;
57
+ border: none;
58
+ cursor: pointer;
59
+ }
60
+ .youml-share-dialog .share-button {
61
+ color: #fff;
62
+ background-color: #007bff;
63
+ }
64
+ .youml-share-dialog .close-button {
65
+ background-color: none;
66
+ }
67
+ .youml-share-dialog .action-button-panel {
68
+ text-align: right;
69
+ display: flex;
70
+ justify-content: space-between;
71
+ }
72
+ .youml-share-dialog .status-message {
73
+ color: #fd7909;
74
+ text-align: center;
75
+ padding: 5px;
76
+ font-size: 18px;
77
+ }
78
+ .youml-share-dialog .status-message a {
79
+ color: white;
80
+ }
81
+ .youml-share-dialog .output-panel {
82
+ overflow: auto;
83
+ max-height: 180px;
84
+ display: grid;
85
+ grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
86
+ grid-template-rows: auto;
87
+ grid-column-gap: 10px;
88
+ grid-row-gap: 10px;
89
+ margin-bottom: 10px;
90
+ padding: 10px;
91
+ border-radius: 8px;
92
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
93
+ background-color: var(--bg-color);
94
+ }
95
+ .youml-share-dialog .output-panel .output-image {
96
+ width: 100px;
97
+ height: 100px;
98
+ objectFit: cover;
99
+ borderRadius: 5px;
100
+ }
101
+
102
+ .youml-share-dialog .output-panel .radio-button {
103
+ color:var(--fg-color);
104
+ }
105
+ .youml-share-dialog .output-panel .radio-text {
106
+ color: gray;
107
+ display: block;
108
+ font-size: 12px;
109
+ overflow-x: hidden;
110
+ text-overflow: ellipsis;
111
+ text-wrap: nowrap;
112
+ max-width: 100px;
113
+ }
114
+ .youml-share-dialog .output-panel .node-id {
115
+ color: #FBFBFD;
116
+ display: block;
117
+ background-color: rgba(0, 0, 0, 0.5);
118
+ font-size: 12px;
119
+ overflow-x: hidden;
120
+ padding: 2px 3px;
121
+ text-overflow: ellipsis;
122
+ text-wrap: nowrap;
123
+ max-width: 100px;
124
+ position: absolute;
125
+ top: 3px;
126
+ left: 3px;
127
+ border-radius: 3px;
128
+ }
129
+ .youml-share-dialog .output-panel .output-label {
130
+ display: flex;
131
+ flex-direction: column;
132
+ align-items: center;
133
+ justify-content: center;
134
+ margin-bottom: 10px;
135
+ cursor: pointer;
136
+ position: relative;
137
+ border: 5px solid transparent;
138
+ }
139
+ .youml-share-dialog .output-panel .output-label:hover {
140
+ border: 5px solid #007bff;
141
+ }
142
+ .youml-share-dialog .output-panel .output-label.checked {
143
+ border: 5px solid #007bff;
144
+ }
145
+ .youml-share-dialog .missing-output-message{
146
+ color: #fd7909;
147
+ font-size: 16px;
148
+ margin-bottom:10px
149
+ }
150
+ .youml-share-dialog .select-output-message{
151
+ color: white;
152
+ margin-bottom:5px
153
+ }
154
+ `;
155
+
156
+ export class YouMLShareDialog extends ComfyDialog {
157
+ static instance = null;
158
+
159
+ constructor() {
160
+ super();
161
+ $el("style", {
162
+ textContent: style,
163
+ parent: document.head,
164
+ });
165
+ this.element = $el(
166
+ "div.comfy-modal.youml-share-dialog",
167
+ {
168
+ parent: document.body,
169
+ },
170
+ [$el("div.comfy-modal-content", {}, [...this.createLayout()])]
171
+ );
172
+ this.selectedOutputIndex = 0;
173
+ this.selectedNodeId = null;
174
+ this.uploadedImages = [];
175
+ this.selectedFile = null;
176
+ }
177
+
178
+ async loadToken() {
179
+ let key = ""
180
+ try {
181
+ const response = await api.fetchApi(`/manager/youml/settings`)
182
+ const settings = await response.json()
183
+ return settings.token
184
+ } catch (error) {
185
+ }
186
+ return key || "";
187
+ }
188
+
189
+ async saveToken(value) {
190
+ await api.fetchApi(`/manager/youml/settings`, {
191
+ method: 'POST',
192
+ headers: {'Content-Type': 'application/json'},
193
+ body: JSON.stringify({
194
+ token: value
195
+ })
196
+ });
197
+ }
198
+
199
+ createLayout() {
200
+ // Header Section
201
+ const headerSection = $el("h3.dialog-header", {
202
+ textContent: "Share your workflow to YouML.com",
203
+ size: 3,
204
+ });
205
+
206
+ // Workflow Info Section
207
+ this.nameInput = $el("input", {
208
+ type: "text",
209
+ placeholder: "Name (required)",
210
+ });
211
+ this.descriptionInput = $el("textarea.workflow-description", {
212
+ placeholder: "Description (optional, markdown supported)",
213
+ });
214
+ const workflowMetadata = $el("div.dialog-section", {}, [
215
+ $el("label", {}, ["Workflow info"]),
216
+ this.nameInput,
217
+ this.descriptionInput,
218
+ ]);
219
+
220
+ // Outputs Section
221
+ this.outputsSection = $el("div.dialog-section", {
222
+ id: "selectOutputs",
223
+ }, []);
224
+
225
+ const outputUploadSection = $el("div.dialog-section", {}, [
226
+ $el("label", {}, ["Thumbnail"]),
227
+ this.outputsSection,
228
+ ]);
229
+
230
+ // API Token Section
231
+ this.apiTokenInput = $el("input", {
232
+ type: "password",
233
+ placeholder: "Copy & paste your API token",
234
+ });
235
+ const getAPITokenButton = $el("button", {
236
+ href: DEFAULT_HOMEPAGE_URL,
237
+ target: "_blank",
238
+ onclick: () => window.open(TOKEN_PAGE_URL, "_blank"),
239
+ }, ["Get your API Token"])
240
+
241
+ const apiTokenSection = $el("div.dialog-section", {}, [
242
+ $el("label", {}, ["YouML API Token"]),
243
+ this.apiTokenInput,
244
+ getAPITokenButton,
245
+ ]);
246
+
247
+ // Message Section
248
+ this.message = $el("div.status-message", {}, []);
249
+
250
+ // Share and Close Buttons
251
+ this.shareButton = $el("button.action-button.share-button", {
252
+ type: "submit",
253
+ textContent: "Share",
254
+ onclick: () => {
255
+ this.handleShareButtonClick();
256
+ },
257
+ });
258
+
259
+ const buttonsSection = $el(
260
+ "div.action-button-panel",
261
+ {},
262
+ [
263
+ $el("button.action-button.close-button", {
264
+ type: "button",
265
+ textContent: "Close",
266
+ onclick: () => {
267
+ this.close();
268
+ },
269
+ }),
270
+ this.shareButton,
271
+ ]
272
+ );
273
+
274
+ // Composing the full layout
275
+ const layout = [
276
+ headerSection,
277
+ workflowMetadata,
278
+ outputUploadSection,
279
+ apiTokenSection,
280
+ this.message,
281
+ buttonsSection,
282
+ ];
283
+
284
+ return layout;
285
+ }
286
+
287
+ async fetchYoumlApi(path, options, statusText) {
288
+ if (statusText) {
289
+ this.message.textContent = statusText;
290
+ }
291
+
292
+ const fullPath = new URL(API_ENDPOINT + path)
293
+
294
+ const fetchOptions = Object.assign({}, options)
295
+
296
+ fetchOptions.headers = {
297
+ ...fetchOptions.headers,
298
+ "Authorization": `Bearer ${this.apiTokenInput.value}`,
299
+ "User-Agent": "ComfyUI-Manager-Youml/1.0.0",
300
+ }
301
+
302
+ const response = await fetch(fullPath, fetchOptions);
303
+
304
+ if (!response.ok) {
305
+ throw new Error(response.statusText + " " + (await response.text()));
306
+ }
307
+
308
+ if (statusText) {
309
+ this.message.textContent = "";
310
+ }
311
+ const data = await response.json();
312
+ return {
313
+ ok: response.ok,
314
+ statusText: response.statusText,
315
+ status: response.status,
316
+ data,
317
+ };
318
+ }
319
+
320
+ async uploadThumbnail(uploadFile, recipeId) {
321
+ const form = new FormData();
322
+ form.append("file", uploadFile, uploadFile.name);
323
+ try {
324
+ const res = await this.fetchYoumlApi(
325
+ `/v1/comfy/recipes/${recipeId}/thumbnail`,
326
+ {
327
+ method: "POST",
328
+ body: form,
329
+ },
330
+ "Uploading thumbnail..."
331
+ );
332
+
333
+ } catch (e) {
334
+ if (e?.response?.status === 413) {
335
+ throw new Error("File size is too large (max 20MB)");
336
+ } else {
337
+ throw new Error("Error uploading thumbnail: " + e.message);
338
+ }
339
+ }
340
+ }
341
+
342
+ async handleShareButtonClick() {
343
+ this.message.textContent = "";
344
+ await this.saveToken(this.apiTokenInput.value);
345
+ try {
346
+ this.shareButton.disabled = true;
347
+ this.shareButton.textContent = "Sharing...";
348
+ await this.share();
349
+ } catch (e) {
350
+ alert(e.message);
351
+ } finally {
352
+ this.shareButton.disabled = false;
353
+ this.shareButton.textContent = "Share";
354
+ }
355
+ }
356
+
357
+ async share() {
358
+ const prompt = await app.graphToPrompt();
359
+ const workflowJSON = prompt["workflow"];
360
+ const workflowAPIJSON = prompt["output"];
361
+ const form_values = {
362
+ name: this.nameInput.value,
363
+ description: this.descriptionInput.value,
364
+ };
365
+
366
+ if (!this.apiTokenInput.value) {
367
+ throw new Error("API token is required");
368
+ }
369
+
370
+ if (!this.selectedFile) {
371
+ throw new Error("Thumbnail is required");
372
+ }
373
+
374
+ if (!form_values.name) {
375
+ throw new Error("Title is required");
376
+ }
377
+
378
+
379
+ try {
380
+ let snapshotData = null;
381
+ try {
382
+ const snapshot = await api.fetchApi(`/snapshot/get_current`)
383
+ snapshotData = await snapshot.json()
384
+ } catch (e) {
385
+ console.error("Failed to get snapshot", e)
386
+ }
387
+
388
+ const request = {
389
+ name: this.nameInput.value,
390
+ description: this.descriptionInput.value,
391
+ workflowUiJson: JSON.stringify(workflowJSON),
392
+ workflowApiJson: JSON.stringify(workflowAPIJSON),
393
+ }
394
+
395
+ if (snapshotData) {
396
+ request.snapshotJson = JSON.stringify(snapshotData)
397
+ }
398
+
399
+ const response = await this.fetchYoumlApi(
400
+ "/v1/comfy/recipes",
401
+ {
402
+ method: "POST",
403
+ headers: {"Content-Type": "application/json"},
404
+ body: JSON.stringify(request),
405
+ },
406
+ "Uploading workflow..."
407
+ );
408
+
409
+ if (response.ok) {
410
+ const {id, recipePageUrl, editorPageUrl} = response.data;
411
+ if (id) {
412
+ let messagePrefix = "Workflow has been shared."
413
+ if (this.selectedFile) {
414
+ try {
415
+ await this.uploadThumbnail(this.selectedFile, id);
416
+ } catch (e) {
417
+ console.error("Thumbnail upload failed: ", e);
418
+ messagePrefix = "Workflow has been shared, but thumbnail upload failed. You can create a thumbnail on YouML later."
419
+ }
420
+ }
421
+ this.message.innerHTML = `${messagePrefix} To turn your workflow into an interactive app, ` +
422
+ `<a href="${recipePageUrl}" target="_blank">visit it on YouML</a>`;
423
+
424
+ this.uploadedImages = [];
425
+ this.nameInput.value = "";
426
+ this.descriptionInput.value = "";
427
+ this.radioButtons.forEach((ele) => {
428
+ ele.checked = false;
429
+ ele.parentElement.classList.remove("checked");
430
+ });
431
+ this.selectedOutputIndex = 0;
432
+ this.selectedNodeId = null;
433
+ this.selectedFile = null;
434
+ }
435
+ }
436
+ } catch (e) {
437
+ throw new Error("Error sharing workflow: " + e.message);
438
+ }
439
+ }
440
+
441
+ async fetchImageBlob(url) {
442
+ const response = await fetch(url);
443
+ const blob = await response.blob();
444
+ return blob;
445
+ }
446
+
447
+ async show(potentialOutputs, potentialOutputNodes) {
448
+ const potentialOutputsToOrder = {};
449
+ potentialOutputNodes.forEach((node, index) => {
450
+ if (node.id in potentialOutputsToOrder) {
451
+ potentialOutputsToOrder[node.id][1].push(potentialOutputs[index]);
452
+ } else {
453
+ potentialOutputsToOrder[node.id] = [node, [potentialOutputs[index]]];
454
+ }
455
+ })
456
+ const sortedPotentialOutputsToOrder = Object.fromEntries(
457
+ Object.entries(potentialOutputsToOrder).sort((a, b) => a[0].id - b[0].id)
458
+ );
459
+ const sortedPotentialOutputs = []
460
+ const sortedPotentiaOutputNodes = []
461
+ for (const [key, value] of Object.entries(sortedPotentialOutputsToOrder)) {
462
+ sortedPotentiaOutputNodes.push(value[0]);
463
+ sortedPotentialOutputs.push(...value[1]);
464
+ }
465
+ potentialOutputNodes = sortedPotentiaOutputNodes;
466
+ potentialOutputs = sortedPotentialOutputs;
467
+
468
+
469
+ // If `selectedNodeId` is provided, we will select the corresponding radio
470
+ // button for the node. In addition, we move the selected radio button to
471
+ // the top of the list.
472
+ if (this.selectedNodeId) {
473
+ const index = potentialOutputNodes.findIndex(node => node.id === this.selectedNodeId);
474
+ if (index >= 0) {
475
+ this.selectedOutputIndex = index;
476
+ }
477
+ }
478
+
479
+ this.radioButtons = [];
480
+ const newRadioButtons = $el("div.output-panel",
481
+ {
482
+ id: "selectOutput-Options",
483
+ },
484
+ potentialOutputs.map((output, index) => {
485
+ const {node_id: nodeId} = output;
486
+ const radioButton = $el("input.radio-button", {
487
+ type: "radio",
488
+ name: "selectOutputImages",
489
+ value: index,
490
+ required: index === 0
491
+ }, [])
492
+ let radioButtonImage;
493
+ let filename;
494
+ if (output.type === "image" || output.type === "temp") {
495
+ radioButtonImage = $el("img.output-image", {
496
+ src: `/view?filename=${output.image.filename}&subfolder=${output.image.subfolder}&type=${output.image.type}`,
497
+ }, []);
498
+ filename = output.image.filename
499
+ } else if (output.type === "output") {
500
+ radioButtonImage = $el("img.output-image", {
501
+ src: output.output.value,
502
+ }, []);
503
+ filename = output.output.filename
504
+ } else {
505
+ radioButtonImage = $el("img.output-image", {
506
+ src: "",
507
+ }, []);
508
+ }
509
+ const radioButtonText = $el("span.radio-text", {}, [output.title])
510
+ const nodeIdChip = $el("span.node-id", {}, [`Node: ${nodeId}`])
511
+ radioButton.checked = this.selectedOutputIndex === index;
512
+
513
+ radioButton.onchange = async () => {
514
+ this.selectedOutputIndex = parseInt(radioButton.value);
515
+
516
+ // Remove the "checked" class from all radio buttons
517
+ this.radioButtons.forEach((ele) => {
518
+ ele.parentElement.classList.remove("checked");
519
+ });
520
+ radioButton.parentElement.classList.add("checked");
521
+
522
+ this.fetchImageBlob(radioButtonImage.src).then((blob) => {
523
+ const file = new File([blob], filename, {
524
+ type: blob.type,
525
+ });
526
+ this.selectedFile = file;
527
+ })
528
+ };
529
+
530
+ if (radioButton.checked) {
531
+ this.fetchImageBlob(radioButtonImage.src).then((blob) => {
532
+ const file = new File([blob], filename, {
533
+ type: blob.type,
534
+ });
535
+ this.selectedFile = file;
536
+ })
537
+ }
538
+
539
+ this.radioButtons.push(radioButton);
540
+
541
+ return $el(`label.output-label${radioButton.checked ? '.checked' : ''}`, {},
542
+ [radioButtonImage, radioButtonText, radioButton, nodeIdChip]);
543
+ })
544
+ );
545
+
546
+ let header;
547
+ if (this.radioButtons.length === 0) {
548
+ header = $el("div.missing-output-message", {textContent: "Queue Prompt to see the outputs and select a thumbnail"}, [])
549
+ } else {
550
+ header = $el("div.select-output-message", {textContent: "Choose one from the outputs (scroll to see all)"}, [])
551
+ }
552
+
553
+ this.outputsSection.innerHTML = "";
554
+ this.outputsSection.appendChild(header);
555
+ if (this.radioButtons.length > 0) {
556
+ this.outputsSection.appendChild(newRadioButtons);
557
+ }
558
+
559
+ this.message.innerHTML = "";
560
+ this.message.textContent = "";
561
+
562
+ const token = await this.loadToken();
563
+ this.apiTokenInput.value = token;
564
+ this.uploadedImages = [];
565
+
566
+ this.element.style.display = "block";
567
+ }
568
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/js/common.js ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../scripts/app.js";
2
+ import { api } from "../../scripts/api.js";
3
+ import { $el, ComfyDialog } from "../../scripts/ui.js";
4
+
5
+ export function show_message(msg) {
6
+ app.ui.dialog.show(msg);
7
+ app.ui.dialog.element.style.zIndex = 10010;
8
+ }
9
+
10
+ export async function sleep(ms) {
11
+ return new Promise(resolve => setTimeout(resolve, ms));
12
+ }
13
+
14
+ export function rebootAPI() {
15
+ if ('electronAPI' in window) {
16
+ window.electronAPI.restartApp();
17
+ return true;
18
+ }
19
+ if (confirm("Are you sure you'd like to reboot the server?")) {
20
+ try {
21
+ api.fetchApi("/manager/reboot");
22
+ }
23
+ catch(exception) {
24
+
25
+ }
26
+ return true;
27
+ }
28
+
29
+ return false;
30
+ }
31
+
32
+ export var manager_instance = null;
33
+
34
+ export function setManagerInstance(obj) {
35
+ manager_instance = obj;
36
+ }
37
+
38
+ export function showToast(message, duration = 3000) {
39
+ const toast = $el("div.comfy-toast", {textContent: message});
40
+ document.body.appendChild(toast);
41
+ setTimeout(() => {
42
+ toast.classList.add("comfy-toast-fadeout");
43
+ setTimeout(() => toast.remove(), 500);
44
+ }, duration);
45
+ }
46
+
47
+ function isValidURL(url) {
48
+ if(url.includes('&'))
49
+ return false;
50
+
51
+ const http_pattern = /^(https?|ftp):\/\/[^\s$?#]+$/;
52
+ const ssh_pattern = /^(.+@|ssh:\/\/).+:.+$/;
53
+ return http_pattern.test(url) || ssh_pattern.test(url);
54
+ }
55
+
56
+ export async function install_pip(packages) {
57
+ if(packages.includes('&'))
58
+ app.ui.dialog.show(`Invalid PIP package enumeration: '${packages}'`);
59
+
60
+ const res = await api.fetchApi("/customnode/install/pip", {
61
+ method: "POST",
62
+ body: packages,
63
+ });
64
+
65
+ if(res.status == 403) {
66
+ show_message('This action is not allowed with this security level configuration.');
67
+ return;
68
+ }
69
+
70
+ if(res.status == 200) {
71
+ 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.`);
72
+
73
+ const rebootButton = document.getElementById('cm-reboot-button3');
74
+ const self = this;
75
+
76
+ rebootButton.addEventListener("click", rebootAPI);
77
+ }
78
+ else {
79
+ show_message(`Failed to install '${packages}'<BR>See terminal log.`);
80
+ }
81
+ }
82
+
83
+ export async function install_via_git_url(url, manager_dialog) {
84
+ if(!url) {
85
+ return;
86
+ }
87
+
88
+ if(!isValidURL(url)) {
89
+ show_message(`Invalid Git url '${url}'`);
90
+ return;
91
+ }
92
+
93
+ show_message(`Wait...<BR><BR>Installing '${url}'`);
94
+
95
+ const res = await api.fetchApi("/customnode/install/git_url", {
96
+ method: "POST",
97
+ body: url,
98
+ });
99
+
100
+ if(res.status == 403) {
101
+ show_message('This action is not allowed with this security level configuration.');
102
+ return;
103
+ }
104
+
105
+ if(res.status == 200) {
106
+ 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.`);
107
+
108
+ const rebootButton = document.getElementById('cm-reboot-button4');
109
+ const self = this;
110
+
111
+ rebootButton.addEventListener("click",
112
+ function() {
113
+ if(rebootAPI()) {
114
+ manager_dialog.close();
115
+ }
116
+ });
117
+ }
118
+ else {
119
+ show_message(`Failed to install '${url}'<BR>See terminal log.`);
120
+ }
121
+ }
122
+
123
+ export async function free_models(free_execution_cache) {
124
+ try {
125
+ let mode = "";
126
+ if(free_execution_cache) {
127
+ mode = '{"unload_models": true, "free_memory": true}';
128
+ }
129
+ else {
130
+ mode = '{"unload_models": true}';
131
+ }
132
+
133
+ let res = await api.fetchApi(`/free`, {
134
+ method: 'POST',
135
+ headers: { 'Content-Type': 'application/json' },
136
+ body: mode
137
+ });
138
+
139
+ if (res.status == 200) {
140
+ if(free_execution_cache) {
141
+ showToast("'Models' and 'Execution Cache' have been cleared.", 3000);
142
+ }
143
+ else {
144
+ showToast("Models' have been unloaded.", 3000);
145
+ }
146
+ } else {
147
+ showToast('Unloading of models failed. Installed ComfyUI may be an outdated version.', 5000);
148
+ }
149
+ } catch (error) {
150
+ showToast('An error occurred while trying to unload models.', 5000);
151
+ }
152
+ }
153
+
154
+ export function md5(inputString) {
155
+ const hc = '0123456789abcdef';
156
+ 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;}
157
+ const ad = (x,y) => {let l=(x&0xFFFF)+(y&0xFFFF);let m=(x>>16)+(y>>16)+(l>>16);return (m<<16)|(l&0xFFFF);}
158
+ const rl = (n,c) => (n<<c)|(n>>>(32-c));
159
+ const cm = (q,a,b,x,s,t) => ad(rl(ad(ad(a,q),ad(x,t)),s),b);
160
+ const ff = (a,b,c,d,x,s,t) => cm((b&c)|((~b)&d),a,b,x,s,t);
161
+ const gg = (a,b,c,d,x,s,t) => cm((b&d)|(c&(~d)),a,b,x,s,t);
162
+ const hh = (a,b,c,d,x,s,t) => cm(b^c^d,a,b,x,s,t);
163
+ const ii = (a,b,c,d,x,s,t) => cm(c^(b|(~d)),a,b,x,s,t);
164
+ const sb = x => {
165
+ let i;const nblk=((x.length+8)>>6)+1;const blks=[];for(i=0;i<nblk*16;i++) { blks[i]=0 };
166
+ for(i=0;i<x.length;i++) {blks[i>>2]|=x.charCodeAt(i)<<((i%4)*8);}
167
+ blks[i>>2]|=0x80<<((i%4)*8);blks[nblk*16-2]=x.length*8;return blks;
168
+ }
169
+ let i,x=sb(inputString),a=1732584193,b=-271733879,c=-1732584194,d=271733878,olda,oldb,oldc,oldd;
170
+ for(i=0;i<x.length;i+=16) {olda=a;oldb=b;oldc=c;oldd=d;
171
+ 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);
172
+ 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);
173
+ 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);
174
+ 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);
175
+ 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);
176
+ 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);
177
+ 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);
178
+ 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);
179
+ 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);
180
+ 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);
181
+ 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);
182
+ 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);
183
+ 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);
184
+ 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);
185
+ 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);
186
+ 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);
187
+ 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);
188
+ 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);
189
+ 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);
190
+ 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);
191
+ 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);
192
+ 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);
193
+ }
194
+ return rh(a)+rh(b)+rh(c)+rh(d);
195
+ }
196
+
197
+ export async function fetchData(route, options) {
198
+ let err;
199
+ const res = await api.fetchApi(route, options).catch(e => {
200
+ err = e;
201
+ });
202
+
203
+ if (!res) {
204
+ return {
205
+ status: 400,
206
+ error: new Error("Unknown Error")
207
+ }
208
+ }
209
+
210
+ const { status, statusText } = res;
211
+ if (err) {
212
+ return {
213
+ status,
214
+ error: err
215
+ }
216
+ }
217
+
218
+ if (status !== 200) {
219
+ return {
220
+ status,
221
+ error: new Error(statusText || "Unknown Error")
222
+ }
223
+ }
224
+
225
+ const data = await res.json();
226
+ if (!data) {
227
+ return {
228
+ status,
229
+ error: new Error(`Failed to load data: ${route}`)
230
+ }
231
+ }
232
+ return {
233
+ status,
234
+ data
235
+ }
236
+ }
237
+
238
+ export const icons = {
239
+ 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>',
240
+ extensions: '<svg viewBox="64 64 896 896" width="100%" height="100%" pointer-events="none" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M843.5 737.4c-12.4-75.2-79.2-129.1-155.3-125.4S550.9 676 546 752c-153.5-4.8-208-40.7-199.1-113.7 3.3-27.3 19.8-41.9 50.1-49 18.4-4.3 38.8-4.9 57.3-3.2 1.7.2 3.5.3 5.2.5 11.3 2.7 22.8 5 34.3 6.8 34.1 5.6 68.8 8.4 101.8 6.6 92.8-5 156-45.9 159.2-132.7 3.1-84.1-54.7-143.7-147.9-183.6-29.9-12.8-61.6-22.7-93.3-30.2-14.3-3.4-26.3-5.7-35.2-7.2-7.9-75.9-71.5-133.8-147.8-134.4S189.7 168 180.5 243.8s40 146.3 114.2 163.9 149.9-23.3 175.7-95.1c9.4 1.7 18.7 3.6 28 5.8 28.2 6.6 56.4 15.4 82.4 26.6 70.7 30.2 109.3 70.1 107.5 119.9-1.6 44.6-33.6 65.2-96.2 68.6-27.5 1.5-57.6-.9-87.3-5.8-8.3-1.4-15.9-2.8-22.6-4.3-3.9-.8-6.6-1.5-7.8-1.8l-3.1-.6c-2.2-.3-5.9-.8-10.7-1.3-25-2.3-52.1-1.5-78.5 4.6-55.2 12.9-93.9 47.2-101.1 105.8-15.7 126.2 78.6 184.7 276 188.9 29.1 70.4 106.4 107.9 179.6 87 73.3-20.9 119.3-93.4 106.9-168.6M329.1 345.2a83.3 83.3 0 1 1 .01-166.61 83.3 83.3 0 0 1-.01 166.61M695.6 845a83.3 83.3 0 1 1 .01-166.61A83.3 83.3 0 0 1 695.6 845"/></svg>',
241
+ 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>',
242
+ 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>',
243
+ 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>'
244
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/js/components-manager.js ADDED
@@ -0,0 +1,811 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../scripts/app.js";
2
+ import { api } from "../../scripts/api.js"
3
+ import { sleep, show_message } 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
+ 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
+ if(confirm(msg)) {
391
+ let mode = confirm('\nWill you save components?\n(cancel=load without save)');
392
+
393
+ for(let name in components) {
394
+ let component = components[name];
395
+ import_component(name, component, mode);
396
+ last_name = name;
397
+ }
398
+
399
+ if(mode) {
400
+ show_message('Components are saved.');
401
+ }
402
+ else {
403
+ show_message('Components are loaded.');
404
+ }
405
+ }
406
+
407
+ if(cnt == 1 && last_name) {
408
+ const node = LiteGraph.createNode(`workflow${SEPARATOR}${last_name}`);
409
+ node.pos = [app.canvas.graph_mouse[0], app.canvas.graph_mouse[1]];
410
+ app.canvas.graph.add(node, false);
411
+ }
412
+ }
413
+
414
+ function handlePaste(e) {
415
+ let data = (e.clipboardData || window.clipboardData);
416
+ const items = data.items;
417
+ for(const item of items) {
418
+ if(item.kind == 'string' && item.type == 'text/plain') {
419
+ data = data.getData("text/plain");
420
+ try {
421
+ let json_data = JSON.parse(data);
422
+ if(json_data.kind == 'ComfyUI Components' && last_paste_timestamp != json_data.timestamp) {
423
+ last_paste_timestamp = json_data.timestamp;
424
+ handle_import_components(json_data.components);
425
+
426
+ // disable paste node
427
+ localStorage.removeItem("litegrapheditor_clipboard", null);
428
+ }
429
+ else {
430
+ console.log('This components are already pasted: ignored');
431
+ }
432
+ }
433
+ catch {
434
+ // nothing to do
435
+ }
436
+ }
437
+ }
438
+ }
439
+
440
+ document.addEventListener("paste", handlePaste);
441
+
442
+
443
+ export class ComponentBuilderDialog extends ComfyDialog {
444
+ constructor() {
445
+ super();
446
+ }
447
+
448
+ clear() {
449
+ while (this.element.children.length) {
450
+ this.element.removeChild(this.element.children[0]);
451
+ }
452
+ }
453
+
454
+ show() {
455
+ this.invalidateControl();
456
+
457
+ this.element.style.display = "block";
458
+ this.element.style.zIndex = 10001;
459
+ this.element.style.width = "500px";
460
+ this.element.style.height = "480px";
461
+ }
462
+
463
+ invalidateControl() {
464
+ this.clear();
465
+
466
+ let self = this;
467
+
468
+ const close_button = $el("button", { id: "cm-close-button", type: "button", textContent: "Close", onclick: () => self.close() });
469
+ this.save_button = $el("button",
470
+ { id: "cm-save-button", type: "button", textContent: "Save", onclick: () =>
471
+ {
472
+ save_as_component(self.target_node, self.version_string.value.trim(), self.author.value.trim(), self.node_prefix.value.trim(),
473
+ self.getNodeName(), self.getPackName(), self.category.value.trim());
474
+ }
475
+ });
476
+
477
+ let default_nodename = getPureName(this.target_node).trim();
478
+
479
+ let groupNode = app.graph.extra.groupNodes[default_nodename];
480
+ let default_packname = groupNode.packname;
481
+ if(!default_packname) {
482
+ default_packname = '';
483
+ }
484
+
485
+ let default_category = groupNode.category;
486
+ if(!default_category) {
487
+ default_category = '';
488
+ }
489
+
490
+ this.default_ver = groupNode.version;
491
+ if(!this.default_ver) {
492
+ this.default_ver = '0.0';
493
+ }
494
+
495
+ let default_author = groupNode.author;
496
+ if(!default_author) {
497
+ default_author = '';
498
+ }
499
+
500
+ let delimiterIndex = default_nodename.indexOf('::');
501
+ let default_prefix = "";
502
+ if(delimiterIndex != -1) {
503
+ default_prefix = default_nodename.substring(0, delimiterIndex);
504
+ default_nodename = default_nodename.substring(delimiterIndex + 2);
505
+ }
506
+
507
+ if(!default_prefix) {
508
+ this.save_button.disabled = true;
509
+ }
510
+
511
+ this.pack_list = this.createPackListCombo();
512
+
513
+ let version_string = this.createLabeledInput('input version (e.g. 1.0)', '*Version : ', this.default_ver);
514
+ this.version_string = version_string[1];
515
+ this.version_string.disabled = true;
516
+
517
+ let author = this.createLabeledInput('input author (e.g. Dr.Lt.Data)', 'Author : ', default_author);
518
+ this.author = author[1];
519
+
520
+ let node_prefix = this.createLabeledInput('input node prefix (e.g. mypack)', '*Prefix : ', default_prefix);
521
+ this.node_prefix = node_prefix[1];
522
+
523
+ let manual_nodename = this.createLabeledInput('input node name (e.g. MAKE_BASIC_PIPE)', 'Nodename : ', default_nodename);
524
+ this.manual_nodename = manual_nodename[1];
525
+
526
+ let manual_packname = this.createLabeledInput('input pack name (e.g. mypack)', 'Packname : ', default_packname);
527
+ this.manual_packname = manual_packname[1];
528
+
529
+ let category = this.createLabeledInput('input category (e.g. util/pipe)', 'Category : ', default_category);
530
+ this.category = category[1];
531
+
532
+ this.node_label = this.createNodeLabel();
533
+
534
+ let author_mode = this.createAuthorModeCheck();
535
+ this.author_mode = author_mode[0];
536
+
537
+ const content =
538
+ $el("div.comfy-modal-content",
539
+ [
540
+ $el("tr.cm-title", {}, [
541
+ $el("font", {size:6, color:"white"}, [`ComfyUI-Manager: Component Builder`])]
542
+ ),
543
+ $el("br", {}, []),
544
+ $el("div.cm-menu-container",
545
+ [
546
+ author_mode[0],
547
+ author_mode[1],
548
+ category[0],
549
+ author[0],
550
+ node_prefix[0],
551
+ manual_nodename[0],
552
+ manual_packname[0],
553
+ version_string[0],
554
+ this.pack_list,
555
+ $el("br", {}, []),
556
+ this.node_label
557
+ ]),
558
+
559
+ $el("br", {}, []),
560
+ this.save_button,
561
+ close_button,
562
+ ]
563
+ );
564
+
565
+ content.style.width = '100%';
566
+ content.style.height = '100%';
567
+
568
+ this.element = $el("div.comfy-modal", { id:'cm-manager-dialog', parent: document.body }, [ content ]);
569
+ }
570
+
571
+ validateInput() {
572
+ let msg = "";
573
+
574
+ if(!isValidVersionString(this.version_string.value)) {
575
+ msg += 'Invalid version string: '+event.value+"\n";
576
+ }
577
+
578
+ if(this.node_prefix.value.trim() == '') {
579
+ msg += 'Node prefix cannot be empty\n';
580
+ }
581
+
582
+ if(this.manual_nodename.value.trim() == '') {
583
+ msg += 'Node name cannot be empty\n';
584
+ }
585
+
586
+ if(msg != '') {
587
+ // alert(msg);
588
+ }
589
+
590
+ this.save_button.disabled = msg != "";
591
+ }
592
+
593
+ getPackName() {
594
+ if(this.pack_list.selectedIndex == 0) {
595
+ return this.manual_packname.value.trim();
596
+ }
597
+
598
+ return this.pack_list.value.trim();
599
+ }
600
+
601
+ getNodeName() {
602
+ if(this.manual_nodename.value.trim() != '') {
603
+ return this.manual_nodename.value.trim();
604
+ }
605
+
606
+ return getPureName(this.target_node);
607
+ }
608
+
609
+ createAuthorModeCheck() {
610
+ let check = $el("input",{type:'checkbox', id:"author-mode"},[])
611
+ const check_label = $el("label",{for:"author-mode"},["Enable author mode"]);
612
+ check_label.style.color = "var(--fg-color)";
613
+ check_label.style.cursor = "pointer";
614
+ check.checked = false;
615
+
616
+ let self = this;
617
+ check.onchange = () => {
618
+ self.version_string.disabled = !check.checked;
619
+
620
+ if(!check.checked) {
621
+ self.version_string.value = self.default_ver;
622
+ }
623
+ else {
624
+ alert('If you are not the author, it is not recommended to change the version, as it may cause component update issues.');
625
+ }
626
+ };
627
+
628
+ return [check, check_label];
629
+ }
630
+
631
+ createNodeLabel() {
632
+ let label = $el('p');
633
+ label.className = 'cb-node-label';
634
+ if(this.target_node.comfyClass.includes('::'))
635
+ label.textContent = getPureName(this.target_node);
636
+ else
637
+ label.textContent = " _::" + getPureName(this.target_node);
638
+ return label;
639
+ }
640
+
641
+ createLabeledInput(placeholder, label, value) {
642
+ let textbox = $el('input.cb-widget-input', {type:'text', placeholder:placeholder, value:value}, []);
643
+
644
+ let self = this;
645
+ textbox.onchange = () => {
646
+ this.validateInput.call(self);
647
+ this.node_label.textContent = this.node_prefix.value + "::" + this.manual_nodename.value;
648
+ }
649
+ let row = $el('span.cb-widget', {}, [ $el('span.cb-widget-input-label', label), textbox]);
650
+
651
+ return [row, textbox];
652
+ }
653
+
654
+ createPackListCombo() {
655
+ let combo = document.createElement("select");
656
+ combo.className = "cb-widget";
657
+ let default_packname_option = { value: '##manual', text: 'Packname: Manual' };
658
+
659
+ combo.appendChild($el('option', default_packname_option, []));
660
+ for(let name in pack_map) {
661
+ combo.appendChild($el('option', { value: name, text: 'Packname: '+ name }, []));
662
+ }
663
+
664
+ let self = this;
665
+ combo.onchange = function () {
666
+ if(combo.selectedIndex == 0) {
667
+ self.manual_packname.disabled = false;
668
+ }
669
+ else {
670
+ self.manual_packname.disabled = true;
671
+ }
672
+ };
673
+
674
+ return combo;
675
+ }
676
+ }
677
+
678
+ let orig_handleFile = app.handleFile;
679
+
680
+ function handleFile(file) {
681
+ if (file.name?.endsWith(".json") || file.name?.endsWith(".pack")) {
682
+ const reader = new FileReader();
683
+ reader.onload = async () => {
684
+ let is_component = false;
685
+ const jsonContent = JSON.parse(reader.result);
686
+ for(let name in jsonContent) {
687
+ let cand = jsonContent[name];
688
+ is_component = cand.datetime && cand.version;
689
+ break;
690
+ }
691
+
692
+ if(is_component) {
693
+ handle_import_components(jsonContent);
694
+ }
695
+ else {
696
+ orig_handleFile.call(app, file);
697
+ }
698
+ };
699
+ reader.readAsText(file);
700
+
701
+ return;
702
+ }
703
+
704
+ orig_handleFile.call(app, file);
705
+ }
706
+
707
+ app.handleFile = handleFile;
708
+
709
+ let current_component_policy = 'workflow';
710
+ try {
711
+ api.fetchApi('/manager/component/policy')
712
+ .then(response => response.text())
713
+ .then(data => { current_component_policy = data; });
714
+ }
715
+ catch {}
716
+
717
+ function getChangedVersion(groupNodes) {
718
+ if(!Object.keys(pack_map).length || !groupNodes)
719
+ return null;
720
+
721
+ let res = {};
722
+ for(let component_name in groupNodes) {
723
+ let data = groupNodes[component_name];
724
+
725
+ if(rpack_map[component_name]) {
726
+ let v = versionCompare(data.version, rpack_map[component_name].version);
727
+ res[component_name] = v;
728
+ }
729
+ }
730
+
731
+ return res;
732
+ }
733
+
734
+ const loadGraphData = app.loadGraphData;
735
+ app.loadGraphData = async function () {
736
+ if(arguments.length == 0)
737
+ return await loadGraphData.apply(this, arguments);
738
+
739
+ let graphData = arguments[0];
740
+ let groupNodes = graphData.extra?.groupNodes;
741
+ let res = getChangedVersion(groupNodes);
742
+
743
+ if(res) {
744
+ let target_components = null;
745
+ switch(current_component_policy) {
746
+ case 'higher':
747
+ target_components = Object.keys(res).filter(key => res[key] == 1);
748
+ break;
749
+
750
+ case 'mine':
751
+ target_components = Object.keys(res);
752
+ break;
753
+
754
+ default:
755
+ // do nothing
756
+ }
757
+
758
+ if(target_components) {
759
+ for(let i in target_components) {
760
+ let component_name = target_components[i];
761
+ let component = rpack_map[component_name];
762
+ if(component && graphData.extra?.groupNodes) {
763
+ graphData.extra.groupNodes[component_name] = component;
764
+ }
765
+ }
766
+ }
767
+ }
768
+ else {
769
+ console.log('Empty components: policy ignored');
770
+ }
771
+
772
+ arguments[0] = graphData;
773
+ return await loadGraphData.apply(this, arguments);
774
+ };
775
+
776
+ export function set_component_policy(v) {
777
+ current_component_policy = v;
778
+ }
779
+
780
+ let graphToPrompt = app.graphToPrompt;
781
+ app.graphToPrompt = async function () {
782
+ let p = await graphToPrompt.call(app);
783
+ try {
784
+ let groupNodes = p.workflow.extra?.groupNodes;
785
+ if(groupNodes) {
786
+ p.workflow.extra = { ... p.workflow.extra};
787
+
788
+ // get used group nodes
789
+ let used_group_nodes = new Set();
790
+ for(let node of p.workflow.nodes) {
791
+ if(node.type.startsWith(`workflow/`) || node.type.startsWith(`workflow${SEPARATOR}`)) {
792
+ used_group_nodes.add(node.type.substring(9));
793
+ }
794
+ }
795
+
796
+ // remove unused group nodes
797
+ let new_groupNodes = {};
798
+ for (let key in p.workflow.extra.groupNodes) {
799
+ if (used_group_nodes.has(key)) {
800
+ new_groupNodes[key] = p.workflow.extra.groupNodes[key];
801
+ }
802
+ }
803
+ p.workflow.extra.groupNodes = new_groupNodes;
804
+ }
805
+ }
806
+ catch(e) {
807
+ console.log(`Failed to filtering group nodes: ${e}`);
808
+ }
809
+
810
+ return p;
811
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/js/custom-nodes-manager.js ADDED
@@ -0,0 +1,1381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../scripts/app.js";
2
+ import { $el } from "../../scripts/ui.js";
3
+ import {
4
+ manager_instance, rebootAPI, install_via_git_url,
5
+ fetchData, md5, icons
6
+ } from "./common.js";
7
+
8
+ // https://cenfun.github.io/turbogrid/api.html
9
+ import TG from "./turbogrid.esm.js";
10
+
11
+ const pageCss = `
12
+ .cn-manager {
13
+ --grid-font: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
14
+ z-index: 10001;
15
+ width: 80%;
16
+ height: 80%;
17
+ display: flex;
18
+ flex-direction: column;
19
+ gap: 10px;
20
+ color: var(--fg-color);
21
+ font-family: arial, sans-serif;
22
+ }
23
+
24
+ .cn-manager .cn-flex-auto {
25
+ flex: auto;
26
+ }
27
+
28
+ .cn-manager button {
29
+ font-size: 16px;
30
+ color: var(--input-text);
31
+ background-color: var(--comfy-input-bg);
32
+ border-radius: 8px;
33
+ border-color: var(--border-color);
34
+ border-style: solid;
35
+ margin: 0;
36
+ padding: 4px 8px;
37
+ min-width: 100px;
38
+ }
39
+
40
+ .cn-manager button:disabled,
41
+ .cn-manager input:disabled,
42
+ .cn-manager select:disabled {
43
+ color: gray;
44
+ }
45
+
46
+ .cn-manager button:disabled {
47
+ background-color: var(--comfy-input-bg);
48
+ }
49
+
50
+ .cn-manager .cn-manager-restart {
51
+ display: none;
52
+ background-color: #500000;
53
+ color: white;
54
+ }
55
+
56
+ .cn-manager-header {
57
+ display: flex;
58
+ flex-wrap: wrap;
59
+ gap: 5px;
60
+ align-items: center;
61
+ padding: 0 5px;
62
+ }
63
+
64
+ .cn-manager-header label {
65
+ display: flex;
66
+ gap: 5px;
67
+ align-items: center;
68
+ }
69
+
70
+ .cn-manager-filter {
71
+ height: 28px;
72
+ line-height: 28px;
73
+ }
74
+
75
+ .cn-manager-keywords {
76
+ height: 28px;
77
+ line-height: 28px;
78
+ padding: 0 5px 0 26px;
79
+ background-size: 16px;
80
+ background-position: 5px center;
81
+ background-repeat: no-repeat;
82
+ background-image: url("data:image/svg+xml;charset=utf8,${encodeURIComponent(icons.search.replace("currentColor", "#888"))}");
83
+ }
84
+
85
+ .cn-manager-status {
86
+ padding-left: 10px;
87
+ }
88
+
89
+ .cn-manager-grid {
90
+ flex: auto;
91
+ border: 1px solid var(--border-color);
92
+ overflow: hidden;
93
+ }
94
+
95
+ .cn-manager-selection {
96
+ display: flex;
97
+ flex-wrap: wrap;
98
+ gap: 10px;
99
+ align-items: center;
100
+ }
101
+
102
+ .cn-manager-message {
103
+
104
+ }
105
+
106
+ .cn-manager-footer {
107
+ display: flex;
108
+ flex-wrap: wrap;
109
+ gap: 10px;
110
+ align-items: center;
111
+ }
112
+
113
+ .cn-manager-grid .tg-turbogrid {
114
+ font-family: var(--grid-font);
115
+ font-size: 15px;
116
+ background: var(--bg-color);
117
+ }
118
+
119
+ .cn-manager-grid .cn-node-name a {
120
+ color: skyblue;
121
+ text-decoration: none;
122
+ word-break: break-word;
123
+ }
124
+
125
+ .cn-manager-grid .cn-node-desc a {
126
+ color: #5555FF;
127
+ font-weight: bold;
128
+ text-decoration: none;
129
+ }
130
+
131
+ .cn-manager-grid .tg-cell a:hover {
132
+ text-decoration: underline;
133
+ }
134
+
135
+ .cn-manager-grid .cn-extensions-button,
136
+ .cn-manager-grid .cn-conflicts-button {
137
+ display: inline-block;
138
+ width: 20px;
139
+ height: 20px;
140
+ color: green;
141
+ border: none;
142
+ padding: 0;
143
+ margin: 0;
144
+ background: none;
145
+ min-width: 20px;
146
+ }
147
+
148
+ .cn-manager-grid .cn-conflicts-button {
149
+ color: orange;
150
+ }
151
+
152
+ .cn-manager-grid .cn-extensions-list,
153
+ .cn-manager-grid .cn-conflicts-list {
154
+ line-height: normal;
155
+ text-align: left;
156
+ max-height: 80%;
157
+ min-height: 200px;
158
+ min-width: 300px;
159
+ overflow-y: auto;
160
+ font-size: 12px;
161
+ border-radius: 5px;
162
+ padding: 10px;
163
+ filter: drop-shadow(2px 5px 5px rgb(0 0 0 / 30%));
164
+ white-space: normal;
165
+ }
166
+
167
+ .cn-manager-grid .cn-extensions-list {
168
+ border-color: var(--bg-color);
169
+ }
170
+
171
+ .cn-manager-grid .cn-conflicts-list {
172
+ background-color: #CCCC55;
173
+ color: #AA3333;
174
+ }
175
+
176
+ .cn-manager-grid .cn-extensions-list h3,
177
+ .cn-manager-grid .cn-conflicts-list h3 {
178
+ margin: 0;
179
+ padding: 5px 0;
180
+ color: #000;
181
+ }
182
+
183
+ .cn-tag-list {
184
+ display: flex;
185
+ flex-wrap: wrap;
186
+ gap: 5px;
187
+ align-items: center;
188
+ margin-bottom: 5px;
189
+ }
190
+
191
+ .cn-tag-list > div {
192
+ background-color: var(--border-color);
193
+ border-radius: 5px;
194
+ padding: 0 5px;
195
+ }
196
+
197
+ .cn-install-buttons {
198
+ display: flex;
199
+ flex-direction: column;
200
+ gap: 3px;
201
+ padding: 3px;
202
+ align-items: center;
203
+ justify-content: center;
204
+ height: 100%;
205
+ }
206
+
207
+ .cn-selected-buttons {
208
+ display: flex;
209
+ gap: 5px;
210
+ align-items: center;
211
+ padding-right: 20px;
212
+ }
213
+
214
+ .cn-manager .cn-btn-enable {
215
+ background-color: blue;
216
+ color: white;
217
+ }
218
+
219
+ .cn-manager .cn-btn-disable {
220
+ background-color: MediumSlateBlue;
221
+ color: white;
222
+ }
223
+
224
+ .cn-manager .cn-btn-update {
225
+ background-color: blue;
226
+ color: white;
227
+ }
228
+
229
+ .cn-manager .cn-btn-try-update {
230
+ background-color: Gray;
231
+ color: white;
232
+ }
233
+
234
+ .cn-manager .cn-btn-try-fix {
235
+ background-color: #6495ED;
236
+ color: white;
237
+ }
238
+
239
+ .cn-manager .cn-btn-install {
240
+ background-color: black;
241
+ color: white;
242
+ }
243
+
244
+ .cn-manager .cn-btn-try-install {
245
+ background-color: Gray;
246
+ color: white;
247
+ }
248
+
249
+ .cn-manager .cn-btn-uninstall {
250
+ background-color: red;
251
+ color: white;
252
+ }
253
+
254
+ @keyframes cn-btn-loading-bg {
255
+ 0% {
256
+ left: 0;
257
+ }
258
+ 100% {
259
+ left: -105px;
260
+ }
261
+ }
262
+
263
+ .cn-manager button.cn-btn-loading {
264
+ position: relative;
265
+ overflow: hidden;
266
+ border-color: rgb(0 119 207 / 80%);
267
+ background-color: var(--comfy-input-bg);
268
+ }
269
+
270
+ .cn-manager button.cn-btn-loading::after {
271
+ position: absolute;
272
+ top: 0;
273
+ left: 0;
274
+ content: "";
275
+ width: 500px;
276
+ height: 100%;
277
+ background-image: repeating-linear-gradient(
278
+ -45deg,
279
+ rgb(0 119 207 / 30%),
280
+ rgb(0 119 207 / 30%) 10px,
281
+ transparent 10px,
282
+ transparent 15px
283
+ );
284
+ animation: cn-btn-loading-bg 2s linear infinite;
285
+ }
286
+
287
+ .cn-manager-light .cn-node-name a {
288
+ color: blue;
289
+ }
290
+
291
+ .cn-manager-light .cm-warn-note {
292
+ background-color: #ccc !important;
293
+ }
294
+
295
+ .cn-manager-light .cn-btn-install {
296
+ background-color: #333;
297
+ }
298
+
299
+ `;
300
+
301
+ const pageHtml = `
302
+ <div class="cn-manager-header">
303
+ <label>Filter
304
+ <select class="cn-manager-filter"></select>
305
+ </label>
306
+ <input class="cn-manager-keywords" type="search" placeholder="Search" />
307
+ <div class="cn-manager-status"></div>
308
+ <div class="cn-flex-auto"></div>
309
+ <div class="cn-manager-channel"></div>
310
+ </div>
311
+ <div class="cn-manager-grid"></div>
312
+ <div class="cn-manager-selection"></div>
313
+ <div class="cn-manager-message"></div>
314
+ <div class="cn-manager-footer">
315
+ <button class="cn-manager-close">Close</button>
316
+ <button class="cn-manager-restart">Restart</button>
317
+ <div class="cn-flex-auto"></div>
318
+ <button class="cn-manager-check-update">Check Update</button>
319
+ <button class="cn-manager-check-missing">Check Missing</button>
320
+ <button class="cn-manager-install-url">Install via Git URL</button>
321
+ </div>
322
+ `;
323
+
324
+ const ShowMode = {
325
+ NORMAL: "Normal",
326
+ UPDATE: "Update",
327
+ MISSING: "Missing",
328
+ ALTERNATIVES: "Alternatives"
329
+ };
330
+
331
+ export class CustomNodesManager {
332
+ static instance = null;
333
+ static ShowMode = ShowMode;
334
+
335
+ constructor(app, manager_dialog) {
336
+ this.app = app;
337
+ this.manager_dialog = manager_dialog;
338
+ this.id = "cn-manager";
339
+
340
+ app.registerExtension({
341
+ name: "Comfy.CustomNodesManager",
342
+ afterConfigureGraph: (missingNodeTypes) => {
343
+ const item = this.getFilterItem(ShowMode.MISSING);
344
+ if (item) {
345
+ item.hasData = false;
346
+ item.hashMap = null;
347
+ }
348
+ }
349
+ });
350
+
351
+ this.filter = '';
352
+ this.keywords = '';
353
+ this.restartMap = {};
354
+
355
+ this.init();
356
+ }
357
+
358
+ init() {
359
+
360
+ if (!document.querySelector(`style[context="${this.id}"]`)) {
361
+ const $style = document.createElement("style");
362
+ $style.setAttribute("context", this.id);
363
+ $style.innerHTML = pageCss;
364
+ document.head.appendChild($style);
365
+ }
366
+
367
+ this.element = $el("div", {
368
+ parent: document.body,
369
+ className: "comfy-modal cn-manager"
370
+ });
371
+ this.element.innerHTML = pageHtml;
372
+ this.initFilter();
373
+ this.bindEvents();
374
+ this.initGrid();
375
+ }
376
+
377
+ initFilter() {
378
+ const $filter = this.element.querySelector(".cn-manager-filter");
379
+ const filterList = [{
380
+ label: "All",
381
+ value: "",
382
+ hasData: true
383
+ }, {
384
+ label: "Installed",
385
+ value: "True",
386
+ hasData: true
387
+ }, {
388
+ label: "Disabled",
389
+ value: "Disabled",
390
+ hasData: true
391
+ }, {
392
+ label: "Import Failed",
393
+ value: "Fail",
394
+ hasData: true
395
+ }, {
396
+ label: "Not Installed",
397
+ value: "False",
398
+ hasData: true
399
+ }, {
400
+ label: "Unknown",
401
+ value: "None",
402
+ hasData: true
403
+ }, {
404
+ label: "Update",
405
+ value: ShowMode.UPDATE,
406
+ hasData: false
407
+ }, {
408
+ label: "Missing",
409
+ value: ShowMode.MISSING,
410
+ hasData: false
411
+ }, {
412
+ label: "Alternatives of A1111",
413
+ value: ShowMode.ALTERNATIVES,
414
+ hasData: false
415
+ }];
416
+ this.filterList = filterList;
417
+ $filter.innerHTML = filterList.map(item => {
418
+ return `<option value="${item.value}">${item.label}</option>`
419
+ }).join("");
420
+ }
421
+
422
+ getFilterItem(filter) {
423
+ return this.filterList.find(it => it.value === filter)
424
+ }
425
+
426
+ getInstallButtons(installed, title) {
427
+
428
+ const buttons = {
429
+ "enable": {
430
+ label: "Enable",
431
+ mode: "toggle_active"
432
+ },
433
+ "disable": {
434
+ label: "Disable",
435
+ mode: "toggle_active"
436
+ },
437
+
438
+ "update": {
439
+ label: "Update",
440
+ mode: "update"
441
+ },
442
+ "try-update": {
443
+ label: "Try update",
444
+ mode: "update"
445
+ },
446
+
447
+ "try-fix": {
448
+ label: "Try fix",
449
+ mode: "fix"
450
+ },
451
+
452
+ "install": {
453
+ label: "Install",
454
+ mode: "install"
455
+ },
456
+ "try-install": {
457
+ label: "Try install",
458
+ mode: "install"
459
+ },
460
+ "uninstall": {
461
+ label: "Uninstall",
462
+ mode: "uninstall"
463
+ }
464
+ }
465
+
466
+ const installGroups = {
467
+ "Disabled": ["enable", "uninstall"],
468
+ "Update": ["update", "disable", "uninstall"],
469
+ "Fail": ["try-fix", "uninstall"],
470
+ "True": ["try-update", "disable", "uninstall"],
471
+ "False": ["install"],
472
+ 'None': ["try-install"]
473
+ }
474
+
475
+ if (!manager_instance.update_check_checkbox.checked) {
476
+ installGroups.True = installGroups.True.filter(it => it !== "try-update");
477
+ }
478
+
479
+ if (title === "ComfyUI-Manager") {
480
+ installGroups.True = installGroups.True.filter(it => it !== "disable");
481
+ }
482
+
483
+ const list = installGroups[installed];
484
+ if (!list) {
485
+ return "";
486
+ }
487
+
488
+ return list.map(id => {
489
+ const bt = buttons[id];
490
+ return `<button class="cn-btn-${id}" group="${installed}" mode="${bt.mode}">${bt.label}</button>`;
491
+ }).join("");
492
+ }
493
+
494
+ getButton(target) {
495
+ if(!target) {
496
+ return;
497
+ }
498
+ const mode = target.getAttribute("mode");
499
+ if (!mode) {
500
+ return;
501
+ }
502
+ const group = target.getAttribute("group");
503
+ if (!group) {
504
+ return;
505
+ }
506
+ return {
507
+ group,
508
+ mode,
509
+ target,
510
+ label: target.innerText
511
+ }
512
+ }
513
+
514
+ bindEvents() {
515
+ const eventsMap = {
516
+ ".cn-manager-filter": {
517
+ change: (e) => {
518
+
519
+ if (this.grid) {
520
+ this.grid.selectAll(false);
521
+ }
522
+
523
+ const value = e.target.value
524
+ this.filter = value;
525
+ const item = this.getFilterItem(value);
526
+ if (item && !item.hasData) {
527
+ this.loadData(value);
528
+ return;
529
+ }
530
+ this.updateGrid();
531
+ }
532
+ },
533
+
534
+ ".cn-manager-keywords": {
535
+ input: (e) => {
536
+ const keywords = `${e.target.value}`.trim();
537
+ if (keywords !== this.keywords) {
538
+ this.keywords = keywords;
539
+ this.updateGrid();
540
+ }
541
+ },
542
+ focus: (e) => e.target.select()
543
+ },
544
+
545
+ ".cn-manager-selection": {
546
+ click: (e) => {
547
+ const btn = this.getButton(e.target);
548
+ if (btn) {
549
+ const nodes = this.selectedMap[btn.group];
550
+ if (nodes) {
551
+ this.installNodes(nodes, btn);
552
+ }
553
+ }
554
+ }
555
+ },
556
+
557
+ ".cn-manager-close": {
558
+ click: (e) => this.close()
559
+ },
560
+
561
+ ".cn-manager-restart": {
562
+ click: () => {
563
+ if(rebootAPI()) {
564
+ this.close();
565
+ this.manager_dialog.close();
566
+ }
567
+ }
568
+ },
569
+
570
+ ".cn-manager-check-update": {
571
+ click: (e) => {
572
+ e.target.classList.add("cn-btn-loading");
573
+ this.setFilter(ShowMode.UPDATE);
574
+ this.loadData(ShowMode.UPDATE);
575
+ }
576
+ },
577
+
578
+ ".cn-manager-check-missing": {
579
+ click: (e) => {
580
+ e.target.classList.add("cn-btn-loading");
581
+ this.setFilter(ShowMode.MISSING);
582
+ this.loadData(ShowMode.MISSING);
583
+ }
584
+ },
585
+
586
+ ".cn-manager-install-url": {
587
+ click: (e) => {
588
+ const url = prompt("Please enter the URL of the Git repository to install", "");
589
+ if (url !== null) {
590
+ install_via_git_url(url, this.manager_dialog);
591
+ }
592
+ }
593
+ }
594
+ };
595
+ Object.keys(eventsMap).forEach(selector => {
596
+ const target = this.element.querySelector(selector);
597
+ if (target) {
598
+ const events = eventsMap[selector];
599
+ if (events) {
600
+ Object.keys(events).forEach(type => {
601
+ target.addEventListener(type, events[type]);
602
+ });
603
+ }
604
+ }
605
+ });
606
+ }
607
+
608
+ // ===========================================================================================
609
+
610
+ initGrid() {
611
+ const container = this.element.querySelector(".cn-manager-grid");
612
+ const grid = new TG.Grid(container);
613
+ this.grid = grid;
614
+
615
+ let prevViewRowsLength = -1;
616
+ grid.bind('onUpdated', (e, d) => {
617
+
618
+ const viewRows = grid.viewRows;
619
+ if (viewRows.length !== prevViewRowsLength) {
620
+ prevViewRowsLength = viewRows.length;
621
+ this.showStatus(`${prevViewRowsLength.toLocaleString()} custom nodes`);
622
+ }
623
+
624
+ });
625
+
626
+ grid.bind('onSelectChanged', (e, changes) => {
627
+ this.renderSelected();
628
+ });
629
+
630
+ grid.bind('onClick', (e, d) => {
631
+ const btn = this.getButton(d.e.target);
632
+ if (btn) {
633
+ this.installNodes([d.rowItem.hash], btn, d.rowItem.title);
634
+ }
635
+ });
636
+
637
+ grid.setOption({
638
+ theme: 'dark',
639
+ selectVisible: true,
640
+ selectMultiple: true,
641
+ selectAllVisible: true,
642
+
643
+ textSelectable: true,
644
+ scrollbarRound: true,
645
+
646
+ frozenColumn: 1,
647
+ rowNotFound: "No Results",
648
+
649
+ rowHeight: 40,
650
+ bindWindowResize: true,
651
+ bindContainerResize: true,
652
+
653
+ cellResizeObserver: (rowItem, columnItem) => {
654
+ const autoHeightColumns = ['title', 'installed', 'description', "alternatives"];
655
+ return autoHeightColumns.includes(columnItem.id)
656
+ },
657
+
658
+ // updateGrid handler for filter and keywords
659
+ rowFilter: (rowItem) => {
660
+
661
+ const searchableColumns = ["title", "author", "description"];
662
+ if (this.hasAlternatives()) {
663
+ searchableColumns.push("alternatives");
664
+ }
665
+
666
+ let shouldShown = grid.highlightKeywordsFilter(rowItem, searchableColumns, this.keywords);
667
+
668
+ if (shouldShown) {
669
+ if(this.filter && rowItem.filterTypes) {
670
+ shouldShown = rowItem.filterTypes.includes(this.filter);
671
+ }
672
+ }
673
+
674
+ return shouldShown;
675
+ }
676
+ });
677
+
678
+ }
679
+
680
+ hasAlternatives() {
681
+ return this.filter === ShowMode.ALTERNATIVES
682
+ }
683
+
684
+ renderGrid() {
685
+
686
+ // update theme
687
+ const colorPalette = this.app.ui.settings.settingsValues['Comfy.ColorPalette'];
688
+ Array.from(this.element.classList).forEach(cn => {
689
+ if (cn.startsWith("cn-manager-")) {
690
+ this.element.classList.remove(cn);
691
+ }
692
+ });
693
+ this.element.classList.add(`cn-manager-${colorPalette}`);
694
+
695
+ const options = {
696
+ theme: colorPalette === "light" ? "" : "dark"
697
+ };
698
+
699
+ const rows = this.custom_nodes || [];
700
+ rows.forEach((item, i) => {
701
+ item.id = i + 1;
702
+ const nodeKey = item.files[0];
703
+ const extensionInfo = this.extension_mappings[nodeKey];
704
+ if(extensionInfo) {
705
+ const { extensions, conflicts } = extensionInfo;
706
+ if (extensions.length) {
707
+ item.extensions = extensions.length;
708
+ item.extensionsList = extensions;
709
+ }
710
+ if (conflicts) {
711
+ item.conflicts = conflicts.length;
712
+ item.conflictsList = conflicts;
713
+ }
714
+ }
715
+ });
716
+
717
+ const columns = [{
718
+ id: 'id',
719
+ name: 'ID',
720
+ width: 50,
721
+ align: 'center'
722
+ }, {
723
+ id: 'title',
724
+ name: 'Title',
725
+ width: 200,
726
+ minWidth: 100,
727
+ maxWidth: 500,
728
+ classMap: 'cn-node-name',
729
+ formatter: (title, rowItem, columnItem) => {
730
+ return `${rowItem.installed === 'Fail' ? '<font color="red"><B>(IMPORT FAILED)</B></font>' : ''}
731
+ <a href=${rowItem.reference} target="_blank"><b>${title}</b></a>`;
732
+ }
733
+ }, {
734
+ id: 'installed',
735
+ name: 'Install',
736
+ width: 130,
737
+ minWidth: 110,
738
+ maxWidth: 200,
739
+ sortable: false,
740
+ align: 'center',
741
+ formatter: (installed, rowItem, columnItem) => {
742
+ if (rowItem.restart) {
743
+ return `<font color="red">Restart Required</span>`;
744
+ }
745
+ const buttons = this.getInstallButtons(installed, rowItem.title);
746
+ return `<div class="cn-install-buttons">${buttons}</div>`;
747
+ }
748
+ }, {
749
+ id: "alternatives",
750
+ name: "Alternatives",
751
+ width: 400,
752
+ maxWidth: 5000,
753
+ invisible: !this.hasAlternatives(),
754
+ classMap: 'cn-node-desc'
755
+ }, {
756
+ id: 'description',
757
+ name: 'Description',
758
+ width: 400,
759
+ maxWidth: 5000,
760
+ classMap: 'cn-node-desc'
761
+ }, {
762
+ id: "extensions",
763
+ name: "Extensions",
764
+ width: 80,
765
+ align: 'center',
766
+ formatter: (extensions, rowItem, columnItem) => {
767
+ const extensionsList = rowItem.extensionsList;
768
+ if (!extensionsList) {
769
+ return;
770
+ }
771
+ const list = [];
772
+ const eId = `popover_extensions_${columnItem.id}_${rowItem.tg_index}`;
773
+ list.push(`<button popovertarget="${eId}" title="${extensionsList.length} Extension Nodes" class="cn-extensions-button">${icons.extensions}</button>`)
774
+ list.push(`<div popover id="${eId}" class="cn-extensions-list">`)
775
+ list.push(`<h3>【${rowItem.title}】Extension Nodes (${extensionsList.length})</h3>`);
776
+ extensionsList.forEach(en => {
777
+ list.push(`<li>${en}</li>`);
778
+ })
779
+ list.push("</div>");
780
+ return list.join("");
781
+ }
782
+ }, {
783
+ id: "conflicts",
784
+ name: "Conflicts",
785
+ width: 80,
786
+ align: 'center',
787
+ formatter: (conflicts, rowItem, columnItem) => {
788
+ const conflictsList = rowItem.conflictsList;
789
+ if (!conflictsList) {
790
+ return;
791
+ }
792
+ const list = [];
793
+ const cId = `popover_conflicts_${columnItem.id}_${rowItem.tg_index}`;
794
+ list.push(`<button popovertarget="${cId}" title="${conflictsList.length} Conflicted Nodes" class="cn-conflicts-button">${icons.conflicts}</button>`)
795
+ list.push(`<div popover id="${cId}" class="cn-conflicts-list">`)
796
+ list.push(`<h3>【${rowItem.title}】Conflicted Nodes (${conflictsList.length})</h3>`);
797
+ conflictsList.forEach(en => {
798
+ let [node_name, extension_name] = en;
799
+ extension_name = extension_name.split('/').filter(it => it).pop();
800
+ if(extension_name.endsWith('.git')) {
801
+ extension_name = extension_name.slice(0, -4);
802
+ }
803
+ list.push(`<li><B>${node_name}</B> [${extension_name}]</li>`);
804
+ })
805
+ list.push("</div>");
806
+ return list.join("");
807
+ }
808
+ }, {
809
+ id: 'author',
810
+ name: 'Author',
811
+ width: 120,
812
+ classMap: "cn-node-author",
813
+ formatter: (author, rowItem, columnItem) => {
814
+ if (rowItem.trust) {
815
+ return `<span title="This author has been active for more than six months in GitHub">✅ ${author}</span>`;
816
+ }
817
+ return author;
818
+ }
819
+ }, {
820
+ id: 'stars',
821
+ name: '★',
822
+ align: 'center',
823
+ classMap: "cn-node-stars",
824
+ formatter: (stars) => {
825
+ if (stars < 0) {
826
+ return 'N/A';
827
+ }
828
+ if (typeof stars === 'number') {
829
+ return stars.toLocaleString();
830
+ }
831
+ return stars;
832
+ }
833
+ }, {
834
+ id: 'last_update',
835
+ name: 'Last Update',
836
+ align: 'center',
837
+ type: 'date',
838
+ width: 100,
839
+ classMap: "cn-node-last-update",
840
+ formatter: (last_update) => {
841
+ if (last_update < 0) {
842
+ return 'N/A';
843
+ }
844
+ return `${last_update}`.split(' ')[0];
845
+ }
846
+ }];
847
+
848
+ this.grid.setData({
849
+ options,
850
+ rows,
851
+ columns
852
+ });
853
+
854
+ this.grid.render();
855
+
856
+ }
857
+
858
+ updateGrid() {
859
+ if (this.grid) {
860
+ this.grid.update();
861
+ if (this.hasAlternatives()) {
862
+ this.grid.showColumn("alternatives");
863
+ } else {
864
+ this.grid.hideColumn("alternatives");
865
+ }
866
+ }
867
+ }
868
+
869
+ // ===========================================================================================
870
+
871
+ renderSelected() {
872
+ const selectedList = this.grid.getSelectedRows();
873
+ if (!selectedList.length) {
874
+ this.showSelection("");
875
+ return;
876
+ }
877
+
878
+ const selectedMap = {};
879
+ selectedList.forEach(item => {
880
+ let type = item.installed;
881
+ if (item.restart) {
882
+ type = "Restart Required";
883
+ }
884
+ if (selectedMap[type]) {
885
+ selectedMap[type].push(item.hash);
886
+ } else {
887
+ selectedMap[type] = [item.hash];
888
+ }
889
+ });
890
+
891
+ this.selectedMap = selectedMap;
892
+
893
+ const list = [];
894
+ Object.keys(selectedMap).forEach(v => {
895
+ const filterItem = this.getFilterItem(v);
896
+ list.push(`<div class="cn-selected-buttons">
897
+ <span>Selected <b>${selectedMap[v].length}</b> ${filterItem ? filterItem.label : v}</span>
898
+ ${this.grid.hasMask ? "" : this.getInstallButtons(v)}
899
+ </div>`);
900
+ });
901
+
902
+ this.showSelection(list.join(""));
903
+ }
904
+
905
+ focusInstall(item, mode) {
906
+ const cellNode = this.grid.getCellNode(item, "installed");
907
+ if (cellNode) {
908
+ const cellBtn = cellNode.querySelector(`button[mode="${mode}"]`);
909
+ if (cellBtn) {
910
+ cellBtn.classList.add("cn-btn-loading");
911
+ return true
912
+ }
913
+ }
914
+ }
915
+
916
+ async installNodes(list, btn, title) {
917
+
918
+ const { target, label, mode} = btn;
919
+
920
+ if(mode === "uninstall") {
921
+ title = title || `${list.length} custom nodes`;
922
+ if (!confirm(`Are you sure uninstall ${title}?`)) {
923
+ return;
924
+ }
925
+ }
926
+
927
+ target.classList.add("cn-btn-loading");
928
+ this.showLoading();
929
+ this.showError("");
930
+
931
+ let needRestart = false;
932
+ let errorMsg = "";
933
+ for (const hash of list) {
934
+
935
+ const item = this.grid.getRowItemBy("hash", hash);
936
+ if (!item) {
937
+ errorMsg = `Not found custom node: ${hash}`;
938
+ break;
939
+ }
940
+
941
+ this.grid.scrollRowIntoView(item);
942
+
943
+ if (!this.focusInstall(item, mode)) {
944
+ this.grid.onNextUpdated(() => {
945
+ this.focusInstall(item, mode);
946
+ });
947
+ }
948
+
949
+ this.showStatus(`${label} ${item.title} ...`);
950
+
951
+ const data = item.originalData;
952
+ const res = await fetchData(`/customnode/${mode}`, {
953
+ method: 'POST',
954
+ headers: { 'Content-Type': 'application/json' },
955
+ body: JSON.stringify(data)
956
+ });
957
+
958
+ if (res.error) {
959
+
960
+ errorMsg = `${item.title} ${mode} failed: `;
961
+ if(res.status == 403) {
962
+ errorMsg += `This action is not allowed with this security level configuration.`;
963
+ } else if(res.status == 404) {
964
+ errorMsg += `With the current security level configuration, only custom nodes from the <B>"default channel"</B> can be installed.`;
965
+ } else {
966
+ errorMsg += res.error.message;
967
+ }
968
+
969
+ break;
970
+ }
971
+
972
+ needRestart = true;
973
+
974
+ this.grid.setRowSelected(item, false);
975
+ item.restart = true;
976
+ this.restartMap[item.hash] = true;
977
+ this.grid.updateCell(item, "installed");
978
+
979
+ //console.log(res.data);
980
+
981
+ }
982
+
983
+ this.hideLoading();
984
+ target.classList.remove("cn-btn-loading");
985
+
986
+ if (errorMsg) {
987
+ this.showError(errorMsg);
988
+ } else {
989
+ this.showStatus(`${label} ${list.length} custom node(s) successfully`);
990
+ }
991
+
992
+ if (needRestart) {
993
+ this.showRestart();
994
+ this.showMessage(`To apply the installed/updated/disabled/enabled custom node, please restart ComfyUI. And refresh browser.`, "red")
995
+ }
996
+
997
+ }
998
+
999
+ // ===========================================================================================
1000
+
1001
+ async getExtensionMappings() {
1002
+ const mode = manager_instance.datasrc_combo.value;
1003
+ this.showStatus(`Loading extension mappings (${mode}) ...`);
1004
+ const res = await fetchData(`/customnode/getmappings?mode=${mode}`);
1005
+ if (res.error) {
1006
+ console.log(res.error);
1007
+ return {}
1008
+ }
1009
+
1010
+ const data = res.data;
1011
+
1012
+ const extension_mappings = {};
1013
+ const conflicts_map = {};
1014
+ Object.keys(data).forEach(k => {
1015
+ const [extensions, metadata] = data[k];
1016
+ extension_mappings[k] = {
1017
+ extensions,
1018
+ metadata
1019
+ }
1020
+ extensions.forEach(node => {
1021
+ let l = conflicts_map[node];
1022
+ if(!l) {
1023
+ l = [];
1024
+ conflicts_map[node] = l;
1025
+ }
1026
+ l.push(k);
1027
+ })
1028
+ })
1029
+
1030
+ Object.keys(conflicts_map).forEach(node => {
1031
+ const list = conflicts_map[node];
1032
+ if(list.length > 1) {
1033
+ list.forEach(k => {
1034
+ const item = extension_mappings[k];
1035
+ if(!item) {
1036
+ console.log(`not found ${k}`)
1037
+ return;
1038
+ }
1039
+
1040
+ if (!item.conflicts) {
1041
+ item.conflicts = [];
1042
+ }
1043
+ list.forEach(key => {
1044
+ if(k !== key) {
1045
+ item.conflicts.push([node, key])
1046
+ }
1047
+ })
1048
+ })
1049
+ }
1050
+ })
1051
+
1052
+ return extension_mappings;
1053
+ }
1054
+
1055
+ async getMissingNodes() {
1056
+ const mode = manager_instance.datasrc_combo.value;
1057
+ this.showStatus(`Loading missing nodes (${mode}) ...`);
1058
+ const res = await fetchData(`/customnode/getmappings?mode=${mode}`);
1059
+ if (res.error) {
1060
+ this.showError(`Failed to get custom node mappings: ${res.error}`);
1061
+ return;
1062
+ }
1063
+
1064
+ const mappings = res.data;
1065
+
1066
+ // build regex->url map
1067
+ const regex_to_url = [];
1068
+ this.custom_nodes.forEach(node => {
1069
+ if(node.nodename_pattern) {
1070
+ regex_to_url.push({
1071
+ regex: new RegExp(node.nodename_pattern),
1072
+ url: node.files[0]
1073
+ });
1074
+ }
1075
+ });
1076
+
1077
+ // build name->url map
1078
+ const name_to_urls = {};
1079
+ for (const url in mappings) {
1080
+ const names = mappings[url];
1081
+
1082
+ for(const name in names[0]) {
1083
+ let v = name_to_urls[names[0][name]];
1084
+ if(v == undefined) {
1085
+ v = [];
1086
+ name_to_urls[names[0][name]] = v;
1087
+ }
1088
+ v.push(url);
1089
+ }
1090
+ }
1091
+
1092
+ const registered_nodes = new Set();
1093
+ for (let i in LiteGraph.registered_node_types) {
1094
+ registered_nodes.add(LiteGraph.registered_node_types[i].type);
1095
+ }
1096
+
1097
+ const missing_nodes = new Set();
1098
+ const workflow = app.graph.serialize();
1099
+ const group_nodes = workflow.extra && workflow.extra.groupNodes ? workflow.extra.groupNodes : [];
1100
+ let nodes = workflow.nodes;
1101
+
1102
+ for (let i in group_nodes) {
1103
+ let group_node = group_nodes[i];
1104
+ nodes = nodes.concat(group_node.nodes);
1105
+ }
1106
+
1107
+ for (let i in nodes) {
1108
+ const node_type = nodes[i].type;
1109
+ if(node_type.startsWith('workflow/') || node_type.startsWith('workflow>'))
1110
+ continue;
1111
+
1112
+ if (!registered_nodes.has(node_type)) {
1113
+ const urls = name_to_urls[node_type.trim()];
1114
+ if(urls)
1115
+ urls.forEach(url => {
1116
+ missing_nodes.add(url);
1117
+ });
1118
+ else {
1119
+ for(let j in regex_to_url) {
1120
+ if(regex_to_url[j].regex.test(node_type)) {
1121
+ missing_nodes.add(regex_to_url[j].url);
1122
+ }
1123
+ }
1124
+ }
1125
+ }
1126
+ }
1127
+
1128
+ const resUnresolved = await fetchData(`/component/get_unresolved`);
1129
+ const unresolved = resUnresolved.data;
1130
+ if (unresolved && unresolved.nodes) {
1131
+ unresolved.nodes.forEach(node_type => {
1132
+ const url = name_to_urls[node_type];
1133
+ if(url) {
1134
+ missing_nodes.add(url);
1135
+ }
1136
+ });
1137
+ }
1138
+
1139
+ const hashMap = {};
1140
+ this.custom_nodes.forEach(item => {
1141
+ if (item.files.some(file => missing_nodes.has(file))) {
1142
+ hashMap[item.hash] = true;
1143
+ }
1144
+ });
1145
+ return hashMap;
1146
+ }
1147
+
1148
+ async getAlternatives() {
1149
+
1150
+ const mode = manager_instance.datasrc_combo.value;
1151
+ this.showStatus(`Loading alternatives (${mode}) ...`);
1152
+ const res = await fetchData(`/customnode/alternatives?mode=${mode}`);
1153
+ if (res.error) {
1154
+ this.showError(`Failed to get alternatives: ${res.error}`);
1155
+ return [];
1156
+ }
1157
+
1158
+ const hashMap = {};
1159
+ const { items } = res.data;
1160
+
1161
+ items.forEach(item => {
1162
+
1163
+ const custom_node = this.custom_nodes.find(node => node.files.find(file => file === item.id));
1164
+ if (!custom_node) {
1165
+ console.log(`Not found custom node: ${item.id}`);
1166
+ return;
1167
+ }
1168
+
1169
+ const tags = `${item.tags}`.split(",").map(tag => {
1170
+ return `<div>${tag.trim()}</div>`;
1171
+ }).join("")
1172
+
1173
+ hashMap[custom_node.hash] = {
1174
+ alternatives: `<div class="cn-tag-list">${tags}</div> ${item.description}`
1175
+ }
1176
+
1177
+ });
1178
+
1179
+ return hashMap
1180
+ }
1181
+
1182
+ async loadData(show_mode = ShowMode.NORMAL) {
1183
+ this.show_mode = show_mode;
1184
+ console.log("Show mode:", show_mode);
1185
+
1186
+ this.showLoading();
1187
+
1188
+ this.extension_mappings = await this.getExtensionMappings();
1189
+
1190
+ const mode = manager_instance.datasrc_combo.value;
1191
+ this.showStatus(`Loading custom nodes (${mode}) ...`);
1192
+
1193
+ const skip_update = this.show_mode === ShowMode.UPDATE ? "" : "&skip_update=true";
1194
+ const res = await fetchData(`/customnode/getlist?mode=${mode}${skip_update}`);
1195
+ if (res.error) {
1196
+ this.showError("Failed to get custom node list.");
1197
+ this.hideLoading();
1198
+ return
1199
+ }
1200
+
1201
+ const { channel, custom_nodes} = res.data;
1202
+ this.channel = channel;
1203
+ this.custom_nodes = custom_nodes;
1204
+
1205
+ if(this.channel !== 'default') {
1206
+ this.element.querySelector(".cn-manager-channel").innerHTML = `Channel: ${this.channel} (Incomplete list)`;
1207
+ }
1208
+
1209
+ for (const item of custom_nodes) {
1210
+ item.originalData = JSON.parse(JSON.stringify(item));
1211
+ const message = item.title + item.files[0];
1212
+ item.hash = md5(message);
1213
+ }
1214
+
1215
+ const filterItem = this.getFilterItem(this.show_mode);
1216
+ if(filterItem) {
1217
+ let hashMap;
1218
+ if(this.show_mode == ShowMode.UPDATE) {
1219
+ hashMap = {};
1220
+ custom_nodes.forEach(it => {
1221
+ if (it.installed === "Update") {
1222
+ hashMap[it.hash] = true;
1223
+ }
1224
+ });
1225
+ } else if(this.show_mode == ShowMode.MISSING) {
1226
+ hashMap = await this.getMissingNodes();
1227
+ } else if(this.show_mode == ShowMode.ALTERNATIVES) {
1228
+ hashMap = await this.getAlternatives();
1229
+ }
1230
+ filterItem.hashMap = hashMap;
1231
+ filterItem.hasData = true;
1232
+ }
1233
+
1234
+ custom_nodes.forEach(nodeItem => {
1235
+ if (this.restartMap[nodeItem.hash]) {
1236
+ nodeItem.restart = true;
1237
+ }
1238
+ const filterTypes = new Set();
1239
+ this.filterList.forEach(filterItem => {
1240
+ const { value, hashMap } = filterItem;
1241
+ if (hashMap) {
1242
+ const hashData = hashMap[nodeItem.hash]
1243
+ if (hashData) {
1244
+ filterTypes.add(value);
1245
+ if (value === ShowMode.UPDATE) {
1246
+ nodeItem.installed = "Update";
1247
+ }
1248
+ if (typeof hashData === "object") {
1249
+ Object.assign(nodeItem, hashData);
1250
+ }
1251
+ }
1252
+ } else {
1253
+ if (nodeItem.installed === value) {
1254
+ filterTypes.add(value);
1255
+ }
1256
+ const map = {
1257
+ "Update": "True",
1258
+ "Disabled": "True",
1259
+ "Fail": "True",
1260
+ "None": "False"
1261
+ }
1262
+ if (map[nodeItem.installed]) {
1263
+ filterTypes.add(map[nodeItem.installed]);
1264
+ }
1265
+ }
1266
+ });
1267
+ nodeItem.filterTypes = Array.from(filterTypes);
1268
+ });
1269
+
1270
+ this.renderGrid();
1271
+
1272
+ this.hideLoading();
1273
+
1274
+ }
1275
+
1276
+ // ===========================================================================================
1277
+
1278
+ showSelection(msg) {
1279
+ this.element.querySelector(".cn-manager-selection").innerHTML = msg;
1280
+ }
1281
+
1282
+ showError(err) {
1283
+ this.showMessage(err, "red");
1284
+ }
1285
+
1286
+ showMessage(msg, color) {
1287
+ if (color) {
1288
+ msg = `<font color="${color}">${msg}</font>`;
1289
+ }
1290
+ this.element.querySelector(".cn-manager-message").innerHTML = msg;
1291
+ }
1292
+
1293
+ showStatus(msg, color) {
1294
+ if (color) {
1295
+ msg = `<font color="${color}">${msg}</font>`;
1296
+ }
1297
+ this.element.querySelector(".cn-manager-status").innerHTML = msg;
1298
+ }
1299
+
1300
+ showLoading() {
1301
+ this.setDisabled(true);
1302
+ if (this.grid) {
1303
+ this.grid.showLoading();
1304
+ this.grid.showMask({
1305
+ opacity: 0.05
1306
+ });
1307
+ }
1308
+ }
1309
+
1310
+ hideLoading() {
1311
+ this.setDisabled(false);
1312
+ if (this.grid) {
1313
+ this.grid.hideLoading();
1314
+ this.grid.hideMask();
1315
+ }
1316
+ }
1317
+
1318
+ setDisabled(disabled) {
1319
+
1320
+ const $close = this.element.querySelector(".cn-manager-close");
1321
+ const $restart = this.element.querySelector(".cn-manager-restart");
1322
+
1323
+ const list = [
1324
+ ".cn-manager-header input",
1325
+ ".cn-manager-header select",
1326
+ ".cn-manager-footer button",
1327
+ ".cn-manager-selection button"
1328
+ ].map(s => {
1329
+ return Array.from(this.element.querySelectorAll(s));
1330
+ })
1331
+ .flat()
1332
+ .filter(it => {
1333
+ return it !== $close && it !== $restart;
1334
+ });
1335
+
1336
+ list.forEach($elem => {
1337
+ if (disabled) {
1338
+ $elem.setAttribute("disabled", "disabled");
1339
+ } else {
1340
+ $elem.removeAttribute("disabled");
1341
+ }
1342
+ });
1343
+
1344
+ Array.from(this.element.querySelectorAll(".cn-btn-loading")).forEach($elem => {
1345
+ $elem.classList.remove("cn-btn-loading");
1346
+ });
1347
+
1348
+ }
1349
+
1350
+ showRestart() {
1351
+ this.element.querySelector(".cn-manager-restart").style.display = "block";
1352
+ }
1353
+
1354
+ setFilter(filterValue) {
1355
+ let filter = "";
1356
+ const filterItem = this.getFilterItem(filterValue);
1357
+ if(filterItem) {
1358
+ filter = filterItem.value;
1359
+ }
1360
+ this.filter = filter;
1361
+ this.element.querySelector(".cn-manager-filter").value = filter;
1362
+ }
1363
+
1364
+ setKeywords(keywords = "") {
1365
+ this.keywords = keywords;
1366
+ this.element.querySelector(".cn-manager-keywords").value = keywords;
1367
+ }
1368
+
1369
+ show(show_mode) {
1370
+ this.element.style.display = "flex";
1371
+ this.setFilter(show_mode);
1372
+ this.setKeywords("");
1373
+ this.showSelection("");
1374
+ this.showMessage("");
1375
+ this.loadData(show_mode);
1376
+ }
1377
+
1378
+ close() {
1379
+ this.element.style.display = "none";
1380
+ }
1381
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/js/model-manager.js ADDED
@@ -0,0 +1,891 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { $el } from "../../scripts/ui.js";
2
+ import {
3
+ manager_instance, rebootAPI,
4
+ fetchData, md5, icons
5
+ } from "./common.js";
6
+
7
+ // https://cenfun.github.io/turbogrid/api.html
8
+ import TG from "./turbogrid.esm.js";
9
+
10
+ const pageCss = `
11
+ .cmm-manager {
12
+ --grid-font: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
13
+ z-index: 10001;
14
+ width: 80%;
15
+ height: 80%;
16
+ display: flex;
17
+ flex-direction: column;
18
+ gap: 10px;
19
+ color: var(--fg-color);
20
+ font-family: arial, sans-serif;
21
+ }
22
+
23
+ .cmm-manager .cmm-flex-auto {
24
+ flex: auto;
25
+ }
26
+
27
+ .cmm-manager button {
28
+ font-size: 16px;
29
+ color: var(--input-text);
30
+ background-color: var(--comfy-input-bg);
31
+ border-radius: 8px;
32
+ border-color: var(--border-color);
33
+ border-style: solid;
34
+ margin: 0;
35
+ padding: 4px 8px;
36
+ min-width: 100px;
37
+ }
38
+
39
+ .cmm-manager button:disabled,
40
+ .cmm-manager input:disabled,
41
+ .cmm-manager select:disabled {
42
+ color: gray;
43
+ }
44
+
45
+ .cmm-manager button:disabled {
46
+ background-color: var(--comfy-input-bg);
47
+ }
48
+
49
+ .cmm-manager-header {
50
+ display: flex;
51
+ flex-wrap: wrap;
52
+ gap: 5px;
53
+ align-items: center;
54
+ padding: 0 5px;
55
+ }
56
+
57
+ .cmm-manager-header label {
58
+ display: flex;
59
+ gap: 5px;
60
+ align-items: center;
61
+ }
62
+
63
+ .cmm-manager-type,
64
+ .cmm-manager-base,
65
+ .cmm-manager-filter {
66
+ height: 28px;
67
+ line-height: 28px;
68
+ }
69
+
70
+ .cmm-manager-keywords {
71
+ height: 28px;
72
+ line-height: 28px;
73
+ padding: 0 5px 0 26px;
74
+ background-size: 16px;
75
+ background-position: 5px center;
76
+ background-repeat: no-repeat;
77
+ background-image: url("data:image/svg+xml;charset=utf8,${encodeURIComponent(icons.search.replace("currentColor", "#888"))}");
78
+ }
79
+
80
+ .cmm-manager-status {
81
+ padding-left: 10px;
82
+ }
83
+
84
+ .cmm-manager-grid {
85
+ flex: auto;
86
+ border: 1px solid var(--border-color);
87
+ overflow: hidden;
88
+ }
89
+
90
+ .cmm-manager-selection {
91
+ display: flex;
92
+ flex-wrap: wrap;
93
+ gap: 10px;
94
+ align-items: center;
95
+ }
96
+
97
+ .cmm-manager-message {
98
+
99
+ }
100
+
101
+ .cmm-manager-footer {
102
+ display: flex;
103
+ flex-wrap: wrap;
104
+ gap: 10px;
105
+ align-items: center;
106
+ }
107
+
108
+ .cmm-manager-grid .tg-turbogrid {
109
+ font-family: var(--grid-font);
110
+ font-size: 15px;
111
+ background: var(--bg-color);
112
+ }
113
+
114
+ .cmm-manager-grid .cmm-node-name a {
115
+ color: skyblue;
116
+ text-decoration: none;
117
+ word-break: break-word;
118
+ }
119
+
120
+ .cmm-manager-grid .cmm-node-desc a {
121
+ color: #5555FF;
122
+ font-weight: bold;
123
+ text-decoration: none;
124
+ }
125
+
126
+ .cmm-manager-grid .tg-cell a:hover {
127
+ text-decoration: underline;
128
+ }
129
+
130
+ .cmm-icon-passed {
131
+ width: 20px;
132
+ height: 20px;
133
+ position: absolute;
134
+ left: calc(50% - 10px);
135
+ top: calc(50% - 10px);
136
+ }
137
+
138
+ .cmm-manager .cmm-btn-enable {
139
+ background-color: blue;
140
+ color: white;
141
+ }
142
+
143
+ .cmm-manager .cmm-btn-disable {
144
+ background-color: MediumSlateBlue;
145
+ color: white;
146
+ }
147
+
148
+ .cmm-manager .cmm-btn-install {
149
+ background-color: black;
150
+ color: white;
151
+ }
152
+
153
+ .cmm-btn-download {
154
+ width: 18px;
155
+ height: 18px;
156
+ position: absolute;
157
+ left: calc(50% - 10px);
158
+ top: calc(50% - 10px);
159
+ cursor: pointer;
160
+ opacity: 0.8;
161
+ color: #fff;
162
+ }
163
+
164
+ .cmm-btn-download:hover {
165
+ opacity: 1;
166
+ }
167
+
168
+ .cmm-manager-light .cmm-btn-download {
169
+ color: #000;
170
+ }
171
+
172
+ @keyframes cmm-btn-loading-bg {
173
+ 0% {
174
+ left: 0;
175
+ }
176
+ 100% {
177
+ left: -105px;
178
+ }
179
+ }
180
+
181
+ .cmm-manager button.cmm-btn-loading {
182
+ position: relative;
183
+ overflow: hidden;
184
+ border-color: rgb(0 119 207 / 80%);
185
+ background-color: var(--comfy-input-bg);
186
+ }
187
+
188
+ .cmm-manager button.cmm-btn-loading::after {
189
+ position: absolute;
190
+ top: 0;
191
+ left: 0;
192
+ content: "";
193
+ width: 500px;
194
+ height: 100%;
195
+ background-image: repeating-linear-gradient(
196
+ -45deg,
197
+ rgb(0 119 207 / 30%),
198
+ rgb(0 119 207 / 30%) 10px,
199
+ transparent 10px,
200
+ transparent 15px
201
+ );
202
+ animation: cmm-btn-loading-bg 2s linear infinite;
203
+ }
204
+
205
+ .cmm-manager-light .cmm-node-name a {
206
+ color: blue;
207
+ }
208
+
209
+ .cmm-manager-light .cm-warn-note {
210
+ background-color: #ccc !important;
211
+ }
212
+
213
+ .cmm-manager-light .cmm-btn-install {
214
+ background-color: #333;
215
+ }
216
+
217
+ `;
218
+
219
+ const pageHtml = `
220
+ <div class="cmm-manager-header">
221
+ <label>Filter
222
+ <select class="cmm-manager-filter"></select>
223
+ </label>
224
+ <label>Type
225
+ <select class="cmm-manager-type"></select>
226
+ </label>
227
+ <label>Base
228
+ <select class="cmm-manager-base"></select>
229
+ </label>
230
+ <input class="cmm-manager-keywords" type="search" placeholder="Search" />
231
+ <div class="cmm-manager-status"></div>
232
+ <div class="cmm-flex-auto"></div>
233
+ </div>
234
+ <div class="cmm-manager-grid"></div>
235
+ <div class="cmm-manager-selection"></div>
236
+ <div class="cmm-manager-message"></div>
237
+ <div class="cmm-manager-footer">
238
+ <button class="cmm-manager-close">Close</button>
239
+ <div class="cmm-flex-auto"></div>
240
+ </div>
241
+ `;
242
+
243
+ export class ModelManager {
244
+ static instance = null;
245
+
246
+ constructor(app, manager_dialog) {
247
+ this.app = app;
248
+ this.manager_dialog = manager_dialog;
249
+ this.id = "cmm-manager";
250
+
251
+ this.filter = '';
252
+ this.type = '';
253
+ this.base = '';
254
+ this.keywords = '';
255
+
256
+ this.init();
257
+ }
258
+
259
+ init() {
260
+
261
+ if (!document.querySelector(`style[context="${this.id}"]`)) {
262
+ const $style = document.createElement("style");
263
+ $style.setAttribute("context", this.id);
264
+ $style.innerHTML = pageCss;
265
+ document.head.appendChild($style);
266
+ }
267
+
268
+ this.element = $el("div", {
269
+ parent: document.body,
270
+ className: "comfy-modal cmm-manager"
271
+ });
272
+ this.element.innerHTML = pageHtml;
273
+ this.initFilter();
274
+ this.bindEvents();
275
+ this.initGrid();
276
+ }
277
+
278
+ initFilter() {
279
+
280
+ this.filterList = [{
281
+ label: "All",
282
+ value: ""
283
+ }, {
284
+ label: "Installed",
285
+ value: "True"
286
+ }, {
287
+ label: "Not Installed",
288
+ value: "False"
289
+ }];
290
+
291
+ this.typeList = [{
292
+ label: "All",
293
+ value: ""
294
+ }];
295
+
296
+ this.baseList = [{
297
+ label: "All",
298
+ value: ""
299
+ }];
300
+
301
+ this.updateFilter();
302
+
303
+ }
304
+
305
+ updateFilter() {
306
+ const $filter = this.element.querySelector(".cmm-manager-filter");
307
+ $filter.innerHTML = this.filterList.map(item => {
308
+ const selected = item.value === this.filter ? " selected" : "";
309
+ return `<option value="${item.value}"${selected}>${item.label}</option>`
310
+ }).join("");
311
+
312
+ const $type = this.element.querySelector(".cmm-manager-type");
313
+ $type.innerHTML = this.typeList.map(item => {
314
+ const selected = item.value === this.type ? " selected" : "";
315
+ return `<option value="${item.value}"${selected}>${item.label}</option>`
316
+ }).join("");
317
+
318
+ const $base = this.element.querySelector(".cmm-manager-base");
319
+ $base.innerHTML = this.baseList.map(item => {
320
+ const selected = item.value === this.base ? " selected" : "";
321
+ return `<option value="${item.value}"${selected}>${item.label}</option>`
322
+ }).join("");
323
+
324
+ }
325
+
326
+ bindEvents() {
327
+ const eventsMap = {
328
+ ".cmm-manager-filter": {
329
+ change: (e) => {
330
+ this.filter = e.target.value;
331
+ this.updateGrid();
332
+ }
333
+ },
334
+ ".cmm-manager-type": {
335
+ change: (e) => {
336
+ this.type = e.target.value;
337
+ this.updateGrid();
338
+ }
339
+ },
340
+ ".cmm-manager-base": {
341
+ change: (e) => {
342
+ this.base = e.target.value;
343
+ this.updateGrid();
344
+ }
345
+ },
346
+
347
+ ".cmm-manager-keywords": {
348
+ input: (e) => {
349
+ const keywords = `${e.target.value}`.trim();
350
+ if (keywords !== this.keywords) {
351
+ this.keywords = keywords;
352
+ this.updateGrid();
353
+ }
354
+ },
355
+ focus: (e) => e.target.select()
356
+ },
357
+
358
+ ".cmm-manager-selection": {
359
+ click: (e) => {
360
+ const target = e.target;
361
+ const mode = target.getAttribute("mode");
362
+ if (mode === "install") {
363
+ this.installModels(this.selectedModels, target);
364
+ }
365
+ }
366
+ },
367
+
368
+ ".cmm-manager-close": {
369
+ click: (e) => this.close()
370
+ },
371
+
372
+ };
373
+ Object.keys(eventsMap).forEach(selector => {
374
+ const target = this.element.querySelector(selector);
375
+ if (target) {
376
+ const events = eventsMap[selector];
377
+ if (events) {
378
+ Object.keys(events).forEach(type => {
379
+ target.addEventListener(type, events[type]);
380
+ });
381
+ }
382
+ }
383
+ });
384
+ }
385
+
386
+ // ===========================================================================================
387
+
388
+ initGrid() {
389
+ const container = this.element.querySelector(".cmm-manager-grid");
390
+ const grid = new TG.Grid(container);
391
+ this.grid = grid;
392
+
393
+ grid.bind('onUpdated', (e, d) => {
394
+
395
+ this.showStatus(`${grid.viewRows.length.toLocaleString()} external models`);
396
+
397
+ });
398
+
399
+ grid.bind('onSelectChanged', (e, changes) => {
400
+ this.renderSelected();
401
+ });
402
+
403
+ grid.bind('onClick', (e, d) => {
404
+ const { rowItem } = d;
405
+ const target = d.e.target;
406
+ const mode = target.getAttribute("mode");
407
+ if (mode === "install") {
408
+ this.installModels([rowItem], target);
409
+ }
410
+
411
+ });
412
+
413
+ grid.setOption({
414
+ theme: 'dark',
415
+
416
+ selectVisible: true,
417
+ selectMultiple: true,
418
+ selectAllVisible: true,
419
+
420
+ textSelectable: true,
421
+ scrollbarRound: true,
422
+
423
+ frozenColumn: 1,
424
+ rowNotFound: "No Results",
425
+
426
+ rowHeight: 40,
427
+ bindWindowResize: true,
428
+ bindContainerResize: true,
429
+
430
+ cellResizeObserver: (rowItem, columnItem) => {
431
+ const autoHeightColumns = ['name', 'description'];
432
+ return autoHeightColumns.includes(columnItem.id)
433
+ },
434
+
435
+ // updateGrid handler for filter and keywords
436
+ rowFilter: (rowItem) => {
437
+
438
+ const searchableColumns = ["name", "type", "base", "description", "filename", "save_path"];
439
+
440
+ let shouldShown = grid.highlightKeywordsFilter(rowItem, searchableColumns, this.keywords);
441
+
442
+ if (shouldShown) {
443
+ if(this.filter && rowItem.installed !== this.filter) {
444
+ return false;
445
+ }
446
+
447
+ if(this.type && rowItem.type !== this.type) {
448
+ return false;
449
+ }
450
+
451
+ if(this.base && rowItem.base !== this.base) {
452
+ return false;
453
+ }
454
+
455
+ }
456
+
457
+ return shouldShown;
458
+ }
459
+ });
460
+
461
+ }
462
+
463
+ renderGrid() {
464
+
465
+ // update theme
466
+ const colorPalette = this.app.ui.settings.settingsValues['Comfy.ColorPalette'];
467
+ Array.from(this.element.classList).forEach(cn => {
468
+ if (cn.startsWith("cmm-manager-")) {
469
+ this.element.classList.remove(cn);
470
+ }
471
+ });
472
+ this.element.classList.add(`cmm-manager-${colorPalette}`);
473
+
474
+ const options = {
475
+ theme: colorPalette === "light" ? "" : "dark"
476
+ };
477
+
478
+ const rows = this.modelList || [];
479
+
480
+ const columns = [{
481
+ id: 'id',
482
+ name: 'ID',
483
+ width: 50,
484
+ align: 'center'
485
+ }, {
486
+ id: 'name',
487
+ name: 'Name',
488
+ width: 200,
489
+ minWidth: 100,
490
+ maxWidth: 500,
491
+ classMap: 'cmm-node-name',
492
+ formatter: function(name, rowItem, columnItem, cellNode) {
493
+ return `<a href=${rowItem.reference} target="_blank"><b>${name}</b></a>`;
494
+ }
495
+ }, {
496
+ id: 'installed',
497
+ name: 'Install',
498
+ width: 130,
499
+ minWidth: 110,
500
+ maxWidth: 200,
501
+ sortable: false,
502
+ align: 'center',
503
+ formatter: (installed, rowItem, columnItem) => {
504
+ if (rowItem.refresh) {
505
+ return `<font color="red">Refresh Required</span>`;
506
+ }
507
+ if (installed === "True") {
508
+ return `<div class="cmm-icon-passed">${icons.passed}</div>`;
509
+ }
510
+ return `<button class="cmm-btn-install" mode="install">Install</button>`;
511
+ }
512
+ }, {
513
+ id: 'url',
514
+ name: '',
515
+ width: 50,
516
+ sortable: false,
517
+ align: 'center',
518
+ formatter: (url, rowItem, columnItem) => {
519
+ return `<a class="cmm-btn-download" title="Download file" href="${url}" target="_blank">${icons.download}</a>`;
520
+ }
521
+ }, {
522
+ id: 'size',
523
+ name: 'Size',
524
+ width: 100,
525
+ formatter: (size) => {
526
+ if (typeof size === "number") {
527
+ return this.formatSize(size);
528
+ }
529
+ return size;
530
+ }
531
+ }, {
532
+ id: 'type',
533
+ name: 'Type',
534
+ width: 100
535
+ }, {
536
+ id: 'base',
537
+ name: 'Base'
538
+ }, {
539
+ id: 'description',
540
+ name: 'Description',
541
+ width: 400,
542
+ maxWidth: 5000,
543
+ classMap: 'cmm-node-desc'
544
+ }, {
545
+ id: "save_path",
546
+ name: 'Save Path',
547
+ width: 200
548
+ }, {
549
+ id: 'filename',
550
+ name: 'Filename',
551
+ width: 200
552
+ }];
553
+
554
+ this.grid.setData({
555
+ options,
556
+ rows,
557
+ columns
558
+ });
559
+
560
+ this.grid.render();
561
+
562
+ }
563
+
564
+ updateGrid() {
565
+ if (this.grid) {
566
+ this.grid.update();
567
+ }
568
+ }
569
+
570
+ // ===========================================================================================
571
+
572
+ renderSelected() {
573
+ const selectedList = this.grid.getSelectedRows();
574
+ if (!selectedList.length) {
575
+ this.showSelection("");
576
+ this.selectedModels = [];
577
+ return;
578
+ }
579
+
580
+ this.selectedModels = selectedList;
581
+ this.showSelection(`<span>Selected <b>${selectedList.length}</b> models <button class="cmm-btn-install" mode="install">Install</button>`);
582
+ }
583
+
584
+ focusInstall(item) {
585
+ const cellNode = this.grid.getCellNode(item, "installed");
586
+ if (cellNode) {
587
+ const cellBtn = cellNode.querySelector(`button[mode="install"]`);
588
+ if (cellBtn) {
589
+ cellBtn.classList.add("cmm-btn-loading");
590
+ return true
591
+ }
592
+ }
593
+ }
594
+
595
+ async installModels(list, btn) {
596
+
597
+ btn.classList.add("cmm-btn-loading");
598
+ this.showLoading();
599
+ this.showError("");
600
+
601
+ let needRestart = false;
602
+ let errorMsg = "";
603
+
604
+ for (const item of list) {
605
+
606
+ this.grid.scrollRowIntoView(item);
607
+
608
+ if (!this.focusInstall(item)) {
609
+ this.grid.onNextUpdated(() => {
610
+ this.focusInstall(item);
611
+ });
612
+ }
613
+
614
+ this.showStatus(`Install ${item.name} ...`);
615
+
616
+ const data = item.originalData;
617
+ const res = await fetchData('/model/install', {
618
+ method: 'POST',
619
+ headers: { 'Content-Type': 'application/json' },
620
+ body: JSON.stringify(data)
621
+ });
622
+
623
+
624
+ if (res.error) {
625
+ errorMsg = `Install failed: ${item.name} ${res.error.message}`;
626
+ break;;
627
+ }
628
+
629
+ needRestart = true;
630
+
631
+ this.grid.setRowSelected(item, false);
632
+
633
+ item.refresh = true;
634
+ item.selectable = false;
635
+ this.grid.updateCell(item, "installed");
636
+ this.grid.updateCell(item, "tg-column-select");
637
+
638
+ this.showStatus(`Install ${item.name} successfully`);
639
+
640
+ }
641
+
642
+ this.hideLoading();
643
+ btn.classList.remove("cmm-btn-loading");
644
+
645
+ if (errorMsg) {
646
+ this.showError(errorMsg);
647
+ } else {
648
+ this.showStatus(`Install ${list.length} models successfully`);
649
+ }
650
+
651
+ if (needRestart) {
652
+ this.showMessage(`To apply the installed model, please click the 'Refresh' button on the main menu.`, "red")
653
+ }
654
+
655
+ }
656
+
657
+ getModelList(models) {
658
+
659
+ const typeMap = new Map();
660
+ const baseMap = new Map();
661
+
662
+ models.forEach((item, i) => {
663
+ const { type, base, name, reference, installed } = item;
664
+ item.originalData = JSON.parse(JSON.stringify(item));
665
+ item.size = this.sizeToBytes(item.size);
666
+ item.hash = md5(name + reference);
667
+ item.id = i + 1;
668
+
669
+ if (installed === "True") {
670
+ item.selectable = false;
671
+ }
672
+
673
+ typeMap.set(type, type);
674
+ baseMap.set(base, base);
675
+
676
+ });
677
+
678
+ const typeList = [];
679
+ typeMap.forEach(type => {
680
+ typeList.push({
681
+ label: type,
682
+ value: type
683
+ });
684
+ });
685
+ typeList.sort((a,b)=> {
686
+ const au = a.label.toUpperCase();
687
+ const bu = b.label.toUpperCase();
688
+ if (au !== bu) {
689
+ return au > bu ? 1 : -1;
690
+ }
691
+ return 0;
692
+ });
693
+ this.typeList = [{
694
+ label: "All",
695
+ value: ""
696
+ }].concat(typeList);
697
+
698
+
699
+ const baseList = [];
700
+ baseMap.forEach(base => {
701
+ baseList.push({
702
+ label: base,
703
+ value: base
704
+ });
705
+ });
706
+ baseList.sort((a,b)=> {
707
+ const au = a.label.toUpperCase();
708
+ const bu = b.label.toUpperCase();
709
+ if (au !== bu) {
710
+ return au > bu ? 1 : -1;
711
+ }
712
+ return 0;
713
+ });
714
+ this.baseList = [{
715
+ label: "All",
716
+ value: ""
717
+ }].concat(baseList);
718
+
719
+ return models;
720
+ }
721
+
722
+ // ===========================================================================================
723
+
724
+ async loadData() {
725
+
726
+ this.showLoading();
727
+
728
+ this.showStatus(`Loading external model list ...`);
729
+
730
+ const mode = manager_instance.datasrc_combo.value;
731
+
732
+ const res = await fetchData(`/externalmodel/getlist?mode=${mode}`);
733
+ if (res.error) {
734
+ this.showError("Failed to get external model list.");
735
+ this.hideLoading();
736
+ return
737
+ }
738
+
739
+ const { models } = res.data;
740
+
741
+ this.modelList = this.getModelList(models);
742
+ // console.log("models", this.modelList);
743
+
744
+ this.updateFilter();
745
+
746
+ this.renderGrid();
747
+
748
+ this.hideLoading();
749
+
750
+ }
751
+
752
+ // ===========================================================================================
753
+
754
+ formatSize(v) {
755
+ const base = 1000;
756
+ const units = ['', 'K', 'M', 'G', 'T', 'P'];
757
+ const space = '';
758
+ const postfix = 'B';
759
+ if (v <= 0) {
760
+ return `0${space}${postfix}`;
761
+ }
762
+ for (let i = 0, l = units.length; i < l; i++) {
763
+ const min = Math.pow(base, i);
764
+ const max = Math.pow(base, i + 1);
765
+ if (v > min && v <= max) {
766
+ const unit = units[i];
767
+ if (unit) {
768
+ const n = v / min;
769
+ const nl = n.toString().split('.')[0].length;
770
+ const fl = Math.max(3 - nl, 1);
771
+ v = n.toFixed(fl);
772
+ }
773
+ v = v + space + unit + postfix;
774
+ break;
775
+ }
776
+ }
777
+ return v;
778
+ }
779
+
780
+ // for size sort
781
+ sizeToBytes(v) {
782
+ if (typeof v === "number") {
783
+ return v;
784
+ }
785
+ if (typeof v === "string") {
786
+ const n = parseFloat(v);
787
+ const unit = v.replace(/[0-9.B]+/g, "").trim().toUpperCase();
788
+ if (unit === "K") {
789
+ return n * 1000;
790
+ }
791
+ if (unit === "M") {
792
+ return n * 1000 * 1000;
793
+ }
794
+ if (unit === "G") {
795
+ return n * 1000 * 1000 * 1000;
796
+ }
797
+ if (unit === "T") {
798
+ return n * 1000 * 1000 * 1000 * 1000;
799
+ }
800
+ }
801
+ return v;
802
+ }
803
+
804
+ showSelection(msg) {
805
+ this.element.querySelector(".cmm-manager-selection").innerHTML = msg;
806
+ }
807
+
808
+ showError(err) {
809
+ this.showMessage(err, "red");
810
+ }
811
+
812
+ showMessage(msg, color) {
813
+ if (color) {
814
+ msg = `<font color="${color}">${msg}</font>`;
815
+ }
816
+ this.element.querySelector(".cmm-manager-message").innerHTML = msg;
817
+ }
818
+
819
+ showStatus(msg, color) {
820
+ if (color) {
821
+ msg = `<font color="${color}">${msg}</font>`;
822
+ }
823
+ this.element.querySelector(".cmm-manager-status").innerHTML = msg;
824
+ }
825
+
826
+ showLoading() {
827
+ this.setDisabled(true);
828
+ if (this.grid) {
829
+ this.grid.showLoading();
830
+ this.grid.showMask({
831
+ opacity: 0.05
832
+ });
833
+ }
834
+ }
835
+
836
+ hideLoading() {
837
+ this.setDisabled(false);
838
+ if (this.grid) {
839
+ this.grid.hideLoading();
840
+ this.grid.hideMask();
841
+ }
842
+ }
843
+
844
+ setDisabled(disabled) {
845
+
846
+ const $close = this.element.querySelector(".cmm-manager-close");
847
+
848
+ const list = [
849
+ ".cmm-manager-header input",
850
+ ".cmm-manager-header select",
851
+ ".cmm-manager-footer button",
852
+ ".cmm-manager-selection button"
853
+ ].map(s => {
854
+ return Array.from(this.element.querySelectorAll(s));
855
+ })
856
+ .flat()
857
+ .filter(it => {
858
+ return it !== $close;
859
+ });
860
+
861
+ list.forEach($elem => {
862
+ if (disabled) {
863
+ $elem.setAttribute("disabled", "disabled");
864
+ } else {
865
+ $elem.removeAttribute("disabled");
866
+ }
867
+ });
868
+
869
+ Array.from(this.element.querySelectorAll(".cmm-btn-loading")).forEach($elem => {
870
+ $elem.classList.remove("cmm-btn-loading");
871
+ });
872
+
873
+ }
874
+
875
+ setKeywords(keywords = "") {
876
+ this.keywords = keywords;
877
+ this.element.querySelector(".cmm-manager-keywords").value = keywords;
878
+ }
879
+
880
+ show() {
881
+ this.element.style.display = "flex";
882
+ this.setKeywords("");
883
+ this.showSelection("");
884
+ this.showMessage("");
885
+ this.loadData();
886
+ }
887
+
888
+ close() {
889
+ this.element.style.display = "none";
890
+ }
891
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/js/node_fixer.js ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../scripts/app.js";
2
+ import { api } from "../../scripts/api.js";
3
+
4
+ let double_click_policy = "copy-all";
5
+
6
+ api.fetchApi('/manager/dbl_click/policy')
7
+ .then(response => response.text())
8
+ .then(data => set_double_click_policy(data));
9
+
10
+ export function set_double_click_policy(mode) {
11
+ double_click_policy = mode;
12
+ }
13
+
14
+ function addMenuHandler(nodeType, cb) {
15
+ const getOpts = nodeType.prototype.getExtraMenuOptions;
16
+ nodeType.prototype.getExtraMenuOptions = function () {
17
+ const r = getOpts.apply(this, arguments);
18
+ cb.apply(this, arguments);
19
+ return r;
20
+ };
21
+ }
22
+
23
+ function distance(node1, node2) {
24
+ let dx = (node1.pos[0] + node1.size[0]/2) - (node2.pos[0] + node2.size[0]/2);
25
+ let dy = (node1.pos[1] + node1.size[1]/2) - (node2.pos[1] + node2.size[1]/2);
26
+ return Math.sqrt(dx * dx + dy * dy);
27
+ }
28
+
29
+ function lookup_nearest_nodes(node) {
30
+ let nearest_distance = Infinity;
31
+ let nearest_node = null;
32
+ for(let other of app.graph._nodes) {
33
+ if(other === node)
34
+ continue;
35
+
36
+ let dist = distance(node, other);
37
+ if (dist < nearest_distance && dist < 1000) {
38
+ nearest_distance = dist;
39
+ nearest_node = other;
40
+ }
41
+ }
42
+
43
+ return nearest_node;
44
+ }
45
+
46
+ function lookup_nearest_inputs(node) {
47
+ let input_map = {};
48
+
49
+ for(let i in node.inputs) {
50
+ let input = node.inputs[i];
51
+
52
+ if(input.link || input_map[input.type])
53
+ continue;
54
+
55
+ input_map[input.type] = {distance: Infinity, input_name: input.name, node: null, slot: null};
56
+ }
57
+
58
+ let x = node.pos[0];
59
+ let y = node.pos[1] + node.size[1]/2;
60
+
61
+ for(let other of app.graph._nodes) {
62
+ if(other === node || !other.outputs)
63
+ continue;
64
+
65
+ let dx = x - (other.pos[0] + other.size[0]);
66
+ let dy = y - (other.pos[1] + other.size[1]/2);
67
+
68
+ if(dx < 0)
69
+ continue;
70
+
71
+ let dist = Math.sqrt(dx * dx + dy * dy);
72
+
73
+ for(let input_type in input_map) {
74
+ for(let j in other.outputs) {
75
+ let output = other.outputs[j];
76
+ if(output.type == input_type) {
77
+ if(input_map[input_type].distance > dist) {
78
+ input_map[input_type].distance = dist;
79
+ input_map[input_type].node = other;
80
+ input_map[input_type].slot = parseInt(j);
81
+ }
82
+ }
83
+ }
84
+ }
85
+ }
86
+
87
+ let res = {};
88
+ for (let i in input_map) {
89
+ if (input_map[i].node) {
90
+ res[i] = input_map[i];
91
+ }
92
+ }
93
+
94
+ return res;
95
+ }
96
+
97
+ function connect_inputs(nearest_inputs, node) {
98
+ for(let i in nearest_inputs) {
99
+ let info = nearest_inputs[i];
100
+ info.node.connect(info.slot, node.id, info.input_name);
101
+ }
102
+ }
103
+
104
+ function node_info_copy(src, dest, connect_both, copy_shape) {
105
+ // copy input connections
106
+ for(let i in src.inputs) {
107
+ let input = src.inputs[i];
108
+ if (input.widget !== undefined) {
109
+ const destWidget = dest.widgets.find(x => x.name === input.widget.name);
110
+ dest.convertWidgetToInput(destWidget);
111
+ }
112
+ if(input.link) {
113
+ let link = app.graph.links[input.link];
114
+ let src_node = app.graph.getNodeById(link.origin_id);
115
+ src_node.connect(link.origin_slot, dest.id, input.name);
116
+ }
117
+ }
118
+
119
+ // copy output connections
120
+ if(connect_both) {
121
+ let output_links = {};
122
+ for(let i in src.outputs) {
123
+ let output = src.outputs[i];
124
+ if(output.links) {
125
+ let links = [];
126
+ for(let j in output.links) {
127
+ links.push(app.graph.links[output.links[j]]);
128
+ }
129
+ output_links[output.name] = links;
130
+ }
131
+ }
132
+
133
+ for(let i in dest.outputs) {
134
+ let links = output_links[dest.outputs[i].name];
135
+ if(links) {
136
+ for(let j in links) {
137
+ let link = links[j];
138
+ let target_node = app.graph.getNodeById(link.target_id);
139
+ dest.connect(parseInt(i), target_node, link.target_slot);
140
+ }
141
+ }
142
+ }
143
+ }
144
+
145
+ if(copy_shape) {
146
+ dest.color = src.color;
147
+ dest.bgcolor = src.bgcolor;
148
+ dest.size = max(src.size, dest.size);
149
+ }
150
+
151
+ app.graph.afterChange();
152
+ }
153
+
154
+ app.registerExtension({
155
+ name: "Comfy.Manager.NodeFixer",
156
+
157
+ async nodeCreated(node, app) {
158
+ let orig_dblClick = node.onDblClick;
159
+ node.onDblClick = function (e, pos, self) {
160
+ orig_dblClick?.apply?.(this, arguments);
161
+
162
+ if((!node.inputs && !node.outputs) || pos[1] > 0)
163
+ return;
164
+
165
+ switch(double_click_policy) {
166
+ case "copy-all":
167
+ case "copy-full":
168
+ case "copy-input":
169
+ {
170
+ if(node.inputs?.some(x => x.link != null) || node.outputs?.some(x => x.links != null && x.links.length > 0) )
171
+ return;
172
+
173
+ let src_node = lookup_nearest_nodes(node);
174
+ if(src_node)
175
+ {
176
+ let both_connection = double_click_policy != "copy-input";
177
+ let copy_shape = double_click_policy == "copy-full";
178
+ node_info_copy(src_node, node, both_connection, copy_shape);
179
+ }
180
+ }
181
+ break;
182
+ case "possible-input":
183
+ {
184
+ let nearest_inputs = lookup_nearest_inputs(node);
185
+ if(nearest_inputs)
186
+ connect_inputs(nearest_inputs, node);
187
+ }
188
+ break;
189
+ case "dual":
190
+ {
191
+ if(pos[0] < node.size[0]/2) {
192
+ // left: possible-input
193
+ let nearest_inputs = lookup_nearest_inputs(node);
194
+ if(nearest_inputs)
195
+ connect_inputs(nearest_inputs, node);
196
+ }
197
+ else {
198
+ // right: copy-all
199
+ if(node.inputs?.some(x => x.link != null) || node.outputs?.some(x => x.links != null && x.links.length > 0) )
200
+ return;
201
+
202
+ let src_node = lookup_nearest_nodes(node);
203
+ if(src_node)
204
+ node_info_copy(src_node, node, true);
205
+ }
206
+ }
207
+ break;
208
+ }
209
+ }
210
+ },
211
+
212
+ beforeRegisterNodeDef(nodeType, nodeData, app) {
213
+ addMenuHandler(nodeType, function (_, options) {
214
+ options.push({
215
+ content: "Fix node (recreate)",
216
+ callback: () => {
217
+ let new_node = LiteGraph.createNode(nodeType.comfyClass);
218
+ new_node.pos = [this.pos[0], this.pos[1]];
219
+ app.canvas.graph.add(new_node, false);
220
+ node_info_copy(this, new_node, true);
221
+ app.canvas.graph.remove(this);
222
+ },
223
+ });
224
+ });
225
+ }
226
+ });
ComfyUI/custom_nodes/ComfyUI-Manager/js/snapshot.js ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../scripts/app.js";
2
+ import { api } from "../../scripts/api.js"
3
+ import { ComfyDialog, $el } from "../../scripts/ui.js";
4
+ import { manager_instance, rebootAPI, show_message } from "./common.js";
5
+
6
+
7
+ async function restore_snapshot(target) {
8
+ if(SnapshotManager.instance) {
9
+ try {
10
+ const response = await api.fetchApi(`/snapshot/restore?target=${target}`, { cache: "no-store" });
11
+
12
+ if(response.status == 403) {
13
+ show_message('This action is not allowed with this security level configuration.');
14
+ return false;
15
+ }
16
+
17
+ if(response.status == 400) {
18
+ show_message(`Restore snapshot failed: ${target.title} / ${exception}`);
19
+ }
20
+
21
+ app.ui.dialog.close();
22
+ return true;
23
+ }
24
+ catch(exception) {
25
+ show_message(`Restore snapshot failed: ${target.title} / ${exception}`);
26
+ return false;
27
+ }
28
+ finally {
29
+ await SnapshotManager.instance.invalidateControl();
30
+ SnapshotManager.instance.updateMessage("<BR>To apply the snapshot, please <button id='cm-reboot-button2' class='cm-small-button'>RESTART</button> ComfyUI. And refresh browser.", 'cm-reboot-button2');
31
+ }
32
+ }
33
+ }
34
+
35
+ async function remove_snapshot(target) {
36
+ if(SnapshotManager.instance) {
37
+ try {
38
+ const response = await api.fetchApi(`/snapshot/remove?target=${target}`, { cache: "no-store" });
39
+
40
+ if(response.status == 403) {
41
+ show_message('This action is not allowed with this security level configuration.');
42
+ return false;
43
+ }
44
+
45
+ if(response.status == 400) {
46
+ show_message(`Remove snapshot failed: ${target.title} / ${exception}`);
47
+ }
48
+
49
+ app.ui.dialog.close();
50
+ return true;
51
+ }
52
+ catch(exception) {
53
+ show_message(`Restore snapshot failed: ${target.title} / ${exception}`);
54
+ return false;
55
+ }
56
+ finally {
57
+ await SnapshotManager.instance.invalidateControl();
58
+ }
59
+ }
60
+ }
61
+
62
+ async function save_current_snapshot() {
63
+ try {
64
+ const response = await api.fetchApi('/snapshot/save', { cache: "no-store" });
65
+ app.ui.dialog.close();
66
+ return true;
67
+ }
68
+ catch(exception) {
69
+ show_message(`Backup snapshot failed: ${exception}`);
70
+ return false;
71
+ }
72
+ finally {
73
+ await SnapshotManager.instance.invalidateControl();
74
+ SnapshotManager.instance.updateMessage("<BR>Current snapshot saved.");
75
+ }
76
+ }
77
+
78
+ async function getSnapshotList() {
79
+ const response = await api.fetchApi(`/snapshot/getlist`);
80
+ const data = await response.json();
81
+ return data;
82
+ }
83
+
84
+ export class SnapshotManager extends ComfyDialog {
85
+ static instance = null;
86
+
87
+ restore_buttons = [];
88
+ message_box = null;
89
+ data = null;
90
+
91
+ clear() {
92
+ this.restore_buttons = [];
93
+ this.message_box = null;
94
+ this.data = null;
95
+ }
96
+
97
+ constructor(app, manager_dialog) {
98
+ super();
99
+ this.manager_dialog = manager_dialog;
100
+ this.search_keyword = '';
101
+ this.element = $el("div.comfy-modal", { parent: document.body }, []);
102
+ }
103
+
104
+ async remove_item() {
105
+ caller.disableButtons();
106
+
107
+ await caller.invalidateControl();
108
+ }
109
+
110
+ createControls() {
111
+ return [
112
+ $el("button.cm-small-button", {
113
+ type: "button",
114
+ textContent: "Close",
115
+ onclick: () => { this.close(); }
116
+ })
117
+ ];
118
+ }
119
+
120
+ startRestore(target) {
121
+ const self = SnapshotManager.instance;
122
+
123
+ self.updateMessage(`<BR><font color="green">Restore snapshot '${target.name}'</font>`);
124
+
125
+ for(let i in self.restore_buttons) {
126
+ self.restore_buttons[i].disabled = true;
127
+ self.restore_buttons[i].style.backgroundColor = 'gray';
128
+ }
129
+ }
130
+
131
+ async invalidateControl() {
132
+ this.clear();
133
+ this.data = (await getSnapshotList()).items;
134
+
135
+ while (this.element.children.length) {
136
+ this.element.removeChild(this.element.children[0]);
137
+ }
138
+
139
+ await this.createGrid();
140
+ await this.createBottomControls();
141
+ }
142
+
143
+ updateMessage(msg, btn_id) {
144
+ this.message_box.innerHTML = msg;
145
+ if(btn_id) {
146
+ const rebootButton = document.getElementById(btn_id);
147
+ const self = this;
148
+ rebootButton.onclick = function() {
149
+ if(rebootAPI()) {
150
+ self.close();
151
+ self.manager_dialog.close();
152
+ }
153
+ };
154
+ }
155
+ }
156
+
157
+ async createGrid(models_json) {
158
+ var grid = document.createElement('table');
159
+ grid.setAttribute('id', 'snapshot-list-grid');
160
+
161
+ var thead = document.createElement('thead');
162
+ var tbody = document.createElement('tbody');
163
+
164
+ var headerRow = document.createElement('tr');
165
+ thead.style.position = "sticky";
166
+ thead.style.top = "0px";
167
+ thead.style.borderCollapse = "collapse";
168
+ thead.style.tableLayout = "fixed";
169
+
170
+ var header1 = document.createElement('th');
171
+ header1.innerHTML = '&nbsp;&nbsp;ID&nbsp;&nbsp;';
172
+ header1.style.width = "20px";
173
+ var header2 = document.createElement('th');
174
+ header2.innerHTML = 'Datetime';
175
+ header2.style.width = "100%";
176
+ var header_button = document.createElement('th');
177
+ header_button.innerHTML = 'Action';
178
+ header_button.style.width = "100px";
179
+
180
+ thead.appendChild(headerRow);
181
+ headerRow.appendChild(header1);
182
+ headerRow.appendChild(header2);
183
+ headerRow.appendChild(header_button);
184
+
185
+ headerRow.style.backgroundColor = "Black";
186
+ headerRow.style.color = "White";
187
+ headerRow.style.textAlign = "center";
188
+ headerRow.style.width = "100%";
189
+ headerRow.style.padding = "0";
190
+
191
+ grid.appendChild(thead);
192
+ grid.appendChild(tbody);
193
+
194
+ this.grid_rows = {};
195
+
196
+ if(this.data)
197
+ for (var i = 0; i < this.data.length; i++) {
198
+ const data = this.data[i];
199
+ var dataRow = document.createElement('tr');
200
+ var data1 = document.createElement('td');
201
+ data1.style.textAlign = "center";
202
+ data1.innerHTML = i+1;
203
+ var data2 = document.createElement('td');
204
+ data2.innerHTML = `&nbsp;${data}`;
205
+ var data_button = document.createElement('td');
206
+ data_button.style.textAlign = "center";
207
+
208
+ var restoreBtn = document.createElement('button');
209
+ restoreBtn.innerHTML = 'Restore';
210
+ restoreBtn.style.width = "100px";
211
+ restoreBtn.style.backgroundColor = 'blue';
212
+
213
+ restoreBtn.addEventListener('click', function() {
214
+ restore_snapshot(data);
215
+ });
216
+
217
+ var removeBtn = document.createElement('button');
218
+ removeBtn.innerHTML = 'Remove';
219
+ removeBtn.style.width = "100px";
220
+ removeBtn.style.backgroundColor = 'red';
221
+
222
+ removeBtn.addEventListener('click', function() {
223
+ remove_snapshot(data);
224
+ });
225
+
226
+ data_button.appendChild(restoreBtn);
227
+ data_button.appendChild(removeBtn);
228
+
229
+ dataRow.style.backgroundColor = "var(--bg-color)";
230
+ dataRow.style.color = "var(--fg-color)";
231
+ dataRow.style.textAlign = "left";
232
+
233
+ dataRow.appendChild(data1);
234
+ dataRow.appendChild(data2);
235
+ dataRow.appendChild(data_button);
236
+ tbody.appendChild(dataRow);
237
+
238
+ this.grid_rows[i] = {data:data, control:dataRow};
239
+ }
240
+
241
+ let self = this;
242
+ const panel = document.createElement('div');
243
+ panel.style.width = "100%";
244
+ panel.appendChild(grid);
245
+
246
+ function handleResize() {
247
+ const parentHeight = self.element.clientHeight;
248
+ const gridHeight = parentHeight - 200;
249
+
250
+ grid.style.height = gridHeight + "px";
251
+ }
252
+ window.addEventListener("resize", handleResize);
253
+
254
+ grid.style.position = "relative";
255
+ grid.style.display = "inline-block";
256
+ grid.style.width = "100%";
257
+ grid.style.height = "100%";
258
+ grid.style.overflowY = "scroll";
259
+ this.element.style.height = "85%";
260
+ this.element.style.width = "80%";
261
+ this.element.appendChild(panel);
262
+
263
+ handleResize();
264
+ }
265
+
266
+ async createBottomControls() {
267
+ var close_button = document.createElement("button");
268
+ close_button.className = "cm-small-button";
269
+ close_button.innerHTML = "Close";
270
+ close_button.onclick = () => { this.close(); }
271
+ close_button.style.display = "inline-block";
272
+
273
+ var save_button = document.createElement("button");
274
+ save_button.className = "cm-small-button";
275
+ save_button.innerHTML = "Save snapshot";
276
+ save_button.onclick = () => { save_current_snapshot(); }
277
+ save_button.style.display = "inline-block";
278
+ save_button.style.horizontalAlign = "right";
279
+ save_button.style.width = "170px";
280
+
281
+ this.message_box = $el('div', {id:'custom-download-message'}, [$el('br'), '']);
282
+ this.message_box.style.height = '60px';
283
+ this.message_box.style.verticalAlign = 'middle';
284
+
285
+ this.element.appendChild(this.message_box);
286
+ this.element.appendChild(close_button);
287
+ this.element.appendChild(save_button);
288
+ }
289
+
290
+ async show() {
291
+ try {
292
+ this.invalidateControl();
293
+ this.element.style.display = "block";
294
+ this.element.style.zIndex = 10001;
295
+ }
296
+ catch(exception) {
297
+ app.ui.dialog.show(`Failed to get external model list. / ${exception}`);
298
+ }
299
+ }
300
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/js/turbogrid.esm.js ADDED
The diff for this file is too large to render. See raw diff
 
ComfyUI/custom_nodes/ComfyUI-Manager/json-checker.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import argparse
3
+
4
+ def check_json_syntax(file_path):
5
+ try:
6
+ with open(file_path, 'r', encoding='utf-8') as file:
7
+ json_str = file.read()
8
+ json.loads(json_str)
9
+ print(f"[ OK ] {file_path}")
10
+ except UnicodeDecodeError as e:
11
+ print(f"Unicode decode error: {e}")
12
+ except json.JSONDecodeError as e:
13
+ print(f"[FAIL] {file_path}\n\n {e}\n")
14
+ except FileNotFoundError:
15
+ print(f"[FAIL] {file_path}\n\n File not found\n")
16
+
17
+ def main():
18
+ parser = argparse.ArgumentParser(description="JSON File Syntax Checker")
19
+ parser.add_argument("file_path", type=str, help="Path to the JSON file for syntax checking")
20
+
21
+ args = parser.parse_args()
22
+ check_json_syntax(args.file_path)
23
+
24
+ if __name__ == "__main__":
25
+ main()
ComfyUI/custom_nodes/ComfyUI-Manager/misc/Impact.pack ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "Impact::MAKE_BASIC_PIPE": {
3
+ "category": "",
4
+ "config": {
5
+ "1": {
6
+ "input": {
7
+ "text": {
8
+ "name": "Positive prompt"
9
+ }
10
+ }
11
+ },
12
+ "2": {
13
+ "input": {
14
+ "text": {
15
+ "name": "Negative prompt"
16
+ }
17
+ }
18
+ }
19
+ },
20
+ "datetime": 1705418802481,
21
+ "external": [],
22
+ "links": [
23
+ [
24
+ 0,
25
+ 1,
26
+ 1,
27
+ 0,
28
+ 1,
29
+ "CLIP"
30
+ ],
31
+ [
32
+ 0,
33
+ 1,
34
+ 2,
35
+ 0,
36
+ 1,
37
+ "CLIP"
38
+ ],
39
+ [
40
+ 0,
41
+ 0,
42
+ 3,
43
+ 0,
44
+ 1,
45
+ "MODEL"
46
+ ],
47
+ [
48
+ 0,
49
+ 1,
50
+ 3,
51
+ 1,
52
+ 1,
53
+ "CLIP"
54
+ ],
55
+ [
56
+ 0,
57
+ 2,
58
+ 3,
59
+ 2,
60
+ 1,
61
+ "VAE"
62
+ ],
63
+ [
64
+ 1,
65
+ 0,
66
+ 3,
67
+ 3,
68
+ 3,
69
+ "CONDITIONING"
70
+ ],
71
+ [
72
+ 2,
73
+ 0,
74
+ 3,
75
+ 4,
76
+ 4,
77
+ "CONDITIONING"
78
+ ]
79
+ ],
80
+ "nodes": [
81
+ {
82
+ "flags": {},
83
+ "index": 0,
84
+ "mode": 0,
85
+ "order": 0,
86
+ "outputs": [
87
+ {
88
+ "links": [],
89
+ "name": "MODEL",
90
+ "shape": 3,
91
+ "slot_index": 0,
92
+ "type": "MODEL"
93
+ },
94
+ {
95
+ "links": [],
96
+ "name": "CLIP",
97
+ "shape": 3,
98
+ "slot_index": 1,
99
+ "type": "CLIP"
100
+ },
101
+ {
102
+ "links": [],
103
+ "name": "VAE",
104
+ "shape": 3,
105
+ "slot_index": 2,
106
+ "type": "VAE"
107
+ }
108
+ ],
109
+ "pos": [
110
+ 550,
111
+ 360
112
+ ],
113
+ "properties": {
114
+ "Node name for S&R": "CheckpointLoaderSimple"
115
+ },
116
+ "size": {
117
+ "0": 315,
118
+ "1": 98
119
+ },
120
+ "type": "CheckpointLoaderSimple",
121
+ "widgets_values": [
122
+ "SDXL/sd_xl_base_1.0_0.9vae.safetensors"
123
+ ]
124
+ },
125
+ {
126
+ "flags": {},
127
+ "index": 1,
128
+ "inputs": [
129
+ {
130
+ "link": null,
131
+ "name": "clip",
132
+ "type": "CLIP"
133
+ }
134
+ ],
135
+ "mode": 0,
136
+ "order": 1,
137
+ "outputs": [
138
+ {
139
+ "links": [],
140
+ "name": "CONDITIONING",
141
+ "shape": 3,
142
+ "slot_index": 0,
143
+ "type": "CONDITIONING"
144
+ }
145
+ ],
146
+ "pos": [
147
+ 940,
148
+ 480
149
+ ],
150
+ "properties": {
151
+ "Node name for S&R": "CLIPTextEncode"
152
+ },
153
+ "size": {
154
+ "0": 263,
155
+ "1": 99
156
+ },
157
+ "title": "Positive",
158
+ "type": "CLIPTextEncode",
159
+ "widgets_values": [
160
+ ""
161
+ ]
162
+ },
163
+ {
164
+ "flags": {},
165
+ "index": 2,
166
+ "inputs": [
167
+ {
168
+ "link": null,
169
+ "name": "clip",
170
+ "type": "CLIP"
171
+ }
172
+ ],
173
+ "mode": 0,
174
+ "order": 2,
175
+ "outputs": [
176
+ {
177
+ "links": [],
178
+ "name": "CONDITIONING",
179
+ "shape": 3,
180
+ "slot_index": 0,
181
+ "type": "CONDITIONING"
182
+ }
183
+ ],
184
+ "pos": [
185
+ 940,
186
+ 640
187
+ ],
188
+ "properties": {
189
+ "Node name for S&R": "CLIPTextEncode"
190
+ },
191
+ "size": {
192
+ "0": 263,
193
+ "1": 99
194
+ },
195
+ "title": "Negative",
196
+ "type": "CLIPTextEncode",
197
+ "widgets_values": [
198
+ ""
199
+ ]
200
+ },
201
+ {
202
+ "flags": {},
203
+ "index": 3,
204
+ "inputs": [
205
+ {
206
+ "link": null,
207
+ "name": "model",
208
+ "type": "MODEL"
209
+ },
210
+ {
211
+ "link": null,
212
+ "name": "clip",
213
+ "type": "CLIP"
214
+ },
215
+ {
216
+ "link": null,
217
+ "name": "vae",
218
+ "type": "VAE"
219
+ },
220
+ {
221
+ "link": null,
222
+ "name": "positive",
223
+ "type": "CONDITIONING"
224
+ },
225
+ {
226
+ "link": null,
227
+ "name": "negative",
228
+ "type": "CONDITIONING"
229
+ }
230
+ ],
231
+ "mode": 0,
232
+ "order": 3,
233
+ "outputs": [
234
+ {
235
+ "links": null,
236
+ "name": "basic_pipe",
237
+ "shape": 3,
238
+ "slot_index": 0,
239
+ "type": "BASIC_PIPE"
240
+ }
241
+ ],
242
+ "pos": [
243
+ 1320,
244
+ 360
245
+ ],
246
+ "properties": {
247
+ "Node name for S&R": "ToBasicPipe"
248
+ },
249
+ "size": {
250
+ "0": 241.79998779296875,
251
+ "1": 106
252
+ },
253
+ "type": "ToBasicPipe"
254
+ }
255
+ ],
256
+ "packname": "Impact",
257
+ "version": "1.0"
258
+ },
259
+ "Impact::SIMPLE_DETAILER_PIPE": {
260
+ "category": "",
261
+ "config": {
262
+ "0": {
263
+ "output": {
264
+ "0": {
265
+ "visible": false
266
+ },
267
+ "1": {
268
+ "visible": false
269
+ }
270
+ }
271
+ },
272
+ "2": {
273
+ "input": {
274
+ "Select to add LoRA": {
275
+ "visible": false
276
+ },
277
+ "Select to add Wildcard": {
278
+ "visible": false
279
+ },
280
+ "wildcard": {
281
+ "visible": false
282
+ }
283
+ }
284
+ }
285
+ },
286
+ "datetime": 1705419147116,
287
+ "external": [],
288
+ "links": [
289
+ [
290
+ null,
291
+ 0,
292
+ 2,
293
+ 0,
294
+ 6,
295
+ "BASIC_PIPE"
296
+ ],
297
+ [
298
+ 0,
299
+ 0,
300
+ 2,
301
+ 1,
302
+ 13,
303
+ "BBOX_DETECTOR"
304
+ ],
305
+ [
306
+ 1,
307
+ 0,
308
+ 2,
309
+ 2,
310
+ 15,
311
+ "SAM_MODEL"
312
+ ]
313
+ ],
314
+ "nodes": [
315
+ {
316
+ "flags": {},
317
+ "index": 0,
318
+ "mode": 0,
319
+ "order": 2,
320
+ "outputs": [
321
+ {
322
+ "links": [],
323
+ "name": "BBOX_DETECTOR",
324
+ "shape": 3,
325
+ "type": "BBOX_DETECTOR"
326
+ },
327
+ {
328
+ "links": null,
329
+ "name": "SEGM_DETECTOR",
330
+ "shape": 3,
331
+ "type": "SEGM_DETECTOR"
332
+ }
333
+ ],
334
+ "pos": [
335
+ 590,
336
+ 830
337
+ ],
338
+ "properties": {
339
+ "Node name for S&R": "UltralyticsDetectorProvider"
340
+ },
341
+ "size": {
342
+ "0": 315,
343
+ "1": 78
344
+ },
345
+ "type": "UltralyticsDetectorProvider",
346
+ "widgets_values": [
347
+ "bbox/Eyeful_v1.pt"
348
+ ]
349
+ },
350
+ {
351
+ "flags": {},
352
+ "index": 1,
353
+ "mode": 0,
354
+ "order": 3,
355
+ "outputs": [
356
+ {
357
+ "links": [],
358
+ "name": "SAM_MODEL",
359
+ "shape": 3,
360
+ "type": "SAM_MODEL"
361
+ }
362
+ ],
363
+ "pos": [
364
+ 590,
365
+ 960
366
+ ],
367
+ "properties": {
368
+ "Node name for S&R": "SAMLoader"
369
+ },
370
+ "size": {
371
+ "0": 315,
372
+ "1": 82
373
+ },
374
+ "type": "SAMLoader",
375
+ "widgets_values": [
376
+ "sam_vit_b_01ec64.pth",
377
+ "AUTO"
378
+ ]
379
+ },
380
+ {
381
+ "flags": {},
382
+ "index": 2,
383
+ "inputs": [
384
+ {
385
+ "link": null,
386
+ "name": "basic_pipe",
387
+ "type": "BASIC_PIPE"
388
+ },
389
+ {
390
+ "link": null,
391
+ "name": "bbox_detector",
392
+ "slot_index": 1,
393
+ "type": "BBOX_DETECTOR"
394
+ },
395
+ {
396
+ "link": null,
397
+ "name": "sam_model_opt",
398
+ "slot_index": 2,
399
+ "type": "SAM_MODEL"
400
+ },
401
+ {
402
+ "link": null,
403
+ "name": "segm_detector_opt",
404
+ "type": "SEGM_DETECTOR"
405
+ },
406
+ {
407
+ "link": null,
408
+ "name": "detailer_hook",
409
+ "type": "DETAILER_HOOK"
410
+ }
411
+ ],
412
+ "mode": 0,
413
+ "order": 5,
414
+ "outputs": [
415
+ {
416
+ "links": null,
417
+ "name": "detailer_pipe",
418
+ "shape": 3,
419
+ "type": "DETAILER_PIPE"
420
+ }
421
+ ],
422
+ "pos": [
423
+ 1044,
424
+ 812
425
+ ],
426
+ "properties": {
427
+ "Node name for S&R": "BasicPipeToDetailerPipe"
428
+ },
429
+ "size": {
430
+ "0": 400,
431
+ "1": 204
432
+ },
433
+ "type": "BasicPipeToDetailerPipe",
434
+ "widgets_values": [
435
+ "",
436
+ "Select the LoRA to add to the text",
437
+ "Select the Wildcard to add to the text"
438
+ ]
439
+ }
440
+ ],
441
+ "packname": "Impact",
442
+ "version": "1.0"
443
+ }
444
+ }
ComfyUI/custom_nodes/ComfyUI-Manager/misc/custom-nodes.jpg ADDED
ComfyUI/custom_nodes/ComfyUI-Manager/misc/main.jpg ADDED
ComfyUI/custom_nodes/ComfyUI-Manager/misc/menu.jpg ADDED
ComfyUI/custom_nodes/ComfyUI-Manager/misc/missing-list.jpg ADDED
ComfyUI/custom_nodes/ComfyUI-Manager/misc/missing-menu.jpg ADDED
ComfyUI/custom_nodes/ComfyUI-Manager/misc/models.png ADDED
ComfyUI/custom_nodes/ComfyUI-Manager/misc/nickname.jpg ADDED
ComfyUI/custom_nodes/ComfyUI-Manager/misc/portable-install.png ADDED
ComfyUI/custom_nodes/ComfyUI-Manager/misc/share-setting.jpg ADDED