Compare commits

...
Author SHA1 Message Date
Dr.Lt.Data b93836c527 Test that the registry request carries the form factor
The tests of this branch call `get_form_factor()` only. A request that
no longer used it, or that left `form_factor` out, passed them.

- Add a case that runs the fetch of the registry list on Linux with
  the marker of Desktop, and reads the address that is asked for
2026-12-03 09:31:59 +09:00
Dr.Lt.Data 6177db9272 Merge branch 'manager-v4' into desktop-linux-form-factor 2026-12-03 09:03:17 +09:00
Dr.Lt.Data b64a6e330b v4: aria2 does not download a file that is already there (#3648)
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 main is #3647.
2026-12-03 09:02:30 +09:00
Dr.Lt.Data 6fe5f7f98e v4: Without COMFYUI_MANAGER_ARIA2_SAME_PATHS aria2 gets the same folder on Windows as before
#3644 changed the folder that aria2 gets when the variable is not set.
For a folder under ComfyUI it put `/` before the rest of the path, and on
Windows that rest starts with a backslash: `C:\ComfyUI\models\checkpoints`
became `/\models\checkpoints`, which Windows reads as the network path
`\\models\checkpoints`. Before #3644 aria2 got `\models\checkpoints`.

- The folder under ComfyUI is made as before #3644, with
  `os.path.join('/models', ...)`. With the variable set nothing changes
- The test of the default runs on Windows as well, and expects the
  ComfyUI folder as the root in the separators of the system

The same change for main is in #2999.
2026-12-03 07:34:40 +09:00
Dr.Lt.Data 4b658361d9 v4: A download that was stopped in aria2 is reported as failed, and a failed nodepack archive is removed (#3645)
Two things that the download through aria2 still got wrong after #3246.
A download that was paused or removed in aria2 while the install waited
for it was taken as done when a part of the file was there. And when
aria2 failed in the middle of the archive of a registry nodepack, the
part that was downloaded stayed in `custom_nodes` as
`CNR_temp_<uuid>.zip`, with the control file of aria2 next to it, at an
install and at a start that carries out a reserved switch of the version.

- `aria2_download_url` fails unless aria2 has the download as complete,
  with the status of the download when aria2 gives no error message
- The install of a registry nodepack and the reserved switch remove the
  archive and the control file of aria2 when the download fails
- Add tests, and extend the CHANGELOG entry of #3246

The same change for main is in #3643.
2026-12-03 07:30:29 +09:00
Dr.Lt.DataandViolinKaine 0cf2445e51 v4: An aria2 on the same machine can be the downloader (#3644)
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 main is #2999.

Co-authored-by: ViolinKaine <125495038+ViolinKaine@users.noreply.github.com>
2026-12-02 19:33:52 +09:00
Koray Ulusan fdc9c1177d v4: --mode remote reads the channel when the Manager is installed as a pip package (#3590)
When the Manager is installed as a pip package, every mode read the
cached list of the channel, or the list that comes with the package.
`--mode remote` did not read the channel, so a nodepack that was added
to the channel after the package was built did not show.

- `get_data_by_mode` of both cores reads the list from the channel and
  caches it in remote mode on a pip install, unless `network_mode` is
  offline. `cm-cli` uses the legacy core, the server either
- When that read fails, a message says so and the list is read as cache
  mode reads it on a pip install: from the cache, else from the package
- The other modes, offline mode and installs that are not a pip package
  are unchanged
- Add tests and a CHANGELOG entry
2026-12-02 12:55:37 +09:00
Dr.Lt.Data 6c22515d55 v4: The legacy Model Manager finds a model in a subfolder of an extra model path (#3633)
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 copy of the function in `glob/utils/model_utils.py` gets the same
  check
- 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

The same change for main is #3631.
2026-12-02 12:45:43 +09:00
Reinis 86634380db v4: A download through aria2 works again, and one that fails is reported as failed (#3246)
With `COMFYUI_MANAGER_ARIA2_SERVER` set, the install of a registry
nodepack or of a model failed with `No module named 'manager_core'`:
`aria2_download_url` imported the core by its name of the main line
(#3064).

- `aria2_download_url` reads `comfy_path` from
  `comfyui_manager.common.context`, so the download goes through aria2
  again
- It waits while aria2 has the download waiting or active, and fails
  with the error message of aria2 when aria2 fails it
- 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
- Add tests and a CHANGELOG entry
2026-12-02 12:36:54 +09:00
Dr.Lt.Data aa58d0ff43 v4: A conflict in the legacy Custom Nodes Manager counts only enabled nodepacks (#3636)
The Nodes column of the legacy 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 main is #3273.
2026-12-02 09:08:02 +09:00
Dr.Lt.Data 24b27b7ea6 v4: An install without a version enables a disabled registry nodepack, and Enable fails for one the registry data does not list (#3638)
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 Enable reported
success for a disabled nodepack that the registry data does not list,
while nothing was enabled (#3469).

- `is_disabled()` of both cores 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. Enable then reports `Failed to enable: '<id>'`
- 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 main is #3528.
2026-12-02 02:34:18 +09:00
Dr.Lt.Data e2124a8585 v4: A nodepack that two node mappings name shows all its nodes in the legacy Custom Nodes Manager, and the list is drawn (#3635)
Two node mappings can name one nodepack, one by its id or git URL and
one by its `title_aux`. In the legacy 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.

- `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 conflict pass is not changed, and the Nodes Manager of the
  ComfyUI frontend does not run this code
- Add a test and a CHANGELOG entry

The same change for main is #3629.
2026-12-02 02:14:21 +09:00
Dr.Lt.Data 0f7d5f588b v4: An install from a Git URL installs the dependencies when Windows cannot read requirements.txt (#3637)
An install of a nodepack from a Git URL (Install via Git URL of the
legacy Custom Nodes Manager, `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()` in both cores: 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 main is #3520.
2026-12-02 01:54:18 +09:00
Can H. Tartanoglu d972b17712 v4: dependency_management = off turns off the changes that the Manager makes to Python packages on its own (#2851)
On a Python that cannot be changed, such as one of Nix, Guix or a
distribution, the Manager ran pip at every start and after an install.
It could uninstall `comfy`, install torch again and install the packages
of `pip_auto_fix.list`, and with `use_unified_resolver = True` the
startup batch of the resolver installed packages.

- Add `dependency_management = off` for the `[default]` section of
  `config.ini`, and `COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT=off`, which
  wins over `config.ini`. With either, none of this runs. The setting is
  on by default, and while it is unset nothing changes
- Install the requirements of an install or update that is asked for
  whatever the setting, also of one that is applied at the next restart.
  The `install.py` of a nodepack still runs
- Apply the setting in `cm-cli` as well, including the `cm-cli` that the
  startup runs to restore a snapshot
- Where the setting skips the startup batch of the resolver, turn the
  resolver off for the session, so that an install uses pip for each
  nodepack
- Say so in the README, and add tests and a CHANGELOG entry
2026-12-02 00:43:47 +09:00
Dr.Lt.Data d917f19598 v4: A nodepack that only the registry lists shows Update in the legacy Custom Nodes Manager when the registry has a newer version (#3634)
A nodepack that is in the registry and not in the node list never showed
Update in the legacy 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. The
  same lines in the glob and the legacy core
- 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
- The Nodes Manager already offered Update for such a nodepack and is
  not changed
- Add tests and a CHANGELOG entry

The same change for main is #3261.
2026-12-01 19:14:01 +09:00
H.W.Prinz de0a6111aa v4: The log file has no color codes of the console (#3466)
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 main is #3315.
2026-12-01 12:25:01 +09:00
Dr.Lt.Data 6fe0d72dc4 v4: Restore the PyTorch builds that were installed before a nodepack (#3618)
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 #3618.

The same change for main is #3617.
2026-12-01 00:14:19 +09:00
Dr.Lt.Data 7494883c93 bump version to 4.5 2026-11-30 23:42:37 +09:00
Dr.Lt.Data 347473e689 v4: Check a nightly install of the legacy Manager by the repository it clones (#3623)
- Look the repository of a nightly up by the id of the nodepack before
  the install is queued, with the lookup the install itself uses, and
  check that repository
- Refuse a nightly of a nodepack that no list has at once, where it
  failed in the queue
- Add tests and a CHANGELOG entry
2026-11-30 18:47:27 +09:00
Dr.Lt.Data 4bbdb2e95f v4: Reinstall a nodepack named without a version at the version that is installed (#3625)
`cm-cli reinstall <nodepack>` resolved a name without a version to the
latest version of the registry, whatever was installed. A reinstall of
1.0.1 left 1.0.2, and a reinstall of a nightly clone left a registry
version.

- Reinstall the registry version that is installed, enabled or disabled,
  when the nodepack is named by its id without a version; a nightly
  clone is cloned again
- Keep the latest version for a nodepack that is not installed, and what
  `@latest`, `@<version>`, `@nightly` and a URL name
- Add tests, a CHANGELOG entry and a line in the cm-cli docs

The same changes for main are #3624.
2026-11-30 18:36:08 +09:00
Dr.Lt.Data 455ad3acd0 v4: Print the values that cm-cli dropped, and a line for each counted nodepack (#3612)
cm-cli printed every line through rich, which reads a lowercase word in
square brackets as markup and drops it, and typer shows a help text the
same way.

- Print every line with the print of the core, which writes it as it
  is, and give that print a style for the lines that cm-cli colours:
  the version of `fix`, the name of a nodepack, the reason of a failed
  or skipped action, a title and an author of the node list, a
  changelog line, a path, the name of a snapshot and a requirement in
  the report of a failed resolution lost a part in square brackets, a
  path lost a backslash before a bracket, and a line longer than the
  console is wide was broken in two, at 80 columns where no terminal is
  attached
- Write the help texts that were in brackets without them: `--mode` and
  the argument of show, simple-show, update, enable, disable and fix
  showed no help
- Refuse a word that is no list in `simple-show` without the tags of a
  colour around the line
- Print a line for the Manager in `disable all` and for a disabled
  nodepack in `fix all`: each run skipped a number
- Leave `__pycache__` out of restore-dependencies
- Remove the `f` before the reason of a failed fix, and the `print("")`
  after the entry point: the `cm-cli` command imports the module, so
  each command began with an empty line
- Add tests and a CHANGELOG entry

The same changes for main are #3611.
2026-11-29 19:09:01 +09:00
Dr.Lt.Data e32d3a4a71 v4: Restore a git nodepack that a snapshot lists as disabled as disabled (#3610)
A snapshot lists each git nodepack with `disabled`, and restore_snapshot
did not read it, in either core. Since the restore moved into the core
(b3be55683), every git entry of a snapshot was enabled, checked out or
cloned: a nodepack saved as disabled came back enabled, and one removed
since was cloned again.

- Leave a git entry that is listed as disabled out of the restore, so
  that the nodepack is left disabled, is disabled when it is enabled,
  and is not cloned when it is not installed
- Keep the clone of a nodepack saved at a version of the registry as
  what is restored when that version cannot be
- List a URL as enabled in a snapshot when one of its two clones is
  enabled: the clone read last named the entry
- Add tests and a CHANGELOG entry

The same changes for main are #3609.
2026-11-29 15:04:45 +09:00
Dr.Lt.Data 899819d230 v4: Do not move a nodepack into an existing folder on disable or enable (#3614)
unified_disable and unified_enable of both cores move the folder of a
nodepack with shutil.move, which puts it inside the destination when
that is a folder that exists. With an enabled nodepack and a disabled
copy of it, a disable left `.disabled/<name>/<name>` and reported
success.

- Fail a disable or an enable whose destination exists, and leave the
  nodepack in its folder
- Disable the enabled version for another one in one place,
  `disable_for_replacement`: fail with nothing changed when anything but
  the folder of the enabled version is where the other one goes, then
  disable that version when its folder is there, and return the answer.
  unified_enable (for a version and for the nightly clone),
  install_by_id and _install_git each began with a disable whose result
  was dropped
- Stop an install when the disabled version that it enables before a
  switch cannot be enabled: it went on to switch what was in the folder
- Report a failed disable or enable to the page: the disable task of
  both servers tested the result object, which is always true, and the
  enable task dropped its result
- Print the error of an enable that failed in `cm-cli install`: it
  printed `[ ENABLED ]`
- Add tests and a CHANGELOG entry

The same changes for main are #3613.
2026-11-29 01:29:18 +09:00
Dr.Lt.Data a1b0264744 v4: Fix defects of cm-cli, the legacy Model Manager and Custom Nodes Manager, requirements.txt rows and the default channel (#3604)
While each feature of 4.4.3 was driven for its release video, some
`cm-cli` commands and some pages of the legacy Manager did not do what
they say. Each root cause has its test and its CHANGELOG entry.

cm-cli
- Print the snapshot in `show snapshot` and `simple-show snapshot`, as it
  is: both printed only a RuntimeWarning
- End `install --exit-on-fail` with exit code 1 when a nodepack could not
  be installed
- Enable the disabled nodepacks in `enable all`, take `<id>@latest` as the
  installed nodepack, and enable a disabled pre-release version
- Say `Not installed` in `disable`, `update` and `fix` for a registry
  nodepack that is not installed
- List a git nodepack that the lists do not know in `show installed`,
  `show enabled` and `show disabled`
- Tell in `deps-in-workflow` whether a registry nodepack is installed
- Restore an editable install in `restore-snapshot`
- Write the git backend line at the start of the server only: `cm-cli`
  and its shell completion no longer write it

Rows of requirements.txt
- Read a row the same way in every place that installs it, in both
  cores: a requirement with a comment is no longer one argument, and a
  URL keeps its fragment
- Apply an option to its own row only: a row with only an option no
  longer stops the rows after it
- Install an editable row as `-e` and its target
- Install a row that names a path, such as `-e .`, for each nodepack of a
  session
- With uv, install an editable git URL without `-e`, in a row and in a
  line of a snapshot

Legacy pages
- List only the models of the workflow in the In Workflow filter of the
  Model Manager, also for a file named with a folder, and apply Type and
  Base together with the Filter
- End the install in the Custom Nodes Manager when Stop drops its batch
- Refuse Try fix in the Custom Nodes Manager when the security_level does
  not allow it, and say so

Default channel and e2e
- Treat both URLs of the default channel as one channel
- Keep the Manager under test after an e2e test updates ComfyUI

The same changes for main are #3603.
2026-11-28 08:42:46 +09:00
Dr.Lt.Data 9f1faeb0f5 v4: Make torchaudio optional in the PyTorch check and restore (#3606)
ComfyUI no longer needs torchaudio, but PIPFixer.fix_broken() still
required it. On an install with torch and torchvision and without
torchaudio it logged "[ComfyUI-Manager] PyTorch is not installed" at
every start, after a cm-cli install, update or fix, and after the server
installed the requirements of a nodepack, and it never restored PyTorch
when a nodepack changed torch or torchvision.

- Require and compare only torch and torchvision in the check, so such
  an install is not reported as one without PyTorch, and a nodepack that
  changes only torchaudio starts no restore
- Name torchaudio in the restore commands only when it was installed
  before the nodepack or is installed after it, so the restore adds no
  torchaudio to an install that has none
- Add tests that run fix_broken() and check the commands it sends
- Add a CHANGELOG entry

What the restore installs is not changed: an install without torchaudio
gets the commands that an install with torchaudio gets, without
torchaudio.

The same change for main is #3388.
2026-11-27 20:13:57 +09:00
Dr.Lt.Data fef6b412fc v4: Find a registry nodepack whose id has capital letters from a workflow node, in the legacy Custom Nodes Manager (#3599)
GET /v2/customnode/installed of the legacy server gave the id of a nodepack
installed from the registry in lowercase (comfyui_sigmoidoffsetscheduler),
and a node added to a workflow took that id. The legacy Custom Nodes Manager
names the nodepack as the registry writes it (ComfyUI_SigmoidOffsetScheduler)
and did not find it from the node: Custom Nodes In Workflow showed 0 custom
nodes, and Check Missing and Install Missing Custom Nodes said "Failed to
find the following ComfyRegistry list" for the id and then listed the same
nodepack.

identify_node_pack_from_path of the legacy core now returns the name of
pyproject.toml as it is written, as that of the glob core does since
d7799964d. Workflows saved with an earlier install keep the lowercased id,
so the page also matches the id of a node without regard to case when the
list has no exact match.

workflow-metadata.js gives a new node no id when the installed list names
its nodepack comfy-core. That comparison is now made in lowercase, so that
it holds as before with the list in the spelling of pyproject.toml.

A node of ComfyUI itself has the id comfy-core. That id is looked up as it
is written only, so that Check Missing and Custom Nodes In Workflow do not
list a nodepack named Comfy-Core for a built-in node.
2026-11-26 21:56:40 +09:00
Dr.Lt.Data 780c199dc7 v4: Remove the "Alternatives of A1111" filter of the legacy Custom Nodes Manager (#3601)
The choice asked /v2/customnode/alternatives, which no server registers. The
choice, its column, GET /customnode/alternatives, the fetch of alter-list.json
and the copies of the file are removed.
2026-11-26 21:07:57 +09:00
Dr.Lt.Data 25ca413586 v4: Show the result of Update All in the legacy Manager menu (#3597)
Update All made a batch id but did not put it into the batch it sent to
/v2/manager/queue/batch. The server reported the end of that batch with
batch_id null, and the menu, which shows only the end of its own batch,
showed nothing: no result box and no RESTART button. Update All now sends
the id, as Update ComfyUI and the other senders of a batch do.

The batch of Update All Custom Nodes in the desktop app has no result for
ComfyUI, and the menu then called startsWith on null. A missing result for
ComfyUI now leaves the ComfyUI line out of the box.
2026-11-26 20:56:20 +09:00
Benjamin Lu 9c069c13c5 v4: Report desktop-linux form factor for Desktop installs on Linux
Desktop runs on Linux now, but get_form_factor mapped a Desktop install on
Linux to 'other', losing the platform in registry data.
2026-10-14 17:22:27 -07:00
84 changed files with 6767 additions and 1105 deletions
+464
View File
@@ -7,6 +7,469 @@ and this project adheres to [Semantic Versioning 2.0.0](https://semver.org/spec/
## [Unreleased]
### Added
- 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.
- `dependency_management = off` turns off the changes that the Manager makes
to Python packages on its own. On a Python that cannot be changed, such as
one of Nix, Guix or a distribution, the Manager ran pip at every start and
after an install. It could uninstall `comfy`, install torch again and
install the packages of `pip_auto_fix.list`, and with
`use_unified_resolver = True` the startup batch of the resolver installed
packages (#2851). With `dependency_management = off` in the `[default]`
section of `config.ini`, or `COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT=off`,
none of this runs, in the server or in `cm-cli`, and installs use pip for
each nodepack in place of the resolver. The environment variable wins over
`config.ini`. An install or update that is asked for, also one applied at
the next restart, still installs its requirements, and the `install.py` of
a nodepack still runs. The setting is on by default, and while it is unset
nothing changes.
### Changed
- 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
(#3466). 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`.
### Fixed
- Report the `desktop-linux` form factor to the registry for Desktop installs
on Linux, which previously reported `other`.
- 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.
- `--mode remote` reads the channel when the Manager is installed as a pip
package. On such an install every mode read the cached list, or the list
that comes with the package, so a nodepack that was added to the channel
after the package was built did not show (#3590). Remote mode now reads the
list from the channel and caches it, in `cm-cli` and in the server. When
the channel cannot be read, a message says so and the list is the one from
before: the cached list, else the list of the package. The other modes and
`network_mode = offline` are unchanged.
- The legacy 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 download through aria2 works again, and one that fails is reported as
failed. With `COMFYUI_MANAGER_ARIA2_SERVER` set, the install of a registry
nodepack or of a model failed with `No module named 'manager_core'` (#3064,
#3246). The download goes through aria2 again. The install 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 conflict in the legacy Custom Nodes Manager counts only enabled
nodepacks. The Nodes column 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. The Nodes Manager does not run this
code.
- An install without a version enables a disabled registry nodepack, and
Enable 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. **Enable** reported success for a disabled nodepack
that the registry data does not list: nothing was enabled. It now reports
`Failed to enable: '<id>'`, and the terminal says
`Specified inactive node not exists: <id>`.
- A nodepack that two node mappings name shows all its nodes in the legacy
Custom Nodes Manager, 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`. 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
Nodes Manager does not run this code.
- 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** of the legacy Custom Nodes Manager,
`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 in the legacy Custom
Nodes Manager when the registry has a newer version. A nodepack that is in
the registry and not in the node list never showed **Update** there, and
the Update filter did not list it (#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 Nodes Manager already offered **Update** for such a nodepack
and is not changed.
- 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.
## [4.5] - 2026-11-30
### Removed
- Remove the "Alternatives of A1111" choice from the Filter of the legacy
Custom Nodes Manager, with its Alternatives column and the legacy route
`GET /customnode/alternatives`. The page asked `/v2/customnode/alternatives`,
which no server registers, so the choice showed no rows and an error. Manager
no longer fetches `alter-list.json` at start or in `cm-cli update-cache`, and
no longer ships it.
### Fixed
- The legacy Manager checks the install of a nightly by the repository that
the install clones. It looks that repository up by the id of the nodepack
before the install is queued, with the lookup the install itself uses. A
nightly of a nodepack that no list has is refused at once, where it failed
in the queue.
- `cm-cli reinstall` keeps the version that is installed. `cm-cli reinstall
<nodepack>` without a version removed the nodepack and installed the latest
version of the registry, whatever was installed: 1.0.1 became 1.0.2, and a
nightly clone became a registry version. It now installs the version that is
installed, enabled or disabled, and a nightly clone is cloned again. A
nodepack that is not installed gets the latest version, and
`<nodepack>@latest`, `<nodepack>@<version>` or a URL installs what it names,
as before. When the registry no longer has the version that is installed,
the reinstall fails with `not available node: <nodepack>@<version>` and the
nodepack stays as it is; `<nodepack>@latest` installs the latest one.
- cm-cli prints a value in square brackets, and a line for each nodepack it
counts. cm-cli printed every line through rich, which reads a lowercase word
in square brackets as markup and drops it, and typer shows a help text the
same way. `cm-cli fix` named no version for a git nodepack (`[unknown]`,
`[nightly]`), and an install of an id that no list has ended with `not found
in` and nothing after it. The name of a nodepack, a reason, a title or an
author of the node list, a changelog line, a path or the name of a snapshot
lost a part in square brackets that starts with a lowercase letter, and with
`--uv-compile` the report of a failed resolution dropped the extra of a
requirement, such as `[ffmpeg]` of `opencv-python-headless[ffmpeg]`. A path
lost a backslash before a bracket. cm-cli now writes every line as it is, as
the Manager writes its own, a coloured line in its colour. A line longer than
the console is wide is no longer broken in two, which was at 80 columns where
no terminal is attached, as in a script, and a code such as `:bug:` in a
value is no longer turned into an emoji. `--help` showed no text for `--mode`
and for the argument of `show`, `simple-show`, `update`, `enable`, `disable`
and `fix`. These texts are now written without their brackets, as
`remote|local|cache`, and read the same with and without rich. `cm-cli
simple-show` refused a word that is no list with the tags of a colour around
the line: `[bold red]Invalid command: ...[/bold red]`. The reason of a failed
`cm-cli fix` had an `f` before it. `cm-cli disable all` printed no line for
the Manager and `cm-cli fix all` none for a disabled nodepack, so each
skipped a number; both print a line now, as `update all` does. `cm-cli
restore-dependencies` counted `__pycache__` as a nodepack. The `cm-cli`
command printed an empty line before the output of each command, also before
the script of `--show-completion`.
- A git nodepack that a snapshot lists as disabled is restored as disabled. A
snapshot lists each git nodepack with whether it was disabled when the
snapshot was saved, and a restore did not read that, with `cm-cli
restore-snapshot` and from the Snapshot Manager alike. A nodepack saved as
disabled was enabled when it was disabled, left enabled when it was enabled,
and cloned when it was not installed. It is now left disabled, disabled, and
not cloned. A nodepack saved at a version of the registry keeps its git clone
disabled: that clone is restored when the version could not be, as before,
where the node list of the machine that restores knows the URL of the clone.
Where a URL has an enabled and a disabled clone installed, a snapshot lists
it as enabled, with the commit of the enabled clone; it listed the clone it
read last.
- A disable or an enable does not move a nodepack into a folder that exists.
Disabling a nodepack moves its folder into `custom_nodes/.disabled`, and
enabling moves it back. Where the folder it moves to was already there, as
with an enabled nodepack and a disabled copy of it, the nodepack was moved
inside that folder (`.disabled/<name>/<name>`) and reported as disabled.
`cm-cli disable`, the Disable button of both UIs, a restore that disables a
nodepack, and an enable or an install that first disables the enabled version
all did so. The disable or enable now fails with
`Destination already exists: <folder>` and the nodepack stays in its folder.
An enable or an install that first disables the enabled version now looks at
its own folder before it does so, and stops when that version cannot be
disabled, so one that is refused changes nothing. The Disable and Enable
buttons reported success for a disable or an enable that the Manager refused;
they now report the failure, and the terminal says why. `cm-cli install`
printed its `ENABLED` line for an enable that failed; it now prints the error.
An install that first enables a disabled version stops when that enable fails;
it went on to switch the version of whatever was in the folder.
- Both URLs of the default channel,
`https://raw.githubusercontent.com/Comfy-Org/ComfyUI-Manager/main` and
`https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main`, are one
channel. The server of the new UI cached the lists under the ltdrdata URL,
while the legacy server and cm-cli used the Comfy-Org URL, so
`cm-cli update-cache` refreshed lists that the new UI never read. A first
start with the new UI writes the ltdrdata URL into `config.ini`. With that
`config.ini` the legacy Custom Nodes Manager left out every nodepack that is
only in the registry, and the channel menu of the legacy Manager showed no
channel. Both servers and cm-cli now write and read one set of cache files
under the Comfy-Org URL, whichever URL `config.ini` or `channels.list`
names, and `default` is selected. Neither file is rewritten. Lists cached
under the ltdrdata URL are no longer read: the next start fetches them
again under the Comfy-Org URL. With `network_mode = offline`, or `private`
when the start cannot reach the channel, a user who only used the new UI
reads the lists that come with the installed version until a start fetches
the lists or `cm-cli update-cache` is run.
- Every place that installs the `requirements.txt` of a nodepack line by line
reads a line the same way. In an install, an update and a fix, the legacy
core, which `cm-cli` uses, gave a requirement with a comment, such as
`pygit2>=1.18 # clone_repository(proxy=...) requires 1.18.0+` in the
Manager's own `requirements.txt`, to pip or uv as one argument, which both
refuse, so `cm-cli fix all` and `cm-cli restore-dependencies` ended with a
traceback and exit 1. Every other place cut a URL at its `#`, so
`git+https://host/repo#subdirectory=sub` installed the root of the
repository, which pip and uv refuse as no Python project. A requirement
followed by `--index-url URL` went to the installer as one argument in an
install from the registry, an update and a fix of a nodepack, `cm-cli`
included. An entry of `pip_overrides.json` did not apply to a line with a
comment there either, nor in a reserved install that runs at the next
start. Now a comment starts at a `#` at the start of the line or after
whitespace, as pip reads it, and a requirement followed by
`--index-url URL` is installed from that index in every place. A
requirement followed by another option, such as
`flash-attn --no-build-isolation`, still goes to the installer as one
argument and fails as before.
- An option in `requirements.txt` applies to its own row only. A row of the
`requirements.txt` of a nodepack that has only an option, such as
`--extra-index-url URL`, `--trusted-host host` or `-r other.txt`, went to
pip or uv as one argument, which both refuse. In an install from the
registry, an update and a fix of a nodepack, `cm-cli` included, that
failure stopped every row after it: none of them was installed, and the
nodepack was reported as failed. The Manager installs requirements one row
at a time. A row with only an option has nothing to install: it is now
left out with the line `skip '<row>': the Manager installs requirements one
row at a time and does not apply this row`, and the rows after it are
installed. `-r` and `-c` install nothing. A row `-e path` or
`--editable path` is an editable requirement and goes to the installer as
`-e` and its target, which pip and uv install as editable; before, uv
installed `-e path` and pip refused it. With a git URL, pip installs `-e`
as it is written. uv installs an editable from a local folder only, so with
uv a row `-e git+URL`, with or without index options after it, is installed
without `-e`, and a line says so; before, uv refused the row.
`--extra-index-url URL` after a requirement now goes to the installer with
that requirement, as `--index-url URL` does.
- A row of `requirements.txt` that names a path, such as `-e .`,
`-e ./local` or `./wheels/demo-1.0-py3-none-any.whl`, is installed for each
nodepack. In one session the Manager installs a row once: a row that an
earlier nodepack has installed is not installed again, and such a row
counted as the same row in every nodepack, although the installer reads the
path from the folder of each nodepack. In an install, an update and a fix
without the unified resolver, the second nodepack with such a row was
reported as done without its row being installed. A row counts as one that
names a path when an argument of it, without extras and marker, exists as a
path seen from that folder. Any other row is installed once in a session,
as before.
- `cm-cli show snapshot` and `cm-cli simple-show snapshot` print the snapshot
of the current state: as JSON with `show`, and with `simple-show` a line
with the commit hash of ComfyUI and of each git nodepack. They printed only
a `RuntimeWarning` that a coroutine was never awaited, and ended with exit
code 0. The hashes, the URLs and the JSON are written as they are, so a hash
that starts with a letter is no longer left out and a long line is not
broken.
- `cm-cli enable all` enables the disabled nodepacks. It enabled nothing and
said `Already enabled` for every nodepack, the disabled ones too: `all`
names each nodepack with its version, and a nodepack named with a version
counted as enabled and as disabled at once. `enable`, `disable`, `update`
and `fix` now look at the state of the version that is named, also in
`<id>@<version>` on the command line, so `disable all` says
`Already disabled` for a disabled registry nodepack instead of
`Not installed`, and `fix all` leaves the disabled nodepacks out instead of
printing an error for each. `<id>@latest` names no installed version, so
with it these four commands act on the installed nodepack, as with the id
alone. A disabled version with a pre-release part, such as `1.0.0-rc1`, is
enabled as well: it was named `1.0.0rc1`, which no installed version is
called, so `cm-cli enable` did not find it. The legacy Custom Nodes Manager
shows the version of a disabled nodepack under that name too. For a
registry nodepack that is not installed, `update` and `fix` say
`Not installed` and `enable` and `disable` say `Not found`, instead of
`Disabled` and `Already disabled`.
- `cm-cli install --exit-on-fail` ends with exit code 1 when an id that
neither the registry nor the node list knows, or a git URL, could not be
installed. It goes on with the other nodepacks of the command, then lists
the ones that failed. The option did not reach the install, and the command
ended with exit code 0.
- `cm-cli show installed`, `show enabled` and `show disabled`, and the same
lists of `simple-show`, list a git nodepack that neither the node list of the
channel nor the registry knows, with its id and `author: N/A`. They left it
out, enabled or disabled, where the documentation says that `installed`
shows all nodes that have been installed.
- `cm-cli` no longer writes the line `[ComfyUI-Manager] Using GitPython
backend`, or its pygit2 form. The line was written whenever the Manager was
loaded, so it came first in the output of every `cm-cli` command:
`cm-cli --show-completion` did not print the completion script alone, a
shell that evaluated it said `[ComfyUI-Manager]: command not found`, and
with the completion installed a Tab offered the line among its candidates.
The server writes the line at its start, on stderr as the other messages
about git.
- `cm-cli deps-in-workflow` tells whether a nodepack installed from the
registry is installed. It wrote `"state": "not-installed"` for such a
nodepack, enabled or disabled, and for a git nodepack disabled into
`custom_nodes/.disabled`: it looked for a folder named after the
repository, but a registry install has a folder named by its id, and a
disable moves the folder into `.disabled`. The state now comes from the
nodepacks the Manager knows to be installed, as in the Custom Nodes
Manager. `cm-cli install-deps`, which reads the same state, enables a
disabled nodepack as `cm-cli enable` does. For a disabled registry
nodepack it cloned the repository as a nightly beside it, and a git
nodepack in `.disabled` stayed disabled. It no longer runs an `enable.py`
of the nodepack, which `cm-cli enable` and the Custom Nodes Manager do not
run either.
- `cm-cli restore-snapshot` with `--pip-non-url`, `--pip-non-local-url` or
`--pip-local-url` restores a package installed in editable mode, as
`pip install -e` makes it. It ended with exit code 1: the pip list of the
snapshot has it as `-e <path or url>` (pip adds a comment line before it),
and the restore gave those lines to pip as packages of PyPI, which pip
refused; every package was then installed again one at a time. An editable
install is now restored as editable with the option of where it is:
`--pip-local-url` for a path, `--pip-non-local-url` for a repository URL.
With uv, a git URL is installed without `-e`, as such a row of
`requirements.txt` is, and a line says so. A path that the machine does not
have is listed under `Installation failed for pip packages`, as a `file:`
URL is. The comment line is skipped.
- The Filter "In Workflow" of the legacy Model Manager lists only the models
whose file a widget of the workflow names, also in a subfolder. It took the
name of each model file of the workflow without its extension and showed
every row that had that text anywhere in its name, type, base, description,
file name or save path. The default workflow loads `ae.safetensors`, and the
filter showed 29 rows, every TAESD model among them, where only FLUX.1 VAE
model is that file. It also cleared the marks of a search, and did not list
a model whose file has none of eight extensions, such as a `.gguf` file.
- The Filter of the legacy Model Manager works together with Type and Base.
With a choice other than All it ignored them: Type TAESD with the Filter at
Not Installed showed all 569 models that are not installed, instead of the
8 TAESD models. The list now shows the rows that match the Filter, Type,
Base and the search together.
- After Stop, the legacy Custom Nodes Manager shows Install again on the rows
whose install did not start, hides the Stop button, and offers Restart when
a nodepack of the batch was installed. Those rows stayed shown as being
installed and the Stop button stayed: the page waited for the report of the
end of its batch, and the server sends none for a batch that Stop drops. When
the queue reports its own end and is no longer running, the page now ends the
install, as the Model Manager already does.
- Try fix in the legacy Custom Nodes Manager is refused when it is pressed at
a `security_level` that does not allow it, as the other actions of the list
are. At the default `security_level = normal` the server took the request
and then did not run it: the box said only `failed`, the row said
`Restart Required` with a Restart button, and after the restart the
nodepack still failed to import. Try fix needs `security_level = normal-` or
`weak` with a loopback `--listen`, or `weak` with
`network_mode = personal_cloud`. At any other level the box now says
`[FAIL]` with the name of the nodepack, the terminal log says which setting
is needed, nothing is queued, and no restart is asked for.
- An update of ComfyUI by the legacy Manager skips ComfyUI's
`manager_requirements.txt` when `COMFYUI_MANAGER_SKIP_MANAGER_REQUIREMENTS`
is set, as one by the new Manager does. It installed the file anyway, and
with it the Manager version that ComfyUI pins in place of the installed one.
Without the variable an update installs that pin, as before.
- An install without torchaudio is no longer reported as one without
PyTorch, and gets the PyTorch restore after a nodepack. ComfyUI no longer
needs torchaudio (Comfy-Org/ComfyUI#16457). On an install without it,
Manager logged `[ComfyUI-Manager] PyTorch is not installed` at every start
and after an install, an update or a fix of a nodepack that has
requirements, and did not restore PyTorch when a nodepack changed torch or
torchvision (#3388). That line is no longer logged, and after such a
nodepack Manager runs the PyTorch restore that an install with torchaudio
gets. The restore installs torchaudio only when the install had it or the
nodepack added it. A nodepack that changes only torchaudio no longer starts
that restore.
- The legacy server lists a nodepack installed from the registry with its id
as the registry writes it, as `ComfyUI_SigmoidOffsetScheduler`, as the
server of the new UI already does. It gave the id in lowercase, a node
added to a workflow took that id, and the legacy Custom Nodes Manager,
which names the nodepack as the registry writes it, did not find it from
that node. Custom Nodes In Workflow and Used In Workflow showed
`0 custom nodes` for such a workflow, and Check Missing and Install Missing
Custom Nodes said `Failed to find the following ComfyRegistry list` for the
id and then listed the same nodepack.
- The legacy Custom Nodes Manager also finds the nodepack of a workflow node
whose id differs from the registry's only in case, as the lowercased id in
a workflow saved with an earlier install. When that nodepack was not
installed, Check Missing and Install Missing Custom Nodes said `Failed to
find the following ComfyRegistry list` for the id, and did not list the
nodepack at all when the node map did not know the node. The id of a node
is now matched without regard to case when the list has no exact match.
- Update All in the legacy Manager menu shows its result again when its tasks
are done: a box that lists the nodepacks that were updated and those whose
update failed, with a RESTART button, or says that everything is up to
date. The menu sent the batch without the id by which it recognizes the
report of the batch's end, so it ignored that report and showed nothing.
Update All Custom Nodes of the desktop app, which does not update ComfyUI,
shows its result as well.
## [4.4.3] - 2026-11-24
### Changed
@@ -855,6 +1318,7 @@ programmatic clients.
perform the change from a trusted entry point. Read access via `GET` is
unaffected.
[4.5]: https://github.com/Comfy-Org/ComfyUI-Manager/compare/v4.4.3...v4.5
[4.4.3]: https://github.com/Comfy-Org/ComfyUI-Manager/compare/v4.4.2...v4.4.3
[4.4.2]: https://github.com/Comfy-Org/ComfyUI-Manager/compare/v4.4.1...v4.4.2
[4.4.1]: https://github.com/Comfy-Org/ComfyUI-Manager/compare/v4.4...v4.4.1
-1
View File
@@ -10,6 +10,5 @@ include extension-node-list.json
include extras.json
include github-stats.json
include model-list.json
include alter-list.json
include comfyui_manager/channels.list.template
prune tests
+6 -1
View File
@@ -209,6 +209,7 @@ The following settings are applied based on the section marked as `is_default`.
[default]
git_exe = <Manually specify the path to the git executable. If left empty, the default git executable path will be used.>
use_uv = <Use uv instead of pip for dependency installation.>
dependency_management = <on|off; defaults to on. Disable automatic startup package changes in externally-managed Python environments.>
default_cache_as_channel_url = <Determines whether to retrieve the DB designated as channel_url at startup>
bypass_ssl = <Set to True if SSL errors occur to disable SSL.>
file_logging = <Configure whether to create a log file used by ComfyUI-Manager.>
@@ -227,7 +228,11 @@ The following settings are applied based on the section marked as `is_default`.
- public: An environment that uses a typical public network.
- private: An environment that uses a closed network, where a private node DB is configured via `channel_url`. (Uses cache if available)
- offline: An environment that does not use any external connections when using an offline network. (Uses cache if available)
- personal_cloud: Applies relaxed security features in cloud environments such as Google Colab or Runpod, where strong security is not required.
- personal_cloud: Applies relaxed security features in cloud environments such as Google Colab or Runpod, where strong security is not required.
* `dependency_management = off` skips PIPFixer auto-healing (in the server and in cm-cli) and the startup unified dependency resolver; with the resolver skipped, installs use per-node pip. Read-only package inventory operations remain available.
- `COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT=on|off` overrides the config setting. `false`, `0`, `no`, and `disabled` also disable it (case-insensitive).
- Explicit install/update commands, including those applied at the next restart, and custom-node `install.py` scripts remain available and can modify the environment. This setting is not a sandbox; externally-managed installations should use `--no-deps` for explicit node operations where supported and provision dependencies separately.
## Additional Feature
-1
View File
@@ -2,7 +2,6 @@
python json-checker.py "custom-node-list.json"
python json-checker.py "model-list.json"
python json-checker.py "alter-list.json"
python json-checker.py "extension-node-map.json"
python json-checker.py "node_db\new\custom-node-list.json"
python json-checker.py "node_db\new\model-list.json"
-1
View File
@@ -6,7 +6,6 @@ echo CHECK1
files=(
"custom-node-list.json"
"model-list.json"
"alter-list.json"
"extension-node-map.json"
"github-stats.json"
"extras.json"
+82 -86
View File
@@ -8,8 +8,7 @@ import threading
from typing import Optional
import typer
from rich import print
from rich.markup import escape
import rich
from typing_extensions import List, Annotated
import re
import importlib
@@ -22,13 +21,13 @@ import importlib
comfy_path = os.environ.get('COMFYUI_PATH')
if comfy_path is None:
print("[bold red]cm-cli: environment variable 'COMFYUI_PATH' is not specified.[/bold red]")
rich.print("[bold red]cm-cli: environment variable 'COMFYUI_PATH' is not specified.[/bold red]")
exit(-1)
sys.path.append(comfy_path)
if not os.path.exists(os.path.join(comfy_path, 'folder_paths.py')):
print("[bold red]cm-cli: '{comfy_path}' is not a valid 'COMFYUI_PATH' location.[/bold red]")
rich.print("[bold red]cm-cli: '{comfy_path}' is not a valid 'COMFYUI_PATH' location.[/bold red]")
exit(-1)
@@ -41,6 +40,8 @@ from comfyui_manager.common import context
from comfyui_manager.legacy.manager_core import unified_manager
from comfyui_manager.common import cnr_utils
print = core.print
comfyui_manager_path = os.path.abspath(os.path.dirname(__file__))
cm_global.pip_blacklist = {'torch', 'torchaudio', 'torchsde', 'torchvision'}
@@ -68,7 +69,7 @@ def check_comfyui_hash():
core.comfy_ui_revision = repo.iter_commits_count()
core.comfy_ui_commit_datetime = repo.head_commit_datetime
except Exception:
print('[bold yellow]INFO: Frozen ComfyUI mode.[/bold yellow]')
print('INFO: Frozen ComfyUI mode.', style='bold yellow')
core.comfy_ui_revision = 0
core.comfy_ui_commit_datetime = 0
@@ -197,7 +198,7 @@ def install_node(node_spec_str, is_all=False, cnt_msg='', **kwargs):
res = asyncio.run(core.gitclone_install(node_spec_str, no_deps=cmd_ctx.no_deps))
if not res.result:
print(res.msg)
print(f"[bold red]ERROR: An error occurred while installing '{node_spec_str}'.[/bold red]")
print(f"ERROR: An error occurred while installing '{node_spec_str}'.", style="bold red")
if raise_on_fail:
raise NodeInstallError(node_spec_str)
else:
@@ -218,7 +219,7 @@ def install_node(node_spec_str, is_all=False, cnt_msg='', **kwargs):
if res.action == 'skip':
print(f"{cnt_msg} [ SKIP ] {node_name:50} => Already installed")
elif res.action == 'enable':
elif res.action == 'enable' and res.result:
print(f"{cnt_msg} [ ENABLED ] {node_name:50}")
elif res.action == 'install-git' and res.target == 'nightly':
print(f"{cnt_msg} [INSTALLED] {node_name:50}[NIGHTLY]")
@@ -233,7 +234,7 @@ def install_node(node_spec_str, is_all=False, cnt_msg='', **kwargs):
show_versions(node_name)
print("")
else:
print(f"[bold red]ERROR: An error occurred while installing '{node_name}'.\n{res.msg}[/bold red]")
print(f"ERROR: An error occurred while installing '{node_name}'.\n{res.msg}", style="bold red")
if raise_on_fail:
raise NodeInstallError(node_name)
@@ -250,7 +251,13 @@ def reinstall_node(node_spec_str, is_all=False, cnt_msg=''):
else:
node_name, version_spec, repo_url = core.unknown_node_id(url), 'unknown', url
else:
node_name, version_spec, _ = unified_manager.resolve_node_spec(node_spec_str)
node_name, version_spec, is_specified = unified_manager.resolve_node_spec(node_spec_str)
if not is_specified:
for guess_mode in ('active', 'inactive'):
installed = unified_manager.resolve_unspecified_version(node_name, guess_mode=guess_mode)
if installed not in (None, 'unknown'):
version_spec = installed
break
res = asyncio.run(unified_manager.reinstall_by_id(node_name, version_spec, cmd_ctx.channel, cmd_ctx.mode, instant_execution=True,
no_deps=cmd_ctx.no_deps, repo_url=repo_url))
@@ -258,10 +265,9 @@ def reinstall_node(node_spec_str, is_all=False, cnt_msg=''):
print(f"{cnt_msg} [ SKIP ] {node_name:50} => Already installed")
return
if not res.result:
print(f"[bold red]ERROR: An error occurred while reinstalling '{node_name}'.\n{escape(res.msg)}[/bold red]")
print(f"ERROR: An error occurred while reinstalling '{node_name}'.\n{res.msg}", style="bold red")
raise NodeInstallError(node_name)
# in capitals, as install_node prints a git install: rich reads a lowercase [nightly] as markup
target = res.target.upper() if res.target in ('nightly', 'unknown') else res.target
print(f"{cnt_msg} [REINSTALLED] {node_name:50}[{target}]")
@@ -270,11 +276,10 @@ def fix_node(node_spec_str, is_all=False, cnt_msg='', fixed=None):
node_spec = unified_manager.resolve_node_spec(node_spec_str, guess_mode='active')
if node_spec is None:
if not is_all:
if unified_manager.resolve_node_spec(node_spec_str, guess_mode='inactive') is not None:
print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Disabled")
else:
print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Not installed")
if unified_manager.resolve_node_spec(node_spec_str, guess_mode='inactive') is not None:
print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Disabled")
else:
print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Not installed")
return
@@ -284,7 +289,7 @@ def fix_node(node_spec_str, is_all=False, cnt_msg='', fixed=None):
res = unified_manager.unified_fix(node_name, version_spec, no_deps=cmd_ctx.no_deps, fixed=fixed)
if not res.result:
print(f"[bold red]ERROR: f{res.msg}[/bold red]")
print(f"ERROR: {res.msg}", style="bold red")
def uninstall_node(node_spec_str: str, is_all: bool = False, cnt_msg: str = ''):
@@ -416,6 +421,7 @@ def enable_node(node_spec_str, is_all=False, cnt_msg=''):
def disable_node(node_spec_str: str, is_all=False, cnt_msg=''):
if 'comfyui-manager' in node_spec_str.lower():
print(f"{cnt_msg} [ SKIP ] {node_spec_str:50} => Not disabled: its name has 'comfyui-manager'")
return
node_spec = unified_manager.resolve_node_spec(node_spec_str, guess_mode='active')
@@ -472,11 +478,7 @@ def show_list(kind, simple=False):
if flag and kind != 'cnr':
for k, v in unified_manager.unknown_active_nodes.items():
item = repo_unknown.get(k)
if item is None:
continue
item = repo_unknown.get(k, {'title': k, 'author': 'N/A'})
log_item = "[ ENABLED ] ", item['title'], k, item['author']
unknown_processed.append(log_item)
@@ -509,11 +511,7 @@ def show_list(kind, simple=False):
if flag and kind != 'cnr':
for k, v in unified_manager.unknown_inactive_nodes.items():
item = repo_unknown.get(k)
if item is None:
continue
item = repo_unknown.get(k, {'title': k, 'author': 'N/A'})
log_item = "[ DISABLED ] ", item['title'], k, item['author']
unknown_processed.append(log_item)
@@ -547,7 +545,7 @@ def show_list(kind, simple=False):
if simple:
print(title+'@'+ver_spec)
else:
print(f"{prefix} {title:50} {short_id:30} (author: {author:20}) \\[{ver_spec}]")
print(f"{prefix} {title:50} {short_id:30} (author: {author:20}) [{ver_spec}]")
for x in unknown_processed:
prefix, title, short_id, author = x
@@ -557,19 +555,19 @@ def show_list(kind, simple=False):
print(f"{prefix} {title:50} {short_id:30} (author: {author:20}) [UNKNOWN]")
async def show_snapshot(simple_mode=False):
json_obj = await core.get_current_snapshot()
def show_snapshot(simple_mode=False):
json_obj = asyncio.run(core.get_current_snapshot())
if simple_mode:
print(f"[{json_obj['comfyui']}] comfyui")
core.print(f"[{json_obj['comfyui']}] comfyui")
for k, v in json_obj['git_custom_nodes'].items():
print(f"[{v['hash']}] {k}")
core.print(f"[{v['hash']}] {k}")
for v in json_obj['file_custom_nodes']:
print(f"[ N/A ] {v['filename']}")
core.print(f"[ N/A ] {v['filename']}")
else:
formatted_json = json.dumps(json_obj, ensure_ascii=False, indent=4)
print(formatted_json)
core.print(formatted_json)
def show_snapshot_list(simple_mode=False):
@@ -650,7 +648,7 @@ def for_each_nodes(nodes, act, allow_all=True, **kwargs):
failed.append(x)
if failed:
print(f"\n[bold red]Failed nodes ({len(failed)}/{total}): {', '.join(str(x) for x in failed)}[/bold red]")
print(f"\nFailed nodes ({len(failed)}/{total}): {', '.join(str(x) for x in failed)}", style="bold red")
sys.exit(1)
@@ -677,7 +675,7 @@ def install(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
no_deps: Annotated[
Optional[bool],
@@ -708,7 +706,7 @@ def install(
cmd_ctx.set_channel_mode(channel, mode)
if uv_compile and no_deps:
print("[bold red]--uv-compile and --no-deps are mutually exclusive.[/bold red]")
print("--uv-compile and --no-deps are mutually exclusive.", style="bold red")
raise typer.Exit(1)
if uv_compile:
@@ -717,7 +715,7 @@ def install(
cmd_ctx.set_no_deps(no_deps)
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
for_each_nodes(nodes, act=install_node, exit_on_fail=exit_on_fail)
for_each_nodes(nodes, act=install_node, raise_on_fail=exit_on_fail)
_finalize_resolve(pip_fixer, uv_compile)
@@ -736,7 +734,7 @@ def reinstall(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
no_deps: Annotated[
Optional[bool],
@@ -763,7 +761,7 @@ def reinstall(
cmd_ctx.set_channel_mode(channel, mode)
if uv_compile and no_deps:
print("[bold red]--uv-compile and --no-deps are mutually exclusive.[/bold red]")
print("--uv-compile and --no-deps are mutually exclusive.", style="bold red")
raise typer.Exit(1)
if uv_compile:
@@ -791,7 +789,7 @@ def uninstall(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
):
cmd_ctx.set_channel_mode(channel, mode)
@@ -802,7 +800,7 @@ def uninstall(
def update(
nodes: List[str] = typer.Argument(
...,
help="[all|List of custom nodes to update]"
help="all|List of custom nodes to update"
),
channel: Annotated[
str,
@@ -813,7 +811,7 @@ def update(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -853,7 +851,7 @@ def update(
def disable(
nodes: List[str] = typer.Argument(
...,
help="[all|List of custom nodes to disable]"
help="all|List of custom nodes to disable"
),
channel: Annotated[
str,
@@ -864,7 +862,7 @@ def disable(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -884,7 +882,7 @@ def disable(
def enable(
nodes: List[str] = typer.Argument(
...,
help="[all|List of custom nodes to enable]"
help="all|List of custom nodes to enable"
),
channel: Annotated[
str,
@@ -895,7 +893,7 @@ def enable(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -915,7 +913,7 @@ def enable(
def fix(
nodes: List[str] = typer.Argument(
...,
help="[all|List of custom nodes to fix]"
help="all|List of custom nodes to fix"
),
channel: Annotated[
str,
@@ -926,7 +924,7 @@ def fix(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -969,7 +967,7 @@ def show_versions(node_name: str):
@app.command("show", help="Show node list")
def show(
arg: str = typer.Argument(
help="[installed|enabled|not-installed|disabled|all|cnr|snapshot|snapshot-list]"
help="installed|enabled|not-installed|disabled|all|cnr|snapshot|snapshot-list"
),
channel: Annotated[
str,
@@ -980,7 +978,7 @@ def show(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -1014,7 +1012,7 @@ def show(
@app.command("simple-show", help="Show node list (simple mode)")
def simple_show(
arg: str = typer.Argument(
help="[installed|enabled|not-installed|disabled|all|snapshot|snapshot-list]"
help="installed|enabled|not-installed|disabled|all|snapshot|snapshot-list"
),
channel: Annotated[
str,
@@ -1025,7 +1023,7 @@ def simple_show(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -1042,7 +1040,7 @@ def simple_show(
"snapshot-list",
]
if arg not in valid_commands:
typer.echo(f"[bold red]Invalid command: `show {arg}`[/bold red]", err=True)
typer.echo(f"Invalid command: `show {arg}`", err=True)
exit(1)
cmd_ctx.set_user_directory(user_directory)
@@ -1076,7 +1074,7 @@ def deps_in_workflow(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -1090,7 +1088,7 @@ def deps_in_workflow(
output_path = output
if not os.path.exists(input_path):
print(f"[bold red]File not found: {input_path}[/bold red]")
print(f"File not found: {input_path}", style="bold red")
exit(1)
used_exts, unknown_nodes = asyncio.run(core.extract_nodes_from_workflow(input_path, mode=cmd_ctx.mode, channel_url=cmd_ctx.channel))
@@ -1135,13 +1133,13 @@ def save_snapshot(
if output is not None:
if(not output.endswith('.json') and not output.endswith('.yaml')):
print("[bold red]ERROR: output path should be either '.json' or '.yaml' file.[/bold red]")
print("ERROR: output path should be either '.json' or '.yaml' file.", style="bold red")
raise typer.Exit(code=1)
dir_path = os.path.dirname(output)
if(dir_path != '' and not os.path.exists(dir_path)):
print(f"[bold red]ERROR: {output} path not exists.[/bold red]")
print(f"ERROR: {output} path not exists.", style="bold red")
raise typer.Exit(code=1)
path = asyncio.run(core.save_snapshot_with_postfix('snapshot', output, not full_snapshot))
@@ -1211,14 +1209,14 @@ def restore_snapshot(
else:
snapshot_path = os.path.join(cmd_ctx.get_snapshot_path(), snapshot_name)
if not os.path.exists(snapshot_path):
print(f"[bold red]ERROR: `{snapshot_path}` is not exists.[/bold red]")
print(f"ERROR: `{snapshot_path}` is not exists.", style="bold red")
exit(1)
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
try:
is_restored = asyncio.run(core.restore_snapshot(snapshot_path, extras))
except Exception:
print("[bold red]ERROR: Failed to restore snapshot.[/bold red]")
print("ERROR: Failed to restore snapshot.", style="bold red")
traceback.print_exc()
if uv_compile:
pip_fixer.fix_broken()
@@ -1257,7 +1255,7 @@ def restore_dependencies(
for base_path in cmd_ctx.get_custom_nodes_paths():
for name in os.listdir(base_path):
target = os.path.join(base_path, name)
if os.path.isdir(target) and not name.endswith('.disabled'):
if os.path.isdir(target) and not name.endswith('.disabled') and name != '__pycache__':
node_paths.append(target)
total = len(node_paths)
@@ -1305,7 +1303,7 @@ def install_deps(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -1329,14 +1327,14 @@ def install_deps(
asyncio.run(auto_save_snapshot())
if not os.path.exists(deps):
print(f"[bold red]File not found: {deps}[/bold red]")
print(f"File not found: {deps}", style="bold red")
exit(1)
else:
with open(deps, 'r', encoding="UTF-8", errors="ignore") as json_file:
try:
json_obj = json.load(json_file)
except Exception:
print(f"[bold red]Invalid json file: {deps}[/bold red]")
print(f"Invalid json file: {deps}", style="bold red")
exit(1)
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
@@ -1347,7 +1345,8 @@ def install_deps(
elif state == 'not-installed':
asyncio.run(core.gitclone_install(k, instant_execution=True, no_deps=bool(uv_compile)))
else: # disabled
core.gitclone_set_active([k], False)
cnr = unified_manager.get_cnr_by_repo(k)
enable_node(cnr['id'] if cnr else core.unknown_node_id(k))
_finalize_resolve(pip_fixer, uv_compile)
@@ -1360,12 +1359,12 @@ def _finalize_resolve(pip_fixer, uv_compile) -> None:
try:
_run_unified_resolve()
except ImportError as e:
print(f"[bold red]Failed to import unified_dep_resolver: {e}[/bold red]")
print(f"Failed to import unified_dep_resolver: {e}", style="bold red")
raise typer.Exit(1)
except typer.Exit:
raise
except Exception as e:
print(f"[bold red]Batch resolution failed: {e}[/bold red]")
print(f"Batch resolution failed: {e}", style="bold red")
raise typer.Exit(1)
finally:
pip_fixer.fix_broken()
@@ -1385,7 +1384,7 @@ def _run_unified_resolve():
node_pack_paths = collect_node_pack_paths(cmd_ctx.get_custom_nodes_paths())
if not node_pack_paths:
print("[bold yellow]No custom node packs found.[/bold yellow]")
print("No custom node packs found.", style="bold yellow")
return
print(f"Resolving dependencies for {len(node_pack_paths)} node pack(s)...")
@@ -1400,27 +1399,28 @@ def _run_unified_resolve():
try:
result = resolver.resolve_and_install()
except UvNotAvailableError:
print("[bold red]uv is not available. Install uv to use this feature.[/bold red]")
print("uv is not available. Install uv to use this feature.", style="bold red")
raise typer.Exit(1)
if result.success:
collected = result.collected
if collected:
print(
f"[bold green]Resolved {len(collected.requirements)} deps "
f"Resolved {len(collected.requirements)} deps "
f"from {len(collected.sources)} source(s) "
f"(skipped {len(collected.skipped)}).[/bold green]"
f"(skipped {len(collected.skipped)}).",
style="bold green",
)
else:
print("[bold green]Resolution complete (no deps needed).[/bold green]")
print("Resolution complete (no deps needed).", style="bold green")
else:
print(f"[bold red]Resolution failed: {result.error}[/bold red]")
print(f"Resolution failed: {result.error}", style="bold red")
if result.lockfile and result.lockfile.conflicts and result.collected:
attributed = attribute_conflicts(result.collected.sources, result.lockfile.conflicts)
if attributed:
print("[bold yellow]Conflicting packages (by node pack):[/bold yellow]")
print("Conflicting packages (by node pack):", style="bold yellow")
for pkg_name, requesters in sorted(attributed.items()):
print(f" [yellow]{pkg_name}[/yellow]:")
print(f" {pkg_name}:", style="yellow")
for pack_path, pkg_spec in requesters:
print(f" {os.path.basename(pack_path)} → {pkg_spec}")
raise typer.Exit(1)
@@ -1442,12 +1442,12 @@ def unified_uv_compile(
try:
_run_unified_resolve()
except ImportError as e:
print(f"[bold red]Failed to import unified_dep_resolver: {e}[/bold red]")
print(f"Failed to import unified_dep_resolver: {e}", style="bold red")
raise typer.Exit(1)
except typer.Exit:
raise
except Exception as e:
print(f"[bold red]Unexpected error: {e}[/bold red]")
print(f"Unexpected error: {e}", style="bold red")
raise typer.Exit(1)
finally:
pip_fixer.fix_broken()
@@ -1470,7 +1470,7 @@ def export_custom_node_ids(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -1532,7 +1532,6 @@ async def _force_update_cache(channel):
"custom-node-list.json",
"extension-node-map.json",
"model-list.json",
"alter-list.json",
"github-stats.json",
]
@@ -1553,7 +1552,7 @@ async def _force_update_cache(channel):
print(f" [CACHED] {filename}")
except Exception as e:
print(f" [bold red][FAILED] {filename}: {e}[/bold red]")
print(f" [FAILED] {filename}: {e}", style="bold red")
failed.append(filename)
print("Fetching channel data...")
@@ -1566,7 +1565,7 @@ async def _force_update_cache(channel):
try:
await unified_manager.reload('remote', dont_wait=False)
except Exception as e:
print(f" [bold red][FAILED] CNR registry: {e}[/bold red]")
print(f" [FAILED] CNR registry: {e}", style="bold red")
failed.append("CNR registry")
# Step 3: Load nightly data (cache files now exist from Step 1)
@@ -1574,10 +1573,10 @@ async def _force_update_cache(channel):
await unified_manager.load_nightly(channel or 'default', 'cache')
if failed:
print(f"\n[bold red]Cache update incomplete. Failed: {', '.join(failed)}[/bold red]")
print(f"\nCache update incomplete. Failed: {', '.join(failed)}", style="bold red")
sys.exit(1)
else:
print("[bold green]Cache update complete.[/bold green]")
print("Cache update complete.", style="bold green")
def main():
@@ -1587,6 +1586,3 @@ def main():
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(app())
print("")
-224
View File
@@ -1,224 +0,0 @@
{
"items": [
{
"id":"https://github.com/Fannovel16/comfyui_controlnet_aux",
"tags":"controlnet",
"description": "This extension provides preprocessor nodes for using controlnet."
},
{
"id":"https://github.com/comfyanonymous/ComfyUI_experiments",
"tags":"Dynamic Thresholding, DT, CFG, controlnet, reference only",
"description": "This experimental nodes contains a 'Reference Only' node and a 'ModelSamplerTonemapNoiseTest' node corresponding to the 'Dynamic Threshold'."
},
{
"id":"https://github.com/ltdrdata/ComfyUI-Impact-Pack",
"tags":"ddetailer, adetailer, ddsd, DD, loopback scaler, prompt, wildcard, dynamic prompt",
"description": "To implement the feature of automatically detecting faces and enhancing details, various detection nodes and detailers provided by the Impact Pack can be applied. Similarly to Loopback Scaler, it also provides various custom workflows that can apply Ksampler while gradually scaling up."
},
{
"id":"https://github.com/ltdrdata/ComfyUI-Inspire-Pack",
"tags":"lora block weight, effective block analyzer, lbw, variation seed",
"description": "The Inspire Pack provides the functionality of Lora Block Weight, Variation Seed."
},
{
"id":"https://github.com/biegert/ComfyUI-CLIPSeg/raw/main/custom_nodes/clipseg.py",
"tags":"ddsd",
"description": "This extension provides a feature that generates segment masks on an image using a text prompt. When used in conjunction with Impact Pack, it enables applications such as DDSD."
},
{
"id":"https://github.com/BadCafeCode/masquerade-nodes-comfyui",
"tags":"ddetailer",
"description": "This extension is a less feature-rich and well-maintained alternative to Impact Pack, but it has fewer dependencies and may be easier to install on abnormal configurations. The author recommends trying Impact Pack first."
},
{
"id":"https://github.com/BlenderNeko/ComfyUI_Cutoff",
"tags":"cutoff",
"description": "By using this extension, prompts like 'blue hair' can be prevented from interfering with other prompts by blocking the attribute 'blue' from being used in prompts other than 'hair'."
},
{
"id":"https://github.com/BlenderNeko/ComfyUI_ADV_CLIP_emb",
"tags":"prompt, weight",
"description": "There are differences in the processing methods of prompts, such as weighting and scheduling, between A1111 and ComfyUI. With this extension, various settings can be used to implement prompt processing methods similar to A1111. As this feature is also integrated into ComfyUI Cutoff, please download the Cutoff extension if you plan to use it in conjunction with Cutoff."
},
{
"id":"https://github.com/shiimizu/ComfyUI_smZNodes",
"tags":"prompt, weight",
"description": "There are differences in the processing methods of prompts, such as weighting and scheduling, between A1111 and ComfyUI. This extension helps to reproduce the same embedding as A1111."
},
{
"id":"https://github.com/BlenderNeko/ComfyUI_Noise",
"tags":"img2img alt, random",
"description": "The extension provides an unsampler that reverses the sampling process, allowing for a function similar to img2img alt to be implemented. Furthermore, ComfyUI uses CPU's Random instead of GPU's Random for better reproducibility compared to A1111. This extension provides the ability to use GPU's Random for Latent Noise. However, since GPU's Random may vary depending on the GPU model, reproducibility on different devices cannot be guaranteed."
},
{
"id":"https://github.com/BlenderNeko/ComfyUI_SeeCoder",
"tags":"seecoder, prompt-free-diffusion",
"description": "The extension provides seecoder feature."
},
{
"id":"https://github.com/lilly1987/ComfyUI_node_Lilly",
"tags":"prompt, wildcard",
"description": "This extension provides features such as a wildcard function that randomly selects prompts belonging to a category and the ability to directly load lora from prompts."
},
{
"id":"https://github.com/Davemane42/ComfyUI_Dave_CustomNode",
"tags":"latent couple",
"description": "ComfyUI already provides the ability to composite latents by default. However, this extension makes it more convenient to use by visualizing the composite area."
},
{
"id":"https://github.com/LEv145/images-grid-comfy-plugin",
"tags":"X/Y Plot",
"description": "This tool provides a viewer node that allows for checking multiple outputs in a grid, similar to the X/Y Plot extension."
},
{
"id":"https://github.com/pythongosssss/ComfyUI-WD14-Tagger",
"tags":"deepbooru, clip interrogation",
"description": "This extension generates clip text by taking an image as input and using the Deepbooru model."
},
{
"id":"https://github.com/szhublox/ambw_comfyui",
"tags":"supermerger",
"description": "This node takes two models, merges individual blocks together at various ratios, and automatically rates each merge, keeping the ratio with the highest score. "
},
{
"id":"https://github.com/ssitu/ComfyUI_UltimateSDUpscale",
"tags":"upscaler, Ultimate SD Upscale",
"description": "ComfyUI nodes for the Ultimate Stable Diffusion Upscale script by Coyote-A. Uses the same script used in the A1111 extension to hopefully replicate images generated using the A1111 webui."
},
{
"id":"https://github.com/dawangraoming/ComfyUI_ksampler_gpu/raw/main/ksampler_gpu.py",
"tags":"random, noise",
"description": "A1111 provides KSampler that uses GPU-based random noise. This extension offers KSampler utilizing GPU-based random noise."
},
{
"id":"https://github.com/space-nuko/nui-suite",
"tags":"prompt, dynamic prompt",
"description": "This extension provides nodes with the functionality of dynamic prompts."
},
{
"id":"https://github.com/melMass/comfy_mtb",
"tags":"roop",
"description": "This extension provides bunch of nodes including roop"
},
{
"id":"https://github.com/ssitu/ComfyUI_roop",
"tags":"roop",
"description": "This extension provides nodes for the roop A1111 webui script."
},
{
"id":"https://github.com/asagi4/comfyui-prompt-control",
"tags":"prompt, prompt editing",
"description": "This extension provides the ability to use prompts like \n\n**a [large::0.1] [cat|dog:0.05] [<lora:somelora:0.5:0.6>::0.5] [in a park:in space:0.4]**\n\n"
},
{
"id":"https://github.com/adieyal/comfyui-dynamicprompts",
"tags":"prompt, dynamic prompt",
"description": "This extension is a port of sd-dynamic-prompt to ComfyUI."
},
{
"id":"https://github.com/kwaroran/abg-comfyui",
"tags":"abg, background remover",
"description": "A Anime Background Remover node for comfyui, based on this hf space, works same as AGB extention in automatic1111."
},
{
"id":"https://github.com/Gourieff/comfyui-reactor-node",
"tags":"reactor, sd-webui-roop-nsfw",
"description": "This is a ported version of ComfyUI for the sd-webui-roop-nsfw extension."
},
{
"id":"https://github.com/laksjdjf/cgem156-ComfyUI",
"tags":"regional prompt, latent couple, prompt",
"description": "This custom nodes provide a functionality similar to regional prompts, offering couple features at the attention level."
},
{
"id":"https://github.com/FizzleDorf/ComfyUI_FizzNodes",
"tags":"deforum",
"description": "This custom nodes provide functionality that assists in animation creation, similar to deforum."
},
{
"id":"https://github.com/seanlynch/comfyui-optical-flow",
"tags":"deforum, vid2vid",
"description": "This custom nodes provide functionality that assists in animation creation, similar to deforum."
},
{
"id":"https://github.com/ssitu/ComfyUI_fabric",
"tags":"fabric",
"description": "Similar to sd-webui-fabric, this custom nodes provide the functionality of [a/FABRIC](https://github.com/sd-fabric/fabric)."
},
{
"id":"https://github.com/Zuellni/ComfyUI-ExLlama",
"tags":"ExLlama, prompt, language model",
"description": "Similar to text-generation-webui, this custom nodes provide the functionality of [a/exllama](https://github.com/turboderp/exllama)."
},
{
"id":"https://github.com/spinagon/ComfyUI-seamless-tiling",
"tags":"tiling",
"description": "ComfyUI node for generating seamless textures Replicates 'Tiling' option from A1111"
},
{
"id":"https://github.com/laksjdjf/cd-tuner_negpip-ComfyUI",
"tags":"cd-tuner, negpip",
"description": "This extension is a port of the [a/sd-webui-cd-tuner](https://github.com/hako-mikan/sd-webui-cd-tuner)(a.k.a. CD(color/Detail) Tuner )and [a/sd-webui-negpip](https://github.com/hako-mikan/sd-webui-negpip)(a.k.a. NegPiP) extensions of A1111 to ComfyUI."
},
{
"id":"https://github.com/mcmonkeyprojects/sd-dynamic-thresholding",
"tags":"DT, dynamic thresholding",
"description": "This custom node is a port of the Dynamic Thresholding extension from A1111 to make it available for use in ComfyUI."
},
{
"id":"https://github.com/hhhzzyang/Comfyui_Lama",
"tags":"lama, inpainting anything",
"description": "This extension provides custom nodes developed based on [a/LaMa](https://github.com/advimman/lama) and [a/Inpainting anything](https://github.com/geekyutao/Inpaint-Anything)."
},
{
"id":"https://github.com/mlinmg/ComfyUI-LaMA-Preprocessor",
"tags":"lama",
"description": "This extension provides custom nodes for [a/LaMa](https://github.com/advimman/lama) functionality."
},
{
"id":"https://github.com/Haoming02/comfyui-diffusion-cg",
"tags":"diffusion-cg",
"description": "This extension provides custom nodes for [a/SD Webui Diffusion Color Grading](https://github.com/Haoming02/sd-webui-diffusion-cg) functionality."
},
{
"id":"https://github.com/asagi4/ComfyUI-CADS",
"tags":"diffusion-cg",
"description": "This extension provides custom nodes for [a/sd-webui-cads](https://github.com/v0xie/sd-webui-cads) functionality."
},
{
"id":"https://git.mmaker.moe/mmaker/sd-webui-color-enhance",
"tags":"color-enhance",
"description": "This extension supports both A1111 and ComfyUI simultaneously."
},
{
"id":"https://github.com/shiimizu/ComfyUI-TiledDiffusion",
"tags":"multidiffusion",
"description": "This extension provides custom nodes for [a/Mixture of Diffusers](https://github.com/albarji/mixture-of-diffusers) and [a/MultiDiffusion](https://github.com/omerbt/MultiDiffusion)"
},
{
"id":"https://github.com/abyz22/image_control",
"tags":"BMAB",
"description": "This extension provides some alternative functionalities of the [a/sd-webui-bmab](https://github.com/portu-sim/sd-webui-bmab) extension."
},
{
"id":"https://github.com/blepping/ComfyUI-sonar",
"tags":"sonar",
"description": "This extension provides some alternative functionalities of the [a/stable-diffusion-webui-sonar](https://github.com/Kahsolt/stable-diffusion-webui-sonar) extension."
},
{
"id":"https://github.com/AIFSH/ComfyUI-RVC",
"tags":"sonar",
"description": "a comfyui custom node for [a/Retrieval-based-Voice-Conversion-WebUI](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI.git), you can Voice-Conversion in comfyui now!"
},
{
"id":"https://github.com/portu-sim/comfyui-bmab",
"tags":"bmab",
"description": "a comfyui custom node for [a/sd-webui-bmab](https://github.com/portu-sim/sd-webui-bmab)"
},
{
"id":"https://github.com/ThereforeGames/ComfyUI-Unprompted",
"tags":"unprompted",
"description": "This extension is a port of [a/unprompted](https://github.com/ThereforeGames/unprompted)"
}
]
}
+24 -21
View File
@@ -20,6 +20,29 @@ lock = asyncio.Lock()
is_cache_loading = False
def get_form_factor():
"""Form factor reported to the registry, based on environment and platform."""
is_desktop = bool(os.environ.get('__COMFYUI_DESKTOP_VERSION__'))
system = platform.system().lower()
if is_desktop:
if system == 'windows':
return 'desktop-win'
if system == 'darwin':
return 'desktop-mac'
if system == 'linux':
return 'desktop-linux'
return 'other'
if system == 'windows':
return 'git-windows'
if system == 'darwin':
return 'git-mac'
if system == 'linux':
return 'git-linux'
return 'other'
async def get_cnr_data(cache_mode=True, dont_wait=True):
try:
return await _get_cnr_data(cache_mode, dont_wait)
@@ -39,12 +62,7 @@ async def _get_cnr_data(cache_mode=True, dont_wait=True):
full_nodes = {}
# Determine form factor based on environment and platform
is_desktop = bool(os.environ.get('__COMFYUI_DESKTOP_VERSION__'))
system = platform.system().lower()
is_windows = system == 'windows'
is_mac = system == 'darwin'
is_linux = system == 'linux'
# Get ComfyUI version tag
if is_desktop:
@@ -53,22 +71,7 @@ async def _get_cnr_data(cache_mode=True, dont_wait=True):
else:
comfyui_ver = context.get_comfyui_tag() or 'unknown'
if is_desktop:
if is_windows:
form_factor = 'desktop-win'
elif is_mac:
form_factor = 'desktop-mac'
else:
form_factor = 'other'
else:
if is_windows:
form_factor = 'git-windows'
elif is_mac:
form_factor = 'git-mac'
elif is_linux:
form_factor = 'git-linux'
else:
form_factor = 'other'
form_factor = get_form_factor()
from comfyui_manager.glob import manager_core
verbose = manager_core.get_config().get('verbose', False)
+3 -3
View File
@@ -202,11 +202,11 @@ else:
if USE_PYGIT2:
if _PYGIT2_REQUESTED:
print("[ComfyUI-Manager] Using pygit2 backend (CM_USE_PYGIT2=1)")
BACKEND_LINE = "[ComfyUI-Manager] Using pygit2 backend (CM_USE_PYGIT2=1)"
else:
print("[ComfyUI-Manager] Using pygit2 backend (system git not available)")
BACKEND_LINE = "[ComfyUI-Manager] Using pygit2 backend (system git not available)"
else:
print("[ComfyUI-Manager] Using GitPython backend")
BACKEND_LINE = "[ComfyUI-Manager] Using GitPython backend"
# ===================================================================
+33 -7
View File
@@ -76,21 +76,33 @@ def aria2_find_task(dir: str, filename: str):
def aria2_download_url(model_url: str, model_dir: str, filename: str):
import manager_core as core
try:
from comfyui_manager.common import context
except ImportError:
import manager_core as context
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(context.comfy_path):
rel = model_dir[len(context.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 +110,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:
+521 -27
View File
@@ -2,16 +2,23 @@
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 shutil
import importlib.metadata
import traceback
import aiohttp
import json
import math
import threading
import contextlib
import os
import subprocess
import sys
import tempfile
import re
import codecs
import logging
import platform
import shlex
@@ -34,6 +41,50 @@ use_uv = False
use_unified_resolver = False
bypass_ssl = False
# When False, ComfyUI-Manager will not attempt to install, upgrade, or
# uninstall Python packages on its own (prestartup auto-healing and the unified
# dependency resolver batch). This is intended for distro-packaged or otherwise
# externally-managed Python environments (e.g. Nix, Guix, system package
# managers, locked-down corporate images) where the interpreter is read-only.
#
# Read-only pip operations (`list`, `freeze`, `show`) still run so the UI,
# inventory, and security checks keep working.
dependency_management_enabled = True
_OFF_VALUES = frozenset({'off', 'false', '0', 'no', 'disabled'})
def is_off_value(value):
"""Return True if a config or env-var string spells "off".
Anything else — including the empty string and unknown words — is treated
as "on", so a typo doesn't silently disable dependency management.
"""
return value.strip().lower() in _OFF_VALUES
DEPENDENCY_MANAGEMENT_ENV = 'COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT'
def apply_dependency_management_setting(config_value=None):
"""Set `dependency_management_enabled` from the environment, else from config.ini's value.
The environment wins over config.ini; with neither, the current value stays. Every process
that loads this module (the server, cm-cli, the cm-cli that the startup runs) applies the
environment."""
global dependency_management_enabled
value = os.environ.get(DEPENDENCY_MANAGEMENT_ENV)
if value is None:
value = config_value
if value is not None:
dependency_management_enabled = not is_off_value(value)
return dependency_management_enabled
apply_dependency_management_setting()
def is_manager_pip_package():
return not os.path.exists(os.path.join(comfyui_manager_path, '..', 'custom_nodes'))
@@ -404,6 +455,9 @@ def normalize_pip_name(name):
_PIP_LINE_TAIL_PATTERN = re.compile(r'\s[#-]') # a comment or a pip option after the requirement
_PIP_COMMENT_PATTERN = re.compile(r'(^|\s)#.*') # as pip reads it: the '#' of a URL fragment starts no comment
_PIP_INDEX_OPTIONS = {'--index-url', '--extra-index-url'}
_PIP_EDITABLE_PATTERN = re.compile(r'(?:-e\s*|--editable(?:\s+|=))(\S+)') # how pip reads -e and its target
_PIP_MALFORMED_PATTERN = re.compile(r'([A-Za-z0-9][A-Za-z0-9._-]*)\s*(\[[^\]]*\]\s*)?[<>=!~(]')
_PIP_URL_PATTERN = re.compile(r'[A-Za-z][A-Za-z0-9+.-]*://')
@@ -442,6 +496,54 @@ def parse_pip_spec(spec):
return name, extras, [(specifier.operator, specifier.version) for specifier in requirement.specifier]
def installer_args(requirement):
"""The arguments of a requirement as the installer in use takes them.
uv installs an editable from a local folder only: where the arguments are `-e`
and a git URL, uv gets the URL alone, as a normal install, and a line says so.
"""
if requirement[0] == '-e' and requirement[1].startswith('git+') and 'uv' in get_pip_cmd(force_uv=use_uv):
print(f"[ComfyUI-Manager] uv installs an editable from a local folder only: '{requirement[1]}' is installed without -e")
return requirement[1:]
return requirement
def pip_install_args(line, overrides):
"""The arguments that a line of requirements.txt gives to `pip install`, or [] if it has none.
Each line is installed on its own, and an option applies to its line only. The
comment is left out as pip leaves it out, so a URL keeps its fragment. A line that
`overrides` (pip_overrides.json) names is replaced. An editable requirement
(`-e path`, `--editable=path`) is `-e` and its target. A requirement followed by
index options, such as `--extra-index-url URL`, gives the requirement and the
options; any other line with a requirement is one argument, with the spaces of an
environment marker. Where `-e` and a git URL are two arguments, uv gets the URL
alone: it installs an editable from a local folder only. A line that starts with
another option than `-e`, such as `-r other.txt`, names no requirement and gives
none.
"""
text = _PIP_COMMENT_PATTERN.sub('', line).strip()
if text in overrides:
print(f"[ComfyUI-Manager] '{text}' is remapped to '{overrides[text]}'")
text = overrides[text]
if not text:
return []
editable = _PIP_EDITABLE_PATTERN.match(text)
if editable is not None:
requirement, options = ['-e', editable.group(1)], text[editable.end():].split()
elif text.startswith('-'):
print(f"[ComfyUI-Manager] skip '{text}': the Manager installs requirements one row at a time and does not apply this row")
return []
else:
tail = _PIP_LINE_TAIL_PATTERN.search(text)
if tail is None:
return [text]
requirement, options = [text[:tail.start()].rstrip()], text[tail.start():].split()
if len(options) % 2 == 0 and set(options[::2]) <= _PIP_INDEX_OPTIONS:
return [*installer_args(requirement), *options]
return [text]
def _upper_bound_state(operator, version, installed):
"""Where an installed version sits against one upper-bound clause.
@@ -712,15 +814,15 @@ def installed_from(url, name=None):
return None
def fix_cmd(requirement):
"""The pip command with which a fix installs a requirement.
def fix_cmd(install_args):
"""The pip command with which a fix installs the arguments of a requirement line, from `pip_install_args()`.
A direct reference is installed again by force, whatever is installed: nothing but
its URL says what it should be. That command is run with `reinstall()`. Any other
requirement is installed as an install does it.
"""
cmd = make_pip_cmd(['install', requirement])
clauses = parse_pip_spec(requirement)[2]
cmd = make_pip_cmd(['install', *install_args])
clauses = parse_pip_spec(install_args[0])[2]
if clauses and clauses[0][0] == '@':
# --no-deps: without it every package the distribution needs is installed again as well, torch among them.
# The cache is left out: with it uv installs the wheel it has built of the commit before, forced or not, and so
@@ -883,9 +985,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'),
@@ -897,19 +1011,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):
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', 'torch', 'torchvision', 'torchaudio'])
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])
@@ -917,21 +1031,342 @@ def torch_rollback(prev):
torch_torchvision_torchaudio_ver = torch_torchvision_torchaudio_version_map.get(torch_ver)
if torch_torchvision_torchaudio_ver is None:
cmd = make_pip_cmd(['install', '--pre', 'torch', 'torchvision', 'torchaudio',
'--index-url', f"https://download.pytorch.org/whl/nightly/{platform}"])
cmd = make_pip_cmd(['install', '--pre', *packages,
'--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
cmd = make_pip_cmd(['install', f'torch=={torch_ver}', f'torchvision=={torchvision_ver}', f"torchaudio=={torchaudio_ver}",
'--index-url', f"https://download.pytorch.org/whl/{platform}"])
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}", *options])
logging.info(f"[ComfyUI-Manager] restore PyTorch to {torch_ver}+{platform}")
subprocess.check_output(cmd, universal_newlines=True)
def _pytorch_index(build, option):
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()):
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):
# 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):
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
@@ -945,6 +1380,10 @@ class PIPFixer:
return {parse_pip_spec(x)[0] for x in f.readlines()}
def fix_broken(self):
if not dependency_management_enabled:
logging.info("[ComfyUI-Manager] dependency management disabled; skipping PIPFixer.fix_broken()")
return
new_pip_versions = get_installed_packages(True)
# remove `comfy` python package
@@ -960,12 +1399,12 @@ class PIPFixer:
# fix torch - reinstall torch packages if version is changed
try:
if 'torch' not in self.prev_pip_versions or 'torchvision' not in self.prev_pip_versions or 'torchaudio' not in self.prev_pip_versions:
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'] \
or self.prev_pip_versions['torchaudio'] != new_pip_versions['torchaudio']:
torch_rollback(self.prev_pip_versions['torch'])
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)
@@ -1098,6 +1537,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.
@@ -1134,13 +1619,22 @@ def restore_pip_snapshot(pips, options):
if k.startswith("torch==") or k.startswith("torchvision==") or k.startswith("torchaudio==") or k.startswith("nvidia-"):
continue
if v == "":
# pip freeze prints an editable install as `-e <path or url>`, after a comment line
if k.startswith('#'):
continue
elif k.startswith('-e '):
v = k[3:]
args = ['-e', v]
elif v == "":
non_url.append(k)
continue
else:
if v.startswith('file:'):
local_url.append(v)
else:
non_local_url.append(v)
args = [v]
if v.startswith('file:') or '://' not in v:
local_url.append(args)
else:
non_local_url.append(args)
# restore other pips
@@ -1169,23 +1663,23 @@ def restore_pip_snapshot(pips, options):
for x in non_local_url:
res = 1
try:
res = subprocess.check_call(make_pip_cmd(['install', '--no-deps', x]))
res = subprocess.check_call(make_pip_cmd(['install', '--no-deps', *installer_args(x)]))
except Exception:
pass
if res != 0:
failed.append(x)
failed.append(' '.join(x))
if '--pip-local-url' in options:
for x in local_url:
res = 1
try:
res = subprocess.check_call(make_pip_cmd(['install', '--no-deps', x]))
res = subprocess.check_call(make_pip_cmd(['install', '--no-deps', *installer_args(x)]))
except Exception:
pass
if res != 0:
failed.append(x)
failed.append(' '.join(x))
print(f"Installation failed for pip packages: {failed}")
return failed
+121 -161
View File
@@ -48,10 +48,9 @@ from ..common.enums import NetworkMode, SecurityLevel, DBMode
from ..common import context
def print(*objects, sep=" ", end="\n", file=None):
# rich's print with its highlighting only, so that a path, a URL or an error text is written as it is
def print(*objects, sep=" ", end="\n", file=None, style=None):
console = rich.get_console() if file is None else Console(file=file)
console.print(*objects, sep=sep, end=end, markup=False, emoji=False, soft_wrap=True)
console.print(*objects, sep=sep, end=end, style=style, highlight=style is None, markup=False, emoji=False, soft_wrap=True)
try:
@@ -63,8 +62,8 @@ except Exception:
version_str = f"V{_raw_version}"
DEFAULT_CHANNEL = "https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main"
DEFAULT_CHANNEL_LEGACY = "https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main"
DEFAULT_CHANNEL = "https://raw.githubusercontent.com/Comfy-Org/ComfyUI-Manager/main"
DEFAULT_CHANNEL_URLS = {"https://raw.githubusercontent.com/Comfy-Org/ComfyUI-Manager/main", "https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main"}
# SSH git URL pattern (e.g., git@github.com:user/repo.git)
SSH_URL_PATTERN = re.compile(r"^(.+@|ssh://).+:.+$")
@@ -171,30 +170,25 @@ cached_config = None
js_path = None
channel_dict = None
valid_channels = {'default', 'local', DEFAULT_CHANNEL, DEFAULT_CHANNEL_LEGACY}
valid_channels = {'default', 'local', DEFAULT_CHANNEL}
channel_list = None
def remap_pip_package(pkg):
if pkg in cm_global.pip_overrides:
res = cm_global.pip_overrides[pkg]
print(f"[ComfyUI-Manager] '{pkg}' is remapped to '{res}'")
return res
else:
return pkg
def is_blacklisted(name):
return manager_util.pip_block_reason(name, cm_global.pip_blacklist, cm_global.pip_downgrade_blacklist) is not None
def normalize_channel_url(url):
return DEFAULT_CHANNEL if url in DEFAULT_CHANNEL_URLS else url
def normalize_channel(channel):
if channel == 'local':
return channel
elif channel is None:
return None
elif channel.startswith('https://'):
return channel
return normalize_channel_url(channel)
elif channel.startswith('http://') and get_config()['http_channel_enabled'] == True:
return channel
@@ -383,11 +377,12 @@ class UnifiedManager:
if latest is not None:
version_spec = str(latest[0])
elif node_name in self.nightly_inactive_nodes:
version_spec = "nightly"
elif node_name in self.unknown_inactive_nodes:
version_spec = "unknown"
else:
if node_name in self.nightly_inactive_nodes:
version_spec = "nightly"
else:
version_spec = "unknown"
return None
elif node_name in self.unknown_inactive_nodes:
version_spec = "unknown"
@@ -425,7 +420,8 @@ class UnifiedManager:
spec = node_name.split('@')
if len(spec) == 2:
# 'latest' names no installed version: with a guess mode the installed one is guessed, as for a bare name
if len(spec) == 2 and (spec[1] != 'latest' or guess_mode is None):
node_name = spec[0]
version_spec = spec[1]
@@ -436,6 +432,11 @@ class UnifiedManager:
else:
version_spec = self.cnr_map[node_name]['latest_version']['version']
if guess_mode == 'active' and not self.is_enabled(node_name, version_spec):
return None
elif guess_mode == 'inactive' and not self.is_disabled(node_name, version_spec):
return None
elif guess_mode in ['active', 'inactive']:
node_name = spec[0]
version_spec = self.resolve_unspecified_version(node_name, guess_mode=guess_mode)
@@ -552,6 +553,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:
@@ -652,7 +659,7 @@ class UnifiedManager:
return True
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
@@ -695,13 +702,8 @@ class UnifiedManager:
latest = None
for k, v in ver_map.items():
if latest is None:
latest = self.safe_version(k), v
continue
cur_ver = self.safe_version(k)
if cur_ver > latest[0]:
latest = cur_ver, v
if latest is None or self.safe_version(k) > self.safe_version(latest[0]):
latest = k, v
return latest
@@ -850,12 +852,14 @@ class UnifiedManager:
# a fix is held back by what the same fix has done, and not by an install or another fix of the session
done = self.processed_install if fixed is None else fixed
for line in lines:
package_name = remap_pip_package(line.strip())
if package_name and not package_name.startswith('#') and package_name not in done:
clean_package_name = package_name.split('#')[0].strip()
install_cmd = manager_util.make_pip_cmd(["install", clean_package_name]) if fixed is None else manager_util.fix_cmd(clean_package_name)
if clean_package_name != "" and not clean_package_name.startswith('#'):
res = res and try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
install_args = manager_util.pip_install_args(line, cm_global.pip_overrides)
package_name = ' '.join(install_args)
names_a_path = any(os.path.exists(os.path.join(repo_path, re.split(r'[\[;]', arg)[0].strip())) for arg in install_args)
if names_a_path:
package_name = f'{repo_path}: {package_name}'
if install_args and package_name not in done:
install_cmd = manager_util.make_pip_cmd(["install", *install_args]) if fixed is None else manager_util.fix_cmd(install_args)
res = res and try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
if res:
self.processed_install.add(package_name)
done.add(package_name)
@@ -993,6 +997,22 @@ class UnifiedManager:
return result
def disable_for_replacement(self, node_id, to_path):
"""
Disable the enabled version of node_id, for another version that goes to to_path.
Fails with nothing changed when anything but the folder of the enabled version is at to_path.
"""
result = ManagedResult('disable')
enabled = self.active_nodes.get(node_id)
on_disk = enabled is not None and os.path.exists(enabled[1])
if os.path.lexists(to_path) and not (on_disk and os.path.samestat(os.lstat(enabled[1]), os.lstat(to_path))):
return result.fail(f'Destination already exists: {to_path}')
if on_disk:
return self.unified_disable(node_id, False)
return result
def unified_enable(self, node_id: str, version_spec=None):
"""
priority if version_spec == None
@@ -1009,7 +1029,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):
@@ -1030,14 +1050,12 @@ class UnifiedManager:
base_path = extract_base_custom_nodes_dir(from_path)
to_path = os.path.join(base_path, node_id)
elif version_spec == 'nightly':
self.unified_disable(node_id, False)
from_path = self.nightly_inactive_nodes.get(node_id)
if from_path is None:
return result.fail(f'Specified inactive node not exists: {node_id}@nightly')
base_path = extract_base_custom_nodes_dir(from_path)
to_path = os.path.join(base_path, node_id)
elif version_spec is not None:
self.unified_disable(node_id, False)
cnr_info = self.cnr_inactive_nodes.get(node_id)
if cnr_info is None or len(cnr_info) == 0:
@@ -1056,6 +1074,14 @@ class UnifiedManager:
if from_path is None or not os.path.exists(from_path):
return result.fail(f'Specified inactive node path not exists: {from_path}')
if version_spec == 'unknown':
if os.path.lexists(to_path):
return result.fail(f'Destination already exists: {to_path}')
else:
res = self.disable_for_replacement(node_id, to_path)
if not res.result:
return res
# move from disk
shutil.move(from_path, to_path)
@@ -1098,6 +1124,8 @@ class UnifiedManager:
base_path = extract_base_custom_nodes_dir(repo_and_path[1])
to_path = os.path.join(base_path, '.disabled', node_id)
if os.path.lexists(to_path):
return result.fail(f'Destination already exists: {to_path}')
shutil.move(repo_and_path[1], to_path)
result.append((repo_and_path[1], to_path))
@@ -1117,6 +1145,9 @@ class UnifiedManager:
# NOTE: A disabled node may have multiple versions, so preserve it using the `@ suffix`.
to_path = os.path.join(base_path, '.disabled', f"{node_id}@{ver_and_path[0].replace('.', '_')}")
if os.path.lexists(to_path):
return result.fail(f'Destination already exists: {to_path}')
shutil.move(ver_and_path[1], to_path)
result.append((ver_and_path[1], to_path))
@@ -1240,7 +1271,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)
@@ -1440,7 +1475,9 @@ class UnifiedManager:
if version_spec == 'nightly':
# disable cnr nodes
if self.is_enabled(node_id, 'cnr'):
self.unified_disable(node_id, False)
res = self.disable_for_replacement(node_id, to_path)
if not res.result:
return res
res = self.repo_install(repo_url, to_path, instant_execution=instant_execution, no_deps=no_deps, return_postinstall=return_postinstall)
if res.result:
@@ -1468,6 +1505,8 @@ class UnifiedManager:
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):
@@ -1500,22 +1539,26 @@ class UnifiedManager:
if node_info is None or not node_info.download_url:
return ManagedResult('install-cnr').fail(f'not available node: {node_id}@{version_spec}')
if self.is_enabled(node_id, 'nightly'):
# disable nightly nodes
self.unified_disable(node_id, False) # NOTE: don't return from here
if self.is_disabled(node_id, version_spec):
# enable and return if specified version is disabled
return self.unified_enable(node_id, version_spec)
if self.is_disabled(node_id, "cnr"):
# enable and switch version if cnr is disabled (not specified version)
self.unified_enable(node_id, "cnr")
res = self.unified_enable(node_id, "cnr")
if not res.result:
return res
return self._cnr_switch_version(node_id, node_info, instant_execution, no_deps, return_postinstall)
if self.is_enabled(node_id, "cnr"):
return self._cnr_switch_version(node_id, node_info, instant_execution, no_deps, return_postinstall)
if self.is_enabled(node_id, 'nightly'):
# disable nightly nodes
res = self.disable_for_replacement(node_id, os.path.join(get_default_custom_nodes_path(), node_id))
if not res.result:
return res
res = self._cnr_install(node_id, node_info, instant_execution, no_deps, return_postinstall)
if res.result:
self.active_nodes[node_id] = version_spec, res.to_path
@@ -1800,8 +1843,9 @@ def get_channel_dict():
for x in channels.split('\n'):
channel_info = x.split("::")
if len(channel_info) == 2:
channel_dict[channel_info[0]] = channel_info[1]
valid_channels.add(channel_info[1])
channel_url = normalize_channel_url(channel_info[1])
channel_dict[channel_info[0]] = channel_url
valid_channels.add(channel_url)
return channel_dict
@@ -1881,6 +1925,7 @@ def read_config():
return default_conf[key].lower() == 'true' if key in default_conf else False
manager_util.use_uv = default_conf['use_uv'].lower() == 'true' if 'use_uv' in default_conf else False
manager_util.apply_dependency_management_setting(default_conf.get('dependency_management'))
# Don't override use_unified_resolver here: prestartup_script.py already reads config
# and sets this flag, then may reset it to False on resolver fallback.
# Re-reading from config would undo the fallback.
@@ -1892,7 +1937,7 @@ def read_config():
'git_exe': default_conf.get('git_exe', '', raw=True),
'use_uv': get_bool('use_uv', True),
'use_unified_resolver': get_bool('use_unified_resolver', False),
'channel_url': default_conf.get('channel_url', DEFAULT_CHANNEL),
'channel_url': normalize_channel_url(default_conf.get('channel_url', DEFAULT_CHANNEL)),
'default_cache_as_channel_url': get_bool('default_cache_as_channel_url', False),
'share_option': default_conf.get('share_option', 'all').lower(),
'bypass_ssl': get_bool('bypass_ssl', False),
@@ -2163,27 +2208,10 @@ def execute_install_script(url, repo_path, lazy_mode=False, instant_execution=Fa
elif os.path.exists(requirements_path) and not no_deps:
print("Install: pip packages")
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), context.comfy_path, context.manager_files_path)
with open(requirements_path, "r") as requirements_file:
for line in requirements_file:
#handle comments
if '#' in line:
if line.strip()[0] == '#':
print("Line is comment...skipping")
continue
else:
line = line.split('#')[0].strip()
package_name = remap_pip_package(line.strip())
if package_name and not package_name.startswith('#'):
if '--index-url' in package_name:
s = package_name.split('--index-url')
install_cmd = manager_util.make_pip_cmd(["install", s[0].strip(), '--index-url', s[1].strip()])
else:
install_cmd = manager_util.make_pip_cmd(["install", package_name])
if package_name.strip() != "" and not package_name.startswith('#'):
try_install_script(url, repo_path, install_cmd, 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):
@@ -2210,13 +2238,9 @@ def install_manager_requirements(repo_path):
logging.info("[ComfyUI-Manager] Installing manager_requirements.txt")
with open(manager_requirements_path, "r") as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
if '#' in line:
line = line.split('#')[0].strip()
if line:
install_cmd = manager_util.make_pip_cmd(["install", line])
subprocess.run(install_cmd)
install_args = manager_util.pip_install_args(line, {})
if install_args:
subprocess.run(manager_util.make_pip_cmd(["install", *install_args]))
def git_repo_update_check_with(path, do_fetch=False, do_update=False, no_deps=False):
@@ -2489,23 +2513,26 @@ def git_pull(path):
async def get_data_by_mode(mode, filename, channel_url=None):
if channel_url in get_channel_dict():
channel_url = get_channel_dict()[channel_url]
try:
local_uri = os.path.join(manager_util.comfyui_manager_path, filename)
if mode == "local":
json_obj = await manager_util.get_data(local_uri)
else:
if channel_url is None:
uri = get_config()['channel_url'] + '/' + filename
else:
uri = channel_url + '/' + filename
channel_url = normalize_channel(channel_url) or get_config()['channel_url']
uri = channel_url + '/' + filename
cache_uri = str(manager_util.simple_hash(uri))+'_'+filename
cache_uri = os.path.join(manager_util.cache_dir, cache_uri)
if mode == "remote" and get_config()['network_mode'] != 'offline' and manager_util.is_manager_pip_package():
try:
json_obj = await manager_util.get_data(uri)
manager_util.write_cache_file(cache_uri, json_obj)
return json_obj
except Exception as e:
print(f"[ComfyUI-Manager] Due to a network error, switching to cache mode.\n=> {filename} @ {channel_url}/{mode}\n=> {e}")
if get_config()['network_mode'] == 'offline' or manager_util.is_manager_pip_package():
# offline network mode
if os.path.exists(cache_uri):
@@ -2629,70 +2656,6 @@ def gitclone_uninstall(files):
return True
def gitclone_set_active(files, is_disable):
import os
if is_disable:
action_name = "Disable"
else:
action_name = "Enable"
print(f"{action_name}: {files}")
for url in files:
if url.endswith("/"):
url = url[:-1]
try:
for custom_nodes_dir in get_custom_nodes_paths():
dir_name:str = os.path.splitext(os.path.basename(url))[0].replace(".git", "")
dir_path = os.path.join(custom_nodes_dir, dir_name)
# safety check
if dir_path == '/' or dir_path[1:] == ":/" or dir_path == '':
print(f"{action_name}(git-clone) error: invalid path '{dir_path}' for '{url}'")
return False
if is_disable:
current_path = dir_path
base_path = extract_base_custom_nodes_dir(current_path)
new_path = os.path.join(base_path, ".disabled", dir_name)
if not os.path.exists(current_path):
continue
else:
current_path1 = os.path.join(get_default_custom_nodes_path(), ".disabled", dir_name)
current_path2 = dir_path + ".disabled"
if os.path.exists(current_path1):
current_path = current_path1
elif os.path.exists(current_path2):
current_path = current_path2
else:
continue
base_path = extract_base_custom_nodes_dir(current_path)
new_path = os.path.join(base_path, dir_name)
shutil.move(current_path, new_path)
if is_disable:
if os.path.exists(os.path.join(new_path, "disable.py")):
disable_script = [sys.executable, "disable.py"]
try_install_script(url, new_path, disable_script)
else:
if os.path.exists(os.path.join(new_path, "enable.py")):
enable_script = [sys.executable, "enable.py"]
try_install_script(url, new_path, enable_script)
break # for safety
except Exception as e:
print(f"{action_name}(git-clone) error: {url} / {e}", file=sys.stderr)
return False
print(f"{action_name} was successful.")
return True
def gitclone_update(files, instant_execution=False, skip_script=False, msg_prefix="", no_deps=False):
import os
@@ -2859,17 +2822,6 @@ def lookup_installed_custom_nodes_legacy(repo_name):
return None
def simple_check_custom_node(url):
dir_name = os.path.splitext(os.path.basename(url))[0].replace(".git", "")
dir_path = os.path.join(get_default_custom_nodes_path(), dir_name)
if os.path.exists(dir_path):
return 'installed'
elif os.path.exists(dir_path+'.disabled'):
return 'disabled'
return 'not-installed'
def check_state_of_git_node_pack_single(item, do_fetch=False, do_update_check=True, do_update=False):
if item['version'] == 'unknown':
dir_path = unified_manager.unknown_active_nodes.get(item['id'])[1]
@@ -2959,6 +2911,9 @@ async def get_current_snapshot(custom_nodes_only = False):
else:
commit_hash = git_utils.get_commit_hash(fullpath)
url = git_utils.git_url(fullpath)
# of two clones of a repository, the enabled one is what a restore brings back
if is_disabled and url in git_custom_nodes:
continue
git_custom_nodes[url] = dict(hash=commit_hash, disabled=is_disabled)
except Exception:
print(f"Failed to extract snapshots for the custom node '{path}'.")
@@ -3254,8 +3209,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]):
@@ -3277,6 +3232,7 @@ 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
@@ -3446,10 +3402,14 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
norm_k = git_utils.normalize_url(k)
# a node pack saved at a version of the registry has the clone it keeps disabled as a git entry
# a clone saved as disabled is left out: the restore then disables it, leaves it disabled or does not clone it.
# A nodepack saved at a version of the registry has such a clone, which is restored when that version could not be
cnr = unified_manager.repo_cnr_map.get(norm_k)
version = (cnr_info or {}).get(cnr['id']) if cnr is not None else None
if version is not None and unified_manager.is_enabled(cnr['id'], 'cnr') and f"{cnr['id']}@{version}" not in failed:
if version is None:
if v.get('disabled'):
continue
elif unified_manager.is_enabled(cnr['id'], 'cnr') and f"{cnr['id']}@{version}" not in failed:
continue
git_info[norm_k] = v
+10 -6
View File
@@ -895,8 +895,12 @@ async def task_worker():
if replaces_cnr_with_nightly(cnr_id) and not security_utils.is_allowed_security_level('middle+'):
logging.error(SECURITY_MESSAGE_MIDDLE_P)
return OperationResult.failed.value
core.unified_manager.unified_enable(cnr_id)
return OperationResult.success.value
res = core.unified_manager.unified_enable(cnr_id)
if res.result:
return OperationResult.success.value
logging.error(f"[ComfyUI-Manager] Failed to enable '{cnr_id}': {res.msg}")
return f"Failed to enable: '{cnr_id}'"
async def do_update(params: UpdatePackParams) -> dict[str, str]:
node_name = params.node_name
@@ -1064,9 +1068,10 @@ async def task_worker():
try:
res = core.unified_manager.unified_disable(node_name, is_unknown)
if res:
if res.result:
return OperationResult.success.value
logging.error(f"[ComfyUI-Manager] Failed to disable '{node_name}': {res.msg}")
except Exception:
traceback.print_exc()
@@ -2201,10 +2206,9 @@ async def default_cache_update():
a = get_cache("custom-node-list.json")
b = get_cache("extension-node-map.json")
c = get_cache("model-list.json")
d = get_cache("alter-list.json")
e = get_cache("github-stats.json")
d = get_cache("github-stats.json")
await asyncio.gather(a, b, c, d, e)
await asyncio.gather(a, b, c, d)
if core.get_config()["network_mode"] == "private":
logging.info(
@@ -124,7 +124,6 @@ def initialize_environment():
# Legacy database paths - kept for potential future use
# local_db_model = os.path.join(manager_util.comfyui_manager_path, "model-list.json")
# local_db_alter = os.path.join(manager_util.comfyui_manager_path, "alter-list.json")
# local_db_custom_node_list = os.path.join(
# manager_util.comfyui_manager_path, "custom-node-list.json"
# )
+3 -1
View File
@@ -127,8 +127,10 @@ def check_model_installed(json_obj):
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"]:
+1 -1
View File
@@ -53,7 +53,7 @@ async def get_risky_level(files, pip_packages):
json_data2 = await core.get_data_by_mode(
ManagerDatabaseSource.cache.value,
"custom-node-list.json",
channel_url="https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main",
channel_url=core.DEFAULT_CHANNEL,
)
all_urls = set()
+3 -13
View File
@@ -131,17 +131,6 @@ docStyle.innerHTML = `
text-decoration: underline;
}
#alternatives-grid a {
color: #5555FF;
font-weight: bold;
text-decoration: none;
}
#alternatives-grid a:hover {
color: #7777FF;
text-decoration: underline;
}
.cm-notice-board {
width: auto;
height: 280px;
@@ -717,7 +706,7 @@ async function onQueueStatus(event) {
let msg = "";
if(success_list.length == 0 && comfyui_state.startsWith('skip')) {
if(success_list.length == 0 && (comfyui_state == null || comfyui_state.startsWith('skip'))) {
if(failed_list.length == 0) {
msg += "You are already up to date.";
}
@@ -729,7 +718,7 @@ async function onQueueStatus(event) {
msg += "ComfyUI has been updated to latest nightly version.<BR><BR>";
infoToast("ComfyUI has been updated to the latest nightly version.");
}
else if(comfyui_state.startsWith('success-stable')) {
else if(comfyui_state?.startsWith('success-stable')) {
const ver = comfyui_state.split("-").pop();
msg += `ComfyUI has been updated to ${ver}.<BR><BR>`;
infoToast(`ComfyUI has been updated to ${ver}`);
@@ -805,6 +794,7 @@ async function updateAll(update_comfyui) {
batch_id = generateUUID();
let batch = {};
batch['batch_id'] = batch_id;
if(update_comfyui) {
update_all_button.innerText = "Updating ComfyUI...";
batch['update_comfyui'] = true;
+1 -14
View File
@@ -218,6 +218,7 @@
.cn-manager-grid .cn-pack-conflicts {
color: orange;
white-space: normal;
}
.cn-popover {
@@ -590,20 +591,6 @@
word-break: break-word;
}
.cn-tag-list {
display: flex;
flex-wrap: wrap;
gap: 5px;
align-items: center;
margin-bottom: 5px;
}
.cn-tag-list > div {
background-color: var(--border-color);
border-radius: 5px;
padding: 0 5px;
}
.cn-install-buttons {
display: flex;
flex-direction: column;
+74 -76
View File
@@ -44,7 +44,6 @@ const ShowMode = {
UPDATE: "Update",
MISSING: "Missing",
FAVORITES: "Favorites",
ALTERNATIVES: "Alternatives",
IN_WORKFLOW: "In Workflow",
};
@@ -289,10 +288,6 @@ export class CustomNodesManager {
label: "Favorites",
value: ShowMode.FAVORITES,
hasData: false
}, {
label: "Alternatives of A1111",
value: ShowMode.ALTERNATIVES,
hasData: false
}];
this.filterList = filterList;
$filter.innerHTML = filterList.map(item => {
@@ -607,7 +602,7 @@ export class CustomNodesManager {
bindContainerResize: true,
cellResizeObserver: (rowItem, columnItem) => {
const autoHeightColumns = ['title', 'action', 'description', "alternatives"];
const autoHeightColumns = ['title', 'action', 'description'];
return autoHeightColumns.includes(columnItem.id)
},
@@ -625,9 +620,6 @@ export class CustomNodesManager {
rowFilter: (rowItem) => {
const searchableColumns = ["title", "author", "description"];
if (this.hasAlternatives()) {
searchableColumns.push("alternatives");
}
let shouldShown = grid.highlightKeywordsFilter(rowItem, searchableColumns, this.keywords);
@@ -742,10 +734,6 @@ export class CustomNodesManager {
return 1 / distance;
}
hasAlternatives() {
return this.filter === ShowMode.ALTERNATIVES
}
async handleImportFail(rowItem) {
var info;
if(rowItem.version == 'unknown'){
@@ -895,16 +883,12 @@ 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("");
}
}, {
id: "alternatives",
name: "Alternatives",
width: 400,
maxWidth: 5000,
invisible: !this.hasAlternatives(),
classMap: 'cn-pack-desc' // composed HTML; tags are escaped in getAlternatives
}, {
id: 'description',
name: 'Description',
@@ -989,11 +973,6 @@ export class CustomNodesManager {
updateGrid() {
if (this.grid) {
this.grid.update();
if (this.hasAlternatives()) {
this.grid.showColumn("alternatives");
} else {
this.grid.hideColumn("alternatives");
}
}
}
@@ -1350,8 +1329,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';
}
@@ -1360,8 +1340,9 @@ export class CustomNodesManager {
// `it.name` is a raw node name from getmappings (not the pack name)
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}">${String(c.title ?? '')}</div>`;
}).join("<b>,</b>")}</div>`);
}
@@ -1404,6 +1385,7 @@ export class CustomNodesManager {
}
const conflictsMap = {};
const nodesMapByPack = new Map();
// add nodes data
Object.keys(data).forEach(k => {
@@ -1416,9 +1398,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
};
@@ -1430,6 +1415,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)
@@ -1446,13 +1432,15 @@ export class CustomNodesManager {
cList.forEach(key => {
const nodeItem = node_packs[key];
const extItem = nodeItem.nodesMap[extName];
if(!extItem.conflicts) {
extItem.conflicts = []
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
@@ -1466,6 +1454,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;
}
})
@@ -1655,7 +1644,8 @@ export class CustomNodesManager {
}
}
this.install_context = {btn: btn, targets: target_items};
const context = {btn: btn, targets: target_items};
this.install_context = context;
if(errorMsg) {
this.showError(errorMsg);
@@ -1713,6 +1703,7 @@ export class CustomNodesManager {
return;
}
context.queued = true;
this.showStop();
}
}
@@ -1792,6 +1783,37 @@ export class CustomNodesManager {
self.hideStop();
self.onQueueCompleted(event.detail);
}
else if(event.detail.status == 'all-done') {
self.endDroppedInstall();
}
}
// The end of the queue was reported and the install did not get the end of its batch: Stop dropped
// the batch. The report can also be that of a queue that ran before the batch was added, so the
// install is ended only if the queue is not running now.
async endDroppedInstall() {
const context = this.install_context;
if(!context?.queued) {
return;
}
// Without an answer the queue may still be running.
const { data } = await fetchData('/v2/manager/queue/status');
if(!data || data.is_processing) {
return;
}
context.btn.target.classList.remove("cn-btn-loading");
for(const item of context.targets) {
this.grid.updateCell(item, "action");
}
this.hideStop();
this.install_context = undefined;
if(context.targets.some(item => item.restart)) {
this.showRestart();
this.showMessage(`To apply the installed/updated/disabled/enabled custom node, please restart ComfyUI. And refresh browser.`, "red");
}
}
async onQueueCompleted(info) {
@@ -1884,6 +1906,21 @@ export class CustomNodesManager {
return allUsedNodes;
}
getNodepackByCnrId(cnr_id) {
let item = this.custom_nodes[cnr_id];
// comfy-core is ComfyUI itself, not a nodepack that is named so in another case
if(item || cnr_id == 'comfy-core') {
return item;
}
const normalized_id = String(cnr_id).toLowerCase();
for(let k in this.custom_nodes) {
if(k.toLowerCase() == normalized_id) {
return this.custom_nodes[k];
}
}
}
async getMissingNodes() {
let unresolved_missing_nodes = new Set();
let hashMap = {};
@@ -1908,7 +1945,7 @@ export class CustomNodesManager {
outdated_comfyui = true;
}
let item = this.custom_nodes[node.properties.cnr_id];
let item = this.getNodepackByCnrId(node.properties.cnr_id);
if(item) {
hashMap[item.hash] = true;
}
@@ -2078,7 +2115,7 @@ export class CustomNodesManager {
for(let k in allUsedNodes) {
var item;
if(allUsedNodes[k].properties.cnr_id) {
item = this.custom_nodes[allUsedNodes[k].properties.cnr_id];
item = this.getNodepackByCnrId(allUsedNodes[k].properties.cnr_id);
}
else if(allUsedNodes[k].properties.aux_id) {
item = aux_id_to_pack[allUsedNodes[k].properties.aux_id];
@@ -2091,40 +2128,6 @@ export class CustomNodesManager {
return hashMap;
}
async getAlternatives() {
const mode = manager_instance.datasrc_combo.value;
this.showStatus(`Loading alternatives (${mode}) ...`);
const res = await fetchData(`/v2/customnode/alternatives?mode=${mode}`);
if (res.error) {
this.showError(`Failed to get alternatives: ${sanitizeHTML(String(res.error))}`);
return [];
}
const hashMap = {};
const items = res.data;
for(let i in items) {
let item = items[i];
let custom_node = this.custom_nodes[i];
if (!custom_node) {
console.log(`Not found custom node: ${item.id}`);
continue;
}
const tags = `${item.tags}`.split(",").map(tag => {
return `<div>${sanitizeHTML(tag.trim())}</div>`;
}).join("");
hashMap[custom_node.hash] = {
alternatives: `<div class="cn-tag-list">${tags}</div> ${item.description}`
}
}
return hashMap;
}
async loadData(show_mode = ShowMode.NORMAL) {
const isElectron = 'electronAPI' in window;
@@ -2201,8 +2204,6 @@ export class CustomNodesManager {
}
} else if(this.show_mode == ShowMode.MISSING) {
hashMap = await this.getMissingNodes();
} else if(this.show_mode == ShowMode.ALTERNATIVES) {
hashMap = await this.getAlternatives();
} else if(this.show_mode == ShowMode.FAVORITES) {
hashMap = await this.getFavorites();
} else if(this.show_mode == ShowMode.IN_WORKFLOW) {
@@ -2249,9 +2250,6 @@ export class CustomNodesManager {
if (value === ShowMode.MISSING) {
nodeItem['missing-node'] = "true";
}
if (typeof hashData === "object") {
Object.assign(nodeItem, hashData);
}
}
} else {
if (nodeItem.state === value) {
+10 -21
View File
@@ -258,31 +258,20 @@ export class ModelManager {
rowFilter: (rowItem) => {
const searchableColumns = ["name", "type", "base", "description", "filename", "save_path"];
const models_extensions = ['.ckpt', '.pt', '.pt2', '.bin', '.pth', '.safetensors', '.pkl', '.sft'];
let shouldShown = grid.highlightKeywordsFilter(rowItem, searchableColumns, this.keywords);
if (shouldShown) {
if(this.filter) {
if (this.filter == "in_workflow") {
rowItem.in_workflow = null;
if (Array.isArray(app.graph._nodes)) {
app.graph._nodes.forEach((item, i) => {
if (Array.isArray(item.widgets_values)) {
item.widgets_values.forEach((_item, i) => {
if (rowItem.in_workflow === null && _item !== null && models_extensions.includes("." + _item.toString().split('.').pop())) {
let filename = _item.match(/([^\/]+)(?=\.\w+$)/)[0];
if (grid.highlightKeywordsFilter(rowItem, searchableColumns, filename)) {
rowItem.in_workflow = "True";
grid.highlightKeywordsFilter(rowItem, searchableColumns, "");
}
}
});
}
});
}
}
return ((this.filter == "installed" && rowItem.installed == "True") || (this.filter == "not_installed" && rowItem.installed == "False") || (this.filter == "in_workflow" && rowItem.in_workflow == "True"));
if(this.filter == "installed" && rowItem.installed !== "True") {
return false;
}
if(this.filter == "not_installed" && rowItem.installed !== "False") {
return false;
}
if(this.filter == "in_workflow" && !app.graph._nodes.some(node => Array.isArray(node.widgets_values) && node.widgets_values.some(value => String(value).split(/[\\/]/).pop() === rowItem.filename))) {
return false;
}
if(this.type && rowItem.type !== this.type) {
+1 -1
View File
@@ -67,7 +67,7 @@ class WorkflowMetadataExtension {
this.installedNodes[nodePackageName.toLowerCase()] ??
{};
if (cnr_id === "comfy-core") return; // don't allow hijacking comfy-core name
if (cnr_id?.toLowerCase() === "comfy-core") return; // don't allow hijacking comfy-core name
if (cnr_id) nodeProperties.cnr_id = cnr_id;
else nodeProperties.aux_id = aux_id;
if (ver) nodeProperties.ver = ver.trim();
+132 -156
View File
@@ -46,10 +46,9 @@ from ..common.enums import NetworkMode, SecurityLevel, DBMode
from ..common import context
def print(*objects, sep=" ", end="\n", file=None):
# rich's print with its highlighting only, so that a path, a URL or an error text is written as it is
def print(*objects, sep=" ", end="\n", file=None, style=None):
console = rich.get_console() if file is None else Console(file=file)
console.print(*objects, sep=sep, end=end, markup=False, emoji=False, soft_wrap=True)
console.print(*objects, sep=sep, end=end, style=style, highlight=style is None, markup=False, emoji=False, soft_wrap=True)
try:
@@ -62,7 +61,7 @@ version_str = f"V{_raw_version}"
DEFAULT_CHANNEL = "https://raw.githubusercontent.com/Comfy-Org/ComfyUI-Manager/main"
DEFAULT_CHANNEL_LEGACY = "https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main"
DEFAULT_CHANNEL_URLS = {"https://raw.githubusercontent.com/Comfy-Org/ComfyUI-Manager/main", "https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main"}
# SSH git URL pattern (e.g., git@github.com:user/repo.git)
SSH_URL_PATTERN = re.compile(r"^(.+@|ssh://).+:.+$")
@@ -172,30 +171,25 @@ comfy_ui_revision = "Unknown"
comfy_ui_commit_datetime = datetime(1900, 1, 1, 0, 0, 0)
channel_dict = None
valid_channels = {'default', 'local', DEFAULT_CHANNEL, DEFAULT_CHANNEL_LEGACY}
valid_channels = {'default', 'local', DEFAULT_CHANNEL}
channel_list = None
def remap_pip_package(pkg):
if pkg in cm_global.pip_overrides:
res = cm_global.pip_overrides[pkg]
print(f"[ComfyUI-Manager] '{pkg}' is remapped to '{res}'")
return res
else:
return pkg
def is_blacklisted(name):
return manager_util.pip_block_reason(name, cm_global.pip_blacklist, cm_global.pip_downgrade_blacklist) is not None
def normalize_channel_url(url):
return DEFAULT_CHANNEL if url in DEFAULT_CHANNEL_URLS else url
def normalize_channel(channel):
if channel == 'local':
return channel
elif channel is None:
return None
elif channel.startswith('https://'):
return channel
return normalize_channel_url(channel)
elif channel.startswith('http://') and get_config()['http_channel_enabled'] == True:
return channel
@@ -373,11 +367,12 @@ class UnifiedManager:
if latest is not None:
version_spec = str(latest[0])
elif node_name in self.nightly_inactive_nodes:
version_spec = "nightly"
elif node_name in self.unknown_inactive_nodes:
version_spec = "unknown"
else:
if node_name in self.nightly_inactive_nodes:
version_spec = "nightly"
else:
version_spec = "unknown"
return None
elif node_name in self.unknown_inactive_nodes:
version_spec = "unknown"
@@ -415,7 +410,8 @@ class UnifiedManager:
spec = node_name.split('@')
if len(spec) == 2:
# 'latest' names no installed version: with a guess mode the installed one is guessed, as for a bare name
if len(spec) == 2 and (spec[1] != 'latest' or guess_mode is None):
node_name = spec[0]
version_spec = spec[1]
@@ -426,6 +422,11 @@ class UnifiedManager:
else:
version_spec = self.cnr_map[node_name]['latest_version']['version']
if guess_mode == 'active' and not self.is_enabled(node_name, version_spec):
return None
elif guess_mode == 'inactive' and not self.is_disabled(node_name, version_spec):
return None
elif guess_mode in ['active', 'inactive']:
node_name = spec[0]
version_spec = self.resolve_unspecified_version(node_name, guess_mode=guess_mode)
@@ -542,6 +543,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:
@@ -603,7 +610,7 @@ class UnifiedManager:
return True
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
@@ -646,13 +653,8 @@ class UnifiedManager:
latest = None
for k, v in ver_map.items():
if latest is None:
latest = self.safe_version(k), v
continue
cur_ver = self.safe_version(k)
if cur_ver > latest[0]:
latest = cur_ver, v
if latest is None or self.safe_version(k) > self.safe_version(latest[0]):
latest = k, v
return latest
@@ -798,11 +800,14 @@ class UnifiedManager:
# a fix is held back by what the same fix has done, and not by an install or another fix of the session
done = self.processed_install if fixed is None else fixed
for line in lines:
package_name = remap_pip_package(line.strip())
if package_name and not package_name.startswith('#') and package_name not in done:
install_cmd = manager_util.make_pip_cmd(["install", package_name]) if fixed is None else manager_util.fix_cmd(package_name)
if package_name.strip() != "" and not package_name.startswith('#'):
res = res and try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
install_args = manager_util.pip_install_args(line, cm_global.pip_overrides)
package_name = ' '.join(install_args)
names_a_path = any(os.path.exists(os.path.join(repo_path, re.split(r'[\[;]', arg)[0].strip())) for arg in install_args)
if names_a_path:
package_name = f'{repo_path}: {package_name}'
if install_args and package_name not in done:
install_cmd = manager_util.make_pip_cmd(["install", *install_args]) if fixed is None else manager_util.fix_cmd(install_args)
res = res and try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
if res:
self.processed_install.add(package_name)
done.add(package_name)
@@ -940,6 +945,22 @@ class UnifiedManager:
return result
def disable_for_replacement(self, node_id, to_path):
"""
Disable the enabled version of node_id, for another version that goes to to_path.
Fails with nothing changed when anything but the folder of the enabled version is at to_path.
"""
result = ManagedResult('disable')
enabled = self.active_nodes.get(node_id)
on_disk = enabled is not None and os.path.exists(enabled[1])
if os.path.lexists(to_path) and not (on_disk and os.path.samestat(os.lstat(enabled[1]), os.lstat(to_path))):
return result.fail(f'Destination already exists: {to_path}')
if on_disk:
return self.unified_disable(node_id, False)
return result
def unified_enable(self, node_id: str, version_spec=None):
"""
priority if version_spec == None
@@ -957,7 +978,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):
@@ -978,14 +999,12 @@ class UnifiedManager:
base_path = extract_base_custom_nodes_dir(from_path)
to_path = os.path.join(base_path, node_id)
elif version_spec == 'nightly':
self.unified_disable(node_id, False)
from_path = self.nightly_inactive_nodes.get(node_id)
if from_path is None:
return result.fail(f'Specified inactive node not exists: {node_id}@nightly')
base_path = extract_base_custom_nodes_dir(from_path)
to_path = os.path.join(base_path, node_id)
elif version_spec is not None:
self.unified_disable(node_id, False)
cnr_info = self.cnr_inactive_nodes.get(node_id)
if cnr_info is None or len(cnr_info) == 0:
@@ -1004,6 +1023,14 @@ class UnifiedManager:
if from_path is None or not os.path.exists(from_path):
return result.fail(f'Specified inactive node path not exists: {from_path}')
if version_spec == 'unknown':
if os.path.lexists(to_path):
return result.fail(f'Destination already exists: {to_path}')
else:
res = self.disable_for_replacement(node_id, to_path)
if not res.result:
return res
# move from disk
shutil.move(from_path, to_path)
@@ -1046,6 +1073,8 @@ class UnifiedManager:
base_path = extract_base_custom_nodes_dir(repo_and_path[1])
to_path = os.path.join(base_path, '.disabled', node_id)
if os.path.lexists(to_path):
return result.fail(f'Destination already exists: {to_path}')
shutil.move(repo_and_path[1], to_path)
result.append((repo_and_path[1], to_path))
@@ -1065,6 +1094,9 @@ class UnifiedManager:
# NOTE: A disabled node may have multiple versions, so preserve it using the `@ suffix`.
to_path = os.path.join(base_path, '.disabled', f"{node_id}@{ver_and_path[0].replace('.', '_')}")
if os.path.lexists(to_path):
return result.fail(f'Destination already exists: {to_path}')
shutil.move(ver_and_path[1], to_path)
result.append((ver_and_path[1], to_path))
@@ -1188,7 +1220,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)
@@ -1384,6 +1420,8 @@ class UnifiedManager:
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):
@@ -1394,7 +1432,7 @@ class UnifiedManager:
if version_spec in ('unknown', 'nightly'):
try:
repo_url = await self._get_git_install_url(node_id, version_spec, channel, mode)
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}')
except LookupError as exc:
@@ -1417,29 +1455,33 @@ class UnifiedManager:
if node_info is None or not node_info.download_url:
return ManagedResult('install-cnr').fail(f'not available node: {node_id}@{version_spec}')
if self.is_enabled(node_id, 'nightly'):
# disable nightly nodes
self.unified_disable(node_id, False) # NOTE: don't return from here
if self.is_disabled(node_id, version_spec):
# enable and return if specified version is disabled
return self.unified_enable(node_id, version_spec)
if self.is_disabled(node_id, "cnr"):
# enable and switch version if cnr is disabled (not specified version)
self.unified_enable(node_id, "cnr")
res = self.unified_enable(node_id, "cnr")
if not res.result:
return res
return self._cnr_switch_version(node_id, node_info, instant_execution, no_deps, return_postinstall)
if self.is_enabled(node_id, "cnr"):
return self._cnr_switch_version(node_id, node_info, instant_execution, no_deps, return_postinstall)
if self.is_enabled(node_id, 'nightly'):
# disable nightly nodes
res = self.disable_for_replacement(node_id, os.path.join(get_default_custom_nodes_path(), node_id))
if not res.result:
return res
res = self._cnr_install(node_id, node_info, instant_execution, no_deps, return_postinstall)
if res.result:
self.active_nodes[node_id] = version_spec, res.to_path
return res
async def _get_git_install_url(self, node_id, version_spec, channel, mode):
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 not None:
@@ -1469,7 +1511,9 @@ class UnifiedManager:
if version_spec == 'nightly':
# disable cnr nodes
if self.is_enabled(node_id, 'cnr'):
self.unified_disable(node_id, False)
res = self.disable_for_replacement(node_id, to_path)
if not res.result:
return res
res = self.repo_install(repo_url, to_path, instant_execution=instant_execution, no_deps=no_deps, return_postinstall=return_postinstall)
if res.result:
@@ -1490,7 +1534,7 @@ class UnifiedManager:
if version_spec in ('unknown', 'nightly'):
if repo_url is None:
try:
repo_url = await self._get_git_install_url(node_id, version_spec, channel, mode)
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}')
except LookupError as exc:
@@ -1570,7 +1614,7 @@ def identify_node_pack_from_path(fullpath):
# cnr
cnr = cnr_utils.read_cnr_info(fullpath)
if cnr is not None:
return module_name, cnr['version'], cnr['id'], None
return module_name, cnr['version'], cnr['original_name'], None
return None
else:
@@ -1746,8 +1790,9 @@ def get_channel_dict():
for x in channels.split('\n'):
channel_info = x.split("::")
if len(channel_info) == 2:
channel_dict[channel_info[0]] = channel_info[1]
valid_channels.add(channel_info[1])
channel_url = normalize_channel_url(channel_info[1])
channel_dict[channel_info[0]] = channel_url
valid_channels.add(channel_url)
return channel_dict
@@ -1825,6 +1870,7 @@ def read_config():
return default_conf[key].lower() == 'true' if key in default_conf else False
manager_util.use_uv = default_conf['use_uv'].lower() == 'true' if 'use_uv' in default_conf else False
manager_util.apply_dependency_management_setting(default_conf.get('dependency_management'))
manager_util.bypass_ssl = get_bool('bypass_ssl', False)
return with_valid_values({
@@ -1832,7 +1878,7 @@ def read_config():
# read as written: a path of Windows may hold a `%`, which the parser takes as the start of a reference
'git_exe': default_conf.get('git_exe', '', raw=True),
'use_uv': get_bool('use_uv', True),
'channel_url': default_conf.get('channel_url', DEFAULT_CHANNEL),
'channel_url': normalize_channel_url(default_conf.get('channel_url', DEFAULT_CHANNEL)),
'default_cache_as_channel_url': get_bool('default_cache_as_channel_url', False),
'share_option': default_conf.get('share_option', 'all').lower(),
'bypass_ssl': get_bool('bypass_ssl', False),
@@ -2087,27 +2133,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(), context.comfy_path, context.manager_files_path)
with open(requirements_path, "r") as requirements_file:
for line in requirements_file:
#handle comments
if '#' in line:
if line.strip()[0] == '#':
print("Line is comment...skipping")
continue
else:
line = line.split('#')[0].strip()
package_name = remap_pip_package(line.strip())
if package_name and not package_name.startswith('#'):
if '--index-url' in package_name:
s = package_name.split('--index-url')
install_cmd = manager_util.make_pip_cmd(["install", s[0].strip(), '--index-url', s[1].strip()])
else:
install_cmd = manager_util.make_pip_cmd(["install", package_name])
if package_name.strip() != "" and not package_name.startswith('#'):
try_install_script(url, repo_path, install_cmd, 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):
@@ -2123,6 +2152,10 @@ def install_manager_requirements(repo_path):
Install packages from manager_requirements.txt if it exists.
This is specifically for ComfyUI's manager_requirements.txt.
"""
if os.environ.get("COMFYUI_MANAGER_SKIP_MANAGER_REQUIREMENTS", "").lower() in ("1", "true", "yes"):
logging.info("[ComfyUI-Manager] Skipping manager_requirements.txt install (COMFYUI_MANAGER_SKIP_MANAGER_REQUIREMENTS set)")
return
manager_requirements_path = os.path.join(repo_path, "manager_requirements.txt")
if not os.path.exists(manager_requirements_path):
return
@@ -2130,13 +2163,9 @@ def install_manager_requirements(repo_path):
logging.info("[ComfyUI-Manager] Installing manager_requirements.txt")
with open(manager_requirements_path, "r") as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
if '#' in line:
line = line.split('#')[0].strip()
if line:
install_cmd = manager_util.make_pip_cmd(["install", line])
subprocess.run(install_cmd)
install_args = manager_util.pip_install_args(line, {})
if install_args:
subprocess.run(manager_util.make_pip_cmd(["install", *install_args]))
def git_repo_update_check_with(path):
@@ -2347,23 +2376,26 @@ def git_pull(path):
async def get_data_by_mode(mode, filename, channel_url=None):
if channel_url in get_channel_dict():
channel_url = get_channel_dict()[channel_url]
try:
local_uri = os.path.join(manager_util.comfyui_manager_path, filename)
if mode == "local":
json_obj = await manager_util.get_data(local_uri)
else:
if channel_url is None:
uri = get_config()['channel_url'] + '/' + filename
else:
uri = channel_url + '/' + filename
channel_url = normalize_channel(channel_url) or get_config()['channel_url']
uri = channel_url + '/' + filename
cache_uri = str(manager_util.simple_hash(uri))+'_'+filename
cache_uri = os.path.join(manager_util.cache_dir, cache_uri)
if mode == "remote" and get_config()['network_mode'] != 'offline' and manager_util.is_manager_pip_package():
try:
json_obj = await manager_util.get_data(uri)
manager_util.write_cache_file(cache_uri, json_obj)
return json_obj
except Exception as e:
print(f"[ComfyUI-Manager] Due to a network error, switching to cache mode.\n=> {filename} @ {channel_url}/{mode}\n=> {e}")
if get_config()['network_mode'] == 'offline' or manager_util.is_manager_pip_package():
# offline network mode
if os.path.exists(cache_uri):
@@ -2487,70 +2519,6 @@ def gitclone_uninstall(files):
return True
def gitclone_set_active(files, is_disable):
import os
if is_disable:
action_name = "Disable"
else:
action_name = "Enable"
print(f"{action_name}: {files}")
for url in files:
if url.endswith("/"):
url = url[:-1]
try:
for custom_nodes_dir in get_custom_nodes_paths():
dir_name:str = os.path.splitext(os.path.basename(url))[0].replace(".git", "")
dir_path = os.path.join(custom_nodes_dir, dir_name)
# safety check
if dir_path == '/' or dir_path[1:] == ":/" or dir_path == '':
print(f"{action_name}(git-clone) error: invalid path '{dir_path}' for '{url}'")
return False
if is_disable:
current_path = dir_path
base_path = extract_base_custom_nodes_dir(current_path)
new_path = os.path.join(base_path, ".disabled", dir_name)
if not os.path.exists(current_path):
continue
else:
current_path1 = os.path.join(get_default_custom_nodes_path(), ".disabled", dir_name)
current_path2 = dir_path + ".disabled"
if os.path.exists(current_path1):
current_path = current_path1
elif os.path.exists(current_path2):
current_path = current_path2
else:
continue
base_path = extract_base_custom_nodes_dir(current_path)
new_path = os.path.join(base_path, dir_name)
shutil.move(current_path, new_path)
if is_disable:
if os.path.exists(os.path.join(new_path, "disable.py")):
disable_script = [sys.executable, "disable.py"]
try_install_script(url, new_path, disable_script)
else:
if os.path.exists(os.path.join(new_path, "enable.py")):
enable_script = [sys.executable, "enable.py"]
try_install_script(url, new_path, enable_script)
break # for safety
except Exception as e:
print(f"{action_name}(git-clone) error: {url} / {e}", file=sys.stderr)
return False
print(f"{action_name} was successful.")
return True
def gitclone_update(files, instant_execution=False, skip_script=False, msg_prefix="", no_deps=False):
import os
@@ -2720,11 +2688,11 @@ def lookup_installed_custom_nodes_legacy(repo_name):
def simple_check_custom_node(url):
dir_name = os.path.splitext(os.path.basename(url))[0].replace(".git", "")
dir_path = os.path.join(get_default_custom_nodes_path(), dir_name)
if os.path.exists(dir_path):
cnr = unified_manager.get_cnr_by_repo(url)
node_id = cnr['id'] if cnr else unknown_node_id(url)
if unified_manager.is_enabled(node_id):
return 'installed'
elif os.path.exists(dir_path+'.disabled'):
elif unified_manager.installed_folders_of(node_id):
return 'disabled'
return 'not-installed'
@@ -2824,6 +2792,9 @@ async def get_current_snapshot(custom_nodes_only = False):
else:
commit_hash = git_utils.get_commit_hash(fullpath)
url = git_utils.git_url(fullpath)
# of two clones of a repository, the enabled one is what a restore brings back
if is_disabled and url in git_custom_nodes:
continue
git_custom_nodes[url] = dict(hash=commit_hash, disabled=is_disabled)
except Exception:
print(f"Failed to extract snapshots for the custom node '{path}'.")
@@ -3119,8 +3090,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]):
@@ -3142,6 +3113,7 @@ 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
@@ -3311,10 +3283,14 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
norm_k = git_utils.normalize_url(k)
# a node pack saved at a version of the registry has the clone it keeps disabled as a git entry
# a clone saved as disabled is left out: the restore then disables it, leaves it disabled or does not clone it.
# A nodepack saved at a version of the registry has such a clone, which is restored when that version could not be
cnr = unified_manager.repo_cnr_map.get(norm_k)
version = (cnr_info or {}).get(cnr['id']) if cnr is not None else None
if version is not None and unified_manager.is_enabled(cnr['id'], 'cnr') and f"{cnr['id']}@{version}" not in failed:
if version is None:
if v.get('disabled'):
continue
elif unified_manager.is_enabled(cnr['id'], 'cnr') and f"{cnr['id']}@{version}" not in failed:
continue
git_info[norm_k] = v
+22 -31
View File
@@ -141,7 +141,7 @@ def _dedicated_install_allowed(flag_key: str) -> bool:
async def get_risky_level(files, pip_packages):
json_data1 = await core.get_data_by_mode('local', 'custom-node-list.json')
json_data2 = await core.get_data_by_mode('cache', 'custom-node-list.json', channel_url='https://raw.githubusercontent.com/Comfy-Org/ComfyUI-Manager/main')
json_data2 = await core.get_data_by_mode('cache', 'custom-node-list.json', channel_url=core.DEFAULT_CHANNEL)
all_urls = set()
for x in json_data1['custom_nodes'] + json_data2['custom_nodes']:
@@ -195,7 +195,6 @@ context.comfy_path = os.path.dirname(folder_paths.__file__)
core.js_path = os.path.join(context.comfy_path, "web", "extensions")
local_db_model = os.path.join(manager_util.comfyui_manager_path, "model-list.json")
local_db_alter = os.path.join(manager_util.comfyui_manager_path, "alter-list.json")
local_db_custom_node_list = os.path.join(manager_util.comfyui_manager_path, "custom-node-list.json")
local_db_extension_node_mappings = os.path.join(manager_util.comfyui_manager_path, "extension-node-map.json")
@@ -501,8 +500,12 @@ async def task_worker():
if replaces_cnr_with_nightly(cnr_id) and not is_allowed_security_level('middle+'):
logging.error(SECURITY_MESSAGE_MIDDLE_P)
return 'failed'
core.unified_manager.unified_enable(cnr_id)
return 'success'
res = core.unified_manager.unified_enable(cnr_id)
if res.result:
return 'success'
logging.error(f"[ComfyUI-Manager] Failed to enable '{cnr_id}': {res.msg}")
return f"Failed to enable: '{cnr_id}'"
async def do_update(item):
ui_id, node_name, node_ver = item
@@ -620,9 +623,10 @@ async def task_worker():
try:
res = core.unified_manager.unified_disable(node_name, is_unknown)
if res:
if res.result:
return 'success'
logging.error(f"[ComfyUI-Manager] Failed to disable '{node_name}': {res.msg}")
except Exception:
traceback.print_exc()
@@ -1157,7 +1161,7 @@ async def fetch_customnode_list(request):
if channel != 'local':
found = 'custom'
if channel == core.DEFAULT_CHANNEL or channel == core.DEFAULT_CHANNEL_LEGACY:
if channel == core.DEFAULT_CHANNEL:
channel = 'default'
else:
for name, url in core.get_channel_dict().items():
@@ -1172,21 +1176,6 @@ async def fetch_customnode_list(request):
return web.json_response(result, content_type='application/json')
@routes.get("/customnode/alternatives")
async def fetch_customnode_alternatives(request):
alter_json = await core.get_data_by_mode(request.rel_url.query["mode"], 'alter-list.json')
res = {}
for item in alter_json['items']:
populate_markdown(item)
res[item['id']] = item
res = core.map_to_unified_keys(res)
return web.json_response(res, content_type='application/json')
def check_model_installed(json_obj):
def is_exists(model_dir_name, filename, url):
if filename == '<huggingface>':
@@ -1235,8 +1224,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']:
@@ -1549,10 +1540,11 @@ async def _queue_node_install(json_data, operation):
node_spec_str = f"{cnr_id}@{selected_version}"
else:
node_spec_str = f"{cnr_id}@nightly"
git_url = [json_data.get('repository')]
if git_url is None:
logging.error(f"[ComfyUI-Manager] Following node pack doesn't provide `nightly` version: ${git_url}")
return web.Response(status=404, text=f"Following node pack doesn't provide `nightly` version: ${git_url}")
try:
git_url = [await core.unified_manager.get_git_install_url(cnr_id, 'nightly', json_data['channel'], json_data['mode'])]
except (LookupError, core.InvalidChannel):
logging.error(f"[ComfyUI-Manager] Following nodepack doesn't provide `nightly` version: {cnr_id}")
return web.Response(status=404, text=f"Following nodepack doesn't provide `nightly` version: {cnr_id}")
elif json_data['version'] != 'unknown' and selected_version == 'unknown':
logging.error(f"[ComfyUI-Manager] Invalid installation request: {json_data}")
@@ -1615,8 +1607,8 @@ def _queue_start():
async def _fix_custom_node(json_data):
if not is_allowed_security_level('middle'):
logging.error(SECURITY_MESSAGE_GENERAL)
if not is_allowed_security_level('high+'):
logging.error(SECURITY_MESSAGE_HIGH_P)
return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
node_id = json_data.get('id')
@@ -2078,10 +2070,9 @@ async def default_cache_update():
a = get_cache("custom-node-list.json")
b = get_cache("extension-node-map.json")
c = get_cache("model-list.json")
d = get_cache("alter-list.json")
e = get_cache("github-stats.json")
d = get_cache("github-stats.json")
await asyncio.gather(a, b, c, d, e)
await asyncio.gather(a, b, c, d)
if core.get_config()['network_mode'] == 'private':
logging.info("[ComfyUI-Manager] The private comfyregistry is not yet supported in `network_mode=private`.")
+56 -24
View File
@@ -35,6 +35,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):
@@ -95,11 +100,30 @@ def read_unified_resolver_mode():
if 'use_unified_resolver' in default_conf:
manager_util.use_unified_resolver = default_conf['use_unified_resolver'].lower() == 'true'
def read_dependency_management_mode():
# Config: [default] dependency_management = on|off (default on).
# Env override: COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT=on|off wins over config.
# `off` opts out of automatic Python-package mutation Manager performs at
# startup (PIPFixer auto-heal, unified resolver batch).
# Intended for distro-packaged / externally-managed Python environments
# where the interpreter is read-only (Nix, Guix, system packages, etc.).
manager_util.apply_dependency_management_setting(default_conf.get('dependency_management'))
if not manager_util.dependency_management_enabled:
logging.info("[ComfyUI-Manager] dependency management disabled; auto-install/upgrade/uninstall paths will be skipped.")
def check_file_logging():
global enable_file_logging
if 'file_logging' in default_conf and default_conf['file_logging'].lower() == 'false':
enable_file_logging = False
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
def set_git_executable():
# read as written: a path of Windows may hold a `%`, which the parser takes as the start of a reference
@@ -110,11 +134,14 @@ def set_git_executable():
read_config()
set_git_executable()
from .common import git_compat # noqa: E402,F401
from .common import git_compat # noqa: E402
print(git_compat.BACKEND_LINE, file=sys.stderr)
read_uv_mode()
read_unified_resolver_mode()
read_dependency_management_mode()
security_check.security_check()
check_file_logging()
check_strip_ansi_file_logging()
# Module-level flag set by startup batch resolver when it succeeds.
# Used by execute_lazy_install_script() to skip per-node pip installs.
@@ -135,15 +162,6 @@ if os.path.exists(manager_pip_blacklist_path):
cm_global.pip_blacklist.add(y)
def remap_pip_package(pkg):
if pkg in cm_global.pip_overrides:
res = cm_global.pip_overrides[pkg]
print(f"[ComfyUI-Manager] '{pkg}' is remapped to '{res}'")
return res
else:
return pkg
std_log_lock = threading.Lock()
@@ -270,6 +288,10 @@ try:
pat_tqdm = r'\d+%.*\[(.*?)\]'
pat_import_fail = r'seconds \(IMPORT FAILED\):(.*)$'
# CSI (ECMA-48) escape sequences: ESC [ <params: digits/;/> <?> <final letter>.
# Covers SGR color codes (m), cursor moves, clears, and the tqdm/progress-bar
# control codes that also land in the startup log.
pat_ansi = r'\x1b\[[0-9;?]*[a-zA-Z]'
is_start_mode = True
@@ -377,15 +399,25 @@ try:
except OSError:
self.console_is_gone = True
def _file_message(self, message):
# The disk log is the ONLY place file content and console content are
# allowed to diverge: here we drop ANSI so the file stays plain text.
# 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()
@@ -648,16 +680,9 @@ def execute_lazy_install_script(repo_path, executable):
lines = manager_util.robust_readlines(requirements_path)
for line in lines:
package_name = remap_pip_package(line.strip())
package_name = package_name.split('#')[0].strip()
if package_name and not is_installed(package_name):
if '--index-url' in package_name:
s = package_name.split('--index-url')
install_cmd = manager_util.make_pip_cmd(["install", s[0].strip(), '--index-url', s[1].strip()])
else:
install_cmd = manager_util.make_pip_cmd(["install", package_name])
process_wrap(install_cmd, repo_path)
install_args = manager_util.pip_install_args(line, cm_global.pip_overrides)
if install_args and not is_installed(install_args[0]):
process_wrap(manager_util.make_pip_cmd(["install", *install_args]), repo_path)
if os.path.exists(install_script_path) and f'{repo_path}/install.py' not in processed_install:
processed_install.add(f'{repo_path}/install.py')
@@ -688,7 +713,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)
@@ -816,7 +845,10 @@ def execute_startup_script():
# --- Unified dependency resolver: batch resolution at startup ---
# Runs unconditionally when enabled, independent of install-scripts.txt existence.
if manager_util.use_unified_resolver:
if manager_util.use_unified_resolver and not manager_util.dependency_management_enabled:
logging.info("[ComfyUI-Manager] dependency management disabled; skipping unified dependency resolver, installs use per-node pip")
manager_util.use_unified_resolver = False
elif manager_util.use_unified_resolver:
try:
from .common.unified_dep_resolver import (
UnifiedDepResolver,
+12 -23
View File
@@ -12,7 +12,7 @@ comfyui_manager/
│ ├── manager_util.py # Existing: get_pip_cmd(), PIPFixer, use_uv flag
│ ├── cm_global.py # Existing: pip_overrides, pip_blacklist (runtime dynamic assignment)
│ └── unified_dep_resolver.py # New: Unified dependency resolution module
├── prestartup_script.py # Existing: config reading, remap_pip_package, cm_global initialization
├── prestartup_script.py # Existing: config reading, cm_global initialization
└── legacy/
└── manager_core.py # Legacy (not a modification target)
cm_cli/
@@ -248,7 +248,7 @@ def collect_requirements(self) -> CollectedDeps:
skipped.append((line, f"rejected: path separator in package name"))
continue
# 2. Apply remap_pip_package (using cm_global.pip_overrides)
# 2. Apply cm_global.pip_overrides
pkg_spec = self._remap_package(line)
# 3. Blacklist check (cm_global.pip_blacklist)
@@ -318,8 +318,7 @@ def _is_downgrade_blacklisted(self, pkg_name: str, pkg_spec: str, installed: dic
return blocked
def _remap_package(self, pkg: str) -> str:
"""Package name remapping based on cm_global.pip_overrides.
Reuses existing remap_pip_package() logic."""
"""Package name remapping based on cm_global.pip_overrides."""
if pkg in self.overrides:
remapped = self.overrides[pkg]
logging.info(f"[UnifiedDepResolver] '{pkg}' remapped to '{remapped}'")
@@ -735,15 +734,11 @@ sequenceDiagram
> **Note**: Line numbers may shift as code changes, so references use symbol names (function/class names).
> Use `grep -n` or IDE symbol search for exact locations.
### remap_pip_package Location (Code Duplication Exists)
### pip_overrides Outside the Resolver
```
comfyui_manager/glob/manager_core.py — def remap_pip_package(pkg)
comfyui_manager/prestartup_script.py — def remap_pip_package(pkg)
```
Both reference `cm_global.pip_overrides` with identical logic.
The unified resolver uses `cm_global.pip_overrides` directly to avoid adding more duplication.
The paths that install one line at a time read each line with
`manager_util.pip_install_args(line, cm_global.pip_overrides)`, which applies the override.
The unified resolver applies `cm_global.pip_overrides` itself in `_remap_package()`.
### cm_global Global State
@@ -795,15 +790,9 @@ The unified resolver's `_is_downgrade_blacklisted()` method calls the same
`manager_util.parse_pip_spec()` and `manager_util.downgrade_protection()`, so the two
paths cannot diverge.
### Existing Code --index-url Handling (Asymmetric)
### Existing Code --index-url Handling
```python
# Only exists in standalone function execute_install_script():
if '--index-url' in package_name:
s = package_name.split('--index-url')
install_cmd = manager_util.make_pip_cmd(["install", s[0].strip(), '--index-url', s[1].strip()])
# UnifiedManager.execute_install_script() method does NOT have this handling
```
The unified resolver unifies both paths for consistent handling via `_split_index_url()`.
On every path that installs one line at a time, `manager_util.pip_install_args()` gives a
requirement followed by `--index-url URL` or `--extra-index-url URL` to the installer with that
requirement only, and leaves out a line that has only an option.
The unified resolver collects index URLs for the whole batch via `_split_index_url()`.
+1 -1
View File
@@ -104,7 +104,7 @@ ComfyUI-Loopchain
* Detailed Operations
* `install`: Installs the specified custom nodes.
* `reinstall`: Removes and then reinstalls the specified custom nodes.
* `reinstall`: Removes and then reinstalls the specified custom nodes. A nodepack named by its id without a version is reinstalled at the version that is installed.
* `uninstall`: Uninstalls the specified custom nodes.
* `update`: Updates the specified custom nodes.
* `disable`: Disables the specified custom nodes.
+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
```
+1 -1
View File
@@ -105,7 +105,7 @@ ComfyUI-Loopchain
* 세부 동작
* `install`: 지정된 커스텀 노드들을 설치합니다
* `reinstall`: 지정된 커스텀 노드를 삭제하고 재설치 합니다.
* `reinstall`: 지정된 커스텀 노드를 삭제하고 재설치 합니다. 버전 없이 이름만 지정하면 설치되어 있는 버전으로 재설치합니다.
* `uninstall`: 지정된 커스텀 노드들을 삭제합니다.
* `update`: 지정된 커스텀 노드들을 업데이트합니다.
* `disable`: 지정된 커스텀 노드들을 비활성화합니다.
-1
View File
@@ -19,7 +19,6 @@ Each subdirectory contains a standard set of JSON files:
- **custom-node-list.json**: Primary database of custom nodes with metadata
- **extension-node-map.json**: Maps between extensions and individual nodes they provide
- **model-list.json**: Catalog of models that can be downloaded through the manager
- **alter-list.json**: Alternative implementations of nodes for compatibility or functionality
- **github-stats.json**: GitHub repository statistics for node popularity metrics
## Database Schema
-1
View File
@@ -1 +0,0 @@
{}
-4
View File
@@ -1,4 +0,0 @@
{
"items": [
]
}
+1 -1
View File
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "comfyui-manager"
license = { text = "GPL-3.0-only" }
version = "4.4.3"
version = "4.5"
requires-python = ">=3.10"
description = "ComfyUI-Manager provides features to install and manage custom nodes for ComfyUI, as well as various functionalities to assist with ComfyUI."
readme = "README.md"
+22 -24
View File
@@ -397,12 +397,11 @@
## 22. tests/e2e/test_e2e_legacy_endpoints.py — Legacy-only endpoint positive-path suite (WI-TT + WI-UU deliverable)
**Reference**: WI-TT seeded this file with 6 GET positive-path tests closing pytest-N gaps (wi-031/032/033/034/035/036). WI-UU extends the file with a 7th test — the POST `/v2/manager/queue/batch` positive-path (wi-039) — closing the pytest-I gap for the high-fanout queue-batch endpoint. All seven routes are registered only in `legacy/manager_server.py` and reachable only under `--enable-manager-legacy-ui`, so they share the same legacy fixture (`start_comfyui_legacy.sh`, PORT 8199) mirroring the `test_e2e_csrf_legacy.py` pattern.
**Reference**: WI-TT seeded this file with 6 GET positive-path tests closing pytest-N gaps (wi-031/032/033/034/035/036). WI-UU extends the file with a 7th test — the POST `/v2/manager/queue/batch` positive-path (wi-039) — closing the pytest-I gap for the high-fanout queue-batch endpoint. All six routes are registered only in `legacy/manager_server.py` and reachable only under `--enable-manager-legacy-ui`, so they share the same legacy fixture (`start_comfyui_legacy.sh`, PORT 8199) mirroring the `test_e2e_csrf_legacy.py` pattern.
**Scope**: Positive-path assertions — status 200 + response-shape verification for each legacy-only endpoint. `disabled_versions` additionally accepts 400 as a valid branch because the handler returns 400 when the target node has no disabled versions (empty-result convention, not a validation error). `queue/batch` uses an empty-payload strategy to exercise the full handler path (parse → action-loop no-op → finalize-with-empty-guard → `_queue_start()` → JSON 200) with zero state mutation, plus a queue/status liveness check to verify the worker lock was released cleanly.
| Test | Design Goal | Verdict | Evidence |
|---|---|---|---|
| `TestLegacyCustomNodeAlternatives::test_returns_dict_of_alternatives` | Endpoint contract (alternatives — wi-031) | ✅ PASS | GET `/customnode/alternatives?mode=local` → 200 + dict body. Exercises unified-key mapping path (handler L1072-1084). |
| `TestLegacyCustomNodeDisabledVersions::test_endpoint_reachable_and_parses_param` | Endpoint contract (disabled_versions — wi-032) | ✅ PASS | GET `/v2/customnode/disabled_versions/ComfyUI_SigmoidOffsetScheduler` → status ∈ {200, 400}; 200 body asserted as list of `{version}` entries. Seed pack has no disabled versions → 400 is the live branch, 200 is guarded for when state is mutated. |
| `TestLegacyCustomNodeGetList::test_returns_channel_and_node_packs` | Endpoint contract (getlist — wi-033) | ✅ PASS | GET `/v2/customnode/getlist?mode=local&skip_update=true` → 200 + `{channel, node_packs}` dict with node_packs as dict. Exercises the unified `get_unified_total_nodes + populate_*` pipeline. |
| `TestLegacyCustomNodeVersions::test_returns_versions_list_for_seed_pack` | Endpoint contract (versions — wi-034) | ✅ PASS | GET `/v2/customnode/versions/ComfyUI_SigmoidOffsetScheduler` → 200 + non-empty list. Verifies CNR version lookup for the seed pack (handler L1262-1270). |
@@ -410,7 +409,7 @@
| `TestLegacyManagerNotice::test_returns_text_body` | Endpoint contract (notice — wi-036) | ✅ PASS | GET `/v2/manager/notice` → 200 + non-empty text body. Handler returns text/html (not JSON); both the markdown-fetch branch and the 'Unable to retrieve Notice' fallback return 200 with body. |
| `TestLegacyQueueBatch::test_accepts_empty_payload_returns_failed_list` | Endpoint contract (queue/batch — wi-039) | ✅ PASS | POST `/v2/manager/queue/batch` with `{}` → 200 + `{"failed": []}`. Safe-payload choice (empty body) exercises full handler path with zero state mutation; `finalize_temp_queue_batch` no-ops via its `if len(temp_queue_batch):` guard (handler L444), and `_queue_start()` releases the task-worker lock cleanly. Post-POST `/v2/manager/queue/status` returns 200 — lock-release liveness check. Closes the wi-039 pytest-I gap (was CSRF-only direct + indirect-via-callers). |
**File verdict**: 7/7 ✅ PASS.
**File verdict**: 6/6 ✅ PASS.
---
@@ -431,32 +430,32 @@
| test_e2e_csrf_legacy.py | 29 | 0 | 0 | 0 | 29 |
| test_e2e_secgate_strict.py | 1 | 0 | 0 | 0 | 1 |
| test_e2e_secgate_default.py | 1 | 0 | 0 | 0 | 1 |
| test_e2e_legacy_endpoints.py | 7 | 0 | 0 | 0 | 7 |
| test_e2e_legacy_endpoints.py | 6 | 0 | 0 | 0 | 6 |
| legacy-ui-manager-menu.spec.ts | 5 | 0 | 0 | 0 | 5 |
| legacy-ui-custom-nodes.spec.ts | 5 | 0 | 0 | 0 | 5 |
| legacy-ui-model-manager.spec.ts | 4 | 0 | 0 | 0 | 4 |
| legacy-ui-snapshot.spec.ts | 3 | 0 | 0 | 0 | 3 |
| legacy-ui-navigation.spec.ts | 2 | 0 | 0 | 0 | 2 |
| legacy-ui-install.spec.ts | 2 | 0 | 0 | 0 | 2 |
| **TOTAL** | **122** | **0** | **0** | **1** | **123** |
| **TOTAL** | **121** | **0** | **0** | **1** | **122** |
(Count adjusted to 109 after Wave1 WI-L/M/N: 10 WEAK→PASS upgrades across 5 files (endpoint, git_clone, customnode_info, queue_lifecycle, version_mgmt) + 1 WEAK-row retired via WI-M dedup (test_get_current_returns_dict folded into strengthened test_get_current_snapshot — the folded row is treated as a deletion rather than a separate upgrade). Stage2 WI-F earlier established the 110 baseline from 112 by retiring 4 INADEQUATE legacy-ui tests with net +2 PASS. Wave2 WI-P/Q added 7 more WEAK→PASS upgrades (WI-P: task_operations 6 upgrades for update/fix effect + params; WI-Q: snapshot_lifecycle 1 upgrade for save_snapshot disk + content verification). Wave3 WI-T/U/W completed the reconciliation with 10 further WEAK→PASS upgrades: WI-T Cluster C+G strengthened queue_lifecycle (3), customnode_info (1), system_info (1) for field-level effect checks; WI-U Cluster H rewrote 3 Playwright legacy-ui specs (manager-menu 2, custom-nodes 1, model-manager 2) to verify UI state via dialog reopen / `<select>.value` assertions instead of direct API; WI-W fixed the TaskHistoryItem schema-drop regression enabling queue_lifecycle un-skip. Cumulative **upgrade** count across the three waves = 10 + 7 + 10 = **27** (unchanged). WI-Z reconciled the audit with the actual test-file surface (no upgrades, only inventory): Y1 recorded the pre-existing `test_remove_path_traversal_rejected` in snapshot_lifecycle (§7, 6→7), and Y3 recorded 5 pre-existing config_api rows (junk_value rejections ×3 + persists_to_config_ini ×2 from WI-E/WI-I, §4, 10→15). WI-AA recorded the pre-existing `legacy-ui-install.spec.ts` (LB1 + LB2) as new §16 — these UI-driven install/uninstall tests (from WI-U Cluster) close the LB1/LB2 gap formerly flagged in `coverage_gaps.md`. WI-GG added new §19 for `test_e2e_csrf_legacy.py` (from WI-FF): 4 new test functions / 26 parametrized invocations closing the legacy-side CSRF regression-guard gap — counted per-invocation (+26 PASS rows) for parity with the CSRF endpoint-fixture accounting in `endpoint_scenarios.md`; this is an accounting-granularity choice, not a contract addition (CSRF-M1/M2/M3 Goals were already referenced in §18). Total test count progression: **109 → 115 (WI-Z) → 117 (WI-AA) → 143 (WI-GG) → 146 (WI-JJ) → 148 (WI-LL)**; all 39 added rows were **pre-existing** tests or newly-added tests from their source WIs, not new engineering work performed by the audit reconciliation itself.)
> **Note**: The matrix above counts *tests* (148), not *design Goals* (92).
> See `reports/verification_design.md` for the 92 Goals and the RV-B trace
> **Note**: The matrix above counts *tests* (147), not *design Goals* (91).
> See `reports/verification_design.md` for the 91 Goals and the RV-B trace
> (adhoc-rv-b-trace session evidence) for the Goal↔test cross-reference.
> **Design-Goal coverage: 70/92 Goals referenced (76.1%), 22 Goals absent from this audit** — see § Design-Goal Coverage Gap below. With the 3 CSRF-mitigation Goals (CSRF-M1/M2/M3) from `verification_design.md` Section 10 added as supplementary coverage, the superset tally is **73/95** (76.8%). (WI-Z Y1 strengthens SR3 coverage from Key-gap note to an actual ✅ PASS row (`test_remove_path_traversal_rejected`); WI-AA adds ✅ PASS rows for LB1/LB2 via `legacy-ui-install.spec.ts`. WI-GG adds a second test-reference for CSRF-M1/M2/M3 via `test_e2e_csrf_legacy.py` but does NOT introduce new Goals — each CSRF-M Goal is now backed by paired glob + legacy coverage. WI-LL adds two previously T2 SECGATE-PENDING Goals (SR4 via `test_e2e_secgate_strict.py` §20, CV4 via `test_e2e_secgate_default.py` §21) as formal ✅ PASS rows — reclassifying them from "T2-pending" Key-gap notes to test-backed coverage. The 68→70 base tally uplift reflects this formal-status upgrade: SR4 and CV4 transition from Key-gap reference to explicit test-row-backed Goals.)
> **Design-Goal coverage: 69/91 Goals referenced (75.8%), 22 Goals absent from this audit** — see § Design-Goal Coverage Gap below. With the 3 CSRF-mitigation Goals (CSRF-M1/M2/M3) from `verification_design.md` Section 10 added as supplementary coverage, the superset tally is **72/94** (76.6%). (WI-Z Y1 strengthens SR3 coverage from Key-gap note to an actual ✅ PASS row (`test_remove_path_traversal_rejected`); WI-AA adds ✅ PASS rows for LB1/LB2 via `legacy-ui-install.spec.ts`. WI-GG adds a second test-reference for CSRF-M1/M2/M3 via `test_e2e_csrf_legacy.py` but does NOT introduce new Goals — each CSRF-M Goal is now backed by paired glob + legacy coverage. WI-LL adds two previously T2 SECGATE-PENDING Goals (SR4 via `test_e2e_secgate_strict.py` §20, CV4 via `test_e2e_secgate_default.py` §21) as formal ✅ PASS rows — reclassifying them from "T2-pending" Key-gap notes to test-backed coverage. The 68→70 base tally uplift reflects this formal-status upgrade: SR4 and CV4 transition from Key-gap reference to explicit test-row-backed Goals.)
Percentages (excluding N/A, denominator = 122+0+0 = 122):
- ✅ PASS: 122 / 122 = 100%
- ⚠️ WEAK: 0 / 122 = 0%
- ❌ INADEQUATE: 0 / 122 = 0%
Percentages (excluding N/A, denominator = 121+0+0 = 121):
- ✅ PASS: 121 / 121 = 100%
- ⚠️ WEAK: 0 / 121 = 0%
- ❌ INADEQUATE: 0 / 121 = 0%
---
# Design-Goal Coverage Gap
24 of 92 design Goals (`reports/verification_design.md`) have no corresponding row in
24 of 91 design Goals (`reports/verification_design.md`) have no corresponding row in
the test audit above. Full list:
| Section | Goal | Intent | Recommended |
@@ -482,11 +481,11 @@ the test audit above. Full list:
| 6.1 | LB4 | UI update-all | NORMAL add |
| 6.1 | LB5 | Batch partial failure | NORMAL add |
| 6.2 | LG2 | List without fetch | NORMAL add |
| 6.4 | LM2 | Install flag seed | NORMAL add |
| 6.5 | LV1 | Version dropdown | NORMAL add |
| 6.5 | LV2 | Unknown pack 400 | NORMAL add |
| 6.3 | LM2 | Install flag seed | NORMAL add |
| 6.4 | LV1 | Version dropdown | NORMAL add |
| 6.4 | LV2 | Unknown pack 400 | NORMAL add |
Final Goal-class tally (92 design Goals): KEEP 22 (SR4 + CV4 promoted post-WI-LL) / NORMAL strengthen 25 / NORMAL add 39 (22 UNREF + 14 GAP + 3 T1 DESTRUCTIVE-SAFE) / T2 PENDING-SECGATE **reduced 8 → 4 and reclassified** (see WI-KK SECGATE Harness Design block below) / T3 IRREDUCIBLE-NA 0. With the supplementary CSRF-M1/M2/M3 Goals covered by `verification_design.md` Section 10, superset tally is 95 Goals: KEEP 25 / rest unchanged.
Final Goal-class tally (91 design Goals): KEEP 22 (SR4 + CV4 promoted post-WI-LL) / NORMAL strengthen 25 / NORMAL add 39 (22 UNREF + 14 GAP + 3 T1 DESTRUCTIVE-SAFE) / T2 PENDING-SECGATE **reduced 8 → 4 and reclassified** (see WI-KK SECGATE Harness Design block below) / T3 IRREDUCIBLE-NA 0. With the supplementary CSRF-M1/M2/M3 Goals covered by `verification_design.md` Section 10, superset tally is 94 Goals: KEEP 25 / rest unchanged.
---
@@ -539,7 +538,6 @@ Final Goal-class tally (92 design Goals): KEEP 22 (SR4 + CV4 promoted post-WI-LL
- LN1-LN4 manager/notice tests (4 variants)
- LPP1/LPP2 pip install tests
- LGU1/LGU2 git_url install tests
- LA1 alternatives display test
- LDV1 disabled_versions test
## Classification policy (tier rule)
@@ -599,9 +597,9 @@ should land as one cross-cutting item" collapses into a 4-sub-tier structure:
| T2-TASKLEVEL | IM4 | Queue-observation pattern (not HTTP 403) — pattern TBD | Open design question; not a simple mechanical add |
Propagation plan (post-PR):
1. Land SR6, V5, UA2 in `test_e2e_secgate_strict.py` using the SR4 template; adds 3 PASS rows, brings this audit to 136/151 TOTAL.
2. Create `test_e2e_secgate_legacy_default.py` for LGU2 + LPP2; +2 PASS → 138/153.
3. Design the IM4 queue-observation pattern (distinct from the HTTP 403 pattern used in §20/§21); +1 PASS → 139/154. This item may be reclassified to T3 IRREDUCIBLE-NA if the observable turns out to be log-only.
1. Land SR6, V5, UA2 in `test_e2e_secgate_strict.py` using the SR4 template; adds 3 PASS rows, brings this audit to 135/150 TOTAL.
2. Create `test_e2e_secgate_legacy_default.py` for LGU2 + LPP2; +2 PASS → 137/152.
3. Design the IM4 queue-observation pattern (distinct from the HTTP 403 pattern used in §20/§21); +1 PASS → 138/153. This item may be reclassified to T3 IRREDUCIBLE-NA if the observable turns out to be log-only.
---
@@ -617,11 +615,11 @@ Cumulative Wave1+Wave2+Wave3 upgrade count: **27 WEAK → PASS** (10 + 7 + 10).
- Check status code without verifying the actual effect (WEAK — 0%) ✅
- Use direct API in UI tests (INADEQUATE — 0%) ✅
- Are outside endpoint-effect scope (N/A — 15/148 ≈ 10.1% of total)
- Are outside endpoint-effect scope (N/A — 15/147 ≈ 10.2% of total)
Remaining 🟢 gaps (not WEAK): ~~**SR3 snapshot-remove path-traversal**~~ (RESOLVED by WI-Z Y1 — `test_remove_path_traversal_rejected`) and **QH2 queue-history path-traversal** (destructive-safe security test, already present via `test_history_path_traversal_rejected` in queue_lifecycle § Key gaps). Design-Goal coverage gap (22/92 absent, 70/92 referenced) is tracked separately in § Design-Goal Coverage Gap and is not a test-quality issue.
Remaining 🟢 gaps (not WEAK): ~~**SR3 snapshot-remove path-traversal**~~ (RESOLVED by WI-Z Y1 — `test_remove_path_traversal_rejected`) and **QH2 queue-history path-traversal** (destructive-safe security test, already present via `test_history_path_traversal_rejected` in queue_lifecycle § Key gaps). Design-Goal coverage gap (22/91 absent, 69/91 referenced) is tracked separately in § Design-Goal Coverage Gap and is not a test-quality issue.
Post-Wave3 + WI-Z + WI-AA + WI-GG + WI-JJ + WI-LL state: **100% adequate coverage achieved** (133/133 PASS, excluding 15 N/A). Audit is in a terminal state for the current 148 tests. Further coverage expansion (design-Goal additions, the 3 T2-pending harness-ready Goals, NORMAL-legacy Goals, T2-TASKLEVEL IM4) is new-work territory — propagation plan is documented in the WI-KK SECGATE Harness Design block above — not reconciliation.
Post-Wave3 + WI-Z + WI-AA + WI-GG + WI-JJ + WI-LL state: **100% adequate coverage achieved** (132/132 PASS, excluding 15 N/A). Audit is in a terminal state for the current 147 tests. Further coverage expansion (design-Goal additions, the 3 T2-pending harness-ready Goals, NORMAL-legacy Goals, T2-TASKLEVEL IM4) is new-work territory — propagation plan is documented in the WI-KK SECGATE Harness Design block above — not reconciliation.
> **WI-Z + WI-AA + WI-GG + WI-JJ + WI-LL note**: Total test count 109 → 115 (WI-Z Y1 +1 snapshot, Y3 +5 config_api) → 117 (WI-AA +2 LB1/LB2) → 143 (WI-GG +26 legacy CSRF per-invocation rows) → 146 (WI-JJ +3 legacy-side install/parity rows) → 148 (WI-LL +2 SECGATE PoC rows) reflects inventory reconciliation plus WI-KK's newly-landed secgate coverage. Cumulative **upgrade** count remains 27 (unchanged since Wave3). WI-LL is the first audit-reflect WI to also introduce a Classification-policy reshape (T2 SECGATE-PENDING 8 → 4 sub-tiers), not just row additions.
+2 -8
View File
@@ -10,9 +10,9 @@
| Category | Endpoints | Unique Scenarios |
|---|---:|---:|
| Glob v2 | 30 | 120 |
| Legacy-only (not in glob) | 9 | 34 |
| Legacy-only (not in glob) | 8 | 33 |
| Legacy-shared (same path as glob) | 29 | — (see glob) |
| **TOTAL unique HTTP handlers** | **39** | **154** |
| **TOTAL unique HTTP handlers** | **38** | **153** |
Security-gated endpoints:
- `middle`: reboot, snapshot/remove, _uninstall_custom_node, _update_custom_node
@@ -309,12 +309,6 @@ Endpoints in this section exist **only in the legacy server** (not registered in
3. Removes comfyui-manager self-entry from results
4. Channel lookup resolves to 'default'/'custom'/known name
### GET /customnode/alternatives
- **Handler**: `fetch_customnode_alternatives` (L1072)
- **Query**: `mode` (required)
- **Scenarios**:
1. Success — alter-list.json items keyed by id → 200
### GET /v2/externalmodel/getlist
- **Handler**: `fetch_externalmodel_list` (L1143)
- **Query**: `mode` (required)
-9
View File
@@ -388,14 +388,6 @@ Purpose: **feed the Custom Nodes Manager dialog with the list of available + ins
| With or without skip_update | No git fetch performed (check timing / no remote calls) |
| Channel resolution | Maps URL back to name (default/custom/etc.) |
### GET /customnode/alternatives (legacy)
Purpose: **show alternative pack recommendations for a given pack**.
| Scenario | Effect to verify |
|---|---|
| Success | Response dict keyed by unified pack id; values from `alter-list.json` with markdown processed |
### GET /v2/externalmodel/getlist (legacy)
Purpose: **list available external models with install state for Model Manager dialog**.
@@ -473,7 +465,6 @@ For Playwright tests, the "UI→effect" contract requires:
| Click "Disable" on row | POST queue/batch (disable) | Pack in `.disabled/` + row state "Disabled" |
| Click "Update" on outdated row | POST queue/batch (update) | Pack version changes + row state update |
| Click "Fix" on row | POST queue/batch (fix) | Dependencies restored |
| Click "Try alternatives" | GET /customnode/alternatives | Alternatives list rendered |
| Open "Versions" dropdown on row | GET customnode/versions/{id} | Version list rendered in UI |
| Open "Disabled Versions" on row | GET customnode/disabled_versions/{id} | Disabled versions rendered |
| Click "Install via Git URL" button + enter URL + confirm | POST customnode/install/git_url | Pack cloned; dir visible in UI |
+3 -9
View File
@@ -316,12 +316,6 @@ Same as db_mode: observability of current policy + user choice to change update
| With or without skip_update | Performance: the list loads without a remote fetch; a check for updates runs in the background |
| Channel resolution | Observability: user sees which channel data came from |
### GET /customnode/alternatives
| Scenario | Intent |
|---|---|
| Success | User capability: recommend alternative packs when one is discontinued/unavailable |
### GET /v2/externalmodel/getlist
| Scenario | Intent |
@@ -385,7 +379,7 @@ Some scenarios recur across many endpoints with consistent intent:
| Security level denial (middle/middle+/high+) | destructive endpoints | Security boundary — tier privileged ops per deployment risk profile |
| Idempotent re-call on empty state | queue/reset, history_list, snapshot/getlist, installed | Idempotency — safe to poll or retry |
| Repeated read returns same value | version, db_mode, policy/update | Data integrity — config/runtime state is stable |
| Empty collection returned cleanly | history, getlist, installed, alternatives | Input resilience — empty is valid, not an error |
| Empty collection returned cleanly | history, getlist, installed | Input resilience — empty is valid, not an error |
---
@@ -393,7 +387,7 @@ Some scenarios recur across many endpoints with consistent intent:
| Intent category | # scenarios | Notes |
|---|---:|---|
| User capability (positive user need) | 62 | The "happy paths" |
| User capability (positive user need) | 61 | The "happy paths" |
| Input resilience | 32 | Mostly 400s for bad input |
| Security boundary | 15 | Security levels + path traversal |
| Idempotency | 14 | No-op / retry safety |
@@ -402,7 +396,7 @@ Some scenarios recur across many endpoints with consistent intent:
| Recovery | 5 | Fix, restore, reset |
| Concurrency safety | 2 | Worker dedup |
Total unique scenarios mapped: ~154 (matches Report A).
Total unique scenarios mapped: ~153 (matches Report A).
---
+7 -14
View File
@@ -518,14 +518,7 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
- **Observable**: loading time; network log
- **Assertion**: no git fetch calls; load time < N seconds
## 6.3 GET /customnode/alternatives
### Goal LA1 — Show alternatives on dedicated UI flow
- **Action (UI)**: trigger alternatives display (specific button or context)
- **Observable**: alternatives panel/dialog
- **Assertion**: populated with alter-list.json entries (at least one if data exists)
## 6.4 GET /v2/externalmodel/getlist
## 6.3 GET /v2/externalmodel/getlist
### Goal LM1 — Populate Model Manager dialog
- **Action (UI)**: open Model Manager
@@ -537,7 +530,7 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
- **Action (UI)**: open Model Manager
- **Assertion**: that model row shows "Installed"
## 6.5 GET /v2/customnode/versions/{node_name}
## 6.4 GET /v2/customnode/versions/{node_name}
### Goal LV1 — Version dropdown on Install click
- **Action (UI)**: click Install on a CNR pack row
@@ -548,7 +541,7 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
- **Action**: direct API call with bogus node_name
- **Assertion**: 400; UI shows error or skips
## 6.6 GET /v2/customnode/disabled_versions/{node_name}
## 6.5 GET /v2/customnode/disabled_versions/{node_name}
### Goal LDV1 — Show disabled versions for re-enable
- **Precondition**: pack has disabled versions
@@ -556,7 +549,7 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
- **Observable**: dropdown options
- **Assertion**: options match backend disabled_versions response
## 6.7 POST /v2/customnode/install/git_url
## 6.6 POST /v2/customnode/install/git_url
### Goal LGU1 — Install via "Install via Git URL" button
- **Precondition**: security_level ≥ high+; pack absent
@@ -568,7 +561,7 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
- **Precondition**: security_level < high+
- **Assertion**: 403 from API; UI shows error; no clone occurs
## 6.8 POST /v2/customnode/install/pip
## 6.7 POST /v2/customnode/install/pip
### Goal LPP1 — Install pip packages via UI
- **Action (UI)**: trigger pip install flow with known package
@@ -578,7 +571,7 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
### Goal LPP2 — Security gate
- **Assertion**: 403 at lower security; no pip invocation
## 6.9 GET /v2/manager/notice
## 6.8 GET /v2/manager/notice
### Goal LN1 — Fetch and display News
- **Precondition**: GitHub reachable
@@ -752,7 +745,7 @@ Reusable verification templates organized by intent category. Apply the template
| Intent category | Template | Scenarios using | Test type needed |
|---|---|---:|---|
| User capability | 7.1 | 62 | E2E effect verification (real install/remove/save etc.) |
| User capability | 7.1 | 61 | E2E effect verification (real install/remove/save etc.) |
| Input resilience | 7.2 | 32 | Negative tests with negative-check assertions |
| Security boundary | 7.3 | 15 | Permission tests at each security level |
| Observability | 7.4 | 16 | GET correctness + traceability tests |
@@ -0,0 +1,220 @@
"""
Tests for the `dependency_management` opt-out switch without a ComfyUI runtime.
Load the actual utility module and startup functions with isolated collaborators;
never execute startup's host-side registration, network, or interpreter mutations.
"""
import ast
import importlib.util
import logging
import os
from pathlib import Path
import sys
import tempfile
import types
import unittest
from unittest import mock
_PACKAGE = Path(__file__).resolve().parents[2] / "comfyui_manager"
def _import_manager_util():
# Other tests replace the public module with a resolver stub. Import a fresh
# private instance rather than depending on collection order or booting the
# package's __init__, which imports the full ComfyUI application.
spec = importlib.util.spec_from_file_location(
"dependency_management_test_util", _PACKAGE / "common" / "manager_util.py"
)
module = importlib.util.module_from_spec(spec)
# HTTP is unrelated to dependency policy and is never called by these tests.
with mock.patch.dict(sys.modules, {"aiohttp": types.ModuleType("aiohttp")}):
spec.loader.exec_module(module)
return module
def _startup_namespace(manager_util):
return {
"manager_util": manager_util,
"os": os,
"logging": logging,
"default_conf": {},
"processed_install": set(),
"_unified_resolver_succeeded": False,
"comfy_path": "/externally-managed-comfy",
"process_wrap": mock.Mock(return_value=0),
"is_installed": mock.Mock(return_value=False),
"cm_global": types.SimpleNamespace(pip_overrides={}),
}
def _load_startup_nodes(namespace, predicate):
path = _PACKAGE / "prestartup_script.py"
parsed = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
nodes = [node for node in parsed.body if predicate(node)]
if not nodes:
raise AssertionError("Startup policy code was not found")
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(path), "exec"), namespace)
class DependencyManagementFlagTest(unittest.TestCase):
def setUp(self):
self.manager_util = _import_manager_util()
self._prev = self.manager_util.dependency_management_enabled
self.addCleanup(setattr, self.manager_util, "dependency_management_enabled", self._prev)
def test_default_is_enabled(self):
# Default must preserve today's behavior.
self.assertTrue(self._prev)
def test_environment_is_applied_when_the_module_loads(self):
# A cm-cli process loads manager_util without running prestartup_script.
for environment, expected in [({"COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT": "off"}, False), ({}, True)]:
with self.subTest(environment=environment):
with mock.patch.dict(os.environ, environment, clear=True):
self.assertEqual(_import_manager_util().dependency_management_enabled, expected)
def test_pip_fixer_short_circuits_when_disabled(self):
self.manager_util.dependency_management_enabled = False
class _Stub(self.manager_util.PIPFixer):
def __init__(self): # bypass parent init
pass
with mock.patch.object(self.manager_util, "get_installed_packages") as patched:
_Stub().fix_broken()
patched.assert_not_called()
def test_pip_fixer_runs_when_enabled(self):
# The enabled path must read the current installed package inventory.
self.manager_util.dependency_management_enabled = True
class _Stub(self.manager_util.PIPFixer):
def __init__(self):
self.prev_pip_versions = {}
self.comfyui_path = "/nonexistent"
self.manager_files_path = "/nonexistent"
class InventoryRead(Exception):
pass
with mock.patch.object(self.manager_util, "get_installed_packages", side_effect=InventoryRead) as patched:
with self.assertRaises(InventoryRead):
_Stub().fix_broken()
patched.assert_called_once_with(True)
def test_make_pip_cmd_not_gated(self):
# make_pip_cmd is consulted for both read and write ops (pip list,
# pip install, …). Gating it would break read paths the UI relies on.
# Assert the helper still produces a runnable command when the flag
# is off — gating happens at call sites that perform writes.
self.manager_util.dependency_management_enabled = False
with mock.patch.object(self.manager_util, "get_pip_cmd", return_value=[sys.executable, "-m", "pip"]):
cmd = self.manager_util.make_pip_cmd(["list"])
install_cmd = self.manager_util.make_pip_cmd(["install", "some-pkg"])
self.assertIsInstance(cmd, list)
self.assertGreaterEqual(len(cmd), 3)
self.assertIn("list", cmd)
self.assertIn("install", install_cmd)
self.assertIn("some-pkg", install_cmd)
class StartupDependencyPolicyTest(unittest.TestCase):
def setUp(self):
self.manager_util = _import_manager_util()
self.namespace = _startup_namespace(self.manager_util)
_load_startup_nodes(
self.namespace,
lambda node: isinstance(node, ast.FunctionDef)
and node.name in {"read_dependency_management_mode", "execute_lazy_install_script"},
)
def test_config_off(self):
self.namespace["default_conf"]["dependency_management"] = "off"
with mock.patch.dict(os.environ, {}, clear=True):
self.namespace["read_dependency_management_mode"]()
self.assertFalse(self.manager_util.dependency_management_enabled)
def test_environment_wins_in_both_directions(self):
for config, environment, expected in [("off", "on", True), ("on", "off", False)]:
with self.subTest(config=config, environment=environment):
self.namespace["default_conf"]["dependency_management"] = config
with mock.patch.dict(os.environ, {"COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT": environment}, clear=True):
self.namespace["read_dependency_management_mode"]()
self.assertEqual(self.manager_util.dependency_management_enabled, expected)
def test_lazy_requirements_of_a_scheduled_install_still_install_when_disabled(self):
# An install or update the user scheduled for the restart is explicit: its requirements are installed.
self.manager_util.dependency_management_enabled = False
with tempfile.TemporaryDirectory() as directory:
Path(directory, "requirements.txt").write_text("example-package==1.0\n")
with (
mock.patch.object(self.manager_util, "robust_readlines", return_value=["example-package==1.0\n"]),
mock.patch.object(self.manager_util, "make_pip_cmd", return_value=["pip", "install", "example-package==1.0"]),
):
self.namespace["execute_lazy_install_script"](directory, sys.executable)
self.namespace["process_wrap"].assert_called_once_with(
["pip", "install", "example-package==1.0"], directory
)
def test_lazy_requirements_are_installed_when_enabled(self):
with tempfile.TemporaryDirectory() as directory:
Path(directory, "requirements.txt").write_text("example-package==1.0\n")
with (
mock.patch.object(self.manager_util, "robust_readlines", return_value=["example-package==1.0\n"]),
mock.patch.object(self.manager_util, "make_pip_cmd", return_value=["pip", "install", "example-package==1.0"]),
):
self.namespace["execute_lazy_install_script"](directory, sys.executable)
self.namespace["process_wrap"].assert_called_once_with(
["pip", "install", "example-package==1.0"], directory
)
def test_explicit_node_install_script_is_not_gated(self):
self.manager_util.dependency_management_enabled = False
with tempfile.TemporaryDirectory() as directory:
Path(directory, "install.py").write_text("# Explicitly scheduled node installation\n")
self.namespace["execute_lazy_install_script"](directory, sys.executable)
call = self.namespace["process_wrap"].call_args
self.assertEqual(call.args, ([sys.executable, "install.py"], directory))
self.assertEqual(call.kwargs["env"]["COMFYUI_FOLDERS_BASE_PATH"], self.namespace["comfy_path"])
def test_disabled_startup_turns_the_resolver_off_so_installs_use_pip(self):
# The resolver batch does not run, so an install must not defer its requirements to it.
self.manager_util.dependency_management_enabled = False
self.manager_util.use_unified_resolver = True
_load_startup_nodes(
self.namespace,
lambda node: isinstance(node, ast.If)
and any(isinstance(part, ast.Attribute) and part.attr == "use_unified_resolver" for part in ast.walk(node.test)),
)
self.assertFalse(self.manager_util.use_unified_resolver)
self.assertFalse(self.namespace["_unified_resolver_succeeded"])
class IsOffValueTest(unittest.TestCase):
"""`is_off_value` is the single source of truth for the config/env vocabulary."""
def setUp(self):
self.manager_util = _import_manager_util()
def test_off_synonyms(self):
for value in ("off", "OFF", " false ", "0", "no", "Disabled"):
with self.subTest(value=value):
self.assertTrue(self.manager_util.is_off_value(value))
def test_on_values(self):
# Anything not in the off vocabulary — including the empty string and
# typos — keeps dependency management enabled. Better to be noisy than
# to silently swallow installs.
for value in ("on", "true", "1", "yes", "enabled", "auto", "", " ", "off-ish"):
with self.subTest(value=value):
self.assertFalse(self.manager_util.is_off_value(value))
if __name__ == "__main__":
unittest.main()
+23
View File
@@ -348,3 +348,26 @@ class TestNightlyInstallCycle:
f"Installed entry {pkg_key!r} still references {PACK_TEST1!r} "
f"via cnr_id/aux_id: {pkg!r}"
)
class TestGitBackendLine:
def test_server_log_has_the_line(self, comfyui):
with open(os.path.join(E2E_ROOT, "logs", "comfyui.log")) as f:
log = f.read()
assert "Using GitPython backend" in log or "Using pygit2 backend" in log
def test_cm_cli_does_not_write_the_line(self, comfyui):
r = subprocess.run([_cm_cli_path(), "--help"], capture_output=True, text=True, timeout=120,
env={**os.environ, "COMFYUI_PATH": COMFYUI_PATH})
assert r.returncode == 0, r.stderr
assert "Using GitPython backend" not in r.stdout + r.stderr
assert "Using pygit2 backend" not in r.stdout + r.stderr
def test_cm_cli_writes_no_empty_line_before_the_output_of_its_command(self, comfyui):
r = subprocess.run([_cm_cli_path(), "simple-show", "snapshot-list"], capture_output=True, text=True, timeout=120,
env={**os.environ, "COMFYUI_PATH": COMFYUI_PATH})
assert r.returncode == 0, r.stderr
assert not r.stdout.startswith("\n")
+1 -21
View File
@@ -1,12 +1,11 @@
"""E2E positive-path tests for legacy-only GET endpoints.
SCOPE — closes the 6 pytest-N gaps from reports/api-coverage-matrix.md
SCOPE — closes the pytest-N gaps from reports/api-coverage-matrix.md
(WI-TT). Each target endpoint is registered ONLY in
`comfyui_manager/legacy/manager_server.py` and thus reachable only when
ComfyUI runs with `--enable-manager-legacy-ui`.
Endpoints covered:
- GET /customnode/alternatives (legacy L1072)
- GET /v2/customnode/disabled_versions/{node_name} (legacy L1273)
- GET /v2/customnode/getlist (legacy L1018)
- GET /v2/customnode/versions/{node_name} (legacy L1262)
@@ -96,25 +95,6 @@ def comfyui_legacy():
_stop_comfyui()
class TestLegacyCustomNodeAlternatives:
"""GET /customnode/alternatives?mode=local (wi-031)."""
def test_returns_dict_of_alternatives(self, comfyui_legacy):
resp = requests.get(
f"{BASE_URL}/customnode/alternatives",
params={"mode": "local"},
timeout=30,
)
assert resp.status_code == 200, (
f"Expected 200, got {resp.status_code}: {resp.text[:200]}"
)
data = resp.json()
assert isinstance(data, dict), (
f"alternatives response should be a dict keyed by unified id, "
f"got {type(data).__name__}"
)
class TestLegacyCustomNodeDisabledVersions:
"""GET /v2/customnode/disabled_versions/{node_name} (wi-032).
+1
View File
@@ -326,6 +326,7 @@ class TestUpdateComfyuiQueued:
f"update_comfyui should return 200 at default security_level, "
f"got {resp.status_code}: {resp.text[:200]}"
)
requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10).raise_for_status()
class TestInstallModelRealDownload:
+2 -3
View File
@@ -626,7 +626,7 @@ class TestUnknownPipStaysBlocked:
# ===========================================================================
def _batch_op_item(ui_id: str) -> dict:
"""Item for middle-gated batch ops (fix/uninstall/update). The GATE
"""Item for middle-gated batch ops (uninstall/update). The GATE
check precedes node resolution, so a placeholder spec is sufficient:
the queue worker's later failure on the nonexistent node is irrelevant
to the synchronous gate observable (the response's failed list)."""
@@ -646,10 +646,9 @@ class _LegacyGuardRows:
flags_label = ""
def _assert_sc25a(self):
"""SC-25A: legacy middle-gated ops (fix/uninstall/update) stay
"""SC-25A: legacy middle-gated ops (uninstall/update) stay
allowed at sl=normal local for this flag combination."""
payload = {
"fix": [_batch_op_item(f"sc25a-fix-{self.flags_label}")],
"uninstall": [_batch_op_item(f"sc25a-unin-{self.flags_label}")],
"update": [_batch_op_item(f"sc25a-upd-{self.flags_label}")],
}
+2 -4
View File
@@ -56,7 +56,6 @@ ComfyUI's `api.fetchApi()` automatically prepends the `/api` prefix to every pat
| 2-5 | Import Failed filter | Filter → "Import Failed" | Filter works | Client-side filter |
| 2-6 | Check Update | "Check Update" button | Filter flips to "Update", the check runs in the background, the list is loaded when the `cm-check-update` event tells its end | `POST /api/v2/customnode/check_update`, then `GET /api/v2/customnode/getlist?mode=cache&skip_update=true` |
| 2-7 | Check Missing | "Check Missing" button | Filter flips to "Missing" | `GET /api/v2/customnode/getmappings?mode=cache` |
| 2-8 | Alternatives filter | Filter → "Alternatives of A1111" | Data loads | `GET /api/customnode/alternatives?mode=cache` |
## 3. Full node install lifecycle
@@ -156,7 +155,7 @@ Note: skipped when no import-failed nodes are present.
| File | New/Enhanced | Scenarios | Target Endpoints |
|------|----------|:-------:|---------------|
| `legacy-ui-manager-menu.spec.ts` | enhanced | 7 | db_mode, channel_url_list, policy/update, notice |
| `legacy-ui-custom-nodes.spec.ts` | enhanced | 9 | getlist, getmappings, alternatives, import_fail_info |
| `legacy-ui-custom-nodes.spec.ts` | enhanced | 8 | getlist, getmappings, import_fail_info |
| `legacy-ui-node-lifecycle.spec.ts` | **new** | 8 | versions/{id}, disabled_versions/{id}, queue/batch (install/uninstall/update/fix/disable/enable) |
| `legacy-ui-node-versions.spec.ts` | **new** | 2 | versions/{id}, disabled_versions/{id} |
| `legacy-ui-batch-operations.spec.ts` | **new** | 4 | queue/batch (update_all, update_comfyui), queue/reset |
@@ -165,7 +164,7 @@ Note: skipped when no import-failed nodes are present.
| `legacy-ui-snapshot.spec.ts` | enhanced | 4 | snapshot/getlist, save, restore, remove |
| `legacy-ui-navigation.spec.ts` | existing | 4 | is_legacy_manager_ui, version |
**Total: 44 scenarios**
**Total: 43 scenarios**
## Legacy-only endpoint coverage
@@ -173,7 +172,6 @@ Note: skipped when no import-failed nodes are present.
|----------|---------|
| `GET /api/v2/customnode/getlist` | 2-1, 2-6 |
| `GET /api/v2/customnode/getmappings` | 2-2, 2-7 |
| `GET /api/customnode/alternatives` | 2-8 |
| `GET /api/v2/customnode/versions/{id}` | 3-1, 4-1 |
| `GET /api/v2/customnode/disabled_versions/{id}` | 3-6, 4-2 |
| `POST /api/v2/customnode/import_fail_info` | 7-1 |
+1 -42
View File
@@ -40,7 +40,6 @@ import {
openCustomNodesManager,
routeNodeList,
routeMappings,
routeAlternatives,
makePack,
expectInert,
serverSanitizeTag,
@@ -120,7 +119,7 @@ test.describe('grid render sinks', () => {
// PRECONDITION — the two virtualised columns must actually have body
// cells before their legs mean anything. Without this the row can go
// pass again the moment a layout change hides them, on a fixture that
// proved nothing (the same vacuous-pass shape the tags row guards against).
// proved nothing.
await expect(
page.locator(`${GRID} .cn-pack-stars`).first(),
'precondition: no .cn-pack-stars body cell rendered — the stars column is virtualised away at this viewport, so its leg would pass vacuously.',
@@ -136,46 +135,6 @@ test.describe('grid render sinks', () => {
});
});
test('hostile tags render inert once the alternatives column is shown (LIVE, gated)', async ({ page }) => {
// The alternatives column is `invisible: !this.hasAlternatives()`, so this
// row MUST establish the gate. Without the precondition assertion below it
// passes vacuously against a grid that never rendered the column at all.
await routeNodeList(page, { alt1: makePack('alt1') });
await routeAlternatives(page, {
alt1: {
id: 'alt1',
title: 'alt1',
description: 'alternative description',
tags: XSS_PAYLOAD,
},
});
await openManagerMenu(page);
await openCustomNodesManager(page);
// ESTABLISH THE GATE. `hasAlternatives()` is `this.filter ===
// ShowMode.ALTERNATIVES`, so the column exists ONLY while the filter
// dropdown is on "Alternatives of A1111" — selecting it is also what
// triggers getAlternatives() and therefore the `:1903` tag loop. Without
// this step the fixture is never fetched, nothing renders, and the row
// would report a failure that has nothing to do with the sink.
const filterSelect = page.locator('select.cn-manager-filter').first();
await expect(filterSelect).toBeVisible({ timeout: 10_000 });
await filterSelect.selectOption({ label: 'Alternatives of A1111' });
// PRECONDITION — assert on `.cn-tag-list` SPECIFICALLY, the div the tag
// loop emits. An earlier draft accepted `.cn-pack-desc` too, which the
// description column also carries: it matched, the row failed on a
// different leg, and it looked like a reproduction. That is the vacuous
// vacuous pass this row has to guard against, arriving as a vacuous
// FAILURE instead.
await expect(
page.locator(`${GRID} .cn-tag-list`).first(),
'precondition: no .cn-tag-list rendered, so the alternatives tag sink was never exercised — the row proves nothing about the sink.',
).toBeVisible({ timeout: 15_000 });
await expectInert(page, GRID, XSS_PAYLOAD, 'img', 'tags');
});
test('a server-escaped title renders decoded (no double-escape)', async ({ page }) => {
// THE REGRESSION GUARD FOR THE DOUBLE-ESCAPE FIX, and it only guards
// anything because the fixture is the WIRE form.
-13
View File
@@ -220,19 +220,6 @@ export async function routeMappings(page: Page, mappings: Record<string, unknown
});
}
/** Seed `/customnode/alternatives` — required to OPEN the alternatives column,
* which is `invisible: !this.hasAlternatives()`. Without this the alternatives
* column stays hidden and any test asserting on it passes vacuously. */
export async function routeAlternatives(page: Page, alts: Record<string, unknown>) {
await page.route('**/customnode/alternatives**', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(alts),
});
});
}
/** Open Manager menu -> Custom Nodes Manager and wait for the grid to fill. */
export async function openCustomNodesManager(page: Page) {
await clickMenuButton(page, 'Custom Nodes Manager');
@@ -530,7 +530,6 @@ test('nodes: lookup errors and missing row IDs remain literal text', async ({ pa
try {
for (const invoke of [
() => manager.getMissingNodesLegacy({}, new Set()),
() => manager.getAlternatives(),
() => manager.installNodes([payload], { target: document.createElement('button'), mode: 'install' }),
]) {
await invoke();
@@ -543,7 +542,7 @@ test('nodes: lookup errors and missing row IDs remain literal text', async ({ pa
}
return results;
}, XSS_PAYLOAD);
expect(results).toHaveLength(3);
expect(results).toHaveLength(2);
for (const result of results) {
expect(result.text).toContain(XSS_PAYLOAD);
expect(result.images).toBe(0);
+181
View File
@@ -0,0 +1,181 @@
"""aria2_download_url keeps the contract of download_url: it returns only when the
file is at <model_dir>/<filename> on this machine, and raises otherwise."""
import os
import time
import types
import pytest
from _install_flags_testutil import import_context
from test_snapshot_restore_pins import core # noqa: F401
posix_folder = pytest.mark.skipif(os.name == 'nt', reason='the folder that aria2 gets is a POSIX path')
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 # what aria2 writes through the mount when it completes
self.error_message = error_message
self.total_length = 10
self.completed_length = 0
self.updates = 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')
is_paused = property(lambda self: self.status == 'paused')
has_failed = property(lambda self: self.status == 'error')
is_complete = property(lambda self: self.status == 'complete')
is_removed = property(lambda self: self.status == 'removed')
def update(self):
self.updates += 1
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]
@pytest.fixture
def md(tmp_path, monkeypatch):
import_context()
from comfyui_manager.common import context, manager_downloader
monkeypatch.setattr(context, 'comfy_path', str(tmp_path))
monkeypatch.setattr(time, 'sleep', lambda s: None)
monkeypatch.delenv('COMFYUI_MANAGER_ARIA2_SAME_PATHS', raising=False)
return manager_downloader
def install(md, tmp_path, monkeypatch, fake):
monkeypatch.setattr(md, 'aria2', fake)
return md.download_url('https://huggingface.co/x/y.safetensors', str(tmp_path / 'models' / 'checkpoints'), 'y.safetensors')
def local(tmp_path):
return str(tmp_path / 'models' / 'checkpoints' / 'y.safetensors')
def test_a_download_that_aria2_fails_raises_with_its_message(md, tmp_path, monkeypatch):
fake = FakeAria2(FakeDownload(['error'], error_message='Failed to make the directory /models/checkpoints, cause: Permission denied'))
with pytest.raises(Exception, match='Permission denied'):
install(md, tmp_path, monkeypatch, fake)
@pytest.mark.parametrize('status', ['paused', 'removed'])
def test_a_download_that_was_stopped_with_a_part_of_the_file_there_raises(md, tmp_path, monkeypatch, status):
os.makedirs(os.path.dirname(local(tmp_path))); open(local(tmp_path), 'wb').close(); open(local(tmp_path) + '.aria2', 'wb').close()
with pytest.raises(Exception, match=status):
install(md, tmp_path, monkeypatch, FakeAria2(FakeDownload(['active', status])))
def test_a_file_that_aria2_saved_elsewhere_raises(md, tmp_path, monkeypatch):
fake = FakeAria2(FakeDownload(['complete'])) # complete, but not through a mount of this models folder
with pytest.raises(Exception, match='y.safetensors'):
install(md, tmp_path, monkeypatch, fake)
@posix_folder
def test_a_queued_download_is_waited_for(md, tmp_path, monkeypatch):
download = FakeDownload(['waiting', 'active', 'complete'], local_file=local(tmp_path))
fake = FakeAria2(download)
install(md, tmp_path, monkeypatch, fake)
assert download.is_complete and os.path.exists(local(tmp_path))
assert fake.added == [{'dir': '/models/checkpoints', 'out': 'y.safetensors'}]
@posix_folder
def test_a_failed_earlier_download_is_not_reused(md, tmp_path, monkeypatch):
old = FakeDownload(['error'], target='/models/checkpoints/y.safetensors')
fake = FakeAria2(FakeDownload(['active', 'complete'], local_file=local(tmp_path)), existing=[old])
install(md, tmp_path, monkeypatch, fake)
assert len(fake.added) == 1
@posix_folder
def test_a_finished_earlier_download_whose_file_is_there_is_reused(md, tmp_path, monkeypatch):
os.makedirs(os.path.dirname(local(tmp_path))); open(local(tmp_path), 'wb').close()
old = FakeDownload(['complete'], target='/models/checkpoints/y.safetensors')
fake = FakeAria2(FakeDownload(['complete']), existing=[old])
install(md, tmp_path, monkeypatch, fake)
assert fake.added == []
@posix_folder
def test_an_earlier_download_that_is_still_queued_is_waited_for(md, tmp_path, monkeypatch):
old = FakeDownload(['waiting', 'active', 'complete'], local_file=local(tmp_path), target='/models/checkpoints/y.safetensors')
fake = FakeAria2(FakeDownload(['complete']), existing=[old])
install(md, tmp_path, monkeypatch, fake)
assert fake.added == [] and os.path.exists(local(tmp_path))
def test_a_file_that_is_already_there_is_not_downloaded_again(md, tmp_path, monkeypatch):
os.makedirs(os.path.dirname(local(tmp_path))); open(local(tmp_path), 'wb').close()
fake = FakeAria2(FakeDownload(['complete']))
install(md, tmp_path, monkeypatch, fake)
assert fake.added == []
def test_a_part_that_aria2_has_a_control_file_for_is_downloaded(md, tmp_path, monkeypatch):
os.makedirs(os.path.dirname(local(tmp_path))); open(local(tmp_path), 'wb').close(); open(local(tmp_path) + '.aria2', 'wb').close()
fake = FakeAria2(FakeDownload(['complete']))
install(md, tmp_path, monkeypatch, fake)
assert len(fake.added) == 1
def test_a_nodepack_archive_whose_download_fails_leaves_no_file(core, md, tmp_path, monkeypatch): # noqa: F811
class Aria2ThatFailsHalfway(FakeAria2):
def add(self, url, options):
for name in (options['out'], options['out'] + '.aria2'):
(tmp_path / name).touch()
return super().add(url, options)
monkeypatch.setattr(md, 'aria2', Aria2ThatFailsHalfway(FakeDownload(['error'], error_message='the speed was too low')))
version = types.SimpleNamespace(version='1.0.0', download_url='https://example.invalid/fixture.zip')
with pytest.raises(Exception, match='the speed was too low'):
core.UnifiedManager()._cnr_install('fixture', version)
assert os.listdir(tmp_path) == []
def dir_given_to_aria2(md, monkeypatch, model_dir):
fake = FakeAria2(FakeDownload(['active', 'complete'], local_file=os.path.join(model_dir, 'y.safetensors')))
monkeypatch.setattr(md, 'aria2', fake)
md.download_url('https://huggingface.co/x/y.safetensors', model_dir, 'y.safetensors')
return fake.added[0]['dir']
@pytest.mark.parametrize('setting', [None, 'false'])
def test_by_default_aria2_gets_the_comfyui_folder_as_its_root(md, tmp_path, tmp_path_factory, monkeypatch, setting):
if setting is not None:
monkeypatch.setenv('COMFYUI_MANAGER_ARIA2_SAME_PATHS', setting)
outside = str(tmp_path_factory.mktemp('outside') / 'checkpoints')
assert dir_given_to_aria2(md, monkeypatch, str(tmp_path / 'models' / 'checkpoints')) == os.sep + os.path.join('models', 'checkpoints')
assert dir_given_to_aria2(md, monkeypatch, str(tmp_path / 'custom_nodes')) == os.sep + 'custom_nodes'
assert dir_given_to_aria2(md, monkeypatch, outside) == outside
def test_with_same_paths_aria2_gets_each_folder_as_it_is(md, tmp_path, tmp_path_factory, monkeypatch):
monkeypatch.setenv('COMFYUI_MANAGER_ARIA2_SAME_PATHS', 'true')
for model_dir in (str(tmp_path / 'models' / 'checkpoints'), str(tmp_path / 'custom_nodes'),
str(tmp_path_factory.mktemp('outside') / 'checkpoints')):
assert dir_given_to_aria2(md, monkeypatch, model_dir) == model_dir
+52 -5
View File
@@ -3,7 +3,8 @@
The channel is a local HTTP server. The startup cache update and `get_data_by_mode`
are the real functions of each server, run against a temporary cache directory and a
temporary bundled list. The Manager is laid out as an installed package, so the lists
are read from the cache that the startup cache update writes.
are read from the cache that the startup cache update writes. In `remote` mode the list
is read from the channel, and the cached list is kept when the channel fails (#3590).
"""
import asyncio
import json
@@ -20,7 +21,7 @@ from _install_flags_testutil import import_context
from legacy_html_testutil import PACKAGE, load_functions
FILENAME = "model-list.json"
STARTUP_FILES = 5
STARTUP_FILES = 4
BUNDLED = {"models": [{"name": "bundled with the Manager"}]}
SERVED = {"models": [{"name": "served by the channel"}]}
NOT_JSON = [
@@ -51,12 +52,12 @@ def manager_util(tmp_path, monkeypatch):
return manager_util
def load_server(server, manager_util, channel_url):
def load_server(server, manager_util, channel_url, network_mode="public"):
"""The startup cache update and `get_data_by_mode` of `server`, set to read `channel_url`."""
async def loaded(*args, **kwargs):
pass
config = {"channel_url": channel_url, "network_mode": "public", "default_cache_as_channel_url": True}
config = {"channel_url": channel_url, "network_mode": network_mode, "default_cache_as_channel_url": True}
core = SimpleNamespace(get_config=lambda: config, refresh_channel_dict=lambda: None, check_invalid_nodes=lambda: None,
unified_manager=SimpleNamespace(reload=loaded, get_custom_nodes=loaded))
remote = SimpleNamespace(remote=SimpleNamespace(value="remote"))
@@ -65,7 +66,7 @@ def load_server(server, manager_util, channel_url):
"manager_util": manager_util, "core": core, "ManagerDatabaseSource": remote})
reader = load_functions(PACKAGE / server / "manager_core.py", {"get_data_by_mode"}, {
"os": os, "json": json, "manager_util": manager_util,
"get_config": lambda: config, "get_channel_dict": lambda: {}})
"get_config": lambda: config, "normalize_channel": lambda channel: channel})
return startup["default_cache_update"], reader["get_data_by_mode"]
@@ -162,6 +163,52 @@ def test_list_from_the_channel_is_read_from_the_cache(manager_util, server):
assert run(scenario) == (SERVED, SERVED, STARTUP_FILES)
@pytest.mark.parametrize("server", SERVERS)
def test_remote_mode_reads_the_list_from_the_channel(manager_util, server):
async def scenario(channel, channel_url):
_, get_data_by_mode = load_server(server, manager_util, channel_url)
remote = await get_data_by_mode("remote", FILENAME)
cached = await get_data_by_mode("cache", FILENAME)
return remote, cached, channel.requests
assert run(scenario) == (SERVED, SERVED, 1)
@pytest.mark.parametrize("server", SERVERS)
@pytest.mark.parametrize("status, text", NOT_JSON)
def test_remote_mode_keeps_the_cached_list_when_the_channel_fails(manager_util, server, status, text):
async def scenario(channel, channel_url):
start, get_data_by_mode = load_server(server, manager_util, channel_url)
await start()
channel.serve(status, text)
return await get_data_by_mode("remote", FILENAME), channel.requests
assert run(scenario) == (SERVED, STARTUP_FILES + 1)
@pytest.mark.parametrize("server", SERVERS)
@pytest.mark.parametrize("status, text", NOT_JSON)
def test_remote_mode_of_an_install_that_is_no_pip_package_asks_the_channel_once_as_before(
manager_util, tmp_path, server, status, text):
os.makedirs(tmp_path / "custom_nodes")
async def scenario(channel, channel_url):
_, get_data_by_mode = load_server(server, manager_util, channel_url)
channel.serve(status, text)
return manager_util.is_manager_pip_package(), await get_data_by_mode("remote", FILENAME), channel.requests
assert run(scenario) == (False, BUNDLED, 1)
@pytest.mark.parametrize("server", SERVERS)
def test_remote_mode_does_not_ask_the_channel_when_offline(manager_util, server):
async def scenario(channel, channel_url):
_, get_data_by_mode = load_server(server, manager_util, channel_url, network_mode="offline")
return await get_data_by_mode("remote", FILENAME), channel.requests
assert run(scenario) == (BUNDLED, 0)
def test_unreadable_local_file_still_reads_as_empty(manager_util):
async def scenario(channel, channel_url):
path = os.path.join(manager_util.comfyui_manager_path, "broken.json")
+2 -2
View File
@@ -145,8 +145,8 @@ def run_the_queue(core, monkeypatch, update_check_done, *tasks): # noqa: F811
scratch = Path(core.get_default_custom_nodes_path()).parent
core.get_config()['model_download_by_agent'] = True
monkeypatch.setattr(core, 'update_path', lambda path: order.append('ComfyUI is updated') or 'skipped')
monkeypatch.setattr(core.unified_manager, 'unified_disable', lambda node_name, is_unknown: order.append('the task') or True)
monkeypatch.setattr(core.unified_manager, 'unified_enable', lambda cnr_id: order.append('the task'))
monkeypatch.setattr(core.unified_manager, 'unified_disable', lambda node_name, is_unknown: order.append('the task') or core.ManagedResult('disable'))
monkeypatch.setattr(core.unified_manager, 'unified_enable', lambda cnr_id: order.append('the task') or core.ManagedResult('enable'))
monkeypatch.setattr(core.unified_manager, 'unified_update', lambda node_name, node_ver: order.append('the task') or SimpleNamespace(
ver='unknown', result=True, action='skip'))
namespace = server({'task_worker', 'TaskBatch'}, core=core, logging=logging, traceback=traceback, os=os,
+85
View File
@@ -0,0 +1,85 @@
import asyncio
import io
import os
import sys
import traceback
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
import pytest
import typer
from rich.console import Console
from typing_extensions import Annotated, List
from legacy_html_testutil import ROOT, load_functions
from test_snapshot_restore_pins import core, manager # noqa: F401
@pytest.fixture
def cm_cli(manager, tmp_path): # noqa: F811
for name in ('enabled-pack', '.disabled/registry-pack@1_0_0', '.disabled/rc-pack@1_0_0-rc1', '.disabled/git-pack'):
(tmp_path / name).mkdir(parents=True)
manager.active_nodes['enabled-pack'] = ('2.0.0', str(tmp_path / 'enabled-pack'))
manager.cnr_inactive_nodes['registry-pack'] = {'1.0.0': str(tmp_path / '.disabled/registry-pack@1_0_0')}
manager.cnr_inactive_nodes['rc-pack'] = {'1.0.0-rc1': str(tmp_path / '.disabled/rc-pack@1_0_0-rc1')}
manager.unknown_inactive_nodes['git-pack'] = ('https://github.com/owner/git-pack', str(tmp_path / '.disabled/git-pack'))
out = io.StringIO()
def cm_cli(*names):
return load_functions(ROOT / 'cm_cli/__main__.py', set(names), {
'app': SimpleNamespace(command=lambda *args, **kwargs: lambda function: function),
'typer': typer, 'Annotated': Annotated, 'List': List, 'asyncio': asyncio, 'sys': sys, 'traceback': traceback,
'print': Console(file=out, width=1000, color_system=None).print, 'NodeInstallError': type('NodeInstallError', (Exception,), {}),
'cmd_ctx': Mock(no_deps=False), 'unified_manager': manager, 'auto_save_snapshot': AsyncMock(),
})
cm_cli.said = lambda: [' '.join(line.split()) for line in out.getvalue().splitlines() if 'pack' in line]
cm_cli.folders = lambda: (sorted(os.listdir(tmp_path)), sorted(os.listdir(tmp_path / '.disabled')))
return cm_cli
def all_of(cm_cli, name):
cm_cli(name, 'for_each_nodes', 'get_all_installed_node_specs', 'enable_node', 'disable_node')[name](['all'], None, None, None)
return [line.split('=>')[-1].strip() for line in cm_cli.said()], *cm_cli.folders()
def test_enable_all_enables_every_disabled_nodepack(cm_cli):
said, enabled, disabled = all_of(cm_cli, 'enable')
assert enabled == ['.disabled', 'enabled-pack', 'git-pack', 'rc-pack', 'registry-pack']
assert disabled == []
assert said[0] == 'Already enabled'
def test_disable_all_disables_every_enabled_nodepack_and_leaves_the_disabled_ones(cm_cli):
said, enabled, disabled = all_of(cm_cli, 'disable')
assert enabled == ['.disabled']
assert disabled == ['enabled-pack@2_0_0', 'git-pack', 'rc-pack@1_0_0-rc1', 'registry-pack@1_0_0']
assert said[1:] == ['Already disabled', 'Already disabled', 'Already disabled']
def test_latest_names_the_installed_nodepack_as_a_bare_id_does(cm_cli, manager, core, monkeypatch): # noqa: F811
for name, latest in (('enabled-pack', '3.0.0'), ('registry-pack', '1.5.0')):
manager.cnr_map[name] = {'id': name, 'latest_version': {'version': latest}}
monkeypatch.setattr(manager, 'unified_update', lambda node_id, version_spec=None, **kwargs: core.ManagedResult('update').with_target('3.0.0'))
monkeypatch.setattr(manager, 'unified_fix', lambda node_id, version_spec, **kwargs: core.ManagedResult('fix'))
acts = cm_cli('update_node', 'fix_node', 'disable_node', 'enable_node')
for act, name in (('update_node', 'enabled-pack'), ('fix_node', 'enabled-pack'), ('disable_node', 'enabled-pack'), ('enable_node', 'registry-pack')):
acts[act](name + '@latest')
assert cm_cli.said() == ['[ UPDATED ]: enabled-pack => (2.0.0 -> 3.0.0)', '[ FIXING ]: enabled-pack [2.0.0]', '[DISABLED] enabled-pack',
'[ENABLED] registry-pack']
assert cm_cli.folders() == (['.disabled', 'registry-pack'], ['enabled-pack@2_0_0', 'git-pack', 'rc-pack@1_0_0-rc1'])
def test_a_registry_nodepack_that_is_not_installed_is_not_called_disabled(cm_cli, manager): # noqa: F811
manager.cnr_map['absent-pack'] = {'id': 'absent-pack', 'latest_version': {'version': '1.0.0'}}
acts = cm_cli('update_node', 'fix_node', 'disable_node', 'enable_node')
for name in ('absent-pack', 'absent-pack@latest'):
for act in ('update_node', 'fix_node', 'disable_node', 'enable_node'):
acts[act](name)
assert [line.split('=>')[-1].strip() for line in cm_cli.said()] == ['Not installed', 'Not installed', 'Not found', 'Not found'] * 2
+350
View File
@@ -0,0 +1,350 @@
import ast
import asyncio
import concurrent.futures
import inspect
import io
import json
import os
import sys
import threading
import traceback
from types import SimpleNamespace
from typing import Optional
from unittest.mock import AsyncMock, Mock
import pytest
import rich
import typer
import typer.testing
from rich.console import Console
from typing_extensions import Annotated, List
from legacy_html_testutil import ROOT, load_functions
from test_snapshot_restore_pins import core, manager # noqa: F401
REASON = 'cannot move [the folder]'
def binds_print(node):
if isinstance(node, ast.Assign):
return any(isinstance(target, ast.Name) and target.id == 'print' for target in node.targets)
return isinstance(node, ast.ImportFrom) and any((name.asname or name.name) == 'print' for name in node.names)
@pytest.fixture
def cm_cli(manager, core, monkeypatch): # noqa: F811
out = io.StringIO()
path = ROOT / 'cm_cli/__main__.py'
its_print = [node for node in ast.parse(path.read_text(encoding='utf-8')).body if binds_print(node)]
def cm_cli(*names, width=1000, color_system=None, **more):
console = Console(file=out, width=width, color_system=color_system, no_color=False)
monkeypatch.setattr(rich, 'get_console', lambda: console)
scope = {
'app': SimpleNamespace(command=lambda *args, **kwargs: lambda function: function),
'typer': typer, 'Annotated': Annotated, 'List': List, 'Optional': Optional, 'asyncio': asyncio, 'os': os, 'sys': sys,
'json': json, 'threading': threading, 'concurrent': concurrent,
'traceback': traceback, 'core': core,
'NodeInstallError': type('NodeInstallError', (Exception,), {}),
'cmd_ctx': Mock(no_deps=False, channel='default', mode='cache'), 'unified_manager': manager, 'auto_save_snapshot': AsyncMock(),
'manager_util': Mock(), 'context': Mock(), 'comfy_path': '', '_finalize_resolve': Mock(), **more,
}
exec(compile(ast.Module(its_print, []), str(path), 'exec'), scope)
return load_functions(path, set(names), scope)
cm_cli.said = lambda: [' '.join(line.split()) for line in out.getvalue().splitlines() if line.strip()]
return cm_cli
def command(scope, name, **given):
try:
scope[name](**{**dict.fromkeys(inspect.signature(scope[name]).parameters), **given})
except (SystemExit, typer.Exit):
pass
@pytest.fixture
def folder(tmp_path):
(tmp_path / '[my] files').mkdir()
return str(tmp_path / '[my] files')
@pytest.fixture
def git_pack(tmp_path):
return 'https://example.invalid/git-pack', str(tmp_path / 'git-pack')
@pytest.mark.parametrize('name, label', [('git-pack', '[unknown]'), ('git-pack@nightly', '[nightly]')], ids=['unknown', 'nightly'])
def test_fix_names_the_version_of_a_git_nodepack(cm_cli, manager, core, git_pack, monkeypatch, name, label): # noqa: F811
if label == '[unknown]':
manager.unknown_active_nodes['git-pack'] = git_pack
else:
manager.active_nodes['git-pack'] = ('nightly', git_pack[1])
monkeypatch.setattr(manager, 'unified_fix', lambda node_id, version_spec, **kwargs: core.ManagedResult('fix'))
cm_cli('fix_node')['fix_node'](name, cnt_msg='1/1')
assert cm_cli.said() == [f'1/1 [ FIXING ]: git-pack {label}']
def test_fix_that_fails_says_why(cm_cli, manager, core, git_pack, monkeypatch): # noqa: F811
manager.unknown_active_nodes['git-pack'] = git_pack
monkeypatch.setattr(manager, 'unified_fix', lambda node_id, version_spec, **kwargs: core.ManagedResult('fix').fail('cannot fix [the reason]'))
cm_cli('fix_node')['fix_node']('git-pack', cnt_msg='1/1')
assert cm_cli.said()[1:] == ['ERROR: cannot fix [the reason]']
def test_fix_all_has_a_line_for_each_nodepack_it_counts(cm_cli, manager, core, git_pack, monkeypatch, tmp_path): # noqa: F811
manager.unknown_active_nodes['git-pack'] = git_pack
manager.unknown_inactive_nodes['old-pack'] = ('https://example.invalid/old-pack', str(tmp_path / '.disabled/old-pack'))
monkeypatch.setattr(manager, 'unified_fix', lambda node_id, version_spec, **kwargs: core.ManagedResult('fix'))
command(cm_cli('fix', 'for_each_nodes', 'get_all_installed_node_specs', 'fix_node'), 'fix', nodes=['all'])
assert cm_cli.said() == ['1/2 [ FIXING ]: git-pack [unknown]', '2/2 [ SKIPPED ]: old-pack@unknown => Disabled']
def test_url_that_is_not_installed_says_why(cm_cli, core, git_pack, monkeypatch): # noqa: F811
monkeypatch.setattr(core, 'gitclone_install', AsyncMock(return_value=core.ManagedResult('install-git').fail('cannot clone [the reason]')))
cm_cli('install_node')['install_node'](git_pack[0], cnt_msg='1/1')
assert cm_cli.said() == ['cannot clone [the reason]', "ERROR: An error occurred while installing 'https://example.invalid/git-pack'."]
def test_install_of_an_id_that_no_list_has_says_where_it_was_looked_for(cm_cli):
cm_cli('install_node')['install_node']('no-such-pack', cnt_msg='1/1')
assert cm_cli.said() == ["ERROR: An error occurred while installing 'no-such-pack'.", "Node 'no-such-pack@unknown' not found in [default, cache]"]
@pytest.mark.parametrize('enabled, method, answer, act, line', [
(False, 'unified_enable', lambda result: result('enable').fail(REASON), 'enable_node', '1/1 [ FAIL ] git-pack => ' + REASON),
(False, 'unified_enable', lambda result: result('skip').with_msg(REASON), 'enable_node', '1/1 [ SKIP ] git-pack => ' + REASON),
(True, 'unified_disable', lambda result: result('disable').fail(REASON), 'disable_node', '1/1 [ FAIL ] git-pack => ' + REASON),
(True, 'unified_disable', lambda result: result('skip').with_msg(REASON), 'disable_node', '1/1 [ SKIP ] git-pack => ' + REASON),
(True, 'unified_update', lambda result: result('skip').with_msg(REASON), 'update_node', '1/1 [ SKIPPED ]: git-pack => ' + REASON),
], ids=['enable_fails', 'enable_is_skipped', 'disable_fails', 'disable_is_skipped', 'update_is_skipped'])
def test_reason_in_square_brackets_is_printed_whole(cm_cli, manager, core, git_pack, monkeypatch, enabled, method, answer, act, line): # noqa: F811
(manager.unknown_active_nodes if enabled else manager.unknown_inactive_nodes)['git-pack'] = git_pack
monkeypatch.setattr(manager, method, lambda *args, **kwargs: answer(core.ManagedResult))
cm_cli(act)[act]('git-pack', cnt_msg='1/1')
assert cm_cli.said() == [line]
@pytest.mark.parametrize('name, enabled, act, line', [
('git-pack[old]', False, 'enable_node', '1/1 [ENABLED] git-pack[old]'),
('git-pack[old]', True, 'disable_node', '1/1 [DISABLED] git-pack[old]'),
('comfyui-manager[old]', True, 'disable_node', "1/1 [ SKIP ] comfyui-manager[old] => Not disabled: its name has 'comfyui-manager'"),
('git-pack[old]', False, 'fix_node', '1/1 [ SKIPPED ]: git-pack[old] => Disabled'),
('git-pack[old]', None, 'fix_node', '1/1 [ SKIPPED ]: git-pack[old] => Not installed'),
('git-pack[old]', None, 'update_node', '1/1 [ SKIPPED ]: git-pack[old] => Not installed'),
], ids=['enable', 'disable', 'disable_of_the_manager', 'fix_of_a_disabled_one', 'fix_of_one_that_is_not_installed',
'update_of_one_that_is_not_installed'])
def test_name_in_square_brackets_is_printed_whole(cm_cli, manager, core, tmp_path, monkeypatch, name, enabled, act, line): # noqa: F811
if enabled is not None:
(manager.unknown_active_nodes if enabled else manager.unknown_inactive_nodes)[name] = ('https://example.invalid/git-pack', str(tmp_path / name))
monkeypatch.setattr(manager, 'unified_enable', lambda *args, **kwargs: core.ManagedResult('enable'))
monkeypatch.setattr(manager, 'unified_disable', lambda *args, **kwargs: core.ManagedResult('disable'))
cm_cli(act)[act](name, cnt_msg='1/1')
assert cm_cli.said() == [line]
def test_line_longer_than_the_console_is_wide_is_written_as_one_line(cm_cli, manager, git_pack): # noqa: F811
manager.unknown_active_nodes['git-pack'] = git_pack
cm_cli('enable_node', width=80)['enable_node']('git-pack', cnt_msg='1/1')
assert cm_cli.said() == ['1/1 [ SKIP ] git-pack => Already enabled']
def test_error_of_a_nodepack_in_a_run_over_several_is_printed_whole(cm_cli):
def act(name, **kwargs):
raise RuntimeError('no such [thing] for ' + name)
with pytest.raises(SystemExit):
cm_cli('for_each_nodes', traceback=Mock())['for_each_nodes'](['git-pack'], act)
assert cm_cli.said()[0] == 'ERROR: no such [thing] for git-pack'
def test_error_of_an_update_in_a_run_over_several_is_printed_whole(cm_cli):
cm_cli('update_parallel', update_node=Mock(side_effect=RuntimeError('no such [thing]')), traceback=Mock())['update_parallel'](['git-pack'])
assert cm_cli.said() == ['ERROR: no such [thing]']
def test_show_versions_prints_a_changelog_with_square_brackets(cm_cli):
versions = [{'createdAt': '2026-01-02T03:04:05', 'version': '1.0.1', 'changelog': '[fix] a crash'}]
cm_cli('show_versions', cnr_utils=SimpleNamespace(all_versions_of_node=lambda name: versions))['show_versions']('git-pack')
assert cm_cli.said() == ['[2026-01-02] 1.0.1 -- [fix] a crash']
def test_show_prints_a_title_and_an_author_with_square_brackets(cm_cli, manager, tmp_path): # noqa: F811
manager.get_custom_nodes = AsyncMock(return_value={
'listed-pack': {'title': 'Listed [gist-wrapper] Pack', 'author': 'some[one]', 'files': ['https://github.com/someone/listed-pack']},
})
manager.cnr_map['registry-pack'] = {'id': 'registry-pack', 'name': 'Registry[official] Pack', 'publisher': {'name': 'someone'},
'latest_version': {'version': '1.0.0'}}
manager.active_nodes['registry-pack'] = ('1.0.0', str(tmp_path / 'registry-pack'))
manager.unknown_active_nodes['listed-pack'] = ('https://github.com/someone/listed-pack', str(tmp_path / 'listed-pack'))
scope = cm_cli('show', 'simple_show', 'show_list')
scope['show']('installed', None, None, None)
scope['simple_show']('installed', None, None, None)
assert cm_cli.said() == ['[ ENABLED ] Registry[official] Pack registry-pack (author: someone ) [1.0.0]',
'[ ENABLED ] Listed [gist-wrapper] Pack listed-pack (author: some[one] ) [UNKNOWN]',
'Registry[official] Pack@1.0.0', 'Listed [gist-wrapper] Pack@unknown']
def test_show_of_a_word_that_is_no_list_is_refused_in_plain_words(cm_cli, capsys):
command(cm_cli('simple_show'), 'simple_show', arg='[nodes]')
assert capsys.readouterr().err.split() == ['Invalid', 'command:', '`show', '[nodes]`']
def test_names_of_snapshots_are_listed_whole(cm_cli, folder):
open(os.path.join(folder, 'before [the update].json'), 'w').close()
scope = cm_cli('show_snapshot_list')
scope['cmd_ctx'].get_snapshot_path.return_value = folder
scope['show_snapshot_list']()
assert cm_cli.said() == ['before [the update].json']
def restore_of_a_file_that_is_not_there(scope, folder):
scope['cmd_ctx'].get_snapshot_path.return_value = folder
command(scope, 'restore_snapshot', snapshot_name='gone.json')
def save_as(scope, folder):
scope['core'].save_snapshot_with_postfix = AsyncMock(return_value=folder + '/snapshot.json')
command(scope, 'save_snapshot', output=folder + '/snapshot.json')
def deps_of_a_workflow(scope, folder):
open(folder + '/workflow.json', 'w').close()
scope['core'].extract_nodes_from_workflow = AsyncMock(return_value=({}, []))
command(scope, 'deps_in_workflow', workflow=folder + '/workflow.json', output=folder + '/deps.json')
def install_deps_of_a_file_that_is_not_json(scope, folder):
open(folder + '/deps.json', 'w').close()
command(scope, 'install_deps', deps=folder + '/deps.json')
@pytest.mark.parametrize('call, line', [
(restore_of_a_file_that_is_not_there, f'ERROR: `{{folder}}{os.sep}gone.json` is not exists.'),
(lambda scope, folder: command(scope, 'save_snapshot', output=folder + '/gone/snapshot.json'),
'ERROR: {folder}/gone/snapshot.json path not exists.'),
(save_as, 'Current snapshot is saved as `{folder}/snapshot.json`'),
(lambda scope, folder: command(scope, 'deps_in_workflow', workflow=folder + '/gone.json', output='deps.json'),
'File not found: {folder}/gone.json'),
(deps_of_a_workflow, 'Workflow dependencies are being saved into {folder}/deps.json.'),
(lambda scope, folder: command(scope, 'install_deps', deps=folder + '/gone.json'), 'File not found: {folder}/gone.json'),
(install_deps_of_a_file_that_is_not_json, 'Invalid json file: {folder}/deps.json'),
], ids=['restore-snapshot of a file that is not there', 'save-snapshot into a folder that is not there', 'save-snapshot',
'deps-in-workflow of a file that is not there', 'deps-in-workflow', 'install-deps of a file that is not there',
'install-deps of a file that is not JSON'])
def test_path_with_square_brackets_is_printed_whole(cm_cli, core, monkeypatch, folder, call, line): # noqa: F811
monkeypatch.setattr(core, 'save_snapshot_with_postfix', None)
monkeypatch.setattr(core, 'extract_nodes_from_workflow', None)
call(cm_cli('restore_snapshot', 'save_snapshot', 'deps_in_workflow', 'install_deps'), folder)
assert cm_cli.said()[-1:] == [line.replace('{folder}', folder)]
@pytest.mark.parametrize('path', [r'C:\ComfyUI\[My] files\deps.json', '/nodes/' + 'long-folder-name/' * 5 + 'deps.json', '/nodes/x:100:y/deps.json'],
ids=['a backslash before a bracket', 'longer than the console is wide', 'the code of an emoji'])
@pytest.mark.parametrize('call, line', [
(lambda scope, path: command(scope, 'install_deps', deps=path), 'File not found: {}'),
(lambda scope, path: command(scope, 'save_snapshot'), 'Current snapshot is saved as `{}`'),
], ids=['a coloured line', 'a line without a colour'])
def test_line_is_written_as_it_is(cm_cli, core, monkeypatch, call, line, path): # noqa: F811
monkeypatch.setattr(core, 'save_snapshot_with_postfix', AsyncMock(return_value=path))
call(cm_cli('install_deps', 'save_snapshot', width=80), path)
assert cm_cli.said() == [line.format(path)]
def list_a_snapshot_with_a_quoted_word(scope, folder):
open(os.path.join(folder, "the 'old' one.json"), 'w').close()
scope['cmd_ctx'].get_snapshot_path.return_value = folder
scope['show_snapshot_list']()
@pytest.mark.parametrize('call, line', [
(lambda scope, folder: command(scope, 'install_deps', deps='deps.json'), '\x1b[1;31mFile not found: deps.json\x1b[0m'),
(list_a_snapshot_with_a_quoted_word, "the \x1b[32m'old'\x1b[0m one.json"),
], ids=['a line that cm-cli colours', 'a quoted text in another line'])
def test_line_keeps_its_colour(cm_cli, folder, call, line):
call(cm_cli('install_deps', 'show_snapshot_list', color_system='standard'), folder)
assert cm_cli.said() == [line]
@pytest.mark.parametrize('app', [typer.Typer, lambda: typer.Typer(rich_markup_mode=None)], ids=['with rich markup', 'without'])
def test_help_names_the_values_that_an_argument_and_an_option_take(cm_cli, app):
app = cm_cli('show', 'update', app=app())['app']
def help(name):
return ' '.join(typer.testing.CliRunner().invoke(app, [name, '--help'], env={'COLUMNS': '200'}).output.split())
assert 'installed|enabled|not-installed' in help('show') and 'all|List of custom nodes to update' in help('update')
assert 'remote|local|cache' in help('show') and 'remote|local|cache' in help('update')
assert '\\' not in help('show') + help('update')
def test_report_of_the_resolver_names_a_requirement_with_its_extra(cm_cli, monkeypatch, tmp_path):
result = SimpleNamespace(success=False, error='no solution for [the pack]', lockfile=SimpleNamespace(conflicts=['a conflict']),
collected=SimpleNamespace(sources={}))
monkeypatch.setitem(sys.modules, 'comfyui_manager.common.unified_dep_resolver', SimpleNamespace(
collect_node_pack_paths=lambda paths: [str(tmp_path / 'a-pack')], collect_base_requirements=lambda path: [],
UnifiedDepResolver=lambda **kwargs: SimpleNamespace(resolve_and_install=lambda: result), UvNotAvailableError=RuntimeError,
attribute_conflicts=lambda sources, conflicts: {'opencv-python-headless': [(str(tmp_path / 'a-pack'), 'opencv-python-headless[ffmpeg]>=4')]}))
command(cm_cli('_run_unified_resolve', cm_global=Mock()), '_run_unified_resolve')
assert cm_cli.said()[1:] == ['Resolution failed: no solution for [the pack]', 'Conflicting packages (by node pack):',
'opencv-python-headless:', 'a-pack → opencv-python-headless[ffmpeg]>=4']
def test_disable_says_why_the_manager_is_not_disabled(cm_cli):
cm_cli('disable_node')['disable_node']('comfyui-manager', cnt_msg='1/1')
assert cm_cli.said() == ["1/1 [ SKIP ] comfyui-manager => Not disabled: its name has 'comfyui-manager'"]
def test_disable_all_has_a_line_for_each_nodepack_it_counts(cm_cli, manager, tmp_path): # noqa: F811
for name in ('comfyui-manager', 'git-pack'):
(tmp_path / name).mkdir()
manager.unknown_active_nodes[name] = ('https://example.invalid/' + name, str(tmp_path / name))
cm_cli('disable', 'for_each_nodes', 'get_all_installed_node_specs', 'disable_node')['disable'](['all'], None, None, None)
assert [line.split()[0] for line in cm_cli.said()] == ['1/2', '2/2']
def test_restore_dependencies_runs_for_the_nodepacks_only(cm_cli, manager, folder): # noqa: F811
for name in ('a-pack', '__pycache__', 'b-pack.disabled', '.disabled'):
os.mkdir(os.path.join(folder, name))
manager.execute_install_script = Mock()
scope = cm_cli('restore_dependencies')
scope['cmd_ctx'].get_custom_nodes_paths.return_value = [folder]
command(scope, 'restore_dependencies', uv_compile=False)
assert [line for line in cm_cli.said() if line.startswith('Restoring')] == [f'Restoring [1/1]: {folder}{os.sep}a-pack']
assert [call.args[1] for call in manager.execute_install_script.call_args_list] == [os.path.join(folder, 'a-pack')]
+197
View File
@@ -0,0 +1,197 @@
import os
from pathlib import Path
import pytest
from test_grid_highlight_escaping import browser # noqa: F401 -- fixture
JS = Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "comfyui_manager" / "js"))
EXTENSION = "http://manager.test/extensions/comfyui-manager-legacy/"
CONTENT_TYPES = {".js": "text/javascript", ".css": "text/css"}
BATCH = "/v2/manager/queue/batch"
RESET = "/v2/manager/queue/reset"
STATUS = "/v2/manager/queue/status"
TITLES = ["String Join Tools", "ComfyUI-PromptUtilities", "String Join (Multi)"]
SCRIPTS = {
"api.js": """
class Api extends EventTarget {
async getNodeDefs() { return {}; }
async fetchApi(route, options) {
const path = route.split('?')[0];
requested.push({path, method: options?.method ?? 'GET', body: options?.body ? JSON.parse(options.body) : null});
await during[path]?.();
const answer = server[path];
if(answer === undefined) return {status: 404, statusText: 'Not Found'};
return {status: 200, json: async () => structuredClone(answer)};
}
}
export const api = new Api();
""",
"app.js": """
export const app = {
graph: {_nodes: [], extra: {}},
registerExtension() {},
ui: {settings: {settingsValues: {}}, dialog: {element: document.createElement('div'), show() {}}},
};
""",
"ui.js": """
export function $el(tag, props, children) {
if(Array.isArray(props)) [props, children] = [{}, props];
const names = tag.split('.');
const element = document.createElement(names.shift());
element.classList.add(...names);
const {parent, style, ...rest} = props ?? {};
Object.assign(element.style, style);
Object.assign(element, rest);
element.append(...(children ?? []));
parent?.append(element);
return element;
}
export class ComfyDialog {}
""",
}
def pack(title):
key = title.lower().replace(" ", "-")
repository = "https://github.com/someone/" + key
return {"id": key, "title": title, "author": "someone", "description": "nodes", "repository": repository,
"reference": repository, "files": [repository], "install_type": "cnr", "version": "1.0.0",
"cnr_latest": "1.0.0", "state": "not-installed", "stars": 10, "last_update": "2025-01-01 00:00:00"}
@pytest.fixture
def page(browser): # noqa: F811
page = browser.new_page(viewport={"width": 1600, "height": 900})
def route(request):
url = request.request.url
name = url.rsplit("/", 1)[-1]
if url == "http://manager.test/":
request.fulfill(body="<body></body>", content_type="text/html")
elif url.startswith(EXTENSION) and (JS / name).is_file():
request.fulfill(path=str(JS / name), content_type=CONTENT_TYPES.get((JS / name).suffix, "text/plain"))
elif url == "http://manager.test/scripts/" + name and name in SCRIPTS:
request.fulfill(body=SCRIPTS[name], content_type="text/javascript")
else:
request.abort()
page.route("**/*", route)
page.errors = []
page.on("pageerror", lambda error: page.errors.append(str(error)))
page.goto("http://manager.test/")
page.evaluate("""async ({module, packs}) => {
window.requested = [];
window.during = {};
window.server = {
'/v2/customnode/getlist': {channel: 'default', node_packs: Object.fromEntries(packs.map(pack => [pack.id, pack]))},
'/v2/customnode/getmappings': {},
'/v2/manager/queue/batch': {failed: []},
'/v2/manager/queue/reset': '',
};
const {app} = await import('/scripts/app.js');
const {setManagerInstance} = await import(new URL('common.js', module).href);
setManagerInstance({datasrc_combo: {value: 'cache'}});
const {CustomNodesManager} = await import(module);
CustomNodesManager.instance = new CustomNodesManager(app, null);
CustomNodesManager.instance.show(CustomNodesManager.ShowMode.NORMAL);
}""", {"module": EXTENSION + "custom-nodes-manager.js", "packs": [pack(title) for title in TITLES]})
page.wait_for_function("document.querySelector('.cn-manager-status').textContent == '3 custom nodes'")
yield page
page.close()
def queue_is_running(page, running):
page.evaluate("running => server['%s'] = {total_count: 0, done_count: 0, in_progress_count: 0, is_processing: running}"
% STATUS, running)
def install_all(page):
page.locator(".cn-manager-grid .tg-select-icon-all").click()
page.locator(".cn-manager-selection button[mode='install']").click()
page.wait_for_function("requested.some(request => request.path == '%s')" % BATCH)
batch = page.evaluate("requested.find(request => request.path == '%s').body" % BATCH)
return batch["batch_id"], [item["ui_id"] for item in batch["install"]]
def report(page, detail):
page.evaluate("""async (detail) => {
const { api } = await import('/scripts/api.js');
api.dispatchEvent(new CustomEvent('cm-queue-status', {detail}));
await new Promise(resolve => setTimeout(resolve));
}""", detail)
def installed(page, batch_id, targets):
for done, target in enumerate(targets, 1):
report(page, {"status": "in_progress", "target": target, "batch_id": batch_id, "ui_target": "nodepack_manager",
"total_count": len(TITLES), "done_count": done})
def finish(page, batch_id, targets):
installed(page, batch_id, targets)
report(page, {"status": "batch-done", "nodepack_result": dict.fromkeys(targets, "success"), "model_result": {},
"total_count": len(TITLES), "done_count": len(TITLES), "batch_id": batch_id, "remaining_batch_count": 1})
report(page, {"status": "all-done"})
def shown(page):
return page.evaluate("""() => {
const rows = [...document.querySelectorAll('.cn-manager-grid .tg-body .tg-row')];
return {
rows: rows.filter(row => row.querySelector('.cn-pack-name')).map(row => {
const right = rows.find(other => other.getAttribute('row') == row.getAttribute('row') && other != row);
const action = right.querySelector('.cn-install-buttons, font');
return [row.querySelector('.cn-pack-name').innerText.trim(), action.innerText.trim(), !!action.querySelector('.cn-btn-loading')];
}),
stop: document.querySelector('.cn-manager-stop').checkVisibility(),
restart: document.querySelector('.cn-manager-restart').checkVisibility(),
};
}""")
@pytest.mark.parametrize("done", [1, 0], ids=["after-the-first-install", "before-the-batch-started"])
def test_stop_returns_the_rows_that_were_not_installed_to_install(page, done):
queue_is_running(page, False)
batch_id, targets = install_all(page)
assert shown(page)["stop"] is True
page.locator(".cn-manager-stop").click()
page.wait_for_function("requested.some(request => request.path == '%s' && request.method == 'POST')" % RESET)
installed(page, batch_id, targets[:done])
report(page, {"status": "all-done"})
assert shown(page) == {
"rows": [[title, "Restart Required" if i < done else "Install", False] for i, title in enumerate(TITLES)],
"stop": False, "restart": done > 0}
assert page.errors == []
def test_the_end_of_an_earlier_queue_leaves_a_running_install_waiting(page):
queue_is_running(page, True)
batch_id, targets = install_all(page)
report(page, {"status": "all-done"})
assert shown(page) == {"rows": [[title, "Install", True] for title in TITLES], "stop": True, "restart": False}
finish(page, batch_id, targets)
assert shown(page) == {"rows": [[title, "Restart Required", False] for title in TITLES], "stop": False, "restart": True}
assert page.errors == []
def test_the_end_of_an_earlier_queue_while_the_install_is_being_queued_leaves_it_waiting(page):
queue_is_running(page, False)
page.evaluate("""() => during['%s'] = async () => {
const { api } = await import('/scripts/api.js');
api.dispatchEvent(new CustomEvent('cm-queue-status', {detail: {status: 'all-done'}}));
await new Promise(resolve => setTimeout(resolve));
}""" % BATCH)
batch_id, targets = install_all(page)
page.wait_for_function("document.querySelector('.cn-manager-stop').checkVisibility()", timeout=5000)
assert shown(page) == {"rows": [[title, "Install", True] for title in TITLES], "stop": True, "restart": False}
finish(page, batch_id, targets)
assert shown(page) == {"rows": [[title, "Restart Required", False] for title in TITLES], "stop": False, "restart": True}
assert page.errors == []
+198
View File
@@ -0,0 +1,198 @@
import asyncio
import json
import logging
import os
import sys
import traceback
from types import SimpleNamespace
import pytest
from aiohttp import web
from _install_flags_testutil import import_context, import_glob_security_utils, import_reader
from legacy_html_testutil import PACKAGE, ROOT, load_functions
COMFY_ORG = 'https://raw.githubusercontent.com/Comfy-Org/ComfyUI-Manager/main'
LTDRDATA = 'https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main'
MIRROR = 'https://example.invalid/mirror'
BAR_URL = 'https://github.com/example/ComfyUI-Bar'
SERVED = {
'custom-node-list.json': {'custom_nodes': [{'author': 'example', 'title': 'ComfyUI-Bar', 'reference': BAR_URL, 'files': [BAR_URL],
'install_type': 'git-clone', 'description': ''}]},
'extension-node-map.json': {BAR_URL: [['BarNode'], {'title_aux': 'ComfyUI-Bar'}]},
'model-list.json': {'models': [{'name': 'served by the channel'}]},
'github-stats.json': {BAR_URL: {'stars': 7, 'last_update': '2026-11-01 00:00:00', 'author_account_age_days': 900}},
}
BUNDLED = {'custom-node-list.json': {'custom_nodes': []}, 'extension-node-map.json': {}, 'model-list.json': {'models': []},
'github-stats.json': {}, 'extras.json': {'favorites': []}}
REGISTRY = [{'id': 'comfyui-foo', 'name': 'Foo', 'repository': 'https://github.com/example/ComfyUI-Foo',
'publisher': {'name': 'example'}, 'description': '', 'latest_version': {'version': '1.0.1'}}]
SPELLINGS = [pytest.param(COMFY_ORG, id='Comfy-Org'), pytest.param(LTDRDATA, id='ltdrdata')]
CONFIGS = [pytest.param(None, id='no channel_url')] + SPELLINGS
WRITERS = ['glob start', 'legacy start', 'cm-cli update-cache']
CACHED = [pytest.param((), id='DEFAULT_CHANNEL'), pytest.param(('default_cache_as_channel_url = True',), id='channel_url')]
route = lambda path: lambda handler: handler # noqa: E731
@pytest.fixture
def user(tmp_path, monkeypatch):
context = import_context()
from comfyui_manager.common import manager_util
cores = {'glob': import_reader('glob'), 'legacy': import_reader('legacy')}
for core in cores.values():
monkeypatch.setattr(core, 'cached_config', None)
monkeypatch.setattr(core, 'channel_dict', None)
monkeypatch.setattr(core, 'channel_list', None)
monkeypatch.setattr(core, 'valid_channels', set(core.valid_channels))
monkeypatch.setattr(context, 'manager_config_path', str(tmp_path / 'config.ini'))
monkeypatch.setattr(context, 'manager_channel_list_path', str(tmp_path / 'channels.list'))
monkeypatch.setattr(manager_util, 'cache_dir', str(tmp_path / 'cache'))
monkeypatch.setattr(manager_util, 'comfyui_manager_path', str(tmp_path / 'manager'))
os.makedirs(manager_util.cache_dir)
os.makedirs(manager_util.comfyui_manager_path)
for name, data in BUNDLED.items():
with open(os.path.join(manager_util.comfyui_manager_path, name), 'w', encoding='utf-8') as f:
json.dump(data, f)
get_data = manager_util.get_data
async def from_the_channel(uri, silent=False):
if uri.startswith('https://'):
return json.loads(json.dumps(SERVED[os.path.basename(uri)]))
return await get_data(uri, silent)
monkeypatch.setattr(manager_util, 'get_data', from_the_channel)
return SimpleNamespace(cores=cores, util=manager_util, path=tmp_path, monkeypatch=monkeypatch)
def configure(user, channel_url, default_url, *lines):
config = ['[default]'] + ([f'channel_url = {channel_url}'] if channel_url else []) + list(lines)
(user.path / 'config.ini').write_text('\n'.join(config) + '\n')
(user.path / 'channels.list').write_text(f'default::{default_url}\nrecent::{default_url}/node_db/new\nmirror::{MIRROR}\n')
async def idle(*args, **kwargs):
pass
def write(user, writer):
core = user.cores['glob' if writer == 'glob start' else 'legacy']
with user.monkeypatch.context() as m:
m.setattr(core, 'unified_manager', SimpleNamespace(reload=idle, get_custom_nodes=idle))
m.setattr(core, 'check_invalid_nodes', lambda: None)
if writer == 'cm-cli update-cache':
cli = load_functions(ROOT / 'cm_cli/__main__.py', {'_force_update_cache'}, {
'os': os, 'sys': sys, 'asyncio': asyncio, 'print': lambda *args, **kwargs: None, 'core': core,
'manager_util': user.util, 'unified_manager': SimpleNamespace(reload=idle, load_nightly=idle)})
asyncio.run(cli['_force_update_cache']('default'))
else:
server = load_functions(PACKAGE / writer.split()[0] / 'manager_server.py', {'default_cache_update'}, {
'os': os, 'logging': logging, 'traceback': traceback, 'asyncio': asyncio, 'manager_util': user.util,
'core': core, 'ManagerDatabaseSource': SimpleNamespace(remote=SimpleNamespace(value='remote'))})
asyncio.run(server['default_cache_update']())
def handlers(user, server, names):
return load_functions(PACKAGE / server / 'manager_server.py', names, {
'core': user.cores[server], 'web': web, 'routes': SimpleNamespace(get=route, post=route),
'populate_markdown': lambda node_pack: None})
def answer(handler, **query):
response = asyncio.run(handler(SimpleNamespace(rel_url=SimpleNamespace(query=query))))
return json.loads(response.text)
def install_levels(user):
glob = import_glob_security_utils()
legacy = load_functions(PACKAGE / 'legacy/manager_server.py', {'get_risky_level'}, {'core': user.cores['legacy']})
return {'glob': asyncio.run(glob.get_risky_level([BAR_URL], [])), 'legacy': asyncio.run(legacy['get_risky_level']([BAR_URL], []))}
def unread(user):
return {(name, channel, filename): data
for name, core in user.cores.items() for channel in (None, 'default', COMFY_ORG, LTDRDATA) for filename in SERVED
if (data := asyncio.run(core.get_data_by_mode('cache', filename, channel))) != SERVED[filename]}
@pytest.mark.parametrize('cached', CACHED)
@pytest.mark.parametrize('default_url', SPELLINGS)
@pytest.mark.parametrize('channel_url', CONFIGS)
@pytest.mark.parametrize('writer', WRITERS)
def test_every_reader_reads_the_lists_that_were_written(user, writer, channel_url, default_url, cached):
configure(user, channel_url, default_url, *cached)
write(user, writer)
assert unread(user) == {}
assert install_levels(user) == {'glob': 'middle+', 'legacy': 'middle+'}
@pytest.mark.parametrize('cached', CACHED)
@pytest.mark.parametrize('default_url', SPELLINGS)
@pytest.mark.parametrize('channel_url', CONFIGS)
def test_both_servers_and_cm_cli_write_one_set_of_cache_files(user, channel_url, default_url, cached):
configure(user, channel_url, default_url, *cached)
for writer in WRITERS:
write(user, writer)
assert len(os.listdir(user.util.cache_dir)) == len(SERVED)
@pytest.fixture
def registry(user, monkeypatch):
custom_nodes = user.path / 'comfyui' / 'custom_nodes'
custom_nodes.mkdir(parents=True)
monkeypatch.setattr(sys.modules['folder_paths'], 'get_folder_paths', lambda name: [str(custom_nodes)], raising=False)
core = user.cores['legacy']
async def get_cnr_data(*args, **kwargs):
return REGISTRY
monkeypatch.setattr(core.cnr_utils, 'get_cnr_data', get_cnr_data)
monkeypatch.setattr(core, 'unified_manager', core.UnifiedManager())
@pytest.mark.parametrize('default_url', SPELLINGS)
@pytest.mark.parametrize('channel_url', CONFIGS)
def test_custom_nodes_manager_lists_the_registry_nodepacks_on_the_default_channel(user, registry, channel_url, default_url):
configure(user, channel_url, default_url)
write(user, 'legacy start')
listed = answer(handlers(user, 'legacy', {'fetch_customnode_list'})['fetch_customnode_list'], mode='cache')
assert listed['channel'] == 'default'
assert {key: row['reference'] for key, row in listed['node_packs'].items()} == {
'ComfyUI-Bar': BAR_URL, 'comfyui-foo': 'https://registry.comfy.org/nodes/comfyui-foo'}
@pytest.mark.parametrize('server', ['glob', 'legacy'])
@pytest.mark.parametrize('default_url', SPELLINGS)
@pytest.mark.parametrize('channel_url', CONFIGS)
def test_channel_menu_selects_the_default_channel(user, server, channel_url, default_url):
configure(user, channel_url, default_url)
assert answer(handlers(user, server, {'channel_url_list'})['channel_url_list'])['selected'] == 'default'
@pytest.mark.parametrize('server', ['glob', 'legacy'])
@pytest.mark.parametrize('default_url', SPELLINGS)
def test_another_channel_keeps_its_own_lists(user, server, default_url):
configure(user, MIRROR, default_url, 'default_cache_as_channel_url = True')
write(user, f'{server} start')
core = user.cores[server]
assert sorted(os.listdir(user.util.cache_dir)) == sorted(
f'{user.util.simple_hash(f"{MIRROR}/{filename}")}_{filename}' for filename in SERVED)
assert {filename: asyncio.run(core.get_data_by_mode('cache', filename)) for filename in SERVED} == SERVED
assert answer(handlers(user, server, {'channel_url_list'})['channel_url_list'])['selected'] == 'mirror'
@pytest.mark.parametrize('default_url', SPELLINGS)
def test_custom_nodes_manager_on_another_channel_lists_only_its_nodepacks(user, registry, default_url):
configure(user, MIRROR, default_url, 'default_cache_as_channel_url = True')
write(user, 'legacy start')
listed = answer(handlers(user, 'legacy', {'fetch_customnode_list'})['fetch_customnode_list'], mode='cache')
assert (listed['channel'], list(listed['node_packs'])) == ('mirror', ['ComfyUI-Bar'])
@@ -0,0 +1,23 @@
"""config.ini's `dependency_management` reaches manager_util through both config readers, as cm-cli reads it."""
import pytest
from _install_flags_testutil import import_context, import_reader
@pytest.mark.parametrize("reader", ["glob", "legacy"])
@pytest.mark.parametrize("environment, expected", [(None, False), ("on", True)])
def test_config_value_is_applied_unless_the_environment_says_otherwise(reader, environment, expected, monkeypatch, tmp_path):
core = import_reader(reader)
path = tmp_path / "config.ini"
path.write_text("[default]\ndependency_management = off\n", encoding="utf-8")
monkeypatch.setattr(import_context(), "manager_config_path", str(path))
monkeypatch.setattr(core, "cached_config", None)
monkeypatch.setattr(core.manager_util, "dependency_management_enabled", True)
if environment is None:
monkeypatch.delenv("COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT", raising=False)
else:
monkeypatch.setenv("COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT", environment)
core.get_config()
assert core.manager_util.dependency_management_enabled is expected
+1 -1
View File
@@ -63,7 +63,7 @@ def load(monkeypatch, server, security_level, listener, active=None, nightly_ina
manager.cnr_inactive_nodes = packs(cnr_inactive)
manager.unknown_active_nodes = unknown_active or {}
manager.unknown_inactive_nodes = unknown_inactive or {}
manager.unified_enable = enabled.append
manager.unified_enable = lambda cnr_id: enabled.append(cnr_id) or SimpleNamespace(result=True)
core = SimpleNamespace(
unified_manager=manager,
get_config=lambda: {"security_level": security_level,
+103
View File
@@ -454,6 +454,109 @@ def test_snapshot_denial_preserves_existing_pack_without_retry(core, monkeypatch
assert get.call_count == 1
def disabled_fixture(manager, tmp_path, versions, in_registry_data=True):
if in_registry_data:
manager.cnr_map['fixture'] = {'id': 'fixture', 'latest_version': {'version': '2.0.0'}}
for key in versions:
folder = tmp_path / ('.disabled/fixture@' + key.replace('.', '_'))
folder.mkdir(parents=True)
(folder / '__init__.py').write_text(key)
(folder / '.tracking').write_text('__init__.py')
manager.cnr_inactive_nodes.setdefault('fixture', {})[key] = str(folder)
return manager
def mock_registry_query_and_download(core, monkeypatch):
get, download = Mock(return_value=api_response('NodeVersionStatusActive')), Mock()
monkeypatch.setattr(core.cnr_utils.requests, 'get', get)
monkeypatch.setattr(core.manager_downloader, 'download_url', download)
monkeypatch.setattr(core.manager_downloader, 'basic_download_url', download)
return get, download
def press_enable(core, manager, node_id):
path = Path(core.__file__).with_name('manager_server.py')
names = {'do_enable', 'replaces_cnr_with_nightly'}
nodes = [node for node in ast.walk(ast.parse(path.read_text(encoding='utf-8')))
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names]
allowed = lambda level: True
namespace = {'core': SimpleNamespace(unified_manager=manager), 'logging': logging, 'SECURITY_MESSAGE_MIDDLE_P': '',
'is_allowed_security_level': allowed, 'security_utils': SimpleNamespace(is_allowed_security_level=allowed)}
if core.__name__ == 'comfyui_manager.glob.manager_core':
from comfyui_manager.data_models import EnablePackParams, OperationResult
namespace.update(OperationResult=OperationResult, EnablePackParams=EnablePackParams)
task = EnablePackParams(cnr_id=node_id)
else:
task = ('row', node_id)
exec(compile(ast.Module(nodes, []), str(path), 'exec'), namespace)
return asyncio.run(namespace['do_enable'](task))
@pytest.mark.parametrize('key', ['1.0.0', '1.0.0-beta'])
def test_install_without_version_restores_the_disabled_version(core, monkeypatch, tmp_path, key):
get, download = mock_registry_query_and_download(core, monkeypatch)
manager = disabled_fixture(core.UnifiedManager(), tmp_path, [key])
result = asyncio.run(manager.install_by_id('fixture', instant_execution=True))
assert (result.result, result.action, (tmp_path / 'fixture/__init__.py').read_text()) == (True, 'enable', key)
assert manager.active_nodes['fixture'] == (key, str(tmp_path / 'fixture'))
assert (get.call_count, download.call_count) == (0, 0)
def test_enable_without_version_restores_the_disabled_version(core, tmp_path):
manager = disabled_fixture(core.UnifiedManager(), tmp_path, ['1.0.0'])
assert manager.is_disabled('fixture')
result = manager.unified_enable('fixture')
assert (result.result, result.action, (tmp_path / 'fixture/__init__.py').read_text()) == (True, 'enable', '1.0.0')
assert not (tmp_path / '.disabled/fixture@1_0_0').exists()
def test_enable_button_answers_success_for_an_enabled_pack_that_the_registry_data_does_not_list(core, tmp_path):
manager = disabled_fixture(core.UnifiedManager(), tmp_path, ['0.9.0'], in_registry_data=False)
enabled = tmp_path / 'fixture'
enabled.mkdir()
(enabled / '__init__.py').write_text('1.0.0')
manager.active_nodes['fixture'] = ('1.0.0', str(enabled))
assert press_enable(core, manager, 'fixture') == 'success'
assert (enabled / '__init__.py').read_text() == '1.0.0'
assert (tmp_path / '.disabled/fixture@0_9_0/__init__.py').read_text() == '0.9.0'
def test_enable_button_says_why_for_a_disabled_pack_that_the_registry_data_does_not_list(core, tmp_path, caplog):
manager = disabled_fixture(core.UnifiedManager(), tmp_path, ['1.0.0'], in_registry_data=False)
assert press_enable(core, manager, 'fixture') == "Failed to enable: 'fixture'"
assert 'Specified inactive node not exists: fixture' in caplog.text
assert (tmp_path / '.disabled/fixture@1_0_0/__init__.py').read_text() == '1.0.0'
assert not (tmp_path / 'fixture').exists()
@pytest.mark.parametrize('disabled, done, enabled', [
(['0.9.0', '1.0.0'], (True, 'enable', None), '0.9.0'),
(['1.0.0'], (False, 'enable', 'Specified inactive node path not exists: <folder>'), None),
], ids=['an older version is left', 'no version is left'])
def test_install_without_version_when_the_newest_disabled_version_was_removed_after_the_scan(
core, monkeypatch, tmp_path, disabled, done, enabled,
):
_, download = mock_registry_query_and_download(core, monkeypatch)
manager = disabled_fixture(core.UnifiedManager(), tmp_path, disabled)
gone = tmp_path / '.disabled/fixture@1_0_0'
for file in gone.iterdir():
file.unlink()
gone.rmdir()
result = asyncio.run(manager.install_by_id('fixture', instant_execution=True))
restored = tmp_path / 'fixture/__init__.py'
assert (result.result, result.action, result.msg and result.msg.replace(str(gone), '<folder>')) == done
assert (restored.read_text() if restored.exists() else None) == enabled
assert download.call_count == 0
@pytest.mark.parametrize('core', ['legacy'], indirect=True)
def test_reinstall_stops_when_the_installed_folder_cannot_be_moved_aside(core, monkeypatch, tmp_path):
get = Mock(return_value=api_response('NodeVersionStatusActive'))
+58
View File
@@ -0,0 +1,58 @@
"""Form factor the CNR client reports to the registry."""
import asyncio
import pytest
from _install_flags_testutil import import_context
@pytest.fixture
def cnr_utils():
import_context()
from comfyui_manager.common import cnr_utils
return cnr_utils
@pytest.mark.parametrize(
('system', 'desktop', 'expected'),
[
('Windows', True, 'desktop-win'),
('Darwin', True, 'desktop-mac'),
('Linux', True, 'desktop-linux'),
('FreeBSD', True, 'other'),
('Windows', False, 'git-windows'),
('Darwin', False, 'git-mac'),
('Linux', False, 'git-linux'),
('FreeBSD', False, 'other'),
],
)
def test_form_factor(cnr_utils, monkeypatch, system, desktop, expected):
monkeypatch.setattr(cnr_utils.platform, 'system', lambda: system)
if desktop:
monkeypatch.setenv('__COMFYUI_DESKTOP_VERSION__', '1.0.0')
else:
monkeypatch.delenv('__COMFYUI_DESKTOP_VERSION__', raising=False)
assert cnr_utils.get_form_factor() == expected
def test_the_registry_request_carries_the_form_factor(cnr_utils, monkeypatch):
from comfyui_manager.glob import manager_core
asked = []
async def get_data_with_cache(uri, **kwargs):
asked.append(uri)
return {'nodes': [], 'totalPages': 1}
monkeypatch.setattr(cnr_utils.manager_util, 'get_data_with_cache', get_data_with_cache)
monkeypatch.setattr(cnr_utils.manager_util, 'save_to_cache', lambda uri, data: None)
monkeypatch.setattr(manager_core, 'get_config', lambda: {})
monkeypatch.setattr(cnr_utils.time, 'sleep', lambda seconds: None)
monkeypatch.setattr(cnr_utils.platform, 'system', lambda: 'Linux')
monkeypatch.setenv('__COMFYUI_DESKTOP_VERSION__', '1.0.0')
asyncio.run(cnr_utils._get_cnr_data(cache_mode=False))
assert [uri.partition('&form_factor=')[2] for uri in asked] == ['desktop-linux']
+29
View File
@@ -0,0 +1,29 @@
import ast
import os
import subprocess
import sys
import pytest
from legacy_html_testutil import PACKAGE
@pytest.mark.parametrize('use_pygit2, line', [
('', '[ComfyUI-Manager] Using GitPython backend'),
('1', '[ComfyUI-Manager] Using pygit2 backend (CM_USE_PYGIT2=1)'),
])
def test_git_backend_is_not_told_by_the_import_so_that_cm_cli_writes_only_the_output_of_its_command(use_pygit2, line):
done = subprocess.run([sys.executable, '-c', 'import git_compat; print(git_compat.BACKEND_LINE)'], capture_output=True, text=True,
cwd=PACKAGE / 'common', env={**os.environ, 'CM_USE_PYGIT2': use_pygit2})
assert done.returncode == 0, done.stderr
assert done.stdout.splitlines() == [line]
assert line not in done.stderr
def test_git_backend_is_told_by_the_server_at_its_start():
body = ast.parse((PACKAGE / 'prestartup_script.py').read_text(encoding='utf-8')).body
told = [number for number, statement in enumerate(body) if ast.unparse(statement) == 'print(git_compat.BACKEND_LINE, file=sys.stderr)']
imported = [number for number, statement in enumerate(body) if ast.unparse(statement) == 'from .common import git_compat']
assert len(told) == 1 and told[0] == imported[0] + 1
+1 -1
View File
@@ -182,7 +182,7 @@ def test_manager_search_matches_visible_text(page, filename, column, value, quer
const element = document.createElement('div');
element.innerHTML = '<div id="tested-grid" class="cn-manager-grid cmm-manager-grid" style="width:800px;height:300px"></div>';
document.body.append(element);
window.manager = {element, keywords: query, showStatus() {}, handleFlyoverHover() {}, createFlyover: () => ({}), hasAlternatives: () => false,
window.manager = {element, keywords: query, showStatus() {}, handleFlyoverHover() {}, createFlyover: () => ({}),
calculateSortScore: new Function(`return ${score}`)()};
initGrid.call(manager);
manager.grid.setData({columns: [{id: column, name: column}], rows: [{[column]: value}]});
+42
View File
@@ -0,0 +1,42 @@
import asyncio
import sys
import traceback
from types import SimpleNamespace
from typing import Optional
from unittest.mock import Mock
import pytest
import typer
from typing_extensions import Annotated, List
from legacy_html_testutil import ROOT, load_functions
class NodeInstallError(Exception):
pass
def install(node, exit_on_fail):
async def install_by_id(*args, **kwargs):
return SimpleNamespace(action='install', result=False, target=None, msg=f"Node '{node}@unknown' not found")
unified_manager = SimpleNamespace(resolve_node_spec=lambda spec: (spec, 'unknown', False), install_by_id=install_by_id, cnr_map={})
load_functions(ROOT / 'cm_cli/__main__.py', {'install', 'install_node', 'for_each_nodes', '_finalize_resolve'}, {
'app': SimpleNamespace(command=lambda *args, **kwargs: lambda function: function),
'typer': typer, 'Annotated': Annotated, 'List': List, 'Optional': Optional,
'asyncio': asyncio, 'sys': sys, 'traceback': traceback, 'print': lambda *objects, style=None: print(*objects), 'NodeInstallError': NodeInstallError,
'cmd_ctx': Mock(no_deps=False), 'comfy_path': '', 'context': Mock(), 'manager_util': Mock(),
'core': SimpleNamespace(is_valid_url=lambda spec: False), 'unified_manager': unified_manager,
})['install']([node], None, None, False, False, None, exit_on_fail)
def test_install_that_fails_ends_with_1_with_exit_on_fail(capsys):
with pytest.raises(SystemExit) as exit:
install('no-such-nodepack', exit_on_fail=True)
assert exit.value.code == 1
assert "An error occurred while installing 'no-such-nodepack'" in capsys.readouterr().out
def test_install_that_fails_goes_on_without_exit_on_fail():
install('no-such-nodepack', exit_on_fail=False)
+9
View File
@@ -0,0 +1,9 @@
from test_invalid_installation import core, custom_nodes, pack # noqa: F401 -- fixtures
def test_a_registry_nodepack_is_listed_with_its_id_as_its_pyproject_spells_it(core, custom_nodes): # noqa: F811
pack(custom_nodes / 'ComfyUI_SigmoidOffsetScheduler', 'ComfyUI_SigmoidOffsetScheduler', version='1.1.1', tracking=True)
assert core.get_installed_node_packs() == {
'ComfyUI_SigmoidOffsetScheduler': {'ver': '1.1.1', 'cnr_id': 'ComfyUI_SigmoidOffsetScheduler', 'aux_id': None,
'enabled': True}}
+150 -5
View File
@@ -17,7 +17,6 @@ from unittest.mock import Mock
import pytest
import rich.console
import rich.markup
from _install_flags_testutil import import_reader
from js_lift import NODE, JsSource, line_containing, parse, run_node, slice_braced
@@ -118,6 +117,24 @@ def registry_api(monkeypatch, core, status='NodeVersionStatusActive', download=a
monkeypatch.setattr(core.manager_downloader, 'download_url', Mock(side_effect=download))
def registry_with_every_version(monkeypatch, core):
def version(url, **kwargs):
asked = url.split('version=')[1]
return SimpleNamespace(status_code=200, json=lambda: {
'id': 'version-id', 'node_id': 'comfyui-foo', 'version': asked, 'status': 'NodeVersionStatusActive',
'downloadUrl': f'https://example.invalid/comfyui-foo-{asked}.zip'})
def archive(url, directory, name):
asked = url.rsplit('-', 1)[1][:-len('.zip')]
with zipfile.ZipFile(Path(directory) / name, 'w') as archive:
archive.writestr('__init__.py', 'NODE_CLASS_MAPPINGS = {}\n')
archive.writestr('pyproject.toml', f'[project]\nname = "comfyui-foo"\nversion = "{asked}"\n')
monkeypatch.setattr(core.cnr_utils.requests, 'get', version)
monkeypatch.setattr(core.manager_funcs, 'is_flagged_install_allowed', lambda node_id: False)
monkeypatch.setattr(core.manager_downloader, 'download_url', archive)
def files(path):
return {x.relative_to(path).as_posix(): x.read_text() for x in sorted(Path(path).rglob('*')) if x.is_file()}
@@ -232,6 +249,31 @@ def test_uninstall_by_id_after_the_registry_list_has_loaded_removes_what_the_sca
assert listing(custom_nodes) == []
BAZ_LATEST = next(item['latest_version']['version'] for item in REGISTRY if item['id'] == 'comfyui-baz')
@pytest.mark.parametrize('installed, state, active_version, offered', [
('1.0.0', 'enabled', '1.0.0', 'true'),
(BAZ_LATEST, 'enabled', BAZ_LATEST, 'false'),
('nightly', 'enabled', 'nightly', 'false'),
('disabled 1.0.0', 'disabled', None, 'false'),
(None, 'not-installed', None, 'false'),
])
def test_a_pack_that_only_the_registry_lists_offers_update_for_an_older_version_alone(core, custom_nodes, installed,
state, active_version, offered):
if installed == 'nightly':
pack(custom_nodes / 'comfyui-baz', git_url='https://github.com/example/comfyui-baz')
elif installed == 'disabled 1.0.0':
pack(custom_nodes / '.disabled/comfyui-baz@1_0_0', 'comfyui-baz', version='1.0.0', tracking=True)
elif installed is not None:
pack(custom_nodes / 'comfyui-baz', 'comfyui-baz', version=installed, tracking=True)
reload(core)
row = asyncio.run(core.get_unified_total_nodes(core.DEFAULT_CHANNEL, 'cache'))['comfyui-baz']
assert (row['state'], row.get('active_version'), row.get('update-state')) == (state, active_version, offered)
@pytest.mark.parametrize('valid, row, state', [
('comfyui-foo', 'comfyui-foo', 'enabled'),
('.disabled/comfyui-foo@1_0_1', 'comfyui-foo', 'disabled'),
@@ -1440,11 +1482,11 @@ class NodeInstallError(Exception):
def cm_cli_reinstall_node(core, out=None):
console = rich.console.Console(file=out if out is not None else io.StringIO(), width=1000, color_system=None)
out = out if out is not None else io.StringIO()
return cm_cli_function('reinstall_node', {
'asyncio': asyncio, 'os': os, 'core': core, 'unified_manager': core.unified_manager, 'print': console.print,
'escape': rich.markup.escape, 'cmd_ctx': SimpleNamespace(channel='default', mode='cache', no_deps=False),
'NodeInstallError': NodeInstallError})
'asyncio': asyncio, 'os': os, 'core': core, 'unified_manager': core.unified_manager,
'print': lambda *objects, **kwargs: core.print(*objects, file=out, **kwargs),
'cmd_ctx': SimpleNamespace(channel='default', mode='cache', no_deps=False), 'NodeInstallError': NodeInstallError})
@pytest.mark.parametrize('core', ['legacy'], indirect=True)
@@ -1486,6 +1528,109 @@ def test_cm_cli_reinstall_archives_what_sits_at_the_install_path_under_another_k
assert core.get_installed_node_packs()['comfyui-foo']['cnr_id'] == 'comfyui-foo'
INSTALLED_BEFORE_A_REINSTALL = {
'a_version': lambda nodes: pack(nodes / 'comfyui-foo', 'comfyui-foo', version='1.0.0', tracking=True),
'the_nightly_clone': lambda nodes: pack(nodes / 'comfyui-foo', git_url=FOO_URL),
'a_disabled_version': lambda nodes: pack(nodes / '.disabled/comfyui-foo@1_0_0', 'comfyui-foo', version='1.0.0', tracking=True),
'a_disabled_nightly_clone': lambda nodes: pack(nodes / '.disabled/comfyui-foo@nightly', git_url=FOO_URL),
'a_version_and_a_disabled_nightly_clone': lambda nodes: (
pack(nodes / 'comfyui-foo', 'comfyui-foo', version='1.0.0', tracking=True),
pack(nodes / '.disabled/comfyui-foo@nightly', git_url=FOO_URL)),
'nothing': lambda nodes: None,
}
def cm_cli_reinstall(core, custom_nodes, monkeypatch, installed, spec):
INSTALLED_BEFORE_A_REINSTALL[installed](custom_nodes)
registry_with_every_version(monkeypatch, core)
git_clone_stand_in(monkeypatch, core)
reload(core)
out = io.StringIO()
cm_cli_reinstall_node(core, out)(spec)
assert listing(custom_nodes) == ['comfyui-foo']
line = out.getvalue().split()
assert line[:2] == ['[REINSTALLED]', 'comfyui-foo']
left = files(custom_nodes / 'comfyui-foo')
return line[2], 'the clone' if '.git/config' in left else left['pyproject.toml'].split('version = ')[1].strip().strip('"')
@pytest.mark.parametrize('core', ['legacy'], indirect=True)
@pytest.mark.parametrize('installed', ['a_version', 'a_disabled_version', 'a_version_and_a_disabled_nightly_clone'])
def test_cm_cli_reinstall_without_a_version_installs_the_version_that_is_installed(core, custom_nodes, monkeypatch,
installed):
assert cm_cli_reinstall(core, custom_nodes, monkeypatch, installed, 'comfyui-foo') == ('[1.0.0]', '1.0.0')
@pytest.mark.parametrize('core', ['legacy'], indirect=True)
@pytest.mark.parametrize('listed', [True, False], ids=['in-the-node-list', 'only-in-the-registry'])
@pytest.mark.parametrize('installed', ['the_nightly_clone', 'a_disabled_nightly_clone'])
def test_cm_cli_reinstall_without_a_version_clones_the_nightly_that_is_installed(core, custom_nodes, monkeypatch,
installed, listed):
if not listed:
monkeypatch.setitem(globals(), 'NODE_LIST', [x for x in NODE_LIST if x['reference'] != FOO_URL])
assert cm_cli_reinstall(core, custom_nodes, monkeypatch, installed, 'comfyui-foo') == ('[NIGHTLY]', 'the clone')
@pytest.mark.parametrize('core', ['legacy'], indirect=True)
def test_cm_cli_reinstall_without_a_version_keeps_a_version_that_the_registry_no_longer_has(core, custom_nodes,
monkeypatch):
pack(custom_nodes / 'comfyui-foo', 'comfyui-foo', version='1.0.0', tracking=True)
before = files(custom_nodes)
registry_with_every_version(monkeypatch, core)
every_version = core.cnr_utils.requests.get
monkeypatch.setattr(core.cnr_utils.requests, 'get', lambda url, **kwargs: (
SimpleNamespace(status_code=404) if url.endswith('version=1.0.0') else every_version(url, **kwargs)))
reload(core)
out = io.StringIO()
with pytest.raises(NodeInstallError):
cm_cli_reinstall_node(core, out)('comfyui-foo')
assert 'not available node: comfyui-foo@1.0.0' in out.getvalue()
assert files(custom_nodes) == before
@pytest.mark.parametrize('core', ['legacy'], indirect=True)
@pytest.mark.parametrize('installed, spec, version', [
('nothing', 'comfyui-foo', '1.0.1'),
('a_version', 'comfyui-foo@latest', '1.0.1'),
('the_nightly_clone', 'comfyui-foo@latest', '1.0.1'),
('a_version', 'comfyui-foo@1.0.1', '1.0.1'),
('the_nightly_clone', 'comfyui-foo@1.0.0', '1.0.0'),
], ids=['not-installed', 'latest-over-a-version', 'latest-over-the-nightly-clone', 'another-version', 'a-version-over-the-nightly-clone'])
def test_cm_cli_reinstall_installs_the_version_it_is_given_and_the_latest_of_a_nodepack_that_is_not_installed(
core, custom_nodes, monkeypatch, installed, spec, version):
assert cm_cli_reinstall(core, custom_nodes, monkeypatch, installed, spec) == (f'[{version}]', version)
@pytest.mark.parametrize('core', ['legacy'], indirect=True)
@pytest.mark.parametrize('folder', ['foo-fork', '.disabled/foo-fork'])
def test_cm_cli_reinstall_without_a_version_archives_a_clone_of_a_fork_and_installs_the_latest(core, custom_nodes,
monkeypatch, folder):
fork = pack(custom_nodes / folder, git_url='https://github.com/someone/comfyui-foo')
before = files(fork)
registry_with_every_version(monkeypatch, core)
git_clone_stand_in(monkeypatch, core)
reload(core)
out = io.StringIO()
cm_cli_reinstall_node(core, out)('comfyui-foo')
assert out.getvalue().split()[:3] == ['[REINSTALLED]', 'comfyui-foo', '[1.0.1]']
assert files(custom_nodes / 'comfyui-foo')['pyproject.toml'] == '[project]\nname = "comfyui-foo"\nversion = "1.0.1"\n'
[archived] = (custom_nodes / '.disabled/.archived').glob('*/foo-fork')
assert files(archived) == before
@pytest.mark.parametrize('core', ['legacy'], indirect=True)
@pytest.mark.parametrize('spec', ['comfyui-foo@nightly', FOO_URL], ids=['at-nightly', 'by-url'])
def test_cm_cli_reinstall_at_nightly_or_by_a_registered_url_clones_over_an_installed_version(core, custom_nodes,
monkeypatch, spec):
assert cm_cli_reinstall(core, custom_nodes, monkeypatch, 'a_version', spec) == ('[NIGHTLY]', 'the clone')
@pytest.mark.parametrize('core', ['legacy'], indirect=True)
def test_cm_cli_reinstall_by_a_registered_url_that_the_node_list_lacks_installs_the_nightly(core, custom_nodes,
monkeypatch):
+60
View File
@@ -286,6 +286,66 @@ def test_p2_unknown_pip_block_denies_404_even_at_weak(ms, gate, monkeypatch):
assert resp.status == 404
FOO_URL = "https://github.com/example/ComfyUI-Foo"
BAR_URL = "https://github.com/example/ComfyUI-Bar"
@pytest.fixture
def lists(ms, monkeypatch):
bar = {"id": "comfyui-bar", "files": [BAR_URL], "repository": BAR_URL}
fork = {"id": "comfyui-bar", "files": [BAR_URL + "-fork"], "repository": BAR_URL + "-fork"}
async def node_list(*args, **kwargs):
return {"custom_nodes": [bar]}
async def custom_nodes(channel, mode):
return {"comfyui-bar": fork if channel == "forks" else bar}
monkeypatch.setattr(ms.core, "get_data_by_mode", node_list)
monkeypatch.setattr(ms.core.unified_manager, "get_custom_nodes", custom_nodes)
monkeypatch.setattr(ms.core.unified_manager, "cnr_map", {
"comfyui-foo": {"id": "comfyui-foo", "repository": FOO_URL},
"comfyui-bar": {"id": "comfyui-bar", "repository": BAR_URL}})
monkeypatch.setattr(ms.args, "listen", "127.0.0.1")
monkeypatch.setattr(ms, "temp_queue_batch", [])
def nightly_install(ms, node_id, repository, channel="default"):
resp = _run(ms._queue_node_install({
"id": node_id, "version": "1.0.1", "selected_version": "nightly", "repository": repository, "pip": [],
"ui_id": "u", "channel": channel, "mode": "cache"}, "install"))
return resp.status, [item[1] for _, item in ms.temp_queue_batch]
@pytest.mark.parametrize("repository", [FOO_URL, BAR_URL], ids=["its-repository", "the-repository-of-another-nodepack"])
def test_the_nightly_of_a_nodepack_that_the_node_list_lacks_needs_allow_git_url_install(ms, gate, lists, repository):
gate("normal", is_local_mode=True)
assert nightly_install(ms, "comfyui-foo", repository) == (404, [])
def test_the_nightly_of_a_nodepack_that_the_node_list_lacks_is_queued_with_allow_git_url_install(ms, gate, lists,
monkeypatch):
gate("normal", is_local_mode=True)
config = ms.core.get_config()
monkeypatch.setattr(ms.core, "get_config", lambda: {**config, "allow_git_url_install": True})
assert nightly_install(ms, "comfyui-foo", FOO_URL) == (200, ["comfyui-foo@nightly"])
def test_the_nightly_of_a_nodepack_of_the_node_list_is_queued(ms, gate, lists):
gate("normal", is_local_mode=True)
assert nightly_install(ms, "comfyui-bar", BAR_URL) == (200, ["comfyui-bar@nightly"])
def test_the_nightly_is_looked_up_in_the_node_list_of_the_channel_of_the_request(ms, gate, lists):
gate("normal", is_local_mode=True)
assert nightly_install(ms, "comfyui-bar", BAR_URL, channel="forks") == (404, [])
def test_the_nightly_of_a_nodepack_that_no_list_has_is_not_queued(ms, gate, lists):
gate("normal", is_local_mode=True)
assert nightly_install(ms, "comfyui-baz", BAR_URL) == (404, [])
def test_p3_comfyui_switch_version_denies_high_plus_403(ms, gate):
"""P3 high+ handler: comfyui_switch_version denies with 403 at sl=normal
(high+ requires normal- or lower on loopback)."""
+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)
+30
View File
@@ -0,0 +1,30 @@
import pytest
from _install_flags_testutil import import_reader
VARIABLE = "COMFYUI_MANAGER_SKIP_MANAGER_REQUIREMENTS"
def pip_installs(core, comfyui_path, monkeypatch):
(comfyui_path / "manager_requirements.txt").write_text("comfyui-manager==4.2.2\n")
core = import_reader(core)
commands = []
monkeypatch.setattr(core.manager_util, "make_pip_cmd", lambda args: ["pip", *args])
monkeypatch.setattr(core.subprocess, "run", commands.append)
core.install_manager_requirements(str(comfyui_path))
return commands
@pytest.mark.parametrize("core", ["glob", "legacy"])
def test_pin_of_comfyui_is_installed(core, monkeypatch, tmp_path):
monkeypatch.delenv(VARIABLE, raising=False)
assert pip_installs(core, tmp_path, monkeypatch) == [["pip", "install", "comfyui-manager==4.2.2"]]
@pytest.mark.parametrize("core", ["glob", "legacy"])
@pytest.mark.parametrize("value", ["1", "true", "YES"])
def test_variable_skips_the_pin(core, value, monkeypatch, tmp_path):
monkeypatch.setenv(VARIABLE, value)
assert pip_installs(core, tmp_path, monkeypatch) == []
+57
View File
@@ -0,0 +1,57 @@
import concurrent.futures
import os
from types import SimpleNamespace
import pytest
from legacy_html_testutil import PACKAGE, load_functions
KEYS = ("checkpoints", "controlnet")
CORES = {"legacy": PACKAGE / "legacy/manager_server.py", "glob": PACKAGE / "glob/utils/model_utils.py"}
def installed(tmp_path, core, 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)
namespace = load_functions(CORES[core], {"check_model_installed"},
{"os": os, "concurrent": concurrent, "folder_paths": folder_paths,
"model_dir_name_map": {}, "MODEL_DIR_NAMES": KEYS})
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")
@pytest.mark.parametrize("core", CORES)
def test_model_in_a_subfolder_of_an_extra_model_path_is_installed(tmp_path, core):
assert installed(tmp_path, core, "checkpoints/SD1.5", "extra/checkpoints/SD1.5/model.safetensors") == "True"
@pytest.mark.parametrize("core", CORES)
@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, core, save_path, file, expected):
assert installed(tmp_path, core, save_path, file) == expected
+100
View File
@@ -0,0 +1,100 @@
import pytest
from test_workflow_nodepack_lookup import EXTENSION, browser, page # noqa: F401 -- fixture
def model(name, model_type, base, save_path, filename, installed):
return {"name": name, "type": model_type, "base": base, "save_path": save_path, "description": name,
"reference": "https://example.invalid/" + filename, "filename": filename,
"url": "https://example.invalid/" + filename, "size": "4.71MB", "installed": installed}
MODELS = [
model("FLUX.1 VAE model", "VAE", "FLUX.1", "vae/FLUX1", "ae.safetensors", "False"),
model("TAEF1 Decoder", "TAESD", "FLUX.1", "vae_approx", "taef1_decoder.pth", "True"),
model("TAESD Decoder", "TAESD", "SD1.x", "vae_approx", "taesd_decoder.pth", "False"),
model("RealESRGAN x2", "upscale", "upscale", "default", "RealESRGAN_x2.pth", "False"),
model("FLUX.1 dev Q4_0", "unet", "FLUX.1", "diffusion_models/FLUX1", "flux1-dev-Q4_0.gguf", "False"),
model("v1-5-pruned-emaonly", "checkpoint", "SD1.5", "checkpoints/SD1.5", "v1-5-pruned-emaonly.safetensors", "True"),
]
def node(node_type, *values):
return {"type": node_type, "widgets_values": list(values)}
def workflow(*loaders):
return [*loaders,
node("UNETLoader", "z_image_turbo_bf16.safetensors", "default"),
node("KSampler", 42, "fixed", 8, 1, "res_multistep", "simple", 1),
node("CLIPTextEncode", "a cute anime girl with gigantic fennec ears and a big fluffy fox tail"),
{"type": "VHS_VideoCombine", "widgets_values": {"frame_rate": 8, "filename_prefix": "AnimateDiff"}},
{"type": "Reroute"}]
def choose(page, change): # noqa: F811
page.evaluate("() => { window.updated = false; manager.grid.onNextUpdated(() => { window.updated = true; }); }")
change()
page.wait_for_function("window.updated")
def open_models(page, nodes, keywords="", **choices): # noqa: F811
page.evaluate("""async ({module, server, nodes}) => {
window.server = server;
const {app} = await import('/scripts/app.js');
app.graph._nodes = nodes;
const {setManagerInstance} = await import(new URL('common.js', module).href);
setManagerInstance({datasrc_combo: {value: 'cache'}});
const {ModelManager} = await import(module);
window.manager = new ModelManager(app, null);
manager.show();
}""", {"module": EXTENSION + "model-manager.js", "server": {"/v2/externalmodel/getlist": {"models": MODELS}},
"nodes": nodes})
page.wait_for_function("/^[\\d,]+ external models$/.test(document.querySelector('.cmm-manager-status').textContent)")
if keywords:
choose(page, lambda: page.fill(".cmm-manager-keywords", keywords))
for name, value in choices.items():
choose(page, lambda: page.select_option(".cmm-manager-" + name, value))
return page.evaluate("""() => ({
rows: [...document.querySelectorAll('.cmm-manager-grid .tg-body .cmm-node-name')].map(cell => cell.innerText.trim()),
status: document.querySelector('.cmm-manager-status').textContent,
})""")
@pytest.mark.parametrize("value, rows", [
("ae.safetensors", ["FLUX.1 VAE model"]),
("FLUX1/ae.safetensors", ["FLUX.1 VAE model"]),
("FLUX1\\ae.safetensors", ["FLUX.1 VAE model"]),
("flux1-dev-Q4_0.gguf", ["FLUX.1 dev Q4_0"]),
("qwen_3_4b.safetensors", []),
], ids=["file", "file in a folder", "file in a Windows folder", "gguf file", "file not in the list"])
def test_in_workflow_lists_the_models_whose_file_the_workflow_loads(page, value, rows): # noqa: F811
shown = open_models(page, workflow(node("VAELoader", value)), filter="in_workflow")
assert shown == {"rows": rows, "status": f"{len(rows)} external models"}
assert page.errors == []
def test_in_workflow_keeps_the_marks_of_a_search(page): # noqa: F811
shown = open_models(page, workflow(node("VAELoader", "ae.safetensors")), keywords="flux", filter="in_workflow")
assert shown == {"rows": ["FLUX.1 VAE model"], "status": "1 external models"}
page.wait_for_function("document.querySelector('.cmm-manager-grid .tg-body .cmm-node-name mark')")
assert page.locator(".cmm-manager-grid .tg-body .cmm-node-name mark").all_text_contents() == ["FLUX"]
assert page.errors == []
@pytest.mark.parametrize("keywords, choices, rows", [
("", {"type": "TAESD", "base": "FLUX.1"}, ["TAEF1 Decoder"]),
("", {"filter": "installed", "base": "FLUX.1"}, ["TAEF1 Decoder"]),
("", {"filter": "not_installed", "type": "TAESD"}, ["TAESD Decoder"]),
("", {"filter": "in_workflow", "type": "checkpoint"}, ["v1-5-pruned-emaonly"]),
("flux", {"filter": "not_installed", "type": "unet"}, ["FLUX.1 dev Q4_0"]),
], ids=["All", "Installed", "Not Installed", "In Workflow", "Not Installed and a search"])
def test_a_filter_choice_narrows_the_list_together_with_type_base_and_search(page, keywords, choices, rows): # noqa: F811
nodes = workflow(node("VAELoader", "ae.safetensors"), node("CheckpointLoaderSimple", "SD1.5/v1-5-pruned-emaonly.safetensors"))
shown = open_models(page, nodes, keywords, **choices)
assert shown == {"rows": rows, "status": f"{len(rows)} external models"}
assert page.errors == []
+76
View File
@@ -0,0 +1,76 @@
import json
import os
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 / "comfyui_manager" / "js")))
MANAGER = "custom-nodes-manager.js"
def nodes_column_and_list_text(states, mappings):
source = JS.text(MANAGER)
nodes_column = slice_object_entry(source, 'id: "nodes"')
show_nodes = source[source.index("\tshowNodes(d) {"):source.index("\tasync loadNodes(node_packs) {")]
rows = {key: {"key": key, "title": key, "hash": key, "state": state} for key, state in states.items()}
script = "\n".join([
JS.lift_declaration("common.js", "export function sanitizeHTML("),
"const icons = {conflicts: '<svg></svg>'};",
"const manager_instance = {datasrc_combo: {value: 'cache'}};",
"const fetchData = async () => ({data: %s});" % json.dumps(mappings),
"const text = (html) => html.replace(/<[^>]+>/g, ' ').replace(/\\s+/g, ' ').trim();",
"const column = {%s};" % nodes_column,
"const manager = {showStatus() {}, flyover: {show(title, body) { manager.list = body; }},",
slice_braced(source, "\tasync loadNodes(node_packs) ") + ",",
show_nodes + "};",
"const rows = %s;" % json.dumps(rows),
"await manager.loadNodes(rows);",
"console.log(JSON.stringify(Object.fromEntries(Object.entries(rows).map(([key, row]) => {",
" manager.list = '';",
" manager.showNodes({rowItem: row});",
" return [key, [text(column.formatter(row.nodes, row, column)), text(manager.list)]];",
"}))));",
])
return {key: tuple(value) for key, value in run_node(script).items()}
SHARED = {"A": [["X"], {}], "B": [["X"], {}]}
CASES = {
"an enabled pack and a pack that is not installed": (
{"A": "enabled", "B": "not-installed"}, SHARED,
{"A": ("1 node", "1 X"),
"B": ("1 node 1 potential conflict", "1 X Potential conflict if installed/enabled with A")}),
"an enabled pack and a disabled pack": (
{"A": "enabled", "B": "disabled"}, SHARED,
{"A": ("1 node", "1 X"),
"B": ("1 node 1 potential conflict", "1 X Potential conflict if installed/enabled with A")}),
"two enabled packs": (
{"A": "enabled", "B": "enabled"}, SHARED,
{"A": ("1 node 1 conflict", "1 X Conflict with enabled packs B"),
"B": ("1 node 1 conflict", "1 X Conflict with enabled packs A")}),
"a disabled pack and a pack that is not installed": (
{"A": "disabled", "B": "not-installed"}, SHARED,
{"A": ("1 node", "1 X"), "B": ("1 node", "1 X")}),
"a disabled pack beside two enabled packs, one of which lists a node twice": (
{"A": "enabled", "B": "enabled", "C": "disabled"},
{"A": [["Shared", "Shared", "Own"], {}], "B": [["Shared"], {}], "C": [["Shared"], {}]},
{"A": ("2 nodes 1 conflict", "1 Shared Conflict with enabled packs B 2 Own"),
"B": ("1 node 1 conflict", "1 Shared Conflict with enabled packs A"),
"C": ("1 node 1 potential conflict", "1 Shared Potential conflict if installed/enabled with A , B")}),
"an enabled pack whose node only a pack without a row lists": (
{"A": "enabled"}, SHARED,
{"A": ("1 node", "1 X")}),
"packs found by the end of their URL and by their title": (
{"A": "enabled", "B": "disabled"},
{"https://example.invalid/A": [["X"], {}], "other": [["X"], {"title_aux": "B"}]},
{"A": ("1 node", "1 X"),
"B": ("1 node 1 potential conflict", "1 X Potential conflict if installed/enabled with A")}),
}
@pytest.mark.skipif(NODE is None, reason="node is required to execute the lifted production JS")
@pytest.mark.parametrize("states, mappings, expected", CASES.values(), ids=CASES.keys())
def test_only_an_enabled_pack_is_a_conflict_and_any_other_pack_sees_a_potential_one(states, mappings, expected):
assert nodes_column_and_list_text(states, mappings) == expected
+264
View File
@@ -0,0 +1,264 @@
import ast
import asyncio
import io
import logging
import shutil
import traceback
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import Mock
import pytest
from legacy_html_testutil import PACKAGE
from test_invalid_installation import (BAR_URL, FOO_URL, NodeInstallError, cm_cli_function, core, custom_nodes, # noqa: F401
data_models, pack, registry_api, reload, run_glob_worker)
UNKNOWN, VERSION, NIGHTLY = {'git_url': BAR_URL}, {'project_name': 'comfyui-foo', 'tracking': True}, {'project_name': 'comfyui-foo', 'git_url': FOO_URL}
KINDS = pytest.mark.parametrize('name, made_with, disabled, version', [
('ComfyUI-Bar', UNKNOWN, '.disabled/ComfyUI-Bar', 'unknown'),
('comfyui-foo', VERSION, '.disabled/comfyui-foo@1_0_1', '1.0.1'),
('comfyui-foo', NIGHTLY, '.disabled/comfyui-foo@nightly', 'nightly'),
], ids=['git_clone_that_no_list_knows', 'registry_version', 'nightly_clone'])
def folders(path):
return sorted(folder.relative_to(path).as_posix() for folder in path.rglob('*')
if (folder.is_dir() or folder.is_symlink()) and folder.name != '.git')
def broken_link(path):
path.parent.mkdir(exist_ok=True)
path.symlink_to(path.parent / 'gone')
def stand_ins(module, monkeypatch):
def clone(url, folder, **options):
Path(folder).mkdir()
return module.ManagedResult('install-git')
registry_api(monkeypatch, module)
monkeypatch.setattr(module.manager_downloader, 'basic_download_url', module.manager_downloader.download_url)
manager = reload(module)
manager.repo_install = Mock(side_effect=clone)
return manager
def install(module, path, version):
manager = module.unified_manager
result = asyncio.run(manager.install_by_id('comfyui-foo', version, module.DEFAULT_CHANNEL, 'cache', instant_execution=True))
return [result.result, module.manager_downloader.download_url.call_count + manager.repo_install.call_count, folders(path)]
def legacy_task(name, **names):
path = PACKAGE / 'legacy/manager_server.py'
found = [node for node in ast.walk(ast.parse(path.read_text(encoding='utf-8')))
if isinstance(node, ast.AsyncFunctionDef) and node.name == name]
exec(compile(ast.Module(found, []), str(path), 'exec'), names)
return names[name]
@KINDS
@pytest.mark.parametrize('taken_by', ['a_disabled_copy', 'a_broken_link'])
def test_disable_fails_when_its_destination_is_taken(core, custom_nodes, taken_by, name, made_with, disabled, version): # noqa: F811
pack(custom_nodes / name, **made_with)
if taken_by == 'a_disabled_copy':
pack(custom_nodes / disabled, **made_with)
else:
broken_link(custom_nodes / disabled)
manager = reload(core)
assert [manager.unified_disable(name, version == 'unknown').result, folders(custom_nodes)] == [False, ['.disabled', disabled, name]]
@KINDS
@pytest.mark.parametrize('taken_by', ['a_folder_made_since_the_last_scan', 'a_broken_link'])
def test_enable_fails_when_its_destination_is_taken(core, custom_nodes, taken_by, name, made_with, disabled, version): # noqa: F811
pack(custom_nodes / disabled, **made_with)
manager = reload(core)
if taken_by == 'a_folder_made_since_the_last_scan':
(custom_nodes / name).mkdir()
else:
broken_link(custom_nodes / name)
assert [manager.unified_enable(name, version).result, folders(custom_nodes)] == [False, ['.disabled', disabled, name]]
def test_git_clone_that_no_list_knows_is_not_enabled_over_the_enabled_version_of_its_name(core, custom_nodes): # noqa: F811
pack(custom_nodes / 'comfyui-foo', **VERSION)
pack(custom_nodes / '.disabled/comfyui-foo', git_url='https://github.com/someone/comfyui-foo')
manager = reload(core)
assert [manager.unified_enable('comfyui-foo', 'unknown').result, folders(custom_nodes)] == [
False, ['.disabled', '.disabled/comfyui-foo', 'comfyui-foo']]
@pytest.mark.parametrize('linked, taken', [
(False, lambda path: (path / 'comfyui-foo').mkdir()),
(False, lambda path: (path / 'comfyui-foo').symlink_to(path / 'foo')),
(True, lambda path: (path / 'comfyui-foo').symlink_to(path.parent / 'checkout')),
], ids=['by_another_folder', 'by_a_link_to_the_enabled_folder', 'by_a_second_link_to_the_folder_of_the_enabled_link'])
def test_enable_whose_folder_is_taken_leaves_the_enabled_version_enabled(core, custom_nodes, linked, taken): # noqa: F811
pack(custom_nodes.parent / 'checkout' if linked else custom_nodes / 'foo', **NIGHTLY)
if linked:
(custom_nodes / 'foo').symlink_to(custom_nodes.parent / 'checkout')
pack(custom_nodes / '.disabled/comfyui-foo@1_0_1', **VERSION)
manager = reload(core)
taken(custom_nodes)
assert [manager.unified_enable('comfyui-foo', '1.0.1').result, folders(custom_nodes)] == [
False, ['.disabled', '.disabled/comfyui-foo@1_0_1', 'comfyui-foo', 'foo']]
def test_enable_whose_folder_is_taken_fails_when_the_folder_of_the_enabled_version_is_gone(core, custom_nodes): # noqa: F811
pack(custom_nodes / 'foo', **NIGHTLY)
pack(custom_nodes / '.disabled/comfyui-foo@1_0_1', **VERSION)
manager = reload(core)
shutil.rmtree(custom_nodes / 'foo')
(custom_nodes / 'comfyui-foo').mkdir()
assert [manager.unified_enable('comfyui-foo', '1.0.1').result, folders(custom_nodes)] == [
False, ['.disabled', '.disabled/comfyui-foo@1_0_1', 'comfyui-foo']]
@pytest.mark.parametrize('folder', ['comfyui-foo', 'ComfyUI-Foo'], ids=['in_the_folder_of_its_id', 'in_a_folder_of_another_spelling'])
def test_version_takes_the_folder_of_the_enabled_nightly_clone(core, custom_nodes, folder): # noqa: F811
pack(custom_nodes / folder, **NIGHTLY)
pack(custom_nodes / '.disabled/comfyui-foo@1_0_1', **VERSION)
manager = reload(core)
assert [manager.unified_enable('comfyui-foo', '1.0.1').result, folders(custom_nodes)] == [
True, ['.disabled', '.disabled/comfyui-foo@nightly', 'comfyui-foo']]
@pytest.mark.parametrize('enabled, taken, disabled, made_with, act, refused', [
(NIGHTLY, '.disabled/comfyui-foo@nightly', '.disabled/comfyui-foo@1_0_1', VERSION,
lambda module, path: module.unified_manager.unified_enable('comfyui-foo', '1.0.1').result, False),
(VERSION, '.disabled/comfyui-foo@1_0_1', '.disabled/comfyui-foo@nightly', NIGHTLY,
lambda module, path: module.unified_manager.unified_enable('comfyui-foo', 'nightly').result, False),
(NIGHTLY, '.disabled/comfyui-foo@nightly', None, None, lambda module, path: install(module, path, '1.0.1')[:2], [False, 0]),
(VERSION, '.disabled/comfyui-foo@1_0_1', None, None, lambda module, path: install(module, path, 'nightly')[:2], [False, 0]),
], ids=['enable_of_a_version', 'enable_of_the_nightly_clone', 'install_of_a_version', 'install_of_the_nightly_clone'])
def test_nodepack_does_not_take_the_place_of_an_enabled_one_that_cannot_be_disabled(core, custom_nodes, monkeypatch, enabled, taken, # noqa: F811
disabled, made_with, act, refused):
for folder in ('ComfyUI-Foo', taken):
pack(custom_nodes / folder, **enabled)
if disabled is not None:
pack(custom_nodes / disabled, **made_with)
stand_ins(core, monkeypatch)
before = folders(custom_nodes)
assert [act(core, custom_nodes), folders(custom_nodes)] == [refused, before]
@pytest.mark.parametrize('enabled, disabled, made_with, act, done', [
(NIGHTLY, '.disabled/comfyui-foo@1_0_1', VERSION, lambda module, path: module.unified_manager.unified_enable('comfyui-foo', '1.0.1').result,
[True, ['.disabled', 'comfyui-foo']]),
(VERSION, '.disabled/comfyui-foo@nightly', NIGHTLY, lambda module, path: module.unified_manager.unified_enable('comfyui-foo', 'nightly').result,
[True, ['.disabled', 'comfyui-foo']]),
(NIGHTLY, None, None, lambda module, path: install(module, path, '1.0.1')[:2], [[True, 1], ['comfyui-foo']]),
(VERSION, None, None, lambda module, path: install(module, path, 'nightly')[:2], [[True, 1], ['comfyui-foo']]),
], ids=['enable_of_a_version', 'enable_of_the_nightly_clone', 'install_of_a_version', 'install_of_the_nightly_clone'])
def test_nodepack_takes_the_place_of_an_enabled_one_whose_folder_is_gone(core, custom_nodes, monkeypatch, enabled, disabled, # noqa: F811
made_with, act, done):
pack(custom_nodes / 'ComfyUI-Foo', **enabled)
if disabled is not None:
pack(custom_nodes / disabled, **made_with)
stand_ins(core, monkeypatch)
shutil.rmtree(custom_nodes / 'ComfyUI-Foo')
assert [act(core, custom_nodes), folders(custom_nodes)] == done
@pytest.mark.parametrize('enabled, disabled, version', [
(NIGHTLY, '.disabled/comfyui-foo@1_0_0', '1.0.1'),
(NIGHTLY, None, '1.0.1'),
(VERSION, None, 'nightly'),
], ids=['of_a_version_that_enables_a_disabled_one', 'of_a_version_that_is_downloaded', 'of_the_nightly_clone'])
def test_install_whose_folder_is_taken_leaves_the_enabled_one_enabled(core, custom_nodes, monkeypatch, enabled, disabled, # noqa: F811
version):
pack(custom_nodes / 'foo', **enabled)
if disabled is not None:
pack(custom_nodes / disabled, 'comfyui-foo', version='1.0.0', tracking=True)
stand_ins(core, monkeypatch)
(custom_nodes / 'comfyui-foo').mkdir()
before = folders(custom_nodes)
assert install(core, custom_nodes, version) == [False, 0, before]
def test_version_is_not_switched_when_the_disabled_one_cannot_be_enabled(core, custom_nodes, monkeypatch): # noqa: F811
pack(custom_nodes / 'comfyui-foo', git_url='https://github.com/someone/comfyui-foo')
pack(custom_nodes / '.disabled/comfyui-foo@1_0_0', 'comfyui-foo', version='1.0.0', tracking=True)
stand_ins(core, monkeypatch)
assert install(core, custom_nodes, '1.0.1') == [False, 0, ['.disabled', '.disabled/comfyui-foo@1_0_0', 'comfyui-foo']]
@pytest.mark.parametrize('core', ['glob'], indirect=True)
def test_the_v4_queue_tells_the_page_that_a_disable_failed_and_the_terminal_why(core, custom_nodes, monkeypatch, caplog): # noqa: F811
for folder in ('ComfyUI-Bar', '.disabled/ComfyUI-Bar'):
pack(custom_nodes / folder, **UNKNOWN)
reload(core)
task = data_models(monkeypatch).QueueTaskItem.model_validate({
'ui_id': 'ui', 'client_id': 'client', 'kind': 'disable', 'params': {'node_name': 'ComfyUI-Bar', 'is_unknown': True}})
assert [run_glob_worker(monkeypatch, core, task), folders(custom_nodes)] == [
[('disable', "Failed to disable: 'ComfyUI-Bar'", 'error')], ['.disabled', '.disabled/ComfyUI-Bar', 'ComfyUI-Bar']]
assert str(custom_nodes / '.disabled' / 'ComfyUI-Bar') in caplog.text
@pytest.mark.parametrize('core', ['legacy'], indirect=True)
def test_the_legacy_queue_tells_the_page_that_a_disable_failed_and_the_terminal_why(core, custom_nodes, caplog): # noqa: F811
for folder in ('ComfyUI-Bar', '.disabled/ComfyUI-Bar'):
pack(custom_nodes / folder, **UNKNOWN)
reload(core)
disable = legacy_task('do_disable', core=core, logging=logging, traceback=traceback)
assert [asyncio.run(disable(('the row', 'ComfyUI-Bar', True))), folders(custom_nodes)] == [
"Failed to disable: 'ComfyUI-Bar'", ['.disabled', '.disabled/ComfyUI-Bar', 'ComfyUI-Bar']]
assert str(custom_nodes / '.disabled' / 'ComfyUI-Bar') in caplog.text
def a_version_whose_folder_is_taken(module, path):
pack(path / '.disabled/comfyui-foo@1_0_1', **VERSION)
reload(module)
(path / 'comfyui-foo').mkdir()
@pytest.mark.parametrize('core', ['glob'], indirect=True)
def test_the_v4_queue_tells_the_page_that_an_enable_failed_and_the_terminal_why(core, custom_nodes, monkeypatch, caplog): # noqa: F811
a_version_whose_folder_is_taken(core, custom_nodes)
task = data_models(monkeypatch).QueueTaskItem.model_validate({
'ui_id': 'ui', 'client_id': 'client', 'kind': 'enable', 'params': {'cnr_id': 'comfyui-foo'}})
assert [run_glob_worker(monkeypatch, core, task), folders(custom_nodes)] == [
[('enable', "Failed to enable: 'comfyui-foo'", 'error')], ['.disabled', '.disabled/comfyui-foo@1_0_1', 'comfyui-foo']]
assert str(custom_nodes / 'comfyui-foo') in caplog.text
@pytest.mark.parametrize('core', ['legacy'], indirect=True)
def test_the_legacy_queue_tells_the_page_that_an_enable_failed_and_the_terminal_why(core, custom_nodes, caplog): # noqa: F811
a_version_whose_folder_is_taken(core, custom_nodes)
enable = legacy_task('do_enable', core=core, logging=logging, replaces_cnr_with_nightly=lambda cnr_id: False)
assert [asyncio.run(enable(('the row', 'comfyui-foo'))), folders(custom_nodes)] == [
"Failed to enable: 'comfyui-foo'", ['.disabled', '.disabled/comfyui-foo@1_0_1', 'comfyui-foo']]
assert str(custom_nodes / 'comfyui-foo') in caplog.text
@pytest.mark.parametrize('core', ['legacy'], indirect=True)
def test_cm_cli_install_reports_an_enable_that_failed(core, custom_nodes): # noqa: F811
pack(custom_nodes / '.disabled/ComfyUI-Bar', **UNKNOWN)
manager = reload(core)
(custom_nodes / 'ComfyUI-Bar').mkdir()
out = io.StringIO()
install_node = cm_cli_function('install_node', {
'asyncio': asyncio, 'core': core, 'unified_manager': manager, 'print': lambda *objects, **kwargs: print(*objects, file=out),
'cmd_ctx': SimpleNamespace(channel=core.DEFAULT_CHANNEL, mode='cache', no_deps=False), 'NodeInstallError': NodeInstallError})
with pytest.raises(NodeInstallError):
install_node('ComfyUI-Bar@unknown', cnt_msg='1/1', raise_on_fail=True)
assert ['[ ENABLED ]' in out.getvalue(), folders(custom_nodes)] == [False, ['.disabled', '.disabled/ComfyUI-Bar', 'ComfyUI-Bar']]
+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 / "comfyui_manager" / "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"]}},
}
+175 -2
View File
@@ -41,7 +41,7 @@ def set_lists(monkeypatch):
import_context()
from comfyui_manager.common import cm_global, manager_util
monkeypatch.setattr(manager_util, 'make_pip_cmd', lambda cmd: ['python', '-m', 'pip', *cmd])
monkeypatch.setattr(manager_util, 'get_pip_cmd', lambda force_uv=False: ['python', '-m', 'pip'])
monkeypatch.setattr(manager_util, 'subprocess', SimpleNamespace(
check_output=lambda *args, **kwargs: PIP_LIST, CalledProcessError=subprocess.CalledProcessError))
monkeypatch.setattr(manager_util, 'pip_map', None)
@@ -60,7 +60,7 @@ def load_prestartup(**module_globals):
from comfyui_manager.common import cm_global, manager_util
source = Path(manager_util.__file__).parents[1] / 'prestartup_script.py'
wanted = {'is_installed', 'remap_pip_package', 'execute_lazy_install_script', 'execute_startup_script'}
wanted = {'is_installed', 'execute_lazy_install_script', 'execute_startup_script'}
functions = [node for node in ast.parse(source.read_text(encoding='utf-8')).body
if isinstance(node, ast.FunctionDef) and node.name in wanted]
scope = {'os': os, 're': re, 'manager_util': manager_util, 'cm_global': cm_global, **module_globals}
@@ -387,6 +387,179 @@ def test_requirements_file_lines_are_checked_before_install(set_lists, monkeypat
assert requirements == ['scipy --index-url https://example.invalid/simple', 'pyyaml>=6']
def ansi_open(file, mode='r', *args, encoding=None, **kwargs):
if 'b' not in mode and encoding is None:
encoding = 'cp1252'
return open(file, mode, *args, encoding=encoding, **kwargs)
def ansi_core(monkeypatch, tree, executed):
core = import_reader(tree)
monkeypatch.setattr(core.manager_funcs, 'run_script', lambda cmd, cwd='.': executed.append(cmd) or 0)
monkeypatch.setattr(core.manager_util, 'PIPFixer', lambda *args: SimpleNamespace(fix_broken=lambda: None))
monkeypatch.setattr(core.manager_util, 'use_unified_resolver', False)
for module in (core, core.manager_util):
monkeypatch.setattr(module, 'open', ansi_open, raising=False)
return core
def chardet_names(monkeypatch, encoding):
import chardet
monkeypatch.setattr(chardet, 'detect', lambda data: {'encoding': encoding, 'confidence': 0.06, 'language': None})
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')
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
def test_utf8_requirements_file_with_non_ascii_comments_is_installed_in_a_windows_code_page(
set_lists, monkeypatch, tmp_path, tree):
(tmp_path / 'requirements.txt').write_text('# Łukasz ✨ 中文\nnumpy\nrich # Łukasz\n', encoding='utf-8')
executed = []
core = ansi_core(monkeypatch, tree, executed)
assert core.execute_install_script(None, str(tmp_path), instant_execution=True) is True
assert [cmd[cmd.index('install') + 1:] for cmd in executed] == [['numpy'], ['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'])
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
def test_requirements_file_whose_comment_chardet_misreads_is_installed(
set_lists, monkeypatch, tmp_path, tree, content, named, installed):
(tmp_path / 'requirements.txt').write_bytes(content)
executed = []
core = ansi_core(monkeypatch, tree, executed)
chardet_names(monkeypatch, named)
assert core.execute_install_script(None, str(tmp_path), instant_execution=True) is True
assert [cmd[cmd.index('install') + 1:] for cmd in executed] == [[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'])
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
def test_utf8_requirements_file_with_non_ascii_blanks_is_installed(
set_lists, monkeypatch, tmp_path, tree, text, installed):
(tmp_path / 'requirements.txt').write_text(text, encoding='utf-8')
executed = []
core = ansi_core(monkeypatch, tree, executed)
chardet_names(monkeypatch, 'utf-8')
assert core.execute_install_script(None, str(tmp_path), instant_execution=True) is True
assert [cmd[cmd.index('install') + 1:] for cmd in executed] == [[name] for name in installed]
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
def test_requirement_line_with_a_no_break_space_fails_the_install(set_lists, monkeypatch, tmp_path, tree):
(tmp_path / 'requirements.txt').write_text('numpy\u00a0 # 依存関係\nrich\n', encoding='utf-8')
executed = []
core = ansi_core(monkeypatch, tree, executed)
chardet_names(monkeypatch, 'utf-8')
with pytest.raises(UnicodeDecodeError) as error:
core.execute_install_script(None, str(tmp_path), instant_execution=True)
assert str(error.value) == "'charmap' codec can't decode byte 0x9d in position 12: character maps to <undefined>"
assert executed == []
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
def test_requirement_with_a_non_ascii_url_fragment_fails_the_install(set_lists, monkeypatch, tmp_path, tree):
(tmp_path / 'requirements.txt').write_text('git+https://host/repo#egg=依存\nrich\n', encoding='utf-8')
executed = []
core = ansi_core(monkeypatch, tree, executed)
chardet_names(monkeypatch, 'utf-8')
with pytest.raises(UnicodeDecodeError):
core.execute_install_script(None, str(tmp_path), instant_execution=True)
assert executed == []
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
def test_utf16_requirements_file_with_byte_order_mark_installs_only_its_requirements(
set_lists, monkeypatch, tmp_path, tree):
(tmp_path / 'requirements.txt').write_bytes('# 依赖列表\nrich\n'.encode('utf-16'))
executed = []
core = ansi_core(monkeypatch, tree, executed)
chardet_names(monkeypatch, 'utf-16-le')
assert core.execute_install_script(None, str(tmp_path), instant_execution=True) is True
assert [cmd[cmd.index('install') + 1:] for cmd in executed] == [['rich']]
@pytest.mark.parametrize('named', ['ISO-8859-5', 'MacCyrillic', None],
ids=['chardet-7.7.0', 'chardet-7.1.0', 'no-encoding'])
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
def test_requirements_file_that_is_not_text_fails_the_install(set_lists, monkeypatch, tmp_path, tree, named):
(tmp_path / 'requirements.txt').write_bytes(NOT_TEXT)
executed = []
core = ansi_core(monkeypatch, tree, executed)
chardet_names(monkeypatch, named)
with pytest.raises(UnicodeDecodeError) as error:
core.execute_install_script(None, str(tmp_path), instant_execution=True)
assert str(error.value) == "'charmap' codec can't decode byte 0x81 in position 1: character maps to <undefined>"
assert executed == []
@pytest.mark.parametrize('named', ['cp500', 'cp1140'])
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
def test_requirements_file_that_an_ebcdic_guess_reads_as_ascii_fails_the_install(
set_lists, monkeypatch, tmp_path, tree, named):
(tmp_path / 'requirements.txt').write_bytes(EBCDIC)
executed = []
core = ansi_core(monkeypatch, tree, executed)
chardet_names(monkeypatch, named)
with pytest.raises(UnicodeDecodeError) as error:
core.execute_install_script(None, str(tmp_path), instant_execution=True)
assert str(error.value) == "'charmap' codec can't decode byte 0x81 in position 1: character maps to <undefined>"
assert executed == []
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
def test_requirements_file_with_carriage_return_line_ends_is_installed(set_lists, monkeypatch, tmp_path, tree):
(tmp_path / 'requirements.txt').write_bytes('pandas\r# 依存関係\r'.encode('utf-8'))
executed = []
core = ansi_core(monkeypatch, tree, executed)
chardet_names(monkeypatch, 'utf-8')
assert core.execute_install_script(None, str(tmp_path), instant_execution=True) is True
assert [cmd[cmd.index('install') + 1:] for cmd in executed] == [['pandas']]
@pytest.mark.parametrize('entry_point', ['glob manager', 'legacy manager', 'startup', 'resolver'])
def test_the_other_installers_take_the_requirements_chardet_reads(
set_lists, monkeypatch, tmp_path, entry_point):
(tmp_path / 'requirements.txt').write_bytes(MAC_ROMAN)
executed = []
core = ansi_core(monkeypatch, 'legacy' if entry_point == 'legacy manager' else 'glob', executed)
chardet_names(monkeypatch, 'ISO-8859-5')
if entry_point == 'startup':
startup = load_prestartup(
process_wrap=lambda cmd, cwd=None, **kwargs: executed.append(cmd) or 0,
processed_install=set(), _unified_resolver_succeeded=False)
startup['execute_lazy_install_script'](str(tmp_path), 'python')
elif entry_point == 'resolver':
from comfyui_manager.common import unified_dep_resolver
monkeypatch.setattr(unified_dep_resolver, 'manager_util', core.manager_util)
collected = unified_dep_resolver.UnifiedDepResolver(node_pack_paths=[str(tmp_path)]).collect_requirements()
executed.extend(['install', r.spec] for r in collected.requirements)
else:
monkeypatch.setattr(core.unified_manager, 'processed_install', set())
core.unified_manager.execute_install_script(None, str(tmp_path), instant_execution=True)
assert [cmd[cmd.index('install') + 1:] for cmd in executed] == [['rich']]
# Every base command make_pip_cmd() can produce.
PIP_COMMANDS = [
['python', '-m', 'pip'], ['python', '-s', '-m', 'pip'],
+204
View File
@@ -0,0 +1,204 @@
import os
from types import SimpleNamespace
import pytest
from _install_flags_testutil import import_reader
from test_pip_blacklist_matching import load_prestartup, set_lists # noqa: F401 -- fixture
INDEX = 'https://example.invalid/whl/cu121'
MIRROR = 'https://example.invalid/simple'
REPO = 'git+https://example.invalid/packs/proto'
OVERRIDES = {'opencv-python': 'opencv-contrib-python-headless'}
FORCED = ['--force-reinstall', '--no-deps', '--no-cache-dir']
LINES = {
'demo-pkg': [['demo-pkg']],
'demo-pkg==1.2': [['demo-pkg==1.2']],
'demo-pkg>=1,<2': [['demo-pkg>=1,<2']],
'demo-pkg; python_version < "3.12"': [['demo-pkg; python_version < "3.12"']],
'opencv-python': [['opencv-contrib-python-headless']],
'pygit2>=1.18 # clone_repository(proxy=...) requires 1.18.0+': [['pygit2>=1.18']],
'demo-pkg; python_version < "3.12" # older pythons': [['demo-pkg; python_version < "3.12"']],
'opencv-python # headless on servers': [['opencv-contrib-python-headless']],
f'torch --index-url {INDEX}': [['torch', '--index-url', INDEX]],
f'torch==2.1.1 --index-url {INDEX} # the CUDA build': [['torch==2.1.1', '--index-url', INDEX]],
f'torch --extra-index-url {INDEX} # the CUDA build': [['torch', '--extra-index-url', INDEX]],
f'torch --index-url {MIRROR} --extra-index-url {INDEX}': [['torch', '--index-url', MIRROR, '--extra-index-url', INDEX]],
'# a comment': [],
' ': [],
}
URL_LINES = {
f'{REPO}#subdirectory=sub': [f'{REPO}#subdirectory=sub'],
f'proto-dist @ {REPO}#egg=proto-dist # pinned': [f'proto-dist @ {REPO}#egg=proto-dist'],
}
BLACKLISTED = ['xformers', 'xformers # attention', f'xformers --index-url {INDEX}', f'XFormers>=0.0.30 --extra-index-url {INDEX} # attention']
OPTION_ROWS = {
f'--extra-index-url {INDEX}': f'--extra-index-url {INDEX}',
f'--index-url {INDEX} # the CUDA build': f'--index-url {INDEX}',
'-r other.txt': '-r other.txt',
'-c constraints.txt': '-c constraints.txt',
'-f https://example.invalid/wheels': '-f https://example.invalid/wheels',
'--trusted-host example.invalid': '--trusted-host example.invalid',
'--only-binary :all:': '--only-binary :all:',
' --hash=sha256:4bc89822243270757f4c272934e2521ad4b41f0cdcdce82672eeacf01ca3d5f1': '--hash=sha256:4bc89822243270757f4c272934e2521ad4b41f0cdcdce82672eeacf01ca3d5f1',
}
EDITABLE_ROWS = {
'-e ./local': ['-e', './local'],
'-e .': ['-e', '.'],
'--editable ./local': ['-e', './local'],
'--editable=./local': ['-e', './local'],
'-e./local': ['-e', './local'],
f'-e {REPO}#egg=proto-dist # pinned': ['-e', f'{REPO}#egg=proto-dist'],
'-e requests': ['-e', 'requests'],
f'-e ./local --extra-index-url {INDEX}': ['-e', './local', '--extra-index-url', INDEX],
}
CORE_PATHS = [f'{tree} {path}' for tree in ('glob', 'legacy') for path in ('install', 'fix', 'install from a git url')]
@pytest.fixture(params=[*CORE_PATHS, 'start'])
def installs(request, set_lists, monkeypatch, tmp_path, capsys): # noqa: F811
from comfyui_manager.common import cm_global
set_lists(blacklist={'xformers'})
monkeypatch.setattr(cm_global, 'pip_overrides', OVERRIDES)
executed = []
def ran(action, line):
(tmp_path / 'requirements.txt').write_text(line + '\n', encoding='utf-8')
capsys.readouterr()
ok = action()
said = [said for said in capsys.readouterr().out.splitlines() if 'one row at a time' in said]
return SimpleNamespace(commands=executed, ok=bool(ok), said=said)
def start(line):
startup = load_prestartup(processed_install=set(), comfy_path=str(tmp_path), _unified_resolver_succeeded=False,
process_wrap=lambda cmd, cwd=None, **kwargs: executed.append(cmd[4:]) or int(cmd[4].startswith('-') and cmd[4] != '-e'))
return ran(lambda: startup['execute_lazy_install_script'](str(tmp_path), 'python') or True, line)
if request.param == 'start':
start.path = 'start'
return start
tree, path = request.param.split(' ', 1)
core = import_reader(tree)
monkeypatch.setattr(core.manager_util, 'PIPFixer', lambda *args: SimpleNamespace(fix_broken=lambda: None))
monkeypatch.setattr(core.manager_util, 'use_unified_resolver', False)
monkeypatch.setattr(core.manager_funcs, 'run_script', lambda cmd, cwd='.': executed.append(cmd[4:]) or int(cmd[4].startswith('-') and cmd[4] != '-e'))
monkeypatch.setattr(core.unified_manager, 'processed_install', set())
monkeypatch.setattr(core.unified_manager, 'unknown_active_nodes', {'pack': ('https://example.invalid/pack', str(tmp_path))})
action = {'install': lambda: core.unified_manager.execute_install_script(None, str(tmp_path), instant_execution=True),
'fix': lambda: core.unified_manager.unified_fix('pack', 'unknown', instant_execution=True).result,
'install from a git url': lambda: core.execute_install_script(None, str(tmp_path), instant_execution=True)}[path]
def installs(line):
return ran(action, line)
installs.path = path
return installs
@pytest.mark.parametrize('line', LINES)
def test_each_path_gives_the_installer_the_line_as_pip_reads_it(installs, line):
assert installs(line).commands == LINES[line]
@pytest.mark.parametrize('line', URL_LINES)
def test_a_url_keeps_its_fragment_on_each_path(installs, line):
forced = [[*URL_LINES[line], *FORCED]] if installs.path == 'fix' else []
assert installs(line).commands == [URL_LINES[line], *forced]
@pytest.mark.parametrize('line', BLACKLISTED)
def test_a_blacklisted_package_is_skipped_however_its_line_is_written(installs, line):
assert installs(line).commands == []
@pytest.mark.parametrize('row', OPTION_ROWS)
def test_a_row_with_only_an_option_is_left_out_with_one_line_and_the_rows_after_it_are_installed(installs, row):
run = installs(f'{row}\ndemo-pkg')
assert (run.commands, run.ok) == ([['demo-pkg']], True)
assert len(run.said) == 1 and f"'{OPTION_ROWS[row]}'" in run.said[0]
@pytest.mark.parametrize('row', EDITABLE_ROWS)
def test_an_editable_row_goes_to_the_installer_as_its_option_and_its_target(installs, row):
run = installs(f'{row}\ndemo-pkg')
assert (run.commands, run.ok, run.said) == ([EDITABLE_ROWS[row], ['demo-pkg']], True, [])
@pytest.mark.parametrize('line', ['# a comment', ' ', 'demo-pkg'])
def test_a_row_that_is_not_an_option_row_is_left_out_or_installed_without_that_line(installs, line):
assert installs(line).said == []
@pytest.mark.parametrize('installer, row, installed, said', [
(['python', '-m', 'pip'], f'-e {REPO}#egg=proto-dist # pinned', ['-e', f'{REPO}#egg=proto-dist'], False),
(['python', '-m', 'uv', 'pip'], f'-e {REPO}#egg=proto-dist # pinned', [f'{REPO}#egg=proto-dist'], True),
(['uv', 'pip'], f'--editable={REPO}#egg=proto-dist --extra-index-url {INDEX}', [f'{REPO}#egg=proto-dist', '--extra-index-url', INDEX], True),
(['uv', 'pip'], f'-e {REPO}#egg=proto-dist --no-build-isolation', [f'-e {REPO}#egg=proto-dist --no-build-isolation'], False),
(['python', '-m', 'pip'], '-e ./local', ['-e', './local'], False),
(['uv', 'pip'], '-e ./local', ['-e', './local'], False),
(['uv', 'pip'], f'{REPO}#egg=proto-dist', [f'{REPO}#egg=proto-dist'], False),
])
def test_uv_installs_an_editable_git_requirement_without_e_and_pip_installs_it_as_it_is_written(installer, row, installed, said, monkeypatch, capsys):
manager_util = import_reader('glob').manager_util
monkeypatch.setattr(manager_util, 'get_pip_cmd', lambda force_uv=False: installer)
assert manager_util.pip_install_args(row, {}) == installed
assert ('without -e' in capsys.readouterr().out) == said
SAME_ROW_OF_TWO_NODEPACKS = {
'-e .': ['pack-a', 'pack-b'],
'-e ./local': ['pack-a', 'pack-b'],
'./wheels/demo_pkg-1.0-py3-none-any.whl': ['pack-a', 'pack-b'],
'-e .[extra]': ['pack-a', 'pack-b'],
'./wheels/demo_pkg-1.0-py3-none-any.whl; python_version >= "3"': ['pack-a', 'pack-b'],
'demo-pkg': ['pack-a'],
'demo-pkg[extra]>=1; python_version >= "3"': ['pack-a'],
f'-e {REPO}#egg=proto-dist': ['pack-a'],
}
@pytest.mark.parametrize('path', ['install', 'fix'])
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
@pytest.mark.parametrize('row', SAME_ROW_OF_TWO_NODEPACKS)
def test_a_row_that_names_a_path_of_the_nodepack_is_installed_for_each_nodepack_of_a_session(row, tree, path, set_lists, monkeypatch, tmp_path): # noqa: F811
core = import_reader(tree)
packs = [tmp_path / name for name in ('pack-a', 'pack-b')]
for pack in packs:
(pack / 'local').mkdir(parents=True)
(pack / 'wheels').mkdir()
(pack / 'wheels' / 'demo_pkg-1.0-py3-none-any.whl').write_bytes(b'')
(pack / 'requirements.txt').write_text(row + '\n', encoding='utf-8')
installed_in = []
monkeypatch.setattr(core.manager_util, 'PIPFixer', lambda *args: SimpleNamespace(fix_broken=lambda: None))
monkeypatch.setattr(core.manager_util, 'use_unified_resolver', False)
monkeypatch.setattr(core.manager_funcs, 'run_script', lambda cmd, cwd='.': installed_in.append(os.path.basename(cwd)) or 0)
monkeypatch.setattr(core.unified_manager, 'processed_install', set())
monkeypatch.setattr(core.unified_manager, 'unknown_active_nodes', {pack.name: (f'https://example.invalid/{pack.name}', str(pack)) for pack in packs})
fixed = set()
action = {'install': lambda pack: core.unified_manager.execute_install_script(None, str(pack), instant_execution=True),
'fix': lambda pack: core.unified_manager.unified_fix(pack.name, 'unknown', instant_execution=True, fixed=fixed)}[path]
for pack in packs:
action(pack)
assert installed_in == SAME_ROW_OF_TWO_NODEPACKS[row]
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
def test_the_manager_requirements_of_comfyui_are_read_by_the_same_rule(tree, set_lists, monkeypatch, tmp_path): # noqa: F811
core = import_reader(tree)
executed = []
monkeypatch.setattr(core.subprocess, 'run', lambda cmd, **kwargs: executed.append(cmd[4:]))
monkeypatch.delenv('COMFYUI_MANAGER_SKIP_MANAGER_REQUIREMENTS', raising=False)
(tmp_path / 'manager_requirements.txt').write_text(
f'# the Manager\n--extra-index-url {INDEX}\ncomfyui_manager==4.0.3 # pinned by ComfyUI\n\n{REPO}#subdirectory=manager\n', encoding='utf-8')
core.install_manager_requirements(str(tmp_path))
assert executed == [['comfyui_manager==4.0.3'], [f'{REPO}#subdirectory=manager']]
+59 -5
View File
@@ -23,6 +23,16 @@ PIPS = {
'torch==2.5.1': '',
}
GIT_URL = 'git+https://example.com/vcs-pack.git@0123abcd#egg=vcs-pack'
EDITABLE = {
'alpha==1.0': '',
'# Editable install with no version control (local-pack==0.1)': '',
'-e /work/local-pack': '',
'-e file:///work/uv-pack': '',
f'-e {GIT_URL}': '',
}
UV = ['uv', 'pip']
@pytest.fixture
def restore(monkeypatch, capsys):
@@ -30,11 +40,11 @@ def restore(monkeypatch, capsys):
import_context()
from comfyui_manager.common import manager_util
def run(options, failing=()):
def run(options, failing=(), pips=PIPS, installer=('python', '-m', 'pip')):
commands = []
def check_call(cmd, **_):
commands.append(cmd[3:])
commands.append(cmd[len(installer):])
if any(name in arg for arg in cmd for name in failing):
raise subprocess.CalledProcessError(1, cmd)
return 0
@@ -43,13 +53,13 @@ def restore(monkeypatch, capsys):
# pip's output, as the real check_output returns it: never an exit status.
return check_call(cmd) or b'Successfully installed\n'
monkeypatch.setattr(manager_util, 'make_pip_cmd', lambda cmd: ['python', '-m', 'pip', *cmd])
monkeypatch.setattr(manager_util, 'get_pip_cmd', lambda force_uv=False: list(installer))
monkeypatch.setattr(manager_util, 'subprocess', SimpleNamespace(
check_call=check_call, check_output=check_output,
CalledProcessError=subprocess.CalledProcessError))
run.not_installed = manager_util.restore_pip_snapshot(PIPS, options)
report = capsys.readouterr().out.strip().splitlines()[-1]
run.not_installed = manager_util.restore_pip_snapshot(pips, options)
*run.said, report = capsys.readouterr().out.strip().splitlines()
return commands, report
return run
@@ -118,3 +128,47 @@ def test_group_without_its_option_is_left_alone(restore):
assert commands == []
assert report == 'Installation failed for pip packages: []'
@pytest.mark.parametrize('option, installed', [
('--pip-non-url', [['install', 'alpha==1.0']]),
('--pip-local-url', [['install', '--no-deps', '-e', '/work/local-pack'],
['install', '--no-deps', '-e', 'file:///work/uv-pack']]),
('--pip-non-local-url', [['install', '--no-deps', '-e', GIT_URL]]),
])
def test_editable_install_is_restored_as_editable_with_the_option_of_its_url(restore, option, installed):
commands, report = restore([option], pips=EDITABLE)
assert commands == installed
assert restore.said == []
assert report == 'Installation failed for pip packages: []'
def test_uv_restores_an_editable_install_of_a_git_url_without_e(restore):
commands, report = restore(['--pip-non-local-url', '--pip-local-url'], pips=EDITABLE, installer=UV)
assert commands == [['install', '--no-deps', GIT_URL],
['install', '--no-deps', '-e', '/work/local-pack'],
['install', '--no-deps', '-e', 'file:///work/uv-pack']]
assert restore.said == [f"[ComfyUI-Manager] uv installs an editable from a local folder only: '{GIT_URL}' is installed without -e"]
assert report == 'Installation failed for pip packages: []'
def test_uv_says_nothing_of_an_editable_install_that_its_option_leaves_alone(restore):
commands, _ = restore(['--pip-local-url'], pips=EDITABLE, installer=UV)
assert commands == [['install', '--no-deps', '-e', '/work/local-pack'], ['install', '--no-deps', '-e', 'file:///work/uv-pack']]
assert restore.said == []
def test_an_editable_git_url_that_uv_does_not_install_is_reported_as_the_snapshot_has_it(restore):
_, report = restore(['--pip-non-local-url'], failing=['vcs-pack'], pips=EDITABLE, installer=UV)
assert report == f"Installation failed for pip packages: ['-e {GIT_URL}']"
def test_editable_install_whose_path_is_gone_is_reported(restore):
_, report = restore(['--pip-non-url', '--pip-local-url'], failing=['/work/local-pack'], pips=EDITABLE)
assert report == "Installation failed for pip packages: ['-e /work/local-pack']"
assert restore.not_installed == ['-e /work/local-pack']
+38 -1
View File
@@ -137,6 +137,7 @@ def test_enabled_version_of_the_registry_is_disabled_before_the_clone_of_a_snaps
registered = {'id': 'fixture', 'repository': REPO_URL, 'publisher': {'name': 'owner'}}
manager.repo_cnr_map[REPO_URL] = manager.cnr_map['fixture'] = registered
manager.get_custom_nodes.return_value = {'fixture': {'repository': REPO_URL}} if in_node_list else {}
(tmp_path / 'fixture').mkdir()
manager.active_nodes['fixture'] = ('1.0.0', str(tmp_path / 'fixture'))
assert summary(cnr_custom_nodes=None, **pinned(REPO_URL)) == ['[ INSTALLED ] fixture']
@@ -171,6 +172,7 @@ def test_pack_saved_at_a_version_of_the_registry_with_its_clone_disabled_is_rest
def test_clone_that_is_enabled_is_left_to_the_install_of_the_version_that_the_snapshot_names(manager, summary, steps, tmp_path): # noqa: F811
manager.repo_cnr_map[REPO_URL] = manager.cnr_map['fixture'] = {'id': 'fixture', 'repository': REPO_URL, 'publisher': {'name': 'owner'}}
(tmp_path / 'fixture').mkdir()
manager.active_nodes['fixture'] = ('nightly', str(tmp_path / 'fixture'))
assert summary(cnr_custom_nodes={'fixture': '1.0.0'}, git_custom_nodes={REPO_URL: {'hash': COMMIT, 'disabled': True}}) == ['[ INSTALLED ] fixture@1.0.0']
@@ -180,10 +182,11 @@ def test_clone_that_is_enabled_is_left_to_the_install_of_the_version_that_the_sn
@pytest.mark.parametrize('failure, lines, done', [
('the registry does not have it', [f'[ CHECKOUT ] fixture@{COMMIT}', '[ FAILED ] fixture@1.0.0'], []),
('its download fails', [f'[ CHECKOUT ] fixture@{COMMIT}', '[ FAILED ] fixture@1.0.0'], ['disable fixture', 'enable fixture@nightly']),
('its download fails after another version was enabled', [f'[ CHECKOUT ] fixture@{COMMIT}', '[ FAILED ] fixture@1.0.0'], ['disable fixture', 'enable fixture@cnr', 'enable fixture@nightly']),
('its download fails after another version was enabled', [f'[ CHECKOUT ] fixture@{COMMIT}', '[ FAILED ] fixture@1.0.0'], ['enable fixture@cnr', 'disable fixture', 'enable fixture@nightly']),
], ids=['the registry does not have it', 'its download fails', 'its download fails after another version was enabled'])
def test_clone_of_the_snapshot_is_restored_when_the_version_that_the_snapshot_names_cannot_be_installed(core, manager, summary, steps, monkeypatch, tmp_path, failure, lines, done): # noqa: F811
manager.repo_cnr_map[REPO_URL] = manager.cnr_map['fixture'] = {'id': 'fixture', 'repository': REPO_URL, 'publisher': {'name': 'owner'}}
(tmp_path / 'fixture').mkdir()
manager.active_nodes['fixture'] = ('nightly', str(tmp_path / 'fixture'))
def disable(name, is_unknown):
@@ -194,6 +197,7 @@ def test_clone_of_the_snapshot_is_restored_when_the_version_that_the_snapshot_na
def enable(name, version):
steps.append('enable %s@%s' % (name, version))
if version == 'cnr':
disable(name, False)
manager.active_nodes[name] = ('2.0.0', manager.cnr_inactive_nodes[name].pop('2.0.0'))
return core.ManagedResult('enable').with_target(str(tmp_path / name))
@@ -494,6 +498,39 @@ def test_checkout_that_fails_is_reported_as_failed(manager, summary, tmp_path, i
assert summary(**pinned(REPO_URL)) == [f'[ FAILED ] fixture@{COMMIT}']
@pytest.mark.parametrize('installed, lines, done', [
(registry_git_pack, ['[ DISABLED ] fixture'], ['disable fixture']),
(unknown_git_pack, ['[ DISABLED ] fixture'], ['disable fixture']),
(disabled_registry_git_pack, [], []),
(disabled_unknown_git_pack, [], []),
(lambda unified_manager, path: in_registry(unified_manager), [], []),
(lambda unified_manager, path: None, [], []),
], ids=['registry_git_pack', 'unknown_git_pack', 'disabled_registry_git_pack', 'disabled_unknown_git_pack',
'registry_git_pack_that_is_not_installed', 'unknown_git_pack_that_is_not_installed'])
def test_git_pack_that_the_snapshot_lists_as_disabled_is_restored_as_disabled(manager, summary, steps, tmp_path, installed, lines, done): # noqa: F811
"""Enabled, it is disabled; disabled, it is left as it is; not installed, it is not cloned."""
installed(manager, tmp_path)
assert summary(git_custom_nodes={REPO_URL: {'hash': COMMIT, 'disabled': True}}) == lines
assert steps == done
@pytest.mark.parametrize('read_first', ['nodes', 'more_nodes'], ids=['enabled_clone_read_first', 'disabled_clone_read_first'])
def test_snapshot_lists_a_repository_as_enabled_when_one_of_its_two_clones_is_enabled(core, manager, monkeypatch, tmp_path, read_first): # noqa: F811
"""Both clones have the URL that names the entry: the enabled one is what a restore brings back."""
enabled, disabled = tmp_path / 'nodes/fixture', tmp_path / 'more_nodes/.disabled/fixture'
repository(enabled)
subprocess.run(['git', 'checkout', '-q', repository(disabled)[0]], cwd=disabled, check=True)
for clone in (enabled, disabled):
subprocess.run(['git', 'remote', 'add', 'origin', REPO_URL], cwd=clone, check=True)
folders = sorted(['nodes', 'more_nodes'], key=lambda name: name != read_first)
monkeypatch.setattr(core, 'get_custom_nodes_paths', lambda: [str(tmp_path / name) for name in folders])
saved = asyncio.run(core.get_current_snapshot(custom_nodes_only=True))['git_custom_nodes']
assert saved == {REPO_URL: {'hash': head(enabled), 'disabled': False}}
def test_pack_that_fails_at_two_steps_is_listed_once(core, manager, summary, answer, tmp_path): # noqa: F811
manager.active_nodes['fixture'] = ('1.0.0', str(tmp_path / 'fixture'))
in_registry(manager)
-1
View File
@@ -24,7 +24,6 @@ OPEN_GRID = """async (rows) => {
keywords: '',
filter: '',
grid: new ManagerGrid(document.getElementById('grid')),
hasAlternatives() { return false; },
setDisabled() {},
%(show_loading)s,
%(hide_loading)s,
+50
View File
@@ -0,0 +1,50 @@
import asyncio
import io
import os
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
import pytest
import typer
from rich.console import Console
from typing_extensions import Annotated
from legacy_html_testutil import ROOT, load_functions
from test_snapshot_restore_pins import core, manager # noqa: F401
@pytest.fixture
def show(manager, tmp_path): # noqa: F811
manager.get_custom_nodes = AsyncMock(return_value={
'listed-pack': {'title': 'Listed Pack', 'author': 'someone', 'files': ['https://github.com/someone/listed-pack']},
})
manager.cnr_map['registry-pack'] = {'id': 'registry-pack', 'name': 'Registry Pack', 'publisher': {'name': 'someone'},
'latest_version': {'version': '1.0.0'}}
manager.active_nodes['registry-pack'] = ('1.0.0', str(tmp_path / 'registry-pack'))
manager.unknown_active_nodes['listed-pack'] = ('https://github.com/someone/listed-pack', str(tmp_path / 'listed-pack'))
manager.unknown_active_nodes['git-pack'] = ('https://example.invalid/git-pack', str(tmp_path / 'git-pack'))
manager.unknown_inactive_nodes['old-git-pack'] = ('https://example.invalid/old-git-pack', str(tmp_path / '.disabled/old-git-pack'))
def show(name, kind):
out = io.StringIO()
load_functions(ROOT / 'cm_cli/__main__.py', {name, 'show_list'}, {
'app': SimpleNamespace(command=lambda *args, **kwargs: lambda function: function),
'typer': typer, 'Annotated': Annotated, 'asyncio': asyncio, 'os': os,
'print': Console(file=out, width=1000, color_system=None).print, 'cmd_ctx': Mock(), 'unified_manager': manager,
})[name](kind, None, None, None)
return [' '.join(line.split()) for line in out.getvalue().splitlines()]
return show
def test_simple_show_lists_every_installed_nodepack(show):
assert show('simple_show', 'enabled') == ['Registry Pack@1.0.0', 'Listed Pack@unknown', 'git-pack@unknown']
assert show('simple_show', 'disabled') == ['old-git-pack@unknown']
assert show('simple_show', 'installed') == ['Registry Pack@1.0.0', 'Listed Pack@unknown', 'git-pack@unknown', 'old-git-pack@unknown']
def test_show_names_a_git_nodepack_that_the_lists_do_not_know_by_its_id(show):
assert show('show', 'installed')[2:] == [
'[ ENABLED ] git-pack git-pack (author: N/A ) [UNKNOWN]',
'[ DISABLED ] old-git-pack old-git-pack (author: N/A ) [UNKNOWN]',
]
+51
View File
@@ -0,0 +1,51 @@
import asyncio
import json
from types import SimpleNamespace
from unittest.mock import Mock
import rich
import typer
from rich import print
from rich.console import Console
from typing_extensions import Annotated
from legacy_html_testutil import PACKAGE, ROOT, load_functions
COMFYUI = 'f0123456789abcdef0123456789abcdef0123456'
PACK = 'abcdef0123456789abcdef0123456789abcdef01'
URL = 'https://gitlab.com/group/' + 'subgroup/' * 30 + 'pack'
SNAPSHOT = {
'comfyui': COMFYUI,
'git_custom_nodes': {URL: {'hash': PACK, 'disabled': False}},
'cnr_custom_nodes': {'registry-pack': '1.0.0'},
'file_custom_nodes': [{'filename': 'single.py', 'disabled': False}],
'pips': {'torch': '2.0.0'},
}
def command(name):
async def get_current_snapshot():
return SNAPSHOT
core = load_functions(PACKAGE / 'legacy/manager_core.py', {'print'}, {'rich': rich, 'Console': Console})
return load_functions(ROOT / 'cm_cli/__main__.py', {name, 'show_snapshot'}, {
'app': SimpleNamespace(command=lambda *args, **kwargs: lambda function: function),
'typer': typer, 'Annotated': Annotated, 'asyncio': asyncio, 'json': json, 'print': print,
'core': SimpleNamespace(get_current_snapshot=get_current_snapshot, print=core['print']), 'cmd_ctx': Mock(),
})[name]
def test_show_snapshot_prints_the_current_snapshot(capsys):
command('show')('snapshot', None, None, None)
assert json.loads(capsys.readouterr().out) == SNAPSHOT
def test_simple_show_snapshot_prints_a_line_per_nodepack(capsys):
command('simple_show')('snapshot', None, None, None)
assert capsys.readouterr().out.splitlines() == [
f'[{COMFYUI}] comfyui',
f'[{PACK}] {URL}',
'[ N/A ] single.py',
]
File diff suppressed because it is too large Load Diff
+231
View File
@@ -0,0 +1,231 @@
import ast
import asyncio
import json
import logging
import os
import runpy
import threading
import traceback
from collections import deque
from pathlib import Path
from types import SimpleNamespace
import pytest
from aiohttp import web
from legacy_html_testutil import PACKAGE
from test_grid_highlight_escaping import browser # noqa: F401 -- fixture
SERVER = PACKAGE / "legacy/manager_server.py"
MESSAGES = runpy.run_path(str(PACKAGE / "common/security_messages.py"))
NAMES = {"is_allowed_security_level", "TaskBatch", "finalize_temp_queue_batch", "queue_batch", "_queue_start",
"_fix_custom_node", "task_worker"}
JS = Path(os.environ.get("MANAGER_JS_DIR") or (PACKAGE / "js"))
EXTENSION = "http://manager.test/extensions/comfyui-manager/"
CONTENT_TYPES = {".js": "text/javascript", ".css": "text/css"}
LEVELS = ["strong", "normal", "normal-", "weak"]
LISTENERS = ["loopback", "personal_cloud", "public"]
PACK = {"id": "comfyui-ollama", "title": "comfyui-ollama", "author": "Stav Sapir", "description": "Ollama nodes",
"repository": "https://github.com/stavsap/comfyui-ollama", "reference": "https://github.com/stavsap/comfyui-ollama",
"files": ["https://github.com/stavsap/comfyui-ollama"], "install_type": "git-clone", "version": "nightly",
"active_version": "nightly", "cnr_latest": "2.1.0", "state": "enabled", "import-fail": True,
"update-state": "false", "stars": 879, "last_update": "2025-10-23 17:02:46"}
def fix_allowed(security_level, listener):
return security_level == "weak" and listener != "public" or security_level == "normal-" and listener == "loopback"
ALLOWED = [(level, listener) for level in LEVELS for listener in LISTENERS if fix_allowed(level, listener)]
REFUSED = [(level, listener) for level in LEVELS for listener in LISTENERS if not fix_allowed(level, listener)]
def legacy_server(security_level, listener, history):
fixed, sent = [], []
async def reload(mode):
pass
core = SimpleNamespace(
get_config=lambda: {"security_level": security_level,
"network_mode": "personal_cloud" if listener == "personal_cloud" else "public"},
unified_manager=SimpleNamespace(reload=reload, unified_fix=lambda name, version: fixed.append(name) or SimpleNamespace(result=True)))
update_check_done = threading.Event()
update_check_done.set()
namespace = {
"web": web, "json": json, "os": os, "asyncio": asyncio, "threading": threading, "logging": logging,
"traceback": traceback, "routes": SimpleNamespace(post=lambda path: lambda handler: handler),
"manager_security": SimpleNamespace(reject_non_json_post=lambda request: None), "core": core,
"is_local_mode": listener == "loopback", "context": SimpleNamespace(manager_batch_history_path=str(history)),
"PromptServer": SimpleNamespace(instance=SimpleNamespace(send_sync=lambda name, data: sent.append(data))),
"temp_queue_batch": [], "task_batch_queue": deque(), "tasks_in_progress": set(),
"task_worker_lock": threading.Lock(), "task_worker_thread": None, "update_check_done": update_check_done,
**{name: text for name, text in MESSAGES.items() if name.startswith("SECURITY_MESSAGE_")},
}
nodes = [node for node in ast.parse(SERVER.read_text(encoding="utf-8")).body if getattr(node, "name", None) in NAMES]
assert {node.name for node in nodes} == NAMES
exec(compile(ast.Module(nodes, []), str(SERVER), "exec"), namespace)
async def body(batch):
return batch
def send(batch):
sent.clear()
answer = asyncio.run(namespace["queue_batch"](SimpleNamespace(json=lambda: body(batch))))
namespace["task_worker_thread"].join(5)
return json.loads(answer.text), list(sent)
return send, fixed
@pytest.mark.parametrize("security_level, listener", ALLOWED)
def test_try_fix_runs_at_a_level_that_allows_it(tmp_path, security_level, listener):
send, fixed = legacy_server(security_level, listener, tmp_path)
answer, sent = send({"batch_id": "the batch", "fix": [dict(PACK, ui_id="the row")]})
assert answer == {"failed": []}
assert fixed == ["comfyui-ollama"]
assert [event["nodepack_result"] for event in sent if event["status"] == "batch-done"] == [{"the row": "success"}]
@pytest.mark.parametrize("security_level, listener", REFUSED)
def test_try_fix_at_a_level_that_does_not_allow_it_is_refused_and_not_queued(tmp_path, caplog, security_level, listener):
send, fixed = legacy_server(security_level, listener, tmp_path)
answer, sent = send({"batch_id": "the batch", "fix": [dict(PACK, ui_id="the row")]})
assert answer == {"failed": ["comfyui-ollama"]}
assert fixed == []
assert [event["status"] for event in sent] == ["all-done"]
assert caplog.messages == [MESSAGES["SECURITY_MESSAGE_HIGH_P"]]
SCRIPTS = {
"api.js": """
class Api extends EventTarget {
getNodeDefs = async () => ({});
async fetchApi(path, options) {
const route = path.split('?')[0];
if(route == '/v2/manager/queue/batch') {
const {answer, events} = await window.legacyServer(JSON.parse(options.body));
setTimeout(() => {
events.forEach((detail) => this.dispatchEvent(new CustomEvent('cm-queue-status', {detail})));
window.reported = true;
});
return {status: 200, json: async () => answer};
}
const answer = window.server[route];
if(answer === undefined) return {status: 404, statusText: 'Not Found'};
return {status: 200, json: async () => structuredClone(answer)};
}
}
export const api = new Api();
""",
"app.js": """
const dialog = document.createElement('div');
dialog.className = 'comfy-modal';
export const app = {
graph: {_nodes: [], extra: {}},
registerExtension() {},
ui: {
settings: {settingsValues: {'Comfy.ColorPalette': 'dark'}},
dialog: {element: dialog, show(html) { dialog.innerHTML = html; document.body.append(dialog); }},
},
};
""",
"ui.js": """
export function $el(tag, props, children) {
if(Array.isArray(props)) [props, children] = [{}, props];
const names = tag.split('.');
const element = document.createElement(names.shift());
element.classList.add(...names);
const {parent, style, ...rest} = props ?? {};
Object.assign(element.style, style);
Object.assign(element, rest);
element.append(...(children ?? []));
parent?.append(element);
return element;
}
export class ComfyDialog {}
""",
}
@pytest.fixture
def page(browser): # noqa: F811
page = browser.new_page(viewport={"width": 1600, "height": 900})
def route(request):
url = request.request.url
name = url.rsplit("/", 1)[-1]
if url == "http://manager.test/":
request.fulfill(body="<body></body>", content_type="text/html")
elif url.startswith(EXTENSION) and (JS / name).is_file():
request.fulfill(path=str(JS / name), content_type=CONTENT_TYPES.get((JS / name).suffix, "text/plain"))
elif url == "http://manager.test/scripts/" + name and name in SCRIPTS:
request.fulfill(body=SCRIPTS[name], content_type="text/javascript")
else:
request.abort()
page.route("**/*", route)
page.errors = []
page.on("pageerror", lambda error: page.errors.append(str(error)))
page.goto("http://manager.test/")
yield page
page.close()
def try_fix(page, send):
def serve(batch):
# Playwright's sync API keeps an event loop running in this thread, where asyncio.run cannot start another.
replies = []
server = threading.Thread(target=lambda: replies.append(send(batch)))
server.start()
server.join()
answer, events = replies[0]
return {"answer": answer, "events": events}
page.expose_function("legacyServer", serve)
page.evaluate("""async ({module, server}) => {
window.server = server;
const {app} = await import('/scripts/app.js');
const {setManagerInstance} = await import(new URL('common.js', module).href);
setManagerInstance({datasrc_combo: {value: 'cache'}});
const {CustomNodesManager} = await import(module);
window.manager = CustomNodesManager.instance = new CustomNodesManager(app, null);
manager.show(CustomNodesManager.ShowMode.NORMAL);
}""", {"module": EXTENSION + "custom-nodes-manager.js",
"server": {"/v2/customnode/getlist": {"channel": "default", "node_packs": {"comfyui-ollama": PACK}},
"/v2/customnode/getmappings": {}}})
page.wait_for_function("document.querySelector('.cn-manager-status').textContent == '1 custom nodes'")
page.get_by_role("button", name="Try fix", exact=True).click()
page.wait_for_function("window.reported && manager.install_context === undefined")
return page.evaluate("""() => ({
box: (document.querySelector('.comfy-modal')?.textContent ?? '').split(/\\s+/).filter(Boolean).join(' '),
action: [...document.querySelectorAll('.cn-manager-grid .tg-body button, .cn-manager-grid .tg-body font')]
.map((element) => element.textContent),
restart: document.querySelector('.cn-manager-restart').checkVisibility(),
})""")
def test_try_fix_at_the_default_level_is_refused_without_asking_for_a_restart(page, tmp_path):
send, fixed = legacy_server("normal", "loopback", tmp_path)
shown = try_fix(page, send)
assert shown == {"box": "[Installation Errors] [FAIL] comfyui-ollama",
"action": ["IMPORT FAILED ↗", "Try fix", "Switch Ver", "Disable", "Uninstall"], "restart": False}
assert fixed == []
assert page.errors == []
def test_try_fix_at_a_level_that_allows_it_runs_and_asks_for_a_restart(page, tmp_path):
send, fixed = legacy_server("normal-", "loopback", tmp_path)
shown = try_fix(page, send)
assert shown == {"box": "", "action": ["IMPORT FAILED ↗", "Restart Required"], "restart": True}
assert fixed == ["comfyui-ollama"]
assert page.errors == []
+237
View File
@@ -0,0 +1,237 @@
import os
from pathlib import Path
import pytest
from test_grid_highlight_escaping import browser # noqa: F401 -- fixture
JS = Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "comfyui_manager" / "js"))
EXTENSION = "http://manager.test/extensions/comfyui-manager-legacy/"
BATCH = "/v2/manager/queue/batch"
REBOOT = "/v2/manager/reboot"
ANSWERS = {
"/v2/manager/version": "V4.4.3",
"/v2/manager/share_option": "all",
"/v2/manager/db_mode": "cache",
"/v2/manager/channel_url_list": {"list": ["default::https://example.invalid/channel"], "selected": "default"},
"/v2/manager/policy/update": "stable-comfyui",
"/v2/manager/notice": "",
BATCH: {"failed": []},
}
SCRIPTS = {
"api.js": """
class Api extends EventTarget {
async fetchApi(path, options) {
const answer = window.answers[path.split('?')[0]] ?? '';
window.requested.push({path, method: options?.method ?? 'GET', body: options?.body ? JSON.parse(options.body) : null});
return {status: 200, json: async () => answer, text: async () => typeof answer == 'string' ? answer : JSON.stringify(answer)};
}
}
export const api = new Api();
""",
"app.js": """
import { ComfyDialog } from './ui.js';
export const app = {
ui: {dialog: new ComfyDialog()},
registerExtension(extension) { window.extension = extension; },
};
""",
"ui.js": """
const style = document.createElement('style');
style.textContent = '.comfy-modal { display: none; position: fixed; z-index: 100; top: 50%; left: 50%; transform: translate(-50%, -50%); padding: 20px; background: #353535; color: #ddd; }';
document.head.append(style);
export function $el(tag, propsOrChildren, children) {
const [name, ...classes] = tag.split('.');
const element = document.createElement(name);
element.classList.add(...classes);
if(typeof propsOrChildren == 'string') {
propsOrChildren = {textContent: propsOrChildren};
}
else if(Array.isArray(propsOrChildren) || propsOrChildren instanceof Element) {
children = propsOrChildren;
propsOrChildren = {};
}
const {parent, $: callback, dataset, style, ...props} = propsOrChildren ?? {};
Object.assign(element.style, style);
Object.assign(element.dataset, dataset);
Object.assign(element, props);
if(children) {
element.append(...[children].flat());
}
parent?.append(element);
callback?.(element);
return element;
}
export class ComfyDialog {
constructor() {
this.element = $el('div.comfy-modal', {parent: document.body}, [
$el('div.comfy-modal-content', [
$el('p', {$: (p) => (this.textElement = p)}),
$el('button', {type: 'button', textContent: 'Close', onclick: () => this.close()}),
]),
]);
}
close() {
this.element.style.display = 'none';
}
show(html) {
this.textElement.innerHTML = html;
this.element.style.display = 'flex';
}
}
""",
}
UPDATED = {"msg": "success", "title": "ComfyUI-TechsToolz", "url": "https://verify.invalid/packs/ComfyUI-TechsToolz"}
UP_TO_DATE = {"msg": "skip", "title": "ComfyUI-CyberUtils", "url": "https://verify.invalid/packs/ComfyUI-CyberUtils"}
FAILED = {"msg": "An error occurred while updating 'comfyui-manager'.", "title": "ComfyUI-Manager",
"url": "https://github.com/Comfy-Org/ComfyUI-Manager"}
@pytest.fixture
def page(browser): # noqa: F811
page = browser.new_page()
def route(request):
url = request.request.url
name = url.rsplit("/", 1)[-1]
if url == "http://manager.test/":
request.fulfill(body="<body></body>", content_type="text/html")
elif url.startswith(EXTENSION) and (JS / name).is_file():
request.fulfill(path=str(JS / name), content_type="text/css" if name.endswith(".css") else "text/javascript")
elif url == "http://manager.test/scripts/" + name and name in SCRIPTS:
request.fulfill(body=SCRIPTS[name], content_type="text/javascript")
else:
request.abort()
page.route("**/*", route)
page.add_init_script("""
window.errors = [];
addEventListener('error', (event) => errors.push(String(event.error ?? event.message)));
addEventListener('unhandledrejection', (event) => errors.push(String(event.reason)));
""")
page.goto("http://manager.test/")
yield page
page.close()
def open_menu(page, electron=False):
page.evaluate("""async ({module, answers, electron}) => {
if(electron) {
window.electronAPI = {restartApp() {}};
}
window.requested = [];
window.answers = answers;
await import(module);
window.extension.commands.find((command) => command.id == 'Comfy.Manager.Menu.ToggleVisibility').function();
}""", {"module": EXTENSION + "comfyui-manager.js", "answers": ANSWERS, "electron": electron})
def sent_batch(page):
batches = page.evaluate("requested.filter((request) => request.path == '%s').map((request) => request.body)" % BATCH)
assert len(batches) == 1
return batches[0]
def report(page, detail):
page.evaluate("""async (detail) => {
const { api } = await import('/scripts/api.js');
api.dispatchEvent(new CustomEvent('cm-queue-status', {detail}));
}""", detail)
def finish(page, nodepack_result):
batch_id = sent_batch(page).get("batch_id")
total = len(nodepack_result)
for done, target in enumerate(nodepack_result, 1):
report(page, {"status": "in_progress", "target": target, "batch_id": batch_id, "ui_target": "main",
"total_count": total, "done_count": done})
report(page, {"status": "batch-done", "nodepack_result": nodepack_result, "model_result": {},
"total_count": total, "done_count": total, "batch_id": batch_id, "remaining_batch_count": 1})
report(page, {"status": "all-done"})
def result(page):
page.wait_for_function("errors.length > 0 || [...document.querySelectorAll('.comfy-modal')].some((box) => box.checkVisibility())",
timeout=5000)
assert page.evaluate("errors") == []
box = page.locator(".comfy-modal:visible .comfy-modal-content > p")
return box.inner_text(), box.locator("li").all_inner_texts()
def test_update_all_shows_what_was_updated_and_restarts_comfyui(page):
open_menu(page)
page.get_by_role("button", name="Update All", exact=True).click()
batch = sent_batch(page)
assert batch["update_comfyui"] is True
assert batch["update_all"] == "cache"
assert batch.get("batch_id")
finish(page, {"comfyui-techstoolz": UPDATED, "comfyui-cyberutils": UP_TO_DATE, "comfyui-manager": FAILED,
"comfyui": "success-stable-v0.3.60"})
text, items = result(page)
assert "To apply the updates, you need to RESTART ComfyUI." in text
assert "ComfyUI has been updated to v0.3.60." in text
assert "The following custom nodes have been updated:" in text
assert "The update for the following custom nodes has failed:" in text
assert items == ["ComfyUI-TechsToolz", "ComfyUI-Manager"]
page.get_by_role("button", name="RESTART", exact=True).click()
page.get_by_text("Are you sure you'd like to reboot the server?").wait_for()
page.get_by_role("button", name="Confirm").click()
page.wait_for_function("requested.some((request) => request.method == 'POST' && request.path == '%s')" % REBOOT)
def test_update_all_says_when_everything_is_up_to_date(page):
open_menu(page)
page.get_by_role("button", name="Update All", exact=True).click()
finish(page, {"comfyui-cyberutils": UP_TO_DATE, "comfyui": "skip"})
text, _ = result(page)
assert text == "You are already up to date."
assert page.get_by_role("button", name="RESTART", exact=True).count() == 0
@pytest.mark.parametrize("nodepack_result, shown, items, restart", [
({"comfyui-techstoolz": UPDATED, "comfyui-cyberutils": UP_TO_DATE},
"To apply the updates, you need to RESTART ComfyUI.", ["ComfyUI-TechsToolz"], True),
({"comfyui-cyberutils": UP_TO_DATE}, "You are already up to date.", [], False),
({"comfyui-manager": FAILED}, "The update for the following custom nodes has failed:", ["ComfyUI-Manager"], False),
], ids=["updated", "up-to-date", "failed"])
def test_the_electron_button_shows_a_result_without_comfyui(page, nodepack_result, shown, items, restart):
open_menu(page, electron=True)
page.get_by_role("button", name="Update All Custom Nodes", exact=True).click()
batch = sent_batch(page)
assert "update_comfyui" not in batch
assert batch["update_all"] == "cache"
finish(page, nodepack_result)
text, listed = result(page)
assert shown in text
assert "ComfyUI has been updated" not in text
assert "ComfyUI is already up to date" not in text
assert "Failed to update ComfyUI" not in text
assert listed == items
assert page.get_by_role("button", name="RESTART", exact=True).count() == (1 if restart else 0)
def test_the_end_of_another_batch_is_not_shown(page):
open_menu(page)
page.get_by_role("button", name="Update All", exact=True).click()
report(page, {"status": "batch-done", "batch_id": "another-batch", "model_result": {}, "remaining_batch_count": 2,
"nodepack_result": {"foreign-pack": {"msg": "success", "title": "Foreign Pack"}}})
assert page.locator(".comfy-modal:visible").count() == 0
finish(page, {"comfyui-techstoolz": UPDATED, "comfyui": "skip"})
text, items = result(page)
assert "ComfyUI is already up to date." in text
assert items == ["ComfyUI-TechsToolz"]
+18 -19
View File
@@ -394,10 +394,10 @@ def recorder(result=lambda cmd: 0):
def test_fix_installs_a_url_requirement_by_force_and_other_requirements_as_ever(installer):
assert manager_util().fix_cmd(f'git+{REPO}') == [*installer.base, 'install', f'git+{REPO}', *installer.forced]
assert manager_util().fix_cmd(f'Proto-Dist @ git+{REPO}') == [*installer.base, 'install', f'Proto-Dist @ git+{REPO}', *installer.forced]
assert manager_util().fix_cmd(WHEEL) == [*installer.base, 'install', WHEEL, *installer.forced]
assert manager_util().fix_cmd('numpy>=1.20') == [*installer.base, 'install', 'numpy>=1.20']
assert manager_util().fix_cmd([f'git+{REPO}']) == [*installer.base, 'install', f'git+{REPO}', *installer.forced]
assert manager_util().fix_cmd([f'Proto-Dist @ git+{REPO}']) == [*installer.base, 'install', f'Proto-Dist @ git+{REPO}', *installer.forced]
assert manager_util().fix_cmd([WHEEL]) == [*installer.base, 'install', WHEEL, *installer.forced]
assert manager_util().fix_cmd(['numpy>=1.20']) == [*installer.base, 'install', 'numpy>=1.20']
@pytest.mark.parametrize('cmd,forced', [
@@ -416,7 +416,7 @@ def test_forced_install_is_known_by_its_url_requirement_and_its_option(cmd, forc
def test_fix_installs_the_requirement_as_an_install_does_and_then_the_package_by_force(installer, capsys):
"""The first resolves what the package needs and changes nothing when it cannot; the second puts a clean copy there."""
run, commands = recorder()
forced = manager_util().fix_cmd(f'git+{REPO}')
forced = manager_util().fix_cmd([f'git+{REPO}'])
assert manager_util().reinstall(forced, run) == 0
assert commands == [[*installer.base, 'install', f'git+{REPO}'], forced]
@@ -425,13 +425,13 @@ def test_fix_installs_the_requirement_as_an_install_does_and_then_the_package_by
def test_fix_forces_also_what_the_install_has_just_put_there(installer):
"""uv takes a commit it has built before from its cache while the remote answers: only the forced install is a clean copy."""
forced = manager_util().fix_cmd(f'git+{REPO}')
forced = manager_util().fix_cmd([f'git+{REPO}'])
run, commands = recorder(lambda cmd: installer.install('Proto-Dist', installer.records['no revision'].replace(COMMIT, LATER)) or 0)
assert manager_util().reinstall(forced, run) == 0
assert commands == [[*installer.base, 'install', f'git+{REPO}'], forced]
other = manager_util().fix_cmd(OTHER)
other = manager_util().fix_cmd([OTHER])
run, commands = recorder(lambda cmd: installer.install('Other', installer.records['no revision'].replace(REPO, OTHER[4:])) or 0)
assert manager_util().reinstall(other, run) == 0
@@ -440,7 +440,7 @@ def test_fix_forces_also_what_the_install_has_just_put_there(installer):
def test_fix_keeps_what_is_installed_when_the_requirement_cannot_be_installed(installer):
"""What the new commit needs may not be there to install: the forced install would leave the package without it."""
forced = manager_util().fix_cmd(f'git+{REPO}')
forced = manager_util().fix_cmd([f'git+{REPO}'])
run, commands = recorder(lambda cmd: 1)
assert manager_util().reinstall(forced, run) == 1
@@ -452,7 +452,7 @@ def test_fix_goes_on_when_only_the_forced_install_fails(installer, capsys):
Nothing is installed in place of the clean copy: that it failed does not say that the remote is out of reach.
"""
forced = manager_util().fix_cmd(f'git+{REPO}')
forced = manager_util().fix_cmd([f'git+{REPO}'])
run, commands = recorder(lambda cmd: int(cmd == forced))
assert manager_util().reinstall(forced, run) == 0
@@ -472,7 +472,7 @@ def test_fix_uses_the_cache_of_uv_only_when_the_remote_is_out_of_reach(installer
installer.install('Proto-Dist', installer.records[record])
asked = []
monkeypatch.setattr(manager_util(), 'is_git_remote_usable', lambda url: asked.append(url) or remote == 'answers')
forced = manager_util().fix_cmd(requirement)
forced = manager_util().fix_cmd([requirement])
plain = [*installer.base, 'install', requirement]
cached = [*installer.base, 'install', from_the_cache, '--force-reinstall', '--no-deps', '--offline']
run, commands = recorder(lambda cmd: int(cmd == plain))
@@ -488,7 +488,7 @@ def test_fix_uses_the_cache_of_uv_only_when_the_remote_is_out_of_reach(installer
def test_fix_does_not_take_a_package_of_another_name_from_the_cache(installer, monkeypatch):
"""A requirement that gives a name is met by a distribution of that name only."""
monkeypatch.setattr(manager_util(), 'is_git_remote_usable', lambda url: False)
forced = manager_util().fix_cmd(f'Other-Name @ git+{REPO}')
forced = manager_util().fix_cmd([f'Other-Name @ git+{REPO}'])
run, commands = recorder(lambda cmd: 1)
assert manager_util().reinstall(forced, run) == 1
@@ -498,7 +498,7 @@ def test_fix_does_not_take_a_package_of_another_name_from_the_cache(installer, m
def test_fix_with_a_run_that_raises_as_in_cm_cli(installer, monkeypatch):
"""What `run` raised for the install is raised again, unless the cache made the fix good."""
monkeypatch.setattr(manager_util(), 'is_git_remote_usable', lambda url: False)
forced = manager_util().fix_cmd(f'git+{REPO}')
forced = manager_util().fix_cmd([f'git+{REPO}'])
plain = [*installer.base, 'install', f'git+{REPO}']
commands = []
@@ -530,7 +530,7 @@ def startup_runs(tmp_path, lines):
def test_startup_runs_the_forced_install_a_fix_reserved(installer, tmp_path):
"""The plain command for the same requirement is skipped: the package is installed."""
forced = manager_util().fix_cmd(f'git+{REPO}')
forced = manager_util().fix_cmd([f'git+{REPO}'])
plain = [*installer.base, 'install', f'git+{REPO}']
assert startup_runs(tmp_path, [[str(tmp_path), *plain], [str(tmp_path), *forced]]) == [plain, forced]
@@ -546,7 +546,7 @@ def test_command_the_user_forced_is_run_as_it_is(installer, tmp_path):
def test_blacklisted_requirement_is_not_installed_by_a_reserved_forced_install(installer, set_lists, tmp_path): # noqa: F811
set_lists(blacklist={f'git+{REPO}'})
assert startup_runs(tmp_path, [[str(tmp_path), *manager_util().fix_cmd(f'git+{REPO}')]]) == []
assert startup_runs(tmp_path, [[str(tmp_path), *manager_util().fix_cmd([f'git+{REPO}'])]]) == []
CM_CLI = Path(__file__).resolve().parent.parent / 'cm_cli' / '__main__.py'
@@ -645,18 +645,17 @@ def test_cm_cli_says_each_command_before_the_command_writes(packs, monkeypatch):
monkeypatch.setattr(core.subprocess, 'check_call', lambda cmd, **options: said.append(''.join(out)))
monkeypatch.setattr(sys, 'stdout', SimpleNamespace(write=written.append, flush=lambda: (out.extend(written), written.clear())))
assert core.try_install_script(None, '.', manager_util().fix_cmd(f'git+{REPO}'), instant_execution=True) is True
assert core.try_install_script(None, '.', manager_util().fix_cmd([f'git+{REPO}']), instant_execution=True) is True
assert [text.count('EXECUTE =>') for text in said] == [1, 2]
def test_startup_skips_what_an_install_reserved_for_a_url_with_a_fragment(packs, monkeypatch, tmp_path):
"""The legacy core reserves a requirement line whole, and the other one cuts it at '#'."""
core = packs(pack=f'git+{REPO}#egg=proto-dist\n{OTHER}#egg=other\n')
monkeypatch.setattr(core, 'get_config', lambda: {'always_lazy_install': True})
assert core.unified_manager.execute_install_script(None, str(tmp_path / 'pack')) is True
assert [cmd[-1] for cmd in startup_runs(tmp_path, reserved(tmp_path))] == [OTHER + ('#egg=other' if packs.tree == 'legacy' else '')]
assert [cmd[-1] for cmd in startup_runs(tmp_path, reserved(tmp_path))] == [f'{OTHER}#egg=other']
@pytest.fixture(scope='module')
@@ -693,7 +692,7 @@ def test_fix_with_the_real_pip(set_lists, monkeypatch, pip_environment): # noqa
monkeypatch.setattr(manager_util(), 'pip_map', None)
def fix():
code = manager_util().reinstall(manager_util().fix_cmd(f'git+{REMOTE}'), lambda cmd: subprocess.run(cmd, capture_output=True, env=env).returncode)
code = manager_util().reinstall(manager_util().fix_cmd([f'git+{REMOTE}']), lambda cmd: subprocess.run(cmd, capture_output=True, env=env).returncode)
manager_util().clear_pip_cache()
return code, manager_util().installed_from(f'git+{REMOTE}')['vcs_info']['commit_id']
@@ -757,7 +756,7 @@ def test_fix_with_the_real_uv(set_lists, monkeypatch, uv_environment): # noqa:
def fix(clean_copy=True):
"""`clean_copy=False`: the install without the cache fails, as with a temporary folder that is full."""
code = manager_util().reinstall(manager_util().fix_cmd(f'git+{REMOTE}'), lambda cmd: (
code = manager_util().reinstall(manager_util().fix_cmd([f'git+{REMOTE}']), lambda cmd: (
subprocess.run(cmd, capture_output=True).returncode if clean_copy or '--no-cache' not in cmd else 1))
manager_util().clear_pip_cache()
return code, manager_util().installed_from(f'git+{REMOTE}')['vcs_info']['commit_id']
+19
View File
@@ -407,6 +407,25 @@ 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')
downloader = import_reader('glob').manager_downloader
monkeypatch.setattr(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(core, monkeypatch, tmp_path): # noqa: F811
custom_nodes = tmp_path / 'custom_nodes'
(old_version(custom_nodes, 'fixture') / '.tracking').unlink()
+80
View File
@@ -0,0 +1,80 @@
import asyncio
import io
import json
import os
from types import SimpleNamespace
from typing import Optional
import pytest
import rich.console
import typer
from typing_extensions import Annotated
from test_invalid_installation import (BAR_URL, FOO_URL, NODE_LIST, cm_cli_function, core, custom_nodes, # noqa: F401 -- fixtures
listing, pack, reload)
@pytest.fixture
def cm_cli(core, custom_nodes, monkeypatch, tmp_path): # noqa: F811
async def get_data_by_mode(mode, filename, channel_url=None):
if filename == 'extension-node-map.json':
return {FOO_URL: [['FooNode'], {}], BAR_URL: [['BarNode'], {}]}
return {'custom_nodes': [dict(item) for item in NODE_LIST]}
async def auto_save_snapshot():
pass
monkeypatch.setattr(core, 'get_data_by_mode', get_data_by_mode)
out = io.StringIO()
namespace = {
'asyncio': asyncio, 'os': os, 'json': json, 'core': core, 'unified_manager': core.unified_manager, 'typer': typer,
'Annotated': Annotated, 'Optional': Optional, 'app': SimpleNamespace(command=lambda *args, **kwargs: lambda f: f),
'print': rich.console.Console(file=out, width=1000, color_system=None).print,
'auto_save_snapshot': auto_save_snapshot, 'comfy_path': str(tmp_path),
'context': SimpleNamespace(manager_files_path=str(tmp_path)),
'manager_util': SimpleNamespace(get_installed_packages=dict,
PIPFixer=lambda *args: SimpleNamespace(fix_broken=lambda: None)),
'cmd_ctx': SimpleNamespace(set_user_directory=lambda path: None, set_channel_mode=lambda channel, mode: reload(core),
set_no_deps=lambda no_deps: None, mode='cache', channel='default'),
'out': out}
for name in ('enable_node', '_finalize_resolve', 'deps_in_workflow', 'install_deps'):
cm_cli_function(name, namespace)
return namespace
@pytest.mark.parametrize('core', ['legacy'], indirect=True)
@pytest.mark.parametrize('folder, kwargs, foo, bar', [
('comfyui-foo', {'project_name': 'comfyui-foo', 'tracking': True}, 'installed', 'not-installed'),
('.disabled/comfyui-foo@1_0_1', {'project_name': 'comfyui-foo', 'tracking': True}, 'disabled', 'not-installed'),
('.disabled/comfyui-foo@nightly', {'git_url': FOO_URL}, 'disabled', 'not-installed'),
('ComfyUI-Bar', {'git_url': BAR_URL}, 'not-installed', 'installed'),
('.disabled/ComfyUI-Bar', {'git_url': BAR_URL}, 'not-installed', 'disabled'),
('ComfyUI-Bar.disabled', {'git_url': BAR_URL}, 'not-installed', 'disabled'),
], ids=['registry', 'registry-disabled', 'nightly-disabled', 'git', 'git-disabled', 'git-disabled-old-style'])
def test_deps_in_workflow_writes_the_state_of_each_nodepack(core, custom_nodes, cm_cli, tmp_path, folder, kwargs, foo, bar): # noqa: F811
pack(custom_nodes / folder, **kwargs)
workflow = tmp_path / 'workflow.json'
workflow.write_text(json.dumps({'nodes': [{'id': 1, 'type': 'FooNode'}, {'id': 2, 'type': 'BarNode'}]}))
cm_cli['deps_in_workflow'](workflow=str(workflow), output=str(tmp_path / 'deps.json'), channel=None, mode=None,
user_directory=None)
assert json.loads((tmp_path / 'deps.json').read_text()) == {
'custom_nodes': {FOO_URL: {'state': foo, 'hash': '-'}, BAR_URL: {'state': bar, 'hash': '-'}}, 'unknown_nodes': []}
@pytest.mark.parametrize('core', ['legacy'], indirect=True)
@pytest.mark.parametrize('folder, kwargs, url, enabled', [
('.disabled/comfyui-foo@1_0_1', {'project_name': 'comfyui-foo', 'tracking': True}, FOO_URL, 'comfyui-foo'),
('.disabled/ComfyUI-Bar', {'git_url': BAR_URL}, BAR_URL, 'ComfyUI-Bar'),
('ComfyUI-Bar.disabled', {'git_url': BAR_URL}, BAR_URL, 'ComfyUI-Bar'),
], ids=['registry', 'git', 'git-old-style'])
def test_install_deps_enables_a_disabled_nodepack(core, custom_nodes, cm_cli, tmp_path, folder, kwargs, url, enabled): # noqa: F811
pack(custom_nodes / folder, **kwargs)
deps = tmp_path / 'deps.json'
deps.write_text(json.dumps({'custom_nodes': {url: {'state': 'disabled', 'hash': '-'}}, 'unknown_nodes': []}))
cm_cli['install_deps'](deps=str(deps), channel=None, mode=None, user_directory=None, uv_compile=False)
assert listing(custom_nodes) == [enabled]
assert cm_cli['out'].getvalue().splitlines()[-1] == 'Dependency installation and activation complete.'
+214
View File
@@ -0,0 +1,214 @@
import os
from pathlib import Path
import pytest
from test_grid_highlight_escaping import browser # noqa: F401 -- fixture
JS = Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "comfyui_manager" / "js"))
EXTENSION = "http://manager.test/extensions/comfyui-manager/"
CONTENT_TYPES = {".js": "text/javascript", ".css": "text/css"}
REPOSITORY = "https://github.com/silveroxides/ComfyUI_SigmoidOffsetScheduler"
TITLE = "ComfyUI Sigmoid Offset Scheduler"
NODE = "SigmoidOffsetScheduler"
SPELLINGS = ["ComfyUI_SigmoidOffsetScheduler", "comfyui_sigmoidoffsetscheduler"]
SPELLING_IDS = ["registry case", "lowercase, saved earlier"]
SCRIPTS = {
"api.js": """
export const api = {
addEventListener() {},
getNodeDefs: async () => ({}),
getSystemStats: async () => ({system: {comfyui_version: '0.3.60'}}),
async fetchApi(path) {
const answer = window.server[path.split('?')[0]];
if(answer === undefined) return {status: 404, statusText: 'Not Found'};
return {status: 200, json: async () => structuredClone(answer)};
}
};
""",
"app.js": """
const dialog = document.createElement('div');
dialog.className = 'comfy-modal';
export const app = {
graph: {_nodes: [], extra: {}},
extensions: [],
registerExtension(extension) { this.extensions.push(extension); },
ui: {
settings: {settingsValues: {'Comfy.ColorPalette': 'dark'}},
dialog: {element: dialog, show(html) { dialog.innerHTML = html; document.body.append(dialog); }},
},
};
""",
"ui.js": """
export function $el(tag, props, children) {
if(Array.isArray(props)) [props, children] = [{}, props];
const names = tag.split('.');
const element = document.createElement(names.shift());
element.classList.add(...names);
const {parent, style, ...rest} = props ?? {};
Object.assign(element.style, style);
Object.assign(element, rest);
element.append(...(children ?? []));
parent?.append(element);
return element;
}
export class ComfyDialog {}
""",
}
def pack(key, title, state, repository):
return {"id": key, "title": title, "author": "author", "description": "nodes", "repository": repository,
"reference": repository, "files": [repository], "install_type": "cnr", "version": "1.1.1",
"cnr_latest": "1.1.1", "state": state, "stars": 10, "last_update": "2025-01-01 00:00:00"}
def node_packs(state):
return {
"ComfyUI_SigmoidOffsetScheduler": pack("ComfyUI_SigmoidOffsetScheduler", TITLE, state, REPOSITORY),
"comfyui-other-pack": pack("comfyui-other-pack", "Other Pack", "not-installed",
"https://github.com/someone/comfyui-other-pack"),
}
@pytest.fixture
def page(browser): # noqa: F811
page = browser.new_page(viewport={"width": 1600, "height": 900})
def route(request):
url = request.request.url
name = url.rsplit("/", 1)[-1]
if url == "http://manager.test/":
request.fulfill(body="<body></body>", content_type="text/html")
elif url.startswith(EXTENSION) and (JS / name).is_file():
request.fulfill(path=str(JS / name), content_type=CONTENT_TYPES.get((JS / name).suffix, "text/plain"))
elif url == "http://manager.test/scripts/" + name and name in SCRIPTS:
request.fulfill(body=SCRIPTS[name], content_type="text/javascript")
else:
request.abort()
page.route("**/*", route)
page.errors = []
page.on("pageerror", lambda error: page.errors.append(str(error)))
page.goto("http://manager.test/")
yield page
page.close()
def open_list(page, mode, packs, nodes, registered, mapped=True):
server = {
"/v2/customnode/getlist": {"channel": "default", "node_packs": packs},
"/v2/customnode/getmappings": {REPOSITORY: [[NODE], {"title_aux": TITLE}]} if mapped else {},
}
page.evaluate("""async ({module, mode, server, nodes, registered}) => {
window.server = server;
window.LiteGraph = {registered_node_types: Object.fromEntries(registered.map(type => [type, {type}]))};
const {app} = await import('/scripts/app.js');
app.graph._nodes = nodes;
const {setManagerInstance} = await import(new URL('common.js', module).href);
setManagerInstance({datasrc_combo: {value: 'cache'}});
const {CustomNodesManager} = await import(module);
window.manager = new CustomNodesManager(app, null);
manager.show(CustomNodesManager.ShowMode[mode]);
}""", {"module": EXTENSION + "custom-nodes-manager.js", "mode": mode, "server": server, "nodes": nodes,
"registered": registered})
page.wait_for_function("/^[\\d,]+ custom nodes$/.test(document.querySelector('.cn-manager-status').textContent)")
return page.evaluate("""() => ({
rows: [...document.querySelectorAll('.cn-manager-grid .tg-body .cn-pack-name')].map(cell => cell.innerText.trim()),
status: document.querySelector('.cn-manager-status').textContent,
message: document.querySelector('.comfy-modal')?.innerText ?? '',
})""")
def workflow_node(cnr_id):
return {"type": NODE, "properties": {"cnr_id": cnr_id, "ver": "1.1.1"}}
@pytest.mark.parametrize("cnr_id", SPELLINGS, ids=SPELLING_IDS)
def test_in_workflow_lists_the_installed_nodepack_of_a_node(page, cnr_id):
shown = open_list(page, "IN_WORKFLOW", node_packs("enabled"), [workflow_node(cnr_id)], [NODE])
assert shown == {"rows": [TITLE], "status": "1 custom nodes", "message": ""}
assert page.errors == []
def test_in_workflow_lists_nothing_for_a_node_whose_id_is_a_number(page):
shown = open_list(page, "IN_WORKFLOW", node_packs("enabled"), [workflow_node(123)], [NODE])
assert shown == {"rows": [], "status": "0 custom nodes", "message": ""}
assert page.errors == []
@pytest.mark.parametrize("mapped", [True, False], ids=["node in the node map", "node not in the node map"])
@pytest.mark.parametrize("cnr_id", SPELLINGS, ids=SPELLING_IDS)
def test_missing_lists_the_nodepack_of_an_unknown_node_without_saying_it_is_not_in_the_registry(page, cnr_id, mapped):
shown = open_list(page, "MISSING", node_packs("not-installed"), [workflow_node(cnr_id)], [], mapped)
assert shown == {"rows": [TITLE], "status": "1 custom nodes", "message": ""}
assert page.errors == []
@pytest.mark.parametrize("cnr_id", ["comfyui-nowhere", 123], ids=["text", "number"])
def test_missing_says_which_id_of_the_workflow_no_nodepack_has(page, cnr_id):
node = {"type": "NowhereNode", "properties": {"cnr_id": cnr_id, "ver": "1.0.0"}}
shown = open_list(page, "MISSING", node_packs("not-installed"), [node], [])
assert shown["rows"] == []
assert "Failed to find the following ComfyRegistry list." in shown["message"]
assert str(cnr_id) in shown["message"]
assert page.errors == []
def with_core_lookalike(packs, state):
packs["Comfy-Core"] = pack("Comfy-Core", "Core Lookalike", state, "https://github.com/someone/Comfy-Core")
return packs
def test_missing_does_not_offer_a_nodepack_named_as_the_core_for_a_built_in_node(page):
node = {"type": "NewBuiltInNode", "properties": {"cnr_id": "comfy-core", "ver": "0.3.60"}}
shown = open_list(page, "MISSING", with_core_lookalike(node_packs("not-installed"), "not-installed"), [node], [])
assert shown["rows"] == []
assert "comfy-core" in shown["message"]
assert page.errors == []
def test_in_workflow_does_not_list_a_nodepack_named_as_the_core_for_a_built_in_node(page):
node = {"type": "KSampler", "properties": {"cnr_id": "comfy-core", "ver": "0.3.60"}}
shown = open_list(page, "IN_WORKFLOW", with_core_lookalike(node_packs("enabled"), "enabled"), [node], ["KSampler"])
assert shown == {"rows": [], "status": "0 custom nodes", "message": ""}
assert page.errors == []
def new_node_properties(page, folder, cnr_id):
installed = {folder: {"ver": "1.1.1", "cnr_id": cnr_id, "aux_id": None, "enabled": True}}
return page.evaluate("""async ({module, server, python_module}) => {
window.server = server;
const {app} = await import('/scripts/app.js');
await import(module);
const extension = app.extensions.find(extension => extension.nodeCreated);
await extension.init();
class Node {}
Node.nodeData = {python_module};
const node = new Node();
extension.nodeCreated(node);
return node.properties;
}""", {"module": EXTENSION + "workflow-metadata.js", "server": {"/v2/customnode/installed": installed},
"python_module": "custom_nodes." + folder})
def test_a_new_node_takes_the_id_of_its_nodepack_as_the_installed_list_spells_it(page):
properties = new_node_properties(page, "ComfyUI_SigmoidOffsetScheduler", "ComfyUI_SigmoidOffsetScheduler")
assert properties == {"cnr_id": "ComfyUI_SigmoidOffsetScheduler", "ver": "1.1.1"}
@pytest.mark.parametrize("cnr_id", ["comfy-core", "Comfy-Core"])
def test_a_new_node_of_a_nodepack_that_names_itself_as_the_core_takes_no_id(page, cnr_id):
assert new_node_properties(page, "core-lookalike", cnr_id) == {}