Compare commits

...
Author SHA1 Message Date
Dr.Lt.Data 77a8fc0cdc An install by a git URL clones a repository that the registry lists
`cm-cli install <url>` and Install via Git URL asked the registry for the
latest version of the nodepack and unpacked its archive when the URL was of
a repository that the registry lists, since #1813 (3.32). The URL with
`@<commit>` was cloned.

- `gitclone_install` asks for the nightly of such a nodepack, which is a
  clone of its repository. A version of the registry that is enabled is
  disabled for the clone, as for any nightly install
- `_install_git` enables that version again when the clone fails. It
  disabled the version before the clone and left the nodepack with no
  enabled version, also for `<id>@nightly` and for a switch to nightly in
  Custom Nodes Manager
- `gitclone_install` passes `instant_execution` and `no_deps` on, which were
  dropped for such a repository, and the URL, which `install_by_id` now
  takes as `reinstall_by_id` does. The clone is of the URL that was given,
  also when the channel has another repository under the name of the nodepack
- `_get_git_install_url` takes the repository of a nightly from the registry
  when the channel does not list the nodepack. Without it that install fails
  with `Node '<id>@nightly' not found`, which #1813 avoided by asking for no
  version (#1812)
- `cm-cli reinstall` of a nightly clone that only the registry lists clones
  it again. The test that pinned `not found` for it now expects the clone
- Add tests: the URL of a repository that only the registry lists is cloned
  from a repository of the test with the flags of the caller, also over a
  version that is enabled or disabled, and the enabled version is enabled
  again when the clone fails
- Add a CHANGELOG entry
2026-12-05 21:11:48 +09:00
Dr.Lt.Data f2bfcd979a update DB 2026-12-05 11:12:36 +09:00
Dr.Lt.Data 78443bb50f Merge pull request #3497 from xm6018924/bsai-split-3-media-servers
Add 2 BSAI custom node packs to custom node list (split 3/3: media server packs)
2026-12-05 11:12:19 +09:00
Dr.Lt.Data 85ffb140c1 update DB 2026-12-05 11:11:55 +09:00
Dr.Lt.Data 915f3403c7 Merge pull request #3657 from founden-bot/feat/add-genmagic-nodes
Add GenMagic custom nodes to custom-node-list.json
2026-12-05 11:11:37 +09:00
Dr.Lt.Data 5c92a53132 update DB 2026-12-05 11:11:04 +09:00
Dr.Lt.Data 16223c45fd Merge pull request #3656 from kama0630-cmyk/add-kama0630-studio-packs
Add 5 Studio Packs by kama0630-cmyk (Krea2, SDXL, FLUX, Z-Image, Wan2.2)
2026-12-05 11:10:45 +09:00
Stefano-retinize eb7e6b0640 A folder can be a channel of a private network (#2669)
A line of `channels.list` that names a folder, such as
`private::\\NAS\comfy\channel`, was refused with
`An invalid channel was used`: `normalize_channel` took an https URL,
an http URL with `http_channel_enabled`, or the name of a channel, and
raised `InvalidChannel` for the folder that the name stood for.

- `normalize_channel` returns a UNC path or an absolute path as it is
  with `network_mode = private`. `load_nightly` still refuses a channel
  that `channels.list` does not have, so a folder that a request names
  is refused before anything is read
- With another `network_mode` the folder is refused with a reason that
  names the channel by its name of `channels.list`, and the setting.
  No reason has the URL or the folder of a channel in it
- The reason is what the list route of the Custom Nodes Manager
  answers with 403 in place of a 500, what the page shows in place of
  `Failed to get custom node list.`, what an install reports, and what
  `cm-cli` prints in place of a traceback. The start logs it as a
  warning and completes
- Add tests and a CHANGELOG entry

The same change for manager-v4 is #3654.
2026-12-05 10:34:09 +09:00
founden-bot aeba60fce8 Add GenMagic custom nodes to custom-node-list.json 2026-12-04 23:13:50 +00:00
kama 07f678bdb1 Add 5 Studio Packs by kama0630-cmyk to custom-node-list.json 2026-12-04 09:16:13 +09:00
KeLin f9edca916f A list request without mode is answered (#2741)
`GET /customnode/getlist`, `/customnode/getmappings` and
`/externalmodel/getlist` read `mode` with
`request.rel_url.query["mode"]` and answered 500 with
`KeyError: 'mode'` for a request without it (#2740).

- The three handlers read `mode` with `cache` as its default
- Add a test for the three handlers: a request without `mode` gets the
  answer of `mode=cache`, which is not the answer of `mode=local`
- Add a CHANGELOG entry

The same change for manager-v4 is #3653.
2026-12-04 02:20:49 +09:00
Dr.Lt.Data 40edd368b9 update DB 2026-12-04 01:43:07 +09:00
Dr.Lt.Data be146f983d Merge pull request #3239 from vangel76/add-valitools
Add ValiTools node pack
2026-12-04 01:42:26 +09:00
Dhevenddra K G 42e6979cbe The test of the install-denial messages checks the loopback requirement (#3216)
`is_dedicated_install_allowed` is the flag and a loopback listener, and
the two denial messages, `SECURITY_MESSAGE_FLAG_GIT_URL` and
`SECURITY_MESSAGE_FLAG_PIP`, name both. `_assert_honest_copy` checked
the name of the flag and `config.ini` in them and not the loopback
clause, so an edit could take the clause out of a message with every
test passing.

- `_assert_honest_copy` asserts that the message names the loopback
  requirement

`manager-v4` has this check in
`tests/test_config_write_and_install_denial.py`.
2026-12-04 01:26:29 +09:00
Dr.Lt.Data 2cd48a8e6c Remove retired ComfyUI Sync Lipsync Node entries 2026-12-04 00:41:58 +09:00
Dr.Lt.Data 40482abac9 update DB 2026-12-03 23:34:04 +09:00
Dr.Lt.Data 9e1e224af1 Merge pull request #3655 from ShaoDingBao/add-moback-turbo
Add MoBack-Turbo to custom-node-list.json
2026-12-03 23:33:33 +09:00
Dr.Lt.Data cc5f1cc532 Merge pull request #3646 from haryai-com/add-comfyui-haryai
Add HaryAI (comfyui-haryai) to the custom node list
2026-12-03 23:33:25 +09:00
ShaoDingBao ae51e92df2 Add MoBack-Turbo to custom-node-list.json 2026-12-03 18:37:17 +08:00
赵瑞哲 967de883db The Version column no longer shows an older registry version as an update (#3364)
The Version column of the Custom Nodes Manager showed `[↑<version>]`
whenever the installed version was not the latest version of the
registry, so a nodepack installed at 1.78.1 showed `[↑1.47.0]` when the
registry had 1.47.0 as its latest (#3272). The Update button followed
the server and was right. Only the arrow was wrong.

- `compareVersionSpecs` orders versions that are only numbers, and the
  arrow is shown only when the version of the registry is newer
- For any other version, such as `2.0.0-rc1`, an enabled nodepack
  shows the arrow when the server offers an update for it
  (`update-state`). A disabled nodepack is as before
- Add tests and a CHANGELOG entry

The same change for manager-v4 is #3651.
2026-12-03 12:50:41 +09:00
Dr.Lt.Data cbc597ce25 aria2 does not download a file that is already there (#3647)
With aria2 as the downloader, an install of a model whose file was
already in its folder downloaded the model once more. aria2 does not
overwrite a file that it has no control file for: it saved the download
next to it as `<name>.1.<ext>`, and the install was reported as done
because a file of that name was there. The downloader that is used
without aria2 returns without a download when the file is there.

- `aria2_download_url` returns without asking aria2 when the file is
  there and aria2 has no control file (`<name>.aria2`) for it. A part
  with a control file still goes to aria2, which continues it
- This takes the place of the check for a complete earlier download
  whose file is there, which is one case of it
- The archive of a registry nodepack has a new name at every download
  (`CNR_temp_<uuid>.zip`), so it is always downloaded
- Tests: the stand-ins of three cases put the file there before the
  download was asked for, and now put it there when aria2 is asked.
  Add two cases and a CHANGELOG entry

The same change for manager-v4 is #3648.
2026-12-03 09:02:27 +09:00
ViolinKaine 0187c72807 An aria2 on the same machine can be the downloader (#2999)
With aria2 as the downloader, the Manager asks aria2 to save a file
into `/models/...` or `/custom_nodes`, which is where the container of
`docs/en/use_aria2.md` sees the folders of ComfyUI. An aria2 that runs
on the same machine without a container cannot write there, and its
downloads failed.

- With `COMFYUI_MANAGER_ARIA2_SAME_PATHS=true` the Manager gives aria2
  each folder as ComfyUI sees it. Without it nothing changes
- The error for a file that is not where ComfyUI reads it points to
  `docs/en/use_aria2.md` without naming one of the two setups
- `docs/en/use_aria2.md` describes an aria2 on the same machine
- Add tests and a CHANGELOG entry

The same change for manager-v4 is #3644.
2026-12-03 07:44:06 +09:00
sunsiyuanandClaude Opus 5.5 7b8e3138f2 Add HaryAI (comfyui-haryai) to the custom node list; move seedance-comfyui to its new URL
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-12-03 02:18:29 +08:00
Dr.Lt.Data a3c89b1b39 A download through aria2 that fails is reported as failed (#3643)
With `COMFYUI_MANAGER_ARIA2_SERVER` set, `aria2_download_url` returned
without looking at what aria2 did with the download. A model was
reported as installed when aria2 had failed the download, had saved the
file in a folder that ComfyUI does not read, or still had the download
waiting.

- It waits while aria2 has the download waiting or active, and fails
  with the error message of aria2 when aria2 fails it, or with the
  status of the download when it is paused or removed before it is
  complete
- It fails when the file is not at `<model_dir>/<filename>` once the
  download is over, naming the folder aria2 wrote to and
  `docs/en/use_aria2.md`
- A download of the same file that aria2 still lists is reused only
  while it is waiting or active, or when it is complete and its file is
  there
- When the download of a nodepack archive fails, the install and the
  reserved switch at a start remove the part that was downloaded and
  the control file of aria2 from `custom_nodes`
- Add tests and a CHANGELOG entry

The same change for manager-v4 is #3246, and #3645 for a stopped
download and for the archive.
2026-12-02 23:08:40 +09:00
Dr.Lt.DataandJean Paul Ruiz c9c5aef804 A nodepack that two node mappings name shows all its nodes, and the list is drawn (#3629)
Two node mappings can name one nodepack, one by its id or git URL and
one by its `title_aux`. In the Custom Nodes Manager the second mapping
replaced the nodes of the first. When another nodepack had a node of
the first mapping, the page failed with a `TypeError` in the conflict
pass and drew no list (#2502). A node that both mappings name showed
each other nodepack twice.

- `loadNodes()` adds the mappings of one nodepack to one node map and
  skips a name that is already in it, so each pair of name and nodepack
  enters the conflict map once
- The Nodes column and the node list of such a nodepack have the nodes
  of both mappings, so a row can list more nodes than before
- The checks that #2502 added to the conflict pass are not in the final
  code: with one node map per nodepack the state they skipped does not
  occur
- Add a test and a CHANGELOG entry

It takes the place of #2502. The same change for manager-v4 is #3635.

Co-authored-by: Jean Paul Ruiz <jpruiz114@gmail.com>
2026-12-02 13:06:36 +09:00
Dr.Lt.Data 331710cb03 The Model Manager finds a model in a subfolder of an extra model path (#3631)
A model whose folder in the list has a subfolder, such as
`checkpoints/SD1.5`, was shown as not installed when its file was in
that subfolder of a folder that `extra_model_paths.yaml` adds (#1844).
The row offered Install, and the Installed filter left it out.

- After its checks, `check_model_installed` asks
  `folder_paths.get_full_path` for the rest of the save path and the
  file name, under the first folder of the save path. ComfyUI looks in
  every folder it has for that name, the extra ones included
- The check only adds a way to be found, so a model that was shown as
  installed still is
- Add tests and a CHANGELOG entry

It takes the place of #1859. The same change for manager-v4 is #3633.
2026-12-02 12:45:39 +09:00
yonghaozheng64-commits c298bb3da5 A conflict in the Custom Nodes Manager counts only enabled nodepacks (#3273)
The Nodes column of the Custom Nodes Manager counted a conflict for
every node name that another nodepack in the list also has, whether
that nodepack is installed or not. An enabled nodepack showed
`N conflicts` for nodepacks that are disabled or not installed, which
ComfyUI does not load (#3092).

- A conflict counts only another enabled nodepack. An enabled nodepack
  shows `N conflicts`, and its node list says
  `Conflict with enabled packs`
- A disabled or not installed nodepack shows `N potential conflicts`
  for the enabled nodepacks it would conflict with, and its node list
  says `Potential conflict if installed/enabled with`
- Two nodepacks that are both not enabled show nothing for each other
- `N potential conflicts` takes two lines in the Nodes column, which is
  100px wide
- Add tests and a CHANGELOG entry

The same change for manager-v4 is #3636.
2026-12-02 09:07:59 +09:00
Perfect Johny fcb1799d24 An install without a version enables a disabled registry nodepack, and an enable request fails for one the registry data does not list (#3528)
An install without a version did not see a registry nodepack that was
disabled: with the nodepack disabled at 1.0.0 and the registry at
2.0.0, `cm-cli install <id>` installed 2.0.0. And a request to enable a
disabled nodepack that the registry data does not list was answered
with success, while nothing was enabled (#3469).

- `is_disabled()` counts a disabled registry version when no version is
  given, so the install enables it with no download
- `unified_enable()` fails with `Specified inactive node not exists:
  <id>` when it can name no version to enable, unless the nodepack is
  enabled. The request is then answered with 400 and that reason
- An install without a version leaves out the disabled versions whose
  folder is gone, when one is left, and enables the newest that is
  there
- Add tests and a CHANGELOG entry

The same change for manager-v4 is #3638.
2026-12-02 02:40:56 +09:00
Hyungjoo Jeon ab8410cb27 An install from a Git URL installs the dependencies when Windows cannot read requirements.txt (#3520)
An install of a nodepack from a Git URL (Install via Git URL,
`cm-cli install <URL>`, `cm-cli install-deps`) read its
`requirements.txt` in the encoding of the locale, which on Windows is
the ANSI code page. A UTF-8 file with a Chinese or Korean comment failed
with `UnicodeDecodeError`, and the nodepack was cloned without its
dependencies.

- Read the file of a Git URL install with the new
  `read_requirements_lines()`: when the locale cannot read it, take the
  encoding that `chardet` names, if that encoding reads ASCII bytes as
  ASCII or is UTF-16/32 and every line is printable ASCII outside its
  comment
- Otherwise fail with the same `UnicodeDecodeError` as before, as for a
  file that is not text or a requirement with a non-ASCII path. Such a
  failure no longer installs the lines in front of the byte it fails on
- Leave `robust_readlines()`, the Registry install and the install at
  startup as they are
- Add tests and a CHANGELOG entry

The same change for manager-v4 is #3637.
2026-12-02 00:59:44 +09:00
Gary 983cd37888 A nodepack that only the registry lists shows Update when the registry has a newer version (#3261)
A nodepack that is in the registry and not in the node list never showed
Update in the Custom Nodes Manager, and the Update filter did not list
it, even when the registry had a newer version (#3220). Its row showed
Try update, which did update it, but nothing said that an update was
there.

- Give the rows of registry-only nodepacks the `update-state` that the
  page reads, as the rows of the node list have: `true` for an enabled
  nodepack with a newer version in the registry, `false` otherwise
- Offer no Update for a nodepack installed as nightly, as for a
  nodepack of the node list
- A registry-only nodepack that failed to import and has a newer
  version shows Update in place of `IMPORT FAILED` and Try fix, as the
  row of a nodepack of the node list already did. The Import Failed
  filter still lists it
- Add a test and a CHANGELOG entry

The same change for manager-v4 is #3634.
2026-12-01 19:13:44 +09:00
Dr.Lt.Data 2db3f4d60c Merge pull request #3640 from alphaziod/update-saya-couple
Update alphaziod entry: Saya Couple (renamed repo)
2026-12-01 18:20:26 +09:00
alphaziodandClaude Sonnet 5.5 5dac360d69 Update alphaziod node entry: Saya Couple
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 10:04:57 +01:00
H.W.Prinz 6f98354e4b The log file has no color codes of the console (#3315)
The Manager writes what ComfyUI prints to the console and to the log
file, `comfyui.log` in the user directory. The color codes of the
console, such as `ESC[32m`, went into the file as well, where an editor
or `grep` shows them as text.

- Leave the color codes out of what is written to the log file: an
  `ESC[` sequence of digits, `;` and `?` that ends in a letter. The
  console gets the text as before, with its colors
- Read the setting `strip_ansi_file_logging` of `config.ini`. Without
  the key the codes are left out, and with `false` the file keeps them
  as before
- Add tests and a CHANGELOG entry

The same change for manager-v4 is #3466.
2026-12-01 12:24:57 +09:00
zzlol63 ab7ed0f67d The Node Usage Analyzer counts the nodes inside subgraphs, and Uninstall Selected uninstalls (#3285)
The Node Usage Analyzer counted only the nodes at the top of a workflow,
not those inside a subgraph, and left out a workflow that had a `null`
node. A nodepack that was used only there showed 0 workflows and was
offered for uninstall. A node whose `cnr_id` is not text stopped the whole
count with `TypeError: cnrId.toLowerCase is not a function`.

Uninstall Selected uninstalled nothing. The page sent the queue reset and
start as GET to routes that take only POST, and a nodepack that only the
registry lists was queued without a name. The page said to restart
ComfyUI, and the uninstalls ran at the next Update All.

- Scan the nodes of every subgraph of a workflow, also of a subgraph
  inside a subgraph. Skip a node that is not an object or whose `type` is
  not text, and leave out a `cnr_id` that is not text
- Read a workflow file inside a `with` block, so the file is closed when
  the read ends
- Send the queue reset and start of Uninstall Selected and of the analyzer
  as POST with Content-Type: application/json
- Give a nodepack that the list names without an `id` its key as `id`, so
  it is queued by name
- Report a queue that did not start, in place of the restart message
- Add tests and a CHANGELOG entry
2026-12-01 09:41:09 +09:00
Dr.Lt.Data b3cabc86ee update DB 2026-12-01 00:56:54 +09:00
Dr.Lt.Data 69529c6784 Merge pull request #3621 from AceDataCloud/catalog/ace-music-gpt-image-local-db-20261130
List ACE Music and GPT Image in the Local DB
2026-12-01 00:56:27 +09:00
Dr.Lt.Data 3902292033 update DB 2026-12-01 00:45:49 +09:00
Dr.Lt.Data c0f58ee0a7 Merge pull request #3622 from nikolai-vysotskyi/add-assetfeed-nodes
Add AssetFeed to the custom node list
2026-12-01 00:45:21 +09:00
Dr.Lt.Data 81ca9190f9 Merge pull request #3593 from Raykosan/main
Add ComfyUI-RS_WorkspaceManager
2026-12-01 00:45:16 +09:00
Dr.Lt.Data 20999f24ad Restore the PyTorch builds that were installed before a nodepack (#3617)
When a nodepack changed torch or torchvision, torch_rollback() chose
what to install from the torch version from before. Without a local
label it sent `pip install --force` with the package names, which
installs the newest releases and which uv refuses. With a label it sent
the versions of a table that ends at 2.7.0, or the newest nightly build
for a version that the table lacks. A nodepack that removed torch, or
removed torchvision and left torch as it was, ended the restore in a
KeyError.

- Give torch_rollback() what was installed before and after the
  nodepack, and the names that the torch from before requires, read when
  PIPFixer is constructed. Count a removed torch or torchvision as
  changed
- Install the torch from before as `torch===<build>` with its
  dependencies, then a changed torchvision or torchaudio with
  `--no-deps`, from https://download.pytorch.org/whl/<label> for a local
  label and from the nightly index for a development build
- Put back with torch each of its requirements, still at its version,
  with a file on disk that is not of the size its RECORD gives, such as
  CUDA libraries that a torch of another CUDA version overwrote. pip
  fetches them before torch is replaced
- Resolve last `torch===<build> torchvision torchaudio<next minor>` with
  dependencies: what fits torch stays, what does not is replaced, a
  removed dependency comes back
- Check in a child process that torch, torchvision and torchaudio work.
  For a torch that does not, install again its requirements with a file
  that is gone. Install a torchvision or torchaudio that does not again
  from torch's index, and log an ERROR for what still does not work
- When the torch from before cannot be had, restore by the version table
  as before. Renew the table up to 2.15.0
- With uv, send the command that installs torch, or a changed
  torchvision or torchaudio, at its build only in a form whose
  `--dry-run` resolved, and once more when it fails while it installs
- Do not start the restore when the disk of site-packages has less free
  space than the restore can take: twice the size of what is installed
  again with pip, one and a half times with uv. PIPFixer reads the sizes
  when it is constructed
- Run pip without its cache during the restore (`PIP_NO_CACHE_DIR`):
  with the cache pip holds each wheel twice while it writes the files,
  which took 2.35 times the size for a CUDA torch for Windows
- Drop the cached package list when a restore runs
- Extend tests/test_torch_rollback.py: the tests run fix_broken() with
  pip and with uv
- Add a CHANGELOG entry

A command that fails after torch was replaced can leave torch not
importable; the restore then ends with an ERROR line. What was measured
and what the restore cannot do is listed in #3617.

The same change for manager-v4 is #3618.
2026-12-01 00:11:23 +09:00
nikolai-vysotskyi 3407fdd404 Describe AssetFeed data handling in the node list entry 2026-11-30 03:27:40 +04:00
nikolai-vysotskyi bebdf19035 Add AssetFeed to the custom node list 2026-11-30 03:25:03 +04:00
Ace Data Cloud Dev dab74c91c9 List ACE Music and GPT Image in Local DB 2026-11-30 00:52:55 +08:00
Raykosan 088c149880 Fix missing comma in custom-node-list 2026-11-25 00:59:05 +03:00
Raykosan f92a308602 Add ComfyUI-RS_WorkspaceManager 2026-11-25 00:48:12 +03:00
BSAI 54285d6322 List only Film Factory and Premiere Pro in the media pack
Drop the BSAI-ComfyUI_Contextual-Series entry. Film Factory already ships all
eleven node classes Contextual-Series registers (BSAI_AssetLibraryInput,
BSAI_AssetRefSelector, BSAI_ClipComposer, BSAI_ClipSequencer,
BSAI_ContextualSeriesExtract/Load, BSAI_ImageBatchSplitter, BSAI_VideoCombiner,
BSAI_AudioCombiner, BSAI_SubtitleConfig/Renderer) plus 27 more, and both packs
also registered the same nine /bsai/* asset routes, so installing both
overwrote one with the other depending on load order. Listing it again would
only re-introduce that overlap; the nodes are reachable through Film Factory.
The Contextual-Series repository keeps its own namespaced /bsai/contextual/*
routes for direct installs.
2026-11-16 13:31:25 +08:00
BSAI 808f6a6b8d Add 3 BSAI custom node packs to custom node list (split 3/3: media server packs)
注册 3 个 BSAI 插件(拆分 3/3:含 HTTP 路由的媒体包):`BSAI-ComfyUI-H3-Film-Factory`, `BSAI_Premiere_Pro`, `BSAI-ComfyUI_Contextual-Series`
2026-11-12 14:17:17 +08:00
vangel76andClaude Opus 5 8dfd5354cb Add ValiTools node pack
ValiTools bundles VSmartPrompt (Dynamic Prompts with a rich-text editor,
reusable variables, switcher conditions, chaining inputs and post-run
selection highlighting), VFileRandom, VRandomSelector and VWaitForVRAM.

Repository: https://github.com/vangel76/comfyui-ValiTools
Registry:   https://registry.comfy.org/publishers/vangel/nodes/valitools

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 00:00:53 +02:00
37 changed files with 4066 additions and 192 deletions
+238
View File
@@ -2,6 +2,244 @@
## Unreleased
### An install by a git URL clones the repository, also one that the registry lists
`cm-cli install <url>` and **Install via Git URL** did not clone a repository
that the registry lists: they asked the registry for the latest version of
that nodepack and unpacked its archive, and said `[INSTALLED] <url>` as for a
clone. The folder had no `.git`, and what the repository got after that
version was not in it. The same URL with `@<commit>` was cloned.
The URL without a commit is now cloned as well, as the nightly of the
nodepack, and the clone is of the URL that was given. A registry version of
the nodepack that is enabled is disabled for that clone. A nightly of the
nodepack that is already installed is kept as it is, and nothing is cloned. A
URL with `@<commit>` is cloned as before. The install also takes `--no-deps`
for such a repository now.
A nightly install over an enabled version disabled that version first, and
left the nodepack with no enabled version when the repository could not be
cloned. The version is now enabled again in that case. A clone that arrives
and whose install script then fails stays in place with the version disabled,
as before. This is also so for `cm-cli install <id>@nightly` and for a switch
to `nightly` in **Custom Nodes Manager**.
A nightly install of a nodepack that the registry lists and the channel does
not failed with `Node '<id>@nightly' not found` (#1812). That is why the
install by a URL was moved to the registry version in 3.32. The repository of
such a nodepack is now taken from the registry: `cm-cli install <id>@nightly`
installs it, and `cm-cli reinstall` of its nightly clone clones it again,
where it said `not found` and left the clone.
### A folder can be a channel of a private network
With `network_mode = private`, a line of `channels.list` can name a folder,
such as `private::\\NAS\comfy\channel` or `private::/srv/comfy/channel`. Such a
line was refused with `An invalid channel was used`: the channel was in the
Channel menu, and its list did not load. The folder is now read as a channel,
so a closed network needs no web server for its own `custom-node-list.json`.
Only a folder that is written in `channels.list` is a channel, and only on a
private network. A folder that a request names, or that only `channel_url` of
`config.ini` names, is refused as before.
With another `network_mode` the folder is refused, and the refusal names the
channel as `channels.list` names it and the setting that it needs, not the
folder. The Custom Nodes Manager shows it in place of
`Failed to get custom node list.`, an install from that channel reports it,
`cm-cli show` prints it in place of a traceback, and the start logs it as a
warning. A refused channel no longer stops the tasks of the start with a
traceback. For a channel that `channels.list` does not have, the Custom Nodes
Manager, `cm-cli` and an install say that a channel has to be in
`channels.list`, without its URL or folder.
### A list request without `mode` is answered
`GET /customnode/getlist`, `/customnode/getmappings` and
`/externalmodel/getlist` answered 500 with `KeyError: 'mode'` when the
request had no `mode` (#2740). Such a request is now answered as one with
`mode=cache`. The pages of the Manager always send `mode`, so nothing changes
for them.
### The Version column no longer shows an older registry version as an update
The Version column of the Custom Nodes Manager showed `[↑<version>]` whenever
the installed version was not the latest version of the registry, so a
nodepack installed at 1.78.1 showed `[↑1.47.0]` when the registry had 1.47.0
as its latest (#3272). The arrow is now shown only when the version of the
registry is newer. For a version that is not only numbers, such as
`2.0.0rc1`, an enabled nodepack shows the arrow when an update is offered for
it, and a disabled one is as before. The **Update** button is not changed: it
was already offered only for a newer version.
### aria2 does not download a file that is already there
With aria2 as the downloader, an install of a model whose file was already in
its folder downloaded the model once more. aria2 saved the download next to
the file under another name (`<name>.1.<ext>`), and the install was reported
as done. Nothing is downloaded now and the file that is there is kept, as
with an install without aria2. A part of a file that aria2 keeps a control
file for (`<name>.aria2`) is still continued.
### An aria2 on the same machine can be the downloader
With aria2 as the downloader, the Manager asks aria2 to save a file into
`/models/...` or `/custom_nodes`, which is where the container of
`docs/en/use_aria2.md` sees the folders of ComfyUI. An aria2 that runs on the
same machine without a container cannot write there, and its downloads failed
(#2999). With `COMFYUI_MANAGER_ARIA2_SAME_PATHS=true` the Manager gives aria2
each folder as ComfyUI sees it. Without the variable nothing changes.
### A download through aria2 that fails is reported as failed
With `COMFYUI_MANAGER_ARIA2_SERVER` set, the Manager did not look at what
aria2 did with a download. A model was reported as installed when aria2 had
failed the download, or had saved the file in a folder that ComfyUI does not
read. A download that aria2 had queued behind others was not waited for: a
model was reported as installed before its file was there, and the install of
a registry nodepack failed with `Failed to extract archive`. An install now
waits for a download that aria2 has queued, and fails with the error of aria2
when aria2 fails the download, or when the download is paused or removed in
aria2 before it is complete. It also fails when the file is not where
ComfyUI reads it, as when aria2 does not see the ComfyUI folder as `/`
(`docs/en/use_aria2.md`): the terminal names the folder that aria2 wrote to.
When the download of the archive of a registry nodepack fails, the part that
was downloaded and the control file of aria2 no longer stay in `custom_nodes`.
### A nodepack that two node mappings name shows all its nodes, and the list is drawn
Two node mappings can name one nodepack, one by its id or git URL and one by
its `title_aux`. In the Custom Nodes Manager the second mapping replaced the
nodes of the first. When another nodepack had a node of the first mapping,
the page failed with `TypeError: Cannot read properties of undefined (reading
'conflicts')` and drew no list (#2502). A node that both mappings name showed
a conflict with no other nodepack, or each other nodepack twice. The Nodes
column and the node list of such a nodepack now have the nodes of both
mappings, and each conflict names each other nodepack once. A row can
therefore list more nodes than before.
### The Model Manager finds a model in a subfolder of an extra model path
A model whose folder in the list has a subfolder, such as `checkpoints/SD1.5`,
was shown as not installed when its file was in that subfolder of a folder
that `extra_model_paths.yaml` adds (#1844). The Model Manager now also asks
ComfyUI where the file is. ComfyUI looks in every folder it has for the first
part of the path, the extra ones included, so the model is shown as installed.
A model that was shown as installed before still is.
### A conflict in the Custom Nodes Manager counts only enabled nodepacks
The Nodes column of the Custom Nodes Manager counted a conflict for every
node name that another nodepack in the list also has, whether that nodepack
is installed or not. An enabled nodepack showed `N conflicts` for nodepacks
that are disabled or not installed, which ComfyUI does not load (#3092,
#3273). A conflict now counts only another enabled nodepack. An enabled
nodepack shows `N conflicts`, and its node list says
`Conflict with enabled packs`. A disabled or not installed nodepack shows
`N potential conflicts` for the enabled nodepacks it would conflict with, and
its node list says `Potential conflict if installed/enabled with`. In the
Nodes column `N potential conflicts` takes two lines. Two nodepacks that are
both not enabled show nothing for each other.
### An install without a version enables a disabled registry nodepack, and an enable request fails for one the registry data does not list
An install without a version did not see a registry nodepack that was
disabled: with the nodepack disabled at 1.0.0 and the registry at 2.0.0,
`cm-cli install <id>` installed 2.0.0. It now enables 1.0.0, with no download
(#3469, #3528). Where the folder of the newest disabled version is gone, it
enables the newest version whose folder is there.
A request to enable a disabled nodepack that the registry data does not list
was answered with success, and nothing was enabled. It is now answered with
400 and `Specified inactive node not exists: <id>`. The Custom Nodes Manager
shows such a nodepack as not installed and has no **Enable** for it, so the
page does not send this request.
### An install from a Git URL installs the dependencies when Windows cannot read `requirements.txt`
An install of a nodepack from a Git URL (**Install via Git URL**,
`cm-cli install <URL>`, `cm-cli install-deps`) read its `requirements.txt` in
the encoding of the locale, which on Windows is the ANSI code page. A UTF-8
file with a Chinese or Korean comment failed with `UnicodeDecodeError`, and
the nodepack was cloned without its dependencies (#3520). When the locale
cannot read the file, the install now reads it in the encoding that `chardet`
names, if every line is printable ASCII outside its comment. Otherwise, as
for a file that is not text or a requirement with a non-ASCII path, it fails
with the same error as before. Such a failure no longer installs the lines in
front of the byte it fails on.
### A nodepack that only the registry lists shows Update when the registry has a newer version
A nodepack that is in the registry and not in the node list never showed
**Update** in the Custom Nodes Manager, and the Update filter did not list it,
even when the registry had a newer version (#3220, #3261). The row showed
**Try update**, which did update it, but nothing said that an update was
there. The row of an enabled nodepack of this kind now shows **Update**, and
the Update filter lists it. A nodepack installed as nightly gets no **Update**
this way, as for a nodepack of the node list. When such a nodepack failed to
import and has a newer version, its row shows **Update** in place of
`IMPORT FAILED ↗` and **Try fix**, as the row of a nodepack of the node list
already did. The Import Failed filter still lists it.
### The log file has no color codes of the console
The Manager writes what ComfyUI prints to the console and to the log file,
`comfyui.log` in the user directory. The color codes of the console, such as
`ESC[32m`, went into the file as well, where an editor or `grep` shows them as
text (#3315). They are now left out of the file, and the console keeps its
colors. To keep them in the file as before, set
`strip_ansi_file_logging = false` in `config.ini`.
### The Node Usage Analyzer counts the nodes inside subgraphs, and Uninstall Selected uninstalls
The Node Usage Analyzer counted only the nodes at the top of a workflow, not
those inside a subgraph, and left out a workflow that had a `null` node. A
nodepack that was used only there showed 0 workflows and was offered for
uninstall. The nodes of every subgraph are now counted, and a workflow with
a malformed node is counted without that node (#3285). A node whose `cnr_id`
is not text stopped the whole count with
`TypeError: cnrId.toLowerCase is not a function`. Such a `cnr_id` is now left
out.
**Uninstall Selected** uninstalled nothing. The page said to restart ComfyUI,
and the uninstalls ran at the next Update All, where a nodepack that only the
registry lists failed with `An error occurred while uninstalling 'None'.` The
uninstalls now run at once. When the queue cannot be started, the page says
`Couldn't start the uninstall queue (HTTP <status>). Nothing was
uninstalled.`, and the uninstalls still run at the next Update All, as
before.
### The PyTorch restore after a nodepack installs the builds that were installed before
When a nodepack changed torch or torchvision and the torch from before had
no local label, Manager installed the newest releases, and through uv
nothing. For a torch with a label it installed the versions of a table that
ends at 2.7.0, or the newest nightly build. A nodepack that removed torch,
or removed torchvision and left torch as it was, ended the restore with
`Failed to restore PyTorch`.
Now Manager installs each of torch, torchvision and torchaudio that is not
the build it was before as that build, such as `torch===2.14.0+cu130` from
`https://download.pytorch.org/whl/cu130`. A torchvision or torchaudio whose
build cannot be had is replaced by one that fits that torch. A package that
this torch requires is installed again with it when another package wrote
over one of its files, as a torch of another CUDA version does with the
CUDA libraries. A last command resolves torch with torchvision and
torchaudio: what fits that torch stays, what does not is replaced, and a
dependency that the nodepack removed comes back.
Then Manager checks in a separate process that torch, torchvision and
torchaudio work. For a torch that does not, the packages it requires that
lack a file are installed again. A torchvision or torchaudio that does not
is installed again from torch's index. What still does not work is named in
an ERROR line. When the torch from before cannot be had, Manager restores
by its version table as before; the table now goes up to 2.15.0. With uv,
the command that installs torch, or a changed torchvision or torchaudio, at
its build is sent only in a form that a dry run resolved, and once more
when it fails while it installs. For safety the restore does not start when
the disk has less free space than it can take: twice the size of what it
installs again with pip, one and a half times with uv. pip runs without its
cache during the restore, so that it holds each wheel once.
### cm-cli reinstall keeps the version that is installed
`cm-cli reinstall <nodepack>` without a version removed the nodepack and
+10 -2
View File
@@ -441,7 +441,11 @@ def disable_node(node_spec_str: str, is_all=False, cnt_msg=''):
def show_list(kind, simple=False):
custom_nodes = asyncio.run(unified_manager.get_custom_nodes(channel=cmd_ctx.channel, mode=cmd_ctx.mode))
try:
custom_nodes = asyncio.run(unified_manager.get_custom_nodes(channel=cmd_ctx.channel, mode=cmd_ctx.mode))
except core.InvalidChannel as e:
print(f"ERROR: {e.reason}", style="bold red")
raise typer.Exit(code=1)
# collect not-installed unknown nodes
not_installed_unknown_nodes = []
@@ -1289,7 +1293,11 @@ def export_custom_node_ids(
for x in unified_manager.cnr_map.keys():
print(x, file=output_file)
custom_nodes = asyncio.run(unified_manager.get_custom_nodes(channel=cmd_ctx.channel, mode=cmd_ctx.mode))
try:
custom_nodes = asyncio.run(unified_manager.get_custom_nodes(channel=cmd_ctx.channel, mode=cmd_ctx.mode))
except core.InvalidChannel as e:
print(f"ERROR: {e.reason}", style="bold red")
raise typer.Exit(code=1)
for x in custom_nodes.values():
if 'cnr_latest' not in x:
if len(x['files']) == 1:
+167 -17
View File
@@ -31593,16 +31593,6 @@
"description": "Ambrosinus ToolKit - Streamlined workflow export with transparent backgrounds, professional themes, and smart scaling. Perfect for creating clean, high-resolution workflow documentation and sharing.",
"category": "Utils"
},
{
"author": "wasilone11",
"title": "ComfyUI Sync Lipsync Node",
"reference": "https://github.com/wasilone11/comfyui-sync-lipsync-node",
"files": [
"https://github.com/wasilone11/comfyui-sync-lipsync-node"
],
"install_type": "git-clone",
"description": "This custom node allows you to perform audio-video lip synchronization inside ComfyUI using a simple interface."
},
{
"author": "wasilone11",
"title": "ComfyUI Sync PVM Node",
@@ -57120,13 +57110,13 @@
},
{
"author": "alphaziod",
"title": "saya-comfy-couple-plus",
"reference": "https://github.com/alphaziod/saya-comfy-couple-plus",
"title": "Saya Couple",
"reference": "https://github.com/alphaziod/saya-studio-x-couple",
"files": [
"https://github.com/alphaziod/saya-comfy-couple-plus"
"https://github.com/alphaziod/saya-studio-x-couple"
],
"install_type": "git-clone",
"description": "Saya Comfy Couple+ is a modified Comfy Couple node for ComfyUI made for cleaner solo, duo, and dual-character workflows with better control over prompts, masks, and IPAdapter routing."
"description": "Separate MAIN scene / ACTION / P1 / P2 prompts for each character, in couple or solo mode, with no changes to the ComfyUI core."
},
{
"author": "andreyvagner74-art",
@@ -61417,6 +61407,26 @@
"install_type": "git-clone",
"description": "Extract reference frames from previously generated video to maintain visual consistency across sequential MiniMax H3 video generations"
},
{
"author": "BSAI",
"title": "BSAI-ComfyUI-H3-Film-Factory",
"reference": "https://github.com/xm6018924/BSAI-ComfyUI-H3-Film-Factory",
"files": [
"https://github.com/xm6018924/BSAI-ComfyUI-H3-Film-Factory"
],
"install_type": "git-clone",
"description": "Complete film production toolkit for MiniMax H3: asset library, storyboard clip management, subtitle rendering, media combining, and contextual frame extraction"
},
{
"author": "BSAI",
"title": "BSAI_Premiere_Pro",
"reference": "https://github.com/xm6018924/BSAI_Premiere_Pro",
"files": [
"https://github.com/xm6018924/BSAI_Premiere_Pro"
],
"install_type": "git-clone",
"description": "BSAI Premiere Pro - Timeline-based video editing node for ComfyUI with auto-import, transitions, trim, audio replacement, and ffmpeg merge"
},
{
"author": "Strix-3D",
"title": "ComfyUI-DLSS5-Enhancer-v15",
@@ -61902,6 +61912,28 @@
"install_type": "git-clone",
"description": "Generate Wan videos and retrieve task results. Requires an Ace Data Cloud API key. Generation is metered."
},
{
"author": "AceDataCloud",
"title": "ACE Music",
"id": "ace-acemusic",
"reference": "https://github.com/AceDataCloud/ACEMusicComfyUI",
"files": [
"https://github.com/AceDataCloud/ACEMusicComfyUI"
],
"install_type": "git-clone",
"description": "Generate ACE Music songs and lyrics, import reference assets, and retrieve results by task ID. Requires an Ace Data Cloud API key. Generation and reference imports are metered."
},
{
"author": "AceDataCloud",
"title": "GPT Image",
"id": "gpt-image",
"reference": "https://github.com/AceDataCloud/GPTImageComfyUI",
"files": [
"https://github.com/AceDataCloud/GPTImageComfyUI"
],
"install_type": "git-clone",
"description": "Generate and edit images with GPT Image, retrieve task results, and load the resulting images in ComfyUI. Requires an Ace Data Cloud API key. Generation and editing are metered."
},
{
"author": "NotUsingGithub",
"title": "Wan27",
@@ -62718,12 +62750,23 @@
"author": "haryai",
"title": "Seedance 2.5 (HaryAI)",
"id": "seedance-comfyui",
"reference": "https://github.com/sunsiyuan/seedance-comfyui",
"reference": "https://github.com/haryai-com/seedance-comfyui",
"files": [
"https://github.com/sunsiyuan/seedance-comfyui"
"https://github.com/haryai-com/seedance-comfyui"
],
"install_type": "git-clone",
"description": "Seedance 2.5 and Seedance 2.5 Flash video generation through the HaryAI API: text to video, first and last frame, reference images, sound. No BytePlus account needed."
"description": "Superseded by HaryAI (comfyui-haryai), which has the same nodes plus chat. Seedance 2.5 video and Seedream / Nano Banana images through the HaryAI API: text to video, first and last frame, reference images, videos and audio, draft mode, text to image and edits. Needs a HaryAI API key in the node's api_key field; requests go to api.haryai.com."
},
{
"author": "haryai",
"title": "HaryAI",
"id": "comfyui-haryai",
"reference": "https://github.com/haryai-com/comfyui-haryai",
"files": [
"https://github.com/haryai-com/comfyui-haryai"
],
"install_type": "git-clone",
"description": "Nodes for HaryAI's models: Seedance video (text to video, first and last frame, reference images, videos and audio, draft mode), Seedream and Nano Banana images (text to image and edits), and DeepSeek chat for writing video prompts and storyboards in a workflow. Billed to a HaryAI balance; needs a HaryAI API key in each node's api_key field (saved in the workflow); requests go to api.haryai.com."
},
{
"author": "zhulinyv",
@@ -62788,6 +62831,113 @@
"install_type": "git-clone",
"description": "Find misspelled text in photos and AI-generated images with Gemini, then use an image-editing workflow to fix localized text and review spelling and style. Includes check-only and SenseNova U1.6 examples."
},
{
"author": "Raykosan (RaykoStudio)",
"title": "ComfyUI-RS_WorkspaceManager",
"reference": "https://github.com/Raykosan/ComfyUI-RS_WorkspaceManager",
"files": [
"https://github.com/Raykosan/ComfyUI-RS_WorkspaceManager"
],
"install_type": "git-clone",
"description": "Workflow Preset Manager and Interface Settings Backup for ComfyUI."
},
{
"author": "assetfeed",
"title": "AssetFeed",
"reference": "https://github.com/assetfeed/comfyui-assetfeed",
"files": [
"https://github.com/assetfeed/comfyui-assetfeed"
],
"install_type": "git-clone",
"description": "Nodes for the AssetFeed API: AssetFeed OCR reads the text in an image, and AssetFeed AI Text Check estimates the AI-written share of an English text. Needs an ASSETFEED_API_KEY environment variable; images and text are sent to api.assetfeed.com; data handling is in the README."
},
{
"author": "Orange-3DV-Team",
"title": "MoBack-Turbo",
"id": "moback-turbo",
"reference": "https://github.com/Orange-3DV-Team/MoBack",
"files": [
"https://github.com/Orange-3DV-Team/MoBack"
],
"install_type": "git-clone",
"description": "End-to-end 4-step video background replacement with text (Task A), background image (Task B), or edited-keyframe (Task C) guidance based on Wan2.2 and Qwen3-VL (Linux/CUDA). Uses native VIDEO ports and supports resident, --offload-dit, and --low-vram (24 GB VRAM) modes."
},
{
"author": "Valentin Klein",
"title": "ValiTools",
"reference": "https://github.com/vangel76/comfyui-ValiTools",
"files": [
"https://github.com/vangel76/comfyui-ValiTools"
],
"install_type": "git-clone",
"description": "ValiTools node collection: VSmartPrompt (Dynamic Prompts with a rich-text editor, reusable variables, switcher conditions, chaining inputs and post-run selection highlighting), VFileRandom (no-repeat random image loader), VRandomSelector (lazy random passthrough of N same-type inputs) and VWaitForVRAM (hold execution until enough VRAM is free)."
},
{
"author": "kama0630-cmyk",
"title": "Krea 2 Studio Pack (Multi-Character & Factory)",
"id": "krea2-studio-pack",
"reference": "https://github.com/kama0630-cmyk/ComfyUI-Krea2-Studio-Pack",
"files": [
"https://github.com/kama0630-cmyk/ComfyUI-Krea2-Studio-Pack"
],
"install_type": "git-clone",
"description": "All-in-one ComfyUI custom nodes and workflows for Krea 2: Multi-Character Reference (Face/Outfit separation + Identity Edit V2), 4-Mode Character Factory, 4-Stage Fast Preview & Polish Studio Controllers, and non-destructive V2 RoPE runtime patch."
},
{
"author": "kama0630-cmyk",
"title": "SDXL Pro Studio (Fast Preview, Polish & Fooocus Controls)",
"id": "sdxl-pro-studio",
"reference": "https://github.com/kama0630-cmyk/ComfyUI-SDXL-Pro-Studio",
"files": [
"https://github.com/kama0630-cmyk/ComfyUI-SDXL-Pro-Studio"
],
"install_type": "git-clone",
"description": "All-in-one ComfyUI custom nodes and workflow for SDXL: 4-Stage Fast Preview & Polish Switch, 5-part selective SAM detailers, 1.5x refiner & quality finisher, and optional zero-overhead Fooocus 4-in-1 controls."
},
{
"author": "kama0630-cmyk",
"title": "FLUX Pro Studio (Fast Preview, Polish & Detail Daemon)",
"id": "flux-pro-studio",
"reference": "https://github.com/kama0630-cmyk/ComfyUI-FLUX-Pro-Studio",
"files": [
"https://github.com/kama0630-cmyk/ComfyUI-FLUX-Pro-Studio"
],
"install_type": "git-clone",
"description": "All-in-one ComfyUI custom nodes and workflows (safetensors & GGUF) for FLUX.1: 4-Stage Fast Preview & Polish Switch, 16-channel resolution presets, Flow-Matching Detail Daemon, 5-part selective SAM detailers, 1.5x refiner & quality finisher, and built-in VRAM cleanup."
},
{
"author": "kama0630-cmyk",
"title": "Z-Image Pro Studio (Fast Preview, Polish & Detail Daemon)",
"id": "z-image-pro-studio",
"reference": "https://github.com/kama0630-cmyk/ComfyUI-Z-Image-Pro-Studio",
"files": [
"https://github.com/kama0630-cmyk/ComfyUI-Z-Image-Pro-Studio"
],
"install_type": "git-clone",
"description": "All-in-one ComfyUI custom nodes and workflows (safetensors & GGUF) for Z-Image: 4-Stage Fast Preview & Polish Switch, 16-channel resolution presets, AuraFlow Flow-Matching Detail Daemon, 5-part selective SAM detailers, 1.5x refiner & quality finisher, and built-in VRAM cleanup."
},
{
"author": "kama0630-cmyk",
"title": "Wan 2.2 5B Video Studio (Auto-Ratio TI2V, FunControl & 3-Stage Polish)",
"id": "wan22-5b-video-studio",
"reference": "https://github.com/kama0630-cmyk/ComfyUI-Wan22-5B-Video-Studio",
"files": [
"https://github.com/kama0630-cmyk/ComfyUI-Wan22-5B-Video-Studio"
],
"install_type": "git-clone",
"description": "All-in-one ComfyUI custom nodes and unified workflow for Wan 2.2 5B: aspect-ratio auto-sizing (4n+1 frames), lazy Standard TI2V / FunControl mode router, temporal MKL color matching, 3-stage preview-to-2x-48fps polish pipeline, and SageAttention safe fallback."
},
{
"author": "GenMagic",
"title": "GenMagic (450+ AI Models: Image, Video, Speech, Music & Text)",
"id": "genmagic",
"reference": "https://github.com/yumaheymans/comfyui-genmagic",
"files": [
"https://github.com/yumaheymans/comfyui-genmagic"
],
"install_type": "git-clone",
"description": "Five ComfyUI nodes (GenMagicImage, GenMagicVideo, GenMagicSpeech, GenMagicMusic, GenMagicText) calling 450+ AI models (Veo 3.1, Seedance, Wan 3.0, Nano Banana, GPT Image, FLUX, Lyria 3, Claude, GPT) with one pay-as-you-go GENMAGIC_API_KEY. Supports image-to-image and image-to-video; requests are sent to genmagic.co/api/v1."
},
{
"author": "ntdviet",
"title": "ntdviet/comfyui-ext",
+10
View File
@@ -38,3 +38,13 @@ services:
options:
max-size: 1m
```
## aria2 on the same machine, without a container
The Manager asks aria2 to save a file into `/models/...` or `/custom_nodes`. The container above sees the `models` and `custom_nodes` folders of ComfyUI there, through its volumes.
An aria2 that runs on the same machine as ComfyUI, without a container, sees these folders where ComfyUI sees them. For it, set one more variable. The Manager then gives aria2 each folder as it is.
```bash
export COMFYUI_MANAGER_ARIA2_SAME_PATHS=true
```
+52 -20
View File
@@ -63,9 +63,10 @@ default_custom_nodes_path = None
class InvalidChannel(Exception):
def __init__(self, channel):
def __init__(self, channel, reason='The channel is not allowed. A channel has to be in `channels.list`.'):
self.channel = channel
super().__init__(channel)
self.reason = reason
super().__init__(reason)
def get_default_custom_nodes_path():
global default_custom_nodes_path
@@ -296,6 +297,13 @@ def normalize_channel(channel):
return normalize_channel_url(channel)
elif channel.startswith('http://') and get_config()['http_channel_enabled'] == True:
return channel
elif channel.startswith('\\\\') or os.path.isabs(channel):
network_mode = get_config()['network_mode']
if network_mode == 'private':
return channel
for name, url in get_channel_dict().items():
if url == channel:
raise InvalidChannel(channel, f"The channel '{name}' is a folder, and a folder is allowed as a channel only with `network_mode = private`. The current network_mode is `{network_mode}`.")
tmp_dict = get_channel_dict()
channel_url = tmp_dict.get(channel)
@@ -647,6 +655,12 @@ class UnifiedManager:
for folder in folders:
self.invalid_installations.pop(folder, None)
def forget_gone_disabled_versions_if_one_is_left(self, node_id):
disabled = self.cnr_inactive_nodes.get(node_id, {})
gone = [x for x in disabled.values() if not os.path.exists(x)]
if len(gone) < len(disabled):
self.forget_folders(gone)
def move_invalid_installation(self, from_path, to_path, enabled):
x = self.invalid_installations.pop(from_path, None)
if x is not None:
@@ -707,8 +721,12 @@ class UnifiedManager:
elif node_id in self.unknown_inactive_nodes:
return True
# cnr_inactive_nodes holds a version -> path dict; comparing the dict
# to version_spec (None here) is always False, so a disabled CNR pack
# looked active and enable never restored it. Any non-nightly inactive
# version counts, mirroring the explicit "cnr" branch above.
target = self.cnr_inactive_nodes.get(node_id, None)
if target is not None and target == version_spec:
if target and any(ver != 'nightly' for ver in target.keys()):
return True
return False
@@ -1073,7 +1091,7 @@ class UnifiedManager:
if version_spec is None:
version_spec = self.resolve_unspecified_version(node_id, guess_mode='inactive')
if version is None:
if version_spec is None and not self.is_enabled(node_id):
return result.fail(f'Specified inactive node not exists: {node_id}')
if self.is_enabled(node_id, version_spec):
@@ -1315,7 +1333,11 @@ class UnifiedManager:
if os.path.exists(install_path):
return result.fail(f'Install path already exists: {install_path}')
manager_downloader.download_url(node_info.download_url, get_default_custom_nodes_path(), archive_name)
try:
manager_downloader.download_url(node_info.download_url, get_default_custom_nodes_path(), archive_name)
except Exception:
manager_downloader.remove_failed_download(get_default_custom_nodes_path(), archive_name)
raise
os.makedirs(install_path, exist_ok=True)
try:
extracted = manager_util.extract_package_as_zip(download_path, install_path)
@@ -1510,7 +1532,7 @@ class UnifiedManager:
else:
return self.cnr_switch_version(node_id, instant_execution=instant_execution, no_deps=no_deps, return_postinstall=return_postinstall).with_ver('cnr')
async def install_by_id(self, node_id: str, version_spec=None, channel=None, mode=None, instant_execution=False, no_deps=False, return_postinstall=False):
async def install_by_id(self, node_id: str, version_spec=None, channel=None, mode=None, instant_execution=False, no_deps=False, return_postinstall=False, repo_url=None):
"""
priority if version_spec == None
1. CNR latest
@@ -1522,8 +1544,9 @@ class UnifiedManager:
if 'comfyui-manager' in node_id.lower():
return ManagedResult('skip').fail(f"ignored: installing '{node_id}'")
repo_url = None
if version_spec is None:
if node_id in self.cnr_map:
self.forget_gone_disabled_versions_if_one_is_left(node_id)
if self.is_enabled(node_id):
return ManagedResult('skip')
elif self.is_disabled(node_id):
@@ -1532,11 +1555,11 @@ class UnifiedManager:
else:
version_spec = self.resolve_unspecified_version(node_id)
if version_spec in ('unknown', 'nightly'):
if repo_url is None and version_spec in ('unknown', 'nightly'):
try:
repo_url = await self._get_git_install_url(node_id, version_spec, channel, mode)
except InvalidChannel as exc:
return ManagedResult('fail').fail(f'Invalid channel is used: {exc.channel}')
return ManagedResult('fail').fail(exc.reason)
except LookupError as exc:
return ManagedResult('install').fail(str(exc))
@@ -1587,9 +1610,13 @@ class UnifiedManager:
async def _get_git_install_url(self, node_id, version_spec, channel, mode):
custom_nodes = await self.get_custom_nodes(channel, mode)
node = custom_nodes.get(node_id)
if node is None:
raise LookupError(f"Node '{node_id}@{version_spec}' not found in [{channel}, {mode}]")
return node['files'][0] if version_spec == 'unknown' else node['repository']
if node is not None:
return node['files'][0] if version_spec == 'unknown' else node['repository']
if version_spec == 'nightly':
cnr = self.cnr_map.get(node_id)
if cnr is not None and cnr.get('repository'):
return cnr['repository']
raise LookupError(f"Node '{node_id}@{version_spec}' not found in [{channel}, {mode}]")
def _git_install_path(self, node_id):
return os.path.abspath(os.path.join(get_default_custom_nodes_path(), node_id))
@@ -1597,9 +1624,11 @@ class UnifiedManager:
def _install_git(self, node_id, version_spec, repo_url, instant_execution=False, no_deps=False, return_postinstall=False):
to_path = self._git_install_path(node_id)
replaced_version = None
if version_spec == 'nightly':
# disable cnr nodes
if self.is_enabled(node_id, 'cnr'):
replaced_version = self.get_cnr_active_version(node_id)
res = self.disable_for_replacement(node_id, to_path)
if not res.result:
return res
@@ -1612,6 +1641,8 @@ class UnifiedManager:
cnr_utils.generate_cnr_id(to_path, node_id)
self.active_nodes[node_id] = 'nightly', to_path
else:
if replaced_version is not None and not os.path.lexists(to_path):
self.unified_enable(node_id, replaced_version)
return res
return res.with_target(version_spec)
@@ -1625,7 +1656,7 @@ class UnifiedManager:
try:
repo_url = await self._get_git_install_url(node_id, version_spec, channel, mode)
except InvalidChannel as exc:
return ManagedResult('fail').fail(f'Invalid channel is used: {exc.channel}')
return ManagedResult('fail').fail(exc.reason)
except LookupError as exc:
return ManagedResult('install').fail(str(exc))
install_path = self._git_install_path(node_id)
@@ -2351,11 +2382,10 @@ def execute_install_script(url, repo_path, lazy_mode=False, instant_execution=Fa
if os.path.exists(requirements_path) and not no_deps:
print("Install: pip packages")
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, manager_files_path if manager_migration.has_system_user_api() else None)
with open(requirements_path, "r") as requirements_file:
for line in requirements_file:
install_args = manager_util.pip_install_args(line, cm_global.pip_overrides)
if install_args:
try_install_script(url, repo_path, manager_util.make_pip_cmd(["install", *install_args]), instant_execution=instant_execution)
for line in manager_util.read_requirements_lines(requirements_path):
install_args = manager_util.pip_install_args(line, cm_global.pip_overrides)
if install_args:
try_install_script(url, repo_path, manager_util.make_pip_cmd(["install", *install_args]), instant_execution=instant_execution)
pip_fixer.fix_broken()
if os.path.exists(install_script_path):
@@ -2480,7 +2510,7 @@ async def gitclone_install(url, instant_execution=False, msg_prefix='', no_deps=
cnr = unified_manager.get_cnr_by_repo(url)
if cnr:
cnr_id = cnr['id']
return await unified_manager.install_by_id(cnr_id, version_spec=None, channel='default', mode='cache')
return await unified_manager.install_by_id(cnr_id, version_spec='nightly', channel='default', mode='cache', instant_execution=instant_execution, no_deps=no_deps, repo_url=url)
else:
new_url, commit_id = extract_url_and_commit_id(url)
if commit_id != "":
@@ -3295,8 +3325,8 @@ async def get_unified_total_nodes(channel, mode, regsitry_cache_mode='cache'):
if cnr_id in unified_manager.active_nodes:
# installed
state = 'enabled'
updatable = unified_manager.is_updatable(cnr_id)
active_version = unified_manager.active_nodes[cnr['id']][0]
updatable = active_version != 'nightly' and unified_manager.is_updatable(cnr_id)
ver = active_version
if cm_global.try_call(api="cm.is_import_failed_extension", name=unified_manager.active_nodes[cnr_id][1]):
@@ -3319,6 +3349,8 @@ async def get_unified_total_nodes(channel, mode, regsitry_cache_mode='cache'):
item = dict(author=author, title=title, reference=reference, repository=repository, install_type=install_type,
description=description, state=state, updatable=updatable, version=ver)
item['update-state'] = 'true' if updatable else 'false'
if active_version:
item['active_version'] = active_version
+29 -6
View File
@@ -80,17 +80,26 @@ def aria2_download_url(model_url: str, model_dir: str, filename: str):
import tqdm
import time
if model_dir.startswith(core.comfy_path):
model_dir = model_dir[len(core.comfy_path) :]
local_path = os.path.join(model_dir, filename)
download_dir = model_dir if model_dir.startswith('/') else os.path.join('/models', model_dir)
same_paths = os.environ.get('COMFYUI_MANAGER_ARIA2_SAME_PATHS', '').lower() == 'true'
if not same_paths and model_dir.startswith(core.comfy_path):
rel = model_dir[len(core.comfy_path):]
download_dir = rel if rel.startswith('/') else os.path.join('/models', rel)
elif os.path.isabs(model_dir):
download_dir = model_dir
else:
download_dir = os.path.join('/models', model_dir)
download = aria2_find_task(download_dir, filename)
if download is None:
if download is None or not (download.is_active or download.is_waiting):
if os.path.exists(local_path) and not os.path.exists(local_path + '.aria2'):
return
options = {'dir': download_dir, 'out': filename}
download = aria2.add(model_url, options)[0]
if download.is_active:
if download.is_active or download.is_waiting:
with tqdm.tqdm(
total=download.total_length,
bar_format='{l_bar}{bar}{r_bar}',
@@ -98,13 +107,27 @@ def aria2_download_url(model_url: str, model_dir: str, filename: str):
unit='B',
unit_scale=True,
) as progress_bar:
while download.is_active:
while download.is_active or download.is_waiting:
if progress_bar.total == 0 and download.total_length != 0:
progress_bar.reset(download.total_length)
progress_bar.update(download.completed_length - progress_bar.n)
time.sleep(1)
download.update()
if not download.is_complete:
raise Exception(f"aria2 failed to download '{model_url}' into '{download_dir}': {download.error_message or download.status}")
if not os.path.exists(local_path):
raise Exception(f"aria2 saved '{filename}' into its '{download_dir}', but the file is not at '{local_path}'. "
"See docs/en/use_aria2.md for where aria2 must see the folders of ComfyUI.")
def remove_failed_download(model_dir: str, filename: str):
for name in (filename, filename + '.aria2'):
try:
os.remove(os.path.join(model_dir, name))
except OSError:
pass
def download_url_with_agent(url, save_path):
try:
+102 -33
View File
@@ -735,7 +735,7 @@ async def fetch_customnode_mappings(request):
"""
provide unified (node -> node pack) mapping list
"""
mode = request.rel_url.query["mode"]
mode = request.rel_url.query.get("mode", "cache")
nickname_mode = False
if mode == "nickname":
@@ -781,6 +781,75 @@ async def fetch_updates(request):
status=410,
)
def collect_node_types_in_graph(graph, subgraph_definitions, node_set, workflow_file_path, visited_subgraph_ids):
"""
collect the node type info of a single graph (the root workflow, or a subgraph definition)
into node_set, recursing into any subgraph that the graph instantiates
"""
# a subgraph definition can carry its own nested definitions - register them before walking the nodes
nested_definitions = graph.get("definitions")
if isinstance(nested_definitions, dict):
nested_subgraphs = nested_definitions.get("subgraphs")
if isinstance(nested_subgraphs, list):
for subgraph in nested_subgraphs:
if isinstance(subgraph, dict) and "id" in subgraph:
subgraph_definitions.setdefault(subgraph["id"], subgraph)
nodes = graph.get("nodes")
if not isinstance(nodes, list):
logging.warning(f"{workflow_file_path} has a malformed 'nodes' value - skipping this graph")
return
for node in nodes:
# a malformed entry shouldn't take the whole workflow down with it
if not isinstance(node, dict):
logging.warning(f"Found a non-object node in {workflow_file_path} - skipping it")
continue
if "id" not in node:
logging.warning("Found a node with no ID - possibly corrupt/invalid workflow?")
continue
# if there's no type, throw a warning
if "type" not in node:
logging.warning(f"Node type not found in {workflow_file_path} for node ID {node['id']}")
# skip to next node
continue
node_type = node["type"]
# an unhashable type (list/dict) would blow up the subgraph lookup below, and any
# non-string is junk in the report either way
if not isinstance(node_type, str):
logging.warning(f"Node {node['id']} has a non-string type in {workflow_file_path} - skipping it")
continue
# a node whose type is a subgraph id is an instance of that subgraph, not a real node type:
# descend into the definition instead of reporting the (meaningless) subgraph uuid
if node_type in subgraph_definitions:
# guard against a subgraph that (directly or indirectly) instantiates itself
if node_type not in visited_subgraph_ids:
visited_subgraph_ids.add(node_type)
collect_node_types_in_graph(subgraph_definitions[node_type], subgraph_definitions, node_set,
workflow_file_path, visited_subgraph_ids)
continue
node_data_to_return = {"type": node_type}
properties = node.get("properties")
if not isinstance(properties, dict):
logging.warning(f"Node {node['id']} has no properties field - can't determine cnr_id")
else:
for property_key in ["cnr_id", "ver"]:
if property_key in properties:
# a non-string cnr_id reaches findPackageByCnrId on the client, where
# cnrId.toLowerCase() throws and takes the whole usage analysis with it
if property_key == "cnr_id" and not isinstance(properties[property_key], str):
logging.warning(f"Node {node['id']} has a non-string cnr_id in {workflow_file_path} - ignoring it")
continue
node_data_to_return[property_key] = properties[property_key]
# add it to the list for this workflow
if not node_data_to_return in node_set:
node_set.append(node_data_to_return)
@routes.get("/customnode/get_node_types_in_workflows")
async def get_node_types_in_workflows(request):
try:
@@ -796,7 +865,7 @@ async def get_node_types_in_workflows(request):
if not os.path.isdir(workflow_files_base_path):
logging.debug("workflows base path doesn't exist - nothing to do...")
return web.Response(status=204)
# get all JSON files under the workflow directory
workflow_file_relative_paths: list[str] = glob.glob(pathname="**/*.json", root_dir=workflow_files_base_path, recursive=True)
@@ -812,7 +881,8 @@ async def get_node_types_in_workflows(request):
workflow_file_absolute_path = os.path.abspath(os.path.join(workflow_files_base_path, workflow_file_path))
logging.debug(f"starting work on {workflow_file_absolute_path}")
# load the JSON file
workflow_file_data = json.load(open(workflow_file_absolute_path, "r", encoding="utf-8-sig"))
with open(workflow_file_absolute_path, "r", encoding="utf-8-sig") as workflow_file:
workflow_file_data = json.load(workflow_file)
# make sure there's a nodes key (otherwise this might not actually be a workflow file)
if "nodes" not in workflow_file_data:
@@ -825,38 +895,26 @@ async def get_node_types_in_workflows(request):
# we can't use an actual set, because you can't use dicts as set members
node_set = []
# iterate over each node in the workflow
for node in workflow_file_data["nodes"]:
if "id" not in node:
logging.warning("Found a node with no ID - possibly corrupt/invalid workflow?")
continue
# if there's no type, throw a warning
if "type" not in node:
logging.warning(f"Node type not found in {workflow_file_path} for node ID {node['id']}")
# skip to next node
continue
# subgraph definitions are stored flat at the root of the workflow, keyed by their uuid;
# nodes inside them never appear in the root "nodes" list, so they have to be walked separately
subgraph_definitions = {}
definitions = workflow_file_data.get("definitions")
if isinstance(definitions, dict):
for subgraph in definitions.get("subgraphs", []):
if isinstance(subgraph, dict) and "id" in subgraph:
subgraph_definitions[subgraph["id"]] = subgraph
node_data_to_return = {"type": node["type"]}
if "properties" not in node:
logging.warning(f"Node ${node['id']} has no properties field - can't determine cnr_id")
else:
for property_key in ["cnr_id", "ver"]:
if property_key in node["properties"]:
node_data_to_return[property_key] = node["properties"][property_key]
# add it to the list for this workflow
if not node_data_to_return in node_set:
node_set.append(node_data_to_return)
collect_node_types_in_graph(workflow_file_data, subgraph_definitions, node_set,
workflow_file_path, set())
# annoyingly, Python can't serialize sets to JSON
new_mapping["node_types"] = list(node_set)
workflow_node_mappings.append(new_mapping)
workflow_node_mappings.append(new_mapping)
except Exception as e:
logging.warning(f"Couldn't open {workflow_file_path}: {e}")
return web.json_response(workflow_node_mappings, content_type='application/json')
except:
traceback.print_exc()
return web.Response(status=500)
@@ -1067,14 +1125,20 @@ async def fetch_customnode_list(request):
"""
provide unified custom node list
"""
if request.rel_url.query["mode"] == "local":
mode = request.rel_url.query.get("mode", "cache")
if mode == "local":
channel = 'local'
else:
channel = core.get_config()['channel_url']
node_packs = await core.get_unified_total_nodes(channel, request.rel_url.query["mode"], 'cache')
json_obj_github = core.get_data_by_mode(request.rel_url.query["mode"], 'github-stats.json', 'default')
json_obj_extras = core.get_data_by_mode(request.rel_url.query["mode"], 'extras.json', 'default')
try:
node_packs = await core.get_unified_total_nodes(channel, mode, 'cache')
except core.InvalidChannel as e:
logging.warning(f"[ComfyUI-Manager] {e.reason}")
return web.Response(status=403, text=e.reason)
json_obj_github = core.get_data_by_mode(mode, 'github-stats.json', 'default')
json_obj_extras = core.get_data_by_mode(mode, 'extras.json', 'default')
core.populate_github_stats(node_packs, await json_obj_github)
core.populate_favorites(node_packs, await json_obj_extras)
@@ -1145,8 +1209,10 @@ def check_model_installed(json_obj):
filename = item['filename']
fullpath = os.path.join(folder_paths.models_dir, item['save_path'], filename)
subpath = os.path.join(item['save_path'].partition('/')[2], filename)
found = os.path.exists(fullpath) or folder_paths.get_full_path(model_dir_name, subpath)
item['installed'] = 'True' if os.path.exists(fullpath) else 'False'
item['installed'] = 'True' if found else 'False'
with concurrent.futures.ThreadPoolExecutor(8) as executor:
for item in json_obj['models']:
@@ -1156,7 +1222,7 @@ def check_model_installed(json_obj):
@routes.get("/externalmodel/getlist")
async def fetch_externalmodel_list(request):
# The model list is only allowed in the default channel, yet.
json_obj = await core.get_data_by_mode(request.rel_url.query["mode"], 'model-list.json')
json_obj = await core.get_data_by_mode(request.rel_url.query.get("mode", "cache"), 'model-list.json')
check_model_installed(json_obj)
@@ -2171,7 +2237,10 @@ async def default_cache_update():
else:
# load at least once
await core.unified_manager.reload('remote', dont_wait=False)
await core.unified_manager.get_custom_nodes(channel_url, 'remote')
try:
await core.unified_manager.get_custom_nodes(channel_url, 'remote')
except core.InvalidChannel as e:
logging.warning(f"[ComfyUI-Manager] {e.reason}")
else:
await core.unified_manager.reload('remote', dont_wait=False, update_cnr_map=False)
+402 -12
View File
@@ -2,6 +2,8 @@
description:
`manager_util` is the lightest module shared across the prestartup_script, main code, and cm-cli of ComfyUI-Manager.
"""
import csv
import sysconfig
import importlib.metadata
import traceback
import ipaddress
@@ -9,14 +11,17 @@ import socket
import aiohttp
import json
import math
import threading
import os
import shutil
import contextlib
from datetime import datetime
import subprocess
import tempfile
import sys
import re
import codecs
import logging
import platform
import shlex
@@ -1091,9 +1096,21 @@ def parse_requirement_line(line):
torch_torchvision_torchaudio_version_map = {
'2.15.0': ('0.29.2', '2.11.*'),
'2.14.1': ('0.29.1', '2.11.*'),
'2.14.0': ('0.29.0', '2.11.*'),
'2.13.0': ('0.28.0', '2.11.*'),
'2.12.1': ('0.27.1', '2.11.*'),
'2.12.0': ('0.27.0', '2.11.*'),
'2.11.0': ('0.26.0', '2.11.*'),
'2.10.0': ('0.25.0', '2.10.0'),
'2.9.1': ('0.24.1', '2.9.1'),
'2.9.0': ('0.24.0', '2.9.0'),
'2.8.0': ('0.23.0', '2.8.0'),
'2.7.1': ('0.22.1', '2.7.1'),
'2.7.0': ('0.22.0', '2.7.0'),
'2.6.0': ('0.21.0', '2.6.0'),
'2.5.1': ('0.20.0', '2.5.0'),
'2.5.1': ('0.20.1', '2.5.1'),
'2.5.0': ('0.20.0', '2.5.0'),
'2.4.1': ('0.19.1', '2.4.1'),
'2.4.0': ('0.19.0', '2.4.0'),
@@ -1105,19 +1122,19 @@ torch_torchvision_torchaudio_version_map = {
'2.1.2': ('0.16.2', '2.1.2'),
'2.1.1': ('0.16.1', '2.1.1'),
'2.1.0': ('0.16.0', '2.1.0'),
'2.0.1': ('0.15.2', '2.0.1'),
'2.0.1': ('0.15.2', '2.0.2'),
'2.0.0': ('0.15.1', '2.0.0'),
}
def torch_rollback(prev, packages):
def torch_rollback_by_version_table(prev, packages, options=()):
spec = prev.split('+')
if len(spec) > 1:
platform = spec[1]
else:
cmd = make_pip_cmd(['install', '--force', *packages])
cmd = make_pip_cmd(['install', '--force', *packages, *options])
logging.info("[ComfyUI-Manager] restore PyTorch to the newest release")
subprocess.check_output(cmd, universal_newlines=True)
logging.error(cmd)
return
torch_ver = StrictVersion(spec[0])
@@ -1126,21 +1143,349 @@ def torch_rollback(prev, packages):
if torch_torchvision_torchaudio_ver is None:
cmd = make_pip_cmd(['install', '--pre', *packages,
'--index-url', f"https://download.pytorch.org/whl/nightly/{platform}"])
'--index-url', f"https://download.pytorch.org/whl/nightly/{platform}", *options])
logging.info("[ComfyUI-Manager] restore PyTorch to nightly version")
else:
torchvision_ver, torchaudio_ver = torch_torchvision_torchaudio_ver
versions = {'torch': torch_ver, 'torchvision': torchvision_ver, 'torchaudio': torchaudio_ver}
cmd = make_pip_cmd(['install', *[f'{name}=={versions[name]}' for name in packages],
'--index-url', f"https://download.pytorch.org/whl/{platform}"])
'--index-url', f"https://download.pytorch.org/whl/{platform}", *options])
logging.info(f"[ComfyUI-Manager] restore PyTorch to {torch_ver}+{platform}")
subprocess.check_output(cmd, universal_newlines=True)
def _pytorch_index(build, option):
from packaging.version import Version
version = Version(build)
if version.is_devrelease:
return ['--pre', option, f"https://download.pytorch.org/whl/nightly/{version.local or 'cpu'}"]
if version.local is not None:
return [option, f"https://download.pytorch.org/whl/{version.local}"]
return []
def _installed_version(name):
try:
return importlib.metadata.version(name)
except importlib.metadata.PackageNotFoundError:
return None
def _recorded_files(name):
try:
distribution = importlib.metadata.distribution(name)
except importlib.metadata.PackageNotFoundError:
return []
# From the RECORD itself: files() leaves out the missing ones from Python 3.12 on
return [(distribution.locate_file(row[0]), int(row[2]))
for row in csv.reader((distribution.read_text('RECORD') or '').splitlines()) if len(row) == 3 and row[2]]
def _required_here(name, extras=frozenset()):
from packaging.requirements import InvalidRequirement, Requirement
found = []
for line in importlib.metadata.requires(name) or []:
try:
requirement = Requirement(line)
except InvalidRequirement:
continue
if requirement.marker is None or any(requirement.marker.evaluate({'extra': extra}) for extra in {*extras, ''}):
found.append((normalize_pip_name(requirement.name), set(requirement.extras)))
return found
def _size_of_pytorch():
extras, todo = {}, [(name, set()) for name in ('torch', 'torchvision', 'torchaudio')]
while todo:
name, wanted = todo.pop()
if _installed_version(name) is None or name in extras and wanted <= extras[name]:
continue
extras[name] = extras.get(name, set()) | wanted
todo += _required_here(name, extras[name])
return {name: sum(size for _, size in _recorded_files(name)) for name in extras}
def _space_to_restore(installed_before, installed_after, overwritten, size_of_pytorch, times_the_size):
return int(times_the_size * sum(size for name, size in size_of_pytorch.items()
if installed_after.get(name) != installed_before.get(name) or name in overwritten))
def _overwritten(installed_before, installed_after, required_by_torch):
# cuDNN, cuSPARSELt, NCCL and NVSHMEM ship one distribution per CUDA version, all writing the same file paths.
return {name: installed_after[name] for name in sorted(required_by_torch)
if name in installed_after and installed_before.get(name) == installed_after[name]
and any(os.path.isfile(file) and os.path.getsize(file) != size for file, size in _recorded_files(name))}
def _incomplete(required_by_torch):
return {name: _installed_version(name) for name in sorted(required_by_torch)
if any(not os.path.isfile(file) for file, _ in _recorded_files(name))}
# The metadata of a torchvision or torchaudio can fit torch while its native library does not load beside it: a build
# for another CUDA version, or the PyPI build beside a CPU torch. torch imports beside a cuDNN older than the one it
# was built for; cudnn.version() compares the two without a GPU, and a CPU build has none to compare.
_PYTORCH_CHECKS = {
'torch': 'import torch; torch.backends.cudnn.version()',
'torchvision': 'import torch, torchvision; torchvision.ops.nms(torch.rand(3, 4) * 10, torch.rand(3), 0.5)',
'torchaudio': 'import torch, torchaudio.functional as F; F.lowpass_biquad(torch.rand(1, 100), 16000, 300.0)',
}
_CHECK_TIME_LIMIT = 300
# A .pth file or a module can print to the same stdout when Python starts, and can leave its line without an end.
_CHECK_LINE = '[ComfyUI-Manager] PyTorch check:'
_CHECK_DID_NOT_RUN = None
def _not_working(names):
code = f"print({_CHECK_LINE!r}, flush=True)\n" + ''.join(
f"try:\n {_PYTORCH_CHECKS[name]}\n print({f'{_CHECK_LINE} {name}'!r}, flush=True)\nexcept Exception:\n"
f" pass\n" for name in names)
try:
printed = subprocess.run([sys.executable, '-c', code], capture_output=True, text=True,
timeout=_CHECK_TIME_LIMIT).stdout.splitlines()
except subprocess.TimeoutExpired:
return _CHECK_DID_NOT_RUN
def told(line):
return any(found.endswith(line) for found in printed)
if not told(_CHECK_LINE):
return _CHECK_DID_NOT_RUN
return [name for name in names if not told(f'{_CHECK_LINE} {name}')]
class _Pip:
# Measured: pip holds a wheel in its temporary folder while it writes the files, at the peak 1.7 times the size of
# the files. With its cache it holds the wheel there too, at the peak 2.35 times for a CUDA torch for Windows.
times_the_size = 2
@contextlib.contextmanager
def environment(self):
before = os.environ.get('PIP_NO_CACHE_DIR')
os.environ['PIP_NO_CACHE_DIR'] = '1'
try:
yield
finally:
if before is None:
del os.environ['PIP_NO_CACHE_DIR']
else:
os.environ['PIP_NO_CACHE_DIR'] = before
def install(self, name, build, *options):
command = make_pip_cmd(['install', *options, f'{name}==={build}', *_pytorch_index(build, '--extra-index-url')])
try:
subprocess.check_output(command, universal_newlines=True)
except subprocess.CalledProcessError:
return False
return True
@contextlib.contextmanager
def putting_back(self, overwritten, torch):
# pip installs no distribution of a command again without all the others.
pins = [f'{name}=={version}' for name, version in overwritten.items()]
with tempfile.TemporaryDirectory() as wheels:
if pins:
try:
subprocess.check_output(make_pip_cmd(['download', '--no-deps', '-d', wheels, *pins,
*_pytorch_index(torch, '--extra-index-url')]),
universal_newlines=True)
except subprocess.CalledProcessError:
raise RuntimeError(f"{', '.join(pins)} cannot be had")
yield []
left = [f'{name}=={version}' for name, version in overwritten.items()
if _installed_version(name) == version]
if left:
subprocess.check_output(make_pip_cmd(['install', '--no-deps', '--force-reinstall', '--no-index',
'--find-links', wheels, *left]), universal_newlines=True)
def own_index(self, torch):
return _pytorch_index(torch, '--index-url')
def install_again(self, broken, requirements, torch):
# pip joins PIP_EXTRA_INDEX_URL to an index and takes the highest version of all, which can be a build for
# another CUDA version.
index = _pytorch_index(torch, '--find-links')
if index:
*pre, _, url = index
index = [*pre, '--no-index', *[option for name in broken for option in ('--find-links', f'{url}/{name}/')]]
subprocess.check_output(make_pip_cmd(['install', '--force-reinstall', '--no-deps',
*[requirements[name] for name in broken], *index]),
universal_newlines=True)
def install_files_again(self, name, version, torch):
subprocess.check_output(make_pip_cmd(['install', '--force-reinstall', '--no-deps', f'{name}=={version}',
*_pytorch_index(torch, '--extra-index-url')]), universal_newlines=True)
class _Uv:
# Measured: uv unpacks a wheel into its cache and links the files from there, at the peak 1.06 times the size of
# the files. Where it copies them, it removes the old build first.
times_the_size = 1.5
def __init__(self):
from packaging.version import Version
# uv's version line can follow what Python prints as it starts.
try:
printed = subprocess.check_output([*make_pip_cmd([])[:-1], '--version'], universal_newlines=True)
except subprocess.CalledProcessError:
printed = ''
version = re.search(r'^uv (\d+(\.\d+)*)', printed, re.MULTILINE)
self.reads_index = version is not None and Version(version[1]) >= Version('0.4.23')
def environment(self):
return contextlib.nullcontext()
def install(self, name, build, *options):
# uv does not put back what it removed when a command fails while it installs, and an install command sent
# after it can lay the new build over what is left and report it as installed. uv ends a command when it
# cannot reach an index that the command names. A --extra-index-url of the command takes the place of
# UV_EXTRA_INDEX_URL.
index = _pytorch_index(build, '--extra-index-url')
command = make_pip_cmd(['install', *options, f'{name}==={build}', *index])
forms = [command, [*command, '--offline']]
if index:
forms.append([*make_pip_cmd(['install', *options, f'{name}==={build}', *index[:-2]]), '--offline'])
for form in forms:
try:
subprocess.check_output([*form, '--dry-run'], universal_newlines=True, stderr=subprocess.PIPE)
except subprocess.CalledProcessError as e:
if form is command:
reason = '\n'.join(line for line in e.stderr.strip().splitlines()
if not line.startswith('Using Python '))
continue
if form is not command:
logging.info("[ComfyUI-Manager] restore PyTorch: the command does not resolve with its indexes, "
"installing from uv's cache alone")
try:
subprocess.check_output(form, universal_newlines=True)
except subprocess.CalledProcessError:
logging.warning(f"[ComfyUI-Manager] restore PyTorch: installing {name} {build} failed, "
f"sending it once more")
subprocess.check_output([*form, '--reinstall-package', name], universal_newlines=True)
return True
logging.warning(f"[ComfyUI-Manager] restore PyTorch: uv does not resolve the command: {reason}")
return False
def putting_back(self, overwritten, torch):
return contextlib.nullcontext([option for name in overwritten for option in ('--reinstall-package', name)])
def own_index(self, torch):
# uv reads --index before UV_INDEX, UV_EXTRA_INDEX_URL and the default index, and a --index of the command
# takes the place of UV_INDEX.
index = _pytorch_index(torch, '--index-url')
return [*index, '--index' if self.reads_index else '--extra-index-url', index[-1]] if index else []
def install_again(self, broken, requirements, torch):
again = [option for name in broken for option in ('--reinstall-package', name)]
subprocess.check_output(make_pip_cmd(['install', *requirements.values(), *self.own_index(torch), *again]),
universal_newlines=True)
def install_files_again(self, name, version, torch):
subprocess.check_output(make_pip_cmd(['install', '--no-deps', f'{name}=={version}',
*_pytorch_index(torch, '--extra-index-url'),
'--reinstall-package', name]), universal_newlines=True)
def _report_not_working(names):
if names is _CHECK_DID_NOT_RUN:
logging.warning("[ComfyUI-Manager] restore PyTorch: the check of what works did not run")
elif names:
logging.error(f"[ComfyUI-Manager] restore PyTorch: does not work after the restore: "
f"{', '.join(f'{name} {_installed_version(name)}' for name in names)}")
def torch_rollback(installed_before, installed_after, required_by_torch, size_of_pytorch):
from packaging.version import Version
tool = _Uv() if 'uv' in make_pip_cmd([]) else _Pip()
torch = installed_before['torch']
packages = [name for name in ('torch', 'torchvision', 'torchaudio')
if name in installed_before or name in installed_after]
changed = {name: installed_before[name] for name in ('torch', 'torchvision', 'torchaudio')
if name in installed_before and installed_after.get(name) != installed_before[name]}
logging.info(f"[ComfyUI-Manager] restore PyTorch: {', '.join(f'{name} {build}' for name, build in changed.items())}")
companions = {name: build for name, build in changed.items() if name != 'torch'}
overwritten = _overwritten(installed_before, installed_after, required_by_torch)
needed = _space_to_restore(installed_before, installed_after, overwritten, size_of_pytorch, tool.times_the_size)
free = shutil.disk_usage(sysconfig.get_path('purelib')).free
if free < needed:
raise RuntimeError(f"for safety the restore does not start: it can take {math.ceil(needed / 10 ** 6)} MB on "
f"the disk of the Python environment, where {free // 10 ** 6} MB are free")
with tool.environment():
if 'torch' in changed or overwritten:
with tool.putting_back(overwritten, torch) as options:
torch_installed = tool.install('torch', torch, *options)
if not torch_installed:
logging.warning(f"[ComfyUI-Manager] restore PyTorch: torch {torch} cannot be had, "
f"restoring by the version table instead")
torch_rollback_by_version_table(torch, packages, options)
if not torch_installed:
_report_not_working(_not_working(packages))
return
for name, build in companions.items():
if not tool.install(name, build, '--no-deps'):
logging.warning(f"[ComfyUI-Manager] restore PyTorch: {name} {build} cannot be had, "
f"installing a {name} that fits torch {torch} instead")
# torchaudio 2.11.0 declares no requirement on torch, so without a bound the resolver takes it beside an older
# torch. The bound is the next minor version of torch, as a patch release of torchaudio can be newer than its
# torch: 2.0.2 goes with 2.0.1.
version = Version(torch)
requirement = {'torch': f'torch==={torch}', 'torchvision': 'torchvision',
'torchaudio': f'torchaudio<{version.major}.{version.minor + 1}'}
requirements = {name: requirement[name] for name in packages}
try:
subprocess.check_output(make_pip_cmd(['install', *requirements.values(), *tool.own_index(torch)]),
universal_newlines=True)
except subprocess.CalledProcessError as e:
logging.warning(f"[ComfyUI-Manager] restore PyTorch: the whole set failed to install, checking what "
f"works: {e}")
broken = _not_working(packages)
if broken and 'torch' in broken:
# An uninstall takes the files that two distributions share.
incomplete = _incomplete(required_by_torch)
for name, version in incomplete.items():
try:
tool.install_files_again(name, version, torch)
except subprocess.CalledProcessError:
pass
if incomplete:
broken = _not_working(packages)
if broken and 'torch' not in broken:
torchvision = _installed_version('torchvision')
if 'torchvision' in broken and torchvision is not None:
requirements['torchvision'] = f"torchvision=={Version(torchvision).public}"
try:
tool.install_again(broken, requirements, torch)
except subprocess.CalledProcessError:
pass
broken = _not_working(packages)
_report_not_working(broken)
class PIPFixer:
def __init__(self, prev_pip_versions, comfyui_path, manager_files_path):
self.prev_pip_versions = { **prev_pip_versions }
self.required_by_torch, self.size_of_pytorch = set(), {}
torch = prev_pip_versions.get('torch')
try:
list_names_the_installed_torch = torch is not None and _installed_version('torch') == torch
if list_names_the_installed_torch:
self.required_by_torch, self.size_of_pytorch = ({name for name, _ in _required_here('torch')},
_size_of_pytorch())
except Exception as e:
logging.warning(f"[ComfyUI-Manager] restore PyTorch: what torch requires could not be read, "
f"a restore will put no library back: {e!r}")
self.comfyui_path = comfyui_path
self.manager_files_path = manager_files_path
@@ -1162,11 +1507,10 @@ class PIPFixer:
try:
if 'torch' not in self.prev_pip_versions or 'torchvision' not in self.prev_pip_versions:
logging.error("[ComfyUI-Manager] PyTorch is not installed")
elif self.prev_pip_versions['torch'] != new_pip_versions['torch'] \
or self.prev_pip_versions['torchvision'] != new_pip_versions['torchvision']:
packages = [name for name in ('torch', 'torchvision', 'torchaudio')
if name in self.prev_pip_versions or name in new_pip_versions]
torch_rollback(self.prev_pip_versions['torch'], packages)
elif any(self.prev_pip_versions[name] != new_pip_versions.get(name) for name in ('torch', 'torchvision')):
clear_pip_cache()
torch_rollback(self.prev_pip_versions, new_pip_versions, self.required_by_torch,
self.size_of_pytorch)
except Exception as e:
logging.error("[ComfyUI-Manager] Failed to restore PyTorch")
logging.error(e)
@@ -1302,6 +1646,52 @@ def robust_readlines(fullpath):
return []
_PRINTABLE_ASCII = re.compile(r'[\t-\r -~]*')
_PRINTABLE_ASCII_BYTES = bytes(range(0x09, 0x0e)) + bytes(range(0x20, 0x7f))
_WIDE_UNICODE_CODECS = ('utf-16', 'utf-16-le', 'utf-16-be', 'utf-32', 'utf-32-le', 'utf-32-be')
def _is_ascii_compatible_or_wide_unicode(encoding):
try:
codec = codecs.lookup(encoding)
if codec.name in _WIDE_UNICODE_CODECS:
return True
return codec.decode(_PRINTABLE_ASCII_BYTES)[0] == _PRINTABLE_ASCII_BYTES.decode('ascii')
except (LookupError, UnicodeDecodeError):
return False
def _hands_pip_only_ascii(line):
before_comment = _PIP_COMMENT_PATTERN.sub('', line)
return before_comment.isspace() or _PRINTABLE_ASCII.fullmatch(before_comment) is not None
def read_requirements_lines(fullpath):
try:
with open(fullpath, "r") as f:
return f.readlines()
except UnicodeDecodeError:
import chardet
with open(fullpath, "rb") as f:
encoding = chardet.detect(f.read())['encoding']
lines = None
if encoding is not None and _is_ascii_compatible_or_wide_unicode(encoding):
try:
with open(fullpath, "r", encoding=encoding) as f:
lines = f.readlines()
except UnicodeDecodeError:
pass
if lines:
# chardet 7.1.0 names UTF-16-LE for a UTF-16 file with a byte order mark, which then stays in the text
lines[0] = lines[0].lstrip('\ufeff')
if lines is None or not all(_hands_pip_only_ascii(line) for line in lines):
raise
return lines
def build_restart_command(argv, drop_args=()):
"""
Rebuild the command line used to re-exec the current ComfyUI process.
+15 -3
View File
@@ -448,7 +448,8 @@ export async function fetchData(route, options) {
if (status !== 200) {
return {
status,
error: new Error(statusText || "Unknown Error")
error: new Error(statusText || "Unknown Error"),
detail: await res.text().catch(() => "")
}
}
@@ -732,7 +733,7 @@ export async function uninstallNodes(nodeList, options = {}) {
let errorMsg = "";
let target_items = [];
await api.fetchApi('/manager/queue/reset');
await api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
for (const nodeItem of nodeList) {
target_items.push(nodeItem);
@@ -770,7 +771,18 @@ export async function uninstallNodes(nodeList, options = {}) {
show_message("[Uninstall Errors]\n" + errorMsg);
return { success: false, error: errorMsg, targets: target_items };
} else {
await api.fetchApi('/manager/queue/start');
// the queue endpoints are POST-only - a GET here silently fails to start the
// worker, leaving every queued uninstall sitting untouched in the queue
// 200 = worker started, 201 = a worker was already running and will pick up
// the items just queued - both mean the uninstall is under way
const startRes = await api.fetchApi('/manager/queue/start', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
if (startRes.status !== 200 && startRes.status !== 201) {
errorMsg = `Couldn't start the uninstall queue (HTTP ${startRes.status}). Nothing was uninstalled.\n`;
onError(errorMsg);
show_message("[Uninstall Errors]\n" + errorMsg);
return { success: false, error: errorMsg, targets: target_items };
}
onSuccess(target_items);
showTerminal();
return { success: true, targets: target_items };
+1
View File
@@ -218,6 +218,7 @@
.cn-manager-grid .cn-pack-conflicts {
color: orange;
white-space: normal;
}
.cn-popover {
+55 -11
View File
@@ -21,6 +21,25 @@ const gridId = "node";
const INVALID_INSTALLATION_GUIDANCE = "This nodepack was not installed through ComfyUI-Manager, or its installation is damaged, so the Manager cannot update it. Reinstalling deletes its folder and installs the nodepack again.";
// Compare dot-separated numeric version specs. Returns 1 if a > b, -1 if a < b,
// 0 if equal, or null when either spec is not fully numeric (e.g. "nightly",
// "1.2.3rc1").
function compareVersionSpecs(a, b) {
const pa = String(a).split(".").map((x) => /^\d+$/.test(x) ? parseInt(x, 10) : NaN);
const pb = String(b).split(".").map((x) => /^\d+$/.test(x) ? parseInt(x, 10) : NaN);
if (pa.some(Number.isNaN) || pb.some(Number.isNaN)) {
return null;
}
const len = Math.max(pa.length, pb.length);
for (let i = 0; i < len; i++) {
const x = pa[i] || 0;
const y = pb[i] || 0;
if (x > y) return 1;
if (x < y) return -1;
}
return 0;
}
const pageHtml = `
<div class="cn-manager cn-manager-dark">
<div class="cn-manager-grid"></div>
@@ -864,7 +883,17 @@ export class CustomNodesManager {
if(version == 'nightly') {
return `<div>${safeVersion}</div><div>[${safeLatest}]</div>`;
}
return `<div>${safeVersion}</div><div>[↑${safeLatest}]</div>`;
// Flag an update only when the registry version is provably newer
// (cmp === 1). cmp === -1/0 means the local install is already
// current or newer (issue #3272: 1.78.1 was flagged as updatable
// to 1.47.0).
const cmp = compareVersionSpecs(rowItem.cnr_latest, version);
const serverChecked = rowItem.state === 'enabled';
const newer = cmp === null && serverChecked ? rowItem['update-state'] === 'true' : cmp === null || cmp === 1;
if(newer) {
return `<div>${safeVersion}</div><div>[↑${safeLatest}]</div>`;
}
return safeVersion;
}
return safeVersion;
}
@@ -897,6 +926,9 @@ export class CustomNodesManager {
if (rowItem.conflicts) {
list.push(`<div class="cn-pack-conflicts">${rowItem.conflicts} conflict${(rowItem.conflicts>1?'s':'')}</div>`);
}
if (rowItem.potentialConflicts) {
list.push(`<div class="cn-pack-conflicts">${rowItem.potentialConflicts} potential conflict${(rowItem.potentialConflicts>1?'s':'')}</div>`);
}
list.push('</div>');
return list.join("");
}
@@ -1262,8 +1294,9 @@ export class CustomNodesManager {
list.push(`<div class="cn-nodes-list">`);
nodesList.forEach((it, i) => {
const conflicts = it.conflicts || it.potentialConflicts;
let rowClass = 'cn-nodes-row'
if (it.conflicts) {
if (conflicts) {
rowClass += ' cn-nodes-conflict';
}
@@ -1272,8 +1305,9 @@ export class CustomNodesManager {
// extName via /customnode/getmappings, no server sanitize: escaped at the sink.
list.push(`<div class="cn-nodes-name">${sanitizeHTML(String(it.name))}</div>`);
if (it.conflicts) {
list.push(`<div class="cn-conflicts-list"><div class="cn-nodes-conflict cn-icon">${icons.conflicts}</div><b>Conflict with</b>${it.conflicts.map(c => {
if (conflicts) {
const label = it.conflicts ? 'Conflict with enabled packs' : 'Potential conflict if installed/enabled with';
list.push(`<div class="cn-conflicts-list"><div class="cn-nodes-conflict cn-icon">${icons.conflicts}</div><b>${label}</b>${conflicts.map(c => {
return `<div class="cn-nodes-pack" hash="${c.hash}">${c.title}</div>`;
}).join("<b>,</b>")}</div>`);
}
@@ -1316,6 +1350,7 @@ export class CustomNodesManager {
}
const conflictsMap = {};
const nodesMapByPack = new Map();
// add nodes data
Object.keys(data).forEach(k => {
@@ -1328,9 +1363,12 @@ export class CustomNodesManager {
// deduped
const eList = Array.from(new Set(nodes));
nodeItem.nodes = eList.length;
const nodesMap = {};
const nodesMap = nodesMapByPack.get(nodeItem) || {};
nodesMapByPack.set(nodeItem, nodesMap);
eList.forEach(extName => {
if (nodesMap[extName]) {
return;
}
nodesMap[extName] = {
name: extName
};
@@ -1342,6 +1380,7 @@ export class CustomNodesManager {
cList.push(nodeItem.key);
});
nodeItem.nodesMap = nodesMap;
nodeItem.nodes = Object.keys(nodesMap).length;
} else {
// should be removed
// console.log("not found", k, title, nodes)
@@ -1358,13 +1397,17 @@ export class CustomNodesManager {
cList.forEach(key => {
const nodeItem = node_packs[key];
const extItem = nodeItem.nodesMap[extName];
if(!extItem.conflicts) {
extItem.conflicts = []
// Catalog entries are not necessarily installed or enabled. Only
// enabled peers can conflict; inactive packs get a separate preview.
const conflictsList = cList.filter(k => k !== key && node_packs[k].state === 'enabled');
if (!conflictsList.length) {
return;
}
const conflictsList = cList.filter(k => k !== key);
const field = nodeItem.state === 'enabled' ? 'conflicts' : 'potentialConflicts';
extItem[field] = [];
conflictsList.forEach(k => {
const nItem = node_packs[k];
extItem.conflicts.push({
extItem[field].push({
key: k,
title: nItem.title,
hash: nItem.hash
@@ -1378,6 +1421,7 @@ export class CustomNodesManager {
if (nodeItem.nodesMap) {
nodeItem.nodesList = Object.values(nodeItem.nodesMap);
nodeItem.conflicts = nodeItem.nodesList.filter(it => it.conflicts).length;
nodeItem.potentialConflicts = nodeItem.nodesList.filter(it => it.potentialConflicts).length;
}
})
@@ -2120,7 +2164,7 @@ export class CustomNodesManager {
// a server that was not restarted since its update still fetches every repository without skip_update
const res = await fetchData(`/customnode/getlist?mode=${mode}&skip_update=true`);
if (res.error) {
this.showError("Failed to get custom node list.");
this.showError(res.status === 403 && res.detail ? sanitizeHTML(res.detail) : "Failed to get custom node list.");
this.hideLoading();
return;
}
+11 -3
View File
@@ -101,7 +101,7 @@ export class NodeUsageAnalyzer {
".nu-manager-stop": {
click: () => {
api.fetchApi('/manager/queue/reset');
api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
}
},
@@ -340,7 +340,7 @@ export class NodeUsageAnalyzer {
let needRefresh = false;
let errorMsg = "";
await api.fetchApi('/manager/queue/reset');
await api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
let target_items = [];
@@ -388,7 +388,7 @@ export class NodeUsageAnalyzer {
}
}
else {
await api.fetchApi('/manager/queue/start');
await api.fetchApi('/manager/queue/start', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
this.ui.showStop();
showTerminal();
}
@@ -610,6 +610,13 @@ export class NodeUsageAnalyzer {
Object.keys(node_packs).forEach((packKey, index) => {
const pack = node_packs[packKey];
// packs that aren't in the node DB come back without an 'id'; the uninstall
// endpoint keys off it, so backfill it from the pack key (as the custom node
// manager does) or the uninstall is queued against a null node name
if (pack.id === undefined) {
pack.id = packKey;
}
// Only include installed packages (filter out "not-installed" packages)
if (pack.state === "not-installed") {
return; // Skip non-installed packages
@@ -625,6 +632,7 @@ export class NodeUsageAnalyzer {
used_in_count: usedCount,
workflowDetails: workflowDetails,
name: packKey,
hash: md5(packKey),
originalData: pack
});
});
-10
View File
@@ -4631,16 +4631,6 @@
"install_type": "git-clone",
"description": "Minimal custom node that enables comprehensive Datadog APM tracing and profiling for ComfyUI.\nNOTE: The files in the repo are not organized."
},
{
"author": "synchronicity-labs",
"title": "ComfyUI Sync Lipsync Node",
"reference": "https://github.com/synchronicity-labs/sync-comfyui",
"files": [
"https://github.com/synchronicity-labs/sync-comfyui"
],
"install_type": "git-clone",
"description": "NODES: WanVideo T5 Apply Soft Prefix"
},
{
"author": "NSFW-API",
"title": "ComfyUI-WanSoftPrefix",
-10
View File
@@ -10,16 +10,6 @@
"install_type": "git-clone",
"description": "Patched fork of ComfyUI-MultiGPU providing universal .safetensors and GGUF multi-GPU distribution with DisTorch 2.0 engine, model-driven allocation options (bytes/ratio modes), WanVideoWrapper integration, and up to 10% faster GGUF inference. (Description by CC)"
},
{
"author": "synchronicity-labs",
"title": "ComfyUI Sync Lipsync Node",
"reference": "https://github.com/synchronicity-labs/sync-comfyui",
"files": [
"https://github.com/synchronicity-labs/sync-comfyui"
],
"install_type": "git-clone",
"description": "This custom node allows you to perform audio-video lip synchronization inside ComfyUI using a simple interface."
},
{
"author": "joaomede",
"title": "ComfyUI-Unload-Model-Fork",
+163 -3
View File
@@ -1,5 +1,165 @@
{
"custom_nodes": [
{
"author": "BSAI",
"title": "BSAI_Premiere_Pro",
"reference": "https://github.com/xm6018924/BSAI_Premiere_Pro",
"files": [
"https://github.com/xm6018924/BSAI_Premiere_Pro"
],
"install_type": "git-clone",
"description": "BSAI Premiere Pro - Timeline-based video editing node for ComfyUI with auto-import, transitions, trim, audio replacement, and ffmpeg merge"
},
{
"author": "BSAI",
"title": "BSAI-ComfyUI-H3-Film-Factory",
"reference": "https://github.com/xm6018924/BSAI-ComfyUI-H3-Film-Factory",
"files": [
"https://github.com/xm6018924/BSAI-ComfyUI-H3-Film-Factory"
],
"install_type": "git-clone",
"description": "Complete film production toolkit for MiniMax H3: asset library, storyboard clip management, subtitle rendering, media combining, and contextual frame extraction"
},
{
"author": "GenMagic",
"title": "GenMagic (450+ AI Models: Image, Video, Speech, Music & Text)",
"id": "genmagic",
"reference": "https://github.com/yumaheymans/comfyui-genmagic",
"files": [
"https://github.com/yumaheymans/comfyui-genmagic"
],
"install_type": "git-clone",
"description": "Five ComfyUI nodes (GenMagicImage, GenMagicVideo, GenMagicSpeech, GenMagicMusic, GenMagicText) calling 450+ AI models (Veo 3.1, Seedance, Wan 3.0, Nano Banana, GPT Image, FLUX, Lyria 3, Claude, GPT) with one pay-as-you-go GENMAGIC_API_KEY. Supports image-to-image and image-to-video; requests are sent to genmagic.co/api/v1."
},
{
"author": "kama0630-cmyk",
"title": "Wan 2.2 5B Video Studio (Auto-Ratio TI2V, FunControl & 3-Stage Polish)",
"id": "wan22-5b-video-studio",
"reference": "https://github.com/kama0630-cmyk/ComfyUI-Wan22-5B-Video-Studio",
"files": [
"https://github.com/kama0630-cmyk/ComfyUI-Wan22-5B-Video-Studio"
],
"install_type": "git-clone",
"description": "All-in-one ComfyUI custom nodes and unified workflow for Wan 2.2 5B: aspect-ratio auto-sizing (4n+1 frames), lazy Standard TI2V / FunControl mode router, temporal MKL color matching, 3-stage preview-to-2x-48fps polish pipeline, and SageAttention safe fallback."
},
{
"author": "kama0630-cmyk",
"title": "Z-Image Pro Studio (Fast Preview, Polish & Detail Daemon)",
"id": "z-image-pro-studio",
"reference": "https://github.com/kama0630-cmyk/ComfyUI-Z-Image-Pro-Studio",
"files": [
"https://github.com/kama0630-cmyk/ComfyUI-Z-Image-Pro-Studio"
],
"install_type": "git-clone",
"description": "All-in-one ComfyUI custom nodes and workflows (safetensors & GGUF) for Z-Image: 4-Stage Fast Preview & Polish Switch, 16-channel resolution presets, AuraFlow Flow-Matching Detail Daemon, 5-part selective SAM detailers, 1.5x refiner & quality finisher, and built-in VRAM cleanup."
},
{
"author": "kama0630-cmyk",
"title": "FLUX Pro Studio (Fast Preview, Polish & Detail Daemon)",
"id": "flux-pro-studio",
"reference": "https://github.com/kama0630-cmyk/ComfyUI-FLUX-Pro-Studio",
"files": [
"https://github.com/kama0630-cmyk/ComfyUI-FLUX-Pro-Studio"
],
"install_type": "git-clone",
"description": "All-in-one ComfyUI custom nodes and workflows (safetensors & GGUF) for FLUX.1: 4-Stage Fast Preview & Polish Switch, 16-channel resolution presets, Flow-Matching Detail Daemon, 5-part selective SAM detailers, 1.5x refiner & quality finisher, and built-in VRAM cleanup."
},
{
"author": "kama0630-cmyk",
"title": "SDXL Pro Studio (Fast Preview, Polish & Fooocus Controls)",
"id": "sdxl-pro-studio",
"reference": "https://github.com/kama0630-cmyk/ComfyUI-SDXL-Pro-Studio",
"files": [
"https://github.com/kama0630-cmyk/ComfyUI-SDXL-Pro-Studio"
],
"install_type": "git-clone",
"description": "All-in-one ComfyUI custom nodes and workflow for SDXL: 4-Stage Fast Preview & Polish Switch, 5-part selective SAM detailers, 1.5x refiner & quality finisher, and optional zero-overhead Fooocus 4-in-1 controls."
},
{
"author": "kama0630-cmyk",
"title": "Krea 2 Studio Pack (Multi-Character & Factory)",
"id": "krea2-studio-pack",
"reference": "https://github.com/kama0630-cmyk/ComfyUI-Krea2-Studio-Pack",
"files": [
"https://github.com/kama0630-cmyk/ComfyUI-Krea2-Studio-Pack"
],
"install_type": "git-clone",
"description": "All-in-one ComfyUI custom nodes and workflows for Krea 2: Multi-Character Reference (Face/Outfit separation + Identity Edit V2), 4-Mode Character Factory, 4-Stage Fast Preview & Polish Studio Controllers, and non-destructive V2 RoPE runtime patch."
},
{
"author": "Valentin Klein",
"title": "ValiTools",
"reference": "https://github.com/vangel76/comfyui-ValiTools",
"files": [
"https://github.com/vangel76/comfyui-ValiTools"
],
"install_type": "git-clone",
"description": "ValiTools node collection: VSmartPrompt (Dynamic Prompts with a rich-text editor, reusable variables, switcher conditions, chaining inputs and post-run selection highlighting), VFileRandom (no-repeat random image loader), VRandomSelector (lazy random passthrough of N same-type inputs) and VWaitForVRAM (hold execution until enough VRAM is free)."
},
{
"author": "Orange-3DV-Team",
"title": "MoBack-Turbo",
"id": "moback-turbo",
"reference": "https://github.com/Orange-3DV-Team/MoBack",
"files": [
"https://github.com/Orange-3DV-Team/MoBack"
],
"install_type": "git-clone",
"description": "End-to-end 4-step video background replacement with text (Task A), background image (Task B), or edited-keyframe (Task C) guidance based on Wan2.2 and Qwen3-VL (Linux/CUDA). Uses native VIDEO ports and supports resident, --offload-dit, and --low-vram (24 GB VRAM) modes."
},
{
"author": "haryai",
"title": "HaryAI",
"id": "comfyui-haryai",
"reference": "https://github.com/haryai-com/comfyui-haryai",
"files": [
"https://github.com/haryai-com/comfyui-haryai"
],
"install_type": "git-clone",
"description": "Nodes for HaryAI's models: Seedance video (text to video, first and last frame, reference images, videos and audio, draft mode), Seedream and Nano Banana images (text to image and edits), and DeepSeek chat for writing video prompts and storyboards in a workflow. Billed to a HaryAI balance; needs a HaryAI API key in each node's api_key field (saved in the workflow); requests go to api.haryai.com."
},
{
"author": "AceDataCloud",
"title": "GPT Image",
"id": "gpt-image",
"reference": "https://github.com/AceDataCloud/GPTImageComfyUI",
"files": [
"https://github.com/AceDataCloud/GPTImageComfyUI"
],
"install_type": "git-clone",
"description": "Generate and edit images with GPT Image, retrieve task results, and load the resulting images in ComfyUI. Requires an Ace Data Cloud API key. Generation and editing are metered."
},
{
"author": "AceDataCloud",
"title": "ACE Music",
"id": "ace-acemusic",
"reference": "https://github.com/AceDataCloud/ACEMusicComfyUI",
"files": [
"https://github.com/AceDataCloud/ACEMusicComfyUI"
],
"install_type": "git-clone",
"description": "Generate ACE Music songs and lyrics, import reference assets, and retrieve results by task ID. Requires an Ace Data Cloud API key. Generation and reference imports are metered."
},
{
"author": "assetfeed",
"title": "AssetFeed",
"reference": "https://github.com/assetfeed/comfyui-assetfeed",
"files": [
"https://github.com/assetfeed/comfyui-assetfeed"
],
"install_type": "git-clone",
"description": "Nodes for the AssetFeed API: AssetFeed OCR reads the text in an image, and AssetFeed AI Text Check estimates the AI-written share of an English text. Needs an ASSETFEED_API_KEY environment variable; images and text are sent to api.assetfeed.com; data handling is in the README."
},
{
"author": "Raykosan (RaykoStudio)",
"title": "ComfyUI-RS_WorkspaceManager",
"reference": "https://github.com/Raykosan/ComfyUI-RS_WorkspaceManager",
"files": [
"https://github.com/Raykosan/ComfyUI-RS_WorkspaceManager"
],
"install_type": "git-clone",
"description": "Workflow Preset Manager and Interface Settings Backup for ComfyUI."
},
{
"author": "bewizsky",
"title": "Eyes4AI Text Repair",
@@ -274,12 +434,12 @@
"author": "haryai",
"title": "Seedance 2.5 (HaryAI)",
"id": "seedance-comfyui",
"reference": "https://github.com/sunsiyuan/seedance-comfyui",
"reference": "https://github.com/haryai-com/seedance-comfyui",
"files": [
"https://github.com/sunsiyuan/seedance-comfyui"
"https://github.com/haryai-com/seedance-comfyui"
],
"install_type": "git-clone",
"description": "Seedance 2.5 and Seedance 2.5 Flash video generation through the HaryAI API: text to video, first and last frame, reference images, sound. No BytePlus account needed."
"description": "Superseded by HaryAI (comfyui-haryai), which has the same nodes plus chat. Seedance 2.5 video and Seedream / Nano Banana images through the HaryAI API: text to video, first and last frame, reference images, videos and audio, draft mode, text to image and edits. Needs a HaryAI API key in the node's api_key field; requests go to api.haryai.com."
},
{
"author": "codalanguez",
+37 -3
View File
@@ -51,6 +51,11 @@ message_collapses = [skip_pip_spam]
import_failed_extensions = set()
cm_global.variables['cm.on_revision_detected_handler'] = []
enable_file_logging = True
# When file logging is on, strip ANSI color/escape codes from the bytes written to
# the disk log so the file stays plain and readable. The console ALWAYS keeps its
# original (colored) output -- this only ever touches the file branch of sync_write.
# Default on; set `strip_ansi_file_logging = False` in config.ini to keep ANSI in the file.
strip_ansi_file_logging = True
def register_message_collapse(f):
@@ -132,12 +137,18 @@ def set_git_executable():
if git_exe is not None:
os.environ['GIT_PYTHON_GIT_EXECUTABLE'] = git_exe
def check_strip_ansi_file_logging():
global strip_ansi_file_logging
if 'strip_ansi_file_logging' in default_conf and default_conf['strip_ansi_file_logging'].lower() == 'false':
strip_ansi_file_logging = False
read_config()
set_git_executable()
read_uv_mode()
security_check.security_check()
check_file_logging()
check_strip_ansi_file_logging()
cm_global.pip_overrides = {}
@@ -281,6 +292,14 @@ try:
pat_tqdm = r'\d+%.*\[(.*?)\]'
pat_import_fail = r'seconds \(IMPORT FAILED\):(.*)$'
# CSI (ECMA-48) escape sequences: ESC [ <params: digits/;/> <?> <final letter>.
# Covers SGR colors (\x1b[31m, \x1b[0m, \x1b[1;32m), private modes (\x1b[?25l),
# cursor moves and erase codes (\x1b[2J, \x1b[0K). It never matches a real '\n',
# so line structure/timestamps are untouched. Self-contained on purpose -- we do
# NOT route this through colorama, which is the exact dependency that proved
# unreliable in issue #3259.
pat_ansi = r'\x1b\[[0-9;?]*[a-zA-Z]'
is_start_mode = True
@@ -387,15 +406,26 @@ try:
except OSError:
self.console_is_gone = True
def _file_message(self, message):
# The exact bytes that go to the disk log. When strip_ansi_file_logging
# is on, ANSI escape sequences are removed so the file is plain and
# readable. This is the ONLY place the file content diverges from what
# the console receives -- the console path below always uses the
# original, unmodified message, so its coloring is never affected.
if strip_ansi_file_logging:
return re.sub(pat_ansi, '', message)
return message
def sync_write(self, message, file_only=False):
with log_lock:
# after close_log() the output goes to the console only
if not log_file.closed:
file_message = self._file_message(message)
timestamp = current_timestamp()
if self.last_char != '\n':
log_file.write(message)
log_file.write(file_message)
else:
log_file.write(f"[{timestamp}] {message}")
log_file.write(f"[{timestamp}] {file_message}")
try:
log_file.flush()
@@ -735,7 +765,11 @@ def execute_lazy_cnr_switch(target, zip_url, from_path, to_path, no_deps, custom
# 1. download
archive_name = f"CNR_temp_{str(uuid.uuid4())}.zip" # should be unpredictable name - security precaution
download_path = os.path.join(custom_nodes_path, archive_name)
manager_downloader.download_url(zip_url, custom_nodes_path, archive_name)
try:
manager_downloader.download_url(zip_url, custom_nodes_path, archive_name)
except Exception:
manager_downloader.remove_failed_download(custom_nodes_path, archive_name)
raise
try:
extracted = manager_util.switch_package_files(download_path, from_path)
+168
View File
@@ -0,0 +1,168 @@
import os
import pytest
from test_install_flags_config import _run_child
posix_folder = pytest.mark.skipif(os.name == 'nt', reason='the folder that aria2 gets is a POSIX path')
PRELUDE = '''
import time
md = manager_core.manager_downloader
manager_core.comfy_path = tmp
time.sleep = lambda seconds: None
LOCAL = os.path.join(tmp, 'models', 'checkpoints', 'y.safetensors')
TARGET = '/models/checkpoints/y.safetensors'
class FakeDownload:
def __init__(self, statuses, local_file=None, error_message=None, target=None):
self._statuses = list(statuses)
self.status = self._statuses.pop(0)
self._local_file = local_file
self.error_message = error_message
self.total_length = 10
self.completed_length = 0
self.files = [type('F', (), {'is_metadata': False, 'path': target})()] if target else []
self._write_if_complete()
def _write_if_complete(self):
if self.status == 'complete' and self._local_file:
os.makedirs(os.path.dirname(self._local_file), exist_ok=True)
open(self._local_file, 'wb').close()
is_active = property(lambda self: self.status == 'active')
is_waiting = property(lambda self: self.status == 'waiting')
has_failed = property(lambda self: self.status == 'error')
is_complete = property(lambda self: self.status == 'complete')
def update(self):
if self._statuses:
self.status = self._statuses.pop(0)
self._write_if_complete()
class FakeAria2:
def __init__(self, new, existing=()):
self.new, self.existing, self.added = new, list(existing), []
def get_downloads(self):
return self.existing
def add(self, url, options):
self.added.append(dict(options))
return [self.new]
def install(fake):
md.aria2 = fake
error = None
try:
md.download_url('https://huggingface.co/x/y.safetensors', os.path.dirname(LOCAL), 'y.safetensors')
except Exception as e:
error = str(e)
print(json.dumps({'error': error, 'added': fake.added, 'status': fake.new.status, 'file': os.path.exists(LOCAL)}))
'''
def run(body):
return _run_child(PRELUDE + body)
def test_a_download_that_aria2_fails_raises_with_its_message():
data = run('''
install(FakeAria2(FakeDownload(['error'], error_message='Failed to make the directory /models/checkpoints, cause: Permission denied')))
''')
assert 'Permission denied' in data['error'], data
@pytest.mark.parametrize('status', ['paused', 'removed'])
def test_a_download_that_was_stopped_with_a_part_of_the_file_there_raises(status):
data = run(f'''
os.makedirs(os.path.dirname(LOCAL))
open(LOCAL, 'wb').close()
open(LOCAL + '.aria2', 'wb').close()
install(FakeAria2(FakeDownload(['active', {status!r}])))
''')
assert status in data['error'], data
def test_a_file_that_aria2_saved_elsewhere_raises():
data = run('''
install(FakeAria2(FakeDownload(['complete'])))
''')
assert 'y.safetensors' in data['error'] and 'docs/en/use_aria2.md' in data['error'], data
@posix_folder
def test_a_queued_download_is_waited_for():
data = run('''
install(FakeAria2(FakeDownload(['waiting', 'active', 'complete'], local_file=LOCAL)))
''')
assert data == {'error': None, 'added': [{'dir': '/models/checkpoints', 'out': 'y.safetensors'}], 'status': 'complete', 'file': True}
@posix_folder
def test_a_failed_earlier_download_is_not_reused():
data = run('''
install(FakeAria2(FakeDownload(['active', 'complete'], local_file=LOCAL), existing=[FakeDownload(['error'], target=TARGET)]))
''')
assert data['error'] is None and len(data['added']) == 1, data
@posix_folder
def test_a_finished_earlier_download_whose_file_is_there_is_reused():
data = run('''
os.makedirs(os.path.dirname(LOCAL))
open(LOCAL, 'wb').close()
install(FakeAria2(FakeDownload(['complete']), existing=[FakeDownload(['complete'], target=TARGET)]))
''')
assert data['error'] is None and data['added'] == [], data
@posix_folder
def test_an_earlier_download_that_is_still_queued_is_waited_for():
data = run('''
install(FakeAria2(FakeDownload(['complete']), existing=[FakeDownload(['waiting', 'active', 'complete'], local_file=LOCAL, target=TARGET)]))
''')
assert data['error'] is None and data['added'] == [] and data['file'], data
def test_a_file_that_is_already_there_is_not_downloaded_again():
data = run('''
os.makedirs(os.path.dirname(LOCAL))
open(LOCAL, 'wb').close()
install(FakeAria2(FakeDownload(['complete'])))
''')
assert data['error'] is None and data['added'] == [], data
def test_a_part_that_aria2_has_a_control_file_for_is_downloaded():
data = run('''
os.makedirs(os.path.dirname(LOCAL))
open(LOCAL, 'wb').close()
open(LOCAL + '.aria2', 'wb').close()
install(FakeAria2(FakeDownload(['complete'])))
''')
assert data['error'] is None and len(data['added']) == 1, data
def test_a_nodepack_archive_whose_download_fails_leaves_no_file():
data = run('''
nodes = os.path.join(tmp, 'custom_nodes')
os.makedirs(nodes)
manager_core.get_default_custom_nodes_path = lambda: nodes
class Aria2ThatFailsHalfway(FakeAria2):
def add(self, url, options):
for name in (options['out'], options['out'] + '.aria2'):
open(os.path.join(nodes, name), 'wb').close()
return super().add(url, options)
md.aria2 = Aria2ThatFailsHalfway(FakeDownload(['error'], error_message='the speed was too low'))
error = None
try:
manager_core.UnifiedManager()._cnr_install('fixture', types.SimpleNamespace(version='1.0.0', download_url='https://example.invalid/fixture.zip'))
except Exception as e:
error = str(e)
print(json.dumps({'error': error, 'left': os.listdir(nodes)}))
''')
assert 'the speed was too low' in data['error'] and data['left'] == [], data
+58
View File
@@ -0,0 +1,58 @@
import os
from test_install_flags_config import _run_child
PRELUDE = '''
md = manager_core.manager_downloader
manager_core.comfy_path = tmp
class FakeDownload:
is_active = is_waiting = has_failed = False
is_complete = True
class FakeAria2:
def __init__(self, model_dir):
self.model_dir, self.added = model_dir, []
def get_downloads(self):
return []
def add(self, url, options):
self.added.append(dict(options))
open(os.path.join(self.model_dir, options['out']), 'wb').close()
return [FakeDownload()]
def dir_given_to_aria2(model_dir):
md.aria2 = FakeAria2(model_dir)
os.makedirs(model_dir, exist_ok=True)
md.download_url('https://huggingface.co/x/y.safetensors', model_dir, 'y.safetensors')
return md.aria2.added[0]['dir']
checkpoints = os.path.join(tmp, 'models', 'checkpoints')
custom_nodes = os.path.join(tmp, 'custom_nodes')
outside = os.path.join(tempfile.mkdtemp(), 'checkpoints')
print(json.dumps({
'checkpoints': [checkpoints, dir_given_to_aria2(checkpoints)],
'custom_nodes': [custom_nodes, dir_given_to_aria2(custom_nodes)],
'outside': [outside, dir_given_to_aria2(outside)],
}))
'''
def run(setting):
return _run_child(f"os.environ['COMFYUI_MANAGER_ARIA2_SAME_PATHS'] = {setting!r}\n" + PRELUDE)
def test_by_default_aria2_gets_the_comfyui_folder_as_its_root():
for setting in ('', 'false'):
data = run(setting)
assert data['checkpoints'][1] == os.sep + os.path.join('models', 'checkpoints')
assert data['custom_nodes'][1] == os.sep + 'custom_nodes'
assert data['outside'][1] == data['outside'][0]
def test_with_same_paths_aria2_gets_each_folder_as_it_is():
data = run('true')
for local, given in data.values():
assert given == local
+13
View File
@@ -302,3 +302,16 @@ command(scope, 'restore_dependencies')
lines = lambda: ([line.replace(folder, '{folder}') for line in said() if line.startswith('Restoring')]
+ [os.path.basename(call.args[1]) for call in manager.execute_install_script.call_args_list])
''') == ['Restoring [1/1]: {folder}' + os.sep + 'a-pack', 'a-pack']
def test_a_list_of_a_refused_channel_says_why_and_fails():
assert said('''
async def refused(channel, mode):
raise core.InvalidChannel('/srv/channel', 'the reason [of it]')
manager.get_custom_nodes = refused
scope, lines = cm_cli('show_list')
try:
scope['show_list']('all')
except typer.Exit as stop:
scope['print'](f'exit {stop.exit_code}')
''') == ['ERROR: the reason [of it]', 'exit 1']
+126
View File
@@ -251,6 +251,132 @@ print(json.dumps({'ok': result.result, 'old_path': installed.exists(),
'queries': 0, 'downloads': 0, 'scripts': 0}
def test_unspecified_version_enable_restores_cnr_disabled_pack():
data = run('''
installed = nodes / '.disabled/fixture@1_0_0'
installed.mkdir(parents=True)
(installed / '__init__.py').write_text('already installed')
manager.cnr_map['fixture'] = {'id': 'fixture'}
manager.cnr_inactive_nodes['fixture'] = {'1.0.0': str(installed)}
# version_spec=None: the inactive-dict fallback must recognize the disabled
# CNR pack (a dict never equals version_spec) and enable must restore it
# without re-downloading, instead of routing install_by_id to a fresh install
disabled = manager.is_disabled('fixture')
result = manager.unified_enable('fixture')
print(json.dumps({'disabled': disabled, 'ok': result.result, 'action': result.action,
'msg': result.msg,
'active_ok': manager.active_nodes.get('fixture') == ('1.0.0', str(nodes / 'fixture')),
'old_path': installed.exists(),
'downloads': core.manager_downloader.download_url.call_count}))
''')
assert data == {'disabled': True, 'ok': True, 'action': 'enable', 'msg': None,
'active_ok': True, 'old_path': False, 'downloads': 0}
@pytest.mark.parametrize('key', ['1.0.0', '1.0.0-beta'])
def test_install_without_version_restores_the_disabled_version(key):
data = run(f"""
status = 'NodeVersionStatusActive'
installed = nodes / '.disabled/fixture@1_0_0'
installed.mkdir(parents=True)
(installed / '__init__.py').write_text('v1')
(installed / '.tracking').write_text('__init__.py')
manager.cnr_map['fixture'] = {{'id': 'fixture', 'latest_version': {{'version': '2.0.0'}}}}
manager.cnr_inactive_nodes['fixture'] = {{{key!r}: str(installed)}}
result = asyncio.run(manager.install_by_id('fixture', instant_execution=True))
f = nodes / 'fixture/__init__.py'
print(json.dumps({{'ok': result.result, 'action': result.action, 'content': f.read_text() if f.exists() else None,
'downloads': core.manager_downloader.download_url.call_count, 'queries': get.call_count}}))
""")
assert data == {'ok': True, 'action': 'enable', 'content': 'v1', 'downloads': 0, 'queries': 0}
def press_enable(body):
return f"BODY = {body!r}" + """
import ast
from aiohttp import web
source = pathlib.Path(core.__file__).with_name('manager_server.py').read_text(encoding='utf-8')
handler = [node for node in ast.parse(source).body
if isinstance(node, ast.AsyncFunctionDef) and node.name == '_queue_node_install']
events = []
namespace = {'core': core, 'web': web, 'logging': logging, 'os': os,
'_reject_non_json_content_type': lambda request: None, 'is_allowed_security_level': lambda level: True,
'PromptServer': SimpleNamespace(instance=SimpleNamespace(send_sync=lambda event, data: events.append(data)))}
exec(compile(ast.Module(body=handler, type_ignores=[]), 'manager_server.py', 'exec'), namespace)
body = dict(BODY, channel='default', mode='cache', ui_id='row', skip_post_install=True)
response = asyncio.run(namespace['_queue_node_install'](SimpleNamespace(json=AsyncMock(return_value=body)), 'install'))
reported = [event['nodepack_result'] for event in events if event['status'] == 'done']
"""
def test_enable_button_answers_success_for_an_enabled_pack_that_the_registry_data_does_not_list():
data = run("""
enabled, disabled = nodes / 'fixture', nodes / '.disabled/fixture@0_9_0'
for folder, version in ((enabled, '1.0.0'), (disabled, '0.9.0')):
folder.mkdir(parents=True)
(folder / '__init__.py').write_text(version)
manager.active_nodes['fixture'] = ('1.0.0', str(enabled))
manager.cnr_inactive_nodes['fixture'] = {'0.9.0': str(disabled)}
""" + press_enable({'id': 'fixture', 'version': '1.0.0', 'selected_version': '0.9.0'}) + """
print(json.dumps({'status': response.status, 'reported': reported,
'enabled': (enabled / '__init__.py').read_text(), 'disabled': (disabled / '__init__.py').read_text()}))
""")
assert data == {'status': 200, 'reported': [{'row': 'success'}], 'enabled': '1.0.0', 'disabled': '0.9.0'}
def test_enable_button_says_why_for_a_disabled_pack_that_the_registry_data_does_not_list():
data = run("""
disabled = nodes / '.disabled/fixture@1_0_0'
disabled.mkdir(parents=True)
(disabled / '__init__.py').write_text('v1')
manager.cnr_inactive_nodes['fixture'] = {'1.0.0': str(disabled)}
""" + press_enable({'id': 'fixture', 'version': '1.0.0', 'selected_version': '1.0.0'}) + """
print(json.dumps({'status': response.status, 'text': response.text, 'reported': reported,
'disabled': (disabled / '__init__.py').read_text(), 'enabled': (nodes / 'fixture').exists()}))
""")
assert data == {'status': 400, 'text': 'Specified inactive node not exists: fixture', 'reported': [],
'disabled': 'v1', 'enabled': False}
@pytest.mark.parametrize('disabled, printed, enabled', [
(['0.9.0', '1.0.0'], ['1/1 [ ENABLED ] fixture'], '0.9.0'),
(['1.0.0'], ["ERROR: An error occurred while installing 'fixture'.",
'Specified inactive node path not exists: <folder>'], None),
], ids=['an older version is left', 'no version is left'])
def test_cli_install_without_version_when_the_newest_disabled_version_was_removed_after_the_scan(disabled, printed, enabled):
data = run(f"DISABLED = {disabled!r}" + """
import ast, shutil, rich.console
status = 'NodeVersionStatusActive'
async def get_cnr_data(*args, **kwargs):
return [{'id': 'fixture', 'name': 'Fixture', 'repository': 'https://github.com/owner/fixture',
'publisher': {'name': 'owner'}, 'latest_version': {'version': '2.0.0'}}]
cnr_utils.get_cnr_data = get_cnr_data
sys.modules['folder_paths'].get_folder_paths = lambda name: [str(nodes)]
for version in DISABLED:
folder = nodes / ('.disabled/fixture@' + version.replace('.', '_'))
folder.mkdir(parents=True)
(folder / '__init__.py').write_text(version)
(folder / '.tracking').write_text('__init__.py\\npyproject.toml\\n')
(folder / 'pyproject.toml').write_text(f'[project]\\nname = "fixture"\\nversion = "{version}"\\n')
asyncio.run(manager.reload('cache', dont_wait=False))
gone = nodes / '.disabled/fixture@1_0_0'
shutil.rmtree(gone)
source = (pathlib.Path(core.__file__).parent.parent / 'cm-cli.py').read_text(encoding='utf-8')
found = [node for node in ast.parse(source).body if isinstance(node, ast.FunctionDef) and node.name == 'install_node']
out = io.StringIO()
scope = {'core': core, 'unified_manager': manager, 'asyncio': asyncio, 'sys': sys,
'print': rich.console.Console(file=out, width=1000, color_system=None).print,
'cmd_ctx': SimpleNamespace(channel='default', mode='cache', no_deps=False)}
exec(compile(ast.Module(found, []), 'cm-cli.py', 'exec'), scope)
scope['install_node']('fixture', cnt_msg='1/1')
enabled = nodes / 'fixture/__init__.py'
print(json.dumps({'printed': [' '.join(line.replace(str(gone), '<folder>').split()) for line in out.getvalue().splitlines()],
'enabled': enabled.read_text() if enabled.exists() else None,
'downloads': core.manager_downloader.download_url.call_count}))
""")
assert data == {'printed': printed, 'enabled': enabled, 'downloads': 0}
def test_reinstall_stops_when_the_installed_folder_cannot_be_moved_aside():
data = run('''
status = 'NodeVersionStatusActive'
+85
View File
@@ -0,0 +1,85 @@
import pytest
from test_install_flags_config import _run_child
SCRIPT = '''
import asyncio, pathlib, subprocess
import cnr_utils
def git(path, *args):
return subprocess.run(['git', '-c', 'user.name=test', '-c', 'user.email=test@example.invalid', *args],
cwd=path, check=True, capture_output=True, text=True).stdout.strip()
origin = pathlib.Path(tmp) / 'grp' / 'zz-pack'
origin.mkdir(parents=True)
git(origin, 'init', '-q')
for version in (1, 2):
(origin / '__init__.py').write_text('VERSION = %d' % version)
git(origin, 'add', '.')
git(origin, 'commit', '-q', '-m', 'version %d' % version)
tip = git(origin, 'rev-parse', 'HEAD')
other = pathlib.Path(tmp) / 'other' / 'zz-pack'
other.mkdir(parents=True)
git(other, 'init', '-q')
(other / '__init__.py').write_text('ANOTHER = 1')
git(other, 'add', '.')
git(other, 'commit', '-q', '-m', 'another repository of the same name')
os.environ.update(GIT_CONFIG_COUNT='2', GIT_CONFIG_KEY_0='url.%s/%s/.insteadOf' % (tmp, 'grp' if CLONE_WORKS else 'gone'), GIT_CONFIG_VALUE_0='https://git.example.invalid/grp/',
GIT_CONFIG_KEY_1='url.%s/other/.insteadOf' % tmp, GIT_CONFIG_VALUE_1='https://git.example.invalid/other/')
nodes = pathlib.Path(tmp) / 'custom_nodes'
nodes.mkdir()
sys.modules['folder_paths'].get_folder_paths = lambda name: [str(nodes)]
manager_core.get_default_custom_nodes_path = lambda: str(nodes)
manager_core.get_config = lambda: {'network_mode': 'public', 'channel_url': manager_core.DEFAULT_CHANNEL, 'http_channel_enabled': False}
flags = []
manager_core.unified_manager.execute_install_script = lambda url, path, **given: flags.append(given) or True
async def registry(*args, **kwargs):
return [{'id': 'zz-pack', 'repository': 'https://git.example.invalid/grp/zz-pack', 'latest_version': {'version': '1.0.0'}}]
async def channel(mode, filename, channel_url=None):
return {'custom_nodes': LISTED_BY_THE_CHANNEL}
asked = []
cnr_utils.get_cnr_data = registry
cnr_utils.install_node = lambda node_id, version=None: asked.append([node_id, version])
manager_core.get_data_by_mode = channel
installed = FOLDER_OF_A_VERSION
if installed:
(nodes / installed).mkdir(parents=True)
(nodes / installed / 'pyproject.toml').write_text('[project]\\nname = "zz-pack"\\nversion = "1.0.0"\\n')
(nodes / installed / '.tracking').write_text('pyproject.toml')
result = asyncio.run(manager_core.gitclone_install('https://git.example.invalid/grp/zz-pack', instant_execution=True, no_deps=True))
left = {str(path.relative_to(nodes)): 'the tip' if git(path, 'rev-parse', 'HEAD') == tip else 'a clone' for path in nodes.rglob('*') if (path / '.git').is_dir()}
left.update({str(path.relative_to(nodes)): 'version 1.0.0' for path in nodes.rglob('*') if (path / '.tracking').is_file()})
print(json.dumps({'installed': result.result, 'left': left, 'asked the registry for': asked, 'flags of the clone': flags}))
'''
ANOTHER_OF_THE_SAME_NAME = [{'id': 'zz-pack', 'title': 'zz-pack', 'author': 'other', 'install_type': 'git-clone', 'description': '',
'reference': 'https://git.example.invalid/other/zz-pack', 'files': ['https://git.example.invalid/other/zz-pack']}]
def install_by_url(folder_of_a_version=None, clone_works=True, channel=()):
return _run_child(SCRIPT.replace('FOLDER_OF_A_VERSION', repr(folder_of_a_version)).replace('CLONE_WORKS', repr(clone_works)).replace('LISTED_BY_THE_CHANNEL', repr(list(channel))))
CLONED = {'installed': True, 'asked the registry for': [], 'flags of the clone': [{'instant_execution': True, 'no_deps': True}]}
def test_url_of_a_repository_that_the_registry_lists_is_cloned():
assert install_by_url() == {**CLONED, 'left': {'zz-pack': 'the tip'}}
def test_url_is_what_is_cloned_when_the_channel_lists_another_repository_of_that_name():
assert install_by_url(channel=ANOTHER_OF_THE_SAME_NAME) == {**CLONED, 'left': {'zz-pack': 'the tip'}}
@pytest.mark.parametrize('folder', ['zz-pack', '.disabled/zz-pack@1_0_0'], ids=['enabled', 'disabled'])
def test_url_of_a_nodepack_that_is_installed_at_a_version_is_cloned_and_the_version_is_disabled(folder):
assert install_by_url(folder) == {**CLONED, 'left': {'zz-pack': 'the tip', '.disabled/zz-pack@1_0_0': 'version 1.0.0'}}
def test_enabled_version_is_enabled_again_when_the_clone_in_its_place_fails():
assert install_by_url('zz-pack', clone_works=False) == {'installed': False, 'left': {'zz-pack': 'version 1.0.0'}, 'asked the registry for': [], 'flags of the clone': []}
+4
View File
@@ -374,6 +374,10 @@ class DenialConstantsTest(unittest.TestCase):
def _assert_honest_copy(self, const, flag_name):
self.assertIn(flag_name, const, "constant must name the responsible flag")
self.assertIn("config.ini", const, "constant must name config.ini")
# The gate is `flag AND loopback` (is_dedicated_install_allowed), so a
# message that stops at the flag sends non-loopback users to re-check a
# setting they already enabled.
self.assertIn("loopback", const, "constant must name the loopback requirement")
for cause_phrasing in (
"is not allowed in this security_level",
"set the security level",
+213
View File
@@ -0,0 +1,213 @@
"""execute_install_script() must install from a node pack's requirements.txt
that the locale encoding cannot decode, and take from the encoding that
chardet guesses only requirements that do not depend on the guess.
On Windows the locale encoding is the ANSI code page, so a UTF-8
requirements.txt with a non-ASCII comment made the module-level installer
raise UnicodeDecodeError before any package was installed. The test pins the
locale to cp1252 so it reproduces the Windows behavior on any platform.
"""
import ast
import builtins
import os
import sys
import types
import chardet
import pytest
from manager_test_utils import GLOB_DIR, load_manager_util
NOT_TEXT = bytes(range(128, 256)) * 4 + b"\nnumpy\n"
MAC_ROMAN = "# Dependências do nó – instalação\nrich\n".encode("mac_roman")
SHIFT_JIS = "numpy\nrich # 画像処理用\n".encode("shift_jis")
EBCDIC = "pandas\r".encode("cp500")
def ansi_open(file, mode="r", *args, encoding=None, **kwargs):
if "b" not in mode and encoding is None:
encoding = "cp1252"
return builtins.open(file, mode, *args, encoding=encoding, **kwargs)
def load_execute_install_script(manager_util, calls):
source = (GLOB_DIR / "manager_core.py").read_text(encoding="utf-8")
functions = [node for node in ast.parse(source).body
if isinstance(node, ast.FunctionDef) and node.name == "execute_install_script"]
assert len(functions) == 1
namespace = {
"os": os,
"sys": sys,
"open": ansi_open,
"manager_util": manager_util,
"cm_global": types.SimpleNamespace(pip_overrides={}),
"try_install_script": lambda url, repo_path, cmd, instant_execution=False: calls.append(cmd),
"comfy_path": "",
"manager_files_path": "",
"manager_migration": types.SimpleNamespace(has_system_user_api=lambda: False),
}
exec(compile(ast.Module(body=functions, type_ignores=[]), "<install-extract>", "exec"), namespace)
return namespace["execute_install_script"]
def load_install_at_startup(manager_util, calls):
source = (GLOB_DIR.parent / "prestartup_script.py").read_text(encoding="utf-8")
functions = [node for node in ast.parse(source).body
if isinstance(node, ast.FunctionDef) and node.name == "execute_lazy_install_script"]
assert len(functions) == 1
namespace = {
"os": os,
"manager_util": manager_util,
"cm_global": types.SimpleNamespace(pip_overrides={}),
"is_installed": lambda name: False,
"process_wrap": lambda cmd, cwd, **kwargs: calls.append(cmd),
"processed_install": set(),
"comfy_path": "",
}
exec(compile(ast.Module(body=functions, type_ignores=[]), "<startup-extract>", "exec"), namespace)
return namespace["execute_lazy_install_script"]
class FakePIPFixer:
def __init__(self, *args):
pass
def fix_broken(self):
pass
def ansi_manager_util(monkeypatch):
real_util = load_manager_util()
monkeypatch.setattr(real_util, "open", ansi_open, raising=False)
monkeypatch.setattr(real_util, "PIPFixer", FakePIPFixer)
monkeypatch.setattr(real_util, "get_installed_packages", lambda: {})
monkeypatch.setattr(real_util, "make_pip_cmd", lambda args: ["pip"] + args)
return real_util
def chardet_names(monkeypatch, encoding):
monkeypatch.setattr(chardet, "detect", lambda data: {"encoding": encoding, "confidence": 0.06, "language": None})
def install(manager_util, tmp_path):
calls = []
execute_install_script = load_execute_install_script(manager_util, calls)
assert execute_install_script("https://example.invalid/pack", str(tmp_path)) is True
return calls
def test_utf8_requirements_with_non_ascii_comment_install(tmp_path, monkeypatch):
manager_util = ansi_manager_util(monkeypatch)
(tmp_path / "requirements.txt").write_text(
"# Łukasz ✨ 中文\nnumpy\nrich # Łukasz\n", encoding="utf-8")
assert install(manager_util, tmp_path) == [["pip", "install", "numpy"], ["pip", "install", "rich"]]
@pytest.mark.parametrize("content, named, installed", [
(MAC_ROMAN, "ISO-8859-5", ["rich"]),
(SHIFT_JIS, "cp1006", ["numpy", "rich"]),
], ids=["mac-roman-chardet-7.1.0", "shift-jis-chardet-7.1.0"])
def test_requirements_whose_comment_chardet_misreads_install(tmp_path, monkeypatch, content, named, installed):
manager_util = ansi_manager_util(monkeypatch)
chardet_names(monkeypatch, named)
(tmp_path / "requirements.txt").write_bytes(content)
assert install(manager_util, tmp_path) == [["pip", "install", name] for name in installed]
@pytest.mark.parametrize("text, installed", [
("\u3000# 依存関係\nnumpy\n", ["numpy"]),
("# 依存関係\nnumpy\n\u00a0\u00a0\nrich\n", ["numpy", "rich"]),
], ids=["comment-indented-with-an-ideographic-space", "line-of-no-break-spaces"])
def test_utf8_requirements_with_non_ascii_blanks_install(tmp_path, monkeypatch, text, installed):
manager_util = ansi_manager_util(monkeypatch)
chardet_names(monkeypatch, "utf-8")
(tmp_path / "requirements.txt").write_text(text, encoding="utf-8")
assert install(manager_util, tmp_path) == [["pip", "install", name] for name in installed]
def test_requirement_line_with_a_no_break_space_fails_the_install(tmp_path, monkeypatch):
manager_util = ansi_manager_util(monkeypatch)
chardet_names(monkeypatch, "utf-8")
(tmp_path / "requirements.txt").write_text("numpy\u00a0 # 依存関係\nrich\n", encoding="utf-8")
calls = []
execute_install_script = load_execute_install_script(manager_util, calls)
with pytest.raises(UnicodeDecodeError) as error:
execute_install_script("https://example.invalid/pack", str(tmp_path))
assert str(error.value) == "'charmap' codec can't decode byte 0x9d in position 12: character maps to <undefined>"
assert calls == []
def test_requirement_with_a_non_ascii_url_fragment_fails_the_install(tmp_path, monkeypatch):
manager_util = ansi_manager_util(monkeypatch)
chardet_names(monkeypatch, "utf-8")
(tmp_path / "requirements.txt").write_text("git+https://host/repo#egg=依存\nrich\n", encoding="utf-8")
calls = []
execute_install_script = load_execute_install_script(manager_util, calls)
with pytest.raises(UnicodeDecodeError):
execute_install_script("https://example.invalid/pack", str(tmp_path))
assert calls == []
def test_utf16_requirements_with_byte_order_mark_install_only_their_requirements(tmp_path, monkeypatch):
manager_util = ansi_manager_util(monkeypatch)
chardet_names(monkeypatch, "utf-16-le")
(tmp_path / "requirements.txt").write_bytes("# 依赖列表\nrich\n".encode("utf-16"))
assert install(manager_util, tmp_path) == [["pip", "install", "rich"]]
@pytest.mark.parametrize("named", ["ISO-8859-5", "MacCyrillic", None],
ids=["chardet-7.7.0", "chardet-7.1.0", "no-encoding"])
def test_requirements_that_are_not_text_fail_the_install(tmp_path, monkeypatch, named):
manager_util = ansi_manager_util(monkeypatch)
chardet_names(monkeypatch, named)
(tmp_path / "requirements.txt").write_bytes(NOT_TEXT)
calls = []
execute_install_script = load_execute_install_script(manager_util, calls)
with pytest.raises(UnicodeDecodeError) as error:
execute_install_script("https://example.invalid/pack", str(tmp_path))
assert str(error.value) == "'charmap' codec can't decode byte 0x81 in position 1: character maps to <undefined>"
assert calls == []
@pytest.mark.parametrize("named", ["cp500", "cp1140"])
def test_requirements_that_an_ebcdic_guess_reads_as_ascii_fail_the_install(tmp_path, monkeypatch, named):
manager_util = ansi_manager_util(monkeypatch)
chardet_names(monkeypatch, named)
(tmp_path / "requirements.txt").write_bytes(EBCDIC)
calls = []
execute_install_script = load_execute_install_script(manager_util, calls)
with pytest.raises(UnicodeDecodeError) as error:
execute_install_script("https://example.invalid/pack", str(tmp_path))
assert str(error.value) == "'charmap' codec can't decode byte 0x81 in position 1: character maps to <undefined>"
assert calls == []
def test_requirements_with_carriage_return_line_ends_install(tmp_path, monkeypatch):
manager_util = ansi_manager_util(monkeypatch)
chardet_names(monkeypatch, "utf-8")
(tmp_path / "requirements.txt").write_bytes("pandas\r# 依存関係\r".encode("utf-8"))
assert install(manager_util, tmp_path) == [["pip", "install", "pandas"]]
def test_the_install_at_startup_takes_the_requirements_chardet_reads(tmp_path, monkeypatch):
manager_util = ansi_manager_util(monkeypatch)
chardet_names(monkeypatch, "ISO-8859-5")
(tmp_path / "requirements.txt").write_bytes(MAC_ROMAN)
calls = []
load_install_at_startup(manager_util, calls)(str(tmp_path), sys.executable)
assert calls == [["pip", "install", "rich"]]
+7 -16
View File
@@ -1422,9 +1422,10 @@ INSTALLED_BEFORE_A_REINSTALL = {
}
def cm_cli_reinstall(installed, spec):
def cm_cli_reinstall(installed, spec, before=''):
data = run(f'''
import io
{before}
{INSTALLED_BEFORE_A_REINSTALL[installed]}
registry_with_every_version()
clone_stand_in()
@@ -1451,23 +1452,13 @@ def test_cm_cli_reinstall_without_a_version_clones_the_nightly_that_is_installed
assert cm_cli_reinstall(installed, spec) == ('[NIGHTLY]', 'the clone')
NODE_LIST_LACKS_IT = "NODE_LIST[:] = [x for x in NODE_LIST if x['reference'] != FOO_URL]"
@pytest.mark.parametrize('installed', ['the_nightly_clone', 'a_disabled_nightly_clone'])
@pytest.mark.parametrize('spec', ['comfyui-foo', 'https://github.com/example/ComfyUI-Foo'], ids=['by-id', 'by-url'])
def test_cm_cli_reinstall_without_a_version_keeps_a_nightly_clone_that_the_node_list_lacks(spec, installed):
data = run(f'''
import io
NODE_LIST[:] = [x for x in NODE_LIST if x['reference'] != FOO_URL]
{INSTALLED_BEFORE_A_REINSTALL[installed]}
registry_with_every_version()
clone_stand_in()
reload()
before = files(nodes)
out = io.StringIO()
cm_cli_reinstall_node(out)({spec!r})
emit({{'out': out.getvalue(), 'same': before == files(nodes)}})
''')
assert "Node 'comfyui-foo@nightly' not found" in data['out']
assert data['same']
def test_cm_cli_reinstall_without_a_version_clones_a_nightly_that_only_the_registry_lists(spec, installed):
assert cm_cli_reinstall(installed, spec, before=NODE_LIST_LACKS_IT) == ('[NIGHTLY]', 'the clone')
def test_cm_cli_reinstall_without_a_version_keeps_a_version_that_the_registry_no_longer_has():
+19 -4
View File
@@ -87,10 +87,11 @@ def assigned(name):
if isinstance(n, ast.Assign) and [t.id for t in n.targets if isinstance(t, ast.Name)] == [name])
def writing_loggers(stdout, stderr, log_file):
def writing_loggers(stdout, stderr, log_file, strip=True):
return loggers(stdout, stderr, log_file=log_file, log_lock=threading.Lock(), std_log_lock=threading.Lock(),
current_timestamp=lambda: "12:00:00", write_stdout=stdout.write, write_stderr=stderr.write,
re=re, pat_tqdm=assigned("pat_tqdm"), message_collapses=[], is_start_mode=False)
re=re, pat_tqdm=assigned("pat_tqdm"), pat_ansi=assigned("pat_ansi"),
strip_ansi_file_logging=strip, message_collapses=[], is_start_mode=False)
def recording_stream():
@@ -98,10 +99,10 @@ def recording_stream():
return SimpleNamespace(write=written.append, flush=lambda: None), written
def writing_logger(log_file):
def writing_logger(log_file, strip=True):
"""The stderr logger with what its writes need, and the list of what reached the console."""
stream, console = recording_stream()
_, err = writing_loggers(stream, stream, log_file)
_, err = writing_loggers(stream, stream, log_file, strip)
return err, console
@@ -270,6 +271,20 @@ def test_open_log_file_gets_what_is_written():
assert console == ["first\n"]
@pytest.mark.parametrize("strip, file_text", [
(True, "colored\n"),
(False, "\x1b[32mcolored\x1b[0m\n"),
])
def test_file_logging_strips_ansi_codes_and_the_console_keeps_them(strip, file_text):
log_file = LogFile()
logger, console = writing_logger(log_file, strip)
logger.sync_write("\x1b[32mcolored\x1b[0m\n")
assert log_file.written == [file_text]
assert console == ["\x1b[32mcolored\x1b[0m\n"]
def test_closed_log_file_is_left_alone():
log_file = LogFile(closed=True)
logger, console = writing_logger(log_file)
+3 -1
View File
@@ -374,6 +374,7 @@ class HtmlByDesignSinkTest(unittest.TestCase):
"custom-nodes-manager.js": {
'`Failed to get custom node mappings: ${sanitizeHTML(String(res.error))}`);',
'`Failed to get workflow data: ${sanitizeHTML(String(result.error))}`);',
'res.status === 403 && res.detail ? sanitizeHTML(res.detail) : "Failed to get custom node list.");',
},
"node-usage-analyzer.js": {'sanitizeHTML(String(result.error)));'},
}
@@ -415,7 +416,8 @@ class HtmlByDesignSinkTest(unittest.TestCase):
"node-usage-analyzer.js": common | {
"errorMsg = `'${sanitizeHTML(String(item.name))}': `;", queue_error,
},
"common.js": common | {"errorMsg = `'${displayTitle}': `;"},
"common.js": common | {"errorMsg = `'${displayTitle}': `;",
"errorMsg = `Couldn't start the uninstall queue (HTTP ${startRes.status}). Nothing was uninstalled.\\n`;"},
}
mutations = re.compile(r"(?<![\w$.])errorMsg\s*(?:[+*/%&|^?-]*=(?!=)|\+\+|--)[^;]*;")
for name, statements in expected.items():
+23
View File
@@ -0,0 +1,23 @@
import pytest
from test_default_channel import COMFY_ORG, run
ROUTES = ['fetch_customnode_list', 'fetch_customnode_mappings', 'fetch_externalmodel_list']
@pytest.mark.parametrize('route', ROUTES)
def test_a_request_without_mode_is_answered_as_mode_cache(route):
without, cache, local = run(f'''
import re
configure(None, {COMFY_ORG!r})
start()
handler = server({route!r})
handler.update(nodes=SimpleNamespace(NODE_CLASS_MAPPINGS={{}}), re=re, check_model_installed=lambda listed: None)
def ask(**query):
return json.loads(asyncio.run(handler[{route!r}](SimpleNamespace(rel_url=SimpleNamespace(query=query)))).text)
emit([ask(), ask(mode='cache'), ask(mode='local')])
''')
assert without == cache != local
+58
View File
@@ -0,0 +1,58 @@
import ast
import concurrent.futures
import os
from types import SimpleNamespace
import pytest
from manager_test_utils import GLOB_DIR
KEYS = ("checkpoints", "controlnet")
def installed(tmp_path, save_path, file):
folders = {key: [str(tmp_path / "models" / key), str(tmp_path / "extra" / key)] for key in KEYS}
path = tmp_path / file
path.parent.mkdir(parents=True)
path.write_bytes(b"")
def get_full_path(key, name):
return next((os.path.join(folder, name) for folder in folders.get(key, [])
if os.path.isfile(os.path.join(folder, name))), None)
def get_filename_list(key):
return [os.path.relpath(os.path.join(root, name), folder)
for folder in folders.get(key, []) for root, _, names in os.walk(folder) for name in names]
folder_paths = SimpleNamespace(models_dir=str(tmp_path / "models"),
folder_names_and_paths={key: (paths, set()) for key, paths in folders.items()},
get_folder_paths=lambda key: folders[key],
get_filename_list=get_filename_list, get_full_path=get_full_path)
source = (GLOB_DIR / "manager_server.py").read_text(encoding="utf-8")
nodes = [node for node in ast.parse(source).body
if isinstance(node, ast.FunctionDef) and node.name == "check_model_installed"]
assert len(nodes) == 1
namespace = {"os": os, "concurrent": concurrent, "folder_paths": folder_paths, "model_dir_name_map": {}}
exec(compile(ast.Module(nodes, []), "<check_model_installed>", "exec"), namespace)
row = {"name": "m", "type": "checkpoint", "base": "SD1.5", "save_path": save_path,
"filename": "model.safetensors", "url": "https://example.invalid/model.safetensors"}
namespace["check_model_installed"]({"models": [row]})
return row.get("installed")
def test_model_in_a_subfolder_of_an_extra_model_path_is_installed(tmp_path):
assert installed(tmp_path, "checkpoints/SD1.5", "extra/checkpoints/SD1.5/model.safetensors") == "True"
@pytest.mark.parametrize("save_path, file, expected", [
("checkpoints/SD1.5", "models/checkpoints/SD1.5/model.safetensors", "True"),
("checkpoints/SD1.5", "extra/checkpoints/model.safetensors", "True"),
("RGT/RGT", "models/RGT/RGT/model.safetensors", "True"),
("checkpoints/SD1.5", "extra/checkpoints/SDXL/model.safetensors", "False"),
("checkpoints/SD1.5", "extra/controlnet/SD1.5/model.safetensors", "False"),
("RGT/RGT", "extra/RGT/RGT/model.safetensors", "False"),
], ids=["install folder", "top of an extra folder", "folder of no key", "other subfolder", "folder of another key",
"extra folder of no key"])
def test_other_layouts_keep_their_state(tmp_path, save_path, file, expected):
assert installed(tmp_path, save_path, file) == expected
+101
View File
@@ -0,0 +1,101 @@
// Run with: node --test tests/test_node_conflicts.cjs
// Exercise the actual UI method without importing ComfyUI or starting a server.
const { readFileSync } = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const test = require('node:test');
const assert = require('node:assert/strict');
const source = readFileSync(path.join(__dirname, '../js/custom-nodes-manager.js'), 'utf8');
const start = source.indexOf('\tasync loadNodes(node_packs) {');
const end = source.indexOf('\n\trenderSelected()', start);
assert.ok(start >= 0 && end > start, 'loadNodes method boundaries must exist');
const method = source.slice(start, end);
async function load(packs, data = { A: [['Shared'], {}], B: [['Shared'], {}] }) {
const manager = vm.runInNewContext(`({ showStatus() {}, ${method} })`, {
manager_instance: { datasrc_combo: { value: 'cache' } },
fetchData: async () => ({ data }),
console,
});
await manager.loadNodes(packs);
}
function pack(key, state) {
return { key, state, title: key, hash: key };
}
for (const inactive of ['not-installed', 'disabled']) {
test(`enabled pack ignores ${inactive} peer; inactive pack retains preview`, async () => {
const packs = { A: pack('A', 'enabled'), B: pack('B', inactive) };
await load(packs);
assert.equal(packs.A.conflicts, 0);
assert.equal(packs.A.potentialConflicts, 0);
assert.equal(packs.B.conflicts, 0);
assert.equal(packs.B.potentialConflicts, 1);
assert.equal(packs.B.nodesMap.Shared.potentialConflicts[0].key, 'A');
assert.equal(packs.B.nodes, 1);
});
}
test('two enabled packs have symmetric conflicts, not potential conflicts', async () => {
const packs = { A: pack('A', 'enabled'), B: pack('B', 'enabled') };
await load(packs);
for (const key of ['A', 'B']) {
assert.equal(packs[key].conflicts, 1);
assert.equal(packs[key].potentialConflicts, 0);
assert.equal(packs[key].nodesMap.Shared.conflicts.length, 1);
assert.notEqual(packs[key].nodesMap.Shared.conflicts[0].key, key);
}
});
test('inactive catalog packs do not conflict with each other', async () => {
const packs = { A: pack('A', 'disabled'), B: pack('B', 'not-installed') };
await load(packs);
for (const p of Object.values(packs)) {
assert.equal(p.conflicts, 0);
assert.equal(p.potentialConflicts, 0);
assert.equal(p.nodesList.length, 1);
}
});
test('mixed catalog only lists enabled peers and deduplicates node names', async () => {
const packs = { A: pack('A', 'enabled'), B: pack('B', 'enabled'), C: pack('C', 'disabled') };
await load(packs, { A: [['Shared', 'Shared', 'Unique'], {}], B: [['Shared'], {}], C: [['Shared'], {}] });
assert.equal(packs.A.nodes, 2);
assert.equal(packs.A.conflicts, 1);
assert.equal(packs.A.nodesMap.Shared.conflicts.length, 1);
assert.equal(packs.A.nodesMap.Shared.conflicts[0].key, 'B');
assert.equal(packs.C.conflicts, 0);
assert.equal(packs.C.potentialConflicts, 1);
assert.equal(packs.C.nodesMap.Shared.potentialConflicts.length, 2);
});
test('reload after disabling a peer clears previous active conflicts', async () => {
const packs = { A: pack('A', 'enabled'), B: pack('B', 'enabled') };
await load(packs);
packs.B.state = 'disabled';
await load(packs);
assert.equal(packs.A.conflicts, 0);
assert.equal(packs.A.nodesMap.Shared.conflicts, undefined);
assert.equal(packs.B.conflicts, 0);
assert.equal(packs.B.potentialConflicts, 1);
packs.B.state = 'enabled';
await load(packs);
assert.equal(packs.B.conflicts, 1);
assert.equal(packs.B.potentialConflicts, 0);
});
test('a single enabled pack and unrelated catalog mapping have no conflicts', async () => {
const packs = { A: pack('A', 'enabled') };
await load(packs);
assert.equal(packs.A.conflicts, 0);
assert.equal(packs.A.potentialConflicts, 0);
});
test('URL basename and title fallback still resolve pack mappings', async () => {
const packs = { A: pack('A', 'enabled'), B: pack('B', 'disabled') };
await load(packs, { 'https://example.invalid/A': [['Shared'], {}], other: [['Shared'], { title_aux: 'B' }] });
assert.equal(packs.A.conflicts, 0);
assert.equal(packs.B.potentialConflicts, 1);
});
+111
View File
@@ -0,0 +1,111 @@
import json
import os
import re
from html.parser import HTMLParser
from pathlib import Path
import pytest
from js_lift import NODE, JsSource, run_node, slice_braced, slice_object_entry
JS = JsSource(Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "js")))
MANAGER = "custom-nodes-manager.js"
pytestmark = pytest.mark.skipif(NODE is None, reason="node is required to execute the lifted production JS")
class NodesFlyover(HTMLParser):
def __init__(self):
super().__init__()
self.nodes = {}
self.open = []
self.row = None
def handle_starttag(self, tag, attrs):
if tag == "div":
self.open.append((dict(attrs).get("class") or "").split())
def handle_endtag(self, tag):
if tag == "div":
self.open.pop()
def handle_data(self, data):
if self.open and "cn-nodes-name" in self.open[-1]:
self.row = data
self.nodes[data] = []
elif self.open and "cn-nodes-pack" in self.open[-1] and self.row is not None:
self.nodes[self.row].append(data)
def shown(packs, mappings):
source = JS.text(MANAGER)
column = slice_object_entry(source, 'id: "nodes",')
script = """
%s
%s
const formatter = %s;
const manager_instance = {datasrc_combo: {value: 'cache'}};
const fetchData = async () => ({data: %s});
const manager = {
showStatus() {},
flyover: {show(title, body) { manager.body = body; }},
%s,
%s
};
const packs = %s;
await manager.loadNodes(packs);
const rows = {};
for (const [key, rowItem] of Object.entries(packs)) {
manager.body = '';
manager.showNodes({rowItem});
rows[key] = {column: String(formatter(null, rowItem, {})), flyover: manager.body};
}
console.log(JSON.stringify(rows));
""" % (JS.lift_declaration("common.js", "export function sanitizeHTML("),
JS.lift_declaration("common.js", "export const icons = "),
column[column.index("formatter:") + len("formatter:"):].strip(),
json.dumps(mappings),
slice_braced(source, "\tasync loadNodes(node_packs) "),
JS.lift_span(MANAGER, "\tshowNodes(d) {", "\t\tthis.flyover.show(titleHtml, bodyHtml);\n\t}"),
json.dumps({key: {"key": key, "title": key, "hash": key, "state": "enabled"} for key in packs}))
view = {}
for key, row in run_node(script).items():
flyover = NodesFlyover()
flyover.feed(row["flyover"])
view[key] = {"column": " ".join(re.sub(r"<[^>]+>", " ", row["column"]).split()), "nodes": flyover.nodes}
return view
def test_the_nodes_of_both_mappings_are_shown_and_each_conflict_names_its_peer():
view = shown(["A", "B"], {
"https://example.invalid/A": [["Shared"], {}],
"other": [["Own"], {"title_aux": "A"}],
"B": [["Shared"], {}],
})
assert view == {
"A": {"column": "2 nodes 1 conflict", "nodes": {"Shared": ["B"], "Own": []}},
"B": {"column": "1 node 1 conflict", "nodes": {"Shared": ["A"]}},
}
def test_a_node_in_both_mappings_of_a_pack_is_no_conflict_with_itself():
view = shown(["A"], {
"https://example.invalid/A": [["Shared"], {}],
"other": [["Shared"], {"title_aux": "A"}],
})
assert view == {"A": {"column": "1 node", "nodes": {"Shared": []}}}
def test_a_node_in_both_mappings_of_a_pack_names_another_pack_once():
view = shown(["A", "B"], {
"https://example.invalid/A": [["Shared"], {}],
"other": [["Shared"], {"title_aux": "A"}],
"B": [["Shared"], {}],
})
assert view == {
"A": {"column": "1 node 1 conflict", "nodes": {"Shared": ["B"]}},
"B": {"column": "1 node 1 conflict", "nodes": {"Shared": ["A"]}},
}
+112
View File
@@ -0,0 +1,112 @@
import pytest
from test_default_channel import COMFY_ORG, run
UNLISTED = 'The channel is not allowed. A channel has to be in `channels.list`.'
def needs(mode):
return ("The channel 'private' is a folder, and a folder is allowed as a channel only with `network_mode = private`. "
f'The current network_mode is `{mode}`.')
SHARE = '''
share = user / 'share'
share.mkdir()
SHARED_URL = 'https://github.com/example/ComfyUI-Shared'
(share / 'custom-node-list.json').write_text(json.dumps({'custom_nodes': [
{'author': 'example', 'title': 'ComfyUI-Shared', 'reference': SHARED_URL, 'files': [SHARED_URL], 'install_type': 'git-clone',
'description': ''}]}))
read, cloned = [], []
read_data = manager_util.get_data
async def recording(uri, silent=False):
read.append(uri)
return await read_data(uri, silent)
def repo_install(url, to_path, **kwargs):
cloned.append(url)
return core.ManagedResult('install')
manager_util.get_data = recording
core.unified_manager.repo_install = repo_install
def install(channel):
result = asyncio.run(core.unified_manager.install_by_id('ComfyUI-Shared', 'unknown', channel, 'cache'))
return [result.result, result.msg]
def of_the_share():
return sorted(os.path.basename(uri) for uri in read if uri.startswith(str(share)))
def listed():
handler = server('fetch_customnode_list')['fetch_customnode_list']
return asyncio.run(handler(SimpleNamespace(rel_url=SimpleNamespace(query={'mode': 'cache'}))))
'''
def test_a_folder_that_channels_list_names_is_a_channel_of_a_private_network():
data = run(SHARE + f'''
configure(share, {COMFY_ORG!r}, 'network_mode = private')
with open(user / 'channels.list', 'a') as f:
f.write(f'private::{{share}}\\n')
start()
listed = answer('fetch_customnode_list', mode='cache')
emit({{'listed': [listed['channel'], list(listed['node_packs'])], 'selected': answer('get_channel_url_list')['selected'],
'installed': install('private'), 'cloned': cloned}})
''')
assert data == {'listed': ['private', ['ComfyUI-Shared']], 'selected': 'private', 'installed': [True, None],
'cloned': ['https://github.com/example/ComfyUI-Shared']}
@pytest.mark.parametrize('channel', ['str(share)', "'\\\\\\\\attacker\\\\share'"], ids=['folder', 'UNC'])
def test_a_request_cannot_name_a_folder_that_channels_list_does_not_have(channel):
data = run(SHARE + f'''
configure(None, {COMFY_ORG!r}, 'network_mode = private')
start()
read.clear()
channel = {channel}
emit({{'installed': install(channel), 'cloned': cloned, 'read': read}})
''')
assert data == {'installed': [False, UNLISTED], 'cloned': [], 'read': []}
@pytest.mark.parametrize('lines', [('network_mode = private',), ()], ids=['private', 'public'])
def test_a_folder_that_only_config_ini_names_is_refused(lines):
data = run(SHARE + f'''
configure(share, {COMFY_ORG!r}, *{lines!r})
start()
response = listed()
emit({{'listed': [response.status, response.text], 'read': of_the_share()}})
''')
assert data == {'listed': [403, UNLISTED], 'read': []}
@pytest.mark.parametrize('lines,mode', [((), 'public'), (('network_mode = offline',), 'offline')], ids=['public', 'offline'])
def test_a_folder_on_another_network_is_refused_with_the_setting_it_needs(lines, mode):
data = run(SHARE + f'''
configure(share, {COMFY_ORG!r}, *{lines!r})
with open(user / 'channels.list', 'a') as f:
f.write(f'private::{{share}}\\n')
start()
response = listed()
emit({{'listed': [response.status, response.text], 'installed': install('private'), 'cloned': cloned, 'read': of_the_share()}})
''')
assert data == {'listed': [403, needs(mode)], 'installed': [False, needs(mode)], 'cloned': [], 'read': []}
def test_the_start_warns_of_a_folder_on_a_public_network_and_completes():
data = run(SHARE + f'''
configure(share, {COMFY_ORG!r})
with open(user / 'channels.list', 'a') as f:
f.write(f'private::{{share}}\\n')
warned = []
logging.getLogger().addHandler(type('Recorder', (logging.Handler,), {{'emit': lambda self, record: warned.append(record.getMessage())}})())
failed = start()
emit({{'failed': failed, 'warned': [message for message in warned if 'network_mode' in message], 'read': of_the_share()}})
''')
assert data == {'failed': None, 'warned': [f'[ComfyUI-Manager] {needs("public")}'], 'read': []}
+23
View File
@@ -0,0 +1,23 @@
"""The Update button of a nodepack that is only in the registry, through the real get_unified_total_nodes."""
from test_flagged_nodepack_policy import run
def test_registry_only_rows_offer_update_only_for_an_older_version():
data = run('''
manager.reload = AsyncMock()
manager.get_custom_nodes = AsyncMock(return_value={})
core.flag_invalid_installation = lambda *a, **k: None
packs = ('active-1.0.0', 'active-nightly', 'active-2.0.0', 'disabled-1.0.0', 'not-installed')
for pack in packs:
manager.cnr_map[pack] = {'id': pack, 'name': pack, 'publisher': {'name': 'p'},
'latest_version': {'version': '2.0.0'}}
manager.active_nodes['active-1.0.0'] = ('1.0.0', str(nodes / 'active-1.0.0'))
manager.active_nodes['active-nightly'] = ('nightly', str(nodes / 'active-nightly'))
manager.active_nodes['active-2.0.0'] = ('2.0.0', str(nodes / 'active-2.0.0'))
manager.cnr_inactive_nodes['disabled-1.0.0'] = {'1.0.0': str(nodes / '.disabled/disabled-1.0.0')}
rows = asyncio.run(core.get_unified_total_nodes(core.DEFAULT_CHANNEL, 'cache'))
print(json.dumps({pack: rows[pack].get('update-state') for pack in packs}))
''')
assert data == {'active-1.0.0': 'true', 'active-nightly': 'false', 'active-2.0.0': 'false',
'disabled-1.0.0': 'false', 'not-installed': 'false'}
File diff suppressed because it is too large Load Diff
+86
View File
@@ -0,0 +1,86 @@
"""Uninstall Selected of the Node Usage Analyzer queues the selected nodepacks and starts the queue.
The cases run the shipped `uninstallNodes` of common.js in node, on the rows that the shipped code of
node-usage-analyzer.js makes from two installed nodepacks as `/customnode/getlist` gives them: one that only the
registry lists, which comes without an `id`, and one of custom-node-list.json. A stand-in for the API records each
request that changes the queue and answers the start of the queue as the case says.
"""
import json
import os
from pathlib import Path
import pytest
from js_lift import NODE, JsSource, run_node, slice_braced
from test_workflow_node_scan import in_any_order
JS = JsSource(Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "js")))
pytestmark = pytest.mark.skipif(NODE is None, reason="node is required to execute the lifted production JS")
NODEPACKS = {"comfyui-registry-only": {"title": "Registry only", "state": "enabled", "version": "1.0.0"},
"comfyui-listed": {"id": "comfyui-listed", "title": "Listed", "state": "enabled", "version": "nightly"}}
JSON_POST = {"method": "POST", "content_type": "application/json"}
def uninstall_selected(start_status):
"""Select both rows and confirm Uninstall Selected; return the requests, the result and the messages."""
script = """
const requests = [], messages = [];
const api = {fetchApi: async (route, options = {}) => {
if(route === '/manager/queue/status') {
return {status: 200, json: async () => ({is_processing: false})};
}
const request = {route, method: (options.method || 'GET').toUpperCase(),
content_type: new Headers(options.headers).get('Content-Type')};
if(options.body) {
request.id = JSON.parse(options.body).id ?? null;
}
requests.push(request);
return {status: route === '/manager/queue/start' ? %s : 200, text: async () => ''};
}};
const customConfirm = async () => true;
const show_message = (text) => messages.push(text);
const showTerminal = () => {};
const md5 = (text) => 'md5 of ' + text;
%s
%s
const node_packs = %s;
const result = {};
const models = [];
%s);
const answer = await uninstallNodes(models);
console.log(JSON.stringify({requests, success: answer.success, messages}));
""" % (
json.dumps(start_status),
JS.lift_declaration("common.js", "export function sanitizeHTML("),
JS.lift_declaration("common.js", "export async function uninstallNodes(nodeList, options = {})"),
json.dumps(NODEPACKS),
slice_braced(JS.text("node-usage-analyzer.js"), "Object.keys(node_packs).forEach((packKey, index) => "),
)
return run_node(script)
def test_the_selected_nodepacks_are_queued_by_their_names_and_the_queue_is_started():
seen = uninstall_selected(start_status=200)
first, *queued, last = seen["requests"]
assert first == {"route": "/manager/queue/reset", **JSON_POST}
assert in_any_order(queued) == in_any_order([
{"route": "/manager/queue/uninstall", **JSON_POST, "id": "comfyui-registry-only"},
{"route": "/manager/queue/uninstall", **JSON_POST, "id": "comfyui-listed"}])
assert last == {"route": "/manager/queue/start", **JSON_POST}
assert seen["success"] is True
assert seen["messages"] == []
def test_a_queue_that_is_already_running_counts_as_started():
assert uninstall_selected(start_status=201)["success"] is True
@pytest.mark.parametrize("status", [400, 502])
def test_a_queue_that_does_not_start_is_reported(status):
seen = uninstall_selected(start_status=status)
assert seen["success"] is False
assert [("HTTP %d" % status) in message for message in seen["messages"]] == [True]
+170
View File
@@ -0,0 +1,170 @@
"""RED->GREEN guard for the Version column's CNR update badge (issue #3272).
WHY
---
The Custom Nodes grid's Version column used to decide whether to render the
``[↑x.y.z]`` update badge with a bare string inequality:
if(rowItem.cnr_latest && version != rowItem.cnr_latest) {
String comparison says ``"1.47.0" != "1.78.1"``, so a node installed at
1.78.1 was flagged as updatable to 1.47.0 -- exactly the report in #3272,
confirmed by maintainers there. The backend never had this bug:
``is_updatable`` in glob/manager_core.py compares ``packaging`` versions via
``safe_version``. The fix adds a module-level ``compareVersionSpecs`` helper
to js/custom-nodes-manager.js and gates the badge on the registry version
being PROVABLY newer (cmp === 1); when either spec is not fully numeric
("nightly", "1.2.3rc1", ...) the helper returns null, and the formatter
follows the server's update-state for an enabled nodepack and keeps the legacy
string behavior for any other row.
A side effect pinned here: glob/manager_core.py injects ``cnr_latest =
'0.0.0'`` when the registry has no ``latest_version``. Under the string
inequality that rendered a nonsensical ``[↑0.0.0]`` badge on every such row;
under the numeric compare 0.0.0 is simply older than the install, so no
badge.
REPRODUCE THE RED HALF against the pre-fix revision -- one command:
mkdir -p /some/dir
git show <base>:js/custom-nodes-manager.js > /some/dir/custom-nodes-manager.js
git show <base>:js/common.js > /some/dir/common.js
MANAGER_JS_DIR=/some/dir pytest tests/test_version_badge_semver.py
"""
import json
import os
import unittest
from pathlib import Path
from js_lift import NODE, JsSource, run_node, slice_braced, slice_object_entry
REPO_ROOT = Path(__file__).resolve().parent.parent
JS = JsSource(os.environ.get("MANAGER_JS_DIR") or (REPO_ROOT / "js"))
MANAGER = "custom-nodes-manager.js"
COMMON = "common.js"
VERSION_ANCHOR = "id: 'version',"
HELPER_MARKER = "function compareVersionSpecs"
def _helper_source() -> str:
"""The module-level compareVersionSpecs, lifted from the shipped file."""
return slice_braced(JS.text(MANAGER), HELPER_MARKER)
def _version_formatter() -> str:
"""The Version column formatter, lifted verbatim out of its array entry."""
block = slice_object_entry(JS.text(MANAGER), VERSION_ANCHOR)
marker = "formatter:"
return block[block.index(marker) + len(marker):].strip()
def _sanitize_html_source() -> str:
return JS.lift_declaration(COMMON, "export function sanitizeHTML(")
def _render(formatter_source: str, installed, cnr_latest, **row) -> str:
script = "\n".join([
_sanitize_html_source(),
_helper_source(),
"const formatter = %s;" % (formatter_source,),
"const rowItem = %s;" % json.dumps({"cnr_latest": cnr_latest, "originalData": {"id": "x"}, **row}),
"console.log(JSON.stringify({markup: String(formatter(%s, rowItem, {}))}));"
% json.dumps(installed),
])
return run_node(script)["markup"]
# The installed/cnr_latest pairs the badge decision must get right, with the
# exact markup a correct formatter returns for each.
BADGE = "<div>%s</div><div>[↑%s]</div>"
CASES = [
# (installed, cnr_latest, expected, why)
("1.78.1", "1.47.0", "1.78.1",
"issue #3272: locally newer must NOT be flagged as updatable"),
("1.47.0", "1.47.0", "1.47.0",
"equal versions: no badge"),
("1.0.0", "1.47.0", BADGE % ("1.0.0", "1.47.0"),
"registry is genuinely newer: badge kept"),
("1.78.1", "0.0.0", "1.78.1",
"manager_core's 'no latest_version' sentinel must not render [↑0.0.0]"),
("0.0.0", "1.47.0", BADGE % ("0.0.0", "1.47.0"),
"a 0.0.0 install is still older than the registry: badge kept"),
("1.2", "1.10.0", BADGE % ("1.2", "1.10.0"),
"numeric compare: 1.10.0 > 1.2 (a string compare would miss this update)"),
("1.10.0", "1.2", "1.10.0",
"numeric compare: 1.10.0 > 1.2, so no badge"),
("nightly", "1.47.0", "<div>nightly</div><div>[1.47.0]</div>",
"the nightly branch is untouched: no arrow, badge-free"),
("1.2.3rc1", "1.47.0", BADGE % ("1.2.3rc1", "1.47.0"),
"unparseable spec: legacy string behavior kept"),
]
UNORDERED_CASES = [
("2.0.0rc1", "1.47.0", "enabled", "false", "2.0.0rc1",
"a release candidate of a newer version is not behind the registry"),
("1.0.0-beta.2", "0.9.0", "enabled", "false", "1.0.0-beta.2",
"a beta of a newer version is not behind the registry"),
("1.0.0", "nightly", "enabled", "false", "1.0.0",
"a nodepack without a version in the registry has nothing to update to"),
("1.2.3rc1", "1.47.0", "enabled", "true", BADGE % ("1.2.3rc1", "1.47.0"),
"the server offers the update: badge kept"),
("1.2.3rc1", "1.47.0", "disabled", "false", BADGE % ("1.2.3rc1", "1.47.0"),
"disabled: the server has no answer, legacy string behavior kept"),
("1.78.1", "1.47.0", "enabled", "true", "1.78.1",
"versions the helper orders do not read update-state"),
]
@unittest.skipIf(NODE is None, "node is required to execute the lifted production JS")
class VersionBadgeSemverTest(unittest.TestCase):
"""The Version column formatter, lifted and executed as shipped."""
@classmethod
def setUpClass(cls):
cls.formatter = _version_formatter()
def _markup(self, installed, cnr_latest) -> str:
return _render(self.formatter, installed, cnr_latest)
def test_the_badge_follows_numeric_ordering(self):
for installed, latest, expected, why in CASES:
with self.subTest(installed=installed, cnr_latest=latest):
self.assertEqual(self._markup(installed, latest), expected, why)
def test_an_enabled_nodepack_follows_the_server_for_versions_the_helper_cannot_order(self):
for installed, latest, state, update_state, expected, why in UNORDERED_CASES:
with self.subTest(installed=installed, cnr_latest=latest, state=state):
row = {"state": state, "update-state": update_state}
self.assertEqual(_render(self.formatter, installed, latest, **row), expected, why)
@unittest.skipIf(NODE is None, "node is required to execute the lifted production JS")
class CompareVersionSpecsTest(unittest.TestCase):
"""The helper itself, lifted and executed directly."""
def _compare(self, a, b):
out = run_node(
"%s\nconsole.log(JSON.stringify({r: compareVersionSpecs(%s, %s)}));"
% (_helper_source(), json.dumps(a), json.dumps(b))
)
return out["r"]
def test_dot_separated_specs_order_numerically(self):
self.assertEqual(self._compare("1.2.10", "1.2.9"), 1)
self.assertEqual(self._compare("1.10.0", "1.9"), 1)
self.assertEqual(self._compare("1.9", "1.10.0"), -1)
self.assertEqual(self._compare("1.47.0", "1.47.0"), 0)
self.assertEqual(self._compare("1.2", "1.2.0"), 0)
def test_non_numeric_specs_return_null(self):
self.assertIsNone(self._compare("nightly", "1.47.0"))
self.assertIsNone(self._compare("1.2.3rc1", "1.47.0"))
self.assertIsNone(self._compare("1.47.0", ""))
if __name__ == "__main__":
unittest.main()
+22
View File
@@ -1,4 +1,5 @@
import ast
import importlib.util
import json
import logging
import os
@@ -417,6 +418,27 @@ def test_reserved_switch_that_fails_leaves_no_archive(switch, tmp_path):
assert archives(custom_nodes) == []
def test_reserved_switch_whose_download_fails_leaves_no_archive(monkeypatch, tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0'), custom_nodes / 'fixture@2_0_0'
def download(url, directory, name):
for part in (name, name + '.aria2'):
(custom_nodes / part).write_text('a part of the archive')
raise Exception('the download failed')
spec = importlib.util.spec_from_file_location('_manager_downloader_under_test', GLOB_DIR / 'manager_downloader.py')
downloader = importlib.util.module_from_spec(spec)
spec.loader.exec_module(downloader)
downloader.download_url = download
switch = startup_functions(lambda name, module: monkeypatch.setitem(sys.modules, name, module), manager_downloader=downloader)['execute_lazy_cnr_switch']
with pytest.raises(Exception, match='the download failed'):
switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert sorted(os.listdir(custom_nodes)) == ['fixture@1_0_0', 'removed.py']
def test_switch_at_once_that_fails_leaves_no_archive(tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
(old_version(custom_nodes, 'fixture') / '.tracking').unlink()
+118
View File
@@ -0,0 +1,118 @@
"""What `/customnode/get_node_types_in_workflows` answers about the saved workflows.
Each case runs the real handler of `glob/manager_server.py` on workflow files in a folder of its own.
"""
import ast
import asyncio
import builtins
import codecs
import gc
import glob
import json
import logging
import os
import traceback
import warnings
from types import SimpleNamespace
import pytest
from aiohttp import web
from test_json_body_content_type import functions
SUBGRAPH, NESTED_SUBGRAPH = "5eb5cfa6-f140-40b7-0000-000000000001", "5eb5cfa6-f140-40b7-0000-000000000002"
def open_as_on_windows(file, mode="r", *args, encoding=None, **options):
if "b" not in mode and encoding is None:
encoding = "cp1252"
return builtins.open(file, mode, *args, encoding=encoding, **options)
def node(number, kind, nodepack):
return {"id": number, "type": kind, "properties": {"cnr_id": nodepack}}
def subgraph_node(number, subgraph):
return {"id": number, "type": subgraph, "properties": {}}
def in_any_order(nodes):
return sorted(nodes, key=lambda found: json.dumps(found, sort_keys=True))
def scan(folder, workflows):
"""The node types that are answered for each workflow file."""
saved = folder / "default" / "workflows"
saved.mkdir(parents=True)
for name, workflow in workflows.items():
(saved / name).write_bytes(workflow if isinstance(workflow, bytes) else json.dumps(workflow).encode("utf-8"))
routes = web.RouteTableDef()
namespace = {
"web": web, "os": os, "json": json, "glob": glob, "logging": logging, "traceback": traceback,
"open": open_as_on_windows, "routes": routes,
"folder_paths": SimpleNamespace(get_user_directory=lambda: str(folder)),
"PromptServer": SimpleNamespace(instance=SimpleNamespace(
routes=routes, user_manager=SimpleNamespace(get_request_user_id=lambda request: "default")))}
defined = list(functions("manager_server.py").values())
exec(compile(ast.Module(body=defined, type_ignores=[]), "manager_server.py", "exec"), namespace)
response = asyncio.run(namespace["get_node_types_in_workflows"](None))
assert response.status == 200
return {answer["workflow_file_name"]: in_any_order(answer["node_types"]) for answer in json.loads(response.text)}
def test_the_nodes_inside_a_subgraph_and_inside_a_subgraph_of_it_are_answered(tmp_path):
workflow = {
"nodes": [node(1, "KSampler", "comfy-core"), subgraph_node(2, SUBGRAPH)],
"definitions": {"subgraphs": [
{"id": SUBGRAPH, "nodes": [node(10, "UnetLoaderGGUF", "comfyui-gguf"), subgraph_node(11, NESTED_SUBGRAPH)]},
{"id": NESTED_SUBGRAPH, "nodes": [node(20, "ImageResizeKJv2", "comfyui-kjnodes")]}]}}
assert scan(tmp_path, {"subgraph.json": workflow}) == {"subgraph.json": in_any_order([
{"type": "KSampler", "cnr_id": "comfy-core"},
{"type": "UnetLoaderGGUF", "cnr_id": "comfyui-gguf"},
{"type": "ImageResizeKJv2", "cnr_id": "comfyui-kjnodes"}])}
def test_a_subgraph_that_holds_itself_is_answered_once(tmp_path):
workflow = {
"nodes": [subgraph_node(1, SUBGRAPH)],
"definitions": {"subgraphs": [
{"id": SUBGRAPH, "nodes": [node(10, "UnetLoaderGGUF", "comfyui-gguf"), subgraph_node(11, SUBGRAPH)]}]}}
assert scan(tmp_path, {"holds_itself.json": workflow}) == {
"holds_itself.json": [{"type": "UnetLoaderGGUF", "cnr_id": "comfyui-gguf"}]}
def test_a_workflow_with_a_node_that_is_not_an_object_is_answered_without_that_node(tmp_path):
workflow = {"nodes": [None, node(1, "KSampler", "comfy-core"), node(2, "VHS_VideoCombine", "comfyui-videohelpersuite")]}
assert scan(tmp_path, {"null_node.json": workflow}) == {"null_node.json": in_any_order([
{"type": "KSampler", "cnr_id": "comfy-core"},
{"type": "VHS_VideoCombine", "cnr_id": "comfyui-videohelpersuite"}])}
def test_a_type_or_a_cnr_id_that_is_not_text_is_left_out(tmp_path):
workflow = {"nodes": [{"id": 1, "type": "Foo", "properties": {"cnr_id": 5}},
{"id": 2, "type": ["x"], "properties": {"cnr_id": "comfyui-x"}}]}
assert scan(tmp_path, {"odd_values.json": workflow}) == {"odd_values.json": [{"type": "Foo"}]}
@pytest.mark.parametrize("byte_order_mark", [b"", codecs.BOM_UTF8])
def test_a_workflow_is_read_as_utf8_whatever_the_default_encoding_is(tmp_path, byte_order_mark):
workflow = {"extra": {"title": "Łukasz ✨ 中文 “quote”"}, "nodes": [node(1, "WanVideoSampler", "comfyui-wanvideowrapper")]}
saved = byte_order_mark + json.dumps(workflow, ensure_ascii=False).encode("utf-8")
assert scan(tmp_path, {"non_ascii.json": saved}) == {
"non_ascii.json": [{"type": "WanVideoSampler", "cnr_id": "comfyui-wanvideowrapper"}]}
def test_no_workflow_file_is_left_for_the_garbage_collector_to_close(tmp_path):
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always", ResourceWarning)
answered = scan(tmp_path, {"read.json": {"nodes": [node(1, "KSampler", "comfy-core")]}, "not_json.json": b"{"})
gc.collect()
assert set(answered) == {"read.json"}
assert [str(warning.message) for warning in caught if str(tmp_path) in str(warning.message)] == []